@dxos/react-ui-form 0.8.4-main.b97322e → 0.8.4-main.bcb3aa67d6

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 (205) hide show
  1. package/README.md +0 -1
  2. package/dist/lib/browser/index.mjs +2315 -2116
  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 +2315 -2116
  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 +84 -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 +43 -0
  17. package/dist/types/src/components/Form/FormField.d.ts.map +1 -0
  18. package/dist/types/src/components/Form/FormFieldComponent.d.ts +77 -0
  19. package/dist/types/src/components/Form/FormFieldComponent.d.ts.map +1 -0
  20. package/dist/types/src/components/Form/FormFieldComponent.stories.d.ts +9 -0
  21. package/dist/types/src/components/Form/FormFieldComponent.stories.d.ts.map +1 -0
  22. package/dist/types/src/components/Form/FormFieldSet.d.ts +18 -0
  23. package/dist/types/src/components/Form/FormFieldSet.d.ts.map +1 -0
  24. package/dist/types/src/components/Form/fields/ArrayField.d.ts +18 -0
  25. package/dist/types/src/components/Form/fields/ArrayField.d.ts.map +1 -0
  26. package/dist/types/src/components/Form/fields/BooleanField.d.ts +4 -0
  27. package/dist/types/src/components/Form/fields/BooleanField.d.ts.map +1 -0
  28. package/dist/types/src/components/Form/fields/GeoPointField.d.ts +5 -0
  29. package/dist/types/src/components/Form/fields/GeoPointField.d.ts.map +1 -0
  30. package/dist/types/src/components/Form/fields/MarkdownField.d.ts +4 -0
  31. package/dist/types/src/components/Form/fields/MarkdownField.d.ts.map +1 -0
  32. package/dist/types/src/components/Form/fields/NumberField.d.ts +4 -0
  33. package/dist/types/src/components/Form/fields/NumberField.d.ts.map +1 -0
  34. package/dist/types/src/components/Form/fields/RefField.d.ts +16 -0
  35. package/dist/types/src/components/Form/fields/RefField.d.ts.map +1 -0
  36. package/dist/types/src/components/Form/fields/SelectField.d.ts +10 -0
  37. package/dist/types/src/components/Form/fields/SelectField.d.ts.map +1 -0
  38. package/dist/types/src/components/Form/fields/SelectOptionField.d.ts +5 -0
  39. package/dist/types/src/components/Form/fields/SelectOptionField.d.ts.map +1 -0
  40. package/dist/types/src/components/Form/fields/SelectOptionField.stories.d.ts +82 -0
  41. package/dist/types/src/components/Form/fields/SelectOptionField.stories.d.ts.map +1 -0
  42. package/dist/types/src/components/Form/fields/TextAreaField.d.ts +4 -0
  43. package/dist/types/src/components/Form/fields/TextAreaField.d.ts.map +1 -0
  44. package/dist/types/src/components/Form/fields/TextField.d.ts +4 -0
  45. package/dist/types/src/components/Form/fields/TextField.d.ts.map +1 -0
  46. package/dist/types/src/components/Form/fields/TupleField.d.ts +6 -0
  47. package/dist/types/src/components/Form/fields/TupleField.d.ts.map +1 -0
  48. package/dist/types/src/components/Form/fields/index.d.ts +12 -0
  49. package/dist/types/src/components/Form/fields/index.d.ts.map +1 -0
  50. package/dist/types/src/components/Form/index.d.ts +2 -4
  51. package/dist/types/src/components/Form/index.d.ts.map +1 -1
  52. package/dist/types/src/components/ObjectPicker/ObjectPicker.d.ts +54 -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 +39 -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 +63 -54
  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 +3 -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 +52 -43
  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/AUDIT.md +17 -0
  96. package/src/components/Form/Form.stories.tsx +154 -219
  97. package/src/components/Form/Form.tsx +314 -97
  98. package/src/components/Form/FormField.tsx +305 -0
  99. package/src/components/Form/FormFieldComponent.stories.tsx +65 -0
  100. package/src/components/Form/FormFieldComponent.tsx +171 -0
  101. package/src/components/Form/FormFieldSet.tsx +129 -0
  102. package/src/components/Form/README.md +3 -0
  103. package/src/components/Form/fields/ArrayField.tsx +154 -0
  104. package/src/components/Form/fields/BooleanField.tsx +22 -0
  105. package/src/components/Form/fields/GeoPointField.tsx +120 -0
  106. package/src/components/Form/fields/MarkdownField.tsx +78 -0
  107. package/src/components/Form/fields/NumberField.tsx +39 -0
  108. package/src/components/Form/fields/RefField.tsx +199 -0
  109. package/src/components/Form/fields/SelectField.tsx +65 -0
  110. package/src/components/Form/fields/SelectOptionField.stories.tsx +64 -0
  111. package/src/components/Form/{custom/SelectOptionsInput.tsx → fields/SelectOptionField.tsx} +49 -45
  112. package/src/components/Form/fields/TextAreaField.tsx +38 -0
  113. package/src/components/Form/fields/TextField.tsx +38 -0
  114. package/src/components/Form/{custom/TupleInput.tsx → fields/TupleField.tsx} +17 -10
  115. package/src/components/Form/fields/index.ts +15 -0
  116. package/src/components/Form/index.ts +3 -4
  117. package/src/components/ObjectPicker/ObjectPicker.stories.tsx +210 -0
  118. package/src/components/ObjectPicker/ObjectPicker.tsx +186 -0
  119. package/src/components/{ControlSection → ObjectPicker}/index.ts +1 -1
  120. package/src/components/Settings/Settings.stories.tsx +56 -0
  121. package/src/components/Settings/Settings.tsx +129 -0
  122. package/src/components/Settings/index.ts +5 -0
  123. package/src/components/ViewEditor/ViewEditor.stories.tsx +141 -63
  124. package/src/components/ViewEditor/ViewEditor.test.tsx +17 -18
  125. package/src/components/ViewEditor/ViewEditor.tsx +353 -203
  126. package/src/components/index.ts +2 -3
  127. package/src/components/testing.tsx +33 -13
  128. package/src/hooks/index.ts +2 -3
  129. package/src/hooks/useFormHandler.ts +380 -0
  130. package/src/hooks/useKeyHandler.tsx +37 -0
  131. package/src/translations.ts +66 -58
  132. package/src/util/field.ts +33 -43
  133. package/src/util/formatting.ts +22 -22
  134. package/src/util/index.ts +1 -1
  135. package/src/util/properties.ts +18 -0
  136. package/src/util/refs.ts +17 -19
  137. package/dist/types/src/components/ControlSection/ControlSection.d.ts +0 -23
  138. package/dist/types/src/components/ControlSection/ControlSection.d.ts.map +0 -1
  139. package/dist/types/src/components/ControlSection/ControlSection.stories.d.ts +0 -8
  140. package/dist/types/src/components/ControlSection/ControlSection.stories.d.ts.map +0 -1
  141. package/dist/types/src/components/ControlSection/index.d.ts +0 -2
  142. package/dist/types/src/components/ControlSection/index.d.ts.map +0 -1
  143. package/dist/types/src/components/Form/ArrayField.d.ts +0 -16
  144. package/dist/types/src/components/Form/ArrayField.d.ts.map +0 -1
  145. package/dist/types/src/components/Form/Defaults.d.ts +0 -14
  146. package/dist/types/src/components/Form/Defaults.d.ts.map +0 -1
  147. package/dist/types/src/components/Form/FormActions.d.ts +0 -9
  148. package/dist/types/src/components/Form/FormActions.d.ts.map +0 -1
  149. package/dist/types/src/components/Form/FormContent.d.ts +0 -57
  150. package/dist/types/src/components/Form/FormContent.d.ts.map +0 -1
  151. package/dist/types/src/components/Form/FormContext.d.ts +0 -23
  152. package/dist/types/src/components/Form/FormContext.d.ts.map +0 -1
  153. package/dist/types/src/components/Form/Input.d.ts +0 -26
  154. package/dist/types/src/components/Form/Input.d.ts.map +0 -1
  155. package/dist/types/src/components/Form/RefField.d.ts +0 -12
  156. package/dist/types/src/components/Form/RefField.d.ts.map +0 -1
  157. package/dist/types/src/components/Form/custom/GeoPointInput.d.ts +0 -4
  158. package/dist/types/src/components/Form/custom/GeoPointInput.d.ts.map +0 -1
  159. package/dist/types/src/components/Form/custom/SelectOptionsInput.d.ts +0 -4
  160. package/dist/types/src/components/Form/custom/SelectOptionsInput.d.ts.map +0 -1
  161. package/dist/types/src/components/Form/custom/SelectOptionsInput.stories.d.ts +0 -7
  162. package/dist/types/src/components/Form/custom/SelectOptionsInput.stories.d.ts.map +0 -1
  163. package/dist/types/src/components/Form/custom/TupleInput.d.ts +0 -6
  164. package/dist/types/src/components/Form/custom/TupleInput.d.ts.map +0 -1
  165. package/dist/types/src/components/Form/custom/index.d.ts +0 -4
  166. package/dist/types/src/components/Form/custom/index.d.ts.map +0 -1
  167. package/dist/types/src/components/Form/factory.d.ts +0 -8
  168. package/dist/types/src/components/Form/factory.d.ts.map +0 -1
  169. package/dist/types/src/components/deprecated/Form.d.ts +0 -15
  170. package/dist/types/src/components/deprecated/Form.d.ts.map +0 -1
  171. package/dist/types/src/components/deprecated/Form.stories.d.ts +0 -13
  172. package/dist/types/src/components/deprecated/Form.stories.d.ts.map +0 -1
  173. package/dist/types/src/components/deprecated/FormInput.d.ts +0 -16
  174. package/dist/types/src/components/deprecated/FormInput.d.ts.map +0 -1
  175. package/dist/types/src/components/deprecated/index.d.ts +0 -2
  176. package/dist/types/src/components/deprecated/index.d.ts.map +0 -1
  177. package/dist/types/src/hooks/useForm.d.ts +0 -67
  178. package/dist/types/src/hooks/useForm.d.ts.map +0 -1
  179. package/dist/types/src/hooks/useQueryRefOptions.d.ts +0 -23
  180. package/dist/types/src/hooks/useQueryRefOptions.d.ts.map +0 -1
  181. package/dist/types/src/hooks/useRefQueryLookupHandler.d.ts +0 -8
  182. package/dist/types/src/hooks/useRefQueryLookupHandler.d.ts.map +0 -1
  183. package/dist/types/src/util/schema.d.ts +0 -3
  184. package/dist/types/src/util/schema.d.ts.map +0 -1
  185. package/src/components/ControlSection/ControlSection.stories.tsx +0 -41
  186. package/src/components/ControlSection/ControlSection.tsx +0 -139
  187. package/src/components/Form/ArrayField.tsx +0 -124
  188. package/src/components/Form/Defaults.tsx +0 -203
  189. package/src/components/Form/FormActions.tsx +0 -53
  190. package/src/components/Form/FormContent.tsx +0 -240
  191. package/src/components/Form/FormContext.tsx +0 -110
  192. package/src/components/Form/Input.tsx +0 -51
  193. package/src/components/Form/RefField.tsx +0 -213
  194. package/src/components/Form/custom/GeoPointInput.tsx +0 -72
  195. package/src/components/Form/custom/SelectOptionsInput.stories.tsx +0 -61
  196. package/src/components/Form/custom/index.ts +0 -7
  197. package/src/components/Form/factory.tsx +0 -31
  198. package/src/components/deprecated/Form.stories.tsx +0 -62
  199. package/src/components/deprecated/Form.tsx +0 -119
  200. package/src/components/deprecated/FormInput.tsx +0 -71
  201. package/src/components/deprecated/index.ts +0 -5
  202. package/src/hooks/useForm.ts +0 -291
  203. package/src/hooks/useQueryRefOptions.ts +0 -53
  204. package/src/hooks/useRefQueryLookupHandler.ts +0 -39
  205. package/src/util/schema.ts +0 -14
@@ -1,807 +1,443 @@
1
1
  import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
2
 
3
3
  // src/translations.ts
4
- var translationKey = "react-ui-form";
4
+ var translationKey = "@dxos/react-ui-form";
5
5
  var translations = [
6
6
  {
7
7
  "en-US": {
8
8
  [translationKey]: {
9
- "fields label": "Fields",
10
- "hidden fields label": "Hidden Fields",
11
- "empty readonly ref field label": "(none)",
12
- // TODO(burdon): Standardize field/property.
13
- "button add property": "Add property",
14
- "field property label": "Property",
15
- "field property placeholder": "Property name",
16
- "field format label": "Type",
17
- "field path label": "Field path",
18
- "add field": "Add field",
19
- "delete field": "Delete field",
20
- "field limit reached": "Maximum number of fields reached",
21
- "boolean input true value": "Yes",
22
- "boolean input false value": "No",
23
- // TODO(burdon): Factor out?
24
- "button cancel": "Cancel",
25
- "button save": "Save",
26
- // FormatEnum
27
- "format boolean": "Boolean",
28
- "format currency": "Currency",
29
- "format date": "Date",
30
- "format date-time": "DateTime",
31
- "format did": "DID",
32
- "format duration": "Duration",
33
- "format dxn": "DXN",
34
- "format email": "Email",
35
- "format formula": "Formula",
36
- "format hostname": "Hostname",
37
- "format integer": "Integer",
38
- "format json": "JSON",
39
- "format latlng": "Geopoint",
40
- "format markdown": "Markdown",
41
- "format percent": "Percent",
42
- "format ref": "Reference",
43
- "format regex": "RegExp",
44
- "format string": "String",
45
- "format single-select": "Select",
46
- "format multi-select": "Multi-select",
47
- "format text": "Long text",
48
- "format time": "Time",
49
- "format timestamp": "Timestamp",
50
- "format user": "User",
51
- "format number": "Number",
52
- "format uri": "URI",
53
- "format url": "URL",
54
- "format uuid": "UUID",
55
- // Placeholders.
56
- "placeholder latitude": "Latitude",
57
- "placeholder longitude": "Longitude",
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",
9
+ "fields.label": "Fields",
10
+ "hidden-fields.label": "Hidden Fields",
11
+ "empty-readonly-ref-field.label": "(none)",
12
+ "add-property-button.label": "Add property",
13
+ "field-property.label": "Property",
14
+ "field-property.placeholder": "Property name",
15
+ "field-format.label": "Type",
16
+ "field-path.label": "Field path",
17
+ "add-field.button": "Add field",
18
+ "boolean-input-true.value": "Yes",
19
+ "boolean-input-false.value": "No",
20
+ "show-field.label": "Show field",
21
+ "hide-field.label": "Hide field",
22
+ "delete-field.label": "Delete field",
23
+ "ref-field-combobox-input.placeholder": "Search\u2026",
24
+ "ref-field.placeholder": "Select\u2026",
25
+ "ref-field.placeholder_one": "Select\u2026",
26
+ "ref-field.placeholder_other": "Select items\u2026",
27
+ "create-option.label": "Create",
28
+ "example.placeholder": "Example",
29
+ "latitude.placeholder": "Latitude (e.g., 40.7128)",
30
+ "longitude.placeholder": "Longitude (e.g., -74.0060)",
31
+ "cancel-button.label": "Cancel",
32
+ "save-button.label": "Save",
33
+ // TypeFormat
34
+ "format.boolean.label": "Boolean",
35
+ "format.currency.label": "Currency",
36
+ "format.date.label": "Date",
37
+ "format.date-time.label": "DateTime",
38
+ "format.did.label": "DID",
39
+ "format.duration.label": "Duration",
40
+ "format.dxn.label": "DXN",
41
+ "format.email.label": "Email",
42
+ "format.formula.label": "Formula",
43
+ "format.hostname.label": "Hostname",
44
+ "format.integer.label": "Integer",
45
+ "format.json.label": "JSON",
46
+ "format.lnglat.label": "Geopoint",
47
+ "format.markdown.label": "Markdown",
48
+ "format.percent.label": "Percent",
49
+ "format.ref.label": "Reference",
50
+ "format.regex.label": "RegExp",
51
+ "format.string.label": "String",
52
+ "format.single-select.label": "Select",
53
+ "format.multi-select.label": "Multi-select",
54
+ "format.text.label": "Long text",
55
+ "format.time.label": "Time",
56
+ "format.timestamp.label": "Timestamp",
57
+ "format.user.label": "User",
58
+ "format.number.label": "Number",
59
+ "format.uri.label": "URI",
60
+ "format.url.label": "URL",
61
+ "format.uuid.label": "UUID",
62
+ // GeoPointField.
63
+ "latitude.label": "Latitude",
64
+ "longitude.label": "Longitude",
65
+ // SelectOptionsField.
66
+ "select-option.label": "Label",
67
+ "select-option-label.placeholder": "Option label",
68
+ "select-option-delete.button": "Delete",
69
+ "select-option-add.button": "Add option",
64
70
  // System schema message.
65
- "system schema title": "System Schema",
66
- "system schema description": "This is a system schema and cannot be modified."
71
+ "system-schema.title": "System type",
72
+ "system-schema.description": "System type: cannot add or remove fields.",
73
+ "remove.button": "Remove"
67
74
  }
68
75
  }
69
76
  }
70
77
  ];
71
78
 
72
- // src/components/deprecated/FormInput.tsx
73
- import { useSignals as _useSignals } from "@preact-signals/safe-react/tracking";
74
- import React from "react";
75
- import { Input } from "@dxos/react-ui";
76
- import { mx, textBlockWidth } from "@dxos/react-ui-theme";
77
- var DeprecatedFormContainer = ({ children, classNames }) => {
78
- var _effect = _useSignals();
79
- try {
80
- return /* @__PURE__ */ React.createElement("div", {
81
- role: "none",
82
- className: "container-max-width p-4 justify-center overflow-x-hidden overflow-y-auto"
83
- }, /* @__PURE__ */ React.createElement("div", {
84
- role: "form",
85
- className: mx("flex flex-col", textBlockWidth, classNames)
86
- }, children));
87
- } finally {
88
- _effect.f();
79
+ // src/components/FieldEditor/FieldEditor.tsx
80
+ import React17, { useCallback as useCallback14, useEffect as useEffect7, useMemo as useMemo7, useState as useState5 } from "react";
81
+ import { Obj as Obj2 } from "@dxos/echo";
82
+ import { Format as Format4, FormatEnums, formatToType } from "@dxos/echo/internal";
83
+ import { log as log2 } from "@dxos/log";
84
+ import { useAsyncEffect, useTranslation as useTranslation8 } from "@dxos/react-ui";
85
+ import { formatToAdditionalPropertyAttributes, getFormatSchema } from "@dxos/schema";
86
+
87
+ // src/util/field.ts
88
+ import { Format, GeoLocation, TypeEnum } from "@dxos/echo/internal";
89
+ var parseValue = ({ type, format, value: value3 }) => {
90
+ if (value3 === void 0 || value3 === null || value3 === "") {
91
+ return void 0;
89
92
  }
90
- };
91
- var DeprecatedFormInput = ({ label, description, secondary, children }) => {
92
- var _effect = _useSignals();
93
- try {
94
- const primary = /* @__PURE__ */ React.createElement("div", {
95
- role: "none",
96
- className: "flex w-full gap-4 py-1"
97
- }, /* @__PURE__ */ React.createElement(Input.Root, null, /* @__PURE__ */ React.createElement("div", {
98
- role: "none",
99
- className: "flex flex-col w-full"
100
- }, /* @__PURE__ */ React.createElement(Input.Label, {
101
- classNames: "flex min-bs-[--rail-action] items-center",
102
- style: {
103
- fontSize: "unset"
93
+ const parseScalar = (type2) => {
94
+ switch (type2) {
95
+ case TypeEnum.Boolean: {
96
+ if (typeof value3 === "string") {
97
+ const lowercaseValue = value3.toLowerCase();
98
+ if (lowercaseValue === "0" || lowercaseValue === "false") {
99
+ return false;
100
+ } else if (lowercaseValue === "1" || lowercaseValue === "true") {
101
+ return true;
102
+ }
103
+ }
104
+ return Boolean(value3);
105
+ }
106
+ case TypeEnum.Number: {
107
+ const cleaned = typeof value3 === "string" ? value3.replace(/[^0-9.-]+/g, "") : value3;
108
+ const num = Number(cleaned);
109
+ return Number.isNaN(num) ? null : num;
110
+ }
111
+ case TypeEnum.String:
112
+ case TypeEnum.Ref:
113
+ return String(value3);
114
+ default: {
115
+ return value3;
104
116
  }
105
- }, label), description && /* @__PURE__ */ React.createElement(Input.DescriptionAndValidation, {
106
- classNames: "mbs-0.5"
107
- }, /* @__PURE__ */ React.createElement(Input.Description, null, description))), /* @__PURE__ */ React.createElement("div", {
108
- role: "none"
109
- }, /* @__PURE__ */ React.createElement("div", {
110
- role: "none",
111
- className: "flex min-bs-[--rail-action] items-center"
112
- }, children))));
113
- if (secondary) {
114
- return /* @__PURE__ */ React.createElement("div", {
115
- role: "none"
116
- }, primary, secondary);
117
117
  }
118
- return primary;
119
- } finally {
120
- _effect.f();
121
- }
122
- };
123
-
124
- // src/components/ControlSection/ControlSection.tsx
125
- import { useSignals as _useSignals2 } from "@preact-signals/safe-react/tracking";
126
- import React2 from "react";
127
- import { Button, Input as Input2, toLocalizedString, useTranslation } from "@dxos/react-ui";
128
- import { mx as mx2 } from "@dxos/react-ui-theme";
129
- var ControlPage = ({ children, classNames, ...props }) => {
130
- var _effect = _useSignals2();
131
- try {
132
- return /* @__PURE__ */ React2.createElement("div", {
133
- role: "none",
134
- className: mx2("pli-cardSpacingInline", classNames),
135
- ...props
136
- }, children);
137
- } finally {
138
- _effect.f();
139
- }
140
- };
141
- var ControlSection = ({ title, description, children }) => {
142
- var _effect = _useSignals2();
143
- try {
144
- return /* @__PURE__ */ React2.createElement(React2.Fragment, null, /* @__PURE__ */ React2.createElement(ControlSectionHeading, {
145
- title,
146
- description
147
- }), children);
148
- } finally {
149
- _effect.f();
150
- }
151
- };
152
- var ControlSectionHeading = ({ title, description }) => {
153
- var _effect = _useSignals2();
154
- try {
155
- const { t } = useTranslation(translationKey);
156
- return /* @__PURE__ */ React2.createElement(React2.Fragment, null, /* @__PURE__ */ React2.createElement("h2", {
157
- className: "pli-trimMd container-max-width text-xl mbs-trimLg mbe-trimMd"
158
- }, toLocalizedString(title, t)), description && /* @__PURE__ */ React2.createElement("p", {
159
- className: "pli-trimMd mlb-trimMd container-max-width text-description"
160
- }, toLocalizedString(description, t)));
161
- } finally {
162
- _effect.f();
163
- }
164
- };
165
- var ControlGroupButton = ({ classNames, ...props }) => {
166
- var _effect = _useSignals2();
167
- try {
168
- return /* @__PURE__ */ React2.createElement(Button, {
169
- ...props,
170
- classNames: [
171
- "md:col-span-2",
172
- classNames
173
- ]
174
- });
175
- } finally {
176
- _effect.f();
177
- }
178
- };
179
- var ControlGroup = ({ children, classNames }) => {
180
- var _effect = _useSignals2();
181
- try {
182
- return /* @__PURE__ */ React2.createElement("div", {
183
- role: "none",
184
- className: mx2("group container-max-width grid grid-cols-1 md:grid-cols-[1fr_min-content] gap-trimMd", classNames)
185
- }, children);
186
- } finally {
187
- _effect.f();
188
- }
189
- };
190
- var ControlFrame = ({ children }) => {
191
- var _effect = _useSignals2();
192
- try {
193
- return /* @__PURE__ */ React2.createElement("div", {
194
- role: "none",
195
- className: "p-trimMd container-max-width grid grid-cols-1 md:grid-cols-[1fr_1fr] gap-trimSm md:gap-trimMd border border-separator rounded-md"
196
- }, children);
197
- } finally {
198
- _effect.f();
199
- }
200
- };
201
- var controlItemClasses = "pli-trimMd plb-trimMd container-max-width grid md:col-span-2 grid-cols-subgrid items-center gap-trimSm border border-separator rounded-md *:first:!mbs-0 *:last:!mbe-0";
202
- var controlItemTitleClasses = "text-lg font-normal";
203
- var controlItemDescriptionClasses = "text-base mlb-trimSm md:mbe-0 text-description";
204
- var ControlItem = ({ title, description, children }) => {
205
- var _effect = _useSignals2();
206
- try {
207
- const { t } = useTranslation(translationKey);
208
- return /* @__PURE__ */ React2.createElement("div", {
209
- className: controlItemClasses
210
- }, /* @__PURE__ */ React2.createElement("div", {
211
- role: "none"
212
- }, /* @__PURE__ */ React2.createElement("h3", {
213
- className: controlItemTitleClasses
214
- }, toLocalizedString(title, t)), description && /* @__PURE__ */ React2.createElement("p", {
215
- className: controlItemDescriptionClasses
216
- }, toLocalizedString(description, t))), children);
217
- } finally {
218
- _effect.f();
219
- }
220
- };
221
- var ControlItemInput = ({ title, description, children }) => {
222
- var _effect = _useSignals2();
223
- try {
224
- const { t } = useTranslation(translationKey);
225
- return /* @__PURE__ */ React2.createElement(Input2.Root, null, /* @__PURE__ */ React2.createElement("div", {
226
- className: controlItemClasses
227
- }, /* @__PURE__ */ React2.createElement("div", {
228
- role: "none"
229
- }, /* @__PURE__ */ React2.createElement(Input2.Label, {
230
- classNames: controlItemTitleClasses
231
- }, toLocalizedString(title, t)), description && /* @__PURE__ */ React2.createElement(Input2.DescriptionAndValidation, null, /* @__PURE__ */ React2.createElement(Input2.Description, {
232
- classNames: controlItemDescriptionClasses
233
- }, toLocalizedString(description, t)))), children));
234
- } finally {
235
- _effect.f();
118
+ };
119
+ if (!format) {
120
+ return parseScalar(type);
236
121
  }
237
- };
238
- var ControlFrameItem = ({ title, description, children }) => {
239
- var _effect = _useSignals2();
240
- try {
241
- const { t } = useTranslation(translationKey);
242
- return /* @__PURE__ */ React2.createElement("div", {
243
- role: "group",
244
- className: "min-is-0"
245
- }, /* @__PURE__ */ React2.createElement("h3", {
246
- className: "text-lg mbe-2"
247
- }, toLocalizedString(title, t)), description && /* @__PURE__ */ React2.createElement("p", {
248
- className: "mlb-trimSm md:mbe-0 text-description"
249
- }, toLocalizedString(description, t)), children);
250
- } finally {
251
- _effect.f();
122
+ switch (format) {
123
+ case Format.TypeFormat.Boolean:
124
+ return parseScalar(TypeEnum.Boolean);
125
+ case Format.TypeFormat.Number:
126
+ case Format.TypeFormat.Percent:
127
+ case Format.TypeFormat.Currency:
128
+ return parseScalar(TypeEnum.Number);
129
+ case Format.TypeFormat.String:
130
+ case Format.TypeFormat.Markdown: {
131
+ return parseScalar(TypeEnum.String);
132
+ }
133
+ case Format.TypeFormat.Ref:
134
+ throw new Error(`unexpected format: ${Format.TypeFormat.Ref}`);
135
+ case Format.TypeFormat.DateTime:
136
+ case Format.TypeFormat.Date:
137
+ case Format.TypeFormat.Time:
138
+ case Format.TypeFormat.Timestamp: {
139
+ const date = new Date(value3);
140
+ return isNaN(date.getTime()) ? null : date;
141
+ }
142
+ case Format.TypeFormat.GeoPoint: {
143
+ if (typeof value3 === "string") {
144
+ const cleaned = value3.replace(/[^0-9.,-]+/g, "");
145
+ const parts = cleaned.split(",");
146
+ if (parts.length === 2) {
147
+ const lat = parseFloat(parts[0]);
148
+ const long = parseFloat(parts[1]);
149
+ if (!isNaN(lat) && !isNaN(long)) {
150
+ return GeoLocation.toGeoPoint({
151
+ latitude: lat,
152
+ longitude: long
153
+ });
154
+ }
155
+ }
156
+ }
157
+ return [
158
+ 0,
159
+ 0
160
+ ];
161
+ }
162
+ default: {
163
+ return value3;
164
+ }
252
165
  }
253
166
  };
254
-
255
- // src/components/FieldEditor/FieldEditor.tsx
256
- import { useSignals as _useSignals14 } from "@preact-signals/safe-react/tracking";
257
- import React14, { useCallback as useCallback9, useEffect as useEffect8, useMemo as useMemo7, useState as useState5 } from "react";
258
- import { FormatEnum as FormatEnum5, FormatEnums, formatToType } from "@dxos/echo-schema";
259
- import { log as log3 } from "@dxos/log";
260
- import { useTranslation as useTranslation8 } from "@dxos/react-ui";
261
- import { getFormatSchema, getSchemaProperties as getSchemaProperties3, sortProperties } from "@dxos/schema";
262
-
263
- // src/components/Form/custom/GeoPointInput.tsx
264
- import { useSignals as _useSignals4 } from "@preact-signals/safe-react/tracking";
265
- import React4, { useCallback, useState, useEffect, useMemo } from "react";
266
- import { GeoLocation } from "@dxos/echo-schema";
267
- import { Input as Input4, useTranslation as useTranslation2 } from "@dxos/react-ui";
268
- import { safeParseFloat } from "@dxos/util";
269
-
270
- // src/components/Form/Input.tsx
271
- import { useSignals as _useSignals3 } from "@preact-signals/safe-react/tracking";
272
- import React3 from "react";
273
- import { Icon, Input as Input3, Tooltip } from "@dxos/react-ui";
274
- import { labelSpacing } from "@dxos/react-ui-stack";
275
- import { errorText, mx as mx3 } from "@dxos/react-ui-theme";
276
- var InputHeader = ({ error, label, readonly }) => {
277
- var _effect = _useSignals3();
278
- try {
279
- const Label = readonly ? "span" : Input3.Label;
280
- const labelProps = readonly ? {} : {
281
- classNames: "!mlb-0"
282
- };
283
- return /* @__PURE__ */ React3.createElement("div", {
284
- role: "none",
285
- className: mx3("flex justify-between items-center", labelSpacing)
286
- }, /* @__PURE__ */ React3.createElement(Label, labelProps, label), error && /* @__PURE__ */ React3.createElement(Tooltip.Trigger, {
287
- asChild: true,
288
- content: error,
289
- side: "bottom"
290
- }, /* @__PURE__ */ React3.createElement(Icon, {
291
- icon: "ph--warning--regular",
292
- size: 4,
293
- classNames: errorText
294
- })));
295
- } finally {
296
- _effect.f();
167
+ var cellClassesForFieldType = ({ type, format }) => {
168
+ switch (format || type) {
169
+ case Format.TypeFormat.Markdown:
170
+ return void 0;
171
+ case Format.TypeFormat.Time:
172
+ case Format.TypeFormat.Timestamp:
173
+ case Format.TypeFormat.DateTime:
174
+ case Format.TypeFormat.Date:
175
+ case Format.TypeFormat.Duration:
176
+ return [
177
+ "font-mono",
178
+ "text-right"
179
+ ];
180
+ case Format.TypeFormat.Currency:
181
+ return [
182
+ "text-right"
183
+ ];
184
+ case Format.TypeFormat.JSON:
185
+ case Format.TypeFormat.DID:
186
+ return [
187
+ "font-mono"
188
+ ];
189
+ case TypeEnum.Number:
190
+ case TypeEnum.Boolean:
191
+ return [
192
+ "text-right",
193
+ "font-mono"
194
+ ];
195
+ case TypeEnum.String:
196
+ return void 0;
197
+ case TypeEnum.Ref:
198
+ return void 0;
199
+ default:
200
+ return void 0;
297
201
  }
298
202
  };
203
+ var pathNotUniqueError = (path) => ({
204
+ path: "path",
205
+ message: `'${path}' is already present`
206
+ });
299
207
 
300
- // src/components/Form/custom/GeoPointInput.tsx
301
- var GeoPointInput = ({ type, label, disabled, getStatus, getValue: getValue3, onValueChange, onBlur }) => {
302
- var _effect = _useSignals4();
303
- try {
304
- const { t } = useTranslation2(translationKey);
305
- const { status, error } = getStatus();
306
- const geoPoint = useMemo(() => getValue3() ?? [
307
- 0,
308
- 0
309
- ], [
310
- getValue3
311
- ]);
312
- const geoLocation = useMemo(() => GeoLocation.fromGeoPoint(geoPoint), [
313
- geoPoint
314
- ]);
315
- const [longitudeText, setLongitudeText] = useState(geoLocation.longitude?.toString());
316
- const [latitudeText, setLatitudeText] = useState(geoLocation.latitude?.toString());
317
- useEffect(() => {
318
- const location = GeoLocation.fromGeoPoint(geoPoint);
319
- setLongitudeText(location.longitude.toString());
320
- setLatitudeText(location.latitude.toString());
321
- }, [
322
- geoPoint
323
- ]);
324
- const handleCoordinateChange = useCallback((coordinateType, setText) => (event) => {
325
- const inputText = event.target.value;
326
- setText(inputText);
327
- if (inputText !== "" && inputText !== "-") {
328
- const coord = safeParseFloat(inputText);
329
- if (coord !== void 0 && !isNaN(coord)) {
330
- const currentLocation = GeoLocation.fromGeoPoint(getValue3() ?? [
331
- 0,
332
- 0
333
- ]);
334
- const newLocation = {
335
- ...currentLocation,
336
- [coordinateType]: coord
337
- };
338
- const newValue = GeoLocation.toGeoPoint(newLocation);
339
- onValueChange(type, newValue);
340
- }
208
+ // src/util/formatting.ts
209
+ import { format as formatDate } from "date-fns/format";
210
+ import { Format as Format2, GeoLocation as GeoLocation2, TypeEnum as TypeEnum2 } from "@dxos/echo/internal";
211
+ var formatForDisplay = ({ type, format, value: value3, locale = void 0 }) => {
212
+ const formatScalar = (type2) => {
213
+ switch (type2) {
214
+ case TypeEnum2.Boolean:
215
+ return value3.toLocaleString().toUpperCase();
216
+ case TypeEnum2.Number:
217
+ return value3.toLocaleString(locale);
218
+ case TypeEnum2.String:
219
+ case TypeEnum2.Ref:
220
+ return String(value3);
221
+ default: {
222
+ return String(value3);
341
223
  }
342
- }, [
343
- getValue3,
344
- onValueChange,
345
- type
346
- ]);
347
- return /* @__PURE__ */ React4.createElement(Input4.Root, {
348
- validationValence: status
349
- }, /* @__PURE__ */ React4.createElement(InputHeader, {
350
- error,
351
- label
352
- }), /* @__PURE__ */ React4.createElement("div", {
353
- role: "none",
354
- className: "grid grid-cols-2 gap-2"
355
- }, /* @__PURE__ */ React4.createElement(Input4.TextInput, {
356
- type: "text",
357
- pattern: "^-?[0-9]*\\.?[0-9]*$",
358
- disabled,
359
- placeholder: t("placeholder latitude"),
360
- value: latitudeText,
361
- onChange: handleCoordinateChange("latitude", setLatitudeText),
362
- onBlur
363
- }), /* @__PURE__ */ React4.createElement(Input4.TextInput, {
364
- type: "text",
365
- pattern: "^-?[0-9]*\\.?[0-9]*$",
366
- disabled,
367
- placeholder: t("placeholder longitude"),
368
- value: longitudeText,
369
- onChange: handleCoordinateChange("longitude", setLongitudeText),
370
- onBlur
371
- })));
372
- } finally {
373
- _effect.f();
224
+ }
225
+ };
226
+ if (!format) {
227
+ return formatScalar(type);
374
228
  }
375
- };
376
-
377
- // src/components/Form/custom/SelectOptionsInput.tsx
378
- import { useSignals as _useSignals5 } from "@preact-signals/safe-react/tracking";
379
- import React5, { useCallback as useCallback2, useEffect as useEffect2, useState as useState2, useRef } from "react";
380
- import { PublicKey } from "@dxos/keys";
381
- import { Icon as Icon2, IconButton, Input as Input5, Tag, Toolbar, useTranslation as useTranslation3 } from "@dxos/react-ui";
382
- import { List } from "@dxos/react-ui-list";
383
- import { HuePicker } from "@dxos/react-ui-pickers";
384
- import { hues, mx as mx4 } from "@dxos/react-ui-theme";
385
- var SelectOptionInput = ({ type, label, disabled, getStatus, getValue: getValue3, onValueChange }) => {
386
- var _effect = _useSignals5();
387
- try {
388
- const [selected, setSelectedId] = useState2(null);
389
- const [isNewOption, setIsNewOption] = useState2(false);
390
- const inputRef = useRef(null);
391
- const { t } = useTranslation3(translationKey);
392
- const { status, error } = getStatus();
393
- const options = getValue3();
394
- useEffect2(() => {
395
- if (options === void 0) {
396
- onValueChange(type, []);
229
+ switch (format) {
230
+ case Format2.TypeFormat.Boolean: {
231
+ return formatScalar(TypeEnum2.Boolean);
232
+ }
233
+ case Format2.TypeFormat.Number: {
234
+ return formatScalar(TypeEnum2.Number);
235
+ }
236
+ case Format2.TypeFormat.String:
237
+ case Format2.TypeFormat.Ref: {
238
+ return formatScalar(TypeEnum2.String);
239
+ }
240
+ case Format2.TypeFormat.Percent: {
241
+ return `${value3 * 100}%`;
242
+ }
243
+ case Format2.TypeFormat.Currency: {
244
+ return value3.toLocaleString(locale, {
245
+ style: "currency",
246
+ currency: "USD",
247
+ minimumFractionDigits: 2,
248
+ maximumFractionDigits: 2
249
+ });
250
+ }
251
+ case Format2.TypeFormat.Date: {
252
+ try {
253
+ return formatDate(new Date(value3), "yyyy-MM-dd");
254
+ } catch (error) {
255
+ return "Invalid Date";
397
256
  }
398
- }, [
399
- options,
400
- onValueChange,
401
- type
402
- ]);
403
- const randomHue = () => {
404
- const usedHues = new Set(options?.map((option) => option.color) ?? []);
405
- const unusedHues = hues.filter((hue) => !usedHues.has(hue));
406
- if (unusedHues.length > 0) {
407
- return unusedHues[Math.floor(Math.random() * unusedHues.length)];
257
+ }
258
+ case Format2.TypeFormat.Time: {
259
+ try {
260
+ return formatDate(new Date(value3), "HH:mm:ss");
261
+ } catch (error) {
262
+ return "Invalid Time";
408
263
  }
409
- const lastThree = new Set(options?.slice(-3).map((option) => option.color) ?? []);
410
- const availableHues = hues.filter((hue) => !lastThree.has(hue));
411
- return availableHues[Math.floor(Math.random() * availableHues.length)] ?? hues[Math.floor(Math.random() * hues.length)];
412
- };
413
- const handleAdd = useCallback2(() => {
414
- const newId = PublicKey.random().truncate();
415
- const newOption = {
416
- id: newId,
417
- title: "",
418
- color: randomHue()
419
- };
420
- onValueChange(type, [
421
- ...options ?? [],
422
- newOption
423
- ]);
424
- setSelectedId(newId);
425
- setIsNewOption(true);
426
- }, [
427
- options,
428
- type,
429
- onValueChange
430
- ]);
431
- const handleDelete = useCallback2((id) => {
432
- const newOptions = options?.filter((option) => option.id !== id) ?? [];
433
- onValueChange(type, newOptions);
434
- setSelectedId(null);
435
- }, [
436
- options,
437
- type,
438
- onValueChange
439
- ]);
440
- const handleMove = useCallback2((from, to) => {
441
- if (!options) {
442
- return;
264
+ }
265
+ case Format2.TypeFormat.DateTime: {
266
+ try {
267
+ return formatDate(new Date(value3), "yyyy-MM-dd HH:mm:ss");
268
+ } catch (error) {
269
+ return "Invalid DateTime";
443
270
  }
444
- const newOptions = [
445
- ...options
446
- ];
447
- const [removed] = newOptions.splice(from, 1);
448
- newOptions.splice(to, 0, removed);
449
- onValueChange(type, newOptions);
450
- }, [
451
- options,
452
- type,
453
- onValueChange
454
- ]);
455
- const handleClick = useCallback2((id) => {
456
- setSelectedId((current) => current === id ? null : id);
457
- }, []);
458
- const handleTitleChange = useCallback2((id) => (e) => {
459
- const newOptions = options?.map((o) => o.id === id ? {
460
- ...o,
461
- title: e.target.value
462
- } : o);
463
- onValueChange(type, newOptions ?? []);
464
- }, [
465
- options,
466
- type,
467
- onValueChange
468
- ]);
469
- const handleKeyDown = useCallback2((e) => {
470
- if (e.key === "Enter") {
471
- setSelectedId(null);
271
+ }
272
+ case Format2.TypeFormat.GeoPoint: {
273
+ if (value3 === null || value3 === void 0) {
274
+ return "";
472
275
  }
473
- }, []);
474
- const handleColorChange = useCallback2((id) => (hue) => {
475
- const newOptions = options?.map((o) => o.id === id ? {
476
- ...o,
477
- color: hue
478
- } : o);
479
- onValueChange(type, newOptions ?? []);
480
- }, [
481
- options,
482
- type,
483
- onValueChange
484
- ]);
485
- useEffect2(() => {
486
- if (selected && isNewOption && inputRef.current) {
487
- inputRef.current.focus();
488
- setIsNewOption(false);
276
+ if (Array.isArray(value3) && value3.length >= 2 && value3.every(Number.isFinite)) {
277
+ const { latitude, longitude } = GeoLocation2.fromGeoPoint(value3);
278
+ return `${latitude},${longitude}`;
489
279
  }
490
- }, [
491
- selected,
492
- isNewOption
493
- ]);
494
- return /* @__PURE__ */ React5.createElement(Input5.Root, {
495
- validationValence: status
496
- }, /* @__PURE__ */ React5.createElement(InputHeader, {
497
- error,
498
- label
499
- }), /* @__PURE__ */ React5.createElement("div", {
500
- role: "none"
501
- }, options && /* @__PURE__ */ React5.createElement(List.Root, {
502
- items: options,
503
- isItem: (item) => true,
504
- onMove: handleMove
505
- }, ({ items }) => /* @__PURE__ */ React5.createElement("div", {
506
- role: "list",
507
- className: "w-full overflow-auto"
508
- }, items?.map((item) => /* @__PURE__ */ React5.createElement("div", {
509
- key: item.id
510
- }, /* @__PURE__ */ React5.createElement(List.Item, {
511
- role: "button",
512
- item,
513
- classNames: [
514
- "p-1 plb-2",
515
- "flex flex-col",
516
- "cursor-pointer",
517
- "hover:bg-hoverOverlay"
518
- ],
519
- "aria-expanded": selected === item.id
520
- }, /* @__PURE__ */ React5.createElement("div", {
521
- className: "flex items-center"
522
- }, /* @__PURE__ */ React5.createElement(List.ItemDragHandle, null), /* @__PURE__ */ React5.createElement(List.ItemTitle, {
523
- onClick: () => handleClick(item.id),
524
- classNames: "flex-1"
525
- }, /* @__PURE__ */ React5.createElement(Tag, {
526
- palette: item.color
527
- }, item.title || "\u200B")), /* @__PURE__ */ React5.createElement(Icon2, {
528
- icon: selected === item.id ? "ph--caret-down--regular" : "ph--caret-right--regular",
529
- onClick: () => handleClick(item.id)
530
- })), selected === item.id && /* @__PURE__ */ React5.createElement("div", {
531
- className: "mis-4 mbs-2 flex flex-col gap-1"
532
- }, /* @__PURE__ */ React5.createElement(Input5.Label, {
533
- classNames: "text-xs"
534
- }, t("select option label")), /* @__PURE__ */ React5.createElement("div", {
535
- className: "flex flex-row items-center gap-1"
536
- }, /* @__PURE__ */ React5.createElement(Input5.TextInput, {
537
- placeholder: t("select option label placeholder"),
538
- ref: selected === item.id ? inputRef : void 0,
539
- value: item.title,
540
- onChange: handleTitleChange(item.id),
541
- onKeyDown: handleKeyDown,
542
- classNames: "flex-1",
543
- "data-no-submit": true
544
- }), /* @__PURE__ */ React5.createElement(Toolbar.Root, {
545
- classNames: "p-0 m-0 !is-auto"
546
- }, /* @__PURE__ */ React5.createElement(HuePicker, {
547
- value: item.color,
548
- onChange: handleColorChange(item.id),
549
- rootVariant: "toolbar-button"
550
- })), /* @__PURE__ */ React5.createElement(IconButton, {
551
- icon: "ph--trash--fill",
552
- iconOnly: true,
553
- label: t("select option delete"),
554
- onClick: () => handleDelete(item.id)
555
- })))))), /* @__PURE__ */ React5.createElement("div", {
556
- role: "listitem"
557
- }, /* @__PURE__ */ React5.createElement("div", {
558
- role: "button",
559
- className: mx4("p-1 plb-2", "flex flex-col", "cursor-pointer", "hover:bg-hoverOverlay"),
560
- onClick: handleAdd
561
- }, /* @__PURE__ */ React5.createElement("div", {
562
- className: "flex items-center gap-1"
563
- }, /* @__PURE__ */ React5.createElement(Icon2, {
564
- icon: "ph--plus--regular"
565
- }), /* @__PURE__ */ React5.createElement("span", {
566
- className: "text-sm"
567
- }, t("select option add")))))))));
568
- } finally {
569
- _effect.f();
570
- }
571
- };
572
-
573
- // src/components/Form/custom/TupleInput.tsx
574
- import { useSignals as _useSignals6 } from "@preact-signals/safe-react/tracking";
575
- import React6 from "react";
576
- import { Input as Input6 } from "@dxos/react-ui";
577
- import { mx as mx5 } from "@dxos/react-ui-theme";
578
- import { safeParseFloat as safeParseFloat2 } from "@dxos/util";
579
- var gridCols = [
580
- "grid-cols-1",
581
- "grid-cols-2",
582
- "grid-cols-3",
583
- "grid-cols-4"
584
- ];
585
- var TupleInput = ({ binding, type, label, disabled, getStatus, getValue: getValue3, onValueChange, onBlur }) => {
586
- var _effect = _useSignals6();
587
- try {
588
- const { status, error } = getStatus();
589
- const values = getValue3() ?? {};
590
- return /* @__PURE__ */ React6.createElement(Input6.Root, {
591
- validationValence: status
592
- }, /* @__PURE__ */ React6.createElement(InputHeader, {
593
- error,
594
- label
595
- }), /* @__PURE__ */ React6.createElement("div", {
596
- className: mx5("grid gap-2", gridCols[binding.length - 1])
597
- }, binding.map((prop) => /* @__PURE__ */ React6.createElement(Input6.TextInput, {
598
- key: prop,
599
- type: "number",
600
- disabled,
601
- value: values[prop],
602
- onChange: (event) => onValueChange(type, {
603
- ...values,
604
- [prop]: safeParseFloat2(event.target.value, 0)
605
- }),
606
- onBlur
607
- }))));
608
- } finally {
609
- _effect.f();
610
- }
611
- };
612
-
613
- // src/components/Form/Defaults.tsx
614
- import { useSignals as _useSignals7 } from "@preact-signals/safe-react/tracking";
615
- import React7, { useCallback as useCallback3, useEffect as useEffect3, useRef as useRef2 } from "react";
616
- import { Input as Input7, Select, useTranslation as useTranslation4 } from "@dxos/react-ui";
617
- var TextInput = ({ type, label, inputOnly, disabled, placeholder, getStatus, getValue: getValue3, onValueChange, onBlur }) => {
618
- var _effect = _useSignals7();
619
- try {
620
- const { status, error } = getStatus();
621
- return disabled && !getValue3() ? null : disabled && inputOnly ? /* @__PURE__ */ React7.createElement("p", null, getValue3() ?? "") : /* @__PURE__ */ React7.createElement(Input7.Root, {
622
- validationValence: status
623
- }, !inputOnly && /* @__PURE__ */ React7.createElement(InputHeader, {
624
- error,
625
- label
626
- }), disabled ? /* @__PURE__ */ React7.createElement("p", null, getValue3() ?? "") : /* @__PURE__ */ React7.createElement(Input7.TextInput, {
627
- disabled,
628
- placeholder,
629
- value: getValue3() ?? "",
630
- onChange: (event) => onValueChange(type, event.target.value),
631
- onBlur
632
- }), inputOnly && /* @__PURE__ */ React7.createElement(Input7.Validation, null, error));
633
- } finally {
634
- _effect.f();
280
+ return String(value3);
281
+ }
282
+ default: {
283
+ if (value3 === null || value3 === "undefined") {
284
+ return "";
285
+ }
286
+ return String(value3);
287
+ }
635
288
  }
636
289
  };
637
- var NumberInput = ({ type, label, inputOnly, disabled, placeholder, getStatus, getValue: getValue3, onValueChange, onBlur }) => {
638
- var _effect = _useSignals7();
639
- try {
640
- const { status, error } = getStatus();
641
- return disabled && !getValue3() ? null : disabled && inputOnly ? /* @__PURE__ */ React7.createElement("p", null, getValue3() ?? "") : /* @__PURE__ */ React7.createElement(Input7.Root, {
642
- validationValence: status
643
- }, !inputOnly && /* @__PURE__ */ React7.createElement(InputHeader, {
644
- error,
645
- label
646
- }), disabled ? /* @__PURE__ */ React7.createElement("p", null, getValue3() ?? "") : /* @__PURE__ */ React7.createElement(Input7.TextInput, {
647
- type: "number",
648
- disabled,
649
- placeholder,
650
- value: getValue3() ?? 0,
651
- onChange: (event) => onValueChange(type, event.target.value),
652
- onBlur
653
- }), inputOnly && /* @__PURE__ */ React7.createElement(Input7.DescriptionAndValidation, null, error));
654
- } finally {
655
- _effect.f();
290
+ var formatForEditing = ({ type, format, value: value3, locale = void 0 }) => {
291
+ const formatScalar = (type2) => {
292
+ switch (type2) {
293
+ case TypeEnum2.Boolean:
294
+ case TypeEnum2.Number:
295
+ case TypeEnum2.String:
296
+ case TypeEnum2.Ref:
297
+ return String(value3);
298
+ default:
299
+ return String(value3);
300
+ }
301
+ };
302
+ if (!format) {
303
+ return formatScalar(type);
656
304
  }
657
- };
658
- var BooleanInput = ({ type, label, inputOnly, getStatus, getValue: getValue3, onValueChange, disabled }) => {
659
- var _effect = _useSignals7();
660
- try {
661
- const { status, error } = getStatus();
662
- const checked = Boolean(getValue3());
663
- const { t } = useTranslation4(translationKey);
664
- return /* @__PURE__ */ React7.createElement(Input7.Root, {
665
- validationValence: status
666
- }, !inputOnly && /* @__PURE__ */ React7.createElement(InputHeader, {
667
- error,
668
- label
669
- }), disabled ? /* @__PURE__ */ React7.createElement("p", null, t(checked ? "boolean input true value" : "boolean input false value")) : /* @__PURE__ */ React7.createElement(Input7.Switch, {
670
- checked,
671
- onCheckedChange: (value) => onValueChange(type, value)
672
- }), inputOnly && /* @__PURE__ */ React7.createElement(Input7.DescriptionAndValidation, null, error));
673
- } finally {
674
- _effect.f();
305
+ switch (format) {
306
+ case Format2.TypeFormat.Boolean:
307
+ case Format2.TypeFormat.Number:
308
+ case Format2.TypeFormat.String:
309
+ case Format2.TypeFormat.Ref: {
310
+ return formatScalar(type);
311
+ }
312
+ case Format2.TypeFormat.Percent: {
313
+ return String(value3 * 100);
314
+ }
315
+ case Format2.TypeFormat.Currency: {
316
+ return String(value3);
317
+ }
318
+ case Format2.TypeFormat.DateTime: {
319
+ const date = new Date(value3);
320
+ return date.toISOString();
321
+ }
322
+ case Format2.TypeFormat.Date: {
323
+ const date = new Date(value3);
324
+ return date.toISOString().split("T")[0];
325
+ }
326
+ case Format2.TypeFormat.Time: {
327
+ const date = new Date(value3);
328
+ return date.toISOString().split("T")[1].split(".")[0];
329
+ }
330
+ case Format2.TypeFormat.GeoPoint: {
331
+ if (value3 === null || value3 === void 0) {
332
+ return "";
333
+ }
334
+ if (Array.isArray(value3) && value3.length >= 2 && value3.every(Number.isFinite)) {
335
+ const { latitude, longitude } = GeoLocation2.fromGeoPoint(value3);
336
+ return `${latitude},${longitude}`;
337
+ }
338
+ return String(value3);
339
+ }
340
+ default: {
341
+ return String(value3);
342
+ }
675
343
  }
676
344
  };
677
- var SelectInput = ({ type, label, inputOnly, disabled, placeholder, options, getStatus, getValue: getValue3, onValueChange }) => {
678
- var _effect = _useSignals7();
679
- try {
680
- const { status, error } = getStatus();
681
- const value = getValue3();
682
- const handleValueChange = useCallback3((value2) => onValueChange(type, value2), [
683
- type,
684
- onValueChange
685
- ]);
686
- return disabled && !value ? null : /* @__PURE__ */ React7.createElement(Input7.Root, {
687
- validationValence: status
688
- }, !inputOnly && /* @__PURE__ */ React7.createElement(InputHeader, {
689
- error,
690
- label
691
- }), disabled ? /* @__PURE__ */ React7.createElement("p", null, options?.find(({ value: optionValue }) => optionValue === value)?.label ?? String(value)) : /* @__PURE__ */ React7.createElement(Select.Root, {
692
- value,
693
- onValueChange: handleValueChange
694
- }, /* @__PURE__ */ React7.createElement(Select.TriggerButton, {
695
- classNames: "is-full",
696
- disabled,
697
- placeholder
698
- }), /* @__PURE__ */ React7.createElement(Select.Portal, null, /* @__PURE__ */ React7.createElement(Select.Content, null, /* @__PURE__ */ React7.createElement(Select.Viewport, null, options?.map(({ value: value2, label: label2 }) => (
699
- // NOTE: Numeric values are converted to and from strings.
700
- /* @__PURE__ */ React7.createElement(Select.Option, {
701
- key: String(value2),
702
- value: String(value2)
703
- }, label2 ?? String(value2))
704
- )))))), inputOnly && /* @__PURE__ */ React7.createElement(Input7.DescriptionAndValidation, null, error));
705
- } finally {
706
- _effect.f();
707
- }
345
+
346
+ // src/util/properties.ts
347
+ import * as Option from "effect/Option";
348
+ import { Annotation } from "@dxos/echo";
349
+ import { getProperties } from "@dxos/effect";
350
+ var getFormProperties = (ast) => {
351
+ return getProperties(ast).filter((prop) => Annotation.FormInputAnnotation.getFromAst(prop.type).pipe(Option.getOrElse(() => true)));
708
352
  };
709
- var MarkdownInput = ({ type, label, inputOnly, disabled, placeholder, getStatus, getValue: getValue3, onValueChange, onBlur }) => {
710
- var _effect = _useSignals7();
711
- try {
712
- const { status, error } = getStatus();
713
- const textareaRef = useRef2(null);
714
- const adjustHeight = useCallback3(() => {
715
- const textarea = textareaRef.current;
716
- if (textarea) {
717
- textarea.style.blockSize = "auto";
718
- textarea.style.blockSize = `${textarea.scrollHeight + 2}px`;
353
+
354
+ // src/util/refs.ts
355
+ import { Ref } from "@dxos/echo";
356
+ import { ReferenceAnnotationId } from "@dxos/echo/internal";
357
+ import { findAnnotation, getArrayElementType, isArrayType } from "@dxos/effect";
358
+ var getRefProps = (ast) => {
359
+ if (isArrayType(ast)) {
360
+ const elementType = getArrayElementType(ast);
361
+ if (elementType) {
362
+ if (Ref.isRefType(elementType)) {
363
+ const typename = findAnnotation(elementType, ReferenceAnnotationId)?.typename;
364
+ return {
365
+ ast: elementType,
366
+ isArray: true,
367
+ typename
368
+ };
719
369
  }
720
- }, []);
721
- useEffect3(() => {
722
- adjustHeight();
723
- }, [
724
- adjustHeight
725
- ]);
726
- useEffect3(() => {
727
- adjustHeight();
728
- }, [
729
- getValue3(),
730
- adjustHeight
731
- ]);
732
- return /* @__PURE__ */ React7.createElement(Input7.Root, {
733
- validationValence: status
734
- }, !inputOnly && /* @__PURE__ */ React7.createElement(InputHeader, {
735
- error,
736
- label
737
- }), disabled ? /* @__PURE__ */ React7.createElement("p", null, getValue3() ?? "") : /* @__PURE__ */ React7.createElement(Input7.TextArea, {
738
- ref: textareaRef,
739
- disabled,
740
- placeholder,
741
- value: getValue3() ?? "",
742
- classNames: "min-bs-auto max-h-40 overflow-auto",
743
- onChange: (event) => onValueChange(type, event.target.value),
744
- onBlur,
745
- style: {
746
- resize: "none"
747
- },
748
- spellCheck: false
749
- }), inputOnly && /* @__PURE__ */ React7.createElement(Input7.Validation, null, error));
750
- } finally {
751
- _effect.f();
370
+ }
371
+ }
372
+ if (Ref.isRefType(ast)) {
373
+ const typename = findAnnotation(ast, ReferenceAnnotationId)?.typename;
374
+ return {
375
+ ast,
376
+ isArray: false,
377
+ typename
378
+ };
752
379
  }
380
+ return void 0;
753
381
  };
754
382
 
755
- // src/components/Form/Form.tsx
756
- import { useSignals as _useSignals13 } from "@preact-signals/safe-react/tracking";
757
- import React13, { useEffect as useEffect7, useMemo as useMemo6, useRef as useRef3 } from "react";
758
- import { cardDialogOverflow, cardSpacing as cardSpacing2 } from "@dxos/react-ui-stack";
759
-
760
- // src/components/Form/FormActions.tsx
761
- import { useSignals as _useSignals9 } from "@preact-signals/safe-react/tracking";
762
- import React9 from "react";
763
- import { IconButton as IconButton2, useTranslation as useTranslation5 } from "@dxos/react-ui";
764
- import { cardSpacing } from "@dxos/react-ui-stack";
765
- import { mx as mx6 } from "@dxos/react-ui-theme";
383
+ // src/components/Form/fields/ArrayField.tsx
384
+ import * as Option3 from "effect/Option";
385
+ import * as SchemaAST3 from "effect/SchemaAST";
386
+ import React5, { useCallback as useCallback3 } from "react";
387
+ import { findNode as findNode2, getArrayElementType as getArrayElementType2, getDiscriminatedType as getDiscriminatedType2, isDiscriminatedUnion as isDiscriminatedUnion2, isNestedType as isNestedType2 } from "@dxos/effect";
388
+ import { IconButton as IconButton2, useTranslation as useTranslation3 } from "@dxos/react-ui";
766
389
 
767
- // src/components/Form/FormContext.tsx
768
- import { useSignals as _useSignals8 } from "@preact-signals/safe-react/tracking";
769
- import React8, { createContext, useContext, useEffect as useEffect6, useMemo as useMemo3, useCallback as useCallback6 } from "react";
770
- import { raise } from "@dxos/debug";
771
- import { getValue as getValue2 } from "@dxos/echo-schema";
772
- import { createJsonPath as createJsonPath2 } from "@dxos/effect";
390
+ // src/components/Form/Form.tsx
391
+ import { createContext } from "@radix-ui/react-context";
392
+ import * as Schema2 from "effect/Schema";
393
+ import * as SchemaAST2 from "effect/SchemaAST";
394
+ import React4, { useEffect as useEffect3, useMemo as useMemo4, useRef } from "react";
395
+ import { createJsonPath as createJsonPath3, getValue as getValue$2 } from "@dxos/effect";
396
+ import { IconButton, ScrollArea, useTranslation as useTranslation2 } from "@dxos/react-ui";
397
+ import { composable, composableProps, mx } from "@dxos/ui-theme";
773
398
 
774
- // src/hooks/useForm.ts
775
- import { SchemaAST } from "effect";
776
- import { useCallback as useCallback4, useEffect as useEffect4, useMemo as useMemo2, useState as useState3 } from "react";
777
- import { getValue, setValue } from "@dxos/echo-schema";
778
- import { createJsonPath, fromEffectValidationPath } from "@dxos/effect";
779
- import { invariant } from "@dxos/invariant";
399
+ // src/hooks/useFormHandler.ts
400
+ import { useControllableState } from "@radix-ui/react-use-controllable-state";
401
+ import { useCallback, useEffect, useMemo, useState } from "react";
402
+ import { createJsonPath, fromEffectValidationPath, getValue as getValue$ } from "@dxos/effect";
780
403
  import { log } from "@dxos/log";
404
+ import { useDefaultValue } from "@dxos/react-ui";
781
405
  import { validateSchema } from "@dxos/schema";
782
- var __dxlog_file = "/__w/dxos/dxos/packages/ui/react-ui-form/src/hooks/useForm.ts";
783
- var useForm = ({ schema, initialValues, onValuesChanged, onValidate, onValid, onSave }) => {
784
- invariant(SchemaAST.isTypeLiteral(schema.ast), void 0, {
785
- F: __dxlog_file,
786
- L: 93,
787
- S: void 0,
788
- A: [
789
- "SchemaAST.isTypeLiteral(schema.ast)",
790
- ""
791
- ]
406
+ var __dxlog_file = "/__w/dxos/dxos/packages/ui/react-ui-form/src/hooks/useFormHandler.ts";
407
+ var useFormHandler = ({ schema, autoSave, values: valuesProp, defaultValues: defaultValuesProp, onValuesChanged, onValidate, onSave, onCancel, ...props }) => {
408
+ const [changed, setChanged] = useState({});
409
+ const [touched, setTouched] = useState({});
410
+ const [errors, setErrors] = useState({});
411
+ const [saving, setSaving] = useState(false);
412
+ const defaultValues = useDefaultValue(defaultValuesProp, () => ({}));
413
+ const [values$, setValues] = useControllableState({
414
+ prop: valuesProp,
415
+ defaultProp: defaultValues,
416
+ onChange: () => {
417
+ if (valuesProp !== void 0) {
418
+ setValues(valuesProp ?? defaultValues);
419
+ setChanged({});
420
+ setTouched({});
421
+ setErrors({});
422
+ setSaving(false);
423
+ }
424
+ }
792
425
  });
793
- const [values, setValues] = useState3(initialValues);
794
- useEffect4(() => {
795
- setValues(initialValues);
796
- }, [
797
- initialValues
798
- ]);
799
- const [touched, setTouched] = useState3(createKeySet(initialValues, false));
800
- const [changed, setChanged] = useState3(createKeySet(initialValues, false));
801
- const [errors, setErrors] = useState3({});
802
- const [saving, setSaving] = useState3(false);
803
- const validate = useCallback4((values2) => {
426
+ const values = values$;
427
+ const validate = useCallback((values2) => {
428
+ if (!schema) {
429
+ return false;
430
+ }
804
431
  let errors2 = validateSchema(schema, values2) ?? [];
432
+ log("validate", {
433
+ values: values2,
434
+ errors: errors2
435
+ }, {
436
+ F: __dxlog_file,
437
+ L: 155,
438
+ S: void 0,
439
+ C: (f, a) => f(...a)
440
+ });
805
441
  if (errors2.length === 0 && onValidate) {
806
442
  const validatedValues = values2;
807
443
  errors2 = onValidate(validatedValues) ?? [];
@@ -813,36 +449,38 @@ var useForm = ({ schema, initialValues, onValuesChanged, onValidate, onValid, on
813
449
  schema,
814
450
  onValidate
815
451
  ]);
816
- const [schemaDirty, setSchemaDirty] = useState3(false);
817
- useEffect4(() => setSchemaDirty(true), [
452
+ const [schemaChanged, setSchemaChanged] = useState(false);
453
+ useEffect(() => setSchemaChanged(true), [
818
454
  schema
819
455
  ]);
820
- useEffect4(() => {
821
- if (schemaDirty) {
456
+ useEffect(() => {
457
+ if (schemaChanged) {
822
458
  validate(values);
823
- setSchemaDirty(false);
459
+ setSchemaChanged(false);
824
460
  }
825
461
  }, [
462
+ validate,
826
463
  values,
827
- schemaDirty
464
+ schemaChanged
828
465
  ]);
829
- const formIsValid = useMemo2(() => {
466
+ const isValid = useMemo(() => {
830
467
  return Object.keys(errors).length === 0;
831
468
  }, [
832
469
  errors
833
470
  ]);
834
- const canSave = useMemo2(() => !saving && // Check if any error paths that are touched have errors.
471
+ const canSave = useMemo(() => !saving && // Check if any error paths that are touched have errors.
835
472
  !Object.entries(touched).some(([path, isTouched]) => isTouched && Object.keys(errors).some((errorPath) => errorPath === path || errorPath.startsWith(`${path}.`) || errorPath.startsWith(`${path}[`))), [
836
473
  touched,
837
474
  errors,
838
475
  saving
839
476
  ]);
840
- const handleSave = useCallback4(async () => {
477
+ const handleSave = useCallback(async () => {
841
478
  if (validate(values)) {
842
479
  setSaving(true);
843
480
  try {
844
481
  await onSave?.(values, {
845
- changed
482
+ changed,
483
+ isValid
846
484
  });
847
485
  } finally {
848
486
  setSaving(false);
@@ -852,11 +490,17 @@ var useForm = ({ schema, initialValues, onValuesChanged, onValidate, onValid, on
852
490
  values,
853
491
  validate,
854
492
  onSave,
855
- changed
493
+ changed,
494
+ isValid
856
495
  ]);
857
- const getStatus = useCallback4((path) => {
496
+ const handleCancel = useCallback(() => {
497
+ onCancel?.();
498
+ }, [
499
+ onCancel
500
+ ]);
501
+ const getStatus = useCallback((path) => {
858
502
  const jsonPath = Array.isArray(path) ? createJsonPath(path) : path;
859
- const matchingError = Object.entries(errors).find(([errorPath]) => errorPath === jsonPath || errorPath.startsWith(`${jsonPath}.`) || errorPath.startsWith(`${jsonPath}[`));
503
+ const [_, error] = Object.entries(errors).find(([errorPath]) => errorPath === jsonPath || errorPath.startsWith(`${jsonPath}.`) || errorPath.startsWith(`${jsonPath}[`)) ?? [];
860
504
  const isTouched = touched[jsonPath];
861
505
  if (!isTouched) {
862
506
  return {
@@ -865,110 +509,138 @@ var useForm = ({ schema, initialValues, onValuesChanged, onValidate, onValid, on
865
509
  };
866
510
  }
867
511
  return {
868
- status: matchingError ? "error" : void 0,
869
- error: matchingError ? matchingError[1] : void 0
512
+ status: error ? "error" : void 0,
513
+ error: error ? error ?? void 0 : void 0
870
514
  };
871
515
  }, [
872
516
  errors,
873
517
  touched
874
518
  ]);
875
- const getFormValue = useCallback4((path) => {
876
- return getValue(values, createJsonPath(path));
519
+ const getValue = useCallback((path) => {
520
+ return getValue$(values, createJsonPath(path));
877
521
  }, [
878
522
  values
879
523
  ]);
880
- const onValueChange = useCallback4((path, type, value) => {
524
+ const onValueChange = useCallback((path, type, value3) => {
525
+ log("onValueChange", {
526
+ path,
527
+ value: value3
528
+ }, {
529
+ F: __dxlog_file,
530
+ L: 254,
531
+ S: void 0,
532
+ C: (f, a) => f(...a)
533
+ });
881
534
  const jsonPath = createJsonPath(path);
882
- let parsedValue = value;
535
+ const pathArray = path;
536
+ let parsedValue = value3;
883
537
  try {
884
- if (type === "number") {
885
- parsedValue = parseFloat(value) || 0;
538
+ if (type._tag === "NumberKeyword") {
539
+ parsedValue = parseFloat(value3) || 0;
886
540
  }
887
541
  } catch (err) {
888
542
  log.catch(err, void 0, {
889
543
  F: __dxlog_file,
890
- L: 213,
544
+ L: 264,
891
545
  S: void 0,
892
546
  C: (f, a) => f(...a)
893
547
  });
894
548
  parsedValue = void 0;
895
549
  }
896
- const newValues = {
897
- ...setValue(values, jsonPath, parsedValue)
550
+ const newValues = mergeAtPath(values, pathArray, parsedValue);
551
+ const newChanged = {
552
+ [jsonPath]: true
898
553
  };
899
- setValues(newValues);
900
554
  setChanged((prev) => ({
901
555
  ...prev,
902
- [jsonPath]: true
556
+ ...newChanged
903
557
  }));
904
- onValuesChanged?.(newValues);
905
- const isValid = validate(newValues);
906
- if (isValid && onValid) {
907
- onValid(newValues, {
908
- changed
909
- });
558
+ const isValid2 = validate(newValues);
559
+ onValuesChanged?.(newValues, {
560
+ isValid: isValid2,
561
+ changed: newChanged
562
+ });
563
+ if (valuesProp === void 0) {
564
+ setValues(newValues);
910
565
  }
911
566
  }, [
912
567
  values,
913
- onValuesChanged,
914
568
  validate,
915
- onValid,
916
- changed
569
+ onValuesChanged,
570
+ valuesProp
917
571
  ]);
918
- const onTouched = useCallback4((path) => {
572
+ const onBlur = useCallback(async (path) => {
919
573
  const jsonPath = createJsonPath(path);
920
574
  setTouched((touched2) => ({
921
575
  ...touched2,
922
576
  [jsonPath]: true
923
577
  }));
924
- validate(values);
578
+ const isValid2 = validate(values);
579
+ if (Object.keys(changed).length > 0 && isValid2 && autoSave) {
580
+ await onSave?.(values, {
581
+ changed,
582
+ isValid: isValid2
583
+ });
584
+ }
925
585
  }, [
926
586
  validate,
927
- values
587
+ values,
588
+ changed,
589
+ autoSave,
590
+ onSave
928
591
  ]);
929
- return useMemo2(() => ({
592
+ return useMemo(() => ({
930
593
  // State.
594
+ schema,
931
595
  values,
932
596
  errors,
933
597
  touched,
934
598
  changed,
599
+ isValid,
935
600
  canSave,
936
- formIsValid,
601
+ autoSave,
937
602
  // Actions.
938
- handleSave,
603
+ onSave: handleSave,
604
+ onCancel: handleCancel,
939
605
  // Field utils.
940
606
  getStatus,
941
- getValue: getFormValue,
607
+ getValue,
608
+ onBlur,
942
609
  onValueChange,
943
- onTouched
610
+ ...props
944
611
  }), [
612
+ schema,
945
613
  values,
946
614
  errors,
947
615
  touched,
948
616
  changed,
949
617
  canSave,
950
- formIsValid,
951
- handleSave,
618
+ isValid,
952
619
  getStatus,
953
- getFormValue,
620
+ getValue,
621
+ onBlur,
954
622
  onValueChange,
955
- onTouched
623
+ onSave,
624
+ onCancel
956
625
  ]);
957
626
  };
958
- var createKeySet = (obj, value) => {
959
- invariant(obj, void 0, {
960
- F: __dxlog_file,
961
- L: 275,
962
- S: void 0,
963
- A: [
964
- "obj",
965
- ""
966
- ]
967
- });
968
- return Object.keys(obj).reduce((acc, key) => ({
969
- ...acc,
970
- [key]: value
971
- }), {});
627
+ var mergeAtPath = (obj, path, value3) => {
628
+ if (path.length === 0) {
629
+ return value3;
630
+ }
631
+ const [head2, ...rest] = path;
632
+ const child = rest.length === 0 ? value3 : mergeAtPath(obj?.[head2], rest, value3);
633
+ if (Array.isArray(obj)) {
634
+ const copy = [
635
+ ...obj
636
+ ];
637
+ copy[head2] = child;
638
+ return copy;
639
+ }
640
+ return {
641
+ ...obj,
642
+ [head2]: child
643
+ };
972
644
  };
973
645
  var flatMap = (errors) => {
974
646
  return errors.reduce((result, { path, message }) => {
@@ -980,1424 +652,1951 @@ var flatMap = (errors) => {
980
652
  }, {});
981
653
  };
982
654
 
983
- // src/hooks/useRefQueryLookupHandler.ts
984
- import { useCallback as useCallback5 } from "react";
985
- import { getObjectDXN } from "@dxos/echo-schema";
986
- import { Filter } from "@dxos/react-client/echo";
987
- import { isNonNullable } from "@dxos/util";
988
- var useRefQueryLookupHandler = ({ space }) => {
989
- return useCallback5(async (typeInfo) => {
990
- if (!space) {
991
- return [];
992
- }
993
- const query = space.db.query(Filter.typename(typeInfo.typename));
994
- const { objects } = await query.run();
995
- return objects.map((object) => {
996
- const dxn = getObjectDXN(object);
997
- if (!dxn) {
998
- return void 0;
655
+ // src/hooks/useKeyHandler.tsx
656
+ import { useCallback as useCallback2, useEffect as useEffect2 } from "react";
657
+ import { addEventListener } from "@dxos/async";
658
+ var useKeyHandler = (formElement, form) => {
659
+ const handleKeyDown = useCallback2((event) => {
660
+ switch (event.key) {
661
+ case "Enter": {
662
+ if (event.metaKey && form.canSave) {
663
+ form.onSave();
664
+ }
665
+ break;
999
666
  }
1000
- const item = {
1001
- dxn,
1002
- label: object?.name ?? object?.id ?? ""
1003
- };
1004
- return item;
1005
- }).filter(isNonNullable);
667
+ }
1006
668
  }, [
1007
- space
669
+ form.isValid,
670
+ form.canSave,
671
+ form.onSave,
672
+ form.autoSave
1008
673
  ]);
1009
- };
1010
-
1011
- // src/hooks/useQueryRefOptions.ts
1012
- import { useEffect as useEffect5, useState as useState4 } from "react";
1013
- import { log as log2 } from "@dxos/log";
1014
- var __dxlog_file2 = "/__w/dxos/dxos/packages/ui/react-ui-form/src/hooks/useQueryRefOptions.ts";
1015
- var useQueryRefOptions = ({ refTypeInfo, onQueryRefOptions }) => {
1016
- const [options, setOptions] = useState4([]);
1017
- const [loading, setLoading] = useState4(false);
1018
- useEffect5(() => {
1019
- if (!refTypeInfo || !onQueryRefOptions) {
674
+ useEffect2(() => {
675
+ if (!formElement) {
1020
676
  return;
1021
677
  }
1022
- const fetchOptions = async () => {
1023
- setLoading(true);
1024
- try {
1025
- const fetchedOptions = await onQueryRefOptions(refTypeInfo);
1026
- setOptions(fetchedOptions.map((option) => {
1027
- const dxn = option.dxn.toString();
1028
- return {
1029
- id: dxn,
1030
- label: option.label ?? dxn,
1031
- hue: "neutral"
1032
- };
1033
- }));
1034
- } catch (error) {
1035
- log2.error("Failed to fetch ref options:", error, {
1036
- F: __dxlog_file2,
1037
- L: 42,
1038
- S: void 0,
1039
- C: (f, a) => f(...a)
1040
- });
1041
- setOptions([]);
1042
- } finally {
1043
- setLoading(false);
1044
- }
1045
- };
1046
- void fetchOptions();
678
+ return addEventListener(formElement, "keydown", handleKeyDown);
1047
679
  }, [
1048
- refTypeInfo,
1049
- onQueryRefOptions
680
+ formElement,
681
+ handleKeyDown
1050
682
  ]);
1051
- return {
1052
- options,
1053
- loading
1054
- };
1055
683
  };
1056
684
 
1057
- // src/components/Form/FormContext.tsx
1058
- var FormContext = /* @__PURE__ */ createContext(void 0);
1059
- var useFormContext = () => {
1060
- return useContext(FormContext) ?? raise(new Error("Missing FormContext"));
1061
- };
1062
- var useFormValues = (path = []) => {
1063
- const { values: formValues } = useFormContext();
1064
- const jsonPath = createJsonPath2(path);
1065
- return getValue2(formValues, jsonPath);
1066
- };
1067
- var useInputProps = (path = []) => {
1068
- const { getStatus, getValue: getFormValue, onValueChange, onTouched } = useFormContext();
1069
- const stablePath = useMemo3(() => path, [
1070
- Array.isArray(path) ? path.join(".") : path
1071
- ]);
1072
- return useMemo3(() => ({
1073
- getStatus: () => getStatus(stablePath),
1074
- getValue: () => getFormValue(stablePath),
1075
- onValueChange: (type, value) => onValueChange(stablePath, type, value),
1076
- onBlur: () => onTouched(stablePath)
1077
- }), [
1078
- getStatus,
1079
- getFormValue,
1080
- onValueChange,
1081
- onTouched,
1082
- stablePath
1083
- ]);
1084
- };
1085
- var FormProvider = ({ children, formRef, autoSave, ...formOptions }) => {
1086
- var _effect = _useSignals8();
1087
- try {
1088
- const form = useForm(formOptions);
1089
- const handleKeyDown = useCallback6((event) => {
1090
- const keyIsEnter = event.key === "Enter";
1091
- const modifierUsed = event.ctrlKey || event.altKey || event.metaKey || event.shiftKey;
1092
- const inputIsTextarea = event.target.tagName.toLowerCase() === "textarea";
1093
- const inputOptOut = event.target.hasAttribute("data-no-submit") || event.target.closest("[data-no-submit]") !== null;
1094
- const shouldSubmitRegularInput = !inputIsTextarea && keyIsEnter && !modifierUsed;
1095
- const shouldSubmitTextarea = inputIsTextarea && keyIsEnter && event.metaKey;
1096
- if ((shouldSubmitRegularInput || shouldSubmitTextarea) && !inputOptOut) {
1097
- if (!autoSave && form.canSave) {
1098
- form.handleSave();
1099
- }
1100
- if (autoSave && form.formIsValid) {
1101
- event.target.blur();
1102
- }
1103
- }
1104
- }, [
1105
- form,
1106
- autoSave
1107
- ]);
1108
- useEffect6(() => {
1109
- if (!formRef?.current) {
1110
- return;
1111
- }
1112
- const formElement = formRef.current;
1113
- formElement.addEventListener("keydown", handleKeyDown);
1114
- return () => formElement.removeEventListener("keydown", handleKeyDown);
1115
- }, [
1116
- formRef,
1117
- form.canSave,
1118
- form.formIsValid,
1119
- form.handleSave,
1120
- autoSave
1121
- ]);
1122
- return /* @__PURE__ */ React8.createElement(FormContext.Provider, {
1123
- value: form
1124
- }, children);
1125
- } finally {
1126
- _effect.f();
1127
- }
685
+ // src/components/Form/FormFieldComponent.tsx
686
+ import React, { Component } from "react";
687
+ import { Icon, Input, Tooltip } from "@dxos/react-ui";
688
+ import { inputTextLabel } from "@dxos/ui-theme";
689
+ var FormFieldLabel = ({ label, error, readonly, asChild }) => {
690
+ const Label = readonly || asChild ? "span" : Input.Label;
691
+ return /* @__PURE__ */ React.createElement("div", {
692
+ role: "none",
693
+ className: "flex items-center justify-between"
694
+ }, /* @__PURE__ */ React.createElement(Label, {
695
+ className: inputTextLabel
696
+ }, label), error && /* @__PURE__ */ React.createElement(Tooltip.Trigger, {
697
+ asChild: true,
698
+ content: error,
699
+ side: "bottom"
700
+ }, /* @__PURE__ */ React.createElement(Icon, {
701
+ icon: "ph--warning--regular",
702
+ size: 4,
703
+ classNames: "text-error-text"
704
+ })));
1128
705
  };
1129
-
1130
- // src/components/Form/FormActions.tsx
1131
- var FormActions = ({ readonly, onCancel, outerSpacing = true }) => {
1132
- var _effect = _useSignals9();
1133
- try {
1134
- const { t } = useTranslation5(translationKey);
1135
- const { canSave, handleSave } = useFormContext();
1136
- return /* @__PURE__ */ React9.createElement("div", {
1137
- role: "none",
1138
- className: mx6(outerSpacing === "scroll-fields" ? "pli-cardSpacingInline mbe-cardSpacingBlock" : outerSpacing ? cardSpacing : "mbs-cardSpacingBlock", "flex [&_button]:grow gap-1 first:mbs-0")
1139
- }, onCancel && !readonly && /* @__PURE__ */ React9.createElement(IconButton2, {
1140
- "data-testid": "cancel-button",
1141
- icon: "ph--x--regular",
1142
- label: t("button cancel"),
1143
- onClick: onCancel
1144
- }), handleSave && /* @__PURE__ */ React9.createElement(IconButton2, {
1145
- type: "submit",
1146
- "data-testid": "save-button",
1147
- disabled: !canSave,
1148
- icon: "ph--check--regular",
1149
- label: t("button save"),
1150
- onClick: handleSave
1151
- }));
1152
- } finally {
1153
- _effect.f();
706
+ FormFieldLabel.displayName = "Form.FieldLabel";
707
+ var FormFieldWrapper = (props) => {
708
+ const { children, readonly, layout, label, getStatus, getValue } = props;
709
+ const { status, error } = getStatus();
710
+ const value3 = getValue();
711
+ if (layout === "static" && value3 == null) {
712
+ return null;
1154
713
  }
714
+ const str = String(value3 ?? "");
715
+ return /* @__PURE__ */ React.createElement("div", {
716
+ role: "none",
717
+ className: "contents"
718
+ }, /* @__PURE__ */ React.createElement(Input.Root, {
719
+ validationValence: status
720
+ }, layout !== "inline" && /* @__PURE__ */ React.createElement(FormFieldLabel, {
721
+ error,
722
+ readonly,
723
+ label
724
+ }), layout === "static" ? /* @__PURE__ */ React.createElement("p", null, str) : children ? children({
725
+ value: value3
726
+ }) : null, layout === "full" && /* @__PURE__ */ React.createElement(Input.DescriptionAndValidation, null, /* @__PURE__ */ React.createElement(Input.Validation, null, error))));
1155
727
  };
1156
-
1157
- // src/components/Form/FormContent.tsx
1158
- import { useSignals as _useSignals12 } from "@preact-signals/safe-react/tracking";
1159
- import { Schema, SchemaAST as SchemaAST4, pipe as pipe2 } from "effect";
1160
- import { capitalize as capitalize2 } from "effect/String";
1161
- import React12, { forwardRef, useMemo as useMemo5 } from "react";
1162
- import { createJsonPath as createJsonPath3, findNode as findNode3, getDiscriminatedType as getDiscriminatedType2, isDiscriminatedUnion as isDiscriminatedUnion2 } from "@dxos/effect";
1163
- import { mx as mx8 } from "@dxos/react-ui-theme";
1164
- import { getSchemaProperties as getSchemaProperties2 } from "@dxos/schema";
1165
- import { isNotFalsy } from "@dxos/util";
1166
-
1167
- // src/components/Form/ArrayField.tsx
1168
- import { useSignals as _useSignals10 } from "@preact-signals/safe-react/tracking";
1169
- import { SchemaAST as SchemaAST3, pipe } from "effect";
1170
- import { capitalize } from "effect/String";
1171
- import React10, { Fragment, useCallback as useCallback7 } from "react";
1172
- import { findNode as findNode2, getDiscriminatedType, isDiscriminatedUnion, SimpleType } from "@dxos/effect";
1173
- import { invariant as invariant2 } from "@dxos/invariant";
1174
- import { IconButton as IconButton3, useTranslation as useTranslation6 } from "@dxos/react-ui";
1175
- import { getSchemaProperties } from "@dxos/schema";
1176
-
1177
- // src/util/field.ts
1178
- import { FormatEnum, GeoLocation as GeoLocation2, TypeEnum } from "@dxos/echo-schema";
1179
- var parseValue = ({ type, format, value }) => {
1180
- if (value === void 0 || value === null || value === "") {
1181
- return void 0;
728
+ var FormFieldErrorBoundary = class extends Component {
729
+ static getDerivedStateFromError(error) {
730
+ return {
731
+ error
732
+ };
1182
733
  }
1183
- const parseScalar = (type2) => {
1184
- switch (type2) {
1185
- case TypeEnum.Boolean: {
1186
- if (typeof value === "string") {
1187
- const lowercaseValue = value.toLowerCase();
1188
- if (lowercaseValue === "0" || lowercaseValue === "false") {
1189
- return false;
1190
- } else if (lowercaseValue === "1" || lowercaseValue === "true") {
1191
- return true;
1192
- }
1193
- }
1194
- return Boolean(value);
1195
- }
1196
- case TypeEnum.Number: {
1197
- const cleaned = typeof value === "string" ? value.replace(/[^0-9.-]+/g, "") : value;
1198
- const num = Number(cleaned);
1199
- return Number.isNaN(num) ? null : num;
1200
- }
1201
- case TypeEnum.String:
1202
- case TypeEnum.Ref:
1203
- return String(value);
1204
- default: {
1205
- return value;
1206
- }
1207
- }
734
+ state = {
735
+ error: void 0
1208
736
  };
1209
- if (!format) {
1210
- return parseScalar(type);
1211
- }
1212
- switch (format) {
1213
- case FormatEnum.Boolean:
1214
- return parseScalar(TypeEnum.Boolean);
1215
- case FormatEnum.Number:
1216
- case FormatEnum.Percent:
1217
- case FormatEnum.Currency:
1218
- return parseScalar(TypeEnum.Number);
1219
- case FormatEnum.String:
1220
- case FormatEnum.Markdown: {
1221
- return parseScalar(TypeEnum.String);
1222
- }
1223
- case FormatEnum.Ref:
1224
- throw new Error(`unexpected format: ${FormatEnum.Ref}`);
1225
- case FormatEnum.DateTime:
1226
- case FormatEnum.Date:
1227
- case FormatEnum.Time:
1228
- case FormatEnum.Timestamp: {
1229
- const date = new Date(value);
1230
- return isNaN(date.getTime()) ? null : date;
1231
- }
1232
- case FormatEnum.GeoPoint: {
1233
- if (typeof value === "string") {
1234
- const cleaned = value.replace(/[^0-9.,-]+/g, "");
1235
- const parts = cleaned.split(",");
1236
- if (parts.length === 2) {
1237
- const lat = parseFloat(parts[0]);
1238
- const long = parseFloat(parts[1]);
1239
- if (!isNaN(lat) && !isNaN(long)) {
1240
- return GeoLocation2.toGeoPoint({
1241
- latitude: lat,
1242
- longitude: long
1243
- });
1244
- }
1245
- }
1246
- }
1247
- return [
1248
- 0,
1249
- 0
1250
- ];
1251
- }
1252
- default: {
1253
- return value;
737
+ componentDidUpdate(prevProps) {
738
+ if (prevProps.path !== this.props.path) {
739
+ this.resetError();
1254
740
  }
1255
741
  }
1256
- };
1257
- var cellClassesForFieldType = ({ type, format }) => {
1258
- if (!format) {
1259
- switch (type) {
1260
- case TypeEnum.Number:
1261
- return [
1262
- "text-right",
1263
- "font-mono"
1264
- ];
1265
- case TypeEnum.Boolean:
1266
- return [
1267
- "text-right",
1268
- "font-mono"
1269
- ];
1270
- case TypeEnum.String:
1271
- return void 0;
1272
- case TypeEnum.Ref:
1273
- return void 0;
1274
- default: {
1275
- return void 0;
1276
- }
742
+ render() {
743
+ if (this.state.error) {
744
+ return /* @__PURE__ */ React.createElement("div", {
745
+ className: "flex gap-2 border border-rose-fill font-mono text-sm"
746
+ }, /* @__PURE__ */ React.createElement("span", {
747
+ className: "bg-rose-fill text-surface-text px-1 font-thin"
748
+ }, "ERROR"), String(this.props.path?.join(".")));
1277
749
  }
750
+ return this.props.children;
1278
751
  }
1279
- switch (format) {
1280
- case FormatEnum.Markdown:
1281
- return void 0;
1282
- case FormatEnum.Time:
1283
- case FormatEnum.Timestamp:
1284
- case FormatEnum.DateTime:
1285
- case FormatEnum.Date:
1286
- case FormatEnum.Duration:
1287
- return [
1288
- "font-mono",
1289
- "text-right"
1290
- ];
1291
- case FormatEnum.Currency:
1292
- return [
1293
- "text-right"
1294
- ];
1295
- case FormatEnum.JSON:
1296
- case FormatEnum.DID:
1297
- return [
1298
- "font-mono"
1299
- ];
1300
- default:
1301
- return void 0;
752
+ resetError() {
753
+ this.setState({
754
+ error: void 0
755
+ });
1302
756
  }
1303
757
  };
1304
- var pathNotUniqueError = (path) => ({
1305
- path: "path",
1306
- message: `'${path}' is already present`
1307
- });
1308
758
 
1309
- // src/util/formatting.ts
1310
- import { format as formatDate } from "date-fns/format";
1311
- import { FormatEnum as FormatEnum2, GeoLocation as GeoLocation3, TypeEnum as TypeEnum2 } from "@dxos/echo-schema";
1312
- var formatForDisplay = ({ type, format, value, locale = void 0 }) => {
1313
- const formatScalar = (type2) => {
1314
- switch (type2) {
1315
- case TypeEnum2.Boolean:
1316
- return value.toLocaleString().toUpperCase();
1317
- case TypeEnum2.Number:
1318
- return value.toLocaleString(locale);
1319
- case TypeEnum2.String:
1320
- case TypeEnum2.Ref:
1321
- return String(value);
1322
- default: {
1323
- return String(value);
1324
- }
1325
- }
759
+ // src/components/Form/FormFieldSet.tsx
760
+ import React3, { useMemo as useMemo3 } from "react";
761
+
762
+ // src/components/Form/FormField.tsx
763
+ import * as Match from "effect/Match";
764
+ import * as Option2 from "effect/Option";
765
+ import * as Schema from "effect/Schema";
766
+ import * as SchemaAST from "effect/SchemaAST";
767
+ import * as String2 from "effect/String";
768
+ import React2, { useMemo as useMemo2 } from "react";
769
+ import { Format as Format3 } from "@dxos/echo";
770
+ import { createJsonPath as createJsonPath2, findNode, getAnnotation, getDiscriminatedType, isArrayType as isArrayType2, isDiscriminatedUnion, isLiteralUnion, isNestedType } from "@dxos/effect";
771
+ import { useTranslation } from "@dxos/react-ui";
772
+ var FormField = (props) => {
773
+ const {
774
+ type,
775
+ name,
776
+ path,
777
+ projection,
778
+ fieldMap,
779
+ fieldProvider,
780
+ readonly,
781
+ layout,
782
+ // RefFieldProps
783
+ createTypename,
784
+ createOptionLabel,
785
+ createOptionIcon,
786
+ createInitialValuePath,
787
+ createFieldMap,
788
+ db,
789
+ schemaHook,
790
+ getOptions: getRefOptions,
791
+ onCreate
792
+ } = props;
793
+ const { t } = useTranslation(translationKey);
794
+ const title = getAnnotation(SchemaAST.TitleAnnotationId)(type);
795
+ const description = getAnnotation(SchemaAST.DescriptionAnnotationId)(type);
796
+ const examples = getAnnotation(SchemaAST.ExamplesAnnotationId)(type);
797
+ const label = useMemo2(() => title ?? String2.capitalize(name), [
798
+ title,
799
+ name
800
+ ]);
801
+ const placeholder = useMemo2(() => examples?.length ? `${t("example.placeholder")}: ${examples[0]}` : description ?? label, [
802
+ examples,
803
+ description,
804
+ label
805
+ ]);
806
+ const fieldState = useFormFieldState(FormField.displayName, path);
807
+ const fieldProps = {
808
+ type,
809
+ format: Format3.FormatAnnotation.getFromAst(type).pipe((annotation) => Option2.getOrUndefined(annotation)),
810
+ readonly,
811
+ label,
812
+ placeholder,
813
+ layout,
814
+ ...fieldState
1326
815
  };
1327
- if (!format) {
1328
- return formatScalar(type);
816
+ const jsonPath = createJsonPath2(path ?? []);
817
+ const CustomField = fieldMap?.[jsonPath];
818
+ if (CustomField) {
819
+ return /* @__PURE__ */ React2.createElement(CustomField, fieldProps);
820
+ }
821
+ const component = fieldProvider?.({
822
+ schema: Schema.make(type),
823
+ prop: name,
824
+ fieldProps
825
+ });
826
+ if (component) {
827
+ return component;
828
+ }
829
+ if (isArrayType2(type)) {
830
+ return /* @__PURE__ */ React2.createElement(ArrayField, {
831
+ fieldProps: fieldState,
832
+ label,
833
+ ...props
834
+ });
835
+ }
836
+ const Field = getFormField(fieldProps);
837
+ if (Field) {
838
+ return /* @__PURE__ */ React2.createElement(Field, fieldProps);
839
+ }
840
+ const options = getOptions(type);
841
+ if (options) {
842
+ const fieldProjections = projection?.getFieldProjections();
843
+ const fieldProjection = fieldProjections?.find((fp) => fp.field.path === name);
844
+ const selectOptions = fieldProjection?.props.options;
845
+ return /* @__PURE__ */ React2.createElement(SelectField, {
846
+ ...fieldProps,
847
+ options: options.map((option) => {
848
+ const selectOption = selectOptions?.find((so) => so.id === globalThis.String(option));
849
+ return {
850
+ value: option,
851
+ label: selectOption?.title ?? option.toString()
852
+ };
853
+ })
854
+ });
855
+ }
856
+ const refProps = getRefProps(type);
857
+ if (refProps) {
858
+ const isCreateTarget = !createTypename || refProps.typename === createTypename;
859
+ return /* @__PURE__ */ React2.createElement(RefField, {
860
+ ...fieldProps,
861
+ ...refProps,
862
+ createOptionLabel: isCreateTarget ? createOptionLabel : void 0,
863
+ createOptionIcon: isCreateTarget ? createOptionIcon : void 0,
864
+ createInitialValuePath: isCreateTarget ? createInitialValuePath : void 0,
865
+ createFieldMap: isCreateTarget ? createFieldMap : void 0,
866
+ db,
867
+ schemaHook,
868
+ getOptions: getRefOptions,
869
+ onCreate
870
+ });
1329
871
  }
1330
- switch (format) {
1331
- case FormatEnum2.Boolean: {
1332
- return formatScalar(TypeEnum2.Boolean);
1333
- }
1334
- case FormatEnum2.Number: {
1335
- return formatScalar(TypeEnum2.Number);
1336
- }
1337
- case FormatEnum2.String:
1338
- case FormatEnum2.Ref: {
1339
- return formatScalar(TypeEnum2.String);
1340
- }
1341
- case FormatEnum2.Percent: {
1342
- return `${value * 100}%`;
1343
- }
1344
- case FormatEnum2.Currency: {
1345
- return value.toLocaleString(locale, {
1346
- style: "currency",
1347
- currency: "USD",
1348
- minimumFractionDigits: 2,
1349
- maximumFractionDigits: 2
872
+ if (isNestedType(type)) {
873
+ const baseNode = findNode(type, isDiscriminatedUnion);
874
+ const typeLiteral = baseNode ? getDiscriminatedType(baseNode, fieldState.getValue()) : findNode(type, SchemaAST.isTypeLiteral);
875
+ if (typeLiteral) {
876
+ const schema = Schema.make(typeLiteral);
877
+ return /* @__PURE__ */ React2.createElement(FormFieldSet, {
878
+ schema,
879
+ path,
880
+ readonly,
881
+ layout,
882
+ label,
883
+ projection,
884
+ fieldMap,
885
+ fieldProvider,
886
+ createOptionLabel,
887
+ createOptionIcon,
888
+ createInitialValuePath,
889
+ db,
890
+ schemaHook,
891
+ getOptions: getRefOptions,
892
+ onCreate
1350
893
  });
1351
894
  }
1352
- case FormatEnum2.Date: {
1353
- try {
1354
- return formatDate(new Date(value), "yyyy-MM-dd");
1355
- } catch (error) {
1356
- return "Invalid Date";
1357
- }
1358
- }
1359
- case FormatEnum2.Time: {
1360
- try {
1361
- return formatDate(new Date(value), "HH:mm:ss");
1362
- } catch (error) {
1363
- return "Invalid Time";
1364
- }
1365
- }
1366
- case FormatEnum2.DateTime: {
1367
- try {
1368
- return formatDate(new Date(value), "yyyy-MM-dd HH:mm:ss");
1369
- } catch (error) {
1370
- return "Invalid DateTime";
1371
- }
895
+ }
896
+ return null;
897
+ };
898
+ FormField.displayName = "Form.FormField";
899
+ var getFormField = ({ type, format }) => {
900
+ const formatField = Match.value(format).pipe(Match.withReturnType(), Match.when(Format3.TypeFormat.GeoPoint, () => GeoPointField), Match.when(Format3.TypeFormat.Markdown, () => MarkdownField), Match.when(Format3.TypeFormat.Text, () => TextAreaField), Match.orElse(() => void 0));
901
+ if (formatField) {
902
+ return formatField;
903
+ }
904
+ switch (type._tag) {
905
+ // TODO(wittjosiah): Schema.Any is currently used to represent template inputs.
906
+ case "AnyKeyword":
907
+ case "StringKeyword":
908
+ return TextField;
909
+ case "NumberKeyword":
910
+ return NumberField;
911
+ case "BooleanKeyword":
912
+ return BooleanField;
913
+ }
914
+ };
915
+ var getOptions = (ast) => {
916
+ if (isLiteralUnion(ast)) {
917
+ return ast.types.map((type) => type.literal).filter((v) => v !== null);
918
+ }
919
+ return Format3.OptionsAnnotation.getFromAst(ast).pipe((annotation) => Option2.getOrUndefined(annotation));
920
+ };
921
+
922
+ // src/components/Form/FormFieldSet.tsx
923
+ var FORM_FIELDSET_NAME = "Form.FieldSet";
924
+ var FormFieldSet = ({ label, schema, readonly, path, sort, exclude, projection, layout, ...props }) => {
925
+ const values = useFormValues(FORM_FIELDSET_NAME, path);
926
+ const properties = useMemo3(() => {
927
+ if (!schema) {
928
+ return [];
1372
929
  }
1373
- case FormatEnum2.GeoPoint: {
1374
- if (value === null || value === void 0) {
1375
- return "";
1376
- }
1377
- if (Array.isArray(value) && value.length >= 2 && value.every(Number.isFinite)) {
1378
- const { latitude, longitude } = GeoLocation3.fromGeoPoint(value);
1379
- return `${latitude},${longitude}`;
930
+ const schemaProps = getFormProperties(schema.ast);
931
+ const filteredProps = exclude ? exclude(schemaProps) : schemaProps;
932
+ if (projection) {
933
+ const fieldProjections = projection.getFieldProjections();
934
+ const hiddenProperties = new Set(projection.getHiddenProperties());
935
+ const visibleProps = filteredProps.filter((prop) => !hiddenProperties.has(prop.name.toString()));
936
+ const orderedProps = [];
937
+ for (const fieldProjection of fieldProjections) {
938
+ const fieldPath = String(fieldProjection.field.path);
939
+ const prop = visibleProps.find((p) => p.name === fieldPath);
940
+ if (prop) {
941
+ orderedProps.push(prop);
942
+ }
1380
943
  }
1381
- return String(value);
944
+ const projectionPaths = new Set(fieldProjections.map((projection2) => String(projection2.field.path)));
945
+ const remainingProps = visibleProps.filter((prop) => !projectionPaths.has(prop.name.toString()));
946
+ orderedProps.push(...remainingProps);
947
+ return orderedProps;
1382
948
  }
1383
- default: {
1384
- if (value === null || value === "undefined") {
1385
- return "";
1386
- }
1387
- return String(value);
949
+ return sort ? [
950
+ ...filteredProps
951
+ ].sort(({ name: a }, { name: b }) => sort.indexOf(a.toString()) - sort.indexOf(b.toString())) : filteredProps;
952
+ }, [
953
+ schema,
954
+ values,
955
+ exclude,
956
+ sort,
957
+ projection
958
+ ]);
959
+ if ((readonly || layout === "static") && values == null) {
960
+ return null;
961
+ }
962
+ return /* @__PURE__ */ React3.createElement(React3.Fragment, null, layout !== "inline" && label && /* @__PURE__ */ React3.createElement(FormFieldLabel, {
963
+ label,
964
+ asChild: true
965
+ }), properties.map((property) => {
966
+ const name = property.name.toString();
967
+ return /* @__PURE__ */ React3.createElement(FormFieldErrorBoundary, {
968
+ key: name,
969
+ path: [
970
+ ...path ?? [],
971
+ name
972
+ ]
973
+ }, /* @__PURE__ */ React3.createElement(FormField, {
974
+ type: property.type,
975
+ name,
976
+ path: [
977
+ ...path ?? [],
978
+ name
979
+ ],
980
+ readonly,
981
+ layout,
982
+ projection,
983
+ ...props
984
+ }));
985
+ }));
986
+ };
987
+ FormFieldSet.displayName = FORM_FIELDSET_NAME;
988
+
989
+ // src/components/Form/Form.tsx
990
+ var omitId = (schema) => schema.pipe(Schema2.omit("id"));
991
+ var [FormContextProvider, useFormContext] = createContext("Form");
992
+ var useFormValues = (componentName, path, defaultValue) => {
993
+ const stablePath = useMemo4(() => path ?? [], [
994
+ path ? path.join(".") : void 0
995
+ ]);
996
+ const jsonPath = createJsonPath3(stablePath);
997
+ const { form: { values, onValueChange } } = useFormContext(componentName);
998
+ const value3 = getValue$2(values, jsonPath);
999
+ const lastAppliedPathRef = useRef(null);
1000
+ useEffect3(() => {
1001
+ if (value3 == null && defaultValue && lastAppliedPathRef.current !== jsonPath) {
1002
+ lastAppliedPathRef.current = jsonPath;
1003
+ onValueChange(stablePath, SchemaAST2.stringKeyword, defaultValue());
1388
1004
  }
1005
+ }, [
1006
+ value3,
1007
+ defaultValue,
1008
+ onValueChange,
1009
+ stablePath,
1010
+ jsonPath
1011
+ ]);
1012
+ return value3;
1013
+ };
1014
+ var useFormFieldState = (componentName, path = []) => {
1015
+ const stablePath = useMemo4(() => path, [
1016
+ Array.isArray(path) ? path.join(".") : path
1017
+ ]);
1018
+ const { form: { getStatus, getValue, onBlur, onValueChange } } = useFormContext(componentName);
1019
+ return useMemo4(() => ({
1020
+ getStatus: () => getStatus(stablePath),
1021
+ getValue: () => getValue(stablePath),
1022
+ onBlur: () => onBlur(stablePath),
1023
+ onValueChange: (ast, value3) => onValueChange(stablePath, ast, value3)
1024
+ }), [
1025
+ getStatus,
1026
+ getValue,
1027
+ onBlur,
1028
+ onValueChange,
1029
+ stablePath
1030
+ ]);
1031
+ };
1032
+ var FormRoot = ({ children, schema, values, onSave, onCancel, ...props }) => {
1033
+ const form = useFormHandler({
1034
+ schema,
1035
+ values,
1036
+ onSave,
1037
+ onCancel,
1038
+ ...props
1039
+ });
1040
+ return /* @__PURE__ */ React4.createElement(FormContextProvider, {
1041
+ form,
1042
+ ...props
1043
+ }, children);
1044
+ };
1045
+ FormRoot.displayName = "Form.Root";
1046
+ var FORM_VIEWPORT_NAME = "Form.Viewport";
1047
+ var FormViewport = composable(({ children, ...props }, forwardedRef) => {
1048
+ return /* @__PURE__ */ React4.createElement(ScrollArea.Root, {
1049
+ ...composableProps(props),
1050
+ orientation: "vertical",
1051
+ centered: true,
1052
+ padding: true,
1053
+ thin: true,
1054
+ ref: forwardedRef
1055
+ }, /* @__PURE__ */ React4.createElement(ScrollArea.Viewport, null, children));
1056
+ });
1057
+ FormViewport.displayName = FORM_VIEWPORT_NAME;
1058
+ var FORM_CONTENT_NAME = "Form.Content";
1059
+ var FormContent = ({ classNames, children }) => {
1060
+ const { form, testId } = useFormContext(FORM_CONTENT_NAME);
1061
+ const ref = useRef(null);
1062
+ useKeyHandler(ref.current, form);
1063
+ return /* @__PURE__ */ React4.createElement("div", {
1064
+ ref,
1065
+ role: "form",
1066
+ className: mx("flex flex-col w-full", classNames),
1067
+ "data-testid": testId
1068
+ }, children);
1069
+ };
1070
+ FormContent.displayName = FORM_CONTENT_NAME;
1071
+ var FORM_FIELDSET_NAME2 = "Form.FieldSet";
1072
+ var FormFieldSet2 = (props) => {
1073
+ const { form, ...contextProps } = useFormContext(FORM_FIELDSET_NAME2);
1074
+ return /* @__PURE__ */ React4.createElement(FormFieldSet, {
1075
+ schema: form.schema,
1076
+ ...contextProps,
1077
+ ...props
1078
+ });
1079
+ };
1080
+ FormFieldSet2.displayName = FORM_FIELDSET_NAME2;
1081
+ var FORM_ACTIONS_NAME = "Form.Actions";
1082
+ var FormActions = ({ classNames }) => {
1083
+ const { t } = useTranslation2(translationKey);
1084
+ const { form: { canSave, onSave, onCancel }, readonly, layout } = useFormContext(FORM_ACTIONS_NAME);
1085
+ if (readonly || layout === "static") {
1086
+ return null;
1389
1087
  }
1088
+ return /* @__PURE__ */ React4.createElement("div", {
1089
+ role: "none",
1090
+ className: mx("grid grid-flow-col gap-form-gap auto-cols-fr py-form-padding", classNames)
1091
+ }, onCancel && /* @__PURE__ */ React4.createElement(IconButton, {
1092
+ icon: "ph--x--regular",
1093
+ iconEnd: true,
1094
+ label: t("cancel-button.label"),
1095
+ onClick: onCancel,
1096
+ "data-testid": "cancel-button"
1097
+ }), onSave && /* @__PURE__ */ React4.createElement(IconButton, {
1098
+ type: "submit",
1099
+ variant: "primary",
1100
+ disabled: !canSave,
1101
+ icon: "ph--check--regular",
1102
+ iconEnd: true,
1103
+ label: t("save-button.label"),
1104
+ onClick: onSave,
1105
+ "data-testid": "save-button"
1106
+ }));
1390
1107
  };
1391
- var formatForEditing = ({ type, format, value, locale = void 0 }) => {
1392
- const formatScalar = (type2) => {
1393
- switch (type2) {
1394
- case TypeEnum2.Boolean:
1395
- case TypeEnum2.Number:
1396
- case TypeEnum2.String:
1397
- case TypeEnum2.Ref:
1398
- return String(value);
1399
- default:
1400
- return String(value);
1108
+ FormActions.displayName = FORM_ACTIONS_NAME;
1109
+ var FORM_SUBMIT_NAME = "Form.Submit";
1110
+ var FormSubmit = ({ classNames, label, icon, disabled }) => {
1111
+ const { t } = useTranslation2(translationKey);
1112
+ const { form: { canSave, onSave }, readonly, layout } = useFormContext(FORM_SUBMIT_NAME);
1113
+ if (readonly || layout === "static") {
1114
+ return null;
1115
+ }
1116
+ return /* @__PURE__ */ React4.createElement("div", {
1117
+ role: "none",
1118
+ className: mx("flex w-full pt-form-padding", classNames)
1119
+ }, /* @__PURE__ */ React4.createElement(IconButton, {
1120
+ classNames: "w-full",
1121
+ type: "submit",
1122
+ variant: "primary",
1123
+ disabled: disabled ?? !canSave,
1124
+ icon: icon ?? "ph--check--regular",
1125
+ label: label ?? t("save-button.label"),
1126
+ onClick: onSave,
1127
+ "data-testid": "save-button"
1128
+ }));
1129
+ };
1130
+ FormSubmit.displayName = FORM_SUBMIT_NAME;
1131
+ var Form = {
1132
+ Root: FormRoot,
1133
+ Viewport: FormViewport,
1134
+ Content: FormContent,
1135
+ FieldSet: FormFieldSet2,
1136
+ Label: FormFieldLabel,
1137
+ Actions: FormActions,
1138
+ Submit: FormSubmit
1139
+ };
1140
+
1141
+ // src/components/Form/fields/ArrayField.tsx
1142
+ var ArrayField = ({ type, path, label, readonly, layout, fieldProps: inputProps, ...props }) => {
1143
+ const { t } = useTranslation3(translationKey);
1144
+ const elementType = getArrayElementType2(type);
1145
+ const { onValueChange } = inputProps;
1146
+ const values = useFormValues(ArrayField.displayName, path, () => []);
1147
+ const getDefaultObjectValue = (typeNode) => {
1148
+ const baseNode = findNode2(typeNode, isDiscriminatedUnion2);
1149
+ const typeLiteral = baseNode ? getDiscriminatedType2(baseNode, {}) : findNode2(typeNode, SchemaAST3.isTypeLiteral);
1150
+ if (!typeLiteral) {
1151
+ return {};
1401
1152
  }
1153
+ return Object.fromEntries(getFormProperties(typeLiteral).map((prop) => {
1154
+ const defaultValue = SchemaAST3.getDefaultAnnotation(prop.type).pipe((annotation) => Option3.getOrUndefined(annotation));
1155
+ return [
1156
+ prop.name,
1157
+ defaultValue
1158
+ ];
1159
+ }));
1402
1160
  };
1403
- if (!format) {
1404
- return formatScalar(type);
1161
+ const handleAdd = useCallback3(() => {
1162
+ const defaultValue = isNestedType2(type) && elementType ? getDefaultObjectValue(elementType) : getDefaultValue(elementType);
1163
+ values && onValueChange(type, [
1164
+ ...values,
1165
+ defaultValue
1166
+ ]);
1167
+ }, [
1168
+ onValueChange,
1169
+ type,
1170
+ elementType,
1171
+ values
1172
+ ]);
1173
+ const handleDelete = useCallback3((idx) => {
1174
+ onValueChange(type, values?.filter((_, i) => i !== idx));
1175
+ }, [
1176
+ onValueChange,
1177
+ type,
1178
+ values
1179
+ ]);
1180
+ if (!elementType || (readonly || layout === "static") && values && values.length < 1) {
1181
+ return null;
1405
1182
  }
1406
- switch (format) {
1407
- case FormatEnum2.Boolean:
1408
- case FormatEnum2.Number:
1409
- case FormatEnum2.String:
1410
- case FormatEnum2.Ref: {
1411
- return formatScalar(type);
1412
- }
1413
- case FormatEnum2.Percent: {
1414
- return String(value * 100);
1415
- }
1416
- case FormatEnum2.Currency: {
1417
- return String(value);
1418
- }
1419
- case FormatEnum2.DateTime: {
1420
- const date = new Date(value);
1421
- return date.toISOString();
1183
+ return /* @__PURE__ */ React5.createElement(React5.Fragment, null, (layout !== "static" || values && values.length > 0) && /* @__PURE__ */ React5.createElement(FormFieldLabel, {
1184
+ readonly,
1185
+ label,
1186
+ asChild: true
1187
+ }), /* @__PURE__ */ React5.createElement("div", {
1188
+ role: "none",
1189
+ className: "flex flex-col gap-form-gap"
1190
+ }, values?.map((_, index) => {
1191
+ return /* @__PURE__ */ React5.createElement("div", {
1192
+ role: "none",
1193
+ key: index,
1194
+ className: "flex gap-form-gap last:mb-form-gap"
1195
+ }, /* @__PURE__ */ React5.createElement(FormField, {
1196
+ autoFocus: index === values.length - 1,
1197
+ type: elementType,
1198
+ path: [
1199
+ ...path ?? [],
1200
+ index
1201
+ ],
1202
+ readonly: readonly || layout === "static",
1203
+ layout: "inline",
1204
+ ...props
1205
+ }), !readonly && layout !== "static" && /* @__PURE__ */ React5.createElement("div", {
1206
+ role: "none",
1207
+ className: "flex flex-col h-full justify-end"
1208
+ }, /* @__PURE__ */ React5.createElement("div", {
1209
+ role: "none",
1210
+ className: "flex items-center h-[2rem]"
1211
+ }, /* @__PURE__ */ React5.createElement(IconButton2, {
1212
+ icon: "ph--x--regular",
1213
+ iconOnly: true,
1214
+ label: t("remove.button"),
1215
+ onClick: () => handleDelete(index),
1216
+ classNames: "self-center"
1217
+ }))));
1218
+ })), !readonly && layout !== "static" && /* @__PURE__ */ React5.createElement(IconButton2, {
1219
+ classNames: "flex w-full",
1220
+ icon: "ph--plus--regular",
1221
+ label: t("add-field.button"),
1222
+ onClick: handleAdd
1223
+ }));
1224
+ };
1225
+ ArrayField.displayName = "Form.ArrayField";
1226
+ var getDefaultValue = (ast) => {
1227
+ switch (ast?._tag) {
1228
+ case "StringKeyword": {
1229
+ return "";
1422
1230
  }
1423
- case FormatEnum2.Date: {
1424
- const date = new Date(value);
1425
- return date.toISOString().split("T")[0];
1231
+ case "NumberKeyword": {
1232
+ return 0;
1426
1233
  }
1427
- case FormatEnum2.Time: {
1428
- const date = new Date(value);
1429
- return date.toISOString().split("T")[1].split(".")[0];
1234
+ case "BooleanKeyword": {
1235
+ return false;
1430
1236
  }
1431
- case FormatEnum2.GeoPoint: {
1432
- if (value === null || value === void 0) {
1433
- return "";
1434
- }
1435
- if (Array.isArray(value) && value.length >= 2 && value.every(Number.isFinite)) {
1436
- const { latitude, longitude } = GeoLocation3.fromGeoPoint(value);
1437
- return `${latitude},${longitude}`;
1438
- }
1439
- return String(value);
1237
+ case "Suspend": {
1238
+ return getDefaultValue(ast.f());
1440
1239
  }
1441
1240
  default: {
1442
- return String(value);
1241
+ if (ast && isNestedType2(ast)) {
1242
+ return {};
1243
+ } else {
1244
+ throw new Error(`Unsupported type: ${ast?._tag}`);
1245
+ }
1443
1246
  }
1444
1247
  }
1445
1248
  };
1446
1249
 
1447
- // src/util/refs.ts
1448
- import { FormatEnum as FormatEnum3, ReferenceAnnotationId } from "@dxos/echo-schema";
1449
- import { findAnnotation } from "@dxos/effect";
1450
-
1451
- // src/util/schema.ts
1452
- import { SchemaAST as SchemaAST2 } from "effect";
1453
- import { findNode } from "@dxos/effect";
1454
- var findArrayElementType = (ast) => {
1455
- const tupleType = findNode(ast, SchemaAST2.isTupleType);
1456
- const elementType = tupleType?.rest[0]?.type;
1457
- return elementType;
1250
+ // src/components/Form/fields/BooleanField.tsx
1251
+ import React6, { useCallback as useCallback4 } from "react";
1252
+ import { Input as Input2 } from "@dxos/react-ui";
1253
+ var BooleanField = ({ type, readonly, onValueChange, ...props }) => {
1254
+ const handleChange = useCallback4((value3) => onValueChange?.(type, value3), [
1255
+ type,
1256
+ onValueChange
1257
+ ]);
1258
+ return /* @__PURE__ */ React6.createElement(FormFieldWrapper, {
1259
+ readonly,
1260
+ ...props
1261
+ }, ({ value: value3 }) => /* @__PURE__ */ React6.createElement(Input2.Switch, {
1262
+ disabled: !!readonly,
1263
+ checked: value3,
1264
+ onCheckedChange: handleChange
1265
+ }));
1458
1266
  };
1459
1267
 
1460
- // src/util/refs.ts
1461
- var getRefProps = (property) => {
1462
- const { ast, format, array } = property;
1463
- if (format === FormatEnum3.Ref) {
1464
- return {
1465
- ast,
1466
- isArray: false
1467
- };
1468
- }
1469
- if (array) {
1470
- const elementType = findArrayElementType(ast);
1471
- if (elementType) {
1472
- const annotation = findAnnotation(elementType, ReferenceAnnotationId);
1473
- if (annotation) {
1474
- return {
1475
- ast: elementType,
1476
- isArray: true
1268
+ // src/components/Form/fields/GeoPointField.tsx
1269
+ import React7, { useCallback as useCallback5, useEffect as useEffect4, useMemo as useMemo5, useState as useState2 } from "react";
1270
+ import { GeoLocation as GeoLocation3 } from "@dxos/echo/internal";
1271
+ import { Input as Input3, useTranslation as useTranslation4 } from "@dxos/react-ui";
1272
+ import { safeParseFloat } from "@dxos/util";
1273
+ var GeoPointField = ({ type, label, readonly, layout, getStatus, getValue, onValueChange, onBlur }) => {
1274
+ const { t } = useTranslation4(translationKey);
1275
+ const { status, error } = getStatus();
1276
+ const geoPoint = useMemo5(() => getValue() ?? [
1277
+ 0,
1278
+ 0
1279
+ ], [
1280
+ getValue
1281
+ ]);
1282
+ const value3 = useMemo5(() => GeoLocation3.fromGeoPoint(geoPoint), [
1283
+ geoPoint
1284
+ ]);
1285
+ const [longitudeText, setLongitudeText] = useState2(value3.longitude?.toString());
1286
+ const [latitudeText, setLatitudeText] = useState2(value3.latitude?.toString());
1287
+ useEffect4(() => {
1288
+ const location = GeoLocation3.fromGeoPoint(geoPoint);
1289
+ setLongitudeText(location.longitude?.toString());
1290
+ setLatitudeText(location.latitude?.toString());
1291
+ }, [
1292
+ geoPoint
1293
+ ]);
1294
+ const handleChange = useCallback5((coordinateType, setText) => (event) => {
1295
+ const inputText = event.target.value;
1296
+ setText(inputText);
1297
+ if (inputText !== "" && inputText !== "-") {
1298
+ const coord = safeParseFloat(inputText);
1299
+ if (coord !== void 0 && !isNaN(coord)) {
1300
+ const currentLocation = GeoLocation3.fromGeoPoint(getValue() ?? [
1301
+ 0,
1302
+ 0
1303
+ ]);
1304
+ const newLocation = {
1305
+ ...currentLocation,
1306
+ [coordinateType]: coord
1477
1307
  };
1308
+ const newValue = GeoLocation3.toGeoPoint(newLocation);
1309
+ onValueChange(type, newValue);
1478
1310
  }
1479
1311
  }
1312
+ }, [
1313
+ type,
1314
+ getValue,
1315
+ onValueChange
1316
+ ]);
1317
+ if ((readonly || layout === "static") && !value3?.latitude && !value3?.longitude) {
1318
+ return null;
1480
1319
  }
1481
- return void 0;
1320
+ return /* @__PURE__ */ React7.createElement(Input3.Root, {
1321
+ validationValence: status
1322
+ }, layout !== "inline" && /* @__PURE__ */ React7.createElement(FormFieldLabel, {
1323
+ error,
1324
+ readonly,
1325
+ label,
1326
+ asChild: true
1327
+ }), layout === "static" ? /* @__PURE__ */ React7.createElement(LatLng, value3) : /* @__PURE__ */ React7.createElement("div", {
1328
+ role: "none",
1329
+ className: "grid grid-cols-2 gap-form-gap"
1330
+ }, /* @__PURE__ */ React7.createElement("div", null, /* @__PURE__ */ React7.createElement(Input3.Root, null, layout !== "inline" && /* @__PURE__ */ React7.createElement(Input3.Label, null, t("latitude.label")), /* @__PURE__ */ React7.createElement(Input3.TextInput, {
1331
+ type: "number",
1332
+ step: "0.00001",
1333
+ min: "-90",
1334
+ max: "90",
1335
+ disabled: !!readonly,
1336
+ placeholder: t("latitude.placeholder"),
1337
+ value: latitudeText ?? "",
1338
+ onChange: handleChange("latitude", setLatitudeText),
1339
+ onBlur
1340
+ }))), /* @__PURE__ */ React7.createElement("div", null, /* @__PURE__ */ React7.createElement(Input3.Root, null, layout !== "inline" && /* @__PURE__ */ React7.createElement(Input3.Label, null, t("longitude.label")), /* @__PURE__ */ React7.createElement(Input3.TextInput, {
1341
+ type: "number",
1342
+ step: "0.00001",
1343
+ min: "-180",
1344
+ max: "180",
1345
+ disabled: !!readonly,
1346
+ placeholder: t("longitude.placeholder"),
1347
+ value: longitudeText ?? "",
1348
+ onChange: handleChange("longitude", setLongitudeText),
1349
+ onBlur
1350
+ })))));
1351
+ };
1352
+ var LatLng = ({ latitude = 0, longitude = 0 }) => {
1353
+ const latHem = latitude >= 0 ? "N" : "S";
1354
+ const lngHem = longitude >= 0 ? "E" : "W";
1355
+ return /* @__PURE__ */ React7.createElement("span", {
1356
+ className: "inline-flex items-center gap-form-gap"
1357
+ }, /* @__PURE__ */ React7.createElement("span", null, /* @__PURE__ */ React7.createElement("span", null, Math.abs(latitude).toFixed(5)), /* @__PURE__ */ React7.createElement("span", {
1358
+ className: "text-subdued"
1359
+ }, "\xB0", latHem)), /* @__PURE__ */ React7.createElement("span", null, /* @__PURE__ */ React7.createElement("span", null, Math.abs(longitude).toFixed(5)), /* @__PURE__ */ React7.createElement("span", {
1360
+ className: "text-subdued"
1361
+ }, "\xB0", lngHem)));
1482
1362
  };
1483
1363
 
1484
- // src/components/Form/ArrayField.tsx
1485
- var __dxlog_file3 = "/__w/dxos/dxos/packages/ui/react-ui-form/src/components/Form/ArrayField.tsx";
1486
- var ArrayField = ({ property, readonly, path, inputProps, Custom, lookupComponent }) => {
1487
- var _effect = _useSignals10();
1488
- try {
1489
- const { t } = useTranslation6(translationKey);
1490
- const { ast, name, type, title } = property;
1491
- const values = useFormValues(path ?? []) ?? [];
1492
- invariant2(Array.isArray(values), `Values at path ${path?.join(".")} must be an array.`, {
1493
- F: __dxlog_file3,
1494
- L: 36,
1495
- S: void 0,
1496
- A: [
1497
- "Array.isArray(values)",
1498
- "`Values at path ${path?.join('.')} must be an array.`"
1499
- ]
1500
- });
1501
- const label = title ?? pipe(name, capitalize);
1502
- const elementType = findArrayElementType(ast);
1503
- const getDefaultObjectValue = (typeNode) => {
1504
- const baseNode = findNode2(typeNode, isDiscriminatedUnion);
1505
- const typeLiteral = baseNode ? getDiscriminatedType(baseNode, {}) : findNode2(typeNode, SchemaAST3.isTypeLiteral);
1506
- if (!typeLiteral) {
1507
- return {};
1508
- }
1509
- return Object.fromEntries(getSchemaProperties(typeLiteral, {}).map((prop) => [
1510
- prop.name,
1511
- prop.defaultValue
1512
- ]));
1513
- };
1514
- const getDefaultValue = () => type === "object" && elementType ? getDefaultObjectValue(elementType) : SimpleType.getDefaultValue(type);
1515
- const handleAdd = useCallback7(() => {
1516
- inputProps.onValueChange(type, [
1517
- ...values,
1518
- getDefaultValue()
1519
- ]);
1520
- }, [
1521
- type,
1522
- elementType,
1523
- inputProps,
1524
- values
1525
- ]);
1526
- const handleRemove = useCallback7((index) => {
1527
- const newValues = values.filter((_, i) => i !== index);
1528
- inputProps.onValueChange(type, newValues);
1529
- }, [
1530
- type,
1531
- inputProps,
1532
- values
1533
- ]);
1534
- if (!elementType) {
1535
- return null;
1364
+ // src/components/Form/fields/MarkdownField.tsx
1365
+ import React8, { useCallback as useCallback6, useEffect as useEffect5, useRef as useRef2 } from "react";
1366
+ import { Input as Input4 } from "@dxos/react-ui";
1367
+ var MarkdownField = ({ type, readonly, label, placeholder, layout, getStatus, getValue, onValueChange, onBlur }) => {
1368
+ const { status, error } = getStatus();
1369
+ const textareaRef = useRef2(null);
1370
+ const adjustHeight = useCallback6(() => {
1371
+ const textarea = textareaRef.current;
1372
+ if (textarea) {
1373
+ textarea.style.blockSize = "auto";
1374
+ textarea.style.blockSize = `${textarea.scrollHeight + 2}px`;
1536
1375
  }
1537
- return readonly && values.length < 1 ? null : /* @__PURE__ */ React10.createElement(React10.Fragment, null, /* @__PURE__ */ React10.createElement(InputHeader, {
1538
- readonly: true,
1539
- label
1540
- }), /* @__PURE__ */ React10.createElement("div", {
1541
- role: "none",
1542
- className: readonly ? "flex flex-wrap gap-1 mlb-1" : values.length > 0 ? "grid gap-1 grid-cols-[1fr_min-content] mlb-1" : "hidden"
1543
- }, values.map((_value, index) => {
1544
- const field = /* @__PURE__ */ React10.createElement(FormField, {
1545
- property: {
1546
- ...property,
1547
- array: false,
1548
- ast: elementType
1549
- },
1550
- path: [
1551
- ...path ?? [],
1552
- index
1553
- ],
1554
- readonly,
1555
- inline: true,
1556
- Custom,
1557
- lookupComponent
1558
- });
1559
- return readonly ? field : /* @__PURE__ */ React10.createElement(Fragment, {
1560
- key: index
1561
- }, /* @__PURE__ */ React10.createElement("div", {
1562
- role: "none"
1563
- }, field), /* @__PURE__ */ React10.createElement(IconButton3, {
1564
- icon: "ph--trash--regular",
1565
- iconOnly: true,
1566
- label: t("button remove"),
1567
- onClick: () => handleRemove(index),
1568
- classNames: "self-center"
1569
- }));
1570
- })), !readonly && /* @__PURE__ */ React10.createElement(IconButton3, {
1571
- classNames: "is-full mlb-cardSpacingBlock flex",
1572
- icon: "ph--plus--regular",
1573
- label: t("add field"),
1574
- onClick: handleAdd
1575
- }));
1576
- } finally {
1577
- _effect.f();
1376
+ }, []);
1377
+ useEffect5(() => {
1378
+ adjustHeight();
1379
+ }, [
1380
+ adjustHeight
1381
+ ]);
1382
+ useEffect5(() => {
1383
+ adjustHeight();
1384
+ }, [
1385
+ getValue(),
1386
+ adjustHeight
1387
+ ]);
1388
+ const handleChange = useCallback6((event) => onValueChange(type, event.target.value), [
1389
+ type,
1390
+ onValueChange
1391
+ ]);
1392
+ const value3 = getValue();
1393
+ if ((readonly || layout === "static") && !value3) {
1394
+ return null;
1578
1395
  }
1396
+ return /* @__PURE__ */ React8.createElement(Input4.Root, {
1397
+ validationValence: status
1398
+ }, layout !== "inline" && /* @__PURE__ */ React8.createElement(FormFieldLabel, {
1399
+ error,
1400
+ readonly,
1401
+ label
1402
+ }), layout === "static" ? /* @__PURE__ */ React8.createElement("p", null, value3) : /* @__PURE__ */ React8.createElement(Input4.TextArea, {
1403
+ ref: textareaRef,
1404
+ disabled: !!readonly,
1405
+ placeholder,
1406
+ value: value3 ?? "",
1407
+ classNames: "min-h-auto max-h-40 overflow-auto",
1408
+ onChange: handleChange,
1409
+ onBlur,
1410
+ style: {
1411
+ resize: "none"
1412
+ },
1413
+ spellCheck: false
1414
+ }), layout === "full" && /* @__PURE__ */ React8.createElement(Input4.Validation, null, error));
1415
+ };
1416
+
1417
+ // src/components/Form/fields/NumberField.tsx
1418
+ import React9, { useCallback as useCallback7 } from "react";
1419
+ import { Input as Input5 } from "@dxos/react-ui";
1420
+ import { safeParseFloat as safeParseFloat2 } from "@dxos/util";
1421
+ var NumberField = ({ type, readonly, placeholder, onValueChange, onBlur, ...props }) => {
1422
+ const handleChange = useCallback7((event) => onValueChange(type, safeParseFloat2(event.target.value) || 0), [
1423
+ type,
1424
+ onValueChange
1425
+ ]);
1426
+ return /* @__PURE__ */ React9.createElement(FormFieldWrapper, {
1427
+ readonly,
1428
+ ...props
1429
+ }, ({ value: value3 = "" }) => /* @__PURE__ */ React9.createElement(Input5.TextInput, {
1430
+ type: "number",
1431
+ disabled: !!readonly,
1432
+ placeholder,
1433
+ value: value3,
1434
+ onChange: handleChange,
1435
+ onBlur
1436
+ }));
1579
1437
  };
1580
1438
 
1581
- // src/components/Form/RefField.tsx
1582
- import { useSignals as _useSignals11 } from "@preact-signals/safe-react/tracking";
1583
- import React11, { useCallback as useCallback8, useMemo as useMemo4 } from "react";
1584
- import { Expando, getTypeAnnotation, Ref, ReferenceAnnotationId as ReferenceAnnotationId2 } from "@dxos/echo-schema";
1439
+ // src/components/Form/fields/RefField.tsx
1440
+ import "@dxos/lit-ui/dx-tag-picker.pcss";
1441
+ import React11, { useCallback as useCallback9, useMemo as useMemo6 } from "react";
1442
+ import { Entity, Filter, Obj, Ref as Ref2, Type } from "@dxos/echo";
1443
+ import { ReferenceAnnotationId as ReferenceAnnotationId2 } from "@dxos/echo/internal";
1444
+ import { useQuery, useSchema as useSchema$ } from "@dxos/echo-react";
1585
1445
  import { findAnnotation as findAnnotation2 } from "@dxos/effect";
1586
1446
  import { DXN } from "@dxos/keys";
1587
- import { DxRefTag } from "@dxos/lit-ui/react";
1588
- import { Input as Input8, useTranslation as useTranslation7 } from "@dxos/react-ui";
1589
- import { TagPicker } from "@dxos/react-ui-tag-picker";
1590
- import { descriptionText, mx as mx7 } from "@dxos/react-ui-theme";
1591
- import { isNonNullable as isNonNullable2 } from "@dxos/util";
1592
- var RefField = ({ type, label, disabled, placeholder, inputOnly, array, ast, getValue: getValue3, onBlur, onQueryRefOptions, onValueChange, ...restInputProps }) => {
1593
- var _effect = _useSignals11();
1594
- try {
1595
- const { t } = useTranslation7(translationKey);
1596
- const refTypeInfo = useMemo4(() => ast ? findAnnotation2(ast, ReferenceAnnotationId2) : void 0, [
1597
- ast
1598
- ]);
1599
- const { options: availableOptions, loading: _loading } = useQueryRefOptions({
1600
- refTypeInfo,
1601
- onQueryRefOptions
1602
- });
1603
- if (refTypeInfo && refTypeInfo?.typename === getTypeAnnotation(Expando)?.typename || !onQueryRefOptions) {
1604
- return /* @__PURE__ */ React11.createElement(RefFieldFallback, {
1605
- type,
1606
- label,
1607
- placeholder,
1608
- disabled,
1609
- inputOnly,
1610
- getValue: getValue3,
1611
- onBlur,
1612
- onValueChange,
1613
- ...restInputProps
1614
- });
1447
+ import { DxAnchor } from "@dxos/lit-ui/react";
1448
+ import { Button, Icon as Icon2, Input as Input6, useTranslation as useTranslation6 } from "@dxos/react-ui";
1449
+ import { ParentLabelAnnotationId } from "@dxos/schema";
1450
+ import { mx as mx2 } from "@dxos/ui-theme";
1451
+
1452
+ // src/components/ObjectPicker/ObjectPicker.tsx
1453
+ import React10, { forwardRef, useCallback as useCallback8, useState as useState3 } from "react";
1454
+ import { Popover, useTranslation as useTranslation5 } from "@dxos/react-ui";
1455
+ import { Combobox, useSearchListInput, useSearchListResults } from "@dxos/react-ui-search";
1456
+ var ObjectPickerContent = /* @__PURE__ */ forwardRef(({ options, selectedIds, createSchema, createOptionLabel, createOptionIcon, createInitialValuePath, createFieldMap, onSelect, onCreate, ...props }, forwardedRef) => {
1457
+ const { t } = useTranslation5(translationKey);
1458
+ const [showForm, setShowForm] = useState3(false);
1459
+ const [formInitialValue, setFormInitialValue] = useState3("");
1460
+ const { results, handleSearch } = useSearchListResults({
1461
+ items: options
1462
+ });
1463
+ const handleFormSave = useCallback8((values) => {
1464
+ onCreate?.(values);
1465
+ setShowForm(false);
1466
+ setFormInitialValue("");
1467
+ }, [
1468
+ onCreate
1469
+ ]);
1470
+ const handleFormCancel = useCallback8(() => {
1471
+ setShowForm(false);
1472
+ setFormInitialValue("");
1473
+ }, []);
1474
+ const handleKeyDown = useCallback8((event) => {
1475
+ if (event.key === "Enter" && createSchema && event.currentTarget.querySelector('[role="option"][aria-selected="true"][data-value="__create__"]')) {
1476
+ event.stopPropagation();
1477
+ event.preventDefault();
1478
+ const input = event.currentTarget.querySelector('input[type="text"]');
1479
+ const currentQuery = input?.value || "";
1480
+ setFormInitialValue(currentQuery);
1481
+ setShowForm(true);
1615
1482
  }
1616
- const handleGetValue = useCallback8(() => {
1617
- const formValue = getValue3();
1618
- const unknownToRefOption = (val) => {
1619
- if (Ref.isRef(val)) {
1620
- const dxnString = val.dxn.toString();
1621
- const matchingOption = availableOptions.find((option2) => option2.id === dxnString);
1622
- if (matchingOption) {
1623
- return matchingOption;
1624
- }
1625
- }
1626
- return void 0;
1627
- };
1628
- if (array && Array.isArray(formValue)) {
1629
- return formValue.map(unknownToRefOption).filter(isNonNullable2) ?? [];
1630
- }
1631
- const option = unknownToRefOption(formValue);
1632
- if (option) {
1633
- return [
1634
- option
1635
- ];
1636
- }
1637
- return [];
1638
- }, [
1639
- getValue3,
1640
- availableOptions,
1641
- array
1642
- ]);
1643
- const handleSearch = useCallback8((text, ids) => availableOptions.filter((option) => !ids.includes(option.id)).filter((option) => option.label.toLowerCase().includes(text.toLowerCase())).map((option) => ({
1644
- id: option.id,
1645
- label: option.label,
1646
- hue: option.hue
1647
- })), [
1648
- availableOptions
1649
- ]);
1650
- const handleUpdate = useCallback8((ids) => {
1651
- if (ids.length === 0) {
1652
- onValueChange("object", void 0);
1653
- return;
1654
- }
1655
- const refs = ids.map((id) => {
1656
- const item = availableOptions.find((option) => option.id === id);
1657
- if (item) {
1658
- const dxn = DXN.parse(item.id);
1659
- return Ref.fromDXN(dxn);
1660
- }
1661
- return null;
1662
- }).filter(isNonNullable2);
1663
- if (array) {
1664
- onValueChange("object", refs);
1665
- } else {
1666
- onValueChange("object", refs[0]);
1667
- }
1668
- }, [
1669
- availableOptions,
1670
- array,
1671
- onValueChange
1672
- ]);
1673
- const tagPickerMode = useMemo4(() => array ? "multi-select" : "single-select", [
1674
- array
1675
- ]);
1676
- if (!refTypeInfo) {
1677
- return null;
1678
- }
1679
- const { status, error } = restInputProps.getStatus();
1680
- const items = handleGetValue();
1681
- return disabled && items.length < 1 ? null : /* @__PURE__ */ React11.createElement(Input8.Root, {
1682
- validationValence: status
1683
- }, !inputOnly && /* @__PURE__ */ React11.createElement(InputHeader, {
1684
- error,
1685
- label
1686
- }), /* @__PURE__ */ React11.createElement("div", {
1687
- "data-no-submit": true
1688
- }, disabled ? items.length < 1 ? /* @__PURE__ */ React11.createElement("p", {
1689
- className: mx7(descriptionText, "mbe-2")
1690
- }, t("empty readonly ref field label")) : items.map((item) => /* @__PURE__ */ React11.createElement(DxRefTag, {
1691
- key: item.id,
1692
- refid: item.id,
1693
- rootclassname: "mie-1",
1694
- style: {
1695
- marginInlineEnd: ".25rem"
1696
- }
1697
- }, item.label)) : /* @__PURE__ */ React11.createElement(TagPicker, {
1698
- readonly: disabled,
1699
- items,
1700
- mode: tagPickerMode,
1701
- onBlur: (event) => onBlur(event),
1702
- onUpdate: handleUpdate,
1483
+ }, [
1484
+ createSchema
1485
+ ]);
1486
+ if (showForm && createSchema) {
1487
+ return /* @__PURE__ */ React10.createElement(Combobox.Content, {
1488
+ ...props,
1703
1489
  onSearch: handleSearch,
1704
- classNames: "bg-inputSurface p-1.5 rounded-sm"
1705
- })), inputOnly && /* @__PURE__ */ React11.createElement(Input8.DescriptionAndValidation, null, error));
1706
- } finally {
1707
- _effect.f();
1490
+ onKeyDownCapture: handleKeyDown,
1491
+ ref: forwardedRef
1492
+ }, /* @__PURE__ */ React10.createElement(Popover.Viewport, null, /* @__PURE__ */ React10.createElement(Form.Root, {
1493
+ testId: "create-referenced-object-form",
1494
+ schema: createSchema,
1495
+ defaultValues: createInitialValuePath ? {
1496
+ [createInitialValuePath]: formInitialValue
1497
+ } : {},
1498
+ fieldMap: createFieldMap,
1499
+ onSave: handleFormSave,
1500
+ onCancel: handleFormCancel
1501
+ }, /* @__PURE__ */ React10.createElement(Form.Viewport, null, /* @__PURE__ */ React10.createElement(Form.Content, null, /* @__PURE__ */ React10.createElement(Form.FieldSet, null), /* @__PURE__ */ React10.createElement(Form.Actions, null))))), /* @__PURE__ */ React10.createElement(Combobox.Arrow, null));
1708
1502
  }
1503
+ return /* @__PURE__ */ React10.createElement(Combobox.Content, {
1504
+ ...props,
1505
+ onSearch: handleSearch,
1506
+ onKeyDownCapture: handleKeyDown,
1507
+ ref: forwardedRef
1508
+ }, /* @__PURE__ */ React10.createElement(Combobox.Input, {
1509
+ placeholder: t("ref-field-combobox-input.placeholder"),
1510
+ autoFocus: true
1511
+ }), /* @__PURE__ */ React10.createElement(Combobox.List, null, results.map((option) => /* @__PURE__ */ React10.createElement(Combobox.Item, {
1512
+ key: option.id,
1513
+ value: option.id,
1514
+ label: option.label,
1515
+ checked: selectedIds?.includes(option.id),
1516
+ onSelect: () => onSelect(option.id),
1517
+ classNames: "flex items-center gap-2"
1518
+ })), createSchema && onCreate && /* @__PURE__ */ React10.createElement(CreateItem, {
1519
+ createOptionLabel,
1520
+ createOptionIcon: createOptionIcon ?? "ph--plus--regular",
1521
+ onCreateItemSelect: (query) => {
1522
+ setFormInitialValue(query);
1523
+ setShowForm(true);
1524
+ }
1525
+ })), /* @__PURE__ */ React10.createElement(Combobox.Arrow, null));
1526
+ });
1527
+ var CreateItem = ({ createOptionLabel, createOptionIcon, onCreateItemSelect }) => {
1528
+ const { t } = useTranslation5(translationKey);
1529
+ const { query } = useSearchListInput();
1530
+ const label = createOptionLabel ? t(createOptionLabel[0], {
1531
+ ns: createOptionLabel[1].ns,
1532
+ text: query
1533
+ }) : t("create-option.label");
1534
+ return /* @__PURE__ */ React10.createElement(Combobox.Item, {
1535
+ value: "__create__",
1536
+ label,
1537
+ icon: createOptionIcon,
1538
+ classNames: "flex items-center gap-2",
1539
+ closeOnSelect: false,
1540
+ onSelect: () => {
1541
+ onCreateItemSelect(query);
1542
+ }
1543
+ });
1709
1544
  };
1710
- var RefFieldFallback = ({ type, label, disabled, placeholder, inputOnly, getValue: getValue3, onValueChange, ...restInputProps }) => {
1711
- var _effect = _useSignals11();
1712
- try {
1713
- const handleOnValueChange = (_type, dxnString) => {
1714
- const dxn = DXN.tryParse(dxnString);
1715
- if (dxn) {
1716
- onValueChange?.("object", Ref.fromDXN(dxn));
1717
- } else if (dxnString === "") {
1718
- onValueChange?.("object", void 0);
1719
- } else {
1720
- onValueChange?.("string", dxnString);
1721
- }
1722
- };
1723
- const handleGetValue = () => {
1724
- const formValue = getValue3();
1725
- if (typeof formValue === "string") {
1726
- return formValue;
1727
- }
1728
- if (Ref.isRef(formValue)) {
1729
- return formValue.dxn.toString();
1545
+ ObjectPickerContent.displayName = "ObjectPicker.Content";
1546
+ var ObjectPicker = {
1547
+ Root: Combobox.Root,
1548
+ Portal: Combobox.Portal,
1549
+ Trigger: Combobox.Trigger,
1550
+ VirtualTrigger: Combobox.VirtualTrigger,
1551
+ Content: ObjectPickerContent
1552
+ };
1553
+
1554
+ // src/components/Form/fields/RefField.tsx
1555
+ var isRefSnapshot = (val) => {
1556
+ return typeof val === "object" && typeof val?.["/"] === "string";
1557
+ };
1558
+ var defaultGetOptions = (results, { parentLabel } = {}) => results.map((result) => {
1559
+ const id = Entity.getDXN(result).toString();
1560
+ const parent = parentLabel ? Obj.getParent(result) : void 0;
1561
+ const label = parent ? Entity.getLabel(parent) : Entity.getLabel(result);
1562
+ return {
1563
+ id,
1564
+ label: label ?? id
1565
+ };
1566
+ });
1567
+ var defaultResultsHook = (db, typename) => useQuery(db, typename ? typename === Type.getTypename(Obj.Unknown) ? Filter.everything() : Filter.typename(typename) : Filter.nothing());
1568
+ var RefField = (props) => {
1569
+ const { type, readonly, label, placeholder, layout, getStatus, getValue, createOptionLabel, createOptionIcon, createInitialValuePath, createFieldMap, db, resultsHook: useResults = defaultResultsHook, schemaHook: useSchema = useSchema$, getOptions: getOptions2 = defaultGetOptions, onCreate, onValueChange } = props;
1570
+ const { t } = useTranslation6(translationKey);
1571
+ const { status, error } = getStatus();
1572
+ const typename = useMemo6(() => type ? findAnnotation2(type, ReferenceAnnotationId2)?.typename : void 0, [
1573
+ type
1574
+ ]);
1575
+ const results = useResults(db, typename);
1576
+ const options = useMemo6(() => {
1577
+ const parentLabel = type ? findAnnotation2(type, ParentLabelAnnotationId) === true : false;
1578
+ return getOptions2(results, {
1579
+ parentLabel
1580
+ });
1581
+ }, [
1582
+ results,
1583
+ getOptions2,
1584
+ type
1585
+ ]);
1586
+ const handleGetValue = useCallback9(() => {
1587
+ const formValue = getValue();
1588
+ const unknownToRefOption = (value3) => {
1589
+ const isRef = Ref2.isRef(value3);
1590
+ if (isRef || isRefSnapshot(value3)) {
1591
+ const dxnString = isRef ? value3.dxn.toString() : value3["/"];
1592
+ const matchingOption = options.find((option) => option.id === dxnString);
1593
+ if (matchingOption) {
1594
+ return matchingOption;
1595
+ }
1730
1596
  }
1731
1597
  return void 0;
1732
1598
  };
1733
- return /* @__PURE__ */ React11.createElement(TextInput, {
1734
- type,
1735
- label,
1736
- disabled,
1737
- placeholder,
1738
- inputOnly,
1739
- getValue: handleGetValue,
1740
- onValueChange: handleOnValueChange,
1741
- ...restInputProps
1742
- });
1743
- } finally {
1744
- _effect.f();
1599
+ return unknownToRefOption(formValue);
1600
+ }, [
1601
+ options,
1602
+ getValue
1603
+ ]);
1604
+ const handleUpdate = useCallback9((id) => {
1605
+ const item2 = options.find((option) => option.id === id);
1606
+ const ref = item2 ? Ref2.fromDXN(DXN.parse(item2.id)) : void 0;
1607
+ onValueChange(type, ref);
1608
+ }, [
1609
+ options,
1610
+ type,
1611
+ onValueChange
1612
+ ]);
1613
+ const item = handleGetValue();
1614
+ const selectedIds = useMemo6(() => item ? [
1615
+ item.id
1616
+ ] : [], [
1617
+ item
1618
+ ]);
1619
+ const createSchema = useSchema(db, typename);
1620
+ const handleCreate = useCallback9((values) => {
1621
+ if (createSchema && onCreate) {
1622
+ onCreate(createSchema, values);
1623
+ }
1624
+ }, [
1625
+ createSchema,
1626
+ onCreate
1627
+ ]);
1628
+ const handleSelect = useCallback9((id) => {
1629
+ if (item?.id === id) {
1630
+ handleUpdate(void 0);
1631
+ } else {
1632
+ handleUpdate(id);
1633
+ }
1634
+ }, [
1635
+ item,
1636
+ handleUpdate
1637
+ ]);
1638
+ if (!typename || (readonly || layout === "static") && !item) {
1639
+ return null;
1745
1640
  }
1641
+ return /* @__PURE__ */ React11.createElement(Input6.Root, {
1642
+ validationValence: status
1643
+ }, layout !== "inline" && /* @__PURE__ */ React11.createElement(FormFieldLabel, {
1644
+ error,
1645
+ readonly,
1646
+ label
1647
+ }), /* @__PURE__ */ React11.createElement("div", null, readonly ? !item ? /* @__PURE__ */ React11.createElement("p", {
1648
+ className: mx2("text-description", "mb-2")
1649
+ }, t("empty-readonly-ref-field.label")) : /* @__PURE__ */ React11.createElement(DxAnchor, {
1650
+ key: item.id,
1651
+ dxn: item.id,
1652
+ rootclassname: "me-1"
1653
+ }, item.label) : /* @__PURE__ */ React11.createElement(ObjectPicker.Root, null, /* @__PURE__ */ React11.createElement(ObjectPicker.Trigger, {
1654
+ asChild: true,
1655
+ classNames: "p-0"
1656
+ }, item ? /* @__PURE__ */ React11.createElement("div", {
1657
+ className: "flex gap-form-gap w-full"
1658
+ }, /* @__PURE__ */ React11.createElement(Input6.Root, {
1659
+ key: item.id
1660
+ }, /* @__PURE__ */ React11.createElement(Input6.TextInput, {
1661
+ value: item.label,
1662
+ readOnly: true,
1663
+ classNames: "w-full"
1664
+ }))) : /* @__PURE__ */ React11.createElement(Button, {
1665
+ classNames: "w-full text-start gap-form-gap"
1666
+ }, /* @__PURE__ */ React11.createElement("div", {
1667
+ role: "none",
1668
+ className: "grow overflow-hidden"
1669
+ }, /* @__PURE__ */ React11.createElement("span", {
1670
+ className: "flex truncate text-description"
1671
+ }, placeholder ?? t("ref-field.placeholder"))), /* @__PURE__ */ React11.createElement(Icon2, {
1672
+ size: 3,
1673
+ icon: "ph--caret-down--bold"
1674
+ }))), /* @__PURE__ */ React11.createElement(ObjectPicker.Portal, null, /* @__PURE__ */ React11.createElement(ObjectPicker.Content, {
1675
+ classNames: "dx-card-popover-width",
1676
+ options,
1677
+ selectedIds,
1678
+ createSchema: createSchema && omitId(createSchema),
1679
+ createOptionLabel,
1680
+ createOptionIcon,
1681
+ createInitialValuePath,
1682
+ createFieldMap,
1683
+ onCreate: handleCreate,
1684
+ onSelect: handleSelect
1685
+ })))), layout === "full" && /* @__PURE__ */ React11.createElement(Input6.DescriptionAndValidation, null, error));
1746
1686
  };
1747
1687
 
1748
- // src/components/Form/factory.tsx
1749
- import { FormatEnum as FormatEnum4 } from "@dxos/echo-schema";
1750
- var getInputComponent = (type, format) => {
1751
- switch (format) {
1752
- case FormatEnum4.GeoPoint:
1753
- return GeoPointInput;
1754
- case FormatEnum4.Markdown:
1755
- return MarkdownInput;
1756
- }
1757
- switch (type) {
1758
- case "string":
1759
- return TextInput;
1760
- case "number":
1761
- return NumberInput;
1762
- case "boolean":
1763
- return BooleanInput;
1688
+ // src/components/Form/fields/SelectField.tsx
1689
+ import React12, { useCallback as useCallback10 } from "react";
1690
+ import { Input as Input7, Select } from "@dxos/react-ui";
1691
+ var SelectField = ({ type, readonly, label, layout, placeholder, options, getStatus, getValue, onValueChange }) => {
1692
+ const { status, error } = getStatus();
1693
+ const value3 = getValue();
1694
+ const handleValueChange = useCallback10((value4) => onValueChange(type, value4), [
1695
+ type,
1696
+ onValueChange
1697
+ ]);
1698
+ if ((readonly || layout === "static") && value3 == null) {
1699
+ return null;
1764
1700
  }
1701
+ return /* @__PURE__ */ React12.createElement(Input7.Root, {
1702
+ validationValence: status
1703
+ }, layout !== "inline" && /* @__PURE__ */ React12.createElement(FormFieldLabel, {
1704
+ error,
1705
+ readonly,
1706
+ label
1707
+ }), layout === "static" ? /* @__PURE__ */ React12.createElement("p", null, options?.find(({ value: optionValue }) => optionValue === value3)?.label ?? String(value3)) : /* @__PURE__ */ React12.createElement(Select.Root, {
1708
+ value: value3,
1709
+ onValueChange: handleValueChange
1710
+ }, /* @__PURE__ */ React12.createElement(Select.TriggerButton, {
1711
+ classNames: "w-full",
1712
+ disabled: !!readonly,
1713
+ placeholder
1714
+ }), /* @__PURE__ */ React12.createElement(Select.Portal, null, /* @__PURE__ */ React12.createElement(Select.Content, null, /* @__PURE__ */ React12.createElement(Select.Viewport, null, options?.map(({ value: value4, label: label2 }) => (
1715
+ // NOTE: Numeric values are converted to and from strings.
1716
+ /* @__PURE__ */ React12.createElement(Select.Option, {
1717
+ key: String(value4),
1718
+ value: String(value4)
1719
+ }, label2 ?? String(value4))
1720
+ ))), /* @__PURE__ */ React12.createElement(Select.Arrow, null)))), layout === "full" && /* @__PURE__ */ React12.createElement(Input7.DescriptionAndValidation, null, error));
1765
1721
  };
1766
1722
 
1767
- // src/components/Form/FormContent.tsx
1768
- var FormField = ({ property, path, readonly, inline, onQueryRefOptions, lookupComponent, Custom }) => {
1769
- var _effect = _useSignals12();
1770
- try {
1771
- const { ast, name, type, format, title, description, options, examples, array } = property;
1772
- const inputProps = useInputProps(path);
1773
- const label = useMemo5(() => title ?? pipe2(name, capitalize2), [
1774
- title,
1775
- name
1776
- ]);
1777
- const placeholder = useMemo5(() => examples?.length ? `Example: "${examples[0]}"` : description, [
1778
- examples,
1779
- description
1780
- ]);
1781
- const FoundComponent = lookupComponent?.({
1782
- prop: name,
1783
- schema: Schema.make(ast),
1784
- inputProps: {
1785
- type,
1786
- format,
1787
- label,
1788
- disabled: readonly,
1789
- placeholder,
1790
- ...inputProps
1791
- }
1792
- });
1793
- if (FoundComponent) {
1794
- return FoundComponent;
1795
- }
1796
- const jsonPath = createJsonPath3(path ?? []);
1797
- const CustomComponent = Custom?.[jsonPath];
1798
- if (CustomComponent) {
1799
- return /* @__PURE__ */ React12.createElement(CustomComponent, {
1800
- type,
1801
- format,
1802
- label,
1803
- inputOnly: inline,
1804
- placeholder,
1805
- disabled: readonly,
1806
- ...inputProps
1807
- });
1808
- }
1809
- const refProps = getRefProps(property);
1810
- if (refProps) {
1811
- return /* @__PURE__ */ React12.createElement(RefField, {
1812
- ast: refProps.ast,
1813
- array: refProps.isArray,
1814
- type,
1815
- format,
1816
- label,
1817
- placeholder,
1818
- disabled: readonly,
1819
- inputOnly: inline,
1820
- onQueryRefOptions,
1821
- ...inputProps
1822
- });
1723
+ // src/components/Form/fields/SelectOptionField.tsx
1724
+ import React13, { useCallback as useCallback11, useEffect as useEffect6, useRef as useRef3, useState as useState4 } from "react";
1725
+ import { PublicKey } from "@dxos/keys";
1726
+ import { IconButton as IconButton3, Input as Input8, Tag, useTranslation as useTranslation7 } from "@dxos/react-ui";
1727
+ import { List } from "@dxos/react-ui-list";
1728
+ import { HuePicker } from "@dxos/react-ui-pickers";
1729
+ import { hues, osTranslations, subtleHover } from "@dxos/ui-theme";
1730
+ var SelectOptionField = ({ type, readonly, label, getStatus, getValue, onValueChange }) => {
1731
+ const { t } = useTranslation7(translationKey);
1732
+ const { status, error } = getStatus();
1733
+ const [selected, setSelectedId] = useState4(null);
1734
+ const [isNewOption, setIsNewOption] = useState4(false);
1735
+ const inputRef = useRef3(null);
1736
+ const options = getValue();
1737
+ useEffect6(() => {
1738
+ if (options === void 0) {
1739
+ onValueChange(type, []);
1823
1740
  }
1824
- if (array) {
1825
- return /* @__PURE__ */ React12.createElement(ArrayField, {
1826
- property,
1827
- path,
1828
- inputProps,
1829
- readonly,
1830
- Custom
1831
- });
1741
+ }, [
1742
+ options,
1743
+ type,
1744
+ onValueChange
1745
+ ]);
1746
+ const randomHue = () => {
1747
+ const usedHues = new Set(options?.map((option) => option.color) ?? []);
1748
+ const unusedHues = hues.filter((hue) => !usedHues.has(hue));
1749
+ if (unusedHues.length > 0) {
1750
+ return unusedHues[Math.floor(Math.random() * unusedHues.length)];
1832
1751
  }
1833
- const InputComponent = getInputComponent(type, format);
1834
- if (InputComponent) {
1835
- return /* @__PURE__ */ React12.createElement(InputComponent, {
1836
- type,
1837
- format,
1838
- label,
1839
- inputOnly: inline,
1840
- placeholder,
1841
- disabled: readonly,
1842
- ...inputProps
1843
- });
1752
+ const lastThree = new Set(options?.slice(-3).map((option) => option.color) ?? []);
1753
+ const availableHues = hues.filter((hue) => !lastThree.has(hue));
1754
+ return availableHues[Math.floor(Math.random() * availableHues.length)] ?? hues[Math.floor(Math.random() * hues.length)];
1755
+ };
1756
+ const handleAdd = useCallback11(() => {
1757
+ const newId = PublicKey.random().truncate();
1758
+ const newOption = {
1759
+ id: newId,
1760
+ title: "",
1761
+ color: randomHue()
1762
+ };
1763
+ onValueChange(type, [
1764
+ ...options ?? [],
1765
+ newOption
1766
+ ]);
1767
+ setSelectedId(newId);
1768
+ setIsNewOption(true);
1769
+ }, [
1770
+ options,
1771
+ type,
1772
+ onValueChange
1773
+ ]);
1774
+ const handleDelete = useCallback11((id) => {
1775
+ const newOptions = options?.filter((option) => option.id !== id) ?? [];
1776
+ onValueChange(type, newOptions);
1777
+ setSelectedId(null);
1778
+ }, [
1779
+ options,
1780
+ type,
1781
+ onValueChange
1782
+ ]);
1783
+ const handleMove = useCallback11((from, to) => {
1784
+ if (!options) {
1785
+ return;
1844
1786
  }
1845
- if (options) {
1846
- return /* @__PURE__ */ React12.createElement(SelectInput, {
1847
- type,
1848
- format,
1849
- disabled: readonly,
1850
- inputOnly: inline,
1851
- label,
1852
- options: options.map((option) => ({
1853
- value: option,
1854
- label: String(option)
1855
- })),
1856
- placeholder,
1857
- ...inputProps
1858
- });
1787
+ const newOptions = [
1788
+ ...options
1789
+ ];
1790
+ const [removed] = newOptions.splice(from, 1);
1791
+ newOptions.splice(to, 0, removed);
1792
+ onValueChange(type, newOptions);
1793
+ }, [
1794
+ options,
1795
+ type,
1796
+ onValueChange
1797
+ ]);
1798
+ const handleClick = useCallback11((id) => {
1799
+ setSelectedId((current) => current === id ? null : id);
1800
+ }, []);
1801
+ const handleTitleChange = useCallback11((id) => (e) => {
1802
+ const newOptions = options?.map((o) => o.id === id ? {
1803
+ ...o,
1804
+ title: e.target.value
1805
+ } : o);
1806
+ onValueChange(type, newOptions ?? []);
1807
+ }, [
1808
+ options,
1809
+ type,
1810
+ onValueChange
1811
+ ]);
1812
+ const handleKeyDown = useCallback11((ev) => {
1813
+ if (ev.key === "Enter") {
1814
+ setSelectedId(null);
1859
1815
  }
1860
- if (type === "object") {
1861
- const baseNode = findNode3(ast, isDiscriminatedUnion2);
1862
- const typeLiteral = baseNode ? getDiscriminatedType2(baseNode, inputProps.getValue()) : findNode3(ast, SchemaAST4.isTypeLiteral);
1863
- if (typeLiteral) {
1864
- return /* @__PURE__ */ React12.createElement(React12.Fragment, null, !inline && /* @__PURE__ */ React12.createElement("h3", {
1865
- className: mx8("text-lg mlb-inputSpacingBlock first:mbs-0")
1866
- }, label), /* @__PURE__ */ React12.createElement(FormFields, {
1867
- schema: Schema.make(typeLiteral),
1868
- path,
1869
- readonly,
1870
- onQueryRefOptions,
1871
- Custom,
1872
- lookupComponent
1873
- }));
1874
- }
1816
+ }, []);
1817
+ const handleColorChange = useCallback11((id) => (hue) => {
1818
+ const newOptions = options?.map((o) => o.id === id ? {
1819
+ ...o,
1820
+ color: hue
1821
+ } : o);
1822
+ onValueChange(type, newOptions ?? []);
1823
+ }, [
1824
+ options,
1825
+ type,
1826
+ onValueChange
1827
+ ]);
1828
+ useEffect6(() => {
1829
+ if (selected && isNewOption && inputRef.current) {
1830
+ inputRef.current.focus();
1831
+ setIsNewOption(false);
1875
1832
  }
1876
- return null;
1877
- } finally {
1878
- _effect.f();
1879
- }
1833
+ }, [
1834
+ selected,
1835
+ isNewOption
1836
+ ]);
1837
+ return /* @__PURE__ */ React13.createElement(Input8.Root, {
1838
+ validationValence: status
1839
+ }, /* @__PURE__ */ React13.createElement(FormFieldLabel, {
1840
+ error,
1841
+ readonly,
1842
+ label
1843
+ }), /* @__PURE__ */ React13.createElement("div", {
1844
+ role: "none"
1845
+ }, options && /* @__PURE__ */ React13.createElement(List.Root, {
1846
+ items: options,
1847
+ isItem: (_item) => true,
1848
+ onMove: readonly ? void 0 : handleMove,
1849
+ readonly: !!readonly
1850
+ }, ({ items }) => /* @__PURE__ */ React13.createElement("div", {
1851
+ role: "list",
1852
+ className: "w-full overflow-auto"
1853
+ }, items?.map((item) => /* @__PURE__ */ React13.createElement("div", {
1854
+ key: item.id
1855
+ }, /* @__PURE__ */ React13.createElement(List.Item, {
1856
+ role: "button",
1857
+ item,
1858
+ classNames: [
1859
+ subtleHover,
1860
+ "flex flex-col cursor-pointer rounded-xs"
1861
+ ],
1862
+ "aria-expanded": selected === item.id
1863
+ }, /* @__PURE__ */ React13.createElement("div", {
1864
+ className: "flex items-center"
1865
+ }, /* @__PURE__ */ React13.createElement(List.ItemDragHandle, {
1866
+ disabled: !!readonly
1867
+ }), /* @__PURE__ */ React13.createElement(List.ItemTitle, {
1868
+ onClick: () => handleClick(item.id),
1869
+ classNames: "flex-1"
1870
+ }, /* @__PURE__ */ React13.createElement(Tag, {
1871
+ palette: item.color
1872
+ }, item.title || "\u200B")), /* @__PURE__ */ React13.createElement(IconButton3, {
1873
+ iconOnly: true,
1874
+ variant: "ghost",
1875
+ label: t(selected === item.id ? "collapse label" : "expand label", {
1876
+ ns: osTranslations
1877
+ }),
1878
+ icon: selected === item.id ? "ph--caret-down--regular" : "ph--caret-right--regular",
1879
+ onClick: () => handleClick(item.id)
1880
+ })), selected === item.id && /* @__PURE__ */ React13.createElement("div", {
1881
+ className: "flex flex-col p-form-padding gap-form-gap dx-density-fine"
1882
+ }, /* @__PURE__ */ React13.createElement(Input8.Label, {
1883
+ classNames: "text-xs"
1884
+ }, t("select-option.label")), /* @__PURE__ */ React13.createElement("div", {
1885
+ className: "grid grid-cols-[1fr_min-content_min-content] gap-form-gap"
1886
+ }, /* @__PURE__ */ React13.createElement(Input8.TextInput, {
1887
+ disabled: !!readonly,
1888
+ placeholder: t("select-option-label.placeholder"),
1889
+ ref: selected === item.id ? inputRef : void 0,
1890
+ value: item.title,
1891
+ onChange: handleTitleChange(item.id),
1892
+ onKeyDown: handleKeyDown,
1893
+ classNames: "flex-1"
1894
+ }), /* @__PURE__ */ React13.createElement(HuePicker, {
1895
+ disabled: !!readonly,
1896
+ value: item.color,
1897
+ onChange: handleColorChange(item.id)
1898
+ }), /* @__PURE__ */ React13.createElement(IconButton3, {
1899
+ disabled: !!readonly,
1900
+ icon: "ph--trash--fill",
1901
+ iconOnly: true,
1902
+ label: t("select-option-delete.button"),
1903
+ onClick: () => handleDelete(item.id)
1904
+ })))))), /* @__PURE__ */ React13.createElement(IconButton3, {
1905
+ variant: "ghost",
1906
+ icon: "ph--plus--regular",
1907
+ label: t("select-option-add.button"),
1908
+ onClick: handleAdd,
1909
+ disabled: !!readonly,
1910
+ classNames: "w-full"
1911
+ })))));
1880
1912
  };
1881
- var FormFields = /* @__PURE__ */ forwardRef(({ classNames, testId, schema, path, filter, sort, readonly, lookupComponent, Custom, onQueryRefOptions }, forwardRef2) => {
1882
- var _effect = _useSignals12();
1883
- try {
1884
- const values = useFormValues(path);
1885
- const properties = useMemo5(() => {
1886
- const props = getSchemaProperties2(schema.ast, values);
1887
- const filtered = filter ? filter(props) : props;
1888
- return sort ? filtered.sort((a, b) => sort.indexOf(a.name) - sort.indexOf(b.name)) : filtered;
1889
- }, [
1890
- schema,
1891
- values,
1892
- filter,
1893
- sort
1894
- ]);
1895
- return /* @__PURE__ */ React12.createElement("div", {
1896
- role: "form",
1897
- className: mx8("is-full", classNames),
1898
- ref: forwardRef2
1899
- }, properties.map((property) => {
1900
- return /* @__PURE__ */ React12.createElement(FormField, {
1901
- key: property.name,
1902
- property,
1903
- path: [
1904
- ...path ?? [],
1905
- property.name
1906
- ],
1907
- readonly,
1908
- onQueryRefOptions,
1909
- lookupComponent,
1910
- Custom
1911
- });
1912
- }).filter(isNotFalsy));
1913
- } finally {
1914
- _effect.f();
1915
- }
1916
- });
1917
1913
 
1918
- // src/components/Form/Form.tsx
1919
- var Form = ({ classNames, testId, values: initialValues, autoFocus, readonly, autoSave, outerSpacing = true, onCancel, schema, onValuesChanged, onValidate, onSave, ...props }) => {
1920
- var _effect = _useSignals13();
1921
- try {
1922
- const formRef = useRef3(null);
1923
- const handleValid = useMemo6(() => autoSave ? onSave : void 0, [
1924
- autoSave,
1925
- onSave
1926
- ]);
1927
- useEffect7(() => {
1928
- if (autoFocus && formRef.current) {
1929
- const input = formRef.current.querySelector("input");
1930
- if (input) {
1931
- input.focus();
1932
- }
1933
- }
1934
- }, [
1935
- autoFocus
1936
- ]);
1937
- return /* @__PURE__ */ React13.createElement(FormProvider, {
1938
- formRef,
1939
- schema,
1940
- autoSave,
1941
- initialValues,
1942
- onValuesChanged,
1943
- onValidate,
1944
- onValid: handleValid,
1945
- onSave
1946
- }, /* @__PURE__ */ React13.createElement("div", {
1947
- role: "none",
1948
- className: "contents",
1949
- "data-testid": testId
1950
- }, /* @__PURE__ */ React13.createElement(FormFields, {
1951
- ...props,
1952
- ref: formRef,
1953
- classNames: [
1954
- outerSpacing === "blockStart-0" ? "pli-cardSpacingInline mbe-cardSpacingBlock [&>.mbs-inputSpacingBlock:first-child]:!mbs-0" : outerSpacing === "scroll-fields" ? "pli-cardSpacingInline pbe-cardSpacingBlock" : outerSpacing ? cardSpacing2 : false,
1955
- outerSpacing === "scroll-fields" && cardDialogOverflow,
1956
- classNames
1957
- ],
1958
- readonly,
1959
- schema
1960
- }), (onCancel || onSave) && !autoSave && /* @__PURE__ */ React13.createElement(FormActions, {
1961
- readonly,
1962
- onCancel,
1963
- outerSpacing
1964
- })));
1965
- } finally {
1966
- _effect.f();
1967
- }
1914
+ // src/components/Form/fields/TextField.tsx
1915
+ import React14, { useCallback as useCallback12 } from "react";
1916
+ import { Input as Input9 } from "@dxos/react-ui";
1917
+ var TextField = ({ type, readonly, placeholder, onValueChange, onBlur, ...props }) => {
1918
+ const handleChange = useCallback12((event) => onValueChange(type, event.target.value), [
1919
+ type,
1920
+ onValueChange
1921
+ ]);
1922
+ return /* @__PURE__ */ React14.createElement(FormFieldWrapper, {
1923
+ readonly,
1924
+ ...props
1925
+ }, ({ value: value3 = "" }) => /* @__PURE__ */ React14.createElement(Input9.TextInput, {
1926
+ noAutoFill: true,
1927
+ disabled: !!readonly,
1928
+ placeholder,
1929
+ value: value3,
1930
+ onChange: handleChange,
1931
+ onBlur
1932
+ }));
1933
+ };
1934
+
1935
+ // src/components/Form/fields/TextAreaField.tsx
1936
+ import React15, { useCallback as useCallback13 } from "react";
1937
+ import { Input as Input10 } from "@dxos/react-ui";
1938
+ var TextAreaField = ({ type, readonly, placeholder, onValueChange, onBlur, ...props }) => {
1939
+ const handleChange = useCallback13((event) => onValueChange(type, event.target.value), [
1940
+ type,
1941
+ onValueChange
1942
+ ]);
1943
+ return /* @__PURE__ */ React15.createElement(FormFieldWrapper, {
1944
+ readonly,
1945
+ ...props
1946
+ }, ({ value: value3 = "" }) => /* @__PURE__ */ React15.createElement(Input10.TextArea, {
1947
+ rows: 3,
1948
+ disabled: !!readonly,
1949
+ placeholder,
1950
+ value: value3,
1951
+ onChange: handleChange,
1952
+ onBlur
1953
+ }));
1954
+ };
1955
+
1956
+ // src/components/Form/fields/TupleField.tsx
1957
+ import React16 from "react";
1958
+ import { Input as Input11 } from "@dxos/react-ui";
1959
+ import { mx as mx3 } from "@dxos/ui-theme";
1960
+ import { safeParseFloat as safeParseFloat3 } from "@dxos/util";
1961
+ var gridCols = [
1962
+ "grid-cols-1",
1963
+ "grid-cols-2",
1964
+ "grid-cols-3",
1965
+ "grid-cols-4"
1966
+ ];
1967
+ var TupleField = ({ binding, type, readonly, label, getStatus, getValue, onValueChange, onBlur }) => {
1968
+ const { status, error } = getStatus();
1969
+ const values = getValue() ?? {};
1970
+ return /* @__PURE__ */ React16.createElement(Input11.Root, {
1971
+ validationValence: status
1972
+ }, /* @__PURE__ */ React16.createElement(FormFieldLabel, {
1973
+ error,
1974
+ readonly,
1975
+ label
1976
+ }), /* @__PURE__ */ React16.createElement("div", {
1977
+ className: mx3("grid gap-form-gap", gridCols[binding.length - 1])
1978
+ }, binding.map((prop) => /* @__PURE__ */ React16.createElement(Input11.TextInput, {
1979
+ key: prop,
1980
+ type: "number",
1981
+ disabled: !!readonly,
1982
+ value: values[prop],
1983
+ onChange: (event) => {
1984
+ onValueChange(type, {
1985
+ ...values,
1986
+ [prop]: safeParseFloat3(event.target.value, 0)
1987
+ });
1988
+ },
1989
+ onBlur
1990
+ }))));
1968
1991
  };
1969
1992
 
1970
1993
  // src/components/FieldEditor/FieldEditor.tsx
1971
- var __dxlog_file4 = "/__w/dxos/dxos/packages/ui/react-ui-form/src/components/FieldEditor/FieldEditor.tsx";
1972
- var FieldEditor = ({ projection, field, registry, onSave, onCancel, outerSpacing }) => {
1973
- var _effect = _useSignals14();
1974
- try {
1975
- const { t } = useTranslation8(translationKey);
1976
- const [props, setProps] = useState5(projection.getFieldProjection(field.id).props);
1977
- useEffect8(() => setProps(projection.getFieldProjection(field.id).props), [
1978
- field,
1979
- projection
1980
- ]);
1981
- const [schemas, setSchemas] = useState5([]);
1982
- useEffect8(() => {
1983
- if (!registry) {
1984
- return;
1994
+ var __dxlog_file2 = "/__w/dxos/dxos/packages/ui/react-ui-form/src/components/FieldEditor/FieldEditor.tsx";
1995
+ var FieldEditor = ({ readonly, projection, field, registry, view, onSave, onCancel }) => {
1996
+ const { t } = useTranslation8(translationKey);
1997
+ const [props, setProps] = useState5(projection.getFieldProjection(field.id).props);
1998
+ useEffect7(() => setProps(projection.getFieldProjection(field.id).props), [
1999
+ field,
2000
+ projection
2001
+ ]);
2002
+ const [schemas, setSchemas] = useState5([]);
2003
+ useAsyncEffect(async () => {
2004
+ if (!registry) {
2005
+ return;
2006
+ }
2007
+ const subscription = registry.query().subscribe((query) => setSchemas(query.results), {
2008
+ fire: true
2009
+ });
2010
+ const schemas2 = await registry.query().run();
2011
+ setSchemas(schemas2);
2012
+ return () => subscription?.();
2013
+ }, [
2014
+ registry
2015
+ ]);
2016
+ const [referenceSchema, setReferenceSchema] = useState5();
2017
+ useEffect7(() => {
2018
+ setReferenceSchema(schemas.find((schema) => schema.typename === props?.referenceSchema));
2019
+ }, [
2020
+ schemas,
2021
+ props?.referenceSchema
2022
+ ]);
2023
+ const [{ fieldSchema }, setFieldSchema] = useState5({
2024
+ fieldSchema: getFormatSchema(props?.format)
2025
+ });
2026
+ const fieldMap = useMemo7(() => ({
2027
+ ["format"]: (props2) => /* @__PURE__ */ React17.createElement(SelectField, {
2028
+ ...props2,
2029
+ options: FormatEnums.filter((value3) => value3 !== Format4.TypeFormat.None).map((value3) => ({
2030
+ value: value3,
2031
+ label: t(`format.${value3}.label`)
2032
+ }))
2033
+ }),
2034
+ ["referenceSchema"]: (props2) => /* @__PURE__ */ React17.createElement(SelectField, {
2035
+ ...props2,
2036
+ options: schemas.map((schema) => ({
2037
+ value: schema.typename
2038
+ }))
2039
+ }),
2040
+ ["referencePath"]: (props2) => /* @__PURE__ */ React17.createElement(SelectField, {
2041
+ ...props2,
2042
+ options: referenceSchema ? getFormProperties(referenceSchema.ast).sort((a, b) => a.name.toString().localeCompare(b.name.toString())).map((p) => ({
2043
+ value: p.name.toString()
2044
+ })) : []
2045
+ }),
2046
+ ["options"]: (props2) => /* @__PURE__ */ React17.createElement(SelectOptionField, props2)
2047
+ }), [
2048
+ t,
2049
+ schemas,
2050
+ referenceSchema
2051
+ ]);
2052
+ const propIsNotType = useCallback14((props2) => props2.filter((prop) => prop.name !== "type"), []);
2053
+ const handleValuesChanged = useCallback14((_props) => {
2054
+ setFieldSchema((prev) => {
2055
+ const fieldSchema2 = getFormatSchema(_props.format);
2056
+ if (prev.fieldSchema === fieldSchema2) {
2057
+ return prev;
1985
2058
  }
1986
- const subscription = registry.query().subscribe((query) => setSchemas(query.results), {
1987
- fire: true
1988
- });
1989
- const t2 = setTimeout(async () => {
1990
- const schemas2 = await registry.query().run();
1991
- setSchemas(schemas2);
1992
- });
1993
- return () => {
1994
- clearTimeout(t2);
1995
- subscription?.();
2059
+ return {
2060
+ fieldSchema: fieldSchema2
1996
2061
  };
1997
- }, [
1998
- registry
1999
- ]);
2000
- const [referenceSchema, setReferenceSchema] = useState5();
2001
- useEffect8(() => {
2002
- setReferenceSchema(schemas.find((schema) => schema.typename === props?.referenceSchema));
2003
- }, [
2004
- schemas,
2005
- props?.referenceSchema
2006
- ]);
2007
- const [{ fieldSchema }, setFieldSchema] = useState5({
2008
- fieldSchema: getFormatSchema(props?.format)
2009
2062
  });
2010
- const handleValuesChanged = useCallback9((_props) => {
2011
- setFieldSchema((prev) => {
2012
- const fieldSchema2 = getFormatSchema(_props.format);
2013
- if (prev.fieldSchema === fieldSchema2) {
2014
- return prev;
2063
+ setReferenceSchema((prev) => {
2064
+ if (_props.referenceSchema !== prev?.typename) {
2065
+ const newSchema = schemas.find((schema) => schema.typename === _props.referenceSchema);
2066
+ if (newSchema) {
2067
+ return newSchema;
2015
2068
  }
2069
+ }
2070
+ return prev;
2071
+ });
2072
+ setProps((props2) => {
2073
+ const type = formatToType[_props.format];
2074
+ const additionalProps = formatToAdditionalPropertyAttributes[_props.format];
2075
+ if (props2.type !== type) {
2016
2076
  return {
2017
- fieldSchema: fieldSchema2
2077
+ ...props2,
2078
+ ..._props,
2079
+ ...additionalProps,
2080
+ type
2018
2081
  };
2019
- });
2020
- setReferenceSchema((prev) => {
2021
- if (_props.referenceSchema !== prev?.typename) {
2022
- const newSchema = schemas.find((schema) => schema.typename === _props.referenceSchema);
2023
- if (newSchema) {
2024
- return newSchema;
2025
- }
2026
- }
2027
- return prev;
2028
- });
2029
- setProps((props2) => {
2030
- const type = formatToType[_props.format];
2031
- if (props2.type !== type) {
2032
- return {
2033
- ...props2,
2034
- ..._props,
2035
- type
2036
- };
2082
+ }
2083
+ return _props;
2084
+ });
2085
+ }, [
2086
+ schemas,
2087
+ props.format,
2088
+ props.referenceSchema
2089
+ ]);
2090
+ const handleValidate = useCallback14(({ property }) => {
2091
+ if (property && projection.getFields().find((f) => f.path === property && f.path !== field.path)) {
2092
+ return [
2093
+ {
2094
+ path: "property",
2095
+ message: `property is not unique: '${property}'`
2037
2096
  }
2038
- return _props;
2097
+ ];
2098
+ }
2099
+ }, [
2100
+ projection.getFields(),
2101
+ field
2102
+ ]);
2103
+ const handleSave = useCallback14((props2) => {
2104
+ if (view) {
2105
+ Obj2.change(view, () => {
2106
+ projection.setFieldProjection({
2107
+ field,
2108
+ props: props2
2109
+ });
2039
2110
  });
2040
- }, [
2041
- schemas,
2042
- props.format,
2043
- props.referenceSchema
2044
- ]);
2045
- const handleValidate = useCallback9(({ property }) => {
2046
- if (property && projection.fields.find((f) => f.path === property && f.path !== field.path)) {
2047
- return [
2048
- {
2049
- path: "property",
2050
- message: `property is not unique: '${property}'`
2051
- }
2052
- ];
2053
- }
2054
- }, [
2055
- projection.fields,
2056
- field
2057
- ]);
2058
- const handleSave = useCallback9((props2) => {
2111
+ } else {
2059
2112
  projection.setFieldProjection({
2060
2113
  field,
2061
2114
  props: props2
2062
2115
  });
2063
- onSave();
2064
- }, [
2065
- projection,
2066
- field,
2067
- onSave
2068
- ]);
2069
- const handleCancel = useCallback9(() => {
2070
- requestAnimationFrame(() => onCancel?.());
2071
- onSave();
2072
- }, [
2073
- onSave
2074
- ]);
2075
- const custom = useMemo7(() => ({
2076
- ["format"]: (props2) => /* @__PURE__ */ React14.createElement(SelectInput, {
2077
- ...props2,
2078
- options: FormatEnums.filter((value) => value !== FormatEnum5.None).map((value) => ({
2079
- value,
2080
- label: t(`format ${value}`)
2081
- }))
2082
- }),
2083
- ["referenceSchema"]: (props2) => /* @__PURE__ */ React14.createElement(SelectInput, {
2084
- ...props2,
2085
- options: schemas.map((schema) => ({
2086
- value: schema.typename
2087
- }))
2088
- }),
2089
- ["referencePath"]: (props2) => /* @__PURE__ */ React14.createElement(SelectInput, {
2090
- ...props2,
2091
- options: referenceSchema ? getSchemaProperties3(referenceSchema.ast).sort(sortProperties).map((p) => ({
2092
- value: p.name
2093
- })) : []
2094
- }),
2095
- ["options"]: (props2) => /* @__PURE__ */ React14.createElement(SelectOptionInput, props2)
2096
- }), [
2097
- t,
2098
- schemas,
2099
- referenceSchema
2100
- ]);
2101
- const propIsNotType = useCallback9((props2) => props2.filter((p) => p.name !== "type"), []);
2102
- if (!fieldSchema) {
2103
- log3.warn("invalid format", {
2104
- props
2105
- }, {
2106
- F: __dxlog_file4,
2107
- L: 173,
2108
- S: void 0,
2109
- C: (f, a) => f(...a)
2110
- });
2111
- return null;
2112
2116
  }
2113
- return /* @__PURE__ */ React14.createElement(Form, {
2114
- key: field.id,
2115
- autoFocus: true,
2116
- values: props,
2117
- schema: fieldSchema,
2118
- filter: propIsNotType,
2119
- sort: [
2120
- "property",
2121
- "format"
2122
- ],
2123
- onValuesChanged: handleValuesChanged,
2124
- onValidate: handleValidate,
2125
- onSave: handleSave,
2126
- onCancel: handleCancel,
2127
- Custom: custom,
2128
- outerSpacing
2117
+ onSave();
2118
+ }, [
2119
+ projection,
2120
+ field,
2121
+ view,
2122
+ onSave
2123
+ ]);
2124
+ const handleCancel = useCallback14(() => {
2125
+ onSave();
2126
+ requestAnimationFrame(() => onCancel?.());
2127
+ }, [
2128
+ onSave
2129
+ ]);
2130
+ if (!fieldSchema) {
2131
+ log2.warn("invalid format", {
2132
+ props
2133
+ }, {
2134
+ F: __dxlog_file2,
2135
+ L: 172,
2136
+ S: void 0,
2137
+ C: (f, a) => f(...a)
2129
2138
  });
2130
- } finally {
2131
- _effect.f();
2139
+ return null;
2132
2140
  }
2141
+ return /* @__PURE__ */ React17.createElement(Form.Root, {
2142
+ key: field.id,
2143
+ fieldMap,
2144
+ autoFocus: true,
2145
+ readonly,
2146
+ schema: fieldSchema,
2147
+ values: props,
2148
+ exclude: propIsNotType,
2149
+ sort: [
2150
+ "property",
2151
+ "format"
2152
+ ],
2153
+ onValuesChanged: handleValuesChanged,
2154
+ onValidate: handleValidate,
2155
+ onSave: handleSave,
2156
+ onCancel: handleCancel
2157
+ }, /* @__PURE__ */ React17.createElement(Form.Content, null, /* @__PURE__ */ React17.createElement(Form.FieldSet, null), /* @__PURE__ */ React17.createElement(Form.Actions, null)));
2158
+ };
2159
+
2160
+ // src/components/Settings/Settings.tsx
2161
+ import React18 from "react";
2162
+ import { Input as Input12, ScrollArea as ScrollArea2, toLocalizedString, useTranslation as useTranslation9 } from "@dxos/react-ui";
2163
+ import { composable as composable2, composableProps as composableProps2, mx as mx4 } from "@dxos/ui-theme";
2164
+ var SETTINGS_ROOT_NAME = "Settings.Root";
2165
+ var SETTINGS_VIEWPORT_NAME = "Settings.Viewport";
2166
+ var SETTINGS_SECTION_NAME = "Settings.Section";
2167
+ var SETTINGS_PANEL_NAME = "Settings.Panel";
2168
+ var SETTINGS_ITEM_NAME = "Settings.Item";
2169
+ var SettingsRoot = ({ children, classNames }) => {
2170
+ return /* @__PURE__ */ React18.createElement("div", {
2171
+ className: mx4("flex flex-col gap-2", classNames)
2172
+ }, children);
2173
+ };
2174
+ SettingsRoot.displayName = SETTINGS_ROOT_NAME;
2175
+ var SettingsViewport = composable2(({ children, ...props }, forwardedRef) => {
2176
+ return /* @__PURE__ */ React18.createElement(ScrollArea2.Root, {
2177
+ ...composableProps2(props),
2178
+ orientation: "vertical",
2179
+ centered: true,
2180
+ thin: true,
2181
+ ref: forwardedRef
2182
+ }, /* @__PURE__ */ React18.createElement(ScrollArea2.Viewport, {
2183
+ classNames: "px-4 pointer-coarse:px-2"
2184
+ }, /* @__PURE__ */ React18.createElement("div", {
2185
+ role: "none",
2186
+ className: "dx-document flex flex-col gap-2 py-4"
2187
+ }, children)));
2188
+ });
2189
+ SettingsViewport.displayName = SETTINGS_VIEWPORT_NAME;
2190
+ var SettingsSection = ({ title, description, children }) => {
2191
+ const { t } = useTranslation9(translationKey);
2192
+ return /* @__PURE__ */ React18.createElement(React18.Fragment, null, /* @__PURE__ */ React18.createElement("h2", {
2193
+ className: "px-trim-md mt-trim-md text-xl"
2194
+ }, toLocalizedString(title, t)), description && /* @__PURE__ */ React18.createElement("p", {
2195
+ className: "px-trim-md text-description"
2196
+ }, toLocalizedString(description, t)), /* @__PURE__ */ React18.createElement("div", {
2197
+ className: "w-full pt-trim-md space-y-trim-md"
2198
+ }, children));
2199
+ };
2200
+ SettingsSection.displayName = SETTINGS_SECTION_NAME;
2201
+ var SettingsPanel = ({ classNames, children }) => {
2202
+ return /* @__PURE__ */ React18.createElement("div", {
2203
+ role: "none",
2204
+ className: mx4("flex flex-col gap-3 p-trim-md border border-separator rounded-sm", classNames)
2205
+ }, children);
2206
+ };
2207
+ SettingsPanel.displayName = SETTINGS_PANEL_NAME;
2208
+ var SettingsItem = ({ title, description = "", children }) => {
2209
+ const { t } = useTranslation9(translationKey);
2210
+ return /* @__PURE__ */ React18.createElement(Input12.Root, null, /* @__PURE__ */ React18.createElement(SettingsPanel, {
2211
+ classNames: "grid grid-cols-1 md:grid-cols-[1fr_1fr] gap-x-trim-lg gap-y-0"
2212
+ }, /* @__PURE__ */ React18.createElement(Input12.Label, {
2213
+ classNames: "pb-trim-md text-base-surface-text text-lg md:col-span-2"
2214
+ }, toLocalizedString(title, t)), /* @__PURE__ */ React18.createElement(Input12.DescriptionAndValidation, null, /* @__PURE__ */ React18.createElement(Input12.Description, {
2215
+ classNames: "text-base text-description"
2216
+ }, toLocalizedString(description, t))), /* @__PURE__ */ React18.createElement("div", {
2217
+ role: "none",
2218
+ className: "text-end py-1"
2219
+ }, children)));
2220
+ };
2221
+ SettingsItem.displayName = SETTINGS_ITEM_NAME;
2222
+ var Settings = {
2223
+ Root: SettingsRoot,
2224
+ Viewport: SettingsViewport,
2225
+ Section: SettingsSection,
2226
+ Panel: SettingsPanel,
2227
+ Item: SettingsItem
2133
2228
  };
2134
2229
 
2135
2230
  // src/components/ViewEditor/ViewEditor.tsx
2136
- import { useSignals as _useSignals15 } from "@preact-signals/safe-react/tracking";
2137
- import { Schema as Schema2 } from "effect";
2138
- import React15, { useCallback as useCallback10, useMemo as useMemo8, useState as useState6 } from "react";
2139
- import { EchoSchema, Format, isMutable, toJsonSchema } from "@dxos/echo-schema";
2140
- import { invariant as invariant3 } from "@dxos/invariant";
2141
- import { Callout, IconButton as IconButton4, useTranslation as useTranslation9 } from "@dxos/react-ui";
2231
+ import { RegistryContext } from "@effect-atom/atom-react";
2232
+ import * as Array2 from "effect/Array";
2233
+ import * as Match2 from "effect/Match";
2234
+ import * as Option4 from "effect/Option";
2235
+ import * as Schema3 from "effect/Schema";
2236
+ import React19, { forwardRef as forwardRef2, useCallback as useCallback15, useContext, useImperativeHandle, useMemo as useMemo8, useState as useState6 } from "react";
2237
+ import { Entity as Entity2, Feed, Filter as Filter2, Format as Format5, Obj as Obj3, Query, QueryAST, Ref as Ref3 } from "@dxos/echo";
2238
+ import { View } from "@dxos/echo";
2239
+ import { EchoSchema, isMutable, toJsonSchema } from "@dxos/echo/internal";
2240
+ import { invariant } from "@dxos/invariant";
2241
+ import { useObject, useQuery as useQuery2 } from "@dxos/react-client/echo";
2242
+ import { IconButton as IconButton4, Input as Input13, Message, useTranslation as useTranslation10 } from "@dxos/react-ui";
2243
+ import { QueryForm } from "@dxos/react-ui-components";
2142
2244
  import { List as List2 } from "@dxos/react-ui-list";
2143
- import { cardSpacing as cardSpacing3 } from "@dxos/react-ui-stack";
2144
- import { ghostHover, inputTextLabel, mx as mx9 } from "@dxos/react-ui-theme";
2145
- import { FieldSchema, VIEW_FIELD_LIMIT, ProjectionModel } from "@dxos/schema";
2146
- var __dxlog_file5 = "/__w/dxos/dxos/packages/ui/react-ui-form/src/components/ViewEditor/ViewEditor.tsx";
2147
- var grid = "grid grid-cols-[32px_1fr_32px_32px] min-bs-[2.5rem]";
2148
- var ViewMetaSchema = Schema2.Struct({
2149
- typename: Format.URL.annotations({
2150
- title: "Typename"
2151
- })
2152
- }).pipe(Schema2.mutable);
2153
- var ViewEditor = ({ classNames, schema, view, registry, readonly: _readonly, showHeading = false, onTypenameChanged, onDelete, outerSpacing = true }) => {
2154
- var _effect = _useSignals15();
2155
- try {
2156
- const { t } = useTranslation9(translationKey);
2157
- const projection = useMemo8(() => {
2158
- const jsonSchema = schema instanceof EchoSchema ? schema.jsonSchema : toJsonSchema(schema);
2159
- return new ProjectionModel(jsonSchema, view.projection);
2160
- }, [
2161
- schema,
2162
- view.projection
2163
- ]);
2164
- const [field, setField] = useState6();
2165
- const readonly = _readonly || !isMutable(schema);
2166
- const viewValues = useMemo8(() => {
2167
- return {
2168
- // TODO(burdon): Need to warn user of possible consequences of editing.
2169
- // TODO(burdon): Settings should have domain name owned by user.
2170
- typename: view.query.typename
2171
- };
2172
- }, [
2173
- view.query.typename
2174
- ]);
2175
- const handleSelect = useCallback10((field2) => {
2176
- if (readonly) {
2177
- return;
2178
- }
2179
- setField((f) => f === field2 ? void 0 : field2);
2180
- }, [
2181
- readonly
2182
- ]);
2183
- const handleAdd = useCallback10(() => {
2184
- invariant3(!readonly, void 0, {
2185
- F: __dxlog_file5,
2186
- L: 88,
2187
- S: void 0,
2188
- A: [
2189
- "!readonly",
2190
- ""
2191
- ]
2192
- });
2193
- const field2 = projection.createFieldProjection();
2194
- setField(field2);
2195
- }, [
2196
- schema,
2197
- projection,
2198
- readonly
2199
- ]);
2200
- const handleUpdate = useCallback10(({ typename }) => {
2201
- invariant3(!readonly, void 0, {
2202
- F: __dxlog_file5,
2203
- L: 95,
2204
- S: void 0,
2205
- A: [
2206
- "!readonly",
2207
- ""
2208
- ]
2209
- });
2210
- requestAnimationFrame(() => {
2211
- if (view.query.typename !== typename && !readonly) {
2212
- onTypenameChanged?.(typename);
2213
- }
2214
- });
2215
- }, [
2216
- view.query.typename,
2217
- onTypenameChanged,
2218
- readonly
2219
- ]);
2220
- const handleDelete = useCallback10((fieldId) => {
2221
- invariant3(!readonly, void 0, {
2222
- F: __dxlog_file5,
2223
- L: 107,
2224
- S: void 0,
2225
- A: [
2226
- "!readonly",
2227
- ""
2228
- ]
2229
- });
2230
- if (fieldId === field?.id) {
2231
- setField(void 0);
2245
+ import { ParentLabelAnnotation, ProjectionModel, VIEW_FIELD_LIMIT, createEchoChangeCallback, getTypenameFromQuery } from "@dxos/schema";
2246
+ import { mx as mx5, osTranslations as osTranslations2, subtleHover as subtleHover2 } from "@dxos/ui-theme";
2247
+ var __dxlog_file3 = "/__w/dxos/dxos/packages/ui/react-ui-form/src/components/ViewEditor/ViewEditor.tsx";
2248
+ var ViewEditor = /* @__PURE__ */ forwardRef2(({ classNames, schema, view, mode = "schema", registry, db, readonly, showHeading = false, types, tags, onQueryChanged, onDelete }, forwardedRef) => {
2249
+ const atomRegistry = useContext(RegistryContext);
2250
+ const schemaReadonly = !isMutable(schema);
2251
+ const { t } = useTranslation10(translationKey);
2252
+ const projectionModel = useMemo8(() => {
2253
+ const jsonSchema = schema instanceof EchoSchema ? schema.jsonSchema : toJsonSchema(schema);
2254
+ const change = createEchoChangeCallback(view, schema instanceof EchoSchema ? schema : void 0);
2255
+ const model = new ProjectionModel({
2256
+ registry: atomRegistry,
2257
+ view,
2258
+ baseSchema: jsonSchema,
2259
+ change
2260
+ });
2261
+ return model;
2262
+ }, [
2263
+ atomRegistry,
2264
+ schema,
2265
+ view
2266
+ ]);
2267
+ useImperativeHandle(forwardedRef, () => projectionModel, [
2268
+ projectionModel
2269
+ ]);
2270
+ const queueTarget = Match2.value(view.query.ast).pipe(Match2.when({
2271
+ type: "from"
2272
+ }, ({ from }) => {
2273
+ if (from._tag !== "scope") {
2274
+ return void 0;
2275
+ }
2276
+ return Option4.fromNullable(from.scope.queues).pipe(Option4.flatMap((queues) => Array2.head(queues)), Option4.map(String), Option4.getOrUndefined);
2277
+ }), Match2.orElse(() => void 0));
2278
+ const feeds = useQuery2(db, Filter2.type(Feed.Feed));
2279
+ const targetRef = useMemo8(() => {
2280
+ if (!queueTarget) {
2281
+ return void 0;
2282
+ }
2283
+ const feed = feeds.find((feed2) => Feed.getQueueDxn(feed2)?.toString() === queueTarget);
2284
+ return feed ? Ref3.fromDXN(Entity2.getDXN(feed)) : void 0;
2285
+ }, [
2286
+ queueTarget,
2287
+ feeds
2288
+ ]);
2289
+ const viewSchema = useMemo8(() => {
2290
+ const base = Schema3.Struct({
2291
+ query: mode === "schema" ? Format5.URL.annotations({
2292
+ title: "Record type"
2293
+ }) : QueryAST.Query.annotations({
2294
+ title: "Query"
2295
+ })
2296
+ });
2297
+ if (mode === "tag") {
2298
+ return Schema3.Struct({
2299
+ ...base.fields,
2300
+ // TODO(wittjosiah): Replace Type.Feed with Dataset.Dataset when Ref.Ref supports unions.
2301
+ target: Ref3.Ref(Feed.Feed).pipe(Schema3.annotations({
2302
+ title: "Target Feed"
2303
+ }), ParentLabelAnnotation.set(true), Schema3.optional)
2304
+ }).pipe(Schema3.mutable);
2305
+ }
2306
+ return base.pipe(Schema3.mutable);
2307
+ }, [
2308
+ mode
2309
+ ]);
2310
+ const viewValues = useMemo8(() => ({
2311
+ query: mode === "schema" ? getTypenameFromQuery(view.query.ast) : view.query.ast,
2312
+ target: targetRef
2313
+ }), [
2314
+ mode,
2315
+ view.query.ast,
2316
+ targetRef
2317
+ ]);
2318
+ const fieldMap = useMemo8(() => mode === "tag" ? customFields({
2319
+ types,
2320
+ tags
2321
+ }) : void 0, [
2322
+ mode,
2323
+ types,
2324
+ tags
2325
+ ]);
2326
+ const handleUpdate = useCallback15((values) => {
2327
+ const targetValue = values.target;
2328
+ let queueDxn;
2329
+ if (Ref3.isRef(targetValue)) {
2330
+ const feedDxn = targetValue.dxn.toString();
2331
+ const feed = feeds.find((feed2) => Obj3.getDXN(feed2).toString() === feedDxn);
2332
+ if (feed) {
2333
+ queueDxn = Feed.getQueueDxn(feed)?.toString();
2232
2334
  }
2233
- onDelete?.(fieldId);
2234
- }, [
2235
- field,
2236
- onDelete,
2237
- readonly
2238
- ]);
2239
- const handleMove = useCallback10((fromIndex, toIndex) => {
2240
- invariant3(!readonly, void 0, {
2241
- F: __dxlog_file5,
2242
- L: 119,
2243
- S: void 0,
2244
- A: [
2245
- "!readonly",
2246
- ""
2247
- ]
2248
- });
2335
+ }
2336
+ const query = mode === "schema" ? Query.select(Filter2.typename(values.query)).ast : JSON.parse(JSON.stringify(values.query));
2337
+ onQueryChanged?.(query, queueDxn);
2338
+ }, [
2339
+ onQueryChanged,
2340
+ mode,
2341
+ feeds
2342
+ ]);
2343
+ const handleDelete = useCallback15((fieldId) => {
2344
+ invariant(!readonly, void 0, {
2345
+ F: __dxlog_file3,
2346
+ L: 185,
2347
+ S: void 0,
2348
+ A: [
2349
+ "!readonly",
2350
+ ""
2351
+ ]
2352
+ });
2353
+ onDelete?.(fieldId);
2354
+ }, [
2355
+ onDelete,
2356
+ readonly
2357
+ ]);
2358
+ return /* @__PURE__ */ React19.createElement("div", {
2359
+ role: "none",
2360
+ className: mx5(classNames)
2361
+ }, schemaReadonly && !readonly && /* @__PURE__ */ React19.createElement(Message.Root, {
2362
+ valence: "info",
2363
+ classNames: "my-form-padding"
2364
+ }, /* @__PURE__ */ React19.createElement(Message.Title, null, t("system-schema.description"))), /* @__PURE__ */ React19.createElement(Form.Root, {
2365
+ schema: viewSchema,
2366
+ values: viewValues,
2367
+ fieldMap,
2368
+ db,
2369
+ onValuesChanged: handleUpdate
2370
+ }, /* @__PURE__ */ React19.createElement(Form.FieldSet, null), /* @__PURE__ */ React19.createElement(FormFieldLabel, {
2371
+ label: t("fields.label"),
2372
+ asChild: true
2373
+ }), /* @__PURE__ */ React19.createElement(FieldList, {
2374
+ schema,
2375
+ view,
2376
+ registry,
2377
+ readonly,
2378
+ showHeading,
2379
+ onDelete: handleDelete
2380
+ })));
2381
+ });
2382
+ var FieldList = ({ schema, view, registry, readonly, showHeading = false, onDelete }) => {
2383
+ const atomRegistry = useContext(RegistryContext);
2384
+ const schemaReadonly = !isMutable(schema);
2385
+ const { t } = useTranslation10(translationKey);
2386
+ const [viewSnapshot] = useObject(view);
2387
+ const projectionModel = useMemo8(() => {
2388
+ const jsonSchema = schema instanceof EchoSchema ? schema.jsonSchema : toJsonSchema(schema);
2389
+ const change = createEchoChangeCallback(view, schema instanceof EchoSchema ? schema : void 0);
2390
+ const model = new ProjectionModel({
2391
+ registry: atomRegistry,
2392
+ view,
2393
+ baseSchema: jsonSchema,
2394
+ change
2395
+ });
2396
+ return model;
2397
+ }, [
2398
+ atomRegistry,
2399
+ schema,
2400
+ view
2401
+ ]);
2402
+ const [expandedField, setExpandedField] = useState6();
2403
+ const handleAdd = useCallback15(() => {
2404
+ invariant(!readonly, void 0, {
2405
+ F: __dxlog_file3,
2406
+ L: 250,
2407
+ S: void 0,
2408
+ A: [
2409
+ "!readonly",
2410
+ ""
2411
+ ]
2412
+ });
2413
+ const field = projectionModel.createFieldProjection();
2414
+ setExpandedField(field.id);
2415
+ }, [
2416
+ projectionModel,
2417
+ readonly
2418
+ ]);
2419
+ const handleToggleField = useCallback15((field) => {
2420
+ setExpandedField((prevExpandedFieldId) => prevExpandedFieldId === field.id ? void 0 : field.id);
2421
+ }, [
2422
+ readonly
2423
+ ]);
2424
+ const handleDelete = useCallback15((fieldId) => {
2425
+ invariant(!readonly, void 0, {
2426
+ F: __dxlog_file3,
2427
+ L: 264,
2428
+ S: void 0,
2429
+ A: [
2430
+ "!readonly",
2431
+ ""
2432
+ ]
2433
+ });
2434
+ if (fieldId === expandedField) {
2435
+ setExpandedField(void 0);
2436
+ }
2437
+ onDelete?.(fieldId);
2438
+ }, [
2439
+ expandedField,
2440
+ onDelete,
2441
+ readonly
2442
+ ]);
2443
+ const handleMove = useCallback15((fromIndex, toIndex) => {
2444
+ invariant(!readonly, void 0, {
2445
+ F: __dxlog_file3,
2446
+ L: 276,
2447
+ S: void 0,
2448
+ A: [
2449
+ "!readonly",
2450
+ ""
2451
+ ]
2452
+ });
2453
+ Obj3.change(view, (obj) => {
2249
2454
  const fields = [
2250
- ...view.projection.fields
2455
+ ...obj.projection.fields
2251
2456
  ];
2252
2457
  const [moved] = fields.splice(fromIndex, 1);
2253
2458
  fields.splice(toIndex, 0, moved);
2254
- view.projection.fields = fields;
2255
- }, [
2256
- view.projection.fields,
2257
- readonly
2258
- ]);
2259
- const handleClose = useCallback10(() => setField(void 0), []);
2260
- const hiddenProperties = projection.getHiddenProperties();
2261
- const handleHide = useCallback10((fieldId) => {
2262
- setField(void 0);
2263
- projection.hideFieldProjection(fieldId);
2264
- }, [
2265
- projection
2266
- ]);
2267
- const handleShow = useCallback10((property) => {
2268
- setField(void 0);
2269
- projection.showFieldProjection(property);
2270
- }, [
2271
- projection
2272
- ]);
2273
- return /* @__PURE__ */ React15.createElement("div", {
2274
- role: "none",
2275
- className: mx9(classNames)
2276
- }, readonly && /* @__PURE__ */ React15.createElement("div", {
2459
+ obj.projection.fields = fields;
2460
+ });
2461
+ }, [
2462
+ view,
2463
+ readonly
2464
+ ]);
2465
+ const handleClose = useCallback15(() => setExpandedField(void 0), []);
2466
+ const handleHide = useCallback15((fieldId) => {
2467
+ setExpandedField(void 0);
2468
+ projectionModel.hideFieldProjection(fieldId);
2469
+ }, [
2470
+ projectionModel
2471
+ ]);
2472
+ const handleShow = useCallback15((property) => {
2473
+ setExpandedField(void 0);
2474
+ projectionModel.showFieldProjection(property);
2475
+ }, [
2476
+ projectionModel
2477
+ ]);
2478
+ if (!viewSnapshot) {
2479
+ return null;
2480
+ }
2481
+ return /* @__PURE__ */ React19.createElement(List2.Root, {
2482
+ items: viewSnapshot.projection.fields,
2483
+ isItem: Schema3.is(View.FieldSchema),
2484
+ getId: (field) => field.id,
2485
+ onMove: readonly ? void 0 : handleMove,
2486
+ readonly
2487
+ }, ({ items: fields }) => /* @__PURE__ */ React19.createElement(React19.Fragment, null, showHeading && /* @__PURE__ */ React19.createElement("h3", {
2488
+ className: "text-sm"
2489
+ }, t("field-path.label")), /* @__PURE__ */ React19.createElement("div", {
2490
+ role: "list",
2491
+ className: "grid grid-cols-[min-content_1fr_min-content_min-content_min-content]"
2492
+ }, fields?.map((field) => {
2493
+ const hidden = field.visible === false;
2494
+ return /* @__PURE__ */ React19.createElement(List2.Item, {
2495
+ key: field.id,
2496
+ item: field,
2497
+ classNames: "grid grid-cols-subgrid col-span-5",
2498
+ "aria-expanded": expandedField === field.id
2499
+ }, /* @__PURE__ */ React19.createElement("div", {
2277
2500
  role: "none",
2278
- className: mx9("is-full", outerSpacing && "plb-cardSpacingBlock pli-cardSpacingInline")
2279
- }, /* @__PURE__ */ React15.createElement(Callout.Root, {
2280
- valence: "info"
2281
- }, /* @__PURE__ */ React15.createElement(Callout.Title, null, t("system schema description")))), /* @__PURE__ */ React15.createElement(Form, {
2282
- autoSave: true,
2283
- schema: ViewMetaSchema,
2284
- values: viewValues,
2285
- readonly,
2286
- onSave: handleUpdate,
2287
- outerSpacing
2288
- }), /* @__PURE__ */ React15.createElement("div", {
2501
+ className: mx5(subtleHover2, "grid grid-cols-subgrid col-span-5", "rounded-xs cursor-pointer min-h-10")
2502
+ }, /* @__PURE__ */ React19.createElement(List2.ItemDragHandle, {
2503
+ disabled: readonly || schemaReadonly
2504
+ }), /* @__PURE__ */ React19.createElement(List2.ItemTitle, {
2505
+ classNames: hidden && "text-subdued",
2506
+ onClick: () => handleToggleField(field)
2507
+ }, field.path), /* @__PURE__ */ React19.createElement(List2.ItemIconButton, {
2508
+ label: t(hidden ? "show field label" : "hide field label"),
2509
+ "data-testid": hidden ? "show-field-button" : "hide-field-button",
2510
+ icon: hidden ? "ph--eye-closed--regular" : "ph--eye--regular",
2511
+ autoHide: false,
2512
+ disabled: readonly || !hidden && projectionModel.getFields().length <= 1,
2513
+ onClick: () => hidden ? handleShow(field.path) : handleHide(field.id)
2514
+ }), !readonly && /* @__PURE__ */ React19.createElement(React19.Fragment, null, /* @__PURE__ */ React19.createElement(List2.ItemDeleteButton, {
2515
+ label: t("delete-field.label"),
2516
+ autoHide: false,
2517
+ disabled: readonly || schemaReadonly || viewSnapshot.projection.fields.length <= 1,
2518
+ onClick: () => handleDelete(field.id),
2519
+ "data-testid": "field.delete"
2520
+ }), /* @__PURE__ */ React19.createElement(List2.ItemIconButton, {
2521
+ iconOnly: true,
2522
+ variant: "ghost",
2523
+ label: t("toggle-expand.label", {
2524
+ ns: osTranslations2
2525
+ }),
2526
+ icon: expandedField === field.id ? "ph--caret-down--regular" : "ph--caret-right--regular",
2527
+ onClick: () => handleToggleField(field),
2528
+ "data-testid": "field.toggle"
2529
+ }))), expandedField === field.id && !readonly && /* @__PURE__ */ React19.createElement("div", {
2289
2530
  role: "none",
2290
- className: outerSpacing ? cardSpacing3 : "mlb-cardSpacingBlock"
2291
- }, /* @__PURE__ */ React15.createElement("label", {
2292
- className: mx9(inputTextLabel)
2293
- }, t("fields label")), /* @__PURE__ */ React15.createElement(List2.Root, {
2294
- items: view.projection.fields,
2295
- isItem: Schema2.is(FieldSchema),
2296
- getId: (field2) => field2.id,
2297
- readonly,
2298
- onMove: readonly ? void 0 : handleMove
2299
- }, ({ items: fields }) => /* @__PURE__ */ React15.createElement(React15.Fragment, null, showHeading && /* @__PURE__ */ React15.createElement("div", {
2300
- role: "heading",
2301
- className: grid
2302
- }, /* @__PURE__ */ React15.createElement("div", null), /* @__PURE__ */ React15.createElement("div", {
2303
- className: "flex items-center text-sm"
2304
- }, t("field path label"))), /* @__PURE__ */ React15.createElement("div", {
2305
- role: "list",
2306
- className: "flex flex-col is-full"
2307
- }, fields?.map((field2) => /* @__PURE__ */ React15.createElement(List2.Item, {
2308
- key: field2.id,
2309
- item: field2,
2310
- classNames: mx9(grid, ghostHover, "overflow-hidden", !readonly && "cursor-pointer")
2311
- }, /* @__PURE__ */ React15.createElement(List2.ItemDragHandle, null), /* @__PURE__ */ React15.createElement(List2.ItemTitle, {
2312
- onClick: () => handleSelect(field2)
2313
- }, field2.path), /* @__PURE__ */ React15.createElement(List2.ItemButton, {
2314
- "data-testid": "hide-field-button",
2315
- icon: "ph--eye-slash--regular",
2316
- // TDOO(burdon): Is this the correct test?
2317
- disabled: view.projection.fields.length <= 1,
2318
- onClick: () => handleHide(field2.id)
2319
- }), !readonly && /* @__PURE__ */ React15.createElement(List2.ItemDeleteButton, {
2320
- disabled: view.projection.fields.length <= 1,
2321
- onClick: () => handleDelete(field2.id)
2322
- })))))), hiddenProperties.length > 0 && /* @__PURE__ */ React15.createElement(React15.Fragment, null, /* @__PURE__ */ React15.createElement("label", {
2323
- className: mx9(inputTextLabel)
2324
- }, t("hidden fields label")), /* @__PURE__ */ React15.createElement(List2.Root, {
2325
- items: hiddenProperties,
2326
- isItem: (item) => typeof item === "string",
2327
- getId: (property) => property
2328
- }, ({ items: properties }) => /* @__PURE__ */ React15.createElement("div", {
2329
- role: "list",
2330
- className: "flex flex-col is-full"
2331
- }, properties?.map((property) => /* @__PURE__ */ React15.createElement(List2.Item, {
2332
- key: property,
2333
- item: property,
2334
- classNames: mx9(grid, ghostHover, !readonly && "cursor-pointer")
2335
- }, /* @__PURE__ */ React15.createElement(List2.ItemDragHandle, {
2336
- disabled: true
2337
- }), /* @__PURE__ */ React15.createElement(List2.ItemTitle, null, property), /* @__PURE__ */ React15.createElement(List2.ItemButton, {
2338
- icon: "ph--eye--regular",
2339
- onClick: () => handleShow(property),
2340
- "data-testid": "show-field-button"
2341
- }))))))), field && /* @__PURE__ */ React15.createElement(FieldEditor, {
2342
- key: field.id,
2343
- projection,
2344
- field,
2531
+ className: "col-span-5 mt-1 mb-1 border border-separator rounded-md"
2532
+ }, /* @__PURE__ */ React19.createElement(FieldEditor, {
2533
+ readonly: readonly || schemaReadonly,
2345
2534
  registry,
2535
+ projection: projectionModel,
2536
+ field,
2346
2537
  onSave: handleClose
2347
- }), !readonly && !field && /* @__PURE__ */ React15.createElement("div", {
2348
- role: "none",
2349
- className: outerSpacing ? cardSpacing3 : "mlb-cardSpacingBlock"
2350
- }, /* @__PURE__ */ React15.createElement(IconButton4, {
2351
- icon: "ph--plus--regular",
2352
- label: t("button add property"),
2353
- onClick: readonly ? void 0 : handleAdd,
2354
- // TODO(burdon): Show field limit in ux (not tooltip).
2355
- disabled: view.projection.fields.length >= VIEW_FIELD_LIMIT,
2356
- classNames: "flex is-full"
2357
2538
  })));
2358
- } finally {
2359
- _effect.f();
2360
- }
2539
+ })), !readonly && !expandedField && /* @__PURE__ */ React19.createElement("div", {
2540
+ role: "none",
2541
+ className: "my-form-padding"
2542
+ }, /* @__PURE__ */ React19.createElement(IconButton4, {
2543
+ icon: "ph--plus--regular",
2544
+ label: t("add-property-button.label"),
2545
+ onClick: handleAdd,
2546
+ disabled: viewSnapshot.projection.fields.length >= VIEW_FIELD_LIMIT,
2547
+ classNames: "w-full"
2548
+ }))));
2361
2549
  };
2550
+ var customFields = ({ types, tags }) => ({
2551
+ query: ({ type, readonly, label, getValue, onValueChange }) => {
2552
+ const handleChange = useCallback15((query) => onValueChange(type, query.ast), [
2553
+ onValueChange
2554
+ ]);
2555
+ return /* @__PURE__ */ React19.createElement(Input13.Root, null, /* @__PURE__ */ React19.createElement(FormFieldLabel, {
2556
+ readonly,
2557
+ label
2558
+ }), /* @__PURE__ */ React19.createElement(QueryForm, {
2559
+ initialQuery: getValue(),
2560
+ types,
2561
+ tags,
2562
+ onChange: handleChange
2563
+ }));
2564
+ }
2565
+ });
2362
2566
  export {
2363
- BooleanInput,
2364
- ControlFrame,
2365
- ControlFrameItem,
2366
- ControlGroup,
2367
- ControlGroupButton,
2368
- ControlItem,
2369
- ControlItemInput,
2370
- ControlPage,
2371
- ControlSection,
2372
- ControlSectionHeading,
2373
- DeprecatedFormContainer,
2374
- DeprecatedFormInput,
2567
+ ArrayField,
2568
+ BooleanField,
2375
2569
  FieldEditor,
2376
2570
  Form,
2377
- FormProvider,
2378
- GeoPointInput,
2379
- InputHeader,
2380
- MarkdownInput,
2381
- NumberInput,
2382
- SelectInput,
2383
- SelectOptionInput,
2384
- TextInput,
2385
- TupleInput,
2571
+ FormFieldErrorBoundary,
2572
+ FormFieldLabel,
2573
+ FormFieldWrapper,
2574
+ GeoPointField,
2575
+ MarkdownField,
2576
+ NumberField,
2577
+ ObjectPicker,
2578
+ RefField,
2579
+ SelectField,
2580
+ SelectOptionField,
2581
+ Settings,
2582
+ TextAreaField,
2583
+ TextField,
2584
+ TupleField,
2386
2585
  ViewEditor,
2387
2586
  cellClassesForFieldType,
2388
- controlItemClasses,
2389
- findArrayElementType,
2390
2587
  formatForDisplay,
2391
2588
  formatForEditing,
2589
+ getDefaultValue,
2590
+ getFormProperties,
2392
2591
  getRefProps,
2592
+ omitId,
2393
2593
  parseValue,
2394
2594
  pathNotUniqueError,
2395
2595
  translations,
2396
- useForm,
2397
2596
  useFormContext,
2597
+ useFormFieldState,
2598
+ useFormHandler,
2398
2599
  useFormValues,
2399
- useInputProps,
2400
- useQueryRefOptions,
2401
- useRefQueryLookupHandler
2600
+ useKeyHandler
2402
2601
  };
2403
2602
  //# sourceMappingURL=index.mjs.map