@kilichat/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,900 @@
1
+ "use client";
2
+
3
+ // src/kili-chat.tsx
4
+ import { useEffect as useEffect3 } from "react";
5
+
6
+ // src/components/widget/chat-widget.tsx
7
+ import { useCallback as useCallback2, useEffect as useEffect2, useRef as useRef2, useState as useState2 } from "react";
8
+
9
+ // src/components/widget/chat-home.tsx
10
+ import { ChevronRight, MessageSquarePlus } from "lucide-react";
11
+
12
+ // src/lib/utils.ts
13
+ import { clsx } from "clsx";
14
+ import { twMerge } from "tailwind-merge";
15
+ function cn(...inputs) {
16
+ return twMerge(clsx(inputs));
17
+ }
18
+ function getInitialsFromFullName(fullname) {
19
+ if (!fullname) return "CS";
20
+ const [fname, lname] = fullname.split(" ");
21
+ const firstInitial = fname?.substring(0, 1) ?? "";
22
+ const lastInitial = lname?.substring(0, 1) ?? "";
23
+ if (firstInitial === "" && lastInitial === "") return "CS";
24
+ return `${firstInitial.toUpperCase()}${lastInitial.toUpperCase()}`;
25
+ }
26
+ function getInitialsFromNames(fname, lname) {
27
+ const firstInitial = fname?.substring(0, 1) ?? "";
28
+ const lastInitial = lname?.substring(0, 1) ?? "";
29
+ if (firstInitial === "" && lastInitial === "") return "CS";
30
+ return `${firstInitial.toUpperCase()}${lastInitial.toUpperCase()}`;
31
+ }
32
+
33
+ // src/components/widget/avatar.tsx
34
+ import { jsx } from "react/jsx-runtime";
35
+ function InitialsAvatar({
36
+ initials,
37
+ size = "md",
38
+ tone = "brand",
39
+ className
40
+ }) {
41
+ return /* @__PURE__ */ jsx(
42
+ "span",
43
+ {
44
+ className: cn(
45
+ "inline-flex shrink-0 items-center justify-center rounded-full font-heading font-semibold tracking-tight",
46
+ size === "sm" && "size-7 text-[11px]",
47
+ size === "md" && "size-9 text-xs",
48
+ size === "lg" && "size-12 text-sm",
49
+ tone === "brand" && "bg-primary/15 text-primary",
50
+ tone === "sage" && "bg-sage/20 text-forest",
51
+ tone === "muted" && "bg-muted text-muted-foreground",
52
+ className
53
+ ),
54
+ children: initials
55
+ }
56
+ );
57
+ }
58
+
59
+ // src/components/ui/button.tsx
60
+ import * as React from "react";
61
+ import { Slot } from "@radix-ui/react-slot";
62
+ import { cva } from "class-variance-authority";
63
+ import { jsx as jsx2 } from "react/jsx-runtime";
64
+ var buttonVariants = cva(
65
+ "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium cursor-pointer transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 disabled:cursor-not-allowed [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
66
+ {
67
+ variants: {
68
+ variant: {
69
+ default: "bg-primary text-primary-foreground shadow hover:bg-primary/90",
70
+ destructive: "bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
71
+ outline: "border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
72
+ secondary: "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
73
+ ghost: "hover:bg-accent hover:text-accent-foreground",
74
+ link: "text-primary underline-offset-4 hover:underline"
75
+ },
76
+ size: {
77
+ default: "h-9 px-4 py-2",
78
+ sm: "h-8 rounded-md px-3 text-xs",
79
+ lg: "h-10 rounded-md px-8",
80
+ icon: "h-9 w-9"
81
+ }
82
+ },
83
+ defaultVariants: {
84
+ variant: "default",
85
+ size: "default"
86
+ }
87
+ }
88
+ );
89
+ var Button = React.forwardRef(
90
+ ({ className, variant, size, asChild = false, ...props }, ref) => {
91
+ const Comp = asChild ? Slot : "button";
92
+ return /* @__PURE__ */ jsx2(Comp, { className: cn(buttonVariants({ variant, size, className })), ref, ...props });
93
+ }
94
+ );
95
+ Button.displayName = "Button";
96
+
97
+ // src/lib/widget-data.ts
98
+ var brand = {
99
+ name: "Kili",
100
+ greeting: "Hi there",
101
+ subline: "Ask us anything, or share your feedback. We usually reply in a few minutes.",
102
+ replyTime: "Typically replies in a few minutes"
103
+ };
104
+ var customer = {
105
+ name: "You",
106
+ initials: "YO"
107
+ };
108
+ var agents = [
109
+ { id: "a-mara", name: "Mara Okafor", initials: "MO", role: "Customer Support" },
110
+ { id: "a-devon", name: "Devon Reyes", initials: "DR", role: "Billing Specialist" },
111
+ { id: "a-bot", name: "Kili Team", initials: "KT", role: "Support Team" }
112
+ ];
113
+ var hoursAgo = (h) => new Date(Date.now() - h * 36e5).toISOString();
114
+ var daysAgo = (d, h = 0) => new Date(Date.now() - d * 864e5 - h * 36e5).toISOString();
115
+ var seedConversations = [
116
+ {
117
+ id: "c-1",
118
+ subject: "Trouble syncing my orders",
119
+ agentId: "a-mara",
120
+ messages: [
121
+ {
122
+ id: "m-1",
123
+ kind: "customer",
124
+ body: "Hey \u2014 my orders stopped syncing this morning. Nothing new has come through since about 8am.",
125
+ at: hoursAgo(5)
126
+ },
127
+ {
128
+ id: "m-2",
129
+ kind: "agent",
130
+ authorId: "a-mara",
131
+ body: "Thanks for flagging that! I can see the sync queue backed up on our side. I've re-queued your account now.",
132
+ at: hoursAgo(4.6)
133
+ },
134
+ {
135
+ id: "m-3",
136
+ kind: "customer",
137
+ body: "Great, I can see a few coming in now. How long until it catches up fully?",
138
+ at: hoursAgo(4.2)
139
+ },
140
+ {
141
+ id: "m-4",
142
+ kind: "agent",
143
+ authorId: "a-mara",
144
+ body: "Should be fully caught up within the hour. I'll keep an eye on it and let you know if anything stalls again.",
145
+ at: hoursAgo(4)
146
+ }
147
+ ]
148
+ },
149
+ {
150
+ id: "c-2",
151
+ subject: "Invoice for August",
152
+ agentId: "a-devon",
153
+ messages: [
154
+ {
155
+ id: "m-5",
156
+ kind: "customer",
157
+ body: "Could you resend the August invoice? I can't find it in my inbox.",
158
+ at: daysAgo(3, 2)
159
+ },
160
+ {
161
+ id: "m-6",
162
+ kind: "agent",
163
+ authorId: "a-devon",
164
+ body: "Just sent it over to the billing email on file. Let me know if it doesn't land in the next few minutes.",
165
+ at: daysAgo(3, 1)
166
+ },
167
+ {
168
+ id: "m-7",
169
+ kind: "customer",
170
+ body: "Got it, thank you!",
171
+ at: daysAgo(3)
172
+ }
173
+ ],
174
+ closed: true
175
+ }
176
+ ];
177
+ var cannedReplies = [
178
+ "Thanks for reaching out! Let me take a look at that for you.",
179
+ "Good question \u2014 I'm checking with the team and will come right back to you.",
180
+ "I've made a note of this on your account. Anything else I can help with?",
181
+ "That should be sorted now. Give it a refresh and let me know how it looks."
182
+ ];
183
+ var replyIndex = 0;
184
+ function nextCannedReply() {
185
+ const reply = cannedReplies[replyIndex % cannedReplies.length];
186
+ replyIndex += 1;
187
+ return reply;
188
+ }
189
+ function agentById(id) {
190
+ return agents.find((a) => a.id === id) ?? agents[2];
191
+ }
192
+
193
+ // src/lib/widget-format.ts
194
+ function clockTime(iso) {
195
+ if (!iso) return (/* @__PURE__ */ new Date()).toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });
196
+ return new Date(iso).toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });
197
+ }
198
+ function dayLabel(iso) {
199
+ if (!iso) return (/* @__PURE__ */ new Date()).toLocaleDateString([], { weekday: "long", month: "short", day: "numeric" });
200
+ const date = new Date(iso);
201
+ const today = /* @__PURE__ */ new Date();
202
+ const yesterday = new Date(Date.now() - 864e5);
203
+ const sameDay = (a, b) => a.toDateString() === b.toDateString();
204
+ if (sameDay(date, today)) return "Today";
205
+ if (sameDay(date, yesterday)) return "Yesterday";
206
+ return date.toLocaleDateString([], { weekday: "long", month: "short", day: "numeric" });
207
+ }
208
+ function relativeTime(iso) {
209
+ const diff = Date.now() - new Date(iso).getTime();
210
+ const minutes = Math.round(diff / 6e4);
211
+ if (minutes < 1) return "just now";
212
+ if (minutes < 60) return `${minutes}m ago`;
213
+ const hours = Math.round(minutes / 60);
214
+ if (hours < 24) return `${hours}h ago`;
215
+ const days = Math.round(hours / 24);
216
+ if (days < 7) return `${days}d ago`;
217
+ return new Date(iso).toLocaleDateString([], { month: "short", day: "numeric" });
218
+ }
219
+
220
+ // src/components/widget/chat-home.tsx
221
+ import { Fragment, jsx as jsx3, jsxs } from "react/jsx-runtime";
222
+ function ChatHome({
223
+ chats,
224
+ onOpen,
225
+ onStartNew
226
+ }) {
227
+ return /* @__PURE__ */ jsxs("div", { className: "flex min-h-0 flex-1 flex-col", children: [
228
+ /* @__PURE__ */ jsx3("header", { className: "bg-brand-gradient px-6 pt-10 pb-12 text-primary-foreground sm:px-10 sm:pt-14", children: /* @__PURE__ */ jsxs("div", { className: "mx-auto w-full max-w-2xl", children: [
229
+ /* @__PURE__ */ jsx3("p", { className: "font-heading text-sm font-semibold tracking-wide opacity-90", children: brand.name }),
230
+ /* @__PURE__ */ jsx3("h1", { className: "mt-4 font-heading text-3xl font-semibold sm:text-4xl", children: brand.greeting }),
231
+ /* @__PURE__ */ jsx3("p", { className: "mt-2 max-w-md text-sm opacity-90 sm:text-base", children: brand.subline })
232
+ ] }) }),
233
+ /* @__PURE__ */ jsx3("div", { className: "min-h-0 flex-1 overflow-y-auto scrollbar-thin px-4 pt-6 pb-10 sm:px-10", children: /* @__PURE__ */ jsxs("div", { className: "mx-auto w-full max-w-2xl space-y-3", children: [
234
+ /* @__PURE__ */ jsxs(
235
+ "button",
236
+ {
237
+ type: "button",
238
+ onClick: onStartNew,
239
+ className: "flex w-full items-center gap-3 rounded-2xl border border-border bg-card p-4 text-left shadow-soft transition-colors hover:bg-accent/40",
240
+ children: [
241
+ /* @__PURE__ */ jsx3("span", { className: "grid size-10 shrink-0 place-items-center rounded-full bg-primary/15 text-primary", children: /* @__PURE__ */ jsx3(MessageSquarePlus, { className: "size-5" }) }),
242
+ /* @__PURE__ */ jsxs("span", { className: "min-w-0 flex-1", children: [
243
+ /* @__PURE__ */ jsx3("span", { className: "block font-heading text-sm font-semibold", children: "Start a conversation" }),
244
+ /* @__PURE__ */ jsx3("span", { className: "block text-xs text-muted-foreground", children: brand.replyTime })
245
+ ] }),
246
+ /* @__PURE__ */ jsx3(ChevronRight, { className: "size-4 shrink-0 text-muted-foreground" })
247
+ ]
248
+ }
249
+ ),
250
+ chats.length > 0 && /* @__PURE__ */ jsxs(Fragment, { children: [
251
+ /* @__PURE__ */ jsx3("p", { className: "px-1 pt-4 text-xs font-medium tracking-wide text-muted-foreground uppercase", children: "Your conversations" }),
252
+ /* @__PURE__ */ jsx3("ul", { className: "space-y-2", children: chats.map((chat) => {
253
+ const last = chat.lastMessagePreview;
254
+ return /* @__PURE__ */ jsx3("li", { children: /* @__PURE__ */ jsxs(
255
+ "button",
256
+ {
257
+ type: "button",
258
+ onClick: () => onOpen(chat),
259
+ className: "flex w-full items-start gap-3 rounded-2xl border border-border bg-card p-4 text-left transition-colors hover:bg-accent/40",
260
+ children: [
261
+ /* @__PURE__ */ jsx3(InitialsAvatar, { initials: getInitialsFromFullName(chat.assignedStaffFullName ?? ""), size: "md", tone: "sage" }),
262
+ /* @__PURE__ */ jsxs("span", { className: "min-w-0 flex-1", children: [
263
+ /* @__PURE__ */ jsxs("span", { className: "flex items-center justify-between gap-2", children: [
264
+ /* @__PURE__ */ jsx3("span", { className: "truncate font-heading text-sm font-semibold", children: chat.title ?? chat.summary ?? chat.lastMessagePreview?.substring(0, 30) ?? "Open conversation" }),
265
+ /* @__PURE__ */ jsx3("span", { className: "shrink-0 text-[11px] text-muted-foreground", children: last ? relativeTime(chat.lastMessageSentAt ?? chat.updatedAt) : "" })
266
+ ] }),
267
+ /* @__PURE__ */ jsx3("span", { className: "mt-0.5 block truncate text-xs text-muted-foreground", children: last ? `${chat.lastMessageSenderAccountType === "staff" ? chat.assignedStaffFullName?.split(" ")[0] ?? "CS" : "You"}: ${last}` : "No messages yet" }),
268
+ chat.closedAt && /* @__PURE__ */ jsx3("span", { className: "mt-2 inline-flex rounded-full bg-muted px-2 py-0.5 text-[11px] text-muted-foreground", children: "Closed" })
269
+ ] })
270
+ ]
271
+ }
272
+ ) }, chat.id);
273
+ }) })
274
+ ] }),
275
+ /* @__PURE__ */ jsx3("div", { className: "pt-6 text-center", children: /* @__PURE__ */ jsx3(Button, { variant: "ghost", size: "sm", className: "text-xs text-muted-foreground", onClick: () => {
276
+ }, children: "Can't find what you need? Message us" }) })
277
+ ] }) })
278
+ ] });
279
+ }
280
+
281
+ // src/components/widget/chat-thread.tsx
282
+ import { useEffect, useRef } from "react";
283
+ import { ArrowLeft, Paperclip, Send, Smile } from "lucide-react";
284
+
285
+ // src/components/ui/textarea.tsx
286
+ import * as React2 from "react";
287
+ import { jsx as jsx4 } from "react/jsx-runtime";
288
+ var Textarea = React2.forwardRef(
289
+ ({ className, ...props }, ref) => {
290
+ return /* @__PURE__ */ jsx4(
291
+ "textarea",
292
+ {
293
+ className: cn(
294
+ "flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
295
+ className
296
+ ),
297
+ ref,
298
+ ...props
299
+ }
300
+ );
301
+ }
302
+ );
303
+ Textarea.displayName = "Textarea";
304
+
305
+ // src/lib/storage-keys.ts
306
+ var LocalStorageKeys = {
307
+ AccessTokenExp: "atexp",
308
+ JwtAccessToken: "at",
309
+ JwtRefreshToken: "rt",
310
+ User: "u"
311
+ };
312
+ var SessionStorageKeys = {
313
+ ActiveChat: "ac"
314
+ };
315
+
316
+ // src/context/state.tsx
317
+ import { createContext, useCallback, useContext, useState } from "react";
318
+ import { jsx as jsx5 } from "react/jsx-runtime";
319
+ var AppStateContext = createContext(null);
320
+ var AppStateProvider = ({ children }) => {
321
+ const [accessToken, setAccessToken] = useState(null);
322
+ const [chats, setChats] = useState([]);
323
+ const [messages, setMessages] = useState([]);
324
+ const [refreshToken, setRefreshToken] = useState(null);
325
+ const [user, setUser] = useState(null);
326
+ const appendMessage = useCallback((msg) => {
327
+ setMessages((prev) => {
328
+ const dedup = prev.filter((p) => String(p.id) !== String(msg.id));
329
+ return [...dedup, msg];
330
+ });
331
+ }, []);
332
+ const updateAccessToken = useCallback((at) => {
333
+ localStorage.setItem(LocalStorageKeys.JwtAccessToken, at);
334
+ setAccessToken(at);
335
+ }, []);
336
+ const updateChat = useCallback((chat) => {
337
+ setChats((prev) => prev.map((p) => String(p.id) === String(chat.id) ? chat : p));
338
+ }, []);
339
+ const updateChats = useCallback((chats2) => {
340
+ setChats(chats2);
341
+ }, []);
342
+ const updateMessages = useCallback((msgs) => {
343
+ setMessages(msgs);
344
+ }, []);
345
+ const updateRefreshToken = useCallback((rt) => {
346
+ localStorage.setItem(LocalStorageKeys.JwtRefreshToken, rt);
347
+ setRefreshToken(rt);
348
+ }, []);
349
+ const updateUser = useCallback((usr) => {
350
+ localStorage.setItem(LocalStorageKeys.User, JSON.stringify(usr));
351
+ setUser(usr);
352
+ }, []);
353
+ const appState = {
354
+ accessToken,
355
+ setAccessToken: updateAccessToken,
356
+ chats,
357
+ setChats: updateChats,
358
+ updateChat,
359
+ messages,
360
+ setMessages: updateMessages,
361
+ appendMessage,
362
+ refreshToken,
363
+ setRefreshToken: updateRefreshToken,
364
+ user,
365
+ setUser: updateUser
366
+ };
367
+ return /* @__PURE__ */ jsx5(AppStateContext.Provider, { value: appState, children });
368
+ };
369
+ var useApp = () => {
370
+ const ctx = useContext(AppStateContext);
371
+ if (!ctx) throw new Error("useApp can only be called from inside AppStateProvider");
372
+ return ctx;
373
+ };
374
+ var state_default = AppStateProvider;
375
+
376
+ // src/lib/http.ts
377
+ import axios from "axios";
378
+
379
+ // src/lib/config.ts
380
+ var currentConfig = null;
381
+ function configureKili(config) {
382
+ currentConfig = config;
383
+ }
384
+ function getKiliConfig() {
385
+ if (!currentConfig) {
386
+ throw new Error(
387
+ "Kili SDK is not configured. Render <KiliChat config={...} /> or call configureKili() first."
388
+ );
389
+ }
390
+ return currentConfig;
391
+ }
392
+ function getSocketBaseUrl() {
393
+ const config = getKiliConfig();
394
+ return config.socketBaseUrl ?? config.apiBaseUrl;
395
+ }
396
+
397
+ // src/lib/http.ts
398
+ var http = axios.create();
399
+ http.interceptors.request.use((req) => {
400
+ const config = getKiliConfig();
401
+ req.baseURL = config.apiBaseUrl;
402
+ req.headers["Api-Key"] = config.apiKey;
403
+ req.headers["Api-Secret"] = config.apiSecret;
404
+ const token = localStorage.getItem(LocalStorageKeys.JwtAccessToken);
405
+ if (token) req.headers["Authorization"] = `Bearer ${token}`;
406
+ return req;
407
+ });
408
+ var http_default = http;
409
+
410
+ // src/services/chat.service.ts
411
+ var chatService = {
412
+ async getAllChats(userId) {
413
+ const res = await http_default.get(`/chats?customerId=${userId}`);
414
+ return res.data.data;
415
+ },
416
+ async getChatMessages(chatId) {
417
+ const res = await http_default.get(`/chats/${chatId}/messages`);
418
+ return res.data.data;
419
+ },
420
+ async startChat() {
421
+ const res = await http_default.post("/chats", { initiationChannel: "web_widget" });
422
+ return res.data.data;
423
+ },
424
+ async sendMessage() {
425
+ },
426
+ async markMessageAsRead() {
427
+ }
428
+ };
429
+ var chat_service_default = chatService;
430
+
431
+ // src/components/widget/chat-thread.tsx
432
+ import { jsx as jsx6, jsxs as jsxs2 } from "react/jsx-runtime";
433
+ function ChatThread({
434
+ chat: conversation,
435
+ draft,
436
+ typing,
437
+ onDraftChange,
438
+ onSend,
439
+ onBack,
440
+ onTextFieldBlur,
441
+ onTextfieldFocus
442
+ }) {
443
+ const bottomRef = useRef(null);
444
+ const { messages, setMessages } = useApp();
445
+ const agentInitials = getInitialsFromFullName(conversation.assignedStaffFullName);
446
+ const customerInitials = getInitialsFromFullName(conversation.customerFullName);
447
+ const loadChatHistory = async () => {
448
+ const messages2 = await chat_service_default.getChatMessages(conversation.id);
449
+ setMessages(messages2.data);
450
+ };
451
+ useEffect(() => {
452
+ bottomRef.current?.scrollIntoView({ behavior: "smooth", block: "end" });
453
+ }, [messages.length, typing]);
454
+ useEffect(() => {
455
+ loadChatHistory();
456
+ }, []);
457
+ return /* @__PURE__ */ jsxs2("div", { className: "flex min-h-0 flex-1 flex-col bg-surface", children: [
458
+ /* @__PURE__ */ jsx6("header", { className: "border-b border-border bg-card px-4 py-3 sm:px-6", children: /* @__PURE__ */ jsxs2("div", { className: "mx-auto flex w-full max-w-2xl items-center gap-3", children: [
459
+ /* @__PURE__ */ jsx6(Button, { variant: "ghost", size: "icon", className: "size-8 shrink-0", onClick: onBack, "aria-label": "Back", children: /* @__PURE__ */ jsx6(ArrowLeft, { className: "size-4" }) }),
460
+ /* @__PURE__ */ jsx6(InitialsAvatar, { initials: agentInitials, size: "md", tone: "sage" }),
461
+ /* @__PURE__ */ jsxs2("div", { className: "min-w-0 flex-1", children: [
462
+ /* @__PURE__ */ jsx6("p", { className: "truncate font-heading text-sm font-semibold", children: conversation.assignedStaffFullName }),
463
+ /* @__PURE__ */ jsx6("p", { className: "truncate text-xs text-muted-foreground", children: typing ? `${conversation.assignedStaffFullName?.split(" ")[0]} is typing\u2026` : brand.replyTime })
464
+ ] })
465
+ ] }) }),
466
+ /* @__PURE__ */ jsx6("div", { className: "min-h-0 flex-1 overflow-y-auto scrollbar-thin px-4 py-6 sm:px-6", children: /* @__PURE__ */ jsxs2("div", { className: "mx-auto w-full max-w-2xl space-y-4", children: [
467
+ !!messages.length && /* @__PURE__ */ jsxs2("div", { className: "rounded-2xl border border-dashed border-border bg-card/60 p-6 text-center", children: [
468
+ /* @__PURE__ */ jsx6(InitialsAvatar, { initials: getInitialsFromFullName(conversation.assignedStaffFullName), size: "lg", tone: "sage", className: "mx-auto" }),
469
+ /* @__PURE__ */ jsxs2("p", { className: "mt-3 font-heading text-sm font-semibold", children: [
470
+ "Say hello to ",
471
+ conversation.assignedStaffFullName?.split(" ")[0]
472
+ ] }),
473
+ /* @__PURE__ */ jsx6("p", { className: "mt-1 text-xs text-muted-foreground", children: "Describe what you need help with and we'll take it from there." })
474
+ ] }),
475
+ messages.map((m, i) => {
476
+ const prev = messages[i - 1];
477
+ const showDay = !prev || dayLabel(prev.sentAt) !== dayLabel(m.sentAt);
478
+ return /* @__PURE__ */ jsxs2("div", { className: "space-y-4", children: [
479
+ showDay && /* @__PURE__ */ jsxs2("div", { className: "flex items-center gap-3", children: [
480
+ /* @__PURE__ */ jsx6("span", { className: "h-px flex-1 bg-border" }),
481
+ /* @__PURE__ */ jsx6("span", { className: "text-[11px] text-muted-foreground", children: dayLabel(m.sentAt) }),
482
+ /* @__PURE__ */ jsx6("span", { className: "h-px flex-1 bg-border" })
483
+ ] }),
484
+ m.senderAccountType === "staff" ? /* @__PURE__ */ jsxs2("div", { className: "flex max-w-[80%] items-end gap-2", children: [
485
+ /* @__PURE__ */ jsx6(InitialsAvatar, { initials: getInitialsFromNames(m.senderFirstName, m.senderLastName), size: "sm", tone: "sage" }),
486
+ /* @__PURE__ */ jsxs2("div", { className: "rounded-2xl rounded-bl-sm border border-border bg-card px-4 py-2.5", children: [
487
+ /* @__PURE__ */ jsx6("p", { className: "text-sm whitespace-pre-wrap", children: m.content }),
488
+ /* @__PURE__ */ jsxs2("p", { className: "mt-1 text-[11px] text-muted-foreground", children: [
489
+ m.senderFirstName,
490
+ " \xB7 ",
491
+ clockTime(m.sentAt)
492
+ ] })
493
+ ] })
494
+ ] }) : /* @__PURE__ */ jsxs2("div", { className: "ml-auto flex max-w-[80%] flex-row-reverse items-end gap-2", children: [
495
+ /* @__PURE__ */ jsx6(InitialsAvatar, { initials: customerInitials, size: "sm", tone: "muted" }),
496
+ /* @__PURE__ */ jsxs2("div", { className: "rounded-2xl rounded-br-sm bg-primary px-4 py-2.5 text-primary-foreground", children: [
497
+ /* @__PURE__ */ jsx6("p", { className: "text-sm whitespace-pre-wrap", children: m.content }),
498
+ /* @__PURE__ */ jsxs2("p", { className: "mt-1 text-[11px] opacity-80", children: [
499
+ clockTime(m.sentAt),
500
+ " \xB7 Sent"
501
+ ] })
502
+ ] })
503
+ ] })
504
+ ] }, crypto.randomUUID());
505
+ }),
506
+ typing && /* @__PURE__ */ jsxs2("div", { className: "flex max-w-[80%] items-end gap-2", children: [
507
+ /* @__PURE__ */ jsx6(InitialsAvatar, { initials: agentInitials, size: "sm", tone: "sage" }),
508
+ /* @__PURE__ */ jsxs2("div", { className: "flex items-center gap-1 rounded-2xl rounded-bl-sm border border-border bg-card px-4 py-3", children: [
509
+ /* @__PURE__ */ jsx6(Dot, { delay: "0ms" }),
510
+ /* @__PURE__ */ jsx6(Dot, { delay: "150ms" }),
511
+ /* @__PURE__ */ jsx6(Dot, { delay: "300ms" })
512
+ ] })
513
+ ] }),
514
+ /* @__PURE__ */ jsx6("div", { ref: bottomRef })
515
+ ] }) }),
516
+ /* @__PURE__ */ jsx6("div", { className: "border-t border-border bg-card px-4 py-3 sm:px-6", children: /* @__PURE__ */ jsxs2("div", { className: "mx-auto w-full max-w-2xl", children: [
517
+ /* @__PURE__ */ jsxs2("div", { className: "flex items-end gap-2", children: [
518
+ /* @__PURE__ */ jsx6(
519
+ Textarea,
520
+ {
521
+ value: draft,
522
+ onChange: (e) => onDraftChange(e.target.value),
523
+ onKeyDown: (e) => {
524
+ if (e.key === "Enter" && !e.shiftKey) {
525
+ e.preventDefault();
526
+ onSend();
527
+ }
528
+ },
529
+ onFocus: onTextfieldFocus,
530
+ onBlur: onTextFieldBlur,
531
+ placeholder: "Write a message\u2026",
532
+ "aria-label": "Write a message",
533
+ className: "max-h-40 min-h-[44px] flex-1 resize-none bg-background text-sm"
534
+ }
535
+ ),
536
+ /* @__PURE__ */ jsx6(Button, { size: "icon", className: "size-10 shrink-0", onClick: onSend, disabled: !draft.trim(), "aria-label": "Send", children: /* @__PURE__ */ jsx6(Send, { className: "size-4" }) })
537
+ ] }),
538
+ /* @__PURE__ */ jsxs2("div", { className: "mt-2 flex items-center gap-2 text-muted-foreground", children: [
539
+ /* @__PURE__ */ jsx6(Paperclip, { className: "size-4", "aria-hidden": true }),
540
+ /* @__PURE__ */ jsx6(Smile, { className: "size-4", "aria-hidden": true }),
541
+ /* @__PURE__ */ jsx6("span", { className: "ml-auto text-[11px]", children: "Enter to send \xB7 Shift + Enter for a new line" })
542
+ ] })
543
+ ] }) })
544
+ ] });
545
+ }
546
+ function Dot({ delay }) {
547
+ return /* @__PURE__ */ jsx6(
548
+ "span",
549
+ {
550
+ className: "size-1.5 animate-bounce rounded-full bg-muted-foreground/60",
551
+ style: { animationDelay: delay }
552
+ }
553
+ );
554
+ }
555
+
556
+ // src/lib/socket-events.ts
557
+ var SocketEvent = Object.freeze({
558
+ Connection: "connection",
559
+ Disconnect: "disconnect",
560
+ Error: "error",
561
+ AssignChat: "assign_chat",
562
+ ChatAction: "chat_action",
563
+ ChatAssigned: "chat_assigned",
564
+ ChatDeassigned: "chat_deassigned",
565
+ ChatStarted: "chat_started",
566
+ ChatUpdated: "chat_updated",
567
+ ChatWindowClosed: "chat_window_closed",
568
+ ChatWindowOpened: "chat_window_opened",
569
+ CloseChat: "close_chat",
570
+ InternalNote: "internal_note",
571
+ JoinAllUnclosedChatRooms: "join_all_unclosed_chat_rooms",
572
+ JoinChatRoom: "join_chat_room",
573
+ JoinedChatRoom: "joined_chat_room",
574
+ LeaveRoom: "leave_room",
575
+ MarkMsgAsRead: "mark_msg_as_read",
576
+ Message: "message",
577
+ MessageDelivered: "message_delivered",
578
+ NewMention: "new_mention",
579
+ PrioritizeChat: "prioritize_chat",
580
+ RefetchChats: "refetch_chats",
581
+ ReopenChat: "reopen_chat",
582
+ RefetchChatCounts: "refetch_chat_counts",
583
+ SnoozeChat: "snooze_chat",
584
+ StartChat: "start_chat"
585
+ });
586
+
587
+ // src/components/widget/chat-widget.tsx
588
+ import { io } from "socket.io-client";
589
+ import { jsx as jsx7 } from "react/jsx-runtime";
590
+ function ChatWidget() {
591
+ const [draft, setDraft] = useState2("");
592
+ const [typing, setTyping] = useState2(false);
593
+ const timers = useRef2([]);
594
+ const state = useApp();
595
+ const [activeChat, setActiveChat] = useState2(null);
596
+ const socketRef = useRef2(null);
597
+ const appendMessage = (msg) => {
598
+ const chatJson = sessionStorage.getItem(SessionStorageKeys.ActiveChat);
599
+ if (!chatJson) return;
600
+ const chat = JSON.parse(chatJson);
601
+ if (msg.chatId == chat.id) {
602
+ state?.appendMessage(msg);
603
+ }
604
+ };
605
+ const handleChatAction = (action) => {
606
+ switch (action.action) {
607
+ case "typing.started":
608
+ setTyping(true);
609
+ break;
610
+ case "typing.stopped":
611
+ setTyping(false);
612
+ break;
613
+ case "uploading_file.started":
614
+ case "uploading_file.stopped":
615
+ default:
616
+ break;
617
+ }
618
+ };
619
+ const handleChatStarted = async (chat) => {
620
+ const user = JSON.parse(localStorage.getItem(LocalStorageKeys.User));
621
+ if (chat.customerId != user.id) {
622
+ console.log("chat created by a different cstomer");
623
+ return;
624
+ }
625
+ socketRef.current?.emit(SocketEvent.JoinChatRoom, chat.id);
626
+ const chats = await chat_service_default.getAllChats(user.id);
627
+ state?.setChats(chats.data);
628
+ persistActiveChat(chat);
629
+ };
630
+ const updateChat = (chat) => {
631
+ const acJson = sessionStorage.getItem(SessionStorageKeys.ActiveChat);
632
+ if (!acJson) return;
633
+ const ac = JSON.parse(acJson);
634
+ if (ac && ac.id === chat.id) {
635
+ setActiveChat(chat);
636
+ }
637
+ };
638
+ const persistActiveChat = (c) => {
639
+ setActiveChat(c);
640
+ if (!c) {
641
+ sessionStorage.removeItem(SessionStorageKeys.ActiveChat);
642
+ } else {
643
+ sessionStorage.setItem(SessionStorageKeys.ActiveChat, JSON.stringify(c));
644
+ }
645
+ };
646
+ useEffect2(() => {
647
+ const pending = timers.current;
648
+ return () => pending.forEach(clearTimeout);
649
+ }, []);
650
+ useEffect2(() => {
651
+ if (!state || !state.user || !state.accessToken) return;
652
+ if (socketRef.current) return;
653
+ const socket = io(getSocketBaseUrl(), {
654
+ extraHeaders: {
655
+ "Api-Key": getKiliConfig().apiKey,
656
+ "Api-Secret": getKiliConfig().apiSecret,
657
+ "Authorization": `Bearer ${state.accessToken}`
658
+ }
659
+ });
660
+ socket.on("connect", () => {
661
+ console.log("socket connected");
662
+ socket.emit(SocketEvent.JoinAllUnclosedChatRooms);
663
+ socket.on(SocketEvent.ChatAction, handleChatAction);
664
+ socket.on(SocketEvent.ChatStarted, handleChatStarted);
665
+ socket.on(SocketEvent.ChatUpdated, updateChat);
666
+ socket.on(SocketEvent.MessageDelivered, appendMessage);
667
+ });
668
+ socket.on(SocketEvent.Disconnect, () => {
669
+ console.log("socket disconnected");
670
+ });
671
+ socket.on(SocketEvent.Error, (err) => {
672
+ console.log(socket.id, "has an error", err);
673
+ });
674
+ socketRef.current = socket;
675
+ }, [state]);
676
+ const sendMessage = useCallback2(() => {
677
+ if (!activeChat) return;
678
+ const user = state?.user ?? JSON.parse(localStorage.getItem(LocalStorageKeys.User));
679
+ const msg = {
680
+ chatId: Number(activeChat.id),
681
+ content: draft.trim(),
682
+ senderEmail: user.email,
683
+ senderId: user.id,
684
+ sentAt: (/* @__PURE__ */ new Date()).toISOString(),
685
+ senderAccountType: "CUSTOMER",
686
+ senderFirstName: user.firstName,
687
+ senderLastName: user.lastName,
688
+ type: "TEXT"
689
+ };
690
+ socketRef.current.emit(SocketEvent.ChatAction, {
691
+ action: "typing.stopped",
692
+ chatId: activeChat.id
693
+ });
694
+ socketRef.current.emit(SocketEvent.Message, msg);
695
+ setDraft("");
696
+ }, [activeChat, draft]);
697
+ const startChatOld = useCallback2(async () => {
698
+ const chat = await chat_service_default.startChat();
699
+ socketRef.current?.emit(SocketEvent.JoinChatRoom, { chatId: chat.id });
700
+ const user = JSON.parse(localStorage.getItem(LocalStorageKeys.User));
701
+ const chats = await chat_service_default.getAllChats(user.id);
702
+ state?.setChats(chats.data);
703
+ persistActiveChat(chat);
704
+ setDraft("");
705
+ }, []);
706
+ const startChat = useCallback2(() => {
707
+ socketRef?.current?.emit(SocketEvent.StartChat, { initiationChannel: "web_widget" });
708
+ setDraft("");
709
+ }, []);
710
+ return state && /* @__PURE__ */ jsx7("div", { className: "kili-root flex h-dvh w-full flex-col overflow-hidden bg-background", children: activeChat ? /* @__PURE__ */ jsx7(
711
+ ChatThread,
712
+ {
713
+ chat: activeChat,
714
+ draft,
715
+ typing,
716
+ onDraftChange: setDraft,
717
+ onSend: sendMessage,
718
+ onBack: () => {
719
+ persistActiveChat(null);
720
+ setTyping(false);
721
+ },
722
+ onTextFieldBlur: () => {
723
+ socketRef.current?.emit(SocketEvent.ChatAction, {
724
+ action: "typing.stopped",
725
+ chatId: activeChat.id
726
+ });
727
+ },
728
+ onTextfieldFocus: () => {
729
+ socketRef.current?.emit(SocketEvent.ChatAction, {
730
+ action: "typing.started",
731
+ chatId: activeChat.id
732
+ });
733
+ }
734
+ }
735
+ ) : /* @__PURE__ */ jsx7(
736
+ ChatHome,
737
+ {
738
+ chats: state.chats,
739
+ onOpen: (c) => {
740
+ persistActiveChat(c);
741
+ setDraft("");
742
+ },
743
+ onStartNew: startChat
744
+ }
745
+ ) });
746
+ }
747
+
748
+ // src/services/core.service.ts
749
+ import randomName from "@scaleway/random-name";
750
+ var coreService = {
751
+ async createCustomer() {
752
+ let user = localStorage.getItem(LocalStorageKeys.User);
753
+ if (user) return JSON.parse(user);
754
+ const [fname, lname] = randomName("", " ").split(" ");
755
+ const res = await http_default.post("/customers", {
756
+ city: "Denver",
757
+ country: "united states",
758
+ device: "iPhone 17 pro",
759
+ email: `${fname}.${lname}@kili.africa`,
760
+ firstName: fname,
761
+ id: crypto.randomUUID(),
762
+ lastName: lname,
763
+ phoneCountryCode: "1",
764
+ phoneNumberSuffix: "1234567",
765
+ state: "Colorado"
766
+ });
767
+ console.dir({ createdCustomer: res.data }, { depth: null });
768
+ localStorage.setItem(LocalStorageKeys.User, JSON.stringify(res.data.data));
769
+ return res.data.data;
770
+ },
771
+ async registerCustomer() {
772
+ const data = localStorage.getItem(LocalStorageKeys.User);
773
+ const user = JSON.parse(data);
774
+ const res = await http_default.put("/customers", {
775
+ id: user.userId,
776
+ email: user.email
777
+ });
778
+ localStorage.setItem(LocalStorageKeys.JwtAccessToken, res.data.data.accessToken);
779
+ localStorage.setItem(LocalStorageKeys.AccessTokenExp, res.data.data.expiresAt);
780
+ return res.data.data;
781
+ },
782
+ async setCustomerHmac() {
783
+ const data = localStorage.getItem(LocalStorageKeys.User);
784
+ const user = JSON.parse(data);
785
+ const hmac = crypto.randomUUID();
786
+ await http_default.patch(`/customers/${user.userId}/hmac`, { hmac });
787
+ }
788
+ };
789
+ var core_service_default = coreService;
790
+
791
+ // src/kili-chat.tsx
792
+ import { jsx as jsx8 } from "react/jsx-runtime";
793
+ function KiliChat({ config }) {
794
+ configureKili(config);
795
+ return /* @__PURE__ */ jsx8(state_default, { children: /* @__PURE__ */ jsx8(KiliChatBootstrap, {}) });
796
+ }
797
+ function KiliChatBootstrap() {
798
+ const state = useApp();
799
+ const onMount = async () => {
800
+ const customer2 = await core_service_default.createCustomer();
801
+ await core_service_default.setCustomerHmac();
802
+ const auth = await core_service_default.registerCustomer();
803
+ state?.setUser(customer2);
804
+ state?.setAccessToken(auth.accessToken);
805
+ const chats = await chat_service_default.getAllChats(customer2.id);
806
+ state?.setChats(chats.data);
807
+ };
808
+ useEffect3(() => {
809
+ onMount();
810
+ }, []);
811
+ return /* @__PURE__ */ jsx8(ChatWidget, {});
812
+ }
813
+
814
+ // src/context/socket.tsx
815
+ import { io as io2 } from "socket.io-client";
816
+ import React3, { useContext as useContext3 } from "react";
817
+ import { jsx as jsx9 } from "react/jsx-runtime";
818
+ var SocketContext = React3.createContext(null);
819
+ function SocketProvider({ children }) {
820
+ const [socket, setSocket] = React3.useState(null);
821
+ const state = useContext3(AppStateContext);
822
+ React3.useEffect(() => {
823
+ if (!state || !state.user || !state.accessToken) return;
824
+ if (socket) return;
825
+ const socketClient = io2(getSocketBaseUrl(), {
826
+ extraHeaders: {
827
+ "Api-Key": getKiliConfig().apiKey,
828
+ "Api-Secret": getKiliConfig().apiSecret,
829
+ "Authorization": `Bearer ${state.accessToken}`
830
+ }
831
+ });
832
+ socketClient.on("connect", () => {
833
+ console.log(socketClient.id, "connected to the socket");
834
+ socketClient.emit(SocketEvent.JoinAllUnclosedChatRooms);
835
+ socketClient.on(SocketEvent.JoinedChatRoom, (roomId) => console.log("joined chat room", roomId));
836
+ });
837
+ socketClient.on(SocketEvent.Disconnect, () => {
838
+ console.log(socketClient.id, "has disconnected from the socket");
839
+ });
840
+ socketClient.on(SocketEvent.Error, (err) => {
841
+ console.log(socketClient.id, "has an error", err);
842
+ });
843
+ setSocket(socketClient);
844
+ }, [state]);
845
+ return /* @__PURE__ */ jsx9(SocketContext.Provider, { value: socket, children });
846
+ }
847
+
848
+ // src/hooks/use-mobile.tsx
849
+ import * as React4 from "react";
850
+ var MOBILE_BREAKPOINT = 768;
851
+ function useIsMobile() {
852
+ const [isMobile, setIsMobile] = React4.useState(void 0);
853
+ React4.useEffect(() => {
854
+ const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
855
+ const onChange = () => {
856
+ setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
857
+ };
858
+ mql.addEventListener("change", onChange);
859
+ setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
860
+ return () => mql.removeEventListener("change", onChange);
861
+ }, []);
862
+ return !!isMobile;
863
+ }
864
+ export {
865
+ AppStateContext,
866
+ state_default as AppStateProvider,
867
+ Button,
868
+ ChatHome,
869
+ ChatThread,
870
+ ChatWidget,
871
+ InitialsAvatar,
872
+ KiliChat,
873
+ LocalStorageKeys,
874
+ SessionStorageKeys,
875
+ SocketContext,
876
+ SocketEvent,
877
+ SocketProvider,
878
+ Textarea,
879
+ agentById,
880
+ agents,
881
+ brand,
882
+ buttonVariants,
883
+ chat_service_default as chatService,
884
+ clockTime,
885
+ cn,
886
+ configureKili,
887
+ core_service_default as coreService,
888
+ customer,
889
+ dayLabel,
890
+ getInitialsFromFullName,
891
+ getInitialsFromNames,
892
+ getKiliConfig,
893
+ http_default as http,
894
+ nextCannedReply,
895
+ relativeTime,
896
+ seedConversations,
897
+ useApp,
898
+ useIsMobile
899
+ };
900
+ //# sourceMappingURL=index.js.map