makepad-widgets 1.0.0

Makepad widgets
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
use crate::{
    widget::*,
    makepad_derive_widget::*,
    makepad_draw::*,
    scroll_bar::{ScrollBar, ScrollAxis, ScrollBarAction}
};

live_design!{
    link widgets;
    use link::theme::*;
    use link::shaders::*;
    use crate::scroll_bar::ScrollBar;
    
    pub PortalListBase = {{PortalList}} {}
        
    pub PortalList = <PortalListBase> {
        width: Fill, height: Fill,
        capture_overload: true
        scroll_bar: <ScrollBar> {}
        flow: Down
    }
}

/// The maximum number of items that will be shown as part of a smooth scroll animation.
const SMOOTH_SCROLL_MAXIMUM_WINDOW: usize = 20;

#[derive(Clone,Copy)]
struct ScrollSample{
    abs: f64,
    time: f64,
}

enum ScrollState {
    Stopped,
    Drag{samples:Vec<ScrollSample>},
    Flick {delta: f64, next_frame: NextFrame},
    Pulldown {next_frame: NextFrame},
    ScrollingTo {target_id: usize, delta: f64, next_frame: NextFrame},
}

#[derive(Clone)]
enum ListDrawState {
    Begin,
    Down {index: usize, pos: f64, viewport: Rect},
    Up {index: usize, pos: f64, hit_bottom: bool, viewport: Rect},
    DownAgain {index: usize, pos: f64, viewport: Rect},
    End {viewport: Rect}
}

#[derive(Clone, Debug, DefaultNone)]
pub enum PortalListAction {
    Scroll,
    SmoothScrollReached,
    None
}
impl ListDrawState {
    fn is_down_again(&self) -> bool {
        match self {
            Self::DownAgain {..} => true,
            _ => false
        }
    }
}
#[derive(Live, Widget)]
pub struct PortalList {
    #[redraw] #[rust] area: Area,
    #[walk] walk: Walk,
    #[layout] layout: Layout,
    
    #[rust] range_start: usize,
    #[rust(usize::MAX)] range_end: usize,
    #[rust(0usize)] view_window: usize,
    #[rust(0usize)] visible_items: usize,
    #[live(0.2)] flick_scroll_minimum: f64,
    #[live(80.0)] flick_scroll_maximum: f64,
    #[live(0.005)] flick_scroll_scaling: f64,
    #[live(0.97)] flick_scroll_decay: f64,
    #[live(80.0)] max_pull_down: f64,
    #[live(true)] align_top_when_empty: bool,
    #[live(false)] grab_key_focus: bool,
    #[live(true)] drag_scrolling: bool,
    #[rust] first_id: usize,
    #[rust] first_scroll: f64,
    #[rust(Vec2Index::X)] vec_index: Vec2Index,
    #[live] scroll_bar: ScrollBar,
    #[live] capture_overload: bool,
    #[live(false)] keep_invisible: bool,
    #[rust] draw_state: DrawStateWrap<ListDrawState>,
    #[rust] draw_align_list: Vec<AlignItem>,
    #[rust] detect_tail_in_draw: bool,
    #[live(false)] auto_tail: bool,
    #[live(false)] draw_caching: bool,
    
    #[rust(false)] tail_range: bool,
    #[rust(false)] at_end: bool,
    #[rust(true)] not_filling_viewport: bool,
    #[live(false)] reuse_items: bool,
    
    #[rust] templates: ComponentMap<LiveId, LivePtr>,
    #[rust] items: ComponentMap<usize, WidgetItem>,
    #[rust] reusable_items: Vec<WidgetItem>,
    #[rust] _draw_list_cache: Vec<DrawList>,
    
    //#[rust(DragState::None)] drag_state: DragState,
    #[rust(ScrollState::Stopped)] scroll_state: ScrollState,
    /// Whether the PortalList was actively scrolling during the most recent finger down hit.
    #[rust] was_scrolling: bool,
}


#[derive(Default)]
struct WidgetItem{
    widget: WidgetRef,
    template: LiveId,
}

struct AlignItem {
    align_range: TurtleAlignRange,
    size: DVec2,
    shift: f64,
    index: usize
}

impl LiveHook for PortalList {
    fn before_apply(&mut self, _cx: &mut Cx, apply: &mut Apply, _index: usize, _nodes: &[LiveNode]) {
        if let ApplyFrom::UpdateFromDoc {..} = apply.from {
            self.templates.clear();
        }
    }
    
    // hook the apply flow to collect our templates and apply to instanced childnodes
    fn apply_value_instance(&mut self, cx: &mut Cx, apply: &mut Apply, index: usize, nodes: &[LiveNode]) -> usize {
        if nodes[index].is_instance_prop() {
            if let Some(live_ptr) = apply.from.to_live_ptr(cx, index){
                let id = nodes[index].id;
                self.templates.insert(id, live_ptr);
                // lets apply this thing over all our childnodes with that template
                for (_, item) in self.items.iter_mut() {
                    if item.template == id {
                        item.widget.apply(cx, apply, index, nodes);
                    }
                }
            }
        }
        else {
            cx.apply_error_no_matching_field(live_error_origin!(), index, nodes);
        }
        nodes.skip_node(index)
    }
    
    fn after_apply(&mut self, _cx: &mut Cx, _applyl: &mut Apply, _index: usize, _nodes: &[LiveNode]) {
        if let Flow::Down = self.layout.flow {
            self.vec_index = Vec2Index::Y
        }
        else {
            self.vec_index = Vec2Index::X
        }
        if self.auto_tail{
            self.tail_range = true;
        }
    }
}

impl PortalList {
    
    fn begin(&mut self, cx: &mut Cx2d, walk: Walk) {
        cx.begin_turtle(walk, self.layout);
        self.draw_align_list.clear();
    }
    
    fn end(&mut self, cx: &mut Cx2d) {
        // in this code we position all the drawn items 

        self.at_end = false;
        self.not_filling_viewport = false;

        let vi = self.vec_index;
        let mut visible_items = 0;

        if let Some(ListDrawState::End {viewport}) = self.draw_state.get() {
            let list = &mut self.draw_align_list;
            if list.len() > 0 {
                list.sort_by( | a, b | a.index.cmp(&b.index));
                let first_index = list.iter().position( | v | v.index == self.first_id).unwrap();
                
                // find the position of the first item in our set
                
                let mut first_pos = self.first_scroll;
                for i in (0..first_index).rev() {
                    let item = &list[i];
                    first_pos -= item.size.index(vi);
                }
                
                // find the position of the last item in the range
                // note that the listview requests items beyond the range so you can pad out the listview 
                // when there is not enough data

                let mut last_pos = self.first_scroll;
                let mut last_item_pos = None;
                for i in first_index..list.len() {
                    let item = &list[i];
                    last_pos += item.size.index(vi);
                    if item.index < self.range_end {
                        last_item_pos = Some(last_pos);
                    }
                    else {
                        break;
                    }
                }
                
                // compute if we are filling the viewport
                // if not we have to trigger a stick-to-top
                if list[0].index == self.range_start {
                    let mut total = 0.0;
                    for item in list.iter() {
                        if item.index >= self.range_end {
                            break;
                        }
                        total += item.size.index(vi);
                    }
                    self.not_filling_viewport = total < viewport.size.index(vi);
                }
                
                // in this case we manage the 'pull down' situation when we are at the top
                if list.first().unwrap().index == self.range_start && first_pos > 0.0 {
                    let min = if let ScrollState::Stopped = self.scroll_state {
                        0.0
                    }
                    else {
                        self.max_pull_down
                    };
                    
                    let mut pos = first_pos.min(min); // lets do a maximum for first scroll
                    for item in list {
                        let shift = DVec2::from_index_pair(vi, pos, 0.0);
                        cx.shift_align_range(&item.align_range, shift - DVec2::from_index_pair(vi, item.shift, 0.0));
                        pos += item.size.index(vi);
                        visible_items += 1;
                    }
                    self.first_scroll = first_pos.min(min);
                    self.first_id = self.range_start;
                }
                else {
                    // this is the normal case, however we have to here compute
                    // the 'stick to bottom' case 
                    let shift = if let Some(last_item_pos) = last_item_pos {
                        if self.align_top_when_empty && self.not_filling_viewport {
                            -first_pos
                        }
                        else {
                            let ret = viewport.size.index(vi) - last_item_pos;
                            if ret >= 0.0 {
                                self.at_end = true;
                            }
                            ret.max(0.0)
                        }
                    }
                    else {
                        0.0
                    };
                    // first we scan upwards and move items in place
                    let mut first_id_changed = false;
                    let start_pos = self.first_scroll + shift;
                    let mut pos = start_pos;
                    for i in (0..first_index).rev() {
                        let item = &list[i];
                        let visible = pos > 0.0;
                        pos -= item.size.index(vi);
                        let shift = DVec2::from_index_pair(vi, pos, 0.0);
                        cx.shift_align_range(&item.align_range, shift - DVec2::from_index_pair(vi, item.shift, 0.0));
                        if visible { // move up
                            self.first_scroll = pos;
                            self.first_id = item.index;
                            first_id_changed = true;
                            if item.index < self.range_end {
                                visible_items += 1;
                            }
                        }
                    }
                    // then we scan downwards
                    let mut pos = start_pos;
                    for i in first_index..list.len() {
                        let item = &list[i];
                        let shift = DVec2::from_index_pair(vi, pos, 0.0);
                        cx.shift_align_range(&item.align_range, shift - DVec2::from_index_pair(vi, item.shift, 0.0));
                        pos += item.size.index(vi);
                        let invisible = pos < 0.0;
                        if invisible { // move down
                            self.first_scroll = pos - item.size.index(vi);
                            self.first_id = item.index;
                            first_id_changed = true;
                        }
                        else if item.index < self.range_end {
                            visible_items += 1;
                        }
                    }
                    // overwrite first scroll for top/bottom aligns if we havent updated already
                    if !first_id_changed {
                        self.first_scroll = start_pos;
                    }
                }
                if !self.scroll_bar.animator_in_state(cx, id!(hover.pressed)){
                    self.update_scroll_bar(cx);
                }
            }
        }
        else {
            //log!("Draw state not at end in listview, please review your next_visible_item loop")
        }
        let rect = cx.turtle().rect();
        if self.at_end || self.view_window == 0 || self.view_window > visible_items{
            self.view_window = visible_items.max(4) - 3;
        }
        if self.detect_tail_in_draw{
            self.detect_tail_in_draw = false;
            if self.auto_tail && self.at_end{
                self.tail_range = true;
            }
        }
        let total_views = (self.range_end - self.range_start) as f64 / self.view_window as f64;
        match self.vec_index {
            Vec2Index::Y => {
                self.scroll_bar.draw_scroll_bar(cx, ScrollAxis::Vertical, rect, dvec2(100.0, rect.size.y * total_views));
            }
            Vec2Index::X => {
                self.scroll_bar.draw_scroll_bar(cx, ScrollAxis::Horizontal, rect, dvec2(rect.size.x * total_views, 100.0));
            }
        }        
        
        if !self.keep_invisible{
            if self.reuse_items{
                let reusable_items = &mut self.reusable_items;
                self.items.retain_visible_with(|v|{
                    reusable_items.push(v);
                });
            }
            else{
                self.items.retain_visible();
            }
        }

        cx.end_turtle_with_area(&mut self.area);
        self.visible_items = visible_items;
    }
    
    
    /// Returns the index of the next visible item that will be drawn by this PortalList.
    pub fn next_visible_item(&mut self, cx: &mut Cx2d) -> Option<usize> {
        let vi = self.vec_index;
        let layout = if vi == Vec2Index::Y { Layout::flow_down() } else { Layout::flow_right() };
        if let Some(draw_state) = self.draw_state.get() {
            match draw_state {
                ListDrawState::Begin => {
                    // Sanity check: warn on the first item ID being outside of the previously-set item range.
                    // This check is done here rather than in `begin()`, as most PortalList usage doesn't set
                    // the item range properly until right before looping over `next_visible_items()`.
                    #[cfg(debug_assertions)]
                    if self.fails_sanity_check_first_id_within_item_range() {
                        warning!("PortalList: first_id {} is greater than range_end {}.\n\
                            --> Check that you have set the correct item range and first item ID!",
                            self.first_id, self.range_end,
                        );
                    }

                    let viewport = cx.turtle().padded_rect();
                    self.draw_state.set(ListDrawState::Down {
                        index: self.first_id,
                        pos: self.first_scroll,
                        viewport,
                    });
                    match vi {
                        Vec2Index::Y => {
                            cx.begin_turtle(Walk {
                                abs_pos: Some(dvec2(viewport.pos.x, viewport.pos.y + self.first_scroll)),
                                margin: Default::default(),
                                width: Size::Fill,
                                height: Size::Fit
                            }, layout);
                        }
                        Vec2Index::X => {
                            cx.begin_turtle(Walk {
                                abs_pos: Some(dvec2(viewport.pos.x + self.first_scroll, viewport.pos.y)),
                                margin: Default::default(),
                                width: Size::Fit,
                                height: Size::Fill
                            }, layout);
                        }
                    }
                    return Some(self.first_id);
                }
                ListDrawState::Down {index, pos, viewport} | ListDrawState::DownAgain {index, pos, viewport} => {
                    let is_down_again = draw_state.is_down_again();
                    let did_draw = cx.turtle_has_align_items();
                    let align_range = cx.get_turtle_align_range();
                    let rect = cx.end_turtle();
                    self.draw_align_list.push(AlignItem {
                        align_range,
                        shift: pos, 
                        size: rect.size,
                        index
                    });
                    
                    if !did_draw || pos + rect.size.index(vi) > viewport.size.index(vi) {
                        // lets scan upwards
                        if self.first_id>0 && !is_down_again {
                            self.draw_state.set(ListDrawState::Up {
                                index: self.first_id - 1,
                                pos: self.first_scroll,
                                hit_bottom: index >= self.range_end,
                                viewport
                            });
                            match vi {
                                Vec2Index::Y => {
                                    cx.begin_turtle(Walk {
                                        abs_pos: Some(dvec2(viewport.pos.x, viewport.pos.y)),
                                        margin: Default::default(),
                                        width: Size::Fill,
                                        height: Size::Fit
                                    }, layout);
                                }
                                Vec2Index::X => {
                                    cx.begin_turtle(Walk {
                                        abs_pos: Some(dvec2(viewport.pos.x, viewport.pos.y)),
                                        margin: Default::default(),
                                        width: Size::Fit,
                                        height: Size::Fill
                                    }, layout);
                                }
                            }
                            return Some(self.first_id - 1);
                        }
                        else {
                            self.draw_state.set(ListDrawState::End {viewport});
                            return None
                        }
                    }
                    if is_down_again {
                        self.draw_state.set(ListDrawState::DownAgain {
                            index: index + 1,
                            pos: pos + rect.size.index(vi),
                            viewport
                        });
                    }
                    else {
                        self.draw_state.set(ListDrawState::Down {
                            index: index + 1,
                            pos: pos + rect.size.index(vi),
                            viewport
                        });
                    }
                    match vi {
                        Vec2Index::Y => {
                            cx.begin_turtle(Walk {
                                abs_pos: Some(dvec2(viewport.pos.x, viewport.pos.y + pos + rect.size.index(vi))),
                                margin: Default::default(),
                                width: Size::Fill,
                                height: Size::Fit
                            }, layout);
                        }
                        Vec2Index::X => {
                            cx.begin_turtle(Walk {
                                abs_pos: Some(dvec2(viewport.pos.x + pos + rect.size.index(vi), viewport.pos.y)),
                                margin: Default::default(),
                                width: Size::Fit,
                                height: Size::Fill
                            }, layout);
                        }
                    }
                    return Some(index + 1);
                }
                ListDrawState::Up {index, pos, hit_bottom, viewport} => {
                    let did_draw = cx.turtle_has_align_items();
                    let align_range = cx.get_turtle_align_range();
                    let rect = cx.end_turtle();
                    self.draw_align_list.push(AlignItem {
                        align_range,
                        size: rect.size,
                        shift: 0.0,
                        index
                    });
                    if index == self.range_start {
                        // we are at range start, but if we snap to top, we might need to walk further down as well
                        // therefore we now go 'down again' to make sure we have enough visible items
                        // if we snap to the top 
                        if pos - rect.size.index(vi) > 0.0 {
                            // scan the tail
                            if let Some(last_index) = self.draw_align_list.iter().map( | v | v.index).max() {
                                // lets sum up all the items
                                let total_height: f64 = self.draw_align_list.iter().map( | v | v.size.index(vi)).sum();
                                self.draw_state.set(ListDrawState::DownAgain {
                                    index: last_index + 1,
                                    pos: total_height,
                                    viewport
                                });
                                cx.begin_turtle(Walk {
                                    abs_pos: Some(dvec2(viewport.pos.x, viewport.pos.y + total_height)),
                                    margin: Default::default(),
                                    width: Size::Fill,
                                    height: Size::Fit
                                }, Layout::flow_down());
                                return Some(last_index + 1);
                            }
                        }
                        self.draw_state.set(ListDrawState::End {viewport});
                        return None
                    }
                    
                    if !did_draw || pos < if hit_bottom {-viewport.size.index(vi)} else {0.0} {
                        self.draw_state.set(ListDrawState::End {viewport});
                        return None
                    }
                    
                    self.draw_state.set(ListDrawState::Up {
                        index: index - 1,
                        hit_bottom,
                        pos: pos - rect.size.index(vi),
                        viewport
                    });
                    
                    cx.begin_turtle(Walk {
                        abs_pos: Some(dvec2(viewport.pos.x, viewport.pos.y)),
                        margin: Default::default(),
                        width: Size::Fill,
                        height: Size::Fit
                    }, Layout::flow_down());
                    
                    return Some(index - 1);
                }
                _ => ()
            }
        }
        None
    }
    
    /// Creates a new widget from the given `template` or returns an existing widget,
    /// if one already exists with the same `entry_id`.
    ///
    /// If you care whether the widget already existed or not, use [`PortalList::item_with_existed()`] instead.
    ///
    /// ## Return
    /// * If a widget already existed for the given `entry_id` and `template`,
    ///   this returns a reference to that widget.
    /// * If a new widget was created successfully, this returns a reference to that new widget.
    /// * If the given `template` could not be found, this returns `None`.
    pub fn item(&mut self, cx: &mut Cx, entry_id: usize, template: LiveId) -> WidgetRef {
        self.item_with_existed(cx, entry_id, template).0
    }

    /// Creates a new widget from the given `template` or returns an existing widget,
    /// if one already exists with the same `entry_id` and `template`.
    ///
    /// * If you only want to check whether the item already existed without creating one,
    ///   use [`PortalList::get_item()`] instead.
    /// * If you don't care whether the widget already existed or not, use [`PortalList::item()`] instead.
    ///
    /// ## Return
    /// * If a widget of the same `template` already existed for the given `entry_id`,
    ///   this returns a tuple of that widget and `true`.
    /// * If a new widget was created successfully, either because an item with the given `entry_id`
    ///   did not exist or because the existing item with the given `entry_id` did not use the given `template`,
    ///   this returns a tuple of that widget and `false`.
    /// * If the given `template` could not be found, this returns `None`.
    pub fn item_with_existed(&mut self, cx: &mut Cx, entry_id: usize, template: LiveId) -> (WidgetRef, bool) {
        use std::collections::hash_map::Entry;
        if let Some(ptr) = self.templates.get(&template) {
            match self.items.entry(entry_id) {
                Entry::Occupied(mut occ) => {
                    if occ.get().template == template {
                        (occ.get().widget.clone(), true)
                    } else {
                        let widget_ref =  if let Some(pos) = self.reusable_items.iter().position(|v| v.template == template){
                            self.reusable_items.remove(pos).widget
                        }
                        else{
                            WidgetRef::new_from_ptr(cx, Some(*ptr))
                        };
                        occ.insert(WidgetItem{
                            template, 
                            widget:widget_ref.clone(),
                            ..Default::default()
                        });
                        (widget_ref, false)
                    }
                }
                Entry::Vacant(vac) => {
                    let widget_ref =  if let Some(pos) = self.reusable_items.iter().position(|v| v.template == template){
                        self.reusable_items.remove(pos).widget
                    }
                    else{
                        WidgetRef::new_from_ptr(cx, Some(*ptr))
                    };
                    vac.insert(WidgetItem{
                        template, 
                        widget: widget_ref.clone(),
                        ..Default::default()
                    });
                    (widget_ref, false)
                }
            }
        } else {
            warning!("Template not found: {template}. Did you add it to the <PortalList> instance in `live_design!{{}}`?");
            (WidgetRef::empty(), false)
        }
    }

    /// Returns the "start" position of the item with the given `entry_id`
    /// relative to the "start" position of the PortalList.
    ///
    /// * For vertical lists, the start position is the top of the item
    ///   relative to the top of the PortalList.
    /// * For horizontal lists, the start position is the left side of the item
    ///   relative to the left side of the PortalList.
    ///
    /// Returns `None` if the item with the given `entry_id` does not exist
    /// or if the item's area rectangle is zero.
    ///
    /// TODO: FIXME: this may not properly handle bottom-up lists
    ///              or lists that go from right to left.
    pub fn position_of_item(&self, cx: &Cx, entry_id: usize) -> Option<f64> {
        const ZEROED: Rect = Rect { pos: DVec2 { x: 0.0, y: 0.0 }, size: DVec2 { x: 0.0, y: 0.0 } };

        if let Some(item) = self.items.get(&entry_id) {
            let item_rect = item.widget.area().rect(cx);
            if item_rect == ZEROED {
                return None;
            }
            let self_rect = self.area.rect(cx);
            if self_rect == ZEROED {
                return None;
            }
            let vi = self.vec_index;
            Some(item_rect.pos.index(vi) - self_rect.pos.index(vi))
        } else {
            None
        }
    }
    
    /// Returns a reference to the template and widget for the given `entry_id`.
    pub fn get_item(&self, entry_id: usize) -> Option<(LiveId,WidgetRef)> {
        if let Some(item) = self.items.get(&entry_id){
            Some((item.template.clone(), item.widget.clone()))
        }
        else{
            None
        }
    }
    
    pub fn set_item_range(&mut self, cx: &mut Cx, range_start: usize, range_end: usize) {
        self.range_start = range_start;
        if self.range_end != range_end {
            self.range_end = range_end;
            if self.tail_range{
                self.first_id = self.range_end.max(1) - 1;
                self.first_scroll = 0.0;
            }
            self.update_scroll_bar(cx);
        }
    }
    
    pub fn update_scroll_bar(&mut self, cx: &mut Cx) {
        let scroll_pos = ((self.first_id - self.range_start) as f64 / ((self.range_end - self.range_start).max(self.view_window + 1) - self.view_window) as f64) * self.scroll_bar.get_scroll_view_total();
        // move the scrollbar to the right 'top' position
        self.scroll_bar.set_scroll_pos_no_action(cx, scroll_pos);
    }

    /// Sets the current scroll offset (`first_scroll`) based on the given `delta` value.
    ///
    /// ## Arguments
    /// * `delta`: The amount to scroll by.
    ///    A positive value scrolls upwards towards the top of the list,
    ///    while a negative value scrolls downwards towards the bottom of the list.
    /// * `clip_top`: If `true`, the scroll offset will be clamped to `0.0`, meaning that
    ///    no pulldown "bounce" animation will occur when you scroll upwards beyond the top of the list.
    /// * `transition_to_pulldown`: Whether to transition an existing scroll action to the `Pulldown`
    ///    scroll state when an upwards scroll action reaches the top of the list.
    fn delta_top_scroll(
        &mut self,
        cx: &mut Cx,
        delta: f64,
        clip_top: bool,
        transition_to_pulldown: bool,
    ) {
        if self.range_start == self.range_end {
            self.first_scroll = 0.0
        }
        else {
            self.first_scroll += delta;
        }

        if self.first_id == self.range_start {
            self.first_scroll = self.first_scroll.min(self.max_pull_down);
            if transition_to_pulldown && self.first_scroll > 0.0 {
                self.scroll_state = ScrollState::Pulldown {next_frame: cx.new_next_frame()};
            }
        }
        if clip_top && self.first_id == self.range_start && self.first_scroll > 0.0 {
            self.first_scroll = 0.0;
        }
        // Stop a downwards scroll when we reach the end of the list.
        if self.at_end && delta < 0.0 {
            self.was_scrolling = false;
            self.scroll_state = ScrollState::Stopped;
        }
        self.update_scroll_bar(cx);
    }

    /// Returns `true` if currently at the end of the list, meaning that the lasat item
    /// is visible in the viewport.
    pub fn is_at_end(&self) -> bool {
        self.at_end
    }

    /// Returns the number of items that are currently visible in the viewport,
    /// including partially visible items.
    pub fn visible_items(&self) -> usize {
        self.visible_items
    }

    /// Returns `true` if this sanity check fails: the first item ID is within the item range.
    ///
    /// Returns `false` if the sanity check passes as expected.
    pub fn fails_sanity_check_first_id_within_item_range(&self) -> bool {
        !self.tail_range
            && (self.first_id > self.range_end)
    }

    /// Initiates a smooth scrolling animation to the specified target item in the list.
    ///
    /// ## Arguments
    /// * `target_id`: The ID (index) of the item to scroll to.
    /// * `speed`: A positive floating-point value that controls the speed of the animation.
    ///    The `speed` will always be treated as an absolute value, with the direction of the scroll
    ///    (up or down) determined by whether `target_id` is above or below the current item.
    /// * `max_items_to_show`: The maximum number of items to show during the scrolling animation.
    ///    If `None`, the default value of 20 is used.
    ///
    /// ## Example
    /// ```rust,ignore
    /// // Scrolls to item 42 at speed 100.0, including at most 30 items in the scroll animation.
    /// smooth_scroll_to(&mut cx, 42, 100.0, Some(30));
    /// ```
    pub fn smooth_scroll_to(&mut self, cx: &mut Cx, target_id: usize, speed: f64, max_items_to_show: Option<usize>) {
        if self.items.is_empty() { return };
        if target_id < self.range_start || target_id > self.range_end { return };

        let max_items_to_show = max_items_to_show.unwrap_or(SMOOTH_SCROLL_MAXIMUM_WINDOW);
        let scroll_direction: f64;
        let starting_id: Option<usize>;
        if target_id > self.first_id {
            // Scrolling down to a larger item index
            scroll_direction = -1.0;
            starting_id = ((target_id.saturating_sub(self.first_id)) > max_items_to_show)
                .then_some(target_id.saturating_sub(max_items_to_show));
        } else {
            // Scrolling up to a smaller item index
            scroll_direction = 1.0;
            starting_id = ((self.first_id.saturating_sub(target_id)) > max_items_to_show)
                .then_some(target_id + max_items_to_show);
        };

        // First, if the target_id was too far away, jump directly to a closer starting_id.
        if let Some(start) = starting_id {
            self.first_id = start;
        }
        // Then, we kick off the actual smooth scroll process.
        self.scroll_state = ScrollState::ScrollingTo {
            target_id,
            delta: speed.abs() * scroll_direction as f64,
            next_frame: cx.new_next_frame()
        };
    }

    /// Trigger an scrolling animation to the end of the list
    ///
    /// ## Arguments
    /// * `speed`: This value controls how fast the scrolling animation is.
    ///    Note: This number should be large enough to reach the end, so it is important to
    ///    test the passed number. TODO provide a better implementation to ensure that the end
    ///    is always reached, no matter the speed value.
    /// * `max_items_to_show`: The maximum number of items to show during the scrolling animation.
    ///    If `None`, the default value of 20 is used.
    pub fn smooth_scroll_to_end(&mut self, cx: &mut Cx, speed: f64, max_items_to_show: Option<usize>) {
        if self.items.is_empty() { return };

	let speed = speed * self.range_end as f64;
	self.smooth_scroll_to(cx, self.range_end, speed, max_items_to_show);
    }
}


impl Widget for PortalList {

    fn handle_event(&mut self, cx: &mut Cx, event: &Event, scope: &mut Scope) {
        let uid = self.widget_uid();
        
        let mut scroll_to = None;
        self.scroll_bar.handle_event_with(cx, event, &mut | _cx, action | {
            // snap the scrollbar to a top-index with scroll_pos 0
            if let ScrollBarAction::Scroll {scroll_pos, view_total, view_visible} = action {
                scroll_to = Some((scroll_pos, scroll_pos+0.5 >= view_total - view_visible))
            }
        });
        if let Some((scroll_to, at_end)) = scroll_to {
            if at_end && self.auto_tail{
                self.first_id = self.range_end.max(1) - 1;
                self.first_scroll = 0.0;
                self.tail_range = true;
            } else {
                self.tail_range = false;
            }

            self.first_id = ((scroll_to / self.scroll_bar.get_scroll_view_visible()) * self.view_window as f64) as usize;
            self.first_scroll = 0.0;
            cx.widget_action(uid, &scope.path, PortalListAction::Scroll);
            self.was_scrolling = false;
            self.area.redraw(cx);
        }

        for item in self.items.values_mut() {
            let item_uid = item.widget.widget_uid();
            cx.group_widget_actions(uid, item_uid, |cx|{
                item.widget.handle_event(cx, event, scope)
            });
        }
        
        match &mut self.scroll_state {
            ScrollState::ScrollingTo {target_id, delta, next_frame} => {
                if let Some(_) = next_frame.is_event(event) {
                    let target_id = *target_id;

                    let distance_to_target = target_id as isize - self.first_id as isize;
                    let target_passed = distance_to_target.signum() == delta.signum() as isize;
                    // check to see if we passed the target and fix it. this may happen if the delta is too high,
                    // so we can just correct the first id, since the animation isn't being smooth anyways.
                    if target_passed {
                        self.first_id = target_id;
                        self.area.redraw(cx);
                    }

                    let distance_to_target = target_id as isize - self.first_id as isize;

                    // If the target is under first_id (its bigger than it), and end is reached,
                    // first_id would never be the target, so we just take it as reached.
                    let target_visible_at_end = self.at_end && target_id > self.first_id;
                    let target_reached = distance_to_target == 0 || target_visible_at_end;

                    if !target_reached {
                        *next_frame = cx.new_next_frame();
                        let delta = *delta;
                        // Don't enable the pulldown animation when scrolling to a specific item.
                        self.delta_top_scroll(cx, delta, true, false);
                        cx.widget_action(uid, &scope.path, PortalListAction::Scroll);
                        self.area.redraw(cx);
                    } else {
                        self.was_scrolling = false;
                        self.scroll_state = ScrollState::Stopped;
                        cx.widget_action(uid, &scope.path, PortalListAction::SmoothScrollReached);
                    }
                }
            }
            ScrollState::Flick {delta, next_frame} => {
                if let Some(_) = next_frame.is_event(event) {
                    *delta = *delta * self.flick_scroll_decay;
                    if delta.abs()>self.flick_scroll_minimum {
                        *next_frame = cx.new_next_frame();
                        let delta = *delta;
                        self.delta_top_scroll(cx, delta, false, true);
                        cx.widget_action(uid, &scope.path, PortalListAction::Scroll);
                        self.area.redraw(cx);
                    } else {
                        self.was_scrolling = false;
                        self.scroll_state = ScrollState::Stopped;
                    }
                }
            }
            ScrollState::Pulldown {next_frame} => {
                if let Some(_) = next_frame.is_event(event) {
                    // we have to bounce back
                    if self.first_id == self.range_start && self.first_scroll > 0.0 {
                        self.first_scroll *= 0.85;
                        if self.first_scroll < 1.0 {
                            self.first_scroll = 0.0;
                            // the pulldown animation is finished
                            self.was_scrolling = false;
                            self.scroll_state = ScrollState::Stopped;
                        }
                        else {
                            *next_frame = cx.new_next_frame();
                            cx.widget_action(uid, &scope.path, PortalListAction::Scroll);
                        }
                        self.area.redraw(cx);
                    }
                    else {
                        self.was_scrolling = false;
                        self.scroll_state = ScrollState::Stopped;
                    }
                }
            }
            _=>()
        }
        let vi = self.vec_index;
        let is_scroll = if let Event::Scroll(_) = event {true} else {false};
        if self.scroll_bar.is_area_captured(cx){
            self.scroll_state = ScrollState::Stopped;
        }
        if !self.scroll_bar.is_area_captured(cx) || is_scroll{ 
            match event.hits_with_capture_overload(cx, self.area, self.capture_overload) {
                Hit::FingerScroll(e) => {
                    self.tail_range = false;
                    self.detect_tail_in_draw = true;
                    self.was_scrolling = false;
                    self.scroll_state = ScrollState::Stopped;
                    self.delta_top_scroll(cx, -e.scroll.index(vi), false, true);
                    cx.widget_action(uid, &scope.path, PortalListAction::Scroll);
                    self.area.redraw(cx);
                },
                
                Hit::KeyDown(ke) => match ke.key_code {
                    KeyCode::Home => {
                        self.first_id = 0;
                        self.first_scroll = 0.0;
                        self.tail_range = false;
                        self.update_scroll_bar(cx);
                        self.area.redraw(cx);
                    },
                    KeyCode::End => {
                        self.first_id = self.range_end.max(1) - 1;
                        self.first_scroll = 0.0;
                        if self.auto_tail {
                            self.tail_range = true;
                        }
                        self.update_scroll_bar(cx);
                        self.area.redraw(cx);
                    },
                    KeyCode::PageUp => {
                        self.first_id = self.first_id.max(self.view_window) - self.view_window;
                        self.first_scroll = 0.0;
                        self.tail_range = false;
                        self.update_scroll_bar(cx);
                        self.area.redraw(cx);
                    },
                    KeyCode::PageDown => {
                        self.first_id += self.view_window;
                        self.first_scroll = 0.0;
                        if self.first_id >= self.range_end.max(1) {
                            self.first_id = self.range_end.max(1) - 1;
                        }
                        self.detect_tail_in_draw = true;
                        self.update_scroll_bar(cx);
                        self.area.redraw(cx);
                    },
                    KeyCode::ArrowDown => {
                        self.first_id += 1;
                        if self.first_id >= self.range_end.max(1) {
                            self.first_id = self.range_end.max(1) - 1;
                        }
                        self.detect_tail_in_draw = true;
                        self.first_scroll = 0.0;
                        self.update_scroll_bar(cx);
                        self.area.redraw(cx);
                    },
                    KeyCode::ArrowUp => {
                        if self.first_id > 0 {
                            self.first_id -= 1;
                            if self.first_id < self.range_start {
                                self.first_id = self.range_start;
                            }
                            self.first_scroll = 0.0;
                            self.area.redraw(cx);
                            self.tail_range = false;
                            self.update_scroll_bar(cx);
                        }
                    },
                    _ => ()
                }
                Hit::FingerDown(fe) => {
                    // We allow other mouse buttons to grab key focus and stop the tail range behavior,
                    // but we only want the primary button (or touch) to actually scroll via dragging.

                    //log!("Finger down {} {}", e.time, e.abs);
                    if self.grab_key_focus {
                        cx.set_key_focus(self.area);
                    }
                    self.tail_range = false;
                    self.was_scrolling = match &self.scroll_state {
                        ScrollState::Drag { samples } => samples.len() > 1,
                        ScrollState::Stopped => false,
                        _ => true,
                    };
                    if self.drag_scrolling && fe.is_primary_hit() {
                        self.scroll_state = ScrollState::Drag {
                            samples: vec![ScrollSample{abs: fe.abs.index(vi), time: fe.time}]
                        };
                    }
                }
                Hit::FingerMove(e) => {
                    //log!("Finger move {} {}", e.time, e.abs);
                    cx.set_cursor(MouseCursor::Default);
                    match &mut self.scroll_state {
                        ScrollState::Drag {samples}=>{
                            let new_abs = e.abs.index(vi);
                            let old_sample = *samples.last().unwrap();
                            samples.push(ScrollSample{abs:new_abs, time:e.time});
                            if samples.len()>4{
                                samples.remove(0);
                            }
                            self.delta_top_scroll(cx, new_abs - old_sample.abs, false, false);
                            self.area.redraw(cx);
                        }
                        _=>()
                    }
                }
                Hit::FingerUp(fe) if fe.is_primary_hit() => {
                    //log!("Finger up {} {}", e.time, e.abs);
                    match &mut self.scroll_state {
                        ScrollState::Drag {samples}=>{
                            // alright so we need to see if in the last couple of samples
                            // we have a certain distance per time
                            let mut last = None;
                            let mut scaled_delta = 0.0;
                            let mut total_delta = 0.0;
                            for sample in samples.iter().rev(){
                                if last.is_none(){
                                    last = Some(sample);
                                }
                                else{
                                    total_delta += last.unwrap().abs - sample.abs;
                                    scaled_delta += (last.unwrap().abs - sample.abs)/ (last.unwrap().time - sample.time)
                                }
                            }
                            scaled_delta *= self.flick_scroll_scaling;
                            if self.first_id == self.range_start && self.first_scroll > 0.0 {
                                self.scroll_state = ScrollState::Pulldown {next_frame: cx.new_next_frame()};
                            }
                            else if total_delta.abs() > 10.0 && scaled_delta.abs() > self.flick_scroll_minimum{
                                
                                self.scroll_state = ScrollState::Flick {
                                    delta: scaled_delta.min(self.flick_scroll_maximum).max(-self.flick_scroll_maximum),
                                    next_frame: cx.new_next_frame()
                                };
                            }
                            else {
                                self.was_scrolling = false;
                                self.scroll_state = ScrollState::Stopped;
                            }
                        }
                        _=>()
                    }
                    // ok so. lets check our gap from 'drag'
                    // here we kinda have to take our last delta and animate it
                }
                Hit::KeyFocus(_) => {
                }
                Hit::KeyFocusLost(_) => {
                }
                _ => ()
            }
        }
    }
    
    fn draw_walk(&mut self, cx: &mut Cx2d, _scope:&mut Scope, walk: Walk) -> DrawStep {
        if self.draw_state.begin(cx, ListDrawState::Begin) {
            self.begin(cx, walk);
            return DrawStep::make_step()
        }
        // ok so if we are
        if let Some(_) = self.draw_state.get() {
            self.end(cx);
            self.draw_state.end();
        }
        DrawStep::done()
    }
}

impl PortalListRef {
    /// Sets the first item to be shown and its scroll offset.
    ///
    /// On the next draw pass, this PortalList will draw the item with the given `id`
    /// as the first item in the list, and will set the *scroll offset*
    /// (from the top of the viewport to the beginning of the first item)
    /// to the given value `s`.
    pub fn set_first_id_and_scroll(&self, id: usize, s: f64) {
        if let Some(mut inner) = self.borrow_mut() {
            inner.first_id = id;
            inner.first_scroll = s;
        }
    }
    
    /// Sets the first item to be shown by this PortalList to the item with the given `id`.
    pub fn set_first_id(&self, id: usize) {
        if let Some(mut inner) = self.borrow_mut() {
            inner.first_id = id;
        }
    }
    
    /// Returns the ID of the item currently shown as the first item in this PortalList.
    pub fn first_id(&self) -> usize {
        if let Some(inner) = self.borrow() {
            inner.first_id
        }
        else {
            0
        }
    }
    
    /// Enables whether the PortalList auto-tracks the last item in the list.
    ///
    /// If `true`, the PortalList will continually scroll to the last item in the list
    /// automatically, as new items are added.
    /// If `false`, the PortalList will not auto-scroll to the last item.
    pub fn set_tail_range(&self, tail_range: bool) {
        if let Some(mut inner) = self.borrow_mut() {
            inner.tail_range = tail_range
        }
    }

    /// See [`PortalList::is_at_end()`].
    pub fn is_at_end(&self) -> bool {
        let Some(inner) = self.borrow() else { return false };
        inner.is_at_end()
    }

    /// See [`PortalList::visible_items()`].
    pub fn visible_items(&self) -> usize {
        let Some(inner) = self.borrow() else { return 0 };
        inner.visible_items()
    }

    /// Returns whether this PortalList was scrolling when the most recent finger hit occurred.
    pub fn was_scrolling(&self) -> bool {
        self.borrow().is_some_and(|inner| inner.was_scrolling)
    }

    /// Returns whether the given `actions` contain an action indicating that this PortalList was scrolled.
    pub fn scrolled(&self, actions: &Actions) -> bool {
        if let PortalListAction::Scroll = actions.find_widget_action(self.widget_uid()).cast() {
            return true;
        }
        false
    }

    /// Returns the current scroll offset of this PortalList.
    ///
    /// See [`PortalListRef::set_first_id_and_scroll()`] for more information.
    pub fn scroll_position(&self) -> f64 {
        let Some(inner) = self.borrow_mut() else { return 0.0 };
        inner.first_scroll
    }
    
    /// See [`PortalList::item()`].
    pub fn item(&self, cx: &mut Cx, entry_id: usize, template: LiveId) -> WidgetRef {
        if let Some(mut inner) = self.borrow_mut(){
            inner.item(cx, entry_id, template)
        }
        else{
            WidgetRef::empty()
        }
    }

    /// See [`PortalList::item_with_existed()`].
    pub fn item_with_existed(&self, cx: &mut Cx, entry_id: usize, template: LiveId) -> (WidgetRef, bool) {
        if let Some(mut inner) = self.borrow_mut(){
            inner.item_with_existed(cx, entry_id, template)
        }
        else{
            (WidgetRef::empty(), false)
        }
    }

    /// See [`PortalList::get_item()`].
    pub fn get_item(&self, entry_id: usize) -> Option<(LiveId, WidgetRef)> {
        let Some(inner) = self.borrow() else { return None };
        inner.get_item(entry_id)
    }
    
    pub fn position_of_item(&self, cx:&Cx, entry_id: usize) -> Option<f64>{
        let Some(inner) = self.borrow() else { return None };
        inner.position_of_item(cx, entry_id)
    }
    
    pub fn items_with_actions(&self, actions: &Actions) -> ItemsWithActions {
        let mut set = Vec::new();
        self.items_with_actions_vec(actions, &mut set);
        set
    }
    
    fn items_with_actions_vec(&self, actions: &Actions, set: &mut ItemsWithActions) {
        let uid = self.widget_uid();
        if let Some(inner) = self.borrow() {
            for action in actions {
                if let Some(action) = action.as_widget_action(){
                    if let Some(group) = &action.group{
                        if group.group_uid == uid{
                            for (item_id, item) in inner.items.iter() {
                                if group.item_uid == item.widget.widget_uid(){
                                    set.push((*item_id, item.widget.clone()))
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    
    pub fn any_items_with_actions(&self, actions: &Actions)->bool {
        let uid = self.widget_uid();
        for action in actions {
            if let Some(action) = action.as_widget_action(){
                if let Some(group) = &action.group{
                    if group.group_uid == uid{
                        return true
                    }
                }
            }
        }
        false
    }

    /// Initiates a smooth scrolling animation to the specified target item in the list.
    ///
    /// ## Arguments
    /// * `target_id`: The ID (index) of the item to scroll to.
    /// * `speed`: A positive floating-point value that controls the speed of the animation.
    ///    The `speed` will always be treated as an absolute value, with the direction of the scroll
    ///    (up or down) determined by whether `target_id` is above or below the current item.
    /// * `max_items_to_show`: The maximum number of items to show during the scrolling animation.
    ///    If `None`, the default value of 20 is used.
    ///
    /// ## Example
    /// ```rust,ignore
    /// // Scrolls to item 42 at speed 100.0, including at most 30 items in the scroll animation.
    /// smooth_scroll_to(&mut cx, 42, 100.0, Some(30));
    /// ```
    pub fn smooth_scroll_to(&self, cx: &mut Cx, target_id: usize, speed: f64, max_items_to_show: Option<usize>) {
        let Some(mut inner) = self.borrow_mut() else { return };
	inner.smooth_scroll_to(cx, target_id, speed, max_items_to_show);
    }

    /// Returns the ID of the item that is currently being smoothly scrolled to, if any.
    pub fn is_smooth_scrolling(&self) -> Option<usize> {
        let Some(inner) = self.borrow_mut() else { return None };
        if let ScrollState::ScrollingTo { target_id, .. } = inner.scroll_state {
            Some(target_id)
        } else {
            None
        }
    }

    /// Returns whether the given `actions` contain an action indicating that this PortalList completed
    /// a smooth scroll, reaching the target.
    pub fn smooth_scroll_reached(&self, actions: &Actions) -> bool {
        if let PortalListAction::SmoothScrollReached = actions.find_widget_action(self.widget_uid()).cast() {
            return true;
        }
        false
    }

    /// Trigger an scrolling animation to the end of the list
    ///
    /// ## Arguments
    /// * `speed`: This value controls how fast the scrolling animation is.
    ///    Note: This number should be large enough to reach the end, so it is important to
    ///    test the passed number. TODO provide a better implementation to ensure that the end
    ///    is always reached, no matter the speed value.
    /// * `max_items_to_show`: The maximum number of items to show during the scrolling animation.
    ///    If `None`, the default value of 20 is used.
    pub fn smooth_scroll_to_end(&self, cx: &mut Cx, speed: f64, max_items_to_show: Option<usize>) {
        let Some(mut inner) = self.borrow_mut() else { return };

	inner.smooth_scroll_to_end(cx, speed, max_items_to_show);
    }

    /// It indicates if we have items not displayed towards the end of the list (below)
    /// For instance, it is useful to show or hide a "jump to the most recent" button
    /// on a chat messages list
    pub fn further_items_bellow_exist(&self) -> bool {
        let Some(inner) = self.borrow() else { return false };
        !(inner.at_end || inner.not_filling_viewport)
    }
}

type ItemsWithActions = Vec<(usize, WidgetRef)>;

impl PortalListSet {
    pub fn set_first_id(&self, id: usize) {
        for list in self.iter() {
            list.set_first_id(id)
        }
    }
    
    
    pub fn items_with_actions(&self, actions: &Actions) -> ItemsWithActions {
        let mut set = Vec::new();
        for list in self.iter() {
            list.items_with_actions_vec(actions, &mut set)
        }
        set
    }
}