Add LoginForm and InputOTP, release 0.2.0

LoginForm covers login/password, sign-in with an electronic signature
and a second step with a one-time code when onLogin (or onSignature)
returns an OtpChallenge. Errors are thrown from the async callbacks and
shown in the form.

- Password field: show/hide toggle, Caps Lock hint
- OTP step: auto-submit on the last digit, wrong code clears the field,
  resend after a countdown when the code was sent somewhere, back to
  the password step
- InputOTP primitive from shadcn (input-otp dependency), caret-blink
  animation in styles.css

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ilya Mukhortov 2026-10-25 11:31:17 +10:00
parent 5d22cf4948
commit 7446adc55c
7 changed files with 424 additions and 2 deletions

View File

@ -18,7 +18,7 @@ src/styles.css тема (токены, шрифты, тёмный режим)
Пакет ставится прямо из git, версии — теги `vX.Y.Z`:
```bash
npm i "git+https://git.med-logic.ru/medlogic/medkit.git#semver:^0.1.0"
npm i "git+https://git.med-logic.ru/medlogic/medkit.git#semver:^0.2.0"
```
`package-lock.json` фиксирует коммит; обновиться до свежего тега — `npm update @medkit/ui`. В medicine-ui kit подключён git-submodule в `packages/medkit` (npm workspace) — правки видны сразу.

View File

@ -1,6 +1,6 @@
{
"name": "@medkit/ui",
"version": "0.1.0",
"version": "0.2.0",
"private": true,
"description": "Medkit — UI kit МИС «Медицина»: React 19 + Tailwind 4 + Radix (shadcn/ui)",
"repository": {
@ -29,6 +29,7 @@
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
"input-otp": "^1.5.0",
"lucide-react": "^1.61.0",
"radix-ui": "^1.8.1",
"react-day-picker": "^9.14.0",

View File

@ -15,6 +15,7 @@ export * from "./ui/empty"
export * from "./ui/hover-card"
export * from "./ui/input"
export * from "./ui/input-group"
export * from "./ui/input-otp"
export * from "./ui/kbd"
export * from "./ui/label"
export * from "./ui/popover"

View File

@ -12,6 +12,7 @@ export * from "./file-drop"
export * from "./file-gallery"
export * from "./form-field"
export * from "./info-section"
export * from "./login-form"
export * from "./multi-select"
export * from "./notify"
export * from "./page-frame"

338
src/kit/login-form.tsx Normal file
View File

@ -0,0 +1,338 @@
import * as React from "react"
import { ArrowLeftIcon, EyeIcon, EyeOffIcon, FileKeyIcon, Loader2Icon } from "lucide-react"
import { Button } from "../ui/button"
import { Checkbox } from "../ui/checkbox"
import { Input } from "../ui/input"
import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from "../ui/input-group"
import { InputOTP, InputOTPGroup, InputOTPSlot } from "../ui/input-otp"
import { Label } from "../ui/label"
import { cn } from "../lib/utils"
import { FormField } from "./form-field"
export interface LoginCredentials {
login: string
password: string
remember: boolean
}
/** Второй шаг входа: у пользователя включён одноразовый код. */
export interface OtpChallenge {
/** Число цифр в коде, по умолчанию 6. */
length?: number
/** Куда отправлен код («+7 *** ***-45-67»). Без него — код из приложения-аутентификатора, без повторной отправки. */
destination?: string
/** Через сколько секунд можно запросить код повторно, по умолчанию 60. */
resendIn?: number
}
export interface LoginFormProps {
title?: React.ReactNode
description?: React.ReactNode
/** Слот над заголовком — знак продукта. */
logo?: React.ReactNode
defaultLogin?: string
/** Фокус в поле при показе (логин, а если он подставлен — пароль). По умолчанию включён. */
autoFocus?: boolean
/** Вернуть OtpChallenge — форма перейдёт к вводу кода. Ошибка — `throw new Error("текст")`. */
onLogin: (credentials: LoginCredentials) => Promise<void | OtpChallenge>
onVerifyOtp?: (code: string) => Promise<void>
onResendOtp?: () => Promise<void>
/** Кнопка «Войти по электронной подписи»; выбор сертификата — на стороне приложения. */
onSignature?: () => Promise<void | OtpChallenge>
onForgotPassword?: () => void
className?: string
}
type Pending = "login" | "signature" | "otp" | "resend" | null
function errorText(e: unknown) {
return e instanceof Error && e.message ? e.message : "Не удалось войти. Попробуйте ещё раз."
}
function formatCountdown(sec: number) {
return `${Math.floor(sec / 60)}:${String(sec % 60).padStart(2, "0")}`
}
/**
* Форма входа: логин и пароль, вход по электронной подписи, второй шаг с одноразовым кодом.
* Без своей рамки — фон и раскладку задаёт страница.
*/
export function LoginForm({
title = "Вход в систему",
description,
logo,
defaultLogin = "",
autoFocus = true,
onLogin,
onVerifyOtp,
onResendOtp,
onSignature,
onForgotPassword,
className,
}: LoginFormProps) {
const [login, setLogin] = React.useState(defaultLogin)
const [password, setPassword] = React.useState("")
const [remember, setRemember] = React.useState(true)
const [showPassword, setShowPassword] = React.useState(false)
const [capsLock, setCapsLock] = React.useState(false)
const [challenge, setChallenge] = React.useState<OtpChallenge | null>(null)
const [code, setCode] = React.useState("")
const [resendLeft, setResendLeft] = React.useState(0)
const [pending, setPending] = React.useState<Pending>(null)
const [error, setError] = React.useState<string>()
const busy = pending !== null
const otpLength = challenge?.length ?? 6
React.useEffect(() => {
if (resendLeft <= 0) return
const timer = setTimeout(() => setResendLeft((s) => s - 1), 1000)
return () => clearTimeout(timer)
}, [resendLeft])
async function run<T>(kind: Exclude<Pending, null>, action: () => Promise<T>) {
setPending(kind)
setError(undefined)
try {
return { ok: true as const, value: await action() }
} catch (e) {
setError(errorText(e))
return { ok: false as const }
} finally {
setPending(null)
}
}
function startOtp(next: void | OtpChallenge) {
if (!next) return
setChallenge(next)
setCode("")
setResendLeft(next.resendIn ?? 60)
}
async function submitLogin() {
if (busy || !login.trim() || !password) return
const result = await run("login", () => onLogin({ login: login.trim(), password, remember }))
if (result.ok) startOtp(result.value)
}
async function submitSignature() {
if (busy || !onSignature) return
const result = await run("signature", onSignature)
if (result.ok) startOtp(result.value)
}
async function submitOtp(value = code) {
if (busy || !onVerifyOtp || value.length < otpLength) return
const result = await run("otp", () => onVerifyOtp(value))
if (!result.ok) setCode("")
}
async function resend() {
if (busy || !onResendOtp) return
const result = await run("resend", onResendOtp)
if (result.ok) setResendLeft(challenge?.resendIn ?? 60)
}
function back() {
setChallenge(null)
setPassword("")
setCode("")
setError(undefined)
}
const spinner = <Loader2Icon className="animate-spin" />
if (challenge) {
return (
<div className={cn("w-full max-w-sm space-y-6", className)}>
<LoginHeader
logo={logo}
title="Код подтверждения"
description={
challenge.destination ? (
<>
Отправили код на <span className="font-medium text-foreground">{challenge.destination}</span>
</>
) : (
"Введите код из приложения-аутентификатора"
)
}
/>
<form
noValidate
className="space-y-4"
onSubmit={(e) => {
e.preventDefault()
void submitOtp()
}}
>
<InputOTP
maxLength={otpLength}
value={code}
onChange={(v) => {
setCode(v)
setError(undefined)
}}
onComplete={(v: string) => void submitOtp(v)}
disabled={pending === "otp"}
autoFocus
autoComplete="one-time-code"
inputMode="numeric"
pattern="^[0-9]*$"
aria-label="Одноразовый код"
containerClassName="justify-center"
>
<InputOTPGroup>
{Array.from({ length: otpLength }, (_, i) => (
<InputOTPSlot key={i} index={i} aria-invalid={Boolean(error)} className="h-11 w-10 text-base" />
))}
</InputOTPGroup>
</InputOTP>
{error && <p className="text-center text-sm text-destructive">{error}</p>}
<Button type="submit" size="lg" className="w-full" disabled={busy || code.length < otpLength}>
{pending === "otp" && spinner} Подтвердить
</Button>
<div className="flex items-center justify-between gap-2 text-sm">
<Button type="button" variant="ghost" size="sm" className="-ml-2.5" onClick={back} disabled={busy}>
<ArrowLeftIcon /> Назад
</Button>
{challenge.destination && onResendOtp && (
resendLeft > 0 ? (
<span className="text-muted-foreground tabular">
Повторно — через {formatCountdown(resendLeft)}
</span>
) : (
<Button type="button" variant="link" size="sm" className="-mr-3" onClick={resend} disabled={busy}>
{pending === "resend" && spinner} Отправить код повторно
</Button>
)
)}
</div>
</form>
</div>
)
}
return (
<div className={cn("w-full max-w-sm space-y-6", className)}>
<LoginHeader logo={logo} title={title} description={description} />
<form
noValidate
className="space-y-4"
onSubmit={(e) => {
e.preventDefault()
void submitLogin()
}}
>
<FormField label="Логин" htmlFor="login-form-login">
<Input
id="login-form-login"
autoComplete="username"
autoFocus={autoFocus && !defaultLogin}
value={login}
onChange={(e) => {
setLogin(e.target.value)
setError(undefined)
}}
disabled={busy}
/>
</FormField>
<FormField
label="Пароль"
htmlFor="login-form-password"
hint={capsLock ? "Включён Caps Lock" : undefined}
>
<InputGroup data-disabled={busy || undefined}>
<InputGroupInput
id="login-form-password"
type={showPassword ? "text" : "password"}
autoComplete="current-password"
autoFocus={autoFocus && Boolean(defaultLogin)}
value={password}
onChange={(e) => {
setPassword(e.target.value)
setError(undefined)
}}
onKeyDown={(e) => setCapsLock(e.getModifierState("CapsLock"))}
onKeyUp={(e) => setCapsLock(e.getModifierState("CapsLock"))}
onBlur={() => setCapsLock(false)}
aria-invalid={Boolean(error)}
disabled={busy}
/>
<InputGroupAddon align="inline-end">
<InputGroupButton
size="icon-xs"
aria-label={showPassword ? "Скрыть пароль" : "Показать пароль"}
onClick={() => setShowPassword((v) => !v)}
disabled={busy}
>
{showPassword ? <EyeOffIcon /> : <EyeIcon />}
</InputGroupButton>
</InputGroupAddon>
</InputGroup>
</FormField>
<div className="flex items-center justify-between gap-2">
<Label className="font-normal">
<Checkbox checked={remember} onCheckedChange={(v) => setRemember(v === true)} disabled={busy} />
Запомнить меня
</Label>
{onForgotPassword && (
<Button
type="button"
variant="link"
size="sm"
className="-mr-3 h-auto py-0"
onClick={onForgotPassword}
disabled={busy}
>
Забыли пароль?
</Button>
)}
</div>
{error && <p className="text-sm text-destructive">{error}</p>}
<Button type="submit" size="lg" className="w-full" disabled={busy || !login.trim() || !password}>
{pending === "login" && spinner} Войти
</Button>
{onSignature && (
<>
<div className="flex items-center gap-3 text-xs text-muted-foreground">
<span className="h-px flex-1 bg-border" />
или
<span className="h-px flex-1 bg-border" />
</div>
<Button type="button" variant="outline" size="lg" className="w-full" onClick={submitSignature} disabled={busy}>
{pending === "signature" ? spinner : <FileKeyIcon />} Войти по электронной подписи
</Button>
</>
)}
</form>
</div>
)
}
function LoginHeader({
logo,
title,
description,
}: {
logo?: React.ReactNode
title: React.ReactNode
description?: React.ReactNode
}) {
return (
<div className="space-y-2 text-center">
{logo && <div className="mb-4 flex justify-center">{logo}</div>}
<h1 className="text-xl font-semibold tracking-tight">{title}</h1>
{description && <p className="text-sm text-muted-foreground">{description}</p>}
</div>
)
}

View File

@ -161,6 +161,13 @@
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-border: var(--sidebar-border);
/* Курсор в ячейке InputOTP */
--animate-caret-blink: caret-blink 1.25s ease-out infinite;
@keyframes caret-blink {
0%, 70%, 100% { opacity: 1; }
20%, 50% { opacity: 0; }
}
}
@layer base {

74
src/ui/input-otp.tsx Normal file
View File

@ -0,0 +1,74 @@
import * as React from "react"
import { cn } from "../lib/utils"
import { OTPInput, OTPInputContext } from "input-otp"
import { MinusIcon } from "lucide-react"
function InputOTP({
className,
containerClassName,
...props
}: React.ComponentProps<typeof OTPInput> & {
containerClassName?: string
}) {
return (
<OTPInput
data-slot="input-otp"
containerClassName={cn(
"flex items-center gap-2 has-disabled:opacity-50",
containerClassName
)}
className={cn("disabled:cursor-not-allowed", className)}
{...props}
/>
)
}
function InputOTPGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="input-otp-group"
className={cn("flex items-center", className)}
{...props}
/>
)
}
function InputOTPSlot({
index,
className,
...props
}: React.ComponentProps<"div"> & {
index: number
}) {
const inputOTPContext = React.useContext(OTPInputContext)
const { char, hasFakeCaret, isActive } = inputOTPContext?.slots[index] ?? {}
return (
<div
data-slot="input-otp-slot"
data-active={isActive}
className={cn(
"relative flex h-9 w-9 items-center justify-center border-y border-r border-input text-sm shadow-xs transition-all outline-none first:rounded-l-md first:border-l last:rounded-r-md aria-invalid:border-destructive data-[active=true]:z-10 data-[active=true]:border-ring data-[active=true]:ring-[3px] data-[active=true]:ring-ring/50 data-[active=true]:aria-invalid:border-destructive data-[active=true]:aria-invalid:ring-destructive/20 dark:bg-input/30 dark:data-[active=true]:aria-invalid:ring-destructive/40",
className
)}
{...props}
>
{char}
{hasFakeCaret && (
<div className="pointer-events-none absolute inset-0 flex items-center justify-center">
<div className="h-4 w-px animate-caret-blink bg-foreground duration-1000" />
</div>
)}
</div>
)
}
function InputOTPSeparator({ ...props }: React.ComponentProps<"div">) {
return (
<div data-slot="input-otp-separator" role="separator" {...props}>
<MinusIcon />
</div>
)
}
export { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator }