@terreno/ui 57.11.0 → 57.13.0

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 (166) hide show
  1. package/dist/AiSuggestionBox.js +9 -9
  2. package/dist/AiSuggestionBox.js.map +1 -1
  3. package/dist/Banner.js +1 -1
  4. package/dist/Banner.js.map +1 -1
  5. package/dist/Box.d.ts.map +1 -1
  6. package/dist/Box.js +36 -3
  7. package/dist/Box.js.map +1 -1
  8. package/dist/Button.d.ts.map +1 -1
  9. package/dist/Button.js +7 -0
  10. package/dist/Button.js.map +1 -1
  11. package/dist/Common.d.ts +34 -4
  12. package/dist/Common.d.ts.map +1 -1
  13. package/dist/Common.js.map +1 -1
  14. package/dist/DataTable.d.ts.map +1 -1
  15. package/dist/DataTable.js +50 -3
  16. package/dist/DataTable.js.map +1 -1
  17. package/dist/Image.d.ts.map +1 -1
  18. package/dist/Image.js +1 -1
  19. package/dist/Image.js.map +1 -1
  20. package/dist/MarkdownView.d.ts.map +1 -1
  21. package/dist/MarkdownView.js +67 -5
  22. package/dist/MarkdownView.js.map +1 -1
  23. package/dist/Modal.js +1 -1
  24. package/dist/SegmentedControl.d.ts.map +1 -1
  25. package/dist/SegmentedControl.js +15 -11
  26. package/dist/SegmentedControl.js.map +1 -1
  27. package/dist/SelectField.d.ts.map +1 -1
  28. package/dist/SelectField.js +4 -1
  29. package/dist/SelectField.js.map +1 -1
  30. package/dist/SplitPage.d.ts.map +1 -1
  31. package/dist/SplitPage.js +145 -55
  32. package/dist/SplitPage.js.map +1 -1
  33. package/dist/SplitPage.native.js +1 -1
  34. package/dist/SplitPage.native.js.map +1 -1
  35. package/dist/TerrenoProvider.d.ts +7 -3
  36. package/dist/TerrenoProvider.d.ts.map +1 -1
  37. package/dist/TerrenoProvider.js +2 -2
  38. package/dist/TerrenoProvider.js.map +1 -1
  39. package/dist/Theme.d.ts +19 -85
  40. package/dist/Theme.d.ts.map +1 -1
  41. package/dist/Theme.js +149 -33
  42. package/dist/Theme.js.map +1 -1
  43. package/dist/Toast.d.ts.map +1 -1
  44. package/dist/Toast.js +21 -12
  45. package/dist/Toast.js.map +1 -1
  46. package/dist/ToastNotifications.d.ts.map +1 -1
  47. package/dist/ToastNotifications.js +5 -2
  48. package/dist/ToastNotifications.js.map +1 -1
  49. package/dist/Tooltip.d.ts +1 -0
  50. package/dist/Tooltip.d.ts.map +1 -1
  51. package/dist/Tooltip.js +84 -37
  52. package/dist/Tooltip.js.map +1 -1
  53. package/dist/blocks/BlocksView.d.ts.map +1 -1
  54. package/dist/blocks/BlocksView.js +5 -1
  55. package/dist/blocks/BlocksView.js.map +1 -1
  56. package/dist/blocks/blockRenderers.d.ts +10 -1
  57. package/dist/blocks/blockRenderers.d.ts.map +1 -1
  58. package/dist/blocks/blockRenderers.js +330 -9
  59. package/dist/blocks/blockRenderers.js.map +1 -1
  60. package/dist/blocks/useChecklistState.d.ts +18 -0
  61. package/dist/blocks/useChecklistState.d.ts.map +1 -0
  62. package/dist/blocks/useChecklistState.js +29 -0
  63. package/dist/blocks/useChecklistState.js.map +1 -0
  64. package/dist/blocks/useResolvedImages.d.ts.map +1 -1
  65. package/dist/blocks/useResolvedImages.js +16 -0
  66. package/dist/blocks/useResolvedImages.js.map +1 -1
  67. package/dist/colorContrast.d.ts +9 -0
  68. package/dist/colorContrast.d.ts.map +1 -0
  69. package/dist/colorContrast.js +47 -0
  70. package/dist/colorContrast.js.map +1 -0
  71. package/dist/icons/OfflineIcon.js +1 -1
  72. package/dist/table/TableDate.d.ts.map +1 -1
  73. package/dist/table/TableDate.js +3 -1
  74. package/dist/table/TableDate.js.map +1 -1
  75. package/package.json +2 -2
  76. package/src/AiSuggestionBox.tsx +10 -10
  77. package/src/Banner.tsx +1 -1
  78. package/src/Box.test.tsx +80 -0
  79. package/src/Box.tsx +52 -0
  80. package/src/Button.test.tsx +39 -1
  81. package/src/Button.tsx +9 -0
  82. package/src/Common.ts +35 -4
  83. package/src/DataTable.test.tsx +133 -1
  84. package/src/DataTable.tsx +78 -3
  85. package/src/Image.tsx +1 -0
  86. package/src/MarkdownView.test.tsx +165 -2
  87. package/src/MarkdownView.tsx +100 -5
  88. package/src/Modal.tsx +1 -1
  89. package/src/SegmentedControl.test.tsx +7 -0
  90. package/src/SegmentedControl.tsx +22 -11
  91. package/src/SelectField.tsx +4 -1
  92. package/src/SplitPage.native.tsx +1 -1
  93. package/src/SplitPage.test.tsx +473 -5
  94. package/src/SplitPage.tsx +266 -132
  95. package/src/TerrenoProvider.tsx +15 -5
  96. package/src/Theme.test.tsx +212 -3
  97. package/src/Theme.tsx +184 -39
  98. package/src/Toast.test.tsx +7 -0
  99. package/src/Toast.tsx +22 -12
  100. package/src/ToastNotifications.test.tsx +36 -0
  101. package/src/ToastNotifications.tsx +5 -2
  102. package/src/Tooltip.test.tsx +232 -1
  103. package/src/Tooltip.tsx +128 -67
  104. package/src/__snapshots__/AddressField.test.tsx.snap +7 -7
  105. package/src/__snapshots__/AiSuggestionBox.test.tsx.snap +23 -23
  106. package/src/__snapshots__/Banner.test.tsx.snap +3 -0
  107. package/src/__snapshots__/BooleanField.test.tsx.snap +3 -3
  108. package/src/__snapshots__/Button.test.tsx.snap +16 -16
  109. package/src/__snapshots__/Card.test.tsx.snap +0 -1
  110. package/src/__snapshots__/CustomSelectField.test.tsx.snap +23 -23
  111. package/src/__snapshots__/DataTable.test.tsx.snap +30 -30
  112. package/src/__snapshots__/DecimalRangeActionSheet.test.tsx.snap +2 -2
  113. package/src/__snapshots__/DropdownPanel.test.tsx.snap +2 -2
  114. package/src/__snapshots__/EmailField.test.tsx.snap +2 -2
  115. package/src/__snapshots__/ErrorPage.test.tsx.snap +1 -1
  116. package/src/__snapshots__/Field.test.tsx.snap +37 -37
  117. package/src/__snapshots__/FilterSelectMenu.test.tsx.snap +2 -1
  118. package/src/__snapshots__/HeightActionSheet.test.tsx.snap +2 -2
  119. package/src/__snapshots__/HeightField.test.tsx.snap +8 -8
  120. package/src/__snapshots__/HeightFieldDesktop.test.tsx.snap +6 -6
  121. package/src/__snapshots__/InfoModalIcon.test.tsx.snap +2 -2
  122. package/src/__snapshots__/MarkdownView.test.tsx.snap +2 -2
  123. package/src/__snapshots__/MobileAddressAutoComplete.test.tsx.snap +1 -1
  124. package/src/__snapshots__/Modal.test.tsx.snap +10 -10
  125. package/src/__snapshots__/NumberField.test.tsx.snap +1 -1
  126. package/src/__snapshots__/NumberPickerActionSheet.test.tsx.snap +2 -2
  127. package/src/__snapshots__/Page.test.tsx.snap +1 -1
  128. package/src/__snapshots__/PhoneNumberField.test.tsx.snap +4 -4
  129. package/src/__snapshots__/PickerSelect.test.tsx.snap +8 -8
  130. package/src/__snapshots__/SectionDivider.test.tsx.snap +2 -2
  131. package/src/__snapshots__/SegmentedControl.test.tsx.snap +183 -0
  132. package/src/__snapshots__/SelectBadge.test.tsx.snap +9 -9
  133. package/src/__snapshots__/SelectField.test.tsx.snap +19 -19
  134. package/src/__snapshots__/Signature.test.tsx.snap +1 -1
  135. package/src/__snapshots__/SignatureCaptureField.test.tsx.snap +2 -2
  136. package/src/__snapshots__/SignatureField.test.tsx.snap +2 -2
  137. package/src/__snapshots__/SplitPage.test.tsx.snap +165 -67
  138. package/src/__snapshots__/TapToEdit.test.tsx.snap +1 -1
  139. package/src/__snapshots__/TerrenoProvider.test.tsx.snap +20 -4
  140. package/src/__snapshots__/TextArea.test.tsx.snap +4 -4
  141. package/src/__snapshots__/TextField.test.tsx.snap +3 -3
  142. package/src/__snapshots__/TimezonePicker.test.tsx.snap +18 -18
  143. package/src/__snapshots__/Toast.test.tsx.snap +224 -154
  144. package/src/__snapshots__/TypedSignatureField.test.tsx.snap +3 -3
  145. package/src/__snapshots__/UnifiedAddressAutoComplete.test.tsx.snap +6 -6
  146. package/src/__snapshots__/WebAddressAutocomplete.test.tsx.snap +4 -4
  147. package/src/blocks/BlocksView.test.tsx +1101 -2
  148. package/src/blocks/BlocksView.tsx +5 -1
  149. package/src/blocks/blockRenderers.tsx +730 -22
  150. package/src/blocks/useChecklistState.ts +46 -0
  151. package/src/blocks/useResolvedImages.ts +16 -0
  152. package/src/bunSetup.ts +3 -0
  153. package/src/colorContrast.test.ts +27 -0
  154. package/src/colorContrast.ts +55 -0
  155. package/src/icons/OfflineIcon.tsx +2 -2
  156. package/src/icons/__snapshots__/OfflineIcon.test.tsx.snap +4 -4
  157. package/src/login/__snapshots__/LoginScreen.test.tsx.snap +7 -7
  158. package/src/signUp/__snapshots__/OAuthButtons.test.tsx.snap +3 -3
  159. package/src/signUp/__snapshots__/SignUpScreen.test.tsx.snap +7 -7
  160. package/src/table/TableDate.tsx +3 -1
  161. package/src/table/__snapshots__/Table.test.tsx.snap +5 -5
  162. package/src/table/__snapshots__/TableBadge.test.tsx.snap +3 -3
  163. package/src/table/__snapshots__/TableDate.test.tsx.snap +4 -0
  164. package/src/table/__snapshots__/TableHeader.test.tsx.snap +4 -4
  165. package/src/table/__snapshots__/TableHeaderCell.test.tsx.snap +7 -7
  166. package/src/table/__snapshots__/TableRow.test.tsx.snap +6 -6
@@ -1,9 +1,14 @@
1
- import {describe, expect, it, mock} from "bun:test";
1
+ import {afterEach, describe, expect, it, jest, mock} from "bun:test";
2
2
  import {readdirSync, readFileSync} from "node:fs";
3
3
  import {join} from "node:path";
4
+ import type {Block} from "@terreno/blocks";
4
5
  import {act, fireEvent, waitFor} from "@testing-library/react-native";
5
- import {ActivityIndicator, Image as NativeImage} from "react-native";
6
+ import {setStringAsync} from "expo-clipboard";
7
+ import {ActivityIndicator, Image as NativeImage, ScrollView, StyleSheet} from "react-native";
6
8
 
9
+ import {IconButton} from "../IconButton";
10
+ import {Image} from "../Image";
11
+ import {MarkdownView} from "../MarkdownView";
7
12
  import {sharedResponsiveBreakpointStore} from "../ResponsiveBreakpoint";
8
13
  import {renderWithTheme} from "../test-utils";
9
14
  import {BlocksView} from "./BlocksView";
@@ -93,6 +98,73 @@ blocks:
93
98
  - type: divider
94
99
  `;
95
100
 
101
+ const STEPPER = `v: 1
102
+ blocks:
103
+ - type: card
104
+ children:
105
+ - type: stepper
106
+ id: guests
107
+ label: Number of people
108
+ unit: People
109
+ value: 5
110
+ min: 1
111
+ max: 20
112
+ callback:
113
+ name: scaleStepper
114
+ payload:
115
+ recipe: roast
116
+ itemsTitle: Your shopping quantities
117
+ items:
118
+ - label: Bone-in leg of lamb
119
+ amount: 2
120
+ unit: kg
121
+ decimals: 1
122
+ - label: Carrots
123
+ amount: 8
124
+ round: up
125
+ note: Generous portions, with a little extra.
126
+ `;
127
+
128
+ const CHECKLIST_ITEMS = ` items:
129
+ - {id: oven, meta: "1:00 pm", text: Preheat the oven, detail: "220 C, fan off.", checked: true}
130
+ - {id: lamb_in, meta: "1:30 pm", text: Put the lamb in}
131
+ - {id: veg, text: Peel the vegetables}
132
+ - {id: parsnips, text: Par-boil the parsnips}
133
+ - {id: potatoes, text: Roast the potatoes}
134
+ - {id: gravy, text: Make the gravy}
135
+ - {id: rest, text: Rest the lamb}
136
+ - {id: carve, text: Carve and serve}
137
+ `;
138
+
139
+ const CHECKLIST = `v: 1
140
+ blocks:
141
+ - type: checklist
142
+ id: cooking
143
+ title: Cooking checklist
144
+ callback:
145
+ name: toggleChecklist
146
+ payload:
147
+ recipe: roast
148
+ ${CHECKLIST_ITEMS}`;
149
+
150
+ const LOCAL_CHECKLIST = `v: 1
151
+ blocks:
152
+ - type: checklist
153
+ id: cooking
154
+ title: Cooking checklist
155
+ ${CHECKLIST_ITEMS}`;
156
+
157
+ const CHECKLIST_ITEM_IDS = [
158
+ "oven",
159
+ "lamb_in",
160
+ "veg",
161
+ "parsnips",
162
+ "potatoes",
163
+ "gravy",
164
+ "rest",
165
+ "carve",
166
+ ] as const;
167
+
96
168
  // Button presses await a haptic call before running onClick.
97
169
  const press = async (element: Parameters<typeof fireEvent.press>[0]): Promise<void> => {
98
170
  await act(async () => {
@@ -101,6 +173,67 @@ const press = async (element: Parameters<typeof fireEvent.press>[0]): Promise<vo
101
173
  });
102
174
  };
103
175
 
176
+ type RenderedView = ReturnType<typeof renderWithTheme>;
177
+
178
+ // bunSetup replaces IconButton with a null mock, so stepper buttons are found by their props.
179
+ const iconButton = (
180
+ view: RenderedView,
181
+ label: string
182
+ ): {props: {disabled?: boolean; onClick: () => Promise<void> | void}} => {
183
+ const found = view
184
+ .UNSAFE_getAllByType(IconButton)
185
+ .find((node) => node.props.accessibilityLabel === label);
186
+ if (found === undefined) {
187
+ throw new Error(`No IconButton labelled ${label}`);
188
+ }
189
+ return found as unknown as {props: {disabled?: boolean; onClick: () => Promise<void> | void}};
190
+ };
191
+
192
+ const tap = async (view: RenderedView, label: string): Promise<void> => {
193
+ await act(async () => {
194
+ await iconButton(view, label).props.onClick();
195
+ });
196
+ };
197
+
198
+ describe("BlocksView card eyebrow", () => {
199
+ const eyebrowDoc = (lines: string): string => `v: 1
200
+ blocks:
201
+ - type: card
202
+ ${lines} children:
203
+ - type: context
204
+ text: Serves six.
205
+ `;
206
+
207
+ it("draws a small muted eyebrow above the card title", () => {
208
+ const view = renderWithTheme(
209
+ <BlocksView
210
+ document={eyebrowDoc(" eyebrow: Your dinner plan\n title: Sunday roast\n")}
211
+ />
212
+ );
213
+ const eyebrow = view.getByTestId("blocks-0-eyebrow");
214
+ expect(eyebrow.props.children).toBe("Your dinner plan");
215
+ const flat = StyleSheet.flatten(eyebrow.props.style);
216
+ const label = StyleSheet.flatten(view.getByText("Your dinner plan").props.style);
217
+ expect(flat.color).toBe(label.color);
218
+ const json = JSON.stringify(view.toJSON());
219
+ expect(json.indexOf("Your dinner plan")).toBeLessThan(json.indexOf("Sunday roast"));
220
+ expect(json.indexOf("Sunday roast")).toBeLessThan(json.indexOf("Serves six."));
221
+ });
222
+
223
+ it("draws an eyebrow on a card with no title, above the children", () => {
224
+ const view = renderWithTheme(<BlocksView document={eyebrowDoc(" eyebrow: Tonight\n")} />);
225
+ expect(view.getByTestId("blocks-0-eyebrow")).toBeTruthy();
226
+ const json = JSON.stringify(view.toJSON());
227
+ expect(json.indexOf("Tonight")).toBeLessThan(json.indexOf("Serves six."));
228
+ });
229
+
230
+ it("draws no eyebrow when the card has none", () => {
231
+ const view = renderWithTheme(<BlocksView document={eyebrowDoc(" title: Sunday roast\n")} />);
232
+ expect(view.queryByTestId("blocks-0-eyebrow")).toBeNull();
233
+ expect(view.getByText("Sunday roast")).toBeTruthy();
234
+ });
235
+ });
236
+
104
237
  describe("BlocksView", () => {
105
238
  it("renders leaf and layout blocks with Terreno components", async () => {
106
239
  const {getByText, getByTestId} = renderWithTheme(<BlocksView document={LAYOUT} />);
@@ -203,6 +336,112 @@ blocks:
203
336
  expect(getByText("Jan")).toBeTruthy();
204
337
  });
205
338
 
339
+ describe("typed table columns", () => {
340
+ const LAMB = `v: 1
341
+ datasets:
342
+ lamb:
343
+ columns:
344
+ - name: guests
345
+ type: number
346
+ - name: lamb_kg
347
+ type: number
348
+ - name: served
349
+ type: date
350
+ - name: cut
351
+ type: string
352
+ rows:
353
+ - [6, 2.4, "2026-03-14", shoulder]
354
+ blocks:
355
+ - type: table
356
+ title: How much lamb?
357
+ data: lamb
358
+ `;
359
+ type StyledNode = {parent: StyledNode | null; props: {style?: unknown}};
360
+ const flatStyle = (node: StyledNode): {textAlign?: string; width?: number} =>
361
+ (StyleSheet.flatten(node.props.style as never) ?? {}) as {
362
+ textAlign?: string;
363
+ width?: number;
364
+ };
365
+ const cellWidth = (node: StyledNode): number | undefined => {
366
+ let current: StyledNode | null = node;
367
+ while (current) {
368
+ const width = flatStyle(current).width;
369
+ if (typeof width === "number") {
370
+ return width;
371
+ }
372
+ current = current.parent;
373
+ }
374
+ return undefined;
375
+ };
376
+ const layout = async (view: RenderedView, width: number): Promise<void> => {
377
+ await act(async () => {
378
+ fireEvent(view.getByTestId("blocks-0"), "layout", {
379
+ nativeEvent: {layout: {height: 200, width, x: 0, y: 0}},
380
+ });
381
+ });
382
+ };
383
+
384
+ it("sizes the table to its rows so it never spills past the block", () => {
385
+ const view = renderWithTheme(<BlocksView document={LAMB} />);
386
+ const frame = view.getByTestId("blocks-0-table-frame");
387
+ // One header row plus one data row, 54 each, plus the 2px border.
388
+ expect(flatStyle(frame as unknown as StyledNode).height).toBe(110);
389
+ });
390
+
391
+ it("caps a long table at ten visible rows and lets it scroll", () => {
392
+ const rows = Array.from(
393
+ {length: 30},
394
+ (_, index) => ` - [${index}, 2.4, "2026-03-14", shoulder]`
395
+ ).join("\n");
396
+ const long = LAMB.replace(' - [6, 2.4, "2026-03-14", shoulder]', rows);
397
+ const view = renderWithTheme(<BlocksView document={long} />);
398
+ const frame = view.getByTestId("blocks-0-table-frame");
399
+ expect(flatStyle(frame as unknown as StyledNode).height).toBe(11 * 54 + 2);
400
+ });
401
+
402
+ it("shows column names with underscores as spaced headers", () => {
403
+ const view = renderWithTheme(<BlocksView document={LAMB} />);
404
+ expect(view.getByText("lamb kg")).toBeTruthy();
405
+ expect(view.queryByText("lamb_kg")).toBeNull();
406
+ });
407
+ it("maps number columns to right-aligned cells and date columns to DATE_MED", () => {
408
+ const {getByText, queryByText} = renderWithTheme(<BlocksView document={LAMB} />);
409
+ expect(flatStyle(getByText("6") as unknown as StyledNode).textAlign).toBe("right");
410
+ expect(flatStyle(getByText("2.4") as unknown as StyledNode).textAlign).toBe("right");
411
+ expect(getByText("Mar 14, 2026")).toBeTruthy();
412
+ expect(queryByText("2026-03-14")).toBeNull();
413
+ expect(flatStyle(getByText("shoulder") as unknown as StyledNode).textAlign).not.toBe("right");
414
+ });
415
+
416
+ it("uses 120 per column until the table is measured", () => {
417
+ const {getByText} = renderWithTheme(<BlocksView document={LAMB} />);
418
+ expect(cellWidth(getByText("shoulder") as unknown as StyledNode)).toBe(120);
419
+ });
420
+
421
+ it("splits the measured width evenly across columns", async () => {
422
+ const view = renderWithTheme(<BlocksView document={LAMB} />);
423
+ await layout(view, 600);
424
+ expect(cellWidth(view.getByText("shoulder") as unknown as StyledNode)).toBe(150);
425
+ expect(cellWidth(view.getByText("6") as unknown as StyledNode)).toBe(150);
426
+ });
427
+
428
+ it("keeps each column at least 96 wide when the container is narrow", async () => {
429
+ const view = renderWithTheme(<BlocksView document={LAMB} />);
430
+ await layout(view, 200);
431
+ expect(cellWidth(view.getByText("shoulder") as unknown as StyledNode)).toBe(96);
432
+ });
433
+
434
+ it("keeps each listed column's type when the table picks a subset", () => {
435
+ const document = LAMB.replace(
436
+ " data: lamb\n",
437
+ " data: lamb\n columns: [cut, guests]\n"
438
+ );
439
+ const {getByText, queryByText} = renderWithTheme(<BlocksView document={document} />);
440
+ expect(flatStyle(getByText("6") as unknown as StyledNode).textAlign).toBe("right");
441
+ expect(queryByText("Mar 14, 2026")).toBeNull();
442
+ });
443
+ });
444
+
206
445
  it("uses the default selection setter when a select button has no host context", async () => {
207
446
  const view = renderBlock(
208
447
  {
@@ -593,6 +832,866 @@ blocks:
593
832
  expect(allowed.getByText("Pixel")).toBeTruthy();
594
833
  });
595
834
 
835
+ it("renders a stepper with its unit, items grid, and note", () => {
836
+ const {getByText, getByTestId} = renderWithTheme(<BlocksView document={STEPPER} />);
837
+ expect(getByText("Number of people")).toBeTruthy();
838
+ expect(getByTestId("blocks-0-0-value").props.children).toBe("5");
839
+ expect(getByText("People")).toBeTruthy();
840
+ expect(getByText("Your shopping quantities")).toBeTruthy();
841
+ expect(getByText("Bone-in leg of lamb")).toBeTruthy();
842
+ expect(getByText("2.0 kg")).toBeTruthy();
843
+ expect(getByText("8")).toBeTruthy();
844
+ expect(getByText("Generous portions, with a little extra.")).toBeTruthy();
845
+ });
846
+
847
+ it("emits a stepper callback with the agent payload and the next value", async () => {
848
+ const onAction = mock(() => undefined);
849
+ const view = renderWithTheme(
850
+ <BlocksView document={STEPPER} hostActions={["scaleStepper"]} onAction={onAction} />
851
+ );
852
+ expect(view.getByTestId("blocks-0-0")).toBeTruthy();
853
+ await tap(view, "Increase Number of people");
854
+ await tap(view, "Decrease Number of people");
855
+ expect(onAction).toHaveBeenNthCalledWith(1, {
856
+ action: {kind: "callback", name: "scaleStepper", payload: {recipe: "roast", value: 6}},
857
+ blockId: "guests",
858
+ elementId: "guests_increase",
859
+ });
860
+ expect(onAction).toHaveBeenNthCalledWith(2, {
861
+ action: {kind: "callback", name: "scaleStepper", payload: {recipe: "roast", value: 4}},
862
+ blockId: "guests",
863
+ elementId: "guests_decrease",
864
+ });
865
+ });
866
+
867
+ it("disables stepper buttons at the bounds, while pending, and for an unregistered callback", async () => {
868
+ const onAction = mock(() => undefined);
869
+ const disabled = (view: RenderedView, label: string): boolean =>
870
+ iconButton(view, `${label} Number of people`).props.disabled === true;
871
+
872
+ const atMin = renderWithTheme(
873
+ <BlocksView document={STEPPER.replace("value: 5", "value: 1")} onAction={onAction} />
874
+ );
875
+ expect(disabled(atMin, "Decrease")).toBe(true);
876
+ expect(disabled(atMin, "Increase")).toBe(false);
877
+ await tap(atMin, "Decrease Number of people");
878
+ expect(onAction).not.toHaveBeenCalled();
879
+
880
+ const atMax = renderWithTheme(
881
+ <BlocksView document={STEPPER.replace("value: 5", "value: 20")} />
882
+ );
883
+ expect(disabled(atMax, "Increase")).toBe(true);
884
+ expect(disabled(atMax, "Decrease")).toBe(false);
885
+
886
+ // With step 2, a value one partial step from a bound would step past it, so that button is off.
887
+ const nearBounds = (value: number): string =>
888
+ STEPPER.replace("value: 5", `value: ${value}\n step: 2`);
889
+ const nearMax = renderWithTheme(<BlocksView document={nearBounds(19)} onAction={onAction} />);
890
+ expect(disabled(nearMax, "Increase")).toBe(true);
891
+ expect(disabled(nearMax, "Decrease")).toBe(false);
892
+ await tap(nearMax, "Increase Number of people");
893
+ expect(onAction).not.toHaveBeenCalled();
894
+ const nearMin = renderWithTheme(<BlocksView document={nearBounds(2)} onAction={onAction} />);
895
+ expect(disabled(nearMin, "Decrease")).toBe(true);
896
+ expect(disabled(nearMin, "Increase")).toBe(false);
897
+ await tap(nearMin, "Decrease Number of people");
898
+ expect(onAction).not.toHaveBeenCalled();
899
+ const fullStep = renderWithTheme(<BlocksView document={nearBounds(18)} />);
900
+ expect(disabled(fullStep, "Increase")).toBe(false);
901
+ const fullStepDown = renderWithTheme(<BlocksView document={nearBounds(3)} />);
902
+ expect(disabled(fullStepDown, "Decrease")).toBe(false);
903
+
904
+ const pending = renderWithTheme(
905
+ <BlocksView document={STEPPER} onAction={onAction} pendingElementIds={["guests_increase"]} />
906
+ );
907
+ expect(disabled(pending, "Increase")).toBe(true);
908
+ expect(disabled(pending, "Decrease")).toBe(true);
909
+ await tap(pending, "Decrease Number of people");
910
+ expect(onAction).not.toHaveBeenCalled();
911
+
912
+ const unregistered = renderWithTheme(
913
+ <BlocksView document={STEPPER} hostActions={["other"]} onAction={onAction} />
914
+ );
915
+ expect(disabled(unregistered, "Increase")).toBe(true);
916
+ expect(disabled(unregistered, "Decrease")).toBe(true);
917
+ });
918
+
919
+ it("renders a stepper override with the new value and amounts", () => {
920
+ const {getByTestId, getByText, queryByText} = renderWithTheme(
921
+ <BlocksView
922
+ document={STEPPER}
923
+ overrides={{
924
+ guests: {
925
+ callback: {name: "scaleStepper"},
926
+ id: "guests",
927
+ items: [
928
+ {amount: 2.4, decimals: 1, label: "Bone-in leg of lamb", unit: "kg"},
929
+ {amount: 10, label: "Carrots", round: "up"},
930
+ ],
931
+ label: "Number of people",
932
+ max: 20,
933
+ min: 1,
934
+ type: "stepper",
935
+ unit: "People",
936
+ value: 6,
937
+ },
938
+ }}
939
+ />
940
+ );
941
+ expect(getByTestId("blocks-0-0-value").props.children).toBe("6");
942
+ expect(getByText("2.4 kg")).toBeTruthy();
943
+ expect(getByText("10")).toBeTruthy();
944
+ expect(queryByText("2.0 kg")).toBeNull();
945
+ });
946
+
947
+ describe("checklist", () => {
948
+ const counter = (view: RenderedView): string =>
949
+ String(view.getByTestId("blocks-0-counter").props.children);
950
+ const tick = async (view: RenderedView, itemId: string): Promise<void> => {
951
+ await press(view.getByTestId(`blocks-0-cooking_${itemId}-row-clickable`));
952
+ };
953
+ const isTicked = (view: RenderedView, itemId: string): boolean =>
954
+ view.getByTestId(`blocks-0-cooking_${itemId}-checkbox`).props.style.backgroundColor !==
955
+ "transparent";
956
+ const rowState = (view: RenderedView, itemId: string): unknown =>
957
+ view.getByTestId(`blocks-0-cooking_${itemId}-row-clickable`).props.accessibilityState;
958
+ const overrideWith = (checkedIds: readonly string[]): Record<string, Block> => ({
959
+ cooking: {
960
+ callback: {name: "toggleChecklist", payload: {recipe: "roast"}},
961
+ id: "cooking",
962
+ items: CHECKLIST_ITEM_IDS.map((id) => ({
963
+ checked: checkedIds.includes(id),
964
+ id,
965
+ text: `Step ${id}`,
966
+ })),
967
+ title: "Cooking checklist",
968
+ type: "checklist",
969
+ },
970
+ });
971
+
972
+ it("renders the title, the n of m counter, and a row per item", () => {
973
+ const view = renderWithTheme(<BlocksView document={CHECKLIST} />);
974
+ expect(view.getByText("Cooking checklist")).toBeTruthy();
975
+ expect(counter(view)).toBe("1 of 8");
976
+ expect(view.getByText("1:00 pm")).toBeTruthy();
977
+ expect(view.getByText("Preheat the oven")).toBeTruthy();
978
+ expect(view.getByText("220 C, fan off.")).toBeTruthy();
979
+ expect(view.getByText("Carve and serve")).toBeTruthy();
980
+ expect(isTicked(view, "oven")).toBe(true);
981
+ expect(isTicked(view, "lamb_in")).toBe(false);
982
+ expect(view.getByTestId("blocks-0-cooking_lamb_in-row-clickable").props["aria-label"]).toBe(
983
+ "Put the lamb in"
984
+ );
985
+ });
986
+
987
+ it("shows each row's bold text first, then the small muted meta, then the muted detail", () => {
988
+ const view = renderWithTheme(<BlocksView document={CHECKLIST} />);
989
+ const rowPath = "blocks-0-cooking_oven";
990
+ const ids = [
991
+ ...new Set(
992
+ view
993
+ .getByTestId(rowPath)
994
+ .findAll((node) => typeof node.props.testID === "string")
995
+ .map((node) => String(node.props.testID))
996
+ .filter((id) => /-(text|meta|detail)$/.test(id))
997
+ ),
998
+ ];
999
+ expect(ids).toEqual([`${rowPath}-text`, `${rowPath}-meta`, `${rowPath}-detail`]);
1000
+ const propsOf = (testID: string): Record<string, unknown> => {
1001
+ const [node] = view.UNSAFE_root.findAll((candidate) => candidate.props.testID === testID);
1002
+ return node?.props ?? {};
1003
+ };
1004
+ expect(propsOf(`${rowPath}-text`)).toMatchObject({bold: true, children: "Preheat the oven"});
1005
+ expect(propsOf(`${rowPath}-meta`)).toMatchObject({
1006
+ children: "1:00 pm",
1007
+ color: "secondaryLight",
1008
+ size: "sm",
1009
+ });
1010
+ expect(propsOf(`${rowPath}-detail`)).toMatchObject({
1011
+ children: "220 C, fan off.",
1012
+ color: "secondaryLight",
1013
+ });
1014
+ expect(view.queryByTestId("blocks-0-cooking_veg-meta")).toBeNull();
1015
+ expect(view.queryByTestId("blocks-0-cooking_veg-detail")).toBeNull();
1016
+ });
1017
+
1018
+ it("exposes each row as a labelled checkbox with its checked state, kept while locked", () => {
1019
+ const props = {document: CHECKLIST, hostActions: ["toggleChecklist"], onAction: () => {}};
1020
+ const view = renderWithTheme(<BlocksView {...props} />);
1021
+ const row = (itemId: string): {props: Record<string, unknown>} =>
1022
+ view.getByTestId(`blocks-0-cooking_${itemId}-row-clickable`);
1023
+ expect(row("oven").props.accessibilityRole).toBe("checkbox");
1024
+ expect(row("oven").props["aria-label"]).toBe("Preheat the oven");
1025
+ expect(row("oven").props["aria-checked"]).toBe(true);
1026
+ expect(rowState(view, "oven")).toEqual({checked: true, disabled: false});
1027
+ expect(row("lamb_in").props["aria-checked"]).toBe(false);
1028
+ expect(rowState(view, "lamb_in")).toEqual({checked: false, disabled: false});
1029
+
1030
+ view.rerender(<BlocksView {...props} pendingElementIds={["cooking_oven"]} />);
1031
+ expect(row("lamb_in").props.accessibilityRole).toBe("checkbox");
1032
+ expect(row("lamb_in").props["aria-label"]).toBe("Put the lamb in");
1033
+ expect(row("lamb_in").props["aria-disabled"]).toBe(true);
1034
+ expect(rowState(view, "oven")).toEqual({checked: true, disabled: true});
1035
+ });
1036
+
1037
+ it("ticks items on the device when the checklist has no callback", async () => {
1038
+ const onAction = mock(() => undefined);
1039
+ const view = renderWithTheme(
1040
+ <BlocksView
1041
+ document={LOCAL_CHECKLIST}
1042
+ hostActions={["toggleChecklist"]}
1043
+ onAction={onAction}
1044
+ />
1045
+ );
1046
+ await tick(view, "lamb_in");
1047
+ expect(counter(view)).toBe("2 of 8");
1048
+ expect(isTicked(view, "lamb_in")).toBe(true);
1049
+ await tick(view, "oven");
1050
+ expect(counter(view)).toBe("1 of 8");
1051
+ expect(isTicked(view, "oven")).toBe(false);
1052
+ expect(onAction).not.toHaveBeenCalled();
1053
+ });
1054
+
1055
+ it("keeps ticks local to each rendered document", async () => {
1056
+ const first = renderWithTheme(<BlocksView document={LOCAL_CHECKLIST} />);
1057
+ await tick(first, "veg");
1058
+ // Testing Library ignores presses outside the latest render, so the second view mounts after.
1059
+ const second = renderWithTheme(<BlocksView document={LOCAL_CHECKLIST} />);
1060
+ expect(counter(first)).toBe("2 of 8");
1061
+ expect(counter(second)).toBe("1 of 8");
1062
+ });
1063
+
1064
+ it("ticks locally when the callback is not a registered host action", async () => {
1065
+ const onAction = mock(() => undefined);
1066
+ const view = renderWithTheme(
1067
+ <BlocksView document={CHECKLIST} hostActions={["other"]} onAction={onAction} />
1068
+ );
1069
+ await tick(view, "lamb_in");
1070
+ expect(counter(view)).toBe("2 of 8");
1071
+ expect(onAction).not.toHaveBeenCalled();
1072
+ });
1073
+
1074
+ it("emits the tick with the full state and waits for the override", async () => {
1075
+ const onAction = mock(() => undefined);
1076
+ const view = renderWithTheme(
1077
+ <BlocksView document={CHECKLIST} hostActions={["toggleChecklist"]} onAction={onAction} />
1078
+ );
1079
+ await tick(view, "lamb_in");
1080
+ expect(onAction).toHaveBeenCalledTimes(1);
1081
+ expect(onAction).toHaveBeenCalledWith({
1082
+ action: {
1083
+ kind: "callback",
1084
+ name: "toggleChecklist",
1085
+ payload: {
1086
+ checked: true,
1087
+ itemId: "lamb_in",
1088
+ recipe: "roast",
1089
+ state: {
1090
+ carve: false,
1091
+ gravy: false,
1092
+ lamb_in: true,
1093
+ oven: true,
1094
+ parsnips: false,
1095
+ potatoes: false,
1096
+ rest: false,
1097
+ veg: false,
1098
+ },
1099
+ },
1100
+ },
1101
+ blockId: "cooking",
1102
+ elementId: "cooking_lamb_in",
1103
+ });
1104
+ expect(counter(view)).toBe("1 of 8");
1105
+ expect(isTicked(view, "lamb_in")).toBe(false);
1106
+
1107
+ view.rerender(
1108
+ <BlocksView
1109
+ document={CHECKLIST}
1110
+ hostActions={["toggleChecklist"]}
1111
+ onAction={onAction}
1112
+ pendingElementIds={["cooking_lamb_in"]}
1113
+ />
1114
+ );
1115
+ expect(rowState(view, "lamb_in")).toEqual({checked: false, disabled: true});
1116
+ expect(counter(view)).toBe("1 of 8");
1117
+
1118
+ view.rerender(
1119
+ <BlocksView
1120
+ document={CHECKLIST}
1121
+ hostActions={["toggleChecklist"]}
1122
+ onAction={onAction}
1123
+ overrides={overrideWith(["oven", "lamb_in"])}
1124
+ />
1125
+ );
1126
+ expect(counter(view)).toBe("2 of 8");
1127
+ expect(isTicked(view, "lamb_in")).toBe(true);
1128
+ });
1129
+
1130
+ it("disables the whole checklist while a tick is pending", async () => {
1131
+ const onAction = mock(() => undefined);
1132
+ const props = {document: CHECKLIST, hostActions: ["toggleChecklist"], onAction};
1133
+ const view = renderWithTheme(<BlocksView {...props} />);
1134
+ await tick(view, "lamb_in");
1135
+ view.rerender(<BlocksView {...props} pendingElementIds={["cooking_lamb_in"]} />);
1136
+ expect(rowState(view, "veg")).toEqual({checked: false, disabled: true});
1137
+ await tick(view, "veg");
1138
+ expect(onAction).toHaveBeenCalledTimes(1);
1139
+
1140
+ view.rerender(<BlocksView {...props} overrides={overrideWith(["oven", "lamb_in"])} />);
1141
+ await tick(view, "veg");
1142
+ expect(onAction).toHaveBeenCalledTimes(2);
1143
+ const [event] = onAction.mock.calls[1] as unknown as [
1144
+ {action: {payload: {itemId: string; state: Record<string, boolean>}}},
1145
+ ];
1146
+ expect(event.action.payload.itemId).toBe("veg");
1147
+ expect(event.action.payload.state).toMatchObject({lamb_in: true, oven: true, veg: true});
1148
+ });
1149
+
1150
+ it("emits the tick when hostActions is omitted, like the stepper", async () => {
1151
+ const onAction = mock(() => undefined);
1152
+ const view = renderWithTheme(<BlocksView document={CHECKLIST} onAction={onAction} />);
1153
+ await tick(view, "oven");
1154
+ expect(onAction).toHaveBeenCalledTimes(1);
1155
+ const [event] = onAction.mock.calls[0] as unknown as [
1156
+ {action: {payload: {checked: boolean; itemId: string}}},
1157
+ ];
1158
+ expect(event.action.payload.itemId).toBe("oven");
1159
+ expect(event.action.payload.checked).toBe(false);
1160
+ expect(counter(view)).toBe("1 of 8");
1161
+ });
1162
+
1163
+ it("drops local ticks when an override for the checklist arrives", async () => {
1164
+ const view = renderWithTheme(<BlocksView document={LOCAL_CHECKLIST} />);
1165
+ await tick(view, "veg");
1166
+ expect(counter(view)).toBe("2 of 8");
1167
+ view.rerender(
1168
+ <BlocksView
1169
+ document={LOCAL_CHECKLIST}
1170
+ overrides={overrideWith(["gravy", "rest", "carve"])}
1171
+ />
1172
+ );
1173
+ expect(counter(view)).toBe("3 of 8");
1174
+ expect(isTicked(view, "veg")).toBe(false);
1175
+ expect(isTicked(view, "gravy")).toBe(true);
1176
+ });
1177
+ });
1178
+
1179
+ describe("gallery", () => {
1180
+ const PIXEL = "data:image/png;base64,iVBORw0KGgo=";
1181
+ const galleryOf = (count: number): string =>
1182
+ `v: 1
1183
+ blocks:
1184
+ - type: gallery
1185
+ id: roast_photos
1186
+ images:
1187
+ ${Array.from({length: count}, (_, index) => {
1188
+ const caption = index === 0 ? "\n caption: Roast lamb" : "";
1189
+ return ` - src: "${PIXEL}"\n alt: Photo ${index + 1}${caption}`;
1190
+ }).join("\n")}
1191
+ `;
1192
+ const measure = async (view: RenderedView, testID: string, width: number): Promise<void> => {
1193
+ await act(async () => {
1194
+ fireEvent(view.getByTestId(testID), "layout", {
1195
+ nativeEvent: {layout: {height: 300, width, x: 0, y: 0}},
1196
+ });
1197
+ });
1198
+ };
1199
+ const imageSizes = (view: RenderedView): {height?: number; width?: number}[] =>
1200
+ view
1201
+ .UNSAFE_getAllByType(NativeImage)
1202
+ .map((node) => StyleSheet.flatten(node.props.style) as {height?: number; width?: number})
1203
+ .map(({height, width}) => ({height, width}));
1204
+ // Composite and host nodes share a testID, so ids are deduplicated in render order.
1205
+ const tileIdsIn = (view: RenderedView, rowTestID: string): string[] => [
1206
+ ...new Set(
1207
+ view
1208
+ .getByTestId(rowTestID)
1209
+ .findAll((node) => typeof node.props.testID === "string")
1210
+ .map((node) => String(node.props.testID))
1211
+ .filter((id) => /^blocks-0-image-\d+$/.test(id))
1212
+ ),
1213
+ ];
1214
+
1215
+ it("draws up to three @terreno/ui Image tiles in one 4:3 row with alt as the accessible label", async () => {
1216
+ const view = renderWithTheme(<BlocksView document={galleryOf(3)} />);
1217
+ await measure(view, "blocks-0", 600);
1218
+ expect(view.UNSAFE_getAllByType(Image)).toHaveLength(3);
1219
+ const images = view.UNSAFE_getAllByType(NativeImage);
1220
+ expect(images.map((node) => node.props.accessibilityLabel)).toEqual([
1221
+ "Photo 1",
1222
+ "Photo 2",
1223
+ "Photo 3",
1224
+ ]);
1225
+ expect(images.every((node) => node.props.source.uri === PIXEL)).toBe(true);
1226
+ // (600 - 2 gaps of 8) / 3 = 194.67, floored; 194 * 3 / 4 = 145.5, rounded.
1227
+ expect(imageSizes(view)).toEqual([
1228
+ {height: 146, width: 194},
1229
+ {height: 146, width: 194},
1230
+ {height: 146, width: 194},
1231
+ ]);
1232
+ expect(tileIdsIn(view, "blocks-0-row-0")).toEqual([
1233
+ "blocks-0-image-0",
1234
+ "blocks-0-image-1",
1235
+ "blocks-0-image-2",
1236
+ ]);
1237
+ expect(view.queryByTestId("blocks-0-row-1")).toBeNull();
1238
+ expect(view.queryByTestId("blocks-0-scroll")).toBeNull();
1239
+ });
1240
+
1241
+ it("gives each loaded tile image the <tile>-image test ID, like list thumbnails", () => {
1242
+ const view = renderWithTheme(<BlocksView document={galleryOf(3)} />);
1243
+ for (const index of [0, 1, 2]) {
1244
+ const frame = view.getByTestId(`blocks-0-image-${index}-image`);
1245
+ expect(frame.findAllByType(NativeImage)).toHaveLength(1);
1246
+ expect(frame.findByType(NativeImage).props.accessibilityLabel).toBe(`Photo ${index + 1}`);
1247
+ }
1248
+ expect(view.queryByTestId("blocks-0-image-0-placeholder")).toBeNull();
1249
+ });
1250
+
1251
+ it("shows a caption as small muted text under its tile", () => {
1252
+ const view = renderWithTheme(<BlocksView document={galleryOf(2)} />);
1253
+ const caption = view.getByTestId("blocks-0-image-0-caption");
1254
+ expect(caption.props.children).toBe("Roast lamb");
1255
+ expect(view.queryByTestId("blocks-0-image-1-caption")).toBeNull();
1256
+ });
1257
+
1258
+ it("splits two images across the row as equal halves", async () => {
1259
+ const view = renderWithTheme(<BlocksView document={galleryOf(2)} />);
1260
+ await measure(view, "blocks-0", 408);
1261
+ expect(imageSizes(view)).toEqual([
1262
+ {height: 150, width: 200},
1263
+ {height: 150, width: 200},
1264
+ ]);
1265
+ });
1266
+
1267
+ it("wraps more than three images into a three-column grid", async () => {
1268
+ const view = renderWithTheme(<BlocksView document={galleryOf(5)} />);
1269
+ await measure(view, "blocks-0", 600);
1270
+ expect(tileIdsIn(view, "blocks-0-row-0")).toEqual([
1271
+ "blocks-0-image-0",
1272
+ "blocks-0-image-1",
1273
+ "blocks-0-image-2",
1274
+ ]);
1275
+ expect(tileIdsIn(view, "blocks-0-row-1")).toEqual(["blocks-0-image-3", "blocks-0-image-4"]);
1276
+ expect(imageSizes(view).every(({width}) => width === 194)).toBe(true);
1277
+ });
1278
+
1279
+ it("uses 160 wide tiles until the gallery is measured", () => {
1280
+ const view = renderWithTheme(<BlocksView document={galleryOf(3)} />);
1281
+ expect(imageSizes(view)[0]).toEqual({height: 120, width: 160});
1282
+ expect(view.getByTestId("blocks-0-row-0")).toBeTruthy();
1283
+ });
1284
+
1285
+ it("scrolls one row sideways when tiles would be narrower than 160", async () => {
1286
+ const view = renderWithTheme(<BlocksView document={galleryOf(5)} />);
1287
+ await measure(view, "blocks-0", 320);
1288
+ expect(view.queryByTestId("blocks-0-row-0")).toBeNull();
1289
+ expect(tileIdsIn(view, "blocks-0-scroll")).toHaveLength(5);
1290
+ expect(view.UNSAFE_getAllByType(ScrollView).some((node) => node.props.horizontal)).toBe(true);
1291
+ expect(imageSizes(view).every(({height, width}) => width === 160 && height === 120)).toBe(
1292
+ true
1293
+ );
1294
+ });
1295
+
1296
+ it("loads file: tiles inside a card through resolveImage and keeps an unresolved tile as a labelled placeholder", async () => {
1297
+ const document = `v: 1
1298
+ blocks:
1299
+ - type: card
1300
+ children:
1301
+ - type: gallery
1302
+ images:
1303
+ - src: file:table-setting
1304
+ alt: A table set for six
1305
+ - src: file:flowers
1306
+ alt: A jug of spring flowers
1307
+ `;
1308
+ const resolveImage = mock(async (id: string) =>
1309
+ id === "table-setting" ? "https://cdn.example/table.png" : undefined
1310
+ );
1311
+ const view = renderWithTheme(<BlocksView document={document} resolveImage={resolveImage} />);
1312
+ await waitFor(() => {
1313
+ expect(view.UNSAFE_getAllByType(NativeImage)).toHaveLength(1);
1314
+ });
1315
+ expect(resolveImage).toHaveBeenCalledWith("table-setting");
1316
+ expect(resolveImage).toHaveBeenCalledWith("flowers");
1317
+ const [loaded] = view.UNSAFE_getAllByType(NativeImage);
1318
+ expect(loaded?.props.source.uri).toBe("https://cdn.example/table.png");
1319
+ expect(loaded?.props.accessibilityLabel).toBe("A table set for six");
1320
+ const placeholder = view.getByTestId("blocks-0-0-image-1-placeholder");
1321
+ expect(placeholder.props.accessibilityLabel).toBe("A jug of spring flowers");
1322
+ expect(view.getByText("A jug of spring flowers")).toBeTruthy();
1323
+ });
1324
+ });
1325
+
1326
+ describe("list", () => {
1327
+ const PIXEL = "data:image/png;base64,iVBORw0KGgo=";
1328
+ const MENU = `v: 1
1329
+ blocks:
1330
+ - type: list
1331
+ id: menu
1332
+ items:
1333
+ - title: Roast leg of lamb
1334
+ text: Rubbed with garlic and rosemary.
1335
+ meta: Main
1336
+ image: {src: "${PIXEL}", alt: Roast leg of lamb on a carving board}
1337
+ - title: Crisp potatoes
1338
+ image: {src: "${PIXEL}", alt: Crisp roast potatoes in a tray}
1339
+ `;
1340
+ const textProps = (
1341
+ view: RenderedView,
1342
+ testID: string
1343
+ ): {bold?: boolean; children?: unknown; color?: string; size?: string} => {
1344
+ // `Text` is memoized, so the outermost node with the testID carries the props the renderer passed.
1345
+ const [node] = view.UNSAFE_root.findAll((candidate) => candidate.props.testID === testID);
1346
+ if (node === undefined) {
1347
+ throw new Error(`No Text with testID ${testID}`);
1348
+ }
1349
+ return node.props;
1350
+ };
1351
+ // Composite and host nodes share a testID, so ids are deduplicated in render order.
1352
+ const idsIn = (view: RenderedView, testID: string, pattern: RegExp): string[] => [
1353
+ ...new Set(
1354
+ view
1355
+ .getByTestId(testID)
1356
+ .findAll((node) => typeof node.props.testID === "string")
1357
+ .map((node) => String(node.props.testID))
1358
+ .filter((id) => pattern.test(id))
1359
+ ),
1360
+ ];
1361
+
1362
+ it("draws each item as a 112 by 149 (3:4) @terreno/ui Image left of the title, with alt as the accessible label", () => {
1363
+ const view = renderWithTheme(<BlocksView document={MENU} />);
1364
+ expect(view.UNSAFE_getAllByType(Image)).toHaveLength(2);
1365
+ const images = view.UNSAFE_getAllByType(NativeImage);
1366
+ expect(images.map((node) => node.props.accessibilityLabel)).toEqual([
1367
+ "Roast leg of lamb on a carving board",
1368
+ "Crisp roast potatoes in a tray",
1369
+ ]);
1370
+ expect(images.every((node) => node.props.source.uri === PIXEL)).toBe(true);
1371
+ expect(
1372
+ images.map((node) => {
1373
+ const {height, width} = StyleSheet.flatten(node.props.style) as {
1374
+ height?: number;
1375
+ width?: number;
1376
+ };
1377
+ return {height, width};
1378
+ })
1379
+ ).toEqual([
1380
+ {height: 149, width: 112},
1381
+ {height: 149, width: 112},
1382
+ ]);
1383
+ expect(idsIn(view, "blocks-0-item-0", /^blocks-0-item-0-(image|body)$/)).toEqual([
1384
+ "blocks-0-item-0-image",
1385
+ "blocks-0-item-0-body",
1386
+ ]);
1387
+ });
1388
+
1389
+ it("shows the meta small and muted above a bold title, then muted plain text", () => {
1390
+ const view = renderWithTheme(<BlocksView document={MENU} />);
1391
+ expect(idsIn(view, "blocks-0-item-0-body", /^blocks-0-item-0-(meta|title|text)$/)).toEqual([
1392
+ "blocks-0-item-0-meta",
1393
+ "blocks-0-item-0-title",
1394
+ "blocks-0-item-0-text",
1395
+ ]);
1396
+ expect(textProps(view, "blocks-0-item-0-meta")).toMatchObject({
1397
+ children: "Main",
1398
+ color: "secondaryLight",
1399
+ size: "sm",
1400
+ });
1401
+ expect(textProps(view, "blocks-0-item-0-title")).toMatchObject({
1402
+ bold: true,
1403
+ children: "Roast leg of lamb",
1404
+ });
1405
+ expect(textProps(view, "blocks-0-item-0-text")).toMatchObject({
1406
+ children: "Rubbed with garlic and rosemary.",
1407
+ color: "secondaryLight",
1408
+ });
1409
+ expect(view.queryByTestId("blocks-0-item-1-meta")).toBeNull();
1410
+ expect(view.queryByTestId("blocks-0-item-1-text")).toBeNull();
1411
+ });
1412
+
1413
+ it("draws item text as plain text, not markdown", () => {
1414
+ const document = `v: 1
1415
+ blocks:
1416
+ - type: list
1417
+ items:
1418
+ - title: Mint sauce
1419
+ text: "**Fresh** mint, sugar, and vinegar"
1420
+ `;
1421
+ const view = renderWithTheme(<BlocksView document={document} />);
1422
+ expect(textProps(view, "blocks-0-item-0-text").children).toBe(
1423
+ "**Fresh** mint, sugar, and vinegar"
1424
+ );
1425
+ expect(view.UNSAFE_queryAllByType(MarkdownView)).toHaveLength(0);
1426
+ });
1427
+
1428
+ it("keeps a 112 wide gutter for an item without an image when another item has one, so titles line up", () => {
1429
+ const document = `v: 1
1430
+ blocks:
1431
+ - type: list
1432
+ items:
1433
+ - title: Roast leg of lamb
1434
+ image: {src: "${PIXEL}", alt: Roast leg of lamb}
1435
+ - title: Mint sauce
1436
+ `;
1437
+ const view = renderWithTheme(<BlocksView document={document} />);
1438
+ expect(view.queryByTestId("blocks-0-item-1-image")).toBeNull();
1439
+ const gutter = view.getByTestId("blocks-0-item-1-gutter");
1440
+ expect(StyleSheet.flatten(gutter.props.style)).toMatchObject({width: 112});
1441
+ expect(view.queryByTestId("blocks-0-item-0-gutter")).toBeNull();
1442
+ });
1443
+
1444
+ it("draws a list with no images as text only, with no gutter", () => {
1445
+ const document = `v: 1
1446
+ blocks:
1447
+ - type: list
1448
+ items:
1449
+ - title: Mint sauce
1450
+ - title: Redcurrant jelly
1451
+ `;
1452
+ const view = renderWithTheme(<BlocksView document={document} />);
1453
+ expect(view.UNSAFE_queryAllByType(Image)).toHaveLength(0);
1454
+ expect(view.queryByTestId("blocks-0-item-0-gutter")).toBeNull();
1455
+ expect(view.queryByTestId("blocks-0-item-1-gutter")).toBeNull();
1456
+ expect(textProps(view, "blocks-0-item-1-title").children).toBe("Redcurrant jelly");
1457
+ });
1458
+
1459
+ it("loads file: thumbnails inside a card through resolveImage and keeps an unresolved one as a labelled 3:4 placeholder", async () => {
1460
+ const document = `v: 1
1461
+ blocks:
1462
+ - type: card
1463
+ children:
1464
+ - type: list
1465
+ items:
1466
+ - title: Roast leg of lamb
1467
+ image: {src: "file:roast-lamb", alt: Roast leg of lamb on a carving board}
1468
+ - title: Apple crumble
1469
+ image: {src: "file:crumble", alt: Apple crumble with custard}
1470
+ `;
1471
+ const resolveImage = mock(async (id: string) =>
1472
+ id === "roast-lamb" ? "https://cdn.example/lamb.png" : undefined
1473
+ );
1474
+ const view = renderWithTheme(<BlocksView document={document} resolveImage={resolveImage} />);
1475
+ await waitFor(() => {
1476
+ expect(view.UNSAFE_getAllByType(NativeImage)).toHaveLength(1);
1477
+ });
1478
+ expect(resolveImage).toHaveBeenCalledWith("roast-lamb");
1479
+ expect(resolveImage).toHaveBeenCalledWith("crumble");
1480
+ const [loaded] = view.UNSAFE_getAllByType(NativeImage);
1481
+ expect(loaded?.props.source.uri).toBe("https://cdn.example/lamb.png");
1482
+ expect(loaded?.props.accessibilityLabel).toBe("Roast leg of lamb on a carving board");
1483
+ const placeholder = view.getByTestId("blocks-0-0-item-1-placeholder");
1484
+ expect(placeholder.props.accessibilityLabel).toBe("Apple crumble with custard");
1485
+ expect(StyleSheet.flatten(placeholder.props.style)).toMatchObject({height: 149, width: 112});
1486
+ expect(view.getByText("Apple crumble with custard")).toBeTruthy();
1487
+ });
1488
+ });
1489
+
1490
+ describe("copy", () => {
1491
+ const mockedSetStringAsync = setStringAsync as unknown as ReturnType<typeof mock>;
1492
+ const COPY_DOC = `v: 1
1493
+ datasets:
1494
+ cuts:
1495
+ columns:
1496
+ - {name: cut, type: string}
1497
+ - {name: kg, type: number}
1498
+ rows:
1499
+ - [Leg, 2.4]
1500
+ - [Shoulder, 2]
1501
+ prices:
1502
+ source: ref
1503
+ id: ds_prices
1504
+ blocks:
1505
+ ${STEPPER.split("blocks:\n")[1]} - type: checklist
1506
+ id: cooking
1507
+ items:
1508
+ - {id: oven, text: Preheat the oven, checked: true}
1509
+ - {id: lamb_in, text: Put the lamb in}
1510
+ - type: table
1511
+ id: cuts_table
1512
+ data: cuts
1513
+ - type: table
1514
+ id: price_table
1515
+ data: prices
1516
+ - type: actions
1517
+ id: copy_actions
1518
+ elements:
1519
+ - {type: button, id: copy_list, text: Copy shopping list, action: {kind: copy, target: guests}}
1520
+ - {type: button, id: copy_note, text: Copy note, action: {kind: copy, text: Bring a bottle of red}}
1521
+ - {type: button, id: copy_steps, text: Copy steps, action: {kind: copy, target: cooking}}
1522
+ - {type: button, id: copy_cuts, text: Copy cuts, action: {kind: copy, target: cuts_table}}
1523
+ - {type: button, id: copy_prices, text: Copy prices, action: {kind: copy, target: price_table}}
1524
+ `;
1525
+ const SIX_GUESTS: Block = {
1526
+ callback: {name: "scaleStepper"},
1527
+ id: "guests",
1528
+ items: [
1529
+ {amount: 2.4, decimals: 1, label: "Bone-in leg of lamb", unit: "kg"},
1530
+ {amount: 10, label: "Carrots", round: "up"},
1531
+ ],
1532
+ label: "Number of people",
1533
+ max: 20,
1534
+ min: 1,
1535
+ type: "stepper",
1536
+ unit: "People",
1537
+ value: 6,
1538
+ };
1539
+ const status = (view: RenderedView, elementId: string): string | undefined => {
1540
+ const text = view.queryByTestId(`blocks-4-${elementId}-status-text`);
1541
+ return text === null ? undefined : String(text.props.children);
1542
+ };
1543
+ // Flushes the haptic and clipboard promises without real timers, so fake timers can run.
1544
+ const pressCopy = async (view: RenderedView, elementId: string): Promise<void> => {
1545
+ await act(async () => {
1546
+ fireEvent.press(view.getByTestId(`blocks-4-${elementId}`));
1547
+ for (let index = 0; index < 50; index += 1) {
1548
+ await Promise.resolve();
1549
+ }
1550
+ });
1551
+ };
1552
+
1553
+ afterEach(() => {
1554
+ jest.useRealTimers();
1555
+ mockedSetStringAsync.mockClear();
1556
+ });
1557
+
1558
+ it("copies the scaled shopping list from a stepper at 6 and shows Copied, without calling onAction", async () => {
1559
+ const onAction = mock(() => undefined);
1560
+ const view = renderWithTheme(
1561
+ <BlocksView
1562
+ document={COPY_DOC}
1563
+ hostActions={["scaleStepper"]}
1564
+ onAction={onAction}
1565
+ overrides={{guests: SIX_GUESTS}}
1566
+ />
1567
+ );
1568
+ expect(status(view, "copy_list")).toBeUndefined();
1569
+ await pressCopy(view, "copy_list");
1570
+ expect(mockedSetStringAsync).toHaveBeenCalledTimes(1);
1571
+ expect(mockedSetStringAsync).toHaveBeenCalledWith(
1572
+ "Number of people: 6 People\nBone-in leg of lamb: 2.4 kg\nCarrots: 10"
1573
+ );
1574
+ expect(status(view, "copy_list")).toBe("Copied");
1575
+ expect(onAction).not.toHaveBeenCalled();
1576
+ });
1577
+
1578
+ it("copies the override that arrived after the first render", async () => {
1579
+ const view = renderWithTheme(
1580
+ <BlocksView document={COPY_DOC} hostActions={["scaleStepper"]} />
1581
+ );
1582
+ view.rerender(
1583
+ <BlocksView
1584
+ document={COPY_DOC}
1585
+ hostActions={["scaleStepper"]}
1586
+ overrides={{guests: SIX_GUESTS}}
1587
+ />
1588
+ );
1589
+ await pressCopy(view, "copy_list");
1590
+ expect(mockedSetStringAsync).toHaveBeenCalledWith(
1591
+ "Number of people: 6 People\nBone-in leg of lamb: 2.4 kg\nCarrots: 10"
1592
+ );
1593
+ });
1594
+
1595
+ it("announces the status in a polite live region", async () => {
1596
+ const view = renderWithTheme(<BlocksView document={COPY_DOC} />);
1597
+ expect(view.getByTestId("blocks-4-copy_note-status").props["aria-live"]).toBe("polite");
1598
+ await pressCopy(view, "copy_note");
1599
+ expect(status(view, "copy_note")).toBe("Copied");
1600
+ expect(view.getByTestId("blocks-4-copy_note-status").props["aria-live"]).toBe("polite");
1601
+ });
1602
+
1603
+ it("copies literal text", async () => {
1604
+ const view = renderWithTheme(<BlocksView document={COPY_DOC} />);
1605
+ await pressCopy(view, "copy_note");
1606
+ expect(mockedSetStringAsync).toHaveBeenCalledWith("Bring a bottle of red");
1607
+ });
1608
+
1609
+ it("copies a checklist with the ticks made on the device", async () => {
1610
+ const view = renderWithTheme(<BlocksView document={COPY_DOC} />);
1611
+ await press(view.getByTestId("blocks-1-cooking_lamb_in-row-clickable"));
1612
+ await press(view.getByTestId("blocks-1-cooking_oven-row-clickable"));
1613
+ await pressCopy(view, "copy_steps");
1614
+ expect(mockedSetStringAsync).toHaveBeenCalledWith(
1615
+ "[ ] Preheat the oven\n[x] Put the lamb in"
1616
+ );
1617
+ });
1618
+
1619
+ it("copies an inline table and a ref table once resolveDataset returns its rows", async () => {
1620
+ const resolveDataset = mock(async () => ({
1621
+ columns: [
1622
+ {name: "cut", type: "string" as const},
1623
+ {name: "price", type: "number" as const},
1624
+ ],
1625
+ rows: [["Leg", 32]],
1626
+ }));
1627
+ const view = renderWithTheme(
1628
+ <BlocksView document={COPY_DOC} resolveDataset={resolveDataset} />
1629
+ );
1630
+ await waitFor(() => {
1631
+ expect(view.getByText("32")).toBeTruthy();
1632
+ });
1633
+ await pressCopy(view, "copy_cuts");
1634
+ expect(mockedSetStringAsync).toHaveBeenLastCalledWith("cut\tkg\nLeg\t2.4\nShoulder\t2");
1635
+ await pressCopy(view, "copy_prices");
1636
+ expect(mockedSetStringAsync).toHaveBeenLastCalledWith("cut\tprice\nLeg\t32");
1637
+ });
1638
+
1639
+ it("shows Couldn't copy when the clipboard write fails, and does not throw", async () => {
1640
+ const warn = jest.spyOn(console, "warn").mockImplementation(() => {});
1641
+ mockedSetStringAsync.mockImplementationOnce(() => Promise.reject(new Error("denied")));
1642
+ const view = renderWithTheme(<BlocksView document={COPY_DOC} />);
1643
+ await pressCopy(view, "copy_note");
1644
+ expect(status(view, "copy_note")).toBe("Couldn't copy");
1645
+ expect(warn).toHaveBeenCalled();
1646
+ warn.mockRestore();
1647
+ });
1648
+
1649
+ it("shows Couldn't copy without writing when a ref table has no rows yet", async () => {
1650
+ const warn = jest.spyOn(console, "warn").mockImplementation(() => {});
1651
+ const view = renderWithTheme(<BlocksView document={COPY_DOC} />);
1652
+ await pressCopy(view, "copy_prices");
1653
+ expect(mockedSetStringAsync).not.toHaveBeenCalled();
1654
+ expect(status(view, "copy_prices")).toBe("Couldn't copy");
1655
+ warn.mockRestore();
1656
+ });
1657
+
1658
+ it("clears Copied after 2 seconds and cancels the timer on unmount", async () => {
1659
+ jest.useFakeTimers();
1660
+ const view = renderWithTheme(<BlocksView document={COPY_DOC} />);
1661
+ await pressCopy(view, "copy_note");
1662
+ expect(status(view, "copy_note")).toBe("Copied");
1663
+ act(() => {
1664
+ jest.advanceTimersByTime(1999);
1665
+ });
1666
+ expect(status(view, "copy_note")).toBe("Copied");
1667
+ act(() => {
1668
+ jest.advanceTimersByTime(1);
1669
+ });
1670
+ expect(status(view, "copy_note")).toBeUndefined();
1671
+ view.unmount();
1672
+
1673
+ // A fresh view: the Button press cooldown reads Date.now, which fake timers do not move.
1674
+ const setTimeoutSpy = jest.spyOn(globalThis, "setTimeout");
1675
+ const clearTimeoutSpy = jest.spyOn(globalThis, "clearTimeout");
1676
+ const unmounted = renderWithTheme(<BlocksView document={COPY_DOC} />);
1677
+ await pressCopy(unmounted, "copy_note");
1678
+ expect(status(unmounted, "copy_note")).toBe("Copied");
1679
+ // The status timer is the 2 second one; other components may hold their own timers.
1680
+ const statusTimerIndex = setTimeoutSpy.mock.calls.findIndex(([, delay]) => delay === 2000);
1681
+ expect(statusTimerIndex).toBeGreaterThanOrEqual(0);
1682
+ const statusTimer = setTimeoutSpy.mock.results[statusTimerIndex]?.value;
1683
+ unmounted.unmount();
1684
+ expect(clearTimeoutSpy.mock.calls.some(([id]) => id === statusTimer)).toBe(true);
1685
+ setTimeoutSpy.mockRestore();
1686
+ clearTimeoutSpy.mockRestore();
1687
+ });
1688
+
1689
+ it("keeps copy buttons enabled when hostActions is passed", () => {
1690
+ const view = renderWithTheme(<BlocksView document={COPY_DOC} hostActions={[]} />);
1691
+ expect(view.getByTestId("blocks-4-copy_list").props.accessibilityState.disabled).toBe(false);
1692
+ });
1693
+ });
1694
+
596
1695
  it("does not use raw react-native views in the blocks folder", () => {
597
1696
  const dir = import.meta.dir;
598
1697
  const files = readdirSync(dir).filter(