Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(reading): stop the annotation popover disarming the toolbar

Bingxi Zhao (Frank)3466cf0cb06f
diff --git a/web/components/reading/ReaderPane.tsx b/web/components/reading/ReaderPane.tsx
index 4700dd453..0644e4cd6 100644
--- a/web/components/reading/ReaderPane.tsx
+++ b/web/components/reading/ReaderPane.tsx
@@ -158,6 +158,28 @@ export function ReaderPane({
null,
);
const [selection, setSelection] = useState<SelectionPayload | null>(null);
+ // Whether the annotation popover is showing, kept apart from whether there
+ // IS a selection. They used to be the same flag, and the popover dismisses
+ // itself on a document-level, capture-phase `pointerdown` — so pressing a
+ // toolbar button cleared `selection` before the click could land, React
+ // re-rendered the button as `disabled` (all four selection-gated actions
+ // declare `requires: ["selection"]`), and the browser then refused to
+ // dispatch the rest of the activation sequence to a disabled control. No
+ // fetch, no spinner, no error: 引导我 / 翻译成英文 / 翻译成中文 / 解释词汇
+ // have been unreachable by pointer since the toolbar shipped.
+ const [popoverOpen, setPopoverOpen] = useState(false);
+
+ /** One place to open a selection, so the popover cannot drift out of step. */
+ const openSelection = useCallback((payload: SelectionPayload | null) => {
+ setSelection(payload);
+ setPopoverOpen(payload !== null);
+ }, []);
+
+ /** Drop the selection entirely — it is stale, not merely unfocused. */
+ const clearSelection = useCallback(() => {
+ setSelection(null);
+ setPopoverOpen(false);
+ }, []);
const [jump, setJump] = useState<JumpRequest | null>(null);
// `null` = follow the document: show the panel once there is something in it.
// An empty panel is a whole column of nothing next to the page, which reads as
@@ -645,10 +667,10 @@ export function ReaderPane({
updated_at: now,
},
);
- setSelection(null);
+ clearSelection();
window.getSelection()?.removeAllRanges();
},
- [selection, material, saveMark],
+ [selection, material, saveMark, clearSelection],
);
const askAboutSelection = useCallback(() => {
@@ -662,9 +684,9 @@ export function ReaderPane({
},
}),
);
- setSelection(null);
+ clearSelection();
window.getSelection()?.removeAllRanges();
- }, [selection, material]);
+ }, [selection, material, clearSelection]);
// -- export --------------------------------------------------------------
@@ -869,6 +891,7 @@ export function ReaderPane({
<ReadingExtensionBar
materialId={material.material_id}
locator={currentLocator}
+ selectionLocator={selection?.locator}
selection={selection?.quote}
onError={setError}
/>
@@ -903,7 +926,7 @@ export function ReaderPane({
annotations={annotations}
jump={materialJump}
highlightedAnnotationId={activeAnnotationId}
- onSelection={setSelection}
+ onSelection={openSelection}
onAnnotationClick={(annotation) =>
setActiveAnnotationId(annotation.annotation_id)
}
@@ -920,7 +943,7 @@ export function ReaderPane({
annotations={annotations}
jump={materialJump}
highlightedAnnotationId={activeAnnotationId}
- onSelection={setSelection}
+ onSelection={openSelection}
onAnnotationClick={(annotation) =>
setActiveAnnotationId(annotation.annotation_id)
}
@@ -936,7 +959,7 @@ export function ReaderPane({
annotations={annotations}
jump={materialJump}
highlightedAnnotationId={activeAnnotationId}
- onSelection={setSelection}
+ onSelection={openSelection}
onAnnotationClick={(annotation) =>
setActiveAnnotationId(annotation.annotation_id)
}
@@ -964,7 +987,10 @@ export function ReaderPane({
)}
</div>
- {selection && material && (
+ {/* `popoverOpen` and not just `selection`: dismissal now leaves the
+ selection in place for the toolbar, so gating the mount on the
+ selection alone would make Escape and outside-click stop working. */}
+ {popoverOpen && selection && material && (
<AnnotationPopover
anchor={selection.anchor}
quote={selection.quote}
@@ -973,7 +999,9 @@ export function ReaderPane({
onNote={(note, color) => commitSelection("note", color, note)}
onCitation={(color) => commitSelection("citation", color)}
onAsk={askAboutSelection}
- onDismiss={() => setSelection(null)}
+ // Closes the popover WITHOUT dropping the selection, so the
+ // toolbar's selection-gated actions stay reachable.
+ onDismiss={() => setPopoverOpen(false)}
/>
)}
</div>
diff --git a/web/components/reading/ReadingExtensionBar.tsx b/web/components/reading/ReadingExtensionBar.tsx
index efc4349a8..4fff4fea9 100644
--- a/web/components/reading/ReadingExtensionBar.tsx
+++ b/web/components/reading/ReadingExtensionBar.tsx
@@ -32,11 +32,20 @@ type TranslationResult = {
export function ReadingExtensionBar({
materialId,
locator,
+ selectionLocator,
selection,
onError,
}: {
materialId: string;
locator: number;
+ /**
+ * The unit the selection was made in, when there is one.
+ *
+ * `locator` is the *viewport* locator and drifts as the reader scrolls. The
+ * server verifies the quote against the text of the unit it is told about
+ * and 400s when they disagree, so a selection has to travel with its own.
+ */
+ selectionLocator?: number;
selection?: string;
onError: (message: string) => void;
}) {
@@ -66,8 +75,17 @@ export function ReadingExtensionBar({
};
}, [onError]);
+ // Two effects, because the two things they clean up move on different
+ // clocks. A result belongs to the document: keyed on `locator` as well, an
+ // ordinary scroll erased a card the reader was still reading, since
+ // `locator` is the scroll-derived *viewport* locator.
useEffect(() => {
setResult(null);
+ }, [materialId]);
+
+ // Speech, on the other hand, must stop the moment the reader navigates
+ // away from the passage being read aloud — so this one keeps both keys.
+ useEffect(() => {
return () => {
window.speechSynthesis?.cancel();
setSpeaking(false);
@@ -94,7 +112,7 @@ export function ReadingExtensionBar({
extension.id,
action.id,
{
- locator,
+ locator: selection?.trim() ? (selectionLocator ?? locator) : locator,
selection: selection || "",
locale: i18n.language,
},
@@ -127,15 +145,23 @@ export function ReadingExtensionBar({
<div className="flex shrink-0 gap-1.5 overflow-x-auto border-b border-[var(--border)] bg-[color-mix(in_srgb,var(--muted)_25%,transparent)] px-2.5 py-2">
{actions.map(({ extension, action }) => {
const key = `${extension.id}:${action.id}`;
- const disabled =
- Boolean(busy) ||
- (action.requires.includes("selection") && !selection?.trim());
+ const needsSelection =
+ action.requires.includes("selection") && !selection?.trim();
+ // `busy === key`, not `Boolean(busy)`: an action can take the full
+ // 30s server timeout, and disabling all six meanwhile is
+ // indistinguishable from the toolbar being broken.
+ const disabled = busy === key || needsSelection;
const builtInLabel = builtInActionLabel(extension.id, action.id);
return (
<button
key={key}
type="button"
disabled={disabled}
+ title={
+ needsSelection
+ ? t("Select text in the document first.")
+ : undefined
+ }
onClick={() => void run(extension, action)}
className="inline-flex h-8 min-w-[88px] flex-1 items-center justify-center gap-1.5 rounded-lg border border-[var(--border)] bg-[var(--card)] px-2 text-xs font-medium text-[var(--foreground)] transition hover:bg-[var(--muted)] disabled:opacity-50"
>
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index e60a964c0..5611e5b2f 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -4000,5 +4000,6 @@
"attachments": "attachments",
"references": "references",
"That question is no longer waiting for an answer, so this was sent as a new message.": "That question is no longer waiting for an answer, so this was sent as a new message.",
- "A knowledge base name cannot contain {{chars}} — these separate paths and URLs.": "A knowledge base name cannot contain {{chars}} — these separate paths and URLs."
+ "A knowledge base name cannot contain {{chars}} — these separate paths and URLs.": "A knowledge base name cannot contain {{chars}} — these separate paths and URLs.",
+ "Select text in the document first.": "Select text in the document first."
}
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 3579cd317..5f199113e 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -4000,5 +4000,6 @@
"attachments": "附件",
"references": "引用",
"That question is no longer waiting for an answer, so this was sent as a new message.": "这道题已经不再等待作答,所以这条内容作为新消息发送了。",
- "A knowledge base name cannot contain {{chars}} — these separate paths and URLs.": "知识库名称不能包含 {{chars}} —— 这些字符会切断路径和 URL。"
+ "A knowledge base name cannot contain {{chars}} — these separate paths and URLs.": "知识库名称不能包含 {{chars}} —— 这些字符会切断路径和 URL。",
+ "Select text in the document first.": "请先在文档中选中文字。"
}
diff --git a/web/tests/reading-toolbar-selection.spec.tsx b/web/tests/reading-toolbar-selection.spec.tsx
new file mode 100644
index 000000000..f17033079
--- /dev/null
+++ b/web/tests/reading-toolbar-selection.spec.tsx
@@ -0,0 +1,154 @@
+import { act, render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { initI18n } from "@/i18n/init";
+
+initI18n("en");
+
+const api = vi.hoisted(() => ({
+ runReadingExtension: vi.fn(
+ async (
+ _materialId: string,
+ _extensionId: string,
+ _actionId: string,
+ _body: { locator: number; selection: string; locale: string },
+ ) => ({
+ type: "card",
+ title: "Translation",
+ message: "",
+ payload: { translation: "斜率" },
+ }),
+ ),
+ listReadingExtensions: vi.fn(async () => [
+ {
+ id: "translation",
+ version: "1.0.0",
+ name: "Translation",
+ actions: [
+ {
+ id: "translate_zh",
+ label: "Translate to Chinese",
+ requires: ["selection"],
+ },
+ ],
+ result_types: ["card"],
+ },
+ ]),
+}));
+
+/** The document view is stubbed down to "report this selection upward". */
+const view = vi.hoisted(() => ({
+ select: null as null | ((payload: unknown) => void),
+}));
+
+vi.mock("@/lib/reading-api", async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ ...api,
+ fetchExport: vi.fn(),
+ getMaterial: vi.fn(async () => null),
+ getReadingPosition: vi.fn(async () => ({ locator: 1, source_anchor: "" })),
+ saveReadingPosition: vi.fn(),
+}));
+
+vi.mock("@/components/reading/PdfDocumentView", () => ({
+ PdfDocumentView: ({
+ onSelection,
+ }: {
+ onSelection: (payload: unknown) => void;
+ }) => {
+ view.select = onSelection;
+ return <div data-testid="doc" />;
+ },
+}));
+
+vi.mock("@/components/reading/EpubDocumentView", () => ({
+ EpubDocumentView: () => null,
+}));
+
+vi.mock("@/components/reading/TextUnitView", () => ({
+ TextUnitView: () => null,
+ unitLabel: () => "page",
+}));
+
+vi.mock("@/components/reading/AnnotationList", () => ({
+ AnnotationList: () => null,
+}));
+
+const material = {
+ material_id: "m1",
+ title: "Understanding Deep Learning",
+ filename: "udl.pdf",
+ unit: "page",
+ mime: "application/pdf",
+ render_mode: "raw",
+ has_raw_view: true,
+ unit_count: 10,
+};
+
+vi.mock("@/context/ReadingContext", () => ({
+ useReading: () => ({
+ material,
+ annotations: [],
+ loading: false,
+ error: "",
+ openMaterial: vi.fn(),
+ closeMaterial: vi.fn(),
+ saveMark: vi.fn(),
+ removeMark: vi.fn(),
+ mergeMark: vi.fn(),
+ dismissError: vi.fn(),
+ setError: vi.fn(),
+ reportViewport: vi.fn(),
+ }),
+}));
+
+const { ReaderPane } = await import("@/components/reading/ReaderPane");
+
+describe("reading toolbar with a live selection", () => {
+ beforeEach(() => {
+ api.runReadingExtension.mockClear();
+ view.select = null;
+ });
+
+ /**
+ * The regression. `AnnotationPopover` dismisses itself on a document-level,
+ * CAPTURE-phase pointerdown, and that used to clear the reader's selection.
+ * Pressing a toolbar button therefore disabled it between `pointerdown` and
+ * `click` — and a disabled control receives neither — so 翻译成中文 and the
+ * three other selection-gated actions did nothing at all, silently.
+ */
+ it("runs a selection-gated action when the button is pressed", async () => {
+ const user = userEvent.setup();
+ render(<ReaderPane onClose={() => undefined} />);
+
+ await waitFor(() => expect(view.select).not.toBeNull());
+ act(() =>
+ view.select?.({
+ locator: 4,
+ quote: "the slope of the line",
+ rects: [],
+ anchor: { x: 100, y: 200 },
+ }),
+ );
+
+ const button = await screen.findByRole("button", {
+ name: "Translate to Chinese",
+ });
+ await waitFor(() => expect(button).toBeEnabled());
+ await user.click(button);
+
+ await waitFor(() => expect(api.runReadingExtension).toHaveBeenCalled());
+ const call = api.runReadingExtension.mock.calls[0];
+ expect(call).toBeDefined();
+ const [materialId, extensionId, actionId, body] = call;
+ expect(materialId).toBe("m1");
+ expect(extensionId).toBe("translation");
+ expect(actionId).toBe("translate_zh");
+ expect(body.selection).toBe("the slope of the line");
+ // The selection's own unit, not the scroll-derived viewport locator: the
+ // server verifies the quote against the text of the unit it is told about
+ // and 400s when they disagree.
+ expect(body.locator).toBe(4);
+ });
+});