fluidattacks-designs 0.11.0

Fluid Attacks design system, GPUI variant: desktop widgets over the shared tokens
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
//! `TextArea` — the web textarea: the same labeled outline container as
//! [`crate::TextInput`], grown to the lines its `rows` ask for and holding a
//! block of editable text rather than a single line.
//!
//! [`TextAreaState`] holds the text and editing state as an entity the app
//! owns; [`TextArea`] renders it:
//!
//! ```ignore
//! let state = cx.new(|cx| TextAreaState::new(window, cx).rows(6));
//! TextArea::new(&state).label("Justification").required(true)
//! ```
//!
//! Everything around the text — the label, the border's state machine, the
//! counter, the help line — is the single-line field's, shared rather than
//! restated. What the second dimension brings is this module's own: text that
//! wraps, a caret that walks up and down, `Home` and `End` that answer to the
//! visual row instead of the whole value, an `Enter` that writes a newline,
//! and a paste that keeps the newlines the single-line field has to flatten.
//!
//! The editing core (offsets, IME, clipboard) is adapted from gpui's `input`
//! example (Apache-2.0).

use std::ops::Range;
use std::time::{Duration, Instant};

use std::sync::Arc;

use unicode_segmentation::UnicodeSegmentation as _;

use fluidattacks_designs_domain::inputs::{
    State, Validation, CURSOR_BLINK_MS, CURSOR_WIDTH, DEFAULT_ROWS, LINE_HEIGHT, OUTLINE_GAP,
    PLACEHOLDER, SELECTION, TEXT, TEXT_SIZE,
};
use fluidattacks_designs_domain::typography::FONT_PRIMARY;
use gpui::prelude::FluentBuilder as _;
use gpui::{
    div, fill, point, px, relative, rgb, rgb_to_hsla, rgba, size, App, AvailableSpace, Bounds,
    ClipboardItem, Context, CursorStyle, Element, ElementId, ElementInputHandler, Entity,
    EntityInputHandler, FocusHandle, Focusable, GlobalElementId, InteractiveElement as _,
    IntoElement, KeyBinding, LayoutId, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent,
    PaintQuad, ParentElement as _, Pixels, Point, RenderOnce, ScrollHandle, SharedString,
    StatefulInteractiveElement as _, Style, Styled as _, TextAlign, TextRun, UTF16Selection,
    Window, WrappedLine,
};

use crate::scrollbar::Scrollbar;
use crate::text_input::{
    block_field_frame, bottom_row, help_row, label_row, text_runs, validation_icon, x_at,
};
use crate::theme::ActiveTheme as _;

const CONTEXT: &str = "DesignsTextArea";

// the actions! expansion derives PartialEq without Eq; not ours to fix
#[allow(clippy::derive_partial_eq_without_eq)]
mod action_defs {
    gpui::actions!(
        designs_text_area,
        [
            Backspace,
            Delete,
            Left,
            Right,
            Up,
            Down,
            SelectLeft,
            SelectRight,
            SelectUp,
            SelectDown,
            SelectAll,
            Home,
            End,
            Newline,
            ShowCharacterPalette,
            Paste,
            Cut,
            Copy,
        ]
    );
}
use action_defs::{
    Backspace, Copy, Cut, Delete, Down, End, Home, Left, Newline, Paste, Right, SelectAll,
    SelectDown, SelectLeft, SelectRight, SelectUp, ShowCharacterPalette, Up,
};

/// Registers the textarea's key bindings; [`crate::Theme::init`] calls this
/// once at startup.
///
/// The bindings the single-line field also has are repeated rather than
/// borrowed: they hang off this widget's own key context, which is what lets
/// `Enter` write a newline here and stay free to mean submit there.
pub fn bind_keys(cx: &mut App) {
    cx.bind_keys([
        KeyBinding::new("backspace", Backspace, Some(CONTEXT)),
        KeyBinding::new("delete", Delete, Some(CONTEXT)),
        KeyBinding::new("left", Left, Some(CONTEXT)),
        KeyBinding::new("right", Right, Some(CONTEXT)),
        KeyBinding::new("up", Up, Some(CONTEXT)),
        KeyBinding::new("down", Down, Some(CONTEXT)),
        KeyBinding::new("shift-left", SelectLeft, Some(CONTEXT)),
        KeyBinding::new("shift-right", SelectRight, Some(CONTEXT)),
        KeyBinding::new("shift-up", SelectUp, Some(CONTEXT)),
        KeyBinding::new("shift-down", SelectDown, Some(CONTEXT)),
        KeyBinding::new("cmd-a", SelectAll, Some(CONTEXT)),
        KeyBinding::new("enter", Newline, Some(CONTEXT)),
        KeyBinding::new("home", Home, Some(CONTEXT)),
        KeyBinding::new("cmd-left", Home, Some(CONTEXT)),
        KeyBinding::new("end", End, Some(CONTEXT)),
        KeyBinding::new("cmd-right", End, Some(CONTEXT)),
        KeyBinding::new("ctrl-cmd-space", ShowCharacterPalette, Some(CONTEXT)),
        KeyBinding::new("cmd-v", Paste, Some(CONTEXT)),
        KeyBinding::new("cmd-c", Copy, Some(CONTEXT)),
        KeyBinding::new("cmd-x", Cut, Some(CONTEXT)),
    ]);
}

/// How far down the block the window has to sit for the caret to be inside
/// it, or `None` if it already is.
///
/// All three arguments measure down from the top of the block: `caret` is the
/// caret's own top, `window` is how much of the block the box shows at once,
/// and `shown` is where the window sits now. The result is a distance, never
/// negative — the sign the scroll handle wants is the caller's to add.
fn held_at(caret: f32, window: f32, shown: f32) -> Option<f32> {
    let bottom = caret + LINE_HEIGHT;
    if caret < shown {
        Some(caret.max(0.0))
    } else if bottom > shown + window {
        Some((bottom - window).max(0.0))
    } else {
        None
    }
}

/// A count in pixel units. `as` is denied and there is no `f32: From<usize>`,
/// so the conversion goes the long way round.
fn scaled(count: usize, unit: f32) -> f32 {
    f32::from(u16::try_from(count).unwrap_or(u16::MAX)) * unit
}

/// The height `rows` lines of text need, with no padding in it.
///
/// [`inputs::rows_height`](fluidattacks_designs_domain::inputs::rows_height) is
/// the box; this is what the box holds, which is where the web's `min-height`
/// is written.
fn text_room(rows: u16) -> f32 {
    f32::from(rows.max(1)) * LINE_HEIGHT
}

/// Where each hard line begins, which is what `shape_text` splits on and does
/// not report back.
fn line_starts(text: &str) -> Vec<usize> {
    let mut starts = vec![0];
    starts.extend(
        text.match_indices('\n')
            .map(|(index, _)| index.saturating_add(1)),
    );
    starts
}

/// The shaped text, kept from the last layout so the caret and the mouse can
/// be placed without shaping again.
///
/// One entry per hard line break — `shape_text` splits there — each carrying
/// where in the value it starts, and each standing as many visual rows as its
/// wrapping needed.
#[derive(Default)]
struct Block {
    lines: Arc<[WrappedLine]>,
    starts: Vec<usize>,
}

impl Block {
    /// How many visual rows a hard line takes once wrapped.
    fn rows(line: &WrappedLine) -> usize {
        line.wrap_boundaries().len().saturating_add(1)
    }

    fn height(&self, line_height: f32) -> f32 {
        scaled(self.lines.iter().map(Self::rows).sum(), line_height)
    }

    fn width(&self) -> Pixels {
        self.lines.iter().fold(px(0.0), |widest, line| {
            widest.max(line.size(px(LINE_HEIGHT)).width)
        })
    }

    /// Where line `index` starts, measured down from the block's top.
    fn top(&self, index: usize, line_height: f32) -> f32 {
        scaled(
            self.lines.iter().take(index).map(Self::rows).sum(),
            line_height,
        )
    }

    /// The line holding `offset`, and how far into that line it sits.
    fn locate(&self, offset: usize) -> Option<(usize, usize)> {
        let mut found = None;
        for (index, start) in self.starts.iter().enumerate() {
            if *start > offset {
                break;
            }
            found = Some((index, offset.saturating_sub(*start)));
        }
        found
    }

    /// Where the caret for `offset` sits, relative to the block's top left.
    fn position(&self, offset: usize, line_height: f32) -> Option<Point<Pixels>> {
        let (index, within) = self.locate(offset)?;
        let line = self.lines.get(index)?;
        let local = line.position_for_index(within, px(line_height))?;
        Some(point(
            local.x,
            px(f32::from(local.y) + self.top(index, line_height)),
        ))
    }

    /// The offset a point lands on, relative to the block's top left.
    ///
    /// A point above or below the text answers with the nearest line rather
    /// than with nothing: a drag that runs off the box still has to select.
    fn index_at(&self, position: Point<Pixels>, line_height: f32) -> usize {
        let mut top = 0.0_f32;
        let last = self.lines.len().saturating_sub(1);
        for (index, line) in self.lines.iter().enumerate() {
            let rows = Self::rows(line);
            let bottom = top + scaled(rows, line_height);
            if f32::from(position.y) < bottom || index == last {
                // clamp into this line's own rows, so a point past the block
                // lands on its final row instead of falling off the layout
                let row_top = scaled(rows.saturating_sub(1), line_height);
                let local_y = (f32::from(position.y) - top).clamp(0.0, row_top);
                let within = line
                    .closest_index_for_position(point(position.x, px(local_y)), px(line_height))
                    .unwrap_or_else(|fallback| fallback);
                return self
                    .starts
                    .get(index)
                    .copied()
                    .unwrap_or_default()
                    .saturating_add(within);
            }
            top = bottom;
        }
        0
    }
}

/// The text and editing state behind a [`TextArea`]. Offsets are utf-8 byte
/// positions into `value`, always on grapheme boundaries.
pub struct TextAreaState {
    focus_handle: FocusHandle,
    value: SharedString,
    placeholder: SharedString,
    rows: u16,
    selected_range: Range<usize>,
    selection_reversed: bool,
    marked_range: Option<Range<usize>>,
    block: Block,
    last_bounds: Option<Bounds<Pixels>>,
    is_selecting: bool,
    max_length: Option<usize>,
    blink_scheduled: bool,
    /// Where the window onto the text sits. The box is the size `rows` asked
    /// for, so everything past it lives here rather than on the page.
    scroll: ScrollHandle,
    /// The caret this last scrolled to, so a reader who scrolls away is left
    /// where they put themselves until the caret actually moves again.
    held: Option<Instant>,
    /// The column a run of up/down arrows walks along, so a short line on the
    /// way does not drag the caret left with it. Any move that is not
    /// vertical clears it.
    goal_x: Option<f32>,
    /// Resets on every edit or caret move so the caret holds solid while
    /// typing, like the native caret the web inherits.
    caret_epoch: Instant,
}

impl TextAreaState {
    pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
        let focus_handle = cx.focus_handle();
        // the border and caret restyle on focus, which paint alone won't see
        cx.on_focus(&focus_handle, window, |_, _, cx| cx.notify())
            .detach();
        cx.on_blur(&focus_handle, window, |_, _, cx| cx.notify())
            .detach();
        Self {
            focus_handle,
            value: SharedString::default(),
            placeholder: SharedString::default(),
            rows: DEFAULT_ROWS,
            selected_range: 0..0,
            selection_reversed: false,
            marked_range: None,
            block: Block::default(),
            last_bounds: None,
            is_selecting: false,
            max_length: None,
            blink_scheduled: false,
            scroll: ScrollHandle::new(),
            held: None,
            goal_x: None,
            caret_epoch: Instant::now(),
        }
    }

    /// How many lines the box opens at (web `rows`). It grows past this as the
    /// text does; it never shrinks below it.
    #[must_use]
    pub const fn rows(mut self, rows: u16) -> Self {
        self.rows = rows;
        self
    }

    /// Cap the value length in graphemes (web `maxLength`); the widget shows
    /// the counter.
    #[must_use]
    pub const fn max_length(mut self, max_length: usize) -> Self {
        self.max_length = Some(max_length);
        self
    }

    #[must_use]
    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
        self.placeholder = placeholder.into();
        self
    }

    #[must_use]
    pub fn value(&self) -> &str {
        &self.value
    }

    pub fn set_placeholder(
        &mut self,
        placeholder: impl Into<SharedString>,
        cx: &mut Context<Self>,
    ) {
        self.placeholder = placeholder.into();
        cx.notify();
    }

    pub fn set_value(&mut self, value: impl Into<SharedString>, cx: &mut Context<Self>) {
        self.value = value.into();
        let end = self.value.len();
        self.selected_range = end..end;
        self.selection_reversed = false;
        self.marked_range = None;
        cx.notify();
    }

    fn left(&mut self, _: &Left, _: &mut Window, cx: &mut Context<Self>) {
        if self.selected_range.is_empty() {
            self.move_to(self.previous_boundary(self.cursor_offset()), cx);
        } else {
            self.move_to(self.selected_range.start, cx);
        }
    }

    fn right(&mut self, _: &Right, _: &mut Window, cx: &mut Context<Self>) {
        if self.selected_range.is_empty() {
            self.move_to(self.next_boundary(self.cursor_offset()), cx);
        } else {
            self.move_to(self.selected_range.end, cx);
        }
    }

    fn up(&mut self, _: &Up, _: &mut Window, cx: &mut Context<Self>) {
        self.walk(false, false, cx);
    }

    fn down(&mut self, _: &Down, _: &mut Window, cx: &mut Context<Self>) {
        self.walk(true, false, cx);
    }

    fn select_up(&mut self, _: &SelectUp, _: &mut Window, cx: &mut Context<Self>) {
        self.walk(false, true, cx);
    }

    fn select_down(&mut self, _: &SelectDown, _: &mut Window, cx: &mut Context<Self>) {
        self.walk(true, true, cx);
    }

    /// Walks the caret one visual row, holding the column it started from.
    ///
    /// Running off the top lands on the first offset and off the bottom on the
    /// last, which is what a native caret does rather than stopping dead.
    fn walk(&mut self, downward: bool, select: bool, cx: &mut Context<Self>) {
        let Some(position) = self.block.position(self.cursor_offset(), LINE_HEIGHT) else {
            return;
        };
        let column = self.goal_x.unwrap_or_else(|| f32::from(position.x));
        let target = if downward {
            f32::from(position.y) + LINE_HEIGHT
        } else {
            f32::from(position.y) - LINE_HEIGHT
        };
        let offset = if target < 0.0 {
            0
        } else if target >= self.block.height(LINE_HEIGHT) {
            self.value.len()
        } else {
            self.snapped(
                self.block
                    .index_at(point(px(column), px(target)), LINE_HEIGHT),
            )
        };
        if select {
            self.select_to(offset, cx);
        } else {
            self.move_to(offset, cx);
        }
        self.goal_x = Some(column);
    }

    fn select_left(&mut self, _: &SelectLeft, _: &mut Window, cx: &mut Context<Self>) {
        self.select_to(self.previous_boundary(self.cursor_offset()), cx);
    }

    fn select_right(&mut self, _: &SelectRight, _: &mut Window, cx: &mut Context<Self>) {
        self.select_to(self.next_boundary(self.cursor_offset()), cx);
    }

    fn select_all(&mut self, _: &SelectAll, _: &mut Window, cx: &mut Context<Self>) {
        self.move_to(0, cx);
        self.select_to(self.value.len(), cx);
    }

    /// The start of the visual row, not of the value: a wrapped line reads as
    /// a row of its own, so it is one to `Home` too.
    fn home(&mut self, _: &Home, _: &mut Window, cx: &mut Context<Self>) {
        self.move_to(self.row_edge(false), cx);
    }

    fn end(&mut self, _: &End, _: &mut Window, cx: &mut Context<Self>) {
        self.move_to(self.row_edge(true), cx);
    }

    /// The offset at one end of the caret's own visual row.
    fn row_edge(&self, trailing: bool) -> usize {
        let Some(position) = self.block.position(self.cursor_offset(), LINE_HEIGHT) else {
            return if trailing { self.value.len() } else { 0 };
        };
        // past every row's last glyph, so the hit test clamps to the row end
        let x = if trailing {
            px(f32::from(self.block.width()) + LINE_HEIGHT)
        } else {
            px(0.0)
        };
        self.snapped(self.block.index_at(point(x, position.y), LINE_HEIGHT))
    }

    fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
        self.replace_text_in_range(None, "\n", window, cx);
    }

    fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
        if self.selected_range.is_empty() {
            self.select_to(self.previous_boundary(self.cursor_offset()), cx);
        }
        self.replace_text_in_range(None, "", window, cx);
    }

    fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
        if self.selected_range.is_empty() {
            self.select_to(self.next_boundary(self.cursor_offset()), cx);
        }
        self.replace_text_in_range(None, "", window, cx);
    }

    /// Newlines land as newlines. The single-line field has to flatten them;
    /// pasting a key or a stack trace into a block is the whole point of one.
    fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
        if let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) {
            self.replace_text_in_range(None, &text, window, cx);
        }
    }

    fn selected_text(&self) -> &str {
        self.value
            .get(self.selected_range.clone())
            .unwrap_or_default()
    }

    fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
        if !self.selected_range.is_empty() {
            cx.write_to_clipboard(ClipboardItem::new_string(self.selected_text().to_owned()));
        }
    }

    fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
        if !self.selected_range.is_empty() {
            cx.write_to_clipboard(ClipboardItem::new_string(self.selected_text().to_owned()));
            self.replace_text_in_range(None, "", window, cx);
        }
    }

    fn on_mouse_down(&mut self, event: &MouseDownEvent, _: &mut Window, cx: &mut Context<Self>) {
        self.is_selecting = true;
        if event.modifiers.shift {
            self.select_to(self.index_for_mouse_position(event.position), cx);
        } else {
            self.move_to(self.index_for_mouse_position(event.position), cx);
        }
    }

    const fn on_mouse_up(&mut self, _: &MouseUpEvent, _: &mut Window, _: &mut Context<Self>) {
        self.is_selecting = false;
    }

    fn on_mouse_move(&mut self, event: &MouseMoveEvent, _: &mut Window, cx: &mut Context<Self>) {
        if self.is_selecting {
            self.select_to(self.index_for_mouse_position(event.position), cx);
        }
    }

    fn move_to(&mut self, offset: usize, cx: &mut Context<Self>) {
        self.selected_range = offset..offset;
        self.goal_x = None;
        self.caret_epoch = Instant::now();
        cx.notify();
    }

    const fn cursor_offset(&self) -> usize {
        if self.selection_reversed {
            self.selected_range.start
        } else {
            self.selected_range.end
        }
    }

    fn index_for_mouse_position(&self, position: Point<Pixels>) -> usize {
        if self.value.is_empty() {
            return 0;
        }
        let Some(bounds) = self.last_bounds.as_ref() else {
            return 0;
        };
        let local = point(
            px(f32::from(position.x) - f32::from(bounds.left())),
            px(f32::from(position.y) - f32::from(bounds.top())),
        );
        self.snapped(self.block.index_at(local, LINE_HEIGHT))
    }

    /// An offset the value can actually be cut at: inside it, and on a
    /// character boundary. The shaper answers in the text it was handed, which
    /// is the placeholder while the value is empty.
    fn snapped(&self, offset: usize) -> usize {
        let mut offset = offset.min(self.value.len());
        while offset > 0 && !self.value.is_char_boundary(offset) {
            offset = offset.saturating_sub(1);
        }
        offset
    }

    /// Scrolls the caret back into the window `rows` opens, if it has walked
    /// out of it.
    ///
    /// See [`held_at`] for the arithmetic; this is the part that needs a
    /// laid-out block to read it from.
    ///
    /// A box that grows never needs this; one that scrolls has nothing else to
    /// do it. Reading the block after it is shaped is what makes it right for
    /// an edit as well as for a move — a newline at the bottom pushes the
    /// caret past the last row it had.
    fn hold_caret_in_view(&self) {
        let Some(at) = self.block.position(self.cursor_offset(), LINE_HEIGHT) else {
            return;
        };
        // the handle carries content up as a negative offset
        let shown = -f32::from(self.scroll.offset().y);
        let Some(moved) = held_at(f32::from(at.y), text_room(self.rows), shown) else {
            return;
        };
        let across = self.scroll.offset().x;
        self.scroll.set_offset(point(across, px(-moved)));
    }

    fn select_to(&mut self, offset: usize, cx: &mut Context<Self>) {
        if self.selection_reversed {
            self.selected_range.start = offset;
        } else {
            self.selected_range.end = offset;
        }
        if self.selected_range.end < self.selected_range.start {
            self.selection_reversed = !self.selection_reversed;
            self.selected_range = self.selected_range.end..self.selected_range.start;
        }
        self.goal_x = None;
        self.caret_epoch = Instant::now();
        cx.notify();
    }

    fn offset_from_utf16(&self, offset: usize) -> usize {
        let mut utf8_offset = 0_usize;
        let mut utf16_count = 0_usize;
        for ch in self.value.chars() {
            if utf16_count >= offset {
                break;
            }
            utf16_count = utf16_count.saturating_add(ch.len_utf16());
            utf8_offset = utf8_offset.saturating_add(ch.len_utf8());
        }
        utf8_offset
    }

    fn offset_to_utf16(&self, offset: usize) -> usize {
        let mut utf16_offset = 0_usize;
        let mut utf8_count = 0_usize;
        for ch in self.value.chars() {
            if utf8_count >= offset {
                break;
            }
            utf8_count = utf8_count.saturating_add(ch.len_utf8());
            utf16_offset = utf16_offset.saturating_add(ch.len_utf16());
        }
        utf16_offset
    }

    fn range_to_utf16(&self, range: &Range<usize>) -> Range<usize> {
        self.offset_to_utf16(range.start)..self.offset_to_utf16(range.end)
    }

    fn range_from_utf16(&self, range_utf16: &Range<usize>) -> Range<usize> {
        self.offset_from_utf16(range_utf16.start)..self.offset_from_utf16(range_utf16.end)
    }

    /// The IME target: the explicit range, else the composing range, else the
    /// selection.
    fn target_range(&self, range_utf16: Option<&Range<usize>>) -> Range<usize> {
        range_utf16
            .map(|utf16| self.range_from_utf16(utf16))
            .or_else(|| self.marked_range.clone())
            .unwrap_or_else(|| self.selected_range.clone())
    }

    fn previous_boundary(&self, offset: usize) -> usize {
        let mut previous = 0;
        for (idx, _) in self.value.grapheme_indices(true) {
            if idx >= offset {
                break;
            }
            previous = idx;
        }
        previous
    }

    fn next_boundary(&self, offset: usize) -> usize {
        self.value
            .grapheme_indices(true)
            .find_map(|(idx, _)| (idx > offset).then_some(idx))
            .unwrap_or(self.value.len())
    }

    /// Splices `new_text` over `range`, returning the caret's new offset.
    fn splice(&mut self, range: &Range<usize>, new_text: &str) -> usize {
        let prefix = self.value.get(..range.start).unwrap_or_default();
        let suffix = self.value.get(range.end..).unwrap_or_default();
        let new_text = self.max_length.map_or(new_text, |max| {
            // like the browser maxLength: typing stops, pastes truncate —
            // at grapheme boundaries, keeping the module offset promise
            let kept = prefix
                .graphemes(true)
                .count()
                .saturating_add(suffix.graphemes(true).count());
            let room = max.saturating_sub(kept);
            let end = new_text
                .grapheme_indices(true)
                .nth(room)
                .map_or(new_text.len(), |(idx, _)| idx);
            new_text.get(..end).unwrap_or_default()
        });
        self.value = format!("{prefix}{new_text}{suffix}").into();
        self.goal_x = None;
        self.caret_epoch = Instant::now();
        range.start.saturating_add(new_text.len())
    }
}

impl Focusable for TextAreaState {
    fn focus_handle(&self, _: &App) -> FocusHandle {
        self.focus_handle.clone()
    }
}

impl gpui::Render for TextAreaState {
    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        div()
            .w_full()
            // the box `rows` asked for, filled. The caret and the drag hang
            // off this element, so its height is also how much of the field
            // answers the mouse — sized to the text, only the lines already
            // written would.
            .h_full()
            .key_context(CONTEXT)
            .track_focus(&self.focus_handle)
            .cursor(CursorStyle::IBeam)
            .on_action(cx.listener(Self::backspace))
            .on_action(cx.listener(Self::delete))
            .on_action(cx.listener(Self::left))
            .on_action(cx.listener(Self::right))
            .on_action(cx.listener(Self::up))
            .on_action(cx.listener(Self::down))
            .on_action(cx.listener(Self::select_left))
            .on_action(cx.listener(Self::select_right))
            .on_action(cx.listener(Self::select_up))
            .on_action(cx.listener(Self::select_down))
            .on_action(cx.listener(Self::select_all))
            .on_action(cx.listener(Self::home))
            .on_action(cx.listener(Self::end))
            .on_action(cx.listener(Self::newline))
            .on_action(|_: &ShowCharacterPalette, window: &mut Window, _| {
                window.show_character_palette();
            })
            .on_action(cx.listener(Self::paste))
            .on_action(cx.listener(Self::cut))
            .on_action(cx.listener(Self::copy))
            .on_mouse_down(MouseButton::Left, cx.listener(Self::on_mouse_down))
            .on_mouse_up(MouseButton::Left, cx.listener(Self::on_mouse_up))
            .on_mouse_up_out(MouseButton::Left, cx.listener(Self::on_mouse_up))
            .on_mouse_move(cx.listener(Self::on_mouse_move))
            .child(
                div()
                    .id(("designs-text-area", cx.entity_id()))
                    .w_full()
                    .h_full()
                    .overflow_y_scroll()
                    .track_scroll(&self.scroll)
                    .child(BlockElement { state: cx.entity() }),
            )
    }
}

impl EntityInputHandler for TextAreaState {
    fn text_for_range(
        &mut self,
        range_utf16: Range<usize>,
        actual_range: &mut Option<Range<usize>>,
        _: &mut Window,
        _: &mut Context<Self>,
    ) -> Option<String> {
        let range = self.range_from_utf16(&range_utf16);
        actual_range.replace(self.range_to_utf16(&range));
        Some(self.value.get(range).unwrap_or_default().to_owned())
    }

    fn selected_text_range(
        &mut self,
        _ignore_disabled_input: bool,
        _: &mut Window,
        _: &mut Context<Self>,
    ) -> Option<UTF16Selection> {
        Some(UTF16Selection {
            range: self.range_to_utf16(&self.selected_range),
            reversed: self.selection_reversed,
        })
    }

    fn marked_text_range(&self, _: &mut Window, _: &mut Context<Self>) -> Option<Range<usize>> {
        self.marked_range
            .as_ref()
            .map(|range| self.range_to_utf16(range))
    }

    fn unmark_text(&mut self, _: &mut Window, _: &mut Context<Self>) {
        self.marked_range = None;
    }

    fn replace_text_in_range(
        &mut self,
        range_utf16: Option<Range<usize>>,
        new_text: &str,
        _: &mut Window,
        cx: &mut Context<Self>,
    ) {
        let range = self.target_range(range_utf16.as_ref());
        let caret = self.splice(&range, new_text);
        self.selected_range = caret..caret;
        self.marked_range.take();
        cx.notify();
    }

    fn replace_and_mark_text_in_range(
        &mut self,
        range_utf16: Option<Range<usize>>,
        new_text: &str,
        new_selected_range_utf16: Option<Range<usize>>,
        _: &mut Window,
        cx: &mut Context<Self>,
    ) {
        let range = self.target_range(range_utf16.as_ref());
        let caret = self.splice(&range, new_text);
        self.marked_range = if new_text.is_empty() {
            None
        } else {
            Some(range.start..caret)
        };
        self.selected_range = new_selected_range_utf16
            .as_ref()
            .map(|utf16| self.range_from_utf16(utf16))
            .map(|new_range| {
                new_range.start.saturating_add(range.start)
                    ..new_range.end.saturating_add(range.start)
            })
            .unwrap_or(caret..caret);
        cx.notify();
    }

    /// The candidate window opens against the caret's own row. A block that
    /// answered with the first row would put it at the top of the box no
    /// matter how far down the text the caret had walked.
    fn bounds_for_range(
        &mut self,
        range_utf16: Range<usize>,
        bounds: Bounds<Pixels>,
        _: &mut Window,
        _: &mut Context<Self>,
    ) -> Option<Bounds<Pixels>> {
        let range = self.range_from_utf16(&range_utf16);
        let start = self.block.position(range.start, LINE_HEIGHT)?;
        let end = self.block.position(range.end, LINE_HEIGHT)?;
        let top = f32::from(bounds.top()) + f32::from(start.y);
        Some(Bounds::from_corners(
            point(x_at(&bounds, start.x), px(top)),
            point(x_at(&bounds, end.x), px(top + LINE_HEIGHT)),
        ))
    }

    fn character_index_for_point(
        &mut self,
        point_at: Point<Pixels>,
        _: &mut Window,
        _: &mut Context<Self>,
    ) -> Option<usize> {
        let local = self.last_bounds?.localize(&point_at)?;
        Some(self.offset_to_utf16(self.snapped(self.block.index_at(local, LINE_HEIGHT))))
    }
}

/// One row of the selection wash. A block selection is not a rectangle, so it
/// is painted a row at a time.
fn row_quad(top: f32, left: Pixels, right: Pixels, tone: u32) -> PaintQuad {
    fill(
        Bounds::from_corners(point(left, px(top)), point(right, px(top + LINE_HEIGHT))),
        rgba(tone << 8 | 0xff),
    )
}

/// The selection wash across however many rows the range covers: caret to
/// edge on the first, edge to edge in between, edge to caret on the last.
fn selection_quads(
    block: &Block,
    bounds: &Bounds<Pixels>,
    range: &Range<usize>,
    tone: u32,
) -> Vec<PaintQuad> {
    let (Some(start), Some(end)) = (
        block.position(range.start, LINE_HEIGHT),
        block.position(range.end, LINE_HEIGHT),
    ) else {
        return Vec::new();
    };
    let left = bounds.left();
    let right = px(f32::from(bounds.left()) + f32::from(bounds.size.width));
    let top = f32::from(bounds.top());
    let (first, last) = (f32::from(start.y), f32::from(end.y));
    if last - first < LINE_HEIGHT {
        return vec![row_quad(
            top + first,
            x_at(bounds, start.x),
            x_at(bounds, end.x),
            tone,
        )];
    }
    let mut quads = vec![row_quad(top + first, x_at(bounds, start.x), right, tone)];
    for step in 1..u16::MAX {
        let row = f32::from(step).mul_add(LINE_HEIGHT, first);
        if row >= last {
            break;
        }
        quads.push(row_quad(top + row, left, right, tone));
    }
    quads.push(row_quad(top + last, left, x_at(bounds, end.x), tone));
    quads
}

/// Wake the view when the caret phase flips.
fn schedule_blink(state: &Entity<TextAreaState>, until_flip: u64, window: &Window, cx: &mut App) {
    state.update(cx, |area, _| area.blink_scheduled = true);
    let entity = state.clone();
    let view = window.current_view();
    window
        .spawn(cx, async move |task_cx| {
            task_cx
                .background_executor()
                .timer(Duration::from_millis(until_flip))
                .await;
            task_cx
                .update(|_, app| {
                    entity.update(app, |area, _| area.blink_scheduled = false);
                    app.notify(view);
                })
                .ok();
        })
        .detach();
}

/// What the layout is asking the block for.
///
/// Telling the last two apart is the whole point of the type. A flex item's
/// automatic minimum is its min-content width, so a block that answers
/// "narrowest?" with its longest unwrapped line can never shrink: the box
/// widens with the text instead of wrapping into it. Text wraps, so its
/// narrowest is nothing at all.
#[derive(Clone, Copy)]
enum Ask {
    /// A width the layout has settled on. Wrap into it, and report it back.
    At(Pixels),
    /// The narrowest the block may be squeezed to.
    Narrowest,
    /// The width the text would take with nothing in its way.
    Widest,
}

impl Ask {
    /// What the layout is asking, read off the space it offers.
    fn new(known: Option<Pixels>, available: AvailableSpace) -> Self {
        known.map_or_else(
            || match available {
                AvailableSpace::Definite(width) => Self::At(width),
                AvailableSpace::MinContent => Self::Narrowest,
                AvailableSpace::MaxContent => Self::Widest,
            },
            Self::At,
        )
    }

    /// The width to shape at. Only a settled width wraps the text; the other
    /// two are questions about the text, not constraints on it.
    const fn wrap_width(self) -> Option<Pixels> {
        match self {
            Self::At(width) => Some(width),
            Self::Narrowest | Self::Widest => None,
        }
    }

    /// Whether this ask produced the block the widget will actually paint.
    ///
    /// Only a settled width does. A probe shapes the text to answer a question
    /// about it, and keeping that answer would leave the caret and the paint
    /// reading a block laid out at a width the box never had.
    const fn settles(self) -> bool {
        matches!(self, Self::At(_))
    }

    /// The width to answer with, once the block has been shaped.
    fn answer(self, block: &Block) -> Pixels {
        match self {
            Self::At(width) => width,
            Self::Narrowest => px(0.0),
            Self::Widest => block.width(),
        }
    }
}

/// Shapes the block for `ask`, keeps it on the state for the paint that
/// follows, and answers with the room it needs.
fn measure_block(
    state: &Entity<TextAreaState>,
    ask: Ask,
    window: &Window,
    app: &mut App,
) -> gpui::Size<Pixels> {
    let theme = app.theme();
    let (body, hint) = (theme.shade(TEXT), theme.shade(PLACEHOLDER));
    let area = state.read(app);
    let empty = area.value.is_empty();
    let text = if empty {
        area.placeholder.clone()
    } else {
        area.value.clone()
    };
    let marked = area.marked_range.clone();
    let style = window.text_style();
    let run = TextRun {
        len: text.len(),
        font: style.font(),
        color: rgb_to_hsla(rgb(if empty { hint } else { body })),
        background_color: None,
        underline: None,
        strikethrough: None,
        letter_spacing: None,
    };
    let runs = text_runs(text.len(), marked.as_ref(), &run);
    let starts = line_starts(&text);
    let font_size = style.font_size.to_pixels(window.rem_size());
    let lines: Vec<WrappedLine> = window
        .text_system()
        .shape_text(text, font_size, &runs, ask.wrap_width(), None)
        .map(|shaped| shaped.into_iter().collect())
        .unwrap_or_default();
    let block = Block {
        lines: lines.into(),
        starts,
    };
    let measured = size(
        ask.answer(&block),
        px(block.height(LINE_HEIGHT).max(LINE_HEIGHT)),
    );
    if ask.settles() {
        state.update(app, |shaped, _| shaped.block = block);
    }
    measured
}

/// The editable block: shapes the text at the width it is given, paints the
/// selection and caret, and connects the platform input handler for IME.
struct BlockElement {
    state: Entity<TextAreaState>,
}

struct BlockPrepaint {
    lines: Arc<[WrappedLine]>,
    selection: Vec<PaintQuad>,
    cursor: Option<PaintQuad>,
}

impl IntoElement for BlockElement {
    type Element = Self;

    fn into_element(self) -> Self::Element {
        self
    }
}

impl Element for BlockElement {
    type RequestLayoutState = ();
    type PrepaintState = BlockPrepaint;

    fn id(&self) -> Option<ElementId> {
        None
    }

    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
        None
    }

    /// Height comes out of the shaping, and the shaping needs the width the
    /// layout is about to hand down — so the two happen together, in a
    /// measured layout, and the block is kept for the paint that follows.
    fn request_layout(
        &mut self,
        _: Option<&GlobalElementId>,
        _: Option<&gpui::InspectorElementId>,
        window: &mut Window,
        _cx: &mut App,
    ) -> (LayoutId, Self::RequestLayoutState) {
        let mut style = Style::default();
        style.size.width = relative(1.0).into();
        let state = self.state.clone();
        let layout_id =
            window.request_measured_layout(style, move |known, available, window, app| {
                measure_block(&state, Ask::new(known.width, available.width), window, app)
            });
        (layout_id, ())
    }

    fn prepaint(
        &mut self,
        _: Option<&GlobalElementId>,
        _: Option<&gpui::InspectorElementId>,
        bounds: Bounds<Pixels>,
        &mut (): &mut Self::RequestLayoutState,
        _window: &mut Window,
        cx: &mut App,
    ) -> Self::PrepaintState {
        let theme = cx.theme();
        let (caret_tone, selection_tone) = (theme.shade(TEXT), theme.shade(SELECTION));
        let chased = self.state.read(cx).held;
        let epoch = self.state.read(cx).caret_epoch;
        if chased != Some(epoch) {
            self.state.update(cx, |area, _| {
                area.hold_caret_in_view();
                area.held = Some(epoch);
            });
        }
        let state = self.state.read(cx);
        let range = state.selected_range.clone();
        let (selection, cursor) = if range.is_empty() {
            let caret = state.block.position(range.start, LINE_HEIGHT).map(|at| {
                fill(
                    Bounds::new(
                        point(
                            x_at(&bounds, at.x),
                            px(f32::from(bounds.top()) + f32::from(at.y)),
                        ),
                        size(px(CURSOR_WIDTH), px(LINE_HEIGHT)),
                    ),
                    rgb(caret_tone),
                )
            });
            (Vec::new(), caret)
        } else {
            (
                selection_quads(&state.block, &bounds, &range, selection_tone),
                None,
            )
        };
        BlockPrepaint {
            lines: state.block.lines.clone(),
            selection,
            cursor,
        }
    }

    fn paint(
        &mut self,
        _: Option<&GlobalElementId>,
        _: Option<&gpui::InspectorElementId>,
        bounds: Bounds<Pixels>,
        &mut (): &mut Self::RequestLayoutState,
        prepaint: &mut Self::PrepaintState,
        window: &mut Window,
        cx: &mut App,
    ) {
        let (focus_handle, until_flip, blink_visible) = {
            let state = self.state.read(cx);
            let focus_handle = state.focus_handle.clone();
            // the native caret blinks: solid right after edits, then 530ms phases
            let elapsed = state.caret_epoch.elapsed().as_millis();
            let blink_phase = elapsed
                .checked_div(u128::from(CURSOR_BLINK_MS))
                .unwrap_or(0);
            let blink_visible = blink_phase & 1 == 0;
            let into_phase = elapsed
                .checked_rem(u128::from(CURSOR_BLINK_MS))
                .unwrap_or(0);
            let until_flip = CURSOR_BLINK_MS.saturating_sub(u64::try_from(into_phase).unwrap_or(0));
            (focus_handle, until_flip, blink_visible)
        };
        window.handle_input(
            &focus_handle,
            ElementInputHandler::new(bounds, self.state.clone()),
            cx,
        );
        for quad in prepaint.selection.drain(..) {
            window.paint_quad(quad);
        }
        let line_height = px(LINE_HEIGHT);
        let mut top = f32::from(bounds.top());
        for line in prepaint.lines.iter() {
            line.paint(
                point(bounds.left(), px(top)),
                line_height,
                TextAlign::default(),
                Some(bounds),
                window,
                cx,
            )
            .ok();
            top += scaled(Block::rows(line), LINE_HEIGHT);
        }
        let focused = focus_handle.is_focused(window);
        // one wake per phase flip, not a full-rate repaint
        if focused && !self.state.read(cx).blink_scheduled {
            schedule_blink(&self.state, until_flip, window, cx);
        }
        if let Some(cursor) = prepaint.cursor.take().filter(|_| focused && blink_visible) {
            window.paint_quad(cursor);
        }
        self.state
            .update(cx, |area, _| area.last_bounds = Some(bounds));
    }
}

/// The widget: outline container, label with the required asterisk, the
/// editable block, a validation icon and the error message.
#[derive(IntoElement)]
pub struct TextArea {
    state: Entity<TextAreaState>,
    label: Option<SharedString>,
    label_tooltip: Option<(ElementId, SharedString)>,
    required: bool,
    error: Option<SharedString>,
    success: bool,
    disabled: bool,
    help_text: Option<SharedString>,
    help_link: Option<(ElementId, SharedString, SharedString)>,
}

impl TextArea {
    #[must_use]
    pub fn new(state: &Entity<TextAreaState>) -> Self {
        Self {
            state: state.clone(),
            label: None,
            label_tooltip: None,
            required: false,
            error: None,
            success: false,
            disabled: false,
            help_text: None,
            help_link: None,
        }
    }

    #[must_use]
    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
        self.label = Some(label.into());
        self
    }

    #[must_use]
    pub const fn required(mut self, required: bool) -> Self {
        self.required = required;
        self
    }

    /// An info glyph after the label carrying a tooltip (web label `tooltip`).
    #[must_use]
    pub fn label_tooltip(mut self, id: impl Into<ElementId>, tip: impl Into<SharedString>) -> Self {
        self.label_tooltip = Some((id.into(), tip.into()));
        self
    }

    /// Gray helper line under the field (web `helpText`).
    #[must_use]
    pub fn help_text(mut self, help_text: impl Into<SharedString>) -> Self {
        self.help_text = Some(help_text.into());
        self
    }

    /// A link beside the help line (web `helpLink`).
    #[must_use]
    pub fn help_link(
        mut self,
        id: impl Into<ElementId>,
        label: impl Into<SharedString>,
        href: impl Into<SharedString>,
    ) -> Self {
        self.help_link = Some((id.into(), label.into(), href.into()));
        self
    }

    #[must_use]
    pub fn error(mut self, error: impl Into<SharedString>) -> Self {
        self.error = Some(error.into());
        self
    }

    #[must_use]
    pub const fn success(mut self, success: bool) -> Self {
        self.success = success;
        self
    }

    #[must_use]
    pub const fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    fn field(self, state: State, cx: &App) -> gpui::Div {
        let theme = cx.theme();
        let rows = self.state.read(cx).rows;
        block_field_frame(state, rows, theme)
            .map(|el| {
                if self.disabled {
                    el.cursor(CursorStyle::OperationNotAllowed)
                        .child(self.static_text(cx))
                } else {
                    el.child(
                        div()
                            // a flex item's automatic minimum is its
                            // min-content width, and this block's is the
                            // longest line unwrapped, so without the floor
                            // released the box widens with the text instead of
                            // wrapping into it
                            .min_w(px(0.0))
                            .flex_1()
                            .h_full()
                            .child(self.state.clone()),
                    )
                }
            })
            .when_some(
                validation_icon(
                    matches!(state, State::Error),
                    matches!(state, State::Success),
                    theme,
                ),
                gpui::ParentElement::child,
            )
            // hung off the frame rather than off the text, because an absolute
            // child is placed against its ancestor's padding box: from here the
            // bar meets the border, where the native one sits, instead of
            // standing one PADDING_X inside it
            .child(Scrollbar::vertical(
                ("designs-text-area-bar", self.state.entity_id()),
                &self.state.read(cx).scroll,
            ))
    }

    /// Disabled areas show static text; the editable block is the state entity
    /// itself, a child view that redraws as it edits.
    ///
    /// It scrolls all the same. Locking a field stops it being edited, not
    /// read, and a fixed box that cannot scroll would simply cut whatever it
    /// was locked holding.
    fn static_text(&self, cx: &App) -> gpui::Stateful<gpui::Div> {
        let area = self.state.read(cx);
        let empty = area.value.is_empty();
        let shown = if empty {
            area.placeholder.clone()
        } else {
            area.value.clone()
        };
        div()
            .id(("designs-text-area-locked", self.state.entity_id()))
            .min_w(px(0.0))
            .flex_1()
            .h_full()
            .overflow_y_scroll()
            .track_scroll(&area.scroll)
            .when(empty, |el| {
                el.text_color(rgb(cx.theme().shade(PLACEHOLDER)))
            })
            .child(shown)
    }
}

impl RenderOnce for TextArea {
    fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let focused = self.state.read(cx).focus_handle.is_focused(window);
        let validation = if self.error.is_some() && !self.disabled {
            Validation::Error
        } else if self.success {
            Validation::Success
        } else {
            Validation::None
        };
        let state = State::resolve(focused, validation, self.disabled);
        let label = self.label.take();
        let label_tooltip = self.label_tooltip.take();
        let required = self.required;
        let error = if self.disabled {
            None
        } else {
            self.error.take()
        };
        let counter = {
            let area = self.state.read(cx);
            area.max_length
                .map(|max| format!("{}/{max}", area.value.graphemes(true).count()))
        };
        let help = self.help_text.take();
        let help_link = self.help_link.take();
        let theme = cx.theme();
        let bottom =
            (error.is_some() || counter.is_some()).then(|| bottom_row(error, counter, theme));

        div()
            .flex()
            .flex_col()
            .items_start()
            .gap(px(OUTLINE_GAP))
            .w_full()
            .font_family(FONT_PRIMARY)
            .text_size(px(TEXT_SIZE.px()))
            .line_height(px(LINE_HEIGHT))
            .when_some(label, |el, label| {
                el.child(label_row(label, required, label_tooltip, theme))
            })
            .child(self.field(state, cx))
            .when_some(bottom, gpui::ParentElement::child)
            .when(help.is_some() || help_link.is_some(), |el| {
                el.child(help_row(help, help_link, theme))
            })
    }
}

#[cfg(test)]
mod tests {
    use super::{held_at, line_starts, scaled, text_room, Ask, Block};
    use fluidattacks_designs_domain::inputs::{rows_height, LINE_HEIGHT, PADDING_Y};
    use gpui::{px, AvailableSpace};

    /// The narrowest a wrapping block can be is nothing. Answering with its
    /// longest line instead is what stops a flex item from ever shrinking —
    /// the box then widens with the text rather than wrapping into it.
    #[test]
    fn the_narrowest_a_block_can_be_is_nothing() {
        let block = Block::default();
        assert_eq!(Ask::Narrowest.answer(&block), px(0.0));
        assert_eq!(Ask::At(px(120.0)).answer(&block), px(120.0));
    }

    /// Only a settled width wraps the text. The other two are questions about
    /// the text, and shaping into them would answer a different one.
    #[test]
    fn only_a_settled_width_wraps_the_text() {
        assert_eq!(Ask::At(px(120.0)).wrap_width(), Some(px(120.0)));
        assert_eq!(Ask::Narrowest.wrap_width(), None);
        assert_eq!(Ask::Widest.wrap_width(), None);
    }

    /// Only a settled width leaves a block behind. A probe that kept its own
    /// would hand the caret and the paint a layout at a width the box never
    /// had.
    #[test]
    fn only_a_settled_width_leaves_a_block_behind() {
        assert!(Ask::At(px(120.0)).settles());
        assert!(!Ask::Narrowest.settles());
        assert!(!Ask::Widest.settles());
    }

    /// A width the layout already knows outranks whatever space it offers.
    #[test]
    fn a_known_width_settles_the_ask() {
        assert_eq!(
            Ask::new(Some(px(80.0)), AvailableSpace::MinContent).wrap_width(),
            Some(px(80.0))
        );
        assert_eq!(
            Ask::new(None, AvailableSpace::MinContent).wrap_width(),
            None
        );
        assert_eq!(
            Ask::new(None, AvailableSpace::Definite(px(64.0))).wrap_width(),
            Some(px(64.0))
        );
    }

    /// The mouse answers across the room `rows` asks for, not across the lines
    /// written into it, so an empty three-row area is clickable all the way
    /// down.
    #[test]
    fn the_room_is_the_rows_not_the_content() {
        assert_eq!(text_room(3).to_bits(), 60.0_f32.to_bits());
        assert_eq!(text_room(0).to_bits(), text_room(1).to_bits());
    }

    /// The box and what it holds must not drift apart: the room is the
    /// domain's box less the padding the frame puts around it.
    #[test]
    fn the_room_is_the_domain_box_less_its_padding() {
        for rows in [1_u16, 3, 6] {
            let expected = rows_height(rows) - PADDING_Y - PADDING_Y;
            assert_eq!(text_room(rows).to_bits(), expected.to_bits(), "{rows} rows");
        }
    }

    /// A caret already inside the window moves nothing. Scrolling on every
    /// keystroke would fight a reader who had scrolled somewhere themselves.
    #[test]
    fn a_caret_in_view_holds_the_window_still() {
        let window = text_room(3);
        assert_eq!(held_at(0.0, window, 0.0), None);
        assert_eq!(held_at(40.0, window, 0.0), None);
    }

    /// Walking off the bottom brings the window down by just enough to show
    /// the caret's own row, not by a whole screen.
    #[test]
    fn a_caret_below_the_window_pulls_it_down() {
        let window = text_room(3);
        assert_eq!(held_at(60.0, window, 0.0), Some(20.0));
        assert_eq!(held_at(200.0, window, 0.0), Some(160.0));
    }

    /// And off the top brings it back up to the caret's row.
    #[test]
    fn a_caret_above_the_window_pulls_it_up() {
        let window = text_room(3);
        assert_eq!(held_at(20.0, window, 100.0), Some(20.0));
        assert_eq!(held_at(0.0, window, 60.0), Some(0.0));
    }

    /// The window never leaves the top of the block. A negative offset would
    /// scroll the first line off the top of a box it should never leave.
    #[test]
    fn the_window_never_climbs_above_the_block() {
        for shown in [0.0_f32, 20.0, 200.0] {
            if let Some(moved) = held_at(0.0, text_room(3), shown) {
                assert!(moved >= 0.0, "{moved} from {shown}");
            }
        }
    }

    /// `shape_text` splits on newlines and hands back lines with no word on
    /// where they came from, so the offsets have to be tracked alongside.
    #[test]
    fn line_starts_follow_the_hard_breaks() {
        assert_eq!(line_starts(""), vec![0]);
        assert_eq!(line_starts("one line"), vec![0]);
        assert_eq!(line_starts("a\nb"), vec![0, 2]);
        assert_eq!(line_starts("a\nbb\nc"), vec![0, 2, 5]);
    }

    /// A trailing newline opens a line that is empty but real — the caret has
    /// to be able to sit on it.
    #[test]
    fn a_trailing_newline_opens_a_line() {
        assert_eq!(line_starts("a\n"), vec![0, 2]);
    }

    /// Multi-byte text keeps the starts in bytes, since every offset in the
    /// module is a utf-8 byte position.
    #[test]
    fn line_starts_are_byte_offsets() {
        assert_eq!(line_starts("é\nb"), vec![0, 3]);
    }

    #[test]
    fn a_count_of_rows_scales_to_pixels() {
        assert_eq!(scaled(0, LINE_HEIGHT).to_bits(), 0.0_f32.to_bits());
        assert_eq!(scaled(3, LINE_HEIGHT).to_bits(), 60.0_f32.to_bits());
    }
}