Repository navigation
Expand file tree
/
Copy pathChatModal.astro
More file actions
589 lines (544 loc) · 27.8 KB
/
Copy pathChatModal.astro
File metadata and controls
589 lines (544 loc) · 27.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
---
---
<div id="ai-chat-widget">
<!-- Floating Trigger Button -->
<button
type="button"
id="ai-chat-open-btn"
class="fixed bottom-6 right-6 z-50 flex items-center gap-2.5 rounded-full bg-primary px-4 py-3 text-sm font-semibold text-primary-foreground shadow-lg hover:opacity-90 transition-all hover:scale-105 cursor-pointer focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2"
aria-label="Open Agent AJ"
>
<img src="/icon.svg" alt="" class="size-5 object-contain" width="20" height="20" />
<span>Ask Agent AJ</span>
</button>
<!-- Modal Backdrop & Window -->
<div
id="ai-chat-modal"
class="hidden fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-xs transition-opacity"
role="dialog"
aria-modal="true"
aria-labelledby="ai-chat-title"
>
<div class="relative flex flex-col w-full max-w-2xl h-[640px] max-h-[90vh] rounded-2xl border border-border bg-card shadow-2xl overflow-hidden">
<!-- Header -->
<header class="flex items-center justify-between border-b border-border px-5 py-3.5 bg-muted/40">
<div class="flex items-center gap-3">
<img
src="/icon.svg"
alt="Agent AJ Logo"
class="size-8 rounded-lg object-contain bg-primary/10 p-1"
width="32"
height="32"
/>
<div>
<h2 id="ai-chat-title" class="text-sm font-bold tracking-tight">Agent AJ</h2>
<p class="text-[11px] text-muted-foreground">Grounded in Sanity Content Lake & Workers AI</p>
</div>
</div>
<button
type="button"
id="ai-chat-close-btn"
class="rounded-md p-1.5 text-muted-foreground hover:bg-accent hover:text-foreground transition-colors cursor-pointer"
aria-label="Close dialog"
>
<svg class="size-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<line x1="18" y1="6" x2="6" y2="18"></line>
<line x1="6" y1="6" x2="18" y2="18"></line>
</svg>
</button>
</header>
<!-- Messages Container -->
<div id="ai-chat-messages" class="flex-1 overflow-y-auto p-4 sm:p-5 flex flex-col gap-4 text-sm">
<!-- Welcome / Prompt chips -->
<div id="ai-chat-welcome" class="flex flex-col gap-3 my-auto text-center items-center py-6">
<img src="/icon.svg" alt="Agent AJ" class="size-14 rounded-2xl object-contain bg-primary/10 p-2 shadow-sm" width="56" height="56" />
<h3 class="font-semibold text-base">Hi, I'm Agent AJ!</h3>
<p class="text-xs text-muted-foreground max-w-sm">
I query live CodingCat.dev podcasts, tutorials, and transcripts. Ask me anything or select a quick request:
</p>
<div class="flex flex-wrap gap-2 justify-center max-w-md pt-2">
<button
type="button"
class="ai-prompt-chip inline-flex items-center gap-1.5 text-xs px-3.5 py-2 rounded-full border border-border bg-card hover:bg-accent text-foreground cursor-pointer transition-all font-medium shadow-2xs hover:scale-105"
data-prompt="What is the latest podcast episode?"
>
<svg class="size-3.5 text-primary" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"></path>
<path d="M19 10v2a7 7 0 0 1-14 0v-2"></path>
<line x1="12" x2="12" y1="19" y2="22"></line>
</svg>
<span>Latest podcast</span>
</button>
<button
type="button"
class="ai-prompt-chip inline-flex items-center gap-1.5 text-xs px-3.5 py-2 rounded-full border border-border bg-card hover:bg-accent text-foreground cursor-pointer transition-all font-medium shadow-2xs hover:scale-105"
data-prompt="What is the latest blog post?"
>
<svg class="size-3.5 text-primary" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
<polyline points="14 2 14 8 20 8"></polyline>
<line x1="16" y1="13" x2="8" y2="13"></line>
<line x1="16" y1="17" x2="8" y2="17"></line>
</svg>
<span>Latest blog post</span>
</button>
<button
type="button"
class="ai-prompt-chip inline-flex items-center gap-1.5 text-xs px-3.5 py-2 rounded-full border border-border bg-card hover:bg-accent text-foreground cursor-pointer transition-all font-medium shadow-2xs hover:scale-105"
data-prompt="What are the top videos on CodingCat.dev?"
>
<svg class="size-3.5 text-primary" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polygon points="23 7 16 12 23 17 23 7"></polygon>
<rect x="1" y="5" width="15" height="14" rx="2" ry="2"></rect>
</svg>
<span>Top videos</span>
</button>
<button
type="button"
class="ai-prompt-chip inline-flex items-center gap-1.5 text-xs px-3.5 py-2 rounded-full border border-border bg-card hover:bg-accent text-foreground cursor-pointer transition-all font-medium shadow-2xs hover:scale-105"
data-prompt="Tell me a programming dad joke!"
>
<svg class="size-3.5 text-primary" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="10"></circle>
<path d="M8 14s1.5 2 4 2 4-2 4-2"></path>
<line x1="9" x2="9.01" y1="9" y2="9"></line>
<line x1="15" x2="15.01" y1="9" y2="9"></line>
</svg>
<span>Coding joke</span>
</button>
</div>
</div>
</div>
<!-- Predefined Quick Request Buttons (Sticky Bar) -->
<div class="flex items-center gap-1.5 px-3 sm:px-4 py-2 border-t border-border/40 bg-muted/20 overflow-x-auto no-scrollbar">
<span class="text-[11px] font-semibold text-muted-foreground uppercase tracking-wider shrink-0 mr-1">Quick:</span>
<button
type="button"
class="ai-prompt-chip shrink-0 inline-flex items-center gap-1.5 text-xs px-3 py-1 rounded-full border border-border bg-card hover:bg-accent text-muted-foreground hover:text-foreground cursor-pointer transition-colors font-medium shadow-2xs"
data-prompt="What is the latest podcast episode?"
>
<svg class="size-3 text-primary" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"></path>
<path d="M19 10v2a7 7 0 0 1-14 0v-2"></path>
<line x1="12" x2="12" y1="19" y2="22"></line>
</svg>
<span>Latest podcast</span>
</button>
<button
type="button"
class="ai-prompt-chip shrink-0 inline-flex items-center gap-1.5 text-xs px-3 py-1 rounded-full border border-border bg-card hover:bg-accent text-muted-foreground hover:text-foreground cursor-pointer transition-colors font-medium shadow-2xs"
data-prompt="What is the latest blog post?"
>
<svg class="size-3 text-primary" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
<polyline points="14 2 14 8 20 8"></polyline>
<line x1="16" y1="13" x2="8" y2="13"></line>
<line x1="16" y1="17" x2="8" y2="17"></line>
</svg>
<span>Latest blog post</span>
</button>
<button
type="button"
class="ai-prompt-chip shrink-0 inline-flex items-center gap-1.5 text-xs px-3 py-1 rounded-full border border-border bg-card hover:bg-accent text-muted-foreground hover:text-foreground cursor-pointer transition-colors font-medium shadow-2xs"
data-prompt="What are the top videos on CodingCat.dev?"
>
<svg class="size-3 text-primary" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polygon points="23 7 16 12 23 17 23 7"></polygon>
<rect x="1" y="5" width="15" height="14" rx="2" ry="2"></rect>
</svg>
<span>Top videos</span>
</button>
<button
type="button"
class="ai-prompt-chip shrink-0 inline-flex items-center gap-1.5 text-xs px-3 py-1 rounded-full border border-border bg-card hover:bg-accent text-muted-foreground hover:text-foreground cursor-pointer transition-colors font-medium shadow-2xs"
data-prompt="Tell me a programming dad joke!"
>
<svg class="size-3 text-primary" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="10"></circle>
<path d="M8 14s1.5 2 4 2 4-2 4-2"></path>
<line x1="9" x2="9.01" y1="9" y2="9"></line>
<line x1="15" x2="15.01" y1="9" y2="9"></line>
</svg>
<span>Coding joke</span>
</button>
</div>
<!-- Input Form -->
<form id="ai-chat-form" class="border-t border-border p-3 sm:p-4 bg-card flex items-center gap-2">
<input
type="text"
id="ai-chat-input"
placeholder="Ask Agent AJ about CodingCat.dev..."
class="flex-1 rounded-xl border border-input bg-background px-4 py-2.5 text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary transition-all"
autocomplete="off"
/>
<button
type="submit"
id="ai-chat-send-btn"
class="rounded-xl bg-primary px-4 py-2.5 text-sm font-semibold text-primary-foreground hover:opacity-90 disabled:opacity-50 transition-all cursor-pointer"
>
Send
</button>
</form>
</div>
</div>
</div>
<script>
const openBtn = document.getElementById("ai-chat-open-btn");
const closeBtn = document.getElementById("ai-chat-close-btn");
const modal = document.getElementById("ai-chat-modal");
const form = document.getElementById("ai-chat-form") as HTMLFormElement | null;
const input = document.getElementById("ai-chat-input") as HTMLInputElement | null;
const sendBtn = document.getElementById("ai-chat-send-btn") as HTMLButtonElement | null;
const messagesContainer = document.getElementById("ai-chat-messages");
const welcomeContainer = document.getElementById("ai-chat-welcome");
let isStreaming = false;
function openModal() {
if (modal) {
modal.classList.remove("hidden");
input?.focus();
}
}
function closeModal() {
if (modal) {
modal.classList.add("hidden");
}
}
openBtn?.addEventListener("click", openModal);
closeBtn?.addEventListener("click", closeModal);
modal?.addEventListener("click", (e) => {
if (e.target === modal) {
closeModal();
}
});
window.addEventListener("keydown", (e) => {
if (e.key === "Escape" && modal && !modal.classList.contains("hidden")) {
closeModal();
}
});
document.querySelectorAll(".ai-prompt-chip").forEach((chip) => {
chip.addEventListener("click", () => {
const prompt = chip.getAttribute("data-prompt");
if (prompt && input) {
input.value = prompt;
form?.dispatchEvent(new Event("submit", { cancelable: true }));
}
});
});
function escapeHtml(text: string): string {
return text
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
const PROVIDER_CONFIG: Array<{
key: string;
label: string;
colorClass: string;
svg: string;
}> = [
{
key: "spotify",
label: "Spotify",
colorClass: "text-[#1DB954]",
svg: '<svg class="size-3.5 fill-current" viewBox="0 0 24 24"><path d="M12 0C5.4 0 0 5.4 0 12s5.4 12 12 12 12-5.4 12-12S18.66 0 12 0Zm5.521 17.34c-.24.359-.66.48-1.021.24-2.82-1.74-6.36-2.101-10.561-1.141-.418.122-.779-.179-.899-.539-.12-.421.18-.78.54-.9 4.56-1.021 8.52-.6 11.64 1.32.42.18.479.659.301 1.02Zm1.44-3.3c-.301.42-.841.6-1.262.3-3.239-1.98-8.159-2.58-11.939-1.38-.479.12-1.02-.12-1.14-.6-.12-.48.12-1.021.6-1.141C9.6 9.9 15 10.561 18.72 12.84c.361.181.54.78.241 1.2Zm.12-3.36C15.24 8.4 8.82 8.16 5.16 9.301c-.6.179-1.2-.181-1.38-.721-.18-.601.18-1.2.72-1.381 4.26-1.26 11.28-1.02 15.721 1.621.539.3.719 1.02.419 1.56-.299.421-1.02.599-1.559.3Z"/></svg>',
},
{
key: "apple",
label: "Apple",
colorClass: "text-[#A555F7]",
svg: '<svg class="size-3.5 fill-current" viewBox="0 0 24 24"><path d="M5.34 0A5.328 5.328 0 0 0 0 5.34v13.32A5.328 5.328 0 0 0 5.34 24h13.32A5.328 5.328 0 0 0 24 18.66V5.34A5.328 5.328 0 0 0 18.66 0Zm6.525 2.568c2.336 0 4.448.902 6.056 2.587 1.224 1.272 1.912 2.619 2.264 4.392.12.59.12 2.2.007 2.864a8.506 8.506 0 0 1-3.24 5.296c-.608.46-2.096 1.261-2.336 1.261-.088 0-.096-.091-.056-.46.072-.592.144-.715.48-.856.535-.224 1.447-.874 2.008-1.435a7.644 7.644 0 0 0 2.008-3.536c.208-.824.184-2.656-.048-3.504-.728-2.672-2.512-4.544-5.096-5.336-.784-.24-2.44-.336-3.384-.2-2.36.32-4.448 1.664-5.616 3.616-1.096 1.832-1.264 4.24-.44 6.224.6 1.448 1.784 2.792 3.048 3.472.28.152.352.28.416.72.048.36.024.44-.056.44-.048 0-.416-.16-.816-.36l-.024-.008c-1.472-.72-2.72-2.032-3.448-3.648-1.472-3.248-.688-7.02 1.928-9.352 1.72-1.53 3.88-2.28 6.344-2.28z"/></svg>',
},
{
key: "youtube",
label: "YouTube",
colorClass: "text-[#FF0000]",
svg: '<svg class="size-3.5 fill-current" viewBox="0 0 24 24"><path d="M23.498 6.186a3.016 3.016 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 0 0 .502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 0 0 2.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 0 0 2.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814ZM9.545 15.568V8.432L15.818 12l-6.273 3.568Z"/></svg>',
},
{
key: "pocketCasts",
label: "Pocket Casts",
colorClass: "text-[#F43E37]",
svg: '<svg class="size-3.5 fill-current" viewBox="0 0 24 24"><path d="M12 0C5.372 0 0 5.372 0 12s5.372 12 12 12 12-5.372 12-12S18.628 0 12 0zm0 3.6c4.639 0 8.4 3.761 8.4 8.4h-2.1c0-3.48-2.82-6.3-6.3-6.3S5.7 8.52 5.7 12s2.82 6.3 6.3 6.3v2.1c-4.639 0-8.4-3.761-8.4-8.4S7.361 3.6 12 3.6zm0 3.45c2.734 0 4.95 2.216 4.95 4.95h-2.1c0-1.574-1.276-2.85-2.85-2.85S9.15 10.426 9.15 12s1.276 2.85 2.85 2.85v2.1c-2.734 0-4.95-2.216-4.95-4.95S9.266 7.05 12 7.05z"/></svg>',
},
{
key: "castbox",
label: "Castbox",
colorClass: "text-[#F55B23]",
svg: '<svg class="size-3.5 fill-current" viewBox="0 0 24 24"><path d="M12 0C5.373 0 0 5.373 0 12s5.373 12 12 12 12-5.373 12-12S18.627 0 12 0zm-4.5 9.5a1 1 0 0 1 2 0v5a1 1 0 0 1-2 0v-5zm3.5-3a1 1 0 0 1 2 0v11a1 1 0 0 1-2 0v-11zm3.5 2a1 1 0 0 1 2 0v7a1 1 0 0 1-2 0v-7zm3.5 2.5a1 1 0 0 1 2 0v2a1 1 0 0 1-2 0v-2zm-14 0a1 1 0 0 1 2 0v2a1 1 0 0 1-2 0v-2z"/></svg>',
},
{
key: "castro",
label: "Castro",
colorClass: "text-[#00B265]",
svg: '<svg class="size-3.5 fill-current" viewBox="0 0 24 24"><path d="M12 0C5.373 0 0 5.373 0 12s5.373 12 12 12 12-5.373 12-12S18.627 0 12 0zm0 4.5a7.5 7.5 0 0 1 6.364 11.47l-2.12-1.474a4.92 4.92 0 1 0-8.488 0l-2.12 1.474A7.5 7.5 0 0 1 12 4.5zm0 4.8a2.7 2.7 0 1 1 0 5.4 2.7 2.7 0 0 1 0-5.4z"/></svg>',
},
{
key: "overcast",
label: "Overcast",
colorClass: "text-[#FC7E0F]",
svg: '<svg class="size-3.5 fill-current" viewBox="0 0 24 24"><path d="M12 2.25c-5.376 0-9.75 4.374-9.75 9.75s4.374 9.75 9.75 9.75 9.75-4.374 9.75-9.75S17.376 2.25 12 2.25zm0 1.5c4.55 0 8.25 3.7 8.25 8.25 0 2.91-1.515 5.475-3.795 6.945l-.915-2.07c1.62-.99 2.71-2.775 2.71-4.875 0-3.31-2.69-6-6-6s-6 2.69-6 6c0 2.1 1.09 3.885 2.71 4.875l-.915 2.07C5.765 17.475 4.25 14.91 4.25 12c0-4.55 3.7-8.25 8.25-8.25zm0 5.25a3 3 0 0 1 1.32 5.69l1.43 4.81h-1.6l-.8-2.69h-.7l-.8 2.69H9.25l1.43-4.81A3 3 0 0 1 12 9z"/></svg>',
},
{
key: "rss",
label: "RSS",
colorClass: "text-[#FFA500]",
svg: '<svg class="size-3.5 fill-current" viewBox="0 0 24 24"><path d="M6.18 15.64a2.18 2.18 0 0 1 2.18 2.18C8.36 19 7.38 20 6.18 20C5 20 4 19 4 17.82a2.18 2.18 0 0 1 2.18-2.18M4 4.44A15.56 15.56 0 0 1 19.56 20h-2.83A12.73 12.73 0 0 0 4 7.27V4.44m0 5.66a9.9 9.9 0 0 1 9.9 9.9h-2.83A7.07 7.07 0 0 0 4 12.93V10.1Z"/></svg>',
},
];
function stripProviderTrailer(text: string): string {
return text.replace(/\n?<!--AJ_PODCAST_PROVIDERS:[\s\S]*?(?:-->|$)/g, "");
}
function renderRichAssistantContent(container: HTMLElement, rawText: string) {
// Extract podcast provider metadata trailer if present
const providerMap = new Map<string, Record<string, string>>();
const providerItems: Array<{
title: string;
url: string;
listenLinks: Record<string, string>;
}> = [];
const trailerMatch = rawText.match(
/<!--AJ_PODCAST_PROVIDERS:([\s\S]*?)-->/,
);
if (trailerMatch?.[1]) {
try {
const parsed = JSON.parse(trailerMatch[1]);
if (Array.isArray(parsed)) {
for (const item of parsed) {
if (item?.url && item?.listenLinks) {
providerMap.set(item.url, item.listenLinks);
providerItems.push(item);
}
}
}
} catch {}
}
// Clean up any localhost, trailer, or malformed url artifacts
let cleanedText = stripProviderTrailer(rawText)
.replace(/http:\/\/localhost:\d+/g, "")
.replace(/\[\s*["']?(\/[a-zA-Z0-9_\-\/]+)["']?\s*\]\((?:http:\/\/localhost:\d+)?(\/[a-zA-Z0-9_\-\/]+)\)/g, "[$1]($2)")
.replace(/\[\s*["']?(\/[a-zA-Z0-9_\-\/]+)["']?\s*\]/g, "[$1]($1)");
// Extract YouTube links
const ytRegex = /(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:watch\?v=|embed\/|live\/))([\w-]{11})/gi;
const youtubeIds = new Set<string>();
let ytMatch: RegExpExecArray | null;
while ((ytMatch = ytRegex.exec(cleanedText)) !== null) {
if (ytMatch[1]) {
youtubeIds.add(ytMatch[1]);
}
}
// Extract Internal Episode / Post Links
const internalLinkRegex = /\[([^\]]+)\]\(((\/(?:podcast|post)\/[a-zA-Z0-9_\-]+))\)/gi;
const internalLinks: Array<{ title: string; url: string; type: "podcast" | "post" }> = [];
let intMatch: RegExpExecArray | null;
while ((intMatch = internalLinkRegex.exec(cleanedText)) !== null) {
const linkUrl = intMatch[2];
const linkTitle = intMatch[1];
const type = linkUrl.startsWith("/podcast") ? "podcast" : "post";
if (!internalLinks.some((l) => l.url === linkUrl)) {
internalLinks.push({ title: linkTitle, url: linkUrl, type });
}
}
// Ensure podcast items from tool results that were mentioned are included in internalLinks
for (const pItem of providerItems) {
if (
!internalLinks.some((l) => l.url === pItem.url) &&
(internalLinks.length === 0 ||
cleanedText.toLowerCase().includes(pItem.title.toLowerCase().slice(0, 24)))
) {
internalLinks.push({
title: pItem.title,
url: pItem.url,
type: "podcast",
});
}
}
// Convert markdown formatting to safe HTML
let html = escapeHtml(cleanedText);
// Bold: **text**
html = html.replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
// Bullet list: - text
html = html.replace(/^[ \t]*-[ \t]+(.*)$/gm, "<li class='ml-4 list-disc'>$1</li>");
// Markdown links: [Title](url)
html = html.replace(
/\[([^\]]+)\]\(([^)]+)\)/g,
"<a href='$2' class='text-primary font-medium hover:underline inline-flex items-center gap-0.5' target='_blank' rel='noopener noreferrer'>$1<svg class='size-3 inline opacity-70' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2'><path d='M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6'></path><polyline points='15 3 21 3 21 9'></polyline><line x1='10' y1='14' x2='21' y2='3'></line></svg></a>",
);
// Naked YouTube URLs
html = html.replace(
/(https?:\/\/(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:watch\?v=|embed\/|live\/))[\w-]+[^\s<]*)/gi,
"<a href='$1' class='text-primary font-medium hover:underline' target='_blank' rel='noopener noreferrer'>$1</a>",
);
// Newlines to <br> or <p>
html = html.replace(/\n\n/g, "<div class='h-2'></div>");
html = html.replace(/\n/g, "<br />");
// Build Cards Section
let cardsHtml = "";
// 1. YouTube Preview Cards
if (youtubeIds.size > 0) {
cardsHtml += `<div class="mt-3 flex flex-col gap-2.5">`;
for (const ytId of youtubeIds) {
const thumbUrl = `https://img.youtube.com/vi/${ytId}/mqdefault.jpg`;
const ytUrl = `https://www.youtube.com/watch?v=${ytId}`;
cardsHtml += `
<a href="${ytUrl}" target="_blank" rel="noopener noreferrer" class="group relative flex flex-col sm:flex-row items-center gap-3 p-2.5 rounded-xl border border-border bg-card/80 hover:bg-accent/60 transition-all hover:scale-[1.01] hover:shadow-md overflow-hidden text-left no-underline">
<div class="relative shrink-0 w-full sm:w-36 h-24 sm:h-20 rounded-lg overflow-hidden bg-black/20 flex items-center justify-center">
<img src="${thumbUrl}" alt="YouTube Preview" class="w-full h-full object-cover group-hover:opacity-90 transition-opacity" loading="lazy" />
<div class="absolute inset-0 flex items-center justify-center bg-black/25 group-hover:bg-black/10 transition-colors">
<div class="size-8 rounded-full bg-red-600/90 text-white flex items-center justify-center shadow-lg group-hover:scale-110 transition-transform">
<svg class="size-4 ml-0.5 fill-current" viewBox="0 0 24 24"><polygon points="5 3 19 12 5 21 5 3"></polygon></svg>
</div>
</div>
</div>
<div class="flex-1 min-w-0 py-0.5">
<div class="inline-flex items-center gap-1.5 text-[10px] uppercase font-bold tracking-wider text-red-500 mb-0.5">
<svg class="size-3.5 fill-current" viewBox="0 0 24 24"><path d="M23.498 6.186a3.016 3.016 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 0 0 .502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 0 0 2.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 0 0 2.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814zM9.545 15.568V8.432L15.818 12l-6.273 3.568z"/></svg>
YouTube Video
</div>
<div class="text-xs font-semibold text-foreground truncate group-hover:text-primary transition-colors">Watch on YouTube</div>
<div class="text-[11px] text-muted-foreground truncate">youtube.com/watch?v=${ytId}</div>
</div>
</a>
`;
}
cardsHtml += `</div>`;
}
// 2. Clickable Episode / Post Cards (+ Podcast Host Provider Logos)
if (internalLinks.length > 0) {
cardsHtml += `<div class="mt-2.5 flex flex-col gap-2">`;
for (const link of internalLinks) {
const isPodcast = link.type === "podcast";
const linksForEp = providerMap.get(link.url);
let providerBadgesHtml = "";
if (isPodcast && linksForEp) {
const badges = PROVIDER_CONFIG.filter((p) => Boolean(linksForEp[p.key]))
.map(
(p) => `
<a
href="${escapeHtml(linksForEp[p.key])}"
target="_blank"
rel="noopener noreferrer"
title="Listen on ${p.label}"
aria-label="Listen on ${p.label}"
class="inline-flex items-center gap-1 rounded-md border border-border/70 bg-background/80 px-2 py-1 text-[11px] font-medium text-foreground hover:bg-accent hover:border-primary/40 transition-colors no-underline"
>
<span class="${p.colorClass}">${p.svg}</span>
<span>${p.label}</span>
</a>
`,
)
.join("");
if (badges) {
providerBadgesHtml = `
<div class="mt-2 pt-2 border-t border-border/60 flex flex-wrap items-center gap-1.5">
<span class="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground mr-1">Listen on:</span>
${badges}
</div>
`;
}
}
cardsHtml += `
<div class="flex flex-col p-3 rounded-xl border border-border bg-card/90 hover:border-primary/40 transition-all shadow-2xs text-left">
<a href="${link.url}" class="group flex items-center justify-between gap-3 no-underline">
<div class="flex items-center gap-2.5 min-w-0">
<div class="size-8 rounded-lg ${isPodcast ? "bg-purple-500/10 text-purple-600 dark:text-purple-400" : "bg-blue-500/10 text-blue-600 dark:text-blue-400"} flex items-center justify-center shrink-0">
${
isPodcast
? '<svg class="size-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"></path><path d="M19 10v2a7 7 0 0 1-14 0v-2"></path><line x1="12" x2="12" y1="19" y2="22"></line></svg>'
: '<svg class="size-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline><line x1="16" y1="13" x2="8" y2="13"></line><line x1="16" y1="17" x2="8" y2="17"></line></svg>'
}
</div>
<div class="min-w-0">
<div class="text-xs font-semibold text-foreground group-hover:text-primary transition-colors truncate">${escapeHtml(link.title)}</div>
<div class="text-[10px] text-muted-foreground uppercase tracking-wider">${isPodcast ? "Podcast Episode" : "Blog Post"} • CodingCat.dev</div>
</div>
</div>
<div class="shrink-0 text-xs font-medium text-primary flex items-center gap-1 group-hover:translate-x-0.5 transition-transform">
<span>View</span>
<svg class="size-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="9 18 15 12 9 6"></polyline></svg>
</div>
</a>
${providerBadgesHtml}
</div>
`;
}
cardsHtml += `</div>`;
}
container.innerHTML = html + cardsHtml;
}
function appendMessage(role: "user" | "assistant", initialText = ""): HTMLElement {
if (welcomeContainer) {
welcomeContainer.classList.add("hidden");
}
const msgDiv = document.createElement("div");
msgDiv.className = `flex flex-col gap-1 max-w-[85%] ${
role === "user"
? "ml-auto bg-primary text-primary-foreground rounded-2xl rounded-tr-xs px-4 py-2.5"
: "mr-auto bg-muted/60 text-foreground rounded-2xl rounded-tl-xs px-4 py-2.5 border border-border"
}`;
if (role === "assistant") {
const badge = document.createElement("div");
badge.className = "flex items-center gap-1.5 text-[11px] font-semibold text-primary mb-0.5";
badge.innerHTML = `<img src="/icon.svg" alt="" class="size-3.5 object-contain" width="14" height="14" /><span>Agent AJ</span>`;
msgDiv.appendChild(badge);
}
const contentDiv = document.createElement("div");
contentDiv.className = "leading-relaxed text-sm";
contentDiv.textContent = initialText;
msgDiv.appendChild(contentDiv);
messagesContainer?.appendChild(msgDiv);
messagesContainer?.scrollTo({ top: messagesContainer.scrollHeight, behavior: "smooth" });
return contentDiv;
}
form?.addEventListener("submit", async (e) => {
e.preventDefault();
if (!input) return;
const prompt = input.value.trim();
if (!prompt || isStreaming) return;
input.value = "";
isStreaming = true;
if (sendBtn) sendBtn.disabled = true;
appendMessage("user", prompt);
const assistantContent = appendMessage("assistant", "Thinking...");
try {
const res = await fetch("/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ prompt }),
});
if (!res.ok) {
const errorJson = (await res.json().catch(() => ({}))) as {
error?: string;
};
assistantContent.textContent = `Error: ${errorJson.error || "Failed to generate answer"}`;
return;
}
if (!res.body) {
assistantContent.textContent = "No response stream received.";
return;
}
let accumulatedText = "";
const reader = res.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value, { stream: true });
accumulatedText += chunk;
// Render progressive text during streaming (without metadata trailer)
assistantContent.textContent = stripProviderTrailer(accumulatedText);
messagesContainer?.scrollTo({ top: messagesContainer.scrollHeight, behavior: "smooth" });
}
// On complete stream finish: render full rich content with cards & links
renderRichAssistantContent(assistantContent, accumulatedText);
messagesContainer?.scrollTo({ top: messagesContainer.scrollHeight, behavior: "smooth" });
} catch (err) {
assistantContent.textContent = `Connection error: ${err instanceof Error ? err.message : String(err)}`;
} finally {
isStreaming = false;
if (sendBtn) sendBtn.disabled = false;
input?.focus();
}
});
</script>