use std::cmp::Ordering;
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;
use serde::{Deserialize, Serialize};
use crate::collection::Id;
use crate::model::Model;
pub use crate::upsert::At;
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Segment {
Field(String),
Item(Id),
Key(String),
Cell { row: Id, column: Id },
}
impl std::fmt::Display for Segment {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Field(key) | Self::Key(key) => f.write_str(key),
Self::Item(id) => write!(f, "{id}"),
Self::Cell { row, column } => write!(f, "{row}:{column}"),
}
}
}
pub struct Path<R, T> {
segments: Vec<Segment>,
marker: PhantomData<fn() -> (R, T)>,
}
#[allow(
clippy::mismatching_type_param_order,
reason = "the root is the record seen as a value of itself"
)]
impl<R> Path<R, R> {
#[must_use]
pub const fn root() -> Self {
Self {
segments: Vec::new(),
marker: PhantomData,
}
}
}
impl<R: Model, T> Path<R, T> {
#[must_use]
pub fn object(&self, doc: &crate::Doc) -> Option<automerge::ObjId> {
object_at(R::SHAPE, &self.segments, doc)
}
}
fn object_at(
shape: crate::Shape,
segments: &[Segment],
doc: &crate::Doc,
) -> Option<automerge::ObjId> {
use crate::Shape;
use automerge::ReadDoc;
fn child(doc: &crate::Doc, obj: &automerge::ObjId, key: &str) -> Option<automerge::ObjId> {
match doc.get(obj, key).ok()?? {
(automerge::Value::Object(_), id) => Some(id),
(automerge::Value::Scalar(_), _) => None,
}
}
let mut obj = automerge::ROOT;
let mut shape = shape;
for segment in segments {
match (shape, segment) {
(Shape::Record(fields), Segment::Field(key)) => {
shape = fields
.iter()
.find(|field| field.key == key)
.map_or(Shape::Value, |field| field.shape);
obj = child(doc, &obj, key)?;
}
(Shape::Collection(item), Segment::Item(id)) => {
let entry = child(doc, &obj, id.as_str())?;
obj = child(doc, &entry, crate::collection::VALUE)?;
shape = *item;
}
(Shape::Keyed(item), Segment::Item(id)) => {
obj = child(doc, &obj, id.as_str())?;
shape = *item;
}
(_, Segment::Field(key) | Segment::Key(key)) => {
obj = child(doc, &obj, key)?;
shape = Shape::Value;
}
(_, Segment::Item(id)) => {
obj = child(doc, &obj, id.as_str())?;
shape = Shape::Value;
}
(_, Segment::Cell { .. }) => return None,
}
}
Some(obj)
}
impl<R, T> Path<R, T> {
#[must_use]
pub fn from_segments(segments: Vec<Segment>) -> Self {
Self {
segments,
marker: PhantomData,
}
}
pub fn segments(&self) -> &[Segment] {
&self.segments
}
#[must_use]
pub fn into_segments(self) -> Vec<Segment> {
self.segments
}
#[doc(hidden)]
#[must_use]
#[inline]
pub fn child<U>(&self, segment: Segment) -> Path<R, U> {
Path::from_segments(extended(&self.segments, segment))
}
#[doc(hidden)]
#[must_use]
pub fn cast<U>(self) -> Path<R, U> {
Path::from_segments(self.segments)
}
#[must_use]
pub fn under<P>(&self, prefix: &Path<P, R>) -> Path<P, T> {
let mut segments = prefix.segments.clone();
segments.extend(self.segments.iter().cloned());
Path::from_segments(segments)
}
pub fn get<'a>(&self, root: &'a R) -> Option<&'a T>
where
R: Model + 'static,
T: 'static,
{
root.get_at(&self.segments)?.downcast_ref()
}
pub fn starts_with<U>(&self, other: &Path<R, U>) -> bool {
self.segments.starts_with(&other.segments)
}
#[must_use]
pub fn edits(&self, before: &T, after: &T) -> Vec<Edit<R>>
where
T: Model,
{
let mut found: Vec<Edit<()>> = Vec::new();
before.diff(after, &self.segments, &mut found);
retyped_all(found)
}
#[must_use]
#[inline]
pub fn edit(&self, op: EditOp) -> Edit<R> {
Edit {
path: self.segments.clone(),
op,
marker: PhantomData,
}
}
}
pub(crate) fn edit_risk(
shape: crate::Shape,
path: &[Segment],
op: &EditOp,
now: Option<&[(String, String)]>,
) -> tilo_actions::RiskLevel {
use tilo_action_policy::edits::{EditStep, field_edit_asks};
let mut steps: Vec<EditStep<'_>> = Vec::with_capacity(path.len());
for segment in path {
steps.push(match segment {
Segment::Field(key) => EditStep::Field(key),
Segment::Item(_) | Segment::Key(_) | Segment::Cell { .. } => EditStep::Item,
});
}
match shape.trust_at(path) {
crate::Trust::Ordinary => {}
crate::Trust::Weakens(weaker) => {
let at = tilo_action_policy::edits::dotted(&steps);
let weakens = match op {
EditOp::Set { value } => weaker.weakens(
now.and_then(|now| now.iter().find(|(path, _)| *path == at))
.map(|(_, now)| now.as_str()),
&value.to_string(),
),
_ => true,
};
if weakens {
return tilo_actions::RiskLevel::Privileged;
}
}
trust => return trust.risk(),
}
let quiet = shape.quiet_removals();
let quiet: Vec<&str> = quiet.iter().map(String::as_str).collect();
if field_edit_asks(op.name(), &steps, &quiet, &[]) {
tilo_actions::RiskLevel::Destructive
} else {
tilo_actions::RiskLevel::Low
}
}
fn extended(segments: &[Segment], segment: Segment) -> Vec<Segment> {
let mut extended = Vec::with_capacity(segments.len().saturating_add(1));
extended.extend_from_slice(segments);
extended.push(segment);
extended
}
impl<R, T> Clone for Path<R, T> {
fn clone(&self) -> Self {
Self::from_segments(self.segments.clone())
}
}
impl<R, T> std::fmt::Debug for Path<R, T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
fmt_segments(&self.segments, f)
}
}
fn fmt_segments(segments: &[Segment], f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("Path(")?;
for (index, segment) in segments.iter().enumerate() {
if index > 0 {
f.write_str(" › ")?;
}
write!(f, "{segment}")?;
}
f.write_str(")")
}
impl<R, T> PartialEq for Path<R, T> {
fn eq(&self, other: &Self) -> bool {
self.segments == other.segments
}
}
impl<R, T> Eq for Path<R, T> {}
impl<R, T> PartialOrd for Path<R, T> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<R, T> Ord for Path<R, T> {
fn cmp(&self, other: &Self) -> Ordering {
self.segments.cmp(&other.segments)
}
}
impl<R, T> Hash for Path<R, T> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.segments.hash(state);
}
}
impl<R, T> Serialize for Path<R, T> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.segments.serialize(serializer)
}
}
impl<'de, R, T> Deserialize<'de> for Path<R, T> {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let value = serde_json::Value::deserialize(deserializer)?;
match segments_from_json(value) {
Ok(segments) => Ok(Self::from_segments(segments)),
Err(error) => Err(serde::de::Error::custom(error)),
}
}
}
#[inline(never)]
fn segments_from_json(value: serde_json::Value) -> Result<Vec<Segment>, serde_json::Error> {
Vec::<Segment>::deserialize(value)
}
#[inline(never)]
fn edit_from_json(value: serde_json::Value) -> Result<(Vec<Segment>, EditOp), serde_json::Error> {
use serde::de::Error as _;
let serde_json::Value::Object(mut map) = value else {
return Err(serde_json::Error::custom("an edit is a JSON object"));
};
let path = map
.remove("path")
.ok_or_else(|| serde_json::Error::missing_field("path"))?;
let path = segments_from_json(path)?;
let op = op_from_json(serde_json::Value::Object(map))?;
Ok((path, op))
}
pub trait Settable: Model {}
impl<R, T: Settable> Path<R, T> {
#[must_use]
#[allow(
clippy::needless_pass_by_value,
reason = "a value is set as written: `set(true)`, `set(Language::Rust)`"
)]
pub fn set(&self, value: T) -> Edit<R> {
self.edit(EditOp::Set {
value: crate::shape::without_absent::<T>(value.to_json()),
})
}
}
pub trait Operations: Model {
type Op: Serialize + serde::de::DeserializeOwned + crate::JsonSchema;
fn coalesces(previous: &Self::Op, next: &Self::Op) -> bool {
let _ = (previous, next);
false
}
fn continuable(op: &Self::Op) -> bool {
let _ = op;
true
}
fn describe(op: &Self::Op) -> OpDescription {
let _ = op;
OpDescription::default()
}
fn lands(&self, op: &Self::Op) -> Option<crate::Place> {
let _ = op;
None
}
}
#[doc(hidden)]
pub fn op_coalesces<T: Operations>(
path: &[Segment],
previous: &serde_json::Value,
next: &serde_json::Value,
) -> Option<bool> {
if !path.is_empty() {
return None;
}
let previous = serde_json::from_value(previous.clone()).ok()?;
let next = serde_json::from_value(next.clone()).ok()?;
Some(T::coalesces(&previous, &next))
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct OpDescription {
pub op: tilo_actions::EditOp,
pub args: std::collections::BTreeMap<String, tilo_actions::Scalar>,
}
impl Default for OpDescription {
fn default() -> Self {
Self {
op: tilo_actions::EditOp::Mark,
args: std::collections::BTreeMap::new(),
}
}
}
#[doc(hidden)]
pub fn op_describe<T: Operations>(
path: &[Segment],
op: &serde_json::Value,
) -> Option<OpDescription> {
if !path.is_empty() {
return None;
}
Some(T::describe(&serde_json::from_value(op.clone()).ok()?))
}
#[doc(hidden)]
pub fn op_continuable<T: Operations>(path: &[Segment], op: &serde_json::Value) -> Option<bool> {
if !path.is_empty() {
return None;
}
Some(T::continuable(&serde_json::from_value(op.clone()).ok()?))
}
#[doc(hidden)]
pub fn op_lands<T: Operations>(
value: &T,
path: &[Segment],
op: &serde_json::Value,
) -> Option<crate::Place> {
if !path.is_empty() {
return None;
}
value.lands(&serde_json::from_value(op.clone()).ok()?)
}
#[macro_export]
macro_rules! operations_model {
() => {
const OPS: bool = true;
fn op_coalesces(
path: &[$crate::Segment],
previous: &$crate::__private::serde_json::Value,
next: &$crate::__private::serde_json::Value,
) -> ::core::option::Option<bool> {
$crate::path::op_coalesces::<Self>(path, previous, next)
}
fn op_continuable(
path: &[$crate::Segment],
op: &$crate::__private::serde_json::Value,
) -> ::core::option::Option<bool> {
$crate::path::op_continuable::<Self>(path, op)
}
fn op_describe(
path: &[$crate::Segment],
op: &$crate::__private::serde_json::Value,
) -> ::core::option::Option<$crate::path::OpDescription> {
$crate::path::op_describe::<Self>(path, op)
}
fn op_lands(
&self,
path: &[$crate::Segment],
op: &$crate::__private::serde_json::Value,
) -> ::core::option::Option<$crate::Place> {
$crate::path::op_lands::<Self>(self, path, op)
}
fn op_schemas(
prefix: &str,
out: &mut ::std::vec::Vec<(
::std::string::String,
$crate::__private::serde_json::Value,
)>,
) {
out.push((
::std::string::String::from(prefix.trim_end_matches('.')),
<<Self as $crate::Operations>::Op as $crate::JsonSchema>::json_schema(),
));
}
};
}
impl<R, T: Operations> Path<R, T> {
pub fn perform(&self, op: &T::Op) -> Result<Edit<R>, serde_json::Error> {
Ok(self.edit(EditOp::Rich {
rich: crate::__private::json_via_bytes(op)?,
}))
}
}
impl<R, T: Model> Path<R, Option<T>> {
#[must_use]
pub fn some(&self) -> T::Paths<R> {
T::paths_at(self.clone().cast())
}
}
impl<R> Path<R, String> {
#[must_use]
pub fn splice(&self, at: usize, delete: usize, insert: impl Into<String>) -> Edit<R> {
self.edit(EditOp::Splice {
at,
delete,
insert: insert.into(),
})
}
#[must_use]
pub fn replace(&self, text: impl Into<String>) -> Edit<R> {
self.edit(EditOp::Replace { text: text.into() })
}
}
impl<R> Path<R, crate::Counter> {
#[must_use]
pub fn add(&self, by: i64) -> Edit<R> {
self.edit(EditOp::Add { by })
}
}
impl<R, T: Model> Path<R, crate::Set<T>> {
#[must_use]
pub fn insert(&self, value: &T) -> Edit<R> {
self.edit(EditOp::Insert {
value: value.to_json(),
})
}
#[must_use]
pub fn remove(&self, value: &T) -> Edit<R> {
self.edit(EditOp::Remove {
value: value.to_json(),
})
}
}
impl<R, T: Model> Path<R, crate::Collection<T>> {
#[must_use]
pub fn item(&self, id: &Id) -> T::Paths<R> {
T::paths_at(self.child(Segment::Item(id.clone())))
}
#[must_use]
pub fn item_path(&self, id: &Id) -> Path<R, T> {
self.child(Segment::Item(id.clone()))
}
#[must_use]
pub fn insert(&self, at: usize, value: &T) -> Edit<R> {
self.edit(EditOp::InsertItem {
id: None,
at: At::Index(at),
value: crate::shape::without_absent::<T>(value.to_json()),
})
}
#[must_use]
pub fn insert_as(&self, id: &Id, at: usize, value: &T) -> Edit<R> {
self.edit(EditOp::InsertItem {
id: Some(id.clone()),
at: At::Index(at),
value: crate::shape::without_absent::<T>(value.to_json()),
})
}
#[must_use]
pub fn remove(&self, id: &Id) -> Edit<R> {
self.edit(EditOp::RemoveItem { id: id.clone() })
}
#[must_use]
pub fn move_to(&self, id: &Id, at: usize) -> Edit<R> {
self.edit(EditOp::MoveTo {
id: id.clone(),
at: At::Index(at),
})
}
#[must_use]
pub fn upsert_by(
&self,
matching: serde_json::Map<String, serde_json::Value>,
value: serde_json::Value,
) -> Edit<R> {
self.edit(EditOp::UpsertItem {
matching,
value,
id: None,
})
}
}
impl<R, T: Model> Path<R, std::collections::BTreeMap<String, T>> {
#[must_use]
pub fn key(&self, key: impl Into<String>) -> T::Paths<R> {
T::paths_at(self.child(Segment::Key(key.into())))
}
#[must_use]
pub fn remove(&self, key: impl Into<String>) -> Edit<R> {
self.edit(EditOp::RemoveKey { key: key.into() })
}
}
impl<R, T: Model> Path<R, crate::Grid<T>> {
#[must_use]
pub fn cell(&self, row: &Id, column: &Id) -> T::Paths<R> {
T::paths_at(self.child(Segment::Cell {
row: row.clone(),
column: column.clone(),
}))
}
#[must_use]
pub fn set_cell(&self, row: &Id, column: &Id, value: Option<&T>) -> Edit<R> {
self.edit(EditOp::SetCell {
row: row.clone(),
column: column.clone(),
value: value.map(|value| crate::shape::without_absent::<T>(value.to_json())),
})
}
#[must_use]
pub fn insert_row(&self, at: usize) -> Edit<R> {
self.edit(EditOp::InsertRow { id: None, at })
}
#[must_use]
pub fn insert_column(&self, at: usize) -> Edit<R> {
self.edit(EditOp::InsertColumn { id: None, at })
}
#[must_use]
pub fn remove_row(&self, row: &Id) -> Edit<R> {
self.edit(EditOp::RemoveRow { id: row.clone() })
}
#[must_use]
pub fn remove_column(&self, column: &Id) -> Edit<R> {
self.edit(EditOp::RemoveColumn { id: column.clone() })
}
}
impl<R, T: Model, O: Serialize + serde::de::DeserializeOwned + Default + 'static>
Path<R, crate::Outbox<T, O>>
{
#[must_use]
pub fn settle(&self, id: &Id, outcome: &crate::Settled<O>) -> Edit<R> {
self.edit(EditOp::Settle {
id: id.clone(),
outcome: Model::to_json(outcome),
})
}
#[must_use]
pub fn forget(&self, id: &Id) -> Edit<R> {
self.edit(EditOp::Forget { id: id.clone() })
}
}
impl<R> Path<R, crate::Reactions> {
#[must_use]
pub fn react(&self, emoji: impl Into<String>) -> Edit<R> {
self.edit(EditOp::React {
emoji: emoji.into(),
})
}
#[must_use]
pub fn unreact(&self, emoji: impl Into<String>) -> Edit<R> {
self.edit(EditOp::Unreact {
emoji: emoji.into(),
})
}
}
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(tag = "op", rename_all = "kebab-case")]
pub enum EditOp {
Set {
value: serde_json::Value,
},
Splice {
at: usize,
delete: usize,
insert: String,
},
Replace {
text: String,
},
Add {
by: i64,
},
Insert {
value: serde_json::Value,
},
Remove {
value: serde_json::Value,
},
InsertItem {
#[serde(default, skip_serializing_if = "Option::is_none")]
id: Option<Id>,
at: At,
value: serde_json::Value,
},
UpsertItem {
#[serde(rename = "match")]
matching: serde_json::Map<String, serde_json::Value>,
value: serde_json::Value,
#[serde(default, skip_serializing_if = "Option::is_none")]
id: Option<Id>,
},
RemoveItem {
id: Id,
},
MoveTo {
id: Id,
at: At,
},
RemoveKey {
key: String,
},
SetCell {
row: Id,
column: Id,
#[serde(default, skip_serializing_if = "Option::is_none")]
value: Option<serde_json::Value>,
},
InsertRow {
#[serde(default, skip_serializing_if = "Option::is_none")]
id: Option<Id>,
at: usize,
},
InsertColumn {
#[serde(default, skip_serializing_if = "Option::is_none")]
id: Option<Id>,
at: usize,
},
RemoveRow {
id: Id,
},
RemoveColumn {
id: Id,
},
Settle {
id: Id,
outcome: serde_json::Value,
},
Forget {
id: Id,
},
React {
emoji: String,
},
Unreact {
emoji: String,
},
Rich {
rich: serde_json::Value,
},
}
impl<'de> Deserialize<'de> for EditOp {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let value = serde_json::Value::deserialize(deserializer)?;
match op_from_json(value) {
Ok(op) => Ok(op),
Err(error) => Err(serde::de::Error::custom(error)),
}
}
}
#[derive(Deserialize)]
#[serde(rename_all = "kebab-case")]
enum EditOpWire {
Set {
value: serde_json::Value,
},
Splice {
at: usize,
delete: usize,
insert: String,
},
Replace {
text: String,
},
Add {
by: i64,
},
Insert {
value: serde_json::Value,
},
Remove {
value: serde_json::Value,
},
InsertItem {
#[serde(default)]
id: Option<Id>,
#[serde(default)]
at: At,
value: serde_json::Value,
},
UpsertItem {
#[serde(rename = "match")]
matching: serde_json::Map<String, serde_json::Value>,
value: serde_json::Value,
#[serde(default)]
id: Option<Id>,
},
RemoveItem {
id: Id,
},
MoveTo {
id: Id,
#[serde(default)]
at: At,
},
RemoveKey {
key: String,
},
SetCell {
row: Id,
column: Id,
#[serde(default)]
value: Option<serde_json::Value>,
},
InsertRow {
#[serde(default)]
id: Option<Id>,
at: usize,
},
InsertColumn {
#[serde(default)]
id: Option<Id>,
at: usize,
},
RemoveRow {
id: Id,
},
RemoveColumn {
id: Id,
},
Settle {
id: Id,
outcome: serde_json::Value,
},
Forget {
id: Id,
},
React {
emoji: String,
},
Unreact {
emoji: String,
},
Rich {
rich: serde_json::Value,
},
}
impl From<EditOpWire> for EditOp {
fn from(wire: EditOpWire) -> Self {
match wire {
EditOpWire::Set { value } => Self::Set { value },
EditOpWire::Splice { at, delete, insert } => Self::Splice { at, delete, insert },
EditOpWire::Replace { text } => Self::Replace { text },
EditOpWire::Add { by } => Self::Add { by },
EditOpWire::Insert { value } => Self::Insert { value },
EditOpWire::Remove { value } => Self::Remove { value },
EditOpWire::InsertItem { id, at, value } => Self::InsertItem { id, at, value },
EditOpWire::UpsertItem {
matching,
value,
id,
} => Self::UpsertItem {
matching,
value,
id,
},
EditOpWire::RemoveItem { id } => Self::RemoveItem { id },
EditOpWire::MoveTo { id, at } => Self::MoveTo { id, at },
EditOpWire::RemoveKey { key } => Self::RemoveKey { key },
EditOpWire::SetCell { row, column, value } => Self::SetCell { row, column, value },
EditOpWire::InsertRow { id, at } => Self::InsertRow { id, at },
EditOpWire::InsertColumn { id, at } => Self::InsertColumn { id, at },
EditOpWire::RemoveRow { id } => Self::RemoveRow { id },
EditOpWire::RemoveColumn { id } => Self::RemoveColumn { id },
EditOpWire::Settle { id, outcome } => Self::Settle { id, outcome },
EditOpWire::Forget { id } => Self::Forget { id },
EditOpWire::React { emoji } => Self::React { emoji },
EditOpWire::Unreact { emoji } => Self::Unreact { emoji },
EditOpWire::Rich { rich } => Self::Rich { rich },
}
}
}
#[inline(never)]
fn op_from_json(value: serde_json::Value) -> Result<EditOp, serde_json::Error> {
use serde::de::Error as _;
let serde_json::Value::Object(mut fields) = value else {
return Err(serde_json::Error::custom(
"an edit operation is a JSON object",
));
};
let Some(serde_json::Value::String(op)) = fields.remove("op") else {
return Err(serde_json::Error::missing_field("op"));
};
let mut tagged = serde_json::Map::new();
tagged.insert(op, serde_json::Value::Object(fields));
EditOpWire::deserialize(serde_json::Value::Object(tagged)).map(EditOp::from)
}
pub const OP_ARGUMENTS: &[(&str, &[&str], &[&str])] = &[
("set", &["value"], &[]),
("splice", &["at", "delete", "insert"], &[]),
("replace", &["text"], &[]),
("add", &["by"], &[]),
("insert", &["value"], &[]),
("remove", &["value"], &[]),
("insert-item", &["value"], &["id", "at"]),
("upsert-item", &["match", "value"], &["id"]),
("remove-item", &["id"], &[]),
("move-to", &["id"], &["at"]),
("remove-key", &["key"], &[]),
("set-cell", &["row", "column"], &["value"]),
("insert-row", &["at"], &["id"]),
("insert-column", &["at"], &["id"]),
("remove-row", &["id"], &[]),
("remove-column", &["id"], &[]),
("settle", &["id", "outcome"], &[]),
("forget", &["id"], &[]),
("react", &["emoji"], &[]),
("unreact", &["emoji"], &[]),
("rich", &["rich"], &[]),
];
#[must_use]
pub fn op_arguments(op: &str) -> Option<(&'static [&'static str], &'static [&'static str])> {
OP_ARGUMENTS
.iter()
.find(|(name, ..)| *name == op)
.map(|(_, required, optional)| (*required, *optional))
}
#[must_use]
pub fn op_argument_schema(op: &str, argument: &str) -> serde_json::Value {
let described = |schema: serde_json::Value, description: &str| {
let mut schema = schema;
if let Some(object) = schema.as_object_mut() {
object.insert("description".into(), description.into());
}
schema
};
match (op, argument) {
("splice", "delete") => described(
serde_json::json!({ "type": "integer", "minimum": 0 }),
"splice: how many characters it replaces",
),
("splice", "insert") => described(
serde_json::json!({ "type": "string" }),
"splice: the text it puts there",
),
(_, "at") => serde_json::json!({
"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",
"oneOf": [
{ "const": "end" },
{ "type": "object", "properties": { "after": { "type": "string" } }, "required": ["after"] },
{ "type": "object", "properties": { "before": { "type": "string" } }, "required": ["before"] },
{ "type": "integer", "minimum": 0 }
]
}),
(_, "text") => described(
serde_json::json!({ "type": "string" }),
"replace: the whole new text; rich text takes markdown",
),
(_, "by") => described(serde_json::json!({ "type": "integer" }), "add: how much"),
(_, "id") => described(
serde_json::json!({ "type": "string" }),
"remove-item, move-to, remove-row, remove-column, settle, forget: the item's id; \
insert-item, upsert-item, insert-row, insert-column: the new item's id, minted without",
),
(_, "key") => described(
serde_json::json!({ "type": "string" }),
"remove-key: the entry's key",
),
(_, "row" | "column") => described(
serde_json::json!({ "type": "string" }),
"set-cell: the cell's row and column ids",
),
(_, "outcome") => described(
serde_json::json!({ "type": "object" }),
"settle: how the entry settled",
),
(_, "emoji") => described(
serde_json::json!({ "type": "string" }),
"react, unreact: a Unicode emoji, or a workspace emoji as :name:",
),
(_, "match") => serde_json::json!({
"type": "object",
"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"
}),
(_, "rich") => described(
serde_json::json!({ "type": "object" }),
"rich: an edit in the field type's own vocabulary",
),
_ => serde_json::json!({}),
}
}
#[must_use]
pub fn op_usage(op: &str) -> String {
let Some((required, optional)) = op_arguments(op) else {
return op.to_owned();
};
if required == ["value"] && optional.is_empty() {
return op.to_owned();
}
let arguments: Vec<String> = required
.iter()
.map(|argument| (*argument).to_owned())
.chain(optional.iter().map(|argument| format!("{argument}?")))
.collect();
if arguments.is_empty() {
op.to_owned()
} else {
format!("{op} {{{}}}", arguments.join(", "))
}
}
impl EditOp {
#[must_use]
pub const fn name(&self) -> &'static str {
match self {
Self::Set { .. } => "set",
Self::Splice { .. } => "splice",
Self::Replace { .. } => "replace",
Self::Add { .. } => "add",
Self::Insert { .. } => "insert",
Self::Remove { .. } => "remove",
Self::InsertItem { .. } => "insert-item",
Self::UpsertItem { .. } => "upsert-item",
Self::RemoveItem { .. } => "remove-item",
Self::MoveTo { .. } => "move-to",
Self::RemoveKey { .. } => "remove-key",
Self::SetCell { .. } => "set-cell",
Self::InsertRow { .. } => "insert-row",
Self::InsertColumn { .. } => "insert-column",
Self::RemoveRow { .. } => "remove-row",
Self::RemoveColumn { .. } => "remove-column",
Self::Settle { .. } => "settle",
Self::Forget { .. } => "forget",
Self::React { .. } => "react",
Self::Unreact { .. } => "unreact",
Self::Rich { .. } => "rich",
}
}
#[must_use]
pub const fn removes(&self) -> bool {
matches!(
self,
Self::RemoveItem { .. }
| Self::RemoveKey { .. }
| Self::RemoveRow { .. }
| Self::RemoveColumn { .. }
)
}
}
pub struct Edit<R> {
path: Vec<Segment>,
op: EditOp,
marker: PhantomData<fn() -> R>,
}
impl<R> Edit<R> {
#[must_use]
pub fn new(path: Vec<Segment>, op: EditOp) -> Self {
Self {
path,
op,
marker: PhantomData,
}
}
pub fn path(&self) -> &[Segment] {
&self.path
}
pub fn op(&self) -> &EditOp {
&self.op
}
#[must_use]
pub fn retyped<S>(self) -> Edit<S> {
Edit::new(self.path, self.op)
}
pub fn from_json(value: serde_json::Value) -> Result<Self, String> {
match edit_from_json(value) {
Ok((path, op)) => Ok(Self::new(path, op)),
Err(error) => Err(error.to_string()),
}
}
pub(crate) fn past_resource_name(
self,
root: crate::Shape,
names: &[&str],
) -> Result<Self, String> {
let fields = root.fields();
let Some((Segment::Field(head), rest)) = self.path.split_first() else {
return Ok(self);
};
if fields.iter().any(|field| field.key == head)
|| !names.iter().any(|name| name.eq_ignore_ascii_case(head))
{
return Ok(self);
}
let Some(start) = rest.first() else {
let editable: Vec<&str> = fields
.iter()
.filter(|field| !field.readonly)
.map(|field| field.key)
.collect();
return Err(format!(
"`{head}` is the resource itself, not one of its fields: start the path at the field to change, one of {}",
editable.join(", ")
));
};
if root.trust_at(rest) != crate::Trust::Ordinary {
return Err(format!(
"`{head}` is the resource itself, not one of its fields: start the path at `{start}`"
));
}
Ok(Self::new(rest.to_vec(), self.op))
}
#[must_use]
pub fn coalesces(&self, next: &Self) -> bool
where
R: Model,
{
edits_coalesce(
(&self.path, &self.op),
(&next.path, &next.op),
R::op_coalesces,
)
}
#[must_use]
pub fn risk(&self) -> tilo_actions::RiskLevel
where
R: Model,
{
edit_risk(R::SHAPE, &self.path, &self.op, None)
}
#[must_use]
pub fn tree_path(
&self,
workspace: &str,
app: &str,
record: &str,
) -> tilo_action_policy::TreePath
where
R: crate::Resource,
{
use tilo_action_policy::Level;
let mut tree = tilo_action_policy::TreePath::workspace(workspace)
.app(app)
.kind(R::KIND)
.resource(record);
let mut item = false;
let mut segments = self.path.iter().peekable();
while let Some(segment) = segments.next() {
tree = match segment {
Segment::Field(_) if !item && matches!(segments.peek(), Some(Segment::Item(_))) => {
tree
}
Segment::Item(id) if !item => {
item = true;
tree.item(id.as_str())
}
Segment::Field(key) | Segment::Key(key) => tree.push(Level::Field, key.as_str()),
Segment::Item(id) => tree.push(Level::Field, id.as_str()),
Segment::Cell { row, column } => tree
.push(Level::Field, row.as_str())
.push(Level::Field, column.as_str()),
};
}
tree.action(crate::FIELD_EDIT)
}
pub fn apply_local(&self, doc: &mut crate::Doc) -> Result<(), crate::ModelError>
where
R: crate::Fields,
{
let payload = serde_json::to_vec(self)
.map_err(|error| crate::ModelError::invalid(error.to_string()))?;
let mut cx = crate::ActionCx::for_write(doc, &payload);
self.apply(doc, &mut cx)
}
pub fn apply(
&self,
doc: &mut crate::Doc,
cx: &mut crate::ActionCx,
) -> Result<(), crate::ModelError>
where
R: crate::Fields,
{
R::edit_fields(doc, &automerge::ROOT, &self.path, &self.op, cx)
}
}
#[inline(never)]
fn edits_coalesce(
(previous_path, previous_op): (&[Segment], &EditOp),
(next_path, next_op): (&[Segment], &EditOp),
rich: fn(&[Segment], &serde_json::Value, &serde_json::Value) -> Option<bool>,
) -> bool {
if previous_path != next_path {
return false;
}
match (previous_op, next_op) {
(EditOp::Rich { rich: previous }, EditOp::Rich { rich: next }) => {
rich(previous_path, previous, next).unwrap_or(false)
}
(EditOp::Set { .. }, EditOp::Set { .. }) | (EditOp::Add { .. }, EditOp::Add { .. }) => true,
(EditOp::Replace { text: previous }, EditOp::Replace { text: next }) => {
replace_continues(previous, next)
}
(
EditOp::Splice {
at, delete, insert, ..
},
EditOp::Splice {
at: next_at,
delete: next_delete,
insert: next_insert,
},
) => {
let typed = insert.chars().count();
let typing = *delete == 0
&& *next_delete == 0
&& !next_insert.is_empty()
&& *next_at == at.saturating_add(typed)
&& !insert.ends_with(char::is_whitespace);
let erasing = insert.is_empty()
&& next_insert.is_empty()
&& next_at.saturating_add(*next_delete) == *at;
typing || erasing
}
_ => false,
}
}
impl<R> Clone for Edit<R> {
fn clone(&self) -> Self {
let (path, op) = clone_edit(&self.path, &self.op);
Self::new(path, op)
}
}
#[inline(never)]
fn clone_edit(path: &[Segment], op: &EditOp) -> (Vec<Segment>, EditOp) {
(path.to_vec(), op.clone())
}
impl<R> std::fmt::Debug for Edit<R> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
fmt_edit(&self.path, &self.op, f)
}
}
fn fmt_edit(path: &[Segment], op: &EditOp, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Edit")
.field("path", &Path::<(), ()>::from_segments(path.to_vec()))
.field("op", op)
.finish()
}
impl<R> PartialEq for Edit<R> {
fn eq(&self, other: &Self) -> bool {
self.path == other.path && self.op == other.op
}
}
impl<R> Serialize for Edit<R> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
edit_to_json(&self.path, &self.op).serialize(serializer)
}
}
#[must_use]
pub fn outbox_settle_arguments(
field: &str,
id: &str,
outcome: &serde_json::Value,
) -> serde_json::Map<String, serde_json::Value> {
let op = EditOp::Settle {
id: Id::from_raw(id),
outcome: outcome.clone(),
};
let edit = edit_to_json(&[Segment::Field(field.to_owned())], &op);
serde_json::Map::from_iter([(crate::EDIT_PARAM.to_owned(), edit)])
}
#[inline(never)]
fn edit_to_json(path: &[Segment], op: &EditOp) -> serde_json::Value {
let mut form = crate::__private::json_via_bytes(op).unwrap_or_default();
if let serde_json::Value::Object(map) = &mut form {
map.insert(
"path".into(),
crate::__private::json_via_bytes(path).unwrap_or_default(),
);
}
form
}
impl<'de, R> Deserialize<'de> for Edit<R> {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let value = serde_json::Value::deserialize(deserializer)?;
match edit_from_json(value) {
Ok((path, op)) => Ok(Self::new(path, op)),
Err(error) => Err(serde::de::Error::custom(error)),
}
}
}
impl<R> crate::JsonSchema for Edit<R> {
fn json_schema() -> serde_json::Value {
edit_schema()
}
}
fn edit_schema() -> serde_json::Value {
edit_schema_taking(|_| true)
}
#[inline(never)]
pub(crate) fn edit_schema_taking(takes: impl Fn(&str) -> bool) -> serde_json::Value {
let offered: Vec<&(&str, &[&str], &[&str])> =
OP_ARGUMENTS.iter().filter(|(op, ..)| takes(op)).collect();
let ops: Vec<&str> = offered.iter().map(|(op, ..)| *op).collect();
let mut properties = serde_json::Map::new();
properties.insert(
"path".into(),
serde_json::json!({ "type": "array", "items": {"type": "object"} }),
);
properties.insert(
"op".into(),
serde_json::json!({ "type": "string", "enum": ops }),
);
let mut needs = Vec::new();
for (op, required, optional) in offered {
for argument in required.iter().chain(optional.iter()) {
if !properties.contains_key(*argument) {
properties.insert((*argument).to_owned(), op_argument_schema(op, argument));
}
}
let mut needed = vec!["path", "op"];
needed.extend(required.iter().copied());
needs.push(serde_json::json!({
"properties": { "op": { "const": op } },
"required": needed,
}));
}
serde_json::json!({
"type": "object",
"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",
"properties": properties,
"required": ["path", "op"],
"oneOf": needs,
})
}
#[must_use]
pub fn retyped_all<R>(edits: Vec<Edit<()>>) -> Vec<Edit<R>> {
let mut out = Vec::with_capacity(edits.len());
for edit in edits {
out.push(edit.retyped());
}
out
}
#[doc(hidden)]
pub fn leaf<R, T>(path: Path<R, T>) -> Path<R, T> {
path
}
fn replace_continues(previous: &str, next: &str) -> bool {
let (was, now): (Vec<char>, Vec<char>) = (previous.chars().collect(), next.chars().collect());
let (prefix, suffix) = crate::text::common_ends(&was, &now);
let (before, after) = (was.len(), now.len());
let kept = prefix.saturating_add(suffix);
let deleted = before.saturating_sub(kept);
let inserted = after.saturating_sub(kept);
match (deleted, inserted) {
(1.., 0) => true,
(0, 1) => prefix
.checked_sub(1)
.and_then(|at| was.get(at))
.is_some_and(|c| !c.is_whitespace()),
_ => false,
}
}