nsh_core/props.rs
1//! Non-style view properties: touch handling, accessibility, gesture values
2//! and layout animations.
3
4use std::sync::Arc;
5
6use crate::{
7 element::PropEnum,
8 geometry::{Edges, Point, Points, px},
9 js::host::HostProps,
10};
11
12/// Edge insets in points.
13pub type EdgeInsets = Edges<Points>;
14
15/// Which touches a view and its children receive (`pointerEvents`).
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
17pub enum PointerEvents {
18 /// The view and its children receive touches (default).
19 #[default]
20 Auto,
21 /// Neither the view nor its children receive touches.
22 None,
23 /// Only the children receive touches; the view itself is transparent to them.
24 #[prop(rename = "box-none")]
25 BoxNone,
26 /// Only the view receives touches, never its children.
27 #[prop(rename = "box-only")]
28 BoxOnly,
29}
30
31/// What an element is, for assistive technologies (`role`).
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
33pub enum AccessibilityRole {
34 /// No particular role.
35 #[default]
36 None,
37 /// A button.
38 Button,
39 /// A link.
40 Link,
41 /// A search field.
42 Search,
43 /// A text box: a field the user types text into.
44 Textbox,
45 /// An image.
46 Image,
47 /// An image that acts as a button.
48 #[prop(rename = "imagebutton")]
49 ImageButton,
50 /// A key of a keyboard.
51 #[prop(rename = "keyboardkey")]
52 KeyboardKey,
53 /// Static text.
54 Text,
55 /// A value that can be adjusted (slider).
56 Adjustable,
57 /// A section header.
58 Header,
59 /// A summary of the app's state.
60 Summary,
61 /// An alert.
62 Alert,
63 /// A checkbox.
64 Checkbox,
65 /// A combo box.
66 Combobox,
67 /// A menu.
68 Menu,
69 /// A menu bar.
70 Menubar,
71 /// An item of a menu.
72 Menuitem,
73 /// A progress bar.
74 Progressbar,
75 /// A radio button.
76 Radio,
77 /// A group of radio buttons.
78 Radiogroup,
79 /// A scroll bar.
80 Scrollbar,
81 /// A spin button.
82 Spinbutton,
83 /// A switch.
84 Switch,
85 /// A tab.
86 Tab,
87 /// A list of tabs.
88 Tablist,
89 /// A timer.
90 Timer,
91 /// A toolbar.
92 Toolbar,
93 /// A list.
94 List,
95 /// A grid.
96 Grid,
97 /// A table: rows of cells under column headers.
98 Table,
99 /// A row of a table.
100 Row,
101 /// A cell of a table's row.
102 Cell,
103 /// A column's header cell.
104 #[prop(rename = "columnheader")]
105 ColumnHeader,
106 /// A group of a table's rows: its header, body or footer.
107 #[prop(rename = "rowgroup")]
108 RowGroup,
109 /// A list of options to choose from: a select's or combo box's popup.
110 Listbox,
111 /// An option of a listbox; `accessibilityState.selected` marks the chosen
112 /// one.
113 Option,
114 /// A group of related elements that is no landmark: an accordion, the
115 /// controls of a toolbar that belong together.
116 Group,
117 /// A section of the page a user may want to reach (a landmark): an
118 /// accordion's panel, labelled by its header.
119 Region,
120 /// A landmark of links or controls that move around the app: a
121 /// pagination, a breadcrumb.
122 Navigation,
123 /// A tree of items that expand and collapse (`treeitem`s).
124 Tree,
125 /// An item of a tree; `accessibilityState.expanded` tells whether its
126 /// children show, `accessibilityLevel` its depth (1 at the top).
127 #[prop(rename = "treeitem")]
128 TreeItem,
129 /// An item of a menu that is checked or not
130 /// (`accessibilityState.checked`).
131 #[prop(rename = "menuitemcheckbox")]
132 MenuItemCheckbox,
133 /// An item of a menu that is one choice of a group of them
134 /// (`accessibilityState.checked`).
135 #[prop(rename = "menuitemradio")]
136 MenuItemRadio,
137 /// A dialog over the rest of the app, named by its `label` (its
138 /// title): what `nsh_base::dialog` is unless the app gives it another
139 /// role.
140 Dialog,
141 /// A dialog that asks the user to confirm something or tells them
142 /// something urgent (a destructive action's confirmation), named by
143 /// its `label`.
144 #[prop(rename = "alertdialog")]
145 AlertDialog,
146 /// The content a tab of a [`Tablist`](Self::Tablist) shows: the
147 /// selected tab's section, which the tabs name with
148 /// `accessibilityControls`.
149 #[prop(rename = "tabpanel")]
150 TabPanel,
151}
152
153impl AccessibilityRole {
154 /// Whether the role is a control the pointer presses (a button, link,
155 /// tab, menu item…): text inside one shows the control's pointer, not
156 /// the I-beam of a selectable area around it, as a browser's
157 /// `<button>` text does.
158 pub fn is_control(self) -> bool {
159 matches!(
160 self,
161 Self::Button
162 | Self::Link
163 | Self::ImageButton
164 | Self::KeyboardKey
165 | Self::Checkbox
166 | Self::Combobox
167 | Self::Menuitem
168 | Self::MenuItemCheckbox
169 | Self::MenuItemRadio
170 | Self::Radio
171 | Self::Switch
172 | Self::Tab
173 | Self::Option
174 | Self::TreeItem
175 | Self::Adjustable
176 | Self::Spinbutton
177 | Self::Scrollbar
178 )
179 }
180}
181
182/// Whether a checkable element is checked (`accessibilityState.checked`).
183#[derive(Debug, Clone, Copy, PartialEq, Eq)]
184pub enum Checked {
185 /// Not checked.
186 False,
187 /// Checked.
188 True,
189 /// Partially checked.
190 Mixed,
191}
192
193/// Which item of a set an element is the current one of
194/// (`accessibilityState.current`, ARIA's `aria-current`).
195#[derive(Debug, Clone, Copy, PartialEq, Eq)]
196pub enum AccessibilityCurrent {
197 /// The current item of a set, of no particular kind (`true`).
198 True,
199 /// The current page: a pagination's, a breadcrumb's last link.
200 Page,
201 /// The current step of a process.
202 Step,
203 /// The current location: a place in a map or a flow chart.
204 Location,
205 /// The current date of a calendar.
206 Date,
207 /// The current time of a timetable.
208 Time,
209}
210
211/// Dynamic state of an element (`accessibilityState`).
212#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
213pub struct AccessibilityState {
214 /// Disabled.
215 pub disabled: bool,
216 /// Selected.
217 pub selected: bool,
218 /// Checked state of checkable elements.
219 pub checked: Option<Checked>,
220 /// Busy (loading).
221 pub busy: bool,
222 /// Expanded or collapsed, for expandable elements.
223 pub expanded: Option<bool>,
224 /// Pressed state of a toggle button (ARIA's `aria-pressed`): `Some`
225 /// makes a button one that stays on or off; `Mixed` is partly
226 /// pressed.
227 pub pressed: Option<Checked>,
228 /// The current item of a set (ARIA's `aria-current`): a pagination's
229 /// page, a wizard's step.
230 pub current: Option<AccessibilityCurrent>,
231 /// Opens a popup (ARIA's `aria-haspopup`): a menu's, a popover's or a
232 /// select's trigger, whose `expanded` says whether the popup is open;
233 /// an `expanded` element without it is a disclosure, which shows its
234 /// content in place (a collapsible's or an accordion's trigger).
235 pub has_popup: bool,
236 /// The content does not pass the app's checks (ARIA's
237 /// `aria-invalid`): a field whose text was rejected, a select left
238 /// empty that must not be.
239 pub invalid: bool,
240}
241
242/// The value of a range or textual element (`accessibilityValue`).
243#[derive(Debug, Clone, PartialEq, Default)]
244pub struct AccessibilityValue {
245 /// Minimum of the range.
246 pub min: Option<f32>,
247 /// Maximum of the range.
248 pub max: Option<f32>,
249 /// Current value in the range.
250 pub now: Option<f32>,
251 /// A textual description of the value; wins over the range.
252 pub text: Option<Arc<str>>,
253}
254
255/// How changes of an element are announced (Android `accessibilityLiveRegion`).
256#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
257pub enum LiveRegion {
258 /// Not announced.
259 #[default]
260 None,
261 /// Announced when the user is idle.
262 Polite,
263 /// Announced right away.
264 Assertive,
265}
266
267/// A custom action offered to assistive technologies.
268#[derive(Debug, Clone, PartialEq)]
269pub struct AccessibilityActionDef {
270 /// Name reported back in `onAccessibilityAction` (`activate`,
271 /// `increment`, `decrement` and `longpress` are standard actions).
272 pub name: Arc<str>,
273 /// Label shown to the user; required for custom actions.
274 pub label: Option<Arc<str>>,
275}
276
277crate::static_reactive!(Vec<AccessibilityActionDef>: Vec<AccessibilityActionDef>);
278
279/// Accessibility of one view.
280#[derive(Debug, Clone, PartialEq, Default)]
281pub struct Accessibility {
282 /// `accessible`: the view is one element for assistive technologies
283 /// (its children are not exposed separately). `None` keeps the
284 /// platform default: views with text or touch handlers are elements.
285 pub accessible: Option<bool>,
286 /// `accessibilityLabel`.
287 pub label: Option<Arc<str>>,
288 /// `accessibilityHint`.
289 pub hint: Option<Arc<str>>,
290 /// `accessibilityDescription`: more about the element than its name
291 /// (ARIA's `aria-description`): a dialog's message, what a field
292 /// expects. While `accessibilityDescribedBy` names a rendered element
293 /// with text, that text, which the core keeps current (ARIA's
294 /// `aria-describedby` wins over `aria-description` alike).
295 pub description: Option<Arc<str>>,
296 /// `role`.
297 pub role: AccessibilityRole,
298 /// `accessibilityState`.
299 pub state: AccessibilityState,
300 /// `accessibilityValue`.
301 pub value: Option<AccessibilityValue>,
302 /// `accessibilityElementsHidden` / `importantForAccessibility:
303 /// "no-hide-descendants"`: hide the view and its subtree.
304 pub hidden: bool,
305 /// `accessibilityLiveRegion`.
306 pub live_region: LiveRegion,
307 /// `accessibilityActions`.
308 pub actions: Vec<AccessibilityActionDef>,
309 /// `accessibilityLevel`: the level of a heading (1 the top), the depth
310 /// of a tree item (1 at the top); `None` has none.
311 pub level: Option<u32>,
312 /// `accessibilityActiveDescendant`: the view (its native id) that is
313 /// the active one inside this focused view, which keeps the keyboard
314 /// focus (ARIA's `aria-activedescendant`): a combo box's highlighted
315 /// option, a list's cursor row. Resolved by the core from the element
316 /// the app names; `None` when it names none or that element is gone.
317 pub active_descendant: Option<crate::NodeId>,
318 /// `accessibilityControls`: the view (its native id) whose content
319 /// this one controls (ARIA's `aria-controls`): a combo box's listbox,
320 /// a tab's panel. Resolved as [`Accessibility::active_descendant`].
321 pub controls: Option<crate::NodeId>,
322 /// `accessibilityDescribedBy`: the view (its native id) whose text
323 /// describes this one (ARIA's `aria-describedby`): a field's error
324 /// line. Resolved as [`Accessibility::active_descendant`]; its text is
325 /// [`Accessibility::description`], so a platform without such a
326 /// relation reads it all the same.
327 pub described_by: Option<crate::NodeId>,
328 /// The list's orientation (ARIA's `aria-orientation`, reported on the
329 /// web): `"horizontal"` or `"vertical"`, for a tab list or toolbar laid
330 /// out along that axis; `None` has none.
331 pub orientation: Option<crate::geometry::Axis>,
332}
333
334impl Accessibility {
335 /// True if nothing is set.
336 pub fn is_default(&self) -> bool {
337 *self == Self::default()
338 }
339
340 /// What a platform with one place for everything read after the name
341 /// (AT-SPI's and AccessKit's description, AppKit's help, UIKit's
342 /// hint) gets: `value_text` (a value it reads nowhere else), the
343 /// description and the hint, in that order, each a sentence of its
344 /// own (". " between them, or only a space after a part that already
345 /// ends with `.`, `!`, `?` or `…`, nothing after a full-width `。`,
346 /// `!` or `?`); `None` when there is none of them.
347 pub fn help_text(&self, value_text: Option<&str>) -> Option<String> {
348 let mut parts = [
349 value_text,
350 self.description.as_deref(),
351 self.hint.as_deref(),
352 ]
353 .into_iter()
354 .flatten()
355 .filter(|s| !s.is_empty());
356 let first = parts.next()?;
357 let mut out = first.to_owned();
358 for part in parts {
359 // A part that already ends its sentence keeps its own mark: a
360 // full-width one needs no space after it, a Latin one a space.
361 match out.chars().last() {
362 Some('。' | '!' | '?') => {}
363 Some('.' | '!' | '?' | '…') => out.push(' '),
364 _ => out.push_str(". "),
365 }
366 out.push_str(part);
367 }
368 Some(out)
369 }
370}
371
372/// One accessibility property, as set from JS.
373#[derive(Debug, Clone, PartialEq, HostProps)]
374pub enum AccessibilityProp {
375 /// `accessible`: the view is one element for assistive technologies (its
376 /// children are not exposed separately).
377 #[prop(js = "accessible")]
378 Accessible(Option<bool>),
379 /// `accessibilityLabel`: what screen readers read.
380 #[prop(js = "accessibilityLabel")]
381 Label(Option<Arc<str>>),
382 /// `accessibilityHint`: what activating the element does.
383 #[prop(js = "accessibilityHint")]
384 Hint(Option<Arc<str>>),
385 /// `accessibilityDescription`: more about the element than its name,
386 /// read after it: a dialog's message, what a field expects.
387 #[prop(js = "accessibilityDescription")]
388 Description(Option<Arc<str>>),
389 /// `role`: what the element is.
390 #[prop(js = "role", with = crate::js::host_values::role, reset = AccessibilityProp::Role(AccessibilityRole::None))]
391 Role(AccessibilityRole),
392 /// `accessibilityState`.
393 #[prop(js = "accessibilityState")]
394 State(AccessibilityState),
395 /// `accessibilityValue`: the value of a range or textual element.
396 #[prop(js = "accessibilityValue")]
397 Value(Option<AccessibilityValue>),
398 /// `accessibilityElementsHidden`: hides the view and its subtree from assistive
399 /// technologies.
400 #[prop(js = "accessibilityElementsHidden")]
401 Hidden(bool),
402 /// `importantForAccessibility`: `"auto"`, `"yes"`, `"no"` or
403 /// `"no-hide-descendants"`.
404 #[prop(js = "importantForAccessibility", with = crate::js::host_values::important, reset = AccessibilityProp::Important(None, false), ts = "\"auto\" | \"yes\" | \"no\" | \"no-hide-descendants\"")]
405 Important(Option<bool>, bool),
406 /// `accessibilityLiveRegion`: how changes of the view are announced by the
407 /// screen reader — TalkBack on Android, VoiceOver on macOS, UIA's live
408 /// setting and notification on Windows (`"polite"` when the user is idle,
409 /// `"assertive"` right away).
410 #[prop(android = "accessibilityLiveRegion")]
411 #[prop(
412 js = "accessibilityLiveRegion",
413 ts = "\"none\" | \"polite\" | \"assertive\""
414 )]
415 LiveRegion(LiveRegion),
416 /// `accessibilityActions`: custom actions offered to assistive technologies
417 /// (`onAccessibilityAction` reports them).
418 #[prop(js = "accessibilityActions")]
419 Actions(Vec<AccessibilityActionDef>),
420 /// `accessibilityLevel`: the level of a heading (`role="header"`, 1
421 /// the top) or the depth of a tree item (`role="treeitem"`, 1 at the
422 /// top); others than whole numbers from 1 are none.
423 #[prop(js = "accessibilityLevel", with = crate::js::host_values::accessibility_level, reset = AccessibilityProp::Level(None), ts = "number")]
424 Level(Option<u32>),
425 /// `accessibilityActiveDescendant`: the element that is the active one
426 /// while this element keeps the keyboard focus (ARIA's
427 /// `aria-activedescendant`): a combo box's highlighted option, a
428 /// list's cursor row. Screen readers read it as it changes.
429 #[prop(js = "accessibilityActiveDescendant", with = crate::js::host_values::active_descendant, reset = AccessibilityProp::ActiveDescendant(None), ts = "ViewRef | null")]
430 ActiveDescendant(Option<crate::element::ElementTarget>),
431 /// `accessibilityControls`: the element whose content this one
432 /// controls (ARIA's `aria-controls`): a combo box's listbox.
433 #[prop(js = "accessibilityControls", with = crate::js::host_values::accessibility_controls, reset = AccessibilityProp::Controls(None), ts = "ViewRef | null")]
434 Controls(Option<crate::element::ElementTarget>),
435 /// `accessibilityDescribedBy`: the element whose text describes this
436 /// one (ARIA's `aria-describedby`): a field's error or help line,
437 /// placed apart from it. Screen readers read that text after the
438 /// name, in the place of `accessibilityDescription` while it names a
439 /// rendered element with text.
440 #[prop(js = "accessibilityDescribedBy", with = crate::js::host_values::accessibility_described_by, reset = AccessibilityProp::DescribedBy(None), ts = "ViewRef | null")]
441 DescribedBy(Option<crate::element::ElementTarget>),
442 /// `aria-orientation` (web): set by a component from its own
443 /// orientation (a `Tabs`'s), never from JS.
444 Orientation(Option<crate::geometry::Axis>),
445}
446
447/// Android's press ripple (`android={{ ripple }}`).
448#[derive(Debug, Clone, Copy, PartialEq, Default)]
449pub struct Ripple {
450 /// Ripple color; the theme's when `None`.
451 pub color: Option<crate::style::Color>,
452 /// The ripple is not clipped to the view.
453 pub borderless: bool,
454 /// Radius in points; the platform's when `None`.
455 pub radius: Option<Points>,
456 /// Drawn over the view's content (else behind it).
457 pub foreground: bool,
458}
459
460/// Non-style properties of a view that only the platform needs.
461#[derive(Debug, Clone, PartialEq, Default)]
462pub struct ViewProps {
463 /// Resolved overlay placement for native grid projection; ordinary views have none.
464 pub overlay_anchor: Option<crate::overlay::PlacedAnchor>,
465 /// A shown overlay's place in the Tab order: right after this view
466 /// and before its children, where the app put the overlay (a popover's
467 /// content follows its trigger), not at the end of the root view its
468 /// native view is in. Set by the core; platforms that order Tab
469 /// themselves walk with [`crate::input::tab_order`].
470 pub tab_after: Option<crate::NodeId>,
471 /// Tab and screen readers go through the view's children as they are
472 /// on screen, along this axis and then across it, instead of in tree
473 /// order. The core sets it on a list in its parent's viewport: a list
474 /// recycles its cells, so in the tree they are not in their rows'
475 /// order. Scroll views read their content so without it.
476 pub screen_order: Option<crate::geometry::Axis>,
477 /// Which touches the view and its subtree receive.
478 pub pointer_events: PointerEvents,
479 /// Extends the touch area beyond the view's bounds.
480 pub hit_slop: EdgeInsets,
481 /// Milliseconds before a press becomes a long press (platform default
482 /// when `None`).
483 pub long_press_delay: Option<f32>,
484 /// Ripple while pressed (Android).
485 pub ripple: Option<Ripple>,
486 /// Accessibility.
487 pub accessibility: Accessibility,
488 /// `testID`: an identifier for UI tests.
489 pub test_id: Option<Arc<str>>,
490 /// `nativeID`: names the view for the embedding app's native code (a
491 /// watched scroll view, `watchScroll`), apart from `testID`, which is
492 /// for tests.
493 pub native_id: Option<Arc<str>>,
494 /// `web={{ element }}`: the HTML element the web draws the view as.
495 pub web_element: Option<crate::WebElement>,
496 /// Where the view goes as a link (`Link`'s `href`): data for the
497 /// platform, never shown or read to accessibility clients. A terminal
498 /// draws the text inside the view as an OSC 8 hyperlink to it. A
499 /// span's (`TextView`'s links) goes into its block's text instead
500 /// (`AttributedText::link_hrefs`).
501 pub href: Option<Arc<str>>,
502 /// `panActivation`: the view's touch responder waits for a pan the
503 /// platform recognizes.
504 pub pan_activation: Option<PanActivation>,
505 /// A vertical pan cooperates with descendant scroll views on iOS.
506 pub pan_scroll_handoff: bool,
507 /// `windowDrag` (desktops): pressing the view drags the window; `None`
508 /// leaves it to the views around it.
509 pub window_drag: Option<bool>,
510 /// `windowControl` (desktops): the system window button the view acts
511 /// as.
512 pub window_control: Option<crate::desktop::WindowControl>,
513 /// `windowResize` (desktops): the edge or corner of a frameless window
514 /// pressing the view resizes it by.
515 pub window_resize: Option<crate::desktop::ResizeEdge>,
516 /// `focusable`: whether the view is a stop of the keyboard focus (Tab):
517 /// `Some(true)` makes any view one, whether or not it takes presses (a
518 /// chart, a slider, a list that moves its selection with the arrow
519 /// keys); `Some(false)` keeps a view that takes presses out; `None`, the
520 /// default, leaves it to the presses ([`ViewProps::focus_stop`]).
521 pub focusable: Option<bool>,
522 /// Keys consumed by this view or a focused descendant before native
523 /// defaults run. Backends decide from the mounted rules without
524 /// waiting for a listener (`Interactive::capture_keys`).
525 pub key_capture: crate::KeyCapture,
526 /// Where keyboard ancestry continues for a portaled view (an overlay
527 /// whose native parent is its root view while its logical parent is
528 /// the view it is in): the logical parent's node id. Internal routing
529 /// only; native layout, focus and hit testing keep their parent. `None`
530 /// for ordinary views and for portals with no key listener or capture
531 /// rule on their logical ancestry.
532 pub key_parent: Option<crate::NodeId>,
533 /// The app's content view where unfocused keys start in this native
534 /// window. Mounted by the core so keyboard routing follows logical
535 /// order even when the backend stacks the children differently. Only
536 /// sent when that path has a key listener or capture rule.
537 #[doc(hidden)]
538 pub key_content: Option<crate::NodeId>,
539 /// The view is a selectable view (`View`'s `selectable`): the
540 /// texts in its subtree that are not `selectable={false}` share one
541 /// selection, from text to text ([`crate::selection`]); an area inside
542 /// another is part of the outer one. Texts outside areas select alone.
543 pub selectable_view: bool,
544 /// The app's items of a selectable view's selection menu, after the
545 /// system's (`selectionMenu`): plain items and separators, each
546 /// action's `id` reported as the root's `Menu` event when chosen. The
547 /// selection's menu takes the items of the outermost selectable view
548 /// around it ([`crate::desktop::MenuItem::selection_menu`]).
549 pub selection_menu: Arc<[crate::desktop::MenuItem]>,
550 /// The text continues the text before it in document order, as a long
551 /// line's next wrapped part (`Element::continues_text`): in a
552 /// selectable view a copy joins the two with nothing between them,
553 /// and a double or triple click selects across them
554 /// ([`crate::selection::SelectionTexts::continues`]).
555 pub continues_text: bool,
556 /// `ios={{ scrollEdgeElement }}`: the scroll view the view floats
557 /// over and the edge of it the view sits at. Resolved by the core from
558 /// the element the app names; `None` when it names none or that element
559 /// is gone.
560 pub scroll_edge_element: Option<ScrollEdgeElement>,
561}
562
563/// The edge of a scroll view a view floating over it sits at
564/// (`ios={{ scrollEdgeElement }}`).
565#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
566#[non_exhaustive]
567pub enum ScrollEdge {
568 /// The top edge.
569 Top,
570 /// The bottom edge (default).
571 #[default]
572 Bottom,
573}
574
575/// A view floating over an edge of a scroll view, as the platform gets it
576/// ([`ViewProps::scroll_edge_element`]): on iOS 26 and later the scroll
577/// edge effect of that scroll view takes its shape from the view, as it
578/// does from a bar, so the content scrolled under the view fades out
579/// around what the view shows instead of being cut by it. Elsewhere a
580/// fade the app draws under the view gives the same separation.
581#[derive(Debug, Clone, Copy, PartialEq, Eq)]
582#[non_exhaustive]
583pub struct ScrollEdgeElement {
584 /// The scroll view (its native id).
585 pub scroll_view: crate::NodeId,
586 /// The edge of it the view sits at.
587 pub edge: ScrollEdge,
588}
589
590impl ViewProps {
591 /// Whether a view with these props is a stop of the keyboard focus
592 /// (Tab and Shift+Tab reach it; it hears `onFocus` / `onBlur` and takes
593 /// the `focus:` styles), given whether it `takes_presses` (listens for
594 /// `onPress`): `focusable` decides when it is set, else taking presses
595 /// does; a disabled view is never one.
596 ///
597 /// Focus and presses are separate: a stop that takes no presses is not
598 /// pressed by Return or Space (its keys reach it through the app's
599 /// keymap while it has the focus), and a view needs no press handler to
600 /// be focusable, which would take the presses of a pressable around it
601 /// (a chart in a card that opens a page). Backends use this decision
602 /// for view focus stops; inputs that edit are stops by their own rule,
603 /// and each platform adds what it knows of visibility.
604 pub fn focus_stop(&self, takes_presses: bool) -> bool {
605 self.focusable.unwrap_or(takes_presses) && !self.accessibility.state.disabled
606 }
607}
608
609/// The way a finger moves (`PanActivation::direction`): toward the left
610/// edge, the right edge, the top or the bottom.
611#[derive(Debug, Clone, Copy, PartialEq, Eq, PropEnum)]
612#[non_exhaustive]
613pub enum PanDirection {
614 /// Toward the left edge.
615 Left,
616 /// Toward the right edge.
617 Right,
618 /// Toward the top.
619 Up,
620 /// Toward the bottom.
621 Down,
622}
623
624/// An edge of the screen, or of the window on desktops and the page on
625/// the web, that a pan starts at (`PanActivation::edge`).
626#[derive(Debug, Clone, Copy, PartialEq, Eq, PropEnum)]
627#[non_exhaustive]
628pub enum PanEdge {
629 /// The left edge: the pan moves right.
630 Left,
631 /// The right edge: the pan moves left.
632 Right,
633 /// The top edge: the pan moves down.
634 Top,
635 /// The bottom edge: the pan moves up.
636 Bottom,
637}
638
639impl PanEdge {
640 /// The way a pan from this edge moves: away from it.
641 pub(crate) fn direction(self) -> PanDirection {
642 match self {
643 PanEdge::Left => PanDirection::Right,
644 PanEdge::Right => PanDirection::Left,
645 PanEdge::Top => PanDirection::Down,
646 PanEdge::Bottom => PanDirection::Up,
647 }
648 }
649}
650
651/// When the pans on a view activate (`panActivation`; react-native-gesture-
652/// handler's `activeOffsetX` / `failOffsetY`), decided by the platform on
653/// the main thread as the fingers move: once the finger has moved further
654/// than an active offset from where it went down, the pan activates (the
655/// view becomes the touch responder and the scroll views around it can no
656/// longer take these touches); once it has moved further than a fail offset
657/// first, the pan fails and the scroll views keep the touches. Offsets are
658/// distances in points along one axis, either direction. Without active
659/// offsets, the pan activates after [`PanActivation::MIN_DISTANCE`] in any
660/// direction. The view's native pan (`pan` values, `on_pan_start`) starts
661/// when it activates too.
662///
663/// A [`direction`](Self::direction) keeps the pan to one way: a drag the
664/// other way, or mostly across it, fails it and stays with the views
665/// around. An [`edge`](Self::edge) keeps it to fingers that go down at
666/// that edge of the screen, moving away from it.
667#[derive(Debug, Clone, Copy, PartialEq, Default)]
668pub struct PanActivation {
669 /// Activates once the finger moved further than this horizontally.
670 pub active_offset_x: Option<Points>,
671 /// Activates once the finger moved further than this vertically.
672 pub active_offset_y: Option<Points>,
673 /// Fails once the finger moved further than this horizontally first.
674 pub fail_offset_x: Option<Points>,
675 /// Fails once the finger moved further than this vertically first.
676 pub fail_offset_y: Option<Points>,
677 /// The one way the pan activates in: once the finger moved that way
678 /// further than the active offset along its axis
679 /// ([`PanActivation::MIN_DISTANCE`] without one), and more along it
680 /// than across. A move as far the other way fails the pan, and so does
681 /// one mostly across it, unless a fail offset across is given, which
682 /// decides that instead. The active offset across is not used.
683 pub direction: Option<PanDirection>,
684 /// The edge of the screen the pan starts at (of the window on desktops,
685 /// of the page on the web): only a finger that goes down within
686 /// [`PanActivation::EDGE_WIDTH`] of it starts the pan, which then moves
687 /// away from it (that is its direction; `direction` is not used). iOS
688 /// recognizes the native pan with its own screen-edge gesture, whose
689 /// edge is the system's, and a navigation stack that can go back keeps
690 /// its swipe back. On Android, the system's back gesture keeps the left
691 /// and right edges under gesture navigation.
692 pub edge: Option<PanEdge>,
693}
694
695impl PanActivation {
696 /// How far the finger moves before a pan without active offsets
697 /// activates, in points.
698 pub const MIN_DISTANCE: Points = px(10.0);
699
700 /// How far from its edge a finger goes down to start an edge pan
701 /// ([`PanActivation::edge`]), in points.
702 pub const EDGE_WIDTH: Points = px(20.0);
703
704 /// Sets [`PanActivation::active_offset_x`].
705 pub fn active_offset_x(mut self, offset: Points) -> Self {
706 self.active_offset_x = Some(offset);
707 self
708 }
709
710 /// Sets [`PanActivation::active_offset_y`].
711 pub fn active_offset_y(mut self, offset: Points) -> Self {
712 self.active_offset_y = Some(offset);
713 self
714 }
715
716 /// Sets [`PanActivation::fail_offset_x`].
717 pub fn fail_offset_x(mut self, offset: Points) -> Self {
718 self.fail_offset_x = Some(offset);
719 self
720 }
721
722 /// Sets [`PanActivation::fail_offset_y`].
723 pub fn fail_offset_y(mut self, offset: Points) -> Self {
724 self.fail_offset_y = Some(offset);
725 self
726 }
727
728 /// Sets [`PanActivation::direction`]: a drawer opened by a drag to
729 /// the right over its content, `PanActivation::default()
730 /// .direction(PanDirection::Right)`, leaves the drags to the left to
731 /// the content.
732 pub fn direction(mut self, direction: PanDirection) -> Self {
733 self.direction = Some(direction);
734 self
735 }
736
737 /// Sets [`PanActivation::edge`]: a drawer opened from the left edge,
738 /// `PanActivation::default().edge(PanEdge::Left)`.
739 pub fn edge(mut self, edge: PanEdge) -> Self {
740 self.edge = Some(edge);
741 self
742 }
743
744 /// The way the pan activates in, if it has one: away from its edge, or
745 /// its direction. For the backends.
746 #[doc(hidden)]
747 pub fn way(&self) -> Option<PanDirection> {
748 self.edge.map(PanEdge::direction).or(self.direction)
749 }
750
751 /// Whether a finger going down at `at` may start the pan, in an area
752 /// (the screen, the window or the page) of `size` with `at` measured
753 /// from its top left corner: anywhere without an
754 /// [`edge`](Self::edge), else within [`PanActivation::EDGE_WIDTH`] of
755 /// it. For the backends.
756 #[doc(hidden)]
757 pub fn starts_at(&self, at: Point<Points>, size: crate::Size<Points>) -> bool {
758 let w = Self::EDGE_WIDTH.0;
759 match self.edge {
760 None => true,
761 Some(PanEdge::Left) => at.x.0 <= w,
762 Some(PanEdge::Right) => at.x.0 >= size.width.0 - w,
763 Some(PanEdge::Top) => at.y.0 <= w,
764 Some(PanEdge::Bottom) => at.y.0 >= size.height.0 - w,
765 }
766 }
767
768 /// A pan that activates horizontally past `active` and fails when it
769 /// moves vertically past `fail` first (a scrubber in a vertical scroll
770 /// view).
771 pub const fn horizontal(active: Points, fail: Points) -> Self {
772 Self {
773 active_offset_x: Some(active),
774 active_offset_y: None,
775 fail_offset_x: None,
776 fail_offset_y: Some(fail),
777 direction: None,
778 edge: None,
779 }
780 }
781
782 /// A pan that activates vertically past `active` and fails when it
783 /// moves horizontally past `fail` first.
784 pub const fn vertical(active: Points, fail: Points) -> Self {
785 Self {
786 active_offset_x: None,
787 active_offset_y: Some(active),
788 fail_offset_x: Some(fail),
789 fail_offset_y: None,
790 direction: None,
791 edge: None,
792 }
793 }
794
795 /// The one axis this pan is for, when its way or its offsets name one:
796 /// `Some(true)` horizontal (a way left or right, an active offset along
797 /// x, or a fail offset along y), `Some(false)` vertical, `None` either.
798 /// A view listening to `onWheel` with a pan along one axis takes only
799 /// the wheels along it ([`crate::input::wheel_along`]).
800 pub fn axis(&self) -> Option<bool> {
801 if let Some(way) = self.way() {
802 return Some(matches!(way, PanDirection::Left | PanDirection::Right));
803 }
804 let x = self.active_offset_x.is_some() || self.fail_offset_y.is_some();
805 let y = self.active_offset_y.is_some() || self.fail_offset_x.is_some();
806 match (x, y) {
807 (true, false) => Some(true),
808 (false, true) => Some(false),
809 _ => None,
810 }
811 }
812
813 /// The decision once the finger moved by (`dx`, `dy`) since it went
814 /// down: `Some(true)` activates, `Some(false)` fails (a fail offset
815 /// passed wins over an active one passed by the same move), `None`
816 /// waits. The platforms ask it on every move until it decides.
817 pub fn decide(&self, dx: Points, dy: Points) -> Option<bool> {
818 let (dx, dy) = (dx.0, dy.0);
819 let past = |limit: Option<Points>, d: f32| limit.is_some_and(|l| d.abs() > l.0);
820 if past(self.fail_offset_x, dx) || past(self.fail_offset_y, dy) {
821 return Some(false);
822 }
823 if let Some(way) = self.way() {
824 // How far it moved that way and across, the offset along it, and
825 // whether a fail offset across decides the moves across.
826 let (along, across, active, fail_across) = match way {
827 PanDirection::Right => (dx, dy, self.active_offset_x, self.fail_offset_y),
828 PanDirection::Left => (-dx, dy, self.active_offset_x, self.fail_offset_y),
829 PanDirection::Down => (dy, dx, self.active_offset_y, self.fail_offset_x),
830 PanDirection::Up => (-dy, dx, self.active_offset_y, self.fail_offset_x),
831 };
832 let limit = active.unwrap_or(Self::MIN_DISTANCE).0;
833 let across = across.abs();
834 if along > limit && along >= across {
835 return Some(true);
836 }
837 let across_fails = fail_across.is_none() && across > limit && across > along;
838 return (-along > limit || across_fails).then_some(false);
839 }
840 let activates = if self.active_offset_x.is_some() || self.active_offset_y.is_some() {
841 past(self.active_offset_x, dx) || past(self.active_offset_y, dy)
842 } else {
843 dx.hypot(dy) > Self::MIN_DISTANCE.0
844 };
845 activates.then_some(true)
846 }
847
848 /// [`PanActivation::decide`] on a move of the finger from offset `from`
849 /// to offset `to` (both from where it went down), judged along the
850 /// straight line between them a point at a time: the offset the finger
851 /// passed first decides, even when the move passes both. Moves arrive
852 /// several points apart, and a diagonal 1.5 across for 1 down passes
853 /// `activeOffsetX: 10` and `failOffsetY: 10` within one 10-point move.
854 /// The platforms ask it with the previous move's offset as `from`.
855 pub fn decide_move(&self, from: Point<Points>, to: Point<Points>) -> Option<bool> {
856 let (mx, my) = (to.x.0 - from.x.0, to.y.0 - from.y.0);
857 let steps = mx.hypot(my).ceil().max(1.0) as u32;
858 (1..=steps).find_map(|i| {
859 let t = i as f32 / steps as f32;
860 self.decide(Points(from.x.0 + mx * t), Points(from.y.0 + my * t))
861 })
862 }
863}
864
865/// Native animation values driven by gestures on a view.
866#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
867pub struct GestureValues {
868 /// Horizontal drag translation (`pan={{ x }}`).
869 pub pan_x: Option<crate::animation::NodeId>,
870 /// Vertical drag translation (`pan={{ y }}`).
871 pub pan_y: Option<crate::animation::NodeId>,
872 /// Pinch scale (`pinch={{ scale }}`), multiplied from its value when the
873 /// pinch starts.
874 pub pinch: Option<crate::animation::NodeId>,
875 /// Two-finger rotation in degrees (`rotation={{ angle }}`), added to its
876 /// value when the rotation starts.
877 pub rotation: Option<crate::animation::NodeId>,
878}
879
880impl GestureValues {
881 /// True if no value is driven.
882 pub fn is_empty(&self) -> bool {
883 *self == Self::default()
884 }
885}
886
887/// Timing curve of a layout animation.
888#[derive(Debug, Clone, Copy, PartialEq)]
889pub enum LayoutCurve {
890 /// Constant speed.
891 Linear,
892 /// Accelerates.
893 EaseIn,
894 /// Decelerates.
895 EaseOut,
896 /// Accelerates, then decelerates.
897 EaseInEaseOut,
898 /// A spring's physics ([`LayoutTransition::spring`]): it times itself,
899 /// lasting until it settles ([`Spring::settle_ms`]), and moves the same
900 /// on every platform. The transition's `duration_ms` is not used. Its
901 /// `velocity` and `frame_rate` are not either: a layout moves from rest
902 /// at the screen's rate. JS names it with a `type: "spring"` phase's
903 /// `stiffness`, `damping` or `mass`.
904 ///
905 /// [`Spring::settle_ms`]: crate::element::Spring::settle_ms
906 Spring(crate::element::Spring),
907 /// A spring of this damping ratio fitted into the transition's
908 /// duration, which each platform draws with its own spring: the JS
909 /// `LayoutAnimation`'s `type: "spring"` (`springDamping`) without a
910 /// stiffness, damping or mass. Rust prefers
911 /// [`LayoutCurve::Spring`].
912 FittedSpring {
913 /// Damping ratio (0..1): 1 does not overshoot.
914 damping_ratio: f32,
915 },
916 /// The software keyboard's motion (`type: "keyboard"`): the curve the
917 /// system moves its keyboard with, timed from when the keyboard
918 /// started to move, so that what makes room for it moves with it (the
919 /// duration is the keyboard's, `keyboard_duration`). Where there is no
920 /// software keyboard, or nothing moved it, it eases in and out.
921 Keyboard,
922 /// A cubic Bézier `[x1, y1, x2, y2]` over the transition's duration,
923 /// as CSS `cubic-bezier()` (`type: "bezier"` with `bezier` in JS):
924 /// the curve an app's design names. The `x` of each control point is
925 /// clamped to 0..1.
926 Bezier([f32; 4]),
927}
928
929impl LayoutCurve {
930 /// A cubic Bézier `[x1, y1, x2, y2]` ([`LayoutCurve::Bezier`]), each
931 /// control point's `x` clamped to 0..1.
932 pub fn bezier(x1: f32, y1: f32, x2: f32, y2: f32) -> Self {
933 Self::Bezier([x1.clamp(0.0, 1.0), y1, x2.clamp(0.0, 1.0), y2])
934 }
935}
936
937/// The property animated when views appear or disappear.
938#[derive(Debug, Clone, Copy, PartialEq, Eq)]
939pub enum LayoutProperty {
940 /// Fade in / out.
941 Opacity,
942 /// Grow / shrink from the center.
943 Scale,
944}
945
946/// How one kind of change animates.
947#[derive(Debug, Clone, Copy, PartialEq)]
948pub struct LayoutTransition {
949 /// Curve.
950 pub curve: LayoutCurve,
951 /// Animated property of appearing / disappearing views.
952 pub property: LayoutProperty,
953 /// Duration in milliseconds.
954 pub duration_ms: f32,
955 /// Delay in milliseconds.
956 pub delay_ms: f32,
957}
958
959/// Animates the layout changes of the next commit
960/// (`LayoutAnimation.configureNext`).
961#[derive(Debug, Clone, Copy, PartialEq, Default)]
962pub struct LayoutAnimation {
963 /// Views inserted by the commit.
964 pub create: Option<LayoutTransition>,
965 /// Views whose frame changes.
966 pub update: Option<LayoutTransition>,
967 /// Views removed by the commit.
968 pub delete: Option<LayoutTransition>,
969}
970
971impl LayoutTransition {
972 /// `curve` over `duration_ms`, appearing views fading.
973 pub const fn new(curve: LayoutCurve, duration_ms: f32) -> Self {
974 Self {
975 curve,
976 property: LayoutProperty::Opacity,
977 duration_ms,
978 delay_ms: 0.0,
979 }
980 }
981
982 /// On `spring`'s physics ([`LayoutCurve::Spring`]), lasting until it
983 /// settles, appearing views fading.
984 pub fn spring(spring: crate::element::Spring) -> Self {
985 Self::new(LayoutCurve::Spring(spring), spring.settle_ms())
986 }
987
988 /// How long it runs, in milliseconds: its `duration_ms`, or the time
989 /// its spring settles in ([`LayoutCurve::Spring`] times itself). What
990 /// the platforms animate over.
991 pub fn run_ms(&self) -> f32 {
992 match self.curve {
993 LayoutCurve::Spring(spring) => spring.settle_ms(),
994 _ => self.duration_ms,
995 }
996 }
997}
998
999impl LayoutAnimation {
1000 /// `transition` for every kind of change.
1001 pub const fn all(transition: LayoutTransition) -> Self {
1002 Self {
1003 create: Some(transition),
1004 update: Some(transition),
1005 delete: Some(transition),
1006 }
1007 }
1008
1009 /// React Native's `LayoutAnimation.Presets.easeInEaseOut`: 300 ms,
1010 /// views fading in and out.
1011 pub const EASE_IN_EASE_OUT: Self =
1012 Self::all(LayoutTransition::new(LayoutCurve::EaseInEaseOut, 300.0));
1013
1014 /// `Presets.linear`: 500 ms at constant speed.
1015 pub const LINEAR: Self = Self::all(LayoutTransition::new(LayoutCurve::Linear, 500.0));
1016
1017 /// `Presets.spring`: frames spring (damping 0.4) over 700 ms, views
1018 /// fade linearly.
1019 pub const SPRING: Self = Self {
1020 create: Some(LayoutTransition::new(LayoutCurve::Linear, 700.0)),
1021 update: Some(LayoutTransition::new(
1022 LayoutCurve::FittedSpring { damping_ratio: 0.4 },
1023 700.0,
1024 )),
1025 delete: Some(LayoutTransition::new(LayoutCurve::Linear, 700.0)),
1026 };
1027}