@dxos/react-ui-form 0.8.4-main.7ace549 → 0.8.4-main.937b3ca

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