use super::host::{HostCx, HostInput, HostList, HostValue, field};
use crate::{
AccessibilityCurrent, AccessibilityProp, AccessibilityRole, AccessibilityState, AutoFill,
CellSlot, EdgeInsets, HeaderItem, HeaderItemContent, HeaderSystemItem, ImageScales,
ImageSource, KeyboardTaps, ListContentStyle, MacOsBackdrop, MacOsBackdropBlending,
MacOsBackdropMaterial, MacOsBackdropState, ModalProp, Prop, RevealOptions, ScreenProp,
ScrollAlignment, ScrollProp, StatusBarSetting, StatusBarStyle, Viewability, WindowsBackdrop,
WindowsBackdropMaterial,
element::{ElementTarget, TsTypes},
geometry::{Bounds, Percentage, Points, point, size},
mount::ModalConfig,
ops::OverlayProp,
overlay::{OverlayAnchor, TooltipContent},
props::{AccessibilityActionDef, AccessibilityValue, Checked, PanActivation, Ripple},
};
impl HostValue for crate::KeyCapture {
fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
let apple = crate::element::try_apple_keys().unwrap_or(false);
super::host::decode_capture_keys(input, cx, apple)
}
fn ts_type(_: &mut TsTypes) -> String {
"\"none\" | \"all\" | readonly string[]".into()
}
}
fn number<I: HostInput>(input: &I, key: &str) -> Option<f32> {
input
.field(key)
.and_then(|v| v.as_number())
.map(|n| n as f32)
}
fn points<I: HostInput>(input: &I, key: &str) -> Option<Points> {
number(input, key).map(Points)
}
fn scales<I: HostInput>(input: &I) -> ImageScales {
let Some(list) = input.field("scales").and_then(|s| s.as_list()) else {
return ImageScales::NONE;
};
(0..list.len().min(crate::ops::SCALES_READ))
.filter_map(|i| list.item(i)?.as_number())
.map(|n| n as f32)
.collect()
}
impl HostValue for ImageSource {
fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
if let Some(url) = input.as_string() {
return (!url.is_empty()).then(|| ImageSource {
uri: url.into(),
size: None,
scales: ImageScales::NONE,
data: None,
});
}
let url = input.field("url")?.as_string()?;
let extent = input.field("size");
let size = match extent
.as_ref()
.map(|e| (number(e, "width"), number(e, "height")))
{
Some((Some(w), Some(h))) => Some(size(Points(w), Points(h))),
_ => None,
};
Some(ImageSource {
uri: url.into(),
size,
scales: scales(input),
data: None,
})
}
fn ts_type(_: &mut TsTypes) -> String {
"string | ImageAsset".into()
}
}
impl HostValue for RevealOptions {
fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
let mut options = RevealOptions::default();
if input.is_nullish() {
return Some(options);
}
if !input.is_object() {
return None;
}
let mut alignment = |key: &str, default: ScrollAlignment| match input.field(key) {
Some(value) if !value.is_nullish() => {
<ScrollAlignment as HostValue>::decode(&value, cx)
}
_ => Some(default),
};
options.vertical = alignment("vertical", options.vertical)?;
options.horizontal = alignment("horizontal", options.horizontal)?;
if let Some(animated) = input.field("animated").and_then(|a| a.as_bool()) {
options.animated = animated;
}
Some(options)
}
fn ts_type(types: &mut TsTypes) -> String {
let alignment = <ScrollAlignment as HostValue>::ts_type(types);
types.declare("RevealOptions", |_| {
format!(
"/** How `reveal` places a view in the scroll views around it. */\n\
export interface RevealOptions {{\n \
/** Along vertical scroll views; `\"start\"` by default. */\n \
vertical?: {alignment};\n \
/** Along horizontal scroll views; `\"nearest\"` by default. */\n \
horizontal?: {alignment};\n \
/** Animate the scrolls; `true` by default. */\n \
animated?: boolean;\n}}"
)
})
}
}
impl HostValue for ListContentStyle {
fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
let n = |key| points(input, key);
let all = n("padding").unwrap_or_default();
let inline = n("paddingHorizontal").unwrap_or(all);
let block = n("paddingVertical").unwrap_or(all);
let gap = n("gap").unwrap_or_default();
Some(ListContentStyle {
padding: EdgeInsets {
top: n("paddingTop").unwrap_or(block),
right: n("paddingRight").unwrap_or(inline),
bottom: n("paddingBottom").unwrap_or(block),
left: n("paddingLeft").unwrap_or(inline),
},
row_gap: n("rowGap").unwrap_or(gap),
column_gap: n("columnGap").unwrap_or(gap),
})
}
fn ts_type(types: &mut TsTypes) -> String {
types.declare("ListContentStyle", |_| {
"/** Padding and gaps of a list's content (`contentStyle`). */\n\
export interface ListContentStyle {\n padding?: number;\n paddingHorizontal?: number;\n \
paddingVertical?: number;\n paddingTop?: number;\n paddingRight?: number;\n \
paddingBottom?: number;\n paddingLeft?: number;\n gap?: number;\n rowGap?: number;\n \
columnGap?: number;\n}"
.into()
})
}
}
impl HostValue for MacOsBackdrop {
fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
if !input.is_object() {
return None;
}
Some(MacOsBackdrop {
material: field::<MacOsBackdropMaterial, _>(input, "material", cx).unwrap_or_default(),
blending: field::<MacOsBackdropBlending, _>(input, "blending", cx).unwrap_or_default(),
state: field::<MacOsBackdropState, _>(input, "state", cx).unwrap_or_default(),
})
}
fn ts_type(types: &mut TsTypes) -> String {
let material = <MacOsBackdropMaterial as HostValue>::ts_type(types);
let blending = <MacOsBackdropBlending as HostValue>::ts_type(types);
let state = <MacOsBackdropState as HostValue>::ts_type(types);
types.declare("MacOsBackdrop", |_| {
format!(
"/** The material a view draws with on macOS (`macos={{{{ backdrop }}}}`). */\n\
export interface MacOsBackdrop {{\n material?: {material};\n \
blending?: {blending};\n state?: {state};\n}}"
)
})
}
}
impl HostValue for WindowsBackdrop {
fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
if !input.is_object() {
return None;
}
Some(Self {
material: field(input, "material", cx)?,
})
}
fn ts_type(types: &mut TsTypes) -> String {
let material = <WindowsBackdropMaterial as HostValue>::ts_type(types);
types.declare("WindowsBackdrop", |_| {
format!(
"/** The material a view draws with on Windows (`windows={{{{ backdrop }}}}`). */\n\
export interface WindowsBackdrop {{\n material: {material};\n}}"
)
})
}
}
impl HostValue for crate::SheetDetent {
fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
use crate::SheetDetent;
if input.is_nullish() {
return None;
}
if let Some(name) = input.as_string() {
match name.as_str() {
"medium" => return Some(SheetDetent::Medium),
"large" => return Some(SheetDetent::Large),
_ => {}
}
} else if input.is_object() {
let number = |key| input.field(key).and_then(|v| v.as_number());
let detent = match number("height") {
Some(height) => SheetDetent::of_height(height),
None => number("fraction").and_then(SheetDetent::of_fraction),
};
if detent.is_some() {
return detent;
}
}
cx.warn(
r#"detent: expected "medium", "large", `{ height }` (0 or more) or `{ fraction }` (0 to 1)"#,
);
None
}
fn ts_type(types: &mut TsTypes) -> String {
<crate::SheetDetent as crate::element::JsValue>::ts_type(types)
}
}
impl HostValue for StatusBarSetting {
fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
if !input.is_object() {
return None;
}
let flag = |key| input.field(key).and_then(|v| v.as_bool());
Some(StatusBarSetting {
style: input
.field("foreground")
.and_then(|v| v.as_string())
.and_then(|s| StatusBarStyle::from_name(&s)),
hidden: flag("hidden"),
animated: flag("animated"),
})
}
fn ts_type(_: &mut TsTypes) -> String {
"StatusBar".into()
}
}
impl HostValue for Viewability {
fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
Some(Viewability {
view_area_coverage_threshold: number(input, "viewAreaCoverageThreshold")
.map(Percentage),
item_visible_threshold: number(input, "itemVisibleThreshold").map(Percentage),
})
}
fn ts_type(_: &mut TsTypes) -> String {
"ViewabilityConfig".into()
}
}
impl HostValue for PanActivation {
fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
if !input.is_object() {
return None;
}
let offset = |key| points(input, key).map(Points::abs);
Some(PanActivation {
active_offset_x: offset("activeOffsetX"),
active_offset_y: offset("activeOffsetY"),
fail_offset_x: offset("failOffsetX"),
fail_offset_y: offset("failOffsetY"),
})
}
fn ts_type(_: &mut TsTypes) -> String {
"PanActivation".into()
}
}
impl HostValue for AccessibilityState {
fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
let flag = |key| input.field(key).and_then(|v| v.as_bool()).unwrap_or(false);
let tristate = |key| {
let value = input.field(key);
match value.as_ref().and_then(|c| c.as_bool()) {
Some(true) => Some(Checked::True),
Some(false) => Some(Checked::False),
None => value
.and_then(|c| c.as_string())
.filter(|s| s == "mixed")
.map(|_| Checked::Mixed),
}
};
let current = input.field("current");
Some(AccessibilityState {
disabled: flag("disabled"),
selected: flag("selected"),
checked: tristate("checked"),
busy: flag("busy"),
expanded: input.field("expanded").and_then(|v| v.as_bool()),
pressed: tristate("pressed"),
has_popup: flag("hasPopup"),
invalid: flag("invalid"),
current: match current.as_ref().and_then(|c| c.as_bool()) {
Some(true) => Some(AccessibilityCurrent::True),
Some(false) => None,
None => match current.and_then(|c| c.as_string()).as_deref() {
Some("page") => Some(AccessibilityCurrent::Page),
Some("step") => Some(AccessibilityCurrent::Step),
Some("location") => Some(AccessibilityCurrent::Location),
Some("date") => Some(AccessibilityCurrent::Date),
Some("time") => Some(AccessibilityCurrent::Time),
Some("true") => Some(AccessibilityCurrent::True),
_ => None,
},
},
})
}
fn ts_type(types: &mut TsTypes) -> String {
types.declare("AccessibilityState", |_| {
"/** The state assistive technologies report (`accessibilityState`). */\n\
export interface AccessibilityState {\n disabled?: boolean;\n selected?: boolean;\n \
checked?: boolean | \"mixed\";\n busy?: boolean;\n expanded?: boolean;\n \
/** A toggle button that is on or off (ARIA's `aria-pressed`). */\n \
pressed?: boolean | \"mixed\";\n \
/** The current item of a set (ARIA's `aria-current`): a pagination's page, a wizard's step. */\n \
current?: boolean | \"page\" | \"step\" | \"location\" | \"date\" | \"time\";\n \
/** Opens a popup, a menu or a list (ARIA's `aria-haspopup`); `expanded` says whether it is open. */\n \
hasPopup?: boolean;\n \
/** The content does not pass the app's checks (ARIA's `aria-invalid`): a rejected field. */\n \
invalid?: boolean;\n}"
.into()
})
}
}
impl HostValue for AccessibilityValue {
fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
if !input.is_object() {
return None;
}
Some(AccessibilityValue {
min: number(input, "min"),
max: number(input, "max"),
now: number(input, "now"),
text: field(input, "text", cx),
})
}
fn ts_type(_: &mut TsTypes) -> String {
"{ min?: number; max?: number; now?: number; text?: string }".into()
}
}
impl HostValue for AccessibilityActionDef {
fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
Some(AccessibilityActionDef {
name: field(input, "name", cx)?,
label: field(input, "label", cx),
})
}
fn ts_type(_: &mut TsTypes) -> String {
"{ name: string; label?: string }".into()
}
}
const AUTO_COMPLETE: &[&str] = &[
"off",
"username",
"password",
"current-password",
"new-password",
"one-time-code",
"sms-otp",
"email",
"tel",
"name",
"given-name",
"family-name",
"additional-name",
"nickname",
"organization",
"street-address",
"address-line1",
"address-line2",
"address-level1",
"address-level2",
"postal-code",
"country",
"cc-number",
"cc-exp",
"cc-csc",
"cc-name",
"url",
"birthdate-full",
];
const TEXT_CONTENT_TYPE: &[&str] = &[
"none",
"username",
"password",
"newPassword",
"oneTimeCode",
"emailAddress",
"telephoneNumber",
"name",
"givenName",
"middleName",
"familyName",
"nickname",
"organizationName",
"fullStreetAddress",
"streetAddressLine1",
"streetAddressLine2",
"addressCity",
"addressState",
"postalCode",
"countryName",
"creditCardNumber",
"creditCardExpiration",
"creditCardSecurityCode",
"creditCardName",
"URL",
"birthdate",
];
impl HostValue for AutoFill {
fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
let name = input.as_string()?;
let fill = AutoFill::parse(&name);
if fill.is_none() {
cx.warn(format!(
"{name:?} is not a supported autoComplete / textContentType value"
));
}
fill
}
fn ts_type(types: &mut TsTypes) -> String {
let union = |names: &[&str]| {
names
.iter()
.map(|n| format!("{n:?}"))
.collect::<Vec<_>>()
.join(" | ")
};
let web = types.declare("AutoComplete", |_| {
format!(
"/** What an input holds, for autofill (React Native's `autoComplete` values). */\n\
export type AutoComplete = {};",
union(AUTO_COMPLETE)
)
});
let ios = types.declare("TextContentType", |_| {
format!(
"/** iOS's names for `autoComplete` values. */\nexport type TextContentType = {};",
union(TEXT_CONTENT_TYPE)
)
});
format!("{web} | {ios}")
}
}
impl HostValue for Ripple {
fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
if !input.is_object() {
return None;
}
let flag = |key| input.field(key).and_then(|v| v.as_bool()).unwrap_or(false);
Some(Ripple {
color: field(input, "color", cx),
borderless: flag("borderless"),
radius: points(input, "radius"),
foreground: flag("foreground"),
})
}
fn ts_type(_: &mut TsTypes) -> String {
"{ color?: ColorValue; borderless?: boolean; radius?: number; foreground?: boolean }".into()
}
}
impl HostValue for HeaderItem {
fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
if !input.is_object() {
return None;
}
let system = field::<HeaderSystemItem, _>(input, "systemItem", cx);
let symbol = field::<std::sync::Arc<str>, _>(input, "symbol", cx);
let label_content = field::<std::sync::Arc<str>, _>(input, "label", cx);
let content = match (system, symbol, label_content.clone()) {
(Some(item), None, _) => HeaderItemContent::SystemItem(item),
(None, Some(name), _) => HeaderItemContent::Symbol(name),
(None, None, Some(text)) => HeaderItemContent::Label(text),
_ => {
cx.warn("headerRightItems entry needs exactly one of systemItem, symbol, or label");
return None;
}
};
let label = match &content {
HeaderItemContent::Label(_) => None,
_ => label_content,
};
let flag = |key| input.field(key).and_then(|v| v.as_bool()).unwrap_or(false);
let menu = input.field("menu").and_then(|v| {
v.as_list()?;
Some(
v.items()
.iter()
.filter_map(|item| decode_menu_item(item, cx))
.collect::<Vec<_>>(),
)
});
Some(HeaderItem {
key: field(input, "key", cx),
content,
label,
disabled: flag("disabled"),
press_id: 0,
menu,
})
}
fn ts_type(types: &mut TsTypes) -> String {
let system = HeaderSystemItem::ts_type(types);
types.declare("HeaderItem", |_| {
format!(
"/** A trailing iOS navigation-bar button (`ios.headerRightItems`).\n\
* `menu` takes `nsh/desktop`'s `MenuItem` items (`onSelect` per\n\
* item; `destructive`, `inline`, `symbol` as documented there).\n\
* `onPress` runs when the button has no menu. */\n\
export type HeaderItem = {{\n key?: string;\n disabled?: boolean;\n \
onPress?: () => void;\n menu?: import(\"nsh/desktop\").MenuItem[];\n}} & (\n \
{{ systemItem: {system}; symbol?: never; label?: string }} \
| {{ symbol: string; systemItem?: never; label?: string }} \
| {{ label: string; systemItem?: never; symbol?: never }}\n);"
)
})
}
}
fn decode_menu_item<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<crate::desktop::MenuItem> {
use crate::{
desktop::{MenuAction, MenuItem},
keymap::When,
};
if !input.is_object() {
return None;
}
if input.field("type").and_then(|v| v.as_string()).as_deref() == Some("separator") {
return Some(MenuItem::Separator);
}
let flag = |key| input.field(key).and_then(|v| v.as_bool());
let label = field::<String, _>(input, "label", cx).unwrap_or_default();
let enabled = !flag("disabled").unwrap_or(false);
let icon = field::<ImageSource, _>(input, "icon", cx);
let symbol = field::<String, _>(input, "symbol", cx);
if let Some(items_input) = input.field("submenu") {
let items = items_input
.items()
.iter()
.filter_map(|item| decode_menu_item(item, cx))
.collect();
return Some(MenuItem::Submenu {
label,
enabled,
items,
icon,
symbol,
inline: flag("inline").unwrap_or(false),
});
}
let role = field::<String, _>(input, "role", cx).and_then(|name| menu_role(&name));
if label.is_empty() && role.is_none() {
return None;
}
Some(MenuItem::Action(MenuAction {
id: 0,
label,
shortcut: None,
enabled,
checked: flag("checked"),
role,
when: When::Always,
icon,
symbol,
destructive: flag("destructive").unwrap_or(false),
}))
}
fn menu_role(name: &str) -> Option<crate::desktop::MenuRole> {
use crate::desktop::MenuRole;
Some(match name {
"about" => MenuRole::About,
"hide" => MenuRole::Hide,
"hideOthers" => MenuRole::HideOthers,
"showAll" => MenuRole::ShowAll,
"quit" => MenuRole::Quit,
"undo" => MenuRole::Undo,
"redo" => MenuRole::Redo,
"cut" => MenuRole::Cut,
"copy" => MenuRole::Copy,
"paste" => MenuRole::Paste,
"selectAll" => MenuRole::SelectAll,
"minimize" => MenuRole::Minimize,
"zoom" => MenuRole::Zoom,
"toggleFullScreen" => MenuRole::ToggleFullScreen,
"close" => MenuRole::Close,
_ => return None,
})
}
pub(crate) fn selection_menu<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Prop> {
if input.is_nullish() {
return Some(Prop::SelectionMenu(Vec::new()));
}
input.as_list()?;
Some(Prop::SelectionMenu(
input
.items()
.iter()
.filter_map(|item| decode_menu_item(item, cx))
.collect(),
))
}
pub(crate) fn slot<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
Some(Prop::Slot(match input.as_string() {
Some(role) => match role.as_str() {
"header" => CellSlot::Header,
"footer" => CellSlot::Footer,
_ => CellSlot::Empty,
},
None => CellSlot::Item(input.as_number().unwrap_or(0.0) as u32),
}))
}
pub(crate) fn splice<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
let items = input.items();
let at = |i: usize| {
items
.get(i)
.and_then(|v| v.as_number())
.unwrap_or(0.0)
.max(0.0) as u32
};
Some(Prop::Splice(at(0), at(1), at(2)))
}
pub(crate) fn sticky<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
Some(Prop::StickyIndices(
input
.items()
.iter()
.filter_map(|v| v.as_number())
.filter(|v| *v >= 0.0)
.map(|v| v as u32)
.collect(),
))
}
pub(crate) fn selection<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
let field = |key| input.field(key).and_then(|v| v.as_number());
let start = field("start")?.max(0.0) as u32;
Some(Prop::Selection(
start,
field("end").map_or(start, |e| e.max(0.0) as u32),
))
}
pub(crate) fn pan<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
let axis = |key| input.field(key).and_then(|v| v.animated_node());
Some(Prop::PanValues(axis("x"), axis("y")))
}
pub(crate) fn pinch<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
Some(Prop::PinchValue(
input.field("scale").and_then(|v| v.animated_node()),
))
}
pub(crate) fn overlay_anchor<I: HostInput>(input: &I, _: &mut HostCx) -> Option<OverlayProp> {
let bounds = || {
let origin = input.field("origin")?;
let extent = input.field("size")?;
Some(Bounds {
origin: point(points(&origin, "x")?, points(&origin, "y")?),
size: size(
points(&extent, "width")?.max(Points::ZERO),
points(&extent, "height")?.max(Points::ZERO),
),
})
};
let anchor = match (input.node(), points(input, "x"), points(input, "y")) {
(Some(id), ..) => OverlayAnchor::Node(id),
(None, Some(x), Some(y)) => OverlayAnchor::Point(point(x, y)),
_ => bounds().map_or(OverlayAnchor::None, OverlayAnchor::Bounds),
};
Some(OverlayProp::Anchor(anchor))
}
pub(crate) fn active_descendant<I: HostInput>(
input: &I,
_: &mut HostCx,
) -> Option<AccessibilityProp> {
Some(AccessibilityProp::ActiveDescendant(
input.node().map(ElementTarget::of_node),
))
}
pub(crate) fn accessibility_controls<I: HostInput>(
input: &I,
_: &mut HostCx,
) -> Option<AccessibilityProp> {
Some(AccessibilityProp::Controls(
input.node().map(ElementTarget::of_node),
))
}
pub(crate) fn accessibility_described_by<I: HostInput>(
input: &I,
_: &mut HostCx,
) -> Option<AccessibilityProp> {
Some(AccessibilityProp::DescribedBy(
input.node().map(ElementTarget::of_node),
))
}
pub(crate) fn tooltip<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
let content = input
.node()
.map_or(TooltipContent::None, TooltipContent::Node);
Some(Prop::Tooltip(content))
}
pub(crate) fn rotation<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
Some(Prop::RotationValue(
input.field("angle").and_then(|v| v.animated_node()),
))
}
pub(crate) fn scroll_value<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
Some(Prop::ScrollValue(input.animated_node()))
}
pub(crate) fn pull_value<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
Some(Prop::PullValue(input.animated_node()))
}
pub(crate) fn sticky_offset<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
match input.as_number() {
Some(n) => Some(Prop::StickyOffset(Points(n as f32))),
None => input
.animated_node()
.map(|node| Prop::StickyOffsetNode(Some(node))),
}
}
pub(crate) fn hit_slop<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Prop> {
Some(Prop::HitSlop(match input.as_number() {
Some(n) => EdgeInsets::all(Points(n as f32)),
None => EdgeInsets::decode(input, cx).unwrap_or_default(),
}))
}
pub(crate) fn class_list<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
Some(Prop::ClassList(
input
.entries()
.into_iter()
.filter(|(_, on)| on.truthy())
.map(|(name, _)| name.into())
.collect(),
))
}
pub(crate) fn tailwind_theme<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
Some(Prop::TailwindTheme(input.as_string()?.into()))
}
pub(crate) fn ui_theme<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
Some(Prop::UiTheme(input.as_string()?.into()))
}
pub(crate) fn role<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<AccessibilityProp> {
let role = AccessibilityRole::decode(input, cx);
if role.is_none()
&& let Some(name) = input.as_string().filter(|n| !n.is_empty())
{
cx.warn(format!("unknown role `{name}`"));
}
Some(AccessibilityProp::Role(role.unwrap_or_default()))
}
pub(crate) fn accessibility_level<I: HostInput>(
input: &I,
_: &mut HostCx,
) -> Option<AccessibilityProp> {
let level = input
.as_number()
.filter(|n| *n >= 1.0 && n.fract() == 0.0 && *n <= f64::from(u32::MAX))
.map(|n| n as u32);
Some(AccessibilityProp::Level(level))
}
pub(crate) fn important<I: HostInput>(input: &I, _: &mut HostCx) -> Option<AccessibilityProp> {
Some(match input.as_string().as_deref() {
Some("yes") => AccessibilityProp::Important(Some(true), false),
Some("no") => AccessibilityProp::Important(Some(false), false),
Some("no-hide-descendants") => AccessibilityProp::Important(Some(false), true),
_ => AccessibilityProp::Important(None, false),
})
}
pub(crate) fn deceleration<I: HostInput>(input: &I, _: &mut HostCx) -> Option<ScrollProp> {
Some(ScrollProp::Deceleration(match input.as_string() {
Some(s) => match s.as_str() {
"fast" => 0.99,
"normal" => 0.998,
_ => 0.0,
},
None => input.as_number().unwrap_or(0.0) as f32,
}))
}
pub(crate) fn visible_content<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
Some(Prop::FollowEnd(
points(input, "autoscrollToBottomThreshold").map(|t| t.max(Points::ZERO)),
))
}
pub(crate) fn refresh_indicator<I: HostInput>(input: &I, _: &mut HostCx) -> Option<ScrollProp> {
Some(ScrollProp::RefreshIndicator(
points(input, "height").map(|h| h.max(Points::ZERO)),
))
}
pub(crate) fn content_offset<I: HostInput>(input: &I, _: &mut HostCx) -> Option<ScrollProp> {
let n = |key| points(input, key).unwrap_or_default();
Some(ScrollProp::ContentOffset(point(n("x"), n("y"))))
}
pub(crate) fn scrollbar<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Prop> {
Some(Prop::Scrollbar(match input.as_bool() {
Some(shows) => shows.into(),
None if input.is_object() => {
crate::ScrollbarSetting::Themed(std::sync::Arc::new(json_of(input, 0, &mut {
JSON_ENTRIES
})))
}
None => crate::ScrollbarSetting::Shown,
}))
}
const JSON_DEPTH: u32 = 64;
const JSON_ENTRIES: usize = 1 << 20;
fn json_of<I: HostInput>(input: &I, depth: u32, left: &mut usize) -> crate::JsonValue {
use crate::JsonValue;
if let Some(b) = input.as_bool() {
return JsonValue::Bool(b);
}
if let Some(n) = input.as_number() {
return serde_json::Number::from_f64(n).map_or(JsonValue::Null, JsonValue::Number);
}
if let Some(s) = input.as_string() {
return JsonValue::String(s);
}
if depth >= JSON_DEPTH {
return JsonValue::Null;
}
if let Some(list) = input.as_list() {
let mut items = Vec::new();
for i in 0..list.len() {
if *left == 0 {
break;
}
*left -= 1;
if let Some(item) = list.item(i) {
items.push(json_of(&item, depth + 1, left));
}
}
return JsonValue::Array(items);
}
if input.is_object() {
let mut fields = serde_json::Map::new();
for (key, value) in input.entries() {
if *left == 0 {
break;
}
*left -= 1;
fields.insert(key, json_of(&value, depth + 1, left));
}
return JsonValue::Object(fields);
}
JsonValue::Null
}
pub(crate) fn keyboard_taps<I: HostInput>(input: &I, _: &mut HostCx) -> Option<ScrollProp> {
Some(ScrollProp::KeyboardTaps(match input.as_bool() {
Some(true) => KeyboardTaps::Always,
Some(false) => KeyboardTaps::Never,
None => match input.as_string().as_deref() {
Some("always") => KeyboardTaps::Always,
Some("handled") => KeyboardTaps::Handled,
_ => KeyboardTaps::Never,
},
}))
}
pub(crate) fn orientations<I: HostInput>(input: &I, _: &mut HostCx) -> Option<ModalProp> {
Some(ModalProp::Orientations(orientation_bits(input)))
}
pub(crate) fn page_orientations<I: HostInput>(input: &I, _: &mut HostCx) -> Option<ScreenProp> {
Some(ScreenProp::Orientations(orientation_bits(input)))
}
fn orientation_bits<I: HostInput>(input: &I) -> u8 {
let mut bits = 0;
for name in input.items() {
bits |= match name.as_string().as_deref() {
Some("portrait") => ModalConfig::PORTRAIT,
Some("portrait-upside-down") => ModalConfig::PORTRAIT_UPSIDE_DOWN,
Some("landscape") => ModalConfig::LANDSCAPE_LEFT | ModalConfig::LANDSCAPE_RIGHT,
Some("landscape-left") => ModalConfig::LANDSCAPE_LEFT,
Some("landscape-right") => ModalConfig::LANDSCAPE_RIGHT,
_ => 0,
};
}
bits
}
impl HostValue for crate::shader::ShaderUniforms {
fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
if !input.is_object() {
return None;
}
let mut values = Vec::new();
for (name, value) in input.entries() {
match uniform_value(&value, 0) {
Some(v) => values.push((name.as_str().into(), v)),
None => cx.warn(format!(
"uniform `{name}`: a number, a color, an animated value or a list of them"
)),
}
}
Some(crate::shader::ShaderUniforms(values))
}
fn ts_type(types: &mut TsTypes) -> String {
let value = types.declare("ShaderUniform", |_| {
"/** A value of a shader's uniform: a number (`f32`, `i32`, `u32`), a color\n \
* (`vec3f` / `vec4f`, sRGB 0..1), an animated value, or a list of them (a\n \
* vector's components, an `array<vec4f, N>`'s items). */\n\
export type ShaderUniform = number | ColorValue | AnimatedNode | readonly ShaderUniform[];"
.into()
});
format!("Record<string, {value}>")
}
}
impl HostValue for crate::shader::NavShaderSpec {
fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
if !input.is_object() {
return None;
}
let mut source = None;
let mut uniforms = crate::shader::ShaderUniforms::default();
let mut duration = None;
for (name, value) in input.entries() {
match name.as_str() {
"source" => source = value.as_string(),
"uniforms" => {
uniforms = crate::shader::ShaderUniforms::decode(&value, cx).unwrap_or_default()
}
"duration" => duration = value.as_number().map(|d| d as f32),
_ => {}
}
}
Some(crate::shader::NavShaderSpec {
source: source?.as_str().into(),
uniforms,
duration,
})
}
fn ts_type(types: &mut TsTypes) -> String {
let uniforms = crate::shader::ShaderUniforms::ts_type(types);
format!("{{ source: string; uniforms?: {uniforms}; duration?: number }}")
}
}
impl HostValue for crate::shader::ShaderProgress {
fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
if let Some(n) = input.as_number() {
return Some(crate::shader::ShaderProgress::Number(
crate::geometry::Percentage(n as f32),
));
}
input
.animated_node()
.map(crate::shader::ShaderProgress::Animated)
}
fn ts_type(_: &mut TsTypes) -> String {
"number | AnimatedNode".into()
}
}
impl HostValue for crate::shader::TransitionKey {
fn decode<I: HostInput>(input: &I, _: &mut HostCx) -> Option<Self> {
if let Some(b) = input.as_bool() {
return Some(crate::shader::TransitionKey::Bool(b));
}
if let Some(n) = input.as_number() {
return Some(crate::shader::TransitionKey::number(n));
}
input
.as_string()
.map(|s| crate::shader::TransitionKey::String(s.as_str().into()))
}
fn ts_type(_: &mut TsTypes) -> String {
"string | number | boolean".into()
}
}
fn uniform_value<I: HostInput>(input: &I, depth: u32) -> Option<crate::shader::UniformValue> {
use crate::shader::UniformValue;
if let Some(n) = input.as_number() {
return Some(UniformValue::Number(n as f32));
}
if let Some(s) = input.as_string() {
return crate::Color::parse(&s).map(UniformValue::Color);
}
if let Some(node) = input.animated_node() {
return Some(UniformValue::Animated(node));
}
let list = input.as_list()?;
if depth > 1 {
return None;
}
(0..list.len())
.map(|i| {
list.item(i)
.and_then(|item| uniform_value(&item, depth + 1))
})
.collect::<Option<Vec<_>>>()
.map(UniformValue::List)
}