nami-core 0.5.0

A powerful, lightweight reactive framework.
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
//! Core components for the Nami framework.

#![no_std]
#![forbid(unsafe_code)]
extern crate alloc;
// Observability scopes its observer to one reactive graph with a thread-local,
// which needs `std`. The crate stays `no_std` in every other configuration.
#[cfg(feature = "observability")]
extern crate std;

use alloc::rc::Rc;
use core::{
    any::TypeId,
    cell::RefCell,
    hash::{Hash, Hasher},
    panic::Location,
};

use crate::watcher::{Context, WatcherGuard};

/// Stable identity for reactive signal instances that own observable state.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct SignalIdentity(usize);

impl SignalIdentity {
    /// Creates an identity from a shared allocation pointer.
    ///
    /// The allocation must be tied to the semantic signal instance and be cloned
    /// together with that instance.
    #[must_use]
    pub fn from_rc<T>(value: &Rc<T>) -> Self {
        Self::from_ptr(Rc::as_ptr(value))
    }

    /// Creates an identity from a stable allocation pointer.
    ///
    /// # Panics
    ///
    /// Panics when the pointer is null.
    #[must_use]
    pub fn from_ptr<T>(value: *const T) -> Self {
        let value = value.cast::<()>() as usize;
        assert!(value != 0, "signal identity pointer must not be null");
        Self(value)
    }

    /// Raw value for renderer-local key composition.
    #[must_use]
    pub const fn raw(self) -> usize {
        self.0
    }

    /// Creates a stable derived identity for a property of this signal.
    #[must_use]
    pub const fn with_discriminator(self, discriminator: usize) -> Self {
        Self(
            self.0.wrapping_mul(0x9E37_79B9usize).rotate_left(7)
                ^ discriminator.wrapping_add(0x517C_C1B7usize),
        )
    }

    /// Combines two stable signal identities into one deterministic identity.
    #[must_use]
    pub const fn combine(self, other: Self) -> Self {
        self.with_discriminator(other.0)
    }

    /// Creates a stable discriminator from a call site and semantic wrapper type.
    #[must_use]
    pub fn call_site_discriminator<T: 'static>(caller: &'static Location<'static>) -> usize {
        let mut hasher = IdentityDiscriminatorHasher::new();
        TypeId::of::<T>().hash(&mut hasher);
        caller.file().hash(&mut hasher);
        caller.line().hash(&mut hasher);
        caller.column().hash(&mut hasher);
        hasher.value()
    }
}

struct IdentityDiscriminatorHasher(usize);

impl IdentityDiscriminatorHasher {
    const OFFSET: usize = 0x811C_9DC5;
    const PRIME: usize = 0x0100_0193;

    const fn new() -> Self {
        Self(Self::OFFSET)
    }

    const fn value(&self) -> usize {
        self.0
    }
}

impl Hasher for IdentityDiscriminatorHasher {
    fn finish(&self) -> u64 {
        self.0 as u64
    }

    fn write(&mut self, bytes: &[u8]) {
        for byte in bytes {
            self.0 ^= usize::from(*byte);
            self.0 = self.0.wrapping_mul(Self::PRIME);
            self.0 = self.0.rotate_left(5);
        }
    }
}

/// Collection types for Nami.
pub mod collection;
pub mod dictionary;
pub mod id;
pub mod observe;
pub mod watcher;

pub use id::{Identifiable, IdentifiableExt, SelfId, UseId};

/// The core trait for reactive system.
///
/// Types implementing `Signal` represent a computation that can produce a value
/// and notify observers when that value changes.
#[diagnostic::on_unimplemented(
    message = "`{Self}` is not a nami `Signal`",
    label = "expected a `Signal` implementation",
    note = "`Signal` is nami's reactive read trait; wrap a value in `nami::Binding` or `nami::Computed`, or create a fixed one with `nami::constant(value)`"
)]
pub trait Signal: Clone + 'static {
    /// The type of value produced by this computation.
    type Output: 'static;
    /// The guard type returned by the watch method that manages watcher lifecycle.
    type Guard: WatcherGuard;

    /// Takes a snapshot of the computation's current value.
    ///
    /// This is a one-off, untracked read: the value is detached from
    /// reactivity and no dependency is recorded. Application code rarely
    /// needs it — watchers and derived signals track changes, and
    /// read-modify-write goes through `set`, `get_mut`, `with_mut` and
    /// friends on `Binding`.
    fn snapshot(&self) -> Self::Output;

    /// Lends the current value to `f`, untracked like [`Self::snapshot`].
    ///
    /// The default takes a [`snapshot`](Self::snapshot). Signals that store
    /// their value immutably (constants), share it copy-on-write (`Binding`),
    /// or forward to one of those (`Computed`) lend it without copying, and a
    /// mutation made inside `f` still never panics: copy-on-write storage
    /// leaves `f` reading the value it was lent. Signals that recompute
    /// (maps, zips) keep the snapshot.
    ///
    /// Named `with_ref` because `SignalExt::with` already attaches metadata.
    fn with_ref<R>(&self, f: impl FnOnce(&Self::Output) -> R) -> R {
        f(&self.snapshot())
    }

    /// Returns the stable semantic identity of this signal, when one exists.
    ///
    /// Constant signals intentionally return `None` because they do not own
    /// observable state.
    fn identity(&self) -> Option<SignalIdentity> {
        None
    }

    /// Register a watcher to be notified when the computed value changes.
    ///
    /// Returns a guard that, when dropped, will unregister the watcher.
    #[must_use = "the watcher stops when its guard is dropped"]
    fn watch(&self, watcher: impl Fn(Context<Self::Output>) + 'static) -> Self::Guard;
}

/// The `CustomBinding` trait represents a computable value that can also be set.
///
/// Any type implementing this trait must also implement `Signal` to provide the
/// ability to retrieve its current value, and adds the ability to mutate the value.
pub trait CustomBinding: Signal {
    /// Sets a new value for this binding.
    ///
    /// This will typically trigger notifications to any watchers.
    fn set(&self, value: Self::Output);
}

/// Macro to implement the Signal trait for constant types.
///
/// This macro generates Signal implementations for types that don't change,
/// providing them with empty watcher functionality since they never notify changes.
#[macro_export]
macro_rules! impl_constant {
    ($($ty:ty),*) => {
         $(
            impl $crate::Signal for $ty {
                type Output = Self;
                type Guard = ();

                fn snapshot(&self) -> Self::Output {
                    self.clone()
                }

                fn with_ref<R>(&self, f: impl FnOnce(&Self::Output) -> R) -> R {
                    f(self)
                }

                fn watch(
                    &self,
                    _watcher: impl Fn($crate::watcher::Context<Self::Output>)+'static,
                )  {

                }
            }
        )*
    };

}

macro_rules! impl_generic_constant {

    ( $($ty:ident < $($param:ident),* >),* $(,)? ) => {
        $(
            impl<$($param: Clone + 'static),*> $crate::Signal for $ty<$($param),*> {
                type Output = Self;
                type Guard = ();

                fn snapshot(&self) -> Self::Output {
                    self.clone()
                }

                fn with_ref<R>(&self, f: impl FnOnce(&Self::Output) -> R) -> R {
                    f(self)
                }

                fn watch(
                    &self,
                    _watcher: impl Fn($crate::watcher::Context<Self::Output>)+'static,
                ) {

                }
            }
        )*
    };




}

mod impl_constant {
    use alloc::borrow::Cow;
    use alloc::collections::{BTreeMap, BTreeSet};
    use core::time::Duration;

    use crate::Signal;
    use alloc::string::String;
    use alloc::vec::Vec;
    impl_constant!(
        &'static str,
        u8,
        u16,
        u32,
        u64,
        usize,
        i8,
        i16,
        i32,
        i64,
        isize,
        f32,
        f64,
        bool,
        char,
        Duration,
        String,
        Cow<'static, str>
    );

    impl_generic_constant!(Vec<T>,BTreeMap<K,V>,BTreeSet<T>);

    impl<T: 'static> Signal for &'static [T] {
        type Output = &'static [T];
        type Guard = ();
        fn snapshot(&self) -> Self::Output {
            self
        }
        fn with_ref<R>(&self, f: impl FnOnce(&Self::Output) -> R) -> R {
            f(self)
        }
        fn watch(&self, _watcher: impl Fn(crate::watcher::Context<Self::Output>) + 'static) {}
    }

    // Fixed-size arrays of `Clone + 'static` elements act as constant signals.
    // This lets callers pass typed value arrays (e.g. mesh-gradient palettes)
    // directly into `IntoSignal<[T; N]>`-typed parameters without wrapping.
    impl<T: Clone + 'static, const N: usize> Signal for [T; N] {
        type Output = Self;
        type Guard = ();
        fn snapshot(&self) -> Self::Output {
            self.clone()
        }
        fn with_ref<R>(&self, f: impl FnOnce(&Self::Output) -> R) -> R {
            f(self)
        }
        fn watch(&self, _watcher: impl Fn(crate::watcher::Context<Self::Output>) + 'static) {}
    }
}

/// Constant signals for kurbo's geometry types.
///
/// A plain `Affine`, `Rect` or `BezPath` passed where an API takes
/// `impl Signal<Output = T>` is a signal that never changes.
#[cfg(feature = "kurbo")]
mod impl_kurbo_constant {
    use kurbo::{
        Affine, Arc, BezPath, Circle, CircleSegment, CubicBez, Ellipse, Insets, Line, PathEl,
        Point, QuadBez, Rect, RoundedRect, RoundedRectRadii, Size, Stroke, Vec2,
    };

    impl_constant!(
        Affine,
        Arc,
        BezPath,
        Circle,
        CircleSegment,
        CubicBez,
        Ellipse,
        Insets,
        Line,
        PathEl,
        Point,
        QuadBez,
        Rect,
        RoundedRect,
        RoundedRectRadii,
        Size,
        Stroke,
        Vec2
    );

    #[cfg(test)]
    mod tests {
        use kurbo::Affine;

        use crate::Signal;

        #[test]
        fn plain_affine_is_a_constant_signal() {
            let affine = Affine::translate((1.0, 2.0));
            assert_eq!(affine.snapshot(), affine);
            let () = affine.watch(|_| unreachable!("a constant never notifies"));
        }
    }
}

impl<T: Signal> Signal for Option<T> {
    type Output = Option<T::Output>;
    type Guard = Option<T::Guard>;
    fn snapshot(&self) -> Self::Output {
        self.as_ref().map(Signal::snapshot)
    }
    fn identity(&self) -> Option<SignalIdentity> {
        self.as_ref().and_then(Signal::identity)
    }
    fn watch(&self, watcher: impl Fn(Context<Self::Output>) + 'static) -> Self::Guard {
        self.as_ref()
            .map(|s| s.watch(move |context| watcher(context.map(Some))))
    }
}

impl<T: Signal, E: Signal> Signal for Result<T, E> {
    type Output = Result<T::Output, E::Output>;
    type Guard = Result<T::Guard, E::Guard>;
    fn snapshot(&self) -> Self::Output {
        match &self {
            Ok(s) => Ok(s.snapshot()),
            Err(e) => Err(e.snapshot()),
        }
    }
    fn identity(&self) -> Option<SignalIdentity> {
        match &self {
            Ok(s) => s.identity(),
            Err(e) => e.identity(),
        }
    }
    fn watch(&self, watcher: impl Fn(Context<Self::Output>) + 'static) -> Self::Guard {
        match &self {
            Ok(s) => Ok(s.watch(move |context| watcher(context.map(Ok)))),
            Err(e) => Err(e.watch(move |context| watcher(context.map(Err)))),
        }
    }
}

struct TupleWatchState<L, R, W> {
    latest_left: RefCell<L>,
    latest_right: RefCell<R>,
    watcher: W,
}

impl<T, U> Signal for (T, U)
where
    T: Signal,
    U: Signal,
    T::Output: Clone,
    U::Output: Clone,
{
    type Output = (T::Output, U::Output);
    type Guard = (T::Guard, U::Guard);

    fn snapshot(&self) -> Self::Output {
        (self.0.snapshot(), self.1.snapshot())
    }

    fn watch(&self, watcher: impl Fn(Context<Self::Output>) + 'static) -> Self::Guard {
        let state = Rc::new(TupleWatchState {
            latest_left: RefCell::new(self.0.snapshot()),
            latest_right: RefCell::new(self.1.snapshot()),
            watcher,
        });

        let left_guard = {
            let state = Rc::clone(&state);
            self.0.watch(move |ctx: Context<T::Output>| {
                let updated_left = ctx.value().clone();
                *state.latest_left.borrow_mut() = updated_left;
                let right = state.latest_right.borrow().clone();
                (state.watcher)(ctx.map(|left| (left, right)));
            })
        };

        let right_guard = self.1.watch(move |ctx: Context<U::Output>| {
            let updated_right = ctx.value().clone();
            *state.latest_right.borrow_mut() = updated_right;
            let left = state.latest_left.borrow().clone();
            (state.watcher)(ctx.map(|right| (left, right)));
        });

        (left_guard, right_guard)
    }
}

#[cfg(test)]
mod tests {
    use alloc::{rc::Rc, vec, vec::Vec};
    use core::cell::RefCell;

    use crate::{Signal, watcher::Context};

    #[derive(Clone)]
    struct TestSignal<T> {
        value: Rc<RefCell<T>>,
        watchers: Rc<RefCell<Vec<Watcher<T>>>>,
    }

    type Watcher<T> = Rc<dyn Fn(Context<T>)>;

    impl<T: Clone + 'static> TestSignal<T> {
        fn new(value: T) -> Self {
            Self {
                value: Rc::new(RefCell::new(value)),
                watchers: Rc::new(RefCell::new(Vec::new())),
            }
        }

        fn set(&self, value: T) {
            *self.value.borrow_mut() = value.clone();
            for watcher in self.watchers.borrow().iter() {
                watcher(Context::from(value.clone()));
            }
        }
    }

    impl<T: Clone + 'static> Signal for TestSignal<T> {
        type Output = T;
        type Guard = ();

        fn snapshot(&self) -> Self::Output {
            self.value.borrow().clone()
        }

        fn watch(&self, watcher: impl Fn(Context<Self::Output>) + 'static) -> Self::Guard {
            self.watchers.borrow_mut().push(Rc::new(watcher));
        }
    }

    #[test]
    fn tuple_signal_tracks_both_inputs() {
        let left = TestSignal::new(1_i32);
        let right = TestSignal::new(2_i32);
        let pair = (left.clone(), right.clone());
        let updates = Rc::new(RefCell::new(Vec::new()));

        let _ = pair.watch({
            let updates = updates.clone();
            move |ctx| {
                updates.borrow_mut().push(ctx.into_value());
            }
        });

        left.set(3);
        right.set(4);

        assert_eq!(pair.snapshot(), (3, 4));
        assert_eq!(*updates.borrow(), vec![(3, 2), (3, 4)]);
    }
}