use std::{
cell::RefCell,
collections::HashMap,
sync::{
Arc, Weak,
atomic::{AtomicBool, Ordering},
},
time::Duration,
};
use super::{
field::{FieldControl, InField},
icons, names,
part_style::{Length, PartStyle},
recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe, Selector},
shared::glyph,
text_box::{self, BoxStates, Judgment, TextBoxSize, TextBoxState},
theme::{Themed, current_theme},
};
use crate::{
animation::{AnimatableProperty, Animation, Easing, Keyframes, KeyframesId},
app::{
events::{EditCommand, KeyboardEvent, MouseEvent, PasteEvent, TextInputEvent},
theme::{IconSize, OpacityLevel, PaletteColor, Theme, TypographyStyle},
},
components::{self, ContentKind, KeyboardKind, Row, Stack},
core::{ElementRef, Signal},
layout::{Alignment, StackAlignment, layout_kind::Justify, text_style::TextStyle},
node::{CursorIcon, Element, color::Color, dimension::Dimension},
};
pub const INPUT_OTP_CARET_BLINK: KeyframesId = KeyframesId::new(0xFF41);
pub const INPUT_OTP_CARET_PERIOD: Duration = Duration::from_millis(1060);
pub(crate) fn keyframes() -> [Keyframes; 1] {
let blink = Keyframes::new(INPUT_OTP_CARET_BLINK)
.frame(0.0, |frame| {
frame.set(AnimatableProperty::Opacity, 1.0);
})
.frame(0.5, |frame| {
frame.set(AnimatableProperty::Opacity, 1.0);
})
.frame(0.501, |frame| {
frame.set(AnimatableProperty::Opacity, 0.0);
})
.frame(1.0, |frame| {
frame.set(AnimatableProperty::Opacity, 0.0);
});
[blink]
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum InputOtpPart {
Root,
Cell,
Value,
Caret,
Separator,
}
names!(InputOtpPart {
Root => "root",
Cell => "cell",
Value => "value",
Caret => "caret",
Separator => "separator",
});
pub type InputOtpSize = TextBoxSize;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum InputOtpState {
Invalid,
Warning,
Valid,
ReadOnly,
Disabled,
Masked,
Active,
Filled,
}
names!(InputOtpState {
Invalid => "invalid",
Warning => "warning",
Valid => "valid",
ReadOnly => "read_only",
Disabled => "disabled",
Masked => "masked",
Active => "active",
Filled => "filled",
});
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum InputOtpKind {
#[default]
Digits,
Alphanumeric,
}
impl InputOtpKind {
pub fn takes(self, character: char) -> bool {
match self {
Self::Digits => character.is_ascii_digit(),
Self::Alphanumeric => character.is_ascii_alphanumeric(),
}
}
}
pub type InputOtpRenderer = Arc<dyn Fn(InputOtpView) -> Element + Send + Sync>;
type CodeHandler = Arc<dyn Fn(&str) + Send + Sync>;
pub struct InputOtp {
value: Signal<String>,
length: usize,
groups: Vec<usize>,
kind: InputOtpKind,
uppercase: bool,
mask: bool,
on_change: Vec<CodeHandler>,
on_complete: Vec<CodeHandler>,
boxed: BoxStates,
states: Vec<Name>,
rules: Recipe,
forced: Option<Interaction>,
name: Option<Arc<str>>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl InputOtp {
pub fn new(value: Signal<String>) -> Self {
Self {
value,
length: 6,
groups: Vec::new(),
kind: InputOtpKind::default(),
uppercase: false,
mask: false,
on_change: Vec::new(),
on_complete: Vec::new(),
boxed: BoxStates::default(),
states: Vec::new(),
rules: Recipe::new(),
forced: None,
name: None,
id: None,
key: None,
}
}
pub fn length(mut self, length: usize) -> Self {
self.length = length.max(1);
self
}
pub fn groups(mut self, groups: impl IntoIterator<Item = usize>) -> Self {
self.groups = groups.into_iter().filter(|group| *group > 0).collect();
self
}
pub fn kind(mut self, kind: InputOtpKind) -> Self {
self.kind = kind;
self
}
pub fn uppercase(mut self, uppercase: bool) -> Self {
self.uppercase = uppercase;
self
}
pub fn mask(mut self, mask: bool) -> Self {
self.mask = mask;
self
}
pub fn on_change(mut self, handler: impl Fn(&str) + Send + Sync + 'static) -> Self {
self.on_change.push(Arc::new(handler));
self
}
pub fn on_complete(mut self, handler: impl Fn(&str) + Send + Sync + 'static) -> Self {
self.on_complete.push(Arc::new(handler));
self
}
pub fn size(mut self, size: impl Into<Name>) -> Self {
self.boxed.size = size.into();
self
}
pub fn invalid(mut self, invalid: bool) -> Self {
self.boxed.invalid = invalid;
self
}
pub fn warning(mut self, warning: bool) -> Self {
self.boxed.warning = warning;
self
}
pub fn valid(mut self, valid: bool) -> Self {
self.boxed.valid = valid;
self
}
pub fn read_only(mut self, read_only: bool) -> Self {
self.boxed.read_only = read_only;
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.boxed.disabled = disabled;
self
}
pub fn label(mut self, label: &str) -> Self {
self.boxed.label = Some(Arc::from(label));
self
}
pub fn state(mut self, state: impl Into<Name>, on: bool) -> Self {
let state = state.into();
self.states.retain(|held| *held != state);
if on {
self.states.push(state);
}
self
}
#[cfg(feature = "form")]
pub fn name(mut self, name: impl Into<Arc<str>>) -> Self {
self.name = Some(name.into());
self
}
pub fn style(mut self, part: impl Into<Name>, style: impl FnOnce(PartStyle) -> PartStyle) -> Self {
self.rules = self.rules.base(part, style);
self
}
pub fn rules(mut self, rules: &Recipe) -> Self {
self.rules = self.rules.extend(rules);
self
}
pub fn force(mut self, interaction: Option<Interaction>) -> Self {
self.forced = interaction;
self
}
pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
self.id = Some(id.into());
self
}
pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
self.key = Some(key.into());
self
}
pub fn build(self, theme: &Theme) -> Element {
let case = self
.boxed
.case(self.states.clone())
.state(InputOtpState::Masked, self.mask);
let cell_case = |active: bool, filled: bool| {
case
.clone()
.state(InputOtpState::Active, active)
.state(InputOtpState::Filled, filled)
};
let recipe = theme
.resolve::<InputOtp>(&case, Some(&self.rules))
.owned_by(self.id.as_ref());
let resolve = |case: &Case| theme.resolve::<InputOtp>(case, Some(&self.rules)).owned_like(&recipe);
let cells = [
resolve(&cell_case(false, false)),
resolve(&cell_case(false, true)),
resolve(&cell_case(true, false)),
resolve(&cell_case(true, true)),
];
let cursor = cursor(&self.value);
let held = self.value.get();
let characters: Vec<char> = taken(&held, self.kind, self.uppercase)
.into_iter()
.take(self.length)
.collect();
let code: String = characters.iter().collect();
if code != held {
self.value.set(code);
}
let last = last_cell(characters.len(), self.length);
let focused = cursor.focused.get() || self.forced == Some(Interaction::FocusVisible);
let active = focused.then(|| {
if cursor.focused.get_untracked() {
cursor.at.get().min(last)
} else {
last
}
});
let editor = Editor {
value: self.value.clone(),
cursor,
length: self.length,
kind: self.kind,
uppercase: self.uppercase,
on_change: self.on_change,
on_complete: self.on_complete,
};
let view = InputOtpView {
value: self.value,
length: self.length,
characters,
active,
separators: separators(&self.groups, self.length),
kind: self.kind,
mask: self.mask,
label: self.boxed.label.clone(),
invalid: self.boxed.judgment() == Some(Judgment::Invalid),
read_only: self.boxed.read_only,
disabled: self.boxed.disabled,
recipe,
cells,
cell_refs: (0..self.length).map(|_| ElementRef::new()).collect(),
forced: self.forced,
boxed: self.boxed,
editor,
name: self.name,
id: self.id,
key: self.key,
};
match theme.renderer::<InputOtp>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
}
impl FieldControl for InputOtp {
fn in_field(mut self, field: &InField) -> Element {
self.boxed.in_field(field);
self.into()
}
}
impl From<InputOtp> for Element {
fn from(otp: InputOtp) -> Self {
otp.build(¤t_theme())
}
}
fn taken(text: &str, kind: InputOtpKind, uppercase: bool) -> Vec<char> {
text
.chars()
.filter(|character| kind.takes(*character))
.map(|character| {
if uppercase {
character.to_ascii_uppercase()
} else {
character
}
})
.collect()
}
fn last_cell(filled: usize, length: usize) -> usize {
filled.min(length.saturating_sub(1))
}
fn separators(groups: &[usize], length: usize) -> Vec<usize> {
let mut after = Vec::new();
let mut end = 0;
for group in groups {
end += group;
if end >= length {
break;
}
after.push(end);
}
after
}
struct CursorState {
focused: Signal<bool>,
at: Signal<usize>,
past: AtomicBool,
all: AtomicBool,
}
type Cursor = Arc<CursorState>;
thread_local! {
static CURSORS: RefCell<HashMap<usize, Weak<CursorState>>> = RefCell::new(HashMap::new());
}
fn cursor(value: &Signal<String>) -> Cursor {
CURSORS.with(|cursors| {
let mut cursors = cursors.borrow_mut();
if let Some(cursor) = cursors.get(&value.id()).and_then(Weak::upgrade) {
return cursor;
}
cursors.retain(|_, cursor| cursor.strong_count() > 0);
let cursor = Arc::new(CursorState {
focused: Signal::new(false),
at: Signal::new(0),
past: AtomicBool::new(false),
all: AtomicBool::new(false),
});
cursors.insert(value.id(), Arc::downgrade(&cursor));
cursor
})
}
#[derive(Clone)]
struct Editor {
value: Signal<String>,
cursor: Cursor,
length: usize,
kind: InputOtpKind,
uppercase: bool,
on_change: Vec<CodeHandler>,
on_complete: Vec<CodeHandler>,
}
impl Editor {
fn characters(&self) -> Vec<char> {
taken(&self.value.get_untracked(), self.kind, self.uppercase)
.into_iter()
.take(self.length)
.collect()
}
fn at(&self, filled: usize) -> usize {
self.cursor.at.get_untracked().min(last_cell(filled, self.length))
}
fn taken(&self, text: &str) -> Vec<char> {
taken(text, self.kind, self.uppercase)
}
fn set(&self, before: &[char], characters: Vec<char>, at: usize) {
let full = characters.len() == self.length && characters != before;
let code: String = characters.iter().collect();
self.put_at(last_cell(characters.len(), self.length).min(at));
let past = characters.len() == self.length && at >= self.length;
self.cursor.past.store(past, Ordering::Relaxed);
if self.value.get_untracked() != code {
self.value.set(code.clone());
for handler in &self.on_change {
handler(&code);
}
}
if full {
for handler in &self.on_complete {
handler(&code);
}
}
}
fn move_to(&self, at: usize) {
self.cursor.past.store(false, Ordering::Relaxed);
self.cursor.all.store(false, Ordering::Relaxed);
self.put_at(at);
}
fn take_all(&self) -> bool {
self.cursor.all.swap(false, Ordering::Relaxed)
}
fn put_at(&self, at: usize) {
if self.cursor.at.get_untracked() != at {
self.cursor.at.set(at);
}
}
fn write(&self, text: &str) {
let taken = self.taken(text);
if taken.is_empty() {
return;
}
let before = self.characters();
if self.take_all() {
let code: Vec<char> = taken.into_iter().take(self.length).collect();
let at = code.len();
self.set(&before, code, at);
return;
}
if taken.len() < self.length && self.cursor.past.load(Ordering::Relaxed) && before.len() == self.length {
return;
}
if taken.len() >= self.length {
let code: Vec<char> = taken.into_iter().take(self.length).collect();
let at = code.len();
self.set(&before, code, at);
return;
}
let start = self.at(before.len());
let mut code = before.clone();
for (offset, character) in taken.iter().enumerate() {
let cell = start + offset;
if cell >= self.length {
break;
}
if cell < code.len() {
code[cell] = *character;
} else {
code.push(*character);
}
}
self.set(&before, code, start + taken.len());
}
fn backspace(&self) {
if self.take_all() {
self.clear();
return;
}
self.cursor.past.store(false, Ordering::Relaxed);
let before = self.characters();
let at = self.at(before.len());
let mut code = before.clone();
if at < code.len() {
code.remove(at);
self.set(&before, code, at);
} else if at > 0 {
code.remove(at - 1);
self.set(&before, code, at - 1);
}
}
fn delete(&self) {
if self.take_all() {
self.clear();
return;
}
let before = self.characters();
let at = self.at(before.len());
if at < before.len() {
let mut code = before.clone();
code.remove(at);
self.set(&before, code, at);
}
}
fn clear(&self) {
let before = self.characters();
self.set(&before, Vec::new(), 0);
}
fn step(&self, by: isize) {
let filled = self.characters().len();
let at = self.at(filled).saturating_add_signed(by);
self.move_to(at.min(last_cell(filled, self.length)));
}
fn click(&self, cell: usize) {
self.move_to(cell.min(last_cell(self.characters().len(), self.length)));
}
}
pub struct InputOtpView {
pub value: Signal<String>,
pub length: usize,
pub characters: Vec<char>,
pub active: Option<usize>,
pub separators: Vec<usize>,
pub kind: InputOtpKind,
pub mask: bool,
pub label: Option<Arc<str>>,
pub invalid: bool,
pub read_only: bool,
pub disabled: bool,
pub recipe: ResolvedRecipe,
cells: [ResolvedRecipe; 4],
cell_refs: Vec<ElementRef>,
forced: Option<Interaction>,
boxed: BoxStates,
editor: Editor,
#[cfg_attr(not(feature = "form"), allow(dead_code))]
name: Option<Arc<str>>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl InputOtpView {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part).forced(self.forced)
}
pub fn cell_part(&self, index: usize, part: impl Into<Name>) -> ResolvedPart {
let active = self.active == Some(index);
let filled = index < self.characters.len();
self.cells[usize::from(active) * 2 + usize::from(filled)]
.part(part)
.forced(self.forced)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
pub fn shown(&self, index: usize) -> Option<char> {
let character = *self.characters.get(index)?;
Some(if self.mask { '\u{2022}' } else { character })
}
pub fn size(&self) -> Option<(f32, f32)> {
let theme = self.theme();
let px = |length: Option<Length>| match length?.resolve(theme)? {
Dimension::Px(px) => Some(px),
_ => None,
};
let cell = self.part(InputOtpPart::Cell).rest();
let (width, height) = (px(cell.width)?, px(cell.height)?);
let separator = px(
self
.part(InputOtpPart::Separator)
.rest()
.width
.or(Some(Length::Icon(IconSize::Md))),
)?;
let gap = self
.part(InputOtpPart::Root)
.rest()
.gap
.map(|gap| gap.resolve(&theme.spacing(), 0.0))
.unwrap_or(0.0);
let separators = self.separators.len();
let items = self.length + separators;
let row = width * self.length as f32 + separator * separators as f32 + gap * items.saturating_sub(1) as f32;
Some((row, height.max(separator)))
}
pub fn input(&self) -> components::TextInput {
let clear = Color::new(0, 0, 0, 0);
let mut control = components::TextInput::new(self.value.clone())
.single_line()
.text_style(TextStyle {
color: clear,
..TextStyle::default()
})
.caret_color(clear)
.selection_color(clear)
.keyboard(match self.kind {
InputOtpKind::Digits => KeyboardKind::Number,
InputOtpKind::Alphanumeric => KeyboardKind::Text,
})
.content(ContentKind::OneTimeCode)
.cursor(CursorIcon::Text);
if self.mask {
control = control.mask();
}
control = match self.size() {
Some((width, height)) => control.width(width).height(height),
None => control.width(Dimension::Pct(100.0)).height(Dimension::Pct(100.0)),
};
let mut control = text_box::text_box(control, &self.boxed, Vec::new());
let (read_only, disabled) = (self.boxed.read_only, self.boxed.disabled);
let editor = self.editor.clone();
control = control.on_input(move |event: TextInputEvent| {
event.prevent_default();
if read_only || disabled {
return;
}
let keyboard = &event.keyboard;
if event.new_value.is_empty() {
editor.clear();
} else if !keyboard.ctrl && !keyboard.meta && event.new_value.contains(keyboard.key.as_str()) {
editor.write(&keyboard.key);
}
});
let editor = self.editor.clone();
control = control.on_paste(move |event: PasteEvent| {
event.prevent_default();
if read_only || disabled {
return;
}
if let Some(text) = event.text() {
editor.write(text);
}
});
let editor = self.editor.clone();
control = control.on_key_down(move |event: KeyboardEvent| {
if !event.focus_within || disabled || event.composing {
return;
}
if event.edit_command() == Some(EditCommand::SelectAll) {
editor.cursor.all.store(true, Ordering::Relaxed);
return;
}
let edits = !read_only;
match event.key.as_str() {
"Backspace" if edits => editor.backspace(),
"Delete" if edits => editor.delete(),
"Backspace" | "Delete" => {}
"ArrowLeft" => editor.step(-1),
"ArrowRight" => editor.step(1),
"Home" | "ArrowUp" => editor.move_to(0),
"End" | "ArrowDown" => editor.step(isize::MAX),
_ => return,
}
event.prevent_default();
});
let cursor = self.editor.cursor.clone();
let editor = self.editor.clone();
control = control
.on_focus(move || {
editor.step(isize::MAX);
if !cursor.focused.get_untracked() {
cursor.focused.set(true);
}
})
.on_blur({
let cursor = self.editor.cursor.clone();
move || {
cursor.all.store(false, Ordering::Relaxed);
if cursor.focused.get_untracked() {
cursor.focused.set(false);
}
}
});
let (editor, cells) = (self.editor.clone(), self.cell_refs.clone());
control = control.on_click(move |event: MouseEvent| {
if disabled || event.from_keyboard {
return;
}
let under = cells.iter().position(|cell| {
let bounds = cell.bounds();
cell.is_attached() && event.x >= bounds.x && event.x < bounds.x + bounds.width
});
if let Some(cell) = under {
editor.click(cell);
}
});
#[cfg(feature = "form")]
if let Some(name) = &self.name {
control = control.name(name.clone());
}
if let Some(id) = &self.id {
control = control.id(id.clone());
}
if let Some(key) = &self.key {
control = control.key(key.clone());
}
control
}
pub fn cell(&self, index: usize) -> Row {
let mut cell = Row::new()
.part(&self.cell_part(index, InputOtpPart::Cell))
.justify(Justify::Center)
.align_items(Alignment::Center);
if let Some(cell_ref) = self.cell_refs.get(index) {
cell = cell.ref_element(cell_ref.clone());
}
if let Some(shown) = self.shown(index) {
let value = self.cell_part(index, InputOtpPart::Value);
cell = cell.child(value.text(&shown.to_string()).nowrap());
} else if self.active == Some(index) {
let mut caret = Row::new().part(&self.cell_part(index, InputOtpPart::Caret));
if !self.theme().reduced_motion() {
caret = caret.animation(
Animation::new(INPUT_OTP_CARET_BLINK)
.duration(INPUT_OTP_CARET_PERIOD)
.easing(Easing::Linear)
.infinite(),
);
}
cell = cell.child(caret);
}
cell
}
pub fn separator(&self) -> Element {
glyph(&self.part(InputOtpPart::Separator), icons::MINUS.into(), false)
}
pub fn cells(&self) -> Row {
let mut row = Row::new()
.part(&self.part(InputOtpPart::Root))
.align_items(Alignment::Center)
.pointer_events_none();
for index in 0..self.length {
row = row.child(self.cell(index));
if self.separators.contains(&(index + 1)) {
row = row.child(self.separator());
}
}
row
}
pub fn render(self) -> Element {
Stack::new()
.stack_align(StackAlignment::CenterStart)
.child(self.input())
.child(self.cells())
.into()
}
}
impl crate::ui::Styled for InputOtp {
type Component = Self;
fn rules(self, rules: &crate::ui::Recipe) -> Self {
Self::rules(self, rules)
}
fn state(self, state: impl Into<crate::ui::Name>, on: bool) -> Self {
Self::state(self, state, on)
}
}
impl Themed for InputOtp {
const NAME: &'static str = "input_otp";
type Renderer = InputOtpRenderer;
fn parts() -> crate::ui::Declared {
InputOtpPart::declared()
}
fn states() -> crate::ui::Declared {
InputOtpState::declared()
}
fn recipe() -> Recipe {
use InputOtpPart::{Caret, Cell, Root, Separator, Value};
use PaletteColor::{Border, Foreground, Muted, MutedForeground, Ring};
let recipe = Recipe::new()
.base(Root, |s| s.gap(6.0))
.base(Cell, |s| text_box::box_style(s).width(36.0).height(40.0).padding_x(0.0))
.base(Value, |s| {
s.typography(TypographyStyle::Mono)
.font_size(16.0)
.foreground(Foreground)
})
.base(Caret, |s| s.width(1.5).height(18.0).background(Foreground))
.base(Separator, |s| s.square(IconSize::Md).foreground(MutedForeground))
.state(InputOtpState::Active, Cell, |s| s.outline(text_box::ring(Ring)))
.state(TextBoxState::ReadOnly, Cell, |s| {
s.background(Muted).border(text_box::edge(Border))
})
.state(TextBoxState::Disabled, Root, |s| s.opacity(OpacityLevel::Disabled))
.state(TextBoxState::Disabled, Cell, |s| {
s.background(Muted).cursor(CursorIcon::Default)
});
let recipe = [
(TextBoxSize::Sm, 32.0, 36.0, 14.0, 16.0),
(TextBoxSize::Lg, 40.0, 44.0, 18.0, 20.0),
]
.into_iter()
.fold(recipe, |recipe, (size, width, height, font_size, caret)| {
recipe
.size(size, Cell, |s| s.width(width).height(height))
.size(size, Value, |s| s.font_size(font_size))
.size(size, Caret, |s| s.height(caret))
});
[Judgment::Invalid, Judgment::Warning, Judgment::Valid]
.into_iter()
.fold(recipe, |recipe, judgment| {
let (state, color) = (TextBoxState::from(judgment), judgment.color());
recipe
.state(state, Cell, |s| s.border(text_box::edge(color.clone())))
.when(Selector::new().state(state).state(InputOtpState::Active), Cell, |s| {
s.outline(text_box::ring(color))
})
})
}
}