medkit/src/lib/form-control.ts

47 lines
1.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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
}