Skip to main content

strata_ui/
inputs.rs

1//! High-Level Accessible Form Controls and Inputs for Strata UI.
2
3#![allow(non_snake_case)]
4
5use strata_dom::{create_dropdown_portal, use_persistent_signal, AnchorPlacement, Signal, View};
6use strata_icons::prelude::{Icon, IconName};
7use strata_macro::{component, rsx};
8
9/// Standard text input field with prefix/suffix icons, helper text, and error states.
10#[component]
11pub fn Input(
12    label: Option<&'static str>,
13    placeholder: Option<&'static str>,
14    value: Option<Signal<String>>,
15    prefix_icon: Option<IconName>,
16    suffix_icon: Option<IconName>,
17    helper_text: Option<&'static str>,
18    is_error: Option<bool>,
19    error_message: Option<&'static str>,
20    disabled: Option<bool>,
21    class: Option<&'static str>,
22) -> View {
23    let custom = class.unwrap_or("");
24    let err = is_error.unwrap_or(false);
25    let border_color = if err {
26        "border-rose-500 focus:border-rose-500 focus:ring-rose-500/20"
27    } else {
28        "border-neutral-800 focus:border-indigo-500 focus:ring-indigo-500/20"
29    };
30
31    let pl = if prefix_icon.is_some() {
32        "pl-10"
33    } else {
34        "pl-3.5"
35    };
36    let pr = if suffix_icon.is_some() {
37        "pr-10"
38    } else {
39        "pr-3.5"
40    };
41
42    let input_classes = format!(
43        "w-full h-10 bg-neutral-900 border rounded-lg text-sm text-white placeholder-neutral-500 focus:outline-none focus:ring-2 transition-all duration-150 disabled:opacity-50 disabled:pointer-events-none {border_color} {pl} {pr} {custom}"
44    );
45
46    let val_str = value.map(|s| s.get()).unwrap_or_default();
47
48    rsx! {
49        <div class="flex flex-col gap-1.5 w-full">
50            {if let Some(lbl) = label {
51                rsx! { <label class="text-xs font-mono uppercase tracking-wider text-neutral-400 select-none">{lbl}</label> }
52            } else {
53                rsx! { <></> }
54            }}
55            <div class="relative flex items-center w-full">
56                {if let Some(icon) = prefix_icon {
57                    rsx! {
58                        <div class="absolute left-3 flex items-center pointer-events-none text-neutral-500">
59                            {Icon(icon, Some("w-4 h-4 text-neutral-400")).root}
60                        </div>
61                    }
62                } else {
63                    rsx! { <></> }
64                }}
65                <input
66                    type="text"
67                    class={input_classes}
68                    placeholder={placeholder.unwrap_or("")}
69                    disabled={disabled.unwrap_or(false)}
70                    value={val_str}
71                />
72                {if let Some(icon) = suffix_icon {
73                    rsx! {
74                        <div class="absolute right-3 flex items-center pointer-events-none text-neutral-500">
75                            {Icon(icon, Some("w-4 h-4 text-neutral-400")).root}
76                        </div>
77                    }
78                } else {
79                    rsx! { <></> }
80                }}
81            </div>
82            {if let (true, Some(err_msg)) = (err, error_message) {
83                rsx! { <span class="text-xs text-rose-400 font-medium">{err_msg}</span> }
84            } else if let Some(help) = helper_text {
85                rsx! { <span class="text-xs text-neutral-500">{help}</span> }
86            } else {
87                rsx! { <></> }
88            }}
89        </div>
90    }
91}
92
93/// Password input with interactive eye toggle button for visibility.
94#[component]
95pub fn PasswordInput(
96    label: Option<&'static str>,
97    placeholder: Option<&'static str>,
98    value: Option<Signal<String>>,
99    show_password: Option<Signal<bool>>,
100    disabled: Option<bool>,
101    class: Option<&'static str>,
102) -> View {
103    let show = show_password.as_ref().map(|s| s.get()).unwrap_or(false);
104    let input_type = if show { "text" } else { "password" };
105    let icon = if show {
106        IconName::EyeOff
107    } else {
108        IconName::Eye
109    };
110    let show_sig = show_password.clone();
111
112    rsx! {
113        <div class="flex flex-col gap-1.5 w-full">
114            {if let Some(lbl) = label {
115                rsx! { <label class="text-xs font-mono uppercase tracking-wider text-neutral-400 select-none">{lbl}</label> }
116            } else {
117                rsx! { <></> }
118            }}
119            <div class="relative flex items-center w-full">
120                <input
121                    type={input_type}
122                    class={format!("w-full h-10 bg-neutral-900 border border-neutral-800 rounded-lg pl-3.5 pr-10 text-sm text-white placeholder-neutral-500 focus:outline-none focus:border-indigo-500 transition-colors {}", class.unwrap_or(""))}
123                    placeholder={placeholder.unwrap_or("••••••••")}
124                    disabled={disabled.unwrap_or(false)}
125                    value={value.map(|s| s.get()).unwrap_or_default()}
126                />
127                <button
128                    type="button"
129                    class="absolute right-3 text-neutral-400 hover:text-white cursor-pointer select-none"
130                    onclick={move |_| {
131                        if let Some(s) = &show_sig {
132                            s.update(|v| *v = !*v);
133                        }
134                    }}
135                >
136                    {Icon(icon, Some("w-4 h-4 text-neutral-400 hover:text-white")).root}
137                </button>
138            </div>
139        </div>
140    }
141}
142
143/// Numeric input with stepper increment and decrement buttons.
144#[component]
145pub fn NumberInput(
146    label: Option<&'static str>,
147    value: Signal<i64>,
148    min: Option<i64>,
149    max: Option<i64>,
150    step: Option<i64>,
151    disabled: Option<bool>,
152    class: Option<&'static str>,
153) -> View {
154    let s = step.unwrap_or(1);
155    let mi = min.unwrap_or(i64::MIN);
156    let ma = max.unwrap_or(i64::MAX);
157
158    let val = value.get();
159    let val_dec = value.clone();
160    let val_inc = value.clone();
161
162    rsx! {
163        <div class="flex flex-col gap-1.5 w-full">
164            {if let Some(lbl) = label {
165                rsx! { <label class="text-xs font-mono uppercase tracking-wider text-neutral-400 select-none">{lbl}</label> }
166            } else {
167                rsx! { <></> }
168            }}
169            <div class="flex items-center rounded-lg border border-neutral-800 bg-neutral-900 overflow-hidden w-full h-10">
170                <button
171                    type="button"
172                    class="h-full px-3 text-neutral-400 hover:text-white hover:bg-neutral-800/60 cursor-pointer select-none transition-colors"
173                    onclick={move |_| {
174                        val_dec.update(|v| *v = (*v - s).max(mi));
175                    }}
176                >
177                    {"-"}
178                </button>
179                <div class="flex-1 text-center font-mono text-sm text-white select-none">
180                    {val.to_string()}
181                </div>
182                <button
183                    type="button"
184                    class="h-full px-3 text-neutral-400 hover:text-white hover:bg-neutral-800/60 cursor-pointer select-none transition-colors"
185                    onclick={move |_| {
186                        val_inc.update(|v| *v = (*v + s).min(ma));
187                    }}
188                >
189                    {"+"}
190                </button>
191            </div>
192        </div>
193    }
194}
195
196/// Search input with search icon prefix and clear button.
197#[component]
198pub fn SearchInput(
199    placeholder: Option<&'static str>,
200    value: Signal<String>,
201    class: Option<&'static str>,
202) -> View {
203    let val = value.get();
204    let has_content = !val.is_empty();
205    let val_clear = value.clone();
206
207    rsx! {
208        <div class="relative flex items-center w-full">
209            <div class="absolute left-3 flex items-center pointer-events-none text-neutral-500">
210                {Icon(IconName::Search, Some("w-4 h-4 text-neutral-400")).root}
211            </div>
212            <input
213                type="text"
214                class={format!("w-full h-10 bg-neutral-900 border border-neutral-800 rounded-lg pl-10 pr-10 text-sm text-white placeholder-neutral-500 focus:outline-none focus:border-indigo-500 transition-colors {}", class.unwrap_or(""))}
215                placeholder={placeholder.unwrap_or("Search...")}
216                value={val}
217            />
218            {if has_content {
219                rsx! {
220                    <button
221                        type="button"
222                        class="absolute right-3 text-neutral-400 hover:text-white cursor-pointer select-none"
223                        onclick={move |_| val_clear.set(String::new())}
224                    >
225                        {Icon(IconName::X, Some("w-4 h-4 text-neutral-400 hover:text-white")).root}
226                    </button>
227                }
228            } else {
229                rsx! { <></> }
230            }}
231        </div>
232    }
233}
234
235/// Multi-line expanding text area editor.
236#[component]
237pub fn Textarea(
238    label: Option<&'static str>,
239    placeholder: Option<&'static str>,
240    rows: Option<usize>,
241    value: Option<Signal<String>>,
242    disabled: Option<bool>,
243    class: Option<&'static str>,
244) -> View {
245    let r = rows.unwrap_or(4);
246    let custom = class.unwrap_or("");
247    let val_str = value.as_ref().map(|s| s.get()).unwrap_or_default();
248    let val_sig = value.clone();
249
250    rsx! {
251        <div class="flex flex-col gap-1.5 w-full">
252            {if let Some(lbl) = label {
253                rsx! { <label class="text-xs font-mono uppercase tracking-wider text-neutral-400 select-none">{lbl}</label> }
254            } else {
255                rsx! { <></> }
256            }}
257            <textarea
258                rows={r.to_string()}
259                class={format!("w-full p-3.5 bg-neutral-900 border border-neutral-800 rounded-lg text-sm text-white placeholder-neutral-500 focus:outline-none focus:border-indigo-500 transition-colors resize-y {}", custom)}
260                placeholder={placeholder.unwrap_or("")}
261                disabled={disabled.unwrap_or(false)}
262                oninput={move |val: String| {
263                    if let Some(ref sig) = val_sig {
264                        if sig.get() != val {
265                            sig.set(val);
266                        }
267                    }
268                }}
269            >
270                {val_str}
271            </textarea>
272        </div>
273    }
274}
275
276/// Accessible tri-state Checkbox component.
277#[component]
278pub fn Checkbox(
279    label: Option<&'static str>,
280    checked: Signal<bool>,
281    disabled: Option<bool>,
282    class: Option<&'static str>,
283) -> View {
284    let is_checked = checked.get();
285    let is_dis = disabled.unwrap_or(false);
286    let chk = checked.clone();
287
288    let (bg, border) = if is_checked {
289        ("bg-indigo-600", "border-indigo-600")
290    } else {
291        (
292            "bg-neutral-900",
293            "border-neutral-700 hover:border-neutral-500",
294        )
295    };
296
297    rsx! {
298        <label class={format!("inline-flex items-center gap-2.5 cursor-pointer select-none group {}", if is_dis { "opacity-50 pointer-events-none" } else { "" })}>
299            <div
300                class={format!("w-5 h-5 rounded-md border flex items-center justify-center transition-all duration-150 {} {}", bg, border)}
301                onclick={move |_| {
302                    if !is_dis {
303                        chk.update(|c| *c = !*c);
304                    }
305                }}
306            >
307                {if is_checked {
308                    Icon(IconName::Check, Some("w-3.5 h-3.5 text-white stroke-[2.5]"))
309                } else {
310                    rsx! { <></> }
311                }}
312            </div>
313            {if let Some(lbl) = label {
314                rsx! { <span class="text-sm text-neutral-300 group-hover:text-white transition-colors">{lbl}</span> }
315            } else {
316                rsx! { <></> }
317            }}
318        </label>
319    }
320}
321
322/// iOS-style animated toggle switch.
323#[component]
324pub fn Switch(
325    label: Option<&'static str>,
326    description: Option<&'static str>,
327    checked: Signal<bool>,
328    disabled: Option<bool>,
329) -> View {
330    let is_active = checked.get();
331    let is_dis = disabled.unwrap_or(false);
332    let chk = checked.clone();
333
334    let bg_color = if is_active {
335        "bg-indigo-600"
336    } else {
337        "bg-neutral-800"
338    };
339    let knob_pos = if is_active {
340        "translate-x-5"
341    } else {
342        "translate-x-0"
343    };
344
345    rsx! {
346        <div class={format!("flex items-center justify-between w-full py-1.5 {}", if is_dis { "opacity-50 pointer-events-none" } else { "" })}>
347            <div class="flex flex-col">
348                {if let Some(lbl) = label {
349                    rsx! { <span class="text-sm font-medium text-white select-none">{lbl}</span> }
350                } else {
351                    rsx! { <></> }
352                }}
353                {if let Some(desc) = description {
354                    rsx! { <span class="text-xs text-neutral-400 select-none">{desc}</span> }
355                } else {
356                    rsx! { <></> }
357                }}
358            </div>
359            <button
360                type="button"
361                role="switch"
362                aria-checked={if is_active { "true" } else { "false" }}
363                class={format!("w-11 h-6 rounded-full transition-colors duration-200 relative p-0.5 cursor-pointer focus:outline-none {}", bg_color)}
364                onclick={move |_| {
365                    if !is_dis {
366                        chk.update(|c| *c = !*c);
367                    }
368                }}
369            >
370                <div class={format!("w-5 h-5 rounded-full bg-white shadow-md transition-transform duration-200 {}", knob_pos)} />
371            </button>
372        </div>
373    }
374}
375
376/// One entry of a [`Select`]: the submitted `value` and the displayed `label`.
377#[derive(Debug, Clone, PartialEq, Eq)]
378pub struct SelectOption {
379    pub value: String,
380    pub label: String,
381}
382
383impl SelectOption {
384    pub fn new(value: impl Into<String>, label: impl Into<String>) -> Self {
385        Self {
386            value: value.into(),
387            label: label.into(),
388        }
389    }
390}
391
392impl From<&str> for SelectOption {
393    fn from(text: &str) -> Self {
394        Self::new(text, text)
395    }
396}
397
398impl From<String> for SelectOption {
399    fn from(text: String) -> Self {
400        Self::new(text.clone(), text)
401    }
402}
403
404/// Moves `current` by `delta` within `len` options, clamping at both ends.
405pub fn select_step_index(len: usize, current: usize, delta: isize) -> usize {
406    if len == 0 {
407        return 0;
408    }
409    (current as isize + delta).clamp(0, len as isize - 1) as usize
410}
411
412/// Accessible dropdown select with built-in open/close, highlight and value state.
413///
414/// State lives in persistent signals keyed by `id` (or by label and options when no `id` is
415/// given), so it survives root re-invocation without the caller owning any signal. Pass
416/// `value` to control the selection from outside, and `on_change` to observe it. Give each
417/// `Select` that shares the same options and label its own `id`.
418///
419/// Keyboard: Arrow keys move the highlight (and open the list), Home/End jump, Enter or
420/// Space picks, Escape closes. The list renders in the top layer anchored to the trigger, so
421/// it escapes `overflow` containers and flips when it would leave the viewport.
422#[component]
423pub fn Select(
424    id: Option<&'static str>,
425    label: Option<&'static str>,
426    options: Vec<SelectOption>,
427    value: Option<Signal<String>>,
428    on_change: Option<std::rc::Rc<dyn Fn(&str)>>,
429    disabled: Option<bool>,
430    class: Option<&'static str>,
431) -> View {
432    let custom = class.unwrap_or("");
433    let is_dis = disabled.unwrap_or(false);
434    let key = match id {
435        Some(id) => format!("select:{id}"),
436        None => format!(
437            "select:{}:{}",
438            label.unwrap_or(""),
439            options
440                .iter()
441                .map(|o| o.value.as_str())
442                .collect::<Vec<_>>()
443                .join("|")
444        ),
445    };
446    let trigger_id = format!("{key}-trigger");
447
448    let open = use_persistent_signal(&format!("{key}:open"), || false);
449    let first_value = options.first().map(|o| o.value.clone()).unwrap_or_default();
450    let value_sig =
451        value.unwrap_or_else(|| use_persistent_signal(&format!("{key}:value"), || first_value));
452    let current_value = value_sig.get();
453    let selected_idx = options.iter().position(|o| o.value == current_value);
454    let active = use_persistent_signal(&format!("{key}:active"), || 0usize);
455    let is_open = open.get() && !is_dis;
456    let active_idx = active.get().min(options.len().saturating_sub(1));
457
458    let selected_label = selected_idx
459        .map(|i| options[i].label.clone())
460        .unwrap_or_default();
461
462    let option_values: Vec<String> = options.iter().map(|o| o.value.clone()).collect();
463    let pick = {
464        let value_sig = value_sig.clone();
465        let open = open.clone();
466        let on_change = on_change.clone();
467        move |idx: usize| {
468            if let Some(v) = option_values.get(idx) {
469                value_sig.set(v.clone());
470                open.set(false);
471                if let Some(cb) = on_change.as_ref() {
472                    cb(v);
473                }
474            }
475        }
476    };
477
478    let on_keydown = {
479        let open = open.clone();
480        let active = active.clone();
481        let pick = pick.clone();
482        let len = options.len();
483        move |e: strata_dom::Event| {
484            if is_dis {
485                return;
486            }
487            let is_open_now = open.get();
488            match e.key.as_str() {
489                "ArrowDown" | "ArrowUp" => {
490                    let delta = if e.key == "ArrowDown" { 1 } else { -1 };
491                    if is_open_now {
492                        active.set(select_step_index(len, active.get(), delta));
493                    } else {
494                        open.set(true);
495                    }
496                    e.prevent_default();
497                }
498                "Home" if is_open_now => {
499                    active.set(0);
500                    e.prevent_default();
501                }
502                "End" if is_open_now => {
503                    active.set(len.saturating_sub(1));
504                    e.prevent_default();
505                }
506                "Enter" | " " => {
507                    if is_open_now {
508                        pick(active.get());
509                    } else {
510                        open.set(true);
511                    }
512                    e.prevent_default();
513                }
514                "Escape" if is_open_now => {
515                    open.set(false);
516                    e.prevent_default();
517                }
518                _ => {}
519            }
520        }
521    };
522
523    let base = "w-full h-10 flex items-center justify-between bg-neutral-900 border border-neutral-800 rounded-lg px-3.5 text-sm text-white focus:outline-none focus:border-indigo-500 transition-colors cursor-pointer";
524    let combined = format!("{base} {custom}");
525
526    let menu = if is_open {
527        let items: Vec<_> = options
528            .iter()
529            .enumerate()
530            .map(|(i, opt)| {
531                let chosen = Some(i) == selected_idx;
532                let highlighted = i == active_idx;
533                let pick = pick.clone();
534                let row_class = format!(
535                    "px-3.5 py-2 text-sm whitespace-nowrap cursor-pointer {}",
536                    if highlighted {
537                        "bg-neutral-800 text-white"
538                    } else {
539                        "text-neutral-300"
540                    }
541                );
542                rsx! {
543                    <div
544                        role="option"
545                        aria-selected={if chosen { "true" } else { "false" }}
546                        class={row_class}
547                        onclick={move |_| pick(i)}
548                    >
549                        {opt.label.clone()}
550                    </div>
551                }
552            })
553            .collect();
554        let close = open.clone();
555        Some(create_dropdown_portal(
556            trigger_id.clone(),
557            AnchorPlacement::BottomStart,
558            4.0,
559            move |_| close.set(false),
560            rsx! {
561                <div
562                    role="listbox"
563                    class="w-full min-w-40 max-h-64 overflow-y-auto rounded-lg bg-neutral-900 border border-neutral-800 shadow-xl py-1"
564                >
565                    {items}
566                </div>
567            },
568        ))
569    } else {
570        None
571    };
572
573    rsx! {
574        <div class="flex flex-col gap-1.5 w-full">
575            {if let Some(lbl) = label {
576                rsx! { <label class="text-xs font-mono uppercase tracking-wider text-neutral-400 select-none">{lbl}</label> }
577            } else {
578                rsx! { <></> }
579            }}
580            <button
581                type="button"
582                id={trigger_id.clone()}
583                role="combobox"
584                aria-haspopup="listbox"
585                aria-expanded={if is_open { "true" } else { "false" }}
586                disabled={is_dis}
587                class={combined}
588                onclick={{
589                    let open = open.clone();
590                    move |_| {
591                        if !is_dis {
592                            open.update(|o| *o = !*o);
593                        }
594                    }
595                }}
596                onkeydown={on_keydown}
597            >
598                <span>{selected_label}</span>
599                {Icon(IconName::ChevronDown, Some("w-4 h-4 text-neutral-400")).root}
600            </button>
601            {if let Some(menu) = menu { menu } else { rsx! { <></> } }}
602        </div>
603    }
604}
605
606/// Continuous range slider with value track and thumb.
607#[component]
608pub fn Slider(
609    min: f32,
610    max: f32,
611    value: Signal<f32>,
612    disabled: Option<bool>,
613    class: Option<&'static str>,
614) -> View {
615    let val = value.get();
616    let pct = ((val - min) / (max - min)).clamp(0.0, 1.0) * 100.0;
617    let custom = class.unwrap_or("");
618
619    rsx! {
620        <div class={format!("relative flex items-center w-full py-2 {}", custom)}>
621            <div class="w-full h-2 rounded-full bg-neutral-800 overflow-hidden">
622                <div
623                    class="h-full bg-indigo-600 rounded-full transition-all duration-75"
624                    style={format!("width: {pct:.1}%;")}
625                />
626            </div>
627            <div
628                class="absolute w-4 h-4 rounded-full bg-white shadow-md border-2 border-indigo-600 cursor-pointer -ml-2 top-1"
629                style={format!("left: {pct:.1}%;")}
630            />
631        </div>
632    }
633}
634
635/// Multi-digit OTP / 2FA PinInput boxes.
636#[component]
637pub fn PinInput(length: usize, value: Signal<String>, disabled: Option<bool>) -> View {
638    let len = length.max(1);
639    let val = value.get();
640
641    rsx! {
642        <div class="flex items-center gap-2">
643            {(0..len).map(|i| {
644                let char_at = val.chars().nth(i).map(|c| c.to_string()).unwrap_or_default();
645                rsx! {
646                    <div class="w-12 h-14 rounded-xl border border-neutral-800 bg-neutral-900 flex items-center justify-center text-xl font-mono font-bold text-white shadow-inner">
647                        {char_at}
648                    </div>
649                }
650            })}
651        </div>
652    }
653}