Make form errors readable and add a shared phone field.
Screen readers hear field errors, phone entry keeps the caret, table rows open from the keyboard, and mask logic is covered by tests. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
1cad1831b1
commit
dae5d7d533
|
|
@ -16,7 +16,8 @@
|
||||||
"./styles.css": "./src/styles.css"
|
"./styles.css": "./src/styles.css"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"typecheck": "tsc --noEmit -p ."
|
"typecheck": "tsc --noEmit -p .",
|
||||||
|
"test": "vitest run"
|
||||||
},
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"react": "^19.0.0",
|
"react": "^19.0.0",
|
||||||
|
|
@ -36,5 +37,8 @@
|
||||||
"sonner": "^2.0.8",
|
"sonner": "^2.0.8",
|
||||||
"tailwind-merge": "^3.7.0",
|
"tailwind-merge": "^3.7.0",
|
||||||
"tw-animate-css": "^1.4.0"
|
"tw-animate-css": "^1.4.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"vitest": "^5.0.5"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,39 @@
|
||||||
|
import { describe, expect, it } from "vitest"
|
||||||
|
|
||||||
|
import { nextSort, sortRows, type DataColumn } from "./data-table"
|
||||||
|
|
||||||
|
interface Row {
|
||||||
|
name: string
|
||||||
|
age: number
|
||||||
|
}
|
||||||
|
|
||||||
|
const columns: DataColumn<Row>[] = [
|
||||||
|
{ id: "name", header: "Имя", cell: (row) => row.name, sort: (a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0) },
|
||||||
|
{ id: "age", header: "Возраст", cell: (row) => row.age, sort: (a, b) => a.age - b.age },
|
||||||
|
]
|
||||||
|
|
||||||
|
const rows: Row[] = [
|
||||||
|
{ name: "Борис", age: 40 },
|
||||||
|
{ name: "Анна", age: 30 },
|
||||||
|
]
|
||||||
|
|
||||||
|
describe("nextSort", () => {
|
||||||
|
it("крутит колонку: по возрастанию, по убыванию, без сортировки", () => {
|
||||||
|
expect(nextSort(null, "name")).toEqual({ id: "name", direction: "asc" })
|
||||||
|
expect(nextSort({ id: "name", direction: "asc" }, "name")).toEqual({ id: "name", direction: "desc" })
|
||||||
|
expect(nextSort({ id: "name", direction: "desc" }, "name")).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it("клик по другой колонке начинает с возрастания", () => {
|
||||||
|
expect(nextSort({ id: "name", direction: "desc" }, "age")).toEqual({ id: "age", direction: "asc" })
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe("sortRows", () => {
|
||||||
|
it("сортирует копию и без сортировки сохраняет порядок", () => {
|
||||||
|
expect(sortRows(rows, columns, { id: "name", direction: "asc" }).map((row) => row.name)).toEqual(["Анна", "Борис"])
|
||||||
|
expect(sortRows(rows, columns, { id: "age", direction: "desc" }).map((row) => row.age)).toEqual([40, 30])
|
||||||
|
expect(sortRows(rows, columns, null)).toEqual(rows)
|
||||||
|
expect(sortRows(rows, columns, null)).not.toBe(rows)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
@ -57,7 +57,8 @@ export function nextSort(current: SortState | null, id: string): SortState | nul
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Таблица кита: липкая шапка, сортировка по клику на заголовок,
|
* Таблица кита: липкая шапка, сортировка по клику на заголовок,
|
||||||
* кликабельные строки. Строки передаются уже отсортированными/порезанными
|
* кликабельные строки (мышь, Tab, Enter и пробел; кнопка и ссылка внутри строки не открывают её).
|
||||||
|
* Строки передаются уже отсортированными/порезанными
|
||||||
* (см. sortRows) — так таблица одинаково работает с пагинацией и без неё.
|
* (см. sortRows) — так таблица одинаково работает с пагинацией и без неё.
|
||||||
* `empty` — строка (станет EmptyState) или свой EmptyState; `loading` без строк — скелетоны;
|
* `empty` — строка (станет EmptyState) или свой EmptyState; `loading` без строк — скелетоны;
|
||||||
* Ширина считается по контейнеру, а не по окну: колонки с `minWidth` прячутся, когда места мало,
|
* Ширина считается по контейнеру, а не по окну: колонки с `minWidth` прячутся, когда места мало,
|
||||||
|
|
@ -71,6 +72,38 @@ export function nextSort(current: SortState | null, id: string): SortState | nul
|
||||||
const rowLine =
|
const rowLine =
|
||||||
"border-b border-border/60 last:border-b-0 last:*:shadow-[0_1px_0_color-mix(in_oklab,var(--border)_60%,transparent)]"
|
"border-b border-border/60 last:border-b-0 last:*:shadow-[0_1px_0_color-mix(in_oklab,var(--border)_60%,transparent)]"
|
||||||
|
|
||||||
|
/** Клик или клавиша пришли из кнопки, ссылки или поля внутри строки — строку не открываем. */
|
||||||
|
const nestedControl = "a, button, input, textarea, select, [role='button'], [role='link'], [role='checkbox'], [role='menuitem']"
|
||||||
|
|
||||||
|
function isNestedControl(event: React.SyntheticEvent) {
|
||||||
|
const target = event.target
|
||||||
|
if (!(target instanceof Element) || target === event.currentTarget) return false
|
||||||
|
return Boolean(target.closest(nestedControl))
|
||||||
|
}
|
||||||
|
|
||||||
|
function rowActivate<T>(
|
||||||
|
row: T,
|
||||||
|
onRowClick: ((row: T, event: React.MouseEvent | React.KeyboardEvent) => void) | undefined,
|
||||||
|
extra: React.HTMLAttributes<HTMLElement> | undefined,
|
||||||
|
) {
|
||||||
|
if (!onRowClick) return {}
|
||||||
|
return {
|
||||||
|
tabIndex: extra?.tabIndex ?? 0,
|
||||||
|
onClick: (event: React.MouseEvent<HTMLElement>) => {
|
||||||
|
extra?.onClick?.(event)
|
||||||
|
if (event.defaultPrevented || isNestedControl(event)) return
|
||||||
|
onRowClick(row, event)
|
||||||
|
},
|
||||||
|
onKeyDown: (event: React.KeyboardEvent<HTMLElement>) => {
|
||||||
|
extra?.onKeyDown?.(event)
|
||||||
|
if (event.defaultPrevented || isNestedControl(event)) return
|
||||||
|
if (event.key !== "Enter" && event.key !== " ") return
|
||||||
|
event.preventDefault()
|
||||||
|
onRowClick(row, event)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export function DataTable<T>({
|
export function DataTable<T>({
|
||||||
columns,
|
columns,
|
||||||
rows,
|
rows,
|
||||||
|
|
@ -91,7 +124,7 @@ export function DataTable<T>({
|
||||||
getRowId: (row: T) => React.Key
|
getRowId: (row: T) => React.Key
|
||||||
sort?: SortState | null
|
sort?: SortState | null
|
||||||
onSortChange?: (sort: SortState | null) => void
|
onSortChange?: (sort: SortState | null) => void
|
||||||
onRowClick?: (row: T, event: React.MouseEvent) => void
|
onRowClick?: (row: T, event: React.MouseEvent | React.KeyboardEvent) => void
|
||||||
rowProps?: (row: T, index: number) => React.HTMLAttributes<HTMLTableRowElement>
|
rowProps?: (row: T, index: number) => React.HTMLAttributes<HTMLTableRowElement>
|
||||||
rowClassName?: (row: T, index: number) => string | false | undefined
|
rowClassName?: (row: T, index: number) => string | false | undefined
|
||||||
empty?: React.ReactNode
|
empty?: React.ReactNode
|
||||||
|
|
@ -129,10 +162,10 @@ export function DataTable<T>({
|
||||||
return (
|
return (
|
||||||
<li
|
<li
|
||||||
key={getRowId(row)}
|
key={getRowId(row)}
|
||||||
onClick={onRowClick ? (e) => onRowClick(row, e) : undefined}
|
{...rowActivate(row, onRowClick, extra)}
|
||||||
className={cn(
|
className={cn(
|
||||||
"px-4 py-3 transition-colors",
|
"px-4 py-3 transition-colors",
|
||||||
onRowClick && "cursor-pointer active:bg-muted/60",
|
onRowClick && "cursor-pointer active:bg-muted/60 focus-visible:bg-muted/60 focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring",
|
||||||
rowClassName?.(row, i),
|
rowClassName?.(row, i),
|
||||||
extra?.className,
|
extra?.className,
|
||||||
)}
|
)}
|
||||||
|
|
@ -194,11 +227,11 @@ export function DataTable<T>({
|
||||||
<tr
|
<tr
|
||||||
key={getRowId(row)}
|
key={getRowId(row)}
|
||||||
{...extra}
|
{...extra}
|
||||||
onClick={onRowClick ? (e) => onRowClick(row, e) : extra?.onClick}
|
{...rowActivate(row, onRowClick, extra)}
|
||||||
className={cn(
|
className={cn(
|
||||||
rowLine,
|
rowLine,
|
||||||
"transition-colors",
|
"transition-colors",
|
||||||
onRowClick && "cursor-pointer hover:bg-muted/50",
|
onRowClick && "cursor-pointer hover:bg-muted/50 focus-visible:bg-muted/50 focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring",
|
||||||
rowClassName?.(row, i),
|
rowClassName?.(row, i),
|
||||||
extra?.className,
|
extra?.className,
|
||||||
)}
|
)}
|
||||||
|
|
|
||||||
|
|
@ -64,6 +64,8 @@ export function DateRangeInput({
|
||||||
className?: string
|
className?: string
|
||||||
}) {
|
}) {
|
||||||
const wide = useMediaQuery("(min-width: 768px)")
|
const wide = useMediaQuery("(min-width: 768px)")
|
||||||
|
// У «по» свой id: иначе оба поля заберут id FormField, и подпись укажет на два элемента сразу.
|
||||||
|
const toId = React.useId()
|
||||||
const limits = { min, max }
|
const limits = { min, max }
|
||||||
const fromField = useDateText(value.from, (from) => onChange({ ...value, from }), limits)
|
const fromField = useDateText(value.from, (from) => onChange({ ...value, from }), limits)
|
||||||
const toField = useDateText(value.to, (to) => onChange({ ...value, to }), limits)
|
const toField = useDateText(value.to, (to) => onChange({ ...value, to }), limits)
|
||||||
|
|
@ -117,6 +119,7 @@ export function DateRangeInput({
|
||||||
/>
|
/>
|
||||||
<InputGroupText className="px-0.5">—</InputGroupText>
|
<InputGroupText className="px-0.5">—</InputGroupText>
|
||||||
<InputGroupInput
|
<InputGroupInput
|
||||||
|
id={toId}
|
||||||
aria-label="По"
|
aria-label="По"
|
||||||
inputMode="numeric"
|
inputMode="numeric"
|
||||||
autoComplete="off"
|
autoComplete="off"
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
import * as React from "react"
|
import * as React from "react"
|
||||||
|
|
||||||
|
import { FormControlProvider, type FormControlState } from "../lib/form-control"
|
||||||
import { cn } from "../lib/utils"
|
import { cn } from "../lib/utils"
|
||||||
import { Label } from "../ui/label"
|
import { Label } from "../ui/label"
|
||||||
|
|
||||||
|
|
@ -13,7 +14,12 @@ export function FormSection({ title, children }: { title: string; children: Reac
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Подпись, поле, подсказка или ошибка под ним. */
|
/**
|
||||||
|
* Подпись, поле, подсказка или ошибка под ним.
|
||||||
|
* Сам выдаёт id поля и id текста под ним: Input, DateInput, TimeInput, SnilsInput, PhoneInput
|
||||||
|
* и SearchInput подхватывают их и ставят aria-invalid / aria-describedby.
|
||||||
|
* htmlFor — когда контрол сам не читает контекст (список, своя кнопка): подпись укажет на его id.
|
||||||
|
*/
|
||||||
export function FormField({
|
export function FormField({
|
||||||
label,
|
label,
|
||||||
htmlFor,
|
htmlFor,
|
||||||
|
|
@ -29,15 +35,26 @@ export function FormField({
|
||||||
className?: string
|
className?: string
|
||||||
children: React.ReactNode
|
children: React.ReactNode
|
||||||
}) {
|
}) {
|
||||||
|
const generatedId = React.useId()
|
||||||
|
const descriptionId = React.useId()
|
||||||
|
const id = htmlFor ?? generatedId
|
||||||
|
const message = error || hint
|
||||||
|
const control = React.useMemo<FormControlState>(
|
||||||
|
() => ({ id, descriptionId: message ? descriptionId : undefined, invalid: Boolean(error) }),
|
||||||
|
[id, descriptionId, message, error],
|
||||||
|
)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
<FormControlProvider value={control}>
|
||||||
<div className={cn("space-y-1.5", className)}>
|
<div className={cn("space-y-1.5", className)}>
|
||||||
<Label htmlFor={htmlFor}>{label}</Label>
|
<Label htmlFor={id}>{label}</Label>
|
||||||
{children}
|
{children}
|
||||||
{error ? (
|
{error ? (
|
||||||
<p className="text-xs text-destructive">{error}</p>
|
<p id={descriptionId} className="text-xs text-destructive">{error}</p>
|
||||||
) : hint ? (
|
) : hint ? (
|
||||||
<p className="text-xs text-muted-foreground">{hint}</p>
|
<p id={descriptionId} className="text-xs text-muted-foreground">{hint}</p>
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
|
</FormControlProvider>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -33,6 +33,7 @@ export * from "./patient-avatar"
|
||||||
export * from "./patient-panel"
|
export * from "./patient-panel"
|
||||||
export * from "./patient-picker"
|
export * from "./patient-picker"
|
||||||
export * from "./person-chip"
|
export * from "./person-chip"
|
||||||
|
export * from "./phone-input"
|
||||||
export * from "./save-bar"
|
export * from "./save-bar"
|
||||||
export * from "./schedule-grid"
|
export * from "./schedule-grid"
|
||||||
export * from "./search-field"
|
export * from "./search-field"
|
||||||
|
|
|
||||||
|
|
@ -135,6 +135,7 @@ export function LoginForm({
|
||||||
setError(undefined)
|
setError(undefined)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const errorId = React.useId()
|
||||||
const spinner = <Loader2Icon className="animate-spin" />
|
const spinner = <Loader2Icon className="animate-spin" />
|
||||||
|
|
||||||
if (challenge) {
|
if (challenge) {
|
||||||
|
|
@ -184,7 +185,11 @@ export function LoginForm({
|
||||||
</InputOTPGroup>
|
</InputOTPGroup>
|
||||||
</InputOTP>
|
</InputOTP>
|
||||||
|
|
||||||
{error && <p className="text-center text-sm text-destructive">{error}</p>}
|
{error && (
|
||||||
|
<p id={errorId} role="alert" className="text-center text-sm text-destructive">
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
<Button type="submit" size="lg" className="w-full" disabled={busy || code.length < otpLength}>
|
<Button type="submit" size="lg" className="w-full" disabled={busy || code.length < otpLength}>
|
||||||
{pending === "otp" && spinner} Подтвердить
|
{pending === "otp" && spinner} Подтвердить
|
||||||
|
|
@ -222,9 +227,8 @@ export function LoginForm({
|
||||||
void submitLogin()
|
void submitLogin()
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<FormField label="Логин" htmlFor="login-form-login">
|
<FormField label="Логин">
|
||||||
<Input
|
<Input
|
||||||
id="login-form-login"
|
|
||||||
autoComplete="username"
|
autoComplete="username"
|
||||||
autoFocus={autoFocus && !defaultLogin}
|
autoFocus={autoFocus && !defaultLogin}
|
||||||
value={login}
|
value={login}
|
||||||
|
|
@ -232,18 +236,15 @@ export function LoginForm({
|
||||||
setLogin(e.target.value)
|
setLogin(e.target.value)
|
||||||
setError(undefined)
|
setError(undefined)
|
||||||
}}
|
}}
|
||||||
|
aria-invalid={Boolean(error)}
|
||||||
|
aria-describedby={error ? errorId : undefined}
|
||||||
disabled={busy}
|
disabled={busy}
|
||||||
/>
|
/>
|
||||||
</FormField>
|
</FormField>
|
||||||
|
|
||||||
<FormField
|
<FormField label="Пароль" hint={capsLock ? "Включён Caps Lock" : undefined}>
|
||||||
label="Пароль"
|
|
||||||
htmlFor="login-form-password"
|
|
||||||
hint={capsLock ? "Включён Caps Lock" : undefined}
|
|
||||||
>
|
|
||||||
<InputGroup data-disabled={busy || undefined}>
|
<InputGroup data-disabled={busy || undefined}>
|
||||||
<InputGroupInput
|
<InputGroupInput
|
||||||
id="login-form-password"
|
|
||||||
type={showPassword ? "text" : "password"}
|
type={showPassword ? "text" : "password"}
|
||||||
autoComplete="current-password"
|
autoComplete="current-password"
|
||||||
autoFocus={autoFocus && Boolean(defaultLogin)}
|
autoFocus={autoFocus && Boolean(defaultLogin)}
|
||||||
|
|
@ -256,6 +257,7 @@ export function LoginForm({
|
||||||
onKeyUp={(e) => setCapsLock(e.getModifierState("CapsLock"))}
|
onKeyUp={(e) => setCapsLock(e.getModifierState("CapsLock"))}
|
||||||
onBlur={() => setCapsLock(false)}
|
onBlur={() => setCapsLock(false)}
|
||||||
aria-invalid={Boolean(error)}
|
aria-invalid={Boolean(error)}
|
||||||
|
aria-describedby={error ? errorId : undefined}
|
||||||
disabled={busy}
|
disabled={busy}
|
||||||
/>
|
/>
|
||||||
<InputGroupAddon align="inline-end">
|
<InputGroupAddon align="inline-end">
|
||||||
|
|
@ -271,7 +273,11 @@ export function LoginForm({
|
||||||
</InputGroup>
|
</InputGroup>
|
||||||
</FormField>
|
</FormField>
|
||||||
|
|
||||||
{error && <p className="text-sm text-destructive">{error}</p>}
|
{error && (
|
||||||
|
<p id={errorId} role="alert" className="text-sm text-destructive">
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
<Button type="submit" size="lg" className="w-full" disabled={busy || !login.trim() || !password}>
|
<Button type="submit" size="lg" className="w-full" disabled={busy || !login.trim() || !password}>
|
||||||
{pending === "login" && spinner} Войти
|
{pending === "login" && spinner} Войти
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,42 @@
|
||||||
|
import * as React from "react"
|
||||||
|
|
||||||
|
import { InputGroup, InputGroupAddon, InputGroupInput } from "../ui/input-group"
|
||||||
|
import { maskPhone, maskWithCaret } from "../lib/masks"
|
||||||
|
import { useCaret } from "../hooks/use-caret"
|
||||||
|
import { cn } from "../lib/utils"
|
||||||
|
|
||||||
|
/** Мобильный телефон: префикс +7 и маска «(000) 000-00-00». Правка в середине не сдвигает курсор в конец. */
|
||||||
|
export function PhoneInput({
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
invalid,
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: Omit<React.ComponentProps<"input">, "value" | "onChange"> & {
|
||||||
|
value: string
|
||||||
|
onChange: (value: string) => void
|
||||||
|
invalid?: boolean
|
||||||
|
}) {
|
||||||
|
const setCaret = useCaret()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<InputGroup className={cn("w-full", className)}>
|
||||||
|
<InputGroupAddon className="tabular">+7</InputGroupAddon>
|
||||||
|
<InputGroupInput
|
||||||
|
type="tel"
|
||||||
|
inputMode="tel"
|
||||||
|
autoComplete="tel"
|
||||||
|
placeholder="(000) 000-00-00"
|
||||||
|
{...props}
|
||||||
|
value={value}
|
||||||
|
aria-invalid={invalid}
|
||||||
|
onChange={(e) => {
|
||||||
|
const next = maskWithCaret(e.target, (e.nativeEvent as InputEvent).inputType, value, maskPhone)
|
||||||
|
onChange(next.value)
|
||||||
|
setCaret(e.target, next.caret)
|
||||||
|
}}
|
||||||
|
className="tabular"
|
||||||
|
/>
|
||||||
|
</InputGroup>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -4,6 +4,7 @@ import { PlusIcon } from "lucide-react"
|
||||||
import { cn } from "../lib/utils"
|
import { cn } from "../lib/utils"
|
||||||
import { ScrollArea } from "../ui/scroll-area"
|
import { ScrollArea } from "../ui/scroll-area"
|
||||||
import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip"
|
import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip"
|
||||||
|
import { layoutLanes, minutes } from "./schedule-lanes"
|
||||||
import type { StatusTone } from "./status-badge"
|
import type { StatusTone } from "./status-badge"
|
||||||
|
|
||||||
/** Время «ЧЧ:ММ». */
|
/** Время «ЧЧ:ММ». */
|
||||||
|
|
@ -41,36 +42,6 @@ const toneClass: Record<StatusTone, string> = {
|
||||||
neutral: "border-l-muted-foreground/50 bg-muted",
|
neutral: "border-l-muted-foreground/50 bg-muted",
|
||||||
}
|
}
|
||||||
|
|
||||||
const minutes = (t: Clock) => Number(t.slice(0, 2)) * 60 + Number(t.slice(3, 5))
|
|
||||||
|
|
||||||
/** Раскладка пересекающихся записей одного врача по дорожкам: `lane` из `lanes`. */
|
|
||||||
function layoutLanes(events: readonly ScheduleGridEvent[]) {
|
|
||||||
const sorted = events.toSorted((a, b) => minutes(a.start) - minutes(b.start) || minutes(b.end) - minutes(a.end))
|
|
||||||
const result = new Map<React.Key, { lane: number; lanes: number }>()
|
|
||||||
let cluster: ScheduleGridEvent[] = []
|
|
||||||
let laneEnds: number[] = []
|
|
||||||
let clusterEnd = -1
|
|
||||||
|
|
||||||
const flush = () => {
|
|
||||||
for (const e of cluster) result.set(e.id, { lane: result.get(e.id)!.lane, lanes: laneEnds.length })
|
|
||||||
cluster = []
|
|
||||||
laneEnds = []
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const e of sorted) {
|
|
||||||
const start = minutes(e.start)
|
|
||||||
if (start >= clusterEnd) flush()
|
|
||||||
let lane = laneEnds.findIndex((end) => end <= start)
|
|
||||||
if (lane < 0) lane = laneEnds.push(0) - 1
|
|
||||||
laneEnds[lane] = minutes(e.end)
|
|
||||||
clusterEnd = Math.max(clusterEnd, minutes(e.end))
|
|
||||||
cluster.push(e)
|
|
||||||
result.set(e.id, { lane, lanes: 0 })
|
|
||||||
}
|
|
||||||
flush()
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Границы сетки: от первого рабочего часа/записи до последнего, с округлением до часа. */
|
/** Границы сетки: от первого рабочего часа/записи до последнего, с округлением до часа. */
|
||||||
function gridBounds(resources: readonly ScheduleGridResource[], events: readonly ScheduleGridEvent[]) {
|
function gridBounds(resources: readonly ScheduleGridResource[], events: readonly ScheduleGridEvent[]) {
|
||||||
const starts = [...resources.flatMap((r) => r.hours?.map((h) => minutes(h.from)) ?? []), ...events.map((e) => minutes(e.start))]
|
const starts = [...resources.flatMap((r) => r.hours?.map((h) => minutes(h.from)) ?? []), ...events.map((e) => minutes(e.start))]
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,35 @@
|
||||||
|
import { describe, expect, it } from "vitest"
|
||||||
|
|
||||||
|
import { layoutLanes, type LaneEvent } from "./schedule-lanes"
|
||||||
|
|
||||||
|
function lanes(events: readonly LaneEvent[]) {
|
||||||
|
return Object.fromEntries([...layoutLanes(events)].map(([id, lane]) => [id, lane]))
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("layoutLanes", () => {
|
||||||
|
it("ставит непересекающиеся записи в одну дорожку, каждую своим кластером", () => {
|
||||||
|
expect(
|
||||||
|
lanes([
|
||||||
|
{ id: 1, start: "09:00", end: "10:00" },
|
||||||
|
{ id: 2, start: "10:00", end: "11:00" },
|
||||||
|
]),
|
||||||
|
).toEqual({
|
||||||
|
1: { lane: 0, lanes: 1 },
|
||||||
|
2: { lane: 0, lanes: 1 },
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it("кладёт пересечение рядом и возвращает освободившуюся дорожку следующей записи", () => {
|
||||||
|
expect(
|
||||||
|
lanes([
|
||||||
|
{ id: "a", start: "09:00", end: "10:00" },
|
||||||
|
{ id: "b", start: "09:30", end: "11:00" },
|
||||||
|
{ id: "c", start: "10:00", end: "10:30" },
|
||||||
|
]),
|
||||||
|
).toEqual({
|
||||||
|
a: { lane: 0, lanes: 2 },
|
||||||
|
b: { lane: 1, lanes: 2 },
|
||||||
|
c: { lane: 0, lanes: 2 },
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
@ -0,0 +1,40 @@
|
||||||
|
import type { Key } from "react"
|
||||||
|
|
||||||
|
/** «ЧЧ:ММ» → минуты от полуночи. */
|
||||||
|
export function minutes(t: string) {
|
||||||
|
return Number(t.slice(0, 2)) * 60 + Number(t.slice(3, 5))
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LaneEvent {
|
||||||
|
readonly id: Key
|
||||||
|
readonly start: string
|
||||||
|
readonly end: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Раскладка пересекающихся записей одного врача по дорожкам: `lane` из `lanes`. */
|
||||||
|
export function layoutLanes(events: readonly LaneEvent[]) {
|
||||||
|
const sorted = events.toSorted((a, b) => minutes(a.start) - minutes(b.start) || minutes(b.end) - minutes(a.end))
|
||||||
|
const result = new Map<Key, { lane: number; lanes: number }>()
|
||||||
|
let cluster: LaneEvent[] = []
|
||||||
|
let laneEnds: number[] = []
|
||||||
|
let clusterEnd = -1
|
||||||
|
|
||||||
|
const flush = () => {
|
||||||
|
for (const e of cluster) result.set(e.id, { lane: result.get(e.id)!.lane, lanes: laneEnds.length })
|
||||||
|
cluster = []
|
||||||
|
laneEnds = []
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const e of sorted) {
|
||||||
|
const start = minutes(e.start)
|
||||||
|
if (start >= clusterEnd) flush()
|
||||||
|
let lane = laneEnds.findIndex((end) => end <= start)
|
||||||
|
if (lane < 0) lane = laneEnds.push(0) - 1
|
||||||
|
laneEnds[lane] = minutes(e.end)
|
||||||
|
clusterEnd = Math.max(clusterEnd, minutes(e.end))
|
||||||
|
cluster.push(e)
|
||||||
|
result.set(e.id, { lane, lanes: 0 })
|
||||||
|
}
|
||||||
|
flush()
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
import * as React from "react"
|
import * as React from "react"
|
||||||
import { SearchIcon, XIcon } from "lucide-react"
|
import { SearchIcon, XIcon } from "lucide-react"
|
||||||
|
|
||||||
|
import { useFormControl } from "../lib/form-control"
|
||||||
import { cn } from "../lib/utils"
|
import { cn } from "../lib/utils"
|
||||||
|
|
||||||
/** Поле поиска: иконка, крестик очистки. */
|
/** Поле поиска: иконка, крестик очистки. */
|
||||||
|
|
@ -13,7 +14,11 @@ export const SearchInput = React.forwardRef<
|
||||||
/** Что показать справа, пока поле пустое (подсказка клавиши). */
|
/** Что показать справа, пока поле пустое (подсказка клавиши). */
|
||||||
trailing?: React.ReactNode
|
trailing?: React.ReactNode
|
||||||
}
|
}
|
||||||
>(function SearchInput({ value, onValueChange, size = "md", trailing, className, onKeyDown, ...props }, ref) {
|
>(function SearchInput(
|
||||||
|
{ value, onValueChange, size = "md", trailing, className, onKeyDown, id, "aria-describedby": ariaDescribedBy, "aria-invalid": ariaInvalid, ...props },
|
||||||
|
ref,
|
||||||
|
) {
|
||||||
|
const field = useFormControl({ id, "aria-describedby": ariaDescribedBy, "aria-invalid": ariaInvalid })
|
||||||
const innerRef = React.useRef<HTMLInputElement>(null)
|
const innerRef = React.useRef<HTMLInputElement>(null)
|
||||||
React.useImperativeHandle(ref, () => innerRef.current!)
|
React.useImperativeHandle(ref, () => innerRef.current!)
|
||||||
|
|
||||||
|
|
@ -37,15 +42,19 @@ export const SearchInput = React.forwardRef<
|
||||||
}
|
}
|
||||||
onKeyDown?.(e)
|
onKeyDown?.(e)
|
||||||
}}
|
}}
|
||||||
|
{...props}
|
||||||
|
id={field.id}
|
||||||
|
aria-describedby={field["aria-describedby"]}
|
||||||
|
aria-invalid={field["aria-invalid"]}
|
||||||
className={cn(
|
className={cn(
|
||||||
// как Input: рамка на белом, та же подсветка фокуса — в строке фильтров стоит рядом с Select
|
// как Input: рамка на белом, та же подсветка фокуса — в строке фильтров стоит рядом с Select
|
||||||
"w-full min-w-0 rounded-md border border-input bg-transparent shadow-xs transition-[color,box-shadow] outline-none placeholder:text-muted-foreground dark:bg-input/30 [&::-webkit-search-cancel-button]:hidden",
|
"w-full min-w-0 rounded-md border border-input bg-transparent shadow-xs transition-[color,box-shadow] outline-none placeholder:text-muted-foreground dark:bg-input/30 [&::-webkit-search-cancel-button]:hidden",
|
||||||
"focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50",
|
"focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50",
|
||||||
|
"aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",
|
||||||
size === "sm" && "h-8 pr-8 pl-9 text-sm",
|
size === "sm" && "h-8 pr-8 pl-9 text-sm",
|
||||||
size === "md" && "h-9 pr-8 pl-9 text-sm",
|
size === "md" && "h-9 pr-8 pl-9 text-sm",
|
||||||
size === "lg" && "h-12 rounded-xl pr-12 pl-12 text-base",
|
size === "lg" && "h-12 rounded-xl pr-12 pl-12 text-base",
|
||||||
)}
|
)}
|
||||||
{...props}
|
|
||||||
/>
|
/>
|
||||||
<div className="absolute top-1/2 right-2 flex -translate-y-1/2 items-center">
|
<div className="absolute top-1/2 right-2 flex -translate-y-1/2 items-center">
|
||||||
{value ? (
|
{value ? (
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,46 @@
|
||||||
|
import * as React from "react"
|
||||||
|
|
||||||
|
/** Идентификаторы поля, которые FormField отдаёт вложенному контролу. */
|
||||||
|
export interface FormControlState {
|
||||||
|
readonly id: string
|
||||||
|
/** Есть, только когда под полем виден текст подсказки или ошибки. */
|
||||||
|
readonly descriptionId?: string
|
||||||
|
readonly invalid: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
const FormControlContext = React.createContext<FormControlState | null>(null)
|
||||||
|
|
||||||
|
export function FormControlProvider({ value, children }: { value: FormControlState; children: React.ReactNode }) {
|
||||||
|
return React.createElement(FormControlContext.Provider, { value }, children)
|
||||||
|
}
|
||||||
|
|
||||||
|
type AriaInvalid = React.AriaAttributes["aria-invalid"]
|
||||||
|
|
||||||
|
interface ControlProps {
|
||||||
|
id?: string
|
||||||
|
"aria-describedby"?: string
|
||||||
|
"aria-invalid"?: AriaInvalid
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Подмешивает id, aria-describedby и aria-invalid из FormField.
|
||||||
|
* Свой id у контрола важнее: так второе поле диапазона не забирает id первого.
|
||||||
|
* Вне FormField пропсы возвращаются как есть.
|
||||||
|
*/
|
||||||
|
export function useFormControl(props: ControlProps): ControlProps {
|
||||||
|
const field = React.useContext(FormControlContext)
|
||||||
|
if (!field) return props
|
||||||
|
const describedBy = [field.descriptionId, props["aria-describedby"]].filter(Boolean).join(" ") || undefined
|
||||||
|
return {
|
||||||
|
...props,
|
||||||
|
id: props.id ?? field.id,
|
||||||
|
"aria-describedby": describedBy,
|
||||||
|
"aria-invalid": mergeInvalid(props["aria-invalid"], field.invalid),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function mergeInvalid(own: AriaInvalid, fieldInvalid: boolean): AriaInvalid {
|
||||||
|
if (own === true || own === "true" || fieldInvalid) return true
|
||||||
|
if (own === "grammar" || own === "spelling") return own
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,78 @@
|
||||||
|
import { describe, expect, it } from "vitest"
|
||||||
|
|
||||||
|
import {
|
||||||
|
isDatePrefixValid,
|
||||||
|
isSnilsValid,
|
||||||
|
maskDate,
|
||||||
|
maskPhone,
|
||||||
|
maskSnils,
|
||||||
|
maskWithCaret,
|
||||||
|
parseRuDate,
|
||||||
|
} from "./masks"
|
||||||
|
|
||||||
|
function field(value: string, caret: number) {
|
||||||
|
return { value, selectionStart: caret } as HTMLInputElement
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("maskPhone", () => {
|
||||||
|
it("форматирует 10 цифр и отбрасывает 7 или 8 в начале", () => {
|
||||||
|
expect(maskPhone("9141231212")).toBe("(914) 123-12-12")
|
||||||
|
expect(maskPhone("+7 (914) 123-12-12")).toBe("(914) 123-12-12")
|
||||||
|
expect(maskPhone("89141231212")).toBe("(914) 123-12-12")
|
||||||
|
})
|
||||||
|
|
||||||
|
it("не добивает номер нулями", () => {
|
||||||
|
expect(maskPhone("914")).toBe("(914")
|
||||||
|
expect(maskPhone("")).toBe("")
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe("maskSnils / isSnilsValid", () => {
|
||||||
|
it("ставит дефисы и пробел", () => {
|
||||||
|
expect(maskSnils("11223344595")).toBe("112-233-445 95")
|
||||||
|
})
|
||||||
|
|
||||||
|
it("проверяет контрольное число и не ругает короткий номер как неверный формат длины 11", () => {
|
||||||
|
expect(isSnilsValid("112-233-445 95")).toBe(true)
|
||||||
|
expect(isSnilsValid("112-233-445 96")).toBe(false)
|
||||||
|
expect(isSnilsValid("112-233-445")).toBe(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe("isDatePrefixValid / parseRuDate", () => {
|
||||||
|
it("пускает недописанную дату и отвергает невозможную", () => {
|
||||||
|
expect(isDatePrefixValid("3")).toBe(true)
|
||||||
|
expect(isDatePrefixValid("31.1")).toBe(true)
|
||||||
|
expect(isDatePrefixValid("29.02.2024")).toBe(true)
|
||||||
|
expect(isDatePrefixValid("40")).toBe(false)
|
||||||
|
expect(isDatePrefixValid("31.04")).toBe(false)
|
||||||
|
expect(isDatePrefixValid("12.13")).toBe(false)
|
||||||
|
expect(isDatePrefixValid("29.02.2023")).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it("разбирает только существующую полную дату", () => {
|
||||||
|
const date = parseRuDate("17.05.1984")
|
||||||
|
expect(date).toEqual(new Date(1984, 4, 17))
|
||||||
|
expect(parseRuDate("29.02.2024")).toEqual(new Date(2024, 1, 29))
|
||||||
|
expect(parseRuDate("29.02.2023")).toBeNull()
|
||||||
|
expect(parseRuDate("31.04.2024")).toBeNull()
|
||||||
|
expect(parseRuDate("17.05")).toBeNull()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe("maskWithCaret", () => {
|
||||||
|
it("оставляет курсор после вставленной цифры, а не в конце номера", () => {
|
||||||
|
const next = maskWithCaret(field("(914) 912", 7), "insertText", "(914) 12", maskPhone)
|
||||||
|
expect(next).toEqual({ value: "(914) 912", caret: 7 })
|
||||||
|
})
|
||||||
|
|
||||||
|
it("при удалении разделителя стирает соседнюю цифру", () => {
|
||||||
|
const next = maskWithCaret(field("1205", 2), "deleteContentBackward", "12.05", maskDate)
|
||||||
|
expect(next).toEqual({ value: "10.05", caret: 1 })
|
||||||
|
})
|
||||||
|
|
||||||
|
it("не вставляет цифру, из которой не получится дата", () => {
|
||||||
|
const next = maskWithCaret(field("32", 2), "insertText", "3", (value) => value.replace(/\D/g, "").slice(0, 2), isDatePrefixValid)
|
||||||
|
expect(next).toEqual({ value: "3", caret: 1 })
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
@ -1,10 +1,23 @@
|
||||||
import * as React from "react"
|
import * as React from "react"
|
||||||
|
import { useFormControl } from "../lib/form-control"
|
||||||
import { cn } from "../lib/utils"
|
import { cn } from "../lib/utils"
|
||||||
|
|
||||||
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
function Input({
|
||||||
|
className,
|
||||||
|
type,
|
||||||
|
id,
|
||||||
|
"aria-describedby": ariaDescribedBy,
|
||||||
|
"aria-invalid": ariaInvalid,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"input">) {
|
||||||
|
const field = useFormControl({ id, "aria-describedby": ariaDescribedBy, "aria-invalid": ariaInvalid })
|
||||||
return (
|
return (
|
||||||
<input
|
<input
|
||||||
|
{...props}
|
||||||
type={type}
|
type={type}
|
||||||
|
id={field.id}
|
||||||
|
aria-describedby={field["aria-describedby"]}
|
||||||
|
aria-invalid={field["aria-invalid"]}
|
||||||
data-slot="input"
|
data-slot="input"
|
||||||
className={cn(
|
className={cn(
|
||||||
"h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30",
|
"h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30",
|
||||||
|
|
@ -12,7 +25,6 @@ function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||||
"aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",
|
"aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
{...props}
|
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,15 +1,26 @@
|
||||||
import * as React from "react"
|
import * as React from "react"
|
||||||
|
import { useFormControl } from "../lib/form-control"
|
||||||
import { cn } from "../lib/utils"
|
import { cn } from "../lib/utils"
|
||||||
|
|
||||||
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
|
function Textarea({
|
||||||
|
className,
|
||||||
|
id,
|
||||||
|
"aria-describedby": ariaDescribedBy,
|
||||||
|
"aria-invalid": ariaInvalid,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"textarea">) {
|
||||||
|
const field = useFormControl({ id, "aria-describedby": ariaDescribedBy, "aria-invalid": ariaInvalid })
|
||||||
return (
|
return (
|
||||||
<textarea
|
<textarea
|
||||||
|
{...props}
|
||||||
|
id={field.id}
|
||||||
|
aria-describedby={field["aria-describedby"]}
|
||||||
|
aria-invalid={field["aria-invalid"]}
|
||||||
data-slot="textarea"
|
data-slot="textarea"
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex field-sizing-content min-h-16 w-full rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:aria-invalid:ring-destructive/40",
|
"flex field-sizing-content min-h-16 w-full rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:aria-invalid:ring-destructive/40",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
{...props}
|
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,8 @@
|
||||||
|
import { defineConfig } from "vitest/config"
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
environment: "node",
|
||||||
|
include: ["src/**/*.test.ts"],
|
||||||
|
},
|
||||||
|
})
|
||||||
Loading…
Reference in New Issue