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

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