@dxos/react-ui-form 0.8.4-main.ae835ea → 0.8.4-main.bc674ce

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 (177) hide show
  1. package/dist/lib/browser/index.mjs +2182 -2231
  2. package/dist/lib/browser/index.mjs.map +4 -4
  3. package/dist/lib/browser/meta.json +1 -1
  4. package/dist/lib/node-esm/index.mjs +2182 -2231
  5. package/dist/lib/node-esm/index.mjs.map +4 -4
  6. package/dist/lib/node-esm/meta.json +1 -1
  7. package/dist/types/src/components/ControlSection/ControlSection.d.ts +2 -2
  8. package/dist/types/src/components/ControlSection/ControlSection.d.ts.map +1 -1
  9. package/dist/types/src/components/ControlSection/ControlSection.stories.d.ts +11 -8
  10. package/dist/types/src/components/ControlSection/ControlSection.stories.d.ts.map +1 -1
  11. package/dist/types/src/components/FieldEditor/FieldEditor.d.ts +6 -5
  12. package/dist/types/src/components/FieldEditor/FieldEditor.d.ts.map +1 -1
  13. package/dist/types/src/components/FieldEditor/FieldEditor.stories.d.ts +13 -7
  14. package/dist/types/src/components/FieldEditor/FieldEditor.stories.d.ts.map +1 -1
  15. package/dist/types/src/components/Form/Form-old.stories.d.ts +131 -0
  16. package/dist/types/src/components/Form/Form-old.stories.d.ts.map +1 -0
  17. package/dist/types/src/components/Form/Form.d.ts +81 -26
  18. package/dist/types/src/components/Form/Form.d.ts.map +1 -1
  19. package/dist/types/src/components/Form/Form.stories.d.ts +59 -84
  20. package/dist/types/src/components/Form/Form.stories.d.ts.map +1 -1
  21. package/dist/types/src/components/Form/FormField.d.ts +37 -0
  22. package/dist/types/src/components/Form/FormField.d.ts.map +1 -0
  23. package/dist/types/src/components/Form/FormFieldComponent.d.ts +78 -0
  24. package/dist/types/src/components/Form/FormFieldComponent.d.ts.map +1 -0
  25. package/dist/types/src/components/Form/FormFieldComponent.stories.d.ts +9 -0
  26. package/dist/types/src/components/Form/FormFieldComponent.stories.d.ts.map +1 -0
  27. package/dist/types/src/components/Form/FormFieldSet.d.ts +19 -0
  28. package/dist/types/src/components/Form/FormFieldSet.d.ts.map +1 -0
  29. package/dist/types/src/components/Form/fields/ArrayField.d.ts +18 -0
  30. package/dist/types/src/components/Form/fields/ArrayField.d.ts.map +1 -0
  31. package/dist/types/src/components/Form/fields/BooleanField.d.ts +4 -0
  32. package/dist/types/src/components/Form/fields/BooleanField.d.ts.map +1 -0
  33. package/dist/types/src/components/Form/fields/GeoPointField.d.ts +5 -0
  34. package/dist/types/src/components/Form/fields/GeoPointField.d.ts.map +1 -0
  35. package/dist/types/src/components/Form/fields/MarkdownField.d.ts +4 -0
  36. package/dist/types/src/components/Form/fields/MarkdownField.d.ts.map +1 -0
  37. package/dist/types/src/components/Form/fields/NumberField.d.ts +4 -0
  38. package/dist/types/src/components/Form/fields/NumberField.d.ts.map +1 -0
  39. package/dist/types/src/components/Form/fields/RefField.d.ts +14 -0
  40. package/dist/types/src/components/Form/fields/RefField.d.ts.map +1 -0
  41. package/dist/types/src/components/Form/fields/SelectField.d.ts +10 -0
  42. package/dist/types/src/components/Form/fields/SelectField.d.ts.map +1 -0
  43. package/dist/types/src/components/Form/fields/SelectOptionField.d.ts +5 -0
  44. package/dist/types/src/components/Form/fields/SelectOptionField.d.ts.map +1 -0
  45. package/dist/types/src/components/Form/{custom/SelectOptionsInput.stories.d.ts → fields/SelectOptionField.stories.d.ts} +10 -7
  46. package/dist/types/src/components/Form/fields/SelectOptionField.stories.d.ts.map +1 -0
  47. package/dist/types/src/components/Form/fields/TextAreaField.d.ts +4 -0
  48. package/dist/types/src/components/Form/fields/TextAreaField.d.ts.map +1 -0
  49. package/dist/types/src/components/Form/fields/TextField.d.ts +4 -0
  50. package/dist/types/src/components/Form/fields/TextField.d.ts.map +1 -0
  51. package/dist/types/src/components/Form/fields/TupleField.d.ts +6 -0
  52. package/dist/types/src/components/Form/fields/TupleField.d.ts.map +1 -0
  53. package/dist/types/src/components/Form/fields/index.d.ts +12 -0
  54. package/dist/types/src/components/Form/fields/index.d.ts.map +1 -0
  55. package/dist/types/src/components/Form/index.d.ts +2 -4
  56. package/dist/types/src/components/Form/index.d.ts.map +1 -1
  57. package/dist/types/src/components/ObjectPicker/ObjectPicker.d.ts +14 -9
  58. package/dist/types/src/components/ObjectPicker/ObjectPicker.d.ts.map +1 -1
  59. package/dist/types/src/components/ObjectPicker/ObjectPicker.stories.d.ts +9 -6
  60. package/dist/types/src/components/ObjectPicker/ObjectPicker.stories.d.ts.map +1 -1
  61. package/dist/types/src/components/ViewEditor/ViewEditor.d.ts +11 -13
  62. package/dist/types/src/components/ViewEditor/ViewEditor.d.ts.map +1 -1
  63. package/dist/types/src/components/ViewEditor/ViewEditor.stories.d.ts +12 -9
  64. package/dist/types/src/components/ViewEditor/ViewEditor.stories.d.ts.map +1 -1
  65. package/dist/types/src/components/testing.d.ts +0 -2
  66. package/dist/types/src/components/testing.d.ts.map +1 -1
  67. package/dist/types/src/hooks/index.d.ts +2 -3
  68. package/dist/types/src/hooks/index.d.ts.map +1 -1
  69. package/dist/types/src/hooks/useFormHandler.d.ts +82 -0
  70. package/dist/types/src/hooks/useFormHandler.d.ts.map +1 -0
  71. package/dist/types/src/hooks/useKeyHandler.d.ts +6 -0
  72. package/dist/types/src/hooks/useKeyHandler.d.ts.map +1 -0
  73. package/dist/types/src/translations.d.ts +10 -7
  74. package/dist/types/src/translations.d.ts.map +1 -1
  75. package/dist/types/src/util/echo.d.ts +6 -0
  76. package/dist/types/src/util/echo.d.ts.map +1 -0
  77. package/dist/types/src/util/field.d.ts +3 -3
  78. package/dist/types/src/util/field.d.ts.map +1 -1
  79. package/dist/types/src/util/formatting.d.ts +2 -2
  80. package/dist/types/src/util/formatting.d.ts.map +1 -1
  81. package/dist/types/src/util/index.d.ts +2 -1
  82. package/dist/types/src/util/index.d.ts.map +1 -1
  83. package/dist/types/src/util/properties.d.ts +7 -0
  84. package/dist/types/src/util/properties.d.ts.map +1 -0
  85. package/dist/types/src/util/refs.d.ts +1 -2
  86. package/dist/types/src/util/refs.d.ts.map +1 -1
  87. package/dist/types/tsconfig.tsbuildinfo +1 -1
  88. package/package.json +49 -43
  89. package/src/components/ControlSection/ControlSection.stories.tsx +1 -1
  90. package/src/components/ControlSection/ControlSection.tsx +8 -8
  91. package/src/components/FieldEditor/FieldEditor.stories.tsx +42 -21
  92. package/src/components/FieldEditor/FieldEditor.tsx +73 -76
  93. package/src/components/Form/Form-old.stories.tsx +314 -0
  94. package/src/components/Form/Form.stories.tsx +148 -248
  95. package/src/components/Form/Form.tsx +320 -108
  96. package/src/components/Form/FormField.tsx +286 -0
  97. package/src/components/Form/FormFieldComponent.stories.tsx +65 -0
  98. package/src/components/Form/FormFieldComponent.tsx +174 -0
  99. package/src/components/Form/FormFieldSet.tsx +125 -0
  100. package/src/components/Form/README.md +3 -0
  101. package/src/components/Form/fields/ArrayField.tsx +151 -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 +181 -0
  107. package/src/components/Form/fields/SelectField.tsx +65 -0
  108. package/src/components/Form/{custom/SelectOptionsInput.stories.tsx → fields/SelectOptionField.stories.tsx} +17 -14
  109. package/src/components/Form/{custom/SelectOptionsInput.tsx → fields/SelectOptionField.tsx} +21 -15
  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} +15 -8
  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 +20 -13
  116. package/src/components/ObjectPicker/ObjectPicker.tsx +76 -62
  117. package/src/components/ViewEditor/ViewEditor.stories.tsx +42 -40
  118. package/src/components/ViewEditor/ViewEditor.test.tsx +8 -4
  119. package/src/components/ViewEditor/ViewEditor.tsx +233 -172
  120. package/src/components/testing.tsx +9 -7
  121. package/src/hooks/index.ts +2 -3
  122. package/src/hooks/useFormHandler.ts +362 -0
  123. package/src/hooks/useKeyHandler.tsx +37 -0
  124. package/src/translations.ts +12 -10
  125. package/src/util/echo.ts +25 -0
  126. package/src/util/field.ts +25 -25
  127. package/src/util/formatting.ts +22 -22
  128. package/src/util/index.ts +2 -1
  129. package/src/util/properties.ts +18 -0
  130. package/src/util/refs.ts +11 -17
  131. package/dist/types/src/components/Form/ArrayField.d.ts +0 -16
  132. package/dist/types/src/components/Form/ArrayField.d.ts.map +0 -1
  133. package/dist/types/src/components/Form/Defaults.d.ts +0 -14
  134. package/dist/types/src/components/Form/Defaults.d.ts.map +0 -1
  135. package/dist/types/src/components/Form/FormActions.d.ts +0 -9
  136. package/dist/types/src/components/Form/FormActions.d.ts.map +0 -1
  137. package/dist/types/src/components/Form/FormContent.d.ts +0 -63
  138. package/dist/types/src/components/Form/FormContent.d.ts.map +0 -1
  139. package/dist/types/src/components/Form/FormContext.d.ts +0 -23
  140. package/dist/types/src/components/Form/FormContext.d.ts.map +0 -1
  141. package/dist/types/src/components/Form/Input.d.ts +0 -29
  142. package/dist/types/src/components/Form/Input.d.ts.map +0 -1
  143. package/dist/types/src/components/Form/RefField.d.ts +0 -22
  144. package/dist/types/src/components/Form/RefField.d.ts.map +0 -1
  145. package/dist/types/src/components/Form/custom/GeoPointInput.d.ts +0 -4
  146. package/dist/types/src/components/Form/custom/GeoPointInput.d.ts.map +0 -1
  147. package/dist/types/src/components/Form/custom/SelectOptionsInput.d.ts +0 -4
  148. package/dist/types/src/components/Form/custom/SelectOptionsInput.d.ts.map +0 -1
  149. package/dist/types/src/components/Form/custom/SelectOptionsInput.stories.d.ts.map +0 -1
  150. package/dist/types/src/components/Form/custom/TupleInput.d.ts +0 -6
  151. package/dist/types/src/components/Form/custom/TupleInput.d.ts.map +0 -1
  152. package/dist/types/src/components/Form/custom/index.d.ts +0 -4
  153. package/dist/types/src/components/Form/custom/index.d.ts.map +0 -1
  154. package/dist/types/src/components/Form/factory.d.ts +0 -8
  155. package/dist/types/src/components/Form/factory.d.ts.map +0 -1
  156. package/dist/types/src/hooks/useForm.d.ts +0 -67
  157. package/dist/types/src/hooks/useForm.d.ts.map +0 -1
  158. package/dist/types/src/hooks/useQueryRefOptions.d.ts +0 -29
  159. package/dist/types/src/hooks/useQueryRefOptions.d.ts.map +0 -1
  160. package/dist/types/src/hooks/useRefQueryLookupHandler.d.ts +0 -8
  161. package/dist/types/src/hooks/useRefQueryLookupHandler.d.ts.map +0 -1
  162. package/dist/types/src/util/schema.d.ts +0 -3
  163. package/dist/types/src/util/schema.d.ts.map +0 -1
  164. package/src/components/Form/ArrayField.tsx +0 -125
  165. package/src/components/Form/Defaults.tsx +0 -205
  166. package/src/components/Form/FormActions.tsx +0 -54
  167. package/src/components/Form/FormContent.tsx +0 -322
  168. package/src/components/Form/FormContext.tsx +0 -110
  169. package/src/components/Form/Input.tsx +0 -54
  170. package/src/components/Form/RefField.tsx +0 -283
  171. package/src/components/Form/custom/GeoPointInput.tsx +0 -80
  172. package/src/components/Form/custom/index.ts +0 -7
  173. package/src/components/Form/factory.tsx +0 -31
  174. package/src/hooks/useForm.ts +0 -296
  175. package/src/hooks/useQueryRefOptions.ts +0 -62
  176. package/src/hooks/useRefQueryLookupHandler.ts +0 -39
  177. package/src/util/schema.ts +0 -12
@@ -0,0 +1,362 @@
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 { Obj } from '@dxos/echo';
11
+ import { type AnyProperties } from '@dxos/echo/internal';
12
+ import {
13
+ type JsonPath,
14
+ createJsonPath,
15
+ fromEffectValidationPath,
16
+ getValue as getValue$,
17
+ setValue as setValue$,
18
+ } from '@dxos/effect';
19
+ import { log } from '@dxos/log';
20
+ import { useDefaultValue } from '@dxos/react-ui';
21
+ import { type ValidationError, validateSchema } from '@dxos/schema';
22
+ import { type MaybePromise } from '@dxos/util';
23
+
24
+ import { setValueEchoAware } from '../util';
25
+
26
+ export type FormFieldStatus = {
27
+ status?: 'error';
28
+ error?: string;
29
+ };
30
+
31
+ /**
32
+ * Form properties.
33
+ */
34
+ export interface FormHandlerProps<T extends AnyProperties> {
35
+ /**
36
+ * Effect schema (Type literal).
37
+ */
38
+ schema?: Schema.Schema<T, any>;
39
+
40
+ /**
41
+ * Values for the form if controlled.
42
+ */
43
+ values?: Partial<T>;
44
+
45
+ /**
46
+ * Default values for the form which will be used if values is not provided.
47
+ */
48
+ defaultValues?: Partial<T>;
49
+
50
+ /**
51
+ * Auto-save the form when the values change.
52
+ */
53
+ autoSave?: boolean;
54
+
55
+ /**
56
+ * Callback for value changes. Note: This is called even when values are invalid.
57
+ * Sometimes the parent component may want to know about changes even if the form is
58
+ * in an invalid state.
59
+ */
60
+ onValuesChanged?: (values: Partial<T>, meta: FormUpdateMeta<T>) => void;
61
+
62
+ /**
63
+ * Custom validation function that runs only after schema validation passes.
64
+ * Use this for complex validation logic that can't be expressed in the schema.
65
+ * @returns Array of validation errors, or undefined if validation passes
66
+ */
67
+ onValidate?: (values: T) => ValidationError[] | undefined;
68
+
69
+ /**
70
+ * Called when the form is submitted and passes validation.
71
+ */
72
+ onSave?: (values: T, meta: FormUpdateMeta<T>) => MaybePromise<void>;
73
+
74
+ /**
75
+ * Called when the form is canceled.
76
+ */
77
+ onCancel?: () => void;
78
+ }
79
+
80
+ export type FormUpdateMeta<T extends AnyProperties> = {
81
+ changed: FormHandler<T>['changed'];
82
+ isValid: boolean;
83
+ };
84
+
85
+ /**
86
+ * Form handler properties and methods.
87
+ */
88
+ export type FormHandler<T extends AnyProperties> = Pick<FormHandlerProps<T>, 'schema' | 'autoSave'> & {
89
+ /** Initial values (which may not pass validation). */
90
+ values: Partial<T>;
91
+
92
+ /** Map of changed fields. */
93
+ changed: Record<JsonPath, boolean>;
94
+ // TODO(burdon): How is this different from above?
95
+ touched: Record<JsonPath, boolean>;
96
+
97
+ /** Map of error strings. */
98
+ errors: Record<JsonPath, string>;
99
+
100
+ /** Whether the form can be saved (i.e., data is valid). */
101
+ isValid: boolean;
102
+ // TODO(burdon): Why is this needed separately from isValid?
103
+ canSave: boolean;
104
+
105
+ onSave: () => void;
106
+ onCancel: () => void;
107
+
108
+ //
109
+ // Form field state management
110
+ //
111
+
112
+ getStatus: (path: string | (string | number)[]) => FormFieldStatus;
113
+ getValue: <V>(path: (string | number)[]) => V | undefined;
114
+ onBlur: (path: (string | number)[]) => void;
115
+ onValueChange: <V>(path: (string | number)[], type: SchemaAST.AST, value: V) => void;
116
+ };
117
+
118
+ /**
119
+ * Creates a hook for managing form state, including values, validation, and submission.
120
+ * Deeply integrated with `@dxos/schema` for schema-based validation.
121
+ */
122
+ export const useFormHandler = <T extends AnyProperties>({
123
+ schema,
124
+ autoSave,
125
+ values: valuesProp,
126
+ defaultValues: defaultValuesProp,
127
+ onValuesChanged,
128
+ onValidate,
129
+ onSave,
130
+ onCancel,
131
+ ...props
132
+ }: FormHandlerProps<T>): FormHandler<T> => {
133
+ const [changed, setChanged] = useState<Record<JsonPath, boolean>>({});
134
+ const [touched, setTouched] = useState<Record<JsonPath, boolean>>({});
135
+ const [errors, setErrors] = useState<Record<JsonPath, string>>({});
136
+ const [saving, setSaving] = useState(false);
137
+ const defaultValues = useDefaultValue<Partial<T>>(defaultValuesProp, () => ({}));
138
+ const [values$, setValues] = useControllableState<Partial<T>>({
139
+ prop: valuesProp,
140
+ defaultProp: defaultValues,
141
+ onChange: () => {
142
+ setValues(valuesProp ?? defaultValues);
143
+ setChanged({});
144
+ setTouched({});
145
+ setErrors({});
146
+ setSaving(false);
147
+ },
148
+ });
149
+ // TODO(wittjosiah): Upgrade @radix-ui/react-use-controllable-state.
150
+ const values = values$ as Partial<T>;
151
+
152
+ // Validate.
153
+ const validate = useCallback(
154
+ (values: Partial<T>): values is T => {
155
+ if (!schema) {
156
+ return false;
157
+ }
158
+
159
+ let errors: ValidationError[] = validateSchema(schema, values) ?? [];
160
+ log('validate', { values, errors });
161
+ if (errors.length === 0 && onValidate) {
162
+ const validatedValues = values as T;
163
+ errors = onValidate(validatedValues) ?? [];
164
+ }
165
+
166
+ setErrors(flatMap(errors));
167
+ const valid = errors.length === 0;
168
+ return valid;
169
+ },
170
+ [schema, onValidate],
171
+ );
172
+
173
+ // Validate on schema change.
174
+ const [schemaChanged, setSchemaChanged] = useState(false);
175
+ useEffect(() => setSchemaChanged(true), [schema]);
176
+ useEffect(() => {
177
+ if (schemaChanged) {
178
+ validate(values);
179
+ setSchemaChanged(false);
180
+ }
181
+ }, [validate, values, schemaChanged]);
182
+
183
+ const isValid = useMemo(() => {
184
+ return Object.keys(errors).length === 0;
185
+ }, [errors]);
186
+
187
+ /**
188
+ * NOTE: We can submit if there is no touched field that has an error.
189
+ * If there's a validation message visible in the form, submit should be disabled.
190
+ */
191
+ const canSave = useMemo(
192
+ () =>
193
+ !saving &&
194
+ // Check if any error paths that are touched have errors.
195
+ !Object.entries(touched).some(
196
+ ([path, isTouched]) =>
197
+ isTouched &&
198
+ Object.keys(errors).some(
199
+ (errorPath) => errorPath === path || errorPath.startsWith(`${path}.`) || errorPath.startsWith(`${path}[`),
200
+ ),
201
+ ),
202
+ [touched, errors, saving],
203
+ );
204
+
205
+ const handleSave = useCallback(async () => {
206
+ if (validate(values)) {
207
+ setSaving(true);
208
+ try {
209
+ await onSave?.(values, { changed, isValid });
210
+ } finally {
211
+ setSaving(false);
212
+ }
213
+ }
214
+ }, [values, validate, onSave, changed, isValid]);
215
+
216
+ const handleCancel = useCallback(() => {
217
+ onCancel?.();
218
+ }, [onCancel]);
219
+
220
+ //
221
+ // Fields.
222
+ //
223
+
224
+ const getStatus = useCallback<FormHandler<T>['getStatus']>(
225
+ (path) => {
226
+ const jsonPath = Array.isArray(path) ? createJsonPath(path) : path;
227
+ const [_, error] =
228
+ Object.entries(errors).find(
229
+ ([errorPath]) =>
230
+ errorPath === jsonPath || errorPath.startsWith(`${jsonPath}.`) || errorPath.startsWith(`${jsonPath}[`),
231
+ ) ?? [];
232
+
233
+ // Only show errors for touched fields.
234
+ const isTouched = touched[jsonPath as JsonPath];
235
+ if (!isTouched) {
236
+ return {
237
+ status: undefined,
238
+ error: undefined,
239
+ };
240
+ }
241
+
242
+ return {
243
+ status: error ? 'error' : undefined,
244
+ error: error ? (error ?? undefined) : undefined,
245
+ };
246
+ },
247
+ [errors, touched],
248
+ );
249
+
250
+ const getValue = useCallback<FormHandler<T>['getValue']>(
251
+ (path) => {
252
+ return getValue$(values, createJsonPath(path));
253
+ },
254
+ [values],
255
+ );
256
+
257
+ const onValueChange = useCallback<FormHandler<T>['onValueChange']>(
258
+ (path, type, value) => {
259
+ log('onValueChange', { path, value });
260
+
261
+ const jsonPath = createJsonPath(path);
262
+ let parsedValue = value as any;
263
+ try {
264
+ if (type._tag === 'NumberKeyword') {
265
+ parsedValue = parseFloat(value as string) || 0;
266
+ }
267
+ } catch (err) {
268
+ log.catch(err);
269
+ parsedValue = undefined;
270
+ }
271
+
272
+ // Update.
273
+ // For ECHO objects, mutate in place via Obj.change(); for plain objects, spread to create new reference.
274
+ const newValues = Obj.isObject(values)
275
+ ? (setValueEchoAware(values, jsonPath, parsedValue), values)
276
+ : { ...setValue$(values, jsonPath, parsedValue) };
277
+ setValues(newValues);
278
+
279
+ // TODO(burdon): Check value has changed from original.
280
+ const newChanged = { [jsonPath]: true };
281
+ setChanged({ ...changed, ...newChanged });
282
+
283
+ // Validate.
284
+ const isValid = validate(newValues);
285
+
286
+ // Callback.
287
+ onValuesChanged?.(newValues, { isValid, changed: newChanged });
288
+ },
289
+ [values, changed, validate, onValuesChanged],
290
+ );
291
+
292
+ const onBlur = useCallback(
293
+ async (path: (string | number)[]) => {
294
+ const jsonPath = createJsonPath(path);
295
+
296
+ // TODO(burdon): Check value has changed from original.
297
+ setTouched((touched) => ({ ...touched, [jsonPath]: true }));
298
+ const isValid = validate(values);
299
+
300
+ // Auto-save when a field is blurred and is valid.
301
+ if (Object.keys(changed).length > 0 && isValid && autoSave) {
302
+ await onSave?.(values as T, { changed, isValid });
303
+ }
304
+ },
305
+ [validate, values, changed, autoSave, onSave],
306
+ );
307
+
308
+ return useMemo<FormHandler<T>>(
309
+ () => ({
310
+ // State.
311
+ schema,
312
+ values,
313
+ errors,
314
+ touched,
315
+ changed,
316
+ isValid,
317
+ canSave,
318
+ autoSave,
319
+
320
+ // Actions.
321
+ onSave: handleSave,
322
+ onCancel: handleCancel,
323
+
324
+ // Field utils.
325
+ getStatus,
326
+ getValue,
327
+ onBlur,
328
+ onValueChange,
329
+
330
+ ...props,
331
+ }),
332
+ [
333
+ schema,
334
+ values,
335
+ errors,
336
+ touched,
337
+ changed,
338
+ canSave,
339
+ isValid,
340
+ getStatus,
341
+ getValue,
342
+ onBlur,
343
+ onValueChange,
344
+ onSave,
345
+ onCancel,
346
+ ],
347
+ );
348
+ };
349
+
350
+ const flatMap = (errors: ValidationError[]) => {
351
+ return errors.reduce(
352
+ (result, { path, message }) => {
353
+ // Convert the validation error path format to our JsonPath format.
354
+ const jsonPath = fromEffectValidationPath(path);
355
+ if (!(jsonPath in result)) {
356
+ result[jsonPath] = message;
357
+ }
358
+ return result;
359
+ },
360
+ {} as Record<JsonPath, string>,
361
+ );
362
+ };
@@ -0,0 +1,37 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { useCallback, useEffect } 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 = (formElement: 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
+ useEffect(() => {
30
+ if (!formElement) {
31
+ return;
32
+ }
33
+
34
+ // TODO(burdon): Move to @dxos/dom-util.
35
+ return addEventListener(formElement, 'keydown', handleKeyDown);
36
+ }, [formElement, handleKeyDown]);
37
+ };
@@ -4,7 +4,7 @@
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
  {
@@ -15,7 +15,7 @@ export const translations = [
15
15
  'empty readonly ref field label': '(none)',
16
16
 
17
17
  // TODO(burdon): Standardize field/property.
18
- 'button add property': 'Add property',
18
+ 'add property button label': 'Add property',
19
19
  'field property label': 'Property',
20
20
  'field property placeholder': 'Property name',
21
21
  'field format label': 'Type',
@@ -32,9 +32,12 @@ export const translations = [
32
32
  'ref field placeholder_one': 'Select…',
33
33
  'ref field placeholder_other': 'Select items…',
34
34
 
35
- // TODO(burdon): Factor out?
36
- 'button cancel': 'Cancel',
37
- 'button save': 'Save',
35
+ 'example placeholder': 'Example',
36
+ 'latitude placeholder': 'Latitude (e.g., 40.7128)',
37
+ 'longitude placeholder': 'Longitude (e.g., -74.0060)',
38
+
39
+ 'cancel button label': 'Cancel',
40
+ 'save button label': 'Save',
38
41
 
39
42
  // FormatEnum
40
43
  'format boolean': 'Boolean',
@@ -66,11 +69,11 @@ export const translations = [
66
69
  'format url': 'URL',
67
70
  'format uuid': 'UUID',
68
71
 
69
- // GeoPointInput.
72
+ // GeoPointField.
70
73
  'latitude label': 'Latitude',
71
74
  'longitude label': 'Longitude',
72
75
 
73
- // SelectOptionsInput.
76
+ // SelectOptionsField.
74
77
  'select option label': 'Label',
75
78
  'select option label placeholder': 'Option label',
76
79
  'select option color': 'Color',
@@ -78,9 +81,8 @@ export const translations = [
78
81
  'select option add': 'Add option',
79
82
 
80
83
  // System schema message.
81
- 'system schema title': 'System record type',
82
- 'system schema description':
83
- 'This is a system record type and cannot be modified, though the view can still be configured.',
84
+ 'system schema title': 'System type',
85
+ 'system schema description': 'System type: cannot add or remove fields.',
84
86
  },
85
87
  },
86
88
  },
@@ -0,0 +1,25 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { Obj } from '@dxos/echo';
6
+ import { type JsonPath, setValue as setValuePlain, splitJsonPath } from '@dxos/effect';
7
+
8
+ /**
9
+ * Sets a value on an object, using Obj.change() if it's an ECHO object.
10
+ */
11
+ // TODO(wittjosiah): Consider refactoring Form to not know about ECHO at all.
12
+ // Instead of directly mutating the values object, Form could work with a plain
13
+ // object copy and communicate all mutations through callbacks (e.g., onValuesChanged).
14
+ // The caller would then be responsible for applying changes to ECHO objects via
15
+ // Obj.change(). This would keep Form agnostic to the underlying data layer and
16
+ // avoid coupling react-ui-form to @dxos/echo.
17
+ export const setValueEchoAware = <T extends object>(obj: T, path: JsonPath, value: any): T => {
18
+ if (Obj.isObject(obj)) {
19
+ Obj.change(obj, (mutableObj) => {
20
+ Obj.setValue(mutableObj, splitJsonPath(path), value);
21
+ });
22
+ return obj;
23
+ }
24
+ return setValuePlain(obj, path, value);
25
+ };
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:
@@ -4,11 +4,11 @@
4
4
 
5
5
  import { format as formatDate } from 'date-fns/format';
6
6
 
7
- import { FormatEnum, GeoLocation, TypeEnum } from '@dxos/echo/internal';
7
+ import { Format, GeoLocation, TypeEnum } from '@dxos/echo/internal';
8
8
 
9
9
  type ValueFormatProps = {
10
10
  type: TypeEnum;
11
- format?: FormatEnum | undefined;
11
+ format?: Format.TypeFormat | undefined;
12
12
  value: any;
13
13
  locale?: string | undefined;
14
14
  };
@@ -41,20 +41,20 @@ export const formatForDisplay = ({ type, format, value, locale = undefined }: Va
41
41
  }
42
42
 
43
43
  switch (format) {
44
- case FormatEnum.Boolean: {
44
+ case Format.TypeFormat.Boolean: {
45
45
  return formatScalar(TypeEnum.Boolean);
46
46
  }
47
- case FormatEnum.Number: {
47
+ case Format.TypeFormat.Number: {
48
48
  return formatScalar(TypeEnum.Number);
49
49
  }
50
- case FormatEnum.String:
51
- case FormatEnum.Ref: {
50
+ case Format.TypeFormat.String:
51
+ case Format.TypeFormat.Ref: {
52
52
  return formatScalar(TypeEnum.String);
53
53
  }
54
- case FormatEnum.Percent: {
54
+ case Format.TypeFormat.Percent: {
55
55
  return `${(value as number) * 100}%`;
56
56
  }
57
- case FormatEnum.Currency: {
57
+ case Format.TypeFormat.Currency: {
58
58
  // TODO(burdon): Get from property annotation.
59
59
  return (value as number).toLocaleString(locale, {
60
60
  style: 'currency',
@@ -63,28 +63,28 @@ export const formatForDisplay = ({ type, format, value, locale = undefined }: Va
63
63
  maximumFractionDigits: 2,
64
64
  });
65
65
  }
66
- case FormatEnum.Date: {
66
+ case Format.TypeFormat.Date: {
67
67
  try {
68
68
  return formatDate(new Date(value as number), 'yyyy-MM-dd');
69
69
  } catch (error) {
70
70
  return 'Invalid Date';
71
71
  }
72
72
  }
73
- case FormatEnum.Time: {
73
+ case Format.TypeFormat.Time: {
74
74
  try {
75
75
  return formatDate(new Date(value as number), 'HH:mm:ss');
76
76
  } catch (error) {
77
77
  return 'Invalid Time';
78
78
  }
79
79
  }
80
- case FormatEnum.DateTime: {
80
+ case Format.TypeFormat.DateTime: {
81
81
  try {
82
82
  return formatDate(new Date(value as number), 'yyyy-MM-dd HH:mm:ss');
83
83
  } catch (error) {
84
84
  return 'Invalid DateTime';
85
85
  }
86
86
  }
87
- case FormatEnum.GeoPoint: {
87
+ case Format.TypeFormat.GeoPoint: {
88
88
  if (value === null || value === undefined) {
89
89
  return '';
90
90
  }
@@ -125,31 +125,31 @@ export const formatForEditing = ({ type, format, value, locale = undefined }: Va
125
125
  }
126
126
 
127
127
  switch (format) {
128
- case FormatEnum.Boolean:
129
- case FormatEnum.Number:
130
- case FormatEnum.String:
131
- case FormatEnum.Ref: {
128
+ case Format.TypeFormat.Boolean:
129
+ case Format.TypeFormat.Number:
130
+ case Format.TypeFormat.String:
131
+ case Format.TypeFormat.Ref: {
132
132
  return formatScalar(type);
133
133
  }
134
- case FormatEnum.Percent: {
134
+ case Format.TypeFormat.Percent: {
135
135
  return String(value * 100);
136
136
  }
137
- case FormatEnum.Currency: {
137
+ case Format.TypeFormat.Currency: {
138
138
  return String(value);
139
139
  }
140
- case FormatEnum.DateTime: {
140
+ case Format.TypeFormat.DateTime: {
141
141
  const date = new Date(value as number);
142
142
  return date.toISOString();
143
143
  }
144
- case FormatEnum.Date: {
144
+ case Format.TypeFormat.Date: {
145
145
  const date = new Date(value as number);
146
146
  return date.toISOString().split('T')[0];
147
147
  }
148
- case FormatEnum.Time: {
148
+ case Format.TypeFormat.Time: {
149
149
  const date = new Date(value as number);
150
150
  return date.toISOString().split('T')[1].split('.')[0];
151
151
  }
152
- case FormatEnum.GeoPoint: {
152
+ case Format.TypeFormat.GeoPoint: {
153
153
  // Handle null or undefined
154
154
  if (value === null || value === undefined) {
155
155
  return '';