operad 8.0.1

A cross-platform GUI library for Rust.
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
//! Backend-neutral retained widget state and lifecycle reconciliation.
//!
//! The store in this module is intentionally app-agnostic. Applications provide
//! stable widget IDs and scopes, while widgets describe typed state slots that
//! can survive document rebuilds without coupling to a renderer or host.

use std::collections::{HashMap, HashSet};
use std::fmt;

use crate::{
    runtime::{RuntimeInvalidation, RuntimeInvalidationReason, RuntimeWindowId},
    AnimationState, DirtyFlags, ScrollState,
};

#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct WidgetId(String);

impl WidgetId {
    pub fn new(id: impl Into<String>) -> Self {
        Self(id.into())
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }

    pub fn into_string(self) -> String {
        self.0
    }
}

impl AsRef<str> for WidgetId {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl From<&str> for WidgetId {
    fn from(value: &str) -> Self {
        Self::new(value)
    }
}

impl From<String> for WidgetId {
    fn from(value: String) -> Self {
        Self::new(value)
    }
}

impl From<&WidgetId> for WidgetId {
    fn from(value: &WidgetId) -> Self {
        value.clone()
    }
}

impl fmt::Display for WidgetId {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct WidgetStateSlotId(String);

impl WidgetStateSlotId {
    pub fn new(id: impl Into<String>) -> Self {
        Self(id.into())
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl From<&str> for WidgetStateSlotId {
    fn from(value: &str) -> Self {
        Self::new(value)
    }
}

impl From<String> for WidgetStateSlotId {
    fn from(value: String) -> Self {
        Self::new(value)
    }
}

impl fmt::Display for WidgetStateSlotId {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum WidgetStateScope {
    Document(String),
    Window(RuntimeWindowId),
    Custom(String),
}

impl WidgetStateScope {
    pub fn document(id: impl Into<String>) -> Self {
        Self::Document(id.into())
    }

    pub fn window(id: impl Into<RuntimeWindowId>) -> Self {
        Self::Window(id.into())
    }

    pub fn custom(id: impl Into<String>) -> Self {
        Self::Custom(id.into())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct WidgetKey {
    pub scope: WidgetStateScope,
    pub id: WidgetId,
}

impl WidgetKey {
    pub fn new(scope: WidgetStateScope, id: impl Into<WidgetId>) -> Self {
        Self {
            scope,
            id: id.into(),
        }
    }

    pub fn document(document: impl Into<String>, id: impl Into<WidgetId>) -> Self {
        Self::new(WidgetStateScope::document(document), id)
    }

    pub fn window(window: impl Into<RuntimeWindowId>, id: impl Into<WidgetId>) -> Self {
        Self::new(WidgetStateScope::window(window), id)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct WidgetStateKey {
    pub widget: WidgetKey,
    pub slot: WidgetStateSlotId,
}

impl WidgetStateKey {
    pub fn new(widget: WidgetKey, slot: impl Into<WidgetStateSlotId>) -> Self {
        Self {
            widget,
            slot: slot.into(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum WidgetStateSlotKind {
    Focus,
    Hover,
    Pressed,
    Overlay,
    Scroll,
    Animation,
    Edit,
    Custom(String),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WidgetStateSlotDescriptor {
    pub id: WidgetStateSlotId,
    pub kind: WidgetStateSlotKind,
    pub dirty_flags: DirtyFlags,
    pub invalidation_reason: RuntimeInvalidationReason,
}

impl WidgetStateSlotDescriptor {
    pub fn new(id: impl Into<WidgetStateSlotId>, kind: WidgetStateSlotKind) -> Self {
        let kind_for_flags = kind.clone();
        Self {
            id: id.into(),
            kind,
            dirty_flags: dirty_flags_for_slot_kind(&kind_for_flags),
            invalidation_reason: invalidation_reason_for_slot_kind(&kind_for_flags),
        }
    }

    pub fn focus() -> Self {
        Self::new("focus", WidgetStateSlotKind::Focus)
    }

    pub fn hover() -> Self {
        Self::new("hover", WidgetStateSlotKind::Hover)
    }

    pub fn pressed() -> Self {
        Self::new("pressed", WidgetStateSlotKind::Pressed)
    }

    pub fn overlay() -> Self {
        Self::new("overlay", WidgetStateSlotKind::Overlay)
    }

    pub fn scroll() -> Self {
        Self::new("scroll", WidgetStateSlotKind::Scroll)
    }

    pub fn animation() -> Self {
        Self::new("animation", WidgetStateSlotKind::Animation)
    }

    pub fn edit() -> Self {
        Self::new("edit", WidgetStateSlotKind::Edit)
    }

    pub fn custom(id: impl Into<WidgetStateSlotId>, kind: impl Into<String>) -> Self {
        Self::new(id, WidgetStateSlotKind::Custom(kind.into()))
    }

    pub const fn dirty_flags(mut self, dirty_flags: DirtyFlags) -> Self {
        self.dirty_flags = dirty_flags;
        self
    }

    pub const fn invalidation_reason(mut self, reason: RuntimeInvalidationReason) -> Self {
        self.invalidation_reason = reason;
        self
    }
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct WidgetFocusState {
    pub focused: bool,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct WidgetHoverState {
    pub hovered: bool,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct WidgetPressedState {
    pub pressed: bool,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct WidgetOverlayState {
    pub open: bool,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct WidgetEditState {
    pub text: String,
    pub cursor_byte_index: usize,
    pub selection_anchor_byte_index: Option<usize>,
    pub composing: bool,
}

#[derive(Debug, Clone, PartialEq)]
pub enum WidgetStateValue {
    Focus(WidgetFocusState),
    Hover(WidgetHoverState),
    Pressed(WidgetPressedState),
    Overlay(WidgetOverlayState),
    Scroll(ScrollState),
    Animation(AnimationState),
    Edit(WidgetEditState),
    Custom { kind: String, revision: u64 },
}

impl WidgetStateValue {
    pub const fn focus(focused: bool) -> Self {
        Self::Focus(WidgetFocusState { focused })
    }

    pub const fn hover(hovered: bool) -> Self {
        Self::Hover(WidgetHoverState { hovered })
    }

    pub const fn pressed(pressed: bool) -> Self {
        Self::Pressed(WidgetPressedState { pressed })
    }

    pub const fn overlay(open: bool) -> Self {
        Self::Overlay(WidgetOverlayState { open })
    }

    pub fn edit(text: impl Into<String>, cursor_byte_index: usize) -> Self {
        Self::Edit(WidgetEditState {
            text: text.into(),
            cursor_byte_index,
            selection_anchor_byte_index: None,
            composing: false,
        })
    }

    pub fn custom(kind: impl Into<String>, revision: u64) -> Self {
        Self::Custom {
            kind: kind.into(),
            revision,
        }
    }

    pub fn kind(&self) -> WidgetStateSlotKind {
        match self {
            Self::Focus(_) => WidgetStateSlotKind::Focus,
            Self::Hover(_) => WidgetStateSlotKind::Hover,
            Self::Pressed(_) => WidgetStateSlotKind::Pressed,
            Self::Overlay(_) => WidgetStateSlotKind::Overlay,
            Self::Scroll(_) => WidgetStateSlotKind::Scroll,
            Self::Animation(_) => WidgetStateSlotKind::Animation,
            Self::Edit(_) => WidgetStateSlotKind::Edit,
            Self::Custom { kind, .. } => WidgetStateSlotKind::Custom(kind.clone()),
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct RetainedWidgetStateEntry {
    pub key: WidgetStateKey,
    pub descriptor: WidgetStateSlotDescriptor,
    pub value: WidgetStateValue,
    pub created_generation: u64,
    pub updated_generation: u64,
    pub last_seen_generation: u64,
    pub stale_since_generation: Option<u64>,
    pub keepalive: bool,
    pub revision: u64,
}

impl RetainedWidgetStateEntry {
    fn new(
        key: WidgetStateKey,
        descriptor: WidgetStateSlotDescriptor,
        value: WidgetStateValue,
        generation: u64,
    ) -> Self {
        Self {
            key,
            descriptor,
            value,
            created_generation: generation,
            updated_generation: generation,
            last_seen_generation: generation,
            stale_since_generation: None,
            keepalive: false,
            revision: 0,
        }
    }

    pub const fn is_stale(&self) -> bool {
        self.stale_since_generation.is_some()
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WidgetStateRetention {
    pub max_stale_generations: u64,
    pub max_entry_age_generations: Option<u64>,
}

impl WidgetStateRetention {
    pub const fn new(max_stale_generations: u64) -> Self {
        Self {
            max_stale_generations,
            max_entry_age_generations: None,
        }
    }

    pub const fn with_max_entry_age_generations(mut self, max_age: u64) -> Self {
        self.max_entry_age_generations = Some(max_age);
        self
    }
}

impl Default for WidgetStateRetention {
    fn default() -> Self {
        Self::new(2)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum WidgetStateLifecycleOutcome {
    Created,
    Reused,
    Expired,
    Orphaned,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WidgetStateLifecycleItem {
    pub key: WidgetStateKey,
    pub outcome: WidgetStateLifecycleOutcome,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct WidgetStateLifecycleReport {
    pub generation: u64,
    pub created: Vec<WidgetStateKey>,
    pub reused: Vec<WidgetStateKey>,
    pub expired: Vec<WidgetStateKey>,
    pub orphaned: Vec<WidgetStateKey>,
}

impl WidgetStateLifecycleReport {
    fn push(&mut self, key: WidgetStateKey, outcome: WidgetStateLifecycleOutcome) {
        match outcome {
            WidgetStateLifecycleOutcome::Created => self.created.push(key),
            WidgetStateLifecycleOutcome::Reused => self.reused.push(key),
            WidgetStateLifecycleOutcome::Expired => self.expired.push(key),
            WidgetStateLifecycleOutcome::Orphaned => self.orphaned.push(key),
        }
    }

    pub fn items(&self) -> Vec<WidgetStateLifecycleItem> {
        self.created
            .iter()
            .cloned()
            .map(|key| WidgetStateLifecycleItem {
                key,
                outcome: WidgetStateLifecycleOutcome::Created,
            })
            .chain(
                self.reused
                    .iter()
                    .cloned()
                    .map(|key| WidgetStateLifecycleItem {
                        key,
                        outcome: WidgetStateLifecycleOutcome::Reused,
                    }),
            )
            .chain(
                self.expired
                    .iter()
                    .cloned()
                    .map(|key| WidgetStateLifecycleItem {
                        key,
                        outcome: WidgetStateLifecycleOutcome::Expired,
                    }),
            )
            .chain(
                self.orphaned
                    .iter()
                    .cloned()
                    .map(|key| WidgetStateLifecycleItem {
                        key,
                        outcome: WidgetStateLifecycleOutcome::Orphaned,
                    }),
            )
            .collect()
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WidgetStateError {
    SlotKindMismatch {
        key: Box<WidgetStateKey>,
        expected: WidgetStateSlotKind,
        actual: WidgetStateSlotKind,
    },
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WidgetStateUpdateReport {
    pub key: WidgetStateKey,
    pub changed: bool,
    pub created: bool,
    pub dirty_flags: DirtyFlags,
    pub invalidations: Vec<RuntimeInvalidation>,
}

impl WidgetStateUpdateReport {
    fn unchanged(key: WidgetStateKey, created: bool) -> Self {
        Self {
            key,
            changed: false,
            created,
            dirty_flags: DirtyFlags::NONE,
            invalidations: Vec::new(),
        }
    }

    fn changed(key: WidgetStateKey, created: bool, descriptor: &WidgetStateSlotDescriptor) -> Self {
        let detail = format!(
            "widget state changed: widget={} slot={}",
            key.widget.id, key.slot
        );
        Self {
            key,
            changed: true,
            created,
            dirty_flags: descriptor.dirty_flags,
            invalidations: vec![
                RuntimeInvalidation::new(descriptor.invalidation_reason).detail(detail)
            ],
        }
    }
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct WidgetStateInvalidationSummary {
    pub dirty_flags: DirtyFlags,
    pub invalidations: Vec<RuntimeInvalidation>,
}

impl WidgetStateInvalidationSummary {
    pub fn push(&mut self, report: &WidgetStateUpdateReport) {
        self.dirty_flags = self.dirty_flags.union(report.dirty_flags);
        self.invalidations.extend(report.invalidations.clone());
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct RetainedWidgetStateStore {
    generation: u64,
    retention: WidgetStateRetention,
    entries: HashMap<WidgetStateKey, RetainedWidgetStateEntry>,
    last_lifecycle_report: WidgetStateLifecycleReport,
}

impl RetainedWidgetStateStore {
    pub fn new(retention: WidgetStateRetention) -> Self {
        Self {
            generation: 0,
            retention,
            entries: HashMap::new(),
            last_lifecycle_report: WidgetStateLifecycleReport::default(),
        }
    }

    pub fn generation(&self) -> u64 {
        self.generation
    }

    pub fn retention(&self) -> WidgetStateRetention {
        self.retention
    }

    pub fn set_retention(&mut self, retention: WidgetStateRetention) {
        self.retention = retention;
    }

    pub fn len(&self) -> usize {
        self.entries.len()
    }

    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    pub fn entries(&self) -> impl Iterator<Item = &RetainedWidgetStateEntry> {
        self.entries.values()
    }

    pub fn last_lifecycle_report(&self) -> &WidgetStateLifecycleReport {
        &self.last_lifecycle_report
    }

    pub fn begin_frame(
        &mut self,
        seen_widgets: impl IntoIterator<Item = WidgetKey>,
    ) -> WidgetStateLifecycleReport {
        self.generation = self.generation.wrapping_add(1);
        let seen_widgets: HashSet<WidgetKey> = seen_widgets.into_iter().collect();
        let mut report = WidgetStateLifecycleReport {
            generation: self.generation,
            ..WidgetStateLifecycleReport::default()
        };
        let mut expired = Vec::new();

        for (key, entry) in &mut self.entries {
            if seen_widgets.contains(&key.widget) {
                entry.last_seen_generation = self.generation;
                entry.stale_since_generation = None;
                report.push(key.clone(), WidgetStateLifecycleOutcome::Reused);
                continue;
            }

            if entry.stale_since_generation.is_none() {
                entry.stale_since_generation = Some(self.generation);
                report.push(key.clone(), WidgetStateLifecycleOutcome::Orphaned);
            }

            if !entry.keepalive && entry_expired(entry, self.generation, self.retention) {
                expired.push(key.clone());
            }
        }

        for key in expired {
            self.entries.remove(&key);
            report.push(key, WidgetStateLifecycleOutcome::Expired);
        }

        self.last_lifecycle_report = report.clone();
        report
    }

    pub fn get(&self, key: &WidgetStateKey) -> Option<&RetainedWidgetStateEntry> {
        self.entries.get(key)
    }

    pub fn value(
        &self,
        key: &WidgetStateKey,
        descriptor: &WidgetStateSlotDescriptor,
    ) -> Result<Option<&WidgetStateValue>, WidgetStateError> {
        let Some(entry) = self.entries.get(key) else {
            return Ok(None);
        };
        validate_slot_kind(key, &entry.descriptor.kind, &descriptor.kind)?;
        Ok(Some(&entry.value))
    }

    pub fn set_keepalive(&mut self, key: &WidgetStateKey, keepalive: bool) -> bool {
        if let Some(entry) = self.entries.get_mut(key) {
            entry.keepalive = keepalive;
            true
        } else {
            false
        }
    }

    pub fn ensure(
        &mut self,
        widget: WidgetKey,
        descriptor: WidgetStateSlotDescriptor,
        default_value: WidgetStateValue,
    ) -> Result<WidgetStateUpdateReport, WidgetStateError> {
        validate_slot_kind_for_value(
            &WidgetStateKey::new(widget.clone(), descriptor.id.clone()),
            &descriptor.kind,
            &default_value,
        )?;

        let key = WidgetStateKey::new(widget, descriptor.id.clone());
        let Some(entry) = self.entries.get_mut(&key) else {
            let entry = RetainedWidgetStateEntry::new(
                key.clone(),
                descriptor.clone(),
                default_value,
                self.generation,
            );
            self.entries.insert(key.clone(), entry);
            self.last_lifecycle_report
                .push(key.clone(), WidgetStateLifecycleOutcome::Created);
            return Ok(WidgetStateUpdateReport::changed(key, true, &descriptor));
        };

        validate_slot_kind(&key, &entry.descriptor.kind, &descriptor.kind)?;
        entry.last_seen_generation = self.generation;
        entry.stale_since_generation = None;
        Ok(WidgetStateUpdateReport::unchanged(key, false))
    }

    pub fn set(
        &mut self,
        widget: WidgetKey,
        descriptor: WidgetStateSlotDescriptor,
        value: WidgetStateValue,
    ) -> Result<WidgetStateUpdateReport, WidgetStateError> {
        validate_slot_kind_for_value(
            &WidgetStateKey::new(widget.clone(), descriptor.id.clone()),
            &descriptor.kind,
            &value,
        )?;

        let key = WidgetStateKey::new(widget, descriptor.id.clone());
        let Some(entry) = self.entries.get_mut(&key) else {
            let entry = RetainedWidgetStateEntry::new(
                key.clone(),
                descriptor.clone(),
                value,
                self.generation,
            );
            self.entries.insert(key.clone(), entry);
            self.last_lifecycle_report
                .push(key.clone(), WidgetStateLifecycleOutcome::Created);
            return Ok(WidgetStateUpdateReport::changed(key, true, &descriptor));
        };

        validate_slot_kind(&key, &entry.descriptor.kind, &descriptor.kind)?;

        entry.last_seen_generation = self.generation;
        entry.stale_since_generation = None;
        if entry.value == value {
            return Ok(WidgetStateUpdateReport::unchanged(key, false));
        }

        entry.value = value;
        entry.descriptor = descriptor.clone();
        entry.updated_generation = self.generation;
        entry.revision = entry.revision.saturating_add(1);
        Ok(WidgetStateUpdateReport::changed(key, false, &descriptor))
    }

    pub fn invalidation_summary<'a>(
        reports: impl IntoIterator<Item = &'a WidgetStateUpdateReport>,
    ) -> WidgetStateInvalidationSummary {
        let mut summary = WidgetStateInvalidationSummary::default();
        for report in reports {
            summary.push(report);
        }
        summary
    }
}

impl Default for RetainedWidgetStateStore {
    fn default() -> Self {
        Self::new(WidgetStateRetention::default())
    }
}

fn dirty_flags_for_slot_kind(kind: &WidgetStateSlotKind) -> DirtyFlags {
    match kind {
        WidgetStateSlotKind::Focus
        | WidgetStateSlotKind::Hover
        | WidgetStateSlotKind::Pressed
        | WidgetStateSlotKind::Overlay
        | WidgetStateSlotKind::Scroll
        | WidgetStateSlotKind::Edit => DirtyFlags {
            input: true,
            paint: true,
            ..DirtyFlags::NONE
        },
        WidgetStateSlotKind::Animation => DirtyFlags {
            paint: true,
            ..DirtyFlags::NONE
        },
        WidgetStateSlotKind::Custom(_) => DirtyFlags {
            layout: true,
            paint: true,
            ..DirtyFlags::NONE
        },
    }
}

fn invalidation_reason_for_slot_kind(kind: &WidgetStateSlotKind) -> RuntimeInvalidationReason {
    match kind {
        WidgetStateSlotKind::Animation => RuntimeInvalidationReason::Animation,
        WidgetStateSlotKind::Custom(_) => RuntimeInvalidationReason::Explicit,
        _ => RuntimeInvalidationReason::Input,
    }
}

fn entry_expired(
    entry: &RetainedWidgetStateEntry,
    generation: u64,
    retention: WidgetStateRetention,
) -> bool {
    let stale_expired = entry.stale_since_generation.is_some_and(|stale_since| {
        generation.saturating_sub(stale_since) > retention.max_stale_generations
    });
    let age_expired = retention
        .max_entry_age_generations
        .is_some_and(|max_age| generation.saturating_sub(entry.created_generation) > max_age);
    stale_expired || age_expired
}

fn validate_slot_kind(
    key: &WidgetStateKey,
    expected: &WidgetStateSlotKind,
    actual: &WidgetStateSlotKind,
) -> Result<(), WidgetStateError> {
    if expected == actual {
        Ok(())
    } else {
        Err(WidgetStateError::SlotKindMismatch {
            key: Box::new(key.clone()),
            expected: expected.clone(),
            actual: actual.clone(),
        })
    }
}

fn validate_slot_kind_for_value(
    key: &WidgetStateKey,
    expected: &WidgetStateSlotKind,
    value: &WidgetStateValue,
) -> Result<(), WidgetStateError> {
    validate_slot_kind(key, expected, &value.kind())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{runtime::RuntimeWindowId, ScrollAxes, UiPoint};

    fn widget(id: &str) -> WidgetKey {
        WidgetKey::document("doc-a", id)
    }

    fn focus_key(id: &str) -> WidgetStateKey {
        WidgetStateKey::new(widget(id), "focus")
    }

    #[test]
    fn state_preserves_value_across_document_rebuilds() {
        let mut store = RetainedWidgetStateStore::default();
        let field = widget("field");

        store.begin_frame([field.clone()]);
        store
            .set(
                field.clone(),
                WidgetStateSlotDescriptor::focus(),
                WidgetStateValue::focus(true),
            )
            .unwrap();
        let ensured = store
            .ensure(
                field.clone(),
                WidgetStateSlotDescriptor::focus(),
                WidgetStateValue::focus(false),
            )
            .unwrap();
        assert!(!ensured.changed);

        let report = store.begin_frame([field]);
        assert_eq!(report.reused, vec![focus_key("field")]);
        assert_eq!(
            store.get(&focus_key("field")).unwrap().value,
            WidgetStateValue::focus(true)
        );
    }

    #[test]
    fn removed_widgets_are_orphaned_then_expired() {
        let mut store = RetainedWidgetStateStore::new(WidgetStateRetention::new(1));
        let field = widget("field");

        store.begin_frame([field.clone()]);
        store
            .set(
                field,
                WidgetStateSlotDescriptor::hover(),
                WidgetStateValue::hover(true),
            )
            .unwrap();

        let hover_key = WidgetStateKey::new(widget("field"), "hover");
        let orphaned = store.begin_frame([]);
        assert_eq!(orphaned.orphaned, vec![hover_key.clone()]);
        assert!(store.get(&hover_key).unwrap().is_stale());

        store.begin_frame([]);
        let expired = store.begin_frame([]);
        assert_eq!(expired.expired, vec![hover_key.clone()]);
        assert!(store.get(&hover_key).is_none());
    }

    #[test]
    fn keepalive_entries_survive_missing_frames() {
        let mut store = RetainedWidgetStateStore::new(WidgetStateRetention::new(0));
        let popover = widget("popover");
        let overlay_key = WidgetStateKey::new(popover.clone(), "overlay");

        store.begin_frame([popover.clone()]);
        store
            .set(
                popover,
                WidgetStateSlotDescriptor::overlay(),
                WidgetStateValue::overlay(true),
            )
            .unwrap();
        assert!(store.set_keepalive(&overlay_key, true));

        let orphaned = store.begin_frame([]);
        assert_eq!(orphaned.orphaned, vec![overlay_key.clone()]);
        let expired = store.begin_frame([]);
        assert!(expired.expired.is_empty());
        assert_eq!(
            store.get(&overlay_key).unwrap().value,
            WidgetStateValue::overlay(true)
        );
    }

    #[test]
    fn scopes_isolate_matching_widget_ids() {
        let mut store = RetainedWidgetStateStore::default();
        let document_widget = WidgetKey::document("doc-a", "shared");
        let window_widget = WidgetKey::window(RuntimeWindowId::new("main"), "shared");

        store.begin_frame([document_widget.clone(), window_widget.clone()]);
        store
            .set(
                document_widget.clone(),
                WidgetStateSlotDescriptor::scroll(),
                WidgetStateValue::Scroll(ScrollState {
                    axes: ScrollAxes::VERTICAL,
                    offset: UiPoint::new(0.0, 24.0),
                    viewport_size: crate::UiSize::new(100.0, 100.0),
                    content_size: crate::UiSize::new(100.0, 500.0),
                }),
            )
            .unwrap();
        store
            .set(
                window_widget.clone(),
                WidgetStateSlotDescriptor::scroll(),
                WidgetStateValue::Scroll(ScrollState {
                    axes: ScrollAxes::VERTICAL,
                    offset: UiPoint::new(0.0, 88.0),
                    viewport_size: crate::UiSize::new(100.0, 100.0),
                    content_size: crate::UiSize::new(100.0, 500.0),
                }),
            )
            .unwrap();

        let document_key = WidgetStateKey::new(document_widget, "scroll");
        let window_key = WidgetStateKey::new(window_widget, "scroll");
        assert_ne!(
            store.get(&document_key).unwrap().value,
            store.get(&window_key).unwrap().value
        );
    }

    #[test]
    fn typed_slot_mismatch_is_rejected() {
        let mut store = RetainedWidgetStateStore::default();
        let field = widget("field");
        let key = focus_key("field");

        store.begin_frame([field.clone()]);
        store
            .set(
                field.clone(),
                WidgetStateSlotDescriptor::focus(),
                WidgetStateValue::focus(true),
            )
            .unwrap();

        let err = store
            .set(
                field,
                WidgetStateSlotDescriptor::focus(),
                WidgetStateValue::hover(true),
            )
            .unwrap_err();
        assert_eq!(
            err,
            WidgetStateError::SlotKindMismatch {
                key: Box::new(key.clone()),
                expected: WidgetStateSlotKind::Focus,
                actual: WidgetStateSlotKind::Hover,
            }
        );
        assert_eq!(
            store.get(&key).unwrap().value,
            WidgetStateValue::focus(true)
        );
    }

    #[test]
    fn changed_state_reports_dirty_flags_and_runtime_invalidation() {
        let mut store = RetainedWidgetStateStore::default();
        let button = widget("button");

        store.begin_frame([button.clone()]);
        let first = store
            .set(
                button.clone(),
                WidgetStateSlotDescriptor::pressed(),
                WidgetStateValue::pressed(false),
            )
            .unwrap();
        let second = store
            .set(
                button.clone(),
                WidgetStateSlotDescriptor::pressed(),
                WidgetStateValue::pressed(true),
            )
            .unwrap();
        let unchanged = store
            .set(
                button,
                WidgetStateSlotDescriptor::pressed(),
                WidgetStateValue::pressed(true),
            )
            .unwrap();

        assert!(first.created);
        assert!(second.changed);
        assert!(second.dirty_flags.input);
        assert!(second.dirty_flags.paint);
        assert_eq!(
            second.invalidations[0].reason,
            RuntimeInvalidationReason::Input
        );
        assert!(!unchanged.changed);
        assert!(unchanged.invalidations.is_empty());

        let summary = RetainedWidgetStateStore::invalidation_summary([&second, &unchanged]);
        assert!(summary.dirty_flags.input);
        assert_eq!(summary.invalidations.len(), 1);
    }
}