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
43use crate::{
45 Hyphens, OverflowWrap, TextDirection, TextShadow, TextTransform, WordBreak,
46 scene::sane_text_spacing,
47};
48
49use 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
80pub const MAX_BOX_SHADOWS_PER_ELEMENT: usize = 8;
82
83pub const MAX_HOVER_GROUP_NAME_BYTES: usize = 256;
85pub const MAX_GROUP_STYLES_PER_ELEMENT: usize = 8;
87
88pub const MAX_OUTLINE_WIDTH: f32 = 1_024.0;
90pub const MAX_BACKGROUND_IMAGE_TILES: usize = 256;
95pub const MAX_OUTLINE_OFFSET: f32 = 1_024.0;
97pub const MAX_CORNER_RADIUS: f32 = 4_096.0;
102
103pub const MAX_GRID_TRACKS: u16 = 1_024;
109
110pub const MAX_CONTAINER_QUERIES_PER_WINDOW: usize = 1_024;
112
113pub const MAX_CONTAINER_QUERY_DEPTH: usize = 16;
115
116pub const MAX_MOUSE_LISTENERS_PER_ELEMENT: usize = 16;
120
121pub 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#[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#[derive(Clone, Copy, Debug, PartialEq)]
203pub struct GridTrack(TrackSizingFunction);
204
205impl GridTrack {
206 pub fn auto() -> Self {
208 Self(auto())
209 }
210
211 pub fn min_content() -> Self {
213 Self(min_content())
214 }
215
216 pub fn max_content() -> Self {
218 Self(max_content())
219 }
220
221 pub fn px(value: f32) -> Self {
223 Self(length(finite_nonnegative(value)))
224 }
225
226 pub fn percent(fraction: f32) -> Self {
228 Self(percent(finite_nonnegative(fraction).min(1.0)))
229 }
230
231 pub fn fr(fraction: f32) -> Self {
233 Self(flex(finite_nonnegative(fraction)))
234 }
235
236 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 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#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
309pub struct ElementId(pub(crate) u64);
310
311#[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#[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#[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#[derive(Clone, Copy, Debug, PartialEq)]
430pub struct ResolvedAnchorPlacement {
431 pub placement: AnchorPlacement,
433 pub anchor: crate::Rect,
435 pub bounds: crate::Rect,
437 pub available: crate::Size,
443 pub anchor_hidden: bool,
448}
449
450impl ResolvedAnchorPlacement {
451 pub const fn side(self) -> AnchorSide {
453 AnchorSide::of(self.placement)
454 }
455
456 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#[derive(Clone, Default)]
499pub struct AnchorPlacementHandle(Rc<RefCell<AnchorPlacementInner>>);
500
501impl AnchorPlacementHandle {
502 pub fn new() -> Self {
503 Self::default()
504 }
505
506 pub fn resolved(&self) -> Option<ResolvedAnchorPlacement> {
508 self.0.borrow().resolved
509 }
510
511 pub fn placement_or(&self, preferred: AnchorPlacement) -> AnchorPlacement {
513 self.resolved()
514 .map_or(preferred, |resolved| resolved.placement)
515 }
516
517 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#[derive(Clone, Default)]
579pub struct LayoutBoundsHandle(Rc<RefCell<LayoutBoundsInner>>);
580
581impl LayoutBoundsHandle {
582 pub fn new() -> Self {
583 Self::default()
584 }
585
586 pub fn bounds(&self) -> Option<Rect> {
589 self.0.borrow().bounds
590 }
591
592 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#[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 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 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 pub const fn is_vertical(self) -> bool {
668 matches!(self, Self::Top | Self::Bottom)
669 }
670}
671
672#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
674pub enum AnchorAlign {
675 #[default]
676 Start,
677 Center,
678 End,
679}
680
681impl AnchorAlign {
682 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
701pub 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#[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 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 Slider,
770 SpinButton,
772 ProgressIndicator,
774 Meter,
776 SplitterHandle,
781 Toolbar,
783 ToggleButton,
785 MenuBar,
787 Alert,
789 Status,
791 Navigation,
793 ScrollView,
795 ScrollBar,
797}
798
799#[derive(Clone, Copy, Debug, Eq, PartialEq)]
801pub enum AccessibilityOrientation {
802 Horizontal,
803 Vertical,
804}
805
806#[derive(Clone, Copy, Debug, Eq, PartialEq)]
811pub enum AccessibilityLive {
812 Polite,
814 Assertive,
816}
817
818#[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 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 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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
870pub enum AccessibilityPopover {
871 Menu,
872 ListBox,
873 Tree,
874 Grid,
875 Dialog,
876}
877
878#[derive(Clone, Copy, Debug, Eq, PartialEq)]
880pub enum AccessibilitySortDirection {
881 Ascending,
882 Descending,
883 Other,
884}
885
886#[derive(Clone, Copy, Debug, Eq, PartialEq)]
888pub enum AccessibilityAutoComplete {
889 Inline,
890 List,
891 Both,
892}
893
894#[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#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
928pub enum UserSelect {
929 #[default]
930 Auto,
931 Text,
932 None,
933}
934
935#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
940pub enum Visibility {
941 #[default]
942 Visible,
943 Hidden,
944}
945
946pub 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 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 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#[derive(Clone, Copy, Debug, Default, PartialEq)]
1139pub enum BackgroundSize {
1140 #[default]
1142 Auto,
1143 Cover,
1145 Contain,
1147 Fixed(f32, f32),
1149}
1150
1151#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
1153pub enum BackgroundRepeat {
1154 #[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#[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#[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 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#[derive(Clone, Copy, Debug, PartialEq)]
1278pub struct Outline {
1279 pub width: f32,
1280 pub color: Color,
1281 pub offset: f32,
1283 pub style: BorderStyle,
1284}
1285
1286impl Outline {
1287 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 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 pub background_gradient: Option<Gradient>,
1333 pub background_image: Option<Box<BackgroundImage>>,
1335 pub filters: Filters,
1337 pub border_color: Option<Color>,
1338 pub border_widths: Insets,
1339 pub border_style: BorderStyle,
1340 pub radius: f32,
1341 pub corner_radii: Option<Corners>,
1343 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 pub transform: Transform2D,
1353 pub transform_origin: Point,
1355 pub backdrop: Filters,
1357 pub blend: BlendMode,
1359}
1360
1361impl VisualStyle {
1362 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#[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 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 pub fn transform(mut self, transform: Transform2D) -> Self {
1458 self.transform = Some(transform);
1459 self
1460 }
1461
1462 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 pub fn translate(self, x: f32, y: f32) -> Self {
1470 self.transform(Transform2D::translate(x, y))
1471 }
1472
1473 pub fn rotate_degrees(self, degrees: f32) -> Self {
1475 self.transform(Transform2D::rotate_degrees(degrees))
1476 }
1477
1478 pub fn scale(self, x: f32, y: f32) -> Self {
1480 self.transform(Transform2D::scale(x, y))
1481 }
1482
1483 pub fn scale_uniform(self, scale: f32) -> Self {
1485 self.transform(Transform2D::scale_uniform(scale))
1486 }
1487
1488 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 pub fn outline(mut self, width: f32, color: Color) -> Self {
1507 self.outline = Some(Outline::new(width, color));
1508 self
1509 }
1510
1511 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 pub fn outline_none(mut self) -> Self {
1519 self.outline = Some(Outline::new(0.0, Color::TRANSPARENT));
1520 self
1521 }
1522
1523 pub fn outline_dashed(self) -> Self {
1525 self.outline_style(BorderStyle::Dashed)
1526 }
1527
1528 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 pub fn border_width(mut self, width: f32) -> Self {
1548 self.border_width = Some(finite_nonnegative(width));
1549 self
1550 }
1551
1552 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 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 pub fn opacity(mut self, opacity: f32) -> Self {
1572 self.opacity = Some(finite_opacity(opacity));
1573 self
1574 }
1575
1576 pub fn shadow(mut self, shadow: BoxShadow) -> Self {
1578 self.shadows = Some(Arc::from([shadow]));
1579 self
1580 }
1581
1582 pub fn shadows(mut self, shadows: impl IntoIterator<Item = BoxShadow>) -> Self {
1584 self.shadows = Some(collect_box_shadows(shadows));
1585 self
1586 }
1587
1588 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 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1669pub(crate) enum GroupState {
1670 Hover,
1672 Active,
1674}
1675
1676#[derive(Clone, Debug, PartialEq)]
1678pub(crate) struct GroupStateStyle {
1679 pub(crate) state: GroupState,
1680 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#[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#[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#[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#[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 pub(crate) selected_style: ElementStateStyle,
2069 pub(crate) dragging: ElementStateStyle,
2070 pub(crate) drag_over: ElementStateStyle,
2071 pub(crate) focus_within: ElementStateStyle,
2073 pub(crate) group_styles: Vec<GroupStateStyle>,
2075 pub(crate) group: bool,
2077 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 #[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 pub(crate) vertical_scrollbar_hidden: bool,
2128 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 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 pub(crate) direction: Option<Direction>,
2145 pub(crate) resolved_direction: Direction,
2147 pub(crate) logical_insets: Option<Box<LogicalInsets>>,
2149 pub(crate) sticky: Option<StickyInsets>,
2151 pub(crate) scroll_snap: Option<ScrollSnapStyle>,
2153 pub(crate) snap_align: Option<SnapAlign>,
2155 pub(crate) snap_stop_always: bool,
2157}
2158
2159#[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 Transform {
2185 id: ElementId,
2186 transform: Transform2D,
2187 },
2188 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 pub(crate) const fn is_keyboard_focusable(&self) -> bool {
2243 self.focusable && (!self.accessibility.disabled || self.focusable_when_disabled)
2244 }
2245}
2246
2247pub fn div() -> Element {
2249 Element::container()
2250}
2251
2252pub 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
2294pub fn form() -> Element {
2299 let mut element = div().accessibility_role(AccessibilityRole::Form);
2300 element.form = true;
2301 element
2302}
2303
2304pub fn overlay() -> Element {
2309 div().overlay()
2310}
2311
2312pub 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
2321pub fn submit_button() -> Element {
2323 button().form_submitter()
2324}
2325
2326pub fn text(content: impl Into<Arc<str>>) -> Element {
2328 Element::text(content.into())
2329}
2330
2331pub fn img(source: impl Into<ImageSource>) -> Element {
2333 Element::image(source.into())
2334}
2335
2336pub fn svg(source: impl Into<Svg>) -> Element {
2338 Element::svg(source.into())
2339}
2340
2341pub fn path(source: impl Into<Path>) -> Element {
2343 Element::path(source.into())
2344}
2345
2346pub fn canvas(painter: impl for<'a> Fn(Rect, &mut Canvas<'a>) + 'static) -> Element {
2350 Element::canvas(painter)
2351}
2352
2353pub fn custom_shader(shader: impl Into<CustomShader>) -> Element {
2358 Element::custom_shader(shader.into())
2359}
2360
2361pub fn text_input(value: impl Into<Arc<str>>) -> Element {
2365 Element::text_input(value.into(), Arc::from([]), false)
2366}
2367
2368pub fn text_area(value: impl Into<Arc<str>>) -> Element {
2373 Element::text_input(value.into(), Arc::from([]), true)
2374}
2375
2376pub fn styled_text_input(value: StyledText) -> Element {
2382 let (value, highlights) = value.into_parts();
2383 Element::text_input(value, highlights, false)
2384}
2385
2386pub fn styled_text_area(value: StyledText) -> Element {
2391 let (value, highlights) = value.into_parts();
2392 Element::text_input(value, highlights, true)
2393}
2394
2395#[cfg(target_os = "macos")]
2400pub fn native_view(view: &NSView) -> Element {
2401 Element::native_view(MacNativeView::new(view))
2402}
2403
2404#[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;