Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 20960f97c0 | |||
| 068debee16 | |||
| a60d03a3a7 | |||
| ba16f5fe06 |
@@ -2,6 +2,7 @@
|
||||
"name": "bizmatch-qc-desktop",
|
||||
"version": "0.1.3",
|
||||
"exports": "./main.ts",
|
||||
"unstable": ["raw-imports"],
|
||||
"imports": {
|
||||
"@std/assert": "jsr:@std/assert@^1",
|
||||
"@std/path": "jsr:@std/path@^1",
|
||||
|
||||
285
main.ts
285
main.ts
@@ -25,6 +25,147 @@ import PDFJS_LIB_TEXT from "pdfjs-dist/legacy/build/pdf.min.mjs" with {
|
||||
import PDFJS_WORKER_TEXT from "pdfjs-dist/legacy/build/pdf.worker.min.mjs" with {
|
||||
type: "text",
|
||||
};
|
||||
// PDF.js >= 5 needs these auxiliary assets at runtime (fetched by the worker):
|
||||
// - wasm/: CCITT-G4 + JBIG2 (B/W scans), JPEG2000 and qcms (ICC) decoders
|
||||
// - standard_fonts/: base-14 font substitutes for PDFs without embedded fonts
|
||||
// - iccs/: default CMYK ICC profile
|
||||
// Embedded via import attributes so the compiled desktop binary stays self-contained.
|
||||
import WASM_JBIG2 from "pdfjs-dist/wasm/jbig2.wasm" with { type: "bytes" };
|
||||
import WASM_OPENJPEG from "pdfjs-dist/wasm/openjpeg.wasm" with {
|
||||
type: "bytes",
|
||||
};
|
||||
import WASM_QCMS from "pdfjs-dist/wasm/qcms_bg.wasm" with { type: "bytes" };
|
||||
import JS_JBIG2_FALLBACK from "pdfjs-dist/wasm/jbig2_nowasm_fallback.js" with {
|
||||
type: "text",
|
||||
};
|
||||
import JS_OPENJPEG_FALLBACK from "pdfjs-dist/wasm/openjpeg_nowasm_fallback.js" with {
|
||||
type: "text",
|
||||
};
|
||||
import ICC_CGATS from "pdfjs-dist/iccs/CGATS001Compat-v2-micro.icc" with {
|
||||
type: "bytes",
|
||||
};
|
||||
import FONT_DINGBATS from "pdfjs-dist/standard_fonts/FoxitDingbats.pfb" with {
|
||||
type: "bytes",
|
||||
};
|
||||
import FONT_FIXED from "pdfjs-dist/standard_fonts/FoxitFixed.pfb" with {
|
||||
type: "bytes",
|
||||
};
|
||||
import FONT_FIXED_B from "pdfjs-dist/standard_fonts/FoxitFixedBold.pfb" with {
|
||||
type: "bytes",
|
||||
};
|
||||
import FONT_FIXED_BI from "pdfjs-dist/standard_fonts/FoxitFixedBoldItalic.pfb" with {
|
||||
type: "bytes",
|
||||
};
|
||||
import FONT_FIXED_I from "pdfjs-dist/standard_fonts/FoxitFixedItalic.pfb" with {
|
||||
type: "bytes",
|
||||
};
|
||||
import FONT_SERIF from "pdfjs-dist/standard_fonts/FoxitSerif.pfb" with {
|
||||
type: "bytes",
|
||||
};
|
||||
import FONT_SERIF_B from "pdfjs-dist/standard_fonts/FoxitSerifBold.pfb" with {
|
||||
type: "bytes",
|
||||
};
|
||||
import FONT_SERIF_BI from "pdfjs-dist/standard_fonts/FoxitSerifBoldItalic.pfb" with {
|
||||
type: "bytes",
|
||||
};
|
||||
import FONT_SERIF_I from "pdfjs-dist/standard_fonts/FoxitSerifItalic.pfb" with {
|
||||
type: "bytes",
|
||||
};
|
||||
import FONT_SYMBOL from "pdfjs-dist/standard_fonts/FoxitSymbol.pfb" with {
|
||||
type: "bytes",
|
||||
};
|
||||
import FONT_LSANS from "pdfjs-dist/standard_fonts/LiberationSans-Regular.ttf" with {
|
||||
type: "bytes",
|
||||
};
|
||||
import FONT_LSANS_B from "pdfjs-dist/standard_fonts/LiberationSans-Bold.ttf" with {
|
||||
type: "bytes",
|
||||
};
|
||||
import FONT_LSANS_BI from "pdfjs-dist/standard_fonts/LiberationSans-BoldItalic.ttf" with {
|
||||
type: "bytes",
|
||||
};
|
||||
import FONT_LSANS_I from "pdfjs-dist/standard_fonts/LiberationSans-Italic.ttf" with {
|
||||
type: "bytes",
|
||||
};
|
||||
|
||||
const PDFJS_ASSETS: Record<
|
||||
string,
|
||||
{ body: Uint8Array | string; type: string }
|
||||
> = {
|
||||
"/pdfjs/wasm/jbig2.wasm": { body: WASM_JBIG2, type: "application/wasm" },
|
||||
"/pdfjs/wasm/openjpeg.wasm": {
|
||||
body: WASM_OPENJPEG,
|
||||
type: "application/wasm",
|
||||
},
|
||||
"/pdfjs/wasm/qcms_bg.wasm": { body: WASM_QCMS, type: "application/wasm" },
|
||||
"/pdfjs/wasm/jbig2_nowasm_fallback.js": {
|
||||
body: JS_JBIG2_FALLBACK,
|
||||
type: "text/javascript; charset=utf-8",
|
||||
},
|
||||
"/pdfjs/wasm/openjpeg_nowasm_fallback.js": {
|
||||
body: JS_OPENJPEG_FALLBACK,
|
||||
type: "text/javascript; charset=utf-8",
|
||||
},
|
||||
"/pdfjs/iccs/CGATS001Compat-v2-micro.icc": {
|
||||
body: ICC_CGATS,
|
||||
type: "application/vnd.iccprofile",
|
||||
},
|
||||
"/pdfjs/standard_fonts/FoxitDingbats.pfb": {
|
||||
body: FONT_DINGBATS,
|
||||
type: "application/octet-stream",
|
||||
},
|
||||
"/pdfjs/standard_fonts/FoxitFixed.pfb": {
|
||||
body: FONT_FIXED,
|
||||
type: "application/octet-stream",
|
||||
},
|
||||
"/pdfjs/standard_fonts/FoxitFixedBold.pfb": {
|
||||
body: FONT_FIXED_B,
|
||||
type: "application/octet-stream",
|
||||
},
|
||||
"/pdfjs/standard_fonts/FoxitFixedBoldItalic.pfb": {
|
||||
body: FONT_FIXED_BI,
|
||||
type: "application/octet-stream",
|
||||
},
|
||||
"/pdfjs/standard_fonts/FoxitFixedItalic.pfb": {
|
||||
body: FONT_FIXED_I,
|
||||
type: "application/octet-stream",
|
||||
},
|
||||
"/pdfjs/standard_fonts/FoxitSerif.pfb": {
|
||||
body: FONT_SERIF,
|
||||
type: "application/octet-stream",
|
||||
},
|
||||
"/pdfjs/standard_fonts/FoxitSerifBold.pfb": {
|
||||
body: FONT_SERIF_B,
|
||||
type: "application/octet-stream",
|
||||
},
|
||||
"/pdfjs/standard_fonts/FoxitSerifBoldItalic.pfb": {
|
||||
body: FONT_SERIF_BI,
|
||||
type: "application/octet-stream",
|
||||
},
|
||||
"/pdfjs/standard_fonts/FoxitSerifItalic.pfb": {
|
||||
body: FONT_SERIF_I,
|
||||
type: "application/octet-stream",
|
||||
},
|
||||
"/pdfjs/standard_fonts/FoxitSymbol.pfb": {
|
||||
body: FONT_SYMBOL,
|
||||
type: "application/octet-stream",
|
||||
},
|
||||
"/pdfjs/standard_fonts/LiberationSans-Regular.ttf": {
|
||||
body: FONT_LSANS,
|
||||
type: "font/ttf",
|
||||
},
|
||||
"/pdfjs/standard_fonts/LiberationSans-Bold.ttf": {
|
||||
body: FONT_LSANS_B,
|
||||
type: "font/ttf",
|
||||
},
|
||||
"/pdfjs/standard_fonts/LiberationSans-BoldItalic.ttf": {
|
||||
body: FONT_LSANS_BI,
|
||||
type: "font/ttf",
|
||||
},
|
||||
"/pdfjs/standard_fonts/LiberationSans-Italic.ttf": {
|
||||
body: FONT_LSANS_I,
|
||||
type: "font/ttf",
|
||||
},
|
||||
};
|
||||
|
||||
const PREFIX = "[BizMatch QC]";
|
||||
|
||||
@@ -320,9 +461,57 @@ async function servePdfBytes(
|
||||
|
||||
// ------- HTTP Server -------
|
||||
|
||||
// ---- Webview-reported window size (fallback tracking) ----
|
||||
// Both getSize() and (apparently) the native resize events are unreliable
|
||||
// in the experimental desktop backend, so the frontend reports its viewport
|
||||
// size via POST /api/window-metrics. The first report arrives ~800ms after
|
||||
// startup, i.e. after the enforced setSize, and is used to calibrate the
|
||||
// per-session offset between the outer window size and the webview viewport
|
||||
// (titlebar + borders). Later reports are translated back to outer-window
|
||||
// coordinates with that offset. Calibrating per session means any error
|
||||
// cancels out and the window cannot shrink a little on every restart.
|
||||
let webviewMetricsOffset: { dw: number; dh: number } | null = null;
|
||||
let sizeSeenFromWebview = false;
|
||||
|
||||
Deno.serve(async (request) => {
|
||||
const url = new URL(request.url);
|
||||
|
||||
if (url.pathname === "/api/window-metrics" && request.method === "POST") {
|
||||
try {
|
||||
const body = await request.json() as {
|
||||
innerWidth?: number;
|
||||
innerHeight?: number;
|
||||
};
|
||||
const iw = Math.round(Number(body.innerWidth) || 0);
|
||||
const ih = Math.round(Number(body.innerHeight) || 0);
|
||||
if (iw > 200 && ih > 200) {
|
||||
if (webviewMetricsOffset === null) {
|
||||
// First report: window is still at the enforced startup size,
|
||||
// so the difference to the viewport is the decoration size.
|
||||
webviewMetricsOffset = {
|
||||
dw: Math.min(Math.max(clamped.windowWidth - iw, 0), 200),
|
||||
dh: Math.min(Math.max(clamped.windowHeight - ih, 0), 200),
|
||||
};
|
||||
console.log(
|
||||
`${PREFIX} Window metrics calibrated: viewport ${iw}x${ih}, decoration offset ${webviewMetricsOffset.dw}x${webviewMetricsOffset.dh}`,
|
||||
);
|
||||
} else {
|
||||
const w = iw + webviewMetricsOffset.dw;
|
||||
const h = ih + webviewMetricsOffset.dh;
|
||||
if (w >= 1100 && h >= 700) {
|
||||
settings.windowWidth = w;
|
||||
settings.windowHeight = h;
|
||||
sizeSeenFromWebview = true;
|
||||
console.log(`${PREFIX} Window size (from webview): ${w}x${h}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
return json({ ok: true });
|
||||
} catch {
|
||||
return json({ ok: false }, 400);
|
||||
}
|
||||
}
|
||||
|
||||
if (url.pathname === "/api/state" && request.method === "GET") {
|
||||
const configForClient = {
|
||||
jsonPath: settings.jsonPath,
|
||||
@@ -452,6 +641,17 @@ Deno.serve(async (request) => {
|
||||
});
|
||||
}
|
||||
|
||||
// ---- PDF.js auxiliary assets (wasm decoders, standard fonts, ICC) ----
|
||||
const pdfjsAsset = PDFJS_ASSETS[url.pathname];
|
||||
if (pdfjsAsset) {
|
||||
return new Response(pdfjsAsset.body as BodyInit, {
|
||||
headers: {
|
||||
"content-type": pdfjsAsset.type,
|
||||
"cache-control": "public, max-age=86400",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// ---- PDF.js library assets ----
|
||||
if (url.pathname === "/pdfjs/legacy/pdf.min.mjs") {
|
||||
return new Response(PDFJS_LIB_TEXT, {
|
||||
@@ -557,17 +757,50 @@ if (
|
||||
|
||||
// Native resize tracking using Deno 2.9 BrowserWindow events
|
||||
let resizeTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
let sizeSeenFromEvent = false;
|
||||
let resizeEventLogsLeft = 3;
|
||||
try {
|
||||
win.addEventListener(
|
||||
"resize",
|
||||
((e: CustomEvent) => {
|
||||
if (resizeTimer !== undefined) clearTimeout(resizeTimer);
|
||||
// Store immediately but debounce writes
|
||||
const w = e.detail?.width ?? 0;
|
||||
const h = e.detail?.height ?? 0;
|
||||
// The payload shape of the experimental backend is not settled;
|
||||
// accept detail.{width,height}, detail.{w,h}, detail as [w, h],
|
||||
// and width/height directly on the event object.
|
||||
const anyEvent = e as unknown as Record<string, unknown>;
|
||||
const detail = anyEvent.detail as
|
||||
| Record<string, unknown>
|
||||
| number[]
|
||||
| undefined;
|
||||
let w = 0;
|
||||
let h = 0;
|
||||
if (Array.isArray(detail)) {
|
||||
w = Number(detail[0]) || 0;
|
||||
h = Number(detail[1]) || 0;
|
||||
} else if (detail && typeof detail === "object") {
|
||||
w = Number(detail.width ?? detail.w) || 0;
|
||||
h = Number(detail.height ?? detail.h) || 0;
|
||||
}
|
||||
if (!w) w = Number(anyEvent.width) || 0;
|
||||
if (!h) h = Number(anyEvent.height) || 0;
|
||||
|
||||
// Log the first few raw events so we can see what the backend
|
||||
// actually delivers (helps debug the unreliable size reporting).
|
||||
if (resizeEventLogsLeft > 0) {
|
||||
resizeEventLogsLeft--;
|
||||
try {
|
||||
console.log(
|
||||
`${PREFIX} Native resize event: parsed=${w}x${h}, detail=${
|
||||
JSON.stringify(detail)
|
||||
}, event.width/height=${anyEvent.width}/${anyEvent.height}`,
|
||||
);
|
||||
} catch { /* ok */ }
|
||||
}
|
||||
|
||||
if (w >= 1100 && h >= 700) {
|
||||
settings.windowWidth = w;
|
||||
settings.windowHeight = h;
|
||||
sizeSeenFromEvent = true;
|
||||
}
|
||||
resizeTimer = setTimeout(() => {
|
||||
if (settings.windowWidth >= 1100 && settings.windowHeight >= 700) {
|
||||
@@ -588,17 +821,28 @@ try {
|
||||
"close",
|
||||
(() => {
|
||||
if (resizeTimer !== undefined) clearTimeout(resizeTimer);
|
||||
const [fw, fh] = win.getSize();
|
||||
if (fw >= 1100 && fh >= 700) {
|
||||
settings.windowWidth = fw;
|
||||
settings.windowHeight = fh;
|
||||
// Prefer sizes reported by native resize events or by the webview.
|
||||
// getSize() has been observed to return a stale value (the last
|
||||
// programmatically requested size) instead of the actual window
|
||||
// size, which caused the same size to be saved on every close.
|
||||
if (!sizeSeenFromEvent && !sizeSeenFromWebview) {
|
||||
try {
|
||||
const [fw, fh] = win.getSize();
|
||||
if (fw >= 1100 && fh >= 700) {
|
||||
settings.windowWidth = fw;
|
||||
settings.windowHeight = fh;
|
||||
}
|
||||
} catch { /* ok */ }
|
||||
}
|
||||
try {
|
||||
const path = resolveSettingsPath();
|
||||
Deno.mkdirSync(dirname(path), { recursive: true });
|
||||
Deno.writeTextFileSync(path, JSON.stringify(settings, null, 2));
|
||||
const source = sizeSeenFromEvent
|
||||
? "resize events"
|
||||
: (sizeSeenFromWebview ? "webview" : "getSize()");
|
||||
console.log(
|
||||
`${PREFIX} Window size saved on close: ${settings.windowWidth}x${settings.windowHeight}`,
|
||||
`${PREFIX} Window size saved on close: ${settings.windowWidth}x${settings.windowHeight} (source: ${source})`,
|
||||
);
|
||||
} catch (err) {
|
||||
console.error(
|
||||
@@ -614,3 +858,28 @@ try {
|
||||
}
|
||||
|
||||
win.show();
|
||||
|
||||
// Workaround: with the experimental desktop backend the first BrowserWindow
|
||||
// "adopts" the implicit startup window, which is created before user code
|
||||
// runs. Sometimes the native window keeps its built-in default size even
|
||||
// though getSize() already reports the requested values, so the early
|
||||
// setSize-on-mismatch above is skipped. Enforce the persisted size
|
||||
// unconditionally after show(), and verify once more shortly after.
|
||||
try {
|
||||
win.setSize(clamped.windowWidth, clamped.windowHeight);
|
||||
setTimeout(() => {
|
||||
try {
|
||||
const [w, h] = win.getSize();
|
||||
if (w !== clamped.windowWidth || h !== clamped.windowHeight) {
|
||||
console.log(
|
||||
`${PREFIX} Window size drifted to ${w}x${h}, enforcing ${clamped.windowWidth}x${clamped.windowHeight}`,
|
||||
);
|
||||
win.setSize(clamped.windowWidth, clamped.windowHeight);
|
||||
}
|
||||
} catch { /* ok */ }
|
||||
}, 250);
|
||||
} catch (err) {
|
||||
console.warn(
|
||||
`${PREFIX} Post-show size enforcement failed: ${errorMessage(err)}`,
|
||||
);
|
||||
}
|
||||
31
src/data.ts
31
src/data.ts
@@ -24,6 +24,17 @@ export function validateDocuments(value: unknown): BuyerDocument[] {
|
||||
});
|
||||
}
|
||||
|
||||
// Normalized person key from the extracted buyer name: lowercase,
|
||||
// punctuation stripped, tokens sorted for order-insensitive comparison.
|
||||
function personKey(docs: BuyerDocument[]): string | null {
|
||||
const name = docs.map((d) => d.prospective_buyer).find((v) => text(v));
|
||||
if (!name) return null;
|
||||
const tokens = String(name).toLocaleLowerCase()
|
||||
.replace(/[^\p{L}\p{N}]+/gu, " ").trim().split(/\s+/).filter(Boolean)
|
||||
.sort();
|
||||
return tokens.length ? tokens.join(" ") : null;
|
||||
}
|
||||
|
||||
export function groupDocuments(documents: BuyerDocument[]): PersonGroup[] {
|
||||
const groups = new Map<string, BuyerDocument[]>();
|
||||
for (const doc of documents) {
|
||||
@@ -33,6 +44,24 @@ export function groupDocuments(documents: BuyerDocument[]): PersonGroup[] {
|
||||
groups.set(key, bucket);
|
||||
}
|
||||
|
||||
// Merge filename-based buckets that share the same prospective_buyer
|
||||
// (catches typos in scan filenames, e.g. "Zaboor" vs "Zahoor").
|
||||
const byPerson = new Map<string, string>(); // personKey -> bucket key
|
||||
for (const [key, docs] of [...groups.entries()]) {
|
||||
const pKey = personKey(docs);
|
||||
if (!pKey) continue;
|
||||
const existingKey = byPerson.get(pKey);
|
||||
if (existingKey === undefined) {
|
||||
byPerson.set(pKey, key);
|
||||
continue;
|
||||
}
|
||||
const target = groups.get(existingKey);
|
||||
if (target) {
|
||||
target.push(...docs);
|
||||
groups.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
return [...groups.entries()]
|
||||
.map(([key, docs]) => {
|
||||
docs.sort((a, b) => a.file_name.localeCompare(b.file_name));
|
||||
@@ -66,4 +95,4 @@ export function filterGroups(
|
||||
return groups.filter((group) =>
|
||||
terms.every((term) => group.searchText.includes(term))
|
||||
);
|
||||
}
|
||||
}
|
||||
77
web/app.js
77
web/app.js
@@ -1,6 +1,7 @@
|
||||
let state;
|
||||
let groups = [];
|
||||
let selectedIndex = -1;
|
||||
let loadedIndex = -1; // which document the PDF viewer currently shows/loads
|
||||
let pdfViewer = null;
|
||||
let loadRequestId = 0;
|
||||
|
||||
@@ -50,6 +51,19 @@ const esc = (value) =>
|
||||
"'": "'",
|
||||
})[char]);
|
||||
|
||||
// Normalized person key from the vision-extracted buyer name: lowercase,
|
||||
// punctuation stripped, name tokens sorted so "Zahoor Bilal" and
|
||||
// "Bilal Zahoor" compare equal.
|
||||
function personKey(group) {
|
||||
const name = group.docs.map((d) => d.prospective_buyer).find((v) =>
|
||||
typeof v === "string" && v.trim()
|
||||
);
|
||||
if (!name) return null;
|
||||
const tokens = name.toLocaleLowerCase().replace(/[^\p{L}\p{N}]+/gu, " ")
|
||||
.trim().split(/\s+/).filter(Boolean).sort();
|
||||
return tokens.length ? tokens.join(" ") : null;
|
||||
}
|
||||
|
||||
function buildGroups(docs) {
|
||||
const map = new Map();
|
||||
docs.forEach((doc, index) => {
|
||||
@@ -70,7 +84,33 @@ function buildGroups(docs) {
|
||||
].filter(Boolean).join(" ");
|
||||
map.set(key, group);
|
||||
});
|
||||
return [...map.values()].sort((a, b) => a.key.localeCompare(b.key));
|
||||
|
||||
// Second pass: merge filename-based groups that refer to the same person
|
||||
// according to the extracted prospective_buyer. This catches typos in the
|
||||
// scan filenames (e.g. "Zaboor, Bilal" vs "Zahoor, Bilal") which would
|
||||
// otherwise show the same buyer twice. Groups without a prospective_buyer
|
||||
// are never merged.
|
||||
const byPerson = new Map();
|
||||
const merged = [];
|
||||
for (const group of map.values()) {
|
||||
const pKey = personKey(group);
|
||||
const target = pKey ? byPerson.get(pKey) : undefined;
|
||||
if (target) {
|
||||
target.docs.push(...group.docs);
|
||||
target.text += " " + group.text;
|
||||
continue;
|
||||
}
|
||||
if (pKey) byPerson.set(pKey, group);
|
||||
merged.push(group);
|
||||
}
|
||||
for (const group of merged) {
|
||||
group.docs.sort((a, b) => a.file_name.localeCompare(b.file_name));
|
||||
const preferred = group.docs.find((d) =>
|
||||
typeof d.prospective_buyer === "string" && d.prospective_buyer.trim()
|
||||
);
|
||||
if (preferred) group.displayName = preferred.prospective_buyer;
|
||||
}
|
||||
return merged.sort((a, b) => a.key.localeCompare(b.key));
|
||||
}
|
||||
|
||||
function visibleGroups() {
|
||||
@@ -116,15 +156,20 @@ async function loadPdf(index) {
|
||||
const doc = state.documents[index];
|
||||
if (!doc) return;
|
||||
|
||||
// Deduplicate: don't reload the same document
|
||||
if (index === selectedIndex && pdfViewer) {
|
||||
// Deduplicate: don't reload the document that is already shown.
|
||||
// NOTE: must compare against loadedIndex, NOT selectedIndex --
|
||||
// select() updates selectedIndex before calling loadPdf(), so a
|
||||
// selectedIndex comparison is always true and blocks every reload.
|
||||
if (index === loadedIndex && pdfViewer) {
|
||||
return;
|
||||
}
|
||||
loadedIndex = index;
|
||||
|
||||
const previousZoom = pdfViewer ? pdfViewer.zoom : 1;
|
||||
if (pdfViewer) {
|
||||
pdfViewer.destroy();
|
||||
}
|
||||
pdfViewer = new PdfViewer(pdfContainer);
|
||||
pdfViewer = new PdfViewer(pdfContainer, { initialZoom: previousZoom });
|
||||
viewer.classList.remove("loaded");
|
||||
pdfMessage.hidden = false;
|
||||
pdfMessage.textContent = "Loading PDF\u2026";
|
||||
@@ -164,6 +209,7 @@ async function loadPdf(index) {
|
||||
console.log(`[BizMatch QC] PDF ${reqId} rendering complete`);
|
||||
} catch (error) {
|
||||
if (index !== selectedIndex) return;
|
||||
loadedIndex = -1; // allow retry: clicking the same document again reloads it
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
pdfMessage.textContent = `Cannot open PDF: ${message}`;
|
||||
pdfMessage.hidden = false;
|
||||
@@ -281,6 +327,7 @@ async function load() {
|
||||
throw new Error(`State request failed with HTTP ${response.status}.`);
|
||||
}
|
||||
state = await response.json();
|
||||
loadedIndex = -1; // document set changed; index-based dedup is invalid now
|
||||
groups = buildGroups(state.documents);
|
||||
showError(state.loadError || "");
|
||||
renderList();
|
||||
@@ -291,3 +338,25 @@ async function load() {
|
||||
}
|
||||
|
||||
void load();
|
||||
|
||||
// ---- Window size reporting ----
|
||||
// The backend's native size APIs are unreliable (see main.ts), so the
|
||||
// webview reports its own viewport size. The first report, sent shortly
|
||||
// after startup, calibrates the decoration offset on the backend; later
|
||||
// reports track user resizes.
|
||||
let metricsTimer = null;
|
||||
function reportWindowMetrics() {
|
||||
fetch("/api/window-metrics", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
innerWidth: globalThis.innerWidth,
|
||||
innerHeight: globalThis.innerHeight,
|
||||
}),
|
||||
}).catch(() => {});
|
||||
}
|
||||
globalThis.addEventListener("resize", () => {
|
||||
clearTimeout(metricsTimer);
|
||||
metricsTimer = setTimeout(reportWindowMetrics, 250);
|
||||
});
|
||||
setTimeout(reportWindowMetrics, 800); // calibration report
|
||||
@@ -1,22 +1,44 @@
|
||||
// PDF.js viewer using pdfjs-dist 6.1.200 legacy build.
|
||||
// Depends on global pdfjsLib (loaded in index.html).
|
||||
|
||||
const ZOOM_MIN = 0.25;
|
||||
const ZOOM_MAX = 5;
|
||||
const ZOOM_STEP = 1.2; // multiplicative
|
||||
|
||||
class PdfViewer {
|
||||
constructor(container) {
|
||||
constructor(container, options = {}) {
|
||||
this.container = container;
|
||||
this.generation = 0;
|
||||
this.loadingTask = null;
|
||||
this.doc = null;
|
||||
this.numPages = 0;
|
||||
this.renderTasks = new Set();
|
||||
this.lastUrl = null;
|
||||
this.lastSize = null;
|
||||
// multiplier on fit-to-width (1 = fit width); can be seeded from the
|
||||
// previous viewer instance so zoom survives switching documents
|
||||
this.zoom = Math.min(
|
||||
ZOOM_MAX,
|
||||
Math.max(ZOOM_MIN, options.initialZoom ?? 1),
|
||||
);
|
||||
this._lastRenderWidth = 0;
|
||||
this._resizeTimer = null;
|
||||
this._zoomTimer = null;
|
||||
this.resizeObserver = null;
|
||||
this._createDOM();
|
||||
this._updateZoomLabel();
|
||||
this._observeResize();
|
||||
}
|
||||
|
||||
_createDOM() {
|
||||
// The pages container is always visible (never hidden).
|
||||
// Loading and error states are overlays on top.
|
||||
this.container.innerHTML = `
|
||||
<div class="pdf-v-toolbar" hidden>
|
||||
<button class="pdf-v-zoom-out" title="Verkleinern (Strg+Mausrad)">\u2212</button>
|
||||
<button class="pdf-v-zoom-label" title="Auf Seitenbreite einpassen">100%</button>
|
||||
<button class="pdf-v-zoom-in" title="Vergr\u00f6\u00dfern (Strg+Mausrad)">+</button>
|
||||
</div>
|
||||
<div class="pdf-v-pages"></div>
|
||||
<div class="pdf-v-overlay pdf-v-loading" hidden>Loading PDF\u2026</div>
|
||||
<div class="pdf-v-overlay pdf-v-error" hidden>
|
||||
@@ -24,6 +46,8 @@ class PdfViewer {
|
||||
<button class="pdf-v-retry">Retry</button>
|
||||
</div>
|
||||
`;
|
||||
this.toolbar = this.container.querySelector(".pdf-v-toolbar");
|
||||
this.zoomLabel = this.container.querySelector(".pdf-v-zoom-label");
|
||||
this.pagesDiv = this.container.querySelector(".pdf-v-pages");
|
||||
this.loadingDiv = this.container.querySelector(".pdf-v-loading");
|
||||
this.errorDiv = this.container.querySelector(".pdf-v-error");
|
||||
@@ -36,16 +60,90 @@ class PdfViewer {
|
||||
this._loadInternal(this.lastUrl, this.lastSize);
|
||||
}
|
||||
});
|
||||
|
||||
this.container.querySelector(".pdf-v-zoom-in").addEventListener(
|
||||
"click",
|
||||
() => this.setZoom(this.zoom * ZOOM_STEP),
|
||||
);
|
||||
this.container.querySelector(".pdf-v-zoom-out").addEventListener(
|
||||
"click",
|
||||
() => this.setZoom(this.zoom / ZOOM_STEP),
|
||||
);
|
||||
// Clicking the percentage resets to fit-width.
|
||||
this.zoomLabel.addEventListener("click", () => this.setZoom(1));
|
||||
|
||||
// Ctrl + mouse wheel zoom, like in browsers / PDF readers.
|
||||
this.pagesDiv.addEventListener("wheel", (e) => {
|
||||
if (!e.ctrlKey) return;
|
||||
e.preventDefault();
|
||||
this.setZoom(this.zoom * (e.deltaY < 0 ? 1.1 : 1 / 1.1));
|
||||
}, { passive: false });
|
||||
}
|
||||
|
||||
_setState(state) {
|
||||
this.loadingDiv.hidden = true;
|
||||
this.errorDiv.hidden = true;
|
||||
if (state === "loading") this.loadingDiv.hidden = false;
|
||||
if (state === "error") this.errorDiv.hidden = false;
|
||||
this._viewerState = state;
|
||||
// ---- Zoom ----
|
||||
|
||||
setZoom(zoom) {
|
||||
const clamped = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, zoom));
|
||||
if (Math.abs(clamped - this.zoom) < 0.001) return;
|
||||
this.zoom = clamped;
|
||||
this._updateZoomLabel();
|
||||
if (!this.doc) return;
|
||||
// Debounce so repeated +/+/+ or wheel ticks trigger one re-render.
|
||||
clearTimeout(this._zoomTimer);
|
||||
this._zoomTimer = setTimeout(() => this._rerender(), 120);
|
||||
}
|
||||
|
||||
_updateZoomLabel() {
|
||||
this.zoomLabel.textContent = `${Math.round(this.zoom * 100)}%`;
|
||||
}
|
||||
|
||||
// ---- Resize ----
|
||||
|
||||
_observeResize() {
|
||||
if (typeof ResizeObserver === "undefined") return;
|
||||
this.resizeObserver = new ResizeObserver(() => {
|
||||
if (!this.doc) return;
|
||||
const width = this._renderWidth();
|
||||
if (Math.abs(width - this._lastRenderWidth) < 2) return;
|
||||
clearTimeout(this._resizeTimer);
|
||||
this._resizeTimer = setTimeout(() => {
|
||||
console.log(
|
||||
`[BizMatch QC] PDF viewer resized, re-rendering at ${this._renderWidth()}px`,
|
||||
);
|
||||
this._rerender();
|
||||
}, 150);
|
||||
});
|
||||
this.resizeObserver.observe(this.container);
|
||||
}
|
||||
|
||||
_renderWidth() {
|
||||
return Math.max(Math.round(this._getViewportWidth() * this.zoom), 100);
|
||||
}
|
||||
|
||||
// Re-render all pages of the already-loaded document (zoom / resize),
|
||||
// preserving the relative scroll position.
|
||||
async _rerender() {
|
||||
if (!this.doc) return;
|
||||
const generation = ++this.generation;
|
||||
|
||||
for (const rt of this.renderTasks) {
|
||||
try {
|
||||
rt.cancel();
|
||||
} catch { /* ok */ }
|
||||
}
|
||||
this.renderTasks.clear();
|
||||
|
||||
const scrollRatio = this.pagesDiv.scrollHeight > 0
|
||||
? this.pagesDiv.scrollTop / this.pagesDiv.scrollHeight
|
||||
: 0;
|
||||
|
||||
await this._renderAllPages(this.doc, generation, false);
|
||||
if (generation !== this.generation) return;
|
||||
this.pagesDiv.scrollTop = scrollRatio * this.pagesDiv.scrollHeight;
|
||||
}
|
||||
|
||||
// ---- Loading ----
|
||||
|
||||
async load(url, byteSize) {
|
||||
this.lastUrl = url;
|
||||
this.lastSize = byteSize;
|
||||
@@ -71,6 +169,13 @@ class PdfViewer {
|
||||
url,
|
||||
rangeChunkSize: 65536,
|
||||
disableAutoFetch: false,
|
||||
// PDF.js >= 5 decodes CCITT-G4/JBIG2 (B/W scans), JPEG2000 and ICC
|
||||
// color via WASM modules fetched from wasmUrl. Without these URLs
|
||||
// the decoders fail silently (ignoreErrors default) and scanned
|
||||
// pages render as blank white canvases of the correct size.
|
||||
wasmUrl: "/pdfjs/wasm/",
|
||||
standardFontDataUrl: "/pdfjs/standard_fonts/",
|
||||
iccUrl: "/pdfjs/iccs/",
|
||||
});
|
||||
this.loadingTask = task;
|
||||
|
||||
@@ -80,50 +185,25 @@ class PdfViewer {
|
||||
return;
|
||||
}
|
||||
this.doc = doc;
|
||||
this.numPages = doc.numPages;
|
||||
|
||||
const numPages = doc.numPages;
|
||||
const loadMs = Math.round(performance.now() - loadStart);
|
||||
console.log(
|
||||
`[BizMatch QC] PDF document loaded: ${numPages} pages in ${loadMs}ms`,
|
||||
`[BizMatch QC] PDF document loaded: ${this.numPages} pages in ${loadMs}ms`,
|
||||
);
|
||||
|
||||
const viewerWidth = this._getViewportWidth();
|
||||
console.log(`[BizMatch QC] PDF usable render width: ${viewerWidth}px`);
|
||||
this.toolbar.hidden = false;
|
||||
this._updateZoomLabel();
|
||||
|
||||
const pageStart = performance.now();
|
||||
await this._renderPage(doc, 1, viewerWidth, generation);
|
||||
await this._renderAllPages(doc, generation, true);
|
||||
if (generation !== this.generation) return;
|
||||
|
||||
this._setState(null); // Remove loading overlay
|
||||
const firstPageMs = Math.round(performance.now() - pageStart);
|
||||
console.log(
|
||||
`[BizMatch QC] PDF page 1 rendered in ${firstPageMs}ms`,
|
||||
);
|
||||
console.log(
|
||||
`[BizMatch QC] First page visible after ${
|
||||
Math.round(performance.now() - loadStart)
|
||||
}ms`,
|
||||
);
|
||||
|
||||
for (let p = 2; p <= numPages; p++) {
|
||||
if (generation !== this.generation) return;
|
||||
const pStart = performance.now();
|
||||
await this._renderPage(doc, p, viewerWidth, generation);
|
||||
if (generation !== this.generation) return;
|
||||
console.log(
|
||||
`[BizMatch QC] PDF page ${p} rendered in ${
|
||||
Math.round(performance.now() - pStart)
|
||||
}ms`,
|
||||
);
|
||||
await new Promise((r) => requestAnimationFrame(r));
|
||||
}
|
||||
|
||||
const totalMs = Math.round(performance.now() - loadStart);
|
||||
console.log(
|
||||
`[BizMatch QC] PDF viewer load completed: generation ${generation}`,
|
||||
);
|
||||
console.log(
|
||||
`[BizMatch QC] PDF fully rendered: ${numPages} pages in ${totalMs}ms`,
|
||||
`[BizMatch QC] PDF fully rendered: ${this.numPages} pages in ${totalMs}ms`,
|
||||
);
|
||||
} catch (err) {
|
||||
if (generation !== this.generation) return;
|
||||
@@ -141,6 +221,41 @@ class PdfViewer {
|
||||
}
|
||||
}
|
||||
|
||||
// Shared render loop for initial load, zoom and resize.
|
||||
// hideLoadingAfterFirstPage: true on initial load (removes the overlay
|
||||
// as soon as page 1 is visible).
|
||||
async _renderAllPages(doc, generation, hideLoadingAfterFirstPage) {
|
||||
this.pagesDiv.innerHTML = "";
|
||||
|
||||
const viewerWidth = this._renderWidth();
|
||||
this._lastRenderWidth = viewerWidth;
|
||||
console.log(`[BizMatch QC] PDF render width: ${viewerWidth}px`);
|
||||
|
||||
for (let p = 1; p <= this.numPages; p++) {
|
||||
if (generation !== this.generation) return;
|
||||
const pStart = performance.now();
|
||||
await this._renderPage(doc, p, viewerWidth, generation);
|
||||
if (generation !== this.generation) return;
|
||||
if (p === 1 && hideLoadingAfterFirstPage) {
|
||||
this._setState(null); // Remove loading overlay
|
||||
}
|
||||
console.log(
|
||||
`[BizMatch QC] PDF page ${p} rendered in ${
|
||||
Math.round(performance.now() - pStart)
|
||||
}ms`,
|
||||
);
|
||||
await new Promise((r) => requestAnimationFrame(r));
|
||||
}
|
||||
}
|
||||
|
||||
_setState(state) {
|
||||
this.loadingDiv.hidden = true;
|
||||
this.errorDiv.hidden = true;
|
||||
if (state === "loading") this.loadingDiv.hidden = false;
|
||||
if (state === "error") this.errorDiv.hidden = false;
|
||||
this._viewerState = state;
|
||||
}
|
||||
|
||||
_getViewportWidth() {
|
||||
const style = globalThis.getComputedStyle
|
||||
? getComputedStyle(this.pagesDiv)
|
||||
@@ -174,6 +289,7 @@ class PdfViewer {
|
||||
await this.doc.destroy();
|
||||
} catch { /* ok */ }
|
||||
this.doc = null;
|
||||
this.numPages = 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -240,8 +356,15 @@ class PdfViewer {
|
||||
|
||||
destroy() {
|
||||
this.generation = 0;
|
||||
clearTimeout(this._resizeTimer);
|
||||
clearTimeout(this._zoomTimer);
|
||||
if (this.resizeObserver) {
|
||||
this.resizeObserver.disconnect();
|
||||
this.resizeObserver = null;
|
||||
}
|
||||
this._disposeCurrentDocument().catch(() => {});
|
||||
this.pagesDiv.innerHTML = "";
|
||||
this.toolbar.hidden = true;
|
||||
this._setState("loading");
|
||||
}
|
||||
}
|
||||
@@ -250,7 +373,7 @@ function isCancellationError(err) {
|
||||
if (!(err instanceof Error)) return false;
|
||||
const msg = err.message || "";
|
||||
return msg.includes("cancelled") ||
|
||||
msg.includes("cancelled") ||
|
||||
msg.includes("canceled") ||
|
||||
msg.includes("destroyed") ||
|
||||
msg.includes("Worker was destroyed");
|
||||
}
|
||||
@@ -259,4 +382,4 @@ function errorMsg(err) {
|
||||
return err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
|
||||
globalThis.PdfViewer = PdfViewer;
|
||||
globalThis.PdfViewer = PdfViewer;
|
||||
@@ -229,11 +229,12 @@ hr.field-sep {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
overflow-y: scroll;
|
||||
overflow-x: hidden;
|
||||
overflow-x: auto;
|
||||
scrollbar-gutter: stable;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
align-items: safe center; /* keeps left edge reachable when zoomed wider than the pane */
|
||||
gap: 16px;
|
||||
padding: 12px;
|
||||
}
|
||||
@@ -245,3 +246,38 @@ hr.field-sep {
|
||||
.pdf-v-page canvas {
|
||||
display: block;
|
||||
}
|
||||
|
||||
/* Zoom toolbar */
|
||||
.pdf-v-toolbar {
|
||||
position: absolute;
|
||||
top: 10px;
|
||||
right: 24px;
|
||||
z-index: 3;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
background: rgba(35, 35, 38, 0.88);
|
||||
border: 1px solid #666;
|
||||
border-radius: 6px;
|
||||
padding: 3px 4px;
|
||||
box-shadow: 0 1px 5px rgba(0, 0, 0, 0.4);
|
||||
}
|
||||
.pdf-v-toolbar button {
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: #e5e5e5;
|
||||
font-size: 15px;
|
||||
line-height: 1;
|
||||
padding: 5px 9px;
|
||||
cursor: pointer;
|
||||
border-radius: 4px;
|
||||
}
|
||||
.pdf-v-toolbar button:hover {
|
||||
background: #555;
|
||||
}
|
||||
.pdf-v-zoom-label {
|
||||
min-width: 52px;
|
||||
text-align: center;
|
||||
font-size: 12px !important;
|
||||
color: #ccc !important;
|
||||
}
|
||||
Reference in New Issue
Block a user