@qoretechnologies/reqraft 0.10.53 → 0.10.54-pr.115.ge2d364c

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 (215) hide show
  1. package/.claude/CLAUDE.md +25 -0
  2. package/.tasks/INDEX.md +1 -0
  3. package/.tasks/STORY_NETWORK_ISOLATION.md +98 -0
  4. package/README.md +1 -1
  5. package/design/FORM_ENGINE_EXPRESSIONS.md +110 -0
  6. package/design/RENDER_EXPRESSION_TRANSPORT.md +18 -0
  7. package/dist/components/dpqlEditor/dpqlProbe.d.ts +37 -0
  8. package/dist/components/dpqlEditor/dpqlProbe.d.ts.map +1 -0
  9. package/dist/components/dpqlEditor/dpqlProbe.js +203 -0
  10. package/dist/components/dpqlEditor/dpqlProbe.js.map +1 -0
  11. package/dist/components/dpqlEditor/index.d.ts +4 -0
  12. package/dist/components/dpqlEditor/index.d.ts.map +1 -1
  13. package/dist/components/dpqlEditor/index.js +5 -1
  14. package/dist/components/dpqlEditor/index.js.map +1 -1
  15. package/dist/components/dpqlEditor/types.d.ts +29 -2
  16. package/dist/components/dpqlEditor/types.d.ts.map +1 -1
  17. package/dist/components/dpqlEditor/useDpqlProbe.d.ts +4 -0
  18. package/dist/components/dpqlEditor/useDpqlProbe.d.ts.map +1 -0
  19. package/dist/components/dpqlEditor/useDpqlProbe.js +29 -0
  20. package/dist/components/dpqlEditor/useDpqlProbe.js.map +1 -0
  21. package/dist/components/dpqlEditor/useDpqlSession.d.ts +5 -2
  22. package/dist/components/dpqlEditor/useDpqlSession.d.ts.map +1 -1
  23. package/dist/components/dpqlEditor/useDpqlSession.js +8 -2
  24. package/dist/components/dpqlEditor/useDpqlSession.js.map +1 -1
  25. package/dist/components/form/engine/CompactRow.d.ts.map +1 -1
  26. package/dist/components/form/engine/CompactRow.js +186 -21
  27. package/dist/components/form/engine/CompactRow.js.map +1 -1
  28. package/dist/components/form/engine/CompactToolbar.d.ts.map +1 -1
  29. package/dist/components/form/engine/CompactToolbar.js +5 -2
  30. package/dist/components/form/engine/CompactToolbar.js.map +1 -1
  31. package/dist/components/form/engine/FormEngine.d.ts +159 -11
  32. package/dist/components/form/engine/FormEngine.d.ts.map +1 -1
  33. package/dist/components/form/engine/FormEngine.js +376 -75
  34. package/dist/components/form/engine/FormEngine.js.map +1 -1
  35. package/dist/components/form/engine/FormFieldsSkeleton.d.ts +48 -0
  36. package/dist/components/form/engine/FormFieldsSkeleton.d.ts.map +1 -0
  37. package/dist/components/form/engine/FormFieldsSkeleton.js +38 -0
  38. package/dist/components/form/engine/FormFieldsSkeleton.js.map +1 -0
  39. package/dist/components/form/engine/OptionFieldMessages.d.ts +17 -2
  40. package/dist/components/form/engine/OptionFieldMessages.d.ts.map +1 -1
  41. package/dist/components/form/engine/OptionFieldMessages.js +61 -11
  42. package/dist/components/form/engine/OptionFieldMessages.js.map +1 -1
  43. package/dist/components/form/engine/_structuredData/SchemaDataView.d.ts.map +1 -1
  44. package/dist/components/form/engine/_structuredData/SchemaDataView.js +7 -1
  45. package/dist/components/form/engine/_structuredData/SchemaDataView.js.map +1 -1
  46. package/dist/components/form/engine/compactToolbarContext.d.ts +1 -0
  47. package/dist/components/form/engine/compactToolbarContext.d.ts.map +1 -1
  48. package/dist/components/form/engine/readFirst.d.ts +42 -1
  49. package/dist/components/form/engine/readFirst.d.ts.map +1 -1
  50. package/dist/components/form/engine/readFirst.js +74 -7
  51. package/dist/components/form/engine/readFirst.js.map +1 -1
  52. package/dist/components/form/engine/rendererTypes.d.ts +13 -0
  53. package/dist/components/form/engine/rendererTypes.d.ts.map +1 -1
  54. package/dist/components/form/engine/rendererTypes.js.map +1 -1
  55. package/dist/components/form/engine/rowMenuContext.d.ts +78 -0
  56. package/dist/components/form/engine/rowMenuContext.d.ts.map +1 -0
  57. package/dist/components/form/engine/rowMenuContext.js +103 -0
  58. package/dist/components/form/engine/rowMenuContext.js.map +1 -0
  59. package/dist/components/form/engine/typeChoices.d.ts +37 -0
  60. package/dist/components/form/engine/typeChoices.d.ts.map +1 -0
  61. package/dist/components/form/engine/typeChoices.js +25 -0
  62. package/dist/components/form/engine/typeChoices.js.map +1 -0
  63. package/dist/components/form/expressions/ExpressionField.d.ts +7 -1
  64. package/dist/components/form/expressions/ExpressionField.d.ts.map +1 -1
  65. package/dist/components/form/expressions/ExpressionField.js +181 -33
  66. package/dist/components/form/expressions/ExpressionField.js.map +1 -1
  67. package/dist/components/form/expressions/argumentPresence.d.ts +97 -0
  68. package/dist/components/form/expressions/argumentPresence.d.ts.map +1 -0
  69. package/dist/components/form/expressions/argumentPresence.js +203 -0
  70. package/dist/components/form/expressions/argumentPresence.js.map +1 -0
  71. package/dist/components/form/expressions/builder/argumentLabel.d.ts.map +1 -1
  72. package/dist/components/form/expressions/builder/argumentLabel.js +9 -4
  73. package/dist/components/form/expressions/builder/argumentLabel.js.map +1 -1
  74. package/dist/components/form/expressions/builder/index.d.ts +15 -2
  75. package/dist/components/form/expressions/builder/index.d.ts.map +1 -1
  76. package/dist/components/form/expressions/builder/index.js +19 -57
  77. package/dist/components/form/expressions/builder/index.js.map +1 -1
  78. package/dist/components/form/expressions/dpqlMockLsp.d.ts +17 -0
  79. package/dist/components/form/expressions/dpqlMockLsp.d.ts.map +1 -1
  80. package/dist/components/form/expressions/dpqlMockLsp.js +75 -9
  81. package/dist/components/form/expressions/dpqlMockLsp.js.map +1 -1
  82. package/dist/components/form/expressions/renderExpressionToText.d.ts.map +1 -1
  83. package/dist/components/form/expressions/renderExpressionToText.js +94 -19
  84. package/dist/components/form/expressions/renderExpressionToText.js.map +1 -1
  85. package/dist/components/form/fields/Field.d.ts.map +1 -1
  86. package/dist/components/form/fields/Field.js +3 -1
  87. package/dist/components/form/fields/Field.js.map +1 -1
  88. package/dist/components/form/fields/allowed-values/AllowedValues.d.ts +11 -1
  89. package/dist/components/form/fields/allowed-values/AllowedValues.d.ts.map +1 -1
  90. package/dist/components/form/fields/allowed-values/AllowedValues.js +14 -2
  91. package/dist/components/form/fields/allowed-values/AllowedValues.js.map +1 -1
  92. package/dist/components/form/fields/auto/AutoFormField.d.ts.map +1 -1
  93. package/dist/components/form/fields/auto/AutoFormField.js +13 -2
  94. package/dist/components/form/fields/auto/AutoFormField.js.map +1 -1
  95. package/dist/components/form/fields/rich-text/RichText.d.ts +11 -0
  96. package/dist/components/form/fields/rich-text/RichText.d.ts.map +1 -1
  97. package/dist/components/form/fields/rich-text/RichText.js +84 -5
  98. package/dist/components/form/fields/rich-text/RichText.js.map +1 -1
  99. package/dist/components/form/fields/template/ReadOnlyTemplateTag.d.ts +2 -1
  100. package/dist/components/form/fields/template/ReadOnlyTemplateTag.d.ts.map +1 -1
  101. package/dist/components/form/fields/template/ReadOnlyTemplateTag.js +3 -2
  102. package/dist/components/form/fields/template/ReadOnlyTemplateTag.js.map +1 -1
  103. package/dist/components/form/fields/template/TemplateField.d.ts +31 -1
  104. package/dist/components/form/fields/template/TemplateField.d.ts.map +1 -1
  105. package/dist/components/form/fields/template/TemplateField.js +507 -40
  106. package/dist/components/form/fields/template/TemplateField.js.map +1 -1
  107. package/dist/components/form/index.d.ts +1 -0
  108. package/dist/components/form/index.d.ts.map +1 -1
  109. package/dist/components/form/index.js +1 -0
  110. package/dist/components/form/index.js.map +1 -1
  111. package/dist/components/smartEditor/__fixtures__/mockLspServer.d.ts +1 -0
  112. package/dist/components/smartEditor/__fixtures__/mockLspServer.d.ts.map +1 -1
  113. package/dist/components/smartEditor/__fixtures__/mockLspServer.js +6 -1
  114. package/dist/components/smartEditor/__fixtures__/mockLspServer.js.map +1 -1
  115. package/dist/helpers/dpqlDetection.d.ts +58 -0
  116. package/dist/helpers/dpqlDetection.d.ts.map +1 -0
  117. package/dist/helpers/dpqlDetection.js +164 -0
  118. package/dist/helpers/dpqlDetection.js.map +1 -0
  119. package/dist/helpers/optionUiTypes.d.ts +1 -1
  120. package/dist/helpers/options.d.ts +37 -0
  121. package/dist/helpers/options.d.ts.map +1 -1
  122. package/dist/helpers/options.js +78 -1
  123. package/dist/helpers/options.js.map +1 -1
  124. package/dist/helpers/templateItems.d.ts +47 -0
  125. package/dist/helpers/templateItems.d.ts.map +1 -0
  126. package/dist/helpers/templateItems.js +88 -0
  127. package/dist/helpers/templateItems.js.map +1 -0
  128. package/dist/helpers/templates.d.ts +21 -0
  129. package/dist/helpers/templates.d.ts.map +1 -1
  130. package/dist/helpers/templates.js +49 -3
  131. package/dist/helpers/templates.js.map +1 -1
  132. package/dist/helpers/validations.d.ts.map +1 -1
  133. package/dist/helpers/validations.js +56 -9
  134. package/dist/helpers/validations.js.map +1 -1
  135. package/dist/hooks/useArgSchema.d.ts +2 -1
  136. package/dist/hooks/useArgSchema.d.ts.map +1 -1
  137. package/dist/hooks/useFetch/useFetch.d.ts +3 -1
  138. package/dist/hooks/useFetch/useFetch.d.ts.map +1 -1
  139. package/dist/hooks/useFetch/useFetch.js +47 -9
  140. package/dist/hooks/useFetch/useFetch.js.map +1 -1
  141. package/dist/hooks/useTemplates.d.ts +20 -0
  142. package/dist/hooks/useTemplates.d.ts.map +1 -1
  143. package/dist/hooks/useTemplates.js +34 -2
  144. package/dist/hooks/useTemplates.js.map +1 -1
  145. package/dist/index.d.ts +2 -1
  146. package/dist/index.d.ts.map +1 -1
  147. package/dist/index.js +5 -1
  148. package/dist/index.js.map +1 -1
  149. package/dist/stories/storyNetwork.d.ts +36 -0
  150. package/dist/stories/storyNetwork.d.ts.map +1 -0
  151. package/dist/stories/storyNetwork.js +82 -0
  152. package/dist/stories/storyNetwork.js.map +1 -0
  153. package/dist/utils/fetch.d.ts +151 -1
  154. package/dist/utils/fetch.d.ts.map +1 -1
  155. package/dist/utils/fetch.js +256 -44
  156. package/dist/utils/fetch.js.map +1 -1
  157. package/dist/utils/lspClient.d.ts +6 -0
  158. package/dist/utils/lspClient.d.ts.map +1 -1
  159. package/dist/utils/lspClient.js +62 -11
  160. package/dist/utils/lspClient.js.map +1 -1
  161. package/dist/utils/websocket.d.ts +6 -0
  162. package/dist/utils/websocket.d.ts.map +1 -1
  163. package/dist/utils/websocket.js +15 -7
  164. package/dist/utils/websocket.js.map +1 -1
  165. package/package.json +2 -2
  166. package/src/components/dpqlEditor/DpqlEditor.stories.tsx +0 -2
  167. package/src/components/dpqlEditor/dpqlProbe.ts +165 -0
  168. package/src/components/dpqlEditor/index.ts +4 -0
  169. package/src/components/dpqlEditor/types.ts +26 -2
  170. package/src/components/dpqlEditor/useDpqlProbe.ts +33 -0
  171. package/src/components/dpqlEditor/useDpqlSession.ts +20 -4
  172. package/src/components/form/engine/CompactRow.tsx +231 -11
  173. package/src/components/form/engine/CompactToolbar.tsx +10 -3
  174. package/src/components/form/engine/FormEngine.stories.tsx +331 -30
  175. package/src/components/form/engine/FormEngine.tsx +504 -87
  176. package/src/components/form/engine/FormFieldsSkeleton.tsx +76 -0
  177. package/src/components/form/engine/OptionFieldMessages.tsx +89 -11
  178. package/src/components/form/engine/_structuredData/SchemaDataView.tsx +11 -0
  179. package/src/components/form/engine/compactToolbarContext.ts +1 -1
  180. package/src/components/form/engine/readFirst.ts +86 -7
  181. package/src/components/form/engine/rendererTypes.ts +12 -0
  182. package/src/components/form/engine/rowMenuContext.ts +159 -0
  183. package/src/components/form/engine/typeChoices.ts +55 -0
  184. package/src/components/form/expressions/ExpressionField.stories.tsx +828 -31
  185. package/src/components/form/expressions/ExpressionField.tsx +234 -29
  186. package/src/components/form/expressions/argumentPresence.ts +200 -0
  187. package/src/components/form/expressions/builder/argumentLabel.tsx +10 -4
  188. package/src/components/form/expressions/builder/index.tsx +31 -75
  189. package/src/components/form/expressions/dpqlMockLsp.ts +81 -1
  190. package/src/components/form/expressions/renderExpressionToText.ts +106 -17
  191. package/src/components/form/fields/Field.tsx +3 -2
  192. package/src/components/form/fields/allowed-values/AllowedValues.tsx +13 -2
  193. package/src/components/form/fields/auto/AutoFormField.tsx +12 -2
  194. package/src/components/form/fields/rich-text/RichText.tsx +112 -19
  195. package/src/components/form/fields/template/ReadOnlyTemplateTag.tsx +4 -2
  196. package/src/components/form/fields/template/TemplateField.tsx +667 -95
  197. package/src/components/form/index.tsx +1 -0
  198. package/src/components/log/Log.stories.tsx +2 -1
  199. package/src/components/smartEditor/__fixtures__/mockLspServer.ts +6 -1
  200. package/src/helpers/dpqlDetection.ts +209 -0
  201. package/src/helpers/options.ts +70 -0
  202. package/src/helpers/templateItems.ts +81 -0
  203. package/src/helpers/templates.ts +51 -2
  204. package/src/helpers/validations.ts +59 -9
  205. package/src/hooks/useFetch/useFetch.stories.tsx +6 -5
  206. package/src/hooks/useFetch/useFetch.tsx +53 -7
  207. package/src/hooks/useStorage/useStorage.stories.tsx +2 -1
  208. package/src/hooks/useTemplates.ts +41 -0
  209. package/src/hooks/useWebSocket/useWebsocket.stories.tsx +2 -1
  210. package/src/index.tsx +14 -1
  211. package/src/stores/currentUser/currentUser.stories.tsx +2 -1
  212. package/src/stories/storyNetwork.ts +92 -0
  213. package/src/utils/fetch.ts +311 -21
  214. package/src/utils/lspClient.ts +68 -11
  215. package/src/utils/websocket.ts +20 -9
@@ -2,11 +2,12 @@ import { ReqoreButton } from '@qoretechnologies/reqore';
2
2
  import type { IReqoreEffect } from '@qoretechnologies/reqore/dist/components/Effect';
3
3
  import { StoryObj } from '@storybook/react-vite';
4
4
  import { expect, fn, userEvent, waitFor, within } from 'storybook/test';
5
- import { useState } from 'react';
5
+ import { useEffect, useMemo, useState } from 'react';
6
6
 
7
+ import { storyApiUrl } from '../../../stories/storyNetwork';
7
8
  import { StoryMeta } from '../../../types';
8
9
  import { FormEngine } from '../engine/FormEngine';
9
- import { startDpqlMockLsp } from './dpqlMockLsp';
10
+ import { dpqlMockParseCalls, startDpqlMockLsp } from './dpqlMockLsp';
10
11
  import { ExpressionField } from './ExpressionField';
11
12
  import { mockExpressions } from './mockExpressions';
12
13
  import { IExpression } from './types';
@@ -24,6 +25,9 @@ const IDE_AI_BUTTON_EFFECT: IReqoreEffect = {
24
25
  },
25
26
  };
26
27
 
28
+ /** A stable `onChange` for stories that own their value themselves. */
29
+ const noopChange = (): void => undefined;
30
+
27
31
  const SAMPLE: IExpression = {
28
32
  is_expression: true,
29
33
  value: {
@@ -41,7 +45,7 @@ const meta = {
41
45
  parameters: {
42
46
  mockData: [
43
47
  {
44
- url: 'https://hq.qoretechnologies.com:8092/api/latest/system?action=expressions&context=ui',
48
+ url: storyApiUrl('system?action=expressions&context=ui'),
45
49
  method: 'GET',
46
50
  status: 200,
47
51
  response: mockExpressions,
@@ -101,16 +105,15 @@ export const Default: Story = {
101
105
 
102
106
  // Visual mode renders the ported builder (with its own Explain); the shell
103
107
  // adds only the Visual/Text toggle.
104
- await waitFor(
105
- () => expect(canvasElement.querySelector('.expression')).toBeInTheDocument(),
106
- { timeout: 6000 }
107
- );
108
+ await waitFor(() => expect(canvasElement.querySelector('.expression')).toBeInTheDocument(), {
109
+ timeout: 6000,
110
+ });
108
111
  await expect(await canvas.findByText('Logical Equals')).toBeInTheDocument();
109
112
  },
110
113
  };
111
114
 
112
115
  /**
113
- * Empty expression — an empty AST renders no "Parsed" box at all (nothing to
116
+ * Empty expression — an empty AST renders no "Preview" box at all (nothing to
114
117
  * parse), just the bare editor waiting for input.
115
118
  */
116
119
  export const Empty: Story = {
@@ -122,7 +125,7 @@ export const Empty: Story = {
122
125
  docs: {
123
126
  description: {
124
127
  story:
125
- 'Renders ExpressionField in Text mode with an empty expression AST — only the DPQL editor shows; the "Parsed" preview box stays hidden until there is a query to parse.',
128
+ 'Renders ExpressionField in Text mode with an empty expression AST — only the DPQL editor shows; the "Preview" box stays hidden until there is something to show.',
126
129
  },
127
130
  },
128
131
  },
@@ -133,9 +136,12 @@ export const Empty: Story = {
133
136
  async play({ canvasElement }) {
134
137
  const canvas = within(canvasElement);
135
138
  await waitForLspIdle(canvasElement);
136
- // An empty query has nothing to parse — no Parsed box.
139
+ /* An empty query has nothing to render — no Preview box.
140
+ The testid is the assertion that matters: after the rename a
141
+ `queryByText('Parsed')` would be null whatever the box did, and an
142
+ assertion that cannot fail is worse than no assertion. */
137
143
  await expect(canvas.queryByTestId('expression-preview')).toBeNull();
138
- await expect(canvas.queryByText('Parsed')).toBeNull();
144
+ await expect(canvas.queryByText('Preview')).toBeNull();
139
145
  },
140
146
  };
141
147
 
@@ -255,10 +261,9 @@ export const ViaFormEngine: Story = {
255
261
  async play({ canvasElement }) {
256
262
  const canvas = within(canvasElement);
257
263
  // The ported builder rendered inside the engine-driven form.
258
- await waitFor(
259
- () => expect(canvasElement.querySelector('.expression')).toBeInTheDocument(),
260
- { timeout: 6000 }
261
- );
264
+ await waitFor(() => expect(canvasElement.querySelector('.expression')).toBeInTheDocument(), {
265
+ timeout: 6000,
266
+ });
262
267
  await expect(await canvas.findByText('Logical Equals')).toBeInTheDocument();
263
268
  // The ExpressionField shell wraps it: the Visual/Text toggle is present.
264
269
  await expect(await canvas.findByText('Visual')).toBeInTheDocument();
@@ -272,7 +277,7 @@ export const ViaFormEngine: Story = {
272
277
  /**
273
278
  * FormEngine → Text mode, the serialize direction: switching the
274
279
  * engine-driven expression field to Text seeds the DPQL editor from the
275
- * stored AST (`dpql/serialize` over the mock LSP) and the "Parsed" preview
280
+ * stored AST (`dpql/serialize` over the mock LSP) and the "Preview" box
276
281
  * renders the same AST.
277
282
  */
278
283
  export const ViaFormEngineTextMode: Story = {
@@ -280,7 +285,7 @@ export const ViaFormEngineTextMode: Story = {
280
285
  docs: {
281
286
  description: {
282
287
  story:
283
- 'Renders the FormEngine expression field, then switches to Text mode — the DPQL editor seeds from the stored AST via the mock LSP\'s dpql/serialize call and the "Parsed" preview mirrors it.',
288
+ 'Renders the FormEngine expression field, then switches to Text mode — the DPQL editor seeds from the stored AST via the mock LSP\'s dpql/serialize call and the "Preview" box mirrors it.',
284
289
  },
285
290
  },
286
291
  },
@@ -293,10 +298,9 @@ export const ViaFormEngineTextMode: Story = {
293
298
  const canvas = within(canvasElement);
294
299
 
295
300
  // Visual (the builder) renders first.
296
- await waitFor(
297
- () => expect(canvasElement.querySelector('.expression')).toBeInTheDocument(),
298
- { timeout: 6000 }
299
- );
301
+ await waitFor(() => expect(canvasElement.querySelector('.expression')).toBeInTheDocument(), {
302
+ timeout: 6000,
303
+ });
300
304
 
301
305
  // Switch to Text — the DPQL editor mounts and seeds from the AST
302
306
  // (`dpql/serialize` over the mock LSP).
@@ -339,7 +343,7 @@ export const ViaFormEngineTextTyping: Story = {
339
343
  docs: {
340
344
  description: {
341
345
  story:
342
- 'Renders the FormEngine expression field with an empty AST in Text mode. Typing DPQL text triggers the mock LSP\'s dpql/parse and the parsed expression lands in the form value with is_expression set.',
346
+ "Renders the FormEngine expression field with an empty AST in Text mode. Typing DPQL text triggers the mock LSP's dpql/parse and the parsed expression lands in the form value with is_expression set.",
343
347
  },
344
348
  },
345
349
  },
@@ -403,17 +407,204 @@ export const ViaFormEngineTextTyping: Story = {
403
407
  },
404
408
  { timeout: 10000 }
405
409
  );
406
- await waitFor(
407
- () => expect(canvas.getByTestId('expression-preview')).toBeInTheDocument(),
408
- { timeout: 10000 }
409
- );
410
+ await waitFor(() => expect(canvas.getByTestId('expression-preview')).toBeInTheDocument(), {
411
+ timeout: 10000,
412
+ });
410
413
  await waitForLspIdle(canvasElement);
411
414
  },
412
415
  };
413
416
 
417
+ /**
418
+ * A field's declared type travels with every parse, and the answer is shown
419
+ * only where there is something to decide.
420
+ *
421
+ * The mock returns type analysis ONLY when the request carried a
422
+ * `target_type`, exactly as the server does - so these stories fail if the
423
+ * field stops sending it, rather than passing on a fixture.
424
+ */
425
+ /* `text` is per-story, and that is not cosmetic. `DpqlProbe` caches parse
426
+ results in a session-wide singleton keyed by the TEXT ALONE, so two stories
427
+ typing the same string share one answer: the second gets a cache HIT, sends
428
+ no request at all, and is handed the answer computed for the OTHER field's
429
+ type. That is order-dependent, so it passed locally and failed on CI, where
430
+ the two ran the other way round — and the instrumentation proved it by
431
+ reporting `parses=[]` for a field that was nonetheless showing a parsed
432
+ value. Distinct text per story keeps them independent. */
433
+ const typedExpressionStory = (
434
+ fieldType: string,
435
+ text: string,
436
+ expectation: (canvasElement: HTMLElement) => Promise<void>
437
+ ): Story => ({
438
+ render: () => {
439
+ const [value, setValue] = useState<any>({
440
+ amount: { type: fieldType, value: { args: [] }, is_expression: true },
441
+ });
442
+ return (
443
+ <FormEngine
444
+ name='typedExprForm'
445
+ options={
446
+ {
447
+ amount: {
448
+ type: fieldType,
449
+ ui_type: fieldType,
450
+ display_name: 'Amount',
451
+ preselected: true,
452
+ supports_expressions: true,
453
+ expressions: mockExpressions,
454
+ },
455
+ } as any
456
+ }
457
+ value={value}
458
+ onChange={(_n, v) => setValue(v)}
459
+ />
460
+ );
461
+ },
462
+ async beforeEach() {
463
+ const stop = startDpqlMockLsp();
464
+ return () => stop();
465
+ },
466
+ async play({ canvasElement }) {
467
+ const canvas = within(canvasElement);
468
+ await userEvent.click(await canvas.findByText('Text'));
469
+ const editable = (await waitFor(
470
+ () => {
471
+ const el = canvasElement.querySelector('[contenteditable="true"]');
472
+ if (!el) throw new Error('editor not ready');
473
+ return el as HTMLElement;
474
+ },
475
+ { timeout: 10000 }
476
+ )) as HTMLElement;
477
+ /* The editor mounting is NOT the same as the language server being ready,
478
+ and typing into it before the socket is up loses the parse: no request is
479
+ sent, so no `target_type` answer ever comes back and the fit message is
480
+ never rendered. That is a race, not a slow response — raising the
481
+ expectation's timeout would not have helped.
482
+
483
+ It cost a red CI run that was green locally, where the mock connects
484
+ immediately. Worse, it is silent in the sibling story: one that asserts
485
+ the ABSENCE of the message passes for the wrong reason under exactly the
486
+ same race. */
487
+ await waitForLspIdle(canvasElement);
488
+ await userEvent.click(editable);
489
+ await userEvent.type(editable, text);
490
+ await expectation(canvasElement);
491
+ await waitForLspIdle(canvasElement);
492
+ },
493
+ });
494
+
495
+ /**
496
+ * Text used as a number: the conversion is attempted, not guaranteed, so the
497
+ * field says so and offers the conversion. The value itself is checked again
498
+ * server-side when the expression actually runs.
499
+ */
500
+ export const TextModeTypeMayNotFit: Story = typedExpressionStory(
501
+ 'int',
502
+ 'total_may_not_fit',
503
+ async (canvasElement) => {
504
+ /* Matched against the rendered TEXT, not with `getByText`. `ReqoreMessage`
505
+ renders its title through nested nodes, so an exact single-element match
506
+ reports "unable to find" for a message that is demonstrably on screen —
507
+ the very failure testing-library's own error describes ("the text is
508
+ broken up by multiple elements"). A unit test against this component
509
+ reproduced that directly: the container held the title, the message and
510
+ the fix chip, and `getByText` still could not find it.
511
+
512
+ The assertion stays meaningful: the title has to be present AND the
513
+ suggested conversion has to be the one for this field's type. */
514
+ /* The assertion carries the diagnosis with it. A DOM dump is truncated by
515
+ testing-library and a `console.log` does not reliably reach a CI log, but
516
+ a custom matcher message always does — and the one thing worth knowing
517
+ here is whether the front end SENT `target_type` at all, because the mock
518
+ answers with analysis only when it did. Without this the failure looks
519
+ identical whether the request lacked a target or the answer went
520
+ unrendered. */
521
+ const why = () =>
522
+ `parses=${JSON.stringify(dpqlMockParseCalls)} text=${JSON.stringify(
523
+ (canvasElement.textContent || '').slice(0, 400)
524
+ )}`;
525
+ await waitFor(
526
+ () => {
527
+ expect(canvasElement.textContent, why()).toContain('This may not fit');
528
+ expect(
529
+ canvasElement.querySelector('[data-testid="expression-type-fix"]')?.textContent,
530
+ why()
531
+ ).toContain('toInt(');
532
+ },
533
+ { timeout: 10000 }
534
+ );
535
+ }
536
+ );
537
+
538
+ /**
539
+ * Text used as text needs no conversion at all, so nothing is said. A warning
540
+ * here would be noise, and noise is what teaches people to ignore the
541
+ * warnings that matter.
542
+ */
543
+ export const TextModeTypeFits: Story = typedExpressionStory(
544
+ 'string',
545
+ 'total_type_fits',
546
+ async (canvasElement) => {
547
+ const canvas = within(canvasElement);
548
+ await waitFor(() => expect(canvas.getByTestId('expression-preview')).toBeInTheDocument(), {
549
+ timeout: 10000,
550
+ });
551
+ /* Absence, checked against the rendered text for the same reason its sibling
552
+ checks presence that way: `queryByText` returns null for a message that IS
553
+ on screen but split across nodes, so it would report "no warning" whether
554
+ or not one was drawn — passing for the wrong reason is worse here than
555
+ failing, because absence is the whole claim. */
556
+ expect(canvasElement.textContent).not.toContain('This may not fit');
557
+ expect(canvasElement.textContent).not.toContain('This does not fit');
558
+ }
559
+ );
560
+
561
+ /**
562
+ * An `auto` field accepts anything, so there is nothing to check the
563
+ * expression's return type against and no target is sent at all.
564
+ *
565
+ * This is not a hypothetical. An expression VALUE is
566
+ * `{ is_expression: true, value: {...} }` — a hash whatever the expression
567
+ * computes — and the auto field used to infer its type from that envelope, so
568
+ * writing an expression made the field decide it held a `hash`. That inferred
569
+ * type was then handed back as the return type to check against, and `1 + 2`
570
+ * was rejected on a test assertion's Value with "The expression returns int,
571
+ * and this field holds hash": the field disagreeing with itself about a value
572
+ * the author had just written.
573
+ */
574
+ export const TextModeAutoAsksNothing: Story = typedExpressionStory(
575
+ 'auto',
576
+ 'total_auto_field',
577
+ async (canvasElement) => {
578
+ await waitFor(
579
+ () => {
580
+ expect(canvasElement.querySelector('[contenteditable="true"]')).toBeTruthy();
581
+ },
582
+ { timeout: 10000 }
583
+ );
584
+ /* The contract, not just the symptom: the mock answers with analysis only
585
+ when a target was sent, so asserting the MESSAGE is absent would also
586
+ pass if the request simply never happened. Assert what was asked. */
587
+ await waitFor(
588
+ () => {
589
+ expect(
590
+ dpqlMockParseCalls.length,
591
+ `parses=${JSON.stringify(dpqlMockParseCalls)}`
592
+ ).toBeGreaterThan(0);
593
+ },
594
+ { timeout: 10000 }
595
+ );
596
+ expect(
597
+ dpqlMockParseCalls.every((call) => !call.target),
598
+ `an auto field must send no target_type: ${JSON.stringify(dpqlMockParseCalls)}`
599
+ ).toBe(true);
600
+ expect(canvasElement.textContent).not.toContain('This does not fit');
601
+ expect(canvasElement.textContent).not.toContain('This may not fit');
602
+ }
603
+ );
604
+
414
605
  /**
415
606
  * Text (DPQL) mode, backed by a mock-socket LSP. Typing DPQL parses to the
416
- * AST (`dpql/parse`); the "Parsed" preview reflects it. (Slate typing is
607
+ * AST (`dpql/parse`); the "Preview" box reflects it. (Slate typing is
417
608
  * driven live; the play test asserts the editor mounted + connected.)
418
609
  */
419
610
  export const TextMode: Story = {
@@ -425,7 +616,7 @@ export const TextMode: Story = {
425
616
  docs: {
426
617
  description: {
427
618
  story:
428
- 'Renders ExpressionField in Text (DPQL) mode over a mock-socket LSP. Typing DPQL text triggers dpql/parse and the "Parsed" preview reflects the resulting AST.',
619
+ 'Renders ExpressionField in Text (DPQL) mode over a mock-socket LSP. Typing DPQL text triggers dpql/parse and the "Preview" box reflects the resulting AST.',
429
620
  },
430
621
  },
431
622
  },
@@ -444,7 +635,7 @@ export const TextMode: Story = {
444
635
  { timeout: 6000 }
445
636
  )) as HTMLElement;
446
637
 
447
- // Type DPQL → debounced `dpql/parse` → AST → the "Parsed" preview
638
+ // Type DPQL → debounced `dpql/parse` → AST → the "Preview" box
448
639
  // reflects it (the mock echoes the typed text into an `==` expression).
449
640
  await userEvent.click(editable);
450
641
  await userEvent.type(editable, 'name');
@@ -524,6 +715,612 @@ export const ToggleInFormEngine: Story = {
524
715
  },
525
716
  };
526
717
 
718
+ /**
719
+ * Wait for the DOM to stop changing.
720
+ *
721
+ * Both stories below assert a NEGATIVE — that the view the author was put in
722
+ * is not swapped out from under them — and a swap lands a render or two after
723
+ * the interaction that causes it. `waitFor` is therefore no help at all: it
724
+ * passes on the transient state BEFORE the swap and proves nothing. Settling
725
+ * on the DOM going quiet is what makes the assertion mean something.
726
+ */
727
+ const settle = (root: HTMLElement, quietMs = 400): Promise<void> =>
728
+ new Promise<void>((resolve) => {
729
+ let quiet: ReturnType<typeof setTimeout>;
730
+ const stop = (): void => {
731
+ observer.disconnect();
732
+ resolve();
733
+ };
734
+ const observer = new MutationObserver(() => {
735
+ clearTimeout(quiet);
736
+ quiet = setTimeout(stop, quietMs);
737
+ });
738
+ observer.observe(root, {
739
+ attributes: true,
740
+ characterData: true,
741
+ childList: true,
742
+ subtree: true,
743
+ });
744
+ quiet = setTimeout(stop, quietMs);
745
+ });
746
+
747
+ /** Open a compact row — a read-first row shows its label, not its editor. */
748
+ const openCompactRow = async (canvasElement: HTMLElement): Promise<void> => {
749
+ const label = (await waitFor(
750
+ () => {
751
+ const el = within(canvasElement).queryByText('Value');
752
+ if (!el) throw new Error('row not rendered');
753
+ return el as HTMLElement;
754
+ },
755
+ { timeout: 10000 }
756
+ )) as HTMLElement;
757
+ if (!canvasElement.querySelector('input[type="text"], textarea, [contenteditable="true"]')) {
758
+ await userEvent.click(label);
759
+ }
760
+ };
761
+
762
+ /**
763
+ * Type an expression into a plain field, accept the offer, and assert the
764
+ * shell opens on TEXT and stays there.
765
+ *
766
+ * Shared so that each story below differs only in the FORM around the field —
767
+ * which is the variable under test, the plain engine being healthy and the
768
+ * arrangements a real consumer builds being the ones that break it.
769
+ */
770
+ const acceptTypedExpression = async (canvasElement: HTMLElement): Promise<void> => {
771
+ const input = (await waitFor(
772
+ () => {
773
+ const el = canvasElement.querySelector(
774
+ 'input[type="text"], textarea, [contenteditable="true"]'
775
+ );
776
+ if (!el) throw new Error('field not ready');
777
+ return el as HTMLElement;
778
+ },
779
+ { timeout: 10000 }
780
+ )) as HTMLElement;
781
+
782
+ await userEvent.click(input);
783
+ await userEvent.type(input, '1 + 2');
784
+
785
+ // The offer appears only after the server (here the mock) has said the text
786
+ // really is an expression — a successful parse alone means nothing.
787
+ const offer = (await waitFor(
788
+ () => {
789
+ const el = canvasElement.querySelector('.dpql-detected-offer');
790
+ if (!el) throw new Error('offer not made');
791
+ return el as HTMLElement;
792
+ },
793
+ { timeout: 10000 }
794
+ )) as HTMLElement;
795
+
796
+ await userEvent.click(offer);
797
+
798
+ await waitFor(() => expect(canvasElement.querySelector('.expression-field')).toBeInTheDocument(), {
799
+ timeout: 10000,
800
+ });
801
+
802
+ await settle(canvasElement);
803
+
804
+ // Text, not Visual: the DPQL editor is mounted and the builder is not.
805
+ const editable = canvasElement.querySelector(
806
+ '.expression-field [contenteditable="true"]'
807
+ ) as HTMLElement | null;
808
+ expect(editable).toBeInTheDocument();
809
+ expect(canvasElement.querySelector('.expression-field .expression')).not.toBeInTheDocument();
810
+
811
+ /* And it holds the author's own sentence.
812
+ *
813
+ * Landing in Text mode with an EMPTY editor is barely better than landing in
814
+ * the builder: what the author typed is not on screen either way, and a
815
+ * Preview of it sitting beside an empty box reads as the text having been
816
+ * thrown away. The AST reaches this shell one render after the mode does, so
817
+ * this is exactly the assertion that fails when seeding only ever gets one
818
+ * turn. */
819
+ await waitFor(() => expect(editable?.textContent).toContain('1 + 2'), { timeout: 10000 });
820
+ };
821
+
822
+ /**
823
+ * Accepting "Use as expression" lands in TEXT mode, and STAYS there.
824
+ *
825
+ * An author who typed `1 + 2` into a plain field and accepted the offer is
826
+ * already writing in that language: `TemplateField` hands the shell
827
+ * `defaultMode='text'` for exactly that reason. Landing them in the visual
828
+ * builder instead makes them find their own sentence again — and the sentence
829
+ * they typed is not shown anywhere, because the builder renders operands, not
830
+ * text.
831
+ *
832
+ * The whole path is covered deliberately: the offer is the ONLY entry that
833
+ * asks for Text mode, so a story that enters expression mode through the More
834
+ * menu (`ToggleInFormEngine`) cannot guard it — that route never sets
835
+ * `expressionFromText` and correctly lands on Visual.
836
+ */
837
+ export const OfferAcceptedOpensTextMode: Story = {
838
+ parameters: {
839
+ docs: {
840
+ description: {
841
+ story:
842
+ 'Types DPQL into a plain string field, accepts the "Use as expression" offer, and asserts the expression shell opens on Text (the DPQL editor seeded with the typed text) rather than on the visual builder — and stays there once the DOM settles.',
843
+ },
844
+ },
845
+ },
846
+ render: () => {
847
+ const [value, setValue] = useState<any>({});
848
+ return (
849
+ <FormEngine
850
+ name='dpqlOfferForm'
851
+ options={
852
+ {
853
+ expected: {
854
+ type: 'string',
855
+ ui_type: 'string',
856
+ display_name: 'Value',
857
+ preselected: true,
858
+ supports_expressions: true,
859
+ expressions: mockExpressions,
860
+ },
861
+ } as any
862
+ }
863
+ value={value}
864
+ onChange={(_n, v) => setValue(v)}
865
+ />
866
+ );
867
+ },
868
+ async beforeEach() {
869
+ const stop = startDpqlMockLsp();
870
+ return () => stop();
871
+ },
872
+ async play({ canvasElement }) {
873
+ await acceptTypedExpression(canvasElement);
874
+ },
875
+ };
876
+
877
+ /**
878
+ * The accepted offer survives a host that rebuilds the field's schema.
879
+ *
880
+ * A consumer form does not hand the engine one frozen schema. qorus-ide's test
881
+ * step drawer derives the schema it passes FROM the current value — a path that
882
+ * holds a reference is given the reference editor, a compared value is typed by
883
+ * the path it is compared against — so the engine is handed a brand-new options
884
+ * object on every change, including the one the accepted offer itself causes.
885
+ *
886
+ * The offer's whole promise is that the author keeps writing where they were
887
+ * writing. If a re-derived schema takes that away, the promise is only kept on
888
+ * forms simple enough not to have one, which is not the form this feature was
889
+ * built for.
890
+ */
891
+ export const OfferSurvivesARederivedSchema: Story = {
892
+ parameters: {
893
+ docs: {
894
+ description: {
895
+ story:
896
+ "Repeats the accepted-offer flow against a host that rebuilds the options schema from the value on every change (as qorus-ide's step drawer does) — the Text view the offer opened must survive the churn.",
897
+ },
898
+ },
899
+ },
900
+ render: () => {
901
+ const [value, setValue] = useState<any>({});
902
+ // Rebuilt from the value, so its identity changes on every edit — the
903
+ // host behaviour being modelled.
904
+ const options = useMemo(
905
+ () =>
906
+ ({
907
+ expected: {
908
+ type: 'string',
909
+ ui_type: 'string',
910
+ display_name: 'Value',
911
+ preselected: true,
912
+ supports_expressions: true,
913
+ expressions: mockExpressions,
914
+ },
915
+ }) as any,
916
+ [value]
917
+ );
918
+ return (
919
+ <FormEngine
920
+ name='dpqlOfferChurnForm'
921
+ options={options}
922
+ value={value}
923
+ onChange={(_n, v) => setValue(v)}
924
+ />
925
+ );
926
+ },
927
+ async beforeEach() {
928
+ const stop = startDpqlMockLsp();
929
+ return () => stop();
930
+ },
931
+ async play({ canvasElement }) {
932
+ await acceptTypedExpression(canvasElement);
933
+ },
934
+ };
935
+
936
+ /**
937
+ * The accepted offer survives the COMPACT read-first row.
938
+ *
939
+ * The forms this feature was built for are compact ones — qorus-ide's test step
940
+ * drawer renders every option as a read-first row that shows a summary of what
941
+ * the field holds and opens onto the editor. Accepting the offer is the moment
942
+ * a field that held nothing starts holding something, so it is exactly the
943
+ * moment that treatment changes, and the author is inside the control while it
944
+ * does.
945
+ */
946
+ export const OfferSurvivesACompactRow: Story = {
947
+ parameters: {
948
+ docs: {
949
+ description: {
950
+ story:
951
+ 'Repeats the accepted-offer flow in a compact (read-first) form whose schema is rebuilt from the value — the arrangement qorus-ide uses — and asserts the Text view survives it.',
952
+ },
953
+ },
954
+ },
955
+ render: () => {
956
+ const [value, setValue] = useState<any>({});
957
+ const options = useMemo(
958
+ () =>
959
+ ({
960
+ expected: {
961
+ type: 'string',
962
+ ui_type: 'string',
963
+ display_name: 'Value',
964
+ preselected: true,
965
+ supports_expressions: true,
966
+ expressions: mockExpressions,
967
+ },
968
+ }) as any,
969
+ [value]
970
+ );
971
+ return (
972
+ <FormEngine
973
+ name='dpqlOfferCompactForm'
974
+ compact
975
+ flat
976
+ transparent
977
+ padded={false}
978
+ showTypeToggle={false}
979
+ size='small'
980
+ options={options}
981
+ value={value}
982
+ onChange={(_n, v) => setValue(v)}
983
+ />
984
+ );
985
+ },
986
+ async beforeEach() {
987
+ const stop = startDpqlMockLsp();
988
+ return () => stop();
989
+ },
990
+ async play({ canvasElement }) {
991
+ await openCompactRow(canvasElement);
992
+ await acceptTypedExpression(canvasElement);
993
+ },
994
+ };
995
+
996
+ /**
997
+ * The Text view survives the host answering LATE about the field.
998
+ *
999
+ * A consumer does not settle a row's schema the moment it is drawn. qorus-ide
1000
+ * re-derives these rows from catalogues it is still fetching — the type a
1001
+ * compared value gets is read off the reference it is compared against — so the
1002
+ * type a row was OPENED with is not always the type it ends up with, and the
1003
+ * change can land a second or two after the author has already acted.
1004
+ *
1005
+ * That is the reported symptom this covers, and it is the one that made the bug
1006
+ * look intermittent rather than reproducible: clicking Text appeared to work,
1007
+ * and then a moment later the control was back on Visual with nothing on screen
1008
+ * to say why.
1009
+ */
1010
+ export const TextViewSurvivesALateHostChange: Story = {
1011
+ parameters: {
1012
+ docs: {
1013
+ description: {
1014
+ story:
1015
+ "Accepts the offer in a compact row, then has the host re-type the field a moment later (as qorus-ide does when its reference catalogue answers) — the Text view must not be swapped out from under the author.",
1016
+ },
1017
+ },
1018
+ },
1019
+ render: () => {
1020
+ const [value, setValue] = useState<any>({});
1021
+ const [retyped, setRetyped] = useState(false);
1022
+ // Fires once the field is holding an expression: the host's answer lands
1023
+ // after the author has already accepted the offer.
1024
+ const isExpression = !!value?.expected?.is_expression;
1025
+ useEffect(() => {
1026
+ if (!isExpression) return undefined;
1027
+ const timer = setTimeout(() => setRetyped(true), 500);
1028
+ return () => clearTimeout(timer);
1029
+ }, [isExpression]);
1030
+ const options = useMemo(
1031
+ () =>
1032
+ ({
1033
+ expected: {
1034
+ // `auto` is one of the types a compact row opens as a CARD rather
1035
+ // than in place, so this is a re-type that moves the editor — the
1036
+ // whole point of the exercise.
1037
+ type: retyped ? 'auto' : 'string',
1038
+ ui_type: retyped ? 'auto' : 'string',
1039
+ display_name: 'Value',
1040
+ preselected: true,
1041
+ supports_expressions: true,
1042
+ expressions: mockExpressions,
1043
+ },
1044
+ }) as any,
1045
+ [retyped]
1046
+ );
1047
+ return (
1048
+ <>
1049
+ <FormEngine
1050
+ name='dpqlOfferLateForm'
1051
+ compact
1052
+ flat
1053
+ transparent
1054
+ padded={false}
1055
+ showTypeToggle={false}
1056
+ size='small'
1057
+ options={options}
1058
+ value={value}
1059
+ onChange={(_n, v) => setValue(v)}
1060
+ />
1061
+ {/* The host's answer is not otherwise visible, and the assertion has to
1062
+ wait for it rather than for a duration. */}
1063
+ <span data-testid='host-retyped'>{String(retyped)}</span>
1064
+ </>
1065
+ );
1066
+ },
1067
+ async beforeEach() {
1068
+ const stop = startDpqlMockLsp();
1069
+ return () => stop();
1070
+ },
1071
+ async play({ canvasElement }) {
1072
+ await openCompactRow(canvasElement);
1073
+ await acceptTypedExpression(canvasElement);
1074
+
1075
+ // Wait for the host's late answer to actually land — a timeout here would
1076
+ // make the assertion a race.
1077
+ await waitFor(
1078
+ () =>
1079
+ expect(canvasElement.querySelector('[data-testid="host-retyped"]')?.textContent).toBe(
1080
+ 'true'
1081
+ ),
1082
+ { timeout: 10000 }
1083
+ );
1084
+ await settle(canvasElement);
1085
+
1086
+ expect(
1087
+ canvasElement.querySelector('.expression-field [contenteditable="true"]')
1088
+ ).toBeInTheDocument();
1089
+ expect(canvasElement.querySelector('.expression-field .expression')).not.toBeInTheDocument();
1090
+ },
1091
+ };
1092
+
1093
+ /**
1094
+ * The field's own menu stays in the toolbar row.
1095
+ *
1096
+ * `TemplateField` renders its controls — the More menu that offers "Use
1097
+ * Template", and the undo for an accepted offer — as SIBLINGS of the expression
1098
+ * shell. Beside an ordinary one-line editor, centring that menu in the flex
1099
+ * line is what lines it up with the row's other buttons.
1100
+ *
1101
+ * The shell is not one line. It is a toolbar with an editor, a type message and
1102
+ * a preview stacked under it, so centring put the menu somewhere down the side
1103
+ * of that block — level with nothing, overlapping the editor, and a long way
1104
+ * from the Undo it belongs beside.
1105
+ *
1106
+ * Only reachable with templates ON OFFER, which is why the stories above miss
1107
+ * it: with nothing to offer the menu is not rendered at all.
1108
+ *
1109
+ * Inside a form row the field no longer draws that menu itself: it publishes
1110
+ * its items into the row's own ⋮ (`rowMenuContext` — one menu per control), so
1111
+ * the menu asserted here is the row's, and the field's own must be absent.
1112
+ */
1113
+ export const FieldMenuStaysInTheToolbar: Story = {
1114
+ parameters: {
1115
+ docs: {
1116
+ description: {
1117
+ story:
1118
+ "Accepts the offer on a compact row whose field also has templates. The row shows ONE More menu — the field publishes its items into the row's ⋮ rather than drawing its own — and that menu sits in the shell's toolbar row, level with Undo, not part-way down the editor.",
1119
+ },
1120
+ },
1121
+ },
1122
+ render: () => {
1123
+ const [value, setValue] = useState<any>({});
1124
+ return (
1125
+ <FormEngine
1126
+ name='dpqlOfferToolbarForm'
1127
+ compact
1128
+ flat
1129
+ transparent
1130
+ padded={false}
1131
+ showTypeToggle={false}
1132
+ size='small'
1133
+ options={
1134
+ {
1135
+ expected: {
1136
+ type: 'string',
1137
+ ui_type: 'string',
1138
+ display_name: 'Value',
1139
+ preselected: true,
1140
+ supports_expressions: true,
1141
+ supports_templates: true,
1142
+ expressions: mockExpressions,
1143
+ templates: {
1144
+ items: [
1145
+ {
1146
+ label: 'Values this case captures',
1147
+ items: [{ label: 'Order status', value: '$.order.status', badge: 'string' }],
1148
+ },
1149
+ ],
1150
+ },
1151
+ },
1152
+ } as any
1153
+ }
1154
+ value={value}
1155
+ onChange={(_n, v) => setValue(v)}
1156
+ />
1157
+ );
1158
+ },
1159
+ async beforeEach() {
1160
+ const stop = startDpqlMockLsp();
1161
+ return () => stop();
1162
+ },
1163
+ async play({ canvasElement }) {
1164
+ await openCompactRow(canvasElement);
1165
+ await acceptTypedExpression(canvasElement);
1166
+
1167
+ // One menu per control: the row's ⋮, not a second one drawn by the field.
1168
+ expect(canvasElement.querySelector('.template-more')).toBeNull();
1169
+ const menus = canvasElement.querySelectorAll('.options-readfirst-more');
1170
+ expect(menus).toHaveLength(1);
1171
+ const menu = menus[0] as HTMLElement;
1172
+
1173
+ // The toolbar row is the shell's first line — the Visual/Text toggle.
1174
+ const toggle = within(canvasElement).getByText('Text').closest('button') as HTMLElement;
1175
+ const toolbar = toggle.getBoundingClientRect();
1176
+ const control = menu.getBoundingClientRect();
1177
+
1178
+ /* Reported as numbers: "the menu is in the wrong place" is not something a
1179
+ CI log can show, and the two rectangles are the whole story. */
1180
+ const where = `toolbar ${Math.round(toolbar.top)}–${Math.round(
1181
+ toolbar.bottom
1182
+ )}, menu ${Math.round(control.top)}–${Math.round(control.bottom)}`;
1183
+
1184
+ // Level with the toolbar: the menu's own centre falls inside that row.
1185
+ const centre = control.top + control.height / 2;
1186
+ expect(
1187
+ centre >= toolbar.top && centre <= toolbar.bottom,
1188
+ `the field's More menu should sit in the toolbar row — ${where}`
1189
+ ).toBe(true);
1190
+ },
1191
+ };
1192
+
1193
+ /**
1194
+ * The Text editor seeds from an AST that arrives AFTER the mode flips.
1195
+ *
1196
+ * `TemplateField` passes the shell its OWN `value` prop, and on the render
1197
+ * that flips the field into expression mode that prop is still the STRING the
1198
+ * author typed — the parsed AST only comes back through the host form one
1199
+ * render later. So the shell mounts in Text mode with nothing to serialize,
1200
+ * and an effect that runs on the mode alone has already had its only turn: the
1201
+ * author gets an empty editor with a Preview of an expression sitting beside
1202
+ * it, which reads as the text having been thrown away.
1203
+ *
1204
+ * Modelled here rather than live because it is a pure ordering problem — no
1205
+ * instance, no offer, no host form. The late arrival is the whole test.
1206
+ */
1207
+ export const TextModeSeedsWhenAstArrivesLate: Story = {
1208
+ parameters: {
1209
+ docs: {
1210
+ description: {
1211
+ story:
1212
+ "Mounts the shell in Text mode with a value that is not yet an AST, then delivers the AST a moment later — the DPQL editor must seed from it rather than stay empty.",
1213
+ },
1214
+ },
1215
+ },
1216
+ render: () => {
1217
+ const [value, setValue] = useState<IExpression>({
1218
+ is_expression: true,
1219
+ // What `TemplateField` actually holds at that moment: the typed text.
1220
+ value: '1 + 2' as unknown as IExpression['value'],
1221
+ });
1222
+ useEffect(() => {
1223
+ const timer = setTimeout(() => setValue(SAMPLE), 100);
1224
+ return () => clearTimeout(timer);
1225
+ }, []);
1226
+ return (
1227
+ <ExpressionField
1228
+ value={value}
1229
+ onChange={noopChange}
1230
+ defaultMode='text'
1231
+ expressions={mockExpressions}
1232
+ />
1233
+ );
1234
+ },
1235
+ async beforeEach() {
1236
+ const stop = startDpqlMockLsp();
1237
+ return () => stop();
1238
+ },
1239
+ async play({ canvasElement }) {
1240
+ const editable = (await waitFor(
1241
+ () => {
1242
+ const el = canvasElement.querySelector('[contenteditable="true"]');
1243
+ if (!el) throw new Error('editor not ready');
1244
+ return el as HTMLElement;
1245
+ },
1246
+ { timeout: 10000 }
1247
+ )) as HTMLElement;
1248
+
1249
+ // The AST arrives late; the editor must catch up with it.
1250
+ await waitFor(
1251
+ () => {
1252
+ expect(editable.textContent).toMatch(/local:?\s*name/);
1253
+ expect(editable.textContent).toContain('John');
1254
+ },
1255
+ { timeout: 10000 }
1256
+ );
1257
+ await waitForLspIdle(canvasElement);
1258
+ },
1259
+ };
1260
+
1261
+ /**
1262
+ * The Text view offers template completions.
1263
+ *
1264
+ * Templates are how an author names a value the surrounding interface already
1265
+ * has, and the Text view is a DPQL editor like any other: typing `$` asks the
1266
+ * language server, in position, and shows what it answers. Nothing about
1267
+ * mounting that editor inside the expression shell changes it — the shell
1268
+ * passes no template list of its own, because there is none to pass.
1269
+ *
1270
+ * Asserted here because it had never been asserted anywhere: the shell's Text
1271
+ * view had only ever been exercised for parse, serialize and type analysis, so
1272
+ * "does `$` still work in there?" was an open question with no cost to
1273
+ * answering. What this covers is the CLIENT half — that the shell surfaces
1274
+ * what the server offers. Which contexts the live Qorus server offers is its
1275
+ * own question, and this cannot answer it.
1276
+ */
1277
+ export const TextModeOffersTemplateCompletions: Story = {
1278
+ args: {
1279
+ value: { is_expression: true, value: { args: [] } },
1280
+ defaultMode: 'text',
1281
+ },
1282
+ parameters: {
1283
+ docs: {
1284
+ description: {
1285
+ story:
1286
+ 'Types `$` into the shell\'s Text view — the DPQL editor asks the language server in position and the template namespaces ($data:, $config:, …) open in the completion dropdown.',
1287
+ },
1288
+ },
1289
+ },
1290
+ async beforeEach() {
1291
+ const stop = startDpqlMockLsp();
1292
+ return () => stop();
1293
+ },
1294
+ async play({ canvasElement }) {
1295
+ const editable = (await waitFor(
1296
+ () => {
1297
+ const el = canvasElement.querySelector('[contenteditable="true"]');
1298
+ if (!el) throw new Error('editor not ready');
1299
+ return el as HTMLElement;
1300
+ },
1301
+ { timeout: 10000 }
1302
+ )) as HTMLElement;
1303
+
1304
+ // The editor mounting is not the language server being ready, and a `$`
1305
+ // typed before the socket is up asks nothing at all.
1306
+ await waitForLspIdle(canvasElement);
1307
+ await userEvent.click(editable);
1308
+ await userEvent.type(editable, '$');
1309
+
1310
+ // The dropdown is portalled, so it is looked for in the document rather
1311
+ // than in the canvas.
1312
+ await waitFor(
1313
+ () => {
1314
+ const dropdown = document.querySelector('.reqore-menu');
1315
+ expect(dropdown).not.toBeNull();
1316
+ expect(dropdown!.textContent).toContain('$data:');
1317
+ expect(dropdown!.textContent).toContain('$config:');
1318
+ },
1319
+ { timeout: 20000 }
1320
+ );
1321
+ },
1322
+ };
1323
+
527
1324
  /**
528
1325
  * LIVE — fetches the real expression catalogue from the configured Qorus
529
1326
  * instance (no `expressions` override). This is the true apples-to-apples
@@ -583,7 +1380,7 @@ export const Live: Story = {
583
1380
 
584
1381
  /**
585
1382
  * LIVE — server-side rendering over the LSP (`dpql/renderExpression`). Text
586
- * mode against the real instance: the live "Parsed" line should show the
1383
+ * mode against the real instance: the live "Preview" box should show the
587
1384
  * server rendering — `"test".startsWith("t", true)` — not the DPQL form
588
1385
  * (`"test" startsWith "t"`) or the client-side approximation. Compare with
589
1386
  * qorus-ide's Explain (storybook :6007) for the same AST. Prereq: same as
@@ -597,7 +1394,7 @@ export const LiveExplain: Story = {
597
1394
  docs: {
598
1395
  description: {
599
1396
  story:
600
- 'Renders ExpressionField in Text mode against a live Qorus instance — the "Parsed" preview uses the server-rendered form via dpql/renderExpression rather than the client-side approximation.',
1397
+ 'Renders ExpressionField in Text mode against a live Qorus instance — the "Preview" box uses the server-rendered form via dpql/renderExpression rather than the client-side approximation.',
601
1398
  },
602
1399
  },
603
1400
  },