diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 45e9d52..9acb729 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -13,6 +13,7 @@ - [ ] `cargo fmt --all --check` and `cargo clippy --workspace -- -D warnings` are clean; the wasm build still works. - [ ] **Perf-sensitive change?** (ink, core, render, the engine's pointer path, package I/O) I ran `cargo run -p rupok-bench --release` before and after and pasted both budget tables below. Otherwise: not perf-sensitive. - [ ] **Format, protocol or SDK change?** `spec/` (and `packages/object-sdk/index.d.ts`) is updated in this PR, with a link to the accepted RFC. Otherwise: no spec impact. +- [ ] **Agent-controllable:** live op / MCP tool added (and a row in `docs/agent-capabilities.md`), or marked *teacher only* with a reason. Otherwise: no user-facing change. - [ ] Docs updated (README, ROADMAP status, plan doc) if behaviour or status changed.
diff --git a/AGENTS.md b/AGENTS.md index 7f6363c..7757431 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -16,12 +16,12 @@ a Tauri 2 shell (planned). Status: Phase 0, pre-alpha. See | `crates/rupok-ink` | Pen input pipeline, wasm-safe | `StrokeBuilder` (wet ink), `filter::OneEuro2`, `pressure::PressureCurve`, `simplify`, `codec::{encode_points, decode_points}` (point codec v1), `MIN_WIDTH_RATIO`, `point_radius`, `math` (handwritten maths → LaTeX), `write` (text + LaTeX → timed handwriting strokes) | | `crates/rupok-core` | Lesson document on Loro | `Lesson` (`doc.rs`: all mutations), model types (`model.rs`: `ItemData`, `StrokeData`, `ObjectData`, `PageSpec`…), `Scene` (`scene.rs`: R*-tree hit-test, eraser, lasso), `DOC_FORMAT` | | `crates/rupok-format` | `.rpk` package and Smart Object bundles (Apache-2.0) | `Package::{read, write, from_lesson, add_asset, content_markdown}`, `readable` (derived `README.md`/`content.md`/`content.json`), `ObjectBundle::{from_single_html, from_files, from_dir, validate}`, `LIBS`, `safe_path`, `FORMAT_VERSION`, `MIMETYPE`, `media` (embed allowlist, `parse_link`, `embed_url`, `prepare`), `model3d` (3D viewer object) | -| `crates/rupok-live` | Live agent bridge shared by the board and `rupok mcp --live` | `protocol.rs` (WebSocket protocol v1: channels, ports, origin/host checks), `op.rs` (`Op`), `apply.rs` (`apply`: one attributed commit per agent op), `attribution.rs`, `sync` | +| `crates/rupok-live` | Live agent bridge shared by the board and `rupok mcp --live` | `protocol.rs` (WebSocket protocol v1: channels, ports, origin/host checks), `op.rs` (`Op`), `apply.rs` (`apply`: one attributed commit per agent op), `items.rs` (pages and items: move, align, restyle, scale, draw…), `stamps.rs` (built-in and custom stamps, Smart stamps), `attribution.rs`, `sync` | | `crates/rupok-render` | wgpu ink renderer | `InkRenderer` (SDF capsules, chunk culling, cached dry layer, wet layer), `Camera`, `Gpu::headless`, `ink.wgsl` | | `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) | +| `crates/rupok-cli` | `rupok` binary: CLI and MCP server | `cli.rs` (clap), `ops.rs` (shared operations), `mcp.rs` + `tools.rs` (lesson tools), `mcp_agent.rs` (agent control: pages, items, stamps, modes, export, library, settings, dock; docs/agent-capabilities.md), `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` + `agentControl.ts` + `snapshot.ts` + `components/LivePanel.tsx` (Connect AI; board-side agent ops), `customStamps.ts` + `stampLib.ts` + `components/StampEditor.tsx` (My stamps), `components/DockEditor.tsx` (Customize dock), `agentSettings.ts` (settings an agent may change), `chat.ts` + `components/ChatPanel.tsx` + `markdown.ts` (AI chat), `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` | @@ -103,3 +103,22 @@ The toolchain (1.100, edition 2024) is pinned in `rust-toolchain.toml`. asks. 7. **Stay in scope.** Other contributors (human or agent) may be editing other parts of the tree; change only what your task needs. +8. **Agent-first: every feature is agent-controllable.** Anything a teacher + can do, their AI agent must be able to do on their behalf. A new + user-facing feature ships, in the same pull request, with matching live + op(s) in `crates/rupok-live` (`op.rs`, run in `apply`/`items.rs`/… or + the board's `agentControl.ts`), MCP tool(s) (`crates/rupok-cli/src/ + mcp*.rs`, working on a file and with `path: "live"` where that makes + sense), docs in `docs/ai-agents.md` and `skills/rupok-live-board/ + SKILL.md`, tests, and a row in `docs/agent-capabilities.md` + (`tests/agent_capabilities.rs` fails CI for a setting, dock button or op + without one). Guardrails, always: + - one attributed undo step per agent action (one Loro commit tagged + with `rupok_live::commit_message`); + - respect **Allow AI to edit live** and Student view (the op's `Access`); + - settings and mode changes ask the teacher's permission in the chat like + edits, and can be undone from the AI chip; + - agent-written code runs only in the Smart Object sandbox; + - AI keys, accounts, payments, storage locations and permissions stay + teacher only. When an agent must not do something, mark it *teacher + only* in the matrix with the reason. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 137d79c..b557571 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -62,7 +62,16 @@ node --test "packages/object-sdk/test/*.test.mjs" 6. If the change touches the file format, the Smart Object protocol or the SDK API, update `spec/` in the same PR. A non-editorial spec change needs an accepted RFC. -7. Open the PR. On your first PR, sign the Contributor License Agreement +7. **Agent-first.** A user-facing feature ships with its agent path: a live + op and an MCP tool (on a file and live where that makes sense), docs in + `docs/ai-agents.md` and the `rupok-live-board` skill, tests, and a row in + `docs/agent-capabilities.md` (CI checks settings, dock buttons and live + ops against it). Agent actions are one attributed undo step, respect + *Allow AI to edit live* and Student view, ask permission for settings and + mode changes, and run agent code only in the Smart Object sandbox. AI + keys, accounts, payments and permissions stay teacher only: mark such + rows *teacher only* with the reason. See AGENTS.md, rule 8. +8. Open the PR. On your first PR, sign the Contributor License Agreement (CLA, below); a bot will ask. CI must be green. Commit messages: an imperative subject of 72 characters or fewer, with an area diff --git a/ROADMAP.md b/ROADMAP.md index 627acff..653215f 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -65,6 +65,7 @@ first (see [CONTRIBUTING.md](CONTRIBUTING.md#rfcs)). | 💡 | Brand kit: school colours, fonts and logo as theme tokens for every object | | | | ✅ | Agent panel (ACP): chat with your own AI agent inside Rupok (v0.2.0: Claude, Codex, OpenCode through `rupok agent`) | [acp-agent-panel](docs/roadmap/acp-agent-panel.md) | advanced | | ✅ | Live agent edits during class, merged into the open lesson (v0.2.0, `rupok mcp --live`, [docs/ai-agents.md](docs/ai-agents.md)) | [acp-agent-panel § Live edits](docs/roadmap/acp-agent-panel.md#live-edits) | advanced | +| 🚧 | Agent-first: every part of Rupok controllable by the teacher's agent (pages, items, stamps, modes, export, Library, settings, Smart Dock), checked in CI against [docs/agent-capabilities.md](docs/agent-capabilities.md); custom stamps and Smart stamps; a customisable dock (groups, split dock, sizes, named layouts). Format keys (root `stamps`) and Smart stamps need the RFC | `crates/rupok-live` (`items.rs`, `stamps.rs`), `crates/rupok-cli/src/mcp_agent.rs`, `apps/board/src/agentControl.ts`, [spec § Custom stamps](spec/rupok-format.md#custom-stamps) | advanced | | 📋 | Replay with audio | [replay-audio](docs/roadmap/replay-audio.md) | intermediate | | 📋 | LAN "send to board" from laptop or phone | [lan-send](docs/roadmap/lan-send.md) | intermediate | | 🚧 | Web viewer (PWA): open any `.rpk` in a browser, offline. Read-only student view at `/board/?view` done; the `/open/` page hands a picked file to it; installed-PWA "Open with" (`launchQueue`) done; offline service worker done ([offline.md](docs/offline.md)) | [web-viewer](docs/roadmap/web-viewer.md) | intermediate | diff --git a/apps/board/src/App.tsx b/apps/board/src/App.tsx index 0ffbfcd..761de4c 100644 --- a/apps/board/src/App.tsx +++ b/apps/board/src/App.tsx @@ -32,6 +32,8 @@ import { isPhone, pagesDrawer, pagesShown } from "./viewport"; import { PageDesignHost } from "./components/PageDesign"; import { drawCursor } from "./wetInk"; import { Celebrate, QuickMenu } from "./components/Stamps"; +import { DockEditor } from "./components/DockEditor"; +import { StampEditorHost } from "./components/StampEditor"; import { UpdateNotice } from "./updates/UpdateNotice"; import { startUpdateChecks } from "./updates/updates"; import { Tour } from "./tour/Tour"; @@ -174,6 +176,8 @@ export default function App() { + + {/* Connect AI: the teacher's own agent edits the board live (live.ts). */} diff --git a/apps/board/src/agentControl.ts b/apps/board/src/agentControl.ts new file mode 100644 index 0000000..e29bc70 --- /dev/null +++ b/apps/board/src/agentControl.ts @@ -0,0 +1,370 @@ +// Board-app operations for the teacher's AI agent (docs/agent-capabilities.md): +// the parts of Rupok that are not the lesson document. Modes, the view, +// replay, celebrations, the current tool, the agent's own undo, PDF export, +// the Library, settings and the Smart Dock. live.ts calls `runBoardOp` for +// these and wraps the stamp operations with the device library ("My +// stamps") around the document op the core runs. +// +// The board enforces the rules before it gets here (live.ts): "Allow AI to +// edit live", Student view, and the agent's permission prompts in the chat. +// Settings and dock changes return an `undo`, which the AI chip's Undo runs. + +import type { Controller } from "./controller"; +import { type Mode, type ToolbarItem, DEFAULT_MODES, DOCK_PRESETS, TOOLBAR_ITEMS, CORE_TOOLS, SHAPES_PIN, dockWarnings, sanitizeMode, type DockConfig } from "./modes"; +import { type Prefs, isView, mode, modeConfig, pages, prefs, setColor, setHlColor, setPrefs, setSizes, sizes, title, type Tool } from "./state"; +import { celebrate, type CelebrateKind, freshStamps } from "./stamps"; +import { agentSettings, setAgentSetting } from "./agentSettings"; +import { applyPreset, placeable, savePreset, savedPresets } from "./components/DockEditor"; +import { resetDock } from "./dock"; +import { isBrush, setBrushOf } from "./brushes"; +import { myStamps, resolveStamp } from "./stampLib"; +import { deleteStamp as deleteLibStamp, saveStamp } from "./customStamps"; + +function b64(bytes: Uint8Array): string { + let s = ""; + for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000)); + return btoa(s); +} + +export class AgentOpError extends Error { + constructor(message: string, public data?: unknown) { + super(message); + } +} + +export interface BoardOpResult { + result: unknown; + /** Puts a settings or dock change back (the AI chip's Undo). */ + undo?: () => void; + /** The board changed what it shows (refresh). */ + changed?: boolean; +} + +/** Ops this module handles (the rest go to the core's `live_apply`). */ +export const BOARD_OPS = new Set([ + "set_mode", "zoom_to", "fit_page", "start_replay", "stop_replay", "celebrate", "set_tool", "undo", "export_pdf", + "library_list", "library_open", "library_create_lesson", "library_move", "library_rename", "library_trash", + "get_settings", "set_setting", "get_dock_layout", "set_dock_layout", "list_dock_items", "save_dock_preset", "apply_dock_preset", +]); + +const fail = (m: string): never => { + throw new AgentOpError(m); +}; +const num = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : undefined); +const hexColor = (s: unknown): number | undefined => { + if (typeof s !== "string" || !/^#?[0-9a-f]{6}$/i.test(s.trim())) return undefined; + return ((parseInt(s.trim().replace("#", ""), 16) << 8) | 0xff) >>> 0; +}; + +/** Snapshot of the prefs a settings or dock change touches, for its undo. */ +function prefsUndo(c: Controller, keys: (keyof Prefs)[]): () => void { + const before: Partial = {}; + for (const k of keys) (before as any)[k] = structuredClone(prefs()[k]); + return () => { + setPrefs(before); + c.applyPrefs(); + resetDock("prepare"); + resetDock("teach"); + c.updateInsets(mode() === "teach"); + }; +} + +const MODE_OF: Record = { prepare: "prepare", teach: "teach", student: "view", view: "view" }; + +export async function runBoardOp(c: Controller, op: any, agent: string, lastAgentEdit: () => boolean): Promise { + switch (op.op) { + // ------------------------------------------------------------ view + case "set_mode": { + const m = MODE_OF[String(op.mode)] ?? fail("mode must be prepare, teach or student"); + if (isView() && m !== "view") fail("The board is in Student view; only the teacher can leave it."); + c.setMode(m); + return { result: { mode: op.mode, page: c.board.page_index() + 1 }, changed: true }; + } + case "fit_page": + c.board.fit_page(); + return { result: { fitted: true }, changed: true }; + case "zoom_to": { + const z = num(op.zoom) ?? 1; + if (z < 0.1 || z > 8) fail("zoom must be between 0.1 and 8 (1 = the fitted slide)"); + const r = c.root.getBoundingClientRect(); + const fit = c.board.fit_zoom() || 1; + const cam = c.board.camera(); + const zoom = fit * z; + const cx = num(op.x) ?? cam[0] + r.width / 2 / cam[2]; + const cy = num(op.y) ?? cam[1] + r.height / 2 / cam[2]; + c.board.set_camera(cx - r.width / 2 / zoom, cy - r.height / 2 / zoom, zoom); + return { result: { zoom: z, x: Math.round(cx), y: Math.round(cy) }, changed: true }; + } + case "start_replay": { + if (op.page !== undefined) { + const n = num(op.page); + if (!n || n < 1 || n > pages().length) fail(`page ${op.page} does not exist; the lesson has ${pages().length} page(s)`); + c.board.goto_page(n! - 1); + } + const speed = Math.min(8, Math.max(0.5, num(op.speed) ?? 2)); + const d = c.board.replay_start(); + c.board.replay_play(true, speed); + return { result: { page: c.board.page_index() + 1, duration_s: Math.round(d / 100) / 10, speed }, changed: true }; + } + case "stop_replay": + c.board.replay_stop(); + return { result: { stopped: true }, changed: true }; + case "celebrate": { + const k = (op.kind ?? "stars") as CelebrateKind; + if (!["stars", "confetti", "hearts"].includes(k)) fail("kind must be stars, confetti or hearts"); + celebrate(k); + return { result: { celebrated: k } }; + } + case "set_tool": { + const tools: Tool[] = ["pen", "highlighter", "eraser", "lasso", "laser", "text", "shape", "stamp", "hand", "interact"]; + const t = (op.tool === "select" ? "lasso" : op.tool) as Tool; + if (!tools.includes(t)) fail(`tool must be one of ${tools.join(", ")}`); + if (isView() && t !== "hand" && t !== "interact") fail("Student view only pans and uses Smart Objects"); + const kind = t === "highlighter" ? "highlighter" : t === "shape" ? "shape" : "pen"; + if (op.brush !== undefined) { + if (!isBrush(op.brush)) fail("brush must be a pen style such as pen, ballpoint, fountain, marker, pencil, chalk, brush, dashed, dotted, neon or rainbow"); + setBrushOf(kind, op.brush); + } + if (op.color !== undefined) { + const col = hexColor(op.color) ?? fail("color must look like #rrggbb"); + if (t === "highlighter") setHlColor(col); + else setColor(col); + c.board.set_color(col); + } + if (op.width !== undefined) { + const w = num(op.width); + if (!w || w < 0.5 || w > 200) fail("width must be 0.5 to 200"); + setSizes({ ...sizes(), [t === "highlighter" ? "highlighter" : t === "eraser" ? "eraser" : "pen"]: w as number }); + c.board.set_width(w!); + } + c.setTool(t); + c.applyPrefs(); + return { result: { tool: t } }; + } + case "undo": { + if (!lastAgentEdit()) fail("Your last change is no longer the newest one on the board (the teacher has changed it since), so it was not undone. Fix it with another edit, or ask the teacher."); + c.board.undo(); + return { result: { undone: true }, changed: true }; + } + + // ---------------------------------------------------------- export + case "export_pdf": { + const n = pages().length; + const sel = parsePages(String(op.pages ?? "all"), c.board.page_index(), n); + const layout = ({ slides: "slides", "handout-2": "handout2", "handout-3": "handout3", handout2: "handout2", handout3: "handout3" } as const)[String(op.layout ?? "slides") as "slides"] ?? fail("layout must be slides, handout-2 or handout-3"); + const { exportPdf } = await import("./export-pdf"); + const bytes = await exportPdf(c, { pages: sel, layout, printFriendly: !!op.print_friendly, includeInk: op.ink !== false, title: title() }, () => {}, new AbortController().signal); + let saved: string | null = null; + if (op.download) { + const { savePdfBytes } = await import("./platform"); + saved = await savePdfBytes(`${title().replace(/[\\/:*?"<>|]+/g, "-") || "lesson"}.pdf`, bytes); + } + return { result: { title: title(), pages: sel.length, layout: op.layout ?? "slides", bytes: bytes.length, saved_on_board: saved, pdf_base64: b64(bytes) } }; + } + + // ---------------------------------------------------------- library + case "library_list": + case "library_open": + case "library_create_lesson": + case "library_move": + case "library_rename": + case "library_trash": + return library(c, op); + + // ---------------------------------------------------------- settings + case "get_settings": + return { result: { settings: agentSettings(), note: "change one with set_setting(key, value); AI keys, accounts, payments, storage and permissions are not listed: they are the teacher's alone" } }; + case "set_setting": { + const { result, undo } = setAgentSetting(String(op.key), op.value); + c.applyPrefs(); + c.updateInsets(false); + return { result, undo, changed: true }; + } + + // -------------------------------------------------------------- dock + case "get_dock_layout": { + const m = dockMode(op.mode); + const cfg = modeConfig(m); + return { result: { mode: m, dock: cfg.dock, tools: cfg.tools, warnings: dockWarnings(m, cfg) } }; + } + case "list_dock_items": { + const items = [...TOOLBAR_ITEMS.map((t) => ({ id: t.id, label: t.label, key: t.key })), { id: SHAPES_PIN.id, label: SHAPES_PIN.label }] + .filter((t) => t.id !== "rect" && t.id !== "ellipse" && t.id !== "line" && t.id !== "arrow" && t.id !== "shape") + .map((t) => ({ ...t, always: CORE_TOOLS.includes(t.id as ToolbarItem), prepare: placeable("prepare").includes(t.id as any), teach: placeable("teach").includes(t.id as any) })); + return { + result: { + items, + positions: ["auto", "left", "right", "top", "bottom", "bottom-left", "bottom-right", "top-left", "top-right"], + sizes: ["s", "m", "l"], + presets: [...DOCK_PRESETS.map((p) => ({ name: p.name, hint: p.hint, builtin: true })), ...savedPresets().map((p) => ({ name: p.name, builtin: false }))], + example: { position: "left", size: "l", groups: [{ label: "Ink", items: ["pen", "highlighter", "eraser"] }], split: { position: "right", groups: [{ items: ["undo", "redo"] }, { items: ["pager"] }] } }, + }, + }; + } + case "set_dock_layout": { + const m = dockMode(op.mode); + const layout = op.layout; + if (!layout || typeof layout !== "object" || Array.isArray(layout)) fail("layout must be an object, e.g. {\"position\": \"left\", \"groups\": [{\"items\": [\"pen\", \"eraser\"]}]}"); + const known = new Set(["position", "orientation", "minimized", "pinned", "groups", "split", "size", "sizes", "large"]); + const unknown = Object.keys(layout).filter((k) => !known.has(k)); + if (unknown.length) fail(`unknown layout keys: ${unknown.join(", ")} (allowed: ${[...known].join(", ")})`); + const placeableIds = new Set([...placeable(m), "rect", "ellipse", "line", "arrow", "shape"]); + const items = [...(layout.groups ?? []), ...(layout.split?.groups ?? [])].flatMap((g: any) => (Array.isArray(g) ? g : g?.items ?? [])); + const bad = items.filter((x: unknown) => typeof x !== "string" || !placeableIds.has(x)); + if (bad.length) fail(`not dock buttons in ${m === "teach" ? "Teach" : "Prepare"}: ${bad.join(", ")} (list_dock_items shows the ids)`); + const undo = prefsUndo(c, ["modes"]); + const cur = modeConfig(m); + const dock: Partial = { ...cur.dock, ...layout }; + // A new grouping replaces the old one; a layout without groups keeps them. + if ("groups" in layout && !layout.groups) delete dock.groups; + const next = sanitizeMode(m, { chrome: cur.chrome, tools: cur.tools, dock }); + setPrefs({ modes: { ...prefs().modes, [m]: next } }); + resetDock(m); + c.updateInsets(mode() === "teach"); + return { result: { mode: m, dock: next.dock, warnings: dockWarnings(m, next) }, undo, changed: true }; + } + case "save_dock_preset": { + const name = String(op.name ?? "").trim(); + if (!name) fail("name is required"); + if (DOCK_PRESETS.some((p) => p.name.toLowerCase() === name.toLowerCase())) fail(`“${name}” is a built-in layout; pick another name`); + const modes = (op.modes ?? ["prepare", "teach"]).map((x: string) => dockMode(x)) as ("prepare" | "teach")[]; + const undo = prefsUndo(c, ["dockPresets"]); + const p = savePreset(name, modes); + return { result: { saved: p.name, modes: Object.keys(p.modes) }, undo }; + } + case "apply_dock_preset": { + const name = String(op.name ?? "").trim().toLowerCase(); + const p = [...DOCK_PRESETS, ...savedPresets()].find((x) => x.name.toLowerCase() === name) + ?? fail(`no layout “${op.name}”; list_dock_items shows the layouts`); + const undo = prefsUndo(c, ["modes", "hand"]); + applyPreset(p!); + return { result: { applied: p!.name, prepare: modeConfig("prepare").dock, teach: modeConfig("teach").dock }, undo, changed: true }; + } + } + throw new AgentOpError(`the board does not know \`${op.op}\``); +} + +function dockMode(m: unknown): "prepare" | "teach" { + if (m === undefined || m === null) return mode() === "teach" ? "teach" : "prepare"; + if (m === "prepare" || m === "teach") return m; + return fail("mode must be prepare or teach (the Student view has a fixed dock)"); +} + +/** `all`, `current`, `3`, `2-5`, `1,3,5` → 0-based page indexes. */ +export function parsePages(spec: string, current: number, n: number): number[] { + const s = spec.trim().toLowerCase(); + if (s === "all" || s === "") return Array.from({ length: n }, (_, i) => i); + if (s === "current") return [current]; + const out: number[] = []; + for (const part of s.split(",")) { + const m = /^(\d+)(?:\s*-\s*(\d+))?$/.exec(part.trim()); + if (!m) fail(`pages: use all, current, a page like 3 or a range like 2-5 (got “${spec}”)`); + const a = Number(m![1]), b = Number(m![2] ?? m![1]); + if (a < 1 || b > n || a > b) fail(`pages ${part.trim()} is outside 1–${n}`); + for (let i = a; i <= b; i++) if (!out.includes(i - 1)) out.push(i - 1); + } + return out; +} + +// --------------------------------------------------------------- library + +async function library(c: Controller, op: any): Promise { + const session = await import("./library/session"); + const actions = await import("./library/actions"); + const s = session.store() ?? fail("the Library is not ready on this board (no storage chosen yet)"); + const str = (v: unknown, what: string) => (typeof v === "string" && v.trim() ? v.trim() : fail(`${what} is required`)); + switch (op.op) { + case "library_list": { + const entries = await s!.walk(typeof op.folder === "string" ? op.folder : ""); + const q = typeof op.query === "string" ? op.query.toLowerCase() : ""; + const list = entries + .filter((e) => !q || (e.title ?? e.name).toLowerCase().includes(q)) + .slice(0, 500) + .map((e) => ({ id: e.path, kind: e.kind, name: e.name, title: e.title, pages: e.pages, modified: e.modified ? new Date(e.modified).toISOString() : undefined })); + return { result: { open: session.current()?.path ?? null, count: list.length, items: list } }; + } + case "library_open": { + const id = str(op.id, "id"); + const st = await s!.stat(id); + if (!st || st.kind !== "lesson") fail(`no lesson “${id}” in the Library; library_list shows the ids`); + const ok = await session.openLesson(id, { quiet: true }); + if (!ok) fail(`could not open “${id}”`); + return { result: { opened: id, title: title(), pages: pages().length }, changed: true }; + } + case "library_create_lesson": { + const name = str(op.title, "title"); + const tpl = (op.template ?? "blank") as "blank" | "slides" | "lined" | "grid"; + if (!["blank", "slides", "lined", "grid"].includes(tpl)) fail("template must be blank, slides, lined or grid"); + const prev = session.current()?.path ?? null; + const path = await actions.newLesson(typeof op.folder === "string" ? op.folder : "", name, tpl); + if (!op.open && prev && prev !== path) await session.openLesson(prev, { quiet: true }); + return { result: { id: path, title: name, opened: !!op.open || !prev }, changed: true }; + } + case "library_move": { + const id = str(op.id, "id"); + const to = await s!.move(id, typeof op.folder === "string" ? op.folder : ""); + session.bump(); + return { result: { id: to, moved_from: id } }; + } + case "library_rename": { + const id = str(op.id, "id"); + const to = await actions.renameItem(id, str(op.name, "name")); + return { result: { id: to, renamed_from: id } }; + } + case "library_trash": { + const id = str(op.id, "id"); + if (session.current()?.path === id) fail("that lesson is open on the board; open another lesson first"); + await s!.trash(id); + session.bump(); + return { result: { trashed: id, note: "the teacher can restore it from the Library's trash" } }; + } + } + return fail("unknown library op"); +} + +// ----------------------------------------------------------------- stamps + +/** Board-side half of the stamp ops: the device library joins the core op. */ +export async function prepareStampOp(op: any): Promise { + switch (op.op) { + case "add_stamp": { + const lib = myStamps().find((s) => s.id === op.stamp); + return lib ? { ...op, def: lib } : op; + } + case "update_stamp": { + const lib = myStamps().find((s) => s.id === op.id); + return lib ? { ...op, base: lib } : op; + } + case "delete_stamp": + return { ...op, in_library: myStamps().some((s) => s.id === op.id) }; + } + return op; +} + +/** After the core ran a stamp op: keep the device library in step. */ +export async function finishStampOp(op: any, result: any): Promise { + switch (op.op) { + case "list_stamps": + return { ...result, library: myStamps().map(({ html: _h, svg, ...s }) => ({ ...s, svg: svg && svg.length > 2000 ? `(${svg.length} bytes of SVG)` : svg, source: "library" })) }; + case "create_stamp": + case "update_stamp": { + const def = { ...(result.stamp ?? {}), html: op.html ?? myStamps().find((s) => s.id === result.id)?.html }; + try { + await saveStamp(def); + return { ...result, in_library: true }; + } catch (e: any) { + return { ...result, in_library: false, library_error: String(e?.message ?? e) }; + } + } + case "delete_stamp": { + const gone = await deleteLibStamp(op.id); + return { ...result, deleted_from_library: gone }; + } + case "add_stamp": + if (result?.item_id) freshStamps.add(result.item_id); + return { ...result, name: resolveStamp(op.stamp)?.name }; + } + return result; +} + +export const isStampOp = (name: string) => ["list_stamps", "create_stamp", "update_stamp", "delete_stamp", "add_stamp"].includes(name); diff --git a/apps/board/src/agentSettings.ts b/apps/board/src/agentSettings.ts new file mode 100644 index 0000000..961a736 --- /dev/null +++ b/apps/board/src/agentSettings.ts @@ -0,0 +1,85 @@ +// Which settings the teacher's AI agent may read and change (get_settings / +// set_setting). An allowlist: anything not here is the teacher's alone. +// docs/agent-capabilities.md lists every setting with this decision (and the +// reason for "teacher only"); crates/rupok-cli/tests/agent_capabilities.rs +// fails CI when the two disagree or a new setting is in neither. +// +// Never add AI keys, the cloud account, payments, storage locations, +// microphone or permission switches here. + +import { allSettings, settingById, type SettingDef } from "./settings"; + +export const AGENT_SETTINGS: readonly string[] = [ + // Appearance + "appearance.theme", "appearance.accent", "appearance.density", "appearance.dockSide", "appearance.iconStyle", + "appearance.pagesPanel", "appearance.pagesPinned", + // Pen and ink + "pen.style", "pen.markerOpacity", "pen.pressure", "pen.smoothing", "pen.hand", "pen.eraserMode", "pen.keepInkOnPage", + "pen.smartShapes", "pen.scratchOut", "pen.stampQuickMenu", "pen.stampSounds", + // Shapes after drawing + "modes.shapeAfterTeach", "modes.shapeAfterPrepare", + // Touch and gestures + "touch.fingers", "touch.palmEraser", "touch.palmSize", "touch.eraserScale", "touch.handCluster", "touch.thumbScrub", + "touch.swipe", "touch.swipeFingers", "touch.flick", "touch.swipeSensitivity", "touch.tapUndo", "touch.tapRedo", + "touch.doubleTapFit", "touch.longPressDock", "touch.largeTargets", "touch.hints", + // PDF defaults + "files.pdfLayout", "files.pdfInk", "files.pdfPrintFriendly", + // Voice (language and style only; the microphone and providers stay the teacher's) + "general.voiceLang", "general.voicePunctuation", "general.voiceMode", + // AI presentation (never permissions, keys or the preview check) + "ai.solveStyle", "ai.solveSpeed", "ai.solveTeachStep", "ai.chatAttach", "ai.chatPosition", + // Statistics overlay + "about.stats", +]; + +type Simple = Extract; +const SIMPLE = new Set(["toggle", "segmented", "select", "slider", "colour"]); +const isSimple = (s: SettingDef | undefined): s is Simple => !!s && SIMPLE.has(s.type); + +function describe(s: Simple) { + const base = { key: s.id, label: s.label, type: s.type, value: s.get() as unknown, group: s.category, description: s.description }; + switch (s.type) { + case "toggle": return { ...base, allowed: [true, false] }; + case "slider": return { ...base, min: s.min, max: s.max, step: s.step }; + default: return { ...base, allowed: s.options.map((o) => o.value), labels: Object.fromEntries(s.options.map((o) => [o.value, o.label])) }; + } +} + +/** The settings an agent may change, with values and what is allowed. */ +export function agentSettings() { + return allSettings().filter((s) => AGENT_SETTINGS.includes(s.id) && isSimple(s)).map((s) => describe(s as Simple)); +} + +/** Change one allowed setting; returns `{key, from, to}` and an undo. */ +export function setAgentSetting(key: string, value: unknown): { result: { key: string; from: unknown; to: unknown }; undo: () => void } { + if (!AGENT_SETTINGS.includes(key)) { + throw new Error(`\`${key}\` cannot be changed by an agent; get_settings lists the settings that can (AI keys, accounts, payments, storage and permissions are the teacher's alone)`); + } + const s = settingById(key); + if (!isSimple(s) || (s.when && !s.when())) throw new Error(`\`${key}\` is not available on this board`); + if (s.enabled && !s.enabled()) throw new Error(`\`${key}\` is switched off by another setting right now`); + const from = s.get(); + let to: unknown = value; + switch (s.type) { + case "toggle": + if (typeof value !== "boolean") throw new Error(`${key} takes true or false`); + (s.set as (v: boolean) => void)(value); + break; + case "slider": { + const v = typeof value === "number" ? value : Number(value); + if (!Number.isFinite(v) || v < s.min || v > s.max) throw new Error(`${key} takes a number from ${s.min} to ${s.max}`); + to = Math.round(v / s.step) * s.step; + (s.set as (v: number) => void)(to as number); + break; + } + default: { + const ok = s.options.map((o) => o.value); + const v = typeof value === "string" ? (ok.find((o) => o.toLowerCase() === value.toLowerCase()) ?? s.options.find((o) => o.label.toLowerCase() === value.toLowerCase())?.value) : undefined; + if (!v) throw new Error(`${key} takes one of: ${ok.join(", ")}`); + to = v; + (s.set as (v: string) => void)(v); + } + } + const undo = () => (s.set as (v: unknown) => void)(from); + return { result: { key, from, to }, undo }; +} diff --git a/apps/board/src/chatContext.ts b/apps/board/src/chatContext.ts index c49e7d6..4d2615a 100644 --- a/apps/board/src/chatContext.ts +++ b/apps/board/src/chatContext.ts @@ -207,6 +207,8 @@ export const RUPOK_COMMANDS: SlashCommand[] = [ { name: "explain", description: "Explain this page simply, for the class", hint: "optional: for which class", source: "rupok" }, { name: "translate", description: "Translate this page onto a new page", hint: "language, e.g. bn", source: "rupok" }, { name: "design", description: "Design the page background, theme and branding", hint: "what you want, e.g. chalkboard, physics, our logo", source: "rupok" }, + { name: "stamp", description: "Make a custom stamp, with its look and behaviour (or logic)", hint: "what it should look like and do", source: "rupok" }, + { name: "dock", description: "Arrange the Smart Dock for you", hint: "e.g. pen and eraser on the left, undo on the right, bigger", source: "rupok" }, { name: "clear", description: "Clear the chat view (the agent keeps its memory)", source: "rupok" }, { name: "new", description: "Start a new chat", source: "rupok" }, ]; @@ -225,6 +227,8 @@ export function runRupokCommand(name: string, args: string): CommandAction { return { prompt: `Translate this page into ${lang} on a new page right after it, keeping the same layout (same positions and sizes). Keep numbers and formulas as they are.`, attachPage: true }; } case "design": return { prompt: designPrompt(a), attachPage: true }; + case "stamp": return { prompt: stampPrompt(a), attachPage: false }; + case "dock": return { prompt: dockPrompt(a), attachPage: false }; case "clear": return { local: "clear" }; case "new": return { local: "new" }; default: return { error: `Unknown command /${name}` }; @@ -249,6 +253,26 @@ export function designPrompt(wish: string): string { ].join("\n"); } +/** `/stamp`: a custom stamp for the teacher's "My stamps", with the house rules. */ +export function stampPrompt(wish: string): string { + return [ + `Make me a custom classroom stamp: ${wish || "a cheerful one for a great answer"}.`, + "Use create_stamp (call list_stamps first to see what exists). Artwork: simple, bold SVG (viewBox about 100×100, fill=\"currentColor\" for the main colour, no text in it), or an emoji, or a short label (text art).", + "Behaviour without code: animation (pop, sparkle, bounce, spin, fade-in), a burst (stars, confetti, hearts, sparkles), counter, sound (chime, pop, ding, tada, clap, whoosh), fade_after seconds. Keep it celebratory but brief: one animation, at most one burst and one short sound.", + "If it needs logic (a dice that rolls on tap, a timer, a tap counter), use art \"smart\" with html: a tiny Smart Object (read_object_spec), the whole body tappable, large and readable on a projector, offline, no network.", + "Then place one with add_stamp on the current page so I can see it, and tell me its name in one line.", + ].join("\n"); +} + +/** `/dock`: arrange the Smart Dock as the teacher asks. */ +export function dockPrompt(wish: string): string { + return [ + `Arrange my Smart Dock: ${wish || "make it comfortable for teaching on a big board"}.`, + "Call list_dock_items and get_dock_layout first, then set_dock_layout (groups of button ids in order, position left/right/top/bottom, an optional split second dock, size s/m/l, large icons) for the mode I mean (teach or prepare; both if I did not say).", + "Pen, highlighter, eraser, laser and undo always stay on a dock. Mention any warnings it returns. Offer to save it with save_dock_preset if I like it. Reply in one or two lines.", + ].join("\n"); +} + // ------------------------------------------- optional modules of other features /** Solve-this (another feature): used by /solve when it is built. */ diff --git a/apps/board/src/components/Dock.css b/apps/board/src/components/Dock.css index e6b73a8..cd1b900 100644 --- a/apps/board/src/components/Dock.css +++ b/apps/board/src/components/Dock.css @@ -210,3 +210,16 @@ html[data-overlay="ink"] .ov-dock > * { pointer-events: auto; } .pin-toggle.fixed { background: transparent; color: var(--text-3); cursor: default; } .dock-settings { display: grid; grid-template-columns: 1fr 1fr; column-gap: var(--s6); align-items: end; margin-top: var(--s2); } .dock-settings > .check { grid-column: 1 / -1; margin-bottom: var(--s2); } + +/* ------------------------------------------- Customize dock: sizes */ +/* A teacher's dock size and large icons (modes.ts → dock.size, dock.large). */ +:root .dock-shell.sz-s { --tb: 40px; --tb-icon: 20px; } +:root .dock-shell.sz-l { --tb: 60px; --tb-icon: 30px; --r-tb: 14px; } +:root .dock-shell.big-icons { --tb-icon: 30px; } +:root .dock-shell.sz-l.big-icons { --tb: 68px; --tb-icon: 36px; } +/* Per-button sizes: the cell does not box its button. */ +.dock-cell { display: contents; } +.dock-cell.sz-l > .tool, .dock-cell.sz-l > .viewer-count { width: calc(var(--tb) * 1.3); height: calc(var(--tb) * 1.3); } +.dock-cell.sz-l > .tool svg.icon { transform: scale(1.3); } +.dock-cell.sz-s > .tool { width: calc(var(--tb) * 0.8); height: calc(var(--tb) * 0.8); } +.dock-cell.sz-s > .tool svg.icon { transform: scale(0.85); } diff --git a/apps/board/src/components/Dock.tsx b/apps/board/src/components/Dock.tsx index 5cf22b3..6a8295d 100644 --- a/apps/board/src/components/Dock.tsx +++ b/apps/board/src/components/Dock.tsx @@ -13,14 +13,16 @@ import { type JSX, For, Match, Show, Switch, createEffect, createMemo, createSignal, on, onCleanup, onMount } from "solid-js"; import { controller } from "../controller"; -import { CORE_TOOLS, TOOLBAR_ITEMS, type ModeConfig, type ToolbarItem } from "../modes"; +import { + CORE_TOOLS, TOOLBAR_ITEMS, type DockConfig, type DockGroup, type DockSize, type ModeConfig, type ToolbarItem, layoutPins, +} from "../modes"; import { type DomItem, HL_COLORS, PEN_COLORS, WIDTHS, type Tool, camera, canRedo, canUndo, color, editingText, hex, hlColor, isView, items, lessonOpened, mode, modeConfig, pageIndex, pages, prefs, replay, selectionIds, setColor, setHlColor, setPrefs, setSizes, setWidth, showToast, sizeKey, sizes, studentEntry, tool, width, } from "../state"; import { - type DockEdge, type DockPlace, dockFrame, dockMinimized, dockPlace, inkForBoard, isVertical, lastShape, placeAround, recentColors, + type DockEdge, type DockPlace, dockFrame, dockMinimized, dockPlace, inkForBoard, isVertical, lastShape, openDockEditor, placeAround, presetPlace, recentColors, registerDockSummon, resetDock, screenBucket, setDockMinimized, setDockPlace, setDockSide, setLastShape, useColor, hlOpacity, setHlOpacityStored, } from "../dock"; @@ -37,6 +39,7 @@ import { MarkerOpacity, SizeControl, StylePicker } from "./InkOptions"; import { StampIcon, StampsPanel } from "./Stamps"; import { brushInfo, brushOf } from "../brushes"; import { celebrate, currentStamp } from "../stamps"; +import { openAiPanel, setComposerDraft } from "../chat"; const META = new Map(TOOLBAR_ITEMS.map((t) => [t.id, t])); const INK_TOOLS: Tool[] = ["pen", "highlighter", "rect", "ellipse", "line", "arrow", "shape"]; @@ -58,13 +61,37 @@ const FADE_NEAR = 120; const FADE_HOLD_MS = 800; const WAKE_NEAR = 56; -type Group = "ink" | "colors" | "create" | "point" | "context" | "history" | "nav" | "exit" | "end"; -type Kind = "tool" | "colors" | "shapes" | "smartink" | "undo" | "redo" | "pager" | "replay" | "exit" | "context" | "more"; -interface Entry { key: string; kind: Kind; group: Group; id?: ToolbarItem } +/** Built-in groups ("ink", "create", …), or a teacher's group (`g:`). */ +type Group = string; +type Kind = + | "tool" | "colors" | "shapes" | "smartink" | "undo" | "redo" | "pager" | "replay" | "exit" | "context" | "more" + | "celebrate" | "pages" | "solve" | "settings"; +interface Entry { key: string; kind: Kind; group: Group; id?: ToolbarItem; size?: DockSize } const GROUP: Partial> = { pen: "ink", highlighter: "ink", eraser: "ink", smartink: "create", text: "create", stamp: "create", lasso: "point", laser: "point", hand: "point", interact: "point", undo: "history", redo: "history", pager: "nav", replay: "nav", exit: "exit", + celebrate: "create", pages: "nav", solve: "create", settings: "end", }; +const ACTION_KINDS: ToolbarItem[] = ["smartink", "undo", "redo", "pager", "replay", "exit", "celebrate", "pages", "solve", "settings"]; +const kindOf = (t: ToolbarItem): Kind => (ACTION_KINDS.includes(t) ? (t as Kind) : "tool"); + +/** A teacher's groups as dock entries (main dock or the split dock). */ +function groupEntries(groups: DockGroup[], sizes: DockConfig["sizes"], prefix: string): Entry[] { + const out: Entry[] = []; + for (const g of groups) { + for (const pin of g.items) { + const size = sizes?.[pin]; + if (pin === "shapes") out.push({ key: "shapes", kind: "shapes", group: `${prefix}${g.id}`, size }); + else out.push({ key: pin, kind: kindOf(pin), id: pin, group: `${prefix}${g.id}`, size }); + } + } + return out; +} + +/** The split dock's entries (a teacher's second dock). */ +export function splitLayout(m: ModeConfig): Entry[] { + return m.dock.split ? groupEntries(m.dock.split.groups, m.dock.sizes, "s:") : []; +} /** 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 ⋯ @@ -82,7 +109,17 @@ export function dockLayout(m: ModeConfig, core: boolean, allowMore: boolean, roo const bar: Entry[] = []; const overflow: ToolbarItem[] = []; let shapes = false; - for (const t of m.tools) { + const custom = core && !!(m.dock.groups?.length || m.dock.split); + if (custom) { + // The teacher's own groups, in their order; the rest waits in ⋯. + bar.push(...groupEntries(m.dock.groups ?? [], m.dock.sizes, "g:")); + const placed = new Set(layoutPins(m.dock)); + for (const t of m.tools) { + const folded = SHAPES.includes(t as Tool) ? placed.has("shapes") : t === "smartink" && placed.has("shapes") && !placed.has("smartink"); + if (!placed.has(t) && !folded) overflow.push(t); + } + } + for (const t of custom ? [] : m.tools) { // Smart shapes folds into the Shapes button unless it is pinned on its own (Teach). if (SHAPES.includes(t as Tool) || (t === "smartink" && shapesOn && !pinned.has("smartink"))) { if (!shapesOn) overflow.push(t); @@ -93,18 +130,26 @@ export function dockLayout(m: ModeConfig, core: boolean, allowMore: boolean, roo continue; } if ((core && CORE_TOOLS.includes(t)) || pinned.has(t)) { - const kind: Kind = ["smartink", "undo", "redo", "pager", "replay", "exit"].includes(t) ? (t as Kind) : "tool"; - bar.push({ key: t, kind, id: t, group: GROUP[t] ?? "point" }); + bar.push({ key: t, kind: kindOf(t), id: t, group: GROUP[t] ?? "point", size: m.dock.sizes?.[t] }); } else overflow.push(t); } - // Recent colours right after the ink tools. - const lastInk = bar.map((e) => e.group).lastIndexOf("ink"); + if (!custom) { + const sh = bar.find((e) => e.kind === "shapes"); + if (sh) sh.size = m.dock.sizes?.shapes; + } + // Recent colours right after the ink tools (in their group when the teacher grouped them). if (m.chrome.colors && core && bar.some((e) => e.id === "pen" || e.id === "highlighter")) { - bar.splice(lastInk + 1, 0, { key: "colors", kind: "colors", group: "colors" }); + if (custom) { + const last = bar.map((e) => e.id === "pen" || e.id === "highlighter").lastIndexOf(true); + bar.splice(last + 1, 0, { key: "colors", kind: "colors", group: bar[last].group }); + } else { + const lastInk = bar.map((e) => e.group).lastIndexOf("ink"); + bar.splice(lastInk + 1, 0, { key: "colors", kind: "colors", group: "colors" }); + } } // The contextual section goes before history (else navigation, else the end). - let at = bar.findIndex((e) => e.group === "history"); - if (at < 0) at = bar.findIndex((e) => e.group === "nav" || e.group === "exit"); + let at = bar.findIndex((e) => (custom ? e.id === "undo" || e.id === "redo" : e.group === "history")); + if (at < 0) at = bar.findIndex((e) => (custom ? e.id === "pager" || e.id === "exit" : e.group === "nav" || e.group === "exit")); bar.splice(at < 0 ? bar.length : at, 0, { key: "context", kind: "context", group: "context" }); if (overflow.length || allowMore) bar.push({ key: "more", kind: "more", group: "end" }); let colors = 3; @@ -491,7 +536,10 @@ export default function Dock(props: { onSettings?: (section?: string) => void }) }; // ------------------------------------------------------------ sizing - const iconSize = () => { + /** The teacher's dock size and large icons (Customize dock). */ + const scale = () => (cfg().dock.size === "s" ? 0.85 : cfg().dock.size === "l" ? 1.2 : 1) * (cfg().dock.large ? 1.25 : 1); + const iconSize = () => Math.round(baseIconSize() * scale()); + const baseIconSize = () => { const d = prefs().density; if (isPhone()) return d === "large" ? 26 : 22; // 44px cells (52 large) for thumbs // Teach is compact, except on a touch board, where fingers need the room (Dock.css). @@ -772,6 +820,26 @@ export default function Dock(props: { onSettings?: (section?: string) => void }) + + + + + + + + + + + + @@ -792,6 +860,27 @@ export default function Dock(props: { onSettings?: (section?: string) => void }) ); + /** An entry in its size cell (Customize dock: per-button sizes). */ + const Cell = (p: { e: Entry }) => ( +
+ +
+ ); + const solveNow = () => { + void import("../solve").then((m) => m.solve({ source: "dock" })).catch(() => showToast("Solve this needs the AI assistant")); + }; + + // The teacher's second dock (Customize dock → split), e.g. undo and the + // pager on the other edge of a big board. + const splitBar = createMemo(() => (core() ? splitLayout(cfg()) : []), undefined, { + equals: (a, b) => JSON.stringify(a) === JSON.stringify(b), + }); + const [splitDrag, setSplitDrag] = createSignal(null); + createEffect(on(() => JSON.stringify(cfg().dock.split ?? null), () => setSplitDrag(null), { defer: true })); + const splitPlace = () => splitDrag() ?? presetPlace(cfg().dock.split?.position ?? "right", prefs().toolbar); + const splitVertical = () => isVertical(splitPlace(), cfg().dock.split?.orientation ?? "auto"); + const splitSep = (i: number) => i > 0 && splitBar()[i - 1].group !== splitBar()[i].group; + // Replay: its controls take the place of the tools. const [speed, setSpeed] = createSignal(2); const fmt = (ms: number) => { @@ -929,7 +1018,11 @@ export default function Dock(props: { onSettings?: (section?: string) => void }) idle: mode() === "teach" && idle() && !pop(), inking: inking(), lefty: prefs().hand === "left", + "sz-s": cfg().dock.size === "s", + "sz-l": cfg().dock.size === "l", + "big-icons": !!cfg().dock.large, }} + onGripHold={core() ? () => openDockEditor(mode()) : undefined} label={label()} iconSize={iconSize()} bubbleLabel={`Open the dock (${labelOf(bubbleTool())})`} @@ -959,7 +1052,7 @@ export default function Dock(props: { onSettings?: (section?: string) => void })
- + )} @@ -975,6 +1068,49 @@ export default function Dock(props: { onSettings?: (section?: string) => void }) + 0 && !replay() && !minimized()}> + setSplitDrag(p)} + minimized={false} + onMinimized={() => {}} + noMinimize + class="toolbar dock dock-split" + classList={{ + teach: mode() === "teach", + idle: mode() === "teach" && idle() && !pop(), + inking: inking(), + "sz-s": cfg().dock.size === "s", + "sz-l": cfg().dock.size === "l", + "big-icons": !!cfg().dock.large, + }} + label="Second dock" + iconSize={iconSize()} + bubble={<>} + bubbleLabel="Second dock" + onActivity={() => { + wake(); + unfade(); + }} + onDragStart={() => setPop(null)} + onGripHold={() => openDockEditor(mode())} + > + + {(e, i) => ( + <> + +
+ + + + )} + + + + {(pp) => { const p = () => pp; @@ -1186,6 +1322,10 @@ export default function Dock(props: { onSettings?: (section?: string) => void }) else if (t === "exit") controller.exitMode(); else if (t === "interact") toggleUse(); else if (t === "shape") openShapesPicker(); + else if (t === "celebrate") celebrate(); + else if (t === "pages") togglePagesDrawer(); + else if (t === "solve") solveNow(); + else if (t === "settings") props.onSettings?.(); else if (t === "stamp") { pick("stamp"); setPop({ kind: "stamp", anchor: moreBtn }); @@ -1265,17 +1405,28 @@ export default function Dock(props: { onSettings?: (section?: string) => void }) > Reset dock position - + +
diff --git a/apps/board/src/components/DockEditor.css b/apps/board/src/components/DockEditor.css new file mode 100644 index 0000000..e5bda43 --- /dev/null +++ b/apps/board/src/components/DockEditor.css @@ -0,0 +1,93 @@ +/* Customize dock (DockEditor.tsx). FigJam-flat, tokens only (DESIGN.md), + * 44px targets, light and dark. */ + +.de-backdrop { + position: fixed; inset: 0; z-index: 60; display: flex; justify-content: flex-end; + background: rgba(10, 12, 16, 0.18); +} +.de-sheet { + width: min(560px, 100vw); height: 100%; display: flex; flex-direction: column; + background: var(--surface-solid); color: var(--text); box-shadow: var(--shadow-2); + animation: de-in 180ms var(--ease) both; +} +@keyframes de-in { from { transform: translateX(24px); } } +.de-head { display: flex; align-items: center; gap: var(--s3); padding: var(--s4) var(--s4) var(--s3); border-bottom: 1px solid var(--hairline); } +.de-head h2 { margin: 0; font: 700 18px/24px var(--font); } +.de-head .seg button, .de-sec .seg button { min-height: 44px; padding: 0 var(--s3); } +.de-close { width: 44px; height: 44px; } +.de-body { flex: 1; overflow-y: auto; padding: var(--s3) var(--s4) var(--s5); display: flex; flex-direction: column; gap: var(--s4); } +.de-sec h3 { margin: 0 0 var(--s2); font: 650 12px/16px var(--font); letter-spacing: 0.04em; text-transform: uppercase; color: var(--text-2); } +.de-row { display: flex; flex-wrap: wrap; align-items: center; gap: var(--s2) var(--s3); margin: var(--s2) 0; } +.de-row .check { min-height: 44px; display: inline-flex; align-items: center; gap: var(--s2); } +.de-label { min-width: 72px; font: 600 14px/20px var(--font); color: var(--text-2); } +.de-hint { margin: 0 0 var(--s2); font: 500 13px/18px var(--font); color: var(--text-2); } +.de-dock-label { margin: var(--s3) 0 var(--s1); font: 650 13px/18px var(--font); color: var(--text); } + +.de-presets { display: flex; flex-wrap: wrap; gap: var(--s2); } +.de-preset-wrap { position: relative; display: inline-flex; } +.de-preset { + min-height: 44px; padding: 0 var(--s4); border: 0; border-radius: 12px; cursor: pointer; + background: var(--accent-3); color: var(--accent-11); font: 650 14px/20px var(--font); + box-shadow: inset 0 0 0 1px var(--hairline); transition: background-color 120ms var(--ease); +} +.de-preset:hover { background: var(--accent-4); } +.de-preset:focus-visible, .de-chip:focus-visible, .de-add-group:focus-visible { outline: 2px solid var(--accent-9); outline-offset: 2px; } +.de-preset-wrap.saved .de-preset { padding-right: 36px; } +.de-preset-x { + position: absolute; right: 4px; top: 50%; transform: translateY(-50%); width: 28px; height: 28px; border: 0; border-radius: 8px; + display: grid; place-items: center; background: transparent; color: var(--accent-11); cursor: pointer; +} +.de-preset-x:hover { background: var(--accent-5); } +.de-save { display: flex; gap: var(--s2); margin-top: var(--s3); } +.de-save .input { flex: 1; min-height: 44px; } +.de-save .btn { min-height: 44px; } + +.de-groups { display: flex; flex-direction: column; align-items: stretch; gap: var(--s2); padding: var(--s2); border-radius: 16px; background: var(--hover); } +.de-group { + display: flex; flex-wrap: wrap; align-items: center; gap: var(--s1); min-height: 56px; min-width: 120px; padding: var(--s1); + border-radius: 12px; background: var(--surface-solid); box-shadow: inset 0 0 0 1px var(--hairline); +} +/* Each group is its own row; the dock draws a separator between them. */ +.de-sep { display: none; } +.de-empty { padding: 0 var(--s3); font: 500 13px/18px var(--font); color: var(--text-3); } +.de-add-group { + min-height: 44px; justify-content: center; padding: 0 var(--s3); border: 1px dashed var(--hairline); border-radius: 12px; background: transparent; cursor: pointer; + display: inline-flex; align-items: center; gap: var(--s1); color: var(--text-2); font: 600 13px/18px var(--font); +} +.de-add-group:hover { background: var(--surface-solid); color: var(--text); } + +.de-chip { + position: relative; display: inline-flex; align-items: center; gap: var(--s2); min-height: 44px; padding: 0 var(--s3); border: 0; + border-radius: 10px; background: var(--surface-solid); color: var(--text); font: 600 13px/18px var(--font); cursor: grab; + box-shadow: inset 0 0 0 1px var(--hairline); touch-action: none; user-select: none; transition: background-color 120ms var(--ease); +} +.de-chip:hover { background: var(--accent-3); } +.de-chip.picked { background: var(--accent-9); color: var(--accent-contrast); box-shadow: none; } +.de-chip.big { min-height: 52px; font-size: 14px; } +.de-chip.big svg.icon { transform: scale(1.2); } +.de-chip.small { font-size: 12px; } +.de-lock { color: var(--accent-11); font-weight: 800; } +.de-chip.picked .de-lock { color: inherit; } +.de-tray { display: flex; flex-wrap: wrap; gap: var(--s1); min-height: 56px; padding: var(--s2); border-radius: 16px; border: 1px dashed var(--hairline); } +.de-tray .de-chip { background: transparent; } +.de-tray .de-chip:hover { background: var(--accent-3); } +.de-picked { padding: var(--s2) var(--s3); border-radius: 12px; background: var(--accent-3); } + +.de-warn { padding: var(--s3); border-radius: 12px; background: var(--danger-soft); color: var(--text); } +.de-warn p { display: flex; gap: var(--s2); align-items: flex-start; margin: 0; font: 550 13px/18px var(--font); } +.de-foot { display: flex; gap: var(--s2); padding: var(--s3) var(--s4); border-top: 1px solid var(--hairline); } +.de-foot .btn { min-height: 44px; } + +.de-ghost { + position: fixed; z-index: 70; transform: translate(-50%, -60%); pointer-events: none; + display: inline-flex; align-items: center; gap: var(--s2); min-height: 44px; padding: 0 var(--s3); border-radius: 10px; + background: var(--accent-9); color: var(--accent-contrast); font: 650 13px/18px var(--font); box-shadow: var(--shadow-2); +} + +@media (max-width: 600px) { + .de-sheet { width: 100vw; } + .de-body { padding: var(--s3); } +} +@media (prefers-reduced-motion: reduce) { + .de-sheet { animation: none; } +} diff --git a/apps/board/src/components/DockEditor.tsx b/apps/board/src/components/DockEditor.tsx new file mode 100644 index 0000000..e09d808 --- /dev/null +++ b/apps/board/src/components/DockEditor.tsx @@ -0,0 +1,532 @@ +// "Customize dock": the teacher arranges the Smart Dock by hand. Buttons +// move between the tray of available buttons and the dock's groups (drag, +// or pick up with Enter and move with the arrow keys), groups get a +// separator between them, a second dock can sit on another edge, and every +// button (or the whole dock) can be bigger. Changes apply at once: the real +// dock behind the sheet is the live preview. Named layouts (built-in and +// the teacher's own) switch everything in one tap. +// +// The model is modes.ts → DockConfig (groups, split, size, sizes, large); +// agents change the same thing with set_dock_layout (agentControl.ts). + +import { For, Show, createMemo, createSignal, onCleanup, onMount } from "solid-js"; +import { controller } from "../controller"; +import { + ALLOWED_TOOLS, CORE_TOOLS, DEFAULT_MODES, DOCK_PRESETS, SHAPE_TOOLS, SHAPES_PIN, TOOLBAR_ITEMS, type DockConfig, type DockGroup, type DockPin, + type DockPosition, type DockPreset, type DockSize, type Mode, type ToolbarItem, applyDockPreset, dockWarnings, layoutPins, sanitizeMode, +} from "../modes"; +import { dockEditor, resetDock, setDockEditor } from "../dock"; +import { mode, modeConfig, prefs, setPrefs, showToast } from "../state"; +import { dockLayout } from "./Dock"; +import { Icon } from "./Icon"; +import type { IconName } from "../icons.generated"; +import "./DockEditor.css"; + +type EditMode = Exclude; +const META = new Map(TOOLBAR_ITEMS.map((t) => [t.id, { icon: t.icon, label: t.label }])); +META.set("shapes", { icon: SHAPES_PIN.icon, label: SHAPES_PIN.label }); +const labelOf = (p: DockPin) => META.get(p)?.label ?? p; +const iconOf = (p: DockPin) => META.get(p)?.icon ?? "pen"; +const isCore = (p: DockPin) => CORE_TOOLS.includes(p as ToolbarItem); + +/** Where a button sits: `main` or `split` dock, group index, position. */ +interface Slot { dock: "main" | "split"; g: number; i: number } + +/** Everything a mode's dock can hold (shape tools fold into one Shapes button). */ +export function placeable(m: Mode): DockPin[] { + const out: DockPin[] = []; + for (const t of ALLOWED_TOOLS[m]) { + const pin: DockPin = SHAPE_TOOLS.includes(t) ? "shapes" : t; + if (!out.includes(pin)) out.push(pin); + } + return out; +} + +/** The dock as groups: the teacher's, or the automatic grouping turned into groups. */ +export function groupsOf(m: EditMode): { main: DockGroup[]; split: DockGroup[] } { + const c = modeConfig(m); + if (c.dock.groups?.length || c.dock.split) return { main: structuredClone(c.dock.groups ?? []), split: structuredClone(c.dock.split?.groups ?? []) }; + const bar = dockLayout(c, true, false).bar.filter((e) => e.kind !== "colors" && e.kind !== "context" && e.kind !== "more"); + const main: DockGroup[] = []; + for (const e of bar) { + const pin: DockPin = e.kind === "shapes" ? "shapes" : (e.id as DockPin); + const last = main[main.length - 1]; + if (last && last.id === e.group) last.items.push(pin); + else main.push({ id: e.group, items: [pin] }); + } + return { main: main.map((g, i) => ({ ...g, id: `g${i + 1}` })), split: [] }; +} + +/** Save a mode's dock (validated like an imported config). */ +export function saveDock(m: EditMode, patch: Partial) { + const cur = modeConfig(m); + const next = sanitizeMode(m, { chrome: cur.chrome, tools: cur.tools, dock: { ...cur.dock, ...patch } }); + setPrefs({ modes: { ...prefs().modes, [m]: next } }); + resetDock(m); + controller.updateInsets(mode() === "teach"); +} + +/** The teacher's saved layouts (prefs → dockPresets). */ +export const savedPresets = (): DockPreset[] => prefs().dockPresets ?? []; + +export function applyPreset(p: DockPreset) { + setPrefs({ modes: applyDockPreset(prefs().modes, p), ...(p.hand ? { hand: p.hand } : {}) }); + resetDock("prepare"); + resetDock("teach"); + controller.updateInsets(mode() === "teach"); +} + +/** Save the current docks as a named layout (replacing one of that name). */ +export function savePreset(name: string, modes: EditMode[] = ["prepare", "teach"]): DockPreset { + const clean = name.trim().slice(0, 32) || "My layout"; + const p: DockPreset = { name: clean, hint: "Saved by you", modes: {} }; + for (const m of modes) p.modes[m] = structuredClone(modeConfig(m).dock); + const rest = savedPresets().filter((x) => x.name.toLowerCase() !== clean.toLowerCase()); + setPrefs({ dockPresets: [...rest, p].slice(-12) }); + return p; +} + +const POSITIONS: { v: DockPosition; label: string }[] = [ + { v: "auto", label: "Auto" }, { v: "left", label: "Left" }, { v: "right", label: "Right" }, { v: "top", label: "Top" }, { v: "bottom", label: "Bottom" }, +]; +const SPLIT_POS: { v: DockPosition; label: string }[] = [ + { v: "left", label: "Left" }, { v: "right", label: "Right" }, { v: "top", label: "Top" }, { v: "bottom", label: "Bottom" }, +]; +const SIZES: { v: DockSize; label: string }[] = [{ v: "s", label: "Small" }, { v: "m", label: "Medium" }, { v: "l", label: "Large" }]; + +export function DockEditor() { + return ( + + {(m) => } + + ); +} + +function Editor(props: { mode: EditMode }) { + const [m, setM] = createSignal(props.mode); + const cfg = () => modeConfig(m()); + const groups = createMemo(() => groupsOf(m())); + const [picked, setPicked] = createSignal(null); + const [drag, setDrag] = createSignal<{ pin: DockPin; x: number; y: number; from: Slot | null } | null>(null); + const [presetName, setPresetName] = createSignal(""); + let sheet!: HTMLDivElement; + + const close = () => setDockEditor(null); + onMount(() => { + const key = (e: KeyboardEvent) => { + if (e.key === "Escape" && !picked()) { + e.preventDefault(); + close(); + } + }; + window.addEventListener("keydown", key); + onCleanup(() => window.removeEventListener("keydown", key)); + queueMicrotask(() => sheet?.querySelector("[data-autofocus]")?.focus()); + }); + + const write = (main: DockGroup[], split: DockGroup[]) => { + const s = cfg().dock.split; + saveDock(m(), { + groups: main.filter((g) => g.items.length || main.length === 1), + split: split.some((g) => g.items.length) ? { position: s?.position ?? "right", orientation: s?.orientation ?? "auto", groups: split.filter((g) => g.items.length) } : null, + }); + }; + const listOf = (d: "main" | "split", gs = groups()) => (d === "main" ? gs.main : gs.split); + const tray = () => { + const on = new Set(layoutPins({ ...cfg().dock, groups: groups().main, split: { position: "right", orientation: "auto", groups: groups().split } })); + return placeable(m()).filter((p) => !on.has(p)); + }; + + /** Move `pin` (from `from`, or the tray) to `to` (or the tray when null). */ + const place = (pin: DockPin, from: Slot | null, to: Slot | null) => { + const gs = structuredClone(groups()); + if (from) listOf(from.dock, gs)[from.g]?.items.splice(from.i, 1); + if (!to) { + if (isCore(pin)) { + showToast(`${labelOf(pin)} always stays on a dock (pen, highlighter, eraser, laser and undo)`); + return; + } + } else { + const list = listOf(to.dock, gs); + while (list.length <= to.g) list.push({ id: `${to.dock === "main" ? "g" : "s"}${Date.now().toString(36)}${list.length}`, items: [] }); + const items = list[to.g].items; + items.splice(Math.min(Math.max(0, to.i), items.length), 0, pin); + } + write(gs.main, gs.split); + }; + const addGroup = (d: "main" | "split") => { + const gs = structuredClone(groups()); + listOf(d, gs).push({ id: `${d === "main" ? "g" : "s"}${Date.now().toString(36)}`, items: [] }); + // An empty group is kept only until it gets a button: show it now. + setEmpty({ dock: d, g: listOf(d, gs).length - 1 }); + }; + const [empty, setEmpty] = createSignal<{ dock: "main" | "split"; g: number } | null>(null); + const groupsFor = (d: "main" | "split") => { + const list = listOf(d); + const e = empty(); + return e && e.dock === d && e.g >= list.length ? [...list, { id: "new", items: [] as DockPin[] }] : list.length ? list : [{ id: "new", items: [] as DockPin[] }]; + }; + + // ------------------------------------------------- keyboard pick-up + const onChipKey = (e: KeyboardEvent, pin: DockPin, at: Slot) => { + const p = picked(); + const same = p && p.dock === at.dock && p.g === at.g && p.i === at.i; + if (e.key === "Enter" || e.key === " ") { + e.preventDefault(); + setPicked(same ? null : at); + return; + } + if (e.key === "Delete" || e.key === "Backspace") { + e.preventDefault(); + setPicked(null); + place(pin, at, null); + return; + } + if (!same) return; + const list = groupsFor(at.dock); + let to: Slot | null = null; + if (e.key === "ArrowLeft" || e.key === "ArrowUp" && e.shiftKey) to = { ...at, i: at.i - 1 }; + else if (e.key === "ArrowRight") to = { ...at, i: at.i + 1 }; + else if (e.key === "ArrowUp") to = at.g > 0 ? { dock: at.dock, g: at.g - 1, i: list[at.g - 1].items.length } : at.dock === "split" ? { dock: "main", g: Math.max(0, groups().main.length - 1), i: 99 } : null; + else if (e.key === "ArrowDown") to = at.g < list.length - 1 ? { dock: at.dock, g: at.g + 1, i: 0 } : at.dock === "main" && cfg().dock.split ? { dock: "split", g: 0, i: 0 } : null; + else if (e.key === "Escape") { + e.preventDefault(); + setPicked(null); + return; + } + if (!to) return; + e.preventDefault(); + if (to.i < 0) { + if (to.g === 0) return; + to = { dock: to.dock, g: to.g - 1, i: list[to.g - 1].items.length }; + } + if (to.i > list[to.g].items.length - (to.g === at.g ? 1 : 0)) { + if (to.g >= list.length - 1) return; + to = { dock: to.dock, g: to.g + 1, i: 0 }; + } + place(pin, at, to); + const nt = to; + setPicked(nt); + queueMicrotask(() => sheet.querySelector(`[data-slot="${nt.dock}-${nt.g}-${nt.i}"]`)?.focus()); + }; + + // ------------------------------------------------------ pointer drag + const startDrag = (e: PointerEvent, pin: DockPin, from: Slot | null) => { + if (e.button !== 0) return; + const [x0, y0] = [e.clientX, e.clientY]; + let moving = false; + const move = (ev: PointerEvent) => { + if (!moving && Math.hypot(ev.clientX - x0, ev.clientY - y0) < 6) return; + moving = true; + ev.preventDefault(); + setDrag({ pin, x: ev.clientX, y: ev.clientY, from }); + // Near the top or bottom of the sheet, scroll it so every group is reachable. + const body = sheet.querySelector(".de-body"); + if (body) { + const r = body.getBoundingClientRect(); + if (ev.clientY < r.top + 48) body.scrollTop -= 16; + else if (ev.clientY > r.bottom - 48) body.scrollTop += 16; + } + }; + const up = (ev: PointerEvent) => { + window.removeEventListener("pointermove", move); + window.removeEventListener("pointerup", up); + window.removeEventListener("pointercancel", up); + if (!moving) return; + setDrag(null); + const target = dropTarget(ev.clientX, ev.clientY); + if (target === "tray") place(pin, from, null); + else if (target) { + // Moving later in the same group: the gap left behind shifts it. + const adj = from && from.dock === target.dock && from.g === target.g && from.i < target.i ? target.i - 1 : target.i; + place(pin, from, { ...target, i: adj }); + } + }; + window.addEventListener("pointermove", move); + window.addEventListener("pointerup", up); + window.addEventListener("pointercancel", up); + }; + const dropTarget = (x: number, y: number): Slot | "tray" | null => { + const el = document.elementFromPoint(x, y) as HTMLElement | null; + if (el?.closest("[data-drop-tray]")) return "tray"; + const zone = el?.closest("[data-drop-group]"); + if (!zone) return null; + const [dock, g] = zone.dataset.dropGroup!.split("-"); + const chips = [...zone.querySelectorAll("[data-chip]")]; + let i = chips.length; + for (const [k, c] of chips.entries()) { + const r = c.getBoundingClientRect(); + if (x < r.left + r.width / 2 && y < r.bottom) { + i = k; + break; + } + } + return { dock: dock as "main" | "split", g: Number(g), i }; + }; + + // ---------------------------------------------------------- settings + const setSize = (v: DockSize) => saveDock(m(), { size: v === "m" ? undefined : v }); + const setButtonSize = (pin: DockPin, v: DockSize) => { + const sizes = { ...(cfg().dock.sizes ?? {}) }; + if (v === "m") delete sizes[pin]; + else sizes[pin] = v; + saveDock(m(), { sizes }); + }; + const pickedPin = (): DockPin | null => { + const p = picked(); + return p ? listOf(p.dock)[p.g]?.items[p.i] ?? null : null; + }; + const splitOn = () => !!cfg().dock.split; + const toggleSplit = (on: boolean) => { + const gs = structuredClone(groups()); + if (on) { + // Start the second dock with undo/redo and the pager, as most teachers want. + const want: DockPin[] = ["undo", "redo", "pager"].filter((p) => placeable(m()).includes(p as DockPin)) as DockPin[]; + for (const g of gs.main) g.items = g.items.filter((x) => !want.includes(x)); + saveDock(m(), { + groups: gs.main.filter((g) => g.items.length), + split: { position: cfg().dock.position === "left" ? "right" : "left", orientation: "auto", groups: [{ id: "s1", items: want.length ? want : ["undo"] }] }, + }); + } else { + gs.main.push(...gs.split.map((g) => ({ ...g, id: `g-${g.id}` }))); + saveDock(m(), { groups: gs.main, split: null }); + } + }; + const reset = () => { + const cur = modeConfig(m()); + setPrefs({ modes: { ...prefs().modes, [m()]: sanitizeMode(m(), { chrome: cur.chrome, tools: DEFAULT_MODES[m()].tools, dock: DEFAULT_MODES[m()].dock }) } }); + resetDock(m()); + controller.updateInsets(mode() === "teach"); + setPicked(null); + showToast(`${m() === "teach" ? "Teach" : "Prepare"} dock reset to default`); + }; + const warnings = () => dockWarnings(m(), cfg()); + + const Chip = (p: { pin: DockPin; at: Slot | null }) => { + const on = () => { + const k = picked(); + return !!(k && p.at && k.dock === p.at.dock && k.g === p.at.g && k.i === p.at.i); + }; + const size = () => cfg().dock.sizes?.[p.pin]; + return ( + + ); + }; + + const Groups = (p: { dock: "main" | "split" }) => ( +
+ + {(g, gi) => ( + <> + 0}> + + ); + + return ( +
e.target === e.currentTarget && close()}> + + + {(d) => ( + + )} + +
+ ); +} diff --git a/apps/board/src/components/DockShell.tsx b/apps/board/src/components/DockShell.tsx index a46e8f8..fd162d0 100644 --- a/apps/board/src/components/DockShell.tsx +++ b/apps/board/src/components/DockShell.tsx @@ -42,9 +42,15 @@ export interface DockShellProps { /** The dock element, or the bubble while minimised. */ ref?: (el: HTMLElement) => void; gripClass?: string; + /** Holding the grip still (opens the "Customize dock" editor). */ + onGripHold?: () => void; + /** No minimise chevron (the split dock). */ + noMinimize?: boolean; children: JSX.Element; } +const HOLD_MS = 650; + /** Six dots: a handle, not an icon, so it is drawn here. */ function GripDots(props: { size: number; vertical: boolean }) { const dots = () => (props.vertical ? [[6, 9], [12, 9], [18, 9], [6, 15], [12, 15], [18, 15]] : [[9, 6], [9, 12], [9, 18], [15, 6], [15, 12], [15, 18]]); @@ -120,6 +126,23 @@ export function DockShell(props: DockShellProps) { props.onActivity?.(); if (props.windowed) return; // data-tauri-drag-region: the OS moves the window const g = e.currentTarget as HTMLElement; + if (props.onGripHold && e.button === 0) { + const [x0, y0] = [e.clientX, e.clientY]; + const timer = window.setTimeout(() => { + cleanup(); + props.onGripHold?.(); + }, HOLD_MS); + const move = (ev: PointerEvent) => Math.hypot(ev.clientX - x0, ev.clientY - y0) >= TAP_MOVE && cleanup(); + const cleanup = () => { + clearTimeout(timer); + g.removeEventListener("pointermove", move); + g.removeEventListener("pointerup", cleanup); + g.removeEventListener("pointercancel", cleanup); + }; + g.addEventListener("pointermove", move); + g.addEventListener("pointerup", cleanup); + g.addEventListener("pointercancel", cleanup); + } track(e, g, () => ({ x: g.offsetLeft + g.offsetWidth / 2, y: g.offsetTop + g.offsetHeight / 2 }), () => { const now = performance.now(); if (now - lastTap < DOUBLE_TAP_MS) { @@ -196,21 +219,23 @@ export function DockShell(props: DockShellProps) { {props.children} - + + +
); diff --git a/apps/board/src/components/ModesSettings.tsx b/apps/board/src/components/ModesSettings.tsx index b92f8b1..ccdf4f8 100644 --- a/apps/board/src/components/ModesSettings.tsx +++ b/apps/board/src/components/ModesSettings.tsx @@ -7,8 +7,9 @@ import { controller } from "../controller"; import { ALLOWED_CHROME, ALLOWED_TOOLS, CHROME_ITEMS, CORE_TOOLS, DEFAULT_MODES, DOCK_POSITIONS, MODES, SHAPE_TOOLS, TOOLBAR_ITEMS, UI_CONFIG_FORMAT, UI_CONFIG_VERSION, type ChromeKey, type DockConfig, type DockPin, type Mode, type ModeConfig, type ToolbarItem, type UiConfigFile, - resolveMode, sanitizeModes, + resolveMode, sanitizeDockPresets, sanitizeModes, } from "../modes"; +import { openDockEditor } from "../dock"; import { ACCENTS, type Prefs, mode, modeConfig, prefs, setPrefs, showToast } from "../state"; import { exportGestures, importGestures } from "../gesturePrefs"; import { Icon } from "./Icon"; @@ -35,6 +36,7 @@ export function exportUiConfig(): UiConfigFile { modes: Object.fromEntries(MODES.map((m) => [m.id, resolveMode(p.modes, m.id)])) as UiConfigFile["modes"], appearance: { theme: p.theme, accent: p.accent, iconStyle: p.iconStyle, toolbar: p.toolbar, density: p.density, hand: p.hand }, gestures: exportGestures(), + dockPresets: p.dockPresets ?? [], }; } @@ -52,6 +54,7 @@ export function importUiConfig(raw: unknown): string { if (typeof a[k] === "string" && allowed.includes(a[k] as string)) (next as any)[k] = a[k]; } if (typeof a.accent === "string" && ACCENTS.some((x) => x.id === a.accent)) next.accent = a.accent as Prefs["accent"]; + if (f.dockPresets !== undefined) next.dockPresets = sanitizeDockPresets(f.dockPresets); setPrefs(next); controller.applyPrefs(); controller.updateInsets(true); @@ -224,6 +227,11 @@ export function ModesSettings() { Start minimised (a small round button)
+ + +

Pen, highlighter, eraser, laser and undo are always on the dock in Prepare and Teach. Tools set to “⋯ menu” wait in the dock's ⋯ button. Drag the dock by its grip; it remembers where you leave it on each screen size.

diff --git a/apps/board/src/components/StampEditor.css b/apps/board/src/components/StampEditor.css new file mode 100644 index 0000000..fd1d16c --- /dev/null +++ b/apps/board/src/components/StampEditor.css @@ -0,0 +1,63 @@ +/* The stamp editor sheet (StampEditor.tsx): FigJam-flat, tokens only, + * 44px targets, light and dark, mint accent (text on mint #04241b). */ + +.se-backdrop { position: fixed; inset: 0; z-index: 62; display: flex; justify-content: flex-end; background: rgba(10, 12, 16, 0.18); } +.se-sheet { + width: min(440px, 100vw); height: 100%; display: flex; flex-direction: column; + background: var(--surface-solid); color: var(--text); box-shadow: var(--shadow-2); animation: se-in 180ms var(--ease) both; +} +@keyframes se-in { from { transform: translateX(24px); } } +.se-head { display: flex; align-items: center; gap: var(--s3); padding: var(--s4) var(--s4) var(--s3); border-bottom: 1px solid var(--hairline); } +.se-head h2 { margin: 0; font: 700 18px/24px var(--font); } +.se-close { width: 44px; height: 44px; } +.se-body { flex: 1; overflow-y: auto; padding: var(--s3) var(--s4) var(--s5); display: flex; flex-direction: column; gap: var(--s3); } +.se-preview { + position: relative; display: grid; place-items: center; height: 180px; border-radius: 16px; overflow: hidden; + background: var(--page-bg, #fff); box-shadow: inset 0 0 0 1px var(--hairline); + background-image: radial-gradient(var(--hairline) 1px, transparent 1px); background-size: 20px 20px; +} +.se-preview-art { position: relative; display: grid; place-items: center; } +.se-preview-art .stamp-icon, .se-preview-art img { width: var(--s); height: var(--s); } +.se-preview-art .stamp-pill { height: 44px; padding: 0 var(--s5); border-radius: 22px; font-size: 20px; } +.se-preview-art.anim-pop > :first-child { animation: stamp-pop 420ms var(--ease) both; } +.se-preview-art.anim-sparkle > :first-child { animation: stamp-pop 420ms var(--ease) both; } +.se-preview-art.anim-bounce > :first-child { animation: stamp-bounce 700ms cubic-bezier(0.28, 0.84, 0.42, 1) both; } +.se-preview-art.anim-spin > :first-child { animation: stamp-spin 600ms var(--ease) both; } +.se-preview-art.anim-fade-in > :first-child { animation: stamp-fade 500ms var(--ease) both; } +.se-count { right: -14px; top: -10px; min-width: 28px; height: 28px; font-size: 14px; } +.se-play { position: absolute; right: var(--s2); bottom: var(--s2); min-height: 44px; } +.se-field { display: flex; flex-direction: column; gap: var(--s1); } +.se-label { font: 650 13px/18px var(--font); color: var(--text-2); } +.se-field .input { min-height: 44px; } +.se-emoji { font-size: 24px; font-family: "Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji", var(--font); } +.se-svg { min-height: 96px; font: 13px/18px ui-monospace, SFMono-Regular, Menlo, monospace; resize: vertical; } +.se-chips { display: flex; flex-wrap: wrap; gap: var(--s1); } +.se-chips button { + min-height: 44px; padding: 0 var(--s3); border: 0; border-radius: 10px; cursor: pointer; background: var(--hover); color: var(--text); + font: 600 13px/18px var(--font); transition: background-color 120ms var(--ease); +} +.se-chips button:hover { background: var(--accent-3); } +.se-chips button.on { background: var(--accent-9); color: var(--accent-contrast); } +.se-chips button:focus-visible, .se-colors button:focus-visible { outline: 2px solid var(--accent-9); outline-offset: 2px; } +.se-colors { display: flex; flex-wrap: wrap; gap: var(--s1); align-items: center; } +.se-colors button { + width: 44px; height: 44px; border: 0; border-radius: 50%; cursor: pointer; background: var(--c); + box-shadow: inset 0 0 0 1px rgba(0, 0, 40, 0.14), 0 0 0 1px var(--hairline); +} +.se-colors button.on { box-shadow: inset 0 0 0 1px rgba(0, 0, 40, 0.14), 0 0 0 2px var(--surface-solid), 0 0 0 4px var(--accent-9); } +.se-colors input[type="color"] { width: 44px; height: 44px; padding: 4px; border: 1px dashed var(--hairline); border-radius: 50%; background: none; cursor: pointer; } +.se-colors input[type="color"]::-webkit-color-swatch-wrapper { padding: 0; } +.se-colors input[type="color"]::-webkit-color-swatch { border: 0; border-radius: 50%; } +.se-colors input[type="color"]::-moz-color-swatch { border: 0; border-radius: 50%; } +.se-check { min-height: 44px; display: flex; align-items: center; gap: var(--s2); font: 550 14px/20px var(--font); } +.se-note { display: flex; gap: var(--s2); margin: 0; padding: var(--s3); border-radius: 12px; background: var(--accent-3); color: var(--accent-11); font: 550 13px/18px var(--font); } +.se-hint { margin: 0; font: 500 12px/16px var(--font); color: var(--text-2); } +.se-error { display: flex; gap: var(--s2); margin: 0; padding: var(--s3); border-radius: 12px; background: var(--danger-soft); color: var(--text); font: 550 13px/18px var(--font); } +.se-manage { display: flex; flex-wrap: wrap; gap: var(--s2); } +.se-manage .btn, .se-foot .btn { min-height: 44px; } +.se-foot { display: flex; gap: var(--s2); padding: var(--s3) var(--s4); border-top: 1px solid var(--hairline); } +.btn.danger { color: var(--danger); } + +@media (prefers-reduced-motion: reduce) { + .se-sheet, .se-preview-art > :first-child { animation: none !important; } +} diff --git a/apps/board/src/components/StampEditor.tsx b/apps/board/src/components/StampEditor.tsx new file mode 100644 index 0000000..a8d3570 --- /dev/null +++ b/apps/board/src/components/StampEditor.tsx @@ -0,0 +1,252 @@ +// The stamp editor: a small sheet to make or change one of "My stamps": +// preview, name, artwork (emoji, a label or a picture as SVG), colour, size, +// and its behaviour (animation, burst, counter, sound, fade). Smart stamps +// (logic written by the teacher's AI, run in the Smart Object sandbox) keep +// their code; here the teacher changes their name, size and behaviour. +// +// Saving checks the definition in the core (customStamps.saveStamp → +// Board.check_stamp_json) and, when the open lesson uses the stamp, updates +// the lesson's copy too as one undo step. + +import { For, Show, createMemo, createSignal, onCleanup, onMount } from "solid-js"; +import { controller } from "../controller"; +import { deleteStamp, moveStamp, playSound, saveStamp } from "../customStamps"; +import { type CustomStamp, type StampArt, type StampBehavior, lessonStamps, myStamps, setStampEditor, stampEditor } from "../stampLib"; +import { toggleFavorite } from "../stamps"; +import { prefs, showToast } from "../state"; +import { CustomIcon } from "./Stamps"; +import { Icon } from "./Icon"; +import "./StampEditor.css"; + +const COLORS = ["#f5b301", "#30a46c", "#e5484d", "#3e63dd", "#f76b15", "#0d9488", "#d6409f", "#1c2024"]; +const ANIMS: [NonNullable, string][] = [["none", "None"], ["pop", "Pop"], ["sparkle", "Sparkle"], ["bounce", "Bounce"], ["spin", "Spin"], ["fade-in", "Fade in"]]; +const BURSTS: [NonNullable, string][] = [["none", "None"], ["stars", "Stars"], ["confetti", "Confetti"], ["hearts", "Hearts"], ["sparkles", "Sparkles"]]; +const SOUNDS: [NonNullable, string][] = [["none", "None"], ["chime", "Chime"], ["pop", "Pop"], ["ding", "Ding"], ["tada", "Ta-da"], ["clap", "Clap"], ["whoosh", "Whoosh"]]; +const FADES: [number, string][] = [[0, "Never"], [3, "3 s"], [5, "5 s"], [10, "10 s"], [30, "30 s"]]; + +export function StampEditorHost() { + return ( + + {(req) => } + + ); +} + +function StampEditor(props: { id?: string }) { + const orig = myStamps().find((s) => s.id === props.id) ?? lessonStamps()[props.id ?? ""]; + const [d, setD] = createSignal( + orig ? structuredClone(orig) : { id: "", name: "", art: "emoji", emoji: "🦉", color: "#f5b301", size: 96, behavior: { animation: "pop" } }, + ); + const [error, setError] = createSignal(null); + const [replay, setReplay] = createSignal(0); + const set = (p: Partial) => setD({ ...d(), ...p }); + const setB = (p: Partial) => setD({ ...d(), behavior: { ...(d().behavior ?? {}), ...p } }); + const smart = () => d().art === "smart"; + const fav = () => prefs().stampFavorites.includes(d().id); + const close = () => setStampEditor(null); + let sheet!: HTMLDivElement; + + onMount(() => { + const key = (e: KeyboardEvent) => e.key === "Escape" && (e.preventDefault(), close()); + window.addEventListener("keydown", key); + onCleanup(() => window.removeEventListener("keydown", key)); + queueMicrotask(() => sheet.querySelector("#se-name")?.focus()); + }); + + const save = async () => { + setError(null); + try { + const clean = await saveStamp({ ...d(), id: d().id || undefined }); + // The open lesson's copy follows, so placed stamps change too. + if (lessonStamps()[clean.id]) { + const { html: _h, ...rest } = clean; + try { + controller.board.live_apply(JSON.stringify({ op: "update_stamp", ...rest }), ""); + controller.sync(true); + } catch { /* the library copy is saved; the lesson keeps its own */ } + } + showToast(`Saved “${clean.name}” in My stamps`); + close(); + } catch (e: any) { + setError(String(e?.message ?? e)); + } + }; + const remove = async () => { + if (!confirm(`Delete “${d().name}” from My stamps? Lessons that use it keep it.`)) return; + await deleteStamp(d().id); + close(); + }; + const loadSvg = () => { + const i = document.createElement("input"); + i.type = "file"; + i.accept = ".svg,image/svg+xml"; + i.onchange = async () => { + const f = i.files?.[0]; + if (f) set({ svg: await f.text(), art: "svg" }); + }; + i.click(); + }; + const preview = createMemo(() => ({ ...d(), name: d().name || "Stamp" })); + const play = () => { + setReplay((n) => n + 1); + playSound(d().behavior?.sound); + }; + + const Chips = (p: { label: string; value: T; options: [T, string][]; onPick: (v: T) => void; extra?: (v: T) => void }) => ( +
+ {p.label} +
+ + {([v, l]) => ( + + )} + +
+
+ ); + + return ( +
e.target === e.currentTarget && close()}> +