@vettvangur/ai-sdk 0.5.2 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,102 @@
1
+ //#region src/live-chat/provider.d.ts
2
+ /**
3
+ * Whether a person can take a chat now. A provider gives `no-agents` only when it can tell; most
4
+ * know only their opening hours.
5
+ */
6
+ type AiLiveChatAvailability = {
7
+ status: 'open';
8
+ } | {
9
+ status: 'closed';
10
+ reason: 'out-of-hours' | 'no-agents';
11
+ };
12
+ type AiLiveChatFieldBase = {
13
+ /** What the provider expects the answer under; opaque to the window. */
14
+ id: string;
15
+ /** A stable name for prefilling, such as `Email`; the id when the provider has none. */
16
+ name: string;
17
+ /** Markdown: a survey can link its privacy policy from a label. */
18
+ label: string;
19
+ required: boolean;
20
+ };
21
+ type AiLiveChatTextField = AiLiveChatFieldBase & {
22
+ kind: 'text';
23
+ inputType: 'text' | 'email' | 'tel' | 'url';
24
+ multiline: boolean;
25
+ maxLength: number | null;
26
+ placeholder: string | null;
27
+ };
28
+ type AiLiveChatChoiceField = AiLiveChatFieldBase & {
29
+ kind: 'choice';
30
+ choices: {
31
+ label: string;
32
+ value: string;
33
+ }[];
34
+ multiple: boolean;
35
+ };
36
+ type AiLiveChatToggleField = AiLiveChatFieldBase & {
37
+ kind: 'toggle';
38
+ };
39
+ /** Text the survey shows between its questions. */
40
+ type AiLiveChatSurveyNote = {
41
+ kind: 'note';
42
+ text: string;
43
+ };
44
+ type AiLiveChatSurveyField = AiLiveChatTextField | AiLiveChatChoiceField | AiLiveChatToggleField | AiLiveChatSurveyNote;
45
+ /**
46
+ * Answers by field id: text and a single choice as their value, several choices as their values
47
+ * joined with commas, a toggle as a boolean.
48
+ */
49
+ type AiLiveChatAnswers = Record<string, string | boolean>;
50
+ type AiLiveChatStartOptions = {
51
+ answers?: AiLiveChatAnswers;
52
+ /** Values the agent sees with the conversation. */
53
+ context?: Record<string, string>;
54
+ /** Sent as the visitor's first message once the chat has started. */
55
+ openingMessage?: string;
56
+ /** A token from `resumeToken()`: reconnect to that chat instead of starting a new one. */
57
+ resume?: string;
58
+ };
59
+ type AiLiveChatMessage = {
60
+ id: string;
61
+ text: string;
62
+ sender: 'agent' | 'system';
63
+ /** The agent's display name, when the provider has one. */
64
+ name: string | null;
65
+ };
66
+ /**
67
+ * What the chat window needs from a live chat service. `onMessage`, `onTyping` and `onEnded` may
68
+ * be subscribed before `start()` and each return an unsubscribe. `onEnded` is for the agent's end
69
+ * of the chat; the visitor's goes through `end()`.
70
+ */
71
+ type AiLiveChatProvider = {
72
+ availability(): Promise<AiLiveChatAvailability>;
73
+ survey(): Promise<AiLiveChatSurveyField[] | null>;
74
+ start(options: AiLiveChatStartOptions): Promise<void>;
75
+ send(text: string): Promise<void>;
76
+ typing(): Promise<void>;
77
+ /**
78
+ * What the visitor has typed and not sent yet, for an agent's preview; empty once they clear the
79
+ * box. A provider with it gets this in place of `typing()`.
80
+ */
81
+ draft?(text: string): Promise<void>;
82
+ end(): Promise<void>;
83
+ onMessage(listener: (message: AiLiveChatMessage) => void): () => void;
84
+ onTyping(listener: () => void): () => void;
85
+ onEnded(listener: () => void): () => void;
86
+ /**
87
+ * When an agent takes the chat, and again after a reconnect. Without it the window takes the
88
+ * first agent message as the join.
89
+ */
90
+ onAgent?(listener: (agent: {
91
+ name: string | null;
92
+ }) => void): () => void;
93
+ /** A token that reconnects to the current chat after a page load, or null when there is none. */
94
+ resumeToken(): Promise<string | null>;
95
+ emailTranscript?(options: {
96
+ email: string;
97
+ message?: string;
98
+ }): Promise<void>;
99
+ upload?(file: File): Promise<void>;
100
+ };
101
+ //#endregion
102
+ export { AiLiveChatProvider as a, AiLiveChatSurveyNote as c, AiLiveChatMessage as i, AiLiveChatTextField as l, AiLiveChatAvailability as n, AiLiveChatStartOptions as o, AiLiveChatChoiceField as r, AiLiveChatSurveyField as s, AiLiveChatAnswers as t, AiLiveChatToggleField as u };
@@ -0,0 +1,163 @@
1
+ /*
2
+ * @vettvangur/ai-sdk/styles.css: an opt-in base for the elements the SDK renders. It holds the
3
+ * mechanics a thread needs to behave, not a look: how things hide, pulse, divide, scroll and
4
+ * switch. Colours, type and spacing stay with the host. Load it before the host's own styles; its
5
+ * selectors are as plain as each rule allows, so a later host rule of the same weight wins.
6
+ *
7
+ * Custom properties, set on the root or any ancestor:
8
+ * --vv-ai-chat-dot-size the tool and typing dots (0.375rem)
9
+ * --vv-ai-chat-dot-color the typing dots (currentColor)
10
+ * --vv-ai-chat-divider-color the lines either side of a divider notice (currentColor)
11
+ * --vv-ai-chat-divider-gap between a divider's text and its lines (0.625rem)
12
+ * --vv-ai-survey-toggle-width the survey's switch (2.125rem)
13
+ * --vv-ai-survey-toggle-height (1.25rem)
14
+ * --vv-ai-survey-toggle-inset between the switch's edge and its knob (0.125rem)
15
+ * --vv-ai-survey-toggle-off the switch's track when off (#9ca3af)
16
+ * --vv-ai-survey-toggle-on the switch's track when on (currentColor)
17
+ * --vv-ai-survey-toggle-knob the knob (#fff)
18
+ */
19
+
20
+ /* What the binding shows and hides with `hidden` stays hidden whatever display a host gives it. */
21
+ [data-ai-chat-send][hidden],
22
+ [data-ai-chat-stop][hidden],
23
+ [data-ai-chat-end][hidden],
24
+ [data-ai-launcher-teaser][hidden],
25
+ .vv-ai-survey__error[hidden] {
26
+ display: none !important;
27
+ }
28
+
29
+ /* A tool's progress dot pulses until the tool is done; the agent's typing dots pulse in turn. */
30
+ .vv-ai-chat__tool-dot,
31
+ .vv-ai-chat__typing-dot {
32
+ flex-shrink: 0;
33
+ width: var(--vv-ai-chat-dot-size, 0.375rem);
34
+ height: var(--vv-ai-chat-dot-size, 0.375rem);
35
+ border-radius: 50%;
36
+ animation: vv-ai-chat-pulse 1.2s ease-in-out infinite;
37
+ }
38
+
39
+ .vv-ai-chat__typing-dot {
40
+ background: var(--vv-ai-chat-dot-color, currentColor);
41
+ }
42
+
43
+ .vv-ai-chat__typing-dot:nth-child(2) {
44
+ animation-delay: 0.15s;
45
+ }
46
+
47
+ .vv-ai-chat__typing-dot:nth-child(3) {
48
+ animation-delay: 0.3s;
49
+ }
50
+
51
+ .vv-ai-chat__tool--done .vv-ai-chat__tool-dot {
52
+ animation: none;
53
+ }
54
+
55
+ @keyframes vv-ai-chat-pulse {
56
+ 0%,
57
+ 100% {
58
+ opacity: 0.3;
59
+ }
60
+
61
+ 50% {
62
+ opacity: 1;
63
+ }
64
+ }
65
+
66
+ /* The typing indicator's text is for screen readers; the dots show it. */
67
+ .vv-ai-chat__typing-label {
68
+ position: absolute;
69
+ width: 1px;
70
+ height: 1px;
71
+ margin: -1px;
72
+ padding: 0;
73
+ overflow: hidden;
74
+ clip-path: inset(50%);
75
+ white-space: nowrap;
76
+ border: 0;
77
+ }
78
+
79
+ /* Who answers from here on: a divider, its text between two lines. */
80
+ .vv-ai-chat__notice--started,
81
+ .vv-ai-chat__notice--joined,
82
+ .vv-ai-chat__notice--agent-ended,
83
+ .vv-ai-chat__notice--ended,
84
+ .vv-ai-chat__notice--system {
85
+ display: flex;
86
+ align-items: center;
87
+ gap: var(--vv-ai-chat-divider-gap, 0.625rem);
88
+ text-align: center;
89
+ }
90
+
91
+ .vv-ai-chat__notice--started::before,
92
+ .vv-ai-chat__notice--started::after,
93
+ .vv-ai-chat__notice--joined::before,
94
+ .vv-ai-chat__notice--joined::after,
95
+ .vv-ai-chat__notice--agent-ended::before,
96
+ .vv-ai-chat__notice--agent-ended::after,
97
+ .vv-ai-chat__notice--ended::before,
98
+ .vv-ai-chat__notice--ended::after,
99
+ .vv-ai-chat__notice--system::before,
100
+ .vv-ai-chat__notice--system::after {
101
+ content: "";
102
+ flex: 1;
103
+ height: 1px;
104
+ background: var(--vv-ai-chat-divider-color, currentColor);
105
+ }
106
+
107
+ /* A wide table scrolls inside its own region, and the scroll does not carry on into the page. */
108
+ .vv-ai-answer-card__table-region {
109
+ max-width: 100%;
110
+ overflow-x: auto;
111
+ overscroll-behavior-x: contain;
112
+ }
113
+
114
+ /*
115
+ * The survey's yes-or-no question as a switch. The input selector outweighs a host's own rule for
116
+ * every survey input, which would otherwise draw the switch as a text box.
117
+ */
118
+ .vv-ai-survey__field--toggle .vv-ai-survey__input[type="checkbox"] {
119
+ position: relative;
120
+ flex-shrink: 0;
121
+ width: var(--vv-ai-survey-toggle-width, 2.125rem);
122
+ height: var(--vv-ai-survey-toggle-height, 1.25rem);
123
+ margin: 0;
124
+ padding: 0;
125
+ cursor: pointer;
126
+ appearance: none;
127
+ background: var(--vv-ai-survey-toggle-off, #9ca3af);
128
+ border: 0;
129
+ border-radius: calc(var(--vv-ai-survey-toggle-height, 1.25rem) / 2);
130
+ transition: background-color 0.2s ease;
131
+ }
132
+
133
+ .vv-ai-survey__field--toggle .vv-ai-survey__input[type="checkbox"]::after {
134
+ content: "";
135
+ position: absolute;
136
+ top: var(--vv-ai-survey-toggle-inset, 0.125rem);
137
+ left: var(--vv-ai-survey-toggle-inset, 0.125rem);
138
+ width: calc(var(--vv-ai-survey-toggle-height, 1.25rem) - 2 * var(--vv-ai-survey-toggle-inset, 0.125rem));
139
+ height: calc(var(--vv-ai-survey-toggle-height, 1.25rem) - 2 * var(--vv-ai-survey-toggle-inset, 0.125rem));
140
+ background: var(--vv-ai-survey-toggle-knob, #fff);
141
+ border-radius: 50%;
142
+ transition: transform 0.2s ease;
143
+ }
144
+
145
+ .vv-ai-survey__field--toggle .vv-ai-survey__input[type="checkbox"]:checked {
146
+ background: var(--vv-ai-survey-toggle-on, currentColor);
147
+ }
148
+
149
+ .vv-ai-survey__field--toggle .vv-ai-survey__input[type="checkbox"]:checked::after {
150
+ transform: translateX(calc(var(--vv-ai-survey-toggle-width, 2.125rem) - var(--vv-ai-survey-toggle-height, 1.25rem)));
151
+ }
152
+
153
+ @media (prefers-reduced-motion: reduce) {
154
+ .vv-ai-chat__tool-dot,
155
+ .vv-ai-chat__typing-dot {
156
+ animation: none;
157
+ }
158
+
159
+ .vv-ai-survey__field--toggle .vv-ai-survey__input[type="checkbox"],
160
+ .vv-ai-survey__field--toggle .vv-ai-survey__input[type="checkbox"]::after {
161
+ transition: none;
162
+ }
163
+ }
@@ -0,0 +1,37 @@
1
+ import { i as isPlainObject } from "./dom.js";
2
+ //#region src/surfaces.ts
3
+ /**
4
+ * A surface that shows one item out of an authored list template. The template is cloned, every
5
+ * element carrying `attribute` whose value is not the payload's `key` field is removed, and the
6
+ * rest of the template stays as authored, so one item is the same markup the whole list shows.
7
+ * Null when the template is missing or no item matches.
8
+ */
9
+ function createTemplateItemSurface(options) {
10
+ return ({ root, data }) => {
11
+ const value = isPlainObject(data) ? data[options.key] : null;
12
+ const template = root.querySelector(`template[data-template="${CSS.escape(options.template)}"]`);
13
+ if (typeof value !== "string" || !template) return null;
14
+ const content = template.content.cloneNode(true);
15
+ let found = false;
16
+ for (const item of content.querySelectorAll(`[${CSS.escape(options.attribute)}]`)) if (item.getAttribute(options.attribute) === value) found = true;
17
+ else item.remove();
18
+ return found ? content : null;
19
+ };
20
+ }
21
+ /**
22
+ * A surface of which only the latest copy stays in the thread, for an embedded component whose
23
+ * script binds to the first match in the document or whose fields share ids. What it draws is
24
+ * marked with `data-ai-chat-single` under `key`, and drawing it again removes the earlier copies.
25
+ */
26
+ function createSingleSurface(key, surface) {
27
+ return (context) => {
28
+ const content = surface(context);
29
+ if (!content) return null;
30
+ for (const earlier of context.root.querySelectorAll(`[data-ai-chat-thread] [data-ai-chat-single="${CSS.escape(key)}"]`)) earlier.remove();
31
+ const elements = content instanceof Element ? [content] : content instanceof DocumentFragment ? Array.from(content.children) : [];
32
+ for (const element of elements) element.setAttribute("data-ai-chat-single", key);
33
+ return content;
34
+ };
35
+ }
36
+ //#endregion
37
+ export { createTemplateItemSurface as n, createSingleSurface as t };
package/dist/survey.js ADDED
@@ -0,0 +1,393 @@
1
+ import { a as isSafeLinkUrl, r as createSafeLink, t as createPart } from "./dom.js";
2
+ //#region src/markdown.ts
3
+ const MAX_MARKDOWN_CHARACTERS = 8e3;
4
+ function isWordCharacter(character) {
5
+ return character !== void 0 && /[\p{L}\p{N}]/u.test(character);
6
+ }
7
+ function delimitedToken(source, start, marker, type) {
8
+ if (!source.startsWith(marker, start)) return null;
9
+ const contentStart = start + marker.length;
10
+ const closing = source.indexOf(marker, contentStart);
11
+ if (closing === -1 || closing === contentStart) return null;
12
+ return {
13
+ type,
14
+ content: source.slice(contentStart, closing),
15
+ end: closing + marker.length
16
+ };
17
+ }
18
+ function linkToken(source, start) {
19
+ if (source[start] !== "[") return null;
20
+ let labelEnd = start + 1;
21
+ while (labelEnd < source.length) {
22
+ if (source[labelEnd] === "[") return null;
23
+ if (source[labelEnd] === "]" && source[labelEnd + 1] === "(") break;
24
+ labelEnd += 1;
25
+ }
26
+ if (labelEnd === source.length) return {
27
+ type: "text",
28
+ content: source.slice(start),
29
+ end: source.length
30
+ };
31
+ if (labelEnd === start + 1) return null;
32
+ let depth = 1;
33
+ let end = labelEnd + 2;
34
+ while (end < source.length && depth > 0) {
35
+ if (source[end] === "(") depth += 1;
36
+ else if (source[end] === ")") depth -= 1;
37
+ end += 1;
38
+ }
39
+ if (depth !== 0) return {
40
+ type: "text",
41
+ content: source.slice(start),
42
+ end: source.length
43
+ };
44
+ const url = source.slice(labelEnd + 2, end - 1);
45
+ if (!isSafeLinkUrl(url)) return {
46
+ type: "text",
47
+ content: source.slice(start, end),
48
+ end
49
+ };
50
+ return {
51
+ type: "link",
52
+ label: source.slice(start + 1, labelEnd),
53
+ url,
54
+ end
55
+ };
56
+ }
57
+ function inlineToken(source, start) {
58
+ const link = linkToken(source, start);
59
+ if (link) return link;
60
+ const code = delimitedToken(source, start, "`", "code");
61
+ if (code) return code;
62
+ const bold = delimitedToken(source, start, "**", "bold") ?? delimitedToken(source, start, "__", "bold");
63
+ if (bold) return bold;
64
+ const marker = source[start];
65
+ if ((marker === "*" || marker === "_") && !isWordCharacter(source[start - 1])) return delimitedToken(source, start, marker, "italic");
66
+ return null;
67
+ }
68
+ function inlineStructuralItemCount(source) {
69
+ let count = 0;
70
+ let index = 0;
71
+ while (index < source.length) {
72
+ const token = inlineToken(source, index);
73
+ if (!token) {
74
+ index += 1;
75
+ continue;
76
+ }
77
+ switch (token.type) {
78
+ case "bold":
79
+ case "italic":
80
+ count += 1 + inlineStructuralItemCount(token.content);
81
+ break;
82
+ case "code":
83
+ case "link": count += 1;
84
+ }
85
+ index = token.end;
86
+ }
87
+ return count;
88
+ }
89
+ function appendInlineMarkdown(document, parent, source) {
90
+ let textStart = 0;
91
+ let index = 0;
92
+ while (index < source.length) {
93
+ const token = inlineToken(source, index);
94
+ if (!token) {
95
+ index += 1;
96
+ continue;
97
+ }
98
+ if (textStart < index) parent.append(document.createTextNode(source.slice(textStart, index)));
99
+ switch (token.type) {
100
+ case "code": {
101
+ const code = document.createElement("code");
102
+ code.append(document.createTextNode(token.content));
103
+ parent.append(code);
104
+ break;
105
+ }
106
+ case "bold": {
107
+ const strong = document.createElement("strong");
108
+ appendInlineMarkdown(document, strong, token.content);
109
+ parent.append(strong);
110
+ break;
111
+ }
112
+ case "italic": {
113
+ const emphasis = document.createElement("em");
114
+ appendInlineMarkdown(document, emphasis, token.content);
115
+ parent.append(emphasis);
116
+ break;
117
+ }
118
+ case "link": {
119
+ const link = createSafeLink(document, token.label, token.url);
120
+ if (link) parent.append(link);
121
+ else parent.append(document.createTextNode(source.slice(index, token.end)));
122
+ break;
123
+ }
124
+ case "text": parent.append(document.createTextNode(token.content));
125
+ }
126
+ index = token.end;
127
+ textStart = index;
128
+ }
129
+ if (textStart < source.length) parent.append(document.createTextNode(source.slice(textStart)));
130
+ }
131
+ function unorderedListItem(line) {
132
+ return /^\s*[-+*]\s+(.+)$/.exec(line)?.[1] ?? null;
133
+ }
134
+ function orderedListItem(line) {
135
+ return /^\s*\d+[.)]\s+(.+)$/.exec(line)?.[1] ?? null;
136
+ }
137
+ function heading(line) {
138
+ return /^\s{0,3}#{1,6}\s+(.+?)\s*#*\s*$/.exec(line)?.[1] ?? null;
139
+ }
140
+ function countMarkdownStructuralItems(source) {
141
+ const lines = source.slice(0, MAX_MARKDOWN_CHARACTERS).split(/\r\n?|\n/);
142
+ let count = 0;
143
+ let index = 0;
144
+ while (index < lines.length) {
145
+ const line = lines[index];
146
+ if (line.trim().length === 0) {
147
+ index += 1;
148
+ continue;
149
+ }
150
+ const headingText = heading(line);
151
+ if (headingText !== null) {
152
+ count += 2 + inlineStructuralItemCount(headingText);
153
+ index += 1;
154
+ continue;
155
+ }
156
+ const unorderedItem = unorderedListItem(line);
157
+ const orderedItem = orderedListItem(line);
158
+ if (unorderedItem !== null || orderedItem !== null) {
159
+ const itemForLine = unorderedItem === null ? orderedListItem : unorderedListItem;
160
+ count += 1;
161
+ while (index < lines.length) {
162
+ const item = itemForLine(lines[index]);
163
+ if (item === null) break;
164
+ count += 1 + inlineStructuralItemCount(item);
165
+ index += 1;
166
+ }
167
+ continue;
168
+ }
169
+ const paragraphLines = [];
170
+ while (index < lines.length) {
171
+ const paragraphLine = lines[index];
172
+ if (paragraphLine.trim().length === 0 || heading(paragraphLine) !== null || unorderedListItem(paragraphLine) !== null || orderedListItem(paragraphLine) !== null) break;
173
+ paragraphLines.push(paragraphLine);
174
+ index += 1;
175
+ }
176
+ count += 1 + inlineStructuralItemCount(paragraphLines.join(" "));
177
+ }
178
+ return count;
179
+ }
180
+ function renderMarkdown(document, source) {
181
+ const fragment = document.createDocumentFragment();
182
+ const lines = source.slice(0, MAX_MARKDOWN_CHARACTERS).split(/\r\n?|\n/);
183
+ let index = 0;
184
+ while (index < lines.length) {
185
+ const line = lines[index];
186
+ if (line.trim().length === 0) {
187
+ index += 1;
188
+ continue;
189
+ }
190
+ const headingText = heading(line);
191
+ if (headingText !== null) {
192
+ const paragraph = document.createElement("p");
193
+ const strong = document.createElement("strong");
194
+ appendInlineMarkdown(document, strong, headingText);
195
+ paragraph.append(strong);
196
+ fragment.append(paragraph);
197
+ index += 1;
198
+ continue;
199
+ }
200
+ const unorderedItem = unorderedListItem(line);
201
+ const orderedItem = orderedListItem(line);
202
+ if (unorderedItem !== null || orderedItem !== null) {
203
+ const list = document.createElement(unorderedItem === null ? "ol" : "ul");
204
+ const itemForLine = unorderedItem === null ? orderedListItem : unorderedListItem;
205
+ while (index < lines.length) {
206
+ const item = itemForLine(lines[index]);
207
+ if (item === null) break;
208
+ const listItem = document.createElement("li");
209
+ appendInlineMarkdown(document, listItem, item);
210
+ list.append(listItem);
211
+ index += 1;
212
+ }
213
+ fragment.append(list);
214
+ continue;
215
+ }
216
+ const paragraphLines = [];
217
+ while (index < lines.length) {
218
+ const paragraphLine = lines[index];
219
+ if (paragraphLine.trim().length === 0 || heading(paragraphLine) !== null || unorderedListItem(paragraphLine) !== null || orderedListItem(paragraphLine) !== null) break;
220
+ paragraphLines.push(paragraphLine);
221
+ index += 1;
222
+ }
223
+ const paragraph = document.createElement("p");
224
+ appendInlineMarkdown(document, paragraph, paragraphLines.join(" "));
225
+ fragment.append(paragraph);
226
+ }
227
+ return fragment;
228
+ }
229
+ //#endregion
230
+ //#region src/live-chat/survey.ts
231
+ /** Every element of the survey form carries a class under this block. */
232
+ const SURVEY_CLASS = "vv-ai-survey";
233
+ let forms = 0;
234
+ function prefillFor(field, prefill) {
235
+ return prefill?.[field.name] ?? prefill?.[field.id];
236
+ }
237
+ function textControl(document, field, value) {
238
+ const input = field.multiline ? createPart(document, "textarea", SURVEY_CLASS, "input") : createPart(document, "input", SURVEY_CLASS, "input");
239
+ if (input instanceof HTMLInputElement) input.type = field.inputType;
240
+ if (field.maxLength) input.maxLength = field.maxLength;
241
+ if (field.placeholder) input.placeholder = field.placeholder;
242
+ if (typeof value === "string") input.value = value;
243
+ return input;
244
+ }
245
+ function choiceControl(document, field, value) {
246
+ const select = createPart(document, "select", SURVEY_CLASS, "input");
247
+ select.multiple = field.multiple;
248
+ if (!field.multiple) select.append(document.createElement("option"));
249
+ const wanted = typeof value === "string" ? value.split(",").map((item) => item.trim()) : [];
250
+ for (const choice of field.choices) {
251
+ const option = document.createElement("option");
252
+ option.value = choice.value;
253
+ option.textContent = choice.label;
254
+ select.append(option);
255
+ option.selected = wanted.includes(choice.value) || wanted.includes(choice.label);
256
+ }
257
+ return select;
258
+ }
259
+ function answerOf(control) {
260
+ const { field, input } = control;
261
+ if (field.kind === "toggle") return input.checked;
262
+ if (input instanceof HTMLSelectElement && input.multiple) return Array.from(input.selectedOptions, (option) => option.value).join(",");
263
+ return input.value.trim();
264
+ }
265
+ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
266
+ function problemOf(control) {
267
+ const answer = answerOf(control);
268
+ if (control.field.required && (answer === "" || answer === false)) return "missing";
269
+ if (control.input instanceof HTMLInputElement && control.input.type === "email" && answer !== "" && !EMAIL.test(String(answer))) return "email";
270
+ return null;
271
+ }
272
+ /**
273
+ * The pre-chat survey as a form in the thread. Prefilled fields are still shown, so the visitor
274
+ * sees and can change everything that is sent. A required toggle must be on, as a consent is.
275
+ * Submit stays disabled until every answer is valid, and a field says what is wrong with it once
276
+ * the visitor leaves it.
277
+ */
278
+ function renderSurveyForm(document, fields, options) {
279
+ forms += 1;
280
+ const form = createPart(document, "form", SURVEY_CLASS);
281
+ form.noValidate = true;
282
+ const controls = [];
283
+ if (options.labels.title || options.labels.intro) {
284
+ const header = createPart(document, "div", SURVEY_CLASS, "header");
285
+ if (options.labels.title) header.append(createPart(document, "p", SURVEY_CLASS, "title", options.labels.title));
286
+ if (options.labels.intro) header.append(createPart(document, "p", SURVEY_CLASS, "intro", options.labels.intro));
287
+ form.append(header);
288
+ }
289
+ fields.forEach((field, index) => {
290
+ if (field.kind === "note") {
291
+ const note = createPart(document, "div", SURVEY_CLASS, "note");
292
+ note.append(renderMarkdown(document, field.text));
293
+ form.append(note);
294
+ return;
295
+ }
296
+ const id = `${SURVEY_CLASS}-${forms}-${index}`;
297
+ const wrapper = createPart(document, "div", SURVEY_CLASS, "field");
298
+ wrapper.classList.add(`${SURVEY_CLASS}__field--${field.kind}`);
299
+ const label = createPart(document, "label", SURVEY_CLASS, "label");
300
+ label.htmlFor = id;
301
+ label.append(renderMarkdown(document, field.label));
302
+ const value = prefillFor(field, options.prefill);
303
+ let input;
304
+ if (field.kind === "text") input = textControl(document, field, value);
305
+ else if (field.kind === "choice") input = choiceControl(document, field, value);
306
+ else {
307
+ input = createPart(document, "input", SURVEY_CLASS, "input");
308
+ input.type = "checkbox";
309
+ input.checked = value === true || value === "true";
310
+ }
311
+ input.id = id;
312
+ input.name = field.name;
313
+ input.required = field.required;
314
+ const error = createPart(document, "p", SURVEY_CLASS, "error", options.labels.required);
315
+ error.id = `${id}-error`;
316
+ error.hidden = true;
317
+ input.setAttribute("aria-describedby", error.id);
318
+ if (field.kind === "toggle") wrapper.append(input, label, error);
319
+ else {
320
+ wrapper.append(label, input);
321
+ if (options.labels.prefilled && input.value !== "") wrapper.append(createPart(document, "p", SURVEY_CLASS, "prefilled", options.labels.prefilled));
322
+ wrapper.append(error);
323
+ }
324
+ form.append(wrapper);
325
+ controls.push({
326
+ field,
327
+ wrapper,
328
+ input,
329
+ error
330
+ });
331
+ });
332
+ const actions = createPart(document, "div", SURVEY_CLASS, "actions");
333
+ const submit = createPart(document, "button", SURVEY_CLASS, "submit", options.labels.submit);
334
+ submit.type = "submit";
335
+ const cancelButton = createPart(document, "button", SURVEY_CLASS, "cancel", options.labels.cancel);
336
+ cancelButton.type = "button";
337
+ actions.append(submit, cancelButton);
338
+ form.append(actions);
339
+ let settle = () => void 0;
340
+ const answers = new Promise((resolve) => {
341
+ settle = resolve;
342
+ });
343
+ let settled = false;
344
+ function finish(result) {
345
+ if (settled) return;
346
+ settled = true;
347
+ form.classList.add(`${SURVEY_CLASS}--${result ? "submitted" : "canceled"}`);
348
+ for (const element of form.querySelectorAll("input, textarea, select, button")) element.disabled = true;
349
+ settle(result);
350
+ }
351
+ function check(control) {
352
+ const problem = problemOf(control);
353
+ control.error.textContent = problem === "email" ? options.labels.invalidEmail ?? options.labels.required : options.labels.required;
354
+ control.wrapper.classList.toggle(`${SURVEY_CLASS}__field--invalid`, problem !== null);
355
+ control.input.setAttribute("aria-invalid", String(problem !== null));
356
+ control.error.hidden = problem === null;
357
+ return problem === null;
358
+ }
359
+ function update() {
360
+ if (!settled) submit.disabled = controls.some((control) => problemOf(control) !== null);
361
+ }
362
+ for (const control of controls) {
363
+ control.input.addEventListener("input", () => {
364
+ if (control.wrapper.classList.contains(`vv-ai-survey__field--invalid`)) check(control);
365
+ update();
366
+ });
367
+ control.input.addEventListener("change", () => {
368
+ check(control);
369
+ update();
370
+ });
371
+ }
372
+ update();
373
+ form.addEventListener("submit", (event) => {
374
+ event.preventDefault();
375
+ const invalid = controls.filter((control) => !check(control));
376
+ if (invalid.length) {
377
+ invalid[0]?.input.focus();
378
+ update();
379
+ return;
380
+ }
381
+ const result = {};
382
+ for (const control of controls) result[control.field.id] = answerOf(control);
383
+ finish(result);
384
+ });
385
+ cancelButton.addEventListener("click", () => finish(null));
386
+ return {
387
+ form,
388
+ answers,
389
+ cancel: () => finish(null)
390
+ };
391
+ }
392
+ //#endregion
393
+ export { renderMarkdown as i, renderSurveyForm as n, countMarkdownStructuralItems as r, SURVEY_CLASS as t };