Skip to main content

byob_protocol/
tree.rs

1//! The view tree (v1): declarative UI that plugins and the model send as JSON and every client
2//! draws natively with its theme (`docs/views.md` is the authoring guide).
3//!
4//! A tree is a [`Node`]: containers (`column`, `row`, `card`) holding leaves (`text`,
5//! `markdown`, `chip`, `button`, `input`, `toggle`, `select`, `progress`, `table`, `chart`,
6//! `separator`, `image`, `canvas`, `grid`). Any node may carry a `key` (patches address it, clients keep
7//! its transient state under it). The user's actions come back as an [`Event`] (an action name
8//! plus the value of every named field, like an HTML form); a plugin answers with a [`Reply`]:
9//! a whole new view, or [`Patch`]es to the current one.
10//!
11//! Trees are untrusted. [`decode`] never fails: it applies the limits ([`MAX_DEPTH`],
12//! [`MAX_NODES`], …), shows a node it doesn't know as its `fallback` text (or leaves it out),
13//! and lists everything it had to fix as [`Fault`]s (a JSON pointer and a sentence) that the
14//! engine can hand back to whoever wrote the tree. [`apply`] applies patches the same way.
15//! [`diff`] turns two trees into patches, so a plugin can always send its whole view and
16//! clients still get small updates.
17//!
18//! On a step, a tree travels as a [`crate::View`] of kind [`KIND`] (`byob.tree`), with a
19//! markdown summary as the fallback for clients that can't draw it.
20
21use std::collections::BTreeMap;
22use std::fmt;
23
24use serde::{Deserialize, Deserializer, Serialize};
25use serde_json::{Map, Value};
26
27pub use byob_types::chart::ChartSpec;
28
29mod decode;
30mod diff;
31mod patch;
32#[cfg(test)]
33mod tests;
34
35pub use decode::{decode, decode_str};
36pub use diff::diff;
37pub use patch::apply;
38
39/// The view kind of a tree on a step.
40pub const KIND: &str = "byob.tree";
41/// Schema version of the tree.
42pub const VERSION: u32 = 1;
43
44/// Deepest nesting (the root is depth 1).
45pub const MAX_DEPTH: usize = 32;
46/// Most nodes in one tree (table rows and canvas shapes aren't nodes).
47pub const MAX_NODES: usize = 20_000;
48/// Longest string anywhere in a node (characters); longer ones are cut.
49pub const MAX_TEXT_CHARS: usize = 64 * 1024;
50/// Longest node key or field name.
51pub const MAX_KEY_CHARS: usize = 128;
52/// Most rows in one table.
53pub const MAX_TABLE_ROWS: usize = 100_000;
54/// Most columns in one table.
55pub const MAX_TABLE_COLUMNS: usize = 64;
56/// Most shapes on one canvas.
57pub const MAX_SHAPES: usize = 20_000;
58/// Most options in one select.
59pub const MAX_OPTIONS: usize = 1_000;
60/// Most patches in one reply.
61pub const MAX_PATCHES: usize = 10_000;
62/// Most named values in an event or reply.
63pub const MAX_VALUES: usize = 1_000;
64/// Most rows in a grid (a spreadsheet's).
65pub const MAX_GRID_ROWS: u32 = 1_048_576;
66/// Most columns in a grid.
67pub const MAX_GRID_COLS: u32 = 16_384;
68/// Most blocks of known cells in one grid.
69pub const MAX_GRID_BLOCKS: usize = 16;
70/// Most cells in all the blocks of one grid.
71pub const MAX_GRID_CELLS: usize = 50_000;
72/// Longest text of one grid cell (shown value or input; characters).
73pub const MAX_CELL_CHARS: usize = 4096;
74/// Most faults reported for one tree or reply (the rest are counted in the last one).
75pub const MAX_FAULTS: usize = 50;
76
77/// One node of a view tree.
78#[derive(Debug, Clone, PartialEq, Serialize)]
79pub struct Node {
80    /// Any string unique in the tree: patches address the node by it, and clients keep its
81    /// state (typed text, scroll, selection) under it across replies.
82    #[serde(default, skip_serializing_if = "Option::is_none")]
83    pub key: Option<String>,
84    #[serde(flatten)]
85    pub kind: Kind,
86}
87
88/// What a node is (`"type"` in JSON).
89#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
90#[serde(tag = "type", rename_all = "snake_case")]
91pub enum Kind {
92    /// Children stacked top to bottom.
93    Column {
94        children: Vec<Node>,
95    },
96    /// Children side by side (wrapping); a row holding cards or columns splits the width
97    /// equally between them.
98    Row {
99        children: Vec<Node>,
100    },
101    /// A framed box with an optional title.
102    Card {
103        #[serde(default, skip_serializing_if = "String::is_empty")]
104        title: String,
105        children: Vec<Node>,
106    },
107    Text {
108        text: String,
109        #[serde(default, skip_serializing_if = "is_default")]
110        style: TextStyle,
111        #[serde(default, skip_serializing_if = "is_default")]
112        tone: Tone,
113    },
114    Markdown {
115        text: String,
116    },
117    /// A small status pill.
118    Chip {
119        text: String,
120        #[serde(default, skip_serializing_if = "is_default")]
121        tone: Tone,
122    },
123    Button {
124        label: String,
125        /// Sent as the event's action.
126        action: String,
127        #[serde(default, skip_serializing_if = "is_false")]
128        primary: bool,
129        #[serde(default, skip_serializing_if = "is_false")]
130        danger: bool,
131    },
132    /// A one-line text field; its text is `values[name]` in every event.
133    Input {
134        name: String,
135        #[serde(default, skip_serializing_if = "String::is_empty")]
136        value: String,
137        #[serde(default, skip_serializing_if = "String::is_empty")]
138        placeholder: String,
139        /// Action sent when Enter is pressed in it.
140        #[serde(default, skip_serializing_if = "Option::is_none")]
141        submit: Option<String>,
142    },
143    /// A checkbox; `values[name]` is a bool.
144    Toggle {
145        name: String,
146        #[serde(default, skip_serializing_if = "String::is_empty")]
147        label: String,
148        #[serde(default, skip_serializing_if = "is_false")]
149        value: bool,
150        /// Action sent when it is flipped.
151        #[serde(default, skip_serializing_if = "Option::is_none")]
152        action: Option<String>,
153    },
154    /// A drop-down; `values[name]` is the chosen option.
155    Select {
156        name: String,
157        options: Vec<String>,
158        #[serde(default, skip_serializing_if = "String::is_empty")]
159        value: String,
160        /// Action sent when the choice changes.
161        #[serde(default, skip_serializing_if = "Option::is_none")]
162        action: Option<String>,
163    },
164    /// A bar, `value` from 0 to 1.
165    Progress {
166        value: f32,
167        #[serde(default, skip_serializing_if = "String::is_empty")]
168        label: String,
169    },
170    /// Rows of cells, drawn virtualized (only what is on screen), with editable columns.
171    Table {
172        /// Names the table in edit events and is `values[name]` (the selected row).
173        #[serde(default, skip_serializing_if = "String::is_empty")]
174        name: String,
175        columns: Vec<TableColumn>,
176        /// Cells in column order: strings, numbers, booleans or null.
177        rows: Vec<Vec<Value>>,
178        /// Tallest the table is drawn (points; it scrolls inside).
179        #[serde(default, skip_serializing_if = "Option::is_none")]
180        height: Option<f32>,
181        /// Action sent when a row is clicked (`values[name]` is its index).
182        #[serde(default, skip_serializing_if = "Option::is_none")]
183        select: Option<String>,
184    },
185    /// A chart: the same spec as `.chart.json` artifacts.
186    Chart {
187        spec: ChartSpec,
188    },
189    Separator {},
190    /// An image from the chat's media (a workspace path) or an artifact.
191    Image {
192        /// A workspace path, as in a media reference.
193        #[serde(default, skip_serializing_if = "Option::is_none")]
194        media: Option<String>,
195        /// An artifact id.
196        #[serde(default, skip_serializing_if = "Option::is_none")]
197        artifact: Option<String>,
198        #[serde(default, skip_serializing_if = "String::is_empty")]
199        alt: String,
200        #[serde(default, skip_serializing_if = "Option::is_none")]
201        width: Option<f32>,
202        #[serde(default, skip_serializing_if = "Option::is_none")]
203        height: Option<f32>,
204    },
205    /// A display list: shapes in a `width` × `height` box (scaled down to fit).
206    Canvas {
207        width: f32,
208        height: f32,
209        shapes: Vec<Shape>,
210        /// Action sent on a click, with the point in `values._x` / `values._y` (canvas units).
211        #[serde(default, skip_serializing_if = "Option::is_none")]
212        action: Option<String>,
213    },
214    /// A spreadsheet: a `rows` × `cols` sheet of which the client has the cells in `blocks`
215    /// and asks for others (a `window` event) as the user scrolls. Its events carry a
216    /// [`GridEvent`]; `values[name]` is the selection (a [`GridRange`]).
217    Grid {
218        /// Names the grid in events and is `values[name]`.
219        #[serde(default, skip_serializing_if = "String::is_empty")]
220        name: String,
221        rows: u32,
222        cols: u32,
223        /// Rectangles of known cells; the rest aren't loaded.
224        #[serde(default, skip_serializing_if = "Vec::is_empty")]
225        blocks: Vec<GridBlock>,
226        /// Data rows (from the top) that stay put while scrolling.
227        #[serde(default, skip_serializing_if = "is_zero_u32")]
228        frozen_rows: u32,
229        /// Data columns (from the left) that stay put while scrolling.
230        #[serde(default, skip_serializing_if = "is_zero_u32")]
231        frozen_cols: u32,
232        /// Column index → width in points.
233        #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
234        widths: BTreeMap<u32, f32>,
235        /// Width of the other columns ([`GRID_DEFAULT_WIDTH`] if not given).
236        #[serde(default, skip_serializing_if = "Option::is_none")]
237        default_width: Option<f32>,
238        /// Cells can be edited, cleared and pasted into.
239        #[serde(default, skip_serializing_if = "is_false")]
240        editable: bool,
241        /// Column letters and row numbers.
242        #[serde(default = "yes", skip_serializing_if = "is_true")]
243        headers: bool,
244        /// Tallest the grid is drawn (points); else the height its site gives.
245        #[serde(default, skip_serializing_if = "Option::is_none")]
246        height: Option<f32>,
247        /// The selection to show (taken when the tree changes it, like a field's value).
248        #[serde(default, skip_serializing_if = "Option::is_none")]
249        selection: Option<GridRange>,
250    },
251}
252
253/// Width of a grid column without its own.
254pub const GRID_DEFAULT_WIDTH: f32 = 90.0;
255
256/// Known cells of a grid: row-major `cells` from (`row`, `col`), 0-based.
257#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
258pub struct GridBlock {
259    pub row: u32,
260    pub col: u32,
261    #[serde(default)]
262    pub cells: Vec<Vec<GridCell>>,
263}
264
265impl GridBlock {
266    /// Rows the block covers.
267    pub fn height(&self) -> u32 {
268        u32::try_from(self.cells.len()).unwrap_or(u32::MAX)
269    }
270
271    /// Columns the block covers (its longest row; a short row's missing cells are empty).
272    pub fn width(&self) -> u32 {
273        u32::try_from(self.cells.iter().map(Vec::len).max().unwrap_or(0)).unwrap_or(u32::MAX)
274    }
275
276    /// Whether (`row`, `col`) of the sheet is in the block.
277    pub fn covers(&self, row: u32, col: u32) -> bool {
278        row >= self.row && col >= self.col && row - self.row < self.height() && col - self.col < self.width()
279    }
280
281    /// The cell at (`row`, `col`) of the sheet: `Some(None)` for an empty cell of the block,
282    /// `None` outside it.
283    pub fn get(&self, row: u32, col: u32) -> Option<Option<&GridCell>> {
284        if row < self.row || col < self.col {
285            return None;
286        }
287        let r = self.cells.get(usize::try_from(row - self.row).ok()?)?;
288        let c = usize::try_from(col - self.col).ok()?;
289        if c >= usize::try_from(self.width()).unwrap_or(0) {
290            return None;
291        }
292        Some(r.get(c))
293    }
294
295    /// Cells in the block.
296    pub fn cell_count(&self) -> usize {
297        self.cells.iter().map(Vec::len).sum()
298    }
299}
300
301/// A rectangle of a grid: the anchor (`row`, `col`, the active cell) and the other corner
302/// (`to_row`, `to_col`).
303#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
304pub struct GridRange {
305    pub row: u32,
306    pub col: u32,
307    pub to_row: u32,
308    pub to_col: u32,
309}
310
311impl GridRange {
312    pub fn cell(row: u32, col: u32) -> Self {
313        Self { row, col, to_row: row, to_col: col }
314    }
315
316    /// Top row, left column, bottom row, right column.
317    pub fn bounds(&self) -> (u32, u32, u32, u32) {
318        (self.row.min(self.to_row), self.col.min(self.to_col), self.row.max(self.to_row), self.col.max(self.to_col))
319    }
320
321    pub fn contains(&self, row: u32, col: u32) -> bool {
322        let (t, l, b, r) = self.bounds();
323        (t..=b).contains(&row) && (l..=r).contains(&col)
324    }
325}
326
327/// What a grid cell holds (`"t"` in JSON: `s`, `n`, `b`, `e`).
328#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
329pub enum CellType {
330    /// Nothing (null).
331    #[default]
332    Empty,
333    Text,
334    Number,
335    Bool,
336    Error,
337}
338
339/// Where a cell's text sits (by default numbers right, booleans centred, the rest left).
340#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
341#[serde(rename_all = "snake_case")]
342pub enum CellAlign {
343    Left,
344    Center,
345    Right,
346}
347
348/// One grid cell. In JSON: null, a string, a number, a bool, or an object `{"v": shown text,
349/// "i": input (a formula), "t": "s"|"n"|"b"|"e", "b": bold, "it": italic, "fill", "color",
350/// "align"}`.
351#[derive(Debug, Clone, Default, PartialEq)]
352pub struct GridCell {
353    /// What the cell shows.
354    pub v: String,
355    /// What editing starts with and the formula bar shows (`=SUM(B2:B9)`), if not `v`.
356    pub i: Option<String>,
357    pub t: CellType,
358    pub bold: bool,
359    pub italic: bool,
360    /// Background: a theme role (`accent`, `chart3`, …) or `#rrggbb`.
361    pub fill: Option<String>,
362    /// Text colour, the same way.
363    pub color: Option<String>,
364    pub align: Option<CellAlign>,
365}
366
367/// Longest colour name of a cell.
368const MAX_COLOR_CHARS: usize = 64;
369
370impl GridCell {
371    pub fn text(v: impl Into<String>) -> Self {
372        Self { v: v.into(), t: CellType::Text, ..Self::default() }
373    }
374
375    /// What editing the cell starts with.
376    pub fn input(&self) -> &str {
377        self.i.as_deref().unwrap_or(&self.v)
378    }
379
380    fn plain(&self) -> bool {
381        self.i.is_none() && !self.bold && !self.italic && self.fill.is_none() && self.color.is_none() && self.align.is_none()
382    }
383
384    /// Decode an untrusted cell (unknown fields ignored); `Err` if it isn't one. Long text is
385    /// cut to [`MAX_CELL_CHARS`] (the bool says so).
386    pub fn decode(v: Value) -> Result<(GridCell, bool), &'static str> {
387        let mut long = false;
388        let mut cut = |s: String| {
389            let (s, l) = cut_chars(s, MAX_CELL_CHARS);
390            long |= l;
391            s
392        };
393        let cell = match v {
394            Value::Null => GridCell::default(),
395            Value::String(s) => GridCell { v: cut(s), t: CellType::Text, ..GridCell::default() },
396            Value::Number(n) => GridCell { v: n.to_string(), t: CellType::Number, ..GridCell::default() },
397            Value::Bool(b) => GridCell { v: bool_text(b).into(), t: CellType::Bool, ..GridCell::default() },
398            Value::Object(mut o) => {
399                let (v, guessed) = match o.remove("v") {
400                    None | Some(Value::Null) => (String::new(), None),
401                    Some(Value::String(s)) => (cut(s), Some(CellType::Text)),
402                    Some(Value::Number(n)) => (n.to_string(), Some(CellType::Number)),
403                    Some(Value::Bool(b)) => (bool_text(b).into(), Some(CellType::Bool)),
404                    Some(other) => (cut(other.to_string()), Some(CellType::Text)),
405                };
406                let t = match o.get("t").and_then(Value::as_str) {
407                    Some("n") => CellType::Number,
408                    Some("b") => CellType::Bool,
409                    Some("e") => CellType::Error,
410                    Some("s") => CellType::Text,
411                    _ => guessed.unwrap_or(CellType::Empty),
412                };
413                let text = |o: &mut Map<String, Value>, k: &str| match o.remove(k) {
414                    Some(Value::String(s)) => Some(s),
415                    Some(Value::Number(n)) => Some(n.to_string()),
416                    _ => None,
417                };
418                let flag = |o: &Map<String, Value>, k: &str| o.get(k).and_then(Value::as_bool).unwrap_or(false);
419                let short = |s: Option<String>| s.map(|s| cut_chars(s, MAX_COLOR_CHARS).0);
420                let i = text(&mut o, "i").map(&mut cut);
421                GridCell {
422                    v,
423                    i,
424                    t,
425                    bold: flag(&o, "b"),
426                    italic: flag(&o, "it"),
427                    fill: short(text(&mut o, "fill")),
428                    color: short(text(&mut o, "color")),
429                    align: match o.get("align").and_then(Value::as_str) {
430                        Some("left") => Some(CellAlign::Left),
431                        Some("center" | "centre") => Some(CellAlign::Center),
432                        Some("right") => Some(CellAlign::Right),
433                        _ => None,
434                    },
435                }
436            }
437            Value::Array(_) => return Err("a cell is null, text, a number, a bool or an object like {\"v\": \"shown\"}"),
438        };
439        Ok((cell, long))
440    }
441}
442
443fn bool_text(b: bool) -> &'static str {
444    if b { "TRUE" } else { "FALSE" }
445}
446
447/// `s` cut to `max` characters; whether it was longer.
448fn cut_chars(mut s: String, max: usize) -> (String, bool) {
449    if s.len() <= max {
450        return (s, false);
451    }
452    match s.char_indices().nth(max) {
453        Some((at, _)) => {
454            s.truncate(at);
455            (s, true)
456        }
457        None => (s, false),
458    }
459}
460
461impl Serialize for GridCell {
462    /// The shortest form that decodes back to the same cell.
463    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
464        use serde::ser::SerializeMap;
465        if self.plain() {
466            match self.t {
467                CellType::Empty if self.v.is_empty() => return s.serialize_none(),
468                CellType::Text => return s.serialize_str(&self.v),
469                CellType::Bool if self.v == "TRUE" || self.v == "FALSE" => return s.serialize_bool(self.v == "TRUE"),
470                CellType::Number => {
471                    if let Ok(n) = self.v.parse::<serde_json::Number>()
472                        && n.to_string() == self.v
473                    {
474                        return n.serialize(s);
475                    }
476                }
477                _ => {}
478            }
479        }
480        let mut m = s.serialize_map(None)?;
481        // Without "v" and "t" an object is an empty cell; with "v" and without "t", text.
482        let t = match self.t {
483            CellType::Empty if self.v.is_empty() => None,
484            CellType::Empty => Some(""),
485            CellType::Text => None,
486            CellType::Number => Some("n"),
487            CellType::Bool => Some("b"),
488            CellType::Error => Some("e"),
489        };
490        if self.t != CellType::Empty || !self.v.is_empty() {
491            m.serialize_entry("v", &self.v)?;
492        }
493        if let Some(t) = t {
494            m.serialize_entry("t", t)?;
495        }
496        if let Some(i) = &self.i {
497            m.serialize_entry("i", i)?;
498        }
499        if self.bold {
500            m.serialize_entry("b", &true)?;
501        }
502        if self.italic {
503            m.serialize_entry("it", &true)?;
504        }
505        if let Some(c) = &self.fill {
506            m.serialize_entry("fill", c)?;
507        }
508        if let Some(c) = &self.color {
509            m.serialize_entry("color", c)?;
510        }
511        if let Some(a) = &self.align {
512            m.serialize_entry("align", a)?;
513        }
514        m.end()
515    }
516}
517
518impl<'de> Deserialize<'de> for GridCell {
519    /// Leniently: what isn't a cell is an empty one.
520    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
521        Ok(GridCell::decode(Value::deserialize(d)?).map(|c| c.0).unwrap_or_default())
522    }
523}
524
525/// A grid column's name: `A`…`Z`, `AA`…
526pub fn column_name(col: u32) -> String {
527    let mut n = u64::from(col) + 1;
528    let mut out = Vec::new();
529    while n > 0 {
530        let rem = u8::try_from((n - 1) % 26).unwrap_or(0);
531        out.push(char::from(b'A' + rem));
532        n = (n - 1) / 26;
533    }
534    out.iter().rev().collect()
535}
536
537/// A cell's name (`B3`) from 0-based indices.
538pub fn cell_name(row: u32, col: u32) -> String {
539    format!("{}{}", column_name(col), u64::from(row) + 1)
540}
541
542/// A colour role, not a colour: clients map it to their theme. Unknown names (a newer tone)
543/// are [`Tone::Normal`].
544#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize)]
545#[serde(rename_all = "snake_case")]
546pub enum Tone {
547    #[default]
548    Normal,
549    Dim,
550    Accent,
551    Success,
552    Warning,
553    Danger,
554}
555
556/// Unknown names (a newer style) are [`TextStyle::Body`].
557#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize)]
558#[serde(rename_all = "snake_case")]
559pub enum TextStyle {
560    #[default]
561    Body,
562    Heading,
563    Strong,
564    Small,
565    Mono,
566}
567
568/// Deserialize an enum by name, unknown names (or non-strings) as the default.
569macro_rules! lenient_names {
570    ($t:ty { $($name:literal => $v:expr),* $(,)? }) => {
571        impl<'de> Deserialize<'de> for $t {
572            fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
573                Ok(match Value::deserialize(d)?.as_str() {
574                    $(Some($name) => $v,)*
575                    _ => <$t>::default(),
576                })
577            }
578        }
579    };
580}
581
582lenient_names!(Tone { "dim" => Tone::Dim, "accent" => Tone::Accent, "success" => Tone::Success, "warning" => Tone::Warning, "danger" => Tone::Danger });
583lenient_names!(TextStyle { "heading" => TextStyle::Heading, "strong" => TextStyle::Strong, "small" => TextStyle::Small, "mono" => TextStyle::Mono });
584
585/// A table column.
586#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
587pub struct TableColumn {
588    /// Names the column in edit events.
589    pub key: String,
590    /// The header (the key if empty).
591    #[serde(default, skip_serializing_if = "String::is_empty")]
592    pub label: String,
593    /// Points; columns without one share the width left.
594    #[serde(default, skip_serializing_if = "Option::is_none")]
595    pub width: Option<f32>,
596    /// Double-clicking a cell edits it and sends an `edit` event.
597    #[serde(default, skip_serializing_if = "is_false")]
598    pub editable: bool,
599}
600
601impl TableColumn {
602    pub fn header(&self) -> &str {
603        if self.label.is_empty() { &self.key } else { &self.label }
604    }
605}
606
607/// One canvas shape (`"type"` in JSON). Colours are theme role names (`accent`, `text_dim`,
608/// `border`, …), `chart1`…`chart8`, or `#rrggbb`.
609#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
610#[serde(tag = "type", rename_all = "snake_case")]
611pub enum Shape {
612    Rect {
613        x: f32,
614        y: f32,
615        w: f32,
616        h: f32,
617        #[serde(default, skip_serializing_if = "Option::is_none")]
618        fill: Option<String>,
619        #[serde(default, skip_serializing_if = "Option::is_none")]
620        stroke: Option<String>,
621        #[serde(default, skip_serializing_if = "is_zero")]
622        radius: f32,
623    },
624    Circle {
625        x: f32,
626        y: f32,
627        r: f32,
628        #[serde(default, skip_serializing_if = "Option::is_none")]
629        fill: Option<String>,
630        #[serde(default, skip_serializing_if = "Option::is_none")]
631        stroke: Option<String>,
632    },
633    Line {
634        points: Vec<[f32; 2]>,
635        #[serde(default, skip_serializing_if = "Option::is_none")]
636        stroke: Option<String>,
637        #[serde(default = "one", skip_serializing_if = "is_one")]
638        width: f32,
639    },
640    Text {
641        x: f32,
642        y: f32,
643        text: String,
644        #[serde(default, skip_serializing_if = "Option::is_none")]
645        color: Option<String>,
646        #[serde(default = "fourteen", skip_serializing_if = "is_fourteen")]
647        size: f32,
648    },
649}
650
651fn is_default<T: Default + PartialEq>(v: &T) -> bool {
652    *v == T::default()
653}
654fn is_false(b: &bool) -> bool {
655    !*b
656}
657fn is_zero_u32(v: &u32) -> bool {
658    *v == 0
659}
660fn yes() -> bool {
661    true
662}
663fn is_true(b: &bool) -> bool {
664    *b
665}
666fn is_zero(v: &f32) -> bool {
667    *v == 0.0
668}
669fn one() -> f32 {
670    1.0
671}
672fn is_one(v: &f32) -> bool {
673    *v == 1.0
674}
675fn fourteen() -> f32 {
676    14.0
677}
678fn is_fourteen(v: &f32) -> bool {
679    *v == 14.0
680}
681
682impl Node {
683    pub fn new(kind: Kind) -> Self {
684        Self { key: None, kind }
685    }
686
687    pub fn keyed(key: impl Into<String>, kind: Kind) -> Self {
688        Self { key: Some(key.into()), kind }
689    }
690
691    /// The `"type"` name.
692    pub fn type_name(&self) -> &'static str {
693        self.kind.type_name()
694    }
695
696    pub fn children(&self) -> &[Node] {
697        match &self.kind {
698            Kind::Column { children } | Kind::Row { children } | Kind::Card { children, .. } => children,
699            _ => &[],
700        }
701    }
702
703    pub fn children_mut(&mut self) -> Option<&mut Vec<Node>> {
704        match &mut self.kind {
705            Kind::Column { children } | Kind::Row { children } | Kind::Card { children, .. } => Some(children),
706            _ => None,
707        }
708    }
709
710    /// Nodes in this subtree, itself included.
711    pub fn count(&self) -> usize {
712        1 + self.children().iter().map(Node::count).sum::<usize>()
713    }
714
715    /// Levels in this subtree (a leaf is 1).
716    pub fn depth(&self) -> usize {
717        1 + self.children().iter().map(Node::depth).max().unwrap_or(0)
718    }
719
720    /// The node with `key` in this subtree.
721    pub fn find(&self, key: &str) -> Option<&Node> {
722        if self.key.as_deref() == Some(key) {
723            return Some(self);
724        }
725        self.children().iter().find_map(|c| c.find(key))
726    }
727
728    /// Markdown for a client that can't draw trees: the texts, titles and tables, without
729    /// the controls.
730    pub fn fallback_markdown(&self) -> String {
731        let mut out = String::new();
732        fallback(self, &mut out);
733        let out = out.trim().to_owned();
734        match out.char_indices().nth(crate::view::MAX_VIEW_FALLBACK_CHARS - 1) {
735            Some((at, _)) => format!("{}…", out.get(..at).unwrap_or_default()),
736            None => out,
737        }
738    }
739
740    /// This tree as a step view.
741    pub fn to_view(&self) -> crate::View {
742        crate::View::of(self)
743    }
744}
745
746impl Kind {
747    pub fn type_name(&self) -> &'static str {
748        match self {
749            Kind::Column { .. } => "column",
750            Kind::Row { .. } => "row",
751            Kind::Card { .. } => "card",
752            Kind::Text { .. } => "text",
753            Kind::Markdown { .. } => "markdown",
754            Kind::Chip { .. } => "chip",
755            Kind::Button { .. } => "button",
756            Kind::Input { .. } => "input",
757            Kind::Toggle { .. } => "toggle",
758            Kind::Select { .. } => "select",
759            Kind::Progress { .. } => "progress",
760            Kind::Table { .. } => "table",
761            Kind::Chart { .. } => "chart",
762            Kind::Separator {} => "separator",
763            Kind::Image { .. } => "image",
764            Kind::Canvas { .. } => "canvas",
765            Kind::Grid { .. } => "grid",
766        }
767    }
768}
769
770/// Rows of a table shown in a fallback.
771const FALLBACK_ROWS: usize = 20;
772/// Columns of a grid shown in a fallback.
773const FALLBACK_COLS: u32 = 12;
774
775fn fallback(n: &Node, out: &mut String) {
776    let cell = |v: &Value| cell_text(v).replace('|', "\\|").replace('\n', " ");
777    match &n.kind {
778        Kind::Column { children } | Kind::Row { children } => children.iter().for_each(|c| fallback(c, out)),
779        Kind::Card { title, children } => {
780            if !title.is_empty() {
781                out.push_str(&format!("\n**{title}**\n\n"));
782            }
783            children.iter().for_each(|c| fallback(c, out));
784        }
785        Kind::Text { text, style: TextStyle::Heading, .. } => out.push_str(&format!("\n**{text}**\n\n")),
786        Kind::Text { text, .. } | Kind::Markdown { text } => out.push_str(&format!("{text}\n\n")),
787        Kind::Chip { text, .. } => out.push_str(&format!("`{text}` ")),
788        Kind::Progress { value, label } => out.push_str(&format!("{label} ({:.0}%)\n\n", value.clamp(0.0, 1.0) * 100.0)),
789        Kind::Chart { spec } => out.push_str(&format!("*Chart: {}*\n\n", spec.title)),
790        Kind::Image { alt, .. } if !alt.is_empty() => out.push_str(&format!("*Image: {alt}*\n\n")),
791        Kind::Table { columns, rows, .. } if !columns.is_empty() => {
792            out.push_str(&format!("\n| {} |\n", columns.iter().map(|c| c.header().replace('|', "\\|")).collect::<Vec<_>>().join(" | ")));
793            out.push_str(&format!("|{}\n", " --- |".repeat(columns.len())));
794            for row in rows.iter().take(FALLBACK_ROWS) {
795                let cells: Vec<String> = (0..columns.len()).map(|i| row.get(i).map(cell).unwrap_or_default()).collect();
796                out.push_str(&format!("| {} |\n", cells.join(" | ")));
797            }
798            if rows.len() > FALLBACK_ROWS {
799                out.push_str(&format!("\n*… {} more rows*\n", rows.len() - FALLBACK_ROWS));
800            }
801            out.push('\n');
802        }
803        Kind::Grid { blocks, rows, cols, .. } => {
804            let size = format!("*Grid: {rows} × {cols}*\n");
805            let Some(b) = blocks.first().filter(|b| b.height() > 0 && b.width() > 0) else {
806                out.push_str(&size);
807                out.push('\n');
808                return;
809            };
810            let esc = |s: &str| s.replace('|', "\\|").replace('\n', " ");
811            let ncols = b.width().min(FALLBACK_COLS);
812            let letters: Vec<String> = (0..ncols).map(|c| column_name(b.col.saturating_add(c))).collect();
813            out.push_str(&format!("\n|   | {} |\n", letters.join(" | ")));
814            out.push_str(&format!("|{}\n", " --- |".repeat(letters.len() + 1)));
815            for (r, row) in (0u64..).zip(b.cells.iter().take(FALLBACK_ROWS)) {
816                let cells: Vec<String> = (0..letters.len()).map(|c| row.get(c).map(|c| esc(&c.v)).unwrap_or_default()).collect();
817                out.push_str(&format!("| {} | {} |\n", u64::from(b.row) + r + 1, cells.join(" | ")));
818            }
819            out.push('\n');
820            out.push_str(&size);
821            out.push('\n');
822        }
823        _ => {}
824    }
825}
826
827/// A table cell as text: strings as they are, null empty, anything else as JSON.
828pub fn cell_text(v: &Value) -> String {
829    match v {
830        Value::String(s) => s.clone(),
831        Value::Null => String::new(),
832        other => other.to_string(),
833    }
834}
835
836impl<'de> Deserialize<'de> for Node {
837    /// Decodes like [`decode`], dropping the faults.
838    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
839        Ok(decode(Value::deserialize(d)?).0)
840    }
841}
842
843impl crate::ViewData for Node {
844    const KIND: &'static str = KIND;
845    const V: u32 = VERSION;
846    fn fallback(&self) -> String {
847        self.fallback_markdown()
848    }
849}
850
851/// Something wrong with a tree, a patch or a reply, for whoever sent it.
852#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
853pub struct Fault {
854    /// JSON pointer into what was sent (`/children/2/action`; `/patch/0/...` in a reply).
855    pub path: String,
856    pub message: String,
857}
858
859impl fmt::Display for Fault {
860    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
861        let path = if self.path.is_empty() { "/" } else { &self.path };
862        write!(f, "{path}: {}", self.message)
863    }
864}
865
866impl Fault {
867    pub fn new(path: impl Into<String>, message: impl Into<String>) -> Self {
868        Self { path: path.into(), message: message.into() }
869    }
870
871    /// Faults as lines for the model ("/children/1: unknown node type \"slider\"").
872    pub fn report(faults: &[Fault]) -> String {
873        faults.iter().map(Fault::to_string).collect::<Vec<_>>().join("\n")
874    }
875}
876
877/// What the user did, for the tree's owner.
878#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
879pub struct Event {
880    /// The button's `action`, an input's `submit`, `"edit"` for a cell edit, …
881    pub action: String,
882    /// The current value of every named field (input text, toggle bool, select option,
883    /// table selection), plus `_x`/`_y` for a canvas click.
884    #[serde(default)]
885    pub values: Map<String, Value>,
886    #[serde(default, skip_serializing_if = "Option::is_none")]
887    pub edit: Option<CellEdit>,
888    /// What happened in a grid (the action is its op).
889    #[serde(default, skip_serializing_if = "Option::is_none")]
890    pub grid: Option<GridEvent>,
891}
892
893/// Something the user did in a grid. `op` (also the event's action) is `edit` (`value` typed
894/// into `row`, `col`), `select` (the selection changed: `to_row`, `to_col` is the other
895/// corner), `window` (the client wants the cells of `rows` × `cols` from `row`, `col`),
896/// `paste` (`text`, tab-separated, at `row`, `col`) or `clear` (the cells to `to_row`,
897/// `to_col`).
898#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
899pub struct GridEvent {
900    /// The grid's `name`.
901    pub name: String,
902    pub op: String,
903    pub row: u32,
904    pub col: u32,
905    #[serde(default, skip_serializing_if = "Option::is_none")]
906    pub to_row: Option<u32>,
907    #[serde(default, skip_serializing_if = "Option::is_none")]
908    pub to_col: Option<u32>,
909    #[serde(default, skip_serializing_if = "Option::is_none")]
910    pub rows: Option<u32>,
911    #[serde(default, skip_serializing_if = "Option::is_none")]
912    pub cols: Option<u32>,
913    /// What was typed (always text; `=…` is a formula, the owner works it out).
914    #[serde(default, skip_serializing_if = "Option::is_none")]
915    pub value: Option<String>,
916    /// Pasted text.
917    #[serde(default, skip_serializing_if = "Option::is_none")]
918    pub text: Option<String>,
919}
920
921/// A table cell the user edited.
922#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
923pub struct CellEdit {
924    pub table: String,
925    pub row: usize,
926    /// The column's key.
927    pub column: String,
928    /// What was typed (always text: convert it yourself).
929    pub value: String,
930}
931
932/// A plugin's answer to an event: a whole new `view`, or patches to the current one; both
933/// may be empty. `values` overrides what the user typed (e.g. `{"new": ""}` clears an input
934/// after Add): a reply never changes a field's text otherwise, unless its `value` changed.
935#[derive(Debug, Clone, Default, PartialEq, Serialize)]
936pub struct Reply {
937    #[serde(default, skip_serializing_if = "Option::is_none")]
938    pub view: Option<Node>,
939    #[serde(default, skip_serializing_if = "Vec::is_empty")]
940    pub patch: Vec<Patch>,
941    #[serde(default, skip_serializing_if = "Map::is_empty")]
942    pub values: Map<String, Value>,
943}
944
945impl Reply {
946    /// Decode an untrusted reply line; faults say what was dropped. Only text that isn't a
947    /// JSON object fails.
948    pub fn parse(line: &str) -> Result<(Reply, Vec<Fault>), Fault> {
949        let v: Value = serde_json::from_str(line).map_err(|e| Fault::new("", format!("not JSON: {e}")))?;
950        if !v.is_object() {
951            return Err(Fault::new("", "a reply must be a JSON object like {\"view\": {...}} or {\"patch\": [...]}"));
952        }
953        Ok(decode::reply(v))
954    }
955
956    /// Apply to `tree`: the new view (if any), then the patches.
957    pub fn apply_to(self, tree: &mut Node) -> Vec<Fault> {
958        if let Some(view) = self.view {
959            *tree = view;
960        }
961        apply(tree, self.patch)
962    }
963}
964
965impl<'de> Deserialize<'de> for Reply {
966    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
967        Ok(decode::reply(Value::deserialize(d)?).0)
968    }
969}
970
971/// Which node a patch is for: by `key`, or by `path`, a JSON pointer through `children`
972/// (`""` is the root, `/children/0/children/2`).
973#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
974pub struct Target {
975    #[serde(default, skip_serializing_if = "Option::is_none")]
976    pub key: Option<String>,
977    #[serde(default, skip_serializing_if = "Option::is_none")]
978    pub path: Option<String>,
979}
980
981impl Target {
982    pub fn key(k: impl Into<String>) -> Self {
983        Self { key: Some(k.into()), path: None }
984    }
985    pub fn path(p: impl Into<String>) -> Self {
986        Self { key: None, path: Some(p.into()) }
987    }
988}
989
990/// One change to a tree. In JSON each is an object with one field naming the operation:
991/// `{"set": {"key": "count", "fields": {"text": "3 left"}}}`.
992#[derive(Debug, Clone, PartialEq, Serialize)]
993#[serde(rename_all = "snake_case")]
994pub enum Patch {
995    /// Replace whatever is at a JSON pointer into the tree as JSON: a node
996    /// (`/children/1`), one field (`/children/1/text`), a table row or cell
997    /// (`/children/0/rows/7/2`). This is what [`diff`] makes.
998    Put { path: String, value: Value },
999    /// Replace the node.
1000    Replace {
1001        #[serde(flatten)]
1002        at: Target,
1003        node: Node,
1004    },
1005    /// Change some fields of the node (`{"text": "3 left", "tone": "success"}`).
1006    Set {
1007        #[serde(flatten)]
1008        at: Target,
1009        fields: Map<String, Value>,
1010    },
1011    /// Add children to the end of a container.
1012    Append {
1013        #[serde(flatten)]
1014        at: Target,
1015        nodes: Vec<Node>,
1016    },
1017    /// Remove the node.
1018    Remove {
1019        #[serde(flatten)]
1020        at: Target,
1021    },
1022    /// Write table rows `start..start + rows.len()` (growing the table as needed), then cut
1023    /// or grow it to `len` rows if given.
1024    Rows {
1025        #[serde(flatten)]
1026        at: Target,
1027        start: usize,
1028        #[serde(default)]
1029        rows: Vec<Vec<Value>>,
1030        #[serde(default, skip_serializing_if = "Option::is_none")]
1031        len: Option<usize>,
1032    },
1033}
1034
1035impl<'de> Deserialize<'de> for Patch {
1036    /// Decodes like a reply's patch list; a patch that doesn't decode is an error here.
1037    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
1038        let mut dec = decode::Decoder::default();
1039        let patch = dec.patch(Value::deserialize(d)?, &mut String::new());
1040        patch.ok_or_else(|| serde::de::Error::custom(Fault::report(&dec.finish())))
1041    }
1042}
1043
1044/// JSON pointer escaping of one segment.
1045pub fn pointer_segment(s: &str) -> String {
1046    s.replace('~', "~0").replace('/', "~1")
1047}
1048
1049/// The segments of a JSON pointer (`""` → none); `None` if it isn't one.
1050pub fn pointer_segments(p: &str) -> Option<Vec<String>> {
1051    if p.is_empty() {
1052        return Some(Vec::new());
1053    }
1054    let rest = p.strip_prefix('/')?;
1055    Some(rest.split('/').map(|s| s.replace("~1", "/").replace("~0", "~")).collect())
1056}