From 47952be1b0dc2c318d8bfd0a9f29fe463e9ec91c Mon Sep 17 00:00:00 2001 From: shaitrish37 <244331886+shaitrish37@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:00:40 +0600 Subject: [PATCH 1/4] live: agent ops for pages, items and custom stamps Every part of the lesson an agent can change, as one attributed undo step, on a lesson file and on the live board with the same code: - pages: list_pages, move_pages, delete_pages, duplicate_pages, set_page_title - items: select_items, move_items, align_items (align and distribute, groups move as one), restyle_items (colour, width, brush, fill, dash, opacity, text size), scale_items, group/ungroup, reorder_items, delete_items, draw_stroke, update_text - stamps: list_stamps, add_stamp (built-in or custom), create_stamp, update_stamp, delete_stamp; custom stamps with sanitised SVG, emoji or a label, declarative behaviour, and Smart stamps (a tiny Smart Object bundle, validated, no network) - board-app ops (modes, view, replay, export, library, settings, dock) are typed in Op and refused by the document Core: Edits gains texts and stamp_defs; the lesson's root stamps map holds custom stamp definitions (proposed, pending RFC). --- crates/rupok-core/src/doc.rs | 155 ++++ crates/rupok-core/src/lib.rs | 2 +- crates/rupok-core/src/model.rs | 8 + crates/rupok-live/src/agent_ops_tests.rs | 819 ++++++++++++++++++ crates/rupok-live/src/apply.rs | 56 +- crates/rupok-live/src/design.rs | 2 + crates/rupok-live/src/items.rs | 1005 ++++++++++++++++++++++ crates/rupok-live/src/lib.rs | 10 +- crates/rupok-live/src/op.rs | 538 +++++++++++- crates/rupok-live/src/stamps.rs | 865 +++++++++++++++++++ crates/rupok-wasm/src/lib.rs | 10 + crates/rupok-wasm/src/live.rs | 109 +++ 12 files changed, 3564 insertions(+), 15 deletions(-) create mode 100644 crates/rupok-live/src/agent_ops_tests.rs create mode 100644 crates/rupok-live/src/items.rs create mode 100644 crates/rupok-live/src/stamps.rs diff --git a/crates/rupok-core/src/doc.rs b/crates/rupok-core/src/doc.rs index 08c1d6d..31b9a7f 100644 --- a/crates/rupok-core/src/doc.rs +++ b/crates/rupok-core/src/doc.rs @@ -749,6 +749,13 @@ impl Lesson { /// is missing (the error is returned and the edit is rolled back by the /// caller's next undo-free commit; callers pass ids from the scene). pub fn apply_edits(&mut self, page_id: &str, e: &Edits) -> Result> { + if let Some((id, _)) = e.stamp_defs.iter().find(|(id, d)| { + !valid_name(id) || d.as_ref().is_some_and(|j| j.len() > MAX_STAMP_DEF_BYTES) + }) { + return Err(CoreError::Corrupt(format!( + "stamp `{id}`: bad id or definition too large" + ))); + } let items = self.items_map(page_id)?; for (id, dx, dy) in &e.translate { Self::write_translate(&items, id, *dx, *dy)?; @@ -774,6 +781,25 @@ impl Lesson { m.insert("color", i64::from(*rgba))?; } } + for (id, text) in &e.texts { + let m = item_map(&items, id)?; + if str_of(&m, "kind").as_deref() == Some("text") { + m.insert("text", text.as_str())?; + } + } + if !e.stamp_defs.is_empty() { + let defs = self.doc.get_map("stamps"); + for (id, def) in &e.stamp_defs { + match def { + Some(json) => defs.insert(id, json.as_str())?, + None => { + if defs.get(id).is_some() { + defs.delete(id)?; + } + } + } + } + } for id in &e.remove { if items.get(id).is_some() { items.delete(id)?; @@ -796,6 +822,35 @@ impl Lesson { Ok(ids) } + /// Custom stamp definitions stored in the lesson (the root `stamps` map, + /// spec: Custom stamps): `(id, JSON)` sorted by id. Entries that are not + /// strings, have a bad id or are too large are skipped (untrusted input). + pub fn stamp_defs(&self) -> Vec<(String, String)> { + let mut out = Vec::new(); + self.doc.get_map("stamps").for_each(|k, v| { + if let ValueOrContainer::Value(LoroValue::String(s)) = v + && valid_name(k) + && s.len() <= MAX_STAMP_DEF_BYTES + { + out.push((k.to_string(), s.to_string())); + } + }); + out.sort(); + out + } + + /// One custom stamp definition (JSON), if the lesson has it. + pub fn stamp_def(&self, id: &str) -> Option { + match self.doc.get_map("stamps").get(id)? { + ValueOrContainer::Value(LoroValue::String(s)) + if valid_name(id) && s.len() <= MAX_STAMP_DEF_BYTES => + { + Some(s.to_string()) + } + _ => None, + } + } + /// Set the geometry of a box item (text, image, object). pub fn set_geom(&mut self, page_id: &str, id: &str, g: BoxGeom) -> Result<()> { let m = item_map(&self.items_map(page_id)?, id)?; @@ -1303,6 +1358,9 @@ fn read_geom(m: &impl Fields) -> BoxGeom { /// A `brush` or `stamp` name: short, lowercase ASCII words (`a-z`, `0-9`, /// `-`). Anything else is treated as absent. +/// Largest custom stamp definition (JSON, with its SVG) a lesson stores. +pub const MAX_STAMP_DEF_BYTES: usize = 256 * 1024; + fn valid_name(s: &str) -> bool { !s.is_empty() && s.len() <= 32 @@ -1867,6 +1925,7 @@ mod tests { z: None, }], text_colors: vec![], + ..Default::default() }, ) .unwrap(); @@ -2714,3 +2773,99 @@ mod tests { assert!(l.set_media(&p, &s, &youtube(), None).is_err()); } } + +#[cfg(test)] +mod stamp_def_tests { + use super::*; + + fn text(s: &str) -> ItemData { + ItemData::Text(TextData { + geom: BoxGeom { + x: 0.0, + y: 0.0, + w: 96.0, + h: 96.0, + rot: 0.0, + }, + text: s.into(), + size: 60.0, + color: 0x000000ff, + latex: false, + stamp: Some("c-dice".into()), + }) + } + + #[test] + fn a_stamp_and_its_definition_are_one_change() { + let mut l = Lesson::new("S", 1.0); + let page = l.page_id_at(0).unwrap(); + let ids = l + .apply_edits( + &page, + &Edits { + add: vec![NewItem { + data: text("🎲"), + created: 2.0, + group: None, + z: None, + }], + stamp_defs: vec![("c-dice".into(), Some(r#"{"name":"Dice"}"#.into()))], + ..Default::default() + }, + ) + .unwrap(); + assert_eq!(ids.len(), 1); + assert_eq!(l.stamp_def("c-dice").as_deref(), Some(r#"{"name":"Dice"}"#)); + assert_eq!(l.stamp_defs().len(), 1); + // text replaced in the same kind of change + l.apply_edits( + &page, + &Edits { + texts: vec![(ids[0].clone(), "🎯".into())], + ..Default::default() + }, + ) + .unwrap(); + match &l.item(&page, &ids[0]).unwrap().data { + ItemData::Text(t) => assert_eq!(t.text, "🎯"), + _ => panic!(), + } + assert!(l.undo().unwrap()); + assert!(l.undo().unwrap()); + assert!(l.items(&page).unwrap().is_empty()); + assert!( + l.stamp_defs().is_empty(), + "one undo removes stamp and definition" + ); + // bad ids are refused, removal of a missing id is harmless + assert!( + l.apply_edits( + &page, + &Edits { + stamp_defs: vec![("Bad Id".into(), Some("{}".into()))], + ..Default::default() + } + ) + .is_err() + ); + l.apply_edits( + &page, + &Edits { + stamp_defs: vec![("c-gone".into(), None)], + ..Default::default() + }, + ) + .unwrap(); + // survives save and load + l.apply_edits( + &page, + &Edits { + stamp_defs: vec![("c-star".into(), Some("{}".into()))], + ..Default::default() + }, + ) + .unwrap(); + let back = Lesson::load(&l.save()).unwrap(); + assert_eq!(back.stamp_def("c-star").as_deref(), Some("{}")); + } +} diff --git a/crates/rupok-core/src/lib.rs b/crates/rupok-core/src/lib.rs index cc2f8b9..e36db88 100644 --- a/crates/rupok-core/src/lib.rs +++ b/crates/rupok-core/src/lib.rs @@ -14,7 +14,7 @@ pub mod doc; pub mod model; pub mod scene; -pub use doc::{CoreError, Lesson, media_from_value}; +pub use doc::{CoreError, Lesson, MAX_STAMP_DEF_BYTES, media_from_value}; pub use model::*; pub use scene::Scene; diff --git a/crates/rupok-core/src/model.rs b/crates/rupok-core/src/model.rs index ca89de5..76895a8 100644 --- a/crates/rupok-core/src/model.rs +++ b/crates/rupok-core/src/model.rs @@ -649,6 +649,12 @@ pub struct Edits { pub add: Vec, /// Recolour text items (0xRRGGBBAA); other kinds are skipped. pub text_colors: Vec<(ItemId, u32)>, + /// Replace the text of text items; other kinds are skipped. + pub texts: Vec<(ItemId, String)>, + /// Set (`Some(json)`) or remove (`None`) custom stamp definitions in the + /// lesson's root `stamps` map (see [`crate::Lesson::stamp_defs`]), so a + /// stamp placed with a new definition is one change. + pub stamp_defs: Vec<(String, Option)>, } impl Edits { @@ -660,6 +666,8 @@ impl Edits { && self.remove.is_empty() && self.add.is_empty() && self.text_colors.is_empty() + && self.texts.is_empty() + && self.stamp_defs.is_empty() } } diff --git a/crates/rupok-live/src/agent_ops_tests.rs b/crates/rupok-live/src/agent_ops_tests.rs new file mode 100644 index 0000000..22044a4 --- /dev/null +++ b/crates/rupok-live/src/agent_ops_tests.rs @@ -0,0 +1,819 @@ +//! Tests of the agent operations on pages, items and stamps +//! (`items.rs`, `stamps.rs`): each write is one attributed undo step, +//! input is validated, Student view refuses writes, board-app ops are +//! refused by the document. + +use rupok_core::{Item, ItemData, Lesson}; +use rupok_format::Package; +use serde_json::{Value, json}; + +use crate::apply::{BoardCtx, LiveError, Outcome, apply}; +use crate::op::{Access, Op}; + +struct Board { + pkg: Package, + lesson: Lesson, + page: String, + selection: Vec, + read_only: bool, +} + +impl Board { + fn new() -> Self { + let lesson = Lesson::new("Agent", 1_000.0); + let pkg = Package::from_lesson(&lesson, "test", 1_000.0); + let page = lesson.page_id_at(0).unwrap(); + Self { + pkg, + lesson, + page, + selection: Vec::new(), + read_only: false, + } + } + fn run(&mut self, v: Value) -> Result { + let op: Op = serde_json::from_value(v).expect("op parses"); + let out = apply( + BoardCtx { + pkg: &mut self.pkg, + lesson: &mut self.lesson, + page_id: &self.page, + selection: &self.selection, + read_only: self.read_only, + }, + &op, + "Claude Code", + 9_000.0, + )?; + if let Some(i) = out.show_page { + self.page = self.lesson.page_id_at(i).unwrap(); + } + Ok(out) + } + fn ok(&mut self, v: Value) -> Value { + match self.run(v.clone()) { + Ok(o) => o.result, + Err(e) => panic!("{v} failed: {e}"), + } + } + fn err(&mut self, v: Value) -> String { + match self.run(v.clone()) { + Ok(o) => panic!("{v} should fail, got {}", o.result), + Err(e) => e.to_string(), + } + } + fn items(&self) -> Vec { + self.lesson.items(&self.page).unwrap() + } + fn item(&self, id: &str) -> Item { + self.lesson.item(&self.page, id).unwrap() + } + fn last_message(&self) -> Option<(String, String)> { + let f = self.lesson.loro().oplog_frontiers(); + let id = f.iter().next()?; + let m = self.lesson.loro().get_change(id)?.message?.to_string(); + crate::parse_commit_message(&m) + } + /// Run a write; it must be one undo step tagged with the agent and op. + fn one_step(&mut self, v: Value) -> Value { + let before = self.lesson.save(); + let name = v["op"].as_str().unwrap().to_string(); + let out = self.ok(v); + assert_eq!( + self.last_message(), + Some(("Claude Code".into(), name.clone())), + "{name} is attributed" + ); + assert!(self.lesson.undo().unwrap(), "{name} can be undone"); + let undone = Lesson::load(&self.lesson.save()).unwrap(); + let orig = Lesson::load(&before).unwrap(); + assert_eq!( + outline(&undone), + outline(&orig), + "one undo takes back all of {name}" + ); + assert!(self.lesson.redo().unwrap()); + out + } + fn stroke(&mut self, pts: &[(f64, f64)]) -> String { + let r = self.ok(json!({"op": "draw_stroke", "points": pts.iter().map(|(x, y)| vec![*x, *y]).collect::>()})); + r["item_ids"][0].as_str().unwrap().to_string() + } + fn text(&mut self, t: &str, x: f64, y: f64) -> String { + let r = self.ok(json!({"op": "add_text", "text": t, "x": x, "y": y, "size": 40})); + r["item_id"].as_str().unwrap().to_string() + } +} + +/// Everything visible about a lesson, to compare before/after an undo. +fn outline(l: &Lesson) -> Value { + let pages: Vec = l + .pages() + .iter() + .map(|p| { + let items: Vec = l + .items(&p.id) + .unwrap() + .iter() + .map(|i| json!([i.id, format!("{:?}", i.data), i.group, i.z])) + .collect(); + json!([p.id, p.title, items]) + }) + .collect(); + json!({ "pages": pages, "stamps": l.stamp_defs() }) +} + +#[test] +fn pages_list_move_delete_duplicate_rename() { + let mut b = Board::new(); + for t in ["Two", "Three", "Four"] { + b.ok(json!({"op": "add_page", "title": t})); + } + let l = b.ok(json!({"op": "list_pages"})); + assert_eq!(l["page_count"], 4); + assert_eq!(l["pages"][1]["title"], "Two"); + let ids: Vec = b.lesson.pages().iter().map(|p| p.id.clone()).collect(); + + // move pages 3 and 4 to the front + let r = b.one_step(json!({"op": "move_pages", "pages": [3, 4], "to": 1})); + assert_eq!(r["pages_now"], json!([1, 2])); + let now: Vec = b.lesson.pages().iter().map(|p| p.id.clone()).collect(); + assert_eq!( + now, + vec![ + ids[2].clone(), + ids[3].clone(), + ids[0].clone(), + ids[1].clone() + ] + ); + // move one page to the end + b.one_step(json!({"op": "move_pages", "pages": [1], "to": 4})); + assert_eq!(b.lesson.pages()[3].id, ids[2]); + assert!( + b.err(json!({"op": "move_pages", "pages": [1], "to": 9})) + .contains("between 1 and 4") + ); + assert!( + b.err(json!({"op": "move_pages", "pages": [], "to": 1})) + .contains("at least one") + ); + assert!( + b.err(json!({"op": "move_pages", "pages": [7], "to": 1})) + .contains("does not exist") + ); + + let r = b.one_step(json!({"op": "duplicate_pages", "pages": [2]})); + assert_eq!(r["copies"], json!([3])); + assert_eq!(b.lesson.page_count(), 5); + + b.one_step(json!({"op": "set_page_title", "page": 1, "title": "Intro"})); + assert_eq!(b.lesson.pages()[0].title, "Intro"); + + let r = b.one_step(json!({"op": "delete_pages", "pages": [2, 3]})); + assert_eq!(r["deleted"], 2); + assert!( + b.err(json!({"op": "delete_pages", "pages": [1, 2, 3]})) + .contains("at least one page") + ); +} + +#[test] +fn deleting_the_page_on_screen_shows_a_neighbour() { + let mut b = Board::new(); + b.ok(json!({"op": "add_page"})); + b.ok(json!({"op": "go_to_page", "page": 2})); + let out = b.run(json!({"op": "delete_pages", "pages": [2]})).unwrap(); + assert_eq!(out.show_page, Some(0)); +} + +#[test] +fn select_move_align_distribute() { + let mut b = Board::new(); + let a = b.text("A", 100.0, 100.0); + let c = b.text("B", 400.0, 160.0); + let d = b.text("C", 900.0, 130.0); + + let out = b + .run(json!({"op": "select_items", "item_ids": [a, c]})) + .unwrap(); + assert_eq!(out.select, Some(vec![a.clone(), c.clone()])); + assert!(!out.changed); + assert_eq!( + serde_json::from_value::(json!({"op": "select_items", "item_ids": []})) + .unwrap() + .access(), + Access::Control + ); + assert!( + b.err(json!({"op": "select_items", "item_ids": ["nope"]})) + .contains("not on page 1") + ); + + b.one_step(json!({"op": "move_items", "item_ids": [a], "dx": 10, "dy": 5})); + let g = |b: &Board, id: &str| match b.item(id).data { + ItemData::Text(t) => t.geom, + _ => panic!(), + }; + assert_eq!((g(&b, &a).x, g(&b, &a).y), (110.0, 105.0)); + b.one_step(json!({"op": "move_items", "item_ids": [a], "x": 50, "y": 60})); + assert_eq!((g(&b, &a).x, g(&b, &a).y), (50.0, 60.0)); + assert!( + b.err(json!({"op": "move_items", "item_ids": [a]})) + .contains("dx/dy") + ); + + b.one_step(json!({"op": "align_items", "item_ids": [a, c, d], "align": "top"})); + assert_eq!(g(&b, &a).y, g(&b, &c).y); + assert_eq!(g(&b, &c).y, g(&b, &d).y); + b.one_step(json!({"op": "align_items", "item_ids": [a, c, d], "distribute": "horizontal"})); + let (ga, gc, gd) = (g(&b, &a), g(&b, &c), g(&b, &d)); + let gap1 = gc.x - (ga.x + ga.w); + let gap2 = gd.x - (gc.x + gc.w); + assert!((gap1 - gap2).abs() < 0.01, "{gap1} vs {gap2}"); + b.one_step( + json!({"op": "align_items", "item_ids": [a], "align": "center", "relative_to": "page"}), + ); + let ga = g(&b, &a); + assert!((ga.x + ga.w / 2.0 - 960.0).abs() < 0.01); + assert!( + b.err(json!({"op": "align_items", "item_ids": [a], "align": "left"})) + .contains("two or more") + ); + assert!( + b.err(json!({"op": "align_items", "item_ids": [a, c], "align": "sideways"})) + .contains("align must be") + ); + assert!( + b.err(json!({"op": "align_items", "item_ids": [a, c], "distribute": "vertical"})) + .contains("three or more") + ); +} + +#[test] +fn grouped_ink_aligns_as_one_unit() { + let mut b = Board::new(); + let s1 = b.stroke(&[(100.0, 100.0), (150.0, 140.0)]); + let s2 = b.stroke(&[(160.0, 300.0), (200.0, 340.0)]); + let t = b.text("T", 600.0, 500.0); + b.one_step(json!({"op": "group_items", "item_ids": [s1, s2]})); + assert!(b.item(&s1).group.is_some()); + assert_eq!(b.item(&s1).group, b.item(&s2).group); + let before1 = b.item(&s1).data.aabb(); + let before2 = b.item(&s2).data.aabb(); + b.ok(json!({"op": "align_items", "item_ids": [s1, s2, t], "align": "left"})); + let after1 = b.item(&s1).data.aabb(); + let after2 = b.item(&s2).data.aabb(); + // both strokes moved by the same amount: the group kept its shape + assert!(((after1[0] - before1[0]) - (after2[0] - before2[0])).abs() < 0.01); + b.one_step(json!({"op": "ungroup_items", "item_ids": [s1]})); + assert!(b.item(&s1).group.is_none() && b.item(&s2).group.is_none()); + let e = b.err(json!({"op": "ungroup_items", "item_ids": [t]})); + assert!(e.contains("is in a group"), "{e}"); + assert!( + b.err(json!({"op": "group_items", "item_ids": [t]})) + .contains("two items") + ); +} + +#[test] +fn restyle_scale_reorder_delete() { + let mut b = Board::new(); + let s = b.stroke(&[(100.0, 100.0), (300.0, 200.0)]); + let h = b.ok( + json!({"op": "draw_stroke", "tool": "highlighter", "points": [[100, 300], [400, 300]]}), + )["item_ids"][0] + .as_str() + .unwrap() + .to_string(); + let t = b.text("Hello", 500.0, 500.0); + + let r = b.one_step(json!({"op": "restyle_items", "item_ids": [s, h, t], "color": "#e5484d", "width": 8, "brush": "chalk"})); + assert_eq!(r["restyled"], 3); + match b.item(&s).data { + ItemData::Stroke(st) => { + assert_eq!(st.color, 0xe5484dff); + assert_eq!(st.width, 8.0); + assert_eq!(st.brush.as_deref(), Some("chalk")); + } + _ => panic!(), + } + match b.item(&h).data { + ItemData::Stroke(st) => assert!( + (st.opacity - 0.38).abs() < 1e-6, + "highlighter keeps its translucency" + ), + _ => panic!(), + } + match b.item(&t).data { + ItemData::Text(tx) => assert_eq!(tx.color, 0xe5484dff), + _ => panic!(), + } + b.one_step(json!({"op": "restyle_items", "item_ids": [s], "brush": "pen", "opacity": 0.5})); + match b.item(&s).data { + ItemData::Stroke(st) => { + assert_eq!(st.brush, None); + assert_eq!(st.opacity, 0.5); + } + _ => panic!(), + } + b.one_step(json!({"op": "restyle_items", "item_ids": [t], "text_size": 80})); + match b.item(&t).data { + ItemData::Text(tx) => assert_eq!(tx.size, 80.0), + _ => panic!(), + } + assert!( + b.err(json!({"op": "restyle_items", "item_ids": [s]})) + .contains("nothing to change") + ); + assert!( + b.err(json!({"op": "restyle_items", "item_ids": [s], "brush": "magic"})) + .contains("brush must be") + ); + assert!( + b.err(json!({"op": "restyle_items", "item_ids": [s], "color": "red"})) + .contains("#rrggbb") + ); + assert!( + b.err(json!({"op": "restyle_items", "item_ids": [s], "opacity": 3})) + .contains("opacity") + ); + + // a uniform scale about the centre + let before = b.item(&s).data.aabb(); + b.one_step(json!({"op": "scale_items", "item_ids": [s], "factor": 2})); + let after = b.item(&s).data.aabb(); + let (bw, aw) = (before[2] - before[0], after[2] - after[0]); + let (bc, ac) = ((before[0] + before[2]) / 2.0, (after[0] + after[2]) / 2.0); + assert!((aw / bw - 2.0).abs() < 0.05, "{bw} → {aw}"); + assert!((ac - bc).abs() < 0.5); + match b.item(&s).data { + ItemData::Stroke(st) => assert_eq!(st.width, 16.0), + _ => panic!(), + } + assert!( + b.err(json!({"op": "scale_items", "item_ids": [s], "factor": 0})) + .contains("factor") + ); + + // reorder + b.one_step(json!({"op": "reorder_items", "item_ids": [s], "to": "front"})); + assert_eq!(b.items().last().unwrap().id, s); + b.one_step(json!({"op": "reorder_items", "item_ids": [s], "to": "back"})); + assert_eq!(b.items().first().unwrap().id, s); + assert!( + b.err(json!({"op": "reorder_items", "item_ids": [s], "to": "up"})) + .contains("front or back") + ); + + let r = b.one_step(json!({"op": "delete_items", "item_ids": [s, h]})); + assert_eq!(r["deleted"], 2); + assert_eq!(b.items().len(), 1); + assert!( + b.err(json!({"op": "delete_items", "item_ids": []})) + .contains("item_ids") + ); +} + +#[test] +fn shapes_keep_fill_and_scale_with_their_geometry() { + let mut b = Board::new(); + let pts: Vec = [ + (100.0, 100.0), + (300.0, 100.0), + (300.0, 200.0), + (100.0, 200.0), + (100.0, 100.0), + ] + .iter() + .enumerate() + .map(|(i, (x, y))| rupok_ink::StrokePoint { + x: *x, + y: *y, + p: 0.6, + dt: i as u32 * 10, + }) + .collect(); + let id = b + .lesson + .add_item( + &b.page.clone(), + &ItemData::Stroke(rupok_core::StrokeData { + tool: "pen".into(), + color: 0x000000ff, + width: 4.0, + opacity: 1.0, + points: pts, + offset: [10.0, 0.0], + shape: Some("rect".into()), + geom: Some(rupok_core::ShapeGeom { + kind: "rect".into(), + x: 100.0, + y: 100.0, + w: 200.0, + h: 100.0, + ..Default::default() + }), + brush: None, + }), + 1.0, + ) + .unwrap(); + b.one_step( + json!({"op": "restyle_items", "item_ids": [id], "fill": "#20c99733", "dashed": true}), + ); + let geom = |b: &Board| match b.item(&id).data { + ItemData::Stroke(s) => (s.geom.unwrap(), s.offset), + _ => panic!(), + }; + let (g, _) = geom(&b); + assert_eq!(g.fill, Some(0x20c99733)); + assert!(g.dash); + b.one_step(json!({"op": "scale_items", "item_ids": [id], "factor": 0.5})); + let (g, off) = geom(&b); + assert_eq!(off, [0.0, 0.0], "the offset is folded in"); + assert!((g.w - 100.0).abs() < 1e-6 && (g.h - 50.0).abs() < 1e-6); + b.ok(json!({"op": "restyle_items", "item_ids": [id], "fill": "none"})); + assert_eq!(geom(&b).0.fill, None); +} + +#[test] +fn draw_stroke_and_update_text() { + let mut b = Board::new(); + let r = b.one_step(json!({ + "op": "draw_stroke", + "strokes": [ + {"points": [[100, 100], [200, 150, 0.8], [300, 100]], "color": "#3e63dd", "brush": "fountain"}, + {"points": [[100, 300], [300, 300]], "width": 10} + ] + })); + assert_eq!(r["item_ids"].as_array().unwrap().len(), 2); + let first = r["item_ids"][0].as_str().unwrap().to_string(); + match b.item(&first).data { + ItemData::Stroke(s) => { + assert_eq!(s.color, 0x3e63ddff); + assert_eq!(s.brush.as_deref(), Some("fountain")); + assert!( + s.points.windows(2).all(|w| w[1].dt > w[0].dt), + "timed for replay" + ); + } + _ => panic!(), + } + assert!(b.err(json!({"op": "draw_stroke"})).contains("points")); + assert!( + b.err(json!({"op": "draw_stroke", "points": [[1]]})) + .contains("[x, y]") + ); + assert!( + b.err(json!({"op": "draw_stroke", "points": [[1, 2, 5]]})) + .contains("pressure") + ); + assert!( + b.err(json!({"op": "draw_stroke", "points": [[1, 2]], "tool": "spray"})) + .contains("pen or highlighter") + ); + + let t = b.text("Old", 100.0, 500.0); + b.one_step(json!({"op": "update_text", "item_id": t, "text": "New text", "size": 60, "color": "#30a46c", "x": 120})); + match b.item(&t).data { + ItemData::Text(tx) => { + assert_eq!(tx.text, "New text"); + assert_eq!(tx.size, 60.0); + assert_eq!(tx.color, 0x30a46cff); + assert_eq!(tx.geom.x, 120.0); + } + _ => panic!(), + } + assert!( + b.err(json!({"op": "update_text", "item_id": t})) + .contains("nothing to change") + ); + assert!( + b.err(json!({"op": "update_text", "item_id": first, "text": "x"})) + .contains("not a text box") + ); +} + +#[test] +fn builtin_stamps_are_placed_like_the_board_does() { + let mut b = Board::new(); + let r = b.one_step(json!({"op": "add_stamp", "stamp": "star", "x": 100, "y": 100})); + let id = r["item_id"].as_str().unwrap().to_string(); + match b.item(&id).data { + ItemData::Text(t) => { + assert_eq!(t.stamp.as_deref(), Some("star")); + assert_eq!(t.text, "⭐"); + assert_eq!((t.geom.w, t.geom.h), (96.0, 96.0)); + } + _ => panic!(), + } + let r = b.ok(json!({"op": "add_stamp", "stamp": "badge"})); + let r2 = b.ok(json!({"op": "add_stamp", "stamp": "badge"})); + let txt = |b: &Board, v: &Value| match b.item(v["item_id"].as_str().unwrap()).data { + ItemData::Text(t) => t.text, + _ => panic!(), + }; + assert_eq!(txt(&b, &r), "1"); + assert_eq!(txt(&b, &r2), "2"); + let r = b.ok(json!({"op": "add_stamp", "stamp": "excellent", "text": "Brilliant!"})); + assert_eq!(txt(&b, &r), "Brilliant!"); + assert!( + b.err(json!({"op": "add_stamp", "stamp": "emoji"})) + .contains("needs `text`") + ); + assert!( + b.err(json!({"op": "add_stamp", "stamp": "nope"})) + .contains("no stamp") + ); + assert!( + b.err(json!({"op": "add_stamp", "stamp": "Bad!"})) + .contains("no stamp") + ); + assert!( + b.err(json!({"op": "add_stamp", "stamp": "star", "size": 5})) + .contains("size") + ); + let l = b.ok(json!({"op": "list_stamps"})); + assert_eq!( + l["builtin"].as_array().unwrap().len(), + crate::stamps::BUILTINS.len() + ); +} + +const SPARKLE_SVG: &str = r##""##; + +const DICE: &str = r#"Dice + +
⚀
"#; + +#[test] +fn custom_svg_stamp_with_behaviour_lifecycle() { + let mut b = Board::new(); + let r = b.one_step(json!({ + "op": "create_stamp", "name": "Super star", "keywords": ["Star", "praise"], + "art": "svg", "svg": SPARKLE_SVG, "color": "#f5b301", + "behavior": {"animation": "sparkle", "burst": "stars", "burst_colors": ["#ffd43b"], "counter": true, "sound": "chime"} + })); + let id = r["id"].as_str().unwrap().to_string(); + assert!(id.starts_with("c-super-star-"), "{id}"); + assert!(crate::stamps::valid_id(&id)); + let def = b.lesson.stamp_def(&id).unwrap(); + assert!(def.contains("xmlns"), "sanitised SVG stored: {def}"); + assert!(def.contains("\"keywords\":[\"star\",\"praise\"]")); + + // place it twice: a text item naming the definition, counted on the page + let p1 = b.one_step(json!({"op": "add_stamp", "stamp": id, "x": 200, "y": 200})); + let p2 = b.ok(json!({"op": "add_stamp", "stamp": id, "x": 400, "y": 200, "size": 140})); + assert_eq!(p1["behavior"]["animation"], "sparkle"); + assert_eq!(p2["count_on_page"], 2); + match b.item(p2["item_id"].as_str().unwrap()).data { + ItemData::Text(t) => { + assert_eq!(t.stamp.as_deref(), Some(id.as_str())); + assert_eq!( + t.text, "Super star", + "fallback text for readers without stamps" + ); + assert_eq!(t.color, 0xf5b301ff); + assert_eq!(t.geom.h, 140.0); + } + _ => panic!(), + } + let l = b.ok(json!({"op": "list_stamps"})); + assert_eq!(l["custom"][0]["placements"], 2); + + // update: only the given fields change + b.one_step(json!({"op": "update_stamp", "id": id, "name": "Gold star", "behavior": {"animation": "bounce"}})); + let d = crate::stamps::lesson_def(&b.lesson, &id).unwrap(); + assert_eq!(d.name.as_deref(), Some("Gold star")); + assert_eq!(d.art.as_deref(), Some("svg")); + assert!(d.svg.is_some()); + assert_eq!(d.behavior.unwrap().animation.as_deref(), Some("bounce")); + + // delete: placements keep it unless asked + let r = b.ok(json!({"op": "delete_stamp", "id": id})); + assert_eq!(r["kept_in_lesson"], true); + assert!(b.lesson.stamp_def(&id).is_some()); + let r = b.one_step(json!({"op": "delete_stamp", "id": id, "remove_placements": true})); + assert_eq!(r["placements_removed"], 2); + assert!(b.lesson.stamp_def(&id).is_none()); + assert!(b.items().is_empty()); + assert!( + b.err(json!({"op": "delete_stamp", "id": id})) + .contains("no custom stamp") + ); + assert!( + b.run(json!({"op": "delete_stamp", "id": id, "in_library": true})) + .is_ok() + ); +} + +#[test] +fn stamp_validation_is_strict() { + let mut b = Board::new(); + let bad = [ + ( + json!({"op": "create_stamp", "art": "emoji", "emoji": "🦉"}), + "name", + ), + ( + json!({"op": "create_stamp", "name": "X"}), + "art is required", + ), + ( + json!({"op": "create_stamp", "name": "X", "art": "gif"}), + "art must be", + ), + ( + json!({"op": "create_stamp", "name": "X", "art": "svg", "svg": ""}), + "svg refused", + ), + ( + json!({"op": "create_stamp", "name": "X", "art": "svg", "svg": ""}), + "svg refused", + ), + ( + json!({"op": "create_stamp", "name": "X", "art": "emoji"}), + "needs `emoji`", + ), + ( + json!({"op": "create_stamp", "name": "X", "art": "text", "text": "a very long label that goes on and on"}), + "1 to 24", + ), + ( + json!({"op": "create_stamp", "name": "X", "art": "emoji", "emoji": "⭐", "behavior": {"animation": "explode"}}), + "animation must be", + ), + ( + json!({"op": "create_stamp", "name": "X", "art": "emoji", "emoji": "⭐", "behavior": {"sound": "siren"}}), + "sound must be", + ), + ( + json!({"op": "create_stamp", "name": "X", "art": "emoji", "emoji": "⭐", "behavior": {"fade_after": 9999}}), + "fade_after", + ), + ( + json!({"op": "create_stamp", "name": "X", "art": "emoji", "emoji": "⭐", "id": "star"}), + "built-in", + ), + ( + json!({"op": "create_stamp", "name": "X", "art": "emoji", "emoji": "⭐", "id": "Bad Id"}), + "id must be", + ), + ( + json!({"op": "create_stamp", "name": "X", "art": "smart"}), + "needs `html`", + ), + ( + json!({"op": "create_stamp", "name": "X", "art": "emoji", "emoji": "⭐", "size": 5000}), + "size", + ), + ( + json!({"op": "update_stamp", "id": "star", "name": "Y"}), + "built-in", + ), + ( + json!({"op": "update_stamp", "id": "c-none", "name": "Y"}), + "no custom stamp", + ), + ]; + for (op, want) in bad { + let e = b.err(op.clone()); + assert!(e.contains(want), "{op}: {e}"); + } + assert!(b.lesson.stamp_defs().is_empty(), "nothing was stored"); + // the same id twice + b.ok(json!({"op": "create_stamp", "id": "owl", "name": "Owl", "art": "emoji", "emoji": "🦉"})); + assert!( + b.err( + json!({"op": "create_stamp", "id": "owl", "name": "Owl", "art": "emoji", "emoji": "🦉"}) + ) + .contains("already exists") + ); + // no picture/smart switch + assert!( + b.err(json!({"op": "update_stamp", "id": "owl", "art": "smart", "html": DICE})) + .contains("cannot become") + ); +} + +#[test] +fn smart_stamps_run_as_sandboxed_objects() { + let mut b = Board::new(); + let r = b.one_step(json!({ + "op": "create_stamp", "id": "dice", "name": "Dice", "art": "smart", "html": DICE, + "width": 160, "height": 160, "behavior": {"animation": "pop"} + })); + let bundle = r["stamp"]["bundle"].as_str().unwrap().to_string(); + assert!(b.pkg.objects.contains_key(&bundle)); + assert!( + !b.lesson.stamp_def("dice").unwrap().contains("Math.random"), + "the HTML is in the bundle, not the definition" + ); + let p = b.one_step(json!({"op": "add_stamp", "stamp": "dice", "x": 100, "y": 100})); + let item = b.item(p["item_id"].as_str().unwrap()); + match &item.data { + ItemData::Object(o) => { + assert_eq!(o.bundle, bundle); + assert_eq!((o.geom.w, o.geom.h), (160.0, 160.0)); + } + _ => panic!("a Smart stamp is an object"), + } + // a second stamp with the same HTML shares the bundle + let r2 = b.ok( + json!({"op": "create_stamp", "id": "dice-2", "name": "Dice", "art": "smart", "html": DICE}), + ); + assert_eq!(r2["stamp"]["bundle"], json!(bundle)); + // network is refused: the sandbox rules apply unchanged + let net = r#""#; + let e = b + .run(json!({"op": "create_stamp", "name": "Net", "art": "smart", "html": net})) + .unwrap_err(); + assert!(matches!(e, LiveError::Diagnostics(_)), "{e}"); + // new HTML re-points the placement + let newer = DICE.replace("⚀", "⚅"); + let u = b.ok(json!({"op": "update_stamp", "id": "dice", "html": newer})); + assert_eq!(u["placements_updated"], 1); + let nb = u["stamp"]["bundle"].as_str().unwrap(); + assert_ne!(nb, bundle); + assert!( + b.items() + .iter() + .any(|i| matches!(&i.data, ItemData::Object(o) if o.bundle == nb)) + ); +} + +#[test] +fn a_stamp_from_the_device_library_comes_with_its_definition() { + let mut b = Board::new(); + let def = + json!({"name": "Owl", "art": "emoji", "emoji": "🦉", "behavior": {"burst": "hearts"}}); + let r = b.one_step(json!({"op": "add_stamp", "stamp": "c-owl", "def": def})); + assert!( + b.lesson.stamp_def("c-owl").is_some(), + "stored with the placement, one step" + ); + match b.item(r["item_id"].as_str().unwrap()).data { + ItemData::Text(t) => assert_eq!(t.text, "🦉"), + _ => panic!(), + } + // update of a library-only stamp: checked, not stored + let u = b + .ok(json!({"op": "update_stamp", "id": "c-lib", "name": "New", "base": {"name": "Lib", "art": "text", "text": "Yes!"}})); + assert_eq!(u["in_lesson"], false); + assert_eq!(u["stamp"]["text"], "Yes!"); + assert!(b.lesson.stamp_def("c-lib").is_none()); +} + +#[test] +fn student_view_refuses_every_new_write_and_board_ops_are_not_document_ops() { + let mut b = Board::new(); + let t = b.text("x", 10.0, 10.0); + b.read_only = true; + for op in [ + json!({"op": "move_pages", "pages": [1], "to": 1}), + json!({"op": "delete_items", "item_ids": [t]}), + json!({"op": "restyle_items", "item_ids": [t], "color": "#000000"}), + json!({"op": "draw_stroke", "points": [[1, 1], [2, 2]]}), + json!({"op": "add_stamp", "stamp": "star"}), + json!({"op": "create_stamp", "name": "S", "art": "emoji", "emoji": "⭐"}), + ] { + assert!( + matches!(b.run(op.clone()), Err(LiveError::ReadOnly)), + "{op}" + ); + } + assert!(b.run(json!({"op": "list_pages"})).is_ok()); + assert!(b.run(json!({"op": "list_stamps"})).is_ok()); + b.read_only = false; + for op in [ + json!({"op": "set_mode", "mode": "teach"}), + json!({"op": "fit_page"}), + json!({"op": "export_pdf"}), + json!({"op": "library_list"}), + json!({"op": "get_settings"}), + json!({"op": "set_dock_layout", "layout": {}}), + json!({"op": "celebrate"}), + ] { + let o: Op = serde_json::from_value(op.clone()).unwrap(); + assert!(o.board_only(), "{op}"); + assert!( + matches!(b.run(op.clone()), Err(LiveError::Unsupported(_))), + "{op}" + ); + } + let access = |v: Value| serde_json::from_value::(v).unwrap().access(); + assert_eq!( + access(json!({"op": "set_setting", "key": "theme", "value": "dark"})), + Access::Write + ); + assert_eq!( + access(json!({"op": "set_mode", "mode": "teach"})), + Access::Control + ); + assert_eq!(access(json!({"op": "get_dock_layout"})), Access::Read); + assert_eq!(access(json!({"op": "undo"})), Access::Write); +} diff --git a/crates/rupok-live/src/apply.rs b/crates/rupok-live/src/apply.rs index 079e177..660f29f 100644 --- a/crates/rupok-live/src/apply.rs +++ b/crates/rupok-live/src/apply.rs @@ -53,6 +53,8 @@ pub struct Outcome { pub changed: bool, /// Show this page (0-based) afterwards. pub show_page: Option, + /// Select these items on the board afterwards (on the shown page). + pub select: Option>, } impl Outcome { @@ -61,6 +63,7 @@ impl Outcome { result, changed: false, show_page: None, + select: None, } } pub(crate) fn changed(result: Value) -> Self { @@ -68,6 +71,7 @@ impl Outcome { result, changed: true, show_page: None, + select: None, } } } @@ -124,7 +128,13 @@ pub fn apply_with( if ctx.read_only && op.access() == Access::Write { return Err(LiveError::ReadOnly); } - let msg = crate::commit_message(agent, op.name()); + // An empty agent is the teacher using the same code path (e.g. placing + // a custom stamp from the board's palette): the change is not tagged. + let msg = if agent.is_empty() { + String::new() + } else { + crate::commit_message(agent, op.name()) + }; let out = if let Op::WriteHandwriting { .. } = op { crate::handwriting::run(&mut ctx, op, &msg, now_ms, glyphs) } else { @@ -140,6 +150,9 @@ pub fn apply_with( /// Tag the next commit with the agent's message. Call right before the one /// mutation that commits. pub(crate) fn tag(lesson: &Lesson, msg: &str) { + if msg.is_empty() { + return; + } lesson.loro().set_next_commit_message(msg); } @@ -204,6 +217,27 @@ 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")), + Op::ListPages + | Op::MovePages { .. } + | Op::DeletePages { .. } + | Op::DuplicatePages { .. } + | Op::SetPageTitle { .. } + | Op::SelectItems { .. } + | Op::MoveItems { .. } + | Op::AlignItems { .. } + | Op::RestyleItems { .. } + | Op::ScaleItems { .. } + | Op::GroupItems { .. } + | Op::UngroupItems { .. } + | Op::ReorderItems { .. } + | Op::DeleteItems { .. } + | Op::DrawStroke { .. } + | Op::UpdateText { .. } => crate::items::run(ctx, op, msg, now), + Op::ListStamps + | Op::CreateStamp(_) + | Op::UpdateStamp { .. } + | Op::DeleteStamp { .. } + | Op::AddStamp { .. } => crate::stamps::run(ctx, op, msg, now), Op::GoToPage { page } => { let (idx, info) = page_ref(ctx.lesson, ctx.page_id, Some(*page))?; @@ -215,6 +249,7 @@ fn run(ctx: &mut BoardCtx<'_>, op: &Op, msg: &str, now: f64) -> Result }), changed: false, show_page: Some(idx), + select: None, }) } Op::SetBoardTheme { @@ -290,6 +325,7 @@ fn run(ctx: &mut BoardCtx<'_>, op: &Op, msg: &str, now: f64) -> Result }), changed: true, show_page: show.then_some(idx0), + select: None, }) } Op::AddText { @@ -798,6 +834,8 @@ fn run(ctx: &mut BoardCtx<'_>, op: &Op, msg: &str, now: f64) -> Result ctx.lesson.set_object_step(&info.id, &item.id, target)?; Ok(Outcome::changed(out)) } + // Board-app ops (UI state, library, settings): not on the document. + op => Err(LiveError::Unsupported(op.name())), } } @@ -910,7 +948,7 @@ fn r1(v: f64) -> f64 { (v * 10.0).round() / 10.0 } -fn geometry_of(g: &BoxGeom) -> Geometry { +pub(crate) fn geometry_of(g: &BoxGeom) -> Geometry { Geometry { x: r1(g.x), y: r1(g.y), @@ -1098,7 +1136,7 @@ pub(crate) fn union_bounds<'a>(items: impl Iterator) -> Option< // ---------------------------------------------------------------- helpers -fn warning(code: &'static str, message: String) -> Diagnostic { +pub(crate) fn warning(code: &'static str, message: String) -> Diagnostic { Diagnostic { severity: Severity::Warning, code, @@ -1106,11 +1144,11 @@ fn warning(code: &'static str, message: String) -> Diagnostic { } } -fn has_errors(d: &[Diagnostic]) -> bool { +pub(crate) fn has_errors(d: &[Diagnostic]) -> bool { d.iter().any(|d| d.severity == Severity::Error) } -fn check_text(text: &str) -> Result<()> { +pub(crate) fn check_text(text: &str) -> Result<()> { if text.trim().is_empty() { return Err(LiveError::Invalid("text must not be empty".into())); } @@ -1194,7 +1232,7 @@ pub fn is_dark(rgba: u32) -> bool { 0.2126 * ch(24) + 0.7152 * ch(16) + 0.0722 * ch(8) < 0.25 } -fn scheme(rgba: u32) -> &'static str { +pub(crate) fn scheme(rgba: u32) -> &'static str { if is_dark(rgba) { "dark" } else { "light" } } @@ -1227,7 +1265,7 @@ fn text_box(text: &str, size: f64, w: Option, x: f64, frame: Frame) -> (f64 (w, rows * size * 1.3) } -fn placement_warning(g: &BoxGeom, frame: Option) -> Option { +pub(crate) fn placement_warning(g: &BoxGeom, frame: Option) -> Option { let f = frame?; let tol = 0.5; let outside = g.x < -tol || g.y < -tol || g.x + g.w > f.w + tol || g.y + g.h > f.h + tol; @@ -1294,7 +1332,7 @@ fn updated_bundle( b } -fn slug(title: &str) -> String { +pub(crate) fn slug(title: &str) -> String { let mut s = String::new(); for c in title.chars() { if s.len() >= 32 { @@ -1314,7 +1352,7 @@ fn slug(title: &str) -> String { } } -fn fnv1a(bytes: &[u8], seed: u64) -> u64 { +pub(crate) fn fnv1a(bytes: &[u8], seed: u64) -> u64 { let mut h = 0xcbf2_9ce4_8422_2325u64 ^ seed; for b in bytes { h ^= u64::from(*b); diff --git a/crates/rupok-live/src/design.rs b/crates/rupok-live/src/design.rs index c8ae9c0..d30d20b 100644 --- a/crates/rupok-live/src/design.rs +++ b/crates/rupok-live/src/design.rs @@ -478,6 +478,7 @@ pub(crate) fn run_page_design(ctx: &mut BoardCtx<'_>, op: &Op, msg: &str) -> Res result: out, changed: true, show_page: Some(idx), + select: None, }) } @@ -578,6 +579,7 @@ pub(crate) fn run_branding(ctx: &mut BoardCtx<'_>, op: &Op, msg: &str) -> Result }), changed: true, show_page: Some(idx), + select: None, } }; if *remove { diff --git a/crates/rupok-live/src/items.rs b/crates/rupok-live/src/items.rs new file mode 100644 index 0000000..451d9cd --- /dev/null +++ b/crates/rupok-live/src/items.rs @@ -0,0 +1,1005 @@ +//! Agent operations on pages and items: list, move, delete and copy pages; +//! select, move, align, restyle, scale, group, reorder and delete items; draw +//! ink and edit text. +//! +//! Each write is **one** Loro commit tagged with the agent (one undo step), +//! on a lesson file exactly as on the live board. Ink points are only +//! rewritten by `scale_items` (a scale is a new shape); a move changes the +//! stroke offset, as when the teacher drags it. + +use std::collections::BTreeMap; + +use rupok_core::{BoxGeom, Edits, Frame, Item, ItemData, NewItem, StrokeData}; +use rupok_ink::{Brush, StrokePoint}; +use serde_json::{Value, json}; + +use crate::apply::{ + BoardCtx, LiveError, Outcome, color_hex, finite, geometry_of, page_index, page_ref, + parse_color, positive, tag, union_bounds, +}; +use crate::op::{Op, StrokeArg}; + +type Result = std::result::Result; + +/// Most items one op may touch. +const MAX_ITEMS: usize = 5_000; +/// Most points in all the strokes of one `draw_stroke`. +const MAX_POINTS: usize = 50_000; +const MAX_STROKES: usize = 500; +const MIN_WIDTH: f64 = 0.5; +const MAX_WIDTH: f64 = 200.0; + +pub(crate) fn run(ctx: &mut BoardCtx<'_>, op: &Op, msg: &str, now: f64) -> Result { + match op { + Op::ListPages => list_pages(ctx), + Op::MovePages { pages, to } => move_pages(ctx, pages, *to, msg), + Op::DeletePages { pages } => delete_pages(ctx, pages, msg), + Op::DuplicatePages { pages } => duplicate_pages(ctx, pages, msg), + Op::SetPageTitle { page, title } => { + if title.chars().count() > 200 { + return Err(LiveError::Invalid( + "title is longer than 200 characters".into(), + )); + } + let (idx, info) = page_ref(ctx.lesson, ctx.page_id, *page)?; + tag(ctx.lesson, msg); + ctx.lesson.set_page_title(&info.id, title.trim())?; + Ok(Outcome::changed( + json!({ "page": idx + 1, "title": title.trim() }), + )) + } + Op::SelectItems { page, item_ids } => { + let (idx, _, chosen) = resolve_allow_empty(ctx, *page, item_ids)?; + let ids: Vec = chosen.iter().map(|i| i.id.clone()).collect(); + let current = page_index(ctx.lesson, ctx.page_id).unwrap_or(0); + Ok(Outcome { + result: json!({ + "page": idx + 1, + "selected": ids.len(), + "bounds": union_bounds(chosen.iter()).map(|b| geometry_of(&b)), + }), + changed: false, + show_page: (idx != current).then_some(idx), + select: Some(ids), + }) + } + Op::MoveItems { + page, + item_ids, + dx, + dy, + x, + y, + } => { + let (idx, info, chosen) = resolve(ctx, *page, item_ids)?; + let b = union_bounds(chosen.iter()).unwrap_or_default(); + let mut ddx = dx.map(|v| finite("dx", v)).transpose()?.unwrap_or(0.0); + let mut ddy = dy.map(|v| finite("dy", v)).transpose()?.unwrap_or(0.0); + if let Some(x) = x { + ddx = finite("x", *x)? - b.x; + } + if let Some(y) = y { + ddy = finite("y", *y)? - b.y; + } + if dx.is_none() && dy.is_none() && x.is_none() && y.is_none() { + return Err(LiveError::Invalid( + "give dx/dy (move by) or x/y (move the items' top-left to)".into(), + )); + } + let e = Edits { + translate: chosen.iter().map(|i| (i.id.clone(), ddx, ddy)).collect(), + ..Default::default() + }; + commit(ctx, &info.id, &e, msg)?; + let moved = BoxGeom { + x: b.x + ddx, + y: b.y + ddy, + ..b + }; + Ok(Outcome::changed(json!({ + "page": idx + 1, + "moved": chosen.len(), + "bounds": geometry_of(&moved), + }))) + } + Op::AlignItems { + page, + item_ids, + align, + distribute, + relative_to, + } => align_items( + ctx, + *page, + item_ids, + align.as_deref(), + distribute.as_deref(), + relative_to.as_deref(), + msg, + ), + Op::RestyleItems { .. } => restyle(ctx, op, msg), + Op::ScaleItems { + page, + item_ids, + factor, + } => scale(ctx, *page, item_ids, *factor, msg), + Op::GroupItems { page, item_ids } => { + let (idx, info, chosen) = resolve(ctx, *page, item_ids)?; + if chosen.len() < 2 { + return Err(LiveError::Invalid("group at least two items".into())); + } + let ids: Vec = chosen.iter().map(|i| i.id.clone()).collect(); + tag(ctx.lesson, msg); + let group = ctx.lesson.group_items(&info.id, &ids)?; + Ok(Outcome::changed( + json!({ "page": idx + 1, "group": group, "items": ids.len() }), + )) + } + Op::UngroupItems { page, item_ids } => { + let (idx, info, chosen) = resolve(ctx, *page, item_ids)?; + let groups: Vec<&String> = chosen.iter().filter_map(|i| i.group.as_ref()).collect(); + if groups.is_empty() { + return Err(LiveError::Invalid( + "none of these items is in a group".into(), + )); + } + let all = ctx.lesson.items(&info.id)?; + let members: Vec = all + .iter() + .filter(|i| i.group.as_ref().is_some_and(|g| groups.contains(&g))) + .map(|i| i.id.clone()) + .collect(); + tag(ctx.lesson, msg); + ctx.lesson.set_group(&info.id, &members, None)?; + Ok(Outcome::changed( + json!({ "page": idx + 1, "ungrouped": members.len() }), + )) + } + Op::ReorderItems { page, item_ids, to } => { + let (idx, info, chosen) = resolve(ctx, *page, item_ids)?; + let back = match to.as_deref().unwrap_or("front") { + "front" => false, + "back" => true, + other => { + return Err(LiveError::Invalid(format!( + "to must be front or back, got `{other}`" + ))); + } + }; + let chosen_ids: Vec = chosen.iter().map(|i| i.id.clone()).collect(); + // Sending to the back raises everything else, in order: the same + // stacking, without a "lowest z" in the format. + let raise: Vec = if back { + ctx.lesson + .items(&info.id)? + .into_iter() + .filter(|i| !chosen_ids.contains(&i.id)) + .map(|i| i.id) + .collect() + } else { + chosen_ids.clone() + }; + if !raise.is_empty() { + tag(ctx.lesson, msg); + ctx.lesson.bring_items_to_front(&info.id, &raise)?; + } + Ok(Outcome::changed(json!({ + "page": idx + 1, + "items": chosen_ids.len(), + "to": if back { "back" } else { "front" }, + }))) + } + Op::DeleteItems { page, item_ids } => { + let (idx, info, chosen) = resolve(ctx, *page, item_ids)?; + let ids: Vec = chosen.iter().map(|i| i.id.clone()).collect(); + tag(ctx.lesson, msg); + let n = ctx.lesson.remove_items(&info.id, &ids)?; + Ok(Outcome::changed(json!({ "page": idx + 1, "deleted": n }))) + } + Op::DrawStroke { .. } => draw(ctx, op, msg, now), + Op::UpdateText { + page, + item_id, + text, + size, + color, + x, + y, + w, + } => { + let (idx, info, chosen) = resolve(ctx, *page, std::slice::from_ref(item_id))?; + let item = &chosen[0]; + let ItemData::Text(t) = &item.data else { + return Err(LiveError::Invalid(format!( + "item `{item_id}` is a {}, not a text box", + item.data.kind() + ))); + }; + let mut e = Edits::default(); + if let Some(s) = text { + crate::apply::check_text(s)?; + if *s != t.text { + e.texts.push((item.id.clone(), s.clone())); + } + } + if let Some(c) = color { + let c = parse_color(c)?; + if c != t.color { + e.text_colors.push((item.id.clone(), c)); + } + } + let mut g = t.geom; + let mut new_size = None; + if let Some(s) = size { + let s = positive("size", *s)?.clamp(4.0, 2000.0); + let k = s / t.size.max(1.0); + g.w = (g.w * k).max(1.0); + g.h = (g.h * k).max(1.0); + new_size = Some(s); + } + if let Some(v) = x { + g.x = finite("x", *v)?; + } + if let Some(v) = y { + g.y = finite("y", *v)?; + } + if let Some(v) = w { + g.w = positive("w", *v)?; + } + if g != t.geom || new_size.is_some() { + e.boxes.push((item.id.clone(), g, new_size)); + } + if e.is_empty() { + return Err(LiveError::Invalid( + "nothing to change: give text, size, color, x, y or w".into(), + )); + } + commit(ctx, &info.id, &e, msg)?; + Ok(Outcome::changed(json!({ + "page": idx + 1, + "item_id": item.id, + "geometry": geometry_of(&g), + }))) + } + _ => Err(LiveError::Unsupported(op.name())), + } +} + +// ------------------------------------------------------------------ pages + +fn list_pages(ctx: &BoardCtx<'_>) -> Result { + let current = page_index(ctx.lesson, ctx.page_id).unwrap_or(0); + let mut pages = Vec::new(); + for (i, p) in ctx.lesson.pages().iter().enumerate() { + let items = ctx.lesson.items(&p.id)?; + let count = |k: &str| items.iter().filter(|it| it.data.kind() == k).count(); + let title = if p.title.is_empty() { + items.iter().find_map(|it| match &it.data { + ItemData::Text(t) if t.stamp.is_none() => Some( + t.text + .lines() + .next() + .unwrap_or("") + .chars() + .take(60) + .collect::(), + ), + _ => None, + }) + } else { + None + }; + pages.push(json!({ + "page": i + 1, + "id": p.id, + "title": p.title, + "first_text": title, + "background": color_hex(p.bg_color), + "pattern": p.pattern.as_str(), + "items": items.len(), + "strokes": count("stroke"), + "texts": count("text"), + "objects": count("object"), + "images": count("image"), + })); + } + Ok(Outcome::read(json!({ + "title": ctx.lesson.title(), + "page_count": pages.len(), + "current_page": current + 1, + "pages": pages, + }))) +} + +/// 1-based page numbers → page ids (deduplicated, in page order). +fn page_ids(ctx: &BoardCtx<'_>, pages: &[u32]) -> Result> { + if pages.is_empty() { + return Err(LiveError::Invalid( + "pages must list at least one page number (1-based)".into(), + )); + } + let all = ctx.lesson.pages(); + let mut out: Vec<(usize, String)> = Vec::new(); + for &n in pages { + let i = n as usize; + if i == 0 || i > all.len() { + return Err(LiveError::Invalid(format!( + "page {n} does not exist; the lesson has {} page(s), numbered from 1", + all.len() + ))); + } + if !out.iter().any(|(j, _)| *j == i - 1) { + out.push((i - 1, all[i - 1].id.clone())); + } + } + out.sort_by_key(|(i, _)| *i); + Ok(out) +} + +fn move_pages(ctx: &mut BoardCtx<'_>, pages: &[u32], to: u32, msg: &str) -> Result { + let ids = page_ids(ctx, pages)?; + let n = ctx.lesson.page_count(); + let k = ids.len(); + if to == 0 || to as usize > n - k + 1 { + return Err(LiveError::Invalid(format!( + "to must be between 1 and {} (where the first moved page ends up)", + n - k + 1 + ))); + } + // `to` counts positions after the move; `move_pages` takes the gap + // before page `gap` among the pages as they are now. + let start = to as usize - 1; + let others: Vec = (0..n) + .filter(|i| !ids.iter().any(|(j, _)| j == i)) + .collect(); + let gap = others.get(start).copied().unwrap_or(n); + let list: Vec = ids.iter().map(|(_, id)| id.clone()).collect(); + tag(ctx.lesson, msg); + ctx.lesson.move_pages(&list, gap)?; + let now: Vec = list + .iter() + .filter_map(|id| page_index(ctx.lesson, id)) + .map(|i| i + 1) + .collect(); + Ok(Outcome::changed(json!({ + "moved": k, + "pages_now": now, + "current_page": page_index(ctx.lesson, ctx.page_id).map(|i| i + 1), + }))) +} + +fn delete_pages(ctx: &mut BoardCtx<'_>, pages: &[u32], msg: &str) -> Result { + let ids = page_ids(ctx, pages)?; + if ids.len() >= ctx.lesson.page_count() { + return Err(LiveError::Invalid( + "a lesson keeps at least one page; leave one page out".into(), + )); + } + let list: Vec = ids.iter().map(|(_, id)| id.clone()).collect(); + let showing_deleted = list.iter().any(|id| id == ctx.page_id); + let first = ids[0].0; + tag(ctx.lesson, msg); + let n = ctx.lesson.remove_pages(&list)?; + let count = ctx.lesson.page_count(); + Ok(Outcome { + result: json!({ "deleted": n, "page_count": count }), + changed: true, + show_page: showing_deleted.then_some(first.min(count - 1)), + select: None, + }) +} + +fn duplicate_pages(ctx: &mut BoardCtx<'_>, pages: &[u32], msg: &str) -> Result { + let ids = page_ids(ctx, pages)?; + let list: Vec = ids.iter().map(|(_, id)| id.clone()).collect(); + tag(ctx.lesson, msg); + let copies = ctx.lesson.duplicate_pages(&list)?; + let numbers: Vec = copies + .iter() + .filter_map(|id| page_index(ctx.lesson, id)) + .map(|i| i + 1) + .collect(); + Ok(Outcome::changed(json!({ + "copies": numbers, + "page_count": ctx.lesson.page_count(), + }))) +} + +// ------------------------------------------------------------------ items + +/// The page and the listed items on it; every id must be there. +fn resolve( + ctx: &BoardCtx<'_>, + page: Option, + ids: &[String], +) -> Result<(usize, rupok_core::PageInfo, Vec)> { + if ids.is_empty() { + return Err(LiveError::Invalid( + "item_ids must list items (ids from get_current_page or get_selection)".into(), + )); + } + resolve_allow_empty(ctx, page, ids) +} + +fn resolve_allow_empty( + ctx: &BoardCtx<'_>, + page: Option, + ids: &[String], +) -> Result<(usize, rupok_core::PageInfo, Vec)> { + if ids.len() > MAX_ITEMS { + return Err(LiveError::Invalid(format!( + "at most {MAX_ITEMS} items per call" + ))); + } + let (idx, info) = page_ref(ctx.lesson, ctx.page_id, page)?; + let items = ctx.lesson.items(&info.id)?; + let missing: Vec<&str> = ids + .iter() + .filter(|id| !items.iter().any(|i| &i.id == *id)) + .map(String::as_str) + .collect(); + if !missing.is_empty() { + return Err(LiveError::NotFound(format!( + "not on page {}: {}; call get_current_page for item ids", + idx + 1, + missing.join(", ") + ))); + } + let chosen = items.into_iter().filter(|i| ids.contains(&i.id)).collect(); + Ok((idx, info, chosen)) +} + +fn commit(ctx: &mut BoardCtx<'_>, page_id: &str, e: &Edits, msg: &str) -> Result> { + if e.is_empty() { + return Ok(Vec::new()); + } + tag(ctx.lesson, msg); + Ok(ctx.lesson.apply_edits(page_id, e)?) +} + +fn aabb(i: &Item) -> [f64; 4] { + let a = i.data.aabb(); + [ + f64::from(a[0]), + f64::from(a[1]), + f64::from(a[2]), + f64::from(a[3]), + ] +} + +fn align_items( + ctx: &mut BoardCtx<'_>, + page: Option, + ids: &[String], + align: Option<&str>, + distribute: Option<&str>, + relative_to: Option<&str>, + msg: &str, +) -> Result { + let (idx, info, chosen) = resolve(ctx, page, ids)?; + if align.is_none() && distribute.is_none() { + return Err(LiveError::Invalid( + "give align (left, center, right, top, middle, bottom) and/or distribute (horizontal, vertical)".into(), + )); + } + // Units: a group moves as one (handwritten words stay words). + let mut units: BTreeMap, [f64; 4])> = BTreeMap::new(); + for it in &chosen { + let key = it.group.clone().unwrap_or_else(|| format!("#{}", it.id)); + let b = aabb(it); + let e = units.entry(key).or_insert((Vec::new(), b)); + e.0.push(it.id.clone()); + e.1 = [ + e.1[0].min(b[0]), + e.1[1].min(b[1]), + e.1[2].max(b[2]), + e.1[3].max(b[3]), + ]; + } + let mut units: Vec<(Vec, [f64; 4], [f64; 2])> = units + .into_values() + .map(|(i, b)| (i, b, [0.0, 0.0])) + .collect(); + let frame = info.frame.unwrap_or(Frame::SLIDE_16_9); + let target = match relative_to.unwrap_or("items") { + "items" => { + let mut t = units[0].1; + for u in &units { + t = [ + t[0].min(u.1[0]), + t[1].min(u.1[1]), + t[2].max(u.1[2]), + t[3].max(u.1[3]), + ]; + } + t + } + "page" => [0.0, 0.0, frame.w, frame.h], + other => { + return Err(LiveError::Invalid(format!( + "relative_to must be items or page, got `{other}`" + ))); + } + }; + if relative_to.unwrap_or("items") == "items" && units.len() < 2 && distribute.is_none() { + return Err(LiveError::Invalid( + "aligning needs two or more items (or groups); use relative_to: \"page\" to align one item on the slide".into(), + )); + } + if let Some(a) = align { + for u in &mut units { + let b = u.1; + match a { + "left" => u.2[0] = target[0] - b[0], + "right" => u.2[0] = target[2] - b[2], + "center" => u.2[0] = (target[0] + target[2]) / 2.0 - (b[0] + b[2]) / 2.0, + "top" => u.2[1] = target[1] - b[1], + "bottom" => u.2[1] = target[3] - b[3], + "middle" => u.2[1] = (target[1] + target[3]) / 2.0 - (b[1] + b[3]) / 2.0, + other => { + return Err(LiveError::Invalid(format!( + "align must be left, center, right, top, middle or bottom, got `{other}`" + ))); + } + } + } + } + if let Some(d) = distribute { + let axis = match d { + "horizontal" => 0, + "vertical" => 1, + other => { + return Err(LiveError::Invalid(format!( + "distribute must be horizontal or vertical, got `{other}`" + ))); + } + }; + if units.len() < 3 { + return Err(LiveError::Invalid( + "distributing needs three or more items (or groups)".into(), + )); + } + let lo = |u: &(Vec, [f64; 4], [f64; 2])| u.1[axis] + u.2[axis]; + let size = |u: &(Vec, [f64; 4], [f64; 2])| u.1[axis + 2] - u.1[axis]; + units.sort_by(|a, b| lo(a).total_cmp(&lo(b))); + let start = lo(&units[0]); + let last = units.len() - 1; + let end = lo(&units[last]) + size(&units[last]); + let total: f64 = units.iter().map(size).sum(); + let gap = (end - start - total) / last as f64; + let mut at = start; + for u in &mut units { + let cur = u.1[axis] + u.2[axis]; + u.2[axis] += at - cur; + at += size(u) + gap; + } + } + let mut e = Edits::default(); + for (ids, _, d) in &units { + if d[0].abs() > 1e-6 || d[1].abs() > 1e-6 { + for id in ids { + e.translate.push((id.clone(), d[0], d[1])); + } + } + } + let moved = e.translate.len(); + commit(ctx, &info.id, &e, msg)?; + Ok(Outcome::changed(json!({ + "page": idx + 1, + "moved": moved, + "units": units.len(), + }))) +} + +/// A brush name an agent may store (`pen` clears it; `magic` is not saved). +pub(crate) fn brush_key(name: &str) -> Result> { + let b = Brush::parse(name); + if b == Brush::Magic || (b == Brush::Pen && name != "pen") { + return Err(LiveError::Invalid(format!( + "brush must be one of pen, ballpoint, fountain, marker, pencil, chalk, brush, dashed, dotted, neon, rainbow; got `{name}`" + ))); + } + Ok(b.key().map(str::to_string)) +} + +fn restyle(ctx: &mut BoardCtx<'_>, op: &Op, msg: &str) -> Result { + let Op::RestyleItems { + page, + item_ids, + color, + width, + brush, + fill, + opacity, + dashed, + text_size, + } = op + else { + return Err(LiveError::Unsupported(op.name())); + }; + let (idx, info, chosen) = resolve(ctx, *page, item_ids)?; + let color = color.as_deref().map(parse_color).transpose()?; + let width = width + .map(|w| positive("width", w).map(|w| w.clamp(MIN_WIDTH, MAX_WIDTH) as f32)) + .transpose()?; + let brush = brush.as_deref().map(brush_key).transpose()?; + let fill = match fill.as_deref() { + None => None, + Some("none") | Some("") => Some(None), + Some(c) => Some(Some(parse_color(c)?)), + }; + let opacity = match opacity { + Some(o) if o.is_finite() && (0.05..=1.0).contains(o) => Some(*o as f32), + Some(_) => { + return Err(LiveError::Invalid( + "opacity must be between 0.05 and 1".into(), + )); + } + None => None, + }; + let text_size = text_size + .map(|s| positive("text_size", s).map(|s| s.clamp(4.0, 2000.0))) + .transpose()?; + if color.is_none() + && width.is_none() + && brush.is_none() + && fill.is_none() + && opacity.is_none() + && dashed.is_none() + && text_size.is_none() + { + return Err(LiveError::Invalid( + "nothing to change: give color, width, brush, fill, opacity, dashed or text_size" + .into(), + )); + } + let mut e = Edits::default(); + let mut skipped: Vec = Vec::new(); + for it in &chosen { + match &it.data { + ItemData::Stroke(s) => { + let mut n = s.clone(); + if let Some(c) = color { + // Highlighter ink keeps its own translucency (opacity). + n.color = if s.tool == "highlighter" { + (c & 0xffff_ff00) | 0xff + } else { + c + }; + } + if let Some(w) = width { + n.width = w; + } + if let Some(b) = &brush { + n.brush = b.clone(); + } + if let Some(o) = opacity { + n.opacity = o; + } + if (fill.is_some() || dashed.is_some()) + && let Some(g) = n.geom.as_mut() + { + if let Some(f) = fill { + g.fill = f; + } + if let Some(d) = dashed { + g.dash = *d; + } + } + if n != *s { + e.strokes.push((it.id.clone(), n)); + } + } + ItemData::Text(t) => { + let mut touched = false; + if let Some(c) = color + && c != t.color + { + e.text_colors.push((it.id.clone(), c)); + touched = true; + } + if let Some(sz) = text_size + && t.stamp.is_none() + && (sz - t.size).abs() > 1e-6 + { + let k = sz / t.size.max(1.0); + let g = BoxGeom { + w: (t.geom.w * k).max(1.0), + h: (t.geom.h * k).max(1.0), + ..t.geom + }; + e.boxes.push((it.id.clone(), g, Some(sz))); + touched = true; + } + if !touched { + skipped.push(json!({ "item_id": it.id, "kind": "text" })); + } + } + other => skipped.push(json!({ "item_id": it.id, "kind": other.kind() })), + } + } + if e.is_empty() { + return Err(LiveError::Invalid(format!( + "nothing changed: the items already look like that, or are images or Smart Objects, which have no ink style ({} skipped)", + skipped.len() + ))); + } + let mut touched: Vec<&String> = e + .strokes + .iter() + .map(|(id, _)| id) + .chain(e.text_colors.iter().map(|(id, _)| id)) + .chain(e.boxes.iter().map(|(id, _, _)| id)) + .collect(); + touched.sort(); + touched.dedup(); + let restyled = touched.len(); + commit(ctx, &info.id, &e, msg)?; + Ok(Outcome::changed(json!({ + "page": idx + 1, + "restyled": restyled, + "skipped": skipped, + }))) +} + +/// Scale about the centre of the items' bounds. A uniform scale maps a +/// stroke exactly: points, width and shape geometry scale together, so a +/// rectangle stays a rectangle and an arrow keeps its head. +fn scale( + ctx: &mut BoardCtx<'_>, + page: Option, + ids: &[String], + factor: f64, + msg: &str, +) -> Result { + if !(factor.is_finite() && (0.05..=20.0).contains(&factor)) { + return Err(LiveError::Invalid( + "factor must be between 0.05 and 20 (1.5 = half as big again)".into(), + )); + } + let (idx, info, chosen) = resolve(ctx, page, ids)?; + let b = union_bounds(chosen.iter()).unwrap_or_default(); + let (cx, cy) = (b.x + b.w / 2.0, b.y + b.h / 2.0); + let k = factor; + let map = |x: f64, y: f64| (cx + (x - cx) * k, cy + (y - cy) * k); + let mut e = Edits::default(); + for it in &chosen { + match &it.data { + ItemData::Stroke(s) => { + let (ox, oy) = (f64::from(s.offset[0]), f64::from(s.offset[1])); + let points = s + .points + .iter() + .map(|p| { + let (x, y) = map(f64::from(p.x) + ox, f64::from(p.y) + oy); + StrokePoint { + x: x as f32, + y: y as f32, + ..*p + } + }) + .collect(); + let geom = s.geom.as_ref().map(|g| { + let (x, y) = map(g.x + ox, g.y + oy); + rupok_core::ShapeGeom { + x, + y, + w: g.w * k, + h: g.h * k, + ..g.clone() + } + }); + e.strokes.push(( + it.id.clone(), + StrokeData { + points, + width: (f64::from(s.width) * k).clamp(MIN_WIDTH, MAX_WIDTH) as f32, + offset: [0.0, 0.0], + geom, + ..s.clone() + }, + )); + } + ItemData::Text(t) => { + let (x, y) = map(t.geom.x, t.geom.y); + let g = BoxGeom { + x, + y, + w: (t.geom.w * k).max(1.0), + h: (t.geom.h * k).max(1.0), + rot: t.geom.rot, + }; + e.boxes + .push((it.id.clone(), g, Some((t.size * k).clamp(4.0, 2000.0)))); + } + ItemData::Image(i) => e.boxes.push((it.id.clone(), scaled(&i.geom, map, k), None)), + ItemData::Object(o) => e.boxes.push((it.id.clone(), scaled(&o.geom, map, k), None)), + } + } + commit(ctx, &info.id, &e, msg)?; + let nb = BoxGeom { + x: cx - b.w * k / 2.0, + y: cy - b.h * k / 2.0, + w: b.w * k, + h: b.h * k, + rot: 0.0, + }; + let mut warnings = Vec::new(); + warnings.extend(crate::apply::placement_warning(&nb, info.frame)); + Ok(Outcome::changed(json!({ + "page": idx + 1, + "scaled": chosen.len(), + "bounds": geometry_of(&nb), + "warnings": warnings, + }))) +} + +fn scaled(g: &BoxGeom, map: impl Fn(f64, f64) -> (f64, f64), k: f64) -> BoxGeom { + let (x, y) = map(g.x, g.y); + BoxGeom { + x, + y, + w: (g.w * k).max(1.0), + h: (g.h * k).max(1.0), + rot: g.rot, + } +} + +fn draw(ctx: &mut BoardCtx<'_>, op: &Op, msg: &str, now: f64) -> Result { + let Op::DrawStroke { + page, + points, + strokes, + color, + width, + brush, + opacity, + tool, + } = op + else { + return Err(LiveError::Unsupported(op.name())); + }; + let mut list: Vec = strokes.clone().unwrap_or_default(); + if let Some(p) = points { + list.insert( + 0, + StrokeArg { + points: p.clone(), + ..Default::default() + }, + ); + } + if list.is_empty() { + return Err(LiveError::Invalid( + "give points ([[x, y], …] in slide pixels) or strokes".into(), + )); + } + if list.len() > MAX_STROKES { + return Err(LiveError::Invalid(format!( + "at most {MAX_STROKES} strokes per call" + ))); + } + let total: usize = list.iter().map(|s| s.points.len()).sum(); + if total > MAX_POINTS { + return Err(LiveError::Invalid(format!( + "at most {MAX_POINTS} points per call" + ))); + } + let highlighter = match tool.as_deref().unwrap_or("pen") { + "pen" => false, + "highlighter" => true, + other => { + return Err(LiveError::Invalid(format!( + "tool must be pen or highlighter, got `{other}`" + ))); + } + }; + let (idx, info) = page_ref(ctx.lesson, ctx.page_id, *page)?; + let def_color = match color { + Some(c) => parse_color(c)?, + None if highlighter => 0xffe629ff, + None => crate::apply::default_ink(info.bg_color), + }; + let def_width = width + .map(|w| positive("width", w)) + .transpose()? + .unwrap_or(if highlighter { 22.0 } else { 4.0 }); + let def_brush = brush.as_deref().map(brush_key).transpose()?.flatten(); + let opacity = match opacity { + Some(o) if o.is_finite() && (0.05..=1.0).contains(o) => *o as f32, + Some(_) => { + return Err(LiveError::Invalid( + "opacity must be between 0.05 and 1".into(), + )); + } + None if highlighter => 0.38, + None => 1.0, + }; + let mut add = Vec::with_capacity(list.len()); + for (si, s) in list.iter().enumerate() { + if s.points.is_empty() { + return Err(LiveError::Invalid(format!( + "stroke {} has no points", + si + 1 + ))); + } + let c = match &s.color { + Some(c) => parse_color(c)?, + None => def_color, + }; + let w = match s.width { + Some(w) => positive("width", w)?, + None => def_width, + } + .clamp(MIN_WIDTH, MAX_WIDTH) as f32; + let b = match &s.brush { + Some(b) => brush_key(b)?, + None => def_brush.clone(), + }; + let mut pts = Vec::with_capacity(s.points.len()); + let mut last: Option<(f64, f64)> = None; + let mut t = 0u32; + for (pi, p) in s.points.iter().enumerate() { + if p.len() < 2 || p.len() > 3 { + return Err(LiveError::Invalid(format!( + "stroke {} point {}: give [x, y] or [x, y, pressure]", + si + 1, + pi + 1 + ))); + } + let x = finite("x", p[0])?; + let y = finite("y", p[1])?; + let pr = p.get(2).copied().unwrap_or(0.5); + if !(pr.is_finite() && (0.0..=1.0).contains(&pr)) { + return Err(LiveError::Invalid(format!( + "stroke {} point {}: pressure must be between 0 and 1", + si + 1, + pi + 1 + ))); + } + // A steady hand: 1 ms per 1.5 px, so replay draws it naturally. + if let Some((lx, ly)) = last { + t += (((x - lx).hypot(y - ly)) / 1.5).clamp(1.0, 200.0) as u32; + } + last = Some((x, y)); + pts.push(StrokePoint { + x: x as f32, + y: y as f32, + p: pr as f32, + dt: t, + }); + } + add.push(NewItem { + data: ItemData::Stroke(StrokeData { + tool: if highlighter { "highlighter" } else { "pen" }.into(), + color: c, + width: w, + opacity, + points: pts, + offset: [0.0, 0.0], + shape: None, + geom: None, + brush: b, + }), + created: now + si as f64, + group: None, + z: None, + }); + } + let e = Edits { + add, + ..Default::default() + }; + let ids = commit(ctx, &info.id, &e, msg)?; + let added: Vec = ctx + .lesson + .items(&info.id)? + .into_iter() + .filter(|i| ids.contains(&i.id)) + .collect(); + Ok(Outcome::changed(json!({ + "page": idx + 1, + "item_ids": ids, + "bounds": union_bounds(added.iter()).map(|b| geometry_of(&b)), + }))) +} diff --git a/crates/rupok-live/src/lib.rs b/crates/rupok-live/src/lib.rs index f0fa03c..695d910 100644 --- a/crates/rupok-live/src/lib.rs +++ b/crates/rupok-live/src/lib.rs @@ -30,12 +30,20 @@ pub mod apply; pub mod attribution; pub mod design; pub mod handwriting; +pub mod items; pub mod op; pub mod protocol; +pub mod stamps; + +#[cfg(test)] +mod agent_ops_tests; pub use apply::{BoardCtx, LiveError, Outcome, apply, apply_with, doc_key}; pub use attribution::{agent_items, parse_commit_message}; -pub use op::{Anchor, BrandingArgs, Op, PageDesignArgs, PatternName, Rect}; +pub use op::{ + Access, Anchor, BrandingArgs, Op, PageDesignArgs, PatternName, Rect, StampBehavior, StampDef, + StrokeArg, +}; /// Prefix of the Loro commit message of every change an agent makes: /// `rupok-agent/1 {"agent":"Claude Code","op":"add_text"}`. diff --git a/crates/rupok-live/src/op.rs b/crates/rupok-live/src/op.rs index de30925..27d9a8d 100644 --- a/crates/rupok-live/src/op.rs +++ b/crates/rupok-live/src/op.rs @@ -142,6 +142,92 @@ pub struct BrandingArgs { pub remove: bool, } +/// One stroke for [`Op::DrawStroke`]: points in slide pixels, each +/// `[x, y]` or `[x, y, pressure]` (pressure 0..1, default 0.5). +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct StrokeArg { + pub points: Vec>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub color: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub width: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub brush: Option, +} + +/// Declarative behaviour of a custom stamp (no code): what happens when it +/// is placed. Unknown values are refused with a clear error. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct StampBehavior { + /// `none`, `pop` (default), `sparkle`, `bounce`, `spin` or `fade-in`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub animation: Option, + /// A short burst around the stamp: `none`, `stars`, `confetti`, + /// `hearts` or `sparkles`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub burst: Option, + /// Burst colours `#rrggbb` (at most 6). Default: the stamp's colour. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub burst_colors: Vec, + /// Show a number badge counting this stamp's placements on the page. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub counter: bool, + /// A short built-in sound (respects the board's mute): `none`, `chime`, + /// `pop`, `ding`, `tada`, `clap` or `whoosh`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub sound: Option, + /// Fade the stamp away this many seconds after it is placed (1–600). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub fade_after: Option, +} + +/// A custom stamp definition, as given to `create_stamp` / `update_stamp` +/// (every field optional for an update) and as stored (spec: Custom +/// stamps). See [`crate::stamps`]. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct StampDef { + /// `a-z`, `0-9`, `-`, at most 32 bytes; generated from the name when + /// omitted. Built-in stamp ids are reserved. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub name: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub keywords: Vec, + /// `svg`, `emoji`, `text` or `smart` (a tiny Smart Object). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub art: Option, + /// SVG markup (sanitised: no scripts, handlers, external references or + /// animation). `currentColor` takes the stamp's colour. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub svg: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub emoji: Option, + /// A short label drawn as a pill (`text` art). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub text: Option, + /// `#rrggbb`: the pill colour, or the tint of `currentColor` in SVG. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub color: Option, + /// Default height in slide pixels (24–600). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub size: Option, + #[serde(default, alias = "behaviour", skip_serializing_if = "Option::is_none")] + pub behavior: Option, + /// `smart` art: the Smart Object HTML (sandboxed, offline, no network). + /// Not stored in the definition: it becomes a bundle in the lesson. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub html: Option, + /// `smart` art: the bundle in the lesson (set by Rupok). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub bundle: Option, + /// `smart` art: width and height of a placement (40–800, default 200). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub width: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub height: Option, +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(tag = "op", rename_all = "snake_case")] pub enum Op { @@ -440,6 +526,314 @@ pub enum Op { #[serde(default)] delta: Option, }, + + // ------------------------------------------------------------ pages + /// Every page: number, id, title, look and item count (lighter than + /// `get_outline`). + ListPages, + /// Move pages (1-based) together so the first ends at position `to` + /// (1-based, in the order after the move), keeping their order. + MovePages { + pages: Vec, + to: u32, + }, + /// Delete pages; a lesson keeps at least one page. + DeletePages { + pages: Vec, + }, + /// Copy pages, each right after its original. + DuplicatePages { + pages: Vec, + }, + SetPageTitle { + #[serde(default)] + page: Option, + title: String, + }, + + // ------------------------------------------------------------ items + /// Select items on the board (board only; the teacher sees the handles). + SelectItems { + #[serde(default)] + page: Option, + item_ids: Vec, + }, + /// Move items by (`dx`, `dy`), or so their bounds' top-left lands at + /// (`x`, `y`). + MoveItems { + #[serde(default)] + page: Option, + item_ids: Vec, + #[serde(default)] + dx: Option, + #[serde(default)] + dy: Option, + #[serde(default)] + x: Option, + #[serde(default)] + y: Option, + }, + /// Align (`left`, `center`, `right`, `top`, `middle`, `bottom`) and/or + /// distribute (`horizontal`, `vertical`) items; groups move as one. + AlignItems { + #[serde(default)] + page: Option, + item_ids: Vec, + #[serde(default)] + align: Option, + #[serde(default)] + distribute: Option, + /// `items` (default: their common bounds) or `page` (the slide frame). + #[serde(default)] + relative_to: Option, + }, + /// Restyle ink, shapes, text and stamps. + RestyleItems { + #[serde(default)] + page: Option, + item_ids: Vec, + #[serde(default)] + color: Option, + #[serde(default)] + width: Option, + #[serde(default)] + brush: Option, + /// Shape fill `#rrggbb[aa]`, or `none` to remove it. + #[serde(default)] + fill: Option, + #[serde(default)] + opacity: Option, + #[serde(default)] + dashed: Option, + /// Font size of text items. + #[serde(default)] + text_size: Option, + }, + /// Scale items by `factor` about the centre of their bounds. + ScaleItems { + #[serde(default)] + page: Option, + item_ids: Vec, + factor: f64, + }, + GroupItems { + #[serde(default)] + page: Option, + item_ids: Vec, + }, + UngroupItems { + #[serde(default)] + page: Option, + item_ids: Vec, + }, + /// Bring items to the `front` (default) or send them to the `back`. + ReorderItems { + #[serde(default)] + page: Option, + item_ids: Vec, + #[serde(default)] + to: Option, + }, + DeleteItems { + #[serde(default)] + page: Option, + item_ids: Vec, + }, + /// Draw ink strokes from points (one stroke via `points`, or several + /// via `strokes`), as one undo step. + DrawStroke { + #[serde(default)] + page: Option, + #[serde(default)] + points: Option>>, + #[serde(default)] + strokes: Option>, + #[serde(default)] + color: Option, + #[serde(default)] + width: Option, + #[serde(default)] + brush: Option, + #[serde(default)] + opacity: Option, + /// `pen` (default) or `highlighter`. + #[serde(default)] + tool: Option, + }, + /// Change a text box: its text, size, colour or position. + UpdateText { + #[serde(default)] + page: Option, + item_id: String, + #[serde(default)] + text: Option, + #[serde(default)] + size: Option, + #[serde(default)] + color: Option, + #[serde(default)] + x: Option, + #[serde(default)] + y: Option, + #[serde(default)] + w: Option, + }, + + // ----------------------------------------------------------- stamps + /// Built-in stamps and the lesson's custom stamps (the board adds the + /// teacher's device library). + ListStamps, + CreateStamp(Box), + /// Change a custom stamp; only the given fields change. `base` is the + /// definition from the board's device library when the lesson does not + /// have it yet (set by the board, not by agents). + UpdateStamp { + #[serde(flatten)] + def: Box, + #[serde(default, skip_serializing_if = "Option::is_none")] + base: Option>, + }, + /// Delete a custom stamp. Placements keep it in the lesson unless + /// `remove_placements`. `in_library` is set by the board. + DeleteStamp { + id: String, + #[serde(default)] + remove_placements: bool, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + in_library: bool, + }, + /// Place a stamp (built-in or custom) at (`x`, `y`), `size` high. + /// `def` is a custom stamp from the board's device library (set by the + /// board, not by agents). + AddStamp { + #[serde(default)] + page: Option, + stamp: String, + #[serde(default)] + x: Option, + #[serde(default)] + y: Option, + #[serde(default)] + size: Option, + #[serde(default)] + color: Option, + /// The emoji of the `emoji` stamp, a badge number, a label's words. + #[serde(default)] + text: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + def: Option>, + }, + + // ------------------------------------------- board app (live only) + /// Switch mode: `prepare`, `teach` or `student`. + SetMode { + mode: String, + }, + /// Zoom the view (`zoom`: 1 = 100 %) around (`x`, `y`) in slide pixels. + ZoomTo { + #[serde(default)] + zoom: Option, + #[serde(default)] + x: Option, + #[serde(default)] + y: Option, + }, + /// Fit the page to the screen. + FitPage, + StartReplay { + #[serde(default)] + page: Option, + /// 0.5–8, default 2. + #[serde(default)] + speed: Option, + }, + StopReplay, + /// A short burst of stars and confetti across the board (not saved). + Celebrate { + #[serde(default)] + kind: Option, + }, + /// The teacher's current tool and its colour, width and pen style. + SetTool { + tool: String, + #[serde(default)] + color: Option, + #[serde(default)] + width: Option, + #[serde(default)] + brush: Option, + }, + /// Undo the agent's own last change, if it is still the newest. + Undo, + /// Make a PDF of the lesson on the board; it answers the bytes + /// (`pdf_base64`) and, with `download`, also saves it on the board. + ExportPdf { + /// `all` (default), `current`, or a range like `2-5`. + #[serde(default)] + pages: Option, + /// `slides` (default), `handout-2` or `handout-3`. + #[serde(default)] + layout: Option, + #[serde(default)] + ink: Option, + #[serde(default)] + print_friendly: Option, + #[serde(default)] + download: bool, + }, + LibraryList { + #[serde(default)] + folder: Option, + #[serde(default)] + query: Option, + }, + LibraryOpen { + id: String, + }, + LibraryCreateLesson { + title: String, + #[serde(default)] + folder: Option, + /// `blank`, `slides`, `lined` or `grid`. + #[serde(default)] + template: Option, + #[serde(default)] + open: bool, + }, + LibraryMove { + id: String, + folder: Option, + }, + LibraryRename { + id: String, + name: String, + }, + LibraryTrash { + id: String, + }, + GetSettings, + SetSetting { + key: String, + value: serde_json::Value, + }, + GetDockLayout { + #[serde(default)] + mode: Option, + }, + SetDockLayout { + #[serde(default)] + mode: Option, + layout: serde_json::Value, + }, + ListDockItems, + SaveDockPreset { + name: String, + #[serde(default)] + modes: Option>, + }, + ApplyDockPreset { + name: String, + }, } /// How an op touches the board, for the teacher's "Allow AI to edit live" @@ -481,15 +875,76 @@ impl Op { Op::WriteHandwriting { .. } => "write_handwriting", Op::AddShape { .. } => "add_shape", Op::AddTable { .. } => "add_table", + Op::ListPages => "list_pages", + Op::MovePages { .. } => "move_pages", + Op::DeletePages { .. } => "delete_pages", + Op::DuplicatePages { .. } => "duplicate_pages", + Op::SetPageTitle { .. } => "set_page_title", + Op::SelectItems { .. } => "select_items", + Op::MoveItems { .. } => "move_items", + Op::AlignItems { .. } => "align_items", + Op::RestyleItems { .. } => "restyle_items", + Op::ScaleItems { .. } => "scale_items", + Op::GroupItems { .. } => "group_items", + Op::UngroupItems { .. } => "ungroup_items", + Op::ReorderItems { .. } => "reorder_items", + Op::DeleteItems { .. } => "delete_items", + Op::DrawStroke { .. } => "draw_stroke", + Op::UpdateText { .. } => "update_text", + Op::ListStamps => "list_stamps", + Op::CreateStamp(_) => "create_stamp", + Op::UpdateStamp { .. } => "update_stamp", + Op::DeleteStamp { .. } => "delete_stamp", + Op::AddStamp { .. } => "add_stamp", + Op::SetMode { .. } => "set_mode", + Op::ZoomTo { .. } => "zoom_to", + Op::FitPage => "fit_page", + Op::StartReplay { .. } => "start_replay", + Op::StopReplay => "stop_replay", + Op::Celebrate { .. } => "celebrate", + Op::SetTool { .. } => "set_tool", + Op::Undo => "undo", + Op::ExportPdf { .. } => "export_pdf", + Op::LibraryList { .. } => "library_list", + Op::LibraryOpen { .. } => "library_open", + Op::LibraryCreateLesson { .. } => "library_create_lesson", + Op::LibraryMove { .. } => "library_move", + Op::LibraryRename { .. } => "library_rename", + Op::LibraryTrash { .. } => "library_trash", + Op::GetSettings => "get_settings", + Op::SetSetting { .. } => "set_setting", + Op::GetDockLayout { .. } => "get_dock_layout", + Op::SetDockLayout { .. } => "set_dock_layout", + Op::ListDockItems => "list_dock_items", + Op::SaveDockPreset { .. } => "save_dock_preset", + Op::ApplyDockPreset { .. } => "apply_dock_preset", } } pub fn access(&self) -> Access { match self { - Op::GetPage { .. } | Op::GetOutline | Op::GetSelection | Op::Snapshot { .. } => { - Access::Read - } - Op::GoToPage { .. } | Op::PointAt { .. } => Access::Control, + Op::GetPage { .. } + | Op::GetOutline + | Op::GetSelection + | Op::Snapshot { .. } + | Op::ListPages + | Op::ListStamps + | Op::LibraryList { .. } + | Op::GetSettings + | Op::GetDockLayout { .. } + | Op::ListDockItems => Access::Read, + Op::GoToPage { .. } + | Op::PointAt { .. } + | Op::SelectItems { .. } + | Op::SetMode { .. } + | Op::ZoomTo { .. } + | Op::FitPage + | Op::StartReplay { .. } + | Op::StopReplay + | Op::Celebrate { .. } + | Op::SetTool { .. } + | Op::ExportPdf { .. } + | Op::LibraryOpen { .. } => Access::Control, Op::SetBoardTheme { page_color, pattern, @@ -505,6 +960,38 @@ impl Op { } } + /// Ops the board app runs itself (UI state, the library, settings): + /// [`crate::apply`] refuses them and lesson files cannot run them. + pub fn board_only(&self) -> bool { + matches!( + self, + Op::Snapshot { .. } + | Op::PointAt { .. } + | Op::SetMode { .. } + | Op::ZoomTo { .. } + | Op::FitPage + | Op::StartReplay { .. } + | Op::StopReplay + | Op::Celebrate { .. } + | Op::SetTool { .. } + | Op::Undo + | Op::ExportPdf { .. } + | Op::LibraryList { .. } + | Op::LibraryOpen { .. } + | Op::LibraryCreateLesson { .. } + | Op::LibraryMove { .. } + | Op::LibraryRename { .. } + | Op::LibraryTrash { .. } + | Op::GetSettings + | Op::SetSetting { .. } + | Op::GetDockLayout { .. } + | Op::SetDockLayout { .. } + | Op::ListDockItems + | Op::SaveDockPreset { .. } + | Op::ApplyDockPreset { .. } + ) + } + /// A short label for the board's activity feed, e.g. `added text`. pub fn label(&self) -> &'static str { match self { @@ -528,6 +1015,49 @@ impl Op { Op::WriteHandwriting { .. } => "wrote on the board", Op::AddShape { .. } => "drew a shape", Op::AddTable { .. } => "drew a table", + Op::ListPages => "read the lesson", + Op::MovePages { .. } => "moved pages", + Op::DeletePages { .. } => "deleted pages", + Op::DuplicatePages { .. } => "duplicated pages", + Op::SetPageTitle { .. } => "renamed a page", + Op::SelectItems { .. } => "selected items", + Op::MoveItems { .. } => "moved items", + Op::AlignItems { .. } => "aligned items", + Op::RestyleItems { .. } => "restyled items", + Op::ScaleItems { .. } => "resized items", + Op::GroupItems { .. } => "grouped items", + Op::UngroupItems { .. } => "ungrouped items", + Op::ReorderItems { .. } => "reordered items", + Op::DeleteItems { .. } => "deleted items", + Op::DrawStroke { .. } => "drew on the board", + Op::UpdateText { .. } => "edited text", + Op::ListStamps => "read the stamps", + Op::CreateStamp(_) => "made a stamp", + Op::UpdateStamp { .. } => "changed a stamp", + Op::DeleteStamp { .. } => "deleted a stamp", + Op::AddStamp { .. } => "placed a stamp", + Op::SetMode { .. } => "changed the mode", + Op::ZoomTo { .. } => "zoomed", + Op::FitPage => "fitted the page", + Op::StartReplay { .. } => "started a replay", + Op::StopReplay => "stopped the replay", + Op::Celebrate { .. } => "celebrated", + Op::SetTool { .. } => "changed the tool", + Op::Undo => "undid its change", + Op::ExportPdf { .. } => "exported a PDF", + Op::LibraryList { .. } => "read the library", + Op::LibraryOpen { .. } => "opened a lesson", + Op::LibraryCreateLesson { .. } => "created a lesson", + Op::LibraryMove { .. } => "moved a lesson", + Op::LibraryRename { .. } => "renamed a lesson", + Op::LibraryTrash { .. } => "moved a lesson to the trash", + Op::GetSettings => "read the settings", + Op::SetSetting { .. } => "changed a setting", + Op::GetDockLayout { .. } => "read the dock", + Op::SetDockLayout { .. } => "changed the dock", + Op::ListDockItems => "read the dock", + Op::SaveDockPreset { .. } => "saved a dock layout", + Op::ApplyDockPreset { .. } => "changed the dock", } } } diff --git a/crates/rupok-live/src/stamps.rs b/crates/rupok-live/src/stamps.rs new file mode 100644 index 0000000..8dd60b5 --- /dev/null +++ b/crates/rupok-live/src/stamps.rs @@ -0,0 +1,865 @@ +//! Classroom stamps for agents: the built-in set, and **custom stamps** an +//! agent (or the teacher) designs. +//! +//! A custom stamp is a definition ([`StampDef`]): a name, keywords, artwork +//! (sanitised SVG, an emoji or a short label) and a declarative behaviour +//! (placement animation, a burst, a counter badge, a sound, an auto-fade). +//! A **Smart stamp** has `art: "smart"`: its artwork is a tiny Smart Object +//! (HTML/JS) that runs in the ordinary Smart Object sandbox (no network, the +//! SDK only), placed and sized like a stamp. Agent code never runs anywhere +//! else. +//! +//! Lessons store the definitions they use in the root `stamps` map (spec: +//! Custom stamps): id → the definition as JSON, without the Smart stamp's +//! HTML, which lives in the lesson as an ordinary object bundle (shared by +//! every placement, deduplicated by content). A placed SVG, emoji or label +//! stamp is a text item whose `stamp` key is the definition's id and whose +//! `text` is the fallback (the emoji, the label or the name); a placed +//! Smart stamp is an object item. + +use rupok_core::{BoxGeom, Edits, Frame, Item, ItemData, NewItem, ObjectData, TextData}; +use serde_json::{Value, json}; + +use crate::apply::{ + BoardCtx, LiveError, Outcome, color_hex, default_ink, finite, geometry_of, has_errors, + html_bundle, page_ref, parse_color, tag, unique_bundle_id, +}; +use crate::op::{Op, StampBehavior, StampDef}; + +type Result = std::result::Result; + +/// Largest sanitised SVG a stamp may carry. +pub const MAX_SVG_BYTES: usize = 64 * 1024; +/// Largest Smart stamp HTML. +pub const MAX_HTML_BYTES: usize = 512 * 1024; +pub const ANIMATIONS: [&str; 6] = ["none", "pop", "sparkle", "bounce", "spin", "fade-in"]; +pub const BURSTS: [&str; 5] = ["none", "stars", "confetti", "hearts", "sparkles"]; +pub const SOUNDS: [&str; 7] = ["none", "chime", "pop", "ding", "tada", "clap", "whoosh"]; +const ARTS: [&str; 4] = ["svg", "emoji", "text", "smart"]; +/// Default box of a placed stamp, slide pixels. +pub const DEFAULT_SIZE: f64 = 96.0; +const DEFAULT_SMART: f64 = 200.0; + +/// A built-in stamp (apps/board/src/stamps.ts keeps the same list). +pub struct Builtin { + pub id: &'static str, + pub label: &'static str, + /// What a reader without stamps shows (and the default label). + pub text: &'static str, + pub color: u32, + /// A pill sized to its text. + pub pill: bool, +} + +const GOLD: u32 = 0xf5b301ff; +const GREEN: u32 = 0x30a46cff; +const RED: u32 = 0xe5484dff; +const BLUE: u32 = 0x3e63ddff; +const ORANGE: u32 = 0xf76b15ff; +const PURPLE: u32 = 0x8e4ec6ff; + +const fn b(id: &'static str, label: &'static str, text: &'static str, color: u32) -> Builtin { + Builtin { + id, + label, + text, + color, + pill: false, + } +} +const fn pill(id: &'static str, label: &'static str, text: &'static str, color: u32) -> Builtin { + Builtin { + id, + label, + text, + color, + pill: true, + } +} + +pub const BUILTINS: [Builtin; 18] = [ + b("star", "Star", "⭐", GOLD), + b("tick", "Tick", "✅", GREEN), + b("cross", "Cross", "❌", RED), + b("thumbs-up", "Thumbs up", "👍", GOLD), + b("hundred", "100", "💯", RED), + b("heart", "Heart", "❤️", RED), + b("trophy", "Trophy", "🏆", GOLD), + pill("excellent", "Excellent", "Excellent!", GREEN), + pill("good-job", "Good job", "Good job!", BLUE), + pill("try-again", "Try again", "Try again", ORANGE), + pill("important", "Important", "⚡ Important", GOLD), + b("question", "Question", "?", PURPLE), + b("badge", "Number", "1", BLUE), + b("arrow-right", "Arrow right", "→", RED), + b("arrow-down", "Arrow down", "↓", RED), + b("arrow-left", "Arrow left", "←", RED), + b("arrow-up", "Arrow up", "↑", RED), + b("emoji", "Any emoji", "⭐", 0x1c2024ff), +]; + +pub fn builtin(id: &str) -> Option<&'static Builtin> { + BUILTINS.iter().find(|b| b.id == id) +} + +/// Stamp ids follow the format's naming rule: `a-z`, `0-9`, `-`, ≤ 32 bytes. +pub fn valid_id(s: &str) -> bool { + !s.is_empty() + && s.len() <= 32 + && s.bytes() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-') +} + +/// Width of a pill for `text` at height `h` (stamps.ts → stampSize). +fn pill_width(text: &str, h: f64) -> f64 { + let chars = text.chars().count() as f64; + (h * 1.8).max(h * 0.42 * chars + h * 0.9).round() +} + +fn invalid(m: impl Into) -> LiveError { + LiveError::Invalid(m.into()) +} + +fn one_of(what: &str, v: &str, allowed: &[&str]) -> Result { + if allowed.contains(&v) { + Ok(v.to_string()) + } else { + Err(invalid(format!( + "{what} must be one of {}, got `{v}`", + allowed.join(", ") + ))) + } +} + +fn hex(c: &str) -> Result { + Ok(color_hex(parse_color(c)? | 0xff)) +} + +/// Check a behaviour and normalise it (unknown values are refused). +pub fn check_behavior(b: &StampBehavior) -> Result { + let mut out = StampBehavior { + counter: b.counter, + ..Default::default() + }; + if let Some(a) = &b.animation { + out.animation = Some(one_of("animation", a, &ANIMATIONS)?); + } + if let Some(k) = &b.burst { + out.burst = Some(one_of("burst", k, &BURSTS)?); + } + if b.burst_colors.len() > 6 { + return Err(invalid("burst_colors: at most 6 colours")); + } + out.burst_colors = b + .burst_colors + .iter() + .map(|c| hex(c)) + .collect::>()?; + if let Some(s) = &b.sound { + out.sound = Some(one_of("sound", s, &SOUNDS)?); + } + if let Some(f) = b.fade_after { + if !(f.is_finite() && (0.0..=600.0).contains(&f)) { + return Err(invalid( + "fade_after must be between 1 and 600 seconds (0 = never)", + )); + } + out.fade_after = (f >= 1.0).then_some(f); + } + Ok(out) +} + +/// A stamp id from its name: `c--<4 chars>`, unique among `taken`. +fn new_id(name: &str, salt: &str, taken: &dyn Fn(&str) -> bool) -> String { + const D: &[u8; 36] = b"0123456789abcdefghijklmnopqrstuvwxyz"; + let mut base = crate::apply::slug(name); + base.truncate(24); + let base = base.trim_end_matches('-').to_string(); + for seed in 0..10_000u64 { + let mut v = crate::apply::fnv1a(format!("{name}\n{salt}").as_bytes(), seed); + let suffix: String = (0..4) + .map(|_| { + let c = D[(v % 36) as usize] as char; + v /= 36; + c + }) + .collect(); + let id = format!("c-{base}-{suffix}"); + if !taken(&id) && builtin(&id).is_none() { + return id; + } + } + format!("c-{base}") +} + +/// Merge `input` over `base` (an update) and check everything: the result +/// is what is stored (without `html`, which the caller turns into a bundle). +/// Returns the definition and the Smart stamp HTML, if new HTML was given. +pub fn check(input: &StampDef, base: Option<&StampDef>) -> Result<(StampDef, Option)> { + let mut d = base.cloned().unwrap_or_default(); + let pick = |a: &Option, b: &Option| a.clone().or_else(|| b.clone()); + d.name = pick(&input.name, &d.name); + if !input.keywords.is_empty() { + d.keywords = input.keywords.clone(); + } + if let (Some(old), Some(new)) = (&d.art, &input.art) + && old != new + && (old == "smart" || new == "smart") + { + return Err(invalid( + "a Smart stamp cannot become a picture stamp or the other way round; create a new stamp instead", + )); + } + d.art = pick(&input.art, &d.art); + if input.svg.is_some() || input.emoji.is_some() || input.text.is_some() { + d.svg = input.svg.clone(); + d.emoji = input.emoji.clone(); + d.text = input.text.clone(); + } + d.color = pick(&input.color, &d.color); + d.size = input.size.or(d.size); + d.width = input.width.or(d.width); + d.height = input.height.or(d.height); + if let Some(b) = &input.behavior { + d.behavior = Some(b.clone()); + } + d.html = None; + + let name = d.name.as_deref().map(str::trim).unwrap_or(""); + if name.is_empty() || name.chars().count() > 40 { + return Err(invalid( + "name must be 1 to 40 characters, e.g. \"Super star\"", + )); + } + d.name = Some(name.to_string()); + if d.keywords.len() > 12 { + return Err(invalid("keywords: at most 12")); + } + let mut kw = Vec::new(); + for k in &d.keywords { + let k = k.trim().to_lowercase(); + if k.is_empty() || k.chars().count() > 24 { + return Err(invalid("each keyword must be 1 to 24 characters")); + } + if !kw.contains(&k) { + kw.push(k); + } + } + d.keywords = kw; + let art = d + .art + .clone() + .ok_or_else(|| invalid("art is required: svg, emoji, text or smart"))?; + one_of("art", &art, &ARTS)?; + let mut html = None; + match art.as_str() { + "svg" => { + let svg = d + .svg + .as_deref() + .ok_or_else(|| invalid("art \"svg\" needs `svg` markup"))?; + let clean = crate::design::sanitize_svg(svg) + .map_err(|e| invalid(format!("svg refused: {e}")))?; + if clean.len() > MAX_SVG_BYTES { + return Err(invalid(format!( + "svg is larger than {} KB; simplify the drawing", + MAX_SVG_BYTES / 1024 + ))); + } + d.svg = Some(clean); + d.emoji = None; + d.text = None; + } + "emoji" => { + let e = d.emoji.as_deref().map(str::trim).unwrap_or(""); + if e.is_empty() || e.chars().count() > 16 { + return Err(invalid("art \"emoji\" needs `emoji`, e.g. \"🦉\"")); + } + d.emoji = Some(e.to_string()); + d.svg = None; + d.text = None; + } + "text" => { + let t = d.text.as_deref().map(str::trim).unwrap_or(""); + if t.is_empty() || t.chars().count() > 24 { + return Err(invalid( + "art \"text\" needs `text` of 1 to 24 characters, e.g. \"Well done!\"", + )); + } + d.text = Some(t.to_string()); + d.svg = None; + d.emoji = None; + } + _ => { + d.svg = None; + d.emoji = None; + d.text = None; + if let Some(h) = &input.html { + if h.len() > MAX_HTML_BYTES { + return Err(invalid(format!( + "html is larger than {} KB", + MAX_HTML_BYTES / 1024 + ))); + } + html = Some(h.clone()); + } else if d.bundle.is_none() { + return Err(invalid( + "art \"smart\" needs `html`: a tiny Smart Object (read_object_spec)", + )); + } + for (k, v) in [("width", d.width), ("height", d.height)] { + if let Some(v) = v + && !(v.is_finite() && (40.0..=800.0).contains(&v)) + { + return Err(invalid(format!("{k} must be 40 to 800 slide pixels"))); + } + } + } + } + if let Some(c) = &d.color { + d.color = Some(hex(c)?); + } + if let Some(s) = d.size + && !(s.is_finite() && (24.0..=600.0).contains(&s)) + { + return Err(invalid("size must be 24 to 600 slide pixels")); + } + if let Some(b) = &d.behavior { + d.behavior = Some(check_behavior(b)?); + } + Ok((d, html)) +} + +/// The lesson's definition of a custom stamp. +pub fn lesson_def(lesson: &rupok_core::Lesson, id: &str) -> Option { + let json = lesson.stamp_def(id)?; + let mut d: StampDef = serde_json::from_str(&json).ok()?; + d.id = Some(id.to_string()); + d.html = None; + Some(d) +} + +fn store(d: &StampDef) -> Result { + let mut s = d.clone(); + s.html = None; + let json = serde_json::to_string(&s).map_err(|e| invalid(e.to_string()))?; + if json.len() > rupok_core::MAX_STAMP_DEF_BYTES { + return Err(invalid("the stamp definition is too large")); + } + Ok(json) +} + +/// Put Smart stamp HTML in the package as a bundle (reusing an identical +/// one). Returns the bundle id and whether it is new. +fn smart_bundle(ctx: &mut BoardCtx<'_>, d: &StampDef, html: &str) -> Result<(String, bool)> { + let name = d.name.as_deref().unwrap_or("Stamp"); + let w = d.width.unwrap_or(DEFAULT_SMART); + let h = d.height.unwrap_or(DEFAULT_SMART); + for (id, b) in &ctx.pkg.objects { + if b.files.len() == 1 + && b.files.get(&b.manifest.entry).map(Vec::as_slice) == Some(html.as_bytes()) + && b.manifest.permissions.network.is_empty() + { + return Ok((id.clone(), false)); + } + } + let bundle = html_bundle(html, name, w, h, 0, Vec::new()); + let diagnostics = bundle.validate(); + if has_errors(&diagnostics) { + return Err(LiveError::Diagnostics(diagnostics)); + } + let id = unique_bundle_id(name, html, &ctx.pkg.objects); + ctx.pkg.objects.insert(id.clone(), bundle); + Ok((id, true)) +} + +/// Placements of a custom stamp, per page: `(page id, items)`. +fn placements(ctx: &BoardCtx<'_>, d: &StampDef) -> Result)>> { + let id = d.id.as_deref().unwrap_or(""); + let mut out = Vec::new(); + for p in ctx.lesson.pages() { + let on: Vec = ctx + .lesson + .items(&p.id)? + .into_iter() + .filter(|i| match &i.data { + ItemData::Text(t) => t.stamp.as_deref() == Some(id), + ItemData::Object(o) => d.bundle.as_deref() == Some(o.bundle.as_str()), + _ => false, + }) + .collect(); + if !on.is_empty() { + out.push((p.id.clone(), on)); + } + } + Ok(out) +} + +/// What `list_stamps` says about a definition. +fn summary(d: &StampDef, placed: usize) -> Value { + let mut v = serde_json::to_value(d).unwrap_or(Value::Null); + if let Some(m) = v.as_object_mut() { + if let Some(svg) = m.get("svg").and_then(Value::as_str) + && svg.len() > 2_000 + { + let n = svg.len(); + m.insert("svg".into(), json!(format!("({n} bytes of SVG)"))); + } + m.insert("placements".into(), json!(placed)); + m.insert("source".into(), json!("lesson")); + } + v +} + +pub(crate) fn run(ctx: &mut BoardCtx<'_>, op: &Op, msg: &str, now: f64) -> Result { + match op { + Op::ListStamps => { + let builtin: Vec = BUILTINS + .iter() + .map(|b| { + json!({ + "id": b.id, "name": b.label, "text": b.text, + "color": color_hex(b.color), "source": "builtin", + }) + }) + .collect(); + let mut custom = Vec::new(); + for (id, _) in ctx.lesson.stamp_defs() { + if let Some(d) = lesson_def(ctx.lesson, &id) { + let n = placements(ctx, &d)?.iter().map(|(_, v)| v.len()).sum(); + custom.push(summary(&d, n)); + } + } + Ok(Outcome::read(json!({ + "builtin": builtin, + "custom": custom, + "animations": ANIMATIONS, + "bursts": BURSTS, + "sounds": SOUNDS, + "note": "place one with add_stamp(stamp: id); `emoji` takes the emoji as text, `badge` a number", + }))) + } + Op::CreateStamp(input) => { + let (mut d, html) = check(input, None)?; + let taken = |id: &str| ctx.lesson.stamp_def(id).is_some(); + let id = match &input.id { + Some(id) => { + if !valid_id(id) { + return Err(invalid("id must be a-z, 0-9 and -, at most 32 characters")); + } + if builtin(id).is_some() { + return Err(invalid(format!( + "`{id}` is a built-in stamp; pick another id" + ))); + } + if taken(id) { + return Err(invalid(format!( + "a stamp `{id}` already exists; use update_stamp to change it" + ))); + } + id.clone() + } + None => new_id(d.name.as_deref().unwrap_or("stamp"), &store(&d)?, &taken), + }; + d.id = Some(id.clone()); + let mut new_bundle = None; + if let Some(h) = &html { + let (b, fresh) = smart_bundle(ctx, &d, h)?; + d.bundle = Some(b.clone()); + if fresh { + new_bundle = Some(b); + } + } + let e = Edits { + stamp_defs: vec![(id.clone(), Some(store(&d)?))], + ..Default::default() + }; + tag(ctx.lesson, msg); + if let Err(err) = ctx.lesson.apply_edits(ctx.page_id, &e) { + if let Some(b) = new_bundle { + ctx.pkg.objects.remove(&b); + } + return Err(err.into()); + } + Ok(Outcome::changed(json!({ + "id": id, + "stamp": d, + "next": format!("place it with add_stamp(stamp: \"{id}\", x, y)"), + }))) + } + Op::UpdateStamp { def, base } => { + let id = def + .id + .clone() + .ok_or_else(|| invalid("id is required: the stamp to change (list_stamps)"))?; + if builtin(&id).is_some() { + return Err(invalid( + "built-in stamps cannot be changed; create_stamp makes your own", + )); + } + let in_lesson = lesson_def(ctx.lesson, &id); + let existing = in_lesson + .clone() + .or_else(|| base.as_deref().cloned()) + .ok_or_else(|| { + LiveError::NotFound(format!( + "no custom stamp `{id}`; list_stamps shows the ids" + )) + })?; + let (mut d, html) = check(def, Some(&existing))?; + d.id = Some(id.clone()); + if in_lesson.is_none() { + // Only in the teacher's device library: the board keeps it. + return Ok(Outcome::read( + json!({ "id": id, "stamp": d, "in_lesson": false }), + )); + } + let old = in_lesson.unwrap_or_default(); + let mut new_bundle = None; + if let Some(h) = &html { + let (b, fresh) = smart_bundle(ctx, &d, h)?; + d.bundle = Some(b.clone()); + if fresh { + new_bundle = Some(b); + } + } + let json = store(&d)?; + // Smart stamps whose HTML changed: re-point the placements (one + // change per page that shows the stamp). + let mut pages = if d.bundle != old.bundle { + placements(ctx, &old)? + .into_iter() + .map(|(p, items)| { + ( + p, + items + .into_iter() + .filter(|i| matches!(i.data, ItemData::Object(_))) + .collect::>(), + ) + }) + .filter(|(_, v)| !v.is_empty()) + .collect() + } else { + Vec::new() + }; + if pages.is_empty() { + pages.push((ctx.page_id.to_string(), Vec::new())); + } + let mut moved = 0; + for (i, (page, items)) in pages.iter().enumerate() { + let mut e = Edits { + stamp_defs: if i == 0 { + vec![(id.clone(), Some(json.clone()))] + } else { + Vec::new() + }, + ..Default::default() + }; + for it in items { + if let ItemData::Object(o) = &it.data { + e.remove.push(it.id.clone()); + e.add.push(NewItem { + data: ItemData::Object(ObjectData { + bundle: d.bundle.clone().unwrap_or_default(), + title: d.name.clone().unwrap_or_default(), + state: None, + step: 0, + ..o.clone() + }), + created: it.created, + group: it.group.clone(), + z: Some(it.z), + }); + moved += 1; + } + } + tag(ctx.lesson, msg); + if let Err(err) = ctx.lesson.apply_edits(page, &e) { + if let Some(b) = &new_bundle { + ctx.pkg.objects.remove(b); + } + return Err(err.into()); + } + } + Ok(Outcome::changed(json!({ + "id": id, + "stamp": d, + "in_lesson": true, + "placements_updated": moved, + }))) + } + Op::DeleteStamp { + id, + remove_placements, + in_library, + } => { + if builtin(id).is_some() { + return Err(invalid("built-in stamps cannot be deleted")); + } + let Some(d) = lesson_def(ctx.lesson, id) else { + if *in_library { + return Ok(Outcome::read(json!({ "id": id, "in_lesson": false }))); + } + return Err(LiveError::NotFound(format!( + "no custom stamp `{id}` in this lesson; list_stamps shows the ids" + ))); + }; + let placed = placements(ctx, &d)?; + let count: usize = placed.iter().map(|(_, v)| v.len()).sum(); + if count > 0 && !remove_placements { + return Ok(Outcome::read(json!({ + "id": id, + "in_lesson": true, + "kept_in_lesson": true, + "placements": count, + "note": "the lesson still shows this stamp, so it keeps its definition; pass remove_placements: true to remove the stamps from the pages too", + }))); + } + let mut pages = placed; + if pages.is_empty() { + pages.push((ctx.page_id.to_string(), Vec::new())); + } + for (i, (page, items)) in pages.iter().enumerate() { + let e = Edits { + stamp_defs: if i == 0 { + vec![(id.clone(), None)] + } else { + Vec::new() + }, + remove: items.iter().map(|it| it.id.clone()).collect(), + ..Default::default() + }; + tag(ctx.lesson, msg); + ctx.lesson.apply_edits(page, &e)?; + } + Ok(Outcome::changed(json!({ + "id": id, + "deleted": true, + "placements_removed": count, + }))) + } + Op::AddStamp { + page, + stamp, + x, + y, + size, + color, + text, + def, + } => add( + ctx, + *page, + stamp, + *x, + *y, + *size, + color, + text, + def.as_deref(), + msg, + now, + ), + _ => Err(LiveError::Unsupported(op.name())), + } +} + +#[allow(clippy::too_many_arguments)] +fn add( + ctx: &mut BoardCtx<'_>, + page: Option, + stamp: &str, + x: Option, + y: Option, + size: Option, + color: &Option, + text: &Option, + def: Option<&StampDef>, + msg: &str, + now: f64, +) -> Result { + let (idx, info) = page_ref(ctx.lesson, ctx.page_id, page)?; + let frame = info.frame.unwrap_or(Frame::SLIDE_16_9); + let size = match size { + Some(s) if s.is_finite() && (16.0..=800.0).contains(&s) => Some(s), + Some(_) => return Err(invalid("size must be 16 to 800 slide pixels")), + None => None, + }; + let color = color.as_deref().map(parse_color).transpose()?; + if let Some(t) = text + && (t.trim().is_empty() || t.chars().count() > 24) + { + return Err(invalid("text must be 1 to 24 characters")); + } + let place = |w: f64, h: f64| -> Result { + Ok(BoxGeom { + x: finite("x", x.unwrap_or((frame.w - w) / 2.0))?, + y: finite("y", y.unwrap_or((frame.h - h) / 2.0))?, + w, + h, + rot: 0.0, + }) + }; + let mut e = Edits::default(); + let mut new_bundle = None; + let mut behavior = None; + let data = if let Some(b) = builtin(stamp) { + let h = size.unwrap_or(if b.pill { 76.0 } else { DEFAULT_SIZE }); + let t = match b.id { + "emoji" => text + .clone() + .ok_or_else(|| invalid("the emoji stamp needs `text`: the emoji, e.g. \"🦉\""))?, + "badge" => match text { + Some(t) => t.clone(), + None => next_badge(&ctx.lesson.items(&info.id)?).to_string(), + }, + _ if b.pill => text.clone().unwrap_or_else(|| b.text.to_string()), + _ => b.text.to_string(), + }; + let w = if b.pill { pill_width(&t, h) } else { h }; + ItemData::Text(TextData { + geom: place(w, h)?, + text: t, + size: (h * 0.7).round(), + color: color.unwrap_or(b.color), + latex: false, + stamp: Some(b.id.to_string()), + }) + } else { + if !valid_id(stamp) { + return Err(invalid(format!( + "no stamp `{stamp}`; list_stamps shows the ids" + ))); + } + let (d, html) = match lesson_def(ctx.lesson, stamp) { + Some(d) => (d, None), + None => { + let Some(given) = def else { + return Err(LiveError::NotFound(format!( + "no stamp `{stamp}`; list_stamps shows the ids (create_stamp makes a new one)" + ))); + }; + let (mut d, html) = check(given, None)?; + d.id = Some(stamp.to_string()); + (d, html) + } + }; + let mut d = d; + let fresh_def = lesson_def(ctx.lesson, stamp).is_none(); + behavior = d.behavior.clone(); + let name = d.name.clone().unwrap_or_default(); + if d.art.as_deref() == Some("smart") { + let have = d + .bundle + .as_ref() + .is_some_and(|b| ctx.pkg.objects.contains_key(b)); + if !have { + let h = html.ok_or_else(|| { + invalid(format!( + "the Smart stamp `{stamp}` has no HTML in this lesson; update_stamp with html first" + )) + })?; + let (b, fresh) = smart_bundle(ctx, &d, &h)?; + d.bundle = Some(b.clone()); + if fresh { + new_bundle = Some(b); + } + } + if fresh_def || d.bundle != lesson_def(ctx.lesson, stamp).and_then(|o| o.bundle) { + e.stamp_defs.push((stamp.to_string(), Some(store(&d)?))); + } + let (dw, dh) = ( + d.width.unwrap_or(DEFAULT_SMART), + d.height.unwrap_or(DEFAULT_SMART), + ); + let h = size.or(d.size).unwrap_or(dh); + let w = (dw * h / dh).round(); + ItemData::Object(ObjectData { + geom: place(w, h)?, + bundle: d.bundle.clone().unwrap_or_default(), + title: name, + step: 0, + state: None, + }) + } else { + if fresh_def { + e.stamp_defs.push((stamp.to_string(), Some(store(&d)?))); + } + let h = size.or(d.size).unwrap_or(DEFAULT_SIZE); + let (fallback, w) = match d.art.as_deref() { + Some("text") => { + let t = d.text.clone().unwrap_or(name.clone()); + let w = pill_width(&t, h); + (t, w) + } + Some("emoji") => (d.emoji.clone().unwrap_or(name.clone()), h), + _ => (name.clone(), h), + }; + let tint = d + .color + .as_deref() + .and_then(|c| parse_color(c).ok()) + .unwrap_or_else(|| default_ink(info.bg_color)); + ItemData::Text(TextData { + geom: place(w, h)?, + text: fallback, + size: (h * 0.7).round(), + color: color.unwrap_or(tint), + latex: false, + stamp: Some(stamp.to_string()), + }) + } + }; + let geom = match &data { + ItemData::Text(t) => t.geom, + ItemData::Object(o) => o.geom, + _ => BoxGeom::default(), + }; + e.add.push(NewItem { + data, + created: now, + group: None, + z: None, + }); + tag(ctx.lesson, msg); + let ids = match ctx.lesson.apply_edits(&info.id, &e) { + Ok(ids) => ids, + Err(err) => { + if let Some(b) = new_bundle { + ctx.pkg.objects.remove(&b); + } + return Err(err.into()); + } + }; + let count = ctx + .lesson + .items(&info.id)? + .iter() + .filter(|i| match &i.data { + ItemData::Text(t) => t.stamp.as_deref() == Some(stamp), + _ => false, + }) + .count(); + Ok(Outcome::changed(json!({ + "item_id": ids.first(), + "stamp": stamp, + "page": idx + 1, + "geometry": geometry_of(&geom), + "count_on_page": count, + "behavior": behavior, + }))) +} + +/// The next number for a badge: one more than the highest on the page. +fn next_badge(items: &[Item]) -> u32 { + items + .iter() + .filter_map(|i| match &i.data { + ItemData::Text(t) if t.stamp.as_deref() == Some("badge") => t.text.trim().parse().ok(), + _ => None, + }) + .max() + .unwrap_or(0) + + 1 +} diff --git a/crates/rupok-wasm/src/lib.rs b/crates/rupok-wasm/src/lib.rs index 9ffab26..4ce4eb4 100644 --- a/crates/rupok-wasm/src/lib.rs +++ b/crates/rupok-wasm/src/lib.rs @@ -999,6 +999,16 @@ mod web { .map_err(|e| JsValue::from_str(&e)) } + /// Custom stamps stored in the lesson: `{id: definition}`. + pub fn stamp_defs_json(&self) -> String { + crate::live::stamp_defs_json(&self.engine) + } + + /// Check a custom stamp definition (the stamp editor, stamp packs). + pub fn check_stamp_json(def_json: &str) -> Result { + crate::live::check_stamp_json(def_json).map_err(|e| JsValue::from_str(&e)) + } + // ------------------------------------------- AI handwriting (solve) // `write_handwriting` writes through `live_apply`; these set the // teacher's glyphs, preview without writing, and drive the reveal. diff --git a/crates/rupok-wasm/src/live.rs b/crates/rupok-wasm/src/live.rs index 2c3b104..64aaf3e 100644 --- a/crates/rupok-wasm/src/live.rs +++ b/crates/rupok-wasm/src/live.rs @@ -143,6 +143,9 @@ pub fn apply( if let Some(i) = out.show_page { e.goto_page(i); } + if let Some(ids) = out.select.take() { + e.select(ids); + } if let Op::WriteHandwriting { .. } = &op { start_reveal(e, &mut out.result, now_ms); } @@ -177,6 +180,32 @@ fn start_reveal(e: &mut Engine, result: &mut serde_json::Value, n } } +/// The lesson's custom stamp definitions, `{id: definition}` (for drawing +/// them; see [`rupok_live::stamps`]). +pub fn stamp_defs_json(e: &Engine) -> String { + let mut m = serde_json::Map::new(); + for (id, _) in e.lesson.stamp_defs() { + if let Some(d) = rupok_live::stamps::lesson_def(&e.lesson, &id) { + m.insert(id, serde_json::to_value(d).unwrap_or_default()); + } + } + serde_json::Value::Object(m).to_string() +} + +/// Check a custom stamp definition from the teacher's editor or an +/// imported stamp pack (SVG sanitised, behaviour checked) without touching +/// the lesson. Returns the clean definition (keeping `html` for a Smart +/// stamp) or `{"error"}`. +pub fn check_stamp_json(def_json: &str) -> Result { + let d: rupok_live::StampDef = + serde_json::from_str(def_json).map_err(|err| error_json(format!("bad stamp: {err}")))?; + let (mut clean, html) = + rupok_live::stamps::check(&d, None).map_err(|err| err.to_json().to_string())?; + clean.id = d.id.filter(|i| rupok_live::stamps::valid_id(i)); + clean.html = html; + Ok(serde_json::to_string(&clean).unwrap_or_default()) +} + /// The lesson's encoded version vector. pub fn version(e: &Engine) -> Vec { rupok_live::sync::version(&e.lesson) @@ -274,6 +303,86 @@ mod tests { assert!(apply(&mut e, r#"{"op":"get_page"}"#, "A", 4.0).is_ok()); } + #[test] + fn item_ops_select_restyle_and_stamps_on_the_live_engine() { + let mut e = engine(); + let r = apply( + &mut e, + r#"{"op":"draw_stroke","points":[[100,100],[300,200]]}"#, + "Claude Code", + 2_000.0, + ) + .unwrap(); + let v: serde_json::Value = serde_json::from_str(&r).unwrap(); + let id = v["item_ids"][0].as_str().unwrap().to_string(); + assert_eq!(e.stroke_count(), 1, "drawn in the scene"); + apply( + &mut e, + &format!(r#"{{"op":"select_items","item_ids":["{id}"]}}"#), + "Claude Code", + 2_100.0, + ) + .unwrap(); + assert_eq!( + e.selection(), + std::slice::from_ref(&id), + "the board shows the selection" + ); + apply( + &mut e, + &format!(r##"{{"op":"restyle_items","item_ids":["{id}"],"color":"#e5484d"}}"##), + "Claude Code", + 2_200.0, + ) + .unwrap(); + assert_eq!( + attribution_json(&e, 0), + format!(r#"{{"{id}":"Claude Code"}}"#) + ); + assert!(e.undo(), "one undo per agent op"); + assert!(e.undo()); + assert_eq!(e.stroke_count(), 0); + + // custom stamps: the agent makes one, the teacher places it (untagged) + let r = apply( + &mut e, + r#"{"op":"create_stamp","id":"owl","name":"Owl","art":"emoji","emoji":"🦉"}"#, + "Claude Code", + 3_000.0, + ) + .unwrap(); + assert!(r.contains(r#""id":"owl""#)); + assert!(stamp_defs_json(&e).contains("🦉")); + let r = apply( + &mut e, + r#"{"op":"add_stamp","stamp":"owl","x":10,"y":10}"#, + "", + 3_100.0, + ) + .unwrap(); + let v: serde_json::Value = serde_json::from_str(&r).unwrap(); + let sid = v["item_id"].as_str().unwrap(); + assert!(e.dom_items_json().contains(sid)); + assert!( + !attribution_json(&e, 0).contains(sid), + "the teacher's own placement is not attributed to an agent" + ); + // the editor's check: clean SVG, refused scripts + let ok = check_stamp_json( + r#"{"name":"S","art":"svg","svg":""}"#, + ) + .unwrap(); + assert!(ok.contains("xmlns")); + assert!( + check_stamp_json(r#"{"name":"S","art":"svg","svg":""}"#).is_err() + ); + let smart = check_stamp_json(r#"{"name":"D","art":"smart","html":"

hi

"}"#).unwrap(); + assert!( + smart.contains("

hi

"), + "the editor keeps the HTML for the device library" + ); + } + #[test] fn handwriting_is_revealed_stroke_by_stroke_and_undone_at_once() { let mut e = engine(); From 6e87dcfeb0ec2b5364dc60afecea4db4ba49fdf5 Mon Sep 17 00:00:00 2001 From: shaitrish37 <244331886+shaitrish37@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:00:52 +0600 Subject: [PATCH 2/4] cli: MCP tools for everything on the board mcp_agent.rs adds the agent-control tools: pages, items, stamps (file and live, path optional), modes, zoom, replay, celebrate, set_tool, undo_last_change, export_pdf (the board makes it, the server saves it in the workspace), the Library, settings (allowlist; secrets refused before they reach the board) and the Smart Dock (live). doc_op runs any document op on a lesson file. Tests: MCP e2e on files, the fake ACP agent's /stamp flow in the chat test, and agent_capabilities.rs, which fails CI when a setting, dock button or live op has no row in docs/agent-capabilities.md. --- crates/rupok-cli/src/lib.rs | 3 + crates/rupok-cli/src/live/mod.rs | 9 +- crates/rupok-cli/src/mcp.rs | 13 +- crates/rupok-cli/src/mcp_agent.rs | 1533 ++++++++++++++++++ crates/rupok-cli/src/tools.rs | 18 + crates/rupok-cli/src/workspace.rs | 32 +- crates/rupok-cli/tests/agent_capabilities.rs | 167 ++ crates/rupok-cli/tests/chat.rs | 30 + crates/rupok-cli/tests/fake-acp-agent.mjs | 29 + crates/rupok-cli/tests/mcp_e2e.rs | 144 ++ 10 files changed, 1969 insertions(+), 9 deletions(-) create mode 100644 crates/rupok-cli/src/mcp_agent.rs create mode 100644 crates/rupok-cli/tests/agent_capabilities.rs diff --git a/crates/rupok-cli/src/lib.rs b/crates/rupok-cli/src/lib.rs index f084648..7119a81 100644 --- a/crates/rupok-cli/src/lib.rs +++ b/crates/rupok-cli/src/lib.rs @@ -5,6 +5,8 @@ //! - [`tools`]: the MCP tool surface as plain Rust (params + [`tools::Tools`]). //! - [`mcp`]: the rmcp stdio server wrapping [`tools::Tools`]. //! - [`live`], [`mcp_live`]: the live board channel (`rupok mcp --live`) and its tools. +//! - [`mcp_agent`]: tools for everything else on the board (pages, items, stamps, modes, +//! export, library, settings, dock); docs/agent-capabilities.md. //! - [`cli`]: the clap command line. //! - [`spec`]: the Smart Object spec served to agents. @@ -12,6 +14,7 @@ pub mod chat; pub mod cli; pub mod live; pub mod mcp; +pub mod mcp_agent; pub mod mcp_http; pub mod mcp_live; pub mod ops; diff --git a/crates/rupok-cli/src/live/mod.rs b/crates/rupok-cli/src/live/mod.rs index 1e0ac08..ba4b14d 100644 --- a/crates/rupok-cli/src/live/mod.rs +++ b/crates/rupok-cli/src/live/mod.rs @@ -427,6 +427,11 @@ impl LiveHub { /// Run an agent op on the paired board and wait for its result. pub async fn call(&self, op: Op) -> Result { + // Making a PDF of a long lesson takes the board a while. + let timeout = match &op { + Op::ExportPdf { .. } => self.cfg.op_timeout.max(Duration::from_secs(180)), + _ => self.cfg.op_timeout, + }; let (id, rx, track) = { let mut s = self.lock(); let Some(board) = s.board.as_ref() else { @@ -471,14 +476,14 @@ impl LiveHub { } (id, orx, track) }; - let res = match tokio::time::timeout(self.cfg.op_timeout, rx).await { + let res = match tokio::time::timeout(timeout, rx).await { Ok(Ok(r)) => r, Ok(Err(_)) => Err(CallError::new("the board disconnected before answering")), Err(_) => { self.lock().waiting.remove(&id); Err(CallError::new(format!( "the board did not answer within {} s; it may be busy or the tab may be in the background", - self.cfg.op_timeout.as_secs() + timeout.as_secs() ))) } }; diff --git a/crates/rupok-cli/src/mcp.rs b/crates/rupok-cli/src/mcp.rs index 40fcf5a..d73a53a 100644 --- a/crates/rupok-cli/src/mcp.rs +++ b/crates/rupok-cli/src/mcp.rs @@ -53,6 +53,13 @@ you teach on the board.\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\ +- Agent-first: you can do anything the teacher can. Pages (`list_pages`, `move_pages`, `duplicate_pages`, \ +`delete_pages`), items (`select_items`, `move_items`, `align_items`, `restyle_items`, `scale_items`, `group_items`, \ +`delete_items`, `draw_stroke`, `update_text`), stamps (`add_stamp`, `create_stamp` incl. Smart stamps with sandboxed \ +logic), modes and view (`set_mode`, `zoom_to`, `start_replay`, `celebrate`), `export_pdf`, the Library \ +(`library_*`), settings (`get_settings`/`set_setting`, an allowlist) and the Smart Dock (`set_dock_layout`). \ +Document tools take an optional `path` (omit for the board). Settings and mode changes ask the teacher's permission \ +like edits; AI keys, accounts, payments and permissions are never yours to change.\n\ - To solve a problem written on the board, read it (`get_page_snapshot` with its item_ids), check every \ step, then `write_handwriting` the solution as short lines; the board writes it in handwriting next to \ the problem. If the result says `preview`, the teacher is checking it first: do not write it again.", @@ -62,7 +69,7 @@ the problem. If the result says `preview`, the teacher is checking it first: do #[derive(Clone)] pub struct McpServer { - tools: Arc, + pub(crate) tools: Arc, /// The live board channel (see `crate::mcp_live`); disabled without `--live`. pub(crate) live: Arc, tool_router: ToolRouter, @@ -81,12 +88,12 @@ impl McpServer { Self { tools: Arc::new(tools), live, - tool_router: Self::tool_router() + Self::live_tool_router(), + tool_router: Self::tool_router() + Self::live_tool_router() + Self::agent_tool_router(), } } /// Run a tool body on the blocking pool (it does file IO) and map the result. - async fn run(&self, f: F) -> CallToolResult + pub(crate) async fn run(&self, f: F) -> CallToolResult where T: Serialize + Send + 'static, F: FnOnce(&Tools) -> Result + Send + 'static, diff --git a/crates/rupok-cli/src/mcp_agent.rs b/crates/rupok-cli/src/mcp_agent.rs new file mode 100644 index 0000000..2b36353 --- /dev/null +++ b/crates/rupok-cli/src/mcp_agent.rs @@ -0,0 +1,1533 @@ +//! MCP tools that make every part of Rupok controllable by an agent +//! (docs/agent-capabilities.md): pages, items (select, move, align, +//! restyle, scale, group, reorder, delete, draw, edit text), stamps and +//! custom stamps, modes and the view, replay, PDF export, the Library, +//! settings and the Smart Dock. +//! +//! Document tools take an optional `path`: omitted or `"live"` runs on the +//! paired board (one attributed undo step there), a `.rpk` path runs the +//! same [`rupok_live`] code on a lesson file. Board-app tools (modes, view, +//! library, settings, dock, export) need the live board. The board enforces +//! "Allow AI to edit live" and Student view for all of them, and settings +//! never include AI keys, accounts, payments or permissions. + +use base64::Engine as _; +use rmcp::handler::server::wrapper::Parameters; +use rmcp::model::{CallToolResult, ContentBlock}; +use rmcp::{tool, tool_router}; +use rupok_live::{Op, StampBehavior, StampDef, StrokeArg}; +use schemars::JsonSchema; +use serde::Deserialize; +use serde_json::{Value, json}; + +use crate::mcp::McpServer; +use crate::mcp_live::is_live; + +// ------------------------------------------------------------------ params + +#[derive(Clone, Debug, Default, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct PathOnly { + /// `"live"` (default) for the lesson open on the paired board, or a + /// `.rpk` path in the workspace. + #[serde(default)] + pub path: Option, +} + +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct PagesParams { + /// `"live"` (default) or a `.rpk` path. + #[serde(default)] + pub path: Option, + /// 1-based page numbers, e.g. `[3, 4]`. + pub pages: Vec, +} + +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct MovePagesParams { + /// `"live"` (default) or a `.rpk` path. + #[serde(default)] + pub path: Option, + /// 1-based page numbers to move (they stay in order, side by side). + pub pages: Vec, + /// Where the first moved page ends up, 1-based, counted after the move + /// (1 = the front; the page count minus the moved pages plus 1 = the end). + #[schemars(range(min = 1))] + pub to: u32, +} + +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct PageTitleParams { + /// `"live"` (default) or a `.rpk` path. + #[serde(default)] + pub path: Option, + /// 1-based page. Omit for the current page (page 1 in a file). + #[serde(default)] + pub page: Option, + /// The page's name in the pages panel (not drawn on the slide). + pub title: String, +} + +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ItemsParams { + /// `"live"` (default) or a `.rpk` path. + #[serde(default)] + pub path: Option, + /// 1-based page. Omit for the current page (page 1 in a file). + #[serde(default)] + pub page: Option, + /// Item ids from get_current_page, get_selection or get_lesson_outline. + pub item_ids: Vec, +} + +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct SelectParams { + /// 1-based page (the board shows it). Omit for the current page. + #[serde(default)] + pub page: Option, + /// Items to select; `[]` clears the selection. + pub item_ids: Vec, +} + +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct MoveItemsParams { + /// `"live"` (default) or a `.rpk` path. + #[serde(default)] + pub path: Option, + #[serde(default)] + pub page: Option, + pub item_ids: Vec, + /// Move by this much (slide pixels). + #[serde(default)] + pub dx: Option, + #[serde(default)] + pub dy: Option, + /// Or move so the items' bounds start here (top-left, slide pixels). + #[serde(default)] + pub x: Option, + #[serde(default)] + pub y: Option, +} + +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct AlignParams { + /// `"live"` (default) or a `.rpk` path. + #[serde(default)] + pub path: Option, + #[serde(default)] + pub page: Option, + pub item_ids: Vec, + /// `left`, `center`, `right`, `top`, `middle` or `bottom`. + #[serde(default)] + pub align: Option, + /// `horizontal` or `vertical`: equal gaps (three or more items). + #[serde(default)] + pub distribute: Option, + /// `items` (default: their common bounds) or `page` (the slide). + #[serde(default)] + pub relative_to: Option, +} + +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct RestyleParams { + /// `"live"` (default) or a `.rpk` path. + #[serde(default)] + pub path: Option, + #[serde(default)] + pub page: Option, + pub item_ids: Vec, + /// Ink, text and stamp colour `#rrggbb`. + #[serde(default)] + pub color: Option, + /// Line width in slide pixels (0.5–200). + #[serde(default)] + pub width: Option, + /// Pen style: pen, ballpoint, fountain, marker, pencil, chalk, brush, + /// dashed, dotted, neon or rainbow. + #[serde(default)] + pub brush: Option, + /// Shape fill `#rrggbb` or `#rrggbbaa` (e.g. `#20c99733`), or `none`. + #[serde(default)] + pub fill: Option, + /// Ink opacity 0.05–1. + #[serde(default)] + pub opacity: Option, + /// Dashed shape outline. + #[serde(default)] + pub dashed: Option, + /// Font size of text boxes, slide pixels. + #[serde(default)] + pub text_size: Option, +} + +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ScaleParams { + /// `"live"` (default) or a `.rpk` path. + #[serde(default)] + pub path: Option, + #[serde(default)] + pub page: Option, + pub item_ids: Vec, + /// 2 = twice as big, 0.5 = half (0.05–20), about the items' centre. + pub factor: f64, +} + +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct StrokeParam { + /// `[[x, y], [x, y, pressure], …]` in slide pixels; pressure 0–1. + pub points: Vec>, + #[serde(default)] + pub color: Option, + #[serde(default)] + pub width: Option, + #[serde(default)] + pub brush: Option, +} + +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct DrawStrokeParams { + /// `"live"` (default) or a `.rpk` path. + #[serde(default)] + pub path: Option, + #[serde(default)] + pub page: Option, + /// One stroke: `[[x, y], …]` or `[[x, y, pressure], …]`, slide pixels. + #[serde(default)] + pub points: Option>>, + /// Several strokes, each with its own points and optional style. + #[serde(default)] + pub strokes: Option>, + /// Ink colour `#rrggbb`. Default: readable on the page. + #[serde(default)] + pub color: Option, + /// Pen width in slide pixels. Default 4 (highlighter 22). + #[serde(default)] + pub width: Option, + /// Pen style (see restyle_items). + #[serde(default)] + pub brush: Option, + #[serde(default)] + pub opacity: Option, + /// `pen` (default) or `highlighter`. + #[serde(default)] + pub tool: Option, +} + +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct UpdateTextParams { + /// `"live"` (default) or a `.rpk` path. + #[serde(default)] + pub path: Option, + #[serde(default)] + pub page: Option, + pub item_id: String, + #[serde(default)] + pub text: Option, + /// Font size, slide pixels (keep ≥ 24 for projectors). + #[serde(default)] + pub size: Option, + #[serde(default)] + pub color: Option, + #[serde(default)] + pub x: Option, + #[serde(default)] + pub y: Option, + #[serde(default)] + pub w: Option, +} + +/// A stamp's behaviour (no code). +#[derive(Clone, Debug, Default, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct StampBehaviorArg { + /// Placement animation: none, pop (default), sparkle, bounce, spin, fade-in. + #[serde(default)] + pub animation: Option, + /// A short burst around the stamp: none, stars, confetti, hearts, sparkles. + #[serde(default)] + pub burst: Option, + /// Burst colours `#rrggbb`, at most 6. + #[serde(default)] + pub burst_colors: Option>, + /// A number badge counting this stamp on the page (1, 2, 3…). + #[serde(default)] + pub counter: Option, + /// A short sound (the board's mute wins): none, chime, pop, ding, tada, clap, whoosh. + #[serde(default)] + pub sound: Option, + /// Fade away this many seconds after it is placed (1–600; 0 = never). + #[serde(default)] + pub fade_after: Option, +} + +impl From for StampBehavior { + fn from(b: StampBehaviorArg) -> Self { + StampBehavior { + animation: b.animation, + burst: b.burst, + burst_colors: b.burst_colors.unwrap_or_default(), + counter: b.counter.unwrap_or(false), + sound: b.sound, + fade_after: b.fade_after, + } + } +} + +#[derive(Clone, Debug, Default, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct StampParams { + /// `"live"` (default: the board and the teacher's stamp library) or a `.rpk` path. + #[serde(default)] + pub path: Option, + /// For update: the stamp to change. For create: optional id (a-z, 0-9, + /// -; generated from the name when omitted). + #[serde(default)] + pub id: Option, + /// Shown in the Stamps palette, e.g. "Super star". + #[serde(default)] + pub name: Option, + /// Search words, e.g. ["praise", "gold"]. + #[serde(default)] + pub keywords: Option>, + /// `svg`, `emoji`, `text` (a pill with a short label) or `smart` (a tiny + /// Smart Object with your logic, e.g. a dice that rolls on tap). + #[serde(default)] + pub art: Option, + /// SVG markup, simple and bold, viewBox about 100×100. Use + /// `fill="currentColor"` to let the teacher recolour it. No scripts, + /// event handlers, external references or SMIL animation (refused). + #[serde(default)] + pub svg: Option, + #[serde(default)] + pub emoji: Option, + /// The pill's label (1–24 characters), e.g. "Well done!". + #[serde(default)] + pub text: Option, + /// `#rrggbb`: the pill colour, or the SVG's currentColor. + #[serde(default)] + pub color: Option, + /// Default height, slide pixels (24–600; default 96). + #[serde(default)] + pub size: Option, + #[serde(default)] + pub behavior: Option, + /// `smart` art: complete HTML for a small Smart Object (read_object_spec; + /// sandboxed, offline, no network). Make the whole body tappable. + #[serde(default)] + pub html: Option, + /// `smart` art: placement width and height (40–800, default 200). + #[serde(default)] + pub width: Option, + #[serde(default)] + pub height: Option, +} + +impl StampParams { + fn def(self) -> (Option, StampDef) { + ( + self.path, + StampDef { + id: self.id, + name: self.name, + keywords: self.keywords.unwrap_or_default(), + art: self.art, + svg: self.svg, + emoji: self.emoji, + text: self.text, + color: self.color, + size: self.size, + behavior: self.behavior.map(Into::into), + html: self.html, + bundle: None, + width: self.width, + height: self.height, + }, + ) + } +} + +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct DeleteStampParams { + /// `"live"` (default: the board and the teacher's stamp library) or a `.rpk` path. + #[serde(default)] + pub path: Option, + pub id: String, + /// Also remove the placed stamps from the pages. Default false: a stamp + /// still on a page keeps its definition in the lesson. + #[serde(default)] + pub remove_placements: Option, +} + +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct AddStampParams { + /// `"live"` (default) or a `.rpk` path. + #[serde(default)] + pub path: Option, + #[serde(default)] + pub page: Option, + /// A stamp id from list_stamps: built-in (`star`, `tick`, `excellent`, + /// `badge`, `emoji`, …) or custom. + pub stamp: String, + /// Top-left in slide pixels. Default: centred. + #[serde(default)] + pub x: Option, + #[serde(default)] + pub y: Option, + /// Height in slide pixels (16–800). Default: the stamp's size (96). + #[serde(default)] + pub size: Option, + #[serde(default)] + pub color: Option, + /// The emoji for `emoji`, a number for `badge`, the words of a pill. + #[serde(default)] + pub text: Option, +} + +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ModeParams { + /// `prepare`, `teach` or `student`. Leaving Student view is the teacher's call. + pub mode: String, +} + +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ZoomParams { + /// 1 = 100 %, 2 = 200 % (0.1–8). + #[serde(default)] + pub zoom: Option, + /// Centre on this point (slide pixels). Default: the middle of the screen. + #[serde(default)] + pub x: Option, + #[serde(default)] + pub y: Option, +} + +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ReplayParams { + /// 1-based page to replay. Default: the current page. + #[serde(default)] + pub page: Option, + /// 0.5–8, default 2. + #[serde(default)] + pub speed: Option, +} + +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct CelebrateParams { + /// `stars` (default), `confetti` or `hearts`. + #[serde(default)] + pub kind: Option, +} + +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct SetToolParams { + /// pen, highlighter, eraser, lasso (select), laser, text, shape, stamp, hand or interact. + pub tool: String, + /// Ink colour `#rrggbb` (pen, highlighter). + #[serde(default)] + pub color: Option, + /// Pen width in slide pixels. + #[serde(default)] + pub width: Option, + /// Pen style (see restyle_items). + #[serde(default)] + pub brush: Option, +} + +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ExportPdfParams { + /// `all` (default), `current`, or a range like `2-5`. + #[serde(default)] + pub pages: Option, + /// `slides` (default), `handout-2` or `handout-3`. + #[serde(default)] + pub layout: Option, + /// Include the ink (default true). + #[serde(default)] + pub ink: Option, + /// White pages and dark ink for printing. + #[serde(default)] + pub print_friendly: Option, + /// Save the PDF here in the workspace (must end in .pdf). Default: + /// `.pdf`. + #[serde(default)] + pub save_as: Option, + /// Also download it on the board (the teacher's browser or app). + #[serde(default)] + pub download: Option, +} + +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct LibraryListParams { + /// A folder id from a previous library_list. Default: everything. + #[serde(default)] + pub folder: Option, + /// Search in titles. + #[serde(default)] + pub query: Option, +} + +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct LibraryIdParams { + /// A lesson (or folder) id from library_list. + pub id: String, +} + +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct LibraryCreateParams { + pub title: String, + /// Folder id from library_list. Default: the top of the library. + #[serde(default)] + pub folder: Option, + /// `blank` (default), `slides`, `lined` or `grid`. + #[serde(default)] + pub template: Option, + /// Open it on the board right away (the open lesson is saved first). + #[serde(default)] + pub open: Option, +} + +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct LibraryMoveParams { + pub id: String, + /// Destination folder id; omit or null for the top of the library. + #[serde(default)] + pub folder: Option, +} + +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct LibraryRenameParams { + pub id: String, + pub name: String, +} + +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct SetSettingParams { + /// A key from get_settings, e.g. `theme`, `accent`, `density`, + /// `pen.style`, `pen.color`, `pen.width`, `smartShapes`. + pub key: String, + /// The new value (a string, number or boolean as get_settings shows). + pub value: Value, +} + +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct DockModeParams { + /// `prepare` or `teach`. Default: the mode on screen. + #[serde(default)] + pub mode: Option, +} + +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct SetDockParams { + /// `prepare` or `teach`. Default: the mode on screen. + #[serde(default)] + pub mode: Option, + /// The dock: `{position, orientation, size, large, groups: [{label?, + /// items: [ids]}], split: {position, groups}}`; ids from list_dock_items. + /// Only the given keys change. Pen, eraser and undo always stay. + pub layout: Value, +} + +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct SaveDockPresetParams { + /// A name for the teacher's layout list, e.g. "Science lab". + pub name: String, + /// Which modes it stores (default both). + #[serde(default)] + pub modes: Option>, +} + +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct DockPresetParams { + /// "Left-handed", "Minimal teaching", "Maths class", "Default" or a + /// layout the teacher saved. + pub name: String, +} + +// ------------------------------------------------------------------- tools + +fn live_or(path: &Option) -> Option { + match path.as_deref() { + None => None, + Some(p) if is_live(p) => None, + Some(p) => Some(p.to_string()), + } +} + +/// Keys that are never an agent's business, refused before they reach the +/// board (the board has its own allowlist too). +fn forbidden_setting(key: &str) -> bool { + let k = key.to_ascii_lowercase(); + [ + "key", + "token", + "secret", + "password", + "cloud", + "account", + "billing", + "payment", + "plan", + "permission", + "allowedit", + "allow_edit", + "chatpermissions", + "chatallownoprompt", + "connect", + ] + .iter() + .any(|w| k.contains(w)) +} + +/// A safe file name from a lesson title. +fn pdf_name(title: &str) -> String { + let mut s: String = title + .chars() + .map(|c| { + if c.is_alphanumeric() || c == ' ' || c == '-' || c == '_' { + c + } else { + '-' + } + }) + .collect(); + s = s.trim().chars().take(80).collect(); + if s.is_empty() { + s = "lesson".into(); + } + format!("{s}.pdf") +} + +impl McpServer { + /// A document op: on the board (`path` omitted or `"live"`) or a file. + async fn doc(&self, path: Option, op: Op) -> CallToolResult { + match live_or(&path) { + None => self.live_call(op).await, + Some(p) => self.run(move |t| t.doc_op(&p, op)).await, + } + } +} + +#[tool_router(router = agent_tool_router, vis = "pub(crate)")] +impl McpServer { + // ------------------------------------------------------------- pages + #[tool( + description = "List every page of a lesson: number, id, title (or its first text), colour, pattern \ +and how many items it has. Lighter than get_lesson_outline. Omit `path` for the live board.", + annotations(read_only_hint = true, open_world_hint = false) + )] + async fn list_pages(&self, Parameters(p): Parameters) -> CallToolResult { + self.doc(p.path, Op::ListPages).await + } + + #[tool( + description = "Reorder pages: move the given pages (1-based) together so the first lands at position \ +`to` (counted after the move). One undo step. Example: move page 5 to the front with pages [5], to 1.", + annotations( + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn move_pages(&self, Parameters(p): Parameters) -> CallToolResult { + self.doc( + p.path, + Op::MovePages { + pages: p.pages, + to: p.to, + }, + ) + .await + } + + #[tool( + description = "Delete pages (1-based). A lesson keeps at least one page. Confirm with the teacher first. \ +One undo step brings them all back.", + annotations( + read_only_hint = false, + destructive_hint = true, + open_world_hint = false + ) + )] + async fn delete_pages(&self, Parameters(p): Parameters) -> CallToolResult { + self.doc(p.path, Op::DeletePages { pages: p.pages }).await + } + + #[tool( + description = "Duplicate pages (1-based), each copy right after its original, with everything on it. \ +One undo step; returns the copies' page numbers.", + annotations( + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn duplicate_pages(&self, Parameters(p): Parameters) -> CallToolResult { + self.doc(p.path, Op::DuplicatePages { pages: p.pages }) + .await + } + + #[tool( + description = "Rename a page (its title in the pages panel; not drawn on the slide).", + annotations( + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn set_page_title(&self, Parameters(p): Parameters) -> CallToolResult { + self.doc( + p.path, + Op::SetPageTitle { + page: p.page, + title: p.title, + }, + ) + .await + } + + // ------------------------------------------------------------- items + #[tool( + description = "Select items on the live board, as if the teacher lassoed them (the selection toolbar \ +appears). `[]` clears it. Use it to show the teacher what you mean before changing it.", + annotations( + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn select_items(&self, Parameters(p): Parameters) -> CallToolResult { + self.live_call(Op::SelectItems { + page: p.page, + item_ids: p.item_ids, + }) + .await + } + + #[tool( + description = "Move items by (dx, dy), or so their common bounds start at (x, y), in slide pixels. \ +Ink, text, shapes, images and Smart Objects all move. One undo step.", + annotations( + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn move_items(&self, Parameters(p): Parameters) -> CallToolResult { + self.doc( + p.path, + Op::MoveItems { + page: p.page, + item_ids: p.item_ids, + dx: p.dx, + dy: p.dy, + x: p.x, + y: p.y, + }, + ) + .await + } + + #[tool( + description = "Align items (left, center, right, top, middle, bottom) to their common bounds or to the \ +slide, and/or distribute them with equal gaps (horizontal, vertical; three or more). Grouped items (e.g. a \ +handwritten word) move as one. One undo step.", + annotations( + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn align_items(&self, Parameters(p): Parameters) -> CallToolResult { + self.doc( + p.path, + Op::AlignItems { + page: p.page, + item_ids: p.item_ids, + align: p.align, + distribute: p.distribute, + relative_to: p.relative_to, + }, + ) + .await + } + + #[tool( + description = "Restyle items: colour (ink, text, stamps), line width, pen style (brush), shape fill \ +(`#rrggbbaa` or none), dashed outline, ink opacity and text size. Highlighter ink stays translucent. Images and \ +Smart Objects are skipped. One undo step.", + annotations( + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn restyle_items(&self, Parameters(p): Parameters) -> CallToolResult { + self.doc( + p.path, + Op::RestyleItems { + page: p.page, + item_ids: p.item_ids, + color: p.color, + width: p.width, + brush: p.brush, + fill: p.fill, + opacity: p.opacity, + dashed: p.dashed, + text_size: p.text_size, + }, + ) + .await + } + + #[tool( + description = "Make items bigger or smaller by `factor` about their centre: ink, shapes (still exact \ +shapes), text (font size too), images and Smart Objects. One undo step.", + annotations( + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn scale_items(&self, Parameters(p): Parameters) -> CallToolResult { + self.doc( + p.path, + Op::ScaleItems { + page: p.page, + item_ids: p.item_ids, + factor: p.factor, + }, + ) + .await + } + + #[tool( + description = "Group items so they select, move and delete together (at least two). One undo step.", + annotations( + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn group_items(&self, Parameters(p): Parameters) -> CallToolResult { + self.doc( + p.path, + Op::GroupItems { + page: p.page, + item_ids: p.item_ids, + }, + ) + .await + } + + #[tool( + description = "Ungroup: dissolve the groups the given items belong to. One undo step.", + annotations( + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn ungroup_items(&self, Parameters(p): Parameters) -> CallToolResult { + self.doc( + p.path, + Op::UngroupItems { + page: p.page, + item_ids: p.item_ids, + }, + ) + .await + } + + #[tool( + description = "Bring items to the front (on top of everything else on the page). One undo step.", + annotations( + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn bring_to_front(&self, Parameters(p): Parameters) -> CallToolResult { + self.doc( + p.path, + Op::ReorderItems { + page: p.page, + item_ids: p.item_ids, + to: Some("front".into()), + }, + ) + .await + } + + #[tool( + description = "Send items to the back (behind everything else on the page). One undo step.", + annotations( + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn send_to_back(&self, Parameters(p): Parameters) -> CallToolResult { + self.doc( + p.path, + Op::ReorderItems { + page: p.page, + item_ids: p.item_ids, + to: Some("back".into()), + }, + ) + .await + } + + #[tool( + description = "Delete several items at once (ink, text, shapes, stamps, images, Smart Objects). Never \ +delete the teacher's work without asking first. One undo step brings them all back.", + annotations( + read_only_hint = false, + destructive_hint = true, + open_world_hint = false + ) + )] + async fn delete_items(&self, Parameters(p): Parameters) -> CallToolResult { + self.doc( + p.path, + Op::DeleteItems { + page: p.page, + item_ids: p.item_ids, + }, + ) + .await + } + + #[tool( + description = "Draw ink on the board from points: one stroke (`points`) or several (`strokes`), in a \ +colour, width and pen style (pen, ballpoint, fountain, marker, pencil, chalk, brush, dashed, dotted, neon, \ +rainbow), as pen or highlighter. Points are slide pixels, optionally with pressure. Use it to underline, circle \ +or tick; for shapes prefer add_shape, for words add_text or write_handwriting. One undo step.", + annotations( + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn draw_stroke(&self, Parameters(p): Parameters) -> CallToolResult { + let strokes = p.strokes.map(|v| { + v.into_iter() + .map(|s| StrokeArg { + points: s.points, + color: s.color, + width: s.width, + brush: s.brush, + }) + .collect() + }); + self.doc( + p.path, + Op::DrawStroke { + page: p.page, + points: p.points, + strokes, + color: p.color, + width: p.width, + brush: p.brush, + opacity: p.opacity, + tool: p.tool, + }, + ) + .await + } + + #[tool( + description = "Edit a text box: its text, font size, colour or position. One undo step.", + annotations( + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn update_text(&self, Parameters(p): Parameters) -> CallToolResult { + self.doc( + p.path, + Op::UpdateText { + page: p.page, + item_id: p.item_id, + text: p.text, + size: p.size, + color: p.color, + x: p.x, + y: p.y, + w: p.w, + }, + ) + .await + } + + // ------------------------------------------------------------ stamps + #[tool( + description = "List the stamps: built-in (star, tick, cross, excellent, badge, emoji, arrows…), the \ +lesson's custom stamps (with how often each is placed) and, live, the teacher's own library (\"My stamps\"). \ +Also lists the animations, bursts and sounds a custom stamp can use.", + annotations(read_only_hint = true, open_world_hint = false) + )] + async fn list_stamps(&self, Parameters(p): Parameters) -> CallToolResult { + self.doc(p.path, Op::ListStamps).await + } + + #[tool( + description = "Make a custom stamp for the teacher. Artwork: `svg` (bold and simple, viewBox ~100×100, \ +fill=\"currentColor\" so it can be recoloured), `emoji`, or `text` (a short pill label). Behaviour without code: \ +animation (pop, sparkle, bounce, spin, fade-in), a burst (stars, confetti, hearts, sparkles; colours), a counter \ +badge, a sound (chime, pop, ding, tada, clap, whoosh; the board's mute wins) and fade_after seconds. Or `art: \ +\"smart\"` with `html`: a tiny Smart Object with your own logic (a dice that rolls on tap, a timer, a tap counter) \ +that runs in the Smart Object sandbox (offline, no network; read_object_spec). Live, it joins the teacher's \"My \ +stamps\" and the lesson. One undo step. Keep stamps readable on a projector, celebratory but brief.", + annotations( + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn create_stamp(&self, Parameters(p): Parameters) -> CallToolResult { + let (path, def) = p.def(); + self.doc(path, Op::CreateStamp(Box::new(def))).await + } + + #[tool( + description = "Change a custom stamp by id: only the fields you give change (name, keywords, artwork, \ +colour, size, behaviour, Smart stamp html). Every placement shows the new look. Built-in stamps cannot change.", + annotations( + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn update_stamp(&self, Parameters(p): Parameters) -> CallToolResult { + if p.id.is_none() { + return CallToolResult::structured_error( + json!({ "error": "id is required: the custom stamp to change (list_stamps)" }), + ); + } + let (path, def) = p.def(); + self.doc( + path, + Op::UpdateStamp { + def: Box::new(def), + base: None, + }, + ) + .await + } + + #[tool( + description = "Delete a custom stamp from the teacher's library (live) and the lesson. A stamp still \ +placed on a page keeps its definition in the lesson unless remove_placements is true (which also removes \ +those stamps). Ask the teacher first.", + annotations( + read_only_hint = false, + destructive_hint = true, + open_world_hint = false + ) + )] + async fn delete_stamp(&self, Parameters(p): Parameters) -> CallToolResult { + self.doc( + p.path, + Op::DeleteStamp { + id: p.id, + remove_placements: p.remove_placements.unwrap_or(false), + in_library: false, + }, + ) + .await + } + + #[tool( + description = "Place a stamp on a page by id (built-in or custom) at (x, y) with a size: a star for a \ +good answer, a tick, \"Excellent!\", a numbered badge (`badge`, numbers itself), any emoji (`emoji` with text) \ +or the teacher's own. Its behaviour (animation, burst, sound) plays on the board. One undo step.", + annotations( + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn add_stamp(&self, Parameters(p): Parameters) -> CallToolResult { + self.doc( + p.path, + Op::AddStamp { + page: p.page, + stamp: p.stamp, + x: p.x, + y: p.y, + size: p.size, + color: p.color, + text: p.text, + def: None, + }, + ) + .await + } + + // ------------------------------------------------- the board (live) + #[tool( + description = "Switch the board's mode: `prepare` (build the lesson), `teach` (present full screen) or \ +`student` (read-only). The teacher's permission is asked like an edit; leaving Student view is refused (the \ +teacher does that).", + annotations( + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn set_mode(&self, Parameters(p): Parameters) -> CallToolResult { + if !matches!(p.mode.as_str(), "prepare" | "teach" | "student") { + return CallToolResult::structured_error( + json!({ "error": "mode must be prepare, teach or student" }), + ); + } + self.live_call(Op::SetMode { mode: p.mode }).await + } + + #[tool( + description = "Zoom the board's view (1 = 100 %) around a point on the slide, e.g. to show detail. \ +fit_page goes back.", + annotations( + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn zoom_to(&self, Parameters(p): Parameters) -> CallToolResult { + self.live_call(Op::ZoomTo { + zoom: p.zoom, + x: p.x, + y: p.y, + }) + .await + } + + #[tool( + description = "Fit the whole page on the screen again.", + annotations( + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn fit_page(&self) -> CallToolResult { + self.live_call(Op::FitPage).await + } + + #[tool( + description = "Replay a page stroke by stroke, as it was written (great for revising how a diagram \ +was built).", + annotations( + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn start_replay(&self, Parameters(p): Parameters) -> CallToolResult { + self.live_call(Op::StartReplay { + page: p.page, + speed: p.speed, + }) + .await + } + + #[tool( + description = "Stop a running replay.", + annotations( + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn stop_replay(&self) -> CallToolResult { + self.live_call(Op::StopReplay).await + } + + #[tool( + description = "A short celebration across the board (stars, confetti or hearts) for a class \ +achievement. Nothing is saved.", + annotations( + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn celebrate(&self, Parameters(p): Parameters) -> CallToolResult { + self.live_call(Op::Celebrate { kind: p.kind }).await + } + + #[tool( + description = "Pick the teacher's current tool (pen, highlighter, eraser, lasso, laser, text, shape, \ +stamp, hand, interact) and, for ink, its colour, width and pen style, e.g. \"give me a red chalk pen\".", + annotations( + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn set_tool(&self, Parameters(p): Parameters) -> CallToolResult { + self.live_call(Op::SetTool { + tool: p.tool, + color: p.color, + width: p.width, + brush: p.brush, + }) + .await + } + + #[tool( + description = "Undo your own last change on the board, if it is still the newest change (it never \ +undoes the teacher's work).", + annotations( + read_only_hint = false, + destructive_hint = true, + open_world_hint = false + ) + )] + async fn undo_last_change(&self) -> CallToolResult { + self.live_call(Op::Undo).await + } + + #[tool( + description = "Export the lesson on the board as a PDF (all pages, the current one or a range; slides \ +or handouts; print-friendly) and save it in the workspace (`save_as`, default `.pdf`); `download` also \ +saves it on the teacher's board. Returns where it was saved.", + annotations( + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn export_pdf(&self, Parameters(p): Parameters<ExportPdfParams>) -> CallToolResult { + if let Some(s) = &p.save_as + && let Err(e) = self.tools.workspace().resolve_new_pdf(s) + { + return CallToolResult::structured_error(json!({ "error": e.to_string() })); + } + let op = Op::ExportPdf { + pages: p.pages, + layout: p.layout, + ink: p.ink, + print_friendly: p.print_friendly, + download: p.download.unwrap_or(false), + }; + let mut v = match self.live.call(op).await { + Ok(v) => v, + Err(e) => return CallToolResult::structured_error(e.to_json()), + }; + let b64 = v + .get("pdf_base64") + .and_then(Value::as_str) + .unwrap_or_default() + .to_string(); + let bytes = match base64::engine::general_purpose::STANDARD.decode(b64.as_bytes()) { + Ok(b) if b.starts_with(b"%PDF") => b, + _ => { + return CallToolResult::structured_error( + json!({ "error": "the board did not return a PDF" }), + ); + } + }; + let name = p.save_as.unwrap_or_else(|| { + pdf_name(v.get("title").and_then(Value::as_str).unwrap_or("lesson")) + }); + let tools = self.tools.clone(); + let len = bytes.len(); + let saved = tokio::task::spawn_blocking(move || -> Result<String, String> { + let ws = tools.workspace(); + let abs = ws.resolve_new_pdf(&name).map_err(|e| e.to_string())?; + if let Some(dir) = abs.parent() { + std::fs::create_dir_all(dir).map_err(|e| e.to_string())?; + } + std::fs::write(&abs, &bytes).map_err(|e| e.to_string())?; + Ok(ws.display(&abs)) + }) + .await; + match saved { + Ok(Ok(path)) => { + if let Some(m) = v.as_object_mut() { + m.remove("pdf_base64"); + m.insert("saved_to".into(), json!(path)); + m.insert("bytes".into(), json!(len)); + } + CallToolResult::structured(v) + } + Ok(Err(e)) => CallToolResult::structured_error(json!({ "error": e })), + Err(e) => { + CallToolResult::error(vec![ContentBlock::text(format!("internal error: {e}"))]) + } + } + } + + // ----------------------------------------------------------- library + #[tool( + description = "The teacher's Rupok Library on the board (browser storage, a folder or the desktop app): \ +lessons and folders with ids, titles, where they are and when they changed. Workspace .rpk files are \ +list_lessons instead.", + annotations(read_only_hint = true, open_world_hint = false) + )] + async fn library_list(&self, Parameters(p): Parameters<LibraryListParams>) -> CallToolResult { + self.live_call(Op::LibraryList { + folder: p.folder, + query: p.query, + }) + .await + } + + #[tool( + description = "Open a lesson from the Library on the board (the open lesson is saved first). The class \ +sees the new lesson, so do it when asked.", + annotations( + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn library_open(&self, Parameters(p): Parameters<LibraryIdParams>) -> CallToolResult { + self.live_call(Op::LibraryOpen { id: p.id }).await + } + + #[tool( + description = "Create a new lesson in the teacher's Library (blank, slides, lined or grid), in a folder, \ +optionally opening it. Returns its id.", + annotations( + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn library_create_lesson( + &self, + Parameters(p): Parameters<LibraryCreateParams>, + ) -> CallToolResult { + self.live_call(Op::LibraryCreateLesson { + title: p.title, + folder: p.folder, + template: p.template, + open: p.open.unwrap_or(false), + }) + .await + } + + #[tool( + description = "Move a lesson or folder to another folder of the Library.", + annotations( + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn library_move(&self, Parameters(p): Parameters<LibraryMoveParams>) -> CallToolResult { + self.live_call(Op::LibraryMove { + id: p.id, + folder: p.folder, + }) + .await + } + + #[tool( + description = "Rename a lesson or folder in the Library.", + annotations( + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn library_rename( + &self, + Parameters(p): Parameters<LibraryRenameParams>, + ) -> CallToolResult { + self.live_call(Op::LibraryRename { + id: p.id, + name: p.name, + }) + .await + } + + #[tool( + description = "Move a lesson or folder to the Library's trash (the teacher can restore it; deleting \ +forever is the teacher's call). Ask first.", + annotations( + read_only_hint = false, + destructive_hint = true, + open_world_hint = false + ) + )] + async fn library_trash(&self, Parameters(p): Parameters<LibraryIdParams>) -> CallToolResult { + self.live_call(Op::LibraryTrash { id: p.id }).await + } + + // ---------------------------------------------------------- settings + #[tool( + description = "Read the board settings an agent may change (theme, accent colour, density, toolbar \ +side, icon style, pages panel, pen style/colour/width, eraser, smart shapes, voice language, PDF defaults…), \ +with their current values and allowed values. AI keys, the cloud account, payments and permissions are never \ +included.", + annotations(read_only_hint = true, open_world_hint = false) + )] + async fn get_settings(&self) -> CallToolResult { + self.live_call(Op::GetSettings).await + } + + #[tool( + description = "Change one board setting from get_settings (e.g. theme dark, accent #20c997, pen.style \ +chalk). The teacher is asked like for an edit, and the AI chip's Undo puts it back.", + annotations( + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn set_setting(&self, Parameters(p): Parameters<SetSettingParams>) -> CallToolResult { + if forbidden_setting(&p.key) { + return CallToolResult::structured_error(json!({ + "error": format!("`{}` is the teacher's alone (AI keys, accounts, payments and permissions are never changed by an agent)", p.key) + })); + } + self.live_call(Op::SetSetting { + key: p.key, + value: p.value, + }) + .await + } + + // -------------------------------------------------------------- dock + #[tool( + description = "Read the Smart Dock layout of a mode (Prepare or Teach): position, orientation, button \ +size, large icons, the groups of buttons in order, and the optional second (split) dock.", + annotations(read_only_hint = true, open_world_hint = false) + )] + async fn get_dock_layout(&self, Parameters(p): Parameters<DockModeParams>) -> CallToolResult { + self.live_call(Op::GetDockLayout { mode: p.mode }).await + } + + #[tool( + description = "Customise the Smart Dock for the teacher (\"pen, highlighter and eraser on the left, undo \ +and next page on the right, bigger buttons\"): position (left, right, top, bottom, corners), orientation, \ +groups of buttons (ids from list_dock_items, each group separated), a split second dock on another edge, button \ +size (small, medium, large) and large icons. Pen, eraser and undo always stay. Validated; the teacher is asked \ +like for an edit and can undo it from the AI chip.", + annotations( + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn set_dock_layout(&self, Parameters(p): Parameters<SetDockParams>) -> CallToolResult { + self.live_call(Op::SetDockLayout { + mode: p.mode, + layout: p.layout, + }) + .await + } + + #[tool( + description = "Everything that can go on the Smart Dock (tools and action buttons with ids, labels and \ +whether they must stay), and the named layouts (built-in and the teacher's).", + annotations(read_only_hint = true, open_world_hint = false) + )] + async fn list_dock_items(&self) -> CallToolResult { + self.live_call(Op::ListDockItems).await + } + + #[tool( + description = "Save the current dock layout (Prepare and Teach) under a name the teacher can switch to.", + annotations( + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn save_dock_preset( + &self, + Parameters(p): Parameters<SaveDockPresetParams>, + ) -> CallToolResult { + self.live_call(Op::SaveDockPreset { + name: p.name, + modes: p.modes, + }) + .await + } + + #[tool( + description = "Switch to a named dock layout: \"Left-handed\", \"Minimal teaching\", \"Maths class\", \ +\"Default\" or one the teacher saved.", + annotations( + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn apply_dock_preset( + &self, + Parameters(p): Parameters<DockPresetParams>, + ) -> CallToolResult { + self.live_call(Op::ApplyDockPreset { name: p.name }).await + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn paths_names_and_guards() { + assert_eq!(live_or(&None), None); + assert_eq!(live_or(&Some("LIVE".into())), None); + assert_eq!(live_or(&Some("a.rpk".into())), Some("a.rpk".into())); + assert!(forbidden_setting("claudeKey")); + assert!(forbidden_setting("ai.allowEdit")); + assert!(forbidden_setting("cloudAccount")); + assert!(!forbidden_setting("theme")); + assert!(!forbidden_setting("pen.style")); + assert_eq!(pdf_name("Ohm's law / Class 9"), "Ohm-s law - Class 9.pdf"); + assert_eq!(pdf_name("///"), "---.pdf"); + assert_eq!(pdf_name(""), "lesson.pdf"); + } + + #[test] + fn stamp_params_become_a_definition() { + let p: StampParams = serde_json::from_value(json!({ + "name": "Dice", "art": "smart", "html": "<p>1</p>", + "behavior": {"animation": "pop", "counter": true} + })) + .unwrap(); + let (path, d) = p.def(); + assert!(path.is_none()); + assert_eq!(d.html.as_deref(), Some("<p>1</p>")); + assert!(d.behavior.unwrap().counter); + assert!(serde_json::from_value::<StampParams>(json!({"bogus": 1})).is_err()); + } +} diff --git a/crates/rupok-cli/src/tools.rs b/crates/rupok-cli/src/tools.rs index 32d9e09..9caf64d 100644 --- a/crates/rupok-cli/src/tools.rs +++ b/crates/rupok-cli/src/tools.rs @@ -726,6 +726,20 @@ impl Tools { /// Run a page design op (`set_page_design`, `set_branding`) on a lesson /// file: the same code the live board runs, saved when it changed. pub fn design_op(&self, path: &str, op: rupok_live::Op) -> Result<serde_json::Value> { + self.doc_op(path, op) + } + + /// Run a live operation (pages, items, stamps, page design…) on a lesson + /// file with exactly the code the board runs, and save the file when it + /// changed. "The current page" is page 1. Board-app operations (modes, + /// the view, the library, settings) are refused with a clear error. + pub fn doc_op(&self, path: &str, op: rupok_live::Op) -> Result<serde_json::Value> { + if op.board_only() { + return Err(ops::OpError::Invalid(format!( + "`{}` works only on the live board: pass path \"live\" (a board must be paired)", + op.name() + ))); + } let _g = self.guard(); let abs = self.lesson(path)?; let (mut pkg, mut lesson) = ops::load(&abs)?; @@ -742,6 +756,10 @@ impl Tools { }; let out = rupok_live::apply(ctx, &op, "agent", now).map_err(|e| match e { rupok_live::LiveError::NotFound(m) => ops::OpError::NotFound(m), + rupok_live::LiveError::Diagnostics(d) => ops::OpError::Diagnostics(d), + rupok_live::LiveError::Unsupported(name) => ops::OpError::Invalid(format!( + "`{name}` works only on the live board: pass path \"live\" (a board must be paired)" + )), e => ops::OpError::Invalid(e.to_string()), })?; if out.changed { diff --git a/crates/rupok-cli/src/workspace.rs b/crates/rupok-cli/src/workspace.rs index 76750da..18ce6cc 100644 --- a/crates/rupok-cli/src/workspace.rs +++ b/crates/rupok-cli/src/workspace.rs @@ -6,7 +6,8 @@ //! - `..` components are rejected outright (even when they would stay inside); //! - absolute paths are accepted only when they point inside the workspace; //! - symlinks are resolved and the *target* must be inside the workspace; -//! - only `.rpk` files may be written. +//! - only `.rpk` files may be written, plus the `.pdf` an agent exports +//! from the live board (`export_pdf`). use std::ffi::OsStr; use std::path::{Component, Path, PathBuf}; @@ -23,6 +24,8 @@ pub enum PathError { SymlinkEscape(String), #[error("only .rpk lesson files may be written, got `{0}`")] NotLesson(String), + #[error("an exported PDF must be saved as a .pdf file, got `{0}`")] + NotPdf(String), #[error("`{0}` does not exist")] NotFound(String), #[error("`{0}` is not a regular file")] @@ -144,9 +147,24 @@ impl Workspace { /// are allowed (they must themselves end up inside the workspace); the /// caller creates them. pub fn resolve_new_lesson(&self, user: &str) -> Result<PathBuf, PathError> { + self.resolve_new(user, is_lesson_path, PathError::NotLesson) + } + + /// Resolve a `.pdf` path to write (an exported lesson), like + /// [`Workspace::resolve_new_lesson`]. + pub fn resolve_new_pdf(&self, user: &str) -> Result<PathBuf, PathError> { + self.resolve_new(user, is_pdf_path, PathError::NotPdf) + } + + fn resolve_new( + &self, + user: &str, + is_lesson_path: fn(&Path) -> bool, + bad: fn(String) -> PathError, + ) -> Result<PathBuf, PathError> { let joined = self.lexical(user)?; if !is_lesson_path(&joined) { - return Err(PathError::NotLesson(user.to_string())); + return Err(bad(user.to_string())); } // If something already exists at the path (file or dangling link), // resolve it fully so a symlink cannot redirect the write. @@ -158,7 +176,7 @@ impl Workspace { return Err(self.escape_error(user, &joined)); } if !is_lesson_path(&canonical) { - return Err(PathError::NotLesson(user.to_string())); + return Err(bad(user.to_string())); } return Ok(canonical); } @@ -166,7 +184,7 @@ impl Workspace { // components are plain names (no `..`, checked above). let file_name = joined .file_name() - .ok_or_else(|| PathError::NotLesson(user.to_string()))? + .ok_or_else(|| bad(user.to_string()))? .to_owned(); let mut existing = joined .parent() @@ -226,6 +244,12 @@ impl Workspace { } } +pub fn is_pdf_path(p: &Path) -> bool { + p.extension() + .and_then(OsStr::to_str) + .is_some_and(|e| e.eq_ignore_ascii_case("pdf")) +} + pub fn is_lesson_path(p: &Path) -> bool { p.extension() .and_then(OsStr::to_str) diff --git a/crates/rupok-cli/tests/agent_capabilities.rs b/crates/rupok-cli/tests/agent_capabilities.rs new file mode 100644 index 0000000..870574e --- /dev/null +++ b/crates/rupok-cli/tests/agent_capabilities.rs @@ -0,0 +1,167 @@ +//! Rupok is agent-first (AGENTS.md, rule 8): every setting, dock button and +//! live operation must have an agent path or be marked "teacher only" with a +//! reason in docs/agent-capabilities.md, and the settings an agent may +//! change must match the board's allowlist (apps/board/src/agentSettings.ts). +//! This test keeps the three in step. It reads the sources as text. + +use std::collections::BTreeSet; +use std::path::{Path, PathBuf}; + +fn root() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../..") +} + +fn read(rel: &str) -> String { + std::fs::read_to_string(root().join(rel)).unwrap_or_else(|e| panic!("{rel}: {e}")) +} + +/// Every `"…"` string after `marker` up to the first `end`. +fn quoted_between(src: &str, marker: &str, end: &str) -> Vec<String> { + let start = src.find(marker).unwrap_or_else(|| panic!("no `{marker}`")) + marker.len(); + let rest = &src[start..]; + let body = &rest[..rest.find(end).unwrap_or(rest.len())]; + body.split('"') + .enumerate() + .filter(|(i, _)| i % 2 == 1) + .map(|(_, s)| s.to_string()) + .collect() +} + +/// Registry ids: `id: "x.y"` in settings/defs (dotted ids; keyboard list skipped). +fn registry_ids() -> BTreeSet<String> { + let dir = root().join("apps/board/src/settings/defs"); + let mut out = BTreeSet::new(); + for e in std::fs::read_dir(&dir).unwrap() { + let p = e.unwrap().path(); + let src = std::fs::read_to_string(&p).unwrap(); + for part in src.split("id: \"").skip(1) { + let id = &part[..part.find('"').unwrap()]; + if id.contains('.') && !id.starts_with("keyboard.") && !id.contains('$') { + out.insert(id.to_string()); + } + } + } + out +} + +/// `| \`id\` | who | how |` rows of the section titled `heading`. +fn rows(doc: &str, heading: &str) -> Vec<(String, String, String)> { + let start = doc + .find(heading) + .unwrap_or_else(|| panic!("no section {heading}")); + let body = &doc[start + heading.len()..]; + let body = &body[..body.find("\n## ").unwrap_or(body.len())]; + body.lines() + .filter(|l| l.starts_with("| `")) + .map(|l| { + let cells: Vec<String> = l + .trim_matches('|') + .split(" | ") + .map(|c| c.trim().to_string()) + .collect(); + let id = cells[0].trim_matches('`').to_string(); + ( + id, + cells.get(1).cloned().unwrap_or_default(), + cells.get(2).cloned().unwrap_or_default(), + ) + }) + .collect() +} + +#[test] +fn every_setting_has_an_agent_path_or_a_reason() { + let doc = read("docs/agent-capabilities.md"); + let registry = registry_ids(); + assert!(registry.len() > 40, "found {} settings", registry.len()); + let table = rows(&doc, "## Settings"); + let listed: BTreeSet<String> = table.iter().map(|r| r.0.clone()).collect(); + let missing: Vec<&String> = registry.difference(&listed).collect(); + assert!( + missing.is_empty(), + "settings with no row in docs/agent-capabilities.md (add them as agent or teacher only, with a reason): {missing:?}" + ); + let stale: Vec<&String> = listed.difference(®istry).collect(); + assert!( + stale.is_empty(), + "rows for settings that no longer exist: {stale:?}" + ); + for (id, who, how) in &table { + assert!( + who == "agent" || who == "teacher only", + "{id}: who must be `agent` or `teacher only`, got `{who}`" + ); + assert!(how.len() > 8, "{id}: say how, or why it is teacher only"); + } + let by_set_setting: BTreeSet<String> = table + .iter() + .filter(|(_, who, how)| who == "agent" && how.starts_with("`set_setting`")) + .map(|r| r.0.clone()) + .collect(); + let allow: BTreeSet<String> = quoted_between( + &read("apps/board/src/agentSettings.ts"), + "AGENT_SETTINGS: readonly string[] = [", + "];", + ) + .into_iter() + .collect(); + assert_eq!( + by_set_setting, allow, + "the settings marked `set_setting` in docs/agent-capabilities.md must be exactly AGENT_SETTINGS in agentSettings.ts" + ); + for forbidden in [ + "ai.claudeKey", + "ai.allowEdit", + "ai.chatPermissions", + "general.cloudAccount", + ] { + assert!( + !allow.contains(forbidden), + "{forbidden} must stay teacher only" + ); + } +} + +#[test] +fn every_dock_button_is_listed() { + let doc = read("docs/agent-capabilities.md"); + let modes = read("apps/board/src/modes.ts"); + let start = modes.find("export const TOOLBAR_ITEMS").unwrap(); + let block = &modes[start..start + modes[start..].find("];").unwrap()]; + let mut ids: BTreeSet<String> = block + .split("{ id: \"") + .skip(1) + .map(|p| p[..p.find('"').unwrap()].to_string()) + .collect(); + ids.insert("shapes".into()); + let listed: BTreeSet<String> = rows(&doc, "## Dock buttons") + .into_iter() + .map(|r| r.0) + .collect(); + let missing: Vec<&String> = ids.difference(&listed).collect(); + assert!( + missing.is_empty(), + "dock buttons missing from docs/agent-capabilities.md: {missing:?}" + ); +} + +#[test] +fn every_live_operation_is_in_the_matrix() { + let doc = read("docs/agent-capabilities.md"); + let op = read("crates/rupok-live/src/op.rs"); + let start = op.find("pub fn name(&self)").unwrap(); + let body = &op[start..start + op[start..].find("pub fn access").unwrap()]; + let names: Vec<&str> = body + .split("=> \"") + .skip(1) + .map(|p| &p[..p.find('"').unwrap()]) + .collect(); + assert!(names.len() > 60, "found {} ops", names.len()); + let section = &doc[doc.find("## Live operations").unwrap()..]; + for n in names { + assert!( + section.contains(&format!("`{n}`")), + "live op `{n}` is not in the Live operations table of docs/agent-capabilities.md" + ); + } +} diff --git a/crates/rupok-cli/tests/chat.rs b/crates/rupok-cli/tests/chat.rs index 511185f..eae9f9a 100644 --- a/crates/rupok-cli/tests/chat.rs +++ b/crates/rupok-cli/tests/chat.rs @@ -324,6 +324,36 @@ async fn chat_builds_a_class_on_the_board() { .any(|f| f["update"]["sessionUpdate"] == "plan") ); + // /stamp: custom stamps (SVG with behaviour, a Smart dice), placed, ink + // drawn and restyled, pages copied and reordered, all through MCP. + b.chat.clear(); + b.ops.clear(); + send( + &mut b.ws, + json!({"ch": "chat", "t": "prompt", "text": "/stamp a gold star that sparkles and a dice"}), + ) + .await; + let done = b.until_chat(|f| f["t"] == "done").await; + assert_eq!(done["stop_reason"], "end_turn", "{done} {}", b.text()); + assert_eq!( + b.ops, + [ + "create_stamp", + "create_stamp", + "add_stamp", + "add_stamp", + "draw_stroke", + "restyle_items", + "list_stamps", + "duplicate_pages", + "move_pages" + ] + ); + assert_eq!(b.lesson.stamp_defs().len(), 2); + assert!(b.lesson.stamp_def("dice").is_some()); + assert_eq!(b.lesson.page_count(), 3); + assert!(b.text().contains("Dice"), "{}", b.text()); + // Board context reaches the agent as a resource block. b.chat.clear(); send(&mut b.ws, json!({"ch": "chat", "t": "prompt", "text": "What context did you get?", diff --git a/crates/rupok-cli/tests/fake-acp-agent.mjs b/crates/rupok-cli/tests/fake-acp-agent.mjs index 3761ced..1fa6c84 100644 --- a/crates/rupok-cli/tests/fake-acp-agent.mjs +++ b/crates/rupok-cli/tests/fake-acp-agent.mjs @@ -13,6 +13,10 @@ // selection, points at it, writes a step-by-step // solution with write_handwriting, then explains. // "/review ..." one of its slash commands: answers "Reviewing: …". +// "/stamp ..." makes two custom stamps (an SVG star with a sparkle +// and a counter, a Smart dice that rolls on tap), +// places them, draws and restyles ink, and reorders +// pages, through the agent-control MCP tools. // It also offers Claude-style modes, a model picker (session config option // with category "model", mirrored in the unstable `models` field), slash // commands, usage updates, and session list/load (replaying the chat). @@ -204,6 +208,30 @@ async function solveThis(sid, text) { return "end_turn"; } +const STAR_SVG = '<svg viewBox="0 0 100 100"><path d="M50 6 61 38 95 38 67 58 78 92 50 72 22 92 33 58 5 38 39 38Z" fill="currentColor"/></svg>'; +const DICE_HTML = `<!doctype html><html><head><title>Dice +
⚀
`; + +async function stamps(sid) { + await say(sid, "Making your stamps…\n\n"); + const star = await tool("create_stamp", { name: "Super star", keywords: ["praise"], art: "svg", svg: STAR_SVG, color: "#f5b301", + behavior: { animation: "sparkle", burst: "stars", counter: true, sound: "chime" } }); + const dice = await tool("create_stamp", { id: "dice", name: "Dice", art: "smart", html: DICE_HTML, width: 160, height: 160 }); + const a = await tool("add_stamp", { stamp: star.id, x: 200, y: 200 }); + await tool("add_stamp", { stamp: dice.id, x: 500, y: 200 }); + const s = await tool("draw_stroke", { points: [[100, 600], [400, 650], [700, 600]], brush: "marker" }); + await tool("restyle_items", { item_ids: [s.item_ids[0], a.item_id], color: "#e5484d" }); + await tool("list_stamps", {}); + await tool("duplicate_pages", { pages: [1] }); + await tool("move_pages", { pages: [2], to: 1 }); + await say(sid, `Done: **${star.stamp.name}** sparkles and counts, the **Dice** rolls when tapped. Both are in My stamps.`); + return "end_turn"; +} + async function prompt(params) { const sid = params.sessionId; cancelled = false; @@ -227,6 +255,7 @@ async function prompt(params) { if (all.length > 1 || imgs.length > 1) await say(sid, `\n\nAll context: ${all.join(", ")}; ${imgs.length} picture(s).`); return { stopReason: "end_turn" }; } + if (/^\/stamp/i.test(text)) return { stopReason: await stamps(sid) }; if (/ohm/i.test(text)) return { stopReason: await ohm(sid) }; if (/^\/review\b/.test(text)) { await say(sid, `Reviewing: ${text.slice(7).trim() || "the board"} (model ${model}, mode ${mode}).`); diff --git a/crates/rupok-cli/tests/mcp_e2e.rs b/crates/rupok-cli/tests/mcp_e2e.rs index 324d40a..29cc388 100644 --- a/crates/rupok-cli/tests/mcp_e2e.rs +++ b/crates/rupok-cli/tests/mcp_e2e.rs @@ -231,6 +231,150 @@ fn mcp_server_over_stdio() { "{m}" ); + // ------------------------------------------------ agent control on a file + for expected in [ + "list_pages", + "move_pages", + "delete_pages", + "duplicate_pages", + "select_items", + "move_items", + "align_items", + "restyle_items", + "scale_items", + "group_items", + "bring_to_front", + "send_to_back", + "delete_items", + "draw_stroke", + "update_text", + "list_stamps", + "create_stamp", + "update_stamp", + "delete_stamp", + "add_stamp", + "set_mode", + "zoom_to", + "fit_page", + "start_replay", + "celebrate", + "export_pdf", + "library_list", + "library_open", + "get_settings", + "set_setting", + "get_dock_layout", + "set_dock_layout", + "list_dock_items", + "apply_dock_preset", + ] { + assert!(names.contains(&expected), "missing tool {expected}"); + } + let f = "units/plants.rpk"; + let r = structured(&c.call( + "draw_stroke", + json!({ "path": f, "page": 2, "points": [[100, 100], [400, 300]], "brush": "chalk" }), + )); + let stroke = r["item_ids"][0].as_str().unwrap().to_string(); + let t = structured(&c.call( + "add_text", + json!({ "path": f, "page": 2, "text": "Leaf", "x": 600, "y": 100, "size": 48 }), + )); + let text = t["item_id"].as_str().unwrap().to_string(); + let r = c.call( + "restyle_items", + json!({ "path": f, "page": 2, "item_ids": [stroke, text], "color": "#30a46c" }), + ); + assert_ne!(r["isError"], true, "{r}"); + assert_eq!(structured(&r)["restyled"], 2); + let r = c.call( + "align_items", + json!({ "path": f, "page": 2, "item_ids": [stroke, text], "align": "top" }), + ); + assert_ne!(r["isError"], true, "{r}"); + let r = c.call( + "update_text", + json!({ "path": f, "page": 2, "item_id": text, "text": "Leaf cell" }), + ); + assert_ne!(r["isError"], true, "{r}"); + // a custom SVG stamp with behaviour, and a Smart stamp, placed in the file + let svg = + r#""#; + let st = structured(&c.call( + "create_stamp", + json!({ "path": f, "name": "Sun", "art": "svg", "svg": svg, + "color": "#f5b301", "behavior": { "animation": "sparkle", "counter": true } }), + )); + let sid = st["id"].as_str().unwrap().to_string(); + let r = c.call( + "add_stamp", + json!({ "path": f, "page": 2, "stamp": sid, "x": 800, "y": 400 }), + ); + assert_ne!(r["isError"], true, "{r}"); + let dice = r#"Dice1 +"#; + let r = c.call( + "create_stamp", + json!({ "path": f, "id": "dice", "name": "Dice", "art": "smart", "html": dice }), + ); + assert_ne!(r["isError"], true, "{r}"); + let r = c.call( + "add_stamp", + json!({ "path": f, "page": 2, "stamp": "dice" }), + ); + assert_ne!(r["isError"], true, "{r}"); + let stamps = structured(&c.call("list_stamps", json!({ "path": f }))); + assert_eq!(stamps["custom"].as_array().unwrap().len(), 2); + // unsafe SVG is refused and nothing is saved + let before = std::fs::read(dir.path().join(f)).unwrap(); + let r = c.call( + "create_stamp", + json!({ "path": f, "name": "Bad", "art": "svg", "svg": "" }), + ); + assert_eq!(r["isError"], true); + assert!( + structured(&r)["error"] + .as_str() + .unwrap() + .contains("svg refused") + ); + assert_eq!(std::fs::read(dir.path().join(f)).unwrap(), before); + // pages + let r = structured(&c.call("duplicate_pages", json!({ "path": f, "pages": [2] }))); + assert_eq!(r["copies"], json!([3])); + let r = c.call("move_pages", json!({ "path": f, "pages": [3], "to": 1 })); + assert_ne!(r["isError"], true, "{r}"); + let pages = structured(&c.call("list_pages", json!({ "path": f }))); + assert_eq!(pages["page_count"], 3); + assert_eq!( + pages["pages"][0]["objects"], 1, + "the copy (with the Smart stamp) is first: {pages}" + ); + // board-only tools need the live board + let r = c.call("set_mode", json!({ "mode": "teach" })); + assert_eq!(r["isError"], true); + assert!( + structured(&r)["error"] + .as_str() + .unwrap() + .contains("no board is paired") + ); + // settings that are the teacher's alone never reach the board + let r = c.call( + "set_setting", + json!({ "key": "claudeKey", "value": "sk-x" }), + ); + assert_eq!(r["isError"], true); + assert!( + structured(&r)["error"] + .as_str() + .unwrap() + .contains("teacher's alone") + ); + // the PDF goes in the workspace only + let r = c.call("export_pdf", json!({ "save_as": "../out.pdf" })); + assert_eq!(r["isError"], true); + // list + spec let lessons = structured(&c.call("list_lessons", json!({}))); assert_eq!(lessons["lessons"][0]["title"], "How plants grow"); From b9e4e071f4bbc82888afe2e04d9948155f8d4304 Mon Sep 17 00:00:00 2001 From: shaitrish37 <244331886+shaitrish37@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:00:52 +0600 Subject: [PATCH 3/4] board: custom stamps, a customisable dock, and the agent's board ops - My stamps: the teacher's stamps in IndexedDB and in lessons that use them; a stamp editor (preview, name, artwork, colour, size, animation, burst, sound, fade, counter); stamp packs; Make a stamp with AI (/stamp). Custom SVG is drawn only as an image; Smart stamps run as sandboxed Smart Objects; behaviour plays on placement (sounds honour a new switch). - Smart Dock: ordered groups, a split second dock, button sizes, large icons, per mode; named layouts (Left-handed, Minimal teaching, Maths class, the teacher's own); a Customize dock editor (drag, keyboard, reset), from the dock's menu, a long press on the grip or Settings; Customize dock with AI (/dock). - agentControl.ts runs the board-app ops for agents (modes, view, replay, export, Library, settings allowlist, dock) with Undo from the AI chip. --- apps/board/src/App.tsx | 4 + apps/board/src/agentControl.ts | 370 ++++++++++++++ apps/board/src/agentSettings.ts | 85 ++++ apps/board/src/chatContext.ts | 24 + apps/board/src/components/Dock.css | 13 + apps/board/src/components/Dock.tsx | 185 ++++++- apps/board/src/components/DockEditor.css | 93 ++++ apps/board/src/components/DockEditor.tsx | 532 ++++++++++++++++++++ apps/board/src/components/DockShell.tsx | 43 +- apps/board/src/components/ModesSettings.tsx | 10 +- apps/board/src/components/StampEditor.css | 63 +++ apps/board/src/components/StampEditor.tsx | 252 ++++++++++ apps/board/src/components/Stamps.css | 60 +++ apps/board/src/components/Stamps.tsx | 162 +++++- apps/board/src/controller.ts | 13 + apps/board/src/customStamps.ts | 261 ++++++++++ apps/board/src/dock.ts | 10 + apps/board/src/live.ts | 54 +- apps/board/src/modes.ts | 234 ++++++++- apps/board/src/settings/defs/stamps.tsx | 11 +- apps/board/src/stampLib.ts | 96 ++++ apps/board/src/stamps.ts | 37 +- apps/board/src/state.ts | 10 +- 23 files changed, 2571 insertions(+), 51 deletions(-) create mode 100644 apps/board/src/agentControl.ts create mode 100644 apps/board/src/agentSettings.ts create mode 100644 apps/board/src/components/DockEditor.css create mode 100644 apps/board/src/components/DockEditor.tsx create mode 100644 apps/board/src/components/StampEditor.css create mode 100644 apps/board/src/components/StampEditor.tsx create mode 100644 apps/board/src/customStamps.ts create mode 100644 apps/board/src/stampLib.ts 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()}> +