@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,334 @@
1
+ import {
2
+ type AskResponse,
3
+ type AskValidationError,
4
+ type FormField,
5
+ validateAskResponse,
6
+ } from "@terreno/blocks";
7
+ import {DateTime} from "luxon";
8
+ import type React from "react";
9
+ import {useCallback, useMemo, useState} from "react";
10
+
11
+ import {BooleanField} from "../BooleanField";
12
+ import {Box} from "../Box";
13
+ import {Button} from "../Button";
14
+ import type {DateTimeEntryStatus} from "../Common";
15
+ import {DateTimeField} from "../DateTimeField";
16
+ import {MultiselectField} from "../MultiselectField";
17
+ import {SelectField} from "../SelectField";
18
+ import {Text} from "../Text";
19
+ import {TextArea} from "../TextArea";
20
+ import {TextField} from "../TextField";
21
+ import {type AskControlProps, AskErrors, SkipButton, useAnswerButton} from "./askControls";
22
+ import {
23
+ type FormDraft,
24
+ type FormDraftValue,
25
+ formatFormValue,
26
+ formDraftValues,
27
+ formFieldErrorText,
28
+ fromPickerValue,
29
+ initialFormDraft,
30
+ isFormFieldError,
31
+ toPickerValue,
32
+ type UnfinishedEntries,
33
+ unfinishedEntryText,
34
+ } from "./askFormDraft";
35
+ import type {ChatAsk} from "./askTypes";
36
+
37
+ const SUBMIT_ACTION_ID = "submit";
38
+
39
+ const TEXT_FIELD_TYPES = {
40
+ email: "email",
41
+ number: "text",
42
+ phone: "phoneNumber",
43
+ text: "text",
44
+ url: "url",
45
+ } as const;
46
+
47
+ export interface AskFormProps extends AskControlProps {
48
+ ask: Extract<ChatAsk, {kind: "form"}>;
49
+ }
50
+
51
+ /** Field ids the user has edited since the host last passed `errors`. */
52
+ interface EditedSinceErrors {
53
+ errors?: AskValidationError[];
54
+ ids: Record<string, true>;
55
+ }
56
+
57
+ const fieldTitle = (field: FormField): string =>
58
+ field.required === true ? `${field.label} (required)` : field.label;
59
+
60
+ const localTimezone = (): string => DateTime.local().zoneName ?? "UTC";
61
+
62
+ interface FormFieldControlProps {
63
+ disabled: boolean;
64
+ errorText?: string;
65
+ field: FormField;
66
+ onChange: (id: string, value: FormDraftValue) => void;
67
+ onEntryStatusChange: (id: string, status: DateTimeEntryStatus) => void;
68
+ onTimezoneChange: (id: string, timezone: string) => void;
69
+ testID: string;
70
+ timezone: string;
71
+ value: FormDraftValue;
72
+ }
73
+
74
+ /** The `@terreno/ui` control for one field, chosen by its type. */
75
+ const FormFieldControl = ({
76
+ disabled,
77
+ errorText,
78
+ field,
79
+ onChange,
80
+ onEntryStatusChange,
81
+ onTimezoneChange,
82
+ testID,
83
+ timezone,
84
+ value,
85
+ }: FormFieldControlProps): React.ReactElement => {
86
+ const shared = {
87
+ disabled,
88
+ errorText,
89
+ helperText: field.helperText,
90
+ testID,
91
+ title: fieldTitle(field),
92
+ };
93
+ const handleText = (text: string): void => onChange(field.id, text);
94
+
95
+ switch (field.type) {
96
+ case "boolean":
97
+ return (
98
+ <BooleanField
99
+ {...shared}
100
+ onChange={(checked) => onChange(field.id, checked)}
101
+ value={value === true}
102
+ />
103
+ );
104
+ case "select":
105
+ return (
106
+ <SelectField
107
+ {...shared}
108
+ onChange={handleText}
109
+ options={field.options.map((option) => ({label: option.label, value: option.id}))}
110
+ value={typeof value === "string" ? value : ""}
111
+ />
112
+ );
113
+ case "multiselect":
114
+ return (
115
+ <MultiselectField
116
+ {...shared}
117
+ onChange={(selected) => onChange(field.id, selected)}
118
+ options={field.options.map((option) => ({label: option.label, value: option.id}))}
119
+ value={Array.isArray(value) ? value : []}
120
+ />
121
+ );
122
+ case "date":
123
+ case "time":
124
+ case "datetime": {
125
+ const draft = typeof value === "string" ? value : "";
126
+ const pickerValue = toPickerValue({timezone, type: field.type, value: draft});
127
+ // DateTimeField reports a new zone, then in the same call emits the value read in that zone,
128
+ // before this render's `timezone` has updated.
129
+ let activeTimezone = timezone;
130
+ return (
131
+ <DateTimeField
132
+ {...shared}
133
+ onChange={(iso) => {
134
+ if (iso === (pickerValue ?? "")) {
135
+ return;
136
+ }
137
+ onChange(field.id, fromPickerValue({iso, timezone: activeTimezone, type: field.type}));
138
+ }}
139
+ onEntryStatusChange={(status) => onEntryStatusChange(field.id, status)}
140
+ onTimezoneChange={(nextTimezone) => {
141
+ activeTimezone = nextTimezone;
142
+ onTimezoneChange(field.id, nextTimezone);
143
+ }}
144
+ timezone={timezone}
145
+ type={field.type}
146
+ value={pickerValue}
147
+ />
148
+ );
149
+ }
150
+ case "textarea":
151
+ return (
152
+ <TextArea
153
+ {...shared}
154
+ onChange={handleText}
155
+ trimOnBlur={false}
156
+ value={typeof value === "string" ? value : ""}
157
+ />
158
+ );
159
+ default:
160
+ return (
161
+ <TextField
162
+ {...shared}
163
+ onChange={handleText}
164
+ trimOnBlur={false}
165
+ type={TEXT_FIELD_TYPES[field.type]}
166
+ value={typeof value === "string" ? value : ""}
167
+ />
168
+ );
169
+ }
170
+ };
171
+
172
+ /**
173
+ * Fill in a form's fields and submit them at once. Each field uses the `@terreno/ui` control for
174
+ * its type. Submit is enabled once the answer passes the ask's rules and no date field holds an
175
+ * unfinished entry; a field says what is wrong after the user edits it, and the host's `errors`
176
+ * for a field show on that field.
177
+ */
178
+ export const AskForm: React.FC<AskFormProps> = ({
179
+ ask,
180
+ errors,
181
+ isDisabled,
182
+ onAnswer,
183
+ pendingActionId,
184
+ testID,
185
+ }) => {
186
+ const {input} = ask;
187
+ const [draft, setDraft] = useState<FormDraft>(() => initialFormDraft(input));
188
+ const [touched, setTouched] = useState<Record<string, true>>({});
189
+ const [editedSinceErrors, setEditedSinceErrors] = useState<EditedSinceErrors>({ids: {}});
190
+ const [timezones, setTimezones] = useState<Record<string, string>>({});
191
+ const [unfinished, setUnfinished] = useState<UnfinishedEntries>({});
192
+ const isAnswering = pendingActionId !== undefined;
193
+ const renderButton = useAnswerButton({isDisabled, onAnswer, pendingActionId, testID});
194
+
195
+ const response = useMemo(
196
+ (): AskResponse => ({action: "accept", content: {values: formDraftValues({draft, input})}}),
197
+ [draft, input]
198
+ );
199
+ const clientErrors = useMemo(
200
+ () => validateAskResponse({input, kind: "form", response}),
201
+ [input, response]
202
+ );
203
+ const editedIds = editedSinceErrors.errors === errors ? editedSinceErrors.ids : {};
204
+
205
+ const handleChange = useCallback(
206
+ (id: string, value: FormDraftValue): void => {
207
+ if (isDisabled || isAnswering) {
208
+ return;
209
+ }
210
+ setDraft((previous) => ({...previous, [id]: value}));
211
+ setTouched((previous) => ({...previous, [id]: true}));
212
+ setEditedSinceErrors((previous) => ({
213
+ errors,
214
+ ids: previous.errors === errors ? {...previous.ids, [id]: true} : {[id]: true},
215
+ }));
216
+ },
217
+ [errors, isAnswering, isDisabled]
218
+ );
219
+
220
+ const handleEntryStatusChange = useCallback(
221
+ (id: string, status: DateTimeEntryStatus): void => {
222
+ if (isDisabled || isAnswering) {
223
+ return;
224
+ }
225
+ setUnfinished((previous) => {
226
+ if (status === "invalid") {
227
+ return previous[id] ? previous : {...previous, [id]: true};
228
+ }
229
+ if (!previous[id]) {
230
+ return previous;
231
+ }
232
+ const {[id]: _finished, ...rest} = previous;
233
+ return rest;
234
+ });
235
+ if (status === "empty") {
236
+ handleChange(id, "");
237
+ }
238
+ },
239
+ [handleChange, isAnswering, isDisabled]
240
+ );
241
+
242
+ const handleTimezoneChange = useCallback((id: string, timezone: string): void => {
243
+ setTimezones((previous) => ({...previous, [id]: timezone}));
244
+ }, []);
245
+
246
+ const handleSubmit = useCallback(
247
+ (): void | Promise<void> => onAnswer({actionId: SUBMIT_ACTION_ID, response}),
248
+ [onAnswer, response]
249
+ );
250
+
251
+ const fieldErrorText = (field: FormField): string | undefined => {
252
+ if (unfinished[field.id]) {
253
+ return unfinishedEntryText(field);
254
+ }
255
+ if (touched[field.id]) {
256
+ const clientText = formFieldErrorText({errors: clientErrors, field});
257
+ if (clientText) {
258
+ return clientText;
259
+ }
260
+ }
261
+ return editedIds[field.id] ? undefined : formFieldErrorText({errors: errors ?? [], field});
262
+ };
263
+
264
+ return (
265
+ <Box gap={3}>
266
+ {input.fields.map((field) => (
267
+ <Box key={field.id} testID={`${testID}-form-field-${field.id}`}>
268
+ <FormFieldControl
269
+ disabled={isDisabled || isAnswering}
270
+ errorText={fieldErrorText(field)}
271
+ field={field}
272
+ onChange={handleChange}
273
+ onEntryStatusChange={handleEntryStatusChange}
274
+ onTimezoneChange={handleTimezoneChange}
275
+ testID={`${testID}-field-${field.id}`}
276
+ timezone={timezones[field.id] ?? localTimezone()}
277
+ value={draft[field.id] ?? ""}
278
+ />
279
+ </Box>
280
+ ))}
281
+ <AskErrors
282
+ errors={errors?.filter((error) => !input.fields.some((f) => isFormFieldError(error, f)))}
283
+ testID={`${testID}-errors`}
284
+ />
285
+ <Box direction="row" gap={2} wrap>
286
+ <Button
287
+ disabled={
288
+ isDisabled ||
289
+ clientErrors.length > 0 ||
290
+ Object.keys(unfinished).length > 0 ||
291
+ (isAnswering && pendingActionId !== SUBMIT_ACTION_ID)
292
+ }
293
+ loading={pendingActionId === SUBMIT_ACTION_ID}
294
+ onClick={handleSubmit}
295
+ testID={`${testID}-submit`}
296
+ text={input.submitLabel ?? "Submit"}
297
+ wrapText
298
+ />
299
+ <SkipButton ask={ask} renderButton={renderButton} />
300
+ </Box>
301
+ </Box>
302
+ );
303
+ };
304
+
305
+ /**
306
+ * The values an answered `form` sent back, under its summary line: one "label: value" row per
307
+ * answered field, in the form's order.
308
+ */
309
+ export const AskFormAnswer = ({
310
+ ask,
311
+ testID,
312
+ values,
313
+ }: {
314
+ ask: Extract<ChatAsk, {kind: "form"}>;
315
+ testID: string;
316
+ values: Record<string, unknown>;
317
+ }): React.ReactElement | null => {
318
+ const rows = ask.input.fields.filter((field) => Object.hasOwn(values, field.id));
319
+ if (rows.length === 0) {
320
+ return null;
321
+ }
322
+ return (
323
+ <Box border="default" gap={2} padding={3} rounding="md" testID={`${testID}-answer`}>
324
+ {rows.map((field) => (
325
+ <Box key={field.id}>
326
+ <Text color="secondaryDark" size="sm">
327
+ {field.label}
328
+ </Text>
329
+ <Text>{formatFormValue({field, value: values[field.id]})}</Text>
330
+ </Box>
331
+ ))}
332
+ </Box>
333
+ );
334
+ };
@@ -0,0 +1,176 @@
1
+ import {
2
+ type AskResponse,
3
+ type AskValidationError,
4
+ type MarkdownAskInput,
5
+ markdownLengthBounds,
6
+ validateAskResponse,
7
+ } from "@terreno/blocks";
8
+ import type React from "react";
9
+ import {useCallback, useMemo, useState} from "react";
10
+
11
+ import {Box} from "../Box";
12
+ import {Button} from "../Button";
13
+ import {MarkdownEditorField} from "../MarkdownEditorField";
14
+ import {MarkdownView} from "../MarkdownView";
15
+ import {type AskControlProps, AskErrors, SkipButton, useAnswerButton} from "./askControls";
16
+ import {formatCount} from "./askSummary";
17
+ import type {ChatAsk} from "./askTypes";
18
+
19
+ const SUBMIT_ACTION_ID = "submit";
20
+
21
+ /** Answers longer than this show a preview in the transcript until the user expands them. */
22
+ export const MARKDOWN_ANSWER_PREVIEW_LENGTH = 280;
23
+
24
+ const WORD_BOUNDARY = /\s\S*$/;
25
+
26
+ export interface AskMarkdownProps extends AskControlProps {
27
+ ask: Extract<ChatAsk, {kind: "markdown"}>;
28
+ }
29
+
30
+ /** "120 / 2,000 characters. At least 20." from the draft's length and the ask's bounds. */
31
+ const lengthHint = (input: MarkdownAskInput, markdown: string): string => {
32
+ const {max, min} = markdownLengthBounds(input);
33
+ const count = `${formatCount(markdown.length)} / ${formatCount(max)} characters.`;
34
+ return min > 0 ? `${count} At least ${formatCount(min)}.` : count;
35
+ };
36
+
37
+ const editorErrorText = ({
38
+ errors,
39
+ input,
40
+ markdown,
41
+ }: {
42
+ errors?: AskValidationError[];
43
+ input: MarkdownAskInput;
44
+ markdown: string;
45
+ }): string | undefined => {
46
+ const {max} = markdownLengthBounds(input);
47
+ if (markdown.length > max) {
48
+ return `Keep this to ${formatCount(max)} characters or fewer.`;
49
+ }
50
+ return errors?.find((error) => error.path === "content.markdown")?.message;
51
+ };
52
+
53
+ /**
54
+ * Edit a markdown draft and send it back. The editor starts from the ask's `initial` draft, and
55
+ * Submit is enabled once the text meets the ask's length rules. The answer's `changed` says whether
56
+ * the text differs from the draft.
57
+ */
58
+ export const AskMarkdown: React.FC<AskMarkdownProps> = ({
59
+ ask,
60
+ errors,
61
+ isDisabled,
62
+ onAnswer,
63
+ pendingActionId,
64
+ testID,
65
+ }) => {
66
+ const {input} = ask;
67
+ const initial = input.initial ?? "";
68
+ const [markdown, setMarkdown] = useState<string>(initial);
69
+ const isAnswering = pendingActionId !== undefined;
70
+ const renderButton = useAnswerButton({isDisabled, onAnswer, pendingActionId, testID});
71
+
72
+ const draft = useMemo(
73
+ (): AskResponse => ({action: "accept", content: {changed: markdown !== initial, markdown}}),
74
+ [initial, markdown]
75
+ );
76
+ const isDraftValid = useMemo(
77
+ () => validateAskResponse({input, kind: "markdown", response: draft}).length === 0,
78
+ [draft, input]
79
+ );
80
+
81
+ const handleChange = useCallback(
82
+ (value: string): void => {
83
+ if (isDisabled || isAnswering) {
84
+ return;
85
+ }
86
+ setMarkdown(value);
87
+ },
88
+ [isAnswering, isDisabled]
89
+ );
90
+
91
+ const handleSubmit = useCallback(
92
+ (): void | Promise<void> => onAnswer({actionId: SUBMIT_ACTION_ID, response: draft}),
93
+ [draft, onAnswer]
94
+ );
95
+
96
+ return (
97
+ <Box gap={3}>
98
+ <MarkdownEditorField
99
+ disabled={isDisabled || isAnswering}
100
+ errorText={editorErrorText({errors, input, markdown})}
101
+ helperText={lengthHint(input, markdown)}
102
+ maxHeight={320}
103
+ onChange={handleChange}
104
+ placeholder={input.placeholder}
105
+ testID={`${testID}-editor`}
106
+ value={markdown}
107
+ />
108
+ <AskErrors
109
+ errors={errors?.filter((error) => error.path !== "content.markdown")}
110
+ testID={`${testID}-errors`}
111
+ />
112
+ <Box direction="row" gap={2} wrap>
113
+ <Button
114
+ disabled={
115
+ isDisabled || !isDraftValid || (isAnswering && pendingActionId !== SUBMIT_ACTION_ID)
116
+ }
117
+ loading={pendingActionId === SUBMIT_ACTION_ID}
118
+ onClick={handleSubmit}
119
+ testID={`${testID}-submit`}
120
+ text={input.submitLabel ?? "Submit"}
121
+ wrapText
122
+ />
123
+ <SkipButton ask={ask} renderButton={renderButton} />
124
+ </Box>
125
+ </Box>
126
+ );
127
+ };
128
+
129
+ /** The start of a long answer, cut at a word boundary when one falls in its second half. */
130
+ const previewOf = (markdown: string): string => {
131
+ let kept = markdown.slice(0, MARKDOWN_ANSWER_PREVIEW_LENGTH);
132
+ const boundary = kept.search(WORD_BOUNDARY);
133
+ if (boundary >= MARKDOWN_ANSWER_PREVIEW_LENGTH / 2) {
134
+ kept = kept.slice(0, boundary);
135
+ }
136
+ return `${kept.trimEnd()}…`;
137
+ };
138
+
139
+ /**
140
+ * The text an answered `markdown` ask sent back, under its summary line. A long answer shows a
141
+ * preview with Show all, so it does not push the rest of the transcript out of view.
142
+ */
143
+ export const AskMarkdownAnswer = ({
144
+ markdown,
145
+ testID,
146
+ }: {
147
+ markdown: string;
148
+ testID: string;
149
+ }): React.ReactElement | null => {
150
+ const [isExpanded, setIsExpanded] = useState(false);
151
+ const isLong = markdown.length > MARKDOWN_ANSWER_PREVIEW_LENGTH;
152
+
153
+ const handleToggle = useCallback((): void => {
154
+ setIsExpanded((wasExpanded) => !wasExpanded);
155
+ }, []);
156
+
157
+ if (markdown.trim() === "") {
158
+ return null;
159
+ }
160
+ return (
161
+ <Box border="default" gap={2} padding={3} rounding="md" testID={`${testID}-answer`}>
162
+ <MarkdownView>{isLong && !isExpanded ? previewOf(markdown) : markdown}</MarkdownView>
163
+ {isLong ? (
164
+ <Box alignSelf="start">
165
+ <Button
166
+ iconName={isExpanded ? "chevron-up" : "chevron-down"}
167
+ onClick={handleToggle}
168
+ testID={`${testID}-answer-toggle`}
169
+ text={isExpanded ? "Show less" : "Show all"}
170
+ variant="ghost"
171
+ />
172
+ </Box>
173
+ ) : null}
174
+ </Box>
175
+ );
176
+ };