quickgui 0.1.1

A damage-driven, GPU-accelerated desktop GUI foundation
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
use std::{
    any::{Any, TypeId},
    borrow::Cow,
    fmt,
    rc::Rc,
    sync::Arc,
};

use glyphon::{Style as GlyphStyle, Weight};
use taffy::{
    Style,
    geometry::{Line as TaffyLine, Point as TaffyPoint, Rect as TaffyRect, Size as TaffySize},
    prelude::{
        AlignContent, AlignItems, AlignSelf, Dimension, Display, FlexDirection, FlexWrap,
        GridAutoFlow, GridPlacement, GridTemplateComponent, JustifyContent, LengthPercentage,
        LengthPercentageAuto, Position, TrackSizingFunction,
    },
    style::Overflow,
    style_helpers::{
        auto, fit_content, flex, fr, length, line, max_content, min_content, minmax, percent,
        repeat,
    },
};

use crate::{
    AnimatedImage, Background, BoxShadow, Canvas, Color, CursorStyle, CustomShader, DispatchPhase,
    Font, FontFallbacks, FontFamily, FontFeatures, Image, ImageSource, Insets, KeyContext,
    MAX_VALIDATION_MESSAGE_BYTES, ObjectFit, Path, Rect, ScenePlane, ShaderParameters, StyledText,
    Svg, SvgTransform, TextAlign, TextHighlight, TextOverflow, TextShaping, TextStyle,
    TextUnderline, TextWrap, Tooltip, Transition, WhiteSpace,
    action::{ActionListenerBinding, MAX_ACTION_LISTENERS_PER_ELEMENT},
    animation::ElementAnimation,
    font::{assert_valid_font_family, normalize_fallbacks},
    spring::ElementSpring,
    virtual_list::{
        ListItemMeasurement, ListState, VirtualList, VirtualScrollHandle, VirtualScrollMount,
    },
};

#[cfg(target_os = "macos")]
use crate::native_view::MacNativeView;
#[cfg(target_os = "macos")]
use objc2_app_kit::NSView;

const SPACING_UNIT: f32 = 4.0;
const DEFAULT_ANCHOR_GAP: f32 = 8.0;
const DEFAULT_VIEWPORT_MARGIN: f32 = 8.0;

macro_rules! state_cursor_helper {
    ($method:ident, $variant:ident, $css:literal) => {
        #[doc = concat!("Use the native `", $css, "` cursor while this state is active.")]
        pub fn $method(self) -> Self {
            self.cursor(CursorStyle::$variant)
        }
    };
}

macro_rules! spacing_scale_methods {
    ($setter:ident; $($method:ident => $units:expr),+ $(,)?) => {
        $(
            pub fn $method(self) -> Self {
                self.$setter(SPACING_UNIT * $units)
            }
        )+
    };
}

/// Maximum CSS-like box shadows retained by one element or interaction-state override.
pub const MAX_BOX_SHADOWS_PER_ELEMENT: usize = 8;

/// Maximum explicit grid tracks accepted on either axis.
///
/// The public grid helpers retain a compact `repeat()` definition, but layout cost still scales
/// with the resolved track count. Keeping this below Taffy's much larger internal safety limit
/// prevents dynamic application data from accidentally creating an expensive desktop layout.
pub const MAX_GRID_TRACKS: u16 = 1_024;

/// Maximum CSS-like container query nodes retained by one window declaration.
pub const MAX_CONTAINER_QUERIES_PER_WINDOW: usize = 1_024;

/// Maximum nested container-query depth resolved in one declaration.
pub const MAX_CONTAINER_QUERY_DEPTH: usize = 16;

/// Maximum targeted desktop mouse declarations attached to one retained element.
///
/// Ordinary elements retain only one optional pointer and allocate nothing for mouse dispatch.
pub const MAX_MOUSE_LISTENERS_PER_ELEMENT: usize = 16;

/// Maximum focused key listeners attached to one retained element.
pub const MAX_KEY_LISTENERS_PER_ELEMENT: usize = 16;

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct MouseListenerKey(pub(crate) u32);

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum MouseListenerKind {
    Down,
    Up,
    Move,
    Exit,
    Hover,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct MouseListenerBinding {
    pub(crate) key: MouseListenerKey,
    pub(crate) kind: MouseListenerKind,
    pub(crate) phase: DispatchPhase,
    pub(crate) button: Option<crate::MouseButton>,
    pub(crate) outside: bool,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct KeyListenerKey(pub(crate) u32);

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum KeyListenerKind {
    Down,
    Up,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct KeyListenerBinding {
    pub(crate) key: KeyListenerKey,
    pub(crate) kind: KeyListenerKind,
    pub(crate) phase: DispatchPhase,
}

const DISMISS_ON_ESCAPE: u8 = 1 << 0;
const DISMISS_ON_POINTER_OUTSIDE: u8 = 1 << 1;

/// Independent event boundaries for one dismissible retained surface.
///
/// Keeping this as one byte lets modal components distinguish ordinary dialogs from alert
/// dialogs without adding another pair of booleans to every [`Element`].
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub(crate) struct DismissPolicy(u8);

impl DismissPolicy {
    pub(crate) const BOTH: Self = Self(DISMISS_ON_ESCAPE | DISMISS_ON_POINTER_OUTSIDE);

    pub(crate) const fn on_escape(self) -> bool {
        self.0 & DISMISS_ON_ESCAPE != 0
    }

    pub(crate) const fn on_pointer_outside(self) -> bool {
        self.0 & DISMISS_ON_POINTER_OUTSIDE != 0
    }

    pub(crate) const fn with_escape(self) -> Self {
        Self(self.0 | DISMISS_ON_ESCAPE)
    }

    pub(crate) const fn with_pointer_outside(self) -> Self {
        Self(self.0 | DISMISS_ON_POINTER_OUTSIDE)
    }

    pub(crate) const fn is_empty(self) -> bool {
        self.0 == 0
    }
}

const MAX_GRID_LINE: i16 = MAX_GRID_TRACKS as i16 + 1;

/// One explicit CSS-grid track used by [`Element::grid_template_columns`] and
/// [`Element::grid_template_rows`].
///
/// Fractional tracks use `minmax(0, Nfr)`, which matches the web-friendly behavior of GPUI's
/// equal-column helpers and allows content to shrink without forcing overflow.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GridTrack(TrackSizingFunction);

impl GridTrack {
    /// A content-sized `auto` track.
    pub fn auto() -> Self {
        Self(auto())
    }

    /// A track sized to its minimum content contribution.
    pub fn min_content() -> Self {
        Self(min_content())
    }

    /// A track sized to its maximum content contribution.
    pub fn max_content() -> Self {
        Self(max_content())
    }

    /// A fixed logical-pixel track.
    pub fn px(value: f32) -> Self {
        Self(length(finite_nonnegative(value)))
    }

    /// A percentage track expressed as a `0.0..=1.0` fraction of the grid container.
    pub fn percent(fraction: f32) -> Self {
        Self(percent(finite_nonnegative(fraction).min(1.0)))
    }

    /// A flexible `minmax(0, Nfr)` track.
    pub fn fr(fraction: f32) -> Self {
        Self(flex(finite_nonnegative(fraction)))
    }

    /// The common responsive web track `minmax(<minimum px>, <fraction>fr)`.
    pub fn minmax_px_fr(minimum: f32, fraction: f32) -> Self {
        Self(minmax(
            length(finite_nonnegative(minimum)),
            fr(finite_nonnegative(fraction)),
        ))
    }

    /// An `auto` minimum with a fixed fit-content limit in logical pixels.
    pub fn fit_content_px(limit: f32) -> Self {
        Self(fit_content(LengthPercentage::length(finite_nonnegative(
            limit,
        ))))
    }
}

#[derive(Clone, Copy, Debug)]
enum EqualGridTrackSizing {
    Zero,
    MinContent,
    MaxContent,
}

fn finite_nonnegative(value: f32) -> f32 {
    if value.is_finite() {
        value.max(0.0)
    } else {
        0.0
    }
}

fn finite_opacity(value: f32) -> f32 {
    if value.is_finite() {
        value.clamp(0.0, 1.0)
    } else {
        1.0
    }
}

fn finite_length(value: f32) -> f32 {
    if value.is_finite() { value } else { 0.0 }
}

fn equal_grid_tracks(
    count: u16,
    sizing: EqualGridTrackSizing,
) -> Vec<GridTemplateComponent<String>> {
    let count = count.min(MAX_GRID_TRACKS);
    if count == 0 {
        return Vec::new();
    }
    let track: TrackSizingFunction = match sizing {
        EqualGridTrackSizing::Zero => minmax(length(0.0_f32), fr(1.0_f32)),
        EqualGridTrackSizing::MinContent => minmax(min_content(), fr(1.0_f32)),
        EqualGridTrackSizing::MaxContent => minmax(length(0.0_f32), max_content()),
    };
    vec![repeat(count, vec![track])]
}

fn bounded_grid_line(index: i16) -> GridPlacement<String> {
    if index == 0 {
        GridPlacement::Auto
    } else {
        line(index.clamp(-MAX_GRID_LINE, MAX_GRID_LINE))
    }
}

fn bounded_grid_span(span: u16) -> GridPlacement<String> {
    GridPlacement::Span(span.clamp(1, MAX_GRID_TRACKS))
}

/// A stable identifier used for hit testing and retained state.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct ElementId(pub(crate) u64);

/// Web-style window drag behavior for a laid-out element.
///
/// A `Drag` region hands primary-button drags to the native window and ignores element-level
/// pointer input. Descendants such as buttons opt back into normal input with `NoDrag`.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum AppRegion {
    Drag,
    NoDrag,
}

impl ElementId {
    pub const fn new(value: u64) -> Self {
        Self(value)
    }

    pub fn named(value: &str) -> Self {
        Self(stable_hash(value.as_bytes()))
    }

    pub const fn as_u64(self) -> u64 {
        self.0
    }

    pub(crate) const fn value(self) -> u64 {
        self.as_u64()
    }
}

impl From<u64> for ElementId {
    fn from(value: u64) -> Self {
        Self::new(value)
    }
}

impl From<usize> for ElementId {
    fn from(value: usize) -> Self {
        Self::new(value as u64)
    }
}

impl From<&str> for ElementId {
    fn from(value: &str) -> Self {
        Self::named(value)
    }
}

impl From<String> for ElementId {
    fn from(value: String) -> Self {
        Self::named(&value)
    }
}

/// A stable handle for programmatic and keyboard focus.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct FocusHandle(ElementId);

impl FocusHandle {
    pub fn new(id: impl Into<ElementId>) -> Self {
        Self(id.into())
    }

    pub const fn id(self) -> ElementId {
        self.0
    }
}

impl From<FocusHandle> for ElementId {
    fn from(value: FocusHandle) -> Self {
        value.id()
    }
}

/// Preferred placement for a floating element relative to its anchor.
///
/// Placement automatically flips to the opposite side when it has more usable space, then shifts
/// inside the window's content viewport.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum AnchorPlacement {
    TopStart,
    Top,
    TopEnd,
    #[default]
    BottomStart,
    Bottom,
    BottomEnd,
    LeftStart,
    Left,
    LeftEnd,
    RightStart,
    Right,
    RightEnd,
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum AnchorTarget {
    Element(ElementId),
    Point(crate::Point),
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct AnchorStyle {
    pub target: AnchorTarget,
    pub placement: AnchorPlacement,
    pub gap: f32,
    pub viewport_margin: f32,
}

/// Platform-neutral semantics used to build the native accessibility tree.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum AccessibilityRole {
    #[default]
    GenericContainer,
    Label,
    Button,
    Link,
    Image,
    List,
    ListItem,
    Heading,
    CheckBox,
    RadioButton,
    RadioGroup,
    Switch,
    TextInput,
    PasswordInput,
    MultilineTextInput,
    Dialog,
    AlertDialog,
    Menu,
    MenuItem,
    MenuItemCheckBox,
    MenuItemRadio,
    /// A non-interactive visual or structural divider.
    ///
    /// AccessKit names the platform-neutral role `Splitter`; without value-changing actions it
    /// projects as the native separator/divider role exposed by each platform adapter.
    Separator,
    Group,
    Region,
    ListBox,
    ListBoxOption,
    ComboBox,
    EditableComboBox,
    Table,
    Tree,
    Grid,
    Row,
    ColumnHeader,
    RowHeader,
    GridCell,
    TreeItem,
    Tab,
    TabList,
    TabPanel,
    Tooltip,
    Form,
}

/// Axis projected for accessibility roles whose behavior changes with orientation.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum AccessibilityOrientation {
    Horizontal,
    Vertical,
}

/// Kind of popover exposed by a trigger to assistive technology.
///
/// This mirrors the finite ARIA/AccessKit `has-popup` vocabulary. It describes the controlled
/// surface without imposing a visual component implementation.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AccessibilityPopover {
    Menu,
    ListBox,
    Tree,
    Grid,
    Dialog,
}

/// Sort order exposed by a table or grid column header.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AccessibilitySortDirection {
    Ascending,
    Descending,
    Other,
}

/// Suggestion presentation exposed by an editable combobox or text input.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AccessibilityAutoComplete {
    Inline,
    List,
    Both,
}

/// The controlled checked state exposed by checkbox-like accessibility roles.
///
/// [`ToggleState::Mixed`] corresponds to the web `indeterminate` state and is intended primarily
/// for checkboxes that summarize a partially selected collection.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum ToggleState {
    #[default]
    Off,
    On,
    Mixed,
}

impl ToggleState {
    pub const fn is_on(self) -> bool {
        matches!(self, Self::On)
    }

    pub const fn is_mixed(self) -> bool {
        matches!(self, Self::Mixed)
    }
}

impl From<bool> for ToggleState {
    fn from(checked: bool) -> Self {
        if checked { Self::On } else { Self::Off }
    }
}

/// CSS-like policy for selecting immutable text with the pointer.
///
/// [`UserSelect::Auto`] keeps ordinary text selectable while inheriting suppression from controls
/// such as buttons and drag sources. [`UserSelect::Text`] explicitly re-enables selection and
/// [`UserSelect::None`] disables it for the complete subtree.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum UserSelect {
    #[default]
    Auto,
    Text,
    None,
}

/// Whether an element subtree is painted while retaining its layout box.
///
/// This mirrors GPUI's visibility model: [`Visibility::Hidden`] suppresses the element and its
/// descendants from paint, input, focus, and accessibility, but their layout still participates.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum Visibility {
    #[default]
    Visible,
    Hidden,
}

/// Converts common values into an [`Element`] for `.child(...)` and `.children(...)`.
pub trait IntoElement {
    fn into_element(self) -> Element;
}

impl IntoElement for Element {
    fn into_element(self) -> Element {
        self
    }
}

impl IntoElement for String {
    fn into_element(self) -> Element {
        text(self)
    }
}

impl IntoElement for Arc<str> {
    fn into_element(self) -> Element {
        text(self)
    }
}

impl IntoElement for &str {
    fn into_element(self) -> Element {
        text(Arc::<str>::from(self))
    }
}

impl IntoElement for Cow<'_, str> {
    fn into_element(self) -> Element {
        text(Arc::<str>::from(self.as_ref()))
    }
}

impl IntoElement for StyledText {
    fn into_element(self) -> Element {
        Element::styled_text(self)
    }
}

#[derive(Clone, Debug)]
pub(crate) enum ElementKind {
    Container,
    ContainerQuery(ContainerQueryElement),
    Text(Arc<str>),
    StyledText(StyledText),
    Image(ImageElement),
    Svg(SvgElement),
    Path(PathElement),
    Canvas(CanvasElement),
    CustomShader(ShaderElement),
    TextInput(TextInputElement),
    #[cfg(target_os = "macos")]
    NativeView(MacNativeView),
}

#[derive(Clone)]
pub(crate) struct ContainerQueryElement {
    render: Rc<dyn Fn(crate::Size) -> Element>,
    pub(crate) resolved_size: Option<crate::Size>,
    /// Declarative motion mounted directly by this callback. Descendant query callbacks retain
    /// their own IDs, which lets a size change unmount exactly the replaced subtree without
    /// disturbing motion elsewhere in the window.
    pub(crate) resolved_motion_ids: Vec<ElementId>,
    pub(crate) layout_pending: bool,
}

impl ContainerQueryElement {
    pub(crate) fn render(&self, size: crate::Size) -> Element {
        (self.render)(size)
    }
}

impl fmt::Debug for ContainerQueryElement {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ContainerQueryElement")
            .field("resolved_size", &self.resolved_size)
            .field("resolved_motion_count", &self.resolved_motion_ids.len())
            .field("layout_pending", &self.layout_pending)
            .finish_non_exhaustive()
    }
}

#[derive(Clone, Debug)]
pub(crate) struct ImageElement {
    pub source: ImageSource,
    pub object_fit: ObjectFit,
    pub grayscale: bool,
    pub resolved: ImageResolution,
    pub loading: Option<ImageReplacement>,
    pub fallback: Option<ImageReplacement>,
}

#[derive(Clone, Debug)]
pub(crate) struct SvgElement {
    pub svg: Svg,
    pub object_fit: ObjectFit,
    pub transform: SvgTransform,
}

#[derive(Clone, Debug)]
pub(crate) struct PathElement {
    pub path: Path,
    pub object_fit: ObjectFit,
    pub background: Option<Background>,
}

#[derive(Clone)]
pub(crate) struct CanvasElement {
    pub painter: Rc<CanvasPainter>,
}

#[derive(Clone, Debug)]
pub(crate) struct ShaderElement {
    pub shader: CustomShader,
    pub parameters: ShaderParameters,
}

type CanvasPainter = dyn for<'a> Fn(Rect, &mut Canvas<'a>);

impl fmt::Debug for CanvasElement {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("CanvasElement(..)")
    }
}

#[derive(Clone, Debug)]
pub(crate) enum ImageResolution {
    Ready(Image),
    Animated(AnimatedImage),
    Loading,
    Failed,
}

#[derive(Clone)]
pub(crate) struct ImageReplacement(Rc<dyn Fn() -> Element>);

impl ImageReplacement {
    fn new<E: IntoElement + 'static>(render: impl Fn() -> E + 'static) -> Self {
        Self(Rc::new(move || render().into_element()))
    }

    pub(crate) fn render(&self) -> Element {
        (self.0)()
    }
}

impl fmt::Debug for ImageReplacement {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("ImageReplacement(..)")
    }
}

#[derive(Clone, Debug)]
pub(crate) struct TextInputElement {
    pub value: Arc<str>,
    pub highlights: Arc<[TextHighlight]>,
    pub placeholder: Arc<str>,
    pub multiline: bool,
    pub password: bool,
    pub constraints: InputConstraints,
}

pub(crate) type InputFilterCallback = Arc<dyn Fn(&str) -> bool>;

#[derive(Clone, Default)]
pub(crate) struct InputConstraints {
    pub max_length: Option<usize>,
    pub filter: Option<InputFilterCallback>,
}

impl fmt::Debug for InputConstraints {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("InputConstraints")
            .field("max_length", &self.max_length)
            .field("filter", &self.filter.as_ref().map(|_| "InputFilter(..)"))
            .finish()
    }
}

#[derive(Clone, Debug, PartialEq)]
pub(crate) struct VisualStyle {
    pub background: Option<Color>,
    pub border_color: Option<Color>,
    pub border_width: f32,
    pub radius: f32,
    pub shadows: Option<Arc<[BoxShadow]>>,
    pub opacity: f32,
}

impl Default for VisualStyle {
    fn default() -> Self {
        Self {
            background: None,
            border_color: None,
            border_width: 0.0,
            radius: 0.0,
            shadows: None,
            opacity: 1.0,
        }
    }
}

/// Non-layout overrides for hover, pressed, focus, validation, and drag states.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ElementStateStyle {
    pub(crate) background: Option<Color>,
    pub(crate) border_color: Option<Color>,
    pub(crate) border_width: Option<f32>,
    pub(crate) radius: Option<f32>,
    pub(crate) text_color: Option<Color>,
    pub(crate) shadows: Option<Arc<[BoxShadow]>>,
    pub(crate) opacity: Option<f32>,
    pub(crate) cursor_style: Option<CursorStyle>,
}

impl ElementStateStyle {
    /// Set the native cursor while this state is active.
    pub fn cursor(mut self, cursor: CursorStyle) -> Self {
        self.cursor_style = Some(cursor);
        self
    }

    state_cursor_helper!(cursor_default, Arrow, "default");
    state_cursor_helper!(cursor_pointer, PointingHand, "pointer");
    state_cursor_helper!(cursor_text, IBeam, "text");
    state_cursor_helper!(cursor_move, ClosedHand, "move");
    state_cursor_helper!(cursor_not_allowed, OperationNotAllowed, "not-allowed");
    state_cursor_helper!(cursor_context_menu, ContextualMenu, "context-menu");
    state_cursor_helper!(cursor_crosshair, Crosshair, "crosshair");
    state_cursor_helper!(
        cursor_vertical_text,
        IBeamCursorForVerticalLayout,
        "vertical-text"
    );
    state_cursor_helper!(cursor_alias, DragLink, "alias");
    state_cursor_helper!(cursor_copy, DragCopy, "copy");
    state_cursor_helper!(cursor_no_drop, OperationNotAllowed, "no-drop");
    state_cursor_helper!(cursor_grab, OpenHand, "grab");
    state_cursor_helper!(cursor_grabbing, ClosedHand, "grabbing");
    state_cursor_helper!(cursor_ew_resize, ResizeLeftRight, "ew-resize");
    state_cursor_helper!(cursor_ns_resize, ResizeUpDown, "ns-resize");
    state_cursor_helper!(cursor_nesw_resize, ResizeUpRightDownLeft, "nesw-resize");
    state_cursor_helper!(cursor_nwse_resize, ResizeUpLeftDownRight, "nwse-resize");
    state_cursor_helper!(cursor_col_resize, ResizeColumn, "col-resize");
    state_cursor_helper!(cursor_row_resize, ResizeRow, "row-resize");
    state_cursor_helper!(cursor_n_resize, ResizeUp, "n-resize");
    state_cursor_helper!(cursor_e_resize, ResizeRight, "e-resize");
    state_cursor_helper!(cursor_s_resize, ResizeDown, "s-resize");
    state_cursor_helper!(cursor_w_resize, ResizeLeft, "w-resize");

    pub fn bg(mut self, color: Color) -> Self {
        self.background = Some(color);
        self
    }

    pub fn border_color(mut self, color: Color) -> Self {
        self.border_color = Some(color);
        self
    }

    /// Paint an inside border without changing layout.
    pub fn border(mut self, width: f32, color: Color) -> Self {
        self.border_width = Some(width.max(0.0));
        self.border_color = Some(color);
        self
    }

    /// Override the paint-only corner radius while this state is active.
    pub fn rounded(mut self, radius: f32) -> Self {
        self.radius = Some(finite_nonnegative(radius));
        self
    }

    pub fn text_color(mut self, color: Color) -> Self {
        self.text_color = Some(color);
        self
    }

    /// Set the opacity of this element and its descendants while this state is active.
    pub fn opacity(mut self, opacity: f32) -> Self {
        self.opacity = Some(finite_opacity(opacity));
        self
    }

    /// Replace the element's shadows while this state is active.
    pub fn shadow(mut self, shadow: BoxShadow) -> Self {
        self.shadows = Some(Arc::from([shadow]));
        self
    }

    /// Replace the element's shadows while this state is active.
    pub fn shadows(mut self, shadows: impl IntoIterator<Item = BoxShadow>) -> Self {
        self.shadows = Some(collect_box_shadows(shadows));
        self
    }

    /// Remove all shadows while this state is active.
    pub fn shadow_none(mut self) -> Self {
        self.shadows = Some(Arc::from([]));
        self
    }

    pub fn shadow_sm(self) -> Self {
        self.shadow(shadow_sm_preset())
    }

    pub fn shadow_md(self) -> Self {
        self.shadows(shadow_md_preset())
    }

    pub fn shadow_lg(self) -> Self {
        self.shadows(shadow_lg_preset())
    }

    pub fn shadow_xl(self) -> Self {
        self.shadows(shadow_xl_preset())
    }

    pub fn shadow_2xl(self) -> Self {
        self.shadow(shadow_2xl_preset())
    }

    fn has_paint_overrides(&self) -> bool {
        self.background.is_some()
            || self.border_color.is_some()
            || self.border_width.is_some()
            || self.radius.is_some()
            || self.text_color.is_some()
            || self.shadows.is_some()
            || self.opacity.is_some()
    }
}

fn shadow_sm_preset() -> BoxShadow {
    BoxShadow::new(0.0, 1.0, Color::rgba8(0, 0, 0, 13)).blur_radius(2.0)
}

fn shadow_md_preset() -> [BoxShadow; 2] {
    [
        BoxShadow::new(0.0, 4.0, Color::rgba8(0, 0, 0, 26))
            .blur_radius(6.0)
            .spread_radius(-1.0),
        BoxShadow::new(0.0, 2.0, Color::rgba8(0, 0, 0, 26))
            .blur_radius(4.0)
            .spread_radius(-2.0),
    ]
}

fn shadow_lg_preset() -> [BoxShadow; 2] {
    [
        BoxShadow::new(0.0, 10.0, Color::rgba8(0, 0, 0, 26))
            .blur_radius(15.0)
            .spread_radius(-3.0),
        BoxShadow::new(0.0, 4.0, Color::rgba8(0, 0, 0, 26))
            .blur_radius(6.0)
            .spread_radius(-4.0),
    ]
}

fn shadow_xl_preset() -> [BoxShadow; 2] {
    [
        BoxShadow::new(0.0, 20.0, Color::rgba8(0, 0, 0, 26))
            .blur_radius(25.0)
            .spread_radius(-5.0),
        BoxShadow::new(0.0, 8.0, Color::rgba8(0, 0, 0, 26))
            .blur_radius(10.0)
            .spread_radius(-6.0),
    ]
}

fn shadow_2xl_preset() -> BoxShadow {
    BoxShadow::new(0.0, 25.0, Color::rgba8(0, 0, 0, 64))
        .blur_radius(50.0)
        .spread_radius(-12.0)
}

fn collect_box_shadows(shadows: impl IntoIterator<Item = BoxShadow>) -> Arc<[BoxShadow]> {
    let mut retained = Vec::with_capacity(2);
    for shadow in shadows {
        assert!(
            retained.len() < MAX_BOX_SHADOWS_PER_ELEMENT,
            "one element retains at most {MAX_BOX_SHADOWS_PER_ELEMENT} box shadows"
        );
        retained.push(shadow);
    }
    Arc::from(retained)
}

#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct AccessibilityStyle {
    pub hidden: bool,
    pub role: AccessibilityRole,
    pub label: Option<Arc<str>>,
    pub value: Option<Arc<str>>,
    pub disabled: bool,
    pub selected: bool,
    pub toggled: Option<ToggleState>,
    pub expanded: Option<bool>,
    pub relations: AccessibilityRelationsStyle,
    pub has_popover: Option<AccessibilityPopover>,
    pub auto_complete: Option<AccessibilityAutoComplete>,
    pub collection: AccessibilityCollectionStyle,
    pub modal: bool,
    pub required: bool,
    pub invalid: bool,
    pub validation_message: Option<Arc<str>>,
    pub validation_message_truncated: bool,
    pub description: Option<Arc<str>>,
    pub orientation: Option<AccessibilityOrientation>,
}

/// Retained keyboard policy for an unstyled tab list.
///
/// This is present only on [`AccessibilityRole::TabList`] elements. It is scanned directly from
/// the mounted tree on explicit keyboard input and retains no item registry or scheduler source.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct TabListBehavior {
    pub(crate) vertical: bool,
    pub(crate) activate_on_focus: bool,
    pub(crate) loop_focus: bool,
}

/// Exact opt-in relationships stored out of line.
///
/// Most retained elements declare no relationship, so they pay one nullable pointer instead of
/// four discriminated `ElementId` words. Relationship-bearing controls allocate one fixed record
/// during declaration and can still represent every `u64` identity without sentinels.
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct AccessibilityRelationsStyle(Option<Box<AccessibilityRelations>>);

#[derive(Clone, Copy, Debug, Default, PartialEq)]
struct AccessibilityRelations {
    controls: Option<ElementId>,
    active_descendant: Option<ElementId>,
    labelled_by: Option<ElementId>,
    described_by: Option<ElementId>,
    described_by_secondary: Option<ElementId>,
}

impl AccessibilityRelationsStyle {
    fn values_mut(&mut self) -> &mut AccessibilityRelations {
        self.0
            .get_or_insert_with(|| Box::new(AccessibilityRelations::default()))
    }

    pub(crate) fn controls(&self) -> Option<ElementId> {
        self.0.as_deref().and_then(|values| values.controls)
    }

    pub(crate) fn set_controls(&mut self, value: ElementId) {
        self.values_mut().controls = Some(value);
    }

    pub(crate) fn active_descendant(&self) -> Option<ElementId> {
        self.0
            .as_deref()
            .and_then(|values| values.active_descendant)
    }

    pub(crate) fn set_active_descendant(&mut self, value: ElementId) {
        self.values_mut().active_descendant = Some(value);
    }

    pub(crate) fn labelled_by(&self) -> Option<ElementId> {
        self.0.as_deref().and_then(|values| values.labelled_by)
    }

    pub(crate) fn set_labelled_by(&mut self, value: ElementId) {
        self.values_mut().labelled_by = Some(value);
    }

    pub(crate) fn described_by(&self) -> Option<ElementId> {
        self.0.as_deref().and_then(|values| values.described_by)
    }

    pub(crate) fn set_described_by(&mut self, value: ElementId) {
        let values = self.values_mut();
        values.described_by = Some(value);
        values.described_by_secondary = None;
    }

    pub(crate) fn described_by_secondary(&self) -> Option<ElementId> {
        self.0
            .as_deref()
            .and_then(|values| values.described_by_secondary)
    }

    pub(crate) fn set_described_by_pair(&mut self, first: ElementId, second: ElementId) {
        let values = self.values_mut();
        values.described_by = Some(first);
        values.described_by_secondary = (second != first).then_some(second);
    }
}

const ACCESSIBILITY_COLLECTION_UNSET: u32 = u32::MAX;

/// Compact inline storage for collection metadata.
///
/// A separate `Option<usize>` for every property would add more than one hundred bytes to every
/// retained element, including ordinary text. The reserved sentinel keeps the complete table/tree
/// vocabulary allocation-free in 32 bytes while still covering QuickGUI's much smaller hard
/// collection bounds.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct AccessibilityCollectionStyle {
    pub row_count: u32,
    pub column_count: u32,
    pub row_index: u32,
    pub column_index: u32,
    pub level: u32,
    pub size_of_set: u32,
    pub position_in_set: u32,
    pub sort_direction: Option<AccessibilitySortDirection>,
}

impl Default for AccessibilityCollectionStyle {
    fn default() -> Self {
        Self {
            row_count: ACCESSIBILITY_COLLECTION_UNSET,
            column_count: ACCESSIBILITY_COLLECTION_UNSET,
            row_index: ACCESSIBILITY_COLLECTION_UNSET,
            column_index: ACCESSIBILITY_COLLECTION_UNSET,
            level: ACCESSIBILITY_COLLECTION_UNSET,
            size_of_set: ACCESSIBILITY_COLLECTION_UNSET,
            position_in_set: ACCESSIBILITY_COLLECTION_UNSET,
            sort_direction: None,
        }
    }
}

impl AccessibilityCollectionStyle {
    pub(crate) fn row_count(self) -> Option<usize> {
        accessibility_collection_value(self.row_count)
    }

    pub(crate) fn column_count(self) -> Option<usize> {
        accessibility_collection_value(self.column_count)
    }

    pub(crate) fn row_index(self) -> Option<usize> {
        accessibility_collection_value(self.row_index)
    }

    pub(crate) fn column_index(self) -> Option<usize> {
        accessibility_collection_value(self.column_index)
    }

    pub(crate) fn level(self) -> Option<usize> {
        accessibility_collection_value(self.level)
    }

    pub(crate) fn size_of_set(self) -> Option<usize> {
        accessibility_collection_value(self.size_of_set)
    }

    pub(crate) fn position_in_set(self) -> Option<usize> {
        accessibility_collection_value(self.position_in_set)
    }
}

fn accessibility_collection_storage(value: usize) -> u32 {
    assert!(
        value < ACCESSIBILITY_COLLECTION_UNSET as usize,
        "accessibility collection values must fit below u32::MAX"
    );
    value as u32
}

fn accessibility_collection_value(value: u32) -> Option<usize> {
    (value != ACCESSIBILITY_COLLECTION_UNSET).then_some(value as usize)
}

#[derive(Clone, Debug)]
pub(crate) struct VirtualScrollStyle {
    pub handle: VirtualScrollHandle,
    pub max_offset_y: f32,
    pub measurement_revision: u64,
    pub mount: VirtualScrollMount,
}

pub(crate) type DropPredicateCallback = Arc<dyn Fn(&dyn Any) -> bool>;

#[derive(Clone)]
pub(crate) struct DropPredicate {
    pub type_id: TypeId,
    pub callback: DropPredicateCallback,
}

impl fmt::Debug for DropPredicate {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("DropPredicate")
            .field("type_id", &self.type_id)
            .finish_non_exhaustive()
    }
}

#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct TypographyStyle {
    pub color: Option<Color>,
    pub font_size: Option<f32>,
    pub line_height: Option<f32>,
    pub monospace_width: Option<f32>,
    pub family: Option<FontFamily>,
    pub features: Option<FontFeatures>,
    pub fallbacks: Option<Option<FontFallbacks>>,
    pub weight: Option<Weight>,
    pub font_style: Option<GlyphStyle>,
    pub font_thicken: Option<bool>,
    pub underline: Option<TextUnderline>,
    pub underline_color: Option<Option<Color>>,
    pub underline_wavy: Option<bool>,
    pub underline_thickness: Option<f32>,
    pub strikethrough: Option<bool>,
    pub strikethrough_color: Option<Option<Color>>,
    pub align: Option<TextAlign>,
    pub wrap: Option<TextWrap>,
    pub text_overflow: Option<TextOverflow>,
    pub line_clamp: Option<usize>,
    pub shaping: Option<TextShaping>,
}

impl TypographyStyle {
    pub(crate) fn resolve(&self, inherited: &TextStyle) -> TextStyle {
        let font_size = self.font_size.unwrap_or(inherited.font_size);
        TextStyle {
            font_size,
            line_height: self.line_height.unwrap_or_else(|| {
                self.font_size
                    .map(|_| font_size * 1.35)
                    .unwrap_or(inherited.line_height)
            }),
            monospace_width: self.monospace_width.or(inherited.monospace_width),
            family: self
                .family
                .clone()
                .unwrap_or_else(|| inherited.family.clone()),
            features: self
                .features
                .clone()
                .unwrap_or_else(|| inherited.features.clone()),
            fallbacks: normalize_fallbacks(
                self.fallbacks
                    .clone()
                    .unwrap_or_else(|| inherited.fallbacks.clone()),
            ),
            weight: self.weight.unwrap_or(inherited.weight),
            font_style: self.font_style.unwrap_or(inherited.font_style),
            font_thicken: self.font_thicken.unwrap_or(inherited.font_thicken),
            underline: self.underline.unwrap_or(inherited.underline),
            underline_color: self.underline_color.unwrap_or(inherited.underline_color),
            underline_wavy: self.underline_wavy.unwrap_or(inherited.underline_wavy),
            underline_thickness: self
                .underline_thickness
                .unwrap_or(inherited.underline_thickness),
            strikethrough: self.strikethrough.unwrap_or(inherited.strikethrough),
            strikethrough_color: self
                .strikethrough_color
                .unwrap_or(inherited.strikethrough_color),
            align: self.align.unwrap_or(inherited.align),
            wrap: self.wrap.unwrap_or(inherited.wrap),
            text_overflow: self
                .text_overflow
                .clone()
                .or_else(|| inherited.text_overflow.clone()),
            line_clamp: self.line_clamp.or(inherited.line_clamp),
            shaping: self.shaping.unwrap_or(inherited.shaping),
            color: self.color.unwrap_or(inherited.color),
        }
    }
}

/// A declarative UI node with Tailwind-like fluent styling.
#[derive(Clone, Debug)]
pub struct Element {
    pub(crate) explicit_id: Option<ElementId>,
    pub(crate) runtime_id: ElementId,
    pub(crate) kind: ElementKind,
    pub(crate) layout: Style,
    pub(crate) visibility: Visibility,
    pub(crate) visual: VisualStyle,
    pub(crate) typography: TypographyStyle,
    pub(crate) resolved_typography: TextStyle,
    pub(crate) hover: ElementStateStyle,
    pub(crate) active: ElementStateStyle,
    pub(crate) focus: ElementStateStyle,
    pub(crate) disabled_style: ElementStateStyle,
    pub(crate) invalid_style: ElementStateStyle,
    pub(crate) dragging: ElementStateStyle,
    pub(crate) drag_over: ElementStateStyle,
    pub(crate) clickable: bool,
    pub(crate) pointer_listener: bool,
    pub(crate) scroll_wheel_listener: bool,
    pub(crate) touch_listener: bool,
    pub(crate) context_menu_listener: bool,
    // This extra indirection is intentional: listeners are uncommon, and keeping the
    // non-interactive Element representation compact matters more than one opt-in allocation.
    #[allow(clippy::box_collection)]
    pub(crate) mouse_listeners: Option<Box<Vec<MouseListenerBinding>>>,
    #[allow(clippy::box_collection)]
    pub(crate) key_listeners: Option<Box<Vec<KeyListenerBinding>>>,
    #[allow(clippy::box_collection)]
    pub(crate) action_listeners: Option<Box<Vec<ActionListenerBinding>>>,
    pub(crate) mouse_pressure_listener: bool,
    pub(crate) pinch_listener: bool,
    pub(crate) rotation_listener: bool,
    pub(crate) smart_magnify_listener: bool,
    pub(crate) drag_source: bool,
    pub(crate) drop_target: bool,
    pub(crate) drop_predicates: Vec<DropPredicate>,
    pub(crate) cursor_style: Option<CursorStyle>,
    pub(crate) cursor_style_explicit: bool,
    pub(crate) user_select: UserSelect,
    pub(crate) resolved_user_select: bool,
    pub(crate) focusable: bool,
    pub(crate) focus_on_pointer: bool,
    pub(crate) hit_slop: Insets,
    pub(crate) focus_trap: bool,
    pub(crate) restore_previous_focus: bool,
    pub(crate) key_context: Option<KeyContext>,
    pub(crate) tab_index: i16,
    pub(crate) auto_focus: bool,
    pub(crate) form: bool,
    pub(crate) form_submitter: bool,
    pub(crate) activation_target: Option<ElementId>,
    pub(crate) accessibility: AccessibilityStyle,
    pub(crate) tab_list_behavior: Option<TabListBehavior>,
    pub(crate) plane: Option<ScenePlane>,
    pub(crate) z_index: Option<i16>,
    pub(crate) portal: bool,
    pub(crate) anchor: Option<AnchorStyle>,
    pub(crate) tooltip: Option<Tooltip>,
    pub(crate) app_region: Option<AppRegion>,
    pub(crate) virtual_scroll: Option<VirtualScrollStyle>,
    pub(crate) scroll_to_end_revision: Option<u64>,
    pub(crate) list_item_measurement: Option<ListItemMeasurement>,
    pub(crate) animation: Option<ElementAnimation>,
    pub(crate) spring: Option<ElementSpring>,
    pub(crate) transition: Option<Transition>,
    pub(crate) blocks_pointer: bool,
    pub(crate) dismiss_policy: DismissPolicy,
    pub(crate) restore_focus: Option<FocusHandle>,
    pub(crate) children: Vec<Element>,
    pub(crate) taffy_node: Option<taffy::NodeId>,
}

/// Create a container element.
pub fn div() -> Element {
    Element::container()
}

/// Create a CSS-like container query whose contents are declared from its assigned size.
///
/// The query fills its parent by default. Its callback is evaluated after the query's own layout,
/// and the returned subtree is laid out independently inside that fixed box, so contents cannot
/// affect the query's intrinsic size.
///
/// An unchanged assigned size retains the existing subtree. A size change evaluates the callback
/// again, while stable declarative-animation IDs keep their playback state. Query contents must be
/// returned from this callback rather than attached with [`Element::child`] or
/// [`Element::children`].
///
/// # Example
///
/// ```
/// use quickgui::{container_query, div, text};
///
/// let responsive = container_query(|size| {
///     if size.width < 480.0 {
///         div().flex_col().child(text("Compact"))
///     } else {
///         div().grid().grid_cols(3).child(text("Wide"))
///     }
/// });
/// ```
pub fn container_query<E>(render: impl Fn(crate::Size) -> E + 'static) -> Element
where
    E: IntoElement,
{
    let mut element = Element::container();
    element.kind = ElementKind::ContainerQuery(ContainerQueryElement {
        render: Rc::new(move |size| render(size).into_element()),
        resolved_size: None,
        resolved_motion_ids: Vec::new(),
        layout_pending: false,
    });
    element.layout.size = TaffySize {
        width: Dimension::percent(1.0),
        height: Dimension::percent(1.0),
    };
    element
}

/// Create a semantic form container.
///
/// Attach callbacks with [`Element::on_form_submit`] and [`Element::on_form_invalid`]. Return in a
/// descendant single-line input and [`submit_button`] both validate the nearest form.
pub fn form() -> Element {
    let mut element = div().accessibility_role(AccessibilityRole::Form);
    element.form = true;
    element
}

/// Create a viewport-level element painted on the overlay plane.
///
/// Overlay elements are removed from normal flow, escape ancestor clipping, and block pointer
/// events inside their bounds. Use [`Element::anchor_to`] for popovers and menus.
pub fn overlay() -> Element {
    div().overlay()
}

/// Create a semantic, keyboard-focusable button container.
pub fn button() -> Element {
    let mut element = div()
        .accessibility_role(AccessibilityRole::Button)
        .focusable();
    element.set_implicit_cursor(CursorStyle::PointingHand);
    element
}

/// Create a button that validates and submits its nearest ancestor [`form`].
pub fn submit_button() -> Element {
    button().form_submitter()
}

/// Create a text element. Strings are owned through `Arc<str>` and cheap to retain.
pub fn text(content: impl Into<Arc<str>>) -> Element {
    Element::text(content.into())
}

/// Create an image element with intrinsic sizing and `object-fit: contain` behavior.
pub fn img(source: impl Into<ImageSource>) -> Element {
    Element::image(source.into())
}

/// Create a monochrome SVG element with intrinsic sizing and inherited text color.
pub fn svg(source: impl Into<Svg>) -> Element {
    Element::svg(source.into())
}

/// Create a retained vector path element with intrinsic sizing and inherited text color.
pub fn path(source: impl Into<Path>) -> Element {
    Element::path(source.into())
}

/// Create a web-like custom paint surface. The callback runs only when the view repaints.
///
/// Callback coordinates are local to the element and are clipped to its layout box.
pub fn canvas(painter: impl for<'a> Fn(Rect, &mut Canvas<'a>) + 'static) -> Element {
    Element::canvas(painter)
}

/// Create a retained rectangle painted by validated application WGSL.
///
/// Like the web canvas default, its initial size is 300 by 150 logical pixels. The shader remains
/// still until application state invalidates the view or explicitly requests another frame.
pub fn custom_shader(shader: impl Into<CustomShader>) -> Element {
    Element::custom_shader(shader.into())
}

/// Create a controlled, single-line text input.
///
/// Attach a stable [`crate::InputListener`] with [`Element::on_input`].
pub fn text_input(value: impl Into<Arc<str>>) -> Element {
    Element::text_input(value.into(), Arc::from([]), false)
}

/// Create a controlled, multiline text area with web-style soft wrapping.
///
/// Attach a stable [`crate::InputListener`] with [`Element::on_input`]. Use [`Element::no_wrap`]
/// for code-editor-style horizontal scrolling.
pub fn text_area(value: impl Into<Arc<str>>) -> Element {
    Element::text_input(value.into(), Arc::from([]), true)
}

/// Create a controlled, single-line input with bounded byte-range text styles.
///
/// Attach a stable [`crate::InputListener`] with [`Element::on_input`] and rebuild the
/// [`StyledText`] from the controlled value when it changes. Editing, selection, IME, hit testing,
/// and painting all reuse the same retained shaped buffer.
pub fn styled_text_input(value: StyledText) -> Element {
    let (value, highlights) = value.into_parts();
    Element::text_input(value, highlights, false)
}

/// Create a controlled, multiline text area with bounded byte-range text styles.
///
/// This is the attributed-text counterpart to [`text_area`]. It preserves wrapping and both-axis
/// scrolling while using the supplied styles for shaping, caret geometry, selection, and paint.
pub fn styled_text_area(value: StyledText) -> Element {
    let (value, highlights) = value.into_parts();
    Element::text_input(value, highlights, true)
}

/// Embed an AppKit view as a declarative leaf on macOS.
///
/// QuickGUI synchronizes layout, clipping, visibility, and sibling order while AppKit keeps
/// ownership of the view's rendering and input behavior.
#[cfg(target_os = "macos")]
pub fn native_view(view: &NSView) -> Element {
    Element::native_view(MacNativeView::new(view))
}

mod construction_layout;
mod interaction;
mod state;
mod style;

fn stable_hash(bytes: &[u8]) -> u64 {
    let mut hash = 0xcbf2_9ce4_8422_2325_u64;
    for byte in bytes {
        hash ^= u64::from(*byte);
        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
    }
    hash
}

fn bounded_validation_message(message: Arc<str>) -> (Option<Arc<str>>, bool) {
    if message.is_empty() {
        return (None, false);
    }
    if message.len() <= MAX_VALIDATION_MESSAGE_BYTES {
        return (Some(message), false);
    }
    let mut end = MAX_VALIDATION_MESSAGE_BYTES;
    while !message.is_char_boundary(end) {
        end -= 1;
    }
    (Some(Arc::from(&message[..end])), true)
}

#[cfg(test)]
mod tests;