Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(ui): follow links in the phone PDF reader (#3028)

Call White317377ee8003
diff --git a/ui/e2e/pdf-preview/pdf.ts b/ui/e2e/pdf-preview/pdf.ts
index 4a2f674f2..d7dedb784 100644
--- a/ui/e2e/pdf-preview/pdf.ts
+++ b/ui/e2e/pdf-preview/pdf.ts
@@ -8,6 +8,9 @@
// ``radicals`` adds a "月份" line whose ToUnicode maps 月 to the Kangxi radical ⽉ (U+2F49), as the
// fonts Chrome embeds do: it looks right, and copies as a different character unless unified.
// ``rotate`` sets every page's /Rotate, as scanners and some exporters do for landscape pages.
+// ``links`` (needs four pages) puts four labelled link annotations on page 1: a web link, an explicit
+// destination on page 3 (XYZ with only y = LINK_DEST_Y), a named destination resolving to page 4 (Fit), and a
+// ``javascript:`` link that must never become clickable.
export type Rgb = readonly [number, number, number];
@@ -15,6 +18,15 @@ export const PAGE_WIDTH = 612;
export const PAGE_HEIGHT = 792;
// The coloured band, in PDF user space (origin bottom-left).
export const BAND = { x: 56, y: 240, width: 500, height: 320 } as const;
+export const LINK_URL = 'https://example.com/pdf-link';
+export const LINK_DEST_Y = 400;
+// Link areas on page 1, in PDF user space, each over its label.
+export const LINKS = {
+ web: { label: 'example.com', rect: [70, 172, 212, 204] },
+ page3: { label: 'To page 3', rect: [248, 172, 362, 204] },
+ page4: { label: 'To page 4', rect: [398, 172, 512, 204] },
+ script: { label: 'Script', rect: [70, 112, 146, 144] },
+} as const;
export function pageColor(index: number): Rgb {
const palette: Rgb[] = [
@@ -30,7 +42,19 @@ export function pageColor(index: number): Rgb {
const unit = (v: number) => (v / 255).toFixed(3);
-export function buildPdf({ pages, cjk = false, radicals = false, rotate = 0 }: { pages: number; cjk?: boolean; radicals?: boolean; rotate?: 0 | 90 | 180 | 270 }): Buffer {
+export function buildPdf({
+ pages,
+ cjk = false,
+ radicals = false,
+ rotate = 0,
+ links = false,
+}: {
+ pages: number;
+ cjk?: boolean;
+ radicals?: boolean;
+ rotate?: 0 | 90 | 180 | 270;
+ links?: boolean;
+}): Buffer {
const objects: string[] = [];
const add = (body: string) => {
objects.push(body);
@@ -74,6 +98,9 @@ export function buildPdf({ pages, cjk = false, radicals = false, rotate = 0 }: {
if (cjk) ops.push('0 0 0 rg BT /F2 40 Tf 72 620 Td <4E2D6587988489C8> Tj ET');
// "月份", in the band's upper edge.
if (radicals) ops.push('0 0 0 rg BT /F2 32 Tf 72 575 Td <67084EFD> Tj ET');
+ if (links && i === 0) {
+ for (const { label, rect } of Object.values(LINKS)) ops.push(`0 0 0 rg BT /F1 24 Tf ${rect[0] + 2} ${rect[1] + 8} Td (${label}) Tj ET`);
+ }
const stream = ops.join('\n');
const content = add(`<< /Length ${Buffer.byteLength(stream)} >>\nstream\n${stream}\nendstream`);
const fonts = `/F1 ${helvetica} 0 R${cjk ? ` /F2 ${song} 0 R` : ''}`;
@@ -81,7 +108,19 @@ export function buildPdf({ pages, cjk = false, radicals = false, rotate = 0 }: {
add(`<< /Type /Page /Parent ${pagesNode} 0 R /MediaBox [0 0 ${PAGE_WIDTH} ${PAGE_HEIGHT}]${rotate ? ` /Rotate ${rotate}` : ''} /Contents ${content} 0 R /Resources << /Font << ${fonts} >> >> >>`),
);
}
- objects[catalog - 1] = `<< /Type /Catalog /Pages ${pagesNode} 0 R >>`;
+ let names = '';
+ if (links) {
+ const box = (rect: readonly number[]) => `/Rect [${rect.join(' ')}] /Border [0 0 0]`;
+ const annots = [
+ add(`<< /Type /Annot /Subtype /Link ${box(LINKS.web.rect)} /A << /S /URI /URI (${LINK_URL}) >> >>`),
+ add(`<< /Type /Annot /Subtype /Link ${box(LINKS.page3.rect)} /Dest [${kids[2]} 0 R /XYZ null ${LINK_DEST_Y} null] >>`),
+ add(`<< /Type /Annot /Subtype /Link ${box(LINKS.page4.rect)} /Dest (page-four) >>`),
+ add(`<< /Type /Annot /Subtype /Link ${box(LINKS.script.rect)} /A << /S /URI /URI (javascript:alert\\(1\\)) >> >>`),
+ ];
+ objects[kids[0] - 1] = objects[kids[0] - 1].replace(' /Contents', ` /Annots [${annots.map((a) => `${a} 0 R`).join(' ')}] /Contents`);
+ names = ` /Names << /Dests << /Names [(page-four) [${kids[3]} 0 R /Fit]] >> >>`;
+ }
+ objects[catalog - 1] = `<< /Type /Catalog /Pages ${pagesNode} 0 R${names} >>`;
objects[pagesNode - 1] = `<< /Type /Pages /Kids [${kids.map((k) => `${k} 0 R`).join(' ')}] /Count ${kids.length} >>`;
let out = '%PDF-1.4\n';
diff --git a/ui/e2e/pdf-preview/preview.spec.ts b/ui/e2e/pdf-preview/preview.spec.ts
index cb65eea9f..586c5c19b 100644
--- a/ui/e2e/pdf-preview/preview.spec.ts
+++ b/ui/e2e/pdf-preview/preview.spec.ts
@@ -1,6 +1,6 @@
import { expect, test, type Locator, type Page } from '@playwright/test';
-import { BAND, PAGE_HEIGHT, PAGE_WIDTH, buildPdf, pageColor, type Rgb } from './pdf';
+import { BAND, LINKS, LINK_DEST_Y, LINK_URL, PAGE_HEIGHT, PAGE_WIDTH, buildPdf, pageColor, type Rgb } from './pdf';
/**
* The chat file viewer's PDF preview, in real engines.
@@ -19,6 +19,8 @@ const DOCS: Record<string, Buffer> = {
doc_long: buildPdf({ pages: 14 }),
doc_cjk: buildPdf({ pages: 2, cjk: true }),
doc_radicals: buildPdf({ pages: 1, cjk: true, radicals: true }),
+ doc_links: buildPdf({ pages: 5, links: true }),
+ doc_links_rot90: buildPdf({ pages: 5, links: true, rotate: 90 }),
doc_rot90: buildPdf({ pages: 1, rotate: 90 }),
doc_rot180: buildPdf({ pages: 1, rotate: 180 }),
doc_rot270: buildPdf({ pages: 1, rotate: 270 }),
@@ -254,6 +256,89 @@ test.describe('phones and tablets', () => {
await expect(pageBox(dialog, 1).locator('.vr-pdf-text')).not.toContainText('\u2F49');
});
+ test('links sit over their labels, and a script link is not clickable', async ({ page }) => {
+ const dialog = await openPreview(page, 'doc_links');
+ await expectTextOverInk(dialog, 1, LINKS.script.label);
+ const anchors = pageBox(dialog, 1).locator('.vr-pdf-links > a');
+ await expect(anchors).toHaveCount(3);
+ await expect(pageBox(dialog, 1).locator('a[href^="javascript"]')).toHaveCount(0);
+ for (const { label } of [LINKS.web, LINKS.page3, LINKS.page4]) {
+ const word = await spanBox(dialog, 1, label);
+ const reached = await page.evaluate(({ x, y }) => document.elementFromPoint(x, y)?.closest('a')?.getAttribute('href') ?? null, {
+ x: word.x + word.width / 2,
+ y: word.y + word.height / 2,
+ });
+ expect(reached, `a tap on "${label}" reaches a link`).not.toBeNull();
+ }
+ // The script link's words are plain, selectable text.
+ const script = await spanBox(dialog, 1, LINKS.script.label);
+ const under = await page.evaluate(({ x, y }) => document.elementFromPoint(x, y)?.textContent, { x: script.x + script.width / 2, y: script.y + script.height / 2 });
+ expect(under).toBe(LINKS.script.label);
+ });
+
+ test('a web link opens in a new tab and leaves the preview open', async ({ page, context }) => {
+ await context.route('https://example.com/**', (route) => route.fulfill({ contentType: 'text/html', body: '<title>linked</title>' }));
+ const dialog = await openPreview(page, 'doc_links');
+ const link = pageBox(dialog, 1).locator(`.vr-pdf-links > a[href="${LINK_URL}"]`);
+ await expect(link).toHaveAttribute('target', '_blank');
+ const popup = page.waitForEvent('popup');
+ await link.tap();
+ expect((await popup).url()).toBe(LINK_URL);
+ await expect(dialog).toBeVisible();
+ });
+
+ test('a link to a place in the document scrolls the reader there', async ({ page }) => {
+ const dialog = await openPreview(page, 'doc_links');
+ await expect(pageBox(dialog, 1).locator('.vr-pdf-links > a')).toHaveCount(3);
+ const tapLabel = async (label: string) => {
+ const word = await spanBox(dialog, 1, label);
+ await page.touchscreen.tap(word.x + word.width / 2, word.y + word.height / 2);
+ };
+
+ // Explicit destination: page 3 at y = LINK_DEST_Y, shown just below the top edge.
+ await tapLabel(LINKS.page3.label);
+ const expected3 = await pageBox(dialog, 3).evaluate(
+ (box: HTMLElement, { y, h }) => box.offsetTop + ((h - y) / h) * box.offsetHeight - 8,
+ { y: LINK_DEST_Y, h: PAGE_HEIGHT },
+ );
+ await expect.poll(async () => Math.abs((await scroller(dialog).evaluate((el) => el.scrollTop)) - expected3)).toBeLessThan(3);
+ await expect(position(dialog)).toHaveText('3 / 5');
+
+ // Named destination: resolved through the document's name tree, to the top of page 4.
+ await scroller(dialog).evaluate((el) => el.scrollTo({ top: 0 }));
+ await expect(position(dialog)).toHaveText('1 / 5');
+ await tapLabel(LINKS.page4.label);
+ const expected4 = await pageBox(dialog, 4).evaluate((box: HTMLElement) => box.offsetTop);
+ await expect.poll(async () => Math.abs((await scroller(dialog).evaluate((el) => el.scrollTop)) - expected4)).toBeLessThan(3);
+ await expect(position(dialog)).toHaveText('4 / 5');
+ await expect(dialog).toBeVisible();
+ });
+
+ test('on a page turned by /Rotate 90, a link lands on its target across the screen', async ({ page }) => {
+ const dialog = await openPreview(page, 'doc_links_rot90');
+ await expect(pageBox(dialog, 1).locator('.vr-pdf-links > a')).toHaveCount(3);
+ // Zoomed in, so the pages also scroll sideways.
+ for (let i = 0; i < 3; i += 1) await dialog.getByRole('button', { name: 'Zoom in' }).click();
+ await expect(dialog.getByText('200%')).toBeVisible();
+ await pageBox(dialog, 1).locator('.vr-pdf-links > a[data-pdf-dest]').first().tap();
+
+ // The destination names only y, which a 90° page shows across the screen (PDF y = 0 at its
+ // left edge): the reader scrolls sideways to it and shows the target page from its top.
+ const expected = await scroller(dialog).evaluate(
+ (el, { y, h }) => {
+ const box = el.querySelector<HTMLElement>('[data-pdf-page="3"]')!;
+ return { top: box.offsetTop, left: Math.min(box.offsetLeft + (y / h) * box.offsetWidth - 8, el.scrollWidth - el.clientWidth) };
+ },
+ { y: LINK_DEST_Y, h: PAGE_HEIGHT },
+ );
+ await expect
+ .poll(() =>
+ scroller(dialog).evaluate((el, want) => Math.max(Math.abs(el.scrollTop - want.top), Math.abs(el.scrollLeft - want.left)), expected),
+ )
+ .toBeLessThan(2);
+ await expect(position(dialog)).toHaveText('3 / 5');
+ });
+
test('on a page with /Rotate the text is turned with the drawing', async ({ page }) => {
for (const file of ['doc_rot90', 'doc_rot180', 'doc_rot270']) {
const dialog = await openPreview(page, file);
diff --git a/ui/eslint-baseline.json b/ui/eslint-baseline.json
index 6aa24af8f..1837329ae 100644
--- a/ui/eslint-baseline.json
+++ b/ui/eslint-baseline.json
@@ -298,7 +298,6 @@
},
"src/components/ui/file-preview.tsx": {
"avibe/localized-user-text": 4,
- "no-useless-assignment": 1,
"react-hooks/set-state-in-effect": 6
},
"src/components/ui/file-viewer-modal.tsx": {
diff --git a/ui/src/components/ui/file-preview.tsx b/ui/src/components/ui/file-preview.tsx
index 420745578..f0aa85b09 100644
--- a/ui/src/components/ui/file-preview.tsx
+++ b/ui/src/components/ui/file-preview.tsx
@@ -21,6 +21,7 @@ import {
JSON_TREE_MAX_NODES,
PREVIEW_MAX_BYTES,
codeLanguage,
+ isSafeDocumentLink,
previewRenderKind,
} from '@/lib/filePreview';
import { FIT_VIEW, type ImageView, clampPan, maxScale, oneToOneScale, toggleScale, zoomPercent, zoomToPoint } from '@/lib/imageZoom';
@@ -394,17 +395,9 @@ const HtmlView: React.FC<{ html: string; className?: string }> = ({ html, classN
// target straight into <a href>, so a crafted `javascript:` link would run in the app origin on
// click). Anything that isn't a plain web/mail link has its href stripped (inert text); safe links
// open in a new tab so a click can't navigate the workbench away.
-const SAFE_LINK_PROTOCOLS = new Set(['http:', 'https:', 'mailto:']);
function sanitizeRenderedLinks(root: HTMLElement) {
root.querySelectorAll('a[href]').forEach((a) => {
- let safe = false;
- try {
- // new URL() normalizes obfuscated schemes (e.g. `java\tscript:`), so the check can't be fooled.
- safe = SAFE_LINK_PROTOCOLS.has(new URL(a.getAttribute('href') || '', window.location.href).protocol);
- } catch {
- safe = false;
- }
- if (safe) {
+ if (isSafeDocumentLink(a.getAttribute('href') || '', window.location.href)) {
a.setAttribute('target', '_blank');
a.setAttribute('rel', 'noopener noreferrer');
} else {
diff --git a/ui/src/components/ui/pdf-pages.tsx b/ui/src/components/ui/pdf-pages.tsx
index 04b907c39..6a9daf800 100644
--- a/ui/src/components/ui/pdf-pages.tsx
+++ b/ui/src/components/ui/pdf-pages.tsx
@@ -6,7 +6,20 @@ import type { PDFDocumentLoadingTask, PDFDocumentProxy, PDFWorker, RenderTask, T
import PdfjsWorker from 'pdfjs-dist/legacy/build/pdf.worker.mjs?worker';
import { Button } from '@/components/ui/button';
-import { PDF_MAX_ZOOM, PDF_MIN_ZOOM, clampPdfZoom, pageIndexAt, pdfOutputScale, stepPdfZoom } from '@/lib/pdfPreview';
+import {
+ PDF_MAX_ZOOM,
+ PDF_MIN_ZOOM,
+ type PdfLinkAnnotation,
+ type PdfLinkTarget,
+ clampPdfZoom,
+ pageIndexAt,
+ pdfDestAxes,
+ pdfDestPoint,
+ pdfLinkAreas,
+ pdfLinkTarget,
+ pdfOutputScale,
+ stepPdfZoom,
+} from '@/lib/pdfPreview';
import { unifyCjkRadicals } from '@/lib/cjkRadicals';
import { PDF_TEXT_LAYER_CLASS, trackPdfTextLayer } from '@/lib/pdfTextSelection';
@@ -23,6 +36,8 @@ import { PDF_TEXT_LAYER_CLASS, trackPdfTextLayer } from '@/lib/pdfTextSelection'
// - Each drawn page carries pdf.js's text layer: transparent text laid exactly over the drawing, so
// the text can be long-pressed or dragged to select and copied (styles: ``.vr-pdf-text`` in
// index.css; selection behaviour: lib/pdfTextSelection.ts).
+// - Link annotations become anchors over their areas: web and mail links open in a new tab, links
+// to a place in the document scroll the reader there. Other actions are not offered.
// - The legacy build is used on purpose: the modern one relies on JavaScript features newer than the
// mobile Safari versions people still run.
@@ -315,6 +330,35 @@ function PdfReader({ doc, ratio, TextLayer, className }: { doc: PDFDocumentProxy
};
}, [scroller, applyZoom]);
+ // Follow a link to a place in the document: scroll its page in, at the point the destination
+ // names when it names one, a little below the top edge so that line is not flush with it.
+ const goTo = React.useCallback(
+ async (dest: string | readonly unknown[]) => {
+ try {
+ const explicit = typeof dest === 'string' ? await doc.getDestination(dest) : dest;
+ if (!scroller || !Array.isArray(explicit) || explicit.length === 0) return;
+ const ref: unknown = explicit[0];
+ const index =
+ typeof ref === 'number' ? ref : ref && typeof ref === 'object' ? await doc.getPageIndex(ref as Parameters<PDFDocumentProxy['getPageIndex']>[0]) : -1;
+ const pageEl = pageElements(contentRef.current)[index];
+ if (!pageEl) return;
+ const page = await doc.getPage(index + 1);
+ const viewport = page.getViewport({ scale: pageEl.offsetWidth / page.getViewport({ scale: 1 }).width });
+ const point = pdfDestPoint(explicit);
+ // On a page with /Rotate 90 or 270 the destination's x and y land on the other screen axes.
+ const axes = pdfDestAxes(point, viewport.rotation);
+ const [vx, vy] = viewport.convertToViewportPoint(point.x ?? 0, point.y ?? 0) as [number, number];
+ scroller.scrollTo({
+ top: pageEl.offsetTop + (axes.top ? Math.max(0, vy - 8) : 0),
+ left: axes.left ? Math.max(0, pageEl.offsetLeft + vx - 8) : scroller.scrollLeft,
+ });
+ } catch {
+ // A destination that does not resolve leaves the reader where it is.
+ }
+ },
+ [doc, scroller],
+ );
+
const pages = React.useMemo(() => Array.from({ length: total }, (_, i) => i + 1), [total]);
const atFit = zoom <= PDF_MIN_ZOOM + 0.001;
const atMax = zoom >= PDF_MAX_ZOOM - 0.001;
@@ -326,7 +370,18 @@ function PdfReader({ doc, ratio, TextLayer, className }: { doc: PDFDocumentProxy
<div ref={contentRef} className="relative flex w-max min-w-full flex-col items-center gap-3 px-3 pb-16 pt-3">
{pageWidth > 0 &&
pages.map((n) => (
- <PdfPage key={n} doc={doc} TextLayer={TextLayer} pageNumber={n} width={pageWidth} fallbackRatio={ratio} watch={watch} label={t('preview.pdfPage', { page: n })} />
+ <PdfPage
+ key={n}
+ doc={doc}
+ TextLayer={TextLayer}
+ pageNumber={n}
+ width={pageWidth}
+ fallbackRatio={ratio}
+ watch={watch}
+ onLink={goTo}
+ label={t('preview.pdfPage', { page: n })}
+ linkLabel={t('preview.pdfInternalLink')}
+ />
))}
</div>
</div>
@@ -357,17 +412,63 @@ function PdfReader({ doc, ratio, TextLayer, className }: { doc: PDFDocumentProxy
);
}
-// What a page box shows: its canvas and text layer, swapped in together. The previous text layer
-// stops being tracked for selection when it leaves the document.
+// What a page box shows: its canvas, text layer and link layer, swapped in together. The previous
+// text layer stops being tracked for selection when it leaves the document.
const trackedLayers = new WeakMap<HTMLElement, () => void>();
-function showPage(box: HTMLElement, canvas: HTMLCanvasElement | null, layer: HTMLElement | null) {
+function showPage(box: HTMLElement, canvas: HTMLCanvasElement | null, layer: HTMLElement | null, links: HTMLElement | null = null) {
trackedLayers.get(box)?.();
trackedLayers.delete(box);
- box.replaceChildren(...[canvas, layer].filter((node): node is HTMLCanvasElement | HTMLElement => node !== null));
+ box.replaceChildren(...[canvas, layer, links].filter((node): node is HTMLCanvasElement | HTMLElement => node !== null));
if (layer) trackedLayers.set(box, trackPdfTextLayer(layer));
}
+// One anchor per link area, positioned in percent of the page so it stays on its words while the
+// box is resized ahead of the next render.
+function linkLayer(
+ annotations: readonly PdfLinkAnnotation[],
+ viewport: { width: number; height: number; convertToViewportPoint: (x: number, y: number) => number[] },
+ onLink: (dest: string | readonly unknown[]) => void,
+ base: string,
+ internalLabel: string,
+): HTMLElement | null {
+ const anchors: HTMLAnchorElement[] = [];
+ for (const annotation of annotations) {
+ const target: PdfLinkTarget | null = pdfLinkTarget(annotation, base);
+ if (!target) continue;
+ for (const area of pdfLinkAreas(annotation)) {
+ const [x1, y1] = viewport.convertToViewportPoint(area[0], area[1]);
+ const [x2, y2] = viewport.convertToViewportPoint(area[2], area[3]);
+ const a = document.createElement('a');
+ a.style.left = `${(100 * Math.min(x1, x2)) / viewport.width}%`;
+ a.style.top = `${(100 * Math.min(y1, y2)) / viewport.height}%`;
+ a.style.width = `${(100 * Math.abs(x2 - x1)) / viewport.width}%`;
+ a.style.height = `${(100 * Math.abs(y2 - y1)) / viewport.height}%`;
+ if (target.kind === 'url') {
+ a.href = target.href;
+ a.target = '_blank';
+ a.rel = 'noopener noreferrer nofollow';
+ a.title = target.href;
+ } else {
+ const { dest } = target;
+ a.href = '#';
+ a.dataset.pdfDest = 'true';
+ a.setAttribute('aria-label', internalLabel);
+ a.addEventListener('click', (event) => {
+ event.preventDefault();
+ onLink(dest);
+ });
+ }
+ anchors.push(a);
+ }
+ }
+ if (anchors.length === 0) return null;
+ const layer = document.createElement('div');
+ layer.className = 'vr-pdf-links';
+ layer.append(...anchors);
+ return layer;
+}
+
const PdfPage = React.memo(function PdfPage({
doc,
TextLayer,
@@ -375,7 +476,9 @@ const PdfPage = React.memo(function PdfPage({
width,
fallbackRatio,
watch,
+ onLink,
label,
+ linkLabel,
}: {
doc: PDFDocumentProxy;
TextLayer: TextLayerClass;
@@ -383,7 +486,9 @@ const PdfPage = React.memo(function PdfPage({
width: number;
fallbackRatio: number;
watch: PageWatch;
+ onLink: (dest: string | readonly unknown[]) => void;
label: string;
+ linkLabel: string;
}) {
const boxRef = React.useRef<HTMLDivElement>(null);
const [near, setNear] = React.useState(false);
@@ -446,10 +551,15 @@ const PdfPage = React.memo(function PdfPage({
return text.render().then(() => true);
})
.catch(() => false);
+ const links = page.getAnnotations({ intent: 'display' }).then(
+ (annotations: PdfLinkAnnotation[]) => linkLayer(annotations, page.getViewport({ scale: cssScale }), onLink, window.location.href, linkLabel),
+ () => null,
+ );
await task.promise;
const hasText = await textReady;
+ const linkLayerEl = await links;
if (cancelled) return;
- showPage(box, canvas, hasText ? layer : null);
+ showPage(box, canvas, hasText ? layer : null, linkLayerEl);
box.dataset.pdfRendered = 'true';
if (hasText) box.dataset.pdfText = 'true';
else delete box.dataset.pdfText;
@@ -459,7 +569,7 @@ const PdfPage = React.memo(function PdfPage({
task?.cancel();
text?.cancel();
};
- }, [doc, TextLayer, pageNumber, width, near]);
+ }, [doc, TextLayer, pageNumber, width, near, onLink, linkLabel]);
// A group, not an image: the page's text is readable by assistive technology through its layer.
return (
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index a3f077847..98fa7c15c 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -192,6 +192,7 @@
"pdfPage": "Page {{page}}",
"pdfPosition": "Page {{page}} of {{total}}",
"pdfCounter": "{{page}} / {{total}}",
+ "pdfInternalLink": "Go to the linked place in this document",
"zoomPercent": "{{percent}}%",
"download": "Download"
},
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 02bf54e37..522e06e36 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -192,6 +192,7 @@
"pdfPage": "第 {{page}} 页",
"pdfPosition": "第 {{page}} 页,共 {{total}} 页",
"pdfCounter": "{{page}} / {{total}}",
+ "pdfInternalLink": "跳转到文档中的链接位置",
"zoomPercent": "{{percent}}%",
"download": "下载"
},
diff --git a/ui/src/index.css b/ui/src/index.css
index 123a28736..5c8bf72ca 100644
--- a/ui/src/index.css
+++ b/ui/src/index.css
@@ -1090,6 +1090,28 @@ pre,
}
.vr-pdf-text.selecting .vr-pdf-text-end { top: 0; }
+/* PDF links (components/ui/pdf-pages.tsx): transparent anchors over each link's area, above the
+ text layer. Only the anchors take pointer events, so text outside a link stays selectable; a tint
+ on hover / press / keyboard focus shows what a tap will follow. */
+.vr-pdf-links {
+ position: absolute;
+ inset: 0;
+ z-index: 1;
+ pointer-events: none;
+}
+.vr-pdf-links > a {
+ position: absolute;
+ border-radius: 2px;
+ pointer-events: auto;
+ -webkit-tap-highlight-color: transparent;
+}
+.vr-pdf-links > a:hover,
+.vr-pdf-links > a:active,
+.vr-pdf-links > a:focus-visible {
+ background: color-mix(in srgb, var(--mint) 22%, transparent);
+}
+.vr-pdf-links > a:focus-visible { outline: 2px solid var(--mint); outline-offset: 1px; }
+
/* The project header remains a scroll/tap target until a touch hold activates. */
.project-drag-header {
cursor: pointer;
diff --git a/ui/src/lib/filePreview.ts b/ui/src/lib/filePreview.ts
index 767a52541..6862dd125 100644
--- a/ui/src/lib/filePreview.ts
+++ b/ui/src/lib/filePreview.ts
@@ -149,6 +149,21 @@ const DOC_EXT: Record<string, DocPreviewKind> = {
};
export const DOC_PREVIEW_MAX_BYTES = IMAGE_PREVIEW_MAX_BYTES; // 25 MB, matches the backend content cap
+// Links that come from inside a previewed document (DOCX hyperlinks, PDF link annotations) are
+// followed only when they are plain web or mail links, and then in a new tab, so a crafted
+// ``javascript:`` target can't run in the app origin and a click can't navigate the workbench away.
+const SAFE_LINK_PROTOCOLS = new Set(['http:', 'https:', 'mailto:']);
+
+/** Whether ``href`` (resolved against ``base``) is a web or mail link safe to open from a document. */
+export function isSafeDocumentLink(href: string, base: string): boolean {
+ try {
+ // new URL() normalizes obfuscated schemes (e.g. `java\tscript:`), so the check can't be fooled.
+ return SAFE_LINK_PROTOCOLS.has(new URL(href, base).protocol);
+ } catch {
+ return false;
+ }
+}
+
// Office/PDF content types → kind, so a descriptive-label chat link (whose name carries no real
// suffix) still classifies via the server-supplied content-type. Limited to formats our renderers
// actually read: the OOXML types + PDF, plus legacy .xls (SheetJS reads BIFF). Legacy binary .doc
diff --git a/ui/src/lib/pdfPreview.test.ts b/ui/src/lib/pdfPreview.test.ts
index f3b5c7b96..bc5de3456 100644
--- a/ui/src/lib/pdfPreview.test.ts
+++ b/ui/src/lib/pdfPreview.test.ts
@@ -7,6 +7,10 @@ import {
PDF_ZOOM_STEPS,
clampPdfZoom,
pageIndexAt,
+ pdfDestAxes,
+ pdfDestPoint,
+ pdfLinkAreas,
+ pdfLinkTarget,
pdfOutputScale,
shouldRenderPdfPages,
stepPdfZoom,
@@ -96,3 +100,81 @@ describe('pageIndexAt', () => {
expect(pageIndexAt([], 100)).toBe(0);
});
});
+
+describe('pdfLinkTarget', () => {
+ const base = 'https://avibe.example/chat/s1';
+ const link = (over: Record<string, unknown>) => ({ subtype: 'Link', rect: [0, 0, 10, 10], ...over });
+
+ it('opens web and mail links', () => {
+ expect(pdfLinkTarget(link({ url: 'https://example.com/a' }), base)).toEqual({ kind: 'url', href: 'https://example.com/a' });
+ expect(pdfLinkTarget(link({ url: 'mailto:[email protected]' }), base)).toEqual({ kind: 'url', href: 'mailto:[email protected]' });
+ });
+
+ it('offers no link for other schemes pdf.js still accepts', () => {
+ expect(pdfLinkTarget(link({ url: 'tel:+15550100' }), base)).toBeNull();
+ expect(pdfLinkTarget(link({ url: 'ftp://files.example.com/x' }), base)).toBeNull();
+ // pdf.js puts a rejected URI in ``unsafeUrl`` and leaves ``url`` unset.
+ expect(pdfLinkTarget(link({ unsafeUrl: 'javascript:alert(1)' }), base)).toBeNull();
+ });
+
+ it('follows named and explicit destinations inside the document', () => {
+ expect(pdfLinkTarget(link({ dest: 'chapter-2' }), base)).toEqual({ kind: 'dest', dest: 'chapter-2' });
+ const explicit = [{ num: 9, gen: 0 }, { name: 'XYZ' }, 0, 400, null];
+ expect(pdfLinkTarget(link({ dest: explicit }), base)).toEqual({ kind: 'dest', dest: explicit });
+ });
+
+ it('ignores hidden links, other annotation types, and links without a target', () => {
+ expect(pdfLinkTarget(link({ url: 'https://example.com', annotationFlags: 0x2 }), base)).toBeNull();
+ expect(pdfLinkTarget({ subtype: 'Text', url: 'https://example.com' }, base)).toBeNull();
+ expect(pdfLinkTarget(link({ dest: [] }), base)).toBeNull();
+ expect(pdfLinkTarget(link({}), base)).toBeNull();
+ });
+});
+
+describe('pdfLinkAreas', () => {
+ it('uses the rectangle, normalized, when there are no quadrilaterals', () => {
+ expect(pdfLinkAreas({ rect: [212, 204, 70, 172] })).toEqual([[70, 172, 212, 204]]);
+ });
+
+ it('gives a link that wraps onto a second line one area per line', () => {
+ const quadPoints = new Float32Array([400, 220, 560, 220, 400, 200, 560, 200, 72, 190, 180, 190, 72, 170, 180, 170]);
+ expect(pdfLinkAreas({ rect: [72, 170, 560, 220], quadPoints })).toEqual([
+ [400, 200, 560, 220],
+ [72, 170, 180, 190],
+ ]);
+ });
+
+ it('has no area without geometry', () => {
+ expect(pdfLinkAreas({ rect: null })).toEqual([]);
+ });
+});
+
+describe('pdfDestPoint', () => {
+ const page = { num: 3, gen: 0 };
+ it.each([
+ [[page, { name: 'XYZ' }, 36, 400, null], { x: 36, y: 400 }],
+ [[page, { name: 'XYZ' }, null, 400, 0], { x: null, y: 400 }],
+ [[page, { name: 'FitH' }, 500], { x: null, y: 500 }],
+ [[page, { name: 'FitBH' }, 500], { x: null, y: 500 }],
+ [[page, { name: 'FitV' }, 20], { x: 20, y: null }],
+ [[page, { name: 'FitR' }, 10, 20, 300, 400], { x: 10, y: 400 }],
+ [[page, { name: 'Fit' }], { x: null, y: null }],
+ [[page], { x: null, y: null }],
+ ])('reads %j', (dest, point) => {
+ expect(pdfDestPoint(dest)).toEqual(point);
+ });
+});
+
+describe('pdfDestAxes', () => {
+ it('fixes the axes the destination names on an upright or upside-down page', () => {
+ expect(pdfDestAxes({ x: null, y: 400 }, 0)).toEqual({ left: false, top: true });
+ expect(pdfDestAxes({ x: 36, y: null }, 180)).toEqual({ left: true, top: false });
+ });
+
+ it('swaps them on a page turned a quarter either way', () => {
+ // FitH names only y, which a 90° page shows across the screen.
+ expect(pdfDestAxes({ x: null, y: 400 }, 90)).toEqual({ left: true, top: false });
+ expect(pdfDestAxes({ x: 36, y: null }, 270)).toEqual({ left: false, top: true });
+ expect(pdfDestAxes({ x: 36, y: 400 }, -90)).toEqual({ left: true, top: true });
+ });
+});
diff --git a/ui/src/lib/pdfPreview.ts b/ui/src/lib/pdfPreview.ts
index b3f970a5d..6eff1463e 100644
--- a/ui/src/lib/pdfPreview.ts
+++ b/ui/src/lib/pdfPreview.ts
@@ -1,3 +1,4 @@
+import { isSafeDocumentLink } from '@/lib/filePreview';
import { isIosDevice } from '@/lib/platform';
// Pure decisions behind the PDF preview (components/ui/pdf-pages.tsx), kept free of pdf.js so they
@@ -81,3 +82,83 @@ export function pageIndexAt(tops: readonly number[], y: number): number {
}
return found;
}
+
+// ── Links ─────────────────────────────────────────────────────────────────────
+// The fields of a pdf.js link annotation the reader uses (``page.getAnnotations()`` data).
+export type PdfLinkAnnotation = {
+ subtype?: string;
+ annotationFlags?: number;
+ rect?: ArrayLike<number> | null;
+ quadPoints?: ArrayLike<number> | null;
+ /** A link pdf.js validated as absolute (http, https, ftp, mailto, tel). */
+ url?: string;
+ /** A named destination (string) or an explicit one ([page, {name}, ...args]). */
+ dest?: unknown;
+};
+
+export type PdfLinkTarget = { kind: 'url'; href: string } | { kind: 'dest'; dest: string | readonly unknown[] };
+export type PdfRect = [number, number, number, number];
+
+const HIDDEN_FLAG = 0x2;
+
+/**
+ * Where a link annotation goes: a web or mail link to open in a new tab, or a destination inside
+ * the document. Anything else — scripts, launch and file actions, non-web schemes, hidden links —
+ * is not offered at all.
+ */
+export function pdfLinkTarget(link: PdfLinkAnnotation, base: string): PdfLinkTarget | null {
+ if (link.subtype !== 'Link' || ((link.annotationFlags ?? 0) & HIDDEN_FLAG) !== 0) return null;
+ if (typeof link.url === 'string' && link.url) return isSafeDocumentLink(link.url, base) ? { kind: 'url', href: link.url } : null;
+ if (typeof link.dest === 'string' && link.dest) return { kind: 'dest', dest: link.dest };
+ if (Array.isArray(link.dest) && link.dest.length > 0) return { kind: 'dest', dest: link.dest };
+ return null;
+}
+
+/** The clickable areas of a link, in PDF user space: one per quadrilateral, or else its rectangle. */
+export function pdfLinkAreas(link: PdfLinkAnnotation): PdfRect[] {
+ const quads = link.quadPoints;
+ if (quads && quads.length >= 8 && quads.length % 8 === 0) {
+ const areas: PdfRect[] = [];
+ for (let i = 0; i < quads.length; i += 8) {
+ const xs = [quads[i], quads[i + 2], quads[i + 4], quads[i + 6]];
+ const ys = [quads[i + 1], quads[i + 3], quads[i + 5], quads[i + 7]];
+ areas.push([Math.min(...xs), Math.min(...ys), Math.max(...xs), Math.max(...ys)]);
+ }
+ return areas;
+ }
+ const r = link.rect;
+ if (!r || r.length !== 4) return [];
+ return [[Math.min(r[0], r[2]), Math.min(r[1], r[3]), Math.max(r[0], r[2]), Math.max(r[1], r[3])]];
+}
+
+/**
+ * The point an explicit destination asks to show, in PDF user space; ``null`` where the destination
+ * leaves that coordinate unchanged (or names no point at all, as Fit does).
+ */
+export function pdfDestPoint(dest: readonly unknown[]): { x: number | null; y: number | null } {
+ const kind = (dest[1] as { name?: unknown } | null | undefined)?.name;
+ const num = (value: unknown) => (typeof value === 'number' && Number.isFinite(value) ? value : null);
+ switch (kind) {
+ case 'XYZ':
+ return { x: num(dest[2]), y: num(dest[3]) };
+ case 'FitH':
+ case 'FitBH':
+ return { x: null, y: num(dest[2]) };
+ case 'FitV':
+ case 'FitBV':
+ return { x: num(dest[2]), y: null };
+ case 'FitR':
+ return { x: num(dest[2]), y: num(dest[5]) };
+ default:
+ return { x: null, y: null };
+ }
+}
+
+/**
+ * Which scroll axes a destination point fixes once the page is on screen: a page turned by a
+ * quarter (/Rotate 90 or 270) shows its x along the vertical and its y along the horizontal.
+ */
+export function pdfDestAxes(point: { x: number | null; y: number | null }, rotation: number): { left: boolean; top: boolean } {
+ const quarterTurn = (((rotation % 360) + 360) % 360) % 180 !== 0;
+ return quarterTurn ? { left: point.y !== null, top: point.x !== null } : { left: point.x !== null, top: point.y !== null };
+}