@wakflo/react 0.0.0-stage → 0.1.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.
package/dist/index.js ADDED
@@ -0,0 +1,890 @@
1
+ "use client";
2
+
3
+ // src/index.ts
4
+ import { PublicError } from "@wakflo/client";
5
+
6
+ // src/contact-form.tsx
7
+ import { useId, useState } from "react";
8
+ import { jsx, jsxs } from "react/jsx-runtime";
9
+ var TYPES = ["text", "email", "number", "textarea"];
10
+ var DEFAULT_CONTACT_FIELDS = [
11
+ { key: "name", label: "Name", required: true, type: "text" },
12
+ { key: "email", label: "Work email", required: true, type: "email" },
13
+ { key: "company", label: "Company", required: false, type: "text" },
14
+ { key: "team_size", label: "Team size", required: false, type: "text" },
15
+ {
16
+ key: "question",
17
+ label: "What would you like to talk about?",
18
+ required: false,
19
+ type: "textarea"
20
+ }
21
+ ];
22
+ function contactPrefill(args) {
23
+ const out = {};
24
+ for (const [k, v] of Object.entries(args)) {
25
+ if (k === "fields" || k === "title") {
26
+ continue;
27
+ }
28
+ if (typeof v === "string" || typeof v === "number") {
29
+ out[k] = String(v);
30
+ }
31
+ }
32
+ return out;
33
+ }
34
+ function contactFields(args) {
35
+ const raw = Array.isArray(args.fields) ? args.fields : [];
36
+ const fields = [];
37
+ for (const f of raw) {
38
+ if (!(f && typeof f === "object")) {
39
+ continue;
40
+ }
41
+ const r = f;
42
+ if (typeof r.key !== "string" || r.key === "") {
43
+ continue;
44
+ }
45
+ fields.push({
46
+ key: r.key,
47
+ label: typeof r.label === "string" && r.label ? r.label : r.key,
48
+ type: TYPES.includes(r.type) ? r.type : "text",
49
+ required: r.required === true
50
+ });
51
+ }
52
+ return fields.length > 0 ? fields : [...DEFAULT_CONTACT_FIELDS];
53
+ }
54
+ function ContactForm({ call, onSubmit }) {
55
+ const id = useId();
56
+ const fields = contactFields(call.args);
57
+ const title = typeof call.args.title === "string" && call.args.title ? call.args.title : "Your details";
58
+ const [values, setValues] = useState(
59
+ () => contactPrefill(call.args)
60
+ );
61
+ const [sent, setSent] = useState(false);
62
+ const submit = (e) => {
63
+ e.preventDefault();
64
+ const out = {};
65
+ for (const f of fields) {
66
+ const v = (values[f.key] ?? "").trim();
67
+ if (v === "") {
68
+ continue;
69
+ }
70
+ const n = Number(v);
71
+ out[f.key] = f.type === "number" && !Number.isNaN(n) ? n : v;
72
+ }
73
+ setSent(true);
74
+ onSubmit(out);
75
+ };
76
+ return /* @__PURE__ */ jsxs("form", { "aria-label": title, className: "wakflo-chat__card", onSubmit: submit, children: [
77
+ /* @__PURE__ */ jsx("p", { className: "wakflo-chat__card-title", children: title }),
78
+ fields.map((f) => {
79
+ const fieldId = `${id}-${f.key}`;
80
+ const common = {
81
+ className: "wakflo-chat__input",
82
+ disabled: sent,
83
+ id: fieldId,
84
+ name: f.key,
85
+ required: f.required,
86
+ value: values[f.key] ?? "",
87
+ onChange: (e) => setValues((v) => ({ ...v, [f.key]: e.target.value }))
88
+ };
89
+ return /* @__PURE__ */ jsxs("label", { className: "wakflo-chat__field", htmlFor: fieldId, children: [
90
+ /* @__PURE__ */ jsxs("span", { children: [
91
+ f.label,
92
+ f.required ? null : /* @__PURE__ */ jsx("span", { className: "wakflo-chat__optional", children: " (optional)" })
93
+ ] }),
94
+ f.type === "textarea" ? /* @__PURE__ */ jsx("textarea", { ...common, rows: 3 }) : /* @__PURE__ */ jsx("input", { ...common, type: f.type })
95
+ ] }, f.key);
96
+ }),
97
+ /* @__PURE__ */ jsx("button", { className: "wakflo-chat__button", disabled: sent, type: "submit", children: sent ? "Sent" : "Send" })
98
+ ] });
99
+ }
100
+
101
+ // src/use-wakflo-chat.ts
102
+ import {
103
+ createClient
104
+ } from "@wakflo/client";
105
+ import {
106
+ useCallback,
107
+ useEffect,
108
+ useMemo,
109
+ useRef,
110
+ useState as useState2,
111
+ useSyncExternalStore
112
+ } from "react";
113
+ var ok = (p) => p.then(
114
+ () => true,
115
+ () => false
116
+ );
117
+ function useWakfloChat(options) {
118
+ const latest = useRef(options);
119
+ latest.current = options;
120
+ const { apiUrl, baseUrl, publishableKey } = options;
121
+ const client = useMemo(() => {
122
+ const o = latest.current;
123
+ return createClient({
124
+ apiUrl,
125
+ baseUrl,
126
+ publishableKey,
127
+ fetch: o.fetch,
128
+ storage: o.storage,
129
+ reconnectDelay: o.reconnectDelay,
130
+ // Asked each time, so a changed prop is used without a new client.
131
+ botToken: () => latest.current.botToken?.() ?? null,
132
+ portalToken: () => latest.current.portalToken?.() ?? null
133
+ });
134
+ }, [apiUrl, baseUrl, publishableKey]);
135
+ const chat = useMemo(() => client.conversation(), [client]);
136
+ const subscribe = useCallback(
137
+ (listener) => chat.subscribe(listener),
138
+ [chat]
139
+ );
140
+ const read = useCallback(() => chat.state, [chat]);
141
+ const state = useSyncExternalStore(subscribe, read, read);
142
+ const [config, setConfig] = useState2(null);
143
+ useEffect(() => {
144
+ let live = true;
145
+ client.config().then(
146
+ (c) => {
147
+ if (live) {
148
+ setConfig(c);
149
+ }
150
+ },
151
+ () => {
152
+ }
153
+ );
154
+ return () => {
155
+ live = false;
156
+ };
157
+ }, [client]);
158
+ const connect = options.connect !== false;
159
+ useEffect(() => {
160
+ if (!connect) {
161
+ return;
162
+ }
163
+ chat.connect();
164
+ return () => chat.disconnect();
165
+ }, [chat, connect]);
166
+ const [open, setOpen] = useState2(options.defaultOpen ?? false);
167
+ const answers = useRef({
168
+ runId: "",
169
+ results: /* @__PURE__ */ new Map()
170
+ });
171
+ const respond = useCallback(
172
+ (callId, result, error) => {
173
+ const pending = chat.pendingTool;
174
+ if (!pending?.calls.some((c) => c.id === callId)) {
175
+ return;
176
+ }
177
+ if (answers.current.runId !== pending.runId) {
178
+ answers.current = { runId: pending.runId, results: /* @__PURE__ */ new Map() };
179
+ }
180
+ const { results } = answers.current;
181
+ results.set(callId, {
182
+ toolCallId: callId,
183
+ result,
184
+ ...error ? { error } : {}
185
+ });
186
+ if (pending.calls.every((c) => results.has(c.id))) {
187
+ const all = pending.calls.map((c) => results.get(c.id)).filter((r) => r !== void 0);
188
+ chat.answerTool(pending.runId, all).catch(() => {
189
+ results.clear();
190
+ });
191
+ }
192
+ },
193
+ [chat]
194
+ );
195
+ const send = useCallback((content) => ok(chat.send(content)), [chat]);
196
+ const handover = useCallback(() => ok(chat.handover()), [chat]);
197
+ const setEmail = useCallback(
198
+ (email, name) => ok(chat.setEmail(email, name)),
199
+ [chat]
200
+ );
201
+ const reset = useCallback(() => chat.reset(), [chat]);
202
+ return {
203
+ client,
204
+ chat,
205
+ config,
206
+ conversation: state.conversation,
207
+ status: state.conversation?.status ?? null,
208
+ messages: state.messages,
209
+ typing: state.typing,
210
+ pendingTool: state.pendingTool,
211
+ toolCall: state.pendingTool,
212
+ notices: state.notices,
213
+ connection: state.connection,
214
+ error: state.error,
215
+ send,
216
+ handover,
217
+ setEmail,
218
+ respond,
219
+ reset,
220
+ open,
221
+ setOpen
222
+ };
223
+ }
224
+
225
+ // src/wakflo-chat.tsx
226
+ import {
227
+ MAX_MESSAGE_LENGTH
228
+ } from "@wakflo/client";
229
+ import {
230
+ useEffect as useEffect2,
231
+ useId as useId2,
232
+ useMemo as useMemo2,
233
+ useRef as useRef2,
234
+ useState as useState3
235
+ } from "react";
236
+
237
+ // src/icons.tsx
238
+ import { jsx as jsx2 } from "react/jsx-runtime";
239
+ function Spark() {
240
+ return /* @__PURE__ */ jsx2(
241
+ "svg",
242
+ {
243
+ "aria-hidden": "true",
244
+ fill: "currentColor",
245
+ focusable: "false",
246
+ height: "13",
247
+ viewBox: "0 0 24 24",
248
+ width: "13",
249
+ children: /* @__PURE__ */ jsx2("path", { d: "M12 2.5c.4 4.6 2.9 7.1 7.5 7.5v.1c-4.6.4-7.1 2.9-7.5 7.5h-.1c-.4-4.6-2.9-7.1-7.4-7.5V10c4.5-.4 7-2.9 7.4-7.5z" })
250
+ }
251
+ );
252
+ }
253
+ var stroke = {
254
+ fill: "none",
255
+ height: 16,
256
+ stroke: "currentColor",
257
+ strokeLinecap: "round",
258
+ strokeLinejoin: "round",
259
+ strokeWidth: 2,
260
+ viewBox: "0 0 24 24",
261
+ width: 16
262
+ };
263
+ function Pencil() {
264
+ return /* @__PURE__ */ jsx2("svg", { "aria-hidden": "true", focusable: "false", ...stroke, children: /* @__PURE__ */ jsx2("path", { d: "M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z" }) });
265
+ }
266
+ function Close() {
267
+ return /* @__PURE__ */ jsx2("svg", { "aria-hidden": "true", focusable: "false", ...stroke, children: /* @__PURE__ */ jsx2("path", { d: "M18 6 6 18M6 6l12 12" }) });
268
+ }
269
+ function Arrow() {
270
+ return /* @__PURE__ */ jsx2("svg", { "aria-hidden": "true", focusable: "false", ...stroke, children: /* @__PURE__ */ jsx2("path", { d: "M5 12h14M13 6l6 6-6 6" }) });
271
+ }
272
+
273
+ // src/markdown.tsx
274
+ import { jsx as jsx3 } from "react/jsx-runtime";
275
+ var BULLET = /^\s*[-*+]\s+(.*)$/;
276
+ var NUMBERED = /^\s*\d+[.)]\s+(.*)$/;
277
+ var HEADING = /^\s*#{1,6}\s+(.*)$/;
278
+ var INLINE = /\*\*([^*]+)\*\*|\[([^\]]+)\]\(([^)\s]+)\)|`([^`]+)`|(https?:\/\/[^\s<]+)/g;
279
+ var TRAILING_PUNCTUATION = /[.,;:!?)]+$/;
280
+ var SAFE_PROTOCOLS = /* @__PURE__ */ new Set(["http:", "https:", "mailto:"]);
281
+ function parseBlocks(text) {
282
+ const blocks = [];
283
+ let para = [];
284
+ let list2 = null;
285
+ const flush = () => {
286
+ if (para.length > 0) {
287
+ blocks.push({ kind: "p", lines: para });
288
+ para = [];
289
+ }
290
+ if (list2) {
291
+ blocks.push(list2);
292
+ list2 = null;
293
+ }
294
+ };
295
+ for (const line of text.replace(/\r\n?/g, "\n").split("\n")) {
296
+ const bullet = BULLET.exec(line);
297
+ const numbered = bullet ? null : NUMBERED.exec(line);
298
+ const item = bullet ?? numbered;
299
+ if (item) {
300
+ const kind = bullet ? "ul" : "ol";
301
+ if (para.length > 0 || list2?.kind !== kind) {
302
+ flush();
303
+ list2 = { kind, items: [] };
304
+ }
305
+ list2?.items.push(item[1] ?? "");
306
+ continue;
307
+ }
308
+ if (line.trim() === "") {
309
+ flush();
310
+ continue;
311
+ }
312
+ if (list2) {
313
+ flush();
314
+ }
315
+ para.push(HEADING.exec(line)?.[1] ?? line);
316
+ }
317
+ flush();
318
+ return blocks;
319
+ }
320
+ function safeHref(url) {
321
+ try {
322
+ const parsed = new URL(url);
323
+ return SAFE_PROTOCOLS.has(parsed.protocol) ? parsed.href : null;
324
+ } catch {
325
+ return null;
326
+ }
327
+ }
328
+ function link(href, label, key) {
329
+ return /* @__PURE__ */ jsx3("a", { href, rel: "noopener noreferrer", target: "_blank", children: label }, key);
330
+ }
331
+ function inline(text, prefix = "i") {
332
+ const out = [];
333
+ let last = 0;
334
+ let n = 0;
335
+ for (const m of text.matchAll(INLINE)) {
336
+ const at = m.index ?? 0;
337
+ if (at > last) {
338
+ out.push(text.slice(last, at));
339
+ }
340
+ n += 1;
341
+ const key = `${prefix}.${n}`;
342
+ const [whole, bold, label, url, code, bare] = m;
343
+ let end = at + whole.length;
344
+ if (bold !== void 0) {
345
+ out.push(/* @__PURE__ */ jsx3("strong", { children: inline(bold, key) }, key));
346
+ } else if (label !== void 0 && url !== void 0) {
347
+ const href = safeHref(url);
348
+ out.push(href ? link(href, label, key) : label);
349
+ } else if (code !== void 0) {
350
+ out.push(/* @__PURE__ */ jsx3("code", { children: code }, key));
351
+ } else if (bare !== void 0) {
352
+ const trimmed = bare.replace(TRAILING_PUNCTUATION, "");
353
+ end = at + trimmed.length;
354
+ const href = safeHref(trimmed);
355
+ out.push(href ? link(href, trimmed, key) : trimmed);
356
+ }
357
+ last = end;
358
+ }
359
+ if (last < text.length) {
360
+ out.push(text.slice(last));
361
+ }
362
+ return out;
363
+ }
364
+ function paragraph(lines, key) {
365
+ const out = [];
366
+ let l = 0;
367
+ for (const line of lines) {
368
+ if (l > 0) {
369
+ out.push(/* @__PURE__ */ jsx3("br", {}, `${key}.br${l}`));
370
+ }
371
+ out.push(...inline(line, `${key}.${l}`));
372
+ l += 1;
373
+ }
374
+ return /* @__PURE__ */ jsx3("p", { children: out }, key);
375
+ }
376
+ function list(block, key) {
377
+ const items = [];
378
+ let i = 0;
379
+ for (const item of block.items) {
380
+ const itemKey = `${key}.${i}`;
381
+ items.push(/* @__PURE__ */ jsx3("li", { children: inline(item, itemKey) }, itemKey));
382
+ i += 1;
383
+ }
384
+ return block.kind === "ul" ? /* @__PURE__ */ jsx3("ul", { children: items }, key) : /* @__PURE__ */ jsx3("ol", { children: items }, key);
385
+ }
386
+ function Markdown({ text }) {
387
+ const out = [];
388
+ let b = 0;
389
+ for (const block of parseBlocks(text)) {
390
+ const key = `b${b}`;
391
+ out.push(
392
+ block.kind === "p" ? paragraph(block.lines, key) : list(block, key)
393
+ );
394
+ b += 1;
395
+ }
396
+ return out;
397
+ }
398
+
399
+ // src/wakflo-chat.tsx
400
+ import { Fragment, jsx as jsx4, jsxs as jsxs2 } from "react/jsx-runtime";
401
+ var WAITING_LINE = "I've asked the team. Someone usually answers within a few minutes.";
402
+ var EMAIL_ASK = "Nobody from the team is free right now. Leave your email and we'll answer there.";
403
+ var UNSUPPORTED = "unsupported_tool";
404
+ var ASK_PREFIX = /^ask\s+/i;
405
+ var SPACE = /\s+/;
406
+ var APPLE = /mac|iphone|ipad/i;
407
+ function initials(name) {
408
+ const parts = name.trim().split(SPACE).filter(Boolean);
409
+ const first = parts[0]?.[0] ?? "";
410
+ const last = parts.length > 1 ? parts.at(-1)?.[0] ?? "" : "";
411
+ return (first + last).toUpperCase() || "?";
412
+ }
413
+ function placeholderFor(title) {
414
+ return ASK_PREFIX.test(title) ? `Ask about ${title.replace(ASK_PREFIX, "")}` : "Ask a question";
415
+ }
416
+ function useIsMac() {
417
+ const [mac, setMac] = useState3(true);
418
+ useEffect2(() => {
419
+ const nav = globalThis.navigator;
420
+ const platform = nav?.userAgentData?.platform ?? nav?.platform ?? "";
421
+ setMac(APPLE.test(platform));
422
+ }, []);
423
+ return mac;
424
+ }
425
+ function MessageView({
426
+ message,
427
+ onRetry
428
+ }) {
429
+ const { author } = message;
430
+ if (author.kind === "system") {
431
+ return /* @__PURE__ */ jsx4("p", { className: "wakflo-chat__system", children: message.content });
432
+ }
433
+ if (author.kind === "visitor") {
434
+ return /* @__PURE__ */ jsxs2("div", { className: "wakflo-chat__mine", children: [
435
+ /* @__PURE__ */ jsx4("div", { className: "wakflo-chat__bubble wakflo-chat__bubble--me", children: message.content }),
436
+ message.failed ? /* @__PURE__ */ jsx4(
437
+ "button",
438
+ {
439
+ className: "wakflo-chat__retry",
440
+ onClick: () => onRetry(message.id),
441
+ type: "button",
442
+ children: "Not sent. Try again"
443
+ }
444
+ ) : null
445
+ ] });
446
+ }
447
+ const body = message.streaming && message.content === "" ? /* @__PURE__ */ jsx4(Dots, {}) : /* @__PURE__ */ jsx4(Markdown, { text: message.content });
448
+ if (author.kind === "member") {
449
+ return /* @__PURE__ */ jsxs2("div", { className: "wakflo-chat__member", children: [
450
+ /* @__PURE__ */ jsx4("span", { "aria-hidden": "true", className: "wakflo-chat__avatar", children: initials(author.name) }),
451
+ /* @__PURE__ */ jsxs2("div", { className: "wakflo-chat__member-body", children: [
452
+ /* @__PURE__ */ jsx4("span", { className: "wakflo-chat__name", children: author.name }),
453
+ /* @__PURE__ */ jsx4("div", { className: "wakflo-chat__bubble", children: body })
454
+ ] })
455
+ ] });
456
+ }
457
+ return /* @__PURE__ */ jsx4(
458
+ "div",
459
+ {
460
+ "aria-busy": message.streaming ? true : void 0,
461
+ className: "wakflo-chat__bubble",
462
+ "data-streaming": message.streaming ? "true" : void 0,
463
+ children: body
464
+ }
465
+ );
466
+ }
467
+ function Dots() {
468
+ return /* @__PURE__ */ jsxs2("span", { className: "wakflo-chat__dots", children: [
469
+ /* @__PURE__ */ jsx4("span", {}),
470
+ /* @__PURE__ */ jsx4("span", {}),
471
+ /* @__PURE__ */ jsx4("span", {})
472
+ ] });
473
+ }
474
+ function EmailAsk({
475
+ notice,
476
+ onSubmit
477
+ }) {
478
+ const id = useId2();
479
+ const [email, setEmail] = useState3("");
480
+ const [name, setName] = useState3("");
481
+ const [busy, setBusy] = useState3(false);
482
+ const submit = async (e) => {
483
+ e.preventDefault();
484
+ if (!email.trim()) {
485
+ return;
486
+ }
487
+ setBusy(true);
488
+ await onSubmit(email.trim(), name.trim() || void 0);
489
+ setBusy(false);
490
+ };
491
+ return /* @__PURE__ */ jsxs2(Fragment, { children: [
492
+ /* @__PURE__ */ jsx4("div", { className: "wakflo-chat__bubble", children: notice.message || EMAIL_ASK }),
493
+ /* @__PURE__ */ jsxs2(
494
+ "form",
495
+ {
496
+ "aria-label": "Leave your email",
497
+ className: "wakflo-chat__card",
498
+ onSubmit: submit,
499
+ children: [
500
+ /* @__PURE__ */ jsxs2("label", { className: "wakflo-chat__field", htmlFor: `${id}-email`, children: [
501
+ /* @__PURE__ */ jsx4("span", { children: "Email" }),
502
+ /* @__PURE__ */ jsx4(
503
+ "input",
504
+ {
505
+ autoComplete: "email",
506
+ className: "wakflo-chat__input",
507
+ disabled: busy,
508
+ id: `${id}-email`,
509
+ onChange: (e) => setEmail(e.target.value),
510
+ required: true,
511
+ type: "email",
512
+ value: email
513
+ }
514
+ )
515
+ ] }),
516
+ /* @__PURE__ */ jsxs2("label", { className: "wakflo-chat__field", htmlFor: `${id}-name`, children: [
517
+ /* @__PURE__ */ jsxs2("span", { children: [
518
+ "Name",
519
+ /* @__PURE__ */ jsx4("span", { className: "wakflo-chat__optional", children: " (optional)" })
520
+ ] }),
521
+ /* @__PURE__ */ jsx4(
522
+ "input",
523
+ {
524
+ autoComplete: "name",
525
+ className: "wakflo-chat__input",
526
+ disabled: busy,
527
+ id: `${id}-name`,
528
+ onChange: (e) => setName(e.target.value),
529
+ type: "text",
530
+ value: name
531
+ }
532
+ )
533
+ ] }),
534
+ /* @__PURE__ */ jsx4("button", { className: "wakflo-chat__button", disabled: busy, type: "submit", children: "Send" })
535
+ ]
536
+ }
537
+ )
538
+ ] });
539
+ }
540
+ function StatusLines({
541
+ available,
542
+ conversation,
543
+ notices,
544
+ setEmail
545
+ }) {
546
+ const askEmail = [...notices].reverse().find((n) => n.code === "ask_email");
547
+ const others = notices.filter((n) => n.code !== "ask_email");
548
+ const status = conversation?.status;
549
+ return /* @__PURE__ */ jsxs2(Fragment, { children: [
550
+ status === "waiting" && available && !askEmail ? /* @__PURE__ */ jsx4("div", { className: "wakflo-chat__bubble", children: WAITING_LINE }) : null,
551
+ askEmail && !conversation?.email ? /* @__PURE__ */ jsx4(EmailAsk, { notice: askEmail, onSubmit: setEmail }) : null,
552
+ conversation?.email && status === "waiting" ? /* @__PURE__ */ jsxs2("p", { className: "wakflo-chat__system", children: [
553
+ "We'll answer at ",
554
+ conversation.email,
555
+ "."
556
+ ] }) : null,
557
+ others.map((n) => /* @__PURE__ */ jsx4("p", { className: "wakflo-chat__system", children: n.message || n.code }, `${n.code}:${n.message}`))
558
+ ] });
559
+ }
560
+ function themeOf(prop, config) {
561
+ return prop ?? config?.theme ?? "system";
562
+ }
563
+ function useTools(state, renderTool) {
564
+ const drawn = [];
565
+ const declined = [];
566
+ for (const call of state.pendingTool?.calls ?? []) {
567
+ const respond2 = (result, error) => state.respond(call.id, result, error);
568
+ const custom = renderTool?.(call, respond2);
569
+ if (custom !== void 0 && custom !== null) {
570
+ drawn.push({ call, node: custom });
571
+ } else if (call.name === "contact_form") {
572
+ drawn.push({
573
+ call,
574
+ node: /* @__PURE__ */ jsx4(ContactForm, { call, onSubmit: (values) => respond2(values) })
575
+ });
576
+ } else {
577
+ declined.push(call.id);
578
+ }
579
+ }
580
+ const declinedKey = declined.join(",");
581
+ const { respond } = state;
582
+ useEffect2(() => {
583
+ if (!declinedKey) {
584
+ return;
585
+ }
586
+ for (const id of declinedKey.split(",")) {
587
+ respond(id, null, UNSUPPORTED);
588
+ }
589
+ }, [declinedKey, respond]);
590
+ return drawn;
591
+ }
592
+ function Header({
593
+ onClose,
594
+ onReset,
595
+ title,
596
+ titleId
597
+ }) {
598
+ return /* @__PURE__ */ jsxs2("div", { className: "wakflo-chat__header", children: [
599
+ /* @__PURE__ */ jsx4("span", { "aria-hidden": "true", className: "wakflo-chat__tile", children: /* @__PURE__ */ jsx4(Spark, {}) }),
600
+ /* @__PURE__ */ jsx4("h2", { className: "wakflo-chat__title", id: titleId, children: title }),
601
+ /* @__PURE__ */ jsx4(
602
+ "button",
603
+ {
604
+ "aria-label": "New chat",
605
+ className: "wakflo-chat__icon-btn",
606
+ onClick: onReset,
607
+ title: "New chat",
608
+ type: "button",
609
+ children: /* @__PURE__ */ jsx4(Pencil, {})
610
+ }
611
+ ),
612
+ /* @__PURE__ */ jsx4(
613
+ "button",
614
+ {
615
+ "aria-label": "Close chat",
616
+ className: "wakflo-chat__icon-btn",
617
+ onClick: onClose,
618
+ title: "Close",
619
+ type: "button",
620
+ children: /* @__PURE__ */ jsx4(Close, {})
621
+ }
622
+ )
623
+ ] });
624
+ }
625
+ function Typing({ state }) {
626
+ const streaming = state.messages.some((m) => m.streaming);
627
+ if (state.typing.length === 0 || streaming) {
628
+ return null;
629
+ }
630
+ const names = state.typing.map((a) => a.name).filter(Boolean);
631
+ return /* @__PURE__ */ jsxs2("output", { className: "wakflo-chat__bubble wakflo-chat__typing", children: [
632
+ /* @__PURE__ */ jsx4("span", { className: "wakflo-chat__sr", children: names.length > 0 ? `${names.join(", ")} is typing` : "Typing" }),
633
+ /* @__PURE__ */ jsx4(Dots, {})
634
+ ] });
635
+ }
636
+ function ErrorLine({ state }) {
637
+ if (!state.error || state.messages.some((m) => m.failed)) {
638
+ return null;
639
+ }
640
+ return /* @__PURE__ */ jsx4("p", { className: "wakflo-chat__system wakflo-chat__system--error", children: state.connection === "closed" ? "The chat can't connect right now." : state.error.message || "Something went wrong." });
641
+ }
642
+ function Log({
643
+ available,
644
+ greeting,
645
+ state,
646
+ tools
647
+ }) {
648
+ const ref = useRef2(null);
649
+ const { messages } = state;
650
+ const lastKey = [
651
+ messages.length,
652
+ messages.at(-1)?.content.length ?? 0,
653
+ state.typing.length,
654
+ state.notices.length,
655
+ state.pendingTool?.runId ?? "",
656
+ state.status ?? ""
657
+ ].join(":");
658
+ useEffect2(() => {
659
+ const log = ref.current;
660
+ if (log && lastKey) {
661
+ log.scrollTop = log.scrollHeight;
662
+ }
663
+ }, [lastKey]);
664
+ const retry = (id) => {
665
+ state.chat.retry(id).catch(() => void 0);
666
+ };
667
+ return /* @__PURE__ */ jsxs2("div", { "aria-live": "polite", className: "wakflo-chat__log", ref, role: "log", children: [
668
+ greeting ? /* @__PURE__ */ jsx4("div", { className: "wakflo-chat__bubble", children: /* @__PURE__ */ jsx4(Markdown, { text: greeting }) }) : null,
669
+ messages.map((m) => /* @__PURE__ */ jsx4(MessageView, { message: m, onRetry: retry }, m.id)),
670
+ /* @__PURE__ */ jsx4(
671
+ StatusLines,
672
+ {
673
+ available,
674
+ conversation: state.conversation,
675
+ notices: state.notices,
676
+ setEmail: state.setEmail
677
+ }
678
+ ),
679
+ tools.map((d) => /* @__PURE__ */ jsx4("div", { className: "wakflo-chat__tool", children: d.node }, d.call.id)),
680
+ /* @__PURE__ */ jsx4(Typing, { state }),
681
+ /* @__PURE__ */ jsx4(ErrorLine, { state })
682
+ ] });
683
+ }
684
+ function Composer({
685
+ inputRef,
686
+ onSend,
687
+ placeholder
688
+ }) {
689
+ const inputId = useId2();
690
+ const [draft, setDraft] = useState3("");
691
+ const submit = (e) => {
692
+ e.preventDefault();
693
+ const text = draft.trim();
694
+ if (!text) {
695
+ return;
696
+ }
697
+ setDraft("");
698
+ onSend(text);
699
+ };
700
+ return /* @__PURE__ */ jsxs2("form", { className: "wakflo-chat__composer", onSubmit: submit, children: [
701
+ /* @__PURE__ */ jsx4("label", { className: "wakflo-chat__sr", htmlFor: inputId, children: "Message" }),
702
+ /* @__PURE__ */ jsx4(
703
+ "input",
704
+ {
705
+ autoComplete: "off",
706
+ className: "wakflo-chat__input wakflo-chat__input--composer",
707
+ id: inputId,
708
+ maxLength: MAX_MESSAGE_LENGTH,
709
+ onChange: (e) => setDraft(e.target.value),
710
+ placeholder,
711
+ ref: inputRef,
712
+ value: draft
713
+ }
714
+ ),
715
+ /* @__PURE__ */ jsx4(
716
+ "button",
717
+ {
718
+ "aria-label": "Send",
719
+ className: "wakflo-chat__send",
720
+ disabled: !draft.trim(),
721
+ type: "submit",
722
+ children: /* @__PURE__ */ jsx4(Arrow, {})
723
+ }
724
+ )
725
+ ] });
726
+ }
727
+ function Suggestions({
728
+ onAsk,
729
+ suggestions
730
+ }) {
731
+ if (suggestions.length === 0) {
732
+ return null;
733
+ }
734
+ return /* @__PURE__ */ jsx4("div", { className: "wakflo-chat__chips", children: suggestions.map((q) => /* @__PURE__ */ jsx4(
735
+ "button",
736
+ {
737
+ className: "wakflo-chat__chip",
738
+ onClick: () => onAsk(q),
739
+ type: "button",
740
+ children: q
741
+ },
742
+ q
743
+ )) });
744
+ }
745
+ function useKeyboard(open, setOpen, refs) {
746
+ useEffect2(() => {
747
+ const onKey = (e) => {
748
+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "j") {
749
+ e.preventDefault();
750
+ setOpen((o) => !o);
751
+ return;
752
+ }
753
+ const panel = refs.panel.current;
754
+ if (e.key === "Escape" && panel && panel.contains(document.activeElement)) {
755
+ setOpen(false);
756
+ }
757
+ };
758
+ document.addEventListener("keydown", onKey);
759
+ return () => document.removeEventListener("keydown", onKey);
760
+ }, [setOpen, refs]);
761
+ const wasOpen = useRef2(open);
762
+ useEffect2(() => {
763
+ if (open && !wasOpen.current) {
764
+ refs.input.current?.focus();
765
+ } else if (!open && wasOpen.current) {
766
+ refs.launcher.current?.focus();
767
+ }
768
+ wasOpen.current = open;
769
+ }, [open, refs]);
770
+ }
771
+ function WakfloChat(props) {
772
+ const { position = "bottom-right" } = props;
773
+ const state = useWakfloChat({
774
+ apiUrl: props.apiUrl,
775
+ baseUrl: props.baseUrl,
776
+ publishableKey: props.publishableKey,
777
+ defaultOpen: props.defaultOpen,
778
+ botToken: props.botToken,
779
+ fetch: props.fetch,
780
+ portalToken: props.portalToken,
781
+ storage: props.storage
782
+ });
783
+ const { config, conversation, messages, open, setOpen } = state;
784
+ const title = props.title ?? (config?.title || "Chat");
785
+ const accent = props.accent ?? config?.accent ?? void 0;
786
+ const mac = useIsMac();
787
+ const tools = useTools(state, props.renderTool);
788
+ const panelId = useId2();
789
+ const titleId = useId2();
790
+ const input = useRef2(null);
791
+ const launcher = useRef2(null);
792
+ const panel = useRef2(null);
793
+ const refs = useMemo2(() => ({ input, launcher, panel }), []);
794
+ useKeyboard(open, setOpen, refs);
795
+ const send = (text) => {
796
+ state.send(text);
797
+ };
798
+ const className = props.className ? `wakflo-chat ${props.className}` : "wakflo-chat";
799
+ return /* @__PURE__ */ jsxs2(
800
+ "div",
801
+ {
802
+ className,
803
+ "data-open": open ? "true" : "false",
804
+ "data-position": position,
805
+ "data-theme": themeOf(props.theme, config),
806
+ style: accent ? { "--wakflo-accent": accent } : void 0,
807
+ children: [
808
+ open ? /* @__PURE__ */ jsxs2(
809
+ "section",
810
+ {
811
+ "aria-labelledby": titleId,
812
+ className: "wakflo-chat__panel",
813
+ id: panelId,
814
+ ref: panel,
815
+ children: [
816
+ /* @__PURE__ */ jsx4(
817
+ Header,
818
+ {
819
+ onClose: () => setOpen(false),
820
+ onReset: () => {
821
+ state.reset();
822
+ },
823
+ title,
824
+ titleId
825
+ }
826
+ ),
827
+ /* @__PURE__ */ jsx4(
828
+ Log,
829
+ {
830
+ available: config?.available !== false,
831
+ greeting: props.greeting ?? config?.greeting ?? "",
832
+ state,
833
+ tools
834
+ }
835
+ ),
836
+ messages.length === 0 ? /* @__PURE__ */ jsx4(
837
+ Suggestions,
838
+ {
839
+ onAsk: send,
840
+ suggestions: props.suggestions ?? config?.suggestions ?? []
841
+ }
842
+ ) : null,
843
+ conversation?.status === "bot" && messages.length > 0 ? /* @__PURE__ */ jsx4("div", { className: "wakflo-chat__actions", children: /* @__PURE__ */ jsx4(
844
+ "button",
845
+ {
846
+ className: "wakflo-chat__link",
847
+ onClick: () => {
848
+ state.handover();
849
+ },
850
+ type: "button",
851
+ children: "Talk to a person"
852
+ }
853
+ ) }) : null,
854
+ /* @__PURE__ */ jsx4(
855
+ Composer,
856
+ {
857
+ inputRef: input,
858
+ onSend: send,
859
+ placeholder: props.placeholder ?? placeholderFor(title)
860
+ }
861
+ )
862
+ ]
863
+ }
864
+ ) : null,
865
+ /* @__PURE__ */ jsxs2(
866
+ "button",
867
+ {
868
+ "aria-controls": open ? panelId : void 0,
869
+ "aria-expanded": open,
870
+ className: "wakflo-chat__launcher",
871
+ onClick: () => setOpen((o) => !o),
872
+ ref: launcher,
873
+ type: "button",
874
+ children: [
875
+ /* @__PURE__ */ jsx4("span", { "aria-hidden": "true", className: "wakflo-chat__spark", children: /* @__PURE__ */ jsx4(Spark, {}) }),
876
+ /* @__PURE__ */ jsx4("span", { children: title }),
877
+ /* @__PURE__ */ jsx4("span", { "aria-hidden": "true", className: "wakflo-chat__kbd", children: mac ? "\u2318J" : "Ctrl J" })
878
+ ]
879
+ }
880
+ )
881
+ ]
882
+ }
883
+ );
884
+ }
885
+ export {
886
+ PublicError,
887
+ WakfloChat,
888
+ contactFields,
889
+ useWakfloChat
890
+ };