Skip to main content

tilo_resource/
items.rs

1//! Actions on the items of a collection, offered on the items themselves.
2//!
3//! An action whose first parameter is an item [`Id`] — "mark this todo
4//! done", "delete this card" — acts on one element of a
5//! [`Collection`](crate::Collection). Asking the user (or an agent) to type
6//! that id is the wrong interface: the palette and context menus should offer
7//! the action *on* the item, with the id already bound. So `#[resource]`
8//! publishes every item of the record's collections as a child resource
9//! whose actions are the item actions for it, their remaining parameters
10//! still typed. The action stays published on the record too, with its id
11//! parameter, for scripts that address items by id.
12//!
13//! The collection an action acts on is the field its item parameter is
14//! named after, or the record's only collection; `#[action(item = field)]`
15//! names it otherwise. `#[resource]` refuses to compile an item action whose
16//! collection is neither.
17//!
18//! ```
19//! use tilo_resource::{Collection, Id, Model, resource};
20//!
21//! #[derive(Model, Default)]
22//! pub struct Shelf { pub books: Collection<String>, pub loans: Collection<String> }
23//!
24//! #[resource(kind = "doc.shelf")]
25//! impl Shelf {
26//!     /// Lend a book.
27//!     #[action(item = books)]
28//!     pub fn lend(&mut self, book: &Id) { self.books.remove(book); }
29//!
30//!     /// Return a loan: the parameter names its collection.
31//!     #[action]
32//!     pub fn loans(&mut self, loans: &Id) { self.loans.remove(loans); }
33//! }
34//! # fn main() {}
35//! ```
36//!
37//! With two collections and neither named, it does not compile:
38//!
39//! ```compile_fail
40//! use tilo_resource::{Collection, Id, Model, resource};
41//!
42//! #[derive(Model, Default)]
43//! pub struct Shelf { pub books: Collection<String>, pub loans: Collection<String> }
44//!
45//! #[resource(kind = "doc.shelf")]
46//! impl Shelf {
47//!     /// Lend a book.
48//!     #[action]
49//!     pub fn lend(&mut self, book: &Id) { self.books.remove(book); }
50//! }
51//! # fn main() {}
52//! ```
53//!
54//! nor does naming a collection the record does not have:
55//!
56//! ```compile_fail
57//! use tilo_resource::{Collection, Id, Model, resource};
58//!
59//! #[derive(Model, Default)]
60//! pub struct Shelf { pub books: Collection<String> }
61//!
62//! #[resource(kind = "doc.shelf")]
63//! impl Shelf {
64//!     /// Lend a book.
65//!     #[action(item = loans)]
66//!     pub fn lend(&mut self, book: &Id) { self.books.remove(book); }
67//! }
68//! # fn main() {}
69//! ```
70//!
71//! or naming one for an action that takes no item:
72//!
73//! ```compile_fail
74//! use tilo_resource::{Collection, Model, resource};
75//!
76//! #[derive(Model, Default)]
77//! pub struct Shelf { pub books: Collection<String> }
78//!
79//! #[resource(kind = "doc.shelf")]
80//! impl Shelf {
81//!     /// Clear the shelf.
82//!     #[action(item = books)]
83//!     pub fn clear(&mut self, everything: bool) { if everything { self.books = Collection::new(); } }
84//! }
85//! # fn main() {}
86//! ```
87//!
88//! A label joined from several fields names each of them once: naming one
89//! twice would label an item by a field that is not there.
90//!
91//! ```compile_fail
92//! use tilo_resource::Model;
93//!
94//! #[derive(Model, Default)]
95//! #[model(label = "first first")]
96//! pub struct Person { pub first: String, pub last: String }
97//! # fn main() {}
98//! ```
99
100use std::any::TypeId;
101use std::cell::RefCell;
102use std::collections::HashMap;
103use std::rc::Rc;
104use std::sync::Arc;
105
106use tilo_actions::{ActionArgs, ActionParam, ActionSpec, ActionType, ExecutionLocus, Target};
107
108use crate::collection::Id;
109use crate::resource::Resource;
110use crate::vocabulary::{Declaration, Vocabulary, vocabulary};
111
112/// One labelled item of a collection, as search indexes it.
113#[derive(Clone, Debug, PartialEq, Eq)]
114pub struct ItemText {
115    /// The collection field's Rust name.
116    pub field: &'static str,
117    pub id: Id,
118    /// Its `#[model(label)]`.
119    pub label: String,
120    /// All of its text.
121    pub text: String,
122}
123
124/// The items of one collection field, as `#[derive(Model)]` lists them.
125#[derive(Clone, Debug, PartialEq, Eq)]
126pub struct ItemCollection {
127    /// The field's Rust name.
128    pub field: &'static str,
129    /// Its items carry a `#[model(label)]`: they are published as item
130    /// resources (which search hits and agents name) even with no item
131    /// verbs or effects.
132    pub labelled: bool,
133    /// Each item's id and a human label (its first text, else its id).
134    pub items: Vec<(Id, String)>,
135    /// The items this collection sits in, outermost first: a slide's
136    /// elements are within `("slides", <slide>)`. Empty for the record's own
137    /// collections.
138    pub within: Vec<(&'static str, Id)>,
139}
140
141/// A collection field's items as `#[derive(Model)]` publishes them: written
142/// with plain loops, once per item type, so a record's derived code calls
143/// these rather than repeating iterator chains per field.
144pub trait ItemSource {
145    /// The first page of items with their labels.
146    fn item_collection(&self, field: &'static str) -> ItemCollection;
147    /// 1 when there is an item, 0 when there is none.
148    fn item_presence(&self) -> usize;
149    /// The label of the item `id`, when there is one.
150    fn label_of_item(&self, id: &Id) -> Option<String>;
151    /// The labelled items with all their text, for search.
152    fn item_texts(&self, field: &'static str, found: &mut Vec<ItemText>);
153    /// The collections inside the first page of items, placed within them.
154    fn nested_items(&self, field: &'static str, out: &mut Vec<ItemCollection>);
155}
156
157/// The id of the child resource an item of a nested collection is
158/// published as: `<kind>/slides/<slide>/elements/<element>`.
159pub fn nested_resource_id<R: Resource>(within: &[(&str, Id)], field: &str, item: &Id) -> String {
160    nested_resource_id_in(R::KIND, within, field, item)
161}
162
163/// [`nested_resource_id`] of a resource of the kind `kind`.
164fn nested_resource_id_in(kind: &str, within: &[(&str, Id)], field: &str, item: &Id) -> String {
165    let mut id = kind.to_owned();
166    for (outer, outer_id) in within {
167        id.push('/');
168        id.push_str(outer);
169        id.push('/');
170        id.push_str(outer_id.as_str());
171    }
172    format!("{id}/{field}/{item}")
173}
174
175/// One action whose first parameter is an item id, as `#[resource]`
176/// records it.
177#[derive(Clone, Copy, Debug, PartialEq, Eq)]
178pub struct ItemAction {
179    /// The action's id.
180    pub action: &'static str,
181    /// The name of its item parameter.
182    pub param: &'static str,
183    /// The collection field named by `#[action(item = "...")]`, if any.
184    pub collection: Option<&'static str>,
185    /// For an item of a nested collection (`item = slides.elements`): the
186    /// enclosing collections, outermost first…
187    pub within: &'static [&'static str],
188    /// …and the parameters naming their items.
189    pub within_params: &'static [&'static str],
190}
191
192/// The id of the child resource an item is published as.
193pub fn item_resource_id<R: Resource>(field: &str, item: &Id) -> String {
194    item_resource_id_in(R::KIND, field, item)
195}
196
197/// [`item_resource_id`] of an item of a resource of kind `kind`: compiled
198/// once in the shared runtime rather than once per resource type in every
199/// app.
200pub fn item_resource_id_in(kind: &str, field: &str, item: &Id) -> String {
201    format!("{kind}/{field}/{item}")
202}
203
204pub use tilo_actions::item_kind;
205
206/// A reference to one item of a collection, as an action that names an item
207/// of its own record takes it.
208///
209/// It is written as the item's id, an address the item is published under
210/// (`<kind>/<field>/<id>`, `<kind>.<field>:<id>`), or the label its
211/// collection publishes it under — what a person or an agent knows the item
212/// by. A resource reference object another surface hands out reads as the
213/// item it names (its `id`, or its `label` when it carries no id), so a
214/// caller may hand back what a listing or a search hit gave it.
215///
216/// What the text names is resolved where the action runs, which refuses a
217/// reference to no item of the collection with the items there are, so a
218/// mistyped or renamed item is never reported as one that went away.
219#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
220pub struct Ref(String);
221
222impl Ref {
223    /// A reference written `text`.
224    #[must_use]
225    pub fn new(text: impl Into<String>) -> Self {
226        Self(text.into())
227    }
228
229    /// The text as it was written.
230    #[must_use]
231    pub fn as_str(&self) -> &str {
232        &self.0
233    }
234}
235
236impl From<Id> for Ref {
237    fn from(id: Id) -> Self {
238        Self(id.as_str().to_owned())
239    }
240}
241
242impl From<&Id> for Ref {
243    fn from(id: &Id) -> Self {
244        Self(id.as_str().to_owned())
245    }
246}
247
248impl From<String> for Ref {
249    fn from(text: String) -> Self {
250        Self(text)
251    }
252}
253
254impl From<&str> for Ref {
255    fn from(text: &str) -> Self {
256        Self(text.to_owned())
257    }
258}
259
260impl serde::Serialize for Ref {
261    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
262        serializer.serialize_str(&self.0)
263    }
264}
265
266/// The fields of a reference object that name the item, in the order they
267/// are read: the address's own id, then the label it reads by.
268const REFERENCE_FIELDS: [&str; 2] = ["id", "label"];
269
270impl<'de> serde::Deserialize<'de> for Ref {
271    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
272        use serde::de::Error as _;
273        struct Reading;
274        impl<'de> serde::de::Visitor<'de> for Reading {
275            type Value = Ref;
276
277            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
278                f.write_str("an item's id or name, or a reference to it")
279            }
280
281            fn visit_str<E: serde::de::Error>(self, text: &str) -> Result<Ref, E> {
282                Ok(Ref(text.to_owned()))
283            }
284
285            fn visit_map<M: serde::de::MapAccess<'de>>(self, mut map: M) -> Result<Ref, M::Error> {
286                let mut named: Option<String> = None;
287                while let Some(key) = map.next_key::<String>()? {
288                    let value = map.next_value::<Option<String>>()?;
289                    if named.is_none()
290                        && REFERENCE_FIELDS.contains(&key.as_str())
291                        && let Some(value) = value.filter(|value| !value.trim().is_empty())
292                    {
293                        named = Some(value);
294                    }
295                }
296                named.map(Ref).ok_or_else(|| {
297                    M::Error::custom("a reference names its item by `id` or by `label`")
298                })
299            }
300        }
301        deserializer.deserialize_any(Reading)
302    }
303}
304
305impl crate::JsonSchema for Ref {
306    fn json_schema() -> serde_json::Value {
307        serde_json::json!({"type": "string", "minLength": 1})
308    }
309    fn field_type(_: &mut crate::TypeSet) -> crate::FieldType {
310        crate::FieldType::Text
311    }
312}
313
314/// The item an item resource id names, if it is one of `R`'s.
315pub fn item_of_resource<R: Resource>(resource_id: &str) -> Option<(&str, Id)> {
316    item_of_resource_in(R::KIND, resource_id)
317}
318
319/// [`item_of_resource`] of a resource of the kind `kind`.
320#[must_use]
321pub fn item_of_resource_in<'a>(kind: &str, resource_id: &'a str) -> Option<(&'a str, Id)> {
322    let rest = resource_id.strip_prefix(kind)?.strip_prefix('/')?;
323    let (field, item) = rest.split_once('/')?;
324    Some((field, Id::from_raw(item)))
325}
326
327fn targets(action: &ItemAction, fields: &[&str], field: &str) -> bool {
328    if !action.within.is_empty() {
329        return false;
330    }
331    if let Some(named) = action.collection {
332        return named == field;
333    }
334    if fields.contains(&action.param) {
335        action.param == field
336    } else {
337        fields.len() == 1
338    }
339}
340
341/// How many items of one collection a published tree carries; the rest are
342/// resolved one by one when addressed ([`item_child`]).
343pub const ITEM_PAGE: usize = 256;
344
345type Cached = HashMap<Id, (String, u64, tilo_actions::ResourceSpec)>;
346
347thread_local! {
348    /// Item resources built before, by resource type and collection, then
349    /// item: rebuilt only when the item's label, the app's code or the
350    /// language its actions' words are read in changed.
351    static BUILT: RefCell<HashMap<(TypeId, String), Cached>> = RefCell::new(HashMap::new());
352}
353
354/// The item resource for `id` in `field`, labelled `label`, offering the
355/// item actions `scoped`: from the cache when it was built for the same
356/// label and code, else built and kept.
357fn item_resource(
358    vocabulary: &'static Vocabulary,
359    scoped: &[(&ItemAction, &Declaration)],
360    field: &str,
361    id: &Id,
362    label: &str,
363) -> tilo_actions::ResourceSpec {
364    cached_item((vocabulary.type_id)(), field, id, label, &|| {
365        build_item(vocabulary, scoped, field, id, label)
366    })
367}
368
369/// The item resource `build` makes, from the cache of the resource type
370/// `kind` when it was built for the same label, code and language.
371fn cached_item(
372    kind: TypeId,
373    field: &str,
374    id: &Id,
375    label: &str,
376    build: &dyn Fn() -> tilo_actions::ResourceSpec,
377) -> tilo_actions::ResourceSpec {
378    let epoch = crate::resource::words_epoch();
379    let key = (kind, field.to_owned());
380    let cached = BUILT.with(|built| {
381        built
382            .borrow()
383            .get(&key)
384            .and_then(|items| items.get(id))
385            .filter(|(cached_label, cached_epoch, _)| {
386                cached_label == label && *cached_epoch == epoch
387            })
388            .map(|(_, _, resource)| resource.clone())
389    });
390    if let Some(resource) = cached {
391        debug_assert_eq!(
392            fingerprint(&resource),
393            fingerprint(&build()),
394            "a cached item resource differs from a fresh one"
395        );
396        return resource;
397    }
398    let resource = build();
399    BUILT.with(|built| {
400        built
401            .borrow_mut()
402            .entry(key)
403            .or_default()
404            .insert(id.clone(), (label.to_owned(), epoch, resource.clone()));
405    });
406    resource
407}
408
409fn build_item(
410    vocabulary: &'static Vocabulary,
411    scoped: &[(&ItemAction, &Declaration)],
412    field: &str,
413    id: &Id,
414    label: &str,
415) -> tilo_actions::ResourceSpec {
416    let mut child = tilo_actions::ResourceSpec::new(
417        item_resource_id_in(vocabulary.kind, field, id),
418        format!("{}.{field}", vocabulary.kind),
419        label,
420    );
421    // What it is, as people name it: an item of the collection's type
422    // (`video` for a `videos` field) of the app's kind, so search finds a
423    // Rust app's item by its type exactly as a tilolang item's.
424    child = child.with_type(crate::words::item_words(vocabulary.kind, field));
425    for (action, decl) in scoped {
426        child = child.with_action(item_spec(decl, action.param, id));
427    }
428    for spec in (vocabulary.item_effects)(field, id) {
429        child = child.with_action(spec);
430    }
431    for view in (vocabulary.item_views)(field, id) {
432        child = child.with_view(view);
433    }
434    crate::share::offer(&mut child);
435    if let Some(rename) = rename_spec(vocabulary, field, id)
436        && !child.actions.iter().any(|action| action.id == rename.id)
437    {
438        child = child.with_action(rename);
439    }
440    // Its fields, edited from the item.
441    if let Some(spec) = crate::resource::item_field_edit_spec_of(vocabulary, field, id) {
442        child = child.with_action(spec);
443    }
444    // The fields holding resources of their own (`#[model(resource)]`).
445    if let Some((key, item)) = item_shape(vocabulary, field) {
446        let parent = item_resource_id_in(vocabulary.kind, field, id);
447        let path = [
448            crate::Segment::Field(key.to_owned()),
449            crate::Segment::Item(id.clone()),
450        ];
451        child = child.with_children(crate::child::nested_children(
452            vocabulary,
453            item,
454            &parent,
455            &path,
456            Some(label),
457        ));
458    }
459    child
460}
461
462/// The key the collection field `field` is stored under and the shape of its
463/// items, when it is a collection of records.
464fn item_shape(
465    vocabulary: &'static Vocabulary,
466    field: &str,
467) -> Option<(&'static str, crate::shape::Shape)> {
468    use crate::shape::Shape;
469    let collection = (vocabulary.shape)()?
470        .fields()
471        .iter()
472        .find(|candidate| candidate.name == field)?;
473    match collection.shape {
474        Shape::Collection(item) | Shape::Keyed(item) => Some((collection.key, *item)),
475        _ => None,
476    }
477}
478
479/// The id of the prompt that renames an item.
480pub const RENAME: &str = "rename";
481
482/// "Rename" on an item whose `#[model(label)]` is a plain text field: the
483/// field edit that sets it, asking for the new name, so the palette and
484/// agents offer what a person would otherwise type into the item's title.
485/// Its type is kept once per collection, bound to the item's id.
486fn rename_spec(vocabulary: &'static Vocabulary, field: &str, id: &Id) -> Option<ActionSpec> {
487    thread_local! {
488        static KEPT: RefCell<crate::kept::KeptByPath> = RefCell::default();
489    }
490    if !vocabulary.edits {
491        return None;
492    }
493    let key = ((vocabulary.type_id)(), field.to_owned());
494    crate::kept::kept_type(&KEPT, key, || rename_type(vocabulary, field))
495        .map(|ty| ty.bind(Target::new(id.clone())))
496}
497
498/// The type of [`rename_spec`] on the items of the collection `field`, whose
499/// target is the item's [`Id`].
500fn rename_type(vocabulary: &'static Vocabulary, field: &str) -> Option<Arc<ActionType>> {
501    use crate::path::{EditOp, Segment};
502    use crate::shape::Shape;
503    let collection = (vocabulary.shape)()?
504        .fields()
505        .iter()
506        .find(|candidate| candidate.name == field)?;
507    let (Shape::Collection(item) | Shape::Keyed(item)) = collection.shape else {
508        return None;
509    };
510    let label = item.fields().iter().find(|candidate| candidate.label)?;
511    let plain_text = label.ty.ends_with("String") || label.ty.ends_with("Atom");
512    if collection.readonly || label.readonly || !plain_text {
513        return None;
514    }
515    let (collection_key, label_key) = (collection.key, label.key);
516    let param = label.name;
517    // What the action is; its builder is the type's, below, which reads the
518    // item from the target.
519    let decl = Declaration::new(
520        vocabulary,
521        RENAME,
522        "Rename".to_owned(),
523        vec![ActionParam::required_owned(
524            param,
525            tilo_actions::ParamType::Text,
526            label.title,
527        )],
528        Arc::new(|_, _| Err("bound to no item".to_owned())),
529    );
530    let spec = crate::resource::spec_of_declaration_on(&decl, move |target, args, now_ms| {
531        let Some(tilo_actions::ArgValue::Text(name)) = args.get(param) else {
532            return Err(format!("missing `{param}`"));
533        };
534        let Some(id) = target.get::<Id>() else {
535            return Err("bound to no item".to_owned());
536        };
537        let path = vec![
538            Segment::Field(collection_key.to_owned()),
539            Segment::Item(id.clone()),
540            Segment::Field(label_key.to_owned()),
541        ];
542        let edit = crate::Edit::<()>::new(
543            path,
544            EditOp::Set {
545                value: serde_json::Value::String(name.clone()),
546            },
547        );
548        crate::resource::stamped_edit(vocabulary, edit, now_ms)
549    });
550    Some(Arc::clone(spec.action_type()))
551}
552
553/// What a published resource is, as text: its identity, its actions with
554/// their parameters and contract, and its children, for telling two
555/// publications of the same thing apart.
556#[must_use]
557pub fn fingerprint(resource: &tilo_actions::ResourceSpec) -> String {
558    use std::fmt::Write as _;
559    let mut out = format!(
560        "{}|{}|{}",
561        resource.id.as_str(),
562        resource.kind,
563        resource.label
564    );
565    for spec in &resource.actions {
566        let _ = write!(
567            out,
568            "|{}:{}:{:?}:{}",
569            spec.id, spec.label, spec.kind, spec.contract.kind
570        );
571        for param in spec.params() {
572            let _ = write!(out, ",{}:{:?}:{}", param.name, param.ty, param.required);
573        }
574    }
575    for child in &resource.children {
576        let _ = write!(out, "[{}]", fingerprint(child));
577    }
578    out
579}
580
581/// The item resources of the collections `fields` of `R` that `actions`
582/// act on: what a publication would carry for item `resource_id`, built on
583/// its own, or for a resource nested in an item
584/// (`<kind>/pages/<page>/body`, [`crate::child::NestedResource`]).
585/// `label_of(field, id)` names an item, or says it is not there.
586pub fn item_child<R: Resource>(
587    resource_id: &str,
588    fields: &[&str],
589    actions: &[ItemAction],
590    label_of: impl Fn(&str, &Id) -> Option<String>,
591) -> Option<tilo_actions::ResourceSpec> {
592    let vocabulary = vocabulary::<R>();
593    let (field, id) = item_of_resource_in(vocabulary.kind, resource_id)?;
594    let field = *fields.iter().find(|candidate| **candidate == field)?;
595    if let Some(label) = label_of(field, &id) {
596        return Some(scoped_item(vocabulary, fields, actions, field, &id, &label));
597    }
598    // Not an item: a resource nested in one, found in the item's resource.
599    let (item, _) = id.as_str().split_once('/')?;
600    let item = Id::from_raw(item);
601    let label = label_of(field, &item)?;
602    let resource = scoped_item(vocabulary, fields, actions, field, &item, &label);
603    descendant(resource, resource_id)
604}
605
606/// The resource `id` among `resource`'s children, at any depth.
607fn descendant(
608    resource: tilo_actions::ResourceSpec,
609    id: &str,
610) -> Option<tilo_actions::ResourceSpec> {
611    resource.children.into_iter().find_map(|child| {
612        if child.id.as_str() == id {
613            Some(child)
614        } else {
615            descendant(child, id)
616        }
617    })
618}
619
620/// The item resource of the item `id` of `field`, labelled `label`.
621fn scoped_item(
622    vocabulary: &'static Vocabulary,
623    fields: &[&str],
624    actions: &[ItemAction],
625    field: &str,
626    id: &Id,
627    label: &str,
628) -> tilo_actions::ResourceSpec {
629    let declarations = vocabulary.declarations();
630    let scoped = scoped(&declarations, actions, fields, field);
631    item_resource(vocabulary, &scoped, field, id, label)
632}
633
634fn scoped<'d, 'a>(
635    declarations: &'d [Declaration],
636    actions: &'a [ItemAction],
637    fields: &[&str],
638    field: &str,
639) -> Vec<(&'a ItemAction, &'d Declaration)> {
640    let mut out = Vec::new();
641    for action in actions {
642        if !targets(action, fields, field) {
643            continue;
644        }
645        for decl in declarations {
646            if decl.id == action.action {
647                out.push((action, decl));
648                break;
649            }
650        }
651    }
652    out
653}
654
655/// The collection an item action with item parameter `param` (and the
656/// collection `named` by `#[action(item = field)]`, or `""`) acts on.
657#[doc(hidden)]
658#[must_use]
659pub fn item_field(
660    collections: &'static [&'static str],
661    param: &str,
662    named: &str,
663) -> Option<&'static str> {
664    if !named.is_empty() {
665        return collections.iter().copied().find(|field| *field == named);
666    }
667    collections
668        .iter()
669        .copied()
670        .find(|field| *field == param)
671        .or(match collections {
672            [only] => Some(*only),
673            _ => None,
674        })
675}
676
677/// Whether an item action with item parameter `param` (and the collection
678/// `named` by `#[action(item = field)]`, or `""`) acts on one of
679/// `collections`: the check `#[resource]` runs when it compiles.
680#[doc(hidden)]
681#[must_use]
682pub const fn item_target(collections: &[&str], param: &str, named: &str) -> bool {
683    if !named.is_empty() {
684        return contains(collections, named);
685    }
686    contains(collections, param) || collections.len() == 1
687}
688
689/// The collection field whose item a verb's first parameter names, among
690/// `collections` (a record's [`ITEM_FIELDS`](crate::Fields::ITEM_FIELDS)):
691/// the field `#[action(item = field)]` names, else the one the parameter is
692/// named after, else the record's only collection where the parameter is
693/// called what one of its items is (`issue` for `issues`).
694///
695/// A parameter named after no collection names no item, also where the
696/// record keeps one collection only: a conversation's id on a record that
697/// keeps messages alone is not a message, so its verb is handed the id as
698/// written rather than refused for naming no message.
699#[doc(hidden)]
700#[must_use]
701pub fn target_field<'a>(collections: &[&'a str], param: &str, named: &str) -> Option<&'a str> {
702    if !named.is_empty() {
703        return collections.iter().copied().find(|field| *field == named);
704    }
705    if let Some(field) = collections.iter().copied().find(|field| *field == param) {
706        return Some(field);
707    }
708    match collections {
709        [only] if one_of(only, param) => Some(only),
710        _ => None,
711    }
712}
713
714/// Whether a parameter called `param` is called what one item of the
715/// collection field `field` is: `issue` for `issues`, `shell-part` for
716/// `shell_parts`.
717fn one_of(field: &str, param: &str) -> bool {
718    tilo_actions::singular(&tilo_actions::in_words(field)) == tilo_actions::in_words(param)
719}
720
721/// Whether `#[action(item = field)]` names one of `outboxes`: the verb acts
722/// on an outbox entry, which is published on no item.
723#[doc(hidden)]
724#[must_use]
725pub const fn entry_target(outboxes: &[&str], named: &str) -> bool {
726    !named.is_empty() && contains(outboxes, named)
727}
728
729#[allow(
730    clippy::indexing_slicing,
731    clippy::arithmetic_side_effects,
732    reason = "a const fn walks the slices by index, bounded by their lengths"
733)]
734const fn contains(names: &[&str], name: &str) -> bool {
735    let mut index = 0;
736    while index < names.len() {
737        if same(names[index].as_bytes(), name.as_bytes()) {
738            return true;
739        }
740        index += 1;
741    }
742    false
743}
744
745#[allow(
746    clippy::indexing_slicing,
747    clippy::arithmetic_side_effects,
748    reason = "a const fn walks the slices by index, bounded by their lengths"
749)]
750const fn same(a: &[u8], b: &[u8]) -> bool {
751    if a.len() != b.len() {
752        return false;
753    }
754    let mut index = 0;
755    while index < a.len() {
756        if a[index] != b[index] {
757            return false;
758        }
759        index += 1;
760    }
761    true
762}
763
764/// The item resources of a record: one per item of each collection, carrying
765/// the item actions that act on that collection with the item bound.
766pub fn item_children<R: Resource>(
767    collections: &[ItemCollection],
768    actions: &[ItemAction],
769) -> Vec<tilo_actions::ResourceSpec> {
770    let mut children = Vec::new();
771    for_each_item_child_of(
772        vocabulary::<R>(),
773        collections,
774        actions,
775        &mut |_, _, _, build| {
776            children.push(build());
777        },
778    );
779    children
780}
781
782/// What [`for_each_item_child`] calls per item child: the collection it is
783/// an item of, its id and label, and how to build it.
784pub type ItemChildVisitor<'a> =
785    dyn FnMut(&ItemCollection, &Id, &str, &dyn Fn() -> tilo_actions::ResourceSpec) + 'a;
786
787/// [`item_children`] one item at a time, for a publisher that keeps the
788/// children it built for an earlier version: `each(collection, id, label,
789/// build)` is called for every item child in order, and `build()` makes
790/// that child exactly as [`item_children`] does. A child is a function of
791/// its collection (field and the items it sits in), its id and its label,
792/// and the locale its actions' labels are in.
793pub fn for_each_item_child<R: Resource>(
794    collections: &[ItemCollection],
795    actions: &[ItemAction],
796    each: &mut ItemChildVisitor<'_>,
797) {
798    for_each_item_child_of(vocabulary::<R>(), collections, actions, each);
799}
800
801/// [`for_each_item_child`] of the resource `vocabulary`.
802fn for_each_item_child_of(
803    vocabulary: &'static Vocabulary,
804    collections: &[ItemCollection],
805    actions: &[ItemAction],
806    each: &mut ItemChildVisitor<'_>,
807) {
808    let declarations = vocabulary.declarations();
809    let fields = own_fields(collections);
810    for collection in collections {
811        if !collection.within.is_empty() {
812            // An item of a collection inside an item: its label, its fields,
813            // `open`, and the verbs declared on it (`item = slides.elements`).
814            let outer = outer_fields(collection);
815            let mut verbs: Vec<(&ItemAction, &Declaration)> = Vec::new();
816            for action in actions {
817                if action.collection != Some(collection.field) || action.within != outer.as_slice()
818                {
819                    continue;
820                }
821                for decl in declarations.iter() {
822                    if decl.id == action.action {
823                        verbs.push((action, decl));
824                        break;
825                    }
826                }
827            }
828            if collection.labelled || !verbs.is_empty() {
829                for (id, label) in &collection.items {
830                    each(collection, id, label, &|| {
831                        let mut child = nested_item(
832                            vocabulary,
833                            &collection.within,
834                            collection.field,
835                            id,
836                            label,
837                        );
838                        for (action, decl) in &verbs {
839                            let values = nested_values(action, &collection.within, id);
840                            child = child.with_action(bound(decl, &values));
841                        }
842                        child
843                    });
844                }
845            }
846            continue;
847        }
848        let scoped = scoped(&declarations, actions, &fields, collection.field);
849        let offers_effects = match collection.items.first() {
850            Some((id, _)) => !(vocabulary.item_effects)(collection.field, id).is_empty(),
851            None => false,
852        };
853        if scoped.is_empty() && !offers_effects && !collection.labelled {
854            continue;
855        }
856        for (id, label) in &collection.items {
857            each(collection, id, label, &|| {
858                item_resource(vocabulary, &scoped, collection.field, id, label)
859            });
860        }
861        forget_gone((vocabulary.type_id)(), collection);
862    }
863}
864
865/// The id of the resource the item `id` of `collection` is published as.
866pub fn item_child_id<R: Resource>(collection: &ItemCollection, id: &Id) -> String {
867    if collection.within.is_empty() {
868        item_resource_id_in(R::KIND, collection.field, id)
869    } else {
870        nested_resource_id_in(R::KIND, &collection.within, collection.field, id)
871    }
872}
873
874/// [`Resource::children`] in the parts a publisher can keep between
875/// versions ([`Resource::children_parts`]): children built afresh, children
876/// kept while they are unchanged, then one per item of `items` carrying
877/// `item_actions` ([`item_children`]).
878pub struct ChildrenParts {
879    /// The children before the kept ones, built afresh.
880    pub others: Vec<tilo_actions::ResourceSpec>,
881    /// The record's nested resources and derived ones
882    /// ([`crate::derived::published`]): the very same, and each the very
883    /// same, while they are unchanged, so a publisher holding what it built
884    /// of them keeps it.
885    pub kept: Rc<[Rc<tilo_actions::ResourceSpec>]>,
886    /// The record's collections, each item with its label.
887    pub items: Vec<ItemCollection>,
888    /// The actions offered on items.
889    pub item_actions: Vec<ItemAction>,
890}
891
892/// The record's own collections' fields (not those inside items).
893fn own_fields(collections: &[ItemCollection]) -> Vec<&'static str> {
894    collections
895        .iter()
896        .filter(|collection| collection.within.is_empty())
897        .map(|collection| collection.field)
898        .collect()
899}
900
901/// The fields of the items a nested collection sits in, outermost first.
902fn outer_fields(collection: &ItemCollection) -> Vec<&'static str> {
903    collection.within.iter().map(|(field, _)| *field).collect()
904}
905
906/// The arguments an item verb of a nested collection binds: the ids of the
907/// items it sits in, then the item's own.
908fn nested_values(
909    action: &ItemAction,
910    within: &[(&'static str, Id)],
911    id: &Id,
912) -> Vec<(String, serde_json::Value)> {
913    let mut values: Vec<(String, serde_json::Value)> = action
914        .within_params
915        .iter()
916        .zip(within)
917        .map(|(param, (_, outer_id))| ((*param).to_owned(), outer_id.as_str().into()))
918        .collect();
919    values.push((action.param.to_owned(), id.as_str().into()));
920    values
921}
922
923/// Forget cached item resources of `collection` (of the resource type
924/// `kind`) whose items are gone.
925fn forget_gone(kind: TypeId, collection: &ItemCollection) {
926    BUILT.with(|built| {
927        if let Some(items) = built
928            .borrow_mut()
929            .get_mut(&(kind, collection.field.to_owned()))
930            && items.len() > collection.items.len().saturating_mul(2).max(ITEM_PAGE)
931        {
932            let present: std::collections::HashSet<&Id> =
933                collection.items.iter().map(|(id, _)| id).collect();
934            items.retain(|id, _| present.contains(id));
935        }
936    });
937}
938
939/// The resource of an item of a nested collection.
940fn nested_item(
941    vocabulary: &'static Vocabulary,
942    within: &[(&'static str, Id)],
943    field: &'static str,
944    id: &Id,
945    label: &str,
946) -> tilo_actions::ResourceSpec {
947    let mut child = tilo_actions::ResourceSpec::new(
948        nested_resource_id_in(vocabulary.kind, within, field, id),
949        format!("{}.{field}", vocabulary.kind),
950        label,
951    );
952    let mut path: Vec<crate::Segment> = Vec::new();
953    for (outer, outer_id) in within {
954        path.push(crate::Segment::Field((*outer).to_owned()));
955        path.push(crate::Segment::Item(outer_id.clone()));
956    }
957    path.push(crate::Segment::Field(field.to_owned()));
958    path.push(crate::Segment::Item(id.clone()));
959    if let Some(spec) = crate::resource::field_edit_spec_at_of(vocabulary, path) {
960        child = child.with_action(spec);
961    }
962    child
963}
964
965/// [`Resource::children_offer_bound`] of a record whose children are
966/// `others`, its `derived` resources, then its [`item_children`]: the
967/// declarations offered bound on `others`, on a derived resource or on the
968/// items of a collection, known from how many items each collection holds
969/// (`sizes`, by field) without building a child per item.
970pub fn offered_on_items<R: Resource>(
971    others: &[tilo_actions::ResourceSpec],
972    derived: &crate::derived::PublishedDerived,
973    sizes: &[(&'static str, usize)],
974    actions: &[ItemAction],
975    nested: &dyn Fn(&ItemAction) -> bool,
976) -> Vec<&'static str> {
977    let declarations = vocabulary::<R>().declarations();
978    let mut declared: Vec<(&'static str, Vec<&str>)> = Vec::with_capacity(declarations.len());
979    for decl in declarations.iter() {
980        let mut names = Vec::with_capacity(decl.params.len());
981        for param in &decl.params {
982            names.push(param.name.as_ref());
983        }
984        declared.push((decl.id, names));
985    }
986    offered_on_items_of(others, derived, sizes, actions, &declared, nested)
987}
988
989/// [`offered_on_items`] over the declarations `declared` (id and parameter
990/// names each). A verb on items of a nested collection is offered when
991/// `nested` says such an item is published.
992fn offered_on_items_of(
993    others: &[tilo_actions::ResourceSpec],
994    derived: &crate::derived::PublishedDerived,
995    sizes: &[(&'static str, usize)],
996    actions: &[ItemAction],
997    declared: &[(&'static str, Vec<&str>)],
998    nested: &dyn Fn(&ItemAction) -> bool,
999) -> Vec<&'static str> {
1000    let fields: Vec<&str> = sizes.iter().map(|(field, _)| *field).collect();
1001    // `item_children` binds the first declaration of an action's id.
1002    let first = |id: &str| declared.iter().find(|(declared, _)| *declared == id);
1003    let mut offered = Vec::new();
1004    for (id, params) in declared {
1005        let on_items = actions.iter().any(|action| {
1006            if action.action != *id {
1007                return false;
1008            }
1009            let Some((_, bound)) = first(action.action) else {
1010                return false;
1011            };
1012            if action.within.is_empty() {
1013                // What `offered_bound` asks of the item's spec: it takes
1014                // fewer parameters than the declaration.
1015                let kept = bound.iter().filter(|name| **name != action.param).count();
1016                kept < params.len()
1017                    && sizes
1018                        .iter()
1019                        .any(|&(field, size)| size > 0 && targets(action, &fields, field))
1020            } else {
1021                // A nested item binds the ids of the items it sits in too.
1022                let kept = bound
1023                    .iter()
1024                    .filter(|name| **name != action.param && !action.within_params.contains(name))
1025                    .count();
1026                kept < params.len() && nested(action)
1027            }
1028        });
1029        if on_items
1030            || offered_bound_as(others, id, params.len())
1031            || derived.offers_bound(id, params.len())
1032        {
1033            offered.push(*id);
1034        }
1035    }
1036    offered
1037}
1038
1039/// The spec of `decl` with its item parameter bound to `item`.
1040fn item_spec(decl: &Declaration, param: &'static str, item: &Id) -> ActionSpec {
1041    bound(
1042        decl,
1043        &[(
1044            param.to_owned(),
1045            serde_json::Value::String(item.as_str().to_owned()),
1046        )],
1047    )
1048}
1049
1050/// `decl` offered on the item it acts on, with `values` bound to their
1051/// parameters: what a published child carries ("remove *this* photograph",
1052/// "rename *this* album"). The other parameters stay typed; the action is
1053/// built, checked and undone exactly as the declaration is. Published on a
1054/// child, the declaration stays on the resource for scripts that name the
1055/// item, out of the palette's way.
1056pub fn bound<N: AsRef<str>>(decl: &Declaration, values: &[(N, serde_json::Value)]) -> ActionSpec {
1057    let mut owned: Vec<(String, serde_json::Value)> = Vec::with_capacity(values.len());
1058    for (name, value) in values {
1059        owned.push((name.as_ref().to_owned(), value.clone()));
1060    }
1061    bound_to(decl, owned)
1062}
1063
1064/// [`bound`] with its values owned: the type of `decl` with those parameters
1065/// bound, kept once for every item it is bound on, bound to `values`.
1066fn bound_to(decl: &Declaration, values: Vec<(String, serde_json::Value)>) -> ActionSpec {
1067    thread_local! {
1068        static KEPT: std::cell::RefCell<crate::kept::KeptTypes<BoundKey>> =
1069            std::cell::RefCell::default();
1070    }
1071    let names: Vec<String> = values.iter().map(|(name, _)| name.clone()).collect();
1072    let key = (decl.resource, decl.id, decl.refines, names);
1073    // The values are the item's, so the target holds them and the type
1074    // only names them; the spec fixes them for a caller that repeats one.
1075    crate::kept::kept_type(&KEPT, key, || bound_type(decl, &values))
1076        .bind(Target::new(values.clone()))
1077        .with_bound(values)
1078}
1079
1080/// Which bound type of a declaration: the kind of resource it is declared
1081/// on, its id, whether it refines one, and the names of its bound parameters.
1082type BoundKey = (&'static str, &'static str, bool, Vec<String>);
1083
1084/// The values a bound spec's [`Target`] holds, by parameter.
1085type BoundValues = Vec<(String, serde_json::Value)>;
1086
1087/// The type of `decl` with the parameters `values` names bound by its target.
1088fn bound_type(decl: &Declaration, values: &[(String, serde_json::Value)]) -> Arc<ActionType> {
1089    let params = unbound_params(&decl.params, values);
1090    let all = decl.params.clone();
1091    let build = Arc::clone(&decl.build);
1092    let label = decl.shown_label();
1093    let spec = ActionSpec::typed_on(
1094        decl.id,
1095        label.clone(),
1096        label,
1097        ExecutionLocus::ClientLocal,
1098        params,
1099        move |target, args| {
1100            let mut arguments = args.to_json();
1101            for (name, value) in target.get::<BoundValues>().into_iter().flatten() {
1102                // An optional parameter bound to nothing is left out.
1103                if !value.is_null() {
1104                    arguments.insert(name.clone(), value.clone());
1105                }
1106            }
1107            let action = match ActionArgs::bind_json(&all, &arguments) {
1108                Ok(args) => {
1109                    crate::content::invoking(|| build(&args, crate::resource::origin_now_ms()))
1110                }
1111                Err(error) => Err(error.to_string()),
1112            };
1113            crate::resource::encode_built(action)
1114        },
1115    )
1116    .of_kind(decl.kind);
1117    let spec = finish_bound(spec, decl);
1118    Arc::clone(spec.action_type())
1119}
1120
1121/// The parameters of `params` that `values` leaves to the caller.
1122fn unbound_params(
1123    params: &[ActionParam],
1124    values: &[(String, serde_json::Value)],
1125) -> Vec<ActionParam> {
1126    params
1127        .iter()
1128        .filter(|candidate| !values.iter().any(|(name, _)| candidate.name == *name))
1129        .cloned()
1130        .collect()
1131}
1132
1133/// What a bound spec carries over from its declaration.
1134fn finish_bound(mut spec: ActionSpec, decl: &Declaration) -> ActionSpec {
1135    if let Some(field) = decl.field {
1136        spec = spec.below_field(field);
1137    }
1138    if let Some(description) = &decl.description {
1139        spec = spec.with_description(description.clone());
1140    }
1141    // On its item it is the same act, in the same picture, said with the same
1142    // words.
1143    spec = crate::resource::with_declared_words(spec, decl);
1144    // Offered to whom it is declared for, housekept and undone as declared:
1145    // `#[action(audience = "people", item = ...)]` is no agent's on its item
1146    // either. Before `destructive`, which settles its confirmation from what
1147    // the tags say and would otherwise ask about the undo they declare.
1148    for tag in &decl.tags {
1149        if !spec.contract.tags.contains(tag) {
1150            spec.type_mut().contract.tags.push(tag.clone());
1151        }
1152    }
1153    if decl.destructive {
1154        spec = spec.destructive();
1155    }
1156    // On its item it is the same kind of step, making the same thing.
1157    let contract = &mut spec.type_mut().contract;
1158    (contract.step, contract.creates) = (decl.step, decl.creates.map(str::to_owned));
1159    // An item verb that answers answers on its item too.
1160    if let Some(result) = &decl.result {
1161        spec.type_mut().contract.result = result.clone();
1162    }
1163    spec
1164}
1165
1166/// Whether some resource in `children`, at any depth, offers `decl` with
1167/// arguments bound ([`bound`]).
1168#[must_use]
1169pub fn offered_bound(children: &[tilo_actions::ResourceSpec], decl: &Declaration) -> bool {
1170    offered_bound_as(children, decl.id, decl.params.len())
1171}
1172
1173/// [`offered_bound`] of the declaration `id` taking `params` parameters.
1174fn offered_bound_as(children: &[tilo_actions::ResourceSpec], id: &str, params: usize) -> bool {
1175    children.iter().any(|child| {
1176        child
1177            .actions
1178            .iter()
1179            .any(|spec| spec.id == id && spec.params().len() < params)
1180            || offered_bound_as(&child.children, id, params)
1181    })
1182}
1183
1184#[cfg(test)]
1185mod item_kind_tests {
1186    #[test]
1187    fn an_items_kind_is_read_from_its_id() {
1188        let id = super::item_resource_id_in("notes.notebook", "pages", &super::Id::from_raw("p1"));
1189        assert_eq!(
1190            super::item_kind(&id).as_deref(),
1191            Some("notes.notebook.pages")
1192        );
1193        assert_eq!(
1194            super::item_kind("notes.notebook"),
1195            None,
1196            "the record itself"
1197        );
1198        assert_eq!(
1199            super::item_kind("deck/slides/s1/elements/e1"),
1200            None,
1201            "a nested item"
1202        );
1203    }
1204}
1205
1206#[cfg(test)]
1207mod target_field_tests {
1208    use super::target_field;
1209
1210    #[test]
1211    fn a_parameter_names_an_item_only_of_the_collection_it_is_named_after() {
1212        // The field the verb names, whatever its parameter is called.
1213        assert_eq!(
1214            target_field(&["cards", "archive"], "card", "archive"),
1215            Some("archive")
1216        );
1217        assert_eq!(target_field(&["cards"], "card", "pages"), None);
1218        // The collection the parameter is named after.
1219        assert_eq!(
1220            target_field(&["cards", "archive"], "archive", ""),
1221            Some("archive")
1222        );
1223        // The record's only collection, where the parameter is called what
1224        // one of its items is.
1225        assert_eq!(target_field(&["issues"], "issue", ""), Some("issues"));
1226        assert_eq!(
1227            target_field(&["shell_parts"], "shell-part", ""),
1228            Some("shell_parts")
1229        );
1230        // A parameter named after no collection names no item, also where
1231        // the record keeps one collection only: a conversation is no message.
1232        assert_eq!(target_field(&["messages"], "channel", ""), None);
1233        assert_eq!(target_field(&["cards", "archive"], "place", ""), None);
1234    }
1235}