diff --git a/README.md b/README.md index 1ce1d62..d59816b 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,7 @@ A Chrome Manifest V3 extension that replaces the normal PDF tab with a local PDF - Remembers the last text clicked or selected on a PDF page; switching away shows a blue text highlight and a left-pointing marker on the right page edge, retained on return until the next page click. The cue follows zoom and page rerenders without saving document text. - Copies the original document URL as `#page=` silently when the mark is clicked. - Honors an existing `#page=N` fragment when opening a document. +- **More PDF tools → Copy link to highlighted text** copies an original-PDF URL containing `#page=N:~:text=...`. Chromium can open these links natively, and PDF-magic resolves the text fragment through its PDF.js search to highlight and scroll to the passage. The PDF needs extractable text; a local `file://` URL is usable only where that path exists. - Places Download beside the page-link icon and keeps rotate left/right and print in the **More tools** menu. - Keeps the More tools menu open across repeated rotate actions. - Offers a default-on **More PDF tools → Join tagged paragraph lines on copy** setting. This uses PDF.js's exposed structure-tree paragraph tags and MCIDs to join soft printed line breaks and respect tagged block reading order in the clipboard; turning it off restores the original line breaks. Plain text copy works without enabling Markdown. PDFs lacking reliable tags retain their native copy behavior. Note: PDF.js does not currently expose /ActualText values stored only in content-stream BDC properties, so this reflows tagged text rather than reading that replacement string verbatim. diff --git a/scripts/test-suites.mjs b/scripts/test-suites.mjs index d31c159..7cfeba1 100644 --- a/scripts/test-suites.mjs +++ b/scripts/test-suites.mjs @@ -50,6 +50,7 @@ export const suites = Object.freeze({ "footnote-scanned-petition.test.mjs" ], "search": [ + "text-fragment-link.test.mjs", "search-empty-state.test.mjs", "search-highlight-cues.test.mjs", "search-matches.test.mjs", diff --git a/src/viewer.html b/src/viewer.html index dfdb8f4..c321bea 100644 --- a/src/viewer.html +++ b/src/viewer.html @@ -141,6 +141,7 @@ Print + diff --git a/src/viewer/sharing/text-fragment.js b/src/viewer/sharing/text-fragment.js new file mode 100644 index 0000000..37dcfaa --- /dev/null +++ b/src/viewer/sharing/text-fragment.js @@ -0,0 +1,52 @@ +// Native Chromium PDF viewing supports text fragments. Decode them in +// PDF-magic too when the PDF URL is redirected to the PDF.js viewer. +const MAX_EXCERPT_LENGTH = 180; + +export function textFragmentExcerpt(value) { + const normalized = String(value ?? "").replace(/\s+/gu, " ").trim(); + if (normalized.length <= MAX_EXCERPT_LENGTH) return normalized; + const prefix = normalized.slice(0, MAX_EXCERPT_LENGTH); + return prefix.replace(/\s+\S*$/u, "").trim() || prefix; +} + +export function pdfTextFragmentUrl(referenceUrl, selectedText, pageNumber) { + let url; + try { + url = new URL(referenceUrl); + } catch { + return null; + } + if (!["http:", "https:", "file:"].includes(url.protocol)) return null; + const excerpt = textFragmentExcerpt(selectedText); + if (!excerpt) return null; + // Hyphens delimit prefix/suffix grammar and must be escaped in literal text. + const encoded = encodeURIComponent(excerpt).replace(/[-!'()*]/g, char => + "%" + char.charCodeAt(0).toString(16).toUpperCase()); + const page = Number.isSafeInteger(pageNumber) && pageNumber > 0 ? "page=" + pageNumber : ""; + url.hash = page + ":~:text=" + encoded; + return url.href; +} + +export function pdfTextFragmentFromUrl(value) { + let url; + try { + url = new URL(value); + } catch { + return null; + } + const delimiter = url.hash.indexOf(":~:"); + if (delimiter === -1) return null; + const directive = url.hash.slice(delimiter + 3) + .split("&").find(part => part.startsWith("text=")); + if (!directive) return null; + let text; + try { + text = decodeURIComponent(directive.slice(5)).replace(/\s+/gu, " ").trim(); + } catch { + return null; + } + if (!text) return null; + const pageMatch = url.hash.slice(0, delimiter).match(/(?:^#|[&#])page=(\d+)/i); + const page = pageMatch ? Number(pageMatch[1]) : null; + return { text, pageNumber: Number.isSafeInteger(page) && page > 0 ? page : null }; +} diff --git a/src/viewer/viewer.js b/src/viewer/viewer.js index 2bce26b..663883e 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"; @@ -43,6 +44,7 @@ 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"); @@ -1243,6 +1245,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(); @@ -1297,6 +1317,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) { @@ -1374,6 +1438,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) => { @@ -1505,7 +1575,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 = ""; @@ -1569,6 +1640,7 @@ async function initialize() { goToPage(currentPage, "auto"); keepRenderWindow(currentPage); pagePreviews.start(rotation, currentPage); + if (incomingTextFragment) await navigateToTextFragment(incomingTextFragment); } window.addEventListener("pagehide", () => { diff --git a/tests/text-fragment-link.test.mjs b/tests/text-fragment-link.test.mjs new file mode 100644 index 0000000..ef635a4 --- /dev/null +++ b/tests/text-fragment-link.test.mjs @@ -0,0 +1,45 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + pdfTextFragmentFromUrl, + pdfTextFragmentUrl, + textFragmentExcerpt, +} from "../src/viewer/sharing/text-fragment.js"; + +test("copies a source PDF URL with page and text fragment", () => { + const url = pdfTextFragmentUrl("https://example.org/report.pdf?draft=2#page=1", "Direct Registration\nSystem", 12); + assert.equal(url, "https://example.org/report.pdf?draft=2#page=12:~:text=Direct%20Registration%20System"); + assert.deepEqual(pdfTextFragmentFromUrl(url), { text: "Direct Registration System", pageNumber: 12 }); +}); + +test("escapes punctuation reserved by the text-fragment grammar", () => { + const url = pdfTextFragmentUrl("https://example.org/a.pdf", "trade-off, equity & (custody)", 3); + assert.match(url, /trade%2Doff%2C%20equity%20%26%20%28custody%29/); + assert.equal(pdfTextFragmentFromUrl(url).text, "trade-off, equity & (custody)"); +}); + +test("supports text-only fragments without a page", () => { + const url = pdfTextFragmentUrl("https://example.org/a.pdf", "exact phrase"); + assert.equal(url, "https://example.org/a.pdf#:~:text=exact%20phrase"); + assert.deepEqual(pdfTextFragmentFromUrl(url), { text: "exact phrase", pageNumber: null }); +}); + +test("abbreviates long selections at a word boundary", () => { + const excerpt = textFragmentExcerpt("first " + "word ".repeat(80)); + assert.ok(excerpt.length <= 180); + assert.ok(excerpt.startsWith("first word")); + assert.ok(excerpt.endsWith("word")); +}); + +test("rejects empty, malformed or non-linkable input", () => { + assert.equal(pdfTextFragmentUrl("https://example.org/a.pdf", " ", 1), null); + assert.equal(pdfTextFragmentUrl("not a URL", "test", 1), null); + assert.equal(pdfTextFragmentUrl("javascript:alert(1)", "test", 1), null); + assert.equal(pdfTextFragmentFromUrl("https://example.org/a.pdf#page=5"), null); + assert.equal(pdfTextFragmentFromUrl("https://example.org/a.pdf#:~:text=%E0%A4%A"), null); +}); + +test("allows local PDFs while retaining the original file path", () => { + assert.equal(pdfTextFragmentUrl("file:///Users/me/archive.pdf", "hello", 2), + "file:///Users/me/archive.pdf#page=2:~:text=hello"); +});