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
use std::{
cell::{Cell, RefCell},
rc::Rc,
};
use crate::{Composer, ComposerCore, Key, RecomposeScope, ValueSlotHandle, composer_context};
/// The parameters of one composable call, kept in a slot between recompositions so the call can
/// skip its body when they are unchanged. Generated by the `#[composable]` macro.
pub struct ParamState<T> {
pub(crate) value: Option<T>,
}
/// A parameter that points at a shared allocation: two that point at the
/// same one are equal without comparing what it holds.
pub trait SharedParam {
/// Whether `self` and `other` point at the same allocation.
fn same_allocation(&self, other: &Self) -> bool;
}
impl<T: ?Sized> SharedParam for Rc<T> {
fn same_allocation(&self, other: &Self) -> bool {
Self::ptr_eq(self, other)
}
}
impl<T: ?Sized> SharedParam for std::sync::Arc<T> {
fn same_allocation(&self, other: &Self) -> bool {
Self::ptr_eq(self, other)
}
}
impl<T> ParamState<T> {
/// Brings a call's stored parameters up to date: `fresh` stores them on
/// the call's first composition, and `refresh` updates each stored field
/// that differs and says whether any did. Unchanged fields are not
/// cloned again.
pub fn update_fields(
&mut self,
fresh: impl FnOnce() -> T,
refresh: impl FnOnce(&mut T) -> bool,
) -> bool {
match self.value.as_mut() {
Some(stored) => refresh(stored),
None => {
self.value = Some(fresh());
true
}
}
}
/// Returns a clone of the stored parameters, or `None` before any composition stored them.
pub fn value(&self) -> Option<T>
where
T: Clone,
{
self.value.clone()
}
}
/// A call's stored parameters and the value its body last returned, held in
/// one slot: a call that skips its body finds both with one lookup.
pub struct ParamReturnState<T, R> {
params: ParamState<T>,
returned: Option<R>,
}
impl<T, R> ParamReturnState<T, R> {
/// [`ParamState::update_fields`] for the stored parameters.
pub fn update_fields(
&mut self,
fresh: impl FnOnce() -> T,
refresh: impl FnOnce(&mut T) -> bool,
) -> bool {
self.params.update_fields(fresh, refresh)
}
/// Returns a clone of the stored parameters, or `None` before any composition stored them.
pub fn value(&self) -> Option<T>
where
T: Clone,
{
self.params.value()
}
/// The value the call's body returned last.
pub fn returned(&self) -> Option<R>
where
R: Clone,
{
self.returned.clone()
}
/// Stores the value the call's body returned, replacing the previous one.
pub fn store_return(&mut self, value: R) {
self.returned = Some(value);
}
}
impl<T, R> Default for ParamReturnState<T, R> {
fn default() -> Self {
Self {
params: ParamState::default(),
returned: None,
}
}
}
/// Updates one stored parameter to `new` and says whether it differed,
/// reusing the stored value's allocations where `Clone::clone_from` can.
pub fn refresh_param<T: PartialEq + Clone>(stored: &mut T, new: &T) -> bool {
if stored == new {
return false;
}
stored.clone_from(new);
true
}
/// Stores `new` as a parameter without comparing, and says it changed: for a
/// call that runs its body whatever its parameters, as one with a callback
/// does, a comparison would decide nothing. A `Modifier` compares element by
/// element.
pub fn store_param<T: Clone>(stored: &mut T, new: &T) -> bool {
stored.clone_from(new);
true
}
/// [`refresh_param`] for an `Rc` or `Arc` parameter: the same allocation is
/// unchanged without comparing its contents, which `PartialEq` on a pointer
/// to a type that is not `Eq` otherwise walks in full on every recomposition.
pub fn refresh_shared_param<T: SharedParam + PartialEq + Clone>(stored: &mut T, new: &T) -> bool {
if stored.same_allocation(new) || stored == new {
return false;
}
stored.clone_from(new);
true
}
/// ParamSlot holds function/closure parameters by ownership (no PartialEq/Clone required).
/// Used by the `#[composable]` macro to store Fn-like parameters in the slot table.
pub struct ParamSlot<T> {
val: RefCell<Option<T>>,
}
impl<T> Default for ParamSlot<T> {
fn default() -> Self {
Self {
val: RefCell::new(None),
}
}
}
impl<T> ParamSlot<T> {
/// Stores `v` as the held value, replacing the previous one.
pub fn set(&self, v: T) {
*self.val.borrow_mut() = Some(v);
}
/// Takes the value out temporarily for a recomposition callback.
pub fn take(&self) -> Option<T> {
self.val.borrow_mut().take()
}
}
type CallbackScopeCell = RefCell<Option<RecomposeScope>>;
// What a holder shares with the forwarders it hands out: the callback stored
// last, and its owner.
struct CallbackShared<F: ?Sized> {
owner: CallbackOwner,
callback: RefCell<Option<Box<F>>>,
}
// The part of a held callback that does not depend on its signature, so
// every forwarder runs one copy of the code that enters a call.
#[derive(Default)]
struct CallbackOwner {
// The scope that stored the callback.
creator_scope: CallbackScopeCell,
// Whether the callback ever ran outside an event handler.
renders: Cell<bool>,
}
// What a forwarder holds while the callback runs: the scope that stored it,
// pushed on the composer's scope stack when a composer is installed.
struct CallbackEntry {
_scope: Option<CallbackScopeGuard>,
}
impl CallbackOwner {
// Notes the run and enters the scope that stored the callback, while
// that scope is active. A run while composing, or outside the snapshot
// event handlers and effects run in, is a run during composition, layout
// or drawing, where what the callback does reaches the picture.
#[inline(never)]
fn enter(&self) -> Option<CallbackEntry> {
if !callback_owner_is_active(&self.creator_scope) {
return None;
}
if !self.renders.get()
&& (composer_context::has_composer() || !crate::in_applied_snapshot())
{
self.renders.set(true);
}
let scope = self.creator_scope.borrow().clone().and_then(|scope| {
composer_context::current_composer()
.map(|composer| CallbackScopeGuard::push(&composer, scope))
});
Some(CallbackEntry { _scope: scope })
}
}
struct CallbackScopeGuard {
core: Rc<ComposerCore>,
}
impl CallbackScopeGuard {
fn push(composer: &Composer, scope: RecomposeScope) -> Self {
composer.core.scope_stack.borrow_mut().push(scope);
Self {
core: composer.clone_core(),
}
}
}
impl Drop for CallbackScopeGuard {
fn drop(&mut self) {
self.core.scope_stack.borrow_mut().pop();
}
}
fn callback_owner_is_active(scope: &CallbackScopeCell) -> bool {
scope
.borrow()
.as_ref()
.is_none_or(RecomposeScope::is_effectively_active)
}
fn callback_owner_scope(composer: &Composer) -> Option<RecomposeScope> {
composer.core.scope_stack.borrow().last().cloned()
}
/// Keeps a composable's callback parameter across recompositions: its forwarders always call the
/// callback stored last. `F` is the callback's trait object, as `dyn FnMut(usize)`.
pub struct CallbackHolder<F: ?Sized + 'static = dyn FnMut()> {
shared: Rc<CallbackShared<F>>,
}
impl<F: ?Sized + 'static> CallbackHolder<F> {
/// A holder with no callback yet; its forwarders do nothing until one is stored.
pub fn new() -> Self {
Self::default()
}
/// Stores `callback` in place of the one stored last. Generated composable helpers take
/// callbacks type-erased at the public-fn boundary, so helper bodies are compiled once
/// instead of once per caller closure type.
pub fn update_boxed(&self, callback: Box<F>) {
*self.shared.callback.borrow_mut() = Some(callback);
*self.shared.owner.creator_scope.borrow_mut() =
composer_context::try_with_composer(callback_owner_scope).flatten();
}
/// Whether the callback ever ran outside an event handler or an effect: during
/// composition, layout or drawing. A call whose other parameters are unchanged skips its
/// body when its new callbacks never did, because its forwarders call the new ones.
pub fn renders(&self) -> bool {
self.shared.owner.renders.get()
}
/// The handle a forwarder closure calls the stored callback through.
pub fn forwarder(&self) -> CallbackForwarder<F> {
CallbackForwarder {
shared: Rc::clone(&self.shared),
}
}
/// Stores a call's callback in its next parameter slot, and says
/// whether the callback stored there before ever ran outside an event
/// handler. One copy per callback signature serves every composable.
#[doc(hidden)]
pub fn __hold(
composer: &Composer,
source: Key,
callback: Box<F>,
) -> (ValueSlotHandle<'_, Self>, bool) {
composer.__update_param_slot(source, Self::new, |holder: &mut Self| {
holder.update_boxed(callback);
holder.renders()
})
}
/// The holder in a call's next parameter slot, for a recomposition
/// that runs the call's body again.
#[doc(hidden)]
pub fn __slot(composer: &Composer, source: Key) -> ValueSlotHandle<'_, Self> {
composer.__use_param_slot(source, Self::new)
}
/// A forwarder for the holder in `slot`.
#[doc(hidden)]
pub fn __forwarder<'pass>(
composer: &'pass Composer,
slot: ValueSlotHandle<'pass, Self>,
) -> CallbackForwarder<F> {
composer.with_slot_value(slot, Self::forwarder)
}
}
impl<F: ?Sized + 'static> Clone for CallbackHolder<F> {
fn clone(&self) -> Self {
Self {
shared: Rc::clone(&self.shared),
}
}
}
impl CallbackHolder {
/// Stores `callback` in place of the one stored last.
pub fn update(&self, callback: impl FnMut() + 'static) {
self.update_boxed(Box::new(callback));
}
/// A forwarder that calls the callback stored last.
pub fn clone_rc(&self) -> impl Fn() + 'static + use<> {
let forwarder = self.forwarder();
move || forwarder.call(|callback| callback())
}
}
impl<F: ?Sized + 'static> Default for CallbackHolder<F> {
fn default() -> Self {
Self {
shared: Rc::new(CallbackShared {
owner: CallbackOwner::default(),
callback: RefCell::new(None),
}),
}
}
}
/// A forwarder's handle on a [`CallbackHolder`], which calls the callback stored last in the
/// scope that stored it.
pub struct CallbackForwarder<F: ?Sized + 'static> {
shared: Rc<CallbackShared<F>>,
}
impl<F: ?Sized + 'static> CallbackForwarder<F> {
/// Calls the callback stored last; once the scope that stored it is no longer
/// active, does nothing.
pub fn call(&self, call: impl FnOnce(&mut F)) {
let Some(_entry) = self.shared.owner.enter() else {
return;
};
if let Some(callback) = self.shared.callback.borrow_mut().as_mut() {
call(callback);
}
}
}
impl<F: ?Sized + 'static> Clone for CallbackForwarder<F> {
fn clone(&self) -> Self {
Self {
shared: Rc::clone(&self.shared),
}
}
}
/// Holds the value a composable call returned, so a later composition that skips the call can
/// return it again.
pub struct ReturnSlot<T> {
value: Option<T>,
}
impl<T: Clone> ReturnSlot<T> {
/// Stores `value` as the call's latest return value.
pub fn store(&mut self, value: T) {
self.value = Some(value);
}
/// Returns a clone of the stored return value, or `None` if the call has not returned one yet.
pub fn get(&self) -> Option<T> {
self.value.clone()
}
}
impl<T> Default for ParamState<T> {
fn default() -> Self {
Self { value: None }
}
}
impl<T> Default for ReturnSlot<T> {
fn default() -> Self {
Self { value: None }
}
}
#[cfg(test)]
#[path = "tests/callbacks_callback_holder_tests.rs"]
mod callback_holder_tests;
#[cfg(test)]
#[path = "tests/callbacks_param_state_tests.rs"]
mod param_state_tests;