1use std::{
4 collections::HashMap,
5 sync::atomic::{AtomicBool, AtomicUsize, Ordering},
6};
7
8use topcoat::{Result, context::Cx, view::*};
9
10use super::{
11 Schema,
12 condition::{Condition, disable, watch},
13 embedded::Embedded,
14 fields::{Field, Placement},
15 layouts::{Grid, Group, Section, Step, Tab, Tabs, Wizard, spanned},
16};
17use crate::values::{FieldError, FieldErrors, FormValue, FormValues};
18
19#[derive(Debug)]
20pub(crate) enum Node {
21 Field(usize),
23 Section(Box<Section>),
24 Group(Box<Group>),
25 Grid(Box<Grid>),
26 Tabs(Box<Tabs>),
28 Tab(Box<Tab>),
30 Wizard(Box<Wizard>),
32 Step(Box<Step>),
34 Embedded(Box<Embedded>),
35}
36
37pub struct Source<'a> {
39 values: &'a FormValues,
40 errors: &'a FieldErrors,
41 watched: HashMap<String, Vec<Condition>>,
43 scope: String,
46 options: Option<String>,
49 editing: bool,
51 mask: super::FormMask,
53 prefix: String,
55 tab_depth: AtomicUsize,
58 flat: bool,
60 in_panel: AtomicBool,
64}
65
66impl<'a> Source<'a> {
67 pub fn form(values: &'a FormValues, errors: &'a FieldErrors) -> Self {
69 Self {
70 values,
71 errors,
72 watched: HashMap::new(),
73 scope: String::new(),
74 options: None,
75 editing: false,
76 mask: super::FormMask::default(),
77 prefix: String::new(),
78 tab_depth: AtomicUsize::new(0),
79 flat: false,
80 in_panel: AtomicBool::new(false),
81 }
82 }
83
84 pub(crate) fn flat(mut self, flat: bool) -> Self {
86 self.flat = flat;
87 self
88 }
89
90 pub(super) fn is_flat(&self) -> bool {
92 self.flat
93 }
94
95 pub(crate) fn within_panel(self) -> Self {
97 self.in_panel.store(true, Ordering::Relaxed);
98 self
99 }
100
101 pub(crate) fn in_panel(&self) -> bool {
103 self.in_panel.load(Ordering::Relaxed)
104 }
105
106 pub(crate) fn set_in_panel(&self, inside: bool) -> bool {
108 self.in_panel.swap(inside, Ordering::Relaxed)
109 }
110
111 pub(crate) fn editing(mut self, editing: bool) -> Self {
113 self.editing = editing;
114 self
115 }
116
117 pub(crate) fn masked(mut self, mask: super::FormMask) -> Self {
119 self.mask = mask;
120 self
121 }
122
123 pub(crate) fn scoped(mut self, scope: impl Into<String>) -> Self {
126 self.scope = scope.into();
127 self
128 }
129
130 pub(crate) fn posting_under(mut self, prefix: impl Into<String>) -> Self {
133 self.prefix = prefix.into();
134 self
135 }
136
137 pub(crate) fn options_at(mut self, url: impl Into<String>) -> Self {
139 self.options = Some(url.into());
140 self
141 }
142
143 pub(crate) fn scope(&self) -> &str {
145 &self.scope
146 }
147
148 pub(crate) fn watching(mut self, watched: HashMap<String, Vec<Condition>>) -> Self {
150 self.watched = watched;
151 self
152 }
153
154 pub(crate) fn guard<'v>(
156 &self,
157 cx: &'v Cx,
158 condition: Option<&Condition>,
159 view: BoxView<'v>,
160 ) -> BoxView<'v> {
161 match condition {
162 Some(condition) => condition.guard(cx, &self.scope, self.values, view),
163 None => view,
164 }
165 }
166
167 pub(crate) fn tab_depth(&self) -> usize {
169 self.tab_depth.load(Ordering::Relaxed)
170 }
171
172 pub(crate) fn set_tab_depth(&self, depth: usize) {
174 self.tab_depth.store(depth, Ordering::Relaxed);
175 }
176
177 pub(crate) fn holds(&self, condition: Option<&Condition>) -> bool {
180 condition.is_none_or(|condition| condition.holds(self.values))
181 }
182
183 pub(crate) fn value(&self, name: &str) -> Option<&FormValue> {
184 self.values.get(name)
185 }
186
187 pub(crate) fn text(&self, name: &str) -> Option<&str> {
189 self.values.text(name)
190 }
191
192 pub(crate) fn rows(&self, name: &str) -> &[FormValues] {
194 self.values.rows(name).unwrap_or_default()
195 }
196
197 pub(crate) fn errors(&self) -> &FieldErrors {
199 self.errors
200 }
201
202 pub(crate) fn options(&self) -> Option<&str> {
204 self.options.as_deref()
205 }
206
207 pub(crate) fn id(&self, name: &str) -> String {
209 self.placement(name, None).id(name)
210 }
211
212 fn placement<'p>(&'p self, name: &str, parent: Option<&'p str>) -> Placement<'p> {
214 Placement {
215 parent,
216 scope: &self.scope,
217 options: self.options.as_deref(),
218 editing: self.editing,
219 locked: self.mask.locks(name),
220 prefix: &self.prefix,
221 }
222 }
223
224 pub(crate) fn error_for(&self, field: &Field) -> Option<&FieldError> {
226 self.errors.first(field.name())
227 }
228}
229
230impl Node {
231 pub(crate) async fn render<'a>(
233 &self,
234 cx: &'a Cx,
235 fields: &[Field],
236 source: &Source<'_>,
237 ) -> Result<BoxView<'a>> {
238 match self {
239 Node::Field(index) => {
240 if !shows(&fields[*index], source) {
241 return Ok(().boxed());
242 }
243 let field = &fields[*index];
244 if let Some(repeater) = field.as_repeater() {
246 let view = Box::pin(repeater.render(cx, field, source)).await?;
247 let view = spanned(cx, field.span(), view);
248 return Ok(source.guard(cx, field.condition(), view));
249 }
250 let error = source.error_for(field);
251 let parent = field.parent_key().and_then(|key| source.text(key));
252 let mut view = Box::pin(field.render_under(
253 cx,
254 source.value(field.name()),
255 error,
256 source.placement(field.name(), parent),
257 ))
258 .await?;
259 if let Some(conditions) = source.watched.get(field.name()) {
260 let posted = format!("{}{}", source.prefix, field.name());
261 view = watch(
262 cx,
263 field,
264 &posted,
265 conditions,
266 &source.scope,
267 source.values,
268 view,
269 );
270 }
271 if let Some(condition) = field.disabling() {
272 view = disable(cx, condition, &source.scope, source.values, view);
273 }
274 let view = spanned(cx, field.span(), view);
275 Ok(source.guard(cx, field.condition(), view))
276 }
277 Node::Section(_) | Node::Group(_) | Node::Grid(_) | Node::Tabs(_) | Node::Wizard(_)
279 if !self.shows_any(fields, source) =>
280 {
281 Ok(().boxed())
282 }
283 Node::Section(s) => {
284 let view = Box::pin(s.render(cx, fields, source)).await?;
285 Ok(source.guard(cx, s.condition.as_ref(), view))
286 }
287 Node::Group(g) => {
288 let view = Box::pin(g.render(cx, fields, source)).await?;
289 Ok(source.guard(cx, g.condition.as_ref(), view))
290 }
291 Node::Grid(g) => {
292 let view = Box::pin(g.render(cx, fields, source)).await?;
293 Ok(source.guard(cx, g.condition.as_ref(), view))
294 }
295 Node::Tabs(t) => {
296 let view = Box::pin(t.render(cx, fields, source)).await?;
297 Ok(source.guard(cx, t.condition.as_ref(), view))
298 }
299 Node::Tab(t) => Box::pin(render_nodes(cx, &t.children.nodes, fields, source)).await,
301 Node::Wizard(w) => {
302 let view = Box::pin(w.render(cx, fields, source)).await?;
303 Ok(source.guard(cx, w.condition.as_ref(), view))
304 }
305 Node::Step(s) => Box::pin(render_nodes(cx, &s.children.nodes, fields, source)).await,
307 Node::Embedded(e) => Box::pin(e.render(cx, fields, source)).await,
308 }
309 }
310
311 pub(crate) fn has_error(&self, fields: &[Field], source: &Source<'_>) -> bool {
314 let mut any = false;
315 self.visit_fields(&mut |index| {
316 let name = fields[index].name();
317 any |= source.errors.iter().any(|error| {
318 error.key == name
319 || error
320 .key
321 .strip_prefix(name)
322 .is_some_and(|rest| rest.starts_with('.'))
323 });
324 });
325 any
326 }
327
328 pub(crate) fn first_field(&self) -> Option<usize> {
330 let mut first = None;
331 self.visit_fields(&mut |index| {
332 first.get_or_insert(index);
333 });
334 first
335 }
336
337 fn visit_fields(&self, f: &mut impl FnMut(usize)) {
339 match self {
340 Node::Field(index) => f(*index),
341 Node::Embedded(e) => e.visit_fields(f),
342 node => {
343 for child in node.children().unwrap_or_default() {
344 child.visit_fields(f);
345 }
346 }
347 }
348 }
349
350 pub(crate) fn shows_any(&self, fields: &[Field], source: &Source<'_>) -> bool {
352 match self {
353 Node::Field(index) => shows(&fields[*index], source),
354 Node::Embedded(e) => {
355 let mut any = false;
356 e.visit_fields(&mut |index| any |= shows(&fields[index], source));
357 any
358 }
359 node => node
360 .children()
361 .unwrap_or_default()
362 .iter()
363 .any(|child| child.shows_any(fields, source)),
364 }
365 }
366
367 pub(crate) fn children(&self) -> Option<&[Node]> {
370 match self {
371 Node::Section(s) => Some(&s.children.nodes),
372 Node::Group(g) => Some(&g.children.nodes),
373 Node::Grid(g) => Some(&g.children.nodes),
374 Node::Tabs(t) => Some(&t.children.nodes),
375 Node::Tab(t) => Some(&t.children.nodes),
376 Node::Wizard(w) => Some(&w.children.nodes),
377 Node::Step(s) => Some(&s.children.nodes),
378 Node::Field(_) | Node::Embedded(_) => None,
379 }
380 }
381
382 fn children_mut(&mut self) -> Option<&mut Vec<Node>> {
383 match self {
384 Node::Section(s) => Some(&mut s.children.nodes),
385 Node::Group(g) => Some(&mut g.children.nodes),
386 Node::Grid(g) => Some(&mut g.children.nodes),
387 Node::Tabs(t) => Some(&mut t.children.nodes),
388 Node::Tab(t) => Some(&mut t.children.nodes),
389 Node::Wizard(w) => Some(&mut w.children.nodes),
390 Node::Step(s) => Some(&mut s.children.nodes),
391 Node::Field(_) | Node::Embedded(_) => None,
392 }
393 }
394
395 pub(crate) fn offset(&mut self, by: usize) {
397 match self {
398 Node::Field(index) => *index += by,
399 Node::Embedded(e) => e.offset(by),
400 _ => {
401 for child in self.children_mut().into_iter().flatten() {
402 child.offset(by);
403 }
404 }
405 }
406 }
407}
408
409impl<F> Schema<F> {
410 pub(crate) fn needs_own_keys(&self) -> Option<&str> {
414 let mut embedded = Vec::new();
415 for node in &self.nodes {
416 node.embedded_fields(&mut embedded);
417 }
418 self.fields
419 .iter()
420 .enumerate()
421 .find(|(index, field)| {
422 embedded.contains(index)
423 || field.is_file()
424 || field.as_repeater().is_some()
425 || field.parent_key().is_some()
426 || field
427 .as_choice()
428 .is_some_and(|choice| choice.is_searchable())
429 })
430 .map(|(_, field)| field.name())
431 }
432}
433
434impl Node {
435 fn embedded_fields(&self, out: &mut Vec<usize>) {
437 match self {
438 Node::Embedded(e) => e.visit_fields(&mut |index| out.push(index)),
439 node => {
440 for child in node.children().unwrap_or_default() {
441 child.embedded_fields(out);
442 }
443 }
444 }
445 }
446}
447
448fn shows(field: &Field, source: &Source<'_>) -> bool {
451 !(source.mask.hides(field.name())
452 || field.is_hidden(source.editing)
453 || (source.mask.locks(field.name()) && field.as_repeater().is_some()))
454}
455
456pub(crate) async fn render_nodes<'a>(
458 cx: &'a Cx,
459 nodes: &[Node],
460 fields: &[Field],
461 source: &Source<'_>,
462) -> Result<BoxView<'a>> {
463 let mut views = Vec::with_capacity(nodes.len());
464 for node in nodes {
465 views.push(node.render(cx, fields, source).await?);
466 }
467 Ok(view! {
468 for v in views {
469 (v)
470 }
471 }
472 .boxed())
473}
474
475#[diagnostic::on_unimplemented(
480 message = "`{Self}` cannot be placed in a `Schema<{F}>`",
481 label = "not a control, layout block, schema, or tuple of 2 to 12 of them for this schema",
482 note = "a resource's form places its record form's own controls, from `controls()`; \
483 `Field::text` and the other constructors build a page's or an action's controls"
484)]
485pub trait IntoSchema<F = ()> {
486 fn into_schema(self) -> Schema<F>;
487}
488
489#[doc(hidden)]
492pub trait Retype {
493 type As<G>;
494
495 fn retype<G>(self) -> Self::As<G>;
496}
497
498impl<F> IntoSchema<F> for Schema<F> {
499 fn into_schema(self) -> Schema<F> {
500 self
501 }
502}
503
504impl IntoSchema for Field {
505 fn into_schema(self) -> Schema {
506 Schema::from_parts(vec![Node::Field(0)], vec![self])
507 }
508}
509
510macro_rules! container_nodes {
513 ($($ty:ident),+ $(,)?) => {
514 $(
515 impl<F> IntoSchema<F> for $ty<Schema<F>> {
516 fn into_schema(self) -> Schema<F> {
517 let mut fields = Vec::new();
518 let block = self.map(|mut children| {
519 fields = std::mem::take(&mut children.fields);
520 children.retype()
521 });
522 Schema::from_parts(vec![Node::$ty(Box::new(block))], fields)
523 }
524 }
525
526 impl<F> IntoSchema<F> for $ty<()> {
527 fn into_schema(self) -> Schema<F> {
528 self.holding(Schema::<F>::default()).into_schema()
529 }
530 }
531 )+
532 };
533}
534
535container_nodes!(Section, Group, Grid);
536
537impl<F> IntoSchema<F> for Tabs<Schema<F>> {
538 fn into_schema(self) -> Schema<F> {
539 let mut fields = Vec::new();
540 let block = self.map(|mut children| {
541 fields = std::mem::take(&mut children.fields);
542 children.retype()
543 });
544 Schema::from_parts(vec![Node::Tabs(Box::new(block))], fields)
545 }
546}
547
548macro_rules! into_schema_tuples {
550 ($($T:ident => $v:ident),+ $(,)?) => {
551 impl<Form, $($T),+> IntoSchema<Form> for ($($T,)+)
552 where
553 $($T: IntoSchema<Form>,)+
554 {
555 fn into_schema(self) -> Schema<Form> {
556 let ($($v,)+) = self;
557 let mut schema = Schema::default();
558 $( schema.append($v.into_schema()); )+
559 schema
560 }
561 }
562 };
563}
564
565into_schema_tuples!(A => a, B => b);
566into_schema_tuples!(A => a, B => b, C => c);
567into_schema_tuples!(A => a, B => b, C => c, D => d);
568into_schema_tuples!(A => a, B => b, C => c, D => d, E => e);
569into_schema_tuples!(A => a, B => b, C => c, D => d, E => e, F => f);
570into_schema_tuples!(A => a, B => b, C => c, D => d, E => e, F => f, G => g);
571into_schema_tuples!(
572 A => a, B => b, C => c, D => d, E => e, F => f, G => g, H => h
573);
574into_schema_tuples!(
575 A => a, B => b, C => c, D => d, E => e, F => f, G => g, H => h, I => i
576);
577into_schema_tuples!(
578 A => a, B => b, C => c, D => d, E => e, F => f, G => g, H => h, I => i, J => j
579);
580into_schema_tuples!(
581 A => a, B => b, C => c, D => d, E => e, F => f, G => g, H => h, I => i, J => j, K => k
582);
583into_schema_tuples!(
584 A => a, B => b, C => c, D => d, E => e, F => f, G => g, H => h, I => i, J => j, K => k, L => l
585);