anathema-widgets 0.2.11

Anathema widget base
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
// -----------------------------------------------------------------------------
//   - Here be dragons -
//   This code needs cleaning up.
//
//   At some point this should be better documented and broken
//   into smaller pieces.
//
//   TODO: clean this blessed mess
// -----------------------------------------------------------------------------
use std::ops::ControlFlow;

use anathema_state::Value as StateValue;
use anathema_templates::blueprints::Blueprint;
use anathema_value_resolver::{AttributeStorage, Scope};

use crate::error::Result;
use crate::layout::{LayoutCtx, LayoutFilter};
use crate::nodes::loops::Iteration;
use crate::nodes::{controlflow, eval_blueprint};
use crate::widget::WidgetTreeView;
use crate::{Element, WidgetContainer, WidgetId, WidgetKind};

pub mod debug;

// TODO:
// Add the option to "skip" values with an offset for `inner_each` (this is for overflow widgets)
// Note that this might not be possible, depending on how widget generation goes

/// Determine what kind of widgets that should be laid out:
/// Fixed or floating.
#[derive(Debug, Copy, Clone)]
pub enum WidgetPositionFilter {
    Floating,
    Fixed,
    All,
    None,
}

#[derive(Debug, Copy, Clone)]
pub enum Generator<'widget, 'bp> {
    Single {
        ident: &'bp str,
        body: &'bp [Blueprint],
    },
    Loop {
        len: usize,
        binding: &'bp str,
        body: &'bp [Blueprint],
    },
    Iteration {
        binding: &'bp str,
        body: &'bp [Blueprint],
    },
    With {
        binding: &'bp str,
        body: &'bp [Blueprint],
    },
    ControlFlow(&'widget controlflow::ControlFlow<'bp>),
    ControlFlowContainer(&'bp [Blueprint]),
    Slot(&'bp [Blueprint]),
}

impl<'widget, 'bp> Generator<'widget, 'bp> {
    fn from_loop(body: &'bp [Blueprint], binding: &'bp str, len: usize) -> Self {
        Self::Loop { binding, body, len }
    }

    fn from_with(body: &'bp [Blueprint], binding: &'bp str) -> Self {
        Self::With { binding, body }
    }
}

impl<'widget, 'bp> From<&'widget WidgetContainer<'bp>> for Generator<'widget, 'bp> {
    fn from(widget: &'widget WidgetContainer<'bp>) -> Self {
        match &widget.kind {
            WidgetKind::Element(_) => panic!("use Self::Single directly"),
            WidgetKind::For(_) => panic!("use Self::Loop directly"),
            WidgetKind::With(_) => panic!("use Self::With directly"),
            WidgetKind::ControlFlowContainer(_) => Self::ControlFlowContainer(widget.children),
            WidgetKind::Component(comp) => Self::Single {
                ident: comp.name,
                body: widget.children,
            },
            WidgetKind::Iteration(iter) => Self::Iteration {
                binding: iter.binding,
                body: widget.children,
            },
            WidgetKind::ControlFlow(controlflow) => Self::ControlFlow(controlflow),
            WidgetKind::Slot => Self::Slot(widget.children),
        }
    }
}

// -----------------------------------------------------------------------------
//   - Layout -
// -----------------------------------------------------------------------------
#[derive(Debug)]
pub struct LayoutForEach<'a, 'bp> {
    tree: WidgetTreeView<'a, 'bp>,
    scope: &'a Scope<'a, 'bp>,
    generator: Option<Generator<'a, 'bp>>,
    parent_component: Option<WidgetId>,
    filter: LayoutFilter,
}

impl<'a, 'bp> LayoutForEach<'a, 'bp> {
    pub fn new(
        tree: WidgetTreeView<'a, 'bp>,
        scope: &'a Scope<'a, 'bp>,
        filter: LayoutFilter,
        parent_component: Option<WidgetId>,
    ) -> Self {
        Self {
            tree,
            scope,
            generator: None,
            parent_component,
            filter,
        }
    }

    fn with_generator(
        tree: WidgetTreeView<'a, 'bp>,
        scope: &'a Scope<'a, 'bp>,
        generator: Generator<'a, 'bp>,
        filter: LayoutFilter,
        parent_component: Option<WidgetId>,
    ) -> Self {
        Self {
            tree,
            scope,
            generator: Some(generator),
            filter,
            parent_component,
        }
    }

    // pub fn first<F>(&mut self, ctx: &mut LayoutCtx<'_, 'bp>, mut f: F) -> Result<ControlFlow<()>>
    // where
    //     F: FnMut(&mut LayoutCtx<'_, 'bp>, &mut Element<'bp>, LayoutForEach<'_, 'bp>) -> Result<ControlFlow<()>>,
    // {
    //     self.inner_each(ctx, &mut f)
    // }

    pub fn each<F>(&mut self, ctx: &mut LayoutCtx<'_, 'bp>, mut f: F) -> Result<ControlFlow<()>>
    where
        F: FnMut(&mut LayoutCtx<'_, 'bp>, &mut Element<'bp>, LayoutForEach<'_, 'bp>) -> Result<ControlFlow<()>>,
    {
        self.inner_each(ctx, &mut f)
    }

    fn inner_each<F>(&mut self, ctx: &mut LayoutCtx<'_, 'bp>, f: &mut F) -> Result<ControlFlow<()>>
    where
        F: FnMut(&mut LayoutCtx<'_, 'bp>, &mut Element<'bp>, LayoutForEach<'_, 'bp>) -> Result<ControlFlow<()>>,
    {
        for index in 0..self.tree.layout_len() {
            match self.process(index, ctx, f)? {
                ControlFlow::Continue(_) => continue,
                ControlFlow::Break(_) => return Ok(ControlFlow::Break(())),
            }
        }

        // If there is no parent then there can be no children generated
        let Some(parent) = self.generator else { return Ok(ControlFlow::Continue(())) };

        // NOTE: Generate will never happen unless the preceding iteration returns `Continue(())`.
        //       Therefore there is no need to worry about excessive creation of `Iter`s for loops.
        loop {
            let index = self.tree.layout_len();
            if !generate(parent, &mut self.tree, ctx, self.scope, self.parent_component)? {
                break;
            }
            match self.process(index, ctx, f)? {
                ControlFlow::Continue(_) => continue,
                ControlFlow::Break(_) => return Ok(ControlFlow::Break(())),
            }
        }

        Ok(ControlFlow::Continue(()))
    }

    // TODO: this function is gross and large
    fn process<F>(&mut self, index: usize, ctx: &mut LayoutCtx<'_, 'bp>, f: &mut F) -> Result<ControlFlow<()>>
    where
        F: FnMut(&mut LayoutCtx<'_, 'bp>, &mut Element<'bp>, LayoutForEach<'_, 'bp>) -> Result<ControlFlow<()>>,
    {
        let node = self
            .tree
            .layout
            .get(index)
            .expect("widgets are always generated before processed");

        let widget_id = node.value();

        self.tree
            .with_value_mut(widget_id, |_, widget, children| {
                let output = self.filter.filter(widget, ctx.attribute_storage);
                if let FilterOutput::Exclude = output {
                    return Ok(ControlFlow::Continue(()));
                }

                match &mut widget.kind {
                    WidgetKind::Element(el) => {
                        let children = LayoutForEach::with_generator(
                            children,
                            self.scope,
                            Generator::Single {
                                ident: el.ident,
                                body: widget.children,
                            },
                            self.filter,
                            self.parent_component,
                        );
                        f(ctx, el, children)
                    }
                    WidgetKind::ControlFlow(_) => {
                        let generator = Generator::from(&*widget);
                        let mut children = LayoutForEach::with_generator(
                            children,
                            self.scope,
                            generator,
                            self.filter,
                            self.parent_component,
                        );
                        children.inner_each(ctx, f)
                    }
                    WidgetKind::For(for_loop) => {
                        let len = for_loop.collection.len();
                        if len == 0 {
                            return Ok(ControlFlow::Break(()));
                        }

                        let scope = Scope::with_collection(&for_loop.collection, self.scope);
                        let mut children = LayoutForEach::with_generator(
                            children,
                            &scope,
                            Generator::from_loop(widget.children, for_loop.binding, len),
                            self.filter,
                            self.parent_component,
                        );

                        children.inner_each(ctx, f)
                    }
                    WidgetKind::Iteration(iteration) => {
                        let loop_index = *iteration.loop_index.to_ref() as usize;
                        let scope = Scope::with_index(
                            iteration.binding,
                            loop_index,
                            self.scope,
                            iteration.loop_index.reference(),
                        );
                        let mut children = LayoutForEach::with_generator(
                            children,
                            &scope,
                            Generator::from(&*widget),
                            self.filter,
                            self.parent_component,
                        );
                        children.inner_each(ctx, f)
                    }
                    WidgetKind::With(with) => {
                        let scope = Scope::with_value(with.binding, &with.data, self.scope);
                        let mut children = LayoutForEach::with_generator(
                            children,
                            &scope,
                            Generator::from_with(widget.children, with.binding),
                            self.filter,
                            self.parent_component,
                        );

                        children.inner_each(ctx, f)
                    }
                    WidgetKind::Component(component) => {
                        let parent_component = component.widget_id;
                        let state_id = component.state_id();
                        let scope = Scope::with_component(state_id, component.widget_id, Some(self.scope));
                        let mut children = LayoutForEach::with_generator(
                            children,
                            &scope,
                            Generator::from(&*widget),
                            self.filter,
                            Some(parent_component),
                        );
                        children.inner_each(ctx, f)
                    }
                    WidgetKind::ControlFlowContainer(_) => {
                        let mut children = LayoutForEach::with_generator(
                            children,
                            self.scope,
                            Generator::from(&*widget),
                            self.filter,
                            self.parent_component,
                        );
                        children.inner_each(ctx, f)
                    }
                    WidgetKind::Slot => {
                        let mut children = LayoutForEach::with_generator(
                            children,
                            self.scope.outer(),
                            Generator::from(&*widget),
                            self.filter,
                            self.parent_component,
                        );
                        children.inner_each(ctx, f)
                    }
                }
            })
            .unwrap_or(Ok(ControlFlow::Continue(())))
    }

    pub(crate) fn len(&self) -> usize {
        self.tree.layout_len()
    }
}

// Generate the next available widget into the tree
// TODO: break this down into more manageable code.
//       this is a hot mess
fn generate<'bp>(
    parent: Generator<'_, 'bp>,
    tree: &mut WidgetTreeView<'_, 'bp>,
    ctx: &mut LayoutCtx<'_, 'bp>,
    scope: &Scope<'_, 'bp>,
    parent_component: Option<WidgetId>,
) -> Result<bool> {
    match parent {
        Generator::Single { body: blueprints, .. }
        | Generator::Iteration { body: blueprints, .. }
        | Generator::With { body: blueprints, .. }
        | Generator::ControlFlowContainer(blueprints) => {
            if blueprints.is_empty() {
                return Ok(false);
            }

            let index = tree.layout_len();
            if index >= blueprints.len() {
                return Ok(false);
            }

            let mut ctx = ctx.eval_ctx(parent_component);
            // TODO: unwrap.
            // this should propagate somewhere useful
            eval_blueprint(&blueprints[index], &mut ctx, scope, tree.offset, tree)?;
            Ok(true)
        }

        Generator::Slot(blueprints) => {
            if blueprints.is_empty() {
                return Ok(false);
            }

            let index = tree.layout_len();
            if index >= blueprints.len() {
                return Ok(false);
            }

            let mut ctx = ctx.eval_ctx(parent_component);
            eval_blueprint(&blueprints[index], &mut ctx, scope, tree.offset, tree).unwrap();
            Ok(true)
        }
        Generator::Loop { len, .. } if len == tree.layout_len() => Ok(false),
        Generator::Loop { binding, body, .. } => {
            let loop_index = tree.layout_len();

            let transaction = tree.insert(tree.offset);
            let widget = WidgetKind::Iteration(Iteration {
                loop_index: StateValue::new(loop_index as i64),
                binding,
            });
            let widget = WidgetContainer::new(widget, body);
            // NOTE: for this to fail one of the values along the path would have to
            // have been removed
            transaction.commit_child(widget).unwrap();
            Ok(true)
        }
        Generator::ControlFlow(controlflow) => {
            let child_count = tree.layout_len();
            assert_eq!(child_count.saturating_sub(1), 0, "too many branches have been created");

            // TODO: this could probably be replaced with the functionality in
            // ControlFlow::has_changed

            let should_create = {
                if child_count == 0 {
                    true
                } else {
                    let node_id = tree.layout[0].value();
                    let (_, widget) = tree
                        .values
                        .get(node_id)
                        .expect("because the node exists, the value exist");

                    let is_true = match &widget.kind {
                        WidgetKind::ControlFlowContainer(id) => controlflow.elses[*id as usize].is_true(),
                        _ => unreachable!("the child of `ControlFlow` can only be `Else`"),
                    };

                    // The condition no longer holds so the branch has to be trimmed
                    if is_true {
                        return Ok(false);
                    }

                    is_true
                }
            };

            if !should_create {
                return Ok(false);
            }

            let thing = controlflow
                .elses
                .iter()
                .enumerate()
                .filter_map(|(id, node)| {
                    // If there is a condition but it's not a bool, then it's false
                    // If there is no condition then it's true (a conditionless else)
                    // Everything else is down to the value
                    let cond = match node.cond.as_ref() {
                        Some(val) => val.truthiness(),
                        None => true,
                    };
                    match cond {
                        true => Some((id, node.body)),
                        false => None,
                    }
                })
                .next();

            match thing {
                Some((id, body)) => {
                    let kind = WidgetKind::ControlFlowContainer(id as u16);
                    let widget = WidgetContainer::new(kind, body);
                    let transaction = tree.insert(tree.offset);
                    transaction.commit_child(widget);
                }
                None => return Ok(false),
            }

            Ok(true)
        }
    }
}

#[derive(Debug)]
pub enum FilterOutput<T, F> {
    Include(T, F),
    Exclude,
    Continue,
}

pub trait Filter<'bp>: std::fmt::Debug + Copy {
    type Output: std::fmt::Debug;

    fn filter<'a>(
        &mut self,
        widget: &'a mut WidgetContainer<'bp>,
        attribute_storage: &AttributeStorage<'_>,
    ) -> FilterOutput<&'a mut Self::Output, Self>;
}

// -----------------------------------------------------------------------------
//   - Position / Paint -
// -----------------------------------------------------------------------------
#[derive(Debug)]
pub struct ForEach<'a, 'bp, Fltr> {
    tree: WidgetTreeView<'a, 'bp>,
    attribute_storage: &'a AttributeStorage<'bp>,
    pub filter: Fltr,
}

impl<'a, 'bp, Fltr: Filter<'bp>> ForEach<'a, 'bp, Fltr> {
    pub fn new(tree: WidgetTreeView<'a, 'bp>, attribute_storage: &'a AttributeStorage<'bp>, filter: Fltr) -> Self {
        Self {
            tree,
            attribute_storage,
            filter,
        }
    }

    pub fn each<F>(&mut self, mut f: F) -> ControlFlow<()>
    where
        F: FnMut(&mut Fltr::Output, ForEach<'_, 'bp, Fltr>) -> ControlFlow<()>,
    {
        self.inner_each(&mut f)
    }

    fn inner_each<F>(&mut self, f: &mut F) -> ControlFlow<()>
    where
        F: FnMut(&mut Fltr::Output, ForEach<'_, 'bp, Fltr>) -> ControlFlow<()>,
    {
        for index in 0..self.tree.layout_len() {
            _ = self.process(index, f);
        }

        ControlFlow::Continue(())
    }

    fn process<F>(&mut self, index: usize, f: &mut F) -> ControlFlow<()>
    where
        F: FnMut(&mut Fltr::Output, ForEach<'_, 'bp, Fltr>) -> ControlFlow<()>,
    {
        let Some(node) = self.tree.layout.get(index) else { panic!() };
        self.tree
            .with_value_mut(node.value(), |_, widget, children| {
                match self.filter.filter(widget, self.attribute_storage) {
                    FilterOutput::Include(el, filter) => f(el, ForEach::new(children, self.attribute_storage, filter)),
                    FilterOutput::Exclude => ControlFlow::Break(()),
                    FilterOutput::Continue => ForEach::new(children, self.attribute_storage, self.filter).inner_each(f),
                }
            })
            .unwrap() // TODO: unwrap...
    }
}