Skip to main content

nsh_core/
mount.rs

1use std::sync::Arc;
2
3use nsh_macros::PropEnum;
4
5use crate::{
6    animation::{AnimationOp, AnimationProp},
7    geometry::{Bounds, Points, Size},
8    ops::{
9        AutoCapitalize, Command, EventMask, HeaderTitleAlign, ImageSource, KeyboardAppearance,
10        KeyboardDismissMode, KeyboardTaps, KeyboardType, ModalAnimation, ModalPresentation, NodeId,
11        PasteBehavior, ResizeMode, ReturnKeyType, ScreenAnimation, SnapAlignment, SubmitBehavior,
12        WebSource,
13    },
14    props::{EdgeInsets, GestureValues, LayoutAnimation, ViewProps},
15    style::{Color, TextAlign, ViewStyle},
16    text::{AttributedText, ResolvedTextStyle, TextLayout},
17};
18
19/// Kind of native view to create.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum ViewKind {
22    /// A plain container view.
23    View,
24    /// A text label.
25    Text,
26    /// An image.
27    Image,
28    /// A scroll view (also used by lists).
29    Scroll,
30    /// A text input.
31    Input,
32    /// A navigation stack: its children are screens, pushed and popped
33    /// natively.
34    Stack,
35    /// A screen of a stack (its root view; the platform also makes its
36    /// header).
37    Screen,
38    /// The root view of a modal: inserting it presents the modal, removing
39    /// it dismisses it.
40    Modal,
41    /// A view shown in a screen's header (its slot is in the screen's
42    /// [`ScreenConfig`]).
43    HeaderItem,
44    /// A bar over the keyboard ([`InputConfig::accessory`]); its frame's
45    /// size is its own, the platform places it.
46    InputAccessory,
47    /// A canvas ([`MountItem::Canvas`]).
48    Canvas,
49    /// A web view.
50    WebView,
51    /// The container of a registered native component: the platform
52    /// creates the component in it ([`MountItem::Component`]) and fills it
53    /// with the component's view; decoration and frames are the
54    /// container's.
55    Native,
56    /// A video player.
57    Video,
58}
59
60/// A web view.
61#[derive(Debug, Clone, PartialEq)]
62pub struct WebProps {
63    /// What it shows.
64    pub source: WebSource,
65    /// The `src` prop, which [`Self::source`] loads unless `html` is set.
66    pub src: Option<Arc<str>>,
67    /// The `baseUrl` prop, which [`Self::source`] holds while `html` is
68    /// set.
69    pub base_url: Option<Arc<str>>,
70    /// The one origin this web view may show besides `webview.hosts`
71    /// (`allowOrigin`, granted by `webview.runtimeOrigin`): a web view's
72    /// backend checks its navigations with
73    /// [`Access::allows_webview_with`](crate::access::Access::allows_webview_with).
74    pub allow_origin: Option<crate::access::WebOrigin>,
75    /// The hosts this web view may show, narrower than the app's grant
76    /// (`allowNavigation`; none: not narrowed). Checked with
77    /// [`Access::allows_webview_in`](crate::access::Access::allows_webview_in).
78    pub allow_navigation: Option<crate::access::WebHosts>,
79    /// Script run after each page loads.
80    pub injected_js: Option<Arc<str>>,
81    /// Script run before each page's own scripts.
82    pub injected_js_before: Option<Arc<str>>,
83    /// User agent; the platform's when `None`.
84    pub user_agent: Option<Arc<str>>,
85    /// The page scrolls.
86    pub scrollable: bool,
87    /// The page may run JavaScript.
88    pub javascript_enabled: bool,
89    /// Swipes go back and forward (iOS).
90    pub back_forward_gestures: bool,
91    /// Website data (cookies, storage, the cache) lives only as long as
92    /// the web view, apart from the app's other web views (Android: no
93    /// HTTP cache and no saved form data). Read when the platform makes the
94    /// web view: the core keeps it from changing afterwards.
95    pub incognito: bool,
96    /// The person can pinch to zoom the page, past its viewport's scale
97    /// limits. Read when the platform makes the web view, as `incognito`.
98    pub zoomable: bool,
99    /// The URL schemes the page loads from the app
100    /// ([`crate::web_resource`]). Read when the platform makes the web
101    /// view, as `incognito`.
102    pub url_schemes: Vec<crate::web_resource::WebUrlScheme>,
103    /// Internal: an `on_download` or `on_download_pending` listener asks
104    /// the platform to hold every download for the core. Read by the
105    /// web view's backend.
106    #[doc(hidden)]
107    pub defer_downloads: bool,
108}
109
110impl Default for WebProps {
111    fn default() -> Self {
112        Self {
113            source: WebSource::None,
114            src: None,
115            base_url: None,
116            allow_origin: None,
117            allow_navigation: None,
118            injected_js: None,
119            injected_js_before: None,
120            user_agent: None,
121            scrollable: true,
122            javascript_enabled: true,
123            back_forward_gestures: false,
124            incognito: false,
125            zoomable: false,
126            url_schemes: Vec::new(),
127            defer_downloads: false,
128        }
129    }
130}
131
132/// What a video's sound does to the rest of the device's audio while it
133/// plays: whether it plays in silent mode, whether other apps' audio pauses,
134/// and whether the system treats it as speech. iOS sets the shared
135/// `AVAudioSession` while such a video plays and restores it after; Android
136/// marks the sound as speech and holds audio focus for `Playback`.
137#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
138pub enum AudioSession {
139    /// The app's audio settings (the platform's for video unless the app, or
140    /// the app embedding NSH, set others): nothing is changed.
141    #[default]
142    Default,
143    /// Plays speech: audible in silent mode, other apps' audio pauses while
144    /// it plays (Apple's `playback` category, `spokenAudio` mode; Android's
145    /// speech content type with transient audio focus).
146    Playback,
147    /// Plays speech over other apps' audio, which keeps playing
148    /// (Apple's `playback` category with `mixWithOthers`; Android's speech
149    /// content type without audio focus).
150    MixWithOthers,
151}
152
153/// A video player.
154#[derive(Debug, Clone, PartialEq)]
155pub struct VideoProps {
156    /// The video's URL (or `asset:/` URI).
157    pub source: Option<Arc<str>>,
158    /// An image (URL or `asset:/` URI) shown while the video loads, until
159    /// its first frame is ready.
160    pub poster: Option<Arc<str>>,
161    /// What its sound does to the rest of the device's audio.
162    pub audio_session: AudioSession,
163    /// Paused.
164    pub paused: bool,
165    /// Muted.
166    pub muted: bool,
167    /// Volume, 0..1.
168    pub volume: f32,
169    /// Playback rate.
170    pub rate: f32,
171    /// Loop.
172    pub repeat: bool,
173    /// How the picture fits the view.
174    pub resize_mode: ResizeMode,
175    /// Show the platform's playback controls.
176    pub controls: bool,
177    /// Milliseconds between `onProgress` events.
178    pub progress_interval_ms: f32,
179}
180
181impl Default for VideoProps {
182    fn default() -> Self {
183        Self {
184            source: None,
185            poster: None,
186            audio_session: AudioSession::default(),
187            paused: false,
188            muted: false,
189            volume: 1.0,
190            rate: 1.0,
191            repeat: false,
192            resize_mode: ResizeMode::Contain,
193            controls: false,
194            progress_interval_ms: 250.0,
195        }
196    }
197}
198
199/// The properties of a native control.
200#[derive(Debug, Clone, PartialEq)]
201pub enum NativeProps {
202    /// A web view.
203    WebView(Box<WebProps>),
204    /// A video player.
205    Video(Box<VideoProps>),
206}
207
208/// How a scroll view scrolls (React Native's ScrollView props).
209#[derive(Debug, Clone, PartialEq)]
210pub struct ScrollBehavior {
211    /// Stops at multiples of the viewport.
212    pub paging: bool,
213    /// Stops at multiples of this length (0: off).
214    pub snap_interval: Points,
215    /// Stops at these offsets.
216    pub snap_offsets: Vec<Points>,
217    /// Which point of a snap page aligns with the viewport.
218    pub snap_alignment: SnapAlignment,
219    /// Velocity kept per millisecond after a fling (0: platform default).
220    pub deceleration: f32,
221    /// The user can scroll it.
222    pub enabled: bool,
223    /// It overscrolls past its edges.
224    pub bounces: bool,
225    /// A tap at the top of the window scrolls it to its top (iOS:
226    /// `UIScrollView.scrollsToTop`).
227    pub scrolls_to_top: bool,
228    /// A mouse wheel's notches glide (`smoothWheel`).
229    pub smooth_wheel: bool,
230    /// Points a mouse wheel's line scrolls; 0 for the platform's own
231    /// (`wheelLineHeight`).
232    pub wheel_line_height: Points,
233    /// Room around the content.
234    pub content_inset: EdgeInsets,
235    /// How far the scroll indicator keeps from each edge of the view: its
236    /// track runs between the top and bottom insets (a horizontal view's:
237    /// left and right), and it moves in from the right (bottom) edge by
238    /// the right (bottom) one. Platforms add the room they keep for the
239    /// keyboard to the bottom.
240    pub scrollbar_inset: EdgeInsets,
241    /// Whether taps dismiss the keyboard.
242    pub keyboard_taps: KeyboardTaps,
243    /// A fling moves one snap point at most (`disableIntervalMomentum`).
244    pub one_step: bool,
245    /// `minimumZoomScale`.
246    pub min_zoom: f32,
247    /// `maximumZoomScale`: pinching zooms the content when above
248    /// `min_zoom` (`<scroll>` only, not lists).
249    pub max_zoom: f32,
250    /// `bouncesZoom`: pinching may go past the limits and springs back.
251    pub bounces_zoom: bool,
252    /// `zoomable`: the user can pinch to zoom.
253    pub pinch: bool,
254    /// `centerContent`: content smaller than the viewport is centered.
255    pub center_content: bool,
256    /// `refreshIndicator`: the height of the app's own pull-to-refresh
257    /// indicator, which replaces the platform's spinner; `None` for the
258    /// platform's.
259    pub refresh_indicator: Option<Points>,
260}
261
262/// How far past the top a released pull refreshes with the platform's
263/// spinner.
264const REFRESH_PULL: Points = Points(64.0);
265/// The room the platform's spinner keeps above the content while
266/// refreshing.
267const REFRESH_SPACE: Points = Points(56.0);
268
269impl Default for ScrollBehavior {
270    fn default() -> Self {
271        Self {
272            paging: false,
273            snap_interval: Points::ZERO,
274            snap_offsets: Vec::new(),
275            snap_alignment: SnapAlignment::Start,
276            deceleration: 0.0,
277            enabled: true,
278            bounces: true,
279            scrolls_to_top: true,
280            smooth_wheel: false,
281            wheel_line_height: Points::ZERO,
282            content_inset: EdgeInsets::default(),
283            scrollbar_inset: EdgeInsets::default(),
284            keyboard_taps: KeyboardTaps::Never,
285            one_step: false,
286            min_zoom: 1.0,
287            max_zoom: 1.0,
288            bounces_zoom: true,
289            pinch: true,
290            center_content: false,
291            refresh_indicator: None,
292        }
293    }
294}
295
296impl ScrollBehavior {
297    /// Whether the content zooms (scrolling both ways while zoomed in).
298    pub fn zooms(&self) -> bool {
299        self.max_zoom > self.min_zoom
300    }
301
302    /// Whether a vertical scroll view dragged to `offset` (negative: pulled
303    /// past its top) refreshes when the finger lifts, if it listens to
304    /// `onRefresh` and is not refreshing yet.
305    pub fn refreshes(&self, offset: Points) -> bool {
306        offset.0 <= -self.refresh_threshold().0
307    }
308
309    /// How far past the top a released pull refreshes: the app's
310    /// indicator's height, or the platform spinner's distance.
311    pub fn refresh_threshold(&self) -> Points {
312        self.refresh_indicator.unwrap_or(REFRESH_PULL)
313    }
314
315    /// The room kept above the content while it refreshes: the app's
316    /// indicator's height, or the platform spinner's.
317    pub fn refresh_inset(&self) -> Points {
318        self.refresh_indicator.unwrap_or(REFRESH_SPACE)
319    }
320
321    /// Whether flings end at snap points.
322    pub fn snaps(&self) -> bool {
323        self.snap_interval.0 > 0.0 || !self.snap_offsets.is_empty()
324    }
325
326    /// The snap point a fling ends at, as in React Native: `offset` is
327    /// where the drag ended, `projected` where the fling would glide to
328    /// (both along the main axis, points) and `velocity` its speed (points
329    /// per millisecond), for a viewport of `viewport` and content of
330    /// `content` points. Pages (and `one_step`) move one snap point; other
331    /// snapping rounds the projected offset in the fling's direction.
332    /// `None` without snapping.
333    pub fn snap_target(
334        &self,
335        offset: Points,
336        projected: Points,
337        velocity: f32,
338        viewport: Points,
339        content: Points,
340    ) -> Option<Points> {
341        let (offset, projected, viewport) = (offset.0, projected.0, viewport.0);
342        let max = (content.0 - viewport).max(0.0);
343        let points: Vec<f32> = if self.snap_interval.0 > 0.0 {
344            let interval = self.snap_interval.0;
345            // Aligns the item at `k * interval` with the viewport.
346            let shift = match self.snap_alignment {
347                SnapAlignment::Start => 0.0,
348                SnapAlignment::Center => (viewport - interval) / 2.0,
349                SnapAlignment::End => viewport - interval,
350            };
351            let n = ((max + shift) / interval).ceil().max(0.0) as usize;
352            (0..=n)
353                .map(|i| (i as f32 * interval - shift).clamp(0.0, max))
354                .collect()
355        } else if !self.snap_offsets.is_empty() {
356            self.snap_offsets
357                .iter()
358                .map(|o| o.0.clamp(0.0, max))
359                .collect()
360        } else if self.paging {
361            let page = viewport.max(1.0);
362            (0..=(max / page).ceil() as usize)
363                .map(|i| (i as f32 * page).min(max))
364                .collect()
365        } else {
366            return None;
367        };
368        // Slower releases (points per ms) settle at the nearest point.
369        const SLOW: f32 = 0.3;
370        let step = self.one_step || (self.paging && !self.snaps());
371        let target = if step {
372            if velocity > SLOW {
373                points.iter().copied().find(|&p| p > offset + 0.5)
374            } else if velocity < -SLOW {
375                points.iter().rev().copied().find(|&p| p < offset - 0.5)
376            } else {
377                nearest(&points, offset)
378            }
379        } else if velocity > SLOW {
380            points.iter().copied().find(|&p| p >= projected - 0.5)
381        } else if velocity < -SLOW {
382            points.iter().rev().copied().find(|&p| p <= projected + 0.5)
383        } else {
384            nearest(&points, projected)
385        };
386        Some(Points(target.unwrap_or(if velocity > 0.0 {
387            max
388        } else {
389            0.0
390        })))
391    }
392}
393
394fn nearest(points: &[f32], to: f32) -> Option<f32> {
395    points
396        .iter()
397        .copied()
398        .min_by(|a, b| (a - to).abs().total_cmp(&(b - to).abs()))
399}
400
401/// A sticky cell that sticks to the start of the viewport (or the list's
402/// sticky offset from it), or, when `end` is before `start`, to its end less
403/// the inset: at scroll offset `offset` (along the main axis) it shows
404/// `offset - start` past where it is laid out, clamped between 0 and
405/// `end - start`, or between `end - start` and 0.
406#[derive(Debug, Clone, Copy, PartialEq, Default)]
407#[non_exhaustive]
408pub struct StickyCell {
409    /// The cell.
410    pub cell: NodeId,
411    /// The scroll offset from which it moves with the scroll: its position
412    /// in the content less the list's sticky offset, or its position plus
413    /// its size and inset less the viewport for an end inset.
414    pub start: Points,
415    /// The scroll offset at which the next sticky cell pushes it out (may be
416    /// infinite), or where its containing block starts for an end inset.
417    pub end: Points,
418    /// An animated value added to the scroll offset: it sticks that much
419    /// further from the viewport's start (below a header that moves), at
420    /// `clamp(offset + value - start, 0, end - start)`. The platforms read
421    /// it from the animation graph whenever they pin, and pin again on the
422    /// graph's frames.
423    pub offset: Option<crate::animation::NodeId>,
424}
425
426/// The header heights a platform without a native header gives the core
427/// ([`crate::Core::set_header_heights`]; the desktops, the web): NSH draws
428/// no header there. A page's `header` slot ([`ScreenConfig::header_view`])
429/// is placed at its top instead, as wide as the page and as tall as it lays
430/// out, and the content starts below it; the native header's options
431/// (`title`, `headerLeft`, `headerStyle`, ...) are ignored.
432pub const NO_NATIVE_HEADER: (Points, Points) = (Points::ZERO, Points::ZERO);
433
434/// Options of a screen: its header and transitions.
435///
436/// The header options are the native header's (iOS, Android); a platform
437/// without one ([`NO_NATIVE_HEADER`]) reads only `header_view`,
438/// `header_height`, `prevent_back`, `gesture_enabled` and `animation`.
439#[derive(Debug, Clone, PartialEq)]
440pub struct ScreenConfig {
441    /// Title in the header.
442    pub title: Option<Arc<str>>,
443    /// Show the native header.
444    pub header_visible: bool,
445    /// Large title (iOS; the content scrolls under the header).
446    pub large_title: bool,
447    /// The content extends under the header.
448    pub header_transparent: bool,
449    /// The hairline under the header (iOS).
450    pub header_shadow_visible: bool,
451    /// Where the title sits (Android; iOS's system bar always centers it and
452    /// ignores this).
453    pub title_align: HeaderTitleAlign,
454    /// A transparent header shows its background once the content scrolls
455    /// under it (iOS).
456    pub header_background_on_scroll: bool,
457    /// The system tab bar leaves while this page is on top.
458    pub hides_bottom_bar_when_pushed: bool,
459    /// Color of the back button and bar buttons.
460    pub tint_color: Option<Color>,
461    /// Header background.
462    pub background_color: Option<Color>,
463    /// Title color.
464    pub title_color: Option<Color>,
465    /// Label of the back button leading back to this screen.
466    pub back_title: Option<Arc<str>>,
467    /// Show the back button.
468    pub back_visible: bool,
469    /// The interactive back gesture (iOS swipe back, Android predictive back
470    /// following the finger) is on; the back button pops either way
471    /// (`popOnSwipe`).
472    pub gesture_enabled: bool,
473    /// The user cannot leave the screen (`popOnBack` false: no swipe, the
474    /// back buttons do not pop): answered by the platform when the system
475    /// asks, without JS. Every back press sends
476    /// [`crate::EventKind::BackRequest`] either way.
477    pub prevent_back: bool,
478    /// Push / pop transition.
479    pub animation: ScreenAnimation,
480    /// Leading header item view.
481    pub left: Option<NodeId>,
482    /// Trailing header item view.
483    pub right: Option<NodeId>,
484    /// UIKit's own bar button in the trailing slot instead of `right`'s
485    /// view (iOS); a press on it presses `right`'s first pressable view.
486    pub right_system_item: Option<crate::HeaderSystemItem>,
487    /// UIKit's own bar button showing this SF Symbol in the trailing slot
488    /// instead of `right`'s view (iOS); `right_system_item` wins over it.
489    pub right_symbol: Option<Arc<str>>,
490    /// As `right_system_item`, in the leading slot, pressing `left`.
491    pub left_system_item: Option<crate::HeaderSystemItem>,
492    /// As `right_symbol`, in the leading slot, pressing `left`.
493    pub left_symbol: Option<Arc<str>>,
494    /// Trailing UIKit bar buttons (`ios={{ headerRightItems }}`); a
495    /// non-empty list wins over `right_system_item` / `right_symbol` and
496    /// leaves `right`'s view out of the iOS bar. Empty is unset.
497    pub right_items: Vec<crate::HeaderItem>,
498    /// As `right_items`, the leading bar buttons (`ios={{ headerLeftItems
499    /// }}`), over `left_system_item` / `left_symbol` and `left`'s view.
500    pub left_items: Vec<crate::HeaderItem>,
501    /// Custom title view.
502    pub title_view: Option<NodeId>,
503    /// The app's header (`header`): on a platform without a native header
504    /// ([`NO_NATIVE_HEADER`]), a view at the top of the screen whose frame
505    /// the core sets (as wide as the screen, as tall as it lays out),
506    /// above the content.
507    pub header_view: Option<NodeId>,
508    /// Height of the header area at the top of the screen, as the core laid
509    /// the content out below it: the native header's (status bar included),
510    /// or the `header` view's without a native header.
511    pub header_height: Points,
512}
513
514impl Default for ScreenConfig {
515    fn default() -> Self {
516        Self {
517            title: None,
518            header_visible: true,
519            large_title: false,
520            header_transparent: false,
521            header_shadow_visible: true,
522            title_align: HeaderTitleAlign::Left,
523            header_background_on_scroll: false,
524            hides_bottom_bar_when_pushed: false,
525            tint_color: None,
526            background_color: None,
527            title_color: None,
528            back_title: None,
529            back_visible: true,
530            gesture_enabled: true,
531            prevent_back: false,
532            animation: ScreenAnimation::Default,
533            left: None,
534            right: None,
535            right_system_item: None,
536            right_symbol: None,
537            left_system_item: None,
538            left_symbol: None,
539            right_items: Vec::new(),
540            left_items: Vec::new(),
541            title_view: None,
542            header_view: None,
543            header_height: Points::ZERO,
544        }
545    }
546}
547
548/// Options of a modal (`Dialog`).
549///
550/// The modal itself has no look: on the desktops and the web it is a
551/// transparent layer over the whole window (no card, scrim, shadow or
552/// background; `presentation` is ignored), and what shows is the app's
553/// popup and backdrop, which the runtime renders inside it.
554#[derive(Debug, Clone, PartialEq)]
555pub struct ModalConfig {
556    /// How it appears.
557    pub animation: ModalAnimation,
558    /// How it covers the screen (iOS).
559    pub presentation: ModalPresentation,
560    /// Android: the content reaches under the status bar.
561    pub status_bar_translucent: bool,
562    /// iOS: the orientations it allows ([`ModalConfig::PORTRAIT`], ...);
563    /// 0 keeps the presenter's.
564    pub orientations: u8,
565    /// Escape and the Android back button close it natively
566    /// (`closeOnEscape`); either way they report
567    /// [`crate::EventKind::RequestClose`] (reason `"cancel"`), and
568    /// [`crate::EventKind::Dismiss`] after closing.
569    pub close_on_escape: bool,
570    /// A press on the backdrop closes it (`closeOnBackdropPress`): the
571    /// runtime handles presses on the app's backdrop part; a platform
572    /// reads it only for a backdrop of its own (a native sheet's).
573    pub close_on_backdrop_press: bool,
574    /// Swiping a sheet down closes it natively (`closeOnSwipe`).
575    pub close_on_swipe: bool,
576    /// The window it shows in (desktops): [`crate::ROOT_ID`], the main
577    /// window, or the root of the app's window of its own that holds it
578    /// (a dialog opened from a `<Window>`'s content shows over that
579    /// window, not the main one). For a window's own root: the window
580    /// holding its node. The core works it out from where the node is.
581    pub window: NodeId,
582    /// iOS sheets: the heights it rests at (`detents`); empty for the
583    /// system's full height.
584    pub detents: Vec<crate::SheetDetent>,
585    /// iOS sheets: the detent the app keeps it at (`detent`); applied when
586    /// it changes.
587    pub detent: Option<crate::SheetDetent>,
588    /// iOS sheets: the detent it opens at without [`Self::detent`]
589    /// (`defaultDetent`); `None` for the smallest.
590    pub default_detent: Option<crate::SheetDetent>,
591    /// iOS sheets: the system's grabber shows (`grabber`).
592    pub grabber: bool,
593    /// iOS sheets: up to this detent what is behind is not dimmed and
594    /// takes touches (`largestUndimmedDetent`).
595    pub largest_undimmed_detent: Option<crate::SheetDetent>,
596}
597
598impl Default for ModalConfig {
599    fn default() -> Self {
600        Self {
601            animation: ModalAnimation::default(),
602            presentation: ModalPresentation::default(),
603            status_bar_translucent: false,
604            orientations: 0,
605            close_on_escape: true,
606            close_on_backdrop_press: true,
607            close_on_swipe: true,
608            window: crate::ROOT_ID,
609            detents: Vec::new(),
610            detent: None,
611            default_detent: None,
612            grabber: false,
613            largest_undimmed_detent: None,
614        }
615    }
616}
617
618impl ModalConfig {
619    /// `portrait`.
620    pub const PORTRAIT: u8 = 1;
621    /// `portrait-upside-down`.
622    pub const PORTRAIT_UPSIDE_DOWN: u8 = 2;
623    /// `landscape-left`.
624    pub const LANDSCAPE_LEFT: u8 = 4;
625    /// `landscape-right`.
626    pub const LANDSCAPE_RIGHT: u8 = 8;
627}
628
629/// Everything about a text input except its text.
630#[derive(Debug, Clone, PartialEq)]
631pub struct InputConfig {
632    /// Font and color of the text.
633    pub style: ResolvedTextStyle,
634    /// Alignment of the text.
635    pub align: TextAlign,
636    /// Shown while the text is empty.
637    pub placeholder: String,
638    /// Placeholder color; the platform's default when `None`.
639    pub placeholder_color: Option<Color>,
640    /// Hide the characters (passwords).
641    pub secure: bool,
642    /// Keyboard layout.
643    pub keyboard: KeyboardType,
644    /// The keyboard's look (iOS).
645    pub keyboard_appearance: KeyboardAppearance,
646    /// Label of the return key.
647    pub return_key: ReturnKeyType,
648    /// Automatic capitalization.
649    pub auto_capitalize: AutoCapitalize,
650    /// The system's corrections: spelling, smart quotes and dashes, text
651    /// replacement.
652    pub auto_correct: bool,
653    /// Several lines (return inserts a line break).
654    pub multiline: bool,
655    /// The most characters the user's edits leave (`maxLength`), counted
656    /// as Unicode scalar values ([`crate::text_edit::char_len`]); an
657    /// insertion is cut by [`crate::text_edit::clip_chars`].
658    pub max_length: Option<u32>,
659    /// The user can edit the text.
660    pub editable: bool,
661    /// Return unfocuses a single-line input without a `submitBehavior`
662    /// (always true from TS); [`InputConfig::submit`] resolves it.
663    pub blur_on_submit: bool,
664    /// `submitBehavior` as set; [`InputConfig::submit`] resolves it.
665    pub submit_behavior: Option<SubmitBehavior>,
666    /// What a paste does (`pasteBehavior`).
667    pub paste_behavior: PasteBehavior,
668    /// The largest pasted file read, in bytes (`pasteMaxSize`): a larger
669    /// one goes to [`crate::PasteEvent::too_large`] unread. `None`: all.
670    pub paste_max_size: Option<u64>,
671    /// Focus once on screen.
672    pub auto_focus: bool,
673    /// Select the whole text when the input takes the focus
674    /// (`selectTextOnFocus`).
675    pub select_text_on_focus: bool,
676    /// Selection highlight color (on iOS also the caret's, unless
677    /// [`InputConfig::caret_color`] is set: UIKit tints both with one).
678    pub selection_color: Option<Color>,
679    /// Caret color; the platform's default when `None`.
680    pub caret_color: Option<Color>,
681    /// What the input holds, for autofill.
682    pub auto_fill: crate::ops::AutoFill,
683    /// The text runs right to left.
684    pub rtl: bool,
685    /// No caret is drawn (`caret={false}`).
686    pub caret_hidden: bool,
687    /// `inputAccessoryViewID` as set.
688    pub accessory_id: Option<Box<str>>,
689    /// The input accessory it names, if one is mounted.
690    pub accessory: Option<NodeId>,
691    /// A multiline input shows its scroll indicator (`scrollbar`; false
692    /// while a built-in bar takes its place).
693    pub scrollbar_visible: bool,
694    /// A bar of the app's follows a multiline input's text (its built-in
695    /// bar, or one the app placed that watches it, `watch_scroll`): the
696    /// platform reports how far the text scrolled
697    /// (`EngineControl::input_scroll`). Off, it reports nothing.
698    pub report_scroll: bool,
699}
700
701impl InputConfig {
702    /// What return does, as `submitBehavior` and `multiline` say
703    /// together: the set behavior (a single line never takes line breaks),
704    /// else a line break in a multiline input, else a submit that
705    /// unfocuses unless [`InputConfig::blur_on_submit`] is false (Rust).
706    pub fn submit(&self) -> SubmitBehavior {
707        match self.submit_behavior {
708            Some(SubmitBehavior::Newline) if !self.multiline => SubmitBehavior::BlurAndSubmit,
709            Some(behavior) => behavior,
710            None if self.multiline => SubmitBehavior::Newline,
711            None if self.blur_on_submit => SubmitBehavior::BlurAndSubmit,
712            None => SubmitBehavior::Submit,
713        }
714    }
715
716    /// A password shown as plain text: the input holds a password
717    /// ([`InputConfig::auto_fill`] `current-password` or `new-password`)
718    /// but is not `secure`, as after a "show password" toggle. Platforms
719    /// type it as it is: Android's visible password keyboard, iOS's ASCII
720    /// keyboard, never capitalized, suggested or corrected.
721    pub fn visible_password(&self) -> bool {
722        !self.secure
723            && matches!(
724                self.auto_fill,
725                crate::ops::AutoFill::Password | crate::ops::AutoFill::NewPassword
726            )
727    }
728}
729
730impl Default for InputConfig {
731    fn default() -> Self {
732        Self {
733            style: ResolvedTextStyle::default(),
734            align: TextAlign::Auto,
735            placeholder: String::new(),
736            placeholder_color: None,
737            secure: false,
738            keyboard: KeyboardType::Default,
739            keyboard_appearance: KeyboardAppearance::Default,
740            return_key: ReturnKeyType::Default,
741            auto_capitalize: AutoCapitalize::Sentences,
742            auto_correct: true,
743            multiline: false,
744            max_length: None,
745            editable: true,
746            blur_on_submit: true,
747            submit_behavior: None,
748            paste_behavior: PasteBehavior::Insert,
749            paste_max_size: None,
750            auto_focus: false,
751            select_text_on_focus: false,
752            selection_color: None,
753            caret_color: None,
754            auto_fill: crate::ops::AutoFill::Default,
755            rtl: false,
756            caret_hidden: false,
757            accessory_id: None,
758            accessory: None,
759            scrollbar_visible: true,
760            report_scroll: false,
761        }
762    }
763}
764
765/// How an image is shown, besides its source.
766#[derive(Debug, Clone, PartialEq, Default)]
767pub struct ImageOptions {
768    /// `placeholder`: shown until the image loads (and if it fails).
769    pub placeholder: Option<ImageSource>,
770    /// `blurRadius` in points (0: sharp).
771    pub blur_radius: Points,
772    /// `fadeDuration` in milliseconds; the platform's default when `None`
773    /// (React Native: 300 on Android, none on iOS).
774    pub fade_ms: Option<f32>,
775    /// `objectPosition`: where the image sits in its box once the resize
776    /// mode has sized it ([`crate::ResizeMode::fit`]).
777    pub position: crate::style::ObjectPosition,
778    /// The color an SVG source's `currentColor` paints with: the element's
779    /// text color, for an `svg()` the platform draws as an image (the web
780    /// runtime); `None` for an image, whose `currentColor` stays the SVG's.
781    pub current_color: Option<crate::style::Color>,
782}
783
784/// One instruction for the platform backend.
785///
786/// Items must be applied in order: [`MountItem::Insert`] refers to views
787/// created by the preceding items.
788#[derive(Debug, Clone)]
789pub enum MountItem {
790    /// Mounted nodes in depth-first logical tree order, independent of native
791    /// stacking (`Insert`); a list's cells, which it recycles, in the order
792    /// they are on screen. Opt-in through `Core::set_tree_order_tracking`;
793    /// emitted after structural changes and when a list's cells move, in the
794    /// same batch as the affected views.
795    TreeOrder(Vec<NodeId>),
796    /// Create a native view. It starts detached and invisible.
797    Create {
798        /// Node id, used to address the view in later items.
799        id: NodeId,
800        /// View kind.
801        kind: ViewKind,
802    },
803    /// Report the view's interaction states named by these bits
804    /// (`tailwind::state`: pressed, hovered, focused, focus within) with
805    /// `EngineControl::set_states`; 0 stops reporting. The states no
806    /// longer tracked are forgotten on both sides (the core and the
807    /// platform keep `states & tracked`), so the two never disagree about
808    /// a state the platform stopped reporting.
809    TrackStates {
810        /// View id.
811        id: NodeId,
812        /// The states.
813        states: u16,
814    },
815    /// The states the view shows as a part of a control (`tailwind::state`
816    /// bits: a list's highlighted option is focused while the focus stays
817    /// on its search field), for a platform that marks them itself. Opt-in
818    /// through `Core::set_projected_state_mounting`; the platform shows
819    /// them and never reports them back.
820    ProjectStates {
821        /// View id.
822        id: NodeId,
823        /// The states.
824        states: u16,
825    },
826    /// Insert (or move) `child` into `parent`, below sibling `before` (or
827    /// on top when `None`). Siblings rather than indices, so platform-owned
828    /// subviews (refresh controls, scroll indicators) cannot shift positions.
829    Insert {
830        /// Parent view.
831        parent: NodeId,
832        /// Child view.
833        child: NodeId,
834        /// The app sibling to insert below.
835        before: Option<NodeId>,
836    },
837    /// Remove a view from its superview, keeping it alive.
838    Remove {
839        /// View to detach.
840        id: NodeId,
841    },
842    /// Destroy a view.
843    Delete {
844        /// View to destroy.
845        id: NodeId,
846    },
847    /// Set the frame of a view, relative to its superview.
848    Frame {
849        /// View.
850        id: NodeId,
851        /// New frame.
852        frame: Bounds<Points>,
853    },
854    /// The area the view's descendants cover outside its bounds, in its
855    /// own coordinates (it contains the bounds), while overflow is visible;
856    /// `None` when they stay inside. It takes in the descendants' hit
857    /// slop. UIKit and Android only look for the target of a touch inside a
858    /// view's bounds: platforms look in the descendants of views with an
859    /// area too, so children placed outside their parent (a dropdown under
860    /// its field) and the slop reaching out of it can be touched. Sent only
861    /// when it changes; from layout frames and hit slop (transforms are not
862    /// included).
863    Overflow {
864        /// View.
865        id: NodeId,
866        /// The area, or `None`.
867        extent: Option<Bounds<Points>>,
868    },
869    /// Set the visual style of a view.
870    ViewStyle {
871        /// View.
872        id: NodeId,
873        /// New style.
874        style: Box<ViewStyle>,
875    },
876    /// Set the content of a text view.
877    Text {
878        /// Text view.
879        id: NodeId,
880        /// Content (for accessibility and debugging); shared, never copied.
881        text: Arc<AttributedText>,
882        /// The final layout, ready to draw.
883        layout: TextLayout,
884        /// Where `layout` goes inside the view (inside padding and border).
885        content: Bounds<Points>,
886    },
887    /// Set which events the view must report.
888    Events {
889        /// View.
890        id: NodeId,
891        /// Event set.
892        events: EventMask,
893    },
894    /// Set the source of an image view.
895    Image {
896        /// Image view.
897        id: NodeId,
898        /// Source; `None` clears the image.
899        source: Option<ImageSource>,
900        /// Fit mode.
901        resize_mode: ResizeMode,
902        /// How it is shown: placeholder, blur, fade.
903        options: ImageOptions,
904    },
905    /// Configure a scroll view.
906    ScrollConfig {
907        /// Scroll view.
908        id: NodeId,
909        /// Scrolls horizontally.
910        horizontal: bool,
911        /// Shows the scroll indicator.
912        scrollbar_visible: bool,
913        /// A built-in bar of the app's takes the indicator's place (the
914        /// core's, over the viewport): the platform shows none on either
915        /// axis.
916        replaced: bool,
917        /// Native animation value fed with the main-axis offset.
918        scroll_value: Option<crate::animation::NodeId>,
919        /// Native animation value fed with how far it is pulled past its
920        /// top (vertical views).
921        pull_value: Option<crate::animation::NodeId>,
922        /// When dragging dismisses the keyboard.
923        keyboard_dismiss: KeyboardDismissMode,
924        /// A horizontal list laid out right to left: the platform mirrors
925        /// the scroll view and each of its cells (so the list's offsets
926        /// stay left to right).
927        mirrored: bool,
928    },
929    /// Set the scrollable content size.
930    ScrollContent {
931        /// Scroll view.
932        id: NodeId,
933        /// Content size.
934        size: Size<Points>,
935    },
936    /// Shift the scroll position, keeping visible content in place when
937    /// items above the viewport change size.
938    ScrollBy {
939        /// Scroll view.
940        id: NodeId,
941        /// Horizontal shift.
942        dx: Points,
943        /// Vertical shift.
944        dy: Points,
945    },
946    /// The surface lays out right to left (or no longer): native controls
947    /// mirror.
948    LayoutDirection {
949        /// Right to left.
950        rtl: bool,
951    },
952    /// The app's appearance changed ([`crate::Core::set_appearance`]):
953    /// native controls (alerts, the status bar's default style, system
954    /// views) show it instead of the system's.
955    Appearance {
956        /// What the app asks for.
957        appearance: crate::platform::Appearance,
958    },
959    /// The surface's keyboard shortcuts (replaces the previous table;
960    /// empty: none). The platform matches every key it gets against it on
961    /// the spot ([`crate::keymap::Keymap::find`]), consumes the keys that
962    /// fire a binding and reports them with
963    /// [`crate::EventKind::KeyCommand`] on the root.
964    Keymap(std::sync::Arc<crate::keymap::Keymap>),
965    /// The sticky cells of a list (replaces the previous set): each one
966    /// is translated along the main axis by `clamp(offset - start, 0,
967    /// end - start)` on every scroll, natively. The set is in the order
968    /// the cells stack, bottom to top (a built-in scroll bar last).
969    StickyCells {
970        /// The list.
971        id: NodeId,
972        /// Cells and their travel.
973        cells: Vec<StickyCell>,
974    },
975    /// Set how a scroll view or list scrolls.
976    ScrollBehavior {
977        /// Scroll view.
978        id: NodeId,
979        /// The behavior.
980        behavior: Box<ScrollBehavior>,
981    },
982    /// Show or hide the pull-to-refresh spinner.
983    Refreshing {
984        /// Scroll view.
985        id: NodeId,
986        /// Spinner state.
987        refreshing: bool,
988    },
989    /// What a canvas draws; its animated values come as
990    /// [`crate::animation::AnimationProp::CanvasArg`] bindings.
991    Canvas {
992        /// The canvas.
993        id: NodeId,
994        /// The drawing.
995        drawing: Arc<crate::canvas::Drawing>,
996    },
997    /// What a shader view draws under its children (`None`: nothing); the
998    /// animated values among its uniforms come as
999    /// [`crate::animation::AnimationProp::CanvasArg`] bindings of its
1000    /// [`crate::shader::ShaderLayer::slots`].
1001    Shader {
1002        /// The view.
1003        id: NodeId,
1004        /// The program and its uniforms.
1005        layer: Option<Arc<crate::shader::ShaderLayer>>,
1006    },
1007    /// The renderer of a GPU view (`None`: none, or a name no UI set
1008    /// registered: it draws nothing), sent after its `Create` and when it
1009    /// changes. Its own props come as [`MountItem::ComponentProps`] and
1010    /// [`MountItem::ComponentPropSlots`], as a native component's
1011    /// ([`crate::gpu`]).
1012    GpuView {
1013        /// The view.
1014        id: NodeId,
1015        /// What makes its renderer.
1016        source: Option<crate::gpu::GpuSource>,
1017    },
1018    /// A shader transition starts: its `value` changed. It comes first in
1019    /// its batch, so the platform takes the picture of what the view (the
1020    /// surface, for a screen transition) shows before the batch's other
1021    /// items, `sample_from`, and runs the layer's `nsh.progress` from 0 to
1022    /// 1 over `duration`, what it draws from then on as `sample_to`; once
1023    /// it ends the children show as they are.
1024    ShaderTransition {
1025        /// The transition.
1026        id: NodeId,
1027        /// How long it runs.
1028        duration: std::time::Duration,
1029    },
1030    /// The shader a page or a dialog comes and goes through
1031    /// (`transitionShader`; `None`: its `animation`): when it is pushed,
1032    /// popped, presented or dismissed, the platform draws the change through
1033    /// the layer for `duration`, the lower side's picture as `sample_from`
1034    /// and the upper's as `sample_to`, whatever the page's `animation`; its
1035    /// `animation` runs where it cannot and when the user asks for less
1036    /// motion, and a change that starts while one runs ends that one first
1037    /// (`docs/dev/shaders.md` "Pages and dialogs").
1038    NavShader {
1039        /// The page or dialog.
1040        id: NodeId,
1041        /// The layer (role [`crate::shader::ShaderRole::Transition`]) and
1042        /// how long it runs.
1043        shader: Option<NavShader>,
1044    },
1045    /// What a shader's pictures show changed, as far as the core knows: a
1046    /// view in an effect's or a transition's subtree was in the batch, or
1047    /// anything for a shader that reads what is behind it and for a screen
1048    /// effect or transition. The platform takes them again; what changes
1049    /// on its UI thread (animations, scrolling, loads) it notices itself.
1050    ShaderInput {
1051        /// The shader's view.
1052        id: NodeId,
1053    },
1054    /// Bind visual properties to native animation nodes.
1055    AnimationBindings {
1056        /// View.
1057        id: NodeId,
1058        /// Property bindings (replaces the previous set).
1059        bindings: Vec<(AnimationProp, crate::animation::NodeId)>,
1060    },
1061    /// Drive native animation values from gestures on the view.
1062    Gestures {
1063        /// View.
1064        id: NodeId,
1065        /// The driven values.
1066        values: GestureValues,
1067    },
1068    /// Set touch, accessibility and test properties.
1069    ViewProps {
1070        /// View.
1071        id: NodeId,
1072        /// The properties (replace the previous ones).
1073        props: Box<ViewProps>,
1074    },
1075    /// Change the accessibility label of a view whose [`ViewProps`] were
1076    /// mounted before, and nothing else: a label following app state
1077    /// changes alone, so the rest is not sent again.
1078    AccessibilityLabel {
1079        /// View.
1080        id: NodeId,
1081        /// `accessibilityLabel` (`None`: none).
1082        label: Option<Arc<str>>,
1083    },
1084    /// Animate the frame changes, insertions and removals that follow in
1085    /// this batch, until the next one replaces it: a batch may lead runs
1086    /// of frames with different ones, an empty one for frames that do not
1087    /// animate (`core/layout_scope.rs`). Platforms animate each frame with
1088    /// the one before it.
1089    LayoutAnimation(LayoutAnimation),
1090    /// An animation graph change, in order with the other items.
1091    Animation(AnimationOp),
1092    /// Configure a text input.
1093    Input {
1094        /// Input view.
1095        id: NodeId,
1096        /// The configuration; boxed because it is large.
1097        config: Box<InputConfig>,
1098    },
1099    /// Set the text of an input (from JS).
1100    InputValue {
1101        /// Input view.
1102        id: NodeId,
1103        /// The text.
1104        text: String,
1105        /// The input's edit count this value is based on: the platform drops
1106        /// it if the user typed since (see [`crate::EventPayload::Text`]).
1107        count: u32,
1108    },
1109    /// Where the text of an input goes (inside padding and border).
1110    InputContent {
1111        /// Input view.
1112        id: NodeId,
1113        /// Content box relative to the view.
1114        content: Bounds<Points>,
1115    },
1116    /// Configure a screen (sent before the screen is inserted into its
1117    /// stack, and on every change).
1118    ScreenConfig {
1119        /// Screen.
1120        id: NodeId,
1121        /// The options.
1122        config: Box<ScreenConfig>,
1123    },
1124    /// Configure a native control (web view, video).
1125    NativeProps {
1126        /// The control.
1127        id: NodeId,
1128        /// All its properties.
1129        props: NativeProps,
1130    },
1131    /// Configure a modal (sent before it is presented, and on changes).
1132    ModalConfig {
1133        /// Modal root view.
1134        id: NodeId,
1135        /// The options.
1136        config: ModalConfig,
1137    },
1138    /// Create the registered component `name` in a [`ViewKind::Native`]
1139    /// container (right after its `Create`). Unknown names leave the
1140    /// container empty.
1141    Component {
1142        /// The container.
1143        id: NodeId,
1144        /// The name it was registered by (`com.example.map`).
1145        name: Arc<str>,
1146    },
1147    /// The names of a registered native component's animated prop slots:
1148    /// `names[n]` is [`AnimationProp::ComponentSlot`]`(n)`. Sent before the
1149    /// [`MountItem::AnimationBindings`] that use new slots; slots keep their
1150    /// name for the component's life.
1151    ComponentPropSlots {
1152        /// The container.
1153        id: NodeId,
1154        /// The name of each slot.
1155        names: Vec<Arc<str>>,
1156    },
1157    /// Properties of a registered native component that changed (all of
1158    /// them after [`MountItem::Component`]); `None` removes one.
1159    ComponentProps {
1160        /// The container.
1161        id: NodeId,
1162        /// Name and value.
1163        props: Vec<(Arc<str>, Option<crate::JsonValue>)>,
1164    },
1165    /// An imperative call (`focus()`, `scrollTo()`...).
1166    Command {
1167        /// View; [`crate::ROOT_ID`] for surface-wide calls.
1168        id: NodeId,
1169        /// The call.
1170        command: Command,
1171    },
1172}
1173
1174impl MountItem {
1175    /// The view the item changes (a parent for its children's insertions),
1176    /// if it is about one: what [`MountItem::ShaderInput`] is derived from.
1177    pub fn view(&self) -> Option<NodeId> {
1178        use MountItem as M;
1179        match self {
1180            M::Create { id, .. }
1181            | M::TrackStates { id, .. }
1182            | M::Remove { id }
1183            | M::Delete { id }
1184            | M::Frame { id, .. }
1185            | M::Overflow { id, .. }
1186            | M::ViewStyle { id, .. }
1187            | M::Text { id, .. }
1188            | M::Image { id, .. }
1189            | M::ScrollContent { id, .. }
1190            | M::Canvas { id, .. }
1191            | M::Shader { id, .. }
1192            | M::GpuView { id, .. }
1193            | M::ViewProps { id, .. }
1194            | M::Input { id, .. }
1195            | M::InputValue { id, .. }
1196            | M::NativeProps { id, .. }
1197            | M::Component { id, .. }
1198            | M::ComponentProps { id, .. } => Some(*id),
1199            M::Insert { parent, .. } => Some(*parent),
1200            _ => None,
1201        }
1202    }
1203}
1204
1205/// A page's or a dialog's transition through a shader
1206/// ([`MountItem::NavShader`]). It has no `Default`: a layer holds a
1207/// compiled program, which has none; [`NavShader::new`] makes one.
1208#[derive(Debug, Clone, PartialEq)]
1209#[non_exhaustive]
1210pub struct NavShader {
1211    /// The program and its uniforms.
1212    pub layer: Arc<crate::shader::ShaderLayer>,
1213    /// How long it runs.
1214    pub duration: std::time::Duration,
1215}
1216
1217impl NavShader {
1218    /// `layer` running for `duration`.
1219    pub fn new(layer: Arc<crate::shader::ShaderLayer>, duration: std::time::Duration) -> Self {
1220        Self { layer, duration }
1221    }
1222}
1223
1224/// All mount items produced by one commit.
1225#[derive(Debug, Default)]
1226pub struct MountBatch {
1227    /// Items, to be applied in order within one UI frame.
1228    pub items: Vec<MountItem>,
1229}
1230
1231#[cfg(test)]
1232mod tests {
1233    use super::*;
1234    use crate::geometry::px;
1235
1236    #[test]
1237    fn snap_targets() {
1238        let paging = ScrollBehavior {
1239            paging: true,
1240            ..Default::default()
1241        };
1242        // Pages of 300 in 1000 points of content (the last page is short):
1243        // one page per fling, wherever the fling would glide.
1244        assert_eq!(
1245            paging.snap_target(px(100.0), px(100.0), 0.0, px(300.0), px(1000.0)),
1246            Some(px(0.0))
1247        );
1248        assert_eq!(
1249            paging.snap_target(px(100.0), px(900.0), 1.0, px(300.0), px(1000.0)),
1250            Some(px(300.0))
1251        );
1252        assert_eq!(
1253            paging.snap_target(px(650.0), px(900.0), 1.0, px(300.0), px(1000.0)),
1254            Some(px(700.0))
1255        );
1256        assert_eq!(
1257            paging.snap_target(px(250.0), px(0.0), -1.0, px(300.0), px(1000.0)),
1258            Some(px(0.0))
1259        );
1260        let interval = ScrollBehavior {
1261            snap_interval: px(120.0),
1262            snap_alignment: SnapAlignment::Center,
1263            ..Default::default()
1264        };
1265        // Items of 120 centered in a 300 viewport: k * 120 - 90.
1266        assert_eq!(
1267            interval.snap_target(px(200.0), px(200.0), 0.0, px(300.0), px(2000.0)),
1268            Some(px(150.0))
1269        );
1270        // A fast fling glides past several items, rounded forward.
1271        assert_eq!(
1272            interval.snap_target(px(200.0), px(700.0), 2.0, px(300.0), px(2000.0)),
1273            Some(px(750.0))
1274        );
1275        let one = ScrollBehavior {
1276            one_step: true,
1277            ..interval.clone()
1278        };
1279        assert_eq!(
1280            one.snap_target(px(200.0), px(700.0), 2.0, px(300.0), px(2000.0)),
1281            Some(px(270.0))
1282        );
1283        let offsets = ScrollBehavior {
1284            snap_offsets: vec![px(0.0), px(500.0), px(900.0)],
1285            ..Default::default()
1286        };
1287        assert_eq!(
1288            offsets.snap_target(px(520.0), px(600.0), 2.0, px(300.0), px(2000.0)),
1289            Some(px(900.0))
1290        );
1291        assert_eq!(
1292            offsets.snap_target(px(520.0), px(520.0), 0.0, px(300.0), px(2000.0)),
1293            Some(px(500.0))
1294        );
1295        assert_eq!(
1296            ScrollBehavior::default().snap_target(px(10.0), px(10.0), 1.0, px(300.0), px(2000.0)),
1297            None
1298        );
1299    }
1300}