vpschatbotwidget 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/Chatbot.svg +1 -0
  2. package/README.md +86 -0
  3. package/dist/assets/index-C0fUDi2s.css +1 -0
  4. package/dist/assets/index-foGq5_Av.js +159 -0
  5. package/dist/index.html +17 -0
  6. package/index.html +16 -0
  7. package/package.json +47 -0
  8. package/src/App.tsx +85 -0
  9. package/src/chatbot/api/chatbot-api.ts +258 -0
  10. package/src/chatbot/api/chatbot-types.ts +145 -0
  11. package/src/chatbot/chatbot.test.tsx +274 -0
  12. package/src/chatbot/config/colors.ts +166 -0
  13. package/src/chatbot/config/suggestions.ts +21 -0
  14. package/src/chatbot/core/ChatContext.tsx +43 -0
  15. package/src/chatbot/core/ChatEmptyState.tsx +21 -0
  16. package/src/chatbot/core/ChatError.tsx +26 -0
  17. package/src/chatbot/core/ChatHeader.tsx +108 -0
  18. package/src/chatbot/core/ChatInput.tsx +103 -0
  19. package/src/chatbot/core/ChatMarkdown.tsx +87 -0
  20. package/src/chatbot/core/ChatMessage.tsx +115 -0
  21. package/src/chatbot/core/ChatMessageList.tsx +47 -0
  22. package/src/chatbot/core/ChatPanel.tsx +66 -0
  23. package/src/chatbot/core/ChatProvider.tsx +185 -0
  24. package/src/chatbot/core/ChatSuggestions.tsx +71 -0
  25. package/src/chatbot/core/ChatTicketConfirmation.tsx +59 -0
  26. package/src/chatbot/core/ChatTypingIndicator.tsx +16 -0
  27. package/src/chatbot/core/ticket-intent.ts +12 -0
  28. package/src/chatbot/embedded/EmbeddedChatbot.tsx +47 -0
  29. package/src/chatbot/embedded/EmbeddedChatbotPanel.tsx +56 -0
  30. package/src/chatbot/embedded/EmbeddedChatbotTrigger.tsx +167 -0
  31. package/src/chatbot/hooks/useChatbot.ts +5 -0
  32. package/src/chatbot/index.ts +7 -0
  33. package/src/chatbot/widget/ChatbotWidget.tsx +43 -0
  34. package/src/chatbot/widget/ChatbotWidgetPanel.tsx +39 -0
  35. package/src/chatbot/widget/ChatbotWidgetTrigger.tsx +32 -0
  36. package/src/components/AgentSummaryCard.tsx +37 -0
  37. package/src/components/ChatHeader.tsx +142 -0
  38. package/src/components/ChatInput.tsx +123 -0
  39. package/src/components/ChatWidget.tsx +295 -0
  40. package/src/components/ConnectingStatus.tsx +16 -0
  41. package/src/components/EnvBadge.tsx +103 -0
  42. package/src/components/FeedbackRatingCard.tsx +123 -0
  43. package/src/components/MessageItem.tsx +157 -0
  44. package/src/components/MessageList.tsx +143 -0
  45. package/src/components/OrderTrackingCard.tsx +104 -0
  46. package/src/components/QuickPrompts.tsx +46 -0
  47. package/src/components/ResponseIconMapper.tsx +155 -0
  48. package/src/components/SourceCitations.tsx +46 -0
  49. package/src/components/ToolCallBadge.tsx +29 -0
  50. package/src/components/TypingProgressBar.tsx +113 -0
  51. package/src/components/ui/message-scroller.tsx +128 -0
  52. package/src/index.css +550 -0
  53. package/src/lib/cn.ts +5 -0
  54. package/src/lib/gibberishDetector.ts +159 -0
  55. package/src/lib/textHighlighter.tsx +206 -0
  56. package/src/main.tsx +10 -0
  57. package/src/services/api.ts +74 -0
  58. package/src/test/message-scroller-stub.tsx +60 -0
  59. package/src/test/setup.ts +8 -0
  60. package/src/types/chat.ts +66 -0
  61. package/src/vite-env.d.ts +14 -0
  62. package/tsconfig.json +21 -0
  63. package/vite.config.ts +28 -0
@@ -0,0 +1,206 @@
1
+ /**
2
+ * textHighlighter.tsx
3
+ *
4
+ * Dynamically highlights:
5
+ * - Double-quoted strings "..." → amber/yellow
6
+ * - Single-quoted strings '...' → sky/blue
7
+ * - ISO dates & human-readable dates 2026-09-11 / Sep 11, 2026 → green
8
+ * - Times 14:41:29 / 2:30 PM → purple
9
+ * - URLs / links https://... → platform-aware badge (LinkedIn, YouTube, etc.)
10
+ *
11
+ * Usage:
12
+ * renderHighlightedText("Check ticket 'TCK-1001' created on 2026-09-11")
13
+ */
14
+
15
+ import React from "react";
16
+ import { Linkedin, Youtube, Github, Twitter, ExternalLink, Globe } from "lucide-react";
17
+
18
+ // ── Token types ────────────────────────────────────────────────────────────────
19
+ type TokenKind =
20
+ | "double-quote"
21
+ | "single-quote"
22
+ | "date"
23
+ | "time"
24
+ | "url"
25
+ | "text";
26
+
27
+ interface Token {
28
+ kind: TokenKind;
29
+ value: string;
30
+ }
31
+
32
+ // ── Master regex (order matters — longer / more specific first) ────────────────
33
+ const MASTER_REGEX = new RegExp(
34
+ [
35
+ // URL (must come before quotes so http://... isn't split mid-string)
36
+ String.raw`(https?:\/\/[^\s"'<>]+)`,
37
+ // ISO datetime 2026-09-11T14:41:29 or 2026-09-11 14:41:29
38
+ String.raw`(\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2})?)`,
39
+ // ISO date 2026-09-11
40
+ String.raw`(\d{4}-\d{2}-\d{2})`,
41
+ // Human date Sep 11, 2026 / 11 September 2026 / September 11, 2026
42
+ String.raw`(\b(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)\s+\d{1,2},?\s+\d{4}|\b\d{1,2}\s+(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)\s+\d{4})`,
43
+ // Time 14:41:29 / 14:41 / 2:30 PM / 2:30 am
44
+ String.raw`(\b\d{1,2}:\d{2}(?::\d{2})?(?:\s?[APap][Mm])?\b)`,
45
+ // Double-quoted string "..."
46
+ String.raw`("(?:[^"\\]|\\.)*")`,
47
+ // Single-quoted string '...' (apostrophes inside words excluded by \b guard)
48
+ String.raw`('(?:[^'\\]|\\.)*')`,
49
+ ].join("|"),
50
+ "g"
51
+ );
52
+
53
+ function classifyMatch(match: RegExpExecArray): Token {
54
+ const [full, url, isoDatetime, isoDate, humanDate, time, dq, sq] = match;
55
+
56
+ if (url) return { kind: "url", value: url };
57
+ if (isoDatetime) return { kind: "date", value: isoDatetime }; // datetime → treat as date (contains time)
58
+ if (isoDate) return { kind: "date", value: isoDate };
59
+ if (humanDate) return { kind: "date", value: humanDate };
60
+ if (time) return { kind: "time", value: time };
61
+ if (dq) return { kind: "double-quote", value: dq };
62
+ if (sq) return { kind: "single-quote", value: sq };
63
+ return { kind: "text", value: full };
64
+ }
65
+
66
+ // ── Tokeniser ──────────────────────────────────────────────────────────────────
67
+ function tokenise(text: string): Token[] {
68
+ const tokens: Token[] = [];
69
+ let lastIndex = 0;
70
+ let match: RegExpExecArray | null;
71
+
72
+ MASTER_REGEX.lastIndex = 0;
73
+
74
+ while ((match = MASTER_REGEX.exec(text)) !== null) {
75
+ if (match.index > lastIndex) {
76
+ tokens.push({ kind: "text", value: text.slice(lastIndex, match.index) });
77
+ }
78
+ tokens.push(classifyMatch(match));
79
+ lastIndex = MASTER_REGEX.lastIndex;
80
+ }
81
+
82
+ if (lastIndex < text.length) {
83
+ tokens.push({ kind: "text", value: text.slice(lastIndex) });
84
+ }
85
+
86
+ return tokens;
87
+ }
88
+
89
+ // ── Inline bold / code inside plain text segments ─────────────────────────────
90
+ const INLINE_REGEX = /(\*\*.*?\*\*|`.*?`)/g;
91
+
92
+ function renderPlainSegment(text: string): React.ReactNode[] {
93
+ const parts = text.split(INLINE_REGEX);
94
+ return parts.map((part, i) => {
95
+ if (part.startsWith("**") && part.endsWith("**")) {
96
+ return <strong key={i}>{part.slice(2, -2)}</strong>;
97
+ }
98
+ if (part.startsWith("`") && part.endsWith("`")) {
99
+ return (
100
+ <code key={i} className="inline-code">
101
+ {part.slice(1, -1)}
102
+ </code>
103
+ );
104
+ }
105
+ return <React.Fragment key={i}>{part}</React.Fragment>;
106
+ });
107
+ }
108
+
109
+ // ── Token → React element ──────────────────────────────────────────────────────
110
+ function renderToken(token: Token, idx: number): React.ReactNode {
111
+ switch (token.kind) {
112
+ case "double-quote":
113
+ return (
114
+ <span key={idx} className="hl-double-quote" title="Quoted value">
115
+ {token.value}
116
+ </span>
117
+ );
118
+
119
+ case "single-quote":
120
+ return (
121
+ <span key={idx} className="hl-single-quote" title="Quoted value">
122
+ {token.value}
123
+ </span>
124
+ );
125
+
126
+ case "date":
127
+ return (
128
+ <span key={idx} className="hl-date" title="Date / DateTime">
129
+ 📅 {token.value}
130
+ </span>
131
+ );
132
+
133
+ case "time":
134
+ return (
135
+ <span key={idx} className="hl-time" title="Time">
136
+ 🕐 {token.value}
137
+ </span>
138
+ );
139
+
140
+ case "url": {
141
+ const href = token.value.startsWith("http")
142
+ ? token.value
143
+ : `https://${token.value}`;
144
+
145
+ // Resolve platform from hostname
146
+ let hostname = "";
147
+ try { hostname = new URL(href).hostname.replace(/^www\./, ""); } catch {}
148
+
149
+ const isLinkedIn = hostname.includes("linkedin.com");
150
+ const isYouTube = hostname.includes("youtube.com") || hostname.includes("youtu.be");
151
+ const isGitHub = hostname.includes("github.com");
152
+ const isTwitter = hostname.includes("twitter.com") || hostname.includes("x.com");
153
+
154
+ const Icon = isLinkedIn ? Linkedin
155
+ : isYouTube ? Youtube
156
+ : isGitHub ? Github
157
+ : isTwitter ? Twitter
158
+ : ExternalLink;
159
+
160
+ const badgeClass = isLinkedIn ? "hl-link hl-link--linkedin"
161
+ : isYouTube ? "hl-link hl-link--youtube"
162
+ : isGitHub ? "hl-link hl-link--github"
163
+ : isTwitter ? "hl-link hl-link--twitter"
164
+ : "hl-link";
165
+
166
+ // Short label — use platform name instead of full URL when recognisable
167
+ const shortLabel = isLinkedIn ? "LinkedIn"
168
+ : isYouTube ? "YouTube"
169
+ : isGitHub ? "GitHub"
170
+ : isTwitter ? "Twitter / X"
171
+ : token.value.length > 45
172
+ ? token.value.slice(0, 45) + "…"
173
+ : token.value;
174
+
175
+ return (
176
+ <a
177
+ key={idx}
178
+ href={href}
179
+ className={badgeClass}
180
+ target="_blank"
181
+ rel="noopener noreferrer"
182
+ title={href}
183
+ >
184
+ <Icon size={13} />
185
+ <span>{shortLabel}</span>
186
+ <Globe size={10} className="hl-link-external-hint" />
187
+ </a>
188
+ );
189
+ }
190
+
191
+ case "text":
192
+ default:
193
+ return (
194
+ <React.Fragment key={idx}>
195
+ {renderPlainSegment(token.value)}
196
+ </React.Fragment>
197
+ );
198
+ }
199
+ }
200
+
201
+ // ── Public API ─────────────────────────────────────────────────────────────────
202
+ export function renderHighlightedText(text: string): React.ReactNode {
203
+ if (!text) return null;
204
+ const tokens = tokenise(text);
205
+ return <>{tokens.map((t, i) => renderToken(t, i))}</>;
206
+ }
package/src/main.tsx ADDED
@@ -0,0 +1,10 @@
1
+ import React from "react";
2
+ import ReactDOM from "react-dom/client";
3
+ import { App } from "./App";
4
+ import "./index.css";
5
+
6
+ ReactDOM.createRoot(document.getElementById("root")!).render(
7
+ <React.StrictMode>
8
+ <App />
9
+ </React.StrictMode>
10
+ );
@@ -0,0 +1,74 @@
1
+ import { ChatApiResponse, Message, SessionResponse } from "../types/chat";
2
+
3
+ const API_BASE = "";
4
+
5
+ export class ChatService {
6
+ static async createSession(): Promise<string> {
7
+ const response = await fetch(`${API_BASE}/api/v1/sessions`, {
8
+ method: "POST",
9
+ headers: { "Content-Type": "application/json" },
10
+ });
11
+ if (!response.ok) {
12
+ throw new Error(`Failed to create session: ${response.statusText}`);
13
+ }
14
+ const data: SessionResponse = await response.json();
15
+ return data.session_id;
16
+ }
17
+
18
+ static async sendMessage(sessionId: string, message: string): Promise<ChatApiResponse> {
19
+ const response = await fetch(`${API_BASE}/api/v1/sessions/${sessionId}/messages`, {
20
+ method: "POST",
21
+ headers: { "Content-Type": "application/json" },
22
+ body: JSON.stringify({ message }),
23
+ });
24
+ if (!response.ok) {
25
+ const err = await response.json().catch(() => ({}));
26
+ const message = err?.error?.message || `Server error (${response.status})`;
27
+ throw new Error(message);
28
+ }
29
+ return response.json();
30
+ }
31
+
32
+ static async getHistory(sessionId: string): Promise<Message[]> {
33
+ const response = await fetch(`${API_BASE}/api/v1/sessions/${sessionId}/messages`);
34
+ if (!response.ok) {
35
+ return [];
36
+ }
37
+ const data = await response.json();
38
+ return (data.messages || []).map((m: any) => ({
39
+ id: m.id,
40
+ role: m.role,
41
+ content: m.content,
42
+ timestamp: m.created_at || new Date().toISOString(),
43
+ usage: m.model ? {
44
+ model: m.model,
45
+ prompt_tokens: m.prompt_tokens || 0,
46
+ completion_tokens: m.completion_tokens || 0,
47
+ total_tokens: (m.prompt_tokens || 0) + (m.completion_tokens || 0),
48
+ } : undefined,
49
+ }));
50
+ }
51
+
52
+ static async closeSession(sessionId: string): Promise<void> {
53
+ await fetch(`${API_BASE}/api/v1/sessions/${sessionId}`, {
54
+ method: "DELETE",
55
+ }).catch(() => {});
56
+ }
57
+
58
+ static async checkHealth(): Promise<boolean> {
59
+ try {
60
+ const res = await fetch(`${API_BASE}/health`);
61
+ return res.ok;
62
+ } catch {
63
+ return false;
64
+ }
65
+ }
66
+
67
+ static async getCustomers(): Promise<any[]> {
68
+ return [];
69
+ }
70
+
71
+ static async getTickets(): Promise<any[]> {
72
+ return [];
73
+ }
74
+ }
@@ -0,0 +1,60 @@
1
+ import React, { type ReactNode } from "react";
2
+
3
+ type Props = {
4
+ children?: ReactNode;
5
+ className?: string;
6
+ "aria-label"?: string;
7
+ "aria-busy"?: boolean;
8
+ messageId?: string;
9
+ scrollAnchor?: boolean;
10
+ autoScroll?: boolean;
11
+ defaultScrollPosition?: string;
12
+ scrollPreviousItemPeek?: number;
13
+ direction?: string;
14
+ };
15
+
16
+ function PassThrough({ children, className, ...props }: Props) {
17
+ const {
18
+ messageId: _messageId,
19
+ scrollAnchor: _scrollAnchor,
20
+ autoScroll: _autoScroll,
21
+ defaultScrollPosition: _defaultScrollPosition,
22
+ scrollPreviousItemPeek: _scrollPreviousItemPeek,
23
+ direction: _direction,
24
+ ...dom
25
+ } = props;
26
+ return (
27
+ <div className={className} {...dom}>
28
+ {children}
29
+ </div>
30
+ );
31
+ }
32
+
33
+ export const MessageScroller = {
34
+ Provider: PassThrough,
35
+ Root: PassThrough,
36
+ Viewport: PassThrough,
37
+ Content: PassThrough,
38
+ Item: PassThrough,
39
+ Button: ({ children, className, ...props }: Props) => (
40
+ <button type="button" className={className} {...props}>
41
+ {children}
42
+ </button>
43
+ ),
44
+ };
45
+
46
+ export function useMessageScroller() {
47
+ return {
48
+ scrollToEnd: () => true,
49
+ scrollToMessage: () => true,
50
+ scrollToStart: () => true,
51
+ };
52
+ }
53
+
54
+ export function useMessageScrollerScrollable() {
55
+ return { start: false, end: false };
56
+ }
57
+
58
+ export function useMessageScrollerVisibility() {
59
+ return { currentAnchorId: null, visibleMessageIds: [] as string[] };
60
+ }
@@ -0,0 +1,8 @@
1
+ import "@testing-library/jest-dom/vitest";
2
+ import { afterEach, vi } from "vitest";
3
+ import { cleanup } from "@testing-library/react";
4
+
5
+ afterEach(() => {
6
+ cleanup();
7
+ vi.restoreAllMocks();
8
+ });
@@ -0,0 +1,66 @@
1
+ export interface Source {
2
+ chunk_id: string;
3
+ source: string;
4
+ score: number;
5
+ }
6
+
7
+ export interface ToolCall {
8
+ tool_name: string;
9
+ arguments: Record<string, any>;
10
+ result: Record<string, any>;
11
+ }
12
+
13
+ export interface TokenUsage {
14
+ model: string;
15
+ prompt_tokens: number;
16
+ completion_tokens: number;
17
+ total_tokens: number;
18
+ }
19
+
20
+ export interface Message {
21
+ id: string;
22
+ role: "user" | "assistant" | "system";
23
+ content: string;
24
+ timestamp: string;
25
+ sources?: Source[];
26
+ tool_calls?: ToolCall[];
27
+ usage?: TokenUsage;
28
+ error?: boolean;
29
+ }
30
+
31
+ export interface Customer {
32
+ customer_id: string;
33
+ name: string;
34
+ company: string;
35
+ email: string;
36
+ phone?: string | null;
37
+ plan: string;
38
+ vessels_count: number;
39
+ transformers_count: number;
40
+ }
41
+
42
+ export interface Ticket {
43
+ ticket_id: string;
44
+ customer_id: string;
45
+ customer_email: string;
46
+ subject: string;
47
+ description: string;
48
+ priority: "low" | "medium" | "high" | "urgent" | string;
49
+ status: "open" | "in_progress" | "resolved" | "closed" | string;
50
+ created_at: string;
51
+ updated_at: string;
52
+ }
53
+
54
+ export interface SessionResponse {
55
+ session_id: string;
56
+ created_at: string;
57
+ }
58
+
59
+ export interface ChatApiResponse {
60
+ request_id: string;
61
+ session_id: string;
62
+ answer: string;
63
+ sources: Source[];
64
+ tool_calls: ToolCall[];
65
+ usage: TokenUsage;
66
+ }
@@ -0,0 +1,14 @@
1
+ /// <reference types="vite/client" />
2
+
3
+ interface ImportMetaEnv {
4
+ /**
5
+ * Base URL for the backend API.
6
+ * - In local dev: leave empty — Vite proxies /api and /health to localhost:8000.
7
+ * - In production builds: set to the deployed backend URL, e.g. https://vpsai.onrender.com
8
+ */
9
+ readonly VITE_API_BASE?: string;
10
+ }
11
+
12
+ interface ImportMeta {
13
+ readonly env: ImportMetaEnv;
14
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2020",
4
+ "useDefineForClassFields": true,
5
+ "lib": ["ES2020", "DOM", "DOM.Iterable"],
6
+ "module": "ESNext",
7
+ "skipLibCheck": true,
8
+ "moduleResolution": "bundler",
9
+ "allowImportingTsExtensions": false,
10
+ "resolveJsonModule": true,
11
+ "isolatedModules": true,
12
+ "noEmit": true,
13
+ "jsx": "react-jsx",
14
+ "strict": true,
15
+ "noUnusedLocals": false,
16
+ "noUnusedParameters": false,
17
+ "noFallthroughCasesInSwitch": true,
18
+ "types": ["vite/client", "vitest/globals"]
19
+ },
20
+ "include": ["src"]
21
+ }
package/vite.config.ts ADDED
@@ -0,0 +1,28 @@
1
+ import tailwindcss from "@tailwindcss/vite";
2
+ import react from "@vitejs/plugin-react";
3
+ import { defineConfig } from "vitest/config";
4
+
5
+ export default defineConfig({
6
+ plugins: [react(), tailwindcss()],
7
+ server: {
8
+ port: 5173,
9
+ proxy: {
10
+ "/api": {
11
+ target: "https://vpsai.onrender.com",
12
+ changeOrigin: true,
13
+ },
14
+ "/health": {
15
+ target: "https://vpsai.onrender.com",
16
+ changeOrigin: true,
17
+ },
18
+ },
19
+ },
20
+ build: {
21
+ outDir: "dist",
22
+ emptyOutDir: true,
23
+ },
24
+ test: {
25
+ environment: "jsdom",
26
+ setupFiles: "./src/test/setup.ts",
27
+ },
28
+ });