diff --git a/docs/API.md b/docs/API.md index 6e3fe7e..101c985 100644 --- a/docs/API.md +++ b/docs/API.md @@ -44,10 +44,13 @@ For the logical field / visual widget data model (plain serializable types, rela - `pdf-elements:end-init` - Emitted when PDF is loaded. - `pdf-elements:adding-ended` - Emitted when interactive placement ends. Payload: `{ reason: 'placed', object, docIndex, pageIndex }` on success or `{ reason: 'cancelled' }` when placement is cancelled. +- `pdf-elements:page-change` - Emitted when the page occupying most of the viewport changes (on scroll, on zoom and once pages have rendered after load). Payload: `{ docIndex, pageIndex }` (zero-based). ## Exposed methods - `startAddingElement(templateObject)` - Starts interactive placement mode. +- `goToPage(pageIndex, docIndex = 0)` - Scrolls the page to the top of the viewer. Zero-based indices. Returns `false` when the page does not exist or has not been rendered yet. When the scroll range cannot bring the page to the top (for example a short last page), it is still reported as the current page until the user scrolls. +- `getCurrentPage()` - Returns `{ docIndex, pageIndex }` for the page occupying most of the viewport, or `null` when no page has been rendered yet. - `cancelAdding()` - Cancels the current placement session and emits `pdf-elements:adding-ended` with `{ reason: 'cancelled' }` when a session was active. ## Slots diff --git a/src/components/PDFElements.vue b/src/components/PDFElements.vue index 28e6a2e..788f409 100644 --- a/src/components/PDFElements.vue +++ b/src/components/PDFElements.vue @@ -145,14 +145,14 @@ import PDFPage from './PDFPage.vue' import DraggableElement from './DraggableElement.vue' import { readAsPDF, readAsArrayBuffer } from '../utils/asyncReader' import { clampPosition, getVisibleArea } from '../utils/geometry' -import { getViewportWindow, isPageInViewport } from '../utils/pageBounds' +import { getViewportWindow, isPageInViewport, findMostVisiblePage } from '../utils/pageBounds' import { objectIdExistsInDoc, findObjectPageIndex, updateObjectInDoc, removeObjectFromDoc } from '../utils/objectStore' import { getCachedMeasurement } from '../utils/measurements' import type { PDFDocumentEntry, PDFElementObject, PDFElementsAddingEndedPayload } from '../types' export default defineComponent({ name: 'PDFElements', - emits: ['pdf-elements:end-init', 'pdf-elements:delete-object', 'pdf-elements:object-click', 'pdf-elements:adding-ended'], + emits: ['pdf-elements:end-init', 'pdf-elements:delete-object', 'pdf-elements:object-click', 'pdf-elements:adding-ended', 'pdf-elements:page-change'], components: { PDFPage, DraggableElement, @@ -252,6 +252,11 @@ export default defineComponent({ pendingDragClientPos: null as { x: number; y: number } | null, pageBoundsVersion: 0, lastScrollTop: 0, + currentVisiblePage: null as { docIndex: number; pageIndex: number } | null, + currentPageRafId: 0, + navigationTarget: null as { docIndex: number; pageIndex: number } | null, + navigationScrollTop: 0, + _measuredPages: markRaw({}) as Record, lastClientWidth: 0, nextObjectCounter: 0, isDraggingElement: false, @@ -338,6 +343,10 @@ export default defineComponent({ window.cancelAnimationFrame(this.viewportRafId) this.viewportRafId = 0 } + if (this.currentPageRafId) { + window.cancelAnimationFrame(this.currentPageRafId) + this.currentPageRafId = 0 + } if (this.hoverRafId) { window.cancelAnimationFrame(this.hoverRafId) this.hoverRafId = 0 @@ -409,11 +418,15 @@ export default defineComponent({ this.pdfDocuments = docs this._pageMeasurementCache = markRaw({}) + this._measuredPages = markRaw({}) + this.currentVisiblePage = null + this.navigationTarget = null if (docs.length) { this.selectedDocIndex = 0 this.selectedPageIndex = 0 this.$emit('pdf-elements:end-init', { docsCount: docs.length }) this.$nextTick(() => { + this.updateCurrentPage() if (this.autoFitZoom) { this.scheduleAutoFitZoom() } @@ -802,10 +815,114 @@ export default defineComponent({ this.scheduleAutoFitZoom() } } + this.updateCurrentPage() this.viewportRafId = 0 }) }, + getPageWrapperElement(docIndex, pageIndex) { + const canvas = this.getPageCanvasElement(docIndex, pageIndex) + return canvas?.closest?.('.page-wrapper') || canvas || null + }, + + isPageMeasured(docIndex, pageIndex) { + return !!this._measuredPages[`${docIndex}-${pageIndex}`] + }, + + getPageViewportRect(docIndex, pageIndex, containerTop) { + const wrapper = this.getPageWrapperElement(docIndex, pageIndex) + if (!wrapper?.getBoundingClientRect) return null + const rect = wrapper.getBoundingClientRect() + return { docIndex, pageIndex, top: rect.top - containerTop, bottom: rect.bottom - containerTop } + }, + + getCurrentPage() { + const container = this.$el + if (!container?.getBoundingClientRect) return null + const entries = [] + this.pdfDocuments.forEach((doc, docIndex) => { + for (let pageIndex = 0; pageIndex < doc.pages.length; pageIndex++) { + entries.push({ docIndex, pageIndex }) + } + }) + if (!entries.length) return null + const containerTop = container.getBoundingClientRect().top + const viewHeight = container.clientHeight || 0 + const rectAt = (i) => this.getPageViewportRect(entries[i].docIndex, entries[i].pageIndex, containerTop) + + // Pages are stacked in document order: start from the last known page and + // only read the pages around the viewport instead of every page. + const known = this.currentVisiblePage + let first = known + ? Math.max(0, entries.findIndex((e) => e.docIndex === known.docIndex && e.pageIndex === known.pageIndex)) + : 0 + while (first > 0) { + const previous = rectAt(first - 1) + if (!previous || previous.bottom <= 0) break + first-- + } + while (first < entries.length - 1) { + const rect = rectAt(first) + if (rect && rect.bottom > 0) break + first++ + } + + const rects = [] + for (let i = first; i < entries.length; i++) { + const rect = rectAt(i) + if (!rect) continue + if (rect.top >= viewHeight) break + // Pages that were not rendered yet still have placeholder dimensions. + if (this.isPageMeasured(rect.docIndex, rect.pageIndex)) rects.push(rect) + } + + const target = this.navigationTarget + if (target) { + if (container.scrollTop === this.navigationScrollTop) { + // goToPage could not bring the page to the top (scroll clamped at the end): keep it current. + const targetRect = rects.find((r) => r.docIndex === target.docIndex && r.pageIndex === target.pageIndex) + if (targetRect && Math.min(targetRect.bottom, viewHeight) - Math.max(targetRect.top, 0) > 0) { + return { docIndex: target.docIndex, pageIndex: target.pageIndex } + } + } else { + this.navigationTarget = null + } + } + return findMostVisiblePage(rects, viewHeight) + }, + + updateCurrentPage() { + const page = this.getCurrentPage() + if (!page) return + const previous = this.currentVisiblePage + if (previous && previous.docIndex === page.docIndex && previous.pageIndex === page.pageIndex) return + this.currentVisiblePage = page + this.$emit('pdf-elements:page-change', { ...page }) + }, + + scheduleCurrentPageUpdate() { + if (this.currentPageRafId) return + this.currentPageRafId = window.requestAnimationFrame(() => { + this.currentPageRafId = 0 + this.updateCurrentPage() + }) + }, + + goToPage(pageIndex, docIndex = 0) { + const doc = this.pdfDocuments[docIndex] + if (!doc || !Number.isInteger(pageIndex) || pageIndex < 0 || pageIndex >= doc.pages.length) return false + if (!this.isPageMeasured(docIndex, pageIndex)) return false + const container = this.$el + const wrapper = this.getPageWrapperElement(docIndex, pageIndex) + if (!container?.getBoundingClientRect || !wrapper?.getBoundingClientRect) return false + const delta = wrapper.getBoundingClientRect().top - container.getBoundingClientRect().top + container.scrollTop = Math.max(0, (container.scrollTop || 0) + delta) + this.navigationTarget = { docIndex, pageIndex } + this.navigationScrollTop = container.scrollTop + this.updateCurrentPage() + return true + }, + handleMouseMove(event) { if (event?.touches?.length > 1 || this.isPinching) return if (!this.isAddingMode || !this.previewElement) return @@ -1348,7 +1465,9 @@ export default defineComponent({ onMeasure(e, docIndex, pageIndex) { if (docIndex < 0 || docIndex >= this.pdfDocuments.length) return this._pageMeasurementCache[`${docIndex}-${pageIndex}`] = null + this._measuredPages[`${docIndex}-${pageIndex}`] = true this.cachePageBoundsForPage(docIndex, pageIndex) + this.scheduleCurrentPageUpdate() if (this.autoFitZoom) { this.scheduleAutoFitZoom() } diff --git a/src/index.ts b/src/index.ts index 33bd198..1ab6f36 100644 --- a/src/index.ts +++ b/src/index.ts @@ -35,6 +35,7 @@ export type { PDFElementsAddingEndedPayload, PDFElementsAddingEndedPlacedPayload, PDFElementsAddingEndedReason, + PDFElementsPageChangePayload, PDFElementsPublicApi, PDFFormField, PDFFormFieldId, diff --git a/src/types.ts b/src/types.ts index 9dbf5fc..c421f4a 100644 --- a/src/types.ts +++ b/src/types.ts @@ -42,6 +42,11 @@ export interface PDFDocumentEntry { allObjects: PDFElementObject[][] } +export interface PDFElementsPageChangePayload { + docIndex: number + pageIndex: number +} + export interface PDFElementsPublicApi { startAddingElement: (templateObject: PDFElementObject) => void addObjectToPage: (object: PDFElementObject, pageIndex?: number, docIndex?: number) => boolean @@ -50,6 +55,8 @@ export interface PDFElementsPublicApi { deleteObject: (docIndex: number, objectId: string) => void duplicateObject: (docIndex: number, objectId: string) => void cancelAdding: () => void + goToPage: (pageIndex: number, docIndex?: number) => boolean + getCurrentPage: () => PDFElementsPageChangePayload | null } /** diff --git a/src/utils/pageBounds.ts b/src/utils/pageBounds.ts index e6ffc1c..d20714e 100644 --- a/src/utils/pageBounds.ts +++ b/src/utils/pageBounds.ts @@ -11,3 +11,29 @@ export function getViewportWindow(scrollTop: number, viewHeight: number, margin export function isPageInViewport(offsetTop: number, offsetHeight: number, minY: number, maxY: number) { return !(offsetTop + offsetHeight < minY || offsetTop > maxY) } + +export interface PageViewportRect { + docIndex: number + pageIndex: number + /** Top edge relative to the top of the scroll viewport. */ + top: number + /** Bottom edge relative to the top of the scroll viewport. */ + bottom: number +} + +/** + * Returns the page occupying the largest visible area of the viewport. + * Ties resolve to the first page in document order. + */ +export function findMostVisiblePage(rects: PageViewportRect[], viewHeight: number) { + let best: PageViewportRect | null = null + let bestVisible = 0 + for (const rect of rects) { + const visible = Math.min(rect.bottom, viewHeight) - Math.max(rect.top, 0) + if (visible > bestVisible) { + best = rect + bestVisible = visible + } + } + return best ? { docIndex: best.docIndex, pageIndex: best.pageIndex } : null +} diff --git a/tests/components/PDFElements.spec.ts b/tests/components/PDFElements.spec.ts index 3866ef7..3d699b5 100644 --- a/tests/components/PDFElements.spec.ts +++ b/tests/components/PDFElements.spec.ts @@ -918,3 +918,111 @@ describe('PDFElements business rules', () => { rafSpy.mockRestore() }) }) + +describe('PDFElements page navigation', () => { + // tops[docIndex][pageIndex] = absolute top of each 400px tall page + const setup = (tops: number[][], { maxScroll = Infinity, measured = true } = {}) => { + const { wrapper, ctx } = makeWrapper() + ctx.pdfDocuments = tops.map((pages) => { + const doc = makeDoc() + doc.pages = pages.map(() => Promise.resolve()) + return doc + }) + const root = ctx.$el as HTMLElement + root.getBoundingClientRect = () => ({ top: 0, bottom: 500 } as DOMRect) + Object.defineProperty(root, 'clientHeight', { value: 500, configurable: true }) + let scrollTop = 0 + Object.defineProperty(root, 'scrollTop', { + configurable: true, + get: () => scrollTop, + set: (value: number) => { scrollTop = Math.min(value, maxScroll) }, + }) + ctx.getPageWrapperElement = vi.fn((d: number, p: number) => { + const top = tops[d]?.[p] + if (top === undefined) return null + return { getBoundingClientRect: () => ({ top: top - scrollTop, bottom: top + 400 - scrollTop }) } + }) + if (measured) { + tops.forEach((pages, d) => pages.forEach((_, p) => { ctx._measuredPages[`${d}-${p}`] = true })) + } + return { wrapper, ctx, root } + } + + it('scrolls to the requested page', () => { + const { ctx, root } = setup([[0, 450]]) + expect(ctx.goToPage(1)).toBe(true) + expect(root.scrollTop).toBe(450) + expect(ctx.getCurrentPage()).toEqual({ docIndex: 0, pageIndex: 1 }) + }) + + it('resolves the page in the requested document', () => { + const { ctx, root } = setup([[0, 450], [900, 1350]]) + expect(ctx.goToPage(0, 1)).toBe(true) + expect(ctx.getPageWrapperElement).toHaveBeenNthCalledWith(1, 1, 0) + expect(root.scrollTop).toBe(900) + expect(ctx.getCurrentPage()).toEqual({ docIndex: 1, pageIndex: 0 }) + }) + + it('rejects invalid pages', () => { + const { ctx } = setup([[0, 450]]) + expect(ctx.goToPage(2)).toBe(false) + expect(ctx.goToPage(-1)).toBe(false) + expect(ctx.goToPage(0, 3)).toBe(false) + }) + + it('returns false while the page is not rendered or has no element', () => { + const { ctx, root } = setup([[0, 450]], { measured: false }) + expect(ctx.goToPage(1)).toBe(false) + expect(ctx.getCurrentPage()).toBeNull() + ctx._measuredPages['0-1'] = true + ctx.getPageWrapperElement = vi.fn(() => null) + expect(ctx.goToPage(1)).toBe(false) + expect(root.scrollTop).toBe(0) + }) + + it('keeps the requested page current when the scroll range is clamped', () => { + const { wrapper, ctx, root } = setup([[0, 450]], { maxScroll: 20 }) + expect(ctx.goToPage(1)).toBe(true) + expect(root.scrollTop).toBe(20) + expect(ctx.getCurrentPage()).toEqual({ docIndex: 0, pageIndex: 1 }) + expect(wrapper.emitted('pdf-elements:page-change')).toEqual([[{ docIndex: 0, pageIndex: 1 }]]) + root.scrollTop = 0 + expect(ctx.getCurrentPage()).toEqual({ docIndex: 0, pageIndex: 0 }) + }) + + it('emits page-change only when the visible page changes', () => { + const { wrapper, ctx, root } = setup([[0, 450]]) + ctx.updateCurrentPage() + ctx.updateCurrentPage() + root.scrollTop = 450 + ctx.updateCurrentPage() + expect(wrapper.emitted('pdf-elements:page-change')).toEqual([ + [{ docIndex: 0, pageIndex: 0 }], + [{ docIndex: 0, pageIndex: 1 }], + ]) + }) + + it('emits the initial page-change once pages are measured', async () => { + const rafSpy = vi.spyOn(window, 'requestAnimationFrame').mockImplementation((cb: FrameRequestCallback) => { + cb(0) + return 1 + }) + const { wrapper, ctx } = setup([[0, 450]], { measured: false }) + ctx.updateCurrentPage() + expect(wrapper.emitted('pdf-elements:page-change')).toBeUndefined() + ctx.onMeasure({}, 0, 0) + expect(wrapper.emitted('pdf-elements:page-change')).toEqual([[{ docIndex: 0, pageIndex: 0 }]]) + rafSpy.mockRestore() + }) + + it('only reads pages around the viewport', () => { + const tops = [Array.from({ length: 200 }, (_, i) => i * 450)] + const { ctx, root } = setup(tops) + root.scrollTop = 450 * 100 + ctx.updateCurrentPage() + ctx.getPageWrapperElement.mockClear() + root.scrollTop = 450 * 101 + expect(ctx.getCurrentPage()).toEqual({ docIndex: 0, pageIndex: 101 }) + expect(ctx.getPageWrapperElement.mock.calls.length).toBeLessThan(10) + }) +}) diff --git a/tests/utils/pageBounds.spec.ts b/tests/utils/pageBounds.spec.ts index 6f94a62..ed662c1 100644 --- a/tests/utils/pageBounds.spec.ts +++ b/tests/utils/pageBounds.spec.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later import { describe, it, expect } from 'vitest' -import { getViewportWindow, isPageInViewport } from '../../src/utils/pageBounds' +import { findMostVisiblePage, getViewportWindow, isPageInViewport } from '../../src/utils/pageBounds' describe('pageBounds', () => { it('computes viewport window with margin', () => { @@ -16,3 +16,19 @@ describe('pageBounds', () => { expect(isPageInViewport(400, 50, 0, 300)).toBe(false) }) }) + +describe('findMostVisiblePage', () => { + const rects = [ + { docIndex: 0, pageIndex: 0, top: -400, bottom: 100 }, + { docIndex: 0, pageIndex: 1, top: 100, bottom: 600 }, + ] + + it('picks the page with the largest visible area', () => { + expect(findMostVisiblePage(rects, 500)).toEqual({ docIndex: 0, pageIndex: 1 }) + }) + + it('returns null when nothing is visible', () => { + expect(findMostVisiblePage([], 500)).toBeNull() + expect(findMostVisiblePage([{ docIndex: 0, pageIndex: 0, top: 600, bottom: 900 }], 500)).toBeNull() + }) +})