@traky-app/ui 1.6.0 → 1.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1250 @@
1
+ "use client";
2
+
3
+ import {
4
+ IconArrowUp,
5
+ IconDotsVertical,
6
+ IconLoader2,
7
+ IconMessages,
8
+ IconPackage,
9
+ IconPaperclip,
10
+ IconPlus,
11
+ IconSparkles,
12
+ IconTrash,
13
+ IconTruckLoading,
14
+ IconX,
15
+ type Icon,
16
+ } from "@tabler/icons-react";
17
+ import {
18
+ useCallback,
19
+ useEffect,
20
+ useLayoutEffect,
21
+ useMemo,
22
+ useRef,
23
+ useState,
24
+ type FormEvent,
25
+ type ReactNode,
26
+ } from "react";
27
+ import {
28
+ AlertDialog,
29
+ AlertDialogAction,
30
+ AlertDialogCancel,
31
+ AlertDialogContent,
32
+ AlertDialogDescription,
33
+ AlertDialogFooter,
34
+ AlertDialogHeader,
35
+ AlertDialogTitle,
36
+ } from "./alert-dialog";
37
+ import { Bubble, BubbleContent } from "./bubble";
38
+ import { Button } from "./button";
39
+ import {
40
+ Dialog,
41
+ DialogContent,
42
+ DialogDescription,
43
+ DialogFooter,
44
+ DialogHeader,
45
+ DialogTitle,
46
+ } from "./dialog";
47
+ import {
48
+ Drawer,
49
+ DrawerClose,
50
+ DrawerContent,
51
+ DrawerDescription,
52
+ DrawerTitle,
53
+ } from "./drawer";
54
+ import {
55
+ DropdownMenu,
56
+ DropdownMenuContent,
57
+ DropdownMenuItem,
58
+ DropdownMenuSeparator,
59
+ DropdownMenuTrigger,
60
+ } from "./dropdown-menu";
61
+ import {
62
+ Empty,
63
+ EmptyDescription,
64
+ EmptyHeader,
65
+ EmptyMedia,
66
+ EmptyTitle,
67
+ } from "./empty";
68
+ import {
69
+ InputGroup,
70
+ InputGroupAddon,
71
+ InputGroupButton,
72
+ InputGroupTextarea,
73
+ } from "./input-group";
74
+ import { Input } from "./input";
75
+ import {
76
+ Message,
77
+ MessageAvatar,
78
+ MessageContent,
79
+ MessageFooter,
80
+ MessageHeader,
81
+ } from "./message";
82
+ import {
83
+ Tooltip,
84
+ TooltipContent,
85
+ TooltipTrigger,
86
+ } from "./tooltip";
87
+ import { cn } from "../lib/utils";
88
+ import {
89
+ buildMentionList,
90
+ DEFAULT_MENTION_KIND_LABEL,
91
+ DEFAULT_MENTION_KIND_ORDER,
92
+ formatMessageTime,
93
+ parseMentionSegment,
94
+ parseSlashMention,
95
+ roomInitialLetter,
96
+ type BuildMentionListOptions,
97
+ type InternalChatMentionCatalogState,
98
+ type InternalChatMentionConfig,
99
+ type InternalChatMentionItem,
100
+ type InternalChatMentionKind,
101
+ type InternalChatMentionListEntry,
102
+ } from "./internal-chat-mention";
103
+
104
+ export type InternalChatRoom = {
105
+ id: string;
106
+ name: string;
107
+ isOrganization?: boolean;
108
+ };
109
+
110
+ export type InternalChatMessageLine = {
111
+ id: string;
112
+ role: "me" | "team";
113
+ author: string;
114
+ initials: string;
115
+ text: string;
116
+ at: string;
117
+ };
118
+
119
+ export type InternalChatMessagesStatus =
120
+ | "idle"
121
+ | "loading"
122
+ | "error"
123
+ | "empty"
124
+ | "ready";
125
+
126
+ export type InternalChatPanelLabels = {
127
+ openChat: string;
128
+ newRoom: string;
129
+ roomMenu: string;
130
+ deleteRoom: string;
131
+ closeChat: string;
132
+ newRoomTitle: string;
133
+ newRoomDescription: string;
134
+ newRoomPlaceholder: string;
135
+ cancel: string;
136
+ create: string;
137
+ deleteRoomTitle: string;
138
+ deleteRoomDescription: (roomName: string) => string;
139
+ deleteConfirm: string;
140
+ noRoomTitle: string;
141
+ noRoomDescription: string;
142
+ loadingMessages: string;
143
+ loadMessagesErrorTitle: string;
144
+ loadMessagesErrorFallback: string;
145
+ emptyThreadTitle: string;
146
+ emptyThreadDescription: (roomName: string) => string;
147
+ loadingOlderMessages: string;
148
+ mentionListLabel: string;
149
+ messagePlaceholder: string;
150
+ messagePlaceholderNoRoom: string;
151
+ messageAriaLabel: string;
152
+ attachAriaLabel: string;
153
+ attachPhotos: string;
154
+ sendSrOnly: string;
155
+ orgRoomSuffix: string;
156
+ orgRoomTooltip: string;
157
+ slashMentionHint: string;
158
+ selectRoomHint: string;
159
+ };
160
+
161
+ const DEFAULT_LABELS: InternalChatPanelLabels = {
162
+ openChat: "Abrir chat de la empresa",
163
+ newRoom: "Nueva sala",
164
+ roomMenu: "Más acciones de salas",
165
+ deleteRoom: "Eliminar sala actual",
166
+ closeChat: "Cerrar chat",
167
+ newRoomTitle: "Nueva sala",
168
+ newRoomDescription:
169
+ "Crea un espacio para conversar con tu equipo en tiempo real.",
170
+ newRoomPlaceholder: "Nombre de la sala",
171
+ cancel: "Cancelar",
172
+ create: "Crear",
173
+ deleteRoomTitle: "¿Eliminar esta sala?",
174
+ deleteRoomDescription: (roomName) =>
175
+ `Se borrarán los mensajes de «${roomName}» en el servidor. Esta acción no se puede deshacer.`,
176
+ deleteConfirm: "Eliminar",
177
+ noRoomTitle: "Sin sala",
178
+ noRoomDescription: "Crea una sala con el botón + a la izquierda.",
179
+ loadingMessages: "Cargando mensajes…",
180
+ loadMessagesErrorTitle: "No se pudieron cargar los mensajes",
181
+ loadMessagesErrorFallback:
182
+ "Revisa que la API esté en marcha y que el módulo de chat interno esté migrado.",
183
+ emptyThreadTitle: "¿De qué hablamos?",
184
+ emptyThreadDescription: (roomName) =>
185
+ `Escribe el primer mensaje en «${roomName}».`,
186
+ loadingOlderMessages: "Cargando mensajes anteriores…",
187
+ mentionListLabel: "Insertar mención",
188
+ messagePlaceholder: "Mensaje… · / comandos",
189
+ messagePlaceholderNoRoom: "Selecciona una sala…",
190
+ messageAriaLabel: "Mensaje",
191
+ attachAriaLabel: "Adjuntar",
192
+ attachPhotos: "Fotos y archivos",
193
+ sendSrOnly: "Enviar",
194
+ orgRoomSuffix: " · Sala de toda la organización",
195
+ orgRoomTooltip: " — toda la organización (no se elimina)",
196
+ slashMentionHint: "menciones (guías y paquetes)",
197
+ selectRoomHint: "Selecciona una sala o crea una nueva.",
198
+ };
199
+
200
+ const DEFAULT_MENTION_CONFIG: InternalChatMentionConfig = {
201
+ kindOrder: DEFAULT_MENTION_KIND_ORDER,
202
+ kindIcons: {
203
+ guide: IconTruckLoading,
204
+ package: IconPackage,
205
+ ai: IconSparkles,
206
+ },
207
+ categoryMeta: {
208
+ guide: {
209
+ label: "Guía",
210
+ hint: "Guías de envío",
211
+ keywords: ["guía", "guia", "guide", "envío", "envio"],
212
+ },
213
+ package: {
214
+ label: "Paquete",
215
+ hint: "Paquetes de la empresa (WR / tracking)",
216
+ keywords: ["paquete", "paquetes", "package", "trk", "wr"],
217
+ },
218
+ ai: {
219
+ label: "Asistencia de IA",
220
+ hint: "Consultas sobre operación y datos (próximamente)",
221
+ keywords: ["ia", "ai", "asistencia", "inteligencia", "asistente"],
222
+ disabled: true,
223
+ },
224
+ },
225
+ };
226
+
227
+ function isMentionEntryDisabled(
228
+ entry: InternalChatMentionListEntry,
229
+ config: InternalChatMentionConfig,
230
+ ): boolean {
231
+ if (entry.type !== "category") return false;
232
+ return Boolean(
233
+ entry.disabled ?? config.categoryMeta[entry.kind]?.disabled,
234
+ );
235
+ }
236
+
237
+ function stepMentionHighlight(
238
+ entries: InternalChatMentionListEntry[],
239
+ config: InternalChatMentionConfig,
240
+ current: number,
241
+ delta: 1 | -1,
242
+ ): number {
243
+ if (entries.length === 0) return 0;
244
+ let next = current;
245
+ for (let i = 0; i < entries.length; i++) {
246
+ next = (next + delta + entries.length) % entries.length;
247
+ if (!isMentionEntryDisabled(entries[next]!, config)) return next;
248
+ }
249
+ return current;
250
+ }
251
+
252
+ function renderMessageTextWithMentions(text: string): ReactNode {
253
+ const parts = text.split(/(@\[[^\]]+\])/g);
254
+ return parts.map((part, index) => {
255
+ const mention = /^@\[(.+)\]$/.exec(part);
256
+ if (mention) {
257
+ return (
258
+ <span
259
+ key={index}
260
+ className="inline-flex max-w-full items-center rounded-md border border-primary/35 bg-primary/12 px-1.5 py-0.5 font-medium text-primary"
261
+ >
262
+ {mention[1]}
263
+ </span>
264
+ );
265
+ }
266
+ return <span key={index}>{part}</span>;
267
+ });
268
+ }
269
+
270
+ export type InternalChatPanelProps = {
271
+ title: string;
272
+ rooms: InternalChatRoom[];
273
+ activeRoomId: string | null;
274
+ onActiveRoomChange: (roomId: string) => void;
275
+ messages: InternalChatMessageLine[];
276
+ messagesStatus: InternalChatMessagesStatus;
277
+ messagesError?: string | null;
278
+ onLoadOlderMessages?: () => void | Promise<void>;
279
+ isLoadingOlder?: boolean;
280
+ hasOlderMessages?: boolean;
281
+ mentionGuideItems?: InternalChatMentionItem[];
282
+ mentionPackageItems?: InternalChatMentionItem[];
283
+ mentionConfig?: InternalChatMentionConfig;
284
+ /** Catálogo de ítems ya filtrado en servidor (guías/paquetes). */
285
+ mentionServerFilteredItems?: boolean;
286
+ mentionCatalogLoading?: boolean;
287
+ onMentionCatalogChange?: (state: InternalChatMentionCatalogState) => void;
288
+ typingLine?: string | null;
289
+ onSendMessage: (text: string) => void | Promise<void>;
290
+ onCreateRoom: (name: string) => void | Promise<void>;
291
+ onDeleteRoom: (roomId: string) => void | Promise<void>;
292
+ onOpenChange?: (open: boolean) => void;
293
+ onDraftChange?: (draft: string) => void;
294
+ onUserGesture?: () => void;
295
+ isSending?: boolean;
296
+ isCreatingRoom?: boolean;
297
+ isDeletingRoom?: boolean;
298
+ onDeleteRoomBlocked?: (reason: string) => void;
299
+ labels?: Partial<InternalChatPanelLabels>;
300
+ className?: string;
301
+ };
302
+
303
+ function InternalChatPanel({
304
+ title,
305
+ rooms,
306
+ activeRoomId,
307
+ onActiveRoomChange,
308
+ messages,
309
+ messagesStatus,
310
+ messagesError = null,
311
+ onLoadOlderMessages,
312
+ isLoadingOlder = false,
313
+ hasOlderMessages = false,
314
+ mentionGuideItems = [],
315
+ mentionPackageItems = [],
316
+ mentionConfig = DEFAULT_MENTION_CONFIG,
317
+ mentionServerFilteredItems = false,
318
+ mentionCatalogLoading = false,
319
+ onMentionCatalogChange,
320
+ typingLine = null,
321
+ onSendMessage,
322
+ onCreateRoom,
323
+ onDeleteRoom,
324
+ onOpenChange,
325
+ onDraftChange,
326
+ onUserGesture,
327
+ isSending = false,
328
+ isCreatingRoom = false,
329
+ isDeletingRoom = false,
330
+ onDeleteRoomBlocked,
331
+ labels: labelsPartial,
332
+ className,
333
+ }: InternalChatPanelProps) {
334
+ const labels = { ...DEFAULT_LABELS, ...labelsPartial };
335
+
336
+ const [open, setOpen] = useState(false);
337
+ const [draft, setDraft] = useState("");
338
+ const [createOpen, setCreateOpen] = useState(false);
339
+ const [newRoomName, setNewRoomName] = useState("");
340
+ const [deleteOpen, setDeleteOpen] = useState(false);
341
+ const [mentionStart, setMentionStart] = useState<number | null>(null);
342
+ const [mentionQuery, setMentionQuery] = useState("");
343
+ const [mentionHighlight, setMentionHighlight] = useState(0);
344
+ const lastMentionQueryRef = useRef("");
345
+ const loadingOlderMessagesRef = useRef(false);
346
+
347
+ const formRef = useRef<HTMLFormElement>(null);
348
+ const scrollerRef = useRef<HTMLDivElement>(null);
349
+ const textareaRef = useRef<HTMLTextAreaElement>(null);
350
+
351
+ const activeRoom = useMemo(
352
+ () => rooms.find((r) => r.id === activeRoomId) ?? null,
353
+ [rooms, activeRoomId],
354
+ );
355
+
356
+ const mentionListOptions = useMemo((): BuildMentionListOptions | undefined => {
357
+ if (!mentionServerFilteredItems) return undefined;
358
+ const seg = parseMentionSegment(mentionQuery, mentionConfig);
359
+ if (seg.phase !== "item") return undefined;
360
+ return { serverFilteredItems: true };
361
+ }, [mentionServerFilteredItems, mentionQuery, mentionConfig]);
362
+
363
+ const mentionEntries = useMemo(
364
+ () =>
365
+ buildMentionList(
366
+ mentionQuery,
367
+ mentionGuideItems,
368
+ mentionPackageItems,
369
+ mentionConfig,
370
+ mentionListOptions,
371
+ ),
372
+ [
373
+ mentionQuery,
374
+ mentionGuideItems,
375
+ mentionPackageItems,
376
+ mentionConfig,
377
+ mentionListOptions,
378
+ ],
379
+ );
380
+
381
+ const mentionSeg = useMemo(
382
+ () => parseMentionSegment(mentionQuery, mentionConfig),
383
+ [mentionQuery, mentionConfig],
384
+ );
385
+
386
+ const mentionOpen =
387
+ Boolean(activeRoom) &&
388
+ mentionStart !== null &&
389
+ (mentionEntries.length > 0 ||
390
+ mentionCatalogLoading ||
391
+ (mentionServerFilteredItems && mentionSeg.phase === "item"));
392
+
393
+ const canSend =
394
+ draft.trim().length > 0 &&
395
+ !isSending &&
396
+ Boolean(activeRoomId);
397
+
398
+ const setOpenWithNotify = useCallback(
399
+ (next: boolean) => {
400
+ if (next) onUserGesture?.();
401
+ setOpen(next);
402
+ onOpenChange?.(next);
403
+ },
404
+ [onOpenChange, onUserGesture],
405
+ );
406
+
407
+ const handleMessagesScroll = useCallback(() => {
408
+ const node = scrollerRef.current;
409
+ if (!node || !activeRoomId || !onLoadOlderMessages) return;
410
+ if (loadingOlderMessagesRef.current) return;
411
+ if (node.scrollTop > 120) return;
412
+ if (!hasOlderMessages || isLoadingOlder) return;
413
+ loadingOlderMessagesRef.current = true;
414
+ const prevHeight = node.scrollHeight;
415
+ const prevTop = node.scrollTop;
416
+ void Promise.resolve(onLoadOlderMessages()).finally(() => {
417
+ loadingOlderMessagesRef.current = false;
418
+ requestAnimationFrame(() => {
419
+ const n = scrollerRef.current;
420
+ if (!n) return;
421
+ const delta = n.scrollHeight - prevHeight;
422
+ n.scrollTop = prevTop + delta;
423
+ });
424
+ });
425
+ }, [
426
+ activeRoomId,
427
+ hasOlderMessages,
428
+ isLoadingOlder,
429
+ onLoadOlderMessages,
430
+ ]);
431
+
432
+ useLayoutEffect(() => {
433
+ if (!open) return;
434
+ const scrollToEnd = () => {
435
+ const node = scrollerRef.current;
436
+ if (!node) return;
437
+ node.scrollTop = node.scrollHeight;
438
+ };
439
+ scrollToEnd();
440
+ let rafNested = 0;
441
+ const rafOuter = requestAnimationFrame(() => {
442
+ scrollToEnd();
443
+ rafNested = requestAnimationFrame(scrollToEnd);
444
+ });
445
+ const timeouts = [0, 50, 150].map((ms) =>
446
+ window.setTimeout(scrollToEnd, ms),
447
+ );
448
+ return () => {
449
+ cancelAnimationFrame(rafOuter);
450
+ if (rafNested) cancelAnimationFrame(rafNested);
451
+ timeouts.forEach(clearTimeout);
452
+ };
453
+ }, [open, activeRoomId, messages.length]);
454
+
455
+ useEffect(() => {
456
+ if (!mentionOpen || mentionEntries.length === 0) return;
457
+ setMentionHighlight((h) => Math.min(h, mentionEntries.length - 1));
458
+ }, [mentionOpen, mentionEntries.length]);
459
+
460
+ useEffect(() => {
461
+ setMentionStart(null);
462
+ setMentionQuery("");
463
+ lastMentionQueryRef.current = "";
464
+ }, [activeRoomId]);
465
+
466
+ useEffect(() => {
467
+ if (!onMentionCatalogChange) return;
468
+ if (mentionStart === null) {
469
+ onMentionCatalogChange({
470
+ open: false,
471
+ phase: "category",
472
+ filter: "",
473
+ });
474
+ return;
475
+ }
476
+ if (mentionSeg.phase === "category") {
477
+ onMentionCatalogChange({
478
+ open: true,
479
+ phase: "category",
480
+ filter: mentionSeg.filter,
481
+ });
482
+ return;
483
+ }
484
+ onMentionCatalogChange({
485
+ open: true,
486
+ phase: "item",
487
+ kind: mentionSeg.kind,
488
+ filter: mentionSeg.filter,
489
+ });
490
+ }, [mentionStart, mentionQuery, mentionConfig, onMentionCatalogChange]);
491
+
492
+ function closeMentionMenu() {
493
+ setMentionStart(null);
494
+ setMentionQuery("");
495
+ lastMentionQueryRef.current = "";
496
+ }
497
+
498
+ function syncMentionMenu(nextDraft: string, cursor: number) {
499
+ const m = parseSlashMention(nextDraft, cursor);
500
+ if (!m) {
501
+ closeMentionMenu();
502
+ return;
503
+ }
504
+ const seg = parseMentionSegment(m.query, mentionConfig);
505
+ const listOptions: BuildMentionListOptions | undefined =
506
+ mentionServerFilteredItems && seg.phase === "item"
507
+ ? { serverFilteredItems: true }
508
+ : undefined;
509
+ const entries = buildMentionList(
510
+ m.query,
511
+ mentionGuideItems,
512
+ mentionPackageItems,
513
+ mentionConfig,
514
+ listOptions,
515
+ );
516
+ const keepOpenOnEmpty =
517
+ mentionCatalogLoading ||
518
+ (mentionServerFilteredItems && seg.phase === "item");
519
+ if (entries.length === 0 && !keepOpenOnEmpty) {
520
+ closeMentionMenu();
521
+ return;
522
+ }
523
+ if (m.query !== lastMentionQueryRef.current) {
524
+ setMentionHighlight(0);
525
+ lastMentionQueryRef.current = m.query;
526
+ }
527
+ setMentionStart(m.start);
528
+ setMentionQuery(m.query);
529
+ }
530
+
531
+ function replaceSlashSegment(newSegment: string) {
532
+ const el = textareaRef.current;
533
+ if (el === null || mentionStart === null) return;
534
+ const cursor = el.selectionStart ?? draft.length;
535
+ const before = draft.slice(0, mentionStart);
536
+ const after = draft.slice(cursor);
537
+ const newDraft = `${before}/${newSegment}${after}`;
538
+ const slashEnd = before.length + 1 + newSegment.length;
539
+ setDraft(newDraft);
540
+ onDraftChange?.(newDraft);
541
+ setMentionQuery(newSegment);
542
+ lastMentionQueryRef.current = newSegment;
543
+ requestAnimationFrame(() => {
544
+ el.focus();
545
+ el.setSelectionRange(slashEnd, slashEnd);
546
+ });
547
+ }
548
+
549
+ function applyCategoryPick(kind: InternalChatMentionKind) {
550
+ if (mentionConfig.categoryMeta[kind]?.disabled) return;
551
+ replaceSlashSegment(`${kind}:`);
552
+ setMentionHighlight(0);
553
+ }
554
+
555
+ function applyItemPick(item: InternalChatMentionItem) {
556
+ const el = textareaRef.current;
557
+ if (el === null || mentionStart === null) return;
558
+ const cursor = el.selectionStart ?? draft.length;
559
+ const before = draft.slice(0, mentionStart);
560
+ const after = draft.slice(cursor);
561
+ const token = `@[${item.insertLabel}]`;
562
+ const needsSpace =
563
+ after.length > 0 && !/^\s/.test(after) && !after.startsWith("\n");
564
+ const newDraft = `${before}${token}${needsSpace ? " " : ""}${after}`;
565
+ setDraft(newDraft);
566
+ onDraftChange?.(newDraft);
567
+ closeMentionMenu();
568
+ const newPos = before.length + token.length + (needsSpace ? 1 : 0);
569
+ requestAnimationFrame(() => {
570
+ el.focus();
571
+ el.setSelectionRange(newPos, newPos);
572
+ });
573
+ }
574
+
575
+ async function onSubmit(event: FormEvent<HTMLFormElement>) {
576
+ event.preventDefault();
577
+ if (mentionOpen) return;
578
+ const text = draft.trim();
579
+ if (!text || !activeRoomId) return;
580
+ onUserGesture?.();
581
+ try {
582
+ await onSendMessage(text);
583
+ setDraft("");
584
+ onDraftChange?.("");
585
+ } catch {
586
+ /* errores vía contenedor */
587
+ }
588
+ }
589
+
590
+ async function handleCreateRoom() {
591
+ const name = newRoomName.trim();
592
+ if (!name) return;
593
+ try {
594
+ await onCreateRoom(name);
595
+ setNewRoomName("");
596
+ setCreateOpen(false);
597
+ } catch {
598
+ /* contenedor */
599
+ }
600
+ }
601
+
602
+ async function handleConfirmDeleteRoom() {
603
+ if (!activeRoom) return;
604
+ try {
605
+ await onDeleteRoom(activeRoom.id);
606
+ setDeleteOpen(false);
607
+ } catch {
608
+ /* contenedor */
609
+ }
610
+ }
611
+
612
+ function requestDeleteRoom() {
613
+ if (!activeRoom) return;
614
+ if (activeRoom.isOrganization) {
615
+ onDeleteRoomBlocked?.("La sala Organización no se puede eliminar.");
616
+ return;
617
+ }
618
+ if (rooms.length <= 1) {
619
+ onDeleteRoomBlocked?.("Debe existir al menos una sala.");
620
+ return;
621
+ }
622
+ setDeleteOpen(true);
623
+ }
624
+
625
+ return (
626
+ <>
627
+ <Button
628
+ type="button"
629
+ size="icon"
630
+ className={cn("relative size-9 text-primary-foreground", className)}
631
+ aria-label={labels.openChat}
632
+ onClick={() => setOpenWithNotify(true)}
633
+ >
634
+ <IconMessages className="size-4" />
635
+ </Button>
636
+
637
+ <Dialog open={createOpen} onOpenChange={setCreateOpen}>
638
+ <DialogContent className="sm:max-w-md">
639
+ <DialogHeader>
640
+ <DialogTitle>{labels.newRoomTitle}</DialogTitle>
641
+ <DialogDescription>{labels.newRoomDescription}</DialogDescription>
642
+ </DialogHeader>
643
+ <Input
644
+ value={newRoomName}
645
+ onChange={(e) => setNewRoomName(e.target.value)}
646
+ placeholder={labels.newRoomPlaceholder}
647
+ autoFocus
648
+ onKeyDown={(e) => {
649
+ if (e.key === "Enter") {
650
+ e.preventDefault();
651
+ void handleCreateRoom();
652
+ }
653
+ }}
654
+ />
655
+ <DialogFooter className="gap-2 sm:gap-0">
656
+ <Button
657
+ type="button"
658
+ variant="outline"
659
+ onClick={() => {
660
+ setCreateOpen(false);
661
+ setNewRoomName("");
662
+ }}
663
+ >
664
+ {labels.cancel}
665
+ </Button>
666
+ <Button
667
+ type="button"
668
+ onClick={() => void handleCreateRoom()}
669
+ disabled={isCreatingRoom}
670
+ >
671
+ {labels.create}
672
+ </Button>
673
+ </DialogFooter>
674
+ </DialogContent>
675
+ </Dialog>
676
+
677
+ <AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
678
+ <AlertDialogContent>
679
+ <AlertDialogHeader>
680
+ <AlertDialogTitle>{labels.deleteRoomTitle}</AlertDialogTitle>
681
+ <AlertDialogDescription>
682
+ {labels.deleteRoomDescription(activeRoom?.name ?? "la sala")}
683
+ </AlertDialogDescription>
684
+ </AlertDialogHeader>
685
+ <AlertDialogFooter>
686
+ <AlertDialogCancel>{labels.cancel}</AlertDialogCancel>
687
+ <AlertDialogAction
688
+ className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
689
+ onClick={() => void handleConfirmDeleteRoom()}
690
+ disabled={isDeletingRoom}
691
+ >
692
+ {labels.deleteConfirm}
693
+ </AlertDialogAction>
694
+ </AlertDialogFooter>
695
+ </AlertDialogContent>
696
+ </AlertDialog>
697
+
698
+ <Drawer
699
+ open={open}
700
+ onOpenChange={setOpenWithNotify}
701
+ direction="right"
702
+ shouldScaleBackground={false}
703
+ >
704
+ <DrawerContent
705
+ className={cn(
706
+ "gap-0 overflow-hidden p-0 shadow-xl",
707
+ "data-[vaul-drawer-direction=right]:inset-y-3",
708
+ "data-[vaul-drawer-direction=right]:right-3",
709
+ "data-[vaul-drawer-direction=right]:left-auto",
710
+ "data-[vaul-drawer-direction=right]:h-[calc(100%-1.5rem)]",
711
+ "data-[vaul-drawer-direction=right]:max-h-[calc(100%-1.5rem)]",
712
+ "data-[vaul-drawer-direction=right]:w-[min(36rem,calc(100vw-1.5rem))]",
713
+ "data-[vaul-drawer-direction=right]:max-w-[min(36rem,calc(100vw-1.5rem))]",
714
+ "data-[vaul-drawer-direction=right]:sm:max-w-[min(36rem,calc(100vw-1.5rem))]",
715
+ "data-[vaul-drawer-direction=right]:rounded-2xl",
716
+ "data-[vaul-drawer-direction=right]:border",
717
+ )}
718
+ >
719
+ <div className="flex h-full min-h-0 flex-row">
720
+ <div className="flex w-[3.25rem] shrink-0 flex-col items-center gap-2 border-r border-border py-4">
721
+ <Tooltip delayDuration={300}>
722
+ <TooltipTrigger asChild>
723
+ <Button
724
+ type="button"
725
+ variant="ghost"
726
+ size="icon"
727
+ className="size-9 shrink-0 rounded-full"
728
+ aria-label={labels.newRoom}
729
+ onClick={() => setCreateOpen(true)}
730
+ >
731
+ <IconPlus className="size-4" />
732
+ </Button>
733
+ </TooltipTrigger>
734
+ <TooltipContent side="left">{labels.newRoom}</TooltipContent>
735
+ </Tooltip>
736
+
737
+ <div className="flex min-h-0 flex-1 flex-col items-center gap-2 overflow-y-auto px-1 py-1">
738
+ {rooms.map((room) => {
739
+ const selected = room.id === activeRoomId;
740
+ return (
741
+ <Tooltip key={room.id} delayDuration={300}>
742
+ <TooltipTrigger asChild>
743
+ <button
744
+ type="button"
745
+ onClick={() => onActiveRoomChange(room.id)}
746
+ className={cn(
747
+ "relative flex size-9 shrink-0 items-center justify-center rounded-full border-2 transition-colors",
748
+ selected
749
+ ? "border-primary bg-primary/15"
750
+ : "border-transparent bg-muted hover:bg-muted/80",
751
+ )}
752
+ aria-label={`Sala ${room.name}${room.isOrganization ? " (toda la organización)" : ""}`}
753
+ aria-current={selected ? "true" : undefined}
754
+ >
755
+ <span className="text-xs font-semibold leading-none">
756
+ {roomInitialLetter(room.name)}
757
+ </span>
758
+ </button>
759
+ </TooltipTrigger>
760
+ <TooltipContent side="left">
761
+ {room.isOrganization
762
+ ? `${room.name}${labels.orgRoomTooltip}`
763
+ : room.name}
764
+ </TooltipContent>
765
+ </Tooltip>
766
+ );
767
+ })}
768
+ </div>
769
+
770
+ <DropdownMenu>
771
+ <DropdownMenuTrigger asChild>
772
+ <Button
773
+ type="button"
774
+ variant="ghost"
775
+ size="icon"
776
+ className="size-9 shrink-0 rounded-full"
777
+ aria-label={labels.roomMenu}
778
+ >
779
+ <IconDotsVertical className="size-4" />
780
+ </Button>
781
+ </DropdownMenuTrigger>
782
+ <DropdownMenuContent side="left" align="end" className="w-48">
783
+ <DropdownMenuItem onClick={() => setCreateOpen(true)}>
784
+ <IconPlus className="size-4" />
785
+ {labels.newRoom}
786
+ </DropdownMenuItem>
787
+ <DropdownMenuSeparator />
788
+ <DropdownMenuItem
789
+ disabled={
790
+ rooms.length <= 1 || activeRoom?.isOrganization
791
+ }
792
+ className="text-destructive focus:text-destructive"
793
+ onClick={requestDeleteRoom}
794
+ >
795
+ <IconTrash className="size-4" />
796
+ {labels.deleteRoom}
797
+ </DropdownMenuItem>
798
+ </DropdownMenuContent>
799
+ </DropdownMenu>
800
+ </div>
801
+
802
+ <div className="flex min-h-0 min-w-0 flex-1 flex-col">
803
+ <div className="flex items-start justify-between gap-4 px-5 pt-5 pb-3">
804
+ <div className="flex min-w-0 flex-col gap-1">
805
+ <DrawerTitle className="flex items-center gap-2 font-medium">
806
+ <IconMessages className="size-5 shrink-0" aria-hidden />
807
+ <span className="min-w-0 truncate">{title}</span>
808
+ </DrawerTitle>
809
+ <DrawerDescription className="line-clamp-2">
810
+ {activeRoom ? (
811
+ <>
812
+ <span className="font-medium text-foreground">
813
+ {activeRoom.name}
814
+ </span>
815
+ {activeRoom.isOrganization ? (
816
+ <>{labels.orgRoomSuffix}</>
817
+ ) : null}
818
+ {" · "}
819
+ <kbd className="pointer-events-none rounded border bg-muted px-0.5 font-mono text-[0.65rem]">
820
+ /
821
+ </kbd>{" "}
822
+ {labels.slashMentionHint}
823
+ </>
824
+ ) : (
825
+ labels.selectRoomHint
826
+ )}
827
+ </DrawerDescription>
828
+ </div>
829
+ <DrawerClose asChild>
830
+ <Button
831
+ type="button"
832
+ variant="outline"
833
+ size="icon"
834
+ className="size-8 shrink-0"
835
+ aria-label={labels.closeChat}
836
+ >
837
+ <IconX className="size-4" />
838
+ </Button>
839
+ </DrawerClose>
840
+ </div>
841
+
842
+ <div
843
+ ref={scrollerRef}
844
+ className="min-h-0 flex-1 overflow-y-auto"
845
+ onScroll={handleMessagesScroll}
846
+ >
847
+ {!activeRoom ? (
848
+ <Empty className="h-full border-0">
849
+ <EmptyHeader>
850
+ <EmptyMedia variant="icon">
851
+ <IconMessages />
852
+ </EmptyMedia>
853
+ <EmptyTitle>{labels.noRoomTitle}</EmptyTitle>
854
+ <EmptyDescription>
855
+ {labels.noRoomDescription}
856
+ </EmptyDescription>
857
+ </EmptyHeader>
858
+ </Empty>
859
+ ) : messagesStatus === "loading" ? (
860
+ <div className="flex h-full flex-col items-center justify-center gap-2 text-muted-foreground">
861
+ <IconLoader2 className="size-6 animate-spin" aria-hidden />
862
+ <span className="text-sm">{labels.loadingMessages}</span>
863
+ </div>
864
+ ) : messagesStatus === "error" ? (
865
+ <Empty className="h-full border-0">
866
+ <EmptyHeader>
867
+ <EmptyMedia variant="icon">
868
+ <IconMessages />
869
+ </EmptyMedia>
870
+ <EmptyTitle>{labels.loadMessagesErrorTitle}</EmptyTitle>
871
+ <EmptyDescription className="text-left">
872
+ {messagesError ?? labels.loadMessagesErrorFallback}
873
+ </EmptyDescription>
874
+ </EmptyHeader>
875
+ </Empty>
876
+ ) : messagesStatus === "empty" ? (
877
+ <Empty className="h-full border-0">
878
+ <EmptyHeader>
879
+ <EmptyMedia variant="icon">
880
+ <IconMessages />
881
+ </EmptyMedia>
882
+ <EmptyTitle>{labels.emptyThreadTitle}</EmptyTitle>
883
+ <EmptyDescription>
884
+ {labels.emptyThreadDescription(activeRoom.name)}
885
+ </EmptyDescription>
886
+ </EmptyHeader>
887
+ </Empty>
888
+ ) : (
889
+ <div className="flex flex-col gap-6 px-5 py-2">
890
+ {isLoadingOlder ? (
891
+ <div className="flex items-center justify-center gap-2 py-2 text-xs text-muted-foreground">
892
+ <IconLoader2
893
+ className="size-3.5 shrink-0 animate-spin"
894
+ aria-hidden
895
+ />
896
+ {labels.loadingOlderMessages}
897
+ </div>
898
+ ) : null}
899
+ {messages.map((message) => {
900
+ const mine = message.role === "me";
901
+ return (
902
+ <Message
903
+ key={message.id}
904
+ align={mine ? "end" : "start"}
905
+ >
906
+ {mine ? null : (
907
+ <MessageAvatar className="size-8 text-xs font-medium">
908
+ {message.initials}
909
+ </MessageAvatar>
910
+ )}
911
+ <MessageContent>
912
+ {mine ? null : (
913
+ <MessageHeader>{message.author}</MessageHeader>
914
+ )}
915
+ <Bubble
916
+ align={mine ? "end" : "start"}
917
+ variant={mine ? "muted" : "outline"}
918
+ >
919
+ <BubbleContent className="break-words whitespace-pre-wrap">
920
+ {renderMessageTextWithMentions(message.text)}
921
+ </BubbleContent>
922
+ </Bubble>
923
+ <MessageFooter>
924
+ {formatMessageTime(message.at)}
925
+ </MessageFooter>
926
+ </MessageContent>
927
+ </Message>
928
+ );
929
+ })}
930
+ </div>
931
+ )}
932
+ {activeRoom && typingLine ? (
933
+ <div
934
+ className="border-t border-border px-5 py-2 text-xs text-muted-foreground"
935
+ aria-live="polite"
936
+ >
937
+ {typingLine}
938
+ </div>
939
+ ) : null}
940
+ </div>
941
+
942
+ <form
943
+ ref={formRef}
944
+ onSubmit={onSubmit}
945
+ className="relative px-5 pt-2 pb-5"
946
+ >
947
+ {mentionOpen ? (
948
+ <div
949
+ role="listbox"
950
+ aria-label={labels.mentionListLabel}
951
+ className="absolute bottom-full left-5 right-5 z-50 mb-1 flex max-h-60 flex-col overflow-hidden rounded-xl border border-border bg-popover text-popover-foreground shadow-md"
952
+ >
953
+ <div className="shrink-0 border-b border-border px-2 py-1.5 text-[0.7rem] text-muted-foreground">
954
+ {mentionSeg.phase === "category" ? (
955
+ <>
956
+ <span className="font-medium text-foreground">
957
+ Tipo
958
+ </span>
959
+ {" · "}
960
+ <kbd className="rounded bg-muted px-1 font-mono text-[0.65rem]">
961
+ Tab
962
+ </kbd>
963
+ /
964
+ <kbd className="rounded bg-muted px-1 font-mono text-[0.65rem]">
965
+ ↵
966
+ </kbd>
967
+ </>
968
+ ) : (
969
+ <>
970
+ <span className="font-medium text-foreground">
971
+ {DEFAULT_MENTION_KIND_LABEL[mentionSeg.kind]}
972
+ </span>
973
+ {" · "}
974
+ <kbd className="rounded bg-muted px-1 font-mono text-[0.65rem]">
975
+ ←
976
+ </kbd>
977
+ </>
978
+ )}
979
+ </div>
980
+ <div className="min-h-0 flex-1 overflow-y-auto p-1">
981
+ {mentionCatalogLoading && mentionEntries.length === 0 ? (
982
+ <div className="flex items-center justify-center gap-2 px-2 py-6 text-sm text-muted-foreground">
983
+ <IconLoader2 className="size-4 animate-spin" />
984
+ Buscando…
985
+ </div>
986
+ ) : null}
987
+ {!mentionCatalogLoading &&
988
+ mentionEntries.length === 0 &&
989
+ mentionSeg.phase === "item" ? (
990
+ <p className="px-2 py-4 text-center text-sm text-muted-foreground">
991
+ Sin resultados
992
+ </p>
993
+ ) : null}
994
+ {mentionEntries.map((entry, index) => {
995
+ if (entry.type === "category") {
996
+ const IconComp = entry.icon;
997
+ const categoryDisabled = isMentionEntryDisabled(
998
+ entry,
999
+ mentionConfig,
1000
+ );
1001
+ return (
1002
+ <button
1003
+ key={`cat-${entry.kind}`}
1004
+ type="button"
1005
+ role="option"
1006
+ aria-selected={index === mentionHighlight}
1007
+ aria-disabled={categoryDisabled}
1008
+ disabled={categoryDisabled}
1009
+ className={cn(
1010
+ "flex w-full items-start gap-2 rounded-lg px-2 py-2 text-left text-sm",
1011
+ categoryDisabled &&
1012
+ "cursor-not-allowed opacity-50",
1013
+ !categoryDisabled &&
1014
+ (index === mentionHighlight
1015
+ ? "bg-accent text-accent-foreground"
1016
+ : "hover:bg-muted/80"),
1017
+ )}
1018
+ onMouseEnter={() => {
1019
+ if (!categoryDisabled) setMentionHighlight(index);
1020
+ }}
1021
+ onMouseDown={(event) => {
1022
+ event.preventDefault();
1023
+ if (categoryDisabled) return;
1024
+ applyCategoryPick(entry.kind);
1025
+ }}
1026
+ >
1027
+ <IconComp className="mt-0.5 size-4 shrink-0 opacity-80" />
1028
+ <span className="min-w-0 flex-1">
1029
+ <span className="block font-medium leading-tight">
1030
+ {entry.label}
1031
+ </span>
1032
+ <span className="mt-0.5 block text-xs text-muted-foreground">
1033
+ {entry.hint}
1034
+ </span>
1035
+ </span>
1036
+ </button>
1037
+ );
1038
+ }
1039
+ const item = entry.data;
1040
+ const IconComp = item.icon;
1041
+ return (
1042
+ <button
1043
+ key={item.id}
1044
+ type="button"
1045
+ role="option"
1046
+ aria-selected={index === mentionHighlight}
1047
+ className={cn(
1048
+ "flex w-full items-start gap-2 rounded-lg px-2 py-2 text-left text-sm",
1049
+ index === mentionHighlight
1050
+ ? "bg-accent text-accent-foreground"
1051
+ : "hover:bg-muted/80",
1052
+ )}
1053
+ onMouseEnter={() => setMentionHighlight(index)}
1054
+ onMouseDown={(event) => {
1055
+ event.preventDefault();
1056
+ applyItemPick(item);
1057
+ }}
1058
+ >
1059
+ <IconComp className="mt-0.5 size-4 shrink-0 opacity-80" />
1060
+ <span className="min-w-0 flex-1">
1061
+ <span className="block font-medium leading-tight">
1062
+ {item.label}
1063
+ </span>
1064
+ <span className="mt-0.5 block text-xs text-muted-foreground">
1065
+ {item.subtitle}
1066
+ </span>
1067
+ </span>
1068
+ </button>
1069
+ );
1070
+ })}
1071
+ </div>
1072
+ </div>
1073
+ ) : null}
1074
+
1075
+ <InputGroup>
1076
+ <InputGroupTextarea
1077
+ ref={textareaRef}
1078
+ value={draft}
1079
+ onChange={(event) => {
1080
+ const v = event.target.value;
1081
+ const cursor =
1082
+ event.target.selectionStart ?? v.length;
1083
+ setDraft(v);
1084
+ onDraftChange?.(v);
1085
+ syncMentionMenu(v, cursor);
1086
+ }}
1087
+ onSelect={(event) => {
1088
+ const t = event.target as HTMLTextAreaElement;
1089
+ syncMentionMenu(
1090
+ t.value,
1091
+ t.selectionStart ?? t.value.length,
1092
+ );
1093
+ }}
1094
+ placeholder={
1095
+ activeRoom
1096
+ ? labels.messagePlaceholder
1097
+ : labels.messagePlaceholderNoRoom
1098
+ }
1099
+ aria-label={labels.messageAriaLabel}
1100
+ className="min-h-14"
1101
+ disabled={!activeRoom}
1102
+ onKeyDown={(event) => {
1103
+ onUserGesture?.();
1104
+ if (mentionOpen) {
1105
+ if (event.key === "ArrowDown") {
1106
+ event.preventDefault();
1107
+ setMentionHighlight((h) =>
1108
+ stepMentionHighlight(
1109
+ mentionEntries,
1110
+ mentionConfig,
1111
+ h,
1112
+ 1,
1113
+ ),
1114
+ );
1115
+ return;
1116
+ }
1117
+ if (event.key === "ArrowUp") {
1118
+ event.preventDefault();
1119
+ setMentionHighlight((h) =>
1120
+ stepMentionHighlight(
1121
+ mentionEntries,
1122
+ mentionConfig,
1123
+ h,
1124
+ -1,
1125
+ ),
1126
+ );
1127
+ return;
1128
+ }
1129
+ if (event.key === "Backspace") {
1130
+ const seg = parseMentionSegment(
1131
+ mentionQuery,
1132
+ mentionConfig,
1133
+ );
1134
+ if (seg.phase === "item" && seg.filter === "") {
1135
+ event.preventDefault();
1136
+ replaceSlashSegment("");
1137
+ setMentionHighlight(0);
1138
+ return;
1139
+ }
1140
+ }
1141
+ if (event.key === "ArrowLeft") {
1142
+ const seg = parseMentionSegment(
1143
+ mentionQuery,
1144
+ mentionConfig,
1145
+ );
1146
+ if (seg.phase === "item" && seg.filter === "") {
1147
+ event.preventDefault();
1148
+ replaceSlashSegment("");
1149
+ setMentionHighlight(0);
1150
+ return;
1151
+ }
1152
+ }
1153
+ if (event.key === "Enter" && !event.shiftKey) {
1154
+ event.preventDefault();
1155
+ const pick = mentionEntries[mentionHighlight];
1156
+ if (!pick || isMentionEntryDisabled(pick, mentionConfig)) {
1157
+ return;
1158
+ }
1159
+ if (pick.type === "category") {
1160
+ applyCategoryPick(pick.kind);
1161
+ } else {
1162
+ applyItemPick(pick.data);
1163
+ }
1164
+ return;
1165
+ }
1166
+ if (event.key === "Tab") {
1167
+ event.preventDefault();
1168
+ const pick = mentionEntries[mentionHighlight];
1169
+ if (!pick || isMentionEntryDisabled(pick, mentionConfig)) {
1170
+ return;
1171
+ }
1172
+ if (pick.type === "category") {
1173
+ applyCategoryPick(pick.kind);
1174
+ } else {
1175
+ applyItemPick(pick.data);
1176
+ }
1177
+ return;
1178
+ }
1179
+ if (event.key === "Escape") {
1180
+ event.preventDefault();
1181
+ closeMentionMenu();
1182
+ return;
1183
+ }
1184
+ }
1185
+ if (event.key === "Enter" && !event.shiftKey) {
1186
+ event.preventDefault();
1187
+ formRef.current?.requestSubmit();
1188
+ }
1189
+ }}
1190
+ />
1191
+ <InputGroupAddon align="block-end" className="pt-1">
1192
+ <DropdownMenu>
1193
+ <DropdownMenuTrigger asChild>
1194
+ <InputGroupButton
1195
+ aria-label={labels.attachAriaLabel}
1196
+ type="button"
1197
+ size="icon-sm"
1198
+ variant="outline"
1199
+ disabled={!activeRoom}
1200
+ >
1201
+ <IconPlus className="size-4" />
1202
+ </InputGroupButton>
1203
+ </DropdownMenuTrigger>
1204
+ <DropdownMenuContent
1205
+ align="start"
1206
+ side="top"
1207
+ className="w-44"
1208
+ >
1209
+ <DropdownMenuItem>
1210
+ <IconPaperclip className="size-4" />
1211
+ {labels.attachPhotos}
1212
+ </DropdownMenuItem>
1213
+ </DropdownMenuContent>
1214
+ </DropdownMenu>
1215
+ <InputGroupButton
1216
+ type="submit"
1217
+ variant="default"
1218
+ size="icon-sm"
1219
+ disabled={!canSend || !activeRoom}
1220
+ className="ml-auto"
1221
+ >
1222
+ <IconArrowUp className="size-4" />
1223
+ <span className="sr-only">{labels.sendSrOnly}</span>
1224
+ </InputGroupButton>
1225
+ </InputGroupAddon>
1226
+ </InputGroup>
1227
+ </form>
1228
+ </div>
1229
+ </div>
1230
+ </DrawerContent>
1231
+ </Drawer>
1232
+ </>
1233
+ );
1234
+ }
1235
+
1236
+ export {
1237
+ InternalChatPanel,
1238
+ DEFAULT_MENTION_CONFIG,
1239
+ DEFAULT_LABELS as DEFAULT_INTERNAL_CHAT_PANEL_LABELS,
1240
+ };
1241
+
1242
+ export { initialsFromDisplayName } from "./internal-chat-mention";
1243
+
1244
+ export type {
1245
+ BuildMentionListOptions,
1246
+ InternalChatMentionCatalogState,
1247
+ InternalChatMentionConfig,
1248
+ InternalChatMentionItem,
1249
+ InternalChatMentionKind,
1250
+ } from "./internal-chat-mention";