diff --git a/README.md b/README.md index 7140ae4..460d925 100644 --- a/README.md +++ b/README.md @@ -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) — правки видны сразу. diff --git a/package.json b/package.json index 3e55182..2472725 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/src/index.ts b/src/index.ts index 5b09e89..25d189a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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" diff --git a/src/kit/index.ts b/src/kit/index.ts index 3aa0abb..f1eafc1 100644 --- a/src/kit/index.ts +++ b/src/kit/index.ts @@ -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" diff --git a/src/kit/login-form.tsx b/src/kit/login-form.tsx new file mode 100644 index 0000000..54ce775 --- /dev/null +++ b/src/kit/login-form.tsx @@ -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 + onVerifyOtp?: (code: string) => Promise + onResendOtp?: () => Promise + /** Кнопка «Войти по электронной подписи»; выбор сертификата — на стороне приложения. */ + onSignature?: () => Promise + 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(null) + const [code, setCode] = React.useState("") + const [resendLeft, setResendLeft] = React.useState(0) + const [pending, setPending] = React.useState(null) + const [error, setError] = React.useState() + 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(kind: Exclude, action: () => Promise) { + 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 = + + if (challenge) { + return ( +
+ + Отправили код на {challenge.destination} + + ) : ( + "Введите код из приложения-аутентификатора" + ) + } + /> +
{ + e.preventDefault() + void submitOtp() + }} + > + { + 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" + > + + {Array.from({ length: otpLength }, (_, i) => ( + + ))} + + + + {error &&

{error}

} + + + +
+ + {challenge.destination && onResendOtp && ( + resendLeft > 0 ? ( + + Повторно — через {formatCountdown(resendLeft)} + + ) : ( + + ) + )} +
+
+
+ ) + } + + return ( +
+ +
{ + e.preventDefault() + void submitLogin() + }} + > + + { + setLogin(e.target.value) + setError(undefined) + }} + disabled={busy} + /> + + + + + { + 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} + /> + + setShowPassword((v) => !v)} + disabled={busy} + > + {showPassword ? : } + + + + + +
+ + {onForgotPassword && ( + + )} +
+ + {error &&

{error}

} + + + + {onSignature && ( + <> +
+ + или + +
+ + + )} +
+
+ ) +} + +function LoginHeader({ + logo, + title, + description, +}: { + logo?: React.ReactNode + title: React.ReactNode + description?: React.ReactNode +}) { + return ( +
+ {logo &&
{logo}
} +

{title}

+ {description &&

{description}

} +
+ ) +} diff --git a/src/styles.css b/src/styles.css index 2bb6eb7..5122752 100644 --- a/src/styles.css +++ b/src/styles.css @@ -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 { diff --git a/src/ui/input-otp.tsx b/src/ui/input-otp.tsx new file mode 100644 index 0000000..5eb24d8 --- /dev/null +++ b/src/ui/input-otp.tsx @@ -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 & { + containerClassName?: string +}) { + return ( + + ) +} + +function InputOTPGroup({ className, ...props }: React.ComponentProps<"div">) { + return ( +
+ ) +} + +function InputOTPSlot({ + index, + className, + ...props +}: React.ComponentProps<"div"> & { + index: number +}) { + const inputOTPContext = React.useContext(OTPInputContext) + const { char, hasFakeCaret, isActive } = inputOTPContext?.slots[index] ?? {} + + return ( +
+ {char} + {hasFakeCaret && ( +
+
+
+ )} +
+ ) +} + +function InputOTPSeparator({ ...props }: React.ComponentProps<"div">) { + return ( +
+ +
+ ) +} + +export { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator }