Skip to content

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

feat(reading): collections as colored folders; rework reader interactions

Bingxi Zhao (Frank)53436f8190de
diff --git a/deeptutor/api/routers/reading.py b/deeptutor/api/routers/reading.py
index 34a826a45..961d340b3 100644
--- a/deeptutor/api/routers/reading.py
+++ b/deeptutor/api/routers/reading.py
@@ -361,12 +361,14 @@ class UrlImportRequest(BaseModel):
class WorkspaceCreateRequest(BaseModel):
title: str = Field(default="Untitled collection", max_length=300)
description: str = Field(default="", max_length=2000)
+ color: str = Field(default="", max_length=32)
material_ids: list[str] = Field(default_factory=list, max_length=100)
class WorkspaceUpdateRequest(BaseModel):
title: str | None = Field(default=None, max_length=300)
description: str | None = Field(default=None, max_length=2000)
+ color: str | None = Field(default=None, max_length=32)
class WorkspaceMaterialRequest(BaseModel):
@@ -614,6 +616,7 @@ async def create_workspace(payload: WorkspaceCreateRequest) -> dict[str, Any]:
payload.title,
payload.material_ids,
description=payload.description,
+ color=payload.color,
)
return {"workspace": row.to_dict()}
except Exception as exc:
@@ -670,6 +673,7 @@ async def update_workspace(workspace_id: str, payload: WorkspaceUpdateRequest) -
workspace_id,
title=payload.title,
description=payload.description,
+ color=payload.color,
)
return {"workspace": row.to_dict()}
except Exception as exc:
diff --git a/deeptutor/reading/catalog_models.py b/deeptutor/reading/catalog_models.py
index 9a9f5d22c..3ca7f07e8 100644
--- a/deeptutor/reading/catalog_models.py
+++ b/deeptutor/reading/catalog_models.py
@@ -94,6 +94,7 @@ class WorkspaceRecord:
workspace_id: str
title: str
description: str = ""
+ color: str = ""
active_material_id: str | None = None
created_at: float = 0.0
updated_at: float = 0.0
@@ -104,6 +105,7 @@ class WorkspaceRecord:
"workspace_id": self.workspace_id,
"title": self.title,
"description": self.description,
+ "color": self.color,
"active_material_id": self.active_material_id,
"created_at": self.created_at,
"updated_at": self.updated_at,
diff --git a/deeptutor/reading/catalog_store.py b/deeptutor/reading/catalog_store.py
index b247be414..289ffb7f1 100644
--- a/deeptutor/reading/catalog_store.py
+++ b/deeptutor/reading/catalog_store.py
@@ -39,6 +39,18 @@ def _new_id(prefix: str) -> str:
return f"{prefix}_{uuid.uuid4().hex}"
+# A collection's folder tint is a palette key the web client maps to its own
+# light/dark tones; anything else falls back to the neutral default.
+COLLECTION_COLORS = frozenset(
+ {"blue", "teal", "green", "amber", "orange", "rose", "violet", "slate"}
+)
+
+
+def _collection_color(color: str) -> str:
+ key = (color or "").strip().lower()
+ return key if key in COLLECTION_COLORS else ""
+
+
class ReadingCatalogStore:
"""Durable workspace metadata for one already-scoped owner."""
@@ -98,6 +110,7 @@ class ReadingCatalogStore:
workspace_id TEXT PRIMARY KEY,
title TEXT NOT NULL,
description TEXT NOT NULL DEFAULT '',
+ color TEXT NOT NULL DEFAULT '',
active_material_id TEXT REFERENCES reading_materials(material_id)
ON DELETE SET NULL,
created_at REAL NOT NULL,
@@ -158,6 +171,14 @@ class ReadingCatalogStore:
"ALTER TABLE reading_materials "
"ADD COLUMN duration_seconds REAL NOT NULL DEFAULT 0"
)
+ collection_columns = {
+ str(row["name"])
+ for row in conn.execute("PRAGMA table_info(reading_workspaces)").fetchall()
+ }
+ if "color" not in collection_columns:
+ conn.execute(
+ "ALTER TABLE reading_workspaces ADD COLUMN color TEXT NOT NULL DEFAULT ''"
+ )
if self._content_id_is_unique(conn):
self._remove_content_id_unique_constraint(conn)
conn.execute(
@@ -555,6 +576,7 @@ class ReadingCatalogStore:
material_ids: Sequence[str] = (),
*,
description: str = "",
+ color: str = "",
workspace_id: str | None = None,
) -> WorkspaceRecord:
resolved_id = workspace_id or _new_id("rw")
@@ -566,13 +588,15 @@ class ReadingCatalogStore:
conn.execute(
"""
INSERT INTO reading_workspaces (
- workspace_id, title, description, active_material_id, created_at, updated_at
- ) VALUES (?, ?, ?, ?, ?, ?)
+ workspace_id, title, description, color, active_material_id,
+ created_at, updated_at
+ ) VALUES (?, ?, ?, ?, ?, ?, ?)
""",
(
resolved_id,
(title or "Untitled reading workspace").strip()[:300],
description.strip()[:2000],
+ _collection_color(color),
unique_materials[0] if unique_materials else None,
now,
now,
@@ -634,7 +658,12 @@ class ReadingCatalogStore:
return results
def update_workspace(
- self, workspace_id: str, *, title: str | None = None, description: str | None = None
+ self,
+ workspace_id: str,
+ *,
+ title: str | None = None,
+ description: str | None = None,
+ color: str | None = None,
) -> WorkspaceRecord:
self._validate_id(workspace_id, "workspace")
assignments = ["updated_at = ?"]
@@ -645,6 +674,9 @@ class ReadingCatalogStore:
if description is not None:
assignments.append("description = ?")
params.append(description.strip()[:2000])
+ if color is not None:
+ assignments.append("color = ?")
+ params.append(_collection_color(color))
params.append(workspace_id)
with self._lock, self._connect() as conn:
changed = conn.execute(
@@ -889,6 +921,23 @@ class ReadingCatalogStore:
).rowcount
)
+ def retitle_session(self, session_id: str, title: str) -> None:
+ """Follow a rename made outside the reader (the sidebar), if tracked."""
+ with self._lock, self._connect() as conn:
+ conn.execute(
+ """UPDATE reading_workspace_sessions SET title = ?, updated_at = ?
+ WHERE session_id = ?""",
+ ((title or "New reading conversation").strip()[:300], time.time(), session_id),
+ )
+
+ def forget_session(self, session_id: str) -> None:
+ """Drop a conversation deleted outside the reader from every collection."""
+ with self._lock, self._connect() as conn:
+ conn.execute(
+ "DELETE FROM reading_workspace_sessions WHERE session_id = ?",
+ (session_id,),
+ )
+
def link_session(
self, workspace_id: str, source_session_id: str, target_session_id: str
) -> None:
@@ -961,6 +1010,7 @@ class ReadingCatalogStore:
workspace_id=row["workspace_id"],
title=row["title"],
description=row["description"],
+ color=row["color"],
active_material_id=row["active_material_id"],
created_at=float(row["created_at"]),
updated_at=float(row["updated_at"]),
diff --git a/tests/reading/test_catalog_store.py b/tests/reading/test_catalog_store.py
index 3b00c391a..08c46df09 100644
--- a/tests/reading/test_catalog_store.py
+++ b/tests/reading/test_catalog_store.py
@@ -168,3 +168,53 @@ def test_default_stores_follow_the_current_user_scope(tmp_path: Path) -> None:
assert attacker.list_workspaces() == []
assert victim.db_path != attacker.db_path
assert victim_content_root != attacker_content_root
+
+
+def test_sidebar_rename_and_delete_reach_the_collection_list(
+ catalog: ReadingCatalogStore,
+) -> None:
+ # The sidebar renames and deletes through /api/sessions, not through the
+ # reader; the collection's own list must follow both.
+ material = _material(catalog, "d" * 16, "Networks")
+ workspace = catalog.create_workspace("Networks", [material.material_id])
+ catalog.attach_session(workspace.workspace_id, "kept", title="Kept")
+ catalog.attach_session(workspace.workspace_id, "gone", title="Gone")
+
+ catalog.retitle_session("kept", "Routing questions")
+ catalog.forget_session("gone")
+ catalog.retitle_session("never_tracked", "No-op")
+
+ rows = catalog.list_sessions(workspace.workspace_id)
+ assert [(row.session_id, row.title) for row in rows] == [("kept", "Routing questions")]
+
+
+def test_collection_color_is_a_palette_key_that_survives_updates(
+ catalog: ReadingCatalogStore,
+) -> None:
+ workspace = catalog.create_workspace("Networks", color="Teal")
+ assert workspace.color == "teal"
+ assert workspace.to_dict()["color"] == "teal"
+
+ renamed = catalog.update_workspace(workspace.workspace_id, title="Routing")
+ assert (renamed.title, renamed.color) == ("Routing", "teal")
+
+ # Arbitrary CSS never reaches the page; it falls back to the default tint.
+ recolored = catalog.update_workspace(workspace.workspace_id, color="#ff0000; x")
+ assert recolored.color == ""
+
+
+def test_catalog_created_before_collection_colors_gains_the_column(
+ tmp_path: Path,
+) -> None:
+ import sqlite3
+
+ root = tmp_path / "reading"
+ catalog = ReadingCatalogStore(root=root)
+ workspace = catalog.create_workspace("Legacy")
+ database = next(root.rglob("*.sqlite*"))
+ with sqlite3.connect(database) as conn:
+ conn.execute("ALTER TABLE reading_workspaces DROP COLUMN color")
+
+ reopened = ReadingCatalogStore(root=root)
+ assert reopened.get_workspace(workspace.workspace_id).color == ""
+ assert reopened.update_workspace(workspace.workspace_id, color="amber").color == "amber"
diff --git a/tests/reading/test_router.py b/tests/reading/test_router.py
index 8a5f21419..c00471040 100644
--- a/tests/reading/test_router.py
+++ b/tests/reading/test_router.py
@@ -896,3 +896,16 @@ def test_deleting_a_material_reports_where_it_was_used(client: TestClient) -> No
assert [row["title"] for row in removed["removed_from"]] == ["Close reading"]
# The sibling still reads the same extracted content, so it survives.
assert client.get(f"/api/reading/materials/{second_id}/units/1").json()["text"]
+
+
+def test_collection_color_round_trips_through_create_and_patch(client: TestClient) -> None:
+ created = client.post(
+ "/api/reading/workspaces", json={"title": "Close reading", "color": "violet"}
+ ).json()["workspace"]
+ assert created["color"] == "violet"
+
+ patched = client.patch(
+ f"/api/reading/workspaces/{created['workspace_id']}",
+ json={"title": "Slow reading", "color": "green"},
+ ).json()["workspace"]
+ assert (patched["title"], patched["color"]) == ("Slow reading", "green")
diff --git a/web/app/(workspace)/learning/reading/folders/[folderId]/page.tsx b/web/app/(workspace)/learning/reading/folders/[folderId]/page.tsx
new file mode 100644
index 000000000..9e331a535
--- /dev/null
+++ b/web/app/(workspace)/learning/reading/folders/[folderId]/page.tsx
@@ -0,0 +1,10 @@
+import { ReadingFolderPage } from "@/components/reading/library/ReadingFolder";
+
+export default async function ImmersiveReadingFolderRoute({
+ params,
+}: {
+ params: Promise<{ folderId: string }>;
+}) {
+ const { folderId } = await params;
+ return <ReadingFolderPage folderId={decodeURIComponent(folderId)} />;
+}
diff --git a/web/app/globals.css b/web/app/globals.css
index 0afdf4408..a2f6ef99b 100644
--- a/web/app/globals.css
+++ b/web/app/globals.css
@@ -199,6 +199,34 @@
transform: translateY(-1px);
}
+ /* Collection folder tints (Immersive Reading). These are user-picked
+ category colours rather than theme accents, so they sit outside the
+ palettes: one set for light canvases, a softer one for dark ones. */
+ :root {
+ --folder-default: #a8a29e;
+ --folder-blue: #4f86f7;
+ --folder-teal: #1fb5a8;
+ --folder-green: #43b05c;
+ --folder-amber: #eaa221;
+ --folder-orange: #f07b3f;
+ --folder-rose: #e8577a;
+ --folder-violet: #8e6cf0;
+ --folder-slate: #6b7a90;
+ }
+
+ .dark,
+ .theme-glass {
+ --folder-default: #8a847f;
+ --folder-blue: #5b8def;
+ --folder-teal: #2aa79c;
+ --folder-green: #4aa35f;
+ --folder-amber: #d69a2d;
+ --folder-orange: #dd7a45;
+ --folder-rose: #d65f7f;
+ --folder-violet: #8b72e6;
+ --folder-slate: #74839a;
+ }
+
* {
@apply border-[color:var(--border)];
scrollbar-width: thin;
diff --git a/web/components/SessionList.tsx b/web/components/SessionList.tsx
index 5fb9080ce..7cf11a071 100644
--- a/web/components/SessionList.tsx
+++ b/web/components/SessionList.tsx
@@ -7,6 +7,7 @@ import { type SessionSummary } from "@/lib/session-api";
import { normalizeMessageContent, truncateText } from "@/lib/message-content";
import {
deriveSessionMark,
+ sessionKindOf,
SessionAvatar,
} from "@/components/sidebar/SessionAvatar";
import { useUnreadSessions } from "@/lib/session-unread";
@@ -160,6 +161,7 @@ export default function SessionList({
<SessionAvatar
sessionId={session.session_id}
mark={deriveSessionMark(session, undefined, unread)}
+ kind={sessionKindOf(session)}
className={
session.status === "running" ? "opacity-100" : "opacity-80"
}
diff --git a/web/components/chat/home/ChatComposer.module.css b/web/components/chat/home/ChatComposer.module.css
index 2df5a5308..cb35dd2c3 100644
--- a/web/components/chat/home/ChatComposer.module.css
+++ b/web/components/chat/home/ChatComposer.module.css
@@ -2,18 +2,21 @@
container: chat-composer / inline-size;
}
-/* Use the actual composer width, including when a side panel is open. */
+/* The actions drop below the context only when the two don't fit side by
+ side. A width breakpoint split them on every narrow surface — a side
+ panel's composer showed a mode chip on one row and a lone send button on
+ the next, with room for both. */
.toolbar {
- display: grid;
- grid-template-columns: minmax(0, 1fr);
- grid-template-areas: "context" "actions";
+ display: flex;
+ flex-wrap: wrap;
align-items: center;
+ justify-content: flex-end;
gap: 4px;
}
.context {
- grid-area: context;
display: flex;
+ flex: 1 1 auto;
min-width: 0;
flex-wrap: wrap;
align-items: center;
@@ -26,8 +29,8 @@
}
.actions {
- grid-area: actions;
display: flex;
+ flex: 0 0 auto;
min-width: 0;
align-items: center;
justify-content: flex-end;
@@ -39,13 +42,6 @@
display: none;
}
-@container chat-composer (min-width: 420px) {
- .toolbar {
- grid-template-columns: minmax(0, 1fr) auto;
- grid-template-areas: "context actions";
- }
-}
-
@container chat-composer (min-width: 600px) {
.toolbar [data-toolbar-label] {
display: inline-flex;
diff --git a/web/components/courses/OrganizedSessionList.tsx b/web/components/courses/OrganizedSessionList.tsx
index 3334054c5..db51073b0 100644
--- a/web/components/courses/OrganizedSessionList.tsx
+++ b/web/components/courses/OrganizedSessionList.tsx
@@ -22,6 +22,7 @@ import {
import { useTranslation } from "react-i18next";
import {
deriveSessionMark,
+ sessionKindOf,
SessionAvatar,
} from "@/components/sidebar/SessionAvatar";
import { useUnreadSessions } from "@/lib/session-unread";
@@ -315,8 +316,8 @@ export default function OrganizedSessionList({
child ? "ml-4 border-l border-[var(--border)]/60 pl-2" : "pl-1.5"
} ${
active
- ? "bg-[var(--background)]/60 text-[var(--foreground)]"
- : "text-[var(--foreground)] hover:bg-[var(--background)]/40"
+ ? "bg-background/60 text-[var(--foreground)]"
+ : "text-[var(--foreground)] hover:bg-background/40"
}`}
>
{children.length > 0 ? (
@@ -344,6 +345,7 @@ export default function OrganizedSessionList({
<SessionAvatar
sessionId={session.session_id}
mark={deriveSessionMark(session, liveSessionIds, unread)}
+ kind={sessionKindOf(session)}
size={child ? 11 : 12}
className={child ? "opacity-65" : "opacity-80"}
/>
@@ -598,7 +600,7 @@ export default function OrganizedSessionList({
style={style}
className={`rounded-lg ${
dragging
- ? "bg-[var(--background)]/85 shadow-lg ring-1 ring-[var(--border)]/70"
+ ? "bg-background/85 shadow-lg ring-1 ring-border/70"
: ""
}`}
>
@@ -639,7 +641,7 @@ export default function OrganizedSessionList({
style={sortable ? style : undefined}
className={`${recent ? "pt-5" : "pt-1.5"} first:pt-0 ${
dragging
- ? "rounded-lg bg-[var(--background)]/85 shadow-lg ring-1 ring-[var(--border)]/70"
+ ? "rounded-lg bg-background/85 shadow-lg ring-1 ring-border/70"
: ""
}`}
>
@@ -660,7 +662,7 @@ export default function OrganizedSessionList({
// had it a hair smaller than a caption and uppercase, which shouted
// in a list of 12.5px rows and did nothing whatsoever to the CJK
// titles most of these groups actually carry.
- className="group/heading flex w-full min-w-0 items-center gap-1.5 rounded-lg px-1.5 py-1 text-left text-[12.5px] font-medium text-[var(--foreground)] transition-colors hover:bg-[var(--background)]/40 hover:text-[var(--foreground)]"
+ className="group/heading flex w-full min-w-0 items-center gap-1.5 rounded-lg px-1.5 py-1 text-left text-[12.5px] font-medium text-[var(--foreground)] transition-colors hover:bg-background/40 hover:text-[var(--foreground)]"
>
{!recent && <GroupMark entry={entry} />}
<span className="min-w-0 truncate">{recent ? t("Recent") : entry.label}</span>
diff --git a/web/components/learning/LibraryWorkspace.tsx b/web/components/learning/LibraryWorkspace.tsx
index 3f2edbe4f..9b73e6fc1 100644
--- a/web/components/learning/LibraryWorkspace.tsx
+++ b/web/components/learning/LibraryWorkspace.tsx
@@ -3,32 +3,54 @@
import { useEffect, useRef, useState } from 'react'
import { usePathname, useRouter, useSearchParams } from 'next/navigation'
import { useTranslation } from 'react-i18next'
+import type { TFunction } from 'i18next'
import Modal from '@/components/common/Modal'
import { useChatWorkspaces } from '@/hooks/useChatWorkspaces'
import { activeWorkspaceId, scopedUrl } from '@/lib/workspace-scope'
import type { LearningOrigin } from '@/lib/learning-library'
+export function workspaceName(row: LearningOrigin, t: TFunction) {
+ return row.content_workspace_name || row.content_workspace_id || t('Default workspace')
+}
+
export function WorkspaceLabel({ row }: { row: LearningOrigin }) {
const { t } = useTranslation()
- return <span className="text-xs text-muted-foreground">{row.content_workspace_name || (row.content_workspace_id ? row.content_workspace_id : t('Default workspace'))}</span>
+ return <span className="text-xs text-muted-foreground">{workspaceName(row, t)}</span>
}
export function useLibraryFilter<T extends LearningOrigin>(rows: T[]) {
const [filter, setFilter] = useState('*')
const { t } = useTranslation()
- const options = new Map(rows.map(row => [row.content_workspace_id ?? '', row.content_workspace_name || row.content_workspace_id || t('Default workspace')]))
+ const options = new Map(rows.map(row => [row.content_workspace_id ?? '', workspaceName(row, t)]))
+ // A workspace that no longer has rows cannot stay selected: its option is
+ // gone, so nothing on screen would say why the list is empty.
+ const active = filter !== '*' && options.has(filter) ? filter : '*'
const control = <label className="inline-flex max-w-full shrink-0 flex-wrap items-center gap-2 text-xs text-muted-foreground">
{t('Show materials from')}
- <select aria-label={t('Filter by workspace')} value={filter} onChange={event => setFilter(event.target.value)} className="h-9 min-w-0 max-w-56 rounded-lg border border-border bg-background px-3 text-sm text-foreground">
+ <select aria-label={t('Filter by workspace')} value={active} onChange={event => setFilter(event.target.value)} className="h-9 min-w-0 max-w-56 rounded-lg border border-border bg-background px-3 text-sm text-foreground">
<option value="*">{t('All workspaces')}</option>
{[...options].map(([id, name]) => <option key={id} value={id}>{name}</option>)}
</select>
</label>
- return { rows: filter === '*' ? rows : rows.filter(row => (row.content_workspace_id ?? '') === filter), control }
+ // The same choice sized for a page's own toolbar row. With one workspace
+ // there is nothing to choose between, so it is not shown at all.
+ const picker = options.size > 1
+ ? <select aria-label={t('Filter by workspace')} value={active} onChange={event => setFilter(event.target.value)} className="h-8 min-w-0 max-w-44 rounded-lg border border-border bg-background px-2 text-[12px] text-foreground">
+ <option value="*">{t('All workspaces')}</option>
+ {[...options].map(([id, name]) => <option key={id} value={id}>{name}</option>)}
+ </select>
+ : null
+ return {
+ rows: active === '*' ? rows : rows.filter(row => (row.content_workspace_id ?? '') === active),
+ control,
+ picker,
+ // More than one workspace on screen at once: rows need to say whose they are.
+ mixed: active === '*' && options.size > 1,
+ }
}
-/** Pick a destination only when creating; URL scopes all ensuing uploads and writes. */
-export function useLearningCreation(open: () => void) {
+/** Opens creation when a link arrives with `?create=1`, then drops the flag from the URL. */
+export function useCreateRequest(open: () => void) {
const router = useRouter()
const pathname = usePathname()
const query = useSearchParams()
@@ -44,27 +66,38 @@ export function useLearningCreation(open: () => void) {
next.delete('create')
router.replace(`${pathname}${next.size ? `?${next}` : ''}`, { scroll: false })
}, [pathname, query, router])
+}
+
+/** Pick a destination only when creating; URL scopes all ensuing uploads and writes. */
+export function useLearningCreation(open: () => void) {
+ const router = useRouter()
+ const pathname = usePathname()
+ const query = useSearchParams()
+ useCreateRequest(open)
const { t } = useTranslation()
const { workspaces, error } = useChatWorkspaces()
const [choosing, setChoosing] = useState(false)
const [destination, setDestination] = useState(activeWorkspaceId)
const dialog = <Modal isOpen={choosing} onClose={() => setChoosing(false)} title={t('Save new content to')} width="sm">
- <div className="space-y-4 p-5">
- <p className="text-sm text-muted-foreground">{t('Only new content is saved here. Your existing materials remain visible in all workspaces.')}</p>
- <select aria-label={t('Save to workspace')} value={destination} onChange={event => setDestination(event.target.value)} className="w-full rounded-lg border border-border bg-background p-2">
+ <div className="p-5">
+ <p className="text-[12.5px] leading-relaxed text-muted-foreground">{t('Only new content is saved here. Your existing materials remain visible in all workspaces.')}</p>
+ <select aria-label={t('Save to workspace')} value={destination} onChange={event => setDestination(event.target.value)} className="mt-3 h-9 w-full rounded-lg border border-border bg-background px-2.5 text-[13px] outline-none focus:border-ring">
<option value="">{t('Default workspace')}</option>
{workspaces.filter(row => !row.archived && row.status === 'ready').map(row => <option key={row.workspace_id} value={row.workspace_id}>{row.display_name}</option>)}
</select>
- {error && <p role="alert" className="text-sm text-destructive">{error}</p>}
- <button type="button" className="rounded-lg bg-primary px-4 py-2 text-sm text-primary-foreground" onClick={() => {
- setChoosing(false)
- if (destination === activeWorkspaceId()) open()
- else {
- const next = new URLSearchParams(query.toString())
- next.delete('dt_workspace'); next.delete('workspace'); next.set('create', '1')
- router.push(scopedUrl(`${pathname}?${next}`, destination))
- }
- }}>{t('Continue')}</button>
+ {error && <p role="alert" className="mt-3 text-[11.5px] text-destructive">{error}</p>}
+ <div className="mt-5 flex justify-end gap-2">
+ <button type="button" className="h-8 rounded-lg px-3 text-[12px] text-muted-foreground hover:bg-muted" onClick={() => setChoosing(false)}>{t('Cancel')}</button>
+ <button type="button" className="h-8 rounded-lg bg-primary px-3.5 text-[12px] font-semibold text-primary-foreground hover:opacity-90" onClick={() => {
+ setChoosing(false)
+ if (destination === activeWorkspaceId()) open()
+ else {
+ const next = new URLSearchParams(query.toString())
+ next.delete('dt_workspace'); next.delete('workspace'); next.set('create', '1')
+ router.push(scopedUrl(`${pathname}?${next}`, destination))
+ }
+ }}>{t('Continue')}</button>
+ </div>
</div>
</Modal>
// Course-created content inherits the course store so its references stay valid.
diff --git a/web/components/reading/AnnotationPopover.tsx b/web/components/reading/AnnotationPopover.tsx
index 4a359d6a6..54a1b4bd1 100644
--- a/web/components/reading/AnnotationPopover.tsx
+++ b/web/components/reading/AnnotationPopover.tsx
@@ -5,6 +5,7 @@ import {
BookmarkPlus,
Highlighter,
MessageSquareQuote,
+ MoreHorizontal,
StickyNote,
Underline,
} from "lucide-react";
@@ -26,8 +27,25 @@ export interface AnnotationPopoverProps {
onCitation: (color: AnnotationColor) => void;
onAsk: () => void;
onDismiss: () => void;
+ /**
+ * AI actions on the selection, shown as a second row under the marking
+ * tools. Without them the popover is the annotation toolbar it always was,
+ * with "Ask about this" as its last icon.
+ */
+ aiActions?: PopoverAiAction[];
}
+export interface PopoverAiAction {
+ key: string;
+ /** Short chip text ("Explain"); `title` carries the full name. */
+ label: string;
+ title: string;
+ onClick: () => void;
+}
+
+/** Chips that fit on the row before the rest go behind ⋯. */
+const INLINE_AI_ACTIONS = 3;
+
/**
* Toolbar that appears over a selection.
*
@@ -49,12 +67,16 @@ export function AnnotationPopover({
onCitation,
onAsk,
onDismiss,
+ aiActions,
}: AnnotationPopoverProps) {
const { t } = useTranslation();
const ref = useRef<HTMLDivElement | null>(null);
const [color, setColor] = useState<AnnotationColor>("yellow");
const [noteOpen, setNoteOpen] = useState(false);
const [note, setNote] = useState("");
+ const [overflowOpen, setOverflowOpen] = useState(false);
+ const inlineAi = aiActions?.slice(0, INLINE_AI_ACTIONS) ?? [];
+ const overflowAi = aiActions?.slice(INLINE_AI_ACTIONS) ?? [];
const [position, setPosition] = useState({ left: anchor.x, top: anchor.y });
useLayoutEffect(() => {
@@ -73,7 +95,7 @@ export function AnnotationPopover({
left,
top: Math.min(top, window.innerHeight - box.height - margin),
});
- }, [anchor.x, anchor.y, noteOpen]);
+ }, [anchor.x, anchor.y, noteOpen, overflowOpen]);
useEffect(() => {
const onKey = (event: KeyboardEvent) => {
@@ -144,13 +166,57 @@ export function AnnotationPopover({
label={t("Save citation")}
onClick={() => onCitation(color)}
/>
- <IconButton
- icon={MessageSquareQuote}
- label={t("Ask about this")}
- onClick={onAsk}
- />
+ {aiActions ? null : (
+ <IconButton
+ icon={MessageSquareQuote}
+ label={t("Ask about this")}
+ onClick={onAsk}
+ />
+ )}
</div>
+ {aiActions && (
+ <div className="mt-1.5 flex items-center gap-1 border-t border-[var(--border)] pt-1.5">
+ <Tooltip label={t("Ask about this")} side="bottom">
+ <button
+ type="button"
+ aria-label={t("Ask about this")}
+ onClick={onAsk}
+ className="inline-flex h-7 items-center gap-1.5 rounded-lg bg-[var(--primary)] px-2.5 text-[12px] font-medium text-[var(--primary-foreground)] transition hover:opacity-90"
+ >
+ <MessageSquareQuote size={13} />
+ {t("Ask")}
+ </button>
+ </Tooltip>
+ {inlineAi.map((action) => (
+ <AiChip key={action.key} action={action} />
+ ))}
+ {overflowAi.length > 0 && (
+ <IconButton
+ icon={MoreHorizontal}
+ label={t("More actions")}
+ active={overflowOpen}
+ onClick={() => setOverflowOpen((open) => !open)}
+ />
+ )}
+ </div>
+ )}
+
+ {overflowOpen && overflowAi.length > 0 && (
+ <div className="mt-1 grid gap-0.5 border-t border-[var(--border)] pt-1">
+ {overflowAi.map((action) => (
+ <button
+ key={action.key}
+ type="button"
+ onClick={action.onClick}
+ className="rounded-lg px-2 py-1.5 text-left text-[12px] text-[var(--foreground)] transition hover:bg-[var(--muted)]"
+ >
+ {action.title}
+ </button>
+ ))}
+ </div>
+ )}
+
{noteOpen && (
<div className="mt-1.5 border-t border-[var(--border)] pt-1.5">
<p className="mb-1 line-clamp-2 px-1 text-[11px] italic text-[var(--muted-foreground)]">
@@ -221,6 +287,21 @@ function IconButton({
);
}
+function AiChip({ action }: { action: PopoverAiAction }) {
+ return (
+ <Tooltip label={action.title} side="bottom">
+ <button
+ type="button"
+ aria-label={action.title}
+ onClick={action.onClick}
+ className="inline-flex h-7 items-center rounded-lg px-2 text-[12px] font-medium text-[var(--muted-foreground)] transition hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
+ >
+ {action.label}
+ </button>
+ </Tooltip>
+ );
+}
+
function swatchLabel(color: AnnotationColor): string {
switch (color) {
case "green":
diff --git a/web/components/reading/ReaderPane.tsx b/web/components/reading/ReaderPane.tsx
index 88aab5cba..bb86bb185 100644
--- a/web/components/reading/ReaderPane.tsx
+++ b/web/components/reading/ReaderPane.tsx
@@ -37,7 +37,7 @@ import {
type ReadingBookmark,
} from "@/lib/reading-api";
import { AnnotationList } from "./AnnotationList";
-import { AnnotationPopover } from "./AnnotationPopover";
+import { AnnotationPopover, type PopoverAiAction } from "./AnnotationPopover";
import { EpubDocumentView } from "./EpubDocumentView";
import {
PdfDocumentView,
@@ -45,6 +45,14 @@ import {
type SelectionPayload,
} from "./PdfDocumentView";
import { ReadingExtensionBar } from "./ReadingExtensionBar";
+import {
+ useReadingActions,
+ type ReadingActionEntry,
+} from "./reading-actions-context";
+import {
+ useWorkspaceMenuSection,
+ type WorkspaceMenuItem,
+} from "./workspace-menu-context";
import { TextUnitView, unitLabel } from "./TextUnitView";
import type { ReaderHeading } from "@/lib/reading-outline";
import {
@@ -116,6 +124,13 @@ export interface ReaderPaneProps {
* clicked while the header counted up (#1447).
*/
onLocatorChange?: (locator: number) => void;
+ /**
+ * Whether the pane shows its own annotation column beside the document.
+ * The workspace turns it off and lists notes in its navigator instead: a
+ * fourth column between the page and the companion left the page itself
+ * the narrowest thing on screen.
+ */
+ ownAnnotationList?: boolean;
}
/**
@@ -147,6 +162,7 @@ export function ReaderPane({
bookmarks = [],
onToggleBookmark,
onLocatorChange,
+ ownAnnotationList = true,
}: ReaderPaneProps) {
const { t } = useTranslation();
// Document + annotations live in the provider (workspace layout), so they
@@ -243,6 +259,33 @@ export function ReaderPane({
document.removeEventListener("pointerdown", onPointerDown);
};
}, [showMoreTools]);
+ // The history list used to close only by picking an entry or by the ⋯ that
+ // opened it. Opened from the workspace's menu there is no ⋯ here to click
+ // again, so it closes the way the menu does: click away, or Escape.
+ const historyPanelRef = useRef<HTMLDivElement>(null);
+ useEffect(() => {
+ if (!showHistory) return;
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.key !== "Escape") return;
+ event.preventDefault();
+ setShowHistory(false);
+ };
+ const onPointerDown = (event: PointerEvent) => {
+ const target = event.target as Node;
+ if (
+ !historyPanelRef.current?.contains(target) &&
+ !moreToolsMenuRef.current?.contains(target)
+ ) {
+ setShowHistory(false);
+ }
+ };
+ document.addEventListener("keydown", onKeyDown);
+ document.addEventListener("pointerdown", onPointerDown);
+ return () => {
+ document.removeEventListener("keydown", onKeyDown);
+ document.removeEventListener("pointerdown", onPointerDown);
+ };
+ }, [showHistory]);
const navigationNonceRef = useRef(0);
const pendingNavigationRef = useRef<{
mode: "push" | "replay";
@@ -731,6 +774,39 @@ export function ReaderPane({
window.getSelection()?.removeAllRanges();
}, [selection, material, clearSelection]);
+ // Inside a workspace the selection's AI actions sit on the popover, next to
+ // the text they act on, and answer in the companion column. They used to be
+ // a strip above the page that stayed greyed out until something was
+ // selected — by then the learner's eyes and pointer were on the page.
+ const readingActions = useReadingActions();
+ const aiActions = useMemo<PopoverAiAction[] | undefined>(() => {
+ if (!readingActions || readingActions.ageMode !== "default") return undefined;
+ if (!selection || !material) return undefined;
+ // One translate chip, pointed away from the passage's own language.
+ const skip = CJK_TEXT.test(selection.quote)
+ ? "translation:translate_zh"
+ : "translation:translate_en";
+ const target = { locator: selection.locator, selection: selection.quote };
+ return readingActions.actions
+ .filter((entry) => entry.needsSelection && entry.key !== skip)
+ .sort(
+ (left, right) =>
+ popoverActionRank(left.key) - popoverActionRank(right.key),
+ )
+ .map((entry: ReadingActionEntry) => ({
+ key: entry.key,
+ label: POPOVER_SHORT_LABELS[entry.key]
+ ? t(POPOVER_SHORT_LABELS[entry.key])
+ : entry.label,
+ title: entry.label,
+ onClick: () => {
+ void readingActions.run(entry, target);
+ clearSelection();
+ window.getSelection()?.removeAllRanges();
+ },
+ }));
+ }, [readingActions, selection, material, clearSelection, t]);
+
// -- export --------------------------------------------------------------
const runExport = useCallback(async () => {
@@ -768,6 +844,61 @@ export function ReaderPane({
? jump
: null;
+ // Inside a workspace these go to the top bar's ⋯, next to the collection's
+ // and the conversation's actions; standing alone, the pane keeps its own.
+ const hasHistory = locationHistory.entries.length > 0;
+ const menuItems = useMemo<WorkspaceMenuItem[] | null>(() => {
+ if (!material) return null;
+ const items: WorkspaceMenuItem[] = [];
+ if (hasHistory) {
+ items.push({
+ key: "history",
+ icon: History,
+ label: t("History"),
+ onSelect: () => setShowHistory(true),
+ });
+ }
+ items.push({
+ key: "follow",
+ icon: Crosshair,
+ label: t("Follow the assistant"),
+ hint: autoJump
+ ? t("Auto-jump on — the view follows what the assistant reads")
+ : t("Auto-jump off — the assistant will not move your view"),
+ active: autoJump,
+ onSelect: toggleAutoJump,
+ });
+ if (ownAnnotationList) {
+ items.push({
+ key: "annotations",
+ icon: showAnnotations ? PanelRightClose : PanelRightOpen,
+ label: t("Annotations"),
+ active: showAnnotations,
+ onSelect: () => setAnnotationPanel(!showAnnotations),
+ });
+ }
+ items.push({
+ key: "export",
+ icon: exporting ? Loader2 : Download,
+ label: t("Export annotated file"),
+ spinning: exporting,
+ disabled: exporting,
+ onSelect: () => void runExport(),
+ });
+ return items;
+ }, [
+ autoJump,
+ exporting,
+ hasHistory,
+ material,
+ ownAnnotationList,
+ runExport,
+ showAnnotations,
+ t,
+ toggleAutoJump,
+ ]);
+ const menuHosted = useWorkspaceMenuSection("material", menuItems);
+
return (
<div className="relative flex h-full min-w-0 flex-col border-r border-[var(--border)] bg-[var(--background)]">
<header className="flex h-11 shrink-0 items-center gap-1 border-b border-[var(--border)] px-2.5">
@@ -788,6 +919,11 @@ export function ReaderPane({
{material?.title || material?.filename || t("Immersive reading")}
</span>
+ {/* Back and Forward stay in the bar because they are how a learner
+ returns from a citation the assistant jumped to. Everything else
+ that used to sit here — history, auto-jump, export, the notes
+ panel — is a setting or a once-a-session action, and seven small
+ grey icons beside the title read as noise. They live under ⋯. */}
{locationHistory.entries.length > 0 && (
<>
<HeaderButton
@@ -804,14 +940,6 @@ export function ReaderPane({
locationHistory.index >= locationHistory.entries.length - 1
}
onClick={() => stepHistory(1)}
- className="hidden md:inline-flex"
- />
- <HeaderButton
- icon={History}
- label={t("History")}
- active={showHistory}
- onClick={() => setShowHistory((current) => !current)}
- className="hidden md:inline-flex"
/>
</>
)}
@@ -821,7 +949,7 @@ export function ReaderPane({
{/* The one place the reader's position is stated. Monospace is for
code, not for a line of UI copy; tabular figures alone stop the
number from jittering as the learner scrolls. */}
- <span className="hidden shrink-0 whitespace-nowrap text-[10.5px] tabular-nums text-[var(--muted-foreground)] md:inline">
+ <span className="hidden shrink-0 whitespace-nowrap px-1 text-[11.5px] tabular-nums text-[var(--muted-foreground)] md:inline">
{t("{{unit}} {{n}} / {{total}}", {
unit: unitWord,
n: currentLocator,
@@ -844,89 +972,44 @@ export function ReaderPane({
onClick={() => onToggleBookmark(currentLocator)}
/>
)}
- <HeaderButton
- icon={Crosshair}
- label={
- autoJump
- ? t(
- "Auto-jump on — the view follows what the assistant reads",
- )
- : t("Auto-jump off — the assistant will not move your view")
- }
- active={autoJump}
- onClick={toggleAutoJump}
- className="hidden md:inline-flex"
- />
- <HeaderButton
- icon={exporting ? Loader2 : Download}
- label={t("Export annotated file")}
- spinning={exporting}
- onClick={() => void runExport()}
- className="hidden md:inline-flex"
- />
- <HeaderButton
- icon={showAnnotations ? PanelRightClose : PanelRightOpen}
- label={t("Annotations")}
- active={showAnnotations}
- onClick={() => setAnnotationPanel(!showAnnotations)}
- // The panel itself only exists at `lg` and up — there is no room
- // for it beside the document on a narrow screen. Hiding the
- // trigger too keeps it from being a button that does nothing.
- className="hidden lg:inline-flex"
- />
+ {!menuHosted && (
+ <HeaderButton
+ icon={MoreHorizontal}
+ label={t("More")}
+ active={showMoreTools}
+ menu
+ buttonRef={moreToolsButtonRef}
+ onClick={() => {
+ setShowMoreTools(!showMoreTools);
+ if (!showMoreTools) setShowHistory(false);
+ }}
+ />
+ )}
</>
)}
- {material && (
- <HeaderButton
- icon={MoreHorizontal}
- label={t("More")}
- active={showMoreTools}
- menu
- buttonRef={moreToolsButtonRef}
- onClick={() => {
- setShowMoreTools(!showMoreTools);
- if (!showMoreTools) setShowHistory(false);
- }}
- className="inline-flex md:hidden"
- />
- )}
</header>
- {showMoreTools && material && (
+ {showMoreTools && material && !menuHosted && (
<div
ref={moreToolsMenuRef}
role="menu"
aria-label={t("More")}
- className="absolute top-11 right-2 z-40 w-56 rounded-xl border border-[var(--border)] bg-[var(--background)] p-1.5 shadow-xl md:hidden"
+ className="absolute top-11 right-2 z-40 w-64 rounded-xl border border-[var(--border)] bg-[var(--background)] p-1.5 shadow-xl"
>
{locationHistory.entries.length > 0 && (
- <>
- <MenuToolButton
- icon={ArrowRight}
- label={t("Forward")}
- disabled={
- locationHistory.index < 0 ||
- locationHistory.index >= locationHistory.entries.length - 1
- }
- onClick={() => {
- stepHistory(1);
- setShowMoreTools(false);
- }}
- />
- <MenuToolButton
- icon={History}
- label={t("History")}
- active={showHistory}
- onClick={() => {
- setShowHistory(true);
- setShowMoreTools(false);
- }}
- />
- </>
+ <MenuToolButton
+ icon={History}
+ label={t("History")}
+ onClick={() => {
+ setShowHistory(true);
+ setShowMoreTools(false);
+ }}
+ />
)}
<MenuToolButton
icon={Crosshair}
- label={
+ label={t("Follow the assistant")}
+ hint={
autoJump
? t("Auto-jump on — the view follows what the assistant reads")
: t("Auto-jump off — the assistant will not move your view")
@@ -934,6 +1017,18 @@ export function ReaderPane({
active={autoJump}
onClick={toggleAutoJump}
/>
+ {ownAnnotationList && (
+ <MenuToolButton
+ icon={showAnnotations ? PanelRightClose : PanelRightOpen}
+ label={t("Annotations")}
+ active={showAnnotations}
+ onClick={() => {
+ setAnnotationPanel(!showAnnotations);
+ setShowMoreTools(false);
+ }}
+ />
+ )}
+ <div className="my-1 h-px bg-[var(--border)]" aria-hidden />
<MenuToolButton
icon={exporting ? Loader2 : Download}
label={t("Export annotated file")}
@@ -947,7 +1042,9 @@ export function ReaderPane({
)}
{showHistory && locationHistory.entries.length > 0 && (
- <div className="absolute top-11 right-2 z-30 max-h-72 w-72 overflow-y-auto rounded-xl border border-[var(--border)] bg-[var(--background)] p-1.5 shadow-xl">
+ <div
+ ref={historyPanelRef}
+ className="absolute top-11 right-2 z-30 max-h-72 w-72 overflow-y-auto rounded-xl border border-[var(--border)] bg-[var(--background)] p-1.5 shadow-xl">
{[...locationHistory.entries]
.map((entry, index) => ({ entry, index }))
.reverse()
@@ -1087,7 +1184,7 @@ export function ReaderPane({
)}
</div>
- {material && showAnnotations && (
+ {material && ownAnnotationList && showAnnotations && (
<aside className="hidden w-[248px] shrink-0 border-l border-[var(--border)] bg-[var(--background)] lg:block">
<AnnotationList
annotations={annotations}
@@ -1115,6 +1212,7 @@ export function ReaderPane({
onNote={(note, color) => commitSelection("note", color, note)}
onCitation={(color) => commitSelection("citation", color)}
onAsk={askAboutSelection}
+ aiActions={aiActions}
// Closes the popover WITHOUT dropping the selection, so the
// toolbar's selection-gated actions stay reachable.
onDismiss={() => setPopoverOpen(false)}
@@ -1124,6 +1222,23 @@ export function ReaderPane({
);
}
+const CJK_TEXT = /[\u3040-\u30ff\u3400-\u9fff\uac00-\ud7af]/;
+
+const POPOVER_SHORT_LABELS: Record<string, string> = {
+ "vocabulary:explain": "Explain",
+ "translation:translate_en": "Translate",
+ "translation:translate_zh": "Translate",
+ "guided_learning:guide": "Guide me",
+};
+
+/** Built-ins first, in the order a reader reaches for them. */
+function popoverActionRank(key: string) {
+ if (key === "vocabulary:explain") return 0;
+ if (key.startsWith("translation:")) return 1;
+ if (key === "guided_learning:guide") return 2;
+ return 3;
+}
+
function HeaderButton({
icon: Icon,
label,
@@ -1176,6 +1291,7 @@ function MenuToolButton({
active,
spinning,
disabled,
+ hint,
}: {
icon: typeof FileText;
label: string;
@@ -1183,17 +1299,19 @@ function MenuToolButton({
active?: boolean;
spinning?: boolean;
disabled?: boolean;
+ /** A second line saying what the setting currently does. */
+ hint?: string;
}) {
return (
<button
type="button"
role={active === undefined ? "menuitem" : "menuitemcheckbox"}
- title={label}
- aria-label={label}
+ title={hint || label}
+ aria-label={hint ? `${label}. ${hint}` : label}
aria-checked={active}
disabled={spinning || disabled}
onClick={onClick}
- className={`flex h-9 w-full items-center gap-2 rounded-lg px-2.5 text-left text-[12px] transition disabled:cursor-default ${
+ className={`flex w-full items-center gap-2 rounded-lg px-2.5 text-left text-[12px] transition disabled:cursor-default ${hint ? "py-1.5" : "h-9"} ${
active
? "bg-[color-mix(in_srgb,var(--primary)_12%,transparent)] text-[var(--primary)]"
: "text-[var(--foreground)] hover:bg-[var(--muted)] disabled:opacity-35 disabled:hover:bg-transparent"
@@ -1207,7 +1325,14 @@ function MenuToolButton({
: "text-[var(--muted-foreground)]"
}
/>
- <span className="min-w-0 flex-1 truncate">{label}</span>
+ <span className="min-w-0 flex-1">
+ <span className="block truncate">{label}</span>
+ {hint ? (
+ <span className="block text-[10.5px] leading-snug opacity-75">
+ {hint}
+ </span>
+ ) : null}
+ </span>
</button>
);
}
diff --git a/web/components/reading/ReadingActionsProvider.tsx b/web/components/reading/ReadingActionsProvider.tsx
new file mode 100644
index 000000000..46e63a017
--- /dev/null
+++ b/web/components/reading/ReadingActionsProvider.tsx
@@ -0,0 +1,240 @@
+"use client";
+
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { fetchAuthStatus } from "@/lib/auth";
+import { getOwnLearnerProfile } from "@/lib/profile-api";
+import {
+ primaryReadingActionRank,
+ resolveReadingAgeMode,
+ type ReadingAgeMode,
+} from "@/lib/reading-age-presentation";
+import {
+ listReadingExtensions,
+ runReadingExtension,
+ type ReadingExtensionManifest,
+} from "@/lib/reading-api";
+import { builtInActionLabel } from "./ReadingExtensionBar";
+import {
+ ReadingActionsContext,
+ type ReadingActionCard,
+ type ReadingActionEntry,
+ type ReadingActionsValue,
+} from "./reading-actions-context";
+
+const MAX_CARDS = 6;
+
+/**
+ * Reading actions for a whole workspace: one catalog, one place results land.
+ *
+ * The reader's selection popover starts them, the companion column shows
+ * them, the header's read-aloud button speaks through them. Before this they
+ * were a strip of chips above the page that owned its own results, and a
+ * learner had two different places an AI answer could appear depending on
+ * which button they had pressed.
+ */
+export function ReadingActionsProvider({
+ materialId,
+ locator,
+ onStart,
+ children,
+}: {
+ /** The material open in the reader; actions run against it. */
+ materialId: string | null;
+ /** The viewport locator, used when an action has no selection of its own. */
+ locator: number;
+ /** A result is on its way — the workspace opens the companion for it. */
+ onStart?: () => void;
+ children: React.ReactNode;
+}) {
+ const { i18n, t } = useTranslation();
+ const [extensions, setExtensions] = useState<ReadingExtensionManifest[]>([]);
+ const [ageMode, setAgeMode] = useState<ReadingAgeMode>("default");
+ const [cards, setCards] = useState<ReadingActionCard[]>([]);
+ const [busyKey, setBusyKey] = useState("");
+ const [speaking, setSpeaking] = useState(false);
+ const onStartRef = useRef(onStart);
+ onStartRef.current = onStart;
+
+ useEffect(() => {
+ let active = true;
+ void listReadingExtensions()
+ .then((rows) => {
+ if (active) setExtensions(rows);
+ })
+ .catch(() => {
+ // No catalog means no actions; reading and chat still work.
+ });
+ return () => {
+ active = false;
+ };
+ }, []);
+
+ useEffect(() => {
+ let active = true;
+ void fetchAuthStatus().then(async (status) => {
+ const learnerMode =
+ status?.preset === "learner" || Boolean(status?.learning_policy);
+ if (!learnerMode) return;
+ const profile = await getOwnLearnerProfile().catch(() => null);
+ if (active) {
+ setAgeMode(
+ resolveReadingAgeMode({
+ learnerMode,
+ profileAge: profile?.age,
+ policyAgeBand: status?.learning_policy?.age_band,
+ }),
+ );
+ }
+ });
+ return () => {
+ active = false;
+ };
+ }, []);
+
+ const stopSpeaking = useCallback(() => {
+ window.speechSynthesis?.cancel();
+ setSpeaking(false);
+ }, []);
+
+ // A card answers a question about one document; switching documents leaves
+ // it describing a page that is no longer on screen.
+ useEffect(() => {
+ setCards([]);
+ }, [materialId]);
+
+ // Speech stops the moment the reader leaves the passage being read, the
+ // same promise the standalone toolbar makes.
+ useEffect(
+ () => () => {
+ window.speechSynthesis?.cancel();
+ setSpeaking(false);
+ },
+ [locator, materialId],
+ );
+
+ const actions = useMemo<ReadingActionEntry[]>(
+ () =>
+ extensions
+ .flatMap((extension) =>
+ extension.actions.map((action) => {
+ const key = `${extension.id}:${action.id}`;
+ const builtIn = builtInActionLabel(extension.id, action.id);
+ return {
+ key,
+ extension,
+ action,
+ label: builtIn ? t(builtIn) : action.label,
+ needsSelection: action.requires.includes("selection"),
+ };
+ }),
+ )
+ .sort((left, right) => {
+ const leftRank = primaryReadingActionRank(left.key);
+ const rightRank = primaryReadingActionRank(right.key);
+ return (
+ (leftRank < 0 ? 3 : leftRank) - (rightRank < 0 ? 3 : rightRank)
+ );
+ }),
+ [extensions, t],
+ );
+
+ const run = useCallback<ReadingActionsValue["run"]>(
+ async (entry, target = {}) => {
+ if (!materialId) return;
+ const selection = (target.selection || "").trim();
+ const requestedLocator = target.locator ?? locator;
+ const speech = entry.key === "read_aloud:read";
+ const cardId = `${entry.key}-${Date.now()}`;
+ const card: ReadingActionCard = {
+ id: cardId,
+ key: entry.key,
+ label: entry.label,
+ quote: selection,
+ locator: requestedLocator,
+ materialId,
+ status: "running",
+ };
+ const open = (row: ReadingActionCard) => {
+ onStartRef.current?.();
+ setCards((current) => [...current, row].slice(-MAX_CARDS));
+ };
+ setBusyKey(entry.key);
+ // Read-aloud has nothing to show but the header's stop button, so it
+ // only gets a card when it fails — silence would read as "it worked".
+ if (!speech) open(card);
+ const settle = (patch: Partial<ReadingActionCard>) => {
+ if (speech) {
+ if (patch.status === "error") open({ ...card, ...patch });
+ return;
+ }
+ setCards((current) =>
+ current.map((row) => (row.id === cardId ? { ...row, ...patch } : row)),
+ );
+ };
+ try {
+ const next = await runReadingExtension(
+ materialId,
+ entry.extension.id,
+ entry.action.id,
+ {
+ locator: requestedLocator,
+ selection,
+ locale: i18n.language,
+ },
+ );
+ if (next.type === "browser_speech") {
+ const text = String(next.payload.text || "");
+ if (!("speechSynthesis" in window) || !text) {
+ settle({
+ status: "error",
+ error: t("No speech voice is available in this browser."),
+ });
+ return;
+ }
+ window.speechSynthesis.cancel();
+ const utterance = new SpeechSynthesisUtterance(text);
+ utterance.lang = String(next.payload.locale || i18n.language);
+ utterance.onend = () => setSpeaking(false);
+ utterance.onerror = () => setSpeaking(false);
+ window.speechSynthesis.speak(utterance);
+ setSpeaking(true);
+ return;
+ }
+ settle({ status: "done", result: next });
+ } catch (error) {
+ settle({
+ status: "error",
+ error: error instanceof Error ? error.message : String(error),
+ });
+ } finally {
+ setBusyKey((current) => (current === entry.key ? "" : current));
+ }
+ },
+ [i18n.language, locator, materialId, t],
+ );
+
+ const dismiss = useCallback((cardId: string) => {
+ setCards((current) => current.filter((card) => card.id !== cardId));
+ }, []);
+
+ const value = useMemo<ReadingActionsValue>(
+ () => ({
+ ageMode,
+ actions,
+ cards,
+ speaking,
+ busyKey,
+ run,
+ stopSpeaking,
+ dismiss,
+ }),
+ [actions, ageMode, busyKey, cards, dismiss, run, speaking, stopSpeaking],
+ );
+
+ return (
+ <ReadingActionsContext.Provider value={value}>
+ {children}
+ </ReadingActionsContext.Provider>
+ );
+}
diff --git a/web/components/reading/ReadingExtensionBar.tsx b/web/components/reading/ReadingExtensionBar.tsx
index 1ba080fec..9f8a5092b 100644
--- a/web/components/reading/ReadingExtensionBar.tsx
+++ b/web/components/reading/ReadingExtensionBar.tsx
@@ -18,6 +18,7 @@ import {
type ReadingExtensionManifest,
type ReadingExtensionResult,
} from "@/lib/reading-api";
+import { useReadingActions } from "./reading-actions-context";
type VocabularyTerm = {
term: string;
@@ -40,14 +41,7 @@ type TranslationResult = {
const PRIMARY_ACTION_ICONS = [Volume2, BookOpenText, PencilLine] as const;
-export function ReadingExtensionBar({
- materialId,
- locator,
- selectionLocator,
- selection,
- sessionId,
- onError,
-}: {
+type ReadingExtensionBarProps = {
materialId: string;
locator: number;
/**
@@ -61,7 +55,33 @@ export function ReadingExtensionBar({
selection?: string;
sessionId?: string | null;
onError: (message: string) => void;
-}) {
+};
+
+/**
+ * The strip of action buttons above the page.
+ *
+ * Inside a reading workspace an adult reader does not get it: the same
+ * actions live where they are needed — on the selection popover, in the
+ * companion's tools menu and on the header's read-aloud button — and their
+ * results land in the companion column. A strip of chips that were greyed
+ * out until something was selected, with a result slot of its own between
+ * the toolbar and the page, was a third place to look. Younger learners keep
+ * it: three big coloured buttons are the whole point of their layout.
+ */
+export function ReadingExtensionBar(props: ReadingExtensionBarProps) {
+ const shared = useReadingActions();
+ if (shared && shared.ageMode === "default") return null;
+ return <ExtensionToolbar {...props} />;
+}
+
+function ExtensionToolbar({
+ materialId,
+ locator,
+ selectionLocator,
+ selection,
+ sessionId,
+ onError,
+}: ReadingExtensionBarProps) {
const { i18n, t } = useTranslation();
const [extensions, setExtensions] = useState<ReadingExtensionManifest[]>([]);
const [busy, setBusy] = useState("");
@@ -272,7 +292,7 @@ export function ReadingExtensionBar({
);
}
-function builtInActionLabel(extensionId: string, actionId: string) {
+export function builtInActionLabel(extensionId: string, actionId: string) {
if (extensionId === "read_aloud" && actionId === "read") {
return "Read aloud";
}
@@ -294,7 +314,7 @@ function builtInActionLabel(extensionId: string, actionId: string) {
return "";
}
-function ExtensionResult({
+export function ExtensionResult({
result,
materialId,
locator,
@@ -302,6 +322,7 @@ function ExtensionResult({
closeLabel,
onClose,
onError,
+ variant = "strip",
}: {
result: ReadingExtensionResult;
materialId: string;
@@ -310,6 +331,12 @@ function ExtensionResult({
closeLabel: string;
onClose: () => void;
onError: (message: string) => void;
+ /**
+ * `strip` is the band under the toolbar, with its own title and close
+ * button. `card` is the body of a companion card, whose header already
+ * carries both.
+ */
+ variant?: "strip" | "card";
}) {
const questions = Array.isArray(result.payload.questions)
? (result.payload.questions as QuizQuestion[])
@@ -337,17 +364,28 @@ function ExtensionResult({
note: String(result.payload.note || ""),
};
const body = String(result.payload.body || result.payload.overview || "");
+ const card = variant === "card";
return (
- <section className="relative shrink-0 border-b border-[var(--border)] bg-[var(--card)] px-3 py-3 text-xs text-[var(--foreground)]">
- <button
- type="button"
- onClick={onClose}
- aria-label={closeLabel}
- className="absolute right-2 top-2 text-[var(--muted-foreground)]"
- >
- <X size={14} />
- </button>
- <h3 className="pr-6 font-semibold">{result.title}</h3>
+ <section
+ className={
+ card
+ ? "text-[12.5px] leading-relaxed text-[var(--foreground)] [&>*:first-child]:mt-0"
+ : "relative shrink-0 border-b border-[var(--border)] bg-[var(--card)] px-3 py-3 text-xs text-[var(--foreground)]"
+ }
+ >
+ {card ? null : (
+ <>
+ <button
+ type="button"
+ onClick={onClose}
+ aria-label={closeLabel}
+ className="absolute right-2 top-2 text-[var(--muted-foreground)]"
+ >
+ <X size={14} />
+ </button>
+ <h3 className="pr-6 font-semibold">{result.title}</h3>
+ </>
+ )}
{result.message ? (
<p className="mt-1 text-[var(--muted-foreground)]">{result.message}</p>
) : null}
diff --git a/web/components/reading/library/FolderDialog.tsx b/web/components/reading/library/FolderDialog.tsx
new file mode 100644
index 000000000..71836ddd9
--- /dev/null
+++ b/web/components/reading/library/FolderDialog.tsx
@@ -0,0 +1,209 @@
+"use client";
+
+import { Loader2 } from "lucide-react";
+import { useEffect, useId, useState, type FormEvent } from "react";
+import { useTranslation } from "react-i18next";
+
+import { useChatWorkspaces } from "@/hooks/useChatWorkspaces";
+import {
+ createReadingWorkspace,
+ updateReadingWorkspace,
+ type ReadingWorkspace,
+} from "@/lib/reading-workspace-api";
+
+import { FOLDER_COLORS, FolderGlyph, folderTone } from "./FolderGlyph";
+
+/**
+ * Creating a collection and renaming or recolouring one are the same small
+ * form. Creating also says where the collection lives: a workspace holds
+ * many collections, and a collection's files and conversations are stored
+ * in exactly one of them.
+ */
+export function FolderDialog({
+ collection,
+ workspaceId,
+ lockWorkspace = false,
+ onClose,
+ onSaved,
+}: {
+ /** Present when editing; absent when creating. */
+ collection?: ReadingWorkspace;
+ /** The workspace a new collection starts in. */
+ workspaceId: string;
+ /** A course keeps what it creates in its own workspace. */
+ lockWorkspace?: boolean;
+ onClose: () => void;
+ onSaved: (collection: ReadingWorkspace, workspaceId: string) => void;
+}) {
+ const { t } = useTranslation();
+ const headingId = useId();
+ const { workspaces } = useChatWorkspaces();
+ const [title, setTitle] = useState(collection?.title ?? "");
+ const [color, setColor] = useState(collection?.color ?? "");
+ const [destination, setDestination] = useState(workspaceId);
+ const [working, setWorking] = useState(false);
+ const [error, setError] = useState("");
+
+ useEffect(() => {
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.key !== "Escape") return;
+ event.preventDefault();
+ onClose();
+ };
+ document.addEventListener("keydown", onKeyDown);
+ return () => document.removeEventListener("keydown", onKeyDown);
+ }, [onClose]);
+
+ const destinations = [
+ { id: "", name: t("Default workspace") },
+ ...workspaces
+ .filter((row) => !row.archived && row.status === "ready")
+ .map((row) => ({ id: row.workspace_id, name: row.display_name })),
+ ];
+ // Only worth asking when there is somewhere else to put it.
+ const askWorkspace =
+ !collection &&
+ !lockWorkspace &&
+ destinations.length > 1 &&
+ destinations.some((row) => row.id === destination);
+
+ const submit = (event: FormEvent) => {
+ event.preventDefault();
+ if (working) return;
+ setWorking(true);
+ setError("");
+ const name = title.trim() || t("Untitled collection");
+ const saved = collection
+ ? updateReadingWorkspace(
+ collection.workspace_id,
+ { title: name, color },
+ collection.content_workspace_id ?? "",
+ ).then((row) => onSaved(row, collection.content_workspace_id ?? ""))
+ : createReadingWorkspace({ title: name, color }, destination).then(
+ (row) => onSaved(row, destination),
+ );
+ void saved
+ .catch((caught) =>
+ setError(
+ caught instanceof Error ? caught.message : t("Could not save."),
+ ),
+ )
+ .finally(() => setWorking(false));
+ };
+
+ return (
+ <div
+ className="fixed inset-0 z-[110] flex items-center justify-center bg-[var(--overlay)] p-4"
+ onMouseDown={(event) => {
+ if (event.target === event.currentTarget) onClose();
+ }}
+ >
+ <form
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby={headingId}
+ onSubmit={submit}
+ className="w-full max-w-[380px] rounded-xl border border-[var(--border)] bg-[var(--card)] p-5 shadow-lg dark:bg-[var(--popover)]"
+ >
+ <h2 id={headingId} className="font-serif text-[17px] font-semibold">
+ {collection ? t("Edit collection") : t("New collection")}
+ </h2>
+
+ <div className="mt-4 flex items-center gap-3">
+ <FolderGlyph
+ color={color}
+ files={collection?.tabs.length ?? 0}
+ size={44}
+ className="shrink-0"
+ />
+ <input
+ autoFocus
+ value={title}
+ onChange={(event) => setTitle(event.target.value)}
+ maxLength={300}
+ placeholder={t("Untitled collection")}
+ aria-label={t("Collection name")}
+ className="h-9 min-w-0 flex-1 rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 text-[13px] outline-none transition placeholder:text-[var(--muted-foreground)] focus:border-[var(--ring)]"
+ />
+ </div>
+
+ <fieldset className="mt-4">
+ <legend className="text-[11.5px] font-medium text-[var(--muted-foreground)]">
+ {t("Color")}
+ </legend>
+ <div className="mt-2 flex flex-wrap gap-2">
+ {FOLDER_COLORS.map((row) => {
+ const selected = row.key === color;
+ return (
+ <button
+ key={row.key || "default"}
+ type="button"
+ onClick={() => setColor(row.key)}
+ aria-label={t(row.label)}
+ aria-pressed={selected}
+ title={t(row.label)}
+ className="size-6 rounded-full transition hover:scale-110"
+ style={{
+ background: row.tone,
+ boxShadow: selected
+ ? `0 0 0 2px var(--card), 0 0 0 3.5px ${folderTone(row.key)}`
+ : undefined,
+ }}
+ />
+ );
+ })}
+ </div>
+ </fieldset>
+
+ {askWorkspace && (
+ <label className="mt-4 block">
+ <span className="text-[11.5px] font-medium text-[var(--muted-foreground)]">
+ {t("Workspace")}
+ </span>
+ <select
+ value={destination}
+ onChange={(event) => setDestination(event.target.value)}
+ aria-label={t("Workspace")}
+ className="mt-2 h-9 w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-2.5 text-[13px] outline-none focus:border-[var(--ring)]"
+ >
+ {destinations.map((row) => (
+ <option key={row.id} value={row.id}>
+ {row.name}
+ </option>
+ ))}
+ </select>
+ <span className="mt-1.5 block text-[11px] leading-relaxed text-[var(--muted-foreground)]">
+ {t(
+ "The collection's files and reading conversations are kept in this workspace.",
+ )}
+ </span>
+ </label>
+ )}
+
+ {error && (
+ <p role="alert" className="mt-3 text-[11px] text-[var(--destructive)]">
+ {error}
+ </p>
+ )}
+
+ <div className="mt-5 flex justify-end gap-2">
+ <button
+ type="button"
+ onClick={onClose}
+ className="h-8 rounded-lg px-3 text-[12px] text-[var(--muted-foreground)] hover:bg-[var(--muted)]"
+ >
+ {t("Cancel")}
+ </button>
+ <button
+ type="submit"
+ disabled={working}
+ className="inline-flex h-8 items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3.5 text-[12px] font-semibold text-[var(--primary-foreground)] transition hover:opacity-90 disabled:opacity-50"
+ >
+ {working && <Loader2 size={12} className="animate-spin" />}
+ {collection ? t("Save") : t("Create")}
+ </button>
+ </div>
+ </form>
+ </div>
+ );
+}
diff --git a/web/components/reading/library/FolderGlyph.tsx b/web/components/reading/library/FolderGlyph.tsx
new file mode 100644
index 000000000..0139e4941
--- /dev/null
+++ b/web/components/reading/library/FolderGlyph.tsx
@@ -0,0 +1,82 @@
+"use client";
+
+/**
+ * A collection's folder tint. The server keeps only the key; the tone is a
+ * `--folder-*` token in globals.css so a palette change never needs a
+ * migration and dark themes get their own shade. "" is the neutral folder
+ * every collection had before colours existed.
+ */
+export const FOLDER_COLORS = [
+ { key: "", label: "Default", tone: "var(--folder-default)" },
+ { key: "blue", label: "Blue", tone: "var(--folder-blue)" },
+ { key: "teal", label: "Teal", tone: "var(--folder-teal)" },
+ { key: "green", label: "Green", tone: "var(--folder-green)" },
+ { key: "amber", label: "Amber", tone: "var(--folder-amber)" },
+ { key: "orange", label: "Orange", tone: "var(--folder-orange)" },
+ { key: "rose", label: "Rose", tone: "var(--folder-rose)" },
+ { key: "violet", label: "Violet", tone: "var(--folder-violet)" },
+ { key: "slate", label: "Slate", tone: "var(--folder-slate)" },
+] as const;
+
+export function folderTone(color: string | undefined): string {
+ return (
+ FOLDER_COLORS.find((row) => row.key === (color ?? ""))?.tone ??
+ FOLDER_COLORS[0].tone
+ );
+}
+
+/**
+ * A folder drawn with one sheet peeking out per file (up to three), so an
+ * empty collection reads as empty at a glance.
+ */
+export function FolderGlyph({
+ color,
+ files,
+ size = 56,
+ className,
+}: {
+ color?: string;
+ files: number;
+ size?: number;
+ className?: string;
+}) {
+ const tone = folderTone(color);
+ const sheets = Math.min(Math.max(files, 0), 3);
+ return (
+ <svg
+ viewBox="0 0 64 50"
+ width={size}
+ height={(size * 50) / 64}
+ aria-hidden
+ className={className}
+ >
+ <path
+ d="M4 8a4 4 0 0 1 4-4h13.6a4 4 0 0 1 2.9 1.2L28 9h28a4 4 0 0 1 4 4v29a4 4 0 0 1-4 4H8a4 4 0 0 1-4-4Z"
+ fill={`color-mix(in srgb, ${tone} 82%, black)`}
+ />
+ {Array.from({ length: sheets }, (_, index) => (
+ <rect
+ key={index}
+ x={10 + index * 3}
+ y={12 - index * 2.5}
+ width={44 - index * 6}
+ height={28}
+ rx={2}
+ fill="var(--card)"
+ stroke={`color-mix(in srgb, ${tone} 35%, var(--border))`}
+ strokeWidth={0.8}
+ />
+ ))}
+ <path
+ d="M4 20a4 4 0 0 1 4-4h48a4 4 0 0 1 4 4v22a4 4 0 0 1-4 4H8a4 4 0 0 1-4-4Z"
+ fill={tone}
+ />
+ <path
+ d="M8 16.5h48"
+ stroke="white"
+ strokeOpacity={0.28}
+ strokeWidth={1}
+ />
+ </svg>
+ );
+}
diff --git a/web/components/reading/library/MaterialLibrary.tsx b/web/components/reading/library/MaterialLibrary.tsx
index a396ee7a8..e7baa7179 100644
--- a/web/components/reading/library/MaterialLibrary.tsx
+++ b/web/components/reading/library/MaterialLibrary.tsx
@@ -9,7 +9,7 @@ import {
import { learningLibrary, libraryItemKey } from "@/lib/learning-library";
import { activeWorkspaceId, scopedUrl } from "@/lib/workspace-scope";
import { useLearningCreation, requestedLearningCreation, useLibraryFilter } from "@/components/learning/LibraryWorkspace";
-import { readingCollectionRoute } from "@/lib/learning-routes";
+import { readingCollectionRoute, readingFolderRoute } from "@/lib/learning-routes";
import Link from "next/link";
import { useRouter } from "next/navigation";
@@ -69,7 +69,7 @@ export function MaterialLibraryPage() {
const router = useRouter();
const [showUpload, setShowUpload] = useState(requestedLearningCreation);
const creation = useLearningCreation(() => setShowUpload(true));
- const { rows: materials, control } = useLibraryFilter(allMaterials);
+ const { rows: materials, picker } = useLibraryFilter(allMaterials);
const [menuFor, setMenuFor] = useState<string | null>(null);
const [assignFor, setAssignFor] = useState<ReadingLibraryMaterial | null>(
null
@@ -142,7 +142,6 @@ export function MaterialLibraryPage() {
onAction={creation.begin}
>
{creation.dialog}
- {control}
<div className="mt-5 flex flex-col gap-3 border-b border-[var(--border)] pb-3 sm:flex-row sm:items-center">
<label className="flex h-8 min-w-0 flex-1 items-center gap-2 rounded-lg border border-[var(--border)] px-2.5 sm:max-w-[330px]">
<Search
@@ -165,9 +164,12 @@ export function MaterialLibraryPage() {
</button>
)}
</label>
- <span className="text-[11px] text-[var(--muted-foreground)] sm:ml-auto">
- {t("{{count}} materials", { count: tally.all })}
- </span>
+ <div className="flex items-center gap-2 sm:ml-auto">
+ {picker}
+ <span className="text-[11px] text-[var(--muted-foreground)]">
+ {t("{{count}} materials", { count: tally.all })}
+ </span>
+ </div>
</div>
<div className="mt-3 flex flex-wrap items-center gap-1.5">
@@ -438,14 +440,15 @@ function MaterialRow({
<span className="hidden min-w-0 items-center gap-1 sm:flex">
{collections.length ? (
<>
- {/* The first chip takes the room the second one leaves, so a
- single membership reads in full and two share the column. */}
+ {/* The first chip may shrink into the room the second one
+ leaves, so a long title truncates before the second is
+ pushed out — but it never grows past its own title. */}
{collections.slice(0, 2).map((row, index) => (
<Link
key={row.workspace_id}
- href={readingCollectionRoute(row.workspace_id, material.content_workspace_id ?? "")}
+ href={readingFolderRoute(row.workspace_id, material.content_workspace_id ?? "")}
className={`min-w-0 truncate rounded-full border border-[var(--border)] px-2 py-0.5 text-[10.5px] hover:border-[var(--primary)] hover:text-[var(--primary)] ${
- index === 0 ? "flex-1" : "max-w-[96px] shrink-0"
+ index === 0 ? "shrink" : "max-w-[96px] shrink-0"
}`}
>
{row.title}
diff --git a/web/components/reading/library/ReadingFolder.tsx b/web/components/reading/library/ReadingFolder.tsx
new file mode 100644
index 000000000..490fd509f
--- /dev/null
+++ b/web/components/reading/library/ReadingFolder.tsx
@@ -0,0 +1,454 @@
+"use client";
+
+import {
+ ArrowRight,
+ BookOpen,
+ ChevronRight,
+ CircleAlert,
+ Loader2,
+ MessageSquare,
+ MoreHorizontal,
+ Palette,
+ Plus,
+ Trash2,
+ X,
+} from "lucide-react";
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { useCallback, useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
+
+import { LearningSkeleton } from "@/components/learning/LearningShell";
+import { useChatWorkspaces } from "@/hooks/useChatWorkspaces";
+import {
+ READING_HOME,
+ readingCollectionRoute,
+ readingSessionRoute,
+} from "@/lib/learning-routes";
+import {
+ activateReadingMaterial,
+ getReadingWorkspace,
+ removeReadingWorkspaceMaterial,
+ type ReadingConversation,
+ type ReadingWorkspace,
+ type ReadingWorkspaceTab,
+} from "@/lib/reading-workspace-api";
+import { activeWorkspaceId, scopedUrl } from "@/lib/workspace-scope";
+
+import { AddMaterialsDialog } from "./AddMaterialsDialog";
+import { FolderDialog } from "./FolderDialog";
+import { FolderGlyph } from "./FolderGlyph";
+import { DeleteCollectionDialog } from "./ReadingLibrary";
+import { MaterialGlyph, materialDetail, relativeDate } from "./shared";
+
+/**
+ * A collection opened like a folder: what is in it, what has been said about
+ * it, and one way in. Reading always opens the whole folder — every file is a
+ * tab of the same reader and shares its conversations — so picking a file here
+ * only chooses which tab comes first.
+ */
+export function ReadingFolderPage({ folderId }: { folderId: string }) {
+ const { t, i18n } = useTranslation();
+ const router = useRouter();
+ const { workspaces } = useChatWorkspaces();
+ const [folder, setFolder] = useState<ReadingWorkspace | null>(null);
+ const [sessions, setSessions] = useState<ReadingConversation[]>([]);
+ const [error, setError] = useState("");
+ const [loading, setLoading] = useState(true);
+ const [opening, setOpening] = useState<string | null>(null);
+ const [menuOpen, setMenuOpen] = useState(false);
+ const [dialog, setDialog] = useState<"add" | "edit" | "delete" | null>(null);
+
+ // The URL names the workspace the folder is stored in; every request on
+ // this page is scoped by it.
+ const contentWorkspace = activeWorkspaceId();
+ const workspaceLabel =
+ workspaces.find((row) => row.workspace_id === contentWorkspace)
+ ?.display_name ||
+ (contentWorkspace ? contentWorkspace : t("Default workspace"));
+
+ const refresh = useCallback(async () => {
+ try {
+ const result = await getReadingWorkspace(folderId);
+ setFolder(result.workspace);
+ setSessions(
+ [...result.sessions].sort((a, b) => b.updated_at - a.updated_at),
+ );
+ setError("");
+ } catch (caught) {
+ setError(
+ caught instanceof Error ? caught.message : t("Could not open this collection."),
+ );
+ } finally {
+ setLoading(false);
+ }
+ }, [folderId, t]);
+
+ useEffect(() => {
+ void refresh();
+ }, [refresh]);
+
+ // Files still being prepared settle on their own; poll until they do so the
+ // page never shows a spinner that has long since finished.
+ const preparing = Boolean(
+ folder?.tabs.some(
+ (tab) =>
+ tab.material.status === "processing" ||
+ tab.material.status === "queued",
+ ),
+ );
+ useEffect(() => {
+ if (!preparing) return;
+ const timer = window.setInterval(() => void refresh(), 4000);
+ return () => window.clearInterval(timer);
+ }, [preparing, refresh]);
+
+ const readerHref = readingCollectionRoute(folderId, contentWorkspace);
+
+ const openFile = async (tab: ReadingWorkspaceTab) => {
+ if (opening) return;
+ setOpening(tab.material.material_id);
+ try {
+ await activateReadingMaterial(folderId, tab.material.material_id);
+ } catch {
+ // The reader still opens; it just starts on the last active file.
+ }
+ router.push(readerHref);
+ };
+
+ const removeFile = async (tab: ReadingWorkspaceTab) => {
+ try {
+ setFolder(
+ await removeReadingWorkspaceMaterial(folderId, tab.material.material_id),
+ );
+ } catch (caught) {
+ setError(caught instanceof Error ? caught.message : t("Could not save."));
+ }
+ };
+
+ if (loading) {
+ return (
+ <FolderFrame>
+ <LearningSkeleton />
+ </FolderFrame>
+ );
+ }
+
+ if (!folder) {
+ return (
+ <FolderFrame>
+ <div className="flex flex-col items-center py-24 text-center">
+ <CircleAlert size={24} className="text-[var(--primary)]" />
+ <p className="mt-3 text-[13px] font-medium">{error}</p>
+ <Link
+ href={scopedUrl(READING_HOME)}
+ className="mt-5 rounded-lg bg-[var(--primary)] px-3.5 py-2 text-[12px] font-semibold text-[var(--primary-foreground)]"
+ >
+ {t("Back to collections")}
+ </Link>
+ </div>
+ </FolderFrame>
+ );
+ }
+
+ const files = folder.tabs;
+ const collection = { ...folder, content_workspace_id: contentWorkspace };
+
+ return (
+ <FolderFrame>
+ <nav
+ aria-label={t("Breadcrumb")}
+ className="flex min-w-0 items-center gap-1 text-[12px] text-[var(--muted-foreground)]"
+ >
+ <Link
+ href={scopedUrl(READING_HOME)}
+ className="shrink-0 hover:text-[var(--foreground)]"
+ >
+ {t("Immersive Reading")}
+ </Link>
+ <ChevronRight size={12} className="shrink-0 opacity-60" />
+ <span className="shrink-0">{workspaceLabel}</span>
+ <ChevronRight size={12} className="shrink-0 opacity-60" />
+ <span className="truncate text-[var(--foreground)]">{folder.title}</span>
+ </nav>
+
+ <header className="mt-6 flex flex-col gap-5 sm:flex-row sm:items-end">
+ <FolderGlyph
+ color={folder.color}
+ files={files.length}
+ size={84}
+ className="shrink-0"
+ />
+ <div className="min-w-0 flex-1">
+ <h1 className="font-serif text-[26px] font-semibold leading-tight tracking-[-0.02em] md:text-[28px]">
+ {folder.title}
+ </h1>
+ <p className="mt-1.5 text-[12.5px] text-[var(--muted-foreground)]">
+ {t("{{count}} files", { count: files.length })}
+ {" · "}
+ {t("Stored in {{workspace}}", { workspace: workspaceLabel })}
+ </p>
+ </div>
+ <div className="relative flex shrink-0 items-center gap-2">
+ {files.length ? (
+ <Link
+ href={readerHref}
+ className="inline-flex h-9 items-center gap-1.5 rounded-lg bg-[var(--primary)] px-4 text-[12.5px] font-semibold text-[var(--primary-foreground)] transition hover:opacity-90"
+ >
+ <BookOpen size={14} />
+ {t("Start reading")}
+ </Link>
+ ) : null}
+ <button
+ type="button"
+ onClick={() => setDialog("add")}
+ className="inline-flex h-9 items-center gap-1.5 rounded-lg border border-[var(--border)] px-3.5 text-[12.5px] transition hover:bg-[var(--muted)]"
+ >
+ <Plus size={14} />
+ {t("Add material")}
+ </button>
+ <button
+ type="button"
+ onClick={() => setMenuOpen((open) => !open)}
+ aria-label={t("Collection menu")}
+ aria-expanded={menuOpen}
+ className="flex size-9 items-center justify-center rounded-lg text-[var(--muted-foreground)] transition hover:bg-[var(--muted)]"
+ >
+ <MoreHorizontal size={15} />
+ </button>
+ {menuOpen && (
+ <>
+ <div
+ className="fixed inset-0 z-10"
+ onClick={() => setMenuOpen(false)}
+ />
+ <div
+ role="menu"
+ className="absolute right-0 top-11 z-20 w-44 rounded-lg border border-[var(--border)] bg-[var(--card)] p-1 text-[12px] shadow-md dark:bg-[var(--popover)]"
+ >
+ <button
+ type="button"
+ role="menuitem"
+ onClick={() => {
+ setMenuOpen(false);
+ setDialog("edit");
+ }}
+ className="flex w-full items-center gap-2 rounded-md px-2.5 py-2 text-left hover:bg-[var(--muted)]"
+ >
+ <Palette size={12} />
+ {t("Rename or recolor")}
+ </button>
+ <button
+ type="button"
+ role="menuitem"
+ onClick={() => {
+ setMenuOpen(false);
+ setDialog("delete");
+ }}
+ className="flex w-full items-center gap-2 rounded-md px-2.5 py-2 text-left text-[var(--destructive)] hover:bg-[var(--muted)]"
+ >
+ <Trash2 size={12} />
+ {t("Delete collection")}
+ </button>
+ </div>
+ </>
+ )}
+ </div>
+ </header>
+
+ {error && (
+ <p role="alert" className="mt-4 text-[12px] text-[var(--destructive)]">
+ {error}
+ </p>
+ )}
+
+ <section className="mt-9">
+ <SectionHeading label={t("Files")} count={files.length} />
+ {files.length ? (
+ <ul className="mt-2 divide-y divide-[var(--border)] border-y border-[var(--border)]">
+ {files.map((tab) => (
+ <FileRow
+ key={tab.material.material_id}
+ tab={tab}
+ opening={opening === tab.material.material_id}
+ onOpen={() => void openFile(tab)}
+ onRemove={() => void removeFile(tab)}
+ />
+ ))}
+ </ul>
+ ) : (
+ <button
+ type="button"
+ onClick={() => setDialog("add")}
+ className="mt-2 flex w-full flex-col items-center gap-1.5 rounded-xl border border-dashed border-[var(--border)] px-6 py-10 text-center transition hover:border-[var(--ring)]"
+ >
+ <Plus size={16} className="text-[var(--muted-foreground)]" />
+ <span className="text-[13px] font-medium">
+ {t("This folder is empty")}
+ </span>
+ <span className="text-[12px] text-[var(--muted-foreground)]">
+ {t("Add papers, chapters, web pages or videos to read them together.")}
+ </span>
+ </button>
+ )}
+ </section>
+
+ <section className="mt-9">
+ <SectionHeading label={t("Conversations")} count={sessions.length} />
+ {sessions.length ? (
+ <ul className="mt-2 divide-y divide-[var(--border)] border-y border-[var(--border)]">
+ {sessions.map((session) => (
+ <li key={session.session_id}>
+ <Link
+ href={readingSessionRoute(
+ folderId,
+ session.session_id,
+ contentWorkspace,
+ )}
+ className="group flex items-center gap-3 px-1 py-2.5 transition hover:bg-[var(--secondary)]"
+ >
+ <MessageSquare
+ size={14}
+ className="shrink-0 text-[var(--muted-foreground)]"
+ />
+ <span className="min-w-0 flex-1 truncate text-[13px]">
+ {session.title || t("New reading conversation")}
+ </span>
+ <span className="shrink-0 text-[11px] text-[var(--muted-foreground)]">
+ {relativeDate(session.updated_at, i18n.language)}
+ </span>
+ <ArrowRight
+ size={13}
+ className="shrink-0 text-[var(--muted-foreground)] opacity-0 transition group-hover:opacity-100"
+ />
+ </Link>
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <p className="mt-2 px-1 text-[12px] text-[var(--muted-foreground)]">
+ {t("Conversations you have while reading this folder appear here.")}
+ </p>
+ )}
+ </section>
+
+ {dialog === "add" && (
+ <AddMaterialsDialog
+ mode="add"
+ workspaceId={folderId}
+ onClose={() => setDialog(null)}
+ onDone={() => {
+ setDialog(null);
+ void refresh();
+ }}
+ />
+ )}
+ {dialog === "edit" && (
+ <FolderDialog
+ collection={collection}
+ workspaceId={contentWorkspace}
+ onClose={() => setDialog(null)}
+ onSaved={(saved) => {
+ setDialog(null);
+ setFolder(saved);
+ }}
+ />
+ )}
+ {dialog === "delete" && (
+ <DeleteCollectionDialog
+ collection={collection}
+ onClose={() => setDialog(null)}
+ onDeleted={async () => {
+ router.push(scopedUrl(READING_HOME));
+ }}
+ />
+ )}
+ </FolderFrame>
+ );
+}
+
+function FolderFrame({ children }: { children: React.ReactNode }) {
+ return (
+ <section className="h-full min-h-0 w-full overflow-y-auto bg-[var(--background)] text-[var(--foreground)]">
+ <div className="mx-auto w-full max-w-[920px] px-6 py-7 md:px-9 lg:py-9">
+ {children}
+ </div>
+ </section>
+ );
+}
+
+function SectionHeading({ label, count }: { label: string; count: number }) {
+ return (
+ <h2 className="flex items-center gap-1.5 px-1 text-[11.5px] font-medium text-[var(--muted-foreground)]">
+ {label}
+ <span className="tabular-nums opacity-70">{count}</span>
+ </h2>
+ );
+}
+
+function FileRow({
+ tab,
+ opening,
+ onOpen,
+ onRemove,
+}: {
+ tab: ReadingWorkspaceTab;
+ opening: boolean;
+ onOpen: () => void;
+ onRemove: () => void;
+}) {
+ const { t } = useTranslation();
+ const material = tab.material;
+ const pending =
+ material.status === "processing" || material.status === "queued";
+ const failed = material.status === "failed";
+ const detail = pending
+ ? t("Preparing")
+ : failed
+ ? t("Could not prepare this file")
+ : materialDetail(material);
+
+ return (
+ <li className="group flex items-center">
+ <button
+ type="button"
+ onClick={onOpen}
+ title={t("Open in reader")}
+ className="flex min-w-0 flex-1 items-center gap-3 px-1 py-2.5 text-left transition hover:bg-[var(--secondary)]"
+ >
+ <span className="flex size-8 shrink-0 items-center justify-center rounded-md bg-[var(--muted)] text-[var(--muted-foreground)]">
+ {opening || pending ? (
+ <Loader2 size={14} className="animate-spin" />
+ ) : (
+ <MaterialGlyph material={material} size={14} />
+ )}
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-[13px] font-medium">
+ {material.title || material.filename}
+ </span>
+ {detail && (
+ <span
+ className={`block truncate text-[11px] ${
+ failed
+ ? "text-[var(--destructive)]"
+ : "text-[var(--muted-foreground)]"
+ }`}
+ >
+ {detail}
+ </span>
+ )}
+ </span>
+ </button>
+ <button
+ type="button"
+ onClick={onRemove}
+ aria-label={t("Remove from collection")}
+ title={t("Remove from collection")}
+ className="mx-1 flex size-7 shrink-0 items-center justify-center rounded-md text-[var(--muted-foreground)] opacity-100 transition hover:bg-[var(--muted)] hover:text-[var(--foreground)] sm:opacity-0 sm:focus:opacity-100 sm:group-hover:opacity-100"
+ >
+ <X size={13} />
+ </button>
+ </li>
+ );
+}
diff --git a/web/components/reading/library/ReadingLibrary.tsx b/web/components/reading/library/ReadingLibrary.tsx
index ea67a3f15..54e6e3aae 100644
--- a/web/components/reading/library/ReadingLibrary.tsx
+++ b/web/components/reading/library/ReadingLibrary.tsx
@@ -2,8 +2,7 @@
import { learningLibrary, libraryItemKey } from "@/lib/learning-library";
import { activeWorkspaceId } from "@/lib/workspace-scope";
-import { useLearningCreation, requestedLearningCreation, useLibraryFilter, WorkspaceLabel } from "@/components/learning/LibraryWorkspace";
-import { LearningCardContent } from "@/components/learning/LearningCard";
+import { useCreateRequest, useLibraryFilter, workspaceName } from "@/components/learning/LibraryWorkspace";
import {
LearningEmptyState,
@@ -11,14 +10,17 @@ import {
LearningSkeleton,
} from "@/components/learning/LearningShell";
-import { readingCollectionRoute } from "@/lib/learning-routes";
+import { readingCollectionRoute, readingFolderRoute } from "@/lib/learning-routes";
import Link from "next/link";
import { useRouter } from "next/navigation";
import {
- ChevronRight,
+ BookOpen,
+ FolderOpen,
Loader2,
MoreHorizontal,
+ Palette,
+ Plus,
Search,
Trash2,
TriangleAlert,
@@ -40,12 +42,17 @@ import {
useCourseScope,
} from "@/components/courses/CourseScope";
-import { AddMaterialsDialog } from "./AddMaterialsDialog";
+import { FolderDialog } from "./FolderDialog";
+import { FolderGlyph } from "./FolderGlyph";
import { LibraryShell } from "./LibraryShell";
-import { MaterialGlyph } from "./shared";
+import { relativeDate } from "./shared";
type SortMode = "recent" | "name";
+type FolderDialogState =
+ | { mode: "create"; workspaceId: string }
+ | { mode: "edit"; collection: ReadingWorkspace };
+
export function ReadingLibraryPage() {
const { t, i18n } = useTranslation();
const router = useRouter();
@@ -55,9 +62,10 @@ export function ReadingLibraryPage() {
const [error, setError] = useState("");
const [search, setSearch] = useState("");
const [sort, setSort] = useState<SortMode>("recent");
- const [showAdd, setShowAdd] = useState(requestedLearningCreation);
- const creation = useLearningCreation(() => setShowAdd(true));
- const { rows: collections, control } = useLibraryFilter(allCollections);
+ const [folderDialog, setFolderDialog] = useState<FolderDialogState | null>(
+ null
+ );
+ const { rows: collections, picker, mixed } = useLibraryFilter(allCollections);
const [menuFor, setMenuFor] = useState<string | null>(null);
const [deleteTarget, setDeleteTarget] = useState<ReadingWorkspace | null>(
null
@@ -66,6 +74,16 @@ export function ReadingLibraryPage() {
// Present when opened from a course page or a Course Study hand-off.
const scope = useCourseScope();
+ // A new collection starts where the page is; the dialog can move it to
+ // another workspace, except inside a course, whose references must stay in
+ // the course's own store.
+ const create = useCallback(
+ (workspaceId = activeWorkspaceId()) =>
+ setFolderDialog({ mode: "create", workspaceId }),
+ []
+ );
+ useCreateRequest(create);
+
const refresh = useCallback(async () => {
setError("");
try {
@@ -125,17 +143,33 @@ export function ReadingLibraryPage() {
return sorted;
}, [collections, i18n.language, scope, sort]);
+ // A workspace holds collections, and each collection is stored in exactly
+ // one workspace: every shelf is headed by the workspace it lives in, so a
+ // folder is never mistaken for the workspace around it. Shelves keep the
+ // order their first folder has under the chosen sort.
+ const groups = useMemo(() => {
+ const byWorkspace = new Map<string, { key: string; name: string; rows: ReadingWorkspace[] }>();
+ for (const row of rows) {
+ const key = row.content_workspace_id ?? "";
+ const group = byWorkspace.get(key) ?? { key, name: workspaceName(row, t), rows: [] };
+ group.rows.push(row);
+ byWorkspace.set(key, group);
+ }
+ return [...byWorkspace.values()];
+ }, [rows, t]);
+
+ const menuKey = (collection: ReadingWorkspace) =>
+ libraryItemKey(collection, collection.workspace_id);
+
return (
<LibraryShell
view="collections"
collectionCount={rows.length}
materialCount={materials.length}
actionLabel={t("New collection")}
- onAction={creation.begin}
+ onAction={() => create()}
scopeChip={scope ? <CourseScopeChip scope={scope} /> : null}
>
- {creation.dialog}
- {control}
<div className="mt-5 flex flex-col gap-3 border-b border-[var(--border)] pb-3 sm:flex-row sm:items-center">
<label className="flex h-8 min-w-0 flex-1 items-center gap-2 rounded-lg border border-[var(--border)] px-2.5 sm:max-w-[330px]">
<Search
@@ -159,6 +193,7 @@ export function ReadingLibraryPage() {
)}
</label>
<div className="flex items-center gap-2 sm:ml-auto">
+ {picker}
<span className="text-[11px] text-[var(--muted-foreground)]">
{t("{{count}} collections", { count: rows.length })}
</span>
@@ -198,46 +233,83 @@ export function ReadingLibraryPage() {
error ? null : (
<EmptyCollections
searching={Boolean(search)}
- onCreate={creation.begin}
+ onCreate={() => create()}
/>
)
) : (
- <ul className="mt-1">
- {rows.map(collection => (
- <CollectionRow
- key={libraryItemKey(collection, collection.workspace_id)}
- collection={collection}
- menuOpen={menuFor === libraryItemKey(collection, collection.workspace_id)}
- onToggleMenu={() =>
- setMenuFor(current =>
- current === libraryItemKey(collection, collection.workspace_id)
- ? null
- : libraryItemKey(collection, collection.workspace_id)
- )
- }
- onDelete={() => {
- setMenuFor(null);
- setDeleteTarget(collection);
- }}
- />
- ))}
- </ul>
+ groups.map(group => (
+ <section
+ key={group.key}
+ aria-label={t("Workspace {{name}}", { name: group.name })}
+ className="mt-6"
+ >
+ <h2 className="flex items-center gap-1.5 px-1 text-[11.5px] font-medium text-[var(--muted-foreground)]">
+ <FolderOpen size={13} strokeWidth={1.7} className="shrink-0" />
+ <span className="truncate">{group.name}</span>
+ <span className="tabular-nums opacity-70">{group.rows.length}</span>
+ </h2>
+ <ul className="mt-2 grid grid-cols-[repeat(auto-fill,minmax(148px,1fr))] gap-1">
+ {group.rows.map(collection => (
+ <FolderTile
+ key={menuKey(collection)}
+ collection={collection}
+ menuOpen={menuFor === menuKey(collection)}
+ onToggleMenu={() =>
+ setMenuFor(current =>
+ current === menuKey(collection) ? null : menuKey(collection)
+ )
+ }
+ onCloseMenu={() => setMenuFor(null)}
+ onEdit={() => {
+ setMenuFor(null);
+ setFolderDialog({ mode: "edit", collection });
+ }}
+ onDelete={() => {
+ setMenuFor(null);
+ setDeleteTarget(collection);
+ }}
+ />
+ ))}
+ {/* Inside the course shelf, and when only one workspace is on
+ screen, the header button already says where it goes. */}
+ {mixed && !scope && (
+ <li>
+ <button
+ type="button"
+ onClick={() => create(group.key)}
+ className="flex h-full min-h-[128px] w-full flex-col items-center justify-center gap-2 rounded-xl text-[11.5px] text-[var(--muted-foreground)] transition hover:bg-[var(--secondary)] hover:text-[var(--foreground)]"
+ >
+ <span className="flex h-[50px] w-16 items-center justify-center rounded-lg border border-dashed border-[var(--border)]">
+ <Plus size={16} />
+ </span>
+ {t("New collection here")}
+ </button>
+ </li>
+ )}
+ </ul>
+ </section>
+ ))
)}
- {showAdd && (
- <AddMaterialsDialog
- mode="create"
- onClose={() => setShowAdd(false)}
- onDone={async ({ workspace }) => {
- setShowAdd(false);
- if (workspace) {
- await scope?.attach(
- "reading_workspace",
- workspace.workspace_id,
- workspace.title
- );
- router.push(readingCollectionRoute(workspace.workspace_id));
- } else void refresh();
+ {folderDialog && (
+ <FolderDialog
+ collection={folderDialog.mode === "edit" ? folderDialog.collection : undefined}
+ workspaceId={folderDialog.mode === "create" ? folderDialog.workspaceId : ""}
+ lockWorkspace={Boolean(scope)}
+ onClose={() => setFolderDialog(null)}
+ onSaved={async (collection, workspaceId) => {
+ const created = folderDialog.mode === "create";
+ setFolderDialog(null);
+ if (!created) {
+ void refresh();
+ return;
+ }
+ await scope?.attach(
+ "reading_workspace",
+ collection.workspace_id,
+ collection.title
+ );
+ router.push(readingFolderRoute(collection.workspace_id, workspaceId));
}}
/>
)}
@@ -280,76 +352,103 @@ function SortButton({
);
}
-function CollectionRow({
+function FolderTile({
collection,
menuOpen,
onToggleMenu,
+ onCloseMenu,
+ onEdit,
onDelete,
}: {
collection: ReadingWorkspace;
menuOpen: boolean;
onToggleMenu: () => void;
+ onCloseMenu: () => void;
+ onEdit: () => void;
onDelete: () => void;
}) {
- const { t } = useTranslation();
- const first = collection.tabs[0]?.material;
- const names = collection.tabs.slice(0, 2).map(tab => tab.material.title);
- const rest = collection.tabs.length - names.length;
+ const { t, i18n } = useTranslation();
+ const files = collection.tabs.length;
const preparing = collection.tabs.some(
tab =>
tab.material.status === "processing" || tab.material.status === "queued"
);
+ const contentWorkspace = collection.content_workspace_id ?? "";
return (
- <li className="group relative my-3 rounded-xl border border-[var(--border)]">
- <WorkspaceLabel row={collection} />
+ <li className="group relative">
<Link
- href={readingCollectionRoute(collection.workspace_id, collection.content_workspace_id ?? "")}
- className="flex items-center gap-3 rounded-xl py-4 pl-4 pr-10 transition hover:bg-[var(--secondary)]"
+ href={readingFolderRoute(collection.workspace_id, contentWorkspace)}
+ className="flex h-full flex-col items-center rounded-xl px-2.5 pb-3 pt-4 text-center transition hover:bg-[var(--secondary)] focus-visible:bg-[var(--secondary)] focus-visible:outline-none"
>
- <LearningCardContent
- title={collection.title}
- icon={
- preparing ? (
- <Loader2 size={14} className="animate-spin" />
- ) : first ? (
- <MaterialGlyph material={first} />
- ) : (
- <ChevronRight size={14} />
- )
- }
- subtitle={
- names.length
- ? [
- names.join(" · "),
- rest > 0 ? t("+{{count}} more", { count: rest }) : "",
- ]
- .filter(Boolean)
- .join(" · ")
- : t("No material yet")
- }
- updatedAt={collection.updated_at}
- />
+ <span className="relative">
+ <FolderGlyph color={collection.color} files={files} size={64} />
+ {preparing && (
+ <Loader2
+ size={13}
+ className="absolute bottom-1 right-1 animate-spin text-white"
+ aria-label={t("Preparing")}
+ />
+ )}
+ </span>
+ <span className="mt-2.5 line-clamp-2 max-w-full break-words text-[13px] font-medium leading-snug text-[var(--foreground)]">
+ {collection.title}
+ </span>
+ <span className="mt-0.5 max-w-full truncate text-[11px] text-[var(--muted-foreground)]">
+ {[
+ files
+ ? t("{{count}} files", { count: files })
+ : t("Empty"),
+ relativeDate(collection.updated_at, i18n.language),
+ ]
+ .filter(Boolean)
+ .join(" · ")}
+ </span>
</Link>
<button
type="button"
onClick={onToggleMenu}
aria-label={t("Collection menu")}
- className="absolute right-1 top-1/2 flex size-7 -translate-y-1/2 items-center justify-center rounded-md text-[var(--muted-foreground)] opacity-100 transition hover:bg-[var(--muted)] sm:opacity-0 sm:group-hover:opacity-100 sm:focus:opacity-100"
+ aria-expanded={menuOpen}
+ className="absolute right-1.5 top-1.5 flex size-7 items-center justify-center rounded-md text-[var(--muted-foreground)] opacity-100 transition hover:bg-[var(--muted)] sm:opacity-0 sm:focus:opacity-100 sm:group-hover:opacity-100 aria-expanded:opacity-100"
>
<MoreHorizontal size={14} />
</button>
{menuOpen && (
- <div className="absolute right-1 top-[calc(50%+14px)] z-10 w-40 rounded-lg border border-[var(--border)] bg-[var(--card)] p-1 text-[11.5px] shadow-md dark:bg-[var(--popover)]">
- <button
- type="button"
- onClick={onDelete}
- className="flex w-full items-center gap-2 rounded-md px-2.5 py-2 text-left text-[var(--destructive)] hover:bg-[var(--muted)]"
+ <>
+ <div className="fixed inset-0 z-10" onClick={onCloseMenu} />
+ <div
+ role="menu"
+ className="absolute right-1.5 top-9 z-20 w-44 rounded-lg border border-[var(--border)] bg-[var(--card)] p-1 text-[12px] shadow-md dark:bg-[var(--popover)]"
>
- <Trash2 size={12} />
- {t("Delete collection")}
- </button>
- </div>
+ <Link
+ role="menuitem"
+ href={readingCollectionRoute(collection.workspace_id, contentWorkspace)}
+ className="flex w-full items-center gap-2 rounded-md px-2.5 py-2 text-left hover:bg-[var(--muted)]"
+ >
+ <BookOpen size={12} />
+ {t("Start reading")}
+ </Link>
+ <button
+ type="button"
+ role="menuitem"
+ onClick={onEdit}
+ className="flex w-full items-center gap-2 rounded-md px-2.5 py-2 text-left hover:bg-[var(--muted)]"
+ >
+ <Palette size={12} />
+ {t("Rename or recolor")}
+ </button>
+ <button
+ type="button"
+ role="menuitem"
+ onClick={onDelete}
+ className="flex w-full items-center gap-2 rounded-md px-2.5 py-2 text-left text-[var(--destructive)] hover:bg-[var(--muted)]"
+ >
+ <Trash2 size={12} />
+ {t("Delete collection")}
+ </button>
+ </div>
+ </>
)}
</li>
);
@@ -454,7 +553,7 @@ function EmptyCollections({
);
}
-function DeleteCollectionDialog({
+export function DeleteCollectionDialog({
collection,
onClose,
onDeleted,
diff --git a/web/components/reading/reading-actions-context.ts b/web/components/reading/reading-actions-context.ts
new file mode 100644
index 000000000..fd3f07abb
--- /dev/null
+++ b/web/components/reading/reading-actions-context.ts
@@ -0,0 +1,80 @@
+"use client";
+
+import { createContext, useContext } from "react";
+import type { ReadingAgeMode } from "@/lib/reading-age-presentation";
+import type {
+ ReadingExtensionManifest,
+ ReadingExtensionResult,
+} from "@/lib/reading-api";
+
+/** One runnable extension action, with its label already resolved. */
+export interface ReadingActionEntry {
+ key: string;
+ extension: ReadingExtensionManifest;
+ action: ReadingExtensionManifest["actions"][number];
+ label: string;
+ /** Needs a text selection to mean anything (translate, explain, guide). */
+ needsSelection: boolean;
+}
+
+/**
+ * One run of an action, as the companion column shows it.
+ *
+ * A card exists from the moment the action starts, so the learner sees where
+ * the answer is going to land before it arrives — the old toolbar spun a chip
+ * and then dropped a result between the toolbar and the page, a place nothing
+ * else on screen ever used.
+ */
+export interface ReadingActionCard {
+ id: string;
+ key: string;
+ label: string;
+ quote: string;
+ locator: number;
+ materialId: string;
+ status: "running" | "done" | "error";
+ result?: ReadingExtensionResult;
+ error?: string;
+}
+
+export interface ReadingActionsValue {
+ ageMode: ReadingAgeMode;
+ actions: ReadingActionEntry[];
+ cards: ReadingActionCard[];
+ speaking: boolean;
+ /** Key of the action currently running, or "". */
+ busyKey: string;
+ run: (
+ entry: ReadingActionEntry,
+ target?: { locator?: number; selection?: string },
+ ) => Promise<void>;
+ stopSpeaking: () => void;
+ dismiss: (cardId: string) => void;
+}
+
+export const ReadingActionsContext = createContext<ReadingActionsValue | null>(
+ null,
+);
+
+/**
+ * The workspace's shared reading actions, or `null` outside a workspace.
+ *
+ * `null` is a real state: the reader pane is also rendered on its own (tests,
+ * and any host without a companion column), and there it keeps its own
+ * toolbar with inline results.
+ */
+export function useReadingActions(): ReadingActionsValue | null {
+ return useContext(ReadingActionsContext);
+}
+
+/**
+ * Put the caret in the companion's composer, leaving its draft alone.
+ *
+ * The composer's own prefill hook *sets* the text, so using it with "" to
+ * "just focus" wiped whatever the learner had half-typed.
+ */
+export function focusReadingComposer() {
+ document
+ .querySelector<HTMLTextAreaElement>("[data-reading-composer] textarea")
+ ?.focus();
+}
diff --git a/web/components/reading/workspace-menu-context.ts b/web/components/reading/workspace-menu-context.ts
new file mode 100644
index 000000000..4f4f0acd3
--- /dev/null
+++ b/web/components/reading/workspace-menu-context.ts
@@ -0,0 +1,60 @@
+"use client";
+
+import type { LucideIcon } from "lucide-react";
+import { createContext, useContext, useEffect } from "react";
+
+/**
+ * One entry in the workspace's single ⋯ menu.
+ *
+ * The reader, the companion and the collection each had a ⋯ of their own —
+ * three identical icons a hand's width apart, and a learner looking for
+ * "export" had to open all three. The panels still own their actions; they
+ * hand them up here, and the top bar lists them in one place.
+ */
+export interface WorkspaceMenuItem {
+ key: string;
+ icon: LucideIcon;
+ label: string;
+ hint?: string;
+ /** A setting that is on (shown with a check), not an action. */
+ active?: boolean;
+ disabled?: boolean;
+ spinning?: boolean;
+ onSelect: () => void;
+}
+
+export type WorkspaceMenuSection = "material" | "conversation";
+
+export interface WorkspaceMenuHost {
+ register: (
+ section: WorkspaceMenuSection,
+ items: WorkspaceMenuItem[] | null,
+ ) => void;
+}
+
+export const WorkspaceMenuContext = createContext<WorkspaceMenuHost | null>(
+ null,
+);
+
+/**
+ * Publish a panel's menu items to the workspace's ⋯ menu.
+ *
+ * Returns whether a workspace is listening: a panel rendered on its own keeps
+ * its own ⋯, since nothing else would show these actions. `items` must be
+ * memoised, or every render re-registers and re-renders the workspace.
+ */
+export function useWorkspaceMenuSection(
+ section: WorkspaceMenuSection,
+ items: WorkspaceMenuItem[] | null,
+): boolean {
+ const host = useContext(WorkspaceMenuContext);
+ useEffect(() => {
+ if (!host) return;
+ host.register(section, items);
+ }, [host, items, section]);
+ useEffect(() => {
+ if (!host) return;
+ return () => host.register(section, null);
+ }, [host, section]);
+ return host !== null;
+}
diff --git a/web/components/reading/workspace/ReadAloudButton.tsx b/web/components/reading/workspace/ReadAloudButton.tsx
new file mode 100644
index 000000000..3e797f008
--- /dev/null
+++ b/web/components/reading/workspace/ReadAloudButton.tsx
@@ -0,0 +1,53 @@
+"use client";
+
+import { Loader2, Square, Volume2 } from "lucide-react";
+import { useTranslation } from "react-i18next";
+
+import { useReadingActions } from "@/components/reading/reading-actions-context";
+
+const READ_ALOUD_KEY = "read_aloud:read";
+
+/**
+ * Read-aloud as one header toggle: speaker to start, square to stop.
+ *
+ * It used to be a chip in the action strip that, once pressed, grew a second
+ * "Reading aloud ■" band above the page — two rows of chrome for one on/off
+ * state. Younger learners keep the big button in their own toolbar, so this
+ * one steps aside for them rather than offering the same thing twice.
+ */
+export function ReadAloudButton({ disabled }: { disabled?: boolean }) {
+ const { t } = useTranslation();
+ const shared = useReadingActions();
+ const entry = shared?.actions.find((row) => row.key === READ_ALOUD_KEY);
+ if (!shared || !entry || shared.ageMode !== "default") return null;
+
+ const busy = shared.busyKey === READ_ALOUD_KEY;
+ const label = shared.speaking
+ ? t("Stop reading aloud")
+ : t("Read this page aloud");
+ return (
+ <button
+ type="button"
+ disabled={disabled || busy}
+ onClick={() =>
+ shared.speaking ? shared.stopSpeaking() : void shared.run(entry)
+ }
+ aria-label={label}
+ aria-pressed={shared.speaking}
+ title={label}
+ className={`flex size-7 shrink-0 items-center justify-center rounded-md transition hover:bg-[var(--muted)] disabled:cursor-not-allowed disabled:opacity-40 ${
+ shared.speaking
+ ? "text-[var(--primary)]"
+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
+ }`}
+ >
+ {busy ? (
+ <Loader2 size={14} className="animate-spin" />
+ ) : shared.speaking ? (
+ <Square size={11} fill="currentColor" />
+ ) : (
+ <Volume2 size={14} />
+ )}
+ </button>
+ );
+}
diff --git a/web/components/reading/workspace/ReadingActionCards.tsx b/web/components/reading/workspace/ReadingActionCards.tsx
new file mode 100644
index 000000000..b2cfd493e
--- /dev/null
+++ b/web/components/reading/workspace/ReadingActionCards.tsx
@@ -0,0 +1,184 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import {
+ CircleAlert,
+ Loader2,
+ MessageSquareQuote,
+ RotateCcw,
+ Sparkles,
+ X,
+} from "lucide-react";
+import { useTranslation } from "react-i18next";
+
+import { ExtensionResult } from "@/components/reading/ReadingExtensionBar";
+import {
+ useReadingActions,
+ type ReadingActionCard,
+} from "@/components/reading/reading-actions-context";
+
+/**
+ * Where a reading action's answer lands: under the conversation, in the same
+ * column the learner already reads answers in.
+ *
+ * A card is not a chat message — nothing here is sent to the model or kept
+ * with the conversation — so it looks like a note pinned under the thread,
+ * with the passage it answers quoted at the top and a way to carry the
+ * question into the conversation proper.
+ */
+export function ReadingActionCards({
+ sessionId,
+ onFollowUp,
+}: {
+ sessionId?: string | null;
+ /** Take the card's passage into the composer as the next question's context. */
+ onFollowUp: (card: ReadingActionCard) => void;
+}) {
+ const shared = useReadingActions();
+ if (!shared || shared.cards.length === 0) return null;
+ return (
+ <div className="mt-4 space-y-3 first:mt-0">
+ {shared.cards.map((card) => (
+ <ActionCard
+ key={card.id}
+ card={card}
+ sessionId={sessionId}
+ onDismiss={() => shared.dismiss(card.id)}
+ onRetry={() => {
+ const entry = shared.actions.find((row) => row.key === card.key);
+ if (!entry) return;
+ shared.dismiss(card.id);
+ void shared.run(entry, {
+ locator: card.locator,
+ selection: card.quote,
+ });
+ }}
+ onFollowUp={() => onFollowUp(card)}
+ />
+ ))}
+ </div>
+ );
+}
+
+function ActionCard({
+ card,
+ sessionId,
+ onDismiss,
+ onRetry,
+ onFollowUp,
+}: {
+ card: ReadingActionCard;
+ sessionId?: string | null;
+ onDismiss: () => void;
+ onRetry: () => void;
+ onFollowUp: () => void;
+}) {
+ const { t } = useTranslation();
+ const ref = useRef<HTMLElement | null>(null);
+ // Quiz answers are saved from inside the card; a failed save belongs to the
+ // card it happened in, not to a banner somewhere else on the page.
+ const [innerError, setInnerError] = useState("");
+
+ // Brought into view when it appears and again when its answer arrives: the
+ // learner pressed a button in the document, and the result is in another
+ // column that may be scrolled far up a long conversation.
+ useEffect(() => {
+ ref.current?.scrollIntoView({ block: "nearest", behavior: "smooth" });
+ }, [card.status]);
+
+ const title = card.result?.title || card.label;
+ return (
+ <article
+ ref={ref}
+ data-reading-action-card={card.status}
+ className="overflow-hidden rounded-xl border border-[var(--border)] bg-[var(--background)]"
+ >
+ <header className="flex items-center gap-2 px-3 pb-1 pt-2.5">
+ <Sparkles size={12} className="shrink-0 text-[var(--primary)]" />
+ <h3 className="min-w-0 flex-1 truncate text-[12px] font-semibold text-[var(--foreground)]">
+ {title}
+ </h3>
+ <button
+ type="button"
+ onClick={onDismiss}
+ aria-label={t("Dismiss")}
+ title={t("Dismiss")}
+ className="inline-flex size-6 shrink-0 items-center justify-center rounded-md text-[var(--muted-foreground)] transition hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
+ >
+ <X size={12} />
+ </button>
+ </header>
+ {card.quote ? (
+ <blockquote className="mx-3 mt-1 line-clamp-3 border-l-2 border-[var(--primary)] pl-2.5 text-[11.5px] leading-relaxed text-[var(--muted-foreground)]">
+ {card.quote}
+ </blockquote>
+ ) : null}
+ <div className="px-3 pb-3 pt-2.5">
+ {card.status === "running" ? (
+ <div role="status" className="space-y-2">
+ <p className="flex items-center gap-1.5 text-[11.5px] text-[var(--muted-foreground)]">
+ <Loader2 size={12} className="animate-spin" />
+ {t("Working on it…")}
+ </p>
+ <div className="h-2 w-11/12 animate-pulse rounded bg-[var(--muted)]" />
+ <div className="h-2 w-8/12 animate-pulse rounded bg-[var(--muted)]" />
+ </div>
+ ) : card.status === "error" ? (
+ <div className="flex items-start gap-2 text-[12px] text-[var(--destructive)]">
+ <CircleAlert size={13} className="mt-0.5 shrink-0" />
+ <p className="min-w-0 flex-1 break-words">{card.error}</p>
+ </div>
+ ) : card.result ? (
+ <ExtensionResult
+ variant="card"
+ result={card.result}
+ materialId={card.materialId}
+ locator={card.locator}
+ sessionId={sessionId}
+ closeLabel={t("Dismiss")}
+ onClose={onDismiss}
+ onError={setInnerError}
+ />
+ ) : null}
+ {innerError ? (
+ <p className="mt-2 text-[11.5px] text-[var(--destructive)]">
+ {innerError}
+ </p>
+ ) : null}
+ </div>
+ {card.status !== "running" ? (
+ <footer className="flex items-center gap-1 border-t border-[var(--border)] px-2 py-1.5">
+ {card.status === "error" ? (
+ <CardButton icon={RotateCcw} label={t("Try again")} onClick={onRetry} />
+ ) : null}
+ <CardButton
+ icon={MessageSquareQuote}
+ label={t("Ask a follow-up")}
+ onClick={onFollowUp}
+ />
+ </footer>
+ ) : null}
+ </article>
+ );
+}
+
+function CardButton({
+ icon: Icon,
+ label,
+ onClick,
+}: {
+ icon: typeof X;
+ label: string;
+ onClick: () => void;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ className="inline-flex h-7 items-center gap-1.5 rounded-md px-2 text-[11.5px] font-medium text-[var(--muted-foreground)] transition hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
+ >
+ <Icon size={12} />
+ {label}
+ </button>
+ );
+}
diff --git a/web/components/reading/workspace/ReadingCompanion.tsx b/web/components/reading/workspace/ReadingCompanion.tsx
index 895ed90b6..ebac03599 100644
--- a/web/components/reading/workspace/ReadingCompanion.tsx
+++ b/web/components/reading/workspace/ReadingCompanion.tsx
@@ -23,15 +23,15 @@
import dynamic from "next/dynamic";
import {
BookmarkPlus,
- ChevronDown,
ChevronLeft,
Download,
Highlighter,
- History,
Link2,
ListOrdered,
MoreHorizontal,
PanelRight,
+ Sparkles,
+ SquarePen,
X,
} from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -63,9 +63,20 @@ import {
type ReadingConversation,
type ReadingLibraryMaterial,
} from "@/lib/reading-workspace-api";
-import { ConversationMenu } from "./dialogs";
+import { READER_ASK_EVENT } from "@/components/reading/ReaderPane";
+import {
+ focusReadingComposer,
+ useReadingActions,
+ type ReadingActionCard,
+ type ReadingActionEntry,
+} from "@/components/reading/reading-actions-context";
+import { ReadingActionCards } from "./ReadingActionCards";
import { ReadingComposer } from "./ReadingComposer";
import { CompanionWelcome, MenuItem } from "./WorkspaceChrome";
+import {
+ useWorkspaceMenuSection,
+ type WorkspaceMenuItem,
+} from "@/components/reading/workspace-menu-context";
const SaveToNotebookModal = dynamic(
() => import("@/components/notebook/SaveToNotebookModal"),
@@ -75,20 +86,29 @@ const SaveToNotebookModal = dynamic(
/** Which face the header's overflow menu is showing. */
type MenuView = "actions" | "turns";
+/** Spoken from the workspace header, not listed as a tool. */
+const READ_ALOUD_KEY = "read_aloud:read";
+
+// The TW3 `bg-[var(--x)]/NN` form compiles to nothing, which is why these
+// header buttons never showed a pressed state; color-mix is what works.
+const HEADER_BUTTON_ACTIVE =
+ "bg-[color-mix(in_srgb,var(--primary)_10%,transparent)] text-[var(--primary)]";
+const HEADER_BUTTON_IDLE =
+ "text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)]";
+
+const COMPOSER_FADE =
+ "linear-gradient(to bottom, #000 calc(100% - 32px), transparent)";
+
export function ReadingCompanion({
workspaceId,
material,
- conversations,
activeConversation,
linkedSessionIds,
activeLocator,
selection,
onClearSelection,
onOpenLinker,
- onSelectConversation,
onNewConversation,
- onRenameConversation,
- onDeleteConversation,
onQuickPrompt,
prefillInputRef,
onClose,
@@ -96,7 +116,6 @@ export function ReadingCompanion({
workspaceId: string;
/** The material currently open in the reader, if any. */
material: ReadingLibraryMaterial | null;
- conversations: ReadingConversation[];
activeConversation: ReadingConversation | null;
/** Conversations pinned as extra context for every turn. */
linkedSessionIds: string[];
@@ -105,10 +124,11 @@ export function ReadingCompanion({
selection: { quote: string; locator: number } | null;
onClearSelection: () => void;
onOpenLinker: () => void;
- onSelectConversation: (sessionId: string) => void | Promise<void>;
+ /**
+ * Past conversations live in the app sidebar with every other one; the
+ * companion only starts a fresh thread.
+ */
onNewConversation: () => void;
- onRenameConversation: (conversation: ReadingConversation) => void;
- onDeleteConversation: (conversation: ReadingConversation) => void;
/** Send a guided one-click prompt without touching the composer's text. */
onQuickPrompt: (prompt: string) => void;
prefillInputRef: React.MutableRefObject<((text: string) => void) | null>;
@@ -127,7 +147,8 @@ export function ReadingCompanion({
} = useChatStateAdapter();
const confirmResearchOutline = useResearchOutlineContinuation();
- const [showSessions, setShowSessions] = useState(false);
+ const readingActions = useReadingActions();
+ const [toolsOpen, setToolsOpen] = useState(false);
const [menuOpen, setMenuOpen] = useState(false);
const [menuView, setMenuView] = useState<MenuView>("actions");
const [showSaveModal, setShowSaveModal] = useState(false);
@@ -150,6 +171,20 @@ export function ReadingCompanion({
setMenuView("actions");
}, []);
+ // The header menus close on a click-away catcher; Escape has to be wired
+ // separately, or a keyboard user who opened one has no way back out.
+ useEffect(() => {
+ if (!toolsOpen && !menuOpen) return;
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.key !== "Escape") return;
+ event.preventDefault();
+ setToolsOpen(false);
+ closeMenu();
+ };
+ document.addEventListener("keydown", onKeyDown);
+ return () => document.removeEventListener("keydown", onKeyDown);
+ }, [closeMenu, menuOpen, toolsOpen]);
+
const handleWelcomeAction = useCallback(
(prompt: string) => {
if (workspaceActionNeedsConfiguration(state.activeCapability)) {
@@ -161,6 +196,63 @@ export function ReadingCompanion({
[onQuickPrompt, prefillInputRef, state.activeCapability],
);
+ /* ── Reading tools ───────────────────────────────────────────────────
+ The same actions the selection popover offers, for when the learner
+ starts from here: page-wide ones (a quiz on this page) always, and the
+ passage ones against the passage already quoted above the composer. */
+ const toolEntries = useMemo(
+ () =>
+ (readingActions?.actions ?? []).filter(
+ (entry) => entry.key !== READ_ALOUD_KEY,
+ ),
+ [readingActions?.actions],
+ );
+ const runTool = useCallback(
+ (entry: ReadingActionEntry) => {
+ if (!readingActions) return;
+ if (entry.needsSelection) {
+ if (!selection) return;
+ void readingActions.run(entry, {
+ locator: selection.locator,
+ selection: selection.quote,
+ });
+ return;
+ }
+ void readingActions.run(entry, { locator: activeLocator });
+ },
+ [activeLocator, readingActions, selection],
+ );
+ const pageTools = useMemo(
+ () =>
+ toolEntries
+ .filter((entry) => !entry.needsSelection)
+ .map((entry) => ({
+ key: entry.key,
+ label: entry.label,
+ onClick: () => runTool(entry),
+ })),
+ [runTool, toolEntries],
+ );
+
+ // "Ask a follow-up" on a card: the passage it answered becomes the quoted
+ // context of the next question, exactly as "Ask about this" does from the
+ // document. A card with no passage (a quiz on the page) just focuses the box.
+ const followUpCard = useCallback(
+ (card: ReadingActionCard) => {
+ if (card.quote) {
+ window.dispatchEvent(
+ new CustomEvent(READER_ASK_EVENT, {
+ detail: { quote: card.quote, locator: card.locator },
+ }),
+ );
+ return;
+ }
+ focusReadingComposer();
+ },
+ [],
+ );
+ const hasCards = Boolean(readingActions?.cards.length);
+
/* ── Transcript scrolling ────────────────────────────────────────────
The pin-to-bottom hook /chat uses. The companion used to be a bare
`overflow-y-auto`, so a streaming reply grew below the fold while the
@@ -297,6 +389,57 @@ export function ReadingCompanion({
[state.messages],
);
+ const downloadMarkdown = useCallback(() => {
+ if (!state.messages.length) return;
+ downloadChatMarkdown(state.messages, {
+ title:
+ activeConversation?.title ||
+ material?.title ||
+ t("Reading conversation"),
+ });
+ }, [activeConversation?.title, material?.title, state.messages, t]);
+
+ // Handed to the workspace's single ⋯. Only the question list stays here: it
+ // is a long, scrolling list, and it belongs over the conversation it jumps
+ // through rather than under the top bar's corner.
+ const menuItems = useMemo<WorkspaceMenuItem[]>(() => {
+ const items: WorkspaceMenuItem[] = [
+ {
+ key: "save",
+ icon: BookmarkPlus,
+ label: t("Save to Notebook"),
+ disabled: !chatSavePayload,
+ onSelect: () => setShowSaveModal(true),
+ },
+ {
+ key: "markdown",
+ icon: Download,
+ label: t("Download Markdown"),
+ disabled: !hasMessages,
+ onSelect: downloadMarkdown,
+ },
+ {
+ key: "activity",
+ icon: PanelRight,
+ label: t("Activity"),
+ onSelect: () => setViewerOpen(true),
+ },
+ ];
+ if (chatOutline.length > 1) {
+ items.push({
+ key: "turns",
+ icon: ListOrdered,
+ label: t("Jump to a question"),
+ onSelect: () => {
+ setMenuView("turns");
+ setMenuOpen(true);
+ },
+ });
+ }
+ return items;
+ }, [chatOutline.length, chatSavePayload, downloadMarkdown, hasMessages, t]);
+ const menuHosted = useWorkspaceMenuSection("conversation", menuItems);
+
const copyAssistantMessage = useCallback(
(content: string) => copyText(content),
[],
@@ -305,17 +448,28 @@ export function ReadingCompanion({
return (
<aside className="absolute inset-y-0 right-0 z-30 flex w-[min(420px,100%)] min-h-0 min-w-0 flex-col bg-[var(--card)] shadow-[-18px_0_42px_rgba(0,0,0,.12)] dark:bg-[var(--background)] xl:static xl:w-auto xl:shadow-none">
<div className="relative flex h-11 shrink-0 items-center gap-2.5 border-b border-[var(--border)] px-4 dark:border-[var(--border)]">
- <div className="min-w-0 flex-1">
- <p className="font-serif text-[13px] font-semibold leading-tight text-[var(--foreground)]">
- {t("Reading companion")}
- </p>
- {/* A material's own title, not a label: upper-casing it would
- rewrite a book name and destroy a CJK one. */}
- <p className="truncate text-[10.5px] text-[var(--muted-foreground)]">
- {material?.title || t("Grounded in your materials")}
- </p>
- </div>
+ {/* No material subtitle: the document's name is already in the tab
+ and the reader's own header, and a third copy only pushed the
+ panel's controls into a truncated corner. */}
+ <p className="min-w-0 flex-1 truncate font-serif text-[13.5px] font-semibold leading-tight text-[var(--foreground)]">
+ {t("Reading companion")}
+ </p>
<div className="flex shrink-0 items-center gap-0.5">
+ {toolEntries.length > 0 && (
+ <Tooltip label={t("Reading tools")} suppressed={toolsOpen}>
+ <button
+ type="button"
+ onClick={() => setToolsOpen((current) => !current)}
+ aria-label={t("Reading tools")}
+ aria-expanded={toolsOpen}
+ className={`inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg transition-[background-color,color,transform] duration-150 active:scale-90 ${
+ toolsOpen ? HEADER_BUTTON_ACTIVE : HEADER_BUTTON_IDLE
+ }`}
+ >
+ <Sparkles size={14} strokeWidth={1.7} />
+ </button>
+ </Tooltip>
+ )}
<Tooltip
label={
activeConversation
@@ -332,8 +486,8 @@ export function ReadingCompanion({
aria-label={t("Link earlier reading conversations")}
className={`relative inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg transition-[background-color,color,transform] duration-150 active:scale-90 disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:bg-transparent ${
linkedSessionIds.length
- ? "bg-[var(--primary)]/10 text-[var(--primary)]"
- : "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/55 hover:text-[var(--foreground)]"
+ ? HEADER_BUTTON_ACTIVE
+ : HEADER_BUTTON_IDLE
}`}
>
<Link2 size={14} strokeWidth={1.7} />
@@ -344,57 +498,82 @@ export function ReadingCompanion({
)}
</button>
</Tooltip>
- <Tooltip label={t("Reading conversations")} suppressed={showSessions}>
- <button
- type="button"
- onClick={() => setShowSessions((current) => !current)}
- aria-label={t("Reading conversations")}
- aria-expanded={showSessions}
- className={`inline-flex h-8 items-center gap-1 rounded-lg px-2 text-[10px] font-medium transition-[background-color,color,transform] duration-150 active:scale-95 ${
- showSessions
- ? "bg-[var(--primary)]/10 text-[var(--primary)]"
- : "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/55 hover:text-[var(--foreground)]"
- }`}
- >
- <History size={13} strokeWidth={1.7} />
- <ChevronDown
- size={10}
- className={`transition-transform duration-150 ${showSessions ? "rotate-180" : ""}`}
- />
- </button>
- </Tooltip>
- <Tooltip label={t("Conversation actions")} suppressed={menuOpen}>
+ <Tooltip label={t("New conversation")}>
<button
type="button"
- onClick={() => (menuOpen ? closeMenu() : setMenuOpen(true))}
- aria-label={t("Conversation actions")}
- aria-expanded={menuOpen}
- className={`inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg transition-[background-color,color,transform] duration-150 active:scale-90 ${
- menuOpen
- ? "bg-[var(--primary)]/10 text-[var(--primary)]"
- : "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/55 hover:text-[var(--foreground)]"
- }`}
+ onClick={onNewConversation}
+ disabled={!activeConversation}
+ aria-label={t("New conversation")}
+ className={`inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg transition-[background-color,color,transform] duration-150 active:scale-90 disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:bg-transparent ${HEADER_BUTTON_IDLE}`}
>
- <MoreHorizontal size={14} strokeWidth={1.7} />
+ <SquarePen size={14} strokeWidth={1.7} />
</button>
</Tooltip>
+ {!menuHosted && (
+ <Tooltip label={t("Conversation actions")} suppressed={menuOpen}>
+ <button
+ type="button"
+ onClick={() => (menuOpen ? closeMenu() : setMenuOpen(true))}
+ aria-label={t("Conversation actions")}
+ aria-expanded={menuOpen}
+ className={`inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg transition-[background-color,color,transform] duration-150 active:scale-90 ${
+ menuOpen ? HEADER_BUTTON_ACTIVE : HEADER_BUTTON_IDLE
+ }`}
+ >
+ <MoreHorizontal size={14} strokeWidth={1.7} />
+ </button>
+ </Tooltip>
+ )}
</div>
<button
type="button"
onClick={onClose}
- className="inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg text-[var(--muted-foreground)] transition-[background-color,color,transform] duration-150 hover:bg-[var(--muted)]/55 hover:text-[var(--foreground)] active:scale-90 xl:hidden"
+ className="inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg text-[var(--muted-foreground)] transition-[background-color,color,transform] duration-150 hover:bg-[var(--muted)] hover:text-[var(--foreground)] active:scale-90 xl:hidden"
aria-label={t("Close reading companion")}
>
<X size={14} strokeWidth={1.7} />
</button>
+ {toolsOpen && (
+ <>
+ <div
+ className="fixed inset-0 z-40"
+ onClick={() => setToolsOpen(false)}
+ />
+ <div className="absolute right-2 top-10 z-50 w-64 rounded-2xl border border-[var(--border)] bg-[var(--card)] p-1.5 text-[12px] shadow-[0_20px_50px_rgba(0,0,0,.18)] dark:border-[var(--border)] dark:bg-[var(--popover)]">
+ {toolEntries.map((entry) => {
+ const blocked = entry.needsSelection && !selection;
+ return (
+ <MenuItem
+ key={entry.key}
+ icon={Sparkles}
+ label={entry.label}
+ disabled={blocked || readingActions?.busyKey === entry.key}
+ hint={
+ entry.needsSelection
+ ? blocked
+ ? t("Select text in the document first.")
+ : t("On the quoted passage")
+ : t("On the page in view")
+ }
+ onClick={() => {
+ setToolsOpen(false);
+ runTool(entry);
+ }}
+ />
+ );
+ })}
+ </div>
+ </>
+ )}
+
{menuOpen && (
<>
{/* Click-away is a full-viewport catcher rather than a blur
handler: the items are buttons, and blur fires before their
click lands. */}
<div className="fixed inset-0 z-40" onClick={closeMenu} />
- <div className="absolute right-2 top-10 z-50 w-60 rounded-2xl border border-[var(--border)] bg-[var(--card)] p-1.5 text-[11px] shadow-[0_20px_50px_rgba(0,0,0,.18)] dark:border-[var(--border)] dark:bg-[var(--popover)]">
+ <div className="absolute right-2 top-10 z-50 w-60 rounded-2xl border border-[var(--border)] bg-[var(--card)] p-1.5 text-[12px] shadow-[0_20px_50px_rgba(0,0,0,.18)] dark:border-[var(--border)] dark:bg-[var(--popover)]">
{menuView === "actions" ? (
<>
<MenuItem
@@ -410,13 +589,7 @@ export function ReadingCompanion({
label={t("Download Markdown")}
onClick={() => {
closeMenu();
- if (!state.messages.length) return;
- downloadChatMarkdown(state.messages, {
- title:
- activeConversation?.title ||
- material?.title ||
- t("Reading conversation"),
- });
+ downloadMarkdown();
}}
/>
<MenuItem
@@ -470,29 +643,6 @@ export function ReadingCompanion({
</div>
</>
)}
-
- {showSessions && (
- <ConversationMenu
- conversations={conversations}
- activeSessionId={state.sessionId}
- onSelect={async (sessionId) => {
- setShowSessions(false);
- await onSelectConversation(sessionId);
- }}
- onNew={() => {
- setShowSessions(false);
- onNewConversation();
- }}
- onRename={(row) => {
- setShowSessions(false);
- onRenameConversation(row);
- }}
- onDelete={(row) => {
- setShowSessions(false);
- onDeleteConversation(row);
- }}
- />
- )}
</div>
<div
@@ -525,7 +675,14 @@ export function ReadingCompanion({
handleMessagesScroll();
}
}}
- className="min-h-0 flex-1 overflow-y-auto px-4 py-4 [scrollbar-gutter:stable]"
+ // No rule above the composer: the last lines fade out instead, so the
+ // composer floats over the conversation as it does on /chat. The
+ // bottom padding keeps that fade over empty space, not the last line.
+ className="min-h-0 flex-1 overflow-y-auto px-4 pb-10 pt-4 [scrollbar-gutter:stable]"
+ style={{
+ WebkitMaskImage: COMPOSER_FADE,
+ maskImage: COMPOSER_FADE,
+ }}
>
{state.messages.length ? (
<ChatMessageList
@@ -554,19 +711,25 @@ export function ReadingCompanion({
}}
showModeBadge={false}
/>
- ) : (
+ ) : hasCards ? null : (
<CompanionWelcome
title={material?.title ?? ""}
onAction={handleWelcomeAction}
suggestions={openers}
+ tools={material ? pageTools : []}
/>
)}
+ <ReadingActionCards
+ sessionId={state.sessionId}
+ onFollowUp={followUpCard}
+ />
<div ref={messagesEndRef} className="h-px" />
</div>
<div
ref={composerBoxRef}
- className="shrink-0 border-t border-[var(--border)] bg-[var(--card)] pt-3 dark:border-[var(--border)] dark:bg-[var(--secondary)]"
+ data-reading-composer=""
+ className="shrink-0 pt-1"
>
{selection && (
<div className="mx-4 mb-2 flex items-start gap-2 rounded-xl border border-[var(--border)] bg-[var(--card)] px-2.5 py-2 dark:border-[var(--border)] dark:bg-[var(--card)]">
@@ -574,23 +737,26 @@ export function ReadingCompanion({
size={12}
className="mt-0.5 shrink-0 text-[var(--primary)]"
/>
- <p className="line-clamp-2 min-w-0 flex-1 text-[10.5px] leading-relaxed text-[var(--muted-foreground)]">
+ <p className="line-clamp-2 min-w-0 flex-1 text-[11.5px] leading-relaxed text-[var(--muted-foreground)]">
{selection.quote}
</p>
<button
type="button"
+ aria-label={t("Remove quoted passage")}
+ title={t("Remove quoted passage")}
+ className="shrink-0 rounded p-0.5 text-[var(--muted-foreground)] transition hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
onClick={() => {
onClearSelection();
setReadingViewport({ selection: "" });
}}
>
- <X size={10} />
+ <X size={11} />
</button>
</div>
)}
{!!linkedSessionIds.length && (
- <div className="mx-4 mb-2 flex items-center gap-1.5 text-[10px] text-[var(--muted-foreground)]">
- <Link2 size={10} />
+ <div className="mx-4 mb-2 flex items-center gap-1.5 text-[11px] text-[var(--muted-foreground)]">
+ <Link2 size={11} />
{t("Using {{count}} linked conversations as context", {
count: linkedSessionIds.length,
})}
diff --git a/web/components/reading/workspace/ReadingWorkspace.tsx b/web/components/reading/workspace/ReadingWorkspace.tsx
index 2a42a0876..8914ab0ec 100644
--- a/web/components/reading/workspace/ReadingWorkspace.tsx
+++ b/web/components/reading/workspace/ReadingWorkspace.tsx
@@ -1,7 +1,7 @@
"use client";
import { scopedUrl } from "@/lib/workspace-scope";
-import { READING_HOME, readingSessionIdFromPath } from "@/lib/learning-routes";
+import { READING_HOME, readingFolderRoute, readingSessionIdFromPath } from "@/lib/learning-routes";
import { browserStorage } from "@/shared/storage";
@@ -15,16 +15,11 @@ import {
} from "next/navigation";
import {
ArrowLeft,
- ChevronDown,
CircleAlert,
Expand,
GraduationCap,
- Highlighter,
- History,
- Link2,
Loader2,
Minimize2,
- MoreHorizontal,
NotebookPen,
PanelLeftClose,
PanelLeftOpen,
@@ -32,17 +27,17 @@ import {
PanelRightOpen,
Plus,
StickyNote,
- X,
} from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import type { JumpRequest } from "@/components/reading/PdfDocumentView";
import { READER_ASK_EVENT, ReaderPane } from "@/components/reading/ReaderPane";
+import { ReadingActionsProvider } from "@/components/reading/ReadingActionsProvider";
+import { focusReadingComposer } from "@/components/reading/reading-actions-context";
import { useChatStateAdapter } from "@/features/chat/ChatStateAdapter";
import type { ReaderHeading } from "@/lib/reading-outline";
import { setReadingViewport } from "@/lib/reading-turn-state";
-import { listNotebooks, type NotebookSummary } from "@/lib/notebook-api";
import { consumePendingPrompt } from "@/lib/pending-prompt";
import {
getMaterial,
@@ -63,26 +58,28 @@ import {
listReadingConversations,
retryReadingMaterial,
unlinkReadingConversation,
- type ReadingConversation,
type ReadingLibraryMaterial,
} from "@/lib/reading-workspace-api";
import { SourceNavigator } from "./SourceNavigator";
import {
- CompanionWelcome,
EmptyWorkspace,
MaterialFailure,
MaterialProcessing,
- MenuItem,
} from "./WorkspaceChrome";
import {
ConversationLinkDialog,
- ConversationMenu,
NotebookCaptureDialog,
OrganizedNotesDialog,
WorkspaceConfirmDialog,
WorkspaceValueDialog,
} from "./dialogs";
import { ReadingCompanion } from "./ReadingCompanion";
+import { ReadAloudButton } from "./ReadAloudButton";
+import {
+ WorkspaceMenuContext,
+ type WorkspaceMenuItem,
+} from "@/components/reading/workspace-menu-context";
+import { WorkspaceMenu, useWorkspaceMenuHost } from "./WorkspaceMenu";
import { useReadingWorkspace } from "./useReadingWorkspace";
import { useReadingLearningMode } from "./useLearningMode";
@@ -159,9 +156,6 @@ export function ReadingWorkspacePage() {
switchMaterial,
removeMaterial,
newConversation,
- openConversation,
- renameConversation,
- deleteConversation,
organizeNotes,
buildMasteryPath,
renameWorkspace,
@@ -214,15 +208,34 @@ export function ReadingWorkspacePage() {
const [showLinker, setShowLinker] = useState(false);
const [showNotebook, setShowNotebook] = useState(false);
const [showAddSource, setShowAddSource] = useState(false);
- const [showActions, setShowActions] = useState(false);
+ const { host: menuHost, sections: menuSections } = useWorkspaceMenuHost();
const [showRename, setShowRename] = useState(false);
const [showMastery, setShowMastery] = useState(false);
+ const collectionMenu = useMemo<WorkspaceMenuItem[]>(
+ () => [
+ {
+ key: "organize",
+ icon: StickyNote,
+ label: t("Organize notes"),
+ onSelect: () => void organizeNotes(),
+ },
+ {
+ key: "notebook",
+ icon: NotebookPen,
+ label: t("Send to Notebook"),
+ onSelect: () => setShowNotebook(true),
+ },
+ {
+ key: "mastery",
+ icon: GraduationCap,
+ label: t("Build Mastery Path"),
+ onSelect: () => setShowMastery(true),
+ },
+ ],
+ [organizeNotes, t],
+ );
const [removeTarget, setRemoveTarget] =
useState<ReadingLibraryMaterial | null>(null);
- const [renameConversationTarget, setRenameConversationTarget] =
- useState<ReadingConversation | null>(null);
- const [deleteConversationTarget, setDeleteConversationTarget] =
- useState<ReadingConversation | null>(null);
const {
closeLearning,
companionOpen,
@@ -255,6 +268,29 @@ export function ReadingWorkspacePage() {
return () => window.cancelAnimationFrame(frame);
}, [setCompanionOpen]);
+ // The two panels are independent wherever at least one of them docks:
+ // opening one used to close the other at every width, so a learner could
+ // never see the outline and the conversation together. Below `lg` both are
+ // sheets over the document, and two sheets at once is just a mess.
+ const toggleNavigator = useCallback(
+ (open: boolean) => {
+ if (open && !window.matchMedia("(min-width: 1024px)").matches) {
+ setCompanionOpen(false);
+ }
+ setNavigatorOpen(open);
+ },
+ [setCompanionOpen, setNavigatorOpen],
+ );
+ const toggleCompanion = useCallback(
+ (open: boolean) => {
+ if (open && !window.matchMedia("(min-width: 1024px)").matches) {
+ setNavigatorOpen(false);
+ }
+ setCompanionOpen(open);
+ },
+ [setCompanionOpen, setNavigatorOpen],
+ );
+
useEffect(() => {
const onAsk = (event: Event) => {
const detail = (event as CustomEvent<ReaderAskDetail>).detail;
@@ -265,12 +301,15 @@ export function ReadingWorkspacePage() {
locator: Number(detail.locator || activeLocator),
selection: quote,
});
- setCompanionOpen(true);
- prefillInputRef.current?.("");
+ toggleCompanion(true);
+ // Focus, not `prefillInputRef("")`: that one *sets* the text, and
+ // "Ask about this" used to wipe whatever the learner had half-typed.
+ // A frame later, because a closed companion is not mounted yet.
+ window.requestAnimationFrame(focusReadingComposer);
};
window.addEventListener(READER_ASK_EVENT, onAsk);
return () => window.removeEventListener(READER_ASK_EVENT, onAsk);
- }, [activeLocator, setCompanionOpen]);
+ }, [activeLocator, toggleCompanion]);
// Guided one-click actions (quick-action row, empty-state suggestions,
// "organize notes") send immediately without ever touching the composer's
@@ -377,7 +416,23 @@ export function ReadingWorkspacePage() {
}
: undefined;
+ // Panels below their docking width are sheets over the document, and a
+ // sheet needs a scrim to close it by. The navigator docks at `lg`, the
+ // companion at `xl`; the scrim used to key on either one being open with a
+ // single `xl:hidden`, so at `lg` it dimmed a document the docked navigator
+ // was sitting beside and swallowed every click on the page.
+ const scrimClass =
+ companionOpen ? "xl:hidden" : navigatorOpen ? "lg:hidden" : "";
+ const materialReady =
+ activeTab?.material.status === "ready" && !isMedia && Boolean(material);
+
return (
+ <ReadingActionsProvider
+ materialId={materialReady ? (activeTab?.material.material_id ?? null) : null}
+ locator={activeLocator}
+ onStart={() => toggleCompanion(true)}
+ >
+ <WorkspaceMenuContext.Provider value={menuHost}>
<main
ref={mainRef}
data-learning={learning ? "true" : undefined}
@@ -386,12 +441,31 @@ export function ReadingWorkspacePage() {
>
<header className="flex h-11 shrink-0 items-center gap-1.5 border-b border-[var(--border)] bg-[var(--card)] px-2.5">
<Link
- href={scopedUrl(READING_HOME)}
+ href={readingFolderRoute(workspace.workspace_id)}
className="flex size-7 shrink-0 items-center justify-center rounded-md text-[var(--muted-foreground)] transition hover:bg-[var(--muted)]"
- aria-label={t("Back to collections")}
+ aria-label={t("Back to folder")}
>
<ArrowLeft size={14} />
</Link>
+ {/* The outline opens on the left, so its switch lives on the left:
+ it sat at the far right, next to the companion's, and a learner
+ had to guess which of two panel icons was which. */}
+ <button
+ type="button"
+ onClick={() => toggleNavigator(!navigatorOpen)}
+ className={`flex size-7 shrink-0 items-center justify-center rounded-md transition hover:bg-[var(--muted)] ${
+ navigatorOpen
+ ? "text-[var(--primary)]"
+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
+ }`}
+ aria-label={
+ navigatorOpen ? t("Collapse contents") : t("Expand contents")
+ }
+ title={navigatorOpen ? t("Collapse contents") : t("Expand contents")}
+ aria-expanded={navigatorOpen}
+ >
+ {navigatorOpen ? <PanelLeftClose size={14} /> : <PanelLeftOpen size={14} />}
+ </button>
<button
type="button"
onClick={() => setShowRename(true)}
@@ -400,17 +474,14 @@ export function ReadingWorkspacePage() {
>
{workspace.title}
</button>
- <span className="mx-1 h-4 w-px shrink-0 bg-[var(--border)]" />
-
- <div className="min-w-0 flex-1" />
<button
type="button"
onClick={() => setShowAddSource(true)}
- className="mr-0.5 flex size-7 shrink-0 items-center justify-center rounded-md text-[var(--muted-foreground)] transition hover:bg-[var(--muted)] hover:text-[var(--primary)]"
+ className="flex size-7 shrink-0 items-center justify-center rounded-md text-[var(--muted-foreground)] transition hover:bg-[var(--muted)] hover:text-[var(--primary)]"
aria-label={t("Add material")}
title={t("Add material")}
>
- <Plus size={13} />
+ <Plus size={14} />
</button>
<div className="ml-auto flex shrink-0 items-center gap-0.5">
@@ -419,77 +490,34 @@ export function ReadingWorkspacePage() {
{notice}
</span>
)}
+ <ReadAloudButton disabled={!materialReady} />
+ {/* An icon, like every other control on this bar: as the only
+ labelled button it read as the page's primary action. */}
<button
type="button"
onClick={() => (learning ? closeLearning() : openLearning())}
- className="flex h-7 shrink-0 items-center gap-1 rounded-md px-1.5 text-[11px] font-medium text-[var(--muted-foreground)] transition hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
+ className={`flex size-7 shrink-0 items-center justify-center rounded-md transition hover:bg-[var(--muted)] ${
+ learning
+ ? "text-[var(--primary)]"
+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
+ }`}
aria-pressed={learning}
- title={t(
+ aria-label={t(
learning ? "Exit learning mode" : "Fullscreen learning",
)}
- >
- {learning ? <Minimize2 size={13} /> : <Expand size={13} />}
- {t(learning ? "Exit learning mode" : "Fullscreen learning")}
- </button>
- <div className="relative">
- <button
- type="button"
- onClick={() => setShowActions((current) => !current)}
- className="flex size-7 items-center justify-center rounded-md text-[var(--muted-foreground)] transition hover:bg-[var(--muted)]"
- aria-label={t("Collection actions")}
- aria-expanded={showActions}
- >
- <MoreHorizontal size={14} />
- </button>
- {showActions && (
- <div className="absolute right-0 top-8 z-40 w-48 rounded-lg border border-[var(--border)] bg-[var(--card)] p-1 text-[11.5px] shadow-md dark:bg-[var(--popover)]">
- <MenuItem
- icon={StickyNote}
- label={t("Organize notes")}
- onClick={() => {
- setShowActions(false);
- void organizeNotes();
- }}
- />
- <MenuItem
- icon={NotebookPen}
- label={t("Send to Notebook")}
- onClick={() => {
- setShowActions(false);
- setShowNotebook(true);
- }}
- />
- <MenuItem
- icon={GraduationCap}
- label={t("Build Mastery Path")}
- onClick={() => {
- setShowActions(false);
- setShowMastery(true);
- }}
- />
- </div>
+ title={t(
+ learning ? "Exit learning mode" : "Fullscreen learning",
)}
- </div>
- <button
- type="button"
- onClick={() => {
- setCompanionOpen(false);
- setNavigatorOpen(!navigatorOpen);
- }}
- className="flex size-7 items-center justify-center rounded-md text-[var(--muted-foreground)] transition hover:bg-[var(--muted)] hover:text-[var(--primary)]"
- aria-label={
- navigatorOpen ? t("Collapse contents") : t("Expand contents")
- }
- aria-expanded={navigatorOpen}
>
- {navigatorOpen ? <PanelLeftClose size={14} /> : <PanelLeftOpen size={14} />}
+ {learning ? <Minimize2 size={14} /> : <Expand size={14} />}
</button>
+ <WorkspaceMenu
+ sections={menuSections}
+ collection={collectionMenu}
+ />
<button
type="button"
- onClick={() => {
- setNavigatorOpen(false);
- setCompanionOpen((current) => !current);
- }}
+ onClick={() => toggleCompanion(!companionOpen)}
className={`flex size-7 items-center justify-center rounded-md transition hover:bg-[var(--muted)] ${
companionOpen
? "text-[var(--primary)]"
@@ -519,12 +547,16 @@ export function ReadingWorkspacePage() {
}`}
style={gridStyle}
>
- {(navigatorOpen || companionOpen) && (
+ {scrimClass && (
<button
type="button"
- className="absolute inset-0 z-20 bg-[var(--overlay)] xl:hidden"
+ className={`absolute inset-0 z-20 bg-[var(--overlay)] ${scrimClass}`}
onClick={() => {
- setNavigatorOpen(false);
+ // Only the panels that are sheets at this width: a docked
+ // navigator has nothing to do with a tap on the scrim.
+ if (!window.matchMedia("(min-width: 1024px)").matches) {
+ setNavigatorOpen(false);
+ }
setCompanionOpen(false);
}}
aria-label={t("Close panels")}
@@ -556,6 +588,13 @@ export function ReadingWorkspacePage() {
activeLocator={activeLocator}
bookmarks={bookmarks}
onRemoveBookmark={(bookmarkId) => void removeBookmark(bookmarkId)}
+ onOpenAnnotation={(locator, quote) =>
+ setDocumentJump((current) => ({
+ locator,
+ quote,
+ nonce: (current?.nonce ?? 0) + 1,
+ }))
+ }
annotationCount={annotations.length}
unitCount={material?.unit_count ?? 0}
open={navigatorOpen}
@@ -616,6 +655,7 @@ export function ReadingWorkspacePage() {
// viewport, unlike the media stage above.
onLocatorChange={setActiveLocator}
headingJump={headingJump}
+ ownAnnotationList={false}
bookmarks={bookmarks}
onToggleBookmark={(locator, label) =>
void toggleBookmark(locator, label)
@@ -625,36 +665,6 @@ export function ReadingWorkspacePage() {
</div>
)}
- {selection && (
- <div className="absolute bottom-4 left-1/2 z-30 flex max-w-[82%] -translate-x-1/2 items-center gap-2 rounded-xl border border-[var(--border)] bg-[var(--card)] px-3 py-2 shadow-[0_12px_36px_rgba(0,0,0,.16)] dark:border-[var(--border)] dark:bg-[var(--popover)]">
- <Highlighter
- size={13}
- className="shrink-0 text-[var(--primary)]"
- />
- <p className="min-w-0 flex-1 truncate text-[10.5px] text-[var(--muted-foreground)] dark:text-[var(--foreground)]">
- “{selection.quote}”
- </p>
- <button
- type="button"
- onClick={() => {
- setCompanionOpen(true);
- prefillInputRef.current?.("");
- }}
- className="shrink-0 rounded-lg bg-[var(--primary)] px-2.5 py-1 text-[10.5px] font-semibold text-[var(--primary-foreground)]"
- >
- {t("Ask AI")}
- </button>
- <button
- type="button"
- onClick={() => {
- setSelection(null);
- setReadingViewport({ selection: "" });
- }}
- >
- <X size={11} />
- </button>
- </div>
- )}
</section>
{showResizeHandle && (
@@ -673,17 +683,13 @@ export function ReadingWorkspacePage() {
<ReadingCompanion
workspaceId={workspaceId}
material={activeTab?.material ?? null}
- conversations={conversations}
activeConversation={activeConversation}
linkedSessionIds={linkedSessionIds}
activeLocator={activeLocator}
selection={selection}
onClearSelection={() => setSelection(null)}
onOpenLinker={() => setShowLinker(true)}
- onSelectConversation={openConversation}
onNewConversation={newConversation}
- onRenameConversation={setRenameConversationTarget}
- onDeleteConversation={setDeleteConversationTarget}
onQuickPrompt={sendQuickPrompt}
prefillInputRef={prefillInputRef}
onClose={() => setCompanionOpen(false)}
@@ -707,38 +713,6 @@ export function ReadingWorkspacePage() {
/>
)}
- {renameConversationTarget && (
- <WorkspaceValueDialog
- title={t("Rename conversation")}
- label={t("Conversation name")}
- initialValue={renameConversationTarget.title}
- actionLabel={t("Save")}
- onClose={() => setRenameConversationTarget(null)}
- onSubmit={async (value) => {
- await renameConversation(
- renameConversationTarget.session_id,
- value,
- );
- setRenameConversationTarget(null);
- }}
- />
- )}
-
- {deleteConversationTarget && (
- <WorkspaceConfirmDialog
- title={t("Delete conversation")}
- body={t("Delete “{{title}}”? The transcript cannot be recovered.", {
- title: deleteConversationTarget.title,
- })}
- actionLabel={t("Delete")}
- onClose={() => setDeleteConversationTarget(null)}
- onConfirm={async () => {
- await deleteConversation(deleteConversationTarget.session_id);
- setDeleteConversationTarget(null);
- }}
- />
- )}
-
{showRename && (
<WorkspaceValueDialog
title={t("Rename collection")}
@@ -827,5 +801,7 @@ export function ReadingWorkspacePage() {
/>
)}
</main>
+ </WorkspaceMenuContext.Provider>
+ </ReadingActionsProvider>
);
}
diff --git a/web/components/reading/workspace/SourceNavigator.tsx b/web/components/reading/workspace/SourceNavigator.tsx
index 61ea41d4d..f00c9fc50 100644
--- a/web/components/reading/workspace/SourceNavigator.tsx
+++ b/web/components/reading/workspace/SourceNavigator.tsx
@@ -4,6 +4,7 @@ import {
BookmarkCheck,
ChevronDown,
ChevronRight,
+ Highlighter,
ListTree,
Loader2,
Search,
@@ -12,7 +13,9 @@ import {
} from "lucide-react";
import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
+import { useReading } from "@/context/ReadingContext";
import {
+ type AnnotationItem,
type OutlineRow,
type ReadingBookmark,
type UnitReference,
@@ -29,6 +32,7 @@ import {
type ReadingWorkspaceTab,
} from "@/lib/reading-workspace-api";
import { formatMediaTime, timeFromSourceHref } from "@/lib/reading-media-time";
+import { AnnotationList } from "../AnnotationList";
import { iconForMaterial } from "./WorkspaceChrome";
import { type TranscriptRow } from "./types";
@@ -56,6 +60,7 @@ export function SourceNavigator({
onNavigate,
bookmarks,
onRemoveBookmark,
+ onOpenAnnotation,
}: {
material: ReadingLibraryMaterial | null;
materials: ReadingWorkspaceTab[];
@@ -81,17 +86,34 @@ export function SourceNavigator({
/** Places the reader kept, listed above the outline. */
bookmarks: ReadingBookmark[];
onRemoveBookmark: (bookmarkId: string) => void;
+ /**
+ * Scroll the document to a mark. Separate from `onNavigate` because a
+ * transcript row's quote becomes the companion's quoted context, and
+ * opening a highlight should not quietly change what the next question is
+ * about.
+ */
+ onOpenAnnotation?: (locator: number, quote?: string) => void;
}) {
const { t } = useTranslation();
+ // The document's marks, listed here rather than in a column of the reader:
+ // beside the navigator and the companion, a fourth column left the page
+ // itself the narrowest thing on screen.
+ const reading = useReading();
+ const [view, setView] = useState<"contents" | "notes">("contents");
+ const [activeAnnotationId, setActiveAnnotationId] = useState<string | null>(
+ null,
+ );
+ const notesAvailable = Boolean(onOpenAnnotation) && !mediaSourceOf(material);
+ const showNotes = notesAvailable && view === "notes";
+ const openAnnotation = (annotation: AnnotationItem) => {
+ setActiveAnnotationId(annotation.annotation_id);
+ onOpenAnnotation?.(annotation.locator, annotation.quote || undefined);
+ };
const [collapsedNodes, setCollapsedNodes] = useState<Set<string>>(new Set());
const [collapsedMaterials, setCollapsedMaterials] = useState<Set<string>>(
new Set(),
);
- const mediaSource =
- material?.render_mode === "video" ||
- material?.render_mode === "audio" ||
- material?.source_kind === "youtube" ||
- material?.source_kind === "bilibili";
+ const mediaSource = mediaSourceOf(material);
const isPdf = material?.render_mode === "pdf";
const reliableOutline = isPdf
? outline.filter((row) => !row.synthesised)
@@ -192,279 +214,354 @@ export function SourceNavigator({
: "hidden"
}`}
>
- <div className="flex h-10 shrink-0 items-center gap-2 border-b border-[var(--border)] px-3 dark:border-[var(--border)]">
- <ListTree size={13} className="text-[var(--primary)]" />
- <p className="min-w-0 flex-1 truncate text-[10.5px] font-semibold">
- {t("Contents")}
- </p>
- {!!annotationCount && (
- <span className="rounded-full bg-[var(--muted)] px-1.5 py-0.5 text-[10px] text-[var(--muted-foreground)]">
- {annotationCount}
- </span>
+ <div className="flex h-11 shrink-0 items-center gap-1 border-b border-[var(--border)] px-2 dark:border-[var(--border)]">
+ {notesAvailable ? (
+ <div role="tablist" className="flex min-w-0 flex-1 items-center gap-0.5">
+ <NavigatorTab
+ active={!showNotes}
+ icon={ListTree}
+ label={t("Contents")}
+ onClick={() => setView("contents")}
+ />
+ <NavigatorTab
+ active={showNotes}
+ icon={Highlighter}
+ label={t("Annotations")}
+ count={annotationCount}
+ onClick={() => setView("notes")}
+ />
+ </div>
+ ) : (
+ <p className="flex min-w-0 flex-1 items-center gap-2 truncate px-1 text-[12px] font-semibold">
+ <ListTree size={13} className="shrink-0 text-[var(--primary)]" />
+ {t("Contents")}
+ </p>
)}
<button
type="button"
onClick={onClose}
- className="flex size-6 items-center justify-center rounded-md text-[var(--muted-foreground)] hover:bg-[var(--muted)]"
+ className="flex size-7 shrink-0 items-center justify-center rounded-md text-[var(--muted-foreground)] hover:bg-[var(--muted)]"
aria-label={t("Close contents")}
>
- <X size={11} />
+ <X size={13} />
</button>
</div>
- <label className="mx-2 mt-2 flex h-8 shrink-0 items-center gap-2 rounded-lg border border-[var(--border)] bg-[var(--card)] px-2.5 dark:border-[var(--border)] dark:bg-[var(--card)]">
- <Search size={11} className="text-[var(--muted-foreground)]" />
- <input
- value={search}
- onChange={(event) => onSearch(event.target.value)}
- placeholder={t("Search materials and contents")}
- className="min-w-0 flex-1 bg-transparent text-[10px] outline-none"
- />
- </label>
+ {showNotes && material ? (
+ <div className="min-h-0 flex-1">
+ <AnnotationList
+ annotations={reading.annotations}
+ unit={reading.material?.unit ?? "page"}
+ activeId={activeAnnotationId}
+ onSelect={openAnnotation}
+ onDelete={(annotation) => void reading.removeMark(annotation)}
+ />
+ </div>
+ ) : (
+ <>
+ <label className="mx-2 mt-2 flex h-8 shrink-0 items-center gap-2 rounded-lg border border-[var(--border)] bg-[var(--card)] px-2.5 dark:border-[var(--border)] dark:bg-[var(--card)]">
+ <Search size={12} className="text-[var(--muted-foreground)]" />
+ <input
+ value={search}
+ onChange={(event) => onSearch(event.target.value)}
+ placeholder={t("Search materials and contents")}
+ className="min-w-0 flex-1 bg-transparent text-[12px] outline-none"
+ />
+ </label>
- <div className="mt-2 min-h-0 flex-1 overflow-y-auto px-2 pb-3">
- {bookmarks.length > 0 && (
- /* The reader's own short index, in front of the document's long
- one. Above rather than below because it is the shorter list and
- the one they came here for — scrolling past 74 outline rows to
- reach three saved places would defeat the point. */
- <div className="mb-2 border-b border-[var(--border)] pb-2">
- <p className="flex items-center gap-1.5 px-2 py-1 text-[10px] font-semibold uppercase tracking-wide text-[var(--muted-foreground)]">
- <BookmarkCheck size={11} className="text-[var(--primary)]" />
- {t("Bookmarks")}
- <span className="tabular-nums opacity-70">
- {bookmarks.length}
- </span>
- </p>
- {bookmarks.map((row) => (
- <div
- key={row.bookmark_id}
- className={`group flex items-center gap-1 rounded-lg transition ${
- activeLocator === row.locator
- ? "bg-[color-mix(in_srgb,var(--primary)_10%,transparent)] text-[var(--primary)]"
- : "text-[var(--foreground)] hover:bg-[var(--muted)]"
- }`}
- >
- <button
- type="button"
- onClick={() => onNavigate(row.locator)}
- className="flex min-w-0 flex-1 items-baseline gap-2 px-2 py-1.5 text-left"
- >
- <span className="w-6 shrink-0 text-right text-[10px] tabular-nums text-[var(--muted-foreground)]">
- {row.locator}
- </span>
- {/* A bookmark saved without a label is "this page", so it
- borrows the outline's own heading for that locator
- rather than making the reader name a place before they
- are allowed to keep it. */}
- <span className="line-clamp-2 min-w-0 text-[10.5px] leading-[1.5]">
- {row.label ||
- outline.find((entry) => entry.locator === row.locator)
- ?.title ||
- t("p. {{page}}", { page: row.locator })}
+ <div className="mt-2 min-h-0 flex-1 overflow-y-auto px-2 pb-3">
+ {bookmarks.length > 0 && (
+ /* The reader's own short index, in front of the document's long
+ one. Above rather than below because it is the shorter list and
+ the one they came here for — scrolling past 74 outline rows to
+ reach three saved places would defeat the point. */
+ <div className="mb-2 border-b border-[var(--border)] pb-2">
+ <p className="flex items-center gap-1.5 px-2 py-1 text-[10.5px] font-semibold uppercase tracking-wide text-[var(--muted-foreground)]">
+ <BookmarkCheck size={11} className="text-[var(--primary)]" />
+ {t("Bookmarks")}
+ <span className="tabular-nums opacity-70">
+ {bookmarks.length}
</span>
- </button>
- <button
- type="button"
- onClick={() => onRemoveBookmark(row.bookmark_id)}
- aria-label={t("Remove this bookmark")}
- className="mr-1 shrink-0 rounded-md p-1 text-[var(--muted-foreground)] opacity-0 transition hover:bg-[var(--accent)] hover:text-[var(--foreground)] focus-visible:opacity-100 group-hover:opacity-100"
- >
- <Trash2 size={11} />
- </button>
- </div>
- ))}
- </div>
- )}
- {visibleMaterials.length === 0 ? (
- <div className="px-2 py-4 text-[10px] leading-relaxed text-[var(--muted-foreground)]">
- {query ? (
- <p>{t("No matching materials or contents.")}</p>
- ) : mediaSource && transcriptUnavailable ? (
- <>
- <p className="font-medium text-[var(--muted-foreground)]">
- {t("No transcript available")}
</p>
- <p className="mt-1">
- {t(
- "Playback still works. Transcript-grounded explanation and timestamp search are unavailable for this video.",
- )}
- </p>
- </>
- ) : (
- <p>
- {material?.status === "ready"
- ? t("This material has no outline to navigate yet.")
- : t("The outline appears once processing finishes.")}
- </p>
- )}
- </div>
- ) : (
- <ul>
- {visibleMaterials.map(({ material: candidate }) => {
- const active = candidate.material_id === activeMaterialId;
- const MaterialIcon = iconForMaterial(candidate);
- const busy =
- candidate.status === "processing" ||
- candidate.status === "queued";
- const expanded =
- active && !collapsedMaterials.has(candidate.material_id);
-
- return (
- <li key={candidate.material_id} className="mb-1">
+ {bookmarks.map((row) => (
<div
- className={`flex items-center gap-1 rounded-lg transition ${
- active
- ? "bg-[var(--primary)]/10 text-[var(--primary)]"
+ key={row.bookmark_id}
+ className={`group flex items-center gap-1 rounded-lg transition ${
+ activeLocator === row.locator
+ ? "bg-[color-mix(in_srgb,var(--primary)_10%,transparent)] text-[var(--primary)]"
: "text-[var(--foreground)] hover:bg-[var(--muted)]"
}`}
>
<button
type="button"
- onClick={() => selectMaterial(candidate)}
- aria-current={active ? "true" : undefined}
- className="flex min-w-0 flex-1 items-center gap-2 px-2 py-2 text-left"
+ onClick={() => onNavigate(row.locator)}
+ className="flex min-w-0 flex-1 items-baseline gap-2 px-2 py-1.5 text-left"
>
- {busy ? (
- <Loader2 size={12} className="shrink-0 animate-spin" />
- ) : (
- <MaterialIcon size={12} className="shrink-0" />
- )}
- <span className="line-clamp-2 min-w-0 text-[11px] font-medium leading-[1.35]">
- {candidate.title || candidate.filename}
+ <span className="w-7 shrink-0 text-right text-[11px] tabular-nums text-[var(--muted-foreground)]">
+ {row.locator}
+ </span>
+ {/* A bookmark saved without a label is "this page", so it
+ borrows the outline's own heading for that locator
+ rather than making the reader name a place before they
+ are allowed to keep it. */}
+ <span className="line-clamp-2 min-w-0 text-[12px] leading-[1.5]">
+ {row.label ||
+ outline.find((entry) => entry.locator === row.locator)
+ ?.title ||
+ t("p. {{page}}", { page: row.locator })}
</span>
</button>
- {active && (
- <button
- type="button"
- onClick={() =>
- setCollapsedMaterials((current) => {
- const next = new Set(current);
- if (next.has(candidate.material_id))
- next.delete(candidate.material_id);
- else next.add(candidate.material_id);
- return next;
- })
- }
- className="mr-1 shrink-0 rounded-md p-1 text-[var(--muted-foreground)] hover:bg-[var(--accent)] hover:text-[var(--foreground)]"
- aria-expanded={expanded}
- aria-label={
- expanded
- ? t("Collapse section")
- : t("Expand section")
- }
- >
- {expanded ? (
- <ChevronDown size={11} />
- ) : (
- <ChevronRight size={11} />
- )}
- </button>
- )}
<button
type="button"
- onClick={() => onRemoveMaterial(candidate)}
- className="mr-1 shrink-0 rounded-md p-1 text-[var(--muted-foreground)] transition hover:bg-[var(--muted)] hover:text-[var(--destructive)]"
- aria-label={t("Remove from collection")}
- title={t("Remove from collection")}
+ onClick={() => onRemoveBookmark(row.bookmark_id)}
+ aria-label={t("Remove this bookmark")}
+ className="mr-1 shrink-0 rounded-md p-1 text-[var(--muted-foreground)] opacity-0 transition hover:bg-[var(--accent)] hover:text-[var(--foreground)] focus-visible:opacity-100 group-hover:opacity-100"
>
- <X size={10} />
+ <Trash2 size={11} />
</button>
</div>
+ ))}
+ </div>
+ )}
+ {visibleMaterials.length === 0 ? (
+ <div className="px-2 py-4 text-[11.5px] leading-relaxed text-[var(--muted-foreground)]">
+ {query ? (
+ <p>{t("No matching materials or contents.")}</p>
+ ) : mediaSource && transcriptUnavailable ? (
+ <>
+ <p className="font-medium text-[var(--muted-foreground)]">
+ {t("No transcript available")}
+ </p>
+ <p className="mt-1">
+ {t(
+ "Playback still works. Transcript-grounded explanation and timestamp search are unavailable for this video.",
+ )}
+ </p>
+ </>
+ ) : (
+ <p>
+ {material?.status === "ready"
+ ? t("This material has no outline to navigate yet.")
+ : t("The outline appears once processing finishes.")}
+ </p>
+ )}
+ </div>
+ ) : (
+ <ul>
+ {visibleMaterials.map(({ material: candidate }) => {
+ const active = candidate.material_id === activeMaterialId;
+ const MaterialIcon = iconForMaterial(candidate);
+ const busy =
+ candidate.status === "processing" ||
+ candidate.status === "queued";
+ const expanded =
+ active && !collapsedMaterials.has(candidate.material_id);
- {expanded && (
- <div className="ml-2 mt-0.5 border-l border-[var(--border)] pl-1">
- {mediaSource ? (
- rows.map((row) => (
+ return (
+ <li key={candidate.material_id} className="mb-1">
+ <div
+ className={`flex items-center gap-1 rounded-lg transition ${
+ active
+ ? "bg-[color-mix(in_srgb,var(--primary)_10%,transparent)] text-[var(--primary)]"
+ : "text-[var(--foreground)] hover:bg-[var(--muted)]"
+ }`}
+ >
+ <button
+ type="button"
+ onClick={() => selectMaterial(candidate)}
+ aria-current={active ? "true" : undefined}
+ className="flex min-w-0 flex-1 items-center gap-2 px-2 py-2 text-left"
+ >
+ {busy ? (
+ <Loader2 size={12} className="shrink-0 animate-spin" />
+ ) : (
+ <MaterialIcon size={12} className="shrink-0" />
+ )}
+ <span className="line-clamp-2 min-w-0 text-[12.5px] font-medium leading-[1.35]">
+ {candidate.title || candidate.filename}
+ </span>
+ </button>
+ {active && (
<button
- key={row.locator}
type="button"
onClick={() =>
- onNavigate(
- row.locator,
- !chaptersOnly && transcript.length
- ? row.text
- : undefined,
- )
+ setCollapsedMaterials((current) => {
+ const next = new Set(current);
+ if (next.has(candidate.material_id))
+ next.delete(candidate.material_id);
+ else next.add(candidate.material_id);
+ return next;
+ })
+ }
+ className="mr-1 shrink-0 rounded-md p-1 text-[var(--muted-foreground)] hover:bg-[var(--accent)] hover:text-[var(--foreground)]"
+ aria-expanded={expanded}
+ aria-label={
+ expanded
+ ? t("Collapse section")
+ : t("Expand section")
}
- className={`mb-0.5 flex w-full gap-2 rounded-lg px-2 py-2 text-left transition ${
- activeLocator === row.locator
- ? "bg-[var(--muted)] text-[var(--primary)]"
- : "text-[var(--muted-foreground)] hover:bg-[var(--muted)]"
- }`}
- >
- <span className="mt-0.5 w-9 shrink-0 text-[10px] font-medium tabular-nums text-[var(--primary)]">
- {row.title || row.locator}
- </span>
- <span className="line-clamp-3 text-[10.5px] leading-[1.45]">
- {row.text}
- </span>
- </button>
- ))
- ) : documentOutline.length > 0 ? (
- <WorkspaceOutlineBranch
- nodes={documentTree}
- activeRow={activeDocumentRow}
- pageFallback={pageFallback}
- collapsedNodes={search ? new Set() : collapsedNodes}
- onToggle={(key) =>
- setCollapsedNodes((current) => {
- const next = new Set(current);
- if (next.has(key)) next.delete(key);
- else next.add(key);
- return next;
- })
- }
- onNavigate={onNavigate}
- />
- ) : (
- visibleHeadings.map((heading) => (
- <button
- key={heading.id}
- type="button"
- onClick={() => onNavigateHeading(heading)}
- style={{
- paddingLeft: `${
- 10 + (Math.min(heading.level, 4) - 1) * 10
- }px`,
- }}
- className={`mb-0.5 block w-full truncate rounded-lg py-1.5 pr-2 text-left text-[10px] leading-[1.4] transition ${
- activeHeadingId === heading.id
- ? "bg-[var(--muted)] font-medium text-[var(--primary)]"
- : "text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
- }`}
- title={heading.title}
>
- {heading.title}
+ {expanded ? (
+ <ChevronDown size={11} />
+ ) : (
+ <ChevronRight size={11} />
+ )}
</button>
- ))
+ )}
+ <button
+ type="button"
+ onClick={() => onRemoveMaterial(candidate)}
+ className="mr-1 shrink-0 rounded-md p-1 text-[var(--muted-foreground)] transition hover:bg-[var(--muted)] hover:text-[var(--destructive)]"
+ aria-label={t("Remove from collection")}
+ title={t("Remove from collection")}
+ >
+ <X size={10} />
+ </button>
+ </div>
+
+ {expanded && (
+ <div className="ml-2 mt-0.5 border-l border-[var(--border)] pl-1">
+ {mediaSource ? (
+ rows.map((row) => (
+ <button
+ key={row.locator}
+ type="button"
+ onClick={() =>
+ onNavigate(
+ row.locator,
+ !chaptersOnly && transcript.length
+ ? row.text
+ : undefined,
+ )
+ }
+ className={`mb-0.5 flex w-full gap-2 rounded-lg px-2 py-2 text-left transition ${
+ activeLocator === row.locator
+ ? "bg-[var(--muted)] text-[var(--primary)]"
+ : "text-[var(--muted-foreground)] hover:bg-[var(--muted)]"
+ }`}
+ >
+ <span className="mt-0.5 w-10 shrink-0 text-[11px] font-medium tabular-nums text-[var(--primary)]">
+ {row.title || row.locator}
+ </span>
+ <span className="line-clamp-3 text-[12px] leading-[1.45]">
+ {row.text}
+ </span>
+ </button>
+ ))
+ ) : documentOutline.length > 0 ? (
+ <WorkspaceOutlineBranch
+ nodes={documentTree}
+ activeRow={activeDocumentRow}
+ pageFallback={pageFallback}
+ collapsedNodes={search ? new Set() : collapsedNodes}
+ onToggle={(key) =>
+ setCollapsedNodes((current) => {
+ const next = new Set(current);
+ if (next.has(key)) next.delete(key);
+ else next.add(key);
+ return next;
+ })
+ }
+ onNavigate={onNavigate}
+ />
+ ) : (
+ visibleHeadings.map((heading) => (
+ <button
+ key={heading.id}
+ type="button"
+ onClick={() => onNavigateHeading(heading)}
+ style={{
+ paddingLeft: `${
+ 10 + (Math.min(heading.level, 4) - 1) * 10
+ }px`,
+ }}
+ className={`mb-0.5 block w-full truncate rounded-lg py-1.5 pr-2 text-left text-[12px] leading-[1.4] transition ${
+ activeHeadingId === heading.id
+ ? "bg-[var(--muted)] font-medium text-[var(--primary)]"
+ : "text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
+ }`}
+ title={heading.title}
+ >
+ {heading.title}
+ </button>
+ ))
+ )}
+ </div>
)}
- </div>
- )}
- </li>
- );
- })}
- </ul>
- )}
- </div>
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ </div>
- <div className="shrink-0 border-t border-[var(--border)] px-3 py-2 text-[10px] text-[var(--muted-foreground)] dark:border-[var(--border)]">
- {material && material.status === "ready"
- ? mediaSource
- ? t("{{count}} passages available to the companion", {
- count: rows.length,
- })
- : pageFallback
- ? t("{{count}} pages", { count: documentOutline.length })
- : t("{{count}} outline entries", {
- count: documentOutline.length,
- })
- : t(material?.status || "queued")}
- </div>
+ <div className="shrink-0 border-t border-[var(--border)] px-3 py-2 text-[11px] text-[var(--muted-foreground)] dark:border-[var(--border)]">
+ {material && material.status === "ready"
+ ? mediaSource
+ ? t("{{count}} passages available to the companion", {
+ count: rows.length,
+ })
+ : pageFallback
+ ? t("{{count}} pages", { count: documentOutline.length })
+ : t("{{count}} outline entries", {
+ count: documentOutline.length,
+ })
+ : t(material?.status || "queued")}
+ </div>
+ </>
+ )}
</aside>
);
}
+function mediaSourceOf(material: ReadingLibraryMaterial | null) {
+ return (
+ material?.render_mode === "video" ||
+ material?.render_mode === "audio" ||
+ material?.source_kind === "youtube" ||
+ material?.source_kind === "bilibili"
+ );
+}
+
+function NavigatorTab({
+ active,
+ icon: Icon,
+ label,
+ count,
+ onClick,
+}: {
+ active: boolean;
+ icon: typeof ListTree;
+ label: string;
+ count?: number;
+ onClick: () => void;
+}) {
+ return (
+ <button
+ type="button"
+ role="tab"
+ aria-selected={active}
+ onClick={onClick}
+ className={`inline-flex h-7 min-w-0 items-center gap-1.5 rounded-md px-2 text-[12px] font-medium transition ${
+ active
+ ? "bg-[var(--muted)] text-[var(--foreground)]"
+ : "text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
+ }`}
+ >
+ <Icon
+ size={12}
+ className={active ? "shrink-0 text-[var(--primary)]" : "shrink-0"}
+ />
+ <span className="truncate">{label}</span>
+ {count ? (
+ <span className="rounded-full bg-[var(--background)] px-1.5 text-[10.5px] tabular-nums text-[var(--muted-foreground)]">
+ {count}
+ </span>
+ ) : null}
+ </button>
+ );
+}
+
export function WorkspaceOutlineBranch({
nodes,
activeRow,
@@ -518,10 +615,10 @@ export function WorkspaceOutlineBranch({
heights and a ragged left edge for the titles. Right-
aligned tabular digits are what a printed contents page
does anyway, and no translation can outgrow them. */}
- <span className="w-6 shrink-0 text-right text-[10px] tabular-nums text-[var(--muted-foreground)]">
+ <span className="w-7 shrink-0 text-right text-[11px] tabular-nums text-[var(--muted-foreground)]">
{node.row.locator}
</span>
- <span className="line-clamp-3 min-w-0 text-[10.5px] leading-[1.5]">
+ <span className="line-clamp-3 min-w-0 text-[12px] leading-[1.5]">
{node.row.title}
</span>
</button>
diff --git a/web/components/reading/workspace/WorkspaceChrome.tsx b/web/components/reading/workspace/WorkspaceChrome.tsx
index d4e20a261..1aec9b64a 100644
--- a/web/components/reading/workspace/WorkspaceChrome.tsx
+++ b/web/components/reading/workspace/WorkspaceChrome.tsx
@@ -2,6 +2,7 @@
import {
BrainCircuit,
+ Check,
ChevronRight,
CircleAlert,
FileAudio,
@@ -9,6 +10,7 @@ import {
Film,
Library,
Loader2,
+ Sparkles,
StickyNote,
Youtube,
} from "lucide-react";
@@ -29,19 +31,47 @@ export function MenuItem({
icon: Icon,
label,
onClick,
+ disabled,
+ hint,
+ active,
+ spinning,
}: {
icon: typeof StickyNote;
label: string;
onClick: () => void;
+ disabled?: boolean;
+ /** A second line under the label — why it is disabled, or what it acts on. */
+ hint?: string;
+ /** A setting that is on. Toggles report it; plain actions leave it unset. */
+ active?: boolean;
+ spinning?: boolean;
}) {
return (
<button
type="button"
onClick={onClick}
- className="flex w-full items-center gap-2 rounded-md px-2.5 py-2 text-left text-[var(--foreground)] transition hover:bg-[var(--muted)]"
+ disabled={disabled}
+ role={active === undefined ? undefined : "menuitemcheckbox"}
+ aria-checked={active}
+ className="flex w-full items-start gap-2 rounded-md px-2.5 py-2 text-left text-[var(--foreground)] transition hover:bg-[var(--muted)] disabled:cursor-not-allowed disabled:opacity-45 disabled:hover:bg-transparent"
>
- <Icon size={12} className="text-[var(--muted-foreground)]" />
- {label}
+ <Icon
+ size={13}
+ className={`mt-[2px] shrink-0 ${
+ active ? "text-[var(--primary)]" : "text-[var(--muted-foreground)]"
+ } ${spinning ? "animate-spin" : ""}`}
+ />
+ <span className="min-w-0 flex-1">
+ <span className="block">{label}</span>
+ {hint ? (
+ <span className="mt-0.5 block text-[10.5px] leading-snug text-[var(--muted-foreground)]">
+ {hint}
+ </span>
+ ) : null}
+ </span>
+ {active ? (
+ <Check size={13} className="mt-[2px] shrink-0 text-[var(--primary)]" />
+ ) : null}
</button>
);
}
@@ -50,9 +80,12 @@ export function CompanionWelcome({
title,
onAction,
suggestions = [],
+ tools = [],
}: {
title: string;
onAction: (prompt: string) => void;
+ /** Page-level reading actions (a quiz on this page, say), one click each. */
+ tools?: { key: string; label: string; onClick: () => void }[];
/**
* Openers written against this material. Empty falls back to the three
* generic lines below, which are true of any document — fine as a floor,
@@ -69,10 +102,10 @@ export function CompanionWelcome({
<p className="mt-4 font-serif text-[17px] font-medium tracking-[-0.01em]">
{t("Read with a grounded companion")}
</p>
- <p className="mt-2 text-[10.5px] leading-relaxed text-[var(--muted-foreground)]">
+ <p className="mt-2 text-[12px] leading-relaxed text-[var(--muted-foreground)]">
{title
? t(
- "Ask about {{title}}, select a passage, or use a guided action above.",
+ "Ask anything about {{title}}, or select a passage in the document to explain, translate or discuss it.",
{ title },
)
: t("Add material to begin a reading conversation.")}
@@ -90,16 +123,31 @@ export function CompanionWelcome({
key={item}
type="button"
onClick={() => onAction(item)}
- className="flex w-full items-start gap-2 rounded-xl border border-[var(--border)] bg-[var(--card)] px-3 py-2.5 text-left text-[10.5px] leading-relaxed text-[var(--muted-foreground)] transition hover:border-[color-mix(in_srgb,var(--primary)_40%,transparent)] hover:text-[var(--foreground)] dark:border-[var(--border)] dark:bg-[var(--card)]"
+ className="flex w-full items-start gap-2 rounded-lg border border-[var(--border)] bg-[var(--card)] px-3 py-2 text-left text-[12px] leading-relaxed text-[var(--muted-foreground)] transition hover:border-[color-mix(in_srgb,var(--primary)_40%,transparent)] hover:text-[var(--foreground)] dark:border-[var(--border)] dark:bg-[var(--card)]"
>
<ChevronRight
- size={10}
+ size={12}
className="mt-[3px] shrink-0 text-[var(--primary)]"
/>
<span className="min-w-0 flex-1">{item}</span>
</button>
))}
</div>
+ {tools.length ? (
+ <div className="mt-4 flex flex-wrap justify-center gap-1.5">
+ {tools.map((tool) => (
+ <button
+ key={tool.key}
+ type="button"
+ onClick={tool.onClick}
+ className="inline-flex h-7 items-center gap-1.5 rounded-full border border-[var(--border)] px-2.5 text-[11.5px] font-medium text-[var(--muted-foreground)] transition hover:border-[color-mix(in_srgb,var(--primary)_40%,transparent)] hover:text-[var(--foreground)]"
+ >
+ <Sparkles size={11} className="text-[var(--primary)]" />
+ {tool.label}
+ </button>
+ ))}
+ </div>
+ ) : null}
</div>
);
}
diff --git a/web/components/reading/workspace/WorkspaceMenu.tsx b/web/components/reading/workspace/WorkspaceMenu.tsx
new file mode 100644
index 000000000..aba3b9976
--- /dev/null
+++ b/web/components/reading/workspace/WorkspaceMenu.tsx
@@ -0,0 +1,128 @@
+"use client";
+
+import { MoreHorizontal } from "lucide-react";
+import { useEffect, useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+
+import {
+ type WorkspaceMenuHost,
+ type WorkspaceMenuItem,
+ type WorkspaceMenuSection,
+} from "@/components/reading/workspace-menu-context";
+import { MenuItem } from "./WorkspaceChrome";
+
+export type WorkspaceMenuSections = Partial<
+ Record<WorkspaceMenuSection, WorkspaceMenuItem[]>
+>;
+
+/**
+ * The collector behind the workspace's single ⋯.
+ *
+ * The reader and the companion hand their ⋯ items up through the host, so
+ * the page has one ⋯ instead of three a hand's width apart.
+ */
+export function useWorkspaceMenuHost(): {
+ host: WorkspaceMenuHost;
+ sections: WorkspaceMenuSections;
+} {
+ const [sections, setSections] = useState<WorkspaceMenuSections>({});
+ const host = useMemo<WorkspaceMenuHost>(
+ () => ({
+ register: (section, items) =>
+ setSections((current) =>
+ current[section] === (items ?? undefined)
+ ? current
+ : { ...current, [section]: items ?? undefined },
+ ),
+ }),
+ [],
+ );
+ return { host, sections };
+}
+
+export function WorkspaceMenu({
+ collection,
+ sections,
+}: {
+ /** What acts on the whole collection; always first. */
+ collection: WorkspaceMenuItem[];
+ sections: WorkspaceMenuSections;
+}) {
+ const { t } = useTranslation();
+ const [open, setOpen] = useState(false);
+ useEffect(() => {
+ if (!open) return;
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.key !== "Escape") return;
+ event.preventDefault();
+ setOpen(false);
+ };
+ document.addEventListener("keydown", onKeyDown);
+ return () => document.removeEventListener("keydown", onKeyDown);
+ }, [open]);
+
+ const groups: Array<[string, string, WorkspaceMenuItem[] | undefined]> = [
+ ["collection", t("Collection"), collection],
+ ["material", t("Document"), sections.material],
+ ["conversation", t("Conversation"), sections.conversation],
+ ];
+
+ return (
+ <div className="relative">
+ <button
+ type="button"
+ onClick={() => setOpen((current) => !current)}
+ className="flex size-7 items-center justify-center rounded-md text-[var(--muted-foreground)] transition hover:bg-[var(--muted)]"
+ aria-label={t("More")}
+ title={t("More")}
+ aria-haspopup="menu"
+ aria-expanded={open}
+ >
+ <MoreHorizontal size={14} />
+ </button>
+ {open && (
+ <>
+ <div className="fixed inset-0 z-30" onClick={() => setOpen(false)} />
+ <div
+ role="menu"
+ aria-label={t("More")}
+ className="absolute right-0 top-8 z-40 max-h-[calc(100vh-4rem)] w-64 overflow-y-auto rounded-lg border border-[var(--border)] bg-[var(--card)] p-1 text-[12px] shadow-md dark:bg-[var(--popover)]"
+ >
+ {groups.map(([key, heading, items], index) => {
+ if (!items?.length) return null;
+ return (
+ <div key={key}>
+ {index > 0 && (
+ <div
+ className="mx-1.5 my-1 h-px bg-[var(--border)]"
+ aria-hidden
+ />
+ )}
+ <p className="px-2.5 pb-0.5 pt-1.5 text-[10.5px] font-medium text-[var(--muted-foreground)]">
+ {heading}
+ </p>
+ {items.map((item) => (
+ <MenuItem
+ key={item.key}
+ icon={item.icon}
+ label={item.label}
+ hint={item.hint}
+ active={item.active}
+ spinning={item.spinning}
+ disabled={item.disabled}
+ onClick={() => {
+ // A toggle stays open so the learner sees it flip.
+ if (item.active === undefined) setOpen(false);
+ item.onSelect();
+ }}
+ />
+ ))}
+ </div>
+ );
+ })}
+ </div>
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/web/components/reading/workspace/dialogs.tsx b/web/components/reading/workspace/dialogs.tsx
index 8011d2e81..3bf2dd674 100644
--- a/web/components/reading/workspace/dialogs.tsx
+++ b/web/components/reading/workspace/dialogs.tsx
@@ -5,17 +5,12 @@ import {
Copy,
Loader2,
NotebookPen,
- PenLine,
- Plus,
Send,
- Trash2,
X,
} from "lucide-react";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
-import { SessionAvatar } from "@/components/sidebar/SessionAvatar";
import { type NotebookSummary, listNotebooks } from "@/lib/notebook-api";
-import { formatRelativeTime } from "@/lib/relative-time";
import { copyText } from "@/lib/clipboard";
import { notify } from "@/lib/notifications";
import {
@@ -58,125 +53,6 @@ export function ModalShell({
);
}
-function ConversationRowAction({
- icon: Icon,
- label,
- onClick,
- danger = false,
-}: {
- icon: typeof PenLine;
- label: string;
- onClick: () => void;
- danger?: boolean;
-}) {
- return (
- <button
- type="button"
- title={label}
- aria-label={label}
- onClick={onClick}
- className={`flex size-6 items-center justify-center rounded-lg transition-[background-color,color,transform] duration-150 active:scale-90 hover:bg-[var(--background)] ${
- danger
- ? "text-[var(--muted-foreground)] hover:text-[var(--destructive)]"
- : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
- }`}
- >
- <Icon size={11} />
- </button>
- );
-}
-
-export function ConversationMenu({
- conversations,
- activeSessionId,
- onSelect,
- onNew,
- onRename,
- onDelete,
-}: {
- conversations: ReadingConversation[];
- activeSessionId: string | null;
- onSelect: (id: string) => void;
- onNew: () => void;
- /** Rename this conversation. The backend has always allowed it. */
- onRename: (conversation: ReadingConversation) => void;
- /** Delete this conversation, after the caller confirms. */
- onDelete: (conversation: ReadingConversation) => void;
-}) {
- const { t, i18n } = useTranslation();
- const renameLabel = t("Rename");
- const deleteLabel = t("Delete");
- return (
- <div className="absolute right-2 top-10 z-50 w-72 rounded-2xl border border-[var(--border)] bg-[var(--card)] p-2.5 shadow-[0_20px_50px_rgba(0,0,0,.18)] dark:border-[var(--border)] dark:bg-[var(--popover)]">
- <div className="mb-1.5 flex items-center justify-between px-1.5 py-1">
- <p className="text-[10px] font-semibold uppercase tracking-[0.14em] text-[var(--muted-foreground)]">
- {t("Reading conversations")}
- </p>
- <button
- type="button"
- onClick={onNew}
- className="flex items-center gap-1 rounded-lg px-2 py-1 text-[10px] font-semibold text-[var(--primary)] transition hover:bg-[color-mix(in_srgb,var(--primary)_10%,transparent)]"
- >
- <Plus size={10} /> {t("New")}
- </button>
- </div>
- <div className="max-h-64 space-y-0.5 overflow-y-auto">
- {conversations.map((row) => {
- const active = row.session_id === activeSessionId;
- return (
- <div
- key={row.session_id}
- className={`group/row relative flex w-full items-center gap-1 overflow-hidden rounded-xl transition-colors ${
- active ? "bg-[color-mix(in_srgb,var(--primary)_10%,transparent)]" : "hover:bg-[var(--muted)]"
- }`}
- >
- {active && (
- <span className="absolute left-0 top-1/2 h-4 w-[2.5px] -translate-y-1/2 rounded-r-full bg-[var(--primary)]" />
- )}
- <button
- type="button"
- onClick={() => onSelect(row.session_id)}
- className="flex min-w-0 flex-1 items-center gap-2.5 py-2.5 pl-3 pr-1.5 text-left"
- >
- <SessionAvatar sessionId={row.session_id} size={13} />
- <div className="min-w-0 flex-1">
- <p
- className={`truncate text-[11px] ${active ? "font-semibold text-[var(--foreground)]" : "font-medium text-[var(--foreground)]"}`}
- >
- {row.title}
- </p>
- <p className="mt-0.5 text-[9.5px] text-[var(--muted-foreground)]">
- {formatRelativeTime(row.updated_at, i18n.language)}
- </p>
- </div>
- {active && (
- <Check size={11} className="shrink-0 text-[var(--primary)]" />
- )}
- </button>
- {/* Revealed on hover so a list of conversations still reads as a
- list. Keyboard users reach them by tabbing, which is why they
- are always in the DOM rather than conditionally rendered. */}
- <span className="flex shrink-0 items-center pr-1 opacity-0 transition-opacity focus-within:opacity-100 group-hover/row:opacity-100">
- <ConversationRowAction
- icon={PenLine}
- label={renameLabel}
- onClick={() => onRename(row)}
- />
- <ConversationRowAction
- icon={Trash2}
- label={deleteLabel}
- danger
- onClick={() => onDelete(row)}
- />
- </span>
- </div>
- );
- })}
- </div>
- </div>
- );
-}
-
export function ConversationLinkDialog({
conversations,
current,
diff --git a/web/components/reading/workspace/useLearningMode.ts b/web/components/reading/workspace/useLearningMode.ts
index 8d91fb7c3..adc8de93a 100644
--- a/web/components/reading/workspace/useLearningMode.ts
+++ b/web/components/reading/workspace/useLearningMode.ts
@@ -51,8 +51,10 @@ export function useReadingLearningMode(workspaceId: string) {
const [companionOpen, setCompanionOpen] = useState(() =>
learning ? false : (learningSnapshot?.companionOpen ?? true)
)
+ // The outline starts closed: a learner opens a collection to read, and the
+ // page is the thing to show. Learning mode still opens it on entry.
const [navigatorOpen, setNavigatorOpen] = useState(() =>
- learning ? true : (learningSnapshot?.navigatorOpen ?? true)
+ learning ? true : (learningSnapshot?.navigatorOpen ?? false)
)
const mainRef = useRef<HTMLElement | null>(null)
diff --git a/web/components/reading/workspace/useReadingWorkspace.ts b/web/components/reading/workspace/useReadingWorkspace.ts
index dc88a7de2..b9a1e9323 100644
--- a/web/components/reading/workspace/useReadingWorkspace.ts
+++ b/web/components/reading/workspace/useReadingWorkspace.ts
@@ -24,12 +24,10 @@ import { setReadingWorkspace } from "@/lib/reading-turn-state";
import { READING_WORKSPACE_MODE } from "@/lib/workspace-mode";
import {
activateReadingMaterial,
- deleteReadingConversation,
generateMasteryPathFromReading,
getReadingWorkspace,
listReadingConversations,
organizeReadingNotes,
- renameReadingConversation,
removeReadingWorkspaceMaterial,
updateReadingWorkspace,
type OrganizedReadingNotes,
@@ -65,7 +63,6 @@ export function useReadingWorkspace(
configureSession,
loadSession,
newSession,
- cancelStreamingTurn,
} = useChatStateAdapter();
const [workspace, setWorkspace] = useState<ReadingWorkspace | null>(null);
@@ -456,46 +453,6 @@ export function useReadingWorkspace(
.catch(() => {});
}, [sessionIdParam, state.sessionId, workspaceId]);
- const renameConversation = useCallback(
- async (sessionId: string, title: string) => {
- await renameReadingConversation(workspaceId, sessionId, title);
- setConversations(await listReadingConversations(workspaceId));
- },
- [workspaceId],
- );
-
- // Mirrors /chat's delete: drop the row, and if it was the conversation on
- // screen, fall back to a fresh draft rather than leaving the reader looking
- // at a transcript that no longer exists.
- const deleteConversation = useCallback(
- async (sessionId: string) => {
- await deleteReadingConversation(workspaceId, sessionId);
- setConversations(await listReadingConversations(workspaceId));
- if (sessionId === sessionIdParam) {
- cancelStreamingTurn();
- newSession({ ...sessionConfiguration, capability: null });
- router.push(readingCollectionRoute(workspaceId));
- }
- },
- [
- cancelStreamingTurn,
- newSession,
- router,
- sessionConfiguration,
- sessionIdParam,
- workspaceId,
- ],
- );
-
- const openConversation = useCallback(
- async (sessionId: string) => {
- router.push(readingSessionRoute(workspaceId, sessionId));
- await loadSession(sessionId);
- configureSession(sessionConfiguration, sessionId);
- },
- [configureSession, loadSession, router, sessionConfiguration, workspaceId],
- );
-
const organizeNotes = useCallback(async () => {
if (!workspace) return;
try {
@@ -573,9 +530,6 @@ export function useReadingWorkspace(
switchMaterial,
removeMaterial,
newConversation,
- openConversation,
- renameConversation,
- deleteConversation,
organizeNotes,
buildMasteryPath,
renameWorkspace,
diff --git a/web/components/sidebar/SessionAvatar.tsx b/web/components/sidebar/SessionAvatar.tsx
index 3c766f814..387f8a89c 100644
--- a/web/components/sidebar/SessionAvatar.tsx
+++ b/web/components/sidebar/SessionAvatar.tsx
@@ -36,8 +36,19 @@ const RING_RATIO = 0.58;
* "working slowly", it is *not working* — a static mark says that outright,
* and costs no rAF in a sidebar that can hold twenty of them.
*/
-function SettledMark({ size, mark }: { size: number; mark: SessionMark }) {
+function SettledMark({
+ size,
+ mark,
+ kind,
+}: {
+ size: number;
+ mark: SessionMark;
+ kind: SessionKind;
+}) {
const filled = mark === "unread" || mark === "failed";
+ const shape = `transition-[fill] duration-300 ease-out ${
+ filled ? "fill-current" : "fill-transparent"
+ }`;
// Ink rides on `currentColor` and alpha on `opacity-*` rather than a colour
// modifier. `stroke-muted-foreground/45` does work now that the theme colours
// go through `color-mix` (see tailwind.config.js), but it would need one class
@@ -56,16 +67,29 @@ function SettledMark({ size, mark }: { size: number; mark: SessionMark }) {
: "text-[var(--muted-foreground)] opacity-45 group-hover/session:opacity-75"
}`}
>
- <circle
- cx="6"
- cy="6"
- r="5.1"
- stroke="currentColor"
- strokeWidth="1.25"
- className={`transition-[fill] duration-300 ease-out ${
- filled ? "fill-current" : "fill-transparent"
- }`}
- />
+ {kind === "reading" ? (
+ // A page: the ring stood on end with its corners let out. Same box,
+ // stroke and ink, so it reads as the same mark in another key.
+ <rect
+ x="1.9"
+ y="0.9"
+ width="8.2"
+ height="10.2"
+ rx="2.4"
+ stroke="currentColor"
+ strokeWidth="1.25"
+ className={shape}
+ />
+ ) : (
+ <circle
+ cx="6"
+ cy="6"
+ r="5.1"
+ stroke="currentColor"
+ strokeWidth="1.25"
+ className={shape}
+ />
+ )}
</svg>
);
}
@@ -111,9 +135,28 @@ export function deriveSessionMark(
return "idle";
}
+/**
+ * Which surface a session belongs to, as far as the resting mark cares.
+ *
+ * Reading conversations sit in the same sidebar list as every other chat but
+ * open beside their material, so they rest as a page rather than a ring. Only
+ * the idle shape differs: running, unread and failed still say the same thing
+ * in the same colour, because state is what the column is for.
+ */
+export type SessionKind = "chat" | "reading";
+
+export function sessionKindOf(session: {
+ preferences?: { workspace_mode?: unknown } | null;
+}): SessionKind {
+ return session.preferences?.workspace_mode === "immersive_reading"
+ ? "reading"
+ : "chat";
+}
+
interface SessionAvatarProps {
sessionId: string;
mark?: SessionMark;
+ kind?: SessionKind;
size?: number;
className?: string;
}
@@ -136,6 +179,7 @@ interface SessionAvatarProps {
export function SessionAvatar({
sessionId: _sessionId,
mark = "idle",
+ kind = "chat",
size = 12,
className = "",
}: SessionAvatarProps) {
@@ -165,7 +209,7 @@ export function SessionAvatar({
running ? "scale-[1.55] opacity-0" : "scale-100 opacity-100"
}`}
>
- <SettledMark size={ring} mark={mark} />
+ <SettledMark size={ring} mark={mark} kind={kind} />
</span>
</span>
);
diff --git a/web/components/sidebar/WorkspaceSidebar.tsx b/web/components/sidebar/WorkspaceSidebar.tsx
index 8d7b4c2b4..77ef8decc 100644
--- a/web/components/sidebar/WorkspaceSidebar.tsx
+++ b/web/components/sidebar/WorkspaceSidebar.tsx
@@ -30,7 +30,8 @@ import {
fetchMasteryTopicIndex,
type MasteryTopicLabel,
} from "@/lib/learning-api";
-import { sessionRoute } from "@/lib/mastery-session";
+import { readingWorkspaceIdOf, sessionRoute } from "@/lib/mastery-session";
+import { readingCollectionRoute } from "@/lib/learning-routes";
import { subscribeSessionChanges } from "@/lib/session-events";
export default function WorkspaceSidebar() {
@@ -183,14 +184,23 @@ export default function WorkspaceSidebar() {
const handleDeleteSession = useCallback(
async (sessionId: string) => {
if (!window.confirm(t("Permanently delete this chat and its tutor threads? This cannot be undone."))) return;
- await deleteSession(sessionId, sessionWorkspaceId(sessions.find(item => item.session_id === sessionId)));
+ const deleted = sessions.find(item => item.session_id === sessionId);
+ await deleteSession(sessionId, sessionWorkspaceId(deleted));
setSessions((prev) =>
prev.filter((session) => session.session_id !== sessionId),
);
if (selectedSessionId === sessionId) {
cancelStreamingTurn();
newSession({ workspaceId: null });
- navigateTask("/chat", router.push);
+ // A reading conversation was open beside its material; deleting it
+ // should leave the reader on that material, not throw them to /chat.
+ const readingId = deleted ? readingWorkspaceIdOf(deleted) : "";
+ navigateTask(
+ readingId
+ ? readingCollectionRoute(readingId, sessionWorkspaceId(deleted))
+ : "/chat",
+ router.push,
+ );
}
},
[cancelStreamingTurn, newSession, router, selectedSessionId, t, sessions],
diff --git a/web/lib/learning-routes.ts b/web/lib/learning-routes.ts
index 67d08c03f..98b775ca3 100644
--- a/web/lib/learning-routes.ts
+++ b/web/lib/learning-routes.ts
@@ -31,6 +31,10 @@ export function masterySessionRoute(pathId: string, sessionId: string, workspace
export function readingCollectionRoute(workspaceId: string, contentWorkspaceId = activeWorkspaceId()): string {
return inWorkspace(`${READING_HOME}/${segment(workspaceId)}`, contentWorkspaceId)
}
+/** A collection seen as a folder: its files, its conversations, and the way into reading. */
+export function readingFolderRoute(workspaceId: string, contentWorkspaceId = activeWorkspaceId()): string {
+ return inWorkspace(`${READING_HOME}/folders/${segment(workspaceId)}`, contentWorkspaceId)
+}
export function readingSessionRoute(workspaceId: string, sessionId: string, contentWorkspaceId = activeWorkspaceId()): string {
return inWorkspace(`${readingCollectionRoute(workspaceId, "")}/sessions/${segment(sessionId)}`, contentWorkspaceId)
}
diff --git a/web/lib/reading-workspace-api.ts b/web/lib/reading-workspace-api.ts
index 66f5cf0c7..1249e4641 100644
--- a/web/lib/reading-workspace-api.ts
+++ b/web/lib/reading-workspace-api.ts
@@ -81,6 +81,8 @@ export interface ReadingWorkspace extends LearningOrigin {
workspace_id: string;
title: string;
description: string;
+ /** Folder tint: a palette key, or "" for the neutral default. */
+ color?: string;
active_material_id: string | null;
created_at: number;
updated_at: number;
@@ -212,24 +214,33 @@ export async function getReadingWorkspace(workspaceId: string): Promise<{
return json(`/workspaces/${workspaceId}`);
}
-export async function createReadingWorkspace(payload: {
- title: string;
- description?: string;
- material_ids?: string[];
-}): Promise<ReadingWorkspace> {
- const result = await json<{ workspace: ReadingWorkspace }>("/workspaces", {
- method: "POST",
- body: JSON.stringify(payload),
- });
+/**
+ * `contentWorkspaceId` is where the collection — its files and every
+ * conversation about them — is stored; it defaults to the page's workspace.
+ */
+export async function createReadingWorkspace(
+ payload: {
+ title: string;
+ description?: string;
+ color?: string;
+ material_ids?: string[];
+ },
+ contentWorkspaceId = activeWorkspaceId(),
+): Promise<ReadingWorkspace> {
+ const result = await json<{ workspace: ReadingWorkspace }>(
+ scopedUrl("/workspaces", contentWorkspaceId),
+ { method: "POST", body: JSON.stringify(payload) },
+ );
return result.workspace;
}
export async function updateReadingWorkspace(
workspaceId: string,
- patch: { title?: string; description?: string },
+ patch: { title?: string; description?: string; color?: string },
+ contentWorkspaceId = activeWorkspaceId(),
): Promise<ReadingWorkspace> {
const result = await json<{ workspace: ReadingWorkspace }>(
- `/workspaces/${workspaceId}`,
+ scopedUrl(`/workspaces/${workspaceId}`, contentWorkspaceId),
{ method: "PATCH", body: JSON.stringify(patch) },
);
return result.workspace;
@@ -424,28 +435,6 @@ export async function listReadingConversations(
);
}
-export async function renameReadingConversation(
- workspaceId: string,
- sessionId: string,
- title: string,
-): Promise<ReadingConversation> {
- return (
- await json<{ session: ReadingConversation }>(
- `/workspaces/${workspaceId}/sessions/${sessionId}`,
- { method: "PATCH", body: JSON.stringify({ title }) },
- )
- ).session;
-}
-
-export async function deleteReadingConversation(
- workspaceId: string,
- sessionId: string,
-): Promise<void> {
- await json(`/workspaces/${workspaceId}/sessions/${sessionId}`, {
- method: "DELETE",
- });
-}
-
export async function linkReadingConversation(
workspaceId: string,
sessionId: string,
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index ae4086792..36c1b8ba2 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -5162,5 +5162,42 @@
"Search materials and contents": "Search materials and contents",
"No matching materials or contents.": "No matching materials or contents.",
"Fullscreen learning": "Fullscreen learning",
- "Exit learning mode": "Exit learning mode"
+ "Exit learning mode": "Exit learning mode",
+ "Working on it…": "Working on it…",
+ "Ask a follow-up": "Ask a follow-up",
+ "Reading tools": "Reading tools",
+ "On the quoted passage": "On the quoted passage",
+ "On the page in view": "On the page in view",
+ "Read this page aloud": "Read this page aloud",
+ "Remove quoted passage": "Remove quoted passage",
+ "Ask anything about {{title}}, or select a passage in the document to explain, translate or discuss it.": "Ask anything about {{title}}, or select a passage in the document to explain, translate or discuss it.",
+ "Ask": "Ask",
+ "Explain": "Explain",
+ "Translate": "Translate",
+ "Follow the assistant": "Follow the assistant",
+ "Collection": "Collection",
+ "Add papers, chapters, web pages or videos to read them together.": "Add papers, chapters, web pages or videos to read them together.",
+ "Amber": "Amber",
+ "Back to folder": "Back to folder",
+ "Conversations you have while reading this folder appear here.": "Conversations you have while reading this folder appear here.",
+ "Could not open this collection.": "Could not open this collection.",
+ "Could not prepare this file": "Could not prepare this file",
+ "Could not save.": "Could not save.",
+ "Edit collection": "Edit collection",
+ "Empty": "Empty",
+ "New collection here": "New collection here",
+ "Open in reader": "Open in reader",
+ "Orange": "Orange",
+ "Rename or recolor": "Rename or recolor",
+ "Rose": "Rose",
+ "Slate": "Slate",
+ "Stored in {{workspace}}": "Stored in {{workspace}}",
+ "Teal": "Teal",
+ "This folder is empty": "This folder is empty",
+ "Untitled collection": "Untitled collection",
+ "Violet": "Violet",
+ "Workspace {{name}}": "Workspace {{name}}",
+ "The collection's files and reading conversations are kept in this workspace.": "The collection's files and reading conversations are kept in this workspace.",
+ "{{count}} files_one": "{{count}} file",
+ "{{count}} files_other": "{{count}} files"
}
diff --git a/web/locales/fr/app.json b/web/locales/fr/app.json
index 94590321f..dbf216eb4 100644
--- a/web/locales/fr/app.json
+++ b/web/locales/fr/app.json
@@ -4402,5 +4402,44 @@
"Search materials and contents": "Rechercher dans les supports et leur contenu",
"No matching materials or contents.": "Aucun support ni contenu correspondant.",
"Fullscreen learning": "Apprentissage en plein écran",
- "Exit learning mode": "Quitter le mode apprentissage"
+ "Exit learning mode": "Quitter le mode apprentissage",
+ "Working on it…": "En cours…",
+ "Ask a follow-up": "Poser une question de suivi",
+ "Reading tools": "Outils de lecture",
+ "On the quoted passage": "Sur le passage cité",
+ "On the page in view": "Sur la page affichée",
+ "Read this page aloud": "Lire cette page à voix haute",
+ "Remove quoted passage": "Retirer le passage cité",
+ "Ask anything about {{title}}, or select a passage in the document to explain, translate or discuss it.": "Posez n’importe quelle question sur {{title}}, ou sélectionnez un passage du document pour l’expliquer, le traduire ou en discuter.",
+ "Ask": "Demander",
+ "Explain": "Expliquer",
+ "Translate": "Traduire",
+ "Follow the assistant": "Suivre l’assistant",
+ "Collection": "Collection",
+ "Conversation": "Conversation",
+ "Add papers, chapters, web pages or videos to read them together.": "Ajoutez des articles, chapitres, pages web ou vidéos pour les lire ensemble.",
+ "Amber": "Ambre",
+ "Back to folder": "Retour au dossier",
+ "Conversations you have while reading this folder appear here.": "Les conversations tenues en lisant ce dossier apparaîtront ici.",
+ "Could not open this collection.": "Impossible d’ouvrir cette collection.",
+ "Could not prepare this file": "Impossible de préparer ce fichier",
+ "Could not save.": "Enregistrement impossible.",
+ "Edit collection": "Modifier la collection",
+ "Empty": "Vide",
+ "New collection here": "Nouvelle collection ici",
+ "Open in reader": "Ouvrir dans le lecteur",
+ "Orange": "Orange",
+ "Rename or recolor": "Renommer ou changer la couleur",
+ "Rose": "Rose",
+ "Slate": "Ardoise",
+ "Stored in {{workspace}}": "Enregistrée dans {{workspace}}",
+ "Teal": "Sarcelle",
+ "This folder is empty": "Ce dossier est vide",
+ "Untitled collection": "Collection sans titre",
+ "Violet": "Violet",
+ "Workspace {{name}}": "Espace de travail {{name}}",
+ "The collection's files and reading conversations are kept in this workspace.": "Les fichiers de la collection et ses conversations de lecture sont conservés dans cet espace de travail.",
+ "{{count}} files_one": "{{count}} fichier",
+ "{{count}} files_other": "{{count}} fichiers",
+ "Save new content to": "Enregistrer le nouveau contenu dans"
}
diff --git a/web/locales/uk/app.json b/web/locales/uk/app.json
index 4f5301030..4666eec6c 100644
--- a/web/locales/uk/app.json
+++ b/web/locales/uk/app.json
@@ -5176,5 +5176,44 @@
"Search materials and contents": "Пошук матеріалів і контенту",
"No matching materials or contents.": "Немає відповідних матеріалів чи вмісту.",
"Fullscreen learning": "Повноекранне навчання",
- "Exit learning mode": "Вийти з режиму навчання"
+ "Exit learning mode": "Вийти з режиму навчання",
+ "Working on it…": "Працюю над цим…",
+ "Ask a follow-up": "Поставити уточнювальне запитання",
+ "Reading tools": "Інструменти читання",
+ "On the quoted passage": "Для цитованого уривка",
+ "On the page in view": "Для сторінки на екрані",
+ "Read this page aloud": "Прочитати цю сторінку вголос",
+ "Remove quoted passage": "Прибрати цитований уривок",
+ "Ask anything about {{title}}, or select a passage in the document to explain, translate or discuss it.": "Запитайте будь-що про {{title}} або виділіть уривок у документі, щоб пояснити, перекласти чи обговорити його.",
+ "Ask": "Запитати",
+ "Explain": "Пояснити",
+ "Translate": "Перекласти",
+ "Follow the assistant": "Стежити за асистентом",
+ "Collection": "Колекція",
+ "Add papers, chapters, web pages or videos to read them together.": "Додайте статті, розділи, вебсторінки чи відео, щоб читати їх разом.",
+ "Amber": "Бурштиновий",
+ "Back to folder": "Назад до теки",
+ "Conversations you have while reading this folder appear here.": "Розмови під час читання цієї теки з’являться тут.",
+ "Could not open this collection.": "Не вдалося відкрити цю колекцію.",
+ "Could not prepare this file": "Не вдалося підготувати цей файл",
+ "Could not save.": "Не вдалося зберегти.",
+ "Edit collection": "Редагувати колекцію",
+ "Empty": "Порожньо",
+ "New collection here": "Нова колекція тут",
+ "Open in reader": "Відкрити в читачі",
+ "Orange": "Помаранчевий",
+ "Rename or recolor": "Перейменувати або змінити колір",
+ "Rose": "Рожевий",
+ "Slate": "Сланцевий",
+ "Stored in {{workspace}}": "Зберігається в «{{workspace}}»",
+ "Teal": "Бірюзовий",
+ "This folder is empty": "Ця тека порожня",
+ "Untitled collection": "Колекція без назви",
+ "Violet": "Фіолетовий",
+ "Workspace {{name}}": "Робочий простір {{name}}",
+ "The collection's files and reading conversations are kept in this workspace.": "Файли колекції та розмови під час читання зберігаються в цьому робочому просторі.",
+ "{{count}} files_one": "{{count}} файл",
+ "{{count}} files_few": "{{count}} файли",
+ "{{count}} files_many": "{{count}} файлів",
+ "{{count}} files_other": "{{count}} файлу"
}
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index e99034df8..60ce317f2 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -5162,5 +5162,42 @@
"Search materials and contents": "搜索资料和目录",
"No matching materials or contents.": "没有匹配的资料或目录。",
"Fullscreen learning": "全屏学习",
- "Exit learning mode": "退出学习模式"
+ "Exit learning mode": "退出学习模式",
+ "Working on it…": "正在处理…",
+ "Ask a follow-up": "继续追问",
+ "Reading tools": "阅读工具",
+ "On the quoted passage": "作用于引用的段落",
+ "On the page in view": "作用于当前页",
+ "Read this page aloud": "朗读本页",
+ "Remove quoted passage": "移除引用的段落",
+ "Ask anything about {{title}}, or select a passage in the document to explain, translate or discuss it.": "关于《{{title}}》随便问,或在文档里选中一段文字来解释、翻译或讨论。",
+ "Ask": "提问",
+ "Explain": "解释",
+ "Translate": "翻译",
+ "Follow the assistant": "跟随助手跳转",
+ "Collection": "资料组",
+ "Add papers, chapters, web pages or videos to read them together.": "在这里放入论文、章节、网页或视频,一起阅读。",
+ "Amber": "琥珀",
+ "Back to folder": "返回资料组",
+ "Conversations you have while reading this folder appear here.": "阅读这个资料组时的对话会出现在这里。",
+ "Could not open this collection.": "无法打开这个资料组。",
+ "Could not prepare this file": "这个文件处理失败",
+ "Could not save.": "保存失败。",
+ "Edit collection": "编辑资料组",
+ "Empty": "空",
+ "New collection here": "在此新建资料组",
+ "Open in reader": "在阅读器中打开",
+ "Orange": "橙",
+ "Rename or recolor": "重命名或换颜色",
+ "Rose": "玫红",
+ "Slate": "石板灰",
+ "Stored in {{workspace}}": "保存在「{{workspace}}」",
+ "Teal": "青绿",
+ "This folder is empty": "这个资料组还是空的",
+ "Untitled collection": "未命名资料组",
+ "Violet": "紫罗兰",
+ "Workspace {{name}}": "工作区 {{name}}",
+ "The collection's files and reading conversations are kept in this workspace.": "资料组的原始文件和阅读对话都保存在这个工作区下。",
+ "{{count}} files_one": "{{count}} 个文件",
+ "{{count}} files_other": "{{count}} 个文件"
}
diff --git a/web/tests/reading-learning-mode.spec.tsx b/web/tests/reading-learning-mode.spec.tsx
index 80aacdfa8..8761cfd68 100644
--- a/web/tests/reading-learning-mode.spec.tsx
+++ b/web/tests/reading-learning-mode.spec.tsx
@@ -51,9 +51,6 @@ vi.mock('@/components/reading/workspace/useReadingWorkspace', () => ({
switchMaterial: vi.fn(),
removeMaterial: vi.fn(),
newConversation: vi.fn(),
- openConversation: vi.fn(),
- renameConversation: vi.fn(),
- deleteConversation: vi.fn(),
organizeNotes: vi.fn(),
buildMasteryPath: vi.fn(),
renameWorkspace: vi.fn(),
@@ -64,6 +61,14 @@ vi.mock('@/components/reading/ReaderPane', () => ({
ReaderPane: () => null,
READER_ASK_EVENT: 'dt:reader-ask',
}))
+// The shared reading-actions catalog fetches on mount; this spec is about the
+// shell's panels, so it stands in as a pass-through (no actions, no header
+// read-aloud button).
+vi.mock('@/components/reading/ReadingActionsProvider', () => ({
+ ReadingActionsProvider: ({ children }: { children: React.ReactNode }) => (
+ <>{children}</>
+ ),
+}))
vi.mock('@/components/reading/workspace/SourceNavigator', () => ({
SourceNavigator: ({ open }: { open: boolean }) => (
<div data-testid="reading-navigator" data-open={String(open)}>
@@ -90,7 +95,6 @@ vi.mock('@/components/reading/workspace/WorkspaceChrome', () => ({
}))
vi.mock('@/components/reading/workspace/dialogs', () => ({
ConversationLinkDialog: () => null,
- ConversationMenu: () => null,
NotebookCaptureDialog: () => null,
OrganizedNotesDialog: () => null,
WorkspaceConfirmDialog: () => null,
@@ -137,7 +141,8 @@ describe('reading fullscreen learning', () => {
const root = screen.getByRole('main')
expect(root).toHaveAttribute('data-reading-workspace')
expect(root).not.toHaveAttribute('data-learning')
- expect(screen.getByTestId('reading-navigator')).toHaveAttribute('data-open', 'true')
+ // The outline starts closed; learning mode opens it and hands it back.
+ expect(screen.getByTestId('reading-navigator')).toHaveAttribute('data-open', 'false')
expect(screen.getByTestId('reading-companion')).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Fullscreen learning' }))
@@ -148,7 +153,7 @@ describe('reading fullscreen learning', () => {
await user.click(screen.getByRole('button', { name: 'Exit learning mode' }))
expect(root).not.toHaveAttribute('data-learning')
- expect(screen.getByTestId('reading-navigator')).toHaveAttribute('data-open', 'true')
+ expect(screen.getByTestId('reading-navigator')).toHaveAttribute('data-open', 'false')
expect(screen.getByTestId('reading-companion')).toBeInTheDocument()
expect(sidebar.inert).not.toBe(true)
expect(sidebar.hasAttribute('inert')).toBe(false)
@@ -186,7 +191,7 @@ describe('reading fullscreen learning', () => {
expect(screen.getByTestId('reading-navigator')).toHaveAttribute('data-open', 'true')
await user.click(screen.getByRole('button', { name: 'Exit learning mode' }))
- expect(screen.getByTestId('reading-navigator')).toHaveAttribute('data-open', 'true')
+ expect(screen.getByTestId('reading-navigator')).toHaveAttribute('data-open', 'false')
})
it("restores the same workspace's saved learning mode and entry panels", async () => {
diff --git a/web/tests/reading-toolbar-selection.spec.tsx b/web/tests/reading-toolbar-selection.spec.tsx
index 3eccb77aa..e40bc068f 100644
--- a/web/tests/reading-toolbar-selection.spec.tsx
+++ b/web/tests/reading-toolbar-selection.spec.tsx
@@ -68,6 +68,12 @@ vi.mock("@/components/reading/PdfDocumentView", () => ({
},
}));
+// The workspace provider asks who the learner is; an adult reader is the
+// case under test, so there is no learner policy to find.
+vi.mock("@/lib/auth", () => ({
+ fetchAuthStatus: vi.fn(async () => null),
+}));
+
vi.mock("@/components/reading/EpubDocumentView", () => ({
EpubDocumentView: () => null,
}));
@@ -110,6 +116,9 @@ vi.mock("@/context/ReadingContext", () => ({
}));
const { ReaderPane } = await import("@/components/reading/ReaderPane");
+const { ReadingActionsProvider } = await import(
+ "@/components/reading/ReadingActionsProvider"
+);
describe("reading toolbar with a live selection", () => {
beforeEach(() => {
@@ -158,7 +167,7 @@ describe("reading toolbar with a live selection", () => {
expect(body.locator).toBe(4);
});
- it("keeps secondary mobile tools behind the reading more menu", async () => {
+ it("keeps secondary reading tools behind the more menu", async () => {
const user = userEvent.setup();
render(
<ReaderPane
@@ -168,7 +177,12 @@ describe("reading toolbar with a live selection", () => {
);
const more = await screen.findByRole("button", { name: "More" });
- expect(more.className).toContain("md:hidden");
+ // At every width now, not only on phones: history, auto-jump and export
+ // are settings and once-a-session actions, not toolbar buttons.
+ expect(more.className).not.toContain("md:hidden");
+ expect(
+ screen.queryByRole("button", { name: /Export annotated file/ }),
+ ).not.toBeInTheDocument();
expect(more).toHaveAttribute("aria-haspopup", "menu");
expect(
screen.getByRole("button", { name: /Bookmark this page/ }),
@@ -191,4 +205,55 @@ describe("reading toolbar with a live selection", () => {
expect(screen.queryByRole("menu", { name: "More" })).not.toBeInTheDocument();
expect(more).toHaveFocus();
});
+
+ /**
+ * Inside a workspace the same action is on the selection popover, and the
+ * strip of chips above the page is gone: one place to start it, and the
+ * answer goes to the companion column rather than a band over the page.
+ */
+ it("runs selection actions from the popover inside a workspace", async () => {
+ const user = userEvent.setup();
+ render(
+ <ReadingActionsProvider materialId="m1" locator={1}>
+ <ReaderPane onClose={() => undefined} />
+ </ReadingActionsProvider>,
+ );
+
+ 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 popover = await screen.findByRole("dialog", {
+ name: "Annotate selection",
+ });
+ const translate = await within(popover).findByRole("button", {
+ name: "Translate to Chinese",
+ });
+ expect(translate).toHaveTextContent("Translate");
+ expect(
+ within(popover).getByRole("button", { name: "Ask about this" }),
+ ).toBeVisible();
+ await user.click(translate);
+
+ await waitFor(() => expect(api.runReadingExtension).toHaveBeenCalled());
+ const [, extensionId, actionId, body] = api.runReadingExtension.mock.calls[0];
+ expect(extensionId).toBe("translation");
+ expect(actionId).toBe("translate_zh");
+ expect(body.selection).toBe("the slope of the line");
+ expect(body.locator).toBe(4);
+ // The popover closes once the action is on its way.
+ expect(
+ screen.queryByRole("dialog", { name: "Annotate selection" }),
+ ).not.toBeInTheDocument();
+ // …and the strip that used to carry the same button is not rendered.
+ expect(
+ screen.queryAllByRole("button", { name: "Translate to Chinese" }),
+ ).toHaveLength(0);
+ });
});