tilo-resource 0.5.1

The Tilo resource layer: typed, hierarchical app resources.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
//! What a record's actions did, as history records it: read from the
//! document before the action applies, through the record's stored shape,
//! without reading the record whole — and, for an item the action makes, from
//! the document once it wrote it.

use automerge::{ObjId, ObjType, ROOT, ReadDoc, ScalarValue, Value};
use tilo_actions::{ActionKey, Described, Did, FieldEdit, PathStep, Scalar};
use tilo_sort::CompactSort as _;

use crate::model::Doc;
use crate::path::{Edit, EditOp, Segment};
use crate::shape::Shape;

/// Where a path leads in the document.
struct Located {
    /// What the path's slot holds, if anything.
    value: Option<(Value<'static>, ObjId)>,
    /// The record type owning the last field on the path, and its key.
    owner: Option<(&'static str, String)>,
    /// The last item on the path: its id and label.
    item: Option<(String, Option<String>)>,
    shape: Shape,
    /// What the last field on the path reads as while absent, for a scalar.
    absent: Option<fn() -> Option<serde_json::Value>>,
}

fn get(doc: &Doc, obj: &ObjId, key: &str) -> Option<(Value<'static>, ObjId)> {
    doc.get(obj, key)
        .ok()
        .flatten()
        .map(|(value, id)| (value.to_owned(), id))
}

fn map_at(doc: &Doc, obj: &ObjId, key: &str) -> Option<ObjId> {
    match get(doc, obj, key)? {
        (Value::Object(ObjType::Map), id) => Some(id),
        _ => None,
    }
}

/// The label of the record of shape `shape` stored in the map `obj`: the
/// texts of its label fields joined by spaces, else its `#[model(label)]`
/// field's.
fn label_of(doc: &Doc, shape: Shape, obj: &ObjId) -> Option<String> {
    let mut parts: Vec<_> = shape
        .fields()
        .iter()
        .filter(|field| field.label_part > 0)
        .collect();
    parts.compact_sort_by_key(|field| field.label_part);
    let joined: Vec<String> = parts
        .iter()
        .filter_map(|field| field_text(doc, obj, field))
        .collect();
    if !joined.is_empty() {
        return Some(joined.join(" "));
    }
    let field = shape.fields().iter().find(|field| field.label)?;
    field_text(doc, obj, field)
}

/// The first line of the text `field` holds in the map `obj`, read as its
/// type stores it (a rich text's first paragraph too).
fn field_text(doc: &Doc, obj: &ObjId, field: &crate::FieldShape) -> Option<String> {
    let (value, id) = get(doc, obj, field.key)?;
    (field.text)(doc, &value, &id)
}

fn locate(doc: &Doc, root: Shape, path: &[Segment]) -> Located {
    let mut located = Located {
        value: Some((Value::Object(ObjType::Map), ROOT)),
        owner: None,
        item: None,
        shape: root,
        absent: None,
    };
    let mut shape = root;
    for segment in path {
        let Some((Value::Object(_), obj)) = located.value.take() else {
            break;
        };
        located.absent = None;
        match (shape, segment) {
            (Shape::Record(fields), Segment::Field(key)) => {
                if let Some(field) = fields.iter().find(|field| field.key == key) {
                    located.owner = Some((field.owner, key.clone()));
                    located.absent = Some(field.absent);
                    shape = field.shape;
                } else {
                    shape = Shape::Value;
                }
                located.value = get(doc, &obj, key);
            }
            (Shape::Collection(item) | Shape::Keyed(item), Segment::Item(id)) => {
                let value = if matches!(shape, Shape::Keyed(_)) {
                    get(doc, &obj, id.as_str())
                } else {
                    map_at(doc, &obj, id.as_str()).and_then(|entry| get(doc, &entry, "v"))
                };
                let label = match &value {
                    Some((Value::Object(ObjType::Map), map)) => label_of(doc, *item, map),
                    _ => None,
                };
                located.item = Some((id.as_str().to_owned(), label));
                located.value = value;
                shape = *item;
            }
            (Shape::Map(value), Segment::Key(key)) => {
                let entry = get(doc, &obj, key);
                let label = match &entry {
                    Some((Value::Object(ObjType::Map), map)) => label_of(doc, *value, map),
                    _ => None,
                };
                located.item = Some((key.clone(), label));
                located.value = entry;
                shape = *value;
            }
            (_, Segment::Key(key)) => {
                located.value = get(doc, &obj, key);
                shape = Shape::Value;
            }
            (_, Segment::Cell { row, column }) => {
                located.value = map_at(doc, &obj, "cells")
                    .and_then(|cells| get(doc, &cells, &format!("{row}/{column}")));
                shape = Shape::Value;
            }
            _ => {
                located.value = None;
                shape = Shape::Value;
            }
        }
    }
    located.shape = shape;
    located
}

/// The label an item written as `value` (its JSON form) carries, for a
/// collection item of shape `item`.
fn label_in(item: Shape, value: &serde_json::Value) -> Option<String> {
    let text = |key: &str| {
        value
            .get(key)?
            .as_str()?
            .lines()
            .next()
            .map(|line| line.trim().to_owned())
            .filter(|line| !line.is_empty())
    };
    let mut parts: Vec<_> = item
        .fields()
        .iter()
        .filter(|field| field.label_part > 0)
        .collect();
    parts.compact_sort_by_key(|field| field.label_part);
    let joined: Vec<String> = parts.iter().filter_map(|field| text(field.key)).collect();
    if !joined.is_empty() {
        return Some(joined.join(" "));
    }
    text(item.fields().iter().find(|field| field.label)?.key)
}

fn scalar(value: &Value<'_>) -> Option<Scalar> {
    let Value::Scalar(scalar) = value else {
        return None;
    };
    let json = match scalar.as_ref() {
        ScalarValue::Str(text) => serde_json::Value::String(text.to_string()),
        ScalarValue::Int(value) => (*value).into(),
        ScalarValue::Uint(value) => (*value).into(),
        ScalarValue::F64(value) => serde_json::Number::from_f64(*value)?.into(),
        ScalarValue::Counter(counter) => i64::from(counter).into(),
        ScalarValue::Boolean(value) => (*value).into(),
        _ => return None,
    };
    Scalar::from_json(&json)
}

fn step(segment: &Segment) -> PathStep {
    match segment {
        Segment::Field(key) => PathStep::Field(key.clone()),
        Segment::Item(id) => PathStep::Item(id.as_str().to_owned()),
        Segment::Key(key) => PathStep::Key(key.clone()),
        Segment::Cell { row, column } => {
            PathStep::Cell(row.as_str().to_owned(), column.as_str().to_owned())
        }
    }
}

const fn operation(op: &EditOp) -> tilo_actions::EditOp {
    use tilo_actions::EditOp as Recorded;
    match op {
        EditOp::Set { .. } | EditOp::UpsertItem { .. } => Recorded::Set,
        EditOp::Settle { .. } => Recorded::Settle,
        EditOp::Forget { .. } => Recorded::Forget,
        EditOp::Splice { .. } => Recorded::Splice,
        EditOp::Replace { .. } => Recorded::Replace,
        EditOp::Add { .. } => Recorded::Add,
        EditOp::Insert { .. } | EditOp::InsertItem { .. } => Recorded::Insert,
        EditOp::Remove { .. } | EditOp::RemoveItem { .. } | EditOp::RemoveKey { .. } => {
            Recorded::Remove
        }
        EditOp::MoveTo { .. } => Recorded::MoveTo,
        EditOp::SetCell { .. } => Recorded::SetCell,
        EditOp::InsertRow { .. } => Recorded::InsertRow,
        EditOp::InsertColumn { .. } => Recorded::InsertColumn,
        EditOp::RemoveRow { .. } => Recorded::RemoveRow,
        EditOp::RemoveColumn { .. } => Recorded::RemoveColumn,
        EditOp::React { .. } => Recorded::React,
        EditOp::Unreact { .. } => Recorded::Unreact,
        EditOp::Rich { .. } => Recorded::Mark,
    }
}

/// The item an insert or upsert of `value` (found by `matching`) under `id`
/// names: its id, else its label, with its label.
fn added_item(
    item: Shape,
    value: &serde_json::Value,
    matching: Option<&serde_json::Map<String, serde_json::Value>>,
    id: Option<&crate::Id>,
) -> Option<(String, Option<String>)> {
    let label = label_in(item, value).or_else(|| {
        matching.and_then(|matching| label_in(item, &serde_json::Value::Object(matching.clone())))
    });
    let id = id
        .map(|id| id.as_str().to_owned())
        .or_else(|| label.clone());
    id.map(|id| (id, label))
}

/// A field edit of a record of shape `shape`, as it reads before it applies.
pub(crate) fn edit<R: crate::Model>(doc: &Doc, shape: Shape, edit: &Edit<R>) -> Option<Described> {
    edit_at(doc, shape, edit.path(), edit.op(), R::op_describe)
}

/// [`edit`] past its one typed step, describing a `rich` operation.
#[inline(never)]
fn edit_at(
    doc: &Doc,
    shape: Shape,
    path: &[crate::Segment],
    op: &EditOp,
    op_describe: fn(&[crate::Segment], &serde_json::Value) -> Option<crate::path::OpDescription>,
) -> Option<Described> {
    let located = locate(doc, shape, path);
    let (owner, field) = located.owner?;
    // A scalar field never written reads as its absent value.
    let old = match &located.value {
        Some((value, _)) => scalar(value),
        None => located
            .absent
            .and_then(|absent| absent())
            .and_then(|value| Scalar::from_json(&value)),
    };
    let new = match op {
        // A set's value, or the element a set gained or lost.
        EditOp::Set { value } | EditOp::Insert { value } | EditOp::Remove { value } => {
            Scalar::from_json(value)
        }
        // A text written whole (a formula, a title) is what it reads now:
        // a reader names it without the document, and elides it to fit.
        EditOp::Replace { text } => Some(Scalar::whole_text(text)),
        // The emoji a reaction gave or took back.
        EditOp::React { emoji } | EditOp::Unreact { emoji } => {
            Scalar::from_json(&serde_json::Value::String(emoji.clone()))
        }
        EditOp::Add { by } => old
            .as_ref()
            .and_then(|old| crate::__private::json_via_bytes(old).ok())
            .and_then(|old| old.as_i64())
            .map(|old| Scalar::from_json(&old.saturating_add(*by).into()))
            .unwrap_or_default(),
        _ => None,
    };
    // An item added or removed is the item the entry is about, unless the
    // collection sits inside an item (a playlist's songs).
    let item = match (op, located.shape) {
        _ if located.item.is_some() => located.item.clone(),
        (EditOp::InsertItem { id, value, .. }, Shape::Collection(item) | Shape::Keyed(item)) => {
            added_item(*item, value, None, id.as_ref())
        }
        (
            EditOp::UpsertItem {
                matching,
                value,
                id,
            },
            Shape::Collection(item) | Shape::Keyed(item),
        ) => added_item(*item, value, Some(matching), id.as_ref()),
        (EditOp::RemoveItem { id }, Shape::Collection(item) | Shape::Keyed(item)) => {
            let stored = match &located.value {
                Some((Value::Object(ObjType::Map), collection)) => {
                    if matches!(located.shape, Shape::Keyed(_)) {
                        map_at(doc, collection, id.as_str())
                    } else {
                        map_at(doc, collection, id.as_str())
                            .and_then(|entry| map_at(doc, &entry, "v"))
                    }
                }
                _ => None,
            };
            let label = stored.and_then(|map| label_of(doc, *item, &map));
            Some((id.as_str().to_owned(), label))
        }
        // An entry removed from a map is the entry the entry is about.
        (EditOp::RemoveKey { key }, Shape::Map(value)) => {
            let label = match &located.value {
                Some((Value::Object(ObjType::Map), map)) => {
                    map_at(doc, map, key).and_then(|entry| label_of(doc, *value, &entry))
                }
                _ => None,
            };
            Some((key.clone(), label))
        }
        _ => located.item.clone(),
    };
    let rich = match op {
        EditOp::Rich { rich } => op_describe(path, rich),
        _ => None,
    };
    if let EditOp::Settle { id, .. } | EditOp::Forget { id } = op {
        return Some(outbox_edit(owner, field, path, op, id));
    }
    let described = Described::new(Did::Edit(FieldEdit {
        ty: owner.to_owned(),
        field,
        path: path.iter().map(step).collect(),
        op: match op {
            EditOp::Rich { .. } => rich
                .as_ref()
                .map_or(tilo_actions::EditOp::Mark, |described| described.op),
            op => operation(op),
        },
        args: rich.map(|described| described.args).unwrap_or_default(),
        old: matches!(op, EditOp::Set { .. } | EditOp::Add { .. })
            .then_some(old)
            .flatten(),
        new,
    }));
    Some(match item {
        Some((id, label)) => {
            let label = label.unwrap_or_else(|| id.clone());
            described.on(id, label)
        }
        None => described,
    })
}

/// An outbox entry settled or forgotten: the entry's id ends the path, and a
/// settlement names its state (`done`, `failed`) and reason.
fn outbox_edit(
    owner: &str,
    field: String,
    path: &[crate::Segment],
    op: &EditOp,
    id: &crate::Id,
) -> Described {
    let mut path: Vec<PathStep> = path.iter().map(step).collect();
    path.push(PathStep::Item(id.as_str().to_owned()));
    let mut args = std::collections::BTreeMap::new();
    if let EditOp::Settle { outcome, .. } = op {
        if let Some(state) = outcome.get("state").and_then(Scalar::from_json) {
            args.insert("state".to_owned(), state);
        }
        if let Some(reason) = outcome
            .get("result")
            .and_then(|result| result.get("reason"))
            .and_then(Scalar::from_json)
        {
            args.insert("reason".to_owned(), reason);
        }
    }
    Described::new(Did::Edit(FieldEdit {
        ty: owner.to_owned(),
        field,
        path,
        op: operation(op),
        args,
        old: None,
        new: None,
    }))
}

/// A verb of a record of shape `shape` and kind `kind`, from its JSON form
/// (`{"action": id, "args": {..}}`): its plain arguments by name and the
/// item its first id argument names in one of the record's collections.
pub(crate) fn verb(
    doc: &Doc,
    shape: Shape,
    kind: &str,
    value: &serde_json::Value,
) -> Option<Described> {
    let id = value.get("action")?.as_str()?;
    let args = value
        .get("args")
        .and_then(serde_json::Value::as_object)
        .cloned()
        .unwrap_or_default();
    // Plain arguments by name; a record argument by its fields, one level
    // deep (`receipt.completed`). Text is kept whole, as passed
    // ([`Scalar::argument`]).
    let mut plain: Vec<(String, Scalar)> = Vec::new();
    for (name, value) in &args {
        match value {
            serde_json::Value::Object(fields) => {
                for (field, value) in fields {
                    if let Some(scalar) = Scalar::argument(value) {
                        plain.push((format!("{name}.{field}"), scalar));
                    }
                }
            }
            value => {
                if let Some(scalar) = Scalar::argument(value) {
                    plain.push((name.clone(), scalar));
                }
            }
        }
    }
    let described = Described::new(Did::verb(ActionKey::new("", kind, id), plain));
    // The item: the innermost item the id arguments name, through the
    // record's collections and those inside their items (a slide's
    // element).
    let ids: Vec<&str> = args
        .values()
        .filter_map(serde_json::Value::as_str)
        .collect();
    Some(match item_named(doc, shape, &ROOT, &ids) {
        Some((id, label)) => {
            let label = label.unwrap_or_else(|| id.clone());
            described.on(id, label)
        }
        None => described,
    })
}

/// The innermost item `ids` name among the collections of the record of
/// shape `shape` stored in `obj`, and inside that item's own collections:
/// its id and label.
fn item_named(
    doc: &Doc,
    shape: Shape,
    obj: &ObjId,
    ids: &[&str],
) -> Option<(String, Option<String>)> {
    for field in shape.fields() {
        let (Shape::Collection(item) | Shape::Keyed(item)) = field.shape else {
            continue;
        };
        let keyed = matches!(field.shape, Shape::Keyed(_));
        let Some(collection) = map_at(doc, obj, field.key) else {
            continue;
        };
        for candidate in ids {
            let Some(entry) = map_at(doc, &collection, candidate) else {
                continue;
            };
            let value = if keyed {
                Some(entry)
            } else {
                map_at(doc, &entry, "v")
            };
            let inner = value
                .as_ref()
                .and_then(|map| item_named(doc, *item, map, ids));
            return inner.or_else(|| {
                let label = value.and_then(|map| label_of(doc, *item, &map));
                Some(((*candidate).to_owned(), label))
            });
        }
    }
    None
}

/// The item the action applying last on this thread made, named as a person
/// reads it: the entry it added to one of the record's collections, with the
/// label the record gives that item, or the item the app named as it ran
/// ([`crate::ActionCx::named`]). An entry is the action's whether it minted
/// the id or was handed it (a window's New knows the id it opens next), and
/// one with no name of its own yet is named by its id alone, which a reader
/// names as the item is called when it reads it (a note by its first line).
/// `None` when it made no item of the record's: a change that names nothing
/// keeps the words its description read before it applied.
pub(crate) fn made<R: crate::Model>(doc: &Doc) -> Option<tilo_actions::ActionItem> {
    if let Some(named) = crate::action::named_item() {
        return Some(named);
    }
    let mut ids = crate::action::minted_so_far();
    let mut handed = crate::action::entries_so_far();
    handed.retain(|id| !ids.contains(id));
    handed.sort_unstable();
    ids.extend(handed);
    ids.into_iter().find_map(|id| {
        let map = crate::action::minted_entry(&id)?;
        let (shape, keyed) = collection_of::<R>(doc, &map)?;
        let item = if keyed {
            map_at(doc, &map, &id)
        } else {
            map_at(doc, &map, &id).and_then(|entry| map_at(doc, &entry, "v"))
        }?;
        let label = label_of(doc, shape, &item).unwrap_or_default();
        Some(tilo_actions::ActionItem { id, label })
    })
}

/// The collection of the record of type `R` whose map in `doc` is `map`: the
/// shape its items have, and whether it stores them keyed.
fn collection_of<R: crate::Model>(doc: &Doc, map: &ObjId) -> Option<(Shape, bool)> {
    let Shape::Record(fields) = R::SHAPE else {
        return None;
    };
    fields.iter().find_map(|field| {
        let (item, keyed) = match field.shape {
            Shape::Collection(item) => (*item, false),
            Shape::Keyed(item) => (*item, true),
            _ => return None,
        };
        (map_at(doc, &ROOT, field.key).as_ref() == Some(map)).then_some((item, keyed))
    })
}