1use super::host::{HostCx, HostInput, HostList, HostValue, field};
6use crate::{
7 AccessibilityCurrent, AccessibilityProp, AccessibilityRole, AccessibilityState, AutoFill,
8 CellSlot, EdgeInsets, HeaderItem, HeaderItemContent, HeaderSystemItem, ImageScales,
9 ImageSource, KeyboardTaps, ListContentStyle, MacOsBackdrop, MacOsBackdropBlending,
10 MacOsBackdropMaterial, MacOsBackdropState, ModalProp, Prop, RevealOptions, ScreenProp,
11 ScrollAlignment, ScrollProp, StatusBarSetting, StatusBarStyle, Viewability, WindowsBackdrop,
12 WindowsBackdropMaterial,
13 element::{ElementTarget, ScrollEdgeTarget, TsTypes},
14 geometry::{Bounds, Percentage, Points, point, size},
15 mount::ModalConfig,
16 ops::OverlayProp,
17 overlay::{OverlayAnchor, TooltipContent},
18 props::{AccessibilityActionDef, AccessibilityValue, Checked, PanActivation, Ripple},
19};
20
21impl HostValue for crate::KeyCapture {
30 fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
31 let apple = crate::element::try_apple_keys().unwrap_or(false);
32 super::host::decode_capture_keys(input, cx, apple)
33 }
34
35 fn ts_type(_: &mut TsTypes) -> String {
36 "\"none\" | \"all\" | \"text\" | readonly string[]".into()
37 }
38}
39
40fn number<I: HostInput>(input: &I, key: &str) -> Option<f32> {
41 input
42 .field(key)
43 .and_then(|v| v.as_number())
44 .map(|n| n as f32)
45}
46
47fn points<I: HostInput>(input: &I, key: &str) -> Option<Points> {
49 number(input, key).map(Points)
50}
51
52fn scales<I: HostInput>(input: &I) -> ImageScales {
55 let Some(list) = input.field("scales").and_then(|s| s.as_list()) else {
56 return ImageScales::NONE;
57 };
58 (0..list.len().min(crate::ops::SCALES_READ))
59 .filter_map(|i| list.item(i)?.as_number())
60 .map(|n| n as f32)
61 .collect()
62}
63
64impl HostValue for ImageSource {
66 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
67 if let Some(url) = input.as_string() {
68 return (!url.is_empty()).then(|| ImageSource {
69 uri: url.into(),
70 size: None,
71 scales: ImageScales::NONE,
72 data: None,
73 });
74 }
75 let url = input.field("url")?.as_string()?;
76 let extent = input.field("size");
77 let size = match extent
78 .as_ref()
79 .map(|e| (number(e, "width"), number(e, "height")))
80 {
81 Some((Some(w), Some(h))) => Some(size(Points(w), Points(h))),
82 _ => None,
83 };
84 Some(ImageSource {
85 uri: url.into(),
86 size,
87 scales: scales(input),
88 data: None,
89 })
90 }
91
92 fn ts_type(_: &mut TsTypes) -> String {
93 "string | ImageAsset".into()
94 }
95}
96
97impl HostValue for RevealOptions {
101 fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
102 let mut options = RevealOptions::default();
103 if input.is_nullish() {
104 return Some(options);
105 }
106 if !input.is_object() {
107 return None;
108 }
109 let mut alignment = |key: &str, default: ScrollAlignment| match input.field(key) {
110 Some(value) if !value.is_nullish() => {
111 <ScrollAlignment as HostValue>::decode(&value, cx)
112 }
113 _ => Some(default),
114 };
115 options.vertical = alignment("vertical", options.vertical)?;
116 options.horizontal = alignment("horizontal", options.horizontal)?;
117 if let Some(animated) = input.field("animated").and_then(|a| a.as_bool()) {
118 options.animated = animated;
119 }
120 Some(options)
121 }
122
123 fn ts_type(types: &mut TsTypes) -> String {
124 let alignment = <ScrollAlignment as HostValue>::ts_type(types);
125 types.declare("RevealOptions", |_| {
126 format!(
127 "/** How `reveal` places a view in the scroll views around it. */\n\
128 export interface RevealOptions {{\n \
129 /** Along vertical scroll views; `\"start\"` by default. */\n \
130 vertical?: {alignment};\n \
131 /** Along horizontal scroll views; `\"nearest\"` by default. */\n \
132 horizontal?: {alignment};\n \
133 /** Animate the scrolls; `true` by default. */\n \
134 animated?: boolean;\n}}"
135 )
136 })
137 }
138}
139
140impl HostValue for ListContentStyle {
143 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
144 let n = |key| points(input, key);
145 let all = n("padding").unwrap_or_default();
146 let inline = n("paddingHorizontal").unwrap_or(all);
147 let block = n("paddingVertical").unwrap_or(all);
148 let gap = n("gap").unwrap_or_default();
149 let align_items = input
150 .field("alignItems")
151 .and_then(|v| v.as_string())
152 .and_then(|v| match v.as_str() {
153 "stretch" => Some(taffy::AlignItems::STRETCH),
154 "flex-start" => Some(taffy::AlignItems::FLEX_START),
155 "center" => Some(taffy::AlignItems::CENTER),
156 "flex-end" => Some(taffy::AlignItems::FLEX_END),
157 _ => None,
158 });
159 Some(ListContentStyle {
160 padding: EdgeInsets {
161 top: n("paddingTop").unwrap_or(block),
162 right: n("paddingRight").unwrap_or(inline),
163 bottom: n("paddingBottom").unwrap_or(block),
164 left: n("paddingLeft").unwrap_or(inline),
165 },
166 row_gap: n("rowGap").unwrap_or(gap),
167 column_gap: n("columnGap").unwrap_or(gap),
168 align_items,
169 })
170 }
171
172 fn ts_type(types: &mut TsTypes) -> String {
173 types.declare("ListContentStyle", |_| {
174 "/** Padding, gaps and cell alignment of a list's content (`contentStyle`). */\n\
175 export interface ListContentStyle {\n padding?: number;\n paddingHorizontal?: number;\n \
176 paddingVertical?: number;\n paddingTop?: number;\n paddingRight?: number;\n \
177 paddingBottom?: number;\n paddingLeft?: number;\n gap?: number;\n rowGap?: number;\n \
178 columnGap?: number;\n alignItems?: \"stretch\" | \"flex-start\" | \"center\" | \"flex-end\";\n}"
179 .into()
180 })
181 }
182}
183
184impl HostValue for MacOsBackdrop {
187 fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
188 if !input.is_object() {
189 return None;
190 }
191 Some(MacOsBackdrop {
192 material: field::<MacOsBackdropMaterial, _>(input, "material", cx).unwrap_or_default(),
193 blending: field::<MacOsBackdropBlending, _>(input, "blending", cx).unwrap_or_default(),
194 state: field::<MacOsBackdropState, _>(input, "state", cx).unwrap_or_default(),
195 })
196 }
197
198 fn ts_type(types: &mut TsTypes) -> String {
199 let material = <MacOsBackdropMaterial as HostValue>::ts_type(types);
200 let blending = <MacOsBackdropBlending as HostValue>::ts_type(types);
201 let state = <MacOsBackdropState as HostValue>::ts_type(types);
202 types.declare("MacOsBackdrop", |_| {
203 format!(
204 "/** The material a view draws with on macOS (`macos={{{{ backdrop }}}}`). */\n\
205 export interface MacOsBackdrop {{\n material?: {material};\n \
206 blending?: {blending};\n state?: {state};\n}}"
207 )
208 })
209 }
210}
211
212impl HostValue for ScrollEdgeTarget {
216 fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
217 let scroll_view = input.field("scrollView")?.node()?;
218 let edge = field::<crate::ScrollEdge, _>(input, "edge", cx).unwrap_or_default();
219 Some(ScrollEdgeTarget::of_node(scroll_view, edge))
220 }
221
222 fn ts_type(types: &mut TsTypes) -> String {
223 let edge = <crate::ScrollEdge as HostValue>::ts_type(types);
224 types.declare("ScrollEdgeElement", |_| {
225 format!(
226 "/** The scroll view a view floats over and the edge of it the view sits at \
227 (`ios={{{{ scrollEdgeElement }}}}`). */\n\
228 export interface ScrollEdgeElement {{\n scrollView: ViewRef;\n \
229 edge?: {edge};\n}}"
230 )
231 })
232 }
233}
234
235impl HostValue for WindowsBackdrop {
236 fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
237 if !input.is_object() {
238 return None;
239 }
240 Some(Self {
241 material: field(input, "material", cx)?,
242 })
243 }
244
245 fn ts_type(types: &mut TsTypes) -> String {
246 let material = <WindowsBackdropMaterial as HostValue>::ts_type(types);
247 types.declare("WindowsBackdrop", |_| {
248 format!(
249 "/** The material a view draws with on Windows (`windows={{{{ backdrop }}}}`). */\n\
250 export interface WindowsBackdrop {{\n material: {material};\n}}"
251 )
252 })
253 }
254}
255
256impl HostValue for crate::SheetDetent {
260 fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
261 use crate::SheetDetent;
262 if input.is_nullish() {
263 return None;
264 }
265 if let Some(name) = input.as_string() {
266 match name.as_str() {
267 "medium" => return Some(SheetDetent::Medium),
268 "large" => return Some(SheetDetent::Large),
269 _ => {}
270 }
271 } else if input.is_object() {
272 let number = |key| input.field(key).and_then(|v| v.as_number());
273 let detent = match number("height") {
274 Some(height) => SheetDetent::of_height(height),
275 None => number("fraction").and_then(SheetDetent::of_fraction),
276 };
277 if detent.is_some() {
278 return detent;
279 }
280 }
281 cx.warn(
282 r#"detent: expected "medium", "large", `{ height }` (0 or more) or `{ fraction }` (0 to 1)"#,
283 );
284 None
285 }
286
287 fn ts_type(types: &mut TsTypes) -> String {
288 <crate::SheetDetent as crate::element::JsValue>::ts_type(types)
289 }
290}
291
292impl HostValue for StatusBarSetting {
296 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
297 if !input.is_object() {
298 return None;
299 }
300 let flag = |key| input.field(key).and_then(|v| v.as_bool());
301 Some(StatusBarSetting {
302 style: input
303 .field("foreground")
304 .and_then(|v| v.as_string())
305 .and_then(|s| StatusBarStyle::from_name(&s)),
306 hidden: flag("hidden"),
307 animated: flag("animated"),
308 })
309 }
310
311 fn ts_type(_: &mut TsTypes) -> String {
312 "StatusBar".into()
313 }
314}
315
316impl HostValue for Viewability {
317 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
318 Some(Viewability {
319 view_area_coverage_threshold: number(input, "viewAreaCoverageThreshold")
320 .map(Percentage),
321 item_visible_threshold: number(input, "itemVisibleThreshold").map(Percentage),
322 })
323 }
324
325 fn ts_type(_: &mut TsTypes) -> String {
326 "ViewabilityConfig".into()
327 }
328}
329
330impl HostValue for PanActivation {
334 fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
335 if !input.is_object() {
336 return None;
337 }
338 let offset = |key| points(input, key).map(Points::abs);
339 Some(PanActivation {
340 active_offset_x: offset("activeOffsetX"),
341 active_offset_y: offset("activeOffsetY"),
342 fail_offset_x: offset("failOffsetX"),
343 fail_offset_y: offset("failOffsetY"),
344 direction: field(input, "direction", cx),
345 edge: field(input, "edge", cx),
346 })
347 }
348
349 fn ts_type(types: &mut TsTypes) -> String {
350 let direction = <crate::PanDirection as HostValue>::ts_type(types);
351 let edge = <crate::PanEdge as HostValue>::ts_type(types);
352 types.declare("PanActivation", |_| {
353 format!(
354 "/** When a view's pans activate (`panActivation`; react-native-gesture-handler's\n \
355 * `activeOffsetX` / `failOffsetY`), decided natively on the main thread as the\n \
356 * finger moves: past an active offset the view becomes the responder, its `pan`\n \
357 * starts and the scroll views around it can no longer take the touches; past a\n \
358 * fail offset first it never does, and they keep them. Distances in points along\n \
359 * one axis, either direction; without active offsets it activates after 10 points. */\n\
360 export interface PanActivation {{\n \
361 activeOffsetX?: number;\n activeOffsetY?: number;\n \
362 failOffsetX?: number;\n failOffsetY?: number;\n \
363 /** The one way it activates in: a drag the other way, or mostly across it, fails it. */\n \
364 direction?: {direction};\n \
365 /** Only a finger that goes down within 20 points of this edge of the screen (the\n \
366 * window on desktops, the page on the web) starts it, moving away from the edge. */\n \
367 edge?: {edge};\n}}"
368 )
369 })
370 }
371}
372
373impl HostValue for AccessibilityState {
377 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
378 let flag = |key| input.field(key).and_then(|v| v.as_bool()).unwrap_or(false);
379 let tristate = |key| {
380 let value = input.field(key);
381 match value.as_ref().and_then(|c| c.as_bool()) {
382 Some(true) => Some(Checked::True),
383 Some(false) => Some(Checked::False),
384 None => value
385 .and_then(|c| c.as_string())
386 .filter(|s| s == "mixed")
387 .map(|_| Checked::Mixed),
388 }
389 };
390 let current = input.field("current");
391 Some(AccessibilityState {
392 disabled: flag("disabled"),
393 selected: flag("selected"),
394 checked: tristate("checked"),
395 busy: flag("busy"),
396 expanded: input.field("expanded").and_then(|v| v.as_bool()),
397 pressed: tristate("pressed"),
398 has_popup: flag("hasPopup"),
399 invalid: flag("invalid"),
400 current: match current.as_ref().and_then(|c| c.as_bool()) {
402 Some(true) => Some(AccessibilityCurrent::True),
403 Some(false) => None,
404 None => match current.and_then(|c| c.as_string()).as_deref() {
405 Some("page") => Some(AccessibilityCurrent::Page),
406 Some("step") => Some(AccessibilityCurrent::Step),
407 Some("location") => Some(AccessibilityCurrent::Location),
408 Some("date") => Some(AccessibilityCurrent::Date),
409 Some("time") => Some(AccessibilityCurrent::Time),
410 Some("true") => Some(AccessibilityCurrent::True),
411 _ => None,
412 },
413 },
414 })
415 }
416
417 fn ts_type(types: &mut TsTypes) -> String {
418 types.declare("AccessibilityState", |_| {
419 "/** The state assistive technologies report (`accessibilityState`). */\n\
420 export interface AccessibilityState {\n disabled?: boolean;\n selected?: boolean;\n \
421 checked?: boolean | \"mixed\";\n busy?: boolean;\n expanded?: boolean;\n \
422 /** A toggle button that is on or off (ARIA's `aria-pressed`). */\n \
423 pressed?: boolean | \"mixed\";\n \
424 /** The current item of a set (ARIA's `aria-current`): a pagination's page, a wizard's step. */\n \
425 current?: boolean | \"page\" | \"step\" | \"location\" | \"date\" | \"time\";\n \
426 /** Opens a popup, a menu or a list (ARIA's `aria-haspopup`); `expanded` says whether it is open. */\n \
427 hasPopup?: boolean;\n \
428 /** The content does not pass the app's checks (ARIA's `aria-invalid`): a rejected field. */\n \
429 invalid?: boolean;\n}"
430 .into()
431 })
432 }
433}
434
435impl HostValue for AccessibilityValue {
437 fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
438 if !input.is_object() {
439 return None;
440 }
441 Some(AccessibilityValue {
442 min: number(input, "min"),
443 max: number(input, "max"),
444 now: number(input, "now"),
445 text: field(input, "text", cx),
446 })
447 }
448
449 fn ts_type(_: &mut TsTypes) -> String {
450 "{ min?: number; max?: number; now?: number; text?: string }".into()
451 }
452}
453
454impl HostValue for AccessibilityActionDef {
456 fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
457 Some(AccessibilityActionDef {
458 name: field(input, "name", cx)?,
459 label: field(input, "label", cx),
460 })
461 }
462
463 fn ts_type(_: &mut TsTypes) -> String {
464 "{ name: string; label?: string }".into()
465 }
466}
467
468const AUTO_COMPLETE: &[&str] = &[
471 "off",
472 "username",
473 "password",
474 "current-password",
475 "new-password",
476 "one-time-code",
477 "sms-otp",
478 "email",
479 "tel",
480 "name",
481 "given-name",
482 "family-name",
483 "additional-name",
484 "nickname",
485 "organization",
486 "street-address",
487 "address-line1",
488 "address-line2",
489 "address-level1",
490 "address-level2",
491 "postal-code",
492 "country",
493 "cc-number",
494 "cc-exp",
495 "cc-csc",
496 "cc-name",
497 "url",
498 "birthdate-full",
499];
500
501const TEXT_CONTENT_TYPE: &[&str] = &[
503 "none",
504 "username",
505 "password",
506 "newPassword",
507 "oneTimeCode",
508 "emailAddress",
509 "telephoneNumber",
510 "name",
511 "givenName",
512 "middleName",
513 "familyName",
514 "nickname",
515 "organizationName",
516 "fullStreetAddress",
517 "streetAddressLine1",
518 "streetAddressLine2",
519 "addressCity",
520 "addressState",
521 "postalCode",
522 "countryName",
523 "creditCardNumber",
524 "creditCardExpiration",
525 "creditCardSecurityCode",
526 "creditCardName",
527 "URL",
528 "birthdate",
529];
530
531impl HostValue for AutoFill {
534 fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
535 let name = input.as_string()?;
536 let fill = AutoFill::parse(&name);
537 if fill.is_none() {
538 cx.warn(format!(
539 "{name:?} is not a supported autoComplete / textContentType value"
540 ));
541 }
542 fill
543 }
544
545 fn ts_type(types: &mut TsTypes) -> String {
547 let union = |names: &[&str]| {
548 names
549 .iter()
550 .map(|n| format!("{n:?}"))
551 .collect::<Vec<_>>()
552 .join(" | ")
553 };
554 let web = types.declare("AutoComplete", |_| {
555 format!(
556 "/** What an input holds, for autofill (React Native's `autoComplete` values). */\n\
557 export type AutoComplete = {};",
558 union(AUTO_COMPLETE)
559 )
560 });
561 let ios = types.declare("TextContentType", |_| {
562 format!(
563 "/** iOS's names for `autoComplete` values. */\nexport type TextContentType = {};",
564 union(TEXT_CONTENT_TYPE)
565 )
566 });
567 format!("{web} | {ios}")
568 }
569}
570
571impl HostValue for Ripple {
573 fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
574 if !input.is_object() {
575 return None;
576 }
577 let flag = |key| input.field(key).and_then(|v| v.as_bool()).unwrap_or(false);
578 Some(Ripple {
579 color: field(input, "color", cx),
580 borderless: flag("borderless"),
581 radius: points(input, "radius"),
582 foreground: flag("foreground"),
583 })
584 }
585
586 fn ts_type(_: &mut TsTypes) -> String {
587 "{ color?: ColorValue; borderless?: boolean; radius?: number; foreground?: boolean }".into()
588 }
589}
590
591impl HostValue for HeaderItem {
595 fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
596 if !input.is_object() {
597 return None;
598 }
599 let system = field::<HeaderSystemItem, _>(input, "systemItem", cx);
600 let symbol = field::<std::sync::Arc<str>, _>(input, "symbol", cx);
601 let label_content = field::<std::sync::Arc<str>, _>(input, "label", cx);
602 let title = field::<std::sync::Arc<str>, _>(input, "title", cx);
603 let content = match (system, symbol, label_content.clone(), title) {
604 (Some(item), None, _, None) => HeaderItemContent::SystemItem(item),
605 (None, Some(name), _, None) => HeaderItemContent::Symbol(name),
606 (None, Some(symbol), _, Some(title)) => {
607 HeaderItemContent::SymbolTitle { symbol, title }
608 }
609 (None, None, Some(text), None) => HeaderItemContent::Label(text),
610 _ => {
611 cx.warn(
612 "header item needs exactly one of systemItem, symbol, or label \
613 (title only with symbol)",
614 );
615 return None;
616 }
617 };
618 let label = match &content {
621 HeaderItemContent::Label(_) => None,
622 _ => label_content,
623 };
624 let flag = |key| input.field(key).and_then(|v| v.as_bool()).unwrap_or(false);
625 let menu = input.field("menu").and_then(|v| {
626 v.as_list()?;
627 Some(
628 v.items()
629 .iter()
630 .filter_map(|item| decode_menu_item(item, cx))
631 .collect::<Vec<_>>(),
632 )
633 });
634 Some(HeaderItem {
635 key: field(input, "key", cx),
636 content,
637 label,
638 disabled: flag("disabled"),
639 press_id: 0,
640 menu,
641 shares_background: input
642 .field("sharesBackground")
643 .and_then(|v| v.as_bool())
644 .unwrap_or(true),
645 })
646 }
647
648 fn ts_type(types: &mut TsTypes) -> String {
649 let system = HeaderSystemItem::ts_type(types);
650 types.declare("HeaderItem", |_| {
651 format!(
652 "/** An iOS navigation-bar button (`ios.headerLeftItems`,\n\
653 * `ios.headerRightItems`). `title` shows after `symbol` in one\n\
654 * button (VoiceOver reads it unless `label` is set).\n\
655 * `menu` takes `nsh/desktop`'s `MenuItem` items (`onSelect` per\n\
656 * item; `destructive`, `inline`, `symbol` as documented there).\n\
657 * `onPress` runs when the button has no menu. `sharesBackground:\n\
658 * false` gives the button its own glass capsule on iOS 26+. */\n\
659 export type HeaderItem = {{\n key?: string;\n disabled?: boolean;\n \
660 sharesBackground?: boolean;\n \
661 onPress?: () => void;\n menu?: import(\"nsh/desktop\").MenuItem[];\n}} & (\n \
662 {{ systemItem: {system}; symbol?: never; title?: never; label?: string }} \
663 | {{ symbol: string; title?: string; systemItem?: never; label?: string }} \
664 | {{ label: string; systemItem?: never; symbol?: never; title?: never }}\n);"
665 )
666 })
667 }
668}
669
670fn decode_menu_item<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<crate::desktop::MenuItem> {
674 use crate::{
675 desktop::{MenuAction, MenuItem},
676 keymap::When,
677 };
678 if !input.is_object() {
679 return None;
680 }
681 if input.field("type").and_then(|v| v.as_string()).as_deref() == Some("separator") {
682 return Some(MenuItem::Separator);
683 }
684 let flag = |key| input.field(key).and_then(|v| v.as_bool());
685 let label = field::<String, _>(input, "label", cx).unwrap_or_default();
686 let enabled = !flag("disabled").unwrap_or(false);
687 let icon = field::<ImageSource, _>(input, "icon", cx);
688 let symbol = field::<String, _>(input, "symbol", cx);
689 if let Some(items_input) = input.field("submenu") {
690 let items = items_input
691 .items()
692 .iter()
693 .filter_map(|item| decode_menu_item(item, cx))
694 .collect();
695 return Some(MenuItem::Submenu {
696 label,
697 enabled,
698 items,
699 icon,
700 symbol,
701 inline: flag("inline").unwrap_or(false),
702 });
703 }
704 let role = field::<String, _>(input, "role", cx).and_then(|name| menu_role(&name));
705 if label.is_empty() && role.is_none() {
706 return None;
707 }
708 Some(MenuItem::Action(MenuAction {
709 id: 0,
710 label,
711 shortcut: None,
712 enabled,
713 checked: flag("checked"),
714 role,
715 when: When::Always,
716 icon,
717 symbol,
718 destructive: flag("destructive").unwrap_or(false),
719 }))
720}
721
722fn menu_role(name: &str) -> Option<crate::desktop::MenuRole> {
723 crate::desktop::MenuRole::from_name(name)
724}
725
726pub(crate) fn selection_menu<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Prop> {
732 if input.is_nullish() {
733 return Some(Prop::SelectionMenu(Vec::new()));
734 }
735 input.as_list()?;
736 Some(Prop::SelectionMenu(
737 input
738 .items()
739 .iter()
740 .filter_map(|item| decode_menu_item(item, cx))
741 .collect(),
742 ))
743}
744
745pub(crate) fn slot<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
747 Some(Prop::Slot(match input.as_string() {
748 Some(role) => match role.as_str() {
749 "header" => CellSlot::Header,
750 "footer" => CellSlot::Footer,
751 _ => CellSlot::Empty,
752 },
753 None => CellSlot::Item(input.as_number().unwrap_or(0.0) as u32),
754 }))
755}
756
757pub(crate) fn splice<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
759 let items = input.items();
760 let at = |i: usize| {
761 items
762 .get(i)
763 .and_then(|v| v.as_number())
764 .unwrap_or(0.0)
765 .max(0.0) as u32
766 };
767 Some(Prop::Splice(at(0), at(1), at(2)))
768}
769
770pub(crate) fn sticky<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
772 Some(Prop::StickyIndices(
773 input
774 .items()
775 .iter()
776 .filter_map(|v| v.as_number())
777 .filter(|v| *v >= 0.0)
778 .map(|v| v as u32)
779 .collect(),
780 ))
781}
782
783pub(crate) fn selection<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
786 let field = |key| input.field(key).and_then(|v| v.as_number());
787 let start = field("start")?.max(0.0) as u32;
788 Some(Prop::Selection(
789 start,
790 field("end").map_or(start, |e| e.max(0.0) as u32),
791 ))
792}
793
794pub(crate) fn pan<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
796 let axis = |key| input.field(key).and_then(|v| v.animated_node());
797 Some(Prop::PanValues(axis("x"), axis("y")))
798}
799
800pub(crate) fn pinch<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
802 Some(Prop::PinchValue(
803 input.field("scale").and_then(|v| v.animated_node()),
804 ))
805}
806
807pub(crate) fn overlay_anchor<I: HostInput>(input: &I, _: &mut HostCx) -> Option<OverlayProp> {
810 let bounds = || {
811 let origin = input.field("origin")?;
812 let extent = input.field("size")?;
813 Some(Bounds {
814 origin: point(points(&origin, "x")?, points(&origin, "y")?),
815 size: size(
816 points(&extent, "width")?.max(Points::ZERO),
817 points(&extent, "height")?.max(Points::ZERO),
818 ),
819 })
820 };
821 let anchor = match (input.node(), points(input, "x"), points(input, "y")) {
822 (Some(id), ..) => OverlayAnchor::Node(id),
823 (None, Some(x), Some(y)) => OverlayAnchor::Point(point(x, y)),
824 _ => bounds().map_or(OverlayAnchor::None, OverlayAnchor::Bounds),
825 };
826 Some(OverlayProp::Anchor(anchor))
827}
828
829pub(crate) fn active_descendant<I: HostInput>(
831 input: &I,
832 _: &mut HostCx,
833) -> Option<AccessibilityProp> {
834 Some(AccessibilityProp::ActiveDescendant(
835 input.node().map(ElementTarget::of_node),
836 ))
837}
838
839pub(crate) fn accessibility_controls<I: HostInput>(
841 input: &I,
842 _: &mut HostCx,
843) -> Option<AccessibilityProp> {
844 Some(AccessibilityProp::Controls(
845 input.node().map(ElementTarget::of_node),
846 ))
847}
848
849pub(crate) fn accessibility_described_by<I: HostInput>(
851 input: &I,
852 _: &mut HostCx,
853) -> Option<AccessibilityProp> {
854 Some(AccessibilityProp::DescribedBy(
855 input.node().map(ElementTarget::of_node),
856 ))
857}
858
859pub(crate) fn tooltip<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
861 let content = input
862 .node()
863 .map_or(TooltipContent::None, TooltipContent::Node);
864 Some(Prop::Tooltip(content))
865}
866
867pub(crate) fn rotation<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
869 Some(Prop::RotationValue(
870 input.field("angle").and_then(|v| v.animated_node()),
871 ))
872}
873
874pub(crate) fn scroll_value<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
876 Some(Prop::ScrollValue(input.animated_node()))
877}
878
879pub(crate) fn pull_value<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
881 Some(Prop::PullValue(input.animated_node()))
882}
883
884pub(crate) fn sticky_offset<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
886 match input.as_number() {
887 Some(n) => Some(Prop::StickyOffset(Points(n as f32))),
888 None => input
889 .animated_node()
890 .map(|node| Prop::StickyOffsetNode(Some(node))),
891 }
892}
893
894pub(crate) fn hit_slop<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Prop> {
896 Some(Prop::HitSlop(match input.as_number() {
897 Some(n) => EdgeInsets::all(Points(n as f32)),
898 None => EdgeInsets::decode(input, cx).unwrap_or_default(),
899 }))
900}
901
902pub(crate) fn class_list<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
904 Some(Prop::ClassList(
905 input
906 .entries()
907 .into_iter()
908 .filter(|(_, on)| on.truthy())
909 .map(|(name, _)| name.into())
910 .collect(),
911 ))
912}
913
914pub(crate) fn tailwind_theme<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
916 Some(Prop::TailwindTheme(input.as_string()?.into()))
917}
918
919pub(crate) fn snap_to_window_margin<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
921 let n = input.as_number()?;
922 (n.is_finite() && n >= 0.0).then(|| Prop::SnapToWindowMargin(Points(n as f32)))
923}
924
925pub(crate) fn ui_theme<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
927 Some(Prop::UiTheme(input.as_string()?.into()))
928}
929
930pub(crate) fn role<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<AccessibilityProp> {
933 let role = AccessibilityRole::decode(input, cx);
934 if role.is_none()
935 && let Some(name) = input.as_string().filter(|n| !n.is_empty())
936 {
937 cx.warn(format!("unknown role `{name}`"));
938 }
939 Some(AccessibilityProp::Role(role.unwrap_or_default()))
940}
941
942pub(crate) fn accessibility_level<I: HostInput>(
944 input: &I,
945 _: &mut HostCx,
946) -> Option<AccessibilityProp> {
947 let level = input
948 .as_number()
949 .filter(|n| *n >= 1.0 && n.fract() == 0.0 && *n <= f64::from(u32::MAX))
950 .map(|n| n as u32);
951 Some(AccessibilityProp::Level(level))
952}
953
954pub(crate) fn important<I: HostInput>(input: &I, _: &mut HostCx) -> Option<AccessibilityProp> {
956 Some(match input.as_string().as_deref() {
957 Some("yes") => AccessibilityProp::Important(Some(true), false),
958 Some("no") => AccessibilityProp::Important(Some(false), false),
959 Some("no-hide-descendants") => AccessibilityProp::Important(Some(false), true),
960 _ => AccessibilityProp::Important(None, false),
961 })
962}
963
964pub(crate) fn deceleration<I: HostInput>(input: &I, _: &mut HostCx) -> Option<ScrollProp> {
967 Some(ScrollProp::Deceleration(match input.as_string() {
968 Some(s) => match s.as_str() {
969 "fast" => 0.99,
970 "normal" => 0.998,
971 _ => 0.0,
972 },
973 None => input.as_number().unwrap_or(0.0) as f32,
974 }))
975}
976
977pub(crate) fn visible_content<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
979 Some(Prop::FollowEnd(
980 points(input, "autoscrollToBottomThreshold").map(|t| t.max(Points::ZERO)),
981 input
982 .field("animated")
983 .and_then(|a| a.as_bool())
984 .unwrap_or(false),
985 ))
986}
987
988pub(crate) fn refresh_indicator<I: HostInput>(input: &I, _: &mut HostCx) -> Option<ScrollProp> {
990 Some(ScrollProp::RefreshIndicator(
991 points(input, "height").map(|h| h.max(Points::ZERO)),
992 ))
993}
994
995pub(crate) fn content_offset<I: HostInput>(input: &I, _: &mut HostCx) -> Option<ScrollProp> {
997 let n = |key| points(input, key).unwrap_or_default();
998 Some(ScrollProp::ContentOffset(point(n("x"), n("y"))))
999}
1000
1001pub(crate) fn scrollbar<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
1004 Some(Prop::Scrollbar(match input.as_bool() {
1005 Some(shows) => shows.into(),
1006 None if input.is_object() => {
1007 crate::ScrollbarSetting::Themed(std::sync::Arc::new(json_of(input, 0, &mut {
1008 JSON_ENTRIES
1009 })))
1010 }
1011 None => crate::ScrollbarSetting::Shown,
1012 }))
1013}
1014
1015const JSON_DEPTH: u32 = 64;
1017const JSON_ENTRIES: usize = 1 << 20;
1019
1020fn json_of<I: HostInput>(input: &I, depth: u32, left: &mut usize) -> crate::JsonValue {
1027 use crate::JsonValue;
1028 if let Some(b) = input.as_bool() {
1029 return JsonValue::Bool(b);
1030 }
1031 if let Some(n) = input.as_number() {
1032 return serde_json::Number::from_f64(n).map_or(JsonValue::Null, JsonValue::Number);
1033 }
1034 if let Some(s) = input.as_string() {
1035 return JsonValue::String(s);
1036 }
1037 if depth >= JSON_DEPTH {
1038 return JsonValue::Null;
1039 }
1040 if let Some(list) = input.as_list() {
1041 let mut items = Vec::new();
1042 for i in 0..list.len() {
1043 if *left == 0 {
1044 break;
1045 }
1046 *left -= 1;
1047 if let Some(item) = list.item(i) {
1048 items.push(json_of(&item, depth + 1, left));
1049 }
1050 }
1051 return JsonValue::Array(items);
1052 }
1053 if input.is_object() {
1054 let mut fields = serde_json::Map::new();
1055 for (key, value) in input.entries() {
1056 if *left == 0 {
1057 break;
1058 }
1059 *left -= 1;
1060 fields.insert(key, json_of(&value, depth + 1, left));
1061 }
1062 return JsonValue::Object(fields);
1063 }
1064 JsonValue::Null
1065}
1066
1067pub(crate) fn keyboard_taps<I: HostInput>(input: &I, _: &mut HostCx) -> Option<ScrollProp> {
1070 Some(ScrollProp::KeyboardTaps(match input.as_bool() {
1071 Some(true) => KeyboardTaps::Always,
1072 Some(false) => KeyboardTaps::Never,
1073 None => match input.as_string().as_deref() {
1074 Some("always") => KeyboardTaps::Always,
1075 Some("handled") => KeyboardTaps::Handled,
1076 _ => KeyboardTaps::Never,
1077 },
1078 }))
1079}
1080
1081pub(crate) fn orientations<I: HostInput>(input: &I, _: &mut HostCx) -> Option<ModalProp> {
1083 Some(ModalProp::Orientations(orientation_bits(input)))
1084}
1085
1086pub(crate) fn page_orientations<I: HostInput>(input: &I, _: &mut HostCx) -> Option<ScreenProp> {
1088 Some(ScreenProp::Orientations(orientation_bits(input)))
1089}
1090
1091fn orientation_bits<I: HostInput>(input: &I) -> u8 {
1094 let mut bits = 0;
1095 for name in input.items() {
1096 bits |= match name.as_string().as_deref() {
1097 Some("portrait") => ModalConfig::PORTRAIT,
1098 Some("portrait-upside-down") => ModalConfig::PORTRAIT_UPSIDE_DOWN,
1099 Some("landscape") => ModalConfig::LANDSCAPE_LEFT | ModalConfig::LANDSCAPE_RIGHT,
1100 Some("landscape-left") => ModalConfig::LANDSCAPE_LEFT,
1101 Some("landscape-right") => ModalConfig::LANDSCAPE_RIGHT,
1102 _ => 0,
1103 };
1104 }
1105 bits
1106}
1107
1108impl HostValue for crate::shader::ShaderUniforms {
1112 fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
1113 if !input.is_object() {
1114 return None;
1115 }
1116 let mut values = Vec::new();
1117 for (name, value) in input.entries() {
1118 match uniform_value(&value, 0) {
1119 Some(v) => values.push((name.as_str().into(), v)),
1120 None => cx.warn(format!(
1121 "uniform `{name}`: a number, a color, an animated value or a list of them"
1122 )),
1123 }
1124 }
1125 Some(crate::shader::ShaderUniforms(values))
1126 }
1127
1128 fn ts_type(types: &mut TsTypes) -> String {
1129 let value = types.declare("ShaderUniform", |_| {
1130 "/** A value of a shader's uniform: a number (`f32`, `i32`, `u32`), a color\n \
1131 * (`vec3f` / `vec4f`, sRGB 0..1), an animated value, or a list of them (a\n \
1132 * vector's components, an `array<vec4f, N>`'s items). */\n\
1133 export type ShaderUniform = number | ColorValue | AnimatedNode | readonly ShaderUniform[];"
1134 .into()
1135 });
1136 format!("Record<string, {value}>")
1137 }
1138}
1139
1140impl HostValue for crate::shader::NavShaderSpec {
1143 fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
1144 if !input.is_object() {
1145 return None;
1146 }
1147 let mut source = None;
1148 let mut uniforms = crate::shader::ShaderUniforms::default();
1149 let mut duration = None;
1150 for (name, value) in input.entries() {
1151 match name.as_str() {
1152 "source" => source = value.as_string(),
1153 "uniforms" => {
1154 uniforms = crate::shader::ShaderUniforms::decode(&value, cx).unwrap_or_default()
1155 }
1156 "duration" => duration = value.as_number().map(|d| d as f32),
1157 _ => {}
1158 }
1159 }
1160 Some(crate::shader::NavShaderSpec {
1161 source: source?.as_str().into(),
1162 uniforms,
1163 duration,
1164 })
1165 }
1166
1167 fn ts_type(types: &mut TsTypes) -> String {
1168 let uniforms = crate::shader::ShaderUniforms::ts_type(types);
1169 format!("{{ source: string; uniforms?: {uniforms}; duration?: number }}")
1170 }
1171}
1172
1173impl HostValue for crate::shader::ShaderProgress {
1175 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
1176 if let Some(n) = input.as_number() {
1177 return Some(crate::shader::ShaderProgress::Number(
1178 crate::geometry::Percentage(n as f32),
1179 ));
1180 }
1181 input
1182 .animated_node()
1183 .map(crate::shader::ShaderProgress::Animated)
1184 }
1185
1186 fn ts_type(_: &mut TsTypes) -> String {
1187 "number | AnimatedNode".into()
1188 }
1189}
1190
1191impl HostValue for crate::shader::TransitionKey {
1193 fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
1194 if let Some(b) = input.as_bool() {
1195 return Some(crate::shader::TransitionKey::Bool(b));
1196 }
1197 if let Some(n) = input.as_number() {
1198 return Some(crate::shader::TransitionKey::number(n));
1199 }
1200 input
1201 .as_string()
1202 .map(|s| crate::shader::TransitionKey::String(s.as_str().into()))
1203 }
1204
1205 fn ts_type(_: &mut TsTypes) -> String {
1206 "string | number | boolean".into()
1207 }
1208}
1209
1210fn uniform_value<I: HostInput>(input: &I, depth: u32) -> Option<crate::shader::UniformValue> {
1211 use crate::shader::UniformValue;
1212 if let Some(n) = input.as_number() {
1213 return Some(UniformValue::Number(n as f32));
1214 }
1215 if let Some(s) = input.as_string() {
1216 return crate::Color::parse(&s).map(UniformValue::Color);
1217 }
1218 if let Some(node) = input.animated_node() {
1219 return Some(UniformValue::Animated(node));
1220 }
1221 let list = input.as_list()?;
1222 if depth > 1 {
1224 return None;
1225 }
1226 (0..list.len())
1227 .map(|i| {
1228 list.item(i)
1229 .and_then(|item| uniform_value(&item, depth + 1))
1230 })
1231 .collect::<Option<Vec<_>>>()
1232 .map(UniformValue::List)
1233}