use super::child_id;
use crate::inputs::field_message::render_field_message;
use arc_motion::{
arc_spring, arc_spring_with_options, is_reduced_motion, motion_now, spring::SpringOptions,
};
use arc_tokens::{ActiveArcTheme as _, BlockTokens, Radii, Spacing, Typography, oklab_mix};
use gpui_kit::base::ElementExt as _;
use gpui_kit::component::input::{
Backspace, Input as KitInput, InputEvent, InputState, MoveLeft, MoveRight,
};
use gpui_kit::{
App, BorderStyle, Bounds, Context, Corners, Edges, ElementId, Entity, Focusable as _,
IntoElement, KeyDownEvent, ParentElement, Pixels, RenderOnce, Role, SharedString, Size, Styled,
Subscription, TestSupportExt as _, TextAlign, Window, bounds, canvas, div, point, prelude::*,
px, quad,
};
use std::{cell::RefCell, rc::Rc};
#[derive(Default)]
struct RingGeometry {
focused: Option<usize>,
target: Option<Bounds<Pixels>>,
row_size: Option<Size<Pixels>>,
}
type Change = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum OtpInputMode {
#[default]
Numeric,
Text,
}
pub fn sanitize_otp(raw: &str, mode: OtpInputMode, length: usize) -> String {
raw.chars()
.filter(|c| mode == OtpInputMode::Text || c.is_ascii_digit())
.take(length)
.collect()
}
struct State {
inputs: Vec<Entity<InputState>>,
slots: Vec<String>,
on_change: Option<Change>,
mode: OtpInputMode,
error_at: f64,
last_error: Option<SharedString>,
measured_slots: Rc<RefCell<Vec<Option<Bounds<Pixels>>>>>,
ring_geometry: Rc<RefCell<RingGeometry>>,
_subscriptions: Vec<Subscription>,
}
impl State {
fn new(length: usize, mode: OtpInputMode, window: &mut Window, cx: &mut Context<Self>) -> Self {
let inputs = (0..length)
.map(|_| cx.new(|cx| InputState::new(window, cx)))
.collect::<Vec<_>>();
let subscriptions = inputs
.iter()
.enumerate()
.map(|(index, input)| {
cx.subscribe_in(input, window, move |s, emitter, event, w, cx| {
if !matches!(event, InputEvent::Change) {
return;
}
let raw = emitter.read(cx).value().to_string();
let clean = sanitize_otp(&raw, s.mode, s.inputs.len() - index);
if clean.is_empty() {
s.slots[index].clear();
} else {
for (offset, c) in clean.chars().enumerate() {
s.slots[index + offset] = c.to_string();
}
}
let count = clean.chars().count();
for (slot, input) in s.inputs.iter().enumerate() {
let text = s.slots[slot].clone();
if input.read(cx).value().as_ref() != text {
input.update(cx, |i, cx| i.set_value(text, w, cx));
}
}
let next = (index + count).min(s.inputs.len() - 1);
if count > 0 {
s.inputs[next].update(cx, |i, cx| {
i.focus(w, cx);
i.select_all(w, cx);
});
}
if let Some(cb) = &s.on_change {
cb(&s.slots.concat().into(), w, cx)
}
cx.notify();
})
})
.collect();
Self {
slots: vec![String::new(); length],
inputs,
mode,
on_change: None,
error_at: f64::NEG_INFINITY,
last_error: None,
measured_slots: Rc::new(RefCell::new(vec![None; length])),
ring_geometry: Rc::default(),
_subscriptions: subscriptions,
}
}
fn navigate(&mut self, index: usize, step: i32, w: &mut Window, cx: &mut Context<Self>) {
let target =
(index as i64 + i64::from(step)).clamp(0, self.inputs.len() as i64 - 1) as usize;
self.inputs[target].update(cx, |i, cx| {
i.focus(w, cx);
i.select_all(w, cx);
});
cx.notify();
}
fn backspace(&mut self, index: usize, w: &mut Window, cx: &mut Context<Self>) {
let target = if self.slots[index].is_empty() {
index.saturating_sub(1)
} else {
index
};
self.slots[target].clear();
self.inputs[target].update(cx, |i, cx| {
i.set_value("", w, cx);
i.focus(w, cx);
});
if let Some(cb) = &self.on_change {
cb(&self.slots.concat().into(), w, cx);
}
cx.notify();
}
fn delete_forward(&mut self, index: usize, w: &mut Window, cx: &mut Context<Self>) {
if self.slots[index].is_empty() {
return;
}
self.slots[index].clear();
self.inputs[index].update(cx, |i, cx| {
i.set_value("", w, cx);
i.focus(w, cx);
});
if let Some(cb) = &self.on_change {
cb(&self.slots.concat().into(), w, cx);
}
cx.notify();
}
}
#[derive(IntoElement)]
pub struct OtpInput {
id: ElementId,
label: SharedString,
length: usize,
value: Option<SharedString>,
description: Option<SharedString>,
error: Option<SharedString>,
auto_focus: bool,
disabled: bool,
mode: OtpInputMode,
on_change: Option<Change>,
}
impl OtpInput {
pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
label: label.into(),
length: 6,
value: None,
description: None,
error: None,
auto_focus: false,
disabled: false,
mode: OtpInputMode::Numeric,
on_change: None,
}
}
pub fn length(mut self, v: usize) -> Self {
self.length = v.max(1);
self
}
pub fn value(mut self, v: impl Into<SharedString>) -> Self {
self.value = Some(v.into());
self
}
pub fn description(mut self, v: impl Into<SharedString>) -> Self {
self.description = Some(v.into());
self
}
pub fn error(mut self, v: impl Into<SharedString>) -> Self {
self.error = Some(v.into());
self
}
pub fn auto_focus(mut self, v: bool) -> Self {
self.auto_focus = v;
self
}
pub fn disabled(mut self, v: bool) -> Self {
self.disabled = v;
self
}
pub fn input_mode(mut self, v: OtpInputMode) -> Self {
self.mode = v;
self
}
pub fn on_change(mut self, f: impl Fn(&SharedString, &mut Window, &mut App) + 'static) -> Self {
self.on_change = Some(Rc::new(f));
self
}
}
impl RenderOnce for OtpInput {
fn render(self, w: &mut Window, cx: &mut App) -> impl IntoElement {
let colors = cx.arc_theme().colors;
let motion = cx.arc_theme().motion;
let state = w.use_keyed_state(
child_id(&self.id, format!("state-{}", self.length)),
cx,
|w, cx| {
let s = State::new(self.length, self.mode, w, cx);
if self.auto_focus && !self.disabled {
let input = s.inputs[0].clone();
w.on_next_frame(move |w, cx| input.update(cx, |i, cx| i.focus(w, cx)));
}
s
},
);
state.update(cx, |s, _| {
s.on_change = self.on_change;
s.mode = self.mode;
});
if let Some(value) = self.value {
let next = sanitize_otp(&value, self.mode, self.length);
if state.read(cx).slots.concat() != next {
state.update(cx, |s, cx| {
s.slots = next
.chars()
.map(|c| c.to_string())
.chain(std::iter::repeat(String::new()))
.take(self.length)
.collect();
for (i, input) in s.inputs.iter().enumerate() {
input.update(cx, |input, cx| input.set_value(s.slots[i].clone(), w, cx));
}
});
}
}
if state.read(cx).last_error != self.error {
let now = motion_now(cx);
let next = self.error.clone();
state.update(cx, |s, _| {
s.last_error = next;
s.error_at = now;
});
}
let shake = if self.error.is_some() && !is_reduced_motion(cx) {
let elapsed = (motion_now(cx) - state.read(cx).error_at).max(0.0);
if elapsed < 0.36 {
w.request_animation_frame();
let p = (elapsed / 0.36) as f32;
(p * std::f32::consts::TAU * 3.0).sin() * 6.0 * (1.0 - p)
} else {
0.0
}
} else {
0.0
};
let inputs = state.read(cx).inputs.clone();
let measured_slots = state.read(cx).measured_slots.clone();
let row_width = BlockTokens::OTP_WIDTH * self.length as f32
+ BlockTokens::OTP_GAP * self.length.saturating_sub(1) as f32;
let mut row = div()
.id(child_id(&self.id, "slots"))
.role(Role::Group)
.aria_label(self.label.clone())
.relative()
.flex()
.gap(BlockTokens::OTP_GAP)
.w(row_width)
.max_w_full()
.ml(px(shake));
let invalid = self.error.is_some();
for (index, input) in inputs.iter().enumerate() {
let filled = !input.read(cx).value().is_empty();
let click_input = input.clone();
let left_state = state.clone();
let right_state = state.clone();
let backspace_state = state.clone();
let delete_state = state.clone();
let disabled = self.disabled;
let measured = measured_slots.clone();
let mut slot = div()
.id(child_id(&self.id, format!("slot-{index}")))
.test_support()
.on_prepaint(move |bounds, _, _| {
measured.borrow_mut()[index] = Some(bounds.extend(Edges::all(px(1.0))));
})
.relative()
.overflow_hidden()
.track_focus(&input.read(cx).focus_handle(cx))
.min_w(px(0.0))
.w(BlockTokens::OTP_WIDTH)
.h(BlockTokens::OTP_HEIGHT)
.flex_shrink(1.0)
.flex_grow(0.0)
.flex_basis(BlockTokens::OTP_WIDTH)
.rounded(Radii::CONTROL)
.border_1()
.border_color(if invalid {
colors.danger
} else if filled {
colors.accent
} else {
colors.border
})
.bg(if invalid {
oklab_mix(colors.danger, colors.surface, 0.07)
} else if filled {
colors.accent_subtle
} else {
colors.surface
})
.hover(move |s| {
if !disabled && !filled && !invalid {
s.border_color(colors.border_strong)
.bg(colors.surface_muted)
} else {
s
}
})
.text_size(Typography::TEXT_LG)
.when(disabled, |d| d.opacity(0.48).bg(colors.surface_muted))
.on_mouse_down(gpui_kit::MouseButton::Left, move |_, w, cx| {
if !disabled {
click_input.update(cx, |i, cx| {
i.focus(w, cx);
i.select_all(w, cx);
});
}
})
.capture_action(move |_: &MoveLeft, w, cx| {
if !disabled {
left_state.update(cx, |s, cx| s.navigate(index, -1, w, cx));
}
cx.stop_propagation();
})
.capture_action(move |_: &MoveRight, w, cx| {
if !disabled {
right_state.update(cx, |s, cx| s.navigate(index, 1, w, cx));
}
cx.stop_propagation();
})
.capture_action(move |_: &Backspace, w, cx| {
if !disabled {
backspace_state.update(cx, |s, cx| s.backspace(index, w, cx));
}
cx.stop_propagation();
})
.capture_key_down(move |event: &KeyDownEvent, w, cx| {
if !disabled && event.keystroke.key == "delete" {
delete_state.update(cx, |s, cx| s.delete_forward(index, w, cx));
cx.stop_propagation();
}
})
.child(
KitInput::new(input)
.appearance(false)
.text_color(gpui_kit::Hsla::transparent_black())
.text_align(TextAlign::Center)
.text_size(Typography::TEXT_LG)
.p(px(0.0))
.min_w(px(0.0))
.id(child_id(&self.id, format!("input-{index}")))
.aria_label(format!(
"{}, digit {} of {}",
self.label,
index + 1,
self.length
))
.disabled(disabled)
.size_full(),
);
if !input.read(cx).value().is_empty() {
let ch = input.read(cx).value().to_string();
let rise = arc_spring_with_options(
(
child_id(&self.id, format!("glyph-{index}")),
SharedString::from(ch.clone()),
),
0.0,
SpringOptions::new(motion.spring.snappy).with_initial_value(4.0),
w,
cx,
);
if !rise.settled {
w.request_animation_frame();
}
let opacity = (1.0 - rise.value / 4.0).clamp(0.0, 1.0);
let click = input.clone();
slot = slot.child(
div()
.id(child_id(&self.id, format!("glyph-{index}")))
.absolute()
.inset_0()
.flex()
.items_center()
.justify_center()
.text_color(colors.foreground)
.mt(px(rise.value))
.opacity(opacity)
.on_mouse_down(gpui_kit::MouseButton::Left, move |_, w, cx| {
if !disabled {
click.update(cx, |i, cx| {
i.focus(w, cx);
i.select_all(w, cx);
});
}
})
.child(ch),
);
}
row = row.child(slot);
}
let focused = if self.disabled {
None
} else {
inputs
.iter()
.position(|i| i.read(cx).focus_handle(cx).is_focused(w))
};
let ring_op = arc_spring(
(child_id(&self.id, "ring-show"), "opacity"),
if focused.is_some() { 1.0 } else { 0.0 },
motion.spring.snappy,
w,
cx,
)
.clamp(0.0, 1.0);
let geometry = state.read(cx).ring_geometry.clone();
let ring_id = child_id(&self.id, "ring-x");
row = row.child(
canvas(
|_, _, _| {},
move |rect, _, window, cx| {
let mut geometry = geometry.borrow_mut();
let resized = geometry.row_size != Some(rect.size);
let entering = geometry.focused.is_none();
let target = focused
.and_then(|index| measured_slots.borrow()[index])
.map(|slot| bounds(slot.origin - rect.origin, slot.size));
if let Some(target) = target {
geometry.target = Some(target);
}
let Some(target) = geometry.target else {
return;
};
let x = arc_spring_with_options(
(ring_id.clone(), "x"),
f32::from(target.origin.x),
SpringOptions::new(motion.spring.snappy).with_travel(!entering && !resized),
window,
cx,
)
.value;
geometry.focused = focused;
geometry.row_size = Some(rect.size);
if ring_op <= 0.01 {
return;
}
let mut color = if invalid {
colors.danger
} else {
colors.accent_strong
};
color.a *= ring_op;
window.paint_quad(quad(
bounds(rect.origin + point(px(x), target.origin.y), target.size),
Corners::all(Radii::CONTROL),
gpui_kit::Hsla::transparent_black(),
Edges::all(px(1.0)),
color,
BorderStyle::Solid,
));
},
)
.absolute()
.inset_0(),
);
div()
.id(self.id.clone())
.w_full()
.flex()
.flex_col()
.gap(Spacing::S2)
.text_color(colors.foreground)
.child(self.label)
.child(row)
.child(render_field_message(
child_id(&self.id, "description"),
self.description,
false,
w,
cx,
))
.child(render_field_message(
child_id(&self.id, "error"),
self.error,
true,
w,
cx,
))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sanitize_is_unicode_safe() {
assert_eq!(
sanitize_otp("a1中23-4567", OtpInputMode::Numeric, 6),
"123456"
);
assert_eq!(sanitize_otp("你好a", OtpInputMode::Text, 2), "你好");
}
}