From 1ade94c2b14d35763cdb6d0c8314cfc8d5fd7416 Mon Sep 17 00:00:00 2001 From: John Wooten <60260750+JFWooten4@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:21:01 -0400 Subject: [PATCH 1/3] =?UTF-8?q?=F0=9F=94=A9=20Enable=20double-click=20para?= =?UTF-8?q?graph=20selection=20and=20clipboard=20copy?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Detect semantic or visually wrapped PDF paragraphs, select all their text when double-clicked, and automatically copy them with the existing Markdown setting. Respect column boundaries, preserve ordinary selection, and add focused tests. Co-authored-by: Codex Web --- package.json | 2 +- .../selection/paragraph-double-click.js | 166 ++++++++++++++++++ src/viewer/viewer.js | 2 + tests/paragraph-double-click.test.mjs | 81 +++++++++ 4 files changed, 250 insertions(+), 1 deletion(-) create mode 100644 src/viewer/selection/paragraph-double-click.js create mode 100644 tests/paragraph-double-click.test.mjs diff --git a/package.json b/package.json index 814a18e..b2a9e1f 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,7 @@ "scripts": { "build": "node scripts/build.mjs", "check": "node scripts/check-extension.mjs", - "test": "node --test tests/enhancer-setup.test.mjs tests/document-title.test.mjs tests/metadata-doi.test.mjs tests/local-file-favicon.test.mjs tests/page-tab-labels.test.mjs tests/minimap.test.mjs tests/clickable-reference-links.test.mjs tests/printed-page-jump.test.mjs tests/markdown-copy.test.mjs tests/terminal-punctuation-selection.test.mjs tests/footnote-click-copy.test.mjs tests/chatgpt-summary-popup.test.mjs tests/chatgpt-pdf-relay.test.mjs tests/selection-gaps.test.mjs" + "test": "node --test tests/enhancer-setup.test.mjs tests/document-title.test.mjs tests/metadata-doi.test.mjs tests/local-file-favicon.test.mjs tests/page-tab-labels.test.mjs tests/minimap.test.mjs tests/clickable-reference-links.test.mjs tests/printed-page-jump.test.mjs tests/markdown-copy.test.mjs tests/terminal-punctuation-selection.test.mjs tests/footnote-click-copy.test.mjs tests/chatgpt-summary-popup.test.mjs tests/chatgpt-pdf-relay.test.mjs tests/selection-gaps.test.mjs tests/paragraph-double-click.test.mjs" }, "dependencies": { "pdfjs-dist": "6.3.289", diff --git a/src/viewer/selection/paragraph-double-click.js b/src/viewer/selection/paragraph-double-click.js new file mode 100644 index 0000000..57faf0f --- /dev/null +++ b/src/viewer/selection/paragraph-double-click.js @@ -0,0 +1,166 @@ +import { markdownFromRuns } from './markdown-copy.js'; + +// PDFs position font runs rather than expose HTML paragraphs. Prefer the PDF +// semantic blocks; otherwise identify nearby lines in one visual column. +function spanItems(spans) { + return spans.flatMap((span, index) => { + const text = span.textContent || ''; + const rect = span.getBoundingClientRect(); + return text.trim() && rect.width > 0 && rect.height > 0 + ? [{ span, index, text, left: rect.left, right: rect.right, + top: rect.top, bottom: rect.bottom, height: rect.height }] : []; + }); +} + +function sameLine(line, item) { + const overlap = Math.min(line.bottom, item.bottom) - Math.max(line.top, item.top); + const verticalMatch = overlap > Math.min(line.height, item.height) * 0.5; + const gap = Math.max(line.left - item.right, item.left - line.right, 0); + return verticalMatch && gap <= Math.max(12, Math.min(line.height, item.height) * 2.2); +} + +function visualLines(items) { + const lines = []; + for (const item of [...items].sort((a, b) => a.top - b.top || a.left - b.left)) { + let line = lines.find(candidate => sameLine(candidate, item)); + if (!line) { + line = { items: [], left: item.left, right: item.right, top: item.top, + bottom: item.bottom, height: item.height }; + lines.push(line); + } + line.items.push(item); + line.left = Math.min(line.left, item.left); + line.right = Math.max(line.right, item.right); + line.top = Math.min(line.top, item.top); + line.bottom = Math.max(line.bottom, item.bottom); + line.height = line.bottom - line.top; + } + for (const line of lines) line.items.sort((a, b) => a.left - b.left || a.index - b.index); + return lines.sort((a, b) => a.top - b.top || a.left - b.left); +} + +function continuesParagraph(previous, next) { + const height = Math.max(previous.height, next.height); + const separation = next.top - previous.top; + if (separation < height * 0.55 || separation > height * 1.95) return false; + if (next.items.some(item => item.span.dataset.markdownParagraphStart === 'true')) return false; + if ([...previous.items, ...next.items].some(item => item.span.dataset.copyBlock !== undefined)) return false; + // Exclude other columns, marginalia, and differently sized headings. + if (Math.min(previous.right, next.right) - Math.max(previous.left, next.left) <= 0) return false; + if (Math.abs(next.left - previous.left) > height * 5) return false; + if (Math.max(previous.height, next.height) / Math.min(previous.height, next.height) > 1.55) return false; + // First-line indentation marks a new paragraph; dedenting a wrapped + // second line is expected. + if (next.left - previous.left > height * 1.7) return false; + // A short sentence-ending line followed by a full line at the same margin + // is often an unindented paragraph boundary. + const previousText = previous.items.map(item => item.text).join(''); + if (/[.!?][”"')\]]?\s*$/.test(previousText) && + previous.right - previous.left > height * 5 && + Math.abs(next.left - previous.left) < height * 1.2 && + previous.right < next.right - height * 3 && + previous.right - previous.left < (next.right - next.left) * 0.75) return false; + return true; +} + +export function paragraphAtSpan(spans, clickedSpan) { + const items = spanItems(spans); + const clicked = items.find(item => item.span === clickedSpan); + if (!clicked) return null; + const block = clickedSpan.dataset.copyBlock; + if (block !== undefined) { + const tagged = items.filter(item => item.span.dataset.copyBlock === block); + if (tagged.length) return { lines: visualLines(tagged), spans: tagged.map(item => item.span) }; + } + + const lines = visualLines(items); + const anchor = lines.find(line => line.items.some(item => item.span === clickedSpan)); + if (!anchor) return null; + // Do not let a parallel column interrupt this paragraph's line sequence. + const columnLines = lines.filter(line => + Math.abs(line.left - anchor.left) < Math.max(line.height, anchor.height) * 6 && + Math.min(line.right, anchor.right) > Math.max(line.left, anchor.left)); + const index = columnLines.indexOf(anchor); + let start = index, end = index; + while (start > 0 && continuesParagraph(columnLines[start - 1], columnLines[start])) start--; + while (end < columnLines.length - 1 && continuesParagraph(columnLines[end], columnLines[end + 1])) end++; + const paragraphLines = columnLines.slice(start, end + 1); + return { lines: paragraphLines, spans: paragraphLines.flatMap(line => line.items.map(item => item.span)) }; +} + +export function paragraphCopyText(lines, markdown = false) { + const runs = []; + for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) { + const items = lines[lineIndex].items; + for (let index = 0; index < items.length; index++) { + const item = items[index]; + const prior = items[index - 1]; + const gap = prior ? item.left - prior.right : 0; + runs.push({ + text: item.text, + bold: item.span.dataset.markdownBold === 'true', + italic: item.span.dataset.markdownItalic === 'true', + newLine: lineIndex > 0 && index === 0, + // The bounds are already one paragraph: reflow visual lines into + // spaces even when the source PDF is not tagged. + role: 'P', block: 'clicked-paragraph', + spaceBefore: item.span.dataset.markdownSpaceBefore === 'true' || + (prior && gap > Math.max(1, Math.min(prior.height, item.height) * 0.12)), + }); + } + } + return markdownFromRuns(runs, { markdown, reflow: true }).trim(); +} + +function selectParagraph(doc, layer, spans) { + const ordered = [...layer.querySelectorAll('[data-markdown-item]')]; + const indices = spans.map(span => ordered.indexOf(span)).filter(index => index >= 0); + if (!indices.length) return false; + const range = doc.createRange(); + range.setStartBefore(ordered[Math.min(...indices)]); + range.setEndAfter(ordered[Math.max(...indices)]); + const selection = doc.getSelection(); + if (!selection) return false; + selection.removeAllRanges(); + selection.addRange(range); + return true; +} + +export function installParagraphDoubleClick(root, markdownToggle, doc = document, view = window) { + if (!root) return; + let pendingCopy = null; + // Installed after the regular copy formatter. Override just this gesture's + // copy with visual paragraph order and optional Markdown formatting. + doc.addEventListener('copy', event => { + if (!pendingCopy || !event.clipboardData) return; + event.clipboardData.setData('text/plain', pendingCopy.text); + if (pendingCopy.markdown) event.clipboardData.setData('text/markdown', pendingCopy.text); + event.preventDefault(); + pendingCopy.handled = true; + }); + doc.addEventListener('dblclick', async event => { + if (event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey || + !event.target?.closest || event.target.closest('a, button, input, textarea, [contenteditable]')) return; + const span = event.target.closest('.text-layer [data-markdown-item]'); + if (!span || !root.contains(span)) return; + const layer = span.closest('.text-layer'); + if (!layer) return; + const paragraph = paragraphAtSpan([...layer.querySelectorAll('[data-markdown-item]')], span); + if (!paragraph || !paragraph.spans.length) return; + const markdown = markdownToggle?.checked === true; + const text = paragraphCopyText(paragraph.lines, markdown); + if (!text || !selectParagraph(doc, layer, paragraph.spans)) return; + event.preventDefault(); + pendingCopy = { text, markdown, handled: false }; + try { + let copied = false; + try { copied = doc.execCommand?.('copy') === true && pendingCopy.handled; } catch { /* blocked */ } + if (!copied) await view.navigator.clipboard.writeText(text); + view.dispatchEvent(new view.CustomEvent('pdf-viewer-toast', { detail: { message: 'Copied paragraph' } })); + } catch { + view.dispatchEvent(new view.CustomEvent('pdf-viewer-toast', { detail: { message: 'Could not copy paragraph' } })); + } finally { + pendingCopy = null; + } + }); +} diff --git a/src/viewer/viewer.js b/src/viewer/viewer.js index 75c09d0..9fe055d 100644 --- a/src/viewer/viewer.js +++ b/src/viewer/viewer.js @@ -8,6 +8,7 @@ import { resolvePdfSource } from "./pdf-source.js"; import { readResumedPage, saveResumedPage } from "./page-resume.js"; import { findSearchMatches } from "./search/search-matches.js"; import { installMarkdownCopy, markPdfTextStyles, markPdfTextStructure } from "./selection/markdown-copy.js"; +import { installParagraphDoubleClick } from "./selection/paragraph-double-click.js"; import { highlightTextLayer, registerSearchText } from "./search/search-highlight.js"; import { normalizeSearchText } from "./search/search-text.js"; import { PagePreviews } from "./page-previews.js"; @@ -1336,6 +1337,7 @@ async function downloadPdf() { function bindControls() { installMarkdownCopy(viewer, document.querySelector("#copy-as-markdown"), document, document.querySelector("#copy-tagged-paragraphs")); + installParagraphDoubleClick(viewer, document.querySelector("#copy-as-markdown")); window.addEventListener("pdf-viewer-toast", (event) => { if (typeof event.detail?.message === "string") showToast(event.detail.message); }); diff --git a/tests/paragraph-double-click.test.mjs b/tests/paragraph-double-click.test.mjs new file mode 100644 index 0000000..a6af4a1 --- /dev/null +++ b/tests/paragraph-double-click.test.mjs @@ -0,0 +1,81 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { paragraphAtSpan, paragraphCopyText, installParagraphDoubleClick } from '../src/viewer/selection/paragraph-double-click.js'; + +function span(text, x, y, width = text.length * 6, dataset = {}, height = 12) { + return { textContent: text, dataset, getBoundingClientRect: () => ({ + left: x, right: x + width, top: y, bottom: y + height, width, height, + }) }; +} + +test('selects all wrapped lines but stops at a new paragraph indent', () => { + const a = span('This is a paragraph', 20, 20, 160); + const b = span('continued on line two', 20, 35, 150); + const c = span('with a third line.', 20, 50, 140); + const d = span('A separate paragraph', 48, 65, 180); + const e = span('continues here', 20, 80, 130); + assert.deepEqual(paragraphAtSpan([a,b,c,d,e],b).spans, [a,b,c]); + assert.equal(paragraphCopyText(paragraphAtSpan([a,b,c,d,e],b).lines), + 'This is a paragraph continued on line two with a third line.'); + assert.deepEqual(paragraphAtSpan([a,b,c,d,e],e).spans, [d,e]); +}); + +test('uses semantic tags instead of visual guesses when available', () => { + const a = span('Tagged paragraph line one',20,20,175,{copyBlock:'5',copyRole:'P'}); + const b = span('line two',20,35,80,{copyBlock:'5',copyRole:'P'}); + const c = span('Different block',20,50,150,{copyBlock:'6',copyRole:'P'}); + assert.deepEqual(paragraphAtSpan([a,b,c],b).spans,[a,b]); +}); + +test('excludes other columns and detached headings', () => { + const left1 = span('Left column line one',20,20,155); + const left2 = span('Left column line two',20,35,150); + const right1 = span('Right column line one',220,20,155); + const right2 = span('Right column line two',220,35,150); + const heading = span('Heading',20,0,55,{},20); + const items=[heading,right2,left1,right1,left2]; + assert.deepEqual(paragraphAtSpan(items,left1).spans,[left1,left2]); + assert.deepEqual(paragraphAtSpan(items,right1).spans,[right1,right2]); +}); + +test('reflows split font runs using the existing Markdown formatter', () => { + const a = span('Hello',20,20,35,{markdownBold:'true'}); + const b = span('world.',60,20,40,{markdownItalic:'true'}); + const c = span('Again.',20,35,60); + const p=paragraphAtSpan([a,b,c],b); + assert.deepEqual(p.spans,[a,b,c]); + assert.equal(paragraphCopyText(p.lines,true),'**Hello** _world._ Again.'); +}); + +test('double-click highlights and copies; unrelated clicks are untouched', async () => { + const first=span('Hello world',20,20,100); + const second=span('from the PDF.',20,35,100); + const spans=[first,second]; + const layer={querySelectorAll:()=>spans}; + for (const s of spans) s.closest=selector=>selector==='.text-layer'?layer:null; + const selection={removeAllRanges(){this.ranges=[];},addRange(r){this.ranges.push(r);}}; + const handlers={}, clipboard={}; + const doc={ + addEventListener(type,handler){handlers[type]=handler;}, + createRange(){return {setStartBefore(s){this.start=s;},setEndAfter(s){this.end=s;}};}, + getSelection(){return selection;}, + execCommand(command){ + assert.equal(command,'copy'); + handlers.copy({clipboardData:{setData(type,value){clipboard[type]=value;}},preventDefault(){}}); + return true; + }, + }; + const events=[]; + const view={dispatchEvent(e){events.push(e);},CustomEvent:class{constructor(type,{detail}){this.type=type;this.detail=detail;}}}; + installParagraphDoubleClick({contains:()=>true},{checked:false},doc,view); + const target={closest(selector){ + if(selector.startsWith('a,'))return null; + if(selector.startsWith('.text-layer'))return second; + return null; + }}; + await handlers.dblclick({button:0,target,preventDefault(){}}); + assert.equal(clipboard['text/plain'],'Hello world from the PDF.'); + assert.equal(selection.ranges[0].start,first); + assert.equal(selection.ranges[0].end,second); + assert.equal(events[0].detail.message,'Copied paragraph'); +}); From f7513af2bff1f8b34c4afd8370cfe339cdbde38a Mon Sep 17 00:00:00 2001 From: Lindsey Pony <346700433+sync@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:01:09 -0500 Subject: [PATCH 2/3] =?UTF-8?q?=F0=9F=9B=A0=EF=B8=8F=20Preserve=20feature-?= =?UTF-8?q?suite=20ownership=20checks=20while=20exposing=20paragraph=20tes?= =?UTF-8?q?ts?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The current base routes tests through scripts/test-suites.mjs, whereas the PR replaces that command with a stale hardcoded Node list. Retain all current suite and syntax checks and add a targeted paragraph test command. The new test remains subject to selection-suite ownership registration; do not weaken or bypass that CI check. --- package.json | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index b2a9e1f..78a4137 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,11 @@ "scripts": { "build": "node scripts/build.mjs", "check": "node scripts/check-extension.mjs", - "test": "node --test tests/enhancer-setup.test.mjs tests/document-title.test.mjs tests/metadata-doi.test.mjs tests/local-file-favicon.test.mjs tests/page-tab-labels.test.mjs tests/minimap.test.mjs tests/clickable-reference-links.test.mjs tests/printed-page-jump.test.mjs tests/markdown-copy.test.mjs tests/terminal-punctuation-selection.test.mjs tests/footnote-click-copy.test.mjs tests/chatgpt-summary-popup.test.mjs tests/chatgpt-pdf-relay.test.mjs tests/selection-gaps.test.mjs tests/paragraph-double-click.test.mjs" + "test": "node scripts/test-suites.mjs all", + "test:feature": "node scripts/test-suites.mjs", + "check:suites": "node scripts/test-suites.mjs --list", + "check:syntax": "node scripts/check-javascript.mjs", + "test:paragraph-double-click": "node --test tests/paragraph-double-click.test.mjs" }, "dependencies": { "pdfjs-dist": "6.3.289", From f40dcc5bee26a56099c1e5b4b4d4a60c0c33323d Mon Sep 17 00:00:00 2001 From: Lindsey Pony <346700433+sync@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:01:10 -0500 Subject: [PATCH 3/3] =?UTF-8?q?=F0=9F=9B=A0=EF=B8=8F=20Enable=20paragraph?= =?UTF-8?q?=20copying=20alongside=20current=20viewer=20controls?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Main already passes both tagged-paragraph and copy-on-select settings into the Markdown-copy installer; the PR starts from the older four-argument call and adds a paragraph double-click listener. Preserve the current five-argument setup, add the listener immediately after it, and retain all other controls, including text-fragment sharing. --- src/viewer/viewer.js | 144 ++++++++++++++++++++++++++++++++----------- 1 file changed, 109 insertions(+), 35 deletions(-) diff --git a/src/viewer/viewer.js b/src/viewer/viewer.js index 9fe055d..e27e0b0 100644 --- a/src/viewer/viewer.js +++ b/src/viewer/viewer.js @@ -2,6 +2,7 @@ import { AnnotationLayer, createValidAbsoluteUrl, getDocument, GlobalWorkerOptio import { EventBus, PDFLinkService } from "../../node_modules/pdfjs-dist/web/pdf_viewer.mjs"; import { abandonPdfDocumentSession, publishPdfDocument } from "./pdf-document-session.js"; import { referenceUrlFromPdfMetadata, resolveDocumentReferenceUrl } from "./document-reference-url.js"; +import { pdfTextFragmentFromUrl, pdfTextFragmentUrl } from "./sharing/text-fragment.js"; import { metadataField, pdfMetadataTitle } from "./pdf-metadata-title.js"; import { doiFromPdfMetadata, doiResolverUrl } from "./metadata-doi.js"; import { resolvePdfSource } from "./pdf-source.js"; @@ -12,11 +13,13 @@ import { installParagraphDoubleClick } from "./selection/paragraph-double-click. import { highlightTextLayer, registerSearchText } from "./search/search-highlight.js"; import { normalizeSearchText } from "./search/search-text.js"; import { PagePreviews } from "./page-previews.js"; +import { hasPageSizedImage } from "./theme/scanned-page-images.js"; import { preparePrintDocument } from "./print-renderer.js"; import { highlightFootnote, renderFootnoteHighlight } from "./navigation/footnote-highlight.js"; import { findPrintedContentsEntries, resolvePrintedContentsPage, contentsEntryHasEmbeddedLink } from "./navigation/printed-contents.js"; import { createClickableReferenceLayer } from "./navigation/clickable-reference-links.js"; import { outlinedSectionHeadings } from "./navigation/section-cross-references.js"; +import { filterOutlineHeadings } from "./navigation/outline-filter.js"; import { printedPageShortcutQuery } from "./navigation/printed-page-shortcut.js"; const sourceMode = window.location.pathname.includes("/src/"); @@ -43,12 +46,14 @@ const searchFirstButton = document.querySelector("#search-first"); const searchPreviousButton = document.querySelector("#search-previous"); const searchNextButton = document.querySelector("#search-next"); const shareButton = document.querySelector("#share-page"); +const copyTextFragmentButton = document.querySelector("#copy-text-fragment"); const shareIcon = document.querySelector("#share-icon"); const sectionNav = document.querySelector("#section-nav"); const sectionToggle = document.querySelector("#section-toggle"); const sectionPopover = document.querySelector("#section-popover"); const sectionDocumentTitle = document.querySelector("#section-document-title"); const sectionList = document.querySelector("#section-list"); +const sectionBookmarkToggle = document.querySelector("#section-bookmark-toggle"); const sectionMetadata = document.querySelector("#section-metadata"); const sectionMetadataList = document.querySelector("#section-metadata-list"); const themeButton = document.querySelector("#theme-toggle"); @@ -74,7 +79,6 @@ const LIGHT_MODE_SHARE_ICON = extensionAssetUrl( "src/assets/copy-page-icon-light.png", "assets/copy-page-icon-light.png", ); -const SCANNED_PAGE_IMAGE_AREA_THRESHOLD = 0.8; const RENDER_WINDOW_RADIUS = 3; const PDF_METADATA_FIELDS = [ ["Title", "Title", "dc:title"], @@ -106,6 +110,10 @@ let completedSearchQuery = ""; let searchMatches = []; let activeSearchIndex = -1; let sectionEntries = []; +let sectionOriginalOutline = []; +let sectionFilteredOutline = []; +let hiddenBookmarkCount = 0; +let showAllBookmarks = false; let contentsPageLabels = null; let contentsOutlineItems = []; let clickableSectionTargetsPromise; @@ -137,31 +145,6 @@ const renderedPages = new Set(); const staleRenderedPages = new Set(); const pageTextCache = new Map(); -function imageAreaFraction(imageCoordinates, offset) { - const topLeftX = imageCoordinates[offset]; - const topLeftY = imageCoordinates[offset + 1]; - const bottomLeftX = imageCoordinates[offset + 2]; - const bottomLeftY = imageCoordinates[offset + 3]; - const topRightX = imageCoordinates[offset + 4]; - const topRightY = imageCoordinates[offset + 5]; - const leftX = bottomLeftX - topLeftX; - const leftY = bottomLeftY - topLeftY; - const topX = topRightX - topLeftX; - const topY = topRightY - topLeftY; - - return Math.abs(leftX * topY - leftY * topX); -} - -function hasPageSizedImage(imageCoordinates) { - for (let offset = 0; offset + 5 < imageCoordinates.length; offset += 6) { - if (imageAreaFraction(imageCoordinates, offset) >= SCANNED_PAGE_IMAGE_AREA_THRESHOLD) { - return true; - } - } - - return false; -} - function clampUnit(value) { return Math.min(1, Math.max(0, value)); } @@ -517,7 +500,7 @@ function createOutlineList(items, parentReference = "") { const hasExplicitReference = Boolean(localReference); const sectionReference = hasExplicitReference ? fullSectionReference(parentReference, localReference) - : fallbackSectionReference(parentReference, visiblePosition); + : fallbackSectionReference(parentReference, item.pdfMagicSourcePosition || visiblePosition); const copyText = hasExplicitReference ? sectionReference : fallbackSectionCopyText(sectionReference, title); @@ -571,6 +554,24 @@ function createOutlineList(items, parentReference = "") { return list; } +function renderSectionOutline() { + sectionEntries = []; + const outline = showAllBookmarks ? sectionOriginalOutline : sectionFilteredOutline; + sectionList.replaceChildren(createOutlineList(outline)); + if (hiddenBookmarkCount) { + sectionBookmarkToggle.textContent = showAllBookmarks + ? "Show sections" + : `Show all bookmarks (${hiddenBookmarkCount} hidden)`; + sectionBookmarkToggle.setAttribute("aria-pressed", String(showAllBookmarks)); + } + void updateCurrentSectionHighlight(); +} + +sectionBookmarkToggle?.addEventListener("click", () => { + showAllBookmarks = !showAllBookmarks; + renderSectionOutline(); +}); + function renderPdfMetadata(entries) { const fragment = document.createDocumentFragment(); for (const { label, value } of entries) { @@ -639,11 +640,13 @@ async function initializeSectionNavigation() { return; } - sectionEntries = []; - const outlineList = createOutlineList(outline); - if (!outlineList.childElementCount) { - return; - } + const filtered = filterOutlineHeadings(outline); + sectionOriginalOutline = outline; + sectionFilteredOutline = filtered.outline; + hiddenBookmarkCount = filtered.hidden; + showAllBookmarks = false; + sectionBookmarkToggle.hidden = hiddenBookmarkCount === 0; + if (!sectionFilteredOutline.length) return; const { title: metadataTitle, entries: metadataEntries } = await getPdfMetadataDetails(); if (metadataTitle) { @@ -652,7 +655,7 @@ async function initializeSectionNavigation() { } renderPdfMetadata(metadataEntries); - sectionList.replaceChildren(outlineList); + renderSectionOutline(); sectionNav.hidden = false; } @@ -1218,6 +1221,24 @@ function getSelectedPdfText() { return selection.toString().replace(/\s+/g, " ").trim(); } +let lastSelectedPdfPassage = null; + +function selectedPdfPassage() { + const selection = window.getSelection(); + const text = getSelectedPdfText(); + if (!text || !selection) return null; + const anchor = selection.anchorNode instanceof Element + ? selection.anchorNode : selection.anchorNode?.parentElement; + const focus = selection.focusNode instanceof Element + ? selection.focusNode : selection.focusNode?.parentElement; + const anchorLayer = anchor?.closest(".text-layer"); + const focusLayer = focus?.closest(".text-layer"); + if (!anchorLayer || !focusLayer) return null; + const pageNumber = Number(anchorLayer.closest(".page")?.dataset.page); + if (!Number.isSafeInteger(pageNumber) || pageNumber < 1) return null; + return { text, pageNumber }; +} + function focusSearch() { searchInput.focus(); searchInput.select(); @@ -1272,6 +1293,50 @@ async function rotatePages(delta) { pageElements[currentPage - 1]?.scrollIntoView({ behavior: "auto", block: "center" }); } +async function copyTextFragmentLink() { + const passage = selectedPdfPassage() || lastSelectedPdfPassage; + setToolsMenuOpen(false); + if (!passage) { + showToast("Select text in the PDF to copy its link"); + return; + } + const referenceUrl = await resolveDocumentReferenceUrl(); + const url = referenceUrl && pdfTextFragmentUrl(referenceUrl, passage.text, passage.pageNumber); + if (!url) { + showToast("No linkable PDF URL is available"); + return; + } + try { + await navigator.clipboard.writeText(url); + showToast("Copied link to highlighted PDF text"); + } catch { + showToast("Could not copy highlighted text link"); + } +} + +async function navigateToTextFragment(fragment) { + searchInput.value = fragment.text; + await runSearch(fragment.text); + if (!searchMatches.length) { + showToast("Linked passage not found in this PDF"); + return; + } + if (fragment.pageNumber) { + const preferred = searchMatches.findIndex(match => match.pageNumber === fragment.pageNumber); + if (preferred >= 0) showSearchMatch(preferred, "auto"); + } + const match = searchMatches[activeSearchIndex]; + if (!match) return; + await queuePageRender(match.pageNumber, true); + refreshSearchHighlights(); + const target = [...pageElements[match.pageNumber - 1].querySelectorAll(".search-highlight")] + .find(mark => mark.dataset.searchOrdinals.split(" ").includes(String(match.ordinal))); + if (!target) return; + const toolbarHeight = document.querySelector(".toolbar")?.getBoundingClientRect().height || 52; + const targetTop = window.scrollY + target.getBoundingClientRect().top; + window.scrollTo({ top: Math.max(0, targetTop - toolbarHeight - 80), behavior: "instant" }); +} + async function shareCurrentPage() { const referenceUrl = await resolveDocumentReferenceUrl(); if (!referenceUrl) { @@ -1336,7 +1401,8 @@ async function downloadPdf() { } function bindControls() { - installMarkdownCopy(viewer, document.querySelector("#copy-as-markdown"), document, document.querySelector("#copy-tagged-paragraphs")); + installMarkdownCopy(viewer, document.querySelector("#copy-as-markdown"), document, + document.querySelector("#copy-tagged-paragraphs"), document.querySelector("#copy-on-select")); installParagraphDoubleClick(viewer, document.querySelector("#copy-as-markdown")); window.addEventListener("pdf-viewer-toast", (event) => { if (typeof event.detail?.message === "string") showToast(event.detail.message); @@ -1349,6 +1415,12 @@ function bindControls() { previousButton.addEventListener("click", () => goToPage(currentPage - 1)); nextButton.addEventListener("click", () => goToPage(currentPage + 1)); shareButton.addEventListener("click", () => void shareCurrentPage()); + copyTextFragmentButton.addEventListener("click", () => void copyTextFragmentLink()); + viewer.addEventListener("pointerdown", () => { lastSelectedPdfPassage = null; }, true); + document.addEventListener("selectionchange", () => { + const passage = selectedPdfPassage(); + if (passage) lastSelectedPdfPassage = passage; + }); sectionToggle.addEventListener("click", toggleSectionPopover); document.addEventListener("pointerdown", (event) => { @@ -1480,7 +1552,8 @@ async function initialize() { } catch { // Fall back to the incoming page link when storage is unavailable. } - const requestedPage = resumedPage ?? getInitialPage(window.location, originalUrl); + const incomingTextFragment = pdfTextFragmentFromUrl(originalUrl.href) || pdfTextFragmentFromUrl(window.location.href); + const requestedPage = incomingTextFragment?.pageNumber ?? resumedPage ?? getInitialPage(window.location, originalUrl); requestUrl = new URL(originalUrl.href); requestUrl.hash = ""; @@ -1544,6 +1617,7 @@ async function initialize() { goToPage(currentPage, "auto"); keepRenderWindow(currentPage); pagePreviews.start(rotation, currentPage); + if (incomingTextFragment) await navigateToTextFragment(incomingTextFragment); } window.addEventListener("pagehide", () => {