One-time-code slots that auto-advance and accept a pasted code.
use gpui::{div, prelude::*, App, Window};
use crate::theme::ActiveTheme;
use crate::ui::input_otp::InputOtp;
pub fn input_otp_demo(window: &mut Window, cx: &mut App) -> impl IntoElement {
// InputOtp is an Entity like TextInput: create it once with `cx.new` in your own view and
// `cx.subscribe` to `OtpEvent::Complete` to verify the code.
let code = window.use_keyed_state("code", cx, |_, cx| InputOtp::new(6, cx).group_size(3));
let otp = code.read(cx);
let status = if otp.is_complete() {
format!("You entered: {}", otp.value())
} else {
"Enter your one-time password.".to_string()
};
div()
.flex()
.flex_col()
.items_center()
.gap_3()
.child(code)
.child(div().text_sm().text_color(cx.theme().muted_foreground).child(status))
}Installation
Copies src/ui/input_otp.rs into your project, along with any components it depends on, and registers the module in src/ui/mod.rs.
Install the theme
Every component reads colors from
crate::theme. Follow the installation guide if you have not added it yet.Copy the source
Paste the code below into
src/ui/input_otp.rs.src/ui/input_otp.rs //! A one-time-code field: N single-character slots that fill left to right. //! //! It is one text field drawn as slots (the model of the `input-otp` library shadcn/ui uses), //! not N separate inputs, so typing auto-advances, Backspace steps back and pasting a whole //! code fills every slot without any focus juggling. Like `TextInput` it is stateful: //! //! ```ignore //! let code = cx.new(|cx| InputOtp::new(6, cx).group_size(3)); //! cx.subscribe(&code, |this, _, event: &OtpEvent, cx| { /* OtpEvent::Complete(code) */ }).detach(); //! ``` use std::{ops::Range, time::Duration}; use gpui::{ canvas, deferred, div, prelude::*, px, Animation, AnimationExt, App, Bounds, ClipboardItem, Context, ElementInputHandler, EntityInputHandler, EventEmitter, FocusHandle, Focusable, KeyDownEvent, MouseButton, MouseDownEvent, Pixels, Point, SharedString, SpringAnimation, SpringConfig, UTF16Selection, Window, }; use crate::theme::ActiveTheme; /// shadcn's `caret-blink`: visible, fade out by 20%, hidden until 50%, back by 70%. const CARET_BLINK: Duration = Duration::from_millis(1250); /// Critically damped and quick (~150ms), like the CSS transition on shadcn's slots. const SLOT_SPRING: SpringConfig = SpringConfig::new(900.0, 60.0, 1.0); const SLOT_SIZE: Pixels = px(36.); #[derive(Clone, Debug, PartialEq)] pub enum OtpEvent { Change(SharedString), /// Every slot is filled. Complete(SharedString), } pub struct InputOtp { focus_handle: FocusHandle, length: usize, // Only ASCII is accepted, so byte, char and UTF-16 offsets are all the same. value: String, group_size: Option<usize>, alphanumeric: bool, disabled: bool, invalid: bool, } impl InputOtp { pub fn new(length: usize, cx: &mut Context<Self>) -> Self { Self { // A tab stop, so Tab and Shift-Tab reach it in a form. focus_handle: cx.focus_handle().tab_stop(true), length: length.max(1), value: String::new(), group_size: None, alphanumeric: false, disabled: false, invalid: false, } } /// Splits the slots into groups of `size` with a dash between them, e.g. 3 for `123-456`. pub fn group_size(mut self, size: usize) -> Self { self.group_size = (size > 0).then_some(size); self } /// Accepts letters as well as digits. pub fn alphanumeric(mut self) -> Self { self.alphanumeric = true; self } pub fn disabled(mut self, disabled: bool) -> Self { self.disabled = disabled; self.focus_handle = self.focus_handle.tab_stop(!disabled); self } pub fn invalid(mut self, invalid: bool) -> Self { self.invalid = invalid; self } /// Initial code. Characters the field doesn't accept are dropped (so call it after /// `alphanumeric` for letters), and it is cut to `length`. pub fn default_value(mut self, value: &str) -> Self { self.value = value.chars().filter(|&ch| self.accepts(ch)).take(self.length).collect(); self } pub fn value(&self) -> SharedString { self.value.clone().into() } pub fn is_complete(&self) -> bool { self.value.len() == self.length } pub fn set_value(&mut self, value: &str, window: &mut Window, cx: &mut Context<Self>) { self.splice(0..self.value.len(), value, window, cx); } pub fn set_invalid(&mut self, invalid: bool, cx: &mut Context<Self>) { if self.invalid != invalid { self.invalid = invalid; cx.notify(); } } fn accepts(&self, ch: char) -> bool { if self.alphanumeric { ch.is_ascii_alphanumeric() } else { ch.is_ascii_digit() } } /// Replaces `range` with the accepted characters of `text`, dropping whatever doesn't fit. fn splice(&mut self, range: Range<usize>, text: &str, window: &mut Window, cx: &mut Context<Self>) { let was_complete = self.is_complete(); let range = self.clamp(&range); let accepted: String = text.chars().filter(|&ch| self.accepts(ch)).collect(); self.value.replace_range(range, &accepted); self.value.truncate(self.length); window.notify_text_input_changed(&self.focus_handle); cx.emit(OtpEvent::Change(self.value())); if self.is_complete() && !was_complete { cx.emit(OtpEvent::Complete(self.value())); } cx.notify(); } fn on_key_down(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) { if self.disabled { return; } let secondary = event.keystroke.modifiers.secondary(cx); let handled = match event.keystroke.key.as_str() { "backspace" => { let end = self.value.len(); let start = if secondary { 0 } else { end.saturating_sub(1) }; self.splice(start..end, "", window, cx); true } "c" if secondary => { cx.write_to_clipboard(ClipboardItem::new_string(self.value.clone())); true } // On the web the clipboard can't be read synchronously; the browser's `paste` // event reaches `EntityInputHandler::paste` instead. "v" if secondary => match cx.read_from_clipboard().and_then(|item| item.text()) { Some(text) => { self.set_value(&text, window, cx); true } None => false, }, _ => false, }; if handled { cx.stop_propagation(); } } fn on_mouse_down(&mut self, _: &MouseDownEvent, window: &mut Window, cx: &mut Context<Self>) { window.focus(&self.focus_handle, cx); window.request_virtual_keyboard(); } fn clamp(&self, range: &Range<usize>) -> Range<usize> { let end = range.end.min(self.value.len()); range.start.min(end)..end } } impl EventEmitter<OtpEvent> for InputOtp {} impl Focusable for InputOtp { fn focus_handle(&self, _: &App) -> FocusHandle { self.focus_handle.clone() } } /// The caret always sits after the last filled slot, so the handler only ever appends, /// deletes from the end, or replaces the whole code on paste. impl EntityInputHandler for InputOtp { fn text_for_range( &mut self, range: Range<usize>, actual_range: &mut Option<Range<usize>>, _window: &mut Window, _cx: &mut Context<Self>, ) -> Option<String> { let range = self.clamp(&range); actual_range.replace(range.clone()); Some(self.value[range].to_string()) } fn selected_text_range( &mut self, _ignore_disabled_input: bool, _window: &mut Window, _cx: &mut Context<Self>, ) -> Option<UTF16Selection> { let end = self.value.len(); Some(UTF16Selection { range: end..end, reversed: false, }) } fn marked_text_range(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Range<usize>> { None } fn unmark_text(&mut self, _window: &mut Window, _cx: &mut Context<Self>) {} fn paste(&mut self, item: ClipboardItem, window: &mut Window, cx: &mut Context<Self>) { if let Some(text) = item.text() { self.set_value(&text, window, cx); } } fn replace_text_in_range( &mut self, range: Option<Range<usize>>, text: &str, window: &mut Window, cx: &mut Context<Self>, ) { if self.disabled { return; } let end = self.value.len(); self.splice(range.unwrap_or(end..end), text, window, cx); } // Codes are digits or ASCII letters, which no IME composes; committed text still arrives // through `replace_text_in_range`. fn replace_and_mark_text_in_range( &mut self, _range: Option<Range<usize>>, _new_text: &str, _new_selected_range: Option<Range<usize>>, _window: &mut Window, _cx: &mut Context<Self>, ) { } fn bounds_for_range( &mut self, _range: Range<usize>, element_bounds: Bounds<Pixels>, _window: &mut Window, _cx: &mut Context<Self>, ) -> Option<Bounds<Pixels>> { Some(element_bounds) } fn character_index_for_point( &mut self, _point: Point<Pixels>, _window: &mut Window, _cx: &mut Context<Self>, ) -> Option<usize> { Some(self.value.len()) } fn text_length_utf16(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<usize> { Some(self.value.len()) } fn accepts_text_input(&self, _window: &mut Window, _cx: &mut Context<Self>) -> bool { !self.disabled } } impl Render for InputOtp { fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { let focused = self.focus_handle.is_focused(window) && !self.disabled; let theme = cx.theme(); let radius = theme.radius; let active = focused.then(|| self.value.len().min(self.length - 1)); let group_size = self.group_size.unwrap_or(self.length); let ring = if self.invalid { theme.destructive.opacity(0.2) } else { theme.ring.opacity(0.5) }; let (idle_border, active_border) = if self.invalid { (theme.destructive, theme.destructive) } else { (theme.input, theme.ring) }; let (background, foreground) = (theme.background, theme.foreground); // Restarts the blink on every keystroke, so the caret is visible right after typing. let caret_cycle = self.value.len(); let slot = |ix: usize| { let first = ix % group_size == 0; let last = ix % group_size == group_size - 1 || ix == self.length - 1; let is_active = active == Some(ix); let digit = self.value.get(ix..ix + 1).map(|ch| SharedString::from(ch.to_string())); let show_caret = is_active && digit.is_none(); div() .relative() .flex() .items_center() .justify_center() .size(SLOT_SIZE) .bg(background) .border_y_1() .border_r_1() .when(first, |this| this.border_l_1().rounded_tl(radius).rounded_bl(radius)) .when(last, |this| this.rounded_tr(radius).rounded_br(radius)) .text_sm() .text_color(foreground) .children(digit) .when(show_caret, |this| { this.child( div() .w(px(1.)) .h(px(16.)) .bg(foreground) .with_animation( ("caret", caret_cycle), Animation::new(CARET_BLINK).repeat(), |caret, t| caret.opacity(caret_blink(t)), ), ) }) // The border and ring ease in and out as the active slot moves. .with_spring( ("slot-active", ix), SpringAnimation::new(SLOT_SPRING).to(is_active), move |this, phase| { let amount = phase.interpolate_clamped(0.0, 1.0); let this = this.border_color(phase.interpolate_clamped(idle_border, active_border)); if amount <= 0.01 { return this; } // Deferred so the ring paints above the neighbouring slots (shadcn's // `z-10`); it sits just outside the slot's 1px border. this.child(deferred( div() .absolute() .top(px(-4.)) .left(px(-4.)) .right(px(-4.)) .bottom(px(-4.)) .border(px(3.)) .border_color(ring.opacity(amount)) .when(first, |this| { this.rounded_tl(radius + px(3.)).rounded_bl(radius + px(3.)) }) .when(last, |this| { this.rounded_tr(radius + px(3.)).rounded_br(radius + px(3.)) }), )) }, ) }; let entity = cx.entity(); let focus_handle = self.focus_handle.clone(); let mut row = div().relative().flex().items_center().gap_2(); let mut start = 0; while start < self.length { let end = (start + group_size).min(self.length); if start > 0 { row = row.child(div().text_color(theme.muted_foreground).child("-")); } row = row.child(div().flex().items_center().children((start..end).map(slot))); start = end; } row.key_context("InputOtp") .track_focus(&self.focus_handle) .when(self.disabled, |this| this.opacity(0.5).cursor_not_allowed()) .when(!self.disabled, |this| { this.cursor_text() .on_key_down(cx.listener(Self::on_key_down)) .on_mouse_down(MouseButton::Left, cx.listener(Self::on_mouse_down)) }) // Registers this entity as the window's text input while it has focus; the slots // themselves are plain divs. .child( canvas( |_, _, _| {}, move |bounds, _, window, cx| { window.handle_input( &focus_handle, ElementInputHandler::new(bounds, entity.clone()), cx, ); }, ) .absolute() .size_full(), ) } } /// Opacity at `t` (0..1) through shadcn's caret-blink keyframes, eased out within each step. fn caret_blink(t: f32) -> f32 { let ease_out = |x: f32| 1.0 - (1.0 - x) * (1.0 - x); match t { t if t < 0.2 => 1.0 - ease_out(t / 0.2), t if t < 0.5 => 0.0, t if t < 0.7 => ease_out((t - 0.5) / 0.2), _ => 1.0, } }Register the module
// src/ui/mod.rs pub mod input_otp;
Usage
use crate::ui::input_otp::*;Examples
Pattern
By default only digits are accepted: letters and symbols are dropped as you type or paste, like shadcn/ui's REGEXP_ONLY_DIGITS. See Alphanumeric for letters too.
use gpui::{div, prelude::*, App, Window};
use crate::theme::ActiveTheme;
use crate::ui::input_otp::InputOtp;
pub fn input_otp_pattern(window: &mut Window, cx: &mut App) -> impl IntoElement {
let code = window.use_keyed_state("input-otp-pattern", cx, |_, cx| InputOtp::new(6, cx));
div()
.flex()
.flex_col()
.items_center()
.gap_3()
.child(code)
.child(
div()
.text_sm()
.text_color(cx.theme().muted_foreground)
.child("Digits only. Try typing a letter."),
)
}Separator
group_size splits the slots into groups with a separator between them. Here six slots become three pairs.
use gpui::{prelude::*, App, Window};
use crate::ui::input_otp::InputOtp;
pub fn input_otp_separator(window: &mut Window, cx: &mut App) -> impl IntoElement {
window.use_keyed_state("input-otp-separator", cx, |_, cx| {
InputOtp::new(6, cx).group_size(2)
})
}Disabled
disabled(true) dims the slots and ignores focus, typing and paste. default_value fills in a code to show.
use gpui::{div, prelude::*, App, FontWeight, Window};
use crate::theme::ActiveTheme;
use crate::ui::input_otp::InputOtp;
pub fn input_otp_disabled(window: &mut Window, cx: &mut App) -> impl IntoElement {
let code = window.use_keyed_state("input-otp-disabled", cx, |_, cx| {
InputOtp::new(6, cx)
.group_size(3)
.default_value("123456")
.disabled(true)
});
div()
.flex()
.flex_col()
.gap_3()
.child(
div()
.text_sm()
.font_weight(FontWeight::MEDIUM)
.text_color(cx.theme().foreground)
.opacity(0.5)
.child("Verification code"),
)
.child(code)
}Controlled
Read the code with value() on every render and change it from outside with set_value.
use gpui::{div, prelude::*, App, Window};
use crate::theme::ActiveTheme;
use crate::ui::button::{Button, ButtonSize, ButtonVariant};
use crate::ui::input_otp::InputOtp;
pub fn input_otp_controlled(window: &mut Window, cx: &mut App) -> impl IntoElement {
let code = window.use_keyed_state("input-otp-controlled", cx, |_, cx| InputOtp::new(6, cx));
let value = code.read(cx).value();
let status = if value.is_empty() {
"Enter your one-time password.".to_string()
} else {
format!("You entered: {value}")
};
let (fill, clear) = (code.clone(), code.clone());
div()
.flex()
.flex_col()
.items_center()
.gap_3()
.child(code)
.child(div().text_sm().text_color(cx.theme().muted_foreground).child(status))
.child(
div()
.flex()
.gap_2()
.child(
Button::new("input-otp-controlled-fill", "Fill 424242")
.variant(ButtonVariant::Outline)
.size(ButtonSize::Sm)
.on_click(move |_, window, cx| {
fill.update(cx, |otp, cx| otp.set_value("424242", window, cx));
}),
)
.child(
Button::new("input-otp-controlled-clear", "Clear")
.variant(ButtonVariant::Ghost)
.size(ButtonSize::Sm)
.on_click(move |_, window, cx| {
clear.update(cx, |otp, cx| otp.set_value("", window, cx));
}),
),
)
}Invalid
invalid(true) turns the slot borders and focus ring destructive, like aria-invalid. Use set_invalid to toggle it after checking a code.
use gpui::{div, prelude::*, App, Window};
use crate::theme::ActiveTheme;
use crate::ui::input_otp::InputOtp;
pub fn input_otp_invalid(window: &mut Window, cx: &mut App) -> impl IntoElement {
let code = window.use_keyed_state("input-otp-invalid", cx, |_, cx| {
InputOtp::new(6, cx)
.group_size(3)
.default_value("000000")
.invalid(true)
});
div()
.flex()
.flex_col()
.gap_3()
.child(code)
.child(
div()
.text_sm()
.text_color(cx.theme().destructive)
.child("Invalid code. Please try again."),
)
}Four Digits
A four-slot PIN: pass the length to InputOtp::new.
use gpui::{prelude::*, App, Window};
use crate::ui::input_otp::InputOtp;
pub fn input_otp_four_digits(window: &mut Window, cx: &mut App) -> impl IntoElement {
window.use_keyed_state("input-otp-four-digits", cx, |_, cx| InputOtp::new(4, cx))
}Alphanumeric
alphanumeric() accepts letters as well as digits, like REGEXP_ONLY_DIGITS_AND_CHARS.
use gpui::{prelude::*, App, Window};
use crate::ui::input_otp::InputOtp;
pub fn input_otp_alphanumeric(window: &mut Window, cx: &mut App) -> impl IntoElement {
window.use_keyed_state("input-otp-alphanumeric", cx, |_, cx| {
InputOtp::new(6, cx).group_size(3).alphanumeric()
})
}Form
A login verification card. Verify stays disabled until the code is complete and correct; a wrong code marks the field invalid, and Resend Code clears it.
use gpui::{div, prelude::*, px, App, FontWeight, Window};
use crate::theme::ActiveTheme;
use crate::ui::button::{Button, ButtonSize, ButtonVariant};
use crate::ui::input_otp::InputOtp;
/// The code this demo accepts. In your app, check the code on your server instead.
const EXPECTED: &str = "123456";
pub fn input_otp_form(window: &mut Window, cx: &mut App) -> impl IntoElement {
let code = window.use_keyed_state("input-otp-form", cx, |_, cx| {
InputOtp::new(6, cx).group_size(3)
});
let (complete, value) = (code.read(cx).is_complete(), code.read(cx).value());
let invalid = complete && value != EXPECTED;
code.update(cx, |otp, cx| otp.set_invalid(invalid, cx));
let resend = code.clone();
let theme = cx.theme();
let (message, message_color) = if invalid {
(format!("That code didn't match. Try {EXPECTED}."), theme.destructive)
} else {
("Enter the 6-digit code sent to your email.".to_string(), theme.muted_foreground)
};
div()
.w(px(380.))
.flex()
.flex_col()
.gap_6()
.p_6()
.rounded(theme.radius)
.border_1()
.border_color(theme.border)
.child(
div()
.flex()
.flex_col()
.gap_1()
.child(
div()
.font_weight(FontWeight::SEMIBOLD)
.text_color(theme.foreground)
.child("Verify your login"),
)
.child(
div()
.text_sm()
.text_color(theme.muted_foreground)
.child("We sent a code to jordan@example.com."),
),
)
.child(
div()
.flex()
.flex_col()
.gap_3()
.child(
div()
.flex()
.items_center()
.justify_between()
.child(
div()
.text_sm()
.font_weight(FontWeight::MEDIUM)
.text_color(theme.foreground)
.child("Verification code"),
)
.child(
Button::new("input-otp-form-resend", "Resend Code")
.variant(ButtonVariant::Ghost)
.size(ButtonSize::Sm)
.on_click(move |_, window, cx| {
resend.update(cx, |otp, cx| otp.set_value("", window, cx));
}),
),
)
.child(code)
.child(div().text_sm().text_color(message_color).child(message)),
)
.child(Button::new("input-otp-form-verify", "Verify").disabled(!complete || invalid))
.child(
div()
.text_sm()
.text_color(theme.muted_foreground)
.child("Having trouble signing in? Contact support."),
)
}API Reference
OtpEvent
OtpEvent::ChangeOtpEvent::CompleteEvery slot is filled.
InputOtp
InputOtp::new(length: usize, cx: &mut Context<Self>) -> Self.group_size(size: usize)Splits the slots into groups of size with a dash between them, e.g. 3 for 123-456.
.alphanumeric()Accepts letters as well as digits.
.disabled(disabled: bool).invalid(invalid: bool).default_value(value: &str)Initial code. Characters the field doesn't accept are dropped (so call it after alphanumeric for letters), and it is cut to length.
.value() -> SharedString.is_complete() -> bool.set_value(value: &str, window: &mut Window, cx: &mut Context<Self>).set_invalid(invalid: bool, cx: &mut Context<Self>)