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
// The type-erased modifier element a chain reconciles with: what it tells of
// the node it makes, and how two compare.

use std::{
    any::{Any, TypeId, type_name},
    cell::{Cell, RefCell},
    fmt,
    hash::Hasher,
    marker::PhantomData,
    rc::Rc,
};

use cranpose_core::{PackedU64, ProvidedValue, hash::default};

use super::{
    InvalidationKind, ModifierNode, ModifierNodeElement, NodeCapabilities, PlainFns, PlainValue,
    PlainWords,
};

/// Type-erased modifier element used by the runtime to reconcile chains.
pub trait AnyModifierElement: fmt::Debug {
    /// The type of the element itself.
    fn element_type(&self) -> TypeId;

    /// How a chain keeps the element: by a node it makes, or as a value.
    fn maker(&self) -> ElementMaker<'_>;

    /// The key that tells apart several elements of one type, or `None` when the element has none.
    fn key(&self) -> Option<u64>;

    /// The capabilities of the nodes that the element creates.
    fn capabilities(&self) -> NodeCapabilities {
        NodeCapabilities::default()
    }

    /// The hash of the element, computed once when the element was wrapped.
    fn hash_code(&self) -> u64;

    /// Whether `other` is an element of the same type with equal data.
    fn equals_element(&self, other: &dyn AnyModifierElement) -> bool;

    /// The name that inspector tooling shows for the element.
    fn inspector_name(&self) -> &'static str;

    /// Reports each inspector property of the element to `visitor` as a name and a value.
    fn record_inspector_properties(&self, visitor: &mut dyn FnMut(&'static str, String));

    /// Whether the node must be updated even when the new element equals the old one.
    fn requires_update(&self) -> bool;

    /// Whether updating an existing node invalidates all pipeline stages that its capabilities
    /// cover.
    fn auto_invalidates_on_update(&self) -> bool;

    /// The one pipeline stage that an update invalidates, or `None` to invalidate by capabilities.
    fn update_invalidation_kind(&self) -> Option<InvalidationKind>;

    /// Whether this element has composition locals for its content.
    fn provides_composition_locals(&self) -> bool {
        false
    }

    /// The composition locals this element hands to its content.
    fn provided_composition_locals(&self) -> Vec<ProvidedValue> {
        Vec::new()
    }

    /// Returns the element as `Any`, for downcasting to its concrete type.
    fn as_any(&self) -> &dyn Any;

    /// Whether `node` is of this element's node type and keeps an element
    /// equal to this one: always `false` for an element whose node keeps
    /// none.
    fn equals_node(&self, _node: &dyn ModifierNode) -> bool {
        false
    }

    /// Whether `words`, the value of a plain element of the type `fns`
    /// tells, hold a value equal to this element: always `false` for an
    /// element that is not plain.
    fn equals_plain(&self, _fns: &PlainFns, _words: &[u32]) -> bool {
        false
    }
}

/// How a chain keeps an element.
pub enum ElementMaker<'a> {
    /// By a node the element makes and updates.
    Node(&'a dyn NodeMaker),
    /// As words in the element's chain entry: see [`super::PlainElement`].
    Plain(&'a dyn PlainValue),
}

/// An element that makes a node and updates it.
pub trait NodeMaker {
    /// The type of node that the element creates.
    fn node_type(&self) -> TypeId;

    /// A new node for this element, in the shared cell its chain entry keeps.
    fn create_node(&self) -> Rc<RefCell<dyn ModifierNode>>;

    /// Whether `node` is of the type that this element updates.
    fn can_update_node(&self, node: &dyn ModifierNode) -> bool;

    /// Brings `node` up to date with the data of this element.
    fn update_node(&self, node: &mut dyn ModifierNode);

    /// What stands for the element beside its node when the node keeps
    /// every value of it: see [`ModifierNodeElement::FROM_NODE`].
    fn held_by_node(&self) -> Option<NodeHeld> {
        None
    }
}

/// What a chain keeps of an element whose node keeps every value of it, in
/// place of the element: its type, and how to read it from the node. One
/// word, so an entry keeps it where it keeps an element.
#[derive(Clone, Copy)]
pub struct NodeHeld(&'static HeldFns);

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

impl NodeHeld {
    pub(crate) fn element_type(self) -> TypeId {
        (self.0.element_type)()
    }

    pub(crate) fn node_type(self) -> TypeId {
        (self.0.node_type)()
    }

    // The hash of the element `node` holds, as the element itself hashes.
    pub(crate) fn hash_code(self, node: &dyn ModifierNode) -> u64 {
        (self.0.hash_code)(node)
    }

    // The element `node` holds, made again.
    pub(crate) fn element(self, node: &dyn ModifierNode) -> DynModifierElement {
        (self.0.element)(node)
    }
}

struct HeldFns {
    element_type: fn() -> TypeId,
    node_type: fn() -> TypeId,
    hash_code: fn(&dyn ModifierNode) -> u64,
    element: fn(&dyn ModifierNode) -> DynModifierElement,
}

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

impl<E: ModifierNodeElement> HeldBy<E> {
    const FNS: HeldFns = HeldFns {
        element_type: TypeId::of::<E>,
        node_type: TypeId::of::<E::Node>,
        hash_code: Self::hash_code,
        element: Self::element,
    };

    // The element `node` holds. A chain keeps a `NodeHeld` only beside a
    // node of the element's node type.
    fn of(node: &dyn ModifierNode) -> E {
        let from_node = E::FROM_NODE.expect("a node-held element makes itself from its node");
        from_node(
            node.as_any()
                .downcast_ref::<E::Node>()
                .expect("a node-held element's node is of its node type"),
        )
    }

    fn hash_code(node: &dyn ModifierNode) -> u64 {
        let mut hasher = default::new();
        Self::of(node).hash(&mut hasher);
        hasher.finish()
    }

    fn element(node: &dyn ModifierNode) -> DynModifierElement {
        modifier_element(Self::of(node))
    }
}

struct TypedModifierElement<E: ModifierNodeElement> {
    element: E,
    // The element's hash, worked out the first time a chain rebuilding
    // asks for it: most elements are built for a recomposition and only
    // compared with the last ones.
    hash: Cell<Option<PackedU64>>,
    provides_locals: bool,
}

impl<E: ModifierNodeElement> TypedModifierElement<E> {
    fn new(element: E) -> Self {
        let provides_locals = !element.provided_composition_locals().is_empty();
        Self {
            element,
            hash: Cell::new(None),
            provides_locals,
        }
    }
}

impl<E> fmt::Debug for TypedModifierElement<E>
where
    E: ModifierNodeElement,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TypedModifierElement")
            .field("type", &type_name::<E>())
            .finish()
    }
}

impl<E> NodeMaker for TypedModifierElement<E>
where
    E: ModifierNodeElement,
{
    fn node_type(&self) -> TypeId {
        TypeId::of::<E::Node>()
    }

    fn create_node(&self) -> Rc<RefCell<dyn ModifierNode>> {
        Rc::new(RefCell::new(self.element.create()))
    }

    fn can_update_node(&self, node: &dyn ModifierNode) -> bool {
        node.as_any().is::<E::Node>()
    }

    fn update_node(&self, node: &mut dyn ModifierNode) {
        if let Some(typed) = node.as_any_mut().downcast_mut::<E::Node>() {
            self.element.update(typed);
        }
    }

    fn held_by_node(&self) -> Option<NodeHeld> {
        E::FROM_NODE.map(|_| NodeHeld(&HeldBy::<E>::FNS))
    }
}

impl<E> AnyModifierElement for TypedModifierElement<E>
where
    E: ModifierNodeElement,
{
    fn element_type(&self) -> TypeId {
        TypeId::of::<E>()
    }

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

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

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

    fn provides_composition_locals(&self) -> bool {
        self.provides_locals
    }

    fn provided_composition_locals(&self) -> Vec<ProvidedValue> {
        self.element.provided_composition_locals()
    }

    fn hash_code(&self) -> u64 {
        if let Some(hash) = self.hash.get() {
            return hash.get();
        }
        let mut hasher = default::new();
        self.element.hash(&mut hasher);
        let hash = hasher.finish();
        self.hash.set(Some(PackedU64::new(hash)));
        hash
    }

    fn equals_element(&self, other: &dyn AnyModifierElement) -> bool {
        other
            .as_any()
            .downcast_ref::<Self>()
            .is_some_and(|typed| typed.element == self.element)
    }

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

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

    fn requires_update(&self) -> bool {
        self.element.always_update()
    }

    fn auto_invalidates_on_update(&self) -> bool {
        self.element.auto_invalidate_on_update()
    }

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

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

    fn equals_node(&self, node: &dyn ModifierNode) -> bool {
        node.as_any()
            .downcast_ref::<E::Node>()
            .is_some_and(|node| self.element.equals_node(node))
    }
}

/// Convenience helper for callers to construct a type-erased modifier
/// element without having to mention the internal wrapper type.
pub fn modifier_element<E: ModifierNodeElement>(element: E) -> DynModifierElement {
    let element = TypedModifierElement::new(element);
    let provides_locals = element.provides_locals;
    DynModifierElement(Repr::Shared {
        element: Rc::new(element),
        provides_locals,
    })
}

/// A type-erased modifier element, as a modifier holds it: a plain
/// element's value in place, or a shared element that makes a node. A plain
/// element takes no allocation of its own.
#[derive(Clone)]
pub struct DynModifierElement(Repr);

// What a `DynModifierElement` holds. A shared element keeps beside it
// whether it has composition locals, in bytes the plain value's room leaves,
// so a modifier of one element tells without a call.
#[derive(Clone)]
pub(crate) enum Repr {
    Plain(PlainWords),
    Shared {
        element: Rc<dyn AnyModifierElement>,
        provides_locals: bool,
    },
}

impl DynModifierElement {
    pub(crate) fn plain(words: PlainWords) -> Self {
        Self(Repr::Plain(words))
    }

    pub(crate) fn of_shared(element: Rc<dyn AnyModifierElement>) -> Self {
        let provides_locals = element.provides_composition_locals();
        Self(Repr::Shared {
            element,
            provides_locals,
        })
    }

    pub(crate) fn repr(&self) -> &Repr {
        &self.0
    }

    // The shared element, or `None` for a plain one, which is a value.
    pub(crate) fn shared(&self) -> Option<&Rc<dyn AnyModifierElement>> {
        match &self.0 {
            Repr::Plain(_) => None,
            Repr::Shared { element, .. } => Some(element),
        }
    }

    // The element as a shared one, which a plain value becomes by a copy in
    // an allocation of its own.
    pub(crate) fn to_shared(&self) -> Rc<dyn AnyModifierElement> {
        match &self.0 {
            Repr::Plain(words) => Rc::new(*words),
            Repr::Shared { element, .. } => Rc::clone(element),
        }
    }

    /// Whether this element has composition locals for its content. A plain
    /// element has none, which this tells without a call.
    #[inline]
    pub fn provides_composition_locals(&self) -> bool {
        match &self.0 {
            Repr::Plain(_) => false,
            Repr::Shared {
                provides_locals, ..
            } => *provides_locals,
        }
    }

    /// Whether `other` is this element itself, not only an equal one: two
    /// plain elements are values, which are never one element.
    pub fn is(&self, other: &Self) -> bool {
        match (&self.0, &other.0) {
            (Repr::Shared { element: a, .. }, Repr::Shared { element: b, .. }) => Rc::ptr_eq(a, b),
            _ => false,
        }
    }
}

impl std::ops::Deref for DynModifierElement {
    type Target = dyn AnyModifierElement;

    #[inline]
    fn deref(&self) -> &Self::Target {
        match &self.0 {
            Repr::Plain(words) => words,
            Repr::Shared { element, .. } => &**element,
        }
    }
}

impl fmt::Debug for DynModifierElement {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&**self, f)
    }
}