cranpose-core 0.13.0

Composition runtime and reactive state for Cranpose
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
use std::{any::Any, cell::RefCell, rc::Rc, sync::Arc};

use crate::{
    Composer, LocalKey, RuntimeHandle, composer_context,
    state::{MutationPolicy, OwnedMutableState},
};

fn provider_entry_source(key: &LocalKey, caller: crate::Key) -> crate::Key {
    (key.entry_source() ^ caller).wrapping_mul(0x0000_0100_0000_01b3)
}

/// A composition local paired with the value to provide, made by `provides` and passed to
/// `CompositionLocalProvider`.
pub struct ProvidedValue {
    key: LocalKey,
    #[expect(clippy::type_complexity)]
    apply: Box<dyn Fn(&Composer, crate::Key) -> (Rc<dyn Any>, bool)>,
}

impl ProvidedValue {
    pub(crate) fn key(&self) -> &LocalKey {
        &self.key
    }

    /// The provided entry, and whether it replaced a different value of a
    /// static local that this site provided before.
    pub(crate) fn into_entry(
        self,
        composer: &Composer,
        site: crate::Key,
    ) -> (LocalKey, Rc<dyn Any>, bool) {
        let ProvidedValue { key, apply } = self;
        let (entry, static_changed) = apply(composer, site);
        (key, entry, static_changed)
    }
}

/// Makes `values` available to `content` and everything it composes. Where two values are for the
/// same local, the last wins. Compose's `CompositionLocalProvider`.
#[expect(non_snake_case)]
#[track_caller]
pub fn CompositionLocalProvider(
    values: impl IntoIterator<Item = ProvidedValue>,
    content: impl FnOnce(),
) {
    let site = crate::caller_location_key();
    composer_context::with_composer(|composer| {
        composer.with_composition_locals(values, site, |_composer| content());
    });
}

pub(crate) struct LocalStateEntry<T: Clone + 'static> {
    state: OwnedMutableState<T>,
}

type LocalEquivalentFn<T> = dyn Fn(&T, &T) -> bool + Send + Sync + 'static;

struct LocalValuePolicy<T: Clone + 'static> {
    equivalent: Arc<LocalEquivalentFn<T>>,
}

impl<T: Clone + 'static> MutationPolicy<T> for LocalValuePolicy<T> {
    fn equivalent(&self, a: &T, b: &T) -> bool {
        (self.equivalent)(a, b)
    }
}

impl<T: Clone + 'static> LocalStateEntry<T> {
    fn new(initial: T, runtime: RuntimeHandle, equivalent: Arc<LocalEquivalentFn<T>>) -> Self {
        Self {
            state: OwnedMutableState::with_runtime_and_policy(
                initial,
                runtime,
                Rc::new(LocalValuePolicy { equivalent }),
            ),
        }
    }

    fn set(&self, value: T) {
        self.state.replace(value);
    }

    pub(crate) fn value(&self) -> T {
        self.state.value()
    }
}

pub(crate) struct StaticLocalEntry<T: Clone + 'static> {
    value: RefCell<T>,
}

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

    /// Stores `value` and says whether it differs from the stored one.
    fn set(&self, value: T, equivalent: &LocalEquivalentFn<T>) -> bool {
        let mut current = self.value.borrow_mut();
        if equivalent(&current, &value) {
            return false;
        }
        *current = value;
        true
    }

    pub(crate) fn value(&self) -> T {
        self.value.borrow().clone()
    }
}

type ComputeLocalFn<T> = dyn Fn(&CompositionLocalAccessorScope) -> T;

/// The value of a local whose provider computes it where it is read, from
/// the other locals there. A reader recomposes when the provider gives a
/// new computation, as with Compose's lambdas that are not remembered.
pub(crate) struct ComputedLocalEntry<T: 'static> {
    compute: OwnedMutableState<Rc<ComputeLocalFn<T>>>,
}

impl<T: 'static> ComputedLocalEntry<T> {
    pub(crate) fn value(&self) -> T {
        let compute = self.compute.value();
        compute(&CompositionLocalAccessorScope { _private: () })
    }
}

/// A static local's computed value: see [`ComputedLocalEntry`]. A new
/// computation recomposes all the provider's content, as a new static value
/// does.
pub(crate) struct StaticComputedLocalEntry<T: 'static> {
    compute: Rc<ComputeLocalFn<T>>,
}

impl<T: 'static> StaticComputedLocalEntry<T> {
    pub(crate) fn value(&self) -> T {
        (self.compute)(&CompositionLocalAccessorScope { _private: () })
    }
}

/// What a computed composition local's value reads other locals through:
/// their values where the computed local is read, not where it was
/// provided. Compose's `CompositionLocalAccessorScope`.
pub struct CompositionLocalAccessorScope {
    _private: (),
}

impl CompositionLocalAccessorScope {
    /// The value `local` has where the computed local is read. Compose's
    /// `CompositionLocal.currentValue` in this scope.
    pub fn current_value<T>(&self, local: &impl ReadableCompositionLocal<T>) -> T {
        local.read_current()
    }
}

/// A composition local whose current value a computed local can read; see
/// [`CompositionLocalAccessorScope`].
pub trait ReadableCompositionLocal<T> {
    /// The local's value where it is read, as `current` gives it.
    fn read_current(&self) -> T;
}

impl<T: Clone + 'static> ReadableCompositionLocal<T> for CompositionLocal<T> {
    fn read_current(&self) -> T {
        self.current()
    }
}

impl<T: Clone + 'static> ReadableCompositionLocal<T> for StaticCompositionLocal<T> {
    fn read_current(&self) -> T {
        self.current()
    }
}

/// A value that composables read from their surroundings without passing it as a parameter, as
/// Jetpack Compose's `compositionLocalOf`. A scope that reads `current` recomposes when the
/// provided value changes.
#[derive(Clone)]
pub struct CompositionLocal<T: Clone + 'static> {
    pub(crate) key: LocalKey,
    default: Rc<dyn Fn() -> T>,
    equivalent: Arc<LocalEquivalentFn<T>>,
}

impl<T: Clone + 'static> PartialEq for CompositionLocal<T> {
    fn eq(&self, other: &Self) -> bool {
        self.key == other.key
    }
}

impl<T: Clone + 'static> Eq for CompositionLocal<T> {}

impl<T: Clone + 'static> CompositionLocal<T> {
    /// Pairs this local with `value` for use in `CompositionLocalProvider`. When a later
    /// composition provides a different value, the scopes that read the local recompose.
    #[track_caller]
    pub fn provides(&self, value: T) -> ProvidedValue {
        let key = self.key.clone();
        let entry_source = provider_entry_source(&key, crate::caller_location_key());
        let equivalent = Arc::clone(&self.equivalent);
        ProvidedValue {
            key,
            apply: Box::new(move |composer: &Composer, site: crate::Key| {
                let runtime = composer.runtime_handle();
                let source = (entry_source ^ site).wrapping_mul(0x0000_0100_0000_01b3);
                let entry_ref = composer.remember_internal(source, || {
                    Rc::new(LocalStateEntry::new(
                        value.clone(),
                        runtime.clone(),
                        Arc::clone(&equivalent),
                    ))
                });
                entry_ref.update(|entry| entry.set(value.clone()));
                entry_ref.with(|entry| (entry.clone() as Rc<dyn Any>, false))
            }),
        }
    }

    /// Pairs this local with `compute`, which runs at each read of the local
    /// under the provider and reads other locals there through its scope.
    /// A reader recomposes when a local the computation read changes, and
    /// when a later composition of the provider gives a new computation.
    /// Compose's `providesComputed`.
    #[track_caller]
    pub fn provides_computed(
        &self,
        compute: impl Fn(&CompositionLocalAccessorScope) -> T + 'static,
    ) -> ProvidedValue {
        let key = self.key.clone();
        let entry_source = provider_entry_source(&key, crate::caller_location_key());
        let compute: Rc<ComputeLocalFn<T>> = Rc::new(compute);
        ProvidedValue {
            key,
            apply: Box::new(move |composer: &Composer, site: crate::Key| {
                let runtime = composer.runtime_handle();
                let source = (entry_source ^ site).wrapping_mul(0x0000_0100_0000_01b3);
                let entry_ref = composer.remember_internal(source, || {
                    Rc::new(ComputedLocalEntry {
                        compute: OwnedMutableState::with_runtime_and_policy(
                            Rc::clone(&compute),
                            runtime.clone(),
                            Rc::new(LocalValuePolicy::<Rc<ComputeLocalFn<T>>> {
                                equivalent: Arc::new(Rc::ptr_eq),
                            }),
                        ),
                    })
                });
                entry_ref.update(|entry| entry.compute.replace(Rc::clone(&compute)));
                entry_ref.with(|entry| (entry.clone() as Rc<dyn Any>, false))
            }),
        }
    }

    /// Returns the value from the innermost enclosing provider, or the default value when none is
    /// in scope. Must be called during composition. The reading scope recomposes when the provided
    /// value changes.
    pub fn current(&self) -> T {
        composer_context::with_composer(|composer| composer.read_composition_local(self))
    }

    /// Returns the value that `current` gives where no provider is in scope.
    pub fn default_value(&self) -> T {
        (self.default)()
    }
}

#[cfg(test)]
fn malformed_provided_value_for_test(key: LocalKey, entry: Rc<dyn Any>) -> ProvidedValue {
    ProvidedValue {
        key,
        apply: Box::new(move |_, _| (entry.clone(), false)),
    }
}

#[cfg(test)]
pub(crate) fn malformed_composition_local_for_test<T: Clone + 'static>(
    local: &CompositionLocal<T>,
    entry: Rc<dyn Any>,
) -> ProvidedValue {
    malformed_provided_value_for_test(local.key.clone(), entry)
}

/// Creates a [`CompositionLocal`] whose default is made by `default`. A provided value replaces the
/// previous one when it differs by `==`. Compose's `compositionLocalOf`.
#[expect(non_snake_case)]
pub fn compositionLocalOf<T: Clone + PartialEq + 'static>(
    default: impl Fn() -> T + 'static,
) -> CompositionLocal<T> {
    compositionLocalOfWithPolicy(default, |current, next| current == next)
}

/// Creates a [`CompositionLocal`] whose default is made by `default`. A provided value replaces the
/// previous one only when `equivalent` returns `false` for the two.
#[expect(non_snake_case)]
pub fn compositionLocalOfWithPolicy<T: Clone + 'static>(
    default: impl Fn() -> T + 'static,
    equivalent: impl Fn(&T, &T) -> bool + Send + Sync + 'static,
) -> CompositionLocal<T> {
    CompositionLocal {
        key: LocalKey::new(),
        default: Rc::new(default),
        equivalent: Arc::new(equivalent),
    }
}

/// A composition local for values that rarely change, as Jetpack Compose's
/// `staticCompositionLocalOf`. A read of `.current()` subscribes nothing, so
/// it costs less than a read of a [`CompositionLocal`]. In return, a
/// provider whose value changes recomposes everything it provides to, not
/// only the readers: every composable call under it runs its body, and
/// every subcomposition under it composes again the same way.
#[derive(Clone)]
pub struct StaticCompositionLocal<T: Clone + 'static> {
    pub(crate) key: LocalKey,
    default: Rc<dyn Fn() -> T>,
    equivalent: Arc<LocalEquivalentFn<T>>,
}

impl<T: Clone + 'static> PartialEq for StaticCompositionLocal<T> {
    fn eq(&self, other: &Self) -> bool {
        self.key == other.key
    }
}

impl<T: Clone + 'static> Eq for StaticCompositionLocal<T> {}

impl<T: Clone + 'static> StaticCompositionLocal<T> {
    /// Pairs this local with `value` for use in `CompositionLocalProvider`. When a later
    /// composition provides a different value, everything under the provider recomposes.
    #[track_caller]
    pub fn provides(&self, value: T) -> ProvidedValue {
        let key = self.key.clone();
        let entry_source = provider_entry_source(&key, crate::caller_location_key());
        let equivalent = Arc::clone(&self.equivalent);
        ProvidedValue {
            key,
            apply: Box::new(move |composer: &Composer, site: crate::Key| {
                let source = (entry_source ^ site).wrapping_mul(0x0000_0100_0000_01b3);
                let entry_ref = composer
                    .remember_internal(source, || Rc::new(StaticLocalEntry::new(value.clone())));
                let changed = entry_ref.update(|entry| entry.set(value.clone(), &*equivalent));
                entry_ref.with(|entry| (entry.clone() as Rc<dyn Any>, changed))
            }),
        }
    }

    /// Pairs this local with `compute`, which runs at each read of the local
    /// under the provider and reads other locals there through its scope.
    /// Each composition of the provider gives a new computation, which
    /// recomposes everything under it. Compose's `providesComputed`.
    #[track_caller]
    pub fn provides_computed(
        &self,
        compute: impl Fn(&CompositionLocalAccessorScope) -> T + 'static,
    ) -> ProvidedValue {
        let compute: Rc<ComputeLocalFn<T>> = Rc::new(compute);
        ProvidedValue {
            key: self.key.clone(),
            apply: Box::new(move |_: &Composer, _: crate::Key| {
                let entry = Rc::new(StaticComputedLocalEntry {
                    compute: Rc::clone(&compute),
                });
                (entry as Rc<dyn Any>, true)
            }),
        }
    }

    /// Returns the value from the innermost enclosing provider, or the default value when none is
    /// in scope. Must be called during composition. A read subscribes nothing.
    pub fn current(&self) -> T {
        composer_context::with_composer(|composer| composer.read_static_composition_local(self))
    }

    /// Returns the value that `current` gives where no provider is in scope.
    pub fn default_value(&self) -> T {
        (self.default)()
    }
}

#[cfg(test)]
pub(crate) fn malformed_static_composition_local_for_test<T: Clone + 'static>(
    local: &StaticCompositionLocal<T>,
    entry: Rc<dyn Any>,
) -> ProvidedValue {
    malformed_provided_value_for_test(local.key.clone(), entry)
}

/// A [`StaticCompositionLocal`] whose provided values compare with `==`.
#[expect(non_snake_case)]
pub fn staticCompositionLocalOf<T: Clone + PartialEq + 'static>(
    default: impl Fn() -> T + 'static,
) -> StaticCompositionLocal<T> {
    staticCompositionLocalOfWithPolicy(default, |current, next| current == next)
}

/// A [`StaticCompositionLocal`] whose provider recomposes its content when
/// `equivalent` says a new value differs from the last one.
#[expect(non_snake_case)]
pub fn staticCompositionLocalOfWithPolicy<T: Clone + 'static>(
    default: impl Fn() -> T + 'static,
    equivalent: impl Fn(&T, &T) -> bool + Send + Sync + 'static,
) -> StaticCompositionLocal<T> {
    StaticCompositionLocal {
        key: LocalKey::new(),
        default: Rc::new(default),
        equivalent: Arc::new(equivalent),
    }
}

/// A [`CompositionLocal`] whose default is computed at each read without a
/// provider, from the other locals there. A scope that reads it recomposes
/// when a dynamic local the computation read changes. As the default reads
/// locals, it is computed during composition only. Compose's
/// `compositionLocalWithComputedDefaultOf`.
#[expect(non_snake_case)]
pub fn compositionLocalWithComputedDefaultOf<T: Clone + PartialEq + 'static>(
    compute: impl Fn(&CompositionLocalAccessorScope) -> T + 'static,
) -> CompositionLocal<T> {
    compositionLocalOf(move || compute(&CompositionLocalAccessorScope { _private: () }))
}

/// A [`StaticCompositionLocal`] whose default is computed at each read
/// without a provider, from the other locals there. Compose's
/// `staticCompositionLocalWithComputedDefaultOf`.
#[expect(non_snake_case)]
pub fn staticCompositionLocalWithComputedDefaultOf<T: Clone + PartialEq + 'static>(
    compute: impl Fn(&CompositionLocalAccessorScope) -> T + 'static,
) -> StaticCompositionLocal<T> {
    staticCompositionLocalOf(move || compute(&CompositionLocalAccessorScope { _private: () }))
}