Initial commit: Loma PDF Editor with Coolify deploy setup
Browser-only PDF editor (React + Vite + pdf-lib + pdf.js + tesseract.js), plus a multi-stage Dockerfile that builds the SPA and serves it from nginx on port 80 with a /health endpoint for Coolify. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -0,0 +1,11 @@
|
|||||||
|
node_modules
|
||||||
|
dist
|
||||||
|
public/pdfjs
|
||||||
|
.git
|
||||||
|
.impeccable
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
!.env.example
|
||||||
|
*.log
|
||||||
|
doc
|
||||||
|
samples
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
# Logs
|
||||||
|
logs
|
||||||
|
*.log
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
pnpm-debug.log*
|
||||||
|
lerna-debug.log*
|
||||||
|
|
||||||
|
node_modules
|
||||||
|
dist
|
||||||
|
dist-ssr
|
||||||
|
*.local
|
||||||
|
|
||||||
|
# Editor directories and files
|
||||||
|
.vscode/*
|
||||||
|
!.vscode/extensions.json
|
||||||
|
.idea
|
||||||
|
.DS_Store
|
||||||
|
*.suo
|
||||||
|
*.ntvs*
|
||||||
|
*.njsproj
|
||||||
|
*.sln
|
||||||
|
*.sw?
|
||||||
|
public/pdfjs
|
||||||
|
|
||||||
|
# Local tool output
|
||||||
|
.impeccable
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
!.env.example
|
||||||
|
|
||||||
|
# Internal infra notes (repo is public)
|
||||||
|
doc/gitea-coolify-deploy-guide.md
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
FROM node:22-bookworm-slim AS build
|
||||||
|
WORKDIR /app
|
||||||
|
COPY package.json package-lock.json ./
|
||||||
|
RUN npm ci
|
||||||
|
COPY . .
|
||||||
|
# prebuild copies pdf.js cmaps/fonts into public/pdfjs, then tsc + vite build -> dist/
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
FROM nginx:1.27-alpine
|
||||||
|
RUN apk add --no-cache curl
|
||||||
|
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||||
|
COPY --from=build /app/dist /usr/share/nginx/html
|
||||||
|
EXPOSE 80
|
||||||
|
HEALTHCHECK --interval=30s --timeout=5s --retries=3 CMD curl -fsS -o /dev/null http://127.0.0.1/health || exit 1
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
# Product
|
||||||
|
|
||||||
|
<!-- impeccable:product-schema 1 -->
|
||||||
|
|
||||||
|
## Platform
|
||||||
|
|
||||||
|
web
|
||||||
|
|
||||||
|
## Users
|
||||||
|
|
||||||
|
Thai office workers and SME staff. They receive PDFs (quotations, contracts, forms, reports) and need to sign them, fill in forms, fix a few words, or merge/split pages, then send the file back. They do this between other work, without buying Adobe Acrobat. Some open PDFs on a phone after receiving them by LINE or email.
|
||||||
|
|
||||||
|
## Product Purpose
|
||||||
|
|
||||||
|
Loma PDF Editor lets people do Acrobat-style PDF work (edit existing text and images, comment, sign, fill and create forms, manage pages, redact, OCR, convert) entirely in the browser. Success: a user opens a PDF, finishes the job, and downloads a correct file without help, an account, or a payment.
|
||||||
|
|
||||||
|
## Positioning
|
||||||
|
|
||||||
|
Free with no sign-up: no account, no watermark on output, no usage quota. Files are processed only in the browser and are never uploaded (confirmed: the product stays browser-only, no server storage).
|
||||||
|
|
||||||
|
## Operating Context
|
||||||
|
|
||||||
|
- Inputs: PDFs (often Thai + English text), images for "images → PDF".
|
||||||
|
- Output: a downloaded file named `<name>-edited.pdf`, plus Word/Excel/PNG/JPG/TXT conversions.
|
||||||
|
- Signatures and stamps are stored in the user's browser (localStorage) only.
|
||||||
|
- OCR downloads language data from the tesseract CDN on first use; the PDF itself is not sent anywhere.
|
||||||
|
|
||||||
|
## Capabilities and Constraints
|
||||||
|
|
||||||
|
- Browser-only (React + Vite, pdf.js, pdf-lib, tesseract.js). No backend; file size is bounded by browser memory. Large files multiply in memory through undo history.
|
||||||
|
- Redaction rasterises affected pages on save (irreversible); "Flatten forms" makes fields non-editable (irreversible).
|
||||||
|
- Edited text is always written in Sarabun, not the original font.
|
||||||
|
- Not supported: password-protected PDFs, Word/Excel/PowerPoint → PDF (needs a server).
|
||||||
|
- UI is bilingual: Thai (primary) and English, switchable (`src/i18n.ts`).
|
||||||
|
|
||||||
|
## Brand Commitments
|
||||||
|
|
||||||
|
- Name: "Loma PDF Editor". Logo source: `public/logo/พรีเซนเทชันแบรนด์ Loma PDF Editor.png` (navy "L" page mark + red PDF tag + pen). Derived assets in `public/logo/`: `loma-icon-*.png` (rounded app icon: favicon, apple-touch, top bar) and `loma-lockup.png` (horizontal lockup, background knocked out — use on white/light surfaces only).
|
||||||
|
- Voice: plain, native Thai (not translated), short instructions.
|
||||||
|
- Sarabun is the document font for Thai text written into PDFs.
|
||||||
|
- Promise shown on the start screen: files are not uploaded anywhere.
|
||||||
|
- Colour palette follows the sister product Lomalotto (`D:\Project 4tech\Lomalotto`): brand blue `#1164C2`, navy gradient header (`#0b2b7c → #1164C2 → #081d63`), page background `#eef3f8`, slate neutrals. Requested by the owner on 2026-11-19.
|
||||||
|
|
||||||
|
## Evidence on Hand
|
||||||
|
|
||||||
|
- `samples/sample.pdf` (generated by `scripts/make-sample.mjs`); its Thai text has spacing artefacts because it is generated without the Thai width fix.
|
||||||
|
- No testimonials, user counts, benchmarks, or press exist. Do not fabricate them.
|
||||||
|
|
||||||
|
## Product Principles
|
||||||
|
|
||||||
|
1. Finishing the job beats feature count: sign, fill, and save must be the shortest paths.
|
||||||
|
2. Never surprise the user with irreversible results; say what becomes permanent before it happens.
|
||||||
|
3. Thai first: Thai text must render, copy, and search correctly, and the UI must read naturally in Thai.
|
||||||
|
4. Private by construction: never introduce a flow that sends file content off the device.
|
||||||
|
5. Works for whoever opens it: keyboard, screen reader, and phone users can complete the core jobs.
|
||||||
|
|
||||||
|
## Accessibility & Inclusion
|
||||||
|
|
||||||
|
Target WCAG 2.2 AA for the app chrome: visible focus, keyboard paths for core jobs (open, edit, sign, fill, save), named controls, 4.5:1 text contrast, touch targets ≥ 44px on mobile. Thai UI text must be large enough for stacked vowels and tone marks.
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
# Loma PDF Editor
|
||||||
|
|
||||||
|
A PDF editor that runs entirely in the browser, aiming at Adobe Acrobat Pro's core features. Files never leave the machine (the only network use is OCR language data from the tesseract CDN).
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install
|
||||||
|
npm run dev # http://localhost:5173
|
||||||
|
npm run build # static site in dist/
|
||||||
|
```
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
| Area | What works |
|
||||||
|
|---|---|
|
||||||
|
| Edit | Edit existing text lines (font colour/background sampled from the page), lift existing images to move/resize/replace/delete, add text/images, whiteout |
|
||||||
|
| Comment | Highlight, pen, rectangle, ellipse, line, arrow, text box, sticky note (real PDF `/Text` annotation), stamps |
|
||||||
|
| Sign | Draw / type / upload signature (white paper made transparent), saved in localStorage |
|
||||||
|
| Forms | Fill existing AcroForm fields (text, checkbox, radio, dropdown), create text fields & checkboxes, optional flatten |
|
||||||
|
| Pages | Drag-reorder thumbnails, rotate, delete, insert blank, merge PDFs, images → pages, extract, split every N (zip), watermark, page numbers |
|
||||||
|
| Redact | Mark areas or search-and-redact; redacted pages are rasterised on save so the text is really gone |
|
||||||
|
| OCR | Thai + English via tesseract.js, adds an invisible searchable text layer |
|
||||||
|
| Convert | PDF → Word, Excel, PNG/JPG (zip), TXT; images → PDF |
|
||||||
|
| Language | Thai / English UI, toggled from the top bar or start screen; defaults to the browser language and is remembered (`src/i18n.ts`) |
|
||||||
|
| Other | Undo/redo, search, zoom, keyboard shortcuts (V/E/T/H/P/N, Ctrl+Z/Y/S/F, Del) |
|
||||||
|
|
||||||
|
## How it works
|
||||||
|
|
||||||
|
- `pdfjs-dist` renders pages and extracts text/image positions; `pdf-lib` writes the output.
|
||||||
|
- Every edit is an overlay item stored in PDF user space (`src/lib/types.ts`) and flattened into the PDF on save (`src/lib/export.ts`); `src/lib/contentEdit.ts` parses the content stream to delete the original text/image operators under edited areas. Page operations rewrite the PDF bytes immediately; items follow pages via stable page ids.
|
||||||
|
- Text is written with Sarabun (Thai + Latin). `src/lib/pdflibThaiFix.ts` patches pdf-lib so GSUB-substituted Thai glyphs get correct widths and ToUnicode entries (without it Thai shows gaps and tone marks vanish on copy).
|
||||||
|
|
||||||
|
## Known limits
|
||||||
|
|
||||||
|
- Editing an existing line or image removes the original operators from the page content stream on save. Content inside Form XObjects is only covered (whiteout), not removed. Glyph positions are estimated from font widths, so a run that shares a text operator with neighbouring text can take that neighbour with it.
|
||||||
|
- Edited text always uses Sarabun, not the original font.
|
||||||
|
- Thai mark positioning uses the font's default glyphs (pdf-lib applies no GPOS).
|
||||||
|
- Word/Excel/PowerPoint → PDF needs a server (e.g. LibreOffice); not included.
|
||||||
|
- Password-protected PDFs are not supported.
|
||||||
|
|
||||||
|
`samples/sample.pdf` (generated by `scripts/make-sample.mjs`) is a test file with Thai text, an image, a table and form fields.
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import js from '@eslint/js'
|
||||||
|
import globals from 'globals'
|
||||||
|
import reactHooks from 'eslint-plugin-react-hooks'
|
||||||
|
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||||
|
import tseslint from 'typescript-eslint'
|
||||||
|
|
||||||
|
export default tseslint.config(
|
||||||
|
{ ignores: ['dist'] },
|
||||||
|
{
|
||||||
|
extends: [js.configs.recommended, ...tseslint.configs.recommended],
|
||||||
|
files: ['**/*.{ts,tsx}'],
|
||||||
|
languageOptions: {
|
||||||
|
ecmaVersion: 2020,
|
||||||
|
globals: globals.browser,
|
||||||
|
},
|
||||||
|
plugins: {
|
||||||
|
'react-hooks': reactHooks,
|
||||||
|
'react-refresh': reactRefresh,
|
||||||
|
},
|
||||||
|
rules: {
|
||||||
|
...reactHooks.configs.recommended.rules,
|
||||||
|
'react-refresh/only-export-components': [
|
||||||
|
'warn',
|
||||||
|
{ allowConstantExport: true },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="th">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>Loma PDF Editor</title>
|
||||||
|
<link rel="icon" type="image/png" sizes="32x32" href="/logo/loma-icon-32.png" />
|
||||||
|
<link rel="icon" type="image/png" sizes="192x192" href="/logo/loma-icon-192.png" />
|
||||||
|
<link rel="apple-touch-icon" sizes="180x180" href="/logo/loma-icon-180.png" />
|
||||||
|
<meta name="theme-color" content="#0b2b7c" />
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="/src/main.tsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
root /usr/share/nginx/html;
|
||||||
|
index index.html;
|
||||||
|
|
||||||
|
gzip on;
|
||||||
|
gzip_types text/css application/javascript application/json image/svg+xml application/wasm;
|
||||||
|
client_max_body_size 1m;
|
||||||
|
|
||||||
|
# pdf.js worker ships as hashed .mjs; module workers need a JavaScript MIME type.
|
||||||
|
location ~* \.mjs$ {
|
||||||
|
types { }
|
||||||
|
default_type application/javascript;
|
||||||
|
expires 1y;
|
||||||
|
add_header Cache-Control "public, immutable";
|
||||||
|
try_files $uri =404;
|
||||||
|
}
|
||||||
|
|
||||||
|
location = /health {
|
||||||
|
access_log off;
|
||||||
|
default_type text/plain;
|
||||||
|
return 200 "ok\n";
|
||||||
|
}
|
||||||
|
|
||||||
|
# Vite assets carry a content hash -> cache forever.
|
||||||
|
location /assets/ {
|
||||||
|
expires 1y;
|
||||||
|
add_header Cache-Control "public, immutable";
|
||||||
|
try_files $uri =404;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Unhashed static files (fonts, logo, pdf.js cmaps): cache, but revalidate.
|
||||||
|
location ~* \.(?:woff2?|ttf|png|jpg|jpeg|gif|ico|webp|svg|bcmap|pfb)$ {
|
||||||
|
add_header Cache-Control "public, max-age=86400";
|
||||||
|
try_files $uri =404;
|
||||||
|
}
|
||||||
|
|
||||||
|
# index.html must always be fresh so users get new releases.
|
||||||
|
location / {
|
||||||
|
add_header Cache-Control "no-cache";
|
||||||
|
try_files $uri $uri/ /index.html;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
{
|
||||||
|
"name": "loma-pdf-editor",
|
||||||
|
"private": true,
|
||||||
|
"version": "0.0.0",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "tsc -b && vite build",
|
||||||
|
"lint": "eslint .",
|
||||||
|
"preview": "vite preview",
|
||||||
|
"predev": "node scripts/copy-pdfjs-assets.mjs",
|
||||||
|
"prebuild": "node scripts/copy-pdfjs-assets.mjs"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@pdf-lib/fontkit": "^1.1.1",
|
||||||
|
"docx": "^9.1.1",
|
||||||
|
"jszip": "^3.10.1",
|
||||||
|
"lucide-react": "^0.460.0",
|
||||||
|
"pdf-lib": "^1.17.1",
|
||||||
|
"pdfjs-dist": "^4.10.38",
|
||||||
|
"react": "^19.1.0",
|
||||||
|
"react-dom": "^19.1.0",
|
||||||
|
"tesseract.js": "^5.1.1",
|
||||||
|
"xlsx": "^0.18.5"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@eslint/js": "^9.25.0",
|
||||||
|
"@types/react": "^19.1.2",
|
||||||
|
"@types/react-dom": "^19.1.2",
|
||||||
|
"@vitejs/plugin-react": "^4.4.1",
|
||||||
|
"eslint": "^9.25.0",
|
||||||
|
"eslint-plugin-react-hooks": "^5.2.0",
|
||||||
|
"eslint-plugin-react-refresh": "^0.4.19",
|
||||||
|
"globals": "^16.0.0",
|
||||||
|
"typescript": "~5.8.3",
|
||||||
|
"typescript-eslint": "^8.30.1",
|
||||||
|
"vite": "^6.3.5"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
After Width: | Height: | Size: 50 KiB |
|
After Width: | Height: | Size: 56 KiB |
|
After Width: | Height: | Size: 2.8 KiB |
|
After Width: | Height: | Size: 243 KiB |
|
After Width: | Height: | Size: 8.2 KiB |
|
After Width: | Height: | Size: 286 KiB |
|
After Width: | Height: | Size: 1.4 MiB |
@@ -0,0 +1,9 @@
|
|||||||
|
// Copies pdf.js cMaps and standard fonts into public/ so the viewer works offline.
|
||||||
|
import { cpSync, existsSync } from 'node:fs';
|
||||||
|
import { resolve } from 'node:path';
|
||||||
|
|
||||||
|
const src = resolve('node_modules/pdfjs-dist');
|
||||||
|
const dst = resolve('public/pdfjs');
|
||||||
|
for (const dir of ['cmaps', 'standard_fonts']) {
|
||||||
|
if (!existsSync(resolve(dst, dir))) cpSync(resolve(src, dir), resolve(dst, dir), { recursive: true });
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
// Generates samples/sample.pdf: Thai + English text, an image, and form fields.
|
||||||
|
import { PDFDocument, StandardFonts, rgb } from 'pdf-lib';
|
||||||
|
import fontkit from '@pdf-lib/fontkit';
|
||||||
|
import { readFileSync, writeFileSync } from 'node:fs';
|
||||||
|
import zlib from 'node:zlib';
|
||||||
|
|
||||||
|
function png(w, h) { // simple gradient PNG
|
||||||
|
const raw = Buffer.alloc((w * 3 + 1) * h);
|
||||||
|
for (let y = 0; y < h; y++) { raw[y * (w * 3 + 1)] = 0; for (let x = 0; x < w; x++) { const o = y * (w * 3 + 1) + 1 + x * 3; raw[o] = (x * 255) / w; raw[o + 1] = (y * 255) / h; raw[o + 2] = 180; } }
|
||||||
|
const chunk = (t, d) => { const b = Buffer.alloc(8 + d.length + 4); b.writeUInt32BE(d.length); b.write(t, 4); d.copy(b, 8); b.writeUInt32BE(zlib.crc32 ? zlib.crc32(Buffer.concat([Buffer.from(t), d])) >>> 0 : 0, 8 + d.length); return b; };
|
||||||
|
const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(w); ihdr.writeUInt32BE(h, 4); ihdr[8] = 8; ihdr[9] = 2;
|
||||||
|
return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk('IHDR', ihdr), chunk('IDAT', zlib.deflateSync(raw)), chunk('IEND', Buffer.alloc(0))]);
|
||||||
|
}
|
||||||
|
|
||||||
|
const d = await PDFDocument.create();
|
||||||
|
d.registerFontkit(fontkit);
|
||||||
|
const th = await d.embedFont(readFileSync('public/fonts/Sarabun-Regular.ttf'));
|
||||||
|
const hb = await d.embedFont(StandardFonts.HelveticaBold);
|
||||||
|
const p = d.addPage([595, 842]);
|
||||||
|
p.drawText('Quarterly Report 2026', { x: 60, y: 770, size: 24, font: hb, color: rgb(0.1, 0.2, 0.5) });
|
||||||
|
p.drawText('รายงานประจำไตรมาส บริษัท ตัวอย่าง จำกัด', { x: 60, y: 735, size: 16, font: th });
|
||||||
|
p.drawText('Revenue grew 12% compared to last quarter.', { x: 60, y: 700, size: 12, font: th });
|
||||||
|
p.drawText('ยอดขายเพิ่มขึ้นร้อยละ 12 เมื่อเทียบกับไตรมาสก่อน', { x: 60, y: 682, size: 12, font: th });
|
||||||
|
const img = await d.embedPng(png(200, 120));
|
||||||
|
p.drawImage(img, { x: 60, y: 520, width: 200, height: 120 });
|
||||||
|
const rows = [['Item', 'Q1', 'Q2'], ['Sales', '1,200', '1,344'], ['Cost', '800', '850']];
|
||||||
|
rows.forEach((r, i) => r.forEach((c, j) => p.drawText(c, { x: 300 + j * 80, y: 620 - i * 20, size: 11, font: th })));
|
||||||
|
const form = d.getForm();
|
||||||
|
p.drawText('ชื่อผู้อนุมัติ:', { x: 60, y: 452, size: 12, font: th });
|
||||||
|
form.createTextField('approver').addToPage(p, { x: 150, y: 445, width: 200, height: 22 });
|
||||||
|
p.drawText('Agree:', { x: 60, y: 420, size: 12, font: th });
|
||||||
|
form.createCheckBox('agree').addToPage(p, { x: 150, y: 415, width: 14, height: 14 });
|
||||||
|
const p2 = d.addPage([595, 842]);
|
||||||
|
p2.drawText('Page two - เลขบัตรประชาชน 1-2345-67890-12-3', { x: 60, y: 770, size: 14, font: th });
|
||||||
|
writeFileSync('samples/sample.pdf', await d.save());
|
||||||
|
console.log('ok');
|
||||||
@@ -0,0 +1,509 @@
|
|||||||
|
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||||
|
import type React from 'react';
|
||||||
|
import { Check, FilePlus2, FolderOpen, Images, Languages, Maximize2, Redo2, Save, ShieldCheck, Undo2, ZoomIn, ZoomOut } from 'lucide-react';
|
||||||
|
import { EditorCtx, type Editor, type Loaded, type ToastAction } from './editor';
|
||||||
|
import { loadPdf } from './lib/pdfjs';
|
||||||
|
import { exportPdf } from './lib/export';
|
||||||
|
import { blankPdf, imagesToPdf } from './lib/pageops';
|
||||||
|
import type { DocState, Rect, Tab, Tool, ToolOpts } from './lib/types';
|
||||||
|
import { baseName, download, friendlyError, pickFiles, readFile, uid } from './lib/util';
|
||||||
|
import { translateItem } from './lib/geom';
|
||||||
|
import { PageView } from './components/PageView';
|
||||||
|
import { Ribbon } from './components/Ribbon';
|
||||||
|
import { SidePanel } from './components/SidePanel';
|
||||||
|
import { Thumbnails } from './components/Thumbnails';
|
||||||
|
import { SignatureModal } from './components/SignatureModal';
|
||||||
|
import { Dialog } from './components/Dialog';
|
||||||
|
import { LomaLockup, LomaMark } from './components/LomaMark';
|
||||||
|
import { setLang, tr, useLang } from './i18n';
|
||||||
|
|
||||||
|
type Hist = { past: DocState[]; cur: DocState | null; future: DocState[] };
|
||||||
|
const DEFAULT_OPTS: ToolOpts = { color: '#000000', fill: null, highlight: '#ffeb3b', width: 2, size: 12, bold: false, opacity: 1, pending: null };
|
||||||
|
const TAB_TOOL: Partial<Record<Tab, Tool>> = { edit: 'edit', comment: 'select', sign: 'select', forms: 'select', redact: 'redact' };
|
||||||
|
|
||||||
|
export default function App() {
|
||||||
|
const lang = useLang();
|
||||||
|
const [hist, setHist] = useState<Hist>({ past: [], cur: null, future: [] });
|
||||||
|
const doc = hist.cur;
|
||||||
|
const [loaded, setLoaded] = useState<Loaded | null>(null);
|
||||||
|
const [tool, setToolRaw] = useState<Tool>('select');
|
||||||
|
const [opts, setOptsRaw] = useState<ToolOpts>(DEFAULT_OPTS);
|
||||||
|
const [selectedId, select] = useState<string | null>(null);
|
||||||
|
const [editingId, setEditing] = useState<string | null>(null);
|
||||||
|
const [scale, setScaleRaw] = useState(1);
|
||||||
|
const [tab, setTabRaw] = useState<Tab>('edit');
|
||||||
|
const [selPages, setSelPages] = useState<string[]>([]);
|
||||||
|
const [current, setCurrent] = useState(0);
|
||||||
|
const [hit, setHit] = useState<{ pageId: string; rect: Rect } | null>(null);
|
||||||
|
const [busy, setBusy] = useState<string | null>(null);
|
||||||
|
const [toastMsg, setToastMsg] = useState<{ msg: string; action?: ToastAction } | null>(null);
|
||||||
|
const [saved, setSaved] = useState<DocState | null>(null);
|
||||||
|
const [confirmSave, setConfirmSave] = useState(false);
|
||||||
|
const [flatten, setFlatten] = useState(false);
|
||||||
|
const [sigOpen, setSigOpen] = useState(false);
|
||||||
|
const [dragOver, setDragOver] = useState(false);
|
||||||
|
const viewer = useRef<HTMLDivElement>(null);
|
||||||
|
const fitPending = useRef(false);
|
||||||
|
/** While true the zoom follows the viewer width (set on open and by "fit width"; cleared by manual zoom). */
|
||||||
|
const fitMode = useRef(true);
|
||||||
|
|
||||||
|
const toast = useCallback((msg: string, action?: ToastAction) => {
|
||||||
|
const t = { msg, action };
|
||||||
|
setToastMsg(t);
|
||||||
|
// Messages with an action stay longer so there is time to use it.
|
||||||
|
window.setTimeout(() => setToastMsg((c) => (c === t ? null : c)), action ? 8000 : 4500);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const run = useCallback(
|
||||||
|
async (label: string, fn: () => Promise<void>) => {
|
||||||
|
setBusy(label);
|
||||||
|
try {
|
||||||
|
await fn();
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
toast(friendlyError(e));
|
||||||
|
} finally {
|
||||||
|
setBusy(null);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[toast],
|
||||||
|
);
|
||||||
|
|
||||||
|
// (Re)load pdf.js whenever the underlying bytes change.
|
||||||
|
useEffect(() => {
|
||||||
|
if (!doc) return;
|
||||||
|
if (loaded?.bytes === doc.bytes) return;
|
||||||
|
let alive = true;
|
||||||
|
const { bytes, pageIds } = doc;
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
const pdf = await loadPdf(bytes);
|
||||||
|
const sizes: { w: number; h: number }[] = [];
|
||||||
|
for (let i = 1; i <= pdf.numPages; i++) {
|
||||||
|
const v = (await pdf.getPage(i)).getViewport({ scale: 1 });
|
||||||
|
sizes.push({ w: v.width, h: v.height });
|
||||||
|
}
|
||||||
|
if (!alive) return void pdf.destroy();
|
||||||
|
setLoaded((prev) => {
|
||||||
|
if (prev && prev.pdf !== pdf) setTimeout(() => prev.pdf.destroy(), 1000);
|
||||||
|
return { bytes, pdf, sizes, pageIds };
|
||||||
|
});
|
||||||
|
if (fitPending.current && sizes.length) {
|
||||||
|
fitPending.current = false;
|
||||||
|
fitMode.current = true;
|
||||||
|
fitTo(sizes);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
toast(`${tr('เปิด PDF ไม่ได้', 'Could not open PDF')}: ${friendlyError(e)}`);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
return () => {
|
||||||
|
alive = false;
|
||||||
|
};
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [doc?.bytes]);
|
||||||
|
|
||||||
|
const commit = useCallback((fn: (d: DocState) => DocState) => {
|
||||||
|
setHist((h) => (h.cur ? { past: [...h.past.slice(-60), h.cur], cur: fn(h.cur), future: [] } : h));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const setBytes = useCallback(
|
||||||
|
(bytes: Uint8Array, pageIds: string[]) => {
|
||||||
|
const keep = new Set(pageIds);
|
||||||
|
commit((d) => ({ ...d, bytes, pageIds, items: d.items.filter((i) => keep.has(i.pageId)) }));
|
||||||
|
setSelPages((s) => s.filter((id) => keep.has(id)));
|
||||||
|
},
|
||||||
|
[commit],
|
||||||
|
);
|
||||||
|
|
||||||
|
const undo = useCallback(() => {
|
||||||
|
setEditing(null);
|
||||||
|
setHist((h) => (h.past.length && h.cur ? { past: h.past.slice(0, -1), cur: h.past[h.past.length - 1], future: [h.cur, ...h.future] } : h));
|
||||||
|
}, []);
|
||||||
|
const redo = useCallback(() => {
|
||||||
|
setEditing(null);
|
||||||
|
setHist((h) => (h.future.length && h.cur ? { past: [...h.past, h.cur], cur: h.future[0], future: h.future.slice(1) } : h));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const setTool = useCallback((t: Tool) => {
|
||||||
|
setToolRaw(t);
|
||||||
|
setEditing(null);
|
||||||
|
if (t !== 'select' && t !== 'edit') select(null);
|
||||||
|
}, []);
|
||||||
|
const setTab = useCallback(
|
||||||
|
(t: Tab) => {
|
||||||
|
setTabRaw(t);
|
||||||
|
const tt = TAB_TOOL[t];
|
||||||
|
if (tt) setTool(tt);
|
||||||
|
},
|
||||||
|
[setTool],
|
||||||
|
);
|
||||||
|
const setOpts = useCallback((p: Partial<ToolOpts>) => setOptsRaw((o) => ({ ...o, ...p })), []);
|
||||||
|
const setScale = useCallback((s: number) => setScaleRaw(Math.min(4, Math.max(0.25, Math.round(s * 100) / 100))), []);
|
||||||
|
|
||||||
|
/** Zoom so the widest page fits the viewer (minus its padding). */
|
||||||
|
const fitTo = useCallback((sizes: { w: number }[], cap = 1.6) => {
|
||||||
|
const v = viewer.current;
|
||||||
|
if (!v || !sizes.length) return;
|
||||||
|
const cs = getComputedStyle(v);
|
||||||
|
const room = v.clientWidth - parseFloat(cs.paddingLeft) - parseFloat(cs.paddingRight) - 4;
|
||||||
|
setScaleRaw(Math.min(cap, Math.max(0.25, Math.floor((room / Math.max(...sizes.map((s) => s.w))) * 100) / 100)));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Keep fitting when the window or panels change size (phones rotate, panels open).
|
||||||
|
useEffect(() => {
|
||||||
|
const v = viewer.current;
|
||||||
|
if (!v || !loaded) return;
|
||||||
|
const ro = new ResizeObserver(() => fitMode.current && fitTo(loaded.sizes));
|
||||||
|
ro.observe(v);
|
||||||
|
return () => ro.disconnect();
|
||||||
|
}, [loaded, fitTo]);
|
||||||
|
const zoomBy = (k: number) => {
|
||||||
|
fitMode.current = false;
|
||||||
|
setScale(scale * k);
|
||||||
|
};
|
||||||
|
|
||||||
|
const gotoPage = useCallback((i: number) => {
|
||||||
|
const el = viewer.current?.querySelector(`.page-wrap[data-index="${i}"]`);
|
||||||
|
el?.scrollIntoView({ block: 'start', behavior: 'smooth' });
|
||||||
|
setCurrent(i);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const exportBytes = useCallback(() => exportPdf(hist.cur!, { flattenForms: flatten }), [hist.cur, flatten]);
|
||||||
|
|
||||||
|
function openDoc(bytes: Uint8Array, name: string, pages: number) {
|
||||||
|
fitPending.current = true;
|
||||||
|
setLoaded(null);
|
||||||
|
const cur = { bytes, name, pageIds: Array.from({ length: pages }, uid), items: [], form: {} };
|
||||||
|
setHist({ past: [], cur, future: [] });
|
||||||
|
setSaved(cur);
|
||||||
|
select(null);
|
||||||
|
setEditing(null);
|
||||||
|
setSelPages([]);
|
||||||
|
setCurrent(0);
|
||||||
|
setTabRaw('edit');
|
||||||
|
setToolRaw('select');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openFiles(files: File[]) {
|
||||||
|
const pdfs = files.filter((f) => f.type === 'application/pdf' || /\.pdf$/i.test(f.name));
|
||||||
|
const imgs = files.filter((f) => f.type.startsWith('image/'));
|
||||||
|
await run(tr('กำลังเปิดไฟล์…', 'Opening file…'), async () => {
|
||||||
|
if (pdfs.length) {
|
||||||
|
const bytes = await readFile(pdfs[0]);
|
||||||
|
const pdf = await loadPdf(bytes);
|
||||||
|
const n = pdf.numPages;
|
||||||
|
pdf.destroy();
|
||||||
|
openDoc(bytes, pdfs[0].name, n);
|
||||||
|
} else if (imgs.length) {
|
||||||
|
const r = await imagesToPdf(imgs);
|
||||||
|
openDoc(r.bytes, `${baseName(imgs[0].name)}.pdf`, r.added);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const dirty = !!doc && doc !== saved;
|
||||||
|
// What becomes permanent on save: redacted pages turn into images, flattened fields stop being editable.
|
||||||
|
const redactions = doc ? doc.items.filter((i) => i.kind === 'redact') : [];
|
||||||
|
const redactPages = new Set(redactions.map((i) => i.pageId)).size;
|
||||||
|
const permanent = redactions.length > 0 || flatten;
|
||||||
|
|
||||||
|
const doSave = useCallback(
|
||||||
|
() =>
|
||||||
|
run(tr('กำลังบันทึก…', 'Saving…'), async () => {
|
||||||
|
const cur = hist.cur!;
|
||||||
|
const out = await exportBytes();
|
||||||
|
download(out, `${baseName(cur.name)}-edited.pdf`);
|
||||||
|
setSaved(cur);
|
||||||
|
toast(tr(`บันทึกแล้ว — ดาวน์โหลด ${baseName(cur.name)}-edited.pdf`, `Saved — downloaded ${baseName(cur.name)}-edited.pdf`));
|
||||||
|
}),
|
||||||
|
[run, exportBytes, hist.cur, toast],
|
||||||
|
);
|
||||||
|
const save = useCallback(() => (permanent ? setConfirmSave(true) : doSave()), [permanent, doSave]);
|
||||||
|
|
||||||
|
// Keyboard shortcuts.
|
||||||
|
useEffect(() => {
|
||||||
|
const onKey = (e: KeyboardEvent) => {
|
||||||
|
const t = e.target as HTMLElement;
|
||||||
|
if (t.closest('input, textarea, select, [contenteditable="true"]')) return;
|
||||||
|
const mod = e.ctrlKey || e.metaKey;
|
||||||
|
if (mod && e.key.toLowerCase() === 'z') {
|
||||||
|
e.preventDefault();
|
||||||
|
(e.shiftKey ? redo : undo)();
|
||||||
|
} else if (mod && e.key.toLowerCase() === 'y') {
|
||||||
|
e.preventDefault();
|
||||||
|
redo();
|
||||||
|
} else if (mod && e.key.toLowerCase() === 's') {
|
||||||
|
e.preventDefault();
|
||||||
|
if (hist.cur) save();
|
||||||
|
} else if (mod && e.key.toLowerCase() === 'f') {
|
||||||
|
e.preventDefault();
|
||||||
|
setTabRaw('search');
|
||||||
|
requestAnimationFrame(() => document.getElementById('search-input')?.focus());
|
||||||
|
} else if (e.key.startsWith('Arrow') && selectedId) {
|
||||||
|
// Nudge the selected item: 1pt, or 10pt with Shift.
|
||||||
|
e.preventDefault();
|
||||||
|
const step = e.shiftKey ? 10 : 1;
|
||||||
|
const d = { ArrowLeft: { x: -step, y: 0 }, ArrowRight: { x: step, y: 0 }, ArrowUp: { x: 0, y: step }, ArrowDown: { x: 0, y: -step } }[e.key];
|
||||||
|
if (d) commit((doc) => ({ ...doc, items: doc.items.map((i) => (i.id === selectedId ? translateItem(i, d) : i)) }));
|
||||||
|
} else if ((e.key === 'Delete' || e.key === 'Backspace') && selectedId) {
|
||||||
|
commit((d) => ({ ...d, items: d.items.filter((i) => i.id !== selectedId) }));
|
||||||
|
select(null);
|
||||||
|
} else if (e.key === 'Escape') {
|
||||||
|
select(null);
|
||||||
|
setTool('select');
|
||||||
|
} else if (!mod && !e.altKey) {
|
||||||
|
const map: Record<string, Tool> = { v: 'select', e: 'edit', t: 'text', h: 'highlight', p: 'pen', n: 'note' };
|
||||||
|
const k = map[e.key.toLowerCase()];
|
||||||
|
if (k && hist.cur) setTool(k);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
window.addEventListener('keydown', onKey);
|
||||||
|
return () => window.removeEventListener('keydown', onKey);
|
||||||
|
}, [undo, redo, save, selectedId, commit, setTool, hist.cur]);
|
||||||
|
|
||||||
|
// Warn before leaving with unsaved changes.
|
||||||
|
useEffect(() => {
|
||||||
|
const h = (e: BeforeUnloadEvent) => {
|
||||||
|
if (dirty) e.preventDefault();
|
||||||
|
};
|
||||||
|
window.addEventListener('beforeunload', h);
|
||||||
|
return () => window.removeEventListener('beforeunload', h);
|
||||||
|
}, [dirty]);
|
||||||
|
|
||||||
|
const onScroll = () => {
|
||||||
|
const v = viewer.current;
|
||||||
|
if (!v) return;
|
||||||
|
const mid = v.scrollTop + v.clientHeight * 0.35;
|
||||||
|
const pages = v.querySelectorAll<HTMLElement>('.page-wrap');
|
||||||
|
for (let i = 0; i < pages.length; i++) {
|
||||||
|
if (pages[i].offsetTop + pages[i].offsetHeight > mid) {
|
||||||
|
if (i !== current) setCurrent(i);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const ed: Editor | null = useMemo(
|
||||||
|
() =>
|
||||||
|
doc && loaded
|
||||||
|
? {
|
||||||
|
lang, doc, loaded, commit, setBytes, undo, redo,
|
||||||
|
canUndo: hist.past.length > 0, canRedo: hist.future.length > 0,
|
||||||
|
tool, setTool, opts, setOpts, selectedId, select, editingId, setEditing,
|
||||||
|
scale, setScale, tab, setTab, selPages, setSelPages, current, gotoPage,
|
||||||
|
hit, setHit, run, toast, exportBytes, flatten, setFlatten,
|
||||||
|
openSignature: () => setSigOpen(true),
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
[lang, doc, loaded, commit, setBytes, undo, redo, hist.past.length, hist.future.length, tool, setTool, opts, setOpts, selectedId, editingId, scale, setScale, tab, setTab, selPages, current, gotoPage, hit, run, toast, exportBytes, flatten],
|
||||||
|
);
|
||||||
|
|
||||||
|
const dropProps = {
|
||||||
|
onDragOver: (e: React.DragEvent) => {
|
||||||
|
if (e.dataTransfer.types.includes('Files')) {
|
||||||
|
e.preventDefault();
|
||||||
|
setDragOver(true);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onDragLeave: () => setDragOver(false),
|
||||||
|
onDrop: (e: React.DragEvent) => {
|
||||||
|
if (!e.dataTransfer.files.length) return;
|
||||||
|
e.preventDefault();
|
||||||
|
setDragOver(false);
|
||||||
|
openFiles(Array.from(e.dataTransfer.files));
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const openBtn = async () => {
|
||||||
|
const f = await pickFiles('application/pdf,image/*');
|
||||||
|
if (f.length) openFiles(f);
|
||||||
|
};
|
||||||
|
|
||||||
|
const langBtn = (
|
||||||
|
<button className="tb lang-btn" onClick={() => setLang(lang === 'th' ? 'en' : 'th')} title={tr('Switch to English', 'เปลี่ยนเป็นภาษาไทย')}>
|
||||||
|
<Languages size={18} /> {lang === 'th' ? 'EN' : 'ไทย'}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
|
||||||
|
const toastEl = toastMsg && (
|
||||||
|
<div className="toast">
|
||||||
|
<span>{toastMsg.msg}</span>
|
||||||
|
{toastMsg.action && (
|
||||||
|
<button
|
||||||
|
className="toast-action"
|
||||||
|
onClick={() => {
|
||||||
|
toastMsg.action!.fn();
|
||||||
|
setToastMsg(null);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{toastMsg.action.label}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
// Live regions stay mounted so screen readers announce changes to them.
|
||||||
|
const live = (
|
||||||
|
<>
|
||||||
|
<div className="sr-only" role="status" aria-live="polite">{toastMsg?.msg ?? ''}</div>
|
||||||
|
<div className="sr-only" aria-live="polite">{busy ?? ''}</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!doc) {
|
||||||
|
return (
|
||||||
|
<div className={`start${dragOver ? ' drag' : ''}`} {...dropProps}>
|
||||||
|
<div className="start-lang">{langBtn}</div>
|
||||||
|
<main className="start-card">
|
||||||
|
<h2 className="logo"><LomaLockup height={72} /></h2>
|
||||||
|
<h1 className="start-title">{tr('เซ็น กรอก แก้ PDF เสร็จในเบราว์เซอร์', 'Sign, fill and edit PDFs in your browser')}</h1>
|
||||||
|
<p className="start-sub">
|
||||||
|
<ShieldCheck size={16} aria-hidden /> {tr('ฟรี ไม่ต้องสมัคร · ไฟล์ไม่ถูกอัปโหลดไปไหน', 'Free, no sign-up · files never leave your device')}
|
||||||
|
</p>
|
||||||
|
<div className="start-actions">
|
||||||
|
<button className="btn primary big" onClick={openBtn}>
|
||||||
|
<FolderOpen size={20} /> {tr('เปิด PDF', 'Open PDF')}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className="btn big"
|
||||||
|
onClick={async () => {
|
||||||
|
const f = await pickFiles('image/*', true);
|
||||||
|
if (f.length) openFiles(f);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Images size={20} /> {tr('รูปภาพ → PDF', 'Images → PDF')}
|
||||||
|
</button>
|
||||||
|
<button className="btn big" onClick={() => run(tr('สร้างเอกสาร…', 'Creating document…'), async () => openDoc(await blankPdf(), tr('เอกสารใหม่.pdf', 'New document.pdf'), 1))}>
|
||||||
|
<FilePlus2 size={20} /> {tr('เอกสารเปล่า', 'Blank document')}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<p className="hint">{tr('หรือลากไฟล์มาวางที่นี่', 'or drop files here')}</p>
|
||||||
|
<ul className="features" aria-label={tr('ทำอะไรได้บ้าง', 'What you can do')}>
|
||||||
|
{[
|
||||||
|
tr('ลงนาม วาด พิมพ์ หรืออัปโหลดลายเซ็น', 'Sign: draw, type or upload a signature'),
|
||||||
|
tr('กรอกฟอร์ม และสร้างช่องกรอกใหม่', 'Fill forms and add new fields'),
|
||||||
|
tr('แก้ข้อความและรูปที่มีอยู่เดิม', 'Edit existing text and images'),
|
||||||
|
tr('ไฮไลต์ คอมเมนต์ ตราประทับ', 'Highlight, comment, stamp'),
|
||||||
|
tr('รวม แยก หมุน จัดเรียงหน้า', 'Merge, split, rotate, reorder pages'),
|
||||||
|
tr('ปกปิดข้อมูลส่วนตัวแบบถาวร', 'Permanently redact personal data'),
|
||||||
|
tr('OCR ไทย/อังกฤษ', 'OCR for Thai and English'),
|
||||||
|
tr('แปลงเป็น Word / Excel / รูป', 'Convert to Word, Excel or images'),
|
||||||
|
].map((t) => (
|
||||||
|
<li key={t}><Check size={15} aria-hidden /> {t}</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</main>
|
||||||
|
{busy && <div className="busy">{busy}</div>}
|
||||||
|
{toastEl}
|
||||||
|
{live}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="app" {...dropProps}>
|
||||||
|
<header className="topbar">
|
||||||
|
<div className="logo small"><LomaMark size={28} /> <span className="logo-word">Loma</span></div>
|
||||||
|
<span className="doc-name" title={doc.name}>{doc.name}</span>
|
||||||
|
{dirty && <span className="dirty" title={tr('มีการแก้ไขที่ยังไม่บันทึก', 'Unsaved changes')}>{tr('ยังไม่บันทึก', 'Unsaved')}</span>}
|
||||||
|
<button className="tb" onClick={openBtn} aria-label={tr('เปิดไฟล์', 'Open file')} title={tr('เปิดไฟล์', 'Open file')}>
|
||||||
|
<FolderOpen size={18} /> <span className="tb-label">{tr('เปิด', 'Open')}</span>
|
||||||
|
</button>
|
||||||
|
<button className="tb primary" onClick={save} disabled={!ed} title={tr('บันทึกและดาวน์โหลด (Ctrl+S)', 'Save & download (Ctrl+S)')}>
|
||||||
|
<Save size={18} /> {tr('บันทึก', 'Save')}
|
||||||
|
</button>
|
||||||
|
<span className="sep" />
|
||||||
|
<button className="tb" onClick={undo} disabled={!hist.past.length} aria-label={tr('เลิกทำ', 'Undo')} title={tr('เลิกทำ (Ctrl+Z)', 'Undo (Ctrl+Z)')}>
|
||||||
|
<Undo2 size={18} />
|
||||||
|
</button>
|
||||||
|
<button className="tb" onClick={redo} disabled={!hist.future.length} aria-label={tr('ทำซ้ำ', 'Redo')} title={tr('ทำซ้ำ (Ctrl+Y)', 'Redo (Ctrl+Y)')}>
|
||||||
|
<Redo2 size={18} />
|
||||||
|
</button>
|
||||||
|
<span className="spacer" />
|
||||||
|
<span className="page-ind">
|
||||||
|
{tr('หน้า', 'Page')} {current + 1} / {doc.pageIds.length}
|
||||||
|
</span>
|
||||||
|
<div className="zoom-group">
|
||||||
|
<button className="tb" onClick={() => zoomBy(1 / 1.2)} aria-label={tr('ซูมออก', 'Zoom out')} title={tr('ซูมออก', 'Zoom out')}>
|
||||||
|
<ZoomOut size={18} />
|
||||||
|
</button>
|
||||||
|
<span className="zoom">{Math.round(scale * 100)}%</span>
|
||||||
|
<button className="tb" onClick={() => zoomBy(1.2)} aria-label={tr('ซูมเข้า', 'Zoom in')} title={tr('ซูมเข้า', 'Zoom in')}>
|
||||||
|
<ZoomIn size={18} />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className="tb"
|
||||||
|
aria-label={tr('พอดีความกว้าง', 'Fit width')}
|
||||||
|
title={tr('พอดีความกว้าง', 'Fit width')}
|
||||||
|
onClick={() => {
|
||||||
|
fitMode.current = true;
|
||||||
|
if (loaded) fitTo(loaded.sizes, 4);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Maximize2 size={18} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{langBtn}
|
||||||
|
</header>
|
||||||
|
{ed ? (
|
||||||
|
<EditorCtx.Provider value={ed}>
|
||||||
|
<Ribbon />
|
||||||
|
<div className="main">
|
||||||
|
<Thumbnails />
|
||||||
|
<main className="viewer" ref={viewer} onScroll={onScroll} aria-label={tr('หน้าเอกสาร', 'Document pages')}>
|
||||||
|
{loaded!.pageIds.map((id, i) => (
|
||||||
|
<PageView key={id} index={i} pageId={id} size={loaded!.sizes[i]} />
|
||||||
|
))}
|
||||||
|
</main>
|
||||||
|
<SidePanel />
|
||||||
|
</div>
|
||||||
|
{sigOpen && <SignatureModal onClose={() => setSigOpen(false)} />}
|
||||||
|
</EditorCtx.Provider>
|
||||||
|
) : (
|
||||||
|
<div className="main loading" ref={viewer}>
|
||||||
|
{tr('กำลังโหลด…', 'Loading…')}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{confirmSave && (
|
||||||
|
<Dialog
|
||||||
|
title={tr('บันทึกแล้วจะแก้กลับไม่ได้', 'Some changes become permanent')}
|
||||||
|
onClose={() => setConfirmSave(false)}
|
||||||
|
className="confirm"
|
||||||
|
footer={
|
||||||
|
<>
|
||||||
|
<span className="spacer" />
|
||||||
|
<button className="btn" onClick={() => setConfirmSave(false)}>{tr('กลับไปแก้', 'Go back')}</button>
|
||||||
|
<button
|
||||||
|
className="btn primary"
|
||||||
|
autoFocus
|
||||||
|
onClick={() => {
|
||||||
|
setConfirmSave(false);
|
||||||
|
doSave();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{tr('บันทึก', 'Save')}
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<ul className="confirm-list">
|
||||||
|
{redactions.length > 0 && (
|
||||||
|
<li>
|
||||||
|
{tr(
|
||||||
|
`ปกปิดถาวร ${redactions.length} จุดใน ${redactPages} หน้า — หน้าเหล่านั้นจะกลายเป็นภาพ เลือกหรือค้นหาข้อความไม่ได้อีก`,
|
||||||
|
`${redactions.length} redaction(s) on ${redactPages} page(s) become permanent — those pages turn into images and their text can no longer be selected or searched`,
|
||||||
|
)}
|
||||||
|
</li>
|
||||||
|
)}
|
||||||
|
{flatten && <li>{tr('ฟอร์มจะถูกล็อก (Flatten) — กรอกหรือแก้ค่าไม่ได้อีก', 'The form is locked (flattened) — fields can no longer be filled or changed')}</li>}
|
||||||
|
</ul>
|
||||||
|
<p className="hint confirm-note">{tr('ไฟล์ต้นฉบับในเครื่องของคุณไม่ถูกแก้ ระบบจะดาวน์โหลดเป็นไฟล์ใหม่', 'Your original file is not changed; a new file is downloaded.')}</p>
|
||||||
|
</Dialog>
|
||||||
|
)}
|
||||||
|
{(busy || (doc && loaded && loaded.bytes !== doc.bytes)) && <div className="busy">{busy ?? tr('กำลังอัปเดต…', 'Updating…')}</div>}
|
||||||
|
{dragOver && <div className="drop-hint">{tr('วางไฟล์เพื่อเปิด', 'Drop to open')}</div>}
|
||||||
|
{toastEl}
|
||||||
|
{live}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
import { useEffect, useId, useRef } from 'react';
|
||||||
|
import type React from 'react';
|
||||||
|
import { X } from 'lucide-react';
|
||||||
|
import { tr } from '../i18n';
|
||||||
|
|
||||||
|
const FOCUSABLE = 'button:not(:disabled), [href], input:not(:disabled), select:not(:disabled), textarea:not(:disabled), canvas[tabindex], [tabindex]:not([tabindex="-1"])';
|
||||||
|
|
||||||
|
/** Modal dialog: labelled, keeps focus inside, closes on Esc or backdrop, restores focus on close. */
|
||||||
|
export function Dialog({ title, onClose, children, footer, className = '' }: {
|
||||||
|
title: string;
|
||||||
|
onClose: () => void;
|
||||||
|
children: React.ReactNode;
|
||||||
|
footer?: React.ReactNode;
|
||||||
|
className?: string;
|
||||||
|
}) {
|
||||||
|
const ref = useRef<HTMLDivElement>(null);
|
||||||
|
const titleId = useId();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const back = document.activeElement as HTMLElement | null;
|
||||||
|
const el = ref.current!;
|
||||||
|
if (!el.contains(document.activeElement)) (el.querySelector<HTMLElement>('[autofocus], ' + FOCUSABLE) ?? el).focus();
|
||||||
|
return () => back?.focus?.();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const onKeyDown = (e: React.KeyboardEvent) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
if (e.key === 'Escape') {
|
||||||
|
e.preventDefault();
|
||||||
|
onClose();
|
||||||
|
} else if (e.key === 'Tab') {
|
||||||
|
const f = [...ref.current!.querySelectorAll<HTMLElement>(FOCUSABLE)];
|
||||||
|
if (!f.length) return;
|
||||||
|
const first = f[0];
|
||||||
|
const last = f[f.length - 1];
|
||||||
|
if (e.shiftKey && document.activeElement === first) {
|
||||||
|
e.preventDefault();
|
||||||
|
last.focus();
|
||||||
|
} else if (!e.shiftKey && document.activeElement === last) {
|
||||||
|
e.preventDefault();
|
||||||
|
first.focus();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="modal-bg" onPointerDown={onClose}>
|
||||||
|
<div
|
||||||
|
ref={ref}
|
||||||
|
className={`modal ${className}`}
|
||||||
|
role="dialog"
|
||||||
|
aria-modal="true"
|
||||||
|
aria-labelledby={titleId}
|
||||||
|
tabIndex={-1}
|
||||||
|
onPointerDown={(e) => e.stopPropagation()}
|
||||||
|
onKeyDown={onKeyDown}
|
||||||
|
>
|
||||||
|
<header>
|
||||||
|
<h2 id={titleId}>{title}</h2>
|
||||||
|
<button className="icon-btn" onClick={onClose} aria-label={tr('ปิด', 'Close')}>
|
||||||
|
<X size={18} />
|
||||||
|
</button>
|
||||||
|
</header>
|
||||||
|
{children}
|
||||||
|
{footer && <footer>{footer}</footer>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import type React from 'react';
|
||||||
|
import { useEditor } from '../editor';
|
||||||
|
import { rectToScreen, type VP } from '../lib/geom';
|
||||||
|
import type { FormValue } from '../lib/types';
|
||||||
|
|
||||||
|
/** Subset of pdf.js widget annotation data we use. */
|
||||||
|
export type WidgetData = {
|
||||||
|
id: string;
|
||||||
|
subtype: string;
|
||||||
|
fieldName: string;
|
||||||
|
fieldType: 'Tx' | 'Btn' | 'Ch' | 'Sig';
|
||||||
|
rect: number[];
|
||||||
|
fieldValue?: string | string[];
|
||||||
|
checkBox?: boolean;
|
||||||
|
radioButton?: boolean;
|
||||||
|
pushButton?: boolean;
|
||||||
|
buttonValue?: string;
|
||||||
|
exportValue?: string;
|
||||||
|
multiLine?: boolean;
|
||||||
|
readOnly?: boolean;
|
||||||
|
hidden?: boolean;
|
||||||
|
combo?: boolean;
|
||||||
|
options?: { exportValue: string; displayValue: string }[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export function FormWidget({ w, vp, active }: { w: WidgetData; vp: VP; active: boolean }) {
|
||||||
|
const ed = useEditor();
|
||||||
|
const name = w.fieldName;
|
||||||
|
const b = rectToScreen(vp, { x: w.rect[0], y: w.rect[1], w: w.rect[2] - w.rect[0], h: w.rect[3] - w.rect[1] });
|
||||||
|
const v = ed.doc.form[name];
|
||||||
|
const set = (val: FormValue) => ed.commit((d) => ({ ...d, form: { ...d.form, [name]: val } }));
|
||||||
|
const style = {
|
||||||
|
...b,
|
||||||
|
fontSize: Math.max(8, Math.min(b.height * 0.65, 13 * vp.scale)),
|
||||||
|
pointerEvents: active && !w.readOnly ? ('auto' as const) : ('none' as const),
|
||||||
|
};
|
||||||
|
const stop = (e: React.PointerEvent | React.KeyboardEvent) => e.stopPropagation();
|
||||||
|
|
||||||
|
if (w.fieldType === 'Tx') return <TextWidget w={w} style={style} value={typeof v === 'string' ? v : String(w.fieldValue ?? '')} onSet={set} />;
|
||||||
|
if (w.fieldType === 'Btn' && w.checkBox) {
|
||||||
|
const on = typeof v === 'boolean' ? v : !!w.fieldValue && w.fieldValue !== 'Off';
|
||||||
|
return <input type="checkbox" className="fw fw-check" style={style} checked={on} onPointerDown={stop} onChange={(e) => set(e.target.checked)} title={name} />;
|
||||||
|
}
|
||||||
|
if (w.fieldType === 'Btn' && w.radioButton) {
|
||||||
|
const cur = typeof v === 'string' ? v : w.fieldValue;
|
||||||
|
return <input type="radio" className="fw fw-check" style={style} checked={!!w.buttonValue && cur === w.buttonValue} onPointerDown={stop} onChange={() => w.buttonValue && set(w.buttonValue)} title={name} />;
|
||||||
|
}
|
||||||
|
if (w.fieldType === 'Ch') {
|
||||||
|
const opts = w.options ?? [];
|
||||||
|
const raw = Array.isArray(w.fieldValue) ? w.fieldValue[0] : w.fieldValue;
|
||||||
|
const cur = typeof v === 'string' ? v : (opts.find((o) => o.exportValue === raw)?.displayValue ?? raw ?? '');
|
||||||
|
return (
|
||||||
|
<select className="fw" style={style} value={cur} onPointerDown={stop} onKeyDown={stop} onChange={(e) => set(e.target.value)} title={name}>
|
||||||
|
<option value="" />
|
||||||
|
{opts.map((o) => (
|
||||||
|
<option key={o.exportValue + o.displayValue} value={o.displayValue}>
|
||||||
|
{o.displayValue}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function TextWidget({ w, style, value, onSet }: { w: WidgetData; style: React.CSSProperties; value: string; onSet: (v: string) => void }) {
|
||||||
|
const [draft, setDraft] = useState(value);
|
||||||
|
useEffect(() => setDraft(value), [value]);
|
||||||
|
const common = {
|
||||||
|
className: 'fw',
|
||||||
|
style,
|
||||||
|
value: draft,
|
||||||
|
title: w.fieldName,
|
||||||
|
onPointerDown: (e: React.PointerEvent) => e.stopPropagation(),
|
||||||
|
onKeyDown: (e: React.KeyboardEvent) => e.stopPropagation(),
|
||||||
|
onChange: (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => setDraft(e.target.value),
|
||||||
|
onBlur: () => draft !== value && onSet(draft),
|
||||||
|
};
|
||||||
|
return w.multiLine ? <textarea {...common} /> : <input {...common} />;
|
||||||
|
}
|
||||||
@@ -0,0 +1,272 @@
|
|||||||
|
import { useEffect, useRef, useState } from 'react';
|
||||||
|
import type React from 'react';
|
||||||
|
import { norm360, ownBox, rectFromTopLeft, rectToScreen, toScreen, topLeftOf, type VP } from '../lib/geom';
|
||||||
|
import type { Item, Rect } from '../lib/types';
|
||||||
|
import { LINE_H, measureText } from '../lib/util';
|
||||||
|
import { useEditor } from '../editor';
|
||||||
|
import { tr } from '../i18n';
|
||||||
|
import { MessageSquare } from 'lucide-react';
|
||||||
|
|
||||||
|
type FocusProps = React.HTMLAttributes<HTMLDivElement> & { tabIndex?: number };
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
it: Item;
|
||||||
|
vp: VP;
|
||||||
|
selected: boolean;
|
||||||
|
interactive: boolean;
|
||||||
|
editing: boolean;
|
||||||
|
onDown: (e: React.PointerEvent, it: Item) => void;
|
||||||
|
onHandle: (e: React.PointerEvent, it: Item) => void;
|
||||||
|
onUpdate: (id: string, fn: (it: Item) => Item | null) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Outer screen box plus the inner (rotated) box for items with their own orientation. */
|
||||||
|
function rotated(vp: VP, rect: Rect, rot: number) {
|
||||||
|
const outer = rectToScreen(vp, rect);
|
||||||
|
const ob = ownBox(rect, rot);
|
||||||
|
const w = ob.W * vp.scale;
|
||||||
|
const h = ob.H * vp.scale;
|
||||||
|
const disp = norm360(vp.rotation - rot);
|
||||||
|
const inner: React.CSSProperties = {
|
||||||
|
position: 'absolute',
|
||||||
|
left: (outer.width - w) / 2,
|
||||||
|
top: (outer.height - h) / 2,
|
||||||
|
width: w,
|
||||||
|
height: h,
|
||||||
|
transform: disp ? `rotate(${disp}deg)` : undefined,
|
||||||
|
};
|
||||||
|
return { outer, inner };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ItemEl({ it, vp, selected, interactive, editing, onDown, onHandle, onUpdate }: Props) {
|
||||||
|
const s = vp.scale;
|
||||||
|
const cls = `item k-${it.kind}${selected ? ' sel' : ''}${interactive ? ' live' : ''}`;
|
||||||
|
const down = (e: React.PointerEvent) => interactive && onDown(e, it);
|
||||||
|
const ed = useEditor();
|
||||||
|
const kindName: Record<Item['kind'], string> = {
|
||||||
|
text: tr('ข้อความ', 'Text'), image: tr('รูปภาพ', 'Image'), highlight: tr('ไฮไลต์', 'Highlight'), whiteout: tr('ปิดทับ', 'Whiteout'),
|
||||||
|
redact: tr('ปกปิด', 'Redaction'), rect: tr('สี่เหลี่ยม', 'Rectangle'), ellipse: tr('วงรี', 'Ellipse'), line: tr('เส้น', 'Line'),
|
||||||
|
arrow: tr('ลูกศร', 'Arrow'), ink: tr('ลายเส้น', 'Drawing'), note: tr('โน้ต', 'Note'), field: tr('ช่องฟอร์ม', 'Form field'),
|
||||||
|
};
|
||||||
|
const text = it.kind === 'text' || it.kind === 'note' ? `: ${it.text}` : '';
|
||||||
|
// Keyboard: Tab reaches each item, focus selects it, Enter edits text/notes, arrows move it (App), Delete removes it (App).
|
||||||
|
const fp: FocusProps = interactive
|
||||||
|
? {
|
||||||
|
tabIndex: 0,
|
||||||
|
role: 'button',
|
||||||
|
'aria-label': kindName[it.kind] + text,
|
||||||
|
onFocus: () => ed.selectedId !== it.id && ed.select(it.id),
|
||||||
|
onKeyDown: (e) => {
|
||||||
|
if (e.key === 'Enter' && (it.kind === 'text' || it.kind === 'note')) {
|
||||||
|
e.preventDefault();
|
||||||
|
ed.setEditing(it.id);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
: {};
|
||||||
|
const handle = selected && interactive && 'rect' in it && it.kind !== 'text' && (
|
||||||
|
<div className="handle" onPointerDown={(e) => onHandle(e, it)} />
|
||||||
|
);
|
||||||
|
|
||||||
|
switch (it.kind) {
|
||||||
|
case 'highlight':
|
||||||
|
case 'whiteout':
|
||||||
|
case 'redact':
|
||||||
|
return (
|
||||||
|
<div {...fp} className={cls} style={{ ...rectToScreen(vp, it.rect), background: it.fill ?? undefined, opacity: it.kind === 'highlight' ? it.opacity : 1 }} onPointerDown={down}>
|
||||||
|
{handle}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
case 'rect':
|
||||||
|
case 'ellipse': {
|
||||||
|
const b = rectToScreen(vp, it.rect);
|
||||||
|
const w = it.width * s;
|
||||||
|
return (
|
||||||
|
<div {...fp} className={cls} style={b} onPointerDown={down}>
|
||||||
|
<svg width={b.width} height={b.height} style={{ opacity: it.opacity, overflow: 'visible' }}>
|
||||||
|
{it.kind === 'rect' ? (
|
||||||
|
<rect x={w / 2} y={w / 2} width={Math.max(0, b.width - w)} height={Math.max(0, b.height - w)} fill={it.fill ?? 'none'} stroke={it.stroke} strokeWidth={w} />
|
||||||
|
) : (
|
||||||
|
<ellipse cx={b.width / 2} cy={b.height / 2} rx={Math.max(0, b.width / 2 - w / 2)} ry={Math.max(0, b.height / 2 - w / 2)} fill={it.fill ?? 'none'} stroke={it.stroke} strokeWidth={w} />
|
||||||
|
)}
|
||||||
|
</svg>
|
||||||
|
{handle}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
case 'line':
|
||||||
|
case 'arrow':
|
||||||
|
case 'ink': {
|
||||||
|
const pts = (it.kind === 'ink' ? it.points : [it.a, it.b]).map((p) => toScreen(vp, p));
|
||||||
|
const pad = it.width * s + 10;
|
||||||
|
const x0 = Math.min(...pts.map((p) => p.x)) - pad;
|
||||||
|
const y0 = Math.min(...pts.map((p) => p.y)) - pad;
|
||||||
|
const x1 = Math.max(...pts.map((p) => p.x)) + pad;
|
||||||
|
const y1 = Math.max(...pts.map((p) => p.y)) + pad;
|
||||||
|
const rel = pts.map((p) => ({ x: p.x - x0, y: p.y - y0 }));
|
||||||
|
let head = '';
|
||||||
|
if (it.kind === 'arrow') {
|
||||||
|
const [a, b] = rel;
|
||||||
|
const ang = Math.atan2(b.y - a.y, b.x - a.x);
|
||||||
|
const len = Math.max(8, it.width * 4) * s;
|
||||||
|
const p1 = { x: b.x + len * Math.cos(ang + Math.PI - 0.45), y: b.y + len * Math.sin(ang + Math.PI - 0.45) };
|
||||||
|
const p2 = { x: b.x + len * Math.cos(ang + Math.PI + 0.45), y: b.y + len * Math.sin(ang + Math.PI + 0.45) };
|
||||||
|
head = `M${p1.x},${p1.y} L${b.x},${b.y} L${p2.x},${p2.y}`;
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<div {...fp} className={`${cls} stroke-item`} style={{ left: x0, top: y0, width: x1 - x0, height: y1 - y0 }}>
|
||||||
|
<svg width={x1 - x0} height={y1 - y0} style={{ opacity: it.opacity }}>
|
||||||
|
<g fill="none" stroke={it.stroke} strokeWidth={Math.max(1, it.width * s)} strokeLinecap="round" strokeLinejoin="round">
|
||||||
|
<polyline points={rel.map((p) => `${p.x},${p.y}`).join(' ')} />
|
||||||
|
{head && <path d={head} />}
|
||||||
|
</g>
|
||||||
|
{/* wide transparent stroke = easier to grab */}
|
||||||
|
<polyline className="grab" points={rel.map((p) => `${p.x},${p.y}`).join(' ')} fill="none" stroke="transparent" strokeWidth={Math.max(12, it.width * s + 8)} onPointerDown={down} />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
case 'image': {
|
||||||
|
const { outer, inner } = rotated(vp, it.rect, it.rot);
|
||||||
|
return (
|
||||||
|
<div {...fp} className={cls} style={outer} onPointerDown={down}>
|
||||||
|
<img src={it.dataUrl} style={inner} draggable={false} alt="" />
|
||||||
|
{handle}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
case 'text':
|
||||||
|
return <TextEl {...{ it, vp, cls, down, editing, onUpdate, fp }} />;
|
||||||
|
case 'note':
|
||||||
|
return <NoteEl {...{ it, vp, cls, down, selected, editing, onUpdate, fp }} />;
|
||||||
|
case 'field': {
|
||||||
|
const b = rectToScreen(vp, it.rect);
|
||||||
|
return (
|
||||||
|
<div {...fp} className={`${cls} field-${it.fieldType}`} style={b} onPointerDown={down} title={it.name}>
|
||||||
|
{it.fieldType === 'text' && <span className="field-label">{it.name}</span>}
|
||||||
|
{handle}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type TextP = { it: Extract<Item, { kind: 'text' }>; vp: VP; cls: string; down: (e: React.PointerEvent) => void; editing: boolean; onUpdate: Props['onUpdate']; fp: FocusProps };
|
||||||
|
|
||||||
|
function TextEl({ it, vp, cls, down, editing, onUpdate, fp }: TextP) {
|
||||||
|
const ed = useEditor();
|
||||||
|
const [draft, setDraft] = useState(it.text);
|
||||||
|
const ref = useRef<HTMLTextAreaElement>(null);
|
||||||
|
const draftRef = useRef(it.text);
|
||||||
|
draftRef.current = draft;
|
||||||
|
|
||||||
|
// Commit when editing ends. React does not fire onBlur for a textarea that is removed,
|
||||||
|
// so committing from blur alone would lose the draft.
|
||||||
|
const wasEditing = useRef(false);
|
||||||
|
useEffect(() => {
|
||||||
|
if (editing) {
|
||||||
|
if (!wasEditing.current) {
|
||||||
|
setDraft(it.text);
|
||||||
|
draftRef.current = it.text;
|
||||||
|
}
|
||||||
|
wasEditing.current = true;
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
ref.current?.focus();
|
||||||
|
ref.current?.select();
|
||||||
|
});
|
||||||
|
} else if (wasEditing.current) {
|
||||||
|
wasEditing.current = false;
|
||||||
|
commit(draftRef.current);
|
||||||
|
}
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [editing]);
|
||||||
|
|
||||||
|
// While editing, size the box from the draft so the layout grows as you type.
|
||||||
|
const shownText = editing ? draft : it.text;
|
||||||
|
const m = measureText(shownText || ' ', it.size, it.bold);
|
||||||
|
const rect = editing ? rectFromTopLeft(topLeftOf(it.rect, it.rot), m.w, m.h, it.rot) : it.rect;
|
||||||
|
const { outer, inner } = rotated(vp, rect, it.rot);
|
||||||
|
const font: React.CSSProperties = {
|
||||||
|
fontSize: it.size * vp.scale,
|
||||||
|
lineHeight: LINE_H,
|
||||||
|
fontWeight: it.bold ? 700 : 400,
|
||||||
|
color: it.color,
|
||||||
|
background: it.bg ?? undefined,
|
||||||
|
};
|
||||||
|
|
||||||
|
function commit(raw: string) {
|
||||||
|
const text = raw.replace(/\s+$/, '');
|
||||||
|
if (text && text === it.text) return;
|
||||||
|
onUpdate(it.id, (cur) => {
|
||||||
|
if (cur.kind !== 'text') return cur;
|
||||||
|
if (!text) return null;
|
||||||
|
if (text === cur.text) return cur;
|
||||||
|
const mm = measureText(text, cur.size, cur.bold);
|
||||||
|
return { ...cur, text, rect: rectFromTopLeft(topLeftOf(cur.rect, cur.rot), mm.w, mm.h, cur.rot) };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div {...(editing ? {} : fp)} className={`${cls}${editing ? ' editing' : ''}`} style={outer} onPointerDown={editing ? (e) => e.stopPropagation() : down}>
|
||||||
|
{editing ? (
|
||||||
|
<textarea
|
||||||
|
ref={ref}
|
||||||
|
className="text-edit"
|
||||||
|
style={{ ...inner, ...font }}
|
||||||
|
value={draft}
|
||||||
|
spellCheck={false}
|
||||||
|
onChange={(e) => setDraft(e.target.value)}
|
||||||
|
onBlur={() => ed.editingId === it.id && ed.setEditing(null)}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
if (e.key === 'Escape') (e.target as HTMLTextAreaElement).blur();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div className="text-view" style={{ ...inner, ...font }}>
|
||||||
|
{it.text}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type NoteP = { it: Extract<Item, { kind: 'note' }>; vp: VP; cls: string; down: (e: React.PointerEvent) => void; selected: boolean; editing: boolean; onUpdate: Props['onUpdate']; fp: FocusProps };
|
||||||
|
|
||||||
|
function NoteEl({ it, vp, cls, down, selected, editing, onUpdate, fp }: NoteP) {
|
||||||
|
const p = toScreen(vp, it.at);
|
||||||
|
const [draft, setDraft] = useState(it.text);
|
||||||
|
const draftRef = useRef(it.text);
|
||||||
|
draftRef.current = draft;
|
||||||
|
const open = selected || editing;
|
||||||
|
const wasOpen = useRef(false);
|
||||||
|
useEffect(() => setDraft(it.text), [it.text]);
|
||||||
|
useEffect(() => {
|
||||||
|
if (open) wasOpen.current = true;
|
||||||
|
else if (wasOpen.current) {
|
||||||
|
wasOpen.current = false;
|
||||||
|
const text = draftRef.current;
|
||||||
|
if (text !== it.text) onUpdate(it.id, (c) => (c.kind === 'note' ? { ...c, text } : c));
|
||||||
|
}
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [open]);
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div {...fp} className={`${cls} note-icon`} style={{ left: p.x, top: p.y, background: it.color }} onPointerDown={down} title={it.text}>
|
||||||
|
<MessageSquare size={13} aria-hidden />
|
||||||
|
</div>
|
||||||
|
{open && (
|
||||||
|
<div className="note-pop" style={{ left: p.x + 28, top: p.y }} onPointerDown={(e) => e.stopPropagation()}>
|
||||||
|
<textarea
|
||||||
|
autoFocus={editing}
|
||||||
|
value={draft}
|
||||||
|
placeholder={tr('พิมพ์ความคิดเห็น…', 'Type a comment…')}
|
||||||
|
onChange={(e) => setDraft(e.target.value)}
|
||||||
|
onBlur={() => draft !== it.text && onUpdate(it.id, (c) => (c.kind === 'note' ? { ...c, text: draft } : c))}
|
||||||
|
onKeyDown={(e) => e.stopPropagation()}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
/** Loma brand app icon (rounded navy square, PDF page + pen). Source art: public/logo/พรีเซนเทชันแบรนด์ Loma PDF Editor.png */
|
||||||
|
export function LomaMark({ size = 24 }: { size?: number }) {
|
||||||
|
const src = size > 48 ? '/logo/loma-icon-192.png' : '/logo/loma-icon-64.png';
|
||||||
|
return <img className="loma-mark" src={src} width={size} height={size} alt="" aria-hidden="true" draggable={false} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Full horizontal lockup ("Loma / PDF Editor"). Background is knocked out for light surfaces only. */
|
||||||
|
export function LomaLockup({ height = 64 }: { height?: number }) {
|
||||||
|
return (
|
||||||
|
<img className="loma-lockup" src="/logo/loma-lockup.png" height={height}
|
||||||
|
style={{ height, width: 'auto' }} alt="Loma PDF Editor" draggable={false} />
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,407 @@
|
|||||||
|
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||||
|
import type React from 'react';
|
||||||
|
import { useEditor } from '../editor';
|
||||||
|
import { pdfjs, renderPage, type PDFPageProxy } from '../lib/pdfjs';
|
||||||
|
import {
|
||||||
|
axes, padRect, rectFromTopLeft, rectToScreen, screenToRect, toPdf, translateItem, type Box, type VP,
|
||||||
|
} from '../lib/geom';
|
||||||
|
import { getImageBoxes, getTextLines, sampleColors, type ImageBox, type TextLine } from '../lib/analyze';
|
||||||
|
import type { Item, Tool } from '../lib/types';
|
||||||
|
import { BASELINE, measureText, uid } from '../lib/util';
|
||||||
|
import { ItemEl } from './ItemEl';
|
||||||
|
import { FormWidget, type WidgetData } from './FormWidget';
|
||||||
|
import { tr } from '../i18n';
|
||||||
|
|
||||||
|
type P = { x: number; y: number };
|
||||||
|
type Drag =
|
||||||
|
| { mode: 'create'; start: P; cur: P; pts: P[] }
|
||||||
|
| { mode: 'move'; id: string; start: P; cur: P }
|
||||||
|
| { mode: 'resize'; id: string; start: P; cur: P; box: Box; aspect: number | null };
|
||||||
|
|
||||||
|
const DRAG_TOOLS = new Set<Tool>(['highlight', 'rect', 'ellipse', 'line', 'arrow', 'whiteout', 'redact', 'fieldText', 'fieldCheck', 'pen']);
|
||||||
|
const PLACE_TOOLS = new Set<Tool>(['image', 'sign', 'stamp']);
|
||||||
|
|
||||||
|
export function PageView({ index, pageId, size }: { index: number; pageId: string; size: { w: number; h: number } }) {
|
||||||
|
const ed = useEditor();
|
||||||
|
const { scale, tool, opts } = ed;
|
||||||
|
const wrapRef = useRef<HTMLDivElement>(null);
|
||||||
|
const canvasRef = useRef<HTMLCanvasElement>(null);
|
||||||
|
const overlayRef = useRef<HTMLDivElement>(null);
|
||||||
|
const [visible, setVisible] = useState(false);
|
||||||
|
const [page, setPage] = useState<PDFPageProxy | null>(null);
|
||||||
|
const [lines, setLines] = useState<TextLine[] | null>(null);
|
||||||
|
const [imgs, setImgs] = useState<ImageBox[] | null>(null);
|
||||||
|
const [widgets, setWidgets] = useState<WidgetData[]>([]);
|
||||||
|
const [drag, setDrag] = useState<Drag | null>(null);
|
||||||
|
const dragRef = useRef<Drag | null>(null);
|
||||||
|
const lastDown = useRef({ id: '', t: 0 });
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const el = wrapRef.current!;
|
||||||
|
const io = new IntersectionObserver(([e]) => setVisible(e.isIntersecting), { rootMargin: '800px 0px' });
|
||||||
|
io.observe(el);
|
||||||
|
return () => io.disconnect();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const pdf = ed.loaded.pdf;
|
||||||
|
useEffect(() => {
|
||||||
|
if (!visible) return;
|
||||||
|
let alive = true;
|
||||||
|
pdf.getPage(index + 1).then((p) => alive && setPage(p), () => {});
|
||||||
|
return () => {
|
||||||
|
alive = false;
|
||||||
|
};
|
||||||
|
}, [visible, pdf, index]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setLines(null);
|
||||||
|
setImgs(null);
|
||||||
|
setWidgets([]);
|
||||||
|
if (!page) return;
|
||||||
|
let alive = true;
|
||||||
|
page.getAnnotations().then(
|
||||||
|
(a) => alive && setWidgets((a as WidgetData[]).filter((x) => x.subtype === 'Widget' && x.fieldName && !x.pushButton && !x.hidden)),
|
||||||
|
() => {},
|
||||||
|
);
|
||||||
|
return () => {
|
||||||
|
alive = false;
|
||||||
|
};
|
||||||
|
}, [page]);
|
||||||
|
|
||||||
|
const vp = useMemo(() => (page ? (page.getViewport({ scale }) as unknown as VP) : null), [page, scale]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const c = canvasRef.current;
|
||||||
|
if (!page || !vp || !c) return;
|
||||||
|
const dpr = window.devicePixelRatio || 1;
|
||||||
|
c.width = Math.floor(vp.width * dpr);
|
||||||
|
c.height = Math.floor(vp.height * dpr);
|
||||||
|
const task = page.render({
|
||||||
|
canvasContext: c.getContext('2d')!,
|
||||||
|
viewport: page.getViewport({ scale }),
|
||||||
|
transform: dpr !== 1 ? [dpr, 0, 0, dpr, 0, 0] : undefined,
|
||||||
|
annotationMode: pdfjs.AnnotationMode.ENABLE_FORMS,
|
||||||
|
});
|
||||||
|
task.promise.catch(() => {});
|
||||||
|
return () => task.cancel();
|
||||||
|
}, [page, vp, scale]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (tool !== 'edit' || !page || lines) return;
|
||||||
|
let alive = true;
|
||||||
|
getTextLines(page).then((l) => alive && setLines(l), () => alive && setLines([]));
|
||||||
|
getImageBoxes(page).then((b) => alive && setImgs(b), () => alive && setImgs([]));
|
||||||
|
return () => {
|
||||||
|
alive = false;
|
||||||
|
};
|
||||||
|
}, [tool, page, lines]);
|
||||||
|
|
||||||
|
const items = useMemo(() => ed.doc.items.filter((i) => i.pageId === pageId), [ed.doc.items, pageId]);
|
||||||
|
const covered = useMemo(() => new Set(items.flatMap((i) => (i.kind === 'whiteout' && i.src ? [i.src] : []))), [items]);
|
||||||
|
|
||||||
|
const addItems = (...its: Item[]) => ed.commit((d) => ({ ...d, items: [...d.items, ...its] }));
|
||||||
|
const updateItem = (id: string, fn: (it: Item) => Item | null) =>
|
||||||
|
ed.commit((d) => ({
|
||||||
|
...d,
|
||||||
|
items: d.items.flatMap((it) => {
|
||||||
|
if (it.id !== id) return [it];
|
||||||
|
const r = fn(it);
|
||||||
|
return r ? [r] : [];
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const pt = (e: React.PointerEvent): P => {
|
||||||
|
const r = overlayRef.current!.getBoundingClientRect();
|
||||||
|
return { x: e.clientX - r.left, y: e.clientY - r.top };
|
||||||
|
};
|
||||||
|
const startDrag = (e: React.PointerEvent, d: Drag) => {
|
||||||
|
overlayRef.current!.setPointerCapture(e.pointerId);
|
||||||
|
dragRef.current = d;
|
||||||
|
setDrag(d);
|
||||||
|
};
|
||||||
|
|
||||||
|
function onDown(e: React.PointerEvent) {
|
||||||
|
if (e.button !== 0 || !vp) return;
|
||||||
|
const p = pt(e);
|
||||||
|
ed.setHit(null);
|
||||||
|
if (tool === 'select' || tool === 'edit') {
|
||||||
|
ed.select(null);
|
||||||
|
ed.setEditing(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (DRAG_TOOLS.has(tool)) {
|
||||||
|
e.preventDefault();
|
||||||
|
startDrag(e, { mode: 'create', start: p, cur: p, pts: [p] });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const id = uid();
|
||||||
|
// setTool() clears selection/editing, so switch tools before selecting the new item.
|
||||||
|
if (tool === 'text') {
|
||||||
|
e.preventDefault(); // keep focus for the textarea that is about to appear
|
||||||
|
const tl = toPdf(vp, p.x, p.y - opts.size * scale * 0.65);
|
||||||
|
const m = measureText(' ', opts.size, opts.bold);
|
||||||
|
addItems({ id, pageId, kind: 'text', rect: rectFromTopLeft(tl, m.w, m.h, vp.rotation), rot: vp.rotation, text: '', size: opts.size, color: opts.color, bold: opts.bold, bg: null });
|
||||||
|
ed.setTool('select');
|
||||||
|
ed.select(id);
|
||||||
|
ed.setEditing(id);
|
||||||
|
} else if (tool === 'note') {
|
||||||
|
e.preventDefault();
|
||||||
|
addItems({ id, pageId, kind: 'note', at: toPdf(vp, p.x - 11, p.y - 11), text: '', color: '#f5b800' });
|
||||||
|
ed.setTool('select');
|
||||||
|
ed.select(id);
|
||||||
|
ed.setEditing(id);
|
||||||
|
} else if (PLACE_TOOLS.has(tool)) {
|
||||||
|
const pend = opts.pending;
|
||||||
|
if (!pend) {
|
||||||
|
ed.toast(tool === 'sign' ? tr('เลือกหรือสร้างลายเซ็นก่อน', 'Choose or create a signature first') : tr('เลือกรูป/ตราประทับก่อน', 'Choose an image or stamp first'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const tl = toPdf(vp, p.x - (pend.w * scale) / 2, p.y - (pend.h * scale) / 2);
|
||||||
|
addItems({ id, pageId, kind: 'image', rect: rectFromTopLeft(tl, pend.w, pend.h, vp.rotation), rot: vp.rotation, dataUrl: pend.dataUrl });
|
||||||
|
ed.select(id);
|
||||||
|
ed.setTool('select');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function onMove(e: React.PointerEvent) {
|
||||||
|
const d = dragRef.current;
|
||||||
|
if (!d) return;
|
||||||
|
const p = pt(e);
|
||||||
|
const next: Drag = { ...d, cur: p };
|
||||||
|
if (next.mode === 'create' && tool === 'pen') {
|
||||||
|
const last = next.pts[next.pts.length - 1];
|
||||||
|
if (Math.hypot(p.x - last.x, p.y - last.y) > 1.5) next.pts = [...next.pts, p];
|
||||||
|
}
|
||||||
|
dragRef.current = next;
|
||||||
|
setDrag(next);
|
||||||
|
}
|
||||||
|
|
||||||
|
function onUp() {
|
||||||
|
const d = dragRef.current;
|
||||||
|
dragRef.current = null;
|
||||||
|
setDrag(null);
|
||||||
|
if (!d || !vp) return;
|
||||||
|
const { start: a, cur: b } = d;
|
||||||
|
const dist = Math.hypot(b.x - a.x, b.y - a.y);
|
||||||
|
if (d.mode === 'move') {
|
||||||
|
if (dist < 2) return;
|
||||||
|
const pa = toPdf(vp, a.x, a.y);
|
||||||
|
const pb = toPdf(vp, b.x, b.y);
|
||||||
|
updateItem(d.id, (it) => translateItem(it, { x: pb.x - pa.x, y: pb.y - pa.y }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (d.mode === 'resize') {
|
||||||
|
updateItem(d.id, (it) => ('rect' in it ? { ...it, rect: resized(d, vp) } : it));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const id = uid();
|
||||||
|
const base = { id, pageId };
|
||||||
|
const sw = { stroke: opts.color, width: opts.width, opacity: opts.opacity };
|
||||||
|
switch (tool) {
|
||||||
|
case 'pen':
|
||||||
|
if (d.pts.length > 1) addItems({ ...base, kind: 'ink', points: d.pts.map((q) => toPdf(vp, q.x, q.y)), ...sw });
|
||||||
|
return;
|
||||||
|
case 'line':
|
||||||
|
case 'arrow':
|
||||||
|
if (dist > 4) addItems({ ...base, kind: tool, a: toPdf(vp, a.x, a.y), b: toPdf(vp, b.x, b.y), ...sw });
|
||||||
|
return;
|
||||||
|
case 'fieldText':
|
||||||
|
case 'fieldCheck': {
|
||||||
|
const isText = tool === 'fieldText';
|
||||||
|
const rect = dist > 6 ? screenToRect(vp, a.x, a.y, b.x, b.y) : screenToRect(vp, a.x, a.y, a.x + (isText ? 160 : 14) * scale, a.y + (isText ? 22 : 14) * scale);
|
||||||
|
const n = ed.doc.items.filter((i) => i.kind === 'field').length + 1;
|
||||||
|
addItems({ ...base, kind: 'field', rect, fieldType: isText ? 'text' : 'checkbox', name: `${isText ? 'text' : 'check'}_${n}` });
|
||||||
|
ed.select(id);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (dist < 4) return;
|
||||||
|
const rect = screenToRect(vp, a.x, a.y, b.x, b.y);
|
||||||
|
if (tool === 'highlight') addItems({ ...base, kind: 'highlight', rect, stroke: '', fill: opts.highlight, width: 0, opacity: 0.45 });
|
||||||
|
else if (tool === 'rect' || tool === 'ellipse') addItems({ ...base, kind: tool, rect, fill: opts.fill, ...sw });
|
||||||
|
else if (tool === 'whiteout') addItems({ ...base, kind: 'whiteout', rect, stroke: '', fill: '#ffffff', width: 0, opacity: 1 });
|
||||||
|
else if (tool === 'redact') addItems({ ...base, kind: 'redact', rect, stroke: '', fill: '#000000', width: 0, opacity: 1 });
|
||||||
|
}
|
||||||
|
|
||||||
|
function onItemDown(e: React.PointerEvent, it: Item) {
|
||||||
|
if (e.button !== 0) return;
|
||||||
|
e.stopPropagation();
|
||||||
|
if (ed.editingId === it.id) return;
|
||||||
|
if (ed.editingId) ed.setEditing(null);
|
||||||
|
const now = performance.now();
|
||||||
|
const isDouble = lastDown.current.id === it.id && now - lastDown.current.t < 400;
|
||||||
|
lastDown.current = { id: it.id, t: now };
|
||||||
|
ed.select(it.id);
|
||||||
|
if (isDouble && (it.kind === 'text' || it.kind === 'note')) {
|
||||||
|
ed.setEditing(it.id);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
startDrag(e, { mode: 'move', id: it.id, start: pt(e), cur: pt(e) });
|
||||||
|
}
|
||||||
|
|
||||||
|
function onHandleDown(e: React.PointerEvent, it: Item) {
|
||||||
|
if (!vp || !('rect' in it)) return;
|
||||||
|
e.stopPropagation();
|
||||||
|
const box = rectToScreen(vp, it.rect);
|
||||||
|
const aspect = it.kind === 'image' || it.kind === 'field' ? box.height / box.width : null;
|
||||||
|
startDrag(e, { mode: 'resize', id: it.id, start: pt(e), cur: pt(e), box, aspect: e.shiftKey ? null : aspect });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Turn an original text line into an editable text item laid over a background-colored patch. */
|
||||||
|
function editLine(l: TextLine) {
|
||||||
|
if (!vp) return;
|
||||||
|
const c = canvasRef.current!;
|
||||||
|
const dpr = c.width / vp.width;
|
||||||
|
const b = rectToScreen(vp, l.rect);
|
||||||
|
const { bg, fg } = sampleColors(c.getContext('2d', { willReadFrequently: true })!, b.left * dpr, b.top * dpr, b.width * dpr, b.height * dpr);
|
||||||
|
const { right, up } = axes(l.rot);
|
||||||
|
const tT = l.t + BASELINE * l.size;
|
||||||
|
const tl = { x: right.x * l.s0 + up.x * tT, y: right.y * l.s0 + up.y * tT };
|
||||||
|
const size = Math.round(l.size * 10) / 10;
|
||||||
|
const m = measureText(l.text, size, l.bold);
|
||||||
|
const id = uid();
|
||||||
|
addItems(
|
||||||
|
{ id: uid(), pageId, kind: 'whiteout', rect: padRect(l.rect, 0.6), stroke: '', fill: bg, width: 0, opacity: 1, src: `t:${l.key}` },
|
||||||
|
{ id, pageId, kind: 'text', rect: rectFromTopLeft(tl, m.w, m.h, l.rot), rot: l.rot, text: l.text, size, color: fg, bold: l.bold, bg: null },
|
||||||
|
);
|
||||||
|
ed.select(id);
|
||||||
|
ed.setEditing(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Lift an original image off the page so it can be moved, resized, replaced or deleted. */
|
||||||
|
async function editImage(box: ImageBox) {
|
||||||
|
if (!page || !vp) return;
|
||||||
|
await ed.run(tr('กำลังเตรียมรูป…', 'Preparing image…'), async () => {
|
||||||
|
const k = Math.min(4, 3000 / Math.max(vp.width / scale, vp.height / scale));
|
||||||
|
const hi = await renderPage(page, k, false);
|
||||||
|
const hvp = page.getViewport({ scale: k }) as unknown as VP;
|
||||||
|
const b = rectToScreen(hvp, box.rect);
|
||||||
|
const x0 = Math.max(0, Math.floor(b.left));
|
||||||
|
const y0 = Math.max(0, Math.floor(b.top));
|
||||||
|
const x1 = Math.min(hi.width, Math.ceil(b.left + b.width));
|
||||||
|
const y1 = Math.min(hi.height, Math.ceil(b.top + b.height));
|
||||||
|
if (x1 - x0 < 2 || y1 - y0 < 2) return;
|
||||||
|
const crop = document.createElement('canvas');
|
||||||
|
crop.width = x1 - x0;
|
||||||
|
crop.height = y1 - y0;
|
||||||
|
crop.getContext('2d')!.drawImage(hi, x0, y0, crop.width, crop.height, 0, 0, crop.width, crop.height);
|
||||||
|
const rect = screenToRect(hvp, x0, y0, x1, y1);
|
||||||
|
const id = uid();
|
||||||
|
addItems(
|
||||||
|
{ id: uid(), pageId, kind: 'whiteout', rect, stroke: '', fill: '#ffffff', width: 0, opacity: 1, src: `i:${box.key}` },
|
||||||
|
{ id, pageId, kind: 'image', rect, rot: vp.rotation, dataUrl: crop.toDataURL('image/png') },
|
||||||
|
);
|
||||||
|
ed.setTool('select');
|
||||||
|
ed.select(id);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const shown = useMemo(() => {
|
||||||
|
if (!drag || drag.mode === 'create' || !vp) return items;
|
||||||
|
return items.map((it) => {
|
||||||
|
if (it.id !== drag.id) return it;
|
||||||
|
if (drag.mode === 'move') {
|
||||||
|
const pa = toPdf(vp, drag.start.x, drag.start.y);
|
||||||
|
const pb = toPdf(vp, drag.cur.x, drag.cur.y);
|
||||||
|
return translateItem(it, { x: pb.x - pa.x, y: pb.y - pa.y });
|
||||||
|
}
|
||||||
|
return 'rect' in it ? { ...it, rect: resized(drag, vp) } : it;
|
||||||
|
});
|
||||||
|
}, [items, drag, vp]);
|
||||||
|
|
||||||
|
const interactive = tool === 'select' || tool === 'edit';
|
||||||
|
const W = size.w * scale;
|
||||||
|
const H = size.h * scale;
|
||||||
|
const hit = ed.hit?.pageId === pageId && vp ? rectToScreen(vp, ed.hit.rect) : null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div ref={wrapRef} className="page-wrap" data-index={index} style={{ width: W, height: H }} role="region" aria-label={tr(`หน้า ${index + 1}`, `Page ${index + 1}`)}>
|
||||||
|
<canvas ref={canvasRef} className="page-canvas" style={{ width: W, height: H }} />
|
||||||
|
{!page && <div className="page-loading">{tr('หน้า', 'Page')} {index + 1}</div>}
|
||||||
|
{vp && (
|
||||||
|
<div
|
||||||
|
ref={overlayRef}
|
||||||
|
className={`overlay tool-${tool}`}
|
||||||
|
onPointerDown={onDown}
|
||||||
|
onPointerMove={onMove}
|
||||||
|
onPointerUp={onUp}
|
||||||
|
onPointerCancel={onUp}
|
||||||
|
>
|
||||||
|
{shown.map((it) => (
|
||||||
|
<ItemEl
|
||||||
|
key={it.id}
|
||||||
|
it={it}
|
||||||
|
vp={vp}
|
||||||
|
selected={ed.selectedId === it.id}
|
||||||
|
interactive={interactive}
|
||||||
|
editing={ed.editingId === it.id}
|
||||||
|
onDown={onItemDown}
|
||||||
|
onHandle={onHandleDown}
|
||||||
|
onUpdate={updateItem}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
{tool === 'edit' &&
|
||||||
|
lines?.filter((l) => !covered.has(`t:${l.key}`)).map((l) => {
|
||||||
|
const b = rectToScreen(vp, l.rect);
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={`t${l.key}`}
|
||||||
|
className="hot hot-text"
|
||||||
|
aria-label={tr(`แก้ข้อความ: ${l.text}`, `Edit text: ${l.text}`)}
|
||||||
|
title={tr('คลิกเพื่อแก้ข้อความ', 'Click to edit text')}
|
||||||
|
style={b}
|
||||||
|
onPointerDown={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
e.preventDefault(); // keep focus for the editor that opens
|
||||||
|
editLine(l);
|
||||||
|
}}
|
||||||
|
onClick={(e) => e.detail === 0 && editLine(l)} // keyboard (Enter/Space)
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
{tool === 'edit' &&
|
||||||
|
imgs?.filter((m) => !covered.has(`i:${m.key}`)).map((m) => (
|
||||||
|
<button
|
||||||
|
key={`i${m.key}`}
|
||||||
|
className="hot hot-img"
|
||||||
|
aria-label={tr(`แก้ไขรูปที่ ${+m.key + 1}`, `Edit image ${+m.key + 1}`)}
|
||||||
|
title={tr('คลิกเพื่อแก้ไขรูป (ย้าย/ย่อขยาย/ลบ/แทนที่)', 'Click to edit image (move/resize/delete/replace)')}
|
||||||
|
style={rectToScreen(vp, m.rect)}
|
||||||
|
onPointerDown={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
editImage(m);
|
||||||
|
}}
|
||||||
|
onClick={(e) => e.detail === 0 && editImage(m)}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
{widgets.map((w) => (
|
||||||
|
<FormWidget key={w.id} w={w} vp={vp} active={tool === 'select'} />
|
||||||
|
))}
|
||||||
|
{drag?.mode === 'create' && <CreatePreview drag={drag} tool={tool} color={tool === 'highlight' ? opts.highlight : opts.color} width={opts.width * scale} />}
|
||||||
|
{hit && <div className="search-hit" style={hit} />}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function resized(d: Extract<Drag, { mode: 'resize' }>, vp: VP) {
|
||||||
|
const w = Math.max(6, d.box.width + d.cur.x - d.start.x);
|
||||||
|
const h = d.aspect ? w * d.aspect : Math.max(6, d.box.height + d.cur.y - d.start.y);
|
||||||
|
return screenToRect(vp, d.box.left, d.box.top, d.box.left + w, d.box.top + h);
|
||||||
|
}
|
||||||
|
|
||||||
|
function CreatePreview({ drag, tool, color, width }: { drag: Extract<Drag, { mode: 'create' }>; tool: Tool; color: string; width: number }) {
|
||||||
|
const { start: a, cur: b } = drag;
|
||||||
|
const box = { left: Math.min(a.x, b.x), top: Math.min(a.y, b.y), width: Math.abs(a.x - b.x), height: Math.abs(a.y - b.y) };
|
||||||
|
if (tool === 'pen' || tool === 'line' || tool === 'arrow') {
|
||||||
|
const pts = tool === 'pen' ? drag.pts : [a, b];
|
||||||
|
return (
|
||||||
|
<svg className="preview-svg">
|
||||||
|
<polyline points={pts.map((p) => `${p.x},${p.y}`).join(' ')} fill="none" stroke={color} strokeWidth={Math.max(1, width)} strokeLinecap="round" strokeLinejoin="round" />
|
||||||
|
</svg>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const cls = tool === 'highlight' ? 'pv-highlight' : tool === 'redact' ? 'pv-redact' : tool === 'whiteout' ? 'pv-whiteout' : 'pv-box';
|
||||||
|
return <div className={`preview ${cls} ${tool === 'ellipse' ? 'round' : ''}`} style={{ ...box, background: tool === 'highlight' ? color : undefined }} />;
|
||||||
|
}
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
import type React from 'react';
|
||||||
|
import type { ReactNode } from 'react';
|
||||||
|
import {
|
||||||
|
ArrowUpRight, Circle, Eraser, FileDown, FilePlus2, Files, Highlighter, ImageUp, RotateCcw, RotateCw, Trash2, ImagePlus, MessageSquare, MousePointer2, PenLine,
|
||||||
|
PenTool, Slash, Square, SquareCheck, Stamp, TextCursorInput, Type, Pencil, EyeOff, TextSelect,
|
||||||
|
} from 'lucide-react';
|
||||||
|
import { useEditor } from '../editor';
|
||||||
|
import type { Tab, Tool } from '../lib/types';
|
||||||
|
import { imageFileToPending, pickFiles } from '../lib/util';
|
||||||
|
import { tr } from '../i18n';
|
||||||
|
import { usePageOps } from './usePageOps';
|
||||||
|
|
||||||
|
const tabs = (): { id: Tab; label: string }[] => [
|
||||||
|
{ id: 'edit', label: tr('แก้ไข PDF', 'Edit PDF') },
|
||||||
|
{ id: 'comment', label: tr('คอมเมนต์', 'Comment') },
|
||||||
|
{ id: 'sign', label: tr('ลงนาม', 'Sign') },
|
||||||
|
{ id: 'forms', label: tr('ฟอร์ม', 'Forms') },
|
||||||
|
{ id: 'pages', label: tr('จัดการหน้า', 'Pages') },
|
||||||
|
{ id: 'redact', label: tr('ปกปิดข้อมูล', 'Redact') },
|
||||||
|
{ id: 'ocr', label: 'OCR' },
|
||||||
|
{ id: 'convert', label: tr('แปลงไฟล์', 'Convert') },
|
||||||
|
{ id: 'search', label: tr('ค้นหา', 'Search') },
|
||||||
|
];
|
||||||
|
|
||||||
|
type ToolDef = { tool: Tool; label: string; icon: ReactNode; hint?: string; desc?: string };
|
||||||
|
const I = 18;
|
||||||
|
const select = (): ToolDef => ({ tool: 'select', label: tr('เลือก', 'Select'), icon: <MousePointer2 size={I} />, hint: 'V' });
|
||||||
|
|
||||||
|
const toolsFor = (): Partial<Record<Tab, ToolDef[]>> => ({
|
||||||
|
edit: [
|
||||||
|
select(),
|
||||||
|
{ tool: 'edit', label: tr('แก้ข้อความ/รูปเดิม', 'Edit text/images'), icon: <TextSelect size={I} />, hint: 'E' },
|
||||||
|
{ tool: 'text', label: tr('เพิ่มข้อความ', 'Add text'), icon: <Type size={I} />, hint: 'T' },
|
||||||
|
{ tool: 'image', label: tr('เพิ่มรูป', 'Add image'), icon: <ImagePlus size={I} /> },
|
||||||
|
{ tool: 'whiteout', label: tr('ปิดทับ (Whiteout)', 'Whiteout'), icon: <Eraser size={I} />, desc: tr('ระบายสีพื้นทับส่วนที่ไม่ต้องการ', 'Paint over an area with the background colour') },
|
||||||
|
],
|
||||||
|
comment: [
|
||||||
|
select(),
|
||||||
|
{ tool: 'highlight', label: tr('ไฮไลต์', 'Highlight'), icon: <Highlighter size={I} />, hint: 'H' },
|
||||||
|
{ tool: 'pen', label: tr('ปากกา', 'Pen'), icon: <Pencil size={I} />, hint: 'P' },
|
||||||
|
{ tool: 'rect', label: tr('สี่เหลี่ยม', 'Rectangle'), icon: <Square size={I} /> },
|
||||||
|
{ tool: 'ellipse', label: tr('วงรี', 'Ellipse'), icon: <Circle size={I} /> },
|
||||||
|
{ tool: 'line', label: tr('เส้น', 'Line'), icon: <Slash size={I} /> },
|
||||||
|
{ tool: 'arrow', label: tr('ลูกศร', 'Arrow'), icon: <ArrowUpRight size={I} /> },
|
||||||
|
{ tool: 'text', label: tr('กล่องข้อความ', 'Text box'), icon: <Type size={I} /> },
|
||||||
|
{ tool: 'note', label: tr('โน้ต', 'Note'), icon: <MessageSquare size={I} />, hint: 'N' },
|
||||||
|
{ tool: 'stamp', label: tr('ตราประทับ', 'Stamp'), icon: <Stamp size={I} /> },
|
||||||
|
],
|
||||||
|
sign: [
|
||||||
|
select(),
|
||||||
|
{ tool: 'sign', label: tr('วางลายเซ็น', 'Place signature'), icon: <PenTool size={I} /> },
|
||||||
|
{ tool: 'text', label: tr('เพิ่มข้อความ', 'Add text'), icon: <Type size={I} /> },
|
||||||
|
],
|
||||||
|
forms: [
|
||||||
|
select(),
|
||||||
|
{ tool: 'fieldText', label: tr('สร้างช่องข้อความ', 'Add text field'), icon: <TextCursorInput size={I} /> },
|
||||||
|
{ tool: 'fieldCheck', label: tr('สร้าง Checkbox', 'Add checkbox'), icon: <SquareCheck size={I} /> },
|
||||||
|
],
|
||||||
|
redact: [select(), { tool: 'redact', label: tr('ทำเครื่องหมายปกปิด', 'Mark for redaction'), icon: <EyeOff size={I} /> }],
|
||||||
|
});
|
||||||
|
|
||||||
|
/** What each tab without drawing tools does, shown in place of tools. */
|
||||||
|
const tabHint = (t: Tab) =>
|
||||||
|
({
|
||||||
|
ocr: tr('ทำให้ PDF ที่สแกนมาค้นหาและคัดลอกข้อความได้ — ตั้งค่าในแผงด้านขวา', 'Make scanned PDFs searchable and copyable — settings are in the right panel'),
|
||||||
|
convert: tr('บันทึกเป็น Word, Excel, รูป หรือข้อความ — เลือกรูปแบบในแผงด้านขวา', 'Save as Word, Excel, images or text — pick a format in the right panel'),
|
||||||
|
search: tr('พิมพ์คำในแผงด้านขวา แล้วคลิกผลลัพธ์เพื่อไปที่หน้านั้น', 'Type a term in the right panel, then click a result to jump to it'),
|
||||||
|
})[t as 'ocr' | 'convert' | 'search'] ?? '';
|
||||||
|
|
||||||
|
export function Ribbon() {
|
||||||
|
const ed = useEditor();
|
||||||
|
const tools = toolsFor()[ed.tab] ?? [];
|
||||||
|
const list = tabs();
|
||||||
|
|
||||||
|
async function choose(t: ToolDef) {
|
||||||
|
if (t.tool === 'image') {
|
||||||
|
const [f] = await pickFiles('image/*');
|
||||||
|
if (!f) return;
|
||||||
|
ed.setOpts({ pending: await imageFileToPending(f) });
|
||||||
|
}
|
||||||
|
if (t.tool === 'sign' && (!ed.opts.pending || ed.tool !== 'sign')) {
|
||||||
|
ed.setOpts({ pending: null });
|
||||||
|
ed.openSignature();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (t.tool === 'stamp') ed.setOpts({ pending: null });
|
||||||
|
ed.setTool(t.tool);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Arrow keys move between tabs (WAI-ARIA tabs pattern).
|
||||||
|
const onTabKey = (e: React.KeyboardEvent, i: number) => {
|
||||||
|
const k = { ArrowRight: 1, ArrowLeft: -1, Home: -i, End: list.length - 1 - i }[e.key];
|
||||||
|
if (k === undefined) return;
|
||||||
|
e.preventDefault();
|
||||||
|
const next = (i + k + list.length) % list.length;
|
||||||
|
ed.setTab(list[next].id);
|
||||||
|
(e.currentTarget.parentElement!.children[next] as HTMLElement).focus();
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="ribbon">
|
||||||
|
<nav className="tabs" role="tablist" aria-label={tr('หมวดเครื่องมือ', 'Tool groups')}>
|
||||||
|
{list.map((t, i) => (
|
||||||
|
<button
|
||||||
|
key={t.id}
|
||||||
|
role="tab"
|
||||||
|
id={`tab-${t.id}`}
|
||||||
|
aria-selected={ed.tab === t.id}
|
||||||
|
tabIndex={ed.tab === t.id ? 0 : -1}
|
||||||
|
className={ed.tab === t.id ? 'on' : ''}
|
||||||
|
onClick={() => ed.setTab(t.id)}
|
||||||
|
onKeyDown={(e) => onTabKey(e, i)}
|
||||||
|
>
|
||||||
|
{t.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</nav>
|
||||||
|
<div className="tools" role="toolbar" aria-labelledby={`tab-${ed.tab}`}>
|
||||||
|
{tools.map((t) => (
|
||||||
|
<button
|
||||||
|
key={t.tool + t.label}
|
||||||
|
className={`tool${ed.tool === t.tool ? ' on' : ''}`}
|
||||||
|
aria-pressed={ed.tool === t.tool}
|
||||||
|
onClick={() => choose(t)}
|
||||||
|
title={[t.desc, t.hint && `${tr('ปุ่มลัด', 'Shortcut')}: ${t.hint}`].filter(Boolean).join(' · ') || t.label}
|
||||||
|
>
|
||||||
|
{t.icon}
|
||||||
|
<span>{t.label}</span>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
{ed.tab === 'sign' && (
|
||||||
|
<button className="tool" onClick={() => ed.openSignature()}>
|
||||||
|
<PenLine size={I} />
|
||||||
|
<span>{tr('สร้างลายเซ็นใหม่', 'New signature')}</span>
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{ed.tab === 'pages' && <PageActions />}
|
||||||
|
{!tools.length && ed.tab !== 'pages' && <span className="tools-hint">{tabHint(ed.tab)}</span>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function PageActions() {
|
||||||
|
const ops = usePageOps();
|
||||||
|
const n = ops.idxs.length;
|
||||||
|
const which = n ? tr(`หน้า ${ops.idxs.map((i) => i + 1).join(', ')}`, `page ${ops.idxs.map((i) => i + 1).join(', ')}`) : '';
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<span className="tools-scope">{tr('ใช้กับ', 'Applies to')} {which}</span>
|
||||||
|
<button className="tool" onClick={() => ops.rotate(-90)} disabled={!n}><RotateCcw size={I} /><span>{tr('หมุนซ้าย', 'Rotate left')}</span></button>
|
||||||
|
<button className="tool" onClick={() => ops.rotate(90)} disabled={!n}><RotateCw size={I} /><span>{tr('หมุนขวา', 'Rotate right')}</span></button>
|
||||||
|
<button className="tool danger" onClick={() => ops.remove()} disabled={!ops.canDelete()}><Trash2 size={I} /><span>{tr('ลบหน้า', 'Delete')}</span></button>
|
||||||
|
<span className="tool-sep" aria-hidden />
|
||||||
|
<button className="tool" onClick={ops.insertBlank}><FilePlus2 size={I} /><span>{tr('แทรกหน้าว่าง', 'Blank page')}</span></button>
|
||||||
|
<button className="tool" onClick={ops.merge}><Files size={I} /><span>{tr('รวม PDF', 'Merge PDF')}</span></button>
|
||||||
|
<button className="tool" onClick={ops.addImages}><ImageUp size={I} /><span>{tr('รูปเป็นหน้า', 'Images')}</span></button>
|
||||||
|
<button className="tool" onClick={ops.extract} disabled={!n}><FileDown size={I} /><span>{tr('ดึงหน้าออก', 'Extract')}</span></button>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,701 @@
|
|||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import type React from 'react';
|
||||||
|
import { Bold, Trash2, BringToFront, Replace, ShieldCheck } from 'lucide-react';
|
||||||
|
import { useEditor } from '../editor';
|
||||||
|
import type { Item, Rect, Tool } from '../lib/types';
|
||||||
|
import { padRect, rectFromTopLeft, topLeftOf } from '../lib/geom';
|
||||||
|
import { baseName, download, friendlyError, imageFileToPending, measureText, pickFiles, uid } from '../lib/util';
|
||||||
|
import { STAMPS, loadSignatures, makeStamp } from '../lib/stamps';
|
||||||
|
import { getTextLines, lineSubRect } from '../lib/analyze';
|
||||||
|
import { addPageNumbers, addWatermark, splitEvery, type PageNumOpts } from '../lib/pageops';
|
||||||
|
import { loadPdf } from '../lib/pdfjs';
|
||||||
|
import { pdfToDocx, pdfToImages, pdfToText, pdfToXlsx } from '../lib/convert';
|
||||||
|
import { ocrPdf } from '../lib/ocr';
|
||||||
|
import JSZip from 'jszip';
|
||||||
|
import { tr } from '../i18n';
|
||||||
|
import { usePageOps } from './usePageOps';
|
||||||
|
|
||||||
|
const COLORS = ['#000000', '#1f4fbf', '#c62828', '#1b8a3a', '#f57c00', '#6a1b9a', '#ffffff'];
|
||||||
|
const HL = ['#ffeb3b', '#a5f36b', '#7fd8ff', '#ff9ecf', '#ffb74d'];
|
||||||
|
|
||||||
|
const colorName = (c: string): string =>
|
||||||
|
({
|
||||||
|
'#000000': tr('ดำ', 'Black'), '#1f4fbf': tr('น้ำเงิน', 'Blue'), '#c62828': tr('แดง', 'Red'), '#1b8a3a': tr('เขียว', 'Green'),
|
||||||
|
'#f57c00': tr('ส้ม', 'Orange'), '#6a1b9a': tr('ม่วง', 'Purple'), '#ffffff': tr('ขาว', 'White'), '#ffeb3b': tr('เหลือง', 'Yellow'),
|
||||||
|
'#a5f36b': tr('เขียวอ่อน', 'Light green'), '#7fd8ff': tr('ฟ้า', 'Light blue'), '#ff9ecf': tr('ชมพู', 'Pink'), '#ffb74d': tr('ส้มอ่อน', 'Light orange'),
|
||||||
|
'#f5b800': tr('เหลือง', 'Yellow'), '#4caf50': tr('เขียว', 'Green'), '#2196f3': tr('ฟ้า', 'Blue'), '#e91e63': tr('ชมพู', 'Pink'),
|
||||||
|
})[c.toLowerCase()] ?? c;
|
||||||
|
|
||||||
|
function Swatches({ value, onChange, list = COLORS, allowNone, label }: { value: string | null; onChange: (c: string | null) => void; list?: string[]; allowNone?: boolean; label?: string }) {
|
||||||
|
const custom = value !== null && !list.includes(value.toLowerCase());
|
||||||
|
return (
|
||||||
|
<div className="swatches" role="group" aria-label={label ?? tr('สี', 'Colour')}>
|
||||||
|
{allowNone && <button className={`sw none${value === null ? ' on' : ''}`} onClick={() => onChange(null)} aria-pressed={value === null} aria-label={tr('ไม่มีสี', 'No colour')} title={tr('ไม่มีสี', 'No colour')} />}
|
||||||
|
{list.map((c) => (
|
||||||
|
<button key={c} className={`sw${value?.toLowerCase() === c ? ' on' : ''}`} style={{ background: c }} onClick={() => onChange(c)} aria-pressed={value?.toLowerCase() === c} aria-label={colorName(c)} title={colorName(c)} />
|
||||||
|
))}
|
||||||
|
<input
|
||||||
|
type="color"
|
||||||
|
className={custom ? 'on' : ''}
|
||||||
|
value={value ?? '#000000'}
|
||||||
|
onChange={(e) => onChange(e.target.value)}
|
||||||
|
aria-label={custom ? tr(`สีที่เลือกเอง ${value}`, `Custom colour ${value}`) : tr('เลือกสีเอง', 'Custom colour')}
|
||||||
|
title={tr('เลือกสีเอง', 'Custom colour')}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const Row = ({ label, children }: { label: string; children: React.ReactNode }) => (
|
||||||
|
<label className="row">
|
||||||
|
<span>{label}</span>
|
||||||
|
{children}
|
||||||
|
</label>
|
||||||
|
);
|
||||||
|
|
||||||
|
export function SidePanel() {
|
||||||
|
const ed = useEditor();
|
||||||
|
const sel = ed.doc.items.find((i) => i.id === ed.selectedId) ?? null;
|
||||||
|
// On phones the panel is a bottom sheet that can be folded away to see the page.
|
||||||
|
const [folded, setFolded] = useState(false);
|
||||||
|
return (
|
||||||
|
<aside className={`side${folded ? ' folded' : ''}`} aria-label={tr('ตัวเลือกและคำสั่ง', 'Options and commands')}>
|
||||||
|
<button className="side-handle" aria-expanded={!folded} onClick={() => setFolded(!folded)}>
|
||||||
|
<span className="side-grip" aria-hidden />
|
||||||
|
{folded ? tr('แสดงตัวเลือก', 'Show options') : tr('ซ่อนตัวเลือก', 'Hide options')}
|
||||||
|
</button>
|
||||||
|
{sel ? <PropsPanel it={sel} /> : <ToolOptions tool={ed.tool} />}
|
||||||
|
{!sel && ed.tool === 'select' && (ed.tab === 'edit' || ed.tab === 'comment') && <DocInfo />}
|
||||||
|
{ed.tab === 'comment' && ed.tool === 'stamp' && <StampPanel />}
|
||||||
|
{ed.tab === 'sign' && <SignPanel />}
|
||||||
|
{ed.tab === 'edit' && <EditHelp />}
|
||||||
|
{ed.tab === 'forms' && <FormsPanel />}
|
||||||
|
{ed.tab === 'pages' && <PagesPanel />}
|
||||||
|
{ed.tab === 'redact' && <RedactPanel />}
|
||||||
|
{ed.tab === 'ocr' && <OcrPanel />}
|
||||||
|
{ed.tab === 'convert' && <ConvertPanel />}
|
||||||
|
{ed.tab === 'search' && <SearchPanel />}
|
||||||
|
{ed.tab === 'comment' && <CommentList />}
|
||||||
|
</aside>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function PropsPanel({ it }: { it: Item }) {
|
||||||
|
const ed = useEditor();
|
||||||
|
const up = (fn: (i: Item) => Item) => ed.commit((d) => ({ ...d, items: d.items.map((x) => (x.id === it.id ? fn(x) : x)) }));
|
||||||
|
const del = () => {
|
||||||
|
ed.commit((d) => ({ ...d, items: d.items.filter((x) => x.id !== it.id) }));
|
||||||
|
ed.select(null);
|
||||||
|
};
|
||||||
|
const front = () => ed.commit((d) => ({ ...d, items: [...d.items.filter((x) => x.id !== it.id), it] }));
|
||||||
|
const textUp = (p: Partial<{ size: number; bold: boolean; color: string; bg: string | null }>) =>
|
||||||
|
up((x) => {
|
||||||
|
if (x.kind !== 'text') return x;
|
||||||
|
const n = { ...x, ...p };
|
||||||
|
const m = measureText(n.text, n.size, n.bold);
|
||||||
|
return { ...n, rect: rectFromTopLeft(topLeftOf(x.rect, x.rot), m.w, m.h, x.rot) };
|
||||||
|
});
|
||||||
|
const names: Record<Item['kind'], string> = {
|
||||||
|
text: tr('ข้อความ', 'Text'), image: tr('รูปภาพ', 'Image'), highlight: tr('ไฮไลต์', 'Highlight'), whiteout: 'Whiteout', redact: tr('ปกปิด', 'Redaction'), rect: tr('สี่เหลี่ยม', 'Rectangle'),
|
||||||
|
ellipse: tr('วงรี', 'Ellipse'), line: tr('เส้น', 'Line'), arrow: tr('ลูกศร', 'Arrow'), ink: tr('ลายเส้น', 'Ink'), note: tr('โน้ต', 'Note'), field: tr('ช่องฟอร์ม', 'Form field'),
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="panel">
|
||||||
|
<h3>{names[it.kind]}</h3>
|
||||||
|
{it.kind === 'text' && (
|
||||||
|
<>
|
||||||
|
<Row label={tr('ขนาด', 'Size')}>
|
||||||
|
<input type="number" min={4} max={200} step={0.5} value={it.size} onChange={(e) => textUp({ size: Math.max(4, +e.target.value || it.size) })} />
|
||||||
|
</Row>
|
||||||
|
<Row label={tr('ตัวหนา', 'Bold')}>
|
||||||
|
<button className={`icon-btn${it.bold ? ' on' : ''}`} onClick={() => textUp({ bold: !it.bold })}>
|
||||||
|
<Bold size={16} />
|
||||||
|
</button>
|
||||||
|
</Row>
|
||||||
|
<p className="lbl">{tr('สีตัวอักษร', 'Text colour')}</p>
|
||||||
|
<Swatches value={it.color} onChange={(c) => textUp({ color: c ?? '#000000' })} />
|
||||||
|
<p className="lbl">{tr('พื้นหลัง', 'Background')}</p>
|
||||||
|
<Swatches value={it.bg} allowNone onChange={(c) => textUp({ bg: c })} />
|
||||||
|
<button className="btn" onClick={() => ed.setEditing(it.id)}>{tr('แก้ข้อความ (ดับเบิลคลิก)', 'Edit text (double-click)')}</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{(it.kind === 'rect' || it.kind === 'ellipse') && (
|
||||||
|
<>
|
||||||
|
<p className="lbl">{tr('เส้นขอบ', 'Border')}</p>
|
||||||
|
<Swatches value={it.stroke} onChange={(c) => up((x) => ({ ...x, stroke: c ?? '#000000' }))} />
|
||||||
|
<p className="lbl">{tr('สีพื้น', 'Fill')}</p>
|
||||||
|
<Swatches value={it.fill} allowNone onChange={(c) => up((x) => ({ ...x, fill: c }))} />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{(it.kind === 'line' || it.kind === 'arrow' || it.kind === 'ink') && (
|
||||||
|
<>
|
||||||
|
<p className="lbl">{tr('สีเส้น', 'Line colour')}</p>
|
||||||
|
<Swatches value={it.stroke} onChange={(c) => up((x) => ({ ...x, stroke: c ?? '#000000' }))} />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{(it.kind === 'rect' || it.kind === 'ellipse' || it.kind === 'line' || it.kind === 'arrow' || it.kind === 'ink') && (
|
||||||
|
<>
|
||||||
|
<Row label={tr('ความหนา', 'Width')}>
|
||||||
|
<input type="range" min={0.5} max={12} step={0.5} value={it.width} onChange={(e) => up((x) => ({ ...x, width: +e.target.value }) as Item)} />
|
||||||
|
</Row>
|
||||||
|
<Row label={tr('ความทึบ', 'Opacity')}>
|
||||||
|
<input type="range" min={0.1} max={1} step={0.05} value={it.opacity} onChange={(e) => up((x) => ({ ...x, opacity: +e.target.value }) as Item)} />
|
||||||
|
</Row>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{it.kind === 'highlight' && (
|
||||||
|
<>
|
||||||
|
<p className="lbl">{tr('สีไฮไลต์', 'Highlight colour')}</p>
|
||||||
|
<Swatches value={it.fill} list={HL} onChange={(c) => up((x) => ({ ...x, fill: c ?? '#ffeb3b' }) as Item)} />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{it.kind === 'whiteout' && (
|
||||||
|
<>
|
||||||
|
<p className="lbl">{tr('สีที่ใช้ปิด', 'Cover colour')}</p>
|
||||||
|
<Swatches value={it.fill} onChange={(c) => up((x) => ({ ...x, fill: c ?? '#ffffff' }) as Item)} />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{it.kind === 'note' && (
|
||||||
|
<>
|
||||||
|
<p className="lbl">{tr('สีโน้ต', 'Note colour')}</p>
|
||||||
|
<Swatches value={it.color} list={['#f5b800', '#4caf50', '#2196f3', '#e91e63']} onChange={(c) => up((x) => ({ ...x, color: c ?? '#f5b800' }) as Item)} />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{it.kind === 'image' && (
|
||||||
|
<button
|
||||||
|
className="btn"
|
||||||
|
onClick={async () => {
|
||||||
|
const [f] = await pickFiles('image/*');
|
||||||
|
if (!f) return;
|
||||||
|
const p = await imageFileToPending(f);
|
||||||
|
up((x) => (x.kind === 'image' ? { ...x, dataUrl: p.dataUrl } : x));
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Replace size={16} /> {tr('แทนที่รูป', 'Replace image')}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{it.kind === 'field' && (
|
||||||
|
<Row label={tr('ชื่อฟิลด์', 'Field name')}>
|
||||||
|
<input value={it.name} onChange={(e) => up((x) => ({ ...x, name: e.target.value.replace(/[.\s]/g, '_') }) as Item)} />
|
||||||
|
</Row>
|
||||||
|
)}
|
||||||
|
<div className="btn-row">
|
||||||
|
<button className="btn" onClick={front} title={tr('นำขึ้นบนสุด', 'Bring to front')}>
|
||||||
|
<BringToFront size={16} /> {tr('บนสุด', 'Front')}
|
||||||
|
</button>
|
||||||
|
<button className="btn danger" onClick={del}>
|
||||||
|
<Trash2 size={16} /> {tr('ลบ', 'Delete')}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{it.kind === 'image' && <p className="hint">{tr('ลากมุมขวาล่างเพื่อย่อ/ขยาย (Shift = ไม่ล็อกสัดส่วน)', 'Drag the bottom-right corner to resize (Shift = free aspect ratio)')}</p>}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const STROKE_TOOLS = new Set<Tool>(['pen', 'rect', 'ellipse', 'line', 'arrow']);
|
||||||
|
|
||||||
|
function ToolOptions({ tool }: { tool: Tool }) {
|
||||||
|
const ed = useEditor();
|
||||||
|
const o = ed.opts;
|
||||||
|
if (tool === 'text')
|
||||||
|
return (
|
||||||
|
<section className="panel">
|
||||||
|
<h3>{tr('ข้อความใหม่', 'New text')}</h3>
|
||||||
|
<Row label={tr('ขนาด', 'Size')}>
|
||||||
|
<input type="number" min={4} max={200} value={o.size} onChange={(e) => ed.setOpts({ size: +e.target.value || 12 })} />
|
||||||
|
</Row>
|
||||||
|
<Row label={tr('ตัวหนา', 'Bold')}>
|
||||||
|
<button className={`icon-btn${o.bold ? ' on' : ''}`} onClick={() => ed.setOpts({ bold: !o.bold })}>
|
||||||
|
<Bold size={16} />
|
||||||
|
</button>
|
||||||
|
</Row>
|
||||||
|
<Swatches value={o.color} onChange={(c) => ed.setOpts({ color: c ?? '#000000' })} />
|
||||||
|
<p className="hint">{tr('คลิกบนหน้าเพื่อวางข้อความ', 'Click on the page to place text')}</p>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
if (tool === 'highlight')
|
||||||
|
return (
|
||||||
|
<section className="panel">
|
||||||
|
<h3>{tr('ไฮไลต์', 'Highlight')}</h3>
|
||||||
|
<Swatches value={o.highlight} list={HL} onChange={(c) => ed.setOpts({ highlight: c ?? '#ffeb3b' })} />
|
||||||
|
<p className="hint">{tr('ลากคลุมข้อความที่ต้องการ', 'Drag over the text to highlight')}</p>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
if (STROKE_TOOLS.has(tool))
|
||||||
|
return (
|
||||||
|
<section className="panel">
|
||||||
|
<h3>{tr('รูปแบบเส้น', 'Line style')}</h3>
|
||||||
|
<Swatches value={o.color} onChange={(c) => ed.setOpts({ color: c ?? '#000000' })} />
|
||||||
|
{(tool === 'rect' || tool === 'ellipse') && (
|
||||||
|
<>
|
||||||
|
<p className="lbl">{tr('สีพื้น', 'Fill')}</p>
|
||||||
|
<Swatches value={o.fill} allowNone onChange={(c) => ed.setOpts({ fill: c })} />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
<Row label={tr('ความหนา', 'Width')}>
|
||||||
|
<input type="range" min={0.5} max={12} step={0.5} value={o.width} onChange={(e) => ed.setOpts({ width: +e.target.value })} />
|
||||||
|
</Row>
|
||||||
|
<Row label={tr('ความทึบ', 'Opacity')}>
|
||||||
|
<input type="range" min={0.1} max={1} step={0.05} value={o.opacity} onChange={(e) => ed.setOpts({ opacity: +e.target.value })} />
|
||||||
|
</Row>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
if (tool === 'image' && o.pending)
|
||||||
|
return (
|
||||||
|
<section className="panel">
|
||||||
|
<h3>{tr('วางรูป', 'Place image')}</h3>
|
||||||
|
<img className="pending" src={o.pending.dataUrl} alt="" />
|
||||||
|
<p className="hint">{tr('คลิกบนหน้าเพื่อวาง', 'Click on the page to place')}</p>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Shown instead of an empty panel: what this document is and the common next steps. */
|
||||||
|
function DocInfo() {
|
||||||
|
const ed = useEditor();
|
||||||
|
const n = ed.doc.pageIds.length;
|
||||||
|
return (
|
||||||
|
<section className="panel">
|
||||||
|
<h3>{tr('เอกสารนี้', 'This document')}</h3>
|
||||||
|
<p className="doc-meta">
|
||||||
|
<span className="doc-meta-name">{ed.doc.name}</span>
|
||||||
|
<span>{tr(`${n} หน้า`, `${n} page${n === 1 ? '' : 's'}`)}{ed.doc.items.length ? tr(` · แก้ไข ${ed.doc.items.length} จุด`, ` · ${ed.doc.items.length} edit(s)`) : ''}</span>
|
||||||
|
</p>
|
||||||
|
<p className="lbl">{tr('อยากทำอะไรต่อ', 'What next')}</p>
|
||||||
|
<div className="next-steps">
|
||||||
|
<button className="btn" onClick={() => { ed.setTab('sign'); ed.openSignature(); }}>{tr('เซ็นเอกสาร', 'Sign this document')}</button>
|
||||||
|
<button className="btn" onClick={() => ed.setTab('forms')}>{tr('กรอกฟอร์ม', 'Fill in a form')}</button>
|
||||||
|
<button className="btn" onClick={() => { ed.setTab('edit'); ed.setTool('edit'); }}>{tr('แก้ข้อความเดิม', 'Change existing text')}</button>
|
||||||
|
</div>
|
||||||
|
<p className="privacy"><ShieldCheck size={15} aria-hidden /> {tr('ไฟล์อยู่ในเครื่องนี้เท่านั้น ไม่ถูกอัปโหลด', 'This file stays on this device. Nothing is uploaded.')}</p>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function EditHelp() {
|
||||||
|
const ed = useEditor();
|
||||||
|
if (ed.tool !== 'edit' && ed.tool !== 'whiteout') return null;
|
||||||
|
return (
|
||||||
|
<section className="panel">
|
||||||
|
<h3>{tr('แก้ไขเนื้อหาเดิม', 'Edit existing content')}</h3>
|
||||||
|
{ed.tool === 'edit' ? (
|
||||||
|
<ul className="hint">
|
||||||
|
<li>{tr('เส้นประฟ้า = ข้อความเดิม → คลิกเพื่อแก้', 'Blue dashed box = existing text → click to edit')}</li>
|
||||||
|
<li>{tr('เส้นประส้ม = รูปเดิม → คลิกเพื่อย้าย/ย่อขยาย/แทนที่/ลบ', 'Orange dashed box = existing image → click to move/resize/replace/delete')}</li>
|
||||||
|
<li>{tr('ลบข้อความทั้งหมดในกล่อง = ลบข้อความเดิมออก', 'Clear the box to remove the original text')}</li>
|
||||||
|
<li>{tr('สีพื้น/สีตัวอักษรดึงจากหน้าเอกสารอัตโนมัติ', 'Text and background colours are sampled from the page')}</li>
|
||||||
|
<li>{tr('ข้อความที่แก้จะใช้ฟอนต์ Sarabun แทนฟอนต์เดิม', 'Edited text is set in Sarabun, not the original font')}</li>
|
||||||
|
</ul>
|
||||||
|
) : (
|
||||||
|
<p className="hint">{tr('ลากคลุมพื้นที่ที่ต้องการลบ (ปิดด้วยสีพื้น)', 'Drag over the area to erase (covered with the background colour)')}</p>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function StampPanel() {
|
||||||
|
const ed = useEditor();
|
||||||
|
const [custom, setCustom] = useState('');
|
||||||
|
const [color, setColor] = useState('#c62828');
|
||||||
|
const choose = async (text: string, c: string) => ed.setOpts({ pending: await makeStamp(text, c) });
|
||||||
|
return (
|
||||||
|
<section className="panel">
|
||||||
|
<h3>{tr('ตราประทับ', 'Stamps')}</h3>
|
||||||
|
<div className="stamps">
|
||||||
|
{STAMPS.map((s) => (
|
||||||
|
<button key={s.text} className="stamp-btn" style={{ color: s.color, borderColor: s.color }} onClick={() => choose(s.text, s.color)}>
|
||||||
|
{s.text}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<p className="lbl">{tr('ข้อความเอง', 'Custom text')}</p>
|
||||||
|
<div className="inline">
|
||||||
|
<input value={custom} aria-label={tr('ข้อความตราประทับ', 'Stamp text')} onChange={(e) => setCustom(e.target.value)} placeholder={tr('เช่น ตรวจแล้ว', 'e.g. REVIEWED')} />
|
||||||
|
<input type="color" value={color} onChange={(e) => setColor(e.target.value)} />
|
||||||
|
<button className="btn" disabled={!custom.trim()} onClick={() => choose(custom.trim(), color)}>
|
||||||
|
{tr('ใช้', 'Use')}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{ed.opts.pending && (
|
||||||
|
<>
|
||||||
|
<img className="pending" src={ed.opts.pending.dataUrl} alt="" />
|
||||||
|
<p className="hint">{tr('คลิกบนหน้าเพื่อประทับ', 'Click on the page to stamp')}</p>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function SignPanel() {
|
||||||
|
const ed = useEditor();
|
||||||
|
const [sigs, setSigs] = useState(loadSignatures);
|
||||||
|
useEffect(() => {
|
||||||
|
const f = () => setSigs(loadSignatures());
|
||||||
|
window.addEventListener('signatures-changed', f);
|
||||||
|
return () => window.removeEventListener('signatures-changed', f);
|
||||||
|
}, []);
|
||||||
|
const use = async (url: string) => {
|
||||||
|
const im = await new Promise<HTMLImageElement>((res) => {
|
||||||
|
const i = new Image();
|
||||||
|
i.onload = () => res(i);
|
||||||
|
i.src = url;
|
||||||
|
});
|
||||||
|
const w = 150;
|
||||||
|
ed.setOpts({ pending: { dataUrl: url, w, h: (w * im.naturalHeight) / im.naturalWidth } });
|
||||||
|
ed.setTool('sign');
|
||||||
|
};
|
||||||
|
return (
|
||||||
|
<section className="panel">
|
||||||
|
<h3>{tr('ลายเซ็นที่บันทึกไว้', 'Saved signatures')}</h3>
|
||||||
|
{sigs.length === 0 && <p className="hint">{tr('ยังไม่มี — กด “สร้างลายเซ็นใหม่”', 'None yet — click “New signature”')}</p>}
|
||||||
|
<div className="sig-list">
|
||||||
|
{sigs.map((s, i) => (
|
||||||
|
<button key={i} className="sig" onClick={() => use(s)} title={tr('คลิกแล้วคลิกบนหน้าเพื่อวาง', 'Click, then click on the page to place')}>
|
||||||
|
<img src={s} alt="" />
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<button className="btn primary" onClick={ed.openSignature}>
|
||||||
|
{tr('สร้างลายเซ็นใหม่', 'New signature')}
|
||||||
|
</button>
|
||||||
|
{ed.tool === 'sign' && ed.opts.pending && <p className="hint">{tr('คลิกบนหน้าเพื่อวางลายเซ็น', 'Click on the page to place the signature')}</p>}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function FormsPanel() {
|
||||||
|
const ed = useEditor();
|
||||||
|
const [names, setNames] = useState<string[] | null>(null);
|
||||||
|
useEffect(() => {
|
||||||
|
let alive = true;
|
||||||
|
ed.loaded.pdf
|
||||||
|
.getFieldObjects()
|
||||||
|
.then((f) => alive && setNames(f ? Object.keys(f) : []))
|
||||||
|
.catch(() => alive && setNames([]));
|
||||||
|
return () => {
|
||||||
|
alive = false;
|
||||||
|
};
|
||||||
|
}, [ed.loaded.pdf]);
|
||||||
|
const created = ed.doc.items.filter((i) => i.kind === 'field').length;
|
||||||
|
return (
|
||||||
|
<section className="panel">
|
||||||
|
<h3>{tr('ฟอร์ม', 'Forms')}</h3>
|
||||||
|
<p className="hint">
|
||||||
|
{tr(`พบฟิลด์ในเอกสาร ${names?.length ?? '…'} ช่อง · สร้างใหม่ ${created} ช่อง`, `${names?.length ?? '…'} fields in document · ${created} created`)}
|
||||||
|
</p>
|
||||||
|
<p className="hint">{tr('ใช้เครื่องมือ “เลือก” แล้วคลิกช่องบนหน้าเพื่อพิมพ์ได้เลย', 'With “Select”, click a field on the page and type')}</p>
|
||||||
|
<label className="check">
|
||||||
|
<input type="checkbox" checked={ed.flatten} onChange={(e) => ed.setFlatten(e.target.checked)} /> {tr('ล็อกฟอร์มตอนบันทึก (Flatten) — รวมค่าที่กรอกเข้ากับหน้า กรอก/แก้ไม่ได้อีก', 'Lock the form on save (flatten) — values become part of the page and can no longer be edited')}
|
||||||
|
</label>
|
||||||
|
<button className="btn" disabled={!Object.keys(ed.doc.form).length} onClick={() => ed.commit((d) => ({ ...d, form: {} }))}>
|
||||||
|
{tr('ล้างค่าที่กรอก', 'Clear entered values')}
|
||||||
|
</button>
|
||||||
|
{!!names?.length && (
|
||||||
|
<details>
|
||||||
|
<summary>{tr('รายชื่อฟิลด์', 'Field names')}</summary>
|
||||||
|
<ul className="field-names">
|
||||||
|
{names.map((n) => (
|
||||||
|
<li key={n}>
|
||||||
|
{n}
|
||||||
|
{n in ed.doc.form && <b> = {String(ed.doc.form[n])}</b>}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</details>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function PagesPanel() {
|
||||||
|
const ed = useEditor();
|
||||||
|
const ids = ed.doc.pageIds;
|
||||||
|
const { idxs } = usePageOps();
|
||||||
|
const [n, setN] = useState(1);
|
||||||
|
const [wm, setWm] = useState({ text: tr('ลับเฉพาะ', 'CONFIDENTIAL'), size: 60, opacity: 0.18, color: '#c62828', angle: 45 });
|
||||||
|
const [pn, setPn] = useState<PageNumOpts>({ format: '{n} / {total}', pos: 'bc', size: 10, start: 1 });
|
||||||
|
const name = baseName(ed.doc.name);
|
||||||
|
|
||||||
|
const op = (label: string, fn: () => Promise<{ bytes: Uint8Array; ids: string[] }>) =>
|
||||||
|
ed.run(label, async () => {
|
||||||
|
const r = await fn();
|
||||||
|
ed.setBytes(r.bytes, r.ids);
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="panel">
|
||||||
|
<h3>{tr('จัดการหน้า', 'Pages')}</h3>
|
||||||
|
<p className="hint">
|
||||||
|
{tr(`เลือกอยู่ ${idxs.length} หน้า`, `${idxs.length} page(s) selected`)}: {idxs.map((i) => i + 1).join(', ') || '-'}
|
||||||
|
<span className="desk-only"> {tr('· Ctrl/Shift+คลิกภาพย่อเพื่อเลือกหลายหน้า', '· Ctrl/Shift+click thumbnails to select several')}</span>
|
||||||
|
</p>
|
||||||
|
<p className="hint">{tr('คำสั่งหมุน ลบ แทรก รวม อยู่ในแถบด้านบน', 'Rotate, delete, insert and merge are in the toolbar above.')}</p>
|
||||||
|
|
||||||
|
<p className="lbl" id="split-n">{tr('แยกเป็นไฟล์ละ N หน้า', 'Split into files of N pages')}</p>
|
||||||
|
<div className="inline">
|
||||||
|
<input type="number" min={1} value={n} aria-labelledby="split-n" onChange={(e) => setN(Math.max(1, +e.target.value || 1))} />
|
||||||
|
<button
|
||||||
|
className="btn"
|
||||||
|
onClick={() =>
|
||||||
|
ed.run(tr('แยกไฟล์…', 'Splitting…'), async () => {
|
||||||
|
const parts = await splitEvery(await ed.exportBytes(), n);
|
||||||
|
const zip = new JSZip();
|
||||||
|
parts.forEach((p, i) => zip.file(`${name}-part${i + 1}.pdf`, p));
|
||||||
|
download(await zip.generateAsync({ type: 'blob' }), `${name}-split.zip`);
|
||||||
|
})
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{tr('แยก (.zip)', 'Split (.zip)')}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<details className="fold">
|
||||||
|
<summary>{tr('ลายน้ำ', 'Watermark')}</summary>
|
||||||
|
<Row label={tr('ข้อความ', 'Text')}>
|
||||||
|
<input value={wm.text} onChange={(e) => setWm({ ...wm, text: e.target.value })} />
|
||||||
|
</Row>
|
||||||
|
<Row label={tr('สี', 'Colour')}>
|
||||||
|
<input type="color" value={wm.color} onChange={(e) => setWm({ ...wm, color: e.target.value })} />
|
||||||
|
</Row>
|
||||||
|
<Row label={tr('ขนาด', 'Size')}>
|
||||||
|
<input type="number" value={wm.size} onChange={(e) => setWm({ ...wm, size: +e.target.value || 60 })} />
|
||||||
|
</Row>
|
||||||
|
<Row label={tr('ความทึบ', 'Opacity')}>
|
||||||
|
<input type="range" min={0.05} max={0.8} step={0.01} value={wm.opacity} onChange={(e) => setWm({ ...wm, opacity: +e.target.value })} />
|
||||||
|
</Row>
|
||||||
|
<Row label={tr('มุม (องศา)', 'Angle (°)')}>
|
||||||
|
<input type="number" value={wm.angle} onChange={(e) => setWm({ ...wm, angle: +e.target.value || 0 })} />
|
||||||
|
</Row>
|
||||||
|
<button className="btn" disabled={!wm.text.trim()} onClick={() => op(tr('ใส่ลายน้ำ…', 'Adding watermark…'), async () => ({ bytes: await addWatermark(ed.doc.bytes, wm), ids }))}>
|
||||||
|
{tr('ใส่ลายน้ำทุกหน้า', 'Watermark all pages')}
|
||||||
|
</button>
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<details className="fold">
|
||||||
|
<summary>{tr('เลขหน้า', 'Page numbers')}</summary>
|
||||||
|
<Row label={tr('รูปแบบ', 'Format')}>
|
||||||
|
<input value={pn.format} onChange={(e) => setPn({ ...pn, format: e.target.value })} />
|
||||||
|
</Row>
|
||||||
|
<p className="hint">{tr('{n} = เลขหน้านี้, {total} = จำนวนหน้าทั้งหมด', '{n} = this page, {total} = page count')}</p>
|
||||||
|
<Row label={tr('ตำแหน่ง', 'Position')}>
|
||||||
|
<select value={pn.pos} onChange={(e) => setPn({ ...pn, pos: e.target.value as PageNumOpts['pos'] })}>
|
||||||
|
<option value="bc">{tr('ล่างกลาง', 'Bottom centre')}</option>
|
||||||
|
<option value="br">{tr('ล่างขวา', 'Bottom right')}</option>
|
||||||
|
<option value="bl">{tr('ล่างซ้าย', 'Bottom left')}</option>
|
||||||
|
<option value="tc">{tr('บนกลาง', 'Top centre')}</option>
|
||||||
|
<option value="tr">{tr('บนขวา', 'Top right')}</option>
|
||||||
|
</select>
|
||||||
|
</Row>
|
||||||
|
<Row label={tr('เริ่มที่', 'Start at')}>
|
||||||
|
<input type="number" value={pn.start} onChange={(e) => setPn({ ...pn, start: +e.target.value || 1 })} />
|
||||||
|
</Row>
|
||||||
|
<button className="btn" onClick={() => op(tr('ใส่เลขหน้า…', 'Adding page numbers…'), async () => ({ bytes: await addPageNumbers(ed.doc.bytes, pn), ids }))}>
|
||||||
|
{tr('ใส่เลขหน้า', 'Add page numbers')}
|
||||||
|
</button>
|
||||||
|
</details>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function RedactPanel() {
|
||||||
|
const ed = useEditor();
|
||||||
|
const [q, setQ] = useState('');
|
||||||
|
const count = ed.doc.items.filter((i) => i.kind === 'redact').length;
|
||||||
|
const findAll = () =>
|
||||||
|
ed.run(tr('ค้นหาเพื่อปกปิด…', 'Finding text to redact…'), async () => {
|
||||||
|
const needle = q.trim().normalize('NFKC').toLowerCase();
|
||||||
|
if (!needle) return;
|
||||||
|
const add: Item[] = [];
|
||||||
|
for (let i = 0; i < ed.loaded.pdf.numPages; i++) {
|
||||||
|
const lines = await getTextLines(await ed.loaded.pdf.getPage(i + 1));
|
||||||
|
for (const l of lines) {
|
||||||
|
const hay = l.text.normalize('NFKC').toLowerCase();
|
||||||
|
for (let k = hay.indexOf(needle); k >= 0; k = hay.indexOf(needle, k + needle.length))
|
||||||
|
// Widths are estimated, so pad the box along the line to be sure nothing peeks out.
|
||||||
|
add.push({ id: uid(), pageId: ed.loaded.pageIds[i], kind: 'redact', rect: padRect(lineSubRect(l, k, needle.length), l.size * 0.3), stroke: '', fill: '#000000', width: 0, opacity: 1 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!add.length) return ed.toast(tr(`ไม่พบ “${q.trim()}” ในเอกสาร — ไม่ได้ปกปิดอะไร`, `“${q.trim()}” was not found — nothing was marked`));
|
||||||
|
ed.commit((d) => ({ ...d, items: [...d.items, ...add] }));
|
||||||
|
ed.toast(tr(`ทำเครื่องหมายปกปิด ${add.length} จุด — จะปกปิดถาวรตอนบันทึก`, `Marked ${add.length} area(s) — they become permanent when you save`));
|
||||||
|
});
|
||||||
|
return (
|
||||||
|
<section className="panel">
|
||||||
|
<h3>{tr('ปกปิดข้อมูล (Redact)', 'Redact')}</h3>
|
||||||
|
<p className="hint">{tr('ลากคลุมส่วนที่ต้องการปกปิด หรือค้นหาคำแล้วปกปิดทั้งหมด. ตอนบันทึก หน้าที่มีการปกปิดจะถูกแปลงเป็นภาพ เพื่อลบข้อความจริงออกถาวร.', 'Drag over what to hide, or search a term and redact every match. On save, redacted pages are rasterised so the underlying text is permanently removed.')}</p>
|
||||||
|
<div className="inline">
|
||||||
|
<input value={q} aria-label={tr('คำที่ต้องการปกปิด', 'Text to redact')} onChange={(e) => setQ(e.target.value)} placeholder={tr('เช่น เลขบัตรประชาชน', 'e.g. ID number')} onKeyDown={(e) => e.key === 'Enter' && findAll()} />
|
||||||
|
<button className="btn" onClick={findAll}>{tr('ปกปิดทั้งหมด', 'Redact all')}</button>
|
||||||
|
</div>
|
||||||
|
<p className="hint">{tr(`มีเครื่องหมายปกปิด ${count} จุด`, `${count} area(s) marked`)}</p>
|
||||||
|
<button className="btn" disabled={!count} onClick={() => ed.commit((d) => ({ ...d, items: d.items.filter((i) => i.kind !== 'redact') }))}>
|
||||||
|
{tr('ล้างเครื่องหมายทั้งหมด', 'Clear all marks')}
|
||||||
|
</button>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function OcrPanel() {
|
||||||
|
const ed = useEditor();
|
||||||
|
const [lang, setLang] = useState('tha+eng');
|
||||||
|
const [scope, setScope] = useState<'current' | 'all'>('all');
|
||||||
|
const [prog, setProg] = useState<{ msg: string; frac: number } | null>(null);
|
||||||
|
const [text, setText] = useState('');
|
||||||
|
const [skip, setSkip] = useState(true);
|
||||||
|
const go = async () => {
|
||||||
|
const pages = scope === 'all' ? ed.doc.pageIds.map((_, i) => i) : [ed.current];
|
||||||
|
try {
|
||||||
|
setProg({ msg: tr('เริ่ม…', 'Starting…'), frac: 0 });
|
||||||
|
const r = await ocrPdf(ed.doc.bytes, ed.loaded.pdf, pages, lang, (msg, frac) => setProg({ msg, frac }), skip);
|
||||||
|
ed.setBytes(r.bytes, ed.doc.pageIds);
|
||||||
|
setText(r.text);
|
||||||
|
ed.toast(tr('OCR เสร็จ — ค้นหา/คัดลอกข้อความได้แล้ว', 'OCR done — text is now searchable and copyable'));
|
||||||
|
} catch (e) {
|
||||||
|
ed.toast(`${tr('OCR ไม่สำเร็จ', 'OCR failed')}: ${friendlyError(e)}`);
|
||||||
|
} finally {
|
||||||
|
setProg(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
return (
|
||||||
|
<section className="panel">
|
||||||
|
<h3>{tr('OCR (รู้จำข้อความ)', 'OCR (text recognition)')}</h3>
|
||||||
|
<p className="hint">{tr('ทำให้ PDF สแกนค้นหา/คัดลอก/แก้ไขข้อความได้ (ใส่ชั้นข้อความล่องหน). ครั้งแรกต้องใช้อินเทอร์เน็ตเพื่อดาวน์โหลดไฟล์ภาษา — ตัว PDF ไม่ถูกส่งไปไหน.', 'Makes scanned PDFs searchable, copyable and editable (adds an invisible text layer). The first run downloads language data from the internet — your PDF is not sent anywhere.')}</p>
|
||||||
|
<Row label={tr('ภาษา', 'Language')}>
|
||||||
|
<select value={lang} onChange={(e) => setLang(e.target.value)}>
|
||||||
|
<option value="tha+eng">{tr('ไทย + อังกฤษ', 'Thai + English')}</option>
|
||||||
|
<option value="tha">{tr('ไทย', 'Thai')}</option>
|
||||||
|
<option value="eng">{tr('อังกฤษ', 'English')}</option>
|
||||||
|
</select>
|
||||||
|
</Row>
|
||||||
|
<Row label={tr('หน้า', 'Pages')}>
|
||||||
|
<select value={scope} onChange={(e) => setScope(e.target.value as 'current' | 'all')}>
|
||||||
|
<option value="all">{tr('ทุกหน้า', 'All pages')}</option>
|
||||||
|
<option value="current">{tr('หน้าปัจจุบัน', 'Current page')} ({ed.current + 1})</option>
|
||||||
|
</select>
|
||||||
|
</Row>
|
||||||
|
<label className="check">
|
||||||
|
<input type="checkbox" checked={skip} onChange={(e) => setSkip(e.target.checked)} /> {tr('ข้ามหน้าที่มีข้อความอยู่แล้ว', 'Skip pages that already have text')}
|
||||||
|
</label>
|
||||||
|
<button className="btn primary" disabled={!!prog} onClick={go}>
|
||||||
|
{tr('เริ่ม OCR', 'Start OCR')}
|
||||||
|
</button>
|
||||||
|
{prog && (
|
||||||
|
<div className="progress" role="progressbar" aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.round(prog.frac * 100)} aria-label={prog.msg}>
|
||||||
|
<div style={{ width: `${Math.round(prog.frac * 100)}%` }} />
|
||||||
|
<span>
|
||||||
|
{prog.msg} {Math.round(prog.frac * 100)}%
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{text && (
|
||||||
|
<>
|
||||||
|
<p className="lbl">{tr('ข้อความที่อ่านได้', 'Recognised text')}</p>
|
||||||
|
<textarea className="ocr-out" readOnly value={text} />
|
||||||
|
<button className="btn" onClick={() => navigator.clipboard.writeText(text)}>{tr('คัดลอก', 'Copy')}</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ConvertPanel() {
|
||||||
|
const ed = useEditor();
|
||||||
|
const name = baseName(ed.doc.name);
|
||||||
|
const withExported = (label: string, fn: (pdf: Awaited<ReturnType<typeof loadPdf>>) => Promise<void>) =>
|
||||||
|
ed.run(label, async () => {
|
||||||
|
const pdf = await loadPdf(await ed.exportBytes());
|
||||||
|
try {
|
||||||
|
await fn(pdf);
|
||||||
|
} finally {
|
||||||
|
pdf.destroy();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return (
|
||||||
|
<section className="panel">
|
||||||
|
<h3>{tr('แปลงจาก PDF', 'Convert from PDF')}</h3>
|
||||||
|
<div className="grid2">
|
||||||
|
<button className="btn" onClick={() => withExported(tr('แปลงเป็น Word…', 'Converting to Word…'), async (p) => download(await pdfToDocx(p), `${name}.docx`))}>Word (.docx)</button>
|
||||||
|
<button className="btn" onClick={() => withExported(tr('แปลงเป็น Excel…', 'Converting to Excel…'), async (p) => download(await pdfToXlsx(p), `${name}.xlsx`))}>Excel (.xlsx)</button>
|
||||||
|
<button className="btn" onClick={() => withExported(tr('แปลงเป็นรูป…', 'Converting to images…'), async (p) => download(await pdfToImages(p, 'png', name), `${name}-png.zip`))}>{tr('รูป PNG', 'PNG images')}</button>
|
||||||
|
<button className="btn" onClick={() => withExported(tr('แปลงเป็นรูป…', 'Converting to images…'), async (p) => download(await pdfToImages(p, 'jpeg', name), `${name}-jpg.zip`))}>{tr('รูป JPG', 'JPG images')}</button>
|
||||||
|
<button className="btn" onClick={() => withExported(tr('ดึงข้อความ…', 'Extracting text…'), async (p) => download(new Blob([await pdfToText(p)], { type: 'text/plain' }), `${name}.txt`))}>{tr('ข้อความ (.txt)', 'Text (.txt)')}</button>
|
||||||
|
</div>
|
||||||
|
<p className="hint">{tr('Word/Excel ได้ข้อความและตำแหน่งคอลัมน์ (ไม่รวมรูป/สไตล์). PDF สแกนให้ทำ OCR ก่อน.', 'Word/Excel get the text and column layout (no images or styles). Run OCR on scanned PDFs first.')}</p>
|
||||||
|
<h3>{tr('แปลงเป็น PDF', 'Convert to PDF')}</h3>
|
||||||
|
<p className="hint">{tr('รูปภาพ → PDF: ใช้ “เพิ่มรูปเป็นหน้า” ในแท็บจัดการหน้า หรือหน้าเริ่มต้น. Word/Excel/PowerPoint → PDF ต้องใช้ server (เช่น LibreOffice) — ยังไม่รองรับในเวอร์ชัน browser.', 'Images → PDF: use “Add images as pages” in the Pages tab, or the start screen. Word/Excel/PowerPoint → PDF needs a server (e.g. LibreOffice) and is not supported in the browser version.')}</p>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function SearchPanel() {
|
||||||
|
const ed = useEditor();
|
||||||
|
const [q, setQ] = useState('');
|
||||||
|
const [res, setRes] = useState<{ i: number; pageId: string; snippet: string; rect: Rect }[] | null>(null);
|
||||||
|
const go = () =>
|
||||||
|
ed.run(tr('ค้นหา…', 'Searching…'), async () => {
|
||||||
|
const needle = q.trim().normalize('NFKC').toLowerCase();
|
||||||
|
if (!needle) return;
|
||||||
|
const out: NonNullable<typeof res> = [];
|
||||||
|
for (let i = 0; i < ed.loaded.pdf.numPages; i++) {
|
||||||
|
for (const l of await getTextLines(await ed.loaded.pdf.getPage(i + 1))) {
|
||||||
|
const hay = l.text.normalize('NFKC').toLowerCase();
|
||||||
|
for (let k = hay.indexOf(needle); k >= 0; k = hay.indexOf(needle, k + needle.length))
|
||||||
|
out.push({ i, pageId: ed.loaded.pageIds[i], snippet: l.text, rect: lineSubRect(l, k, needle.length) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setRes(out);
|
||||||
|
});
|
||||||
|
return (
|
||||||
|
<section className="panel">
|
||||||
|
<h3>{tr('ค้นหาข้อความ', 'Find text')}</h3>
|
||||||
|
<div className="inline">
|
||||||
|
<input id="search-input" autoFocus value={q} aria-label={tr('คำค้น', 'Search term')} onChange={(e) => setQ(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && go()} placeholder={tr('พิมพ์คำค้น แล้ว Enter', 'Type a term, then Enter')} />
|
||||||
|
<button className="btn" onClick={go}>{tr('ค้นหา', 'Search')}</button>
|
||||||
|
</div>
|
||||||
|
{res && <p className="hint">{tr(`พบ ${res.length} ตำแหน่ง`, `${res.length} match(es)`)}</p>}
|
||||||
|
<ul className="results">
|
||||||
|
{res?.map((r, k) => (
|
||||||
|
<li
|
||||||
|
key={k}
|
||||||
|
onClick={() => {
|
||||||
|
ed.gotoPage(r.i);
|
||||||
|
ed.setHit({ pageId: r.pageId, rect: r.rect });
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<b>{tr('หน้า', 'Page')} {r.i + 1}</b> {r.snippet}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function CommentList() {
|
||||||
|
const ed = useEditor();
|
||||||
|
const list = ed.doc.items.filter((i) => i.kind !== 'whiteout' && i.kind !== 'field' && i.kind !== 'redact');
|
||||||
|
if (!list.length) return null;
|
||||||
|
const label = (i: Item) =>
|
||||||
|
i.kind === 'note' ? `💬 ${i.text || tr('(ว่าง)', '(empty)')}` : i.kind === 'text' ? `T ${i.text}` : { highlight: tr('ไฮไลต์', 'Highlight'), ink: tr('ลายเส้น', 'Ink'), rect: tr('สี่เหลี่ยม', 'Rectangle'), ellipse: tr('วงรี', 'Ellipse'), line: tr('เส้น', 'Line'), arrow: tr('ลูกศร', 'Arrow'), image: tr('รูป/ลายเซ็น/ตรา', 'Image/signature/stamp') }[i.kind as string];
|
||||||
|
return (
|
||||||
|
<section className="panel">
|
||||||
|
<h3>{tr('รายการ', 'Items')} ({list.length})</h3>
|
||||||
|
<ul className="results">
|
||||||
|
{list.map((i) => (
|
||||||
|
<li
|
||||||
|
key={i.id}
|
||||||
|
className={ed.selectedId === i.id ? 'on' : ''}
|
||||||
|
onClick={() => {
|
||||||
|
ed.gotoPage(ed.doc.pageIds.indexOf(i.pageId));
|
||||||
|
ed.setTool('select');
|
||||||
|
ed.select(i.id);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<b>{tr('หน้า', 'Page')} {ed.doc.pageIds.indexOf(i.pageId) + 1}</b> {label(i)}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
import { useEffect, useRef, useState } from 'react';
|
||||||
|
import type React from 'react';
|
||||||
|
import { useEditor } from '../editor';
|
||||||
|
import { loadSignatures, saveSignatures } from '../lib/stamps';
|
||||||
|
import { fileToDataUrl, loadImage, pickFiles, trimCanvas } from '../lib/util';
|
||||||
|
import { tr } from '../i18n';
|
||||||
|
import { Dialog } from './Dialog';
|
||||||
|
|
||||||
|
type Mode = 'draw' | 'type' | 'upload';
|
||||||
|
const FONTS = ['"Segoe Script", "Brush Script MT", cursive', '"Lucida Handwriting", cursive', 'Sarabun', 'Georgia, serif'];
|
||||||
|
|
||||||
|
export function SignatureModal({ onClose }: { onClose: () => void }) {
|
||||||
|
const ed = useEditor();
|
||||||
|
const [mode, setMode] = useState<Mode>('draw');
|
||||||
|
const [color, setColor] = useState('#0b1f6b');
|
||||||
|
const [typed, setTyped] = useState('');
|
||||||
|
const [font, setFont] = useState(FONTS[0]);
|
||||||
|
const [upload, setUpload] = useState<string | null>(null);
|
||||||
|
const [empty, setEmpty] = useState(true);
|
||||||
|
const canvas = useRef<HTMLCanvasElement>(null);
|
||||||
|
const last = useRef<{ x: number; y: number } | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const c = canvas.current;
|
||||||
|
if (!c) return;
|
||||||
|
const dpr = window.devicePixelRatio || 1;
|
||||||
|
c.width = 640 * dpr;
|
||||||
|
c.height = 220 * dpr;
|
||||||
|
const ctx = c.getContext('2d')!;
|
||||||
|
ctx.scale(dpr, dpr);
|
||||||
|
setEmpty(true);
|
||||||
|
}, [mode]);
|
||||||
|
|
||||||
|
const pos = (e: React.PointerEvent) => {
|
||||||
|
const r = canvas.current!.getBoundingClientRect();
|
||||||
|
return { x: ((e.clientX - r.left) * 640) / r.width, y: ((e.clientY - r.top) * 220) / r.height };
|
||||||
|
};
|
||||||
|
const draw = (e: React.PointerEvent) => {
|
||||||
|
if (!last.current) return;
|
||||||
|
const p = pos(e);
|
||||||
|
const ctx = canvas.current!.getContext('2d')!;
|
||||||
|
ctx.strokeStyle = color;
|
||||||
|
ctx.lineWidth = 2.6;
|
||||||
|
ctx.lineCap = 'round';
|
||||||
|
ctx.lineJoin = 'round';
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.moveTo(last.current.x, last.current.y);
|
||||||
|
ctx.lineTo(p.x, p.y);
|
||||||
|
ctx.stroke();
|
||||||
|
last.current = p;
|
||||||
|
setEmpty(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
async function result(): Promise<string | null> {
|
||||||
|
if (mode === 'draw') return empty ? null : trimCanvas(canvas.current!, 6).toDataURL('image/png');
|
||||||
|
if (mode === 'type') {
|
||||||
|
if (!typed.trim()) return null;
|
||||||
|
await document.fonts.load(`64px ${font}`).catch(() => {});
|
||||||
|
const c = document.createElement('canvas');
|
||||||
|
c.width = 1400;
|
||||||
|
c.height = 240;
|
||||||
|
const ctx = c.getContext('2d')!;
|
||||||
|
ctx.font = `96px ${font}`;
|
||||||
|
ctx.fillStyle = color;
|
||||||
|
ctx.textBaseline = 'middle';
|
||||||
|
ctx.fillText(typed, 20, 120);
|
||||||
|
return trimCanvas(c, 6).toDataURL('image/png');
|
||||||
|
}
|
||||||
|
return upload;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function onUpload() {
|
||||||
|
const [f] = await pickFiles('image/*');
|
||||||
|
if (!f) return;
|
||||||
|
const im = await loadImage(await fileToDataUrl(f));
|
||||||
|
const c = document.createElement('canvas');
|
||||||
|
const k = Math.min(1, 1200 / im.naturalWidth);
|
||||||
|
c.width = im.naturalWidth * k;
|
||||||
|
c.height = im.naturalHeight * k;
|
||||||
|
const ctx = c.getContext('2d')!;
|
||||||
|
ctx.drawImage(im, 0, 0, c.width, c.height);
|
||||||
|
// Make near-white paper transparent so scanned signatures sit cleanly on the page.
|
||||||
|
const d = ctx.getImageData(0, 0, c.width, c.height);
|
||||||
|
for (let i = 0; i < d.data.length; i += 4) {
|
||||||
|
const l = (d.data[i] + d.data[i + 1] + d.data[i + 2]) / 3;
|
||||||
|
if (l > 225) d.data[i + 3] = 0;
|
||||||
|
else if (l > 180) d.data[i + 3] = Math.round(((225 - l) / 45) * 255);
|
||||||
|
}
|
||||||
|
ctx.putImageData(d, 0, 0);
|
||||||
|
setUpload(trimCanvas(c, 4).toDataURL('image/png'));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function apply() {
|
||||||
|
const url = await result();
|
||||||
|
if (!url) return;
|
||||||
|
saveSignatures([url, ...loadSignatures().filter((s) => s !== url)]);
|
||||||
|
window.dispatchEvent(new Event('signatures-changed'));
|
||||||
|
const im = await loadImage(url);
|
||||||
|
const w = 150;
|
||||||
|
ed.setOpts({ pending: { dataUrl: url, w, h: (w * im.naturalHeight) / im.naturalWidth } });
|
||||||
|
ed.setTab('sign');
|
||||||
|
ed.setTool('sign');
|
||||||
|
onClose();
|
||||||
|
}
|
||||||
|
|
||||||
|
const inkNames: Record<string, string> = { '#0b1f6b': tr('น้ำเงินเข้ม', 'Navy'), '#000000': tr('ดำ', 'Black'), '#1f4fbf': tr('น้ำเงิน', 'Blue') };
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog
|
||||||
|
title={tr('สร้างลายเซ็น', 'Create signature')}
|
||||||
|
onClose={onClose}
|
||||||
|
className="sig-modal"
|
||||||
|
footer={
|
||||||
|
<>
|
||||||
|
{mode === 'draw' && (
|
||||||
|
<button
|
||||||
|
className="btn"
|
||||||
|
onClick={() => {
|
||||||
|
const c = canvas.current!;
|
||||||
|
c.getContext('2d')!.clearRect(0, 0, c.width, c.height);
|
||||||
|
setEmpty(true);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{tr('ล้าง', 'Clear')}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
<span className="spacer" />
|
||||||
|
<button className="btn" onClick={onClose}>{tr('ยกเลิก', 'Cancel')}</button>
|
||||||
|
<button className="btn primary" onClick={apply}>{tr('ใช้ลายเซ็นนี้', 'Use this signature')}</button>
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<div className="sig-bar">
|
||||||
|
<nav className="tabs small" role="tablist" aria-label={tr('วิธีสร้างลายเซ็น', 'How to create it')}>
|
||||||
|
{(['draw', 'type', 'upload'] as Mode[]).map((m) => (
|
||||||
|
<button key={m} role="tab" aria-selected={mode === m} className={mode === m ? 'on' : ''} onClick={() => setMode(m)}>
|
||||||
|
{{ draw: tr('วาด', 'Draw'), type: tr('พิมพ์', 'Type'), upload: tr('อัปโหลดรูป', 'Upload image') }[m]}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</nav>
|
||||||
|
<div className="swatches" role="group" aria-label={tr('สีหมึก', 'Ink colour')}>
|
||||||
|
{['#0b1f6b', '#000000', '#1f4fbf'].map((c) => (
|
||||||
|
<button key={c} className={`sw${color === c ? ' on' : ''}`} style={{ background: c }} aria-pressed={color === c} aria-label={inkNames[c]} title={inkNames[c]} onClick={() => setColor(c)} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="sig-area">
|
||||||
|
{mode === 'draw' && (
|
||||||
|
<canvas
|
||||||
|
ref={canvas}
|
||||||
|
className="sig-canvas"
|
||||||
|
aria-label={tr('พื้นที่วาดลายเซ็น — ใช้เมาส์ นิ้ว หรือปากกา (ใช้คีย์บอร์ดให้เลือก “พิมพ์”)', 'Signature pad — draw with mouse, finger or pen (keyboard users: choose “Type”)')}
|
||||||
|
onPointerDown={(e) => {
|
||||||
|
e.currentTarget.setPointerCapture(e.pointerId);
|
||||||
|
last.current = pos(e);
|
||||||
|
}}
|
||||||
|
onPointerMove={draw}
|
||||||
|
onPointerUp={() => (last.current = null)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{mode === 'type' && (
|
||||||
|
<div className="sig-type">
|
||||||
|
<input autoFocus value={typed} aria-label={tr('ชื่อที่จะใช้เป็นลายเซ็น', 'Name to use as signature')} onChange={(e) => setTyped(e.target.value)} placeholder={tr('พิมพ์ชื่อ', 'Type your name')} />
|
||||||
|
<div className="font-list" role="radiogroup" aria-label={tr('แบบลายมือ', 'Style')}>
|
||||||
|
{FONTS.map((f) => (
|
||||||
|
<button key={f} role="radio" aria-checked={font === f} className={font === f ? 'on' : ''} style={{ fontFamily: f, color }} onClick={() => setFont(f)}>
|
||||||
|
{typed || 'ลายเซ็น Signature'}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{mode === 'upload' && (
|
||||||
|
<div className="sig-upload">
|
||||||
|
{upload ? <img src={upload} alt={tr('ตัวอย่างลายเซ็นที่อัปโหลด', 'Uploaded signature preview')} /> : <p className="hint">{tr('รูปลายเซ็นบนกระดาษขาว — พื้นขาวจะถูกทำให้โปร่งใส', 'A photo of your signature on white paper — the white is made transparent')}</p>}
|
||||||
|
<button className="btn" onClick={onUpload}>{tr('เลือกรูป…', 'Choose image…')}</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<p className="hint sig-note">{tr('ลายเซ็นเก็บไว้ในเบราว์เซอร์นี้เท่านั้น ใช้ซ้ำได้ครั้งหน้า ไม่ถูกส่งไปไหน', 'Signatures are kept only in this browser for next time. They are never sent anywhere.')}</p>
|
||||||
|
</div>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
import { useEffect, useRef, useState } from 'react';
|
||||||
|
import type React from 'react';
|
||||||
|
import { RotateCw, Trash2 } from 'lucide-react';
|
||||||
|
import { useEditor } from '../editor';
|
||||||
|
import { deletePages, reorderPages, rotatePages } from '../lib/pageops';
|
||||||
|
import { tr } from '../i18n';
|
||||||
|
|
||||||
|
const TW = 118;
|
||||||
|
|
||||||
|
export function Thumbnails() {
|
||||||
|
const ed = useEditor();
|
||||||
|
const ids = ed.loaded.pageIds;
|
||||||
|
const [from, setFrom] = useState<number | null>(null);
|
||||||
|
const [over, setOver] = useState<number | null>(null);
|
||||||
|
const anchor = useRef(0);
|
||||||
|
|
||||||
|
const click = (e: React.MouseEvent, i: number) => {
|
||||||
|
const id = ids[i];
|
||||||
|
if (e.ctrlKey || e.metaKey) ed.setSelPages(ed.selPages.includes(id) ? ed.selPages.filter((x) => x !== id) : [...ed.selPages, id]);
|
||||||
|
else if (e.shiftKey) {
|
||||||
|
const [a, b] = [Math.min(anchor.current, i), Math.max(anchor.current, i)];
|
||||||
|
ed.setSelPages(ids.slice(a, b + 1));
|
||||||
|
} else ed.setSelPages([id]);
|
||||||
|
if (!e.shiftKey) anchor.current = i;
|
||||||
|
ed.gotoPage(i);
|
||||||
|
};
|
||||||
|
|
||||||
|
const move = (f: number, to: number) => {
|
||||||
|
if (f === to || f + 1 === to) return;
|
||||||
|
const order = ids.map((_, i) => i);
|
||||||
|
const [m] = order.splice(f, 1);
|
||||||
|
order.splice(to > f ? to - 1 : to, 0, m);
|
||||||
|
ed.run(tr('จัดเรียงหน้า…', 'Reordering pages…'), async () => ed.setBytes(await reorderPages(ed.doc.bytes, order), order.map((i) => ids[i])));
|
||||||
|
};
|
||||||
|
const drop = (to: number) => {
|
||||||
|
const f = from;
|
||||||
|
setFrom(null);
|
||||||
|
setOver(null);
|
||||||
|
if (f !== null) move(f, to);
|
||||||
|
};
|
||||||
|
// Keyboard: arrows move focus between pages, Alt+arrows move the page itself.
|
||||||
|
const onKey = (e: React.KeyboardEvent, i: number) => {
|
||||||
|
const d = e.key === 'ArrowDown' ? 1 : e.key === 'ArrowUp' ? -1 : 0;
|
||||||
|
if (!d) return;
|
||||||
|
e.preventDefault();
|
||||||
|
const j = i + d;
|
||||||
|
if (j < 0 || j >= ids.length) return;
|
||||||
|
if (e.altKey) {
|
||||||
|
move(i, d > 0 ? i + 2 : i - 1);
|
||||||
|
ed.toast(tr(`ย้ายหน้า ${i + 1} ไปเป็นหน้า ${j + 1}`, `Moved page ${i + 1} to ${j + 1}`));
|
||||||
|
}
|
||||||
|
const picks = e.currentTarget.closest('.thumbs')!.querySelectorAll<HTMLElement>('.thumb-pick');
|
||||||
|
picks[j]?.focus();
|
||||||
|
};
|
||||||
|
const remove = (i: number) =>
|
||||||
|
ed.run(tr('ลบหน้า…', 'Deleting page…'), async () => {
|
||||||
|
ed.setBytes(await deletePages(ed.doc.bytes, [i]), ids.filter((_, k) => k !== i));
|
||||||
|
ed.toast(tr(`ลบหน้า ${i + 1} แล้ว`, `Deleted page ${i + 1}`), { label: tr('เลิกทำ', 'Undo'), fn: ed.undo });
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<nav className="thumbs" aria-label={tr('หน้าในเอกสาร', 'Pages')} onDragOver={(e) => e.preventDefault()}>
|
||||||
|
{ids.map((id, i) => {
|
||||||
|
const selected = ed.selPages.includes(id);
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={id}
|
||||||
|
className={`thumb${ed.current === i ? ' cur' : ''}${selected ? ' sel' : ''}${over === i ? ' over' : ''}`}
|
||||||
|
draggable
|
||||||
|
onDragStart={() => setFrom(i)}
|
||||||
|
onDragOver={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setOver(i);
|
||||||
|
}}
|
||||||
|
onDragLeave={() => setOver((o) => (o === i ? null : o))}
|
||||||
|
onDrop={() => drop(i)}
|
||||||
|
onDragEnd={() => {
|
||||||
|
setFrom(null);
|
||||||
|
setOver(null);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
className="thumb-pick"
|
||||||
|
aria-pressed={selected}
|
||||||
|
aria-current={ed.current === i ? 'page' : undefined}
|
||||||
|
aria-label={tr(`หน้า ${i + 1}`, `Page ${i + 1}`)}
|
||||||
|
title={tr('คลิกเพื่อไปหน้านี้ · Ctrl/Shift+คลิก เลือกหลายหน้า · Alt+↑/↓ ย้ายหน้า', 'Click to go here · Ctrl/Shift+click to select several · Alt+↑/↓ to move')}
|
||||||
|
onClick={(e) => click(e, i)}
|
||||||
|
onKeyDown={(e) => onKey(e, i)}
|
||||||
|
>
|
||||||
|
<Thumb index={i} />
|
||||||
|
</button>
|
||||||
|
<div className="thumb-bar">
|
||||||
|
<span aria-hidden>{i + 1}</span>
|
||||||
|
<button
|
||||||
|
aria-label={tr(`หมุนหน้า ${i + 1}`, `Rotate page ${i + 1}`)}
|
||||||
|
title={tr('หมุน', 'Rotate')}
|
||||||
|
onClick={() => ed.run(tr('หมุนหน้า…', 'Rotating page…'), async () => ed.setBytes(await rotatePages(ed.doc.bytes, [i], 90), ids))}
|
||||||
|
>
|
||||||
|
<RotateCw size={15} />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
aria-label={tr(`ลบหน้า ${i + 1}`, `Delete page ${i + 1}`)}
|
||||||
|
title={tr('ลบหน้า', 'Delete page')}
|
||||||
|
disabled={ids.length < 2}
|
||||||
|
onClick={() => remove(i)}
|
||||||
|
>
|
||||||
|
<Trash2 size={15} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
<div className={`thumb-end${over === ids.length ? ' over' : ''}`} onDragOver={(e) => { e.preventDefault(); setOver(ids.length); }} onDrop={() => drop(ids.length)} />
|
||||||
|
</nav>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Thumb({ index }: { index: number }) {
|
||||||
|
const ed = useEditor();
|
||||||
|
const ref = useRef<HTMLCanvasElement>(null);
|
||||||
|
const [vis, setVis] = useState(false);
|
||||||
|
const size = ed.loaded.sizes[index];
|
||||||
|
const h = size ? (TW * size.h) / size.w : TW * 1.4;
|
||||||
|
useEffect(() => {
|
||||||
|
const io = new IntersectionObserver(([e]) => e.isIntersecting && setVis(true), { rootMargin: '400px' });
|
||||||
|
io.observe(ref.current!);
|
||||||
|
return () => io.disconnect();
|
||||||
|
}, []);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!vis) return;
|
||||||
|
let task: { cancel(): void; promise: Promise<unknown> } | null = null;
|
||||||
|
let alive = true;
|
||||||
|
ed.loaded.pdf.getPage(index + 1).then((p) => {
|
||||||
|
if (!alive || !ref.current) return;
|
||||||
|
const vp1 = p.getViewport({ scale: 1 });
|
||||||
|
const vp = p.getViewport({ scale: (TW * 2) / vp1.width });
|
||||||
|
const c = ref.current;
|
||||||
|
c.width = vp.width;
|
||||||
|
c.height = vp.height;
|
||||||
|
task = p.render({ canvasContext: c.getContext('2d')!, viewport: vp });
|
||||||
|
task.promise.catch(() => {});
|
||||||
|
}, () => {});
|
||||||
|
return () => {
|
||||||
|
alive = false;
|
||||||
|
task?.cancel();
|
||||||
|
};
|
||||||
|
}, [vis, ed.loaded.pdf, index]);
|
||||||
|
return <canvas ref={ref} style={{ width: TW, height: h }} />;
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
import { useEditor } from '../editor';
|
||||||
|
import { appendPdfs, deletePages, extractPages, imagesToPdf, insertBlank, rotatePages } from '../lib/pageops';
|
||||||
|
import { baseName, download, pickFiles, readFile, uid } from '../lib/util';
|
||||||
|
import { tr } from '../i18n';
|
||||||
|
|
||||||
|
/** Page operations on the selected pages (or the current page), shared by the ribbon, panel and thumbnails. */
|
||||||
|
export function usePageOps() {
|
||||||
|
const ed = useEditor();
|
||||||
|
const ids = ed.doc.pageIds;
|
||||||
|
const sel = ed.selPages.length ? ed.selPages : [ids[ed.current]].filter(Boolean);
|
||||||
|
const idxs = sel.map((id) => ids.indexOf(id)).filter((i) => i >= 0).sort((a, b) => a - b);
|
||||||
|
const name = baseName(ed.doc.name);
|
||||||
|
|
||||||
|
const op = (label: string, fn: () => Promise<{ bytes: Uint8Array; ids: string[] }>, done?: string) =>
|
||||||
|
ed.run(label, async () => {
|
||||||
|
const r = await fn();
|
||||||
|
ed.setBytes(r.bytes, r.ids);
|
||||||
|
if (done) ed.toast(done, { label: tr('เลิกทำ', 'Undo'), fn: ed.undo });
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
idxs,
|
||||||
|
rotate: (delta: number, at = idxs) => op(tr('หมุนหน้า…', 'Rotating pages…'), async () => ({ bytes: await rotatePages(ed.doc.bytes, at, delta), ids })),
|
||||||
|
canDelete: (at = idxs) => at.length > 0 && at.length < ids.length,
|
||||||
|
remove: (at = idxs) =>
|
||||||
|
op(
|
||||||
|
tr('ลบหน้า…', 'Deleting pages…'),
|
||||||
|
async () => ({ bytes: await deletePages(ed.doc.bytes, at), ids: ids.filter((_, i) => !at.includes(i)) }),
|
||||||
|
tr(`ลบหน้า ${at.map((i) => i + 1).join(', ')} แล้ว`, `Deleted page ${at.map((i) => i + 1).join(', ')}`),
|
||||||
|
),
|
||||||
|
insertBlank: () => {
|
||||||
|
const at = (idxs[idxs.length - 1] ?? ed.current) + 1;
|
||||||
|
return op(tr('แทรกหน้าว่าง…', 'Inserting blank page…'), async () => ({ bytes: await insertBlank(ed.doc.bytes, at), ids: [...ids.slice(0, at), uid(), ...ids.slice(at)] }));
|
||||||
|
},
|
||||||
|
merge: async () => {
|
||||||
|
const files = await pickFiles('application/pdf', true);
|
||||||
|
if (!files.length) return;
|
||||||
|
await op(tr('รวมไฟล์…', 'Merging…'), async () => {
|
||||||
|
const r = await appendPdfs(ed.doc.bytes, await Promise.all(files.map(readFile)));
|
||||||
|
return { bytes: r.bytes, ids: [...ids, ...Array.from({ length: r.added }, uid)] };
|
||||||
|
});
|
||||||
|
},
|
||||||
|
addImages: async () => {
|
||||||
|
const files = await pickFiles('image/*', true);
|
||||||
|
if (!files.length) return;
|
||||||
|
await op(tr('แทรกรูป…', 'Inserting images…'), async () => {
|
||||||
|
const r = await imagesToPdf(files, ed.doc.bytes);
|
||||||
|
return { bytes: r.bytes, ids: [...ids, ...Array.from({ length: r.added }, uid)] };
|
||||||
|
});
|
||||||
|
},
|
||||||
|
extract: () =>
|
||||||
|
ed.run(tr('แยกหน้า…', 'Extracting pages…'), async () => {
|
||||||
|
const out = await ed.exportBytes();
|
||||||
|
download(await extractPages(out, idxs), `${name}-pages-${idxs.map((i) => i + 1).join('_')}.pdf`);
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import { createContext, useContext } from 'react';
|
||||||
|
import type { PDFDocumentProxy } from './lib/pdfjs';
|
||||||
|
import type { DocState, Rect, Tab, Tool, ToolOpts } from './lib/types';
|
||||||
|
import type { Lang } from './i18n';
|
||||||
|
|
||||||
|
export type Loaded = { bytes: Uint8Array; pdf: PDFDocumentProxy; sizes: { w: number; h: number }[]; pageIds: string[] };
|
||||||
|
|
||||||
|
export type ToastAction = { label: string; fn: () => void };
|
||||||
|
|
||||||
|
export type Editor = {
|
||||||
|
/** Current UI language; part of the context so consumers re-render on switch. */
|
||||||
|
lang: Lang;
|
||||||
|
doc: DocState;
|
||||||
|
loaded: Loaded;
|
||||||
|
commit: (fn: (d: DocState) => DocState) => void;
|
||||||
|
/** Replace the PDF bytes after a page operation; items on removed pages are dropped. */
|
||||||
|
setBytes: (bytes: Uint8Array, pageIds: string[]) => void;
|
||||||
|
undo: () => void;
|
||||||
|
redo: () => void;
|
||||||
|
canUndo: boolean;
|
||||||
|
canRedo: boolean;
|
||||||
|
tool: Tool;
|
||||||
|
setTool: (t: Tool) => void;
|
||||||
|
opts: ToolOpts;
|
||||||
|
setOpts: (p: Partial<ToolOpts>) => void;
|
||||||
|
selectedId: string | null;
|
||||||
|
select: (id: string | null) => void;
|
||||||
|
editingId: string | null;
|
||||||
|
setEditing: (id: string | null) => void;
|
||||||
|
scale: number;
|
||||||
|
setScale: (s: number) => void;
|
||||||
|
tab: Tab;
|
||||||
|
setTab: (t: Tab) => void;
|
||||||
|
selPages: string[];
|
||||||
|
setSelPages: (ids: string[]) => void;
|
||||||
|
current: number;
|
||||||
|
gotoPage: (i: number) => void;
|
||||||
|
hit: { pageId: string; rect: Rect } | null;
|
||||||
|
setHit: (h: { pageId: string; rect: Rect } | null) => void;
|
||||||
|
run: (label: string, fn: () => Promise<void>) => Promise<void>;
|
||||||
|
/** Show a status message; `action` adds a button (e.g. Undo) to it. */
|
||||||
|
toast: (msg: string, action?: ToastAction) => void;
|
||||||
|
exportBytes: () => Promise<Uint8Array>;
|
||||||
|
flatten: boolean;
|
||||||
|
setFlatten: (v: boolean) => void;
|
||||||
|
openSignature: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const EditorCtx = createContext<Editor | null>(null);
|
||||||
|
export const useEditor = () => useContext(EditorCtx)!;
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import { useSyncExternalStore } from 'react';
|
||||||
|
|
||||||
|
export type Lang = 'th' | 'en';
|
||||||
|
|
||||||
|
const KEY = 'loma.lang';
|
||||||
|
const listeners = new Set<() => void>();
|
||||||
|
|
||||||
|
function initialLang(): Lang {
|
||||||
|
try {
|
||||||
|
const saved = localStorage.getItem(KEY);
|
||||||
|
if (saved === 'th' || saved === 'en') return saved;
|
||||||
|
} catch {
|
||||||
|
/* storage unavailable: fall back to the browser language */
|
||||||
|
}
|
||||||
|
return navigator.language?.toLowerCase().startsWith('th') ? 'th' : 'en';
|
||||||
|
}
|
||||||
|
|
||||||
|
let current: Lang = initialLang();
|
||||||
|
document.documentElement.lang = current;
|
||||||
|
|
||||||
|
export const getLang = () => current;
|
||||||
|
|
||||||
|
export function setLang(lang: Lang) {
|
||||||
|
if (lang === current) return;
|
||||||
|
current = lang;
|
||||||
|
document.documentElement.lang = lang;
|
||||||
|
try {
|
||||||
|
localStorage.setItem(KEY, lang);
|
||||||
|
} catch {
|
||||||
|
/* preference just won't persist */
|
||||||
|
}
|
||||||
|
listeners.forEach((f) => f());
|
||||||
|
}
|
||||||
|
|
||||||
|
function subscribe(f: () => void) {
|
||||||
|
listeners.add(f);
|
||||||
|
return () => listeners.delete(f);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Current UI language; re-renders the caller when it changes. */
|
||||||
|
export const useLang = () => useSyncExternalStore(subscribe, getLang);
|
||||||
|
|
||||||
|
/** Pick the string for the current UI language. Evaluate at render/call time, not at module load. */
|
||||||
|
export const tr = (th: string, en: string) => (current === 'th' ? th : en);
|
||||||
|
|
||||||
|
/** Locale for dates/numbers in the current UI language. */
|
||||||
|
export const locale = () => (current === 'th' ? 'th-TH' : 'en-GB');
|
||||||
@@ -0,0 +1,294 @@
|
|||||||
|
@font-face { font-family: 'Sarabun'; src: url('/fonts/Sarabun-Regular.ttf') format('truetype'); font-weight: 400; font-display: swap; }
|
||||||
|
@font-face { font-family: 'Sarabun'; src: url('/fonts/Sarabun-Bold.ttf') format('truetype'); font-weight: 700; font-display: swap; }
|
||||||
|
|
||||||
|
:root {
|
||||||
|
/* Loma family palette (shared with Lomalotto): brand blue #1164C2, navy gradient header, slate neutrals. */
|
||||||
|
--bg: #eef3f8;
|
||||||
|
--panel: #ffffff;
|
||||||
|
--panel-2: #f1f5f9;
|
||||||
|
--line: #dbe2ea;
|
||||||
|
--text: #0f172a;
|
||||||
|
--muted: #475569;
|
||||||
|
--brand: #1164c2;
|
||||||
|
--brand-strong: #0e509c;
|
||||||
|
--brand-soft: #e2e7f3;
|
||||||
|
--brand-line: #c3cee8;
|
||||||
|
--brand-ink: #ffffff;
|
||||||
|
--brand-light: #a0b2dc;
|
||||||
|
--brand-navy: #0b2b7c;
|
||||||
|
--accent: var(--brand);
|
||||||
|
--accent-soft: var(--brand-soft);
|
||||||
|
--danger: #dc2626;
|
||||||
|
--blue: #1164c2;
|
||||||
|
--focus: #1164c2;
|
||||||
|
--top: linear-gradient(135deg, #0b2b7c 0%, #1164c2 46%, #081d63 100%);
|
||||||
|
--top-solid: #0b2b7c;
|
||||||
|
--top-text: #ffffff;
|
||||||
|
--top-muted: #e2e7f3;
|
||||||
|
font-family: 'Sarabun', 'Segoe UI', system-ui, sans-serif;
|
||||||
|
font-size: 14px;
|
||||||
|
color: var(--text);
|
||||||
|
background: var(--bg);
|
||||||
|
}
|
||||||
|
* { box-sizing: border-box; }
|
||||||
|
html, body, #root { margin: 0; height: 100%; }
|
||||||
|
button { font: inherit; color: inherit; cursor: pointer; }
|
||||||
|
button:disabled { opacity: 0.45; cursor: default; }
|
||||||
|
input, select, textarea { font: inherit; color: inherit; }
|
||||||
|
|
||||||
|
/* ---------- start screen ---------- */
|
||||||
|
.start { min-height: 100%; display: grid; place-items: center; background: var(--top) top / 100% 300px no-repeat, var(--bg); padding: 72px 16px 24px; }
|
||||||
|
.start.drag { outline: 3px dashed var(--accent); outline-offset: -16px; }
|
||||||
|
.start { position: relative; }
|
||||||
|
.start-lang { position: absolute; top: 16px; right: 16px; }
|
||||||
|
.start-lang .tb { color: var(--text); border: 1px solid var(--line); background: var(--panel); }
|
||||||
|
.start-lang .tb:hover { background: var(--bg); }
|
||||||
|
.start-card { max-width: 640px; width: 100%; text-align: center; background: var(--panel); border-radius: 16px; padding: 40px 32px 32px; box-shadow: 0 1px 2px rgba(8,29,99,.06), 0 12px 40px rgba(8,29,99,.08); }
|
||||||
|
.logo { font-weight: 700; font-size: 34px; letter-spacing: -.5px; }
|
||||||
|
.logo { display: inline-flex; align-items: center; gap: 10px; color: var(--text); }
|
||||||
|
.logo span { color: var(--brand); font-weight: 400; }
|
||||||
|
.logo.small { font-size: 18px; color: var(--top-text); gap: 8px; }
|
||||||
|
.logo.small .logo-word { color: var(--top-text); font-weight: 700; }
|
||||||
|
.start-actions { display: flex; gap: 10px; justify-content: center; flex-wrap: wrap; margin: 24px 0 8px; }
|
||||||
|
.start-title { font-size: 26px; line-height: 1.35; margin: 20px 0 6px; text-wrap: balance; }
|
||||||
|
.start-sub { display: inline-flex; align-items: center; gap: 6px; margin: 0; color: var(--brand-strong); font-size: 15px; }
|
||||||
|
.features { list-style: none; padding: 20px 0 0; margin: 20px 0 0; border-top: 1px solid var(--line); display: grid; grid-template-columns: 1fr 1fr; gap: 8px 20px; text-align: left; }
|
||||||
|
.features li { display: flex; align-items: flex-start; gap: 8px; font-size: 14px; color: var(--text); line-height: 1.45; }
|
||||||
|
.features li svg { color: var(--brand); flex: none; margin-top: 3px; }
|
||||||
|
|
||||||
|
/* ---------- buttons ---------- */
|
||||||
|
.btn { display: inline-flex; align-items: center; justify-content: center; gap: 6px; border: 1px solid var(--line); background: #fff; border-radius: 8px; padding: 6px 12px; min-height: 32px; }
|
||||||
|
.btn:hover:not(:disabled) { border-color: #b9bec8; background: #f7f8fa; }
|
||||||
|
.btn.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
|
||||||
|
.btn.primary:hover:not(:disabled) { background: var(--brand-strong); border-color: var(--brand-strong); }
|
||||||
|
.btn.danger, .tool.danger { color: var(--danger); }
|
||||||
|
.btn.big { padding: 10px 18px; font-size: 15px; }
|
||||||
|
.icon-btn { border: 1px solid var(--line); background: #fff; border-radius: 6px; width: 32px; height: 30px; display: inline-grid; place-items: center; }
|
||||||
|
.icon-btn.on { background: var(--brand-soft); border-color: var(--brand); color: var(--brand-strong); }
|
||||||
|
|
||||||
|
/* ---------- app layout ---------- */
|
||||||
|
.app { height: 100%; display: flex; flex-direction: column; }
|
||||||
|
.topbar { display: flex; align-items: center; gap: 6px; padding: 6px 12px; background: var(--top); background-color: var(--top-solid); color: var(--top-text); }
|
||||||
|
.topbar .doc-name { max-width: 280px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--top-muted); margin: 0 4px 0 8px; }
|
||||||
|
.tb { display: inline-flex; align-items: center; gap: 5px; background: transparent; border: 0; color: var(--top-text); padding: 6px 9px; border-radius: 6px; min-height: 34px; }
|
||||||
|
.tb:hover:not(:disabled) { background: rgba(255,255,255,.1); }
|
||||||
|
/* Like Lomalotto's active nav: white pill with brand text on the blue bar. */
|
||||||
|
.tb.primary { background: #fff; color: var(--brand); font-weight: 700; box-shadow: 0 2px 8px rgba(8,29,99,.25); }
|
||||||
|
.tb.primary:hover:not(:disabled) { background: var(--brand-soft); }
|
||||||
|
.sep { width: 1px; height: 22px; background: rgba(255,255,255,.3); margin: 0 4px; }
|
||||||
|
.spacer { flex: 1; }
|
||||||
|
.zoom { min-width: 46px; text-align: center; font-variant-numeric: tabular-nums; }
|
||||||
|
.page-ind { color: var(--top-muted); margin-right: 8px; font-variant-numeric: tabular-nums; }
|
||||||
|
|
||||||
|
.ribbon { background: var(--panel); border-bottom: 1px solid var(--line); }
|
||||||
|
.tabs { display: flex; gap: 2px; padding: 0 10px; overflow-x: auto; border-bottom: 1px solid var(--line); }
|
||||||
|
.tabs button { background: none; border: 0; padding: 9px 14px; border-bottom: 2px solid transparent; color: var(--muted); white-space: nowrap; font-size: 14.5px; }
|
||||||
|
.tabs button:hover:not(.on) { color: var(--text); }
|
||||||
|
.tabs button.on { color: var(--brand-strong); border-bottom-color: var(--brand); font-weight: 700; }
|
||||||
|
.tabs.small { border-bottom: 0; padding: 0; align-items: center; gap: 4px; }
|
||||||
|
.tools { display: flex; gap: 4px; padding: 6px 10px; align-items: center; overflow-x: auto; min-height: 58px; }
|
||||||
|
.tool { display: flex; flex-direction: column; align-items: center; gap: 3px; background: none; border: 1px solid transparent; border-radius: 8px; padding: 5px 10px; min-width: 64px; font-size: 13px; color: #334155; white-space: nowrap; }
|
||||||
|
.tool:hover:not(:disabled) { background: var(--panel-2); }
|
||||||
|
.tool.on { background: var(--brand-soft); border-color: var(--brand-line); color: var(--brand-strong); }
|
||||||
|
.tools-hint { color: var(--muted); display: inline-flex; gap: 6px; align-items: center; padding-left: 6px; }
|
||||||
|
|
||||||
|
.main { flex: 1; display: flex; min-height: 0; }
|
||||||
|
.main.loading { display: grid; place-items: center; color: var(--muted); }
|
||||||
|
.thumbs { width: 150px; flex: none; overflow-y: auto; background: var(--panel-2); border-right: 1px solid var(--line); padding: 12px 0; display: flex; flex-direction: column; align-items: center; gap: 12px; }
|
||||||
|
.thumb { position: relative; border: 2px solid transparent; border-radius: 4px; cursor: pointer; background: #fff; box-shadow: 0 1px 3px rgba(0,0,0,.15); }
|
||||||
|
.thumb canvas { display: block; }
|
||||||
|
.thumb.cur { border-color: #9aa3b2; }
|
||||||
|
.thumb.sel { border-color: var(--brand); }
|
||||||
|
.thumb.over { box-shadow: 0 -4px 0 var(--blue); }
|
||||||
|
.thumb-end { height: 30px; width: 118px; }
|
||||||
|
.thumb-end.over { box-shadow: 0 -4px 0 var(--blue); }
|
||||||
|
.thumb-bar { display: flex; align-items: center; justify-content: space-between; font-size: 12px; padding: 2px 4px; background: #fff; border-top: 1px solid #eee; }
|
||||||
|
.thumb-bar button { background: none; border: 0; padding: 4px; border-radius: 4px; color: var(--muted); opacity: 0; display: inline-grid; place-items: center; }
|
||||||
|
.thumb:hover .thumb-bar button, .thumb:focus-within .thumb-bar button, .thumb-bar button:focus-visible { opacity: 1; }
|
||||||
|
.thumb-bar button:hover:not(:disabled) { background: var(--panel-2); color: var(--text); }
|
||||||
|
.thumb-pick { display: block; padding: 0; border: 0; background: none; border-radius: 2px 2px 0 0; }
|
||||||
|
|
||||||
|
.viewer { flex: 1; overflow: auto; padding: 24px 32px 80px; display: flex; flex-direction: column; align-items: center; gap: 20px; }
|
||||||
|
.page-wrap { position: relative; flex: none; background: #fff; box-shadow: 0 2px 10px rgba(0,0,0,.12); }
|
||||||
|
.page-canvas { display: block; }
|
||||||
|
.page-loading { position: absolute; inset: 0; display: grid; place-items: center; color: var(--muted); }
|
||||||
|
|
||||||
|
.side { width: 290px; flex: none; overflow-y: auto; background: var(--panel); border-left: 1px solid var(--line); }
|
||||||
|
.panel { padding: 14px 16px; border-bottom: 1px solid var(--line); display: flex; flex-direction: column; gap: 8px; }
|
||||||
|
.panel h3 { margin: 6px 0 2px; font-size: 14px; }
|
||||||
|
.panel .row { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
|
||||||
|
.panel .row input[type=number], .panel .row select, .panel .row input:not([type]) { width: 140px; }
|
||||||
|
.panel input:not([type=color]):not([type=checkbox]):not([type=range]), .panel select, .panel textarea { border: 1px solid var(--line); border-radius: 6px; padding: 5px 8px; background: #fff; min-width: 0; }
|
||||||
|
.lbl { margin: 4px 0 0; font-size: 13px; color: var(--muted); }
|
||||||
|
.hint { margin: 0; font-size: 13.5px; color: var(--muted); line-height: 1.55; }
|
||||||
|
ul.hint { padding-left: 18px; }
|
||||||
|
.inline { display: flex; gap: 6px; align-items: center; }
|
||||||
|
.inline input:not([type=color]) { flex: 1; }
|
||||||
|
.grid2 { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; }
|
||||||
|
.btn-row { display: flex; gap: 6px; margin-top: 4px; }
|
||||||
|
.btn-row .btn { flex: 1; }
|
||||||
|
.check { display: flex; gap: 6px; align-items: flex-start; font-size: 13px; }
|
||||||
|
.swatches { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
|
||||||
|
.sw { width: 22px; height: 22px; border-radius: 50%; border: 1px solid rgba(0,0,0,.2); padding: 0; }
|
||||||
|
.sw.on, .swatches input[type=color].on { outline: 2px solid var(--brand); outline-offset: 2px; }
|
||||||
|
.sw.none { background: linear-gradient(135deg, #fff 45%, #e53935 45%, #e53935 55%, #fff 55%); }
|
||||||
|
.swatches input[type=color] { width: 28px; height: 24px; border: 0; padding: 0; background: none; }
|
||||||
|
.pending { max-width: 100%; max-height: 120px; object-fit: contain; border: 1px dashed var(--line); border-radius: 6px; padding: 6px; background: repeating-conic-gradient(#f3f3f3 0 25%, #fff 0 50%) 0 0/12px 12px; }
|
||||||
|
.stamps { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||||
|
.stamp-btn { border: 2px solid; border-radius: 6px; background: #fff; font-weight: 700; padding: 2px 8px; font-size: 12px; }
|
||||||
|
.sig-list { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; }
|
||||||
|
.sig { border: 1px solid var(--line); border-radius: 6px; background: #fff; padding: 6px; height: 64px; }
|
||||||
|
.sig img { max-width: 100%; max-height: 100%; }
|
||||||
|
.sig:hover { border-color: var(--accent); }
|
||||||
|
.results { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 2px; max-height: 360px; overflow-y: auto; }
|
||||||
|
.results li { padding: 6px 8px; border-radius: 6px; cursor: pointer; font-size: 13px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
.results li:hover, .results li.on { background: #f2f3f6; }
|
||||||
|
.results b { color: var(--muted); font-weight: 400; margin-right: 6px; }
|
||||||
|
.field-names { font-size: 12px; padding-left: 18px; max-height: 240px; overflow: auto; }
|
||||||
|
.progress { position: relative; height: 26px; background: #f0f1f4; border-radius: 6px; overflow: hidden; }
|
||||||
|
.progress div { position: absolute; inset: 0 auto 0 0; background: var(--brand-line); }
|
||||||
|
.progress span { position: relative; font-size: 12px; line-height: 26px; padding-left: 8px; }
|
||||||
|
.ocr-out { height: 180px; font-size: 12px; resize: vertical; }
|
||||||
|
|
||||||
|
/* ---------- page overlay ---------- */
|
||||||
|
.overlay { position: absolute; inset: 0; touch-action: none; }
|
||||||
|
.overlay.tool-text, .overlay.tool-note, .overlay.tool-image, .overlay.tool-sign, .overlay.tool-stamp { cursor: copy; }
|
||||||
|
.overlay.tool-highlight, .overlay.tool-rect, .overlay.tool-ellipse, .overlay.tool-line, .overlay.tool-arrow,
|
||||||
|
.overlay.tool-whiteout, .overlay.tool-redact, .overlay.tool-fieldText, .overlay.tool-fieldCheck, .overlay.tool-pen { cursor: crosshair; }
|
||||||
|
.item { position: absolute; pointer-events: none; }
|
||||||
|
.item.live { pointer-events: auto; cursor: move; }
|
||||||
|
.item.stroke-item, .item.stroke-item.live { pointer-events: none; }
|
||||||
|
.item.stroke-item svg { overflow: visible; }
|
||||||
|
.item.stroke-item.live .grab { pointer-events: stroke; cursor: move; }
|
||||||
|
.item.sel { outline: 1.5px dashed var(--blue); outline-offset: 2px; }
|
||||||
|
.item.k-highlight { mix-blend-mode: multiply; }
|
||||||
|
.item.k-redact { background: #000; outline: 1px solid #e53935; }
|
||||||
|
.item img { pointer-events: none; user-select: none; }
|
||||||
|
.text-view, .text-edit { white-space: pre; font-family: 'Sarabun', sans-serif; transform-origin: center; overflow: visible; }
|
||||||
|
.text-edit { border: 0; outline: 1.5px solid var(--blue); background: rgba(255,255,255,.92); padding: 0; margin: 0; resize: none; overflow: hidden; }
|
||||||
|
.item.k-text.live:hover:not(.sel) { outline: 1px dashed rgba(26,115,232,.5); }
|
||||||
|
.handle { position: absolute; right: -6px; bottom: -6px; width: 11px; height: 11px; background: #fff; border: 1.5px solid var(--blue); border-radius: 2px; cursor: nwse-resize; pointer-events: auto; }
|
||||||
|
.note-icon { width: 22px; height: 22px; border-radius: 4px; display: grid; place-items: center; font-size: 13px; box-shadow: 0 1px 3px rgba(0,0,0,.3); pointer-events: auto; cursor: pointer; }
|
||||||
|
.note-pop { position: absolute; z-index: 5; background: #fffbe6; border: 1px solid #e6d27a; border-radius: 6px; box-shadow: 0 4px 14px rgba(0,0,0,.15); padding: 6px; }
|
||||||
|
.note-pop textarea { width: 220px; height: 90px; border: 0; background: transparent; resize: both; }
|
||||||
|
.k-field { border: 1.5px dashed #5b6ee1; background: rgba(91,110,225,.1); }
|
||||||
|
.field-label { font-size: 10px; color: #5b6ee1; padding: 1px 3px; white-space: nowrap; }
|
||||||
|
.hot { position: absolute; cursor: text; border-radius: 2px; }
|
||||||
|
.hot-text { outline: 1px dashed rgba(26,115,232,.55); }
|
||||||
|
.hot-text:hover { background: rgba(26,115,232,.12); outline-style: solid; }
|
||||||
|
.hot-img { outline: 1.5px dashed rgba(245,124,0,.75); cursor: pointer; }
|
||||||
|
.hot-img:hover { background: rgba(245,124,0,.12); }
|
||||||
|
.fw { position: absolute; border: 1px solid rgba(26,115,232,.35); background: rgba(225,235,255,.75); padding: 0 3px; margin: 0; border-radius: 2px; font-family: 'Sarabun', sans-serif; resize: none; }
|
||||||
|
.fw:focus { outline: 2px solid var(--blue); background: #fff; }
|
||||||
|
.fw-check { accent-color: var(--blue); }
|
||||||
|
.preview { position: absolute; pointer-events: none; }
|
||||||
|
.pv-box { border: 1.5px dashed var(--blue); }
|
||||||
|
.pv-box.round { border-radius: 50%; }
|
||||||
|
.pv-highlight { opacity: .45; mix-blend-mode: multiply; }
|
||||||
|
.pv-redact { background: rgba(0,0,0,.7); }
|
||||||
|
.pv-whiteout { background: #fff; outline: 1px dashed #999; }
|
||||||
|
.preview-svg { position: absolute; inset: 0; width: 100%; height: 100%; pointer-events: none; overflow: visible; }
|
||||||
|
.search-hit { position: absolute; background: rgba(255,152,0,.35); outline: 2px solid #ff9800; pointer-events: none; animation: pulse 1s ease 2; }
|
||||||
|
@keyframes pulse { 50% { background: rgba(255,152,0,.7); } }
|
||||||
|
|
||||||
|
/* ---------- modal / overlays ---------- */
|
||||||
|
.modal-bg { position: fixed; inset: 0; background: rgba(15,18,25,.45); display: grid; place-items: center; z-index: 50; padding: 16px; }
|
||||||
|
.modal { background: #fff; border-radius: 12px; width: min(700px, 100%); box-shadow: 0 20px 60px rgba(0,0,0,.3); display: flex; flex-direction: column; }
|
||||||
|
.modal header, .modal footer { display: flex; align-items: center; gap: 8px; padding: 12px 16px; }
|
||||||
|
.modal header h2 { margin: 0; font-size: 18px; flex: 1; }
|
||||||
|
.modal:focus { outline: none; }
|
||||||
|
.modal nav { padding: 0 16px; }
|
||||||
|
.sig-area { padding: 12px 16px; }
|
||||||
|
.sig-canvas { width: 100%; aspect-ratio: 640 / 220; border: 1px dashed #bbb; border-radius: 8px; background: #fff; touch-action: none; cursor: crosshair; display: block; }
|
||||||
|
.sig-type input { width: 100%; font-size: 18px; padding: 8px 10px; border: 1px solid var(--line); border-radius: 8px; }
|
||||||
|
.font-list { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-top: 10px; }
|
||||||
|
.font-list button { border: 1px solid var(--line); border-radius: 8px; background: #fff; font-size: 28px; padding: 10px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||||
|
.font-list button.on { border-color: var(--accent); box-shadow: 0 0 0 2px var(--accent-soft); }
|
||||||
|
.sig-upload { display: flex; flex-direction: column; gap: 10px; align-items: center; min-height: 160px; justify-content: center; border: 1px dashed #bbb; border-radius: 8px; padding: 12px; }
|
||||||
|
.sig-upload img { max-width: 100%; max-height: 180px; }
|
||||||
|
.busy { position: fixed; left: 50%; top: 70px; transform: translateX(-50%); background: var(--top); color: #fff; padding: 8px 18px; border-radius: 999px; z-index: 60; box-shadow: 0 4px 16px rgba(0,0,0,.25); }
|
||||||
|
.toast { position: fixed; left: 50%; bottom: 24px; transform: translateX(-50%); background: var(--top-solid); color: var(--top-text); padding: 10px 12px 10px 18px; border-radius: 10px; z-index: 60; max-width: calc(100% - 32px); display: flex; align-items: center; gap: 14px; box-shadow: 0 6px 24px rgba(8,29,99,.3); }
|
||||||
|
.toast-action { background: none; border: 1px solid rgba(255,255,255,.35); color: var(--brand-light); font-weight: 700; border-radius: 6px; padding: 4px 12px; min-height: 32px; white-space: nowrap; }
|
||||||
|
.toast-action:hover { background: rgba(255,255,255,.08); }
|
||||||
|
.drop-hint { position: fixed; inset: 0; background: rgba(17,100,194,.08); border: 3px dashed var(--accent); display: grid; place-items: center; font-size: 22px; color: var(--accent); z-index: 40; pointer-events: none; }
|
||||||
|
|
||||||
|
@media (max-width: 900px) {
|
||||||
|
.thumbs { display: none; }
|
||||||
|
.side { width: 240px; }
|
||||||
|
.viewer { padding: 12px 8px 60px; }
|
||||||
|
.topbar .doc-name, .page-ind { display: none; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- Loma additions ---------- */
|
||||||
|
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; }
|
||||||
|
::selection { background: var(--brand-soft); color: var(--text); }
|
||||||
|
input, textarea { caret-color: var(--brand); accent-color: var(--brand); }
|
||||||
|
* { scrollbar-color: #c3c0b8 transparent; scrollbar-width: thin; }
|
||||||
|
|
||||||
|
/* One visible focus ring for every control; the dark top bar gets a light one. */
|
||||||
|
:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; }
|
||||||
|
.topbar :focus-visible, .toast :focus-visible { outline-color: #fff; }
|
||||||
|
.topbar .loma-mark { border-radius: 22%; box-shadow: 0 0 0 1px rgba(255,255,255,.35), 0 1px 3px rgba(8,29,99,.35); }
|
||||||
|
.topbar .tb:hover:not(:disabled):not(.primary) { background: rgba(255,255,255,.15); }
|
||||||
|
.tabs button:focus-visible { outline-offset: -3px; }
|
||||||
|
.thumb-pick:focus-visible { outline-offset: 3px; }
|
||||||
|
.item.live:focus-visible { outline: 2px solid var(--focus); outline-offset: 3px; }
|
||||||
|
.hot { border: 0; padding: 0; margin: 0; background: transparent; font: inherit; }
|
||||||
|
.hot:focus-visible { outline: 2px solid var(--focus); outline-offset: 1px; background: rgba(26,102,217,.12); }
|
||||||
|
|
||||||
|
.loma-mark { flex: none; display: block; user-select: none; }
|
||||||
|
.loma-lockup { display: block; max-width: 100%; user-select: none; }
|
||||||
|
.start-card .logo { margin: 0; justify-content: center; display: flex; }
|
||||||
|
.dirty { font-size: 12.5px; color: #fde68a; border: 1px solid rgba(253,230,138,.55); border-radius: 999px; padding: 1px 8px; white-space: nowrap; margin-right: 4px; }
|
||||||
|
.zoom-group { display: inline-flex; align-items: center; gap: 2px; }
|
||||||
|
.tools-scope { color: var(--muted); font-size: 13px; padding: 0 8px 0 2px; white-space: nowrap; align-self: center; }
|
||||||
|
.tool-sep { width: 1px; align-self: stretch; margin: 6px 4px; background: var(--line); }
|
||||||
|
.tool:disabled { opacity: .4; }
|
||||||
|
.tools-hint { font-size: 13.5px; }
|
||||||
|
|
||||||
|
.doc-meta { margin: 0; display: flex; flex-direction: column; gap: 2px; }
|
||||||
|
.doc-meta-name { font-weight: 700; overflow-wrap: anywhere; }
|
||||||
|
.doc-meta span:last-child { color: var(--muted); font-size: 13.5px; }
|
||||||
|
.next-steps { display: flex; flex-direction: column; gap: 6px; }
|
||||||
|
.next-steps .btn { justify-content: flex-start; }
|
||||||
|
.privacy { display: flex; gap: 6px; align-items: flex-start; margin: 6px 0 0; font-size: 13px; color: var(--brand-strong); }
|
||||||
|
.privacy svg { flex: none; margin-top: 2px; }
|
||||||
|
|
||||||
|
details.fold { border-top: 1px solid var(--line); padding-top: 8px; display: flex; flex-direction: column; gap: 8px; }
|
||||||
|
details.fold > summary { cursor: pointer; font-weight: 700; padding: 4px 0; list-style-position: inside; }
|
||||||
|
details.fold[open] > summary { margin-bottom: 4px; }
|
||||||
|
details.fold > :not(summary) { margin-bottom: 8px; }
|
||||||
|
|
||||||
|
.sig-bar { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; padding: 0 16px; }
|
||||||
|
.sig-bar .swatches { padding: 4px; }
|
||||||
|
.sig-note { margin-top: 10px; }
|
||||||
|
.confirm { width: min(520px, 100%); }
|
||||||
|
.confirm-list { margin: 0; padding: 4px 16px 0 36px; display: flex; flex-direction: column; gap: 8px; line-height: 1.55; }
|
||||||
|
.confirm-note { padding: 10px 16px 0; }
|
||||||
|
|
||||||
|
.side-handle { display: none; }
|
||||||
|
.desk-only { display: inline; }
|
||||||
|
|
||||||
|
/* ---------- phones: page first, options in a bottom sheet ---------- */
|
||||||
|
@media (max-width: 700px) {
|
||||||
|
.desk-only { display: none; }
|
||||||
|
.topbar { overflow-x: auto; gap: 2px; padding: 4px 6px; scrollbar-width: none; }
|
||||||
|
.topbar .logo-word, .topbar .tb-label, .topbar .zoom, .topbar .sep, .topbar .dirty { display: none; }
|
||||||
|
.tb { min-height: 44px; min-width: 44px; justify-content: center; padding: 6px 8px; flex: none; }
|
||||||
|
.tabs button { padding: 12px 12px; }
|
||||||
|
.tools { min-height: 0; padding: 4px 6px; }
|
||||||
|
.tool { min-height: 52px; min-width: 60px; font-size: 12.5px; }
|
||||||
|
.tools-scope { display: none; }
|
||||||
|
.viewer { padding: 10px 6px 46vh; }
|
||||||
|
.side { position: fixed; left: 0; right: 0; bottom: 0; width: auto; max-height: 42vh; z-index: 30; border-left: 0; border-top: 1px solid var(--line); border-radius: 14px 14px 0 0; box-shadow: 0 -8px 30px rgba(8,29,99,.18); }
|
||||||
|
.side.folded { max-height: 52px; overflow: hidden; }
|
||||||
|
.side-handle { display: flex; align-items: center; justify-content: center; gap: 10px; width: 100%; min-height: 48px; border: 0; background: var(--panel); color: var(--muted); position: sticky; top: 0; z-index: 1; border-bottom: 1px solid var(--line); font-size: 13.5px; }
|
||||||
|
.side-grip { width: 32px; height: 4px; border-radius: 2px; background: var(--line); }
|
||||||
|
.sw { width: 32px; height: 32px; }
|
||||||
|
.icon-btn { width: 44px; height: 40px; }
|
||||||
|
.btn { min-height: 44px; }
|
||||||
|
.toast { bottom: calc(42vh + 12px); }
|
||||||
|
.features { grid-template-columns: 1fr; }
|
||||||
|
.start-card { padding: 28px 18px 24px; }
|
||||||
|
.start-title { font-size: 22px; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
import { pdfjs, type PDFPageProxy } from './pdfjs';
|
||||||
|
import { axes, bbox, frameRect, norm360 } from './geom';
|
||||||
|
import type { Rect } from './types';
|
||||||
|
|
||||||
|
/** A run of text on one baseline, in the run's own rotated frame (s = along baseline, t = baseline offset). */
|
||||||
|
export type TextRun = { text: string; rot: number; size: number; s0: number; s1: number; t: number; fontName: string };
|
||||||
|
export type TextLine = TextRun & { key: string; rect: Rect; bold: boolean };
|
||||||
|
export type ImageBox = { key: string; rect: Rect };
|
||||||
|
|
||||||
|
/** Merge pdf.js text items into runs; items further apart than `maxGap` font sizes start a new run. */
|
||||||
|
export async function getRuns(page: PDFPageProxy, maxGap = 1.6): Promise<TextRun[]> {
|
||||||
|
const tc = await page.getTextContent();
|
||||||
|
const runs: TextRun[] = [];
|
||||||
|
let cur: TextRun | null = null;
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
for (const it of tc.items as any[]) {
|
||||||
|
if (typeof it.str !== 'string') continue;
|
||||||
|
const [a, b, , , e, f] = it.transform as number[];
|
||||||
|
const size = Math.hypot(a, b) || it.height;
|
||||||
|
const str: string = it.str;
|
||||||
|
// Skip whitespace-only items: pdf.js emits them to fill gaps (e.g. between table columns),
|
||||||
|
// and their width would glue separate columns into one run. Word gaps add a space below.
|
||||||
|
if (!size || !str.trim()) {
|
||||||
|
if (it.hasEOL) cur = null;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const rot = norm360(Math.round((Math.atan2(b, a) * 180) / Math.PI / 90) * 90);
|
||||||
|
const { right, up } = axes(rot);
|
||||||
|
const s = e * right.x + f * right.y;
|
||||||
|
const t = e * up.x + f * up.y;
|
||||||
|
const width = it.width as number;
|
||||||
|
if (
|
||||||
|
cur &&
|
||||||
|
cur.rot === rot &&
|
||||||
|
Math.abs(cur.t - t) < size * 0.35 &&
|
||||||
|
s > cur.s1 - size * 0.6 &&
|
||||||
|
s - cur.s1 < size * maxGap
|
||||||
|
) {
|
||||||
|
if (s - cur.s1 > size * 0.18 && !cur.text.endsWith(' ') && !str.startsWith(' ')) cur.text += ' ';
|
||||||
|
cur.text += str;
|
||||||
|
cur.s1 = Math.max(cur.s1, s + width);
|
||||||
|
cur.size = Math.max(cur.size, size);
|
||||||
|
} else {
|
||||||
|
cur = { text: str, rot, size, s0: s, s1: s + width, t, fontName: it.fontName };
|
||||||
|
runs.push(cur);
|
||||||
|
}
|
||||||
|
if (it.hasEOL) cur = null;
|
||||||
|
}
|
||||||
|
return runs
|
||||||
|
.map((r) => ({ ...r, text: r.text.replace(/\s+$/, '') }))
|
||||||
|
.filter((r) => r.text);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isBold(page: PDFPageProxy, fontName: string): boolean {
|
||||||
|
try {
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
const f = (page as any).commonObjs.get(fontName);
|
||||||
|
return !!f && (f.bold || /bold|black|heavy|semibold|demi/i.test(f.name ?? ''));
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getTextLines(page: PDFPageProxy): Promise<TextLine[]> {
|
||||||
|
const runs = await getRuns(page);
|
||||||
|
return runs.map((r, i) => ({
|
||||||
|
...r,
|
||||||
|
key: String(i),
|
||||||
|
bold: isBold(page, r.fontName),
|
||||||
|
rect: frameRect(r.rot, r.s0, r.s1, r.t - 0.3 * r.size, r.t + 1.0 * r.size),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
let measureCtx: CanvasRenderingContext2D | null = null;
|
||||||
|
/** Share of the line's width taken by its first `i` characters, measured in a proportional font. */
|
||||||
|
function widthFrac(text: string, i: number): number {
|
||||||
|
measureCtx ??= document.createElement('canvas').getContext('2d')!;
|
||||||
|
measureCtx.font = '100px Sarabun, sans-serif';
|
||||||
|
const full = measureCtx.measureText(text).width;
|
||||||
|
return full ? measureCtx.measureText(text.slice(0, i)).width / full : i / Math.max(1, text.length);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Rect covering characters [from, from+len) of a line (positions estimated from proportional glyph widths). */
|
||||||
|
export function lineSubRect(l: TextRun, from: number, len: number): Rect {
|
||||||
|
const w = l.s1 - l.s0;
|
||||||
|
const a = l.s0 + w * widthFrac(l.text, from);
|
||||||
|
const b = l.s0 + w * widthFrac(l.text, from + len);
|
||||||
|
return frameRect(l.rot, a, b, l.t - 0.3 * l.size, l.t + 1.0 * l.size);
|
||||||
|
}
|
||||||
|
|
||||||
|
type M = number[];
|
||||||
|
const mul = (m1: M, m2: M): M => [
|
||||||
|
m1[0] * m2[0] + m1[1] * m2[2],
|
||||||
|
m1[0] * m2[1] + m1[1] * m2[3],
|
||||||
|
m1[2] * m2[0] + m1[3] * m2[2],
|
||||||
|
m1[2] * m2[1] + m1[3] * m2[3],
|
||||||
|
m1[4] * m2[0] + m1[5] * m2[2] + m2[4],
|
||||||
|
m1[4] * m2[1] + m1[5] * m2[3] + m2[5],
|
||||||
|
];
|
||||||
|
const apply = (m: M, x: number, y: number) => ({ x: m[0] * x + m[2] * y + m[4], y: m[1] * x + m[3] * y + m[5] });
|
||||||
|
|
||||||
|
/** Locate painted images by replaying the operator list's transformation matrix. */
|
||||||
|
export async function getImageBoxes(page: PDFPageProxy): Promise<ImageBox[]> {
|
||||||
|
const { fnArray, argsArray } = await page.getOperatorList();
|
||||||
|
const O = pdfjs.OPS;
|
||||||
|
const imgOps = new Set<number>([O.paintImageXObject, O.paintInlineImageXObject, O.paintImageMaskXObject]);
|
||||||
|
let ctm: M = [1, 0, 0, 1, 0, 0];
|
||||||
|
const stack: M[] = [];
|
||||||
|
const out: ImageBox[] = [];
|
||||||
|
for (let i = 0; i < fnArray.length; i++) {
|
||||||
|
const fn = fnArray[i];
|
||||||
|
const args = argsArray[i];
|
||||||
|
if (fn === O.save) stack.push(ctm);
|
||||||
|
else if (fn === O.restore) ctm = stack.pop() ?? ctm;
|
||||||
|
else if (fn === O.transform) ctm = mul(args as M, ctm);
|
||||||
|
else if (fn === O.paintFormXObjectBegin) {
|
||||||
|
stack.push(ctm);
|
||||||
|
if (Array.isArray(args?.[0]) && args[0].length === 6) ctm = mul(args[0] as M, ctm);
|
||||||
|
} else if (fn === O.paintFormXObjectEnd) ctm = stack.pop() ?? ctm;
|
||||||
|
else if (imgOps.has(fn)) {
|
||||||
|
const r = bbox([apply(ctm, 0, 0), apply(ctm, 1, 0), apply(ctm, 0, 1), apply(ctm, 1, 1)]);
|
||||||
|
if (r.w > 6 && r.h > 6) out.push({ key: String(out.length), rect: r });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
const hex = (r: number, g: number, b: number) => '#' + [r, g, b].map((v) => v.toString(16).padStart(2, '0')).join('');
|
||||||
|
|
||||||
|
/** Guess background (most common) and foreground (most different) colors inside a canvas region. */
|
||||||
|
export function sampleColors(ctx: CanvasRenderingContext2D, x: number, y: number, w: number, h: number) {
|
||||||
|
x = Math.max(0, Math.floor(x));
|
||||||
|
y = Math.max(0, Math.floor(y));
|
||||||
|
w = Math.max(1, Math.min(ctx.canvas.width - x, Math.ceil(w)));
|
||||||
|
h = Math.max(1, Math.min(ctx.canvas.height - y, Math.ceil(h)));
|
||||||
|
const { data } = ctx.getImageData(x, y, w, h);
|
||||||
|
const step = Math.max(1, Math.floor((w * h) / 40000)) * 4;
|
||||||
|
const counts = new Map<number, number>();
|
||||||
|
for (let i = 0; i < data.length; i += step) {
|
||||||
|
const k = ((data[i] >> 4) << 8) | ((data[i + 1] >> 4) << 4) | (data[i + 2] >> 4);
|
||||||
|
counts.set(k, (counts.get(k) ?? 0) + 1);
|
||||||
|
}
|
||||||
|
let bestK = 0xfff, best = -1;
|
||||||
|
counts.forEach((v, k) => {
|
||||||
|
if (v > best) [best, bestK] = [v, k];
|
||||||
|
});
|
||||||
|
const bg = [((bestK >> 8) & 15) * 17, ((bestK >> 4) & 15) * 17, (bestK & 15) * 17];
|
||||||
|
let fg = [0, 0, 0], far = -1;
|
||||||
|
for (let i = 0; i < data.length; i += step) {
|
||||||
|
const d = Math.abs(data[i] - bg[0]) + Math.abs(data[i + 1] - bg[1]) + Math.abs(data[i + 2] - bg[2]);
|
||||||
|
if (d > far) [far, fg] = [d, [data[i], data[i + 1], data[i + 2]]];
|
||||||
|
}
|
||||||
|
if (far < 60) fg = [0, 0, 0];
|
||||||
|
return { bg: hex(bg[0], bg[1], bg[2]), fg: hex(fg[0], fg[1], fg[2]) };
|
||||||
|
}
|
||||||
@@ -0,0 +1,325 @@
|
|||||||
|
/**
|
||||||
|
* Remove original page content (text-showing operators and image draws) that falls inside given
|
||||||
|
* rectangles, by rewriting the page's content stream. Used when the user edits an existing text
|
||||||
|
* line or lifts an existing image, so the old content is really gone instead of just covered.
|
||||||
|
*
|
||||||
|
* Scope: operators in the page's own content stream. Content inside Form XObjects is left alone
|
||||||
|
* (the whiteout still hides it visually).
|
||||||
|
*/
|
||||||
|
import {
|
||||||
|
PDFArray, PDFDict, PDFName, PDFNumber, PDFRawStream, PDFRef, PDFStream, decodePDFRawStream,
|
||||||
|
type PDFDocument, type PDFObject, type PDFPage,
|
||||||
|
} from 'pdf-lib';
|
||||||
|
import type { Pt, Rect } from './types';
|
||||||
|
|
||||||
|
type Val = number | string | boolean | null | { name: string } | { str: string } | Val[] | { dict: Record<string, Val> };
|
||||||
|
type Op = { op: string; args: Val[]; start: number; end: number };
|
||||||
|
|
||||||
|
const WS = new Set([0x00, 0x09, 0x0a, 0x0c, 0x0d, 0x20]);
|
||||||
|
const DELIM = new Set('()<>[]{}/%'.split('').map((c) => c.charCodeAt(0)));
|
||||||
|
|
||||||
|
/** Tokenise a content stream held as a latin1 string (1 char = 1 byte). */
|
||||||
|
export function parseOps(s: string): Op[] {
|
||||||
|
let i = 0;
|
||||||
|
const n = s.length;
|
||||||
|
const skip = () => {
|
||||||
|
for (;;) {
|
||||||
|
while (i < n && WS.has(s.charCodeAt(i))) i++;
|
||||||
|
if (s[i] === '%') while (i < n && s[i] !== '\n' && s[i] !== '\r') i++;
|
||||||
|
else return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const regular = () => {
|
||||||
|
const st = i;
|
||||||
|
while (i < n && !WS.has(s.charCodeAt(i)) && !DELIM.has(s.charCodeAt(i))) i++;
|
||||||
|
return s.slice(st, i);
|
||||||
|
};
|
||||||
|
const literal = (): string => {
|
||||||
|
i++; // (
|
||||||
|
let depth = 1;
|
||||||
|
let out = '';
|
||||||
|
while (i < n) {
|
||||||
|
const c = s[i++];
|
||||||
|
if (c === '\\') {
|
||||||
|
const e = s[i++];
|
||||||
|
if (e === 'n') out += '\n';
|
||||||
|
else if (e === 'r') out += '\r';
|
||||||
|
else if (e === 't') out += '\t';
|
||||||
|
else if (e === 'b') out += '\b';
|
||||||
|
else if (e === 'f') out += '\f';
|
||||||
|
else if (e === '\r') { if (s[i] === '\n') i++; }
|
||||||
|
else if (e === '\n') { /* line continuation */ }
|
||||||
|
else if (e >= '0' && e <= '7') {
|
||||||
|
let oct = e;
|
||||||
|
while (oct.length < 3 && s[i] >= '0' && s[i] <= '7') oct += s[i++];
|
||||||
|
out += String.fromCharCode(parseInt(oct, 8) & 255);
|
||||||
|
} else out += e;
|
||||||
|
} else if (c === '(') { depth++; out += c; }
|
||||||
|
else if (c === ')') { if (--depth === 0) break; out += c; }
|
||||||
|
else out += c;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
};
|
||||||
|
const value = (): Val => {
|
||||||
|
skip();
|
||||||
|
const c = s[i];
|
||||||
|
if (c === '(') return { str: literal() };
|
||||||
|
if (c === '<' && s[i + 1] === '<') {
|
||||||
|
i += 2;
|
||||||
|
const dict: Record<string, Val> = {};
|
||||||
|
for (;;) {
|
||||||
|
skip();
|
||||||
|
if (i >= n) break;
|
||||||
|
if (s[i] === '>' && s[i + 1] === '>') { i += 2; break; }
|
||||||
|
const k = value();
|
||||||
|
const v = value();
|
||||||
|
if (k && typeof k === 'object' && 'name' in k) dict[k.name] = v;
|
||||||
|
}
|
||||||
|
return { dict };
|
||||||
|
}
|
||||||
|
if (c === '<') {
|
||||||
|
const end = s.indexOf('>', i);
|
||||||
|
const hex = s.slice(i + 1, end < 0 ? n : end).replace(/\s+/g, '');
|
||||||
|
i = end < 0 ? n : end + 1;
|
||||||
|
let out = '';
|
||||||
|
for (let k = 0; k < hex.length; k += 2) out += String.fromCharCode(parseInt((hex[k] + (hex[k + 1] ?? '0')), 16));
|
||||||
|
return { str: out };
|
||||||
|
}
|
||||||
|
if (c === '[') {
|
||||||
|
i++;
|
||||||
|
const arr: Val[] = [];
|
||||||
|
for (;;) {
|
||||||
|
skip();
|
||||||
|
if (i >= n || s[i] === ']') { i++; break; }
|
||||||
|
arr.push(value());
|
||||||
|
}
|
||||||
|
return arr;
|
||||||
|
}
|
||||||
|
if (c === '/') { i++; return { name: regular() }; }
|
||||||
|
if (c === ')' || c === '>' || c === '{' || c === '}' || c === ']') { i++; return null; }
|
||||||
|
const tok = regular();
|
||||||
|
if (/^[+-]?(\d+\.?\d*|\.\d+)$/.test(tok)) return parseFloat(tok);
|
||||||
|
if (tok === 'true' || tok === 'false') return tok === 'true';
|
||||||
|
if (tok === 'null') return null;
|
||||||
|
return { op: tok } as unknown as Val; // keyword marker
|
||||||
|
};
|
||||||
|
|
||||||
|
const ops: Op[] = [];
|
||||||
|
let args: Val[] = [];
|
||||||
|
let argStart = -1;
|
||||||
|
while (i < n) {
|
||||||
|
skip();
|
||||||
|
if (i >= n) break;
|
||||||
|
const st = i;
|
||||||
|
if (argStart < 0) argStart = st;
|
||||||
|
const v = value();
|
||||||
|
if (i === st) { i++; continue; } // safety: never stall
|
||||||
|
if (v && typeof v === 'object' && 'op' in (v as object)) {
|
||||||
|
const op = (v as unknown as { op: string }).op;
|
||||||
|
if (op === 'BI') {
|
||||||
|
// Inline image: dict entries up to ID, then binary data up to a whitespace-delimited EI.
|
||||||
|
const id = s.indexOf('ID', i);
|
||||||
|
let p = id + 3;
|
||||||
|
const re = /[\0\t\n\f\r ]EI(?=[\0\t\n\f\r ]|$)/g;
|
||||||
|
re.lastIndex = p;
|
||||||
|
const m = re.exec(s);
|
||||||
|
p = m ? m.index + 3 : n;
|
||||||
|
i = p;
|
||||||
|
ops.push({ op: 'BI', args: [], start: argStart, end: i });
|
||||||
|
} else ops.push({ op, args, start: argStart, end: i });
|
||||||
|
args = [];
|
||||||
|
argStart = -1;
|
||||||
|
} else args.push(v);
|
||||||
|
}
|
||||||
|
return ops;
|
||||||
|
}
|
||||||
|
|
||||||
|
type M = number[];
|
||||||
|
const mul = (a: M, b: M): M => [
|
||||||
|
a[0] * b[0] + a[1] * b[2], a[0] * b[1] + a[1] * b[3],
|
||||||
|
a[2] * b[0] + a[3] * b[2], a[2] * b[1] + a[3] * b[3],
|
||||||
|
a[4] * b[0] + a[5] * b[2] + b[4], a[4] * b[1] + a[5] * b[3] + b[5],
|
||||||
|
];
|
||||||
|
const apply = (m: M, x: number, y: number): Pt => ({ x: m[0] * x + m[2] * y + m[4], y: m[1] * x + m[3] * y + m[5] });
|
||||||
|
const inside = (p: Pt, r: Rect, tol = 1) => p.x >= r.x - tol && p.x <= r.x + r.w + tol && p.y >= r.y - tol && p.y <= r.y + r.h + tol;
|
||||||
|
const num = (v: Val | undefined) => (typeof v === 'number' ? v : 0);
|
||||||
|
|
||||||
|
/** Glyph-width lookup for a font resource (code → width in 1/1000 em), plus bytes per code. */
|
||||||
|
type FontMetrics = { bytes: 1 | 2; width: (code: number) => number };
|
||||||
|
|
||||||
|
function fontMetrics(doc: PDFDocument, fontDict: PDFDict | undefined): FontMetrics {
|
||||||
|
const fallback: FontMetrics = { bytes: 1, width: () => 500 };
|
||||||
|
if (!fontDict) return fallback;
|
||||||
|
const lookupNum = (d: PDFDict, k: string) => {
|
||||||
|
const v = d.lookup(PDFName.of(k));
|
||||||
|
return v instanceof PDFNumber ? v.asNumber() : undefined;
|
||||||
|
};
|
||||||
|
const sub = fontDict.lookup(PDFName.of('Subtype'));
|
||||||
|
if (sub === PDFName.of('Type0')) {
|
||||||
|
const desc = fontDict.lookup(PDFName.of('DescendantFonts'));
|
||||||
|
const cid = desc instanceof PDFArray ? (desc.lookup(0) as PDFDict) : undefined;
|
||||||
|
const dw = (cid && lookupNum(cid, 'DW')) ?? 1000;
|
||||||
|
const map = new Map<number, number>();
|
||||||
|
const W = cid?.lookup(PDFName.of('W'));
|
||||||
|
if (W instanceof PDFArray) {
|
||||||
|
const a = W.asArray().map((o) => doc.context.lookup(o));
|
||||||
|
for (let k = 0; k < a.length; ) {
|
||||||
|
const first = (a[k] as PDFNumber).asNumber();
|
||||||
|
const next = a[k + 1];
|
||||||
|
if (next instanceof PDFArray) {
|
||||||
|
next.asArray().forEach((w, j) => map.set(first + j, (doc.context.lookup(w) as PDFNumber).asNumber()));
|
||||||
|
k += 2;
|
||||||
|
} else {
|
||||||
|
const last = (next as PDFNumber).asNumber();
|
||||||
|
const w = (a[k + 2] as PDFNumber).asNumber();
|
||||||
|
for (let c = first; c <= last; c++) map.set(c, w);
|
||||||
|
k += 3;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { bytes: 2, width: (c) => map.get(c) ?? dw };
|
||||||
|
}
|
||||||
|
const first = lookupNum(fontDict, 'FirstChar') ?? 0;
|
||||||
|
const widths = fontDict.lookup(PDFName.of('Widths'));
|
||||||
|
const fd = fontDict.lookup(PDFName.of('FontDescriptor'));
|
||||||
|
const missing = (fd instanceof PDFDict && lookupNum(fd, 'MissingWidth')) || 500;
|
||||||
|
if (!(widths instanceof PDFArray)) return fallback;
|
||||||
|
const ws = widths.asArray().map((w) => (doc.context.lookup(w) as PDFNumber)?.asNumber?.() ?? missing);
|
||||||
|
return { bytes: 1, width: (c) => ws[c - first] ?? missing };
|
||||||
|
}
|
||||||
|
|
||||||
|
function contentString(doc: PDFDocument, page: PDFPage): string | null {
|
||||||
|
const c = page.node.Contents();
|
||||||
|
const streams: PDFObject[] = c instanceof PDFArray ? c.asArray().map((o) => doc.context.lookup(o)!) : c ? [c] : [];
|
||||||
|
let out = '';
|
||||||
|
for (const st of streams) {
|
||||||
|
if (!(st instanceof PDFRawStream)) return null; // unexpected stream type: leave the page untouched
|
||||||
|
const bytes = decodePDFRawStream(st).decode();
|
||||||
|
for (let k = 0; k < bytes.length; k += 0x8000) out += String.fromCharCode(...bytes.subarray(k, k + 0x8000));
|
||||||
|
out += '\n';
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Strip text-showing operators whose glyph run's midpoint lies in `textRects`, and image draws
|
||||||
|
* whose centre lies in `imageRects`. Returns how many operators were removed.
|
||||||
|
*/
|
||||||
|
export function removePageContent(doc: PDFDocument, page: PDFPage, textRects: Rect[], imageRects: Rect[]): number {
|
||||||
|
if (!textRects.length && !imageRects.length) return 0;
|
||||||
|
const src = contentString(doc, page);
|
||||||
|
if (src === null) return 0;
|
||||||
|
const ops = parseOps(src);
|
||||||
|
const res = page.node.Resources();
|
||||||
|
const fontRes = res?.lookupMaybe(PDFName.of('Font'), PDFDict);
|
||||||
|
const xobjRes = res?.lookupMaybe(PDFName.of('XObject'), PDFDict);
|
||||||
|
const metrics = new Map<string, FontMetrics>();
|
||||||
|
const getMetrics = (name: string) => {
|
||||||
|
let m = metrics.get(name);
|
||||||
|
if (!m) {
|
||||||
|
m = fontMetrics(doc, fontRes?.lookupMaybe(PDFName.of(name), PDFDict));
|
||||||
|
metrics.set(name, m);
|
||||||
|
}
|
||||||
|
return m;
|
||||||
|
};
|
||||||
|
|
||||||
|
type G = { ctm: M; Tc: number; Tw: number; Th: number; TL: number; Tfs: number; font: string };
|
||||||
|
let g: G = { ctm: [1, 0, 0, 1, 0, 0], Tc: 0, Tw: 0, Th: 1, TL: 0, Tfs: 12, font: '' };
|
||||||
|
const stack: G[] = [];
|
||||||
|
let Tm: M = [1, 0, 0, 1, 0, 0];
|
||||||
|
let Tlm: M = [1, 0, 0, 1, 0, 0];
|
||||||
|
const edits: { start: number; end: number; repl: string }[] = [];
|
||||||
|
|
||||||
|
const nextLine = (tx: number, ty: number) => {
|
||||||
|
Tlm = mul([1, 0, 0, 1, tx, ty], Tlm);
|
||||||
|
Tm = Tlm;
|
||||||
|
};
|
||||||
|
/** Advance the text matrix over a string; returns the run's start and end points. */
|
||||||
|
const show = (parts: Val[]) => {
|
||||||
|
const fm = getMetrics(g.font);
|
||||||
|
const start = apply(mul(Tm, g.ctm), 0, 0);
|
||||||
|
let tx = 0;
|
||||||
|
for (const p of parts) {
|
||||||
|
if (typeof p === 'number') tx -= (p / 1000) * g.Tfs * g.Th;
|
||||||
|
else if (p && typeof p === 'object' && 'str' in p) {
|
||||||
|
const str = p.str;
|
||||||
|
for (let k = 0; k + fm.bytes <= str.length; k += fm.bytes) {
|
||||||
|
const code = fm.bytes === 2 ? (str.charCodeAt(k) << 8) | str.charCodeAt(k + 1) : str.charCodeAt(k);
|
||||||
|
const space = fm.bytes === 1 && code === 32 ? g.Tw : 0;
|
||||||
|
tx += ((fm.width(code) / 1000) * g.Tfs + g.Tc + space) * g.Th;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Tm = mul([1, 0, 0, 1, tx, 0], Tm);
|
||||||
|
const end = apply(mul(Tm, g.ctm), 0, 0);
|
||||||
|
return { x: (start.x + end.x) / 2, y: (start.y + end.y) / 2 };
|
||||||
|
};
|
||||||
|
const hitText = (mid: Pt) => textRects.some((r) => inside(mid, r));
|
||||||
|
const hitImage = () => {
|
||||||
|
const c = apply(g.ctm, 0.5, 0.5);
|
||||||
|
return imageRects.some((r) => inside(c, r, 2));
|
||||||
|
};
|
||||||
|
|
||||||
|
for (const o of ops) {
|
||||||
|
const a = o.args;
|
||||||
|
switch (o.op) {
|
||||||
|
case 'q': stack.push({ ...g }); break;
|
||||||
|
case 'Q': g = stack.pop() ?? g; break;
|
||||||
|
case 'cm': g.ctm = mul(a.map(num), g.ctm); break;
|
||||||
|
case 'BT': Tm = [1, 0, 0, 1, 0, 0]; Tlm = Tm; break;
|
||||||
|
case 'Tf': g.font = (a[0] as { name: string })?.name ?? ''; g.Tfs = num(a[1]); break;
|
||||||
|
case 'Tc': g.Tc = num(a[0]); break;
|
||||||
|
case 'Tw': g.Tw = num(a[0]); break;
|
||||||
|
case 'Tz': g.Th = num(a[0]) / 100; break;
|
||||||
|
case 'TL': g.TL = num(a[0]); break;
|
||||||
|
case 'Td': nextLine(num(a[0]), num(a[1])); break;
|
||||||
|
case 'TD': g.TL = -num(a[1]); nextLine(num(a[0]), num(a[1])); break;
|
||||||
|
case 'Tm': Tlm = a.map(num); Tm = Tlm; break;
|
||||||
|
case 'T*': nextLine(0, -g.TL); break;
|
||||||
|
case 'Tj':
|
||||||
|
case 'TJ': {
|
||||||
|
const mid = show(o.op === 'TJ' ? ((a[0] as Val[]) ?? []) : [a[0]]);
|
||||||
|
if (hitText(mid)) edits.push({ start: o.start, end: o.end, repl: '' });
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "'":
|
||||||
|
case '"': {
|
||||||
|
let pre = 'T*';
|
||||||
|
if (o.op === '"') {
|
||||||
|
g.Tw = num(a[0]);
|
||||||
|
g.Tc = num(a[1]);
|
||||||
|
pre = `${num(a[0])} Tw ${num(a[1])} Tc T*`;
|
||||||
|
}
|
||||||
|
nextLine(0, -g.TL);
|
||||||
|
const mid = show([a[a.length - 1]]);
|
||||||
|
// Keep the line move the operator implies, drop only the glyphs.
|
||||||
|
if (hitText(mid)) edits.push({ start: o.start, end: o.end, repl: pre });
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'Do': {
|
||||||
|
const name = (a[0] as { name: string })?.name;
|
||||||
|
const xo = name ? xobjRes?.lookup(PDFName.of(name)) : undefined;
|
||||||
|
const isImage = xo instanceof PDFStream && xo.dict.lookup(PDFName.of('Subtype')) === PDFName.of('Image');
|
||||||
|
if (isImage && hitImage()) edits.push({ start: o.start, end: o.end, repl: '' });
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'BI':
|
||||||
|
if (hitImage()) edits.push({ start: o.start, end: o.end, repl: '' });
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!edits.length) return 0;
|
||||||
|
|
||||||
|
let out = '';
|
||||||
|
let pos = 0;
|
||||||
|
for (const e of edits) {
|
||||||
|
out += src.slice(pos, e.start) + e.repl + ' ';
|
||||||
|
pos = e.end;
|
||||||
|
}
|
||||||
|
out += src.slice(pos);
|
||||||
|
const bytes = new Uint8Array(out.length);
|
||||||
|
for (let k = 0; k < out.length; k++) bytes[k] = out.charCodeAt(k);
|
||||||
|
const ref: PDFRef = doc.context.register(doc.context.flateStream(bytes));
|
||||||
|
page.node.set(PDFName.of('Contents'), ref);
|
||||||
|
return edits.length;
|
||||||
|
}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
import JSZip from 'jszip';
|
||||||
|
import * as XLSX from 'xlsx';
|
||||||
|
import { Document, Packer, PageBreak, Paragraph, TextRun } from 'docx';
|
||||||
|
import { renderPage, scaleFor, type PDFDocumentProxy } from './pdfjs';
|
||||||
|
import { getRuns, type TextRun as Run } from './analyze';
|
||||||
|
|
||||||
|
/** Group runs into visual rows (top to bottom, left to right). Non-horizontal text goes last. */
|
||||||
|
function rows(runs: Run[]): Run[][] {
|
||||||
|
const flat = runs.filter((r) => r.rot === 0).sort((a, b) => b.t - a.t || a.s0 - b.s0);
|
||||||
|
const out: Run[][] = [];
|
||||||
|
for (const r of flat) {
|
||||||
|
const row = out[out.length - 1];
|
||||||
|
if (row && Math.abs(row[0].t - r.t) < Math.min(row[0].size, r.size) * 0.5) row.push(r);
|
||||||
|
else out.push([r]);
|
||||||
|
}
|
||||||
|
out.forEach((row) => row.sort((a, b) => a.s0 - b.s0));
|
||||||
|
const other = runs.filter((r) => r.rot !== 0);
|
||||||
|
if (other.length) out.push(...other.map((r) => [r]));
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function pdfToImages(pdf: PDFDocumentProxy, fmt: 'png' | 'jpeg', name: string): Promise<Blob> {
|
||||||
|
const zip = new JSZip();
|
||||||
|
for (let i = 1; i <= pdf.numPages; i++) {
|
||||||
|
const page = await pdf.getPage(i);
|
||||||
|
const c = await renderPage(page, scaleFor(page, 2200, 3));
|
||||||
|
const blob = await new Promise<Blob>((res) => c.toBlob((b) => res(b!), `image/${fmt}`, 0.92));
|
||||||
|
zip.file(`${name}-${String(i).padStart(3, '0')}.${fmt === 'jpeg' ? 'jpg' : 'png'}`, blob);
|
||||||
|
}
|
||||||
|
return zip.generateAsync({ type: 'blob' });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function pdfToText(pdf: PDFDocumentProxy): Promise<string> {
|
||||||
|
const parts: string[] = [];
|
||||||
|
for (let i = 1; i <= pdf.numPages; i++) {
|
||||||
|
const rs = rows(await getRuns(await pdf.getPage(i)));
|
||||||
|
parts.push(rs.map((row) => row.map((r) => r.text).join('\t')).join('\n'));
|
||||||
|
}
|
||||||
|
return parts.join('\n\n\f');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function pdfToDocx(pdf: PDFDocumentProxy): Promise<Blob> {
|
||||||
|
const paras: Paragraph[] = [];
|
||||||
|
for (let i = 1; i <= pdf.numPages; i++) {
|
||||||
|
const rs = rows(await getRuns(await pdf.getPage(i)));
|
||||||
|
let prev: Run | null = null;
|
||||||
|
rs.forEach((row) => {
|
||||||
|
const first = row[0];
|
||||||
|
if (prev && prev.t - first.t > first.size * 2) paras.push(new Paragraph({}));
|
||||||
|
paras.push(
|
||||||
|
new Paragraph({
|
||||||
|
children: row.map(
|
||||||
|
(r, k) => new TextRun({ text: (k ? '\t' : '') + r.text, size: Math.round(r.size * 2), font: 'Sarabun' }),
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
prev = first;
|
||||||
|
});
|
||||||
|
if (i < pdf.numPages) paras.push(new Paragraph({ children: [new PageBreak()] }));
|
||||||
|
}
|
||||||
|
const doc = new Document({ sections: [{ children: paras }] });
|
||||||
|
return Packer.toBlob(doc);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Each page becomes a sheet; text cells are snapped to column positions shared across the page. */
|
||||||
|
export async function pdfToXlsx(pdf: PDFDocumentProxy): Promise<Blob> {
|
||||||
|
const wb = XLSX.utils.book_new();
|
||||||
|
for (let i = 1; i <= pdf.numPages; i++) {
|
||||||
|
const rs = rows(await getRuns(await pdf.getPage(i), 0.9));
|
||||||
|
const starts = rs.flat().map((r) => r.s0).sort((a, b) => a - b);
|
||||||
|
const cols: number[] = [];
|
||||||
|
for (const s of starts) if (!cols.length || s - cols[cols.length - 1] > 12) cols.push(s);
|
||||||
|
const colOf = (s: number) => cols.reduce((best, c, k) => (Math.abs(c - s) < Math.abs(cols[best] - s) ? k : best), 0);
|
||||||
|
const aoa = rs.map((row) => {
|
||||||
|
const line: string[] = [];
|
||||||
|
for (const r of row) {
|
||||||
|
const k = colOf(r.s0);
|
||||||
|
line[k] = line[k] ? `${line[k]} ${r.text}` : r.text;
|
||||||
|
}
|
||||||
|
return Array.from(line, (v) => {
|
||||||
|
const n = Number(String(v ?? '').replace(/,/g, ''));
|
||||||
|
return v && /^-?[\d,]+(\.\d+)?$/.test(v.trim()) && Number.isFinite(n) ? n : (v ?? '');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(aoa), `Page ${i}`);
|
||||||
|
}
|
||||||
|
const buf = XLSX.write(wb, { type: 'array', bookType: 'xlsx' }) as ArrayBuffer;
|
||||||
|
return new Blob([buf], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
|
||||||
|
}
|
||||||
@@ -0,0 +1,310 @@
|
|||||||
|
import {
|
||||||
|
BlendMode,
|
||||||
|
LineCapStyle,
|
||||||
|
PDFArray,
|
||||||
|
PDFCheckBox,
|
||||||
|
PDFDict,
|
||||||
|
PDFDocument,
|
||||||
|
PDFDropdown,
|
||||||
|
PDFHexString,
|
||||||
|
PDFName,
|
||||||
|
PDFOptionList,
|
||||||
|
PDFRadioGroup,
|
||||||
|
PDFRef,
|
||||||
|
PDFStream,
|
||||||
|
PDFTextField,
|
||||||
|
type PDFObject,
|
||||||
|
degrees,
|
||||||
|
rgb,
|
||||||
|
type PDFFont,
|
||||||
|
type PDFImage,
|
||||||
|
type PDFPage,
|
||||||
|
} from 'pdf-lib';
|
||||||
|
import fontkit from '@pdf-lib/fontkit';
|
||||||
|
import './pdflibThaiFix';
|
||||||
|
import type { DocState, Item, ShapeItem } from './types';
|
||||||
|
import { removePageContent } from './contentEdit';
|
||||||
|
import { ownBox } from './geom';
|
||||||
|
import { BASELINE, LINE_H, dataUrlBytes, hexToRgb01 } from './util';
|
||||||
|
import { loadPdf, renderPage, scaleFor } from './pdfjs';
|
||||||
|
import { tr } from '../i18n';
|
||||||
|
|
||||||
|
const fontCache: Record<string, Promise<ArrayBuffer>> = {};
|
||||||
|
export function fontBytes(bold: boolean): Promise<ArrayBuffer> {
|
||||||
|
const k = bold ? 'Bold' : 'Regular';
|
||||||
|
return (fontCache[k] ??= fetch(`${import.meta.env.BASE_URL}fonts/Sarabun-${k}.ttf`).then((r) => {
|
||||||
|
if (!r.ok) throw new Error(tr('โหลดฟอนต์ไม่ได้', 'Could not load font'));
|
||||||
|
return r.arrayBuffer();
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function openDoc(bytes: Uint8Array): Promise<PDFDocument> {
|
||||||
|
const d = await PDFDocument.load(bytes, { ignoreEncryption: true });
|
||||||
|
d.registerFontkit(fontkit);
|
||||||
|
return d;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Lazily embedded Sarabun fonts for one document. */
|
||||||
|
export function fontLoader(pdf: PDFDocument) {
|
||||||
|
const cache: Partial<Record<'r' | 'b', Promise<PDFFont>>> = {};
|
||||||
|
return (bold = false) =>
|
||||||
|
(cache[bold ? 'b' : 'r'] ??= fontBytes(bold).then((b) => pdf.embedFont(b, { subset: false })));
|
||||||
|
}
|
||||||
|
|
||||||
|
const color = (hex: string) => {
|
||||||
|
const c = hexToRgb01(hex);
|
||||||
|
return rgb(c.r, c.g, c.b);
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ExportOpts = { flattenForms?: boolean };
|
||||||
|
|
||||||
|
export async function exportPdf(doc: DocState, opts: ExportOpts = {}): Promise<Uint8Array> {
|
||||||
|
const pdf = await openDoc(doc.bytes);
|
||||||
|
const font = fontLoader(pdf);
|
||||||
|
const images = new Map<string, Promise<PDFImage>>();
|
||||||
|
const image = (url: string) => {
|
||||||
|
let p = images.get(url);
|
||||||
|
if (!p) {
|
||||||
|
const bytes = dataUrlBytes(url);
|
||||||
|
p = url.startsWith('data:image/png') ? pdf.embedPng(bytes) : pdf.embedJpg(bytes);
|
||||||
|
images.set(url, p);
|
||||||
|
}
|
||||||
|
return p;
|
||||||
|
};
|
||||||
|
const pages = pdf.getPages();
|
||||||
|
const redacted = new Set<number>();
|
||||||
|
|
||||||
|
// Really delete original text/images the user edited (not just cover them).
|
||||||
|
doc.pageIds.forEach((pid, idx) => {
|
||||||
|
const wo = doc.items.filter((i) => i.pageId === pid && i.kind === 'whiteout' && i.src) as ShapeItem[];
|
||||||
|
if (!wo.length) return;
|
||||||
|
try {
|
||||||
|
removePageContent(
|
||||||
|
pdf,
|
||||||
|
pages[idx],
|
||||||
|
wo.filter((w) => w.src!.startsWith('t:')).map((w) => w.rect),
|
||||||
|
wo.filter((w) => w.src!.startsWith('i:')).map((w) => w.rect),
|
||||||
|
);
|
||||||
|
} catch (e) {
|
||||||
|
console.warn('content removal failed; original stays covered by whiteout', e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const it of doc.items) {
|
||||||
|
const idx = doc.pageIds.indexOf(it.pageId);
|
||||||
|
if (idx < 0 || it.kind === 'field') continue;
|
||||||
|
if (it.kind === 'redact') redacted.add(idx);
|
||||||
|
await drawItem(pdf, pages[idx], it, font, image);
|
||||||
|
}
|
||||||
|
|
||||||
|
const fields = doc.items.filter((i) => i.kind === 'field');
|
||||||
|
const formEntries = Object.entries(doc.form);
|
||||||
|
if (formEntries.length || fields.length || opts.flattenForms) {
|
||||||
|
const form = pdf.getForm();
|
||||||
|
for (const [name, val] of formEntries) {
|
||||||
|
try {
|
||||||
|
const f = form.getField(name);
|
||||||
|
if (f instanceof PDFTextField) f.setText(String(val));
|
||||||
|
else if (f instanceof PDFCheckBox) {
|
||||||
|
if (val) f.check();
|
||||||
|
else f.uncheck();
|
||||||
|
} else if ((f instanceof PDFRadioGroup || f instanceof PDFDropdown || f instanceof PDFOptionList) && typeof val === 'string' && val) {
|
||||||
|
f.select(val);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.warn('form field', name, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const taken = new Set(form.getFields().map((f) => f.getName()));
|
||||||
|
for (const it of fields) {
|
||||||
|
const idx = doc.pageIds.indexOf(it.pageId);
|
||||||
|
if (idx < 0) continue;
|
||||||
|
const base = it.name.trim() || 'field';
|
||||||
|
let name = base;
|
||||||
|
for (let n = 2; taken.has(name); n++) name = `${base}_${n}`;
|
||||||
|
taken.add(name);
|
||||||
|
const box = { x: it.rect.x, y: it.rect.y, width: it.rect.w, height: it.rect.h, borderColor: rgb(0.45, 0.5, 0.6), borderWidth: 1 };
|
||||||
|
if (it.fieldType === 'checkbox') form.createCheckBox(name).addToPage(pages[idx], box);
|
||||||
|
else form.createTextField(name).addToPage(pages[idx], { ...box, font: await font() });
|
||||||
|
}
|
||||||
|
form.updateFieldAppearances(await font());
|
||||||
|
if (opts.flattenForms) form.flatten();
|
||||||
|
}
|
||||||
|
|
||||||
|
dropUnreachable(pdf);
|
||||||
|
let out = await pdf.save();
|
||||||
|
if (redacted.size) out = await rasterizePages(out, [...redacted]);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* pdf-lib writes every object it loaded, including ones nothing points to any more (removed
|
||||||
|
* pages, replaced content streams). Delete those so removed or redacted content is not left in
|
||||||
|
* the saved file.
|
||||||
|
*/
|
||||||
|
function dropUnreachable(pdf: PDFDocument) {
|
||||||
|
const ctx = pdf.context;
|
||||||
|
const seen = new Set<string>();
|
||||||
|
const stack: PDFObject[] = [];
|
||||||
|
const t = ctx.trailerInfo;
|
||||||
|
for (const o of [t.Root, t.Info, t.Encrypt]) if (o) stack.push(o);
|
||||||
|
while (stack.length) {
|
||||||
|
const o = stack.pop()!;
|
||||||
|
if (o instanceof PDFRef) {
|
||||||
|
if (seen.has(o.tag)) continue;
|
||||||
|
seen.add(o.tag);
|
||||||
|
const v = ctx.lookup(o);
|
||||||
|
if (v) stack.push(v);
|
||||||
|
} else if (o instanceof PDFDict) stack.push(...o.values());
|
||||||
|
else if (o instanceof PDFArray) stack.push(...o.asArray());
|
||||||
|
else if (o instanceof PDFStream) stack.push(o.dict);
|
||||||
|
}
|
||||||
|
for (const [ref] of ctx.enumerateIndirectObjects()) if (!seen.has(ref.tag)) ctx.delete(ref);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function drawItem(
|
||||||
|
pdf: PDFDocument,
|
||||||
|
page: PDFPage,
|
||||||
|
it: Item,
|
||||||
|
font: (bold?: boolean) => Promise<PDFFont>,
|
||||||
|
image: (url: string) => Promise<PDFImage>,
|
||||||
|
) {
|
||||||
|
switch (it.kind) {
|
||||||
|
case 'highlight':
|
||||||
|
page.drawRectangle({ x: it.rect.x, y: it.rect.y, width: it.rect.w, height: it.rect.h, color: color(it.fill ?? '#ffeb3b'), opacity: it.opacity, blendMode: BlendMode.Multiply });
|
||||||
|
break;
|
||||||
|
case 'whiteout':
|
||||||
|
page.drawRectangle({ x: it.rect.x, y: it.rect.y, width: it.rect.w, height: it.rect.h, color: color(it.fill ?? '#ffffff') });
|
||||||
|
break;
|
||||||
|
case 'redact':
|
||||||
|
page.drawRectangle({ x: it.rect.x, y: it.rect.y, width: it.rect.w, height: it.rect.h, color: rgb(0, 0, 0) });
|
||||||
|
break;
|
||||||
|
case 'rect':
|
||||||
|
page.drawRectangle({
|
||||||
|
x: it.rect.x, y: it.rect.y, width: it.rect.w, height: it.rect.h,
|
||||||
|
borderColor: color(it.stroke), borderWidth: it.width, borderOpacity: it.opacity,
|
||||||
|
color: it.fill ? color(it.fill) : undefined, opacity: it.opacity,
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
case 'ellipse':
|
||||||
|
page.drawEllipse({
|
||||||
|
x: it.rect.x + it.rect.w / 2, y: it.rect.y + it.rect.h / 2, xScale: it.rect.w / 2, yScale: it.rect.h / 2,
|
||||||
|
borderColor: color(it.stroke), borderWidth: it.width, borderOpacity: it.opacity,
|
||||||
|
color: it.fill ? color(it.fill) : undefined, opacity: it.opacity,
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
case 'line':
|
||||||
|
case 'arrow': {
|
||||||
|
const o = { thickness: it.width, color: color(it.stroke), opacity: it.opacity, lineCap: LineCapStyle.Round };
|
||||||
|
page.drawLine({ start: it.a, end: it.b, ...o });
|
||||||
|
if (it.kind === 'arrow') {
|
||||||
|
const ang = Math.atan2(it.b.y - it.a.y, it.b.x - it.a.x);
|
||||||
|
const len = Math.max(8, it.width * 4);
|
||||||
|
for (const s of [-1, 1]) {
|
||||||
|
const a = ang + Math.PI - s * 0.45;
|
||||||
|
page.drawLine({ start: it.b, end: { x: it.b.x + len * Math.cos(a), y: it.b.y + len * Math.sin(a) }, ...o });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'ink': {
|
||||||
|
if (it.points.length < 2) break;
|
||||||
|
// drawSvgPath flips y (SVG is y-down), so negate y and draw at the origin.
|
||||||
|
const d = it.points.map((p, i) => `${i ? 'L' : 'M'}${p.x.toFixed(2)} ${(-p.y).toFixed(2)}`).join(' ');
|
||||||
|
page.drawSvgPath(d, { x: 0, y: 0, borderColor: color(it.stroke), borderWidth: it.width, borderOpacity: it.opacity, borderLineCap: LineCapStyle.Round });
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'text': {
|
||||||
|
const f = await font(it.bold);
|
||||||
|
const b = ownBox(it.rect, it.rot);
|
||||||
|
if (it.bg) page.drawRectangle({ x: it.rect.x, y: it.rect.y, width: it.rect.w, height: it.rect.h, color: color(it.bg) });
|
||||||
|
it.text.split('\n').forEach((line, i) => {
|
||||||
|
if (!line) return;
|
||||||
|
const v = b.H - (i * LINE_H * it.size + BASELINE * it.size);
|
||||||
|
page.drawText(line, {
|
||||||
|
x: b.origin.x + b.up.x * v, y: b.origin.y + b.up.y * v,
|
||||||
|
size: it.size, font: f, color: color(it.color), rotate: degrees(it.rot),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'image': {
|
||||||
|
const b = ownBox(it.rect, it.rot);
|
||||||
|
page.drawImage(await image(it.dataUrl), { x: b.origin.x, y: b.origin.y, width: b.W, height: b.H, rotate: degrees(it.rot) });
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'note': {
|
||||||
|
const c = hexToRgb01(it.color);
|
||||||
|
const annot = pdf.context.obj({
|
||||||
|
Type: 'Annot',
|
||||||
|
Subtype: 'Text',
|
||||||
|
Rect: [it.at.x, it.at.y - 20, it.at.x + 20, it.at.y],
|
||||||
|
Contents: PDFHexString.fromText(it.text),
|
||||||
|
Name: 'Comment',
|
||||||
|
C: [c.r, c.g, c.b],
|
||||||
|
F: 4,
|
||||||
|
Open: false,
|
||||||
|
});
|
||||||
|
page.node.addAnnot(pdf.context.register(annot));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Replace pages with flat images so redacted content is truly gone. */
|
||||||
|
async function rasterizePages(bytes: Uint8Array, idxs: number[]): Promise<Uint8Array> {
|
||||||
|
const pjs = await loadPdf(bytes);
|
||||||
|
const pdf = await PDFDocument.load(bytes, { ignoreEncryption: true });
|
||||||
|
try {
|
||||||
|
for (const i of idxs) {
|
||||||
|
const pg = await pjs.getPage(i + 1);
|
||||||
|
const c = await renderPage(pg, scaleFor(pg, 2600, 3));
|
||||||
|
const vp = pg.getViewport({ scale: 1 });
|
||||||
|
const jpg = await pdf.embedJpg(dataUrlBytes(c.toDataURL('image/jpeg', 0.9)));
|
||||||
|
const old = pdf.getPage(i);
|
||||||
|
// Field values (/V) would keep the text; their appearance is already in the image.
|
||||||
|
removeFieldsOnPage(pdf, old);
|
||||||
|
const np = pdf.insertPage(i, [vp.width, vp.height]);
|
||||||
|
np.drawImage(jpg, { x: 0, y: 0, width: vp.width, height: vp.height });
|
||||||
|
pdf.removePage(i + 1);
|
||||||
|
// Outlines, links and structure trees may still point at the old page and keep it alive.
|
||||||
|
replaceRefs(pdf, old.ref, np.ref);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
pjs.destroy();
|
||||||
|
}
|
||||||
|
dropUnreachable(pdf);
|
||||||
|
return pdf.save();
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeFieldsOnPage(pdf: PDFDocument, page: PDFPage) {
|
||||||
|
if (!pdf.catalog.get(PDFName.of('AcroForm'))) return;
|
||||||
|
const annots = page.node.Annots()?.asArray().map((r) => pdf.context.lookup(r)) ?? [];
|
||||||
|
const form = pdf.getForm();
|
||||||
|
for (const f of form.getFields()) {
|
||||||
|
if (!f.acroField.getWidgets().some((w) => annots.includes(w.dict))) continue;
|
||||||
|
try {
|
||||||
|
form.removeField(f);
|
||||||
|
} catch (e) {
|
||||||
|
console.warn('could not remove field on redacted page', f.getName(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function replaceRefs(pdf: PDFDocument, from: PDFRef, to: PDFRef) {
|
||||||
|
const visit = (o: PDFObject | undefined) => {
|
||||||
|
if (o instanceof PDFStream) visit(o.dict);
|
||||||
|
else if (o instanceof PDFDict) {
|
||||||
|
for (const [k, v] of o.entries()) {
|
||||||
|
if (v === from) o.set(k, to);
|
||||||
|
else visit(v);
|
||||||
|
}
|
||||||
|
} else if (o instanceof PDFArray) {
|
||||||
|
o.asArray().forEach((v, k) => {
|
||||||
|
if (v === from) o.set(k, to);
|
||||||
|
else visit(v);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
for (const [, obj] of pdf.context.enumerateIndirectObjects()) visit(obj);
|
||||||
|
}
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
import type { Item, Pt, Rect } from './types';
|
||||||
|
|
||||||
|
/** Minimal shape of a pdf.js PageViewport that we rely on. */
|
||||||
|
export type VP = {
|
||||||
|
width: number;
|
||||||
|
height: number;
|
||||||
|
scale: number;
|
||||||
|
rotation: number;
|
||||||
|
convertToViewportPoint(x: number, y: number): number[];
|
||||||
|
convertToPdfPoint(x: number, y: number): number[];
|
||||||
|
};
|
||||||
|
export type Box = { left: number; top: number; width: number; height: number };
|
||||||
|
|
||||||
|
export const norm360 = (d: number) => ((Math.round(d) % 360) + 360) % 360;
|
||||||
|
|
||||||
|
export function toScreen(vp: VP, p: Pt): Pt {
|
||||||
|
const [x, y] = vp.convertToViewportPoint(p.x, p.y);
|
||||||
|
return { x, y };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function toPdf(vp: VP, x: number, y: number): Pt {
|
||||||
|
const [px, py] = vp.convertToPdfPoint(x, y);
|
||||||
|
return { x: px, y: py };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function normRect(a: Pt, b: Pt): Rect {
|
||||||
|
return { x: Math.min(a.x, b.x), y: Math.min(a.y, b.y), w: Math.abs(a.x - b.x), h: Math.abs(a.y - b.y) };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function bbox(pts: Pt[]): Rect {
|
||||||
|
const xs = pts.map((p) => p.x);
|
||||||
|
const ys = pts.map((p) => p.y);
|
||||||
|
const x = Math.min(...xs);
|
||||||
|
const y = Math.min(...ys);
|
||||||
|
return { x, y, w: Math.max(...xs) - x, h: Math.max(...ys) - y };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function rectToScreen(vp: VP, r: Rect): Box {
|
||||||
|
const a = toScreen(vp, { x: r.x, y: r.y });
|
||||||
|
const b = toScreen(vp, { x: r.x + r.w, y: r.y + r.h });
|
||||||
|
return { left: Math.min(a.x, b.x), top: Math.min(a.y, b.y), width: Math.abs(a.x - b.x), height: Math.abs(a.y - b.y) };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function screenToRect(vp: VP, x1: number, y1: number, x2: number, y2: number): Rect {
|
||||||
|
return normRect(toPdf(vp, x1, y1), toPdf(vp, x2, y2));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Unit vectors of an item's own frame (baseline direction and "up") in PDF space. */
|
||||||
|
export function axes(rot: number) {
|
||||||
|
const r = (norm360(rot) * Math.PI) / 180;
|
||||||
|
const c = Math.round(Math.cos(r));
|
||||||
|
const s = Math.round(Math.sin(r));
|
||||||
|
return { right: { x: c, y: s }, up: { x: -s, y: c } };
|
||||||
|
}
|
||||||
|
|
||||||
|
const corners = (r: Rect): Pt[] => [
|
||||||
|
{ x: r.x, y: r.y },
|
||||||
|
{ x: r.x + r.w, y: r.y },
|
||||||
|
{ x: r.x, y: r.y + r.h },
|
||||||
|
{ x: r.x + r.w, y: r.y + r.h },
|
||||||
|
];
|
||||||
|
|
||||||
|
/** Describe a rotated item's box: its own bottom-left origin and own width/height. */
|
||||||
|
export function ownBox(rect: Rect, rot: number) {
|
||||||
|
const { right, up } = axes(rot);
|
||||||
|
const score = (p: Pt) => p.x * right.x + p.y * right.y + p.x * up.x + p.y * up.y;
|
||||||
|
const origin = corners(rect).reduce((m, p) => (score(p) < score(m) ? p : m));
|
||||||
|
const flat = norm360(rot) % 180 === 0;
|
||||||
|
return { origin, right, up, W: flat ? rect.w : rect.h, H: flat ? rect.h : rect.w };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function topLeftOf(rect: Rect, rot: number): Pt {
|
||||||
|
const b = ownBox(rect, rot);
|
||||||
|
return { x: b.origin.x + b.up.x * b.H, y: b.origin.y + b.up.y * b.H };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function rectFromTopLeft(tl: Pt, W: number, H: number, rot: number): Rect {
|
||||||
|
const { right, up } = axes(rot);
|
||||||
|
const o = { x: tl.x - up.x * H, y: tl.y - up.y * H };
|
||||||
|
return bbox([
|
||||||
|
o,
|
||||||
|
{ x: o.x + right.x * W, y: o.y + right.y * W },
|
||||||
|
{ x: o.x + up.x * H, y: o.y + up.y * H },
|
||||||
|
{ x: o.x + right.x * W + up.x * H, y: o.y + right.y * W + up.y * H },
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Rect spanning baseline coordinates s0..s1 and perpendicular t0..t1 in a rotated frame. */
|
||||||
|
export function frameRect(rot: number, s0: number, s1: number, t0: number, t1: number): Rect {
|
||||||
|
const { right, up } = axes(rot);
|
||||||
|
const p = (s: number, t: number) => ({ x: right.x * s + up.x * t, y: right.y * s + up.y * t });
|
||||||
|
return bbox([p(s0, t0), p(s1, t0), p(s0, t1), p(s1, t1)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function padRect(r: Rect, d: number): Rect {
|
||||||
|
return { x: r.x - d, y: r.y - d, w: r.w + 2 * d, h: r.h + 2 * d };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function translateItem(it: Item, d: Pt): Item {
|
||||||
|
const mv = (p: Pt) => ({ x: p.x + d.x, y: p.y + d.y });
|
||||||
|
switch (it.kind) {
|
||||||
|
case 'line':
|
||||||
|
case 'arrow':
|
||||||
|
return { ...it, a: mv(it.a), b: mv(it.b) };
|
||||||
|
case 'ink':
|
||||||
|
return { ...it, points: it.points.map(mv) };
|
||||||
|
case 'note':
|
||||||
|
return { ...it, at: mv(it.at) };
|
||||||
|
default:
|
||||||
|
return { ...it, rect: { ...it.rect, x: it.rect.x + d.x, y: it.rect.y + d.y } };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
import { createWorker } from 'tesseract.js';
|
||||||
|
import { degrees } from 'pdf-lib';
|
||||||
|
import { fontLoader, openDoc } from './export';
|
||||||
|
import { ownBox, screenToRect } from './geom';
|
||||||
|
import { renderPage, scaleFor, type PDFDocumentProxy } from './pdfjs';
|
||||||
|
import { tr } from '../i18n';
|
||||||
|
|
||||||
|
export type OcrResult = { bytes: Uint8Array; text: string };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Recognise text on the given pages and add it as an invisible text layer,
|
||||||
|
* making scanned pages searchable/selectable. Language data is fetched from the tesseract CDN.
|
||||||
|
*/
|
||||||
|
export async function ocrPdf(
|
||||||
|
bytes: Uint8Array,
|
||||||
|
pjs: PDFDocumentProxy,
|
||||||
|
pageIdxs: number[],
|
||||||
|
lang: string,
|
||||||
|
onProgress: (msg: string, frac: number) => void,
|
||||||
|
skipTextPages = true,
|
||||||
|
): Promise<OcrResult> {
|
||||||
|
if (skipTextPages) {
|
||||||
|
const keep: number[] = [];
|
||||||
|
for (const i of pageIdxs) {
|
||||||
|
const tc = await (await pjs.getPage(i + 1)).getTextContent();
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
const chars = (tc.items as any[]).reduce((n, it) => n + (it.str?.trim().length ?? 0), 0);
|
||||||
|
if (chars < 20) keep.push(i);
|
||||||
|
}
|
||||||
|
pageIdxs = keep;
|
||||||
|
if (!pageIdxs.length) throw new Error(tr('ทุกหน้ามีข้อความอยู่แล้ว (ปิดตัวเลือก “ข้ามหน้าที่มีข้อความ” เพื่อบังคับ OCR)', 'Every page already has text (untick “Skip pages that already have text” to force OCR)'));
|
||||||
|
}
|
||||||
|
let step = 0;
|
||||||
|
onProgress(tr('กำลังโหลดโมเดล OCR…', 'Loading OCR model…'), 0);
|
||||||
|
const worker = await createWorker(lang.split('+'), 1, {
|
||||||
|
logger: (m: { status: string; progress: number }) => {
|
||||||
|
if (m.status === 'recognizing text') onProgress(`OCR ${tr('หน้า', 'page')} ${pageIdxs[step] + 1}`, (step + m.progress) / pageIdxs.length);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const doc = await openDoc(bytes);
|
||||||
|
const font = await fontLoader(doc)();
|
||||||
|
const pages = doc.getPages();
|
||||||
|
const texts: string[] = [];
|
||||||
|
try {
|
||||||
|
for (step = 0; step < pageIdxs.length; step++) {
|
||||||
|
const idx = pageIdxs[step];
|
||||||
|
const page = await pjs.getPage(idx + 1);
|
||||||
|
const scale = scaleFor(page, 3000, 4);
|
||||||
|
const canvas = await renderPage(page, scale);
|
||||||
|
const vp = page.getViewport({ scale });
|
||||||
|
const { data } = await worker.recognize(canvas);
|
||||||
|
texts.push(data.text);
|
||||||
|
// Draw per line, not per word: Thai has no spaces and tesseract returns one "word" per
|
||||||
|
// character cluster, which text extractors would then split with spaces.
|
||||||
|
for (const w of data.lines ?? []) {
|
||||||
|
const text = w.text.trim();
|
||||||
|
if (!text || w.confidence < 40) continue;
|
||||||
|
const { x0, y0, x1, y1 } = w.bbox;
|
||||||
|
const b = ownBox(screenToRect(vp, x0, y0, x1, y1), page.rotate);
|
||||||
|
const unit = font.widthOfTextAtSize(text, 1);
|
||||||
|
const size = Math.max(1, Math.min(b.H, unit ? b.W / unit : b.H));
|
||||||
|
const v = b.H * 0.22;
|
||||||
|
pages[idx].drawText(text, {
|
||||||
|
x: b.origin.x + b.up.x * v, y: b.origin.y + b.up.y * v,
|
||||||
|
size, font, opacity: 0, rotate: degrees(page.rotate),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
await worker.terminate();
|
||||||
|
}
|
||||||
|
onProgress(tr('เสร็จแล้ว', 'Done'), 1);
|
||||||
|
return { bytes: await doc.save(), text: texts.join('\n\n') };
|
||||||
|
}
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
import { PDFDocument, degrees, rgb, type PDFPage } from 'pdf-lib';
|
||||||
|
import { fontLoader, openDoc } from './export';
|
||||||
|
import { norm360, ownBox } from './geom';
|
||||||
|
import { dataUrlBytes, hexToRgb01, imageFileToPending } from './util';
|
||||||
|
|
||||||
|
const A4: [number, number] = [595.28, 841.89];
|
||||||
|
|
||||||
|
export async function rotatePages(bytes: Uint8Array, idxs: number[], delta: number) {
|
||||||
|
const d = await openDoc(bytes);
|
||||||
|
const ps = d.getPages();
|
||||||
|
for (const i of idxs) ps[i].setRotation(degrees(norm360(ps[i].getRotation().angle + delta)));
|
||||||
|
return d.save();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deletePages(bytes: Uint8Array, idxs: number[]) {
|
||||||
|
const d = await openDoc(bytes);
|
||||||
|
[...idxs].sort((a, b) => b - a).forEach((i) => d.removePage(i));
|
||||||
|
return d.save();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reorder in place (keeps form fields and links attached to the same document). */
|
||||||
|
export async function reorderPages(bytes: Uint8Array, order: number[]) {
|
||||||
|
const d = await openDoc(bytes);
|
||||||
|
const ps = d.getPages();
|
||||||
|
for (let i = ps.length - 1; i >= 0; i--) d.removePage(i);
|
||||||
|
order.forEach((i) => d.addPage(ps[i]));
|
||||||
|
return d.save();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function insertBlank(bytes: Uint8Array, at: number) {
|
||||||
|
const d = await openDoc(bytes);
|
||||||
|
const n = d.getPageCount();
|
||||||
|
const ref = n ? d.getPage(Math.min(Math.max(0, at - 1), n - 1)).getSize() : null;
|
||||||
|
d.insertPage(at, ref ? [ref.width, ref.height] : A4);
|
||||||
|
return d.save();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function blankPdf() {
|
||||||
|
const d = await PDFDocument.create();
|
||||||
|
d.addPage(A4);
|
||||||
|
return d.save();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Append other PDFs; returns new bytes and how many pages each source added. */
|
||||||
|
export async function appendPdfs(bytes: Uint8Array, others: Uint8Array[]) {
|
||||||
|
const d = await openDoc(bytes);
|
||||||
|
const counts: number[] = [];
|
||||||
|
for (const o of others) {
|
||||||
|
const src = await PDFDocument.load(o, { ignoreEncryption: true });
|
||||||
|
const copied = await d.copyPages(src, src.getPageIndices());
|
||||||
|
copied.forEach((p) => d.addPage(p));
|
||||||
|
counts.push(copied.length);
|
||||||
|
}
|
||||||
|
return { bytes: await d.save(), added: counts.reduce((a, b) => a + b, 0) };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function extractPages(bytes: Uint8Array, idxs: number[]) {
|
||||||
|
const src = await PDFDocument.load(bytes, { ignoreEncryption: true });
|
||||||
|
const d = await PDFDocument.create();
|
||||||
|
(await d.copyPages(src, idxs)).forEach((p) => d.addPage(p));
|
||||||
|
return d.save();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function splitEvery(bytes: Uint8Array, n: number) {
|
||||||
|
const src = await PDFDocument.load(bytes, { ignoreEncryption: true });
|
||||||
|
const total = src.getPageCount();
|
||||||
|
const parts: Uint8Array[] = [];
|
||||||
|
for (let i = 0; i < total; i += n) {
|
||||||
|
const idxs = Array.from({ length: Math.min(n, total - i) }, (_, k) => i + k);
|
||||||
|
const d = await PDFDocument.create();
|
||||||
|
(await d.copyPages(src, idxs)).forEach((p) => d.addPage(p));
|
||||||
|
parts.push(await d.save());
|
||||||
|
}
|
||||||
|
return parts;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Add image pages (page size follows the image, longest side ≤ A4 height). */
|
||||||
|
export async function imagesToPdf(files: File[], base?: Uint8Array) {
|
||||||
|
const d = base ? await openDoc(base) : await PDFDocument.create();
|
||||||
|
for (const f of files) {
|
||||||
|
const p = await imageFileToPending(f, 100000);
|
||||||
|
const bytes = dataUrlBytes(p.dataUrl);
|
||||||
|
const img = p.dataUrl.startsWith('data:image/png') ? await d.embedPng(bytes) : await d.embedJpg(bytes);
|
||||||
|
const k = Math.min(1, A4[1] / Math.max(img.width, img.height));
|
||||||
|
const w = img.width * k;
|
||||||
|
const h = img.height * k;
|
||||||
|
d.addPage([w, h]).drawImage(img, { x: 0, y: 0, width: w, height: h });
|
||||||
|
}
|
||||||
|
return { bytes: await d.save(), added: files.length };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Map a point in the page's upright (as displayed) frame to PDF space. */
|
||||||
|
function viewerFrame(page: PDFPage) {
|
||||||
|
const mb = page.getMediaBox();
|
||||||
|
const rot = page.getRotation().angle;
|
||||||
|
const b = ownBox({ x: mb.x, y: mb.y, w: mb.width, h: mb.height }, rot);
|
||||||
|
const at = (u: number, v: number) => ({ x: b.origin.x + b.right.x * u + b.up.x * v, y: b.origin.y + b.right.y * u + b.up.y * v });
|
||||||
|
return { W: b.W, H: b.H, rot, at };
|
||||||
|
}
|
||||||
|
|
||||||
|
export type WatermarkOpts = { text: string; size: number; opacity: number; color: string; angle: number };
|
||||||
|
export async function addWatermark(bytes: Uint8Array, o: WatermarkOpts) {
|
||||||
|
const d = await openDoc(bytes);
|
||||||
|
const font = await fontLoader(d)(true);
|
||||||
|
const c = hexToRgb01(o.color);
|
||||||
|
for (const page of d.getPages()) {
|
||||||
|
const f = viewerFrame(page);
|
||||||
|
const a = norm360(f.rot + o.angle);
|
||||||
|
const rad = (a * Math.PI) / 180;
|
||||||
|
const tw = font.widthOfTextAtSize(o.text, o.size);
|
||||||
|
const ctr = f.at(f.W / 2, f.H / 2);
|
||||||
|
const dir = { x: Math.cos(rad), y: Math.sin(rad) };
|
||||||
|
const perp = { x: -dir.y, y: dir.x };
|
||||||
|
page.drawText(o.text, {
|
||||||
|
x: ctr.x - (dir.x * tw) / 2 - perp.x * o.size * 0.35,
|
||||||
|
y: ctr.y - (dir.y * tw) / 2 - perp.y * o.size * 0.35,
|
||||||
|
size: o.size, font, opacity: o.opacity, color: rgb(c.r, c.g, c.b), rotate: degrees(a),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return d.save();
|
||||||
|
}
|
||||||
|
|
||||||
|
export type PageNumOpts = { format: string; pos: 'bc' | 'br' | 'bl' | 'tr' | 'tc'; size: number; start: number };
|
||||||
|
export async function addPageNumbers(bytes: Uint8Array, o: PageNumOpts) {
|
||||||
|
const d = await openDoc(bytes);
|
||||||
|
const font = await fontLoader(d)();
|
||||||
|
const pages = d.getPages();
|
||||||
|
pages.forEach((page, i) => {
|
||||||
|
const f = viewerFrame(page);
|
||||||
|
const text = o.format.replace('{n}', String(i + o.start)).replace('{total}', String(pages.length + o.start - 1));
|
||||||
|
const tw = font.widthOfTextAtSize(text, o.size);
|
||||||
|
const m = 28;
|
||||||
|
const u = o.pos.endsWith('l') ? m : o.pos.endsWith('r') ? f.W - m - tw : (f.W - tw) / 2;
|
||||||
|
const v = o.pos.startsWith('t') ? f.H - m : m - o.size * 0.3;
|
||||||
|
const p = f.at(u, v);
|
||||||
|
page.drawText(text, { x: p.x, y: p.y, size: o.size, font, color: rgb(0.2, 0.2, 0.2), rotate: degrees(f.rot) });
|
||||||
|
});
|
||||||
|
return d.save();
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import * as pdfjs from 'pdfjs-dist';
|
||||||
|
import type { PDFDocumentProxy, PDFPageProxy } from 'pdfjs-dist';
|
||||||
|
import workerUrl from 'pdfjs-dist/build/pdf.worker.min.mjs?url';
|
||||||
|
|
||||||
|
pdfjs.GlobalWorkerOptions.workerSrc = workerUrl;
|
||||||
|
const BASE = import.meta.env.BASE_URL;
|
||||||
|
|
||||||
|
export { pdfjs };
|
||||||
|
export type { PDFDocumentProxy, PDFPageProxy };
|
||||||
|
|
||||||
|
export function loadPdf(bytes: Uint8Array): Promise<PDFDocumentProxy> {
|
||||||
|
// pdf.js transfers the buffer to its worker, so always hand it a copy.
|
||||||
|
return pdfjs.getDocument({
|
||||||
|
data: bytes.slice(),
|
||||||
|
cMapUrl: `${BASE}pdfjs/cmaps/`,
|
||||||
|
cMapPacked: true,
|
||||||
|
standardFontDataUrl: `${BASE}pdfjs/standard_fonts/`,
|
||||||
|
isEvalSupported: false,
|
||||||
|
}).promise;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Render a page to a fresh canvas (white background). `forms: false` hides form-field appearances. */
|
||||||
|
export async function renderPage(page: PDFPageProxy, scale: number, forms = true): Promise<HTMLCanvasElement> {
|
||||||
|
const vp = page.getViewport({ scale });
|
||||||
|
const c = document.createElement('canvas');
|
||||||
|
c.width = Math.ceil(vp.width);
|
||||||
|
c.height = Math.ceil(vp.height);
|
||||||
|
const ctx = c.getContext('2d')!;
|
||||||
|
ctx.fillStyle = '#fff';
|
||||||
|
ctx.fillRect(0, 0, c.width, c.height);
|
||||||
|
await page.render({
|
||||||
|
canvasContext: ctx,
|
||||||
|
viewport: vp,
|
||||||
|
annotationMode: forms ? pdfjs.AnnotationMode.ENABLE : pdfjs.AnnotationMode.ENABLE_FORMS,
|
||||||
|
}).promise;
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Pick a render scale so the longest side is about `target` pixels. */
|
||||||
|
export function scaleFor(page: PDFPageProxy, target: number, max = 4): number {
|
||||||
|
const vp = page.getViewport({ scale: 1 });
|
||||||
|
return Math.min(max, target / Math.max(vp.width, vp.height));
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
/**
|
||||||
|
* pdf-lib only writes widths (/W) and ToUnicode entries for glyphs reachable from the font's
|
||||||
|
* cmap. Thai shaping (GSUB) swaps in alternates such as `uni0E48.small`; those glyphs then get
|
||||||
|
* the default width 1000 (visible gaps between letters) and no Unicode mapping (tone marks
|
||||||
|
* vanish when copying/searching). Patch the non-subset embedder to cover every glyph.
|
||||||
|
*/
|
||||||
|
import { CustomFontEmbedder, PDFRef } from 'pdf-lib';
|
||||||
|
|
||||||
|
type FkGlyph = { id: number; advanceWidth: number; codePoints: number[]; name?: string };
|
||||||
|
type Embedder = {
|
||||||
|
font: { numGlyphs: number; getGlyph(id: number): FkGlyph };
|
||||||
|
scale: number;
|
||||||
|
constructor: unknown;
|
||||||
|
};
|
||||||
|
type Ctx = { flateStream(s: string): unknown; register(o: unknown): PDFRef };
|
||||||
|
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
const proto = (CustomFontEmbedder as any).prototype;
|
||||||
|
const origWidths = proto.computeWidths;
|
||||||
|
const origCmap = proto.embedUnicodeCmap;
|
||||||
|
|
||||||
|
const isPlain = (e: Embedder): boolean => e.constructor === (CustomFontEmbedder as unknown);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Code point(s) of a glyph, preferring its post-table name (e.g. "uni0E48.small") over the cmap.
|
||||||
|
* The name wins because the cmap can point a composite character at one part of it: Sarabun maps
|
||||||
|
* SARA AM (U+0E33) to the NIKHAHIT glyph "uni0E4D" and GSUB appends "uni0E32", so cmap-based
|
||||||
|
* mapping would copy out "ำา" instead of "ํา" (the NFKC form of "ำ").
|
||||||
|
*/
|
||||||
|
function codePointsFor(g: FkGlyph): number[] {
|
||||||
|
const base = (g.name ?? '').split('.')[0];
|
||||||
|
const uni = /^uni([0-9A-F]{4})+$/i.exec(base);
|
||||||
|
if (uni) return base.slice(3).match(/.{4}/g)!.map((h) => parseInt(h, 16));
|
||||||
|
const u = /^u([0-9A-F]{4,6})$/i.exec(base);
|
||||||
|
if (u) return [parseInt(u[1], 16)];
|
||||||
|
return g.codePoints ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
|
const hex4 = (n: number) => n.toString(16).toUpperCase().padStart(4, '0');
|
||||||
|
const utf16 = (cp: number) => {
|
||||||
|
if (cp < 0x10000) return hex4(cp);
|
||||||
|
const v = cp - 0x10000;
|
||||||
|
return hex4(0xd800 + (v >> 10)) + hex4(0xdc00 + (v & 0x3ff));
|
||||||
|
};
|
||||||
|
|
||||||
|
proto.computeWidths = function (this: Embedder) {
|
||||||
|
if (!isPlain(this)) return origWidths.call(this);
|
||||||
|
const widths: number[] = [];
|
||||||
|
for (let i = 0; i < this.font.numGlyphs; i++) widths.push(Math.round(this.font.getGlyph(i).advanceWidth * this.scale));
|
||||||
|
return [0, widths];
|
||||||
|
};
|
||||||
|
|
||||||
|
proto.embedUnicodeCmap = function (this: Embedder, context: Ctx) {
|
||||||
|
if (!isPlain(this)) return origCmap.call(this, context);
|
||||||
|
const lines: string[] = [];
|
||||||
|
for (let i = 0; i < this.font.numGlyphs; i++) {
|
||||||
|
const cps = codePointsFor(this.font.getGlyph(i));
|
||||||
|
if (cps.length) lines.push(`<${hex4(i)}> <${cps.map(utf16).join('')}>`);
|
||||||
|
}
|
||||||
|
const chunks: string[] = [];
|
||||||
|
for (let i = 0; i < lines.length; i += 100) {
|
||||||
|
const part = lines.slice(i, i + 100);
|
||||||
|
chunks.push(`${part.length} beginbfchar\n${part.join('\n')}\nendbfchar`);
|
||||||
|
}
|
||||||
|
const cmap =
|
||||||
|
'/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n/CIDSystemInfo <<\n /Registry (Adobe)\n /Ordering (UCS)\n /Supplement 0\n>> def\n' +
|
||||||
|
'/CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n1 begincodespacerange\n<0000><ffff>\nendcodespacerange\n' +
|
||||||
|
chunks.join('\n') +
|
||||||
|
'\nendcmap\nCMapName currentdict /CMap defineresource pop\nend\nend';
|
||||||
|
return context.register(context.flateStream(cmap));
|
||||||
|
};
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
import type { Pending } from './types';
|
||||||
|
import { locale } from '../i18n';
|
||||||
|
|
||||||
|
export const STAMPS: { text: string; color: string }[] = [
|
||||||
|
{ text: 'อนุมัติ', color: '#1b8a3a' },
|
||||||
|
{ text: 'APPROVED', color: '#1b8a3a' },
|
||||||
|
{ text: 'ไม่อนุมัติ', color: '#c62828' },
|
||||||
|
{ text: 'REJECTED', color: '#c62828' },
|
||||||
|
{ text: 'สำเนาถูกต้อง', color: '#1f4fbf' },
|
||||||
|
{ text: 'ลับ', color: '#c62828' },
|
||||||
|
{ text: 'CONFIDENTIAL', color: '#c62828' },
|
||||||
|
{ text: 'DRAFT', color: '#6b6b6b' },
|
||||||
|
{ text: 'ชำระแล้ว', color: '#1f4fbf' },
|
||||||
|
{ text: 'PAID', color: '#1f4fbf' },
|
||||||
|
];
|
||||||
|
|
||||||
|
/** Render a rubber-stamp style image (2x resolution) with today's date. */
|
||||||
|
export async function makeStamp(text: string, color: string, withDate = true): Promise<Pending> {
|
||||||
|
await document.fonts.load('700 48px Sarabun');
|
||||||
|
const size = 48;
|
||||||
|
const pad = 22;
|
||||||
|
const date = new Date().toLocaleDateString(locale(), { year: 'numeric', month: 'short', day: 'numeric' });
|
||||||
|
const c = document.createElement('canvas');
|
||||||
|
const ctx = c.getContext('2d')!;
|
||||||
|
ctx.font = `700 ${size}px Sarabun`;
|
||||||
|
const tw = ctx.measureText(text).width;
|
||||||
|
ctx.font = `400 22px Sarabun`;
|
||||||
|
const dw = withDate ? ctx.measureText(date).width : 0;
|
||||||
|
c.width = Math.ceil(Math.max(tw, dw) + pad * 2);
|
||||||
|
c.height = Math.ceil(size * 1.25 + (withDate ? 30 : 0) + pad);
|
||||||
|
ctx.strokeStyle = color;
|
||||||
|
ctx.fillStyle = color;
|
||||||
|
ctx.lineWidth = 5;
|
||||||
|
const r = 14;
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.roundRect(4, 4, c.width - 8, c.height - 8, r);
|
||||||
|
ctx.stroke();
|
||||||
|
ctx.textAlign = 'center';
|
||||||
|
ctx.textBaseline = 'middle';
|
||||||
|
ctx.font = `700 ${size}px Sarabun`;
|
||||||
|
ctx.fillText(text, c.width / 2, pad / 2 + size * 0.65);
|
||||||
|
if (withDate) {
|
||||||
|
ctx.font = `400 22px Sarabun`;
|
||||||
|
ctx.fillText(date, c.width / 2, c.height - pad / 2 - 16);
|
||||||
|
}
|
||||||
|
return { dataUrl: c.toDataURL('image/png'), w: c.width / 2.4, h: c.height / 2.4 };
|
||||||
|
}
|
||||||
|
|
||||||
|
const KEY = 'pdfedit.signatures';
|
||||||
|
export function loadSignatures(): string[] {
|
||||||
|
try {
|
||||||
|
return JSON.parse(localStorage.getItem(KEY) ?? '[]');
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
export function saveSignatures(list: string[]) {
|
||||||
|
try {
|
||||||
|
localStorage.setItem(KEY, JSON.stringify(list.slice(0, 8)));
|
||||||
|
} catch {
|
||||||
|
/* storage unavailable or full: signatures just won't persist */
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
/** Point in PDF user space (origin bottom-left, unrotated page). */
|
||||||
|
export type Pt = { x: number; y: number };
|
||||||
|
/** Axis-aligned rectangle in PDF user space; (x, y) is the bottom-left corner. */
|
||||||
|
export type Rect = { x: number; y: number; w: number; h: number };
|
||||||
|
|
||||||
|
type Base = { id: string; pageId: string };
|
||||||
|
|
||||||
|
export type ShapeKind = 'highlight' | 'rect' | 'ellipse' | 'whiteout' | 'redact';
|
||||||
|
export type ShapeItem = Base & {
|
||||||
|
kind: ShapeKind;
|
||||||
|
rect: Rect;
|
||||||
|
stroke: string;
|
||||||
|
fill: string | null;
|
||||||
|
width: number;
|
||||||
|
opacity: number;
|
||||||
|
/** Source key ("t:3" / "i:1") when this whiteout hides original page content. */
|
||||||
|
src?: string;
|
||||||
|
};
|
||||||
|
export type LineItem = Base & { kind: 'line' | 'arrow'; a: Pt; b: Pt; stroke: string; width: number; opacity: number };
|
||||||
|
export type InkItem = Base & { kind: 'ink'; points: Pt[]; stroke: string; width: number; opacity: number };
|
||||||
|
/** `rot` = counter-clockwise angle (0/90/180/270) of the item's baseline in PDF space. */
|
||||||
|
export type TextItem = Base & {
|
||||||
|
kind: 'text';
|
||||||
|
rect: Rect;
|
||||||
|
rot: number;
|
||||||
|
text: string;
|
||||||
|
size: number;
|
||||||
|
color: string;
|
||||||
|
bold: boolean;
|
||||||
|
bg: string | null;
|
||||||
|
};
|
||||||
|
export type ImageItem = Base & { kind: 'image'; rect: Rect; rot: number; dataUrl: string };
|
||||||
|
export type NoteItem = Base & { kind: 'note'; at: Pt; text: string; color: string };
|
||||||
|
export type FieldItem = Base & { kind: 'field'; rect: Rect; fieldType: 'text' | 'checkbox'; name: string };
|
||||||
|
|
||||||
|
export type Item = ShapeItem | LineItem | InkItem | TextItem | ImageItem | NoteItem | FieldItem;
|
||||||
|
|
||||||
|
export type Tool =
|
||||||
|
| 'select' | 'edit' | 'text' | 'image' | 'sign' | 'stamp' | 'whiteout'
|
||||||
|
| 'highlight' | 'pen' | 'rect' | 'ellipse' | 'line' | 'arrow' | 'note'
|
||||||
|
| 'redact' | 'fieldText' | 'fieldCheck';
|
||||||
|
|
||||||
|
export type Tab = 'edit' | 'comment' | 'sign' | 'forms' | 'pages' | 'redact' | 'ocr' | 'convert' | 'search';
|
||||||
|
|
||||||
|
/** An image waiting to be placed with a click; w/h are the default size in PDF points. */
|
||||||
|
export type Pending = { dataUrl: string; w: number; h: number };
|
||||||
|
|
||||||
|
export type ToolOpts = {
|
||||||
|
color: string;
|
||||||
|
fill: string | null;
|
||||||
|
highlight: string;
|
||||||
|
width: number;
|
||||||
|
size: number;
|
||||||
|
bold: boolean;
|
||||||
|
opacity: number;
|
||||||
|
pending: Pending | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type FormValue = string | boolean;
|
||||||
|
|
||||||
|
export type DocState = {
|
||||||
|
bytes: Uint8Array;
|
||||||
|
name: string;
|
||||||
|
/** Stable id per page, parallel to the pages of `bytes`. */
|
||||||
|
pageIds: string[];
|
||||||
|
items: Item[];
|
||||||
|
form: Record<string, FormValue>;
|
||||||
|
};
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
import type { Pending } from './types';
|
||||||
|
import { tr } from '../i18n';
|
||||||
|
|
||||||
|
export const uid = () => crypto.randomUUID();
|
||||||
|
|
||||||
|
export function download(data: Blob | Uint8Array, name: string, type = 'application/pdf') {
|
||||||
|
const blob = data instanceof Blob ? data : new Blob([data as BlobPart], { type });
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const a = document.createElement('a');
|
||||||
|
a.href = url;
|
||||||
|
a.download = name;
|
||||||
|
a.click();
|
||||||
|
setTimeout(() => URL.revokeObjectURL(url), 10_000);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const readFile = async (f: Blob) => new Uint8Array(await f.arrayBuffer());
|
||||||
|
|
||||||
|
export const fileToDataUrl = (f: Blob) =>
|
||||||
|
new Promise<string>((res, rej) => {
|
||||||
|
const r = new FileReader();
|
||||||
|
r.onload = () => res(r.result as string);
|
||||||
|
r.onerror = () => rej(r.error);
|
||||||
|
r.readAsDataURL(f);
|
||||||
|
});
|
||||||
|
|
||||||
|
export const loadImage = (src: string) =>
|
||||||
|
new Promise<HTMLImageElement>((res, rej) => {
|
||||||
|
const im = new Image();
|
||||||
|
im.onload = () => res(im);
|
||||||
|
im.onerror = () => rej(new Error(tr('โหลดรูปไม่ได้', 'Could not load image')));
|
||||||
|
im.src = src;
|
||||||
|
});
|
||||||
|
|
||||||
|
export function dataUrlBytes(dataUrl: string): Uint8Array {
|
||||||
|
const bin = atob(dataUrl.slice(dataUrl.indexOf(',') + 1));
|
||||||
|
const out = new Uint8Array(bin.length);
|
||||||
|
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hexToRgb01(hex: string) {
|
||||||
|
const h = hex.replace('#', '');
|
||||||
|
const n = parseInt(h.length === 3 ? h.split('').map((c) => c + c).join('') : h.slice(0, 6), 16) || 0;
|
||||||
|
return { r: ((n >> 16) & 255) / 255, g: ((n >> 8) & 255) / 255, b: (n & 255) / 255 };
|
||||||
|
}
|
||||||
|
|
||||||
|
export const baseName = (n: string) => n.replace(/\.[^.]+$/, '');
|
||||||
|
|
||||||
|
/** Pick a file via a hidden input. */
|
||||||
|
export function pickFiles(accept: string, multiple = false): Promise<File[]> {
|
||||||
|
return new Promise((res) => {
|
||||||
|
const inp = document.createElement('input');
|
||||||
|
inp.type = 'file';
|
||||||
|
inp.accept = accept;
|
||||||
|
inp.multiple = multiple;
|
||||||
|
inp.onchange = () => res(Array.from(inp.files ?? []));
|
||||||
|
inp.click();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Convert any browser-readable image to a PNG/JPEG data URL usable by pdf-lib. */
|
||||||
|
export async function imageFileToPending(f: File, maxW = 300): Promise<Pending> {
|
||||||
|
let url = await fileToDataUrl(f);
|
||||||
|
const im = await loadImage(url);
|
||||||
|
if (!/^data:image\/(png|jpeg)/.test(url)) {
|
||||||
|
const c = document.createElement('canvas');
|
||||||
|
c.width = im.naturalWidth;
|
||||||
|
c.height = im.naturalHeight;
|
||||||
|
c.getContext('2d')!.drawImage(im, 0, 0);
|
||||||
|
url = c.toDataURL('image/png');
|
||||||
|
}
|
||||||
|
const k = Math.min(1, maxW / im.naturalWidth);
|
||||||
|
return { dataUrl: url, w: im.naturalWidth * k, h: im.naturalHeight * k };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Crop a canvas to its non-transparent pixels. */
|
||||||
|
export function trimCanvas(c: HTMLCanvasElement, pad = 4): HTMLCanvasElement {
|
||||||
|
const ctx = c.getContext('2d')!;
|
||||||
|
const { data, width, height } = ctx.getImageData(0, 0, c.width, c.height);
|
||||||
|
let x0 = width, y0 = height, x1 = -1, y1 = -1;
|
||||||
|
for (let y = 0; y < height; y++)
|
||||||
|
for (let x = 0; x < width; x++)
|
||||||
|
if (data[(y * width + x) * 4 + 3] > 8) {
|
||||||
|
if (x < x0) x0 = x;
|
||||||
|
if (x > x1) x1 = x;
|
||||||
|
if (y < y0) y0 = y;
|
||||||
|
if (y > y1) y1 = y;
|
||||||
|
}
|
||||||
|
if (x1 < 0) return c;
|
||||||
|
x0 = Math.max(0, x0 - pad);
|
||||||
|
y0 = Math.max(0, y0 - pad);
|
||||||
|
x1 = Math.min(width - 1, x1 + pad);
|
||||||
|
y1 = Math.min(height - 1, y1 + pad);
|
||||||
|
const out = document.createElement('canvas');
|
||||||
|
out.width = x1 - x0 + 1;
|
||||||
|
out.height = y1 - y0 + 1;
|
||||||
|
out.getContext('2d')!.drawImage(c, x0, y0, out.width, out.height, 0, 0, out.width, out.height);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
const mctx = document.createElement('canvas').getContext('2d')!;
|
||||||
|
/** Measure multi-line text in Sarabun; result in the same units as `size` (PDF points). */
|
||||||
|
export function measureText(text: string, size: number, bold: boolean) {
|
||||||
|
mctx.font = `${bold ? 700 : 400} ${size}px Sarabun, sans-serif`;
|
||||||
|
const lines = text.split('\n');
|
||||||
|
const w = Math.max(...lines.map((l) => mctx.measureText(l).width));
|
||||||
|
return { w: Math.max(w, size * 0.6) + 2, h: lines.length * size * LINE_H };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Line height and baseline position (in em) used for text items, on screen and in export. */
|
||||||
|
export const LINE_H = 1.3;
|
||||||
|
export const BASELINE = 1.068;
|
||||||
|
|
||||||
|
/** Turn a thrown error into a sentence the user can act on (library errors are English and technical). */
|
||||||
|
export function friendlyError(e: unknown): string {
|
||||||
|
const err = e as Error;
|
||||||
|
const name = err?.name ?? '';
|
||||||
|
const msg = String(err?.message ?? e);
|
||||||
|
if (name === 'PasswordException' || /encrypt/i.test(msg)) return tr('ไฟล์นี้มีรหัสผ่าน — ยังเปิดแก้ไม่ได้ ปลดรหัสผ่านก่อนแล้วลองใหม่', 'This file is password-protected. Remove the password and try again.');
|
||||||
|
if (name === 'InvalidPDFException' || /invalid pdf|failed to parse|no pdf header/i.test(msg)) return tr('ไฟล์นี้ไม่ใช่ PDF หรือไฟล์เสีย — ลองเปิดไฟล์อื่น', 'This is not a PDF, or the file is damaged. Try another file.');
|
||||||
|
if (/failed to fetch|networkerror|load failed/i.test(msg)) return tr('เชื่อมต่ออินเทอร์เน็ตไม่ได้ — ต้องใช้ตอนโหลดฟอนต์หรือโมเดล OCR ครั้งแรก', 'No internet connection. It is needed the first time fonts or OCR models load.');
|
||||||
|
if (err instanceof RangeError || /allocation|out of memory/i.test(msg)) return tr('ไฟล์ใหญ่เกินหน่วยความจำของเบราว์เซอร์ — ปิดแท็บอื่นหรือแยกไฟล์ให้เล็กลง', 'The file is too large for browser memory. Close other tabs or split the file.');
|
||||||
|
if (/[\u0E00-\u0E7F]/.test(msg)) return msg; // already our own Thai message
|
||||||
|
return tr(`ทำไม่สำเร็จ ลองอีกครั้ง (${msg})`, `That didn't work. Please try again. (${msg})`);
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { StrictMode } from 'react'
|
||||||
|
import { createRoot } from 'react-dom/client'
|
||||||
|
import './index.css'
|
||||||
|
import App from './App.tsx'
|
||||||
|
|
||||||
|
createRoot(document.getElementById('root')!).render(
|
||||||
|
<StrictMode>
|
||||||
|
<App />
|
||||||
|
</StrictMode>,
|
||||||
|
)
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
/// <reference types="vite/client" />
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||||
|
"target": "ES2020",
|
||||||
|
"useDefineForClassFields": true,
|
||||||
|
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||||
|
"module": "ESNext",
|
||||||
|
"skipLibCheck": true,
|
||||||
|
|
||||||
|
/* Bundler mode */
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"allowImportingTsExtensions": true,
|
||||||
|
"verbatimModuleSyntax": true,
|
||||||
|
"moduleDetection": "force",
|
||||||
|
"noEmit": true,
|
||||||
|
"jsx": "react-jsx",
|
||||||
|
|
||||||
|
/* Linting */
|
||||||
|
"strict": true,
|
||||||
|
"noUnusedLocals": true,
|
||||||
|
"noUnusedParameters": true,
|
||||||
|
"erasableSyntaxOnly": true,
|
||||||
|
"noFallthroughCasesInSwitch": true,
|
||||||
|
"noUncheckedSideEffectImports": true
|
||||||
|
},
|
||||||
|
"include": ["src"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"files": [],
|
||||||
|
"references": [
|
||||||
|
{ "path": "./tsconfig.app.json" },
|
||||||
|
{ "path": "./tsconfig.node.json" }
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||||
|
"target": "ES2022",
|
||||||
|
"lib": ["ES2023"],
|
||||||
|
"module": "ESNext",
|
||||||
|
"skipLibCheck": true,
|
||||||
|
|
||||||
|
/* Bundler mode */
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"allowImportingTsExtensions": true,
|
||||||
|
"verbatimModuleSyntax": true,
|
||||||
|
"moduleDetection": "force",
|
||||||
|
"noEmit": true,
|
||||||
|
|
||||||
|
/* Linting */
|
||||||
|
"strict": true,
|
||||||
|
"noUnusedLocals": true,
|
||||||
|
"noUnusedParameters": true,
|
||||||
|
"erasableSyntaxOnly": true,
|
||||||
|
"noFallthroughCasesInSwitch": true,
|
||||||
|
"noUncheckedSideEffectImports": true
|
||||||
|
},
|
||||||
|
"include": ["vite.config.ts"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import { defineConfig } from 'vite'
|
||||||
|
import react from '@vitejs/plugin-react'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [react()],
|
||||||
|
build: { target: 'es2022', chunkSizeWarningLimit: 4000 },
|
||||||
|
optimizeDeps: { esbuildOptions: { target: 'es2022' } },
|
||||||
|
})
|
||||||