Skip to main content

quickgui/
element.rs

1use std::{
2    any::{Any, TypeId},
3    borrow::Cow,
4    cell::RefCell,
5    fmt,
6    rc::Rc,
7    sync::Arc,
8};
9
10use glyphon::{Style as GlyphStyle, Weight};
11use taffy::{
12    Style,
13    geometry::{Line as TaffyLine, Point as TaffyPoint, Rect as TaffyRect, Size as TaffySize},
14    prelude::{
15        AlignContent, AlignItems, AlignSelf, Dimension, Display, FlexDirection, FlexWrap,
16        GridAutoFlow, GridPlacement, GridTemplateComponent, JustifyContent, LengthPercentage,
17        LengthPercentageAuto, Position, TrackSizingFunction,
18    },
19    style::Overflow,
20    style_helpers::{
21        auto, fit_content, flex, fr, length, line, max_content, min_content, minmax, percent,
22        repeat,
23    },
24};
25
26use crate::{
27    AnimatedImage, Background, BorderStyle, BoxShadow, Canvas, Color, ColorStops, Corners,
28    CursorStyle, CustomShader, DispatchPhase, Filter, Filters, Font, FontFallbacks, FontFamily,
29    FontFeatures, Gradient, GradientAngle, GradientCenter, Image, ImageSource, Insets, KeyContext,
30    MAX_VALIDATION_MESSAGE_BYTES, ObjectFit, Path, RadialGradientShape, Rect, ScenePlane,
31    ShaderParameters, StyledText, Svg, SvgTransform, TextAlign, TextCheckingOverrides,
32    TextHighlight, TextOverflow, TextShaping, TextStyle, TextUnderline, TextWrap, Tooltip,
33    Transition, WhiteSpace,
34    action::{ActionListenerBinding, MAX_ACTION_LISTENERS_PER_ELEMENT},
35    animation::ElementAnimation,
36    font::{assert_valid_font_family, normalize_fallbacks},
37    spring::ElementSpring,
38    virtual_list::{
39        ListItemMeasurement, ListState, VirtualList, VirtualScrollHandle, VirtualScrollMount,
40    },
41};
42
43// Direction, sticky positioning, scroll snapping, and extended text styling.
44use crate::{
45    Hyphens, OverflowWrap, TextDirection, TextShadow, TextTransform, WordBreak,
46    scene::sane_text_spacing,
47};
48
49// Compositing layers: transforms, subtree filters, backdrop effects, and blend modes.
50use crate::{BlendMode, DropShadow, Point, Transform2D};
51
52#[cfg(target_os = "macos")]
53use crate::native_view::MacNativeView;
54#[cfg(target_os = "macos")]
55use objc2_app_kit::NSView;
56
57const SPACING_UNIT: f32 = 4.0;
58const DEFAULT_ANCHOR_GAP: f32 = 8.0;
59const DEFAULT_VIEWPORT_MARGIN: f32 = 8.0;
60
61macro_rules! state_cursor_helper {
62    ($method:ident, $variant:ident, $css:literal) => {
63        #[doc = concat!("Use the native `", $css, "` cursor while this state is active.")]
64        pub fn $method(self) -> Self {
65            self.cursor(CursorStyle::$variant)
66        }
67    };
68}
69
70macro_rules! spacing_scale_methods {
71    ($setter:ident; $($method:ident => $units:expr),+ $(,)?) => {
72        $(
73            pub fn $method(self) -> Self {
74                self.$setter(SPACING_UNIT * $units)
75            }
76        )+
77    };
78}
79
80/// Maximum CSS-like box shadows retained by one element or interaction-state override.
81pub const MAX_BOX_SHADOWS_PER_ELEMENT: usize = 8;
82
83/// Longest name a group can be declared with or targeted by, in bytes.
84pub const MAX_HOVER_GROUP_NAME_BYTES: usize = 256;
85/// Most group states — `group_hover` and `group_active` entries together — one element follows.
86pub const MAX_GROUP_STYLES_PER_ELEMENT: usize = 8;
87
88/// Largest accepted outline width in logical pixels.
89pub const MAX_OUTLINE_WIDTH: f32 = 1_024.0;
90/// Largest number of repeated background-image tiles painted for one element.
91///
92/// A tiling that would exceed this bound falls back to a single tile rather than emitting an
93/// unbounded number of per-frame image instances.
94pub const MAX_BACKGROUND_IMAGE_TILES: usize = 256;
95/// Largest accepted absolute outline offset in logical pixels.
96pub const MAX_OUTLINE_OFFSET: f32 = 1_024.0;
97/// Largest accepted corner radius in logical pixels.
98///
99/// Radii are additionally reduced by the CSS uniform-scale rule so two radii sharing one edge
100/// can never overlap.
101pub const MAX_CORNER_RADIUS: f32 = 4_096.0;
102
103/// Maximum explicit grid tracks accepted on either axis.
104///
105/// The public grid helpers retain a compact `repeat()` definition, but layout cost still scales
106/// with the resolved track count. Keeping this below Taffy's much larger internal safety limit
107/// prevents dynamic application data from accidentally creating an expensive desktop layout.
108pub const MAX_GRID_TRACKS: u16 = 1_024;
109
110/// Maximum CSS-like container query nodes retained by one window declaration.
111pub const MAX_CONTAINER_QUERIES_PER_WINDOW: usize = 1_024;
112
113/// Maximum nested container-query depth resolved in one declaration.
114pub const MAX_CONTAINER_QUERY_DEPTH: usize = 16;
115
116/// Maximum targeted desktop mouse declarations attached to one retained element.
117///
118/// Ordinary elements retain only one optional pointer and allocate nothing for mouse dispatch.
119pub const MAX_MOUSE_LISTENERS_PER_ELEMENT: usize = 16;
120
121/// Maximum focused key listeners attached to one retained element.
122pub const MAX_KEY_LISTENERS_PER_ELEMENT: usize = 16;
123
124#[derive(Clone, Copy, Debug, Eq, PartialEq)]
125pub(crate) struct MouseListenerKey(pub(crate) u64);
126
127#[derive(Clone, Copy, Debug, Eq, PartialEq)]
128pub(crate) enum MouseListenerKind {
129    Down,
130    Up,
131    Move,
132    Exit,
133    Hover,
134}
135
136#[derive(Clone, Copy, Debug, Eq, PartialEq)]
137pub(crate) struct MouseListenerBinding {
138    pub(crate) key: MouseListenerKey,
139    pub(crate) kind: MouseListenerKind,
140    pub(crate) phase: DispatchPhase,
141    pub(crate) button: Option<crate::MouseButton>,
142    pub(crate) outside: bool,
143}
144
145#[derive(Clone, Copy, Debug, Eq, PartialEq)]
146pub(crate) struct KeyListenerKey(pub(crate) u64);
147
148#[derive(Clone, Copy, Debug, Eq, PartialEq)]
149pub(crate) enum KeyListenerKind {
150    Down,
151    Up,
152}
153
154#[derive(Clone, Copy, Debug, Eq, PartialEq)]
155pub(crate) struct KeyListenerBinding {
156    pub(crate) key: KeyListenerKey,
157    pub(crate) kind: KeyListenerKind,
158    pub(crate) phase: DispatchPhase,
159}
160
161const DISMISS_ON_ESCAPE: u8 = 1 << 0;
162const DISMISS_ON_POINTER_OUTSIDE: u8 = 1 << 1;
163
164/// Independent event boundaries for one dismissible retained surface.
165///
166/// Keeping this as one byte lets modal components distinguish ordinary dialogs from alert
167/// dialogs without adding another pair of booleans to every [`Element`].
168#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
169pub(crate) struct DismissPolicy(u8);
170
171impl DismissPolicy {
172    pub(crate) const BOTH: Self = Self(DISMISS_ON_ESCAPE | DISMISS_ON_POINTER_OUTSIDE);
173
174    pub(crate) const fn on_escape(self) -> bool {
175        self.0 & DISMISS_ON_ESCAPE != 0
176    }
177
178    pub(crate) const fn on_pointer_outside(self) -> bool {
179        self.0 & DISMISS_ON_POINTER_OUTSIDE != 0
180    }
181
182    pub(crate) const fn with_escape(self) -> Self {
183        Self(self.0 | DISMISS_ON_ESCAPE)
184    }
185
186    pub(crate) const fn with_pointer_outside(self) -> Self {
187        Self(self.0 | DISMISS_ON_POINTER_OUTSIDE)
188    }
189
190    pub(crate) const fn is_empty(self) -> bool {
191        self.0 == 0
192    }
193}
194
195const MAX_GRID_LINE: i16 = MAX_GRID_TRACKS as i16 + 1;
196
197/// One explicit CSS-grid track used by [`Element::grid_template_columns`] and
198/// [`Element::grid_template_rows`].
199///
200/// Fractional tracks use `minmax(0, Nfr)`, which matches the web-friendly behavior of GPUI's
201/// equal-column helpers and allows content to shrink without forcing overflow.
202#[derive(Clone, Copy, Debug, PartialEq)]
203pub struct GridTrack(TrackSizingFunction);
204
205impl GridTrack {
206    /// A content-sized `auto` track.
207    pub fn auto() -> Self {
208        Self(auto())
209    }
210
211    /// A track sized to its minimum content contribution.
212    pub fn min_content() -> Self {
213        Self(min_content())
214    }
215
216    /// A track sized to its maximum content contribution.
217    pub fn max_content() -> Self {
218        Self(max_content())
219    }
220
221    /// A fixed logical-pixel track.
222    pub fn px(value: f32) -> Self {
223        Self(length(finite_nonnegative(value)))
224    }
225
226    /// A percentage track expressed as a `0.0..=1.0` fraction of the grid container.
227    pub fn percent(fraction: f32) -> Self {
228        Self(percent(finite_nonnegative(fraction).min(1.0)))
229    }
230
231    /// A flexible `minmax(0, Nfr)` track.
232    pub fn fr(fraction: f32) -> Self {
233        Self(flex(finite_nonnegative(fraction)))
234    }
235
236    /// The common responsive web track `minmax(<minimum px>, <fraction>fr)`.
237    pub fn minmax_px_fr(minimum: f32, fraction: f32) -> Self {
238        Self(minmax(
239            length(finite_nonnegative(minimum)),
240            fr(finite_nonnegative(fraction)),
241        ))
242    }
243
244    /// An `auto` minimum with a fixed fit-content limit in logical pixels.
245    pub fn fit_content_px(limit: f32) -> Self {
246        Self(fit_content(LengthPercentage::length(finite_nonnegative(
247            limit,
248        ))))
249    }
250}
251
252#[derive(Clone, Copy, Debug)]
253enum EqualGridTrackSizing {
254    Zero,
255    MinContent,
256    MaxContent,
257}
258
259fn finite_nonnegative(value: f32) -> f32 {
260    if value.is_finite() {
261        value.max(0.0)
262    } else {
263        0.0
264    }
265}
266
267fn finite_opacity(value: f32) -> f32 {
268    if value.is_finite() {
269        value.clamp(0.0, 1.0)
270    } else {
271        1.0
272    }
273}
274
275fn finite_length(value: f32) -> f32 {
276    if value.is_finite() { value } else { 0.0 }
277}
278
279fn equal_grid_tracks(
280    count: u16,
281    sizing: EqualGridTrackSizing,
282) -> Vec<GridTemplateComponent<String>> {
283    let count = count.min(MAX_GRID_TRACKS);
284    if count == 0 {
285        return Vec::new();
286    }
287    let track: TrackSizingFunction = match sizing {
288        EqualGridTrackSizing::Zero => minmax(length(0.0_f32), fr(1.0_f32)),
289        EqualGridTrackSizing::MinContent => minmax(min_content(), fr(1.0_f32)),
290        EqualGridTrackSizing::MaxContent => minmax(length(0.0_f32), max_content()),
291    };
292    vec![repeat(count, vec![track])]
293}
294
295fn bounded_grid_line(index: i16) -> GridPlacement<String> {
296    if index == 0 {
297        GridPlacement::Auto
298    } else {
299        line(index.clamp(-MAX_GRID_LINE, MAX_GRID_LINE))
300    }
301}
302
303fn bounded_grid_span(span: u16) -> GridPlacement<String> {
304    GridPlacement::Span(span.clamp(1, MAX_GRID_TRACKS))
305}
306
307/// A stable identifier used for hit testing and retained state.
308#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
309pub struct ElementId(pub(crate) u64);
310
311/// Web-style window drag behavior for a laid-out element.
312///
313/// A `Drag` region hands primary-button drags to the native window and ignores element-level
314/// pointer input. Descendants such as buttons opt back into normal input with `NoDrag`.
315#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
316pub enum AppRegion {
317    Drag,
318    NoDrag,
319}
320
321impl ElementId {
322    pub const fn new(value: u64) -> Self {
323        Self(value)
324    }
325
326    pub fn named(value: &str) -> Self {
327        Self(stable_hash(value.as_bytes()))
328    }
329
330    pub const fn as_u64(self) -> u64 {
331        self.0
332    }
333
334    pub(crate) const fn value(self) -> u64 {
335        self.as_u64()
336    }
337}
338
339impl From<u64> for ElementId {
340    fn from(value: u64) -> Self {
341        Self::new(value)
342    }
343}
344
345impl From<usize> for ElementId {
346    fn from(value: usize) -> Self {
347        Self::new(value as u64)
348    }
349}
350
351impl From<&str> for ElementId {
352    fn from(value: &str) -> Self {
353        Self::named(value)
354    }
355}
356
357impl From<String> for ElementId {
358    fn from(value: String) -> Self {
359        Self::named(&value)
360    }
361}
362
363/// A stable handle for programmatic and keyboard focus.
364#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
365pub struct FocusHandle(ElementId);
366
367impl FocusHandle {
368    pub fn new(id: impl Into<ElementId>) -> Self {
369        Self(id.into())
370    }
371
372    pub const fn id(self) -> ElementId {
373        self.0
374    }
375}
376
377impl From<FocusHandle> for ElementId {
378    fn from(value: FocusHandle) -> Self {
379        value.id()
380    }
381}
382
383/// Preferred placement for a floating element relative to its anchor.
384///
385/// Placement automatically flips to the opposite side when it has more usable space, then shifts
386/// inside the window's content viewport.
387#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
388pub enum AnchorPlacement {
389    TopStart,
390    Top,
391    TopEnd,
392    #[default]
393    BottomStart,
394    Bottom,
395    BottomEnd,
396    LeftStart,
397    Left,
398    LeftEnd,
399    RightStart,
400    Right,
401    RightEnd,
402}
403
404#[derive(Clone, Copy, Debug, PartialEq)]
405pub(crate) enum AnchorTarget {
406    Element(ElementId),
407    Point(crate::Point),
408}
409
410#[derive(Clone, Copy, Debug, PartialEq)]
411pub(crate) struct AnchorStyle {
412    pub target: AnchorTarget,
413    pub placement: AnchorPlacement,
414    pub gap: f32,
415    pub align_offset: f32,
416    pub viewport_margin: f32,
417    pub sticky: bool,
418}
419
420/// Where an anchored element actually landed on the most recently painted frame.
421///
422/// A declared [`AnchorPlacement`] is only a preference: QuickGUI flips to the opposite side and
423/// re-aligns on the cross axis whenever the preferred side does not fit inside the collision
424/// viewport. Presentation that has to follow the real placement — a popover arrow, a
425/// side-dependent transform origin, a popup sized to the space it was actually given — must read
426/// the resolved value instead of guessing from the preference.
427///
428/// Every rectangle is in window logical coordinates.
429#[derive(Clone, Copy, Debug, PartialEq)]
430pub struct ResolvedAnchorPlacement {
431    /// The side and cross-axis alignment the element was actually placed with.
432    pub placement: AnchorPlacement,
433    /// The anchor rectangle the element was placed against.
434    pub anchor: crate::Rect,
435    /// The placed rectangle of the anchored element itself.
436    pub bounds: crate::Rect,
437    /// Space left for the element between the anchor and the collision viewport.
438    ///
439    /// The primary axis measures the gap-adjusted room on [`Self::placement`]'s resolved side; the
440    /// cross axis measures the full margin-inset viewport extent. An application sizes a scrolling
441    /// popup from this instead of measuring the window itself.
442    pub available: crate::Size,
443    /// Whether the anchor rectangle left the collision viewport entirely.
444    ///
445    /// This is the moment Base UI hides a popup whose anchor scrolled out of view; QuickGUI reports
446    /// it and leaves the decision to the application.
447    pub anchor_hidden: bool,
448}
449
450impl ResolvedAnchorPlacement {
451    /// The resolved side, discarding the cross-axis alignment.
452    pub const fn side(self) -> AnchorSide {
453        AnchorSide::of(self.placement)
454    }
455
456    /// The resolved cross-axis alignment, discarding the side.
457    pub const fn align(self) -> AnchorAlign {
458        AnchorAlign::of(self.placement)
459    }
460}
461
462impl Default for ResolvedAnchorPlacement {
463    fn default() -> Self {
464        Self {
465            placement: AnchorPlacement::BottomStart,
466            anchor: crate::Rect::ZERO,
467            bounds: crate::Rect::ZERO,
468            available: crate::Size::ZERO,
469            anchor_hidden: false,
470        }
471    }
472}
473
474#[derive(Debug, Default)]
475struct AnchorPlacementInner {
476    resolved: Option<ResolvedAnchorPlacement>,
477    revision: u64,
478}
479
480/// An application-owned receiver for the placement QuickGUI resolved for one anchored element.
481///
482/// Store the handle on the view next to the state that opens the surface, bind it with
483/// [`Element::report_anchor_placement`], and read [`Self::resolved`] while declaring the next
484/// frame. The handle retains one small allocation and no task, timer, observer, or idle scheduler
485/// source: QuickGUI writes it during the paint it was already performing, and requests exactly one
486/// correcting frame when the resolved placement changed, so a settled window stays settled.
487///
488/// ```
489/// use quickgui::{AnchorPlacement, AnchorPlacementHandle, div};
490///
491/// let placement = AnchorPlacementHandle::new();
492/// assert_eq!(placement.resolved(), None);
493/// let positioner = div()
494///     .anchor_to("trigger", AnchorPlacement::BottomStart)
495///     .report_anchor_placement(placement.clone());
496/// assert!(positioner.reports_anchor_placement());
497/// ```
498#[derive(Clone, Default)]
499pub struct AnchorPlacementHandle(Rc<RefCell<AnchorPlacementInner>>);
500
501impl AnchorPlacementHandle {
502    pub fn new() -> Self {
503        Self::default()
504    }
505
506    /// The placement resolved on the most recent painted frame, or `None` before the first one.
507    pub fn resolved(&self) -> Option<ResolvedAnchorPlacement> {
508        self.0.borrow().resolved
509    }
510
511    /// The resolved placement, falling back to `preferred` before the first painted frame.
512    pub fn placement_or(&self, preferred: AnchorPlacement) -> AnchorPlacement {
513        self.resolved()
514            .map_or(preferred, |resolved| resolved.placement)
515    }
516
517    /// Forget the last resolved placement so a reopened surface cannot read a stale side.
518    pub fn clear(&self) {
519        let mut inner = self.0.borrow_mut();
520        if inner.resolved.is_some() {
521            inner.resolved = None;
522            inner.revision = inner.revision.wrapping_add(1);
523        }
524    }
525
526    pub(crate) fn revision(&self) -> u64 {
527        self.0.borrow().revision
528    }
529
530    pub(crate) fn report(&self, resolved: ResolvedAnchorPlacement) {
531        let mut inner = self.0.borrow_mut();
532        if inner.resolved == Some(resolved) {
533            return;
534        }
535        inner.resolved = Some(resolved);
536        inner.revision = inner.revision.wrapping_add(1);
537    }
538}
539
540impl fmt::Debug for AnchorPlacementHandle {
541    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
542        f.debug_struct("AnchorPlacementHandle")
543            .field("resolved", &self.resolved())
544            .finish_non_exhaustive()
545    }
546}
547
548impl PartialEq for AnchorPlacementHandle {
549    fn eq(&self, other: &Self) -> bool {
550        Rc::ptr_eq(&self.0, &other.0)
551    }
552}
553
554#[derive(Default)]
555struct LayoutBoundsInner {
556    bounds: Option<Rect>,
557    revision: u64,
558}
559
560/// An application-owned receiver for the window-relative bounds QuickGUI laid out for one element.
561///
562/// Store the handle next to the state that depends on the element's real size — a splitter that
563/// must match its container, a scroll area that must know its viewport and content extents — bind
564/// it with [`Element::report_bounds`], and read [`Self::bounds`] while declaring the next frame.
565/// Like [`AnchorPlacementHandle`], it retains one small allocation and no task, timer, observer, or
566/// idle scheduler source: QuickGUI writes it during the paint it was already performing and
567/// requests exactly one correcting frame when the bounds changed, so a settled window stays
568/// settled.
569///
570/// ```
571/// use quickgui::{LayoutBoundsHandle, div};
572///
573/// let bounds = LayoutBoundsHandle::new();
574/// assert_eq!(bounds.bounds(), None);
575/// let pane = div().report_bounds(bounds.clone());
576/// assert!(pane.reports_bounds());
577/// ```
578#[derive(Clone, Default)]
579pub struct LayoutBoundsHandle(Rc<RefCell<LayoutBoundsInner>>);
580
581impl LayoutBoundsHandle {
582    pub fn new() -> Self {
583        Self::default()
584    }
585
586    /// The bounds painted on the most recent frame, in logical window coordinates, or `None`
587    /// before the first painted frame.
588    pub fn bounds(&self) -> Option<Rect> {
589        self.0.borrow().bounds
590    }
591
592    /// Forget the last painted bounds so a remounted element cannot read a stale size.
593    pub fn clear(&self) {
594        let mut inner = self.0.borrow_mut();
595        if inner.bounds.is_some() {
596            inner.bounds = None;
597            inner.revision = inner.revision.wrapping_add(1);
598        }
599    }
600
601    pub(crate) fn revision(&self) -> u64 {
602        self.0.borrow().revision
603    }
604
605    pub(crate) fn report(&self, bounds: Rect) {
606        let mut inner = self.0.borrow_mut();
607        if inner.bounds == Some(bounds) {
608            return;
609        }
610        inner.bounds = Some(bounds);
611        inner.revision = inner.revision.wrapping_add(1);
612    }
613}
614
615impl fmt::Debug for LayoutBoundsHandle {
616    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
617        f.debug_struct("LayoutBoundsHandle")
618            .field("bounds", &self.bounds())
619            .finish_non_exhaustive()
620    }
621}
622
623impl PartialEq for LayoutBoundsHandle {
624    fn eq(&self, other: &Self) -> bool {
625        Rc::ptr_eq(&self.0, &other.0)
626    }
627}
628
629/// The side of its anchor an element was placed on.
630#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
631pub enum AnchorSide {
632    Top,
633    #[default]
634    Bottom,
635    Left,
636    Right,
637}
638
639impl AnchorSide {
640    /// The side half of a full placement.
641    pub const fn of(placement: AnchorPlacement) -> Self {
642        match placement {
643            AnchorPlacement::TopStart | AnchorPlacement::Top | AnchorPlacement::TopEnd => Self::Top,
644            AnchorPlacement::BottomStart | AnchorPlacement::Bottom | AnchorPlacement::BottomEnd => {
645                Self::Bottom
646            }
647            AnchorPlacement::LeftStart | AnchorPlacement::Left | AnchorPlacement::LeftEnd => {
648                Self::Left
649            }
650            AnchorPlacement::RightStart | AnchorPlacement::Right | AnchorPlacement::RightEnd => {
651                Self::Right
652            }
653        }
654    }
655
656    /// The side a flip would move to.
657    pub const fn opposite(self) -> Self {
658        match self {
659            Self::Top => Self::Bottom,
660            Self::Bottom => Self::Top,
661            Self::Left => Self::Right,
662            Self::Right => Self::Left,
663        }
664    }
665
666    /// Whether the side runs along the vertical axis, so the cross axis is horizontal.
667    pub const fn is_vertical(self) -> bool {
668        matches!(self, Self::Top | Self::Bottom)
669    }
670}
671
672/// The cross-axis alignment an element was placed with.
673#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
674pub enum AnchorAlign {
675    #[default]
676    Start,
677    Center,
678    End,
679}
680
681impl AnchorAlign {
682    /// The alignment half of a full placement.
683    pub const fn of(placement: AnchorPlacement) -> Self {
684        match placement {
685            AnchorPlacement::TopStart
686            | AnchorPlacement::BottomStart
687            | AnchorPlacement::LeftStart
688            | AnchorPlacement::RightStart => Self::Start,
689            AnchorPlacement::Top
690            | AnchorPlacement::Bottom
691            | AnchorPlacement::Left
692            | AnchorPlacement::Right => Self::Center,
693            AnchorPlacement::TopEnd
694            | AnchorPlacement::BottomEnd
695            | AnchorPlacement::LeftEnd
696            | AnchorPlacement::RightEnd => Self::End,
697        }
698    }
699}
700
701/// Compose a side and a cross-axis alignment into one [`AnchorPlacement`].
702pub const fn anchor_placement(side: AnchorSide, align: AnchorAlign) -> AnchorPlacement {
703    match (side, align) {
704        (AnchorSide::Top, AnchorAlign::Start) => AnchorPlacement::TopStart,
705        (AnchorSide::Top, AnchorAlign::Center) => AnchorPlacement::Top,
706        (AnchorSide::Top, AnchorAlign::End) => AnchorPlacement::TopEnd,
707        (AnchorSide::Bottom, AnchorAlign::Start) => AnchorPlacement::BottomStart,
708        (AnchorSide::Bottom, AnchorAlign::Center) => AnchorPlacement::Bottom,
709        (AnchorSide::Bottom, AnchorAlign::End) => AnchorPlacement::BottomEnd,
710        (AnchorSide::Left, AnchorAlign::Start) => AnchorPlacement::LeftStart,
711        (AnchorSide::Left, AnchorAlign::Center) => AnchorPlacement::Left,
712        (AnchorSide::Left, AnchorAlign::End) => AnchorPlacement::LeftEnd,
713        (AnchorSide::Right, AnchorAlign::Start) => AnchorPlacement::RightStart,
714        (AnchorSide::Right, AnchorAlign::Center) => AnchorPlacement::Right,
715        (AnchorSide::Right, AnchorAlign::End) => AnchorPlacement::RightEnd,
716    }
717}
718
719/// Platform-neutral semantics used to build the native accessibility tree.
720#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
721pub enum AccessibilityRole {
722    #[default]
723    GenericContainer,
724    Label,
725    Button,
726    Link,
727    Image,
728    List,
729    ListItem,
730    Heading,
731    CheckBox,
732    RadioButton,
733    RadioGroup,
734    Switch,
735    TextInput,
736    PasswordInput,
737    MultilineTextInput,
738    Dialog,
739    AlertDialog,
740    Menu,
741    MenuItem,
742    MenuItemCheckBox,
743    MenuItemRadio,
744    /// A non-interactive visual or structural divider.
745    ///
746    /// AccessKit names the platform-neutral role `Splitter`; without value-changing actions it
747    /// projects as the native separator/divider role exposed by each platform adapter.
748    Separator,
749    Group,
750    Region,
751    ListBox,
752    ListBoxOption,
753    ComboBox,
754    EditableComboBox,
755    Table,
756    Tree,
757    Grid,
758    Row,
759    ColumnHeader,
760    RowHeader,
761    GridCell,
762    TreeItem,
763    Tab,
764    TabList,
765    TabPanel,
766    Tooltip,
767    Form,
768    /// A continuous or stepped range control whose value the user changes directly.
769    Slider,
770    /// A numeric text control with paired increment and decrement affordances.
771    SpinButton,
772    /// A determinate or indeterminate task-completion indicator.
773    ProgressIndicator,
774    /// A static measurement inside a known range, such as disk usage.
775    Meter,
776    /// A movable divider between two resizable panes.
777    ///
778    /// AccessKit names the platform-neutral role `Splitter`. Unlike
779    /// [`AccessibilityRole::Separator`], this variant is focusable and carries a numeric value.
780    SplitterHandle,
781    /// A grouping of controls presented as one compact set of application commands.
782    Toolbar,
783    /// A button with retained pressed state, distinct from a checkbox's checked state.
784    ToggleButton,
785    /// An in-window horizontal set of menu triggers.
786    MenuBar,
787    /// An assertive live region for urgent, time-sensitive messages.
788    Alert,
789    /// A polite live region for advisory status messages.
790    Status,
791    /// A collection of navigation links presented as one landmark.
792    Navigation,
793    /// A clipped scroll viewport whose content is larger than its box.
794    ScrollView,
795    /// A scrollbar whose numeric value is the current scroll position.
796    ScrollBar,
797}
798
799/// Axis projected for accessibility roles whose behavior changes with orientation.
800#[derive(Clone, Copy, Debug, Eq, PartialEq)]
801pub enum AccessibilityOrientation {
802    Horizontal,
803    Vertical,
804}
805
806/// Announcement urgency projected for one live region.
807///
808/// QuickGUI never polls a live region. The projection is rebuilt only when the application
809/// rebuilds the mounted tree, so an unchanged region announces exactly once.
810#[derive(Clone, Copy, Debug, Eq, PartialEq)]
811pub enum AccessibilityLive {
812    /// Announce after the current utterance finishes.
813    Polite,
814    /// Interrupt the current utterance.
815    Assertive,
816}
817
818/// Numeric range projected by slider, spin-button, progress, meter, and splitter roles.
819///
820/// Every field is optional so an indeterminate progress indicator can expose bounds without a
821/// current value. Non-finite inputs are dropped rather than projected.
822#[derive(Clone, Copy, Debug, Default, PartialEq)]
823pub struct AccessibilityValueRange {
824    pub value: Option<f64>,
825    pub min: Option<f64>,
826    pub max: Option<f64>,
827    pub step: Option<f64>,
828}
829
830impl AccessibilityValueRange {
831    /// Create a determinate range. Non-finite components are omitted from the native projection.
832    pub fn new(value: f64, min: f64, max: f64) -> Self {
833        Self {
834            value: finite_value(value),
835            min: finite_value(min),
836            max: finite_value(max),
837            step: None,
838        }
839    }
840
841    /// Create a range with no current value, used by indeterminate progress indicators.
842    pub fn indeterminate(min: f64, max: f64) -> Self {
843        Self {
844            value: None,
845            min: finite_value(min),
846            max: finite_value(max),
847            step: None,
848        }
849    }
850
851    pub fn step(mut self, step: f64) -> Self {
852        self.step = finite_value(step).filter(|step| *step > 0.0);
853        self
854    }
855
856    pub(crate) fn is_empty(&self) -> bool {
857        self.value.is_none() && self.min.is_none() && self.max.is_none() && self.step.is_none()
858    }
859}
860
861fn finite_value(value: f64) -> Option<f64> {
862    value.is_finite().then_some(value)
863}
864
865/// Kind of popover exposed by a trigger to assistive technology.
866///
867/// This mirrors the finite ARIA/AccessKit `has-popup` vocabulary. It describes the controlled
868/// surface without imposing a visual component implementation.
869#[derive(Clone, Copy, Debug, Eq, PartialEq)]
870pub enum AccessibilityPopover {
871    Menu,
872    ListBox,
873    Tree,
874    Grid,
875    Dialog,
876}
877
878/// Sort order exposed by a table or grid column header.
879#[derive(Clone, Copy, Debug, Eq, PartialEq)]
880pub enum AccessibilitySortDirection {
881    Ascending,
882    Descending,
883    Other,
884}
885
886/// Suggestion presentation exposed by an editable combobox or text input.
887#[derive(Clone, Copy, Debug, Eq, PartialEq)]
888pub enum AccessibilityAutoComplete {
889    Inline,
890    List,
891    Both,
892}
893
894/// The controlled checked state exposed by checkbox-like accessibility roles.
895///
896/// [`ToggleState::Mixed`] corresponds to the web `indeterminate` state and is intended primarily
897/// for checkboxes that summarize a partially selected collection.
898#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
899pub enum ToggleState {
900    #[default]
901    Off,
902    On,
903    Mixed,
904}
905
906impl ToggleState {
907    pub const fn is_on(self) -> bool {
908        matches!(self, Self::On)
909    }
910
911    pub const fn is_mixed(self) -> bool {
912        matches!(self, Self::Mixed)
913    }
914}
915
916impl From<bool> for ToggleState {
917    fn from(checked: bool) -> Self {
918        if checked { Self::On } else { Self::Off }
919    }
920}
921
922/// CSS-like policy for selecting immutable text with the pointer.
923///
924/// [`UserSelect::Auto`] keeps ordinary text selectable while inheriting suppression from controls
925/// such as buttons and drag sources. [`UserSelect::Text`] explicitly re-enables selection and
926/// [`UserSelect::None`] disables it for the complete subtree.
927#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
928pub enum UserSelect {
929    #[default]
930    Auto,
931    Text,
932    None,
933}
934
935/// Whether an element subtree is painted while retaining its layout box.
936///
937/// This mirrors GPUI's visibility model: [`Visibility::Hidden`] suppresses the element and its
938/// descendants from paint, input, focus, and accessibility, but their layout still participates.
939#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
940pub enum Visibility {
941    #[default]
942    Visible,
943    Hidden,
944}
945
946/// Converts common values into an [`Element`] for `.child(...)` and `.children(...)`.
947pub trait IntoElement {
948    fn into_element(self) -> Element;
949}
950
951impl IntoElement for Element {
952    fn into_element(self) -> Element {
953        self
954    }
955}
956
957impl IntoElement for String {
958    fn into_element(self) -> Element {
959        text(self)
960    }
961}
962
963impl IntoElement for Arc<str> {
964    fn into_element(self) -> Element {
965        text(self)
966    }
967}
968
969impl IntoElement for &str {
970    fn into_element(self) -> Element {
971        text(Arc::<str>::from(self))
972    }
973}
974
975impl IntoElement for Cow<'_, str> {
976    fn into_element(self) -> Element {
977        text(Arc::<str>::from(self.as_ref()))
978    }
979}
980
981impl IntoElement for StyledText {
982    fn into_element(self) -> Element {
983        Element::styled_text(self)
984    }
985}
986
987#[derive(Clone, Debug)]
988pub(crate) enum ElementKind {
989    Container,
990    ContainerQuery(ContainerQueryElement),
991    Text(Arc<str>),
992    StyledText(StyledText),
993    Image(ImageElement),
994    Svg(SvgElement),
995    Path(PathElement),
996    Canvas(CanvasElement),
997    CustomShader(ShaderElement),
998    TextInput(TextInputElement),
999    #[cfg(target_os = "macos")]
1000    NativeView(MacNativeView),
1001}
1002
1003#[derive(Clone)]
1004pub(crate) struct ContainerQueryElement {
1005    render: Rc<dyn Fn(crate::Size) -> Element>,
1006    pub(crate) resolved_size: Option<crate::Size>,
1007    /// Declarative motion mounted directly by this callback. Descendant query callbacks retain
1008    /// their own IDs, which lets a size change unmount exactly the replaced subtree without
1009    /// disturbing motion elsewhere in the window.
1010    pub(crate) resolved_motion_ids: Vec<ElementId>,
1011    pub(crate) layout_pending: bool,
1012}
1013
1014impl ContainerQueryElement {
1015    pub(crate) fn render(&self, size: crate::Size) -> Element {
1016        (self.render)(size)
1017    }
1018}
1019
1020impl fmt::Debug for ContainerQueryElement {
1021    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1022        formatter
1023            .debug_struct("ContainerQueryElement")
1024            .field("resolved_size", &self.resolved_size)
1025            .field("resolved_motion_count", &self.resolved_motion_ids.len())
1026            .field("layout_pending", &self.layout_pending)
1027            .finish_non_exhaustive()
1028    }
1029}
1030
1031#[derive(Clone, Debug)]
1032pub(crate) struct ImageElement {
1033    pub source: ImageSource,
1034    pub object_fit: ObjectFit,
1035    pub resolved: ImageResolution,
1036    pub loading: Option<ImageReplacement>,
1037    pub fallback: Option<ImageReplacement>,
1038}
1039
1040#[derive(Clone, Debug)]
1041pub(crate) struct SvgElement {
1042    pub svg: Svg,
1043    pub object_fit: ObjectFit,
1044    pub transform: SvgTransform,
1045}
1046
1047#[derive(Clone, Debug)]
1048pub(crate) struct PathElement {
1049    pub path: Path,
1050    pub object_fit: ObjectFit,
1051    pub background: Option<Background>,
1052}
1053
1054#[derive(Clone)]
1055pub(crate) struct CanvasElement {
1056    pub painter: Rc<CanvasPainter>,
1057}
1058
1059#[derive(Clone, Debug)]
1060pub(crate) struct ShaderElement {
1061    pub shader: CustomShader,
1062    pub parameters: ShaderParameters,
1063}
1064
1065type CanvasPainter = dyn for<'a> Fn(Rect, &mut Canvas<'a>);
1066
1067impl fmt::Debug for CanvasElement {
1068    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1069        formatter.write_str("CanvasElement(..)")
1070    }
1071}
1072
1073#[derive(Clone, Debug)]
1074pub(crate) enum ImageResolution {
1075    Ready(Image),
1076    Animated(AnimatedImage),
1077    Loading,
1078    Failed,
1079}
1080
1081#[derive(Clone)]
1082pub(crate) struct ImageReplacement(Rc<dyn Fn() -> Element>);
1083
1084impl ImageReplacement {
1085    fn new<E: IntoElement + 'static>(render: impl Fn() -> E + 'static) -> Self {
1086        Self(Rc::new(move || render().into_element()))
1087    }
1088
1089    pub(crate) fn render(&self) -> Element {
1090        (self.0)()
1091    }
1092}
1093
1094impl fmt::Debug for ImageReplacement {
1095    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1096        formatter.write_str("ImageReplacement(..)")
1097    }
1098}
1099
1100#[derive(Clone, Debug)]
1101pub(crate) struct TextInputElement {
1102    pub value: Arc<str>,
1103    pub highlights: Arc<[TextHighlight]>,
1104    pub placeholder: Arc<str>,
1105    pub multiline: bool,
1106    pub password: bool,
1107    pub constraints: InputConstraints,
1108    #[cfg(feature = "text-input-decorations")]
1109    pub editor: Option<crate::TextInputGutter>,
1110}
1111
1112pub(crate) type InputFilterCallback = Arc<dyn Fn(&str) -> bool>;
1113
1114#[derive(Clone, Default)]
1115pub(crate) struct InputConstraints {
1116    pub max_length: Option<usize>,
1117    pub filter: Option<InputFilterCallback>,
1118    /// Per-input text checking overrides layered over the application policy.
1119    pub text_checking: TextCheckingOverrides,
1120    #[cfg(feature = "text-input-decorations")]
1121    pub editor: Option<crate::TextInputIndentation>,
1122}
1123
1124impl fmt::Debug for InputConstraints {
1125    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1126        let mut debug = formatter.debug_struct("InputConstraints");
1127        debug
1128            .field("max_length", &self.max_length)
1129            .field("filter", &self.filter.as_ref().map(|_| "InputFilter(..)"))
1130            .field("text_checking", &self.text_checking);
1131        #[cfg(feature = "text-input-decorations")]
1132        debug.field("editor", &self.editor);
1133        debug.finish()
1134    }
1135}
1136
1137/// How a background image is scaled inside its element box.
1138#[derive(Clone, Copy, Debug, Default, PartialEq)]
1139pub enum BackgroundSize {
1140    /// Use the decoded pixel size as the logical tile size.
1141    #[default]
1142    Auto,
1143    /// Scale preserving aspect ratio until the tile covers the whole box.
1144    Cover,
1145    /// Scale preserving aspect ratio until the tile fits inside the box.
1146    Contain,
1147    /// An explicit logical tile size.
1148    Fixed(f32, f32),
1149}
1150
1151/// Which axes a background image tiles along.
1152#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
1153pub enum BackgroundRepeat {
1154    /// One tile only.
1155    #[default]
1156    NoRepeat,
1157    RepeatX,
1158    RepeatY,
1159    Repeat,
1160}
1161
1162impl BackgroundRepeat {
1163    pub(crate) fn repeats_x(self) -> bool {
1164        matches!(self, Self::RepeatX | Self::Repeat)
1165    }
1166
1167    pub(crate) fn repeats_y(self) -> bool {
1168        matches!(self, Self::RepeatY | Self::Repeat)
1169    }
1170}
1171
1172/// Where a background tile is anchored, as a fraction of the free space in the element box.
1173///
1174/// `0.0` aligns with the start edge, `0.5` centers, and `1.0` aligns with the end edge. Values
1175/// outside `0.0..=1.0` are clamped so a background image can never escape its own tiling grid.
1176#[derive(Clone, Copy, Debug, PartialEq)]
1177pub struct BackgroundPosition {
1178    pub x: f32,
1179    pub y: f32,
1180}
1181
1182impl Default for BackgroundPosition {
1183    fn default() -> Self {
1184        Self::CENTER
1185    }
1186}
1187
1188impl BackgroundPosition {
1189    pub const TOP_LEFT: Self = Self { x: 0.0, y: 0.0 };
1190    pub const TOP: Self = Self { x: 0.5, y: 0.0 };
1191    pub const TOP_RIGHT: Self = Self { x: 1.0, y: 0.0 };
1192    pub const LEFT: Self = Self { x: 0.0, y: 0.5 };
1193    pub const CENTER: Self = Self { x: 0.5, y: 0.5 };
1194    pub const RIGHT: Self = Self { x: 1.0, y: 0.5 };
1195    pub const BOTTOM_LEFT: Self = Self { x: 0.0, y: 1.0 };
1196    pub const BOTTOM: Self = Self { x: 0.5, y: 1.0 };
1197    pub const BOTTOM_RIGHT: Self = Self { x: 1.0, y: 1.0 };
1198
1199    pub fn new(x: f32, y: f32) -> Self {
1200        Self {
1201            x: if x.is_finite() {
1202                x.clamp(0.0, 1.0)
1203            } else {
1204                0.5
1205            },
1206            y: if y.is_finite() {
1207                y.clamp(0.0, 1.0)
1208            } else {
1209                0.5
1210            },
1211        }
1212    }
1213}
1214
1215/// A raster background painted behind an element's children and inside its rounded corners.
1216#[derive(Clone, Debug, PartialEq)]
1217pub struct BackgroundImage {
1218    pub image: Image,
1219    pub size: BackgroundSize,
1220    pub repeat: BackgroundRepeat,
1221    pub position: BackgroundPosition,
1222}
1223
1224impl BackgroundImage {
1225    pub fn new(image: Image) -> Self {
1226        Self {
1227            image,
1228            size: BackgroundSize::Auto,
1229            repeat: BackgroundRepeat::NoRepeat,
1230            position: BackgroundPosition::CENTER,
1231        }
1232    }
1233
1234    /// The logical tile size for `bounds`, or `None` when nothing can be painted.
1235    pub(crate) fn tile_size(&self, bounds: Rect) -> Option<crate::Size> {
1236        let intrinsic = self.image.size();
1237        if intrinsic.width <= 0.0 || intrinsic.height <= 0.0 {
1238            return None;
1239        }
1240        let size = match self.size {
1241            BackgroundSize::Auto => intrinsic,
1242            BackgroundSize::Fixed(width, height) => crate::Size {
1243                width: if width.is_finite() {
1244                    width.max(0.0)
1245                } else {
1246                    0.0
1247                },
1248                height: if height.is_finite() {
1249                    height.max(0.0)
1250                } else {
1251                    0.0
1252                },
1253            },
1254            BackgroundSize::Cover | BackgroundSize::Contain => {
1255                if bounds.width <= 0.0 || bounds.height <= 0.0 {
1256                    return None;
1257                }
1258                let horizontal = bounds.width / intrinsic.width;
1259                let vertical = bounds.height / intrinsic.height;
1260                let scale = if matches!(self.size, BackgroundSize::Cover) {
1261                    horizontal.max(vertical)
1262                } else {
1263                    horizontal.min(vertical)
1264                };
1265                crate::Size {
1266                    width: intrinsic.width * scale,
1267                    height: intrinsic.height * scale,
1268                }
1269            }
1270        };
1271        (size.width > 0.0 && size.height > 0.0 && size.width.is_finite() && size.height.is_finite())
1272            .then_some(size)
1273    }
1274}
1275
1276/// A ring painted outside the border box without participating in layout.
1277#[derive(Clone, Copy, Debug, PartialEq)]
1278pub struct Outline {
1279    pub width: f32,
1280    pub color: Color,
1281    /// Gap between the border box and the inner edge of the ring. May be negative.
1282    pub offset: f32,
1283    pub style: BorderStyle,
1284}
1285
1286impl Outline {
1287    /// A solid outline with no offset.
1288    pub fn new(width: f32, color: Color) -> Self {
1289        Self {
1290            width: finite_nonnegative(width).min(MAX_OUTLINE_WIDTH),
1291            color,
1292            offset: 0.0,
1293            style: BorderStyle::Solid,
1294        }
1295    }
1296
1297    pub fn offset(mut self, offset: f32) -> Self {
1298        self.offset = if offset.is_finite() {
1299            offset.clamp(-MAX_OUTLINE_OFFSET, MAX_OUTLINE_OFFSET)
1300        } else {
1301            0.0
1302        };
1303        self
1304    }
1305
1306    pub fn style(mut self, style: BorderStyle) -> Self {
1307        self.style = style;
1308        self
1309    }
1310
1311    /// The ring rectangle for a border box, or `None` when nothing is painted.
1312    pub(crate) fn ring(self, bounds: Rect) -> Option<Rect> {
1313        if self.width <= 0.0 || self.color.a <= 0.0 {
1314            return None;
1315        }
1316        let grow = self.offset + self.width;
1317        let left = bounds.x - grow;
1318        let top = bounds.y - grow;
1319        let width = bounds.width + grow * 2.0;
1320        let height = bounds.height + grow * 2.0;
1321        if width <= 0.0 || height <= 0.0 {
1322            return None;
1323        }
1324        Some(Rect::new(left, top, width, height))
1325    }
1326}
1327
1328#[derive(Clone, Debug, PartialEq)]
1329pub(crate) struct VisualStyle {
1330    pub background: Option<Color>,
1331    /// A bounded multi-stop gradient painted instead of `background`.
1332    pub background_gradient: Option<Gradient>,
1333    /// A raster background painted above the background color and behind children.
1334    pub background_image: Option<Box<BackgroundImage>>,
1335    /// A bounded color-filter chain applied to this element's own raster content.
1336    pub filters: Filters,
1337    pub border_color: Option<Color>,
1338    pub border_widths: Insets,
1339    pub border_style: BorderStyle,
1340    pub radius: f32,
1341    /// Per-corner radii. When present they replace `radius` and are not transitioned.
1342    pub corner_radii: Option<Corners>,
1343    /// Explicit radii for a solid background anchored to the nearest scroll viewport.
1344    /// Used by virtual rows whose visible edge moves through the viewport's corners.
1345    pub scroll_background_corners: Option<Corners>,
1346    pub scroll_clip_insets: Option<Insets>,
1347    pub scroll_clip_corners: Option<Corners>,
1348    pub outline: Option<Outline>,
1349    pub shadows: Option<Arc<[BoxShadow]>>,
1350    pub opacity: f32,
1351    /// A subtree transform. Anything but a whole-pixel translation opens a compositing group.
1352    pub transform: Transform2D,
1353    /// Where the transform acts, as a fraction of the element's border box.
1354    pub transform_origin: Point,
1355    /// Color filters applied to what is already painted behind this element.
1356    pub backdrop: Filters,
1357    /// How this element's subtree combines with what is already painted behind it.
1358    pub blend: BlendMode,
1359}
1360
1361impl VisualStyle {
1362    /// The resolved corner radii, preferring explicit per-corner values.
1363    pub(crate) fn corners(&self, radius: f32) -> Corners {
1364        self.corner_radii.unwrap_or(Corners::all(radius))
1365    }
1366}
1367
1368impl Default for VisualStyle {
1369    fn default() -> Self {
1370        Self {
1371            background: None,
1372            background_gradient: None,
1373            background_image: None,
1374            filters: Filters::none(),
1375            border_color: None,
1376            border_widths: Insets::default(),
1377            border_style: BorderStyle::Solid,
1378            radius: 0.0,
1379            corner_radii: None,
1380            scroll_background_corners: None,
1381            scroll_clip_insets: None,
1382            scroll_clip_corners: None,
1383            outline: None,
1384            shadows: None,
1385            opacity: 1.0,
1386            transform: Transform2D::IDENTITY,
1387            transform_origin: Point::new(0.5, 0.5),
1388            backdrop: Filters::none(),
1389            blend: BlendMode::Normal,
1390        }
1391    }
1392}
1393
1394/// Non-layout overrides for hover, pressed, focus, validation, and drag states.
1395#[derive(Clone, Debug, Default, PartialEq)]
1396pub struct ElementStateStyle {
1397    pub(crate) background: Option<Color>,
1398    pub(crate) background_gradient: Option<Gradient>,
1399    pub(crate) outline: Option<Outline>,
1400    pub(crate) border_color: Option<Color>,
1401    pub(crate) border_width: Option<f32>,
1402    pub(crate) radius: Option<f32>,
1403    pub(crate) text_color: Option<Color>,
1404    pub(crate) shadows: Option<Arc<[BoxShadow]>>,
1405    pub(crate) opacity: Option<f32>,
1406    pub(crate) cursor_style: Option<CursorStyle>,
1407    pub(crate) transform: Option<Transform2D>,
1408    pub(crate) transform_origin: Option<Point>,
1409}
1410
1411impl ElementStateStyle {
1412    /// Set the native cursor while this state is active.
1413    pub fn cursor(mut self, cursor: CursorStyle) -> Self {
1414        self.cursor_style = Some(cursor);
1415        self
1416    }
1417
1418    state_cursor_helper!(cursor_default, Arrow, "default");
1419    state_cursor_helper!(cursor_pointer, PointingHand, "pointer");
1420    state_cursor_helper!(cursor_text, IBeam, "text");
1421    state_cursor_helper!(cursor_move, ClosedHand, "move");
1422    state_cursor_helper!(cursor_not_allowed, OperationNotAllowed, "not-allowed");
1423    state_cursor_helper!(cursor_context_menu, ContextualMenu, "context-menu");
1424    state_cursor_helper!(cursor_crosshair, Crosshair, "crosshair");
1425    state_cursor_helper!(
1426        cursor_vertical_text,
1427        IBeamCursorForVerticalLayout,
1428        "vertical-text"
1429    );
1430    state_cursor_helper!(cursor_alias, DragLink, "alias");
1431    state_cursor_helper!(cursor_copy, DragCopy, "copy");
1432    state_cursor_helper!(cursor_no_drop, OperationNotAllowed, "no-drop");
1433    state_cursor_helper!(cursor_grab, OpenHand, "grab");
1434    state_cursor_helper!(cursor_grabbing, ClosedHand, "grabbing");
1435    state_cursor_helper!(cursor_ew_resize, ResizeLeftRight, "ew-resize");
1436    state_cursor_helper!(cursor_ns_resize, ResizeUpDown, "ns-resize");
1437    state_cursor_helper!(cursor_nesw_resize, ResizeUpRightDownLeft, "nesw-resize");
1438    state_cursor_helper!(cursor_nwse_resize, ResizeUpLeftDownRight, "nwse-resize");
1439    state_cursor_helper!(cursor_col_resize, ResizeColumn, "col-resize");
1440    state_cursor_helper!(cursor_row_resize, ResizeRow, "row-resize");
1441    state_cursor_helper!(cursor_n_resize, ResizeUp, "n-resize");
1442    state_cursor_helper!(cursor_e_resize, ResizeRight, "e-resize");
1443    state_cursor_helper!(cursor_s_resize, ResizeDown, "s-resize");
1444    state_cursor_helper!(cursor_w_resize, ResizeLeft, "w-resize");
1445
1446    pub fn bg(mut self, color: Color) -> Self {
1447        self.background = Some(color);
1448        self.background_gradient = None;
1449        self
1450    }
1451
1452    /// Transform the subtree while this state is active.
1453    ///
1454    /// Layout never moves; only paint and hit testing do, so a hover lift or press shrink costs
1455    /// no relayout. A transform in a state overrides the element's own
1456    /// [`Element::transform`](crate::Element::transform).
1457    pub fn transform(mut self, transform: Transform2D) -> Self {
1458        self.transform = Some(transform);
1459        self
1460    }
1461
1462    /// Move the point this state's transform acts around, as a fraction of the border box.
1463    pub fn transform_origin(mut self, x: f32, y: f32) -> Self {
1464        self.transform_origin = Some(Point::new(x, y));
1465        self
1466    }
1467
1468    /// Translate the subtree by logical pixels while this state is active.
1469    pub fn translate(self, x: f32, y: f32) -> Self {
1470        self.transform(Transform2D::translate(x, y))
1471    }
1472
1473    /// Rotate the subtree around its transform origin while this state is active.
1474    pub fn rotate_degrees(self, degrees: f32) -> Self {
1475        self.transform(Transform2D::rotate_degrees(degrees))
1476    }
1477
1478    /// Scale the subtree around its transform origin while this state is active.
1479    pub fn scale(self, x: f32, y: f32) -> Self {
1480        self.transform(Transform2D::scale(x, y))
1481    }
1482
1483    /// Scale the subtree uniformly around its transform origin while this state is active.
1484    pub fn scale_uniform(self, scale: f32) -> Self {
1485        self.transform(Transform2D::scale_uniform(scale))
1486    }
1487
1488    /// Replace the background with a bounded multi-stop gradient while this state is active.
1489    ///
1490    /// Gradients are swapped, not interpolated: only the transitionable solid background,
1491    /// border, radius, shadow, opacity, and text color values animate.
1492    pub fn bg_gradient(mut self, gradient: impl Into<Background>) -> Self {
1493        match gradient.into() {
1494            Background::Solid(color) => {
1495                self.background = Some(color);
1496                self.background_gradient = None;
1497            }
1498            other => {
1499                self.background_gradient = other.as_gradient();
1500            }
1501        }
1502        self
1503    }
1504
1505    /// Paint an outline ring outside the border box while this state is active.
1506    pub fn outline(mut self, width: f32, color: Color) -> Self {
1507        self.outline = Some(Outline::new(width, color));
1508        self
1509    }
1510
1511    /// Paint an offset outline ring outside the border box while this state is active.
1512    pub fn outline_offset(mut self, width: f32, color: Color, offset: f32) -> Self {
1513        self.outline = Some(Outline::new(width, color).offset(offset));
1514        self
1515    }
1516
1517    /// Remove any inherited outline while this state is active.
1518    pub fn outline_none(mut self) -> Self {
1519        self.outline = Some(Outline::new(0.0, Color::TRANSPARENT));
1520        self
1521    }
1522
1523    /// Paint this state's outline as evenly spaced dashes.
1524    pub fn outline_dashed(self) -> Self {
1525        self.outline_style(BorderStyle::Dashed)
1526    }
1527
1528    /// Paint this state's outline as evenly distributed dots.
1529    pub fn outline_dotted(self) -> Self {
1530        self.outline_style(BorderStyle::Dotted)
1531    }
1532
1533    fn outline_style(mut self, style: BorderStyle) -> Self {
1534        let outline = self
1535            .outline
1536            .unwrap_or_else(|| Outline::new(0.0, Color::TRANSPARENT));
1537        self.outline = Some(outline.style(style));
1538        self
1539    }
1540
1541    pub fn border_color(mut self, color: Color) -> Self {
1542        self.border_color = Some(color);
1543        self
1544    }
1545
1546    /// Override the paint-only border width while this state is active, keeping the border color.
1547    pub fn border_width(mut self, width: f32) -> Self {
1548        self.border_width = Some(finite_nonnegative(width));
1549        self
1550    }
1551
1552    /// Paint an inside border without changing layout.
1553    pub fn border(mut self, width: f32, color: Color) -> Self {
1554        self.border_width = Some(width.max(0.0));
1555        self.border_color = Some(color);
1556        self
1557    }
1558
1559    /// Override the paint-only corner radius while this state is active.
1560    pub fn rounded(mut self, radius: f32) -> Self {
1561        self.radius = Some(finite_nonnegative(radius));
1562        self
1563    }
1564
1565    pub fn text_color(mut self, color: Color) -> Self {
1566        self.text_color = Some(color);
1567        self
1568    }
1569
1570    /// Set the opacity of this element and its descendants while this state is active.
1571    pub fn opacity(mut self, opacity: f32) -> Self {
1572        self.opacity = Some(finite_opacity(opacity));
1573        self
1574    }
1575
1576    /// Replace the element's shadows while this state is active.
1577    pub fn shadow(mut self, shadow: BoxShadow) -> Self {
1578        self.shadows = Some(Arc::from([shadow]));
1579        self
1580    }
1581
1582    /// Replace the element's shadows while this state is active.
1583    pub fn shadows(mut self, shadows: impl IntoIterator<Item = BoxShadow>) -> Self {
1584        self.shadows = Some(collect_box_shadows(shadows));
1585        self
1586    }
1587
1588    /// Remove all shadows while this state is active.
1589    pub fn shadow_none(mut self) -> Self {
1590        self.shadows = Some(Arc::from([]));
1591        self
1592    }
1593
1594    pub fn shadow_sm(self) -> Self {
1595        self.shadow(shadow_sm_preset())
1596    }
1597
1598    pub fn shadow_md(self) -> Self {
1599        self.shadows(shadow_md_preset())
1600    }
1601
1602    pub fn shadow_lg(self) -> Self {
1603        self.shadows(shadow_lg_preset())
1604    }
1605
1606    pub fn shadow_xl(self) -> Self {
1607        self.shadows(shadow_xl_preset())
1608    }
1609
1610    pub fn shadow_2xl(self) -> Self {
1611        self.shadow(shadow_2xl_preset())
1612    }
1613
1614    /// Lay `other` over this style: every value it declares replaces the one here.
1615    pub(crate) fn overlay(&mut self, other: &Self) {
1616        if other.background.is_some() {
1617            self.background = other.background;
1618        }
1619        if other.background_gradient.is_some() {
1620            self.background_gradient = other.background_gradient;
1621        }
1622        if other.outline.is_some() {
1623            self.outline = other.outline;
1624        }
1625        if other.border_color.is_some() {
1626            self.border_color = other.border_color;
1627        }
1628        if other.border_width.is_some() {
1629            self.border_width = other.border_width;
1630        }
1631        if other.radius.is_some() {
1632            self.radius = other.radius;
1633        }
1634        if other.text_color.is_some() {
1635            self.text_color = other.text_color;
1636        }
1637        if other.shadows.is_some() {
1638            self.shadows = other.shadows.clone();
1639        }
1640        if other.opacity.is_some() {
1641            self.opacity = other.opacity;
1642        }
1643        if other.cursor_style.is_some() {
1644            self.cursor_style = other.cursor_style;
1645        }
1646        if other.transform.is_some() {
1647            self.transform = other.transform;
1648        }
1649        if other.transform_origin.is_some() {
1650            self.transform_origin = other.transform_origin;
1651        }
1652    }
1653
1654    fn has_paint_overrides(&self) -> bool {
1655        self.background.is_some()
1656            || self.background_gradient.is_some()
1657            || self.outline.is_some()
1658            || self.border_color.is_some()
1659            || self.border_width.is_some()
1660            || self.radius.is_some()
1661            || self.text_color.is_some()
1662            || self.shadows.is_some()
1663            || self.opacity.is_some()
1664    }
1665}
1666
1667/// Which state of an ancestor group a member's style follows.
1668#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1669pub(crate) enum GroupState {
1670    /// The group is hovered.
1671    Hover,
1672    /// A press inside the group is held.
1673    Active,
1674}
1675
1676/// One paint-only style a member paints while an ancestor group is in one state.
1677#[derive(Clone, Debug, PartialEq)]
1678pub(crate) struct GroupStateStyle {
1679    pub(crate) state: GroupState,
1680    /// The named group to follow; `None` follows the nearest group.
1681    pub(crate) target: Option<Arc<str>>,
1682    pub(crate) style: ElementStateStyle,
1683}
1684
1685fn shadow_sm_preset() -> BoxShadow {
1686    BoxShadow::new(0.0, 1.0, Color::rgba8(0, 0, 0, 13)).blur_radius(2.0)
1687}
1688
1689fn shadow_md_preset() -> [BoxShadow; 2] {
1690    [
1691        BoxShadow::new(0.0, 4.0, Color::rgba8(0, 0, 0, 26))
1692            .blur_radius(6.0)
1693            .spread_radius(-1.0),
1694        BoxShadow::new(0.0, 2.0, Color::rgba8(0, 0, 0, 26))
1695            .blur_radius(4.0)
1696            .spread_radius(-2.0),
1697    ]
1698}
1699
1700fn shadow_lg_preset() -> [BoxShadow; 2] {
1701    [
1702        BoxShadow::new(0.0, 10.0, Color::rgba8(0, 0, 0, 26))
1703            .blur_radius(15.0)
1704            .spread_radius(-3.0),
1705        BoxShadow::new(0.0, 4.0, Color::rgba8(0, 0, 0, 26))
1706            .blur_radius(6.0)
1707            .spread_radius(-4.0),
1708    ]
1709}
1710
1711fn shadow_xl_preset() -> [BoxShadow; 2] {
1712    [
1713        BoxShadow::new(0.0, 20.0, Color::rgba8(0, 0, 0, 26))
1714            .blur_radius(25.0)
1715            .spread_radius(-5.0),
1716        BoxShadow::new(0.0, 8.0, Color::rgba8(0, 0, 0, 26))
1717            .blur_radius(10.0)
1718            .spread_radius(-6.0),
1719    ]
1720}
1721
1722fn shadow_2xl_preset() -> BoxShadow {
1723    BoxShadow::new(0.0, 25.0, Color::rgba8(0, 0, 0, 64))
1724        .blur_radius(50.0)
1725        .spread_radius(-12.0)
1726}
1727
1728fn collect_box_shadows(shadows: impl IntoIterator<Item = BoxShadow>) -> Arc<[BoxShadow]> {
1729    let mut retained = Vec::with_capacity(2);
1730    for shadow in shadows {
1731        assert!(
1732            retained.len() < MAX_BOX_SHADOWS_PER_ELEMENT,
1733            "one element retains at most {MAX_BOX_SHADOWS_PER_ELEMENT} box shadows"
1734        );
1735        retained.push(shadow);
1736    }
1737    Arc::from(retained)
1738}
1739
1740#[derive(Clone, Debug, Default, PartialEq)]
1741pub(crate) struct AccessibilityStyle {
1742    pub hidden: bool,
1743    pub role: AccessibilityRole,
1744    pub label: Option<Arc<str>>,
1745    pub value: Option<Arc<str>>,
1746    pub disabled: bool,
1747    pub selected: bool,
1748    pub toggled: Option<ToggleState>,
1749    pub expanded: Option<bool>,
1750    pub relations: AccessibilityRelationsStyle,
1751    pub has_popover: Option<AccessibilityPopover>,
1752    pub auto_complete: Option<AccessibilityAutoComplete>,
1753    pub collection: AccessibilityCollectionStyle,
1754    pub modal: bool,
1755    pub required: bool,
1756    pub read_only: bool,
1757    pub invalid: bool,
1758    pub validation_message: Option<Arc<str>>,
1759    pub validation_message_truncated: bool,
1760    pub description: Option<Arc<str>>,
1761    pub orientation: Option<AccessibilityOrientation>,
1762    pub live: Option<AccessibilityLive>,
1763    pub value_range: Option<Box<AccessibilityValueRange>>,
1764    pub multiselectable: bool,
1765}
1766
1767/// Retained keyboard policy for an unstyled tab list.
1768///
1769/// This is present only on [`AccessibilityRole::TabList`] elements. It is scanned directly from
1770/// the mounted tree on explicit keyboard input and retains no item registry or scheduler source.
1771#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1772pub(crate) struct TabListBehavior {
1773    pub(crate) vertical: bool,
1774    pub(crate) activate_on_focus: bool,
1775    pub(crate) loop_focus: bool,
1776}
1777
1778/// Exact opt-in relationships stored out of line.
1779///
1780/// Most retained elements declare no relationship, so they pay one nullable pointer instead of
1781/// four discriminated `ElementId` words. Relationship-bearing controls allocate one fixed record
1782/// during declaration and can still represent every `u64` identity without sentinels.
1783#[derive(Clone, Debug, Default, PartialEq)]
1784pub(crate) struct AccessibilityRelationsStyle(Option<Box<AccessibilityRelations>>);
1785
1786#[derive(Clone, Copy, Debug, Default, PartialEq)]
1787struct AccessibilityRelations {
1788    controls: Option<ElementId>,
1789    active_descendant: Option<ElementId>,
1790    labelled_by: Option<ElementId>,
1791    described_by: Option<ElementId>,
1792    described_by_secondary: Option<ElementId>,
1793}
1794
1795impl AccessibilityRelationsStyle {
1796    fn values_mut(&mut self) -> &mut AccessibilityRelations {
1797        self.0
1798            .get_or_insert_with(|| Box::new(AccessibilityRelations::default()))
1799    }
1800
1801    pub(crate) fn controls(&self) -> Option<ElementId> {
1802        self.0.as_deref().and_then(|values| values.controls)
1803    }
1804
1805    pub(crate) fn set_controls(&mut self, value: ElementId) {
1806        self.values_mut().controls = Some(value);
1807    }
1808
1809    pub(crate) fn active_descendant(&self) -> Option<ElementId> {
1810        self.0
1811            .as_deref()
1812            .and_then(|values| values.active_descendant)
1813    }
1814
1815    pub(crate) fn set_active_descendant(&mut self, value: ElementId) {
1816        self.values_mut().active_descendant = Some(value);
1817    }
1818
1819    pub(crate) fn labelled_by(&self) -> Option<ElementId> {
1820        self.0.as_deref().and_then(|values| values.labelled_by)
1821    }
1822
1823    pub(crate) fn set_labelled_by(&mut self, value: ElementId) {
1824        self.values_mut().labelled_by = Some(value);
1825    }
1826
1827    pub(crate) fn described_by(&self) -> Option<ElementId> {
1828        self.0.as_deref().and_then(|values| values.described_by)
1829    }
1830
1831    pub(crate) fn set_described_by(&mut self, value: ElementId) {
1832        let values = self.values_mut();
1833        values.described_by = Some(value);
1834        values.described_by_secondary = None;
1835    }
1836
1837    pub(crate) fn described_by_secondary(&self) -> Option<ElementId> {
1838        self.0
1839            .as_deref()
1840            .and_then(|values| values.described_by_secondary)
1841    }
1842
1843    pub(crate) fn set_described_by_pair(&mut self, first: ElementId, second: ElementId) {
1844        let values = self.values_mut();
1845        values.described_by = Some(first);
1846        values.described_by_secondary = (second != first).then_some(second);
1847    }
1848}
1849
1850const ACCESSIBILITY_COLLECTION_UNSET: u32 = u32::MAX;
1851
1852/// Compact inline storage for collection metadata.
1853///
1854/// A separate `Option<usize>` for every property would add more than one hundred bytes to every
1855/// retained element, including ordinary text. The reserved sentinel keeps the complete table/tree
1856/// vocabulary allocation-free in 32 bytes while still covering QuickGUI's much smaller hard
1857/// collection bounds.
1858#[derive(Clone, Copy, Debug, PartialEq)]
1859pub(crate) struct AccessibilityCollectionStyle {
1860    pub row_count: u32,
1861    pub column_count: u32,
1862    pub row_index: u32,
1863    pub column_index: u32,
1864    pub level: u32,
1865    pub size_of_set: u32,
1866    pub position_in_set: u32,
1867    pub sort_direction: Option<AccessibilitySortDirection>,
1868}
1869
1870impl Default for AccessibilityCollectionStyle {
1871    fn default() -> Self {
1872        Self {
1873            row_count: ACCESSIBILITY_COLLECTION_UNSET,
1874            column_count: ACCESSIBILITY_COLLECTION_UNSET,
1875            row_index: ACCESSIBILITY_COLLECTION_UNSET,
1876            column_index: ACCESSIBILITY_COLLECTION_UNSET,
1877            level: ACCESSIBILITY_COLLECTION_UNSET,
1878            size_of_set: ACCESSIBILITY_COLLECTION_UNSET,
1879            position_in_set: ACCESSIBILITY_COLLECTION_UNSET,
1880            sort_direction: None,
1881        }
1882    }
1883}
1884
1885impl AccessibilityCollectionStyle {
1886    pub(crate) fn row_count(self) -> Option<usize> {
1887        accessibility_collection_value(self.row_count)
1888    }
1889
1890    pub(crate) fn column_count(self) -> Option<usize> {
1891        accessibility_collection_value(self.column_count)
1892    }
1893
1894    pub(crate) fn row_index(self) -> Option<usize> {
1895        accessibility_collection_value(self.row_index)
1896    }
1897
1898    pub(crate) fn column_index(self) -> Option<usize> {
1899        accessibility_collection_value(self.column_index)
1900    }
1901
1902    pub(crate) fn level(self) -> Option<usize> {
1903        accessibility_collection_value(self.level)
1904    }
1905
1906    pub(crate) fn size_of_set(self) -> Option<usize> {
1907        accessibility_collection_value(self.size_of_set)
1908    }
1909
1910    pub(crate) fn position_in_set(self) -> Option<usize> {
1911        accessibility_collection_value(self.position_in_set)
1912    }
1913}
1914
1915fn accessibility_collection_storage(value: usize) -> u32 {
1916    assert!(
1917        value < ACCESSIBILITY_COLLECTION_UNSET as usize,
1918        "accessibility collection values must fit below u32::MAX"
1919    );
1920    value as u32
1921}
1922
1923fn accessibility_collection_value(value: u32) -> Option<usize> {
1924    (value != ACCESSIBILITY_COLLECTION_UNSET).then_some(value as usize)
1925}
1926
1927#[derive(Clone, Debug)]
1928pub(crate) struct VirtualScrollStyle {
1929    pub handle: VirtualScrollHandle,
1930    pub max_offset_y: f32,
1931    pub measurement_revision: u64,
1932    pub mount: VirtualScrollMount,
1933    pub report_viewport: bool,
1934}
1935
1936pub(crate) type DropPredicateCallback = Arc<dyn Fn(&dyn Any) -> bool>;
1937
1938#[derive(Clone)]
1939pub(crate) struct DropPredicate {
1940    pub type_id: TypeId,
1941    pub callback: DropPredicateCallback,
1942}
1943
1944impl fmt::Debug for DropPredicate {
1945    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1946        formatter
1947            .debug_struct("DropPredicate")
1948            .field("type_id", &self.type_id)
1949            .finish_non_exhaustive()
1950    }
1951}
1952
1953#[derive(Clone, Debug, Default, PartialEq)]
1954pub(crate) struct TypographyStyle {
1955    pub color: Option<Color>,
1956    pub font_size: Option<f32>,
1957    pub line_height: Option<f32>,
1958    pub monospace_width: Option<f32>,
1959    pub family: Option<FontFamily>,
1960    pub features: Option<FontFeatures>,
1961    pub fallbacks: Option<Option<FontFallbacks>>,
1962    pub weight: Option<Weight>,
1963    pub font_style: Option<GlyphStyle>,
1964    pub font_thicken: Option<bool>,
1965    pub underline: Option<TextUnderline>,
1966    pub underline_color: Option<Option<Color>>,
1967    pub underline_wavy: Option<bool>,
1968    pub underline_thickness: Option<f32>,
1969    pub strikethrough: Option<bool>,
1970    pub strikethrough_color: Option<Option<Color>>,
1971    pub overline: Option<bool>,
1972    pub overline_color: Option<Option<Color>>,
1973    pub direction: Option<TextDirection>,
1974    pub letter_spacing: Option<f32>,
1975    pub word_spacing: Option<f32>,
1976    pub transform: Option<Option<TextTransform>>,
1977    pub word_break: Option<WordBreak>,
1978    pub overflow_wrap: Option<OverflowWrap>,
1979    pub hyphens: Option<Hyphens>,
1980    pub shadow: Option<Option<TextShadow>>,
1981    pub align: Option<TextAlign>,
1982    pub wrap: Option<TextWrap>,
1983    pub text_overflow: Option<TextOverflow>,
1984    pub line_clamp: Option<usize>,
1985    pub shaping: Option<TextShaping>,
1986}
1987
1988impl TypographyStyle {
1989    pub(crate) fn resolve(&self, inherited: &TextStyle) -> TextStyle {
1990        let font_size = self.font_size.unwrap_or(inherited.font_size);
1991        TextStyle {
1992            font_size,
1993            line_height: self.line_height.unwrap_or_else(|| {
1994                self.font_size
1995                    .map(|_| font_size * 1.35)
1996                    .unwrap_or(inherited.line_height)
1997            }),
1998            monospace_width: self.monospace_width.or(inherited.monospace_width),
1999            family: self
2000                .family
2001                .clone()
2002                .unwrap_or_else(|| inherited.family.clone()),
2003            features: self
2004                .features
2005                .clone()
2006                .unwrap_or_else(|| inherited.features.clone()),
2007            fallbacks: normalize_fallbacks(
2008                self.fallbacks
2009                    .clone()
2010                    .unwrap_or_else(|| inherited.fallbacks.clone()),
2011            ),
2012            weight: self.weight.unwrap_or(inherited.weight),
2013            font_style: self.font_style.unwrap_or(inherited.font_style),
2014            font_thicken: self.font_thicken.unwrap_or(inherited.font_thicken),
2015            underline: self.underline.unwrap_or(inherited.underline),
2016            underline_color: self.underline_color.unwrap_or(inherited.underline_color),
2017            underline_wavy: self.underline_wavy.unwrap_or(inherited.underline_wavy),
2018            underline_thickness: self
2019                .underline_thickness
2020                .unwrap_or(inherited.underline_thickness),
2021            strikethrough: self.strikethrough.unwrap_or(inherited.strikethrough),
2022            strikethrough_color: self
2023                .strikethrough_color
2024                .unwrap_or(inherited.strikethrough_color),
2025            overline: self.overline.unwrap_or(inherited.overline),
2026            overline_color: self.overline_color.unwrap_or(inherited.overline_color),
2027            direction: self.direction.unwrap_or(inherited.direction),
2028            letter_spacing: self.letter_spacing.unwrap_or(inherited.letter_spacing),
2029            word_spacing: self.word_spacing.unwrap_or(inherited.word_spacing),
2030            transform: self.transform.unwrap_or(inherited.transform),
2031            word_break: self.word_break.unwrap_or(inherited.word_break),
2032            overflow_wrap: self.overflow_wrap.unwrap_or(inherited.overflow_wrap),
2033            hyphens: self.hyphens.unwrap_or(inherited.hyphens),
2034            shadow: self.shadow.unwrap_or(inherited.shadow),
2035            align: self.align.unwrap_or(inherited.align),
2036            wrap: self.wrap.unwrap_or(inherited.wrap),
2037            text_overflow: self
2038                .text_overflow
2039                .clone()
2040                .or_else(|| inherited.text_overflow.clone()),
2041            line_clamp: self.line_clamp.or(inherited.line_clamp),
2042            shaping: self.shaping.unwrap_or(inherited.shaping),
2043            color: self.color.unwrap_or(inherited.color),
2044        }
2045    }
2046}
2047
2048/// A declarative UI node with Tailwind-like fluent styling.
2049///
2050/// See [`ElementUpdate`] for targeted updates from an embedding runtime that already owns a
2051/// retained declaration.
2052#[derive(Clone, Debug)]
2053pub struct Element {
2054    pub(crate) explicit_id: Option<ElementId>,
2055    pub(crate) runtime_id: ElementId,
2056    pub(crate) kind: ElementKind,
2057    pub(crate) layout: Style,
2058    pub(crate) visibility: Visibility,
2059    pub(crate) visual: VisualStyle,
2060    pub(crate) typography: TypographyStyle,
2061    pub(crate) resolved_typography: TextStyle,
2062    pub(crate) hover: ElementStateStyle,
2063    pub(crate) active: ElementStateStyle,
2064    pub(crate) focus: ElementStateStyle,
2065    pub(crate) disabled_style: ElementStateStyle,
2066    pub(crate) invalid_style: ElementStateStyle,
2067    /// Paint while this element is marked selected, like a chosen row of a native list.
2068    pub(crate) selected_style: ElementStateStyle,
2069    pub(crate) dragging: ElementStateStyle,
2070    pub(crate) drag_over: ElementStateStyle,
2071    /// Paint while this element or a descendant owns keyboard focus, like CSS `:focus-within`.
2072    pub(crate) focus_within: ElementStateStyle,
2073    /// Styles following the state of an ancestor group, in declaration order; later ones win.
2074    pub(crate) group_styles: Vec<GroupStateStyle>,
2075    /// Whether descendants' `group_hover` and `group_active` styles follow this element.
2076    pub(crate) group: bool,
2077    /// The name descendants can target this group by.
2078    pub(crate) group_name: Option<Arc<str>>,
2079    pub(crate) clickable: bool,
2080    pub(crate) pointer_listener: bool,
2081    pub(crate) scroll_wheel_listener: bool,
2082    pub(crate) touch_listener: bool,
2083    pub(crate) context_menu_listener: bool,
2084    // This extra indirection is intentional: listeners are uncommon, and keeping the
2085    // non-interactive Element representation compact matters more than one opt-in allocation.
2086    #[allow(clippy::box_collection)]
2087    pub(crate) mouse_listeners: Option<Box<Vec<MouseListenerBinding>>>,
2088    #[allow(clippy::box_collection)]
2089    pub(crate) key_listeners: Option<Box<Vec<KeyListenerBinding>>>,
2090    #[allow(clippy::box_collection)]
2091    pub(crate) action_listeners: Option<Box<Vec<ActionListenerBinding>>>,
2092    pub(crate) mouse_pressure_listener: bool,
2093    pub(crate) pinch_listener: bool,
2094    pub(crate) rotation_listener: bool,
2095    pub(crate) smart_magnify_listener: bool,
2096    pub(crate) drag_source: bool,
2097    pub(crate) drop_target: bool,
2098    pub(crate) drop_predicates: Vec<DropPredicate>,
2099    pub(crate) cursor_style: Option<CursorStyle>,
2100    pub(crate) cursor_style_explicit: bool,
2101    pub(crate) user_select: UserSelect,
2102    pub(crate) resolved_user_select: bool,
2103    pub(crate) focusable: bool,
2104    pub(crate) focusable_when_disabled: bool,
2105    pub(crate) focus_on_pointer: bool,
2106    pub(crate) hit_slop: Insets,
2107    pub(crate) focus_trap: bool,
2108    pub(crate) restore_previous_focus: bool,
2109    pub(crate) key_context: Option<KeyContext>,
2110    pub(crate) tab_index: i16,
2111    pub(crate) auto_focus: bool,
2112    pub(crate) form: bool,
2113    pub(crate) form_submitter: bool,
2114    pub(crate) activation_target: Option<ElementId>,
2115    pub(crate) accessibility: AccessibilityStyle,
2116    pub(crate) tab_list_behavior: Option<TabListBehavior>,
2117    pub(crate) plane: Option<ScenePlane>,
2118    pub(crate) z_index: Option<i16>,
2119    pub(crate) portal: bool,
2120    pub(crate) anchor: Option<AnchorStyle>,
2121    pub(crate) anchor_placement: Option<AnchorPlacementHandle>,
2122    pub(crate) layout_bounds: Option<LayoutBoundsHandle>,
2123    pub(crate) tooltip: Option<Tooltip>,
2124    pub(crate) app_region: Option<AppRegion>,
2125    pub(crate) virtual_scroll: Option<VirtualScrollStyle>,
2126    /// Keep wheel/trackpad scrolling active while suppressing the built-in vertical overlay thumb.
2127    pub(crate) vertical_scrollbar_hidden: bool,
2128    /// Reserve a fixed left strip outside the horizontal overlay scrollbar track.
2129    pub(crate) horizontal_scrollbar_left_inset: f32,
2130    pub(crate) scroll_to_end_revision: Option<u64>,
2131    pub(crate) layout_rounding: bool,
2132    pub(crate) list_item_measurement: Option<ListItemMeasurement>,
2133    pub(crate) animation: Option<ElementAnimation>,
2134    pub(crate) spring: Option<ElementSpring>,
2135    /// The declaration callback was consumed, but still owns this resolved subtree's values.
2136    pub(crate) resolved_motion: bool,
2137    pub(crate) transition: Option<Transition>,
2138    pub(crate) blocks_pointer: bool,
2139    pub(crate) dismiss_policy: DismissPolicy,
2140    pub(crate) restore_focus: Option<FocusHandle>,
2141    pub(crate) children: Vec<Element>,
2142    pub(crate) taffy_node: Option<taffy::NodeId>,
2143    /// Declared inline layout direction; inherited when absent.
2144    pub(crate) direction: Option<Direction>,
2145    /// Direction resolved against the ancestor chain during layout build.
2146    pub(crate) resolved_direction: Direction,
2147    /// Direction-relative padding and border overrides resolved during layout build.
2148    pub(crate) logical_insets: Option<Box<LogicalInsets>>,
2149    /// CSS-style sticky offsets relative to the nearest scroll container.
2150    pub(crate) sticky: Option<StickyInsets>,
2151    /// Scroll-snap strictness declared by this scroll container.
2152    pub(crate) scroll_snap: Option<ScrollSnapStyle>,
2153    /// Snap alignment declared by a scroll-snap child.
2154    pub(crate) snap_align: Option<SnapAlign>,
2155    /// Whether a scroll gesture may never skip past this snap child.
2156    pub(crate) snap_stop_always: bool,
2157}
2158
2159/// A change to a mounted element, addressed by stable identity.
2160///
2161/// Embedding runtimes can submit a batch with [`crate::AppRunner::update_elements`] after
2162/// updating their source declaration. Text changes invalidate intrinsic layout along the
2163/// affected ancestor path. Colors and opacity require paint only. Unsupported or unmounted
2164/// targets reject the entire batch, allowing the caller to request an ordinary view rebuild.
2165#[derive(Clone, Debug)]
2166pub enum ElementUpdate {
2167    Text {
2168        id: ElementId,
2169        content: Arc<str>,
2170    },
2171    BackgroundColor {
2172        id: ElementId,
2173        color: Color,
2174    },
2175    TextColor {
2176        id: ElementId,
2177        color: Color,
2178    },
2179    Opacity {
2180        id: ElementId,
2181        opacity: f32,
2182    },
2183    /// Change placement without measuring or laying out the subtree again.
2184    Transform {
2185        id: ElementId,
2186        transform: Transform2D,
2187    },
2188    /// Replace a declaration at an existing identity, retaining keyed layout and input state.
2189    /// The replacement root must have the same explicit ID. Register replacement listeners
2190    /// through a component scope; this operation itself does not register callbacks.
2191    Replace {
2192        id: ElementId,
2193        element: Box<Element>,
2194    },
2195}
2196
2197impl ElementUpdate {
2198    pub(crate) fn apply_to_declaration(&self, element: &mut Element) -> bool {
2199        if element.explicit_id != Some(self.id()) {
2200            return false;
2201        }
2202        match self {
2203            Self::Text { content, .. } => {
2204                let ElementKind::Text(value) = &mut element.kind else {
2205                    return false;
2206                };
2207                *value = content.clone();
2208            }
2209            Self::BackgroundColor { color, .. } => element.visual.background = Some(*color),
2210            Self::TextColor { color, .. } => element.typography.color = Some(*color),
2211            Self::Opacity { opacity, .. } => {
2212                element.visual.opacity = if opacity.is_finite() {
2213                    opacity.clamp(0.0, 1.0)
2214                } else {
2215                    1.0
2216                }
2217            }
2218            Self::Transform { transform, .. } => element.visual.transform = *transform,
2219            Self::Replace { .. } => return false,
2220        }
2221        true
2222    }
2223
2224    pub fn id(&self) -> ElementId {
2225        match self {
2226            Self::Text { id, .. }
2227            | Self::BackgroundColor { id, .. }
2228            | Self::TextColor { id, .. }
2229            | Self::Opacity { id, .. }
2230            | Self::Transform { id, .. }
2231            | Self::Replace { id, .. } => *id,
2232        }
2233    }
2234}
2235
2236impl Element {
2237    /// Whether keyboard focus may land on this element.
2238    ///
2239    /// A disabled control leaves the Tab sequence, which is the web default. Toolbars are the
2240    /// documented exception: an item that opts into [`Element::focusable_when_disabled`] stays
2241    /// reachable so a keyboard user can discover why it is unavailable.
2242    pub(crate) const fn is_keyboard_focusable(&self) -> bool {
2243        self.focusable && (!self.accessibility.disabled || self.focusable_when_disabled)
2244    }
2245}
2246
2247/// Create a container element.
2248pub fn div() -> Element {
2249    Element::container()
2250}
2251
2252/// Create a CSS-like container query whose contents are declared from its assigned size.
2253///
2254/// The query fills its parent by default. Its callback is evaluated after the query's own layout,
2255/// and the returned subtree is laid out independently inside that fixed box, so contents cannot
2256/// affect the query's intrinsic size.
2257///
2258/// An unchanged assigned size retains the existing subtree. A size change evaluates the callback
2259/// again, while stable declarative-animation IDs keep their playback state. Query contents must be
2260/// returned from this callback rather than attached with [`Element::child`] or
2261/// [`Element::children`].
2262///
2263/// # Example
2264///
2265/// ```
2266/// use quickgui::{container_query, div, text};
2267///
2268/// let responsive = container_query(|size| {
2269///     if size.width < 480.0 {
2270///         div().flex_col().child(text("Compact"))
2271///     } else {
2272///         div().grid().grid_cols(3).child(text("Wide"))
2273///     }
2274/// });
2275/// ```
2276pub fn container_query<E>(render: impl Fn(crate::Size) -> E + 'static) -> Element
2277where
2278    E: IntoElement,
2279{
2280    let mut element = Element::container();
2281    element.kind = ElementKind::ContainerQuery(ContainerQueryElement {
2282        render: Rc::new(move |size| render(size).into_element()),
2283        resolved_size: None,
2284        resolved_motion_ids: Vec::new(),
2285        layout_pending: false,
2286    });
2287    element.layout.size = TaffySize {
2288        width: Dimension::percent(1.0),
2289        height: Dimension::percent(1.0),
2290    };
2291    element
2292}
2293
2294/// Create a semantic form container.
2295///
2296/// Attach callbacks with [`Element::on_form_submit`] and [`Element::on_form_invalid`]. Return in a
2297/// descendant single-line input and [`submit_button`] both validate the nearest form.
2298pub fn form() -> Element {
2299    let mut element = div().accessibility_role(AccessibilityRole::Form);
2300    element.form = true;
2301    element
2302}
2303
2304/// Create a viewport-level element painted on the overlay plane.
2305///
2306/// Overlay elements are removed from normal flow, escape ancestor clipping, and block pointer
2307/// events inside their bounds. Use [`Element::anchor_to`] for popovers and menus.
2308pub fn overlay() -> Element {
2309    div().overlay()
2310}
2311
2312/// Create a semantic, keyboard-focusable button container.
2313pub fn button() -> Element {
2314    let mut element = div()
2315        .accessibility_role(AccessibilityRole::Button)
2316        .focusable();
2317    element.set_implicit_cursor(CursorStyle::PointingHand);
2318    element
2319}
2320
2321/// Create a button that validates and submits its nearest ancestor [`form`].
2322pub fn submit_button() -> Element {
2323    button().form_submitter()
2324}
2325
2326/// Create a text element. Strings are owned through `Arc<str>` and cheap to retain.
2327pub fn text(content: impl Into<Arc<str>>) -> Element {
2328    Element::text(content.into())
2329}
2330
2331/// Create an image element with intrinsic sizing and `object-fit: contain` behavior.
2332pub fn img(source: impl Into<ImageSource>) -> Element {
2333    Element::image(source.into())
2334}
2335
2336/// Create a monochrome SVG element with intrinsic sizing and inherited text color.
2337pub fn svg(source: impl Into<Svg>) -> Element {
2338    Element::svg(source.into())
2339}
2340
2341/// Create a retained vector path element with intrinsic sizing and inherited text color.
2342pub fn path(source: impl Into<Path>) -> Element {
2343    Element::path(source.into())
2344}
2345
2346/// Create a web-like custom paint surface. The callback runs only when the view repaints.
2347///
2348/// Callback coordinates are local to the element and are clipped to its layout box.
2349pub fn canvas(painter: impl for<'a> Fn(Rect, &mut Canvas<'a>) + 'static) -> Element {
2350    Element::canvas(painter)
2351}
2352
2353/// Create a retained rectangle painted by validated application WGSL.
2354///
2355/// Like the web canvas default, its initial size is 300 by 150 logical pixels. The shader remains
2356/// still until application state invalidates the view or explicitly requests another frame.
2357pub fn custom_shader(shader: impl Into<CustomShader>) -> Element {
2358    Element::custom_shader(shader.into())
2359}
2360
2361/// Create a controlled, single-line text input.
2362///
2363/// Attach a stable [`crate::InputListener`] with [`Element::on_input`].
2364pub fn text_input(value: impl Into<Arc<str>>) -> Element {
2365    Element::text_input(value.into(), Arc::from([]), false)
2366}
2367
2368/// Create a controlled, multiline text area with web-style soft wrapping.
2369///
2370/// Attach a stable [`crate::InputListener`] with [`Element::on_input`]. Use [`Element::no_wrap`]
2371/// for code-editor-style horizontal scrolling.
2372pub fn text_area(value: impl Into<Arc<str>>) -> Element {
2373    Element::text_input(value.into(), Arc::from([]), true)
2374}
2375
2376/// Create a controlled, single-line input with bounded byte-range text styles.
2377///
2378/// Attach a stable [`crate::InputListener`] with [`Element::on_input`] and rebuild the
2379/// [`StyledText`] from the controlled value when it changes. Editing, selection, IME, hit testing,
2380/// and painting all reuse the same retained shaped buffer.
2381pub fn styled_text_input(value: StyledText) -> Element {
2382    let (value, highlights) = value.into_parts();
2383    Element::text_input(value, highlights, false)
2384}
2385
2386/// Create a controlled, multiline text area with bounded byte-range text styles.
2387///
2388/// This is the attributed-text counterpart to [`text_area`]. It preserves wrapping and both-axis
2389/// scrolling while using the supplied styles for shaping, caret geometry, selection, and paint.
2390pub fn styled_text_area(value: StyledText) -> Element {
2391    let (value, highlights) = value.into_parts();
2392    Element::text_input(value, highlights, true)
2393}
2394
2395/// Embed an AppKit view as a declarative leaf on macOS.
2396///
2397/// QuickGUI synchronizes layout, clipping, visibility, and sibling order while AppKit keeps
2398/// ownership of the view's rendering and input behavior.
2399#[cfg(target_os = "macos")]
2400pub fn native_view(view: &NSView) -> Element {
2401    Element::native_view(MacNativeView::new(view))
2402}
2403
2404/// Embed an AppKit view whose frame extends `outset` points past its layout box on every side.
2405///
2406/// Layout, hit regions, and siblings see the element's own box; only the native frame and its clip
2407/// grow, so a control can draw an effect that spills past its bounds, such as Liquid Glass, without
2408/// that headroom pushing its neighbours apart. See [`MacNativeView::with_outset`].
2409#[cfg(target_os = "macos")]
2410pub fn native_view_with_outset(view: &NSView, outset: f32) -> Element {
2411    Element::native_view(MacNativeView::new(view).with_outset(outset))
2412}
2413
2414mod construction_layout;
2415pub use construction_layout::{Direction, SnapAlign, SnapStrictness, StickyInsets};
2416pub(crate) use construction_layout::{LogicalInsets, ScrollSnapStyle};
2417mod interaction;
2418mod state;
2419mod style;
2420
2421fn stable_hash(bytes: &[u8]) -> u64 {
2422    let mut hash = 0xcbf2_9ce4_8422_2325_u64;
2423    for byte in bytes {
2424        hash ^= u64::from(*byte);
2425        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
2426    }
2427    hash
2428}
2429
2430fn bounded_validation_message(message: Arc<str>) -> (Option<Arc<str>>, bool) {
2431    if message.is_empty() {
2432        return (None, false);
2433    }
2434    if message.len() <= MAX_VALIDATION_MESSAGE_BYTES {
2435        return (Some(message), false);
2436    }
2437    let mut end = MAX_VALIDATION_MESSAGE_BYTES;
2438    while !message.is_char_boundary(end) {
2439        end -= 1;
2440    }
2441    (Some(Arc::from(&message[..end])), true)
2442}
2443
2444#[cfg(test)]
2445mod tests;