vpschatbotwidget 1.0.3 → 1.1.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.
- package/dist-lib/types/App.d.ts +1 -0
- package/dist-lib/types/chatbot/api/chatbot-api.d.ts +10 -2
- package/dist-lib/types/chatbot/api/chatbot-types.d.ts +21 -0
- package/dist-lib/types/chatbot/core/AgentReasoning.d.ts +9 -0
- package/dist-lib/types/chatbot/core/ChatContext.d.ts +2 -0
- package/dist-lib/types/chatbot/core/ChatMarkdown.d.ts +2 -2
- package/dist-lib/types/chatbot/core/ChatProvider.d.ts +13 -1
- package/dist-lib/types/chatbot/core/ChatTypingIndicator.d.ts +1 -0
- package/dist-lib/types/chatbot/core/GroundedSources.d.ts +14 -0
- package/dist-lib/types/chatbot/embedded/EmbeddedChatbot.d.ts +13 -1
- package/dist-lib/types/chatbot/index.d.ts +1 -1
- package/dist-lib/types/chatbot/widget/ChatbotWidget.d.ts +13 -1
- package/dist-lib/vps-chatbot.cjs +33 -29
- package/dist-lib/vps-chatbot.js +1198 -967
- package/package.json +1 -1
- package/src/chatbot/api/chatbot-api.ts +105 -3
- package/src/chatbot/api/chatbot-types.ts +23 -0
- package/src/chatbot/core/AgentReasoning.tsx +60 -0
- package/src/chatbot/core/ChatContext.tsx +2 -0
- package/src/chatbot/core/ChatMarkdown.tsx +279 -54
- package/src/chatbot/core/ChatMessage.tsx +41 -45
- package/src/chatbot/core/ChatMessageList.tsx +1 -1
- package/src/chatbot/core/ChatProvider.tsx +109 -22
- package/src/chatbot/core/ChatTypingIndicator.tsx +16 -5
- package/src/chatbot/core/GroundedSources.tsx +181 -0
- package/src/chatbot/embedded/EmbeddedChatbot.tsx +33 -4
- package/src/chatbot/index.ts +1 -0
- package/src/chatbot/widget/ChatbotWidget.tsx +33 -4
- package/src/index.css +1051 -68
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "vpschatbotwidget",
|
|
3
|
-
"version": "1.0
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "This is an Package for the chatbot widget ui for our customer portel . ",
|
|
6
6
|
"homepage": "https://github.com/dhineshkumar-natobotics/VPS-Chatbot-Widget#readme",
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type {
|
|
2
2
|
ApiErrorDto,
|
|
3
|
+
ChatAccessContext,
|
|
3
4
|
ChatApiError,
|
|
4
5
|
ChatMessage,
|
|
5
6
|
ChatMessageDto,
|
|
@@ -92,6 +93,8 @@ export function normalizeSource(dto: SourceDto): Source {
|
|
|
92
93
|
chunkId: dto.chunk_id,
|
|
93
94
|
source: dto.source,
|
|
94
95
|
score: dto.score,
|
|
96
|
+
title: dto.title,
|
|
97
|
+
snippet: dto.snippet,
|
|
95
98
|
};
|
|
96
99
|
}
|
|
97
100
|
|
|
@@ -144,7 +147,20 @@ async function readJson(response: Response): Promise<unknown> {
|
|
|
144
147
|
export interface ChatApiClient {
|
|
145
148
|
apiBaseUrl: string;
|
|
146
149
|
createSession(): Promise<SessionCreated>;
|
|
147
|
-
sendMessage(sessionId: string, message: string): Promise<{
|
|
150
|
+
sendMessage(sessionId: string, message: string, access?: ChatAccessContext): Promise<{
|
|
151
|
+
requestId: string;
|
|
152
|
+
sessionId: string;
|
|
153
|
+
answer: string;
|
|
154
|
+
sources: Source[];
|
|
155
|
+
toolCalls: ToolCall[];
|
|
156
|
+
usage: TokenUsage;
|
|
157
|
+
}>;
|
|
158
|
+
sendMessageStream?(
|
|
159
|
+
sessionId: string,
|
|
160
|
+
message: string,
|
|
161
|
+
access?: ChatAccessContext,
|
|
162
|
+
onProgress?: (stage: string) => void
|
|
163
|
+
): Promise<{
|
|
148
164
|
requestId: string;
|
|
149
165
|
sessionId: string;
|
|
150
166
|
answer: string;
|
|
@@ -201,12 +217,16 @@ export function createChatApi(initialBaseUrl?: string): ChatApiClient {
|
|
|
201
217
|
return { sessionId: dto.session_id, createdAt: dto.created_at };
|
|
202
218
|
},
|
|
203
219
|
|
|
204
|
-
async sendMessage(sessionId: string, message: string) {
|
|
220
|
+
async sendMessage(sessionId: string, message: string, access?: ChatAccessContext) {
|
|
205
221
|
const dto = await request<ChatResponseDto>(
|
|
206
222
|
`/api/v1/sessions/${sessionId}/messages`,
|
|
207
223
|
{
|
|
208
224
|
method: "POST",
|
|
209
|
-
body: JSON.stringify({
|
|
225
|
+
body: JSON.stringify({
|
|
226
|
+
message,
|
|
227
|
+
...(access?.roleId !== undefined ? { role_id: access.roleId } : {}),
|
|
228
|
+
...(access?.client ? { client: access.client } : {}),
|
|
229
|
+
}),
|
|
210
230
|
}
|
|
211
231
|
);
|
|
212
232
|
return {
|
|
@@ -219,6 +239,88 @@ export function createChatApi(initialBaseUrl?: string): ChatApiClient {
|
|
|
219
239
|
};
|
|
220
240
|
},
|
|
221
241
|
|
|
242
|
+
async sendMessageStream(
|
|
243
|
+
sessionId: string,
|
|
244
|
+
message: string,
|
|
245
|
+
access?: ChatAccessContext,
|
|
246
|
+
onProgress?: (stage: string) => void
|
|
247
|
+
) {
|
|
248
|
+
const url = buildApiUrl(baseUrl, `/api/v1/sessions/${sessionId}/messages/stream`);
|
|
249
|
+
try {
|
|
250
|
+
const response = await fetch(url, {
|
|
251
|
+
method: "POST",
|
|
252
|
+
headers: {
|
|
253
|
+
"Content-Type": "application/json",
|
|
254
|
+
},
|
|
255
|
+
body: JSON.stringify({
|
|
256
|
+
message,
|
|
257
|
+
...(access?.roleId !== undefined ? { role_id: access.roleId } : {}),
|
|
258
|
+
...(access?.client ? { client: access.client } : {}),
|
|
259
|
+
}),
|
|
260
|
+
});
|
|
261
|
+
|
|
262
|
+
if (!response.ok || !response.body) {
|
|
263
|
+
return await this.sendMessage(sessionId, message, access);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
const reader = response.body.getReader();
|
|
267
|
+
const decoder = new TextDecoder();
|
|
268
|
+
let buffer = "";
|
|
269
|
+
let finalResult: {
|
|
270
|
+
requestId: string;
|
|
271
|
+
sessionId: string;
|
|
272
|
+
answer: string;
|
|
273
|
+
sources: Source[];
|
|
274
|
+
toolCalls: ToolCall[];
|
|
275
|
+
usage: TokenUsage;
|
|
276
|
+
} | null = null;
|
|
277
|
+
|
|
278
|
+
while (true) {
|
|
279
|
+
const { done, value } = await reader.read();
|
|
280
|
+
if (done) break;
|
|
281
|
+
buffer += decoder.decode(value, { stream: true });
|
|
282
|
+
const lines = buffer.split("\n\n");
|
|
283
|
+
buffer = lines.pop() || "";
|
|
284
|
+
|
|
285
|
+
for (const line of lines) {
|
|
286
|
+
const trimmed = line.trim();
|
|
287
|
+
if (trimmed.startsWith("data:")) {
|
|
288
|
+
try {
|
|
289
|
+
const data = JSON.parse(trimmed.slice(5).trim());
|
|
290
|
+
if (data.type === "progress" && data.stage) {
|
|
291
|
+
onProgress?.(data.stage);
|
|
292
|
+
} else if (data.type === "complete") {
|
|
293
|
+
finalResult = {
|
|
294
|
+
requestId: data.request_id,
|
|
295
|
+
sessionId: data.session_id,
|
|
296
|
+
answer: data.answer,
|
|
297
|
+
sources: (data.sources || []).map(normalizeSource),
|
|
298
|
+
toolCalls: (data.tool_calls || []).map(normalizeToolCall),
|
|
299
|
+
usage: normalizeUsage(data.usage),
|
|
300
|
+
};
|
|
301
|
+
} else if (data.type === "error") {
|
|
302
|
+
throw new Error(data.message || "An error occurred");
|
|
303
|
+
}
|
|
304
|
+
} catch (e) {
|
|
305
|
+
if (e instanceof Error && e.message !== "An error occurred") {
|
|
306
|
+
// Ignore JSON parse error on incomplete chunk
|
|
307
|
+
} else {
|
|
308
|
+
throw e;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
if (finalResult) {
|
|
316
|
+
return finalResult;
|
|
317
|
+
}
|
|
318
|
+
return await this.sendMessage(sessionId, message, access);
|
|
319
|
+
} catch {
|
|
320
|
+
return await this.sendMessage(sessionId, message, access);
|
|
321
|
+
}
|
|
322
|
+
},
|
|
323
|
+
|
|
222
324
|
async getHistory(sessionId: string): Promise<ChatMessage[]> {
|
|
223
325
|
try {
|
|
224
326
|
const dto = await request<SessionMessagesResponseDto>(
|
|
@@ -6,6 +6,8 @@ export interface Source {
|
|
|
6
6
|
chunkId: string;
|
|
7
7
|
source: string;
|
|
8
8
|
score: number;
|
|
9
|
+
title?: string;
|
|
10
|
+
snippet?: string;
|
|
9
11
|
}
|
|
10
12
|
|
|
11
13
|
export interface ToolCall {
|
|
@@ -27,6 +29,7 @@ export interface ChatMessage {
|
|
|
27
29
|
content: string;
|
|
28
30
|
createdAt: string;
|
|
29
31
|
status?: MessageStatus;
|
|
32
|
+
progressText?: string;
|
|
30
33
|
sources?: Source[];
|
|
31
34
|
toolCalls?: ToolCall[];
|
|
32
35
|
usage?: TokenUsage;
|
|
@@ -36,10 +39,20 @@ export interface ChatUserContext {
|
|
|
36
39
|
customerId?: string;
|
|
37
40
|
email?: string;
|
|
38
41
|
name?: string;
|
|
42
|
+
/** Display name of the role, if the host application has one. */
|
|
39
43
|
role?: string;
|
|
44
|
+
/** Authenticated Customer Portal role ID used for server-side RAG routing. */
|
|
45
|
+
roleId?: number;
|
|
46
|
+
/** Client experience that owns this authenticated session. */
|
|
47
|
+
client?: "mobile" | "web" | "admin";
|
|
40
48
|
page?: string;
|
|
41
49
|
}
|
|
42
50
|
|
|
51
|
+
export interface ChatAccessContext {
|
|
52
|
+
roleId?: number;
|
|
53
|
+
client?: "mobile" | "web" | "admin";
|
|
54
|
+
}
|
|
55
|
+
|
|
43
56
|
export interface Ticket {
|
|
44
57
|
ticketId: string;
|
|
45
58
|
customerId: string;
|
|
@@ -79,6 +92,8 @@ export interface SourceDto {
|
|
|
79
92
|
chunk_id: string;
|
|
80
93
|
source: string;
|
|
81
94
|
score: number;
|
|
95
|
+
title?: string;
|
|
96
|
+
snippet?: string;
|
|
82
97
|
}
|
|
83
98
|
|
|
84
99
|
export interface ToolCallDto {
|
|
@@ -121,6 +136,14 @@ export interface ChatResponseDto {
|
|
|
121
136
|
sources: SourceDto[];
|
|
122
137
|
tool_calls?: ToolCallDto[];
|
|
123
138
|
usage: TokenUsageDto;
|
|
139
|
+
role?: RoleDto | null;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export interface RoleDto {
|
|
143
|
+
id: number;
|
|
144
|
+
usertype: string;
|
|
145
|
+
channel: "mobile" | "web" | "admin";
|
|
146
|
+
knowledge_scopes: string[];
|
|
124
147
|
}
|
|
125
148
|
|
|
126
149
|
export interface TicketDto {
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import React, { useState, useEffect } from "react";
|
|
2
|
+
import { Brain, ChevronDown, ChevronRight, CheckCircle2 } from "lucide-react";
|
|
3
|
+
|
|
4
|
+
interface AgentReasoningProps {
|
|
5
|
+
status?: "pending" | "complete" | "error";
|
|
6
|
+
progressText?: string;
|
|
7
|
+
sourcesCount?: number;
|
|
8
|
+
durationMs?: number;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export const AgentReasoning: React.FC<AgentReasoningProps> = ({
|
|
12
|
+
status = "complete",
|
|
13
|
+
progressText,
|
|
14
|
+
sourcesCount = 5,
|
|
15
|
+
durationMs = 1800,
|
|
16
|
+
}) => {
|
|
17
|
+
const isPending = status === "pending";
|
|
18
|
+
const [isOpen, setIsOpen] = useState(isPending);
|
|
19
|
+
const [seconds, setSeconds] = useState(0);
|
|
20
|
+
|
|
21
|
+
useEffect(() => {
|
|
22
|
+
if (!isPending) return;
|
|
23
|
+
setIsOpen(true);
|
|
24
|
+
const start = Date.now();
|
|
25
|
+
const interval = setInterval(() => {
|
|
26
|
+
setSeconds(Number(((Date.now() - start) / 1000).toFixed(1)));
|
|
27
|
+
}, 100);
|
|
28
|
+
return () => clearInterval(interval);
|
|
29
|
+
}, [isPending]);
|
|
30
|
+
|
|
31
|
+
// When transition from pending to complete, collapse like ChatGPT / Open WebUI
|
|
32
|
+
useEffect(() => {
|
|
33
|
+
if (!isPending) {
|
|
34
|
+
setIsOpen(false);
|
|
35
|
+
}
|
|
36
|
+
}, [isPending]);
|
|
37
|
+
|
|
38
|
+
const durationDisplay = isPending
|
|
39
|
+
? `${seconds}s`
|
|
40
|
+
: `${(durationMs / 1000).toFixed(1)}s`;
|
|
41
|
+
|
|
42
|
+
return (
|
|
43
|
+
<div className={`agent-reasoning-container${isPending ? " agent-reasoning--active" : ""}`}>
|
|
44
|
+
<div
|
|
45
|
+
className="agent-reasoning-header"
|
|
46
|
+
aria-expanded={isOpen}
|
|
47
|
+
>
|
|
48
|
+
<div className="agent-reasoning-header-left">
|
|
49
|
+
<Brain
|
|
50
|
+
size={13}
|
|
51
|
+
className={`agent-reasoning-brain-icon${isPending ? " agent-reasoning-brain--pulse" : ""}`}
|
|
52
|
+
/>
|
|
53
|
+
<span className="agent-reasoning-title">
|
|
54
|
+
{isPending ? `Thinking (${durationDisplay})...` : `Thought for ${durationDisplay} `}
|
|
55
|
+
</span>
|
|
56
|
+
</div>
|
|
57
|
+
</div>
|
|
58
|
+
</div>
|
|
59
|
+
);
|
|
60
|
+
};
|
|
@@ -26,6 +26,8 @@ export interface ChatContextValue {
|
|
|
26
26
|
suggestionBadgesEnabled: boolean;
|
|
27
27
|
userContext: ChatUserContext;
|
|
28
28
|
apiBaseUrl?: string;
|
|
29
|
+
hideInspectSources?: boolean;
|
|
30
|
+
showGroundedSources?: boolean;
|
|
29
31
|
sendMessage: (text: string) => Promise<void>;
|
|
30
32
|
retryLast: () => Promise<void>;
|
|
31
33
|
confirmTicket: (customerIdOrEmail?: string) => Promise<void>;
|
|
@@ -1,22 +1,65 @@
|
|
|
1
1
|
import React from "react";
|
|
2
2
|
|
|
3
|
+
/**
|
|
4
|
+
* Robust inline Markdown renderer supporting:
|
|
5
|
+
* - Markdown links [text](url)
|
|
6
|
+
* - Raw URLs https://...
|
|
7
|
+
* - Bold **text**
|
|
8
|
+
* - Italic *text* and _text_
|
|
9
|
+
* - Inline code `text`
|
|
10
|
+
*/
|
|
3
11
|
function renderInline(text: string): React.ReactNode[] {
|
|
4
|
-
|
|
12
|
+
if (!text) return [];
|
|
13
|
+
|
|
14
|
+
// Match: [text](url) | **bold** | *italic* | `code` | https?://...
|
|
15
|
+
const tokenRegex =
|
|
16
|
+
/(\[[^\]]+\]\([^)]+\)|\*\*[^*]+\*\*|\*[^*]+\*|`[^`]+`|https?:\/\/[^\s]+)/g;
|
|
17
|
+
|
|
18
|
+
const parts = text.split(tokenRegex);
|
|
19
|
+
|
|
5
20
|
return parts.map((part, index) => {
|
|
6
|
-
if (part
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
21
|
+
if (!part) return null;
|
|
22
|
+
|
|
23
|
+
// Markdown link: [text](url)
|
|
24
|
+
const linkMatch = part.match(/^\[([^\]]+)\]\(([^)]+)\)$/);
|
|
25
|
+
if (linkMatch) {
|
|
26
|
+
const linkText = linkMatch[1];
|
|
27
|
+
const linkUrl = linkMatch[2];
|
|
28
|
+
const isExternal = /^https?:\/\//i.test(linkUrl);
|
|
10
29
|
return (
|
|
11
|
-
<
|
|
30
|
+
<a
|
|
12
31
|
key={index}
|
|
13
|
-
|
|
32
|
+
href={linkUrl}
|
|
33
|
+
target={isExternal ? "_blank" : undefined}
|
|
34
|
+
rel={isExternal ? "noopener noreferrer" : undefined}
|
|
35
|
+
className="md-link"
|
|
14
36
|
>
|
|
37
|
+
{linkText}
|
|
38
|
+
</a>
|
|
39
|
+
);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Bold: **text**
|
|
43
|
+
if (part.startsWith("**") && part.endsWith("**") && part.length >= 4) {
|
|
44
|
+
return <strong key={index}>{part.slice(2, -2)}</strong>;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Italic: *text*
|
|
48
|
+
if (part.startsWith("*") && part.endsWith("*") && part.length >= 2) {
|
|
49
|
+
return <em key={index}>{part.slice(1, -1)}</em>;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// Inline code: `code`
|
|
53
|
+
if (part.startsWith("`") && part.endsWith("`") && part.length >= 2) {
|
|
54
|
+
return (
|
|
55
|
+
<code key={index} className="md-code">
|
|
15
56
|
{part.slice(1, -1)}
|
|
16
57
|
</code>
|
|
17
58
|
);
|
|
18
59
|
}
|
|
19
|
-
|
|
60
|
+
|
|
61
|
+
// Raw URL: https://...
|
|
62
|
+
if (/^https?:\/\//i.test(part)) {
|
|
20
63
|
return (
|
|
21
64
|
<a
|
|
22
65
|
key={index}
|
|
@@ -29,59 +72,241 @@ function renderInline(text: string): React.ReactNode[] {
|
|
|
29
72
|
</a>
|
|
30
73
|
);
|
|
31
74
|
}
|
|
75
|
+
|
|
32
76
|
return <React.Fragment key={index}>{part}</React.Fragment>;
|
|
33
77
|
});
|
|
34
78
|
}
|
|
35
79
|
|
|
36
|
-
|
|
37
|
-
|
|
80
|
+
type Block =
|
|
81
|
+
| { type: "h"; level: number; content: string }
|
|
82
|
+
| { type: "p"; lines: string[] }
|
|
83
|
+
| { type: "ul"; items: string[] }
|
|
84
|
+
| { type: "ol"; items: string[] }
|
|
85
|
+
| { type: "code"; lang: string; code: string }
|
|
86
|
+
| { type: "quote"; lines: string[] }
|
|
87
|
+
| { type: "hr" }
|
|
88
|
+
| { type: "table"; headers: string[]; rows: string[][] };
|
|
38
89
|
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
.filter((line) => line.trim().startsWith("- ") || line.trim().startsWith("* "));
|
|
47
|
-
return (
|
|
48
|
-
<ul key={blockIndex} className="md-ul">
|
|
49
|
-
{items.map((item, itemIndex) => (
|
|
50
|
-
<li key={itemIndex}>{renderInline(item.replace(/^[-*]\s+/, ""))}</li>
|
|
51
|
-
))}
|
|
52
|
-
</ul>
|
|
53
|
-
);
|
|
54
|
-
}
|
|
90
|
+
/**
|
|
91
|
+
* Line-by-line block parser for Markdown documents.
|
|
92
|
+
* Correctly distinguishes lists, headers, code fences, blockquotes, and paragraphs.
|
|
93
|
+
*/
|
|
94
|
+
function parseBlocks(markdown: string): Block[] {
|
|
95
|
+
const lines = markdown.replace(/\r\n/g, "\n").split("\n");
|
|
96
|
+
const blocks: Block[] = [];
|
|
55
97
|
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
{items.map((item, itemIndex) => (
|
|
61
|
-
<li key={itemIndex}>{renderInline(item.replace(/^\d+\.\s+/, ""))}</li>
|
|
62
|
-
))}
|
|
63
|
-
</ol>
|
|
64
|
-
);
|
|
65
|
-
}
|
|
98
|
+
let i = 0;
|
|
99
|
+
while (i < lines.length) {
|
|
100
|
+
const rawLine = lines[i];
|
|
101
|
+
const trimmed = rawLine.trim();
|
|
66
102
|
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
className="md-pre"
|
|
73
|
-
>
|
|
74
|
-
<code>{content}</code>
|
|
75
|
-
</pre>
|
|
76
|
-
);
|
|
77
|
-
}
|
|
103
|
+
// 1. Skip completely empty lines
|
|
104
|
+
if (!trimmed) {
|
|
105
|
+
i++;
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
78
108
|
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
109
|
+
// 2. Code blocks (```lang ... ```)
|
|
110
|
+
if (trimmed.startsWith("```")) {
|
|
111
|
+
const lang = trimmed.slice(3).trim();
|
|
112
|
+
const codeLines: string[] = [];
|
|
113
|
+
i++;
|
|
114
|
+
while (i < lines.length && !lines[i].trim().startsWith("```")) {
|
|
115
|
+
codeLines.push(lines[i]);
|
|
116
|
+
i++;
|
|
117
|
+
}
|
|
118
|
+
if (i < lines.length && lines[i].trim().startsWith("```")) {
|
|
119
|
+
i++; // skip closing fence
|
|
120
|
+
}
|
|
121
|
+
blocks.push({ type: "code", lang, code: codeLines.join("\n") });
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// 3. Horizontal rule (--- or ***)
|
|
126
|
+
if (/^(---|___|\*\*\*)$/.test(trimmed)) {
|
|
127
|
+
blocks.push({ type: "hr" });
|
|
128
|
+
i++;
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// 4. Headings (# to ####)
|
|
133
|
+
const headingMatch = trimmed.match(/^(#{1,4})\s+(.*)$/);
|
|
134
|
+
if (headingMatch) {
|
|
135
|
+
blocks.push({
|
|
136
|
+
type: "h",
|
|
137
|
+
level: headingMatch[1].length,
|
|
138
|
+
content: headingMatch[2],
|
|
139
|
+
});
|
|
140
|
+
i++;
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// 5. Blockquote (> ...)
|
|
145
|
+
if (trimmed.startsWith(">")) {
|
|
146
|
+
const quoteLines: string[] = [];
|
|
147
|
+
while (i < lines.length && lines[i].trim().startsWith(">")) {
|
|
148
|
+
quoteLines.push(lines[i].trim().replace(/^>\s?/, ""));
|
|
149
|
+
i++;
|
|
150
|
+
}
|
|
151
|
+
blocks.push({ type: "quote", lines: quoteLines });
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// 6. Unordered list (- or *)
|
|
156
|
+
if (/^[-*]\s+/.test(trimmed)) {
|
|
157
|
+
const items: string[] = [];
|
|
158
|
+
while (i < lines.length && /^[-*]\s+/.test(lines[i].trim())) {
|
|
159
|
+
items.push(lines[i].trim().replace(/^[-*]\s+/, ""));
|
|
160
|
+
i++;
|
|
161
|
+
}
|
|
162
|
+
blocks.push({ type: "ul", items });
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// 7. Ordered list (1. 2. ...)
|
|
167
|
+
if (/^\d+\.\s+/.test(trimmed)) {
|
|
168
|
+
const items: string[] = [];
|
|
169
|
+
while (i < lines.length && /^\d+\.\s+/.test(lines[i].trim())) {
|
|
170
|
+
items.push(lines[i].trim().replace(/^\d+\.\s+/, ""));
|
|
171
|
+
i++;
|
|
172
|
+
}
|
|
173
|
+
blocks.push({ type: "ol", items });
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// 8. Markdown table (| col | col |)
|
|
178
|
+
if (trimmed.startsWith("|") && trimmed.endsWith("|")) {
|
|
179
|
+
const tableLines: string[] = [];
|
|
180
|
+
while (i < lines.length && lines[i].trim().startsWith("|") && lines[i].trim().endsWith("|")) {
|
|
181
|
+
tableLines.push(lines[i].trim());
|
|
182
|
+
i++;
|
|
183
|
+
}
|
|
184
|
+
if (tableLines.length >= 2) {
|
|
185
|
+
const parseRow = (line: string) =>
|
|
186
|
+
line
|
|
187
|
+
.slice(1, -1)
|
|
188
|
+
.split("|")
|
|
189
|
+
.map((c) => c.trim());
|
|
190
|
+
const headers = parseRow(tableLines[0]);
|
|
191
|
+
// line 1 is usually separator (|---|---|)
|
|
192
|
+
const rowStartIndex = tableLines[1].includes("-") ? 2 : 1;
|
|
193
|
+
const rows = tableLines.slice(rowStartIndex).map(parseRow);
|
|
194
|
+
blocks.push({ type: "table", headers, rows });
|
|
195
|
+
continue;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// 9. Standard paragraph (accumulate contiguous lines until next empty line or block token)
|
|
200
|
+
const pLines: string[] = [];
|
|
201
|
+
while (
|
|
202
|
+
i < lines.length &&
|
|
203
|
+
lines[i].trim() &&
|
|
204
|
+
!lines[i].trim().startsWith("```") &&
|
|
205
|
+
!/^(#{1,4})\s+/.test(lines[i].trim()) &&
|
|
206
|
+
!/^[-*]\s+/.test(lines[i].trim()) &&
|
|
207
|
+
!/^\d+\.\s+/.test(lines[i].trim()) &&
|
|
208
|
+
!lines[i].trim().startsWith(">") &&
|
|
209
|
+
!/^(---|___|\*\*\*)$/.test(lines[i].trim())
|
|
210
|
+
) {
|
|
211
|
+
pLines.push(lines[i].trim());
|
|
212
|
+
i++;
|
|
213
|
+
}
|
|
214
|
+
if (pLines.length > 0) {
|
|
215
|
+
blocks.push({ type: "p", lines: pLines });
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
return blocks;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
export const ChatMarkdown: React.FC<{ text: string }> = ({ text }) => {
|
|
223
|
+
if (!text) return null;
|
|
224
|
+
|
|
225
|
+
const blocks = parseBlocks(text);
|
|
226
|
+
|
|
227
|
+
return (
|
|
228
|
+
<div className="md-content">
|
|
229
|
+
{blocks.map((block, idx) => {
|
|
230
|
+
switch (block.type) {
|
|
231
|
+
case "h": {
|
|
232
|
+
if (block.level === 1) return <h2 key={idx} className="md-h1">{renderInline(block.content)}</h2>;
|
|
233
|
+
if (block.level === 2) return <h3 key={idx} className="md-h2">{renderInline(block.content)}</h3>;
|
|
234
|
+
if (block.level === 3) return <h4 key={idx} className="md-h3">{renderInline(block.content)}</h4>;
|
|
235
|
+
return <h5 key={idx} className="md-h4">{renderInline(block.content)}</h5>;
|
|
236
|
+
}
|
|
237
|
+
case "ul":
|
|
238
|
+
return (
|
|
239
|
+
<ul key={idx} className="md-ul">
|
|
240
|
+
{block.items.map((item, itemIdx) => (
|
|
241
|
+
<li key={itemIdx} className="md-li">
|
|
242
|
+
{renderInline(item)}
|
|
243
|
+
</li>
|
|
244
|
+
))}
|
|
245
|
+
</ul>
|
|
246
|
+
);
|
|
247
|
+
case "ol":
|
|
248
|
+
return (
|
|
249
|
+
<ol key={idx} className="md-ol">
|
|
250
|
+
{block.items.map((item, itemIdx) => (
|
|
251
|
+
<li key={itemIdx} className="md-li">
|
|
252
|
+
{renderInline(item)}
|
|
253
|
+
</li>
|
|
254
|
+
))}
|
|
255
|
+
</ol>
|
|
256
|
+
);
|
|
257
|
+
case "code":
|
|
258
|
+
return (
|
|
259
|
+
<pre key={idx} className="md-pre">
|
|
260
|
+
<code>{block.code}</code>
|
|
261
|
+
</pre>
|
|
262
|
+
);
|
|
263
|
+
case "quote":
|
|
264
|
+
return (
|
|
265
|
+
<blockquote key={idx} className="md-quote">
|
|
266
|
+
{block.lines.map((line, qIdx) => (
|
|
267
|
+
<p key={qIdx}>{renderInline(line)}</p>
|
|
268
|
+
))}
|
|
269
|
+
</blockquote>
|
|
270
|
+
);
|
|
271
|
+
case "hr":
|
|
272
|
+
return <hr key={idx} className="md-hr" />;
|
|
273
|
+
case "table":
|
|
274
|
+
return (
|
|
275
|
+
<div key={idx} className="md-table-wrap">
|
|
276
|
+
<table className="md-table">
|
|
277
|
+
<thead>
|
|
278
|
+
<tr>
|
|
279
|
+
{block.headers.map((h, hIdx) => (
|
|
280
|
+
<th key={hIdx}>{renderInline(h)}</th>
|
|
281
|
+
))}
|
|
282
|
+
</tr>
|
|
283
|
+
</thead>
|
|
284
|
+
<tbody>
|
|
285
|
+
{block.rows.map((row, rIdx) => (
|
|
286
|
+
<tr key={rIdx}>
|
|
287
|
+
{row.map((cell, cIdx) => (
|
|
288
|
+
<td key={cIdx}>{renderInline(cell)}</td>
|
|
289
|
+
))}
|
|
290
|
+
</tr>
|
|
291
|
+
))}
|
|
292
|
+
</tbody>
|
|
293
|
+
</table>
|
|
294
|
+
</div>
|
|
295
|
+
);
|
|
296
|
+
case "p":
|
|
297
|
+
default:
|
|
298
|
+
return (
|
|
299
|
+
<p key={idx} className="md-p">
|
|
300
|
+
{block.lines.map((line, lineIdx) => (
|
|
301
|
+
<React.Fragment key={lineIdx}>
|
|
302
|
+
{renderInline(line)}
|
|
303
|
+
{lineIdx < block.lines.length - 1 && <br />}
|
|
304
|
+
</React.Fragment>
|
|
305
|
+
))}
|
|
306
|
+
</p>
|
|
307
|
+
);
|
|
308
|
+
}
|
|
84
309
|
})}
|
|
85
|
-
|
|
310
|
+
</div>
|
|
86
311
|
);
|
|
87
|
-
}
|
|
312
|
+
};
|