From 68ccc0105f0b24bbb51ccbf88c5371244608deb4 Mon Sep 17 00:00:00 2001 From: Luis Amorim Date: Wed, 25 Nov 2026 18:28:55 -0300 Subject: [PATCH 01/11] feat(navigation): expose goToPage, getCurrentPage and page-change event Lets hosts build pagination controls and page thumbnails without relying on internal DOM structure. Signed-off-by: Luis Amorim --- docs/API.md | 3 ++ src/components/PDFElements.vue | 48 ++++++++++++++++++++++++++-- src/index.ts | 1 + src/types.ts | 7 ++++ src/utils/pageBounds.ts | 26 +++++++++++++++ tests/components/PDFElements.spec.ts | 42 ++++++++++++++++++++++++ tests/utils/pageBounds.spec.ts | 18 ++++++++++- 7 files changed, 142 insertions(+), 3 deletions(-) diff --git a/docs/API.md b/docs/API.md index 6e3fe7e..cdcf691 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 and 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 is not rendered. +- `getCurrentPage()` - Returns `{ docIndex, pageIndex }` for the page occupying most of the viewport, or `null` when no page is rendered. - `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..d4b7c76 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,7 @@ export default defineComponent({ pendingDragClientPos: null as { x: number; y: number } | null, pageBoundsVersion: 0, lastScrollTop: 0, + currentVisiblePage: null as { docIndex: number; pageIndex: number } | null, lastClientWidth: 0, nextObjectCounter: 0, isDraggingElement: false, @@ -414,6 +415,7 @@ export default defineComponent({ this.selectedPageIndex = 0 this.$emit('pdf-elements:end-init', { docsCount: docs.length }) this.$nextTick(() => { + this.updateCurrentPage() if (this.autoFitZoom) { this.scheduleAutoFitZoom() } @@ -802,10 +804,52 @@ 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 + }, + + getCurrentPage() { + const container = this.$el + if (!container?.getBoundingClientRect) return null + const containerTop = container.getBoundingClientRect().top + const rects = [] + this.pdfDocuments.forEach((doc, docIndex) => { + for (let pageIndex = 0; pageIndex < doc.pages.length; pageIndex++) { + const wrapper = this.getPageWrapperElement(docIndex, pageIndex) + if (!wrapper?.getBoundingClientRect) continue + const rect = wrapper.getBoundingClientRect() + rects.push({ docIndex, pageIndex, top: rect.top - containerTop, bottom: rect.bottom - containerTop }) + } + }) + return findMostVisiblePage(rects, container.clientHeight || 0) + }, + + 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 }) + }, + + goToPage(pageIndex, docIndex = 0) { + const doc = this.pdfDocuments[docIndex] + if (!doc || !Number.isInteger(pageIndex) || pageIndex < 0 || pageIndex >= doc.pages.length) 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) + return true + }, + handleMouseMove(event) { if (event?.touches?.length > 1 || this.isPinching) return if (!this.isAddingMode || !this.previewElement) return 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..71ac991 100644 --- a/tests/components/PDFElements.spec.ts +++ b/tests/components/PDFElements.spec.ts @@ -918,3 +918,45 @@ describe('PDFElements business rules', () => { rafSpy.mockRestore() }) }) + +describe('PDFElements page navigation', () => { + const setup = (tops: number[]) => { + const { wrapper, ctx } = makeWrapper() + const doc = makeDoc() + ctx.pdfDocuments = [doc] + const root = ctx.$el as HTMLElement + root.getBoundingClientRect = () => ({ top: 0, bottom: 500 } as DOMRect) + Object.defineProperty(root, 'clientHeight', { value: 500, configurable: true }) + root.scrollTop = 0 + ctx.getPageWrapperElement = vi.fn((_d: number, p: number) => ({ + getBoundingClientRect: () => ({ top: tops[p] - root.scrollTop, bottom: tops[p] + 400 - root.scrollTop }), + })) + 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('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('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 }], + ]) + }) +}) 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() + }) +}) From 4ebec8c241342032fb75f7c3f4278e79c4e45dbd Mon Sep 17 00:00:00 2001 From: Luis Amorim Date: Wed, 25 Nov 2026 19:36:31 -0300 Subject: [PATCH 02/11] fix(navigation): sync page-change with rendered pages and zoom - track rendered pages and ignore placeholder-sized ones in getCurrentPage - make goToPage return false until the target page has rendered - recompute the current page after page (re)measure, which covers zoom - keep the requested page current when the scroll range is clamped - read only pages around the viewport instead of every page per frame - cover multi-document, unrendered page and clamp cases in tests Signed-off-by: Luis Amorim --- docs/API.md | 6 +- src/components/PDFElements.vue | 89 +++++++++++++++++++++++++--- tests/components/PDFElements.spec.ts | 86 +++++++++++++++++++++++---- 3 files changed, 161 insertions(+), 20 deletions(-) diff --git a/docs/API.md b/docs/API.md index cdcf691..101c985 100644 --- a/docs/API.md +++ b/docs/API.md @@ -44,13 +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 and after load). Payload: `{ docIndex, pageIndex }` (zero-based). +- `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 is not rendered. -- `getCurrentPage()` - Returns `{ docIndex, pageIndex }` for the page occupying most of the viewport, or `null` when no page is rendered. +- `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 d4b7c76..788f409 100644 --- a/src/components/PDFElements.vue +++ b/src/components/PDFElements.vue @@ -253,6 +253,10 @@ export default defineComponent({ 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, @@ -339,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 @@ -410,6 +418,9 @@ 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 @@ -814,20 +825,70 @@ export default defineComponent({ 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 containerTop = container.getBoundingClientRect().top - const rects = [] + const entries = [] this.pdfDocuments.forEach((doc, docIndex) => { for (let pageIndex = 0; pageIndex < doc.pages.length; pageIndex++) { - const wrapper = this.getPageWrapperElement(docIndex, pageIndex) - if (!wrapper?.getBoundingClientRect) continue - const rect = wrapper.getBoundingClientRect() - rects.push({ docIndex, pageIndex, top: rect.top - containerTop, bottom: rect.bottom - containerTop }) + entries.push({ docIndex, pageIndex }) } }) - return findMostVisiblePage(rects, container.clientHeight || 0) + 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() { @@ -839,14 +900,26 @@ export default defineComponent({ 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 }, @@ -1392,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/tests/components/PDFElements.spec.ts b/tests/components/PDFElements.spec.ts index 71ac991..3d699b5 100644 --- a/tests/components/PDFElements.spec.ts +++ b/tests/components/PDFElements.spec.ts @@ -920,36 +920,78 @@ describe('PDFElements business rules', () => { }) describe('PDFElements page navigation', () => { - const setup = (tops: number[]) => { + // tops[docIndex][pageIndex] = absolute top of each 400px tall page + const setup = (tops: number[][], { maxScroll = Infinity, measured = true } = {}) => { const { wrapper, ctx } = makeWrapper() - const doc = makeDoc() - ctx.pdfDocuments = [doc] + 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 }) - root.scrollTop = 0 - ctx.getPageWrapperElement = vi.fn((_d: number, p: number) => ({ - getBoundingClientRect: () => ({ top: tops[p] - root.scrollTop, bottom: tops[p] + 400 - root.scrollTop }), - })) + 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]) + 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]) + 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]) + const { wrapper, ctx, root } = setup([[0, 450]]) ctx.updateCurrentPage() ctx.updateCurrentPage() root.scrollTop = 450 @@ -959,4 +1001,28 @@ describe('PDFElements page navigation', () => { [{ 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) + }) }) From 14e21d26653853e2bbade1d462d444cd040c5250 Mon Sep 17 00:00:00 2001 From: Luis Amorim Date: Wed, 25 Nov 2026 23:24:39 -0300 Subject: [PATCH 03/11] fix(navigation): react to container resize and limit target override - observe the viewer container with a ResizeObserver to refresh the current page - keep the goToPage target only when the scroll was clamped, so zoom cannot pin it Signed-off-by: Luis Amorim --- src/components/PDFElements.vue | 16 ++++++++++-- tests/components/PDFElements.spec.ts | 39 ++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/src/components/PDFElements.vue b/src/components/PDFElements.vue index 788f409..084f0c9 100644 --- a/src/components/PDFElements.vue +++ b/src/components/PDFElements.vue @@ -254,6 +254,7 @@ export default defineComponent({ lastScrollTop: 0, currentVisiblePage: null as { docIndex: number; pageIndex: number } | null, currentPageRafId: 0, + resizeObserver: null as ResizeObserver | null, navigationTarget: null as { docIndex: number; pageIndex: number } | null, navigationScrollTop: 0, _measuredPages: markRaw({}) as Record, @@ -308,6 +309,10 @@ export default defineComponent({ window.addEventListener('scroll', this.onViewportScroll, { passive: true }) window.addEventListener('resize', this.onViewportScroll) this.$el?.addEventListener('scroll', this.onViewportScroll, { passive: true }) + if (typeof ResizeObserver !== 'undefined' && this.$el) { + this.resizeObserver = markRaw(new ResizeObserver(() => this.scheduleCurrentPageUpdate())) + this.resizeObserver.observe(this.$el) + } this.$el?.addEventListener('wheel', this.boundHandleWheel, { passive: false }) this.$el?.addEventListener('touchstart', this.boundHandleTouchStart, { passive: false }) this.$el?.addEventListener('touchmove', this.boundHandleTouchMove, { passive: false }) @@ -343,6 +348,10 @@ export default defineComponent({ window.cancelAnimationFrame(this.viewportRafId) this.viewportRafId = 0 } + if (this.resizeObserver) { + this.resizeObserver.disconnect() + this.resizeObserver = null + } if (this.currentPageRafId) { window.cancelAnimationFrame(this.currentPageRafId) this.currentPageRafId = 0 @@ -916,8 +925,11 @@ export default defineComponent({ 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 } + const desiredScrollTop = Math.max(0, (container.scrollTop || 0) + delta) + container.scrollTop = desiredScrollTop + // Only a clamped scroll (page cannot reach the top) needs the target override. + const clamped = container.scrollTop < desiredScrollTop - 0.5 + this.navigationTarget = clamped ? { docIndex, pageIndex } : null this.navigationScrollTop = container.scrollTop this.updateCurrentPage() return true diff --git a/tests/components/PDFElements.spec.ts b/tests/components/PDFElements.spec.ts index 3d699b5..d47366e 100644 --- a/tests/components/PDFElements.spec.ts +++ b/tests/components/PDFElements.spec.ts @@ -990,6 +990,45 @@ describe('PDFElements page navigation', () => { expect(ctx.getCurrentPage()).toEqual({ docIndex: 0, pageIndex: 0 }) }) + it('does not pin an unclamped target when zoom changes the geometry', () => { + const { ctx } = setup([[0, 450]]) + expect(ctx.goToPage(0)).toBe(true) + expect(ctx.navigationTarget).toBeNull() + ctx.getPageWrapperElement = vi.fn((_d: number, p: number) => ({ + getBoundingClientRect: () => (p === 0 ? { top: 0, bottom: 200 } : { top: 200, bottom: 800 }), + })) + expect(ctx.getCurrentPage()).toEqual({ docIndex: 0, pageIndex: 1 }) + }) + + it('recomputes the current page when the container is resized', () => { + const observers: Array<() => void> = [] + const disconnect = vi.fn() + vi.stubGlobal('ResizeObserver', class { + constructor(cb: () => void) { observers.push(cb) } + observe() {} + disconnect() { disconnect() } + }) + const rafSpy = vi.spyOn(window, 'requestAnimationFrame').mockImplementation((cb: FrameRequestCallback) => { + cb(0) + return 1 + }) + const { wrapper, ctx } = setup([[0, 450]]) + expect(observers).toHaveLength(1) + ctx.updateCurrentPage() + ctx.getPageWrapperElement = vi.fn((_d: number, p: number) => ({ + getBoundingClientRect: () => (p === 0 ? { top: 0, bottom: 100 } : { top: 100, bottom: 700 }), + })) + observers[0]() + expect(wrapper.emitted('pdf-elements:page-change')).toEqual([ + [{ docIndex: 0, pageIndex: 0 }], + [{ docIndex: 0, pageIndex: 1 }], + ]) + wrapper.unmount() + expect(disconnect).toHaveBeenCalled() + rafSpy.mockRestore() + vi.unstubAllGlobals() + }) + it('emits page-change only when the visible page changes', () => { const { wrapper, ctx, root } = setup([[0, 450]]) ctx.updateCurrentPage() From dcd99d3bd664026debf77faf47bf0326b0ee0cfc Mon Sep 17 00:00:00 2001 From: Luis Amorim Date: Thu, 26 Nov 2026 09:40:02 -0300 Subject: [PATCH 04/11] fix(navigation): scroll instantly in goToPage before checking for clamping smooth scroll-behavior on the host could defer the final scrollTop, so the clamp check read the old position and dropped the navigation target. Signed-off-by: Luis Amorim --- src/components/PDFElements.vue | 7 ++++++- tests/components/PDFElements.spec.ts | 8 ++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/components/PDFElements.vue b/src/components/PDFElements.vue index 084f0c9..c388d4c 100644 --- a/src/components/PDFElements.vue +++ b/src/components/PDFElements.vue @@ -926,7 +926,12 @@ export default defineComponent({ if (!container?.getBoundingClientRect || !wrapper?.getBoundingClientRect) return false const delta = wrapper.getBoundingClientRect().top - container.getBoundingClientRect().top const desiredScrollTop = Math.max(0, (container.scrollTop || 0) + delta) - container.scrollTop = desiredScrollTop + // Instant, so `scroll-behavior: smooth` on the host cannot defer the final (clamped) position. + if (typeof container.scrollTo === 'function') { + container.scrollTo({ top: desiredScrollTop, behavior: 'instant' }) + } else { + container.scrollTop = desiredScrollTop + } // Only a clamped scroll (page cannot reach the top) needs the target override. const clamped = container.scrollTop < desiredScrollTop - 0.5 this.navigationTarget = clamped ? { docIndex, pageIndex } : null diff --git a/tests/components/PDFElements.spec.ts b/tests/components/PDFElements.spec.ts index d47366e..b60ce5a 100644 --- a/tests/components/PDFElements.spec.ts +++ b/tests/components/PDFElements.spec.ts @@ -990,6 +990,14 @@ describe('PDFElements page navigation', () => { expect(ctx.getCurrentPage()).toEqual({ docIndex: 0, pageIndex: 0 }) }) + it('scrolls instantly so smooth scroll-behavior cannot defer the clamp check', () => { + const { ctx, root } = setup([[0, 450]], { maxScroll: 20 }) + ;(root as any).scrollTo = vi.fn(({ top }: { top: number }) => { root.scrollTop = top }) + expect(ctx.goToPage(1)).toBe(true) + expect((root as any).scrollTo).toHaveBeenCalledWith({ top: 450, behavior: 'instant' }) + expect(ctx.getCurrentPage()).toEqual({ docIndex: 0, pageIndex: 1 }) + }) + it('does not pin an unclamped target when zoom changes the geometry', () => { const { ctx } = setup([[0, 450]]) expect(ctx.goToPage(0)).toBe(true) From eb746fce042356fd9b132fd090c8c6593ca9659b Mon Sep 17 00:00:00 2001 From: Luis Amorim Date: Thu, 26 Nov 2026 13:15:01 -0300 Subject: [PATCH 05/11] refactor(navigation): follow PDF.js for page geometry and visibility - reserve page dimensions from the PDF.js viewport in PDFPage (onGeometry), so goToPage no longer waits for the canvas render task - keep a valid goToPage request until the layout is known instead of failing (latest request wins) - pick the current page by visible percentage, keep it while fully visible and account for horizontal clipping; explicit navigation sets the current page, which removes navigationTarget/navigationScrollTop - reuse an ordered page index and read only pages around the viewport - scroll the nearest scrollable ancestor or the window when the viewer has no bounded height - add an e2e fixture with mixed page sizes/orientations and Playwright tests for navigation, resize, zoom and multiple documents Signed-off-by: Luis Amorim --- REUSE.toml | 1 + docs/API.md | 6 +- e2e/fixtures/mixed-pages.pdf | Bin 0 -> 1683 bytes e2e/page-navigation.spec.ts | 125 ++++++++++++++++ examples/basic/App.vue | 20 +++ src/components/PDFElements.vue | 191 +++++++++++++++++-------- src/components/PDFPage.vue | 18 ++- src/utils/pageBounds.ts | 51 ++++++- tests/components/PDFElements.spec.ts | 204 ++++++++++++++++++--------- tests/components/PDFPage.spec.ts | 28 ++++ tests/utils/pageBounds.spec.ts | 44 ++++++ 11 files changed, 552 insertions(+), 136 deletions(-) create mode 100644 e2e/fixtures/mixed-pages.pdf create mode 100644 e2e/page-navigation.spec.ts diff --git a/REUSE.toml b/REUSE.toml index 988e4e3..83dc43f 100644 --- a/REUSE.toml +++ b/REUSE.toml @@ -21,6 +21,7 @@ path = [ "vitest.config.ts", "examples/**", "tests/**", + "e2e/fixtures/**", "dist/**", "img/**", ] diff --git a/docs/API.md b/docs/API.md index 101c985..d0a5249 100644 --- a/docs/API.md +++ b/docs/API.md @@ -44,13 +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). +- `pdf-elements:page-change` - Emitted when the current page changes: on scroll, zoom, container resize, once page layout is known after load, and on `goToPage`. The current page is the one with the highest visible percentage (horizontal clipping included); it is kept while it stays fully visible. 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. +- `goToPage(pageIndex, docIndex = 0)` - Scrolls the page to the top of the viewer (the viewer itself, its nearest scrollable ancestor, or the window) and makes it the current page. Zero-based indices. Returns `false` only for pages that do not exist. When the page layout is not known yet (right after load) the request is kept and runs as soon as it is, the latest request winning; page dimensions come from the PDF.js viewport, so it does not wait for canvas rendering. +- `getCurrentPage()` - Returns `{ docIndex, pageIndex }` for the current page (see `pdf-elements:page-change`), or `null` while no page layout is known 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/e2e/fixtures/mixed-pages.pdf b/e2e/fixtures/mixed-pages.pdf new file mode 100644 index 0000000000000000000000000000000000000000..031ee317f016f650dd1bade32f4146d5b3ab26f4 GIT binary patch literal 1683 zcmbVNO>dh(5WVv&=3=Qmq`S-R0+ym2oW`ouR*f8PQ4gDV?GU+8!MdXT^_^Layapw* zK^EA%Pa9oMFKcfPp{GSHL(2eZwu_!IJ2v^!0ye~HV~u33T|#9Tdv8G zexDxb{MgrG-N2*v?y0}e{asLq6$nX>pNL=WO9wiDq&KIK%L-lC!~V&6N<>TmTbRan zZ@$>wAM1)|6QHO7<(n;KR{_bkcUp(;vk|)fV}7nPT7Vx-g5Xg-4G5hzW@4b(ap^8X%%8U@O~H z`}!GEOu6^E{1*W}Q^>sg^odV`=;!IcBwwZB#ogyB051|7DVs$ zrQ`ZZc_^RY{8&DT@+9YN%=w%0s2wkrhnUzZJd{T~C&&}j4So1t-}(Ki&gf4+X?=)p zm?t%;r#eMqxEtP)m|$P}3B=4EOQ=yH)|9vEof`Tra;Zc@1w;+2h+{dajBRZ<5eK0n z1U+1kXe~8t;Aq2MqYKKTO=IH>Y(n8~9N1#2;=m^P7*Aoup`XU#7}^p&KAUQs(LszX z!;B1U^K8ULh%pxt^FW)cO|i4J|3`T!{^4p>xa_LR;f|%0`;BaB=QAm!OrzQC?#D9v E4`6MsX8-^I literal 0 HcmV?d00001 diff --git a/e2e/page-navigation.spec.ts b/e2e/page-navigation.spec.ts new file mode 100644 index 0000000..cb15b63 --- /dev/null +++ b/e2e/page-navigation.spec.ts @@ -0,0 +1,125 @@ +// SPDX-FileCopyrightText: 2026 LibreCode coop and contributors +// SPDX-License-Identifier: AGPL-3.0-or-later + +import path from "node:path"; +import { test, expect, type Page } from "@playwright/test"; + +// 5 pages with different sizes and orientations (portrait, landscape, small, portrait, wide). +const fixture = path.resolve("e2e/fixtures/mixed-pages.pdf"); +const SAMPLE_URL = "https://mozilla.github.io/pdf.js/web/compressed.tracemonkey-pldi-09.pdf"; + +async function loadFixture(page: Page) { + await page.route(SAMPLE_URL, (route) => route.fulfill({ + path: fixture, + contentType: "application/pdf", + headers: { "access-control-allow-origin": "*" }, + })); + await page.goto("/"); + await page.getByRole("button", { name: "Load sample PDF" }).click(); + await expect(page.locator(".page-wrapper")).toHaveCount(5); + await expect(page.getByTestId("current-page")).toHaveText("Document 1 · Page 1"); +} + +/** Public API of the mounted viewer, as a host would call it. */ +const goToPage = (page: Page, pageIndex: number, docIndex = 0) => page.evaluate( + ([p, d]) => { + const root = document.querySelector(".pdf-elements-root") as any; + return root.__vueParentComponent.proxy.goToPage(p, d) as boolean; + }, + [pageIndex, docIndex], +); + +/** + * Geometry of a page relative to what the user can see. The demo viewer grows with + * its content, so the window scrolls; a host with a fixed height scrolls the viewer. + */ +const pageInViewport = (page: Page, wrapperIndex: number) => page.evaluate((i) => { + const root = document.querySelector(".pdf-elements-root") as HTMLElement; + const scrolls = root.scrollHeight > root.clientHeight + 1; + const top = scrolls ? root.getBoundingClientRect().top : 0; + const height = scrolls ? root.clientHeight : window.innerHeight; + const rect = (document.querySelectorAll(".page-wrapper")[i] as HTMLElement).getBoundingClientRect(); + return { top: rect.top - top, bottom: rect.bottom - top, viewHeight: height }; +}, wrapperIndex); + +const offsetFromTop = async (page: Page, wrapperIndex: number) => (await pageInViewport(page, wrapperIndex)).top; + +const scrollToStart = (page: Page) => page.evaluate(() => { + const root = document.querySelector(".pdf-elements-root") as HTMLElement; + root.scrollTop = 0; + window.scrollTo(0, 0); +}); + +const currentPage = (page: Page) => page.getByTestId("current-page"); + +test.describe("page navigation", () => { + test("goToPage scrolls pages of different sizes and orientations to the top", async ({ page }) => { + await loadFixture(page); + + for (const [pageIndex, label] of [[1, "Page 2"], [2, "Page 3"], [3, "Page 4"]] as const) { + expect(await goToPage(page, pageIndex)).toBe(true); + await expect(currentPage(page)).toHaveText(`Document 1 · ${label}`); + expect(Math.abs(await offsetFromTop(page, pageIndex))).toBeLessThan(2); + } + + expect(await goToPage(page, 0)).toBe(true); + await expect(currentPage(page)).toHaveText("Document 1 · Page 1"); + }); + + test("the last page becomes current even when it cannot reach the top", async ({ page }) => { + await loadFixture(page); + expect(await goToPage(page, 4)).toBe(true); + await expect(currentPage(page)).toHaveText("Document 1 · Page 5"); + }); + + test("rejects pages that do not exist", async ({ page }) => { + await loadFixture(page); + expect(await goToPage(page, 5)).toBe(false); + expect(await goToPage(page, -1)).toBe(false); + expect(await goToPage(page, 0, 1)).toBe(false); + await expect(currentPage(page)).toHaveText("Document 1 · Page 1"); + }); + + test("follows scrolling and keeps the navigated page current after a resize", async ({ page }) => { + await loadFixture(page); + expect(await goToPage(page, 2)).toBe(true); + await expect(currentPage(page)).toHaveText("Document 1 · Page 3"); + + await page.setViewportSize({ width: 700, height: 500 }); + await expect(currentPage(page)).toHaveText(/Document 1 · Page \d/); + const shown = Number((await currentPage(page).innerText()).match(/Page (\d)/)![1]) - 1; + const rect = await pageInViewport(page, shown); + // whatever page is reported must really be on screen + expect(rect.bottom).toBeGreaterThan(0); + expect(rect.top).toBeLessThan(rect.viewHeight); + + await scrollToStart(page); + await expect(currentPage(page)).toHaveText("Document 1 · Page 1"); + }); + + test("stays consistent after zooming", async ({ page }) => { + await loadFixture(page); + expect(await goToPage(page, 1)).toBe(true); + await expect(currentPage(page)).toHaveText("Document 1 · Page 2"); + + await page.evaluate(() => { + const root = document.querySelector(".pdf-elements-root") as any; + root.__vueParentComponent.proxy.commitZoom(0.5); + }); + // geometry is re-reserved from the PDF.js viewport: the page is still reachable at the top + expect(await goToPage(page, 3)).toBe(true); + await expect(currentPage(page)).toHaveText("Document 1 · Page 4"); + expect(Math.abs(await offsetFromTop(page, 3))).toBeLessThan(2); + }); + + test("navigates across multiple documents", async ({ page }) => { + await loadFixture(page); + await page.locator('input[type="file"]').setInputFiles(fixture); + await expect(page.locator(".page-wrapper")).toHaveCount(10); + + expect(await goToPage(page, 1, 1)).toBe(true); + await expect(currentPage(page)).toHaveText("Document 2 · Page 2"); + expect(Math.abs(await offsetFromTop(page, 6))).toBeLessThan(2); + expect(await goToPage(page, 0, 2)).toBe(false); + }); +}); diff --git a/examples/basic/App.vue b/examples/basic/App.vue index 047614f..943c1bf 100644 --- a/examples/basic/App.vue +++ b/examples/basic/App.vue @@ -20,6 +20,10 @@ SPDX-License-Identifier: AGPL-3.0-or-later +

+ Document {{ currentPage.docIndex + 1 }} · Page {{ currentPage.pageIndex + 1 }} +

+