use std::{
any::{Any, TypeId},
borrow::Cow,
fmt,
rc::Rc,
sync::Arc,
};
use glyphon::{Style as GlyphStyle, Weight};
use taffy::{
Style,
geometry::{Line as TaffyLine, Point as TaffyPoint, Rect as TaffyRect, Size as TaffySize},
prelude::{
AlignContent, AlignItems, AlignSelf, Dimension, Display, FlexDirection, FlexWrap,
GridAutoFlow, GridPlacement, GridTemplateComponent, JustifyContent, LengthPercentage,
LengthPercentageAuto, Position, TrackSizingFunction,
},
style::Overflow,
style_helpers::{
auto, fit_content, flex, fr, length, line, max_content, min_content, minmax, percent,
repeat,
},
};
use crate::{
AnimatedImage, Background, BoxShadow, Canvas, Color, CursorStyle, CustomShader, DispatchPhase,
Font, FontFallbacks, FontFamily, FontFeatures, Image, ImageSource, Insets, KeyContext,
MAX_VALIDATION_MESSAGE_BYTES, ObjectFit, Path, Rect, ScenePlane, ShaderParameters, StyledText,
Svg, SvgTransform, TextAlign, TextHighlight, TextOverflow, TextShaping, TextStyle,
TextUnderline, TextWrap, Tooltip, Transition, WhiteSpace,
action::{ActionListenerBinding, MAX_ACTION_LISTENERS_PER_ELEMENT},
animation::ElementAnimation,
font::{assert_valid_font_family, normalize_fallbacks},
spring::ElementSpring,
virtual_list::{
ListItemMeasurement, ListState, VirtualList, VirtualScrollHandle, VirtualScrollMount,
},
};
#[cfg(target_os = "macos")]
use crate::native_view::MacNativeView;
#[cfg(target_os = "macos")]
use objc2_app_kit::NSView;
const SPACING_UNIT: f32 = 4.0;
const DEFAULT_ANCHOR_GAP: f32 = 8.0;
const DEFAULT_VIEWPORT_MARGIN: f32 = 8.0;
macro_rules! state_cursor_helper {
($method:ident, $variant:ident, $css:literal) => {
#[doc = concat!("Use the native `", $css, "` cursor while this state is active.")]
pub fn $method(self) -> Self {
self.cursor(CursorStyle::$variant)
}
};
}
macro_rules! spacing_scale_methods {
($setter:ident; $($method:ident => $units:expr),+ $(,)?) => {
$(
pub fn $method(self) -> Self {
self.$setter(SPACING_UNIT * $units)
}
)+
};
}
pub const MAX_BOX_SHADOWS_PER_ELEMENT: usize = 8;
pub const MAX_GRID_TRACKS: u16 = 1_024;
pub const MAX_CONTAINER_QUERIES_PER_WINDOW: usize = 1_024;
pub const MAX_CONTAINER_QUERY_DEPTH: usize = 16;
pub const MAX_MOUSE_LISTENERS_PER_ELEMENT: usize = 16;
pub const MAX_KEY_LISTENERS_PER_ELEMENT: usize = 16;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct MouseListenerKey(pub(crate) u32);
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum MouseListenerKind {
Down,
Up,
Move,
Exit,
Hover,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct MouseListenerBinding {
pub(crate) key: MouseListenerKey,
pub(crate) kind: MouseListenerKind,
pub(crate) phase: DispatchPhase,
pub(crate) button: Option<crate::MouseButton>,
pub(crate) outside: bool,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct KeyListenerKey(pub(crate) u32);
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum KeyListenerKind {
Down,
Up,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct KeyListenerBinding {
pub(crate) key: KeyListenerKey,
pub(crate) kind: KeyListenerKind,
pub(crate) phase: DispatchPhase,
}
const DISMISS_ON_ESCAPE: u8 = 1 << 0;
const DISMISS_ON_POINTER_OUTSIDE: u8 = 1 << 1;
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub(crate) struct DismissPolicy(u8);
impl DismissPolicy {
pub(crate) const BOTH: Self = Self(DISMISS_ON_ESCAPE | DISMISS_ON_POINTER_OUTSIDE);
pub(crate) const fn on_escape(self) -> bool {
self.0 & DISMISS_ON_ESCAPE != 0
}
pub(crate) const fn on_pointer_outside(self) -> bool {
self.0 & DISMISS_ON_POINTER_OUTSIDE != 0
}
pub(crate) const fn with_escape(self) -> Self {
Self(self.0 | DISMISS_ON_ESCAPE)
}
pub(crate) const fn with_pointer_outside(self) -> Self {
Self(self.0 | DISMISS_ON_POINTER_OUTSIDE)
}
pub(crate) const fn is_empty(self) -> bool {
self.0 == 0
}
}
const MAX_GRID_LINE: i16 = MAX_GRID_TRACKS as i16 + 1;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GridTrack(TrackSizingFunction);
impl GridTrack {
pub fn auto() -> Self {
Self(auto())
}
pub fn min_content() -> Self {
Self(min_content())
}
pub fn max_content() -> Self {
Self(max_content())
}
pub fn px(value: f32) -> Self {
Self(length(finite_nonnegative(value)))
}
pub fn percent(fraction: f32) -> Self {
Self(percent(finite_nonnegative(fraction).min(1.0)))
}
pub fn fr(fraction: f32) -> Self {
Self(flex(finite_nonnegative(fraction)))
}
pub fn minmax_px_fr(minimum: f32, fraction: f32) -> Self {
Self(minmax(
length(finite_nonnegative(minimum)),
fr(finite_nonnegative(fraction)),
))
}
pub fn fit_content_px(limit: f32) -> Self {
Self(fit_content(LengthPercentage::length(finite_nonnegative(
limit,
))))
}
}
#[derive(Clone, Copy, Debug)]
enum EqualGridTrackSizing {
Zero,
MinContent,
MaxContent,
}
fn finite_nonnegative(value: f32) -> f32 {
if value.is_finite() {
value.max(0.0)
} else {
0.0
}
}
fn finite_opacity(value: f32) -> f32 {
if value.is_finite() {
value.clamp(0.0, 1.0)
} else {
1.0
}
}
fn finite_length(value: f32) -> f32 {
if value.is_finite() { value } else { 0.0 }
}
fn equal_grid_tracks(
count: u16,
sizing: EqualGridTrackSizing,
) -> Vec<GridTemplateComponent<String>> {
let count = count.min(MAX_GRID_TRACKS);
if count == 0 {
return Vec::new();
}
let track: TrackSizingFunction = match sizing {
EqualGridTrackSizing::Zero => minmax(length(0.0_f32), fr(1.0_f32)),
EqualGridTrackSizing::MinContent => minmax(min_content(), fr(1.0_f32)),
EqualGridTrackSizing::MaxContent => minmax(length(0.0_f32), max_content()),
};
vec![repeat(count, vec![track])]
}
fn bounded_grid_line(index: i16) -> GridPlacement<String> {
if index == 0 {
GridPlacement::Auto
} else {
line(index.clamp(-MAX_GRID_LINE, MAX_GRID_LINE))
}
}
fn bounded_grid_span(span: u16) -> GridPlacement<String> {
GridPlacement::Span(span.clamp(1, MAX_GRID_TRACKS))
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct ElementId(pub(crate) u64);
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum AppRegion {
Drag,
NoDrag,
}
impl ElementId {
pub const fn new(value: u64) -> Self {
Self(value)
}
pub fn named(value: &str) -> Self {
Self(stable_hash(value.as_bytes()))
}
pub const fn as_u64(self) -> u64 {
self.0
}
pub(crate) const fn value(self) -> u64 {
self.as_u64()
}
}
impl From<u64> for ElementId {
fn from(value: u64) -> Self {
Self::new(value)
}
}
impl From<usize> for ElementId {
fn from(value: usize) -> Self {
Self::new(value as u64)
}
}
impl From<&str> for ElementId {
fn from(value: &str) -> Self {
Self::named(value)
}
}
impl From<String> for ElementId {
fn from(value: String) -> Self {
Self::named(&value)
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct FocusHandle(ElementId);
impl FocusHandle {
pub fn new(id: impl Into<ElementId>) -> Self {
Self(id.into())
}
pub const fn id(self) -> ElementId {
self.0
}
}
impl From<FocusHandle> for ElementId {
fn from(value: FocusHandle) -> Self {
value.id()
}
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum AnchorPlacement {
TopStart,
Top,
TopEnd,
#[default]
BottomStart,
Bottom,
BottomEnd,
LeftStart,
Left,
LeftEnd,
RightStart,
Right,
RightEnd,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum AnchorTarget {
Element(ElementId),
Point(crate::Point),
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct AnchorStyle {
pub target: AnchorTarget,
pub placement: AnchorPlacement,
pub gap: f32,
pub viewport_margin: f32,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum AccessibilityRole {
#[default]
GenericContainer,
Label,
Button,
Link,
Image,
List,
ListItem,
Heading,
CheckBox,
RadioButton,
RadioGroup,
Switch,
TextInput,
PasswordInput,
MultilineTextInput,
Dialog,
AlertDialog,
Menu,
MenuItem,
MenuItemCheckBox,
MenuItemRadio,
Separator,
Group,
Region,
ListBox,
ListBoxOption,
ComboBox,
EditableComboBox,
Table,
Tree,
Grid,
Row,
ColumnHeader,
RowHeader,
GridCell,
TreeItem,
Tab,
TabList,
TabPanel,
Tooltip,
Form,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum AccessibilityOrientation {
Horizontal,
Vertical,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AccessibilityPopover {
Menu,
ListBox,
Tree,
Grid,
Dialog,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AccessibilitySortDirection {
Ascending,
Descending,
Other,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AccessibilityAutoComplete {
Inline,
List,
Both,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum ToggleState {
#[default]
Off,
On,
Mixed,
}
impl ToggleState {
pub const fn is_on(self) -> bool {
matches!(self, Self::On)
}
pub const fn is_mixed(self) -> bool {
matches!(self, Self::Mixed)
}
}
impl From<bool> for ToggleState {
fn from(checked: bool) -> Self {
if checked { Self::On } else { Self::Off }
}
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum UserSelect {
#[default]
Auto,
Text,
None,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum Visibility {
#[default]
Visible,
Hidden,
}
pub trait IntoElement {
fn into_element(self) -> Element;
}
impl IntoElement for Element {
fn into_element(self) -> Element {
self
}
}
impl IntoElement for String {
fn into_element(self) -> Element {
text(self)
}
}
impl IntoElement for Arc<str> {
fn into_element(self) -> Element {
text(self)
}
}
impl IntoElement for &str {
fn into_element(self) -> Element {
text(Arc::<str>::from(self))
}
}
impl IntoElement for Cow<'_, str> {
fn into_element(self) -> Element {
text(Arc::<str>::from(self.as_ref()))
}
}
impl IntoElement for StyledText {
fn into_element(self) -> Element {
Element::styled_text(self)
}
}
#[derive(Clone, Debug)]
pub(crate) enum ElementKind {
Container,
ContainerQuery(ContainerQueryElement),
Text(Arc<str>),
StyledText(StyledText),
Image(ImageElement),
Svg(SvgElement),
Path(PathElement),
Canvas(CanvasElement),
CustomShader(ShaderElement),
TextInput(TextInputElement),
#[cfg(target_os = "macos")]
NativeView(MacNativeView),
}
#[derive(Clone)]
pub(crate) struct ContainerQueryElement {
render: Rc<dyn Fn(crate::Size) -> Element>,
pub(crate) resolved_size: Option<crate::Size>,
pub(crate) resolved_motion_ids: Vec<ElementId>,
pub(crate) layout_pending: bool,
}
impl ContainerQueryElement {
pub(crate) fn render(&self, size: crate::Size) -> Element {
(self.render)(size)
}
}
impl fmt::Debug for ContainerQueryElement {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ContainerQueryElement")
.field("resolved_size", &self.resolved_size)
.field("resolved_motion_count", &self.resolved_motion_ids.len())
.field("layout_pending", &self.layout_pending)
.finish_non_exhaustive()
}
}
#[derive(Clone, Debug)]
pub(crate) struct ImageElement {
pub source: ImageSource,
pub object_fit: ObjectFit,
pub grayscale: bool,
pub resolved: ImageResolution,
pub loading: Option<ImageReplacement>,
pub fallback: Option<ImageReplacement>,
}
#[derive(Clone, Debug)]
pub(crate) struct SvgElement {
pub svg: Svg,
pub object_fit: ObjectFit,
pub transform: SvgTransform,
}
#[derive(Clone, Debug)]
pub(crate) struct PathElement {
pub path: Path,
pub object_fit: ObjectFit,
pub background: Option<Background>,
}
#[derive(Clone)]
pub(crate) struct CanvasElement {
pub painter: Rc<CanvasPainter>,
}
#[derive(Clone, Debug)]
pub(crate) struct ShaderElement {
pub shader: CustomShader,
pub parameters: ShaderParameters,
}
type CanvasPainter = dyn for<'a> Fn(Rect, &mut Canvas<'a>);
impl fmt::Debug for CanvasElement {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("CanvasElement(..)")
}
}
#[derive(Clone, Debug)]
pub(crate) enum ImageResolution {
Ready(Image),
Animated(AnimatedImage),
Loading,
Failed,
}
#[derive(Clone)]
pub(crate) struct ImageReplacement(Rc<dyn Fn() -> Element>);
impl ImageReplacement {
fn new<E: IntoElement + 'static>(render: impl Fn() -> E + 'static) -> Self {
Self(Rc::new(move || render().into_element()))
}
pub(crate) fn render(&self) -> Element {
(self.0)()
}
}
impl fmt::Debug for ImageReplacement {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("ImageReplacement(..)")
}
}
#[derive(Clone, Debug)]
pub(crate) struct TextInputElement {
pub value: Arc<str>,
pub highlights: Arc<[TextHighlight]>,
pub placeholder: Arc<str>,
pub multiline: bool,
pub password: bool,
pub constraints: InputConstraints,
}
pub(crate) type InputFilterCallback = Arc<dyn Fn(&str) -> bool>;
#[derive(Clone, Default)]
pub(crate) struct InputConstraints {
pub max_length: Option<usize>,
pub filter: Option<InputFilterCallback>,
}
impl fmt::Debug for InputConstraints {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("InputConstraints")
.field("max_length", &self.max_length)
.field("filter", &self.filter.as_ref().map(|_| "InputFilter(..)"))
.finish()
}
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct VisualStyle {
pub background: Option<Color>,
pub border_color: Option<Color>,
pub border_width: f32,
pub radius: f32,
pub shadows: Option<Arc<[BoxShadow]>>,
pub opacity: f32,
}
impl Default for VisualStyle {
fn default() -> Self {
Self {
background: None,
border_color: None,
border_width: 0.0,
radius: 0.0,
shadows: None,
opacity: 1.0,
}
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ElementStateStyle {
pub(crate) background: Option<Color>,
pub(crate) border_color: Option<Color>,
pub(crate) border_width: Option<f32>,
pub(crate) radius: Option<f32>,
pub(crate) text_color: Option<Color>,
pub(crate) shadows: Option<Arc<[BoxShadow]>>,
pub(crate) opacity: Option<f32>,
pub(crate) cursor_style: Option<CursorStyle>,
}
impl ElementStateStyle {
pub fn cursor(mut self, cursor: CursorStyle) -> Self {
self.cursor_style = Some(cursor);
self
}
state_cursor_helper!(cursor_default, Arrow, "default");
state_cursor_helper!(cursor_pointer, PointingHand, "pointer");
state_cursor_helper!(cursor_text, IBeam, "text");
state_cursor_helper!(cursor_move, ClosedHand, "move");
state_cursor_helper!(cursor_not_allowed, OperationNotAllowed, "not-allowed");
state_cursor_helper!(cursor_context_menu, ContextualMenu, "context-menu");
state_cursor_helper!(cursor_crosshair, Crosshair, "crosshair");
state_cursor_helper!(
cursor_vertical_text,
IBeamCursorForVerticalLayout,
"vertical-text"
);
state_cursor_helper!(cursor_alias, DragLink, "alias");
state_cursor_helper!(cursor_copy, DragCopy, "copy");
state_cursor_helper!(cursor_no_drop, OperationNotAllowed, "no-drop");
state_cursor_helper!(cursor_grab, OpenHand, "grab");
state_cursor_helper!(cursor_grabbing, ClosedHand, "grabbing");
state_cursor_helper!(cursor_ew_resize, ResizeLeftRight, "ew-resize");
state_cursor_helper!(cursor_ns_resize, ResizeUpDown, "ns-resize");
state_cursor_helper!(cursor_nesw_resize, ResizeUpRightDownLeft, "nesw-resize");
state_cursor_helper!(cursor_nwse_resize, ResizeUpLeftDownRight, "nwse-resize");
state_cursor_helper!(cursor_col_resize, ResizeColumn, "col-resize");
state_cursor_helper!(cursor_row_resize, ResizeRow, "row-resize");
state_cursor_helper!(cursor_n_resize, ResizeUp, "n-resize");
state_cursor_helper!(cursor_e_resize, ResizeRight, "e-resize");
state_cursor_helper!(cursor_s_resize, ResizeDown, "s-resize");
state_cursor_helper!(cursor_w_resize, ResizeLeft, "w-resize");
pub fn bg(mut self, color: Color) -> Self {
self.background = Some(color);
self
}
pub fn border_color(mut self, color: Color) -> Self {
self.border_color = Some(color);
self
}
pub fn border(mut self, width: f32, color: Color) -> Self {
self.border_width = Some(width.max(0.0));
self.border_color = Some(color);
self
}
pub fn rounded(mut self, radius: f32) -> Self {
self.radius = Some(finite_nonnegative(radius));
self
}
pub fn text_color(mut self, color: Color) -> Self {
self.text_color = Some(color);
self
}
pub fn opacity(mut self, opacity: f32) -> Self {
self.opacity = Some(finite_opacity(opacity));
self
}
pub fn shadow(mut self, shadow: BoxShadow) -> Self {
self.shadows = Some(Arc::from([shadow]));
self
}
pub fn shadows(mut self, shadows: impl IntoIterator<Item = BoxShadow>) -> Self {
self.shadows = Some(collect_box_shadows(shadows));
self
}
pub fn shadow_none(mut self) -> Self {
self.shadows = Some(Arc::from([]));
self
}
pub fn shadow_sm(self) -> Self {
self.shadow(shadow_sm_preset())
}
pub fn shadow_md(self) -> Self {
self.shadows(shadow_md_preset())
}
pub fn shadow_lg(self) -> Self {
self.shadows(shadow_lg_preset())
}
pub fn shadow_xl(self) -> Self {
self.shadows(shadow_xl_preset())
}
pub fn shadow_2xl(self) -> Self {
self.shadow(shadow_2xl_preset())
}
fn has_paint_overrides(&self) -> bool {
self.background.is_some()
|| self.border_color.is_some()
|| self.border_width.is_some()
|| self.radius.is_some()
|| self.text_color.is_some()
|| self.shadows.is_some()
|| self.opacity.is_some()
}
}
fn shadow_sm_preset() -> BoxShadow {
BoxShadow::new(0.0, 1.0, Color::rgba8(0, 0, 0, 13)).blur_radius(2.0)
}
fn shadow_md_preset() -> [BoxShadow; 2] {
[
BoxShadow::new(0.0, 4.0, Color::rgba8(0, 0, 0, 26))
.blur_radius(6.0)
.spread_radius(-1.0),
BoxShadow::new(0.0, 2.0, Color::rgba8(0, 0, 0, 26))
.blur_radius(4.0)
.spread_radius(-2.0),
]
}
fn shadow_lg_preset() -> [BoxShadow; 2] {
[
BoxShadow::new(0.0, 10.0, Color::rgba8(0, 0, 0, 26))
.blur_radius(15.0)
.spread_radius(-3.0),
BoxShadow::new(0.0, 4.0, Color::rgba8(0, 0, 0, 26))
.blur_radius(6.0)
.spread_radius(-4.0),
]
}
fn shadow_xl_preset() -> [BoxShadow; 2] {
[
BoxShadow::new(0.0, 20.0, Color::rgba8(0, 0, 0, 26))
.blur_radius(25.0)
.spread_radius(-5.0),
BoxShadow::new(0.0, 8.0, Color::rgba8(0, 0, 0, 26))
.blur_radius(10.0)
.spread_radius(-6.0),
]
}
fn shadow_2xl_preset() -> BoxShadow {
BoxShadow::new(0.0, 25.0, Color::rgba8(0, 0, 0, 64))
.blur_radius(50.0)
.spread_radius(-12.0)
}
fn collect_box_shadows(shadows: impl IntoIterator<Item = BoxShadow>) -> Arc<[BoxShadow]> {
let mut retained = Vec::with_capacity(2);
for shadow in shadows {
assert!(
retained.len() < MAX_BOX_SHADOWS_PER_ELEMENT,
"one element retains at most {MAX_BOX_SHADOWS_PER_ELEMENT} box shadows"
);
retained.push(shadow);
}
Arc::from(retained)
}
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct AccessibilityStyle {
pub hidden: bool,
pub role: AccessibilityRole,
pub label: Option<Arc<str>>,
pub value: Option<Arc<str>>,
pub disabled: bool,
pub selected: bool,
pub toggled: Option<ToggleState>,
pub expanded: Option<bool>,
pub relations: AccessibilityRelationsStyle,
pub has_popover: Option<AccessibilityPopover>,
pub auto_complete: Option<AccessibilityAutoComplete>,
pub collection: AccessibilityCollectionStyle,
pub modal: bool,
pub required: bool,
pub invalid: bool,
pub validation_message: Option<Arc<str>>,
pub validation_message_truncated: bool,
pub description: Option<Arc<str>>,
pub orientation: Option<AccessibilityOrientation>,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct TabListBehavior {
pub(crate) vertical: bool,
pub(crate) activate_on_focus: bool,
pub(crate) loop_focus: bool,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct AccessibilityRelationsStyle(Option<Box<AccessibilityRelations>>);
#[derive(Clone, Copy, Debug, Default, PartialEq)]
struct AccessibilityRelations {
controls: Option<ElementId>,
active_descendant: Option<ElementId>,
labelled_by: Option<ElementId>,
described_by: Option<ElementId>,
described_by_secondary: Option<ElementId>,
}
impl AccessibilityRelationsStyle {
fn values_mut(&mut self) -> &mut AccessibilityRelations {
self.0
.get_or_insert_with(|| Box::new(AccessibilityRelations::default()))
}
pub(crate) fn controls(&self) -> Option<ElementId> {
self.0.as_deref().and_then(|values| values.controls)
}
pub(crate) fn set_controls(&mut self, value: ElementId) {
self.values_mut().controls = Some(value);
}
pub(crate) fn active_descendant(&self) -> Option<ElementId> {
self.0
.as_deref()
.and_then(|values| values.active_descendant)
}
pub(crate) fn set_active_descendant(&mut self, value: ElementId) {
self.values_mut().active_descendant = Some(value);
}
pub(crate) fn labelled_by(&self) -> Option<ElementId> {
self.0.as_deref().and_then(|values| values.labelled_by)
}
pub(crate) fn set_labelled_by(&mut self, value: ElementId) {
self.values_mut().labelled_by = Some(value);
}
pub(crate) fn described_by(&self) -> Option<ElementId> {
self.0.as_deref().and_then(|values| values.described_by)
}
pub(crate) fn set_described_by(&mut self, value: ElementId) {
let values = self.values_mut();
values.described_by = Some(value);
values.described_by_secondary = None;
}
pub(crate) fn described_by_secondary(&self) -> Option<ElementId> {
self.0
.as_deref()
.and_then(|values| values.described_by_secondary)
}
pub(crate) fn set_described_by_pair(&mut self, first: ElementId, second: ElementId) {
let values = self.values_mut();
values.described_by = Some(first);
values.described_by_secondary = (second != first).then_some(second);
}
}
const ACCESSIBILITY_COLLECTION_UNSET: u32 = u32::MAX;
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct AccessibilityCollectionStyle {
pub row_count: u32,
pub column_count: u32,
pub row_index: u32,
pub column_index: u32,
pub level: u32,
pub size_of_set: u32,
pub position_in_set: u32,
pub sort_direction: Option<AccessibilitySortDirection>,
}
impl Default for AccessibilityCollectionStyle {
fn default() -> Self {
Self {
row_count: ACCESSIBILITY_COLLECTION_UNSET,
column_count: ACCESSIBILITY_COLLECTION_UNSET,
row_index: ACCESSIBILITY_COLLECTION_UNSET,
column_index: ACCESSIBILITY_COLLECTION_UNSET,
level: ACCESSIBILITY_COLLECTION_UNSET,
size_of_set: ACCESSIBILITY_COLLECTION_UNSET,
position_in_set: ACCESSIBILITY_COLLECTION_UNSET,
sort_direction: None,
}
}
}
impl AccessibilityCollectionStyle {
pub(crate) fn row_count(self) -> Option<usize> {
accessibility_collection_value(self.row_count)
}
pub(crate) fn column_count(self) -> Option<usize> {
accessibility_collection_value(self.column_count)
}
pub(crate) fn row_index(self) -> Option<usize> {
accessibility_collection_value(self.row_index)
}
pub(crate) fn column_index(self) -> Option<usize> {
accessibility_collection_value(self.column_index)
}
pub(crate) fn level(self) -> Option<usize> {
accessibility_collection_value(self.level)
}
pub(crate) fn size_of_set(self) -> Option<usize> {
accessibility_collection_value(self.size_of_set)
}
pub(crate) fn position_in_set(self) -> Option<usize> {
accessibility_collection_value(self.position_in_set)
}
}
fn accessibility_collection_storage(value: usize) -> u32 {
assert!(
value < ACCESSIBILITY_COLLECTION_UNSET as usize,
"accessibility collection values must fit below u32::MAX"
);
value as u32
}
fn accessibility_collection_value(value: u32) -> Option<usize> {
(value != ACCESSIBILITY_COLLECTION_UNSET).then_some(value as usize)
}
#[derive(Clone, Debug)]
pub(crate) struct VirtualScrollStyle {
pub handle: VirtualScrollHandle,
pub max_offset_y: f32,
pub measurement_revision: u64,
pub mount: VirtualScrollMount,
}
pub(crate) type DropPredicateCallback = Arc<dyn Fn(&dyn Any) -> bool>;
#[derive(Clone)]
pub(crate) struct DropPredicate {
pub type_id: TypeId,
pub callback: DropPredicateCallback,
}
impl fmt::Debug for DropPredicate {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("DropPredicate")
.field("type_id", &self.type_id)
.finish_non_exhaustive()
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct TypographyStyle {
pub color: Option<Color>,
pub font_size: Option<f32>,
pub line_height: Option<f32>,
pub monospace_width: Option<f32>,
pub family: Option<FontFamily>,
pub features: Option<FontFeatures>,
pub fallbacks: Option<Option<FontFallbacks>>,
pub weight: Option<Weight>,
pub font_style: Option<GlyphStyle>,
pub font_thicken: Option<bool>,
pub underline: Option<TextUnderline>,
pub underline_color: Option<Option<Color>>,
pub underline_wavy: Option<bool>,
pub underline_thickness: Option<f32>,
pub strikethrough: Option<bool>,
pub strikethrough_color: Option<Option<Color>>,
pub align: Option<TextAlign>,
pub wrap: Option<TextWrap>,
pub text_overflow: Option<TextOverflow>,
pub line_clamp: Option<usize>,
pub shaping: Option<TextShaping>,
}
impl TypographyStyle {
pub(crate) fn resolve(&self, inherited: &TextStyle) -> TextStyle {
let font_size = self.font_size.unwrap_or(inherited.font_size);
TextStyle {
font_size,
line_height: self.line_height.unwrap_or_else(|| {
self.font_size
.map(|_| font_size * 1.35)
.unwrap_or(inherited.line_height)
}),
monospace_width: self.monospace_width.or(inherited.monospace_width),
family: self
.family
.clone()
.unwrap_or_else(|| inherited.family.clone()),
features: self
.features
.clone()
.unwrap_or_else(|| inherited.features.clone()),
fallbacks: normalize_fallbacks(
self.fallbacks
.clone()
.unwrap_or_else(|| inherited.fallbacks.clone()),
),
weight: self.weight.unwrap_or(inherited.weight),
font_style: self.font_style.unwrap_or(inherited.font_style),
font_thicken: self.font_thicken.unwrap_or(inherited.font_thicken),
underline: self.underline.unwrap_or(inherited.underline),
underline_color: self.underline_color.unwrap_or(inherited.underline_color),
underline_wavy: self.underline_wavy.unwrap_or(inherited.underline_wavy),
underline_thickness: self
.underline_thickness
.unwrap_or(inherited.underline_thickness),
strikethrough: self.strikethrough.unwrap_or(inherited.strikethrough),
strikethrough_color: self
.strikethrough_color
.unwrap_or(inherited.strikethrough_color),
align: self.align.unwrap_or(inherited.align),
wrap: self.wrap.unwrap_or(inherited.wrap),
text_overflow: self
.text_overflow
.clone()
.or_else(|| inherited.text_overflow.clone()),
line_clamp: self.line_clamp.or(inherited.line_clamp),
shaping: self.shaping.unwrap_or(inherited.shaping),
color: self.color.unwrap_or(inherited.color),
}
}
}
#[derive(Clone, Debug)]
pub struct Element {
pub(crate) explicit_id: Option<ElementId>,
pub(crate) runtime_id: ElementId,
pub(crate) kind: ElementKind,
pub(crate) layout: Style,
pub(crate) visibility: Visibility,
pub(crate) visual: VisualStyle,
pub(crate) typography: TypographyStyle,
pub(crate) resolved_typography: TextStyle,
pub(crate) hover: ElementStateStyle,
pub(crate) active: ElementStateStyle,
pub(crate) focus: ElementStateStyle,
pub(crate) disabled_style: ElementStateStyle,
pub(crate) invalid_style: ElementStateStyle,
pub(crate) dragging: ElementStateStyle,
pub(crate) drag_over: ElementStateStyle,
pub(crate) clickable: bool,
pub(crate) pointer_listener: bool,
pub(crate) scroll_wheel_listener: bool,
pub(crate) touch_listener: bool,
pub(crate) context_menu_listener: bool,
#[allow(clippy::box_collection)]
pub(crate) mouse_listeners: Option<Box<Vec<MouseListenerBinding>>>,
#[allow(clippy::box_collection)]
pub(crate) key_listeners: Option<Box<Vec<KeyListenerBinding>>>,
#[allow(clippy::box_collection)]
pub(crate) action_listeners: Option<Box<Vec<ActionListenerBinding>>>,
pub(crate) mouse_pressure_listener: bool,
pub(crate) pinch_listener: bool,
pub(crate) rotation_listener: bool,
pub(crate) smart_magnify_listener: bool,
pub(crate) drag_source: bool,
pub(crate) drop_target: bool,
pub(crate) drop_predicates: Vec<DropPredicate>,
pub(crate) cursor_style: Option<CursorStyle>,
pub(crate) cursor_style_explicit: bool,
pub(crate) user_select: UserSelect,
pub(crate) resolved_user_select: bool,
pub(crate) focusable: bool,
pub(crate) focus_on_pointer: bool,
pub(crate) hit_slop: Insets,
pub(crate) focus_trap: bool,
pub(crate) restore_previous_focus: bool,
pub(crate) key_context: Option<KeyContext>,
pub(crate) tab_index: i16,
pub(crate) auto_focus: bool,
pub(crate) form: bool,
pub(crate) form_submitter: bool,
pub(crate) activation_target: Option<ElementId>,
pub(crate) accessibility: AccessibilityStyle,
pub(crate) tab_list_behavior: Option<TabListBehavior>,
pub(crate) plane: Option<ScenePlane>,
pub(crate) z_index: Option<i16>,
pub(crate) portal: bool,
pub(crate) anchor: Option<AnchorStyle>,
pub(crate) tooltip: Option<Tooltip>,
pub(crate) app_region: Option<AppRegion>,
pub(crate) virtual_scroll: Option<VirtualScrollStyle>,
pub(crate) scroll_to_end_revision: Option<u64>,
pub(crate) list_item_measurement: Option<ListItemMeasurement>,
pub(crate) animation: Option<ElementAnimation>,
pub(crate) spring: Option<ElementSpring>,
pub(crate) transition: Option<Transition>,
pub(crate) blocks_pointer: bool,
pub(crate) dismiss_policy: DismissPolicy,
pub(crate) restore_focus: Option<FocusHandle>,
pub(crate) children: Vec<Element>,
pub(crate) taffy_node: Option<taffy::NodeId>,
}
pub fn div() -> Element {
Element::container()
}
pub fn container_query<E>(render: impl Fn(crate::Size) -> E + 'static) -> Element
where
E: IntoElement,
{
let mut element = Element::container();
element.kind = ElementKind::ContainerQuery(ContainerQueryElement {
render: Rc::new(move |size| render(size).into_element()),
resolved_size: None,
resolved_motion_ids: Vec::new(),
layout_pending: false,
});
element.layout.size = TaffySize {
width: Dimension::percent(1.0),
height: Dimension::percent(1.0),
};
element
}
pub fn form() -> Element {
let mut element = div().accessibility_role(AccessibilityRole::Form);
element.form = true;
element
}
pub fn overlay() -> Element {
div().overlay()
}
pub fn button() -> Element {
let mut element = div()
.accessibility_role(AccessibilityRole::Button)
.focusable();
element.set_implicit_cursor(CursorStyle::PointingHand);
element
}
pub fn submit_button() -> Element {
button().form_submitter()
}
pub fn text(content: impl Into<Arc<str>>) -> Element {
Element::text(content.into())
}
pub fn img(source: impl Into<ImageSource>) -> Element {
Element::image(source.into())
}
pub fn svg(source: impl Into<Svg>) -> Element {
Element::svg(source.into())
}
pub fn path(source: impl Into<Path>) -> Element {
Element::path(source.into())
}
pub fn canvas(painter: impl for<'a> Fn(Rect, &mut Canvas<'a>) + 'static) -> Element {
Element::canvas(painter)
}
pub fn custom_shader(shader: impl Into<CustomShader>) -> Element {
Element::custom_shader(shader.into())
}
pub fn text_input(value: impl Into<Arc<str>>) -> Element {
Element::text_input(value.into(), Arc::from([]), false)
}
pub fn text_area(value: impl Into<Arc<str>>) -> Element {
Element::text_input(value.into(), Arc::from([]), true)
}
pub fn styled_text_input(value: StyledText) -> Element {
let (value, highlights) = value.into_parts();
Element::text_input(value, highlights, false)
}
pub fn styled_text_area(value: StyledText) -> Element {
let (value, highlights) = value.into_parts();
Element::text_input(value, highlights, true)
}
#[cfg(target_os = "macos")]
pub fn native_view(view: &NSView) -> Element {
Element::native_view(MacNativeView::new(view))
}
mod construction_layout;
mod interaction;
mod state;
mod style;
fn stable_hash(bytes: &[u8]) -> u64 {
let mut hash = 0xcbf2_9ce4_8422_2325_u64;
for byte in bytes {
hash ^= u64::from(*byte);
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
}
hash
}
fn bounded_validation_message(message: Arc<str>) -> (Option<Arc<str>>, bool) {
if message.is_empty() {
return (None, false);
}
if message.len() <= MAX_VALIDATION_MESSAGE_BYTES {
return (Some(message), false);
}
let mut end = MAX_VALIDATION_MESSAGE_BYTES;
while !message.is_char_boundary(end) {
end -= 1;
}
(Some(Arc::from(&message[..end])), true)
}
#[cfg(test)]
mod tests;