Skip to content

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

feat(reading): adapt built-in actions to learner age (#1419)

Bingxi Zhao (Frank)34251f7d81eb
diff --git a/web/components/reading/ReadingExtensionBar.tsx b/web/components/reading/ReadingExtensionBar.tsx
index 28a83c0ae..6ff9fd6d8 100644
--- a/web/components/reading/ReadingExtensionBar.tsx
+++ b/web/components/reading/ReadingExtensionBar.tsx
@@ -1,8 +1,16 @@
"use client";
import { useEffect, useMemo, useRef, useState } from "react";
-import { Loader2, Sparkles, Square, Volume2, X } from "lucide-react";
+import { BookOpenText, Loader2, PencilLine, Sparkles, Square, Volume2, X } from "lucide-react";
import { useTranslation } from "react-i18next";
+import { fetchAuthStatus } from "@/lib/auth";
+import { getOwnLearnerProfile } from "@/lib/profile-api";
+import {
+ primaryReadingActionRank,
+ readingActionClass,
+ resolveReadingAgeMode,
+ type ReadingAgeMode,
+} from "@/lib/reading-age-presentation";
import {
listReadingExtensions,
runReadingExtension,
@@ -30,6 +38,8 @@ type TranslationResult = {
note: string;
};
+const PRIMARY_ACTION_ICONS = [Volume2, BookOpenText, PencilLine] as const;
+
export function ReadingExtensionBar({
materialId,
locator,
@@ -58,6 +68,7 @@ export function ReadingExtensionBar({
const [result, setResult] = useState<ReadingExtensionResult | null>(null);
const [resultLocator, setResultLocator] = useState(locator);
const [speaking, setSpeaking] = useState(false);
+ const [ageMode, setAgeMode] = useState<ReadingAgeMode>("default");
function stopSpeaking() {
window.speechSynthesis?.cancel();
@@ -78,6 +89,30 @@ export function ReadingExtensionBar({
};
}, [onError]);
+ useEffect(() => {
+ let active = true;
+ void fetchAuthStatus().then(async (status) => {
+ const learnerMode = status?.preset === "learner" || Boolean(status?.learning_policy);
+ if (!learnerMode) {
+ if (active) setAgeMode("default");
+ return;
+ }
+ const profile = await getOwnLearnerProfile().catch(() => null);
+ if (active) {
+ setAgeMode(
+ resolveReadingAgeMode({
+ learnerMode,
+ profileAge: profile?.age,
+ policyAgeBand: status?.learning_policy?.age_band,
+ }),
+ );
+ }
+ });
+ return () => {
+ active = false;
+ };
+ }, []);
+
// 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
@@ -97,7 +132,13 @@ export function ReadingExtensionBar({
const actions = useMemo(
() =>
- extensions.flatMap((extension) => extension.actions.map((action) => ({ extension, action }))),
+ extensions
+ .flatMap((extension) => extension.actions.map((action) => ({ extension, action })))
+ .sort((left, right) => {
+ const leftRank = primaryReadingActionRank(`${left.extension.id}:${left.action.id}`);
+ const rightRank = primaryReadingActionRank(`${right.extension.id}:${right.action.id}`);
+ return (leftRank < 0 ? 3 : leftRank) - (rightRank < 0 ? 3 : rightRank);
+ }),
[extensions],
);
@@ -140,7 +181,10 @@ export function ReadingExtensionBar({
if (actions.length === 0) return null;
return (
<>
- <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">
+ <div
+ data-reading-presentation={ageMode}
+ 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 needsSelection = action.requires.includes("selection") && !selection?.trim();
@@ -149,6 +193,10 @@ export function ReadingExtensionBar({
// indistinguishable from the toolbar being broken.
const disabled = busy === key || needsSelection;
const builtInLabel = builtInActionLabel(extension.id, action.id);
+ const primaryRank = primaryReadingActionRank(key);
+ const Icon =
+ (ageMode !== "default" ? PRIMARY_ACTION_ICONS[primaryRank] : null) ?? Sparkles;
+ const iconSize = primaryRank >= 0 && ageMode === "early" ? 18 : 14;
return (
<button
key={key}
@@ -156,14 +204,22 @@ export function ReadingExtensionBar({
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"
+ className={readingActionClass(ageMode, key)}
>
{busy === key ? (
- <Loader2 size={14} className="animate-spin" />
+ <Loader2 size={iconSize} className="animate-spin" />
) : (
- <Sparkles size={14} />
+ <Icon size={iconSize} aria-hidden="true" />
)}
- <span className="truncate">{builtInLabel ? t(builtInLabel) : action.label}</span>
+ <span
+ className={
+ primaryRank >= 0 && ageMode !== "default"
+ ? "whitespace-nowrap text-center"
+ : "truncate text-center"
+ }
+ >
+ {builtInLabel ? t(builtInLabel) : action.label}
+ </span>
</button>
);
})}
diff --git a/web/lib/reading-age-presentation.ts b/web/lib/reading-age-presentation.ts
new file mode 100644
index 000000000..b12b968e1
--- /dev/null
+++ b/web/lib/reading-age-presentation.ts
@@ -0,0 +1,81 @@
+export type ReadingAgeMode = "early" | "young" | "older" | "default";
+
+type ReadingAgeInput = {
+ learnerMode: boolean;
+ profileAge?: number | null;
+ policyAgeBand?: string | null;
+};
+
+/** Keep a profile age private to the host; extensions only see their usual action input. */
+export function resolveReadingAgeMode({
+ learnerMode,
+ profileAge,
+ policyAgeBand,
+}: ReadingAgeInput): ReadingAgeMode {
+ if (!learnerMode) return "default";
+ if (
+ typeof profileAge === "number" &&
+ Number.isInteger(profileAge) &&
+ profileAge >= 3 &&
+ profileAge <= 120
+ ) {
+ if (profileAge <= 6) return "early";
+ if (profileAge <= 9) return "young";
+ if (profileAge <= 12) return "older";
+ return "default";
+ }
+ // Policy bands are coarser than profile ages. Never guess the 3–6 style
+ // from a 6–8 band, which also includes older learners.
+ if (policyAgeBand === "6-8") return "young";
+ if (policyAgeBand === "9-12") return "older";
+ return "default";
+}
+
+export const PRIMARY_READING_ACTIONS = [
+ "read_aloud:read",
+ "vocabulary:explain",
+ "quiz:start",
+] as const;
+
+export function primaryReadingActionRank(key: string): number {
+ return PRIMARY_READING_ACTIONS.findIndex((candidate) => candidate === key);
+}
+
+const baseButton =
+ "inline-flex min-w-[88px] flex-1 items-center justify-center gap-1.5 border focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-600 focus-visible:ring-offset-2 disabled:opacity-50";
+
+const adultButton =
+ "h-8 rounded-lg border-[var(--border)] bg-[var(--card)] px-2 text-xs font-medium text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]";
+
+const learnerButtons: Record<Exclude<ReadingAgeMode, "default">, string> = {
+ early:
+ "min-h-14 min-w-[112px] w-max flex-none flex-col gap-0.5 rounded-[20px] border-2 px-3 py-1 text-xs font-bold leading-tight motion-safe:animate-[fade-in_220ms_ease-out_both] motion-safe:transition-transform motion-safe:hover:-translate-y-0.5 motion-safe:active:translate-y-0.5",
+ young:
+ "min-h-12 min-w-[100px] w-max flex-none rounded-2xl border-2 px-3 text-sm font-semibold motion-safe:transition-transform motion-safe:hover:-translate-y-0.5 motion-safe:active:scale-[.98]",
+ older:
+ "min-h-11 w-max flex-none rounded-xl border px-3 text-sm font-medium motion-safe:transition-transform motion-safe:active:scale-[.99]",
+};
+
+const tones: Record<Exclude<ReadingAgeMode, "default">, Record<string, string>> = {
+ early: {
+ "read_aloud:read": "border-emerald-300 bg-emerald-100 text-emerald-950 hover:bg-emerald-200",
+ "vocabulary:explain": "border-amber-300 bg-amber-100 text-amber-950 hover:bg-amber-200",
+ "quiz:start": "border-sky-300 bg-sky-100 text-sky-950 hover:bg-sky-200",
+ },
+ young: {
+ "read_aloud:read": "border-emerald-200 bg-emerald-50 text-emerald-950 hover:bg-emerald-100",
+ "vocabulary:explain": "border-amber-200 bg-amber-50 text-amber-950 hover:bg-amber-100",
+ "quiz:start": "border-sky-200 bg-sky-50 text-sky-950 hover:bg-sky-100",
+ },
+ older: {
+ "read_aloud:read": "border-emerald-200 bg-emerald-50 text-emerald-950 hover:bg-emerald-100",
+ "vocabulary:explain": "border-amber-200 bg-amber-50 text-amber-950 hover:bg-amber-100",
+ "quiz:start": "border-sky-200 bg-sky-50 text-sky-950 hover:bg-sky-100",
+ },
+};
+
+export function readingActionClass(mode: ReadingAgeMode, key: string): string {
+ if (mode === "default") return `${baseButton} ${adultButton}`;
+ const tone = tones[mode][key];
+ return tone ? `${baseButton} ${learnerButtons[mode]} ${tone}` : `${baseButton} ${adultButton}`;
+}
diff --git a/web/tailwind.config.js b/web/tailwind.config.js
index bd3e8033c..9443fe7c1 100644
--- a/web/tailwind.config.js
+++ b/web/tailwind.config.js
@@ -22,6 +22,7 @@ module.exports = {
'./features/**/*.{js,ts,jsx,tsx,mdx}',
'./shared/**/*.{js,ts,jsx,tsx,mdx}',
'./app/**/*.{js,ts,jsx,tsx,mdx}',
+ './lib/reading-age-presentation.ts',
],
theme: {
extend: {
diff --git a/web/tests/reading-age-presentation.spec.tsx b/web/tests/reading-age-presentation.spec.tsx
new file mode 100644
index 000000000..89a716e78
--- /dev/null
+++ b/web/tests/reading-age-presentation.spec.tsx
@@ -0,0 +1,164 @@
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { ReadingExtensionBar } from "@/components/reading/ReadingExtensionBar";
+import { initI18n } from "@/i18n/init";
+import { fetchAuthStatus } from "@/lib/auth";
+import { getOwnLearnerProfile } from "@/lib/profile-api";
+import { listReadingExtensions, runReadingExtension } from "@/lib/reading-api";
+import {
+ readingActionClass,
+ resolveReadingAgeMode,
+} from "@/lib/reading-age-presentation";
+
+vi.mock("@/lib/auth", () => ({ fetchAuthStatus: vi.fn() }));
+vi.mock("@/lib/profile-api", () => ({ getOwnLearnerProfile: vi.fn() }));
+vi.mock("@/lib/reading-api", () => ({
+ listReadingExtensions: vi.fn(),
+ runReadingExtension: vi.fn(),
+ submitReadingQuizAnswers: vi.fn(),
+}));
+
+initI18n("en");
+
+const extensions = [
+ {
+ id: "quiz",
+ name: "Quiz",
+ version: "1",
+ protocol_version: "1",
+ actions: [{ id: "start", label: "Quiz me", trigger: "toolbar", requires: [] }],
+ result_types: ["quiz"],
+ },
+ {
+ id: "custom",
+ name: "Custom",
+ version: "1",
+ protocol_version: "1",
+ actions: [{ id: "open", label: "Custom action", trigger: "toolbar", requires: [] }],
+ result_types: ["card"],
+ },
+ {
+ id: "vocabulary",
+ name: "Vocabulary",
+ version: "1",
+ protocol_version: "1",
+ actions: [
+ { id: "explain", label: "Explain vocabulary", trigger: "toolbar", requires: ["selection"] },
+ ],
+ result_types: ["card"],
+ },
+ {
+ id: "read_aloud",
+ name: "Read aloud",
+ version: "1",
+ protocol_version: "1",
+ actions: [{ id: "read", label: "Read aloud", trigger: "toolbar", requires: [] }],
+ result_types: ["browser_speech"],
+ },
+] as Awaited<ReturnType<typeof listReadingExtensions>>;
+
+beforeEach(() => {
+ vi.mocked(listReadingExtensions).mockResolvedValue(extensions);
+ vi.mocked(runReadingExtension).mockImplementation(() => new Promise(() => undefined));
+ vi.mocked(fetchAuthStatus).mockResolvedValue({
+ enabled: true,
+ authenticated: true,
+ preset: "learner",
+ learning_policy: {
+ age_band: "9-12",
+ locked_persona: "",
+ allowed_capabilities: [],
+ default_capability: "chat",
+ },
+ });
+ vi.mocked(getOwnLearnerProfile).mockResolvedValue({ age: 8 });
+});
+
+describe("host-owned Reading age presentation", () => {
+ it("uses exact profile ages and a conservative policy fallback only in learner mode", () => {
+ expect(resolveReadingAgeMode({ learnerMode: false, profileAge: 5, policyAgeBand: "6-8" })).toBe("default");
+ expect(resolveReadingAgeMode({ learnerMode: true, profileAge: 5 })).toBe("early");
+ expect(resolveReadingAgeMode({ learnerMode: true, profileAge: 6 })).toBe("early");
+ expect(resolveReadingAgeMode({ learnerMode: true, profileAge: 8 })).toBe("young");
+ expect(resolveReadingAgeMode({ learnerMode: true, profileAge: 12 })).toBe("older");
+ expect(resolveReadingAgeMode({ learnerMode: true, profileAge: 13 })).toBe("default");
+ expect(resolveReadingAgeMode({ learnerMode: true, profileAge: 2, policyAgeBand: "6-8" })).toBe("young");
+ expect(resolveReadingAgeMode({ learnerMode: true, profileAge: null, policyAgeBand: "9-12" })).toBe("older");
+ expect(resolveReadingAgeMode({ learnerMode: true, profileAge: null, policyAgeBand: "13-15" })).toBe("default");
+ });
+
+ it.each([
+ { age: 5, mode: "early", size: "min-h-14" },
+ { age: 8, mode: "young", size: "min-h-12" },
+ { age: 12, mode: "older", size: "min-h-11" },
+ ])("shows the three fixed actions for age $age without styling plugins", async ({ age, mode, size }) => {
+ vi.mocked(getOwnLearnerProfile).mockResolvedValue({ age });
+ const onError = vi.fn();
+ const { container } = render(
+ <ReadingExtensionBar materialId="material-1" locator={4} onError={onError} />,
+ );
+
+ await waitFor(() =>
+ expect(container.querySelector("[data-reading-presentation]")).toHaveAttribute(
+ "data-reading-presentation",
+ mode,
+ ),
+ );
+ const buttons = screen.getAllByRole("button");
+ expect(buttons.map((button) => button.textContent?.trim())).toEqual([
+ "Read aloud",
+ "Explain vocabulary",
+ "Quiz me",
+ "Custom action",
+ ]);
+ for (const button of buttons.slice(0, 3)) {
+ expect(button).toHaveClass(size);
+ expect(button).toHaveAccessibleName();
+ }
+ expect(buttons[3]).toHaveClass("h-8");
+ expect(buttons[3]).not.toHaveClass(size);
+ expect(buttons[1]).toBeDisabled();
+ expect(onError).not.toHaveBeenCalled();
+ });
+
+ it("keeps adult styling for a standard account and never fetches its learner profile", async () => {
+ vi.mocked(fetchAuthStatus).mockResolvedValue({
+ enabled: true,
+ authenticated: true,
+ preset: "standard",
+ learning_policy: null,
+ });
+ const { container } = render(
+ <ReadingExtensionBar materialId="material-1" locator={4} onError={vi.fn()} />,
+ );
+ await screen.findByRole("button", { name: "Read aloud" });
+ expect(container.querySelector("[data-reading-presentation]")).toHaveAttribute(
+ "data-reading-presentation",
+ "default",
+ );
+ expect(screen.getByRole("button", { name: "Read aloud" })).toHaveClass("h-8");
+ expect(getOwnLearnerProfile).not.toHaveBeenCalled();
+ });
+
+ it("keeps the action request and keyboard order free of age metadata", async () => {
+ vi.mocked(getOwnLearnerProfile).mockResolvedValue({ age: 5 });
+ render(<ReadingExtensionBar materialId="material-1" locator={4} onError={vi.fn()} />);
+ const readButton = await screen.findByRole("button", { name: "Read aloud" });
+ await waitFor(() => expect(readButton.closest("[data-reading-presentation]")).toHaveAttribute("data-reading-presentation", "early"));
+ expect(screen.getAllByRole("button")[0]).toBe(readButton);
+ fireEvent.click(readButton);
+ expect(runReadingExtension).toHaveBeenCalledWith("material-1", "read_aloud", "read", {
+ locator: 4,
+ selection: "",
+ locale: "en",
+ });
+ });
+
+ it("only animates under motion-safe, including the early entrance", () => {
+ expect(readingActionClass("early", "read_aloud:read")).toContain("motion-safe:animate-");
+ expect(readingActionClass("early", "read_aloud:read")).not.toMatch(/(?:^|\s)animate-/);
+ expect(readingActionClass("early", "read_aloud:read")).not.toContain("transition-colors");
+ expect(readingActionClass("default", "read_aloud:read")).not.toContain("motion-safe:animate-");
+ });
+});