1use std::any::{Any, TypeId};
4use std::collections::HashMap;
5use std::fmt;
6use std::hash::{Hash, Hasher};
7use std::rc::Rc;
8
9use waft_foundation::{App, Handle, Key, LocalKey};
10
11use crate::framework::{
12 AnyElement, BuildContext, IntoWidget, KeyRef, StatelessWidget, WidgetRef, downcast_widget,
13};
14use waft_foundation::Ref;
15
16pub struct PageStorageKey {
31 value: Rc<dyn Key>,
32}
33
34impl PageStorageKey {
35 pub fn new<T: PartialEq + Hash + fmt::Debug + 'static>(value: T) -> PageStorageKey {
39 PageStorageKey {
40 value: Rc::new(waft_foundation::ValueKey::new(value)),
41 }
42 }
43
44 pub fn into_key(self) -> KeyRef {
46 self.into()
47 }
48}
49
50impl Key for PageStorageKey {
51 fn eq_key(&self, other: &dyn Key) -> bool {
52 (other as &dyn Any)
53 .downcast_ref::<PageStorageKey>()
54 .is_some_and(|other| *other.value == *self.value)
55 }
56
57 fn hash_key(&self, mut state: &mut dyn Hasher) {
58 TypeId::of::<PageStorageKey>().hash(&mut state);
59 self.value.hash_key(state);
60 }
61}
62
63impl LocalKey for PageStorageKey {}
64
65impl fmt::Debug for PageStorageKey {
66 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67 write!(f, "[PageStorageKey {:?}]", self.value)
68 }
69}
70
71#[derive(Clone)]
74struct StorageEntryIdentifier {
75 keys: Vec<KeyRef>,
76}
77
78impl StorageEntryIdentifier {
79 fn is_not_empty(&self) -> bool {
80 !self.keys.is_empty()
81 }
82}
83
84impl PartialEq for StorageEntryIdentifier {
85 fn eq(&self, other: &StorageEntryIdentifier) -> bool {
86 self.keys.len() == other.keys.len()
87 && self
88 .keys
89 .iter()
90 .zip(&other.keys)
91 .all(|(mine, theirs)| mine == theirs)
92 }
93}
94
95impl Eq for StorageEntryIdentifier {}
96
97impl Hash for StorageEntryIdentifier {
98 fn hash<H: Hasher>(&self, state: &mut H) {
99 for key in &self.keys {
100 key.hash(state);
101 }
102 }
103}
104
105impl fmt::Debug for StorageEntryIdentifier {
106 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107 write!(f, "StorageEntryIdentifier(")?;
108 for (index, key) in self.keys.iter().enumerate() {
109 if index > 0 {
110 write!(f, ":")?;
111 }
112 write!(f, "{key:?}")?;
113 }
114 write!(f, ")")
115 }
116}
117
118#[derive(Clone)]
121enum StorageSlot {
122 Entry(StorageEntryIdentifier),
123 Identifier(KeyRef),
124}
125
126impl PartialEq for StorageSlot {
127 fn eq(&self, other: &StorageSlot) -> bool {
128 match (self, other) {
129 (StorageSlot::Entry(mine), StorageSlot::Entry(theirs)) => mine == theirs,
130 (StorageSlot::Identifier(mine), StorageSlot::Identifier(theirs)) => mine == theirs,
131 _ => false,
132 }
133 }
134}
135
136impl Eq for StorageSlot {}
137
138impl Hash for StorageSlot {
139 fn hash<H: Hasher>(&self, state: &mut H) {
140 match self {
141 StorageSlot::Entry(entry) => {
142 0u8.hash(state);
143 entry.hash(state);
144 }
145 StorageSlot::Identifier(key) => {
146 1u8.hash(state);
147 key.hash(state);
148 }
149 }
150 }
151}
152
153#[derive(Default)]
160pub struct PageStorageBucket {
161 storage: Option<HashMap<StorageSlot, Rc<dyn Any>>>,
162}
163
164impl PageStorageBucket {
165 pub fn new(app: &mut App) -> Ref<PageStorageBucket> {
167 app.create(PageStorageBucket::default())
168 }
169
170 fn maybe_add_key(app: &App, context: AnyElement, keys: &mut Vec<KeyRef>) -> bool {
171 let widget = context.widget(app);
172 if let Some(key) = widget.key()
173 && (key.key() as &dyn Any).is::<PageStorageKey>()
174 {
175 keys.push(key.clone());
176 }
177 downcast_widget::<PageStorage>(&**widget).is_none()
178 }
179
180 fn all_keys(app: &App, context: BuildContext) -> Vec<KeyRef> {
181 let mut keys = Vec::new();
182 if Self::maybe_add_key(app, context, &mut keys) {
183 context.visit_ancestor_elements(app, &mut |element| {
184 Self::maybe_add_key(app, element, &mut keys)
185 });
186 }
187 keys
188 }
189
190 fn compute_identifier(app: &App, context: BuildContext) -> StorageEntryIdentifier {
191 StorageEntryIdentifier {
192 keys: Self::all_keys(app, context),
193 }
194 }
195
196 pub fn write_state(
204 self: Handle<Self>,
205 app: &mut App,
206 context: BuildContext,
207 data: Rc<dyn Any>,
208 identifier: Option<KeyRef>,
209 ) {
210 let slot = match identifier {
211 Some(identifier) => StorageSlot::Identifier(identifier),
212 None => {
213 let context_identifier = Self::compute_identifier(app, context);
214 if !context_identifier.is_not_empty() {
215 app.get_mut(self).storage.get_or_insert_with(HashMap::new);
216 return;
217 }
218 StorageSlot::Entry(context_identifier)
219 }
220 };
221 app.get_mut(self)
222 .storage
223 .get_or_insert_with(HashMap::new)
224 .insert(slot, data);
225 }
226
227 pub fn read_state(
235 self: Handle<Self>,
236 app: &App,
237 context: BuildContext,
238 identifier: Option<KeyRef>,
239 ) -> Option<Rc<dyn Any>> {
240 let storage = app.get(self).storage.as_ref()?;
241 let slot = match identifier {
242 Some(identifier) => StorageSlot::Identifier(identifier),
243 None => {
244 let context_identifier = Self::compute_identifier(app, context);
245 if !context_identifier.is_not_empty() {
246 return None;
247 }
248 StorageSlot::Entry(context_identifier)
249 }
250 };
251 storage.get(&slot).cloned()
252 }
253}
254
255#[derive(Debug)]
268pub struct PageStorage {
269 pub key: Option<KeyRef>,
270 pub bucket: Ref<PageStorageBucket>,
272 pub child: WidgetRef,
274}
275
276impl PageStorage {
277 #[cfg_attr(debug_assertions, track_caller)]
279 pub fn new<K>(bucket: Ref<PageStorageBucket>, child: impl IntoWidget<K>) -> PageStorage {
280 PageStorage {
281 key: None,
282 bucket,
283 child: child.into_widget(),
284 }
285 }
286
287 pub fn key(mut self, key: KeyRef) -> PageStorage {
289 self.key = Some(key);
290 self
291 }
292
293 pub fn maybe_of(app: &App, context: BuildContext) -> Option<Handle<PageStorageBucket>> {
306 context
307 .find_ancestor_widget_of_exact_type::<PageStorage>(app)
308 .map(|widget| widget.bucket.handle())
309 }
310
311 pub fn of(app: &App, context: BuildContext) -> Handle<PageStorageBucket> {
319 PageStorage::maybe_of(app, context).unwrap_or_else(|| {
320 panic!(
321 "PageStorage.of() was called with a context that does not contain a PageStorage \
322 widget.\nNo PageStorage widget ancestor could be found starting from the \
323 context that was passed to PageStorage.of(). This can happen because you are \
324 using a widget that looks for a PageStorage ancestor, but no such ancestor \
325 exists.\nThe context used was:\n {}",
326 context.widget(app).type_name()
327 )
328 })
329 }
330}
331
332impl StatelessWidget for PageStorage {
333 fn key(&self) -> Option<&KeyRef> {
334 self.key.as_ref()
335 }
336
337 fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
338 self.child.clone()
339 }
340}
341
342#[cfg(test)]
343mod tests {
344 use std::cell::RefCell;
345 use waft_foundation::AppCell;
346
347 use super::*;
348 use crate::test_harness::Harness;
349 use crate::widgets::basic::{Builder, Padding, SizedBox};
350 use waft_painting::EdgeInsetsGeometry;
351
352 fn probe(seen: &Rc<RefCell<Vec<Option<i32>>>>, value: i32) -> WidgetRef {
354 let seen = Rc::clone(seen);
355 Builder::new(move |app, context| {
356 let bucket = PageStorage::of(app, context);
357 let read = bucket
358 .read_state(app, context, None)
359 .and_then(|data| data.downcast_ref::<i32>().copied());
360 seen.borrow_mut().push(read);
361 bucket.write_state(app, context, Rc::new(value), None);
362 SizedBox::shrink().into_widget()
363 })
364 .into_widget()
365 }
366
367 #[test]
368 fn state_is_filed_under_the_page_storage_key_chain() {
369 let cell = AppCell::new();
370 let mut app = cell.borrow_mut();
371 let bucket = PageStorageBucket::new(&mut app);
372 let seen = Rc::new(RefCell::new(Vec::new()));
373 let page = |seen: &Rc<RefCell<Vec<Option<i32>>>>, value: i32| {
374 PageStorage::new(
375 bucket.clone(),
376 Padding::new(EdgeInsetsGeometry::ZERO)
377 .key(PageStorageKey::new("page").into_key())
378 .child(probe(seen, value)),
379 )
380 .into_widget()
381 };
382 let harness = Harness::mount(&mut app, page(&seen, 1));
383 harness.pump(&mut app);
384 assert_eq!(*seen.borrow(), vec![None]);
385
386 harness.set_child(&mut app, SizedBox::shrink().into_widget());
388 harness.pump(&mut app);
389 harness.set_child(&mut app, page(&seen, 2));
390 harness.pump(&mut app);
391 assert_eq!(*seen.borrow(), vec![None, Some(1)]);
392 }
393
394 #[test]
395 fn without_keys_nothing_is_saved_and_identifiers_are_direct() {
396 let cell = AppCell::new();
397 let mut app = cell.borrow_mut();
398 let bucket = PageStorageBucket::new(&mut app);
399 let seen = Rc::new(RefCell::new(Vec::new()));
400 let harness = Harness::mount(
401 &mut app,
402 PageStorage::new(bucket.clone(), probe(&seen, 1)).into_widget(),
403 );
404 harness.pump(&mut app);
405 harness.set_child(
406 &mut app,
407 PageStorage::new(bucket.clone(), probe(&seen, 2)).into_widget(),
408 );
409 harness.pump(&mut app);
410 assert_eq!(*seen.borrow(), vec![None, None]);
411
412 let context = Rc::new(std::cell::Cell::new(None));
413 let capture = Builder::new({
414 let context = Rc::clone(&context);
415 move |_app, this| {
416 context.set(Some(this));
417 SizedBox::shrink().into_widget()
418 }
419 });
420 harness.set_child(
421 &mut app,
422 PageStorage::new(bucket.clone(), capture).into_widget(),
423 );
424 harness.pump(&mut app);
425 let context = context.get().expect("the probe built");
426 assert_eq!(PageStorage::maybe_of(&app, context), Some(bucket.handle()));
427
428 let identifier: KeyRef = waft_foundation::ValueKey::new("scroll").into();
429 bucket.write_state(&mut app, context, Rc::new(4.5f64), Some(identifier.clone()));
430 let read = bucket
431 .read_state(&app, context, Some(identifier))
432 .and_then(|data| data.downcast_ref::<f64>().copied());
433 assert_eq!(read, Some(4.5));
434 }
435}