1use 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#[derive(Clone, Debug, PartialEq, Eq)]
114pub struct ItemText {
115 pub field: &'static str,
117 pub id: Id,
118 pub label: String,
120 pub text: String,
122}
123
124#[derive(Clone, Debug, PartialEq, Eq)]
126pub struct ItemCollection {
127 pub field: &'static str,
129 pub labelled: bool,
133 pub items: Vec<(Id, String)>,
135 pub within: Vec<(&'static str, Id)>,
139}
140
141pub trait ItemSource {
145 fn item_collection(&self, field: &'static str) -> ItemCollection;
147 fn item_presence(&self) -> usize;
149 fn label_of_item(&self, id: &Id) -> Option<String>;
151 fn item_texts(&self, field: &'static str, found: &mut Vec<ItemText>);
153 fn nested_items(&self, field: &'static str, out: &mut Vec<ItemCollection>);
155}
156
157pub 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
163fn 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
178pub struct ItemAction {
179 pub action: &'static str,
181 pub param: &'static str,
183 pub collection: Option<&'static str>,
185 pub within: &'static [&'static str],
188 pub within_params: &'static [&'static str],
190}
191
192pub fn item_resource_id<R: Resource>(field: &str, item: &Id) -> String {
194 item_resource_id_in(R::KIND, field, item)
195}
196
197pub 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#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
220pub struct Ref(String);
221
222impl Ref {
223 #[must_use]
225 pub fn new(text: impl Into<String>) -> Self {
226 Self(text.into())
227 }
228
229 #[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
266const 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
314pub fn item_of_resource<R: Resource>(resource_id: &str) -> Option<(&str, Id)> {
316 item_of_resource_in(R::KIND, resource_id)
317}
318
319#[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
341pub const ITEM_PAGE: usize = 256;
344
345type Cached = HashMap<Id, (String, u64, tilo_actions::ResourceSpec)>;
346
347thread_local! {
348 static BUILT: RefCell<HashMap<(TypeId, String), Cached>> = RefCell::new(HashMap::new());
352}
353
354fn 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
369fn 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 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 if let Some(spec) = crate::resource::item_field_edit_spec_of(vocabulary, field, id) {
442 child = child.with_action(spec);
443 }
444 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
462fn 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
479pub const RENAME: &str = "rename";
481
482fn 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
498fn 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 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#[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
581pub 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 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
606fn 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
620fn 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#[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#[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#[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
714fn one_of(field: &str, param: &str) -> bool {
718 tilo_actions::singular(&tilo_actions::in_words(field)) == tilo_actions::in_words(param)
719}
720
721#[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
764pub 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
782pub type ItemChildVisitor<'a> =
785 dyn FnMut(&ItemCollection, &Id, &str, &dyn Fn() -> tilo_actions::ResourceSpec) + 'a;
786
787pub 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
801fn 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 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
865pub 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
874pub struct ChildrenParts {
879 pub others: Vec<tilo_actions::ResourceSpec>,
881 pub kept: Rc<[Rc<tilo_actions::ResourceSpec>]>,
886 pub items: Vec<ItemCollection>,
888 pub item_actions: Vec<ItemAction>,
890}
891
892fn 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
901fn outer_fields(collection: &ItemCollection) -> Vec<&'static str> {
903 collection.within.iter().map(|(field, _)| *field).collect()
904}
905
906fn 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
923fn 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
939fn 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
965pub 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
989fn 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 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 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 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
1039fn 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
1050pub 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
1064fn 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 crate::kept::kept_type(&KEPT, key, || bound_type(decl, &values))
1076 .bind(Target::new(values.clone()))
1077 .with_bound(values)
1078}
1079
1080type BoundKey = (&'static str, &'static str, bool, Vec<String>);
1083
1084type BoundValues = Vec<(String, serde_json::Value)>;
1086
1087fn 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 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
1121fn 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
1133fn 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 spec = crate::resource::with_declared_words(spec, decl);
1144 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 let contract = &mut spec.type_mut().contract;
1158 (contract.step, contract.creates) = (decl.step, decl.creates.map(str::to_owned));
1159 if let Some(result) = &decl.result {
1161 spec.type_mut().contract.result = result.clone();
1162 }
1163 spec
1164}
1165
1166#[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
1173fn 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 assert_eq!(
1214 target_field(&["cards", "archive"], "card", "archive"),
1215 Some("archive")
1216 );
1217 assert_eq!(target_field(&["cards"], "card", "pages"), None);
1218 assert_eq!(
1220 target_field(&["cards", "archive"], "archive", ""),
1221 Some("archive")
1222 );
1223 assert_eq!(target_field(&["issues"], "issue", ""), Some("issues"));
1226 assert_eq!(
1227 target_field(&["shell_parts"], "shell-part", ""),
1228 Some("shell_parts")
1229 );
1230 assert_eq!(target_field(&["messages"], "channel", ""), None);
1233 assert_eq!(target_field(&["cards", "archive"], "place", ""), None);
1234 }
1235}