use chrono::{Datelike, NaiveDate, NaiveDateTime, NaiveTime, Timelike};
use crate::{
JsonValue,
element::{JsHost, JsIn, JsOwned, JsValue, NativeEvent, PropError, TsTypes, native},
platform::{
DATE_TIME_PICKER_COMPONENT, Os, SEGMENTED_CONTROL_COMPONENT, SWITCH_COMPONENT,
TAB_BAR_COMPONENT,
},
prelude::*,
};
#[derive(Debug, Clone, Default, PartialEq, JsObject)]
#[non_exhaustive]
pub struct TabBarItem {
pub title: SharedString,
#[prop(skip_none)]
pub icon: Option<SharedString>,
#[prop(skip_none)]
pub badge: Option<SharedString>,
}
impl TabBarItem {
pub fn new(title: impl Into<SharedString>) -> Self {
Self {
title: title.into(),
..Self::default()
}
}
pub fn icon(mut self, name: impl Into<SharedString>) -> Self {
self.icon = Some(name.into());
self
}
pub fn badge(mut self, text: impl Into<SharedString>) -> Self {
self.badge = Some(text.into());
self
}
}
#[derive(Debug, Clone, PartialEq, Props)]
pub struct TabBarProps {
#[prop(default)]
pub items: Prop<Vec<TabBarItem>>,
#[prop(default)]
pub selected_index: Prop<u32>,
#[prop(default)]
pub hidden: Prop<bool>,
}
#[derive(Debug, Clone, PartialEq, Event)]
pub enum TabBarEvent {
#[args(index)]
Change(u32),
}
#[component]
pub fn TabBar(props: TabBarProps, cx: Scope<TabBarEvent>) -> impl IntoElement {
if !crate::element::has_tab_bar() {
return view().hidden().into_element();
}
let items = props.items;
native(TAB_BAR_COMPONENT)
.prop("items", move || items.with(|items| tabs_json(items)))
.prop("selectedIndex", move || {
JsonValue::from(props.selected_index.get())
})
.prop("hidden", move || JsonValue::Bool(props.hidden.get()))
.prop("tint", || {
tokens()
.color("primary")
.map_or(JsonValue::Null, |primary| color(primary).to_hex().into())
})
.on_native_event(move |event: &NativeEvent| {
if &*event.name == "change"
&& let Some(index) = event.data.as_u64()
{
cx.emit(TabBarEvent::Change(index as u32));
}
})
.into_element()
}
fn tabs_json(items: &[TabBarItem]) -> JsonValue {
items
.iter()
.map(|item| {
let mut tab = serde_json::Map::new();
tab.insert("title".into(), item.title.as_ref().into());
if let Some(icon) = &item.icon {
tab.insert("icon".into(), icon.as_ref().into());
}
if let Some(badge) = &item.badge {
tab.insert("badge".into(), badge.as_ref().into());
}
JsonValue::Object(tab)
})
.collect()
}
#[derive(Debug, Clone, Default, PartialEq, JsObject)]
#[non_exhaustive]
pub struct SegmentedControlItem {
pub title: SharedString,
#[prop(skip_none)]
pub icon: Option<SharedString>,
#[prop(default)]
pub disabled: bool,
}
impl SegmentedControlItem {
pub fn new(title: impl Into<SharedString>) -> Self {
Self {
title: title.into(),
..Self::default()
}
}
pub fn icon(mut self, name: impl Into<SharedString>) -> Self {
self.icon = Some(name.into());
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
}
#[derive(Debug, Clone, PartialEq, Props)]
pub struct SegmentedControlProps {
#[prop(default)]
pub items: Prop<Vec<SegmentedControlItem>>,
#[prop(default)]
pub selected_index: Prop<u32>,
#[prop(default)]
pub disabled: Prop<bool>,
}
#[derive(Debug, Clone, PartialEq, Event)]
pub enum SegmentedControlEvent {
#[args(index)]
Change(u32),
}
#[component]
pub fn SegmentedControl(
props: SegmentedControlProps,
cx: Scope<SegmentedControlEvent>,
) -> impl IntoElement {
if os() != Os::Ios {
return view().hidden().into_element();
}
let items = props.items;
native(SEGMENTED_CONTROL_COMPONENT)
.prop("items", move || items.with(|items| segments_json(items)))
.prop("selectedIndex", move || {
JsonValue::from(props.selected_index.get())
})
.prop("disabled", move || JsonValue::Bool(props.disabled.get()))
.on_native_event(move |event: &NativeEvent| {
if &*event.name == "change"
&& let Some(index) = event.data.as_u64()
{
cx.emit(SegmentedControlEvent::Change(index as u32));
}
})
.into_element()
}
fn segments_json(items: &[SegmentedControlItem]) -> JsonValue {
items
.iter()
.map(|item| {
let mut segment = serde_json::Map::new();
segment.insert("title".into(), item.title.as_ref().into());
if let Some(icon) = &item.icon {
segment.insert("icon".into(), icon.as_ref().into());
}
if item.disabled {
segment.insert("disabled".into(), true.into());
}
JsonValue::Object(segment)
})
.collect()
}
#[derive(Debug, Clone, PartialEq, Props)]
pub struct SwitchProps {
#[prop(default)]
pub checked: Prop<bool>,
#[prop(default)]
pub disabled: Prop<bool>,
pub accessibility_label: Prop<Option<SharedString>>,
}
#[derive(Debug, Clone, PartialEq, Event)]
pub enum SwitchEvent {
#[args(checked)]
Change(bool),
}
#[component]
pub fn Switch(props: SwitchProps, cx: Scope<SwitchEvent>) -> impl IntoElement {
if !matches!(os(), Os::Ios | Os::Android) {
return view().hidden().into_element();
}
let flips = signal(0u32);
native(SWITCH_COMPONENT)
.prop("checked", move || JsonValue::Bool(props.checked.get()))
.prop("revision", move || JsonValue::from(flips.get()))
.prop("disabled", move || JsonValue::Bool(props.disabled.get()))
.prop("accessibilityLabel", move || {
props
.accessibility_label
.get()
.map_or(JsonValue::Null, |label| label.as_ref().into())
})
.prop("tint", || {
tokens()
.color("primary")
.map_or(JsonValue::Null, |primary| color(primary).to_hex().into())
})
.on_native_event(move |event: &NativeEvent| {
if &*event.name == "change"
&& let Some(checked) = event.data.as_bool()
{
cx.emit(SwitchEvent::Change(checked));
flips.update(|n| *n = n.wrapping_add(1));
}
})
.into_element()
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PropEnum)]
pub enum DateTimePickerMode {
#[default]
Date,
Time,
DateTime,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DateTimePickerValue {
Date(NaiveDate),
Time(NaiveTime),
DateTime(NaiveDateTime),
}
impl From<NaiveDate> for DateTimePickerValue {
fn from(value: NaiveDate) -> Self {
Self::Date(value)
}
}
impl From<NaiveTime> for DateTimePickerValue {
fn from(value: NaiveTime) -> Self {
Self::Time(value)
}
}
impl From<NaiveDateTime> for DateTimePickerValue {
fn from(value: NaiveDateTime) -> Self {
Self::DateTime(value)
}
}
impl DateTimePickerValue {
pub fn parse(text: &str) -> Option<Self> {
if let Ok(v) = NaiveDateTime::parse_from_str(text, "%Y-%m-%dT%H:%M") {
Some(Self::DateTime(v))
} else if let Ok(v) = NaiveDate::parse_from_str(text, "%Y-%m-%d") {
Some(Self::Date(v))
} else {
NaiveTime::parse_from_str(text, "%H:%M")
.ok()
.map(Self::Time)
}
}
pub fn iso(&self) -> String {
match self {
Self::Date(v) => v.format("%Y-%m-%d").to_string(),
Self::Time(v) => v.format("%H:%M").to_string(),
Self::DateTime(v) => v.format("%Y-%m-%dT%H:%M").to_string(),
}
}
pub fn mode(&self) -> DateTimePickerMode {
match self {
Self::Date(_) => DateTimePickerMode::Date,
Self::Time(_) => DateTimePickerMode::Time,
Self::DateTime(_) => DateTimePickerMode::DateTime,
}
}
fn fields(&self) -> JsonValue {
let mut fields = serde_json::Map::new();
let date = match self {
Self::Date(d) => Some(*d),
Self::DateTime(v) => Some(v.date()),
Self::Time(_) => None,
};
let time = match self {
Self::Time(t) => Some(*t),
Self::DateTime(v) => Some(v.time()),
Self::Date(_) => None,
};
if let Some(date) = date {
fields.insert("year".into(), date.year().into());
fields.insert("month".into(), date.month().into());
fields.insert("day".into(), date.day().into());
}
if let Some(time) = time {
fields.insert("hour".into(), time.hour().into());
fields.insert("minute".into(), time.minute().into());
}
JsonValue::Object(fields)
}
fn of_fields(mode: DateTimePickerMode, fields: &JsonValue) -> Option<Self> {
let field = |name: &str| -> Option<u32> { fields.get(name)?.as_u64()?.try_into().ok() };
let date = || {
NaiveDate::from_ymd_opt(
field("year")?.try_into().ok()?,
field("month")?,
field("day")?,
)
};
let time = || NaiveTime::from_hms_opt(field("hour")?, field("minute")?, 0);
Some(match mode {
DateTimePickerMode::Date => Self::Date(date()?),
DateTimePickerMode::Time => Self::Time(time()?),
DateTimePickerMode::DateTime => Self::DateTime(date()?.and_time(time()?)),
})
}
}
impl JsValue for DateTimePickerValue {
fn ts_type(_types: &mut TsTypes) -> String {
"string".into()
}
fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
value
.as_string()
.and_then(|s| Self::parse(&s))
.ok_or_else(|| {
value.expected(
"an ISO date or time (`\"2026-11-17\"`, `\"09:30\"`, `\"2026-11-17T09:30\"`)",
)
})
}
fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
SharedString::from(self.iso()).to_js(host)
}
}
#[derive(Debug, Clone, PartialEq, Props)]
pub struct DateTimePickerProps {
#[prop(default)]
pub mode: Prop<DateTimePickerMode>,
pub value: Prop<Option<DateTimePickerValue>>,
pub min: Prop<Option<DateTimePickerValue>>,
pub max: Prop<Option<DateTimePickerValue>>,
#[prop(default = 1)]
pub minute_interval: Prop<u32>,
#[prop(default)]
pub disabled: Prop<bool>,
pub accessibility_label: Prop<Option<SharedString>>,
}
#[derive(Debug, Clone, PartialEq, Event)]
pub enum DateTimePickerEvent {
#[args(value)]
Change(DateTimePickerValue),
}
#[component]
pub fn DateTimePicker(
props: DateTimePickerProps,
cx: Scope<DateTimePickerEvent>,
) -> impl IntoElement {
if !matches!(os(), Os::Ios | Os::Android) {
return view().hidden().into_element();
}
let mode = props.mode;
let fields = move |value: Option<DateTimePickerValue>, prop: &str| match value {
Some(value) if value.mode() == mode.get() => value.fields(),
Some(value) => {
log::warn!(
target: "js",
"DateTimePicker: `{prop}` {:?} is not a value of mode `{}`",
value.iso(),
mode.get().js_name()
);
JsonValue::Null
}
None => JsonValue::Null,
};
native(DATE_TIME_PICKER_COMPONENT)
.prop("mode", move || JsonValue::from(mode.get().js_name()))
.prop("value", move || fields(props.value.get(), "value"))
.prop("min", move || fields(props.min.get(), "min"))
.prop("max", move || fields(props.max.get(), "max"))
.prop("minuteInterval", move || {
let interval = props.minute_interval.get();
if (1..=30).contains(&interval) && 60 % interval == 0 {
JsonValue::from(interval)
} else {
log::warn!(
target: "js",
"DateTimePicker: `minuteInterval` {interval} is not a divisor of 60 from 1 to 30; the minutes step by 1"
);
JsonValue::from(1)
}
})
.prop("disabled", move || JsonValue::Bool(props.disabled.get()))
.prop("accessibilityLabel", move || {
props
.accessibility_label
.get()
.map_or(JsonValue::Null, |label| label.as_ref().into())
})
.on_native_event(move |event: &NativeEvent| {
if &*event.name == "change"
&& let Some(value) = DateTimePickerValue::of_fields(mode.get_untracked(), &event.data)
{
cx.emit(DateTimePickerEvent::Change(value));
}
})
.into_element()
}
#[cfg(test)]
mod tests {
use chrono::{NaiveDate, NaiveTime};
use serde_json::json;
use super::{
DateTimePickerMode, DateTimePickerValue, SegmentedControlItem, TabBarItem, segments_json,
tabs_json,
};
#[test]
fn picker_values_are_iso_strings_of_minutes() {
let day = NaiveDate::from_ymd_opt(2026, 11, 17).unwrap();
let time = NaiveTime::from_hms_opt(9, 30, 0).unwrap();
for (text, value) in [
("2026-11-17", DateTimePickerValue::Date(day)),
("09:30", DateTimePickerValue::Time(time)),
(
"2026-11-17T09:30",
DateTimePickerValue::DateTime(day.and_time(time)),
),
] {
assert_eq!(DateTimePickerValue::parse(text), Some(value), "{text}");
assert_eq!(value.iso(), text);
}
for text in [
"09:30:15",
"2026-11-17T09:30:00",
"2026-02-30",
"25:00",
"",
"today",
] {
assert_eq!(DateTimePickerValue::parse(text), None, "{text}");
}
}
#[test]
fn picker_values_reach_the_platform_as_fields_and_come_back_in_the_mode() {
let value = DateTimePickerValue::parse("2026-11-17T09:30").unwrap();
let fields = json!({ "year": 2026, "month": 11, "day": 17, "hour": 9, "minute": 30 });
assert_eq!(value.fields(), fields);
assert_eq!(
DateTimePickerValue::parse("2026-11-17").unwrap().fields(),
json!({ "year": 2026, "month": 11, "day": 17 })
);
assert_eq!(
DateTimePickerValue::parse("09:30").unwrap().fields(),
json!({ "hour": 9, "minute": 30 })
);
assert_eq!(
DateTimePickerValue::of_fields(DateTimePickerMode::DateTime, &fields),
Some(value)
);
assert_eq!(
DateTimePickerValue::of_fields(DateTimePickerMode::Date, &fields),
DateTimePickerValue::parse("2026-11-17")
);
assert_eq!(
DateTimePickerValue::of_fields(DateTimePickerMode::Time, &fields),
DateTimePickerValue::parse("09:30")
);
let bad = json!({ "year": 2026, "month": 2, "day": 30, "hour": 9, "minute": 30 });
assert_eq!(
DateTimePickerValue::of_fields(DateTimePickerMode::Date, &bad),
None
);
assert_eq!(
DateTimePickerValue::of_fields(DateTimePickerMode::Time, &json!({ "hour": 9 })),
None
);
}
#[test]
fn segments_reach_the_platform_as_titles_icons_and_disabled() {
let segments = [
SegmentedControlItem::new("Light").icon("sun.max"),
SegmentedControlItem::new("Dark").disabled(true),
];
assert_eq!(
segments_json(&segments),
json!([
{ "title": "Light", "icon": "sun.max" },
{ "title": "Dark", "disabled": true },
])
);
}
#[test]
fn tabs_reach_the_platform_as_titles_and_icons() {
let tabs = [
TabBarItem::new("Records").icon("list.bullet"),
TabBarItem::new("Stats"),
];
assert_eq!(
tabs_json(&tabs),
json!([{ "title": "Records", "icon": "list.bullet" }, { "title": "Stats" }])
);
}
#[test]
fn badges_reach_the_platform_as_texts_and_empty_ones() {
let tabs = [
TabBarItem::new("Inbox").badge("3"),
TabBarItem::new("Brain").badge(""),
TabBarItem::new("Stats"),
];
assert_eq!(
tabs_json(&tabs),
json!([
{ "title": "Inbox", "badge": "3" },
{ "title": "Brain", "badge": "" },
{ "title": "Stats" },
])
);
}
}