cranpose-foundation 0.29.0

Modifier-node, input, focus, text and semantics contracts for Cranpose UI
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
515
516
517
518
// A modifier element that is a value alone: a chain keeps it as words in
// the element's entry, with no node.

use std::{
    any::{Any, TypeId, type_name},
    fmt,
    hash::Hasher,
    marker::PhantomData,
};

use cranpose_core::{ProvidedValue, hash::default};
use cranpose_ui_layout::{
    ConstraintsHold, LayoutDirection, LayoutModifierMeasureResult, WrappedHold,
};

use super::super::{
    AnyModifierElement, Constraints, DynModifierElement, ElementMaker, InvalidationKind,
    Measurable, ModifierNodeContext, NodeCapabilities, Size,
};

/// The most words a plain element's value takes: with its type's table
/// they fit in the room of a chain entry, and a coordinator keeps a copy
/// of them for every layout modifier of a node.
pub const PLAIN_WORDS_MAX: usize = 5;

/// A modifier element that is a value and nothing else: it keeps no state
/// between frames, hears of no attach, detach or reset and delegates to no
/// node. A chain keeps its value as [`Self::WORDS`] words and makes no node
/// for it; a reader takes the value back with [`Self::from_words`].
pub trait PlainElement: fmt::Debug + PartialEq + Sized + 'static {
    /// How many words the value takes: at most [`PLAIN_WORDS_MAX`].
    const WORDS: usize;

    /// What the element takes part in: layout, draw or both.
    const CAPABILITIES: NodeCapabilities;

    /// The one pipeline stage a changed value invalidates, or `None` to
    /// invalidate every stage of [`Self::CAPABILITIES`].
    const UPDATE_INVALIDATION: Option<InvalidationKind> = None;

    /// Writes the value into `words`, which holds [`Self::WORDS`] words.
    fn to_words(&self, words: &mut [u32]);

    /// The value that [`Self::to_words`] wrote into `words`.
    fn from_words(words: &[u32]) -> Self;

    /// How the element measures the content it wraps, for an element with
    /// [`NodeCapabilities::LAYOUT`]: `Some(&PlainLayoutFns::of::<Self>())`
    /// for a [`PlainLayout`]. `None`, the default, passes the content's
    /// measure through.
    const LAYOUT: Option<&'static PlainLayoutFns> = None;

    /// Human readable name surfaced to inspector tooling.
    fn inspector_name(&self) -> &'static str {
        type_name::<Self>()
    }

    /// Records inspector properties for tooling.
    fn inspector_properties(&self, _inspector: &mut dyn FnMut(&'static str, String)) {}
}

/// A plain element that measures the content it wraps, as a
/// [`super::super::LayoutModifierNode`] does, from its value alone.
pub trait PlainLayout: PlainElement {
    /// Measures the wrapped content under `constraints` and returns the size
    /// the element takes and where it places the content.
    fn measure(
        &self,
        context: &mut dyn ModifierNodeContext,
        measurable: &dyn Measurable,
        constraints: Constraints,
    ) -> LayoutModifierMeasureResult;

    /// The element as a coordinator keeps it for the measures `at` tells:
    /// an element that rounds its values to device pixels, or mirrors them
    /// for a layout direction, may do so here once, and measure from those
    /// values. The default is the element itself.
    fn prepared(self, _at: PrepareAt) -> Self {
        self
    }

    /// Whether [`Self::prepared`] changes the element: `false`, the
    /// default, lets a coordinator copy the words as they are.
    const PREPARES: bool = false;

    /// The incoming constraints the last measure, which gave `size` under
    /// `constraints`, holds for; see
    /// [`super::super::LayoutModifierNode::measure_hold`].
    fn measure_hold(
        &self,
        _density: f32,
        _constraints: Constraints,
        _size: Size,
        _wrapped: WrappedHold,
    ) -> Option<ConstraintsHold> {
        None
    }

    /// The intrinsic size `kind` names: the wrapped content's by default,
    /// for an element that keeps the content's size.
    fn intrinsic(&self, measurable: &dyn Measurable, kind: PlainIntrinsic, _density: f32) -> f32 {
        kind.of(measurable)
    }
}

/// What a coordinator prepares a plain layout element for.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PrepareAt {
    /// The density of the node's measures.
    pub density: f32,
    /// The direction the node's layout reads.
    pub direction: LayoutDirection,
}

/// Which intrinsic size a measure asks for.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PlainIntrinsic {
    /// The minimum width at a height.
    MinWidth(f32),
    /// The maximum width at a height.
    MaxWidth(f32),
    /// The minimum height at a width.
    MinHeight(f32),
    /// The maximum height at a width.
    MaxHeight(f32),
}

impl PlainIntrinsic {
    /// This intrinsic size of `measurable`.
    pub fn of(self, measurable: &dyn Measurable) -> f32 {
        match self {
            Self::MinWidth(height) => measurable.min_intrinsic_width(height),
            Self::MaxWidth(height) => measurable.max_intrinsic_width(height),
            Self::MinHeight(width) => measurable.min_intrinsic_height(width),
            Self::MaxHeight(width) => measurable.max_intrinsic_height(width),
        }
    }

    /// The extent across the axis asked for: the height of a width, the
    /// width of a height.
    pub fn cross(self) -> f32 {
        match self {
            Self::MinWidth(cross)
            | Self::MaxWidth(cross)
            | Self::MinHeight(cross)
            | Self::MaxHeight(cross) => cross,
        }
    }

    /// The same size asked for at the extent `cross` across its axis.
    pub fn at(self, cross: f32) -> Self {
        match self {
            Self::MinWidth(_) => Self::MinWidth(cross),
            Self::MaxWidth(_) => Self::MaxWidth(cross),
            Self::MinHeight(_) => Self::MinHeight(cross),
            Self::MaxHeight(_) => Self::MaxHeight(cross),
        }
    }

    /// Whether a width is asked for, not a height.
    pub fn is_width(self) -> bool {
        matches!(self, Self::MinWidth(_) | Self::MaxWidth(_))
    }
}

// Writes an element's words as a coordinator keeps them.
type PrepareFn = fn(&[u32], PrepareAt, &mut [u32]);

type MeasureFn = fn(
    &[u32],
    &mut dyn ModifierNodeContext,
    &dyn Measurable,
    Constraints,
) -> LayoutModifierMeasureResult;

/// How a plain layout element measures, read from its words: what a
/// coordinator keeps of the element's type.
pub struct PlainLayoutFns {
    // `None` for an element a coordinator keeps as it is.
    prepare: Option<PrepareFn>,
    measure: MeasureFn,
    measure_hold: fn(&[u32], f32, Constraints, Size, WrappedHold) -> Option<ConstraintsHold>,
    intrinsic: fn(&[u32], &dyn Measurable, PlainIntrinsic, f32) -> f32,
}

impl fmt::Debug for PlainLayoutFns {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PlainLayoutFns").finish_non_exhaustive()
    }
}

impl PlainLayoutFns {
    /// The table of the plain layout element `E`.
    pub const fn of<E: PlainLayout>() -> Self {
        Self {
            prepare: if E::PREPARES {
                Some(|words, at, prepared| {
                    E::from_words(words)
                        .prepared(at)
                        .to_words(&mut prepared[..E::WORDS]);
                })
            } else {
                None
            },
            measure: |words, context, measurable, constraints| {
                E::from_words(words).measure(context, measurable, constraints)
            },
            measure_hold: |words, density, constraints, size, wrapped| {
                E::from_words(words).measure_hold(density, constraints, size, wrapped)
            },
            intrinsic: |words, measurable, kind, density| {
                E::from_words(words).intrinsic(measurable, kind, density)
            },
        }
    }

    /// The words of the element `words` hold as a coordinator keeps it for
    /// the measures `at` tells; see [`PlainLayout::prepared`]. The other
    /// calls take prepared words.
    #[inline]
    pub fn prepare(&self, words: &[u32; PLAIN_WORDS_MAX], at: PrepareAt) -> [u32; PLAIN_WORDS_MAX] {
        match self.prepare {
            Some(prepare) => {
                let mut prepared = [0; PLAIN_WORDS_MAX];
                prepare(words, at, &mut prepared);
                prepared
            }
            None => *words,
        }
    }

    /// Measures as the element `words` hold does.
    #[inline]
    pub fn measure(
        &self,
        words: &[u32],
        context: &mut dyn ModifierNodeContext,
        measurable: &dyn Measurable,
        constraints: Constraints,
    ) -> LayoutModifierMeasureResult {
        (self.measure)(words, context, measurable, constraints)
    }

    /// The hold of the last measure of the element `words` hold.
    pub fn measure_hold(
        &self,
        words: &[u32],
        density: f32,
        constraints: Constraints,
        size: Size,
        wrapped: WrappedHold,
    ) -> Option<ConstraintsHold> {
        (self.measure_hold)(words, density, constraints, size, wrapped)
    }

    /// The intrinsic size `kind` names of the element `words` hold.
    pub fn intrinsic(
        &self,
        words: &[u32],
        measurable: &dyn Measurable,
        kind: PlainIntrinsic,
        density: f32,
    ) -> f32 {
        (self.intrinsic)(words, measurable, kind, density)
    }
}

/// What a chain keeps of a plain element's type beside its words: how many
/// they are, what the element takes part in, and how to read them.
pub struct PlainFns {
    element_type: TypeId,
    words: u8,
    capabilities: NodeCapabilities,
    update_invalidation: Option<InvalidationKind>,
    layout: Option<&'static PlainLayoutFns>,
    type_name: fn() -> &'static str,
    inspector_name: fn(&[u32]) -> &'static str,
    inspector_properties: fn(&[u32], &mut dyn FnMut(&'static str, String)),
}

impl fmt::Debug for PlainFns {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PlainFns").finish_non_exhaustive()
    }
}

impl PlainFns {
    /// The type of the element the words hold.
    pub fn element_type(&self) -> TypeId {
        self.element_type
    }

    /// How many words the element's value takes.
    pub fn words(&self) -> usize {
        usize::from(self.words)
    }

    /// What the element takes part in.
    pub fn capabilities(&self) -> NodeCapabilities {
        self.capabilities
    }

    /// How the element measures, when it does.
    pub fn layout(&self) -> Option<&'static PlainLayoutFns> {
        self.layout
    }

    /// The name of the element's type.
    pub fn type_name(&self) -> &'static str {
        (self.type_name)()
    }

    pub(in super::super) fn hash_code(&self, words: &[u32]) -> u64 {
        hash_words(words)
    }

    pub(in super::super) fn element(&'static self, words: &[u32]) -> DynModifierElement {
        DynModifierElement::plain(PlainWords::new(self, words))
    }

    /// The element `words` hold, when it is an `E`.
    #[inline]
    pub fn read<E: PlainElement>(&self, words: &[u32]) -> Option<E> {
        (self.element_type() == TypeId::of::<E>()).then(|| E::from_words(words))
    }
}

struct FnsOf<E>(PhantomData<fn() -> E>);

impl<E: PlainElement> FnsOf<E> {
    const WORDS: u8 = {
        assert!(E::WORDS <= PLAIN_WORDS_MAX, "a plain element's words fit");
        E::WORDS as u8
    };

    const FNS: PlainFns = PlainFns {
        element_type: TypeId::of::<E>(),
        words: Self::WORDS,
        capabilities: E::CAPABILITIES,
        update_invalidation: E::UPDATE_INVALIDATION,
        layout: E::LAYOUT,
        type_name: type_name::<E>,
        inspector_name: |words| E::from_words(words).inspector_name(),
        inspector_properties: |words, inspector| {
            E::from_words(words).inspector_properties(inspector);
        },
    };
}

// The hash of a plain element: of its words, in one function for every
// type, as two elements compare.
fn hash_words(words: &[u32]) -> u64 {
    let mut hasher = default::new();
    for &word in words {
        hasher.write_u32(word);
    }
    hasher.finish()
}

// Whether two plain elements of one type hold an equal value: equal words,
// as Compose's data classes compare a float by its bits (the two zeros
// differ, a NaN equals itself). The words of a value number five at most,
// so the comparison folds them inline rather than calling `memcmp`.
fn same_words(a: &[u32], b: &[u32]) -> bool {
    a.len() == b.len() && a.iter().zip(b).fold(0, |differ, (&x, &y)| differ | (x ^ y)) == 0
}

/// A plain element as a chain reads it: its type's table, and its value as
/// words.
pub trait PlainValue {
    /// The table of the element's type.
    fn fns(&self) -> &'static PlainFns;

    /// Writes the value into `words`, as many as the table tells.
    fn write_words(&self, words: &mut [u32]);

    /// Whether `words`, written by an element of this type, hold a value
    /// equal to this one, as the element type compares.
    fn equals_words(&self, words: &[u32]) -> bool;
}

// A plain element's value as a modifier holds it in place of an
// allocation: its type's table and its words, those past the value's own
// zero.
#[derive(Clone, Copy)]
pub(crate) struct PlainWords {
    fns: &'static PlainFns,
    words: [u32; PLAIN_WORDS_MAX],
    // A byte that holds one value, in the room after the words: the enums
    // around the value, a modifier's element and a modifier of one element
    // or of several, keep their tags in the values it never holds and stay
    // as large as the value.
    #[expect(dead_code, reason = "its use is the values it never holds")]
    room: Room,
}

#[derive(Clone, Copy)]
#[repr(u8)]
enum Room {
    Zero = 0,
}

impl PlainWords {
    pub(crate) fn new(fns: &'static PlainFns, words: &[u32]) -> Self {
        let mut held = [0; PLAIN_WORDS_MAX];
        held[..words.len()].copy_from_slice(words);
        Self {
            fns,
            words: held,
            room: Room::Zero,
        }
    }

    fn of<E: PlainElement>(element: &E) -> Self {
        let mut words = [0; PLAIN_WORDS_MAX];
        element.to_words(&mut words[..E::WORDS]);
        Self {
            fns: &FnsOf::<E>::FNS,
            words,
            room: Room::Zero,
        }
    }

    pub(crate) fn words(&self) -> &[u32] {
        &self.words[..self.fns.words()]
    }
}

// The type alone, as the wrapper of a node's element prints: the values
// would bring each element's formatting into every image.
impl fmt::Debug for PlainWords {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.fns.type_name())
    }
}

impl PlainValue for PlainWords {
    fn fns(&self) -> &'static PlainFns {
        self.fns
    }

    fn write_words(&self, words: &mut [u32]) {
        words.copy_from_slice(self.words());
    }

    fn equals_words(&self, words: &[u32]) -> bool {
        same_words(self.words(), words)
    }
}

impl AnyModifierElement for PlainWords {
    fn element_type(&self) -> TypeId {
        self.fns.element_type()
    }

    fn maker(&self) -> ElementMaker<'_> {
        ElementMaker::Plain(self)
    }

    fn key(&self) -> Option<u64> {
        None
    }

    fn capabilities(&self) -> NodeCapabilities {
        self.fns.capabilities
    }

    fn hash_code(&self) -> u64 {
        hash_words(self.words())
    }

    fn equals_element(&self, other: &dyn AnyModifierElement) -> bool {
        other.equals_plain(self.fns, self.words())
    }

    fn inspector_name(&self) -> &'static str {
        (self.fns.inspector_name)(self.words())
    }

    fn record_inspector_properties(&self, visitor: &mut dyn FnMut(&'static str, String)) {
        (self.fns.inspector_properties)(self.words(), visitor);
    }

    fn requires_update(&self) -> bool {
        false
    }

    fn auto_invalidates_on_update(&self) -> bool {
        true
    }

    fn update_invalidation_kind(&self) -> Option<InvalidationKind> {
        self.fns.update_invalidation
    }

    fn provided_composition_locals(&self) -> Vec<ProvidedValue> {
        Vec::new()
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn equals_plain(&self, fns: &PlainFns, words: &[u32]) -> bool {
        // The same table tells the same type without a call; two tables of
        // one type may still differ in address.
        (std::ptr::eq(fns, self.fns) || fns.element_type() == self.fns.element_type())
            && same_words(self.words(), words)
    }
}

/// The type-erased element of a plain `element`, a copy of its value.
// One copy for each element type: a modifier builder inlined into an app's
// body then holds a call, not the writing of the element's words.
#[inline(never)]
pub fn plain_element<E: PlainElement>(element: &E) -> DynModifierElement {
    DynModifierElement::plain(PlainWords::of(element))
}