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
// Copyright 2020 The Druid Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! A widget that can switch between one of many views, hiding the inactive ones.

use instant::Duration;
use std::collections::HashMap;
use std::fmt::Debug;
use std::hash::Hash;
use std::marker::PhantomData;
use std::rc::Rc;
use tracing::{instrument, trace};

use crate::commands::SCROLL_TO_VIEW;
use crate::kurbo::{Circle, Line};
use crate::widget::prelude::*;
use crate::widget::{Axis, Flex, Label, LabelText, LensScopeTransfer, Painter, Scope, ScopePolicy};
use crate::{theme, Affine, Data, Insets, Lens, Point, SingleUse, WidgetExt, WidgetPod};

type TabsScope<TP> = Scope<TabsScopePolicy<TP>, Box<dyn Widget<TabsState<TP>>>>;
type TabBodyPod<TP> = WidgetPod<<TP as TabsPolicy>::Input, <TP as TabsPolicy>::BodyWidget>;
type TabBarPod<TP> = WidgetPod<TabsState<TP>, Box<dyn Widget<TabsState<TP>>>>;
type TabIndex = usize;
type Nanos = u64;

/// Information about a tab that may be used by the TabPolicy to
/// drive the visual presentation and behaviour of its label
pub struct TabInfo<Input> {
    /// Name of the tab
    pub name: LabelText<Input>,
    /// Should the user be able to close the tab?
    pub can_close: bool,
}

impl<Input> TabInfo<Input> {
    /// Create a new TabInfo
    pub fn new(name: impl Into<LabelText<Input>>, can_close: bool) -> Self {
        TabInfo {
            name: name.into(),
            can_close,
        }
    }
}

/// A policy that determines how a Tabs instance derives its tabs from its app data.
pub trait TabsPolicy: Data {
    /// The identity of a tab.
    type Key: Hash + Eq + Clone;

    /// The input data that will:
    /// a) be used to determine the tabs present
    /// b) be the input data for all of the child widgets.
    type Input: Data;

    /// The common type for all body widgets in this set of tabs.
    /// A flexible default is Box<dyn Widget<Self::Input>>
    type BodyWidget: Widget<Self::Input>;

    /// The common type for all label widgets in this set of tabs
    /// Usually this would be Label<Self::Input>
    type LabelWidget: Widget<Self::Input>;

    /// The information required to build up this policy.
    /// This is to support policies where at least some tabs are provided up front during widget
    /// construction. If the Build type implements the AddTab trait, the add_tab and with_tab
    /// methods will be available on the Tabs instance to allow the
    /// It can be filled in with () by implementations that do not require it.
    type Build;

    /// Examining the input data, has the set of tabs present changed?
    /// Expected to be cheap, eg pointer or numeric comparison.
    fn tabs_changed(&self, old_data: &Self::Input, data: &Self::Input) -> bool;

    /// From the input data, return the new set of tabs
    fn tabs(&self, data: &Self::Input) -> Vec<Self::Key>;

    /// For this tab key, return the relevant tab information that will drive label construction
    fn tab_info(&self, key: Self::Key, data: &Self::Input) -> TabInfo<Self::Input>;

    /// For this tab key, return the body widget
    fn tab_body(&self, key: Self::Key, data: &Self::Input) -> Self::BodyWidget;

    /// Label widget for the tab.
    /// Usually implemented with a call to default_make_label ( can't default here because Self::LabelWidget isn't determined)
    fn tab_label(
        &self,
        key: Self::Key,
        info: TabInfo<Self::Input>,
        data: &Self::Input,
    ) -> Self::LabelWidget;

    /// Change the data to reflect the user requesting to close a tab.
    #[allow(unused_variables)]
    fn close_tab(&self, key: Self::Key, data: &mut Self::Input) {}

    #[allow(unused_variables)]
    /// Construct an instance of this TabsFromData from its Build type.
    /// The main use case for this is StaticTabs, where the tabs are provided by the app developer up front.
    fn build(build: Self::Build) -> Self {
        panic!("TabsPolicy::Build called on a policy that does not support incremental building")
    }

    /// A default implementation for make label, if you do not wish to construct a custom widget.
    fn default_make_label(info: TabInfo<Self::Input>) -> Label<Self::Input> {
        Label::new(info.name).with_text_color(theme::FOREGROUND_LIGHT)
    }
}

/// A TabsPolicy that allows the app developer to provide static tabs up front when building the
/// widget.
#[derive(Clone)]
pub struct StaticTabs<T> {
    // This needs be able to avoid cloning the widgets we are given -
    // as such it is Rc
    tabs: Rc<[InitialTab<T>]>,
}

impl<T> Default for StaticTabs<T> {
    fn default() -> Self {
        StaticTabs { tabs: Rc::new([]) }
    }
}

impl<T: Data> Data for StaticTabs<T> {
    fn same(&self, _other: &Self) -> bool {
        // Changing the tabs after construction shouldn't be possible for static tabs
        true
    }
}

impl<T: Data> TabsPolicy for StaticTabs<T> {
    type Key = usize;
    type Input = T;
    type BodyWidget = Box<dyn Widget<T>>;
    type LabelWidget = Label<T>;
    type Build = Vec<InitialTab<T>>;

    fn tabs_changed(&self, _old_data: &T, _data: &T) -> bool {
        false
    }

    fn tabs(&self, _data: &T) -> Vec<Self::Key> {
        (0..self.tabs.len()).collect()
    }

    fn tab_info(&self, key: Self::Key, _data: &T) -> TabInfo<Self::Input> {
        // This only allows a static tabs label to be retrieved once,
        // but as we never indicate that the tabs have changed,
        // it should only be called once per key.
        TabInfo::new(
            self.tabs[key]
                .name
                .take()
                .expect("StaticTabs LabelText can only be retrieved once"),
            false,
        )
    }

    fn tab_body(&self, key: Self::Key, _data: &T) -> Self::BodyWidget {
        // This only allows a static tab to be retrieved once,
        // but as we never indicate that the tabs have changed,
        // it should only be called once per key.
        self.tabs
            .get(key)
            .and_then(|initial_tab| initial_tab.child.take())
            .expect("StaticTabs body widget can only be retrieved once")
    }

    fn tab_label(
        &self,
        _key: Self::Key,
        info: TabInfo<Self::Input>,
        _data: &Self::Input,
    ) -> Self::LabelWidget {
        Self::default_make_label(info)
    }

    fn build(build: Self::Build) -> Self {
        StaticTabs { tabs: build.into() }
    }
}

/// AddTabs is an extension to TabsPolicy.
/// If a policy implements AddTab, then the add_tab and with_tab methods will be available on
/// the Tabs instance.
pub trait AddTab: TabsPolicy {
    /// Add a tab to the build type.
    fn add_tab(
        build: &mut Self::Build,
        name: impl Into<LabelText<Self::Input>>,
        child: impl Widget<Self::Input> + 'static,
    );
}

impl<T: Data> AddTab for StaticTabs<T> {
    fn add_tab(
        build: &mut Self::Build,
        name: impl Into<LabelText<T>>,
        child: impl Widget<T> + 'static,
    ) {
        build.push(InitialTab::new(name, child))
    }
}

/// This is the current state of the tabs widget as a whole.
/// This expands the input data to include a policy that determines how tabs are derived,
/// and the index of the currently selected tab
#[derive(Clone, Lens, Data)]
pub struct TabsState<TP: TabsPolicy> {
    inner: TP::Input,
    selected: TabIndex,
    policy: TP,
}

impl<TP: TabsPolicy> TabsState<TP> {
    /// Create a new TabsState
    pub fn new(inner: TP::Input, selected: usize, policy: TP) -> Self {
        TabsState {
            inner,
            selected,
            policy,
        }
    }
}

/// This widget is the tab bar. It contains widgets that when pressed switch the active tab.
struct TabBar<TP: TabsPolicy> {
    axis: Axis,
    edge: TabsEdge,
    tabs: Vec<(TP::Key, TabBarPod<TP>)>,
    hot: Option<TabIndex>,
    phantom_tp: PhantomData<TP>,
}

impl<TP: TabsPolicy> TabBar<TP> {
    /// Create a new TabBar widget.
    fn new(axis: Axis, edge: TabsEdge) -> Self {
        TabBar {
            axis,
            edge,
            tabs: vec![],
            hot: None,
            phantom_tp: Default::default(),
        }
    }

    fn find_idx(&self, pos: Point) -> Option<TabIndex> {
        let major_pix = self.axis.major_pos(pos);
        let axis = self.axis;
        let res = self
            .tabs
            .binary_search_by_key(&((major_pix * 10.) as i64), |(_, tab)| {
                let rect = tab.layout_rect();
                let far_pix = axis.major_pos(rect.origin()) + axis.major(rect.size());
                (far_pix * 10.) as i64
            });
        match res {
            Ok(idx) => Some(idx),
            Err(idx) if idx < self.tabs.len() => Some(idx),
            _ => None,
        }
    }

    fn ensure_tabs(&mut self, data: &TabsState<TP>) {
        ensure_for_tabs(&mut self.tabs, &data.policy, &data.inner, |policy, key| {
            let info = policy.tab_info(key.clone(), &data.inner);

            let can_close = info.can_close;

            let label = data
                .policy
                .tab_label(key.clone(), info, &data.inner)
                .lens(TabsState::<TP>::inner)
                .padding(Insets::uniform_xy(9., 5.));

            if can_close {
                let close_button = Painter::new(|ctx, _, env| {
                    let circ_bounds = ctx.size().to_rect().inset(-2.);
                    let cross_bounds = circ_bounds.inset(-5.);
                    if ctx.is_hot() {
                        ctx.render_ctx.fill(
                            Circle::new(
                                circ_bounds.center(),
                                f64::min(circ_bounds.height(), circ_bounds.width()) / 2.,
                            ),
                            &env.get(theme::BORDER_LIGHT),
                        );
                    }
                    let cross_color = &env.get(if ctx.is_hot() {
                        theme::BACKGROUND_DARK
                    } else {
                        theme::BORDER_LIGHT
                    });
                    ctx.render_ctx.stroke(
                        Line::new(
                            (cross_bounds.x0, cross_bounds.y0),
                            (cross_bounds.x1, cross_bounds.y1),
                        ),
                        cross_color,
                        2.,
                    );
                    ctx.render_ctx.stroke(
                        Line::new(
                            (cross_bounds.x1, cross_bounds.y0),
                            (cross_bounds.x0, cross_bounds.y1),
                        ),
                        cross_color,
                        2.,
                    );
                })
                .fix_size(20., 20.);

                let row = Flex::row()
                    .with_child(label)
                    .with_child(close_button.on_click(
                        move |_ctx, data: &mut TabsState<TP>, _env| {
                            data.policy.close_tab(key.clone(), &mut data.inner);
                        },
                    ));
                WidgetPod::new(Box::new(row))
            } else {
                WidgetPod::new(Box::new(label))
            }
        });
    }
}

impl<TP: TabsPolicy> Widget<TabsState<TP>> for TabBar<TP> {
    #[instrument(name = "TabBar", level = "trace", skip(self, ctx, event, data, env))]
    fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut TabsState<TP>, env: &Env) {
        match event {
            Event::MouseDown(e) => {
                if let Some(idx) = self.find_idx(e.pos) {
                    data.selected = idx;
                }
            }
            Event::MouseMove(e) => {
                let new_hot = if ctx.is_hot() {
                    self.find_idx(e.pos)
                } else {
                    None
                };
                if new_hot != self.hot {
                    self.hot = new_hot;
                    ctx.request_paint();
                }
            }
            _ => {}
        }

        for (_, tab) in self.tabs.iter_mut() {
            tab.event(ctx, event, data, env);
        }
    }

    #[instrument(name = "TabBar", level = "trace", skip(self, ctx, event, data, env))]
    fn lifecycle(
        &mut self,
        ctx: &mut LifeCycleCtx,
        event: &LifeCycle,
        data: &TabsState<TP>,
        env: &Env,
    ) {
        if let LifeCycle::WidgetAdded = event {
            self.ensure_tabs(data);
            ctx.children_changed();
        }

        for (_, tab) in self.tabs.iter_mut() {
            tab.lifecycle(ctx, event, data, env);
        }
    }

    #[instrument(name = "TabBar", level = "trace", skip(self, ctx, old_data, data, env))]
    fn update(
        &mut self,
        ctx: &mut UpdateCtx,
        old_data: &TabsState<TP>,
        data: &TabsState<TP>,
        env: &Env,
    ) {
        for (_, tab) in self.tabs.iter_mut() {
            tab.update(ctx, data, env)
        }

        if data.policy.tabs_changed(&old_data.inner, &data.inner) {
            self.ensure_tabs(data);
            ctx.children_changed();
        } else if old_data.selected != data.selected {
            ctx.request_paint();
        }
    }

    #[instrument(name = "TabBar", level = "trace", skip(self, ctx, bc, data, env))]
    fn layout(
        &mut self,
        ctx: &mut LayoutCtx,
        bc: &BoxConstraints,
        data: &TabsState<TP>,
        env: &Env,
    ) -> Size {
        let mut major: f64 = 0.;
        let mut minor: f64 = 0.;
        for (_, tab) in self.tabs.iter_mut() {
            let size = tab.layout(ctx, bc, data, env);
            tab.set_origin(ctx, self.axis.pack(major, 0.).into());
            major += self.axis.major(size);
            minor = minor.max(self.axis.minor(size));
        }
        let wanted = self.axis.pack(major.max(self.axis.major(bc.max())), minor);
        let size = bc.constrain(wanted);
        trace!("Computed size: {}", size);
        size
    }

    #[instrument(name = "TabBar", level = "trace", skip(self, ctx, data, env))]
    fn paint(&mut self, ctx: &mut PaintCtx, data: &TabsState<TP>, env: &Env) {
        let hl_thickness = 2.;
        let highlight = env.get(theme::PRIMARY_LIGHT);
        for (idx, (_, tab)) in self.tabs.iter_mut().enumerate() {
            let layout_rect = tab.layout_rect();
            let expanded_size = self.axis.pack(
                self.axis.major(layout_rect.size()),
                self.axis.minor(ctx.size()),
            );
            let rect = layout_rect.with_size(expanded_size);
            let bg = match (idx == data.selected, Some(idx) == self.hot) {
                (_, true) => env.get(theme::BUTTON_DARK),
                (true, false) => env.get(theme::BACKGROUND_LIGHT),
                _ => env.get(theme::BACKGROUND_DARK),
            };
            ctx.fill(rect, &bg);

            tab.paint(ctx, data, env);
            if idx == data.selected {
                let (maj_near, maj_far) = self.axis.major_span(rect);
                let (min_near, min_far) = self.axis.minor_span(rect);
                let minor_pos = if let TabsEdge::Trailing = self.edge {
                    min_near + (hl_thickness / 2.)
                } else {
                    min_far - (hl_thickness / 2.)
                };

                ctx.stroke(
                    Line::new(
                        self.axis.pack(maj_near, minor_pos),
                        self.axis.pack(maj_far, minor_pos),
                    ),
                    &highlight,
                    hl_thickness,
                )
            }
        }
    }
}

struct TabsTransitionState {
    previous_idx: TabIndex,
    current_time: u64,
    duration: Nanos,
    increasing: bool,
}

impl TabsTransitionState {
    fn new(previous_idx: TabIndex, duration: Nanos, increasing: bool) -> Self {
        TabsTransitionState {
            previous_idx,
            current_time: 0,
            duration,
            increasing,
        }
    }

    fn live(&self) -> bool {
        self.current_time < self.duration
    }

    fn fraction(&self) -> f64 {
        (self.current_time as f64) / (self.duration as f64)
    }

    fn previous_transform(&self, axis: Axis, main: f64) -> Affine {
        let x = if self.increasing {
            -main * self.fraction()
        } else {
            main * self.fraction()
        };
        Affine::translate(axis.pack(x, 0.))
    }

    fn selected_transform(&self, axis: Axis, main: f64) -> Affine {
        let x = if self.increasing {
            main * (1.0 - self.fraction())
        } else {
            -main * (1.0 - self.fraction())
        };
        Affine::translate(axis.pack(x, 0.))
    }
}

fn ensure_for_tabs<Content, TP: TabsPolicy + ?Sized>(
    contents: &mut Vec<(TP::Key, Content)>,
    policy: &TP,
    data: &TP::Input,
    f: impl Fn(&TP, TP::Key) -> Content,
) -> Vec<usize> {
    let mut existing_by_key: HashMap<TP::Key, Content> = contents.drain(..).collect();

    let mut existing_idx = Vec::new();
    for key in policy.tabs(data).into_iter() {
        let next = if let Some(child) = existing_by_key.remove(&key) {
            existing_idx.push(contents.len());
            child
        } else {
            f(policy, key.clone())
        };
        contents.push((key.clone(), next))
    }
    existing_idx
}

/// This widget is the tabs body. It shows the active tab, keeps other tabs hidden, and can
/// animate transitions between them.
struct TabsBody<TP: TabsPolicy> {
    children: Vec<(TP::Key, TabBodyPod<TP>)>,
    axis: Axis,
    transition: TabsTransition,
    transition_state: Option<TabsTransitionState>,
    phantom_tp: PhantomData<TP>,
}

impl<TP: TabsPolicy> TabsBody<TP> {
    fn new(axis: Axis, transition: TabsTransition) -> TabsBody<TP> {
        TabsBody {
            children: vec![],
            axis,
            transition,
            transition_state: None,
            phantom_tp: Default::default(),
        }
    }

    fn make_tabs(&mut self, data: &TabsState<TP>) -> Vec<usize> {
        ensure_for_tabs(
            &mut self.children,
            &data.policy,
            &data.inner,
            |policy, key| WidgetPod::new(policy.tab_body(key, &data.inner)),
        )
    }

    fn active_child(&mut self, state: &TabsState<TP>) -> Option<&mut TabBodyPod<TP>> {
        Self::child(&mut self.children, state.selected)
    }

    // Doesn't take self to allow separate borrowing
    fn child(
        children: &mut [(TP::Key, TabBodyPod<TP>)],
        idx: usize,
    ) -> Option<&mut TabBodyPod<TP>> {
        children.get_mut(idx).map(|x| &mut x.1)
    }

    fn child_pods(&mut self) -> impl Iterator<Item = &mut TabBodyPod<TP>> {
        self.children.iter_mut().map(|x| &mut x.1)
    }
}

impl<TP: TabsPolicy> Widget<TabsState<TP>> for TabsBody<TP> {
    #[instrument(name = "TabsBody", level = "trace", skip(self, ctx, event, data, env))]
    fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut TabsState<TP>, env: &Env) {
        if let Event::Notification(notification) = event {
            if notification.is(SCROLL_TO_VIEW)
                && Some(notification.route()) != self.active_child(data).map(|w| w.id())
            {
                // Ignore SCROLL_TO_VIEW requests from every widget except the active.
                ctx.set_handled();
            }
        } else if event.should_propagate_to_hidden() {
            for child in self.child_pods() {
                child.event(ctx, event, &mut data.inner, env);
            }
        } else if let Some(child) = self.active_child(data) {
            child.event(ctx, event, &mut data.inner, env);
        }

        if let (Some(t_state), Event::AnimFrame(interval)) = (&mut self.transition_state, event) {
            // We can get a high interval on the first frame due to other widgets or old animations.
            let interval = if t_state.current_time == 0 {
                1
            } else {
                *interval
            };

            t_state.current_time += interval;
            if t_state.live() {
                ctx.request_anim_frame();
            } else {
                self.transition_state = None;
            }
            ctx.request_paint();
        }
    }

    #[instrument(name = "TabsBody", level = "trace", skip(self, ctx, event, data, env))]
    fn lifecycle(
        &mut self,
        ctx: &mut LifeCycleCtx,
        event: &LifeCycle,
        data: &TabsState<TP>,
        env: &Env,
    ) {
        if let LifeCycle::WidgetAdded = event {
            self.make_tabs(data);
            ctx.children_changed();
        }

        if event.should_propagate_to_hidden() {
            for child in self.child_pods() {
                child.lifecycle(ctx, event, &data.inner, env);
            }
        } else if let Some(child) = self.active_child(data) {
            // Pick which events go to all and which just to active
            child.lifecycle(ctx, event, &data.inner, env);
        }
    }

    #[instrument(
        name = "TabsBody",
        level = "trace",
        skip(self, ctx, old_data, data, env)
    )]
    fn update(
        &mut self,
        ctx: &mut UpdateCtx,
        old_data: &TabsState<TP>,
        data: &TabsState<TP>,
        env: &Env,
    ) {
        let init = if data.policy.tabs_changed(&old_data.inner, &data.inner) {
            ctx.children_changed();
            Some(self.make_tabs(data))
        } else {
            None
        };

        if old_data.selected != data.selected {
            self.transition_state = self
                .transition
                .tab_changed(old_data.selected, data.selected);
            ctx.children_changed();

            if self.transition_state.is_some() {
                ctx.request_anim_frame();
            }
        }

        // Make sure to only pass events to initialised children
        if let Some(init) = init {
            for idx in init {
                if let Some(child) = Self::child(&mut self.children, idx) {
                    child.update(ctx, &data.inner, env)
                }
            }
        } else {
            for child in self.child_pods() {
                child.update(ctx, &data.inner, env);
            }
        }
    }

    #[instrument(name = "TabsBody", level = "trace", skip(self, ctx, bc, data, env))]
    fn layout(
        &mut self,
        ctx: &mut LayoutCtx,
        bc: &BoxConstraints,
        data: &TabsState<TP>,
        env: &Env,
    ) -> Size {
        let inner = &data.inner;
        // Laying out all children so events can be delivered to them.
        for child in self.child_pods() {
            child.layout(ctx, bc, inner, env);
            child.set_origin(ctx, Point::ORIGIN);
        }

        bc.max()
    }

    #[instrument(name = "TabsBody", level = "trace", skip(self, ctx, data, env))]
    fn paint(&mut self, ctx: &mut PaintCtx, data: &TabsState<TP>, env: &Env) {
        if let Some(trans) = &self.transition_state {
            let axis = self.axis;
            let size = ctx.size();
            let major = axis.major(size);
            ctx.clip(size.to_rect());

            let children = &mut self.children;
            if let Some(ref mut prev) = Self::child(children, trans.previous_idx) {
                ctx.with_save(|ctx| {
                    ctx.transform(trans.previous_transform(axis, major));
                    prev.paint_raw(ctx, &data.inner, env);
                })
            }
            if let Some(ref mut child) = Self::child(children, data.selected) {
                ctx.with_save(|ctx| {
                    ctx.transform(trans.selected_transform(axis, major));
                    child.paint_raw(ctx, &data.inner, env);
                })
            }
        } else if let Some(ref mut child) = Self::child(&mut self.children, data.selected) {
            child.paint_raw(ctx, &data.inner, env);
        }
    }
}

// This only needs to exist to be able to give a reasonable type to the TabScope
struct TabsScopePolicy<TP> {
    tabs_from_data: TP,
    selected: TabIndex,
}

impl<TP> TabsScopePolicy<TP> {
    fn new(tabs_from_data: TP, selected: TabIndex) -> Self {
        Self {
            tabs_from_data,
            selected,
        }
    }
}

impl<TP: TabsPolicy> ScopePolicy for TabsScopePolicy<TP> {
    type In = TP::Input;
    type State = TabsState<TP>;
    type Transfer = LensScopeTransfer<tabs_state_derived_lenses::inner<TP>, Self::In, Self::State>;

    fn create(self, inner: &Self::In) -> (Self::State, Self::Transfer) {
        (
            TabsState::new(inner.clone(), self.selected, self.tabs_from_data),
            LensScopeTransfer::new(Self::State::inner),
        )
    }
}

/// Determines whether the tabs will have a transition animation when a new tab is selected.
#[derive(Data, Copy, Clone, Debug, PartialOrd, PartialEq, Eq)]
pub enum TabsTransition {
    /// Change tabs instantly with no animation
    Instant,
    /// Slide tabs across in the appropriate direction. The argument is the duration in nanoseconds
    Slide(Nanos),
}

impl Default for TabsTransition {
    fn default() -> Self {
        TabsTransition::Slide(Duration::from_millis(250).as_nanos() as Nanos)
    }
}

impl TabsTransition {
    fn tab_changed(self, old: TabIndex, new: TabIndex) -> Option<TabsTransitionState> {
        match self {
            TabsTransition::Instant => None,
            TabsTransition::Slide(dur) => Some(TabsTransitionState::new(old, dur, old < new)),
        }
    }
}

/// Determines where the tab bar should be placed relative to the cross axis
#[derive(Debug, Copy, Clone, PartialEq, Eq, Data)]
pub enum TabsEdge {
    /// For horizontal tabs, top. For vertical tabs, left.
    Leading,
    /// For horizontal tabs, bottom. For vertical tabs, right.
    Trailing,
}

impl Default for TabsEdge {
    fn default() -> Self {
        Self::Leading
    }
}

pub struct InitialTab<T> {
    name: SingleUse<LabelText<T>>, // This is to avoid cloning provided label texts
    child: SingleUse<Box<dyn Widget<T>>>, // This is to avoid cloning provided tabs
}

impl<T: Data> InitialTab<T> {
    fn new(name: impl Into<LabelText<T>>, child: impl Widget<T> + 'static) -> Self {
        InitialTab {
            name: SingleUse::new(name.into()),
            child: SingleUse::new(child.boxed()),
        }
    }
}

#[allow(clippy::large_enum_variant)]
enum TabsContent<TP: TabsPolicy> {
    Building {
        tabs: TP::Build,
        index: TabIndex,
    },
    Complete {
        tabs: TP,
        index: TabIndex,
    },
    Running {
        scope: WidgetPod<TP::Input, TabsScope<TP>>,
    },
    Swapping,
}

/// A tabs widget.
///
/// The tabs can be provided up front, using Tabs::new() and add_tab()/with_tab().
///
/// Or, the tabs can be derived from the input data by implementing TabsPolicy, and providing it to
/// Tabs::from_policy()
///
/// ```
/// use druid::widget::{Tabs, Label, WidgetExt};
/// use druid::{Data, Lens};
///
/// #[derive(Data, Clone, Lens)]
/// struct AppState{
///     name: String
/// }
///
/// let tabs = Tabs::new()
///     .with_tab("Connection", Label::new("Connection information"))
///     .with_tab("Proxy", Label::new("Proxy settings"))
///     .lens(AppState::name);
///
///
/// ```
///
pub struct Tabs<TP: TabsPolicy> {
    axis: Axis,
    edge: TabsEdge,
    transition: TabsTransition,
    content: TabsContent<TP>,
}

impl<T: Data> Tabs<StaticTabs<T>> {
    /// Create a new Tabs widget, using the static tabs policy.
    /// Use with_tab or add_tab to configure the set of tabs available.
    pub fn new() -> Self {
        Tabs::building(Vec::new())
    }
}

impl<T: Data> Default for Tabs<StaticTabs<T>> {
    fn default() -> Self {
        Self::new()
    }
}

impl<TP: TabsPolicy> Tabs<TP> {
    fn of_content(content: TabsContent<TP>) -> Self {
        Tabs {
            axis: Axis::Horizontal,
            edge: Default::default(),
            transition: Default::default(),
            content,
        }
    }

    /// Create a Tabs widget using the provided policy.
    /// This is useful for tabs derived from data.
    pub fn for_policy(tabs: TP) -> Self {
        Self::of_content(TabsContent::Complete { tabs, index: 0 })
    }

    // This could be public if there is a case for custom policies that support static tabs - ie the AddTab method.
    // It seems very likely that the whole way we do dynamic vs static will change before that
    // becomes an issue.
    fn building(tabs_from_data: TP::Build) -> Self
    where
        TP: AddTab,
    {
        Self::of_content(TabsContent::Building {
            tabs: tabs_from_data,
            index: 0,
        })
    }

    /// Lay out the tab bar along the provided axis.
    pub fn with_axis(mut self, axis: Axis) -> Self {
        self.axis = axis;
        self
    }

    /// Put the tab bar on the specified edge of the cross axis.
    pub fn with_edge(mut self, edge: TabsEdge) -> Self {
        self.edge = edge;
        self
    }

    /// Use the provided transition when tabs change
    pub fn with_transition(mut self, transition: TabsTransition) -> Self {
        self.transition = transition;
        self
    }

    /// Available when the policy implements AddTab - e.g StaticTabs.
    /// Return this Tabs widget with the named tab added.
    pub fn with_tab(
        mut self,
        name: impl Into<LabelText<TP::Input>>,
        child: impl Widget<TP::Input> + 'static,
    ) -> Tabs<TP>
    where
        TP: AddTab,
    {
        self.add_tab(name, child);
        self
    }

    /// A builder-style method to specify the (zero-based) index of the selected tab.
    pub fn with_tab_index(mut self, idx: TabIndex) -> Self {
        self.set_tab_index(idx);
        self
    }

    /// Available when the policy implements AddTab - e.g StaticTabs.
    /// Return this Tabs widget with the named tab added.
    pub fn add_tab(
        &mut self,
        name: impl Into<LabelText<TP::Input>>,
        child: impl Widget<TP::Input> + 'static,
    ) where
        TP: AddTab,
    {
        if let TabsContent::Building { tabs, .. } = &mut self.content {
            TP::add_tab(tabs, name, child)
        } else {
            tracing::warn!("Can't add static tabs to a running or complete tabs instance!")
        }
    }

    /// The (zero-based) index of the currently selected tab.
    pub fn tab_index(&self) -> TabIndex {
        let index = match &self.content {
            TabsContent::Running { scope, .. } => scope.widget().state().map(|s| s.selected),
            TabsContent::Building { index, .. } | TabsContent::Complete { index, .. } => {
                Some(*index)
            }
            TabsContent::Swapping => None,
        };
        index.unwrap_or(0)
    }

    /// Set the selected (zero-based) tab index.
    ///
    /// This tab will become visible if it exists. If animations are enabled
    /// (and the widget is laid out), the tab transition will be animated.
    pub fn set_tab_index(&mut self, idx: TabIndex) {
        match &mut self.content {
            TabsContent::Running { scope, .. } => {
                if let Some(state) = scope.widget_mut().state_mut() {
                    state.selected = idx
                }
            }
            TabsContent::Building { index, .. } | TabsContent::Complete { index, .. } => {
                *index = idx;
            }
            TabsContent::Swapping => (),
        }
    }

    fn make_scope(&self, tabs_from_data: TP, idx: TabIndex) -> WidgetPod<TP::Input, TabsScope<TP>> {
        let tabs_bar = TabBar::new(self.axis, self.edge);
        let tabs_body = TabsBody::new(self.axis, self.transition)
            .padding(5.)
            .border(theme::BORDER_DARK, 0.5);
        let mut layout: Flex<TabsState<TP>> = Flex::for_axis(self.axis.cross());

        if let TabsEdge::Trailing = self.edge {
            layout.add_flex_child(tabs_body, 1.);
            layout.add_child(tabs_bar);
        } else {
            layout.add_child(tabs_bar);
            layout.add_flex_child(tabs_body, 1.);
        };

        WidgetPod::new(Scope::new(
            TabsScopePolicy::new(tabs_from_data, idx),
            Box::new(layout),
        ))
    }
}

impl<TP: TabsPolicy> Widget<TP::Input> for Tabs<TP> {
    #[instrument(name = "Tabs", level = "trace", skip(self, ctx, event, data, env))]
    fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut TP::Input, env: &Env) {
        if let TabsContent::Running { scope } = &mut self.content {
            scope.event(ctx, event, data, env);
        }
    }

    #[instrument(name = "Tabs", level = "trace", skip(self, ctx, event, data, env))]
    fn lifecycle(
        &mut self,
        ctx: &mut LifeCycleCtx,
        event: &LifeCycle,
        data: &TP::Input,
        env: &Env,
    ) {
        if let LifeCycle::WidgetAdded = event {
            let content = std::mem::replace(&mut self.content, TabsContent::Swapping);

            self.content = match content {
                TabsContent::Building { tabs, index } => {
                    ctx.children_changed();
                    TabsContent::Running {
                        scope: self.make_scope(TP::build(tabs), index),
                    }
                }
                TabsContent::Complete { tabs, index } => {
                    ctx.children_changed();
                    TabsContent::Running {
                        scope: self.make_scope(tabs, index),
                    }
                }
                _ => content,
            };
        }
        if let TabsContent::Running { scope } = &mut self.content {
            scope.lifecycle(ctx, event, data, env)
        }
    }

    #[instrument(name = "Tabs", level = "trace", skip(self, ctx, _old_data, data, env))]
    fn update(&mut self, ctx: &mut UpdateCtx, _old_data: &TP::Input, data: &TP::Input, env: &Env) {
        if let TabsContent::Running { scope } = &mut self.content {
            scope.update(ctx, data, env);
        }
    }

    #[instrument(name = "Tabs", level = "trace", skip(self, ctx, bc, data, env))]
    fn layout(
        &mut self,
        ctx: &mut LayoutCtx,
        bc: &BoxConstraints,
        data: &TP::Input,
        env: &Env,
    ) -> Size {
        if let TabsContent::Running { scope } = &mut self.content {
            let size = scope.layout(ctx, bc, data, env);
            scope.set_origin(ctx, Point::ORIGIN);
            size
        } else {
            bc.min()
        }
    }

    #[instrument(name = "Tabs", level = "trace", skip(self, ctx, data, env))]
    fn paint(&mut self, ctx: &mut PaintCtx, data: &TP::Input, env: &Env) {
        if let TabsContent::Running { scope } = &mut self.content {
            scope.paint(ctx, data, env)
        }
    }
}