@jsb188/form 0.0.0-stage → 1.1.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.
Files changed (64) hide show
  1. package/README.md +132 -2
  2. package/css/form.css +2 -0
  3. package/package.json +40 -5
  4. package/src/assets.d.ts +1 -0
  5. package/src/libs/SchemaForm.tsx +158 -0
  6. package/src/libs/SchemaForm.types.ts +165 -0
  7. package/src/libs/defineForm.ts +11 -0
  8. package/src/libs/rules.ts +126 -0
  9. package/src/libs/useField.ts +16 -0
  10. package/src/libs/useSchemaForm.helpers.ts +71 -0
  11. package/src/libs/useSchemaForm.ts +268 -0
  12. package/src/libs/validation.ts +42 -0
  13. package/src/main.ts +40 -0
  14. package/src/modules/FieldLabel.tsx +28 -0
  15. package/src/modules/Form-Input.tsx +2 -0
  16. package/src/modules/Form-Line.tsx +126 -0
  17. package/src/modules/Form.helpers.ts +12 -0
  18. package/src/modules/Form.tsx +14 -0
  19. package/src/modules/FormItem.tsx +117 -0
  20. package/src/modules/FormOptions.tsx +12 -0
  21. package/src/modules/FormUI.tsx +2 -0
  22. package/src/modules/Input.tsx +16 -0
  23. package/src/modules/InputClick.tsx +48 -0
  24. package/src/modules/InputWithButton.tsx +37 -0
  25. package/src/modules/ListItemForm.tsx +345 -0
  26. package/src/modules/ListItemForm.types.ts +50 -0
  27. package/src/modules/PasswordInput.tsx +36 -0
  28. package/src/modules/PopOverInput.tsx +75 -0
  29. package/src/modules/SMSCodeInput.tsx +118 -0
  30. package/src/modules/SchemaField.tsx +104 -0
  31. package/src/modules/Select.tsx +163 -0
  32. package/src/modules/Textarea.tsx +33 -0
  33. package/src/modules/TimeInput.helpers.ts +73 -0
  34. package/src/modules/TimeInput.tsx +159 -0
  35. package/src/modules/TimeInput.types.ts +43 -0
  36. package/src/modules/UploadInput.tsx +141 -0
  37. package/src/modules/composeFormInput.tsx +88 -0
  38. package/src/types/form.ts +65 -0
  39. package/src/ui/ContentEditable.tsx +70 -0
  40. package/src/ui/Form.types.ts +138 -0
  41. package/src/ui/FormOptions.tsx +125 -0
  42. package/src/ui/FormUI.tsx +237 -0
  43. package/src/ui/Input.helpers.ts +7 -0
  44. package/src/ui/Input.tsx +199 -0
  45. package/src/ui/Input.types.ts +48 -0
  46. package/src/ui/InputButtons.tsx +41 -0
  47. package/src/ui/InputControls.tsx +68 -0
  48. package/src/ui/Label.tsx +46 -0
  49. package/src/ui/LineForm.tsx +34 -0
  50. package/src/ui/SMSCodeInput.tsx +51 -0
  51. package/src/ui/Select.tsx +33 -0
  52. package/src/ui/Textarea.tsx +96 -0
  53. package/src/ui/TimeInput.tsx +140 -0
  54. package/tests/controller.test.tsx +336 -0
  55. package/tests/controls.test.tsx +261 -0
  56. package/tests/schema-form.test.tsx +303 -0
  57. package/tests/settings-definitions.test.ts +129 -0
  58. package/tests/sms-input.test.tsx +131 -0
  59. package/tests/time-input.test.tsx +395 -0
  60. package/tests/types.ts +102 -0
  61. package/tests/upload-input.test.tsx +114 -0
  62. package/tests/validation.test.ts +65 -0
  63. package/tsconfig.json +13 -0
  64. package/vitest.config.ts +8 -0
@@ -0,0 +1,71 @@
1
+ import type { DeepPartial, FormErrors, FormValues } from './SchemaForm.types';
2
+
3
+ /* Read a nested field path without interpreting missing containers as values. */
4
+ export function getFieldValue(values: unknown, path: string): any {
5
+ return path
6
+ .split('.')
7
+ .reduce<any>((value, key) => (value != null && Object.hasOwn(Object(value), key) ? value[key] : undefined), values);
8
+ }
9
+
10
+ /* Copy only the ancestors of a changed field, retaining arrays and never mutating previous values. */
11
+ export function setFieldValue<T>(values: T, path: string, value: unknown): T {
12
+ const keys = path.split('.');
13
+ if (keys.some((key) => !key || ['__proto__', 'prototype', 'constructor'].includes(key))) return values;
14
+ /* Rebuild the path from its root while sharing unchanged branches. */
15
+ const update = (node: any, index: number): any => {
16
+ const key = keys[index];
17
+ const copy = Array.isArray(node) ? [...node] : { ...node };
18
+ copy[key as any] = index === keys.length - 1 ? value : update(node?.[key] ?? (/^\d+$/.test(keys[index + 1]) ? [] : {}), index + 1);
19
+ return copy;
20
+ };
21
+ return update(values, 0);
22
+ }
23
+
24
+ /* Isolate form snapshots, preserving dates and undefined values as well as nested objects and arrays. */
25
+ export function cloneValues<T>(value: T): T {
26
+ if (value instanceof Date) return new Date(value.getTime()) as T;
27
+ if (Array.isArray(value)) return value.map(cloneValues) as T;
28
+ if (value && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype) {
29
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, cloneValues(item)])) as T;
30
+ }
31
+ return value;
32
+ }
33
+
34
+ /* Compare form snapshots without database coercion or string trimming. */
35
+ export function valuesEqual(a: unknown, b: unknown): boolean {
36
+ if (Object.is(a, b)) return true;
37
+ if (a instanceof Date || b instanceof Date) return a instanceof Date && b instanceof Date && Object.is(a.getTime(), b.getTime());
38
+ if (!a || !b || typeof a !== 'object' || typeof b !== 'object' || Array.isArray(a) !== Array.isArray(b)) return false;
39
+ const keys = Object.keys(a);
40
+ return (
41
+ keys.length === Object.keys(b).length &&
42
+ keys.every((key) => Object.hasOwn(b, key) && valuesEqual((a as FormValues)[key], (b as FormValues)[key]))
43
+ );
44
+ }
45
+
46
+ /* Merge partial record data over explicit defaults; arrays and null replace defaults. */
47
+ export function initialFormValues<T>(defaults: T, supplied?: DeepPartial<T>): T {
48
+ if (supplied === undefined) return cloneValues(defaults);
49
+ if (
50
+ !defaults ||
51
+ !supplied ||
52
+ typeof defaults !== 'object' ||
53
+ typeof supplied !== 'object' ||
54
+ Array.isArray(defaults) ||
55
+ supplied instanceof Date
56
+ )
57
+ return cloneValues(supplied as T);
58
+ const values: FormValues = cloneValues(defaults);
59
+ for (const [key, value] of Object.entries(supplied)) {
60
+ if (['__proto__', 'prototype', 'constructor'].includes(key)) continue;
61
+ values[key] = initialFormValues(values[key], value as any);
62
+ }
63
+ return values as T;
64
+ }
65
+
66
+ /* Remove errors only for fields whose editable values changed. */
67
+ export function errorsAfterChange(errors: FormErrors, previous: FormValues, next: FormValues): FormErrors {
68
+ return Object.fromEntries(
69
+ Object.entries(errors).filter(([path]) => path && valuesEqual(getFieldValue(previous, path), getFieldValue(next, path))),
70
+ );
71
+ }
@@ -0,0 +1,268 @@
1
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
2
+ import type { z } from 'zod';
3
+ import type {
4
+ FormActions,
5
+ FormController,
6
+ FormDefinition,
7
+ FormError,
8
+ FormErrors,
9
+ FormOptions,
10
+ SubmitResult,
11
+ } from './SchemaForm.types';
12
+ import {
13
+ cloneValues,
14
+ errorsAfterChange,
15
+ getFieldValue,
16
+ initialFormValues,
17
+ setFieldValue as updateFieldValue,
18
+ valuesEqual,
19
+ } from './useSchemaForm.helpers';
20
+ import { formError, validationErrors } from './validation';
21
+
22
+ /* Own editable values and metadata independently, using explicit snapshots for initialization and successful saves. */
23
+ export function useSchemaForm<S extends z.ZodTypeAny>(
24
+ definition: FormDefinition<S>,
25
+ options: FormOptions<z.input<S>, z.output<S>> = {},
26
+ ): FormController<z.input<S>, z.output<S>> {
27
+ type Values = z.input<S>;
28
+ const [values, setValueState] = useState<Values>(() => initialFormValues(definition.defaults, options.initialValues));
29
+ const [baseline, setBaseline] = useState<Values>(() => cloneValues(values));
30
+ const [errors, setErrors] = useState<FormErrors>({});
31
+ const [touched, setTouched] = useState<Record<string, boolean>>({});
32
+ const [submitting, setSubmitting] = useState(false);
33
+ const [isValidating, setValidating] = useState(false);
34
+ const [submitError, setSubmitError] = useState<FormError | null>(null);
35
+ const state = useRef({
36
+ values,
37
+ baseline,
38
+ errors,
39
+ definition,
40
+ options,
41
+ revision: 0,
42
+ validation: 0,
43
+ lifecycle: 0,
44
+ resetKey: 0,
45
+ submitted: false,
46
+ mounted: true,
47
+ });
48
+ const inFlight = useRef<Promise<SubmitResult<Values>> | null>(null);
49
+ const actionsRef = useRef<FormActions<Values>>(null!);
50
+ state.current.definition = definition;
51
+ state.current.options = options;
52
+ state.current.errors = errors;
53
+
54
+ useEffect(() => {
55
+ state.current.mounted = true;
56
+ return () => {
57
+ state.current.mounted = false;
58
+ state.current.lifecycle++;
59
+ };
60
+ }, []);
61
+
62
+ /* Validate a snapshot and discard results made obsolete by typing, reset, or a newer validation. */
63
+ const validate = useCallback(async () => {
64
+ const current = state.current;
65
+ const version = ++current.validation;
66
+ const revision = current.revision;
67
+ const lifecycle = current.lifecycle;
68
+ const snapshot = cloneValues(current.values);
69
+ setValidating(true);
70
+ try {
71
+ const result = await current.definition.schema.safeParseAsync(snapshot);
72
+ const nextErrors = result.success ? {} : validationErrors(result.error.issues);
73
+ if (current.mounted && version === current.validation && revision === current.revision && lifecycle === current.lifecycle) {
74
+ current.errors = nextErrors;
75
+ setErrors(nextErrors);
76
+ }
77
+ return result.success ? { success: true as const, data: result.data } : { success: false as const, errors: nextErrors };
78
+ } catch (error) {
79
+ const nextErrors = { '': [formError(error).message] };
80
+ if (current.mounted && version === current.validation && revision === current.revision && lifecycle === current.lifecycle) {
81
+ current.errors = nextErrors;
82
+ setErrors(nextErrors);
83
+ }
84
+ return { success: false as const, errors: nextErrors };
85
+ } finally {
86
+ if (current.mounted && version === current.validation) setValidating(false);
87
+ }
88
+ }, []);
89
+
90
+ /* Read the latest editable snapshot safely from asynchronous continuations and external integrations. */
91
+ const getValues = useCallback((): Values => cloneValues(state.current.values), []);
92
+
93
+ /* Read dirty state for any schema path, including custom controls omitted from automatic rendering. */
94
+ const isFieldDirty = useCallback<FormController<Values>['isFieldDirty']>(
95
+ (name) => !valuesEqual(getFieldValue(state.current.values, name), getFieldValue(state.current.baseline, name)),
96
+ [],
97
+ );
98
+
99
+ /* Update raw editable values immediately, then revalidate when the selected interaction policy requires it. */
100
+ const setValues = useCallback(
101
+ (next: Values | ((previous: Values) => Values)) => {
102
+ const current = state.current;
103
+ const previous = current.values;
104
+ const resolved = typeof next === 'function' ? (next as (previous: Values) => Values)(cloneValues(previous)) : next;
105
+ if (valuesEqual(previous, resolved)) return;
106
+ current.values = cloneValues(resolved);
107
+ current.revision++;
108
+ current.errors = errorsAfterChange(current.errors, previous, current.values);
109
+ setErrors(current.errors);
110
+ setSubmitError(null);
111
+ setValueState(current.values);
112
+ if (current.submitted || current.options.validateOn === 'change') void validate();
113
+ },
114
+ [validate],
115
+ );
116
+
117
+ /* Apply one immutable field update without requiring callers to reconstruct its ancestors. */
118
+ const setFieldValue = useCallback<FormActions<Values>['setFieldValue']>(
119
+ (name, value) => {
120
+ setValues((previous) => updateFieldValue(previous, name, value));
121
+ },
122
+ [setValues],
123
+ );
124
+
125
+ /* Restore the last saved baseline, or explicitly replace the record and its baseline. */
126
+ const reset = useCallback((next?: Values) => {
127
+ const current = state.current;
128
+ const resetValues = cloneValues(next === undefined ? current.baseline : next);
129
+ current.lifecycle++;
130
+ current.resetKey++;
131
+ current.revision++;
132
+ current.validation++;
133
+ current.submitted = false;
134
+ current.values = resetValues;
135
+ current.baseline = cloneValues(resetValues);
136
+ current.errors = {};
137
+ inFlight.current = null;
138
+ setValueState(resetValues);
139
+ setBaseline(current.baseline);
140
+ setErrors({});
141
+ setTouched({});
142
+ setSubmitError(null);
143
+ setSubmitting(false);
144
+ setValidating(false);
145
+ }, []);
146
+
147
+ /* Mark a field visited and optionally validate the complete schema, including cross-field rules. */
148
+ const setFieldTouched = useCallback<FormActions<Values>['setFieldTouched']>(
149
+ (name) => {
150
+ setTouched((previous) => (previous[name] ? previous : { ...previous, [name]: true }));
151
+ if (state.current.options.validateOn === 'blur') void validate();
152
+ },
153
+ [validate],
154
+ );
155
+
156
+ /* Run exactly one submission pipeline for buttons, Enter, and external actions. */
157
+ const submit = useCallback((): Promise<SubmitResult<Values>> => {
158
+ if (inFlight.current) return inFlight.current;
159
+ const current = state.current;
160
+ const scope = { values: current.values, context: current.options.context };
161
+ if (current.options.disabled || current.options.busy || current.definition.canSubmit?.(scope) === false)
162
+ return Promise.resolve({ status: 'continue' });
163
+ const snapshot = cloneValues(current.values);
164
+ const lifecycle = current.lifecycle;
165
+ current.submitted = true;
166
+ setSubmitting(true);
167
+ setSubmitError(null);
168
+
169
+ /* Report a failure while keeping saved values and all edits intact. */
170
+ const fail = (error: FormError, fieldErrors?: FormErrors): SubmitResult<Values> => {
171
+ if (current.mounted && lifecycle === current.lifecycle) {
172
+ setSubmitError(error);
173
+ if (fieldErrors) {
174
+ // A server error about an older value should not overwrite a newer edit's validation.
175
+ const relevant = Object.fromEntries(
176
+ Object.entries(fieldErrors).filter(
177
+ ([path]) => !path || valuesEqual(getFieldValue(snapshot, path), getFieldValue(current.values, path)),
178
+ ),
179
+ );
180
+ current.errors = { ...current.errors, ...relevant };
181
+ setErrors(current.errors);
182
+ }
183
+ current.options.onError?.(error);
184
+ }
185
+ return { status: 'error', error, fieldErrors };
186
+ };
187
+
188
+ /* Await validation and persistence for the captured edit revision, preserving subsequent typing. */
189
+ const run = async (): Promise<SubmitResult<Values>> => {
190
+ try {
191
+ const validation = await validate();
192
+ if (!current.mounted || lifecycle !== current.lifecycle) return { status: 'continue' };
193
+ if (!validation.success) {
194
+ const [path, messages] = Object.entries(validation.errors)[0];
195
+ return fail({ message: messages[0], path }, validation.errors);
196
+ }
197
+ const result = (await current.options.onSubmit?.(validation.data, actionsRef.current)) ?? { status: 'success' as const };
198
+ if (!current.mounted || lifecycle !== current.lifecycle) return { status: 'continue' };
199
+ if (result.status === 'error') return fail(result.error, result.fieldErrors);
200
+ if (result.status === 'success') {
201
+ const saved = cloneValues(result.values ?? snapshot);
202
+ current.baseline = saved;
203
+ setBaseline(saved);
204
+ if (result.values && valuesEqual(current.values, snapshot)) {
205
+ const normalized = cloneValues(result.values);
206
+ current.errors = errorsAfterChange(current.errors, current.values, normalized);
207
+ current.values = normalized;
208
+ // Normalization replaces the validated edit revision, so any pending draft validation is obsolete.
209
+ current.revision++;
210
+ current.validation++;
211
+ setValidating(false);
212
+ setErrors(current.errors);
213
+ setValueState(current.values);
214
+ }
215
+ }
216
+ return result;
217
+ } catch (error) {
218
+ return fail(formError(error));
219
+ } finally {
220
+ if (current.mounted && lifecycle === current.lifecycle) {
221
+ inFlight.current = null;
222
+ setSubmitting(false);
223
+ }
224
+ }
225
+ };
226
+ inFlight.current = run();
227
+ return inFlight.current;
228
+ }, [validate]);
229
+
230
+ const actions = useMemo(
231
+ () => ({ getValues, setValues, setFieldValue, reset, submit, setFieldTouched }),
232
+ [getValues, setValues, setFieldValue, reset, submit, setFieldTouched],
233
+ );
234
+ actionsRef.current = actions;
235
+
236
+ useEffect(() => {
237
+ state.current.options.onValuesChange?.(values, actionsRef.current);
238
+ }, [values]);
239
+
240
+ const dirtyFields = useMemo(
241
+ () =>
242
+ Object.fromEntries(
243
+ Object.keys(definition.fields)
244
+ .filter((path) => !valuesEqual(getFieldValue(values, path), getFieldValue(baseline, path)))
245
+ .map((path) => [path, true]),
246
+ ),
247
+ [values, baseline, definition.fields],
248
+ );
249
+ const isSubmitting = submitting || !!options.busy;
250
+ return {
251
+ ...actions,
252
+ definition,
253
+ context: options.context,
254
+ values,
255
+ errors,
256
+ touched,
257
+ dirtyFields,
258
+ isFieldDirty,
259
+ resetKey: state.current.resetKey,
260
+ isDirty: !valuesEqual(values, baseline),
261
+ isSubmitting,
262
+ isValidating,
263
+ submitError,
264
+ canSubmit: !options.disabled && !isSubmitting && definition.canSubmit?.({ values, context: options.context }) !== false,
265
+ disabled: !!options.disabled,
266
+ validate,
267
+ };
268
+ }
@@ -0,0 +1,42 @@
1
+ import i18n from '@jsb188/app/i18n/index.ts';
2
+ import type { z } from 'zod';
3
+ import type { FormError, FormErrors, SubmitResult } from './SchemaForm.types';
4
+
5
+ /* Normalize transport or thrown errors without putting metadata in form values. */
6
+ export function formError(error: unknown): FormError {
7
+ if (error && typeof error === 'object' && 'message' in error && typeof error.message === 'string')
8
+ return { ...error, message: error.message };
9
+ return { message: typeof error === 'string' ? error : i18n.t('error.unknown_error_msg') };
10
+ }
11
+
12
+ /* Retain every issue at its nested field path, including form-level issues under the empty path. */
13
+ export function validationErrors(issues: z.ZodIssue[]): FormErrors {
14
+ const errors: FormErrors = {};
15
+ for (const issue of issues) {
16
+ const path = issue.path.join('.');
17
+ errors[path] ??= [];
18
+ errors[path].push(issue.message);
19
+ }
20
+ return errors;
21
+ }
22
+
23
+ /* Explicitly adapt existing mutation results, including several saves, to the form submission contract. */
24
+ export function submissionResult(result: unknown): SubmitResult<never> {
25
+ if (Array.isArray(result)) {
26
+ let aborted = false;
27
+ for (const item of result) {
28
+ const adapted = submissionResult(item);
29
+ if (adapted.status === 'error') return adapted;
30
+ if (adapted.status === 'continue') aborted = true;
31
+ }
32
+ return { status: aborted ? 'continue' : 'success' };
33
+ }
34
+ if (result === false) return { status: 'error', error: formError(null) };
35
+ if (result && typeof result === 'object') {
36
+ if ('aborted' in result && result.aborted) return { status: 'continue' };
37
+ if ('error' in result && result.error) return { status: 'error', error: formError(result.error) };
38
+ if ('errors' in result && Array.isArray(result.errors) && result.errors.length)
39
+ return { status: 'error', error: formError(result.errors[0]) };
40
+ }
41
+ return { status: 'success' };
42
+ }
package/src/main.ts ADDED
@@ -0,0 +1,40 @@
1
+ export { default as SchemaForm } from './libs/SchemaForm';
2
+ export type { SchemaFormProps } from './libs/SchemaForm';
3
+ export { defineForm } from './libs/defineForm';
4
+ export { useSchemaForm } from './libs/useSchemaForm';
5
+ export { useField } from './libs/useField';
6
+ export { rules } from './libs/rules';
7
+ export { submissionResult } from './libs/validation';
8
+ export type {
9
+ FieldDefinition,
10
+ FieldPresentation,
11
+ FieldPath,
12
+ FieldValue,
13
+ DeepPartial,
14
+ FormActions,
15
+ FormController,
16
+ FormDefinition,
17
+ FormError,
18
+ FormErrors,
19
+ FormLayout,
20
+ FormScope,
21
+ FormOptions as UseSchemaFormOptions,
22
+ SubmitResult,
23
+ } from './libs/SchemaForm.types';
24
+ export {
25
+ Input,
26
+ Select,
27
+ Textarea,
28
+ PasswordInput,
29
+ InputClick,
30
+ InputWithButton,
31
+ FormOptions,
32
+ SMSCodeInput,
33
+ InputTimeFromDate,
34
+ ContentEditable,
35
+ } from './modules/Form';
36
+ export { FormBreak, FormElement, FormSectionTitle, Fieldset, ToggleSwitch, ColorInputSwatch, InputWithPostfix } from './ui/FormUI';
37
+ export { Label } from './modules/FieldLabel';
38
+ export { POInput } from './modules/PopOverInput';
39
+ export type { InputTimeProps, TimeFormField, TimeFormValues } from './modules/TimeInput';
40
+ export type { InputType, TextareaType, SelectType, SelectOptionType, SelectValue } from './ui/Form.types';
@@ -0,0 +1,28 @@
1
+ import { TooltipButton } from '@jsb188/react-web/modules/popover/Tooltip';
2
+ import { Icon } from '@jsb188/react-web/svgs/Icon';
3
+ import { memo } from 'react';
4
+ import { Label as LabelUI, type LabelType } from '../ui/Label';
5
+
6
+ /*
7
+ * Add the existing bundled help tooltip to the presentational field label.
8
+ */
9
+ export const Label = memo((p: LabelType) => (
10
+ <LabelUI
11
+ {...p}
12
+ accessory={
13
+ p.iconName || p.info ? (
14
+ <TooltipButton
15
+ message={p.info}
16
+ className="pl_5 shift_up label_r"
17
+ position="right"
18
+ offsetY={-9}
19
+ >
20
+ <Icon name={p.iconName || 'info-circle'} />
21
+ </TooltipButton>
22
+ ) : undefined
23
+ }
24
+ />
25
+ ));
26
+ Label.displayName = 'FieldLabel';
27
+ export { Label as FieldLabel };
28
+ export type { LabelType };
@@ -0,0 +1,2 @@
1
+ export { SMSCodeInput } from './SMSCodeInput';
2
+ export { InputTimeFromDate } from './TimeInput';
@@ -0,0 +1,126 @@
1
+ import { cn } from '@jsb188/app/utils/string.ts';
2
+ import { memo, type KeyboardEvent } from 'react';
3
+ import { Icon } from '@jsb188/react-web/svgs/Icon';
4
+ import { LineRow } from '../ui/FormUI';
5
+ import { Select, type SelectOptionType } from './Select';
6
+ import { TooltipButton } from '@jsb188/react-web/modules/popover/Tooltip';
7
+
8
+ /**
9
+ * Line form; compact labelled rows that share one label column and a bottom border.
10
+ * Rows are controlled by their owner and report plain values instead of DOM events.
11
+ */
12
+
13
+ /*
14
+ * Render the trailing info tooltip of a line row, if the row has one.
15
+ */
16
+ const LineTooltip = (p: { message?: string }) =>
17
+ p.message ? (
18
+ <TooltipButton
19
+ ariaLabel={p.message}
20
+ className="p_10 ic_sm"
21
+ message={p.message}
22
+ >
23
+ <Icon name="info-circle" />
24
+ </TooltipButton>
25
+ ) : null;
26
+
27
+ /*
28
+ * Render a compact controlled input row.
29
+ */
30
+ export const LineInput = memo(
31
+ (p: {
32
+ // Width utility class of the label column; defaults to w_85.
33
+ labelWidthClassName?: string;
34
+ // Background utility class of the input; defaults to the line form hover fade.
35
+ backgroundClassName?: string;
36
+ disabled?: boolean;
37
+ // Render the typed value in the error color.
38
+ isError?: boolean;
39
+ label: string;
40
+ maxLength?: number;
41
+ name: string;
42
+ onChange: (value: string) => void;
43
+ onKeyDown?: (event: KeyboardEvent<HTMLInputElement>) => void;
44
+ placeholder?: string;
45
+ tooltipInfo?: string;
46
+ type: 'email' | 'text';
47
+ value: string;
48
+ }) => (
49
+ <LineRow
50
+ label={p.label}
51
+ name={p.name}
52
+ labelWidthClassName={p.labelWidthClassName}
53
+ >
54
+ <input
55
+ className={cn('ol_none bd_0 py_10 f', p.backgroundClassName ?? 'bg_main_fd_hv', p.isError && 'cl_err')}
56
+ disabled={p.disabled}
57
+ id={p.name}
58
+ maxLength={p.maxLength}
59
+ name={p.name}
60
+ type={p.type}
61
+ value={p.value}
62
+ placeholder={p.placeholder}
63
+ onChange={(event) => p.onChange(event.target.value)}
64
+ onKeyDown={p.onKeyDown}
65
+ />
66
+ <LineTooltip message={p.tooltipInfo} />
67
+ </LineRow>
68
+ ),
69
+ );
70
+
71
+ LineInput.displayName = 'LineInput';
72
+
73
+ /*
74
+ * Render a compact controlled select row.
75
+ */
76
+ export const LineSelect = memo(
77
+ (p: {
78
+ // Width utility class of the label column; defaults to w_85.
79
+ labelWidthClassName?: string;
80
+ // Background utility class of the select trigger; defaults to the line form hover fade.
81
+ backgroundClassName?: string;
82
+ disabled?: boolean;
83
+ // Render the selected value in the error color.
84
+ isError?: boolean;
85
+ label: string;
86
+ // Added to the selected option's icon wrapper.
87
+ leftIconClassName?: string;
88
+ name: string;
89
+ onChange: (value: string) => void;
90
+ options: SelectOptionType[];
91
+ placeholder?: string;
92
+ tooltipInfo?: string;
93
+ value: string;
94
+ }) => (
95
+ <LineRow
96
+ label={p.label}
97
+ name={p.name}
98
+ labelWidthClassName={p.labelWidthClassName}
99
+ >
100
+ <Select
101
+ id={p.name}
102
+ name={p.name}
103
+ preset="none"
104
+ zClassName="z9"
105
+ options={p.options}
106
+ placeholder={p.placeholder}
107
+ value={p.value}
108
+ disabled={p.disabled}
109
+ fullWidth
110
+ leftIconClassName={p.leftIconClassName}
111
+ selectClassName={cn('ol_none bd_0 py_10 pl_n fs', p.backgroundClassName ?? 'bg_main_fd_hv', p.isError && 'cl_err')}
112
+ borderRadiusClassName=""
113
+ matchTriggerWidth
114
+ yOffset={0}
115
+ onChange={(value) => {
116
+ if (typeof value === 'string') p.onChange(value);
117
+ }}
118
+ />
119
+ <LineTooltip message={p.tooltipInfo} />
120
+ </LineRow>
121
+ ),
122
+ );
123
+
124
+ LineSelect.displayName = 'LineSelect';
125
+
126
+ export { LineSelections, type LineSelectionItem } from '../ui/LineForm';
@@ -0,0 +1,12 @@
1
+ import type { FormValuesObj } from '@jsb188/form/types/form';
2
+
3
+ export { setFieldValue as setFormValue } from '../libs/useSchemaForm.helpers';
4
+
5
+ /*
6
+ * Clear the legacy inline error flag when its field changes without mutating the saved value snapshot.
7
+ */
8
+ export function clearFieldError<T extends FormValuesObj>(values: T, name: string): T {
9
+ return values.__errorFields?.includes(name)
10
+ ? { ...values, __errorFields: values.__errorFields.filter((field) => field !== name) }
11
+ : values;
12
+ }
@@ -0,0 +1,14 @@
1
+ export { Input } from './Input';
2
+ export { Select } from './Select';
3
+ export type { SelectOptionType, SelectType, SelectValue, InputType, TextareaType } from '../ui/Form.types';
4
+ export { SideInputButton, InputRightButton } from '../ui/InputButtons';
5
+ export { InputWithButton } from './InputWithButton';
6
+ export { InputClick } from './InputClick';
7
+ export { PasswordInput } from './PasswordInput';
8
+ export { Textarea } from './Textarea';
9
+ export { FormOptions } from './FormOptions';
10
+ export { FormItem } from './FormItem';
11
+ export { composeFormInput } from './composeFormInput';
12
+ export { ContentEditable } from '../ui/ContentEditable';
13
+ export { SMSCodeInput } from './SMSCodeInput';
14
+ export { InputTimeFromDate } from './TimeInput';