Skip to main content

tilo_resource/
path.rs

1//! Typed paths into a model and the field edits made at them.
2//!
3//! `#[derive(Model)]` gives every type a path struct: `Snippets::paths()`
4//! has one field per model field, a [`Collection`](crate::Collection) path
5//! offers [`item`](Path::item), a [`Grid`](crate::Grid) path
6//! [`cell`](Path::cell), a map path [`key`](Path::key). A [`Path`] is plain
7//! data — the stored field names and item ids from the record's root — so it
8//! can be stored, compared and sent.
9//!
10//! Each path offers the edits its type supports. An edit is an [`Edit`]: a
11//! path and an [`EditOp`]. It is one of the resource's actions, so it
12//! replays, syncs, undoes and is named in history like a verb, and it
13//! applies at its path without reading the rest of the record.
14
15use 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/// One step of a [`Path`].
26#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
27#[serde(rename_all = "kebab-case")]
28pub enum Segment {
29    /// A field of a record, by the key it is stored under.
30    Field(String),
31    /// An item of a [`Collection`](crate::Collection) or an entry of an
32    /// [`Outbox`](crate::Outbox), by its id.
33    Item(Id),
34    /// An entry of a map.
35    Key(String),
36    /// A cell of a [`Grid`](crate::Grid), by its row and column ids.
37    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
50/// The location of a `T` inside the record `R`. See the module docs.
51pub 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    /// The record itself.
62    #[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    /// The object the value at this path is stored in — a record's map, a
73    /// list, a text — resolved through each container's own layout, for an
74    /// editor that binds to the object itself (a rich-text field inside a
75    /// collection item); `None` when absent or stored as a scalar.
76    #[must_use]
77    pub fn object(&self, doc: &crate::Doc) -> Option<automerge::ObjId> {
78        object_at(R::SHAPE, &self.segments, doc)
79    }
80}
81
82/// [`Path::object`] of the path `segments` into a record stored as `shape`.
83fn 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    /// A path from stored segments. A path read back from storage or the
132    /// wire is checked when an edit at it applies.
133    #[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    /// One step further down, to a value of type `U`.
151    #[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    /// The same location seen as another type: the inner value of a `Box`,
159    /// the present value of an `Option`.
160    #[doc(hidden)]
161    #[must_use]
162    pub fn cast<U>(self) -> Path<R, U> {
163        Path::from_segments(self.segments)
164    }
165
166    /// This path, rooted at an item, seen from the record containing it: a
167    /// row's `favorite` as `Snippets › snippets › <id> › favorite`.
168    #[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    /// The value at this path in `root`, if it is there.
176    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    /// Whether `self` is `other` or lies inside it.
185    pub fn starts_with<U>(&self, other: &Path<R, U>) -> bool {
186        self.segments.starts_with(&other.segments)
187    }
188
189    /// The field edits that turn `before`, the value at this path, into
190    /// `after`: what a surface that edited a local copy submits, field by
191    /// field and item by item ([`Model::diff`]).
192    #[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    /// The edit `op` at this path.
203    #[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
214/// [`Edit::risk`] of the edit `op` at `path` in a record stored as `shape`:
215/// the field's [`Trust`](crate::Trust), or a removal's. `now` holds the
216/// values, as JSON text by dotted path, of the fields that weaken one way:
217/// a change of one the other way, or to a value as strong, is ordinary;
218/// without its value now, any change of it counts as weakening.
219pub(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
260/// `segments` and one step more.
261fn 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// Paths and edits are decoded in every crate naming a record type, and serde
334// instantiates a generic decoder per calling crate. Going through JSON values
335// keeps one decoder, compiled here.
336#[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
355/// Values a path can [`set`](Path::set) whole: scalars, enums, text, short
356/// lists, options of them and nested records. Containers whose merge is per
357/// element (`Counter`, `Set`, `Collection`, `Grid`, `Outbox`) are edited per
358/// element instead.
359pub trait Settable: Model {}
360
361impl<R, T: Settable> Path<R, T> {
362    /// Replace the value.
363    #[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
375/// A type with its own vocabulary of edits beside the generic ones: rich
376/// text's marks and blocks. Its paths offer [`Path::perform`]; its `Model`
377/// impl calls [`operations_model!`](crate::operations_model) so records
378/// holding it route those edits' gestures, landing places and schema to it.
379pub trait Operations: Model {
380    /// One edit of the type, in its own terms.
381    type Op: Serialize + serde::de::DeserializeOwned + crate::JsonSchema;
382
383    /// Whether `next`, straight after `previous` by the same actor, is the
384    /// same gesture (typing on in one word): one undo step.
385    fn coalesces(previous: &Self::Op, next: &Self::Op) -> bool {
386        let _ = (previous, next);
387        false
388    }
389
390    /// Whether a gesture may go on after `op`.
391    fn continuable(op: &Self::Op) -> bool {
392        let _ = op;
393        true
394    }
395
396    /// What `op` did, as a history entry records it: the kind of edit and
397    /// its plain facts by name (`{mark: "strong", words: 3}`), which the
398    /// reader's message receives.
399    fn describe(op: &Self::Op) -> OpDescription {
400        let _ = op;
401        OpDescription::default()
402    }
403
404    /// Where the actor of `op` is after it applied (the caret after typed
405    /// text), read from the value it applied to.
406    fn lands(&self, op: &Self::Op) -> Option<crate::Place> {
407        let _ = op;
408        None
409    }
410}
411
412/// [`Model::op_coalesces`] of an [`Operations`] type.
413#[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/// What an edit in a type's own vocabulary did ([`Operations::describe`]).
428#[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/// [`Model::op_describe`] of an [`Operations`] type.
444#[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/// [`Model::op_continuable`] of an [`Operations`] type.
456#[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/// [`Model::op_lands`] of an [`Operations`] type.
465#[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/// Implements the `Model` items that route a record's edits of an
478/// [`Operations`] type to it; call it inside the type's `impl Model`.
479#[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    /// The edit `op` of the value at this path, in the type's own vocabulary.
526    ///
527    /// # Errors
528    /// Returns the serialization error of `op`.
529    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    /// The value when present; edits at it refuse while it is absent.
538    #[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    /// Replace `delete` characters at `at` with `insert`.
546    #[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    /// Replace the whole text, written as the smallest splice that turns the
556    /// stored text into it.
557    #[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    /// Add `by` (negative to subtract). Concurrent additions add up.
565    #[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    /// Add an element.
573    #[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    /// Remove an element.
581    #[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    /// The item `id`, its own paths rooted here.
591    #[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    /// The path of the item `id` itself.
597    #[must_use]
598    pub fn item_path(&self, id: &Id) -> Path<R, T> {
599        self.child(Segment::Item(id.clone()))
600    }
601
602    /// Insert `value` at `at` (clamped to the end) under a fresh id minted
603    /// when the edit applies.
604    #[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    /// Insert `value` at `at` (clamped to the end) under `id`.
614    #[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    /// Remove the item `id`.
624    #[must_use]
625    pub fn remove(&self, id: &Id) -> Edit<R> {
626        self.edit(EditOp::RemoveItem { id: id.clone() })
627    }
628
629    /// Move the item `id` to `at` (clamped to the end).
630    #[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    /// Update the one item whose fields hold `matching` with the fields of
639    /// `value`, else append `value` with them ([`EditOp::UpsertItem`]).
640    #[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    /// The entry `key`, its own paths rooted here.
656    #[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    /// Remove the entry `key`.
662    #[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    /// The cell at `row`, `column`, its own paths rooted here.
670    #[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    /// Set or clear one cell.
679    #[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    /// Insert a row at `at` (clamped) under a fresh id minted when the edit
689    /// applies.
690    #[must_use]
691    pub fn insert_row(&self, at: usize) -> Edit<R> {
692        self.edit(EditOp::InsertRow { id: None, at })
693    }
694
695    /// Insert a column at `at` (clamped) under a fresh id.
696    #[must_use]
697    pub fn insert_column(&self, at: usize) -> Edit<R> {
698        self.edit(EditOp::InsertColumn { id: None, at })
699    }
700
701    /// Remove a row and its cells.
702    #[must_use]
703    pub fn remove_row(&self, row: &Id) -> Edit<R> {
704        self.edit(EditOp::RemoveRow { id: row.clone() })
705    }
706
707    /// Remove a column and its cells.
708    #[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    /// Record how the owning device settled the entry `id`: content from
718    /// outside, nobody's undo step.
719    #[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    /// Forget the settled entry `id`: housekeeping, nobody's undo step.
728    #[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    /// React with `emoji` (a Unicode emoji, or a workspace emoji as
736    /// `:name:`), as whoever invokes the edit.
737    #[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    /// Take back the invoker's reaction with `emoji`.
745    #[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/// What an [`Edit`] does at its path. Text positions count characters.
754#[derive(Clone, Debug, PartialEq, Serialize)]
755#[serde(tag = "op", rename_all = "kebab-case")]
756pub enum EditOp {
757    /// Replace the value with one in its JSON form ([`Model::to_json`]).
758    Set {
759        value: serde_json::Value,
760    },
761    /// Replace `delete` characters at `at` with `insert`.
762    Splice {
763        at: usize,
764        delete: usize,
765        insert: String,
766    },
767    /// Replace the whole text by the smallest splice.
768    Replace {
769        text: String,
770    },
771    /// Add to a [`Counter`](crate::Counter).
772    Add {
773        by: i64,
774    },
775    /// Add an element to a [`Set`](crate::Set).
776    Insert {
777        value: serde_json::Value,
778    },
779    /// Remove an element from a [`Set`](crate::Set).
780    Remove {
781        value: serde_json::Value,
782    },
783    /// Insert an item into a collection; `id: None` mints one.
784    InsertItem {
785        #[serde(default, skip_serializing_if = "Option::is_none")]
786        id: Option<Id>,
787        at: At,
788        value: serde_json::Value,
789    },
790    /// Update the one item of a collection whose fields hold `matching`
791    /// with the fields of `value`, else append `value` (with `matching`'s
792    /// fields) as a new item, under `id` when given. Resolved against the
793    /// document as it is when the edit applies; refused when more than one
794    /// item matches.
795    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    /// Remove an item from a collection.
803    RemoveItem {
804        id: Id,
805    },
806    /// Move an item within a collection.
807    MoveTo {
808        id: Id,
809        at: At,
810    },
811    /// Remove an entry of a map.
812    RemoveKey {
813        key: String,
814    },
815    /// Set (`Some`) or clear (`None`) a grid cell.
816    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 an outbox entry, with its [`Settled`](crate::Settled) in JSON
839    /// form.
840    Settle {
841        id: Id,
842        outcome: serde_json::Value,
843    },
844    /// Forget a settled outbox entry.
845    Forget {
846        id: Id,
847    },
848    /// React with `emoji` to what holds a [`Reactions`](crate::Reactions)
849    /// field, as whoever invokes the edit.
850    React {
851        emoji: String,
852    },
853    /// Take back the invoker's reaction with `emoji`.
854    Unreact {
855        emoji: String,
856    },
857    /// An edit of a type with its own vocabulary ([`Operations`]: rich text
858    /// marks and blocks), in that type's JSON form.
859    Rich {
860        rich: serde_json::Value,
861    },
862}
863
864// Read through one JSON value: the tag taken out by hand and the rest read
865// as an externally tagged twin, so no deserializer buffers the edit's content
866// to find its tag, and the reading is compiled once.
867impl<'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/// [`EditOp`] as its JSON form tags it, the tag outside.
878#[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/// The operation in `value`, an edit's JSON form without its path.
1003#[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
1019/// What each field-edit operation takes beside `path` and `op`, as its JSON
1020/// form reads it: the operation's name, the arguments it requires and the
1021/// ones it may be given. The published field-edit schema states these, so an
1022/// agent reading it sends what the edit needs; `op_arguments_match_what_an_edit_reads`
1023/// holds the table to the reader.
1024pub 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/// The arguments the operation `op` requires and may be given
1049/// ([`OP_ARGUMENTS`]); `None` for no operation of that name.
1050#[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/// The schema of the argument `argument` of the operation `op`, as its JSON
1059/// form reads it. An argument several operations share (`at`, `id`) has one
1060/// schema that holds for each of them.
1061#[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/// How the operation `op` reads in a listing of what a path takes, with its
1127/// arguments: `remove-item {id}`, `move-to {id, at?}`; an operation that
1128/// takes only a value (`set`) by its name.
1129#[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    // A value is what every `set` takes: the listing says the field's kind
1135    // of value on the same line.
1136    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    /// The operation's name, as its JSON form tags it.
1153    #[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    /// Whether this operation removes something a person may want back
1181    /// (an item, a row, a map entry).
1182    #[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
1194/// A field edit of the record `R`: a path and an operation. See the module
1195/// docs.
1196pub struct Edit<R> {
1197    path: Vec<Segment>,
1198    op: EditOp,
1199    marker: PhantomData<fn() -> R>,
1200}
1201
1202impl<R> Edit<R> {
1203    /// An edit from its parts, as read back from the wire.
1204    #[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    /// The same edit, of the record `S`: the path and operation it carries
1222    /// do not depend on the record type.
1223    #[must_use]
1224    pub fn retyped<S>(self) -> Edit<S> {
1225        Edit::new(self.path, self.op)
1226    }
1227
1228    /// The edit in `value`, its JSON form.
1229    ///
1230    /// # Errors
1231    /// Why `value` is no field edit.
1232    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    /// The same edit of a record stored as `root`, which callers also call
1240    /// by one of `names`: a path whose first field names no field of the
1241    /// record but the record itself starts at the field after it. A record
1242    /// read nests its fields under such a name (a timeline's `project`), and
1243    /// callers send `project.name` back.
1244    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        // An action API decides whether an edit asks first from the path as sent,
1270        // which names no field that exposes the person or weakens their
1271        // security; an edit of such a field is sent again from the root.
1272        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    /// Whether `next`, by the same actor straight after `self`, continues
1281    /// the same gesture: one undo step. Setting one path again (dragging a
1282    /// slider), typing on at the end of the previous splice (a word) and a
1283    /// text field's whole-text replacements that type or erase within one
1284    /// word (`replace_continues`) continue; an edit in a type's own vocabulary continues as that type
1285    /// says ([`Operations::coalesces`]); anything else starts a new step.
1286    #[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    /// How much harm this edit can do: removing an item of a collection is
1299    /// destructive, like a delete verb, unless the collection is
1300    /// `#[model(remove = "quiet")]`; every other edit is low.
1301    #[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    /// The node of the published tree this edit acts on, for deciding
1310    /// grants: `workspace › app › kind › record [› item] › field… › field-edit`.
1311    /// The collection field holding an item is not a node of its own.
1312    #[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    /// Apply to a document held apart from any resource (a form's local
1349    /// value): no action, no history, ids minted from the document alone.
1350    ///
1351    /// # Errors
1352    /// As [`Self::apply`].
1353    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    /// Apply at its path in `doc`, then run the invariants of every value
1364    /// the edit touched.
1365    ///
1366    /// # Errors
1367    /// Returns why the path or operation does not fit the model, or the
1368    /// refusal of a [`check`](crate::Model::check).
1369    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/// [`Edit::coalesces`] of the edit `previous` (its path and operation) and
1382/// `next`, an edit in a type's own vocabulary continuing as `rich` says:
1383/// compiled once rather than for every record type.
1384#[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            // Typing on after the previous insertion, within one word:
1413            // a space ends the word it follows, so undo takes back
1414            // `world` and leaves `hello `.
1415            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            // Deleting backwards from where the previous deletion was.
1421            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/// A copy of an edit's path and operation, made by one function for every
1438/// resource type.
1439#[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/// The arguments of [`FIELD_EDIT`](crate::FIELD_EDIT) that settle entry
1470/// `id` of the outbox stored at field `field` with `outcome` (a
1471/// [`Settled`](crate::Settled) in JSON form): [`Path::settle`] for a host
1472/// that holds the record without its app's types, such as a workspace's host
1473/// settling what a bot's connector performed.
1474#[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    // Both are plain data: their JSON never fails to build.
1491    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/// The field-edit schema with only the operations `takes` names, and only the
1522/// arguments those take: what a record whose fields take just those publishes,
1523/// so an agent reads none of the operations no path of it takes.
1524#[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/// `edits`, of the record `R`.
1562#[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/// The paths of a type whose values are edited only as a whole or through
1572/// their own operations: the path itself.
1573#[doc(hidden)]
1574pub fn leaf<R, T>(path: Path<R, T>) -> Path<R, T> {
1575    path
1576}
1577
1578/// Whether a text field's replacement of `previous` by `next` continues the
1579/// same typing gesture, so the keystrokes of one word are one undo step as
1580/// with splices: the one change between them is typing a single character
1581/// on after a character that is not a space (a space ends the word it
1582/// follows), or erasing. A paste or any larger change is a step of its own,
1583/// so undo takes it back alone.
1584fn 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        // Erasing: Backspace or Delete runs on through the word.
1593        (1.., 0) => true,
1594        // Typing one character on after a non-space.
1595        (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}