@dxos/react-ui-form 0.8.4-main.1da679c → 0.8.4-main.21d9917

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