From 7db979d23dba1fba8a483d3fe893ccf2bc8b5d12 Mon Sep 17 00:00:00 2001 From: Sin-Kang Date: Sun, 22 Nov 2026 03:48:30 +0900 Subject: [PATCH 1/3] Add a controlled six-digit OTP input to DDS React --- .changeset/react-otp-input.md | 6 ++ docs/components-input-choice-calendar.ko.md | 13 +++ docs/components-input-choice-calendar.md | 13 +++ packages/dds-css/build.mjs | 1 + packages/dds-css/src/otp-input.css | 69 +++++++++++++ packages/dds-react/package.json | 5 + .../src/__tests__/otp-input.test.tsx | 91 ++++++++++++++++++ packages/dds-react/src/index.ts | 1 + packages/dds-react/src/otp-input.tsx | 96 +++++++++++++++++++ packages/dds-react/vite.config.ts | 1 + tests/component-entries.test.mjs | 2 +- 11 files changed, 297 insertions(+), 1 deletion(-) create mode 100644 .changeset/react-otp-input.md create mode 100644 packages/dds-css/src/otp-input.css create mode 100644 packages/dds-react/src/__tests__/otp-input.test.tsx create mode 100644 packages/dds-react/src/otp-input.tsx diff --git a/.changeset/react-otp-input.md b/.changeset/react-otp-input.md new file mode 100644 index 00000000..71d8062b --- /dev/null +++ b/.changeset/react-otp-input.md @@ -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. diff --git a/docs/components-input-choice-calendar.ko.md b/docs/components-input-choice-calendar.ko.md index b942f23e..4b247001 100644 --- a/docs/components-input-choice-calendar.ko.md +++ b/docs/components-input-choice-calendar.ko.md @@ -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 + + {control => } + +``` + +자동 확인이 필요한 폼은 `onComplete={verifyCode}`를 전달한다. 입력값을 편집해 여섯 자리를 새로 완성할 때마다 한 번 호출된다. 확인 버튼을 눌러 제출하는 폼에서는 이 콜백을 생략한다. + ## Select와 SelectPicker, Combobox - Select: 기존 네이티브 select. OS 선택 UI와 기존 API를 유지한다. diff --git a/docs/components-input-choice-calendar.md b/docs/components-input-choice-calendar.md index 86e0fd9a..9e046d16 100644 --- a/docs/components-input-choice-calendar.md +++ b/docs/components-input-choice-calendar.md @@ -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 + + {control => } + +``` + +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. diff --git a/packages/dds-css/build.mjs b/packages/dds-css/build.mjs index d409e03b..175c95d2 100644 --- a/packages/dds-css/build.mjs +++ b/packages/dds-css/build.mjs @@ -20,6 +20,7 @@ export const FILES = [ "iconbutton.css", "textfield.css", "input.css", + "otp-input.css", "textarea.css", "select.css", "choice.css", diff --git a/packages/dds-css/src/otp-input.css b/packages/dds-css/src/otp-input.css new file mode 100644 index 00000000..5fbd8ec8 --- /dev/null +++ b/packages/dds-css/src/otp-input.css @@ -0,0 +1,69 @@ +.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); + 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: 2px solid var(--dds-color-border-focus); + outline-offset: 2px; +} +.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; } +} diff --git a/packages/dds-react/package.json b/packages/dds-react/package.json index 154d96d3..70bd5c50 100644 --- a/packages/dds-react/package.json +++ b/packages/dds-react/package.json @@ -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", diff --git a/packages/dds-react/src/__tests__/otp-input.test.tsx b/packages/dds-react/src/__tests__/otp-input.test.tsx new file mode 100644 index 00000000..97add373 --- /dev/null +++ b/packages/dds-react/src/__tests__/otp-input.test.tsx @@ -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(); + const submit = vi.fn(); + function Form() { + const [value, setValue] = useState(""); + return ( +
{ event.preventDefault(); submit(); }}> + + Enter six digits + + + + ); + } + render(
); + 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 ; + } + render(); + 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(); + const input = screen.getByRole("textbox"); + expect(input).toBeDisabled(); + expect(onComplete).not.toHaveBeenCalled(); + await user.type(input, "8"); + expect(onValueChange).not.toHaveBeenCalled(); + view.rerender(); + expect(input).toHaveValue(""); + expect(onValueChange).not.toHaveBeenCalled(); + fireEvent.input(input, { target: { value: "102938" } }); + expect(onValueChange).toHaveBeenCalledExactlyOnceWith("102938"); + expect(onComplete).toHaveBeenCalledExactlyOnceWith("102938"); + view.rerender(); + expect(onComplete).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/dds-react/src/index.ts b/packages/dds-react/src/index.ts index b37a8534..27dacdda 100644 --- a/packages/dds-react/src/index.ts +++ b/packages/dds-react/src/index.ts @@ -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"; diff --git a/packages/dds-react/src/otp-input.tsx b/packages/dds-react/src/otp-input.tsx new file mode 100644 index 00000000..f7ae7409 --- /dev/null +++ b/packages/dds-react/src/otp-input.tsx @@ -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(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) { + 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 ( +
+ {Array.from({ length: codeLength }, (_, index) => ( +
+ ); +}); diff --git a/packages/dds-react/vite.config.ts b/packages/dds-react/vite.config.ts index a2f76f8c..15afcfa7 100644 --- a/packages/dds-react/vite.config.ts +++ b/packages/dds-react/vite.config.ts @@ -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", diff --git a/tests/component-entries.test.mjs b/tests/component-entries.test.mjs index ca36f471..e12fc249 100644 --- a/tests/component-entries.test.mjs +++ b/tests/component-entries.test.mjs @@ -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)); From e59170235bb6af5a528eabd10551c746a38f4155 Mon Sep 17 00:00:00 2001 From: Sin-Kang Date: Sun, 22 Nov 2026 04:04:46 +0900 Subject: [PATCH 2/3] Keep the last OTP cell reachable in full-width forms --- packages/dds-css/src/otp-input.css | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/dds-css/src/otp-input.css b/packages/dds-css/src/otp-input.css index 5fbd8ec8..e80684aa 100644 --- a/packages/dds-css/src/otp-input.css +++ b/packages/dds-css/src/otp-input.css @@ -20,6 +20,8 @@ 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); From b47f81048d34393f81c0adf83ef85443765e9285 Mon Sep 17 00:00:00 2001 From: Sin-Kang Date: Sun, 22 Nov 2026 04:56:30 +0900 Subject: [PATCH 3/3] Use the DDS inset focus ring for OTP cells --- packages/dds-css/src/otp-input.css | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/dds-css/src/otp-input.css b/packages/dds-css/src/otp-input.css index e80684aa..fb19004c 100644 --- a/packages/dds-css/src/otp-input.css +++ b/packages/dds-css/src/otp-input.css @@ -44,8 +44,8 @@ .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: 2px solid var(--dds-color-border-focus); - outline-offset: 2px; + 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: "";