tilo-resource 0.5.2

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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
//! Actions on the items of a collection, offered on the items themselves.
//!
//! An action whose first parameter is an item [`Id`] — "mark this todo
//! done", "delete this card" — acts on one element of a
//! [`Collection`](crate::Collection). Asking the user (or an agent) to type
//! that id is the wrong interface: the palette and context menus should offer
//! the action *on* the item, with the id already bound. So `#[resource]`
//! publishes every item of the record's collections as a child resource
//! whose actions are the item actions for it, their remaining parameters
//! still typed. The action stays published on the record too, with its id
//! parameter, for scripts that address items by id.
//!
//! The collection an action acts on is the field its item parameter is
//! named after, or the record's only collection; `#[action(item = field)]`
//! names it otherwise. `#[resource]` refuses to compile an item action whose
//! collection is neither.
//!
//! ```
//! use tilo_resource::{Collection, Id, Model, resource};
//!
//! #[derive(Model, Default)]
//! pub struct Shelf { pub books: Collection<String>, pub loans: Collection<String> }
//!
//! #[resource(kind = "doc.shelf")]
//! impl Shelf {
//!     /// Lend a book.
//!     #[action(item = books)]
//!     pub fn lend(&mut self, book: &Id) { self.books.remove(book); }
//!
//!     /// Return a loan: the parameter names its collection.
//!     #[action]
//!     pub fn loans(&mut self, loans: &Id) { self.loans.remove(loans); }
//! }
//! # fn main() {}
//! ```
//!
//! With two collections and neither named, it does not compile:
//!
//! ```compile_fail
//! use tilo_resource::{Collection, Id, Model, resource};
//!
//! #[derive(Model, Default)]
//! pub struct Shelf { pub books: Collection<String>, pub loans: Collection<String> }
//!
//! #[resource(kind = "doc.shelf")]
//! impl Shelf {
//!     /// Lend a book.
//!     #[action]
//!     pub fn lend(&mut self, book: &Id) { self.books.remove(book); }
//! }
//! # fn main() {}
//! ```
//!
//! nor does naming a collection the record does not have:
//!
//! ```compile_fail
//! use tilo_resource::{Collection, Id, Model, resource};
//!
//! #[derive(Model, Default)]
//! pub struct Shelf { pub books: Collection<String> }
//!
//! #[resource(kind = "doc.shelf")]
//! impl Shelf {
//!     /// Lend a book.
//!     #[action(item = loans)]
//!     pub fn lend(&mut self, book: &Id) { self.books.remove(book); }
//! }
//! # fn main() {}
//! ```
//!
//! or naming one for an action that takes no item:
//!
//! ```compile_fail
//! use tilo_resource::{Collection, Model, resource};
//!
//! #[derive(Model, Default)]
//! pub struct Shelf { pub books: Collection<String> }
//!
//! #[resource(kind = "doc.shelf")]
//! impl Shelf {
//!     /// Clear the shelf.
//!     #[action(item = books)]
//!     pub fn clear(&mut self, everything: bool) { if everything { self.books = Collection::new(); } }
//! }
//! # fn main() {}
//! ```
//!
//! A label joined from several fields names each of them once: naming one
//! twice would label an item by a field that is not there.
//!
//! ```compile_fail
//! use tilo_resource::Model;
//!
//! #[derive(Model, Default)]
//! #[model(label = "first first")]
//! pub struct Person { pub first: String, pub last: String }
//! # fn main() {}
//! ```

use std::any::TypeId;
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use std::sync::Arc;

use tilo_actions::{ActionArgs, ActionParam, ActionSpec, ActionType, ExecutionLocus, Target};

use crate::collection::Id;
use crate::resource::Resource;
use crate::vocabulary::{Declaration, Vocabulary, vocabulary};

/// One labelled item of a collection, as search indexes it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ItemText {
    /// The collection field's Rust name.
    pub field: &'static str,
    pub id: Id,
    /// Its `#[model(label)]`.
    pub label: String,
    /// All of its text.
    pub text: String,
}

/// The items of one collection field, as `#[derive(Model)]` lists them.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ItemCollection {
    /// The field's Rust name.
    pub field: &'static str,
    /// Its items carry a `#[model(label)]`: they are published as item
    /// resources (which search hits and agents name) even with no item
    /// verbs or effects.
    pub labelled: bool,
    /// Each item's id and a human label (its first text, else its id).
    pub items: Vec<(Id, String)>,
    /// The items this collection sits in, outermost first: a slide's
    /// elements are within `("slides", <slide>)`. Empty for the record's own
    /// collections.
    pub within: Vec<(&'static str, Id)>,
}

/// A collection field's items as `#[derive(Model)]` publishes them: written
/// with plain loops, once per item type, so a record's derived code calls
/// these rather than repeating iterator chains per field.
pub trait ItemSource {
    /// The first page of items with their labels.
    fn item_collection(&self, field: &'static str) -> ItemCollection;
    /// 1 when there is an item, 0 when there is none.
    fn item_presence(&self) -> usize;
    /// The label of the item `id`, when there is one.
    fn label_of_item(&self, id: &Id) -> Option<String>;
    /// The labelled items with all their text, for search.
    fn item_texts(&self, field: &'static str, found: &mut Vec<ItemText>);
    /// The collections inside the first page of items, placed within them.
    fn nested_items(&self, field: &'static str, out: &mut Vec<ItemCollection>);
}

/// The id of the child resource an item of a nested collection is
/// published as: `<kind>/slides/<slide>/elements/<element>`.
pub fn nested_resource_id<R: Resource>(within: &[(&str, Id)], field: &str, item: &Id) -> String {
    nested_resource_id_in(R::KIND, within, field, item)
}

/// [`nested_resource_id`] of a resource of the kind `kind`.
fn nested_resource_id_in(kind: &str, within: &[(&str, Id)], field: &str, item: &Id) -> String {
    let mut id = kind.to_owned();
    for (outer, outer_id) in within {
        id.push('/');
        id.push_str(outer);
        id.push('/');
        id.push_str(outer_id.as_str());
    }
    format!("{id}/{field}/{item}")
}

/// One action whose first parameter is an item id, as `#[resource]`
/// records it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ItemAction {
    /// The action's id.
    pub action: &'static str,
    /// The name of its item parameter.
    pub param: &'static str,
    /// The collection field named by `#[action(item = "...")]`, if any.
    pub collection: Option<&'static str>,
    /// For an item of a nested collection (`item = slides.elements`): the
    /// enclosing collections, outermost first…
    pub within: &'static [&'static str],
    /// …and the parameters naming their items.
    pub within_params: &'static [&'static str],
}

/// The id of the child resource an item is published as.
pub fn item_resource_id<R: Resource>(field: &str, item: &Id) -> String {
    item_resource_id_in(R::KIND, field, item)
}

/// [`item_resource_id`] of an item of a resource of kind `kind`: compiled
/// once in the shared runtime rather than once per resource type in every
/// app.
pub fn item_resource_id_in(kind: &str, field: &str, item: &Id) -> String {
    format!("{kind}/{field}/{item}")
}

pub use tilo_actions::item_kind;

/// A reference to one item of a collection, as an action that names an item
/// of its own record takes it.
///
/// It is written as the item's id, an address the item is published under
/// (`<kind>/<field>/<id>`, `<kind>.<field>:<id>`), or the label its
/// collection publishes it under — what a person or an agent knows the item
/// by. A resource reference object another surface hands out reads as the
/// item it names (its `id`, or its `label` when it carries no id), so a
/// caller may hand back what a listing or a search hit gave it.
///
/// What the text names is resolved where the action runs, which refuses a
/// reference to no item of the collection with the items there are, so a
/// mistyped or renamed item is never reported as one that went away.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Ref(String);

impl Ref {
    /// A reference written `text`.
    #[must_use]
    pub fn new(text: impl Into<String>) -> Self {
        Self(text.into())
    }

    /// The text as it was written.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl From<Id> for Ref {
    fn from(id: Id) -> Self {
        Self(id.as_str().to_owned())
    }
}

impl From<&Id> for Ref {
    fn from(id: &Id) -> Self {
        Self(id.as_str().to_owned())
    }
}

impl From<String> for Ref {
    fn from(text: String) -> Self {
        Self(text)
    }
}

impl From<&str> for Ref {
    fn from(text: &str) -> Self {
        Self(text.to_owned())
    }
}

impl serde::Serialize for Ref {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&self.0)
    }
}

/// The fields of a reference object that name the item, in the order they
/// are read: the address's own id, then the label it reads by.
const REFERENCE_FIELDS: [&str; 2] = ["id", "label"];

impl<'de> serde::Deserialize<'de> for Ref {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        use serde::de::Error as _;
        struct Reading;
        impl<'de> serde::de::Visitor<'de> for Reading {
            type Value = Ref;

            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.write_str("an item's id or name, or a reference to it")
            }

            fn visit_str<E: serde::de::Error>(self, text: &str) -> Result<Ref, E> {
                Ok(Ref(text.to_owned()))
            }

            fn visit_map<M: serde::de::MapAccess<'de>>(self, mut map: M) -> Result<Ref, M::Error> {
                let mut named: Option<String> = None;
                while let Some(key) = map.next_key::<String>()? {
                    let value = map.next_value::<Option<String>>()?;
                    if named.is_none()
                        && REFERENCE_FIELDS.contains(&key.as_str())
                        && let Some(value) = value.filter(|value| !value.trim().is_empty())
                    {
                        named = Some(value);
                    }
                }
                named.map(Ref).ok_or_else(|| {
                    M::Error::custom("a reference names its item by `id` or by `label`")
                })
            }
        }
        deserializer.deserialize_any(Reading)
    }
}

impl crate::JsonSchema for Ref {
    fn json_schema() -> serde_json::Value {
        serde_json::json!({"type": "string", "minLength": 1})
    }
    fn field_type(_: &mut crate::TypeSet) -> crate::FieldType {
        crate::FieldType::Text
    }
}

/// The item an item resource id names, if it is one of `R`'s.
pub fn item_of_resource<R: Resource>(resource_id: &str) -> Option<(&str, Id)> {
    item_of_resource_in(R::KIND, resource_id)
}

/// [`item_of_resource`] of a resource of the kind `kind`.
#[must_use]
pub fn item_of_resource_in<'a>(kind: &str, resource_id: &'a str) -> Option<(&'a str, Id)> {
    let rest = resource_id.strip_prefix(kind)?.strip_prefix('/')?;
    let (field, item) = rest.split_once('/')?;
    Some((field, Id::from_raw(item)))
}

fn targets(action: &ItemAction, fields: &[&str], field: &str) -> bool {
    if !action.within.is_empty() {
        return false;
    }
    if let Some(named) = action.collection {
        return named == field;
    }
    if fields.contains(&action.param) {
        action.param == field
    } else {
        fields.len() == 1
    }
}

/// How many items of one collection a published tree carries; the rest are
/// resolved one by one when addressed ([`item_child`]).
pub const ITEM_PAGE: usize = 256;

type Cached = HashMap<Id, (String, u64, tilo_actions::ResourceSpec)>;

thread_local! {
    /// Item resources built before, by resource type and collection, then
    /// item: rebuilt only when the item's label, the app's code or the
    /// language its actions' words are read in changed.
    static BUILT: RefCell<HashMap<(TypeId, String), Cached>> = RefCell::new(HashMap::new());
}

/// The item resource for `id` in `field`, labelled `label`, offering the
/// item actions `scoped`: from the cache when it was built for the same
/// label and code, else built and kept.
fn item_resource(
    vocabulary: &'static Vocabulary,
    scoped: &[(&ItemAction, &Declaration)],
    field: &str,
    id: &Id,
    label: &str,
) -> tilo_actions::ResourceSpec {
    cached_item((vocabulary.type_id)(), field, id, label, &|| {
        build_item(vocabulary, scoped, field, id, label)
    })
}

/// The item resource `build` makes, from the cache of the resource type
/// `kind` when it was built for the same label, code and language.
fn cached_item(
    kind: TypeId,
    field: &str,
    id: &Id,
    label: &str,
    build: &dyn Fn() -> tilo_actions::ResourceSpec,
) -> tilo_actions::ResourceSpec {
    let epoch = crate::resource::words_epoch();
    let key = (kind, field.to_owned());
    let cached = BUILT.with(|built| {
        built
            .borrow()
            .get(&key)
            .and_then(|items| items.get(id))
            .filter(|(cached_label, cached_epoch, _)| {
                cached_label == label && *cached_epoch == epoch
            })
            .map(|(_, _, resource)| resource.clone())
    });
    if let Some(resource) = cached {
        debug_assert_eq!(
            fingerprint(&resource),
            fingerprint(&build()),
            "a cached item resource differs from a fresh one"
        );
        return resource;
    }
    let resource = build();
    BUILT.with(|built| {
        built
            .borrow_mut()
            .entry(key)
            .or_default()
            .insert(id.clone(), (label.to_owned(), epoch, resource.clone()));
    });
    resource
}

fn build_item(
    vocabulary: &'static Vocabulary,
    scoped: &[(&ItemAction, &Declaration)],
    field: &str,
    id: &Id,
    label: &str,
) -> tilo_actions::ResourceSpec {
    let mut child = tilo_actions::ResourceSpec::new(
        item_resource_id_in(vocabulary.kind, field, id),
        format!("{}.{field}", vocabulary.kind),
        label,
    );
    // What it is, as people name it: an item of the collection's type
    // (`video` for a `videos` field) of the app's kind, so search finds a
    // Rust app's item by its type exactly as a tilolang item's.
    child = child.with_type(crate::words::item_words(vocabulary.kind, field));
    for (action, decl) in scoped {
        child = child.with_action(item_spec(decl, action.param, id));
    }
    for spec in (vocabulary.item_effects)(field, id) {
        child = child.with_action(spec);
    }
    for view in (vocabulary.item_views)(field, id) {
        child = child.with_view(view);
    }
    crate::share::offer(&mut child);
    if let Some(rename) = rename_spec(vocabulary, field, id)
        && !child.actions.iter().any(|action| action.id == rename.id)
    {
        child = child.with_action(rename);
    }
    // Its fields, edited from the item.
    if let Some(spec) = crate::resource::item_field_edit_spec_of(vocabulary, field, id) {
        child = child.with_action(spec);
    }
    // The fields holding resources of their own (`#[model(resource)]`).
    if let Some((key, item)) = item_shape(vocabulary, field) {
        let parent = item_resource_id_in(vocabulary.kind, field, id);
        let path = [
            crate::Segment::Field(key.to_owned()),
            crate::Segment::Item(id.clone()),
        ];
        child = child.with_children(crate::child::nested_children(
            vocabulary,
            item,
            &parent,
            &path,
            Some(label),
        ));
    }
    child
}

/// The key the collection field `field` is stored under and the shape of its
/// items, when it is a collection of records.
fn item_shape(
    vocabulary: &'static Vocabulary,
    field: &str,
) -> Option<(&'static str, crate::shape::Shape)> {
    use crate::shape::Shape;
    let collection = (vocabulary.shape)()?
        .fields()
        .iter()
        .find(|candidate| candidate.name == field)?;
    match collection.shape {
        Shape::Collection(item) | Shape::Keyed(item) => Some((collection.key, *item)),
        _ => None,
    }
}

/// The id of the prompt that renames an item.
pub const RENAME: &str = "rename";

/// "Rename" on an item whose `#[model(label)]` is a plain text field: the
/// field edit that sets it, asking for the new name, so the palette and
/// agents offer what a person would otherwise type into the item's title.
/// Its type is kept once per collection, bound to the item's id.
fn rename_spec(vocabulary: &'static Vocabulary, field: &str, id: &Id) -> Option<ActionSpec> {
    thread_local! {
        static KEPT: RefCell<crate::kept::KeptByPath> = RefCell::default();
    }
    if !vocabulary.edits {
        return None;
    }
    let key = ((vocabulary.type_id)(), field.to_owned());
    crate::kept::kept_type(&KEPT, key, || rename_type(vocabulary, field))
        .map(|ty| ty.bind(Target::new(id.clone())))
}

/// The type of [`rename_spec`] on the items of the collection `field`, whose
/// target is the item's [`Id`].
fn rename_type(vocabulary: &'static Vocabulary, field: &str) -> Option<Arc<ActionType>> {
    use crate::path::{EditOp, Segment};
    use crate::shape::Shape;
    let collection = (vocabulary.shape)()?
        .fields()
        .iter()
        .find(|candidate| candidate.name == field)?;
    let (Shape::Collection(item) | Shape::Keyed(item)) = collection.shape else {
        return None;
    };
    let label = item.fields().iter().find(|candidate| candidate.label)?;
    let plain_text = label.ty.ends_with("String") || label.ty.ends_with("Atom");
    if collection.readonly || label.readonly || !plain_text {
        return None;
    }
    let (collection_key, label_key) = (collection.key, label.key);
    let param = label.name;
    // What the action is; its builder is the type's, below, which reads the
    // item from the target.
    let decl = Declaration::new(
        vocabulary,
        RENAME,
        "Rename".to_owned(),
        vec![ActionParam::required_owned(
            param,
            tilo_actions::ParamType::Text,
            label.title,
        )],
        Arc::new(|_, _| Err("bound to no item".to_owned())),
    );
    let spec = crate::resource::spec_of_declaration_on(&decl, move |target, args, now_ms| {
        let Some(tilo_actions::ArgValue::Text(name)) = args.get(param) else {
            return Err(format!("missing `{param}`"));
        };
        let Some(id) = target.get::<Id>() else {
            return Err("bound to no item".to_owned());
        };
        let path = vec![
            Segment::Field(collection_key.to_owned()),
            Segment::Item(id.clone()),
            Segment::Field(label_key.to_owned()),
        ];
        let edit = crate::Edit::<()>::new(
            path,
            EditOp::Set {
                value: serde_json::Value::String(name.clone()),
            },
        );
        crate::resource::stamped_edit(vocabulary, edit, now_ms)
    });
    Some(Arc::clone(spec.action_type()))
}

/// What a published resource is, as text: its identity, its actions with
/// their parameters and contract, and its children, for telling two
/// publications of the same thing apart.
#[must_use]
pub fn fingerprint(resource: &tilo_actions::ResourceSpec) -> String {
    use std::fmt::Write as _;
    let mut out = format!(
        "{}|{}|{}",
        resource.id.as_str(),
        resource.kind,
        resource.label
    );
    for spec in &resource.actions {
        let _ = write!(
            out,
            "|{}:{}:{:?}:{}",
            spec.id, spec.label, spec.kind, spec.contract.kind
        );
        for param in spec.params() {
            let _ = write!(out, ",{}:{:?}:{}", param.name, param.ty, param.required);
        }
    }
    for child in &resource.children {
        let _ = write!(out, "[{}]", fingerprint(child));
    }
    out
}

/// The item resources of the collections `fields` of `R` that `actions`
/// act on: what a publication would carry for item `resource_id`, built on
/// its own, or for a resource nested in an item
/// (`<kind>/pages/<page>/body`, [`crate::child::NestedResource`]).
/// `label_of(field, id)` names an item, or says it is not there.
pub fn item_child<R: Resource>(
    resource_id: &str,
    fields: &[&str],
    actions: &[ItemAction],
    label_of: impl Fn(&str, &Id) -> Option<String>,
) -> Option<tilo_actions::ResourceSpec> {
    let vocabulary = vocabulary::<R>();
    let (field, id) = item_of_resource_in(vocabulary.kind, resource_id)?;
    let field = *fields.iter().find(|candidate| **candidate == field)?;
    if let Some(label) = label_of(field, &id) {
        return Some(scoped_item(vocabulary, fields, actions, field, &id, &label));
    }
    // Not an item: a resource nested in one, found in the item's resource.
    let (item, _) = id.as_str().split_once('/')?;
    let item = Id::from_raw(item);
    let label = label_of(field, &item)?;
    let resource = scoped_item(vocabulary, fields, actions, field, &item, &label);
    descendant(resource, resource_id)
}

/// The resource `id` among `resource`'s children, at any depth.
fn descendant(
    resource: tilo_actions::ResourceSpec,
    id: &str,
) -> Option<tilo_actions::ResourceSpec> {
    resource.children.into_iter().find_map(|child| {
        if child.id.as_str() == id {
            Some(child)
        } else {
            descendant(child, id)
        }
    })
}

/// The item resource of the item `id` of `field`, labelled `label`.
fn scoped_item(
    vocabulary: &'static Vocabulary,
    fields: &[&str],
    actions: &[ItemAction],
    field: &str,
    id: &Id,
    label: &str,
) -> tilo_actions::ResourceSpec {
    let declarations = vocabulary.declarations();
    let scoped = scoped(&declarations, actions, fields, field);
    item_resource(vocabulary, &scoped, field, id, label)
}

fn scoped<'d, 'a>(
    declarations: &'d [Declaration],
    actions: &'a [ItemAction],
    fields: &[&str],
    field: &str,
) -> Vec<(&'a ItemAction, &'d Declaration)> {
    let mut out = Vec::new();
    for action in actions {
        if !targets(action, fields, field) {
            continue;
        }
        for decl in declarations {
            if decl.id == action.action {
                out.push((action, decl));
                break;
            }
        }
    }
    out
}

/// The collection an item action with item parameter `param` (and the
/// collection `named` by `#[action(item = field)]`, or `""`) acts on.
#[doc(hidden)]
#[must_use]
pub fn item_field(
    collections: &'static [&'static str],
    param: &str,
    named: &str,
) -> Option<&'static str> {
    if !named.is_empty() {
        return collections.iter().copied().find(|field| *field == named);
    }
    collections
        .iter()
        .copied()
        .find(|field| *field == param)
        .or(match collections {
            [only] => Some(*only),
            _ => None,
        })
}

/// Whether an item action with item parameter `param` (and the collection
/// `named` by `#[action(item = field)]`, or `""`) acts on one of
/// `collections`: the check `#[resource]` runs when it compiles.
#[doc(hidden)]
#[must_use]
pub const fn item_target(collections: &[&str], param: &str, named: &str) -> bool {
    if !named.is_empty() {
        return contains(collections, named);
    }
    contains(collections, param) || collections.len() == 1
}

/// The collection field whose item a verb's first parameter names, among
/// `collections` (a record's [`ITEM_FIELDS`](crate::Fields::ITEM_FIELDS)):
/// the field `#[action(item = field)]` names, else the one the parameter is
/// named after, else the record's only collection where the parameter is
/// called what one of its items is (`issue` for `issues`).
///
/// A parameter named after no collection names no item, also where the
/// record keeps one collection only: a conversation's id on a record that
/// keeps messages alone is not a message, so its verb is handed the id as
/// written rather than refused for naming no message.
#[doc(hidden)]
#[must_use]
pub fn target_field<'a>(collections: &[&'a str], param: &str, named: &str) -> Option<&'a str> {
    if !named.is_empty() {
        return collections.iter().copied().find(|field| *field == named);
    }
    if let Some(field) = collections.iter().copied().find(|field| *field == param) {
        return Some(field);
    }
    match collections {
        [only] if one_of(only, param) => Some(only),
        _ => None,
    }
}

/// Whether a parameter called `param` is called what one item of the
/// collection field `field` is: `issue` for `issues`, `shell-part` for
/// `shell_parts`.
fn one_of(field: &str, param: &str) -> bool {
    tilo_actions::singular(&tilo_actions::in_words(field)) == tilo_actions::in_words(param)
}

/// Whether `#[action(item = field)]` names one of `outboxes`: the verb acts
/// on an outbox entry, which is published on no item.
#[doc(hidden)]
#[must_use]
pub const fn entry_target(outboxes: &[&str], named: &str) -> bool {
    !named.is_empty() && contains(outboxes, named)
}

#[allow(
    clippy::indexing_slicing,
    clippy::arithmetic_side_effects,
    reason = "a const fn walks the slices by index, bounded by their lengths"
)]
const fn contains(names: &[&str], name: &str) -> bool {
    let mut index = 0;
    while index < names.len() {
        if same(names[index].as_bytes(), name.as_bytes()) {
            return true;
        }
        index += 1;
    }
    false
}

#[allow(
    clippy::indexing_slicing,
    clippy::arithmetic_side_effects,
    reason = "a const fn walks the slices by index, bounded by their lengths"
)]
const fn same(a: &[u8], b: &[u8]) -> bool {
    if a.len() != b.len() {
        return false;
    }
    let mut index = 0;
    while index < a.len() {
        if a[index] != b[index] {
            return false;
        }
        index += 1;
    }
    true
}

/// The item resources of a record: one per item of each collection, carrying
/// the item actions that act on that collection with the item bound.
pub fn item_children<R: Resource>(
    collections: &[ItemCollection],
    actions: &[ItemAction],
) -> Vec<tilo_actions::ResourceSpec> {
    let mut children = Vec::new();
    for_each_item_child_of(
        vocabulary::<R>(),
        collections,
        actions,
        &mut |_, _, _, build| {
            children.push(build());
        },
    );
    children
}

/// What [`for_each_item_child`] calls per item child: the collection it is
/// an item of, its id and label, and how to build it.
pub type ItemChildVisitor<'a> =
    dyn FnMut(&ItemCollection, &Id, &str, &dyn Fn() -> tilo_actions::ResourceSpec) + 'a;

/// [`item_children`] one item at a time, for a publisher that keeps the
/// children it built for an earlier version: `each(collection, id, label,
/// build)` is called for every item child in order, and `build()` makes
/// that child exactly as [`item_children`] does. A child is a function of
/// its collection (field and the items it sits in), its id and its label,
/// and the locale its actions' labels are in.
pub fn for_each_item_child<R: Resource>(
    collections: &[ItemCollection],
    actions: &[ItemAction],
    each: &mut ItemChildVisitor<'_>,
) {
    for_each_item_child_of(vocabulary::<R>(), collections, actions, each);
}

/// [`for_each_item_child`] of the resource `vocabulary`.
fn for_each_item_child_of(
    vocabulary: &'static Vocabulary,
    collections: &[ItemCollection],
    actions: &[ItemAction],
    each: &mut ItemChildVisitor<'_>,
) {
    let declarations = vocabulary.declarations();
    let fields = own_fields(collections);
    for collection in collections {
        if !collection.within.is_empty() {
            // An item of a collection inside an item: its label, its fields,
            // `open`, and the verbs declared on it (`item = slides.elements`).
            let outer = outer_fields(collection);
            let mut verbs: Vec<(&ItemAction, &Declaration)> = Vec::new();
            for action in actions {
                if action.collection != Some(collection.field) || action.within != outer.as_slice()
                {
                    continue;
                }
                for decl in declarations.iter() {
                    if decl.id == action.action {
                        verbs.push((action, decl));
                        break;
                    }
                }
            }
            if collection.labelled || !verbs.is_empty() {
                for (id, label) in &collection.items {
                    each(collection, id, label, &|| {
                        let mut child = nested_item(
                            vocabulary,
                            &collection.within,
                            collection.field,
                            id,
                            label,
                        );
                        for (action, decl) in &verbs {
                            let values = nested_values(action, &collection.within, id);
                            child = child.with_action(bound(decl, &values));
                        }
                        child
                    });
                }
            }
            continue;
        }
        let scoped = scoped(&declarations, actions, &fields, collection.field);
        let offers_effects = match collection.items.first() {
            Some((id, _)) => !(vocabulary.item_effects)(collection.field, id).is_empty(),
            None => false,
        };
        if scoped.is_empty() && !offers_effects && !collection.labelled {
            continue;
        }
        for (id, label) in &collection.items {
            each(collection, id, label, &|| {
                item_resource(vocabulary, &scoped, collection.field, id, label)
            });
        }
        forget_gone((vocabulary.type_id)(), collection);
    }
}

/// The id of the resource the item `id` of `collection` is published as.
pub fn item_child_id<R: Resource>(collection: &ItemCollection, id: &Id) -> String {
    if collection.within.is_empty() {
        item_resource_id_in(R::KIND, collection.field, id)
    } else {
        nested_resource_id_in(R::KIND, &collection.within, collection.field, id)
    }
}

/// [`Resource::children`] in the parts a publisher can keep between
/// versions ([`Resource::children_parts`]): children built afresh, children
/// kept while they are unchanged, then one per item of `items` carrying
/// `item_actions` ([`item_children`]).
pub struct ChildrenParts {
    /// The children before the kept ones, built afresh.
    pub others: Vec<tilo_actions::ResourceSpec>,
    /// The record's nested resources and derived ones
    /// ([`crate::derived::published`]): the very same, and each the very
    /// same, while they are unchanged, so a publisher holding what it built
    /// of them keeps it.
    pub kept: Rc<[Rc<tilo_actions::ResourceSpec>]>,
    /// The record's collections, each item with its label.
    pub items: Vec<ItemCollection>,
    /// The actions offered on items.
    pub item_actions: Vec<ItemAction>,
}

/// The record's own collections' fields (not those inside items).
fn own_fields(collections: &[ItemCollection]) -> Vec<&'static str> {
    collections
        .iter()
        .filter(|collection| collection.within.is_empty())
        .map(|collection| collection.field)
        .collect()
}

/// The fields of the items a nested collection sits in, outermost first.
fn outer_fields(collection: &ItemCollection) -> Vec<&'static str> {
    collection.within.iter().map(|(field, _)| *field).collect()
}

/// The arguments an item verb of a nested collection binds: the ids of the
/// items it sits in, then the item's own.
fn nested_values(
    action: &ItemAction,
    within: &[(&'static str, Id)],
    id: &Id,
) -> Vec<(String, serde_json::Value)> {
    let mut values: Vec<(String, serde_json::Value)> = action
        .within_params
        .iter()
        .zip(within)
        .map(|(param, (_, outer_id))| ((*param).to_owned(), outer_id.as_str().into()))
        .collect();
    values.push((action.param.to_owned(), id.as_str().into()));
    values
}

/// Forget cached item resources of `collection` (of the resource type
/// `kind`) whose items are gone.
fn forget_gone(kind: TypeId, collection: &ItemCollection) {
    BUILT.with(|built| {
        if let Some(items) = built
            .borrow_mut()
            .get_mut(&(kind, collection.field.to_owned()))
            && items.len() > collection.items.len().saturating_mul(2).max(ITEM_PAGE)
        {
            let present: std::collections::HashSet<&Id> =
                collection.items.iter().map(|(id, _)| id).collect();
            items.retain(|id, _| present.contains(id));
        }
    });
}

/// The resource of an item of a nested collection.
fn nested_item(
    vocabulary: &'static Vocabulary,
    within: &[(&'static str, Id)],
    field: &'static str,
    id: &Id,
    label: &str,
) -> tilo_actions::ResourceSpec {
    let mut child = tilo_actions::ResourceSpec::new(
        nested_resource_id_in(vocabulary.kind, within, field, id),
        format!("{}.{field}", vocabulary.kind),
        label,
    );
    let mut path: Vec<crate::Segment> = Vec::new();
    for (outer, outer_id) in within {
        path.push(crate::Segment::Field((*outer).to_owned()));
        path.push(crate::Segment::Item(outer_id.clone()));
    }
    path.push(crate::Segment::Field(field.to_owned()));
    path.push(crate::Segment::Item(id.clone()));
    if let Some(spec) = crate::resource::field_edit_spec_at_of(vocabulary, path) {
        child = child.with_action(spec);
    }
    child
}

/// [`Resource::children_offer_bound`] of a record whose children are
/// `others`, its `derived` resources, then its [`item_children`]: the
/// declarations offered bound on `others`, on a derived resource or on the
/// items of a collection, known from how many items each collection holds
/// (`sizes`, by field) without building a child per item.
pub fn offered_on_items<R: Resource>(
    others: &[tilo_actions::ResourceSpec],
    derived: &crate::derived::PublishedDerived,
    sizes: &[(&'static str, usize)],
    actions: &[ItemAction],
    nested: &dyn Fn(&ItemAction) -> bool,
) -> Vec<&'static str> {
    let declarations = vocabulary::<R>().declarations();
    let mut declared: Vec<(&'static str, Vec<&str>)> = Vec::with_capacity(declarations.len());
    for decl in declarations.iter() {
        let mut names = Vec::with_capacity(decl.params.len());
        for param in &decl.params {
            names.push(param.name.as_ref());
        }
        declared.push((decl.id, names));
    }
    offered_on_items_of(others, derived, sizes, actions, &declared, nested)
}

/// [`offered_on_items`] over the declarations `declared` (id and parameter
/// names each). A verb on items of a nested collection is offered when
/// `nested` says such an item is published.
fn offered_on_items_of(
    others: &[tilo_actions::ResourceSpec],
    derived: &crate::derived::PublishedDerived,
    sizes: &[(&'static str, usize)],
    actions: &[ItemAction],
    declared: &[(&'static str, Vec<&str>)],
    nested: &dyn Fn(&ItemAction) -> bool,
) -> Vec<&'static str> {
    let fields: Vec<&str> = sizes.iter().map(|(field, _)| *field).collect();
    // `item_children` binds the first declaration of an action's id.
    let first = |id: &str| declared.iter().find(|(declared, _)| *declared == id);
    let mut offered = Vec::new();
    for (id, params) in declared {
        let on_items = actions.iter().any(|action| {
            if action.action != *id {
                return false;
            }
            let Some((_, bound)) = first(action.action) else {
                return false;
            };
            if action.within.is_empty() {
                // What `offered_bound` asks of the item's spec: it takes
                // fewer parameters than the declaration.
                let kept = bound.iter().filter(|name| **name != action.param).count();
                kept < params.len()
                    && sizes
                        .iter()
                        .any(|&(field, size)| size > 0 && targets(action, &fields, field))
            } else {
                // A nested item binds the ids of the items it sits in too.
                let kept = bound
                    .iter()
                    .filter(|name| **name != action.param && !action.within_params.contains(name))
                    .count();
                kept < params.len() && nested(action)
            }
        });
        if on_items
            || offered_bound_as(others, id, params.len())
            || derived.offers_bound(id, params.len())
        {
            offered.push(*id);
        }
    }
    offered
}

/// The spec of `decl` with its item parameter bound to `item`.
fn item_spec(decl: &Declaration, param: &'static str, item: &Id) -> ActionSpec {
    bound(
        decl,
        &[(
            param.to_owned(),
            serde_json::Value::String(item.as_str().to_owned()),
        )],
    )
}

/// `decl` offered on the item it acts on, with `values` bound to their
/// parameters: what a published child carries ("remove *this* photograph",
/// "rename *this* album"). The other parameters stay typed; the action is
/// built, checked and undone exactly as the declaration is. Published on a
/// child, the declaration stays on the resource for scripts that name the
/// item, out of the palette's way.
pub fn bound<N: AsRef<str>>(decl: &Declaration, values: &[(N, serde_json::Value)]) -> ActionSpec {
    let mut owned: Vec<(String, serde_json::Value)> = Vec::with_capacity(values.len());
    for (name, value) in values {
        owned.push((name.as_ref().to_owned(), value.clone()));
    }
    bound_to(decl, owned)
}

/// [`bound`] with its values owned: the type of `decl` with those parameters
/// bound, kept once for every item it is bound on, bound to `values`.
fn bound_to(decl: &Declaration, values: Vec<(String, serde_json::Value)>) -> ActionSpec {
    thread_local! {
        static KEPT: std::cell::RefCell<crate::kept::KeptTypes<BoundKey>> =
            std::cell::RefCell::default();
    }
    let names: Vec<String> = values.iter().map(|(name, _)| name.clone()).collect();
    let key = (decl.resource, decl.id, decl.refines, names);
    // The values are the item's, so the target holds them and the type
    // only names them; the spec fixes them for a caller that repeats one.
    crate::kept::kept_type(&KEPT, key, || bound_type(decl, &values))
        .bind(Target::new(values.clone()))
        .with_bound(values)
}

/// Which bound type of a declaration: the kind of resource it is declared
/// on, its id, whether it refines one, and the names of its bound parameters.
type BoundKey = (&'static str, &'static str, bool, Vec<String>);

/// The values a bound spec's [`Target`] holds, by parameter.
type BoundValues = Vec<(String, serde_json::Value)>;

/// The type of `decl` with the parameters `values` names bound by its target.
fn bound_type(decl: &Declaration, values: &[(String, serde_json::Value)]) -> Arc<ActionType> {
    let params = unbound_params(&decl.params, values);
    let all = decl.params.clone();
    let build = Arc::clone(&decl.build);
    let label = decl.shown_label();
    let spec = ActionSpec::typed_on(
        decl.id,
        label.clone(),
        label,
        ExecutionLocus::ClientLocal,
        params,
        move |target, args| {
            let mut arguments = args.to_json();
            for (name, value) in target.get::<BoundValues>().into_iter().flatten() {
                // An optional parameter bound to nothing is left out.
                if !value.is_null() {
                    arguments.insert(name.clone(), value.clone());
                }
            }
            let action = match ActionArgs::bind_json(&all, &arguments) {
                Ok(args) => {
                    crate::content::invoking(|| build(&args, crate::resource::origin_now_ms()))
                }
                Err(error) => Err(error.to_string()),
            };
            crate::resource::encode_built(action)
        },
    )
    .of_kind(decl.kind);
    let spec = finish_bound(spec, decl);
    Arc::clone(spec.action_type())
}

/// The parameters of `params` that `values` leaves to the caller.
fn unbound_params(
    params: &[ActionParam],
    values: &[(String, serde_json::Value)],
) -> Vec<ActionParam> {
    params
        .iter()
        .filter(|candidate| !values.iter().any(|(name, _)| candidate.name == *name))
        .cloned()
        .collect()
}

/// What a bound spec carries over from its declaration.
fn finish_bound(mut spec: ActionSpec, decl: &Declaration) -> ActionSpec {
    if let Some(field) = decl.field {
        spec = spec.below_field(field);
    }
    if let Some(description) = &decl.description {
        spec = spec.with_description(description.clone());
    }
    // On its item it is the same act, in the same picture, said with the same
    // words.
    spec = crate::resource::with_declared_words(spec, decl);
    // Offered to whom it is declared for, housekept and undone as declared:
    // `#[action(audience = "people", item = ...)]` is no agent's on its item
    // either. Before `destructive`, which settles its confirmation from what
    // the tags say and would otherwise ask about the undo they declare.
    for tag in &decl.tags {
        if !spec.contract.tags.contains(tag) {
            spec.type_mut().contract.tags.push(tag.clone());
        }
    }
    if decl.destructive {
        spec = spec.destructive();
    }
    // On its item it is the same kind of step, making the same thing.
    let contract = &mut spec.type_mut().contract;
    (contract.step, contract.creates) = (decl.step, decl.creates.map(str::to_owned));
    // An item verb that answers answers on its item too.
    if let Some(result) = &decl.result {
        spec.type_mut().contract.result = result.clone();
    }
    spec
}

/// Whether some resource in `children`, at any depth, offers `decl` with
/// arguments bound ([`bound`]).
#[must_use]
pub fn offered_bound(children: &[tilo_actions::ResourceSpec], decl: &Declaration) -> bool {
    offered_bound_as(children, decl.id, decl.params.len())
}

/// [`offered_bound`] of the declaration `id` taking `params` parameters.
fn offered_bound_as(children: &[tilo_actions::ResourceSpec], id: &str, params: usize) -> bool {
    children.iter().any(|child| {
        child
            .actions
            .iter()
            .any(|spec| spec.id == id && spec.params().len() < params)
            || offered_bound_as(&child.children, id, params)
    })
}

#[cfg(test)]
mod item_kind_tests {
    #[test]
    fn an_items_kind_is_read_from_its_id() {
        let id = super::item_resource_id_in("notes.notebook", "pages", &super::Id::from_raw("p1"));
        assert_eq!(
            super::item_kind(&id).as_deref(),
            Some("notes.notebook.pages")
        );
        assert_eq!(
            super::item_kind("notes.notebook"),
            None,
            "the record itself"
        );
        assert_eq!(
            super::item_kind("deck/slides/s1/elements/e1"),
            None,
            "a nested item"
        );
    }
}

#[cfg(test)]
mod target_field_tests {
    use super::target_field;

    #[test]
    fn a_parameter_names_an_item_only_of_the_collection_it_is_named_after() {
        // The field the verb names, whatever its parameter is called.
        assert_eq!(
            target_field(&["cards", "archive"], "card", "archive"),
            Some("archive")
        );
        assert_eq!(target_field(&["cards"], "card", "pages"), None);
        // The collection the parameter is named after.
        assert_eq!(
            target_field(&["cards", "archive"], "archive", ""),
            Some("archive")
        );
        // The record's only collection, where the parameter is called what
        // one of its items is.
        assert_eq!(target_field(&["issues"], "issue", ""), Some("issues"));
        assert_eq!(
            target_field(&["shell_parts"], "shell-part", ""),
            Some("shell_parts")
        );
        // A parameter named after no collection names no item, also where
        // the record keeps one collection only: a conversation is no message.
        assert_eq!(target_field(&["messages"], "channel", ""), None);
        assert_eq!(target_field(&["cards", "archive"], "place", ""), None);
    }
}