@dxos/react-ui-form 0.8.4-main.72ec0f3 → 0.8.4-main.74a063c4e0

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 (189) hide show
  1. package/README.md +0 -1
  2. package/dist/lib/browser/index.mjs +2305 -2352
  3. package/dist/lib/browser/index.mjs.map +4 -4
  4. package/dist/lib/browser/meta.json +1 -1
  5. package/dist/lib/node-esm/index.mjs +2305 -2352
  6. package/dist/lib/node-esm/index.mjs.map +4 -4
  7. package/dist/lib/node-esm/meta.json +1 -1
  8. package/dist/types/src/components/FieldEditor/FieldEditor.d.ts +8 -7
  9. package/dist/types/src/components/FieldEditor/FieldEditor.d.ts.map +1 -1
  10. package/dist/types/src/components/FieldEditor/FieldEditor.stories.d.ts +66 -59
  11. package/dist/types/src/components/FieldEditor/FieldEditor.stories.d.ts.map +1 -1
  12. package/dist/types/src/components/Form/Form.d.ts +87 -27
  13. package/dist/types/src/components/Form/Form.d.ts.map +1 -1
  14. package/dist/types/src/components/Form/Form.stories.d.ts +112 -136
  15. package/dist/types/src/components/Form/Form.stories.d.ts.map +1 -1
  16. package/dist/types/src/components/Form/FormField.d.ts +43 -0
  17. package/dist/types/src/components/Form/FormField.d.ts.map +1 -0
  18. package/dist/types/src/components/Form/FormFieldComponent.d.ts +77 -0
  19. package/dist/types/src/components/Form/FormFieldComponent.d.ts.map +1 -0
  20. package/dist/types/src/components/Form/FormFieldComponent.stories.d.ts +9 -0
  21. package/dist/types/src/components/Form/FormFieldComponent.stories.d.ts.map +1 -0
  22. package/dist/types/src/components/Form/FormFieldSet.d.ts +18 -0
  23. package/dist/types/src/components/Form/FormFieldSet.d.ts.map +1 -0
  24. package/dist/types/src/components/Form/fields/ArrayField.d.ts +18 -0
  25. package/dist/types/src/components/Form/fields/ArrayField.d.ts.map +1 -0
  26. package/dist/types/src/components/Form/fields/BooleanField.d.ts +4 -0
  27. package/dist/types/src/components/Form/fields/BooleanField.d.ts.map +1 -0
  28. package/dist/types/src/components/Form/fields/GeoPointField.d.ts +5 -0
  29. package/dist/types/src/components/Form/fields/GeoPointField.d.ts.map +1 -0
  30. package/dist/types/src/components/Form/fields/MarkdownField.d.ts +4 -0
  31. package/dist/types/src/components/Form/fields/MarkdownField.d.ts.map +1 -0
  32. package/dist/types/src/components/Form/fields/NumberField.d.ts +4 -0
  33. package/dist/types/src/components/Form/fields/NumberField.d.ts.map +1 -0
  34. package/dist/types/src/components/Form/fields/RefField.d.ts +16 -0
  35. package/dist/types/src/components/Form/fields/RefField.d.ts.map +1 -0
  36. package/dist/types/src/components/Form/fields/SelectField.d.ts +10 -0
  37. package/dist/types/src/components/Form/fields/SelectField.d.ts.map +1 -0
  38. package/dist/types/src/components/Form/fields/SelectOptionField.d.ts +5 -0
  39. package/dist/types/src/components/Form/fields/SelectOptionField.d.ts.map +1 -0
  40. package/dist/types/src/components/Form/fields/SelectOptionField.stories.d.ts +82 -0
  41. package/dist/types/src/components/Form/fields/SelectOptionField.stories.d.ts.map +1 -0
  42. package/dist/types/src/components/Form/fields/TextAreaField.d.ts +4 -0
  43. package/dist/types/src/components/Form/fields/TextAreaField.d.ts.map +1 -0
  44. package/dist/types/src/components/Form/fields/TextField.d.ts +4 -0
  45. package/dist/types/src/components/Form/fields/TextField.d.ts.map +1 -0
  46. package/dist/types/src/components/Form/fields/TupleField.d.ts +6 -0
  47. package/dist/types/src/components/Form/fields/TupleField.d.ts.map +1 -0
  48. package/dist/types/src/components/Form/fields/index.d.ts +12 -0
  49. package/dist/types/src/components/Form/fields/index.d.ts.map +1 -0
  50. package/dist/types/src/components/Form/index.d.ts +2 -4
  51. package/dist/types/src/components/Form/index.d.ts.map +1 -1
  52. package/dist/types/src/components/ObjectPicker/ObjectPicker.d.ts +23 -10
  53. package/dist/types/src/components/ObjectPicker/ObjectPicker.d.ts.map +1 -1
  54. package/dist/types/src/components/ObjectPicker/ObjectPicker.stories.d.ts +62 -58
  55. package/dist/types/src/components/ObjectPicker/ObjectPicker.stories.d.ts.map +1 -1
  56. package/dist/types/src/components/Settings/Settings.d.ts +39 -0
  57. package/dist/types/src/components/Settings/Settings.d.ts.map +1 -0
  58. package/dist/types/src/components/Settings/Settings.stories.d.ts +81 -0
  59. package/dist/types/src/components/Settings/Settings.stories.d.ts.map +1 -0
  60. package/dist/types/src/components/Settings/index.d.ts +2 -0
  61. package/dist/types/src/components/Settings/index.d.ts.map +1 -0
  62. package/dist/types/src/components/ViewEditor/ViewEditor.d.ts +11 -13
  63. package/dist/types/src/components/ViewEditor/ViewEditor.d.ts.map +1 -1
  64. package/dist/types/src/components/ViewEditor/ViewEditor.stories.d.ts +67 -62
  65. package/dist/types/src/components/ViewEditor/ViewEditor.stories.d.ts.map +1 -1
  66. package/dist/types/src/components/index.d.ts +1 -1
  67. package/dist/types/src/components/index.d.ts.map +1 -1
  68. package/dist/types/src/components/testing.d.ts +0 -2
  69. package/dist/types/src/components/testing.d.ts.map +1 -1
  70. package/dist/types/src/hooks/index.d.ts +2 -3
  71. package/dist/types/src/hooks/index.d.ts.map +1 -1
  72. package/dist/types/src/hooks/useFormHandler.d.ts +82 -0
  73. package/dist/types/src/hooks/useFormHandler.d.ts.map +1 -0
  74. package/dist/types/src/hooks/useKeyHandler.d.ts +7 -0
  75. package/dist/types/src/hooks/useKeyHandler.d.ts.map +1 -0
  76. package/dist/types/src/translations.d.ts +63 -59
  77. package/dist/types/src/translations.d.ts.map +1 -1
  78. package/dist/types/src/util/field.d.ts +3 -3
  79. package/dist/types/src/util/field.d.ts.map +1 -1
  80. package/dist/types/src/util/formatting.d.ts +2 -2
  81. package/dist/types/src/util/formatting.d.ts.map +1 -1
  82. package/dist/types/src/util/index.d.ts +1 -1
  83. package/dist/types/src/util/index.d.ts.map +1 -1
  84. package/dist/types/src/util/properties.d.ts +7 -0
  85. package/dist/types/src/util/properties.d.ts.map +1 -0
  86. package/dist/types/src/util/refs.d.ts +2 -2
  87. package/dist/types/src/util/refs.d.ts.map +1 -1
  88. package/dist/types/tsconfig.tsbuildinfo +1 -1
  89. package/package.json +51 -48
  90. package/src/components/FieldEditor/FieldEditor.stories.tsx +43 -25
  91. package/src/components/FieldEditor/FieldEditor.test.tsx +0 -1
  92. package/src/components/FieldEditor/FieldEditor.tsx +74 -78
  93. package/src/components/Form/AUDIT.md +17 -0
  94. package/src/components/Form/Form.stories.tsx +148 -250
  95. package/src/components/Form/Form.tsx +324 -110
  96. package/src/components/Form/FormField.tsx +304 -0
  97. package/src/components/Form/FormFieldComponent.stories.tsx +65 -0
  98. package/src/components/Form/FormFieldComponent.tsx +171 -0
  99. package/src/components/Form/FormFieldSet.tsx +128 -0
  100. package/src/components/Form/README.md +3 -0
  101. package/src/components/Form/fields/ArrayField.tsx +154 -0
  102. package/src/components/Form/fields/BooleanField.tsx +22 -0
  103. package/src/components/Form/fields/GeoPointField.tsx +120 -0
  104. package/src/components/Form/fields/MarkdownField.tsx +78 -0
  105. package/src/components/Form/fields/NumberField.tsx +39 -0
  106. package/src/components/Form/fields/RefField.tsx +198 -0
  107. package/src/components/Form/fields/SelectField.tsx +65 -0
  108. package/src/components/Form/{custom/SelectOptionsInput.stories.tsx → fields/SelectOptionField.stories.tsx} +19 -17
  109. package/src/components/Form/{custom/SelectOptionsInput.tsx → fields/SelectOptionField.tsx} +29 -24
  110. package/src/components/Form/fields/TextAreaField.tsx +38 -0
  111. package/src/components/Form/fields/TextField.tsx +38 -0
  112. package/src/components/Form/{custom/TupleInput.tsx → fields/TupleField.tsx} +16 -9
  113. package/src/components/Form/fields/index.ts +15 -0
  114. package/src/components/Form/index.ts +3 -4
  115. package/src/components/ObjectPicker/ObjectPicker.stories.tsx +18 -16
  116. package/src/components/ObjectPicker/ObjectPicker.tsx +103 -78
  117. package/src/components/Settings/Settings.stories.tsx +55 -0
  118. package/src/components/Settings/Settings.tsx +129 -0
  119. package/src/components/{ControlSection → Settings}/index.ts +1 -1
  120. package/src/components/ViewEditor/ViewEditor.stories.tsx +47 -45
  121. package/src/components/ViewEditor/ViewEditor.test.tsx +5 -5
  122. package/src/components/ViewEditor/ViewEditor.tsx +297 -210
  123. package/src/components/index.ts +1 -1
  124. package/src/components/testing.tsx +23 -9
  125. package/src/hooks/index.ts +2 -3
  126. package/src/hooks/useFormHandler.ts +380 -0
  127. package/src/hooks/useKeyHandler.tsx +37 -0
  128. package/src/translations.ts +66 -64
  129. package/src/util/field.ts +25 -25
  130. package/src/util/formatting.ts +22 -22
  131. package/src/util/index.ts +1 -1
  132. package/src/util/properties.ts +18 -0
  133. package/src/util/refs.ts +13 -15
  134. package/dist/types/src/components/ControlSection/ControlSection.d.ts +0 -23
  135. package/dist/types/src/components/ControlSection/ControlSection.d.ts.map +0 -1
  136. package/dist/types/src/components/ControlSection/ControlSection.stories.d.ts +0 -83
  137. package/dist/types/src/components/ControlSection/ControlSection.stories.d.ts.map +0 -1
  138. package/dist/types/src/components/ControlSection/index.d.ts +0 -2
  139. package/dist/types/src/components/ControlSection/index.d.ts.map +0 -1
  140. package/dist/types/src/components/Form/ArrayField.d.ts +0 -16
  141. package/dist/types/src/components/Form/ArrayField.d.ts.map +0 -1
  142. package/dist/types/src/components/Form/Defaults.d.ts +0 -14
  143. package/dist/types/src/components/Form/Defaults.d.ts.map +0 -1
  144. package/dist/types/src/components/Form/FormActions.d.ts +0 -9
  145. package/dist/types/src/components/Form/FormActions.d.ts.map +0 -1
  146. package/dist/types/src/components/Form/FormContent.d.ts +0 -63
  147. package/dist/types/src/components/Form/FormContent.d.ts.map +0 -1
  148. package/dist/types/src/components/Form/FormContext.d.ts +0 -23
  149. package/dist/types/src/components/Form/FormContext.d.ts.map +0 -1
  150. package/dist/types/src/components/Form/Input.d.ts +0 -29
  151. package/dist/types/src/components/Form/Input.d.ts.map +0 -1
  152. package/dist/types/src/components/Form/RefField.d.ts +0 -22
  153. package/dist/types/src/components/Form/RefField.d.ts.map +0 -1
  154. package/dist/types/src/components/Form/custom/GeoPointInput.d.ts +0 -4
  155. package/dist/types/src/components/Form/custom/GeoPointInput.d.ts.map +0 -1
  156. package/dist/types/src/components/Form/custom/SelectOptionsInput.d.ts +0 -4
  157. package/dist/types/src/components/Form/custom/SelectOptionsInput.d.ts.map +0 -1
  158. package/dist/types/src/components/Form/custom/SelectOptionsInput.stories.d.ts +0 -78
  159. package/dist/types/src/components/Form/custom/SelectOptionsInput.stories.d.ts.map +0 -1
  160. package/dist/types/src/components/Form/custom/TupleInput.d.ts +0 -6
  161. package/dist/types/src/components/Form/custom/TupleInput.d.ts.map +0 -1
  162. package/dist/types/src/components/Form/custom/index.d.ts +0 -4
  163. package/dist/types/src/components/Form/custom/index.d.ts.map +0 -1
  164. package/dist/types/src/components/Form/factory.d.ts +0 -8
  165. package/dist/types/src/components/Form/factory.d.ts.map +0 -1
  166. package/dist/types/src/hooks/useForm.d.ts +0 -67
  167. package/dist/types/src/hooks/useForm.d.ts.map +0 -1
  168. package/dist/types/src/hooks/useQueryRefOptions.d.ts +0 -29
  169. package/dist/types/src/hooks/useQueryRefOptions.d.ts.map +0 -1
  170. package/dist/types/src/hooks/useRefQueryLookupHandler.d.ts +0 -8
  171. package/dist/types/src/hooks/useRefQueryLookupHandler.d.ts.map +0 -1
  172. package/dist/types/src/util/schema.d.ts +0 -3
  173. package/dist/types/src/util/schema.d.ts.map +0 -1
  174. package/src/components/ControlSection/ControlSection.stories.tsx +0 -38
  175. package/src/components/ControlSection/ControlSection.tsx +0 -153
  176. package/src/components/Form/ArrayField.tsx +0 -125
  177. package/src/components/Form/Defaults.tsx +0 -205
  178. package/src/components/Form/FormActions.tsx +0 -54
  179. package/src/components/Form/FormContent.tsx +0 -362
  180. package/src/components/Form/FormContext.tsx +0 -110
  181. package/src/components/Form/Input.tsx +0 -54
  182. package/src/components/Form/RefField.tsx +0 -283
  183. package/src/components/Form/custom/GeoPointInput.tsx +0 -80
  184. package/src/components/Form/custom/index.ts +0 -7
  185. package/src/components/Form/factory.tsx +0 -31
  186. package/src/hooks/useForm.ts +0 -296
  187. package/src/hooks/useQueryRefOptions.ts +0 -62
  188. package/src/hooks/useRefQueryLookupHandler.ts +0 -39
  189. package/src/util/schema.ts +0 -12
@@ -2,6 +2,5 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- export * from './useForm';
6
- export * from './useRefQueryLookupHandler';
7
- export * from './useQueryRefOptions';
5
+ export * from './useFormHandler';
6
+ export * from './useKeyHandler';
@@ -0,0 +1,380 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { useControllableState } from '@radix-ui/react-use-controllable-state';
6
+ import type * as Schema from 'effect/Schema';
7
+ import type * as SchemaAST from 'effect/SchemaAST';
8
+ import { useCallback, useEffect, useMemo, useState } from 'react';
9
+
10
+ import { type AnyProperties } from '@dxos/echo/internal';
11
+ import { type JsonPath, createJsonPath, fromEffectValidationPath, getValue as getValue$ } from '@dxos/effect';
12
+ import { log } from '@dxos/log';
13
+ import { useDefaultValue } from '@dxos/react-ui';
14
+ import { type ValidationError, validateSchema } from '@dxos/schema';
15
+ import { type MaybePromise } from '@dxos/util';
16
+
17
+ export type FormFieldStatus = {
18
+ status?: 'error';
19
+ error?: string;
20
+ };
21
+
22
+ /**
23
+ * Form properties.
24
+ */
25
+ export interface FormHandlerProps<T extends AnyProperties> {
26
+ /**
27
+ * Effect schema (Type literal).
28
+ */
29
+ schema?: Schema.Schema<T, any>;
30
+
31
+ /**
32
+ * Values for the form if controlled.
33
+ */
34
+ values?: Partial<T>;
35
+
36
+ /**
37
+ * Default values for the form which will be used if values is not provided.
38
+ */
39
+ defaultValues?: Partial<T>;
40
+
41
+ /**
42
+ * Auto-save the form when the values change.
43
+ */
44
+ autoSave?: boolean;
45
+
46
+ /**
47
+ * Callback for value changes. Note: This is called even when values are invalid.
48
+ * Sometimes the parent component may want to know about changes even if the form is
49
+ * in an invalid state.
50
+ */
51
+ onValuesChanged?: (values: Partial<T>, meta: FormUpdateMeta<T>) => void;
52
+
53
+ /**
54
+ * Custom validation function that runs only after schema validation passes.
55
+ * Use this for complex validation logic that can't be expressed in the schema.
56
+ * @returns Array of validation errors, or undefined if validation passes
57
+ */
58
+ onValidate?: (values: T) => ValidationError[] | undefined;
59
+
60
+ /**
61
+ * Called when the form is submitted and passes validation.
62
+ */
63
+ onSave?: (values: T, meta: FormUpdateMeta<T>) => MaybePromise<void>;
64
+
65
+ /**
66
+ * Called when the form is canceled.
67
+ */
68
+ onCancel?: () => void;
69
+ }
70
+
71
+ export type FormUpdateMeta<T extends AnyProperties> = {
72
+ changed: FormHandler<T>['changed'];
73
+ isValid: boolean;
74
+ };
75
+
76
+ /**
77
+ * Form handler properties and methods.
78
+ */
79
+ export type FormHandler<T extends AnyProperties> = Pick<FormHandlerProps<T>, 'schema' | 'autoSave'> & {
80
+ /** Initial values (which may not pass validation). */
81
+ values: Partial<T>;
82
+
83
+ /** Map of changed fields. */
84
+ changed: Record<JsonPath, boolean>;
85
+ // TODO(burdon): How is this different from above?
86
+ touched: Record<JsonPath, boolean>;
87
+
88
+ /** Map of error strings. */
89
+ errors: Record<JsonPath, string>;
90
+
91
+ /** Whether the form can be saved (i.e., data is valid). */
92
+ isValid: boolean;
93
+ // TODO(burdon): Why is this needed separately from isValid?
94
+ canSave: boolean;
95
+
96
+ onSave: () => void;
97
+ onCancel: () => void;
98
+
99
+ //
100
+ // Form field state management
101
+ //
102
+
103
+ getStatus: (path: string | (string | number)[]) => FormFieldStatus;
104
+ getValue: <V>(path: (string | number)[]) => V | undefined;
105
+ onBlur: (path: (string | number)[]) => void;
106
+ onValueChange: <V>(path: (string | number)[], type: SchemaAST.AST, value: V) => void;
107
+ };
108
+
109
+ /**
110
+ * Creates a hook for managing form state, including values, validation, and submission.
111
+ * Deeply integrated with `@dxos/schema` for schema-based validation.
112
+ */
113
+ export const useFormHandler = <T extends AnyProperties>({
114
+ schema,
115
+ autoSave,
116
+ values: valuesProp,
117
+ defaultValues: defaultValuesProp,
118
+ onValuesChanged,
119
+ onValidate,
120
+ onSave,
121
+ onCancel,
122
+ ...props
123
+ }: FormHandlerProps<T>): FormHandler<T> => {
124
+ const [changed, setChanged] = useState<Record<JsonPath, boolean>>({});
125
+ const [touched, setTouched] = useState<Record<JsonPath, boolean>>({});
126
+ const [errors, setErrors] = useState<Record<JsonPath, string>>({});
127
+ const [saving, setSaving] = useState(false);
128
+ const defaultValues = useDefaultValue<Partial<T>>(defaultValuesProp, () => ({}));
129
+ const [values$, setValues] = useControllableState<Partial<T>>({
130
+ prop: valuesProp,
131
+ defaultProp: defaultValues,
132
+ onChange: () => {
133
+ // Only reset when controlled: parent passed new values.
134
+ // Uncontrolled updates come from setValues in onValueChange.
135
+ if (valuesProp !== undefined) {
136
+ setValues(valuesProp ?? defaultValues);
137
+ setChanged({});
138
+ setTouched({});
139
+ setErrors({});
140
+ setSaving(false);
141
+ }
142
+ },
143
+ });
144
+ // TODO(wittjosiah): Upgrade @radix-ui/react-use-controllable-state.
145
+ const values = values$ as Partial<T>;
146
+
147
+ // Validate.
148
+ const validate = useCallback(
149
+ (values: Partial<T>): values is T => {
150
+ if (!schema) {
151
+ return false;
152
+ }
153
+
154
+ let errors: ValidationError[] = validateSchema(schema, values) ?? [];
155
+ log('validate', { values, errors });
156
+ if (errors.length === 0 && onValidate) {
157
+ const validatedValues = values as T;
158
+ errors = onValidate(validatedValues) ?? [];
159
+ }
160
+
161
+ setErrors(flatMap(errors));
162
+ const valid = errors.length === 0;
163
+ return valid;
164
+ },
165
+ [schema, onValidate],
166
+ );
167
+
168
+ // Validate on schema change.
169
+ const [schemaChanged, setSchemaChanged] = useState(false);
170
+ useEffect(() => setSchemaChanged(true), [schema]);
171
+ useEffect(() => {
172
+ if (schemaChanged) {
173
+ validate(values);
174
+ setSchemaChanged(false);
175
+ }
176
+ }, [validate, values, schemaChanged]);
177
+
178
+ const isValid = useMemo(() => {
179
+ return Object.keys(errors).length === 0;
180
+ }, [errors]);
181
+
182
+ /**
183
+ * NOTE: We can submit if there is no touched field that has an error.
184
+ * If there's a validation message visible in the form, submit should be disabled.
185
+ */
186
+ const canSave = useMemo(
187
+ () =>
188
+ !saving &&
189
+ // Check if any error paths that are touched have errors.
190
+ !Object.entries(touched).some(
191
+ ([path, isTouched]) =>
192
+ isTouched &&
193
+ Object.keys(errors).some(
194
+ (errorPath) => errorPath === path || errorPath.startsWith(`${path}.`) || errorPath.startsWith(`${path}[`),
195
+ ),
196
+ ),
197
+ [touched, errors, saving],
198
+ );
199
+
200
+ const handleSave = useCallback(async () => {
201
+ if (validate(values)) {
202
+ setSaving(true);
203
+ try {
204
+ await onSave?.(values, { changed, isValid });
205
+ } finally {
206
+ setSaving(false);
207
+ }
208
+ }
209
+ }, [values, validate, onSave, changed, isValid]);
210
+
211
+ const handleCancel = useCallback(() => {
212
+ onCancel?.();
213
+ }, [onCancel]);
214
+
215
+ //
216
+ // Fields.
217
+ //
218
+
219
+ const getStatus = useCallback<FormHandler<T>['getStatus']>(
220
+ (path) => {
221
+ const jsonPath = Array.isArray(path) ? createJsonPath(path) : path;
222
+ const [_, error] =
223
+ Object.entries(errors).find(
224
+ ([errorPath]) =>
225
+ errorPath === jsonPath || errorPath.startsWith(`${jsonPath}.`) || errorPath.startsWith(`${jsonPath}[`),
226
+ ) ?? [];
227
+
228
+ // Only show errors for touched fields.
229
+ const isTouched = touched[jsonPath as JsonPath];
230
+ if (!isTouched) {
231
+ return {
232
+ status: undefined,
233
+ error: undefined,
234
+ };
235
+ }
236
+
237
+ return {
238
+ status: error ? 'error' : undefined,
239
+ error: error ? (error ?? undefined) : undefined,
240
+ };
241
+ },
242
+ [errors, touched],
243
+ );
244
+
245
+ const getValue = useCallback<FormHandler<T>['getValue']>(
246
+ (path) => {
247
+ return getValue$(values, createJsonPath(path));
248
+ },
249
+ [values],
250
+ );
251
+
252
+ const onValueChange = useCallback<FormHandler<T>['onValueChange']>(
253
+ (path, type, value) => {
254
+ log('onValueChange', { path, value });
255
+
256
+ const jsonPath = createJsonPath(path);
257
+ const pathArray = path;
258
+ let parsedValue = value as any;
259
+ try {
260
+ if (type._tag === 'NumberKeyword') {
261
+ parsedValue = parseFloat(value as string) || 0;
262
+ }
263
+ } catch (err) {
264
+ log.catch(err);
265
+ parsedValue = undefined;
266
+ }
267
+
268
+ // Create merged values for validation and callback. Form never mutates; parent applies via onValuesChanged.
269
+ const newValues = mergeAtPath(values, pathArray as (string | number)[], parsedValue) as Partial<T>;
270
+
271
+ // TODO(burdon): Check value has changed from original.
272
+ const newChanged = { [jsonPath]: true };
273
+ setChanged((prev) => ({ ...prev, ...newChanged }));
274
+
275
+ // Validate.
276
+ const isValid = validate(newValues);
277
+
278
+ // Notify parent; parent is responsible for applying the change.
279
+ onValuesChanged?.(newValues, { isValid, changed: newChanged });
280
+
281
+ // For uncontrolled mode, update internal state. Controlled mode relies on parent to pass new values.
282
+ if (valuesProp === undefined) {
283
+ setValues(newValues);
284
+ }
285
+ },
286
+ [values, validate, onValuesChanged, valuesProp],
287
+ );
288
+
289
+ const onBlur = useCallback(
290
+ async (path: (string | number)[]) => {
291
+ const jsonPath = createJsonPath(path);
292
+
293
+ // TODO(burdon): Check value has changed from original.
294
+ setTouched((touched) => ({ ...touched, [jsonPath]: true }));
295
+ const isValid = validate(values);
296
+
297
+ // Auto-save when a field is blurred and is valid.
298
+ if (Object.keys(changed).length > 0 && isValid && autoSave) {
299
+ await onSave?.(values as T, { changed, isValid });
300
+ }
301
+ },
302
+ [validate, values, changed, autoSave, onSave],
303
+ );
304
+
305
+ return useMemo<FormHandler<T>>(
306
+ () => ({
307
+ // State.
308
+ schema,
309
+ values,
310
+ errors,
311
+ touched,
312
+ changed,
313
+ isValid,
314
+ canSave,
315
+ autoSave,
316
+
317
+ // Actions.
318
+ onSave: handleSave,
319
+ onCancel: handleCancel,
320
+
321
+ // Field utils.
322
+ getStatus,
323
+ getValue,
324
+ onBlur,
325
+ onValueChange,
326
+
327
+ ...props,
328
+ }),
329
+ [
330
+ schema,
331
+ values,
332
+ errors,
333
+ touched,
334
+ changed,
335
+ canSave,
336
+ isValid,
337
+ getStatus,
338
+ getValue,
339
+ onBlur,
340
+ onValueChange,
341
+ onSave,
342
+ onCancel,
343
+ ],
344
+ );
345
+ };
346
+
347
+ /**
348
+ * Creates a new object with value at path. Does not mutate source.
349
+ * Preserves arrays when path segments are numeric indices.
350
+ */
351
+ const mergeAtPath = (obj: any, path: readonly (string | number)[], value: any): any => {
352
+ if (path.length === 0) {
353
+ return value;
354
+ }
355
+
356
+ const [head, ...rest] = path;
357
+ const child = rest.length === 0 ? value : mergeAtPath(obj?.[head], rest, value);
358
+
359
+ if (Array.isArray(obj)) {
360
+ const copy = [...obj];
361
+ copy[head as number] = child;
362
+ return copy;
363
+ }
364
+
365
+ return { ...obj, [head]: child };
366
+ };
367
+
368
+ const flatMap = (errors: ValidationError[]) => {
369
+ return errors.reduce(
370
+ (result, { path, message }) => {
371
+ // Convert the validation error path format to our JsonPath format.
372
+ const jsonPath = fromEffectValidationPath(path);
373
+ if (!(jsonPath in result)) {
374
+ result[jsonPath] = message;
375
+ }
376
+ return result;
377
+ },
378
+ {} as Record<JsonPath, string>,
379
+ );
380
+ };
@@ -0,0 +1,37 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { type RefObject, useCallback, useLayoutEffect } from 'react';
6
+
7
+ import { addEventListener } from '@dxos/async';
8
+
9
+ import { type FormHandler } from './useFormHandler';
10
+
11
+ /**
12
+ * Key handler.
13
+ */
14
+ export const useKeyHandler = (elRef: RefObject<HTMLDivElement | null>, form: FormHandler<any>) => {
15
+ const handleKeyDown = useCallback(
16
+ (event: KeyboardEvent) => {
17
+ switch (event.key) {
18
+ case 'Enter': {
19
+ if (event.metaKey && form.canSave) {
20
+ form.onSave();
21
+ }
22
+ break;
23
+ }
24
+ }
25
+ },
26
+ [form.isValid, form.canSave, form.onSave, form.autoSave],
27
+ );
28
+
29
+ useLayoutEffect(() => {
30
+ const el = elRef.current;
31
+ if (!el) {
32
+ return;
33
+ }
34
+
35
+ return addEventListener(el, 'keydown', handleKeyDown);
36
+ }, [elRef, handleKeyDown]);
37
+ };
@@ -4,82 +4,84 @@
4
4
 
5
5
  import { type Resource } from '@dxos/react-ui';
6
6
 
7
- export const translationKey = 'react-ui-form';
7
+ export const translationKey = '@dxos/react-ui-form';
8
8
 
9
9
  export const translations = [
10
10
  {
11
11
  'en-US': {
12
12
  [translationKey]: {
13
- 'fields label': 'Fields',
14
- 'hidden fields label': 'Hidden Fields',
15
- 'empty readonly ref field label': '(none)',
13
+ 'fields.label': 'Fields',
14
+ 'hidden-fields.label': 'Hidden Fields',
15
+ 'empty-readonly-ref-field.label': '(none)',
16
16
 
17
- // TODO(burdon): Standardize field/property.
18
- 'add property button': 'Add property',
19
- 'field property label': 'Property',
20
- 'field property placeholder': 'Property name',
21
- 'field format label': 'Type',
22
- 'field path label': 'Field path',
23
- 'add field': 'Add field',
24
- 'delete field': 'Delete field',
25
- 'field limit reached': 'Maximum number of fields reached',
26
- 'boolean input true value': 'Yes',
27
- 'boolean input false value': 'No',
28
- 'show field label': 'Show field',
29
- 'hide field label': 'Hide field',
30
- 'delete field label': 'Delete field',
31
- 'ref field combobox input placeholder': 'Search…',
32
- 'ref field placeholder_one': 'Select…',
33
- 'ref field placeholder_other': 'Select items…',
17
+ 'add-property-button.label': 'Add property',
18
+ 'field-property.label': 'Property',
19
+ 'field-property.placeholder': 'Property name',
20
+ 'field-format.label': 'Type',
21
+ 'field-path.label': 'Field path',
22
+ 'add-field.button': 'Add field',
23
+ 'boolean-input-true.value': 'Yes',
24
+ 'boolean-input-false.value': 'No',
25
+ 'show-field.label': 'Show field',
26
+ 'hide-field.label': 'Hide field',
27
+ 'delete-field.label': 'Delete field',
28
+ 'ref-field-combobox-input.placeholder': 'Search…',
29
+ 'ref-field.placeholder': 'Select…',
30
+ 'ref-field.placeholder_one': 'Select…',
31
+ 'ref-field.placeholder_other': 'Select items…',
32
+ 'create-option.label': 'Create',
34
33
 
35
- // TODO(burdon): Factor out?
36
- 'save button': 'Save',
34
+ 'example.placeholder': 'Example',
35
+ 'latitude.placeholder': 'Latitude (e.g., 40.7128)',
36
+ 'longitude.placeholder': 'Longitude (e.g., -74.0060)',
37
37
 
38
- // FormatEnum
39
- 'format boolean': 'Boolean',
40
- 'format currency': 'Currency',
41
- 'format date': 'Date',
42
- 'format date-time': 'DateTime',
43
- 'format did': 'DID',
44
- 'format duration': 'Duration',
45
- 'format dxn': 'DXN',
46
- 'format email': 'Email',
47
- 'format formula': 'Formula',
48
- 'format hostname': 'Hostname',
49
- 'format integer': 'Integer',
50
- 'format json': 'JSON',
51
- 'format lnglat': 'Geopoint',
52
- 'format markdown': 'Markdown',
53
- 'format percent': 'Percent',
54
- 'format ref': 'Reference',
55
- 'format regex': 'RegExp',
56
- 'format string': 'String',
57
- 'format single-select': 'Select',
58
- 'format multi-select': 'Multi-select',
59
- 'format text': 'Long text',
60
- 'format time': 'Time',
61
- 'format timestamp': 'Timestamp',
62
- 'format user': 'User',
63
- 'format number': 'Number',
64
- 'format uri': 'URI',
65
- 'format url': 'URL',
66
- 'format uuid': 'UUID',
38
+ 'cancel-button.label': 'Cancel',
39
+ 'save-button.label': 'Save',
67
40
 
68
- // GeoPointInput.
69
- 'latitude label': 'Latitude',
70
- 'longitude label': 'Longitude',
41
+ // TypeFormat
42
+ 'format.boolean.label': 'Boolean',
43
+ 'format.currency.label': 'Currency',
44
+ 'format.date.label': 'Date',
45
+ 'format.date-time.label': 'DateTime',
46
+ 'format.did.label': 'DID',
47
+ 'format.duration.label': 'Duration',
48
+ 'format.dxn.label': 'DXN',
49
+ 'format.email.label': 'Email',
50
+ 'format.formula.label': 'Formula',
51
+ 'format.hostname.label': 'Hostname',
52
+ 'format.integer.label': 'Integer',
53
+ 'format.json.label': 'JSON',
54
+ 'format.lnglat.label': 'Geopoint',
55
+ 'format.markdown.label': 'Markdown',
56
+ 'format.percent.label': 'Percent',
57
+ 'format.ref.label': 'Reference',
58
+ 'format.regex.label': 'RegExp',
59
+ 'format.string.label': 'String',
60
+ 'format.single-select.label': 'Select',
61
+ 'format.multi-select.label': 'Multi-select',
62
+ 'format.text.label': 'Long text',
63
+ 'format.time.label': 'Time',
64
+ 'format.timestamp.label': 'Timestamp',
65
+ 'format.user.label': 'User',
66
+ 'format.number.label': 'Number',
67
+ 'format.uri.label': 'URI',
68
+ 'format.url.label': 'URL',
69
+ 'format.uuid.label': 'UUID',
71
70
 
72
- // SelectOptionsInput.
73
- 'select option label': 'Label',
74
- 'select option label placeholder': 'Option label',
75
- 'select option color': 'Color',
76
- 'select option delete': 'Delete',
77
- 'select option add': 'Add option',
71
+ // GeoPointField.
72
+ 'latitude.label': 'Latitude',
73
+ 'longitude.label': 'Longitude',
74
+
75
+ // SelectOptionsField.
76
+ 'select-option.label': 'Label',
77
+ 'select-option-label.placeholder': 'Option label',
78
+ 'select-option-delete.button': 'Delete',
79
+ 'select-option-add.button': 'Add option',
78
80
 
79
81
  // System schema message.
80
- 'system schema title': 'System record type',
81
- 'system schema description':
82
- 'This is a system record type and cannot be modified, though the view can still be configured.',
82
+ 'system-schema.title': 'System type',
83
+ 'system-schema.description': 'System type: cannot add or remove fields.',
84
+ 'remove.button': 'Remove',
83
85
  },
84
86
  },
85
87
  },
package/src/util/field.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  // Copyright 2024 DXOS.org
3
3
  //
4
4
 
5
- import { FormatEnum, GeoLocation, TypeEnum } from '@dxos/echo/internal';
5
+ import { Format, GeoLocation, TypeEnum } from '@dxos/echo/internal';
6
6
  import { type ValidationError } from '@dxos/schema';
7
7
 
8
8
  /**
@@ -13,7 +13,7 @@ import { type ValidationError } from '@dxos/schema';
13
13
  */
14
14
  export type ParseProps = {
15
15
  type?: TypeEnum;
16
- format?: FormatEnum;
16
+ format?: Format.TypeFormat;
17
17
  value: any;
18
18
  };
19
19
 
@@ -57,31 +57,31 @@ export const parseValue = ({ type, format, value }: ParseProps) => {
57
57
  }
58
58
 
59
59
  switch (format) {
60
- case FormatEnum.Boolean:
60
+ case Format.TypeFormat.Boolean:
61
61
  return parseScalar(TypeEnum.Boolean);
62
62
 
63
- case FormatEnum.Number:
64
- case FormatEnum.Percent:
65
- case FormatEnum.Currency:
63
+ case Format.TypeFormat.Number:
64
+ case Format.TypeFormat.Percent:
65
+ case Format.TypeFormat.Currency:
66
66
  return parseScalar(TypeEnum.Number);
67
67
 
68
- case FormatEnum.String:
69
- case FormatEnum.Markdown: {
68
+ case Format.TypeFormat.String:
69
+ case Format.TypeFormat.Markdown: {
70
70
  return parseScalar(TypeEnum.String);
71
71
  }
72
72
 
73
- case FormatEnum.Ref:
74
- throw new Error(`unexpected format: ${FormatEnum.Ref}`);
73
+ case Format.TypeFormat.Ref:
74
+ throw new Error(`unexpected format: ${Format.TypeFormat.Ref}`);
75
75
 
76
- case FormatEnum.DateTime:
77
- case FormatEnum.Date:
78
- case FormatEnum.Time:
79
- case FormatEnum.Timestamp: {
76
+ case Format.TypeFormat.DateTime:
77
+ case Format.TypeFormat.Date:
78
+ case Format.TypeFormat.Time:
79
+ case Format.TypeFormat.Timestamp: {
80
80
  const date = new Date(value as string | number);
81
81
  return isNaN(date.getTime()) ? null : date;
82
82
  }
83
83
 
84
- case FormatEnum.GeoPoint: {
84
+ case Format.TypeFormat.GeoPoint: {
85
85
  // Parse string in format "lat,long" to GeoPoint [longitude, latitude].
86
86
  if (typeof value === 'string') {
87
87
  // Only keep digits, decimal points, minus signs, and commas.
@@ -108,23 +108,23 @@ export const parseValue = ({ type, format, value }: ParseProps) => {
108
108
  // TODO(burdon): Type and format.
109
109
  export type CellClassesForFieldTypeProps = {
110
110
  type?: TypeEnum;
111
- format?: FormatEnum;
111
+ format?: Format.TypeFormat;
112
112
  };
113
113
 
114
114
  export const cellClassesForFieldType = ({ type, format }: CellClassesForFieldTypeProps): string[] | undefined => {
115
115
  switch (format || type) {
116
- case FormatEnum.Markdown:
116
+ case Format.TypeFormat.Markdown:
117
117
  return undefined;
118
- case FormatEnum.Time:
119
- case FormatEnum.Timestamp:
120
- case FormatEnum.DateTime:
121
- case FormatEnum.Date:
122
- case FormatEnum.Duration:
118
+ case Format.TypeFormat.Time:
119
+ case Format.TypeFormat.Timestamp:
120
+ case Format.TypeFormat.DateTime:
121
+ case Format.TypeFormat.Date:
122
+ case Format.TypeFormat.Duration:
123
123
  return ['font-mono', 'text-right'];
124
- case FormatEnum.Currency:
124
+ case Format.TypeFormat.Currency:
125
125
  return ['text-right'];
126
- case FormatEnum.JSON:
127
- case FormatEnum.DID:
126
+ case Format.TypeFormat.JSON:
127
+ case Format.TypeFormat.DID:
128
128
  return ['font-mono'];
129
129
  case TypeEnum.Number:
130
130
  case TypeEnum.Boolean: