@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.
- package/package.json +1 -1
- package/registry/traky/json/internal-chat-mention.json +17 -0
- package/registry/traky/json/internal-chat-panel.json +31 -0
- package/registry/traky/registry.json +20 -0
- package/registry/traky/ui/internal-chat-mention.ts +233 -0
- package/registry/traky/ui/internal-chat-panel.tsx +1250 -0
- package/src/ui/internal-chat-mention.ts +233 -0
- package/src/ui/internal-chat-panel.tsx +1250 -0
package/package.json
CHANGED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
|
+
"name": "internal-chat-mention",
|
|
4
|
+
"type": "registry:ui",
|
|
5
|
+
"author": "Traky (https://traky.app)",
|
|
6
|
+
"dependencies": [
|
|
7
|
+
"@tabler/icons-react"
|
|
8
|
+
],
|
|
9
|
+
"files": [
|
|
10
|
+
{
|
|
11
|
+
"path": "ui/internal-chat-mention.ts",
|
|
12
|
+
"content": "import type { Icon } from \"@tabler/icons-react\";\n\nexport type InternalChatMentionKind = \"guide\" | \"package\" | \"ai\";\n\nexport type InternalChatMentionItem = {\n id: string;\n kind: InternalChatMentionKind;\n label: string;\n subtitle: string;\n insertLabel: string;\n icon: Icon;\n};\n\nexport type InternalChatMentionCategoryMeta = {\n label: string;\n hint: string;\n keywords: string[];\n /** Visible en el menú de tipo pero no seleccionable (p. ej. próximamente). */\n disabled?: boolean;\n};\n\nexport type InternalChatMentionListEntry =\n | {\n type: \"category\";\n kind: InternalChatMentionKind;\n label: string;\n hint: string;\n icon: Icon;\n disabled?: boolean;\n }\n | { type: \"item\"; data: InternalChatMentionItem };\n\nexport type InternalChatMentionCatalogState = {\n open: boolean;\n phase: \"category\" | \"item\";\n kind?: InternalChatMentionKind;\n filter: string;\n};\n\nexport type BuildMentionListOptions = {\n /** Si true, los ítems ya vienen filtrados del servidor (sin filtro local por texto). */\n serverFilteredItems?: boolean;\n};\n\nexport const DEFAULT_MENTION_KIND_ORDER: InternalChatMentionKind[] = [\n \"guide\",\n \"package\",\n \"ai\",\n];\n\nexport const DEFAULT_MENTION_KIND_LABEL: Record<\n InternalChatMentionKind,\n string\n> = {\n guide: \"Guías\",\n package: \"Paquetes\",\n ai: \"Asistencia de IA\",\n};\n\nexport type InternalChatMentionConfig = {\n kindOrder: InternalChatMentionKind[];\n categoryMeta: Record<\n InternalChatMentionKind,\n InternalChatMentionCategoryMeta\n >;\n kindIcons: Record<InternalChatMentionKind, Icon>;\n kindAliases?: Record<string, InternalChatMentionKind>;\n};\n\nfunction resolveKindAlias(\n raw: string,\n config: InternalChatMentionConfig,\n): InternalChatMentionKind | null {\n const s = raw.trim().toLowerCase();\n if (!s) return null;\n\n const aliases: Record<string, InternalChatMentionKind> = {\n guide: \"guide\",\n guía: \"guide\",\n guia: \"guide\",\n paquete: \"package\",\n paquetes: \"package\",\n package: \"package\",\n ia: \"ai\",\n ai: \"ai\",\n asistencia: \"ai\",\n ...config.kindAliases,\n };\n\n const direct = aliases[s];\n if (direct) return direct;\n\n for (const kind of config.kindOrder) {\n const meta = config.categoryMeta[kind];\n if (kind === s) return kind;\n if (meta.label.toLowerCase() === s) return kind;\n if (meta.keywords.some((k) => k === s)) return kind;\n }\n\n return null;\n}\n\nexport function parseMentionSegment(\n query: string,\n config: InternalChatMentionConfig,\n):\n | { phase: \"category\"; filter: string }\n | { phase: \"item\"; kind: InternalChatMentionKind; filter: string } {\n const colon = query.indexOf(\":\");\n if (colon === -1) {\n return { phase: \"category\", filter: query };\n }\n const head = query.slice(0, colon).trim().toLowerCase();\n const tail = query.slice(colon + 1);\n if (head === \"\") {\n return { phase: \"category\", filter: query.replace(\":\", \"\") };\n }\n const kind = resolveKindAlias(head, config);\n if (!kind) {\n return { phase: \"category\", filter: query };\n }\n return { phase: \"item\", kind, filter: tail };\n}\n\nexport function parseSlashMention(\n draft: string,\n cursor: number,\n): { start: number; query: string } | null {\n const before = draft.slice(0, cursor);\n const lastSlash = before.lastIndexOf(\"/\");\n if (lastSlash === -1) return null;\n const charBefore = lastSlash === 0 ? \" \" : draft[lastSlash - 1];\n if (charBefore !== \" \" && charBefore !== \"\\n\" && lastSlash !== 0) {\n return null;\n }\n const afterSlash = before.slice(lastSlash + 1);\n if (afterSlash.includes(\"\\n\")) return null;\n return { start: lastSlash, query: afterSlash };\n}\n\nfunction filterCategoryEntries(\n filterText: string,\n config: InternalChatMentionConfig,\n): InternalChatMentionListEntry[] {\n const q = filterText.trim().toLowerCase();\n const rows: InternalChatMentionListEntry[] = config.kindOrder.map((kind) => ({\n type: \"category\",\n kind,\n label: config.categoryMeta[kind].label,\n hint: config.categoryMeta[kind].hint,\n icon: config.kindIcons[kind],\n disabled: config.categoryMeta[kind].disabled,\n }));\n if (!q) return rows;\n const byAlias = resolveKindAlias(q, config);\n return rows.filter((row) => {\n if (row.type !== \"category\") return false;\n if (byAlias && row.kind === byAlias) return true;\n return (\n row.label.toLowerCase().includes(q) ||\n row.hint.toLowerCase().includes(q) ||\n config.categoryMeta[row.kind].keywords.some(\n (k) => k.includes(q) || q.includes(k),\n )\n );\n });\n}\n\nfunction filterItemsByKind(\n kind: InternalChatMentionKind,\n filterText: string,\n catalog: InternalChatMentionItem[],\n skipTextFilter = false,\n): InternalChatMentionListEntry[] {\n const q = filterText.trim().toLowerCase();\n let items = catalog.filter((i) => i.kind === kind);\n if (!skipTextFilter && q) {\n items = items.filter(\n (item) =>\n item.label.toLowerCase().includes(q) ||\n item.subtitle.toLowerCase().includes(q) ||\n item.insertLabel.toLowerCase().includes(q),\n );\n }\n return items.map((data) => ({ type: \"item\", data }));\n}\n\nexport function buildMentionList(\n query: string,\n guideItems: InternalChatMentionItem[],\n packageItems: InternalChatMentionItem[],\n config: InternalChatMentionConfig,\n options?: BuildMentionListOptions,\n): InternalChatMentionListEntry[] {\n const seg = parseMentionSegment(query, config);\n if (seg.phase === \"category\") {\n return filterCategoryEntries(seg.filter, config);\n }\n if (seg.kind === \"ai\" || config.categoryMeta[seg.kind]?.disabled) {\n return [];\n }\n const pool = seg.kind === \"guide\" ? guideItems : packageItems;\n return filterItemsByKind(\n seg.kind,\n seg.filter,\n pool,\n Boolean(options?.serverFilteredItems),\n );\n}\n\nexport function roomInitialLetter(name: string): string {\n const t = name.trim();\n if (!t) return \"?\";\n const ch = [...t][0];\n return ch && /\\p{L}/u.test(ch) ? ch.toUpperCase() : \"?\";\n}\n\nexport function initialsFromDisplayName(name: string): string {\n const t = name.trim();\n if (!t) return \"?\";\n const parts = t.split(/\\s+/).filter(Boolean);\n if (parts.length === 0) return \"?\";\n if (parts.length === 1) return parts[0]!.slice(0, 2).toUpperCase();\n return `${parts[0]![0]!}${parts[parts.length - 1]![0]!}`.toUpperCase();\n}\n\nexport function formatMessageTime(iso: string, locale = \"es\"): string {\n return new Intl.DateTimeFormat(locale, {\n hour: \"2-digit\",\n minute: \"2-digit\",\n hour12: false,\n }).format(new Date(iso));\n}\n",
|
|
13
|
+
"type": "registry:ui",
|
|
14
|
+
"target": ""
|
|
15
|
+
}
|
|
16
|
+
]
|
|
17
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
|
+
"name": "internal-chat-panel",
|
|
4
|
+
"type": "registry:ui",
|
|
5
|
+
"author": "Traky (https://traky.app)",
|
|
6
|
+
"dependencies": [
|
|
7
|
+
"@tabler/icons-react"
|
|
8
|
+
],
|
|
9
|
+
"registryDependencies": [
|
|
10
|
+
"alert-dialog",
|
|
11
|
+
"bubble",
|
|
12
|
+
"button",
|
|
13
|
+
"dialog",
|
|
14
|
+
"drawer",
|
|
15
|
+
"dropdown-menu",
|
|
16
|
+
"empty",
|
|
17
|
+
"input",
|
|
18
|
+
"input-group",
|
|
19
|
+
"internal-chat-mention",
|
|
20
|
+
"message",
|
|
21
|
+
"tooltip"
|
|
22
|
+
],
|
|
23
|
+
"files": [
|
|
24
|
+
{
|
|
25
|
+
"path": "ui/internal-chat-panel.tsx",
|
|
26
|
+
"content": "\"use client\";\n\nimport {\n IconArrowUp,\n IconDotsVertical,\n IconLoader2,\n IconMessages,\n IconPackage,\n IconPaperclip,\n IconPlus,\n IconSparkles,\n IconTrash,\n IconTruckLoading,\n IconX,\n type Icon,\n} from \"@tabler/icons-react\";\nimport {\n useCallback,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n type FormEvent,\n type ReactNode,\n} from \"react\";\nimport {\n AlertDialog,\n AlertDialogAction,\n AlertDialogCancel,\n AlertDialogContent,\n AlertDialogDescription,\n AlertDialogFooter,\n AlertDialogHeader,\n AlertDialogTitle,\n} from \"@/components/ui/alert-dialog\";\nimport { Bubble, BubbleContent } from \"@/components/ui/bubble\";\nimport { Button } from \"@/components/ui/button\";\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n} from \"@/components/ui/dialog\";\nimport {\n Drawer,\n DrawerClose,\n DrawerContent,\n DrawerDescription,\n DrawerTitle,\n} from \"@/components/ui/drawer\";\nimport {\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n} from \"@/components/ui/dropdown-menu\";\nimport {\n Empty,\n EmptyDescription,\n EmptyHeader,\n EmptyMedia,\n EmptyTitle,\n} from \"@/components/ui/empty\";\nimport {\n InputGroup,\n InputGroupAddon,\n InputGroupButton,\n InputGroupTextarea,\n} from \"@/components/ui/input-group\";\nimport { Input } from \"@/components/ui/input\";\nimport {\n Message,\n MessageAvatar,\n MessageContent,\n MessageFooter,\n MessageHeader,\n} from \"@/components/ui/message\";\nimport {\n Tooltip,\n TooltipContent,\n TooltipTrigger,\n} from \"@/components/ui/tooltip\";\nimport { cn } from \"@/lib/utils\";\nimport {\n buildMentionList,\n DEFAULT_MENTION_KIND_LABEL,\n DEFAULT_MENTION_KIND_ORDER,\n formatMessageTime,\n parseMentionSegment,\n parseSlashMention,\n roomInitialLetter,\n type BuildMentionListOptions,\n type InternalChatMentionCatalogState,\n type InternalChatMentionConfig,\n type InternalChatMentionItem,\n type InternalChatMentionKind,\n type InternalChatMentionListEntry,\n} from \"@/components/ui/internal-chat-mention\";\n\nexport type InternalChatRoom = {\n id: string;\n name: string;\n isOrganization?: boolean;\n};\n\nexport type InternalChatMessageLine = {\n id: string;\n role: \"me\" | \"team\";\n author: string;\n initials: string;\n text: string;\n at: string;\n};\n\nexport type InternalChatMessagesStatus =\n | \"idle\"\n | \"loading\"\n | \"error\"\n | \"empty\"\n | \"ready\";\n\nexport type InternalChatPanelLabels = {\n openChat: string;\n newRoom: string;\n roomMenu: string;\n deleteRoom: string;\n closeChat: string;\n newRoomTitle: string;\n newRoomDescription: string;\n newRoomPlaceholder: string;\n cancel: string;\n create: string;\n deleteRoomTitle: string;\n deleteRoomDescription: (roomName: string) => string;\n deleteConfirm: string;\n noRoomTitle: string;\n noRoomDescription: string;\n loadingMessages: string;\n loadMessagesErrorTitle: string;\n loadMessagesErrorFallback: string;\n emptyThreadTitle: string;\n emptyThreadDescription: (roomName: string) => string;\n loadingOlderMessages: string;\n mentionListLabel: string;\n messagePlaceholder: string;\n messagePlaceholderNoRoom: string;\n messageAriaLabel: string;\n attachAriaLabel: string;\n attachPhotos: string;\n sendSrOnly: string;\n orgRoomSuffix: string;\n orgRoomTooltip: string;\n slashMentionHint: string;\n selectRoomHint: string;\n};\n\nconst DEFAULT_LABELS: InternalChatPanelLabels = {\n openChat: \"Abrir chat de la empresa\",\n newRoom: \"Nueva sala\",\n roomMenu: \"Más acciones de salas\",\n deleteRoom: \"Eliminar sala actual\",\n closeChat: \"Cerrar chat\",\n newRoomTitle: \"Nueva sala\",\n newRoomDescription:\n \"Crea un espacio para conversar con tu equipo en tiempo real.\",\n newRoomPlaceholder: \"Nombre de la sala\",\n cancel: \"Cancelar\",\n create: \"Crear\",\n deleteRoomTitle: \"¿Eliminar esta sala?\",\n deleteRoomDescription: (roomName) =>\n `Se borrarán los mensajes de «${roomName}» en el servidor. Esta acción no se puede deshacer.`,\n deleteConfirm: \"Eliminar\",\n noRoomTitle: \"Sin sala\",\n noRoomDescription: \"Crea una sala con el botón + a la izquierda.\",\n loadingMessages: \"Cargando mensajes…\",\n loadMessagesErrorTitle: \"No se pudieron cargar los mensajes\",\n loadMessagesErrorFallback:\n \"Revisa que la API esté en marcha y que el módulo de chat interno esté migrado.\",\n emptyThreadTitle: \"¿De qué hablamos?\",\n emptyThreadDescription: (roomName) =>\n `Escribe el primer mensaje en «${roomName}».`,\n loadingOlderMessages: \"Cargando mensajes anteriores…\",\n mentionListLabel: \"Insertar mención\",\n messagePlaceholder: \"Mensaje… · / comandos\",\n messagePlaceholderNoRoom: \"Selecciona una sala…\",\n messageAriaLabel: \"Mensaje\",\n attachAriaLabel: \"Adjuntar\",\n attachPhotos: \"Fotos y archivos\",\n sendSrOnly: \"Enviar\",\n orgRoomSuffix: \" · Sala de toda la organización\",\n orgRoomTooltip: \" — toda la organización (no se elimina)\",\n slashMentionHint: \"menciones (guías y paquetes)\",\n selectRoomHint: \"Selecciona una sala o crea una nueva.\",\n};\n\nconst DEFAULT_MENTION_CONFIG: InternalChatMentionConfig = {\n kindOrder: DEFAULT_MENTION_KIND_ORDER,\n kindIcons: {\n guide: IconTruckLoading,\n package: IconPackage,\n ai: IconSparkles,\n },\n categoryMeta: {\n guide: {\n label: \"Guía\",\n hint: \"Guías de envío\",\n keywords: [\"guía\", \"guia\", \"guide\", \"envío\", \"envio\"],\n },\n package: {\n label: \"Paquete\",\n hint: \"Paquetes de la empresa (WR / tracking)\",\n keywords: [\"paquete\", \"paquetes\", \"package\", \"trk\", \"wr\"],\n },\n ai: {\n label: \"Asistencia de IA\",\n hint: \"Consultas sobre operación y datos (próximamente)\",\n keywords: [\"ia\", \"ai\", \"asistencia\", \"inteligencia\", \"asistente\"],\n disabled: true,\n },\n },\n};\n\nfunction isMentionEntryDisabled(\n entry: InternalChatMentionListEntry,\n config: InternalChatMentionConfig,\n): boolean {\n if (entry.type !== \"category\") return false;\n return Boolean(\n entry.disabled ?? config.categoryMeta[entry.kind]?.disabled,\n );\n}\n\nfunction stepMentionHighlight(\n entries: InternalChatMentionListEntry[],\n config: InternalChatMentionConfig,\n current: number,\n delta: 1 | -1,\n): number {\n if (entries.length === 0) return 0;\n let next = current;\n for (let i = 0; i < entries.length; i++) {\n next = (next + delta + entries.length) % entries.length;\n if (!isMentionEntryDisabled(entries[next]!, config)) return next;\n }\n return current;\n}\n\nfunction renderMessageTextWithMentions(text: string): ReactNode {\n const parts = text.split(/(@\\[[^\\]]+\\])/g);\n return parts.map((part, index) => {\n const mention = /^@\\[(.+)\\]$/.exec(part);\n if (mention) {\n return (\n <span\n key={index}\n 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\"\n >\n {mention[1]}\n </span>\n );\n }\n return <span key={index}>{part}</span>;\n });\n}\n\nexport type InternalChatPanelProps = {\n title: string;\n rooms: InternalChatRoom[];\n activeRoomId: string | null;\n onActiveRoomChange: (roomId: string) => void;\n messages: InternalChatMessageLine[];\n messagesStatus: InternalChatMessagesStatus;\n messagesError?: string | null;\n onLoadOlderMessages?: () => void | Promise<void>;\n isLoadingOlder?: boolean;\n hasOlderMessages?: boolean;\n mentionGuideItems?: InternalChatMentionItem[];\n mentionPackageItems?: InternalChatMentionItem[];\n mentionConfig?: InternalChatMentionConfig;\n /** Catálogo de ítems ya filtrado en servidor (guías/paquetes). */\n mentionServerFilteredItems?: boolean;\n mentionCatalogLoading?: boolean;\n onMentionCatalogChange?: (state: InternalChatMentionCatalogState) => void;\n typingLine?: string | null;\n onSendMessage: (text: string) => void | Promise<void>;\n onCreateRoom: (name: string) => void | Promise<void>;\n onDeleteRoom: (roomId: string) => void | Promise<void>;\n onOpenChange?: (open: boolean) => void;\n onDraftChange?: (draft: string) => void;\n onUserGesture?: () => void;\n isSending?: boolean;\n isCreatingRoom?: boolean;\n isDeletingRoom?: boolean;\n onDeleteRoomBlocked?: (reason: string) => void;\n labels?: Partial<InternalChatPanelLabels>;\n className?: string;\n};\n\nfunction InternalChatPanel({\n title,\n rooms,\n activeRoomId,\n onActiveRoomChange,\n messages,\n messagesStatus,\n messagesError = null,\n onLoadOlderMessages,\n isLoadingOlder = false,\n hasOlderMessages = false,\n mentionGuideItems = [],\n mentionPackageItems = [],\n mentionConfig = DEFAULT_MENTION_CONFIG,\n mentionServerFilteredItems = false,\n mentionCatalogLoading = false,\n onMentionCatalogChange,\n typingLine = null,\n onSendMessage,\n onCreateRoom,\n onDeleteRoom,\n onOpenChange,\n onDraftChange,\n onUserGesture,\n isSending = false,\n isCreatingRoom = false,\n isDeletingRoom = false,\n onDeleteRoomBlocked,\n labels: labelsPartial,\n className,\n}: InternalChatPanelProps) {\n const labels = { ...DEFAULT_LABELS, ...labelsPartial };\n\n const [open, setOpen] = useState(false);\n const [draft, setDraft] = useState(\"\");\n const [createOpen, setCreateOpen] = useState(false);\n const [newRoomName, setNewRoomName] = useState(\"\");\n const [deleteOpen, setDeleteOpen] = useState(false);\n const [mentionStart, setMentionStart] = useState<number | null>(null);\n const [mentionQuery, setMentionQuery] = useState(\"\");\n const [mentionHighlight, setMentionHighlight] = useState(0);\n const lastMentionQueryRef = useRef(\"\");\n const loadingOlderMessagesRef = useRef(false);\n\n const formRef = useRef<HTMLFormElement>(null);\n const scrollerRef = useRef<HTMLDivElement>(null);\n const textareaRef = useRef<HTMLTextAreaElement>(null);\n\n const activeRoom = useMemo(\n () => rooms.find((r) => r.id === activeRoomId) ?? null,\n [rooms, activeRoomId],\n );\n\n const mentionListOptions = useMemo((): BuildMentionListOptions | undefined => {\n if (!mentionServerFilteredItems) return undefined;\n const seg = parseMentionSegment(mentionQuery, mentionConfig);\n if (seg.phase !== \"item\") return undefined;\n return { serverFilteredItems: true };\n }, [mentionServerFilteredItems, mentionQuery, mentionConfig]);\n\n const mentionEntries = useMemo(\n () =>\n buildMentionList(\n mentionQuery,\n mentionGuideItems,\n mentionPackageItems,\n mentionConfig,\n mentionListOptions,\n ),\n [\n mentionQuery,\n mentionGuideItems,\n mentionPackageItems,\n mentionConfig,\n mentionListOptions,\n ],\n );\n\n const mentionSeg = useMemo(\n () => parseMentionSegment(mentionQuery, mentionConfig),\n [mentionQuery, mentionConfig],\n );\n\n const mentionOpen =\n Boolean(activeRoom) &&\n mentionStart !== null &&\n (mentionEntries.length > 0 ||\n mentionCatalogLoading ||\n (mentionServerFilteredItems && mentionSeg.phase === \"item\"));\n\n const canSend =\n draft.trim().length > 0 &&\n !isSending &&\n Boolean(activeRoomId);\n\n const setOpenWithNotify = useCallback(\n (next: boolean) => {\n if (next) onUserGesture?.();\n setOpen(next);\n onOpenChange?.(next);\n },\n [onOpenChange, onUserGesture],\n );\n\n const handleMessagesScroll = useCallback(() => {\n const node = scrollerRef.current;\n if (!node || !activeRoomId || !onLoadOlderMessages) return;\n if (loadingOlderMessagesRef.current) return;\n if (node.scrollTop > 120) return;\n if (!hasOlderMessages || isLoadingOlder) return;\n loadingOlderMessagesRef.current = true;\n const prevHeight = node.scrollHeight;\n const prevTop = node.scrollTop;\n void Promise.resolve(onLoadOlderMessages()).finally(() => {\n loadingOlderMessagesRef.current = false;\n requestAnimationFrame(() => {\n const n = scrollerRef.current;\n if (!n) return;\n const delta = n.scrollHeight - prevHeight;\n n.scrollTop = prevTop + delta;\n });\n });\n }, [\n activeRoomId,\n hasOlderMessages,\n isLoadingOlder,\n onLoadOlderMessages,\n ]);\n\n useLayoutEffect(() => {\n if (!open) return;\n const scrollToEnd = () => {\n const node = scrollerRef.current;\n if (!node) return;\n node.scrollTop = node.scrollHeight;\n };\n scrollToEnd();\n let rafNested = 0;\n const rafOuter = requestAnimationFrame(() => {\n scrollToEnd();\n rafNested = requestAnimationFrame(scrollToEnd);\n });\n const timeouts = [0, 50, 150].map((ms) =>\n window.setTimeout(scrollToEnd, ms),\n );\n return () => {\n cancelAnimationFrame(rafOuter);\n if (rafNested) cancelAnimationFrame(rafNested);\n timeouts.forEach(clearTimeout);\n };\n }, [open, activeRoomId, messages.length]);\n\n useEffect(() => {\n if (!mentionOpen || mentionEntries.length === 0) return;\n setMentionHighlight((h) => Math.min(h, mentionEntries.length - 1));\n }, [mentionOpen, mentionEntries.length]);\n\n useEffect(() => {\n setMentionStart(null);\n setMentionQuery(\"\");\n lastMentionQueryRef.current = \"\";\n }, [activeRoomId]);\n\n useEffect(() => {\n if (!onMentionCatalogChange) return;\n if (mentionStart === null) {\n onMentionCatalogChange({\n open: false,\n phase: \"category\",\n filter: \"\",\n });\n return;\n }\n if (mentionSeg.phase === \"category\") {\n onMentionCatalogChange({\n open: true,\n phase: \"category\",\n filter: mentionSeg.filter,\n });\n return;\n }\n onMentionCatalogChange({\n open: true,\n phase: \"item\",\n kind: mentionSeg.kind,\n filter: mentionSeg.filter,\n });\n }, [mentionStart, mentionQuery, mentionConfig, onMentionCatalogChange]);\n\n function closeMentionMenu() {\n setMentionStart(null);\n setMentionQuery(\"\");\n lastMentionQueryRef.current = \"\";\n }\n\n function syncMentionMenu(nextDraft: string, cursor: number) {\n const m = parseSlashMention(nextDraft, cursor);\n if (!m) {\n closeMentionMenu();\n return;\n }\n const seg = parseMentionSegment(m.query, mentionConfig);\n const listOptions: BuildMentionListOptions | undefined =\n mentionServerFilteredItems && seg.phase === \"item\"\n ? { serverFilteredItems: true }\n : undefined;\n const entries = buildMentionList(\n m.query,\n mentionGuideItems,\n mentionPackageItems,\n mentionConfig,\n listOptions,\n );\n const keepOpenOnEmpty =\n mentionCatalogLoading ||\n (mentionServerFilteredItems && seg.phase === \"item\");\n if (entries.length === 0 && !keepOpenOnEmpty) {\n closeMentionMenu();\n return;\n }\n if (m.query !== lastMentionQueryRef.current) {\n setMentionHighlight(0);\n lastMentionQueryRef.current = m.query;\n }\n setMentionStart(m.start);\n setMentionQuery(m.query);\n }\n\n function replaceSlashSegment(newSegment: string) {\n const el = textareaRef.current;\n if (el === null || mentionStart === null) return;\n const cursor = el.selectionStart ?? draft.length;\n const before = draft.slice(0, mentionStart);\n const after = draft.slice(cursor);\n const newDraft = `${before}/${newSegment}${after}`;\n const slashEnd = before.length + 1 + newSegment.length;\n setDraft(newDraft);\n onDraftChange?.(newDraft);\n setMentionQuery(newSegment);\n lastMentionQueryRef.current = newSegment;\n requestAnimationFrame(() => {\n el.focus();\n el.setSelectionRange(slashEnd, slashEnd);\n });\n }\n\n function applyCategoryPick(kind: InternalChatMentionKind) {\n if (mentionConfig.categoryMeta[kind]?.disabled) return;\n replaceSlashSegment(`${kind}:`);\n setMentionHighlight(0);\n }\n\n function applyItemPick(item: InternalChatMentionItem) {\n const el = textareaRef.current;\n if (el === null || mentionStart === null) return;\n const cursor = el.selectionStart ?? draft.length;\n const before = draft.slice(0, mentionStart);\n const after = draft.slice(cursor);\n const token = `@[${item.insertLabel}]`;\n const needsSpace =\n after.length > 0 && !/^\\s/.test(after) && !after.startsWith(\"\\n\");\n const newDraft = `${before}${token}${needsSpace ? \" \" : \"\"}${after}`;\n setDraft(newDraft);\n onDraftChange?.(newDraft);\n closeMentionMenu();\n const newPos = before.length + token.length + (needsSpace ? 1 : 0);\n requestAnimationFrame(() => {\n el.focus();\n el.setSelectionRange(newPos, newPos);\n });\n }\n\n async function onSubmit(event: FormEvent<HTMLFormElement>) {\n event.preventDefault();\n if (mentionOpen) return;\n const text = draft.trim();\n if (!text || !activeRoomId) return;\n onUserGesture?.();\n try {\n await onSendMessage(text);\n setDraft(\"\");\n onDraftChange?.(\"\");\n } catch {\n /* errores vía contenedor */\n }\n }\n\n async function handleCreateRoom() {\n const name = newRoomName.trim();\n if (!name) return;\n try {\n await onCreateRoom(name);\n setNewRoomName(\"\");\n setCreateOpen(false);\n } catch {\n /* contenedor */\n }\n }\n\n async function handleConfirmDeleteRoom() {\n if (!activeRoom) return;\n try {\n await onDeleteRoom(activeRoom.id);\n setDeleteOpen(false);\n } catch {\n /* contenedor */\n }\n }\n\n function requestDeleteRoom() {\n if (!activeRoom) return;\n if (activeRoom.isOrganization) {\n onDeleteRoomBlocked?.(\"La sala Organización no se puede eliminar.\");\n return;\n }\n if (rooms.length <= 1) {\n onDeleteRoomBlocked?.(\"Debe existir al menos una sala.\");\n return;\n }\n setDeleteOpen(true);\n }\n\n return (\n <>\n <Button\n type=\"button\"\n size=\"icon\"\n className={cn(\"relative size-9 text-primary-foreground\", className)}\n aria-label={labels.openChat}\n onClick={() => setOpenWithNotify(true)}\n >\n <IconMessages className=\"size-4\" />\n </Button>\n\n <Dialog open={createOpen} onOpenChange={setCreateOpen}>\n <DialogContent className=\"sm:max-w-md\">\n <DialogHeader>\n <DialogTitle>{labels.newRoomTitle}</DialogTitle>\n <DialogDescription>{labels.newRoomDescription}</DialogDescription>\n </DialogHeader>\n <Input\n value={newRoomName}\n onChange={(e) => setNewRoomName(e.target.value)}\n placeholder={labels.newRoomPlaceholder}\n autoFocus\n onKeyDown={(e) => {\n if (e.key === \"Enter\") {\n e.preventDefault();\n void handleCreateRoom();\n }\n }}\n />\n <DialogFooter className=\"gap-2 sm:gap-0\">\n <Button\n type=\"button\"\n variant=\"outline\"\n onClick={() => {\n setCreateOpen(false);\n setNewRoomName(\"\");\n }}\n >\n {labels.cancel}\n </Button>\n <Button\n type=\"button\"\n onClick={() => void handleCreateRoom()}\n disabled={isCreatingRoom}\n >\n {labels.create}\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n\n <AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>\n <AlertDialogContent>\n <AlertDialogHeader>\n <AlertDialogTitle>{labels.deleteRoomTitle}</AlertDialogTitle>\n <AlertDialogDescription>\n {labels.deleteRoomDescription(activeRoom?.name ?? \"la sala\")}\n </AlertDialogDescription>\n </AlertDialogHeader>\n <AlertDialogFooter>\n <AlertDialogCancel>{labels.cancel}</AlertDialogCancel>\n <AlertDialogAction\n className=\"bg-destructive text-destructive-foreground hover:bg-destructive/90\"\n onClick={() => void handleConfirmDeleteRoom()}\n disabled={isDeletingRoom}\n >\n {labels.deleteConfirm}\n </AlertDialogAction>\n </AlertDialogFooter>\n </AlertDialogContent>\n </AlertDialog>\n\n <Drawer\n open={open}\n onOpenChange={setOpenWithNotify}\n direction=\"right\"\n shouldScaleBackground={false}\n >\n <DrawerContent\n className={cn(\n \"gap-0 overflow-hidden p-0 shadow-xl\",\n \"data-[vaul-drawer-direction=right]:inset-y-3\",\n \"data-[vaul-drawer-direction=right]:right-3\",\n \"data-[vaul-drawer-direction=right]:left-auto\",\n \"data-[vaul-drawer-direction=right]:h-[calc(100%-1.5rem)]\",\n \"data-[vaul-drawer-direction=right]:max-h-[calc(100%-1.5rem)]\",\n \"data-[vaul-drawer-direction=right]:w-[min(36rem,calc(100vw-1.5rem))]\",\n \"data-[vaul-drawer-direction=right]:max-w-[min(36rem,calc(100vw-1.5rem))]\",\n \"data-[vaul-drawer-direction=right]:sm:max-w-[min(36rem,calc(100vw-1.5rem))]\",\n \"data-[vaul-drawer-direction=right]:rounded-2xl\",\n \"data-[vaul-drawer-direction=right]:border\",\n )}\n >\n <div className=\"flex h-full min-h-0 flex-row\">\n <div className=\"flex w-[3.25rem] shrink-0 flex-col items-center gap-2 border-r border-border py-4\">\n <Tooltip delayDuration={300}>\n <TooltipTrigger asChild>\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon\"\n className=\"size-9 shrink-0 rounded-full\"\n aria-label={labels.newRoom}\n onClick={() => setCreateOpen(true)}\n >\n <IconPlus className=\"size-4\" />\n </Button>\n </TooltipTrigger>\n <TooltipContent side=\"left\">{labels.newRoom}</TooltipContent>\n </Tooltip>\n\n <div className=\"flex min-h-0 flex-1 flex-col items-center gap-2 overflow-y-auto px-1 py-1\">\n {rooms.map((room) => {\n const selected = room.id === activeRoomId;\n return (\n <Tooltip key={room.id} delayDuration={300}>\n <TooltipTrigger asChild>\n <button\n type=\"button\"\n onClick={() => onActiveRoomChange(room.id)}\n className={cn(\n \"relative flex size-9 shrink-0 items-center justify-center rounded-full border-2 transition-colors\",\n selected\n ? \"border-primary bg-primary/15\"\n : \"border-transparent bg-muted hover:bg-muted/80\",\n )}\n aria-label={`Sala ${room.name}${room.isOrganization ? \" (toda la organización)\" : \"\"}`}\n aria-current={selected ? \"true\" : undefined}\n >\n <span className=\"text-xs font-semibold leading-none\">\n {roomInitialLetter(room.name)}\n </span>\n </button>\n </TooltipTrigger>\n <TooltipContent side=\"left\">\n {room.isOrganization\n ? `${room.name}${labels.orgRoomTooltip}`\n : room.name}\n </TooltipContent>\n </Tooltip>\n );\n })}\n </div>\n\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon\"\n className=\"size-9 shrink-0 rounded-full\"\n aria-label={labels.roomMenu}\n >\n <IconDotsVertical className=\"size-4\" />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent side=\"left\" align=\"end\" className=\"w-48\">\n <DropdownMenuItem onClick={() => setCreateOpen(true)}>\n <IconPlus className=\"size-4\" />\n {labels.newRoom}\n </DropdownMenuItem>\n <DropdownMenuSeparator />\n <DropdownMenuItem\n disabled={\n rooms.length <= 1 || activeRoom?.isOrganization\n }\n className=\"text-destructive focus:text-destructive\"\n onClick={requestDeleteRoom}\n >\n <IconTrash className=\"size-4\" />\n {labels.deleteRoom}\n </DropdownMenuItem>\n </DropdownMenuContent>\n </DropdownMenu>\n </div>\n\n <div className=\"flex min-h-0 min-w-0 flex-1 flex-col\">\n <div className=\"flex items-start justify-between gap-4 px-5 pt-5 pb-3\">\n <div className=\"flex min-w-0 flex-col gap-1\">\n <DrawerTitle className=\"flex items-center gap-2 font-medium\">\n <IconMessages className=\"size-5 shrink-0\" aria-hidden />\n <span className=\"min-w-0 truncate\">{title}</span>\n </DrawerTitle>\n <DrawerDescription className=\"line-clamp-2\">\n {activeRoom ? (\n <>\n <span className=\"font-medium text-foreground\">\n {activeRoom.name}\n </span>\n {activeRoom.isOrganization ? (\n <>{labels.orgRoomSuffix}</>\n ) : null}\n {\" · \"}\n <kbd className=\"pointer-events-none rounded border bg-muted px-0.5 font-mono text-[0.65rem]\">\n /\n </kbd>{\" \"}\n {labels.slashMentionHint}\n </>\n ) : (\n labels.selectRoomHint\n )}\n </DrawerDescription>\n </div>\n <DrawerClose asChild>\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"icon\"\n className=\"size-8 shrink-0\"\n aria-label={labels.closeChat}\n >\n <IconX className=\"size-4\" />\n </Button>\n </DrawerClose>\n </div>\n\n <div\n ref={scrollerRef}\n className=\"min-h-0 flex-1 overflow-y-auto\"\n onScroll={handleMessagesScroll}\n >\n {!activeRoom ? (\n <Empty className=\"h-full border-0\">\n <EmptyHeader>\n <EmptyMedia variant=\"icon\">\n <IconMessages />\n </EmptyMedia>\n <EmptyTitle>{labels.noRoomTitle}</EmptyTitle>\n <EmptyDescription>\n {labels.noRoomDescription}\n </EmptyDescription>\n </EmptyHeader>\n </Empty>\n ) : messagesStatus === \"loading\" ? (\n <div className=\"flex h-full flex-col items-center justify-center gap-2 text-muted-foreground\">\n <IconLoader2 className=\"size-6 animate-spin\" aria-hidden />\n <span className=\"text-sm\">{labels.loadingMessages}</span>\n </div>\n ) : messagesStatus === \"error\" ? (\n <Empty className=\"h-full border-0\">\n <EmptyHeader>\n <EmptyMedia variant=\"icon\">\n <IconMessages />\n </EmptyMedia>\n <EmptyTitle>{labels.loadMessagesErrorTitle}</EmptyTitle>\n <EmptyDescription className=\"text-left\">\n {messagesError ?? labels.loadMessagesErrorFallback}\n </EmptyDescription>\n </EmptyHeader>\n </Empty>\n ) : messagesStatus === \"empty\" ? (\n <Empty className=\"h-full border-0\">\n <EmptyHeader>\n <EmptyMedia variant=\"icon\">\n <IconMessages />\n </EmptyMedia>\n <EmptyTitle>{labels.emptyThreadTitle}</EmptyTitle>\n <EmptyDescription>\n {labels.emptyThreadDescription(activeRoom.name)}\n </EmptyDescription>\n </EmptyHeader>\n </Empty>\n ) : (\n <div className=\"flex flex-col gap-6 px-5 py-2\">\n {isLoadingOlder ? (\n <div className=\"flex items-center justify-center gap-2 py-2 text-xs text-muted-foreground\">\n <IconLoader2\n className=\"size-3.5 shrink-0 animate-spin\"\n aria-hidden\n />\n {labels.loadingOlderMessages}\n </div>\n ) : null}\n {messages.map((message) => {\n const mine = message.role === \"me\";\n return (\n <Message\n key={message.id}\n align={mine ? \"end\" : \"start\"}\n >\n {mine ? null : (\n <MessageAvatar className=\"size-8 text-xs font-medium\">\n {message.initials}\n </MessageAvatar>\n )}\n <MessageContent>\n {mine ? null : (\n <MessageHeader>{message.author}</MessageHeader>\n )}\n <Bubble\n align={mine ? \"end\" : \"start\"}\n variant={mine ? \"muted\" : \"outline\"}\n >\n <BubbleContent className=\"break-words whitespace-pre-wrap\">\n {renderMessageTextWithMentions(message.text)}\n </BubbleContent>\n </Bubble>\n <MessageFooter>\n {formatMessageTime(message.at)}\n </MessageFooter>\n </MessageContent>\n </Message>\n );\n })}\n </div>\n )}\n {activeRoom && typingLine ? (\n <div\n className=\"border-t border-border px-5 py-2 text-xs text-muted-foreground\"\n aria-live=\"polite\"\n >\n {typingLine}\n </div>\n ) : null}\n </div>\n\n <form\n ref={formRef}\n onSubmit={onSubmit}\n className=\"relative px-5 pt-2 pb-5\"\n >\n {mentionOpen ? (\n <div\n role=\"listbox\"\n aria-label={labels.mentionListLabel}\n 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\"\n >\n <div className=\"shrink-0 border-b border-border px-2 py-1.5 text-[0.7rem] text-muted-foreground\">\n {mentionSeg.phase === \"category\" ? (\n <>\n <span className=\"font-medium text-foreground\">\n Tipo\n </span>\n {\" · \"}\n <kbd className=\"rounded bg-muted px-1 font-mono text-[0.65rem]\">\n Tab\n </kbd>\n /\n <kbd className=\"rounded bg-muted px-1 font-mono text-[0.65rem]\">\n ↵\n </kbd>\n </>\n ) : (\n <>\n <span className=\"font-medium text-foreground\">\n {DEFAULT_MENTION_KIND_LABEL[mentionSeg.kind]}\n </span>\n {\" · \"}\n <kbd className=\"rounded bg-muted px-1 font-mono text-[0.65rem]\">\n ←\n </kbd>\n </>\n )}\n </div>\n <div className=\"min-h-0 flex-1 overflow-y-auto p-1\">\n {mentionCatalogLoading && mentionEntries.length === 0 ? (\n <div className=\"flex items-center justify-center gap-2 px-2 py-6 text-sm text-muted-foreground\">\n <IconLoader2 className=\"size-4 animate-spin\" />\n Buscando…\n </div>\n ) : null}\n {!mentionCatalogLoading &&\n mentionEntries.length === 0 &&\n mentionSeg.phase === \"item\" ? (\n <p className=\"px-2 py-4 text-center text-sm text-muted-foreground\">\n Sin resultados\n </p>\n ) : null}\n {mentionEntries.map((entry, index) => {\n if (entry.type === \"category\") {\n const IconComp = entry.icon;\n const categoryDisabled = isMentionEntryDisabled(\n entry,\n mentionConfig,\n );\n return (\n <button\n key={`cat-${entry.kind}`}\n type=\"button\"\n role=\"option\"\n aria-selected={index === mentionHighlight}\n aria-disabled={categoryDisabled}\n disabled={categoryDisabled}\n className={cn(\n \"flex w-full items-start gap-2 rounded-lg px-2 py-2 text-left text-sm\",\n categoryDisabled &&\n \"cursor-not-allowed opacity-50\",\n !categoryDisabled &&\n (index === mentionHighlight\n ? \"bg-accent text-accent-foreground\"\n : \"hover:bg-muted/80\"),\n )}\n onMouseEnter={() => {\n if (!categoryDisabled) setMentionHighlight(index);\n }}\n onMouseDown={(event) => {\n event.preventDefault();\n if (categoryDisabled) return;\n applyCategoryPick(entry.kind);\n }}\n >\n <IconComp className=\"mt-0.5 size-4 shrink-0 opacity-80\" />\n <span className=\"min-w-0 flex-1\">\n <span className=\"block font-medium leading-tight\">\n {entry.label}\n </span>\n <span className=\"mt-0.5 block text-xs text-muted-foreground\">\n {entry.hint}\n </span>\n </span>\n </button>\n );\n }\n const item = entry.data;\n const IconComp = item.icon;\n return (\n <button\n key={item.id}\n type=\"button\"\n role=\"option\"\n aria-selected={index === mentionHighlight}\n className={cn(\n \"flex w-full items-start gap-2 rounded-lg px-2 py-2 text-left text-sm\",\n index === mentionHighlight\n ? \"bg-accent text-accent-foreground\"\n : \"hover:bg-muted/80\",\n )}\n onMouseEnter={() => setMentionHighlight(index)}\n onMouseDown={(event) => {\n event.preventDefault();\n applyItemPick(item);\n }}\n >\n <IconComp className=\"mt-0.5 size-4 shrink-0 opacity-80\" />\n <span className=\"min-w-0 flex-1\">\n <span className=\"block font-medium leading-tight\">\n {item.label}\n </span>\n <span className=\"mt-0.5 block text-xs text-muted-foreground\">\n {item.subtitle}\n </span>\n </span>\n </button>\n );\n })}\n </div>\n </div>\n ) : null}\n\n <InputGroup>\n <InputGroupTextarea\n ref={textareaRef}\n value={draft}\n onChange={(event) => {\n const v = event.target.value;\n const cursor =\n event.target.selectionStart ?? v.length;\n setDraft(v);\n onDraftChange?.(v);\n syncMentionMenu(v, cursor);\n }}\n onSelect={(event) => {\n const t = event.target as HTMLTextAreaElement;\n syncMentionMenu(\n t.value,\n t.selectionStart ?? t.value.length,\n );\n }}\n placeholder={\n activeRoom\n ? labels.messagePlaceholder\n : labels.messagePlaceholderNoRoom\n }\n aria-label={labels.messageAriaLabel}\n className=\"min-h-14\"\n disabled={!activeRoom}\n onKeyDown={(event) => {\n onUserGesture?.();\n if (mentionOpen) {\n if (event.key === \"ArrowDown\") {\n event.preventDefault();\n setMentionHighlight((h) =>\n stepMentionHighlight(\n mentionEntries,\n mentionConfig,\n h,\n 1,\n ),\n );\n return;\n }\n if (event.key === \"ArrowUp\") {\n event.preventDefault();\n setMentionHighlight((h) =>\n stepMentionHighlight(\n mentionEntries,\n mentionConfig,\n h,\n -1,\n ),\n );\n return;\n }\n if (event.key === \"Backspace\") {\n const seg = parseMentionSegment(\n mentionQuery,\n mentionConfig,\n );\n if (seg.phase === \"item\" && seg.filter === \"\") {\n event.preventDefault();\n replaceSlashSegment(\"\");\n setMentionHighlight(0);\n return;\n }\n }\n if (event.key === \"ArrowLeft\") {\n const seg = parseMentionSegment(\n mentionQuery,\n mentionConfig,\n );\n if (seg.phase === \"item\" && seg.filter === \"\") {\n event.preventDefault();\n replaceSlashSegment(\"\");\n setMentionHighlight(0);\n return;\n }\n }\n if (event.key === \"Enter\" && !event.shiftKey) {\n event.preventDefault();\n const pick = mentionEntries[mentionHighlight];\n if (!pick || isMentionEntryDisabled(pick, mentionConfig)) {\n return;\n }\n if (pick.type === \"category\") {\n applyCategoryPick(pick.kind);\n } else {\n applyItemPick(pick.data);\n }\n return;\n }\n if (event.key === \"Tab\") {\n event.preventDefault();\n const pick = mentionEntries[mentionHighlight];\n if (!pick || isMentionEntryDisabled(pick, mentionConfig)) {\n return;\n }\n if (pick.type === \"category\") {\n applyCategoryPick(pick.kind);\n } else {\n applyItemPick(pick.data);\n }\n return;\n }\n if (event.key === \"Escape\") {\n event.preventDefault();\n closeMentionMenu();\n return;\n }\n }\n if (event.key === \"Enter\" && !event.shiftKey) {\n event.preventDefault();\n formRef.current?.requestSubmit();\n }\n }}\n />\n <InputGroupAddon align=\"block-end\" className=\"pt-1\">\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <InputGroupButton\n aria-label={labels.attachAriaLabel}\n type=\"button\"\n size=\"icon-sm\"\n variant=\"outline\"\n disabled={!activeRoom}\n >\n <IconPlus className=\"size-4\" />\n </InputGroupButton>\n </DropdownMenuTrigger>\n <DropdownMenuContent\n align=\"start\"\n side=\"top\"\n className=\"w-44\"\n >\n <DropdownMenuItem>\n <IconPaperclip className=\"size-4\" />\n {labels.attachPhotos}\n </DropdownMenuItem>\n </DropdownMenuContent>\n </DropdownMenu>\n <InputGroupButton\n type=\"submit\"\n variant=\"default\"\n size=\"icon-sm\"\n disabled={!canSend || !activeRoom}\n className=\"ml-auto\"\n >\n <IconArrowUp className=\"size-4\" />\n <span className=\"sr-only\">{labels.sendSrOnly}</span>\n </InputGroupButton>\n </InputGroupAddon>\n </InputGroup>\n </form>\n </div>\n </div>\n </DrawerContent>\n </Drawer>\n </>\n );\n}\n\nexport {\n InternalChatPanel,\n DEFAULT_MENTION_CONFIG,\n DEFAULT_LABELS as DEFAULT_INTERNAL_CHAT_PANEL_LABELS,\n};\n\nexport { initialsFromDisplayName } from \"@/components/ui/internal-chat-mention\";\n\nexport type {\n BuildMentionListOptions,\n InternalChatMentionCatalogState,\n InternalChatMentionConfig,\n InternalChatMentionItem,\n InternalChatMentionKind,\n} from \"@/components/ui/internal-chat-mention\";\n",
|
|
27
|
+
"type": "registry:ui",
|
|
28
|
+
"target": ""
|
|
29
|
+
}
|
|
30
|
+
]
|
|
31
|
+
}
|
|
@@ -353,6 +353,26 @@
|
|
|
353
353
|
}
|
|
354
354
|
]
|
|
355
355
|
},
|
|
356
|
+
{
|
|
357
|
+
"name": "internal-chat-mention",
|
|
358
|
+
"type": "registry:ui",
|
|
359
|
+
"files": [
|
|
360
|
+
{
|
|
361
|
+
"path": "json/internal-chat-mention.json",
|
|
362
|
+
"type": "registry:file"
|
|
363
|
+
}
|
|
364
|
+
]
|
|
365
|
+
},
|
|
366
|
+
{
|
|
367
|
+
"name": "internal-chat-panel",
|
|
368
|
+
"type": "registry:ui",
|
|
369
|
+
"files": [
|
|
370
|
+
{
|
|
371
|
+
"path": "json/internal-chat-panel.json",
|
|
372
|
+
"type": "registry:file"
|
|
373
|
+
}
|
|
374
|
+
]
|
|
375
|
+
},
|
|
356
376
|
{
|
|
357
377
|
"name": "item",
|
|
358
378
|
"type": "registry:ui",
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
import type { Icon } from "@tabler/icons-react";
|
|
2
|
+
|
|
3
|
+
export type InternalChatMentionKind = "guide" | "package" | "ai";
|
|
4
|
+
|
|
5
|
+
export type InternalChatMentionItem = {
|
|
6
|
+
id: string;
|
|
7
|
+
kind: InternalChatMentionKind;
|
|
8
|
+
label: string;
|
|
9
|
+
subtitle: string;
|
|
10
|
+
insertLabel: string;
|
|
11
|
+
icon: Icon;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
export type InternalChatMentionCategoryMeta = {
|
|
15
|
+
label: string;
|
|
16
|
+
hint: string;
|
|
17
|
+
keywords: string[];
|
|
18
|
+
/** Visible en el menú de tipo pero no seleccionable (p. ej. próximamente). */
|
|
19
|
+
disabled?: boolean;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export type InternalChatMentionListEntry =
|
|
23
|
+
| {
|
|
24
|
+
type: "category";
|
|
25
|
+
kind: InternalChatMentionKind;
|
|
26
|
+
label: string;
|
|
27
|
+
hint: string;
|
|
28
|
+
icon: Icon;
|
|
29
|
+
disabled?: boolean;
|
|
30
|
+
}
|
|
31
|
+
| { type: "item"; data: InternalChatMentionItem };
|
|
32
|
+
|
|
33
|
+
export type InternalChatMentionCatalogState = {
|
|
34
|
+
open: boolean;
|
|
35
|
+
phase: "category" | "item";
|
|
36
|
+
kind?: InternalChatMentionKind;
|
|
37
|
+
filter: string;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
export type BuildMentionListOptions = {
|
|
41
|
+
/** Si true, los ítems ya vienen filtrados del servidor (sin filtro local por texto). */
|
|
42
|
+
serverFilteredItems?: boolean;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
export const DEFAULT_MENTION_KIND_ORDER: InternalChatMentionKind[] = [
|
|
46
|
+
"guide",
|
|
47
|
+
"package",
|
|
48
|
+
"ai",
|
|
49
|
+
];
|
|
50
|
+
|
|
51
|
+
export const DEFAULT_MENTION_KIND_LABEL: Record<
|
|
52
|
+
InternalChatMentionKind,
|
|
53
|
+
string
|
|
54
|
+
> = {
|
|
55
|
+
guide: "Guías",
|
|
56
|
+
package: "Paquetes",
|
|
57
|
+
ai: "Asistencia de IA",
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
export type InternalChatMentionConfig = {
|
|
61
|
+
kindOrder: InternalChatMentionKind[];
|
|
62
|
+
categoryMeta: Record<
|
|
63
|
+
InternalChatMentionKind,
|
|
64
|
+
InternalChatMentionCategoryMeta
|
|
65
|
+
>;
|
|
66
|
+
kindIcons: Record<InternalChatMentionKind, Icon>;
|
|
67
|
+
kindAliases?: Record<string, InternalChatMentionKind>;
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
function resolveKindAlias(
|
|
71
|
+
raw: string,
|
|
72
|
+
config: InternalChatMentionConfig,
|
|
73
|
+
): InternalChatMentionKind | null {
|
|
74
|
+
const s = raw.trim().toLowerCase();
|
|
75
|
+
if (!s) return null;
|
|
76
|
+
|
|
77
|
+
const aliases: Record<string, InternalChatMentionKind> = {
|
|
78
|
+
guide: "guide",
|
|
79
|
+
guía: "guide",
|
|
80
|
+
guia: "guide",
|
|
81
|
+
paquete: "package",
|
|
82
|
+
paquetes: "package",
|
|
83
|
+
package: "package",
|
|
84
|
+
ia: "ai",
|
|
85
|
+
ai: "ai",
|
|
86
|
+
asistencia: "ai",
|
|
87
|
+
...config.kindAliases,
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
const direct = aliases[s];
|
|
91
|
+
if (direct) return direct;
|
|
92
|
+
|
|
93
|
+
for (const kind of config.kindOrder) {
|
|
94
|
+
const meta = config.categoryMeta[kind];
|
|
95
|
+
if (kind === s) return kind;
|
|
96
|
+
if (meta.label.toLowerCase() === s) return kind;
|
|
97
|
+
if (meta.keywords.some((k) => k === s)) return kind;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
return null;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function parseMentionSegment(
|
|
104
|
+
query: string,
|
|
105
|
+
config: InternalChatMentionConfig,
|
|
106
|
+
):
|
|
107
|
+
| { phase: "category"; filter: string }
|
|
108
|
+
| { phase: "item"; kind: InternalChatMentionKind; filter: string } {
|
|
109
|
+
const colon = query.indexOf(":");
|
|
110
|
+
if (colon === -1) {
|
|
111
|
+
return { phase: "category", filter: query };
|
|
112
|
+
}
|
|
113
|
+
const head = query.slice(0, colon).trim().toLowerCase();
|
|
114
|
+
const tail = query.slice(colon + 1);
|
|
115
|
+
if (head === "") {
|
|
116
|
+
return { phase: "category", filter: query.replace(":", "") };
|
|
117
|
+
}
|
|
118
|
+
const kind = resolveKindAlias(head, config);
|
|
119
|
+
if (!kind) {
|
|
120
|
+
return { phase: "category", filter: query };
|
|
121
|
+
}
|
|
122
|
+
return { phase: "item", kind, filter: tail };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export function parseSlashMention(
|
|
126
|
+
draft: string,
|
|
127
|
+
cursor: number,
|
|
128
|
+
): { start: number; query: string } | null {
|
|
129
|
+
const before = draft.slice(0, cursor);
|
|
130
|
+
const lastSlash = before.lastIndexOf("/");
|
|
131
|
+
if (lastSlash === -1) return null;
|
|
132
|
+
const charBefore = lastSlash === 0 ? " " : draft[lastSlash - 1];
|
|
133
|
+
if (charBefore !== " " && charBefore !== "\n" && lastSlash !== 0) {
|
|
134
|
+
return null;
|
|
135
|
+
}
|
|
136
|
+
const afterSlash = before.slice(lastSlash + 1);
|
|
137
|
+
if (afterSlash.includes("\n")) return null;
|
|
138
|
+
return { start: lastSlash, query: afterSlash };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function filterCategoryEntries(
|
|
142
|
+
filterText: string,
|
|
143
|
+
config: InternalChatMentionConfig,
|
|
144
|
+
): InternalChatMentionListEntry[] {
|
|
145
|
+
const q = filterText.trim().toLowerCase();
|
|
146
|
+
const rows: InternalChatMentionListEntry[] = config.kindOrder.map((kind) => ({
|
|
147
|
+
type: "category",
|
|
148
|
+
kind,
|
|
149
|
+
label: config.categoryMeta[kind].label,
|
|
150
|
+
hint: config.categoryMeta[kind].hint,
|
|
151
|
+
icon: config.kindIcons[kind],
|
|
152
|
+
disabled: config.categoryMeta[kind].disabled,
|
|
153
|
+
}));
|
|
154
|
+
if (!q) return rows;
|
|
155
|
+
const byAlias = resolveKindAlias(q, config);
|
|
156
|
+
return rows.filter((row) => {
|
|
157
|
+
if (row.type !== "category") return false;
|
|
158
|
+
if (byAlias && row.kind === byAlias) return true;
|
|
159
|
+
return (
|
|
160
|
+
row.label.toLowerCase().includes(q) ||
|
|
161
|
+
row.hint.toLowerCase().includes(q) ||
|
|
162
|
+
config.categoryMeta[row.kind].keywords.some(
|
|
163
|
+
(k) => k.includes(q) || q.includes(k),
|
|
164
|
+
)
|
|
165
|
+
);
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function filterItemsByKind(
|
|
170
|
+
kind: InternalChatMentionKind,
|
|
171
|
+
filterText: string,
|
|
172
|
+
catalog: InternalChatMentionItem[],
|
|
173
|
+
skipTextFilter = false,
|
|
174
|
+
): InternalChatMentionListEntry[] {
|
|
175
|
+
const q = filterText.trim().toLowerCase();
|
|
176
|
+
let items = catalog.filter((i) => i.kind === kind);
|
|
177
|
+
if (!skipTextFilter && q) {
|
|
178
|
+
items = items.filter(
|
|
179
|
+
(item) =>
|
|
180
|
+
item.label.toLowerCase().includes(q) ||
|
|
181
|
+
item.subtitle.toLowerCase().includes(q) ||
|
|
182
|
+
item.insertLabel.toLowerCase().includes(q),
|
|
183
|
+
);
|
|
184
|
+
}
|
|
185
|
+
return items.map((data) => ({ type: "item", data }));
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export function buildMentionList(
|
|
189
|
+
query: string,
|
|
190
|
+
guideItems: InternalChatMentionItem[],
|
|
191
|
+
packageItems: InternalChatMentionItem[],
|
|
192
|
+
config: InternalChatMentionConfig,
|
|
193
|
+
options?: BuildMentionListOptions,
|
|
194
|
+
): InternalChatMentionListEntry[] {
|
|
195
|
+
const seg = parseMentionSegment(query, config);
|
|
196
|
+
if (seg.phase === "category") {
|
|
197
|
+
return filterCategoryEntries(seg.filter, config);
|
|
198
|
+
}
|
|
199
|
+
if (seg.kind === "ai" || config.categoryMeta[seg.kind]?.disabled) {
|
|
200
|
+
return [];
|
|
201
|
+
}
|
|
202
|
+
const pool = seg.kind === "guide" ? guideItems : packageItems;
|
|
203
|
+
return filterItemsByKind(
|
|
204
|
+
seg.kind,
|
|
205
|
+
seg.filter,
|
|
206
|
+
pool,
|
|
207
|
+
Boolean(options?.serverFilteredItems),
|
|
208
|
+
);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export function roomInitialLetter(name: string): string {
|
|
212
|
+
const t = name.trim();
|
|
213
|
+
if (!t) return "?";
|
|
214
|
+
const ch = [...t][0];
|
|
215
|
+
return ch && /\p{L}/u.test(ch) ? ch.toUpperCase() : "?";
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
export function initialsFromDisplayName(name: string): string {
|
|
219
|
+
const t = name.trim();
|
|
220
|
+
if (!t) return "?";
|
|
221
|
+
const parts = t.split(/\s+/).filter(Boolean);
|
|
222
|
+
if (parts.length === 0) return "?";
|
|
223
|
+
if (parts.length === 1) return parts[0]!.slice(0, 2).toUpperCase();
|
|
224
|
+
return `${parts[0]![0]!}${parts[parts.length - 1]![0]!}`.toUpperCase();
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
export function formatMessageTime(iso: string, locale = "es"): string {
|
|
228
|
+
return new Intl.DateTimeFormat(locale, {
|
|
229
|
+
hour: "2-digit",
|
|
230
|
+
minute: "2-digit",
|
|
231
|
+
hour12: false,
|
|
232
|
+
}).format(new Date(iso));
|
|
233
|
+
}
|