@dxos/react-ui-form 0.8.4-main.c1de068 → 0.8.4-main.c85a9c8dae

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 (204) hide show
  1. package/README.md +0 -1
  2. package/dist/lib/browser/index.mjs +2314 -2078
  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 +2314 -2078
  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 +82 -5
  11. package/dist/types/src/components/FieldEditor/FieldEditor.stories.d.ts.map +1 -1
  12. package/dist/types/src/components/Form/Form.d.ts +81 -25
  13. package/dist/types/src/components/Form/Form.d.ts.map +1 -1
  14. package/dist/types/src/components/Form/Form.stories.d.ts +127 -55
  15. package/dist/types/src/components/Form/Form.stories.d.ts.map +1 -1
  16. package/dist/types/src/components/Form/FormField.d.ts +37 -0
  17. package/dist/types/src/components/Form/FormField.d.ts.map +1 -0
  18. package/dist/types/src/components/Form/FormFieldComponent.d.ts +78 -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 +19 -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 +14 -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 +46 -0
  53. package/dist/types/src/components/ObjectPicker/ObjectPicker.d.ts.map +1 -0
  54. package/dist/types/src/components/ObjectPicker/ObjectPicker.stories.d.ts +85 -0
  55. package/dist/types/src/components/ObjectPicker/ObjectPicker.stories.d.ts.map +1 -0
  56. package/dist/types/src/components/ObjectPicker/index.d.ts +2 -0
  57. package/dist/types/src/components/ObjectPicker/index.d.ts.map +1 -0
  58. package/dist/types/src/components/Settings/Settings.d.ts +56 -0
  59. package/dist/types/src/components/Settings/Settings.d.ts.map +1 -0
  60. package/dist/types/src/components/Settings/Settings.stories.d.ts +81 -0
  61. package/dist/types/src/components/Settings/Settings.stories.d.ts.map +1 -0
  62. package/dist/types/src/components/Settings/index.d.ts +2 -0
  63. package/dist/types/src/components/Settings/index.d.ts.map +1 -0
  64. package/dist/types/src/components/ViewEditor/ViewEditor.d.ts +22 -10
  65. package/dist/types/src/components/ViewEditor/ViewEditor.d.ts.map +1 -1
  66. package/dist/types/src/components/ViewEditor/ViewEditor.stories.d.ts +84 -8
  67. package/dist/types/src/components/ViewEditor/ViewEditor.stories.d.ts.map +1 -1
  68. package/dist/types/src/components/index.d.ts +2 -2
  69. package/dist/types/src/components/index.d.ts.map +1 -1
  70. package/dist/types/src/components/testing.d.ts +4 -3
  71. package/dist/types/src/components/testing.d.ts.map +1 -1
  72. package/dist/types/src/hooks/index.d.ts +2 -3
  73. package/dist/types/src/hooks/index.d.ts.map +1 -1
  74. package/dist/types/src/hooks/useFormHandler.d.ts +82 -0
  75. package/dist/types/src/hooks/useFormHandler.d.ts.map +1 -0
  76. package/dist/types/src/hooks/useKeyHandler.d.ts +6 -0
  77. package/dist/types/src/hooks/useKeyHandler.d.ts.map +1 -0
  78. package/dist/types/src/translations.d.ts +19 -10
  79. package/dist/types/src/translations.d.ts.map +1 -1
  80. package/dist/types/src/util/field.d.ts +3 -3
  81. package/dist/types/src/util/field.d.ts.map +1 -1
  82. package/dist/types/src/util/formatting.d.ts +2 -2
  83. package/dist/types/src/util/formatting.d.ts.map +1 -1
  84. package/dist/types/src/util/index.d.ts +1 -1
  85. package/dist/types/src/util/index.d.ts.map +1 -1
  86. package/dist/types/src/util/properties.d.ts +7 -0
  87. package/dist/types/src/util/properties.d.ts.map +1 -0
  88. package/dist/types/src/util/refs.d.ts +2 -3
  89. package/dist/types/src/util/refs.d.ts.map +1 -1
  90. package/dist/types/tsconfig.tsbuildinfo +1 -1
  91. package/package.json +51 -42
  92. package/src/components/FieldEditor/FieldEditor.stories.tsx +51 -32
  93. package/src/components/FieldEditor/FieldEditor.test.tsx +3 -2
  94. package/src/components/FieldEditor/FieldEditor.tsx +87 -83
  95. package/src/components/Form/Form.stories.tsx +156 -219
  96. package/src/components/Form/Form.tsx +347 -96
  97. package/src/components/Form/FormField.tsx +294 -0
  98. package/src/components/Form/FormFieldComponent.stories.tsx +65 -0
  99. package/src/components/Form/FormFieldComponent.tsx +172 -0
  100. package/src/components/Form/FormFieldSet.tsx +123 -0
  101. package/src/components/Form/README.md +3 -0
  102. package/src/components/Form/fields/ArrayField.tsx +149 -0
  103. package/src/components/Form/fields/BooleanField.tsx +22 -0
  104. package/src/components/Form/fields/GeoPointField.tsx +120 -0
  105. package/src/components/Form/fields/MarkdownField.tsx +78 -0
  106. package/src/components/Form/fields/NumberField.tsx +39 -0
  107. package/src/components/Form/fields/RefField.tsx +189 -0
  108. package/src/components/Form/fields/SelectField.tsx +65 -0
  109. package/src/components/Form/fields/SelectOptionField.stories.tsx +64 -0
  110. package/src/components/Form/{custom/SelectOptionsInput.tsx → fields/SelectOptionField.tsx} +46 -41
  111. package/src/components/Form/fields/TextAreaField.tsx +38 -0
  112. package/src/components/Form/fields/TextField.tsx +38 -0
  113. package/src/components/Form/{custom/TupleInput.tsx → fields/TupleField.tsx} +16 -9
  114. package/src/components/Form/fields/index.ts +15 -0
  115. package/src/components/Form/index.ts +3 -4
  116. package/src/components/ObjectPicker/ObjectPicker.stories.tsx +210 -0
  117. package/src/components/ObjectPicker/ObjectPicker.tsx +175 -0
  118. package/src/components/{ControlSection → ObjectPicker}/index.ts +1 -1
  119. package/src/components/Settings/Settings.stories.tsx +56 -0
  120. package/src/components/Settings/Settings.tsx +230 -0
  121. package/src/components/Settings/index.ts +5 -0
  122. package/src/components/ViewEditor/ViewEditor.stories.tsx +140 -62
  123. package/src/components/ViewEditor/ViewEditor.test.tsx +17 -18
  124. package/src/components/ViewEditor/ViewEditor.tsx +341 -202
  125. package/src/components/index.ts +2 -3
  126. package/src/components/testing.tsx +22 -11
  127. package/src/hooks/index.ts +2 -3
  128. package/src/hooks/useFormHandler.ts +380 -0
  129. package/src/hooks/useKeyHandler.tsx +37 -0
  130. package/src/translations.ts +21 -12
  131. package/src/util/field.ts +33 -43
  132. package/src/util/formatting.ts +22 -22
  133. package/src/util/index.ts +1 -1
  134. package/src/util/properties.ts +18 -0
  135. package/src/util/refs.ts +12 -18
  136. package/dist/types/src/components/ControlSection/ControlSection.d.ts +0 -23
  137. package/dist/types/src/components/ControlSection/ControlSection.d.ts.map +0 -1
  138. package/dist/types/src/components/ControlSection/ControlSection.stories.d.ts +0 -8
  139. package/dist/types/src/components/ControlSection/ControlSection.stories.d.ts.map +0 -1
  140. package/dist/types/src/components/ControlSection/index.d.ts +0 -2
  141. package/dist/types/src/components/ControlSection/index.d.ts.map +0 -1
  142. package/dist/types/src/components/Form/ArrayField.d.ts +0 -16
  143. package/dist/types/src/components/Form/ArrayField.d.ts.map +0 -1
  144. package/dist/types/src/components/Form/Defaults.d.ts +0 -14
  145. package/dist/types/src/components/Form/Defaults.d.ts.map +0 -1
  146. package/dist/types/src/components/Form/FormActions.d.ts +0 -9
  147. package/dist/types/src/components/Form/FormActions.d.ts.map +0 -1
  148. package/dist/types/src/components/Form/FormContent.d.ts +0 -57
  149. package/dist/types/src/components/Form/FormContent.d.ts.map +0 -1
  150. package/dist/types/src/components/Form/FormContext.d.ts +0 -23
  151. package/dist/types/src/components/Form/FormContext.d.ts.map +0 -1
  152. package/dist/types/src/components/Form/Input.d.ts +0 -26
  153. package/dist/types/src/components/Form/Input.d.ts.map +0 -1
  154. package/dist/types/src/components/Form/RefField.d.ts +0 -12
  155. package/dist/types/src/components/Form/RefField.d.ts.map +0 -1
  156. package/dist/types/src/components/Form/custom/GeoPointInput.d.ts +0 -4
  157. package/dist/types/src/components/Form/custom/GeoPointInput.d.ts.map +0 -1
  158. package/dist/types/src/components/Form/custom/SelectOptionsInput.d.ts +0 -4
  159. package/dist/types/src/components/Form/custom/SelectOptionsInput.d.ts.map +0 -1
  160. package/dist/types/src/components/Form/custom/SelectOptionsInput.stories.d.ts +0 -7
  161. package/dist/types/src/components/Form/custom/SelectOptionsInput.stories.d.ts.map +0 -1
  162. package/dist/types/src/components/Form/custom/TupleInput.d.ts +0 -6
  163. package/dist/types/src/components/Form/custom/TupleInput.d.ts.map +0 -1
  164. package/dist/types/src/components/Form/custom/index.d.ts +0 -4
  165. package/dist/types/src/components/Form/custom/index.d.ts.map +0 -1
  166. package/dist/types/src/components/Form/factory.d.ts +0 -8
  167. package/dist/types/src/components/Form/factory.d.ts.map +0 -1
  168. package/dist/types/src/components/deprecated/Form.d.ts +0 -15
  169. package/dist/types/src/components/deprecated/Form.d.ts.map +0 -1
  170. package/dist/types/src/components/deprecated/Form.stories.d.ts +0 -13
  171. package/dist/types/src/components/deprecated/Form.stories.d.ts.map +0 -1
  172. package/dist/types/src/components/deprecated/FormInput.d.ts +0 -16
  173. package/dist/types/src/components/deprecated/FormInput.d.ts.map +0 -1
  174. package/dist/types/src/components/deprecated/index.d.ts +0 -2
  175. package/dist/types/src/components/deprecated/index.d.ts.map +0 -1
  176. package/dist/types/src/hooks/useForm.d.ts +0 -67
  177. package/dist/types/src/hooks/useForm.d.ts.map +0 -1
  178. package/dist/types/src/hooks/useQueryRefOptions.d.ts +0 -23
  179. package/dist/types/src/hooks/useQueryRefOptions.d.ts.map +0 -1
  180. package/dist/types/src/hooks/useRefQueryLookupHandler.d.ts +0 -8
  181. package/dist/types/src/hooks/useRefQueryLookupHandler.d.ts.map +0 -1
  182. package/dist/types/src/util/schema.d.ts +0 -3
  183. package/dist/types/src/util/schema.d.ts.map +0 -1
  184. package/src/components/ControlSection/ControlSection.stories.tsx +0 -41
  185. package/src/components/ControlSection/ControlSection.tsx +0 -139
  186. package/src/components/Form/ArrayField.tsx +0 -124
  187. package/src/components/Form/Defaults.tsx +0 -203
  188. package/src/components/Form/FormActions.tsx +0 -53
  189. package/src/components/Form/FormContent.tsx +0 -240
  190. package/src/components/Form/FormContext.tsx +0 -110
  191. package/src/components/Form/Input.tsx +0 -51
  192. package/src/components/Form/RefField.tsx +0 -213
  193. package/src/components/Form/custom/GeoPointInput.tsx +0 -72
  194. package/src/components/Form/custom/SelectOptionsInput.stories.tsx +0 -61
  195. package/src/components/Form/custom/index.ts +0 -7
  196. package/src/components/Form/factory.tsx +0 -31
  197. package/src/components/deprecated/Form.stories.tsx +0 -62
  198. package/src/components/deprecated/Form.tsx +0 -119
  199. package/src/components/deprecated/FormInput.tsx +0 -71
  200. package/src/components/deprecated/index.ts +0 -5
  201. package/src/hooks/useForm.ts +0 -291
  202. package/src/hooks/useQueryRefOptions.ts +0 -53
  203. package/src/hooks/useRefQueryLookupHandler.ts +0 -39
  204. package/src/util/schema.ts +0 -14
@@ -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 { 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',
@@ -25,10 +25,19 @@ export const translations = [
25
25
  'field limit reached': 'Maximum number of fields reached',
26
26
  'boolean input true value': 'Yes',
27
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…',
28
34
 
29
- // TODO(burdon): Factor out?
30
- 'button cancel': 'Cancel',
31
- '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',
32
41
 
33
42
  // FormatEnum
34
43
  'format boolean': 'Boolean',
@@ -43,7 +52,7 @@ export const translations = [
43
52
  'format hostname': 'Hostname',
44
53
  'format integer': 'Integer',
45
54
  'format json': 'JSON',
46
- 'format latlng': 'Geopoint',
55
+ 'format lnglat': 'Geopoint',
47
56
  'format markdown': 'Markdown',
48
57
  'format percent': 'Percent',
49
58
  'format ref': 'Reference',
@@ -60,11 +69,11 @@ export const translations = [
60
69
  'format url': 'URL',
61
70
  'format uuid': 'UUID',
62
71
 
63
- // Placeholders.
64
- 'placeholder latitude': 'Latitude',
65
- 'placeholder longitude': 'Longitude',
72
+ // GeoPointField.
73
+ 'latitude label': 'Latitude',
74
+ 'longitude label': 'Longitude',
66
75
 
67
- // SelectOptionsInput.
76
+ // SelectOptionsField.
68
77
  'select option label': 'Label',
69
78
  'select option label placeholder': 'Option label',
70
79
  'select option color': 'Color',
@@ -72,8 +81,8 @@ export const translations = [
72
81
  'select option add': 'Add option',
73
82
 
74
83
  // System schema message.
75
- 'system schema title': 'System Schema',
76
- 'system schema description': 'This is a system schema and cannot be modified.',
84
+ 'system schema title': 'System type',
85
+ 'system schema description': 'System type: cannot add or remove fields.',
77
86
  },
78
87
  },
79
88
  },
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-schema';
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,41 +108,31 @@ 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
- if (!format) {
116
- switch (type) {
117
- case TypeEnum.Number:
118
- return ['text-right', 'font-mono'];
119
- case TypeEnum.Boolean:
120
- return ['text-right', 'font-mono'];
121
- case TypeEnum.String:
122
- return undefined;
123
- case TypeEnum.Ref:
124
- return undefined;
125
-
126
- default: {
127
- return undefined;
128
- }
129
- }
130
- }
131
-
132
- switch (format) {
133
- case FormatEnum.Markdown:
115
+ switch (format || type) {
116
+ case Format.TypeFormat.Markdown:
134
117
  return undefined;
135
- case FormatEnum.Time:
136
- case FormatEnum.Timestamp:
137
- case FormatEnum.DateTime:
138
- case FormatEnum.Date:
139
- 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:
140
123
  return ['font-mono', 'text-right'];
141
- case FormatEnum.Currency:
124
+ case Format.TypeFormat.Currency:
142
125
  return ['text-right'];
143
- case FormatEnum.JSON:
144
- case FormatEnum.DID:
126
+ case Format.TypeFormat.JSON:
127
+ case Format.TypeFormat.DID:
145
128
  return ['font-mono'];
129
+ case TypeEnum.Number:
130
+ case TypeEnum.Boolean:
131
+ return ['text-right', 'font-mono'];
132
+ case TypeEnum.String:
133
+ return undefined;
134
+ case TypeEnum.Ref:
135
+ return undefined;
146
136
  default:
147
137
  return undefined;
148
138
  }