1use std::cmp::Ordering;
16use std::hash::{Hash, Hasher};
17use std::marker::PhantomData;
18
19use serde::{Deserialize, Serialize};
20
21use crate::collection::Id;
22use crate::model::Model;
23pub use crate::upsert::At;
24
25#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
27#[serde(rename_all = "kebab-case")]
28pub enum Segment {
29 Field(String),
31 Item(Id),
34 Key(String),
36 Cell { row: Id, column: Id },
38}
39
40impl std::fmt::Display for Segment {
41 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42 match self {
43 Self::Field(key) | Self::Key(key) => f.write_str(key),
44 Self::Item(id) => write!(f, "{id}"),
45 Self::Cell { row, column } => write!(f, "{row}:{column}"),
46 }
47 }
48}
49
50pub struct Path<R, T> {
52 segments: Vec<Segment>,
53 marker: PhantomData<fn() -> (R, T)>,
54}
55
56#[allow(
57 clippy::mismatching_type_param_order,
58 reason = "the root is the record seen as a value of itself"
59)]
60impl<R> Path<R, R> {
61 #[must_use]
63 pub const fn root() -> Self {
64 Self {
65 segments: Vec::new(),
66 marker: PhantomData,
67 }
68 }
69}
70
71impl<R: Model, T> Path<R, T> {
72 #[must_use]
77 pub fn object(&self, doc: &crate::Doc) -> Option<automerge::ObjId> {
78 object_at(R::SHAPE, &self.segments, doc)
79 }
80}
81
82fn object_at(
84 shape: crate::Shape,
85 segments: &[Segment],
86 doc: &crate::Doc,
87) -> Option<automerge::ObjId> {
88 use crate::Shape;
89 use automerge::ReadDoc;
90 fn child(doc: &crate::Doc, obj: &automerge::ObjId, key: &str) -> Option<automerge::ObjId> {
91 match doc.get(obj, key).ok()?? {
92 (automerge::Value::Object(_), id) => Some(id),
93 (automerge::Value::Scalar(_), _) => None,
94 }
95 }
96 let mut obj = automerge::ROOT;
97 let mut shape = shape;
98 for segment in segments {
99 match (shape, segment) {
100 (Shape::Record(fields), Segment::Field(key)) => {
101 shape = fields
102 .iter()
103 .find(|field| field.key == key)
104 .map_or(Shape::Value, |field| field.shape);
105 obj = child(doc, &obj, key)?;
106 }
107 (Shape::Collection(item), Segment::Item(id)) => {
108 let entry = child(doc, &obj, id.as_str())?;
109 obj = child(doc, &entry, crate::collection::VALUE)?;
110 shape = *item;
111 }
112 (Shape::Keyed(item), Segment::Item(id)) => {
113 obj = child(doc, &obj, id.as_str())?;
114 shape = *item;
115 }
116 (_, Segment::Field(key) | Segment::Key(key)) => {
117 obj = child(doc, &obj, key)?;
118 shape = Shape::Value;
119 }
120 (_, Segment::Item(id)) => {
121 obj = child(doc, &obj, id.as_str())?;
122 shape = Shape::Value;
123 }
124 (_, Segment::Cell { .. }) => return None,
125 }
126 }
127 Some(obj)
128}
129
130impl<R, T> Path<R, T> {
131 #[must_use]
134 pub fn from_segments(segments: Vec<Segment>) -> Self {
135 Self {
136 segments,
137 marker: PhantomData,
138 }
139 }
140
141 pub fn segments(&self) -> &[Segment] {
142 &self.segments
143 }
144
145 #[must_use]
146 pub fn into_segments(self) -> Vec<Segment> {
147 self.segments
148 }
149
150 #[doc(hidden)]
152 #[must_use]
153 #[inline]
154 pub fn child<U>(&self, segment: Segment) -> Path<R, U> {
155 Path::from_segments(extended(&self.segments, segment))
156 }
157
158 #[doc(hidden)]
161 #[must_use]
162 pub fn cast<U>(self) -> Path<R, U> {
163 Path::from_segments(self.segments)
164 }
165
166 #[must_use]
169 pub fn under<P>(&self, prefix: &Path<P, R>) -> Path<P, T> {
170 let mut segments = prefix.segments.clone();
171 segments.extend(self.segments.iter().cloned());
172 Path::from_segments(segments)
173 }
174
175 pub fn get<'a>(&self, root: &'a R) -> Option<&'a T>
177 where
178 R: Model + 'static,
179 T: 'static,
180 {
181 root.get_at(&self.segments)?.downcast_ref()
182 }
183
184 pub fn starts_with<U>(&self, other: &Path<R, U>) -> bool {
186 self.segments.starts_with(&other.segments)
187 }
188
189 #[must_use]
193 pub fn edits(&self, before: &T, after: &T) -> Vec<Edit<R>>
194 where
195 T: Model,
196 {
197 let mut found: Vec<Edit<()>> = Vec::new();
198 before.diff(after, &self.segments, &mut found);
199 retyped_all(found)
200 }
201
202 #[must_use]
204 #[inline]
205 pub fn edit(&self, op: EditOp) -> Edit<R> {
206 Edit {
207 path: self.segments.clone(),
208 op,
209 marker: PhantomData,
210 }
211 }
212}
213
214pub(crate) fn edit_risk(
220 shape: crate::Shape,
221 path: &[Segment],
222 op: &EditOp,
223 now: Option<&[(String, String)]>,
224) -> tilo_actions::RiskLevel {
225 use tilo_action_policy::edits::{EditStep, field_edit_asks};
226 let mut steps: Vec<EditStep<'_>> = Vec::with_capacity(path.len());
227 for segment in path {
228 steps.push(match segment {
229 Segment::Field(key) => EditStep::Field(key),
230 Segment::Item(_) | Segment::Key(_) | Segment::Cell { .. } => EditStep::Item,
231 });
232 }
233 match shape.trust_at(path) {
234 crate::Trust::Ordinary => {}
235 crate::Trust::Weakens(weaker) => {
236 let at = tilo_action_policy::edits::dotted(&steps);
237 let weakens = match op {
238 EditOp::Set { value } => weaker.weakens(
239 now.and_then(|now| now.iter().find(|(path, _)| *path == at))
240 .map(|(_, now)| now.as_str()),
241 &value.to_string(),
242 ),
243 _ => true,
244 };
245 if weakens {
246 return tilo_actions::RiskLevel::Privileged;
247 }
248 }
249 trust => return trust.risk(),
250 }
251 let quiet = shape.quiet_removals();
252 let quiet: Vec<&str> = quiet.iter().map(String::as_str).collect();
253 if field_edit_asks(op.name(), &steps, &quiet, &[]) {
254 tilo_actions::RiskLevel::Destructive
255 } else {
256 tilo_actions::RiskLevel::Low
257 }
258}
259
260fn extended(segments: &[Segment], segment: Segment) -> Vec<Segment> {
262 let mut extended = Vec::with_capacity(segments.len().saturating_add(1));
263 extended.extend_from_slice(segments);
264 extended.push(segment);
265 extended
266}
267
268impl<R, T> Clone for Path<R, T> {
269 fn clone(&self) -> Self {
270 Self::from_segments(self.segments.clone())
271 }
272}
273
274impl<R, T> std::fmt::Debug for Path<R, T> {
275 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
276 fmt_segments(&self.segments, f)
277 }
278}
279
280fn fmt_segments(segments: &[Segment], f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
281 f.write_str("Path(")?;
282 for (index, segment) in segments.iter().enumerate() {
283 if index > 0 {
284 f.write_str(" › ")?;
285 }
286 write!(f, "{segment}")?;
287 }
288 f.write_str(")")
289}
290
291impl<R, T> PartialEq for Path<R, T> {
292 fn eq(&self, other: &Self) -> bool {
293 self.segments == other.segments
294 }
295}
296
297impl<R, T> Eq for Path<R, T> {}
298
299impl<R, T> PartialOrd for Path<R, T> {
300 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
301 Some(self.cmp(other))
302 }
303}
304
305impl<R, T> Ord for Path<R, T> {
306 fn cmp(&self, other: &Self) -> Ordering {
307 self.segments.cmp(&other.segments)
308 }
309}
310
311impl<R, T> Hash for Path<R, T> {
312 fn hash<H: Hasher>(&self, state: &mut H) {
313 self.segments.hash(state);
314 }
315}
316
317impl<R, T> Serialize for Path<R, T> {
318 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
319 self.segments.serialize(serializer)
320 }
321}
322
323impl<'de, R, T> Deserialize<'de> for Path<R, T> {
324 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
325 let value = serde_json::Value::deserialize(deserializer)?;
326 match segments_from_json(value) {
327 Ok(segments) => Ok(Self::from_segments(segments)),
328 Err(error) => Err(serde::de::Error::custom(error)),
329 }
330 }
331}
332
333#[inline(never)]
337fn segments_from_json(value: serde_json::Value) -> Result<Vec<Segment>, serde_json::Error> {
338 Vec::<Segment>::deserialize(value)
339}
340
341#[inline(never)]
342fn edit_from_json(value: serde_json::Value) -> Result<(Vec<Segment>, EditOp), serde_json::Error> {
343 use serde::de::Error as _;
344 let serde_json::Value::Object(mut map) = value else {
345 return Err(serde_json::Error::custom("an edit is a JSON object"));
346 };
347 let path = map
348 .remove("path")
349 .ok_or_else(|| serde_json::Error::missing_field("path"))?;
350 let path = segments_from_json(path)?;
351 let op = op_from_json(serde_json::Value::Object(map))?;
352 Ok((path, op))
353}
354
355pub trait Settable: Model {}
360
361impl<R, T: Settable> Path<R, T> {
362 #[must_use]
364 #[allow(
365 clippy::needless_pass_by_value,
366 reason = "a value is set as written: `set(true)`, `set(Language::Rust)`"
367 )]
368 pub fn set(&self, value: T) -> Edit<R> {
369 self.edit(EditOp::Set {
370 value: crate::shape::without_absent::<T>(value.to_json()),
371 })
372 }
373}
374
375pub trait Operations: Model {
380 type Op: Serialize + serde::de::DeserializeOwned + crate::JsonSchema;
382
383 fn coalesces(previous: &Self::Op, next: &Self::Op) -> bool {
386 let _ = (previous, next);
387 false
388 }
389
390 fn continuable(op: &Self::Op) -> bool {
392 let _ = op;
393 true
394 }
395
396 fn describe(op: &Self::Op) -> OpDescription {
400 let _ = op;
401 OpDescription::default()
402 }
403
404 fn lands(&self, op: &Self::Op) -> Option<crate::Place> {
407 let _ = op;
408 None
409 }
410}
411
412#[doc(hidden)]
414pub fn op_coalesces<T: Operations>(
415 path: &[Segment],
416 previous: &serde_json::Value,
417 next: &serde_json::Value,
418) -> Option<bool> {
419 if !path.is_empty() {
420 return None;
421 }
422 let previous = serde_json::from_value(previous.clone()).ok()?;
423 let next = serde_json::from_value(next.clone()).ok()?;
424 Some(T::coalesces(&previous, &next))
425}
426
427#[derive(Clone, Debug, PartialEq, Eq)]
429pub struct OpDescription {
430 pub op: tilo_actions::EditOp,
431 pub args: std::collections::BTreeMap<String, tilo_actions::Scalar>,
432}
433
434impl Default for OpDescription {
435 fn default() -> Self {
436 Self {
437 op: tilo_actions::EditOp::Mark,
438 args: std::collections::BTreeMap::new(),
439 }
440 }
441}
442
443#[doc(hidden)]
445pub fn op_describe<T: Operations>(
446 path: &[Segment],
447 op: &serde_json::Value,
448) -> Option<OpDescription> {
449 if !path.is_empty() {
450 return None;
451 }
452 Some(T::describe(&serde_json::from_value(op.clone()).ok()?))
453}
454
455#[doc(hidden)]
457pub fn op_continuable<T: Operations>(path: &[Segment], op: &serde_json::Value) -> Option<bool> {
458 if !path.is_empty() {
459 return None;
460 }
461 Some(T::continuable(&serde_json::from_value(op.clone()).ok()?))
462}
463
464#[doc(hidden)]
466pub fn op_lands<T: Operations>(
467 value: &T,
468 path: &[Segment],
469 op: &serde_json::Value,
470) -> Option<crate::Place> {
471 if !path.is_empty() {
472 return None;
473 }
474 value.lands(&serde_json::from_value(op.clone()).ok()?)
475}
476
477#[macro_export]
480macro_rules! operations_model {
481 () => {
482 const OPS: bool = true;
483 fn op_coalesces(
484 path: &[$crate::Segment],
485 previous: &$crate::__private::serde_json::Value,
486 next: &$crate::__private::serde_json::Value,
487 ) -> ::core::option::Option<bool> {
488 $crate::path::op_coalesces::<Self>(path, previous, next)
489 }
490 fn op_continuable(
491 path: &[$crate::Segment],
492 op: &$crate::__private::serde_json::Value,
493 ) -> ::core::option::Option<bool> {
494 $crate::path::op_continuable::<Self>(path, op)
495 }
496 fn op_describe(
497 path: &[$crate::Segment],
498 op: &$crate::__private::serde_json::Value,
499 ) -> ::core::option::Option<$crate::path::OpDescription> {
500 $crate::path::op_describe::<Self>(path, op)
501 }
502 fn op_lands(
503 &self,
504 path: &[$crate::Segment],
505 op: &$crate::__private::serde_json::Value,
506 ) -> ::core::option::Option<$crate::Place> {
507 $crate::path::op_lands::<Self>(self, path, op)
508 }
509 fn op_schemas(
510 prefix: &str,
511 out: &mut ::std::vec::Vec<(
512 ::std::string::String,
513 $crate::__private::serde_json::Value,
514 )>,
515 ) {
516 out.push((
517 ::std::string::String::from(prefix.trim_end_matches('.')),
518 <<Self as $crate::Operations>::Op as $crate::JsonSchema>::json_schema(),
519 ));
520 }
521 };
522}
523
524impl<R, T: Operations> Path<R, T> {
525 pub fn perform(&self, op: &T::Op) -> Result<Edit<R>, serde_json::Error> {
530 Ok(self.edit(EditOp::Rich {
531 rich: crate::__private::json_via_bytes(op)?,
532 }))
533 }
534}
535
536impl<R, T: Model> Path<R, Option<T>> {
537 #[must_use]
539 pub fn some(&self) -> T::Paths<R> {
540 T::paths_at(self.clone().cast())
541 }
542}
543
544impl<R> Path<R, String> {
545 #[must_use]
547 pub fn splice(&self, at: usize, delete: usize, insert: impl Into<String>) -> Edit<R> {
548 self.edit(EditOp::Splice {
549 at,
550 delete,
551 insert: insert.into(),
552 })
553 }
554
555 #[must_use]
558 pub fn replace(&self, text: impl Into<String>) -> Edit<R> {
559 self.edit(EditOp::Replace { text: text.into() })
560 }
561}
562
563impl<R> Path<R, crate::Counter> {
564 #[must_use]
566 pub fn add(&self, by: i64) -> Edit<R> {
567 self.edit(EditOp::Add { by })
568 }
569}
570
571impl<R, T: Model> Path<R, crate::Set<T>> {
572 #[must_use]
574 pub fn insert(&self, value: &T) -> Edit<R> {
575 self.edit(EditOp::Insert {
576 value: value.to_json(),
577 })
578 }
579
580 #[must_use]
582 pub fn remove(&self, value: &T) -> Edit<R> {
583 self.edit(EditOp::Remove {
584 value: value.to_json(),
585 })
586 }
587}
588
589impl<R, T: Model> Path<R, crate::Collection<T>> {
590 #[must_use]
592 pub fn item(&self, id: &Id) -> T::Paths<R> {
593 T::paths_at(self.child(Segment::Item(id.clone())))
594 }
595
596 #[must_use]
598 pub fn item_path(&self, id: &Id) -> Path<R, T> {
599 self.child(Segment::Item(id.clone()))
600 }
601
602 #[must_use]
605 pub fn insert(&self, at: usize, value: &T) -> Edit<R> {
606 self.edit(EditOp::InsertItem {
607 id: None,
608 at: At::Index(at),
609 value: crate::shape::without_absent::<T>(value.to_json()),
610 })
611 }
612
613 #[must_use]
615 pub fn insert_as(&self, id: &Id, at: usize, value: &T) -> Edit<R> {
616 self.edit(EditOp::InsertItem {
617 id: Some(id.clone()),
618 at: At::Index(at),
619 value: crate::shape::without_absent::<T>(value.to_json()),
620 })
621 }
622
623 #[must_use]
625 pub fn remove(&self, id: &Id) -> Edit<R> {
626 self.edit(EditOp::RemoveItem { id: id.clone() })
627 }
628
629 #[must_use]
631 pub fn move_to(&self, id: &Id, at: usize) -> Edit<R> {
632 self.edit(EditOp::MoveTo {
633 id: id.clone(),
634 at: At::Index(at),
635 })
636 }
637
638 #[must_use]
641 pub fn upsert_by(
642 &self,
643 matching: serde_json::Map<String, serde_json::Value>,
644 value: serde_json::Value,
645 ) -> Edit<R> {
646 self.edit(EditOp::UpsertItem {
647 matching,
648 value,
649 id: None,
650 })
651 }
652}
653
654impl<R, T: Model> Path<R, std::collections::BTreeMap<String, T>> {
655 #[must_use]
657 pub fn key(&self, key: impl Into<String>) -> T::Paths<R> {
658 T::paths_at(self.child(Segment::Key(key.into())))
659 }
660
661 #[must_use]
663 pub fn remove(&self, key: impl Into<String>) -> Edit<R> {
664 self.edit(EditOp::RemoveKey { key: key.into() })
665 }
666}
667
668impl<R, T: Model> Path<R, crate::Grid<T>> {
669 #[must_use]
671 pub fn cell(&self, row: &Id, column: &Id) -> T::Paths<R> {
672 T::paths_at(self.child(Segment::Cell {
673 row: row.clone(),
674 column: column.clone(),
675 }))
676 }
677
678 #[must_use]
680 pub fn set_cell(&self, row: &Id, column: &Id, value: Option<&T>) -> Edit<R> {
681 self.edit(EditOp::SetCell {
682 row: row.clone(),
683 column: column.clone(),
684 value: value.map(|value| crate::shape::without_absent::<T>(value.to_json())),
685 })
686 }
687
688 #[must_use]
691 pub fn insert_row(&self, at: usize) -> Edit<R> {
692 self.edit(EditOp::InsertRow { id: None, at })
693 }
694
695 #[must_use]
697 pub fn insert_column(&self, at: usize) -> Edit<R> {
698 self.edit(EditOp::InsertColumn { id: None, at })
699 }
700
701 #[must_use]
703 pub fn remove_row(&self, row: &Id) -> Edit<R> {
704 self.edit(EditOp::RemoveRow { id: row.clone() })
705 }
706
707 #[must_use]
709 pub fn remove_column(&self, column: &Id) -> Edit<R> {
710 self.edit(EditOp::RemoveColumn { id: column.clone() })
711 }
712}
713
714impl<R, T: Model, O: Serialize + serde::de::DeserializeOwned + Default + 'static>
715 Path<R, crate::Outbox<T, O>>
716{
717 #[must_use]
720 pub fn settle(&self, id: &Id, outcome: &crate::Settled<O>) -> Edit<R> {
721 self.edit(EditOp::Settle {
722 id: id.clone(),
723 outcome: Model::to_json(outcome),
724 })
725 }
726
727 #[must_use]
729 pub fn forget(&self, id: &Id) -> Edit<R> {
730 self.edit(EditOp::Forget { id: id.clone() })
731 }
732}
733
734impl<R> Path<R, crate::Reactions> {
735 #[must_use]
738 pub fn react(&self, emoji: impl Into<String>) -> Edit<R> {
739 self.edit(EditOp::React {
740 emoji: emoji.into(),
741 })
742 }
743
744 #[must_use]
746 pub fn unreact(&self, emoji: impl Into<String>) -> Edit<R> {
747 self.edit(EditOp::Unreact {
748 emoji: emoji.into(),
749 })
750 }
751}
752
753#[derive(Clone, Debug, PartialEq, Serialize)]
755#[serde(tag = "op", rename_all = "kebab-case")]
756pub enum EditOp {
757 Set {
759 value: serde_json::Value,
760 },
761 Splice {
763 at: usize,
764 delete: usize,
765 insert: String,
766 },
767 Replace {
769 text: String,
770 },
771 Add {
773 by: i64,
774 },
775 Insert {
777 value: serde_json::Value,
778 },
779 Remove {
781 value: serde_json::Value,
782 },
783 InsertItem {
785 #[serde(default, skip_serializing_if = "Option::is_none")]
786 id: Option<Id>,
787 at: At,
788 value: serde_json::Value,
789 },
790 UpsertItem {
796 #[serde(rename = "match")]
797 matching: serde_json::Map<String, serde_json::Value>,
798 value: serde_json::Value,
799 #[serde(default, skip_serializing_if = "Option::is_none")]
800 id: Option<Id>,
801 },
802 RemoveItem {
804 id: Id,
805 },
806 MoveTo {
808 id: Id,
809 at: At,
810 },
811 RemoveKey {
813 key: String,
814 },
815 SetCell {
817 row: Id,
818 column: Id,
819 #[serde(default, skip_serializing_if = "Option::is_none")]
820 value: Option<serde_json::Value>,
821 },
822 InsertRow {
823 #[serde(default, skip_serializing_if = "Option::is_none")]
824 id: Option<Id>,
825 at: usize,
826 },
827 InsertColumn {
828 #[serde(default, skip_serializing_if = "Option::is_none")]
829 id: Option<Id>,
830 at: usize,
831 },
832 RemoveRow {
833 id: Id,
834 },
835 RemoveColumn {
836 id: Id,
837 },
838 Settle {
841 id: Id,
842 outcome: serde_json::Value,
843 },
844 Forget {
846 id: Id,
847 },
848 React {
851 emoji: String,
852 },
853 Unreact {
855 emoji: String,
856 },
857 Rich {
860 rich: serde_json::Value,
861 },
862}
863
864impl<'de> Deserialize<'de> for EditOp {
868 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
869 let value = serde_json::Value::deserialize(deserializer)?;
870 match op_from_json(value) {
871 Ok(op) => Ok(op),
872 Err(error) => Err(serde::de::Error::custom(error)),
873 }
874 }
875}
876
877#[derive(Deserialize)]
879#[serde(rename_all = "kebab-case")]
880enum EditOpWire {
881 Set {
882 value: serde_json::Value,
883 },
884 Splice {
885 at: usize,
886 delete: usize,
887 insert: String,
888 },
889 Replace {
890 text: String,
891 },
892 Add {
893 by: i64,
894 },
895 Insert {
896 value: serde_json::Value,
897 },
898 Remove {
899 value: serde_json::Value,
900 },
901 InsertItem {
902 #[serde(default)]
903 id: Option<Id>,
904 #[serde(default)]
905 at: At,
906 value: serde_json::Value,
907 },
908 UpsertItem {
909 #[serde(rename = "match")]
910 matching: serde_json::Map<String, serde_json::Value>,
911 value: serde_json::Value,
912 #[serde(default)]
913 id: Option<Id>,
914 },
915 RemoveItem {
916 id: Id,
917 },
918 MoveTo {
919 id: Id,
920 #[serde(default)]
921 at: At,
922 },
923 RemoveKey {
924 key: String,
925 },
926 SetCell {
927 row: Id,
928 column: Id,
929 #[serde(default)]
930 value: Option<serde_json::Value>,
931 },
932 InsertRow {
933 #[serde(default)]
934 id: Option<Id>,
935 at: usize,
936 },
937 InsertColumn {
938 #[serde(default)]
939 id: Option<Id>,
940 at: usize,
941 },
942 RemoveRow {
943 id: Id,
944 },
945 RemoveColumn {
946 id: Id,
947 },
948 Settle {
949 id: Id,
950 outcome: serde_json::Value,
951 },
952 Forget {
953 id: Id,
954 },
955 React {
956 emoji: String,
957 },
958 Unreact {
959 emoji: String,
960 },
961 Rich {
962 rich: serde_json::Value,
963 },
964}
965
966impl From<EditOpWire> for EditOp {
967 fn from(wire: EditOpWire) -> Self {
968 match wire {
969 EditOpWire::Set { value } => Self::Set { value },
970 EditOpWire::Splice { at, delete, insert } => Self::Splice { at, delete, insert },
971 EditOpWire::Replace { text } => Self::Replace { text },
972 EditOpWire::Add { by } => Self::Add { by },
973 EditOpWire::Insert { value } => Self::Insert { value },
974 EditOpWire::Remove { value } => Self::Remove { value },
975 EditOpWire::InsertItem { id, at, value } => Self::InsertItem { id, at, value },
976 EditOpWire::UpsertItem {
977 matching,
978 value,
979 id,
980 } => Self::UpsertItem {
981 matching,
982 value,
983 id,
984 },
985 EditOpWire::RemoveItem { id } => Self::RemoveItem { id },
986 EditOpWire::MoveTo { id, at } => Self::MoveTo { id, at },
987 EditOpWire::RemoveKey { key } => Self::RemoveKey { key },
988 EditOpWire::SetCell { row, column, value } => Self::SetCell { row, column, value },
989 EditOpWire::InsertRow { id, at } => Self::InsertRow { id, at },
990 EditOpWire::InsertColumn { id, at } => Self::InsertColumn { id, at },
991 EditOpWire::RemoveRow { id } => Self::RemoveRow { id },
992 EditOpWire::RemoveColumn { id } => Self::RemoveColumn { id },
993 EditOpWire::Settle { id, outcome } => Self::Settle { id, outcome },
994 EditOpWire::Forget { id } => Self::Forget { id },
995 EditOpWire::React { emoji } => Self::React { emoji },
996 EditOpWire::Unreact { emoji } => Self::Unreact { emoji },
997 EditOpWire::Rich { rich } => Self::Rich { rich },
998 }
999 }
1000}
1001
1002#[inline(never)]
1004fn op_from_json(value: serde_json::Value) -> Result<EditOp, serde_json::Error> {
1005 use serde::de::Error as _;
1006 let serde_json::Value::Object(mut fields) = value else {
1007 return Err(serde_json::Error::custom(
1008 "an edit operation is a JSON object",
1009 ));
1010 };
1011 let Some(serde_json::Value::String(op)) = fields.remove("op") else {
1012 return Err(serde_json::Error::missing_field("op"));
1013 };
1014 let mut tagged = serde_json::Map::new();
1015 tagged.insert(op, serde_json::Value::Object(fields));
1016 EditOpWire::deserialize(serde_json::Value::Object(tagged)).map(EditOp::from)
1017}
1018
1019pub const OP_ARGUMENTS: &[(&str, &[&str], &[&str])] = &[
1025 ("set", &["value"], &[]),
1026 ("splice", &["at", "delete", "insert"], &[]),
1027 ("replace", &["text"], &[]),
1028 ("add", &["by"], &[]),
1029 ("insert", &["value"], &[]),
1030 ("remove", &["value"], &[]),
1031 ("insert-item", &["value"], &["id", "at"]),
1032 ("upsert-item", &["match", "value"], &["id"]),
1033 ("remove-item", &["id"], &[]),
1034 ("move-to", &["id"], &["at"]),
1035 ("remove-key", &["key"], &[]),
1036 ("set-cell", &["row", "column"], &["value"]),
1037 ("insert-row", &["at"], &["id"]),
1038 ("insert-column", &["at"], &["id"]),
1039 ("remove-row", &["id"], &[]),
1040 ("remove-column", &["id"], &[]),
1041 ("settle", &["id", "outcome"], &[]),
1042 ("forget", &["id"], &[]),
1043 ("react", &["emoji"], &[]),
1044 ("unreact", &["emoji"], &[]),
1045 ("rich", &["rich"], &[]),
1046];
1047
1048#[must_use]
1051pub fn op_arguments(op: &str) -> Option<(&'static [&'static str], &'static [&'static str])> {
1052 OP_ARGUMENTS
1053 .iter()
1054 .find(|(name, ..)| *name == op)
1055 .map(|(_, required, optional)| (*required, *optional))
1056}
1057
1058#[must_use]
1062pub fn op_argument_schema(op: &str, argument: &str) -> serde_json::Value {
1063 let described = |schema: serde_json::Value, description: &str| {
1064 let mut schema = schema;
1065 if let Some(object) = schema.as_object_mut() {
1066 object.insert("description".into(), description.into());
1067 }
1068 schema
1069 };
1070 match (op, argument) {
1071 ("splice", "delete") => described(
1072 serde_json::json!({ "type": "integer", "minimum": 0 }),
1073 "splice: how many characters it replaces",
1074 ),
1075 ("splice", "insert") => described(
1076 serde_json::json!({ "type": "string" }),
1077 "splice: the text it puts there",
1078 ),
1079 (_, "at") => serde_json::json!({
1080 "description": "insert-item, move-to: \"end\" (the default), {\"after\": id} or {\"before\": id}; splice: the character the replaced text starts at; insert-row, insert-column: the position it goes at",
1081 "oneOf": [
1082 { "const": "end" },
1083 { "type": "object", "properties": { "after": { "type": "string" } }, "required": ["after"] },
1084 { "type": "object", "properties": { "before": { "type": "string" } }, "required": ["before"] },
1085 { "type": "integer", "minimum": 0 }
1086 ]
1087 }),
1088 (_, "text") => described(
1089 serde_json::json!({ "type": "string" }),
1090 "replace: the whole new text; rich text takes markdown",
1091 ),
1092 (_, "by") => described(serde_json::json!({ "type": "integer" }), "add: how much"),
1093 (_, "id") => described(
1094 serde_json::json!({ "type": "string" }),
1095 "remove-item, move-to, remove-row, remove-column, settle, forget: the item's id; \
1096 insert-item, upsert-item, insert-row, insert-column: the new item's id, minted without",
1097 ),
1098 (_, "key") => described(
1099 serde_json::json!({ "type": "string" }),
1100 "remove-key: the entry's key",
1101 ),
1102 (_, "row" | "column") => described(
1103 serde_json::json!({ "type": "string" }),
1104 "set-cell: the cell's row and column ids",
1105 ),
1106 (_, "outcome") => described(
1107 serde_json::json!({ "type": "object" }),
1108 "settle: how the entry settled",
1109 ),
1110 (_, "emoji") => described(
1111 serde_json::json!({ "type": "string" }),
1112 "react, unreact: a Unicode emoji, or a workspace emoji as :name:",
1113 ),
1114 (_, "match") => serde_json::json!({
1115 "type": "object",
1116 "description": "upsert-item: the fields that identify the item, e.g. {\"name\": \"Ana\"}; it updates the one item holding them with `value`'s fields, else appends `value` as a new item"
1117 }),
1118 (_, "rich") => described(
1119 serde_json::json!({ "type": "object" }),
1120 "rich: an edit in the field type's own vocabulary",
1121 ),
1122 _ => serde_json::json!({}),
1123 }
1124}
1125
1126#[must_use]
1130pub fn op_usage(op: &str) -> String {
1131 let Some((required, optional)) = op_arguments(op) else {
1132 return op.to_owned();
1133 };
1134 if required == ["value"] && optional.is_empty() {
1137 return op.to_owned();
1138 }
1139 let arguments: Vec<String> = required
1140 .iter()
1141 .map(|argument| (*argument).to_owned())
1142 .chain(optional.iter().map(|argument| format!("{argument}?")))
1143 .collect();
1144 if arguments.is_empty() {
1145 op.to_owned()
1146 } else {
1147 format!("{op} {{{}}}", arguments.join(", "))
1148 }
1149}
1150
1151impl EditOp {
1152 #[must_use]
1154 pub const fn name(&self) -> &'static str {
1155 match self {
1156 Self::Set { .. } => "set",
1157 Self::Splice { .. } => "splice",
1158 Self::Replace { .. } => "replace",
1159 Self::Add { .. } => "add",
1160 Self::Insert { .. } => "insert",
1161 Self::Remove { .. } => "remove",
1162 Self::InsertItem { .. } => "insert-item",
1163 Self::UpsertItem { .. } => "upsert-item",
1164 Self::RemoveItem { .. } => "remove-item",
1165 Self::MoveTo { .. } => "move-to",
1166 Self::RemoveKey { .. } => "remove-key",
1167 Self::SetCell { .. } => "set-cell",
1168 Self::InsertRow { .. } => "insert-row",
1169 Self::InsertColumn { .. } => "insert-column",
1170 Self::RemoveRow { .. } => "remove-row",
1171 Self::RemoveColumn { .. } => "remove-column",
1172 Self::Settle { .. } => "settle",
1173 Self::Forget { .. } => "forget",
1174 Self::React { .. } => "react",
1175 Self::Unreact { .. } => "unreact",
1176 Self::Rich { .. } => "rich",
1177 }
1178 }
1179
1180 #[must_use]
1183 pub const fn removes(&self) -> bool {
1184 matches!(
1185 self,
1186 Self::RemoveItem { .. }
1187 | Self::RemoveKey { .. }
1188 | Self::RemoveRow { .. }
1189 | Self::RemoveColumn { .. }
1190 )
1191 }
1192}
1193
1194pub struct Edit<R> {
1197 path: Vec<Segment>,
1198 op: EditOp,
1199 marker: PhantomData<fn() -> R>,
1200}
1201
1202impl<R> Edit<R> {
1203 #[must_use]
1205 pub fn new(path: Vec<Segment>, op: EditOp) -> Self {
1206 Self {
1207 path,
1208 op,
1209 marker: PhantomData,
1210 }
1211 }
1212
1213 pub fn path(&self) -> &[Segment] {
1214 &self.path
1215 }
1216
1217 pub fn op(&self) -> &EditOp {
1218 &self.op
1219 }
1220
1221 #[must_use]
1224 pub fn retyped<S>(self) -> Edit<S> {
1225 Edit::new(self.path, self.op)
1226 }
1227
1228 pub fn from_json(value: serde_json::Value) -> Result<Self, String> {
1233 match edit_from_json(value) {
1234 Ok((path, op)) => Ok(Self::new(path, op)),
1235 Err(error) => Err(error.to_string()),
1236 }
1237 }
1238
1239 pub(crate) fn past_resource_name(
1245 self,
1246 root: crate::Shape,
1247 names: &[&str],
1248 ) -> Result<Self, String> {
1249 let fields = root.fields();
1250 let Some((Segment::Field(head), rest)) = self.path.split_first() else {
1251 return Ok(self);
1252 };
1253 if fields.iter().any(|field| field.key == head)
1254 || !names.iter().any(|name| name.eq_ignore_ascii_case(head))
1255 {
1256 return Ok(self);
1257 }
1258 let Some(start) = rest.first() else {
1259 let editable: Vec<&str> = fields
1260 .iter()
1261 .filter(|field| !field.readonly)
1262 .map(|field| field.key)
1263 .collect();
1264 return Err(format!(
1265 "`{head}` is the resource itself, not one of its fields: start the path at the field to change, one of {}",
1266 editable.join(", ")
1267 ));
1268 };
1269 if root.trust_at(rest) != crate::Trust::Ordinary {
1273 return Err(format!(
1274 "`{head}` is the resource itself, not one of its fields: start the path at `{start}`"
1275 ));
1276 }
1277 Ok(Self::new(rest.to_vec(), self.op))
1278 }
1279
1280 #[must_use]
1287 pub fn coalesces(&self, next: &Self) -> bool
1288 where
1289 R: Model,
1290 {
1291 edits_coalesce(
1292 (&self.path, &self.op),
1293 (&next.path, &next.op),
1294 R::op_coalesces,
1295 )
1296 }
1297
1298 #[must_use]
1302 pub fn risk(&self) -> tilo_actions::RiskLevel
1303 where
1304 R: Model,
1305 {
1306 edit_risk(R::SHAPE, &self.path, &self.op, None)
1307 }
1308
1309 #[must_use]
1313 pub fn tree_path(
1314 &self,
1315 workspace: &str,
1316 app: &str,
1317 record: &str,
1318 ) -> tilo_action_policy::TreePath
1319 where
1320 R: crate::Resource,
1321 {
1322 use tilo_action_policy::Level;
1323 let mut tree = tilo_action_policy::TreePath::workspace(workspace)
1324 .app(app)
1325 .kind(R::KIND)
1326 .resource(record);
1327 let mut item = false;
1328 let mut segments = self.path.iter().peekable();
1329 while let Some(segment) = segments.next() {
1330 tree = match segment {
1331 Segment::Field(_) if !item && matches!(segments.peek(), Some(Segment::Item(_))) => {
1332 tree
1333 }
1334 Segment::Item(id) if !item => {
1335 item = true;
1336 tree.item(id.as_str())
1337 }
1338 Segment::Field(key) | Segment::Key(key) => tree.push(Level::Field, key.as_str()),
1339 Segment::Item(id) => tree.push(Level::Field, id.as_str()),
1340 Segment::Cell { row, column } => tree
1341 .push(Level::Field, row.as_str())
1342 .push(Level::Field, column.as_str()),
1343 };
1344 }
1345 tree.action(crate::FIELD_EDIT)
1346 }
1347
1348 pub fn apply_local(&self, doc: &mut crate::Doc) -> Result<(), crate::ModelError>
1354 where
1355 R: crate::Fields,
1356 {
1357 let payload = serde_json::to_vec(self)
1358 .map_err(|error| crate::ModelError::invalid(error.to_string()))?;
1359 let mut cx = crate::ActionCx::for_write(doc, &payload);
1360 self.apply(doc, &mut cx)
1361 }
1362
1363 pub fn apply(
1370 &self,
1371 doc: &mut crate::Doc,
1372 cx: &mut crate::ActionCx,
1373 ) -> Result<(), crate::ModelError>
1374 where
1375 R: crate::Fields,
1376 {
1377 R::edit_fields(doc, &automerge::ROOT, &self.path, &self.op, cx)
1378 }
1379}
1380
1381#[inline(never)]
1385fn edits_coalesce(
1386 (previous_path, previous_op): (&[Segment], &EditOp),
1387 (next_path, next_op): (&[Segment], &EditOp),
1388 rich: fn(&[Segment], &serde_json::Value, &serde_json::Value) -> Option<bool>,
1389) -> bool {
1390 if previous_path != next_path {
1391 return false;
1392 }
1393 match (previous_op, next_op) {
1394 (EditOp::Rich { rich: previous }, EditOp::Rich { rich: next }) => {
1395 rich(previous_path, previous, next).unwrap_or(false)
1396 }
1397 (EditOp::Set { .. }, EditOp::Set { .. }) | (EditOp::Add { .. }, EditOp::Add { .. }) => true,
1398 (EditOp::Replace { text: previous }, EditOp::Replace { text: next }) => {
1399 replace_continues(previous, next)
1400 }
1401 (
1402 EditOp::Splice {
1403 at, delete, insert, ..
1404 },
1405 EditOp::Splice {
1406 at: next_at,
1407 delete: next_delete,
1408 insert: next_insert,
1409 },
1410 ) => {
1411 let typed = insert.chars().count();
1412 let typing = *delete == 0
1416 && *next_delete == 0
1417 && !next_insert.is_empty()
1418 && *next_at == at.saturating_add(typed)
1419 && !insert.ends_with(char::is_whitespace);
1420 let erasing = insert.is_empty()
1422 && next_insert.is_empty()
1423 && next_at.saturating_add(*next_delete) == *at;
1424 typing || erasing
1425 }
1426 _ => false,
1427 }
1428}
1429
1430impl<R> Clone for Edit<R> {
1431 fn clone(&self) -> Self {
1432 let (path, op) = clone_edit(&self.path, &self.op);
1433 Self::new(path, op)
1434 }
1435}
1436
1437#[inline(never)]
1440fn clone_edit(path: &[Segment], op: &EditOp) -> (Vec<Segment>, EditOp) {
1441 (path.to_vec(), op.clone())
1442}
1443
1444impl<R> std::fmt::Debug for Edit<R> {
1445 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1446 fmt_edit(&self.path, &self.op, f)
1447 }
1448}
1449
1450fn fmt_edit(path: &[Segment], op: &EditOp, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1451 f.debug_struct("Edit")
1452 .field("path", &Path::<(), ()>::from_segments(path.to_vec()))
1453 .field("op", op)
1454 .finish()
1455}
1456
1457impl<R> PartialEq for Edit<R> {
1458 fn eq(&self, other: &Self) -> bool {
1459 self.path == other.path && self.op == other.op
1460 }
1461}
1462
1463impl<R> Serialize for Edit<R> {
1464 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1465 edit_to_json(&self.path, &self.op).serialize(serializer)
1466 }
1467}
1468
1469#[must_use]
1475pub fn outbox_settle_arguments(
1476 field: &str,
1477 id: &str,
1478 outcome: &serde_json::Value,
1479) -> serde_json::Map<String, serde_json::Value> {
1480 let op = EditOp::Settle {
1481 id: Id::from_raw(id),
1482 outcome: outcome.clone(),
1483 };
1484 let edit = edit_to_json(&[Segment::Field(field.to_owned())], &op);
1485 serde_json::Map::from_iter([(crate::EDIT_PARAM.to_owned(), edit)])
1486}
1487
1488#[inline(never)]
1489fn edit_to_json(path: &[Segment], op: &EditOp) -> serde_json::Value {
1490 let mut form = crate::__private::json_via_bytes(op).unwrap_or_default();
1492 if let serde_json::Value::Object(map) = &mut form {
1493 map.insert(
1494 "path".into(),
1495 crate::__private::json_via_bytes(path).unwrap_or_default(),
1496 );
1497 }
1498 form
1499}
1500
1501impl<'de, R> Deserialize<'de> for Edit<R> {
1502 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1503 let value = serde_json::Value::deserialize(deserializer)?;
1504 match edit_from_json(value) {
1505 Ok((path, op)) => Ok(Self::new(path, op)),
1506 Err(error) => Err(serde::de::Error::custom(error)),
1507 }
1508 }
1509}
1510
1511impl<R> crate::JsonSchema for Edit<R> {
1512 fn json_schema() -> serde_json::Value {
1513 edit_schema()
1514 }
1515}
1516
1517fn edit_schema() -> serde_json::Value {
1518 edit_schema_taking(|_| true)
1519}
1520
1521#[inline(never)]
1525pub(crate) fn edit_schema_taking(takes: impl Fn(&str) -> bool) -> serde_json::Value {
1526 let offered: Vec<&(&str, &[&str], &[&str])> =
1527 OP_ARGUMENTS.iter().filter(|(op, ..)| takes(op)).collect();
1528 let ops: Vec<&str> = offered.iter().map(|(op, ..)| *op).collect();
1529 let mut properties = serde_json::Map::new();
1530 properties.insert(
1531 "path".into(),
1532 serde_json::json!({ "type": "array", "items": {"type": "object"} }),
1533 );
1534 properties.insert(
1535 "op".into(),
1536 serde_json::json!({ "type": "string", "enum": ops }),
1537 );
1538 let mut needs = Vec::new();
1539 for (op, required, optional) in offered {
1540 for argument in required.iter().chain(optional.iter()) {
1541 if !properties.contains_key(*argument) {
1542 properties.insert((*argument).to_owned(), op_argument_schema(op, argument));
1543 }
1544 }
1545 let mut needed = vec!["path", "op"];
1546 needed.extend(required.iter().copied());
1547 needs.push(serde_json::json!({
1548 "properties": { "op": { "const": op } },
1549 "required": needed,
1550 }));
1551 }
1552 serde_json::json!({
1553 "type": "object",
1554 "description": "A field edit: the path from the record's root (fields by name, items by id) and an operation the field's type supports, with the arguments that operation takes",
1555 "properties": properties,
1556 "required": ["path", "op"],
1557 "oneOf": needs,
1558 })
1559}
1560
1561#[must_use]
1563pub fn retyped_all<R>(edits: Vec<Edit<()>>) -> Vec<Edit<R>> {
1564 let mut out = Vec::with_capacity(edits.len());
1565 for edit in edits {
1566 out.push(edit.retyped());
1567 }
1568 out
1569}
1570
1571#[doc(hidden)]
1574pub fn leaf<R, T>(path: Path<R, T>) -> Path<R, T> {
1575 path
1576}
1577
1578fn replace_continues(previous: &str, next: &str) -> bool {
1585 let (was, now): (Vec<char>, Vec<char>) = (previous.chars().collect(), next.chars().collect());
1586 let (prefix, suffix) = crate::text::common_ends(&was, &now);
1587 let (before, after) = (was.len(), now.len());
1588 let kept = prefix.saturating_add(suffix);
1589 let deleted = before.saturating_sub(kept);
1590 let inserted = after.saturating_sub(kept);
1591 match (deleted, inserted) {
1592 (1.., 0) => true,
1594 (0, 1) => prefix
1596 .checked_sub(1)
1597 .and_then(|at| was.get(at))
1598 .is_some_and(|c| !c.is_whitespace()),
1599 _ => false,
1600 }
1601}