@terreno/ui 57.8.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.
- package/README.md +2 -0
- package/dist/AreaChart.d.ts +1 -1
- package/dist/AreaChart.d.ts.map +1 -1
- package/dist/AreaChart.js +70 -22
- package/dist/AreaChart.js.map +1 -1
- package/dist/BarChart.d.ts.map +1 -1
- package/dist/BarChart.js +55 -13
- package/dist/BarChart.js.map +1 -1
- package/dist/Button.d.ts.map +1 -1
- package/dist/Button.js +19 -4
- package/dist/Button.js.map +1 -1
- package/dist/ChartCard.d.ts +5 -0
- package/dist/ChartCard.d.ts.map +1 -0
- package/dist/ChartCard.js +18 -0
- package/dist/ChartCard.js.map +1 -0
- package/dist/Common.d.ts +147 -6
- package/dist/Common.d.ts.map +1 -1
- package/dist/Common.js.map +1 -1
- package/dist/DashboardGrid.d.ts +6 -2
- package/dist/DashboardGrid.d.ts.map +1 -1
- package/dist/DashboardGrid.js +43 -10
- package/dist/DashboardGrid.js.map +1 -1
- package/dist/DateTimeField.d.ts.map +1 -1
- package/dist/DateTimeField.js +90 -17
- package/dist/DateTimeField.js.map +1 -1
- package/dist/DonutChart.d.ts.map +1 -1
- package/dist/DonutChart.js +20 -10
- package/dist/DonutChart.js.map +1 -1
- package/dist/DropdownMenuItem.d.ts +16 -0
- package/dist/DropdownMenuItem.d.ts.map +1 -0
- package/dist/DropdownMenuItem.js +11 -0
- package/dist/DropdownMenuItem.js.map +1 -0
- package/dist/FilePickerButton.d.ts +15 -1
- package/dist/FilePickerButton.d.ts.map +1 -1
- package/dist/FilePickerButton.js +90 -13
- package/dist/FilePickerButton.js.map +1 -1
- package/dist/GPTChat.d.ts +57 -1
- package/dist/GPTChat.d.ts.map +1 -1
- package/dist/GPTChat.js +301 -20
- package/dist/GPTChat.js.map +1 -1
- package/dist/HtmlFrame.d.ts +11 -0
- package/dist/HtmlFrame.d.ts.map +1 -0
- package/dist/HtmlFrame.js +29 -0
- package/dist/HtmlFrame.js.map +1 -0
- package/dist/LineChart.d.ts +1 -1
- package/dist/LineChart.d.ts.map +1 -1
- package/dist/LineChart.js +62 -21
- package/dist/LineChart.js.map +1 -1
- package/dist/Scorecard.d.ts +5 -0
- package/dist/Scorecard.d.ts.map +1 -0
- package/dist/Scorecard.js +11 -0
- package/dist/Scorecard.js.map +1 -0
- package/dist/SparklineChart.d.ts +5 -0
- package/dist/SparklineChart.d.ts.map +1 -0
- package/dist/SparklineChart.js +35 -0
- package/dist/SparklineChart.js.map +1 -0
- package/dist/Text.d.ts +1 -1
- package/dist/Text.d.ts.map +1 -1
- package/dist/Text.js +2 -2
- package/dist/Text.js.map +1 -1
- package/dist/TextField.d.ts.map +1 -1
- package/dist/TextField.js +12 -4
- package/dist/TextField.js.map +1 -1
- package/dist/ToastNotifications.d.ts.map +1 -1
- package/dist/ToastNotifications.js +29 -6
- package/dist/ToastNotifications.js.map +1 -1
- package/dist/WebDropdownMenu.d.ts +2 -1
- package/dist/WebDropdownMenu.d.ts.map +1 -1
- package/dist/WebDropdownMenu.js +2 -6
- package/dist/WebDropdownMenu.js.map +1 -1
- package/dist/asks/AskCard.d.ts +34 -0
- package/dist/asks/AskCard.d.ts.map +1 -0
- package/dist/asks/AskCard.js +91 -0
- package/dist/asks/AskCard.js.map +1 -0
- package/dist/asks/AskChoice.d.ts +11 -0
- package/dist/asks/AskChoice.d.ts.map +1 -0
- package/dist/asks/AskChoice.js +146 -0
- package/dist/asks/AskChoice.js.map +1 -0
- package/dist/asks/AskConfirm.d.ts +15 -0
- package/dist/asks/AskConfirm.d.ts.map +1 -0
- package/dist/asks/AskConfirm.js +17 -0
- package/dist/asks/AskConfirm.js.map +1 -0
- package/dist/asks/AskFiles.d.ts +18 -0
- package/dist/asks/AskFiles.d.ts.map +1 -0
- package/dist/asks/AskFiles.js +149 -0
- package/dist/asks/AskFiles.js.map +1 -0
- package/dist/asks/AskForm.d.ts +27 -0
- package/dist/asks/AskForm.d.ts.map +1 -0
- package/dist/asks/AskForm.js +146 -0
- package/dist/asks/AskForm.js.map +1 -0
- package/dist/asks/AskMarkdown.d.ts +25 -0
- package/dist/asks/AskMarkdown.d.ts.map +1 -0
- package/dist/asks/AskMarkdown.js +73 -0
- package/dist/asks/AskMarkdown.js.map +1 -0
- package/dist/asks/SimpleAskCard.d.ts +23 -0
- package/dist/asks/SimpleAskCard.d.ts.map +1 -0
- package/dist/asks/SimpleAskCard.js +32 -0
- package/dist/asks/SimpleAskCard.js.map +1 -0
- package/dist/asks/askControls.d.ts +33 -0
- package/dist/asks/askControls.d.ts.map +1 -0
- package/dist/asks/askControls.js +30 -0
- package/dist/asks/askControls.js.map +1 -0
- package/dist/asks/askFileRefs.d.ts +26 -0
- package/dist/asks/askFileRefs.d.ts.map +1 -0
- package/dist/asks/askFileRefs.js +75 -0
- package/dist/asks/askFileRefs.js.map +1 -0
- package/dist/asks/askFormDraft.d.ts +60 -0
- package/dist/asks/askFormDraft.d.ts.map +1 -0
- package/dist/asks/askFormDraft.js +224 -0
- package/dist/asks/askFormDraft.js.map +1 -0
- package/dist/asks/askSummary.d.ts +10 -0
- package/dist/asks/askSummary.d.ts.map +1 -0
- package/dist/asks/askSummary.js +138 -0
- package/dist/asks/askSummary.js.map +1 -0
- package/dist/asks/askTypes.d.ts +21 -0
- package/dist/asks/askTypes.d.ts.map +1 -0
- package/dist/asks/askTypes.js +2 -0
- package/dist/asks/askTypes.js.map +1 -0
- package/dist/asks/simpleCardButtonVariants.d.ts +5 -0
- package/dist/asks/simpleCardButtonVariants.d.ts.map +1 -0
- package/dist/asks/simpleCardButtonVariants.js +8 -0
- package/dist/asks/simpleCardButtonVariants.js.map +1 -0
- package/dist/blocks/BlocksError.d.ts +8 -0
- package/dist/blocks/BlocksError.d.ts.map +1 -0
- package/dist/blocks/BlocksError.js +14 -0
- package/dist/blocks/BlocksError.js.map +1 -0
- package/dist/blocks/BlocksView.d.ts +10 -0
- package/dist/blocks/BlocksView.d.ts.map +1 -0
- package/dist/blocks/BlocksView.js +90 -0
- package/dist/blocks/BlocksView.js.map +1 -0
- package/dist/blocks/blockRenderers.d.ts +25 -0
- package/dist/blocks/blockRenderers.d.ts.map +1 -0
- package/dist/blocks/blockRenderers.js +136 -0
- package/dist/blocks/blockRenderers.js.map +1 -0
- package/dist/blocks/datasetToPoints.d.ts +22 -0
- package/dist/blocks/datasetToPoints.d.ts.map +1 -0
- package/dist/blocks/datasetToPoints.js +28 -0
- package/dist/blocks/datasetToPoints.js.map +1 -0
- package/dist/blocks/useBlockSelections.d.ts +6 -0
- package/dist/blocks/useBlockSelections.d.ts.map +1 -0
- package/dist/blocks/useBlockSelections.js +10 -0
- package/dist/blocks/useBlockSelections.js.map +1 -0
- package/dist/blocks/useResolvedDatasets.d.ts +18 -0
- package/dist/blocks/useResolvedDatasets.d.ts.map +1 -0
- package/dist/blocks/useResolvedDatasets.js +59 -0
- package/dist/blocks/useResolvedDatasets.js.map +1 -0
- package/dist/blocks/useResolvedImages.d.ts +15 -0
- package/dist/blocks/useResolvedImages.d.ts.map +1 -0
- package/dist/blocks/useResolvedImages.js +66 -0
- package/dist/blocks/useResolvedImages.js.map +1 -0
- package/dist/charts/ChartFacadeContainer.d.ts +10 -0
- package/dist/charts/ChartFacadeContainer.d.ts.map +1 -0
- package/dist/charts/ChartFacadeContainer.js +10 -0
- package/dist/charts/ChartFacadeContainer.js.map +1 -0
- package/dist/charts/ChartFrame.d.ts +4 -0
- package/dist/charts/ChartFrame.d.ts.map +1 -1
- package/dist/charts/ChartFrame.js +4 -2
- package/dist/charts/ChartFrame.js.map +1 -1
- package/dist/charts/layout.d.ts +9 -2
- package/dist/charts/layout.d.ts.map +1 -1
- package/dist/charts/layout.js +28 -6
- package/dist/charts/layout.js.map +1 -1
- package/dist/charts/scales.d.ts +3 -1
- package/dist/charts/scales.d.ts.map +1 -1
- package/dist/charts/scales.js +7 -7
- package/dist/charts/scales.js.map +1 -1
- package/dist/charts/series.d.ts +15 -0
- package/dist/charts/series.d.ts.map +1 -0
- package/dist/charts/series.js +19 -0
- package/dist/charts/series.js.map +1 -0
- package/dist/charts/types/chartTypes.d.ts +7 -0
- package/dist/charts/types/chartTypes.d.ts.map +1 -1
- package/dist/dashboardGridLayout.d.ts +6 -0
- package/dist/dashboardGridLayout.d.ts.map +1 -1
- package/dist/dashboardGridLayout.js +19 -3
- package/dist/dashboardGridLayout.js.map +1 -1
- package/dist/index.d.ts +9 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -1
- package/dist/index.js.map +1 -1
- package/dist/lazyBoundaries/heavyOptionalExports.d.ts +15 -0
- package/dist/lazyBoundaries/heavyOptionalExports.d.ts.map +1 -1
- package/dist/lazyBoundaries/heavyOptionalExports.js +10 -0
- package/dist/lazyBoundaries/heavyOptionalExports.js.map +1 -1
- package/dist/resolveDocumentBodyPortalTarget.d.ts +7 -0
- package/dist/resolveDocumentBodyPortalTarget.d.ts.map +1 -0
- package/dist/resolveDocumentBodyPortalTarget.js +12 -0
- package/dist/resolveDocumentBodyPortalTarget.js.map +1 -0
- package/package.json +2 -1
- package/src/AIRequestExplorer.test.tsx +2 -2
- package/src/AreaChart.test.tsx +81 -0
- package/src/AreaChart.tsx +171 -62
- package/src/BarChart.test.tsx +119 -0
- package/src/BarChart.tsx +94 -20
- package/src/Button.test.tsx +72 -0
- package/src/Button.tsx +34 -4
- package/src/ChartCard.test.tsx +79 -0
- package/src/ChartCard.tsx +80 -0
- package/src/Common.ts +136 -2
- package/src/DashboardGrid.test.tsx +98 -1
- package/src/DashboardGrid.tsx +71 -20
- package/src/DateTimeField.test.tsx +185 -2
- package/src/DateTimeField.tsx +106 -16
- package/src/DonutChart.test.tsx +78 -10
- package/src/DonutChart.tsx +87 -14
- package/src/DropdownMenuItem.tsx +48 -0
- package/src/FilePickerButton.test.tsx +116 -9
- package/src/FilePickerButton.tsx +177 -23
- package/src/GPTChat.test.tsx +891 -8
- package/src/GPTChat.tsx +713 -45
- package/src/HtmlFrame.tsx +60 -0
- package/src/LineChart.test.tsx +109 -10
- package/src/LineChart.tsx +154 -58
- package/src/Scorecard.test.tsx +65 -0
- package/src/Scorecard.tsx +45 -0
- package/src/SparklineChart.test.tsx +69 -0
- package/src/SparklineChart.tsx +85 -0
- package/src/Text.test.tsx +22 -0
- package/src/Text.tsx +10 -1
- package/src/TextField.test.tsx +16 -0
- package/src/TextField.tsx +13 -3
- package/src/ToastNotifications.tsx +33 -6
- package/src/ToastNotifications.webModal.test.tsx +285 -0
- package/src/WebDropdownMenu.tsx +3 -7
- package/src/asks/AskCard.test.tsx +1428 -0
- package/src/asks/AskCard.tsx +240 -0
- package/src/asks/AskChoice.tsx +368 -0
- package/src/asks/AskConfirm.tsx +42 -0
- package/src/asks/AskFiles.test.tsx +347 -0
- package/src/asks/AskFiles.tsx +246 -0
- package/src/asks/AskForm.tsx +334 -0
- package/src/asks/AskMarkdown.tsx +176 -0
- package/src/asks/SimpleAskCard.test.tsx +253 -0
- package/src/asks/SimpleAskCard.tsx +82 -0
- package/src/asks/askControls.tsx +98 -0
- package/src/asks/askFileRefs.test.ts +155 -0
- package/src/asks/askFileRefs.ts +98 -0
- package/src/asks/askFormDraft.test.ts +347 -0
- package/src/asks/askFormDraft.ts +309 -0
- package/src/asks/askSummary.test.ts +255 -0
- package/src/asks/askSummary.ts +160 -0
- package/src/asks/askTypes.ts +25 -0
- package/src/asks/asksUseTerrenoComponents.test.ts +55 -0
- package/src/asks/simpleCardButtonVariants.ts +14 -0
- package/src/blocks/BlocksError.tsx +28 -0
- package/src/blocks/BlocksView.test.tsx +607 -0
- package/src/blocks/BlocksView.tsx +125 -0
- package/src/blocks/blockRenderers.tsx +288 -0
- package/src/blocks/datasetToPoints.test.ts +31 -0
- package/src/blocks/datasetToPoints.ts +48 -0
- package/src/blocks/useBlockSelections.ts +13 -0
- package/src/blocks/useResolvedDatasets.ts +78 -0
- package/src/blocks/useResolvedImages.ts +81 -0
- package/src/bunSetup.ts +1 -0
- package/src/charts/ChartFacadeContainer.tsx +35 -0
- package/src/charts/ChartFrame.tsx +39 -1
- package/src/charts/layout.test.ts +22 -1
- package/src/charts/layout.ts +37 -4
- package/src/charts/scales.test.ts +33 -0
- package/src/charts/scales.ts +10 -6
- package/src/charts/series.ts +43 -0
- package/src/charts/types/chartTypes.ts +8 -0
- package/src/dashboardGridLayout.test.ts +59 -1
- package/src/dashboardGridLayout.ts +30 -3
- package/src/index.tsx +13 -0
- package/src/isolated/HtmlFrame.isolated.tsx +54 -0
- package/src/lazyBoundaries/heavyOptionalExports.test.tsx +2 -0
- package/src/lazyBoundaries/heavyOptionalExports.tsx +35 -0
- package/src/resolveDocumentBodyPortalTarget.ts +11 -0
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
import {afterEach, describe, it, mock} from "bun:test";
|
|
2
|
+
import {readdirSync, readFileSync} from "node:fs";
|
|
3
|
+
import {join} from "node:path";
|
|
4
|
+
import {
|
|
5
|
+
resolveButtonAnswer,
|
|
6
|
+
type SimpleCard,
|
|
7
|
+
type SimpleCardButton,
|
|
8
|
+
simpleCardSchema,
|
|
9
|
+
} from "@terreno/blocks";
|
|
10
|
+
import {act, fireEvent, within} from "@testing-library/react-native";
|
|
11
|
+
import {assert} from "chai";
|
|
12
|
+
|
|
13
|
+
import {renderWithTheme} from "../test-utils";
|
|
14
|
+
import {SimpleAskCard, type SimpleAskCardProps} from "./SimpleAskCard";
|
|
15
|
+
|
|
16
|
+
const FIXTURES_DIR = join(
|
|
17
|
+
import.meta.dir,
|
|
18
|
+
"..",
|
|
19
|
+
"..",
|
|
20
|
+
"..",
|
|
21
|
+
"blocks",
|
|
22
|
+
"src",
|
|
23
|
+
"asks",
|
|
24
|
+
"fixtures",
|
|
25
|
+
"valid"
|
|
26
|
+
);
|
|
27
|
+
|
|
28
|
+
interface CardFixture {
|
|
29
|
+
card: SimpleCard;
|
|
30
|
+
name: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The card each valid `@terreno/blocks` ask fixture derives, so a new fixture is covered here too. */
|
|
34
|
+
const cardFixtures = (): CardFixture[] =>
|
|
35
|
+
readdirSync(FIXTURES_DIR)
|
|
36
|
+
.filter((file) => file.endsWith(".json"))
|
|
37
|
+
.sort()
|
|
38
|
+
.map((file) => ({
|
|
39
|
+
card: simpleCardSchema.parse(
|
|
40
|
+
JSON.parse(readFileSync(join(FIXTURES_DIR, file), "utf8")).simple
|
|
41
|
+
),
|
|
42
|
+
name: file.replace(/\.json$/, ""),
|
|
43
|
+
}));
|
|
44
|
+
|
|
45
|
+
const fixtureCard = (name: string): SimpleCard => {
|
|
46
|
+
const fixture = cardFixtures().find((candidate) => candidate.name === name);
|
|
47
|
+
if (!fixture) {
|
|
48
|
+
throw new Error(`No valid ask fixture named ${name}`);
|
|
49
|
+
}
|
|
50
|
+
return fixture.card;
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
const ANNOUNCEMENT_DRAFT =
|
|
54
|
+
"# We're live\n\nToday we launched **Terreno Asks**: your agent can now ask you a question and wait for the answer.\n\n- Pick from options\n- Approve or deny\n- Edit a draft like this one\n";
|
|
55
|
+
|
|
56
|
+
const renderCard = (props: Partial<SimpleAskCardProps> & Pick<SimpleAskCardProps, "card">) =>
|
|
57
|
+
renderWithTheme(<SimpleAskCard onPress={mock(() => {})} {...props} />);
|
|
58
|
+
|
|
59
|
+
// Button presses await a haptic call before running onClick, so let those microtasks settle.
|
|
60
|
+
const press = async (element: Parameters<typeof fireEvent.press>[0]): Promise<void> => {
|
|
61
|
+
await act(async () => {
|
|
62
|
+
fireEvent.press(element);
|
|
63
|
+
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
64
|
+
});
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
const isDisabled = (element: {props: {accessibilityState?: {disabled?: boolean}}}): boolean =>
|
|
68
|
+
element.props.accessibilityState?.disabled === true;
|
|
69
|
+
|
|
70
|
+
const spinnerCount = (element: {
|
|
71
|
+
findAll: (test: (node: {type: unknown}) => boolean) => unknown[];
|
|
72
|
+
}) => element.findAll((node) => node.type === "ActivityIndicator").length;
|
|
73
|
+
|
|
74
|
+
const BUTTON_TEST_ID = /^simple-ask-card-button-/;
|
|
75
|
+
|
|
76
|
+
const HANDOFF_TEXT: Partial<Record<SimpleCard["kind"], string>> = {
|
|
77
|
+
files: "Upload on your phone",
|
|
78
|
+
form: "Fill it in on your phone",
|
|
79
|
+
markdown: "Edit on your phone",
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
describe("SimpleAskCard", () => {
|
|
83
|
+
afterEach(() => {
|
|
84
|
+
mock.restore();
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
it("covers handoff and non-handoff cards among the fixtures", () => {
|
|
88
|
+
const cards = cardFixtures().map((fixture) => fixture.card);
|
|
89
|
+
assert.isTrue(cards.some((card) => card.handoff));
|
|
90
|
+
assert.isTrue(cards.some((card) => !card.handoff));
|
|
91
|
+
assert.isTrue(cards.some((card) => card.buttons.length === 0));
|
|
92
|
+
assert.isTrue(cards.some((card) => card.title !== undefined));
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it.each(cardFixtures().map((fixture) => [fixture.name, fixture.card] as const))(
|
|
96
|
+
"renders the %s fixture's card",
|
|
97
|
+
(_name, card) => {
|
|
98
|
+
const {getByTestId, getByText, queryAllByTestId, queryByTestId} = renderCard({card});
|
|
99
|
+
|
|
100
|
+
if (card.title !== undefined) {
|
|
101
|
+
assert.isOk(getByText(card.title));
|
|
102
|
+
}
|
|
103
|
+
assert.isOk(getByText(card.text));
|
|
104
|
+
if (card.handoff) {
|
|
105
|
+
assert.isOk(
|
|
106
|
+
within(getByTestId("simple-ask-card-handoff")).getByText(
|
|
107
|
+
HANDOFF_TEXT[card.kind] ?? "Continue on your phone"
|
|
108
|
+
)
|
|
109
|
+
);
|
|
110
|
+
} else {
|
|
111
|
+
assert.isNull(queryByTestId("simple-ask-card-handoff"));
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
assert.deepEqual(
|
|
115
|
+
queryAllByTestId(BUTTON_TEST_ID).map((element) => element.props.testID),
|
|
116
|
+
card.buttons.map((button) => `simple-ask-card-button-${button.id}`)
|
|
117
|
+
);
|
|
118
|
+
for (const button of card.buttons) {
|
|
119
|
+
const element = getByTestId(`simple-ask-card-button-${button.id}`);
|
|
120
|
+
assert.isOk(within(element).getByText(button.label));
|
|
121
|
+
assert.isFalse(isDisabled(element));
|
|
122
|
+
assert.equal(spinnerCount(element), 0);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
);
|
|
126
|
+
|
|
127
|
+
it("wraps each button's label inside the card instead of overflowing it", () => {
|
|
128
|
+
const card = fixtureCard("choice-emoji-label-cut");
|
|
129
|
+
const {getByTestId} = renderCard({card});
|
|
130
|
+
|
|
131
|
+
for (const button of card.buttons) {
|
|
132
|
+
const element = getByTestId(`simple-ask-card-button-${button.id}`);
|
|
133
|
+
assert.include(element.props.style, {maxWidth: "100%"});
|
|
134
|
+
assert.include(within(element).getByText(button.label).props.style, {textAlign: "center"});
|
|
135
|
+
}
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
it("calls onPress with the pressed button, whose id the server resolves to the same answer", async () => {
|
|
139
|
+
const card = fixtureCard("choice-plan-with-default");
|
|
140
|
+
const onPress = mock((_button: SimpleCardButton) => {});
|
|
141
|
+
const {getByTestId} = renderCard({card, onPress});
|
|
142
|
+
|
|
143
|
+
for (const button of card.buttons) {
|
|
144
|
+
await press(getByTestId(`simple-ask-card-button-${button.id}`));
|
|
145
|
+
assert.deepEqual(onPress.mock.calls.at(-1)?.[0], button);
|
|
146
|
+
assert.deepEqual(resolveButtonAnswer({buttonId: button.id, card}), {
|
|
147
|
+
errors: [],
|
|
148
|
+
response: button.response,
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
assert.equal(onPress.mock.calls.length, card.buttons.length);
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
it("offers only the continue-on-phone line when a handoff card has no buttons", () => {
|
|
155
|
+
const card = fixtureCard("choice-many-options-no-buttons");
|
|
156
|
+
const {getByTestId, getByText, queryAllByTestId} = renderCard({card});
|
|
157
|
+
|
|
158
|
+
assert.isOk(getByText(card.text));
|
|
159
|
+
assert.isOk(within(getByTestId("simple-ask-card-handoff")).getByText("Continue on your phone"));
|
|
160
|
+
assert.lengthOf(queryAllByTestId(BUTTON_TEST_ID), 0);
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
it("tells the user to edit a markdown draft on their phone, next to Approve draft and Cancel", async () => {
|
|
164
|
+
const card = fixtureCard("markdown-announcement-draft");
|
|
165
|
+
const onPress = mock((_button: SimpleCardButton) => {});
|
|
166
|
+
const {getByTestId} = renderCard({card, onPress});
|
|
167
|
+
|
|
168
|
+
assert.isOk(within(getByTestId("simple-ask-card-handoff")).getByText("Edit on your phone"));
|
|
169
|
+
assert.isOk(within(getByTestId("simple-ask-card-button-approve")).getByText("Approve draft"));
|
|
170
|
+
assert.isOk(within(getByTestId("simple-ask-card-button-cancel")).getByText("Cancel"));
|
|
171
|
+
await press(getByTestId("simple-ask-card-button-approve"));
|
|
172
|
+
assert.deepEqual(onPress.mock.calls[0]?.[0], card.buttons[0]);
|
|
173
|
+
assert.deepEqual(onPress.mock.calls[0]?.[0]?.response, {
|
|
174
|
+
action: "accept",
|
|
175
|
+
content: {changed: false, markdown: ANNOUNCEMENT_DRAFT},
|
|
176
|
+
});
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
it("tells the user to fill a form in on their phone, next to Submit defaults and Cancel", async () => {
|
|
180
|
+
const card = fixtureCard("form-text-required-default");
|
|
181
|
+
const onPress = mock((_button: SimpleCardButton) => {});
|
|
182
|
+
const {getByTestId} = renderCard({card, onPress});
|
|
183
|
+
|
|
184
|
+
assert.isOk(
|
|
185
|
+
within(getByTestId("simple-ask-card-handoff")).getByText("Fill it in on your phone")
|
|
186
|
+
);
|
|
187
|
+
await press(getByTestId("simple-ask-card-button-submit-defaults"));
|
|
188
|
+
assert.deepEqual(onPress.mock.calls[0]?.[0]?.response, {
|
|
189
|
+
action: "accept",
|
|
190
|
+
content: {values: {name: "Launch plan"}},
|
|
191
|
+
});
|
|
192
|
+
await press(getByTestId("simple-ask-card-button-cancel"));
|
|
193
|
+
assert.deepEqual(onPress.mock.calls[1]?.[0]?.response, {action: "decline"});
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
it("tells the user to upload files on their phone, next to Skip", async () => {
|
|
197
|
+
const card = fixtureCard("files-receipt-photos");
|
|
198
|
+
const onPress = mock((_button: SimpleCardButton) => {});
|
|
199
|
+
const {getByTestId, queryAllByTestId} = renderCard({card, onPress});
|
|
200
|
+
|
|
201
|
+
assert.isOk(within(getByTestId("simple-ask-card-handoff")).getByText("Upload on your phone"));
|
|
202
|
+
assert.deepEqual(
|
|
203
|
+
queryAllByTestId(BUTTON_TEST_ID).map((element) => element.props.testID),
|
|
204
|
+
["simple-ask-card-button-skip"]
|
|
205
|
+
);
|
|
206
|
+
await press(getByTestId("simple-ask-card-button-skip"));
|
|
207
|
+
assert.deepEqual(onPress.mock.calls[0]?.[0]?.response, {action: "decline"});
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
it("keeps the handoff card's buttons next to the continue-on-phone line", async () => {
|
|
211
|
+
const card = fixtureCard("choice-many-options-with-default");
|
|
212
|
+
const onPress = mock((_button: SimpleCardButton) => {});
|
|
213
|
+
const {getByTestId} = renderCard({card, onPress});
|
|
214
|
+
|
|
215
|
+
assert.isOk(getByTestId("simple-ask-card-handoff"));
|
|
216
|
+
await press(getByTestId("simple-ask-card-button-use-default"));
|
|
217
|
+
assert.deepEqual(onPress.mock.calls[0]?.[0]?.response, {
|
|
218
|
+
action: "accept",
|
|
219
|
+
content: {selected: ["eu-west"]},
|
|
220
|
+
});
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
it("shows the pending button loading and disables the others until the answer is sent", async () => {
|
|
224
|
+
const card = fixtureCard("choice-plan-with-default");
|
|
225
|
+
const onPress = mock((_button: SimpleCardButton) => {});
|
|
226
|
+
const {getByTestId, rerender} = renderCard({card, onPress, pendingButtonId: "option:team"});
|
|
227
|
+
|
|
228
|
+
const pending = getByTestId("simple-ask-card-button-option:team");
|
|
229
|
+
assert.equal(spinnerCount(pending), 1);
|
|
230
|
+
assert.isTrue(isDisabled(pending));
|
|
231
|
+
for (const id of ["option:starter", "option:enterprise"]) {
|
|
232
|
+
const other = getByTestId(`simple-ask-card-button-${id}`);
|
|
233
|
+
assert.isTrue(isDisabled(other));
|
|
234
|
+
assert.equal(spinnerCount(other), 0);
|
|
235
|
+
await press(other);
|
|
236
|
+
}
|
|
237
|
+
assert.equal(onPress.mock.calls.length, 0);
|
|
238
|
+
|
|
239
|
+
rerender(<SimpleAskCard card={card} onPress={onPress} />);
|
|
240
|
+
await press(getByTestId("simple-ask-card-button-option:starter"));
|
|
241
|
+
assert.equal(onPress.mock.calls[0]?.[0]?.id, "option:starter");
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
it("uses the given testID for the card, its handoff line, and its buttons", () => {
|
|
245
|
+
const card = fixtureCard("choice-many-options-with-default");
|
|
246
|
+
const {getByTestId} = renderCard({card, testID: "watch-card"});
|
|
247
|
+
|
|
248
|
+
assert.isOk(getByTestId("watch-card"));
|
|
249
|
+
assert.isOk(getByTestId("watch-card-handoff"));
|
|
250
|
+
assert.isOk(getByTestId("watch-card-button-use-default"));
|
|
251
|
+
assert.isOk(getByTestId("watch-card-button-skip"));
|
|
252
|
+
});
|
|
253
|
+
});
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import type {AskKind, SimpleCard, SimpleCardButton} from "@terreno/blocks";
|
|
2
|
+
import type React from "react";
|
|
3
|
+
import {useCallback} from "react";
|
|
4
|
+
|
|
5
|
+
import {Box} from "../Box";
|
|
6
|
+
import {Button} from "../Button";
|
|
7
|
+
import {Heading} from "../Heading";
|
|
8
|
+
import {Text} from "../Text";
|
|
9
|
+
import {SIMPLE_CARD_BUTTON_VARIANTS} from "./simpleCardButtonVariants";
|
|
10
|
+
|
|
11
|
+
const DEFAULT_HANDOFF_TEXT = "Continue on your phone";
|
|
12
|
+
|
|
13
|
+
/** A handoff line that names what the phone is for, where the card's kind says so. */
|
|
14
|
+
const HANDOFF_TEXT_BY_KIND: Partial<Record<AskKind, string>> = {
|
|
15
|
+
files: "Upload on your phone",
|
|
16
|
+
form: "Fill it in on your phone",
|
|
17
|
+
markdown: "Edit on your phone",
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
export interface SimpleAskCardProps {
|
|
21
|
+
/** The ask's simple card: `pendingAsk.simple` from the server, or `simple` on an `{ask}` event. */
|
|
22
|
+
card: SimpleCard;
|
|
23
|
+
/**
|
|
24
|
+
* Called with the pressed button. Send `{toolCallId: card.toolCallId, buttonId: button.id}` to
|
|
25
|
+
* the history's `turn` action; the server answers with that button's stored `response`.
|
|
26
|
+
*/
|
|
27
|
+
onPress: (button: SimpleCardButton) => void | Promise<void>;
|
|
28
|
+
/** The button whose answer is still sending. It shows a spinner and the other buttons are disabled. */
|
|
29
|
+
pendingButtonId?: string;
|
|
30
|
+
testID?: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Any ask as a small-screen card: its title, its question, and up to three buttons that each send an
|
|
35
|
+
* exact answer. For watch-sized and other narrow layouts; it renders every kind the same way. A
|
|
36
|
+
* `handoff` card cannot offer every answer, so it tells the user to continue on their phone ("Edit
|
|
37
|
+
* on your phone" for a `markdown` card, "Fill it in on your phone" for a `form` card, "Upload on your
|
|
38
|
+
* phone" for a `files` card).
|
|
39
|
+
*/
|
|
40
|
+
export const SimpleAskCard: React.FC<SimpleAskCardProps> = ({
|
|
41
|
+
card,
|
|
42
|
+
onPress,
|
|
43
|
+
pendingButtonId,
|
|
44
|
+
testID = "simple-ask-card",
|
|
45
|
+
}) => {
|
|
46
|
+
const isSending = pendingButtonId !== undefined;
|
|
47
|
+
|
|
48
|
+
const handlePress = useCallback(
|
|
49
|
+
(button: SimpleCardButton): void | Promise<void> => {
|
|
50
|
+
if (isSending) {
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
return onPress(button);
|
|
54
|
+
},
|
|
55
|
+
[isSending, onPress]
|
|
56
|
+
);
|
|
57
|
+
|
|
58
|
+
return (
|
|
59
|
+
<Box gap={2} testID={testID}>
|
|
60
|
+
{card.title === undefined ? null : <Heading size="sm">{card.title}</Heading>}
|
|
61
|
+
<Text>{card.text}</Text>
|
|
62
|
+
{card.handoff ? (
|
|
63
|
+
<Text color="secondaryDark" size="sm" testID={`${testID}-handoff`}>
|
|
64
|
+
{HANDOFF_TEXT_BY_KIND[card.kind] ?? DEFAULT_HANDOFF_TEXT}
|
|
65
|
+
</Text>
|
|
66
|
+
) : null}
|
|
67
|
+
{card.buttons.map((button) => (
|
|
68
|
+
<Button
|
|
69
|
+
disabled={isSending && pendingButtonId !== button.id}
|
|
70
|
+
fullWidth
|
|
71
|
+
key={button.id}
|
|
72
|
+
loading={pendingButtonId === button.id}
|
|
73
|
+
onClick={() => handlePress(button)}
|
|
74
|
+
testID={`${testID}-button-${button.id}`}
|
|
75
|
+
text={button.label}
|
|
76
|
+
variant={SIMPLE_CARD_BUTTON_VARIANTS[button.style]}
|
|
77
|
+
wrapText
|
|
78
|
+
/>
|
|
79
|
+
))}
|
|
80
|
+
</Box>
|
|
81
|
+
);
|
|
82
|
+
};
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type Ask,
|
|
3
|
+
type AskResponse,
|
|
4
|
+
type AskValidationError,
|
|
5
|
+
askAllowsDecline,
|
|
6
|
+
type SimpleCardButton,
|
|
7
|
+
} from "@terreno/blocks";
|
|
8
|
+
import type React from "react";
|
|
9
|
+
import {useCallback} from "react";
|
|
10
|
+
|
|
11
|
+
import {Box} from "../Box";
|
|
12
|
+
import {Button} from "../Button";
|
|
13
|
+
import {Text} from "../Text";
|
|
14
|
+
import {SIMPLE_CARD_BUTTON_VARIANTS} from "./simpleCardButtonVariants";
|
|
15
|
+
|
|
16
|
+
export const SKIP_BUTTON: SimpleCardButton = {
|
|
17
|
+
id: "skip",
|
|
18
|
+
label: "Skip",
|
|
19
|
+
response: {action: "decline"},
|
|
20
|
+
style: "cancel",
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
/** An answer from one of the card's controls, named so the card can show that control loading. */
|
|
24
|
+
export interface AskAction {
|
|
25
|
+
actionId: string;
|
|
26
|
+
response: AskResponse;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The props every kind's controls receive from `AskCard`. */
|
|
30
|
+
export interface AskControlProps {
|
|
31
|
+
errors?: AskValidationError[];
|
|
32
|
+
/** True when the host takes no answers: buttons are disabled and radio options are plain text. */
|
|
33
|
+
isDisabled: boolean;
|
|
34
|
+
onAnswer: (action: AskAction) => void | Promise<void>;
|
|
35
|
+
/** The control whose answer the host is still handling. */
|
|
36
|
+
pendingActionId?: string;
|
|
37
|
+
testID: string;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export const AskErrors = ({
|
|
41
|
+
errors,
|
|
42
|
+
testID,
|
|
43
|
+
}: {
|
|
44
|
+
errors?: AskValidationError[];
|
|
45
|
+
testID: string;
|
|
46
|
+
}): React.ReactElement | null => {
|
|
47
|
+
if (!errors || errors.length === 0) {
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
return (
|
|
51
|
+
<Box gap={1} testID={testID}>
|
|
52
|
+
{errors.map((error) => (
|
|
53
|
+
<Text color="error" key={`${error.path}:${error.code}`} size="sm">
|
|
54
|
+
{error.message}
|
|
55
|
+
</Text>
|
|
56
|
+
))}
|
|
57
|
+
</Box>
|
|
58
|
+
);
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
/** Skip, for an ask that accepts a decline. */
|
|
62
|
+
export const SkipButton = ({
|
|
63
|
+
ask,
|
|
64
|
+
renderButton,
|
|
65
|
+
}: {
|
|
66
|
+
ask: Ask;
|
|
67
|
+
renderButton: (button: SimpleCardButton) => React.ReactElement;
|
|
68
|
+
}): React.ReactElement | null => (askAllowsDecline(ask) ? renderButton(SKIP_BUTTON) : null);
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Renders a simple-card button that answers on press. While one answer is sending, that button
|
|
72
|
+
* shows a spinner and the others are disabled.
|
|
73
|
+
*/
|
|
74
|
+
export const useAnswerButton = ({
|
|
75
|
+
isDisabled,
|
|
76
|
+
onAnswer,
|
|
77
|
+
pendingActionId,
|
|
78
|
+
testID,
|
|
79
|
+
}: Pick<AskControlProps, "isDisabled" | "onAnswer" | "pendingActionId" | "testID">): ((
|
|
80
|
+
button: SimpleCardButton
|
|
81
|
+
) => React.ReactElement) => {
|
|
82
|
+
const isAnswering = pendingActionId !== undefined;
|
|
83
|
+
return useCallback(
|
|
84
|
+
(button: SimpleCardButton): React.ReactElement => (
|
|
85
|
+
<Button
|
|
86
|
+
disabled={isDisabled || (isAnswering && pendingActionId !== button.id)}
|
|
87
|
+
key={button.id}
|
|
88
|
+
loading={pendingActionId === button.id}
|
|
89
|
+
onClick={() => onAnswer({actionId: button.id, response: button.response})}
|
|
90
|
+
testID={`${testID}-button-${button.id}`}
|
|
91
|
+
text={button.label}
|
|
92
|
+
variant={SIMPLE_CARD_BUTTON_VARIANTS[button.style]}
|
|
93
|
+
wrapText
|
|
94
|
+
/>
|
|
95
|
+
),
|
|
96
|
+
[isAnswering, isDisabled, onAnswer, pendingActionId, testID]
|
|
97
|
+
);
|
|
98
|
+
};
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import {afterEach, beforeEach, describe, it} from "bun:test";
|
|
2
|
+
import {assert} from "chai";
|
|
3
|
+
|
|
4
|
+
import {
|
|
5
|
+
normalizeMimeType,
|
|
6
|
+
resolveAskFilesAsDataUrls,
|
|
7
|
+
selectedFileMimeType,
|
|
8
|
+
selectedFileToDataUrlRef,
|
|
9
|
+
} from "./askFileRefs";
|
|
10
|
+
|
|
11
|
+
const TEXT = "Coffee, 4.50\nBagel, 3.25\n";
|
|
12
|
+
const textUri = (mimeType: string): string =>
|
|
13
|
+
`data:${mimeType};base64,${Buffer.from(TEXT).toString("base64")}`;
|
|
14
|
+
|
|
15
|
+
describe("askFileRefs", () => {
|
|
16
|
+
it("normalizes a MIME type to its lowercase type without parameters", () => {
|
|
17
|
+
assert.equal(normalizeMimeType("Text/CSV; charset=utf-8"), "text/csv");
|
|
18
|
+
assert.equal(normalizeMimeType("image/png"), "image/png");
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
it("takes the type from the extension when the picker reports none or a generic one", () => {
|
|
22
|
+
assert.equal(selectedFileMimeType({mimeType: "", name: "day.CSV"}), "text/csv");
|
|
23
|
+
assert.equal(
|
|
24
|
+
selectedFileMimeType({mimeType: "application/octet-stream", name: "notes.txt"}),
|
|
25
|
+
"text/plain"
|
|
26
|
+
);
|
|
27
|
+
assert.equal(
|
|
28
|
+
selectedFileMimeType({mimeType: "application/vnd.ms-excel", name: "export.csv"}),
|
|
29
|
+
"text/csv"
|
|
30
|
+
);
|
|
31
|
+
assert.equal(selectedFileMimeType({mimeType: "", name: "scan.jpeg"}), "image/jpeg");
|
|
32
|
+
assert.equal(
|
|
33
|
+
selectedFileMimeType({mimeType: "application/octet-stream", name: "plan.pdf"}),
|
|
34
|
+
"application/pdf"
|
|
35
|
+
);
|
|
36
|
+
assert.equal(selectedFileMimeType({mimeType: "", name: "total.json"}), "application/json");
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it("keeps a specific reported type, and a generic one it cannot improve on", () => {
|
|
40
|
+
assert.equal(selectedFileMimeType({mimeType: "Image/PNG", name: "photo.jpg"}), "image/png");
|
|
41
|
+
assert.equal(
|
|
42
|
+
selectedFileMimeType({mimeType: "application/octet-stream", name: "archive.zip"}),
|
|
43
|
+
"application/octet-stream"
|
|
44
|
+
);
|
|
45
|
+
assert.equal(
|
|
46
|
+
selectedFileMimeType({mimeType: "application/vnd.ms-excel", name: "sheet.xls"}),
|
|
47
|
+
"application/vnd.ms-excel"
|
|
48
|
+
);
|
|
49
|
+
assert.equal(selectedFileMimeType({mimeType: "", name: "README"}), "");
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
it("sends the extension's type in the data URL when the picker reports a generic one", async () => {
|
|
53
|
+
const ref = await selectedFileToDataUrlRef({
|
|
54
|
+
mimeType: "application/vnd.ms-excel",
|
|
55
|
+
name: "items.csv",
|
|
56
|
+
uri: textUri("application/vnd.ms-excel"),
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
assert.equal(ref.mimeType, "text/csv");
|
|
60
|
+
assert.isTrue(ref.url.startsWith("data:text/csv;base64,"));
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
it("reads a picked file into a data URL of its declared type, with its byte size", async () => {
|
|
64
|
+
const ref = await selectedFileToDataUrlRef({
|
|
65
|
+
mimeType: "text/csv; charset=utf-8",
|
|
66
|
+
name: "items.csv",
|
|
67
|
+
uri: textUri("application/octet-stream"),
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
assert.deepEqual(ref, {
|
|
71
|
+
filename: "items.csv",
|
|
72
|
+
mimeType: "text/csv",
|
|
73
|
+
size: Buffer.byteLength(TEXT),
|
|
74
|
+
url: `data:text/csv;base64,${Buffer.from(TEXT).toString("base64")}`,
|
|
75
|
+
});
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
it("resolves every file in order", async () => {
|
|
79
|
+
const refs = await resolveAskFilesAsDataUrls([
|
|
80
|
+
{mimeType: "text/plain", name: "a.txt", uri: textUri("text/plain")},
|
|
81
|
+
{mimeType: "image/png", name: "b.png", uri: "data:image/png;base64,iVBORw0KGgo="},
|
|
82
|
+
]);
|
|
83
|
+
|
|
84
|
+
assert.deepEqual(
|
|
85
|
+
refs.map(({filename, mimeType, size}) => ({filename, mimeType, size})),
|
|
86
|
+
[
|
|
87
|
+
{filename: "a.txt", mimeType: "text/plain", size: Buffer.byteLength(TEXT)},
|
|
88
|
+
{filename: "b.png", mimeType: "image/png", size: 8},
|
|
89
|
+
]
|
|
90
|
+
);
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
describe("with FileReader, as on web", () => {
|
|
94
|
+
const originalFileReader = globalThis.FileReader;
|
|
95
|
+
|
|
96
|
+
/** Reads a blob the way a browser FileReader does, or fails when the blob is empty. */
|
|
97
|
+
class FakeFileReader {
|
|
98
|
+
error: Error | null = null;
|
|
99
|
+
onerror: (() => void) | null = null;
|
|
100
|
+
onload: (() => void) | null = null;
|
|
101
|
+
result: string | null = null;
|
|
102
|
+
|
|
103
|
+
readAsDataURL(blob: Blob): void {
|
|
104
|
+
void blob.arrayBuffer().then((buffer) => {
|
|
105
|
+
if (buffer.byteLength === 0) {
|
|
106
|
+
this.error = new Error("The file is empty.");
|
|
107
|
+
this.onerror?.();
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
this.result = `data:${blob.type};base64,${Buffer.from(buffer).toString("base64")}`;
|
|
111
|
+
this.onload?.();
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
beforeEach(() => {
|
|
117
|
+
globalThis.FileReader = FakeFileReader as unknown as typeof FileReader;
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
afterEach(() => {
|
|
121
|
+
globalThis.FileReader = originalFileReader;
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
it("reads the file's bytes through FileReader", async () => {
|
|
125
|
+
const ref = await selectedFileToDataUrlRef({
|
|
126
|
+
mimeType: "text/plain",
|
|
127
|
+
name: "items.txt",
|
|
128
|
+
uri: textUri("text/plain"),
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
assert.deepEqual(ref, {
|
|
132
|
+
filename: "items.txt",
|
|
133
|
+
mimeType: "text/plain",
|
|
134
|
+
size: Buffer.byteLength(TEXT),
|
|
135
|
+
url: `data:text/plain;base64,${Buffer.from(TEXT).toString("base64")}`,
|
|
136
|
+
});
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
it("rejects when FileReader cannot read the file", async () => {
|
|
140
|
+
let error: unknown;
|
|
141
|
+
try {
|
|
142
|
+
await selectedFileToDataUrlRef({
|
|
143
|
+
mimeType: "text/plain",
|
|
144
|
+
name: "empty.txt",
|
|
145
|
+
uri: "data:text/plain;base64,",
|
|
146
|
+
});
|
|
147
|
+
} catch (caught) {
|
|
148
|
+
error = caught;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
assert.instanceOf(error, Error);
|
|
152
|
+
assert.equal((error as Error).message, "The file is empty.");
|
|
153
|
+
});
|
|
154
|
+
});
|
|
155
|
+
});
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import type {AskFileRef} from "@terreno/blocks";
|
|
2
|
+
|
|
3
|
+
import type {SelectedFile} from "../FilePickerButton";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Turns the files a user picked for a `files` ask into the refs its answer sends. Hosts with file
|
|
7
|
+
* storage upload each file and return `{fileId}` refs; others encode `{url}` data URLs. Throw to
|
|
8
|
+
* keep the ask open: the card shows that the files could not be sent.
|
|
9
|
+
*/
|
|
10
|
+
export type AskFilesResolver = (files: SelectedFile[]) => Promise<AskFileRef[]>;
|
|
11
|
+
|
|
12
|
+
/** The MIME type without parameters, lowercased: "Text/CSV; charset=utf-8" becomes "text/csv". */
|
|
13
|
+
export const normalizeMimeType = (mimeType: string): string =>
|
|
14
|
+
(mimeType.split(";")[0] ?? "").trim().toLowerCase();
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Types pickers report when they do not know the file's type. Windows browsers report a CSV as
|
|
18
|
+
* `application/vnd.ms-excel` when Excel is installed.
|
|
19
|
+
*/
|
|
20
|
+
const GENERIC_MIME_TYPES: readonly string[] = [
|
|
21
|
+
"",
|
|
22
|
+
"application/octet-stream",
|
|
23
|
+
"application/vnd.ms-excel",
|
|
24
|
+
];
|
|
25
|
+
|
|
26
|
+
/** The type of each extension a `files` ask can accept. */
|
|
27
|
+
const MIME_TYPE_BY_EXTENSION: Record<string, string> = {
|
|
28
|
+
csv: "text/csv",
|
|
29
|
+
gif: "image/gif",
|
|
30
|
+
jpeg: "image/jpeg",
|
|
31
|
+
jpg: "image/jpeg",
|
|
32
|
+
json: "application/json",
|
|
33
|
+
pdf: "application/pdf",
|
|
34
|
+
png: "image/png",
|
|
35
|
+
txt: "text/plain",
|
|
36
|
+
webp: "image/webp",
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* A picked file's MIME type, normalized. When the picker reports no type or a generic one, the
|
|
41
|
+
* type of the file's extension, if a `files` ask can accept that extension.
|
|
42
|
+
*/
|
|
43
|
+
export const selectedFileMimeType = (file: {mimeType: string; name: string}): string => {
|
|
44
|
+
const reported = normalizeMimeType(file.mimeType);
|
|
45
|
+
if (!GENERIC_MIME_TYPES.includes(reported)) {
|
|
46
|
+
return reported;
|
|
47
|
+
}
|
|
48
|
+
const extension = file.name.includes(".") ? file.name.split(".").pop()?.toLowerCase() : "";
|
|
49
|
+
return MIME_TYPE_BY_EXTENSION[extension ?? ""] ?? reported;
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
const readViaFileReader = (blob: Blob): Promise<string> =>
|
|
53
|
+
new Promise((resolve, reject) => {
|
|
54
|
+
const reader = new FileReader();
|
|
55
|
+
reader.onload = (): void => {
|
|
56
|
+
const result = String(reader.result ?? "");
|
|
57
|
+
resolve(result.slice(result.indexOf(",") + 1));
|
|
58
|
+
};
|
|
59
|
+
reader.onerror = (): void => reject(reader.error ?? new Error("The file could not be read."));
|
|
60
|
+
reader.readAsDataURL(blob);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
const readViaArrayBuffer = async (blob: Blob): Promise<string> => {
|
|
64
|
+
const bytes = new Uint8Array(await blob.arrayBuffer());
|
|
65
|
+
let binary = "";
|
|
66
|
+
for (const byte of bytes) {
|
|
67
|
+
binary += String.fromCharCode(byte);
|
|
68
|
+
}
|
|
69
|
+
return btoa(binary);
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
const base64Of = async (uri: string): Promise<string> => {
|
|
73
|
+
const response = await fetch(uri);
|
|
74
|
+
const blob = await response.blob();
|
|
75
|
+
return typeof FileReader === "undefined" ? readViaArrayBuffer(blob) : readViaFileReader(blob);
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
const decodedLength = (base64: string): number =>
|
|
79
|
+
Math.floor((base64.length * 3) / 4) - (base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0);
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Reads a picked file into a `{url}` ref: a base64 data URL whose media type is the file's
|
|
83
|
+
* `selectedFileMimeType`, with the size of its bytes.
|
|
84
|
+
*/
|
|
85
|
+
export const selectedFileToDataUrlRef = async (file: SelectedFile): Promise<AskFileRef> => {
|
|
86
|
+
const mimeType = selectedFileMimeType(file);
|
|
87
|
+
const base64 = await base64Of(file.uri);
|
|
88
|
+
return {
|
|
89
|
+
filename: file.name,
|
|
90
|
+
mimeType,
|
|
91
|
+
size: decodedLength(base64),
|
|
92
|
+
url: `data:${mimeType};base64,${base64}`,
|
|
93
|
+
};
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
/** The default `AskFilesResolver`: every file as a data URL, for hosts without file storage. */
|
|
97
|
+
export const resolveAskFilesAsDataUrls: AskFilesResolver = (files) =>
|
|
98
|
+
Promise.all(files.map(selectedFileToDataUrlRef));
|