Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/react-otp-input.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@devslab/dds-react": minor
"@devslab/dds-css": minor
---

Add a controlled six-digit OTP input with native selection and autofill, an active-cell caret, and an optional completion callback.
13 changes: 13 additions & 0 deletions docs/components-input-choice-calendar.ko.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,19 @@ labelPlacement는 outside(기본), inside(값·포커스가 있으면 위로 올

value/onValueChange는 제어 모드, defaultValue는 비제어 모드다. 제어 모드에서는 부모가 값을 갱신한다. clear는 값을 한 번 비우고 입력창으로 포커스를 돌려주며 폼을 제출하지 않는다. 필수 입력도 지울 수 있지만 빈 상태는 invalid다. disabled/readOnly에서는 지우기 버튼이 표시되지 않는다. InputGroup의 start/end는 아이콘·단위·버튼 배치만 담당한다. Field render-prop의 id/ARIA를 Input에 전달할 수 있다. input을 Field와 연결했을 때 추가 label을 이중으로 만들지 않는다.

## React의 6자리 인증 코드

`@devslab/dds-react/otp-input` 또는 패키지 루트에서 `OtpInput`을 가져온다. 레이블을 지정하고 여섯 자리 값은 폼에서 관리한다. ref와 name, ARIA 속성은 키보드 선택, 붙여넣기, 일회용 코드 자동 완성을 지원하는 네이티브 입력에 전달된다.

```tsx
<Field label="인증 코드">
{control => <OtpInput {...control} name="otp" required autoFocus
value={code} onValueChange={setCode} />}
</Field>
```

자동 확인이 필요한 폼은 `onComplete={verifyCode}`를 전달한다. 입력값을 편집해 여섯 자리를 새로 완성할 때마다 한 번 호출된다. 확인 버튼을 눌러 제출하는 폼에서는 이 콜백을 생략한다.

## Select와 SelectPicker, Combobox

- Select: 기존 네이티브 select. OS 선택 UI와 기존 API를 유지한다.
Expand Down
13 changes: 13 additions & 0 deletions docs/components-input-choice-calendar.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,19 @@ labelPlacement is outside (default), inside (floating on focus/value/autofill),

Use value/onValueChange for controlled inputs, or defaultValue for uncontrolled inputs. Clear sends one empty-string notification, returns focus, and does not submit the form. Clearing required inputs makes them invalid. Disabled/readOnly inputs cannot be cleared. Native form reset is respected, including prevented resets and parent-owned controlled values. A composing Enter is not treated as a search submission.

## Six-digit codes in React

Import `OtpInput` from `@devslab/dds-react/otp-input` or the package root. Supply a label and keep the six-digit value in form state. The ref, name and ARIA attributes reach the native input, which supports keyboard selection, paste and one-time-code autofill.

```tsx
<Field label="Authentication code">
{control => <OtpInput {...control} name="otp" required autoFocus
value={code} onValueChange={setCode} />}
</Field>
```

For automatic verification, pass `onComplete={verifyCode}`. Each edit that completes a changed code calls the handler once. An explicit confirmation button can submit the form when the handler is omitted.

## Selecting values

Select keeps its existing native-select behavior. SelectPicker provides a custom non-searchable single-value selector. Combobox combines query entry and selection; it is not a free-text storage control.
Expand Down
1 change: 1 addition & 0 deletions packages/dds-css/build.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export const FILES = [
"iconbutton.css",
"textfield.css",
"input.css",
"otp-input.css",
"textarea.css",
"select.css",
"choice.css",
Expand Down
71 changes: 71 additions & 0 deletions packages/dds-css/src/otp-input.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
.dds-otp-input {
position: relative;
display: grid;
grid-template-columns: repeat(6, 2.4ch);
gap: .6ch;
inline-size: max-content;
max-inline-size: 100%;
color: var(--dds-color-text-primary);
font: 600 clamp(1rem, 5vw, 1.5rem)/1 ui-monospace, monospace;
}
.dds-otp-input > span {
box-sizing: border-box;
block-size: 2.75rem;
border: 1px solid var(--dds-color-border-control, var(--dds-color-border-strong));
border-radius: var(--dds-radius-sm);
background: var(--dds-color-bg-default);
}
.dds-otp-input > .dds-otp-input__control {
position: absolute;
inset: 0 auto 0 0;
box-sizing: border-box;
inline-size: calc(100% + 2ch);
/* Fluid form inputs still need room after the last glyph for native selection. */
min-inline-size: calc(100% + 2ch);
max-inline-size: none;
block-size: 100%;
clip-path: inset(0 2ch 0 0);
appearance: none;
margin: 0;
border: 0;
border-radius: 0;
outline: none;
box-shadow: none;
padding: 0 0 0 .7ch;
background: transparent;
color: inherit;
caret-color: transparent;
font: inherit;
letter-spacing: 2ch;
text-align: start;
direction: ltr;
}
.dds-otp-input[data-disabled] { color: var(--dds-color-text-muted); }
.dds-otp-input:has(input[aria-invalid="true"]) > span { border-color: var(--dds-color-status-danger); }
.dds-otp-input:focus-within > [data-active] {
position: relative;
outline: var(--dds-space-2) solid var(--dds-color-border-focus);
outline-offset: calc(var(--dds-space-2) * -1);
}
.dds-otp-input:focus-within > [data-caret]::after {
content: "";
position: absolute;
z-index: 1;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
inline-size: 2px;
block-size: 1em;
background: currentColor;
pointer-events: none;
}
.dds-otp-input:focus-within > [data-caret="before"]::after { left: .4ch; }
.dds-otp-input:focus-within > [data-caret="after"]::after { left: 1.9ch; }
@keyframes dds-otp-caret-blink { 50% { opacity: 0; } }
@media (prefers-reduced-motion: no-preference) {
.dds-otp-input:focus-within > [data-caret]::after { animation: dds-otp-caret-blink 1s step-end infinite; }
}
@media (forced-colors: active) {
.dds-otp-input:focus-within > [data-active] { outline-color: Highlight; }
.dds-otp-input:focus-within > [data-caret]::after { background: CanvasText; forced-color-adjust: none; }
}
5 changes: 5 additions & 0 deletions packages/dds-react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@
"default": "./dist/index.js"
},
"./styles.css": "./styles.css",
"./otp-input": {
"types": "./dist/otp-input.d.ts",
"import": "./dist/otp-input.js",
"default": "./dist/otp-input.js"
},
"./input": {
"types": "./dist/input.d.ts",
"import": "./dist/input.js",
Expand Down
91 changes: 91 additions & 0 deletions packages/dds-react/src/__tests__/otp-input.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import { createRef, useState } from "react";
import { fireEvent, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest";
import { OtpInput } from "../otp-input";

describe("OtpInput", () => {
it("focuses one labelled native input and lets the form own submission", async () => {
const user = userEvent.setup();
const ref = createRef<HTMLInputElement>();
const submit = vi.fn();
function Form() {
const [value, setValue] = useState("");
return (
<form onSubmit={event => { event.preventDefault(); submit(); }}>
<label htmlFor="code">Authenticator code</label>
<span id="hint">Enter six digits</span>
<OtpInput id="code" name="otp" aria-describedby="hint" autoFocus required
ref={ref} value={value} onValueChange={setValue} />
<button type="submit">Confirm</button>
</form>
);
}
render(<Form />);
const input = screen.getByRole("textbox", { name: "Authenticator code" }) as HTMLInputElement;
expect(screen.getAllByRole("textbox")).toHaveLength(1);
expect(input).toBe(ref.current);
expect(input).toHaveFocus();
expect(input).toHaveAccessibleDescription("Enter six digits");
expect(input).toHaveAttribute("autocomplete", "one-time-code");
expect(input.inputMode).toBe("numeric");
expect(input.checkValidity()).toBe(false);
await user.keyboard("102938");
expect(new FormData(input.form!).get("otp")).toBe("102938");
expect(input.checkValidity()).toBe(true);
expect(submit).not.toHaveBeenCalled();
await user.click(screen.getByRole("button", { name: "Confirm" }));
expect(submit).toHaveBeenCalledTimes(1);
});

it("completes changed codes once and preserves selection while editing or pasting", async () => {
const user = userEvent.setup();
const complete = vi.fn();
function Field() {
const [value, setValue] = useState("");
return <OtpInput aria-label="Code" autoFocus value={value} onValueChange={setValue} onComplete={complete} />;
}
render(<Field />);
const input = screen.getByRole("textbox") as HTMLInputElement;
await user.keyboard("10293");
expect(complete).not.toHaveBeenCalled();
await user.keyboard("8");
expect(complete).toHaveBeenCalledExactlyOnceWith("102938");
input.select();
await user.paste("102 938");
expect(complete).toHaveBeenCalledTimes(1);
input.setSelectionRange(1, 3);
await user.paste("4-5");
expect(input).toHaveValue("145938");
expect(input.selectionStart).toBe(3);
expect(complete).toHaveBeenNthCalledWith(2, "145938");
await user.keyboard("{ArrowRight}{Backspace}");
expect(input).toHaveValue("14538");
expect(input.selectionStart).toBe(3);
expect(complete).toHaveBeenCalledTimes(2);
await user.keyboard("9");
expect(complete).toHaveBeenNthCalledWith(3, "145938");
expect(complete).toHaveBeenCalledTimes(3);
});

it("handles autofill and a caller-controlled reset without submitting during render", async () => {
const user = userEvent.setup();
const onValueChange = vi.fn();
const onComplete = vi.fn();
const props = { "aria-label": "Code", onValueChange, onComplete };
const view = render(<OtpInput {...props} value="102938" disabled />);
const input = screen.getByRole("textbox");
expect(input).toBeDisabled();
expect(onComplete).not.toHaveBeenCalled();
await user.type(input, "8");
expect(onValueChange).not.toHaveBeenCalled();
view.rerender(<OtpInput {...props} value="" />);
expect(input).toHaveValue("");
expect(onValueChange).not.toHaveBeenCalled();
fireEvent.input(input, { target: { value: "102938" } });
expect(onValueChange).toHaveBeenCalledExactlyOnceWith("102938");
expect(onComplete).toHaveBeenCalledExactlyOnceWith("102938");
view.rerender(<OtpInput {...props} value="102938" />);
expect(onComplete).toHaveBeenCalledTimes(1);
});
});
1 change: 1 addition & 0 deletions packages/dds-react/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export * from "./status-pill";
export * from "./pending-action";

export * from "./input";
export * from "./otp-input";
export * from "./combobox";
export * from "./select-picker";
export * from "./dropdown-menu";
Expand Down
96 changes: 96 additions & 0 deletions packages/dds-react/src/otp-input.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import {
forwardRef,
useState,
type ClipboardEvent,
type ComponentPropsWithoutRef,
} from "react";

const codeLength = 6;
const digitsOnly = (text: string) => text.replace(/[^0-9]/g, "");

export interface OtpInputProps extends Omit<
ComponentPropsWithoutRef<"input">,
"value" | "defaultValue" | "type" | "inputMode" | "autoComplete" | "pattern" | "maxLength" | "onChange" | "children"
> {
value: string;
onValueChange: (value: string) => void;
/** Called only when an edit produces a changed six-digit code. */
onComplete?: (digits: string) => void;
}

/** Six visual cells share one native input, selection and autofill target. */
export const OtpInput = forwardRef<HTMLInputElement, OtpInputProps>(function OtpInput(
{ value, onValueChange, onComplete, onFocus, onSelect, onPaste, className, disabled, ...inputProps },
ref,
) {
const code = digitsOnly(value).slice(0, codeLength);
const [selection, setSelection] = useState({ edge: code.length, collapsed: true });
const edge = Math.min(selection.edge, code.length);
const activeCell = Math.min(edge, codeLength - 1);
const caret = edge === codeLength ? "after" : edge === code.length ? "center" : "before";

function trackSelection(input: HTMLInputElement) {
const start = input.selectionStart ?? input.value.length;
const end = input.selectionEnd ?? start;
setSelection({ edge: input.selectionDirection === "backward" ? start : end, collapsed: start === end });
}

function update(input: HTMLInputElement) {
const raw = input.value;
const next = digitsOnly(raw).slice(0, codeLength);
if (next !== raw) {
const start = digitsOnly(raw.slice(0, input.selectionStart ?? raw.length)).length;
const end = digitsOnly(raw.slice(0, input.selectionEnd ?? raw.length)).length;
const direction = input.selectionDirection;
input.value = next;
input.setSelectionRange(start, end, direction ?? "none");
}
trackSelection(input);
if (next === code) return;
onValueChange(next);
if (next.length === codeLength) onComplete?.(next);
}

function paste(event: ClipboardEvent<HTMLInputElement>) {
onPaste?.(event);
if (event.defaultPrevented || disabled || inputProps.readOnly) return;
event.preventDefault();
const input = event.currentTarget;
const start = input.selectionStart ?? code.length;
const end = input.selectionEnd ?? start;
const incoming = digitsOnly(event.clipboardData.getData("text")).slice(0, codeLength - code.length + end - start);
if (incoming) {
input.setRangeText(incoming, start, end, "end");
update(input);
}
}

return (
<div className="dds-otp-input" dir="ltr" data-disabled={disabled || undefined}>
{Array.from({ length: codeLength }, (_, index) => (
<span
key={index}
aria-hidden="true"
data-active={index === activeCell || undefined}
data-caret={index === activeCell && selection.collapsed ? caret : undefined}
/>
))}
<input
{...inputProps}
ref={ref}
className={["dds-otp-input__control", className].filter(Boolean).join(" ")}
type="text"
inputMode="numeric"
autoComplete="one-time-code"
pattern="[0-9]{6}"
maxLength={codeLength}
value={code}
disabled={disabled}
onFocus={event => { trackSelection(event.currentTarget); onFocus?.(event); }}
onSelect={event => { trackSelection(event.currentTarget); onSelect?.(event); }}
onChange={event => update(event.currentTarget)}
onPaste={paste}
/>
</div>
);
});
1 change: 1 addition & 0 deletions packages/dds-react/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export default defineConfig({
entry: {
index: "src/index.ts",
input: "src/input.tsx",
"otp-input": "src/otp-input.tsx",
combobox: "src/combobox.tsx",
"select-picker": "src/select-picker.tsx",
"dropdown-menu": "src/dropdown-menu.tsx",
Expand Down
2 changes: 1 addition & 1 deletion tests/component-entries.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const read=async path=>JSON.parse(await readFile(new URL(`../${path}`,import.met
const paths=['input','combobox','select-picker','dropdown-menu','popover','calendar','date-picker','time-picker','date-range-picker','month-picker','segmented-control','number-input'];
for(const framework of ['solid','react']) test(`${framework} component subpaths ship declarations and runtime modules`,async()=>{
const manifest=await read(`packages/dds-${framework}/package.json`);
for(const subpath of paths){
for(const subpath of framework==='react'?[...paths,'otp-input']:paths){
const entry=manifest.exports[`./${subpath}`];
assert.ok(entry,`${subpath} is a documented public entry`);
const outputs=new Set(Object.values(entry));
Expand Down