#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
feat(read-aloud): Read aloud from selected text (#8488)
EthanHealy01525e0bf863c4
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.tomlindex 9a736fb639..8967130fa0 100644--- a/frontend/editor/public/locales/en-US/translation.toml+++ b/frontend/editor/public/locales/en-US/translation.toml@@ -13713,6 +13713,7 @@ noPdfProvided = "No PDF provided"onlyPdfSupported = "This file format is not supported for preview."pageNavigation = "Page navigation"previousPage = "Previous Page"+readAloudFromHere = "Read aloud from here"saveChangesErrorBody = "The document could not be saved. Try again."saveChangesErrorTitle = "Could not save changes"singlePageView = "Single Page View"diff --git a/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx b/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsxindex f43757bd9a..13e1096dd8 100644--- a/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx+++ b/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx@@ -1782,6 +1782,7 @@ const EmbedPdfViewerContent = ({isScaleCalibrationActive,startScaleCalibration,cancelScaleCalibration,+ currentFile,);// Auto-fetch form fields when a PDF is loaded in the viewer.diff --git a/frontend/editor/src/core/components/viewer/TextSelectionMenu.tsx b/frontend/editor/src/core/components/viewer/TextSelectionMenu.tsxindex e5761a2478..468c87f2df 100644--- a/frontend/editor/src/core/components/viewer/TextSelectionMenu.tsx+++ b/frontend/editor/src/core/components/viewer/TextSelectionMenu.tsx@@ -26,6 +26,11 @@ import {import { MARKUP_ANNOTATION_COLORS } from "@app/components/viewer/annotationDefaults";import { alert } from "@app/components/toast";import { getExternalHref } from "@app/utils/externalUrl";+import {+ READ_ALOUD_FROM_SELECTION_EVENT,+ glyphPositionRatio,+ type ReadAloudFromSelectionDetail,+} from "@app/components/viewer/readAloudFromSelection";import "@app/components/viewer/TextSelectionMenu.css";export type TextSelectionMenuProps = SelectionSelectionMenuProps & {@@ -265,6 +270,43 @@ function TextSelectionMenuInner({],);+ const canReadAloud =+ typeof window !== "undefined" && "speechSynthesis" in window;++ const handleReadAloudFromHere = useCallback(() => {+ const state = selection?.getState(documentId);+ if (!selection || !state?.selection) return;+ const originalSelection = state.selection;+ const { page, index } = originalSelection.start;+ // The text task resolves asynchronously; a selection made in the meantime+ // must not be the one read aloud and cleared.+ const stillSelected = () =>+ selection.getState(documentId).selection === originalSelection;+ const dispatch = (selectedText: string) => {+ if (!stillSelected()) return;+ window.dispatchEvent(+ new CustomEvent<ReadAloudFromSelectionDetail>(+ READ_ALOUD_FROM_SELECTION_EVENT,+ {+ detail: {+ pageNumber: page + 1,+ selectedText,+ approximatePosition: glyphPositionRatio(+ state.geometry[page],+ index,+ ),+ },+ },+ ),+ );+ selection.clear(documentId);+ };+ selection.getSelectedText(documentId).wait(+ (texts) => dispatch(texts[0] ?? ""),+ () => dispatch(""),+ );+ }, [selection, documentId]);+const handleRedact = useCallback(() => {if (!documentId || readOnly) return;const selections = selection?.getFormattedSelection(documentId) ?? [];@@ -453,6 +495,25 @@ function TextSelectionMenuInner({</Tooltip></>)}++ {canReadAloud && (+ <Tooltip+ label={t("viewer.readAloudFromHere", "Read aloud from here")}+ withArrow+ >+ <button+ type="button"+ className="embedpdf-text-selection-btn"+ onClick={handleReadAloudFromHere}+ aria-label={t(+ "viewer.readAloudFromHere",+ "Read aloud from here",+ )}+ >+ <Icon name="volume-2" size={20} />+ </button>+ </Tooltip>+ )}</div></div>,document.body,diff --git a/frontend/editor/src/core/components/viewer/readAloudFromSelection.test.ts b/frontend/editor/src/core/components/viewer/readAloudFromSelection.test.tsnew file mode 100644index 0000000000..58d2480346--- /dev/null+++ b/frontend/editor/src/core/components/viewer/readAloudFromSelection.test.ts@@ -0,0 +1,61 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";+import type { PdfPageGeometry } from "@embedpdf/models";+import {+ findReadAloudStartIndex,+ glyphPositionRatio,+} from "@app/components/viewer/readAloudFromSelection";++describe("findReadAloudStartIndex", () => {+ const text = "The cat sat. The dog ran. The end";++ it("finds the selection in the page text", () => {+ expect(findReadAloudStartIndex(text, "dog ran", 0)).toBe(17);+ });++ it("picks the repeated match nearest the selection's position", () => {+ expect(findReadAloudStartIndex(text, "The", 0)).toBe(0);+ expect(findReadAloudStartIndex(text, "The", 0.45)).toBe(13);+ expect(findReadAloudStartIndex(text, "The", 1)).toBe(26);+ });++ it("prefers a whole word over a nearer match inside a longer word", () => {+ expect(findReadAloudStartIndex("concatenate cat", "cat", 0)).toBe(12);+ });++ it("snaps a selection starting mid-word to the word start", () => {+ expect(findReadAloudStartIndex(text, "og ran", 0)).toBe(17);+ });++ it("falls back to the first word when spacing differs", () => {+ expect(findReadAloudStartIndex(text, "dog\nran fast", 0)).toBe(17);+ });++ it("starts at the page start when the selection is not found", () => {+ expect(findReadAloudStartIndex(text, "bird", 0.5)).toBe(0);+ expect(findReadAloudStartIndex(text, "", 0.5)).toBe(0);+ });+});++describe("glyphPositionRatio", () => {+ const run = (charStart: number, glyphCount: number) => ({+ rect: { x: 0, y: 0, width: 0, height: 0 },+ charStart,+ glyphs: Array.from({ length: glyphCount }, () => ({+ x: 0,+ y: 0,+ width: 0,+ height: 0,+ flags: 0,+ })),+ });++ it("divides the glyph index by the page's glyph count", () => {+ const geometry: PdfPageGeometry = { runs: [run(0, 50), run(50, 50)] };+ expect(glyphPositionRatio(geometry, 25)).toBe(0.25);+ });++ it("is 0 without geometry", () => {+ expect(glyphPositionRatio(undefined, 25)).toBe(0);+ });+});diff --git a/frontend/editor/src/core/components/viewer/readAloudFromSelection.ts b/frontend/editor/src/core/components/viewer/readAloudFromSelection.tsnew file mode 100644index 0000000000..98892f3803--- /dev/null+++ b/frontend/editor/src/core/components/viewer/readAloudFromSelection.ts@@ -0,0 +1,85 @@+import type { PdfPageGeometry } from "@embedpdf/models";++/**+ * Window event the text selection menu dispatches to start read-aloud at a+ * selection. Read-aloud state lives in the hook behind the viewer's workbench+ * bar and no context exposes it, so the menu has nothing to call directly.+ */+export const READ_ALOUD_FROM_SELECTION_EVENT =+ "stirling:read-aloud-from-selection";++export interface ReadAloudFromSelectionDetail {+ /** 1-based. */+ pageNumber: number;+ /** Empty when the document forbids copying its text. */+ selectedText: string;+ /** Where the selection starts, as a 0..1 fraction of the page's glyphs. */+ approximatePosition: number;+}++export function glyphPositionRatio(+ geometry: PdfPageGeometry | undefined,+ glyphIndex: number,+): number {+ const lastRun = geometry?.runs[geometry.runs.length - 1];+ const glyphCount = lastRun ? lastRun.charStart + lastRun.glyphs.length : 0;+ return glyphCount > 0 ? Math.min(1, glyphIndex / glyphCount) : 0;+}++const WORD_CHAR = /[\p{L}\p{N}]/u;++function isWholeWordAt(text: string, index: number, length: number): boolean {+ const before = text[index - 1];+ const after = text[index + length];+ return (+ (before === undefined || !WORD_CHAR.test(before)) &&+ (after === undefined || !WORD_CHAR.test(after))+ );+}++function nearestMatch(+ text: string,+ needle: string,+ target: number,+ wholeWordOnly: boolean,+): number {+ let best = -1;+ for (+ let i = text.indexOf(needle);+ i !== -1;+ i = text.indexOf(needle, i + 1)+ ) {+ if (wholeWordOnly && !isWholeWordAt(text, i, needle.length)) continue;+ if (best === -1 || Math.abs(i - target) < Math.abs(best - target)) {+ best = i;+ }+ }+ return best;+}++/**+ * Char index in a page's read-aloud text at which to start speaking a+ * selection, snapped back to the start of its word; 0 when it is not found.+ * The selection comes from PDFium and the read-aloud text from pdf.js, so the+ * two can disagree on spacing: the first word alone is tried when the whole+ * selection is not found. Whole-word matches win over matches inside a longer+ * word, which only a selection starting mid-word needs, and repeated matches+ * go to the one nearest `approximatePosition`.+ */+export function findReadAloudStartIndex(+ spokenText: string,+ selectedText: string,+ approximatePosition: number,+): number {+ const words = selectedText.split(/\s+/).filter(Boolean);+ if (words.length === 0) return 0;++ const target = approximatePosition * spokenText.length;+ for (const needle of [words.join(" "), words[0]]) {+ for (const wholeWordOnly of [true, false]) {+ const match = nearestMatch(spokenText, needle, target, wholeWordOnly);+ if (match !== -1) return spokenText.lastIndexOf(" ", match) + 1;+ }+ }+ return 0;+}diff --git a/frontend/editor/src/core/components/viewer/useViewerReadAloud.ts b/frontend/editor/src/core/components/viewer/useViewerReadAloud.tsindex 5352ffc748..587e2fb79b 100644--- a/frontend/editor/src/core/components/viewer/useViewerReadAloud.ts+++ b/frontend/editor/src/core/components/viewer/useViewerReadAloud.ts@@ -1,6 +1,10 @@import { useCallback, useEffect, useRef, useState } from "react";import { computeReadAloudHighlightRect } from "@app/components/viewer/readAloudHighlight";-import { useFileSelectors } from "@app/contexts/FileContext";+import {+ READ_ALOUD_FROM_SELECTION_EVENT,+ findReadAloudStartIndex,+ type ReadAloudFromSelectionDetail,+} from "@app/components/viewer/readAloudFromSelection";import { useViewer } from "@app/contexts/ViewerContext";import { useStopReadAloudOnNavigation } from "@app/components/viewer/useStopReadAloudOnNavigation";import { pdfWorkerManager } from "@app/services/pdfWorkerManager";@@ -58,9 +62,26 @@ function createHighlightElement(return highlight;}-export function useViewerReadAloud(defaultLanguage?: string) {+/** -1 when `charIndex` falls on the space between two words. */+function wordIndexAtChar(words: string[], charIndex: number): number {+ let wordStart = 0;+ for (let i = 0; i < words.length; i++) {+ const wordEnd = wordStart + words[i].length;+ if (charIndex < wordEnd) return charIndex >= wordStart ? i : -1;+ wordStart = wordEnd + 1;+ }+ return -1;+}++/**+ * `displayedFile` is the document the viewer is showing, preview included:+ * read-aloud and the selection menu must speak the same file the user sees.+ */+export function useViewerReadAloud(+ defaultLanguage?: string,+ displayedFile?: StirlingFile | File | null,+) {const viewer = useViewer();- const selectors = useFileSelectors();const [isReadingAloud, setIsReadingAloud] = useState(false);const [speechRate, setSpeechRate] = useState(1);@@ -85,7 +106,10 @@ export function useViewerReadAloud(defaultLanguage?: string) {const restartingSpeechRef = useRef(false);const restartTimeoutRef = useRef<number | null>(null);const pageAdvanceTimeoutRef = useRef<number | null>(null);- const currentFileRef = useRef<StirlingFile | null>(null);+ const currentFileRef = useRef<StirlingFile | File | null>(null);+ // Bumped whenever reading starts or stops; async work started under an+ // older value must not speak or tear down the session that replaced it.+ const sessionRef = useRef(0);const totalPagesRef = useRef(0);const speechRateRef = useRef(1); // Keep track of current rate without recreating dependent functionsconst speechLanguageRef = useRef(defaultLanguage || "en-US");@@ -210,16 +234,23 @@ export function useViewerReadAloud(defaultLanguage?: string) {}, []);const stopReadingAloud = useCallback(() => {- if (typeof window !== "undefined" && window.speechSynthesis) {- window.speechSynthesis.cancel();+ sessionRef.current++;+ restartingSpeechRef.current = false;+ if (restartTimeoutRef.current !== null) {+ window.clearTimeout(restartTimeoutRef.current);+ restartTimeoutRef.current = null;}if (pageAdvanceTimeoutRef.current !== null) {window.clearTimeout(pageAdvanceTimeoutRef.current);pageAdvanceTimeoutRef.current = null;}+ if (typeof window !== "undefined" && window.speechSynthesis) {+ window.speechSynthesis.cancel();+ }clearHighlights();setIsReadingAloud(false);currentFileRef.current = null;+ currentWordIndexRef.current = 0;utteranceRef.current = null;cleanupReadingSession();}, [clearHighlights, cleanupReadingSession]);@@ -227,6 +258,19 @@ export function useViewerReadAloud(defaultLanguage?: string) {// Stop reading when navigating away (workbench, file, or window change)useStopReadAloudOnNavigation(isReadingAloud, stopReadingAloud);+ // Stop reading when the displayed file itself is replaced. Navigation+ // watches the workbench and active index, but a preview or re-upload can+ // swap the file underneath both; without this, a pending read resolves+ // for the old file and speaks it over the replacement.+ const previousDisplayedFileRef = useRef(displayedFile);+ useEffect(() => {+ if (previousDisplayedFileRef.current === displayedFile) return;+ previousDisplayedFileRef.current = displayedFile;+ if (isReadingAloud) {+ stopReadingAloud();+ }+ }, [displayedFile, isReadingAloud, stopReadingAloud]);+const highlightWord = useCallback((wordIndex: number, words: string[], pageNumber: number) => {clearHighlights();@@ -269,14 +313,16 @@ export function useViewerReadAloud(defaultLanguage?: string) {[clearHighlights],);+ /**+ * Parses one page's text for speaking. Null when the page has no text or+ * when `session` was superseded mid-parse, so callers check the session+ * before treating null as an empty page.+ */const readPage = useCallback(async (currentFile: StirlingFile | File,pageNumber: number,- options?: {- preserveSpeechState?: boolean;- highlightWordIndex?: number;- },+ session: number,) => {let pdfDoc: Awaited<ReturnType<typeof pdfWorkerManager.createDocument>@@ -289,14 +335,20 @@ export function useViewerReadAloud(defaultLanguage?: string) {if (cachedPdfDocRef.current) {pdfDoc = cachedPdfDocRef.current;} else {- pdfDoc = await pdfWorkerManager.createDocument(+ const createdDoc = await pdfWorkerManager.createDocument(await currentFile.arrayBuffer(),);+ if (session !== sessionRef.current) {+ pdfWorkerManager.destroyDocument(createdDoc);+ return null;+ }+ pdfDoc = createdDoc;cachedPdfDocRef.current = pdfDoc;}const page = await pdfDoc.getPage(pageNumber);const textContent = await page.getTextContent();+ if (session !== sessionRef.current) return null;// The highlight is rendered inside the page element, so we keep geometry in// page-local coordinates and let the viewer's own rotation transform it.const viewportTransform = page.getViewport({ scale: zoom }).transform;@@ -382,22 +434,6 @@ export function useViewerReadAloud(defaultLanguage?: string) {}const words = spokenText.split(/\s+/).filter(Boolean);-- if (!options?.preserveSpeechState) {- speechTextRef.current = spokenText;- speechWordsRef.current = words;- speechCharIndexRef.current = 0;- currentWordIndexRef.current = 0;- }-- const highlightIndex = Math.max(- 0,- Math.min(- options?.highlightWordIndex ?? 0,- Math.max(words.length - 1, 0),- ),- );- highlightWord(highlightIndex, words, pageNumber);return { spokenText, words };} catch (error) {// Clear cache on error to avoid stale state@@ -407,7 +443,7 @@ export function useViewerReadAloud(defaultLanguage?: string) {throw error;}},- [highlightWord, viewer],+ [viewer],);const speakFromCharIndex = useCallback(@@ -442,6 +478,17 @@ export function useViewerReadAloud(defaultLanguage?: string) {return;}+ speechTextRef.current = spokenText;+ speechWordsRef.current = words;+ speechCharIndexRef.current = baseCharIndex;+ currentPageNumberRef.current = pageNumber;+ const startWordIndex = wordIndexAtChar(words, baseCharIndex);+ if (startWordIndex !== -1) {+ currentWordIndexRef.current = startWordIndex;+ highlightWord(startWordIndex, words, pageNumber);+ }++ const session = sessionRef.current;const utterance = new SpeechSynthesisUtterance(remainingText);utterance.rate = rateOverride ?? speechRateRef.current;const currentLang = languageOverride ?? speechLanguageRef.current;@@ -455,6 +502,7 @@ export function useViewerReadAloud(defaultLanguage?: string) {utterance.onstart = () => setIsReadingAloud(true);utterance.onend = () => {+ if (session !== sessionRef.current) return;utteranceRef.current = null;if (restartingSpeechRef.current) {return;@@ -480,7 +528,9 @@ export function useViewerReadAloud(defaultLanguage?: string) {const nextPageData = await readPage(currentFileRef.current,pageNumber + 1,+ session,);+ if (session !== sessionRef.current) return;if (!nextPageData) {currentFileRef.current = null;setIsReadingAloud(false);@@ -496,6 +546,7 @@ export function useViewerReadAloud(defaultLanguage?: string) {speechLanguageRef.current,);} catch (error) {+ if (session !== sessionRef.current) return;console.error("Read aloud page advance failed", error);currentFileRef.current = null;clearHighlights();@@ -513,6 +564,7 @@ export function useViewerReadAloud(defaultLanguage?: string) {cleanupReadingSession();};utterance.onerror = () => {+ if (session !== sessionRef.current) return;utteranceRef.current = null;if (restartingSpeechRef.current) {return;@@ -530,24 +582,24 @@ export function useViewerReadAloud(defaultLanguage?: string) {const absoluteCharIndex = baseCharIndex + event.charIndex;speechCharIndexRef.current = absoluteCharIndex;- let charCount = 0;- for (let i = 0; i < words.length; i++) {- const wordStart = charCount;- const wordEnd = charCount + words[i].length;- if (absoluteCharIndex >= wordStart && absoluteCharIndex < wordEnd) {- currentWordIndexRef.current = i;- currentPageNumberRef.current = pageNumber;- highlightWord(i, words, pageNumber);- break;- }- charCount = wordEnd + 1;- }+ const wordIndex = wordIndexAtChar(words, absoluteCharIndex);+ if (wordIndex === -1) return;+ currentWordIndexRef.current = wordIndex;+ currentPageNumberRef.current = pageNumber;+ highlightWord(wordIndex, words, pageNumber);};utteranceRef.current = utterance;window.speechSynthesis.speak(utterance);},- [clearHighlights, cleanupReadingSession, readPage, viewer.scrollActions],+ [+ clearHighlights,+ cleanupReadingSession,+ findVoiceForLanguage,+ highlightWord,+ readPage,+ viewer.scrollActions,+ ],);const refreshActiveHighlight = useCallback(() => {@@ -568,43 +620,22 @@ export function useViewerReadAloud(defaultLanguage?: string) {highlightWord(wordIndex, words, pageNumber);}, [isReadingAloud, highlightWord]);- const handleReadAloud = useCallback(async () => {- if (typeof window === "undefined" || !window.speechSynthesis) {- return;- }-- if (isReadingAloud) {- restartingSpeechRef.current = false;- if (pageAdvanceTimeoutRef.current !== null) {- window.clearTimeout(pageAdvanceTimeoutRef.current);- pageAdvanceTimeoutRef.current = null;- }- window.speechSynthesis.cancel();- clearHighlights();- setIsReadingAloud(false);- currentFileRef.current = null;- utteranceRef.current = null;- cleanupReadingSession();- return;- }-- try {- const selectedFiles = selectors.getSelectedFiles();- const currentFile =- selectedFiles[viewer.activeFileIndex] ?? selectedFiles[0];- if (!currentFile) return;- currentFileRef.current = currentFile;- totalPagesRef.current = viewer.getScrollState().totalPages || 0;-- setIsReadingAloud(true);+ const startReading = useCallback(+ async (+ pageNumber: number,+ findStartCharIndex?: (spokenText: string) => number,+ ) => {+ if (!displayedFile) return;+ const session = ++sessionRef.current;try {- const currentPage = viewer.getScrollState().currentPage || 1;- currentPageNumberRef.current = currentPage;- const pageData = await readPage(currentFile, currentPage);+ currentFileRef.current = displayedFile;+ totalPagesRef.current = viewer.getScrollState().totalPages || 0;++ setIsReadingAloud(true);+ const pageData = await readPage(displayedFile, pageNumber, session);+ if (session !== sessionRef.current) return;if (!pageData) {- currentFileRef.current = null;- setIsReadingAloud(false);- cleanupReadingSession();+ stopReadingAloud();return;}@@ -612,30 +643,53 @@ export function useViewerReadAloud(defaultLanguage?: string) {speakFromCharIndex(pageData.spokenText,pageData.words,- 0,- currentPage,+ findStartCharIndex?.(pageData.spokenText) ?? 0,+ pageNumber,speechRateRef.current,speechLanguageRef.current,);- } finally {- // readPage handles pdf worker cleanup+ } catch (error) {+ if (session !== sessionRef.current) return;+ console.error("Read aloud failed", error);+ stopReadingAloud();}- } catch (error) {- console.error("Read aloud failed", error);- currentFileRef.current = null;- clearHighlights();- setIsReadingAloud(false);- cleanupReadingSession();+ },+ [displayedFile, readPage, speakFromCharIndex, stopReadingAloud, viewer],+ );++ const handleReadAloud = useCallback(async () => {+ if (typeof window === "undefined" || !window.speechSynthesis) {+ return;+ }++ if (isReadingAloud) {+ stopReadingAloud();+ return;}- }, [- clearHighlights,- cleanupReadingSession,- highlightWord,- isReadingAloud,- selectors,- speakFromCharIndex,- viewer,- ]);++ await startReading(viewer.getScrollState().currentPage || 1);+ }, [isReadingAloud, startReading, stopReadingAloud, viewer]);++ useEffect(() => {+ const handleReadFromSelection = (event: Event) => {+ const { pageNumber, selectedText, approximatePosition } = (+ event as CustomEvent<ReadAloudFromSelectionDetail>+ ).detail;+ stopReadingAloud();+ void startReading(pageNumber, (spokenText) =>+ findReadAloudStartIndex(spokenText, selectedText, approximatePosition),+ );+ };+ window.addEventListener(+ READ_ALOUD_FROM_SELECTION_EVENT,+ handleReadFromSelection,+ );+ return () =>+ window.removeEventListener(+ READ_ALOUD_FROM_SELECTION_EVENT,+ handleReadFromSelection,+ );+ }, [startReading, stopReadingAloud]);const handleSpeechRateChange = useCallback((nextRate: number) => {@@ -693,25 +747,7 @@ export function useViewerReadAloud(defaultLanguage?: string) {});}, [refreshActiveHighlight, viewer]);- useEffect(() => {- return () => {- if (restartTimeoutRef.current !== null) {- window.clearTimeout(restartTimeoutRef.current);- }- if (pageAdvanceTimeoutRef.current !== null) {- window.clearTimeout(pageAdvanceTimeoutRef.current);- }- if (typeof window !== "undefined" && window.speechSynthesis) {- window.speechSynthesis.cancel();- }- restartingSpeechRef.current = false;- clearHighlights();- currentFileRef.current = null;- currentWordIndexRef.current = 0;- utteranceRef.current = null;- cleanupReadingSession();- };- }, [clearHighlights, cleanupReadingSession]);+ useEffect(() => stopReadingAloud, [stopReadingAloud]);const handleSpeechLanguageChange = useCallback((nextLanguage: string) => {diff --git a/frontend/editor/src/core/components/viewer/useViewerWorkbenchBarButtons.tsx b/frontend/editor/src/core/components/viewer/useViewerWorkbenchBarButtons.tsxindex 8acfff9fe7..3d6bfca343 100644--- a/frontend/editor/src/core/components/viewer/useViewerWorkbenchBarButtons.tsx+++ b/frontend/editor/src/core/components/viewer/useViewerWorkbenchBarButtons.tsx@@ -24,6 +24,7 @@ import { useRedaction, useRedactionMode } from "@app/contexts/RedactionContext";import { useViewerReadAloud } from "@app/components/viewer/useViewerReadAloud";import { RulerScaleSettingsButton } from "@app/components/viewer/RulerScaleSettingsButton";import type { MeasureScale } from "@app/utils/measurementTypes";+import type { StirlingFile } from "@app/types/fileContext";export function useViewerWorkbenchBarButtons(isRulerActive?: boolean,@@ -33,6 +34,7 @@ export function useViewerWorkbenchBarButtons(isScaleCalibrationActive?: boolean,startScaleCalibration?: () => void,cancelScaleCalibration?: () => void,+ displayedFile?: StirlingFile | File | null,) {const { t, i18n } = useTranslation();const viewer = useViewer();@@ -68,7 +70,7 @@ export function useViewerWorkbenchBarButtons(handleReadAloud,handleSpeechRateChange,handleSpeechLanguageChange,- } = useViewerReadAloud(i18n.language || "en-US");+ } = useViewerReadAloud(i18n.language || "en-US", displayedFile);useEffect(() => {return registerImmediatePanUpdate((newIsPanning) => {diff --git a/frontend/editor/src/core/tests/stubbed/unlocked-pdf-annotations.spec.ts b/frontend/editor/src/core/tests/stubbed/unlocked-pdf-annotations.spec.tsindex 5ffc08db56..f59d0b6094 100644--- a/frontend/editor/src/core/tests/stubbed/unlocked-pdf-annotations.spec.ts+++ b/frontend/editor/src/core/tests/stubbed/unlocked-pdf-annotations.spec.ts@@ -103,7 +103,7 @@ test("unlocked annotations render before opening comments and remain read-only",).toBeVisible();});-test("unlocked links remain navigable and text selection only offers copying", async ({+test("unlocked links remain navigable and text selection offers reading actions only", async ({page,}) => {await unlockFixture(page, "encrypted-links.pdf", 2);@@ -130,5 +130,8 @@ test("unlocked links remain navigable and text selection only offers copying", aawait expect(selectionMenu.getByRole("button", { name: "Copy", exact: true }),).toBeVisible();- await expect(selectionMenu.getByRole("button")).toHaveCount(1);+ // A password-opened document is view-only, so the menu offers reading actions+ // only: copy, plus read aloud when the browser can speak.+ const canSpeak = await page.evaluate(() => "speechSynthesis" in window);+ await expect(selectionMenu.getByRole("button")).toHaveCount(canSpeak ? 2 : 1);});