@jsb188/form 0.0.0-stage → 1.1.12

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
package/README.md CHANGED
@@ -1,3 +1,133 @@
1
- # Temporary Holding Version
1
+ # Forms
2
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.
3
+ `@jsb188/form` owns form controls, their presentation, interactions, editable form rows, and typed schema forms. Popover infrastructure, tooltips, icons, and buttons live in `@jsb188/react-web`. Dependencies flow from forms to web primitives, with no reverse dependency from React Web to forms.
4
+
5
+ ## Imports and styles
6
+
7
+ ```tsx
8
+ import { SchemaForm, defineForm, rules, useSchemaForm, useField } from '@jsb188/form';
9
+ import { Input } from '@jsb188/form/modules/Input';
10
+ import { Select } from '@jsb188/form/modules/Select';
11
+ import { InputUI } from '@jsb188/form/ui/Input';
12
+ import '@jsb188/form/form.css';
13
+ ```
14
+
15
+ Load the application's existing global CSS, theme variables, icon assets, and popover/modal styles as before. `@jsb188/form/form.css` loads the shared `@jsb188/css/form.css` stylesheet. Shared styles remain in the base CSS package because React Web also uses them for native date/time and Markdown inputs. Components do not inject styles automatically, so SSR applications can retain their current stylesheet ordering.
16
+
17
+ `ui/` contains controlled presentation components; `modules/` owns interactions such as popover selection, password visibility, and textarea sizing; `libs/` owns definitions, form state, and validation. Granular imports let callers use a single input without importing the schema renderer. `@jsb188/form/ui/FormUI` exports pure layout and small controls; `@jsb188/form/ui/Form` preserves the former tooltip-aware Label facade.
18
+
19
+ ## Popover integration
20
+
21
+ React Web renders general list items and provides a typed `PopOverListRenderersProvider` for specialized items. Register form inputs in the application's popover host so root lists and nested submenus receive the same renderer. Applications using the email editor can also register `POLayoutDesigner` from `@jsb188/editor/EmailBuilder/POLayoutDesigner` as `LAYOUT_DESIGNER`.
22
+
23
+ ```tsx
24
+ import { POInput } from '@jsb188/form/modules/PopOverInput';
25
+ import { PopOverList } from '@jsb188/react-web/modules/PopOver';
26
+ import { PopOverListRenderersProvider } from '@jsb188/react-web/modules/popover/PopOverListRenderers';
27
+
28
+ const itemRenderers = { INPUT: POInput };
29
+
30
+ <PopOverListRenderersProvider renderers={itemRenderers}>
31
+ <PopOverList {...handlers} variables={variables} />
32
+ </PopOverListRenderersProvider>;
33
+ ```
34
+
35
+ The old React Web `ui/Input`, `ui/Label`, `ui/InputControls`, `ui/Input.types`, and `ui/Input.helpers` exports have moved to the corresponding `@jsb188/form/ui/` paths. There are no compatibility re-exports back from React Web, which would introduce a circular dependency.
36
+
37
+ ## A complete schema form
38
+
39
+ ```tsx
40
+ import i18n from '@jsb188/app/i18n/index.ts';
41
+ import { z } from 'zod';
42
+ import { defineForm, rules, SchemaForm, submissionResult } from '@jsb188/form';
43
+
44
+ /* Define the value contract, editing defaults, and presentation together. */
45
+ function makeContactForm() {
46
+ return defineForm({
47
+ schema: z.object({ email: rules.email(), phone: rules.phone({ optional: true }) }),
48
+ defaults: { email: '', phone: '' },
49
+ fields: {
50
+ email: { kind: 'input', label: i18n.t('account.email') },
51
+ phone: { kind: 'input', label: i18n.t('c.phone_number'), type: 'tel' },
52
+ },
53
+ canSubmit: ({ values }) => !!values.email.trim(),
54
+ });
55
+ }
56
+
57
+ // Inside a component, keep the definition stable with useMemo when appropriate.
58
+ <SchemaForm
59
+ definition={definition}
60
+ initialValues={contact}
61
+ preset='condensed'
62
+ onError={setError}
63
+ onSubmit={async (values) => submissionResult(await saveContact(values))}
64
+ />
65
+ ```
66
+
67
+ The schema determines editable input and submitted output types. Field keys and layout references are typed paths, including nested objects. Validation reads the entire schema, preserving nested issue paths and cross-field constraints. Successful parsing passes transformed output to `onSubmit`; it does not rewrite draft input while typing.
68
+
69
+ `layout` defaults to field declaration order. To group fields, use `{ kind: 'row', fields: ['profile.firstName', 'profile.lastName'] }`. Section and break entries have stable `id` values. Standard field kinds are `input`, `password`, `textarea`, `select`, `action`, `click`, and `time`.
70
+
71
+ `select` uses the bundled select popover and plain options. `click` preserves richer existing popover descriptors such as grouped country menus; it owns scoped event acknowledgement and value updates. A form generates unique popover IDs so separate instances cannot consume each other's selections.
72
+
73
+ ## Custom layouts and external save buttons
74
+
75
+ ```tsx
76
+ const form = useSchemaForm(definition, {
77
+ initialValues: contact,
78
+ onSubmit: async (values) => submissionResult(await saveContact(values)),
79
+ });
80
+ const email = useField(form, 'email');
81
+
82
+ <Input
83
+ name={email.name}
84
+ value={email.value}
85
+ error={email.errors.length > 0}
86
+ onChange={(event) => email.setValue(event.target.value)}
87
+ onBlur={email.onBlur}
88
+ />
89
+ ```
90
+
91
+ Render `<SchemaForm form={form} />` to reuse the same controller with the automatic layout. External buttons call `form.submit()`. Standalone controls can also receive ordinary `value`/`onChange` props without any schema or controller.
92
+
93
+ The controller exposes `values`, `errors`, `touched`, `dirtyFields`, `isDirty`, `isSubmitting`, `isValidating`, `submitError`, and `canSubmit`. Metadata is never inserted into submitted values. `setFieldValue(path, value)` immutably updates nested data. `getValues()` returns an isolated snapshot for asynchronous continuations. `isFieldDirty(path)` and `useField` also work for custom controls omitted from `fields`; use an empty `fields: {}` when the entire layout is custom.
94
+
95
+ Initial values are read once. `reset()` restores the most recently acknowledged saved values; `reset(nextValues)` explicitly replaces both values and baseline. Use a React record key when switching entities. Background updates must be applied deliberately so they do not erase unsaved edits. A successful save acknowledges only its captured snapshot, preserving changes made while the save was in flight.
96
+
97
+ ## Rules and conditions
98
+
99
+ - `rules.email()`, `rules.phone()`, and `rules.password()` reuse existing application policy and translated messages.
100
+ - `rules.text({ label, minLength, maxLength, optional })` provides text constraints.
101
+ - `rules.url()`, `rules.number({ integer, min, max, optional })`, and `rules.date()` cover common values. Empty required numeric inputs never become zero.
102
+ - `.superRefine(rules.matches('passwordRepeat', 'password'))` attaches confirmation errors to the confirmation field.
103
+ - `.superRefine(rules.requiredWhen('field', predicate, translatedLabel))` declares conditional required values.
104
+
105
+ Optional string rules accept empty input. Defaults should explicitly provide editable strings, including `''`; missing server data should be mapped to those defaults. Shared business rules, such as optional-but-complete addresses, live with their domain definitions and are reused by multiple forms.
106
+
107
+ Use `visibleWhen({ values, context })`, `disabledWhen({ values, context })`, and `resolve({ values, context })` for dynamic presentation. Event handlers are never automatically evaluated. Hidden fields retain their values, and hiding does not silently waive validation: express conditional validation in the value schema. `preset` controls appearance, with explicit per-field overrides.
108
+
109
+ Validation defaults to submit, then revalidates edits after a submit attempt. `validateOn: 'blur' | 'change'` is available on the controller or complete form. Errors continue through existing error UI via `onError`; the renderer adds no new visual messages.
110
+
111
+ ## Submission
112
+
113
+ Always return or await the save promise. Return `{ status: 'success' }` after persistence, `{ status: 'error', error, fieldErrors? }` for a failure, or `{ status: 'continue' }` for a flow that has not saved yet. A successful callback returning void is also accepted. `submissionResult(result)` explicitly adapts existing GraphQL mutation results, including arrays of results and aborted requests.
114
+
115
+ For authentication forms, `{ status: 'native' }` posts to `actionUrl` only after the callback completes. Controls remain enabled so native POST and password managers receive credential values. Click, Enter, and external submission use one deduplicated pipeline. Stale validation and saves completing after reset/unmount cannot replace the current form state.
116
+
117
+ ## Compatibility and checks
118
+
119
+ Import form components directly from this package; the old React Web form forwarding exports have been removed to avoid a circular dependency. Editable list rows and their types are exported from `@jsb188/form/modules/ListItemForm`; general lists remain in `@jsb188/react-web/modules/List`. Existing metadata editors may continue using `FormItem`/`composeFormInput`; new schema forms use named definitions and the new controller. The old `@jsb188/react/schema` hook has been removed after migrating its consumers.
120
+
121
+ ## File uploads
122
+
123
+ `@jsb188/form/modules/UploadInput` owns file selection, clearing, and imperative picker/upload controls. Its required `onUpload(file)` callback returns a promise whose truthy result means success; a falsy result means failure. The component has no GraphQL, storage, or upload-hook dependency. The caller owns upload errors and completion handling.
124
+
125
+ For signed storage uploads, call `useSignedFileUpload` from `@jsb188/react-web/hooks/use-signed-file-upload` in the consuming component and pass `startFileUpload` as `onUpload`. Organization, upload intent, moderation, cache, progress, and completion options belong to the hook. `startUpload({ doNotClearInput: true })` keeps the selected file available for retries; ordinary uploads clear selection before invoking the callback.
126
+
127
+ `InputTimeFromDate` displays and edits a stored instant in its requested `timeZone`, preserving that zone's calendar date, seconds, and milliseconds. Midnight and noon use 12 AM and 12 PM. Empty values initialize on today's date in that zone. Partial or invalid edits stay local until corrected; leaving the control restores the last committed value. Nonexistent daylight-saving times are rejected; repeated times preserve the original offset when possible, otherwise use the earlier instant. Pass `resetKey={form.resetKey}` for custom time layouts so an explicit reset clears an unfinished draft even when the saved date has not changed. The automatic renderer already does this.
128
+
129
+ `SMSCodeInput` keeps the existing visual code slots while supporting numeric keyboards, one-time-code autofill, and formatted paste with leading zeroes. Repeated completion/Enter events are deduplicated; editing, an error, or the end of a pending request allows a retry. Its controlled presentation is available separately from `ui/SMSCodeInput`, as is `ui/TimeInput`.
130
+
131
+ Run `yarn workspace @jsb188/form test` and `yarn workspace @jsb188/form typecheck`. Focused tests cover nested state, asynchronous validation and saving, native submission, domain definitions, and standalone control interactions.
132
+
133
+ Application integration tests live in `apps/marketday/tests/AuthFormIntegration.test.tsx` and `SchemaSettingsIntegration.test.tsx`. They exercise actual form components and their existing request/state boundaries without sending live email, SMS, or OAuth requests. Real provider delivery, real server-issued sessions, and password-manager/OS autofill still require a configured account/device check; they are not simulated by a desktop DOM test.
package/css/form.css ADDED
@@ -0,0 +1,2 @@
1
+ /* Shared control presentation is owned by the base CSS package. */
2
+ @import "@jsb188/css/form.css";
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
- "name": "@jsb188/form",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@jsb188/form",
3
+ "version": "1.1.12",
4
+ "description": "Form controls, presentation, interactions, and typed schema forms for web.",
5
+ "license": "ISC",
6
+ "author": "jsb188",
7
+ "type": "module",
8
+ "sideEffects": [
9
+ "./css/*.css"
10
+ ],
11
+ "exports": {
12
+ ".": "./src/main.ts",
13
+ "./form.css": "./css/form.css",
14
+ "./libs/*": "./src/libs/*.ts",
15
+ "./libs/SchemaForm": "./src/libs/SchemaForm.tsx",
16
+ "./modules/*": "./src/modules/*.tsx",
17
+ "./ui/Form": "./src/modules/FormUI.tsx",
18
+ "./ui/*": "./src/ui/*.tsx",
19
+ "./ui/Form.types": "./src/ui/Form.types.ts",
20
+ "./types/*": "./src/types/*.ts",
21
+ "./ui/Input.types": "./src/ui/Input.types.ts",
22
+ "./ui/Input.helpers": "./src/ui/Input.helpers.ts"
23
+ },
24
+ "peerDependencies": {
25
+ "@jsb188/app": "1.1.12",
26
+ "@jsb188/css": "1.1.12",
27
+ "@jsb188/react": "1.1.12",
28
+ "@jsb188/react-web": "1.1.12",
29
+ "luxon": "^3.7.2",
30
+ "react": "^19.3.0",
31
+ "react-dom": "^19.3.0",
32
+ "react-router": "^8.4.0"
33
+ },
34
+ "dependencies": {
35
+ "zod": "^3.25.76"
36
+ },
37
+ "scripts": {
38
+ "test": "vitest run --config ./vitest.config.ts",
39
+ "typecheck": "tsc -p tsconfig.json"
40
+ }
41
+ }
@@ -0,0 +1 @@
1
+ declare module '*.css';
@@ -0,0 +1,158 @@
1
+ import i18n from '@jsb188/app/i18n/index.ts';
2
+ import { cn } from '@jsb188/app/utils/string.ts';
3
+ import { FullWidthButton } from '@jsb188/react-web/ui/Button';
4
+ import { useId, useRef } from 'react';
5
+ import type { z } from 'zod';
6
+ import { Label } from '../modules/FieldLabel';
7
+ import { SchemaField } from '../modules/SchemaField';
8
+ import { FormSectionTitle, getHtmlFor } from '../ui/FormUI';
9
+ import type { FieldDefinition, FormController, FormDefinition, FormOptions, SchemaFormAppearance } from './SchemaForm.types';
10
+ import { useSchemaForm } from './useSchemaForm';
11
+
12
+ export type SchemaFormProps<S extends z.ZodTypeAny = z.ZodTypeAny> = SchemaFormAppearance &
13
+ (
14
+ | { form: FormController<any, any>; definition?: never }
15
+ | ({ form?: never; definition: FormDefinition<S> } & FormOptions<z.input<S>, z.output<S>>)
16
+ );
17
+
18
+ /* Render the original form structure with either a caller-owned controller or an internally owned one. */
19
+ export default function SchemaForm<S extends z.ZodTypeAny>(p: SchemaFormProps<S>) {
20
+ return p.form ? (
21
+ <SchemaFormView
22
+ {...p}
23
+ form={p.form}
24
+ />
25
+ ) : (
26
+ <OwnedSchemaForm {...p} />
27
+ );
28
+ }
29
+
30
+ /* Supply the convenient complete-form API while retaining the same controller available to custom layouts. */
31
+ function OwnedSchemaForm<S extends z.ZodTypeAny>(
32
+ p: SchemaFormAppearance & FormOptions<z.input<S>, z.output<S>> & { definition: FormDefinition<S> },
33
+ ) {
34
+ const form = useSchemaForm(p.definition, p);
35
+ return (
36
+ <SchemaFormView
37
+ {...p}
38
+ form={form}
39
+ />
40
+ );
41
+ }
42
+
43
+ /* Preserve layout and button presentation while routing every submission through one controller. */
44
+ function SchemaFormView(p: SchemaFormAppearance & { form: FormController<any, any> }) {
45
+ const { form, children, FooterComponent, preset, labelClassName, notAllowed } = p;
46
+ const formRef = useRef<HTMLFormElement>(null);
47
+ const submitInFlight = useRef<{ resetKey: number } | null>(null);
48
+ const instanceId = useId().replaceAll(':', '_');
49
+ const formId = p.id ?? `schema_form_${instanceId}`;
50
+ const fields = form.definition.fields as Record<string, FieldDefinition>;
51
+ const layout = form.definition.layout ?? Object.keys(fields);
52
+ const disabledAppearance = !!(
53
+ notAllowed ||
54
+ p.disabledButton ||
55
+ form.disabled ||
56
+ form.definition.canSubmit?.({ values: form.values, context: form.context }) === false
57
+ );
58
+ const disabledButton = disabledAppearance || !form.canSubmit;
59
+
60
+ /* Validate before native posting, or finish the async callback without submitting the browser form. */
61
+ const onSubmit = async (event: React.FormEvent | React.MouseEvent) => {
62
+ event.preventDefault();
63
+ if (disabledButton || submitInFlight.current?.resetKey === form.resetKey) return;
64
+ const submission = { resetKey: form.resetKey };
65
+ submitInFlight.current = submission;
66
+ let posted = false;
67
+ try {
68
+ const result = await form.submit();
69
+ if (result.status === 'native' && p.actionUrl && formRef.current) {
70
+ // Keep controls enabled so the browser includes them and password managers observe a real POST.
71
+ HTMLFormElement.prototype.submit.call(formRef.current);
72
+ posted = true;
73
+ }
74
+ } finally {
75
+ if (!posted && submitInFlight.current === submission) submitInFlight.current = null;
76
+ }
77
+ };
78
+
79
+ /* Render each field by stable path rather than its position in the current layout. */
80
+ const renderField = (name: string) =>
81
+ fields[name] ? (
82
+ <SchemaField
83
+ key={name}
84
+ form={form}
85
+ name={name}
86
+ field={fields[name]}
87
+ disabled={notAllowed}
88
+ preset={preset}
89
+ labelClassName={labelClassName}
90
+ formId={formId}
91
+ />
92
+ ) : null;
93
+
94
+ return (
95
+ <form
96
+ ref={formRef}
97
+ id={formId}
98
+ method={p.method ?? (p.actionUrl ? 'post' : 'get')}
99
+ action={p.actionUrl}
100
+ className={cn('schema_form', notAllowed && 'form_not_allowed', p.className)}
101
+ name={p.name || 'schema_form'}
102
+ autoComplete={p.autoComplete === false ? 'off' : 'on'}
103
+ noValidate
104
+ onSubmit={onSubmit}
105
+ >
106
+ {children}
107
+ {layout.map((item) => {
108
+ if (typeof item === 'string') return renderField(item);
109
+ if (item.kind === 'break')
110
+ return (
111
+ <div
112
+ key={item.id}
113
+ className="h_6 rel texture_bf pattern_texture mt_16 mb_20"
114
+ />
115
+ );
116
+ if (item.kind === 'section')
117
+ return (
118
+ <FormSectionTitle
119
+ key={item.id}
120
+ title={item.title}
121
+ description={item.description}
122
+ />
123
+ );
124
+ return (
125
+ <div
126
+ key={item.id ?? item.fields.join('|')}
127
+ className={`grid gapx_xs size_${item.fields.length}`}
128
+ >
129
+ {item.label ? (
130
+ <Label
131
+ htmlFor={getHtmlFor(`${formId}_${item.fields[0]}`, item.fields[0])}
132
+ labelClassName={labelClassName}
133
+ >
134
+ {item.label}
135
+ </Label>
136
+ ) : null}
137
+ {item.fields.map(renderField)}
138
+ </div>
139
+ );
140
+ })}
141
+ {FooterComponent}
142
+ {p.hideButton ? null : (
143
+ <div className="pt_df fs z2">
144
+ <FullWidthButton
145
+ className={cn(p.buttonClassName || 'mt_sm', !disabledAppearance && 'shadow')}
146
+ disabled={disabledButton}
147
+ loading={form.isSubmitting}
148
+ preset={p.buttonPreset || 'bg_primary'}
149
+ fullWidth={p.buttonFullWidth}
150
+ onClick={onSubmit}
151
+ >
152
+ {p.buttonText || i18n.t('c.continue')}
153
+ </FullWidthButton>
154
+ </div>
155
+ )}
156
+ </form>
157
+ );
158
+ }
@@ -0,0 +1,165 @@
1
+ import type { ReactNode, MouseEvent, KeyboardEvent, FocusEvent } from 'react';
2
+ import type { z } from 'zod';
3
+ import type { ButtonPresetEnum } from '@jsb188/react-web/ui/Button';
4
+
5
+ export type FieldPath<T, D extends unknown[] = []> = D['length'] extends 6
6
+ ? never
7
+ : T extends Date
8
+ ? never
9
+ : T extends readonly (infer V)[]
10
+ ? `${number}` | `${number}.${FieldPath<V, [...D, 0]>}`
11
+ : T extends object
12
+ ? {
13
+ [K in keyof T & string]:
14
+ | K
15
+ | (NonNullable<T[K]> extends object ? `${K}.${FieldPath<NonNullable<T[K]>, [...D, 0]>}` : never);
16
+ }[keyof T & string]
17
+ : never;
18
+ export type FieldValue<T, P extends string> = P extends keyof T
19
+ ? T[P]
20
+ : P extends `${infer K}.${infer Rest}`
21
+ ? K extends keyof T
22
+ ? FieldValue<NonNullable<T[K]>, Rest>
23
+ : T extends readonly (infer V)[]
24
+ ? K extends `${number}`
25
+ ? FieldValue<V, Rest>
26
+ : never
27
+ : never
28
+ : T extends readonly (infer V)[]
29
+ ? P extends `${number}`
30
+ ? V
31
+ : never
32
+ : never;
33
+
34
+ export type FormValues = Record<string, any>;
35
+ export type DeepPartial<T> = T extends Date | readonly unknown[] ? T : T extends object ? { [K in keyof T]?: DeepPartial<T[K]> } : T;
36
+ export type FormErrors = Record<string, string[]>;
37
+ export type FormError = { message: string; path?: string; [key: string]: unknown };
38
+ export type SubmitResult<T = FormValues> =
39
+ | { status: 'success'; values?: T }
40
+ | { status: 'error'; error: FormError; fieldErrors?: FormErrors }
41
+ | { status: 'continue' }
42
+ | { status: 'native' };
43
+ export type FormScope<T = FormValues> = { values: T; context: any };
44
+
45
+ export interface FieldPresentation {
46
+ label?: string;
47
+ placeholder?: string;
48
+ description?: string;
49
+ info?: string;
50
+ type?: string;
51
+ autoFocus?: boolean;
52
+ autoComplete?: string;
53
+ suppressHydrationWarning?: boolean;
54
+ spellCheck?: boolean;
55
+ disabled?: boolean;
56
+ locked?: boolean;
57
+ editable?: boolean;
58
+ focused?: boolean;
59
+ allowClearIfLocked?: boolean;
60
+ fullWidth?: boolean;
61
+ maxLength?: number;
62
+ minLength?: number;
63
+ minHeight?: number;
64
+ min?: number;
65
+ max?: number;
66
+ step?: number;
67
+ preset?: string;
68
+ focusStyle?: 'outline' | 'shadow';
69
+ className?: string;
70
+ inputClassName?: string;
71
+ textareaClassName?: string;
72
+ labelClassName?: string;
73
+ borderRadiusClassName?: string;
74
+ buttonText?: string;
75
+ getter?: (value: any) => string;
76
+ onClickButton?: (event: MouseEvent) => void;
77
+ onClick?: (event: MouseEvent, name: string) => void;
78
+ onKeyDown?: (event: KeyboardEvent, name: string) => void;
79
+ onFocus?: (event: FocusEvent<any>) => void;
80
+ onBlur?: (event: FocusEvent<any>) => void;
81
+ options?: { value: string | number | null; text: string; description?: string; iconName?: string; disabled?: boolean }[];
82
+ popOverProps?: { id: string; [key: string]: any };
83
+ timeZone?: string;
84
+ scrollAreaDOMId?: string;
85
+ }
86
+
87
+ export interface FieldDefinition<T = FormValues> extends FieldPresentation {
88
+ kind: 'input' | 'password' | 'textarea' | 'select' | 'click' | 'action' | 'time';
89
+ visibleWhen?: (scope: FormScope<T>) => boolean;
90
+ disabledWhen?: (scope: FormScope<T>) => boolean;
91
+ resolve?: (scope: FormScope<T>) => Partial<FieldPresentation>;
92
+ onValueChange?: (value: unknown, actions: FormActions<T>) => void;
93
+ }
94
+
95
+ export type FormLayout<P extends string = string> =
96
+ | P
97
+ | { kind: 'row'; id?: string; fields: P[]; label?: string }
98
+ | { kind: 'section'; id: string; title: string; description?: string }
99
+ | { kind: 'break'; id: string };
100
+ export interface FormDefinition<S extends z.ZodTypeAny = z.ZodTypeAny> {
101
+ schema: S;
102
+ defaults: z.input<S>;
103
+ fields: Partial<Record<FieldPath<z.input<S>>, FieldDefinition<z.input<S>>>>;
104
+ layout?: FormLayout<FieldPath<z.input<S>>>[];
105
+ canSubmit?: (scope: FormScope<z.input<S>>) => boolean;
106
+ }
107
+
108
+ export interface FormActions<T = FormValues> {
109
+ getValues: () => T;
110
+ setValues: (values: T | ((previous: T) => T)) => void;
111
+ setFieldValue: <P extends FieldPath<T>>(name: P, value: FieldValue<T, P>) => void;
112
+ reset: (values?: T) => void;
113
+ submit: () => Promise<SubmitResult<T>>;
114
+ setFieldTouched: (name: FieldPath<T>) => void;
115
+ }
116
+
117
+ export interface FormOptions<T = FormValues, O = T> {
118
+ initialValues?: DeepPartial<T>;
119
+ context?: any;
120
+ busy?: boolean;
121
+ disabled?: boolean;
122
+ validateOn?: 'submit' | 'blur' | 'change';
123
+ // biome-ignore lint/suspicious/noConfusingVoidType: Async save callbacks may complete without an explicit result.
124
+ onSubmit?: (values: O, actions: FormActions<T>) => void | SubmitResult<T> | Promise<void | SubmitResult<T>>;
125
+ onError?: (error: FormError) => void;
126
+ onValuesChange?: (values: T, actions: FormActions<T>) => void;
127
+ }
128
+
129
+ export interface FormController<T = FormValues, O = T> extends FormActions<T> {
130
+ definition: FormDefinition<any>;
131
+ context: any;
132
+ values: T;
133
+ errors: FormErrors;
134
+ touched: Record<string, boolean>;
135
+ dirtyFields: Record<string, boolean>;
136
+ isFieldDirty: (name: FieldPath<T>) => boolean;
137
+ resetKey: number;
138
+ isDirty: boolean;
139
+ isSubmitting: boolean;
140
+ isValidating: boolean;
141
+ submitError: FormError | null;
142
+ canSubmit: boolean;
143
+ disabled: boolean;
144
+ validate: () => Promise<{ success: true; data: O } | { success: false; errors: FormErrors }>;
145
+ }
146
+
147
+ export interface SchemaFormAppearance {
148
+ preset?: string | null;
149
+ className?: string;
150
+ labelClassName?: string;
151
+ buttonClassName?: string;
152
+ buttonPreset?: ButtonPresetEnum;
153
+ buttonFullWidth?: boolean;
154
+ buttonText?: string;
155
+ name?: string;
156
+ id?: string;
157
+ autoComplete?: boolean;
158
+ notAllowed?: boolean;
159
+ disabledButton?: boolean;
160
+ hideButton?: boolean;
161
+ actionUrl?: string;
162
+ method?: 'get' | 'post';
163
+ children?: ReactNode;
164
+ FooterComponent?: ReactNode;
165
+ }
@@ -0,0 +1,11 @@
1
+ import type { z } from 'zod';
2
+ import type { FieldDefinition, FieldPath, FormDefinition } from './SchemaForm.types';
3
+
4
+ /* Keep form definitions as plain objects while checking value paths and presentation at declaration time. */
5
+ export function defineForm<S extends z.ZodTypeAny, F extends Record<string, unknown>>(
6
+ definition: Omit<FormDefinition<S>, 'fields'> & {
7
+ fields: { [K in keyof F]: K extends FieldPath<z.input<S>> ? F[K] & FieldDefinition<z.input<S>> : never };
8
+ },
9
+ ): Omit<FormDefinition<S>, 'fields'> & { fields: F } {
10
+ return definition;
11
+ }
@@ -0,0 +1,126 @@
1
+ import i18n from '@jsb188/app/i18n/index.ts';
2
+ import { isEmail, isPhone, passwordStrength } from '@jsb188/app/utils/string.ts';
3
+ import { z } from 'zod';
4
+ import { getFieldValue } from './useSchemaForm.helpers';
5
+
6
+ interface TextRuleOptions {
7
+ optional?: boolean;
8
+ label?: string;
9
+ minLength?: number;
10
+ maxLength?: number;
11
+ message?: string;
12
+ }
13
+
14
+ /* Validate text without transforming what the user typed; optional fields accept an empty input. */
15
+ function text(options: TextRuleOptions = {}) {
16
+ return z.string().superRefine((value, context) => {
17
+ const trimmed = value.trim();
18
+ if (options.optional && !trimmed) return;
19
+ const minimum = options.minLength ?? (options.optional ? 0 : 1);
20
+ let message: string | undefined;
21
+ if (!trimmed && minimum > 0) {
22
+ message = options.label ? i18n.t('error.msg_value_required', { value: options.label }) : i18n.t('error.msg_form_required');
23
+ } else if (trimmed.length < minimum) {
24
+ message = i18n.t('error.msg_form_text_min', { min: minimum });
25
+ } else if (options.maxLength !== undefined && value.length > options.maxLength) {
26
+ message = i18n.t('error.msg_form_text_max', { max: options.maxLength });
27
+ }
28
+ if (message) context.addIssue({ code: 'custom', message: options.message ?? message });
29
+ });
30
+ }
31
+
32
+ /* Apply the shared email policy and translated message consistently across forms. */
33
+ function email(options: Pick<TextRuleOptions, 'optional' | 'message'> = {}) {
34
+ return z.string().superRefine((value, context) => {
35
+ if (options.optional && !value.trim()) return;
36
+ if (!isEmail(value))
37
+ context.addIssue({ code: 'custom', message: options.message ?? i18n.t('error.msg_email_invalid', { value }) });
38
+ });
39
+ }
40
+
41
+ /* Accept the application's existing international and locally formatted phone numbers. */
42
+ function phone(options: Pick<TextRuleOptions, 'optional' | 'message'> = {}) {
43
+ return z.string().superRefine((value, context) => {
44
+ if (options.optional && !value.trim()) return;
45
+ if (!isPhone(value))
46
+ context.addIssue({ code: 'custom', message: options.message ?? i18n.t('error.msg_phone_invalid', { value }) });
47
+ });
48
+ }
49
+
50
+ /* Preserve the current password policy and its specific translated failure messages. */
51
+ function password(options: { minLength?: number } = {}) {
52
+ return z.string().superRefine((value, context) => {
53
+ const minimum = options.minLength ?? 8;
54
+ const result = passwordStrength(value, minimum);
55
+ if (result.valid) return;
56
+ const messages = [
57
+ !result.isLongEnough && i18n.t('error.msg_password_too_short', { length: minimum }),
58
+ !result.hasLowercase && i18n.t('error.msg_password_lowercase'),
59
+ !result.hasUppercase && i18n.t('error.msg_password_uppercase'),
60
+ !result.hasDigit && i18n.t('error.msg_password_digit'),
61
+ !result.hasSpecial && i18n.t('error.msg_password_special'),
62
+ ].filter(Boolean);
63
+ context.addIssue({ code: 'custom', message: messages.length > 1 ? i18n.t('error.msg_password_insecure') : String(messages[0]) });
64
+ });
65
+ }
66
+
67
+ /* Attach a reusable equality check to the confirmation field of an object schema. */
68
+ function matches(field: string, other: string, message?: string) {
69
+ return (values: unknown, context: z.RefinementCtx) => {
70
+ if (getFieldValue(values, field) !== getFieldValue(values, other))
71
+ context.addIssue({ code: 'custom', path: field.split('.'), message: message ?? i18n.t('error.msg_password_mismatch') });
72
+ };
73
+ }
74
+
75
+ /* Require a field only when the domain's explicit predicate applies. */
76
+ function requiredWhen(field: string, when: (values: any) => boolean, label: string) {
77
+ return (values: unknown, context: z.RefinementCtx) => {
78
+ const value = getFieldValue(values, field);
79
+ if (when(values) && (value == null || (typeof value === 'string' && !value.trim())))
80
+ context.addIssue({ code: 'custom', path: field.split('.'), message: i18n.t('error.msg_value_required', { value: label }) });
81
+ };
82
+ }
83
+
84
+ /* Validate a web address without silently adding or removing a protocol. */
85
+ function url(options: Pick<TextRuleOptions, 'optional' | 'message'> = {}) {
86
+ return z.string().superRefine((value, context) => {
87
+ if (options.optional && !value.trim()) return;
88
+ try {
89
+ if (!['https:', 'http:'].includes(new URL(value).protocol)) throw new Error();
90
+ } catch {
91
+ context.addIssue({ code: 'custom', message: options.message ?? i18n.t('error.msg_form_url_invalid') });
92
+ }
93
+ });
94
+ }
95
+
96
+ /* Validate numeric input and convert only the successfully submitted output, keeping empty distinct from zero. */
97
+ function number(options: { optional?: boolean; integer?: boolean; min?: number; max?: number } = {}) {
98
+ return z
99
+ .union([z.string(), z.number()])
100
+ .superRefine((value, context) => {
101
+ const empty = typeof value === 'string' && !value.trim();
102
+ if (empty && options.optional) return;
103
+ const numeric = Number(value);
104
+ if (
105
+ empty ||
106
+ !Number.isFinite(numeric) ||
107
+ (options.integer && !Number.isInteger(numeric)) ||
108
+ (options.min !== undefined && numeric < options.min) ||
109
+ (options.max !== undefined && numeric > options.max)
110
+ )
111
+ context.addIssue({ code: 'custom', message: i18n.t('error.msg_form_number_invalid') });
112
+ })
113
+ .transform((value) => (typeof value === 'string' && !value.trim() ? undefined : Number(value)));
114
+ }
115
+
116
+ /* Require a real calendar date in the input format used by native date fields. */
117
+ function date(options: { optional?: boolean } = {}) {
118
+ return z.string().superRefine((value, context) => {
119
+ if (options.optional && !value) return;
120
+ const parsed = new Date(`${value}T00:00:00Z`);
121
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(value) || !Number.isFinite(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== value)
122
+ context.addIssue({ code: 'custom', message: i18n.t('error.msg_form_date_invalid') });
123
+ });
124
+ }
125
+
126
+ export const rules = { text, email, phone, password, matches, requiredWhen, url, number, date };
@@ -0,0 +1,16 @@
1
+ import type { FieldPath, FieldValue, FormController } from './SchemaForm.types';
2
+ import { getFieldValue } from './useSchemaForm.helpers';
3
+
4
+ /* Bind an individual control to the same state and validation used by the schema renderer. */
5
+ export function useField<T, P extends FieldPath<T>>(form: FormController<T, any>, name: P) {
6
+ return {
7
+ name,
8
+ value: getFieldValue(form.values, name) as FieldValue<T, P>,
9
+ errors: form.errors[name] ?? [],
10
+ touched: !!form.touched[name],
11
+ dirty: form.isFieldDirty(name),
12
+ disabled: form.disabled,
13
+ setValue: (value: FieldValue<T, P>) => form.setFieldValue(name, value),
14
+ onBlur: () => form.setFieldTouched(name),
15
+ };
16
+ }