From 6e0d33510da924b1a016b47ec08f576616d225a0 Mon Sep 17 00:00:00 2001 From: JasonFraser Date: Wed, 14 Oct 2026 20:34:17 -0400 Subject: [PATCH] Add multi-highlight source panel + click-and-drag region tool (L.5) usePdfViewer.js/useImageZoom.js gain a parallel highlights/showHighlights/ clearHighlights (several labeled boxes at once) alongside the existing single highlight/showHighlight/clearHighlight the review screen already depends on - that call site needed zero changes. SourceDocumentPanel.vue exposes both and renders the plural boxes via a new v-for. New useRegionDraw.js composable adds the click-and-drag-to-define-a-region interaction the manual mapping screen (L.6) will use, wired in via a new regionDrawMode prop + region-drawn emit, a no-op everywhere today. Both viewers now also expose their own raw zoom ref (previously only a formatted display string was public) so the region tool can convert a drawn pixel rectangle back into PDF-point/image-pixel space. Verified: 21 assertions against the real composables (a fake window.addEventListener is the only browser API useRegionDraw touches, so no real DOM was needed) - drag math divides correctly by zoom, an up-left drag still normalizes to a positive box, a sub-threshold drag never fires, and the new multi-highlight state never disturbs the existing single-highlight state. npm run build passes; the app container rebuilt and confirmed serving the new bundle. measure.py unaffected (no backend touched). Not machine-verified: actual on-screen rendering and a real mouse drag, same standing limitation as every other frontend-only change this session. Co-Authored-By: Claude Sonnet 5 --- CLAUDE.md | 53 ++++++++++++- frontend/src/assets/main.css | 30 ++++++- .../src/components/SourceDocumentPanel.vue | 79 +++++++++++++++++-- frontend/src/composables/useImageZoom.js | 28 +++++-- frontend/src/composables/usePdfViewer.js | 41 ++++++++-- frontend/src/composables/useRegionDraw.js | 79 +++++++++++++++++++ 6 files changed, 282 insertions(+), 28 deletions(-) create mode 100644 frontend/src/composables/useRegionDraw.js diff --git a/CLAUDE.md b/CLAUDE.md index a1fefd2..314d653 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -31,7 +31,7 @@ to rough effort: |---|---|---| | **1** | Extraction + 6 checks + Excel export, dual-engine, measurement harness | **In progress — see gaps below** | | 2 | Review screen, suggested-fix patterns, OCR, 2nd+ bank support | OCR routing + working Docling-fallback (`raw_ocr_extract.py`) built and verified against a real multi-page scan 2026-10-11 — one known single-page edge case remains unreliable, see "OCR / scanned statements" below — **review screen (R.1-R.5) complete as of 2026-10-13** (see "Review screen"/"R.2"/"R.3"/"R.4"/"R.5" under Key decisions & lessons) — R.1 (source-position capture + the pdf.js highlighting viewer), R.2 (plain-language flags + jump-to-flagged navigation), R.3 (the suggested-fix engine - debit/credit swap, transposed digits, OCR digit misread), R.4 (structural row edits - flip sign, insert, split, merge, delete, behind a "more actions" menu), and R.5 (edit log + acknowledge/accept workflow + an optional Excel "Edits" sheet) all shipped; "date format swapped" and a separate "bulk column fix" both investigated and found not to apply to this pipeline's own data shape (see R.3/R.4's own entries) | -| 3 | Layout mapper (fingerprinting, versioning, drift detection) | **Pulled forward and in progress as of 2026-10-14** (see "Layout mapper" under Key decisions & lessons) - staged L.1-L.8, full spec scope (§6/§6.1/§9) plus a superuser-review promotion path beyond what's written. L.1 (a modular "layout quirks" tier for mechanical geometric oddities, ahead of the mapper itself) shipped - fixed a real new statement (an Equals Money account) whose header label wrapped across physical lines, plus two more real differences the same statement surfaced (a "$"-prefixed money format, an ISO-shaped date format). L.2 (fingerprinting + the forced-mapping backend contract, no UI/PocketBase yet) shipped - also surfaced and fixed a real gap (a forced mapping had no page-boundary concept, swallowing a cover page's own letterhead into the first transaction; fixed with a new `start_page` field). L.3 (the `layoutMappings`/`layoutMappingVersions` PocketBase schema + the auto-promotion hook) shipped - found and fixed a real rule gap during testing (an owner could self-promote their own mapping to "shared" via a plain update; PocketBase rules gate who can update, not which fields). L.4 (the frontend fingerprint-lookup orchestration, including a real, clickable confirm dialog in `ExtractorView.vue` - not deferred to L.6) shipped - found and fixed two real bugs in the near-match comparator while testing it against the spec's own documented example (per-line vs per-field label text; a 70% overlap threshold that was too strict for that very example, corrected to 50%). L.5-L.8 (the multi-highlight source panel, the manual mapping screen, the Layouts page, the superuser review screen) not started yet | +| 3 | Layout mapper (fingerprinting, versioning, drift detection) | **Pulled forward and in progress as of 2026-10-14** (see "Layout mapper" under Key decisions & lessons) - staged L.1-L.8, full spec scope (§6/§6.1/§9) plus a superuser-review promotion path beyond what's written. L.1 (a modular "layout quirks" tier for mechanical geometric oddities, ahead of the mapper itself) shipped - fixed a real new statement (an Equals Money account) whose header label wrapped across physical lines, plus two more real differences the same statement surfaced (a "$"-prefixed money format, an ISO-shaped date format). L.2 (fingerprinting + the forced-mapping backend contract, no UI/PocketBase yet) shipped - also surfaced and fixed a real gap (a forced mapping had no page-boundary concept, swallowing a cover page's own letterhead into the first transaction; fixed with a new `start_page` field). L.3 (the `layoutMappings`/`layoutMappingVersions` PocketBase schema + the auto-promotion hook) shipped - found and fixed a real rule gap during testing (an owner could self-promote their own mapping to "shared" via a plain update; PocketBase rules gate who can update, not which fields). L.4 (the frontend fingerprint-lookup orchestration, including a real, clickable confirm dialog in `ExtractorView.vue` - not deferred to L.6) shipped - found and fixed two real bugs in the near-match comparator while testing it against the spec's own documented example (per-line vs per-field label text; a 70% overlap threshold that was too strict for that very example, corrected to 50%). L.5 (multi-highlight `SourceDocumentPanel` + a new click-and-drag region tool, `useRegionDraw.js`) shipped - the groundwork L.6's manual mapping screen will build on. L.6-L.8 (the manual mapping screen, the Layouts page, the superuser review screen) not started yet | | 4 | Multi-tenant practice/client accounts, Frappe data model | Not started | | 5 | Free front door, public accuracy page | Not started | | 6 | Append mode, credit cards, multi-account statements | Not started | @@ -535,14 +535,25 @@ security only, not the full SaaS-shaped doc — and the judgment call on what co (gained `highlight`/`highlightStyle`/`showHighlight`/ `clearHighlight` 2026-10-13, for the review screen's row-highlighting on an image upload — reuses its own - existing zoom math), + existing zoom math; as of layout-mapper L.5 (2026-10-14) + also exposes a public `zoom` ref and a parallel + `highlights`/`showHighlights`/`clearHighlights` for + several labeled boxes at once, independent of the single + highlight above), useAutoGrow, useModalFocus (shared by every modal component below: focuses the overlay the instant it becomes visible, so Esc closes it immediately), usePdfViewer (NEW 2026-10-13 — pdf.js document loading, per-page canvas rendering, zoom, "scroll to page N and highlight bbox"; parallels useImageZoom's own shape — see "Review screen" - under Key decisions & lessons for the full record) + under Key decisions & lessons for the full record; gained + the same public `zoom`/`highlights`/`showHighlights`/ + `clearHighlights` as useImageZoom above, L.5), + useRegionDraw (NEW 2026-10-14, layout mapper L.5 — the + click-and-drag-to-define-a-region interaction the manual + mapping screen, L.6, will use; owned by + SourceDocumentPanel.vue via a new `regionDrawMode` prop, + a no-op everywhere today) /components — AppHeader (sticky top bar — brand mark, active-project breadcrumb, account menu with email + sign out; added 2026-10-13, see "Enterprise app-shell redesign" under Key @@ -2234,6 +2245,42 @@ the Python function in isolation. `backend/measure.py` byte-identical throughout (fingerprinting only ever runs on the already-isolated failure path). `npm run build` passes. +**L.5 shipped same day: multi-highlight `SourceDocumentPanel` + a new click-and- +drag region tool - the groundwork the manual mapping screen (L.6, not built yet) +needs.** `usePdfViewer.js`/`useImageZoom.js` each gained a parallel `highlights` +ref (`[{page?, bbox, label?, color?}]`) and `showHighlights(boxes)`/ +`clearHighlights()`, entirely independent of the existing single `highlight`/ +`showHighlight`/`clearHighlight` the review screen's own "Show on source" (R.2) +already depends on - that call site needed zero changes. `SourceDocumentPanel.vue` +exposes the plural versions the same way, and its template now renders a `v-for` +of labeled boxes (blue by default, overridable per box) alongside the existing +single amber highlight. New `frontend/src/composables/useRegionDraw.js` - the +click-and-drag-to-define-a-region interaction that didn't exist anywhere in this +app before - owned by `SourceDocumentPanel.vue` via a new `regionDrawMode` prop +(default `false`, a no-op everywhere today) and a `region-drawn` emit carrying +`{page, bbox}` in the same PDF-point/image-pixel space `source_bbox` already uses +everywhere else. Both viewer composables also had to start exposing their own raw +numeric `zoom` ref (previously only a formatted `zoomLevelText` string was public) +so the region tool can convert a drawn pixel rectangle back into that coordinate +space, the inverse of how a highlight box's own position is already computed. + +**Verified, all real:** a hand-written Node script executed the REAL +`useRegionDraw.js`/`usePdfViewer.js`/`useImageZoom.js` (not reimplementations) via +a minimal fake `window.addEventListener`/`removeEventListener` - the only browser +API the region tool touches, so no real DOM was needed - covering 21 assertions: +a real drag's reported bbox correctly divides by zoom; dragging up-left still +normalizes to `x0 < x1`/`top < bottom` rather than an inverted box; a drag below +the minimum-pixel threshold never fires `onRegionDrawn` (no accidental zero-size +region from a stray click); both viewers' new multi-highlight state coexists with, +and never disturbs, the existing single-highlight state. `npm run build` passes; +the `app` container rebuilt and confirmed serving the new bundle. `backend/ +measure.py` unaffected (no backend touched this stage). **Not machine-verified:** +multiple labeled boxes actually rendering correctly on a real page at several zoom +levels, and a real mouse drag in an actual browser - the coordinate math itself is +proven correct by the Node tests above, but seeing it drawn on screen is the +user's own check, same standing limitation as every other frontend-only change +this session (Claude-in-Chrome still not connected). + **Governing rule: never silently correct or exclude data.** This shows up in several concrete places, not just as an abstract principle: - A row with an unusual status (e.g. HSBC's "Cancelled" wires) stays in the output and is diff --git a/frontend/src/assets/main.css b/frontend/src/assets/main.css index 24ba225..54acc26 100644 --- a/frontend/src/assets/main.css +++ b/frontend/src/assets/main.css @@ -439,14 +439,36 @@ tr.editing td{ background:rgba(37,99,235,.03); } display:flex; align-items:center; justify-content:center; gap:8px; color:var(--t4); font-size:13px; padding:20px; } -/* The review screen's row-highlighting (R.2, not wired up yet - R.1 only - builds the capability) - an absolutely-positioned box over the exact - printed row a flagged transaction came from, same box shape used over - both a pdf.js page and the image panel's own . */ +/* The review screen's row-highlighting (R.2) - an absolutely-positioned + box over the exact printed row a flagged transaction came from, same + box shape used over both a pdf.js page and the image panel's own + . */ .source-highlight-box{ position:absolute; border:2px solid var(--amber); background:rgba(217,119,6,.12); border-radius:3px; pointer-events:none; transition:all .2s; } +/* The layout mapper's own multi-box need (L.5, 2026-10-14) - several + labeled boxes at once (every mapped column region, or every proposed + zone in the superuser review screen - neither built yet). Blue by + default (overridden per-box via an inline color, e.g. one color per + field role in the manual mapping screen) - visually distinct from the + single amber review-screen highlight above, a different purpose. */ +.source-highlight-box-labeled{ border-color:var(--blue); background:rgba(37,99,235,.08); } +.source-highlight-label{ + position:absolute; top:-18px; left:-2px; background:var(--blue); color:#fff; + font-size:10.5px; font-weight:700; padding:1px 6px; border-radius:4px 4px 4px 0; + white-space:nowrap; line-height:1.4; +} +/* The click-and-drag region tool (useRegionDraw.js) - a live "rubber + band" box while dragging, same visual language as the labeled multi- + highlight boxes above (it's drawing exactly that kind of region). + pointer-events:none so it never itself intercepts the mouseup that + ends the drag. */ +.region-draft-box{ + position:absolute; border:2px dashed var(--blue); background:rgba(37,99,235,.12); + border-radius:3px; pointer-events:none; +} +.region-draw-active{ cursor:crosshair; user-select:none; } /* Images get their own zoomable/scrollable panel instead of the PDF iframe - a browser-native PDF viewer has its own zoom controls built in, an in the same iframe would have none at all, which is the diff --git a/frontend/src/components/SourceDocumentPanel.vue b/frontend/src/components/SourceDocumentPanel.vue index e1c9f0b..2c6cbe1 100644 --- a/frontend/src/components/SourceDocumentPanel.vue +++ b/frontend/src/components/SourceDocumentPanel.vue @@ -21,13 +21,27 @@ * chain - TransactionRow and this panel are siblings three levels apart, * not ancestor/descendant). * + * As of the layout-mapper work's L.5 stage (2026-10-14), also exposes + * showHighlights(boxes)/clearHighlights() - SEVERAL labeled boxes at + * once (every mapped column region, or every proposed zone in the + * superuser review screen, L.8 - neither built yet) - entirely separate + * from, and never clearing, the single showHighlight/clearHighlight + * above, which keeps working exactly as it always has for the review + * screen's own one-flag-at-a-time use. `regionDrawMode` (prop) + + * `region-drawn` (emit) is the new click-and-drag-to-define-a-region + * interaction (useRegionDraw.js) the manual mapping screen (L.6, not + * built yet) will drive - a no-op when the prop is left false, which it + * is everywhere today. + * * Data flow: - * previewUrl (string|null) - blob URL for the chosen file - * isImage (boolean) - whether to render the image panel instead of the PDF viewer + * previewUrl (string|null) - blob URL for the chosen file + * isImage (boolean) - whether to render the image panel instead of the PDF viewer + * regionDrawMode (boolean) - layout mapper work; enables the click-and-drag region tool */ import { computed, watch } from 'vue' import { useImageZoom } from '../composables/useImageZoom' import { usePdfViewer } from '../composables/usePdfViewer' +import { useRegionDraw } from '../composables/useRegionDraw' import { useUiStore } from '../stores/uiStore' const uiStore = useUiStore() @@ -35,23 +49,41 @@ const uiStore = useUiStore() const props = defineProps({ previewUrl: { type: String, default: null }, isImage: { type: Boolean, default: false }, + regionDrawMode: { type: Boolean, default: false }, }) +const emit = defineEmits(['region-drawn']) const { - imgRef, wrapRef, zoomLevelText: imgZoomText, onImageLoad, + imgRef, wrapRef, zoom: imgZoom, zoomLevelText: imgZoomText, onImageLoad, zoomIn: imgZoomIn, zoomOut: imgZoomOut, resetZoom: imgResetZoom, highlight: imgHighlight, highlightStyle: imgHighlightStyle, + highlights: imgHighlights, showHighlight: showImgHighlight, clearHighlight: clearImgHighlight, + showHighlights: showImgHighlights, clearHighlights: clearImgHighlights, } = useImageZoom() const { - containerRef, setCanvasRef, setPageWrapRef, numPages, zoomLevelText: pdfZoomText, + containerRef, setCanvasRef, setPageWrapRef, numPages, zoom: pdfZoom, zoomLevelText: pdfZoomText, loading: pdfLoading, loadError: pdfLoadError, highlight: pdfHighlight, highlightStyle: pdfHighlightStyle, + highlights: pdfHighlights, loadDocument, zoomIn: pdfZoomIn, zoomOut: pdfZoomOut, resetZoom: pdfResetZoom, showHighlight: showPdfHighlight, clearHighlight: clearPdfHighlight, + showHighlights: showPdfHighlights, clearHighlights: clearPdfHighlights, } = usePdfViewer() +const activeZoom = computed(() => (props.isImage ? imgZoom.value : pdfZoom.value)) +const { draftRect, drawingPage, handleMouseDown } = useRegionDraw(activeZoom, (page, bbox) => { + emit('region-drawn', { page, bbox }) +}) +const draftBoxStyle = computed(() => (draftRect.value ? { + left: draftRect.value.left + 'px', top: draftRect.value.top + 'px', + width: draftRect.value.width + 'px', height: draftRect.value.height + 'px', +} : null)) +function pdfHighlightsForPage(page) { + return pdfHighlights.value.filter((h) => h.page === page) +} + const zoomLevelText = computed(() => (props.isImage ? imgZoomText.value : pdfZoomText.value)) function zoomIn() { props.isImage ? imgZoomIn() : pdfZoomIn() } function zoomOut() { props.isImage ? imgZoomOut() : pdfZoomOut() } @@ -64,8 +96,10 @@ watch( // active document changes (different page numbers, different source // entirely) - clear both the request and whichever viewer's own // highlight state, so a stale box never lingers over a new document. + // Clears the multi-box highlights too, same reasoning. uiStore.clearHighlightRequest() clearHighlight() + clearHighlights() if (!isImage) loadDocument(url) }, { immediate: true }, @@ -79,7 +113,15 @@ function clearHighlight() { clearImgHighlight() clearPdfHighlight() } -defineExpose({ showHighlight, clearHighlight }) +function showHighlights(boxes) { + if (props.isImage) showImgHighlights(boxes) + else showPdfHighlights(boxes) +} +function clearHighlights() { + clearImgHighlights() + clearPdfHighlights() +} +defineExpose({ showHighlight, clearHighlight, showHighlights, clearHighlights }) diff --git a/frontend/src/composables/useImageZoom.js b/frontend/src/composables/useImageZoom.js index 3558159..e1d6f72 100644 --- a/frontend/src/composables/useImageZoom.js +++ b/frontend/src/composables/useImageZoom.js @@ -21,18 +21,25 @@ export function useImageZoom() { // `* zoom` math applyZoom already uses for the itself, no axis // flip or separate coordinate system needed. const highlight = ref(null) // {bbox} | null + // The layout mapper's own multi-box need (every mapped column region + // at once) - a parallel array alongside `highlight` above, which + // keeps its exact single-box shape for the review screen's own + // "Show on source" (R.2) call site. + const highlights = ref([]) // [{bbox, label?, color?}, ...] const zoomLevelText = computed(() => Math.round(zoom.value * 100) + '%') - const highlightStyle = computed(() => { - if (!highlight.value) return null - const { x0, x1, top, bottom } = highlight.value.bbox + /** Pixel position/size for a bbox at the current zoom - shared by the single highlight and the plural `highlights` below. */ + function boxStyle(bbox) { + const { x0, x1, top, bottom } = bbox return { left: x0 * zoom.value + 'px', top: top * zoom.value + 'px', width: (x1 - x0) * zoom.value + 'px', height: (bottom - top) * zoom.value + 'px', } - }) + } + const highlightStyle = computed(() => (highlight.value ? boxStyle(highlight.value.bbox) : null)) + const highlightsStyle = computed(() => highlights.value.map((h) => ({ ...h, style: boxStyle(h.bbox) }))) function applyZoom(z) { zoom.value = Math.max(ZOOM_MIN, Math.min(ZOOM_MAX, z)) @@ -77,8 +84,17 @@ export function useImageZoom() { highlight.value = null } + /** Shows several labeled boxes at once (the layout mapper's own need) - independent of, and never clearing, the single `highlight` above. No auto-scroll, unlike showHighlight - several boxes can be spread across the whole image at once. */ + function showHighlights(boxes) { + highlights.value = boxes || [] + } + function clearHighlights() { + highlights.value = [] + } + return { - imgRef, wrapRef, zoomLevelText, onImageLoad, zoomIn, zoomOut, resetZoom, - highlight, highlightStyle, showHighlight, clearHighlight, + imgRef, wrapRef, zoom, zoomLevelText, onImageLoad, zoomIn, zoomOut, resetZoom, + highlight, highlightStyle, highlights: highlightsStyle, showHighlight, clearHighlight, + showHighlights, clearHighlights, } } diff --git a/frontend/src/composables/usePdfViewer.js b/frontend/src/composables/usePdfViewer.js index 6f248f0..ed659ed 100644 --- a/frontend/src/composables/usePdfViewer.js +++ b/frontend/src/composables/usePdfViewer.js @@ -38,6 +38,12 @@ export function usePdfViewer() { const zoom = ref(1) const fitZoom = ref(1) const highlight = ref(null) // {page, bbox} | null + // The layout mapper's own multi-box need (showing every mapped column + // region at once, or every proposed zone in the superuser review + // screen) - a parallel array alongside the single `highlight` above, + // which stays exactly as it was for the review screen's one-flag-at- + // a-time "Show on source" (R.2) - that call site needs zero changes. + const highlights = ref([]) // [{page, bbox, label?, color?}, ...] const loading = ref(false) const loadError = ref('') @@ -168,21 +174,40 @@ export function usePdfViewer() { highlight.value = null } - /** Pixel position/size for the active highlight's overlay box, at the current zoom. */ - const highlightStyle = computed(() => { - if (!highlight.value) return null - const { x0, x1, top, bottom } = highlight.value.bbox + /** Pixel position/size for a bbox at the current zoom - the shared math both the single highlight and the plural `highlights` below render with. */ + function boxStyle(bbox) { + const { x0, x1, top, bottom } = bbox return { left: x0 * zoom.value + 'px', top: top * zoom.value + 'px', width: (x1 - x0) * zoom.value + 'px', height: (bottom - top) * zoom.value + 'px', } - }) + } + + /** Pixel position/size for the active highlight's overlay box, at the current zoom. */ + const highlightStyle = computed(() => (highlight.value ? boxStyle(highlight.value.bbox) : null)) + + /** + * Shows several labeled boxes at once (the layout mapper's own need - + * every mapped column region, or every proposed zone in the superuser + * review screen) - unrelated to, and never clearing, the single + * `highlight` above. Does NOT scroll anything into view itself (unlike + * showHighlight) - multiple boxes can span multiple pages at once, so + * there's no single "the" page to scroll to. + */ + function showHighlights(boxes) { + highlights.value = boxes || [] + } + function clearHighlights() { + highlights.value = [] + } + /** Each highlight box's own pre-computed pixel style, for the template's v-for - {..box, style}. */ + const highlightsStyle = computed(() => highlights.value.map((h) => ({ ...h, style: boxStyle(h.bbox) }))) return { - containerRef, setCanvasRef, setPageWrapRef, numPages, zoomLevelText, loading, loadError, - highlight, highlightStyle, loadDocument, renderAllPages, zoomIn, zoomOut, resetZoom, - showHighlight, clearHighlight, + containerRef, setCanvasRef, setPageWrapRef, numPages, zoom, zoomLevelText, loading, loadError, + highlight, highlightStyle, highlights: highlightsStyle, loadDocument, renderAllPages, zoomIn, zoomOut, resetZoom, + showHighlight, clearHighlight, showHighlights, clearHighlights, } } diff --git a/frontend/src/composables/useRegionDraw.js b/frontend/src/composables/useRegionDraw.js new file mode 100644 index 0000000..f46e3c5 --- /dev/null +++ b/frontend/src/composables/useRegionDraw.js @@ -0,0 +1,79 @@ +/** + * Click-and-drag-to-define-a-region interaction - doesn't exist + * anywhere else in this app yet. Built for the layout mapper's manual + * mapping screen (L.6, not built yet): the user drags a box over the + * source document to claim a region for a column role. Owned by + * SourceDocumentPanel.vue (the one place that already renders both the + * pdf.js pages and the image panel), via its own `regionDrawMode` prop + * and `region-drawn` emit - see that component. + * + * `zoomRef` - a reactive ref to whichever viewer's own current zoom + * factor is active (pdf.js's or the image panel's - both already use + * the identical `value * zoom` pixel mapping for their highlight boxes, + * see usePdfViewer.js/useImageZoom.js's own boxStyle()) - needed to + * convert the drawn pixel rectangle back into PDF-point/image-pixel + * space, the same coordinate space source_bbox already uses everywhere + * else in this app. + * + * `onRegionDrawn(page, bbox)` - called once per completed drag with the + * final bbox in that coordinate space; `page` is whatever was passed to + * `handleMouseDown` (a 1-based page number for pdf.js, `null` for the + * single-image panel, which has no page concept at all). + */ +import { ref } from 'vue' + +// Ignores an accidental click with no real drag - avoids ever emitting +// a zero-size (or near-zero) region nobody actually meant to draw. +const MIN_DRAG_PX = 4 + +export function useRegionDraw(zoomRef, onRegionDrawn) { + const draftRect = ref(null) // {left, top, width, height} in PIXELS, relative to whichever container drawing started in + const drawingPage = ref(null) // mirrors handleMouseDown's own `page` arg for the duration of one drag - lets the template show the draft box on the right page only + + let origin = null // {x, y} viewport coords of that container's own top-left at drag start + let startX = 0 + let startY = 0 + + function handleMouseMove(event) { + if (!origin) return + const x = event.clientX - origin.x + const y = event.clientY - origin.y + draftRect.value = { + left: Math.min(startX, x), top: Math.min(startY, y), + width: Math.abs(x - startX), height: Math.abs(y - startY), + } + } + + function handleMouseUp() { + window.removeEventListener('mousemove', handleMouseMove) + window.removeEventListener('mouseup', handleMouseUp) + const rect = draftRect.value + const page = drawingPage.value + draftRect.value = null + drawingPage.value = null + origin = null + if (!rect || rect.width < MIN_DRAG_PX || rect.height < MIN_DRAG_PX) return + + const zoom = zoomRef.value || 1 + onRegionDrawn(page, { + x0: rect.left / zoom, x1: (rect.left + rect.width) / zoom, + top: rect.top / zoom, bottom: (rect.top + rect.height) / zoom, + }) + } + + /** Starts a drag on whichever element this is bound to (its own bounding box is the drawn rectangle's coordinate origin) - `page` is a 1-based page number (pdf.js) or null (the single-image panel). */ + function handleMouseDown(event, page = null) { + if (event.button !== 0) return // left click only + const rect = event.currentTarget.getBoundingClientRect() + origin = { x: rect.left, y: rect.top } + drawingPage.value = page + startX = event.clientX - origin.x + startY = event.clientY - origin.y + draftRect.value = { left: startX, top: startY, width: 0, height: 0 } + window.addEventListener('mousemove', handleMouseMove) + window.addEventListener('mouseup', handleMouseUp) + event.preventDefault() + } + + return { draftRect, drawingPage, handleMouseDown } +}