@lt-ui/form 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cjs/context.js ADDED
@@ -0,0 +1,11 @@
1
+ 'use client';
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.useFormOptions = exports.FormOptionsProvider = void 0;
5
+ const react_1 = require("react");
6
+ const FormOptionsContext = (0, react_1.createContext)({});
7
+ // React 19 — `<Context value>`, React 18 — `<Context.Provider>`
8
+ exports.FormOptionsProvider = Number.parseInt(react_1.version, 10) >= 19 ? FormOptionsContext : FormOptionsContext.Provider;
9
+ /** Настройки ближайшей `Form`: общие `disabled` и `size` для полей */
10
+ const useFormOptions = () => (0, react_1.useContext)(FormOptionsContext);
11
+ exports.useFormOptions = useFormOptions;
@@ -0,0 +1,59 @@
1
+ 'use client';
2
+ "use strict";
3
+ var __importDefault = (this && this.__importDefault) || function (mod) {
4
+ return (mod && mod.__esModule) ? mod : { "default": mod };
5
+ };
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.createFormField = createFormField;
8
+ const react_1 = __importDefault(require("react"));
9
+ const react_hook_form_1 = require("react-hook-form");
10
+ const context_1 = require("./context");
11
+ // Ошибка валидации перекрывает `status` и `caption`, заданные вручную; без ошибки они остаются как есть
12
+ const mapErrorToCaption = (message) => message ? { status: 'error', caption: message } : {};
13
+ /**
14
+ * Превращает компонент с парой «значение + событие» (`value` + `onUpdate`, `checked` + `onUpdate`...) в поле формы
15
+ * react-hook-form. Значение, `onBlur`, `ref` (фокус на первую ошибку при отправке), ошибка и `disabled` формы
16
+ * подключаются сами; остальные свойства компонента работают как обычно.
17
+ *
18
+ * @example
19
+ * const FormStars = createFormField(MyStars, { empty: 0 });
20
+ * <FormStars name="rating" rules={{ min: { value: 1, message: 'Поставьте оценку' } }} />
21
+ */
22
+ function createFormField(Component, options = {}) {
23
+ var _a, _b;
24
+ const { valueProp = 'value', changeProp = 'onUpdate', empty, getValue, mapError = mapErrorToCaption, inherit = ['disabled'], ref: withRef = true, displayName, } = options;
25
+ function Field(props) {
26
+ var _a, _b;
27
+ const { name, control, rules, defaultValue, shouldUnregister, ...rest } = props;
28
+ const { field, fieldState } = (0, react_hook_form_1.useController)({ name, control, rules, defaultValue, shouldUnregister });
29
+ const formOptions = (0, context_1.useFormOptions)();
30
+ const inherited = {};
31
+ if (inherit.includes('disabled') && formOptions.disabled !== undefined)
32
+ inherited.disabled = formOptions.disabled;
33
+ if (inherit.includes('size') && formOptions.size !== undefined)
34
+ inherited.size = formOptions.size;
35
+ if (inherit.includes('fullWidth') && formOptions.fullWidth !== undefined)
36
+ inherited.fullWidth = formOptions.fullWidth;
37
+ const componentProps = {
38
+ ...inherited,
39
+ ...rest,
40
+ ...mapError((_a = fieldState.error) === null || _a === void 0 ? void 0 : _a.message, rest),
41
+ name: field.name,
42
+ [valueProp]: (_b = field.value) !== null && _b !== void 0 ? _b : empty,
43
+ [changeProp]: (...args) => {
44
+ var _a;
45
+ field.onChange(getValue ? getValue(...args) : args[0]);
46
+ (_a = rest[changeProp]) === null || _a === void 0 ? void 0 : _a.call(rest, ...args);
47
+ },
48
+ onBlur: (...args) => {
49
+ var _a;
50
+ field.onBlur();
51
+ (_a = rest.onBlur) === null || _a === void 0 ? void 0 : _a.call(rest, ...args);
52
+ },
53
+ ...(withRef ? { ref: field.ref } : {}),
54
+ };
55
+ return react_1.default.createElement(Component, componentProps);
56
+ }
57
+ Field.displayName = displayName !== null && displayName !== void 0 ? displayName : `Form(${(_b = (_a = Component.displayName) !== null && _a !== void 0 ? _a : Component.name) !== null && _b !== void 0 ? _b : 'Field'})`;
58
+ return Field;
59
+ }
package/cjs/fields.js ADDED
@@ -0,0 +1,75 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FormFileUpload = exports.FormCalendar = exports.FormAutocomplete = exports.FormSwitch = exports.FormCheckbox = exports.FormSegmentedControl = exports.FormRadioGroup = exports.FormTreeSelect = exports.FormTimePicker = exports.FormDatePicker = exports.FormSelect = exports.FormQuantityInput = exports.FormNumberInput = exports.FormPinInput = exports.FormMaskedInput = exports.FormTextarea = exports.FormInput = void 0;
4
+ const uikit_1 = require("@lt-ui/uikit");
5
+ const create_form_field_1 = require("./create-form-field");
6
+ // Компоненты без состояния ошибки: свойства `error` и `caption` в DOM не отдаём
7
+ const noError = () => ({});
8
+ const text = { empty: '', inherit: ['disabled', 'size', 'fullWidth'] };
9
+ const nullable = { empty: null, inherit: ['disabled', 'size', 'fullWidth'] };
10
+ // Счётчик и ячейки кода не растягиваются, пропса `fullWidth` у них нет
11
+ const compact = { inherit: ['disabled', 'size'] };
12
+ /** Поле ввода под управлением формы */
13
+ exports.FormInput = (0, create_form_field_1.createFormField)(uikit_1.Input, { ...text, displayName: 'FormInput' });
14
+ exports.FormTextarea = (0, create_form_field_1.createFormField)(uikit_1.Textarea, { ...text, displayName: 'FormTextarea' });
15
+ exports.FormMaskedInput = (0, create_form_field_1.createFormField)(uikit_1.MaskedInput, { ...text, displayName: 'FormMaskedInput' });
16
+ exports.FormPinInput = (0, create_form_field_1.createFormField)(uikit_1.PinInput, {
17
+ ...compact,
18
+ empty: '',
19
+ displayName: 'FormPinInput',
20
+ });
21
+ exports.FormNumberInput = (0, create_form_field_1.createFormField)(uikit_1.NumberInput, { ...nullable, displayName: 'FormNumberInput' });
22
+ exports.FormQuantityInput = (0, create_form_field_1.createFormField)(uikit_1.QuantityInput, {
23
+ ...compact,
24
+ empty: null,
25
+ displayName: 'FormQuantityInput',
26
+ });
27
+ exports.FormSelect = (0, create_form_field_1.createFormField)(uikit_1.Select, { ...nullable, displayName: 'FormSelect' });
28
+ exports.FormDatePicker = (0, create_form_field_1.createFormField)(uikit_1.DatePicker, { ...nullable, displayName: 'FormDatePicker' });
29
+ exports.FormTimePicker = (0, create_form_field_1.createFormField)(uikit_1.TimePicker, { ...nullable, displayName: 'FormTimePicker' });
30
+ exports.FormTreeSelect = (0, create_form_field_1.createFormField)(uikit_1.TreeSelect, {
31
+ valueProp: 'value',
32
+ changeProp: 'onChange',
33
+ empty: [],
34
+ inherit: ['disabled', 'size', 'fullWidth'],
35
+ displayName: 'FormTreeSelect',
36
+ });
37
+ exports.FormRadioGroup = (0, create_form_field_1.createFormField)(uikit_1.RadioGroup, {
38
+ empty: null,
39
+ inherit: ['disabled', 'size'],
40
+ displayName: 'FormRadioGroup',
41
+ });
42
+ exports.FormSegmentedControl = (0, create_form_field_1.createFormField)(uikit_1.SegmentedControl, {
43
+ mapError: noError,
44
+ inherit: ['disabled', 'size'],
45
+ displayName: 'FormSegmentedControl',
46
+ });
47
+ exports.FormCheckbox = (0, create_form_field_1.createFormField)(uikit_1.Checkbox, {
48
+ valueProp: 'checked',
49
+ empty: false,
50
+ inherit: ['disabled', 'size'],
51
+ displayName: 'FormCheckbox',
52
+ });
53
+ exports.FormSwitch = (0, create_form_field_1.createFormField)(uikit_1.Switch, {
54
+ mapError: noError,
55
+ valueProp: 'checked',
56
+ empty: false,
57
+ inherit: ['disabled', 'size'],
58
+ displayName: 'FormSwitch',
59
+ });
60
+ exports.FormAutocomplete = (0, create_form_field_1.createFormField)(uikit_1.Autocomplete, { ...text, displayName: 'FormAutocomplete' });
61
+ exports.FormCalendar = (0, create_form_field_1.createFormField)(uikit_1.Calendar, {
62
+ mapError: noError,
63
+ empty: null,
64
+ inherit: ['disabled'],
65
+ displayName: 'FormCalendar',
66
+ });
67
+ /** В форме хранится `fileList` (файлы с состоянием загрузки), а не событие целиком */
68
+ exports.FormFileUpload = (0, create_form_field_1.createFormField)(uikit_1.FileUpload, {
69
+ valueProp: 'fileList',
70
+ getValue: info => info.fileList,
71
+ empty: [],
72
+ mapError: message => ({ error: message }),
73
+ inherit: ['disabled', 'size'],
74
+ displayName: 'FormFileUpload',
75
+ });
package/cjs/form.js ADDED
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.Form = Form;
7
+ const jsx_runtime_1 = require("react/jsx-runtime");
8
+ const react_1 = __importDefault(require("react"));
9
+ const react_hook_form_1 = require("react-hook-form");
10
+ const context_1 = require("./context");
11
+ /**
12
+ * Корень формы: `FormProvider` из react-hook-form, `<form noValidate>` и общие `disabled`, `size` и `fullWidth` для полей.
13
+ * Загрузку и блокировку ухода со страницы форма не рисует: `isSubmitting` и `isDirty` берите у `form.formState`.
14
+ */
15
+ function Form({ form, onSubmit, onInvalid, disabled, size, fullWidth, children, ...rest }) {
16
+ const submit = (event) => {
17
+ const handler = form.handleSubmit((values, e) => onSubmit === null || onSubmit === void 0 ? void 0 : onSubmit(values, e), (errors, e) => onInvalid === null || onInvalid === void 0 ? void 0 : onInvalid(errors, e));
18
+ return handler(event);
19
+ };
20
+ return ((0, jsx_runtime_1.jsx)(react_hook_form_1.FormProvider, { ...form, children: (0, jsx_runtime_1.jsx)(context_1.FormOptionsProvider, { value: { disabled, size, fullWidth }, children: (0, jsx_runtime_1.jsx)("form", { noValidate: true, ...rest, onSubmit: submit, children: children }) }) }));
21
+ }
package/cjs/index.js ADDED
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.useWatch = exports.useFormState = exports.useFormContext = exports.useForm = exports.useFieldArray = exports.useController = exports.setServerErrors = exports.createFormField = exports.useFormOptions = exports.Form = void 0;
18
+ var form_1 = require("./form");
19
+ Object.defineProperty(exports, "Form", { enumerable: true, get: function () { return form_1.Form; } });
20
+ var context_1 = require("./context");
21
+ Object.defineProperty(exports, "useFormOptions", { enumerable: true, get: function () { return context_1.useFormOptions; } });
22
+ var create_form_field_1 = require("./create-form-field");
23
+ Object.defineProperty(exports, "createFormField", { enumerable: true, get: function () { return create_form_field_1.createFormField; } });
24
+ var server_errors_1 = require("./server-errors");
25
+ Object.defineProperty(exports, "setServerErrors", { enumerable: true, get: function () { return server_errors_1.setServerErrors; } });
26
+ __exportStar(require("./fields"), exports);
27
+ // Хуки react-hook-form отдаём из пакета: приложению не нужен второй импорт и отдельная зависимость в коде
28
+ var react_hook_form_1 = require("react-hook-form");
29
+ Object.defineProperty(exports, "useController", { enumerable: true, get: function () { return react_hook_form_1.useController; } });
30
+ Object.defineProperty(exports, "useFieldArray", { enumerable: true, get: function () { return react_hook_form_1.useFieldArray; } });
31
+ Object.defineProperty(exports, "useForm", { enumerable: true, get: function () { return react_hook_form_1.useForm; } });
32
+ Object.defineProperty(exports, "useFormContext", { enumerable: true, get: function () { return react_hook_form_1.useFormContext; } });
33
+ Object.defineProperty(exports, "useFormState", { enumerable: true, get: function () { return react_hook_form_1.useFormState; } });
34
+ Object.defineProperty(exports, "useWatch", { enumerable: true, get: function () { return react_hook_form_1.useWatch; } });
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.setServerErrors = setServerErrors;
4
+ /**
5
+ * Показывает ошибки, пришедшие с сервера: `{ 'address.city': 'Нет такого города', email: 'Занят' }`.
6
+ * Первое поле с ошибкой получает фокус (`shouldFocus`).
7
+ */
8
+ function setServerErrors(setError, errors) {
9
+ let focused = false;
10
+ Object.entries(errors).forEach(([name, message]) => {
11
+ if (!message)
12
+ return;
13
+ setError(name, { type: 'server', message }, { shouldFocus: !focused });
14
+ focused = true;
15
+ });
16
+ }
@@ -0,0 +1,95 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.FormTableCellTreeSelect = exports.FormTableCellFileUpload = exports.FormTableCellSwitch = exports.FormTableCellCheckbox = exports.FormTableCellTimePicker = exports.FormTableCellDatePicker = exports.FormTableCellMaskedInput = exports.FormTableCellNumberInput = exports.FormTableCellSelect = exports.FormTableCellTextarea = exports.FormTableCellInput = void 0;
7
+ const jsx_runtime_1 = require("react/jsx-runtime");
8
+ const table_1 = require("@lt-ui/table");
9
+ const react_1 = __importDefault(require("react"));
10
+ const create_form_field_1 = require("../create-form-field");
11
+ /** У ячеек таблицы `error` принимает сам текст: красная рамка и уголок, текст в подсказке */
12
+ const cell = {
13
+ ref: false,
14
+ mapError: (message) => ({ error: message !== null && message !== void 0 ? message : false }),
15
+ };
16
+ // У переключателя и кнопки загрузки состояния ошибки нет: `error` в DOM не отдаём
17
+ const noError = () => ({});
18
+ /**
19
+ * Редактируемые ячейки таблицы под управлением формы: `name` — путь к значению строки (`rows.${row.index}.price`),
20
+ * вместе с `useFieldArray` это таблица-форма. Ошибка поля уходит в `error` ячейки.
21
+ *
22
+ * @example
23
+ * cell: ({ row }) => <FormTableCellInput name={`rows.${row.index}.title`} aria-label="Название" />
24
+ */
25
+ exports.FormTableCellInput = (0, create_form_field_1.createFormField)(table_1.TableCellInput, {
26
+ ...cell,
27
+ ref: true,
28
+ empty: '',
29
+ displayName: 'FormTableCellInput',
30
+ });
31
+ exports.FormTableCellTextarea = (0, create_form_field_1.createFormField)(table_1.TableCellTextarea, {
32
+ ...cell,
33
+ empty: '',
34
+ displayName: 'FormTableCellTextarea',
35
+ });
36
+ exports.FormTableCellSelect = (0, create_form_field_1.createFormField)(table_1.TableCellSelect, {
37
+ ...cell,
38
+ empty: null,
39
+ displayName: 'FormTableCellSelect',
40
+ });
41
+ exports.FormTableCellNumberInput = (0, create_form_field_1.createFormField)(table_1.TableCellNumberInput, {
42
+ ...cell,
43
+ ref: true,
44
+ empty: null,
45
+ displayName: 'FormTableCellNumberInput',
46
+ });
47
+ exports.FormTableCellMaskedInput = (0, create_form_field_1.createFormField)(table_1.TableCellMaskedInput, {
48
+ ...cell,
49
+ ref: true,
50
+ empty: '',
51
+ displayName: 'FormTableCellMaskedInput',
52
+ });
53
+ exports.FormTableCellDatePicker = (0, create_form_field_1.createFormField)(table_1.TableCellDatePicker, {
54
+ ...cell,
55
+ ref: true,
56
+ empty: null,
57
+ displayName: 'FormTableCellDatePicker',
58
+ });
59
+ exports.FormTableCellTimePicker = (0, create_form_field_1.createFormField)(table_1.TableCellTimePicker, {
60
+ ...cell,
61
+ empty: null,
62
+ displayName: 'FormTableCellTimePicker',
63
+ });
64
+ exports.FormTableCellCheckbox = (0, create_form_field_1.createFormField)(table_1.TableCellCheckbox, {
65
+ ...cell,
66
+ valueProp: 'checked',
67
+ empty: false,
68
+ displayName: 'FormTableCellCheckbox',
69
+ });
70
+ exports.FormTableCellSwitch = (0, create_form_field_1.createFormField)(table_1.TableCellSwitch, {
71
+ ...cell,
72
+ mapError: noError,
73
+ valueProp: 'checked',
74
+ empty: false,
75
+ displayName: 'FormTableCellSwitch',
76
+ });
77
+ /** Ячейка загрузки: в форме лежит список `File`, выбор дополняет его (при `multiple`) или заменяет */
78
+ function FileUploadField({ value, onUpdate, multiple, ...props }) {
79
+ return ((0, jsx_runtime_1.jsx)(table_1.TableCellFileUpload, { ...props, multiple: multiple, files: value, onSelect: files => onUpdate(multiple ? [...value, ...files] : files.slice(0, 1)), onRemove: index => onUpdate(value.filter((_, i) => i !== index)) }));
80
+ }
81
+ exports.FormTableCellFileUpload = (0, create_form_field_1.createFormField)(FileUploadField, {
82
+ ...cell,
83
+ mapError: noError,
84
+ empty: [],
85
+ displayName: 'FormTableCellFileUpload',
86
+ });
87
+ /** Ячейка выбора из дерева: свойства `TreeSelect` передаются прямо в поле, в форме лежит `string[]` */
88
+ function TreeSelectField({ value, onUpdate, error, placeholder, disabled, 'aria-label': ariaLabel, ...treeProps }) {
89
+ return ((0, jsx_runtime_1.jsx)(table_1.TableCellSelect, { kind: "tree", "aria-label": ariaLabel, placeholder: placeholder, disabled: disabled, error: error, treeProps: { ...treeProps, value, onChange: next => onUpdate(next) } }));
90
+ }
91
+ exports.FormTableCellTreeSelect = (0, create_form_field_1.createFormField)(TreeSelectField, {
92
+ ...cell,
93
+ empty: [],
94
+ displayName: 'FormTableCellTreeSelect',
95
+ });
package/context.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ export type FormOptions = {
2
+ /** Отключает все поля формы (поле может переопределить своим `disabled`) */
3
+ disabled?: boolean;
4
+ /** Размер полей формы (поле может переопределить своим `size`) */
5
+ size?: string;
6
+ /** Растянуть поля на всю ширину контейнера (поле может переопределить своим `fullWidth`) */
7
+ fullWidth?: boolean;
8
+ };
9
+ export declare const FormOptionsProvider: import("react").Provider<FormOptions>;
10
+ /** Настройки ближайшей `Form`: общие `disabled` и `size` для полей */
11
+ export declare const useFormOptions: () => FormOptions;
package/context.js ADDED
@@ -0,0 +1,7 @@
1
+ 'use client';
2
+ import { createContext, useContext, version } from 'react';
3
+ const FormOptionsContext = createContext({});
4
+ // React 19 — `<Context value>`, React 18 — `<Context.Provider>`
5
+ export const FormOptionsProvider = Number.parseInt(version, 10) >= 19 ? FormOptionsContext : FormOptionsContext.Provider;
6
+ /** Настройки ближайшей `Form`: общие `disabled` и `size` для полей */
7
+ export const useFormOptions = () => useContext(FormOptionsContext);
@@ -0,0 +1,70 @@
1
+ import type { ComponentProps, ComponentType, ReactElement } from 'react';
2
+ import type { Control, FieldPath, FieldValues, PathValue, RegisterOptions } from 'react-hook-form';
3
+ type AnyComponent = ComponentType<any>;
4
+ /** Свойства поля, которые относятся к форме, а не к компоненту */
5
+ export type FormFieldOwnProps<TFieldValues extends FieldValues, TName extends FieldPath<TFieldValues>> = {
6
+ /** Путь к значению в форме: `name`, `address.city`, `rows.0.price` */
7
+ name: TName;
8
+ /** Управление формой. По умолчанию — из ближайшей `Form` / `FormProvider` */
9
+ control?: Control<TFieldValues>;
10
+ /** Правила валидации react-hook-form. Для схем (zod, yup...) используйте `resolver` у `useForm` */
11
+ rules?: Omit<RegisterOptions<TFieldValues, TName>, 'valueAsNumber' | 'valueAsDate' | 'setValueAs' | 'disabled' | 'onChange'>;
12
+ /** Начальное значение поля (для всей формы лучше `defaultValues` у `useForm`) */
13
+ defaultValue?: PathValue<TFieldValues, TName>;
14
+ /** Удалять значение из формы, когда поле размонтируется */
15
+ shouldUnregister?: boolean;
16
+ };
17
+ export type FormFieldProps<C extends AnyComponent, TFieldValues extends FieldValues, TName extends FieldPath<TFieldValues>, ValueProp extends string, ChangeProp extends string> = FormFieldOwnProps<TFieldValues, TName> & Omit<ComponentProps<C>, ValueProp | ChangeProp | 'name' | 'defaultValue' | 'ref'>;
18
+ /** Поле формы: универсальный компонент с типами из react-hook-form */
19
+ export type FormField<C extends AnyComponent, ValueProp extends string = 'value', ChangeProp extends string = 'onUpdate'> = <TFieldValues extends FieldValues = FieldValues, TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>>(props: FormFieldProps<C, TFieldValues, TName, ValueProp, ChangeProp>) => ReactElement | null;
20
+ export type CreateFormFieldOptions<ValueProp extends string, ChangeProp extends string> = {
21
+ /**
22
+ * Свойство компонента со значением.
23
+ * @default 'value'
24
+ */
25
+ valueProp?: ValueProp;
26
+ /**
27
+ * Свойство-событие компонента: получает новое значение первым аргументом.
28
+ * @default 'onUpdate'
29
+ */
30
+ changeProp?: ChangeProp;
31
+ /**
32
+ * Как получить значение формы из аргументов события, если оно не первый аргумент. Например, у `FileUpload`
33
+ * событие отдаёт `{ file, fileList }`, а в форму идёт `fileList`.
34
+ */
35
+ getValue?: (...args: unknown[]) => unknown;
36
+ /**
37
+ * Что передавать компоненту, пока в форме пусто (`undefined`). Нужно, чтобы поле всегда было контролируемым:
38
+ * `''` для текста, `false` для переключателей, `null` для чисел, дат и списков.
39
+ */
40
+ empty?: unknown;
41
+ /**
42
+ * Как показать ошибку: по умолчанию `status="error"` и текст в `caption` (поля `uikit`), у ячеек таблицы `error` —
43
+ * сам текст. Пока ошибки нет, возвращайте `{}`: заданные вручную `status` и `caption` остаются.
44
+ */
45
+ mapError?: (message: string | undefined, props: Record<string, unknown>) => Record<string, unknown>;
46
+ /**
47
+ * Что берёт от `Form` общего: `disabled` по умолчанию, `size` — у полей с размером.
48
+ * @default ['disabled']
49
+ */
50
+ inherit?: readonly ('disabled' | 'size' | 'fullWidth')[];
51
+ /**
52
+ * Передавать ли `ref` поля компоненту (нужен для фокуса на первую ошибку). Выключите для компонентов-функций,
53
+ * которые `ref` не принимают (в React 18 это предупреждение).
54
+ * @default true
55
+ */
56
+ ref?: boolean;
57
+ /** Имя компонента в DevTools */
58
+ displayName?: string;
59
+ };
60
+ /**
61
+ * Превращает компонент с парой «значение + событие» (`value` + `onUpdate`, `checked` + `onUpdate`...) в поле формы
62
+ * react-hook-form. Значение, `onBlur`, `ref` (фокус на первую ошибку при отправке), ошибка и `disabled` формы
63
+ * подключаются сами; остальные свойства компонента работают как обычно.
64
+ *
65
+ * @example
66
+ * const FormStars = createFormField(MyStars, { empty: 0 });
67
+ * <FormStars name="rating" rules={{ min: { value: 1, message: 'Поставьте оценку' } }} />
68
+ */
69
+ export declare function createFormField<C extends AnyComponent, ValueProp extends string = 'value', ChangeProp extends string = 'onUpdate'>(Component: C, options?: CreateFormFieldOptions<ValueProp, ChangeProp>): FormField<C, ValueProp, ChangeProp>;
70
+ export {};
@@ -0,0 +1,53 @@
1
+ 'use client';
2
+ import React from 'react';
3
+ import { useController } from 'react-hook-form';
4
+ import { useFormOptions } from './context';
5
+ // Ошибка валидации перекрывает `status` и `caption`, заданные вручную; без ошибки они остаются как есть
6
+ const mapErrorToCaption = (message) => message ? { status: 'error', caption: message } : {};
7
+ /**
8
+ * Превращает компонент с парой «значение + событие» (`value` + `onUpdate`, `checked` + `onUpdate`...) в поле формы
9
+ * react-hook-form. Значение, `onBlur`, `ref` (фокус на первую ошибку при отправке), ошибка и `disabled` формы
10
+ * подключаются сами; остальные свойства компонента работают как обычно.
11
+ *
12
+ * @example
13
+ * const FormStars = createFormField(MyStars, { empty: 0 });
14
+ * <FormStars name="rating" rules={{ min: { value: 1, message: 'Поставьте оценку' } }} />
15
+ */
16
+ export function createFormField(Component, options = {}) {
17
+ var _a, _b;
18
+ const { valueProp = 'value', changeProp = 'onUpdate', empty, getValue, mapError = mapErrorToCaption, inherit = ['disabled'], ref: withRef = true, displayName, } = options;
19
+ function Field(props) {
20
+ var _a, _b;
21
+ const { name, control, rules, defaultValue, shouldUnregister, ...rest } = props;
22
+ const { field, fieldState } = useController({ name, control, rules, defaultValue, shouldUnregister });
23
+ const formOptions = useFormOptions();
24
+ const inherited = {};
25
+ if (inherit.includes('disabled') && formOptions.disabled !== undefined)
26
+ inherited.disabled = formOptions.disabled;
27
+ if (inherit.includes('size') && formOptions.size !== undefined)
28
+ inherited.size = formOptions.size;
29
+ if (inherit.includes('fullWidth') && formOptions.fullWidth !== undefined)
30
+ inherited.fullWidth = formOptions.fullWidth;
31
+ const componentProps = {
32
+ ...inherited,
33
+ ...rest,
34
+ ...mapError((_a = fieldState.error) === null || _a === void 0 ? void 0 : _a.message, rest),
35
+ name: field.name,
36
+ [valueProp]: (_b = field.value) !== null && _b !== void 0 ? _b : empty,
37
+ [changeProp]: (...args) => {
38
+ var _a;
39
+ field.onChange(getValue ? getValue(...args) : args[0]);
40
+ (_a = rest[changeProp]) === null || _a === void 0 ? void 0 : _a.call(rest, ...args);
41
+ },
42
+ onBlur: (...args) => {
43
+ var _a;
44
+ field.onBlur();
45
+ (_a = rest.onBlur) === null || _a === void 0 ? void 0 : _a.call(rest, ...args);
46
+ },
47
+ ...(withRef ? { ref: field.ref } : {}),
48
+ };
49
+ return React.createElement(Component, componentProps);
50
+ }
51
+ Field.displayName = displayName !== null && displayName !== void 0 ? displayName : `Form(${(_b = (_a = Component.displayName) !== null && _a !== void 0 ? _a : Component.name) !== null && _b !== void 0 ? _b : 'Field'})`;
52
+ return Field;
53
+ }
package/fields.d.ts ADDED
@@ -0,0 +1,115 @@
1
+ /** Поле ввода под управлением формы */
2
+ export declare const FormInput: import("./create-form-field").FormField<import("react").ForwardRefExoticComponent<import("@lt-ui/uikit").InputProps & import("react").RefAttributes<HTMLInputElement>>, "value", "onUpdate">;
3
+ export declare const FormTextarea: import("./create-form-field").FormField<import("react").ForwardRefExoticComponent<import("@lt-ui/uikit").TextareaProps & import("react").RefAttributes<HTMLTextAreaElement>>, "value", "onUpdate">;
4
+ export declare const FormMaskedInput: import("./create-form-field").FormField<import("react").ForwardRefExoticComponent<import("@lt-ui/uikit").MaskedInputProps & import("react").RefAttributes<HTMLInputElement>>, "value", "onUpdate">;
5
+ export declare const FormPinInput: import("./create-form-field").FormField<import("react").ForwardRefExoticComponent<import("@lt-ui/uikit").DataAttributes & Omit<import("react").HTMLAttributes<HTMLDivElement>, "onChange" | "defaultValue" | "children"> & {
6
+ length?: number;
7
+ value?: string;
8
+ defaultValue?: string;
9
+ onUpdate?: (value: string) => void;
10
+ onComplete?: (value: string) => void;
11
+ type?: import("@lt-ui/uikit").PinInputType;
12
+ mask?: boolean;
13
+ size?: import("@lt-ui/uikit").ControlSize;
14
+ status?: import("@lt-ui/uikit").FieldStatus;
15
+ caption?: import("react").ReactNode;
16
+ disabled?: boolean;
17
+ autoFocus?: boolean;
18
+ name?: string;
19
+ placeholder?: string;
20
+ 'aria-label'?: string;
21
+ getCellLabel?: (index: number, length: number) => string;
22
+ } & import("@lt-ui/uikit/utils").WithClassNames<"PinInput"> & import("react").RefAttributes<HTMLDivElement>>, "value", "onUpdate">;
23
+ export declare const FormNumberInput: import("./create-form-field").FormField<import("react").ForwardRefExoticComponent<import("@lt-ui/uikit").NumberInputProps & import("react").RefAttributes<HTMLInputElement>>, "value", "onUpdate">;
24
+ export declare const FormQuantityInput: import("./create-form-field").FormField<import("react").ForwardRefExoticComponent<import("@lt-ui/uikit").DataAttributes & {
25
+ size?: import("@lt-ui/uikit").QuantityInputSize;
26
+ wide?: boolean;
27
+ value?: number | null;
28
+ defaultValue?: number | null;
29
+ onUpdate?: (value: number | null) => void;
30
+ step?: number;
31
+ precision?: number;
32
+ min?: number;
33
+ max?: number;
34
+ variant?: import("@lt-ui/uikit").InputVariant;
35
+ } & import("@lt-ui/uikit/utils").WithClassNames<"QuantityInput"> & Omit<import("@lt-ui/uikit").InputProps, "onChange" | "value" | "mask" | "defaultValue" | "onUpdate" | "size" | "type" | "align" | "startAdornment" | "endAdornment" | "variant" | "classNames" | "allowClear" | "htmlSize" | "maskPlaceholder" | "alwaysShowMask" | "beforeMaskedStateChange"> & import("react").RefAttributes<HTMLInputElement>>, "value", "onUpdate">;
36
+ export declare const FormSelect: import("./create-form-field").FormField<import("react").ForwardRefExoticComponent<import("@lt-ui/uikit").DataAttributes & import("@lt-ui/uikit").UseSelectConfig<import("@lt-ui/uikit/list/types").ItemValue> & import("@lt-ui/uikit").OverlayContainerProps & {
37
+ label?: string;
38
+ status?: import("@lt-ui/uikit").FieldStatus;
39
+ theme?: import("@lt-ui/uikit").ThemeSetting;
40
+ caption?: React.ReactNode;
41
+ mobile?: import("@lt-ui/uikit/_internal/picker").PickerMobile;
42
+ variant?: "outline" | "underline" | "trigger";
43
+ startAdornment?: React.ReactNode;
44
+ fullWidth?: boolean;
45
+ className?: string;
46
+ id?: string;
47
+ size?: import("@lt-ui/uikit/select/components/select-field").SelectFieldSize;
48
+ popoverClassName?: string;
49
+ classNames?: import("@lt-ui/uikit").ComponentClassNames<"Select">;
50
+ dropdownWidth?: "field" | "content";
51
+ placement?: import("@lt-ui/uikit").PopoverPlacement;
52
+ children?: React.ReactNode;
53
+ 'data-testid'?: string;
54
+ } & import("react").RefAttributes<import("@lt-ui/uikit").SelectHandle>>, "value", "onUpdate">;
55
+ export declare const FormDatePicker: import("./create-form-field").FormField<import("react").ForwardRefExoticComponent<import("@lt-ui/uikit").DatePickerProps & import("react").RefAttributes<HTMLInputElement>>, "value", "onUpdate">;
56
+ export declare const FormTimePicker: import("./create-form-field").FormField<(props: import("@lt-ui/uikit").TimePickerProps) => React.JSX.Element, "value", "onUpdate">;
57
+ export declare const FormTreeSelect: import("./create-form-field").FormField<import("react").ForwardRefExoticComponent<import("@lt-ui/uikit").OverlayContainerProps & Pick<import("@lt-ui/uikit").TreeProps<unknown>, "expanded" | "virtualized" | "defaultExpanded" | "onExpandedChange" | "showLines" | "showLeafIndicator" | "onLoadChildren" | "nodes" | "checkStrictly" | "matchNode" | "emptyContent" | "renderRow" | "renderLabel"> & {
58
+ value?: string[];
59
+ defaultValue?: string[];
60
+ onChange?: ((value: string[], nodes: import("@lt-ui/uikit").TreeNodeData<unknown>[]) => void) | undefined;
61
+ selectionMode?: import("@lt-ui/uikit/tree/tree-select-types").TreeSelectMode;
62
+ checkStrategy?: import("@lt-ui/uikit").TreeCheckStrategy;
63
+ chipsVariant?: "none" | "inside";
64
+ label?: string;
65
+ placeholder?: string;
66
+ caption?: import("react").ReactNode;
67
+ status?: import("@lt-ui/uikit").FieldStatus;
68
+ theme?: import("@lt-ui/uikit").ThemeSetting;
69
+ disabled?: boolean;
70
+ fullWidth?: boolean;
71
+ size?: "s" | "m" | "l";
72
+ clearable?: boolean;
73
+ open?: boolean;
74
+ defaultOpen?: boolean;
75
+ onOpenChange?: (open: boolean) => void;
76
+ showSearch?: boolean;
77
+ searchPlaceholder?: string;
78
+ onSearch?: (query: string) => void;
79
+ searchMode?: import("@lt-ui/uikit").TreeProps<T>["searchMode"];
80
+ closeOnSelect?: boolean;
81
+ maxHeight?: number;
82
+ placement?: import("@lt-ui/uikit").PopoverPlacement;
83
+ mobile?: import("@lt-ui/uikit/_internal/picker").PickerMobile;
84
+ variant?: "outline" | "underline";
85
+ className?: string;
86
+ 'data-testid'?: string;
87
+ } & import("react").RefAttributes<HTMLDivElement>>, "value", "onChange">;
88
+ export declare const FormRadioGroup: import("./create-form-field").FormField<({ children, onChange, onUpdate, value: valueProp, defaultValue, name: nameProp, size, status, disabled, required, orientation, className, ...groupProps }: import("react").PropsWithChildren<import("@lt-ui/uikit").RadioGroupProps>) => React.JSX.Element, "value", "onUpdate">;
89
+ export declare const FormSegmentedControl: import("./create-form-field").FormField<import("react").ForwardRefExoticComponent<import("@lt-ui/uikit").DataAttributes & Omit<import("react").HTMLAttributes<HTMLDivElement>, "onChange" | "onUpdate"> & import("@lt-ui/uikit/segmented-control/types").ButtonsTypeObj & {
90
+ value?: import("@lt-ui/uikit/segmented-control/types").SegmentedControlValue;
91
+ defaultValue?: import("@lt-ui/uikit/segmented-control/types").SegmentedControlValue;
92
+ onUpdate?: (value: import("@lt-ui/uikit/segmented-control/types").SegmentedControlValue) => void;
93
+ scrollable?: boolean;
94
+ children?: React.ReactNode;
95
+ } & import("@lt-ui/uikit/utils").WithClassNames<"SegmentedControl"> & import("react").RefAttributes<HTMLDivElement>>, "value", "onUpdate">;
96
+ export declare const FormCheckbox: import("./create-form-field").FormField<import("react").ForwardRefExoticComponent<import("@lt-ui/uikit").CheckboxProps & import("react").RefAttributes<HTMLInputElement>>, "checked", "onUpdate">;
97
+ export declare const FormSwitch: import("./create-form-field").FormField<import("react").ForwardRefExoticComponent<import("@lt-ui/uikit").DataAttributes & Omit<import("react").InputHTMLAttributes<HTMLInputElement>, "disabled" | "onChange" | "size" | "checked" | "defaultChecked" | "onFocus"> & {
98
+ label?: string | React.ReactElement;
99
+ labelPosition?: "right" | "left";
100
+ size?: import("@lt-ui/uikit").SwitchSize;
101
+ variant?: import("@lt-ui/uikit").SwitchVariant;
102
+ theme?: import("@lt-ui/uikit").ThemeSetting;
103
+ checked?: boolean;
104
+ defaultChecked?: boolean;
105
+ disabled?: boolean;
106
+ onChange?: (event: React.ChangeEvent<HTMLInputElement>) => void;
107
+ onUpdate?: (checked: boolean) => void;
108
+ onFocus?: (event: React.SyntheticEvent) => void;
109
+ } & import("@lt-ui/uikit/utils").WithClassNames<"Switch"> & import("react").RefAttributes<HTMLInputElement>>, "checked", "onUpdate">;
110
+ export declare const FormAutocomplete: import("./create-form-field").FormField<import("react").ForwardRefExoticComponent<import("@lt-ui/uikit").AutocompleteProps & import("react").RefAttributes<import("@lt-ui/uikit").SelectHandle>>, "value", "onUpdate">;
111
+ export declare const FormCalendar: import("./create-form-field").FormField<import("react").ForwardRefExoticComponent<import("@lt-ui/uikit").CalendarProps & import("react").RefAttributes<HTMLDivElement>>, "value", "onUpdate">;
112
+ /** В форме хранится `fileList` (файлы с состоянием загрузки), а не событие целиком */
113
+ export declare const FormFileUpload: import("./create-form-field").FormField<(<T = unknown>(props: import("@lt-ui/uikit").FileUploadProps<T> & {
114
+ ref?: React.Ref<import("@lt-ui/uikit").FileUploadHandle>;
115
+ }) => React.ReactElement | null), "fileList", "onUpdate">;
package/fields.js ADDED
@@ -0,0 +1,72 @@
1
+ import { Autocomplete, Calendar, Checkbox, DatePicker, FileUpload, Input, MaskedInput, NumberInput, PinInput, QuantityInput, RadioGroup, SegmentedControl, Select, Switch, Textarea, TimePicker, TreeSelect, } from '@lt-ui/uikit';
2
+ import { createFormField } from './create-form-field';
3
+ // Компоненты без состояния ошибки: свойства `error` и `caption` в DOM не отдаём
4
+ const noError = () => ({});
5
+ const text = { empty: '', inherit: ['disabled', 'size', 'fullWidth'] };
6
+ const nullable = { empty: null, inherit: ['disabled', 'size', 'fullWidth'] };
7
+ // Счётчик и ячейки кода не растягиваются, пропса `fullWidth` у них нет
8
+ const compact = { inherit: ['disabled', 'size'] };
9
+ /** Поле ввода под управлением формы */
10
+ export const FormInput = createFormField(Input, { ...text, displayName: 'FormInput' });
11
+ export const FormTextarea = createFormField(Textarea, { ...text, displayName: 'FormTextarea' });
12
+ export const FormMaskedInput = createFormField(MaskedInput, { ...text, displayName: 'FormMaskedInput' });
13
+ export const FormPinInput = createFormField(PinInput, {
14
+ ...compact,
15
+ empty: '',
16
+ displayName: 'FormPinInput',
17
+ });
18
+ export const FormNumberInput = createFormField(NumberInput, { ...nullable, displayName: 'FormNumberInput' });
19
+ export const FormQuantityInput = createFormField(QuantityInput, {
20
+ ...compact,
21
+ empty: null,
22
+ displayName: 'FormQuantityInput',
23
+ });
24
+ export const FormSelect = createFormField(Select, { ...nullable, displayName: 'FormSelect' });
25
+ export const FormDatePicker = createFormField(DatePicker, { ...nullable, displayName: 'FormDatePicker' });
26
+ export const FormTimePicker = createFormField(TimePicker, { ...nullable, displayName: 'FormTimePicker' });
27
+ export const FormTreeSelect = createFormField(TreeSelect, {
28
+ valueProp: 'value',
29
+ changeProp: 'onChange',
30
+ empty: [],
31
+ inherit: ['disabled', 'size', 'fullWidth'],
32
+ displayName: 'FormTreeSelect',
33
+ });
34
+ export const FormRadioGroup = createFormField(RadioGroup, {
35
+ empty: null,
36
+ inherit: ['disabled', 'size'],
37
+ displayName: 'FormRadioGroup',
38
+ });
39
+ export const FormSegmentedControl = createFormField(SegmentedControl, {
40
+ mapError: noError,
41
+ inherit: ['disabled', 'size'],
42
+ displayName: 'FormSegmentedControl',
43
+ });
44
+ export const FormCheckbox = createFormField(Checkbox, {
45
+ valueProp: 'checked',
46
+ empty: false,
47
+ inherit: ['disabled', 'size'],
48
+ displayName: 'FormCheckbox',
49
+ });
50
+ export const FormSwitch = createFormField(Switch, {
51
+ mapError: noError,
52
+ valueProp: 'checked',
53
+ empty: false,
54
+ inherit: ['disabled', 'size'],
55
+ displayName: 'FormSwitch',
56
+ });
57
+ export const FormAutocomplete = createFormField(Autocomplete, { ...text, displayName: 'FormAutocomplete' });
58
+ export const FormCalendar = createFormField(Calendar, {
59
+ mapError: noError,
60
+ empty: null,
61
+ inherit: ['disabled'],
62
+ displayName: 'FormCalendar',
63
+ });
64
+ /** В форме хранится `fileList` (файлы с состоянием загрузки), а не событие целиком */
65
+ export const FormFileUpload = createFormField(FileUpload, {
66
+ valueProp: 'fileList',
67
+ getValue: info => info.fileList,
68
+ empty: [],
69
+ mapError: message => ({ error: message }),
70
+ inherit: ['disabled', 'size'],
71
+ displayName: 'FormFileUpload',
72
+ });
package/form.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ import React from 'react';
2
+ import type { FormHTMLAttributes } from 'react';
3
+ import type { FieldValues, SubmitErrorHandler, SubmitHandler, UseFormReturn } from 'react-hook-form';
4
+ export type FormProps<TFieldValues extends FieldValues, TTransformed = TFieldValues> = Omit<FormHTMLAttributes<HTMLFormElement>, 'onSubmit' | 'onError'> & {
5
+ /** Экземпляр формы из `useForm` */
6
+ form: UseFormReturn<TFieldValues, unknown, TTransformed>;
7
+ /**
8
+ * Отправка после успешной валидации. Можно вернуть `Promise`: пока он не завершён, `form.formState.isSubmitting`
9
+ * равен `true` (индикатор загрузки и блокировку кнопки рисует приложение).
10
+ */
11
+ onSubmit?: SubmitHandler<TTransformed extends FieldValues ? TTransformed : TFieldValues>;
12
+ /** Валидация не прошла (фокус на первое невалидное поле выставляет react-hook-form) */
13
+ onInvalid?: SubmitErrorHandler<TFieldValues>;
14
+ /** Отключает все поля формы. Поле может переопределить своим `disabled` */
15
+ disabled?: boolean;
16
+ /** Размер полей формы с размером (`Input`, `Select`...). Поле может переопределить своим `size` */
17
+ size?: string;
18
+ /** Растянуть поля на всю ширину контейнера. Поле может переопределить своим `fullWidth` */
19
+ fullWidth?: boolean;
20
+ };
21
+ /**
22
+ * Корень формы: `FormProvider` из react-hook-form, `<form noValidate>` и общие `disabled`, `size` и `fullWidth` для полей.
23
+ * Загрузку и блокировку ухода со страницы форма не рисует: `isSubmitting` и `isDirty` берите у `form.formState`.
24
+ */
25
+ export declare function Form<TFieldValues extends FieldValues, TTransformed = TFieldValues>({ form, onSubmit, onInvalid, disabled, size, fullWidth, children, ...rest }: FormProps<TFieldValues, TTransformed>): React.JSX.Element;
package/form.js ADDED
@@ -0,0 +1,15 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import React from 'react';
3
+ import { FormProvider } from 'react-hook-form';
4
+ import { FormOptionsProvider } from './context';
5
+ /**
6
+ * Корень формы: `FormProvider` из react-hook-form, `<form noValidate>` и общие `disabled`, `size` и `fullWidth` для полей.
7
+ * Загрузку и блокировку ухода со страницы форма не рисует: `isSubmitting` и `isDirty` берите у `form.formState`.
8
+ */
9
+ export function Form({ form, onSubmit, onInvalid, disabled, size, fullWidth, children, ...rest }) {
10
+ const submit = (event) => {
11
+ const handler = form.handleSubmit((values, e) => onSubmit === null || onSubmit === void 0 ? void 0 : onSubmit(values, e), (errors, e) => onInvalid === null || onInvalid === void 0 ? void 0 : onInvalid(errors, e));
12
+ return handler(event);
13
+ };
14
+ return (_jsx(FormProvider, { ...form, children: _jsx(FormOptionsProvider, { value: { disabled, size, fullWidth }, children: _jsx("form", { noValidate: true, ...rest, onSubmit: submit, children: children }) }) }));
15
+ }
package/index.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ export { Form } from './form';
2
+ export type { FormProps } from './form';
3
+ export { useFormOptions } from './context';
4
+ export type { FormOptions } from './context';
5
+ export { createFormField } from './create-form-field';
6
+ export type { CreateFormFieldOptions, FormField, FormFieldOwnProps, FormFieldProps, } from './create-form-field';
7
+ export { setServerErrors } from './server-errors';
8
+ export * from './fields';
9
+ export { useController, useFieldArray, useForm, useFormContext, useFormState, useWatch, } from 'react-hook-form';
10
+ export type { Control, FieldErrors, FieldPath, FieldValues, SubmitErrorHandler, SubmitHandler, UseFormReturn, } from 'react-hook-form';
package/index.js ADDED
@@ -0,0 +1,7 @@
1
+ export { Form } from './form';
2
+ export { useFormOptions } from './context';
3
+ export { createFormField } from './create-form-field';
4
+ export { setServerErrors } from './server-errors';
5
+ export * from './fields';
6
+ // Хуки react-hook-form отдаём из пакета: приложению не нужен второй импорт и отдельная зависимость в коде
7
+ export { useController, useFieldArray, useForm, useFormContext, useFormState, useWatch, } from 'react-hook-form';
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "@lt-ui/form",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.2",
4
+ "description": "LT UI",
5
+ "license": "MIT",
6
+ "peerDependencies": {
7
+ "@lt-ui/table": "0.0.2",
8
+ "@lt-ui/uikit": "0.0.2",
9
+ "react": "^18.0.0 || ^19.0.0",
10
+ "react-hook-form": "^7.55.0"
11
+ },
12
+ "peerDependenciesMeta": {
13
+ "@lt-ui/table": {
14
+ "optional": true
15
+ }
16
+ },
17
+ "main": "./cjs/index.js",
18
+ "module": "./index.js",
19
+ "types": "./index.d.ts",
20
+ "exports": {
21
+ ".": {
22
+ "types": "./index.d.ts",
23
+ "import": "./index.js",
24
+ "require": "./cjs/index.js"
25
+ },
26
+ "./table": {
27
+ "types": "./table/index.d.ts",
28
+ "import": "./table/index.js",
29
+ "require": "./cjs/table/index.js"
30
+ },
31
+ "./*": "./*"
32
+ },
33
+ "sideEffects": false,
34
+ "private": false,
35
+ "publishConfig": {
36
+ "access": "public"
37
+ }
38
+ }
@@ -0,0 +1,6 @@
1
+ import type { FieldPath, FieldValues, UseFormSetError } from 'react-hook-form';
2
+ /**
3
+ * Показывает ошибки, пришедшие с сервера: `{ 'address.city': 'Нет такого города', email: 'Занят' }`.
4
+ * Первое поле с ошибкой получает фокус (`shouldFocus`).
5
+ */
6
+ export declare function setServerErrors<TFieldValues extends FieldValues>(setError: UseFormSetError<TFieldValues>, errors: Partial<Record<FieldPath<TFieldValues>, string>>): void;
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Показывает ошибки, пришедшие с сервера: `{ 'address.city': 'Нет такого города', email: 'Занят' }`.
3
+ * Первое поле с ошибкой получает фокус (`shouldFocus`).
4
+ */
5
+ export function setServerErrors(setError, errors) {
6
+ let focused = false;
7
+ Object.entries(errors).forEach(([name, message]) => {
8
+ if (!message)
9
+ return;
10
+ setError(name, { type: 'server', message }, { shouldFocus: !focused });
11
+ focused = true;
12
+ });
13
+ }
@@ -0,0 +1,154 @@
1
+ import { TableCellCheckbox, TableCellTextarea } from '@lt-ui/table';
2
+ import type { TableCellFileUploadProps, TableCellListSelectProps, TableCellTreeSelectProps } from '@lt-ui/table';
3
+ import React from 'react';
4
+ /**
5
+ * Редактируемые ячейки таблицы под управлением формы: `name` — путь к значению строки (`rows.${row.index}.price`),
6
+ * вместе с `useFieldArray` это таблица-форма. Ошибка поля уходит в `error` ячейки.
7
+ *
8
+ * @example
9
+ * cell: ({ row }) => <FormTableCellInput name={`rows.${row.index}.title`} aria-label="Название" />
10
+ */
11
+ export declare const FormTableCellInput: import("..").FormField<React.ForwardRefExoticComponent<Omit<import("@lt-ui/uikit").InputProps, "label" | "size" | "fullWidth" | "status" | "align"> & {
12
+ 'aria-label': string;
13
+ error?: boolean | string;
14
+ align?: "start" | "center" | "end";
15
+ } & React.RefAttributes<HTMLInputElement>>, "value", "onUpdate">;
16
+ export declare const FormTableCellTextarea: import("..").FormField<typeof TableCellTextarea, "value", "onUpdate">;
17
+ export declare const FormTableCellSelect: import("..").FormField<React.ComponentType<TableCellListSelectProps>, "value", "onUpdate">;
18
+ export declare const FormTableCellNumberInput: import("..").FormField<React.ForwardRefExoticComponent<Omit<Omit<import("@lt-ui/uikit").NumberInputProps & React.RefAttributes<HTMLInputElement>, "caption" | "label" | "size" | "fullWidth" | "status"> & {
19
+ 'aria-label': string;
20
+ error?: boolean | string;
21
+ }, "ref"> & React.RefAttributes<HTMLInputElement>> | {
22
+ (props: Omit<import("@lt-ui/uikit").NumberInputProps & React.RefAttributes<HTMLInputElement>, "caption" | "label" | "size" | "fullWidth" | "status"> & {
23
+ 'aria-label': string;
24
+ error?: boolean | string;
25
+ }): React.JSX.Element;
26
+ displayName: string;
27
+ }, "value", "onUpdate">;
28
+ export declare const FormTableCellMaskedInput: import("..").FormField<React.ForwardRefExoticComponent<Omit<Omit<import("@lt-ui/uikit").MaskedInputProps & React.RefAttributes<HTMLInputElement>, "caption" | "label" | "size" | "fullWidth" | "status"> & {
29
+ 'aria-label': string;
30
+ error?: boolean | string;
31
+ }, "ref"> & React.RefAttributes<HTMLInputElement>> | {
32
+ (props: Omit<import("@lt-ui/uikit").MaskedInputProps & React.RefAttributes<HTMLInputElement>, "caption" | "label" | "size" | "fullWidth" | "status"> & {
33
+ 'aria-label': string;
34
+ error?: boolean | string;
35
+ }): React.JSX.Element;
36
+ displayName: string;
37
+ }, "value", "onUpdate">;
38
+ export declare const FormTableCellDatePicker: import("..").FormField<React.ForwardRefExoticComponent<Omit<import("@lt-ui/uikit").DataAttributes & import("@lt-ui/uikit").OverlayContainerProps & {
39
+ label?: string;
40
+ placeholder?: string;
41
+ caption?: React.ReactNode;
42
+ status?: import("@lt-ui/uikit").FieldStatus;
43
+ theme?: import("@lt-ui/uikit").ThemeSetting;
44
+ disabled?: boolean;
45
+ size?: "s" | "m" | "l";
46
+ fullWidth?: boolean;
47
+ allowClear?: boolean;
48
+ format?: string;
49
+ editable?: boolean;
50
+ locale?: string;
51
+ weekStartsOn?: import("@lt-ui/uikit").WeekDay;
52
+ minDate?: Date;
53
+ maxDate?: Date;
54
+ disabledWeekDays?: number[];
55
+ isDateDisabled?: (date: Date) => boolean;
56
+ views?: import("@lt-ui/uikit").CalendarView[];
57
+ openTo?: import("@lt-ui/uikit").CalendarView;
58
+ presets?: import("@lt-ui/uikit").CalendarPreset[];
59
+ calendarSize?: import("@lt-ui/uikit").CalendarSize;
60
+ open?: boolean;
61
+ defaultOpen?: boolean;
62
+ onOpenChange?: (open: boolean) => void;
63
+ placement?: import("@lt-ui/uikit").PopoverPlacement;
64
+ mobile?: import("@lt-ui/uikit/_internal/picker").PickerMobile;
65
+ variant?: "outline" | "underline";
66
+ keepSecondsOnMobile?: boolean;
67
+ id?: string;
68
+ className?: string;
69
+ classNames?: import("@lt-ui/uikit").ComponentClassNames<"DatePicker">;
70
+ 'aria-label'?: string;
71
+ 'data-testid'?: string;
72
+ } & {
73
+ mode?: "single";
74
+ value?: Date | null;
75
+ defaultValue?: Date | null;
76
+ onUpdate?: (value: Date | null) => void;
77
+ time?: boolean | import("@lt-ui/uikit").TimeOptions;
78
+ }, "caption" | "label" | "size" | "fullWidth" | "status"> & {
79
+ 'aria-label': string;
80
+ error?: boolean | string;
81
+ } & React.RefAttributes<HTMLInputElement>> | {
82
+ (props: Omit<import("@lt-ui/uikit").DataAttributes & import("@lt-ui/uikit").OverlayContainerProps & {
83
+ label?: string;
84
+ placeholder?: string;
85
+ caption?: React.ReactNode;
86
+ status?: import("@lt-ui/uikit").FieldStatus;
87
+ theme?: import("@lt-ui/uikit").ThemeSetting;
88
+ disabled?: boolean;
89
+ size?: "s" | "m" | "l";
90
+ fullWidth?: boolean;
91
+ allowClear?: boolean;
92
+ format?: string;
93
+ editable?: boolean;
94
+ locale?: string;
95
+ weekStartsOn?: import("@lt-ui/uikit").WeekDay;
96
+ minDate?: Date;
97
+ maxDate?: Date;
98
+ disabledWeekDays?: number[];
99
+ isDateDisabled?: (date: Date) => boolean;
100
+ views?: import("@lt-ui/uikit").CalendarView[];
101
+ openTo?: import("@lt-ui/uikit").CalendarView;
102
+ presets?: import("@lt-ui/uikit").CalendarPreset[];
103
+ calendarSize?: import("@lt-ui/uikit").CalendarSize;
104
+ open?: boolean;
105
+ defaultOpen?: boolean;
106
+ onOpenChange?: (open: boolean) => void;
107
+ placement?: import("@lt-ui/uikit").PopoverPlacement;
108
+ mobile?: import("@lt-ui/uikit/_internal/picker").PickerMobile;
109
+ variant?: "outline" | "underline";
110
+ keepSecondsOnMobile?: boolean;
111
+ id?: string;
112
+ className?: string;
113
+ classNames?: import("@lt-ui/uikit").ComponentClassNames<"DatePicker">;
114
+ 'aria-label'?: string;
115
+ 'data-testid'?: string;
116
+ } & {
117
+ mode?: "single";
118
+ value?: Date | null;
119
+ defaultValue?: Date | null;
120
+ onUpdate?: (value: Date | null) => void;
121
+ time?: boolean | import("@lt-ui/uikit").TimeOptions;
122
+ }, "caption" | "label" | "size" | "fullWidth" | "status"> & {
123
+ 'aria-label': string;
124
+ error?: boolean | string;
125
+ }): React.JSX.Element;
126
+ displayName: string;
127
+ }, "value", "onUpdate">;
128
+ export declare const FormTableCellTimePicker: import("..").FormField<React.ForwardRefExoticComponent<Omit<import("@lt-ui/uikit").TimePickerProps, "caption" | "label" | "size" | "fullWidth" | "status"> & {
129
+ 'aria-label': string;
130
+ error?: boolean | string;
131
+ } & React.RefAttributes<HTMLInputElement>> | {
132
+ (props: Omit<import("@lt-ui/uikit").TimePickerProps, "caption" | "label" | "size" | "fullWidth" | "status"> & {
133
+ 'aria-label': string;
134
+ error?: boolean | string;
135
+ }): React.JSX.Element;
136
+ displayName: string;
137
+ }, "value", "onUpdate">;
138
+ export declare const FormTableCellCheckbox: import("..").FormField<typeof TableCellCheckbox, "checked", "onUpdate">;
139
+ export declare const FormTableCellSwitch: import("..").FormField<(props: import("@lt-ui/table").TableCellSwitchProps) => React.JSX.Element, "checked", "onUpdate">;
140
+ type FileUploadFieldProps = Omit<TableCellFileUploadProps, 'files' | 'onSelect' | 'onRemove'> & {
141
+ value: File[];
142
+ onUpdate: (files: File[]) => void;
143
+ };
144
+ /** Ячейка загрузки: в форме лежит список `File`, выбор дополняет его (при `multiple`) или заменяет */
145
+ declare function FileUploadField({ value, onUpdate, multiple, ...props }: FileUploadFieldProps): React.JSX.Element;
146
+ export declare const FormTableCellFileUpload: import("..").FormField<typeof FileUploadField, "value", "onUpdate">;
147
+ type TreeSelectFieldProps = Omit<TableCellTreeSelectProps, 'kind' | 'treeProps'> & Omit<TableCellTreeSelectProps['treeProps'], 'value' | 'onChange'> & {
148
+ value: string[];
149
+ onUpdate: (value: string[]) => void;
150
+ };
151
+ /** Ячейка выбора из дерева: свойства `TreeSelect` передаются прямо в поле, в форме лежит `string[]` */
152
+ declare function TreeSelectField({ value, onUpdate, error, placeholder, disabled, 'aria-label': ariaLabel, ...treeProps }: TreeSelectFieldProps): React.JSX.Element;
153
+ export declare const FormTableCellTreeSelect: import("..").FormField<typeof TreeSelectField, "value", "onUpdate">;
154
+ export {};
package/table/index.js ADDED
@@ -0,0 +1,89 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { TableCellCheckbox, TableCellDatePicker, TableCellFileUpload, TableCellInput, TableCellMaskedInput, TableCellNumberInput, TableCellSelect, TableCellSwitch, TableCellTextarea, TableCellTimePicker, } from '@lt-ui/table';
3
+ import React from 'react';
4
+ import { createFormField } from '../create-form-field';
5
+ /** У ячеек таблицы `error` принимает сам текст: красная рамка и уголок, текст в подсказке */
6
+ const cell = {
7
+ ref: false,
8
+ mapError: (message) => ({ error: message !== null && message !== void 0 ? message : false }),
9
+ };
10
+ // У переключателя и кнопки загрузки состояния ошибки нет: `error` в DOM не отдаём
11
+ const noError = () => ({});
12
+ /**
13
+ * Редактируемые ячейки таблицы под управлением формы: `name` — путь к значению строки (`rows.${row.index}.price`),
14
+ * вместе с `useFieldArray` это таблица-форма. Ошибка поля уходит в `error` ячейки.
15
+ *
16
+ * @example
17
+ * cell: ({ row }) => <FormTableCellInput name={`rows.${row.index}.title`} aria-label="Название" />
18
+ */
19
+ export const FormTableCellInput = createFormField(TableCellInput, {
20
+ ...cell,
21
+ ref: true,
22
+ empty: '',
23
+ displayName: 'FormTableCellInput',
24
+ });
25
+ export const FormTableCellTextarea = createFormField(TableCellTextarea, {
26
+ ...cell,
27
+ empty: '',
28
+ displayName: 'FormTableCellTextarea',
29
+ });
30
+ export const FormTableCellSelect = createFormField(TableCellSelect, {
31
+ ...cell,
32
+ empty: null,
33
+ displayName: 'FormTableCellSelect',
34
+ });
35
+ export const FormTableCellNumberInput = createFormField(TableCellNumberInput, {
36
+ ...cell,
37
+ ref: true,
38
+ empty: null,
39
+ displayName: 'FormTableCellNumberInput',
40
+ });
41
+ export const FormTableCellMaskedInput = createFormField(TableCellMaskedInput, {
42
+ ...cell,
43
+ ref: true,
44
+ empty: '',
45
+ displayName: 'FormTableCellMaskedInput',
46
+ });
47
+ export const FormTableCellDatePicker = createFormField(TableCellDatePicker, {
48
+ ...cell,
49
+ ref: true,
50
+ empty: null,
51
+ displayName: 'FormTableCellDatePicker',
52
+ });
53
+ export const FormTableCellTimePicker = createFormField(TableCellTimePicker, {
54
+ ...cell,
55
+ empty: null,
56
+ displayName: 'FormTableCellTimePicker',
57
+ });
58
+ export const FormTableCellCheckbox = createFormField(TableCellCheckbox, {
59
+ ...cell,
60
+ valueProp: 'checked',
61
+ empty: false,
62
+ displayName: 'FormTableCellCheckbox',
63
+ });
64
+ export const FormTableCellSwitch = createFormField(TableCellSwitch, {
65
+ ...cell,
66
+ mapError: noError,
67
+ valueProp: 'checked',
68
+ empty: false,
69
+ displayName: 'FormTableCellSwitch',
70
+ });
71
+ /** Ячейка загрузки: в форме лежит список `File`, выбор дополняет его (при `multiple`) или заменяет */
72
+ function FileUploadField({ value, onUpdate, multiple, ...props }) {
73
+ return (_jsx(TableCellFileUpload, { ...props, multiple: multiple, files: value, onSelect: files => onUpdate(multiple ? [...value, ...files] : files.slice(0, 1)), onRemove: index => onUpdate(value.filter((_, i) => i !== index)) }));
74
+ }
75
+ export const FormTableCellFileUpload = createFormField(FileUploadField, {
76
+ ...cell,
77
+ mapError: noError,
78
+ empty: [],
79
+ displayName: 'FormTableCellFileUpload',
80
+ });
81
+ /** Ячейка выбора из дерева: свойства `TreeSelect` передаются прямо в поле, в форме лежит `string[]` */
82
+ function TreeSelectField({ value, onUpdate, error, placeholder, disabled, 'aria-label': ariaLabel, ...treeProps }) {
83
+ return (_jsx(TableCellSelect, { kind: "tree", "aria-label": ariaLabel, placeholder: placeholder, disabled: disabled, error: error, treeProps: { ...treeProps, value, onChange: next => onUpdate(next) } }));
84
+ }
85
+ export const FormTableCellTreeSelect = createFormField(TreeSelectField, {
86
+ ...cell,
87
+ empty: [],
88
+ displayName: 'FormTableCellTreeSelect',
89
+ });
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.