From cefc9b38c37de0df71ec30145be055a25477e644 Mon Sep 17 00:00:00 2001 From: A-PachecoT Date: Wed, 11 Nov 2026 17:06:12 -0500 Subject: [PATCH] =?UTF-8?q?fix(marca):=20restaurar=20CRLF=20en=204=20archi?= =?UTF-8?q?vos=20que=20la=20pasada=20de=20Tracta=20pas=C3=B3=20a=20LF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/iife/index.tsx | 510 ++++---- .../navigation/NavDropdown.stories.tsx | 1126 ++++++++--------- src/transports/SocketIOTransport.ts | 1110 ++++++++-------- src/transports/types.ts | 406 +++--- 4 files changed, 1576 insertions(+), 1576 deletions(-) diff --git a/src/iife/index.tsx b/src/iife/index.tsx index 94b6632..4bfd16d 100644 --- a/src/iife/index.tsx +++ b/src/iife/index.tsx @@ -1,255 +1,255 @@ -/** - * IIFE Entry Point for Cofoundy Chat Widget - * - * This file is the entry point for building a standalone IIFE bundle - * that can be embedded on any website via a - * - */ - -import React from "react"; -import { createRoot } from "react-dom/client"; -import { ChatWidgetFloating } from "../components/chat-widget/ChatWidgetFloating"; -import type { ChatWidgetConfig, Message } from "../types"; - -// Import styles — the IIFE-only entry that pulls in the Tailwind utility layer -// (via @tailwindcss/vite) plus the base tokens/styles. See iife.css. (#251) -import "./iife.css"; - -/** - * Widget configuration from window.cofoundyChatConfig - */ -interface WidgetGlobalConfig { - transport?: { - type: "websocket" | "socketio"; - url: string; - tenantId?: string; - sessionId?: string; - }; - theme?: { - primaryColor?: string; - brandName?: string; - brandLogo?: string; - brandSubtitle?: string; - }; - floating?: { - position?: "bottom-right" | "bottom-left" | "top-right" | "top-left"; - showBadge?: boolean; - defaultOpen?: boolean; - offset?: { x?: number; y?: number }; - zIndex?: number; - }; - greeting?: { - id?: string; - content: string; - }; - quickActions?: Array<{ - id: string; - label: string; - message: string; - }>; - session?: { - newSessionOnReload?: boolean; - storageKey?: string; - }; - // Callbacks (optional, for advanced usage) - onReady?: () => void; - onOpenChange?: (open: boolean) => void; - onMessageSent?: (message: string) => void; -} - -declare global { - interface Window { - cofoundyChatConfig?: WidgetGlobalConfig; - CofoundyChat?: { - init: (config: WidgetGlobalConfig) => void; - destroy: () => void; - }; - } -} - -// Container element for the widget -let widgetContainer: HTMLDivElement | null = null; -let widgetRoot: ReturnType | null = null; - -/** - * Convert global config to ChatWidgetConfig - */ -function convertConfig(globalConfig: WidgetGlobalConfig): ChatWidgetConfig { - const config: ChatWidgetConfig = { - mode: "floating", - floating: { - position: globalConfig.floating?.position ?? "bottom-right", - showBadge: globalConfig.floating?.showBadge ?? true, - defaultOpen: globalConfig.floating?.defaultOpen ?? false, - offset: globalConfig.floating?.offset, - zIndex: globalConfig.floating?.zIndex ?? 9999, - }, - theme: { - brandName: globalConfig.theme?.brandName ?? "Chat", - brandLogo: globalConfig.theme?.brandLogo, - brandSubtitle: globalConfig.theme?.brandSubtitle, - primaryColor: globalConfig.theme?.primaryColor ?? "#2984AD", - }, - session: globalConfig.session, - quickActions: globalConfig.quickActions, - onOpenChange: globalConfig.onOpenChange, - onMessageSent: globalConfig.onMessageSent, - }; - - // Set transport config - if (globalConfig.transport) { - if (globalConfig.transport.type === "socketio") { - config.transport = { - type: "socketio", - url: globalConfig.transport.url, - tenantId: globalConfig.transport.tenantId ?? "", - sessionId: globalConfig.transport.sessionId, - }; - } else { - config.transport = { - type: "websocket", - url: globalConfig.transport.url, - sessionId: globalConfig.transport.sessionId, - }; - } - } - - // Set greeting message - if (globalConfig.greeting) { - config.greeting = { - id: globalConfig.greeting.id ?? "greeting-1", - role: "assistant", - content: globalConfig.greeting.content, - timestamp: new Date(), - } as Message; - } - - return config; -} - -/** - * Initialize the chat widget - */ -function init(config: WidgetGlobalConfig) { - // Destroy existing instance if any - destroy(); - - // Create container - widgetContainer = document.createElement("div"); - widgetContainer.id = "cofoundy-chat-widget-root"; - document.body.appendChild(widgetContainer); - - // Convert config - const widgetConfig = convertConfig(config); - - // Create React root and render - widgetRoot = createRoot(widgetContainer); - widgetRoot.render( - - - - ); - - // Call onReady callback - config.onReady?.(); -} - -/** - * Destroy the chat widget - */ -function destroy() { - if (widgetRoot) { - widgetRoot.unmount(); - widgetRoot = null; - } - if (widgetContainer) { - widgetContainer.remove(); - widgetContainer = null; - } -} - -// Expose global API -window.CofoundyChat = { - init, - destroy, -}; - -// Auto-initialize if config is present -if (typeof window !== "undefined" && window.cofoundyChatConfig) { - // Wait for DOM to be ready - if (document.readyState === "loading") { - document.addEventListener("DOMContentLoaded", () => { - init(window.cofoundyChatConfig!); - }); - } else { - init(window.cofoundyChatConfig); - } -} - -// Also support legacy Tracta config format for backwards compatibility -declare global { - interface Window { - inboxaiConfig?: { - tenantId: string; - apiUrl: string; - socketUrl?: string; - primaryColor?: string; - title?: string; - subtitle?: string; - position?: string; - }; - Tracta?: { - init: (config: unknown) => void; - }; - } -} - -// Legacy Tracta compatibility layer -if (typeof window !== "undefined") { - window.InboxAI = { - init: (legacyConfig: unknown) => { - const config = legacyConfig as Window["inboxaiConfig"]; - if (!config) return; - - const modernConfig: WidgetGlobalConfig = { - transport: { - type: "socketio", - url: config.socketUrl ?? config.apiUrl, - tenantId: config.tenantId, - }, - theme: { - primaryColor: config.primaryColor, - brandName: config.title, - brandSubtitle: config.subtitle, - }, - floating: { - position: - (config.position as "bottom-right" | "bottom-left") ?? "bottom-right", - }, - }; - - init(modernConfig); - }, - }; - - // Auto-init with legacy config if present - if (window.inboxaiConfig && !window.cofoundyChatConfig) { - if (document.readyState === "loading") { - document.addEventListener("DOMContentLoaded", () => { - window.InboxAI?.init(window.inboxaiConfig); - }); - } else { - window.InboxAI.init(window.inboxaiConfig); - } - } -} +/** + * IIFE Entry Point for Cofoundy Chat Widget + * + * This file is the entry point for building a standalone IIFE bundle + * that can be embedded on any website via a + * + */ + +import React from "react"; +import { createRoot } from "react-dom/client"; +import { ChatWidgetFloating } from "../components/chat-widget/ChatWidgetFloating"; +import type { ChatWidgetConfig, Message } from "../types"; + +// Import styles — the IIFE-only entry that pulls in the Tailwind utility layer +// (via @tailwindcss/vite) plus the base tokens/styles. See iife.css. (#251) +import "./iife.css"; + +/** + * Widget configuration from window.cofoundyChatConfig + */ +interface WidgetGlobalConfig { + transport?: { + type: "websocket" | "socketio"; + url: string; + tenantId?: string; + sessionId?: string; + }; + theme?: { + primaryColor?: string; + brandName?: string; + brandLogo?: string; + brandSubtitle?: string; + }; + floating?: { + position?: "bottom-right" | "bottom-left" | "top-right" | "top-left"; + showBadge?: boolean; + defaultOpen?: boolean; + offset?: { x?: number; y?: number }; + zIndex?: number; + }; + greeting?: { + id?: string; + content: string; + }; + quickActions?: Array<{ + id: string; + label: string; + message: string; + }>; + session?: { + newSessionOnReload?: boolean; + storageKey?: string; + }; + // Callbacks (optional, for advanced usage) + onReady?: () => void; + onOpenChange?: (open: boolean) => void; + onMessageSent?: (message: string) => void; +} + +declare global { + interface Window { + cofoundyChatConfig?: WidgetGlobalConfig; + CofoundyChat?: { + init: (config: WidgetGlobalConfig) => void; + destroy: () => void; + }; + } +} + +// Container element for the widget +let widgetContainer: HTMLDivElement | null = null; +let widgetRoot: ReturnType | null = null; + +/** + * Convert global config to ChatWidgetConfig + */ +function convertConfig(globalConfig: WidgetGlobalConfig): ChatWidgetConfig { + const config: ChatWidgetConfig = { + mode: "floating", + floating: { + position: globalConfig.floating?.position ?? "bottom-right", + showBadge: globalConfig.floating?.showBadge ?? true, + defaultOpen: globalConfig.floating?.defaultOpen ?? false, + offset: globalConfig.floating?.offset, + zIndex: globalConfig.floating?.zIndex ?? 9999, + }, + theme: { + brandName: globalConfig.theme?.brandName ?? "Chat", + brandLogo: globalConfig.theme?.brandLogo, + brandSubtitle: globalConfig.theme?.brandSubtitle, + primaryColor: globalConfig.theme?.primaryColor ?? "#2984AD", + }, + session: globalConfig.session, + quickActions: globalConfig.quickActions, + onOpenChange: globalConfig.onOpenChange, + onMessageSent: globalConfig.onMessageSent, + }; + + // Set transport config + if (globalConfig.transport) { + if (globalConfig.transport.type === "socketio") { + config.transport = { + type: "socketio", + url: globalConfig.transport.url, + tenantId: globalConfig.transport.tenantId ?? "", + sessionId: globalConfig.transport.sessionId, + }; + } else { + config.transport = { + type: "websocket", + url: globalConfig.transport.url, + sessionId: globalConfig.transport.sessionId, + }; + } + } + + // Set greeting message + if (globalConfig.greeting) { + config.greeting = { + id: globalConfig.greeting.id ?? "greeting-1", + role: "assistant", + content: globalConfig.greeting.content, + timestamp: new Date(), + } as Message; + } + + return config; +} + +/** + * Initialize the chat widget + */ +function init(config: WidgetGlobalConfig) { + // Destroy existing instance if any + destroy(); + + // Create container + widgetContainer = document.createElement("div"); + widgetContainer.id = "cofoundy-chat-widget-root"; + document.body.appendChild(widgetContainer); + + // Convert config + const widgetConfig = convertConfig(config); + + // Create React root and render + widgetRoot = createRoot(widgetContainer); + widgetRoot.render( + + + + ); + + // Call onReady callback + config.onReady?.(); +} + +/** + * Destroy the chat widget + */ +function destroy() { + if (widgetRoot) { + widgetRoot.unmount(); + widgetRoot = null; + } + if (widgetContainer) { + widgetContainer.remove(); + widgetContainer = null; + } +} + +// Expose global API +window.CofoundyChat = { + init, + destroy, +}; + +// Auto-initialize if config is present +if (typeof window !== "undefined" && window.cofoundyChatConfig) { + // Wait for DOM to be ready + if (document.readyState === "loading") { + document.addEventListener("DOMContentLoaded", () => { + init(window.cofoundyChatConfig!); + }); + } else { + init(window.cofoundyChatConfig); + } +} + +// Also support legacy Tracta config format for backwards compatibility +declare global { + interface Window { + inboxaiConfig?: { + tenantId: string; + apiUrl: string; + socketUrl?: string; + primaryColor?: string; + title?: string; + subtitle?: string; + position?: string; + }; + Tracta?: { + init: (config: unknown) => void; + }; + } +} + +// Legacy Tracta compatibility layer +if (typeof window !== "undefined") { + window.InboxAI = { + init: (legacyConfig: unknown) => { + const config = legacyConfig as Window["inboxaiConfig"]; + if (!config) return; + + const modernConfig: WidgetGlobalConfig = { + transport: { + type: "socketio", + url: config.socketUrl ?? config.apiUrl, + tenantId: config.tenantId, + }, + theme: { + primaryColor: config.primaryColor, + brandName: config.title, + brandSubtitle: config.subtitle, + }, + floating: { + position: + (config.position as "bottom-right" | "bottom-left") ?? "bottom-right", + }, + }; + + init(modernConfig); + }, + }; + + // Auto-init with legacy config if present + if (window.inboxaiConfig && !window.cofoundyChatConfig) { + if (document.readyState === "loading") { + document.addEventListener("DOMContentLoaded", () => { + window.InboxAI?.init(window.inboxaiConfig); + }); + } else { + window.InboxAI.init(window.inboxaiConfig); + } + } +} diff --git a/src/stories/navigation/NavDropdown.stories.tsx b/src/stories/navigation/NavDropdown.stories.tsx index 4b9fa18..1aa9768 100644 --- a/src/stories/navigation/NavDropdown.stories.tsx +++ b/src/stories/navigation/NavDropdown.stories.tsx @@ -1,563 +1,563 @@ -import type { Meta, StoryObj } from "@storybook/react"; -import * as React from "react"; - -import { - NavDropdown, - type NavDropdownItem, -} from "../../components/navigation/NavDropdown"; -import { VIEWPORT_MOBILE } from "../_shared/viewports"; - -const meta: Meta = { - title: "Navigation/NavDropdown", - component: NavDropdown, - tags: ["autodocs"], - parameters: { - layout: "centered", - docs: { - description: { - component: ` -A navigation dropdown component designed for navbar menus. - -## Features -- **Hover-to-open** on desktop, **click-to-open** on touch devices -- **150ms close delay** to prevent accidental closure -- **Keyboard navigation**: Arrow keys, Enter, Escape, Tab, Home, End -- **ARIA-compliant**: Proper roles, states, and keyboard support -- **Glassmorphism design**: Backdrop blur, subtle borders -- **Premium animations**: Smooth easing with scale and fade -- **Active state indicator**: Visual highlight for current page -- **Touch-friendly**: 44px minimum touch targets - -## Usage -\`\`\`tsx -import { NavDropdown } from '@cofoundy/ui' - - router.push(href)} -/> -\`\`\` - `, - }, - }, - }, - argTypes: { - variant: { - control: "radio", - options: ["dark", "light"], - description: "Theme variant", - }, - label: { - control: "text", - description: "Trigger button label", - }, - items: { - description: "Menu items array", - }, - onItemClick: { - action: "clicked", - description: "Callback when an item is clicked", - }, - }, - decorators: [ - (Story, context) => { - const isDark = context.args.variant === "dark"; - return ( -
- -
- ); - }, - ], -}; - -export default meta; -type Story = StoryObj; - -// Sample items for stories -const serviceItems: NavDropdownItem[] = [ - { - key: "landing", - href: "/servicios/landing-pages", - label: "Landing Pages", - description: "Tu landing lista en 7 días", - }, - { - key: "pollada", - href: "/servicios/pollada", - label: "Pollada Virtual", - description: "Portafolio desde S/.50", - }, - { - key: "chatbot", - href: "/servicios/chatbot", - label: "AI Chatbot", - description: "Automatiza tu atención 24/7", - }, - { - key: "fullstack", - href: "/servicios/fullstack", - label: "Desarrollo Fullstack", - description: "Apps a medida para tu negocio", - }, -]; - -const productItems: NavDropdownItem[] = [ - { - key: "timely", - href: "/productos/timely-ai", - label: "TimelyAI", - description: "Scheduling inteligente", - isActive: true, - }, - { - key: "inbox", - href: "/productos/inbox-ai", - label: "Tracta", - description: "Omnichannel inbox unificado", - }, - { - key: "pulse", - href: "/productos/pulse-ai", - label: "PulseAI", - description: "Voice agent para llamadas", - }, -]; - -// ============================================ -// Stories -// ============================================ - -export const Default: Story = { - args: { - label: "Servicios", - variant: "dark", - items: serviceItems, - }, -}; - -export const WithActiveItem: Story = { - args: { - label: "Productos", - variant: "dark", - items: productItems, - }, - parameters: { - docs: { - description: { - story: - "Items can have an `isActive` prop to indicate the current page. Shows a primary-colored left border and subtle background.", - }, - }, - }, -}; - -export const LightVariant: Story = { - args: { - label: "Servicios", - variant: "light", - items: serviceItems, - }, - parameters: { - docs: { - description: { - story: "Light variant for use on light backgrounds.", - }, - }, - }, -}; - -export const LightWithActive: Story = { - args: { - label: "Productos", - variant: "light", - items: productItems, - }, -}; - -export const MinimalItems: Story = { - args: { - label: "Resources", - variant: "dark", - items: [ - { key: "docs", href: "/docs", label: "Documentation" }, - { key: "blog", href: "/blog", label: "Blog" }, - ], - }, - parameters: { - docs: { - description: { - story: "Items without descriptions for a more compact menu.", - }, - }, - }, -}; - -export const CustomWidth: Story = { - args: { - label: "Solutions", - variant: "dark", - items: serviceItems, - menuClassName: "min-w-[360px]", - }, - parameters: { - docs: { - description: { - story: - "Use `menuClassName` to customize the dropdown width and other styles.", - }, - }, - }, -}; - -// Interactive demo with navbar context -export const InNavbar: Story = { - render: function Render() { - const [activeKey, setActiveKey] = React.useState("timely"); - - const items = productItems.map((item) => ({ - ...item, - isActive: item.key === activeKey, - })); - - return ( -
- {/* Simulated navbar */} - -
- Page content area. Click on Products dropdown to change active item. -
- Active product: {activeKey} -
-
- ); - }, - parameters: { - docs: { - description: { - story: - "Example of NavDropdown components used within a navbar context. The Products dropdown demonstrates interactive active state management.", - }, - }, - }, -}; - -// Mobile-first contract baseline — 375 px (iPhone SE). -// Verifies the 44 px tap-target claim from the component header against an -// actual mobile viewport. Required per packages/ui/CLAUDE.md. -export const MobileBaseline: Story = { - args: { - label: "Servicios", - variant: "dark", - items: serviceItems, - }, - parameters: { - viewport: VIEWPORT_MOBILE, - docs: { - description: { - story: - "Mobile baseline (375 px, iPhone SE). Trigger and menu items must keep ≥ 44×44 px touch targets — auditable visually at this viewport.", - }, - }, - }, -}; - -// Keyboard navigation demo -export const KeyboardNavigation: Story = { - args: { - label: "Keyboard Demo", - variant: "dark", - items: serviceItems, - }, - parameters: { - docs: { - description: { - story: ` -**Try these keyboard interactions:** -- **Tab** to focus the dropdown trigger -- **Enter/Space** to open the menu -- **Arrow Down/Up** to navigate items -- **Home/End** to jump to first/last item -- **Enter** to select an item -- **Escape** to close the menu -- **Tab** while open to close and move focus - `, - }, - }, - }, -}; - -// Touch device simulation -export const TouchBehavior: Story = { - args: { - label: "Tap to Open", - variant: "dark", - items: serviceItems, - }, - parameters: { - docs: { - description: { - story: - "On touch devices, the dropdown opens and closes on tap instead of hover. Test this on a mobile device or using browser dev tools touch simulation.", - }, - }, - }, -}; - -// ============================================ -// Featured Effects Stories -// ============================================ - -// Items with badge -const itemsWithBadge: NavDropdownItem[] = [ - { - key: "landing", - href: "/servicios/landing-pages", - label: "Landing Pages", - description: "Tu landing lista en 7 días", - }, - { - key: "pollada", - href: "/servicios/pollada", - label: "🍗 Pollada Virtual", - description: "¡Apoya al equipo! Desde S/.50", - badge: "Nuevo", - }, - { - key: "chatbot", - href: "/servicios/chatbot", - label: "AI Chatbot", - description: "Automatiza tu atención 24/7", - }, -]; - -export const WithBadge: Story = { - args: { - label: "Servicios", - variant: "dark", - items: itemsWithBadge, - }, - parameters: { - docs: { - description: { - story: "Items can have a `badge` prop to display a small tag (e.g., 'Nuevo', '🔥').", - }, - }, - }, -}; - -// Gold Shimmer Effect (card) -export const FeaturedShimmer: Story = { - args: { - label: "Servicios", - variant: "dark", - items: [ - { - key: "landing", - href: "/servicios/landing-pages", - label: "Landing Pages", - description: "Tu landing lista en 7 días", - }, - { - key: "pollada", - href: "/servicios/pollada", - label: "🍗 Pollada Virtual", - description: "¡Apoya al equipo! Desde S/.50", - badge: "Nuevo", - featured: "shimmer", - }, - { - key: "chatbot", - href: "/servicios/chatbot", - label: "AI Chatbot", - description: "Automatiza tu atención 24/7", - }, - ], - }, - parameters: { - docs: { - description: { - story: "**Gold Shimmer** - Horizontal gold light sweep animation on the card.", - }, - }, - }, -}; - -// Brand Gradient Border Effect (card) -export const FeaturedGradientBorder: Story = { - args: { - label: "Servicios", - variant: "dark", - items: [ - { - key: "landing", - href: "/servicios/landing-pages", - label: "Landing Pages", - description: "Tu landing lista en 7 días", - }, - { - key: "pollada", - href: "/servicios/pollada", - label: "🍗 Pollada Virtual", - description: "¡Apoya al equipo! Desde S/.50", - badge: "Nuevo", - featured: "gradient-border", - }, - { - key: "chatbot", - href: "/servicios/chatbot", - label: "AI Chatbot", - description: "Automatiza tu atención 24/7", - }, - ], - }, - parameters: { - docs: { - description: { - story: "**Brand Gradient Border** - Animated rotating border with Cofoundy brand colors.", - }, - }, - }, -}; - -// Both effects comparison -export const AllFeaturedEffects: Story = { - render: () => ( -
-
-

Gold Shimmer (Card)

- -
-
-

Brand Gradient Border (Card)

- -
-
- ), - parameters: { - docs: { - description: { - story: "Comparison of both featured effects side by side.", - }, - }, - }, -}; - -// Gold Glow Text Effect (ShimmerText on label) -export const FeaturedGoldGlow: Story = { - args: { - label: "Servicios", - variant: "dark", - items: [ - { - key: "landing", - href: "/servicios/landing-pages", - label: "Landing Pages", - description: "Tu landing lista en 7 días", - }, - { - key: "pollada", - href: "/servicios/pollada", - label: "🍗 Pollada Virtual", - description: "¡Apoya al equipo! Desde S/.50", - badge: "Nuevo", - featured: "gold-glow", - }, - { - key: "chatbot", - href: "/servicios/chatbot", - label: "AI Chatbot", - description: "Automatiza tu atención 24/7", - }, - ], - }, - parameters: { - docs: { - description: { - story: "**Gold Glow** - Animated shimmer effect on the text itself using ShimmerText component.", - }, - }, - }, -}; - -// Light mode featured -export const FeaturedLightMode: Story = { - args: { - label: "Servicios", - variant: "light", - items: [ - { - key: "landing", - href: "/servicios/landing-pages", - label: "Landing Pages", - description: "Tu landing lista en 7 días", - }, - { - key: "pollada", - href: "/servicios/pollada", - label: "🍗 Pollada Virtual", - description: "¡Apoya al equipo! Desde S/.50", - badge: "Nuevo", - featured: "shimmer", - }, - { - key: "chatbot", - href: "/servicios/chatbot", - label: "AI Chatbot", - description: "Automatiza tu atención 24/7", - }, - ], - }, - parameters: { - docs: { - description: { - story: "Featured effects also work in light mode.", - }, - }, - }, -}; +import type { Meta, StoryObj } from "@storybook/react"; +import * as React from "react"; + +import { + NavDropdown, + type NavDropdownItem, +} from "../../components/navigation/NavDropdown"; +import { VIEWPORT_MOBILE } from "../_shared/viewports"; + +const meta: Meta = { + title: "Navigation/NavDropdown", + component: NavDropdown, + tags: ["autodocs"], + parameters: { + layout: "centered", + docs: { + description: { + component: ` +A navigation dropdown component designed for navbar menus. + +## Features +- **Hover-to-open** on desktop, **click-to-open** on touch devices +- **150ms close delay** to prevent accidental closure +- **Keyboard navigation**: Arrow keys, Enter, Escape, Tab, Home, End +- **ARIA-compliant**: Proper roles, states, and keyboard support +- **Glassmorphism design**: Backdrop blur, subtle borders +- **Premium animations**: Smooth easing with scale and fade +- **Active state indicator**: Visual highlight for current page +- **Touch-friendly**: 44px minimum touch targets + +## Usage +\`\`\`tsx +import { NavDropdown } from '@cofoundy/ui' + + router.push(href)} +/> +\`\`\` + `, + }, + }, + }, + argTypes: { + variant: { + control: "radio", + options: ["dark", "light"], + description: "Theme variant", + }, + label: { + control: "text", + description: "Trigger button label", + }, + items: { + description: "Menu items array", + }, + onItemClick: { + action: "clicked", + description: "Callback when an item is clicked", + }, + }, + decorators: [ + (Story, context) => { + const isDark = context.args.variant === "dark"; + return ( +
+ +
+ ); + }, + ], +}; + +export default meta; +type Story = StoryObj; + +// Sample items for stories +const serviceItems: NavDropdownItem[] = [ + { + key: "landing", + href: "/servicios/landing-pages", + label: "Landing Pages", + description: "Tu landing lista en 7 días", + }, + { + key: "pollada", + href: "/servicios/pollada", + label: "Pollada Virtual", + description: "Portafolio desde S/.50", + }, + { + key: "chatbot", + href: "/servicios/chatbot", + label: "AI Chatbot", + description: "Automatiza tu atención 24/7", + }, + { + key: "fullstack", + href: "/servicios/fullstack", + label: "Desarrollo Fullstack", + description: "Apps a medida para tu negocio", + }, +]; + +const productItems: NavDropdownItem[] = [ + { + key: "timely", + href: "/productos/timely-ai", + label: "TimelyAI", + description: "Scheduling inteligente", + isActive: true, + }, + { + key: "inbox", + href: "/productos/inbox-ai", + label: "Tracta", + description: "Omnichannel inbox unificado", + }, + { + key: "pulse", + href: "/productos/pulse-ai", + label: "PulseAI", + description: "Voice agent para llamadas", + }, +]; + +// ============================================ +// Stories +// ============================================ + +export const Default: Story = { + args: { + label: "Servicios", + variant: "dark", + items: serviceItems, + }, +}; + +export const WithActiveItem: Story = { + args: { + label: "Productos", + variant: "dark", + items: productItems, + }, + parameters: { + docs: { + description: { + story: + "Items can have an `isActive` prop to indicate the current page. Shows a primary-colored left border and subtle background.", + }, + }, + }, +}; + +export const LightVariant: Story = { + args: { + label: "Servicios", + variant: "light", + items: serviceItems, + }, + parameters: { + docs: { + description: { + story: "Light variant for use on light backgrounds.", + }, + }, + }, +}; + +export const LightWithActive: Story = { + args: { + label: "Productos", + variant: "light", + items: productItems, + }, +}; + +export const MinimalItems: Story = { + args: { + label: "Resources", + variant: "dark", + items: [ + { key: "docs", href: "/docs", label: "Documentation" }, + { key: "blog", href: "/blog", label: "Blog" }, + ], + }, + parameters: { + docs: { + description: { + story: "Items without descriptions for a more compact menu.", + }, + }, + }, +}; + +export const CustomWidth: Story = { + args: { + label: "Solutions", + variant: "dark", + items: serviceItems, + menuClassName: "min-w-[360px]", + }, + parameters: { + docs: { + description: { + story: + "Use `menuClassName` to customize the dropdown width and other styles.", + }, + }, + }, +}; + +// Interactive demo with navbar context +export const InNavbar: Story = { + render: function Render() { + const [activeKey, setActiveKey] = React.useState("timely"); + + const items = productItems.map((item) => ({ + ...item, + isActive: item.key === activeKey, + })); + + return ( +
+ {/* Simulated navbar */} + +
+ Page content area. Click on Products dropdown to change active item. +
+ Active product: {activeKey} +
+
+ ); + }, + parameters: { + docs: { + description: { + story: + "Example of NavDropdown components used within a navbar context. The Products dropdown demonstrates interactive active state management.", + }, + }, + }, +}; + +// Mobile-first contract baseline — 375 px (iPhone SE). +// Verifies the 44 px tap-target claim from the component header against an +// actual mobile viewport. Required per packages/ui/CLAUDE.md. +export const MobileBaseline: Story = { + args: { + label: "Servicios", + variant: "dark", + items: serviceItems, + }, + parameters: { + viewport: VIEWPORT_MOBILE, + docs: { + description: { + story: + "Mobile baseline (375 px, iPhone SE). Trigger and menu items must keep ≥ 44×44 px touch targets — auditable visually at this viewport.", + }, + }, + }, +}; + +// Keyboard navigation demo +export const KeyboardNavigation: Story = { + args: { + label: "Keyboard Demo", + variant: "dark", + items: serviceItems, + }, + parameters: { + docs: { + description: { + story: ` +**Try these keyboard interactions:** +- **Tab** to focus the dropdown trigger +- **Enter/Space** to open the menu +- **Arrow Down/Up** to navigate items +- **Home/End** to jump to first/last item +- **Enter** to select an item +- **Escape** to close the menu +- **Tab** while open to close and move focus + `, + }, + }, + }, +}; + +// Touch device simulation +export const TouchBehavior: Story = { + args: { + label: "Tap to Open", + variant: "dark", + items: serviceItems, + }, + parameters: { + docs: { + description: { + story: + "On touch devices, the dropdown opens and closes on tap instead of hover. Test this on a mobile device or using browser dev tools touch simulation.", + }, + }, + }, +}; + +// ============================================ +// Featured Effects Stories +// ============================================ + +// Items with badge +const itemsWithBadge: NavDropdownItem[] = [ + { + key: "landing", + href: "/servicios/landing-pages", + label: "Landing Pages", + description: "Tu landing lista en 7 días", + }, + { + key: "pollada", + href: "/servicios/pollada", + label: "🍗 Pollada Virtual", + description: "¡Apoya al equipo! Desde S/.50", + badge: "Nuevo", + }, + { + key: "chatbot", + href: "/servicios/chatbot", + label: "AI Chatbot", + description: "Automatiza tu atención 24/7", + }, +]; + +export const WithBadge: Story = { + args: { + label: "Servicios", + variant: "dark", + items: itemsWithBadge, + }, + parameters: { + docs: { + description: { + story: "Items can have a `badge` prop to display a small tag (e.g., 'Nuevo', '🔥').", + }, + }, + }, +}; + +// Gold Shimmer Effect (card) +export const FeaturedShimmer: Story = { + args: { + label: "Servicios", + variant: "dark", + items: [ + { + key: "landing", + href: "/servicios/landing-pages", + label: "Landing Pages", + description: "Tu landing lista en 7 días", + }, + { + key: "pollada", + href: "/servicios/pollada", + label: "🍗 Pollada Virtual", + description: "¡Apoya al equipo! Desde S/.50", + badge: "Nuevo", + featured: "shimmer", + }, + { + key: "chatbot", + href: "/servicios/chatbot", + label: "AI Chatbot", + description: "Automatiza tu atención 24/7", + }, + ], + }, + parameters: { + docs: { + description: { + story: "**Gold Shimmer** - Horizontal gold light sweep animation on the card.", + }, + }, + }, +}; + +// Brand Gradient Border Effect (card) +export const FeaturedGradientBorder: Story = { + args: { + label: "Servicios", + variant: "dark", + items: [ + { + key: "landing", + href: "/servicios/landing-pages", + label: "Landing Pages", + description: "Tu landing lista en 7 días", + }, + { + key: "pollada", + href: "/servicios/pollada", + label: "🍗 Pollada Virtual", + description: "¡Apoya al equipo! Desde S/.50", + badge: "Nuevo", + featured: "gradient-border", + }, + { + key: "chatbot", + href: "/servicios/chatbot", + label: "AI Chatbot", + description: "Automatiza tu atención 24/7", + }, + ], + }, + parameters: { + docs: { + description: { + story: "**Brand Gradient Border** - Animated rotating border with Cofoundy brand colors.", + }, + }, + }, +}; + +// Both effects comparison +export const AllFeaturedEffects: Story = { + render: () => ( +
+
+

Gold Shimmer (Card)

+ +
+
+

Brand Gradient Border (Card)

+ +
+
+ ), + parameters: { + docs: { + description: { + story: "Comparison of both featured effects side by side.", + }, + }, + }, +}; + +// Gold Glow Text Effect (ShimmerText on label) +export const FeaturedGoldGlow: Story = { + args: { + label: "Servicios", + variant: "dark", + items: [ + { + key: "landing", + href: "/servicios/landing-pages", + label: "Landing Pages", + description: "Tu landing lista en 7 días", + }, + { + key: "pollada", + href: "/servicios/pollada", + label: "🍗 Pollada Virtual", + description: "¡Apoya al equipo! Desde S/.50", + badge: "Nuevo", + featured: "gold-glow", + }, + { + key: "chatbot", + href: "/servicios/chatbot", + label: "AI Chatbot", + description: "Automatiza tu atención 24/7", + }, + ], + }, + parameters: { + docs: { + description: { + story: "**Gold Glow** - Animated shimmer effect on the text itself using ShimmerText component.", + }, + }, + }, +}; + +// Light mode featured +export const FeaturedLightMode: Story = { + args: { + label: "Servicios", + variant: "light", + items: [ + { + key: "landing", + href: "/servicios/landing-pages", + label: "Landing Pages", + description: "Tu landing lista en 7 días", + }, + { + key: "pollada", + href: "/servicios/pollada", + label: "🍗 Pollada Virtual", + description: "¡Apoya al equipo! Desde S/.50", + badge: "Nuevo", + featured: "shimmer", + }, + { + key: "chatbot", + href: "/servicios/chatbot", + label: "AI Chatbot", + description: "Automatiza tu atención 24/7", + }, + ], + }, + parameters: { + docs: { + description: { + story: "Featured effects also work in light mode.", + }, + }, + }, +}; diff --git a/src/transports/SocketIOTransport.ts b/src/transports/SocketIOTransport.ts index 318bfee..8ccb7d8 100644 --- a/src/transports/SocketIOTransport.ts +++ b/src/transports/SocketIOTransport.ts @@ -1,555 +1,555 @@ -"use client"; - -import type { - Transport, - TransportOptions, - SocketIOTransportConfig, - AppointmentConfirmation, -} from "./types"; -import type { ConnectionStatus } from "../types"; -import { CircuitBreaker, type CircuitBreakerState } from "./circuitBreaker"; - -/** - * Socket.IO message types for Tracta backend - */ -interface SocketIOMessage { - content?: string; - text?: string; - message?: string; - type?: string; - // Tool events - tool?: string; - icon?: string; - success?: boolean; - // Slots/confirmation - date?: string; - slots?: string[]; - datetime?: string; - client_name?: string; - client_email?: string; - topic?: string; - event_id?: string; - event_link?: string; -} - -/** - * Socket.IO types (for dynamic import) - */ -interface SocketIOClient { - io: (url: string, opts?: Record) => SocketInstance; -} - -interface SocketInstance { - connected: boolean; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - on: (event: string, callback: (...args: any[]) => void) => void; - emit: (event: string, data: unknown) => void; - connect: () => void; - disconnect: () => void; - removeAllListeners: () => void; -} - -/** - * Map tool names to icons - */ -function getToolIcon(toolName: string): string { - const toolIcons: Record = { - schedule_appointment: "📅", - get_available_slots: "🕐", - search: "🔍", - web_search: "🌐", - calculator: "🔢", - send_email: "📧", - create_task: "✅", - }; - return toolIcons[toolName.toLowerCase()] || "⚡"; -} - -/** - * Dynamic import for socket.io-client - * This ensures the library is only loaded when Socket.IO transport is used - */ -async function loadSocketIO(): Promise { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const socketio = await import("socket.io-client" as any); - return socketio as unknown as SocketIOClient; -} - -/** - * Heartbeat configuration - */ -const HEARTBEAT_INTERVAL = 30000; // 30 seconds -const HEARTBEAT_TIMEOUT = 10000; // 10 seconds to receive pong - -/** - * Creates a Socket.IO transport instance for Tracta backend - */ -export async function createSocketIOTransport( - config: SocketIOTransportConfig, - options: TransportOptions -): Promise { - // Dynamic import of socket.io-client - const { io } = await loadSocketIO(); - - let socket: ReturnType | null = null; - let connectionStatus: ConnectionStatus = "disconnected"; - let reconnectAttempts = 0; - const messageQueue: Array<{ message: string; messageId?: string }> = []; - - // Heartbeat state - let heartbeatInterval: ReturnType | null = null; - let heartbeatTimeout: ReturnType | null = null; - let lastPongTime: number = Date.now(); - - // Circuit breaker for connection resilience - const circuitBreaker = new CircuitBreaker({ - failureThreshold: 5, - resetTimeout: 60000, // 60 seconds - halfOpenRequests: 1, - name: "SocketIO", - }); - - // Listen for circuit breaker state changes - circuitBreaker.onStateChange((state, stats) => { - console.log("[SocketIO] Circuit breaker state:", state, stats); - if (state === "OPEN") { - setConnectionStatus("error"); - onError?.(new Error(`Circuit breaker open after ${stats.failures} failures`)); - } - }); - - const { - url, - tenantId, - namespace = "/", - maxReconnectAttempts = 5, - reconnectDelay = 1000, - } = config; - - const { - sessionId, - onToken, - onStreamComplete, - onStreamError, - onMessageEnd, - onToolStart, - onToolEnd, - onSlots, - onConfirmation, - onMessage, - onMessageAck, - onTypingChange, - onConnect, - onDisconnect, - onError, - onMaxRetriesReached, - } = options; - - function setConnectionStatus(status: ConnectionStatus) { - const previousStatus = connectionStatus; - connectionStatus = status; - - // Fire callbacks on status changes - if (status === "connected" && previousStatus !== "connected") { - onConnect?.(); - } else if (status === "disconnected" && previousStatus === "connected") { - onDisconnect?.(); - } else if (status === "error") { - onError?.(new Error("Connection error")); - } - } - - function flushMessageQueue() { - if (socket?.connected) { - while (messageQueue.length > 0) { - const item = messageQueue.shift(); - if (item) { - socket.emit("widget_message", { - content: item.message, - tenant_id: tenantId, - session_id: sessionId, - client_message_id: item.messageId, - }); - } - } - } - } - - /** - * Start heartbeat monitoring to detect zombie connections - */ - function startHeartbeat() { - stopHeartbeat(); // Clear any existing heartbeat - - lastPongTime = Date.now(); - - heartbeatInterval = setInterval(() => { - if (!socket?.connected) { - stopHeartbeat(); - return; - } - - // Send ping - socket.emit("ping", {}); - console.debug("[SocketIO] Heartbeat ping sent"); - - // Set timeout for pong response - heartbeatTimeout = setTimeout(() => { - const timeSinceLastPong = Date.now() - lastPongTime; - if (timeSinceLastPong > HEARTBEAT_INTERVAL + HEARTBEAT_TIMEOUT) { - console.warn("[SocketIO] Heartbeat timeout - connection may be dead, forcing reconnect"); - // Force reconnection - if (socket) { - socket.disconnect(); - setTimeout(() => connect(), 1000); - } - } - }, HEARTBEAT_TIMEOUT); - }, HEARTBEAT_INTERVAL); - } - - /** - * Stop heartbeat monitoring - */ - function stopHeartbeat() { - if (heartbeatInterval) { - clearInterval(heartbeatInterval); - heartbeatInterval = null; - } - if (heartbeatTimeout) { - clearTimeout(heartbeatTimeout); - heartbeatTimeout = null; - } - } - - /** - * Handle pong response from server - */ - function handlePong() { - lastPongTime = Date.now(); - if (heartbeatTimeout) { - clearTimeout(heartbeatTimeout); - heartbeatTimeout = null; - } - console.debug("[SocketIO] Heartbeat pong received"); - } - - function handleAssistantMessage(data: SocketIOMessage) { - const content = data.content || data.text || data.message || ""; - - // Check if this is a streaming token or complete message - if (data.type === "token") { - onToken?.(content); - } else if (data.type === "done") { - onStreamComplete?.(); - } else if (data.type === "error") { - onStreamError?.(content || "Unknown error"); - } else if (data.type === "message_end") { - onMessageEnd?.(); - } else if (data.type === "tool_start" && data.tool) { - onToolStart?.(data.tool, data.icon || "⚡", content || `Ejecutando ${data.tool}...`); - } else if (data.type === "tool_end" && data.tool) { - onToolEnd?.(data.tool, data.success ?? true); - } else if (data.type === "slots" && data.date && data.slots) { - onSlots?.(data.date, data.slots); - } else if (data.type === "confirmation" && data.datetime) { - const confirmation: AppointmentConfirmation = { - datetime: data.datetime, - client_name: data.client_name || "", - client_email: data.client_email || "", - topic: data.topic || "", - event_id: data.event_id, - event_link: data.event_link, - }; - onConfirmation?.(confirmation); - } else { - // Complete message (non-streaming) - onMessage?.(content); - } - } - - function connect() { - if (!sessionId) return; - - // Check circuit breaker before attempting connection - if (!circuitBreaker.canExecute()) { - const stats = circuitBreaker.getStats(); - console.warn("[SocketIO] Circuit breaker is open, skipping connection attempt. Retry in:", circuitBreaker.getTimeUntilReset(), "ms"); - setConnectionStatus("error"); - - // Schedule retry when circuit breaker resets - const retryDelay = circuitBreaker.getTimeUntilReset(); - if (retryDelay > 0) { - setTimeout(() => { - if (circuitBreaker.canExecute()) { - connect(); - } - }, retryDelay + 1000); // Add 1s buffer - } - return; - } - - setConnectionStatus("connecting"); - - // Get browser timezone - const browserTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone; - - // Create Socket.IO connection - // Widget connections use auth: { widget: true } to bypass JWT auth - socket = io(url, { - path: "/socket.io", - transports: ["websocket", "polling"], - reconnection: true, - reconnectionAttempts: maxReconnectAttempts, - reconnectionDelay: reconnectDelay, - reconnectionDelayMax: 30000, // Max 30s between retries - randomizationFactor: 0.5, // Jitter to avoid thundering herd - timeout: 10000, // 10s timeout per connection attempt - auth: { - widget: true, // Required for Tracta to allow connection without JWT - }, - query: { - sessionId, - tenantId, - tz: browserTimezone, - }, - }); - - socket.on("connect", () => { - // Record successful connection with circuit breaker - circuitBreaker.recordSuccess(); - - // Send widget_init event to initialize the session - socket?.emit("widget_init", { - tenant_id: tenantId, - session_id: sessionId, - visitor_name: "Visitor", - metadata: { - page_url: typeof window !== "undefined" ? window.location.href : "", - page_title: typeof document !== "undefined" ? document.title : "", - }, - }); - - setConnectionStatus("connected"); - reconnectAttempts = 0; - onConnect?.(); - flushMessageQueue(); - - // Start heartbeat monitoring - startHeartbeat(); - }); - - // Listen for pong responses (server should echo back ping) - socket.on("pong", handlePong); - - socket.on("disconnect", (reason: string) => { - // Stop heartbeat on disconnect - stopHeartbeat(); - - setConnectionStatus("disconnected"); - onDisconnect?.(); - - // Check if this was a server disconnect (not user-initiated) - if (reason === "io server disconnect") { - // Server forced disconnect, attempt reconnection - socket?.connect(); - } - }); - - socket.on("connect_error", (error: Error) => { - // Record failure with circuit breaker - circuitBreaker.recordFailure(); - - setConnectionStatus("error"); - onError?.(error); - - reconnectAttempts++; - if (reconnectAttempts >= maxReconnectAttempts) { - onMaxRetriesReached?.(); - } - }); - - // Tracta widget events - socket.on("widget:session", (data: { sessionId: string; conversationId: string | null }) => { - // Session initialized successfully - console.log("[SocketIO] Widget session initialized:", data); - }); - - // Listen for messages (Tracta emits message:new) - socket.on("message:new", (data: SocketIOMessage) => { - // Only handle if it's from AI/agent (not echoed user message) - if (data.type !== "user" && (data as { sender?: { type?: string } }).sender?.type !== "visitor") { - handleAssistantMessage(data); - } - }); - - // Legacy event names for compatibility with other backends - socket.on("assistant_message", handleAssistantMessage); - socket.on("message", (data: SocketIOMessage) => { - if (data.type !== "user") { - handleAssistantMessage(data); - } - }); - socket.on("response", handleAssistantMessage); - socket.on("stream", handleAssistantMessage); - - // AG-UI streaming events (for AI responses) - socket.on("ag_ui:event", (event: Record) => { - const eventType = event.type as string; - - // Message events - if (eventType === "TEXT_MESSAGE_CONTENT") { - onToken?.((event as { delta?: string }).delta || ""); - } else if (eventType === "TEXT_MESSAGE_END") { - onStreamComplete?.(); - } else if (eventType === "RUN_ERROR") { - onStreamError?.((event as { message?: string }).message || "Unknown error"); - } - // Tool events - else if (eventType === "TOOL_CALL_START") { - const toolName = (event as { toolCallName?: string }).toolCallName || "tool"; - const toolIcon = getToolIcon(toolName); - onToolStart?.(toolName, toolIcon, `Ejecutando ${toolName}...`); - } else if (eventType === "TOOL_CALL_END") { - const toolName = (event as { toolCallName?: string }).toolCallName; - if (toolName) { - onToolEnd?.(toolName, true); - } - } else if (eventType === "TOOL_CALL_RESULT") { - const toolCallId = (event as { toolCallId?: string }).toolCallId || ""; - const resultStr = (event as { result?: string }).result || ""; - - // Try to parse the result to check for scheduling confirmation - try { - const result = typeof resultStr === "string" ? JSON.parse(resultStr) : resultStr; - - // Check if this is a scheduling confirmation from schedule_appointment tool - // Backend schema: { success: true, datetime, client_name, client_email, topic, event_id?, event_link? } - if (result?.success === true && result.datetime) { - const confirmation: AppointmentConfirmation = { - datetime: result.datetime, - client_name: result.client_name || "", - client_email: result.client_email || "", - topic: result.topic || "", - event_id: result.event_id, - event_link: result.event_link, - }; - onConfirmation?.(confirmation); - } - } catch { - // Result wasn't JSON or couldn't be parsed - that's OK - console.log("[SocketIO] Tool result not parseable:", toolCallId); - } - } - }); - - // Typing indicator — server-driven. The backend sends both edges - // (true at turn start, false at turn end), so this drives the indicator - // for the whole turn across multi-bubble responses. - socket.on("agent:typing", (data: { active: boolean }) => { - onTypingChange?.(data.active); - }); - - // Message delivery acknowledgment - socket.on("message:ack", (data: { messageId: string; status: string; timestamp?: string; error?: string }) => { - console.log("[SocketIO] Message acknowledged:", data); - onMessageAck?.({ - messageId: data.messageId, - status: data.status as "received" | "delivered" | "failed", - timestamp: data.timestamp, - error: data.error, - }); - }); - } - - function sendMessage(message: string, messageId?: string) { - if (socket?.connected) { - // Use widget_message event for Tracta backend - // Include messageId for delivery acknowledgment - socket.emit("widget_message", { - content: message, - tenant_id: tenantId, - session_id: sessionId, - client_message_id: messageId, - }); - } else { - // Queue message for sending when connected - messageQueue.push({ message, messageId }); - } - } - - function reconnect() { - reconnectAttempts = 0; - if (socket) { - socket.disconnect(); - } - connect(); - } - - function disconnect() { - stopHeartbeat(); - circuitBreaker.dispose(); - if (socket) { - socket.removeAllListeners(); - socket.disconnect(); - socket = null; - } - } - - // Setup visibility change handler - function handleVisibilityChange() { - if ( - typeof document !== "undefined" && - document.visibilityState === "visible" && - (connectionStatus === "disconnected" || connectionStatus === "error") - ) { - reconnect(); - } - } - - // Auto-connect - connect(); - - // Listen for visibility changes - if (typeof document !== "undefined") { - document.addEventListener("visibilitychange", handleVisibilityChange); - } - - return { - sendMessage, - get connectionStatus() { - return connectionStatus; - }, - reconnect, - disconnect: () => { - if (typeof document !== "undefined") { - document.removeEventListener("visibilitychange", handleVisibilityChange); - } - disconnect(); - }, - // Circuit breaker access - get circuitBreakerState(): CircuitBreakerState { - return circuitBreaker.getState(); - }, - get circuitBreakerStats() { - return circuitBreaker.getStats(); - }, - resetCircuitBreaker: () => { - circuitBreaker.forceState("CLOSED"); - }, - }; -} - -/** - * Type guard to check if config is Socket.IO transport - */ -export function isSocketIOConfig( - config: unknown -): config is SocketIOTransportConfig { - return ( - typeof config === "object" && - config !== null && - "type" in config && - (config as { type: string }).type === "socketio" - ); -} +"use client"; + +import type { + Transport, + TransportOptions, + SocketIOTransportConfig, + AppointmentConfirmation, +} from "./types"; +import type { ConnectionStatus } from "../types"; +import { CircuitBreaker, type CircuitBreakerState } from "./circuitBreaker"; + +/** + * Socket.IO message types for Tracta backend + */ +interface SocketIOMessage { + content?: string; + text?: string; + message?: string; + type?: string; + // Tool events + tool?: string; + icon?: string; + success?: boolean; + // Slots/confirmation + date?: string; + slots?: string[]; + datetime?: string; + client_name?: string; + client_email?: string; + topic?: string; + event_id?: string; + event_link?: string; +} + +/** + * Socket.IO types (for dynamic import) + */ +interface SocketIOClient { + io: (url: string, opts?: Record) => SocketInstance; +} + +interface SocketInstance { + connected: boolean; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + on: (event: string, callback: (...args: any[]) => void) => void; + emit: (event: string, data: unknown) => void; + connect: () => void; + disconnect: () => void; + removeAllListeners: () => void; +} + +/** + * Map tool names to icons + */ +function getToolIcon(toolName: string): string { + const toolIcons: Record = { + schedule_appointment: "📅", + get_available_slots: "🕐", + search: "🔍", + web_search: "🌐", + calculator: "🔢", + send_email: "📧", + create_task: "✅", + }; + return toolIcons[toolName.toLowerCase()] || "⚡"; +} + +/** + * Dynamic import for socket.io-client + * This ensures the library is only loaded when Socket.IO transport is used + */ +async function loadSocketIO(): Promise { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const socketio = await import("socket.io-client" as any); + return socketio as unknown as SocketIOClient; +} + +/** + * Heartbeat configuration + */ +const HEARTBEAT_INTERVAL = 30000; // 30 seconds +const HEARTBEAT_TIMEOUT = 10000; // 10 seconds to receive pong + +/** + * Creates a Socket.IO transport instance for Tracta backend + */ +export async function createSocketIOTransport( + config: SocketIOTransportConfig, + options: TransportOptions +): Promise { + // Dynamic import of socket.io-client + const { io } = await loadSocketIO(); + + let socket: ReturnType | null = null; + let connectionStatus: ConnectionStatus = "disconnected"; + let reconnectAttempts = 0; + const messageQueue: Array<{ message: string; messageId?: string }> = []; + + // Heartbeat state + let heartbeatInterval: ReturnType | null = null; + let heartbeatTimeout: ReturnType | null = null; + let lastPongTime: number = Date.now(); + + // Circuit breaker for connection resilience + const circuitBreaker = new CircuitBreaker({ + failureThreshold: 5, + resetTimeout: 60000, // 60 seconds + halfOpenRequests: 1, + name: "SocketIO", + }); + + // Listen for circuit breaker state changes + circuitBreaker.onStateChange((state, stats) => { + console.log("[SocketIO] Circuit breaker state:", state, stats); + if (state === "OPEN") { + setConnectionStatus("error"); + onError?.(new Error(`Circuit breaker open after ${stats.failures} failures`)); + } + }); + + const { + url, + tenantId, + namespace = "/", + maxReconnectAttempts = 5, + reconnectDelay = 1000, + } = config; + + const { + sessionId, + onToken, + onStreamComplete, + onStreamError, + onMessageEnd, + onToolStart, + onToolEnd, + onSlots, + onConfirmation, + onMessage, + onMessageAck, + onTypingChange, + onConnect, + onDisconnect, + onError, + onMaxRetriesReached, + } = options; + + function setConnectionStatus(status: ConnectionStatus) { + const previousStatus = connectionStatus; + connectionStatus = status; + + // Fire callbacks on status changes + if (status === "connected" && previousStatus !== "connected") { + onConnect?.(); + } else if (status === "disconnected" && previousStatus === "connected") { + onDisconnect?.(); + } else if (status === "error") { + onError?.(new Error("Connection error")); + } + } + + function flushMessageQueue() { + if (socket?.connected) { + while (messageQueue.length > 0) { + const item = messageQueue.shift(); + if (item) { + socket.emit("widget_message", { + content: item.message, + tenant_id: tenantId, + session_id: sessionId, + client_message_id: item.messageId, + }); + } + } + } + } + + /** + * Start heartbeat monitoring to detect zombie connections + */ + function startHeartbeat() { + stopHeartbeat(); // Clear any existing heartbeat + + lastPongTime = Date.now(); + + heartbeatInterval = setInterval(() => { + if (!socket?.connected) { + stopHeartbeat(); + return; + } + + // Send ping + socket.emit("ping", {}); + console.debug("[SocketIO] Heartbeat ping sent"); + + // Set timeout for pong response + heartbeatTimeout = setTimeout(() => { + const timeSinceLastPong = Date.now() - lastPongTime; + if (timeSinceLastPong > HEARTBEAT_INTERVAL + HEARTBEAT_TIMEOUT) { + console.warn("[SocketIO] Heartbeat timeout - connection may be dead, forcing reconnect"); + // Force reconnection + if (socket) { + socket.disconnect(); + setTimeout(() => connect(), 1000); + } + } + }, HEARTBEAT_TIMEOUT); + }, HEARTBEAT_INTERVAL); + } + + /** + * Stop heartbeat monitoring + */ + function stopHeartbeat() { + if (heartbeatInterval) { + clearInterval(heartbeatInterval); + heartbeatInterval = null; + } + if (heartbeatTimeout) { + clearTimeout(heartbeatTimeout); + heartbeatTimeout = null; + } + } + + /** + * Handle pong response from server + */ + function handlePong() { + lastPongTime = Date.now(); + if (heartbeatTimeout) { + clearTimeout(heartbeatTimeout); + heartbeatTimeout = null; + } + console.debug("[SocketIO] Heartbeat pong received"); + } + + function handleAssistantMessage(data: SocketIOMessage) { + const content = data.content || data.text || data.message || ""; + + // Check if this is a streaming token or complete message + if (data.type === "token") { + onToken?.(content); + } else if (data.type === "done") { + onStreamComplete?.(); + } else if (data.type === "error") { + onStreamError?.(content || "Unknown error"); + } else if (data.type === "message_end") { + onMessageEnd?.(); + } else if (data.type === "tool_start" && data.tool) { + onToolStart?.(data.tool, data.icon || "⚡", content || `Ejecutando ${data.tool}...`); + } else if (data.type === "tool_end" && data.tool) { + onToolEnd?.(data.tool, data.success ?? true); + } else if (data.type === "slots" && data.date && data.slots) { + onSlots?.(data.date, data.slots); + } else if (data.type === "confirmation" && data.datetime) { + const confirmation: AppointmentConfirmation = { + datetime: data.datetime, + client_name: data.client_name || "", + client_email: data.client_email || "", + topic: data.topic || "", + event_id: data.event_id, + event_link: data.event_link, + }; + onConfirmation?.(confirmation); + } else { + // Complete message (non-streaming) + onMessage?.(content); + } + } + + function connect() { + if (!sessionId) return; + + // Check circuit breaker before attempting connection + if (!circuitBreaker.canExecute()) { + const stats = circuitBreaker.getStats(); + console.warn("[SocketIO] Circuit breaker is open, skipping connection attempt. Retry in:", circuitBreaker.getTimeUntilReset(), "ms"); + setConnectionStatus("error"); + + // Schedule retry when circuit breaker resets + const retryDelay = circuitBreaker.getTimeUntilReset(); + if (retryDelay > 0) { + setTimeout(() => { + if (circuitBreaker.canExecute()) { + connect(); + } + }, retryDelay + 1000); // Add 1s buffer + } + return; + } + + setConnectionStatus("connecting"); + + // Get browser timezone + const browserTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone; + + // Create Socket.IO connection + // Widget connections use auth: { widget: true } to bypass JWT auth + socket = io(url, { + path: "/socket.io", + transports: ["websocket", "polling"], + reconnection: true, + reconnectionAttempts: maxReconnectAttempts, + reconnectionDelay: reconnectDelay, + reconnectionDelayMax: 30000, // Max 30s between retries + randomizationFactor: 0.5, // Jitter to avoid thundering herd + timeout: 10000, // 10s timeout per connection attempt + auth: { + widget: true, // Required for Tracta to allow connection without JWT + }, + query: { + sessionId, + tenantId, + tz: browserTimezone, + }, + }); + + socket.on("connect", () => { + // Record successful connection with circuit breaker + circuitBreaker.recordSuccess(); + + // Send widget_init event to initialize the session + socket?.emit("widget_init", { + tenant_id: tenantId, + session_id: sessionId, + visitor_name: "Visitor", + metadata: { + page_url: typeof window !== "undefined" ? window.location.href : "", + page_title: typeof document !== "undefined" ? document.title : "", + }, + }); + + setConnectionStatus("connected"); + reconnectAttempts = 0; + onConnect?.(); + flushMessageQueue(); + + // Start heartbeat monitoring + startHeartbeat(); + }); + + // Listen for pong responses (server should echo back ping) + socket.on("pong", handlePong); + + socket.on("disconnect", (reason: string) => { + // Stop heartbeat on disconnect + stopHeartbeat(); + + setConnectionStatus("disconnected"); + onDisconnect?.(); + + // Check if this was a server disconnect (not user-initiated) + if (reason === "io server disconnect") { + // Server forced disconnect, attempt reconnection + socket?.connect(); + } + }); + + socket.on("connect_error", (error: Error) => { + // Record failure with circuit breaker + circuitBreaker.recordFailure(); + + setConnectionStatus("error"); + onError?.(error); + + reconnectAttempts++; + if (reconnectAttempts >= maxReconnectAttempts) { + onMaxRetriesReached?.(); + } + }); + + // Tracta widget events + socket.on("widget:session", (data: { sessionId: string; conversationId: string | null }) => { + // Session initialized successfully + console.log("[SocketIO] Widget session initialized:", data); + }); + + // Listen for messages (Tracta emits message:new) + socket.on("message:new", (data: SocketIOMessage) => { + // Only handle if it's from AI/agent (not echoed user message) + if (data.type !== "user" && (data as { sender?: { type?: string } }).sender?.type !== "visitor") { + handleAssistantMessage(data); + } + }); + + // Legacy event names for compatibility with other backends + socket.on("assistant_message", handleAssistantMessage); + socket.on("message", (data: SocketIOMessage) => { + if (data.type !== "user") { + handleAssistantMessage(data); + } + }); + socket.on("response", handleAssistantMessage); + socket.on("stream", handleAssistantMessage); + + // AG-UI streaming events (for AI responses) + socket.on("ag_ui:event", (event: Record) => { + const eventType = event.type as string; + + // Message events + if (eventType === "TEXT_MESSAGE_CONTENT") { + onToken?.((event as { delta?: string }).delta || ""); + } else if (eventType === "TEXT_MESSAGE_END") { + onStreamComplete?.(); + } else if (eventType === "RUN_ERROR") { + onStreamError?.((event as { message?: string }).message || "Unknown error"); + } + // Tool events + else if (eventType === "TOOL_CALL_START") { + const toolName = (event as { toolCallName?: string }).toolCallName || "tool"; + const toolIcon = getToolIcon(toolName); + onToolStart?.(toolName, toolIcon, `Ejecutando ${toolName}...`); + } else if (eventType === "TOOL_CALL_END") { + const toolName = (event as { toolCallName?: string }).toolCallName; + if (toolName) { + onToolEnd?.(toolName, true); + } + } else if (eventType === "TOOL_CALL_RESULT") { + const toolCallId = (event as { toolCallId?: string }).toolCallId || ""; + const resultStr = (event as { result?: string }).result || ""; + + // Try to parse the result to check for scheduling confirmation + try { + const result = typeof resultStr === "string" ? JSON.parse(resultStr) : resultStr; + + // Check if this is a scheduling confirmation from schedule_appointment tool + // Backend schema: { success: true, datetime, client_name, client_email, topic, event_id?, event_link? } + if (result?.success === true && result.datetime) { + const confirmation: AppointmentConfirmation = { + datetime: result.datetime, + client_name: result.client_name || "", + client_email: result.client_email || "", + topic: result.topic || "", + event_id: result.event_id, + event_link: result.event_link, + }; + onConfirmation?.(confirmation); + } + } catch { + // Result wasn't JSON or couldn't be parsed - that's OK + console.log("[SocketIO] Tool result not parseable:", toolCallId); + } + } + }); + + // Typing indicator — server-driven. The backend sends both edges + // (true at turn start, false at turn end), so this drives the indicator + // for the whole turn across multi-bubble responses. + socket.on("agent:typing", (data: { active: boolean }) => { + onTypingChange?.(data.active); + }); + + // Message delivery acknowledgment + socket.on("message:ack", (data: { messageId: string; status: string; timestamp?: string; error?: string }) => { + console.log("[SocketIO] Message acknowledged:", data); + onMessageAck?.({ + messageId: data.messageId, + status: data.status as "received" | "delivered" | "failed", + timestamp: data.timestamp, + error: data.error, + }); + }); + } + + function sendMessage(message: string, messageId?: string) { + if (socket?.connected) { + // Use widget_message event for Tracta backend + // Include messageId for delivery acknowledgment + socket.emit("widget_message", { + content: message, + tenant_id: tenantId, + session_id: sessionId, + client_message_id: messageId, + }); + } else { + // Queue message for sending when connected + messageQueue.push({ message, messageId }); + } + } + + function reconnect() { + reconnectAttempts = 0; + if (socket) { + socket.disconnect(); + } + connect(); + } + + function disconnect() { + stopHeartbeat(); + circuitBreaker.dispose(); + if (socket) { + socket.removeAllListeners(); + socket.disconnect(); + socket = null; + } + } + + // Setup visibility change handler + function handleVisibilityChange() { + if ( + typeof document !== "undefined" && + document.visibilityState === "visible" && + (connectionStatus === "disconnected" || connectionStatus === "error") + ) { + reconnect(); + } + } + + // Auto-connect + connect(); + + // Listen for visibility changes + if (typeof document !== "undefined") { + document.addEventListener("visibilitychange", handleVisibilityChange); + } + + return { + sendMessage, + get connectionStatus() { + return connectionStatus; + }, + reconnect, + disconnect: () => { + if (typeof document !== "undefined") { + document.removeEventListener("visibilitychange", handleVisibilityChange); + } + disconnect(); + }, + // Circuit breaker access + get circuitBreakerState(): CircuitBreakerState { + return circuitBreaker.getState(); + }, + get circuitBreakerStats() { + return circuitBreaker.getStats(); + }, + resetCircuitBreaker: () => { + circuitBreaker.forceState("CLOSED"); + }, + }; +} + +/** + * Type guard to check if config is Socket.IO transport + */ +export function isSocketIOConfig( + config: unknown +): config is SocketIOTransportConfig { + return ( + typeof config === "object" && + config !== null && + "type" in config && + (config as { type: string }).type === "socketio" + ); +} diff --git a/src/transports/types.ts b/src/transports/types.ts index e48df00..7545f6c 100644 --- a/src/transports/types.ts +++ b/src/transports/types.ts @@ -1,203 +1,203 @@ -import type { ConnectionStatus } from "../types"; - -/** - * Appointment confirmation from backend - */ -export interface AppointmentConfirmation { - datetime: string; - client_name: string; - client_email: string; - topic: string; - event_id?: string; - event_link?: string; -} - -/** - * Message acknowledgment status - */ -export type MessageAckStatus = "received" | "delivered" | "failed"; - -/** - * Message acknowledgment event - */ -export interface MessageAck { - messageId: string; - status: MessageAckStatus; - timestamp?: string; - error?: string; -} - -/** - * Transport event callbacks - */ -export interface TransportCallbacks { - /** Called for each streamed token */ - onToken?: (content: string) => void; - /** Called when stream completes */ - onStreamComplete?: () => void; - /** Called on error (including stream errors) */ - onStreamError?: (error: string) => void; - /** Called when message ends (before tool starts) */ - onMessageEnd?: () => void; - /** Called when a tool starts executing */ - onToolStart?: (tool: string, icon: string, text: string) => void; - /** Called when a tool finishes */ - onToolEnd?: (tool: string, success: boolean) => void; - /** Called when slots are available */ - onSlots?: (date: string, slots: string[]) => void; - /** Called when appointment is confirmed */ - onConfirmation?: (confirmation: AppointmentConfirmation) => void; - /** Legacy: Called for non-streaming messages */ - onMessage?: (message: string) => void; - /** Called when message delivery is acknowledged */ - onMessageAck?: (ack: MessageAck) => void; - /** - * Called when the server signals a change in the agent's typing state. - * The backend emits both edges: `true` at turn start and `false` at turn end. - * This is the authoritative signal that a turn is in progress — it keeps the - * typing indicator up across a whole multi-bubble turn (one bubble per - * `send_message` tool call) instead of flickering off between bubbles. - */ - onTypingChange?: (active: boolean) => void; - /** Connection lifecycle callbacks */ - onConnect?: () => void; - onDisconnect?: () => void; - onError?: (error: Event | Error) => void; - onMaxRetriesReached?: () => void; -} - -/** - * Transport configuration options - */ -export interface TransportOptions extends TransportCallbacks { - sessionId: string; - maxReconnectAttempts?: number; - reconnectDelay?: number; -} - -/** - * Circuit breaker state - */ -export type TransportCircuitBreakerState = "CLOSED" | "OPEN" | "HALF_OPEN"; - -/** - * Circuit breaker statistics - */ -export interface TransportCircuitBreakerStats { - state: TransportCircuitBreakerState; - failures: number; - successes: number; - lastFailureTime: number | null; - lastStateChange: number; -} - -/** - * Transport interface - all transport implementations must conform to this - */ -export interface Transport { - /** Send a message through the transport with optional message ID for acknowledgment */ - sendMessage: (message: string, messageId?: string) => void; - /** Current connection status */ - connectionStatus: ConnectionStatus; - /** Manually trigger reconnection */ - reconnect: () => void; - /** Cleanup resources */ - disconnect: () => void; - /** Circuit breaker state (optional, for transports with circuit breaker) */ - readonly circuitBreakerState?: TransportCircuitBreakerState; - /** Circuit breaker statistics (optional) */ - readonly circuitBreakerStats?: TransportCircuitBreakerStats; - /** Reset circuit breaker (optional) */ - resetCircuitBreaker?: () => void; -} - -/** - * Transport type enum - */ -export type TransportType = "websocket" | "socketio" | "agui"; - -/** - * Base transport configuration - */ -interface BaseTransportConfig { - /** Transport type */ - type: TransportType; - /** Server URL */ - url: string; - /** Session ID (optional - auto-generated if not provided) */ - sessionId?: string; - /** Max reconnection attempts */ - maxReconnectAttempts?: number; - /** Delay between reconnection attempts (ms) */ - reconnectDelay?: number; -} - -/** - * WebSocket transport configuration - */ -export interface WebSocketTransportConfig extends BaseTransportConfig { - type: "websocket"; -} - -/** - * Socket.IO transport configuration (for Tracta) - */ -export interface SocketIOTransportConfig extends BaseTransportConfig { - type: "socketio"; - /** Tenant ID for Tracta */ - tenantId: string; - /** Namespace (optional) */ - namespace?: string; -} - -/** - * AG-UI transport configuration (SSE streaming) - */ -export interface AGUITransportConfig extends BaseTransportConfig { - type: "agui"; - /** Auth token */ - authToken?: string; -} - -/** - * Union type for all transport configurations - */ -export type TransportConfig = - | WebSocketTransportConfig - | SocketIOTransportConfig - | AGUITransportConfig; - -/** - * Floating widget position - */ -export type FloatingPosition = - | "bottom-right" - | "bottom-left" - | "top-right" - | "top-left"; - -/** - * Floating mode configuration - */ -export interface FloatingConfig { - /** Position of the floating launcher */ - position?: FloatingPosition; - /** Show unread message badge */ - showBadge?: boolean; - /** Initial open state */ - defaultOpen?: boolean; - /** Custom launcher icon URL */ - launcherIcon?: string; - /** Offset from edges (px) */ - offset?: { - x?: number; - y?: number; - }; - /** Z-index for floating elements */ - zIndex?: number; -} - -/** - * Widget display mode - */ -export type WidgetMode = "embedded" | "floating"; +import type { ConnectionStatus } from "../types"; + +/** + * Appointment confirmation from backend + */ +export interface AppointmentConfirmation { + datetime: string; + client_name: string; + client_email: string; + topic: string; + event_id?: string; + event_link?: string; +} + +/** + * Message acknowledgment status + */ +export type MessageAckStatus = "received" | "delivered" | "failed"; + +/** + * Message acknowledgment event + */ +export interface MessageAck { + messageId: string; + status: MessageAckStatus; + timestamp?: string; + error?: string; +} + +/** + * Transport event callbacks + */ +export interface TransportCallbacks { + /** Called for each streamed token */ + onToken?: (content: string) => void; + /** Called when stream completes */ + onStreamComplete?: () => void; + /** Called on error (including stream errors) */ + onStreamError?: (error: string) => void; + /** Called when message ends (before tool starts) */ + onMessageEnd?: () => void; + /** Called when a tool starts executing */ + onToolStart?: (tool: string, icon: string, text: string) => void; + /** Called when a tool finishes */ + onToolEnd?: (tool: string, success: boolean) => void; + /** Called when slots are available */ + onSlots?: (date: string, slots: string[]) => void; + /** Called when appointment is confirmed */ + onConfirmation?: (confirmation: AppointmentConfirmation) => void; + /** Legacy: Called for non-streaming messages */ + onMessage?: (message: string) => void; + /** Called when message delivery is acknowledged */ + onMessageAck?: (ack: MessageAck) => void; + /** + * Called when the server signals a change in the agent's typing state. + * The backend emits both edges: `true` at turn start and `false` at turn end. + * This is the authoritative signal that a turn is in progress — it keeps the + * typing indicator up across a whole multi-bubble turn (one bubble per + * `send_message` tool call) instead of flickering off between bubbles. + */ + onTypingChange?: (active: boolean) => void; + /** Connection lifecycle callbacks */ + onConnect?: () => void; + onDisconnect?: () => void; + onError?: (error: Event | Error) => void; + onMaxRetriesReached?: () => void; +} + +/** + * Transport configuration options + */ +export interface TransportOptions extends TransportCallbacks { + sessionId: string; + maxReconnectAttempts?: number; + reconnectDelay?: number; +} + +/** + * Circuit breaker state + */ +export type TransportCircuitBreakerState = "CLOSED" | "OPEN" | "HALF_OPEN"; + +/** + * Circuit breaker statistics + */ +export interface TransportCircuitBreakerStats { + state: TransportCircuitBreakerState; + failures: number; + successes: number; + lastFailureTime: number | null; + lastStateChange: number; +} + +/** + * Transport interface - all transport implementations must conform to this + */ +export interface Transport { + /** Send a message through the transport with optional message ID for acknowledgment */ + sendMessage: (message: string, messageId?: string) => void; + /** Current connection status */ + connectionStatus: ConnectionStatus; + /** Manually trigger reconnection */ + reconnect: () => void; + /** Cleanup resources */ + disconnect: () => void; + /** Circuit breaker state (optional, for transports with circuit breaker) */ + readonly circuitBreakerState?: TransportCircuitBreakerState; + /** Circuit breaker statistics (optional) */ + readonly circuitBreakerStats?: TransportCircuitBreakerStats; + /** Reset circuit breaker (optional) */ + resetCircuitBreaker?: () => void; +} + +/** + * Transport type enum + */ +export type TransportType = "websocket" | "socketio" | "agui"; + +/** + * Base transport configuration + */ +interface BaseTransportConfig { + /** Transport type */ + type: TransportType; + /** Server URL */ + url: string; + /** Session ID (optional - auto-generated if not provided) */ + sessionId?: string; + /** Max reconnection attempts */ + maxReconnectAttempts?: number; + /** Delay between reconnection attempts (ms) */ + reconnectDelay?: number; +} + +/** + * WebSocket transport configuration + */ +export interface WebSocketTransportConfig extends BaseTransportConfig { + type: "websocket"; +} + +/** + * Socket.IO transport configuration (for Tracta) + */ +export interface SocketIOTransportConfig extends BaseTransportConfig { + type: "socketio"; + /** Tenant ID for Tracta */ + tenantId: string; + /** Namespace (optional) */ + namespace?: string; +} + +/** + * AG-UI transport configuration (SSE streaming) + */ +export interface AGUITransportConfig extends BaseTransportConfig { + type: "agui"; + /** Auth token */ + authToken?: string; +} + +/** + * Union type for all transport configurations + */ +export type TransportConfig = + | WebSocketTransportConfig + | SocketIOTransportConfig + | AGUITransportConfig; + +/** + * Floating widget position + */ +export type FloatingPosition = + | "bottom-right" + | "bottom-left" + | "top-right" + | "top-left"; + +/** + * Floating mode configuration + */ +export interface FloatingConfig { + /** Position of the floating launcher */ + position?: FloatingPosition; + /** Show unread message badge */ + showBadge?: boolean; + /** Initial open state */ + defaultOpen?: boolean; + /** Custom launcher icon URL */ + launcherIcon?: string; + /** Offset from edges (px) */ + offset?: { + x?: number; + y?: number; + }; + /** Z-index for floating elements */ + zIndex?: number; +} + +/** + * Widget display mode + */ +export type WidgetMode = "embedded" | "floating";