vertigo 0.12.0

Reactive Real-DOM library with SSR 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
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
use std::{collections::HashSet, rc::Rc};

use crate::{
    Computed, DomNode, JsJsonDeserialize, RequestResponse, Resource, Value,
    computed::{
        context::Context,
        struct_mut::{HashMapMut, ValueMut},
    },
    driver_module::api::api_fetch,
    fetch::request_builder::{RequestBody, RequestBuilder},
    get_driver,
    render::collection::CollectionKey,
    transaction,
};

/// Outcome of parsing a response body: `None` to ignore the response (e.g. wrong
/// status), `Some(Ok(value))` on success, or `Some(Err(message))` on a parse error.
pub type MapResponse<V> = Option<Result<V, String>>;
/// Builds the [`RequestBuilder`] used to fetch a single item identified by `K`.
pub type ItemRequestCallback<K> = Rc<dyn Fn(&K) -> RequestBuilder>;
/// Parses an HTTP status and body into a [`MapResponse`] for a value of type `V`.
pub type MapResponseCallback<V> = Rc<dyn Fn(u32, RequestBody) -> MapResponse<V>>;
/// A single list element exposed as its own reactive [`Computed`], yielding
/// `None` when the item is absent or filtered out. See [`LazyListCache::granular`].
pub type GranularItem<T> = Computed<Option<T>>;
/// The result of [`LazyListCache::granular`]: a [`Resource`] wrapping the list of
/// per-item reactive [`GranularItem`]s.
pub type GranularList<T> = Resource<Rc<Vec<GranularItem<T>>>>;

fn get_unique_id() -> u64 {
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(1);
    COUNTER.fetch_add(1, Ordering::Relaxed)
}

/// Per-item storage holding the server-provided original and an optional optimistic override.
pub struct ListItem<V: Clone + PartialEq + 'static> {
    pub original: Value<V>,
    /// `None` = no active override;
    /// `Some(None)` = optimistically removed;
    /// `Some(Some(v))` = optimistic override in effect.
    pub override_val: Value<Option<Option<V>>>,
}

impl<V: Clone + PartialEq + 'static> ListItem<V> {
    fn new(value: V) -> Self {
        ListItem {
            original: Value::new(value),
            override_val: Value::new(None),
        }
    }
}

#[derive(Clone, PartialEq)]
enum ListCacheState {
    Uninitialized,
    Loading,
    Ready,
    Error(String),
}

/// A lazy cache for lists that stores items in an ordered dict `T::Key -> ListItem<T::Value>`.
///
/// Each item has a reactive `original` (from the server) and an optional `override_val`
/// (from [`optimistically_set_item`](LazyListCache::optimistically_set_item)). All reads —
/// [`get`](LazyListCache::get), [`granular`](LazyListCache::granular) and
/// [`get_by_key`](LazyListCache::get_by_key) — are override-aware: they return the override
/// when active, otherwise the server-confirmed original.
///
/// `T` is a marker type implementing [`CollectionKey`].
///
/// See [Lazy List](https://github.com/vertigo-web/vertigo/blob/optimistic-update/demo/app/src/app/lazy_list/state.rs) example in the demo.
///
/// ## State transitions
///
/// ```text
/// UPDATE FLOW -- editing a server-confirmed item (key=2)
///
///  ┌────────────────────────────────┐
///  │ keys: ..2..                    │
///  │ orig=v0, override=None         │
///  │ placeholder: empty             │
///  └────────────────────────────────┘
//////                  │ optimistically_set_item
//////  ┌────────────────────────────────┐
///  │ keys: ..2..                    │
///  │ orig=v0, override=Some(v1)     │
///  │ placeholder: empty             │
///  └────────────────────────────────┘
///          │                   │
///    update_item            rollback
///     (success)              (failure)
///          │                   │
///          ▼                   ▼
///  ┌──────────────────┐  ┌──────────────────┐
///  │ keys: ..2..      │  │ keys: ..2..      │
///  │ orig=v1          │  │ orig=v0          │
///  │ override=None    │  │ override=None    │
///  │ placeholder: -   │  │ placeholder: -   │
///  └──────────────────┘  └──────────────────┘
///
///
/// CREATE FLOW -- new item, temp id=0, server assigns id=42
///
///  ┌────────────────────────────────┐
///  │ keys: 1 2 3                    │
///  │ placeholder: empty             │
///  └────────────────────────────────┘
//////                  │ optimistically_set_item
//////  ┌──────────────────────────────────────┐
///  │ keys: 1 2 3 0                        │
///  │ orig=draft, override=Some(draft)     │
///  │ placeholder: 0                       │
///  └──────────────────────────────────────┘
///          │                            │
///  update_item_with_old_key         rollback
///        (success)                  (failure)
///          │                            │
///          ▼                            ▼
///  ┌──────────────────────┐  ┌──────────────────┐
///  │ keys: 1 2 3 42       │  │ keys: 1 2 3      │
///  │ orig=saved           │  │ placeholder: -   │
///  │ override=None        │  └──────────────────┘
///  │ placeholder: -       │
///  └──────────────────────┘
/// ```
pub struct LazyListCache<T: CollectionKey + 'static> {
    id: u64,
    state: Value<ListCacheState>,
    /// Insertion-ordered list of currently-visible keys: keys from the last server response plus
    /// any keys that were inserted optimistically and have not been rolled back. Reactive, so
    /// consumers (e.g. [`granular`](LazyListCache::granular)) re-evaluate when items are added,
    /// removed, or re-keyed via mutation methods.
    keys: Value<Vec<T::Key>>,
    /// Per-item reactive data, keyed for O(1) lookup.
    items: Rc<HashMapMut<T::Key, ListItem<T::Value>>>,

    /// Request for the list
    list_request: Rc<RequestBuilder>,
    /// If request for the list is queued
    list_queued: Rc<ValueMut<bool>>,
    /// Map response for the list
    list_map_response: MapResponseCallback<Vec<T::Value>>,

    /// Request for the items
    item_request: Option<ItemRequestCallback<T::Key>>,
    /// If request for particular item is queued
    item_queued: Rc<HashMapMut<T::Key, ()>>,
    /// Map response for the items
    item_map_response: Option<MapResponseCallback<T::Value>>,

    /// Keys that exist only as optimistic placeholders (not yet confirmed by the server).
    /// [`rollback`](LazyListCache::rollback) fully removes these instead of merely clearing
    /// the override, so a failed create doesn't leave its draft visible in the list.
    optimistic_placeholders: Rc<HashMapMut<T::Key, ()>>,
}

impl<T: CollectionKey> std::fmt::Debug for LazyListCache<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("LazyListCache")
            .field("id", &self.id)
            .finish()
    }
}

impl<T: CollectionKey> Clone for LazyListCache<T> {
    fn clone(&self) -> Self {
        LazyListCache {
            id: self.id,
            state: self.state.clone(),
            keys: self.keys.clone(),
            items: self.items.clone(),
            list_queued: self.list_queued.clone(),
            list_request: self.list_request.clone(),
            list_map_response: self.list_map_response.clone(),
            item_request: self.item_request.clone(),
            item_map_response: self.item_map_response.clone(),
            item_queued: self.item_queued.clone(),
            optimistic_placeholders: self.optimistic_placeholders.clone(),
        }
    }
}

impl<T: CollectionKey> PartialEq for LazyListCache<T> {
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id
    }
}

impl<T: CollectionKey> LazyListCache<T> {
    /// Create a cache from a list-endpoint `request` and a `map_response` parser.
    ///
    /// The cache starts `Uninitialized` and fetches lazily on the first read
    /// ([`get`](Self::get) / [`get_by_key`](Self::get_by_key) / [`granular`](Self::granular)).
    /// Usually constructed via [`RequestBuilder::lazy_list_cache`](crate::RequestBuilder::lazy_list_cache);
    /// add per-item fetching with [`with_item_fetch`](Self::with_item_fetch).
    pub fn new(
        request: RequestBuilder,
        map_response: impl Fn(u32, RequestBody) -> MapResponse<Vec<T::Value>> + 'static,
    ) -> Self {
        LazyListCache {
            id: get_unique_id(),
            state: Value::new(ListCacheState::Uninitialized),
            keys: Value::new(Vec::new()),
            items: Rc::new(HashMapMut::new()),
            list_queued: Rc::new(ValueMut::new(false)),
            list_request: Rc::new(request),
            list_map_response: Rc::new(map_response),
            item_request: None,
            item_map_response: None,
            item_queued: Rc::new(HashMapMut::new()),
            optimistic_placeholders: Rc::new(HashMapMut::new()),
        }
    }

    /// Configure per-item fetching. Returns `self` for chaining.
    ///
    /// `item_request` builds a `RequestBuilder` for a given key (e.g. `GET /items/{id}`).
    /// `item_map_response` parses the response into a single `T::Value`.
    pub fn with_item_fetch(
        self,
        item_request: impl Fn(&T::Key) -> RequestBuilder + 'static,
        item_map_response: impl Fn(u32, RequestBody) -> MapResponse<T::Value> + 'static,
    ) -> Self {
        LazyListCache {
            item_request: Some(Rc::new(item_request)),
            item_map_response: Some(Rc::new(item_map_response)),
            ..self
        }
    }

    /// Fetch a single item by key and update its `original` value in the cache.
    /// No-op if per-item fetching was not configured via [`with_item_fetch`](Self::with_item_fetch).
    /// Deduplicates in-flight requests for the same key.
    pub fn fetch_item(&self, key: T::Key) {
        let (req_fn, resp_fn) = match (&self.item_request, &self.item_map_response) {
            (Some(r), Some(m)) => (r.clone(), m.clone()),
            _ => return,
        };

        if self.item_queued.get_and_map(&key, |_| ()).is_some() {
            return;
        }
        self.item_queued.insert(key.clone(), ());

        let self_clone = self.clone();
        get_driver().spawn(async move {
            let request = transaction(|context| req_fn(&key).to_request_context(context));
            let result = api_fetch().fetch(request.clone()).await;
            let new_value = RequestResponse::new(request, result).into(resp_fn.as_ref());

            if let Ok(item) = new_value {
                let item_key = T::get_key(&item);
                if self_clone
                    .items
                    .must_change(&item_key, |list_item| list_item.original.set(item.clone()))
                    .is_none()
                {
                    // Item not yet in cache — insert it and append to key order.
                    self_clone
                        .items
                        .insert(item_key.clone(), ListItem::new(item));
                    self_clone.keys.change(|current_keys| {
                        if !current_keys.contains(&item_key) {
                            current_keys.push(item_key);
                        }
                    });
                }
            }

            self_clone.item_queued.retain(|k, _| *k != key);
        });
    }

    /// Get the full list of items in insertion order, **as the user currently sees it**:
    /// optimistic overrides are applied.
    ///
    /// For each item, an active optimistic *edit* replaces the value, an optimistic *insert*
    /// appears, and an optimistic *removal* drops the row from the list entirely (so the deletion
    /// is reflected immediately, before [`remove_item`](Self::remove_item) confirms it). Items
    /// without an active override fall back to their server-confirmed `original` — matching
    /// [`get_by_key`](Self::get_by_key) applied across the whole list.
    pub fn get(&self, context: &Context) -> Resource<Rc<Vec<T::Value>>> {
        let state = self.state.get(context);

        if state == ListCacheState::Uninitialized && !self.list_queued.get() {
            self.update(false, false);
        }

        match state {
            ListCacheState::Uninitialized | ListCacheState::Loading => Resource::Loading,
            ListCacheState::Error(e) => Resource::Error(e),
            ListCacheState::Ready => {
                let keys = self.keys.get(context);
                let list = keys
                    .iter()
                    .filter_map(|k| {
                        self.items
                            .get_and_map(k, |item| {
                                match item.override_val.get(context) {
                                    // Active override: edit/insert -> value, removal -> drop the row.
                                    Some(override_val) => override_val,
                                    // No override: fall back to the server-confirmed original.
                                    None => Some(item.original.get(context)),
                                }
                            })
                            // outer Option: key missing; inner Option: optimistically removed.
                            .flatten()
                    })
                    .collect::<Vec<_>>();
                Resource::Ready(Rc::new(list))
            }
        }
    }

    /// Get the list as individually reactive [`Computed`] items, each yielding `Option<T::Value>`,
    /// **as the user currently sees it**: optimistic overrides are applied.
    ///
    /// Unlike [`get`](Self::get), which returns the whole list as a single reactive unit, this
    /// method wraps every element in its own [`Computed`]. Subscribers re-evaluate only for the
    /// specific items that changed, making it efficient for large lists with sparse updates.
    ///
    /// Each item's [`Computed`] reflects optimistic state: an active edit/insert yields the
    /// override value, and an optimistically *removed* row yields `None` so it disappears from the
    /// rendered list (mirroring [`get`](Self::get) / [`get_by_key`](Self::get_by_key)).
    ///
    /// When `filter` is `Some`, each `Computed` applies the predicate and returns `None` for
    /// items that do not pass, allowing the UI to hide or skip them without recomputing the rest.
    /// The override and the filter compose — a removed row is `None` regardless of the filter, and
    /// a surviving row is then subject to the predicate.
    pub fn granular<F>(&self, ctx: &Context, filter: Option<F>) -> GranularList<T::Value>
    where
        F: Fn(&T::Value) -> bool + Clone + 'static,
    {
        let state = self.state.get(ctx);

        if state == ListCacheState::Uninitialized && !self.list_queued.get() {
            self.update(false, false);
        }

        match state {
            ListCacheState::Uninitialized | ListCacheState::Loading => Resource::Loading,
            ListCacheState::Error(e) => Resource::Error(e),
            ListCacheState::Ready => {
                let keys = self.keys.get(ctx);
                let items = self.items.clone();
                let list = keys
                    .into_iter()
                    .map(|k| {
                        let items = items.clone();
                        let filter = filter.clone();
                        Computed::from(move |ctx| {
                            let item = items
                                .get_and_map(&k, |item| match item.override_val.get(ctx) {
                                    // Active override: edit/insert -> value, removal -> None.
                                    Some(override_val) => override_val,
                                    // No override: fall back to the server original.
                                    None => Some(item.original.get(ctx)),
                                })
                                // outer Option: key missing; inner Option: removed / no value.
                                .flatten();
                            if let Some(filter) = &filter {
                                item.filter(filter)
                            } else {
                                item
                            }
                        })
                    })
                    .collect::<Vec<_>>();
                Resource::Ready(Rc::new(list))
            }
        }
    }

    /// Get one item by key. Returns the active override when set, otherwise the original.
    /// Returns `Resource::Loading` when the list has not yet loaded (unless an override is set).
    pub fn get_by_key(&self, context: &Context, key: &T::Key) -> Resource<Rc<T::Value>> {
        let state = self.state.get(context);

        if state == ListCacheState::Uninitialized && !self.list_queued.get() {
            self.update(false, false);
        }

        // Override wins regardless of fetch state.
        match self
            .items
            .get_and_map(key, |item| item.override_val.get(context))
        {
            Some(Some(Some(v))) => return Resource::Ready(Rc::new(v)),
            Some(Some(None)) => return Resource::Loading,
            _ => (),
        }

        match state {
            ListCacheState::Uninitialized | ListCacheState::Loading => Resource::Loading,
            ListCacheState::Error(e) => Resource::Error(e),
            ListCacheState::Ready => {
                match self
                    .items
                    .get_and_map(key, |item| item.original.get(context))
                {
                    Some(v) => Resource::Ready(Rc::new(v)),
                    None => Resource::Error(format!("key {key:?} not found")),
                }
            }
        }
    }

    /// Clear the cache so it will refetch on next access.
    pub fn forget(&self) {
        self.state.set(ListCacheState::Uninitialized);
    }

    /// Force a refetch now.
    pub fn force_update(&self, with_loading: bool) {
        self.update(with_loading, true);
    }

    /// Insert or update an optimistic override for one item. Does not modify the server-originated data.
    /// If the key is not yet in the dict (e.g. cache is still loading or this is a brand-new item),
    /// a placeholder entry is created and the key is appended to the ordered key list so the item
    /// becomes immediately visible to consumers iterating the list.
    pub fn optimistically_set_item(&self, item: T::Value) {
        let key = T::get_key(&item);
        let updated = self.items.must_change(&key, |list_item| {
            list_item.override_val.set(Some(Some(item.clone())))
        });
        if updated.is_none() {
            // Key not yet loaded from server — create a placeholder and register the key.
            let list_item = ListItem {
                original: Value::new(item.clone()),
                override_val: Value::new(Some(Some(item))),
            };
            self.items.insert(key.clone(), list_item);
            self.optimistic_placeholders.insert(key.clone(), ());
            self.keys.change(|current_keys| {
                if !current_keys.contains(&key) {
                    current_keys.push(key);
                }
            });
        }
    }

    /// Optimistically mark an item as removed. The entry stays in the cache but
    /// [`get_by_key`](Self::get_by_key) reports it as `Resource::Loading` until either
    /// [`remove_item`](Self::remove_item) confirms the deletion or [`rollback`](Self::rollback)
    /// reverts the override. No-op if the key is not in the cache.
    pub fn optimistically_remove_item(&self, key: &T::Key) {
        self.items
            .must_change(key, |list_item| list_item.override_val.set(Some(None)));
    }

    /// Provide a new item (f. ex. returned from a create or update request) and remove the override.
    /// Always ensures the key is present in the ordered key list so newly-created items become
    /// visible even when an optimistic placeholder was inserted earlier.
    ///
    /// If the server may have assigned a different key than the one used in the optimistic
    /// placeholder (a typical create flow with a temporary client-side id), use
    /// [`update_item_with_old_key`](Self::update_item_with_old_key) instead so the placeholder
    /// gets re-keyed in place rather than leaving an orphan under the old key.
    pub fn update_item(&self, item: T::Value) {
        let key = T::get_key(&item);
        if self
            .items
            .must_change(&key, |list_item| {
                list_item.original.set(item.clone());
                list_item.override_val.set(None);
            })
            .is_none()
        {
            // Key not yet in cache — insert it as a committed original.
            self.items.insert(key.clone(), ListItem::new(item));
        }
        self.optimistic_placeholders.remove(&key);
        self.keys.change(|current_keys| {
            if !current_keys.contains(&key) {
                current_keys.push(key);
            }
        });
    }

    /// Like [`update_item`](Self::update_item), but for cases where the server assigns a different
    /// key than the one used in the optimistic placeholder (typical create flow with a temporary
    /// client-side id). The entry is re-keyed in place: the position of `old_key` in the ordered
    /// key list is preserved, and any optimistic override under `old_key` is cleared.
    ///
    /// If `old_key` and `T::get_key(&item)` are equal this delegates to [`update_item`](Self::update_item).
    pub fn update_item_with_old_key(&self, old_key: &T::Key, item: T::Value) {
        let new_key = T::get_key(&item);
        if &new_key == old_key {
            self.update_item(item);
            return;
        }
        // Drop the placeholder under old_key.
        self.items.remove(old_key);
        self.optimistic_placeholders.remove(old_key);
        // Insert (or update) under the new key.
        if self
            .items
            .must_change(&new_key, |list_item| {
                list_item.original.set(item.clone());
                list_item.override_val.set(None);
            })
            .is_none()
        {
            self.items.insert(new_key.clone(), ListItem::new(item));
        }
        self.optimistic_placeholders.remove(&new_key);
        // Replace old_key with new_key in the ordered keys list, preserving position.
        self.keys.change(|keys| {
            let old_pos = keys.iter().position(|k| k == old_key);
            let already_has_new = keys.contains(&new_key);
            match (old_pos, already_has_new) {
                (Some(pos), false) => keys[pos] = new_key.clone(),
                (Some(pos), true) => {
                    keys.remove(pos);
                }
                (None, false) => keys.push(new_key.clone()),
                (None, true) => {}
            }
        });
    }

    /// Remove a single item from the cache: drops it from `items`, from the ordered key list,
    /// and clears any placeholder marker. Typically called after a successful `DELETE` to confirm
    /// a prior [`optimistically_remove_item`](Self::optimistically_remove_item).
    pub fn remove_item(&self, key: &T::Key) {
        self.items.remove(key);
        self.optimistic_placeholders.remove(key);
        self.keys
            .change(|current_keys| current_keys.retain(|k| k != key));
    }

    /// Commit the current override into the original value without contacting the server.
    ///
    /// - If the override holds a value, it becomes the new `original` and the override is cleared.
    /// - If the override marks the item as removed (`Some(None)`), the entry is dropped from
    ///   both `items` and the ordered key list.
    /// - If there is no active override, this is a no-op.
    ///
    /// Either way the placeholder marker is cleared, since a successful commit is treated as
    /// confirmation — a subsequent [`rollback`](Self::rollback) on the same key will only clear
    /// overrides, not delete the row.
    pub fn commit(&self, key: &T::Key) {
        self.items.must_change(key, |list_item| {
            transaction(|ctx| {
                if let Some(override_val) = list_item.override_val.get(ctx) {
                    if let Some(override_val) = override_val {
                        list_item.original.set(override_val.clone());
                        list_item.override_val.set(None);
                    } else {
                        self.items.remove(key);
                        self.keys.change(|keys| keys.retain(|k| k != key));
                    }
                }
            });
        });
        // Treat a successful commit as confirmation, dropping the placeholder marker.
        self.optimistic_placeholders.remove(key);
    }

    /// Discard the optimistic override for a key, restoring the original server value.
    /// If the key was inserted purely optimistically (no server confirmation has ever been
    /// recorded), the entry is fully removed from the list — both `items` and `keys` — so a
    /// failed create doesn't leave its draft visible.
    pub fn rollback(&self, key: &T::Key) {
        if self.optimistic_placeholders.remove(key).is_some() {
            self.items.remove(key);
            self.keys
                .change(|current_keys| current_keys.retain(|k| k != key));
        } else {
            self.items
                .must_change(key, |list_item| list_item.override_val.set(None));
        }
    }

    /// Reactively view the whole list as a [`Computed`], backed by [`get`](Self::get) (so it
    /// reflects the list as the user currently sees it, with optimistic overrides applied).
    pub fn to_computed(&self) -> Computed<Resource<Rc<Vec<T::Value>>>> {
        let state = self.clone();
        Computed::from(move |context| state.get(context))
    }

    /// Render the list, supplying a default `"Loading ..."` / `"error = ..."` view for
    /// the non-ready [`Resource`] states and delegating the ready case to `render`.
    ///
    /// For per-row reactivity, prefer rendering each row from its own [`Computed`] over
    /// [`get_by_key`](Self::get_by_key) instead.
    pub fn render(&self, render: impl Fn(Rc<Vec<T::Value>>) -> DomNode + 'static) -> DomNode {
        self.to_computed().render_value(move |value| match value {
            Resource::Ready(value) => render(value),
            Resource::Loading => {
                use crate as vertigo;
                vertigo::dom! { <div>"Loading ..."</div> }
            }
            Resource::Error(error) => {
                use crate as vertigo;
                vertigo::dom! { <div>"error = " {error}</div> }
            }
        })
    }

    fn update(&self, with_loading: bool, force: bool) {
        if self.list_queued.get() {
            return;
        }
        self.list_queued.set(true);

        if with_loading {
            self.state.set(ListCacheState::Loading);
        }

        let self_clone = self.clone();

        get_driver().spawn(async move {
            let state = transaction(|ctx| self_clone.state.get(ctx));
            let needs_fetch = force || state == ListCacheState::Uninitialized;

            if needs_fetch {
                self_clone.state.set(ListCacheState::Loading);

                let request = transaction(|context| {
                    self_clone
                        .list_request
                        .as_ref()
                        .clone()
                        .to_request_context(context)
                });

                let result = api_fetch().fetch(request.clone()).await;
                let new_value = RequestResponse::new(request, result)
                    .into(self_clone.list_map_response.as_ref());

                match new_value {
                    Ok(items_vec) => {
                        self_clone.apply_response(items_vec);
                        self_clone.state.set(ListCacheState::Ready);
                    }
                    Err(msg) => {
                        self_clone.state.set(ListCacheState::Error(msg));
                    }
                }
            }

            self_clone.list_queued.set(false);
        });
    }

    fn apply_response(&self, new_items: Vec<T::Value>) {
        let new_keys: Vec<T::Key> = new_items.iter().map(T::get_key).collect();
        let new_key_set: HashSet<T::Key> = new_keys.iter().cloned().collect();

        // Remove items no longer present in the response.
        self.items.retain(|k, _| new_key_set.contains(k));

        // Update originals for existing items; insert new ones.
        for item in new_items {
            let key = T::get_key(&item);
            if self
                .items
                .must_change(&key, |list_item| list_item.original.set(item.clone()))
                .is_none()
            {
                self.items.insert(key, ListItem::new(item));
            }
        }

        // Server response is the source of truth — every key it returns is now confirmed,
        // and any unreturned placeholder has just been dropped above. Either way, no entry
        // remains a placeholder after a refresh.
        self.optimistic_placeholders.retain(|_, _| false);

        self.keys.set(new_keys);
    }
}

impl<T: CollectionKey> LazyListCache<T>
where
    T::Value: JsJsonDeserialize,
{
    /// Create a `LazyListCache` that deserializes `Vec<T::Value>` from the given URL.
    pub fn new_resource(api: &str, path: &str, ttl: u64) -> Self {
        let url = [api, path].concat();
        LazyListCache::new(
            get_driver().request_get(url).ttl_seconds(ttl),
            |status, body| {
                if status == 200 {
                    Some(body.into::<Vec<T::Value>>())
                } else {
                    None
                }
            },
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Resource, transaction};

    #[derive(Clone, PartialEq, Debug)]
    struct Item {
        id: i32,
        name: String,
    }

    struct ItemKey;

    impl CollectionKey for ItemKey {
        type Key = i32;
        type Value = Item;

        fn get_key(val: &Item) -> i32 {
            val.id
        }
    }

    fn make_cache() -> LazyListCache<ItemKey> {
        LazyListCache::new(RequestBuilder::get("https://test.example/items"), |_, _| {
            None
        })
    }

    fn seed(cache: &LazyListCache<ItemKey>) {
        cache.apply_response(vec![
            Item {
                id: 1,
                name: "One".to_string(),
            },
            Item {
                id: 2,
                name: "Two".to_string(),
            },
            Item {
                id: 3,
                name: "Three".to_string(),
            },
        ]);
        cache.state.set(ListCacheState::Ready);
    }

    fn get_by_key(cache: &LazyListCache<ItemKey>, key: i32) -> Resource<Rc<Item>> {
        transaction(|ctx| cache.get_by_key(ctx, &key))
    }

    fn get_list(cache: &LazyListCache<ItemKey>) -> Rc<Vec<Item>> {
        transaction(|ctx| match cache.get(ctx) {
            Resource::Ready(v) => v,
            other => panic!("expected Ready, got {:?}", other),
        })
    }

    // --- get (override-aware whole-list view) ---

    #[test]
    fn test_get_returns_ordered_items() {
        let cache = make_cache();
        seed(&cache);

        let list = get_list(&cache);
        assert_eq!(list.len(), 3);
        assert_eq!(list[0].id, 1);
        assert_eq!(list[1].id, 2);
        assert_eq!(list[2].id, 3);
        assert_eq!(list[1].name, "Two");
    }

    #[test]
    fn test_get_returns_loading_before_fetch() {
        let cache = make_cache();
        transaction(|ctx| assert_eq!(cache.get(ctx), Resource::Loading));
    }

    #[test]
    fn test_get_applies_optimistic_edit() {
        let cache = make_cache();
        seed(&cache);

        cache.optimistically_set_item(Item {
            id: 2,
            name: "Two-override".to_string(),
        });

        let list = get_list(&cache);
        assert_eq!(list[1].name, "Two-override");
    }

    #[test]
    fn test_get_omits_optimistically_removed() {
        let cache = make_cache();
        seed(&cache);

        cache.optimistically_remove_item(&2);

        // Row 2 disappears immediately, before remove_item confirms.
        let list = get_list(&cache);
        assert_eq!(list.iter().map(|i| i.id).collect::<Vec<_>>(), vec![1, 3]);
    }

    #[test]
    fn test_get_includes_optimistic_insert() {
        let cache = make_cache();
        seed(&cache);

        cache.optimistically_set_item(Item {
            id: 42,
            name: "New".to_string(),
        });

        let list = get_list(&cache);
        assert_eq!(
            list.iter().map(|i| i.id).collect::<Vec<_>>(),
            vec![1, 2, 3, 42]
        );
        assert_eq!(list[3].name, "New");
    }

    // --- get_by_key ---

    #[test]
    fn test_get_by_key_falls_back_to_original() {
        let cache = make_cache();
        seed(&cache);

        assert_eq!(
            get_by_key(&cache, 2),
            Resource::Ready(Rc::new(Item {
                id: 2,
                name: "Two".to_string()
            }))
        );
    }

    #[test]
    fn test_get_by_key_loading_when_not_ready() {
        let cache = make_cache();
        assert_eq!(get_by_key(&cache, 1), Resource::Loading);
    }

    #[test]
    fn test_get_by_key_error_when_key_missing() {
        let cache = make_cache();
        seed(&cache);
        assert!(matches!(get_by_key(&cache, 99), Resource::Error(_)));
    }

    // --- optimistically_set_item ---

    #[test]
    fn test_override_visible_via_get_by_key() {
        let cache = make_cache();
        seed(&cache);

        cache.optimistically_set_item(Item {
            id: 2,
            name: "Two-override".to_string(),
        });

        assert_eq!(
            get_by_key(&cache, 2),
            Resource::Ready(Rc::new(Item {
                id: 2,
                name: "Two-override".to_string()
            }))
        );
    }

    #[test]
    fn test_override_does_not_modify_original() {
        let cache = make_cache();
        seed(&cache);

        cache.optimistically_set_item(Item {
            id: 2,
            name: "Two-override".to_string(),
        });

        // get() shows the override...
        assert_eq!(get_list(&cache)[1].name, "Two-override");

        // ...but the underlying server-confirmed original is untouched: rolling back restores it.
        cache.rollback(&2);
        assert_eq!(get_list(&cache)[1].name, "Two");
    }

    #[test]
    fn test_override_other_keys_unaffected() {
        let cache = make_cache();
        seed(&cache);

        cache.optimistically_set_item(Item {
            id: 2,
            name: "Two-override".to_string(),
        });

        assert_eq!(
            get_by_key(&cache, 1),
            Resource::Ready(Rc::new(Item {
                id: 1,
                name: "One".to_string()
            }))
        );
        assert_eq!(
            get_by_key(&cache, 3),
            Resource::Ready(Rc::new(Item {
                id: 3,
                name: "Three".to_string()
            }))
        );
    }

    #[test]
    fn test_override_works_while_loading() {
        let cache = make_cache();

        cache.optimistically_set_item(Item {
            id: 1,
            name: "One".to_string(),
        });

        assert_eq!(
            get_by_key(&cache, 1),
            Resource::Ready(Rc::new(Item {
                id: 1,
                name: "One".to_string()
            }))
        );
        // full list is still Loading
        transaction(|ctx| assert_eq!(cache.get(ctx), Resource::Loading));
    }

    #[test]
    fn test_override_update_same_key() {
        let cache = make_cache();
        seed(&cache);

        cache.optimistically_set_item(Item {
            id: 2,
            name: "v1".to_string(),
        });
        cache.optimistically_set_item(Item {
            id: 2,
            name: "v2".to_string(),
        });

        assert_eq!(
            get_by_key(&cache, 2),
            Resource::Ready(Rc::new(Item {
                id: 2,
                name: "v2".to_string()
            }))
        );
    }

    // --- rollback ---

    #[test]
    fn test_rollback_restores_original() {
        let cache = make_cache();
        seed(&cache);

        cache.optimistically_set_item(Item {
            id: 2,
            name: "Two-override".to_string(),
        });
        cache.rollback(&2);

        assert_eq!(
            get_by_key(&cache, 2),
            Resource::Ready(Rc::new(Item {
                id: 2,
                name: "Two".to_string()
            }))
        );
    }

    #[test]
    fn test_rollback_noop_for_unknown_key() {
        let cache = make_cache();
        seed(&cache);

        cache.rollback(&99); // should not panic

        let list = get_list(&cache);
        assert_eq!(list.len(), 3);
    }

    // --- apply_response (refresh preserves overrides) ---

    #[test]
    fn test_refresh_preserves_override() {
        let cache = make_cache();
        seed(&cache);

        cache.optimistically_set_item(Item {
            id: 2,
            name: "Two-override".to_string(),
        });

        // Server returns updated data
        cache.apply_response(vec![
            Item {
                id: 1,
                name: "One-v2".to_string(),
            },
            Item {
                id: 2,
                name: "Two-v2".to_string(),
            },
            Item {
                id: 3,
                name: "Three-v2".to_string(),
            },
        ]);
        cache.state.set(ListCacheState::Ready);

        // get() applies overrides: item 2 keeps its override, while un-overridden rows show the
        // refreshed server values.
        let list = get_list(&cache);
        assert_eq!(list[0].name, "One-v2");
        assert_eq!(list[1].name, "Two-override");
        assert_eq!(list[2].name, "Three-v2");

        // get_by_key still shows override
        assert_eq!(
            get_by_key(&cache, 2),
            Resource::Ready(Rc::new(Item {
                id: 2,
                name: "Two-override".to_string()
            }))
        );

        // Rolling back reveals the refreshed server original underneath.
        cache.rollback(&2);
        assert_eq!(get_list(&cache)[1].name, "Two-v2");
    }

    // --- create flow (optimistic insert + update_item commit) ---

    #[test]
    fn test_optimistic_set_then_update_item_appears_in_list() {
        // Mirrors the panel's create-peer flow: optimistic insert, then commit on POST 200.
        let cache = make_cache();
        seed(&cache);

        let new_item = Item {
            id: 42,
            name: "New".to_string(),
        };

        cache.optimistically_set_item(new_item.clone());

        // Optimistic placeholder is already visible via get() (placeholder original = optimistic).
        let list = get_list(&cache);
        assert!(list.iter().any(|i| i.id == 42 && i.name == "New"));

        // Server confirms — commit the optimistic insert.
        cache.update_item(new_item.clone());

        let list = get_list(&cache);
        assert_eq!(list.len(), 4);
        assert!(list.iter().any(|i| i.id == 42 && i.name == "New"));

        // After update_item, the override is cleared so get_by_key returns the committed original.
        assert_eq!(get_by_key(&cache, 42), Resource::Ready(Rc::new(new_item)));
    }

    #[test]
    fn test_update_item_inserts_unknown_key() {
        let cache = make_cache();
        seed(&cache);

        cache.update_item(Item {
            id: 99,
            name: "Ninety-nine".to_string(),
        });

        let list = get_list(&cache);
        assert_eq!(list.len(), 4);
        assert!(list.iter().any(|i| i.id == 99));
    }

    #[test]
    fn test_keys_reactivity_via_computed() {
        // Subscribers wrapped in a Computed must re-evaluate when keys change.
        let cache = make_cache();
        seed(&cache);

        let computed = {
            let cache = cache.clone();
            Computed::from(move |ctx| match cache.get(ctx) {
                Resource::Ready(v) => v.iter().map(|i| i.id).collect::<Vec<_>>(),
                _ => Vec::new(),
            })
        };

        let initial = transaction(|ctx| computed.get(ctx));
        assert_eq!(initial, vec![1, 2, 3]);

        cache.update_item(Item {
            id: 4,
            name: "Four".to_string(),
        });

        let after = transaction(|ctx| computed.get(ctx));
        assert_eq!(after, vec![1, 2, 3, 4]);
    }

    // --- update_item_with_old_key (re-keying create flow) ---

    #[test]
    fn test_update_item_with_old_key_rekeys_in_place() {
        // Mirrors a typical create flow: optimistic insert under a temp id (0), then the server
        // returns the created entity with a real id (42). The placeholder should be re-keyed to
        // 42 at the same position in the list, and lookups by 0 should fail.
        let cache = make_cache();
        seed(&cache);

        cache.optimistically_set_item(Item {
            id: 0,
            name: "draft".to_string(),
        });

        // Optimistic placeholder is appended at the end: [1, 2, 3, 0].
        let list = get_list(&cache);
        assert_eq!(
            list.iter().map(|i| i.id).collect::<Vec<_>>(),
            vec![1, 2, 3, 0]
        );

        cache.update_item_with_old_key(
            &0,
            Item {
                id: 42,
                name: "Saved".to_string(),
            },
        );

        // Position is preserved: [1, 2, 3, 42], not [1, 2, 3, 0, 42].
        let list = get_list(&cache);
        assert_eq!(
            list.iter().map(|i| i.id).collect::<Vec<_>>(),
            vec![1, 2, 3, 42]
        );
        assert_eq!(list[3].name, "Saved");

        // Old key is gone.
        assert!(matches!(get_by_key(&cache, 0), Resource::Error(_)));
        // New key resolves with the committed original.
        assert_eq!(
            get_by_key(&cache, 42),
            Resource::Ready(Rc::new(Item {
                id: 42,
                name: "Saved".to_string()
            }))
        );
    }

    #[test]
    fn test_update_item_with_old_key_same_key_acts_as_update() {
        let cache = make_cache();
        seed(&cache);

        cache.optimistically_set_item(Item {
            id: 2,
            name: "draft".to_string(),
        });
        cache.update_item_with_old_key(
            &2,
            Item {
                id: 2,
                name: "Saved".to_string(),
            },
        );

        let list = get_list(&cache);
        assert_eq!(list.len(), 3);
        assert_eq!(list[1].name, "Saved");
    }

    // --- rollback of optimistic create (placeholder) ---

    #[test]
    fn test_rollback_removes_optimistic_placeholder() {
        // A failed optimistic create must not leave a draft visible in the list.
        let cache = make_cache();
        seed(&cache);

        cache.optimistically_set_item(Item {
            id: 99,
            name: "draft".to_string(),
        });

        // Visible during the optimistic phase.
        let list = get_list(&cache);
        assert!(list.iter().any(|i| i.id == 99));

        cache.rollback(&99);

        // Fully gone.
        let list = get_list(&cache);
        assert_eq!(list.len(), 3);
        assert!(!list.iter().any(|i| i.id == 99));
        assert!(matches!(get_by_key(&cache, 99), Resource::Error(_)));
    }

    #[test]
    fn test_rollback_existing_item_only_clears_override() {
        // For server-confirmed items, rollback must continue to behave as before:
        // clear the override, restore the original, but never delete the row.
        let cache = make_cache();
        seed(&cache);

        cache.optimistically_set_item(Item {
            id: 2,
            name: "Two-override".to_string(),
        });
        cache.rollback(&2);

        let list = get_list(&cache);
        assert_eq!(list.len(), 3);
        assert_eq!(list[1].name, "Two");
    }

    // --- delete flow (remove_item / optimistically_remove_item) ---

    #[test]
    fn test_optimistic_then_remove_item_reactivity_via_granular() {
        // Full delete flow: optimistically_remove_item drops the row immediately; the later
        // remove_item commit keeps it gone. Verify the granular consumer stays consistent.
        let cache = make_cache();
        seed(&cache);

        let computed = {
            let cache = cache.clone();
            Computed::from(
                move |ctx| match cache.granular::<fn(&Item) -> bool>(ctx, None) {
                    Resource::Ready(items) => items
                        .iter()
                        .filter_map(|item| item.get(ctx).map(|v| v.id))
                        .collect::<Vec<_>>(),
                    _ => Vec::new(),
                },
            )
        };

        assert_eq!(transaction(|ctx| computed.get(ctx)), vec![1, 2, 3]);

        cache.optimistically_remove_item(&2);
        // Optimistic removal is reflected immediately.
        assert_eq!(transaction(|ctx| computed.get(ctx)), vec![1, 3]);

        // Committing the deletion keeps the row gone.
        cache.remove_item(&2);
        assert_eq!(transaction(|ctx| computed.get(ctx)), vec![1, 3]);
    }

    // --- granular (override-aware per-item view) ---

    // Resolve a granular list into (id, name) pairs for the items that are present.
    fn granular_pairs(cache: &LazyListCache<ItemKey>) -> Vec<(i32, String)> {
        transaction(|ctx| match cache.granular::<fn(&Item) -> bool>(ctx, None) {
            Resource::Ready(items) => items
                .iter()
                .filter_map(|item| item.get(ctx).map(|v| (v.id, v.name)))
                .collect::<Vec<_>>(),
            _ => panic!("expected Ready"),
        })
    }

    #[test]
    fn test_granular_applies_optimistic_edit() {
        let cache = make_cache();
        seed(&cache);

        cache.optimistically_set_item(Item {
            id: 2,
            name: "Two-override".to_string(),
        });

        assert_eq!(
            granular_pairs(&cache),
            vec![
                (1, "One".to_string()),
                (2, "Two-override".to_string()),
                (3, "Three".to_string()),
            ]
        );
    }

    #[test]
    fn test_granular_omits_optimistically_removed() {
        let cache = make_cache();
        seed(&cache);

        // optimistically_remove_item flips override_val to Some(None) without touching `keys`,
        // so the removed key is still in the snapshot — the per-item Computed must yield None.
        cache.optimistically_remove_item(&2);

        assert_eq!(
            granular_pairs(&cache)
                .into_iter()
                .map(|(id, _)| id)
                .collect::<Vec<_>>(),
            vec![1, 3]
        );
    }

    #[test]
    fn test_granular_includes_optimistic_insert() {
        let cache = make_cache();
        seed(&cache);

        cache.optimistically_set_item(Item {
            id: 42,
            name: "New".to_string(),
        });

        assert_eq!(
            granular_pairs(&cache)
                .into_iter()
                .map(|(id, _)| id)
                .collect::<Vec<_>>(),
            vec![1, 2, 3, 42]
        );
    }

    #[test]
    fn test_granular_reactivity_on_remove() {
        // A subscriber over granular must see the row drop the moment it is
        // optimistically removed — without waiting for remove_item.
        let cache = make_cache();
        seed(&cache);

        let computed = {
            let cache = cache.clone();
            Computed::from(
                move |ctx| match cache.granular::<fn(&Item) -> bool>(ctx, None) {
                    Resource::Ready(items) => items
                        .iter()
                        .filter_map(|item| item.get(ctx).map(|v| v.id))
                        .collect::<Vec<_>>(),
                    _ => Vec::new(),
                },
            )
        };

        assert_eq!(transaction(|ctx| computed.get(ctx)), vec![1, 2, 3]);

        cache.optimistically_remove_item(&2);
        // The optimistic removal is reflected immediately.
        assert_eq!(transaction(|ctx| computed.get(ctx)), vec![1, 3]);

        // Rolling back restores it.
        cache.rollback(&2);
        assert_eq!(transaction(|ctx| computed.get(ctx)), vec![1, 2, 3]);
    }

    #[test]
    fn test_granular_filter_composes_with_override() {
        let cache = make_cache();
        seed(&cache);

        // Edit id=1 so it would pass a "name starts with O" filter only via the override.
        cache.optimistically_set_item(Item {
            id: 1,
            name: "Other".to_string(),
        });
        // Optimistically remove id=3.
        cache.optimistically_remove_item(&3);

        let filter = |item: &Item| item.name.starts_with('O');
        let ids = transaction(|ctx| match cache.granular(ctx, Some(filter)) {
            Resource::Ready(items) => items
                .iter()
                .filter_map(|item| item.get(ctx).map(|v| v.id))
                .collect::<Vec<_>>(),
            _ => panic!("expected Ready"),
        });

        // id=1 -> "Other" passes; id=2 -> "Two" fails the filter; id=3 -> removed (None).
        assert_eq!(ids, vec![1]);
    }

    #[test]
    fn test_remove_item_after_optimistically_remove_item() {
        // The full delete flow: optimistic mark, then commit on server success.
        let cache = make_cache();
        seed(&cache);

        cache.optimistically_remove_item(&2);
        cache.remove_item(&2);

        let list = get_list(&cache);
        assert_eq!(list.iter().map(|i| i.id).collect::<Vec<_>>(), vec![1, 3]);
        assert!(matches!(get_by_key(&cache, 2), Resource::Error(_)));
    }

    #[test]
    fn test_update_item_clears_placeholder_so_later_rollback_keeps_row() {
        // After update_item commits an optimistic create, a subsequent rollback (e.g. on a
        // follow-up edit) must NOT delete the now-confirmed row.
        let cache = make_cache();
        seed(&cache);

        let new_item = Item {
            id: 99,
            name: "draft".to_string(),
        };
        cache.optimistically_set_item(new_item.clone());
        cache.update_item(Item {
            id: 99,
            name: "Saved".to_string(),
        });

        // User edits optimistically and then cancels.
        cache.optimistically_set_item(Item {
            id: 99,
            name: "draft-edit".to_string(),
        });
        cache.rollback(&99);

        let list = get_list(&cache);
        assert_eq!(list.len(), 4);
        assert!(list.iter().any(|i| i.id == 99 && i.name == "Saved"));
    }

    // --- clone / PartialEq ---

    #[test]
    fn test_clone_eq() {
        let cache = make_cache();
        assert_eq!(cache, cache.clone());
        assert_ne!(cache, make_cache());
    }
}