From 10f93f818882a854a6f75aa5d74a74bb7d37d500 Mon Sep 17 00:00:00 2001 From: shaitrish37 <244331886+shaitrish37@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:30:47 +0600 Subject: [PATCH] board: Voice on the board (speak, and the words go on the slide) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A Voice text tool on the Smart Dock (a mic with a T, Prepare and Teach): tap or drag on the page to place a voice box and talk. Interim words show live and lighter, final words in the pen colour, wrapped inside the box and kept on the page (the box moves in, then shrinks its text). Spoken punctuation in English and Bangla, a ~2 s pause starts a new line. Tap the box, Esc or Done: one normal text item, one undo step per box. In Teach, hold the dock button for push-to-talk (the pen stays the tool); Space or a clicker's B / . toggles listening. On the box: EN / বাং, Text <-> Ask AI (the words become a chat prompt with the page or selection attached), typed <-> hand-written (the Solve this synthesiser), the privacy line. - voice/board.ts, VoiceBoard.tsx, voice-board.css, wrap.ts (line breaking with the board font; unit-tested in test/voice-board.test.ts) - dictation.ts: custom targets can give the text before the caret; the live-text bubble can be turned off per session - engine: add_text_box (world box, kept on the page, one commit) + test - live ops and MCP tools start_voice_text / stop_voice_text (board-only); the board wraps an agent's add_text at its w - settings: default mode, tap or hold to talk, hand-written default, pause length, students may ask the AI by voice - docs: ai-agents.md (Voice on the board, tools, protocol), ui-config.md, the live-board skill --- AGENTS.md | 2 +- apps/board/scripts/gen-icons.mjs | 24 + apps/board/src/App.tsx | 3 + apps/board/src/components/Dock.tsx | 15 +- apps/board/src/controller.ts | 6 +- apps/board/src/icons.generated.ts | 4 +- apps/board/src/live.ts | 13 + apps/board/src/modes.ts | 11 +- apps/board/src/settings/defs/voiceBoard.ts | 78 +++ apps/board/src/state.ts | 2 + apps/board/src/voice/VoiceBoard.tsx | 390 +++++++++++++++ apps/board/src/voice/VoiceLayer.tsx | 4 +- apps/board/src/voice/board.ts | 530 +++++++++++++++++++++ apps/board/src/voice/dictation.ts | 14 +- apps/board/src/voice/voice-board.css | 126 +++++ apps/board/src/voice/wrap.ts | 135 ++++++ apps/board/test/voice-board.test.ts | 50 ++ crates/rupok-cli/src/mcp.rs | 2 + crates/rupok-cli/src/mcp_live.rs | 83 ++++ crates/rupok-live/src/apply.rs | 3 + crates/rupok-live/src/op.rs | 36 ++ crates/rupok-wasm/src/engine.rs | 93 ++++ crates/rupok-wasm/src/lib.rs | 16 + docs/ai-agents.md | 57 ++- docs/ui-config.md | 5 +- skills/AGENTS.md | 2 + skills/rupok-live-board/SKILL.md | 3 +- 27 files changed, 1682 insertions(+), 25 deletions(-) create mode 100644 apps/board/src/settings/defs/voiceBoard.ts create mode 100644 apps/board/src/voice/VoiceBoard.tsx create mode 100644 apps/board/src/voice/board.ts create mode 100644 apps/board/src/voice/voice-board.css create mode 100644 apps/board/src/voice/wrap.ts create mode 100644 apps/board/test/voice-board.test.ts diff --git a/AGENTS.md b/AGENTS.md index 7f6363c..ec2d681 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -21,7 +21,7 @@ a Tauri 2 shell (planned). Status: Phase 0, pre-alpha. See | `crates/rupok-wasm` | Board engine and wasm-bindgen API | `engine.rs` (`Engine`: tools, gestures, selection), `lib.rs` (`Board` JS API), `replay.rs`, `shapes.rs` | | `crates/rupok-cli` | `rupok` binary: CLI and MCP server | `cli.rs` (clap), `ops.rs` (shared operations), `mcp.rs` + `tools.rs` (15 MCP tools), `workspace.rs` (path sandbox), `spec.rs`, `live/` (`LiveHub`: loopback WebSocket, pairing, Loro mirror) + `mcp_live.rs` (live tools; docs/ai-agents.md), `chat/` (`rupok agent`: ACP client relaying the in-app chat) + `mcp_http.rs` (MCP over loopback HTTP for it) | | `bench/` | Performance harness and budgets | `cargo run -p rupok-bench --release [-- --check]` | -| `apps/board` | SolidJS board UI (Vite) | `controller.ts`, `objects.ts` (Smart Object host), `media/` + `components/Media*.tsx` (YouTube, video, audio, web embeds), `pdf.ts`, `storage.ts`, `live.ts` + `snapshot.ts` + `components/LivePanel.tsx` (Connect AI), `chat.ts` + `components/ChatPanel.tsx` + `markdown.ts` (AI chat), `components/` | +| `apps/board` | SolidJS board UI (Vite) | `controller.ts`, `objects.ts` (Smart Object host), `media/` + `components/Media*.tsx` (YouTube, video, audio, web embeds), `pdf.ts`, `storage.ts`, `live.ts` + `snapshot.ts` + `components/LivePanel.tsx` (Connect AI), `chat.ts` + `components/ChatPanel.tsx` + `markdown.ts` (AI chat), `voice/` (dictation; `board.ts` + `VoiceBoard.tsx`: Voice on the board), `components/` | | `packages/object-sdk` | In-object SDK, `window.rupok` (Apache-2.0) | `sdk.js` (ES2019 IIFE), `index.d.ts`, `test/` | | `spec/` | Normative specs (Apache-2.0) | `rupok-format.md`, `smart-object.md` | | `examples/objects/` | Validated example Smart Objects | checked by `crates/rupok-format/tests/examples.rs` | diff --git a/apps/board/scripts/gen-icons.mjs b/apps/board/scripts/gen-icons.mjs index 93bb9b4..771ae4f 100644 --- a/apps/board/scripts/gen-icons.mjs +++ b/apps/board/scripts/gen-icons.mjs @@ -93,6 +93,23 @@ function body(name) { return null; } +// Composed icons: a Solar icon made smaller in the top-left corner, with a +// mark drawn in the free bottom-right corner (same stroke as the variant). +// voiceText: the Voice text tool (src/voice/board.ts), a mic with a T. +const COMPOSE = { + voiceText: { base: "microphone", mark: "M14.5 15H21.5M18 15V21.5" }, +}; +const STROKED = new Set(["linear", "line-duotone", "broken"]); + +function compose({ base, mark }, v) { + const k = 0.74; + let b = body(`${base}-${v}`); + // Keep the stroke width the eye expects after scaling down. + if (STROKED.has(v)) b = b.replace(/stroke-width="1\.5"/g, `stroke-width="${(1.5 / k).toFixed(2)}"`); + const w = STROKED.has(v) ? 1.5 : 2; + return `${b}`; +} + const out = {}; const missing = []; for (const [logical, candidates] of Object.entries(MAP)) { @@ -103,6 +120,13 @@ for (const [logical, candidates] of Object.entries(MAP)) { } out[logical] = Object.fromEntries(VARIANTS.map((v) => [v, body(`${base}-${v}`)])); } +for (const [logical, spec] of Object.entries(COMPOSE)) { + if (!VARIANTS.every((v) => body(`${spec.base}-${v}`))) { + missing.push(logical); + continue; + } + out[logical] = Object.fromEntries(VARIANTS.map((v) => [v, compose(spec, v)])); +} if (missing.length) { console.error("missing icons:", missing.join(", ")); process.exit(1); diff --git a/apps/board/src/App.tsx b/apps/board/src/App.tsx index 0ffbfcd..e8c3025 100644 --- a/apps/board/src/App.tsx +++ b/apps/board/src/App.tsx @@ -20,6 +20,7 @@ import { registerSettingsOpener } from "./components/ToText"; import LivePanel from "./components/LivePanel"; import ChatPanel from "./components/ChatPanel"; import VoiceLayer from "./voice/VoiceLayer"; +import VoiceBoard from "./voice/VoiceBoard"; import { LibraryRoot } from "./components/Library"; import { UpgradeHost } from "./components/Billing"; import { openUpgrade, refreshBilling, takeBillingParams } from "./cloud/billing"; @@ -163,6 +164,8 @@ export default function App() {
+ {/* Voice text: speak, and the words go on the board (voice/board.ts). */} +
setObjectDialog(true)} onSettings={() => openSettings()} /> diff --git a/apps/board/src/components/Dock.tsx b/apps/board/src/components/Dock.tsx index 5cf22b3..e3c9236 100644 --- a/apps/board/src/components/Dock.tsx +++ b/apps/board/src/components/Dock.tsx @@ -37,6 +37,7 @@ import { MarkerOpacity, SizeControl, StylePicker } from "./InkOptions"; import { StampIcon, StampsPanel } from "./Stamps"; import { brushInfo, brushOf } from "../brushes"; import { celebrate, currentStamp } from "../stamps"; +import { dockClickConsumed, dockPress, dockRelease, pickVoiceTool, voiceListening } from "../voice/board"; const META = new Map(TOOLBAR_ITEMS.map((t) => [t.id, t])); const INK_TOOLS: Tool[] = ["pen", "highlighter", "rect", "ellipse", "line", "arrow", "shape"]; @@ -62,14 +63,14 @@ type Group = "ink" | "colors" | "create" | "point" | "context" | "history" | "na type Kind = "tool" | "colors" | "shapes" | "smartink" | "undo" | "redo" | "pager" | "replay" | "exit" | "context" | "more"; interface Entry { key: string; kind: Kind; group: Group; id?: ToolbarItem } const GROUP: Partial> = { - pen: "ink", highlighter: "ink", eraser: "ink", smartink: "create", text: "create", stamp: "create", + pen: "ink", highlighter: "ink", eraser: "ink", smartink: "create", text: "create", voice: "create", stamp: "create", lasso: "point", laser: "point", hand: "point", interact: "point", undo: "history", redo: "history", pager: "nav", replay: "nav", exit: "exit", }; /** On a phone, what moves into ⋯ first when the dock is too long for the * screen ("colors:N" keeps N recent colours). Pen, eraser, the pager and ⋯ * always stay; exit and undo go last (on the narrowest phones in Teach). */ -const PHONE_DROP = ["redo", "hand", "laser", "stamp", "colors:2", "lasso", "colors:1", "smartink", "interact", "replay", "text", "shapes", "highlighter", "colors:0", "exit", "undo"]; +const PHONE_DROP = ["redo", "hand", "laser", "voice", "stamp", "colors:2", "lasso", "colors:1", "smartink", "interact", "replay", "text", "shapes", "highlighter", "colors:0", "exit", "undo"]; /** Phone dock metrics (Dock.css): 44px cells with no gap; a 1px separator with 1.5px margins. */ const PHONE_CELL = 44, PHONE_SEP = 4; @@ -527,14 +528,18 @@ export default function Dock(props: { onSettings?: (section?: string) => void }) ref={btn} class="tool" data-tour={p.id === "pen" ? "pen" : undefined} - classList={{ on: on(), "has-options": options }} - title={tipOf(p.id, p.id === "stamp" ? " · tap again for all stamps" : options ? " · tap again for styles, colours and sizes" : "")} + classList={{ on: on(), "has-options": options, listening: p.id === "voice" && voiceListening() }} + title={tipOf(p.id, p.id === "stamp" ? " · tap again for all stamps" : p.id === "voice" ? " · tap the page and speak; hold to talk" : options ? " · tap again for styles, colours and sizes" : "")} aria-label={labelOf(p.id)} aria-pressed={on()} aria-haspopup={options ? "dialog" : undefined} - onPointerDown={options ? lp.onPointerDown : undefined} + onPointerDown={options ? lp.onPointerDown : p.id === "voice" ? dockPress : undefined} + onPointerUp={p.id === "voice" ? dockRelease : undefined} + onPointerCancel={p.id === "voice" ? dockRelease : undefined} onClick={() => { if (lp.consumed()) return; + // Voice text (voice/board.ts): a hold was push-to-talk, a tap picks the tool. + if (p.id === "voice") { if (!dockClickConsumed()) { setPop(null); pickVoiceTool(); } return; } if (options && on()) toggle(p.id as Pop["kind"], btn); else { setPop(null); diff --git a/apps/board/src/controller.ts b/apps/board/src/controller.ts index cb53acc..a105ad7 100644 --- a/apps/board/src/controller.ts +++ b/apps/board/src/controller.ts @@ -311,16 +311,16 @@ export class Controller { setTool(t: Tool) { // Student view: only panning and using Smart Objects. - if (isView() && t !== "interact") t = "hand"; + if (isView() && t !== "interact" && t !== "voice") t = "hand"; // Leaving "use objects": take keyboard focus back from any object iframe so // shortcuts and the clicker reach the board again. if (t !== "interact" && document.activeElement instanceof HTMLIFrameElement) document.activeElement.blur(); setTool(t); - if (t === "interact" || t === "text" || t === "stamp") { + if (t === "interact" || t === "text" || t === "stamp" || t === "voice") { // A just-placed object stays selected in "use objects" so it can be // resized right away; the text tool starts fresh. this.board.set_tool("lasso"); - if (t === "text" || t === "stamp") this.board.select_json("[]"); + if (t === "text" || t === "stamp" || t === "voice") this.board.select_json("[]"); } else { this.board.set_tool(t === "shape" ? shapeToolName() : t); } diff --git a/apps/board/src/icons.generated.ts b/apps/board/src/icons.generated.ts index fc2d631..d4cda40 100644 --- a/apps/board/src/icons.generated.ts +++ b/apps/board/src/icons.generated.ts @@ -1,5 +1,5 @@ // Generated by scripts/gen-icons.mjs from Solar icons (CC BY 4.0, 480 Design). // Do not edit by hand. export type IconVariant = "linear" | "line-duotone" | "broken" | "bold" | "bold-duotone" | "outline"; -export type IconName = "pen" | "highlighter" | "eraser" | "select" | "laser" | "text" | "rect" | "ellipse" | "line" | "arrow" | "hand" | "interact" | "undo" | "redo" | "save" | "open" | "pdf" | "image" | "object" | "replay" | "play" | "pause" | "fullscreen" | "settings" | "sun" | "moon" | "plus" | "trash" | "close" | "sidebar" | "zoomIn" | "zoomOut" | "download" | "palette" | "layers" | "monitor" | "keyboard" | "info" | "insert" | "more" | "duplicate" | "front" | "prev" | "next" | "eye" | "up" | "down" | "group" | "ungroup" | "merge" | "import" | "export" | "restart" | "exit" | "overlay" | "smartink" | "totext" | "grow" | "shrink" | "broom" | "pin" | "pages" | "video" | "audio" | "cube" | "globe" | "volume" | "mute" | "openLink" | "replace" | "camera3d" | "stamp" | "celebrate" | "heart"; -export const ICONS: Record> = {"pen":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"highlighter":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"eraser":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"select":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"laser":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"text":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"rect":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"ellipse":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"line":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"arrow":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"hand":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"interact":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"undo":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"redo":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"save":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"open":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"pdf":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"image":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"object":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"replay":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"play":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"pause":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"fullscreen":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"settings":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"sun":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"moon":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"plus":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"trash":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"close":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"sidebar":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"zoomIn":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"zoomOut":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"download":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"palette":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"layers":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"monitor":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"keyboard":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"info":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"insert":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"more":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"duplicate":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"front":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"prev":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"next":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"eye":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"up":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"down":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"group":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"ungroup":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"merge":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"import":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"export":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"restart":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"exit":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"overlay":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"smartink":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"totext":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"grow":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"shrink":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"broom":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"pin":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"pages":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"video":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"audio":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"cube":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"globe":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"volume":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"mute":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"openLink":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"replace":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"camera3d":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"stamp":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"celebrate":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"heart":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""}}; +export type IconName = "pen" | "highlighter" | "eraser" | "select" | "laser" | "text" | "rect" | "ellipse" | "line" | "arrow" | "hand" | "interact" | "undo" | "redo" | "save" | "open" | "pdf" | "image" | "object" | "replay" | "play" | "pause" | "fullscreen" | "settings" | "sun" | "moon" | "plus" | "trash" | "close" | "sidebar" | "zoomIn" | "zoomOut" | "download" | "palette" | "layers" | "monitor" | "keyboard" | "info" | "insert" | "more" | "duplicate" | "front" | "prev" | "next" | "eye" | "up" | "down" | "group" | "ungroup" | "merge" | "import" | "export" | "restart" | "exit" | "overlay" | "smartink" | "totext" | "grow" | "shrink" | "broom" | "pin" | "pages" | "video" | "audio" | "cube" | "globe" | "volume" | "mute" | "openLink" | "replace" | "camera3d" | "stamp" | "celebrate" | "heart" | "voiceText"; +export const ICONS: Record> = {"pen":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"highlighter":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"eraser":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"select":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"laser":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"text":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"rect":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"ellipse":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"line":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"arrow":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"hand":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"interact":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"undo":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"redo":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"save":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"open":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"pdf":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"image":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"object":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"replay":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"play":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"pause":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"fullscreen":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"settings":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"sun":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"moon":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"plus":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"trash":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"close":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"sidebar":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"zoomIn":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"zoomOut":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"download":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"palette":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"layers":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"monitor":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"keyboard":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"info":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"insert":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"more":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"duplicate":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"front":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"prev":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"next":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"eye":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"up":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"down":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"group":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"ungroup":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"merge":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"import":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"export":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"restart":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"exit":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"overlay":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"smartink":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"totext":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"grow":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"shrink":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"broom":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"pin":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"pages":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"video":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"audio":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"cube":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"globe":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"volume":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"mute":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"openLink":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"replace":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"camera3d":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"stamp":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"celebrate":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"heart":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""},"voiceText":{"linear":"","line-duotone":"","broken":"","bold":"","bold-duotone":"","outline":""}}; diff --git a/apps/board/src/live.ts b/apps/board/src/live.ts index 5ba5277..b90d401 100644 --- a/apps/board/src/live.ts +++ b/apps/board/src/live.ts @@ -101,9 +101,19 @@ const LABELS: Record = { set_page_design: "changed the page design", set_branding: "changed the branding", replace_items_with_text: "turned ink into text", step_object: "stepped a Smart Object", write_handwriting: "is writing on the board", add_media: "added media", add_model: "added a 3D model", + start_voice_text: "turned on voice text", stop_voice_text: "finished voice text", }; export const opLabel = (op: any) => LABELS[op?.op] ?? "is working"; +/** Break an agent's `add_text` lines at its box width `w`, as the board will + * show them (text items keep explicit line breaks; see voice/wrap.ts). */ +async function wrapForBoard(op: any): Promise { + const { boardMeasure, loadBoardFont, wrapText, WRAP_SLACK } = await import("./voice/wrap"); + const size = typeof op.size === "number" && op.size > 0 ? op.size : 32; + await loadBoardFont(size, op.text); + return { ...op, text: wrapText(op.text, op.w - WRAP_SLACK, boardMeasure(size)) }; +} + class OpError extends Error { constructor(message: string, public data?: any) { super(message); } } @@ -473,7 +483,10 @@ class LiveClient { if (op.op === "snapshot") result = await renderSnapshot(this.c, op, agent); else if (op.op === "point_at") result = this.pointAt(op); else if (op.op === "write_handwriting") result = (await import("./solve")).onWriteOp(op, agent); // preview or write (solve/) + else if (op.op === "start_voice_text" || op.op === "stop_voice_text") result = await (await import("./voice/board")).onVoiceOp(op); // the board's microphone else { + // `add_text` with a width: break the lines to fit it, measured with the board's font (voice/wrap.ts). + if (op.op === "add_text" && typeof op.w === "number" && op.w > 0 && typeof op.text === "string") op = await wrapForBoard(op); try { result = JSON.parse(this.c.board.live_apply(JSON.stringify(op), agent)); } catch (e) { diff --git a/apps/board/src/modes.ts b/apps/board/src/modes.ts index b9393bd..7034cb2 100644 --- a/apps/board/src/modes.ts +++ b/apps/board/src/modes.ts @@ -68,6 +68,7 @@ export const TOOLBAR_ITEMS: { id: ToolbarItem; icon: IconName; label: string; ke { id: "text", icon: "text", label: "Text", key: "T", kind: "tool" }, { id: "shape", icon: "rect", label: "Shapes and tables", key: "S", kind: "tool" }, { id: "stamp", icon: "stamp", label: "Stamps", key: "K", kind: "tool" }, + { id: "voice", icon: "voiceText", label: "Voice text", kind: "tool" }, { id: "rect", icon: "rect", label: "Rectangle", key: "R", kind: "tool" }, { id: "ellipse", icon: "ellipse", label: "Ellipse", key: "O", kind: "tool" }, { id: "line", icon: "line", label: "Line", key: "N", kind: "tool" }, @@ -108,7 +109,7 @@ export const CHROME_ITEMS: { id: ChromeKey; label: string }[] = [ export const ALLOWED_TOOLS: Record = { prepare: TOOLBAR_ITEMS.map((t) => t.id).filter((t) => t !== "exit"), teach: TOOLBAR_ITEMS.map((t) => t.id), - view: ["pager", "hand", "interact", "replay"], + view: ["pager", "hand", "interact", "replay", "voice"], }; /** Chrome each mode may show (the student view has no editing chrome). */ export const ALLOWED_CHROME: Record = { @@ -123,13 +124,13 @@ const chrome = (on: ChromeKey[]): Record => export const DEFAULT_MODES: ModesConfig = { prepare: { chrome: chrome(["switcher", "title", "pagesToggle", "history", "insert", "replay", "open", "theme", "fullscreen", "settings", "save", "ai", "overflow", "pages", "zoom", "stats", "colors", "sizes"]), - tools: ["pen", "highlighter", "eraser", "shape", "rect", "ellipse", "line", "arrow", "smartink", "text", "stamp", "lasso", "laser", "hand", "interact", "undo", "redo"], - dock: { position: "auto", orientation: "auto", minimized: false, pinned: ["shapes", "text", "stamp", "lasso"] }, + tools: ["pen", "highlighter", "eraser", "shape", "rect", "ellipse", "line", "arrow", "smartink", "text", "voice", "stamp", "lasso", "laser", "hand", "interact", "undo", "redo"], + dock: { position: "auto", orientation: "auto", minimized: false, pinned: ["shapes", "text", "voice", "stamp", "lasso"] }, }, teach: { chrome: chrome(["colors", "sizes"]), - tools: ["pen", "highlighter", "eraser", "shape", "text", "stamp", "lasso", "laser", "smartink", "undo", "pager", "exit"], - dock: { position: "auto", orientation: "auto", minimized: false, pinned: ["shapes", "text", "stamp", "lasso", "smartink", "pager", "exit"] }, + tools: ["pen", "highlighter", "eraser", "shape", "text", "voice", "stamp", "lasso", "laser", "smartink", "undo", "pager", "exit"], + dock: { position: "auto", orientation: "auto", minimized: false, pinned: ["shapes", "text", "voice", "stamp", "lasso", "smartink", "pager", "exit"] }, }, view: { chrome: chrome(["switcher", "title", "pagesToggle", "open", "theme", "fullscreen", "overflow", "pages", "zoom"]), diff --git a/apps/board/src/settings/defs/voiceBoard.ts b/apps/board/src/settings/defs/voiceBoard.ts new file mode 100644 index 0000000..8d38a87 --- /dev/null +++ b/apps/board/src/settings/defs/voiceBoard.ts @@ -0,0 +1,78 @@ +// Settings → General → Voice on the board (the dock's Voice text tool; +// src/voice/board.ts, VoiceBoard.tsx), and its keys under Keyboard. + +import { voiceBoardPrefs } from "../../voice/board"; +import { voicePrefs } from "../../voice/dictation"; +import { registerSettings } from "../registry"; + +const d = voiceBoardPrefs.defaults; +const GROUP = "Voice on the board"; +const on = () => voicePrefs.read().enabled; + +registerSettings([ + { + id: "general.voiceBoardMode", category: "general", group: GROUP, order: 320, type: "segmented", label: "A new voice box", + description: "Write what you say on the board, or send it to your AI assistant as a question. Switch on the box any time.", + keywords: ["voice text", "speech", "dictation", "ask AI", "prompt", "board", "ভয়েস", "বোর্ডে লিখুন"], + options: [ + { value: "text", label: "Text on the board" }, + { value: "ask", label: "Ask AI" }, + ], + get: () => voiceBoardPrefs.read().mode, + set: (v) => voiceBoardPrefs.write({ mode: v as typeof d.mode }), + default: d.mode, + enabled: on, + }, + { + id: "general.voiceBoardTalk", category: "general", group: GROUP, order: 321, type: "segmented", label: "Talking", + description: "Tap the page and talk until you finish (holding the dock button is push-to-talk too), or listen only while the dock button, the mic or Space is held.", + keywords: ["push to talk", "hold", "toggle", "walkie-talkie", "clicker", "space"], + options: [ + { value: "toggle", label: "Tap to talk" }, + { value: "hold", label: "Hold to talk" }, + ], + get: () => voiceBoardPrefs.read().talk, + set: (v) => voiceBoardPrefs.write({ talk: v as typeof d.talk }), + default: d.talk, + enabled: on, + }, + { + id: "general.voiceBoardStyle", category: "general", group: GROUP, order: 322, type: "toggle", label: "Write it by hand", + description: "New voice text is written in handwriting, like Solve this (English). Off: typed text you can edit.", + keywords: ["handwriting", "hand-written", "style", "typed", "হাতের লেখা"], + get: () => voiceBoardPrefs.read().style === "handwriting", + set: (v) => voiceBoardPrefs.write({ style: v ? "handwriting" : "typed" }), + default: d.style === "handwriting", + enabled: on, + }, + { + id: "general.voiceBoardPause", category: "general", group: GROUP, order: 323, type: "slider", label: "New line after a pause", + description: "Stop talking this long and the next words start a new line. Saying \"new line\" (নতুন লাইন) always works.", + keywords: ["pause", "silence", "line break", "new line", "বিরতি"], + min: 0, max: 5000, step: 250, + format: (v) => (v === 0 ? "Off" : `${(v / 1000).toFixed(v % 1000 ? 2 : 0).replace(/0$/, "")} s`), + get: () => voiceBoardPrefs.read().pauseMs, + set: (v) => voiceBoardPrefs.write({ pauseMs: v }), + default: d.pauseMs, + enabled: on, + }, + { + id: "general.voiceBoardStudent", category: "general", group: GROUP, order: 324, type: "toggle", label: "Students may ask the AI by voice", + description: "In Student view, the Voice text tool (when added in Teaching modes) can ask the AI. Students never write on the board.", + keywords: ["student", "student view", "allow", "ছাত্র"], + get: () => voiceBoardPrefs.read().student, + set: (v) => voiceBoardPrefs.write({ student: v }), + default: d.student, + enabled: on, + }, + { + id: "keyboard.voiceBoard", category: "keyboard", group: "Editing", order: 392, type: "key", label: "Voice text: listen or pause (with the tool on; hold with Hold to talk)", + keys: ["Space", "B", "."], + keywords: ["shortcut", "voice", "clicker", "presenter", "space", "push to talk"], + }, + { + id: "keyboard.voiceBoardDone", category: "keyboard", group: "Editing", order: 393, type: "key", label: "Voice text: finish the box", + keys: ["Esc"], + keywords: ["shortcut", "voice", "finish", "done"], + }, +]); diff --git a/apps/board/src/state.ts b/apps/board/src/state.ts index bb97fb0..c6f13e6 100644 --- a/apps/board/src/state.ts +++ b/apps/board/src/state.ts @@ -6,6 +6,8 @@ import { type Mode, type ModeConfig, type ModesConfig, resolveMode, sanitizeMode export type Tool = | "pen" | "highlighter" | "eraser" | "lasso" | "hand" | "laser" | "interact" | "text" | "rect" | "ellipse" | "line" | "arrow" | "stamp" + /** Voice text: speak and the words go on the board (voice/board.ts). */ + | "voice" /** The Shapes picker's tool; which shape is shapes.ts `currentShape()`. */ | "shape"; diff --git a/apps/board/src/voice/VoiceBoard.tsx b/apps/board/src/voice/VoiceBoard.tsx new file mode 100644 index 0000000..e0fda0b --- /dev/null +++ b/apps/board/src/voice/VoiceBoard.tsx @@ -0,0 +1,390 @@ +// Voice on the board: the UI of the Voice text tool (logic in voice/board.ts). +// +// - With the tool on, a tap on the page places a voice box there (a drag +// sets its width) and it starts listening. +// - The box shows a pulsing mint mic and the words as they are recognised +// (lighter), final words in the ink colour, wrapped inside the box and the +// page. Drag it to move it, drag its right edge to change the width. +// - Its bar: mic (listen / pause), EN / বাং, Text ↔ Ask AI, typed ↔ +// handwriting, where the audio goes, Done, discard. +// - Tap the box, press Esc or Done to finish: one text item, one undo step. +// - Space (or a clicker's "blank" key, B or .) toggles listening; with +// "Hold to talk" it listens while held. +// +// Mounted inside the board (App.tsx), above the ink, under the chrome. + +import { For, Show, createEffect, createSignal, on, onCleanup, onMount } from "solid-js"; +import { Icon } from "../components/Icon"; +import { MicIcon } from "../components/MicButton"; +import { controller } from "../controller"; +import { camera, hex, isView, mode, pageIndex, pages, tool } from "../state"; +import { + BOX_PAD, finishVoiceBox, listen, onToolChange, openVoiceBox, pauseListening, setVoiceBoxEl, setVoiceLang, + toggleListening, updateVoiceBox, voiceBoardPrefs, voiceBox, voiceLang, voiceLayout, voiceListening, voiceSent, +} from "./board"; +import { privacyShort, privacyText, voiceStatus } from "./dictation"; +import "./voice-board.css"; + +const DRAG_PX = 6; +const BAR_H = 52; + +const editableTarget = (e: Event) => { + const t = e.target as HTMLElement | null; + return !!t && (t.isContentEditable || t.tagName === "INPUT" || t.tagName === "TEXTAREA" || t.tagName === "SELECT"); +}; + +/** Screen (board-relative) px → world units, and back. */ +function toWorld(sx: number, sy: number): [number, number] { + const [cx, cy, z] = camera(); + return [cx + sx / z, cy + sy / z]; +} +function toScreen(wx: number, wy: number): [number, number] { + const [cx, cy, z] = camera(); + return [(wx - cx) * z, (wy - cy) * z]; +} +function boardXY(e: PointerEvent): [number, number] { + const r = controller.root.getBoundingClientRect(); + return [e.clientX - r.left, e.clientY - r.top]; +} + +function GripIcon() { + return ( + + ); +} +function CheckIcon() { + return ( + + ); +} +/** "Hand-written" toggle: a pen nib over a wavy line. */ +function ScriptIcon() { + return ( + + ); +} + +/** Where a tap or a drag on the page will put a box (while dragging). */ +function PlaceLayer() { + const [drag, setDrag] = createSignal<{ x0: number; y0: number; x1: number; y1: number } | null>(null); + let start: { id: number; x: number; y: number } | null = null; + const down = (e: PointerEvent) => { + if (e.button !== 0) return; + e.preventDefault(); + const [x, y] = boardXY(e); + start = { id: e.pointerId, x, y }; + (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId); + }; + const move = (e: PointerEvent) => { + if (!start || e.pointerId !== start.id) return; + const [x, y] = boardXY(e); + if (drag() || Math.hypot(x - start.x, y - start.y) > DRAG_PX * 2) setDrag({ x0: start.x, y0: start.y, x1: x, y1: y }); + }; + const up = (e: PointerEvent) => { + if (!start || e.pointerId !== start.id) return; + const d = drag(); + const s = start; + start = null; + setDrag(null); + if (e.type === "pointercancel") return; + const [wx, wy] = toWorld(d ? Math.min(d.x0, d.x1) : s.x, s.y); + const z = camera()[2]; + const w = d && Math.abs(d.x1 - d.x0) / z > 120 ? Math.abs(d.x1 - d.x0) / z : undefined; + void openVoiceBox({ x: wx, y: wy, w }); + }; + return ( +
+ + {(d) => ( +
+ )} + +
+ ); +} + +/** The voice box on the page (world units) and its bar (screen px). */ +function Box() { + let el!: HTMLDivElement; + onMount(() => setVoiceBoxEl(el)); + onCleanup(() => setVoiceBoxEl(null)); + const b = () => voiceBox()!; + const L = () => voiceLayout(); + const ask = () => b().mode === "ask"; + const bn = () => voiceLang().startsWith("bn"); + const empty = () => !L()?.lines.some((l) => l.done || l.live); + /** The box sits on the page: its colours follow the page, not the app theme. */ + const pageBg = () => pages()[pageIndex()]?.bg_color ?? 0xffffffff; + const darkBoard = () => (pageBg() >>> 8) < 0x808080; + + // Drag the body to move the box; a tap finishes it. + let press: { id: number; x: number; y: number; bx: number; by: number; moved: boolean } | null = null; + const down = (e: PointerEvent) => { + if (e.button !== 0) return; + e.preventDefault(); + e.stopPropagation(); + const [x, y] = boardXY(e); + const l = L(); + press = { id: e.pointerId, x, y, bx: l?.x ?? b().x, by: l?.y ?? b().y, moved: false }; + (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId); + }; + const move = (e: PointerEvent) => { + if (!press || e.pointerId !== press.id) return; + const [x, y] = boardXY(e); + if (!press.moved && Math.hypot(x - press.x, y - press.y) < DRAG_PX) return; + press.moved = true; + const z = camera()[2]; + updateVoiceBox({ x: press.bx + (x - press.x) / z, y: press.by + (y - press.y) / z }); + }; + const up = (e: PointerEvent) => { + if (!press || e.pointerId !== press.id) return; + const p = press; + press = null; + if (e.type === "pointercancel") return; + if (p.moved) { + const l = L(); + if (l) updateVoiceBox({ x: l.x, y: l.y }); // settle where it is shown (on the page) + } else void finishVoiceBox(); + }; + + // The right edge sets the width (the wrap width). + let resize: { id: number; x: number; w: number } | null = null; + const rdown = (e: PointerEvent) => { + e.preventDefault(); + e.stopPropagation(); + const [x] = boardXY(e); + resize = { id: e.pointerId, x, w: L()?.w ?? b().w }; + (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId); + }; + const rmove = (e: PointerEvent) => { + if (!resize || e.pointerId !== resize.id) return; + const [x] = boardXY(e); + updateVoiceBox({ w: Math.max(120, resize.w + (x - resize.x) / camera()[2]) }); + }; + const rup = (e: PointerEvent) => { + if (!resize || e.pointerId !== resize.id) return; + resize = null; + const l = L(); + if (l) updateVoiceBox({ w: l.w }); + }; + + // The bar sits above the box (below it near the top of the screen), on screen. + const bar = () => { + const l = L(); + if (!l) return { left: "0px", top: "0px" }; + const [sx, sy] = toScreen(l.x, l.y); + const [, sy2] = toScreen(l.x, l.y + l.h); + const r = controller.root.getBoundingClientRect(); + const top = sy - BAR_H - 6 < 8 ? sy2 + 6 : sy - BAR_H - 6; + return { left: `${Math.max(8, Math.min(r.width - 8 - 420, sx))}px`, top: `${Math.max(8, Math.min(r.height - BAR_H - 8, top))}px` }; + }; + const [cx, cy, z] = [() => camera()[0], () => camera()[1], () => camera()[2]]; + const holdMode = () => voiceBoardPrefs.read().talk === "hold"; + const micDown = (e: PointerEvent) => { + e.preventDefault(); + if (holdMode()) { listen(); (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId); } + }; + const micUp = () => { if (holdMode()) void finishVoiceBox(); }; + + return ( + <> +
+ + {(l) => ( +
+ + + {ask() ? (bn() ? "AI-কে প্রশ্ন করুন…" : "Ask the AI…") : voiceListening() ? (bn() ? "বলুন…" : "Speak…") : bn() ? "মাইকে চাপ দিন" : "Tap the mic to talk"} +
+ } + > + + {(line) => ( +
+ {line.done} + {line.live} + {!line.done && !line.live ? "​" : ""} +
+ )} +
+
+ + )} + +
+ + + ); +} + +/** "Sent to AI" for a moment after an Ask AI box. */ +function SentBubble() { + return ( + + {(s) => ( +
+ + + {s().ok ? (mode() === "teach" ? "Sent to the AI" : "Asked the AI") : "Waiting in the chat box"} + {s().text} + +
+ )} +
+ ); +} + +export default function VoiceBoard() { + const allowed = () => !isView() || voiceBoardPrefs.read().student; + createEffect(on(tool, (t) => onToolChange(t), { defer: true })); + onMount(() => { + let spaceDown = false; + const active = () => tool() === "voice" || !!voiceBox(); + const down = (e: KeyboardEvent) => { + if (!allowed()) return; + if (e.key === "Escape" && voiceBox()) { + e.preventDefault(); + e.stopImmediatePropagation(); + void finishVoiceBox(); + return; + } + if (!active() || editableTarget(e) || e.ctrlKey || e.metaKey || e.altKey) return; + const clicker = e.key === "b" || e.key === "B" || e.key === "."; + if (e.key !== " " && !clicker) return; + e.preventDefault(); + e.stopImmediatePropagation(); + if (e.repeat || spaceDown) return; + spaceDown = true; + if (voiceBoardPrefs.read().talk === "hold") { + if (!voiceBox()) void openVoiceBox({ ptt: true }); + else listen(); + } else if (!voiceBox()) void openVoiceBox(); + else toggleListening(); + }; + const up = (e: KeyboardEvent) => { + const clicker = e.key === "b" || e.key === "B" || e.key === "."; + if ((e.key !== " " && !clicker) || !spaceDown) return; + spaceDown = false; + e.stopImmediatePropagation(); + if (voiceBoardPrefs.read().talk === "hold" && voiceBox()) { + if (voiceBox()?.ptt) void finishVoiceBox(); + else pauseListening(); + } + }; + window.addEventListener("keydown", down, true); + window.addEventListener("keyup", up, true); + onCleanup(() => { + window.removeEventListener("keydown", down, true); + window.removeEventListener("keyup", up, true); + }); + }); + return ( + +
+ + + + + + + +
+
+ ); +} diff --git a/apps/board/src/voice/VoiceLayer.tsx b/apps/board/src/voice/VoiceLayer.tsx index 1073055..d5137a0 100644 --- a/apps/board/src/voice/VoiceLayer.tsx +++ b/apps/board/src/voice/VoiceLayer.tsx @@ -10,7 +10,7 @@ import { MicButton } from "../components/MicButton"; import { openSettings } from "../settings/open"; import { editingText } from "../state"; import { - activeAnchor, activeLang, cancelDictation, hint, interim, privacyShort, privacyText, setDictationLang, setHint, + activeAnchor, activeLang, bubbleOn, cancelDictation, hint, interim, privacyShort, privacyText, setDictationLang, setHint, startDictation, stopDictation, voiceEnv, voicePrefs, voiceStatus, } from "./dictation"; import { osDictationHint } from "./select"; @@ -54,7 +54,7 @@ function Bubble() { const listening = () => voiceStatus() === "listening"; const lang = () => activeLang(); return ( - + {(r) => (
e.preventDefault()}>
diff --git a/apps/board/src/voice/board.ts b/apps/board/src/voice/board.ts new file mode 100644 index 0000000..2b60ac9 --- /dev/null +++ b/apps/board/src/voice/board.ts @@ -0,0 +1,530 @@ +// Voice on the board ("Voice text", the dock's mic-with-a-T tool). +// +// The teacher places a voice box on the slide and talks; the words appear in +// it while they speak (interim results lighter, final words in the ink +// colour), wrapped inside the box and the page. Finishing (tap the box, Esc, +// releasing a push-to-talk) turns the box into one normal text item: one +// undo step per box. In "Ask AI" mode the words become a prompt to the +// in-app chat instead, with the page or the selection attached. +// +// Speech comes from the shared dictation session (dictation.ts: offline +// Whisper when downloaded, else Web Speech, with the privacy line), spoken +// punctuation from punctuation.ts. A pause of about 2 s starts a new line. +// The UI is VoiceBoard.tsx; agents drive it with the live ops +// `start_voice_text` / `stop_voice_text` (onVoiceOp, called by live.ts). + +import { batch, createMemo, createSignal } from "solid-js"; +import { openAiPanel, sendPrompt, setComposerDraft } from "../chat"; +import { pageAttachment, selectionAttachment } from "../chatContext"; +import { controller } from "../controller"; +import { liveHasChat } from "../live"; +import { jsonStore } from "../settings/bind"; +import { color, hex, isView, mode, pageIndex, pages, showToast, tool } from "../state"; +import { inkForBoard } from "../dock"; +import { + type CustomTarget, activeLang, cancelDictation, isDictating, setDictationLang, startDictation, stopDictation, + voiceChoice, voicePrefs, voiceStatus, +} from "./dictation"; +import { joinDictation } from "./punctuation"; +import type { VoiceLang } from "./types"; +import { type LiveLine, WRAP_SLACK, boardMeasure, loadBoardFont, splitLines, tidyText, wrapLines } from "./wrap"; + +// ---------------------------------------------------------------- settings + +export type VoiceBoxMode = "text" | "ask"; +export type VoiceStyle = "typed" | "handwriting"; + +/** Settings → General → Voice on the board (settings/defs/voiceBoard.ts). */ +export const voiceBoardPrefs = jsonStore("rupok.voiceBoard", { + /** What a new voice box does: words on the board, or a prompt to the AI. */ + mode: "text" as VoiceBoxMode, + /** "toggle": the box listens until finished (holding the dock button is + * push-to-talk too). "hold": it listens only while the dock button, the + * box's mic or Space is held. */ + talk: "toggle" as "toggle" | "hold", + /** New boxes write in handwriting (English) instead of typed text. */ + style: "typed" as VoiceStyle, + /** A pause this long (ms) starts a new line. 0 turns it off. */ + pauseMs: 2000, + /** Let the voice box be used in Student view (Ask AI only: the student + * view cannot write on the board). */ + student: false, +}); + +/** Text size of a voice box, world units (slide px): readable at the back. */ +export const VOICE_TEXT_SIZE = 48; +const DEFAULT_W = 900; +const LINE = 1.25; +/** Inner padding of the live box (world units, matches voice-board.css). */ +export const BOX_PAD = 8; + +// ------------------------------------------------------------------- state + +export interface VoiceBox { + /** Page index the box is on. */ + page: number; + /** World units (slide px): top-left and width; the height follows the text. */ + x: number; + y: number; + w: number; + size: number; + color: number; + mode: VoiceBoxMode; + style: VoiceStyle; + /** Opened by a push-to-talk: finish on release, keep the current tool. */ + ptt: boolean; +} + +const [box, setBox] = createSignal(null); +/** Final words in the box (with spoken punctuation and pause breaks). */ +const [said, setSaid] = createSignal(""); +/** The words being recognised now (replaced on every result). */ +const [live, setLive] = createSignal(""); +/** The box element (the dictation anchor: hint, focus). */ +const [boxEl, setBoxEl] = createSignal(null); +/** "Sent to AI" confirmation: the prompt, shown for a moment. */ +const [sent, setSent] = createSignal<{ text: string; at: number; ok: boolean } | null>(null); +/** The language chosen on the box while it is not listening. */ +const [boxLang, setBoxLang] = createSignal(null); +const [pendingBreak, setPendingBreak] = createSignal(false); + +export { box as voiceBox, boxEl as voiceBoxEl, live as voiceLive, said as voiceSaid, sent as voiceSent, setBoxEl as setVoiceBoxEl }; + +/** Where the last voice text went, so the next box can open under it. */ +let lastPlace: { page: number; x: number; y: number; w: number; bottom: number } | null = null; + +/** The language the box listens in. */ +export const voiceLang = (): VoiceLang => (listening() ? activeLang() : boxLang() ?? activeLang() ?? voicePrefs.read().lang); + +// ---------------------------------------------------------------- geometry + +/** The current page's slide frame (null: an infinite board). */ +export function pageFrame(): { w: number; h: number } | null { + return pages()[pageIndex()]?.frame ?? null; +} + +/** Fit a box onto the page: narrower than the page, inside it left to right + * and top to bottom (as far as its height allows). */ +export function clampBox(b: { x: number; y: number; w: number }, h: number, size: number, frame = pageFrame()): { x: number; y: number; w: number } { + if (!frame) return b; + const minW = Math.min(frame.w, Math.max(size * 5, 240)); + const w = Math.min(frame.w, Math.max(minW, b.w)); + const x = Math.min(Math.max(0, b.x), frame.w - w); + const y = Math.min(Math.max(0, b.y), Math.max(0, frame.h - h)); + return { x, y, w }; +} + +/** Ink colour for new voice text: the pen colour, readable on this board. */ +function inkColor(): number { + const bg = pages()[pageIndex()]?.bg_color ?? 0xffffffff; + return inkForBoard(color(), (bg >>> 8) < 0x808080); +} + +/** The visible part of the board, in world units. */ +function visibleWorld(): { x: number; y: number; w: number; h: number } { + const [cx, cy, z] = controller.board.camera(); + const r = controller.root.getBoundingClientRect(); + const [top, right, bottom, left] = controller.insets; + return { x: cx + left / z, y: cy + top / z, w: Math.max(1, r.width - left - right) / z, h: Math.max(1, r.height - top - bottom) / z }; +} + +/** Where a box opens when nobody said where: under the last voice text on + * this page while there is room, else the middle of the visible page. */ +function defaultPlace(size: number): { x: number; y: number; w: number } { + const frame = pageFrame(); + if (lastPlace && lastPlace.page === pageIndex()) { + const y = lastPlace.bottom + size * 0.5; + if (!frame || y + size * 2 < frame.h) return { x: lastPlace.x, y, w: lastPlace.w }; + } + const v = visibleWorld(); + const w = Math.min(DEFAULT_W, (frame?.w ?? v.w) * 0.6, v.w * 0.8); + return { x: v.x + (v.w - w) / 2, y: v.y + v.h * 0.4, w }; +} + +// -------------------------------------------------------------- the text + +/** Joined preview of the interim words after what was said. */ +function preview(): string { + const l = live().trim(); + if (!l) return ""; + const base = said() + (pendingBreak() && said() ? "\n" : ""); + const p = voicePrefs.read(); + const j = joinDictation(base, l, "", { lang: voiceLang(), autoPunctuation: p.autoPunctuation }); + return (pendingBreak() && said() ? "\n" : "") + j; +} + +/** The box's font size after shrinking to keep a long text on the page. */ +const fitted = createMemo(() => { + const b = box(); + if (!b) return null; + const frame = pageFrame(); + let size = b.size; + let lines: LiveLine[] = []; + for (let i = 0; i < 12; i++) { + lines = splitLines(said(), preview(), b.w - 2 * BOX_PAD - WRAP_SLACK, boardMeasure(size)); + const h = Math.max(1, lines.length) * size * LINE + 2 * BOX_PAD; + if (!frame || h <= frame.h || size <= 20) break; + size = Math.max(20, size * 0.88); + } + const h = Math.max(1, lines.length) * size * LINE + 2 * BOX_PAD; + const at = clampBox(b, h, size); + return { ...at, h, size, lines }; +}); +export { fitted as voiceLayout }; + +// --------------------------------------------------------- the dictation + +let heardAt = 0; +let inUtterance = false; +let wantListen = false; +let restarts: number[] = []; +let endWaiters: (() => void)[] = []; + +const listening = () => isDictating(target); + +function onWords() { + const now = performance.now(); + const pause = voiceBoardPrefs.read().pauseMs; + if (!inUtterance) { + inUtterance = true; + const s = said(); + if (pause > 0 && s && !s.endsWith("\n") && heardAt && now - heardAt >= pause) setPendingBreak(true); + } + heardAt = now; +} + +const target: CustomTarget = { + get element() { return boxEl(); }, + before: () => { + // A final result with no interim before it starts an utterance here. + onWords(); + const s = said(); + return pendingBreak() && s ? `${s}\n` : s; + }, + interim: (t: string) => { + if (t.trim()) onWords(); + setLive(t); + }, + insert: (t: string) => { + batch(() => { + const brk = pendingBreak() && said() && !said().endsWith("\n"); + setSaid((s) => tidyText(s + (brk ? "\n" + t.replace(/^ +/, "") : t))); + setPendingBreak(false); + setLive(""); + }); + inUtterance = false; + heardAt = performance.now(); + }, +}; + +function onEnd(reason: "stopped" | "cancelled" | "error") { + setLive(""); + inUtterance = false; + const waiters = endWaiters; + endWaiters = []; + for (const w of waiters) w(); + // A recogniser that stops by itself (silence, a network hiccup) comes back + // while the box still wants to listen, at most 3 times in 10 s. + if (reason === "stopped" && wantListen && box()) { + const now = performance.now(); + restarts = restarts.filter((t) => now - t < 10000); + if (restarts.length < 3) { + restarts.push(now); + setTimeout(() => { if (wantListen && box() && voiceStatus() === "idle") begin(); }, 120); + return; + } + } + if (reason !== "cancelled") wantListen = false; +} + +function begin(): boolean { + const lang = boxLang() ?? undefined; + return startDictation(target, { lang, anchor: boxEl(), bubble: false, onEnd }); +} + +/** Start listening in the open box. False when no speech provider works + * here (the OS dictation hint is shown) or voice input is off. */ +export function listen(): boolean { + if (!box()) return false; + if (listening()) return true; + if (!voicePrefs.read().enabled) { + showToast("Voice input is off in Settings › General › Voice input"); + return false; + } + wantListen = true; + heardAt = 0; + const ok = begin(); + if (!ok) wantListen = false; + return ok; +} + +/** Stop listening; the box stays open with its words. */ +export function pauseListening() { + wantListen = false; + if (listening()) stopDictation(); +} + +export function toggleListening() { + if (listening()) pauseListening(); + else listen(); +} + +export const voiceListening = listening; + +/** Wait until the running session has delivered its last words. */ +function untilEnded(ms = 3000): Promise { + if (voiceStatus() === "idle" || !listening()) return Promise.resolve(); + return new Promise((resolve) => { + const t = setTimeout(resolve, ms); + endWaiters.push(() => { clearTimeout(t); resolve(); }); + }); +} + +// ------------------------------------------------------------- open/close + +export interface OpenOptions { + x?: number; y?: number; w?: number; + mode?: VoiceBoxMode; style?: VoiceStyle; lang?: VoiceLang; + /** Push-to-talk: finish on release and keep the current tool. */ + ptt?: boolean; + /** Start listening at once (default true). */ + listen?: boolean; +} + +/** Open a voice box (finishing any open one first). Returns false when + * voice text cannot be used here. */ +export async function openVoiceBox(o: OpenOptions = {}): Promise { + if (box()) await finishVoiceBox(); + const p = voiceBoardPrefs.read(); + const m: VoiceBoxMode = isView() ? "ask" : o.mode ?? p.mode; + if (isView() && !p.student) return false; + const size = VOICE_TEXT_SIZE; + const d = defaultPlace(size); + const at = clampBox({ x: o.x ?? d.x, y: o.y ?? d.y, w: o.w ?? d.w }, size * LINE + 2 * BOX_PAD, size); + if (o.lang) setBoxLang(o.lang); + void loadBoardFont(size, "Aঅ"); + batch(() => { + setSaid(""); + setLive(""); + setPendingBreak(false); + setSent(null); + setBox({ page: pageIndex(), ...at, size, color: inkColor(), mode: m, style: o.style ?? p.style, ptt: !!o.ptt }); + }); + restarts = []; + if (o.listen === false) return true; + // The box element is mounted by now (the OS dictation hint anchors to it). + await Promise.resolve(); + listen(); + return true; +} + +/** Change the open box (drag, resize, the mode and style toggles). */ +export function updateVoiceBox(patch: Partial>) { + const b = box(); + if (!b) return; + if (isView() && patch.mode === "text") return; + setBox({ ...b, ...patch }); +} + +/** Switch the box's language (EN / বাং): restarts a running session. */ +export function setVoiceLang(lang: VoiceLang) { + setBoxLang(lang); + if (listening()) setDictationLang(lang); +} + +export interface FinishResult { + text: string; + /** The new text item, or the first handwriting stroke group. */ + item_id?: string; + kind: "text" | "handwriting" | "prompt" | "none"; + note?: string; +} + +let finishing: Promise | null = null; + +/** Finish the box: its words become a text item (one undo step), handwriting, + * or a prompt to the AI; `cancel` throws them away. */ +export function finishVoiceBox(o: { cancel?: boolean } = {}): Promise { + if (finishing) return finishing; + finishing = (async () => { + const b = box(); + if (!b) return { text: "", kind: "none" as const }; + wantListen = false; + if (o.cancel) cancelDictation(); + else if (listening()) { + stopDictation(); + await untilEnded(); + } + const layout = fitted(); + const text = tidyText(said()).trim(); + batch(() => { + setBox(null); + setSaid(""); + setLive(""); + setPendingBreak(false); + }); + if (o.cancel || !text || !layout) return { text: o.cancel ? "" : text, kind: "none" as const }; + if (b.mode === "ask") return sendToAi(text); + // The words go on the page being shown. + const w = layout.w - 2 * BOX_PAD; + const x = layout.x + BOX_PAD, y = layout.y + BOX_PAD; + lastPlace = { page: pageIndex(), x: layout.x, y: layout.y, w: layout.w, bottom: layout.y + layout.h }; + if (b.style === "handwriting") { + const r = writeHandwriting(text, x, y, w, layout.size, b.color); + if (r) return r; + } + await loadBoardFont(layout.size, text); + const lines = wrapLines(text, w - WRAP_SLACK, boardMeasure(layout.size)); + const id = controller.board.add_text_box(x, y, w, lines.join("\n"), layout.size, b.color) ?? undefined; + controller.sync(true); + return { text, item_id: id, kind: "text" as const }; + })(); + const p = finishing; + void p.finally(() => { finishing = null; }); + return p; +} + +/** Handwriting style: the synthesiser that "Solve this" uses writes the lines + * (English; Bangla has no handwriting glyphs yet, so it stays typed). */ +function writeHandwriting(text: string, x: number, y: number, w: number, size: number, rgba: number): FinishResult | null { + if (/[ঀ-৿]/.test(text)) { + showToast("Handwriting is English only for now: written as typed text"); + return null; + } + // The synthesiser's size is a capital's height; the line advance is ~2×. + const cap = size * 0.72; + const lines = wrapLines(text, w, (s) => s.length * cap * 0.62).slice(0, 40).map((l) => l.slice(0, 200)); + try { + const r = JSON.parse(controller.board.live_apply(JSON.stringify({ + op: "write_handwriting", lines, anchor: { x, y }, size: cap, color: hex(rgba), style: "teacher", step_mode: "all", + }), "Voice text")); + controller.sync(true); + void import("../solve").then((m) => m.watchReveal()); + return { text, item_id: r.item_ids?.[0], kind: "handwriting", note: r.note }; + } catch (e) { + console.warn("rupok: voice handwriting failed, writing typed text", e); + return null; + } +} + +/** Ask AI: the words go to the in-app chat with the page (or the selection) + * attached. Teach keeps the chat closed; a small bubble confirms. */ +async function sendToAi(text: string): Promise { + if (!liveHasChat()) { + // Not connected yet: open the AI panel with the words in the composer. + setComposerDraft({ text, n: Date.now() }); + openAiPanel(); + setSent({ text, at: Date.now(), ok: false }); + clearSentSoon(); + return { text, kind: "prompt", note: "the AI chat is not connected; the prompt is waiting in the chat box" }; + } + const sel = controller.board.selection_json(); + const n = (JSON.parse(sel || "[]") as string[]).length; + const att = n ? selectionAttachment(n) : pageAttachment(controller.board.page_index() + 1); + await sendPrompt(text, [att]); + if (mode() !== "teach") openAiPanel(); + setSent({ text, at: Date.now(), ok: true }); + clearSentSoon(); + return { text, kind: "prompt" }; +} + +let sentTimer = 0; +function clearSentSoon() { + clearTimeout(sentTimer); + sentTimer = window.setTimeout(() => setSent(null), 3200); +} + +// ------------------------------------------------------- the dock button + +const HOLD_MS = 350; +let pressTimer = 0; +let pressed = false; +let held = false; + +/** Pointer down on the dock's Voice text button: a hold is push-to-talk. */ +export function dockPress(e: PointerEvent) { + if (e.button !== 0) return; + pressed = true; + held = false; + clearTimeout(pressTimer); + pressTimer = window.setTimeout(() => { + if (!pressed) return; + held = true; + const b = box(); + if (b) { if (!listening()) listen(); } + else void openVoiceBox({ ptt: true }); + }, HOLD_MS); + (e.currentTarget as HTMLElement | null)?.setPointerCapture?.(e.pointerId); +} + +/** Pointer up: a push-to-talk ends, its words go on the board. */ +export function dockRelease() { + clearTimeout(pressTimer); + if (!pressed) return; + pressed = false; + if (!held) return; + const b = box(); + // Push-to-talk boxes finish on release; a toggle box just stops listening. + if (b?.ptt || voiceBoardPrefs.read().talk === "hold") void finishVoiceBox(); + else pauseListening(); +} + +/** The click that ends a hold is not a tap. */ +export function dockClickConsumed(): boolean { + if (held) { held = false; return true; } + return false; +} + +/** A tap on the tool: picking it (VoiceBoard shows where to place a box). */ +export function pickVoiceTool() { + if (tool() === "voice" && box()) { void finishVoiceBox(); return; } + controller.setTool("voice"); +} + +/** Leaving the tool finishes a box it opened (a push-to-talk box stays). */ +export function onToolChange(t: string) { + const b = box(); + if (b && !b.ptt && t !== "voice") void finishVoiceBox(); +} + +// ---------------------------------------------------------- agents (live) + +const num = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : undefined); +const LANGS: Record = { en: "en-US", "en-us": "en-US", "en-gb": "en-GB", "en-in": "en-IN", bn: "bn-BD", "bn-bd": "bn-BD", "bn-in": "bn-IN" }; + +/** live.ts: an agent's `start_voice_text` / `stop_voice_text`. */ +export async function onVoiceOp(op: any): Promise { + if (op.op === "stop_voice_text") { + if (!box()) return { status: "idle", text: "", note: "no voice box was open" }; + const r = await finishVoiceBox({ cancel: op.cancel === true }); + return { status: op.cancel === true ? "cancelled" : "done", ...r }; + } + if (!voicePrefs.read().enabled) throw new Error("Voice input is turned off on this board (Settings › General › Voice input)."); + if (voiceChoice() === "hint") throw new Error("This board has no speech recognition (use Chrome or Edge, or the desktop app with the offline voice model)."); + const modeArg = op.mode === "ask" ? "ask" : op.mode == null || op.mode === "text" ? undefined : null; + if (modeArg === null) throw new Error(`mode must be "text" or "ask", not ${JSON.stringify(op.mode)}`); + const style = op.style === "handwriting" ? "handwriting" : op.style == null || op.style === "typed" ? undefined : null; + if (style === null) throw new Error(`style must be "typed" or "handwriting", not ${JSON.stringify(op.style)}`); + const lang = op.lang == null ? undefined : LANGS[String(op.lang).toLowerCase()]; + if (op.lang != null && !lang) throw new Error(`lang must be en-US or bn-BD (also en-GB, en-IN, bn-IN), not ${JSON.stringify(op.lang)}`); + const w = num(op.w); + if (w !== undefined && w <= 0) throw new Error("w must be positive"); + const ok = await openVoiceBox({ x: num(op.x), y: num(op.y), w, mode: modeArg ?? undefined, style: style ?? undefined, lang, ptt: false }); + if (!ok) throw new Error("Voice text is not available in this mode."); + const b = fitted(); + return { + status: listening() ? "listening" : "open", + page: pageIndex() + 1, + box: b ? { x: Math.round(b.x), y: Math.round(b.y), w: Math.round(b.w) } : null, + mode: box()?.mode, style: box()?.style, lang: voiceLang(), provider: voiceChoice(), + note: "The teacher's words appear in the box as they speak; call stop_voice_text to put them on the board.", + }; +} + +/** For live.ts: is this op a voice op? */ +export const isVoiceOp = (op: any) => op?.op === "start_voice_text" || op?.op === "stop_voice_text"; + +/** Test hook (e2e): the state at a glance. */ +if (typeof window !== "undefined") { + (window as any).__rupokVoiceBoard = { box, said, live, listening, finish: finishVoiceBox, open: openVoiceBox, layout: fitted, op: onVoiceOp }; +} diff --git a/apps/board/src/voice/dictation.ts b/apps/board/src/voice/dictation.ts index 71a3c40..f0212f2 100644 --- a/apps/board/src/voice/dictation.ts +++ b/apps/board/src/voice/dictation.ts @@ -101,6 +101,9 @@ export interface CustomTarget { interim?(text: string): void; /** Where the live-text bubble and the hint are shown. */ element?: HTMLElement | null; + /** The text already there, so new words get a space and sentence + * capitals the way they do in a field (default: none). */ + before?(): string; } export type DictationTarget = EditableEl | CustomTarget; @@ -112,6 +115,9 @@ export interface DictationOptions { onFinal?(text: string): void; /** Called when the session ends (stopped, cancelled or failed). */ onEnd?(reason: "stopped" | "cancelled" | "error"): void; + /** Show the live-text bubble (default true). Voice text on the board + * shows the words in its own box. */ + bubble?: boolean; } export type VoiceStatus = "idle" | "listening" | "finishing"; @@ -126,7 +132,10 @@ const [lastError, setLastError] = createSignal(null); /** The OS-dictation hint popover, anchored to an element. */ const [hint, setHint] = createSignal(null); -export { activeAnchor, activeLang, activeTarget, hint, interim, lastError, level, setHint, status as voiceStatus }; +/** The live-text bubble is wanted for the running session. */ +const [bubbleOn, setBubbleOn] = createSignal(true); + +export { activeAnchor, activeLang, activeTarget, bubbleOn, hint, interim, lastError, level, setHint, status as voiceStatus }; let session: DictationSession | null = null; let sessionOpts: DictationOptions = {}; @@ -158,7 +167,7 @@ function deliver(text: string) { if (!t) return; const p = voicePrefs.read(); if (isCustom(t)) { - const out = joinDictation("", text, "", { lang: activeLang(), autoPunctuation: p.autoPunctuation }); + const out = joinDictation(t.before?.() ?? "", text, "", { lang: activeLang(), autoPunctuation: p.autoPunctuation }); if (out) { t.insert(out); sessionOpts.onFinal?.(out); } return; } @@ -200,6 +209,7 @@ export function startDictation(target?: DictationTarget | null, opts: DictationO setActiveLang(lang); setActiveTarget(() => t); setActiveAnchor(opts.anchor ?? el); + setBubbleOn(opts.bubble !== false); setLastError(null); setInterim(""); setLevel(0); diff --git a/apps/board/src/voice/voice-board.css b/apps/board/src/voice/voice-board.css new file mode 100644 index 0000000..494f66f --- /dev/null +++ b/apps/board/src/voice/voice-board.css @@ -0,0 +1,126 @@ +/* Voice on the board (VoiceBoard.tsx): the place layer, the voice box on the + * page and its bar. FigJam-flat, mint accent, light and dark via tokens. */ + +.vb-layer { position: absolute; inset: 0; pointer-events: none; z-index: 3; } +.vb-place { position: absolute; inset: 0; pointer-events: auto; cursor: cell; touch-action: none; } +.vb-drag { + position: absolute; height: 0; margin-top: -2px; border-top: 4px dashed var(--accent-9); border-radius: 2px; pointer-events: none; +} + +/* ------------------------------------------------------------- the box */ +.vb-world { position: absolute; left: 0; top: 0; transform-origin: 0 0; pointer-events: none; } +.vb-box { + position: absolute; box-sizing: border-box; pointer-events: auto; cursor: grab; touch-action: none; + font-family: var(--font); font-weight: 500; line-height: 1.25; white-space: pre; color: var(--vb-ink); + border-radius: calc(10px / var(--vbz, 1)); + outline: calc(2px / var(--vbz, 1)) dashed var(--accent-9); outline-offset: calc(2px / var(--vbz, 1)); + /* Opaque in the page colour with a mint tint, so the words read over ink. */ + background: color-mix(in srgb, var(--accent-9) 8%, var(--vb-page, #fff)); + box-shadow: 0 6px 18px -10px rgba(0, 0, 40, 0.3); + -webkit-user-select: none; user-select: none; +} +.vb-box:active { cursor: grabbing; } +.vb-box.listening { outline-style: solid; } +/* Ask AI: a question bubble, mint text on light (on the page's own colours). */ +.vb-box.ask { + background: #e6fcf5; color: #087f5b; outline-style: solid; + border-radius: calc(18px / var(--vbz, 1)) calc(18px / var(--vbz, 1)) calc(18px / var(--vbz, 1)) calc(4px / var(--vbz, 1)); +} +.vb-box.ask.on-dark { background: #0b2b23; color: #63e6be; } +.vb-box.ask .vb-done, .vb-box.ask .vb-live, .vb-box.ask .vb-placeholder { color: inherit; } +.vb-line { min-height: 1.25em; } +.vb-done { color: var(--vb-ink); } +.vb-live { color: var(--vb-ink); opacity: 0.45; } +.vb-placeholder { opacity: 0.45; font-weight: 450; } + +/* The pulsing mint mic at the box's corner: the same size at any zoom. */ +.vb-badge { + position: absolute; left: 0; top: 0; width: 28px; height: 28px; border-radius: 50%; + display: grid; place-items: center; background: var(--accent-9); color: var(--accent-contrast); + transform-origin: 0 0; transform: scale(calc(1 / var(--vbz, 1))) translate(-14px, -14px); + box-shadow: 0 0 0 2px #fff; +} +.vb-box.on-dark .vb-badge { box-shadow: 0 0 0 2px #17191c; } +.vb-box:not(.listening) .vb-badge { background: var(--gray-9); color: #fff; } +.vb-box.listening .vb-badge::after { + content: ""; position: absolute; inset: -2px; border-radius: 50%; border: 2px solid var(--accent-9); + animation: vb-pulse 1.4s var(--ease) infinite; +} +@keyframes vb-pulse { 0% { opacity: 0.9; inset: -2px; } 80% { opacity: 0; inset: -12px; } 100% { opacity: 0; } } + +/* Right edge: drag to set the wrap width. */ +.vb-resize { + position: absolute; top: 0; bottom: 0; right: calc(-22px / var(--vbz, 1)); width: calc(44px / var(--vbz, 1)); + cursor: ew-resize; touch-action: none; +} +.vb-resize::after { + content: ""; position: absolute; left: 50%; top: 50%; width: calc(6px / var(--vbz, 1)); height: calc(28px / var(--vbz, 1)); + transform: translate(-50%, -50%); border-radius: 99px; background: var(--accent-9); + box-shadow: 0 0 0 calc(2px / var(--vbz, 1)) var(--surface-solid); +} + +/* -------------------------------------------------------------- the bar */ +.vb-bar { + position: absolute; pointer-events: auto; display: flex; align-items: center; gap: 4px; padding: 4px; + height: 52px; box-sizing: border-box; border-radius: 16px; background: var(--surface-solid); color: var(--text); + box-shadow: 0 0 0 1px var(--hairline), 0 6px 20px -8px rgba(0, 0, 40, 0.22); + font: 550 13px/16px var(--font); white-space: nowrap; animation: pop 160ms var(--ease); +} +.vb-btn { + flex: none; width: 44px; height: 44px; display: grid; place-items: center; border: 0; padding: 0; border-radius: 12px; + background: transparent; color: var(--text-2); cursor: pointer; transition: background 120ms var(--ease), color 120ms var(--ease); + touch-action: none; +} +.vb-btn:hover { background: var(--hover); color: var(--text); } +.vb-btn:active { background: var(--pressed); } +.vb-btn.on { background: var(--accent-3); color: var(--accent-11); } +.vb-grip { width: 28px; cursor: grab; color: var(--text-3); } +.vb-mic { position: relative; border-radius: 999px; } +.vb-mic.on { background: var(--accent-9); color: var(--accent-contrast); } +.vb-mic.on:hover { background: var(--accent-10); } +.vb-mic.on::after { + content: ""; position: absolute; inset: 0; border-radius: inherit; border: 2px solid var(--accent-9); pointer-events: none; + animation: vb-pulse 1.4s var(--ease) infinite; +} +.vb-mic.finishing::after { animation: none; opacity: 0.4; } +.vb-btn.vb-finish { background: var(--accent-9); color: var(--accent-contrast); } +.vb-btn.vb-finish:hover { background: var(--accent-10); } +.vb-seg { flex: none; display: inline-flex; height: 44px; box-sizing: border-box; padding: 4px; gap: 2px; border-radius: 12px; background: var(--gray-a3); } +.vb-seg button { + min-width: 44px; height: 36px; padding: 0 10px; border: 0; border-radius: 9px; background: transparent; color: var(--text-2); + display: inline-flex; align-items: center; justify-content: center; gap: 4px; font: 600 13px/1 var(--font); cursor: pointer; +} +.vb-seg button:hover:not(.on):not(:disabled) { color: var(--text); } +.vb-seg button.on { background: var(--surface-solid); color: var(--accent-11); box-shadow: 0 0 0 1px var(--hairline), 0 1px 2px rgba(0, 0, 40, 0.08); } +.vb-seg button:disabled { opacity: 0.4; cursor: default; } +.vb-privacy { flex: none; padding: 0 6px; font: 550 11px/12px var(--font); color: var(--text-3); max-width: 110px; overflow: hidden; text-overflow: ellipsis; } + +/* ------------------------------------------------- "Sent to the AI" pill */ +.vb-sent { + position: absolute; left: 50%; top: 72px; transform: translateX(-50%); pointer-events: auto; + display: flex; align-items: center; gap: 10px; max-width: min(560px, calc(100% - 32px)); box-sizing: border-box; + padding: 8px 14px 8px 8px; border-radius: 16px; background: var(--surface-solid); color: var(--text); + box-shadow: 0 0 0 1px var(--hairline), 0 8px 24px -8px rgba(0, 0, 40, 0.25); animation: pop 160ms var(--ease); +} +.vb-sent-icon { flex: none; width: 32px; height: 32px; border-radius: 10px; display: grid; place-items: center; background: var(--accent-9); color: var(--accent-contrast); } +.vb-sent-text { display: grid; min-width: 0; font: 450 13px/18px var(--font); } +.vb-sent-text b { font-weight: 650; color: var(--accent-11); } +.vb-sent-text span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } + +@media (max-width: 520px) { + .vb-privacy { display: none; } + .vb-bar { gap: 2px; } +} +@media (prefers-reduced-motion: reduce) { + .vb-box.listening .vb-badge::after, .vb-mic.on::after { animation: none; } + .vb-bar, .vb-sent { animation: none; } +} + +/* The dock's Voice text button while it listens (push-to-talk). */ +.dock-shell .tool.listening { --dock-cell: var(--accent-9); background: var(--accent-9); color: var(--accent-contrast); position: relative; } +.dock-shell .tool.listening:hover { --dock-cell: var(--accent-10); background: var(--accent-10); } +.dock-shell .tool.listening::after { + content: ""; position: absolute; inset: 2px; border-radius: inherit; border: 2px solid var(--accent-9); pointer-events: none; + animation: vb-pulse 1.4s var(--ease) infinite; +} +@media (prefers-reduced-motion: reduce) { .dock-shell .tool.listening::after { animation: none; } } diff --git a/apps/board/src/voice/wrap.ts b/apps/board/src/voice/wrap.ts new file mode 100644 index 0000000..5c062ed --- /dev/null +++ b/apps/board/src/voice/wrap.ts @@ -0,0 +1,135 @@ +// Line breaking for text that must stay inside a box: Voice text on the +// board, and the agents' `add_text` with a width (live.ts). +// +// Board text items never wrap by themselves (`.item.text` has a minimum +// width, not a width), so text that has to fit a box gets its line breaks +// written into it, measured with the board's own font. What the teacher sees +// in the voice box is then exactly the text item it becomes, and every reader +// (PDF export, snapshots, other apps) shows the same lines. +// +// `wrapText` is pure (the measure function is passed in) and unit-tested in +// apps/board/test/voice-board.test.ts. + +/** Width of a string in the units of the box. */ +export type Measure = (s: string) => number; + +/** Grapheme clusters, so a Bangla conjunct or a vowel sign is never split. */ +function graphemes(s: string): string[] { + const Seg = (Intl as any).Segmenter; + if (Seg) return Array.from(new Seg(undefined, { granularity: "grapheme" }).segment(s), (x: any) => x.segment as string); + return Array.from(s); +} + +/** Break a word wider than the box into pieces that fit. */ +function breakWord(word: string, width: number, measure: Measure): string[] { + const out: string[] = []; + let cur = ""; + for (const g of graphemes(word)) { + if (cur && measure(cur + g) > width) { + out.push(cur); + cur = g; + } else cur += g; + } + if (cur) out.push(cur); + return out; +} + +/** + * Break `text` into lines no wider than `width`: at spaces where it can, and + * inside a word only when the word alone is wider than the box. Existing + * line breaks are kept; the space at a break is dropped. Returns the lines. + */ +export function wrapLines(text: string, width: number, measure: Measure): string[] { + const out: string[] = []; + if (!(width > 0)) return text.split("\n"); + for (const para of text.split("\n")) { + const words = para.split(/ +/); + let line = ""; + for (const raw of words) { + if (raw === "") continue; + const next = line ? `${line} ${raw}` : raw; + if (measure(next) <= width) { + line = next; + continue; + } + if (line) out.push(line); + if (measure(raw) <= width) { + line = raw; + continue; + } + const pieces = breakWord(raw, width, measure); + out.push(...pieces.slice(0, -1)); + line = pieces[pieces.length - 1] ?? ""; + } + out.push(line); + } + return out; +} + +/** {@link wrapLines} joined with `\n`. */ +export const wrapText = (text: string, width: number, measure: Measure) => wrapLines(text, width, measure).join("\n"); + +/** Tidy spacing so the wrapping maps back onto the text exactly. */ +export const tidyText = (s: string) => s.replace(/[ \t]+/g, " ").replace(/ *\n */g, "\n"); + +/** One rendered line of the box: the part already final, then the part still being recognised. */ +export interface LiveLine { done: string; live: string } + +/** + * The box's lines: `done + live` wrapped to `width` with `measure`, each line + * split where the final text ends. Pure (unit-tested). + */ +export function splitLines(done: string, liveText: string, width: number, measure: (s: string) => number): LiveLine[] { + const full = tidyText(done + liveText); + const cut = tidyText(done).length; + const lines = wrapLines(full, width, measure); + const out: LiveLine[] = []; + let p = 0; + for (const line of lines) { + const a = p, b = p + line.length; + out.push({ done: full.slice(a, Math.max(a, Math.min(b, cut))), live: full.slice(Math.max(a, Math.min(b, cut)), b) }); + p = b; + // The space or line break the wrap consumed. + if (full[p] === " " || full[p] === "\n") p++; + } + return out; +} + +// ------------------------------------------------------------ board font + +let ctx: CanvasRenderingContext2D | null = null; +let family: string | null = null; + +/** The board's text font family (`.item.text` uses `--font`). */ +function boardFamily(): string { + if (family) return family; + const f = getComputedStyle(document.documentElement).getPropertyValue("--font").trim(); + family = f || "sans-serif"; + return family; +} + +/** The CSS font of a board text item at `size` world units. */ +export const boardFont = (size: number) => `500 ${size}px ${boardFamily()}`; + +/** A measure for board text at font size `size` (world units). The browser + * shapes the canvas text like the DOM text (Bangla included). */ +export function boardMeasure(size: number): Measure { + ctx ??= document.createElement("canvas").getContext("2d"); + const c = ctx; + if (!c) return (s) => s.length * size * 0.55; + const font = boardFont(size); + return (s) => { + c.font = font; + return c.measureText(s).width; + }; +} + +/** Make sure the board font is loaded before measuring `text` with it. */ +export async function loadBoardFont(size: number, text: string): Promise { + try { + await document.fonts.load(boardFont(size), text || "A"); + } catch { /* measure with what there is */ } +} + +/** A little room so a line measured at the limit never wraps in the DOM. */ +export const WRAP_SLACK = 2; diff --git a/apps/board/test/voice-board.test.ts b/apps/board/test/voice-board.test.ts new file mode 100644 index 0000000..d75d351 --- /dev/null +++ b/apps/board/test/voice-board.test.ts @@ -0,0 +1,50 @@ +// Unit tests for Voice on the board: line breaking inside the box +// (src/voice/wrap.ts). Run: node --test apps/board/test/ + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { splitLines, tidyText, wrapLines, wrapText } from "../src/voice/wrap.ts"; + +/** Every character 10 units wide. */ +const mono = (s: string) => [...s].length * 10; + +test("wraps at spaces inside the width", () => { + assert.deepEqual(wrapLines("the quick brown fox jumps", 110, mono), ["the quick", "brown fox", "jumps"]); + for (const l of wrapLines("the quick brown fox jumps over the lazy dog", 110, mono)) assert.ok(mono(l) <= 110, l); +}); + +test("keeps spoken new lines and breaks long words", () => { + assert.deepEqual(wrapLines("one\ntwo three", 200, mono), ["one", "two three"]); + assert.deepEqual(wrapLines("supercalifragilistic", 50, mono), ["super", "calif", "ragil", "istic"]); + assert.equal(wrapText("a b", 0, mono), "a b"); +}); + +test("Bangla wraps at spaces and keeps the danda", () => { + const s = "আমি স্কুলে যাই। তুমি কোথায় যাও?"; + const lines = wrapLines(s, 120, mono); + assert.ok(lines.length > 1); + assert.equal(lines.join(" "), s); + assert.ok(lines.every((l) => !l.startsWith("।")) && lines.some((l) => l.includes("যাই।")), JSON.stringify(lines)); +}); + +test("a Bangla word is never split inside a conjunct", () => { + // Grapheme clusters: ক্ষ (ka + virama + ssa) stays whole when a word must break. + const lines = wrapLines("ক্ষক্ষক্ষক্ষ", 20, (s) => [...new Intl.Segmenter(undefined, { granularity: "grapheme" }).segment(s)].length * 10); + assert.ok(lines.every((l) => !l.startsWith("্")), JSON.stringify(lines)); +}); + +test("splitLines: final words and the live tail map onto the wrapped lines", () => { + const lines = splitLines("Hello class, today we", " learn fractions", 120, mono); + assert.deepEqual(lines.map((l) => l.done + l.live), ["Hello class,", "today we", "learn", "fractions"]); + assert.deepEqual(lines[1], { done: "today we", live: "" }); + assert.deepEqual(lines[2], { done: "", live: "learn" }); + // A line holding both. + const mixed = splitLines("Hi", " there", 200, mono); + assert.deepEqual(mixed, [{ done: "Hi", live: " there" }]); + // A spoken new line. + assert.deepEqual(splitLines("one\n", "two", 200, mono).map((l) => l.done + l.live), ["one", "two"]); +}); + +test("tidyText collapses spaces around line breaks", () => { + assert.equal(tidyText("a b \n c"), "a b\nc"); +}); diff --git a/crates/rupok-cli/src/mcp.rs b/crates/rupok-cli/src/mcp.rs index 40fcf5a..4daf300 100644 --- a/crates/rupok-cli/src/mcp.rs +++ b/crates/rupok-cli/src/mcp.rs @@ -50,6 +50,8 @@ current one; show it with `go_to_page` when it is ready. Never delete or replace without asking first. Match the page `scheme` (light/dark) so objects stay themed.\n\ - `point_at`, `step_object`, `replace_items_with_text` (ink to text) and `set_board_theme` help \ you teach on the board.\n\ +- `start_voice_text` / `stop_voice_text`: the teacher speaks and the words appear as text on the board \ +(or, with `mode: \"ask\"`, become a prompt to you); use them only when the teacher asks.\n\ - Page design (`set_page_design`, `set_branding`): when asked for a background, a theme or a school logo. \ Draw it as SVG; keep the content area calm, ink readable (light ink on dark pages) and the logo small in a \ corner; read the current design first by calling the tool with only `path`.\n\ diff --git a/crates/rupok-cli/src/mcp_live.rs b/crates/rupok-cli/src/mcp_live.rs index a912457..a96ed79 100644 --- a/crates/rupok-cli/src/mcp_live.rs +++ b/crates/rupok-cli/src/mcp_live.rs @@ -469,6 +469,42 @@ pub struct AddTableParams { pub page: Option, } +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct StartVoiceTextParams { + /// Left edge of the voice box in slide pixels. Default: below the last + /// voice text, else the middle of the visible page. + #[serde(default)] + pub x: Option, + /// Top edge of the voice box in slide pixels. + #[serde(default)] + pub y: Option, + /// Box width in slide pixels; the words wrap inside it and inside the page. + /// Default 900. + #[serde(default)] + pub w: Option, + /// Spoken language: `en-US` (English) or `bn-BD` (Bangla). Default: the + /// teacher's voice setting. + #[serde(default)] + pub lang: Option, + /// `text` (default): the words go on the board. `ask`: the words become a + /// prompt to the AI chat, with the page attached. + #[serde(default)] + pub mode: Option, + /// `typed` (default) or `handwriting` (written in the handwriting + /// synthesiser; English only). + #[serde(default)] + pub style: Option, +} + +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct StopVoiceTextParams { + /// Throw the words away instead of putting them on the board. + #[serde(default)] + pub cancel: Option, +} + // ------------------------------------------------------------------- tools fn wrap(v: Value) -> Value { @@ -842,6 +878,51 @@ page colour automatically; new text you add picks a readable colour for it. Use }) .await } + + #[tool( + description = "Turn on \"Voice text\" on the board: the teacher talks and their words appear as text \ +in a box on the current page while they speak, wrapped inside the box and the page. Use it when the teacher asks \ +you to \"take dictation\" or \"let me speak the notes\". It switches on the teacher's microphone on the board, \ +with the board's privacy indicator; it is refused when the board has no speech recognition or voice input is \ +off. With `mode: \"ask\"` the words become a prompt to the AI chat instead. Call stop_voice_text to finish; \ +the teacher can also tap the box or press Esc.", + annotations( + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn start_voice_text( + &self, + Parameters(p): Parameters, + ) -> CallToolResult { + self.live_call(Op::StartVoiceText { + x: p.x, + y: p.y, + w: p.w, + lang: p.lang, + mode: p.mode, + style: p.style, + }) + .await + } + + #[tool( + description = "Finish \"Voice text\" on the board: the words heard so far become one normal text item \ +(one undo step; the teacher can edit, move and recolour it), or are thrown away with `cancel: true`. Returns the \ +text and the new item id (or, in `ask` mode, the prompt sent to the chat).", + annotations( + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn stop_voice_text( + &self, + Parameters(p): Parameters, + ) -> CallToolResult { + self.live_call(Op::StopVoiceText { cancel: p.cancel }).await + } } #[cfg(test)] @@ -888,5 +969,7 @@ mod tests { ); let t = serde_json::to_value(schemars::schema_for!(AddTableParams)).unwrap(); assert_eq!(t["properties"]["rows"]["maximum"], 10); + let v = serde_json::to_value(schemars::schema_for!(StartVoiceTextParams)).unwrap(); + assert!(v["properties"]["lang"]["description"].is_string()); } } diff --git a/crates/rupok-live/src/apply.rs b/crates/rupok-live/src/apply.rs index 079e177..0dc727c 100644 --- a/crates/rupok-live/src/apply.rs +++ b/crates/rupok-live/src/apply.rs @@ -204,6 +204,9 @@ fn run(ctx: &mut BoardCtx<'_>, op: &Op, msg: &str, now: f64) -> Result // Shape geometry lives in the board engine (rupok-wasm `live.rs`). Op::AddShape { .. } => Err(LiveError::Unsupported("add_shape")), Op::AddTable { .. } => Err(LiveError::Unsupported("add_table")), + // Voice text needs the board's microphone (apps/board/src/voice/board.ts). + Op::StartVoiceText { .. } => Err(LiveError::Unsupported("start_voice_text")), + Op::StopVoiceText { .. } => Err(LiveError::Unsupported("stop_voice_text")), Op::GoToPage { page } => { let (idx, info) = page_ref(ctx.lesson, ctx.page_id, Some(*page))?; diff --git a/crates/rupok-live/src/op.rs b/crates/rupok-live/src/op.rs index de30925..a73a63d 100644 --- a/crates/rupok-live/src/op.rs +++ b/crates/rupok-live/src/op.rs @@ -440,6 +440,32 @@ pub enum Op { #[serde(default)] delta: Option, }, + /// Start "Voice text" on the board: the teacher's speech appears as text + /// in a box at `x, y` (slide pixels; default the last place or the middle + /// of the page), `w` wide, wrapped inside the page. `mode` is `text` + /// (default) or `ask` (the speech becomes a prompt to the AI chat); + /// `style` is `typed` (default) or `handwriting`; `lang` is a BCP 47 tag + /// (`en-US`, `bn-BD`). Run by the board app, which owns the microphone. + StartVoiceText { + #[serde(default)] + x: Option, + #[serde(default)] + y: Option, + #[serde(default)] + w: Option, + #[serde(default)] + lang: Option, + #[serde(default)] + mode: Option, + #[serde(default)] + style: Option, + }, + /// Stop "Voice text": what was said becomes a text item (one undo step), + /// or is thrown away with `cancel`. Run by the board app. + StopVoiceText { + #[serde(default)] + cancel: Option, + }, } /// How an op touches the board, for the teacher's "Allow AI to edit live" @@ -481,6 +507,8 @@ impl Op { Op::WriteHandwriting { .. } => "write_handwriting", Op::AddShape { .. } => "add_shape", Op::AddTable { .. } => "add_table", + Op::StartVoiceText { .. } => "start_voice_text", + Op::StopVoiceText { .. } => "stop_voice_text", } } @@ -528,6 +556,8 @@ impl Op { Op::WriteHandwriting { .. } => "wrote on the board", Op::AddShape { .. } => "drew a shape", Op::AddTable { .. } => "drew a table", + Op::StartVoiceText { .. } => "started voice text", + Op::StopVoiceText { .. } => "stopped voice text", } } } @@ -570,5 +600,11 @@ mod tests { let t: Op = serde_json::from_str(r#"{"op":"add_table","x":0,"y":0,"rows":3,"cols":4}"#).unwrap(); assert_eq!(t.name(), "add_table"); + let v: Op = + serde_json::from_str(r#"{"op":"start_voice_text","x":100,"y":200,"lang":"bn-BD"}"#) + .unwrap(); + assert_eq!((v.name(), v.access()), ("start_voice_text", Access::Write)); + let v: Op = serde_json::from_str(r#"{"op":"stop_voice_text"}"#).unwrap(); + assert_eq!(v, Op::StopVoiceText { cancel: None }); } } diff --git a/crates/rupok-wasm/src/engine.rs b/crates/rupok-wasm/src/engine.rs index 1b806a9..59c71c3 100644 --- a/crates/rupok-wasm/src/engine.rs +++ b/crates/rupok-wasm/src/engine.rs @@ -2544,6 +2544,56 @@ impl Engine { self.add_box_item(data, now_ms).ok() } + /// A text box at world (`x`, `y`), `w` wide, holding `text` whose lines + /// the caller already broke to fit `w` (Voice text, `voice/wrap.ts`), in + /// `rgba`. Kept on the page when ink is: the box is narrowed to the page + /// width and moved inside it. One undo step; the new item is selected. + #[allow(clippy::too_many_arguments)] + pub fn add_text_box( + &mut self, + x: f64, + y: f64, + w: f64, + text: &str, + size: f64, + rgba: u32, + now_ms: f64, + ) -> Option { + let ok = |v: f64| v.is_finite(); + if text.trim().is_empty() + || !(ok(x) && ok(y) && ok(w) && ok(size)) + || w <= 0.0 + || size <= 0.0 + { + return None; + } + let size = size.clamp(4.0, 2000.0); + let lines = text.split('\n').count().max(1) as f64; + let h = lines * size * 1.25; + let (mut x, mut y, mut w) = (x, y, w.clamp(size, 20_000.0)); + if let Some(r) = self.ink_bounds() { + let r = r.map(f64::from); + w = w.min(r[2] - r[0]); + x = x.clamp(r[0], r[2] - w); + y = y.clamp(r[1], (r[3] - h).max(r[1])); + } + let data = ItemData::Text(TextData { + latex: false, + geom: BoxGeom { + x, + y, + w, + h, + rot: 0.0, + }, + text: text.into(), + size, + color: rgba, + stamp: None, + }); + self.add_box_item(data, now_ms).ok() + } + /// Place a classroom stamp centred on the screen point (`x`, `y`): a /// text item with the `stamp` key, `w` × `h` world units, holding /// `text` (the emoji or label older readers show). Kept on the page @@ -4165,6 +4215,49 @@ pub(crate) mod tests { assert_eq!(v.stroke_count(), 3); } + #[test] + fn add_text_box_stays_on_the_page_in_one_undo_step() { + let mut e = engine(); + let t = e + .add_text_box(1700.0, 1050.0, 600.0, "one\ntwo", 48.0, 0x087f5bff, 1.0) + .unwrap(); + let Ok(Item { + data: ItemData::Text(d), + .. + }) = e.lesson.item(&e.page.clone(), &t) + else { + panic!("not a text item"); + }; + // Moved left and up so the whole box is on the 1920×1080 slide. + assert_eq!((d.geom.x, d.geom.w), (1320.0, 600.0)); + assert_eq!(d.geom.y, 1080.0 - 2.0 * 48.0 * 1.25); + assert_eq!((d.text.as_str(), d.color), ("one\ntwo", 0x087f5bff)); + assert_eq!(e.selection(), [t.clone()]); + // One undo step takes it away. + assert!(e.undo()); + assert!(e.lesson.item(&e.page.clone(), &t).is_err()); + // Wider than the page: narrowed to it. Nothing to say: nothing added. + let t = e + .add_text_box(-50.0, 10.0, 5000.0, "wide", 40.0, 0, 2.0) + .unwrap(); + let Ok(Item { + data: ItemData::Text(d), + .. + }) = e.lesson.item(&e.page.clone(), &t) + else { + panic!("not a text item"); + }; + assert_eq!((d.geom.x, d.geom.w), (0.0, 1920.0)); + assert!( + e.add_text_box(0.0, 0.0, 100.0, " ", 40.0, 0, 3.0) + .is_none() + ); + assert!( + e.add_text_box(0.0, f64::NAN, 100.0, "x", 40.0, 0, 3.0) + .is_none() + ); + } + #[test] fn bring_to_front_many_and_resize_text() { let mut e = engine(); diff --git a/crates/rupok-wasm/src/lib.rs b/crates/rupok-wasm/src/lib.rs index 9ffab26..14a28aa 100644 --- a/crates/rupok-wasm/src/lib.rs +++ b/crates/rupok-wasm/src/lib.rs @@ -835,6 +835,22 @@ mod web { self.engine.add_text(x, y, text, size, now()) } + /// Voice text: a text box at world (`x`, `y`), `w` wide, its lines + /// already broken to fit, in 0xRRGGBBAA; kept on the page. One undo + /// step. Returns its id. + #[allow(clippy::too_many_arguments)] + pub fn add_text_box( + &mut self, + x: f64, + y: f64, + w: f64, + text: &str, + size: f64, + rgba: u32, + ) -> Option { + self.engine.add_text_box(x, y, w, text, size, rgba, now()) + } + /// Place a classroom stamp (`star`, `tick`, `badge`, `emoji`, …) /// centred on the screen point, `w` × `h` world units; `text` is /// the emoji or label a reader without stamps shows. Returns its id. diff --git a/docs/ai-agents.md b/docs/ai-agents.md index a9380fb..ab1e1f0 100644 --- a/docs/ai-agents.md +++ b/docs/ai-agents.md @@ -321,9 +321,16 @@ tools (`get_lesson_outline`, `add_page`, `add_text`, `add_smart_object`, | `point_at(x, y, w?, h?, label?, seconds?)` | A temporary laser ring or highlight box (not saved). | | `write_handwriting(lines, anchor?, style?, speed?, color?, size?, step_mode?)` | Write lines (text with inline LaTeX) in handwriting, animated stroke by stroke, below the anchor; one undo step. See [Solve this](#solve-this). | | `set_board_theme(page_color?, pattern?, ui?)` | Page colour (white, paper, chalkboard, blackboard, #hex) and pattern; app light/dark. | +| `start_voice_text(x?, y?, w?, lang?, mode?, style?)` | Live only. Turn on [Voice on the board](#voice-on-the-board): the teacher speaks and the words appear in a box at `x, y`, `w` wide (default: under the last voice text, else mid-page), wrapped inside the page. `lang` `en-US` or `bn-BD`; `mode` `text` (default) or `ask` (the words become a chat prompt); `style` `typed` (default) or `handwriting`. Refused when the board has no speech recognition or voice input is off. | +| `stop_voice_text(cancel?)` | Live only. Finish: the words become one text item (one undo step) and the result has `text` and `item_id`; `cancel: true` throws them away. | | `set_page_design(path, page?, all_pages?, color?, pattern?, background_svg?, background_image?, background_fit?, background_opacity?, background_dim?, remove_background?)` | Page design: colour, pattern and a background image (SVG, or base64 PNG/JPEG), for a page or every page. Only `path`: read the design. Live or on a file. | | `set_branding(path, scope?, page?, logo_svg?, logo_image?, logo_corner?, logo_x?, logo_y?, logo_width?, logo_opacity?, remove_logo?, school?, teacher?, class?, date?, text_position?, text_align?, hidden?, remove?)` | Logo and header/footer line on every page (`scope: "lesson"`) or one page; text placeholders `{lesson}`, `{page}`, `{pages}`, `{date}`, `{teacher}`, `{school}`, `{subject}`, `{course}`, `{chapter}`. Only `path`: read it. | +`add_text` with a `w` wraps on the board: the board breaks the lines to fit +`w`, measured with its own font, and stores them as `\n` (text items never +reflow by themselves, so every reader shows the same lines). On a lesson file +the text is stored as given. + Every change is one undo step on the board, tagged with the agent's name in the lesson history (the Loro commit message `rupok-agent/1 {"agent":"Claude Code","op":"add_text"}`). @@ -429,6 +436,50 @@ screen where the teacher writes digits, letters and maths symbols once; the samples (writing units, per device, `rupok.handwriting.v1`) drive both the writer and the recogniser's user templates. +## Voice on the board + +Teachers talk during class and don't want to write whole sentences. The +dock's **Voice text** tool (a mic with a T, in Prepare and Teach) puts what +they say on the board while they say it: + +- **Place:** pick the tool, then tap the page (or drag across it to set the + width). A voice box opens there with a pulsing mint mic and starts + listening. Drag the box to move it, drag its right edge to change the + width. +- **Live words:** words still being recognised show lighter; final words + turn into the ink colour. Text wraps inside the box, and the box stays on + the page (it moves up, then shrinks its text, rather than run off the + slide). +- **Punctuation and lines:** spoken punctuation works as in every field + ("comma", "full stop", "question mark", "new line"; কমা, দাঁড়ি, + প্রশ্নবোধক চিহ্ন, নতুন লাইন). A pause of about 2 s starts a new line. +- **Finish:** tap the box, press Esc or ✓. The words become a normal text + item (editable, resizable, recolourable), with the line breaks the teacher + saw. **One undo step per box**: the box is not in the lesson until it is + finished, so Ctrl+Z after finishing removes the whole voice text. ✕ + discards it. +- **Teach:** hold the dock button to talk (push-to-talk): the box opens under + the last voice text and its words go on the board on release, the pen stays + the tool, one undo step per hold. With the tool on, Space or a clicker's + "blank" key (B or .) toggles listening. +- **On the box:** EN / বাং; **Text ↔ Ask AI**; typed ↔ **hand-written** + (the Solve this synthesiser, English; Bangla stays typed); where the audio + goes (offline Whisper on this computer, or the browser's cloud service). +- **Ask AI:** the words become a prompt to the in-app chat with the page (or + the selection) attached. A small bubble confirms it; in Teach the chat + stays closed. Not connected yet: the chat opens with the words in its box. + +Settings → General → Voice on the board: what a new box does (text or Ask +AI), tap or hold to talk, hand-written by default, the pause before a new +line (0 turns it off), and whether students may ask the AI by voice in +Student view (the tool can then be added to Student view in Teaching modes; +students never write on the board). + +Agents use `start_voice_text` / `stop_voice_text` (live only) when the teacher +asks ("take my dictation", "let me speak the notes"). The microphone is the +teacher's: the board shows it is listening, and the ops need *Allow AI to +edit live*. + ## Pairing and security - `rupok mcp` listens on **127.0.0.1 only**, never on the network. @@ -542,8 +593,10 @@ An operation is `{"op": "", …fields}`; the names and fields are the `update_smart_object`, `add_media`, `add_model`, `delete_item`, `set_page_background`, `set_page_design`, `set_branding`, `replace_items_with_text`, `step_object`, `write_handwriting`, `add_shape`, -`add_table`; the last two run in the board's engine, `crates/rupok-wasm` -`engine/insert.rs`). `add_media` +`add_table`, `start_voice_text`, `stop_voice_text`; `add_shape` and +`add_table` run in the board's engine, `crates/rupok-wasm` +`engine/insert.rs`, the voice ops in the board app, which owns the +microphone, `apps/board/src/voice/board.ts`). `add_media` carries a `url` (YouTube or a trusted embed) or a base64 `file_base64` (video or audio); `add_model` a base64 `.glb` as `file_base64`. The MCP tools `add_youtube`, `add_media` and `add_3d_model` read files from the workspace and diff --git a/docs/ui-config.md b/docs/ui-config.md index 92a8415..df7519a 100644 --- a/docs/ui-config.md +++ b/docs/ui-config.md @@ -101,6 +101,7 @@ Settings → Teaching modes) resets that memory, so the config takes effect. | `laser` | Laser pointer | prepare, teach | | `text` | Text (key `T`) | prepare, teach | | `stamp` | Stamps (key `K`) | prepare, teach | +| `voice` | Voice text: speak and the words go on the board; hold for push-to-talk ([Voice on the board](ai-agents.md#voice-on-the-board)) | prepare, teach; view only with Settings → Voice on the board → "Students may ask the AI by voice" (Ask AI only) | | `shape` | The Shapes picker's tool: every shape and table (key `S` opens the picker) | prepare, teach | | `rect`, `ellipse`, `line`, `arrow` | Single shape tools (keys `R`, `O`, `N`, `A`) | prepare, teach | | `hand` | Pan | all | @@ -315,7 +316,7 @@ student view gets no pages panel. "type": "array", "uniqueItems": true, "items": { - "enum": ["pen", "highlighter", "eraser", "lasso", "laser", "text", "stamp", "rect", "ellipse", "line", "arrow", + "enum": ["pen", "highlighter", "eraser", "lasso", "laser", "text", "voice", "stamp", "rect", "ellipse", "line", "arrow", "hand", "interact", "smartink", "undo", "redo", "replay", "pager", "exit"] } }, @@ -338,7 +339,7 @@ student view gets no pages panel. "type": "array", "uniqueItems": true, "items": { - "enum": ["shapes", "lasso", "text", "stamp", "rect", "ellipse", "line", "arrow", "hand", "interact", "smartink", + "enum": ["shapes", "lasso", "text", "voice", "stamp", "rect", "ellipse", "line", "arrow", "hand", "interact", "smartink", "redo", "replay", "pager", "exit"] } } diff --git a/skills/AGENTS.md b/skills/AGENTS.md index c6c8e03..fd997d6 100644 --- a/skills/AGENTS.md +++ b/skills/AGENTS.md @@ -74,6 +74,8 @@ they have open: they click **Connect AI** and give you a 6-digit code; call `get_selection` show you the board; - `add_page_after_current`, `go_to_page`, `step_object`, `point_at`, `replace_items_with_text` (ink to text) and `set_board_theme` help you teach; +- `start_voice_text` / `stop_voice_text` let the teacher dictate onto the + board (only when they ask); - `add_shape` (rect, circle, arrow, star, Venn, flowchart, number line, axes, speech bubble, …) and `add_table` (rows × cols with cell text) draw clean shapes the teacher can resize, fill and edit. diff --git a/skills/rupok-live-board/SKILL.md b/skills/rupok-live-board/SKILL.md index 83ddd41..88d1150 100644 --- a/skills/rupok-live-board/SKILL.md +++ b/skills/rupok-live-board/SKILL.md @@ -181,7 +181,7 @@ House rules (projectors in bright rooms, chalk-dusted fingers): | `get_board_status`, `connect_board(code)` | Pairing. | | `get_current_page(page?)`, `get_selection()`, `get_page_snapshot(page?, item_ids?, region?, width?)` | Read and see. | | `add_page_after_current(title?, pattern?, color?, show?)`, `go_to_page(page)` | Pages. | -| `add_text`, `add_smart_object`, `update_smart_object`, `delete_item`, `set_page_background`, `add_page`, `get_lesson_outline` with `path: "live"` | Edit the open lesson. | +| `add_text`, `add_smart_object`, `update_smart_object`, `delete_item`, `set_page_background`, `add_page`, `get_lesson_outline` with `path: "live"` | Edit the open lesson (`add_text` with `w` wraps inside `w` on the board). | | `add_youtube`, `add_media`, `add_3d_model` with `path: "live"` | A YouTube video or trusted web embed by link, a video/audio file, or a `.glb` 3D model from the workspace (files are sent to the board). | | `replace_items_with_text(item_ids, text, …)` | Ink to text (confirm first). | | `step_object(item_id?, step?, delta?)` | Next / back inside a Smart Object. | @@ -190,6 +190,7 @@ House rules (projectors in bright rooms, chalk-dusted fingers): | `point_at(x, y, w?, h?, label?, seconds?)` | Show the class where to look. | | `write_handwriting(lines, anchor?, style?, speed?, color?, size?, step_mode?)` | Write a solution in handwriting next to the problem (see Solve this). | | `set_board_theme(page_color?, pattern?, ui?)` | Chalkboard, grid, dark mode. | +| `start_voice_text(x?, y?, w?, lang?, mode?, style?)`, `stop_voice_text(cancel?)` | Live only: the teacher speaks and the words appear as text in a box on the page (`lang` `en-US` or `bn-BD`; `mode: "ask"` makes them a chat prompt). Only when the teacher asks; stop puts the words on the board as one text item. | | `set_page_design(path, page?, all_pages?, color?, pattern?, background_svg?, background_image?, background_fit?, background_opacity?, background_dim?, remove_background?)` | Page colour, pattern and background image (see Page design). | | `set_branding(path, scope?, page?, logo_svg?, logo_image?, logo_corner?, logo_width?, …, school?, teacher?, class?, date?, text_position?, text_align?, hidden?, remove?)` | Logo and header/footer on every page or one. |