@dxos/react-ui-form 0.7.5-main.9d26e3a → 0.7.5-main.b19bfc8

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 (86) hide show
  1. package/dist/lib/browser/index.mjs +1020 -571
  2. package/dist/lib/browser/index.mjs.map +4 -4
  3. package/dist/lib/browser/meta.json +1 -1
  4. package/dist/lib/node/index.cjs +1046 -608
  5. package/dist/lib/node/index.cjs.map +4 -4
  6. package/dist/lib/node/meta.json +1 -1
  7. package/dist/lib/node-esm/index.mjs +1020 -571
  8. package/dist/lib/node-esm/index.mjs.map +4 -4
  9. package/dist/lib/node-esm/meta.json +1 -1
  10. package/dist/types/src/components/FieldEditor/FieldEditor.d.ts +1 -2
  11. package/dist/types/src/components/FieldEditor/FieldEditor.d.ts.map +1 -1
  12. package/dist/types/src/components/Form/ArrayField.d.ts +15 -0
  13. package/dist/types/src/components/Form/ArrayField.d.ts.map +1 -0
  14. package/dist/types/src/components/Form/Defaults.d.ts +6 -7
  15. package/dist/types/src/components/Form/Defaults.d.ts.map +1 -1
  16. package/dist/types/src/components/Form/Form.d.ts +13 -16
  17. package/dist/types/src/components/Form/Form.d.ts.map +1 -1
  18. package/dist/types/src/components/Form/Form.stories.d.ts +2 -1
  19. package/dist/types/src/components/Form/Form.stories.d.ts.map +1 -1
  20. package/dist/types/src/components/Form/FormActions.d.ts +6 -0
  21. package/dist/types/src/components/Form/FormActions.d.ts.map +1 -0
  22. package/dist/types/src/components/Form/FormContent.d.ts +25 -0
  23. package/dist/types/src/components/Form/FormContent.d.ts.map +1 -0
  24. package/dist/types/src/components/Form/FormContext.d.ts +23 -0
  25. package/dist/types/src/components/Form/FormContext.d.ts.map +1 -0
  26. package/dist/types/src/components/Form/Input.d.ts +7 -8
  27. package/dist/types/src/components/Form/Input.d.ts.map +1 -1
  28. package/dist/types/src/components/Form/custom/GeoPointInput.d.ts +1 -3
  29. package/dist/types/src/components/Form/custom/GeoPointInput.d.ts.map +1 -1
  30. package/dist/types/src/components/Form/custom/SelectOptionsInput.d.ts +3 -0
  31. package/dist/types/src/components/Form/custom/SelectOptionsInput.d.ts.map +1 -0
  32. package/dist/types/src/components/Form/custom/SelectOptionsInput.stories.d.ts +7 -0
  33. package/dist/types/src/components/Form/custom/SelectOptionsInput.stories.d.ts.map +1 -0
  34. package/dist/types/src/components/Form/custom/TupleInput.d.ts +2 -4
  35. package/dist/types/src/components/Form/custom/TupleInput.d.ts.map +1 -1
  36. package/dist/types/src/components/Form/custom/index.d.ts +1 -0
  37. package/dist/types/src/components/Form/custom/index.d.ts.map +1 -1
  38. package/dist/types/src/components/Form/factory.d.ts +2 -2
  39. package/dist/types/src/components/Form/factory.d.ts.map +1 -1
  40. package/dist/types/src/components/Form/index.d.ts +2 -0
  41. package/dist/types/src/components/Form/index.d.ts.map +1 -1
  42. package/dist/types/src/components/ViewEditor/Test.stories.d.ts +1 -2
  43. package/dist/types/src/components/ViewEditor/Test.stories.d.ts.map +1 -1
  44. package/dist/types/src/components/ViewEditor/ViewEditor.d.ts +2 -2
  45. package/dist/types/src/components/ViewEditor/ViewEditor.d.ts.map +1 -1
  46. package/dist/types/src/components/ViewEditor/ViewEditor.stories.d.ts.map +1 -1
  47. package/dist/types/src/components/deprecated/Form.d.ts +1 -2
  48. package/dist/types/src/components/deprecated/Form.d.ts.map +1 -1
  49. package/dist/types/src/components/deprecated/Form.stories.d.ts +1 -2
  50. package/dist/types/src/components/deprecated/Form.stories.d.ts.map +1 -1
  51. package/dist/types/src/components/deprecated/FormInput.d.ts +6 -1
  52. package/dist/types/src/components/deprecated/FormInput.d.ts.map +1 -1
  53. package/dist/types/src/components/testing.d.ts +3 -3
  54. package/dist/types/src/components/testing.d.ts.map +1 -1
  55. package/dist/types/src/hooks/useForm.d.ts +11 -11
  56. package/dist/types/src/hooks/useForm.d.ts.map +1 -1
  57. package/dist/types/src/translations.d.ts +6 -0
  58. package/dist/types/src/translations.d.ts.map +1 -1
  59. package/dist/types/src/util/field.d.ts.map +1 -1
  60. package/dist/types/src/util/formatting.d.ts.map +1 -1
  61. package/dist/types/tsconfig.tsbuildinfo +1 -1
  62. package/package.json +29 -27
  63. package/src/components/FieldEditor/FieldEditor.stories.tsx +1 -1
  64. package/src/components/FieldEditor/FieldEditor.tsx +58 -40
  65. package/src/components/Form/ArrayField.tsx +111 -0
  66. package/src/components/Form/Defaults.tsx +78 -34
  67. package/src/components/Form/Form.stories.tsx +15 -5
  68. package/src/components/Form/Form.tsx +51 -327
  69. package/src/components/Form/FormActions.tsx +41 -0
  70. package/src/components/Form/FormContent.tsx +170 -0
  71. package/src/components/Form/FormContext.tsx +92 -0
  72. package/src/components/Form/Input.tsx +5 -6
  73. package/src/components/Form/custom/GeoPointInput.tsx +44 -23
  74. package/src/components/Form/custom/SelectOptionsInput.stories.tsx +58 -0
  75. package/src/components/Form/custom/SelectOptionsInput.tsx +190 -0
  76. package/src/components/Form/custom/TupleInput.tsx +5 -9
  77. package/src/components/Form/custom/index.ts +1 -0
  78. package/src/components/Form/factory.tsx +6 -7
  79. package/src/components/Form/index.ts +3 -0
  80. package/src/components/ViewEditor/ViewEditor.stories.tsx +25 -4
  81. package/src/components/ViewEditor/ViewEditor.tsx +16 -8
  82. package/src/components/deprecated/FormInput.tsx +20 -7
  83. package/src/hooks/useForm.ts +63 -49
  84. package/src/translations.ts +9 -1
  85. package/src/util/field.ts +19 -1
  86. package/src/util/formatting.ts +29 -1
@@ -4,7 +4,6 @@
4
4
 
5
5
  import React from 'react';
6
6
 
7
- import { type BaseObject } from '@dxos/echo-schema';
8
7
  import { Input } from '@dxos/react-ui';
9
8
  import { mx } from '@dxos/react-ui-theme';
10
9
  import { safeParseFloat } from '@dxos/util';
@@ -13,9 +12,8 @@ import { InputHeader, type InputProps } from '../Input';
13
12
 
14
13
  const gridCols = ['grid-cols-1', 'grid-cols-2', 'grid-cols-3', 'grid-cols-4'];
15
14
 
16
- export const TupleInput = <T extends BaseObject>({
15
+ export const TupleInput = ({
17
16
  binding,
18
- property,
19
17
  type,
20
18
  label,
21
19
  disabled,
@@ -23,11 +21,11 @@ export const TupleInput = <T extends BaseObject>({
23
21
  getValue,
24
22
  onValueChange,
25
23
  onBlur,
26
- }: InputProps<T> & { binding: string[] }) => {
27
- const { status, error } = getStatus?.(property);
24
+ }: InputProps & { binding: string[] }) => {
25
+ const { status, error } = getStatus();
28
26
 
29
27
  // TODO(burdon): Generalize number/float/string, etc.
30
- const values: Record<string, number> = getValue<Record<string, number>>(property) ?? {};
28
+ const values: Record<string, number> = getValue<Record<string, number>>() ?? {};
31
29
 
32
30
  return (
33
31
  <Input.Root validationValence={status}>
@@ -41,9 +39,7 @@ export const TupleInput = <T extends BaseObject>({
41
39
  type='number'
42
40
  disabled={disabled}
43
41
  value={values[prop]}
44
- onChange={(event) =>
45
- onValueChange(property, type, { ...values, [prop]: safeParseFloat(event.target.value, 0) })
46
- }
42
+ onChange={(event) => onValueChange(type, { ...values, [prop]: safeParseFloat(event.target.value, 0) })}
47
43
  onBlur={onBlur}
48
44
  />
49
45
  ))}
@@ -3,4 +3,5 @@
3
3
  //
4
4
 
5
5
  export * from './GeoPointInput';
6
+ export * from './SelectOptionsInput';
6
7
  export * from './TupleInput';
@@ -2,23 +2,22 @@
2
2
  // Copyright 2024 DXOS.org
3
3
  //
4
4
 
5
- import { type BaseObject, FormatEnum } from '@dxos/echo-schema';
5
+ import { FormatEnum } from '@dxos/echo-schema';
6
6
  import { type SimpleType } from '@dxos/effect';
7
7
 
8
- import { BooleanInput, NumberInput, TextInput } from './Defaults';
8
+ import { BooleanInput, MarkdownInput, NumberInput, TextInput } from './Defaults';
9
9
  import { type InputComponent } from './Input';
10
10
  import { GeoPointInput } from './custom';
11
11
 
12
12
  /**
13
13
  * Get property input component.
14
14
  */
15
- export const getInputComponent = <T extends BaseObject>(
16
- type: SimpleType,
17
- format?: FormatEnum,
18
- ): InputComponent<T> | undefined => {
15
+ export const getInputComponent = (type: SimpleType, format?: FormatEnum): InputComponent | undefined => {
19
16
  switch (format) {
20
- case FormatEnum.LatLng:
17
+ case FormatEnum.GeoPoint:
21
18
  return GeoPointInput;
19
+ case FormatEnum.Markdown:
20
+ return MarkdownInput;
22
21
  }
23
22
 
24
23
  switch (type) {
@@ -2,8 +2,11 @@
2
2
  // Copyright 2024 DXOS.org
3
3
  //
4
4
 
5
+ import { useFormValues } from './FormContext';
6
+
5
7
  export * from './custom';
6
8
 
7
9
  export * from './Defaults';
8
10
  export * from './Form';
9
11
  export * from './Input';
12
+ export { useFormValues };
@@ -5,13 +5,13 @@
5
5
  import '@dxos-theme';
6
6
 
7
7
  import { type Meta, type StoryObj } from '@storybook/react';
8
- import React, { useCallback, useState } from 'react';
8
+ import React, { useCallback, useMemo, useState } from 'react';
9
9
 
10
10
  import { Format, type EchoSchema, S, toJsonSchema, TypedObject } from '@dxos/echo-schema';
11
- import { useSpace } from '@dxos/react-client/echo';
11
+ import { Filter, useQuery, useSpace } from '@dxos/react-client/echo';
12
12
  import { withClientProvider } from '@dxos/react-client/testing';
13
13
  import { useAsyncEffect } from '@dxos/react-ui';
14
- import { type ViewType, ViewProjection, createView } from '@dxos/schema';
14
+ import { ViewProjection, ViewType, createView } from '@dxos/schema';
15
15
  import { withTheme, withLayout } from '@dxos/storybook-utils';
16
16
 
17
17
  import { ViewEditor } from './ViewEditor';
@@ -41,6 +41,21 @@ const DefaultStory = () => {
41
41
  }
42
42
  }, [space]);
43
43
 
44
+ const views = useQuery(space, Filter.schema(ViewType));
45
+ const currentTypename = useMemo(() => view?.query?.type, [view]);
46
+ const updateViewTypename = useCallback(
47
+ (newTypename: string) => {
48
+ if (!schema) {
49
+ return;
50
+ }
51
+ const matchingViews = views.filter((view) => view.query.type === currentTypename);
52
+ for (const view of matchingViews) {
53
+ view.query.type = newTypename;
54
+ }
55
+ schema.updateTypename(newTypename);
56
+ },
57
+ [views, schema],
58
+ );
44
59
  const handleDelete = useCallback((property: string) => projection?.deleteFieldProjection(property), [projection]);
45
60
 
46
61
  if (!schema || !view || !projection) {
@@ -50,7 +65,13 @@ const DefaultStory = () => {
50
65
  return (
51
66
  <TestLayout json={{ schema, view, projection }}>
52
67
  <TestPanel>
53
- <ViewEditor schema={schema} view={view} registry={space?.db.schemaRegistry} onDelete={handleDelete} />
68
+ <ViewEditor
69
+ schema={schema}
70
+ view={view}
71
+ registry={space?.db.schemaRegistry}
72
+ onTypenameChanged={updateViewTypename}
73
+ onDelete={handleDelete}
74
+ />
54
75
  </TestPanel>
55
76
  </TestLayout>
56
77
  );
@@ -10,7 +10,6 @@ import { IconButton, type ThemedClassName, useTranslation } from '@dxos/react-ui
10
10
  import { List } from '@dxos/react-ui-list';
11
11
  import { ghostHover, inputTextLabel, mx } from '@dxos/react-ui-theme';
12
12
  import { FieldSchema, type FieldType, type ViewType, ViewProjection, VIEW_FIELD_LIMIT } from '@dxos/schema';
13
- import { arrayMove } from '@dxos/util';
14
13
 
15
14
  import { translationKey } from '../../translations';
16
15
  import { FieldEditor } from '../FieldEditor';
@@ -22,7 +21,7 @@ const ViewMetaSchema = S.Struct({
22
21
  name: S.String.annotations({
23
22
  [AST.TitleAnnotationId]: 'View',
24
23
  }),
25
- typename: Format.DXN.annotations({
24
+ typename: Format.URL.annotations({
26
25
  [AST.TitleAnnotationId]: 'Typename',
27
26
  }),
28
27
  }).pipe(S.mutable);
@@ -35,6 +34,7 @@ export type ViewEditorProps = ThemedClassName<{
35
34
  registry?: SchemaRegistry;
36
35
  readonly?: boolean;
37
36
  showHeading?: boolean;
37
+ onTypenameChanged: (typename: string) => void;
38
38
  onDelete: (fieldId: string) => void;
39
39
  }>;
40
40
 
@@ -48,6 +48,7 @@ export const ViewEditor = ({
48
48
  registry,
49
49
  readonly,
50
50
  showHeading = false,
51
+ onTypenameChanged,
51
52
  onDelete,
52
53
  }: ViewEditorProps) => {
53
54
  const { t } = useTranslation(translationKey);
@@ -67,12 +68,15 @@ export const ViewEditor = ({
67
68
  const handleViewUpdate = useCallback(
68
69
  ({ name, typename }: ViewMetaType) => {
69
70
  requestAnimationFrame(() => {
70
- view.name = name;
71
- view.query.type = typename;
72
- schema.updateTypename(typename);
71
+ if (view.name !== name) {
72
+ view.name = name;
73
+ }
74
+ if (view.query.type !== typename) {
75
+ onTypenameChanged(typename);
76
+ }
73
77
  });
74
78
  },
75
- [view, schema],
79
+ [view, schema, onTypenameChanged],
76
80
  );
77
81
 
78
82
  const handleSelect = useCallback((field: FieldType) => {
@@ -86,7 +90,11 @@ export const ViewEditor = ({
86
90
 
87
91
  const handleMove = useCallback(
88
92
  (fromIndex: number, toIndex: number) => {
89
- arrayMove(view.fields, fromIndex, toIndex);
93
+ // NOTE(ZaymonFC): Using arrayMove here causes a race condition with the kanban model.
94
+ const fields = [...view.fields];
95
+ const [moved] = fields.splice(fromIndex, 1);
96
+ fields.splice(toIndex, 0, moved);
97
+ view.fields = fields;
90
98
  },
91
99
  [view.fields],
92
100
  );
@@ -95,7 +103,7 @@ export const ViewEditor = ({
95
103
 
96
104
  return (
97
105
  <div role='none' className={mx('flex flex-col w-full divide-y divide-separator', classNames)}>
98
- <Form<ViewMetaType> autoFocus autoSave schema={ViewMetaSchema} values={viewValues} onSave={handleViewUpdate} />
106
+ <Form<ViewMetaType> autoSave schema={ViewMetaSchema} values={viewValues} onSave={handleViewUpdate} />
99
107
 
100
108
  <div>
101
109
  {/* TODO(burdon): Clean up common form ux. */}
@@ -4,7 +4,21 @@
4
4
 
5
5
  import React, { type JSX, type PropsWithChildren } from 'react';
6
6
 
7
- import { Input } from '@dxos/react-ui';
7
+ import { Input, type ThemedClassName } from '@dxos/react-ui';
8
+ import { mx, textBlockWidth } from '@dxos/react-ui-theme';
9
+
10
+ /**
11
+ * @deprecated
12
+ */
13
+ export const DeprecatedFormContainer = ({ children, classNames }: ThemedClassName<PropsWithChildren>) => {
14
+ return (
15
+ <div role='none' className='w-full p-4 justify-center overflow-x-hidden overflow-y-auto'>
16
+ <div role='form' className={mx('flex flex-col', textBlockWidth, classNames)}>
17
+ {children}
18
+ </div>
19
+ </div>
20
+ );
21
+ };
8
22
 
9
23
  export type DeprecatedFormInputProps = {
10
24
  label: string;
@@ -15,7 +29,6 @@ export type DeprecatedFormInputProps = {
15
29
  /**
16
30
  * @deprecated
17
31
  */
18
- // TODO(burdon): Still used in ObservabilitySettings and all settings.
19
32
  export const DeprecatedFormInput = ({
20
33
  label,
21
34
  description,
@@ -26,8 +39,9 @@ export const DeprecatedFormInput = ({
26
39
  <div role='none' className='flex w-full gap-4 py-1'>
27
40
  <Input.Root>
28
41
  <div role='none' className='flex flex-col w-full'>
29
- {/* TODO(burdon): Consistent height for controls (e.g., Select, Textbox, and Checkbox are all different). */}
30
- <Input.Label classNames='flex min-h-[40px] items-center'>{label}</Input.Label>
42
+ <Input.Label classNames='flex min-bs-[--rail-action] items-center' style={{ fontSize: 'unset' }}>
43
+ {label}
44
+ </Input.Label>
31
45
  {description && (
32
46
  <Input.DescriptionAndValidation classNames='mbs-0.5'>
33
47
  <Input.Description>{description}</Input.Description>
@@ -36,7 +50,7 @@ export const DeprecatedFormInput = ({
36
50
  </div>
37
51
 
38
52
  <div role='none'>
39
- <div role='none' className='flex min-h-[40px] items-center'>
53
+ <div role='none' className='flex min-bs-[--rail-action] items-center'>
40
54
  {children}
41
55
  </div>
42
56
  </div>
@@ -45,9 +59,8 @@ export const DeprecatedFormInput = ({
45
59
  );
46
60
 
47
61
  if (secondary) {
48
- // console.log(secondary);
49
62
  return (
50
- <div role='none' className='flex flex-col w-full'>
63
+ <div role='none'>
51
64
  {primary}
52
65
  {secondary}
53
66
  </div>
@@ -2,10 +2,10 @@
2
2
  // Copyright 2024 DXOS.org
3
3
  //
4
4
 
5
- import { type FocusEvent, useCallback, useEffect, useMemo, useState } from 'react';
5
+ import { useCallback, useEffect, useMemo, useState } from 'react';
6
6
 
7
- import { type BaseObject, type PropertyKey, getValue, setValue } from '@dxos/echo-schema';
8
- import { type SimpleType, type S, type JsonPath } from '@dxos/effect';
7
+ import { type BaseObject, getValue, setValue } from '@dxos/echo-schema';
8
+ import { AST, type S, type SimpleType, type JsonPath, createJsonPath, fromEffectValidationPath } from '@dxos/effect';
9
9
  import { invariant } from '@dxos/invariant';
10
10
  import { log } from '@dxos/log';
11
11
  import { validateSchema, type ValidationError } from '@dxos/schema';
@@ -20,20 +20,21 @@ export type FormHandler<T extends BaseObject> = {
20
20
  //
21
21
 
22
22
  values: Partial<T>;
23
- errors: Record<PropertyKey<T>, string>;
24
- touched: Record<PropertyKey<T>, boolean>;
25
- changed: Record<PropertyKey<T>, boolean>;
23
+ errors: Record<JsonPath, string>;
24
+ touched: Record<JsonPath, boolean>;
25
+ changed: Record<JsonPath, boolean>;
26
26
  canSave: boolean;
27
+ formIsValid: boolean;
27
28
  handleSave: () => void;
28
29
 
29
30
  //
30
31
  // Form input component helpers.
31
32
  //
32
33
 
33
- getStatus: (property: PropertyKey<T>) => { status?: 'error'; error?: string };
34
- getValue: <V>(property: PropertyKey<T>) => V | undefined;
35
- onValueChange: <V>(property: PropertyKey<T>, type: SimpleType, value: V) => void;
36
- onBlur: (event: FocusEvent<HTMLInputElement | HTMLTextAreaElement>) => void;
34
+ getStatus: (path: string | (string | number)[]) => { status?: 'error'; error?: string };
35
+ getValue: <V>(path: (string | number)[]) => V | undefined;
36
+ onValueChange: <V>(path: (string | number)[], type: SimpleType, value: V) => void;
37
+ onTouched: (path: (string | number)[]) => void;
37
38
  };
38
39
 
39
40
  /**
@@ -41,9 +42,8 @@ export type FormHandler<T extends BaseObject> = {
41
42
  */
42
43
  export interface FormOptions<T extends BaseObject> {
43
44
  /**
44
- * Effect schema.
45
+ * Effect schema (Type literal).
45
46
  */
46
- // TODO(burdon): Change to S.Struct<T>?
47
47
  schema: S.Schema<T>;
48
48
 
49
49
  /**
@@ -89,21 +89,22 @@ export const useForm = <T extends BaseObject>({
89
89
  onValid,
90
90
  onSave,
91
91
  }: FormOptions<T>): FormHandler<T> => {
92
+ invariant(AST.isTypeLiteral(schema.ast));
93
+
92
94
  const [values, setValues] = useState<Partial<T>>(initialValues);
93
95
  useEffect(() => {
94
96
  setValues(initialValues);
95
97
  }, [initialValues]);
96
98
 
97
- const [touched, setTouched] = useState<Record<PropertyKey<T>, boolean>>(createKeySet(initialValues, false));
98
- const [changed, setChanged] = useState<Record<PropertyKey<T>, boolean>>(createKeySet(initialValues, false));
99
- const [errors, setErrors] = useState<Record<PropertyKey<T>, string>>({} as Record<PropertyKey<T>, string>);
99
+ const [touched, setTouched] = useState<Record<JsonPath, boolean>>(createKeySet(initialValues, false));
100
+ const [changed, setChanged] = useState<Record<JsonPath, boolean>>(createKeySet(initialValues, false));
101
+ const [errors, setErrors] = useState<Record<JsonPath, string>>({});
100
102
  const [saving, setSaving] = useState(false);
101
103
 
102
104
  //
103
105
  // Validation.
104
106
  //
105
107
 
106
- // TODO(burdon): Validate each property separately.
107
108
  const validate = useCallback(
108
109
  (values: Partial<T>): values is T => {
109
110
  let errors: ValidationError[] = validateSchema(schema, values) ?? [];
@@ -129,6 +130,10 @@ export const useForm = <T extends BaseObject>({
129
130
  }
130
131
  }, [values, schemaDirty]);
131
132
 
133
+ const formIsValid = useMemo(() => {
134
+ return Object.keys(errors).length === 0;
135
+ }, [errors]);
136
+
132
137
  /**
133
138
  * NOTE: We can submit if there is no touched field that has an error.
134
139
  * Basically, if there's a validation message visible in the form, submit should be disabled.
@@ -136,8 +141,15 @@ export const useForm = <T extends BaseObject>({
136
141
  const canSave = useMemo(
137
142
  () =>
138
143
  !saving &&
139
- Object.keys(values).every((property) => touched[property as JsonPath] === false || !errors[property as JsonPath]),
140
- [values, touched, errors, saving],
144
+ // Check if any error paths that are touched have errors
145
+ !Object.entries(touched).some(
146
+ ([path, isTouched]) =>
147
+ isTouched &&
148
+ Object.keys(errors).some(
149
+ (errorPath) => errorPath === path || errorPath.startsWith(`${path}.`) || errorPath.startsWith(`${path}[`),
150
+ ),
151
+ ),
152
+ [touched, errors, saving],
141
153
  );
142
154
 
143
155
  const handleSave = useCallback(async () => {
@@ -156,19 +168,27 @@ export const useForm = <T extends BaseObject>({
156
168
  //
157
169
 
158
170
  const getStatus = useCallback<FormHandler<T>['getStatus']>(
159
- (property: PropertyKey<T>) => ({
160
- status: errors[property] ? 'error' : undefined,
161
- error: errors[property] ? errors[property] : undefined,
162
- }),
163
- [touched, errors],
171
+ (path) => {
172
+ const jsonPath = Array.isArray(path) ? createJsonPath(path) : path;
173
+ const matchingError = Object.entries(errors).find(
174
+ ([errorPath]) =>
175
+ errorPath === jsonPath || errorPath.startsWith(`${jsonPath}.`) || errorPath.startsWith(`${jsonPath}[`),
176
+ );
177
+
178
+ return {
179
+ status: matchingError ? 'error' : undefined,
180
+ error: matchingError ? matchingError[1] : undefined,
181
+ };
182
+ },
183
+ [errors],
164
184
  );
165
185
 
166
- // TODO(burdon): Use path to extract hierarchical value.
167
- const getFormValue = <V>(property: PropertyKey<T>): V | undefined => {
168
- return getValue(values, property as any as JsonPath);
186
+ const getFormValue = <V>(path: (string | number)[]): V | undefined => {
187
+ return getValue(values, createJsonPath(path));
169
188
  };
170
189
 
171
- const onValueChange = (property: PropertyKey<T>, type: SimpleType, value: any) => {
190
+ const onValueChange = (path: (string | number)[], type: SimpleType, value: any) => {
191
+ const jsonPath = createJsonPath(path);
172
192
  let parsedValue = value;
173
193
  try {
174
194
  if (type === 'number') {
@@ -179,9 +199,9 @@ export const useForm = <T extends BaseObject>({
179
199
  parsedValue = undefined;
180
200
  }
181
201
 
182
- const newValues = { ...setValue(values, property as any as JsonPath, parsedValue) };
202
+ const newValues = { ...setValue(values, jsonPath, parsedValue) };
183
203
  setValues(newValues);
184
- setChanged((prev) => ({ ...prev, [property]: true }));
204
+ setChanged((prev) => ({ ...prev, [jsonPath]: true }));
185
205
  onValuesChanged?.(newValues);
186
206
 
187
207
  const isValid = validate(newValues);
@@ -190,19 +210,10 @@ export const useForm = <T extends BaseObject>({
190
210
  }
191
211
  };
192
212
 
193
- // TODO(burdon): This is a leaky abstraction: the hook ideally shouldn't get involved in UX.
194
- const onBlur = useCallback(
195
- (event: FocusEvent<HTMLInputElement | HTMLTextAreaElement>) => {
196
- const { name } = event.target;
197
- setTouched((touched) => ({ ...touched, [name]: true }));
198
-
199
- // TODO(Zan): This should be configurable behavior.
200
- if (event.relatedTarget?.getAttribute('type') === 'submit') {
201
- // NOTE: We do this here instead of onSave because the blur event is triggered before the submit event
202
- // and results in the submit button being disabled when the form is invalid.
203
- setTouched(createKeySet(values, true));
204
- }
205
-
213
+ const onTouched = useCallback(
214
+ (path: (string | number)[]) => {
215
+ const jsonPath = createJsonPath(path);
216
+ setTouched((touched) => ({ ...touched, [jsonPath]: true }));
206
217
  validate(values);
207
218
  },
208
219
  [validate, values],
@@ -216,28 +227,31 @@ export const useForm = <T extends BaseObject>({
216
227
  changed,
217
228
  canSave,
218
229
  handleSave,
230
+ formIsValid,
219
231
 
220
232
  // Field utils.
221
233
  getStatus,
222
234
  getValue: getFormValue,
223
235
  onValueChange,
224
- onBlur,
236
+ onTouched,
225
237
  } satisfies FormHandler<T>;
226
238
  };
227
239
 
228
- const createKeySet = <T extends BaseObject, V>(obj: T, value: V): Record<PropertyKey<T>, V> => {
240
+ const createKeySet = <T extends BaseObject, V>(obj: T, value: V): Record<JsonPath, V> => {
229
241
  invariant(obj);
230
- return Object.keys(obj).reduce((acc, key) => ({ ...acc, [key]: value }), {} as Record<PropertyKey<T>, V>);
242
+ return Object.keys(obj).reduce((acc, key) => ({ ...acc, [key]: value }), {} as Record<JsonPath, V>);
231
243
  };
232
244
 
233
- const flatMap = <T extends BaseObject>(errors: ValidationError[]) => {
245
+ const flatMap = (errors: ValidationError[]) => {
234
246
  return errors.reduce(
235
247
  (result, { path, message }) => {
236
- if (!(path in result)) {
237
- result[path as PropertyKey<T>] = message;
248
+ // Convert the validation error path format to our JsonPath format
249
+ const jsonPath = fromEffectValidationPath(path);
250
+ if (!(jsonPath in result)) {
251
+ result[jsonPath] = message;
238
252
  }
239
253
  return result;
240
254
  },
241
- {} as Record<PropertyKey<T>, string>,
255
+ {} as Record<JsonPath, string>,
242
256
  );
243
257
  };
@@ -36,12 +36,13 @@ export default [
36
36
  'format hostname': 'Hostname',
37
37
  'format integer': 'Integer',
38
38
  'format json': 'JSON',
39
- 'format latlng': 'LatLng',
39
+ 'format latlng': 'Geopoint',
40
40
  'format markdown': 'Markdown',
41
41
  'format percent': 'Percent',
42
42
  'format ref': 'Reference',
43
43
  'format regex': 'RegExp',
44
44
  'format string': 'String',
45
+ 'format single-select': 'Select',
45
46
  'format text': 'Long text',
46
47
  'format time': 'Time',
47
48
  'format timestamp': 'Timestamp',
@@ -53,6 +54,13 @@ export default [
53
54
  // Placeholders
54
55
  'placeholder latitude': 'Latitude',
55
56
  'placeholder longitude': 'Longitude',
57
+
58
+ // SelectOptionsInput
59
+ 'select option label': 'Label',
60
+ 'select option label placeholder': 'Option label',
61
+ 'select option color': 'Color',
62
+ 'select option delete': 'Delete',
63
+ 'select option add': 'Add option',
56
64
  },
57
65
  },
58
66
  },
package/src/util/field.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  // Copyright 2024 DXOS.org
3
3
  //
4
4
 
5
- import { FormatEnum, TypeEnum } from '@dxos/echo-schema';
5
+ import { FormatEnum, GeoLocation, TypeEnum } from '@dxos/echo-schema';
6
6
  import { type ValidationError } from '@dxos/schema';
7
7
 
8
8
  /**
@@ -81,6 +81,24 @@ export const parseValue = ({ type, format, value }: ParseProps) => {
81
81
  return isNaN(date.getTime()) ? null : date;
82
82
  }
83
83
 
84
+ case FormatEnum.GeoPoint: {
85
+ // Parse string in format "lat,long" to GeoPoint [longitude, latitude].
86
+ if (typeof value === 'string') {
87
+ // Only keep digits, decimal points, minus signs, and commas.
88
+ const cleaned = value.replace(/[^0-9.,-]+/g, '');
89
+ const parts = cleaned.split(',');
90
+ if (parts.length === 2) {
91
+ const lat = parseFloat(parts[0]);
92
+ const long = parseFloat(parts[1]);
93
+ if (!isNaN(lat) && !isNaN(long)) {
94
+ return GeoLocation.toGeoPoint({ latitude: lat, longitude: long });
95
+ }
96
+ }
97
+ }
98
+
99
+ return [0, 0];
100
+ }
101
+
84
102
  default: {
85
103
  return value;
86
104
  }
@@ -2,7 +2,7 @@
2
2
  // Copyright 2024 DXOS.org
3
3
  //
4
4
 
5
- import { FormatEnum, TypeEnum } from '@dxos/echo-schema';
5
+ import { FormatEnum, GeoLocation, TypeEnum } from '@dxos/echo-schema';
6
6
 
7
7
  type ValueFormatProps = {
8
8
  type: TypeEnum;
@@ -73,6 +73,19 @@ export const formatForDisplay = ({ type, format, value, locale = undefined }: Va
73
73
  return date.toLocaleTimeString(locale);
74
74
  }
75
75
  }
76
+ case FormatEnum.GeoPoint: {
77
+ if (value === null || value === undefined) {
78
+ return '';
79
+ }
80
+
81
+ // For GeoPoint format [longitude, latitude].
82
+ if (Array.isArray(value) && value.length >= 2 && value.every(Number.isFinite)) {
83
+ const { latitude, longitude } = GeoLocation.fromGeoPoint(value as [number, number]);
84
+ return `${latitude},${longitude}`;
85
+ }
86
+
87
+ return String(value);
88
+ }
76
89
  default: {
77
90
  if (value === null || value === 'undefined') {
78
91
  return '';
@@ -125,6 +138,21 @@ export const formatForEditing = ({ type, format, value, locale = undefined }: Va
125
138
  const date = new Date(value as number);
126
139
  return date.toISOString().split('T')[1].split('.')[0];
127
140
  }
141
+ case FormatEnum.GeoPoint: {
142
+ // Handle null or undefined
143
+ if (value === null || value === undefined) {
144
+ return '';
145
+ }
146
+
147
+ // For GeoPoint format [longitude, latitude].
148
+ if (Array.isArray(value) && value.length >= 2 && value.every(Number.isFinite)) {
149
+ const { latitude, longitude } = GeoLocation.fromGeoPoint(value as [number, number]);
150
+ return `${latitude},${longitude}`;
151
+ }
152
+
153
+ return String(value);
154
+ }
155
+
128
156
  default: {
129
157
  return String(value);
130
158
  }