1use 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
39pub const KIND: &str = "byob.tree";
41pub const VERSION: u32 = 1;
43
44pub const MAX_DEPTH: usize = 32;
46pub const MAX_NODES: usize = 20_000;
48pub const MAX_TEXT_CHARS: usize = 64 * 1024;
50pub const MAX_KEY_CHARS: usize = 128;
52pub const MAX_TABLE_ROWS: usize = 100_000;
54pub const MAX_TABLE_COLUMNS: usize = 64;
56pub const MAX_SHAPES: usize = 20_000;
58pub const MAX_OPTIONS: usize = 1_000;
60pub const MAX_PATCHES: usize = 10_000;
62pub const MAX_VALUES: usize = 1_000;
64pub const MAX_GRID_ROWS: u32 = 1_048_576;
66pub const MAX_GRID_COLS: u32 = 16_384;
68pub const MAX_GRID_BLOCKS: usize = 16;
70pub const MAX_GRID_CELLS: usize = 50_000;
72pub const MAX_CELL_CHARS: usize = 4096;
74pub const MAX_FAULTS: usize = 50;
76
77#[derive(Debug, Clone, PartialEq, Serialize)]
79pub struct Node {
80 #[serde(default, skip_serializing_if = "Option::is_none")]
83 pub key: Option<String>,
84 #[serde(flatten)]
85 pub kind: Kind,
86}
87
88#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
90#[serde(tag = "type", rename_all = "snake_case")]
91pub enum Kind {
92 Column {
94 children: Vec<Node>,
95 },
96 Row {
99 children: Vec<Node>,
100 },
101 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 Chip {
119 text: String,
120 #[serde(default, skip_serializing_if = "is_default")]
121 tone: Tone,
122 },
123 Button {
124 label: String,
125 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 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 #[serde(default, skip_serializing_if = "Option::is_none")]
141 submit: Option<String>,
142 },
143 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 #[serde(default, skip_serializing_if = "Option::is_none")]
152 action: Option<String>,
153 },
154 Select {
156 name: String,
157 options: Vec<String>,
158 #[serde(default, skip_serializing_if = "String::is_empty")]
159 value: String,
160 #[serde(default, skip_serializing_if = "Option::is_none")]
162 action: Option<String>,
163 },
164 Progress {
166 value: f32,
167 #[serde(default, skip_serializing_if = "String::is_empty")]
168 label: String,
169 },
170 Table {
172 #[serde(default, skip_serializing_if = "String::is_empty")]
174 name: String,
175 columns: Vec<TableColumn>,
176 rows: Vec<Vec<Value>>,
178 #[serde(default, skip_serializing_if = "Option::is_none")]
180 height: Option<f32>,
181 #[serde(default, skip_serializing_if = "Option::is_none")]
183 select: Option<String>,
184 },
185 Chart {
187 spec: ChartSpec,
188 },
189 Separator {},
190 Image {
192 #[serde(default, skip_serializing_if = "Option::is_none")]
194 media: Option<String>,
195 #[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 Canvas {
207 width: f32,
208 height: f32,
209 shapes: Vec<Shape>,
210 #[serde(default, skip_serializing_if = "Option::is_none")]
212 action: Option<String>,
213 },
214 Grid {
218 #[serde(default, skip_serializing_if = "String::is_empty")]
220 name: String,
221 rows: u32,
222 cols: u32,
223 #[serde(default, skip_serializing_if = "Vec::is_empty")]
225 blocks: Vec<GridBlock>,
226 #[serde(default, skip_serializing_if = "is_zero_u32")]
228 frozen_rows: u32,
229 #[serde(default, skip_serializing_if = "is_zero_u32")]
231 frozen_cols: u32,
232 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
234 widths: BTreeMap<u32, f32>,
235 #[serde(default, skip_serializing_if = "Option::is_none")]
237 default_width: Option<f32>,
238 #[serde(default, skip_serializing_if = "is_false")]
240 editable: bool,
241 #[serde(default = "yes", skip_serializing_if = "is_true")]
243 headers: bool,
244 #[serde(default, skip_serializing_if = "Option::is_none")]
246 height: Option<f32>,
247 #[serde(default, skip_serializing_if = "Option::is_none")]
249 selection: Option<GridRange>,
250 },
251}
252
253pub const GRID_DEFAULT_WIDTH: f32 = 90.0;
255
256#[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 pub fn height(&self) -> u32 {
268 u32::try_from(self.cells.len()).unwrap_or(u32::MAX)
269 }
270
271 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 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 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 pub fn cell_count(&self) -> usize {
297 self.cells.iter().map(Vec::len).sum()
298 }
299}
300
301#[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 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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
329pub enum CellType {
330 #[default]
332 Empty,
333 Text,
334 Number,
335 Bool,
336 Error,
337}
338
339#[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#[derive(Debug, Clone, Default, PartialEq)]
352pub struct GridCell {
353 pub v: String,
355 pub i: Option<String>,
357 pub t: CellType,
358 pub bold: bool,
359 pub italic: bool,
360 pub fill: Option<String>,
362 pub color: Option<String>,
364 pub align: Option<CellAlign>,
365}
366
367const 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 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 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
447fn 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 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 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 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
525pub 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
537pub fn cell_name(row: u32, col: u32) -> String {
539 format!("{}{}", column_name(col), u64::from(row) + 1)
540}
541
542#[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#[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
568macro_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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
587pub struct TableColumn {
588 pub key: String,
590 #[serde(default, skip_serializing_if = "String::is_empty")]
592 pub label: String,
593 #[serde(default, skip_serializing_if = "Option::is_none")]
595 pub width: Option<f32>,
596 #[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#[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 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 pub fn count(&self) -> usize {
712 1 + self.children().iter().map(Node::count).sum::<usize>()
713 }
714
715 pub fn depth(&self) -> usize {
717 1 + self.children().iter().map(Node::depth).max().unwrap_or(0)
718 }
719
720 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 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 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
770const FALLBACK_ROWS: usize = 20;
772const 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
827pub 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 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
853pub struct Fault {
854 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 pub fn report(faults: &[Fault]) -> String {
873 faults.iter().map(Fault::to_string).collect::<Vec<_>>().join("\n")
874 }
875}
876
877#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
879pub struct Event {
880 pub action: String,
882 #[serde(default)]
885 pub values: Map<String, Value>,
886 #[serde(default, skip_serializing_if = "Option::is_none")]
887 pub edit: Option<CellEdit>,
888 #[serde(default, skip_serializing_if = "Option::is_none")]
890 pub grid: Option<GridEvent>,
891}
892
893#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
899pub struct GridEvent {
900 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 #[serde(default, skip_serializing_if = "Option::is_none")]
915 pub value: Option<String>,
916 #[serde(default, skip_serializing_if = "Option::is_none")]
918 pub text: Option<String>,
919}
920
921#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
923pub struct CellEdit {
924 pub table: String,
925 pub row: usize,
926 pub column: String,
928 pub value: String,
930}
931
932#[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 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 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#[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#[derive(Debug, Clone, PartialEq, Serialize)]
993#[serde(rename_all = "snake_case")]
994pub enum Patch {
995 Put { path: String, value: Value },
999 Replace {
1001 #[serde(flatten)]
1002 at: Target,
1003 node: Node,
1004 },
1005 Set {
1007 #[serde(flatten)]
1008 at: Target,
1009 fields: Map<String, Value>,
1010 },
1011 Append {
1013 #[serde(flatten)]
1014 at: Target,
1015 nodes: Vec<Node>,
1016 },
1017 Remove {
1019 #[serde(flatten)]
1020 at: Target,
1021 },
1022 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 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
1044pub fn pointer_segment(s: &str) -> String {
1046 s.replace('~', "~0").replace('/', "~1")
1047}
1048
1049pub 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}