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 6e3fe7e..d0a5249 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 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 (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 0000000..031ee31
Binary files /dev/null and b/e2e/fixtures/mixed-pages.pdf differ
diff --git a/e2e/page-navigation.spec.ts b/e2e/page-navigation.spec.ts
new file mode 100644
index 0000000..226e9a2
--- /dev/null
+++ b/e2e/page-navigation.spec.ts
@@ -0,0 +1,154 @@
+// 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 to the right page when zoom and goToPage run in the same tick", async ({ page }) => {
+ await loadFixture(page);
+ const accepted = await page.evaluate(() => {
+ const proxy = (document.querySelector(".pdf-elements-root") as any).__vueParentComponent.proxy;
+ proxy.commitZoom(0.5);
+ return proxy.goToPage(2) as boolean;
+ });
+ expect(accepted).toBe(true);
+
+ // The request waits for the pages to re-reserve their size, then lands on the new layout.
+ await expect(currentPage(page)).toHaveText("Document 1 · Page 3");
+ await expect.poll(async () => Math.abs(await offsetFromTop(page, 2))).toBeLessThan(2);
+ // ...and stays there once the zoomed pages finish rendering.
+ await page.waitForTimeout(1000);
+ await expect(currentPage(page)).toHaveText("Document 1 · Page 3");
+ });
+
+ test("applies a navigation requested while the viewer is hidden once it is shown", async ({ page }) => {
+ await loadFixture(page);
+ const viewer = page.locator(".viewer");
+ await viewer.evaluate((el) => { (el as HTMLElement).style.display = "none"; });
+ // e.g. the viewer sits in an inactive tab: the request is accepted but there is no layout yet
+ expect(await goToPage(page, 2)).toBe(true);
+ await viewer.evaluate((el) => { (el as HTMLElement).style.display = ""; });
+
+ await expect(currentPage(page)).toHaveText("Document 1 · Page 3");
+ await expect.poll(async () => Math.abs(await offsetFromTop(page, 2))).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 }}
+
+
,
+ _pageEntries: markRaw([]) as Array<{ docIndex: number; pageIndex: number }>,
+ _pageEntryIndex: markRaw({}) as Record
,
+ _pageEntriesSource: null as unknown,
lastClientWidth: 0,
nextObjectCounter: 0,
isDraggingElement: false,
@@ -303,6 +313,19 @@ export default defineComponent({
window.addEventListener('scroll', this.onViewportScroll, { passive: true })
window.addEventListener('resize', this.onViewportScroll)
this.$el?.addEventListener('scroll', this.onViewportScroll, { passive: true })
+ // `scroll` does not bubble: capture it to follow a scrollable ancestor hosting the viewer.
+ window.addEventListener('scroll', this.onAncestorScroll, { passive: true, capture: true })
+ if (typeof ResizeObserver !== 'undefined' && this.$el) {
+ this.resizeObserver = markRaw(new ResizeObserver(() => {
+ // Also fires when a hidden viewer (e.g. in an inactive tab) becomes visible.
+ this.flushPendingNavigation()
+ this.scheduleCurrentPageUpdate()
+ }))
+ this.resizeObserver.observe(this.$el)
+ for (let el = this.$el.parentElement; el && el !== document.body; el = el.parentElement) {
+ this.resizeObserver.observe(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 })
@@ -332,12 +355,21 @@ export default defineComponent({
}
this.detachAddingListeners()
window.removeEventListener('scroll', this.onViewportScroll)
+ window.removeEventListener('scroll', this.onAncestorScroll, { capture: true })
window.removeEventListener('resize', this.onViewportScroll)
this.$el?.removeEventListener('scroll', this.onViewportScroll)
if (this.viewportRafId) {
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
+ }
if (this.hoverRafId) {
window.cancelAnimationFrame(this.hoverRafId)
this.hoverRafId = 0
@@ -409,11 +441,15 @@ export default defineComponent({
this.pdfDocuments = docs
this._pageMeasurementCache = markRaw({})
+ this._geometryReady = markRaw({})
+ this.currentVisiblePage = null
+ this.pendingNavigation = 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()
}
@@ -780,6 +816,13 @@ export default defineComponent({
return pageComponent ? (pageComponent.$el || pageComponent) : null
},
+ onAncestorScroll(event) {
+ const target = event?.target
+ if (target && target !== this.$el && target !== document && target.contains?.(this.$el)) {
+ this.onViewportScroll()
+ }
+ },
+
onViewportScroll() {
if (this.viewportRafId) return
this.viewportRafId = window.requestAnimationFrame(() => {
@@ -802,10 +845,230 @@ 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
+ },
+
+ /** Ordered list of every page, rebuilt only when the document set changes. */
+ getPageEntries() {
+ if (this._pageEntriesSource !== this.pdfDocuments) {
+ const entries = []
+ const index = {}
+ this.pdfDocuments.forEach((doc, docIndex) => {
+ for (let pageIndex = 0; pageIndex < doc.pages.length; pageIndex++) {
+ index[`${docIndex}-${pageIndex}`] = entries.length
+ entries.push({ docIndex, pageIndex })
+ }
+ })
+ this._pageEntries = markRaw(entries)
+ this._pageEntryIndex = markRaw(index)
+ this._pageEntriesSource = this.pdfDocuments
+ }
+ return this._pageEntries
+ },
+
+ isPageGeometryReady(docIndex, pageIndex) {
+ return this._geometryReady[`${docIndex}-${pageIndex}`] === this.scale
+ },
+
+ isLayoutComplete() {
+ return this.getPageEntries().every((entry) => this.isPageGeometryReady(entry.docIndex, entry.pageIndex))
+ },
+
+ /** A page's position depends on every page before it, so all of them need their geometry. */
+ isNavigationReady(docIndex, pageIndex) {
+ const entries = this.getPageEntries()
+ const last = this._pageEntryIndex[`${docIndex}-${pageIndex}`]
+ for (let i = 0; i <= last; i++) {
+ if (!this.isPageGeometryReady(entries[i].docIndex, entries[i].pageIndex)) return false
+ }
+ return true
+ },
+
+ /**
+ * The element that actually scrolls the pages: the viewer itself when it has a
+ * bounded height, otherwise the nearest scrollable ancestor, or the window (null).
+ */
+ getScrollContainer() {
+ const root = this.$el
+ if (!root) return null
+ let el = root
+ while (el && el !== document.body && el !== document.documentElement) {
+ const scrollable = el === root || /(auto|scroll)/.test(window.getComputedStyle(el).overflowY)
+ if (scrollable && el.scrollHeight > el.clientHeight + 1) return el
+ el = el.parentElement
+ }
+ return null
+ },
+
+ getScrollViewport(container) {
+ if (container) {
+ const rect = container.getBoundingClientRect()
+ return { top: rect.top, left: rect.left, width: container.clientWidth || 0, height: container.clientHeight || 0, scrollTop: container.scrollTop || 0 }
+ }
+ return { top: 0, left: 0, width: window.innerWidth || 0, height: window.innerHeight || 0, scrollTop: window.scrollY || 0 }
+ },
+
+ /** The PDF page box only: the wrapper also holds the footer, which is not page content. */
+ getPageBoundsElement(docIndex, pageIndex) {
+ return this.getPageCanvasElement(docIndex, pageIndex) || this.getPageWrapperElement(docIndex, pageIndex)
+ },
+
+ getPageViewportRect(docIndex, pageIndex, containerRect) {
+ const element = this.getPageBoundsElement(docIndex, pageIndex)
+ if (!element?.getBoundingClientRect) return null
+ const rect = element.getBoundingClientRect()
+ return {
+ docIndex,
+ pageIndex,
+ top: rect.top - containerRect.top,
+ bottom: rect.bottom - containerRect.top,
+ left: (rect.left ?? 0) - (containerRect.left ?? 0),
+ right: (rect.right ?? rect.left ?? 0) - (containerRect.left ?? 0),
+ }
+ },
+
+ getCurrentPage() {
+ if (!this.$el?.getBoundingClientRect) return null
+ const entries = this.getPageEntries()
+ if (!entries.length) return null
+ const containerRect = this.getScrollViewport(this.getScrollContainer())
+ const viewHeight = containerRect.height
+ const viewWidth = containerRect.width
+ const rectAt = (i) => this.getPageViewportRect(entries[i].docIndex, entries[i].pageIndex, containerRect)
+
+ // 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 ? (this._pageEntryIndex[`${known.docIndex}-${known.pageIndex}`] ?? 0) : 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
+ if (this.isPageGeometryReady(rect.docIndex, rect.pageIndex)) rects.push(rect)
+ }
+ // While the layout is unknown (e.g. right after a zoom) keep reporting the known page.
+ return findMostVisiblePage(rects, viewHeight, { viewWidth, current: known }) ?? known
+ },
+
+ setCurrentPage(page) {
+ const previous = this.currentVisiblePage
+ if (previous && previous.docIndex === page.docIndex && previous.pageIndex === page.pageIndex) return
+ this.currentVisiblePage = { docIndex: page.docIndex, pageIndex: page.pageIndex }
+ this.$emit('pdf-elements:page-change', { docIndex: page.docIndex, pageIndex: page.pageIndex })
+ },
+
+ updateCurrentPage() {
+ const page = this.getCurrentPage()
+ if (page) this.setCurrentPage(page)
+ },
+
+ scheduleCurrentPageUpdate() {
+ if (this.currentPageRafId) return
+ this.currentPageRafId = window.requestAnimationFrame(() => {
+ this.currentPageRafId = 0
+ this.flushPendingNavigation()
+ this.updateCurrentPage()
+ })
+ },
+
+ onGeometry(docIndex, pageIndex, e) {
+ if (docIndex < 0 || docIndex >= this.pdfDocuments.length) return
+ this._geometryReady[`${docIndex}-${pageIndex}`] = e?.scale ?? this.scale
+ this.flushPendingNavigation()
+ this.scheduleCurrentPageUpdate()
+ },
+
+ flushPendingNavigation() {
+ const target = this.pendingNavigation
+ if (!target || !this.isViewerVisible() || !this.isNavigationReady(target.docIndex, target.pageIndex)) return
+ this.settleNavigation(target, this.scrollToPage(target.docIndex, target.pageIndex))
+ },
+
+ /** A viewer inside `display: none` (e.g. a hidden tab) has no layout to scroll. */
+ isViewerVisible() {
+ const el = this.$el
+ return typeof el?.checkVisibility === 'function' ? el.checkVisibility() : true
+ },
+
+ /** Whether the page is aligned with the top of the scroll viewport (within a pixel). */
+ isPageAtTop(docIndex, pageIndex) {
+ const wrapper = this.getPageWrapperElement(docIndex, pageIndex)
+ if (!wrapper?.getBoundingClientRect) return false
+ const viewport = this.getScrollViewport(this.getScrollContainer())
+ return Math.abs(wrapper.getBoundingClientRect().top - viewport.top) <= 1
+ },
+
+ /**
+ * A request that could not reach the page (scroll range clamped while later pages are
+ * still unknown) is kept to be corrected once they grow. One that got there is done,
+ * so later geometry reports never undo a scroll made by the user.
+ */
+ settleNavigation(target, scrolled) {
+ const keep = scrolled && !this.isLayoutComplete() && !this.isPageAtTop(target.docIndex, target.pageIndex)
+ // The request may have been replaced meanwhile (e.g. by a page-change listener).
+ if (!keep && this.pendingNavigation === target) this.pendingNavigation = null
+ },
+
+ scrollToPage(docIndex, pageIndex) {
+ const wrapper = this.getPageWrapperElement(docIndex, pageIndex)
+ if (!this.$el?.getBoundingClientRect || !wrapper?.getBoundingClientRect) return false
+ const container = this.getScrollContainer()
+ const viewport = this.getScrollViewport(container)
+ const top = Math.max(0, viewport.scrollTop + wrapper.getBoundingClientRect().top - viewport.top)
+ // Instant, so `scroll-behavior: smooth` on the host cannot defer the scroll.
+ const target = container || window
+ if (typeof target.scrollTo === 'function') {
+ target.scrollTo({ top, behavior: 'instant' })
+ } else if (container) {
+ container.scrollTop = top
+ }
+ // Explicit navigation makes the page current; it stays current while fully visible.
+ this.setCurrentPage({ docIndex, pageIndex })
+ return true
+ },
+
+ /**
+ * Scrolls the page to the top of the viewer. Valid requests are never dropped:
+ * when the layout is not known yet, the latest request runs as soon as it is.
+ */
+ goToPage(pageIndex, docIndex = 0) {
+ if (!Number.isInteger(docIndex) || docIndex < 0) return false
+ const doc = this.pdfDocuments[docIndex]
+ if (!doc || !Number.isInteger(pageIndex) || pageIndex < 0 || pageIndex >= doc.pages.length) return false
+ this.getPageEntries()
+ // markRaw keeps the object identity, so it can be told apart from a newer request.
+ const request = markRaw({ docIndex, pageIndex })
+ this.pendingNavigation = request
+ if (!this.isNavigationReady(docIndex, pageIndex)) return true
+ if (!this.isViewerVisible()) {
+ // Shown again before the resize observer reports it: retry on the next frame.
+ this.scheduleCurrentPageUpdate()
+ return true
+ }
+ const scrolled = this.scrollToPage(docIndex, pageIndex)
+ this.settleNavigation(request, scrolled)
+ return scrolled
+ },
+
handleMouseMove(event) {
if (event?.touches?.length > 1 || this.isPinching) return
if (!this.isAddingMode || !this.previewElement) return
@@ -1348,7 +1611,9 @@ export default defineComponent({
onMeasure(e, docIndex, pageIndex) {
if (docIndex < 0 || docIndex >= this.pdfDocuments.length) return
this._pageMeasurementCache[`${docIndex}-${pageIndex}`] = null
+ this._geometryReady[`${docIndex}-${pageIndex}`] = e?.scale ?? this.scale
this.cachePageBoundsForPage(docIndex, pageIndex)
+ this.scheduleCurrentPageUpdate()
if (this.autoFitZoom) {
this.scheduleAutoFitZoom()
}
@@ -1418,10 +1683,16 @@ export default defineComponent({
))
}
- const optimalScale = this.calculateOptimalScale(maxCanvasWidth)
+ // Compare the scale that will really be applied: below the minimum zoom nothing changes.
+ const optimalScale = this.clampZoomScale(this.calculateOptimalScale(maxCanvasWidth))
this.autoFitApplied = true
if (Math.abs(optimalScale - this.scale) > 0.01) {
+ // A page the host navigated to must stay at the top when the fit changes the layout.
+ const current = this.currentVisiblePage
+ const pinned = current && this.isPageAtTop(current.docIndex, current.pageIndex) ? { ...current } : null
this.commitZoom(optimalScale)
+ // Never replace a request the host made in the meantime.
+ if (pinned && !this.pendingNavigation) this.pendingNavigation = pinned
}
},
},
diff --git a/src/components/PDFPage.vue b/src/components/PDFPage.vue
index c2640b8..10940c5 100644
--- a/src/components/PDFPage.vue
+++ b/src/components/PDFPage.vue
@@ -12,7 +12,7 @@ import { defineComponent, type PropType } from 'vue'
export default defineComponent({
name: 'PDFPage',
- emits: ['onMeasure'],
+ emits: ['onMeasure', 'onGeometry'],
props: {
page: {
type: Object as PropType>,
@@ -34,10 +34,12 @@ export default defineComponent({
watch: {
scale(newScale) {
this.dynamicScale = newScale
+ this.syncGeometry()
this.render()
},
},
mounted() {
+ this.syncGeometry()
this.render()
},
beforeUnmount() {
@@ -62,6 +64,32 @@ export default defineComponent({
scale: this.dynamicScale,
})
},
+ /**
+ * Reserves the page dimensions from the PDF.js viewport, independently of
+ * the (slower) canvas render task, so layout and navigation do not wait for it.
+ */
+ async syncGeometry() {
+ const _page = await this.page
+ const canvas = this.$refs.canvas
+ if (!canvas) return
+ const viewport = _page.getViewport({ scale: this.dynamicScale })
+ const width = Math.floor(viewport.width)
+ const height = Math.floor(viewport.height)
+ // Assigning a size clears the canvas (and resets its context), which would
+ // corrupt a render still painting: cancel it, a new one is already queued.
+ if (canvas.width !== width || canvas.height !== height) {
+ if (this.renderTask) {
+ try {
+ this.renderTask.cancel()
+ } catch {
+ // Ignore render cancellation errors.
+ }
+ }
+ canvas.width = width
+ canvas.height = height
+ }
+ this.$emit('onGeometry', { scale: this.dynamicScale })
+ },
async render() {
if (this.isRendering) {
this.pendingRender = true
@@ -92,7 +120,13 @@ export default defineComponent({
canvasContext: context,
viewport,
})
- await this.renderTask.promise
+ try {
+ await this.renderTask.promise
+ } catch (error) {
+ // Cancelled because the size changed; the queued render takes over.
+ if ((error as { name?: string })?.name === 'RenderingCancelledException') return
+ throw error
+ }
this.measure()
} finally {
this.isRendering = false
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..3687bf4 100644
--- a/src/utils/pageBounds.ts
+++ b/src/utils/pageBounds.ts
@@ -11,3 +11,74 @@ 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
+ /** Left edge relative to the left of the scroll viewport. */
+ left?: number
+ /** Right edge relative to the left of the scroll viewport. */
+ right?: number
+}
+
+export interface MostVisiblePageOptions {
+ /** Viewport width, used to account for horizontal clipping when `left`/`right` are set. */
+ viewWidth?: number
+ /** Page that is current right now; it is kept while it remains fully visible. */
+ current?: { docIndex: number; pageIndex: number } | null
+}
+
+const FULLY_VISIBLE = 0.999
+/** Layout and scroll positions are rounded to device pixels: ignore up to 1px of clipping. */
+const SUBPIXEL_TOLERANCE = 1
+
+const visibleLength = (start: number, end: number, viewLength: number) => {
+ const length = end - start
+ const visible = Math.min(end, viewLength) - Math.max(start, 0)
+ return length - visible <= SUBPIXEL_TOLERANCE ? length : visible
+}
+
+/**
+ * Fraction (0..1) of the page that is inside the viewport.
+ */
+export function getVisibleRatio(rect: PageViewportRect, viewHeight: number, viewWidth?: number) {
+ const height = rect.bottom - rect.top
+ if (height <= 0) return 0
+ const visibleHeight = visibleLength(rect.top, rect.bottom, viewHeight)
+ if (visibleHeight <= 0) return 0
+ let widthRatio = 1
+ if (rect.left !== undefined && rect.right !== undefined && viewWidth !== undefined) {
+ const width = rect.right - rect.left
+ if (width <= 0) return 0
+ const visibleWidth = visibleLength(rect.left, rect.right, viewWidth)
+ if (visibleWidth <= 0) return 0
+ widthRatio = visibleWidth / width
+ }
+ return (visibleHeight / height) * widthRatio
+}
+
+/**
+ * Picks the current page like the PDF.js viewer does: the current page is kept
+ * while it is fully visible, otherwise the page with the highest visible
+ * percentage wins. Ties resolve to the first page in document order.
+ */
+export function findMostVisiblePage(rects: PageViewportRect[], viewHeight: number, options: MostVisiblePageOptions = {}) {
+ const { viewWidth, current } = options
+ let best: PageViewportRect | null = null
+ let bestRatio = 0
+ for (const rect of rects) {
+ const ratio = getVisibleRatio(rect, viewHeight, viewWidth)
+ if (current && rect.docIndex === current.docIndex && rect.pageIndex === current.pageIndex && ratio >= FULLY_VISIBLE) {
+ return { docIndex: rect.docIndex, pageIndex: rect.pageIndex }
+ }
+ if (ratio > bestRatio) {
+ best = rect
+ bestRatio = ratio
+ }
+ }
+ 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..7372d42 100644
--- a/tests/components/PDFElements.spec.ts
+++ b/tests/components/PDFElements.spec.ts
@@ -1,8 +1,9 @@
// SPDX-FileCopyrightText: 2026 LibreCode coop and contributors
// SPDX-License-Identifier: AGPL-3.0-or-later
-import { describe, it, expect, vi } from 'vitest'
-import { shallowMount } from '@vue/test-utils'
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import { mount, shallowMount, flushPromises } from '@vue/test-utils'
+import { markRaw } from 'vue'
import PDFElements from '../../src/components/PDFElements.vue'
const makeDoc = () => ({
@@ -918,3 +919,474 @@ describe('PDFElements business rules', () => {
rafSpy.mockRestore()
})
})
+
+describe('PDFElements page navigation', () => {
+ type Box = { top: number; height: number; left?: number; width?: number; footer?: number }
+ // boxes[docIndex][pageIndex]: absolute layout of each page wrapper
+ const setup = (boxes: Box[][], { maxScroll = Infinity, ready = true, viewHeight = 500, viewWidth = 800 } = {}) => {
+ const { wrapper, ctx } = makeWrapper()
+ ctx.pdfDocuments = boxes.map((pages) => {
+ const doc = makeDoc()
+ doc.pages = pages.map(() => Promise.resolve())
+ return doc
+ })
+ const root = ctx.$el as HTMLElement
+ root.getBoundingClientRect = () => ({ top: 0, bottom: viewHeight, left: 0, right: viewWidth } as DOMRect)
+ // jsdom reports detached elements as not visible
+ ;(root as any).checkVisibility = () => true
+ Object.defineProperty(root, 'clientHeight', { value: viewHeight, configurable: true })
+ Object.defineProperty(root, 'clientWidth', { value: viewWidth, configurable: true })
+ Object.defineProperty(root, 'scrollHeight', { value: 100000, configurable: true })
+ let scrollTop = 0
+ Object.defineProperty(root, 'scrollTop', {
+ configurable: true,
+ get: () => scrollTop,
+ set: (value: number) => { scrollTop = Math.min(value, maxScroll) },
+ })
+ const layout = { boxes }
+ // The wrapper also holds the page footer; the page bounds are the PDF page only.
+ const elementFor = (includeFooter: boolean) => (d: number, p: number) => {
+ const box = layout.boxes[d]?.[p]
+ if (!box) return null
+ const left = box.left ?? 0
+ const width = box.width ?? viewWidth
+ return {
+ getBoundingClientRect: () => ({
+ top: box.top - scrollTop,
+ bottom: box.top + box.height + (includeFooter ? box.footer ?? 0 : 0) - scrollTop,
+ left,
+ right: left + width,
+ }),
+ }
+ }
+ ctx.getPageWrapperElement = vi.fn(elementFor(true))
+ ctx.getPageBoundsElement = vi.fn(elementFor(false))
+ const markReady = () => {
+ boxes.forEach((pages, d) => pages.forEach((_, p) => ctx.onGeometry(d, p)))
+ flushFrames()
+ }
+ if (ready) markReady()
+ return { wrapper, ctx, root, layout, markReady }
+ }
+
+ const stacked = (...heights: number[]): Box[] => {
+ let top = 0
+ return heights.map((height) => {
+ const box = { top, height }
+ top += height + 20
+ return box
+ })
+ }
+
+ let frames: FrameRequestCallback[] = []
+ const flushFrames = () => {
+ const pending = frames
+ frames = []
+ pending.forEach((cb) => cb(0))
+ }
+
+ beforeEach(() => {
+ frames = []
+ vi.spyOn(window, 'requestAnimationFrame').mockImplementation((cb: FrameRequestCallback) => {
+ frames.push(cb)
+ return frames.length
+ })
+ })
+
+ afterEach(() => {
+ vi.restoreAllMocks()
+ vi.unstubAllGlobals()
+ })
+
+ it('scrolls to the requested page and makes it current', () => {
+ const { ctx, root, wrapper } = setup([stacked(400, 400)])
+ expect(ctx.goToPage(1)).toBe(true)
+ expect(root.scrollTop).toBe(420)
+ expect(ctx.getCurrentPage()).toEqual({ docIndex: 0, pageIndex: 1 })
+ expect(wrapper.emitted('pdf-elements:page-change')).toEqual([
+ [{ docIndex: 0, pageIndex: 0 }],
+ [{ docIndex: 0, pageIndex: 1 }],
+ ])
+ })
+
+ it('resolves the page in the requested document', () => {
+ const { ctx, root } = setup([stacked(400, 400), [{ top: 900, height: 400 }, { top: 1320, height: 400 }]])
+ expect(ctx.goToPage(0, 1)).toBe(true)
+ expect(ctx.getPageWrapperElement).toHaveBeenCalledWith(1, 0)
+ expect(root.scrollTop).toBe(900)
+ expect(ctx.getCurrentPage()).toEqual({ docIndex: 1, pageIndex: 0 })
+ })
+
+ it('rejects invalid pages', () => {
+ const { ctx } = setup([stacked(400, 400)])
+ expect(ctx.goToPage(2)).toBe(false)
+ expect(ctx.goToPage(-1)).toBe(false)
+ expect(ctx.goToPage(1.5)).toBe(false)
+ expect(ctx.goToPage(0, 3)).toBe(false)
+ expect(ctx.pendingNavigation).toBeNull()
+ })
+
+ it('navigates before the pages are rendered, once their geometry is known', () => {
+ const { ctx, root, markReady } = setup([stacked(400, 400)], { ready: false })
+ expect(ctx.goToPage(1)).toBe(true)
+ expect(root.scrollTop).toBe(0)
+ ctx.onGeometry(0, 1) // the target alone is not enough: page 0 sits above it
+ expect(root.scrollTop).toBe(0)
+ markReady()
+ expect(root.scrollTop).toBe(420)
+ expect(ctx.pendingNavigation).toBeNull()
+ })
+
+ it('lets the latest pending navigation win', () => {
+ const { ctx, root, markReady } = setup([stacked(400, 400, 400)], { ready: false })
+ ctx.goToPage(2)
+ ctx.goToPage(1)
+ markReady()
+ expect(root.scrollTop).toBe(420)
+ expect(ctx.getCurrentPage()).toEqual({ docIndex: 0, pageIndex: 1 })
+ })
+
+ it('identifies a short page followed by a tall one as current after navigating to it', () => {
+ const { ctx, root } = setup([stacked(200, 800)])
+ root.scrollTop = 220
+ ctx.updateCurrentPage()
+ expect(ctx.goToPage(0)).toBe(true)
+ expect(root.scrollTop).toBe(0)
+ expect(ctx.getCurrentPage()).toEqual({ docIndex: 0, pageIndex: 0 })
+ })
+
+ it('keeps a short last page current when the scroll is clamped', () => {
+ const { ctx, root, wrapper } = setup([stacked(400, 400)], { maxScroll: 20, viewHeight: 900 })
+ 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: 0 }],
+ [{ docIndex: 0, pageIndex: 1 }],
+ ])
+ // both pages are fully visible after scrolling back: the navigated page stays current
+ root.scrollTop = 0
+ ctx.updateCurrentPage()
+ expect(ctx.getCurrentPage()).toEqual({ docIndex: 0, pageIndex: 1 })
+ })
+
+ it('accounts for horizontal clipping and mixed orientations', () => {
+ // portrait page 400 wide, landscape page 1000 wide in an 800px wide viewport
+ const { ctx, layout } = setup([[{ top: 0, height: 300, left: 0, width: 400 }, { top: 320, height: 300, left: -500, width: 1000 }]])
+ expect(ctx.getCurrentPage()).toEqual({ docIndex: 0, pageIndex: 0 })
+ layout.boxes[0][1].left = 0
+ ctx.currentVisiblePage = null
+ expect(ctx.getCurrentPage()).toEqual({ docIndex: 0, pageIndex: 0 })
+ layout.boxes[0][0] = { top: 0, height: 300, left: -380, width: 400 }
+ ctx.currentVisiblePage = null
+ expect(ctx.getCurrentPage()).toEqual({ docIndex: 0, pageIndex: 1 })
+ })
+
+ it('does not pin the target after the user scrolls away', () => {
+ const { ctx, root } = setup([stacked(400, 1200)])
+ expect(ctx.goToPage(0)).toBe(true)
+ root.scrollTop = 420
+ ctx.updateCurrentPage()
+ expect(ctx.getCurrentPage()).toEqual({ docIndex: 0, pageIndex: 1 })
+ })
+
+ it('keeps the navigated page while zoom leaves it fully visible, then follows the geometry', () => {
+ const { ctx, layout } = setup([stacked(400, 1200)])
+ expect(ctx.goToPage(0)).toBe(true)
+ layout.boxes[0] = [{ top: 0, height: 200 }, { top: 220, height: 600 }]
+ ctx.updateCurrentPage()
+ expect(ctx.getCurrentPage()).toEqual({ docIndex: 0, pageIndex: 0 })
+ layout.boxes[0] = [{ top: 0, height: 800 }, { top: 820, height: 600 }]
+ ctx.updateCurrentPage()
+ expect(ctx.getCurrentPage()).toEqual({ docIndex: 0, pageIndex: 0 })
+ })
+
+ 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 { wrapper, ctx, root } = setup([stacked(400, 400)], { viewHeight: 450 })
+ expect(observers).toHaveLength(1)
+ root.scrollTop = 100
+ ctx.updateCurrentPage()
+ Object.defineProperty(root, 'clientHeight', { value: 800, configurable: true })
+ observers[0]()
+ flushFrames()
+ expect(wrapper.emitted('pdf-elements:page-change')).toEqual([
+ [{ docIndex: 0, pageIndex: 0 }],
+ [{ docIndex: 0, pageIndex: 1 }],
+ ])
+ wrapper.unmount()
+ expect(disconnect).toHaveBeenCalled()
+ })
+
+ it('emits page-change only when the visible page changes', () => {
+ const { wrapper, ctx, root } = setup([stacked(400, 400)])
+ ctx.updateCurrentPage()
+ ctx.updateCurrentPage()
+ root.scrollTop = 420
+ 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 geometry is known', () => {
+ const { wrapper, ctx } = setup([stacked(400, 400)], { ready: false })
+ ctx.updateCurrentPage()
+ expect(wrapper.emitted('pdf-elements:page-change')).toBeUndefined()
+ ctx.onGeometry(0, 0)
+ flushFrames()
+ expect(wrapper.emitted('pdf-elements:page-change')).toEqual([[{ docIndex: 0, pageIndex: 0 }]])
+ })
+
+ it('only reads pages around the viewport', () => {
+ const { ctx, root } = setup([stacked(...Array.from({ length: 200 }, () => 400))])
+ root.scrollTop = 420 * 100
+ ctx.updateCurrentPage()
+ ctx.getPageBoundsElement.mockClear()
+ root.scrollTop = 420 * 101
+ expect(ctx.getCurrentPage()).toEqual({ docIndex: 0, pageIndex: 101 })
+ expect(ctx.getPageBoundsElement.mock.calls.length).toBeLessThan(10)
+ })
+
+ it('does not count the page footer as visible page area', () => {
+ // Page 0 is 100px high plus a 50px footer; scrolled by 100px only the footer is on screen.
+ const { ctx, root } = setup([[{ top: 0, height: 100, footer: 50 }, { top: 170, height: 2000 }]])
+ root.scrollTop = 100
+ expect(ctx.getCurrentPage()).toEqual({ docIndex: 0, pageIndex: 1 })
+ })
+
+ it('navigates with the new layout when zoom and goToPage run in the same tick', () => {
+ const { wrapper, ctx, root, layout } = setup([stacked(400, 400, 400)])
+ vi.spyOn(ctx, 'cachePageBounds').mockImplementation(() => {})
+ ctx.commitZoom(0.5)
+ expect(ctx.goToPage(2)).toBe(true)
+ // The pages have not re-reserved their size for the new scale yet: nothing scrolled.
+ expect(root.scrollTop).toBe(0)
+ layout.boxes[0] = stacked(200, 200, 200)
+ layout.boxes[0].forEach((_, p) => ctx.onGeometry(0, p))
+ expect(root.scrollTop).toBe(440)
+ expect(ctx.getCurrentPage()).toEqual({ docIndex: 0, pageIndex: 2 })
+ const events = wrapper.emitted('pdf-elements:page-change') ?? []
+ expect(events[events.length - 1]).toEqual([{ docIndex: 0, pageIndex: 2 }])
+ })
+
+ it('ignores a render finished for an older scale when checking geometry', () => {
+ const { ctx } = setup([stacked(400, 400)])
+ vi.spyOn(ctx, 'cachePageBounds').mockImplementation(() => {})
+ vi.spyOn(ctx, 'cachePageBoundsForPage').mockImplementation(() => {})
+ const initialScale = ctx.scale
+ ctx.commitZoom(0.5)
+ ctx.onMeasure({ scale: initialScale }, 0, 0)
+ expect(ctx.isPageGeometryReady(0, 0)).toBe(false)
+ ctx.onMeasure({ scale: 0.5 }, 0, 0)
+ expect(ctx.isPageGeometryReady(0, 0)).toBe(true)
+ })
+
+ it('rejects document indices that are not integers', () => {
+ const { ctx } = setup([stacked(400, 400)])
+ expect(ctx.goToPage(0, '0' as unknown as number)).toBe(false)
+ expect(ctx.goToPage(0, 'length' as unknown as number)).toBe(false)
+ expect(ctx.goToPage(0, 0.5)).toBe(false)
+ })
+
+ it('stays ready when the scale returns to the one the pages already reserved', () => {
+ const { ctx } = setup([stacked(400, 400)])
+ vi.spyOn(ctx, 'cachePageBounds').mockImplementation(() => {})
+ const initialScale = ctx.scale
+ ctx.commitZoom(0.5)
+ ctx.commitZoom(initialScale)
+ expect(ctx.goToPage(1)).toBe(true)
+ expect(ctx.pendingNavigation).toBeNull()
+ expect(ctx.getCurrentPage()).toEqual({ docIndex: 0, pageIndex: 1 })
+ })
+
+ it('does not trust a geometry report made for another scale', () => {
+ const { ctx } = setup([stacked(400, 400)], { ready: false })
+ ctx.onGeometry(0, 0, { scale: ctx.scale + 1 })
+ expect(ctx.isPageGeometryReady(0, 0)).toBe(false)
+ ctx.onGeometry(0, 0, { scale: ctx.scale })
+ expect(ctx.isPageGeometryReady(0, 0)).toBe(true)
+ })
+
+ it('keeps the request until the whole layout is known and corrects an early clamp', () => {
+ // The scroll range is still too short to reach page 1 (clamped at 100).
+ const { ctx } = setup([stacked(400, 400, 400)], { ready: false, maxScroll: 100 })
+ const scrollSpy = vi.spyOn(ctx, 'scrollToPage')
+ ctx.onGeometry(0, 0)
+ ctx.onGeometry(0, 1)
+ expect(ctx.goToPage(1)).toBe(true)
+ expect(scrollSpy).toHaveBeenCalledTimes(1)
+ // the last page is still unknown, so the scroll range may still grow
+ expect(ctx.pendingNavigation).toEqual({ docIndex: 0, pageIndex: 1 })
+ ctx.onGeometry(0, 2)
+ expect(scrollSpy).toHaveBeenCalledTimes(2)
+ expect(ctx.pendingNavigation).toBeNull()
+ })
+
+ it('drops a request that reached its page so late geometry never undoes a user scroll', () => {
+ const { ctx, root } = setup([stacked(400, 400, 400)], { ready: false })
+ ctx.onGeometry(0, 0)
+ ctx.onGeometry(0, 1)
+ expect(ctx.goToPage(1)).toBe(true)
+ expect(root.scrollTop).toBe(420)
+ expect(ctx.pendingNavigation).toBeNull()
+ root.scrollTop = 0
+ ctx.onGeometry(0, 2)
+ expect(root.scrollTop).toBe(0)
+ })
+
+ it('keeps the navigated page at the top when auto-fit changes the zoom', () => {
+ const { ctx } = setup([stacked(400, 400)])
+ vi.spyOn(ctx, 'cachePageBounds').mockImplementation(() => {})
+ vi.spyOn(ctx, 'calculateOptimalScale').mockReturnValue(0.5)
+ expect(ctx.goToPage(1)).toBe(true)
+ ctx.adjustZoomToFit(true)
+ expect(ctx.pendingNavigation).toEqual({ docIndex: 0, pageIndex: 1 })
+ })
+
+ it('does not pin the page when the auto-fit scale is below the minimum zoom and nothing changes', () => {
+ const { ctx } = setup([stacked(400, 400)])
+ vi.spyOn(ctx, 'cachePageBounds').mockImplementation(() => {})
+ ctx.commitZoom(0.5)
+ ctx.onGeometry(0, 0)
+ ctx.onGeometry(0, 1)
+ expect(ctx.goToPage(1)).toBe(true)
+ vi.spyOn(ctx, 'calculateOptimalScale').mockReturnValue(0.457)
+ ctx.adjustZoomToFit(true)
+ expect(ctx.pendingNavigation).toBeNull()
+ })
+
+ it('does not replace a newer request with the auto-fit pin', () => {
+ const { ctx } = setup([stacked(400, 400, 400)])
+ vi.spyOn(ctx, 'cachePageBounds').mockImplementation(() => {})
+ vi.spyOn(ctx, 'calculateOptimalScale').mockReturnValue(0.6)
+ expect(ctx.goToPage(1)).toBe(true)
+ ctx.pendingNavigation = { docIndex: 0, pageIndex: 2 }
+ ctx.adjustZoomToFit(true)
+ expect(ctx.pendingNavigation).toEqual({ docIndex: 0, pageIndex: 2 })
+ })
+
+ it('keeps a request made by a page-change listener while the navigation lands', () => {
+ const { ctx } = setup([stacked(400, 400, 400)], { ready: false })
+ ctx.onGeometry(0, 0)
+ ctx.onGeometry(0, 1)
+ const setCurrentPage = ctx.setCurrentPage.bind(ctx)
+ let reentered = false
+ vi.spyOn(ctx, 'setCurrentPage').mockImplementation((page: { docIndex: number; pageIndex: number }) => {
+ setCurrentPage(page)
+ if (!reentered) {
+ reentered = true
+ ctx.goToPage(2)
+ }
+ })
+ expect(ctx.goToPage(1)).toBe(true)
+ expect(ctx.pendingNavigation).toEqual({ docIndex: 0, pageIndex: 2 })
+ })
+
+ it('keeps a request made while the viewer is hidden and applies it once it is visible', () => {
+ const observers: Array<() => void> = []
+ vi.stubGlobal('ResizeObserver', class {
+ constructor(cb: () => void) { observers.push(cb) }
+ observe() {}
+ disconnect() {}
+ })
+ const { ctx, root } = setup([stacked(400, 400, 400)])
+ let visible = false
+ ;(root as any).checkVisibility = () => visible
+ expect(ctx.goToPage(2)).toBe(true)
+ expect(root.scrollTop).toBe(0)
+ expect(ctx.pendingNavigation).toEqual({ docIndex: 0, pageIndex: 2 })
+ visible = true
+ observers[0]()
+ expect(root.scrollTop).toBe(840)
+ expect(ctx.getCurrentPage()).toEqual({ docIndex: 0, pageIndex: 2 })
+ expect(ctx.pendingNavigation).toBeNull()
+ })
+
+ it('applies a request made while hidden on the next frame when the viewer is shown again quickly', () => {
+ const { ctx, root } = setup([stacked(400, 400, 400)])
+ let visible = false
+ ;(root as any).checkVisibility = () => visible
+ expect(ctx.goToPage(2)).toBe(true)
+ visible = true
+ flushFrames()
+ expect(root.scrollTop).toBe(840)
+ expect(ctx.pendingNavigation).toBeNull()
+ })
+
+ it('keeps the current page when asked right after a zoom, before the pages report their size', () => {
+ const { ctx } = setup([stacked(400, 400)])
+ vi.spyOn(ctx, 'cachePageBounds').mockImplementation(() => {})
+ expect(ctx.goToPage(1)).toBe(true)
+ ctx.commitZoom(0.5)
+ expect(ctx.getCurrentPage()).toEqual({ docIndex: 0, pageIndex: 1 })
+ })
+})
+
+describe('PDFElements with a real PDFPage', () => {
+ const makeRealPage = (width: number, height: number) => ({
+ getViewport: ({ scale }: { scale: number }) => ({ width: width * scale, height: height * scale }),
+ // The canvas render never finishes.
+ render: vi.fn(() => ({ promise: new Promise(() => {}), cancel: vi.fn() })),
+ })
+
+ it('navigates before the canvas render completes', async () => {
+ ;(HTMLCanvasElement.prototype as any).getContext = vi.fn(() => ({}))
+ const scrollTo = vi.fn()
+ vi.stubGlobal('scrollTo', scrollTo)
+ const wrapper = mount(PDFElements, {
+ props: { initFiles: [] },
+ global: { stubs: { DraggableElement: true } },
+ })
+ const ctx = wrapper.vm as any
+ ;(wrapper.element as any).checkVisibility = () => true
+ const pages = [makeRealPage(612, 792), makeRealPage(792, 612), makeRealPage(300, 200)]
+ ctx.pdfDocuments = [{
+ name: 'doc', file: null, pdfDoc: null, numPages: 3,
+ pages: markRaw(pages.map((p) => Promise.resolve(p))),
+ pageWidths: [612, 792, 300], pagesScale: [1, 1, 1],
+ allObjects: [[], [], []],
+ }]
+ await flushPromises()
+
+ expect(pages[0].render).toHaveBeenCalled()
+ expect(wrapper.findAllComponents({ name: 'PDFPage' }).some((c) => c.emitted('onMeasure'))).toBe(false)
+ expect(ctx.goToPage(2)).toBe(true)
+ expect(ctx.pendingNavigation).toBeNull()
+ expect(scrollTo).toHaveBeenCalled()
+ expect(wrapper.emitted('pdf-elements:page-change')?.slice(-1)[0]).toEqual([{ docIndex: 0, pageIndex: 2 }])
+ expect(ctx.goToPage(3)).toBe(false)
+ vi.unstubAllGlobals()
+ wrapper.unmount()
+ })
+
+ it('follows a scrollable ancestor of the viewer', async () => {
+ const host = document.createElement('div')
+ document.body.appendChild(host)
+ const wrapper = mount(PDFElements, {
+ attachTo: host,
+ props: { initFiles: [] },
+ global: { stubs: { PDFPage: true, DraggableElement: true } },
+ })
+ const raf = vi.spyOn(window, 'requestAnimationFrame').mockImplementation(() => 1)
+ host.dispatchEvent(new Event('scroll'))
+ expect(raf).toHaveBeenCalled()
+ raf.mockClear()
+ // scrolling an unrelated element does not trigger a recalculation
+ const other = document.createElement('div')
+ document.body.appendChild(other)
+ other.dispatchEvent(new Event('scroll'))
+ expect(raf).not.toHaveBeenCalled()
+ raf.mockRestore()
+ wrapper.unmount()
+ host.remove()
+ other.remove()
+ })
+})
diff --git a/tests/components/PDFPage.spec.ts b/tests/components/PDFPage.spec.ts
index d5a771e..a1a6925 100644
--- a/tests/components/PDFPage.spec.ts
+++ b/tests/components/PDFPage.spec.ts
@@ -37,6 +37,34 @@ describe('PDFPage business rules', () => {
expect(wrapper.emitted('onMeasure')?.[0][0]).toEqual({ scale: 2 })
})
+ it('reserves the page size and reports geometry before the render task finishes', async () => {
+ ;(HTMLCanvasElement.prototype as any).getContext = vi.fn(() => ({}))
+ const page = makePage()
+ page.render = vi.fn(() => ({ promise: new Promise(() => {}), cancel: vi.fn() }))
+ const wrapper = mount(PDFPage, { props: { page: Promise.resolve(page), scale: 2 } })
+
+ await flushPromises()
+
+ const canvas = wrapper.find('canvas').element as HTMLCanvasElement
+ expect(canvas.width).toBe(200)
+ expect(canvas.height).toBe(400)
+ expect(wrapper.emitted('onGeometry')?.[0][0]).toEqual({ scale: 2 })
+ expect(wrapper.emitted('onMeasure')).toBeUndefined()
+ })
+
+ it('reserves the new size when the scale changes', async () => {
+ ;(HTMLCanvasElement.prototype as any).getContext = vi.fn(() => ({}))
+ const wrapper = mount(PDFPage, { props: { page: Promise.resolve(makePage()), scale: 1 } })
+ await flushPromises()
+ await wrapper.setProps({ scale: 3 })
+ await flushPromises()
+
+ const canvas = wrapper.find('canvas').element as HTMLCanvasElement
+ expect(canvas.width).toBe(300)
+ const geometry = wrapper.emitted('onGeometry') || []
+ expect(geometry[geometry.length - 1][0]).toEqual({ scale: 3 })
+ })
+
it('reports current canvas measurement', async () => {
;(HTMLCanvasElement.prototype as any).getContext = vi.fn(() => ({}))
const page = makePage()
@@ -134,4 +162,17 @@ describe('PDFPage business rules', () => {
expect(cancel).toHaveBeenCalled()
})
+
+ it('cancels a render in flight when the page size changes', async () => {
+ ;(HTMLCanvasElement.prototype as any).getContext = vi.fn(() => ({}))
+ const cancel = vi.fn()
+ const page = makePage()
+ page.render = vi.fn(() => ({ promise: new Promise(() => {}), cancel }))
+ const wrapper = mount(PDFPage, { props: { page: Promise.resolve(page), scale: 1 } })
+ await flushPromises()
+ expect(cancel).not.toHaveBeenCalled()
+ await wrapper.setProps({ scale: 2 })
+ await flushPromises()
+ expect(cancel).toHaveBeenCalled()
+ })
})
diff --git a/tests/utils/pageBounds.spec.ts b/tests/utils/pageBounds.spec.ts
index 6f94a62..3976201 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,71 @@ 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()
+ })
+})
+
+describe('findMostVisiblePage selection rules', () => {
+ it('uses the visible percentage, not the absolute visible height', () => {
+ const rects = [
+ { docIndex: 0, pageIndex: 0, top: 0, bottom: 200 },
+ { docIndex: 0, pageIndex: 1, top: 220, bottom: 1020 },
+ ]
+ // 200px page is 100% visible, the tall page only 280/800
+ expect(findMostVisiblePage(rects, 500)).toEqual({ docIndex: 0, pageIndex: 0 })
+ })
+
+ it('keeps the current page while it is fully visible, even on a tie', () => {
+ const rects = [
+ { docIndex: 0, pageIndex: 0, top: 0, bottom: 400 },
+ { docIndex: 0, pageIndex: 1, top: 420, bottom: 820 },
+ ]
+ expect(findMostVisiblePage(rects, 900)).toEqual({ docIndex: 0, pageIndex: 0 })
+ expect(findMostVisiblePage(rects, 900, { current: { docIndex: 0, pageIndex: 1 } })).toEqual({ docIndex: 0, pageIndex: 1 })
+ })
+
+ it('stops keeping the current page once it is partially visible', () => {
+ const rects = [
+ { docIndex: 0, pageIndex: 0, top: -300, bottom: 100 },
+ { docIndex: 0, pageIndex: 1, top: 120, bottom: 520 },
+ ]
+ expect(findMostVisiblePage(rects, 500, { current: { docIndex: 0, pageIndex: 0 } })).toEqual({ docIndex: 0, pageIndex: 1 })
+ })
+
+ it('accounts for horizontal clipping', () => {
+ const rects = [
+ { docIndex: 0, pageIndex: 0, top: 0, bottom: 300, left: -350, right: 50 },
+ { docIndex: 0, pageIndex: 1, top: 320, bottom: 620, left: 0, right: 400 },
+ ]
+ expect(findMostVisiblePage(rects, 700, { viewWidth: 800 })).toEqual({ docIndex: 0, pageIndex: 1 })
+ })
+
+ it('resolves ties to the first page in document order', () => {
+ const rects = [
+ { docIndex: 0, pageIndex: 0, top: -250, bottom: 250 },
+ { docIndex: 0, pageIndex: 1, top: 250, bottom: 750 },
+ ]
+ expect(findMostVisiblePage(rects, 500)).toEqual({ docIndex: 0, pageIndex: 0 })
+ })
+
+ it('treats sub-pixel clipping as fully visible so the current page is kept', () => {
+ const rects = [
+ { docIndex: 0, pageIndex: 0, top: -0.3, bottom: 99.7 },
+ { docIndex: 0, pageIndex: 1, top: 148, bottom: 544 },
+ ]
+ expect(findMostVisiblePage(rects, 720, { current: { docIndex: 0, pageIndex: 0 } })).toEqual({ docIndex: 0, pageIndex: 0 })
+ })
+})