Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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=<current 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.
Expand Down
1 change: 1 addition & 0 deletions scripts/test-suites.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
1 change: 1 addition & 0 deletions src/viewer.html
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@
<span>Print</span>
</button>
<button id="qr-file-url" class="tool-button" type="button" role="menuitem">β–¦ <span>QR file URL</span></button>
<button id="copy-text-fragment" class="tool-button" type="button" role="menuitem" title="Copy a link to the selected text in the original PDF">πŸ”— <span>Copy link to highlighted text</span></button>
<button id="open-enhancer-setup" class="tool-button" type="button" role="menuitem">✦ <span>Set up PDF Enhancer</span></button>
<div class="menu-separator" role="separator"></div>
<button id="choose-loading-image" class="tool-button" type="button" role="menuitem">β–§ <span>Custom loading image…</span></button>
Expand Down
52 changes: 52 additions & 0 deletions src/viewer/sharing/text-fragment.js
Original file line number Diff line number Diff line change
@@ -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 };
}
74 changes: 73 additions & 1 deletion src/viewer/viewer.js
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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");
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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) => {
Expand Down Expand Up @@ -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 = "";

Expand Down Expand Up @@ -1569,6 +1640,7 @@ async function initialize() {
goToPage(currentPage, "auto");
keepRenderWindow(currentPage);
pagePreviews.start(rotation, currentPage);
if (incomingTextFragment) await navigateToTextFragment(incomingTextFragment);
}

window.addEventListener("pagehide", () => {
Expand Down
45 changes: 45 additions & 0 deletions tests/text-fragment-link.test.mjs
Original file line number Diff line number Diff line change
@@ -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");
});
Loading