61 lines
2.0 KiB
TypeScript
61 lines
2.0 KiB
TypeScript
import * as React from "react"
|
||
|
||
import { FormControlProvider, type FormControlState } from "../lib/form-control"
|
||
import { cn } from "../lib/utils"
|
||
import { Label } from "../ui/label"
|
||
|
||
/** Подзаголовок группы полей формы. */
|
||
export function FormSection({ title, children }: { title: string; children: React.ReactNode }) {
|
||
return (
|
||
<section className="space-y-4">
|
||
<h2 className="text-xs font-semibold tracking-[0.12em] text-muted-foreground uppercase">{title}</h2>
|
||
{children}
|
||
</section>
|
||
)
|
||
}
|
||
|
||
/**
|
||
* Подпись, поле, подсказка или ошибка под ним.
|
||
* Сам выдаёт id поля и id текста под ним: Input, DateInput, TimeInput, SnilsInput, PhoneInput
|
||
* и SearchInput подхватывают их и ставят aria-invalid / aria-describedby.
|
||
* htmlFor — когда контрол сам не читает контекст (список, своя кнопка): подпись укажет на его id.
|
||
*/
|
||
export function FormField({
|
||
label,
|
||
htmlFor,
|
||
hint,
|
||
error,
|
||
className,
|
||
children,
|
||
}: {
|
||
label: string
|
||
htmlFor?: string
|
||
hint?: string
|
||
error?: string
|
||
className?: string
|
||
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 (
|
||
<FormControlProvider value={control}>
|
||
<div className={cn("space-y-1.5", className)}>
|
||
<Label htmlFor={id}>{label}</Label>
|
||
{children}
|
||
{error ? (
|
||
<p id={descriptionId} className="text-xs text-destructive">{error}</p>
|
||
) : hint ? (
|
||
<p id={descriptionId} className="text-xs text-muted-foreground">{hint}</p>
|
||
) : null}
|
||
</div>
|
||
</FormControlProvider>
|
||
)
|
||
}
|