@convokitapp/chat-embed 0.0.0-stage → 1.0.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/README.md +131 -2
- package/dist/index.d.ts +113 -0
- package/dist/index.js +579 -0
- package/dist/main.js +77 -0
- package/package.json +47 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,579 @@
|
|
|
1
|
+
// src/config.ts
|
|
2
|
+
var DEFAULT_API_URL = "https://api.convokit.app";
|
|
3
|
+
var fail = (message) => {
|
|
4
|
+
throw new TypeError(`ConvoKitWidget: ${message}`);
|
|
5
|
+
};
|
|
6
|
+
var text = (value) => typeof value === "string" ? value.trim() : "";
|
|
7
|
+
var cssSize = (value, fallback) => {
|
|
8
|
+
const size = text(value);
|
|
9
|
+
if (!size) return fallback;
|
|
10
|
+
if (!/^\d+(\.\d+)?(px|vh|vw|%|rem|em)$/.test(size)) fail(`invalid size "${size}"`);
|
|
11
|
+
return size;
|
|
12
|
+
};
|
|
13
|
+
function resolveConfig(input) {
|
|
14
|
+
if (!input || typeof input !== "object") fail("start() needs a configuration object");
|
|
15
|
+
const clientId = text(input.clientId) || fail("clientId is required");
|
|
16
|
+
const mode = input.mode;
|
|
17
|
+
if (mode !== "guest" && mode !== "uid" && mode !== "authToken") fail('mode must be "guest", "uid" or "authToken"');
|
|
18
|
+
if (mode !== "authToken" && !text(input.widgetKey)) fail(`widgetKey is required in ${mode} mode`);
|
|
19
|
+
if (mode === "uid" && !text(input.uid)) fail("uid is required in uid mode");
|
|
20
|
+
if (mode === "authToken") {
|
|
21
|
+
if (!text(input.userId)) fail("userId is required in authToken mode");
|
|
22
|
+
if (!input.tokenProvider && !text(input.tokenUrl)) fail("tokenUrl or tokenProvider is required in authToken mode");
|
|
23
|
+
if (input.widgetKey) fail("do not put a widget key in authToken mode; your server issues the token");
|
|
24
|
+
}
|
|
25
|
+
if (input.startConversationWith !== void 0 && (!Array.isArray(input.startConversationWith) || !input.startConversationWith.every((id) => text(id)))) {
|
|
26
|
+
fail("startConversationWith must be an array of user IDs");
|
|
27
|
+
}
|
|
28
|
+
const primaryColor = text(input.theme?.primaryColor) || "#4f46e5";
|
|
29
|
+
if (!/^#[0-9a-f]{3,8}$/i.test(primaryColor) && !/^(rgb|hsl)a?\([\d\s.,%]+\)$/i.test(primaryColor)) fail("theme.primaryColor must be a hex, rgb() or hsl() color");
|
|
30
|
+
return {
|
|
31
|
+
...input,
|
|
32
|
+
clientId,
|
|
33
|
+
mode,
|
|
34
|
+
widgetKey: text(input.widgetKey) || void 0,
|
|
35
|
+
uid: text(input.uid) || void 0,
|
|
36
|
+
userId: text(input.userId) || void 0,
|
|
37
|
+
startConversationWith: [...new Set((input.startConversationWith ?? []).map((id) => id.trim()))],
|
|
38
|
+
isDocked: input.isDocked ?? true,
|
|
39
|
+
dockedAlignment: input.dockedAlignment === "left" ? "left" : "right",
|
|
40
|
+
width: cssSize(input.width, "380px"),
|
|
41
|
+
height: cssSize(input.height, "560px"),
|
|
42
|
+
title: text(input.title) || "Chat",
|
|
43
|
+
storageMode: input.storageMode === "SESSION" ? "SESSION" : "LOCAL",
|
|
44
|
+
apiUrl: (text(input.apiUrl) || DEFAULT_API_URL).replace(/\/+$/, ""),
|
|
45
|
+
primaryColor
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// src/widget.ts
|
|
50
|
+
import { ConvoKitClient, ConvoKitError, createClientMessageId } from "@convokitapp/sdk";
|
|
51
|
+
|
|
52
|
+
// src/session.ts
|
|
53
|
+
var WidgetSessionError = class extends Error {
|
|
54
|
+
constructor(message, status, code) {
|
|
55
|
+
super(message);
|
|
56
|
+
this.status = status;
|
|
57
|
+
this.code = code;
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
function storage(mode) {
|
|
61
|
+
try {
|
|
62
|
+
return mode === "SESSION" ? window.sessionStorage : window.localStorage;
|
|
63
|
+
} catch {
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
var resumeKey = (clientId) => `convokit-widget:${clientId}:guest`;
|
|
68
|
+
function readResume(config) {
|
|
69
|
+
try {
|
|
70
|
+
return storage(config.storageMode)?.getItem(resumeKey(config.clientId)) ?? null;
|
|
71
|
+
} catch {
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
function writeResume(config, token) {
|
|
76
|
+
try {
|
|
77
|
+
storage(config.storageMode)?.setItem(resumeKey(config.clientId), token);
|
|
78
|
+
} catch {
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
async function requestWidgetSession(config, body, fetchImpl) {
|
|
82
|
+
const response = await fetchImpl(`${config.apiUrl}/api/v1/widget/session`, {
|
|
83
|
+
method: "POST",
|
|
84
|
+
headers: { "Content-Type": "application/json", "x-client-id": config.clientId, "x-widget-key": config.widgetKey },
|
|
85
|
+
body: JSON.stringify(body)
|
|
86
|
+
});
|
|
87
|
+
const payload = await response.json().catch(() => null);
|
|
88
|
+
if (!response.ok || !payload?.data?.token || !payload.data.appUserId) {
|
|
89
|
+
throw new WidgetSessionError(payload?.error ?? "Could not start the chat session", response.status, payload?.code);
|
|
90
|
+
}
|
|
91
|
+
return payload.data;
|
|
92
|
+
}
|
|
93
|
+
function profile(config) {
|
|
94
|
+
const result = {};
|
|
95
|
+
if (config.user?.name) result.name = config.user.name;
|
|
96
|
+
if (config.user?.imageUrl) result.imageUrl = config.user.imageUrl;
|
|
97
|
+
return result;
|
|
98
|
+
}
|
|
99
|
+
function cachedFirst(first, renew) {
|
|
100
|
+
let cached = first.token;
|
|
101
|
+
return {
|
|
102
|
+
appUserId: first.appUserId,
|
|
103
|
+
tokenProvider: async (appUserId) => {
|
|
104
|
+
if (cached) {
|
|
105
|
+
const token = cached;
|
|
106
|
+
cached = null;
|
|
107
|
+
return token;
|
|
108
|
+
}
|
|
109
|
+
const next = await renew();
|
|
110
|
+
if (next.appUserId !== appUserId) throw new WidgetSessionError("The chat session belongs to a different user", 401);
|
|
111
|
+
return next.token;
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
async function openWidgetSession(config, fetchImpl = fetch) {
|
|
116
|
+
if (config.mode === "guest") {
|
|
117
|
+
const request = () => requestWidgetSession(config, { mode: "guest", resumeToken: readResume(config), ...profile(config) }, fetchImpl).then((result) => {
|
|
118
|
+
if (result.resumeToken) writeResume(config, result.resumeToken);
|
|
119
|
+
return result;
|
|
120
|
+
});
|
|
121
|
+
return cachedFirst(await request(), request);
|
|
122
|
+
}
|
|
123
|
+
if (config.mode === "uid") {
|
|
124
|
+
const request = () => requestWidgetSession(config, { mode: "uid", uid: config.uid, ...profile(config) }, fetchImpl);
|
|
125
|
+
return cachedFirst(await request(), request);
|
|
126
|
+
}
|
|
127
|
+
const tokenProvider = config.tokenProvider ?? (async (appUserId) => {
|
|
128
|
+
const response = await fetchImpl(config.tokenUrl, {
|
|
129
|
+
method: "POST",
|
|
130
|
+
credentials: "include",
|
|
131
|
+
headers: { "Content-Type": "application/json" },
|
|
132
|
+
body: JSON.stringify({ appUserId })
|
|
133
|
+
});
|
|
134
|
+
const payload = await response.json().catch(() => null);
|
|
135
|
+
const token = payload?.token ?? payload?.data?.token;
|
|
136
|
+
if (!response.ok || !token) throw new WidgetSessionError("Your token endpoint did not return a token", response.status);
|
|
137
|
+
return token;
|
|
138
|
+
});
|
|
139
|
+
return { appUserId: config.userId, tokenProvider };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// src/styles.ts
|
|
143
|
+
var styles = (primary, width, height, align) => `
|
|
144
|
+
:host { all: initial; --ck-primary: ${primary}; --ck-bg: #ffffff; --ck-fg: #111827; --ck-muted: #6b7280; --ck-border: #e5e7eb; --ck-bubble: #f3f4f6; --ck-danger: #b91c1c;
|
|
145
|
+
font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; font-size: 14px; line-height: 1.4; color: var(--ck-fg); }
|
|
146
|
+
@media (prefers-color-scheme: dark) {
|
|
147
|
+
:host { --ck-bg: #111827; --ck-fg: #f9fafb; --ck-muted: #9ca3af; --ck-border: #374151; --ck-bubble: #1f2937; --ck-danger: #f87171; }
|
|
148
|
+
}
|
|
149
|
+
*, *::before, *::after { box-sizing: border-box; }
|
|
150
|
+
[hidden] { display: none !important; }
|
|
151
|
+
button { font: inherit; color: inherit; cursor: pointer; }
|
|
152
|
+
button:focus-visible, textarea:focus-visible { outline: 2px solid var(--ck-primary); outline-offset: 2px; }
|
|
153
|
+
.docked { position: fixed; bottom: 20px; ${align}: 20px; z-index: 2147483000; display: flex; flex-direction: column; align-items: ${align === "left" ? "flex-start" : "flex-end"}; gap: 12px; }
|
|
154
|
+
.launcher { position: relative; width: 56px; height: 56px; border-radius: 50%; border: 0; background: var(--ck-primary); color: #fff; box-shadow: 0 6px 20px rgb(0 0 0 / .2); display: grid; place-items: center; }
|
|
155
|
+
.launcher svg { width: 26px; height: 26px; }
|
|
156
|
+
.badge { position: absolute; top: -2px; ${align === "left" ? "left" : "right"}: -2px; min-width: 20px; height: 20px; padding: 0 6px; border-radius: 10px; background: #dc2626; color: #fff; font-size: 12px; font-weight: 600; display: grid; place-items: center; }
|
|
157
|
+
.panel { width: ${width}; height: ${height}; max-width: calc(100vw - 32px); max-height: calc(100vh - 110px); background: var(--ck-bg); border: 1px solid var(--ck-border); border-radius: 14px; box-shadow: 0 12px 40px rgb(0 0 0 / .18); display: flex; flex-direction: column; overflow: hidden; }
|
|
158
|
+
.inline .panel { max-height: none; max-width: 100%; box-shadow: none; }
|
|
159
|
+
header { display: flex; align-items: center; gap: 8px; padding: 12px 14px; background: var(--ck-primary); color: #fff; }
|
|
160
|
+
header h2 { flex: 1; margin: 0; font-size: 15px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
|
161
|
+
.icon { border: 0; background: transparent; color: inherit; padding: 4px; border-radius: 6px; display: grid; place-items: center; }
|
|
162
|
+
.icon svg { width: 18px; height: 18px; }
|
|
163
|
+
.body { flex: 1; min-height: 0; display: flex; flex-direction: column; }
|
|
164
|
+
.center { flex: 1; display: grid; place-items: center; padding: 24px; text-align: center; color: var(--ck-muted); gap: 12px; align-content: center; }
|
|
165
|
+
.error { color: var(--ck-danger); }
|
|
166
|
+
.primary { border: 0; border-radius: 8px; padding: 8px 14px; background: var(--ck-primary); color: #fff; font-weight: 600; }
|
|
167
|
+
.list { flex: 1; overflow-y: auto; margin: 0; padding: 0; list-style: none; }
|
|
168
|
+
.list button { width: 100%; text-align: left; border: 0; border-bottom: 1px solid var(--ck-border); background: transparent; padding: 12px 14px; display: grid; grid-template-columns: 1fr auto; gap: 2px 8px; }
|
|
169
|
+
.list button:hover { background: var(--ck-bubble); }
|
|
170
|
+
.list .name { font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
171
|
+
.list .preview { grid-column: 1; color: var(--ck-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
172
|
+
.list .dot { grid-row: 1 / span 2; grid-column: 2; align-self: center; min-width: 20px; height: 20px; padding: 0 6px; border-radius: 10px; background: var(--ck-primary); color: #fff; font-size: 12px; display: grid; place-items: center; }
|
|
173
|
+
.messages { flex: 1; overflow-y: auto; padding: 12px; display: flex; flex-direction: column; gap: 6px; }
|
|
174
|
+
.older { align-self: center; border: 1px solid var(--ck-border); background: transparent; border-radius: 999px; padding: 4px 12px; color: var(--ck-muted); font-size: 12px; }
|
|
175
|
+
.msg { max-width: 80%; display: flex; flex-direction: column; gap: 2px; }
|
|
176
|
+
.msg.mine { align-self: flex-end; align-items: flex-end; }
|
|
177
|
+
.msg .who { font-size: 12px; color: var(--ck-muted); }
|
|
178
|
+
.msg .bubble { padding: 8px 12px; border-radius: 14px; background: var(--ck-bubble); white-space: pre-wrap; overflow-wrap: anywhere; }
|
|
179
|
+
.msg.mine .bubble { background: var(--ck-primary); color: #fff; }
|
|
180
|
+
.msg .meta { font-size: 11px; color: var(--ck-muted); }
|
|
181
|
+
.msg.failed .meta { color: var(--ck-danger); }
|
|
182
|
+
.msg .attachment { font-size: 12px; color: var(--ck-muted); }
|
|
183
|
+
.empty { margin: auto; color: var(--ck-muted); }
|
|
184
|
+
form { display: flex; gap: 8px; padding: 10px; border-top: 1px solid var(--ck-border); align-items: flex-end; }
|
|
185
|
+
textarea { flex: 1; resize: none; max-height: 120px; min-height: 38px; border: 1px solid var(--ck-border); border-radius: 10px; padding: 8px 10px; font: inherit; color: var(--ck-fg); background: var(--ck-bg); }
|
|
186
|
+
form .primary { height: 38px; }
|
|
187
|
+
form .primary:disabled { opacity: .5; cursor: default; }
|
|
188
|
+
@media (max-width: 480px) {
|
|
189
|
+
.docked .panel { position: fixed; inset: 0; width: 100vw; height: 100dvh; max-width: none; max-height: none; border-radius: 0; }
|
|
190
|
+
}
|
|
191
|
+
`;
|
|
192
|
+
|
|
193
|
+
// src/widget.ts
|
|
194
|
+
var ICONS = {
|
|
195
|
+
chat: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>',
|
|
196
|
+
close: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M18 6 6 18M6 6l12 12"/></svg>',
|
|
197
|
+
back: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="m15 18-6-6 6-6"/></svg>'
|
|
198
|
+
};
|
|
199
|
+
var FRIENDLY = {
|
|
200
|
+
WIDGET_USER_LIMIT_REACHED: "Chat is busy right now. Please try again later.",
|
|
201
|
+
RATE_LIMITED: "Too many attempts. Please wait a few minutes and try again.",
|
|
202
|
+
ORIGIN_NOT_ALLOWED: "Chat is not enabled for this website.",
|
|
203
|
+
WIDGET_DISABLED: "Chat is currently unavailable.",
|
|
204
|
+
WIDGET_MODE_DISABLED: "Chat is currently unavailable.",
|
|
205
|
+
SUBSCRIPTION_REQUIRED: "Chat is currently unavailable."
|
|
206
|
+
};
|
|
207
|
+
function friendly(error) {
|
|
208
|
+
const code = error instanceof WidgetSessionError || error instanceof ConvoKitError ? error.code : void 0;
|
|
209
|
+
if (code && FRIENDLY[code]) return FRIENDLY[code];
|
|
210
|
+
return "Could not connect to chat. Check your connection and try again.";
|
|
211
|
+
}
|
|
212
|
+
function el(tag, props = {}, ...children) {
|
|
213
|
+
const node = Object.assign(document.createElement(tag), props);
|
|
214
|
+
node.append(...children);
|
|
215
|
+
return node;
|
|
216
|
+
}
|
|
217
|
+
function iconButton(icon, label, onClick) {
|
|
218
|
+
const button = el("button", { type: "button", className: "icon", onclick: onClick });
|
|
219
|
+
button.setAttribute("aria-label", label);
|
|
220
|
+
button.innerHTML = ICONS[icon];
|
|
221
|
+
return button;
|
|
222
|
+
}
|
|
223
|
+
var ChatWidget = class {
|
|
224
|
+
constructor(config, deps = {}) {
|
|
225
|
+
this.config = config;
|
|
226
|
+
this.deps = deps;
|
|
227
|
+
this.launcher = null;
|
|
228
|
+
this.badge = null;
|
|
229
|
+
this.client = null;
|
|
230
|
+
this.session = null;
|
|
231
|
+
this.connecting = null;
|
|
232
|
+
this.inbox = [];
|
|
233
|
+
this.inboxSubscriptions = [];
|
|
234
|
+
this.threadSubscriptions = [];
|
|
235
|
+
this.thread = null;
|
|
236
|
+
this.inboxRefresh = null;
|
|
237
|
+
this.unsubscribeSession = null;
|
|
238
|
+
this.destroyed = false;
|
|
239
|
+
let target = config.mount ? document.querySelector(config.mount) : null;
|
|
240
|
+
if (!target) {
|
|
241
|
+
target = document.createElement("div");
|
|
242
|
+
if (config.mount?.startsWith("#")) target.id = config.mount.slice(1);
|
|
243
|
+
document.body.append(target);
|
|
244
|
+
}
|
|
245
|
+
this.host = target;
|
|
246
|
+
this.root = target.shadowRoot ?? target.attachShadow({ mode: "open" });
|
|
247
|
+
this.root.replaceChildren(el("style", { textContent: styles(config.primaryColor, config.width, config.height, config.dockedAlignment) }));
|
|
248
|
+
this.heading = el("h2", { textContent: config.title });
|
|
249
|
+
this.backSlot = el("span");
|
|
250
|
+
this.headerActions = el("span");
|
|
251
|
+
this.body = el("div", { className: "body" });
|
|
252
|
+
this.panel = el("section", { className: "panel" }, el("header", {}, this.backSlot, this.heading, this.headerActions), this.body);
|
|
253
|
+
this.panel.setAttribute("aria-label", config.title);
|
|
254
|
+
this.isOpen = !config.isDocked;
|
|
255
|
+
if (config.isDocked) {
|
|
256
|
+
this.badge = el("span", { className: "badge", hidden: true });
|
|
257
|
+
this.launcher = el("button", { type: "button", className: "launcher", onclick: () => this.toggle() });
|
|
258
|
+
this.launcher.innerHTML = ICONS.chat;
|
|
259
|
+
this.launcher.append(this.badge);
|
|
260
|
+
this.headerActions.append(iconButton("close", "Close chat", () => this.close()));
|
|
261
|
+
this.panel.hidden = true;
|
|
262
|
+
this.root.append(el("div", { className: "docked" }, this.panel, this.launcher));
|
|
263
|
+
this.updateLauncher();
|
|
264
|
+
} else {
|
|
265
|
+
this.root.append(el("div", { className: "inline" }, this.panel));
|
|
266
|
+
void this.connect();
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
open() {
|
|
270
|
+
if (this.destroyed) return;
|
|
271
|
+
this.isOpen = true;
|
|
272
|
+
this.panel.hidden = false;
|
|
273
|
+
this.updateLauncher();
|
|
274
|
+
void this.connect().then(() => this.markThreadRead());
|
|
275
|
+
}
|
|
276
|
+
close() {
|
|
277
|
+
if (!this.config.isDocked) return;
|
|
278
|
+
this.isOpen = false;
|
|
279
|
+
this.panel.hidden = true;
|
|
280
|
+
this.updateLauncher();
|
|
281
|
+
this.launcher?.focus();
|
|
282
|
+
}
|
|
283
|
+
toggle() {
|
|
284
|
+
if (this.isOpen) this.close();
|
|
285
|
+
else this.open();
|
|
286
|
+
}
|
|
287
|
+
async destroy() {
|
|
288
|
+
this.destroyed = true;
|
|
289
|
+
if (this.inboxRefresh) clearTimeout(this.inboxRefresh);
|
|
290
|
+
this.unsubscribeSession?.();
|
|
291
|
+
await this.leaveThread();
|
|
292
|
+
await Promise.allSettled(this.inboxSubscriptions.map((subscription) => subscription.unsubscribe()));
|
|
293
|
+
await this.client?.disconnectUser().catch(() => void 0);
|
|
294
|
+
this.root.replaceChildren();
|
|
295
|
+
}
|
|
296
|
+
/** The underlying SDK client, once connected, for advanced integrations. */
|
|
297
|
+
get chatClient() {
|
|
298
|
+
return this.client;
|
|
299
|
+
}
|
|
300
|
+
// ---------------------------------------------------------------- session
|
|
301
|
+
connect() {
|
|
302
|
+
if (this.client && this.session) return Promise.resolve();
|
|
303
|
+
this.connecting ?? (this.connecting = this.doConnect().finally(() => {
|
|
304
|
+
this.connecting = null;
|
|
305
|
+
}));
|
|
306
|
+
return this.connecting;
|
|
307
|
+
}
|
|
308
|
+
async doConnect() {
|
|
309
|
+
this.showCenter("Connecting\u2026");
|
|
310
|
+
try {
|
|
311
|
+
const session = await openWidgetSession(this.config, this.deps.fetch);
|
|
312
|
+
const options = { clientId: this.config.clientId, tokenProvider: session.tokenProvider, backendUrl: this.config.apiUrl };
|
|
313
|
+
const client = this.deps.createClient ? this.deps.createClient(options) : new ConvoKitClient(options);
|
|
314
|
+
await client.connectUser(session.appUserId);
|
|
315
|
+
if (this.destroyed) {
|
|
316
|
+
await client.disconnectUser();
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
319
|
+
this.client = client;
|
|
320
|
+
this.session = session;
|
|
321
|
+
this.unsubscribeSession = client.subscribeSession(() => {
|
|
322
|
+
const state = client.sessionState;
|
|
323
|
+
if (state.status === "disconnected" && state.requiresReauthentication) void this.reset("Your chat session ended.");
|
|
324
|
+
});
|
|
325
|
+
this.watchInbox();
|
|
326
|
+
if (this.config.startConversationWith.length) await this.openConversation(await this.findOrCreateConversation());
|
|
327
|
+
else await this.showInbox();
|
|
328
|
+
} catch (error) {
|
|
329
|
+
console.error("[ConvoKitWidget] could not start chat:", error);
|
|
330
|
+
this.client = null;
|
|
331
|
+
this.session = null;
|
|
332
|
+
this.showCenter(friendly(error), true);
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
async reset(message) {
|
|
336
|
+
await this.leaveThread();
|
|
337
|
+
await Promise.allSettled(this.inboxSubscriptions.map((subscription) => subscription.unsubscribe()));
|
|
338
|
+
this.inboxSubscriptions = [];
|
|
339
|
+
this.unsubscribeSession?.();
|
|
340
|
+
this.unsubscribeSession = null;
|
|
341
|
+
this.client = null;
|
|
342
|
+
this.session = null;
|
|
343
|
+
this.showCenter(message, true);
|
|
344
|
+
}
|
|
345
|
+
get me() {
|
|
346
|
+
return this.session.appUserId;
|
|
347
|
+
}
|
|
348
|
+
// ---------------------------------------------------------------- inbox
|
|
349
|
+
watchInbox() {
|
|
350
|
+
const realtime = this.client.realtime;
|
|
351
|
+
const schedule = () => {
|
|
352
|
+
if (this.inboxRefresh) clearTimeout(this.inboxRefresh);
|
|
353
|
+
this.inboxRefresh = setTimeout(() => {
|
|
354
|
+
void this.loadInbox();
|
|
355
|
+
}, 300);
|
|
356
|
+
};
|
|
357
|
+
this.inboxSubscriptions = [
|
|
358
|
+
realtime.onInboxActivity(this.client.clientId, schedule),
|
|
359
|
+
realtime.onInboxChanged(this.client.clientId, schedule)
|
|
360
|
+
];
|
|
361
|
+
}
|
|
362
|
+
async loadInbox() {
|
|
363
|
+
if (!this.client) return;
|
|
364
|
+
try {
|
|
365
|
+
this.inbox = (await this.client.listInbox({ limit: 50 })).entries;
|
|
366
|
+
this.updateLauncher();
|
|
367
|
+
if (!this.thread) this.renderInbox();
|
|
368
|
+
} catch {
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
async findOrCreateConversation() {
|
|
372
|
+
const wanted = /* @__PURE__ */ new Set([this.me, ...this.config.startConversationWith]);
|
|
373
|
+
const page = await this.client.listInbox({ limit: 100 });
|
|
374
|
+
this.inbox = page.entries;
|
|
375
|
+
const existing = page.entries.find((entry) => {
|
|
376
|
+
const ids = new Set(entry.conversation.participants.map((participant) => participant.appUserId));
|
|
377
|
+
return ids.size === wanted.size && [...wanted].every((id) => ids.has(id));
|
|
378
|
+
});
|
|
379
|
+
if (existing) return existing.conversation;
|
|
380
|
+
return this.client.createConversation({
|
|
381
|
+
participants: this.config.startConversationWith,
|
|
382
|
+
...this.config.conversationTitle ? { title: this.config.conversationTitle } : {}
|
|
383
|
+
});
|
|
384
|
+
}
|
|
385
|
+
async showInbox() {
|
|
386
|
+
await this.leaveThread();
|
|
387
|
+
this.heading.textContent = this.config.title;
|
|
388
|
+
this.backSlot.replaceChildren();
|
|
389
|
+
this.showCenter("Loading\u2026");
|
|
390
|
+
await this.loadInbox();
|
|
391
|
+
this.renderInbox();
|
|
392
|
+
}
|
|
393
|
+
renderInbox() {
|
|
394
|
+
if (!this.client || this.thread) return;
|
|
395
|
+
if (this.inbox.length === 0) {
|
|
396
|
+
const children = [el("p", { textContent: "No conversations yet." })];
|
|
397
|
+
if (this.config.startConversationWith.length) {
|
|
398
|
+
children.push(el("button", { type: "button", className: "primary", textContent: "Start a conversation", onclick: () => void this.findOrCreateConversation().then((conversation) => this.openConversation(conversation)) }));
|
|
399
|
+
}
|
|
400
|
+
this.body.replaceChildren(el("div", { className: "center" }, ...children));
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
const list = el("ul", { className: "list" });
|
|
404
|
+
for (const entry of this.inbox) {
|
|
405
|
+
const preview = entry.latestMessage ? entry.latestMessage.text ?? "Attachment" : "No messages yet";
|
|
406
|
+
const button = el(
|
|
407
|
+
"button",
|
|
408
|
+
{ type: "button", onclick: () => void this.openConversation(entry.conversation) },
|
|
409
|
+
el("span", { className: "name", textContent: entry.conversation.displayTitle }),
|
|
410
|
+
el("span", { className: "preview", textContent: preview })
|
|
411
|
+
);
|
|
412
|
+
if (entry.isUnread) button.append(el("span", { className: "dot", textContent: entry.unreadCount ? String(entry.unreadCount) : "" }));
|
|
413
|
+
list.append(el("li", {}, button));
|
|
414
|
+
}
|
|
415
|
+
this.body.replaceChildren(list);
|
|
416
|
+
}
|
|
417
|
+
updateLauncher() {
|
|
418
|
+
if (!this.launcher || !this.badge) return;
|
|
419
|
+
const unread = this.inbox.reduce((sum, entry) => sum + (entry.isUnread ? Math.max(1, entry.unreadCount) : 0), 0);
|
|
420
|
+
this.badge.textContent = unread > 99 ? "99+" : String(unread);
|
|
421
|
+
this.badge.hidden = unread === 0 || this.isOpen;
|
|
422
|
+
this.launcher.setAttribute("aria-label", this.isOpen ? "Close chat" : unread ? `Open chat, ${unread} unread` : "Open chat");
|
|
423
|
+
this.launcher.setAttribute("aria-expanded", String(this.isOpen));
|
|
424
|
+
}
|
|
425
|
+
// ---------------------------------------------------------------- thread
|
|
426
|
+
async leaveThread() {
|
|
427
|
+
const subscriptions = this.threadSubscriptions;
|
|
428
|
+
this.threadSubscriptions = [];
|
|
429
|
+
this.thread = null;
|
|
430
|
+
await Promise.allSettled(subscriptions.map((subscription) => subscription.unsubscribe()));
|
|
431
|
+
}
|
|
432
|
+
async openConversation(conversation) {
|
|
433
|
+
await this.leaveThread();
|
|
434
|
+
const client = this.client;
|
|
435
|
+
const list = el("div", { className: "messages" });
|
|
436
|
+
list.setAttribute("role", "log");
|
|
437
|
+
list.setAttribute("aria-live", "polite");
|
|
438
|
+
const names = new Map(conversation.participants.map((participant) => [participant.appUserId, participant.name]));
|
|
439
|
+
const thread = { conversation, messages: /* @__PURE__ */ new Map(), pending: [], nextCursor: null, list, names };
|
|
440
|
+
this.thread = thread;
|
|
441
|
+
this.heading.textContent = conversation.displayTitle || this.config.title;
|
|
442
|
+
this.backSlot.replaceChildren(iconButton("back", "All conversations", () => void this.showInbox()));
|
|
443
|
+
this.body.replaceChildren(list, this.composer());
|
|
444
|
+
const realtime = client.realtime;
|
|
445
|
+
this.threadSubscriptions = [
|
|
446
|
+
realtime.onMessage(conversation.id, (event) => {
|
|
447
|
+
if (this.thread !== thread) return;
|
|
448
|
+
thread.pending = thread.pending.filter((item) => item.clientMessageId !== event.message.clientMessageId);
|
|
449
|
+
thread.messages.set(event.message.id, event.message);
|
|
450
|
+
this.renderMessages(true);
|
|
451
|
+
this.markThreadRead();
|
|
452
|
+
}),
|
|
453
|
+
realtime.onMessageDeleted(conversation.id, (event) => {
|
|
454
|
+
if (this.thread !== thread) return;
|
|
455
|
+
thread.messages.delete(event.id);
|
|
456
|
+
this.renderMessages(false);
|
|
457
|
+
})
|
|
458
|
+
];
|
|
459
|
+
await this.loadOlder(thread);
|
|
460
|
+
this.markThreadRead();
|
|
461
|
+
}
|
|
462
|
+
async loadOlder(thread) {
|
|
463
|
+
const page = await this.client.listMessages({ conversationId: thread.conversation.id, limit: 30, cursor: thread.nextCursor });
|
|
464
|
+
if (this.thread !== thread) return;
|
|
465
|
+
for (const message of page.messages) if (!thread.messages.has(message.id)) thread.messages.set(message.id, message);
|
|
466
|
+
thread.nextCursor = page.nextCursor;
|
|
467
|
+
const firstLoad = thread.list.childElementCount === 0;
|
|
468
|
+
const previousHeight = thread.list.scrollHeight;
|
|
469
|
+
this.renderMessages(firstLoad);
|
|
470
|
+
if (!firstLoad) thread.list.scrollTop = thread.list.scrollHeight - previousHeight;
|
|
471
|
+
}
|
|
472
|
+
renderMessages(stickToBottom) {
|
|
473
|
+
const thread = this.thread;
|
|
474
|
+
if (!thread) return;
|
|
475
|
+
const { list } = thread;
|
|
476
|
+
const nearBottom = list.scrollHeight - list.scrollTop - list.clientHeight < 80;
|
|
477
|
+
const ordered = [...thread.messages.values()].sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime() || a.id.localeCompare(b.id));
|
|
478
|
+
const nodes = [];
|
|
479
|
+
if (thread.nextCursor) nodes.push(el("button", { type: "button", className: "older", textContent: "Load earlier messages", onclick: () => void this.loadOlder(thread) }));
|
|
480
|
+
if (ordered.length === 0 && thread.pending.length === 0) nodes.push(el("p", { className: "empty", textContent: "Say hello \u{1F44B}" }));
|
|
481
|
+
let previousSender = null;
|
|
482
|
+
for (const message of ordered) {
|
|
483
|
+
const mine = message.senderId === this.me;
|
|
484
|
+
const item = el("div", { className: mine ? "msg mine" : "msg" });
|
|
485
|
+
if (!mine && message.senderId !== previousSender) item.append(el("span", { className: "who", textContent: thread.names.get(message.senderId) ?? message.senderId }));
|
|
486
|
+
if (message.text) item.append(el("div", { className: "bubble", textContent: message.text }));
|
|
487
|
+
if (message.media.length) item.append(el("span", { className: "attachment", textContent: `\u{1F4CE} ${message.media.length === 1 ? "1 attachment" : `${message.media.length} attachments`}` }));
|
|
488
|
+
const time = message.createdAt.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
|
|
489
|
+
item.append(el("span", { className: "meta", textContent: message.revision > 0 ? `${time} \xB7 edited` : time }));
|
|
490
|
+
nodes.push(item);
|
|
491
|
+
previousSender = message.senderId;
|
|
492
|
+
}
|
|
493
|
+
for (const pending of thread.pending) {
|
|
494
|
+
const item = el("div", { className: pending.failed ? "msg mine failed" : "msg mine" }, el("div", { className: "bubble", textContent: pending.text }));
|
|
495
|
+
item.append(pending.failed ? el("button", { type: "button", className: "older", textContent: "Not sent. Tap to retry", onclick: () => void this.send(pending) }) : el("span", { className: "meta", textContent: "Sending\u2026" }));
|
|
496
|
+
nodes.push(item);
|
|
497
|
+
}
|
|
498
|
+
list.replaceChildren(...nodes);
|
|
499
|
+
if (stickToBottom || nearBottom) list.scrollTop = list.scrollHeight;
|
|
500
|
+
}
|
|
501
|
+
composer() {
|
|
502
|
+
const input = el("textarea", { rows: 1, placeholder: "Write a message\u2026", maxLength: 4e3 });
|
|
503
|
+
input.setAttribute("aria-label", "Message");
|
|
504
|
+
const button = el("button", { type: "submit", className: "primary", textContent: "Send", disabled: true });
|
|
505
|
+
input.oninput = () => {
|
|
506
|
+
button.disabled = !input.value.trim();
|
|
507
|
+
input.style.height = "auto";
|
|
508
|
+
input.style.height = `${Math.min(input.scrollHeight, 120)}px`;
|
|
509
|
+
};
|
|
510
|
+
const form = el("form", {}, input, button);
|
|
511
|
+
const submit = () => {
|
|
512
|
+
const text2 = input.value.trim();
|
|
513
|
+
if (!text2 || !this.thread) return;
|
|
514
|
+
input.value = "";
|
|
515
|
+
input.oninput?.(new Event("input"));
|
|
516
|
+
void this.send({ clientMessageId: createClientMessageId(), text: text2, failed: false });
|
|
517
|
+
};
|
|
518
|
+
form.onsubmit = (event) => {
|
|
519
|
+
event.preventDefault();
|
|
520
|
+
submit();
|
|
521
|
+
};
|
|
522
|
+
input.onkeydown = (event) => {
|
|
523
|
+
if (event.key === "Enter" && !event.shiftKey && !event.isComposing) {
|
|
524
|
+
event.preventDefault();
|
|
525
|
+
submit();
|
|
526
|
+
}
|
|
527
|
+
};
|
|
528
|
+
return form;
|
|
529
|
+
}
|
|
530
|
+
async send(pending) {
|
|
531
|
+
const thread = this.thread;
|
|
532
|
+
if (!thread || !this.client) return;
|
|
533
|
+
pending.failed = false;
|
|
534
|
+
if (!thread.pending.includes(pending)) thread.pending.push(pending);
|
|
535
|
+
this.renderMessages(true);
|
|
536
|
+
try {
|
|
537
|
+
const message = await this.client.sendMessage({ conversationId: thread.conversation.id, text: pending.text, clientMessageId: pending.clientMessageId });
|
|
538
|
+
if (this.thread !== thread) return;
|
|
539
|
+
thread.pending = thread.pending.filter((item) => item !== pending);
|
|
540
|
+
thread.messages.set(message.id, message);
|
|
541
|
+
} catch {
|
|
542
|
+
pending.failed = true;
|
|
543
|
+
}
|
|
544
|
+
this.renderMessages(true);
|
|
545
|
+
}
|
|
546
|
+
markThreadRead() {
|
|
547
|
+
const thread = this.thread;
|
|
548
|
+
if (!thread || !this.client || !this.isOpen) return;
|
|
549
|
+
void this.client.markConversationRead(thread.conversation.id).catch(() => void 0);
|
|
550
|
+
const entry = this.inbox.find((item) => item.conversation.id === thread.conversation.id);
|
|
551
|
+
if (entry) {
|
|
552
|
+
entry.isUnread = false;
|
|
553
|
+
entry.unreadCount = 0;
|
|
554
|
+
this.updateLauncher();
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
// ---------------------------------------------------------------- helpers
|
|
558
|
+
showCenter(message, retry = false) {
|
|
559
|
+
const children = [el("p", { className: retry ? "error" : "", textContent: message })];
|
|
560
|
+
if (retry) children.push(el("button", { type: "button", className: "primary", textContent: "Try again", onclick: () => void this.connect() }));
|
|
561
|
+
const center = el("div", { className: "center" }, ...children);
|
|
562
|
+
center.setAttribute("role", retry ? "alert" : "status");
|
|
563
|
+
this.body.replaceChildren(center);
|
|
564
|
+
}
|
|
565
|
+
};
|
|
566
|
+
|
|
567
|
+
// src/index.ts
|
|
568
|
+
function start(config, deps) {
|
|
569
|
+
if (typeof document === "undefined") throw new TypeError("ConvoKitWidget: start() must run in a browser");
|
|
570
|
+
const resolved = resolveConfig(config);
|
|
571
|
+
const begin = () => new ChatWidget(resolved, deps);
|
|
572
|
+
if (document.body) return begin();
|
|
573
|
+
return new Promise((resolve) => document.addEventListener("DOMContentLoaded", () => resolve(begin()), { once: true }));
|
|
574
|
+
}
|
|
575
|
+
export {
|
|
576
|
+
ChatWidget,
|
|
577
|
+
WidgetSessionError,
|
|
578
|
+
start
|
|
579
|
+
};
|