nsh_core/ops.rs
1use std::sync::Arc;
2
3use crate::{
4 animation::AnimationOp,
5 element::PropEnum,
6 geometry::{Bounds, DevicePixels, Percentage, Point, Points, Size},
7 js::host::HostProps,
8 overlay::{Align, OverlayAnchor, Placement, TooltipContent},
9 props::{AccessibilityProp, EdgeInsets, LayoutAnimation, PanEdge, PointerEvents},
10 style::{Color, Style, StylePatch},
11};
12
13/// Identifier of a node, assigned by the JS renderer.
14///
15/// Ids are small, dense and increasing, so the core indexes them directly.
16pub type NodeId = u32;
17
18/// Id of the surface root view. It exists before any JS runs.
19pub const ROOT_ID: NodeId = 1;
20
21/// Element tag of a host node.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum Tag {
24 /// A container view (`<view>`).
25 View,
26 /// A text block, or a span when nested in another text (`<text>`).
27 Text,
28 /// An image (`<image>`).
29 Image,
30 /// A scrolling container (`<scroll>`).
31 Scroll,
32 /// A virtualized list (`<list>`, created by the runtime's `List`).
33 List,
34 /// A recycled list cell (created by the runtime's `List`).
35 Cell,
36 /// A text field, or a text area when `multiline` (`<input>`).
37 Input,
38 /// A native navigation stack (`<stack>`); its children are screens.
39 Stack,
40 /// One screen of a stack (`<screen>`), laid out at the stack's size.
41 Screen,
42 /// A modal presented over everything (`<modal>`), laid out at the size
43 /// the platform presents it at.
44 Modal,
45 /// A view placed in a screen's native header (`<headeritem slot>`),
46 /// sized to its content.
47 HeaderItem,
48 /// A bar over the keyboard of the inputs naming its `nativeID`
49 /// (`<inputaccessory>`, iOS), as wide as the window and as tall as its
50 /// content.
51 InputAccessory,
52 /// A 2D drawing (`<canvas>`, filled by [`Op::Draw`]).
53 Canvas,
54 /// A web page (`<webview>`).
55 WebView,
56 /// A video player (`<video>`).
57 Video,
58 /// A component the embedding app registered (`<native component>`,
59 /// created by `nsh/native`'s `nativeComponent`).
60 Native,
61 /// A view shown on top of the root view it is in (`<overlay>`, TS:
62 /// `Overlay` of `nsh`), outside its parent's layout and clipping, laid
63 /// out on its own and placed by the core ([`crate::overlay`]).
64 Overlay,
65 /// A view whose box a shader draws, under its children (`<shader>`,
66 /// TS: `Shader` of `nsh`; [`crate::shader`]).
67 Shader,
68 /// A view whose children draw through a shader (`<shadereffect>`, TS:
69 /// `ShaderEffect` of `nsh`): what they draw is its `sample_content`.
70 ShaderEffect,
71 /// A view whose children change through a shader (`<shadertransition>`,
72 /// TS: `ShaderTransition` of `nsh`): when its `value` changes, a picture
73 /// of what they drew is its `sample_from`, what they draw its
74 /// `sample_to`.
75 ShaderTransition,
76 /// The whole surface drawn through a shader (`<screeneffect>`, TS:
77 /// `ScreenEffect` of `nsh`): what the surface draws is its
78 /// `sample_content`. It takes no space and has no children.
79 ScreenEffect,
80 /// The whole surface changing through a shader (`<screentransition>`,
81 /// TS: `ScreenTransition` of `nsh`), as a transition does for its
82 /// children. It takes no space and has no children.
83 ScreenTransition,
84 /// A view whose box a renderer of the app's own draws with the GPU,
85 /// under its children (`<gpuview>`, TS: `gpuView` of `nsh`;
86 /// [`crate::gpu`]).
87 GpuView,
88}
89
90impl Tag {
91 /// Parses a host element's name (what `nsh:rt`'s `element` takes).
92 #[inline]
93 pub fn from_name(name: &str) -> Option<Tag> {
94 Some(match name {
95 "view" => Tag::View,
96 "text" => Tag::Text,
97 "image" => Tag::Image,
98 "scroll" => Tag::Scroll,
99 "list" => Tag::List,
100 "cell" => Tag::Cell,
101 "input" => Tag::Input,
102 "stack" => Tag::Stack,
103 "screen" => Tag::Screen,
104 "modal" => Tag::Modal,
105 "headeritem" => Tag::HeaderItem,
106 "inputaccessory" => Tag::InputAccessory,
107 "canvas" => Tag::Canvas,
108 "webview" => Tag::WebView,
109 "video" => Tag::Video,
110 "native" => Tag::Native,
111 "overlay" => Tag::Overlay,
112 "shader" => Tag::Shader,
113 "shadereffect" => Tag::ShaderEffect,
114 "shadertransition" => Tag::ShaderTransition,
115 "screeneffect" => Tag::ScreenEffect,
116 "screentransition" => Tag::ScreenTransition,
117 "gpuview" => Tag::GpuView,
118 _ => return None,
119 })
120 }
121}
122
123macro_rules! events {
124 ($($variant:ident = $prop:literal $(as $js:literal)?: $doc:literal,)*) => {
125 /// An event a node can listen to.
126 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
127 #[repr(u8)]
128 pub enum EventKind {
129 $(#[doc = $doc] $variant,)*
130 }
131
132 impl EventKind {
133 /// Every kind, in discriminant order (`ALL[k as usize] == k`).
134 pub const ALL: &'static [EventKind] = &[$(EventKind::$variant,)*];
135
136 /// Parses an event's protocol name such as `onPress` (what
137 /// platforms send and log; [`EventKind::prop_name`]).
138 #[inline]
139 pub fn from_prop(name: &str) -> Option<EventKind> {
140 match name {
141 $($prop => Some(EventKind::$variant),)*
142 _ => None,
143 }
144 }
145
146 /// The protocol name of this event (platforms send and log it;
147 /// apps name handlers with [`EventKind::handler_name`]).
148 #[inline]
149 pub const fn prop_name(self) -> &'static str {
150 match self {
151 $(EventKind::$variant => $prop,)*
152 }
153 }
154
155 /// The handler prop apps set for this event (`onChange` for
156 /// [`EventKind::ChangeText`]); empty for the events only the
157 /// runtime listens to (a dialog's dismissal, the root's back
158 /// button), which no prop name sets.
159 #[inline]
160 pub const fn handler_name(self) -> &'static str {
161 match self {
162 $(EventKind::$variant => events!(@js $prop $($js)?),)*
163 }
164 }
165
166 /// Parses a handler prop name such as `onPress`
167 /// ([`EventKind::handler_name`]).
168 #[inline]
169 pub fn from_handler(name: &str) -> Option<EventKind> {
170 if name.is_empty() {
171 return None;
172 }
173 #[allow(unreachable_patterns)]
174 match name {
175 $(events!(@js $prop $($js)?) => Some(EventKind::$variant),)*
176 _ => None,
177 }
178 }
179 }
180 };
181 (@js $prop:literal) => { $prop };
182 (@js $prop:literal $js:literal) => { $js };
183}
184
185// The order is part of the platform protocols (`encode.rs`, `Native.java`):
186// append new kinds at the end.
187events! {
188 Press = "onPress": "A tap / click (payload: [`EventPayload::Press`] where the backend knows the pointer, else none).",
189 LongPress = "onLongPress": "A press held for about half a second (payload as `Press`).",
190 PanStart = "onPanStart": "A drag started (payload: [`EventPayload::Pan`]).",
191 PanEnd = "onPanEnd": "A drag ended (payload: [`EventPayload::Pan`] with velocity).",
192 Refresh = "onRefresh": "Pull-to-refresh was triggered on a scroll or list.",
193 LoadMore = "onLoadMore": "A list was scrolled close to its end.",
194 ScrollEnd = "onScrollEnd": "Scrolling came to rest (payload: [`EventPayload::Scroll`]).",
195 Load = "onLoad": "An image loaded (payload: [`EventPayload::Image`]).",
196 Error = "onError": "An image failed to load (payload: [`EventPayload::Error`]).",
197 ChangeText = "onChangeText" as "onChange": "The user edited an input (payload: [`EventPayload::Text`]).",
198 SubmitEditing = "onSubmitEditing" as "onSubmit": "The return key was pressed in an input (payload: [`EventPayload::Text`]).",
199 Focus = "onFocus": "An input, or a view that takes presses, took the keyboard focus.",
200 Blur = "onBlur": "An input, or a view that takes presses, lost the keyboard focus.",
201 PressDown = "onPressIn" as "onPressDown": "A press went down on a pressable view (a finger, a pen or a mouse button; payload as `Press`).",
202 PressUp = "onPressOut" as "onPressUp": "The press ended: released, moved away or cancelled (payload as `Press`).",
203 Layout = "onLayout": "The frame changed (payload: [`EventPayload::Layout`], relative to the parent).",
204 PinchStart = "onPinchStart": "A pinch started (payload: `scale`, `velocity`).",
205 PinchEnd = "onPinchEnd": "A pinch ended (payload: `scale`, `velocity`).",
206 RotationStart = "onRotationStart": "A two-finger rotation started (payload: `rotation`, `velocity`).",
207 RotationEnd = "onRotationEnd": "A two-finger rotation ended (payload: `rotation`, `velocity`).",
208 AccessibilityAction = "onAccessibilityAction": "An assistive technology performed an action (payload: `actionName`).",
209 Dismiss = "onDismiss" as "": "A screen was popped or a modal dismissed by the user or the system (`NavPage`'s `onDismiss`, `Dialog`'s `onClose`).",
210 RequestClose = "onRequestClose" as "": "The user tried to close a modal natively (Escape or the back button, a sheet swiped down; payload: `reason`: `\"cancel\"` or `\"swipe\"`, `\"cancel\"` when none); `Dialog`'s `onCancel` and `onOpenChange` (a press on its backdrop part is handled in JS).",
211 Show = "onShow" as "": "A modal finished appearing (`Dialog`'s `onOpen`).",
212 Insets = "onInsets": "The insets of a screen or modal changed (payload: `top`, `right`, `bottom`, `left`).",
213 LoadStart = "onLoadStart": "A web view, video or image started loading.",
214 Message = "onMessage": "A web page posted a message (payload: `data`).",
215 NavigationStateChange = "onNavigationStateChange": "A web view navigated (payload: `url`, `title`, `loading`, `canGoBack`, `canGoForward`).",
216 Progress = "onProgress": "Video playback progressed (payload: `currentTime`, `duration`).",
217 End = "onEnd": "A video played to its end.",
218 Buffer = "onBuffer": "A video started or stopped buffering (payload: `isBuffering`).",
219 ViewableItemsChange = "onViewableItemsChange": "The range of visible list items changed (payload: `first`, `last`).",
220 BackPress = "onBackPress" as "": "The Android back button was pressed and nothing native handled it (root only).",
221 Scroll = "onScroll": "A scroll view moved, at most once per frame (payload: `x`, `y`, `contentWidth`, `contentHeight`, `width`, `height`).",
222 ScrollDragStart = "onScrollDragStart": "The user started dragging a scroll view (payload: [`EventPayload::Scroll`]).",
223 ScrollDragEnd = "onScrollDragEnd": "The user let go of a scroll view (payload: [`EventPayload::Scroll`]).",
224 MomentumStart = "onMomentumStart": "A scroll view started gliding after a fling (payload: [`EventPayload::Scroll`]).",
225 MomentumEnd = "onMomentumEnd": "A scroll view stopped gliding (payload: [`EventPayload::Scroll`]).",
226 Dialog = "onDialog": "An alert or action sheet closed (root only; payload: `id`, `index`, -1 when dismissed, and `value`, the text of its text field when it has one).",
227 Touch = "onTouch": "Touches on the view or inside it, for the JS touch and responder handlers (payload: [`EventPayload::Touch`]).",
228 SelectionChange = "onSelectionChange": "The selection (or caret) of an input moved (payload: `start`, `end` in UTF-16 units), or the selection of a selectable view changed (payload: `text`, the selected text as a copy gives it, empty once nothing is selected; `start`, where it starts in the view's whole text; `bounds`, the box around it in the view, to which the core adds `pageBounds`; `anchorNode` / `anchorNodeOffset` and `focusNode` / `focusNodeOffset`, the text node of each end and the offset in it, which the core and the runtime turn into `anchor` and `focus`, the list item each end is in).",
229 KeyPress = "onKeyPress": "A key was pressed in an input (payload: `key`: the character, `Backspace` or `Enter`; on iOS also `start` and `end`, the range of the input's text, in UTF-16 units, the edit replaces).",
230 LoadEnd = "onLoadEnd": "An image finished loading, or failed.",
231 ImageInfo = "onImageInfo": "An `Image.getSize` / `Image.prefetch` request finished (root only; payload: `id`, `width` and `height` in pixels, or `error`).",
232 TextLayout = "onTextLayout": "A text block was laid out (payload: [`EventPayload::TextLayout`]).",
233 ContentSizeChange = "onContentSizeChange": "The size of an input's text changed (payload: `width`, `height`; raised by the core).",
234 BackRequest = "onBackRequest" as "onBackPress": "The user pressed back on a screen (the header's back button, Android back, the desktops' back keys and mouse button, the browser's back), whether or not `popOnBack` let it pop.",
235 NativeEvent = "onNativeEvent": "A registered native component emitted an event (payload: [`EventPayload::Native`]).",
236 Clipboard = "onClipboard": "A clipboard read finished (root only; payload: `id`, `has`: whether it holds what was asked; for text `text`, unless only `has` was asked; for an image `uri` (a `data:` URI), `width` and `height`, unless only `has` was asked, or `tooLarge` (its size in bytes) for one over `platform::clipboard::MAX_IMAGE_BYTES`; for files `files`, their `file:` URLs one per line).",
237 KeyCommand = "onKeyCommand": "A key matched a binding of `keymap` (`nsh`) (root only; payload: the binding's id, [`crate::keymap::KeyBinding::id`]).",
238 Menu = "onMenu": "A menu item was chosen: the application menu's or a context menu's (root only; desktops; payload: `id`), or a context menu closed (`closed`: true, after its item).",
239 MouseEnter = "onMouseEnter": "The mouse came over the view or a view inside it (never on touches; payload: [`EventPayload::Mouse`]).",
240 MouseLeave = "onMouseLeave": "The mouse left the view and the views inside it, or the window (payload: [`EventPayload::Mouse`], where it was last).",
241 FileDragEnter = "onFileDragEnter": "A local file drag entered an eligible drop destination, on desktops, iOS and Android (payload: [`EventPayload::FileDrop`]).",
242 FileDragLeave = "onFileDragLeave": "A local file drag left its drop destination, on desktops, iOS and Android.",
243 FileDrop = "onFileDrop": "Local files were dropped (payload: [`EventPayload::FileDropAt`] with where they were let go, or [`EventPayload::FileDrop`] where the backend gives no point).",
244 MouseMove = "onMouseMove": "The mouse moved over the view or a view inside it, with or without a button down, or a modifier key changed while it rests there with none down (payload: [`EventPayload::Mouse`]; at most one per frame).",
245 ContextMenu = "onContextMenu": "The secondary button was pressed over the view (payload: [`EventPayload::ContextMenu`]): the nearest listener around the view under the pointer hears it, unless a text input or selectable text is nearer.",
246 CompositionChange = "onCompositionChange": "An input method's composition in an input started, changed or ended (payload: `composing`, `text`: the text being composed, empty once it ends; after the `onChange` of the committed text).",
247 PressOutside = "onPressOutside": "A press went down outside an overlay, its anchor and the overlays inside it (payload: `pagePosition`, in the root view; raised by the core).",
248 Cancel = "onCancel": "Escape or the Android back button was pressed while the overlay was the top one listening to it (raised by the core).",
249 Position = "onPosition": "The core placed an overlay (payload: `placement`, the side it went on, `x`, `y`, `width`, `height` in the root view, `availableWidth`, `availableHeight`: the room on that side).",
250 Host = "onHost": "The embedding host answered a [`Command::HostCall`] or sent an event to `host`'s listeners (`nsh`) (root only; payload: [`EventPayload::Json`], `{ type: \"reply\", id, ok, value?, error? }` or `{ type: \"event\", event, payload }`).",
251 Pick = "onPick": "A picker closed (root only; payload: [`EventPayload::Picked`], no files when cancelled).",
252 LoadMoreAtStart = "onLoadMoreAtStart": "A list was scrolled close to its start after the user or a scroll command moved it (raised by the core).",
253 OpenUrl = "onOpenUrl": "A [`Command::OpenUrl`] request finished (root only; payload: `id`, `opened`: whether the platform opened the URL).",
254 CaretMove = "onCaretMove": "An input's caret moved: with its selection, or as its text scrolled or wrapped again (payload: `bounds`, the caret in the input; the core adds `pageBounds`, in the root view).",
255 Paste = "onPaste": "The user pasted into an input (payload: [`EventPayload::Paste`]: the text, files with their bytes such as a screenshot, local files' URLs), before the `onChangeText` of the text it inserts.",
256 ClipboardWrite = "onClipboardWrite": "A [`Command::SetClipboard`] or [`Command::SetClipboardItem`] finished, in the order of the writes (root only, platforms with [`crate::platform::Environment::clipboard_write_result`]; payload: `written`: whether the system clipboard took it).",
257 ScreenColor = "onScreenColor": "A [`Command::PickScreenColor`] request finished (root only; payload: `id`, `color`: the color picked, packed `0xRRGGBBAA`, absent when cancelled).",
258 FileRequest = "onFileRequest": "A [`Command::FileRequest`] finished (root only; payload: [`EventPayload::FileRequest`]).",
259 Download = "onDownload": "A web view's download started, finished, failed or was cancelled (payload: `state`, `id`, `url`, `filename`, `path`, `source`; `bytes` once finished, `code` and `message` when it failed, `reason` when it was cancelled).",
260 Notification = "onNotification": "The platform answered a [`Command::Notification`], or the user pressed a notification (root only; payload: the fields of [`crate::notifications::NotificationEvent`]).",
261 UrlScheme = "onUrlScheme": "The system handed the app a URL that opens it (root only; payload: `url`, [`crate::url_scheme::URL`]); the core keeps those of the schemes the app claims ([`crate::url_scheme`]).",
262 SecondInstance = "onSecondInstance": "A later launch of the app handed the running instance its command line (root only; desktops, nsh.json `singleInstance`; payload: [`EventPayload::Json`], [`crate::single_instance::SecondInstance::to_json`]).",
263 Audio = "onAudio": "A sound or a player reported (root only; payload: [`EventPayload::Audio`]).",
264 Window = "onWindow" as "": "A window of the app's own reported its state, a close press or that it closed (on its root node; desktops; payload: [`EventPayload::Window`]).",
265 EditAction = "onEditAction" as "": "An action was chosen from the edit menu a [`Command::OpenEditMenu`] opened on an input (payload: `action`, an [`EditAction`]'s name); Paste is the input's own paste (`onPaste`), never reported.",
266 Wheel = "onWheel": "A mouse wheel or touchpad scrolled over the view (payload: [`EventPayload::Wheel`]): the nearest listener around the view under the pointer hears it; one nearer than any scroll view under the pointer takes the wheel, so nothing scrolls or zooms natively ([`crate::input::wheel_listener`]).",
267 Pinch = "onPinch": "A touchpad pinch over the view (payload: [`EventPayload::Pinch`]; macOS, Linux, GPUI, Safari): the nearest listener around the view under the pointer hears it; one nearer than any view that pinches natively takes it, so nothing zooms or pinches natively ([`crate::input::wheel_listener`]); a pinch stays on the view its start went to.",
268
269 WebEvaluation = "onWebEvaluation" as "": "A native WebView evaluation reply (internal; payload: id and a JSON envelope string data).",
270 MouseUp = "onMouseUp": "A mouse button was released over the view or a view inside it (payload: [`EventPayload::Mouse`], its `button` naming the released one, with where and the modifiers). The primary button's release also reports `onPressUp`.",
271 CanvasImage = "onCanvasImage": "A [`Command::RenderCanvas`] request finished (root only; payload: [`EventPayload::CanvasImage`]).",
272 KeyDown = "onKeyDown": "A hardware key went down on the focused view or a view inside it (payload: [`EventPayload::Key`]). Notifications bubble to enabled listening ancestors within the same native window; returning from the listener cannot change handling, and `default_prevented` reports the mounted capture policy's decision for this transition.",
273 KeyUp = "onKeyUp": "A hardware key came up on the focused view (payload: [`EventPayload::Key`]), with `default_prevented` as the capture policy decided for this transition. It bubbles to enabled ancestors as `onKeyDown` does.",
274 WebViewReply = "onWebViewReply" as "": "A [`Command::WebViewRequest`] was carried out (the web view it was sent to; payload: [`EventPayload::Json`], `{ id, ok, value }` or `{ id, ok, error }`; the core answers the request's typed result and it reaches no listener).",
275 DownloadPending = "onDownloadPending" as "": "A web view's page asked to download a file and waits for the app's destination (payload: [`EventPayload::Json`]; handed to Rust's `WebView::on_download_pending`, not to a JS listener).",
276 DownloadOffer = "onDownloadOffer" as "": "A platform holds a download for the core (payload: [`EventPayload::Json`], [`crate::webview::DownloadOffer`]; never reaches a listener).",
277 DownloadProgress = "onDownloadProgress" as "": "A held download received bytes (payload: [`EventPayload::Json`], [`crate::webview::DownloadProgress`]; never reaches a listener).",
278 DownloadEnd = "onDownloadEnd" as "": "A platform's download ended (payload: [`EventPayload::Json`], [`crate::webview::DownloadEnd`]; never reaches a listener).",
279 DetentChange = "onDetentChange": "The user moved an iOS sheet dialog to another of its `detents` (dragging it, its grabber, a scroll at its edge, a screen reader; payload: [`EventPayload::Json`], `{ detent }`, [`SheetDetent::change_payload`]).",
280 FocusIn = "onFocusIn": "The keyboard focus came into the view: onto it or a view inside it, from outside (it entered `focus-within`; raised by the core). Moving between views inside it is no new coming in.",
281 FocusOut = "onFocusOut": "The keyboard focus left the view: from it or a view inside it to one outside, or to none (it left `focus-within`; raised by the core).",
282 TextDrop = "onTextDrop" as "": "Text dragged from another app or view was dropped on the view (payload: [`EventPayload::TextDrop`]): a Rust component's, such as `RichEditor`'s, which inserts it where it was let go (iOS).",
283 OpenAppSettings = "onOpenAppSettings" as "": "A [`Command::OpenAppSettings`] request finished (root only; payload: `id`, `opened`: whether the system opened the app's page in its settings; [`crate::mobile::open_app_settings`]; never reaches a listener).",
284 BackProgress = "onBackProgress" as "": "A step of the system's back gesture that no modal takes, while the app listens (root only; Android 14 and later; payload: [`BackProgressEvent::payload`], `phase`, `progress` and `edge`).",
285}
286
287/// What an input holds, for the system's autofill and suggestions
288/// (`autoComplete`, `textContentType`).
289#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
290pub enum AutoFill {
291 /// The platform decides.
292 #[default]
293 Default,
294 /// No autofill.
295 Off,
296 /// Account name.
297 Username,
298 /// Existing password.
299 Password,
300 /// A password being chosen.
301 NewPassword,
302 /// A code from a text message or e-mail.
303 OneTimeCode,
304 /// E-mail address.
305 Email,
306 /// Phone number.
307 Tel,
308 /// Full name.
309 Name,
310 /// First name.
311 GivenName,
312 /// Last name.
313 FamilyName,
314 /// Middle name.
315 MiddleName,
316 /// Nickname.
317 Nickname,
318 /// Company.
319 Organization,
320 /// Street address, all lines.
321 StreetAddress,
322 /// First address line.
323 AddressLine1,
324 /// Second address line.
325 AddressLine2,
326 /// City.
327 City,
328 /// State or region.
329 Region,
330 /// Postal code.
331 PostalCode,
332 /// Country.
333 Country,
334 /// Credit card number.
335 CreditCardNumber,
336 /// Credit card expiry date.
337 CreditCardExpiration,
338 /// Credit card security code.
339 CreditCardSecurityCode,
340 /// Name on the credit card.
341 CreditCardName,
342 /// Web address.
343 Url,
344 /// Birth date.
345 Birthdate,
346}
347
348impl AutoFill {
349 /// Parses React Native's `autoComplete` values and iOS's
350 /// `textContentType` names.
351 pub fn parse(name: &str) -> Option<Self> {
352 Some(match name {
353 "off" | "none" => Self::Off,
354 "username" | "username-new" => Self::Username,
355 "password" | "current-password" => Self::Password,
356 "new-password" | "newPassword" | "password-new" => Self::NewPassword,
357 "one-time-code" | "oneTimeCode" | "sms-otp" => Self::OneTimeCode,
358 "email" | "emailAddress" => Self::Email,
359 "tel" | "telephoneNumber" | "tel-national" | "tel-device" | "tel-country-code" => {
360 Self::Tel
361 }
362 "name" | "name-full" => Self::Name,
363 "given-name" | "givenName" | "name-given" => Self::GivenName,
364 "family-name" | "familyName" | "name-family" => Self::FamilyName,
365 "additional-name" | "middleName" | "name-middle" => Self::MiddleName,
366 "nickname" => Self::Nickname,
367 "organization" | "organizationName" => Self::Organization,
368 "street-address" | "fullStreetAddress" | "postal-address" => Self::StreetAddress,
369 "address-line1" | "streetAddressLine1" => Self::AddressLine1,
370 "address-line2" | "streetAddressLine2" => Self::AddressLine2,
371 "address-level2" | "addressCity" | "postal-address-locality" => Self::City,
372 "address-level1" | "addressState" | "postal-address-region" => Self::Region,
373 "postal-code" | "postalCode" => Self::PostalCode,
374 "country" | "countryName" | "postal-address-country" => Self::Country,
375 "cc-number" | "creditCardNumber" => Self::CreditCardNumber,
376 "cc-exp" | "creditCardExpiration" | "cc-exp-month" | "cc-exp-year" => {
377 Self::CreditCardExpiration
378 }
379 "cc-csc" | "creditCardSecurityCode" => Self::CreditCardSecurityCode,
380 "cc-name" | "creditCardName" => Self::CreditCardName,
381 "url" | "URL" => Self::Url,
382 "birthdate-full" | "birthdate" | "birthdate-day" | "birthdate-month"
383 | "birthdate-year" => Self::Birthdate,
384 _ => return None,
385 })
386 }
387}
388
389/// The phase of a [`TouchEvent`].
390#[derive(Debug, Clone, Copy, PartialEq, Eq)]
391pub enum TouchPhase {
392 /// Fingers went down (the changed points).
393 Start,
394 /// Fingers moved.
395 Move,
396 /// Fingers lifted (the changed points).
397 End,
398 /// The system or a native gesture took the touches over.
399 Cancel,
400}
401
402/// One finger of a [`TouchEvent`], in points.
403#[derive(Debug, Clone, PartialEq)]
404pub struct TouchPoint {
405 /// Identifies the finger while it is down.
406 pub id: u32,
407 /// The view under the finger when it went down.
408 pub target: NodeId,
409 /// The views around `target` (it included) that listen to touches,
410 /// innermost first.
411 pub path: Vec<NodeId>,
412 /// Position in the surface.
413 pub page: Point<Points>,
414 /// Position in `target`.
415 pub location: Point<Points>,
416 /// This finger is one the event is about (it went down, moved or
417 /// lifted).
418 pub changed: bool,
419 /// What the pointer is: a finger, a pen, or the mouse, which desktops
420 /// also report as a touch (what a held finger does, such as opening a
421 /// context menu, a held mouse button does not).
422 pub pointer_type: PointerType,
423 /// How hard the pointer presses, from 0 to 1, as the DOM's
424 /// `PointerEvent.pressure`: a device without pressure reports 0.5
425 /// while it is down and 0 once it lifted.
426 pub pressure: f32,
427 /// The pen's tilt toward the right of the surface, in degrees from
428 /// -90 to 90 (the DOM's `tiltX`); 0 for a finger, a mouse, or a pen
429 /// that does not report it.
430 pub tilt_x: f32,
431 /// The pen's tilt toward the bottom of the surface, in degrees from
432 /// -90 to 90 (the DOM's `tiltY`).
433 pub tilt_y: f32,
434 /// The samples the platform merged into this event, oldest first, as
435 /// the DOM's `getCoalescedEvents()` without the last one: a pen moves
436 /// at 120-240 Hz, and when a frame is slow the system hands over only
437 /// its latest position (this point), with the ones before it here.
438 /// Empty when nothing was merged, and for points that did not move.
439 pub coalesced: Vec<CoalescedSample>,
440 /// The pen is used with its eraser end (or the platform's eraser
441 /// mode), as the DOM's eraser button (`buttons & 32`); `pointer_type`
442 /// stays [`PointerType::Pen`].
443 pub eraser: bool,
444 /// The pen's barrel (side) button is held, as the DOM's `buttons & 2`
445 /// for a pen.
446 pub barrel: bool,
447}
448
449/// A pointer sample merged into a [`TouchPoint`] (its
450/// [`coalesced`](TouchPoint::coalesced) list), in points.
451#[derive(Debug, Clone, Copy, PartialEq)]
452pub struct CoalescedSample {
453 /// Position in the surface.
454 pub page: Point<Points>,
455 /// Position in the point's `target`.
456 pub location: Point<Points>,
457 /// How hard the pointer pressed, as [`TouchPoint::pressure`].
458 pub pressure: f32,
459 /// The pen's tilt, as [`TouchPoint::tilt_x`].
460 pub tilt_x: f32,
461 /// The pen's tilt, as [`TouchPoint::tilt_y`].
462 pub tilt_y: f32,
463 /// When the device took the sample, in the clock of
464 /// [`TouchEvent::timestamp`].
465 pub timestamp: f64,
466}
467
468impl TouchPoint {
469 /// Appends a merged sample at `page` (surface points) to
470 /// [`coalesced`](Self::coalesced), its `location` placed as this
471 /// point's (the target's offset from the surface is the same).
472 pub fn push_coalesced(
473 &mut self,
474 page: Point<Points>,
475 pressure: f32,
476 tilt_x: f32,
477 tilt_y: f32,
478 timestamp: f64,
479 ) {
480 let location = Point {
481 x: Points(page.x.0 + self.location.x.0 - self.page.x.0),
482 y: Points(page.y.0 + self.location.y.0 - self.page.y.0),
483 };
484 self.coalesced.push(CoalescedSample {
485 page,
486 location,
487 pressure,
488 tilt_x,
489 tilt_y,
490 timestamp,
491 });
492 }
493
494 /// The pressure of a pointer without pressure sensing in a `phase`
495 /// event, `changed` telling whether the point is the one the event is
496 /// about: 0.5 while down, 0 once lifted (the DOM's default).
497 pub fn default_pressure(phase: TouchPhase, changed: bool) -> f32 {
498 if changed && matches!(phase, TouchPhase::End | TouchPhase::Cancel) {
499 0.0
500 } else {
501 0.5
502 }
503 }
504}
505
506/// Where the mouse is over a view ([`EventKind::MouseEnter`],
507/// [`EventKind::MouseMove`], [`EventKind::MouseLeave`]), and where a mouse
508/// button was released ([`EventKind::MouseUp`]), in points, as GPUI's
509/// `MouseMoveEvent`.
510#[derive(Debug, Clone, Copy, PartialEq)]
511#[non_exhaustive]
512pub struct MouseEvent {
513 /// Position in the view, its transforms undone.
514 pub position: Point<Points>,
515 /// Position in the root view the view is in (the surface, or its
516 /// modal), as touches' `page`.
517 pub page_position: Point<Points>,
518 /// The modifier keys held.
519 pub modifiers: crate::keymap::Modifiers,
520 /// The button held down, if any (a drag).
521 pub pressed_button: Option<MouseButton>,
522 /// The button that changed at this event: the released one on
523 /// [`EventKind::MouseUp`], none on a move.
524 pub button: Option<MouseButton>,
525 /// What the pointer is: the mouse, or a pen over a tablet.
526 pub pointer_type: PointerType,
527 /// How hard the pointer presses, from 0 to 1, as the DOM's
528 /// `PointerEvent.pressure`: 0.5 with a button down and 0 without on a
529 /// device that has no pressure.
530 pub pressure: f32,
531 /// The pen's tilt in degrees, as [`TouchPoint::tilt_x`].
532 pub tilt_x: f32,
533 /// The pen's tilt in degrees, as [`TouchPoint::tilt_y`].
534 pub tilt_y: f32,
535}
536
537impl Default for MouseEvent {
538 fn default() -> Self {
539 Self {
540 position: Point::default(),
541 page_position: Point::default(),
542 modifiers: Default::default(),
543 pressed_button: None,
544 button: None,
545 pointer_type: PointerType::Mouse,
546 pressure: 0.0,
547 tilt_x: 0.0,
548 tilt_y: 0.0,
549 }
550 }
551}
552
553impl MouseEvent {
554 /// The event as reported by a pen (or a pressure-sensing touchpad):
555 /// `pointer_type`, `pressure` from 0 to 1, and tilt in degrees.
556 pub fn with_pointer(
557 mut self,
558 pointer_type: PointerType,
559 pressure: f32,
560 tilt_x: f32,
561 tilt_y: f32,
562 ) -> Self {
563 self.pointer_type = pointer_type;
564 self.pressure = pressure.clamp(0.0, 1.0);
565 self.tilt_x = tilt_x;
566 self.tilt_y = tilt_y;
567 self
568 }
569
570 /// The mouse at `position` in the view and `page_position` in its root
571 /// view, with `modifiers` held and `pressed_button` down.
572 pub fn new(
573 position: Point<Points>,
574 page_position: Point<Points>,
575 modifiers: crate::keymap::Modifiers,
576 pressed_button: Option<MouseButton>,
577 ) -> Self {
578 Self {
579 position,
580 page_position,
581 modifiers,
582 pressed_button,
583 button: None,
584 pressure: if pressed_button.is_some() { 0.5 } else { 0.0 },
585 ..Self::default()
586 }
587 }
588
589 /// A mouse button released at `position` in the view and
590 /// `page_position` in its root view, with `modifiers` held
591 /// ([`EventKind::MouseUp`]).
592 pub fn released(
593 position: Point<Points>,
594 page_position: Point<Points>,
595 modifiers: crate::keymap::Modifiers,
596 button: MouseButton,
597 ) -> Self {
598 Self {
599 position,
600 page_position,
601 modifiers,
602 pressed_button: None,
603 button: Some(button),
604 ..Self::default()
605 }
606 }
607}
608
609/// A touchpad pinch over a view ([`EventKind::Pinch`]), as GPUI's
610/// `PinchEvent`.
611#[derive(Debug, Clone, Copy, Default, PartialEq)]
612#[non_exhaustive]
613pub struct PinchEvent {
614 /// Position in the view, its transforms undone.
615 pub position: Point<Points>,
616 /// Position in the root view the view is in (the surface, or its
617 /// modal), as touches' `page`.
618 pub page_position: Point<Points>,
619 /// How much the scale changed since the last event, as a fraction
620 /// (0.1: 10 % bigger; negative: smaller), as GPUI's.
621 pub delta: crate::geometry::Percentage,
622 /// Where it is in the gesture.
623 pub phase: PinchPhase,
624 /// The modifier keys held.
625 pub modifiers: crate::keymap::Modifiers,
626}
627
628impl PinchEvent {
629 /// A pinch step of `delta` in `phase` at `position` in the view and
630 /// `page_position` in its root view, with `modifiers` held.
631 pub fn new(
632 position: Point<Points>,
633 page_position: Point<Points>,
634 delta: crate::geometry::Percentage,
635 phase: PinchPhase,
636 modifiers: crate::keymap::Modifiers,
637 ) -> Self {
638 Self {
639 position,
640 page_position,
641 delta,
642 phase,
643 modifiers,
644 }
645 }
646}
647
648/// Where a pinch is in its gesture ([`PinchEvent::phase`]), as a touch's
649/// [`TouchPhase`] (TS: `"start"`, `"move"`, `"end"`).
650#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
651#[non_exhaustive]
652pub enum PinchPhase {
653 /// The fingers began pinching.
654 Start,
655 /// The fingers moved.
656 #[default]
657 Move,
658 /// The fingers lifted, or the system cancelled the pinch.
659 End,
660}
661
662impl PinchPhase {
663 /// Its TS name.
664 pub fn name(self) -> &'static str {
665 match self {
666 PinchPhase::Start => "start",
667 PinchPhase::Move => "move",
668 PinchPhase::End => "end",
669 }
670 }
671
672 /// The phase named `name` (its TS name).
673 pub fn from_name(name: &str) -> Option<Self> {
674 Some(match name {
675 "start" => PinchPhase::Start,
676 "move" => PinchPhase::Move,
677 "end" => PinchPhase::End,
678 _ => return None,
679 })
680 }
681}
682
683/// A step of the system's back gesture that the app follows
684/// ([`crate::element::on_back_progress`]; TS: `BackHandler.on("progress",
685/// l)`), as AndroidX's `BackEventCompat`: Android 14 and later (predictive
686/// back) report it while the finger moves ([`EventKind::BackProgress`]).
687#[derive(Debug, Clone, Copy, Default, PartialEq)]
688#[non_exhaustive]
689pub struct BackProgressEvent {
690 /// Where it is in the gesture.
691 pub phase: BackPhase,
692 /// How far the gesture went, from 0 to 1 (all the way), as the system
693 /// reports it.
694 pub progress: Percentage,
695 /// The screen edge the swipe started at ([`PanEdge::Left`] or
696 /// [`PanEdge::Right`]); none when the system names no edge.
697 pub edge: Option<PanEdge>,
698}
699
700impl BackProgressEvent {
701 /// A step in `phase` at `progress` (0 to 1) of a swipe from `edge`.
702 pub fn new(phase: BackPhase, progress: Percentage, edge: Option<PanEdge>) -> Self {
703 Self {
704 phase,
705 progress,
706 edge,
707 }
708 }
709
710 /// The payload of [`EventKind::BackProgress`] (`{ phase, progress,
711 /// edge? }`, the object JS listeners get).
712 pub fn payload(&self) -> EventPayload {
713 let mut fields = vec![
714 ("phase", PayloadValue::Str(self.phase.name().into())),
715 ("progress", PayloadValue::Number(f64::from(self.progress.0))),
716 ];
717 let edge = match self.edge {
718 Some(PanEdge::Left) => Some("left"),
719 Some(PanEdge::Right) => Some("right"),
720 _ => None,
721 };
722 if let Some(edge) = edge {
723 fields.push(("edge", PayloadValue::Str(edge.into())));
724 }
725 EventPayload::Map(fields)
726 }
727
728 /// The step a [`Self::payload`] carries.
729 pub(crate) fn from_payload(payload: &EventPayload) -> Option<Self> {
730 let EventPayload::Map(fields) = payload else {
731 return None;
732 };
733 let mut event = Self::default();
734 let mut phase = None;
735 for (key, value) in fields {
736 match (*key, value) {
737 ("phase", PayloadValue::Str(name)) => phase = BackPhase::from_name(name),
738 ("progress", PayloadValue::Number(n)) => event.progress = Percentage(*n as f32),
739 ("edge", PayloadValue::Str(edge)) => {
740 event.edge = match edge.as_str() {
741 "left" => Some(PanEdge::Left),
742 "right" => Some(PanEdge::Right),
743 _ => None,
744 }
745 }
746 _ => {}
747 }
748 }
749 event.phase = phase?;
750 Some(event)
751 }
752}
753
754/// Where the back gesture is ([`BackProgressEvent::phase`]; TS: `"start"`,
755/// `"move"`, `"end"`, `"cancel"`), as AndroidX's `OnBackPressedCallback`'s
756/// started, progressed, pressed and cancelled.
757#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
758#[non_exhaustive]
759pub enum BackPhase {
760 /// The finger started the gesture.
761 Start,
762 /// The finger moved.
763 #[default]
764 Move,
765 /// The finger let go and the gesture goes back: the back press
766 /// follows.
767 End,
768 /// The finger let go without going back, or the system cancelled the
769 /// gesture.
770 Cancel,
771}
772
773impl BackPhase {
774 /// Its TS name.
775 pub fn name(self) -> &'static str {
776 match self {
777 BackPhase::Start => "start",
778 BackPhase::Move => "move",
779 BackPhase::End => "end",
780 BackPhase::Cancel => "cancel",
781 }
782 }
783
784 /// The phase named `name` (its TS name).
785 pub fn from_name(name: &str) -> Option<Self> {
786 Some(match name {
787 "start" => BackPhase::Start,
788 "move" => BackPhase::Move,
789 "end" => BackPhase::End,
790 "cancel" => BackPhase::Cancel,
791 _ => return None,
792 })
793 }
794}
795
796/// A mouse button, as GPUI's `MouseButton` (TS: `"left"`, `"right"`,
797/// `"middle"`, `"back"`, `"forward"`).
798#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
799pub enum MouseButton {
800 /// The primary button.
801 Left,
802 /// The secondary button.
803 Right,
804 /// The middle button (the wheel).
805 Middle,
806 /// The back button (the DOM's button 3).
807 Back,
808 /// The forward button (the DOM's button 4).
809 Forward,
810}
811
812impl MouseButton {
813 /// Its TS name.
814 pub fn name(self) -> &'static str {
815 match self {
816 MouseButton::Left => "left",
817 MouseButton::Right => "right",
818 MouseButton::Middle => "middle",
819 MouseButton::Back => "back",
820 MouseButton::Forward => "forward",
821 }
822 }
823}
824
825/// Where the pointer was at a press ([`EventKind::Press`],
826/// [`EventKind::LongPress`], [`EventKind::PressDown`],
827/// [`EventKind::PressUp`]), with the modifier keys and the click count, on
828/// backends that know it, in points.
829#[derive(Debug, Clone, Copy, Default, PartialEq)]
830pub struct PressEvent {
831 /// Position in the pressed view, its transforms undone (for a pressed
832 /// span of a text, in that text's view).
833 pub position: Point<Points>,
834 /// Position in the root view the view is in (the surface, or its
835 /// modal), as touches' `page`.
836 pub page_position: Point<Points>,
837 /// The modifier keys held when the press began.
838 pub modifiers: crate::keymap::Modifiers,
839 /// Consecutive clicks at the same place: 1 for a click, 2 for a
840 /// double click, ...; 0 when not from a pointer (a keyboard or
841 /// assistive technology activation), as the DOM's `detail`.
842 pub clicks: u32,
843}
844
845/// Where a context menu was asked for ([`EventKind::ContextMenu`]), in
846/// points.
847#[derive(Debug, Clone, Copy, Default, PartialEq)]
848#[non_exhaustive]
849pub struct ContextMenuEvent {
850 /// Position in the view, its transforms undone: the pointer's, or, when
851 /// no pointer asked ([`ContextMenuEvent::pointer_type`] is `None`), the
852 /// view's bottom-start corner ([`crate::input::context_menu_anchor`]).
853 pub position: Point<Points>,
854 /// Position in the root view the view is in (the surface, or its
855 /// modal): where `Menu.popup` opens a menu.
856 pub page_position: Point<Points>,
857 /// The modifier keys held.
858 pub modifiers: crate::keymap::Modifiers,
859 /// The pointer that asked for the menu (the DOM's `pointerType`), or
860 /// `None` when none did: the keyboard (Shift+F10, the Menu key) or an
861 /// assistive technology's "show menu" action, which a menu answers
862 /// with the keyboard focus on its first item.
863 pub pointer_type: Option<PointerType>,
864}
865
866impl ContextMenuEvent {
867 /// A context menu asked for at `position` in the view and
868 /// `page_position` in its root view, with `modifiers` held, by
869 /// `pointer_type` (`None`: the keyboard or an assistive technology).
870 pub fn new(
871 position: Point<Points>,
872 page_position: Point<Points>,
873 modifiers: crate::keymap::Modifiers,
874 pointer_type: Option<PointerType>,
875 ) -> Self {
876 Self {
877 position,
878 page_position,
879 modifiers,
880 pointer_type,
881 }
882 }
883}
884
885/// How far a wheel scrolled ([`WheelEvent::delta`]), as GPUI's
886/// `ScrollDelta`: positive `y` scrolls toward the end (down), positive `x`
887/// toward the right, as the DOM's `WheelEvent`.
888#[derive(Debug, Clone, Copy, PartialEq)]
889pub enum WheelDelta {
890 /// Points, from a precise device (a touchpad, a Magic Mouse; AppKit's
891 /// `hasPreciseScrollingDeltas`, the DOM's `DOM_DELTA_PIXEL`).
892 Points(Point<Points>),
893 /// Lines (notches) of a mouse wheel, the DOM's `DOM_DELTA_LINE`.
894 Lines(Point<f32>),
895}
896
897impl Default for WheelDelta {
898 fn default() -> Self {
899 WheelDelta::Points(Point::default())
900 }
901}
902
903impl WheelDelta {
904 /// The delta in points, a line being `line_height` points (GPUI's
905 /// `ScrollDelta::pixel_delta`).
906 pub fn points(self, line_height: Points) -> Point<Points> {
907 match self {
908 WheelDelta::Points(p) => p,
909 WheelDelta::Lines(l) => Point {
910 x: Points(l.x * line_height.0),
911 y: Points(l.y * line_height.0),
912 },
913 }
914 }
915
916 /// Whether the delta is in precise points rather than lines.
917 pub fn precise(self) -> bool {
918 matches!(self, WheelDelta::Points(_))
919 }
920
921 /// Its TS `deltaMode`: `"points"` or `"lines"`.
922 pub fn mode_name(self) -> &'static str {
923 match self {
924 WheelDelta::Points(_) => "points",
925 WheelDelta::Lines(_) => "lines",
926 }
927 }
928
929 /// Its raw `(x, y)`, in its own unit.
930 pub fn xy(self) -> (f32, f32) {
931 match self {
932 WheelDelta::Points(p) => (p.x.0, p.y.0),
933 WheelDelta::Lines(l) => (l.x, l.y),
934 }
935 }
936}
937
938/// A wheel over a view ([`EventKind::Wheel`]), in points, as GPUI's
939/// `ScrollWheelEvent`.
940#[derive(Debug, Clone, Copy, Default, PartialEq)]
941#[non_exhaustive]
942pub struct WheelEvent {
943 /// Position in the view, its transforms undone.
944 pub position: Point<Points>,
945 /// Position in the root view the view is in (the surface, or its
946 /// modal), as touches' `page`.
947 pub page_position: Point<Points>,
948 /// How far it scrolled, in lines or points.
949 pub delta: WheelDelta,
950 /// The modifier keys held (Control + wheel zooms by convention).
951 pub modifiers: crate::keymap::Modifiers,
952}
953
954impl WheelEvent {
955 /// A wheel by `delta` at `position` in the view and `page_position` in
956 /// its root view, with `modifiers` held.
957 pub fn new(
958 position: Point<Points>,
959 page_position: Point<Points>,
960 delta: WheelDelta,
961 modifiers: crate::keymap::Modifiers,
962 ) -> Self {
963 Self {
964 position,
965 page_position,
966 delta,
967 modifiers,
968 }
969 }
970}
971
972/// The kind of pointer behind an event, as the DOM's `pointerType` (TS:
973/// `"mouse"`, `"pen"`, `"touch"`).
974#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
975#[non_exhaustive]
976pub enum PointerType {
977 /// A mouse or a touchpad.
978 Mouse,
979 /// A pen or stylus.
980 Pen,
981 /// A finger on a touch screen.
982 Touch,
983}
984
985impl PointerType {
986 /// Its TS name.
987 pub fn name(self) -> &'static str {
988 match self {
989 PointerType::Mouse => "mouse",
990 PointerType::Pen => "pen",
991 PointerType::Touch => "touch",
992 }
993 }
994
995 /// The pointer type of TS name `name` (the DOM's `pointerType`), or
996 /// `None` for one NSH does not know and for the DOM's `""` (no
997 /// pointer).
998 pub fn from_name(name: &str) -> Option<Self> {
999 Some(match name {
1000 "mouse" => PointerType::Mouse,
1001 "pen" => PointerType::Pen,
1002 "touch" => PointerType::Touch,
1003 _ => return None,
1004 })
1005 }
1006}
1007
1008/// Touches for the JS responder system.
1009#[derive(Debug, Clone, PartialEq)]
1010pub struct TouchEvent {
1011 /// What happened.
1012 pub phase: TouchPhase,
1013 /// Milliseconds since an arbitrary origin.
1014 pub timestamp: f64,
1015 /// The fingers down during the event (with those that lifted).
1016 pub points: Vec<TouchPoint>,
1017 /// A view around the fingers whose `panActivation` the platform
1018 /// activated with this event: it becomes the responder.
1019 pub activated: Option<NodeId>,
1020 /// The modifier keys held when the changed pointer went down, as a
1021 /// press's [`PressEvent::modifiers`] (none for a finger on a touch
1022 /// screen).
1023 pub modifiers: crate::keymap::Modifiers,
1024}
1025
1026/// What the user pasted into an input ([`EventKind::Paste`]): what the
1027/// clipboard held when the user pasted, which the platform read then (the
1028/// app never reads the clipboard for it).
1029#[derive(Debug, Clone, Default, PartialEq)]
1030#[non_exhaustive]
1031pub struct PasteEvent {
1032 /// The plain text, empty when it held none.
1033 pub text: String,
1034 /// The same content as HTML (`text/html`), empty when the clipboard
1035 /// held none: what a browser, an office suite or a rich text editor
1036 /// copied, with its formatting.
1037 pub html: String,
1038 /// Files with their bytes: images (a screenshot, an image copied from a
1039 /// page or an app), in the platform's order.
1040 pub files: Vec<PastedFile>,
1041 /// Files larger than the input's `pasteMaxSize`, whose bytes were not
1042 /// read: each with its name, type and size ([`PastedFile::len`]) only,
1043 /// in the platform's order.
1044 pub too_large: Vec<PastedFile>,
1045 /// Absolute `file:` URLs of local files copied in a file manager, in the
1046 /// platform's order (as [`EventPayload::FileDrop`]'s).
1047 pub uris: Vec<String>,
1048}
1049
1050/// Text dropped on a view ([`EventKind::TextDrop`]).
1051#[derive(Debug, Clone, PartialEq, Default)]
1052#[non_exhaustive]
1053pub struct TextDrop {
1054 /// The plain text, empty when the drag held none.
1055 pub text: String,
1056 /// The same content as HTML, empty when the drag held none.
1057 pub html: String,
1058 /// The drop point in the window's coordinates.
1059 pub page_position: Point<Points>,
1060}
1061
1062impl TextDrop {
1063 /// A drop of `text` (and `html`) at `page_position`.
1064 pub fn new(text: String, html: String, page_position: Point<Points>) -> Self {
1065 TextDrop {
1066 text,
1067 html,
1068 page_position,
1069 }
1070 }
1071}
1072
1073impl EventPayload {
1074 /// An `onPaste` payload of fields (`text`; a reported paste with no
1075 /// payload is an empty one) made a [`EventPayload::Paste`], as handlers
1076 /// read it (`files` and `uris` always there).
1077 pub fn into_paste(self) -> EventPayload {
1078 match self {
1079 EventPayload::Map(fields) => {
1080 let mut paste = PasteEvent::default();
1081 for (key, value) in fields {
1082 match (key, value) {
1083 ("text", PayloadValue::Str(text)) => paste.text = text,
1084 ("html", PayloadValue::Str(html)) => paste.html = html,
1085 _ => {}
1086 }
1087 }
1088 EventPayload::Paste(Box::new(paste))
1089 }
1090 EventPayload::None => EventPayload::Paste(Box::default()),
1091 payload => payload,
1092 }
1093 }
1094}
1095
1096impl PasteEvent {
1097 /// A paste of `text`, with no files.
1098 pub fn new(text: impl Into<String>) -> PasteEvent {
1099 PasteEvent {
1100 text: text.into(),
1101 ..PasteEvent::default()
1102 }
1103 }
1104
1105 /// Whether it holds nothing.
1106 pub fn is_empty(&self) -> bool {
1107 self.text.is_empty()
1108 && self.html.is_empty()
1109 && self.files.is_empty()
1110 && self.too_large.is_empty()
1111 && self.uris.is_empty()
1112 }
1113
1114 /// Moves the files larger than `max_size` bytes to
1115 /// [`Self::too_large`], without their bytes.
1116 pub(crate) fn limit_files(&mut self, max_size: u64) {
1117 if self.files.iter().all(|file| file.len <= max_size) {
1118 return;
1119 }
1120 let (read, over): (Vec<_>, Vec<_>) = std::mem::take(&mut self.files)
1121 .into_iter()
1122 .partition(|file| file.len <= max_size);
1123 self.files = read;
1124 self.too_large.extend(
1125 over.into_iter()
1126 .map(|file| PastedFile::too_large(file.name, file.mime, file.len)),
1127 );
1128 }
1129}
1130
1131/// A file pasted with its bytes ([`PasteEvent::files`]): JS gets a `File`.
1132/// One too large to read ([`PasteEvent::too_large`]) has no bytes.
1133#[derive(Debug, Clone, Default, PartialEq)]
1134#[non_exhaustive]
1135pub struct PastedFile {
1136 /// Its name (`image.png` for an image without one).
1137 pub name: String,
1138 /// Its MIME type (`image/png`).
1139 pub mime: String,
1140 /// Its bytes.
1141 pub data: Vec<u8>,
1142 /// Its size in bytes: its bytes' length, or for one not read, the size
1143 /// its platform gave.
1144 pub len: u64,
1145}
1146
1147impl PastedFile {
1148 /// A file named `name` of type `mime` holding `data`.
1149 pub fn new(name: impl Into<String>, mime: impl Into<String>, data: Vec<u8>) -> PastedFile {
1150 PastedFile {
1151 name: name.into(),
1152 mime: mime.into(),
1153 len: data.len() as u64,
1154 data,
1155 }
1156 }
1157
1158 /// The file `name` of type `mime` and `len` bytes, too large to read
1159 /// ([`PasteEvent::too_large`]): no bytes.
1160 pub fn too_large(name: impl Into<String>, mime: impl Into<String>, len: u64) -> PastedFile {
1161 PastedFile {
1162 name: name.into(),
1163 mime: mime.into(),
1164 data: Vec::new(),
1165 len,
1166 }
1167 }
1168
1169 /// An image of encoded `data` (PNG, JPEG, GIF, WebP, HEIC, TIFF, BMP;
1170 /// PNG when unknown), named `image.<extension>`.
1171 pub fn image(data: Vec<u8>) -> PastedFile {
1172 let (mime, extension) = image_type(&data);
1173 PastedFile::new(format!("image.{extension}"), mime, data)
1174 }
1175}
1176
1177/// The MIME type and file extension of encoded image `data`.
1178fn image_type(data: &[u8]) -> (&'static str, &'static str) {
1179 match data {
1180 [0xFF, 0xD8, 0xFF, ..] => ("image/jpeg", "jpg"),
1181 [b'G', b'I', b'F', b'8', ..] => ("image/gif", "gif"),
1182 [
1183 b'R',
1184 b'I',
1185 b'F',
1186 b'F',
1187 _,
1188 _,
1189 _,
1190 _,
1191 b'W',
1192 b'E',
1193 b'B',
1194 b'P',
1195 ..,
1196 ] => ("image/webp", "webp"),
1197 [
1198 _,
1199 _,
1200 _,
1201 _,
1202 b'f',
1203 b't',
1204 b'y',
1205 b'p',
1206 b'h',
1207 b'e',
1208 b'i',
1209 b'c' | b'x',
1210 ..,
1211 ] => ("image/heic", "heic"),
1212 [b'I', b'I', 42, 0, ..] | [b'M', b'M', 0, 42, ..] => ("image/tiff", "tiff"),
1213 [b'B', b'M', ..] => ("image/bmp", "bmp"),
1214 _ => ("image/png", "png"),
1215 }
1216}
1217
1218// Every kind has a bit of [`EventMask`].
1219const _: () = assert!(EventKind::ALL.len() <= 128, "EventMask has 128 bits");
1220
1221/// A set of [`EventKind`]s: one bit per kind, room for 128. Two words, not
1222/// a `u128`: views keep it in Objective-C ivars, which take no 16-byte
1223/// alignment.
1224#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1225pub struct EventMask([u64; 2]);
1226
1227impl std::ops::BitOr for EventMask {
1228 type Output = EventMask;
1229
1230 #[inline]
1231 fn bitor(self, other: EventMask) -> EventMask {
1232 EventMask([self.0[0] | other.0[0], self.0[1] | other.0[1]])
1233 }
1234}
1235
1236impl EventMask {
1237 /// Returns true if `event` is in the set.
1238 #[inline]
1239 pub const fn contains(self, event: EventKind) -> bool {
1240 let k = event as usize;
1241 self.0[k / 64] & (1 << (k % 64)) != 0
1242 }
1243
1244 /// The raw bit set, indexed by `EventKind as u8`.
1245 #[inline]
1246 pub const fn bits(self) -> u128 {
1247 self.0[0] as u128 | (self.0[1] as u128) << 64
1248 }
1249
1250 /// Adds or removes `event`.
1251 #[inline]
1252 pub fn set(&mut self, event: EventKind, enabled: bool) {
1253 let k = event as usize;
1254 if enabled {
1255 self.0[k / 64] |= 1 << (k % 64);
1256 } else {
1257 self.0[k / 64] &= !(1 << (k % 64));
1258 }
1259 }
1260
1261 /// Returns true if no event is set.
1262 #[inline]
1263 pub const fn is_empty(self) -> bool {
1264 self.0[0] == 0 && self.0[1] == 0
1265 }
1266}
1267
1268/// A value in an event payload.
1269#[derive(Debug, Clone, PartialEq)]
1270pub enum PayloadValue {
1271 /// A number.
1272 Number(f64),
1273 /// A boolean.
1274 Bool(bool),
1275 /// A string.
1276 Str(String),
1277 /// `null`.
1278 Null,
1279 /// A position (`{ x, y }`).
1280 Point(Point<Points>),
1281 /// An extent (`{ width, height }`).
1282 Size(Size<Points>),
1283 /// A position and an extent (`{ origin, size }`).
1284 Bounds(Bounds<Points>),
1285}
1286
1287/// Files dragged in with their contents ([`EventPayload::FileContents`]).
1288#[derive(Debug, Clone, PartialEq, Default)]
1289#[non_exhaustive]
1290pub struct FileContents {
1291 /// The regular files, in the drag's order: read ones with their bytes,
1292 /// ones over the limit `tooLarge`; on drag entry, none are read yet.
1293 pub files: Vec<crate::picker::PickedFile>,
1294 /// The MIME type of each offered item, as the platform reports them.
1295 pub mime_types: Vec<String>,
1296 /// Where the files were let go, in the window's coordinates.
1297 pub page_position: Option<Point<Points>>,
1298}
1299
1300impl FileContents {
1301 /// Contents of `files`, typed `mime_types`, let go at `page_position`.
1302 pub fn new(
1303 files: Vec<crate::picker::PickedFile>,
1304 mime_types: Vec<String>,
1305 page_position: Option<Point<Points>>,
1306 ) -> Self {
1307 Self {
1308 files,
1309 mime_types,
1310 page_position,
1311 }
1312 }
1313}
1314
1315/// Data delivered with an event.
1316#[derive(Debug, Clone, PartialEq)]
1317pub enum EventPayload {
1318 /// No data.
1319 None,
1320 /// A single value handed to the handler as is (`onValueChange(value)`).
1321 Value(PayloadValue),
1322 /// An object with named fields.
1323 Map(Vec<(&'static str, PayloadValue)>),
1324 /// A frame relative to the parent (`onLayout`).
1325 Layout(Bounds<Points>),
1326 /// A drag: translation since the start and velocity (points / second).
1327 Pan {
1328 /// Where the finger went down, in the surface.
1329 origin: Point<Points>,
1330 /// The translation.
1331 translation: Point<Points>,
1332 /// Horizontal velocity.
1333 velocity_x: f32,
1334 /// Vertical velocity.
1335 velocity_y: f32,
1336 /// The `pan.x` value now (`None` without one).
1337 value_x: Option<Points>,
1338 /// The `pan.y` value now.
1339 value_y: Option<Points>,
1340 },
1341 /// A system-cancelled drag, with the same last values as `Pan`.
1342 PanCancelled {
1343 /// Where the finger went down, in the surface.
1344 origin: Point<Points>,
1345 /// The translation.
1346 translation: Point<Points>,
1347 /// Horizontal velocity.
1348 velocity_x: f32,
1349 /// Vertical velocity.
1350 velocity_y: f32,
1351 /// The `pan.x` value now (`None` without one).
1352 value_x: Option<Points>,
1353 /// The `pan.y` value now.
1354 value_y: Option<Points>,
1355 },
1356 /// A scroll position: the content offset.
1357 Scroll(Point<Points>),
1358 /// A loaded image's source size in pixels (before downsampling).
1359 Image(Size<DevicePixels>),
1360 /// An error message.
1361 Error {
1362 /// The message.
1363 message: String,
1364 },
1365 /// The text of an input after an edit.
1366 Text {
1367 /// The whole text.
1368 text: String,
1369 /// Number of edits the input has reported so far. A value set by JS
1370 /// based on an older edit is stale and must not overwrite newer
1371 /// typing.
1372 count: u32,
1373 },
1374 /// Touches (`onTouch`).
1375 Touch(Box<TouchEvent>),
1376 /// The mouse over a view (`onMouseEnter`, `onMouseMove`,
1377 /// `onMouseLeave`) or a button released over it (`onMouseUp`, its
1378 /// `button` naming the released one).
1379 Mouse(MouseEvent),
1380 /// A context menu asked for over a view (`onContextMenu`).
1381 ContextMenu(ContextMenuEvent),
1382 /// A wheel over a view (`onWheel`).
1383 Wheel(WheelEvent),
1384 /// A touchpad pinch over a view (`onPinch`).
1385 Pinch(PinchEvent),
1386 /// A hardware key transition on a focused Rust view.
1387 Key(crate::KeyEvent),
1388 /// Where the pointer was at a press (`onPress`, `onLongPress`,
1389 /// `onPressDown`, `onPressUp`), with the modifier keys and the click
1390 /// count, on backends that know it.
1391 Press(PressEvent),
1392 /// Local file URLs offered on drag entry or dropped by the user, in the platform's order.
1393 FileDrop(Vec<String>),
1394 /// [`Self::FileDrop`] with where the files were let go, in the
1395 /// window's coordinates, from backends that know it.
1396 FileDropAt {
1397 /// The files' URLs, as [`Self::FileDrop`]'s.
1398 uris: Vec<String>,
1399 /// The drop point in the window's coordinates.
1400 page_position: Point<Points>,
1401 },
1402 /// Files a drag offers or drops where the platform hands over their
1403 /// contents rather than local paths (the Web): `files` in the drag's
1404 /// order, unread on drag entry (types only), and where they were let
1405 /// go. Boxed, as [`Self::Paste`], to keep every payload small.
1406 FileContents(Box<FileContents>),
1407 /// What the user pasted into an input.
1408 Paste(Box<PasteEvent>),
1409 /// Text dropped on a view ([`EventKind::TextDrop`]); boxed, as
1410 /// [`Self::Paste`], to keep every payload small.
1411 TextDrop(Box<TextDrop>),
1412 /// The lines of a text block.
1413 TextLayout(Vec<crate::text::TextLine>),
1414 /// The files the user picked ([`EventKind::Pick`]), with their bytes.
1415 Picked {
1416 /// The request ([`Command::PickImages`], [`Command::PickFiles`]).
1417 id: u32,
1418 /// The files, in the order picked; none when cancelled.
1419 files: Vec<crate::picker::PickedFile>,
1420 },
1421 /// What a sound or a player reported ([`EventKind::Audio`],
1422 /// [`crate::audio`]).
1423 Audio {
1424 /// The sound or player ([`crate::audio::AudioCommand::id`]).
1425 id: u32,
1426 /// What it reported.
1427 event: crate::audio::AudioEvent,
1428 },
1429 /// What a window of the app's own reported ([`EventKind::Window`]).
1430 Window(Box<crate::desktop::WindowEvent>),
1431 /// The answer to a [`Command::FileRequest`] ([`EventKind::FileRequest`],
1432 /// [`crate::file_dialog`]).
1433 FileRequest {
1434 /// The request.
1435 id: u32,
1436 /// The paths picked, the path chosen to save to or where a trashed
1437 /// item went; none when cancelled, failed or not known.
1438 paths: Vec<std::path::PathBuf>,
1439 /// Why the request failed; `None` when it was carried out (or the
1440 /// dialog cancelled).
1441 error: Option<String>,
1442 },
1443 /// The image a [`Command::RenderCanvas`] made, or why it failed
1444 /// ([`crate::canvas::render`]).
1445 CanvasImage {
1446 /// The request.
1447 id: u32,
1448 /// The encoded image, or why there is none.
1449 result: Result<Vec<u8>, crate::canvas::render::RenderFailure>,
1450 },
1451 /// An event of a registered native component: its name and data (any
1452 /// JSON value), handed to JS as `{ name, data }`.
1453 Native {
1454 /// The event (`regionChange`).
1455 name: Arc<str>,
1456 /// Its data.
1457 data: crate::JsonValue,
1458 },
1459 /// A JSON value handed to JS as it is ([`EventKind::Host`]).
1460 Json(crate::JsonValue),
1461}
1462
1463impl EventPayload {
1464 /// An input's `onCaretMove`: the caret's `bounds` in the input's
1465 /// coordinates (its border box, the input's own scrolling applied), as
1466 /// the platforms report it. The core adds `pageBounds`
1467 /// ([`crate::Core::locate_caret`]).
1468 pub fn caret(bounds: Bounds<Points>) -> EventPayload {
1469 EventPayload::Map(vec![("bounds", PayloadValue::Bounds(bounds))])
1470 }
1471}
1472
1473impl TouchEvent {
1474 /// Folds a later move into this pending one: the later positions,
1475 /// changed if either moved them, and either's activated pan. A point
1476 /// this one moved keeps its samples: they go before the later ones in
1477 /// [`TouchPoint::coalesced`], with this event's own position.
1478 pub fn merge_move(&mut self, later: TouchEvent) {
1479 let mut later = later;
1480 for p in &mut later.points {
1481 if let Some(old) = self.points.iter_mut().find(|o| o.id == p.id) {
1482 p.changed |= old.changed;
1483 if old.changed {
1484 let mut samples = std::mem::take(&mut old.coalesced);
1485 samples.push(CoalescedSample {
1486 page: old.page,
1487 location: old.location,
1488 pressure: old.pressure,
1489 tilt_x: old.tilt_x,
1490 tilt_y: old.tilt_y,
1491 timestamp: self.timestamp,
1492 });
1493 samples.append(&mut p.coalesced);
1494 p.coalesced = samples;
1495 }
1496 }
1497 }
1498 later.activated = later.activated.or(self.activated);
1499 *self = later;
1500 }
1501}
1502
1503/// How an image fits its box.
1504#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
1505pub enum ResizeMode {
1506 /// Fill the box, cropping (default).
1507 #[default]
1508 Cover,
1509 /// Fit inside the box, letterboxing.
1510 Contain,
1511 /// Stretch to the box.
1512 Stretch,
1513 /// Center at natural size, cropped where larger than the box (CSS's
1514 /// `object-fit: none`).
1515 Center,
1516 /// Center at natural size, shrunk to fit the box where larger (CSS's
1517 /// `object-fit: scale-down`, React Native's `center`).
1518 #[prop(rename = "scale-down")]
1519 ScaleDown,
1520}
1521
1522impl ResizeMode {
1523 /// Where content of `natural` size goes in a box of `size`: scaled as
1524 /// the mode scales it (`Center` keeps the natural size, as CSS's
1525 /// `none`; `ScaleDown` shrinks content larger than the box, as CSS's
1526 /// `scale-down`), then placed at `position`. The rectangle
1527 /// may reach outside the box (a covering image), which crops it.
1528 /// Content without a size fills the box.
1529 pub fn fit(
1530 self,
1531 natural: Size<Points>,
1532 size: Size<Points>,
1533 position: crate::style::ObjectPosition,
1534 ) -> Bounds<Points> {
1535 let (nw, nh) = (natural.width.0, natural.height.0);
1536 if nw <= 0.0 || nh <= 0.0 || self == ResizeMode::Stretch {
1537 return Bounds {
1538 origin: Point::default(),
1539 size,
1540 };
1541 }
1542 let contain = (size.width.0 / nw).min(size.height.0 / nh);
1543 let scale = match self {
1544 ResizeMode::Cover => (size.width.0 / nw).max(size.height.0 / nh),
1545 ResizeMode::Contain => contain,
1546 ResizeMode::Center => 1.0,
1547 ResizeMode::ScaleDown => contain.min(1.0),
1548 ResizeMode::Stretch => 1.0,
1549 };
1550 let content = Size {
1551 width: Points(nw * scale),
1552 height: Points(nh * scale),
1553 };
1554 Bounds {
1555 origin: position.place(size, content),
1556 size: content,
1557 }
1558 }
1559}
1560
1561/// An image source.
1562#[derive(Debug, Clone, PartialEq, Default)]
1563pub struct ImageSource {
1564 /// `https://…`, `asset:/path` (bundled file), a file path, a `data:` URI
1565 /// or a `blob:` URL (`URL.createObjectURL`). A source with [`Self::data`]
1566 /// goes by a short key instead of a `data:` URI ([`crate::image`]).
1567 pub uri: Arc<str>,
1568 /// Natural size in points, when known up front (bundled assets): used
1569 /// as the intrinsic layout size.
1570 pub size: Option<Size<Points>>,
1571 /// The pixel densities a bundled asset ships in (`a.png`,
1572 /// `a@2x.png`, ...): the core mounts the one for the screen's pixel
1573 /// ratio. Empty for a single file.
1574 pub scales: ImageScales,
1575 /// The image's bytes when they are in memory (a `data:` URI's, the
1576 /// blob of a `blob:` URL): the platforms decode these instead of
1577 /// loading [`Self::uri`], which stays the cache key.
1578 pub data: Option<crate::image::ImageData>,
1579}
1580
1581impl ImageSource {
1582 /// This source with its bytes in hand when its URI holds them: a
1583 /// `data:` URI decoded (once, when the source is set) and named by a
1584 /// short key. Other sources stay as they are. A `data:` URI that does
1585 /// not decode becomes an empty one (the platforms then report the
1586 /// error): left as it is, an app could write another image's key
1587 /// (`data:<type>;nsh-key=<digest>`, which has no comma) and ask the
1588 /// process-wide caches whether some surface shows those bytes.
1589 #[must_use]
1590 pub fn inline(self) -> ImageSource {
1591 if self.data.is_some() || !self.uri.starts_with("data:") {
1592 return self;
1593 }
1594 match crate::image::decode_data_uri(&self.uri) {
1595 Ok((mime, bytes)) => {
1596 let mime = mime.to_owned();
1597 self.with_bytes(&mime, bytes.into())
1598 }
1599 Err(_) => ImageSource {
1600 uri: "data:,".into(),
1601 ..self
1602 },
1603 }
1604 }
1605
1606 /// Its natural size in points: [`Self::size`], else, for bytes in
1607 /// hand (a `data:` URI, a blob), the size their header gives, one
1608 /// pixel a point. A URL's size is known only once it loads.
1609 pub fn natural_size(&self) -> Option<Size<Points>> {
1610 self.size.or_else(|| {
1611 let data = self.data.as_ref()?;
1612 crate::image::Natural::of(data.bytes()).map(|n| n.points(1.0))
1613 })
1614 }
1615
1616 /// This source showing `data`, of media type `mime` (a blob's bytes),
1617 /// named by a digest of the bytes: equal images share their loads and
1618 /// cache entries, whatever URL named them.
1619 #[must_use]
1620 pub fn with_bytes(self, mime: &str, data: crate::image::ImageData) -> ImageSource {
1621 ImageSource {
1622 uri: crate::image::data_key(mime, &data).into(),
1623 data: Some(data),
1624 ..self
1625 }
1626 }
1627
1628 /// The URI to load at `pixel_ratio` device pixels per point: the
1629 /// variant [`ImageScales::pick`] chooses (`asset:/a.png` at 2 →
1630 /// `asset:/a@2x.png`), or [`Self::uri`] itself when there are no
1631 /// scales, the pick is the 1x file or the URI is not a plain
1632 /// `asset:/` path.
1633 pub(crate) fn uri_for(&self, pixel_ratio: f32) -> Arc<str> {
1634 match self.variant(pixel_ratio) {
1635 Some(scale) => variant_uri(&self.uri, scale).into(),
1636 None => self.uri.clone(),
1637 }
1638 }
1639
1640 /// This source for a screen of `pixel_ratio` device pixels per point:
1641 /// the [`Self::uri_for`] the core picks for what it mounts, for what
1642 /// goes around it (a menu item's icon).
1643 #[must_use]
1644 pub fn at_pixel_ratio(&self, pixel_ratio: f32) -> ImageSource {
1645 ImageSource {
1646 uri: self.uri_for(pixel_ratio),
1647 ..self.clone()
1648 }
1649 }
1650
1651 /// The scale of the variant loaded at `pixel_ratio`, when it is not
1652 /// [`Self::uri`] itself. A query or a fragment is no part of a file
1653 /// name the bundler wrote, so such a URI is loaded as it is.
1654 pub(crate) fn variant(&self, pixel_ratio: f32) -> Option<f32> {
1655 if self.scales.is_empty()
1656 || !self.uri.starts_with("asset:/")
1657 || self.uri.contains(['?', '#'])
1658 {
1659 return None;
1660 }
1661 self.scales.pick(pixel_ratio).filter(|s| *s != 1.0)
1662 }
1663
1664 /// This source as the platform loads it at `pixel_ratio`: the chosen
1665 /// variant's URI, the same size in points and no scales.
1666 pub(crate) fn resolved(&self, pixel_ratio: f32) -> ImageSource {
1667 ImageSource {
1668 uri: self.uri_for(pixel_ratio),
1669 size: self.size,
1670 scales: ImageScales::NONE,
1671 data: self.data.clone(),
1672 }
1673 }
1674}
1675
1676/// `asset:/dir/a.png` at 2 → `asset:/dir/a@2x.png` (`@1.5x` at 1.5).
1677fn variant_uri(uri: &str, scale: f32) -> String {
1678 let name = uri.rfind('/').map_or(0, |i| i + 1);
1679 let (stem, ext) = match uri[name..].rfind('.') {
1680 Some(dot) if dot > 0 => uri.split_at(name + dot),
1681 _ => (uri, ""),
1682 };
1683 format!("{stem}@{scale}x{ext}")
1684}
1685
1686/// The pixel densities an image asset can ship in, as the file name
1687/// suffix says (`@1.5x` ... `@4x`; the file without a suffix is 1x). The
1688/// bundler looks for these siblings of an imported image.
1689pub const IMAGE_SCALES: [f32; 5] = [1.0, 1.5, 2.0, 3.0, 4.0];
1690
1691/// How many entries of a JS `scales` list are read: more than an asset
1692/// lists (one per scale of [`IMAGE_SCALES`]), and few enough that a sparse
1693/// array of a huge length costs nothing.
1694pub(crate) const SCALES_READ: usize = 8;
1695
1696/// A set of [`IMAGE_SCALES`]: the variants an image asset has. Collected
1697/// from scales (`[1.0, 2.0].into_iter().collect()`), it keeps those of
1698/// [`IMAGE_SCALES`] and leaves any other value (NaN, negative, `2.5`)
1699/// out.
1700#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
1701pub struct ImageScales(u8);
1702
1703impl ImageScales {
1704 /// No variants: the URI is the only file.
1705 pub const NONE: ImageScales = ImageScales(0);
1706
1707 /// This set with `scale` added, when it is one of [`IMAGE_SCALES`].
1708 #[must_use]
1709 pub(crate) fn with(self, scale: f32) -> ImageScales {
1710 match IMAGE_SCALES.iter().position(|s| *s == scale) {
1711 Some(i) => ImageScales(self.0 | 1 << i),
1712 None => self,
1713 }
1714 }
1715
1716 /// Whether the set has no scale.
1717 pub fn is_empty(self) -> bool {
1718 self.0 == 0
1719 }
1720
1721 /// The scales in the set, smallest first.
1722 pub fn iter(self) -> impl Iterator<Item = f32> {
1723 IMAGE_SCALES
1724 .into_iter()
1725 .enumerate()
1726 .filter(move |(i, _)| self.0 & 1 << i != 0)
1727 .map(|(_, s)| s)
1728 }
1729
1730 /// The scale to load at `pixel_ratio`, as React Native picks: the
1731 /// smallest that is at least the ratio, otherwise the largest. `None`
1732 /// for an empty set.
1733 pub(crate) fn pick(self, pixel_ratio: f32) -> Option<f32> {
1734 self.iter()
1735 .find(|s| *s >= pixel_ratio)
1736 .or_else(|| self.iter().last())
1737 }
1738}
1739
1740impl FromIterator<f32> for ImageScales {
1741 fn from_iter<I: IntoIterator<Item = f32>>(values: I) -> ImageScales {
1742 values.into_iter().fold(Self::NONE, ImageScales::with)
1743 }
1744}
1745
1746/// Keyboard layout of an input (`keyboardType`).
1747#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
1748pub enum KeyboardType {
1749 /// Full keyboard.
1750 #[default]
1751 Default,
1752 /// Digits only (`number-pad`): no sign, no decimal separator.
1753 #[prop(rename = "number-pad")]
1754 Number,
1755 /// Digits and a decimal separator (`decimal-pad`).
1756 #[prop(rename = "decimal-pad")]
1757 Decimal,
1758 /// Numbers (`numeric`, React Native's): iOS's decimal pad, Android's
1759 /// number keyboard with a sign and a decimal separator.
1760 Numeric,
1761 /// Digits, a sign and punctuation (`numbers-and-punctuation`): iOS's
1762 /// numbers and punctuation keyboard, Android's signed decimal number
1763 /// keyboard (the closest it has).
1764 #[prop(rename = "numbers-and-punctuation")]
1765 NumbersAndPunctuation,
1766 /// E-mail addresses (`email-address`).
1767 #[prop(rename = "email-address")]
1768 Email,
1769 /// Phone numbers (`phone-pad`).
1770 #[prop(rename = "phone-pad")]
1771 Phone,
1772 /// URLs (`url`).
1773 Url,
1774}
1775
1776/// The keyboard's look (`keyboardAppearance`, iOS).
1777#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
1778pub enum KeyboardAppearance {
1779 /// The system's: follows the app's appearance (default).
1780 #[default]
1781 Default,
1782 /// Light.
1783 Light,
1784 /// Dark.
1785 Dark,
1786}
1787
1788/// Label of the return key (`returnKeyType`).
1789#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
1790pub enum ReturnKeyType {
1791 /// Return / new line.
1792 #[default]
1793 Default,
1794 /// Done.
1795 Done,
1796 /// Go.
1797 Go,
1798 /// Next.
1799 Next,
1800 /// Search.
1801 Search,
1802 /// Send.
1803 Send,
1804}
1805
1806/// What an input does with what the user pastes (`pasteBehavior`); it
1807/// reports it either way (`onPaste`).
1808#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
1809pub enum PasteBehavior {
1810 /// Inserts the pasted text (default). Images and files are never
1811 /// inserted: a text input holds text.
1812 #[default]
1813 Insert,
1814 /// Inserts nothing: the app does what it wants with `onPaste`'s text,
1815 /// images and files.
1816 Report,
1817}
1818
1819/// A bar button UIKit draws itself, with the system's look, symbol or
1820/// label (`ios={{ headerLeftSystemItem }}`, `ios={{ headerRightSystemItem }}`).
1821#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
1822pub enum HeaderSystemItem {
1823 /// A plus (`UIBarButtonSystemItemAdd`).
1824 #[default]
1825 Add,
1826 /// The system's "Done" (`UIBarButtonSystemItemDone`).
1827 Done,
1828 /// A close mark (`UIBarButtonSystemItemClose`).
1829 Close,
1830 /// The system's "Edit" (`UIBarButtonSystemItemEdit`).
1831 Edit,
1832 /// A compose symbol (`UIBarButtonSystemItemCompose`).
1833 Compose,
1834 /// A magnifying glass (`UIBarButtonSystemItemSearch`).
1835 Search,
1836 /// The share symbol (`UIBarButtonSystemItemAction`).
1837 Share,
1838 /// A trash can (`UIBarButtonSystemItemTrash`).
1839 Trash,
1840 /// The system's "Save" (`UIBarButtonSystemItemSave`).
1841 Save,
1842 /// The system's "Cancel" (`UIBarButtonSystemItemCancel`).
1843 Cancel,
1844}
1845
1846/// What an iOS bar button shows (`ios={{ headerLeftItems }}`, `ios={{
1847/// headerRightItems }}`): a system item, an SF Symbol, a text label, or an
1848/// SF Symbol with a title next to it.
1849#[derive(Debug, Clone, PartialEq, Eq)]
1850#[non_exhaustive]
1851pub enum HeaderItemContent {
1852 /// A [`HeaderSystemItem`].
1853 SystemItem(HeaderSystemItem),
1854 /// An SF Symbol's name.
1855 Symbol(Arc<str>),
1856 /// A text title on the button.
1857 Label(Arc<str>),
1858 /// An SF Symbol (its name) and a title after it, in one button
1859 /// (`{ symbol, title }`).
1860 SymbolTitle {
1861 /// The SF Symbol's name.
1862 symbol: Arc<str>,
1863 /// The text after it.
1864 title: Arc<str>,
1865 },
1866}
1867
1868/// An iOS navigation-bar button (`ios={{ headerLeftItems }}`, `ios={{
1869/// headerRightItems }}`), as
1870/// the platform sees it: numeric ids for presses and menu actions report
1871/// the root's [`EventKind::Menu`]. Rust apps build one with
1872/// [`crate::element::header::HeaderItem`] (handlers included); JS sets
1873/// `onPress` / `MenuItem.onSelect` and the runtime assigns the ids.
1874#[derive(Debug, Clone, PartialEq)]
1875#[non_exhaustive]
1876pub struct HeaderItem {
1877 /// Optional key for keeping a `UIBarButtonItem` across updates: a kept
1878 /// button takes the new title, symbol, label, menu and state in place.
1879 /// Without a key, a button is kept only while its position and its
1880 /// content are unchanged; any other change makes a new one. It is also
1881 /// the button's accessibility identifier, as a view's `testID` is:
1882 /// tests name it by `id:<key>`.
1883 pub key: Option<Arc<str>>,
1884 /// What the button shows.
1885 pub content: HeaderItemContent,
1886 /// VoiceOver's label when the content is a system item or symbol
1887 /// (the content's own text when it is a [`HeaderItemContent::Label`];
1888 /// the title when it is a [`HeaderItemContent::SymbolTitle`] and this
1889 /// is `None`).
1890 pub label: Option<Arc<str>>,
1891 /// Whether the button is disabled.
1892 pub disabled: bool,
1893 /// Reported as the root's [`EventKind::Menu`] when pressed with no
1894 /// menu (0: no handler).
1895 pub press_id: u32,
1896 /// A native pull-down menu of [`crate::desktop::MenuItem`]s; a press
1897 /// opens it instead of reporting [`Self::press_id`].
1898 pub menu: Option<Vec<crate::desktop::MenuItem>>,
1899 /// Whether the button shares its background with the bar buttons next
1900 /// to it (default true). iOS 26 and later draw neighboring buttons in
1901 /// one glass capsule; false gives this one a capsule of its own
1902 /// (`UIBarButtonItem.sharesBackground`). Earlier iOS versions draw no
1903 /// such background and ignore it.
1904 pub shares_background: bool,
1905}
1906
1907impl HeaderItem {
1908 /// Builds a platform header button from its fields. `#[non_exhaustive]`
1909 /// keeps a struct literal off other crates; prefer
1910 /// [`crate::element::header::HeaderItem`] in Rust apps.
1911 #[doc(hidden)]
1912 pub fn from_parts(
1913 key: Option<Arc<str>>,
1914 content: HeaderItemContent,
1915 label: Option<Arc<str>>,
1916 disabled: bool,
1917 press_id: u32,
1918 menu: Option<Vec<crate::desktop::MenuItem>>,
1919 ) -> Self {
1920 Self {
1921 key,
1922 content,
1923 label,
1924 disabled,
1925 press_id,
1926 menu,
1927 shares_background: true,
1928 }
1929 }
1930
1931 /// Sets [`Self::shares_background`] on a button made by
1932 /// [`Self::from_parts`].
1933 #[doc(hidden)]
1934 pub fn with_shares_background(mut self, shares: bool) -> Self {
1935 self.shares_background = shares;
1936 self
1937 }
1938}
1939
1940/// What return does in an input (`submitBehavior`).
1941#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
1942pub enum SubmitBehavior {
1943 /// Reports `onSubmit` and keeps the focus.
1944 Submit,
1945 /// Reports `onSubmit` and unfocuses the input.
1946 #[default]
1947 BlurAndSubmit,
1948 /// Inserts a line break (multiline inputs; a single line submits).
1949 Newline,
1950}
1951
1952/// Automatic capitalization (`autoCapitalize`).
1953#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
1954pub enum AutoCapitalize {
1955 /// Never.
1956 None,
1957 /// First letter of each sentence (default).
1958 #[default]
1959 Sentences,
1960 /// First letter of each word.
1961 Words,
1962 /// Every letter.
1963 Characters,
1964}
1965
1966/// When a scroll view dismisses the keyboard (`keyboardDismissMode`).
1967#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
1968pub enum KeyboardDismissMode {
1969 /// Never (default).
1970 #[default]
1971 None,
1972 /// As soon as a drag starts.
1973 #[prop(rename = "on-drag")]
1974 OnDrag,
1975 /// Follows the finger while dragging down (iOS).
1976 Interactive,
1977}
1978
1979/// The HTML element the web draws a view or text as (`web={{ element }}`),
1980/// for what `role` cannot say: paragraphs, landmarks, lists, emphasis, ...
1981/// Headings come from `role="header"` with `accessibilityLevel` and links
1982/// from a `Link` with an `href`, everywhere. Only the web reads it; the
1983/// layout, styles and events stay the view's.
1984#[derive(Debug, Clone, Copy, PartialEq, Eq, PropEnum)]
1985pub enum WebElement {
1986 /// A paragraph (`<p>`).
1987 P,
1988 /// Navigation links (`<nav>`).
1989 Nav,
1990 /// The header of the page or a section (`<header>`), a landmark; a
1991 /// heading is `role="header"`.
1992 Header,
1993 /// The footer of the page or a section (`<footer>`).
1994 Footer,
1995 /// The page's main content (`<main>`).
1996 Main,
1997 /// A self-contained composition (`<article>`).
1998 Article,
1999 /// A section of a document (`<section>`).
2000 Section,
2001 /// Content aside from the main content (`<aside>`).
2002 Aside,
2003 /// An unordered list (`<ul>`).
2004 Ul,
2005 /// An ordered list (`<ol>`).
2006 Ol,
2007 /// An item of a list (`<li>`).
2008 Li,
2009 /// Strong importance (`<strong>`).
2010 Strong,
2011 /// Emphasis (`<em>`).
2012 Em,
2013 /// A quotation (`<blockquote>`).
2014 Blockquote,
2015 /// A figure (`<figure>`).
2016 Figure,
2017 /// A figure's caption (`<figcaption>`).
2018 Figcaption,
2019 /// A date or time (`<time>`).
2020 Time,
2021 /// Contact information (`<address>`).
2022 Address,
2023}
2024
2025/// Which point of a page a snapping scroll view aligns to its start.
2026#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
2027pub enum SnapAlignment {
2028 /// The snap point at the viewport's start.
2029 #[default]
2030 Start,
2031 /// At its center.
2032 Center,
2033 /// At its end.
2034 End,
2035}
2036
2037/// Whether a tap in a scroll view dismisses the keyboard
2038/// (`keyboardShouldPersistTaps`).
2039#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2040pub enum KeyboardTaps {
2041 /// A tap only dismisses the keyboard (default): nothing inside acts on
2042 /// it; long presses and drags go on as with the keyboard down.
2043 #[default]
2044 Never,
2045 /// Taps never dismiss the keyboard.
2046 Always,
2047 /// Taps that nothing handles dismiss the keyboard.
2048 Handled,
2049}
2050
2051/// Which scroll bar a scroll view or list shows (`scrollbar`).
2052#[derive(Debug, Clone, PartialEq, Default)]
2053pub enum ScrollbarSetting {
2054 /// Its scroll bar (`true`, the default): the platform's indicator, or
2055 /// the app's built-in bar once the app set a theme for every view
2056 /// (`nsh/base`'s `Scrollbar.setTheme`).
2057 #[default]
2058 Shown,
2059 /// None (`false`).
2060 Hidden,
2061 /// The app's built-in bar drawn as this theme says (an object): the
2062 /// `ScrollbarTheme` of `nsh/base`, which reads it.
2063 Themed(Arc<crate::JsonValue>),
2064 /// The app's built-in bar drawn as this theme says, as Rust gave it: a
2065 /// value of the theme type of the UI set that makes bars, with its
2066 /// maker (`nsh_base::ScrollbarTheme` converts into this).
2067 ThemeValue(crate::element::ScrollbarThemeValue),
2068}
2069
2070impl From<bool> for ScrollbarSetting {
2071 fn from(shows: bool) -> Self {
2072 if shows { Self::Shown } else { Self::Hidden }
2073 }
2074}
2075
2076crate::static_reactive!(ScrollbarSetting: ScrollbarSetting, bool);
2077
2078/// How an `<image>` is shown, besides its source.
2079#[derive(Debug, Clone, PartialEq, HostProps)]
2080pub enum ImageProp {
2081 /// `placeholder`: shown until `src` has loaded (best a local asset).
2082 #[prop(js = "placeholder", on = IMAGE, shared)]
2083 Placeholder(Option<ImageSource>),
2084 /// `blurRadius`: blurs the image by this radius in points (decoded once, off
2085 /// the main thread).
2086 #[prop(js = "blurRadius", on = IMAGE)]
2087 BlurRadius(Points),
2088 /// `fadeDuration`: how long a loaded image fades in, in milliseconds
2089 /// (default: the platform's, 0 on iOS and 300 on Android, like React
2090 /// Native).
2091 #[prop(js = "fadeDuration", min = 0, on = IMAGE)]
2092 FadeDuration(Option<f32>),
2093 /// Set by `svg()` where the platform draws the SVG itself (the web): its
2094 /// `currentColor` is the element's text color
2095 /// ([`crate::mount::ImageOptions::current_color`]).
2096 #[prop(js = "svgCurrentColor", internal)]
2097 SvgCurrentColor(bool),
2098}
2099
2100/// A behavior property of a scroll view or list.
2101#[derive(Debug, Clone, PartialEq, HostProps)]
2102pub enum ScrollProp {
2103 /// `pagingEnabled`: stops at multiples of the viewport.
2104 #[prop(js = "pagingEnabled", on = SCROLLING)]
2105 Paging(bool),
2106 /// `snapToInterval`: stops at multiples of this length (0: off).
2107 #[prop(js = "snapToInterval", on = SCROLLING)]
2108 SnapInterval(Points),
2109 /// `snapToOffsets`: stops at these offsets.
2110 #[prop(js = "snapToOffsets", on = SCROLLING)]
2111 SnapOffsets(Vec<Points>),
2112 /// `snapToAlignment`: which point of an item aligns with the viewport with
2113 /// `snapToInterval`.
2114 #[prop(js = "snapToAlignment", on = SCROLLING)]
2115 SnapAlignment(SnapAlignment),
2116 /// `decelerationRate`: how fast a fling slows down: `"normal"`, `"fast"`, or
2117 /// the velocity kept per millisecond (0.998 / 0.99; 0 is the platform's
2118 /// default).
2119 #[prop(js = "decelerationRate", with = crate::js::host_values::deceleration, reset = ScrollProp::Deceleration(0.0), ts = "\"normal\" | \"fast\" | number", on = SCROLLING)]
2120 Deceleration(f32),
2121 /// `bounces`: overscroll past the edges (default true).
2122 #[prop(js = "bounces", default = true, on = SCROLLING)]
2123 Bounces(bool),
2124 /// `scrollsToTop`: a tap at the top of the window (the status bar's)
2125 /// scrolls it to its top (default true; iOS and Mac Catalyst, where
2126 /// UIKit does it: elsewhere ignored).
2127 #[prop(js = "scrollsToTop", default = true, on = SCROLLING)]
2128 ScrollsToTop(bool),
2129 /// `smoothWheel`: a mouse wheel's notches glide to where they point,
2130 /// eased in and out over 100–200 ms as Chromium's do, a run of notches
2131 /// one motion (default false: the platform's own, which lands at once
2132 /// on macOS and Linux and glides briefly on Windows). The desktops
2133 /// (macOS, Windows, Linux, GPUI); iOS and Android scroll with the
2134 /// system's views, the web with the browser's (both ignore it), as
2135 /// they do when the system reduces motion.
2136 #[prop(js = "smoothWheel", on = SCROLLING)]
2137 SmoothWheel(bool),
2138 /// `wheelLineHeight`: how far a mouse wheel's line scrolls, in points (0,
2139 /// the default: the platform's own, 10 on macOS, 16 on Windows, a
2140 /// notch's length after the view's on Linux). A line is the platform's:
2141 /// a notch on Linux, a third of one on Windows (the system's default),
2142 /// about one per notch on macOS, which accelerates quick runs. The
2143 /// desktops; ignored where `smoothWheel` is.
2144 #[prop(js = "wheelLineHeight", min = 0, on = SCROLLING)]
2145 WheelLineHeight(Points),
2146 /// `contentInset`: room around the content.
2147 #[prop(js = "contentInset", on = SCROLLING)]
2148 ContentInset(EdgeInsets),
2149 /// `scrollbarInset`: how far the scroll indicator keeps from each edge
2150 /// of the view, for bars that float over it (React Native's
2151 /// `scrollIndicatorInsets`); the content still scrolls under them.
2152 #[prop(js = "scrollbarInset", on = SCROLLING)]
2153 ScrollbarInset(EdgeInsets),
2154 /// `contentOffset`: where it starts.
2155 #[prop(js = "contentOffset", with = crate::js::host_values::content_offset, once, ts = "Partial<Point>", on = SCROLLING)]
2156 ContentOffset(Point<Points>),
2157 /// `keyboardShouldPersistTaps`: whether a tap dismisses the keyboard: `"never"`
2158 /// (default: the tap only dismisses it), `"always"` (never dismisses),
2159 /// `"handled"` (unless something handles the tap).
2160 #[prop(js = "keyboardShouldPersistTaps", with = crate::js::host_values::keyboard_taps, reset = ScrollProp::KeyboardTaps(KeyboardTaps::Never), ts = "\"never\" | \"always\" | \"handled\" | boolean", on = SCROLLING)]
2161 KeyboardTaps(KeyboardTaps),
2162 /// `scrollEventThrottle`: minimum milliseconds between `onScroll` events (at
2163 /// most one per frame anyway).
2164 #[prop(js = "scrollEventThrottle", on = SCROLLING)]
2165 EventThrottle(f32),
2166 /// `disableIntervalMomentum`: a fling moves one snap point at most.
2167 #[prop(js = "disableIntervalMomentum", on = SCROLLING)]
2168 DisableIntervalMomentum(bool),
2169 /// `minimumZoomScale`: the smallest zoom (default 1).
2170 #[prop(js = "minimumZoomScale", default = 1.0, on = SCROLL)]
2171 MinZoom(f32),
2172 /// `maximumZoomScale`: pinching zooms the content when it is above
2173 /// `minimumZoomScale` (default 1 both); zoomed in, it scrolls both ways.
2174 #[prop(js = "maximumZoomScale", default = 1.0, on = SCROLL)]
2175 MaxZoom(f32),
2176 /// `zoomScale`: zooms to this scale when it changes (the user's zoom is kept
2177 /// otherwise).
2178 #[prop(js = "zoomScale", default = 1.0, on = SCROLL)]
2179 Zoom(f32),
2180 /// `bouncesZoom`: pinching may go past the limits and springs back (default
2181 /// true).
2182 #[prop(js = "bouncesZoom", default = true, on = SCROLL)]
2183 BouncesZoom(bool),
2184 /// `zoomable`: the user can pinch to zoom (default true).
2185 #[prop(js = "zoomable", default = true, on = SCROLL, shared)]
2186 Pinch(bool),
2187 /// `centerContent`: content smaller than the viewport (zoomed out) is centered.
2188 #[prop(js = "centerContent", on = SCROLL)]
2189 CenterContent(bool),
2190 /// `refreshIndicator`: `{ height }`, the app draws its own
2191 /// pull-to-refresh indicator (from `pullValue`), `height` points tall:
2192 /// the platform's spinner is hidden, a pull refreshes once it reaches
2193 /// `height`, and refreshing keeps `height` above the content.
2194 #[prop(js = "refreshIndicator", with = crate::js::host_values::refresh_indicator, reset = ScrollProp::RefreshIndicator(None), ts = "{ height: number }", on = SCROLLING)]
2195 RefreshIndicator(Option<Points>),
2196}
2197
2198/// What a list cell holds.
2199#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2200pub enum CellSlot {
2201 /// A recycled item cell in this slot.
2202 Item(u32),
2203 /// `header`.
2204 Header,
2205 /// `footer`.
2206 Footer,
2207 /// `empty` (shown while there are no items).
2208 Empty,
2209}
2210
2211/// A list's `contentStyle` (or `contentClass`): padding around the content, gaps
2212/// between rows and columns, and cell alignment on the cross axis.
2213#[derive(Debug, Clone, Copy, PartialEq, Default)]
2214pub struct ListContentStyle {
2215 /// Padding around the content.
2216 pub padding: EdgeInsets,
2217 /// Gap between rows (vertical lists) / columns (horizontal lists).
2218 pub row_gap: Points,
2219 /// Gap between columns (`numColumns`) of vertical lists.
2220 pub column_gap: Points,
2221 /// Cell alignment on the cross axis: stretch (default), flex-start, center
2222 /// or flex-end.
2223 pub align_items: Option<taffy::AlignItems>,
2224}
2225
2226/// Where a list rests (`alignment`), as GPUI's `ListAlignment`.
2227#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
2228#[non_exhaustive]
2229pub enum ListAlignment {
2230 /// At the start of its content (default).
2231 #[default]
2232 Top,
2233 /// At the end, like a chat log: the list opens there, stays there while
2234 /// the content grows and content shorter than the viewport lies at its
2235 /// bottom. Scrolled up, what is visible stays where it is; scrolled back
2236 /// to the end, the list stays there again.
2237 Bottom,
2238}
2239
2240/// What a list scrolls in (`viewport`), fixed when the list is made.
2241#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
2242#[non_exhaustive]
2243pub enum ListViewport {
2244 /// A scroll view of its own (default).
2245 #[default]
2246 Own,
2247 /// The scroll view around it: the list lies in its parent's layout at
2248 /// its full length and renders the rows near that scroll view's
2249 /// viewport, so headers above it and other lists scroll with it as
2250 /// one page.
2251 Parent,
2252}
2253
2254/// When list items count as viewable (React Native's `viewabilityConfig`).
2255/// Without thresholds, any visible pixel does.
2256#[derive(Debug, Clone, Copy, PartialEq, Default)]
2257pub struct Viewability {
2258 /// How much of the viewport an item must cover (TS:
2259 /// `viewAreaCoverageThreshold`, 0 to 1).
2260 pub view_area_coverage_threshold: Option<Percentage>,
2261 /// How much of an item must be visible (TS: `itemVisibleThreshold`, 0
2262 /// to 1).
2263 pub item_visible_threshold: Option<Percentage>,
2264}
2265
2266/// Where a header item goes (`<headeritem slot>`).
2267#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
2268pub enum HeaderSlot {
2269 /// Leading, after the back button.
2270 #[default]
2271 Left,
2272 /// Trailing.
2273 Right,
2274 /// Replaces the title.
2275 Title,
2276 /// Replaces the whole bar (`header`), where the platform draws it.
2277 Header,
2278}
2279
2280/// What a shader transition without a `source` runs (`fallback`).
2281#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
2282pub enum TransitionFallback {
2283 /// A cross-fade ([`crate::shader::crossfade`]).
2284 #[default]
2285 Fade,
2286 /// A cut: the children change at once (`"none"`).
2287 #[prop(rename = "none")]
2288 Cut,
2289}
2290
2291/// How a screen enters and leaves (`animation`).
2292#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
2293pub enum ScreenAnimation {
2294 /// The platform's push / pop transition (`"slide"` too: a
2295 /// dialog's default, which shares the prop).
2296 #[default]
2297 #[prop(alias = "slide")]
2298 Default,
2299 /// Cross-fade.
2300 Fade,
2301 /// No animation.
2302 None,
2303}
2304
2305/// Where a page's title sits in the native header (`headerTitleAlign`).
2306/// Android's toolbar honors it. iOS's system bar always centers the title
2307/// and ignores the value; the desktops and the web draw no native header.
2308#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
2309pub enum HeaderTitleAlign {
2310 /// At the start, after the back button or the leading item (Android's
2311 /// default).
2312 #[default]
2313 Left,
2314 /// Centered across the header, between the leading and trailing items.
2315 Center,
2316}
2317
2318/// A screen option (`<NavPage title headerVisible ...>`).
2319#[derive(Debug, Clone, PartialEq, HostProps)]
2320pub enum ScreenProp {
2321 /// `title`: the header's title (iOS and Android: the system header;
2322 /// ignored on the desktops and the web, which show the app's `header`).
2323 #[prop(js = "title", on = SCREEN)]
2324 Title(Option<Arc<str>>),
2325 /// `headerVisible`: the system header shows (default true; iOS and
2326 /// Android).
2327 #[prop(js = "headerVisible", default = true, on = SCREEN)]
2328 HeaderVisible(bool),
2329 /// `hidesBottomBarWhenPushed`: the system tab bar leaves while this page
2330 /// is on top, moving with the transition (iOS and Android).
2331 #[prop(js = "hidesBottomBarWhenPushed", on = SCREEN)]
2332 HidesBottomBarWhenPushed(bool),
2333 /// `headerLargeTitle` (iOS: the system header; ignored elsewhere): a
2334 /// large title; the content scrolls under the header.
2335 #[prop(js = "headerLargeTitle", on = SCREEN)]
2336 HeaderLargeTitle(bool),
2337 /// `headerTransparent`: the content extends under the system header
2338 /// (iOS and Android).
2339 #[prop(js = "headerTransparent", on = SCREEN)]
2340 HeaderTransparent(bool),
2341 /// `headerShadowVisible` (iOS: the system header; Android's has none):
2342 /// the hairline under the header. Off, the bar has no shadow line, as
2343 /// iOS 26's own bars.
2344 #[prop(js = "headerShadowVisible", default = true, on = SCREEN)]
2345 HeaderShadowVisible(bool),
2346 /// `headerTitleAlign` (Android: the system header): where the title
2347 /// sits, `"left"` (the default) or `"center"`. iOS's system bar always
2348 /// centers the title and ignores the value; the desktops and the web
2349 /// draw no native header.
2350 #[prop(js = "headerTitleAlign", on = SCREEN)]
2351 HeaderTitleAlign(HeaderTitleAlign),
2352 /// `headerBackgroundOnScroll` (iOS: the system header; ignored
2353 /// elsewhere): with `headerTransparent`, the header stays clear while
2354 /// the content rests at its top and shows its background once the
2355 /// content scrolls under it, as UIKit's own bars do.
2356 #[prop(js = "headerBackgroundOnScroll", on = SCREEN)]
2357 HeaderBackgroundOnScroll(bool),
2358 /// `headerBackTitle` (iOS: the system header; ignored elsewhere): the
2359 /// label of the back button leading back to this page.
2360 #[prop(js = "headerBackTitle", on = SCREEN)]
2361 HeaderBackTitle(Option<Arc<str>>),
2362 /// `ios={{ headerRightSystemItem }}`: UIKit's own bar button in the
2363 /// system header's trailing slot, in place of the view of
2364 /// `headerRight`; a press on it is a press on the first pressable view
2365 /// of `headerRight`. Without a `headerRight`, nothing is drawn there.
2366 #[prop(ios = "headerRightSystemItem", on = SCREEN)]
2367 HeaderRightSystemItem(Option<HeaderSystemItem>),
2368 /// `ios={{ headerLeftSystemItem }}`: as `headerRightSystemItem`, in the
2369 /// leading slot, pressing the first pressable view of `headerLeft`.
2370 #[prop(ios = "headerLeftSystemItem", on = SCREEN)]
2371 HeaderLeftSystemItem(Option<HeaderSystemItem>),
2372 /// `ios={{ headerRightSymbol }}`: UIKit's own bar button showing the SF
2373 /// Symbol of that name (`"slider.horizontal.3"`) in the trailing slot,
2374 /// in place of the view of `headerRight`; a press on it is a press on
2375 /// the first pressable view of `headerRight`. `headerRightSystemItem`
2376 /// wins over it; an unknown name draws the view of `headerRight`.
2377 #[prop(ios = "headerRightSymbol", on = SCREEN)]
2378 HeaderRightSymbol(Option<Arc<str>>),
2379 /// `ios={{ headerLeftSymbol }}`: as `headerRightSymbol`, in the leading
2380 /// slot, pressing the first pressable view of `headerLeft`.
2381 #[prop(ios = "headerLeftSymbol", on = SCREEN)]
2382 HeaderLeftSymbol(Option<Arc<str>>),
2383 /// `ios={{ headerRightItems }}`: the trailing UIKit bar buttons, first
2384 /// at the trailing edge; a non-empty list wins over
2385 /// `headerRightSystemItem` / `headerRightSymbol` and leaves
2386 /// `headerRight`'s views out of the iOS bar (they stay the fallback on
2387 /// other platforms). An empty list is unset. A press without a menu,
2388 /// or a menu action, reports the root's `onMenu` with the item's id
2389 /// (its `onPress` / `onSelect`).
2390 #[prop(ios = "headerRightItems", on = SCREEN)]
2391 HeaderRightItems(Vec<HeaderItem>),
2392 /// `ios={{ headerLeftItems }}`: as `headerRightItems`, the leading
2393 /// UIKit bar buttons, first at the leading edge, after the back button
2394 /// when one shows; a non-empty list wins over `headerLeftSystemItem` /
2395 /// `headerLeftSymbol` and leaves `headerLeft`'s views out of the iOS
2396 /// bar.
2397 #[prop(ios = "headerLeftItems", on = SCREEN)]
2398 HeaderLeftItems(Vec<HeaderItem>),
2399 /// `headerBackVisible`: the system header's back button shows (default
2400 /// true; iOS and Android).
2401 #[prop(js = "headerBackVisible", default = true, on = SCREEN)]
2402 HeaderBackVisible(bool),
2403 /// `popOnSwipe`: the interactive back gesture pops (iOS swipe back,
2404 /// Android predictive back following the finger); the back buttons pop
2405 /// either way (default true).
2406 #[prop(js = "popOnSwipe", default = true, on = SCREEN)]
2407 PopOnSwipe(bool),
2408 /// `popOnBack`: the user leaves the page with the back buttons (header,
2409 /// Android back, the desktops' back keys and mouse button, the
2410 /// browser's back) and the swipe back (default true). False keeps it,
2411 /// e.g. to confirm discarding changes in `onBackPress` (called on every
2412 /// back press) and then `pop()`. Decided natively when the system asks,
2413 /// so set it before the user acts.
2414 #[prop(js = "popOnBack", default = true, on = SCREEN)]
2415 PopOnBack(bool),
2416 /// `animation`: how the page enters and leaves.
2417 #[prop(js = "animation", on = SCREEN)]
2418 Animation(ScreenAnimation),
2419 /// `statusBar`: what the status bar shows while the page or dialog is
2420 /// up (iOS and Android; ignored on the desktops and the web), as a view
2421 /// controller's `preferredStatusBarStyle` decides it on iOS. The most
2422 /// recently shown page or dialog wins, field by field, over the pages
2423 /// below it and over the app's default (`nsh.json` `statusBar`). Pages
2424 /// and dialogs share it.
2425 #[prop(js = "statusBar", on = SCREEN | MODAL)]
2426 StatusBar(Option<StatusBarSetting>),
2427 /// `ios={{ supportedOrientations }}` / `android={{ supportedOrientations }}`:
2428 /// the orientations the screen may take while the page is shown
2429 /// (default: the app's). Of the pages in the tree and displayed (not
2430 /// under `display: none`, as a tab not shown is), the most recently
2431 /// shown one with a setting decides; the core sends the result as
2432 /// [`Command::Orientations`].
2433 ///
2434 /// [`crate::ModalConfig::PORTRAIT`] bits.
2435 #[prop(ios = "supportedOrientations", android = "supportedOrientations", with = crate::js::host_values::page_orientations, reset = ScreenProp::Orientations(0), ts = "(\"portrait\" | \"portrait-upside-down\" | \"landscape\" | \"landscape-left\" | \"landscape-right\")[]", on = SCREEN, shared)]
2436 Orientations(u8),
2437}
2438
2439/// How a modal appears (`animation`).
2440#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
2441pub enum ModalAnimation {
2442 /// Slides up from the bottom (default).
2443 #[default]
2444 Slide,
2445 /// Fades in.
2446 Fade,
2447 /// Appears at once.
2448 None,
2449}
2450
2451/// How a modal covers the screen (`presentation`).
2452#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
2453pub enum ModalPresentation {
2454 /// Covers the whole screen (default).
2455 #[default]
2456 FullScreen,
2457 /// A sheet that leaves the presenting content visible behind it.
2458 PageSheet,
2459 /// A smaller centered sheet on large screens.
2460 FormSheet,
2461}
2462
2463/// A height a bottom sheet rests at (TS `SheetDetent`): `nsh-base`'s
2464/// `Sheet` and a dialog presented as an iOS sheet
2465/// ([`ModalPresentation::PageSheet`] / [`ModalPresentation::FormSheet`])
2466/// take a list of them as `detents`. Measured from the bottom of the
2467/// screen, never taller than the screen below the status bar.
2468#[derive(Debug, Clone, Copy, PartialEq)]
2469pub enum SheetDetent {
2470 /// About half the screen (TS `"medium"`).
2471 Medium,
2472 /// The screen below the status bar (TS `"large"`).
2473 Large,
2474 /// This many points tall (TS `{ height }`).
2475 Height(Points),
2476 /// This share, from 0 to 1, of the screen below the status bar (TS
2477 /// `{ fraction }`).
2478 Fraction(Percentage),
2479}
2480
2481impl SheetDetent {
2482 /// As JSON: `"medium"`, `"large"`, `{ "height": n }` or
2483 /// `{ "fraction": n }`, as JS has it (the payload of
2484 /// [`EventKind::DetentChange`]).
2485 pub fn to_json(self) -> crate::JsonValue {
2486 let object = |key: &str, n: f32| {
2487 let mut map = serde_json::Map::new();
2488 map.insert(key.to_owned(), serde_json::json!(n));
2489 crate::JsonValue::Object(map)
2490 };
2491 match self {
2492 Self::Medium => crate::JsonValue::from("medium"),
2493 Self::Large => crate::JsonValue::from("large"),
2494 Self::Height(height) => object("height", height.0),
2495 Self::Fraction(fraction) => object("fraction", fraction.0),
2496 }
2497 }
2498
2499 /// The detent JSON [`Self::to_json`] gives; `None` for anything else.
2500 pub fn from_json(value: &crate::JsonValue) -> Option<Self> {
2501 if let Some(name) = value.as_str() {
2502 return match name {
2503 "medium" => Some(Self::Medium),
2504 "large" => Some(Self::Large),
2505 _ => None,
2506 };
2507 }
2508 if let Some(height) = value.get("height").and_then(|v| v.as_f64()) {
2509 return Self::of_height(height);
2510 }
2511 Self::of_fraction(value.get("fraction").and_then(|v| v.as_f64())?)
2512 }
2513
2514 /// `{ height }`, a height a sheet can rest at: finite, 0 or more.
2515 pub(crate) fn of_height(height: f64) -> Option<Self> {
2516 (height.is_finite() && height >= 0.0).then_some(Self::Height(Points(height as f32)))
2517 }
2518
2519 /// `{ fraction }`, a share from 0 to 1 (`NaN` is none).
2520 pub(crate) fn of_fraction(fraction: f64) -> Option<Self> {
2521 (0.0..=1.0)
2522 .contains(&fraction)
2523 .then_some(Self::Fraction(Percentage(fraction as f32)))
2524 }
2525
2526 /// The payload of [`EventKind::DetentChange`]: `{ detent }`.
2527 pub fn change_payload(self) -> EventPayload {
2528 let mut map = serde_json::Map::new();
2529 map.insert("detent".to_owned(), self.to_json());
2530 EventPayload::Json(crate::JsonValue::Object(map))
2531 }
2532}
2533
2534impl crate::element::JsValue for SheetDetent {
2535 fn ts_type(types: &mut crate::element::TsTypes) -> String {
2536 types.declare("SheetDetent", |_| {
2537 "/** A height a bottom sheet rests at: `\"medium\"` (about half the screen), `\"large\"` (the screen below the status bar), `{ height }` in points or `{ fraction }` (0 to 1) of the large one. */\n\
2538 export type SheetDetent = \"medium\" | \"large\" | { height: number } | { fraction: number };\n"
2539 .to_owned()
2540 })
2541 }
2542
2543 fn from_js(value: crate::element::JsIn<'_>) -> Result<Self, crate::element::PropError> {
2544 use crate::element::JsKind;
2545 let wanted = r#""medium", "large", `{ height }` (0 or more) or `{ fraction }` (0 to 1)"#;
2546 match value.kind() {
2547 JsKind::String => match value.as_string().as_deref() {
2548 Some("medium") => Ok(Self::Medium),
2549 Some("large") => Ok(Self::Large),
2550 _ => Err(value.expected(wanted)),
2551 },
2552 JsKind::Object => {
2553 let height = value.field("height")?;
2554 if let Some(height) = height.get().as_number() {
2555 return Self::of_height(height).ok_or_else(|| value.expected(wanted));
2556 }
2557 let fraction = value.field("fraction")?;
2558 fraction
2559 .get()
2560 .as_number()
2561 .and_then(Self::of_fraction)
2562 .ok_or_else(|| value.expected(wanted))
2563 }
2564 _ => Err(value.expected(wanted)),
2565 }
2566 }
2567
2568 fn to_js<'a>(
2569 &self,
2570 host: &'a dyn crate::element::JsHost,
2571 ) -> Result<crate::element::JsOwned<'a>, crate::element::PropError> {
2572 use crate::element::JsOwned;
2573 let object = |key: &str, n: f32| -> Result<JsOwned<'a>, crate::element::PropError> {
2574 let owned = JsOwned::new(host, host.new_object()?);
2575 host.set_field(owned.get().raw(), key, host.new_number(f64::from(n)))?;
2576 Ok(owned)
2577 };
2578 match *self {
2579 Self::Medium => "medium".to_owned().to_js(host),
2580 Self::Large => "large".to_owned().to_js(host),
2581 Self::Height(height) => object("height", height.0),
2582 Self::Fraction(fraction) => object("fraction", fraction.0),
2583 }
2584 }
2585}
2586
2587/// A modal option (`<Dialog …>`).
2588#[derive(Debug, Clone, PartialEq, HostProps)]
2589pub enum ModalProp {
2590 /// `animation`: how the dialog appears. Pages and dialogs share the
2591 /// name, so JS's value arrives as [`ScreenProp::Animation`], which the
2592 /// core takes for this on a dialog.
2593 Animation(ModalAnimation),
2594 /// `presentation`: `"pageSheet"` / `"formSheet"` keep what is behind
2595 /// visible (iOS; ignored on Android, the desktops and the web, where a
2596 /// dialog is a transparent layer over the window and the app's popup
2597 /// and backdrop are all it shows).
2598 #[prop(js = "presentation", on = MODAL)]
2599 Presentation(ModalPresentation),
2600 /// `statusBarTranslucent` (Android): the content reaches under the status bar
2601 /// (default: it starts below).
2602 #[prop(android = "statusBarTranslucent", on = MODAL)]
2603 StatusBarTranslucent(bool),
2604 /// `supportedOrientations` (iOS): the orientations it allows (default: the
2605 /// presenter's).
2606 ///
2607 /// [`crate::ModalConfig::PORTRAIT`] bits.
2608 #[prop(ios = "supportedOrientations", with = crate::js::host_values::orientations, reset = ModalProp::Orientations(0), ts = "(\"portrait\" | \"portrait-upside-down\" | \"landscape\" | \"landscape-left\" | \"landscape-right\")[]", on = MODAL, shared)]
2609 Orientations(u8),
2610 /// `closeOnEscape`: Escape and the Android back button close it natively
2611 /// (default true); either way they call `onCancel`.
2612 #[prop(js = "closeOnEscape", default = true, on = MODAL)]
2613 CloseOnEscape(bool),
2614 /// `closeOnBackdropPress`: a press on the backdrop part
2615 /// (`backdropClass` / `backdropStyle`, rendered by the runtime) closes
2616 /// it (default true); either way it calls `onCancel`.
2617 #[prop(js = "closeOnBackdropPress", default = true, on = MODAL)]
2618 CloseOnBackdropPress(bool),
2619 /// `closeOnSwipe`: swiping a sheet down (iOS, phone browsers) closes it
2620 /// natively (default true); either way it calls `onCancel`.
2621 #[prop(js = "closeOnSwipe", default = true, on = MODAL)]
2622 CloseOnSwipe(bool),
2623 /// `detents`: the heights an iOS sheet (`presentation` `"pageSheet"` /
2624 /// `"formSheet"`) rests at (none by default: the system's full height).
2625 /// The user drags it between them, the system way; past the smallest
2626 /// it closes when `closeOnSwipe` allows. Ignored on other platforms and
2627 /// presentations: there, `Sheet` (`nsh/base`) rests at detents.
2628 #[prop(js = "detents", on = MODAL)]
2629 Detents(Vec<SheetDetent>),
2630 /// `detent`: the detent of `detents` the sheet rests at: it moves there
2631 /// when the value changes. The user's moves stand even when the app
2632 /// does not follow them; follow `onDetentChange` to keep the value in
2633 /// step.
2634 #[prop(js = "detent", on = MODAL)]
2635 Detent(Option<SheetDetent>),
2636 /// `defaultDetent`: the detent it opens at without `detent` (default
2637 /// the smallest).
2638 #[prop(js = "defaultDetent", on = MODAL)]
2639 DefaultDetent(Option<SheetDetent>),
2640 /// `grabber`: the sheet shows the system's grabber at its top (default
2641 /// false); screen readers move it between detents with it.
2642 #[prop(js = "grabber", on = MODAL)]
2643 Grabber(bool),
2644 /// `largestUndimmedDetent`: up to this detent of `detents`, what is
2645 /// behind the sheet is not dimmed and takes touches (default: dimmed at
2646 /// every detent).
2647 #[prop(js = "largestUndimmedDetent", on = MODAL)]
2648 LargestUndimmedDetent(Option<SheetDetent>),
2649}
2650
2651/// An overlay option (`<Overlay …>`, [`crate::overlay`]).
2652#[derive(Debug, Clone, Copy, PartialEq, HostProps)]
2653pub enum OverlayProp {
2654 /// `anchor`: the view (a ref), the point (`{ x, y }` in the root view,
2655 /// as touches' `pageX` / `pageY`) or the box (`{ origin, size }` in the
2656 /// root view, as an input's caret `pageBounds`) it is placed against,
2657 /// following a view as it moves; without one it is laid out as a
2658 /// `position: fixed` box of its root view.
2659 #[prop(js = "anchor", with = crate::js::host_values::overlay_anchor, reset = OverlayProp::Anchor(OverlayAnchor::None), ts = "ViewRef | Point | Bounds | null", on = OVERLAY)]
2660 Anchor(OverlayAnchor),
2661 /// `placement`: the side of the anchor it goes on (default `"bottom"`);
2662 /// the other side when only that one has room.
2663 #[prop(js = "placement", on = OVERLAY)]
2664 Placement(Placement),
2665 /// `align`: how it lines up with the anchor along that side (default
2666 /// `"center"`; `"start"` / `"end"` follow the layout direction above and
2667 /// below).
2668 #[prop(js = "align", on = OVERLAY)]
2669 Align(Align),
2670 /// `offset`: the gap between the anchor and the overlay (default 0).
2671 #[prop(js = "offset", on = OVERLAY)]
2672 Offset(Points),
2673 /// `margin`: the distance it keeps from the edges of the root view's
2674 /// safe area (default 0).
2675 #[prop(js = "margin", on = OVERLAY)]
2676 Margin(Points),
2677 /// A hint (a tooltip) shown after the pointer rested on the anchor this
2678 /// long ([`crate::overlay::OverlayConfig::hint`]); set by components
2679 /// (`nsh-base`'s `Tooltip`).
2680 #[prop(reset = OverlayProp::Hint(None))]
2681 Hint(Option<std::time::Duration>),
2682 /// A hint shown or hidden whatever the pointer does
2683 /// ([`crate::overlay::OverlayConfig::open`]); set by components.
2684 #[prop(reset = OverlayProp::Open(None))]
2685 Open(Option<bool>),
2686 /// A view inside it laid over the anchor
2687 /// ([`crate::overlay::OverlayConfig::cover`]); set by components
2688 /// (`nsh-base`'s `Select`: the selected item over the trigger).
2689 #[prop(reset = OverlayProp::Cover(None))]
2690 Cover(Option<NodeId>),
2691}
2692
2693/// Input for a web view's page, delivered as the user's hands give it: the
2694/// page's events are trusted (`isTrusted`), which scripts it injects cannot
2695/// make (`WebView`'s `sendInput`). Needs `capabilities.webview.input`.
2696#[derive(Debug, Clone, PartialEq)]
2697#[non_exhaustive]
2698pub enum WebInput {
2699 /// A primary click at a point of the page's viewport: CSS pixels, which
2700 /// are points at the page's own zoom (what `getBoundingClientRect()`
2701 /// reports).
2702 Click {
2703 /// From the viewport's left edge.
2704 x: Points,
2705 /// From the viewport's top edge.
2706 y: Points,
2707 },
2708 /// Text typed into what has the page's keyboard focus.
2709 Text(String),
2710 /// A key pressed and released.
2711 Key(WebKey),
2712}
2713
2714/// A page a web view loads with headers on its request (`WebView`'s
2715/// `load`): the document request carries them; the page's subresources,
2716/// its later navigations and reloads do not. Debug output names the
2717/// headers but never shows their values (they are credentials, as
2718/// `Authorization`).
2719#[derive(Clone, PartialEq, Eq)]
2720#[non_exhaustive]
2721pub struct WebLoad {
2722 /// The URL to load.
2723 pub src: String,
2724 /// The request's headers, in order: names are HTTP tokens and values
2725 /// have no line breaks or NULs ([`WebLoad::new`] checks).
2726 pub headers: Vec<(String, String)>,
2727}
2728
2729impl WebLoad {
2730 /// A load of `src` with `headers`; `None` when a header's name is not
2731 /// an HTTP token (RFC 9110's `tchar`s) or its value holds a CR, LF or
2732 /// NUL, which would let it end the header and start another.
2733 pub fn new(src: impl Into<String>, headers: Vec<(String, String)>) -> Option<Self> {
2734 let token = |name: &str| {
2735 !name.is_empty()
2736 && name
2737 .bytes()
2738 .all(|b| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b))
2739 };
2740 let value = |value: &str| !value.contains(['\r', '\n', '\0']);
2741 headers
2742 .iter()
2743 .all(|(n, v)| token(n) && value(v))
2744 .then(|| Self {
2745 src: src.into(),
2746 headers,
2747 })
2748 }
2749}
2750
2751impl std::fmt::Debug for WebLoad {
2752 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2753 let names: Vec<&str> = self.headers.iter().map(|(n, _)| n.as_str()).collect();
2754 f.debug_struct("WebLoad")
2755 .field("src", &self.src)
2756 .field("headers", &names)
2757 .finish()
2758 }
2759}
2760
2761/// A key `WebInput::Key` presses.
2762#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2763#[non_exhaustive]
2764pub enum WebKey {
2765 /// Return: submits a form, confirms a field.
2766 Enter,
2767 /// Moves the focus forward.
2768 Tab,
2769 /// Escape.
2770 Escape,
2771 /// Deletes backward.
2772 Backspace,
2773}
2774
2775impl WebKey {
2776 /// The key a DOM `KeyboardEvent.key` names (`"Enter"`, ...).
2777 pub fn from_name(name: &str) -> Option<Self> {
2778 Some(match name {
2779 "Enter" => Self::Enter,
2780 "Tab" => Self::Tab,
2781 "Escape" => Self::Escape,
2782 "Backspace" => Self::Backspace,
2783 _ => return None,
2784 })
2785 }
2786}
2787
2788/// Where `reveal` puts a view along the axis of a scroll view around it
2789/// (GPUI's `ScrollStrategy`, with the DOM's `ScrollLogicalPosition`
2790/// names, as [`SnapAlignment`]). Physical: start and end are top and
2791/// bottom along a vertical scroll view, left and right along a horizontal
2792/// one, in either writing direction.
2793#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
2794#[non_exhaustive]
2795pub enum ScrollAlignment {
2796 /// Its start at the start of the viewport.
2797 #[default]
2798 Start,
2799 /// Its middle in the middle of the viewport.
2800 Center,
2801 /// Its end at the end of the viewport.
2802 End,
2803 /// Nowhere new while it is in full view or covers the viewport; else
2804 /// the edge it is past at that edge of the viewport, or, when it is
2805 /// longer than the viewport, its other edge at the viewport's other
2806 /// edge (CSSOM View's).
2807 Nearest,
2808}
2809
2810/// How `reveal` scrolls ([`crate::element::ElementRef::reveal`], TS
2811/// `ref.reveal(options)`). It places the view from the layout and the
2812/// zoom scales the platforms last reported, as `measure()` does:
2813/// transforms (animations included) and a `zoomTo` not applied yet are not
2814/// taken into account.
2815///
2816/// ```
2817/// # use nsh_core::{RevealOptions, ScrollAlignment};
2818/// let options = RevealOptions::default().vertical(ScrollAlignment::Center);
2819/// ```
2820#[derive(Debug, Clone, Copy, PartialEq)]
2821#[non_exhaustive]
2822pub struct RevealOptions {
2823 /// Along vertical scroll views; `Start` by default.
2824 pub vertical: ScrollAlignment,
2825 /// Along horizontal scroll views; `Nearest` by default.
2826 pub horizontal: ScrollAlignment,
2827 /// Animate the scrolls; `true` by default, as `scroll_to`'s.
2828 pub animated: bool,
2829}
2830
2831impl Default for RevealOptions {
2832 fn default() -> Self {
2833 Self {
2834 vertical: ScrollAlignment::Start,
2835 horizontal: ScrollAlignment::Nearest,
2836 animated: true,
2837 }
2838 }
2839}
2840
2841impl RevealOptions {
2842 /// Sets where the view goes along vertical scroll views.
2843 pub fn vertical(mut self, alignment: ScrollAlignment) -> Self {
2844 self.vertical = alignment;
2845 self
2846 }
2847
2848 /// Sets where the view goes along horizontal scroll views.
2849 pub fn horizontal(mut self, alignment: ScrollAlignment) -> Self {
2850 self.horizontal = alignment;
2851 self
2852 }
2853
2854 /// Sets whether the scrolls animate.
2855 pub fn animated(mut self, animated: bool) -> Self {
2856 self.animated = animated;
2857 self
2858 }
2859}
2860
2861/// An imperative call on a native view (`ref.focus()` and the like).
2862#[derive(Debug, Clone, PartialEq)]
2863pub enum Command {
2864 /// Focus an input (show the keyboard).
2865 Focus,
2866 /// Unfocus an input; on the root view, unfocus whatever is focused.
2867 Blur,
2868 /// Clear the selection of a selectable view (`ViewProps::selectable_view`)
2869 /// the view is, is inside or holds.
2870 ClearSelection,
2871 /// Select all the text of the selectable view (`ViewProps::selectable_view`)
2872 /// the view is or is inside, as the selection menu's Select All does.
2873 SelectAll,
2874 /// Scroll a scroll view to an offset.
2875 ScrollTo {
2876 /// Horizontal offset.
2877 x: Points,
2878 /// Vertical offset.
2879 y: Points,
2880 /// Animate the change.
2881 animated: bool,
2882 },
2883 /// Animate the layout changes of the next commit. On the root, all of
2884 /// them; on a node, with its `update`, only the frames that node's
2885 /// change moves (`ElementRef::animate_layout`, `core/layout_scope.rs`).
2886 LayoutAnimation(LayoutAnimation),
2887 /// Leave the app (Android back handling; on the root).
2888 ExitApp,
2889 /// The app's address (`UrlScheme.setUrl`, `set_app_url`; on the root):
2890 /// the web replaces the current history entry's; iOS and macOS give it
2891 /// to the system when the app opts in (Handoff); the other
2892 /// platforms keep none ([`crate::url_scheme`]).
2893 SetAppUrl(String),
2894 /// The app's address as an entry of its own after the current one
2895 /// (`UrlScheme.setUrl(url, { history: "push" })`, `set_app_url_with`; on
2896 /// the root): the web pushes one unless the same turn pushed a page's
2897 /// or it is the address shown; iOS and macOS take it as
2898 /// [`Command::SetAppUrl`]; the other platforms keep none.
2899 PushAppUrl(String),
2900 /// What the back button does when none of the app's listeners took
2901 /// it: the innermost stack pops (or asks, with `popOnBack` false); with
2902 /// none, the app leaves on Android (on the root).
2903 Back,
2904 /// Reload a web view.
2905 Reload,
2906 /// Go back in a web view's history.
2907 GoBack,
2908 /// Go forward in a web view's history.
2909 GoForward,
2910 /// Stop loading a web view.
2911 StopLoading,
2912 /// Run JavaScript in a web view's page.
2913 InjectJavaScript(String),
2914 /// Run a script in a web view's page for its result
2915 /// ([`crate::platform::web_evaluation`]); the platform answers on this
2916 /// node with [`EventKind::WebEvaluation`] (`id`: the request, `data`:
2917 /// the JSON envelope), once.
2918 Evaluate {
2919 /// The engine's request, echoed in the reply.
2920 request: u32,
2921 /// The app's script.
2922 script: String,
2923 },
2924 /// Give up request `request` of [`Command::Evaluate`]: release what the
2925 /// platform keeps for it, answering nothing.
2926 CancelEvaluate {
2927 /// The request.
2928 request: u32,
2929 },
2930 /// Send a message to a web view's page (`window.onmessage` data).
2931 PostMessage(String),
2932 /// Give a web view's page input as the user's own (trusted events).
2933 SendInput(WebInput),
2934 /// Load a page in a web view with headers on its request.
2935 Load(WebLoad),
2936 /// Seek a video to a time in seconds.
2937 Seek(f64),
2938 /// Scroll a list to an item (resolved by the core into `ScrollTo`).
2939 ScrollToIndex {
2940 /// The item.
2941 index: u32,
2942 /// Animate the change.
2943 animated: bool,
2944 /// Where the item ends up: 0 at the start of the viewport, 1 at the
2945 /// end, 0.5 in the middle.
2946 view_position: Percentage,
2947 /// Extra distance from that position.
2948 view_offset: Points,
2949 },
2950 /// Zoom a zoomable scroll view to `scale`, with the content point
2951 /// (`x`, `y`) (points, unzoomed) in the middle of the viewport, or
2952 /// around the viewport's middle.
2953 ZoomTo {
2954 /// The zoom scale (clamped to the view's limits).
2955 scale: f32,
2956 /// The content point to center.
2957 center: Option<Point<Points>>,
2958 /// Animate the change.
2959 animated: bool,
2960 },
2961 /// Scroll the scroll views around the view so it shows (resolved by
2962 /// the core into their `ScrollTo`; never mounted).
2963 Reveal(RevealOptions),
2964 /// Scroll a list to the end of its content.
2965 ScrollToEnd {
2966 /// Animate the change.
2967 animated: bool,
2968 },
2969 /// Set the status bar (on the root): what the platform shows.
2970 StatusBar(StatusBarConfig),
2971 /// The design tokens the app is drawn with (on the root), sent when
2972 /// they change ([`crate::Core::tokens`]): what the platform's own
2973 /// controls (Linux's menus, Android's and iOS's alerts and action
2974 /// sheets) take their colors from, by the tokens' names (`popover`,
2975 /// `accent`, `border`, ...).
2976 Tokens(std::sync::Arc<crate::element::Tokens>),
2977 /// The language the app's text shows in ([`crate::i18n`]: its selected
2978 /// language, `setLocale`'s or the embedding app's included), on the
2979 /// root of an iOS or Android surface, sent when it changes: the words
2980 /// the platform speaks for states it has no system words for
2981 /// (checked, expanded, invalid...) follow it.
2982 TextLocale(crate::platform::Locale),
2983 /// Change what functions set for the status bar (on the root): the
2984 /// core merges it under the settings components render and sends
2985 /// [`Command::StatusBar`] when the result changes.
2986 SetStatusBar(StatusBarSetting),
2987 /// Show an alert or action sheet (on the root); the answer comes back
2988 /// as [`EventKind::Dialog`].
2989 Dialog(Box<AlertDialogRequest>),
2990 /// Close the dialog [`Command::Dialog`] showed with this id (on the
2991 /// root), as if dismissed, without reporting an answer: the app no
2992 /// longer wants one, and the core has already answered it.
2993 CloseDialog(u32),
2994 /// A JS responder took the touches on this view: `block` keeps native
2995 /// scroll views around it from taking them over.
2996 SetJsResponder {
2997 /// Block native scrolling.
2998 block: bool,
2999 },
3000 /// The JS responder let go (on the root).
3001 ClearJsResponder,
3002 /// The press going on in this view (or a view inside it) ends without
3003 /// its release: no `onPressUp` or `onPress` follow, and its `active:`
3004 /// styles reset at once (a context menu opened by a held finger). The
3005 /// core handles it; platforms never see it.
3006 #[doc(hidden)]
3007 CancelPress,
3008 /// Select a range of an input (UTF-16 units; equal for a caret).
3009 /// Platforms drop it when the same batch brought the input a value
3010 /// they dropped as stale (`MountItem::InputValue`'s `count`): its
3011 /// offsets are for the text JS had, not for what the user typed since.
3012 SetSelection {
3013 /// Start.
3014 start: u32,
3015 /// End.
3016 end: u32,
3017 },
3018 /// Insert text into an input in place of its selection, as the user's
3019 /// edit: the input's `maxLength` and line rules apply, `onChangeText`
3020 /// reports it, no key is reported, and where the platform keeps an
3021 /// undo history it is a step of it (unlike a new `value`). With
3022 /// `pasteBehavior` `"report"`, the app inserts a paste it allowed or
3023 /// rewrote this way.
3024 InsertText(String),
3025 /// Have the screen reader read a message (on the root).
3026 Announce(String),
3027 /// Turn the performance monitor on or off (on the root;
3028 /// `setFpsEnabled`): what the platform has of one, the
3029 /// macOS panel or the other platforms' `nsh::fps` lines. Platforms
3030 /// without a monitor ignore it.
3031 PerfMonitor(bool),
3032 /// How the performance monitor shows (on the root; `setFpsMode`): its
3033 /// whole panel, collapsed to its frame rate, or nothing while it still
3034 /// measures. Platforms without a panel ignore it.
3035 PerfMonitorMode(FpsMode),
3036 /// Load the image at `uri` (keeping its bytes for views that show it
3037 /// next) and report its pixel size as [`EventKind::ImageInfo`] `id`
3038 /// (on the root).
3039 ImageInfo {
3040 /// The request.
3041 id: u32,
3042 /// URL or `asset:/` URI.
3043 uri: String,
3044 },
3045 /// Move the screen reader's focus to this view.
3046 AccessibilityFocus,
3047 /// Measure the view with this commit's layout (`ref.measure()`):
3048 /// answered by the core in its events for promise `call`
3049 /// ([`crate::element::JsEvent::Reply`]: a [`crate::Measurement`], or null
3050 /// when the view is not laid out); never mounted.
3051 Measure {
3052 /// The call to answer.
3053 call: u32,
3054 },
3055 /// Where a list's viewport starts among its rows, with this commit's
3056 /// layout (`ref.measureScrollPosition()`): answered by the core in its
3057 /// events for promise `call` (a [`crate::ListScrollPosition`], or null
3058 /// for a view that is no list or a list without items); never
3059 /// mounted.
3060 MeasureScrollPosition {
3061 /// The call to answer.
3062 call: u32,
3063 },
3064 /// Put `text` on the system clipboard (on the root; `Clipboard.writeText`).
3065 SetClipboard(String),
3066 /// Put one item on the system clipboard, each of its formats in one
3067 /// write: the text as plain text, the HTML (when it has some) as the
3068 /// platform's HTML type, which apps that read formatting paste (on the
3069 /// root; `Clipboard.write`). A platform without an HTML type puts the
3070 /// text only. New formats of [`crate::element::ClipboardItem`] come in
3071 /// the same command.
3072 SetClipboardItem(crate::element::ClipboardItem),
3073 /// Read the system clipboard and report it as [`EventKind::Clipboard`]
3074 /// `id` (on the root): `has` and, unless `has_only`, `text`. Asking
3075 /// only whether it holds text does not read it (no iOS paste notice).
3076 ReadClipboard {
3077 /// The request.
3078 id: u32,
3079 /// Only whether it holds text (`Clipboard.hasText`).
3080 has_only: bool,
3081 },
3082 /// Put the image of a `data:` URI on the system clipboard, replacing
3083 /// what it holds (on the root; `Clipboard.writeImage`).
3084 SetClipboardImage(String),
3085 /// Read the image on the system clipboard and report it as
3086 /// [`EventKind::Clipboard`] `id` (on the root): `has` and, unless
3087 /// `has_only`, the image as a `data:` URI (`uri`) and its size in
3088 /// pixels (`width`, `height`), or for an image over
3089 /// [`crate::platform::clipboard::MAX_IMAGE_BYTES`] its size in bytes
3090 /// (`tooLarge`; [`crate::platform::clipboard::image_answer`]).
3091 ReadClipboardImage {
3092 /// The request.
3093 id: u32,
3094 /// Only whether it holds an image (`Clipboard.hasImage`).
3095 has_only: bool,
3096 },
3097 /// Read the local files on the system clipboard (files copied in a
3098 /// file manager) and report them as [`EventKind::Clipboard`] `id` (on
3099 /// the root): `has` and `files`, their `file:` URLs one per line.
3100 ReadClipboardFiles {
3101 /// The request.
3102 id: u32,
3103 },
3104 /// Show the system's picker for images (on the root;
3105 /// `Picker.pickImages`), prepare the picked ones as `request` says
3106 /// ([`crate::picker`]) and report them as [`EventKind::Pick`]
3107 /// ([`EventPayload::Picked`] `id`; no files when cancelled).
3108 PickImages {
3109 /// The request.
3110 id: u32,
3111 /// What to show and how to prepare the images.
3112 request: crate::picker::PickRequest,
3113 },
3114 /// Show the system's picker for files of any type (on the root;
3115 /// `Picker.pickFiles`) and report the picked ones, their bytes as they
3116 /// are, as [`EventKind::Pick`] ([`EventPayload::Picked`] `id`; no files
3117 /// when cancelled; [`crate::picker`]).
3118 PickFiles {
3119 /// The request.
3120 id: u32,
3121 /// What to show.
3122 request: crate::picker::FilePickRequest,
3123 },
3124 /// Open `url` outside the app (on the root; `openUrl` of `nsh/device`,
3125 /// [`crate::open_url`]): the browser, the mail or phone app, the app
3126 /// that registered its scheme. Report whether it opened as
3127 /// [`EventKind::OpenUrl`] `id`. The core sends it once the URL was
3128 /// checked and the embedding app did not take it.
3129 OpenUrl {
3130 /// The request.
3131 id: u32,
3132 /// The URL ([`crate::open_url::check_url`] passed it).
3133 url: String,
3134 },
3135 /// Open the app's own page in the system's settings (on the root;
3136 /// `nsh/mobile`'s `AppSettings.open`,
3137 /// [`crate::mobile::open_app_settings`]): iOS's
3138 /// `UIApplication.openSettingsURLString`, Android's application
3139 /// details. Report whether the system opened it as
3140 /// [`EventKind::OpenAppSettings`] `id`. Sent only on platforms whose
3141 /// [`crate::platform::Environment::app_settings`] is set.
3142 OpenAppSettings {
3143 /// The request.
3144 id: u32,
3145 },
3146 /// Let the user pick a color anywhere on the screen (on the root; a
3147 /// color picker's eyedropper, [`crate::element::ambient::pick_screen_color`]):
3148 /// the system's color sampler or the browser's `EyeDropper`. Report it
3149 /// as [`EventKind::ScreenColor`] `id`, with no `color` when the user
3150 /// cancelled. Sent only on platforms whose
3151 /// [`crate::platform::Environment::screen_color`] is set.
3152 PickScreenColor {
3153 /// The request.
3154 id: u32,
3155 },
3156 /// Render `drawing` offscreen into a `width` × `height` pixel image
3157 /// (on the root; `OffscreenCanvas`'s `convertToBlob`,
3158 /// [`crate::canvas::render`]): replay it as a canvas of `scale` pixels
3159 /// per point draws it on screen, into a bitmap of its own that starts
3160 /// transparent, its animated values at 0, and report the encoded image
3161 /// as [`EventKind::CanvasImage`] `id` ([`EventPayload::CanvasImage`]).
3162 /// Sent only on platforms whose
3163 /// [`crate::platform::Environment::canvas_render`] is set, with a size
3164 /// [`crate::canvas::render::pixel_size`] passed.
3165 RenderCanvas {
3166 /// The request.
3167 id: u32,
3168 /// What to draw, in points.
3169 drawing: std::sync::Arc<crate::canvas::Drawing>,
3170 /// The image's width in pixels.
3171 width: u32,
3172 /// The image's height in pixels.
3173 height: u32,
3174 /// Pixels per point.
3175 scale: f32,
3176 /// The encoding.
3177 format: crate::canvas::render::ImageFormat,
3178 },
3179 /// Carry out `request` on local paths (on the root;
3180 /// [`crate::file_dialog`]): show the open or save dialog, open a file
3181 /// in its app, show it in the file manager or move it to the trash.
3182 /// Report it as [`EventKind::FileRequest`] `id`
3183 /// ([`EventPayload::FileRequest`]). Sent only on platforms whose
3184 /// [`crate::platform::Environment::file_requests`] is set.
3185 FileRequest {
3186 /// The request.
3187 id: u32,
3188 /// What to do.
3189 request: Box<crate::file_dialog::FileRequest>,
3190 },
3191 /// Load, play and free sounds, open and drive players (on the root;
3192 /// `Sound` and `AudioPlayer` of `nsh`, [`crate::audio`]) and report
3193 /// what happens as [`EventKind::Audio`] ([`EventPayload::Audio`]). Sent
3194 /// only on platforms whose [`crate::platform::Environment::audio`] is
3195 /// set.
3196 Audio(crate::audio::AudioCommand),
3197 /// Show a notification, ask for the permission, set the app's badge
3198 /// (on the root; `Notifications` of `nsh`, [`crate::notifications`]).
3199 Notification(crate::notifications::NotificationCommand),
3200 /// Play a haptic (on the root; `Haptics` of `nsh/mobile`,
3201 /// [`crate::element::haptic`]). Platforms without haptics ignore it.
3202 Haptic(Haptic),
3203 /// The orientations the screen may take (on the root; the
3204 /// `supportedOrientations` of the page shown, [`ScreenProp::Orientations`]):
3205 /// [`crate::ModalConfig::PORTRAIT`] bits, 0 for the app's own. iOS and
3206 /// Android; the other platforms ignore it.
3207 Orientations(u8),
3208 /// A desktop command (on the root; `nsh/desktop`): the window, its
3209 /// title bar, menus. Mobile platforms ignore it.
3210 Desktop(Box<crate::desktop::DesktopCommand>),
3211 /// Call function `name` of the app embedding NSH (on the root;
3212 /// `nsh/host`'s `host.call`): the platform answers with
3213 /// [`EventKind::Host`] `{ type: "reply", id, .. }`. Sent only on
3214 /// platforms whose [`crate::platform::Environment::host`] is set, for
3215 /// functions the app's `capabilities.host` grants.
3216 HostCall {
3217 /// The call, echoed by the reply.
3218 id: u64,
3219 /// The host's function.
3220 name: String,
3221 /// Its argument (any JSON value; `null` without one).
3222 args: crate::JsonValue,
3223 },
3224 /// Hand `args` to function `name` of the app embedding NSH, with no
3225 /// answer (on the root; `nsh/host`'s `host.post` without a native SDK
3226 /// channel). Sent only on platforms whose
3227 /// [`crate::platform::Environment::host`] is set, for functions the
3228 /// app's `capabilities.host` grants.
3229 HostPost {
3230 /// The host's function.
3231 name: String,
3232 /// Its argument (any JSON value; `null` without one).
3233 args: crate::JsonValue,
3234 },
3235 /// A call on a registered native component (`ref.command(name, args)`).
3236 Native {
3237 /// The command.
3238 name: Arc<str>,
3239 /// Its arguments (any JSON value).
3240 args: crate::JsonValue,
3241 },
3242 /// Open the system's edit menu over `bounds` (in the root view) on an
3243 /// input that has the focus: the menu of a component that draws its
3244 /// own text selection (`RichEditor`'s on touch screens). UIKit's
3245 /// `UIEditMenuInteraction` on iOS, a floating `ActionMode` on Android;
3246 /// platforms without such a menu ignore it. It offers `actions`, in the
3247 /// platform's order: Paste pastes into the input as the user's paste
3248 /// does (`onPaste`), the others are reported as
3249 /// [`EventKind::EditAction`]. The menu closes when an action is chosen.
3250 OpenEditMenu {
3251 /// What the menu points at, in the root view.
3252 bounds: Bounds<Points>,
3253 /// The actions it offers; those that cannot apply are left out,
3254 /// not disabled.
3255 actions: Vec<EditAction>,
3256 },
3257 /// Close the edit menu [`Command::OpenEditMenu`] opened on an input.
3258 CloseEditMenu,
3259 /// A request on a web view ([`crate::webview`]) sent once the target is
3260 /// known to be a mounted, granted web view; the platform answers on
3261 /// this node with [`EventKind::WebViewReply`] (`id`: the request).
3262 WebViewRequest(crate::webview::WebViewRequest),
3263}
3264
3265/// An editing action of an edit menu ([`Command::OpenEditMenu`],
3266/// [`EventKind::EditAction`]): gpui-base's input actions of the same names.
3267#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PropEnum)]
3268#[non_exhaustive]
3269pub enum EditAction {
3270 /// Cut the selection.
3271 Cut,
3272 /// Copy the selection.
3273 Copy,
3274 /// Paste the clipboard (the input's own paste).
3275 Paste,
3276 /// Select everything.
3277 SelectAll,
3278}
3279
3280/// A haptic the device plays ([`Command::Haptic`], TS: `Haptics` of
3281/// `nsh/mobile`): grouped as UIKit's feedback generators and Expo's API —
3282/// a selection that changed, an impact by weight, a task's outcome. On
3283/// Android it is the view's haptic feedback. What the user feels follows
3284/// the device and its settings: none with haptics turned off, or on
3285/// hardware without them.
3286#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
3287#[non_exhaustive]
3288pub enum Haptic {
3289 /// A selection changed: a picker's value, a segment, a slider's step
3290 /// (`Haptics.selection()`).
3291 Selection,
3292 /// An element collided; the style is its weight (`Haptics.impact`).
3293 Impact(HapticImpact),
3294 /// A task ended (`Haptics.notification`).
3295 Notification(HapticNotification),
3296}
3297
3298/// How the performance monitor shows ([`Command::PerfMonitorMode`], TS:
3299/// `setFpsMode`'s argument: `"expanded"`, `"collapsed"`, `"hidden"`).
3300#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, PropEnum)]
3301#[non_exhaustive]
3302pub enum FpsMode {
3303 /// The whole panel: the readings and the frame-cost trace.
3304 #[default]
3305 Expanded,
3306 /// A small pill with the frame rate only, colored by the frame budget.
3307 Collapsed,
3308 /// Nothing on screen; it still measures (`perfStats()`, the log).
3309 Hidden,
3310}
3311
3312/// The weight of an impact ([`Haptic::Impact`], TS: `Haptics.impact`'s
3313/// argument: `"light"` … `"rigid"`).
3314#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PropEnum)]
3315#[non_exhaustive]
3316pub enum HapticImpact {
3317 /// A small, light element.
3318 Light,
3319 /// A moderate element.
3320 Medium,
3321 /// A large, heavy element.
3322 Heavy,
3323 /// A soft, flexible element.
3324 Soft,
3325 /// A hard, inflexible element.
3326 Rigid,
3327}
3328
3329/// How a task ended ([`Haptic::Notification`], TS: `Haptics.notification`'s
3330/// argument: `"success"`, `"warning"`, `"error"`).
3331#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PropEnum)]
3332#[non_exhaustive]
3333pub enum HapticNotification {
3334 /// It succeeded.
3335 Success,
3336 /// It produced a warning.
3337 Warning,
3338 /// It failed.
3339 Error,
3340}
3341
3342/// The status bar's look.
3343#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
3344pub enum StatusBarStyle {
3345 /// The platform's default for the appearance.
3346 #[default]
3347 Default,
3348 /// Light content (for dark backgrounds).
3349 Light,
3350 /// Dark content (for light backgrounds).
3351 Dark,
3352}
3353
3354impl StatusBarStyle {
3355 /// The style of a TS `StatusBarForeground` (`"auto"`, `"light"`,
3356 /// `"dark"`).
3357 pub fn from_name(name: &str) -> Option<Self> {
3358 match name {
3359 "auto" => Some(Self::Default),
3360 "light" => Some(Self::Light),
3361 "dark" => Some(Self::Dark),
3362 _ => None,
3363 }
3364 }
3365}
3366
3367/// What the status bar shows.
3368#[derive(Debug, Clone, Copy, PartialEq, Default)]
3369pub struct StatusBarConfig {
3370 /// Content color.
3371 pub style: StatusBarStyle,
3372 /// Hidden.
3373 pub hidden: bool,
3374 /// Animate the change.
3375 pub animated: bool,
3376}
3377
3378/// A status bar setting: what it sets; the fields it leaves out keep the
3379/// settings below it.
3380#[derive(Debug, Clone, Copy, PartialEq, Default)]
3381pub struct StatusBarSetting {
3382 /// Content color.
3383 pub style: Option<StatusBarStyle>,
3384 /// Hidden.
3385 pub hidden: Option<bool>,
3386 /// Animate the change.
3387 pub animated: Option<bool>,
3388}
3389
3390/// The setting of the content's color alone (`.status_bar(StatusBarStyle::Light)`).
3391impl From<StatusBarStyle> for StatusBarSetting {
3392 fn from(style: StatusBarStyle) -> Self {
3393 Self::default().foreground(style)
3394 }
3395}
3396
3397impl StatusBarSetting {
3398 /// Sets the content's color.
3399 pub const fn foreground(mut self, style: StatusBarStyle) -> Self {
3400 self.style = Some(style);
3401 self
3402 }
3403
3404 /// Hides or shows the bar.
3405 pub const fn hidden(mut self, hidden: bool) -> Self {
3406 self.hidden = Some(hidden);
3407 self
3408 }
3409
3410 /// Animates the change to this setting.
3411 pub const fn animated(mut self, animated: bool) -> Self {
3412 self.animated = Some(animated);
3413 self
3414 }
3415
3416 /// The app's default (`nsh.json` `"statusBar"`): `{ "foreground":
3417 /// "auto" | "light" | "dark", "hidden": bool }`, both optional. What it
3418 /// cannot read, an unknown key or a value of a form it does not know,
3419 /// is left out and the rest applies: a bundle made by a newer NSH keeps
3420 /// its setting on an older runtime.
3421 pub fn from_json(value: &crate::JsonValue) -> Self {
3422 Self::from_json_lenient(value).0
3423 }
3424
3425 /// [`StatusBarSetting::from_json`], with what it left out
3426 /// (`foreground: "dim" is not "auto", "light" or "dark"`), which the
3427 /// toolchain warns of (a newer NSH's, or a typo).
3428 pub fn from_json_lenient(value: &crate::JsonValue) -> (Self, Vec<String>) {
3429 let mut setting = Self::default();
3430 let mut ignored = Vec::new();
3431 let Some(object) = value.as_object() else {
3432 ignored.push(format!(
3433 "{value} is not an object ({{ \"foreground\": \"light\", \"hidden\": false }})"
3434 ));
3435 return (setting, ignored);
3436 };
3437 for (key, v) in object {
3438 match key.as_str() {
3439 "foreground" => match v.as_str().and_then(StatusBarStyle::from_name) {
3440 Some(style) => setting.style = Some(style),
3441 None => ignored.push(format!(
3442 "foreground: {v} is not \"auto\", \"light\" or \"dark\""
3443 )),
3444 },
3445 "hidden" => match v.as_bool() {
3446 Some(hidden) => setting.hidden = Some(hidden),
3447 None => ignored.push(format!("hidden: {v} is not true or false")),
3448 },
3449 other => ignored.push(format!("unknown key `{other}`")),
3450 }
3451 }
3452 (setting, ignored)
3453 }
3454
3455 /// This setting over `below`.
3456 pub fn over(self, below: Self) -> Self {
3457 Self {
3458 style: self.style.or(below.style),
3459 hidden: self.hidden.or(below.hidden),
3460 animated: self.animated.or(below.animated),
3461 }
3462 }
3463}
3464
3465/// How a dialog button looks.
3466#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
3467#[serde(rename_all = "snake_case")]
3468pub enum DialogButtonStyle {
3469 /// A regular button.
3470 #[default]
3471 Default,
3472 /// The cancel button.
3473 Cancel,
3474 /// A destructive action.
3475 Destructive,
3476}
3477
3478/// A dialog button.
3479#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
3480pub struct DialogButton {
3481 /// Label.
3482 pub text: String,
3483 /// Look.
3484 pub style: DialogButtonStyle,
3485}
3486
3487/// An alert, or with `sheet` an action sheet.
3488#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
3489pub struct AlertDialogRequest {
3490 /// Echoed in the answer.
3491 pub id: u32,
3492 /// Title.
3493 pub title: Option<String>,
3494 /// Message.
3495 pub message: Option<String>,
3496 /// Buttons, or the sheet's options.
3497 pub buttons: Vec<DialogButton>,
3498 /// Tapping outside (or the back button) dismisses it.
3499 pub cancelable: bool,
3500 /// An action sheet rather than an alert.
3501 pub sheet: bool,
3502 /// A text field in the alert (never in an action sheet); its text comes
3503 /// back with the answer as `value`. Platforms whose alert has no text
3504 /// field show the alert without one and answer without `value`.
3505 #[serde(default, skip_serializing_if = "Option::is_none")]
3506 pub input: Option<DialogInput>,
3507}
3508
3509/// The text field of a [`Dialog`].
3510#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
3511#[serde(default)]
3512#[non_exhaustive]
3513pub struct DialogInput {
3514 /// The text it starts with.
3515 pub text: String,
3516 /// Shown while it is empty.
3517 pub placeholder: Option<String>,
3518 /// The starting text is selected when the field takes the focus, so
3519 /// typing replaces it.
3520 pub select_all: bool,
3521 /// While it is empty, every button but the cancel ones is disabled,
3522 /// and return chooses nothing.
3523 pub required: bool,
3524}
3525
3526impl DialogInput {
3527 /// A text field starting with `text`.
3528 pub fn new(text: impl Into<String>) -> Self {
3529 Self {
3530 text: text.into(),
3531 ..Self::default()
3532 }
3533 }
3534
3535 /// Shown while it is empty.
3536 pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
3537 self.placeholder = Some(placeholder.into());
3538 self
3539 }
3540
3541 /// Selects the starting text when the field takes the focus.
3542 pub fn select_all(mut self, select_all: bool) -> Self {
3543 self.select_all = select_all;
3544 self
3545 }
3546
3547 /// Disables every button but the cancel ones while it is empty.
3548 pub fn required(mut self, required: bool) -> Self {
3549 self.required = required;
3550 self
3551 }
3552
3553 /// Whether `button` can be pressed while the field holds `text`: a
3554 /// cancel button always, the others unless the field is required and
3555 /// empty.
3556 pub fn enables(&self, button: &DialogButton, text: &str) -> bool {
3557 !self.required || !text.is_empty() || button.style == DialogButtonStyle::Cancel
3558 }
3559}
3560
3561/// The button return chooses in a dialog: its last regular one (an alert's
3562/// default button), `None` without one.
3563pub fn dialog_default_button(buttons: &[DialogButton]) -> Option<usize> {
3564 buttons
3565 .iter()
3566 .rposition(|b| b.style == DialogButtonStyle::Default)
3567}
3568
3569/// A non-style property of a host node.
3570#[derive(Debug, Clone, PartialEq, HostProps)]
3571pub enum Prop {
3572 /// `component`: which registered native component a `<native>`
3573 /// element is (set once, before it is mounted).
3574 #[prop(js = "component", internal)]
3575 Component(Arc<str>),
3576 /// `componentSlot`: this view holds the JSX a Rust component's host got
3577 /// for slot `name` (created by the generated glue).
3578 #[prop(js = "componentSlot", internal)]
3579 ComponentSlot(Arc<str>),
3580 /// `componentRender`: this view holds what the app's function of a
3581 /// Rust component's render prop rendered for a key (the prop, U+001F,
3582 /// the key; made by the generated glue on `JsEvent::Render`).
3583 #[prop(js = "componentRender", internal)]
3584 ComponentRender(Arc<str>),
3585 /// A property of a registered native component (`$name` from JS):
3586 /// any JSON value, `None` to remove it.
3587 ComponentProp(Arc<str>, Option<crate::JsonValue>),
3588 /// A property of a registered native component bound to an animated
3589 /// value (`$name` from JS given an animated value): the platform pushes
3590 /// the value to the component on every frame it changes. `None` unbinds
3591 /// it; a value set with [`Prop::ComponentProp`] while bound is kept and
3592 /// sent once it is unbound.
3593 ComponentPropBinding(Arc<str>, Option<crate::animation::NodeId>),
3594 /// A prop of a Rust component's host, decoded in the JS call into the
3595 /// prop's Rust type ([`crate::element::PropSpec::decode`]); `None` resets it
3596 /// to its default.
3597 RustProp(&'static str, Option<crate::element::AnyValue>),
3598 /// `source` (shaders): the WGSL defining `fn shade(uv: vec2f) -> vec4f`,
3599 /// the color of each point of the box (`uv` 0..1 from the top left;
3600 /// straight sRGB with alpha), which reads `nsh.size`, `nsh.time`,
3601 /// `nsh.scale` and its `struct Uniforms` as `uniforms`, and an effect's
3602 /// or transition's pictures (`sample_content`, `sample_from`, ...).
3603 /// An effect without one draws its children as they are; a transition
3604 /// without one runs its `fallback`.
3605 #[prop(js = "source", on = SHADER)]
3606 ShaderSource(Option<Arc<str>>),
3607 /// A compiled shader, as Rust sets it (TS sets `source`).
3608 Shader(Option<crate::shader::Shader>),
3609 /// A GPU view's renderer, as Rust sets it (`gpu_view().renderer(…)`;
3610 /// TS names a registered one, [`Prop::Component`]); `None`: none.
3611 GpuRenderer(Option<crate::gpu::GpuSource>),
3612 /// The element whose frame the view's follows along its parent's main
3613 /// axis, as Rust sets it (`View::follow`, `core/follow.rs`); `None`
3614 /// follows nothing.
3615 Follow(Option<crate::element::FollowTarget>),
3616 /// How a view that follows an element moves when it follows another
3617 /// one (`View::follow_transition`); `None` jumps there.
3618 FollowTransition(Option<crate::LayoutTransition>),
3619 /// `uniforms` (shaders): the values of the members of the shader's
3620 /// `struct Uniforms`, by name: numbers, colors, lists of them (vectors,
3621 /// arrays of `vec4f`) and animated values, which move it natively.
3622 #[prop(js = "uniforms", on = SHADER)]
3623 Uniforms(crate::shader::ShaderUniforms),
3624 /// `paused` (shaders): its clock (`nsh.time`) stands still.
3625 #[prop(js = "paused", on = SHADER, shared)]
3626 ShaderPaused(bool),
3627 /// `progress` (shader effects): `nsh.progress`, a number or an animated
3628 /// value, which moves it natively.
3629 #[prop(js = "progress", on = EFFECT)]
3630 ShaderProgress(crate::shader::ShaderProgress),
3631 /// `maxSampleOffset` (shader effects and transitions): how far beyond
3632 /// the box, in points, the shader draws and its pictures reach.
3633 #[prop(js = "maxSampleOffset", on = EFFECT | TRANSITION)]
3634 MaxSampleOffset(Points),
3635 /// `value` (shader transitions): a string, number or boolean; when it
3636 /// changes, the transition runs (not for the first one).
3637 #[prop(js = "value", on = TRANSITION, shared)]
3638 TransitionValue(Option<crate::shader::TransitionKey>),
3639 /// `duration` (shader transitions): how long one runs, in milliseconds
3640 /// (300 by default).
3641 #[prop(js = "duration", on = TRANSITION)]
3642 TransitionDuration(Option<f32>),
3643 /// `fallback` (shader transitions): what runs without a `source`.
3644 #[prop(js = "fallback", on = TRANSITION)]
3645 TransitionFallback(TransitionFallback),
3646 /// `transitionShader` (pages and dialogs): `{ source, uniforms,
3647 /// duration }`, a shader the page or dialog comes and goes through
3648 /// (the lower side `sample_from`, the upper `sample_to`) instead of its
3649 /// `animation`, for `duration` milliseconds (350 by default).
3650 #[prop(js = "transitionShader", on = SCREEN | MODAL)]
3651 TransitionShader(Option<crate::shader::NavShaderSpec>),
3652 /// `src`: a URL, `asset:/path`, or an imported asset.
3653 #[prop(js = "src", on = IMAGE, shared)]
3654 Source(Option<ImageSource>),
3655 /// `horizontal`: scrolls sideways.
3656 #[prop(js = "horizontal", on = SCROLL | LIST)]
3657 Horizontal(bool),
3658 /// Scrolling behavior of a scroll view or list.
3659 #[prop(nested)]
3660 Scroll(ScrollProp),
3661 /// `scrollbar`: the scroll indicator shows (default true), or the
3662 /// app's built-in bar of a theme (an object, `nsh/base`'s
3663 /// `ScrollbarTheme`). A multiline input's is its text's.
3664 #[prop(js = "scrollbar", with = crate::js::host_values::scrollbar, reset = Prop::Scrollbar(ScrollbarSetting::Shown), ts = "boolean | import(\"nsh/base\").ScrollbarTheme", on = SCROLL | LIST | INPUT)]
3665 Scrollbar(ScrollbarSetting),
3666 /// `refreshing`: the pull-to-refresh spinner shows.
3667 #[prop(js = "refreshing", on = SCROLL | LIST)]
3668 Refreshing(bool),
3669 /// Number of items of a list.
3670 #[prop(js = "count", internal)]
3671 Count(u32),
3672 /// `estimatedItemSize`: the size of items not measured yet, in points (default
3673 /// 50).
3674 #[prop(js = "estimatedItemSize", default = Points(50.0), on = LIST)]
3675 EstimatedItemSize(Points),
3676 /// The recycling slot (or the role) of a list cell, set once by the
3677 /// runtime.
3678 #[prop(js = "slot", with = crate::js::host_values::slot, internal)]
3679 Slot(CellSlot),
3680 /// `numColumns`: items per row (vertical lists).
3681 #[prop(js = "numColumns", default = 1, min = 1, on = LIST)]
3682 Columns(u32),
3683 /// The items of a list changed: `removed` at `at` became `inserted`
3684 /// (precedes the new `Count`).
3685 #[prop(js = "splice", with = crate::js::host_values::splice, internal)]
3686 Splice(u32, u32, u32),
3687 /// The items of a keyed list changed: rows kept, moved, inserted and
3688 /// removed, each row that stays keeping its cell (precedes the new
3689 /// `Count`). Set by the runtime's lists.
3690 ListDiff(std::rc::Rc<crate::list_diff::ListDiff>),
3691 /// `inverted`: laid out from the end, item 0 last (chat style); starts scrolled
3692 /// to the end and keeps its distance from the end as content changes.
3693 #[prop(js = "inverted", on = LIST)]
3694 Inverted(bool),
3695 /// `maintainVisibleContentPosition`: with `autoscrollToBottomThreshold`, a list
3696 /// (not inverted) at the end of its content, or within that many points of it,
3697 /// stays at the end as the content grows or the viewport shrinks (a reply
3698 /// streaming into its last item); scrolled further up, it keeps the visible
3699 /// content where it is. Items inserted above the visible ones never move them.
3700 /// With `animated`, an end that moves away by a large step at once (a card or
3701 /// chart appearing in the last item) is followed by an animated scroll whose
3702 /// target keeps up with the end; small steps (text streaming in) follow at
3703 /// once as without it.
3704 #[prop(js = "maintainVisibleContentPosition", with = crate::js::host_values::visible_content, reset = Prop::FollowEnd(None, false), ts = "{ autoscrollToBottomThreshold?: number; animated?: boolean }", on = LIST)]
3705 FollowEnd(Option<Points>, bool),
3706 /// `alignment`: where the list rests; `bottom` for a chat in reading order
3707 /// (an inverted list ignores it).
3708 #[prop(js = "alignment", on = LIST)]
3709 ListAlignment(ListAlignment),
3710 /// `stickyHeaderIndices`: items that stick to the start while scrolled past
3711 /// (one column, not inverted).
3712 #[prop(js = "stickyHeaderIndices", with = crate::js::host_values::sticky, reset = Prop::StickyIndices(Vec::new()), on = LIST)]
3713 StickyIndices(Vec<u32>),
3714 /// `stickyHeaderOffset`: how far from the start of the viewport sticky
3715 /// items stick, as CSS `position: sticky`'s `top` (negative: partly out
3716 /// of view); the content scrolls under the space before them.
3717 #[prop(js = "stickyHeaderOffset", with = crate::js::host_values::sticky_offset, reset = Prop::StickyOffset(Points(0.0)), ts = "number | AnimatedNode", on = LIST)]
3718 StickyOffset(Points),
3719 /// `stickyHeaderOffset` as an animated value: sticky items stick that
3720 /// far from the start of the viewport, following the value (below a
3721 /// header that moves); the platforms read it as they pin.
3722 StickyOffsetNode(Option<crate::animation::NodeId>),
3723 /// `viewport`: `"parent"` lays the list out at its full length in its
3724 /// parent and renders the rows near the viewport of the scroll view
3725 /// around it, which scrolls it (a page of headers and lists); `"own"`
3726 /// (default) scrolls it in a scroll view of its own. Fixed when the
3727 /// list is made.
3728 #[prop(js = "viewport", on = LIST)]
3729 ListViewport(ListViewport),
3730 /// `contentStyle`: padding and gaps of the content.
3731 #[prop(js = "contentStyle", on = LIST)]
3732 ListContent(ListContentStyle),
3733 /// `contentClass`: padding and gaps of the content as classes (`p-*`,
3734 /// `gap-*`); `contentStyle` wins over them (set by the runtime).
3735 ListContentClass(Box<str>),
3736 /// `viewabilityConfig`: when items count as viewable.
3737 #[prop(js = "viewabilityConfig", on = LIST)]
3738 Viewability(Viewability),
3739 /// How close to the end `onLoadMore` fires, in viewports.
3740 #[prop(js = "loadMoreThreshold", default = 1.0, internal)]
3741 LoadMoreThreshold(f32),
3742 /// How close to the start `onLoadMoreAtStart` fires, in viewports.
3743 #[prop(js = "loadMoreAtStartThreshold", default = 1.0, internal)]
3744 LoadMoreAtStartThreshold(f32),
3745 /// The item index a list cell now renders (set by the runtime after
3746 /// each bind, in the same batch as the cell's new content).
3747 #[prop(js = "cellIndex", internal)]
3748 CellIndex(u32),
3749 /// `scrollValue`: an animated value fed with the scroll offset (main axis), for
3750 /// scroll-linked effects.
3751 #[prop(js = "scrollValue", with = crate::js::host_values::scroll_value, reset = Prop::ScrollValue(None), ts = "AnimatedValue", on = SCROLL | LIST)]
3752 ScrollValue(Option<crate::animation::NodeId>),
3753 /// `pullValue`: an animated value fed with how far a vertical scroll
3754 /// view is pulled past its top (0 at rest, growing with the pull; the
3755 /// room kept above the content while it refreshes), for an app's own
3756 /// pull-to-refresh indicator.
3757 #[prop(js = "pullValue", with = crate::js::host_values::pull_value, reset = Prop::PullValue(None), ts = "AnimatedValue", on = SCROLL | LIST)]
3758 PullValue(Option<crate::animation::NodeId>),
3759 /// `pan`: drags drive these animated values (points) on the UI thread.
3760 #[prop(js = "pan", with = crate::js::host_values::pan, reset = Prop::PanValues(None, None), ts = "{ x?: AnimatedValue; y?: AnimatedValue }")]
3761 PanValues(
3762 Option<crate::animation::NodeId>,
3763 Option<crate::animation::NodeId>,
3764 ),
3765 /// `value`: the text, controlled by JS.
3766 #[prop(js = "value", on = INPUT, shared)]
3767 Value(String),
3768 /// `defaultValue`: the initial text.
3769 #[prop(js = "defaultValue", once, on = INPUT)]
3770 DefaultValue(String),
3771 /// `placeholder`: shown while the input is empty.
3772 #[prop(js = "placeholder", on = INPUT, shared)]
3773 Placeholder(String),
3774 /// The placeholder's color (Rust components; TS sets the
3775 /// `placeholderColor` style key or `placeholder:text-*`).
3776 PlaceholderColor(Option<Color>),
3777 /// `masked`: the text is hidden (passwords).
3778 #[prop(js = "masked", on = INPUT)]
3779 Secure(bool),
3780 /// `keyboardType`: the keyboard layout.
3781 #[prop(js = "keyboardType", on = INPUT)]
3782 KeyboardType(KeyboardType),
3783 /// `keyboardAppearance` (iOS): the keyboard's light or dark look;
3784 /// Android's keyboards follow the system's theme.
3785 #[prop(ios = "keyboardAppearance", on = INPUT)]
3786 KeyboardAppearance(KeyboardAppearance),
3787 /// `returnKeyType`: the label of the return key.
3788 #[prop(js = "returnKeyType", on = INPUT)]
3789 ReturnKeyType(ReturnKeyType),
3790 /// `autoCapitalize`: automatic capitalization (default `"sentences"`).
3791 #[prop(js = "autoCapitalize", on = INPUT)]
3792 AutoCapitalize(AutoCapitalize),
3793 /// `autoCorrect`: the system's corrections (default true).
3794 #[prop(js = "autoCorrect", default = true, on = INPUT)]
3795 AutoCorrect(bool),
3796 /// `multiline`: several lines; return inserts a line break.
3797 #[prop(js = "multiline", on = INPUT)]
3798 Multiline(bool),
3799 /// `maxLength`: the most characters the user can enter, counted as
3800 /// Unicode code points on every platform (an emoji such as 😀 is one).
3801 /// A longer paste goes in cut to what fits, never inside a character
3802 /// such as an emoji with its skin tone.
3803 #[prop(js = "maxLength", on = INPUT)]
3804 MaxLength(Option<u32>),
3805 /// `readonly`: the user can select and copy the text but not change it.
3806 #[prop(js = "readonly", on = INPUT)]
3807 Readonly(bool),
3808 /// `submitBehavior`: what return does: `"submit"` (reports
3809 /// `onSubmit`, keeps the focus), `"blurAndSubmit"` (also
3810 /// unfocuses), `"newline"` (inserts a line break; multiline inputs
3811 /// only). Default: `"blurAndSubmit"` for one line, `"newline"` for
3812 /// several. A multiline input that submits still takes line breaks
3813 /// from Shift+Return or Option / Alt+Return on desktops.
3814 #[prop(js = "submitBehavior", on = INPUT)]
3815 SubmitBehavior(Option<SubmitBehavior>),
3816 /// `pasteBehavior`: what a paste does: `"insert"` (default) inserts its
3817 /// text, `"report"` inserts nothing; `onPaste` reports what was pasted
3818 /// either way. Decided natively when the user pastes.
3819 #[prop(js = "pasteBehavior", on = INPUT)]
3820 PasteBehavior(PasteBehavior),
3821 /// `pasteMaxSize`: the largest pasted file read, in bytes; a larger
3822 /// one reaches `onPaste` in `tooLarge`, its name, type and size only,
3823 /// so the app can tell the user. Decided natively when the user
3824 /// pastes, before the file is read where the platform says its size.
3825 /// Default: every file is read.
3826 #[prop(js = "pasteMaxSize", on = INPUT)]
3827 PasteMaxSize(Option<u64>),
3828 /// `autoFocus`: focused when it appears.
3829 #[prop(js = "autoFocus", on = INPUT)]
3830 AutoFocus(bool),
3831 /// `selectTextOnFocus`: the whole text is selected when the input takes
3832 /// the focus (a click, Tab, `focus()`, `autoFocus`). Decided natively as
3833 /// the focus arrives; a click that drags, extends (Shift) or selects
3834 /// words (double click) keeps the user's selection.
3835 #[prop(js = "selectTextOnFocus", on = INPUT)]
3836 SelectTextOnFocus(bool),
3837 /// `caret`: the caret is drawn (default true; `false` hides it).
3838 #[prop(js = "caret", default = true, on = INPUT)]
3839 Caret(bool),
3840 /// `inputAccessoryViewID`: the `nativeID` of an `InputAccessoryView`
3841 /// (`nsh/ios`) shown over the keyboard while the input has focus.
3842 #[prop(ios = "inputAccessoryViewID", on = INPUT)]
3843 InputAccessoryViewId(Option<Box<str>>),
3844 /// `nativeID`: names the view for others: an input accessory's for
3845 /// `inputAccessoryViewID`, a scroll view's for the embedding app's
3846 /// `watchScroll`.
3847 #[prop(js = "nativeID")]
3848 NativeId(Option<Box<str>>),
3849 /// The highlight of an input's or a selectable text's selection (Rust
3850 /// components; TS sets the `selectionColor` style key or
3851 /// `selection:bg-*`).
3852 SelectionColor(Option<Color>),
3853 /// An input's caret (Rust components; TS sets the `caretColor` style
3854 /// key or `caret-*`).
3855 CaretColor(Option<Color>),
3856 /// `autoComplete` (iOS: also `textContentType`): what an input holds, for
3857 /// autofill (React Native's values, e.g. "username", "current-password",
3858 /// "new-password", "one-time-code", "email", "tel", "postal-code", "cc-number",
3859 /// "off").
3860 #[prop(js = "autoComplete", ios = "textContentType", on = INPUT)]
3861 AutoFill(AutoFill),
3862 /// `selectedRange`: the controlled selection (UTF-16 units; `end` defaults to
3863 /// `start`, a caret).
3864 #[prop(js = "selectedRange", with = crate::js::host_values::selection, once, ts = "{ start: number; end?: number }", on = INPUT)]
3865 Selection(u32, u32),
3866 /// `keyboardDismissMode`: whether dragging dismisses the keyboard.
3867 #[prop(js = "keyboardDismissMode", on = SCROLL | LIST)]
3868 KeyboardDismissMode(KeyboardDismissMode),
3869 /// Touch handling of the view and its children (React Native
3870 /// semantics), which wins over the style's `pointerEvents` unless
3871 /// `auto`. Set by the core (a tooltip's overlay), never by JS.
3872 PointerEvents(PointerEvents),
3873 /// `hitSlop`: extends the touch area beyond the bounds.
3874 #[prop(js = "hitSlop", with = crate::js::host_values::hit_slop, reset = Prop::HitSlop(EdgeInsets::default()), ts = "number | Partial<Edges>")]
3875 HitSlop(EdgeInsets),
3876 /// Where a link goes (`nsh/base`'s `Link` sets its `href`, `TextView`
3877 /// its links' URL on their span), carried to the platform as data: a
3878 /// terminal draws the text inside the view as a hyperlink to it, and a
3879 /// span's is recorded in its block's text
3880 /// (`AttributedText::link_hrefs`).
3881 /// Set by the link components, never by JS.
3882 Href(Option<Arc<str>>),
3883 /// `panActivation`: the view's touch responder waits for a pan that the
3884 /// platform activates past an offset on one axis (and fails past one on
3885 /// the other), deciding on the main thread so the scroll views around
3886 /// it keep the touches until then.
3887 #[prop(js = "panActivation")]
3888 PanActivation(Option<crate::props::PanActivation>),
3889 /// Whether native pans may start or update their bound values. Rust
3890 /// components use this to retain gesture state across permission changes.
3891 PanEnabled(bool),
3892 /// A vertical pan cooperates with descendant scroll views on iOS:
3893 /// scrolling consumes the drag until its top, then the pan follows.
3894 PanScrollHandoff(bool),
3895 /// `activeStyle`: the style while pressed (and not disabled), over the
3896 /// view's style; applied natively, no JS round trip.
3897 ActiveStyle(Option<std::rc::Rc<StylePatch>>),
3898 /// `hoverStyle`: the style while a pointer is over the view (and it is
3899 /// not disabled).
3900 HoverStyle(Option<std::rc::Rc<StylePatch>>),
3901 /// `focusStyle`: the style while the view has focus (and is not
3902 /// disabled).
3903 FocusStyle(Option<std::rc::Rc<StylePatch>>),
3904 /// `disabledStyle`: the style while `disabled`, over every other state's.
3905 DisabledStyle(Option<std::rc::Rc<StylePatch>>),
3906 /// `selectedStyle`: the style while `accessibilityState.selected` (a
3907 /// `Button`'s `selected`), and not disabled.
3908 SelectedStyle(Option<std::rc::Rc<StylePatch>>),
3909 /// `checkedStyle`: the style while `accessibilityState.checked` (true,
3910 /// not mixed: a checkbox's, a switch's, a radio's), and not disabled.
3911 CheckedStyle(Option<std::rc::Rc<StylePatch>>),
3912 /// `indeterminateStyle`: the style while `accessibilityState.checked`
3913 /// is mixed (a checkbox's `indeterminate`), and not disabled.
3914 IndeterminateStyle(Option<std::rc::Rc<StylePatch>>),
3915 /// `expandedStyle`: the style while `accessibilityState.expanded` (a
3916 /// `Popover`'s or `Menu`'s trigger while its popup is open), and not
3917 /// disabled.
3918 ExpandedStyle(Option<std::rc::Rc<StylePatch>>),
3919 /// `pressedStyle`: the style while `accessibilityState.pressed` (true,
3920 /// not mixed: a toggle button that is on), and not disabled. Not
3921 /// `activeStyle`, a press in progress.
3922 PressedStyle(Option<std::rc::Rc<StylePatch>>),
3923 /// `focusWithinStyle`: the style while the keyboard focus is on the
3924 /// view or a view inside it (an overlay's content counting as inside
3925 /// the view it is in), and it is not disabled.
3926 FocusWithinStyle(Option<std::rc::Rc<StylePatch>>),
3927 /// `focusVisibleStyle`: the style while the view has focus and shows
3928 /// it (`focus-visible:`: the keyboard moved the focus there, or it is
3929 /// an input that edits), and it is not disabled.
3930 FocusVisibleStyle(Option<std::rc::Rc<StylePatch>>),
3931 /// The states a part of a control shows its classes and state styles
3932 /// as its control has them ([`crate::tailwind::state`] bits: `checked`,
3933 /// `indeterminate`, `disabled`): a switch's thumb styled `checked:`
3934 /// while the switch is on. They tell screen readers nothing and take no
3935 /// presses away: the control announces and handles them. Set by
3936 /// components (`Interactive::project_checked`, `project_indeterminate`,
3937 /// `project_disabled`), never by JS.
3938 ProjectedStates(u16),
3939 /// The group whose press a part of a control shows as its own (`None`:
3940 /// none): its `active:` classes and active style apply while that
3941 /// group around it is pressed, as the platform reports the group's
3942 /// press (a switch's thumb while the switch is held). Set by components
3943 /// (`Interactive::project_group_active`), never by JS.
3944 ProjectedActive(Option<&'static str>),
3945 /// The boolean `data-*` attributes a part of a component shows, by
3946 /// name without `data-` and sorted: its `data-<name>:` classes apply,
3947 /// and with `group` the `group-data-<name>:` classes inside it (a
3948 /// calendar's day at the start of a range, `data-range-start`). They
3949 /// tell screen readers nothing. Set by components
3950 /// (`Interactive::project_data`), never by JS.
3951 ProjectedData(Box<[&'static str]>),
3952 /// `headerStyle` of a page: `backgroundColor`, `color` (the title's) and
3953 /// `tintColor` (the buttons') of its header.
3954 HeaderStyle(Option<std::rc::Rc<StylePatch>>),
3955 /// `headerClass` of a page: the header's colors as classes (`bg-*`,
3956 /// `text-*`, `tint-*`); `headerStyle` wins over them.
3957 HeaderClass(Box<str>),
3958 /// A page header's colors as typed styles lowered as classes are (Rust:
3959 /// `Screen::header_style_with`), in place of `headerClass`;
3960 /// `headerStyle` wins over them. Set by components, never by JS.
3961 HeaderClassList(Option<std::rc::Rc<crate::tailwind::ClassList>>),
3962 /// The surface lays out right to left (on the root, from the user's
3963 /// language).
3964 #[prop(js = "layoutDirectionRtl", internal)]
3965 LayoutDirection(bool),
3966 /// The app's appearance (on the root, from `nsh.json` and
3967 /// `setColorScheme`).
3968 #[prop(js = "appearance", internal)]
3969 Appearance(crate::platform::Appearance),
3970 /// The surface's keyboard shortcuts (on the root, from `nsh/keymap`):
3971 /// the whole table, mounted as [`crate::MountItem::Keymap`].
3972 Keymap(std::sync::Arc<crate::keymap::Keymap>),
3973 /// Padding added to the style's own (safe areas, the keyboard), in
3974 /// points on the physical edges; set by components
3975 /// (`Element::inset_padding`), never by JS.
3976 InsetPadding(EdgeInsets),
3977 /// Margin added to the style's own (an inset margin), in points on the physical edges; set by
3978 /// components.
3979 InsetMargin(EdgeInsets),
3980 /// `class`: Tailwind CSS classes (`"flex-row gap-2 p-4 bg-white
3981 /// dark:bg-zinc-900"`), resolved natively. Later classes win over earlier ones;
3982 /// `style` wins over both.
3983 #[prop(js = "class")]
3984 Class(Box<str>),
3985 /// `classList`: classes applied while their value is truthy (`{ "opacity-50":
3986 /// busy() }`).
3987 #[prop(js = "classList", with = crate::js::host_values::class_list, reset = Prop::ClassList(Vec::new()), ts = "Record<string, boolean | null | undefined>")]
3988 ClassList(Vec<Box<str>>),
3989 /// The app's Tailwind theme (JSON, on the root).
3990 #[prop(js = "tailwindTheme", with = crate::js::host_values::tailwind_theme, internal)]
3991 TailwindTheme(Box<str>),
3992 /// The theme of Rust components (`nsh.json` `theme`, JSON), on the
3993 /// root.
3994 #[prop(js = "uiTheme", with = crate::js::host_values::ui_theme, internal)]
3995 UiTheme(Box<str>),
3996 /// The distance overlays without a `margin` keep from the window's
3997 /// edges (`setSnapToWindowMargin`), on the root.
3998 #[prop(js = "snapToWindowMargin", with = crate::js::host_values::snap_to_window_margin, internal)]
3999 SnapToWindowMargin(Points),
4000 /// An image option.
4001 #[prop(nested)]
4002 Image(ImageProp),
4003 /// `delayLongPress`: milliseconds before a press becomes a long press (default
4004 /// 500).
4005 #[prop(js = "delayLongPress", min = 0)]
4006 LongPressDelay(Option<f32>),
4007 /// `ripple` (Android): the material ripple while pressed.
4008 #[prop(android = "ripple")]
4009 Ripple(Option<crate::props::Ripple>),
4010 /// `elevation` (Android): the material shadow (points), from the view's shape.
4011 #[prop(android = "elevation")]
4012 Elevation(Points),
4013 /// The system material of a backdrop blur (iOS, default `ultraThin`).
4014 #[prop(ios = "backdropMaterial")]
4015 BackdropMaterial(crate::BackdropMaterial),
4016 /// `ios={{ scrollEdgeElement }}`: the scroll view the view floats over
4017 /// and the edge of it the view sits at (iOS 26: that scroll view's edge
4018 /// effect takes its shape from the view); `None`: none.
4019 #[prop(ios = "scrollEdgeElement")]
4020 ScrollEdgeElement(Option<crate::element::ScrollEdgeTarget>),
4021 /// `macos={{ backdrop }}`: the `NSVisualEffectView` material on macOS
4022 /// (default `popover` / `withinWindow` / `active`; `None`: none).
4023 #[prop(macos = "backdrop")]
4024 MacOsBackdrop(Option<crate::MacOsBackdrop>),
4025 /// `windows={{ backdrop }}`: `{ material: "blur" }` draws the system's blur
4026 /// of what is behind a transparent window under the view, on Windows 11.
4027 #[prop(windows = "backdrop")]
4028 WindowsBackdrop(Option<crate::WindowsBackdrop>),
4029 /// An accessibility property.
4030 #[prop(nested)]
4031 Accessibility(AccessibilityProp),
4032 /// `testID`: an identifier for UI tests.
4033 #[prop(js = "testID")]
4034 TestId(Option<Arc<str>>),
4035 /// Internal: the view already stands clear of the software keyboard
4036 /// (a bottom sheet the keyboard lifts), so `env(keyboard-inset-height)`
4037 /// reads 0 in it and in its subtree: padding by it there would lift
4038 /// the content a second time.
4039 #[doc(hidden)]
4040 #[prop(reset = Prop::ClearsKeyboard(false))]
4041 ClearsKeyboard(bool),
4042 /// `copyText`: what a copy of the text around the view gives in its
4043 /// place, when the view (or image) is inside a text (an inline
4044 /// formula's source, an emoji image's character): selecting across it
4045 /// and copying puts this there. Unset, the view adds nothing to the
4046 /// copy. A view outside a text and a nested text span ignore it.
4047 #[prop(js = "copyText")]
4048 CopyText(Option<Arc<str>>),
4049 /// `web={{ element }}`: the HTML element the web draws the view or text
4050 /// as (`"p"`, `"nav"`, `"article"`, ...), for what `role` cannot say;
4051 /// the other platforms keep the view as it is.
4052 #[prop(web = "element")]
4053 WebElement(Option<WebElement>),
4054 /// `windowDrag` (desktops): pressing the view drags the window, as its
4055 /// title bar would (double-clicking maximizes it); `false` keeps a part
4056 /// of a draggable view clickable. The nearest view that sets it
4057 /// decides; text fields and views with press or touch handlers inside
4058 /// a draggable view stay clickable without it.
4059 #[prop(desktop = "windowDrag")]
4060 WindowDrag(Option<bool>),
4061 /// `windowControl` (desktops): the view of a title bar the app draws
4062 /// acts as one of the system's window buttons (minimize, maximize,
4063 /// close): the platform hit-tests it as that button and carries out its
4064 /// press.
4065 #[prop(desktop = "windowControl")]
4066 WindowControl(Option<crate::desktop::WindowControl>),
4067 /// `windowResize` (desktops): pressing the view resizes a frameless
4068 /// window by that edge or corner.
4069 #[prop(desktop = "windowResize")]
4070 WindowResize(Option<crate::desktop::ResizeEdge>),
4071 /// `tooltip`: a hint about the view, shown above it on the desktops
4072 /// while the pointer rests on it (after half a second) until the
4073 /// pointer leaves or presses it, never on touch screens; it never takes
4074 /// the pointer. The element is shown as it is; a `Tooltip` of
4075 /// `nsh/base` is the tooltip itself, with its placement, delay and
4076 /// events.
4077 #[prop(js = "tooltip", with = crate::js::host_values::tooltip, reset = Prop::Tooltip(TooltipContent::None), ts = "JSX.Element")]
4078 Tooltip(TooltipContent),
4079 /// `focusable`: whether the view is a stop of the keyboard focus (Tab,
4080 /// on the platforms that move it between views): `true` makes any view
4081 /// one, whether or not it takes presses (a chart or a slider in a
4082 /// pressable card, which takes its keys while focused); `false` leaves
4083 /// a view that takes presses to the pointer (a backdrop that closes a
4084 /// popover). Unset, the views that take presses are stops.
4085 #[prop(js = "focusable")]
4086 Focusable(Option<bool>),
4087 /// `captureKeys`: the hardware keys this view or a focused descendant
4088 /// consumes before native defaults run: `"none"`, `"all"`, or the
4089 /// canonical keystrokes (`"mod+k"`, `"shift+tab"`) it takes. Decided
4090 /// from mounted props; eligible app shortcuts and focused native
4091 /// inputs keep their keys. Omitting it restores `"none"`.
4092 #[prop(js = "captureKeys", reset = Prop::KeyCapture(crate::KeyCapture::None))]
4093 KeyCapture(crate::KeyCapture),
4094 /// `selectable` of a view: the texts in it share one selection, as a
4095 /// browser page's do ([`crate::selection`]); texts with
4096 /// `selectable={false}` stay out of it, a selectable view inside
4097 /// another is part of the outer one.
4098 #[prop(js = "selectable", on = VIEW, shared)]
4099 SelectableView(bool),
4100 /// `selectionMenu` of a selectable view: the app's items of the
4101 /// system's selection menu (iOS's edit menu, Android's floating text
4102 /// actions, the desktops' secondary-click menu), after the system's own,
4103 /// which stay. Plain items and separators only: submenus, roles,
4104 /// shortcuts and check marks are left out. A chosen item is reported
4105 /// as the root's [`EventKind::Menu`] with its id, as a menu's; the web
4106 /// shows the browser's menu alone. Empty is unset.
4107 #[prop(js = "selectionMenu", on = VIEW, with = crate::js::host_values::selection_menu, reset = Prop::SelectionMenu(Vec::new()), ts = "import(\"nsh/desktop\").MenuItem[]")]
4108 SelectionMenu(Vec<crate::desktop::MenuItem>),
4109 /// The text continues the text before it in document order (a long
4110 /// line's next wrapped part): a selection's copy joins the two with
4111 /// nothing between them, and a double or triple click selects across
4112 /// them ([`crate::selection`]). Set by components
4113 /// (`Element::continues_text`), never by JS.
4114 ContinuesText(bool),
4115 /// The view's children take its own position among its siblings
4116 /// (`first:`, `last:`, `odd:`, `even:`, `only:`), not theirs among
4117 /// its children: a node that only wraps its content. Set by
4118 /// components (`Element::__pass_position`), never by JS.
4119 PassPosition(bool),
4120 /// `allowFontScaling`: follow the system text size (default true).
4121 #[prop(js = "allowFontScaling", default = true, on = TEXT | INPUT)]
4122 AllowFontScaling(bool),
4123 /// `maxFontSizeMultiplier`: the upper bound of the system scale (0 is none).
4124 #[prop(js = "maxFontSizeMultiplier", min = 0, on = TEXT | INPUT)]
4125 MaxFontSizeMultiplier(f32),
4126 /// `adjustsFontSizeToFit`: shrink the font until the text fits its lines
4127 /// (`numberOfLines`) and box.
4128 #[prop(js = "adjustsFontSizeToFit", on = TEXT)]
4129 AdjustsFontSizeToFit(bool),
4130 /// `minimumFontScale`: how far `adjustsFontSizeToFit` shrinks at most (0..1).
4131 #[prop(js = "minimumFontScale", min = 0, max = 1, on = TEXT)]
4132 MinimumFontScale(f32),
4133 /// `pinch`: two-finger pinches drive `scale` natively.
4134 #[prop(js = "pinch", with = crate::js::host_values::pinch, reset = Prop::PinchValue(None), ts = "{ scale?: AnimatedValue }")]
4135 PinchValue(Option<crate::animation::NodeId>),
4136 /// `rotation`: two-finger rotations drive `angle` (degrees) natively.
4137 #[prop(js = "rotation", with = crate::js::host_values::rotation, reset = Prop::RotationValue(None), ts = "{ angle?: AnimatedValue }")]
4138 RotationValue(Option<crate::animation::NodeId>),
4139 /// A screen option.
4140 #[prop(nested)]
4141 Screen(ScreenProp),
4142 /// A modal option.
4143 #[prop(nested)]
4144 Modal(ModalProp),
4145 /// An overlay option.
4146 #[prop(nested)]
4147 Overlay(OverlayProp),
4148 /// `<headeritem slot>`.
4149 #[prop(js = "headerSlot", internal)]
4150 HeaderSlot(HeaderSlot),
4151 /// A property of a native control (web view, video), or `disabled`.
4152 #[prop(nested)]
4153 Native(NativeProp),
4154}
4155
4156/// Where a web view loads from.
4157#[derive(Debug, Clone, PartialEq)]
4158pub enum WebSource {
4159 /// Nothing.
4160 None,
4161 /// A URL (`src`).
4162 Uri(Arc<str>),
4163 /// HTML, with the URL relative links resolve against.
4164 Html {
4165 /// The page.
4166 html: Arc<str>,
4167 /// Base URL.
4168 base_url: Option<Arc<str>>,
4169 },
4170}
4171
4172/// A property of a native control.
4173#[derive(Debug, Clone, PartialEq, HostProps)]
4174pub enum NativeProp {
4175 /// `disabled` (any element): ignores presses (no press feedback either),
4176 /// applies `disabled:` classes, disables controls, and screen readers
4177 /// say it is disabled (its accessibility state).
4178 #[prop(js = "disabled")]
4179 Disabled(bool),
4180 /// What a web view or video loads, as Rust sets it (TS sets `src`,
4181 /// `html` and `baseUrl`).
4182 Source(WebSource),
4183 /// `src` of a web view or video: the URL it loads.
4184 #[prop(js = "src", on = WEBVIEW | VIDEO, shared)]
4185 Src(Option<Arc<str>>),
4186 /// `poster` (videos): an image shown until the video's first frame is ready.
4187 #[prop(js = "poster", on = VIDEO)]
4188 Poster(Option<Arc<str>>),
4189 /// `html` (web views): the page to show instead of loading `src`.
4190 #[prop(js = "html", on = WEBVIEW)]
4191 Html(Option<Arc<str>>),
4192 /// `baseUrl` (web views): the URL the relative links of `html`
4193 /// resolve against.
4194 #[prop(js = "baseUrl", on = WEBVIEW)]
4195 BaseUrl(Option<Arc<str>>),
4196 /// `allowOrigin` (web views): one more origin this web view may show and
4197 /// navigate to besides `webview.hosts`, for an origin known only while
4198 /// the app runs: `scheme://host[:port]`, `http` or `https`, matched
4199 /// exactly ([`crate::access::WebOrigin`]). It needs
4200 /// `"runtimeOrigin": true` in `capabilities.webview`; another value or
4201 /// no grant is refused with a message and the web view has none. Set
4202 /// with `src` in the same render, it applies to that `src`; changed
4203 /// later, it applies from the next navigation. Other web views and
4204 /// the windows a page opens do not have it.
4205 #[prop(js = "allowOrigin", on = WEBVIEW)]
4206 AllowOrigin(Option<Arc<str>>),
4207 /// `allowNavigation` (web views): the hosts this web view may show and
4208 /// navigate to, narrower than `webview.hosts`: the same host patterns
4209 /// (`*`, `*.example.com`, a host name), and an empty list refuses every
4210 /// web page ([`crate::access::WebHosts`]). The platform refuses any
4211 /// other `http` or `https` page before its request is made and reports
4212 /// `onError` with `ERR_ACCESS_DENIED` and the `url`. It never widens
4213 /// the app's grant. A list with a pattern that does not read is refused
4214 /// with a message and the web view is not narrowed.
4215 #[prop(js = "allowNavigation", on = WEBVIEW)]
4216 AllowNavigation(Option<Vec<Arc<str>>>),
4217 /// `injectedJavaScript` (web views): runs after each page loads.
4218 #[prop(js = "injectedJavaScript", on = WEBVIEW)]
4219 InjectedJavaScript(Option<Arc<str>>),
4220 /// `injectedJavaScriptBeforeContentLoaded` (web views): runs before each page's
4221 /// own scripts.
4222 #[prop(js = "injectedJavaScriptBeforeContentLoaded", on = WEBVIEW)]
4223 InjectedJavaScriptBefore(Option<Arc<str>>),
4224 /// `userAgent` (web views): the browser's user agent string.
4225 #[prop(js = "userAgent", on = WEBVIEW)]
4226 UserAgent(Option<Arc<str>>),
4227 /// `scrollable`: the user can scroll it (default true).
4228 #[prop(js = "scrollable", default = true, on = WEBVIEW | SCROLLING)]
4229 Scrollable(bool),
4230 /// `javaScriptEnabled` (web views): pages run scripts (default true).
4231 #[prop(js = "javaScriptEnabled", default = true, on = WEBVIEW)]
4232 JavaScriptEnabled(bool),
4233 /// `allowsBackForwardNavigationGestures` (iOS web views; desktop ones on
4234 /// macOS, with two-finger trackpad swipes): swipe back and forward.
4235 #[prop(
4236 ios = "allowsBackForwardNavigationGestures",
4237 desktop = "allowsBackForwardNavigationGestures",
4238 on = WEBVIEW
4239 )]
4240 BackForwardGestures(bool),
4241 /// `incognito` (web views): the page's website data (cookies, storage,
4242 /// the cache) lives only as long as the web view, apart from the app's
4243 /// other web views; on Android, where every web view shares the app's
4244 /// cookies and storage, it loads without the HTTP cache and saves no
4245 /// form data. Read when the web view is made; a later change is ignored
4246 /// (with a warning): render a new element to change it.
4247 #[prop(js = "incognito", on = WEBVIEW)]
4248 Incognito(bool),
4249 /// `zoomable` (web views): the person can pinch to zoom the page, also
4250 /// past the scale limits of its viewport (Android's built-in zoom with
4251 /// no on-screen buttons, WebKit ignoring the viewport's scale limits on
4252 /// iOS, magnification on macOS). False keeps each platform's own
4253 /// behavior: Android and macOS do not zoom, iOS zooms as far as the
4254 /// page's viewport allows, WebView2 (Windows) zooms by default. Read
4255 /// when the web view is made, as `incognito`.
4256 #[prop(js = "zoomable", on = WEBVIEW, shared)]
4257 Zoomable(bool),
4258 /// The URL schemes a web view serves from the app (Rust's
4259 /// `WebView::url_scheme`). Read when the web view is made, as
4260 /// `incognito`.
4261 UrlSchemes(Vec<crate::web_resource::WebUrlScheme>),
4262 /// Internal: the web view has an `on_download` or
4263 /// `on_download_pending` listener, so it must hold its downloads for
4264 /// the core (which chooses automatic versus manual from the
4265 /// listeners). Without either listener the platform keeps its own
4266 /// download behavior.
4267 #[doc(hidden)]
4268 #[prop(internal, reset = NativeProp::DeferDownloads(false))]
4269 DeferDownloads(bool),
4270 /// `paused` (videos): playback is paused.
4271 #[prop(js = "paused", on = VIDEO, shared)]
4272 Paused(bool),
4273 /// `muted` (videos): no sound.
4274 #[prop(js = "muted", on = VIDEO)]
4275 Muted(bool),
4276 /// `volume` (videos): 0..1.
4277 #[prop(js = "volume", default = 1.0, on = VIDEO)]
4278 Volume(f32),
4279 /// `rate` (videos): the playback speed.
4280 #[prop(js = "rate", default = 1.0, on = VIDEO)]
4281 Rate(f32),
4282 /// `repeat` (videos): plays again from the start at the end.
4283 #[prop(js = "repeat", on = VIDEO)]
4284 Repeat(bool),
4285 /// How a video fits its box (`objectFit`, a Rust `resize_mode`).
4286 #[prop(reset = NativeProp::VideoResizeMode(ResizeMode::Contain))]
4287 VideoResizeMode(ResizeMode),
4288 /// `controls` (videos): the platform's playback controls.
4289 #[prop(js = "controls", on = VIDEO)]
4290 Controls(bool),
4291 /// `progressUpdateInterval` (videos): milliseconds between `onProgress` events
4292 /// (250 by default).
4293 #[prop(js = "progressUpdateInterval", default = 250.0, on = VIDEO)]
4294 ProgressInterval(f32),
4295 /// `audioSession` (videos): what the sound does to the rest of the
4296 /// device's audio while it plays (`"default"` when unset: the app's
4297 /// audio settings).
4298 #[prop(
4299 js = "audioSession",
4300 reset = NativeProp::AudioSession(crate::AudioSession::Default),
4301 on = VIDEO
4302 )]
4303 AudioSession(crate::AudioSession),
4304}
4305
4306/// A mutation produced by the JS renderer.
4307#[derive(Debug)]
4308pub enum Op {
4309 /// `ref.evaluate(script, { timeout })` of a web view, in order with
4310 /// the UI's ops: JS promise `call` settles with its result.
4311 Evaluate {
4312 /// The web view.
4313 id: NodeId,
4314 /// The JS promise's call number.
4315 call: u32,
4316 /// The app's script.
4317 script: String,
4318 /// How long the script may take to answer.
4319 timeout: std::time::Duration,
4320 },
4321 /// `OffscreenCanvas`'s `convertToBlob`: render `drawing` into an image
4322 /// ([`crate::canvas::render`]); JS promise `call` settles with its
4323 /// bytes (a `Uint8Array`) or the failure.
4324 RenderCanvas {
4325 /// The JS promise's call number.
4326 call: u32,
4327 /// What to render.
4328 request: Box<crate::canvas::render::RenderRequest>,
4329 },
4330 /// What a canvas draws (replaces the previous drawing).
4331 Draw {
4332 /// The canvas.
4333 id: NodeId,
4334 /// The recorded operations.
4335 drawing: Box<crate::canvas::Drawing>,
4336 },
4337 /// Creates a detached element node.
4338 Create {
4339 /// New node id.
4340 id: NodeId,
4341 /// Element tag.
4342 tag: Tag,
4343 },
4344 /// Creates a detached raw text node.
4345 CreateText {
4346 /// New node id.
4347 id: NodeId,
4348 /// Text content.
4349 text: String,
4350 },
4351 /// Replaces the content of a raw text node.
4352 SetText {
4353 /// Text node id.
4354 id: NodeId,
4355 /// New content.
4356 text: String,
4357 },
4358 /// Replaces the whole style of a node.
4359 SetStyle {
4360 /// Node id.
4361 id: NodeId,
4362 /// The new style; boxed because layout styles are large.
4363 style: Box<Style>,
4364 /// The declarations `style` was built from, applied again over the
4365 /// node's class styles.
4366 patch: StylePatch,
4367 },
4368 /// Sets a non-style property.
4369 SetProp {
4370 /// Node id.
4371 id: NodeId,
4372 /// The property.
4373 prop: Prop,
4374 },
4375 /// Enables or disables an event listener on a node.
4376 Listen {
4377 /// Node id.
4378 id: NodeId,
4379 /// Event kind.
4380 event: EventKind,
4381 /// Whether a handler is attached.
4382 enabled: bool,
4383 },
4384 /// Inserts (or moves) `child` into `parent` before `before`, or appends.
4385 Insert {
4386 /// Parent node id.
4387 parent: NodeId,
4388 /// Child node id.
4389 child: NodeId,
4390 /// Sibling to insert before; `None` appends.
4391 before: Option<NodeId>,
4392 },
4393 /// Marks detached view `id` the stand-in of an `<Each>` row not
4394 /// rendered yet, sized like its rendered siblings: the core asks JS to
4395 /// render the row once the view would be made
4396 /// ([`crate::element::JsEvent::Rows`]).
4397 Placeholder {
4398 /// Node id.
4399 id: NodeId,
4400 },
4401 /// Detaches `child` from `parent`. The child stays alive until released.
4402 Remove {
4403 /// Parent node id.
4404 parent: NodeId,
4405 /// Child node id.
4406 child: NodeId,
4407 },
4408 /// The JS node was garbage collected: free the node and its native view.
4409 Release {
4410 /// Node id.
4411 id: NodeId,
4412 },
4413 /// An animation graph change, forwarded to the platform in order.
4414 Animation(AnimationOp),
4415 /// An imperative call on a node's native view.
4416 Command {
4417 /// Node id.
4418 id: NodeId,
4419 /// The call.
4420 command: Command,
4421 },
4422 /// A call JS made into Rust that runs in order with the UI's ops: a
4423 /// module function with a context, the start of an `async` function or
4424 /// member, a method of a component's ref, or the place of a JS call
4425 /// posted during a synchronous call ([`crate::element::RustCall`]). Never
4426 /// reaches a platform.
4427 Rust(crate::element::RustOp),
4428}
4429
4430#[cfg(test)]
4431mod tests {
4432 use super::{EventKind, TouchEvent, TouchPhase, TouchPoint};
4433 use crate::geometry::{Point, Points};
4434
4435 fn pen_move(x: f32, pressure: f32, timestamp: f64) -> TouchEvent {
4436 let page = Point {
4437 x: Points(x),
4438 y: Points(10.0),
4439 };
4440 let mut point = TouchPoint {
4441 id: 1,
4442 target: 2,
4443 path: Vec::new(),
4444 page,
4445 location: Point {
4446 x: Points(x - 5.0),
4447 y: Points(0.0),
4448 },
4449 changed: true,
4450 pointer_type: super::PointerType::Pen,
4451 pressure,
4452 tilt_x: 0.0,
4453 tilt_y: 0.0,
4454 coalesced: Vec::new(),
4455 eraser: false,
4456 barrel: false,
4457 };
4458 // A sample the platform merged in, half a step back.
4459 point.push_coalesced(
4460 Point {
4461 x: Points(x - 0.5),
4462 y: Points(10.0),
4463 },
4464 pressure,
4465 0.0,
4466 0.0,
4467 timestamp - 4.0,
4468 );
4469 TouchEvent {
4470 phase: TouchPhase::Move,
4471 timestamp,
4472 points: vec![point],
4473 activated: None,
4474 modifiers: Default::default(),
4475 }
4476 }
4477
4478 /// Moves merged in one engine turn keep the pen's samples in order:
4479 /// the earlier event's (its own position last), then the later one's.
4480 #[test]
4481 fn merged_moves_keep_their_samples() {
4482 let mut pending = pen_move(20.0, 0.25, 100.0);
4483 pending.merge_move(pen_move(30.0, 0.75, 108.0));
4484 let point = &pending.points[0];
4485 assert_eq!(point.page.x.0, 30.0);
4486 let xs: Vec<f32> = point.coalesced.iter().map(|c| c.page.x.0).collect();
4487 assert_eq!(xs, [19.5, 20.0, 29.5]);
4488 let times: Vec<f64> = point.coalesced.iter().map(|c| c.timestamp).collect();
4489 assert_eq!(times, [96.0, 100.0, 104.0]);
4490 // `location` keeps the target's offset from the surface.
4491 assert_eq!(point.coalesced[0].location.x.0, 14.5);
4492 assert_eq!(point.coalesced[1].pressure, 0.25);
4493 }
4494
4495 /// Android reads an event's kind by its index in [`EventKind::ALL`], so
4496 /// `Native.java`'s codes must follow this order: a kind inserted here
4497 /// and not there makes Android report the kinds after it as others.
4498 #[test]
4499 fn androids_event_codes_follow_the_kinds() {
4500 let path = concat!(
4501 env!("CARGO_MANIFEST_DIR"),
4502 "/../nsh-platform-android/java/com/longbridge/nsh/Native.java"
4503 );
4504 let java = std::fs::read_to_string(path).expect("Native.java");
4505 let codes: std::collections::HashMap<&str, usize> = java
4506 .lines()
4507 .filter_map(|line| {
4508 let rest = line.trim().strip_prefix("static final int ")?;
4509 let (name, value) = rest.strip_suffix(';')?.split_once(" = ")?;
4510 Some((name, value.parse().ok()?))
4511 })
4512 .collect();
4513 for (index, kind) in EventKind::ALL.iter().enumerate() {
4514 let prop = kind.prop_name().trim_start_matches("on");
4515 let mut name = String::new();
4516 for (i, c) in prop.chars().enumerate() {
4517 if c.is_ascii_uppercase() && i > 0 {
4518 name.push('_');
4519 }
4520 name.push(c.to_ascii_uppercase());
4521 }
4522 assert_eq!(
4523 codes.get(name.as_str()),
4524 Some(&index),
4525 "Native.{name} for {kind:?}"
4526 );
4527 }
4528 assert_eq!(
4529 codes.len(),
4530 EventKind::ALL.len(),
4531 "Native.java has codes of no kind"
4532 );
4533 }
4534}