tablo_core/schema/layouts/
wizard.rs1use topcoat::{
4 Result,
5 context::Cx,
6 view::{StaticClass, class, *},
7};
8
9use super::{Span, spanned, tab_id};
10use crate::schema::{
11 Schema,
12 condition::Condition,
13 fields::Field,
14 tree::{IntoSchema, Node, Retype, Source, render_nodes},
15};
16
17const STEP_LIST: StaticClass =
20 class!("flex flex-wrap items-center gap-x-6 gap-y-2 [counter-reset:tablo-step]");
21const STEP_TRIGGER: StaticClass = class!(
23 "group inline-flex items-center gap-2 rounded-md text-sm font-medium text-muted-foreground \
24 outline-none [counter-increment:tablo-step] focus-visible:ring-[3px] \
25 focus-visible:ring-ring/50 aria-[current=step]:text-foreground \
26 data-wizard-error:text-destructive"
27);
28const STEP_NUMBER: StaticClass = class!(
30 "flex size-7 shrink-0 items-center justify-center rounded-full border border-input text-xs \
31 before:content-[counter(tablo-step)] group-data-wizard-done:border-primary \
32 group-data-wizard-done:text-primary group-aria-[current=step]:border-primary \
33 group-aria-[current=step]:bg-primary group-aria-[current=step]:text-primary-foreground \
34 group-data-wizard-error:border-destructive group-data-wizard-error:text-destructive"
35);
36
37#[derive(Debug)]
63pub struct Wizard<C = Schema> {
64 pub(crate) children: C,
66 pub(crate) condition: Option<Condition>,
67 pub(super) span: Option<Span>,
68}
69
70impl Wizard<()> {
71 pub fn new<F>(steps: impl IntoIterator<Item = Step<Schema<F>>>) -> Wizard<Schema<F>> {
73 let mut children = Schema::<F>::default();
74 for step in steps {
75 let mut fields = Vec::new();
76 let step = step.map(|mut children| {
77 fields = std::mem::take(&mut children.fields);
78 children.retype()
79 });
80 children.append(Schema::from_parts(vec![Node::Step(Box::new(step))], fields));
81 }
82 Wizard {
83 children,
84 condition: None,
85 span: None,
86 }
87 }
88}
89
90impl<C> Wizard<C> {
91 pub(crate) fn map<D>(self, f: impl FnOnce(C) -> D) -> Wizard<D> {
92 Wizard {
93 children: f(self.children),
94 condition: self.condition,
95 span: self.span,
96 }
97 }
98}
99
100impl<F> IntoSchema<F> for Wizard<Schema<F>> {
101 fn into_schema(self) -> Schema<F> {
102 let mut fields = Vec::new();
103 let block = self.map(|mut children| {
104 fields = std::mem::take(&mut children.fields);
105 children.retype()
106 });
107 Schema::from_parts(vec![Node::Wizard(Box::new(block))], fields)
108 }
109}
110
111#[derive(Debug)]
113pub struct Step<C = Schema> {
114 label: crate::Text,
115 pub(crate) children: C,
116 pub(crate) condition: Option<Condition>,
117}
118
119impl Step<()> {
120 pub fn new(label: impl Into<crate::Text>) -> Self {
121 Self {
122 label: label.into(),
123 children: (),
124 condition: None,
125 }
126 }
127
128 pub fn schema<F>(self, children: impl IntoSchema<F>) -> Step<Schema<F>> {
130 self.map(|_| children.into_schema())
131 }
132}
133
134impl<C> Step<C> {
135 pub(crate) fn map<D>(self, f: impl FnOnce(C) -> D) -> Step<D> {
136 Step {
137 label: self.label,
138 children: f(self.children),
139 condition: self.condition,
140 }
141 }
142}
143
144pub(crate) struct ExtraStep<'a> {
146 pub(crate) id: String,
148 pub(crate) label: crate::Text,
149 pub(crate) errored: bool,
151 pub(crate) body: BoxView<'a>,
152}
153
154impl Wizard<Schema> {
155 pub(crate) async fn render<'a>(
156 &self,
157 cx: &'a Cx,
158 fields: &[Field],
159 source: &Source<'_>,
160 ) -> Result<BoxView<'a>> {
161 self.render_with(cx, fields, source, Vec::new()).await
162 }
163
164 pub(crate) async fn render_with<'a>(
166 &self,
167 cx: &'a Cx,
168 fields: &[Field],
169 source: &Source<'_>,
170 extra: Vec<ExtraStep<'a>>,
171 ) -> Result<BoxView<'a>> {
172 let steps: Vec<(&Node, &Step)> = self
173 .children
174 .nodes
175 .iter()
176 .filter_map(|node| match node {
177 Node::Step(step) if node.shows_any(fields, source) => Some((node, &**step)),
178 _ => None,
179 })
180 .collect();
181 let errored: Vec<bool> = steps
182 .iter()
183 .map(|(node, _)| node.has_error(fields, source))
184 .chain(extra.iter().map(|step| step.errored))
185 .collect();
186 let shown: Vec<bool> = steps
188 .iter()
189 .map(|(_, step)| source.holds(step.condition.as_ref()))
190 .chain(extra.iter().map(|_| true))
191 .collect();
192 let active = errored
193 .iter()
194 .position(|e| *e)
195 .unwrap_or_else(|| shown.iter().position(|s| *s).unwrap_or(0));
196 let first = shown.iter().position(|s| *s);
197 let last = shown.iter().rposition(|s| *s);
198 let depth = source.tab_depth();
199 let mut triggers = Vec::with_capacity(steps.len());
200 let mut panels = Vec::with_capacity(steps.len());
201 for (index, (node, step)) in steps.iter().enumerate() {
202 let id = node
203 .first_field()
204 .map(|field| tab_id(&source.id(fields[field].name()), depth))
205 .unwrap_or_default();
206 source.set_tab_depth(depth + 1);
207 let body = render_nodes(cx, &step.children.nodes, fields, source).await;
208 source.set_tab_depth(depth);
209 let (trigger, panel) = step_view(
210 cx,
211 &id,
212 &step.label,
213 index.cmp(&active),
214 errored[index],
215 body?,
216 );
217 triggers.push(source.guard(cx, step.condition.as_ref(), trigger));
218 panels.push(source.guard(cx, step.condition.as_ref(), panel));
219 }
220 let own = steps.len();
221 for (offset, step) in extra.into_iter().enumerate() {
222 let index = own + offset;
223 let place = index.cmp(&active);
224 let (trigger, panel) =
225 step_view(cx, &step.id, &step.label, place, errored[index], step.body);
226 triggers.push(trigger);
227 panels.push(panel);
228 }
229 let view = view! {
230 <div data-wizard="" class="flex flex-col gap-6">
231 <div class=(STEP_LIST)>
232 for trigger in triggers {
233 (trigger)
234 }
235 </div>
236 for panel in panels {
237 (panel)
238 }
239 <div class="flex items-center justify-between gap-2">
240 tablo_ui::button(
241 variant: tablo_ui::ButtonVariant::Outline,
242 attrs: attributes! {
243 type="button"
244 data-wizard-back=""
245 hidden=(first.is_none_or(|first| active <= first))
246 },
247 (crate::t!(cx, "tablo-wizard-back"))
248 )
249 tablo_ui::button(
250 variant: tablo_ui::ButtonVariant::Secondary,
251 attrs: attributes! {
252 type="button"
253 data-wizard-next=""
254 class="ms-auto"
255 hidden=(last.is_none_or(|last| active >= last))
256 },
257 (crate::t!(cx, "tablo-wizard-next"))
258 )
259 </div>
260 </div>
261 }
262 .boxed();
263 Ok(spanned(cx, self.span, view))
264 }
265}
266
267fn step_view<'a>(
270 cx: &'a Cx,
271 id: &str,
272 label: &crate::Text,
273 place: std::cmp::Ordering,
274 errored: bool,
275 body: BoxView<'a>,
276) -> (BoxView<'a>, BoxView<'a>) {
277 let trigger_id = format!("{id}-step");
278 let panel_id = format!("{id}-steppanel");
279 let labelled_by = trigger_id.clone();
280 let controls = panel_id.clone();
281 let label = label.localize(cx);
282 let current = place.is_eq();
283 let trigger = view! {
284 <button
285 type="button"
286 id=(trigger_id)
287 aria-controls=(controls)
288 aria-current=(current.then_some("step"))
289 data-wizard-trigger=""
290 data-wizard-done=(place.is_lt())
291 data-wizard-error=(errored)
292 class=(STEP_TRIGGER)
293 >
294 <span aria-hidden="true" class=(STEP_NUMBER)></span>
295 (label)
296 </button>
297 }
298 .boxed();
299 let panel = view! {
300 <div
301 role="group"
302 id=(panel_id)
303 aria-labelledby=(labelled_by)
304 hidden=(!current)
305 data-wizard-step=""
306 class="flex flex-col gap-6"
307 >
308 (body)
309 </div>
310 }
311 .boxed();
312 (trigger, panel)
313}