u0ui 0.3.17

Carbon UI: IBM Carbon v11 visuals with a shadcn-style API for GPUI Kit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
//! T3 · Files & preview: [`PreviewChrome`], [`PreviewEmptyState`],
//! [`MiniPlayer`] and [`DeviceControlsRail`] (`src/t3/workspace.jsx`,
//! "Preview" in `src/t3.css`); under a narrow chrome, [`PreviewStrip`] and
//! [`ForwardedPortNote`] (u0's TerminalBrowser and RightColumnStates boards).
use super::parts::{card_sub, child_id, icon_button};
use crate::{
    components::{
        Button, ButtonSize, ButtonVariant, DropdownMenu, DropdownMenuKind, DropdownMenuSize,
        MenuItem,
        floating::Align,
        menu::{self, MenuSize},
        overlay,
    },
    icons::{CarbonIcon, Icon},
    motion::{self, cubic_bezier_at},
    t3::{
        base::EASE_IN_OUT,
        craft::{mono, sans},
        press::{self, Handler, rem},
        shell::{ConnectionStatus, ConnectionStatusDot},
    },
    theme::{LayerLevel, color},
    tokens::ColorRole,
    typography::Phrase,
};
use gpui_kit::{
    Animation, AnimationExt as _, AnyElement, App, AppContext as _, CursorStyle, ElementId, Entity,
    Focusable as _, InteractiveElement as _, IntoElement, ParentElement, RenderOnce, SharedString,
    StatefulInteractiveElement as _, Styled, Window,
    component::{
        Sizable as _,
        input::{Input, InputState},
    },
    div,
    prelude::FluentBuilder as _,
    px, relative,
};
use std::{rc::Rc, time::Duration};

type IndexHandler = Rc<dyn Fn(usize, &mut Window, &mut App)>;

// ── PreviewChrome ───────────────────────────────────────────────────────

/// The viewports of the reference menu (`['Responsive', 'iPhone 16',
/// 'iPad', 'Desktop 1440']`).
pub const VIEWPORTS: [&str; 4] = ["Responsive", "iPhone 16", "iPad", "Desktop 1440"];

/// `@keyframes t3-load { from { left: -40% } to { left: 100% } }`, 1.2s
/// `ease-in-out`, a bar 40% wide.
pub const LOAD_PERIOD: Duration = Duration::from_millis(1200);
/// `.t3-pchrome-load { width: 40% }`.
pub const LOAD_WIDTH: f32 = 0.4;

/// The loading bar's `left` (a fraction of the field) at cycle progress `t`.
pub fn load_left(t: f32) -> f32 {
    let [x1, y1, x2, y2] = EASE_IN_OUT;
    -LOAD_WIDTH + (1. + LOAD_WIDTH) * cubic_bezier_at(x1, y1, x2, y2, t.clamp(0., 1.))
}

/// Texts of a [`PreviewChrome`] (hard-coded in the reference).
#[derive(Clone, Debug)]
pub struct PreviewChromeTexts {
    /// `Back`.
    pub back: SharedString,
    /// `Forward`.
    pub forward: SharedString,
    /// `Reload`.
    pub reload: SharedString,
    /// `Stop` (while loading).
    pub stop: SharedString,
    /// The address field's name (`Address`).
    pub address: SharedString,
    /// The viewport radio group's name (`Viewport`).
    pub viewport: SharedString,
    /// `Open in system browser`.
    pub open_external: SharedString,
    /// `More`.
    pub more: SharedString,
}

impl Default for PreviewChromeTexts {
    fn default() -> Self {
        Self {
            back: "Back".into(),
            forward: "Forward".into(),
            reload: "Reload".into(),
            stop: "Stop".into(),
            address: "Address".into(),
            viewport: "Viewport".into(),
            open_external: "Open in system browser".into(),
            more: "More".into(),
        }
    }
}

struct AddressState {
    input: Entity<InputState>,
    url: SharedString,
}

/// A [`PreviewChrome`]'s address field, made and kept by the caller to
/// reach it from outside the bar ([`PreviewChrome::address`]): an "Open an
/// address…" menu item focuses it with [`Self::focus`].
#[derive(Clone)]
pub struct PreviewAddress(Entity<AddressState>);

impl PreviewAddress {
    /// An empty address field; the chrome it is given to fills in its `url`.
    pub fn new(window: &mut Window, cx: &mut App) -> Self {
        let input = cx.new(|cx| InputState::new(window, cx));
        Self(cx.new(|_| AddressState {
            input,
            url: SharedString::default(),
        }))
    }

    /// Focus the field with its text selected, to type an address over it.
    pub fn focus(&self, window: &mut Window, cx: &mut App) {
        let input = self.0.read(cx).input.clone();
        input.update(cx, |s, cx| {
            s.focus(window, cx);
            s.select_all(window, cx);
        });
    }

    /// The field's focus handle.
    pub fn focus_handle(&self, cx: &App) -> gpui_kit::FocusHandle {
        self.0.read(cx).input.read(cx).focus_handle(cx)
    }

    /// The text in the field, typed or set.
    pub fn text(&self, cx: &App) -> SharedString {
        self.0.read(cx).input.read(cx).value().to_string().into()
    }
}

/// The built-in browser's toolbar (`PreviewChrome`, `.t3-pchrome`): back,
/// forward, reload or stop, the address field (a lock when `secure`, a
/// sliding 2px bar while `loading`), the zoom when not 100%, the viewport
/// menu, open in the system browser and more. 40px on `layer-01`. In a
/// narrow column (`narrow`) the viewport menu and open in the system browser
/// are left out, for the caller to offer elsewhere (in More, and a strip).
#[derive(IntoElement)]
pub struct PreviewChrome {
    id: ElementId,
    url: SharedString,
    loading: bool,
    secure: bool,
    zoom: u32,
    viewports: Vec<SharedString>,
    viewport: SharedString,
    can_back: bool,
    can_forward: bool,
    narrow: bool,
    more_menu: Vec<MenuItem>,
    address: Option<PreviewAddress>,
    texts: PreviewChromeTexts,
    on_back: Option<Handler>,
    on_forward: Option<Handler>,
    on_reload: Option<Handler>,
    on_stop: Option<Handler>,
    on_navigate: Option<super::parts::TextHandler>,
    on_viewport_change: Option<IndexHandler>,
    on_open_external: Option<Handler>,
    on_more: Option<Handler>,
}

impl PreviewChrome {
    /// A toolbar showing `url` (`http://localhost:5173` in the reference).
    pub fn new(id: impl Into<ElementId>, url: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            url: url.into(),
            loading: false,
            secure: false,
            zoom: 100,
            viewports: VIEWPORTS.iter().map(|v| SharedString::from(*v)).collect(),
            viewport: VIEWPORTS[0].into(),
            can_back: true,
            can_forward: false,
            narrow: false,
            more_menu: Vec::new(),
            address: None,
            texts: PreviewChromeTexts::default(),
            on_back: None,
            on_forward: None,
            on_reload: None,
            on_stop: None,
            on_navigate: None,
            on_viewport_change: None,
            on_open_external: None,
            on_more: None,
        }
    }

    /// Loading: Stop replaces Reload and the address bar slides (`loading`).
    pub fn loading(mut self, loading: bool) -> Self {
        self.loading = loading;
        self
    }

    /// A lock instead of the globe (`secure`).
    pub fn secure(mut self, secure: bool) -> Self {
        self.secure = secure;
        self
    }

    /// The zoom in percent (`zoom`, default 100: hidden).
    pub fn zoom(mut self, zoom: u32) -> Self {
        self.zoom = zoom;
        self
    }

    /// The viewport shown on the menu button (`viewport`, default `Responsive`).
    pub fn viewport(mut self, viewport: impl Into<SharedString>) -> Self {
        self.viewport = viewport.into();
        self
    }

    /// Replace the viewport list ([`VIEWPORTS`]).
    pub fn viewports<S: Into<SharedString>>(mut self, list: impl IntoIterator<Item = S>) -> Self {
        self.viewports = list.into_iter().map(Into::into).collect();
        self
    }

    /// Whether Back is enabled (default true).
    pub fn can_back(mut self, can: bool) -> Self {
        self.can_back = can;
        self
    }

    /// Whether Forward is enabled (default false, as in the reference).
    pub fn can_forward(mut self, can: bool) -> Self {
        self.can_forward = can;
        self
    }

    /// Leave out the viewport menu and open in the system browser, so the
    /// address keeps its room in a narrow column (the board's 400px right
    /// column, `.pv-chrome`). Default false.
    pub fn narrow(mut self, narrow: bool) -> Self {
        self.narrow = narrow;
        self
    }

    /// What More opens: an overflow menu of these items (hanging from
    /// its end edge) instead of calling `on_more`.
    pub fn more_menu(mut self, items: impl IntoIterator<Item = MenuItem>) -> Self {
        self.more_menu = items.into_iter().collect();
        self
    }

    /// The address field the caller keeps, to focus it from elsewhere (a
    /// menu item); by default the chrome keeps its own.
    pub fn address(mut self, address: &PreviewAddress) -> Self {
        self.address = Some(address.clone());
        self
    }

    /// Replace the default texts.
    pub fn texts(mut self, texts: PreviewChromeTexts) -> Self {
        self.texts = texts;
        self
    }

    /// Back pressed.
    pub fn on_back(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
        self.on_back = Some(Rc::new(f));
        self
    }

    /// Forward pressed.
    pub fn on_forward(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
        self.on_forward = Some(Rc::new(f));
        self
    }

    /// Reload pressed.
    pub fn on_reload(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
        self.on_reload = Some(Rc::new(f));
        self
    }

    /// Stop pressed (while loading).
    pub fn on_stop(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
        self.on_stop = Some(Rc::new(f));
        self
    }

    /// Enter in the address field, with its text.
    pub fn on_navigate(
        mut self,
        f: impl Fn(SharedString, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_navigate = Some(Rc::new(f));
        self
    }

    /// A viewport picked, with its index.
    pub fn on_viewport_change(
        mut self,
        f: impl Fn(usize, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_viewport_change = Some(Rc::new(f));
        self
    }

    /// Open in system browser pressed.
    pub fn on_open_external(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
        self.on_open_external = Some(Rc::new(f));
        self
    }

    /// More pressed.
    pub fn on_more(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
        self.on_more = Some(Rc::new(f));
        self
    }
}

fn click(b: Button, f: Option<Handler>) -> Button {
    match f {
        Some(f) => b.on_click(move |_, w, cx| f(w, cx)),
        None => b,
    }
}

impl RenderOnce for PreviewChrome {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let id = self.id.clone();
        let state = match &self.address {
            Some(address) => address.0.clone(),
            None => window.use_keyed_state((id.clone(), "address"), cx, {
                let url = self.url.clone();
                move |window, cx| AddressState {
                    input: cx.new(|cx| InputState::new(window, cx).default_value(url.clone())),
                    url,
                }
            }),
        };
        // A new `url` prop replaces the field's text (`defaultValue` per mount).
        if state.read(cx).url != self.url {
            let input = state.read(cx).input.clone();
            let url = self.url.clone();
            input.update(cx, |s, cx| s.set_value(url.clone(), window, cx));
            state.update(cx, |s, _| s.url = url);
        }
        let input = state.read(cx).input.clone();
        let focused = input.read(cx).focus_handle(cx).is_focused(window);
        let reduced = motion::reduced_motion(cx);

        let load_bar = self.loading.then(|| {
            let bar = div()
                .absolute()
                .bottom(px(-1.))
                .h(px(2.))
                .bg(color(ColorRole::Interactive));
            if reduced {
                // `ghost.css`: `@media (prefers-reduced-motion: reduce) { * {
                // animation-duration: 1ms !important; animation-iteration-count: 1
                // !important } }` (`.t3-pchrome-load` is not in its `g-pulse` list):
                // `t3-load` ends at once and the bar rests at its base box,
                // `left: 0; width: 40%`.
                bar.left_0().w(relative(LOAD_WIDTH)).into_any_element()
            } else {
                // `.t3-pchrome-load { position: absolute; left: 0; bottom: -1px; height: 2px;
                // width: 40%; background: interactive; animation: t3-load 1.2s ease-in-out infinite }`.
                bar.w(relative(LOAD_WIDTH))
                    .with_animation(
                        (id.clone(), "load"),
                        Animation::new(LOAD_PERIOD).repeat(),
                        |bar, t| bar.left(relative(load_left(t))),
                    )
                    .into_any_element()
            }
        });

        let on_navigate = self.on_navigate.clone();
        // `.t3-pchrome-url { position: relative; display: flex; flex: 1; align-items: center;
        // gap: spacing-03; height: size-sm; margin: 0 spacing-03; padding: 0 spacing-04;
        // background: field-02; border-bottom: 1px solid border-strong-01; overflow: hidden;
        // min-width: 8rem }`.
        let address = div()
            .relative()
            .flex()
            .flex_row()
            .flex_1()
            .min_w(rem(128.))
            .items_center()
            .gap(rem(8.))
            .h(rem(32.))
            .mx(rem(8.))
            .px(rem(12.))
            .bg(color(ColorRole::Field02))
            .border_b_1()
            .border_color(color(ColorRole::BorderStrong01))
            .overflow_hidden()
            .child(
                press::icon(
                    if self.secure {
                        CarbonIcon::Locked
                    } else {
                        CarbonIcon::Earth
                    },
                    14.,
                    color(ColorRole::IconSecondary),
                )
                .flex_none(),
            )
            .child(
                // `input { flex: 1; font-family: mono; font-size: 0.75rem }`.
                mono(div(), 12., 400)
                    .flex()
                    .flex_1()
                    .min_w_0()
                    .h_full()
                    .items_center()
                    .text_color(color(ColorRole::TextPrimary))
                    .on_key_down({
                        let input = input.clone();
                        move |event, window, cx| {
                            if event.keystroke.key == "enter"
                                && let Some(f) = on_navigate.as_ref()
                            {
                                let text: SharedString = input.read(cx).value().to_string().into();
                                f(text, window, cx);
                            }
                        }
                    })
                    .child(
                        Input::new(&input)
                            .appearance(false)
                            .with_size(gpui_kit::component::Size::XSmall)
                            .aria_label(self.texts.address.clone())
                            .p_0()
                            .h_full()
                            .w_full()
                            .text_size(rem(12.))
                            .line_height(relative(crate::t3::craft::BODY_LINE)),
                    ),
            )
            .children(load_bar)
            // `:focus-within { outline: 2px solid focus; outline-offset: -2px }`.
            .when(focused, |this| this.child(press::ring()));

        let picked = self.viewports.iter().position(|v| *v == self.viewport);
        let on_viewport = self.on_viewport_change.clone();
        let menu = DropdownMenu::new((id.clone(), "viewport"))
            .label(self.viewport.clone())
            .kind(DropdownMenuKind::Ghost)
            .size(DropdownMenuSize::Sm)
            .item({
                let item =
                    MenuItem::radio_group(self.texts.viewport.clone(), self.viewports.clone())
                        .selected_item(picked);
                match on_viewport {
                    Some(f) => item.on_select_item(move |i, w, cx| f(i, w, cx)),
                    None => item,
                }
            });

        // `.t3-pchrome { display: flex; align-items: center; gap: 2px; height: size-md;
        // padding: 0 spacing-02; background: layer-01; border-bottom: 1px solid border-subtle-01 }`.
        div()
            .id(id.clone())
            .flex()
            .flex_row()
            .items_center()
            .gap(px(2.))
            .w_full()
            .h(rem(40.))
            .px(rem(4.))
            .bg(color(ColorRole::Layer01))
            .border_b_1()
            .border_color(color(ColorRole::BorderSubtle01))
            .child(click(
                icon_button(
                    (id.clone(), "back"),
                    self.texts.back.clone(),
                    CarbonIcon::ArrowLeft,
                )
                .disabled(!self.can_back),
                self.on_back.clone(),
            ))
            .child(click(
                icon_button(
                    (id.clone(), "forward"),
                    self.texts.forward.clone(),
                    CarbonIcon::ArrowRight,
                )
                .disabled(!self.can_forward),
                self.on_forward.clone(),
            ))
            .child(if self.loading {
                click(
                    icon_button(
                        (id.clone(), "stop"),
                        self.texts.stop.clone(),
                        CarbonIcon::Close,
                    ),
                    self.on_stop.clone(),
                )
            } else {
                click(
                    icon_button(
                        (id.clone(), "reload"),
                        self.texts.reload.clone(),
                        CarbonIcon::Renew,
                    ),
                    self.on_reload.clone(),
                )
            })
            .child(address)
            .when(self.zoom != 100, |this| {
                // `.t3-zoom { padding: 0 spacing-03; font-size: 0.75rem; color: text-secondary }`.
                this.child(
                    sans(div(), 12., 400)
                        .flex_none()
                        .px(rem(8.))
                        .text_color(color(ColorRole::TextSecondary))
                        .child(SharedString::from(format!("{}%", self.zoom))),
                )
            })
            .when(!self.narrow, |this| {
                this.child(div().flex_none().child(menu)).child(click(
                    icon_button(
                        (id.clone(), "external"),
                        self.texts.open_external.clone(),
                        CarbonIcon::Launch,
                    ),
                    self.on_open_external.clone(),
                ))
            })
            .child(if self.more_menu.is_empty() {
                click(
                    icon_button(
                        (id.clone(), "more"),
                        self.texts.more.clone(),
                        CarbonIcon::OverflowMenuVertical,
                    ),
                    self.on_more.clone(),
                )
                .into_any_element()
            } else {
                more_menu(
                    (id.clone(), "more"),
                    self.texts.more,
                    self.more_menu,
                    window,
                    cx,
                )
            })
    }
}

/// More as an overflow menu of `items`, hanging from its end edge: it is
/// the last control of the bar, at the column's end.
fn more_menu(
    id: impl Into<ElementId>,
    label: SharedString,
    items: Vec<MenuItem>,
    window: &mut Window,
    cx: &mut App,
) -> AnyElement {
    let id = id.into();
    let openness = overlay::openness(&id, None, false, None, window, cx);
    let (open, set_open) = (openness.open, openness.setter());
    let trigger = overlay::trigger_wrapper(
        (id.clone(), "trigger"),
        icon_button(
            (id.clone(), "button"),
            label.clone(),
            CarbonIcon::OverflowMenuVertical,
        )
        .tooltip(!open)
        .selected(open)
        .into_any_element(),
        {
            let set_open = set_open.clone();
            Rc::new(move |window, cx| set_open(!open, window, cx))
        },
    )
    .into_any_element();
    menu::anchored_menu_aligned(
        &id,
        trigger,
        menu::MenuSpec {
            items,
            size: MenuSize::Sm,
            label,
            open,
            set_open,
            min_width: None,
            on_unhandled_key: None,
        },
        true,
        window,
        cx,
    )
}

// ── PreviewStrip ────────────────────────────────────────────────────────

/// `.pv-strip { min-height: 36px }`.
pub const STRIP_HEIGHT: f32 = 36.;
/// The servers' menu's width (`.pv-pop[aria-label="Dev servers"] { width:
/// 336px }`, the TerminalBrowser board): room for each server's second line.
pub const STRIP_MENU_WIDTH: f32 = 336.;

/// The strip under a narrow [`PreviewChrome`] (`.pv-strip`, the
/// TerminalBrowser board): the dev server the page is of, as a chip whose
/// menu switches to another, the machine it runs on, and one action (open
/// in your browser). Its dot says whether the server answers.
#[derive(IntoElement)]
pub struct PreviewStrip {
    id: ElementId,
    name: SharedString,
    port: Option<u16>,
    answering: bool,
    menu_label: SharedString,
    heading: bool,
    servers: Vec<MenuItem>,
    machine: SharedString,
    action: Option<(SharedString, Handler)>,
}

impl PreviewStrip {
    /// A strip for the server `name` (`dev`), listening on `port`.
    pub fn new(id: impl Into<ElementId>, name: impl Into<SharedString>, port: Option<u16>) -> Self {
        Self {
            id: id.into(),
            name: name.into(),
            port,
            answering: true,
            menu_label: SharedString::default(),
            heading: false,
            servers: Vec::new(),
            machine: SharedString::default(),
            action: None,
        }
    }

    /// The servers the chip's menu offers, and the menu's accessible name.
    pub fn servers(
        mut self,
        label: impl Into<SharedString>,
        items: impl IntoIterator<Item = MenuItem>,
    ) -> Self {
        self.menu_label = label.into();
        self.servers = items.into_iter().collect();
        self
    }

    /// Show the menu's name as its heading, above the servers (`.pv-pop-h`:
    /// `Dev servers your terminals printed`). Default false: the name is
    /// only read aloud.
    pub fn heading(mut self, heading: bool) -> Self {
        self.heading = heading;
        self
    }

    /// Whether the server answers (it does unless told otherwise): its
    /// dot is green while it does, red while it does not.
    pub fn answering(mut self, answering: bool) -> Self {
        self.answering = answering;
        self
    }

    /// The machine the server runs on (`This Mac`).
    pub fn machine(mut self, machine: impl Into<SharedString>) -> Self {
        self.machine = machine.into();
        self
    }

    /// The action at the end: a ghost button with the launch icon.
    pub fn action(
        mut self,
        label: impl Into<SharedString>,
        f: impl Fn(&mut Window, &mut App) + 'static,
    ) -> Self {
        self.action = Some((label.into(), Rc::new(f)));
        self
    }
}

impl RenderOnce for PreviewStrip {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let id = self.id.clone();
        let openness = overlay::openness(&id, None, false, None, window, cx);
        let (open, set_open) = (openness.open, openness.setter());
        let primary = color(ColorRole::TextPrimary);
        // `.pv-srv { display: inline-flex; align-items: center; gap: 6px; height: 32px;
        // padding: 0 8px; background: layer-selected-01; font-size: 12px; color:
        // text-primary; cursor: pointer }`, `b { font-weight: 600 }`, `.pv-dot { 8px;
        // border-radius: 50%; background: support-success }`.
        let chip = sans(div(), 12., 400)
            .flex()
            .flex_row()
            .items_center()
            .gap(px(6.))
            .h(px(32.))
            .px(px(8.))
            .bg(color(ColorRole::LayerSelected01))
            .text_color(primary)
            .cursor(CursorStyle::PointingHand)
            .child(
                div()
                    .size(px(8.))
                    .flex_none()
                    .rounded_full()
                    .bg(color(dot(self.answering))),
            )
            .child(
                div()
                    .flex()
                    .child(sans(div(), 12., 600).child(self.name.clone()))
                    .children(self.port.map(|p| SharedString::from(format!(":{p}")))),
            )
            .child(press::icon(CarbonIcon::ChevronDown, 16., primary));
        let trigger = overlay::trigger_wrapper((id.clone(), "server"), chip.into_any_element(), {
            let set_open = set_open.clone();
            Rc::new(move |window, cx| set_open(!open, window, cx))
        })
        .into_any_element();
        let items = strip_items(self.heading, &self.menu_label, self.servers);
        let server = menu::anchored_menu(
            &id,
            trigger,
            menu::MenuSpec {
                items,
                size: MenuSize::Sm,
                label: self.menu_label,
                open,
                set_open,
                min_width: Some(STRIP_MENU_WIDTH),
                on_unhandled_key: None,
            },
            window,
            cx,
        );
        // `.pv-strip { display: flex; align-items: center; gap: 4px; min-height: 36px;
        // padding: 0 4px 0 8px; border-bottom: 1px solid border-subtle-01; font-size:
        // 12px; line-height: 16px; color: text-secondary }`; the machine
        // (`.pv-strip > span`) takes the room left and ellipsizes.
        div()
            .id(id.clone())
            .flex()
            .flex_row()
            .flex_none()
            .items_center()
            .gap(px(4.))
            .min_h(px(STRIP_HEIGHT))
            .pl(px(8.))
            .pr(px(4.))
            .border_b_1()
            .border_color(color(ColorRole::BorderSubtle01))
            .child(server)
            .child(
                sans(div(), 12., 400)
                    .flex_1()
                    .min_w_0()
                    .truncate()
                    .text_color(color(ColorRole::TextSecondary))
                    .child(self.machine),
            )
            .children(self.action.map(|(label, f)| {
                Button::new((id.clone(), "action"), label)
                    .variant(ButtonVariant::Ghost)
                    .size(ButtonSize::Sm)
                    .icon(CarbonIcon::Launch)
                    .on_click(move |_, w, cx| f(w, cx))
            }))
    }
}

/// The strip's menu: its servers, under its name when it is shown.
fn strip_items(heading: bool, label: &SharedString, servers: Vec<MenuItem>) -> Vec<MenuItem> {
    heading
        .then(|| MenuItem::heading(label.clone()))
        .into_iter()
        .chain(servers)
        .collect()
}

// ── ForwardedPortNote ───────────────────────────────────────────────────

/// `.pv-fwd { padding: 8px 8px 8px 12px }` (top, end, bottom, start).
pub const NOTE_PADDING: [f32; 4] = [8., 8., 8., 12.];
/// `.pv-fwd svg { margin-top: 8px }`, `.pv-fwd > span { padding-top: 8px }`:
/// the icon and words level with the 32px button's label.
pub const NOTE_TEXT_TOP: f32 = 8.;

/// Under a [`PreviewStrip`], for a page of a server on another machine
/// whose port is brought here (`.pv-fwd`, the RightColumnStates board): a
/// plug, what is forwarded where (its address in mono), and one ghost
/// action (Stop). On `layer-02`, ruled off below.
#[derive(IntoElement)]
pub struct ForwardedPortNote {
    id: ElementId,
    text: Phrase,
    action: Option<(SharedString, Handler)>,
}

impl ForwardedPortNote {
    /// A note saying `text` (`Port 6006 on build-box, forwarded to
    /// 127.0.0.1:41873 …`; [`Phrase::marking`] sets its address as code).
    pub fn new(id: impl Into<ElementId>, text: impl Into<Phrase>) -> Self {
        Self {
            id: id.into(),
            text: text.into(),
            action: None,
        }
    }

    /// The action at the end: a small ghost button (`Stop`).
    pub fn action(
        mut self,
        label: impl Into<SharedString>,
        f: impl Fn(&mut Window, &mut App) + 'static,
    ) -> Self {
        self.action = Some((label.into(), Rc::new(f)));
        self
    }
}

impl RenderOnce for ForwardedPortNote {
    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
        let id = self.id.clone();
        let [top, end, bottom, start] = NOTE_PADDING;
        // `.pv-fwd { display: flex; align-items: flex-start; gap: 8px; flex-shrink: 0;
        // border-bottom: 1px solid border-subtle-01; background: layer-02;
        // font-size: 12px; line-height: 16px; color: text-secondary }`.
        sans(div(), 12., 400)
            .id(id.clone())
            .flex()
            .flex_row()
            .flex_none()
            .items_start()
            .gap(px(8.))
            .pt(px(top))
            .pr(px(end))
            .pb(px(bottom))
            .pl(px(start))
            .line_height(px(16.))
            .border_b_1()
            .border_color(color(ColorRole::BorderSubtle01))
            .bg(color(ColorRole::Layer02))
            // `.pv-fwd svg { fill: icon-secondary; flex: none; margin-top: 8px }`.
            .child(div().flex_none().mt(px(NOTE_TEXT_TOP)).child(press::icon(
                CarbonIcon::Plug,
                16.,
                color(ColorRole::IconSecondary),
            )))
            // `.pv-fwd > span { flex: 1; min-width: 0; padding-top: 8px }`.
            .child(
                div()
                    .flex_1()
                    .min_w_0()
                    .pt(px(NOTE_TEXT_TOP))
                    .child(self.text.styled(400, color(ColorRole::TextSecondary))),
            )
            .children(self.action.map(|(label, f)| {
                Button::new((id.clone(), "action"), label)
                    .variant(ButtonVariant::Ghost)
                    .size(ButtonSize::Sm)
                    .on_click(move |_, w, cx| f(w, cx))
            }))
    }
}

// ── PreviewEmptyState ───────────────────────────────────────────────────

/// A local dev server (`servers[]`: `{ port, name }`).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LocalServer {
    /// `port`.
    pub port: u16,
    /// `name`.
    pub name: SharedString,
}

impl LocalServer {
    /// A server on `port`.
    pub fn new(port: u16, name: impl Into<SharedString>) -> Self {
        Self {
            port,
            name: name.into(),
        }
    }
}

/// Texts of a [`PreviewEmptyState`] (hard-coded in the reference).
#[derive(Clone, Debug)]
pub struct PreviewEmptyTexts {
    /// `No preview yet`.
    pub title: SharedString,
    /// The explanation.
    pub body: SharedString,
    /// `Local servers`.
    pub servers: SharedString,
    /// `Recently used`.
    pub recent: SharedString,
}

impl Default for PreviewEmptyTexts {
    fn default() -> Self {
        Self {
            title: "No preview yet".into(),
            body: "Type a URL above, or run a dev script. Local servers this thread starts appear here."
                .into(),
            servers: "Local servers".into(),
            recent: "Recently used".into(),
        }
    }
}

/// The browser's empty state (`PreviewEmptyState`, `.t3-pempty`): a globe,
/// a heading and note, then cards for local servers (status dot, `:port`,
/// name) and recently used addresses.
#[derive(IntoElement)]
pub struct PreviewEmptyState {
    id: ElementId,
    servers: Vec<LocalServer>,
    recent: Vec<SharedString>,
    texts: PreviewEmptyTexts,
    on_server: Option<IndexHandler>,
    on_recent: Option<IndexHandler>,
}

impl PreviewEmptyState {
    /// An empty state.
    pub fn new(id: impl Into<ElementId>) -> Self {
        Self {
            id: id.into(),
            servers: Vec::new(),
            recent: Vec::new(),
            texts: PreviewEmptyTexts::default(),
            on_server: None,
            on_recent: None,
        }
    }

    /// Local servers (`servers`).
    pub fn servers(mut self, servers: impl IntoIterator<Item = LocalServer>) -> Self {
        self.servers = servers.into_iter().collect();
        self
    }

    /// Recent addresses (`recent`).
    pub fn recent<S: Into<SharedString>>(mut self, recent: impl IntoIterator<Item = S>) -> Self {
        self.recent = recent.into_iter().map(Into::into).collect();
        self
    }

    /// Replace the default texts.
    pub fn texts(mut self, texts: PreviewEmptyTexts) -> Self {
        self.texts = texts;
        self
    }

    /// A server card pressed, with its index.
    pub fn on_server(mut self, f: impl Fn(usize, &mut Window, &mut App) + 'static) -> Self {
        self.on_server = Some(Rc::new(f));
        self
    }

    /// A recent card pressed, with its index.
    pub fn on_recent(mut self, f: impl Fn(usize, &mut Window, &mut App) + 'static) -> Self {
        self.on_recent = Some(Rc::new(f));
        self
    }
}

/// `.t3-srvcard`: a 40px `layer-01` button card.
fn server_card(
    id: ElementId,
    label: SharedString,
    children: Vec<AnyElement>,
    on_click: Option<Handler>,
    window: &mut Window,
    cx: &mut App,
) -> AnyElement {
    let (hovered, store) = press::hover((id.clone(), "hover"), window, cx);
    let (focus, ring) = press::focus((id.clone(), "focus"), window, cx);
    // `.t3-srvcard { display: flex; align-items: center; gap: spacing-03; height: size-md;
    // padding: 0 spacing-04; background: layer-01; font-size: 0.875rem }`,
    // `:hover { background: layer-hover-01 }`.
    sans(
        gpui_kit::base::Button::new(id)
            .track_focus(&focus)
            .accessibility_label(label),
        14.,
        400,
    )
    .relative()
    .flex()
    .flex_row()
    .items_center()
    .gap(rem(8.))
    .h(rem(40.))
    .px(rem(12.))
    .bg(color(if hovered {
        ColorRole::LayerHover01
    } else {
        ColorRole::Layer01
    }))
    .text_color(color(ColorRole::TextPrimary))
    .cursor(CursorStyle::PointingHand)
    .on_hover(press::track_hover(store))
    .when_some(on_click, |this, f| this.on_click(move |_, w, cx| f(w, cx)))
    .children(children)
    .when(ring, |this| this.child(press::ring()))
    .into_any_element()
}

impl RenderOnce for PreviewEmptyState {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let id = self.id.clone();
        let secondary = color(ColorRole::TextSecondary);
        // `.t3-pempty-h { margin-top: spacing-05; font-size: 0.75rem; color: text-secondary }`.
        let heading = |text: SharedString| {
            sans(div(), 12., 400)
                .mt(rem(16.))
                .text_color(secondary)
                .child(text)
        };
        // `.t3-pempty-grid { display: flex; flex-wrap: wrap; gap: spacing-03 }`.
        let grid = || div().flex().flex_row().flex_wrap().gap(rem(8.));
        let span = |text: SharedString| div().text_color(secondary).child(text);
        let servers = self
            .servers
            .iter()
            .enumerate()
            .map(|(i, s)| {
                let f = self.on_server.clone();
                server_card(
                    child_id(&id, "server", i),
                    SharedString::from(format!(":{} {}", s.port, s.name)),
                    vec![
                        ConnectionStatusDot::new(ConnectionStatus::Connected)
                            .id(child_id(&id, "server-dot", i))
                            .into_any_element(),
                        // A bare `<b>` (Carbon's `b { font: inherit }`): 400.
                        sans(div(), 14., 400)
                            .child(SharedString::from(format!(":{}", s.port)))
                            .into_any_element(),
                        span(s.name.clone()).into_any_element(),
                    ],
                    f.map(|f| Rc::new(move |w: &mut Window, cx: &mut App| f(i, w, cx)) as Handler),
                    window,
                    cx,
                )
            })
            .collect::<Vec<_>>();
        let recent = self
            .recent
            .iter()
            .enumerate()
            .map(|(i, r)| {
                let f = self.on_recent.clone();
                server_card(
                    child_id(&id, "recent", i),
                    r.clone(),
                    vec![
                        press::icon(CarbonIcon::Time, 14., color(ColorRole::IconSecondary))
                            .flex_none()
                            .into_any_element(),
                        span(r.clone()).into_any_element(),
                    ],
                    f.map(|f| Rc::new(move |w: &mut Window, cx: &mut App| f(i, w, cx)) as Handler),
                    window,
                    cx,
                )
            })
            .collect::<Vec<_>>();
        // `.t3-pempty { display: flex; flex-direction: column; align-items: flex-start;
        // gap: spacing-03; max-width: 32rem; padding: spacing-07 spacing-05 }`.
        sans(div(), 14., 400)
            .id(id)
            .flex()
            .flex_col()
            .items_start()
            .gap(rem(8.))
            .max_w(rem(512.))
            .py(rem(32.))
            .px(rem(16.))
            .text_color(color(ColorRole::TextPrimary))
            .child(press::icon(
                CarbonIcon::Earth,
                32.,
                color(ColorRole::IconSecondary),
            ))
            // `h3 { margin: 0; font-size: 1.25rem; font-weight: 400 }`.
            .child(sans(div(), 20., 400).child(self.texts.title.clone()))
            // `p { margin: 0; font-size: 0.875rem; color: text-secondary }`; the
            // line height is Carbon's `p { line-height: var(--body-02-line-height, 1.5) }`
            // (`bundle.css`): 21px.
            .child(
                sans(div(), 14., 400)
                    .line_height(relative(1.5))
                    .text_color(secondary)
                    .child(self.texts.body.clone()),
            )
            .when(!servers.is_empty(), |this| {
                this.child(heading(self.texts.servers.clone()))
                    .child(grid().children(servers))
            })
            .when(!recent.is_empty(), |this| {
                this.child(heading(self.texts.recent.clone()))
                    .child(grid().children(recent))
            })
    }
}

// ── MiniPlayer ──────────────────────────────────────────────────────────

/// `MiniPlayer` `kind`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum MiniPlayerKind {
    /// `browser` (the default): a wireframe page and a globe.
    #[default]
    Browser,
    /// `device`: a phone outline.
    Device,
}

impl MiniPlayerKind {
    /// Both kinds.
    pub const ALL: [MiniPlayerKind; 2] = [Self::Browser, Self::Device];

    /// The reference name.
    pub const fn name(self) -> &'static str {
        match self {
            Self::Browser => "browser",
            Self::Device => "device",
        }
    }
}

/// Texts of a [`MiniPlayer`] (hard-coded in the reference).
#[derive(Clone, Debug)]
pub struct MiniPlayerTexts {
    /// `Expand`.
    pub expand: SharedString,
    /// `Close`.
    pub close: SharedString,
}

impl Default for MiniPlayerTexts {
    fn default() -> Self {
        Self {
            expand: "Expand".into(),
            close: "Close".into(),
        }
    }
}

/// The floating preview kept while you switch threads (`MiniPlayer`,
/// `.t3-mini`): an 18rem `layer-01` card with the floating shadow, a 9rem
/// screen and a 40px bar with title, subtitle, Expand and Close.
#[derive(IntoElement)]
pub struct MiniPlayer {
    id: ElementId,
    title: SharedString,
    subtitle: Option<SharedString>,
    kind: MiniPlayerKind,
    texts: MiniPlayerTexts,
    on_expand: Option<Handler>,
    on_close: Option<Handler>,
}

impl MiniPlayer {
    /// A mini player titled `title` (`Preview` in the reference).
    pub fn new(id: impl Into<ElementId>, title: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            title: title.into(),
            subtitle: None,
            kind: MiniPlayerKind::Browser,
            texts: MiniPlayerTexts::default(),
            on_expand: None,
            on_close: None,
        }
    }

    /// The subtitle (`subtitle`).
    pub fn subtitle(mut self, subtitle: impl Into<SharedString>) -> Self {
        self.subtitle = Some(subtitle.into());
        self
    }

    /// The kind (`kind`).
    pub fn kind(mut self, kind: MiniPlayerKind) -> Self {
        self.kind = kind;
        self
    }

    /// Replace the default texts.
    pub fn texts(mut self, texts: MiniPlayerTexts) -> Self {
        self.texts = texts;
        self
    }

    /// Expand pressed.
    pub fn on_expand(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
        self.on_expand = Some(Rc::new(f));
        self
    }

    /// Close pressed.
    pub fn on_close(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
        self.on_close = Some(Rc::new(f));
        self
    }
}

impl RenderOnce for MiniPlayer {
    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
        let id = self.id.clone();
        let screen = match self.kind {
            // `.t3-mini-phone { width: 3.5rem; height: 7rem; border: 3px solid icon-primary;
            // border-radius: 10px; background: layer-01 }`.
            MiniPlayerKind::Device => div()
                .w(rem(56.))
                .h(rem(112.))
                .border(px(3.))
                .border_color(color(ColorRole::IconPrimary))
                .rounded(px(10.))
                .bg(color(ColorRole::Layer01))
                .into_any_element(),
            // `.t3-mini-page { display: flex; flex-direction: column; gap: 6px; width: 70% }`,
            // `i { height: 10px; background: layer-01 }`, `i:first-child { width: 40%;
            // height: 14px; background: interactive }`.
            MiniPlayerKind::Browser => div()
                .flex()
                .flex_col()
                .gap(px(6.))
                .w(relative(0.7))
                .child(
                    div()
                        .w(relative(0.4))
                        .h(px(14.))
                        .bg(color(ColorRole::Interactive)),
                )
                .child(div().h(px(10.)).bg(color(ColorRole::Layer01)))
                .child(div().h(px(10.)).bg(color(ColorRole::Layer01)))
                .into_any_element(),
        };
        let glyph = match self.kind {
            MiniPlayerKind::Device => CarbonIcon::Mobile,
            MiniPlayerKind::Browser => CarbonIcon::Earth,
        };
        let on_expand = self.on_expand.clone();
        let on_close = self.on_close.clone();
        // `.t3-mini-bar > span { min-width: 0; white-space: nowrap; overflow: hidden;
        // text-overflow: ellipsis }`.
        let clip = |el: gpui_kit::Div| {
            el.min_w_0()
                .whitespace_nowrap()
                .overflow_hidden()
                .text_ellipsis()
        };
        // `.t3-mini { width: 18rem; max-width: 100%; background: layer-01;
        // box-shadow: 0 2px 6px var(--shadow); border-radius: 0 }`.
        div()
            .id(id.clone())
            .flex()
            .flex_col()
            .w(rem(288.))
            .max_w_full()
            .bg(color(ColorRole::Layer01))
            .shadow(crate::components::overlay::floating_shadow())
            .child(
                // `.t3-mini-screen { display: flex; height: 9rem; align-items: center;
                // justify-content: center; background: layer-accent-01 }`.
                div()
                    .flex()
                    .h(rem(144.))
                    .items_center()
                    .justify_center()
                    .bg(color(ColorRole::LayerAccent01))
                    .child(screen),
            )
            .child(
                // `.t3-mini-bar { display: flex; align-items: center; gap: spacing-03;
                // height: size-md; padding-left: spacing-04; font-size: 0.875rem }`.
                sans(div(), 14., 400)
                    .flex()
                    .flex_row()
                    .items_center()
                    .gap(rem(8.))
                    .h(rem(40.))
                    .pl(rem(12.))
                    .text_color(color(ColorRole::TextPrimary))
                    .child(press::icon(glyph, 14., color(ColorRole::IconSecondary)).flex_none())
                    .child(clip(sans(div(), 14., 600)).child(self.title.clone()))
                    .when_some(self.subtitle.clone(), |this, sub| {
                        this.child(clip(card_sub(sub)))
                    })
                    .child(div().flex_1())
                    .child(click(
                        icon_button(
                            (id.clone(), "expand"),
                            self.texts.expand.clone(),
                            CarbonIcon::Maximize,
                        ),
                        on_expand,
                    ))
                    .child(click(
                        icon_button(
                            (id.clone(), "close"),
                            self.texts.close.clone(),
                            CarbonIcon::Close,
                        ),
                        on_close,
                    )),
            )
    }
}

// ── DeviceControlsRail ──────────────────────────────────────────────────

/// One rail action: a label (its tooltip) and a glyph.
#[derive(Clone)]
pub struct DeviceAction {
    /// The label.
    pub label: SharedString,
    /// The glyph.
    pub icon: Icon,
}

impl DeviceAction {
    /// An action; known labels get the reference glyph (`Home`, `Rotate`,
    /// `Screenshot` → Image, `Record` → Recording, `Shake` → Repeat,
    /// `Volume` → Notification, `Keyboard`), others `Settings`.
    pub fn new(label: impl Into<SharedString>) -> Self {
        let label = label.into();
        let icon = Icon::carbon(device_glyph(&label));
        Self { label, icon }
    }

    /// Replace the glyph.
    pub fn icon(mut self, icon: impl Into<Icon>) -> Self {
        self.icon = icon.into();
        self
    }
}

/// The glyph for a reference action label (`ic[a] || I.Settings`).
pub fn device_glyph(label: &str) -> CarbonIcon {
    match label {
        "Home" => CarbonIcon::Home,
        "Rotate" => CarbonIcon::Rotate,
        "Screenshot" => CarbonIcon::Image,
        "Record" => CarbonIcon::Recording,
        "Shake" => CarbonIcon::Repeat,
        "Volume" => CarbonIcon::Notification,
        "Keyboard" => CarbonIcon::Keyboard,
        _ => CarbonIcon::Settings,
    }
}

/// The reference's default actions.
pub const DEVICE_ACTIONS: [&str; 6] = ["Home", "Rotate", "Screenshot", "Record", "Shake", "Volume"];

/// A vertical device toolbar (`DeviceControlsRail`, `.t3-rail`): ghost md
/// icon buttons with their tooltips on the left, a divider before the
/// fourth, on `layer-01` (or the layer it is set to, [`Self::layer`]).
#[derive(IntoElement)]
pub struct DeviceControlsRail {
    id: ElementId,
    actions: Vec<DeviceAction>,
    layer: LayerLevel,
    on_action: Option<IndexHandler>,
}

/// The rail's `(background, border)` at `layer`: the layer's own surface,
/// and above the first, outlined in the border of the surface it stands
/// on (FilesDevices: `.t3-rail { border: 1px solid border-subtle-01;
/// background: layer-02 }`).
pub fn rail_look(layer: LayerLevel) -> (ColorRole, Option<ColorRole>) {
    let under = match layer {
        LayerLevel::One => None,
        LayerLevel::Two => Some(LayerLevel::One),
        LayerLevel::Three => Some(LayerLevel::Two),
    };
    (layer.layer(), under.map(LayerLevel::border_subtle))
}

impl DeviceControlsRail {
    /// The rail with the reference's six actions.
    pub fn new(id: impl Into<ElementId>) -> Self {
        Self {
            id: id.into(),
            actions: DEVICE_ACTIONS
                .iter()
                .map(|a| DeviceAction::new(*a))
                .collect(),
            layer: LayerLevel::One,
            on_action: None,
        }
    }

    /// The layer it is drawn on (default `One`, `layer-01`): `Two` for a
    /// rail standing on a `layer-01` panel (the FilesDevices board).
    pub fn layer(mut self, layer: LayerLevel) -> Self {
        self.layer = layer;
        self
    }

    /// Replace the actions (`actions`).
    pub fn actions(mut self, actions: impl IntoIterator<Item = DeviceAction>) -> Self {
        self.actions = actions.into_iter().collect();
        self
    }

    /// An action pressed, with its index.
    pub fn on_action(mut self, f: impl Fn(usize, &mut Window, &mut App) + 'static) -> Self {
        self.on_action = Some(Rc::new(f));
        self
    }
}

impl RenderOnce for DeviceControlsRail {
    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
        let id = self.id.clone();
        let mut children: Vec<AnyElement> = Vec::new();
        for (i, a) in self.actions.into_iter().enumerate() {
            if i == 3 {
                // `.t3-rail-div { height: 1px; margin: spacing-02 spacing-03; background: border-subtle-01 }`.
                children.push(
                    div()
                        .h(px(1.))
                        .my(rem(4.))
                        .mx(rem(8.))
                        .bg(color(ColorRole::BorderSubtle01))
                        .into_any_element(),
                );
            }
            let f = self.on_action.clone();
            children.push(
                Button::new(child_id(&id, "action", i), a.label)
                    .icon(a.icon)
                    .icon_only(true)
                    .variant(ButtonVariant::Ghost)
                    .size(ButtonSize::Md)
                    .tooltip_align(Align::Left)
                    .when_some(f, |b, f| b.on_click(move |_, w, cx| f(i, w, cx)))
                    .into_any_element(),
            );
        }
        // `.t3-rail { display: inline-flex; flex-direction: column; background: layer-01 }`.
        let (background, border) = rail_look(self.layer);
        div()
            .id(id)
            .flex()
            .flex_col()
            .flex_none()
            .bg(color(background))
            .when_some(border, |this, border| {
                this.border_1().border_color(color(border))
            })
            .children(children)
    }
}

/// The strip's dot: `support-success` for a server that answers,
/// `support-error` for one that does not.
fn dot(answering: bool) -> ColorRole {
    if answering {
        ColorRole::SupportSuccess
    } else {
        ColorRole::SupportError
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn the_strip_s_dot_is_green_for_a_server_that_answers_and_red_for_one_that_does_not() {
        assert_eq!(dot(true), ColorRole::SupportSuccess);
        assert_eq!(dot(false), ColorRole::SupportError);
    }

    #[test]
    fn the_strip_under_a_narrow_bar_is_36px_as_the_board_draws_it() {
        assert_eq!(STRIP_HEIGHT, 36.);
    }

    #[test]
    fn load_bar_slides_from_minus_40_to_100_percent() {
        assert!((load_left(0.) + 0.4).abs() < 1e-5);
        assert!((load_left(1.) - 1.).abs() < 1e-5);
        // `ease-in-out` is symmetric: halfway is the midpoint.
        assert!((load_left(0.5) - 0.3).abs() < 1e-3);
    }

    #[test]
    fn a_rail_on_layer_two_is_layer_02_outlined_in_border_subtle_01() {
        assert_eq!(rail_look(LayerLevel::One), (ColorRole::Layer01, None));
        assert_eq!(
            rail_look(LayerLevel::Two),
            (ColorRole::Layer02, Some(ColorRole::BorderSubtle01))
        );
        assert_eq!(
            rail_look(LayerLevel::Three),
            (ColorRole::Layer03, Some(ColorRole::BorderSubtle02))
        );
    }

    #[test]
    fn the_strip_s_menu_shows_its_name_as_a_heading_only_when_asked() {
        let label = SharedString::from("Dev servers your terminals printed");
        let servers = || vec![MenuItem::item("dev"), MenuItem::item("storybook")];
        assert_eq!(strip_items(false, &label, servers()).len(), 2);
        assert_eq!(strip_items(true, &label, servers()).len(), 3);
        assert_eq!(STRIP_MENU_WIDTH, 336.);
    }

    #[test]
    fn the_forwarded_note_is_padded_as_pv_fwd() {
        assert_eq!(NOTE_PADDING, [8., 8., 8., 12.]);
        assert_eq!(NOTE_TEXT_TOP, 8.);
    }

    #[test]
    fn rail_glyphs_follow_the_reference_map() {
        assert_eq!(device_glyph("Screenshot"), CarbonIcon::Image);
        assert_eq!(device_glyph("Shake"), CarbonIcon::Repeat);
        assert_eq!(device_glyph("Volume"), CarbonIcon::Notification);
        assert_eq!(device_glyph("Anything"), CarbonIcon::Settings);
    }
}