@terreno/ui 57.9.0 → 57.10.1

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 (162) hide show
  1. package/README.md +2 -0
  2. package/dist/Button.d.ts.map +1 -1
  3. package/dist/Button.js +19 -4
  4. package/dist/Button.js.map +1 -1
  5. package/dist/Common.d.ts +68 -1
  6. package/dist/Common.d.ts.map +1 -1
  7. package/dist/Common.js.map +1 -1
  8. package/dist/DateTimeField.d.ts.map +1 -1
  9. package/dist/DateTimeField.js +90 -17
  10. package/dist/DateTimeField.js.map +1 -1
  11. package/dist/FilePickerButton.d.ts +15 -1
  12. package/dist/FilePickerButton.d.ts.map +1 -1
  13. package/dist/FilePickerButton.js +26 -9
  14. package/dist/FilePickerButton.js.map +1 -1
  15. package/dist/GPTChat.d.ts +57 -1
  16. package/dist/GPTChat.d.ts.map +1 -1
  17. package/dist/GPTChat.js +199 -7
  18. package/dist/GPTChat.js.map +1 -1
  19. package/dist/HtmlFrame.d.ts +11 -0
  20. package/dist/HtmlFrame.d.ts.map +1 -0
  21. package/dist/HtmlFrame.js +29 -0
  22. package/dist/HtmlFrame.js.map +1 -0
  23. package/dist/Text.d.ts +1 -1
  24. package/dist/Text.d.ts.map +1 -1
  25. package/dist/Text.js +2 -2
  26. package/dist/Text.js.map +1 -1
  27. package/dist/asks/AskCard.d.ts +34 -0
  28. package/dist/asks/AskCard.d.ts.map +1 -0
  29. package/dist/asks/AskCard.js +91 -0
  30. package/dist/asks/AskCard.js.map +1 -0
  31. package/dist/asks/AskChoice.d.ts +11 -0
  32. package/dist/asks/AskChoice.d.ts.map +1 -0
  33. package/dist/asks/AskChoice.js +146 -0
  34. package/dist/asks/AskChoice.js.map +1 -0
  35. package/dist/asks/AskConfirm.d.ts +15 -0
  36. package/dist/asks/AskConfirm.d.ts.map +1 -0
  37. package/dist/asks/AskConfirm.js +17 -0
  38. package/dist/asks/AskConfirm.js.map +1 -0
  39. package/dist/asks/AskFiles.d.ts +18 -0
  40. package/dist/asks/AskFiles.d.ts.map +1 -0
  41. package/dist/asks/AskFiles.js +149 -0
  42. package/dist/asks/AskFiles.js.map +1 -0
  43. package/dist/asks/AskForm.d.ts +27 -0
  44. package/dist/asks/AskForm.d.ts.map +1 -0
  45. package/dist/asks/AskForm.js +146 -0
  46. package/dist/asks/AskForm.js.map +1 -0
  47. package/dist/asks/AskMarkdown.d.ts +25 -0
  48. package/dist/asks/AskMarkdown.d.ts.map +1 -0
  49. package/dist/asks/AskMarkdown.js +73 -0
  50. package/dist/asks/AskMarkdown.js.map +1 -0
  51. package/dist/asks/SimpleAskCard.d.ts +23 -0
  52. package/dist/asks/SimpleAskCard.d.ts.map +1 -0
  53. package/dist/asks/SimpleAskCard.js +32 -0
  54. package/dist/asks/SimpleAskCard.js.map +1 -0
  55. package/dist/asks/askControls.d.ts +33 -0
  56. package/dist/asks/askControls.d.ts.map +1 -0
  57. package/dist/asks/askControls.js +30 -0
  58. package/dist/asks/askControls.js.map +1 -0
  59. package/dist/asks/askFileRefs.d.ts +26 -0
  60. package/dist/asks/askFileRefs.d.ts.map +1 -0
  61. package/dist/asks/askFileRefs.js +75 -0
  62. package/dist/asks/askFileRefs.js.map +1 -0
  63. package/dist/asks/askFormDraft.d.ts +60 -0
  64. package/dist/asks/askFormDraft.d.ts.map +1 -0
  65. package/dist/asks/askFormDraft.js +224 -0
  66. package/dist/asks/askFormDraft.js.map +1 -0
  67. package/dist/asks/askSummary.d.ts +10 -0
  68. package/dist/asks/askSummary.d.ts.map +1 -0
  69. package/dist/asks/askSummary.js +138 -0
  70. package/dist/asks/askSummary.js.map +1 -0
  71. package/dist/asks/askTypes.d.ts +21 -0
  72. package/dist/asks/askTypes.d.ts.map +1 -0
  73. package/dist/asks/askTypes.js +2 -0
  74. package/dist/asks/askTypes.js.map +1 -0
  75. package/dist/asks/simpleCardButtonVariants.d.ts +5 -0
  76. package/dist/asks/simpleCardButtonVariants.d.ts.map +1 -0
  77. package/dist/asks/simpleCardButtonVariants.js +8 -0
  78. package/dist/asks/simpleCardButtonVariants.js.map +1 -0
  79. package/dist/blocks/BlocksError.d.ts +8 -0
  80. package/dist/blocks/BlocksError.d.ts.map +1 -0
  81. package/dist/blocks/BlocksError.js +14 -0
  82. package/dist/blocks/BlocksError.js.map +1 -0
  83. package/dist/blocks/BlocksView.d.ts +10 -0
  84. package/dist/blocks/BlocksView.d.ts.map +1 -0
  85. package/dist/blocks/BlocksView.js +90 -0
  86. package/dist/blocks/BlocksView.js.map +1 -0
  87. package/dist/blocks/blockRenderers.d.ts +25 -0
  88. package/dist/blocks/blockRenderers.d.ts.map +1 -0
  89. package/dist/blocks/blockRenderers.js +136 -0
  90. package/dist/blocks/blockRenderers.js.map +1 -0
  91. package/dist/blocks/datasetToPoints.d.ts +22 -0
  92. package/dist/blocks/datasetToPoints.d.ts.map +1 -0
  93. package/dist/blocks/datasetToPoints.js +28 -0
  94. package/dist/blocks/datasetToPoints.js.map +1 -0
  95. package/dist/blocks/useBlockSelections.d.ts +6 -0
  96. package/dist/blocks/useBlockSelections.d.ts.map +1 -0
  97. package/dist/blocks/useBlockSelections.js +10 -0
  98. package/dist/blocks/useBlockSelections.js.map +1 -0
  99. package/dist/blocks/useResolvedDatasets.d.ts +18 -0
  100. package/dist/blocks/useResolvedDatasets.d.ts.map +1 -0
  101. package/dist/blocks/useResolvedDatasets.js +59 -0
  102. package/dist/blocks/useResolvedDatasets.js.map +1 -0
  103. package/dist/blocks/useResolvedImages.d.ts +15 -0
  104. package/dist/blocks/useResolvedImages.d.ts.map +1 -0
  105. package/dist/blocks/useResolvedImages.js +66 -0
  106. package/dist/blocks/useResolvedImages.js.map +1 -0
  107. package/dist/index.d.ts +6 -1
  108. package/dist/index.d.ts.map +1 -1
  109. package/dist/index.js +4 -1
  110. package/dist/index.js.map +1 -1
  111. package/dist/lazyBoundaries/heavyOptionalExports.d.ts +6 -0
  112. package/dist/lazyBoundaries/heavyOptionalExports.d.ts.map +1 -1
  113. package/dist/lazyBoundaries/heavyOptionalExports.js +4 -0
  114. package/dist/lazyBoundaries/heavyOptionalExports.js.map +1 -1
  115. package/package.json +2 -1
  116. package/src/Button.test.tsx +72 -0
  117. package/src/Button.tsx +34 -4
  118. package/src/Common.ts +67 -0
  119. package/src/DateTimeField.test.tsx +185 -2
  120. package/src/DateTimeField.tsx +106 -16
  121. package/src/DonutChart.test.tsx +5 -10
  122. package/src/FilePickerButton.test.tsx +56 -3
  123. package/src/FilePickerButton.tsx +83 -17
  124. package/src/GPTChat.test.tsx +758 -2
  125. package/src/GPTChat.tsx +517 -7
  126. package/src/HtmlFrame.tsx +60 -0
  127. package/src/LineChart.test.tsx +5 -10
  128. package/src/Text.test.tsx +22 -0
  129. package/src/Text.tsx +10 -1
  130. package/src/asks/AskCard.test.tsx +1428 -0
  131. package/src/asks/AskCard.tsx +240 -0
  132. package/src/asks/AskChoice.tsx +368 -0
  133. package/src/asks/AskConfirm.tsx +42 -0
  134. package/src/asks/AskFiles.test.tsx +347 -0
  135. package/src/asks/AskFiles.tsx +246 -0
  136. package/src/asks/AskForm.tsx +334 -0
  137. package/src/asks/AskMarkdown.tsx +176 -0
  138. package/src/asks/SimpleAskCard.test.tsx +253 -0
  139. package/src/asks/SimpleAskCard.tsx +82 -0
  140. package/src/asks/askControls.tsx +98 -0
  141. package/src/asks/askFileRefs.test.ts +155 -0
  142. package/src/asks/askFileRefs.ts +98 -0
  143. package/src/asks/askFormDraft.test.ts +347 -0
  144. package/src/asks/askFormDraft.ts +309 -0
  145. package/src/asks/askSummary.test.ts +255 -0
  146. package/src/asks/askSummary.ts +160 -0
  147. package/src/asks/askTypes.ts +25 -0
  148. package/src/asks/asksUseTerrenoComponents.test.ts +55 -0
  149. package/src/asks/simpleCardButtonVariants.ts +14 -0
  150. package/src/blocks/BlocksError.tsx +28 -0
  151. package/src/blocks/BlocksView.test.tsx +607 -0
  152. package/src/blocks/BlocksView.tsx +125 -0
  153. package/src/blocks/blockRenderers.tsx +288 -0
  154. package/src/blocks/datasetToPoints.test.ts +31 -0
  155. package/src/blocks/datasetToPoints.ts +48 -0
  156. package/src/blocks/useBlockSelections.ts +13 -0
  157. package/src/blocks/useResolvedDatasets.ts +78 -0
  158. package/src/blocks/useResolvedImages.ts +81 -0
  159. package/src/index.tsx +7 -0
  160. package/src/isolated/HtmlFrame.isolated.tsx +54 -0
  161. package/src/lazyBoundaries/heavyOptionalExports.test.tsx +2 -0
  162. package/src/lazyBoundaries/heavyOptionalExports.tsx +14 -0
@@ -0,0 +1,125 @@
1
+ import {type Block, parseBlocks, validateBlocks, wrapAsTextDocument} from "@terreno/blocks";
2
+ import type React from "react";
3
+
4
+ import {Box} from "../Box";
5
+ import type {BlocksViewProps} from "../Common";
6
+ import {Spinner} from "../Spinner";
7
+ import {BlocksError} from "./BlocksError";
8
+ import {type BlockRenderContext, renderBlock} from "./blockRenderers";
9
+ import {useBlockSelections} from "./useBlockSelections";
10
+ import {useResolvedDatasets} from "./useResolvedDatasets";
11
+ import {useResolvedImages} from "./useResolvedImages";
12
+
13
+ export type {BlocksViewProps} from "../Common";
14
+
15
+ const rawOf = (document: BlocksViewProps["document"]): string => {
16
+ if (typeof document === "string") {
17
+ return document;
18
+ }
19
+ return JSON.stringify(document);
20
+ };
21
+
22
+ const renderBlocks = (
23
+ blocks: readonly Block[],
24
+ context: BlockRenderContext,
25
+ testID: string | undefined
26
+ ): React.ReactElement => (
27
+ <Box gap={3} testID={testID}>
28
+ {blocks.map((block, index) => renderBlock(block, `blocks-${index}`, context))}
29
+ </Box>
30
+ );
31
+
32
+ /** A draft that is still streaming should not flash a validation banner the server may still correct. */
33
+ const StreamingBlocks = ({testID}: {testID?: string}): React.ReactElement => (
34
+ <Box testID={testID}>
35
+ <Spinner size="sm" />
36
+ </Box>
37
+ );
38
+
39
+ /**
40
+ * Renders a whole-reply block document.
41
+ * A reply that is not a document becomes one text block. An invalid document shows
42
+ * the first errors and keeps the raw text collapsed.
43
+ */
44
+ export const BlocksView: React.FC<BlocksViewProps> = ({
45
+ allowHtml = false,
46
+ document,
47
+ hostActions,
48
+ imageHosts,
49
+ onAction,
50
+ overrides,
51
+ pendingElementIds,
52
+ resolveDataset,
53
+ resolveImage,
54
+ streaming = false,
55
+ testID,
56
+ }) => {
57
+ const parsed =
58
+ typeof document === "string" ? parseBlocks(document) : {ok: true as const, value: document};
59
+ const validated = parsed.ok
60
+ ? validateBlocks(parsed.value, {
61
+ allowHtml: true,
62
+ ...(imageHosts ? {imageHosts} : {}),
63
+ })
64
+ : undefined;
65
+ const {loadingIds, resolved} = useResolvedDatasets({
66
+ datasets: validated?.ok ? validated.doc.datasets : undefined,
67
+ resolveDataset,
68
+ });
69
+ const {selections, setSelection} = useBlockSelections();
70
+ const resolvedImages = useResolvedImages({
71
+ blocks: validated?.ok ? validated.doc.blocks : undefined,
72
+ resolveImage,
73
+ });
74
+ const boundData: Record<string, string> = {};
75
+ if (validated?.ok) {
76
+ const visit = (blocks: readonly Block[]): void => {
77
+ for (const block of blocks) {
78
+ if (
79
+ (block.type === "chart" || block.type === "table") &&
80
+ block.id !== undefined &&
81
+ block.data !== undefined
82
+ ) {
83
+ boundData[block.id] = block.data;
84
+ }
85
+ if (block.type === "columns" || block.type === "card") {
86
+ visit(block.children);
87
+ }
88
+ }
89
+ };
90
+ visit(validated.doc.blocks);
91
+ }
92
+ const context: BlockRenderContext = {
93
+ allowHtml,
94
+ boundData,
95
+ hostActions,
96
+ loadingIds,
97
+ onAction,
98
+ overrides,
99
+ pendingElementIds: pendingElementIds === undefined ? undefined : new Set(pendingElementIds),
100
+ resolved,
101
+ resolvedImages,
102
+ selections,
103
+ setSelection,
104
+ streaming,
105
+ };
106
+
107
+ if (typeof document === "string" && !parsed.ok) {
108
+ const isNonDocument = parsed.errors.every((error) => error.code === "NOT_A_DOCUMENT");
109
+ if (isNonDocument) {
110
+ return renderBlocks(wrapAsTextDocument(document).blocks, context, testID);
111
+ }
112
+ if (streaming) {
113
+ return <StreamingBlocks testID={testID} />;
114
+ }
115
+ return <BlocksError errors={parsed.errors} raw={document} testID={testID} />;
116
+ }
117
+ if (validated === undefined || !validated.ok) {
118
+ if (streaming) {
119
+ return <StreamingBlocks testID={testID} />;
120
+ }
121
+ const errors = validated === undefined ? [] : validated.errors;
122
+ return <BlocksError errors={errors} raw={rawOf(document)} testID={testID} />;
123
+ }
124
+ return renderBlocks(validated.doc.blocks, context, testID);
125
+ };
@@ -0,0 +1,288 @@
1
+ import type {Block, BlockAction, InlineDataset} from "@terreno/blocks";
2
+ import type React from "react";
3
+
4
+ import {Accordion} from "../Accordion";
5
+ import {AreaChart} from "../AreaChart";
6
+ import {Badge} from "../Badge";
7
+ import {Banner} from "../Banner";
8
+ import {BarChart} from "../BarChart";
9
+ import {Box} from "../Box";
10
+ import {Button} from "../Button";
11
+ import {Card} from "../Card";
12
+ import {DataTable} from "../DataTable";
13
+ import {DonutChart} from "../DonutChart";
14
+ import {Heading} from "../Heading";
15
+ import {HtmlFrame} from "../HtmlFrame";
16
+ import {Image} from "../Image";
17
+ import {LineChart} from "../LineChart";
18
+ import {MarkdownView} from "../MarkdownView";
19
+ import {SectionDivider} from "../SectionDivider";
20
+ import {SegmentedControl} from "../SegmentedControl";
21
+ import {Text} from "../Text";
22
+ import {chartHeight, chartPoints, datasetToPoints} from "./datasetToPoints";
23
+ import {fileRefId} from "./useResolvedImages";
24
+
25
+ export interface BlockRenderContext {
26
+ allowHtml?: boolean;
27
+ hostActions?: readonly string[];
28
+ streaming?: boolean;
29
+ loadingIds: ReadonlySet<string>;
30
+ onAction?: (event: {action: BlockAction; blockId: string; elementId: string}) => void;
31
+ overrides?: Record<string, Block>;
32
+ pendingElementIds?: ReadonlySet<string>;
33
+ resolved: Record<string, InlineDataset | undefined>;
34
+ /** URLs for `file:` image ids. An unset id is not passed to `Image`. */
35
+ resolvedImages?: Record<string, string | undefined>;
36
+ /** Dataset name currently bound on a chart or table id, before any local selection. */
37
+ boundData?: Record<string, string>;
38
+ selections: Record<string, string>;
39
+ setSelection: (target: string, data: string) => void;
40
+ }
41
+
42
+ const EMPTY_CONTEXT: BlockRenderContext = {
43
+ loadingIds: new Set(),
44
+ resolved: {},
45
+ selections: {},
46
+ setSelection: () => {},
47
+ };
48
+
49
+ const trendMark = {
50
+ down: "▼",
51
+ flat: "–",
52
+ up: "▲",
53
+ } as const;
54
+
55
+ const renderChildren = (
56
+ children: readonly Block[],
57
+ path: string,
58
+ context: BlockRenderContext
59
+ ): React.ReactElement[] =>
60
+ children.map((child, index) => renderBlock(child, `${path}-${index}`, context));
61
+
62
+ const chartFor = {
63
+ area: AreaChart,
64
+ bar: BarChart,
65
+ donut: DonutChart,
66
+ line: LineChart,
67
+ } as const;
68
+
69
+ /** Renders one catalog block with @terreno/ui components. */
70
+ export const renderBlock = (
71
+ block: Block,
72
+ path: string,
73
+ context: BlockRenderContext = EMPTY_CONTEXT,
74
+ allowOverride = true
75
+ ): React.ReactElement => {
76
+ if (allowOverride && block.id !== undefined && context.overrides?.[block.id] !== undefined) {
77
+ return renderBlock(context.overrides[block.id], path, context, false);
78
+ }
79
+ switch (block.type) {
80
+ case "heading":
81
+ return (
82
+ <Heading key={path} size={block.size} testID={path}>
83
+ {block.text}
84
+ </Heading>
85
+ );
86
+ case "text":
87
+ return (
88
+ <Box key={path} testID={path}>
89
+ <MarkdownView>{block.markdown}</MarkdownView>
90
+ </Box>
91
+ );
92
+ case "metric":
93
+ return (
94
+ <Card key={path} testID={path}>
95
+ <Text size="sm">{block.label}</Text>
96
+ <Heading>{block.value}</Heading>
97
+ {block.delta || block.trend ? (
98
+ <Text>{`${block.trend ? `${trendMark[block.trend]} ` : ""}${block.delta ?? ""}`}</Text>
99
+ ) : null}
100
+ {block.helper ? (
101
+ <Text color="secondaryLight" size="sm">
102
+ {block.helper}
103
+ </Text>
104
+ ) : null}
105
+ </Card>
106
+ );
107
+ case "badge":
108
+ return <Badge key={path} status={block.status ?? "info"} testID={path} value={block.text} />;
109
+ case "html":
110
+ if (context.streaming || context.allowHtml !== true) {
111
+ return (
112
+ <Card key={path} testID={path}>
113
+ <Text size="sm">Agent-generated preview</Text>
114
+ <Text>
115
+ {context.streaming
116
+ ? "The preview appears when this reply finishes."
117
+ : "HTML preview is turned off."}
118
+ </Text>
119
+ </Card>
120
+ );
121
+ }
122
+ return (
123
+ <Card key={path} testID={path}>
124
+ <Text size="sm">Agent-generated preview</Text>
125
+ {block.title ? <Heading size="sm">{block.title}</Heading> : null}
126
+ <HtmlFrame height={block.height} html={block.html} title={block.title} />
127
+ </Card>
128
+ );
129
+ case "callout":
130
+ return (
131
+ <Box key={path} testID={path}>
132
+ <Banner dismissible={false} status={block.status ?? "info"} text={block.text} />
133
+ </Box>
134
+ );
135
+ case "image": {
136
+ const fileId = fileRefId(block.src);
137
+ const src = fileId === undefined ? block.src : context.resolvedImages?.[fileId];
138
+ return (
139
+ <Box key={path} testID={path}>
140
+ {src ? <Image alt={block.alt} color="transparent" naturalWidth={320} src={src} /> : null}
141
+ <Text size="sm">{block.alt}</Text>
142
+ </Box>
143
+ );
144
+ }
145
+ case "details":
146
+ return (
147
+ <Accordion isCollapsed={false} key={path} title={block.title}>
148
+ <Text>{block.text}</Text>
149
+ </Accordion>
150
+ );
151
+ case "divider":
152
+ return (
153
+ <Box key={path} testID={path}>
154
+ <SectionDivider />
155
+ </Box>
156
+ );
157
+ case "context":
158
+ return (
159
+ <Text color="secondaryLight" key={path} size="sm" testID={path}>
160
+ {block.text}
161
+ </Text>
162
+ );
163
+ case "columns":
164
+ return (
165
+ <Box direction="column" gap={3} key={path} mdDirection="row" testID={path}>
166
+ {renderChildren(block.children, path, context)}
167
+ </Box>
168
+ );
169
+ case "card":
170
+ return (
171
+ <Card key={path} testID={path}>
172
+ {block.title ? <Heading size="sm">{block.title}</Heading> : null}
173
+ {renderChildren(block.children, path, context)}
174
+ </Card>
175
+ );
176
+ case "chart": {
177
+ const Chart = chartFor[block.kind];
178
+ const dataName =
179
+ (block.id !== undefined ? context.selections[block.id] : undefined) ?? block.data;
180
+ const dataset = dataName === undefined ? undefined : context.resolved[dataName];
181
+ const points =
182
+ block.points !== undefined
183
+ ? chartPoints(block.points)
184
+ : dataset !== undefined && block.x !== undefined && block.y !== undefined
185
+ ? datasetToPoints({dataset, x: block.x, y: block.y})
186
+ : [];
187
+ return (
188
+ <Box gap={2} key={path} testID={path}>
189
+ {block.title ? <Heading size="sm">{block.title}</Heading> : null}
190
+ <Chart
191
+ data={points}
192
+ emptyText={block.emptyText}
193
+ height={chartHeight(block.height)}
194
+ legendLabel={block.legend ? block.title : undefined}
195
+ loading={dataName !== undefined && context.loadingIds.has(dataName)}
196
+ testID={`${path}-chart`}
197
+ />
198
+ </Box>
199
+ );
200
+ }
201
+ case "table": {
202
+ const dataName =
203
+ (block.id !== undefined ? context.selections[block.id] : undefined) ?? block.data;
204
+ const dataset = dataName === undefined ? undefined : context.resolved[dataName];
205
+ const names = block.columns ?? dataset?.columns.map((column) => column.name) ?? [];
206
+ const indexes = names.map(
207
+ (name) => dataset?.columns.findIndex((column) => column.name === name) ?? -1
208
+ );
209
+ return (
210
+ <Box gap={2} key={path} testID={path}>
211
+ {block.title ? <Heading size="sm">{block.title}</Heading> : null}
212
+ <DataTable
213
+ columns={names.map((name) => ({columnType: "text", title: name, width: 120}))}
214
+ data={(dataset?.rows ?? []).map((row) =>
215
+ indexes.map((index) => ({value: index < 0 ? "" : row[index]}))
216
+ )}
217
+ testID={`${path}-table`}
218
+ />
219
+ </Box>
220
+ );
221
+ }
222
+ case "actions":
223
+ return (
224
+ <Box direction="row" gap={2} key={path} testID={path} wrap>
225
+ {block.elements.map((element) => {
226
+ if (element.type === "segmented") {
227
+ const selectedData =
228
+ context.selections[element.target] ?? context.boundData?.[element.target];
229
+ const selectedIndex = Math.max(
230
+ 0,
231
+ element.options.findIndex((option) => option.data === selectedData)
232
+ );
233
+ return (
234
+ <SegmentedControl
235
+ items={element.options.map((option) => option.label)}
236
+ key={element.id}
237
+ onChange={(index) => {
238
+ const option = element.options[index];
239
+ if (option === undefined) {
240
+ return;
241
+ }
242
+ context.setSelection(element.target, option.data);
243
+ context.onAction?.({
244
+ action: {data: option.data, kind: "select", target: element.target},
245
+ blockId: block.id,
246
+ elementId: element.id,
247
+ });
248
+ }}
249
+ selectedIndex={selectedData === undefined ? 0 : selectedIndex}
250
+ testID={`${path}-${element.id}`}
251
+ />
252
+ );
253
+ }
254
+ const action = element.action;
255
+ const disabled =
256
+ action.kind === "callback" &&
257
+ context.hostActions !== undefined &&
258
+ !context.hostActions.includes(action.name);
259
+ return (
260
+ <Button
261
+ disabled={disabled}
262
+ key={element.id}
263
+ loading={context.pendingElementIds?.has(element.id) === true}
264
+ onClick={() => {
265
+ if (disabled) {
266
+ return;
267
+ }
268
+ if (action.kind === "select") {
269
+ context.setSelection(action.target, action.data);
270
+ }
271
+ context.onAction?.({
272
+ action,
273
+ blockId: block.id,
274
+ elementId: element.id,
275
+ });
276
+ }}
277
+ testID={`${path}-${element.id}`}
278
+ text={element.text}
279
+ variant={element.variant ?? "primary"}
280
+ />
281
+ );
282
+ })}
283
+ </Box>
284
+ );
285
+ default:
286
+ return <Box key={path} testID={path} />;
287
+ }
288
+ };
@@ -0,0 +1,31 @@
1
+ import {describe, expect, it} from "bun:test";
2
+
3
+ import {chartPoints, datasetToPoints} from "./datasetToPoints";
4
+
5
+ const signups = {
6
+ columns: [
7
+ {name: "month", type: "string" as const},
8
+ {name: "count", type: "number" as const},
9
+ ],
10
+ rows: [
11
+ ["Jan", 120],
12
+ ["Feb", 180],
13
+ ],
14
+ };
15
+
16
+ describe("datasetToPoints", () => {
17
+ it("maps x and y and never returns a color", () => {
18
+ const points = datasetToPoints({dataset: signups, x: "month", y: "count"});
19
+ expect(points).toEqual([
20
+ {label: "Jan", value: 120},
21
+ {label: "Feb", value: 180},
22
+ ]);
23
+ expect(points.every((point) => Object.keys(point).sort().join() === "label,value")).toBe(true);
24
+ });
25
+
26
+ it("drops a color that arrived on a point", () => {
27
+ expect(chartPoints([{color: "#ff0000", label: "Jan", value: 1}])).toEqual([
28
+ {label: "Jan", value: 1},
29
+ ]);
30
+ });
31
+ });
@@ -0,0 +1,48 @@
1
+ import type {InlineDataset} from "@terreno/blocks";
2
+
3
+ export interface ChartPoint {
4
+ label: string;
5
+ value: number;
6
+ }
7
+
8
+ const CHART_HEIGHT: Record<"lg" | "md" | "sm", number> = {
9
+ lg: 300,
10
+ md: 220,
11
+ sm: 160,
12
+ };
13
+
14
+ export const chartHeight = (height: "lg" | "md" | "sm" | undefined): number =>
15
+ CHART_HEIGHT[height ?? "md"];
16
+
17
+ /**
18
+ * Turns an inline dataset into the single series the chart components draw.
19
+ * The agent cannot set a per-point color; only label and value leave this function.
20
+ */
21
+ export const datasetToPoints = ({
22
+ dataset,
23
+ x,
24
+ y,
25
+ }: {
26
+ dataset: InlineDataset;
27
+ x: string;
28
+ y: string;
29
+ }): ChartPoint[] => {
30
+ const xIndex = dataset.columns.findIndex((column) => column.name === x);
31
+ const yIndex = dataset.columns.findIndex((column) => column.name === y);
32
+ if (xIndex < 0 || yIndex < 0) {
33
+ return [];
34
+ }
35
+ return dataset.rows.flatMap((row) => {
36
+ const label = row[xIndex];
37
+ const value = row[yIndex];
38
+ if (typeof label !== "string" || typeof value !== "number" || !Number.isFinite(value)) {
39
+ return [];
40
+ }
41
+ return [{label, value}];
42
+ });
43
+ };
44
+
45
+ /** Drops any extra fields, including color, from chart points. */
46
+ export const chartPoints = (
47
+ points: readonly {color?: string; label: string; value: number}[]
48
+ ): ChartPoint[] => points.map((point) => ({label: point.label, value: point.value}));
@@ -0,0 +1,13 @@
1
+ import {useCallback, useState} from "react";
2
+
3
+ /** Local dataset choice for a chart or table, keyed by that block's id. */
4
+ export const useBlockSelections = (): {
5
+ selections: Record<string, string>;
6
+ setSelection: (target: string, data: string) => void;
7
+ } => {
8
+ const [selections, setSelections] = useState<Record<string, string>>({});
9
+ const setSelection = useCallback((target: string, data: string): void => {
10
+ setSelections((current) => ({...current, [target]: data}));
11
+ }, []);
12
+ return {selections, setSelection};
13
+ };
@@ -0,0 +1,78 @@
1
+ import type {Dataset, InlineDataset, RefDataset} from "@terreno/blocks";
2
+ import {useEffect, useMemo, useState} from "react";
3
+
4
+ export interface DatasetRef {
5
+ grain?: RefDataset["grain"];
6
+ id: string;
7
+ limit?: number;
8
+ }
9
+
10
+ export type ResolveDataset = (ref: DatasetRef) => Promise<InlineDataset | undefined>;
11
+
12
+ const isInline = (dataset: Dataset): dataset is InlineDataset => dataset.source !== "ref";
13
+
14
+ /**
15
+ * Inline datasets are ready immediately. Ref datasets wait on `resolveDataset`.
16
+ */
17
+ export const useResolvedDatasets = ({
18
+ datasets,
19
+ resolveDataset,
20
+ }: {
21
+ datasets?: Record<string, Dataset>;
22
+ resolveDataset?: ResolveDataset;
23
+ }): {loadingIds: ReadonlySet<string>; resolved: Record<string, InlineDataset | undefined>} => {
24
+ const datasetKey = JSON.stringify(datasets ?? null);
25
+ const {inline, refs} = useMemo(() => {
26
+ const ready: Record<string, InlineDataset | undefined> = {};
27
+ const pending: (DatasetRef & {name: string})[] = [];
28
+ const parsed = JSON.parse(datasetKey) as Record<string, Dataset> | null;
29
+ for (const [name, dataset] of Object.entries(parsed ?? {})) {
30
+ if (isInline(dataset)) {
31
+ ready[name] = dataset;
32
+ continue;
33
+ }
34
+ pending.push({grain: dataset.grain, id: dataset.id, limit: dataset.limit, name});
35
+ }
36
+ return {inline: ready, refs: pending};
37
+ }, [datasetKey]);
38
+ const refKey = JSON.stringify(refs);
39
+ const [resolvedRefs, setResolvedRefs] = useState<Record<string, InlineDataset | undefined>>({});
40
+ const [loadingIds, setLoadingIds] = useState<ReadonlySet<string>>(() => new Set());
41
+
42
+ // A ref dataset is fetched once per id, grain, and limit. Inline rows never go through the host.
43
+ useEffect(() => {
44
+ const currentRefs = JSON.parse(refKey) as (DatasetRef & {name: string})[];
45
+ if (currentRefs.length === 0 || resolveDataset === undefined) {
46
+ setLoadingIds(new Set());
47
+ setResolvedRefs({});
48
+ return;
49
+ }
50
+ let cancelled = false;
51
+ setLoadingIds(new Set(currentRefs.map((ref) => ref.name)));
52
+ void Promise.all(
53
+ currentRefs.map(async (ref) => {
54
+ try {
55
+ const rows = await resolveDataset({grain: ref.grain, id: ref.id, limit: ref.limit});
56
+ return [ref.name, rows] as const;
57
+ } catch {
58
+ return [ref.name, undefined] as const;
59
+ }
60
+ })
61
+ ).then((pairs) => {
62
+ if (cancelled) {
63
+ return;
64
+ }
65
+ const next: Record<string, InlineDataset | undefined> = {};
66
+ for (const [name, rows] of pairs) {
67
+ next[name] = rows;
68
+ }
69
+ setResolvedRefs(next);
70
+ setLoadingIds(new Set());
71
+ });
72
+ return () => {
73
+ cancelled = true;
74
+ };
75
+ }, [refKey, resolveDataset]);
76
+
77
+ return {loadingIds, resolved: {...inline, ...resolvedRefs}};
78
+ };
@@ -0,0 +1,81 @@
1
+ import type {Block} from "@terreno/blocks";
2
+ import {useEffect, useState} from "react";
3
+
4
+ /** Turns a `file:` image id into a URL the image component can load. */
5
+ type ResolveImage = (fileId: string) => Promise<string | undefined>;
6
+
7
+ /** The id after `file:`, when `src` is a file ref. */
8
+ export const fileRefId = (src: string): string | undefined => {
9
+ if (!src.startsWith("file:")) {
10
+ return undefined;
11
+ }
12
+ const id = src.slice("file:".length).trim();
13
+ return id.length > 0 ? id : undefined;
14
+ };
15
+
16
+ const collectFileIds = (blocks: readonly Block[], ids: Set<string>): void => {
17
+ for (const block of blocks) {
18
+ if (block.type === "image") {
19
+ const id = fileRefId(block.src);
20
+ if (id !== undefined) {
21
+ ids.add(id);
22
+ }
23
+ }
24
+ if (block.type === "columns" || block.type === "card") {
25
+ collectFileIds(block.children, ids);
26
+ }
27
+ }
28
+ };
29
+
30
+ /**
31
+ * Resolves `file:` image refs. A missing resolver or a failed lookup leaves the id unset
32
+ * so the renderer can keep the alt text and skip the image.
33
+ */
34
+ export const useResolvedImages = ({
35
+ blocks,
36
+ resolveImage,
37
+ }: {
38
+ blocks?: readonly Block[];
39
+ resolveImage?: ResolveImage;
40
+ }): Record<string, string | undefined> => {
41
+ const ids = new Set<string>();
42
+ if (blocks !== undefined) {
43
+ collectFileIds(blocks, ids);
44
+ }
45
+ const key = [...ids].sort().join("\n");
46
+ const [resolved, setResolved] = useState<Record<string, string | undefined>>({});
47
+
48
+ // Each distinct file id is fetched once. Data and https sources never call the host.
49
+ useEffect(() => {
50
+ const current = key.length === 0 ? [] : key.split("\n");
51
+ if (current.length === 0 || resolveImage === undefined) {
52
+ setResolved({});
53
+ return;
54
+ }
55
+ let cancelled = false;
56
+ void Promise.all(
57
+ current.map(async (id) => {
58
+ try {
59
+ const url = await resolveImage(id);
60
+ return [id, url] as const;
61
+ } catch {
62
+ return [id, undefined] as const;
63
+ }
64
+ })
65
+ ).then((pairs) => {
66
+ if (cancelled) {
67
+ return;
68
+ }
69
+ const next: Record<string, string | undefined> = {};
70
+ for (const [id, url] of pairs) {
71
+ next[id] = url;
72
+ }
73
+ setResolved(next);
74
+ });
75
+ return () => {
76
+ cancelled = true;
77
+ };
78
+ }, [key, resolveImage]);
79
+
80
+ return resolved;
81
+ };
package/src/index.tsx CHANGED
@@ -14,6 +14,10 @@ export * from "./AnnouncementScreen";
14
14
  export type * from "./AreaChart";
15
15
  export type * from "./AttachmentPreview";
16
16
  export * from "./Avatar";
17
+ export type * from "./asks/AskCard";
18
+ export * from "./asks/askFileRefs";
19
+ export type * from "./asks/askTypes";
20
+ export * from "./asks/SimpleAskCard";
17
21
  export * from "./Badge";
18
22
  export {Banner, hideBanner} from "./Banner";
19
23
  export type * from "./BarChart";
@@ -58,6 +62,7 @@ export type * from "./GPTMemoryModal";
58
62
  export * from "./Heading";
59
63
  export * from "./HeightActionSheet";
60
64
  export * from "./HeightField";
65
+ export * from "./HtmlFrame";
61
66
  export * from "./Icon";
62
67
  export * from "./IconButton";
63
68
  export * from "./IconRegistry";
@@ -72,8 +77,10 @@ export {
72
77
  AIRequestExplorer,
73
78
  AiSuggestionBox,
74
79
  AreaChart,
80
+ AskCard,
75
81
  AttachmentPreview,
76
82
  BarChart,
83
+ BlocksView,
77
84
  ChartCard,
78
85
  ConflictSheet,
79
86
  ConsentFormScreen,