simple-module-chat 0.0.20__py3-none-any.whl
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.
- simple_module_chat-0.0.20.dist-info/METADATA +118 -0
- simple_module_chat-0.0.20.dist-info/RECORD +46 -0
- simple_module_chat-0.0.20.dist-info/WHEEL +4 -0
- simple_module_chat-0.0.20.dist-info/entry_points.txt +2 -0
- sm_chat/__init__.py +7 -0
- sm_chat/agent/__init__.py +3 -0
- sm_chat/agent/definition.py +72 -0
- sm_chat/agent/instructions.py +101 -0
- sm_chat/agent/toolset.py +102 -0
- sm_chat/contracts/__init__.py +21 -0
- sm_chat/contracts/registry.py +61 -0
- sm_chat/contracts/types.py +51 -0
- sm_chat/core/__init__.py +3 -0
- sm_chat/core/constants.py +55 -0
- sm_chat/core/settings.py +104 -0
- sm_chat/core/tenancy/__init__.py +125 -0
- sm_chat/core/tenancy/_mode.py +207 -0
- sm_chat/index.ts +26 -0
- sm_chat/locales/de.json +99 -0
- sm_chat/locales/en.json +99 -0
- sm_chat/module.py +85 -0
- sm_chat/package.json +20 -0
- sm_chat/pages/Index.tsx +108 -0
- sm_chat/ui/components/ApprovalCard.tsx +129 -0
- sm_chat/ui/components/ChatDrawerHost.tsx +248 -0
- sm_chat/ui/components/ChatExportActions.tsx +87 -0
- sm_chat/ui/components/ChatPanel.tsx +225 -0
- sm_chat/ui/components/MessageList.tsx +153 -0
- sm_chat/ui/components/SuggestedPrompts.tsx +65 -0
- sm_chat/ui/components/ThreadSidebar.tsx +222 -0
- sm_chat/ui/components/ToolCallPill.tsx +105 -0
- sm_chat/ui/hooks/threadMapping.ts +248 -0
- sm_chat/ui/hooks/useChatContext.ts +46 -0
- sm_chat/ui/hooks/useChatThread.ts +289 -0
- sm_chat/ui/hooks/useThreadStream.ts +87 -0
- sm_chat/ui/utils/api.ts +133 -0
- sm_chat/ui/utils/exportMarkdown.ts +66 -0
- sm_chat/ui/utils/i18n.ts +59 -0
- sm_chat/ui/utils/markdown.tsx +238 -0
- sm_chat/ui/utils/sse.ts +171 -0
- sm_chat/ui/utils/types.ts +111 -0
- sm_chat/web/__init__.py +3 -0
- sm_chat/web/endpoints/__init__.py +3 -0
- sm_chat/web/endpoints/api.py +117 -0
- sm_chat/web/endpoints/views.py +22 -0
- sm_chat/web/shared_props.py +33 -0
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/** Internal streaming turn runner for `useChatThread`. */
|
|
2
|
+
|
|
3
|
+
import type { ParsedAiError } from '@simple-module-py/ai';
|
|
4
|
+
import { type Dispatch, type MutableRefObject, type SetStateAction, useCallback } from 'react';
|
|
5
|
+
|
|
6
|
+
import { parseApprovalEvent, type SseChunk, streamThreadTurn } from '../utils/sse';
|
|
7
|
+
import type { ChatMessage, PendingApprovalItem } from '../utils/types';
|
|
8
|
+
import {
|
|
9
|
+
applyChunkToMessage,
|
|
10
|
+
mergePendingApproval,
|
|
11
|
+
parseRunErrorChunk,
|
|
12
|
+
toParsedError,
|
|
13
|
+
} from './threadMapping';
|
|
14
|
+
|
|
15
|
+
type UseThreadStreamArgs = {
|
|
16
|
+
csrfToken?: string;
|
|
17
|
+
abortRef: MutableRefObject<AbortController | null>;
|
|
18
|
+
setStreaming: Dispatch<SetStateAction<boolean>>;
|
|
19
|
+
setError: Dispatch<SetStateAction<ParsedAiError | null>>;
|
|
20
|
+
setMessages: Dispatch<SetStateAction<ChatMessage[]>>;
|
|
21
|
+
setPendingApprovals: Dispatch<SetStateAction<PendingApprovalItem[]>>;
|
|
22
|
+
refreshThreads: () => Promise<void>;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
export function useThreadStream({
|
|
26
|
+
csrfToken,
|
|
27
|
+
abortRef,
|
|
28
|
+
setStreaming,
|
|
29
|
+
setError,
|
|
30
|
+
setMessages,
|
|
31
|
+
setPendingApprovals,
|
|
32
|
+
refreshThreads,
|
|
33
|
+
}: UseThreadStreamArgs) {
|
|
34
|
+
return useCallback(
|
|
35
|
+
async (
|
|
36
|
+
threadId: string,
|
|
37
|
+
assistantMsgId: string,
|
|
38
|
+
turn: Parameters<typeof streamThreadTurn>[1],
|
|
39
|
+
fallbackErrorKey: string,
|
|
40
|
+
) => {
|
|
41
|
+
const controller = new AbortController();
|
|
42
|
+
abortRef.current = controller;
|
|
43
|
+
setStreaming(true);
|
|
44
|
+
setError(null);
|
|
45
|
+
|
|
46
|
+
const handleChunk = (chunk: SseChunk) => {
|
|
47
|
+
if (chunk.type === 'RUN_ERROR') {
|
|
48
|
+
setError(parseRunErrorChunk(chunk.code, chunk.message));
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
const approval = parseApprovalEvent(chunk);
|
|
52
|
+
if (approval) {
|
|
53
|
+
setPendingApprovals((prev) => mergePendingApproval(prev, approval));
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
setMessages((prev) =>
|
|
57
|
+
prev.map((m) => (m.id === assistantMsgId ? applyChunkToMessage(m, chunk) : m)),
|
|
58
|
+
);
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
try {
|
|
62
|
+
await streamThreadTurn(threadId, turn, {
|
|
63
|
+
signal: controller.signal,
|
|
64
|
+
csrfToken,
|
|
65
|
+
onChunk: handleChunk,
|
|
66
|
+
});
|
|
67
|
+
await refreshThreads();
|
|
68
|
+
return true;
|
|
69
|
+
} catch (err) {
|
|
70
|
+
if (err instanceof DOMException && err.name === 'AbortError') {
|
|
71
|
+
setMessages((prev) =>
|
|
72
|
+
prev.map((m) => (m.id === assistantMsgId ? { ...m, cancelled: true } : m)),
|
|
73
|
+
);
|
|
74
|
+
} else {
|
|
75
|
+
setError(toParsedError(err, fallbackErrorKey));
|
|
76
|
+
}
|
|
77
|
+
return false;
|
|
78
|
+
} finally {
|
|
79
|
+
if (abortRef.current === controller) {
|
|
80
|
+
abortRef.current = null;
|
|
81
|
+
}
|
|
82
|
+
setStreaming(false);
|
|
83
|
+
}
|
|
84
|
+
},
|
|
85
|
+
[abortRef, csrfToken, refreshThreads, setError, setMessages, setPendingApprovals, setStreaming],
|
|
86
|
+
);
|
|
87
|
+
}
|
sm_chat/ui/utils/api.ts
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/** REST API client for `/api/chat/context` and `/api/ai/threads`. */
|
|
2
|
+
|
|
3
|
+
import { type ParsedAiError, parseAiError } from '@simple-module-py/ai';
|
|
4
|
+
import { currentCsrfToken } from '@simple-module-py/ui/lib/csrf-token';
|
|
5
|
+
|
|
6
|
+
import type {
|
|
7
|
+
ChatContextData,
|
|
8
|
+
ThreadCancelResponse,
|
|
9
|
+
ThreadDetail,
|
|
10
|
+
ThreadListResponse,
|
|
11
|
+
ThreadSummary,
|
|
12
|
+
} from './types';
|
|
13
|
+
|
|
14
|
+
export const CSRF_HEADER = 'X-CSRF-Token';
|
|
15
|
+
|
|
16
|
+
const UNSAFE_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
|
|
17
|
+
|
|
18
|
+
export class ChatApiError extends Error {
|
|
19
|
+
readonly status: number;
|
|
20
|
+
readonly parsed: ParsedAiError;
|
|
21
|
+
|
|
22
|
+
constructor(status: number, parsed: ParsedAiError) {
|
|
23
|
+
super(parsed.message);
|
|
24
|
+
this.name = 'ChatApiError';
|
|
25
|
+
this.status = status;
|
|
26
|
+
this.parsed = parsed;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function buildCsrfHeaders(method: string, overrideToken?: string): Record<string, string> {
|
|
31
|
+
if (!UNSAFE_METHODS.has(method.toUpperCase())) return {};
|
|
32
|
+
const token = overrideToken ?? currentCsrfToken();
|
|
33
|
+
return token ? { [CSRF_HEADER]: token } : {};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export async function parseResponseError(response: Response): Promise<ChatApiError> {
|
|
37
|
+
const text = await response.text();
|
|
38
|
+
let body: unknown = text;
|
|
39
|
+
try {
|
|
40
|
+
body = text ? (JSON.parse(text) as unknown) : {};
|
|
41
|
+
} catch {
|
|
42
|
+
body = { detail: response.statusText || `HTTP ${response.status}` };
|
|
43
|
+
}
|
|
44
|
+
const parsed = parseAiError({ status: response.status, body });
|
|
45
|
+
return new ChatApiError(response.status, parsed);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async function checkedJson<T>(response: Response): Promise<T> {
|
|
49
|
+
if (!response.ok) throw await parseResponseError(response);
|
|
50
|
+
return (await response.json()) as T;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export async function fetchChatContext(): Promise<ChatContextData> {
|
|
54
|
+
return checkedJson<ChatContextData>(
|
|
55
|
+
await fetch('/api/chat/context', { credentials: 'same-origin' }),
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export async function listThreads(agentId: string): Promise<ThreadSummary[]> {
|
|
60
|
+
const params = new URLSearchParams({ agent_id: agentId });
|
|
61
|
+
const data = await checkedJson<ThreadListResponse>(
|
|
62
|
+
await fetch(`/api/ai/threads?${params}`, { credentials: 'same-origin' }),
|
|
63
|
+
);
|
|
64
|
+
return data.threads;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export async function createThread(
|
|
68
|
+
agentId: string,
|
|
69
|
+
title = '',
|
|
70
|
+
csrfToken?: string,
|
|
71
|
+
): Promise<ThreadSummary> {
|
|
72
|
+
return checkedJson<ThreadSummary>(
|
|
73
|
+
await fetch('/api/ai/threads', {
|
|
74
|
+
method: 'POST',
|
|
75
|
+
credentials: 'same-origin',
|
|
76
|
+
headers: {
|
|
77
|
+
'Content-Type': 'application/json',
|
|
78
|
+
...buildCsrfHeaders('POST', csrfToken),
|
|
79
|
+
},
|
|
80
|
+
body: JSON.stringify({ agent_id: agentId, title }),
|
|
81
|
+
}),
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export async function getThread(threadId: string): Promise<ThreadDetail> {
|
|
86
|
+
return checkedJson<ThreadDetail>(
|
|
87
|
+
await fetch(`/api/ai/threads/${encodeURIComponent(threadId)}`, {
|
|
88
|
+
credentials: 'same-origin',
|
|
89
|
+
}),
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export async function deleteThread(threadId: string, csrfToken?: string): Promise<void> {
|
|
94
|
+
const response = await fetch(`/api/ai/threads/${encodeURIComponent(threadId)}`, {
|
|
95
|
+
method: 'DELETE',
|
|
96
|
+
credentials: 'same-origin',
|
|
97
|
+
headers: buildCsrfHeaders('DELETE', csrfToken),
|
|
98
|
+
});
|
|
99
|
+
if (!response.ok && response.status !== 204) {
|
|
100
|
+
throw await parseResponseError(response);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export async function renameThread(
|
|
105
|
+
threadId: string,
|
|
106
|
+
title: string,
|
|
107
|
+
csrfToken?: string,
|
|
108
|
+
): Promise<ThreadSummary> {
|
|
109
|
+
return checkedJson<ThreadSummary>(
|
|
110
|
+
await fetch(`/api/ai/threads/${encodeURIComponent(threadId)}`, {
|
|
111
|
+
method: 'PATCH',
|
|
112
|
+
credentials: 'same-origin',
|
|
113
|
+
headers: {
|
|
114
|
+
'Content-Type': 'application/json',
|
|
115
|
+
...buildCsrfHeaders('PATCH', csrfToken),
|
|
116
|
+
},
|
|
117
|
+
body: JSON.stringify({ title }),
|
|
118
|
+
}),
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export async function cancelThread(
|
|
123
|
+
threadId: string,
|
|
124
|
+
csrfToken?: string,
|
|
125
|
+
): Promise<ThreadCancelResponse> {
|
|
126
|
+
return checkedJson<ThreadCancelResponse>(
|
|
127
|
+
await fetch(`/api/ai/threads/${encodeURIComponent(threadId)}/cancel`, {
|
|
128
|
+
method: 'POST',
|
|
129
|
+
credentials: 'same-origin',
|
|
130
|
+
headers: buildCsrfHeaders('POST', csrfToken),
|
|
131
|
+
}),
|
|
132
|
+
);
|
|
133
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/** Format and download a chat conversation as Markdown. */
|
|
2
|
+
|
|
3
|
+
import type { ChatMessage } from './types';
|
|
4
|
+
|
|
5
|
+
export type ExportMarkdownOptions = {
|
|
6
|
+
title?: string;
|
|
7
|
+
userLabel?: string;
|
|
8
|
+
assistantLabel?: string;
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
/** Format chat messages into a clean Markdown document. */
|
|
12
|
+
export function formatConversationMarkdown(
|
|
13
|
+
messages: ChatMessage[],
|
|
14
|
+
options: ExportMarkdownOptions = {},
|
|
15
|
+
): string {
|
|
16
|
+
const userLabel = options.userLabel ?? 'You';
|
|
17
|
+
const assistantLabel = options.assistantLabel ?? 'Assistant';
|
|
18
|
+
const sections: string[] = [];
|
|
19
|
+
|
|
20
|
+
const cleanTitle = options.title?.trim();
|
|
21
|
+
if (cleanTitle) {
|
|
22
|
+
sections.push(`# ${cleanTitle}`);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
for (const msg of messages) {
|
|
26
|
+
const body = msg.content.trim();
|
|
27
|
+
const tools = msg.toolCalls ?? [];
|
|
28
|
+
if (!body && tools.length === 0) continue;
|
|
29
|
+
|
|
30
|
+
const heading = msg.role === 'user' ? userLabel : assistantLabel;
|
|
31
|
+
const parts: string[] = [`## ${heading}`];
|
|
32
|
+
if (tools.length > 0) {
|
|
33
|
+
const toolNames = tools.map((tc) => `\`${tc.toolName}\``).join(', ');
|
|
34
|
+
parts.push(`_Tools: ${toolNames}_`);
|
|
35
|
+
}
|
|
36
|
+
if (body) {
|
|
37
|
+
parts.push(body);
|
|
38
|
+
}
|
|
39
|
+
sections.push(parts.join('\n\n'));
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
return sections.length > 0 ? `${sections.join('\n\n')}\n` : '';
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Build a safe `.md` filename from an optional conversation title. */
|
|
46
|
+
export function buildMarkdownFilename(title?: string): string {
|
|
47
|
+
const slug = (title ?? '')
|
|
48
|
+
.toLowerCase()
|
|
49
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
50
|
+
.replace(/^-+|-+$/g, '')
|
|
51
|
+
.slice(0, 64);
|
|
52
|
+
return `${slug || 'conversation'}.md`;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Trigger a browser download for a Markdown string. */
|
|
56
|
+
export function downloadMarkdown(markdown: string, filename: string): void {
|
|
57
|
+
const blob = new Blob([markdown], { type: 'text/markdown;charset=utf-8' });
|
|
58
|
+
const url = URL.createObjectURL(blob);
|
|
59
|
+
const link = document.createElement('a');
|
|
60
|
+
link.href = url;
|
|
61
|
+
link.download = filename;
|
|
62
|
+
document.body.append(link);
|
|
63
|
+
link.click();
|
|
64
|
+
link.remove();
|
|
65
|
+
URL.revokeObjectURL(url);
|
|
66
|
+
}
|
sm_chat/ui/utils/i18n.ts
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Module-local i18n helper for `@simple-module-py/chat`.
|
|
3
|
+
*
|
|
4
|
+
* Derives `keys.chat.<section>.<name>` from `locales/en.json` at compile time
|
|
5
|
+
* so any missing key is a type error at the call site.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { t as frameworkT, useT as useFrameworkT } from '@simple-module-py/i18n';
|
|
9
|
+
import { useMemo } from 'react';
|
|
10
|
+
|
|
11
|
+
import en from '../../locales/en.json';
|
|
12
|
+
|
|
13
|
+
const NAMESPACE = 'chat';
|
|
14
|
+
|
|
15
|
+
type KeyTree<T> = {
|
|
16
|
+
[K in keyof T]: T[K] extends string ? string : KeyTree<T[K]>;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
function build(node: Record<string, unknown>, prefix: string): Record<string, unknown> {
|
|
20
|
+
const out: Record<string, unknown> = {};
|
|
21
|
+
for (const [name, value] of Object.entries(node)) {
|
|
22
|
+
const path = `${prefix}.${name}`;
|
|
23
|
+
out[name] = typeof value === 'string' ? path : build(value as Record<string, unknown>, path);
|
|
24
|
+
}
|
|
25
|
+
return out;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export const keys: Record<typeof NAMESPACE, KeyTree<typeof en>> = {
|
|
29
|
+
[NAMESPACE]: build(en, NAMESPACE) as KeyTree<typeof en>,
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
function flatten(node: Record<string, unknown>, prefix: string, out: Record<string, string>) {
|
|
33
|
+
for (const [name, value] of Object.entries(node)) {
|
|
34
|
+
const path = `${prefix}.${name}`;
|
|
35
|
+
if (typeof value === 'string') out[path] = value;
|
|
36
|
+
else flatten(value as Record<string, unknown>, path, out);
|
|
37
|
+
}
|
|
38
|
+
return out;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const english: Record<string, string> = flatten(en, NAMESPACE, {});
|
|
42
|
+
|
|
43
|
+
export type TranslateParams = Record<string, unknown>;
|
|
44
|
+
export type Translate = (key: string, params?: TranslateParams) => string;
|
|
45
|
+
|
|
46
|
+
export function translate(key: string, params?: TranslateParams): string {
|
|
47
|
+
return frameworkT(key, { defaultValue: english[key] ?? key, ...params });
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function useT(): { t: Translate } {
|
|
51
|
+
const { t } = useFrameworkT();
|
|
52
|
+
return useMemo(
|
|
53
|
+
() => ({
|
|
54
|
+
t: (key: string, params?: TranslateParams) =>
|
|
55
|
+
t(key, { defaultValue: english[key] ?? key, ...params }),
|
|
56
|
+
}),
|
|
57
|
+
[t],
|
|
58
|
+
);
|
|
59
|
+
}
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lightweight, XSS-safe Markdown renderer.
|
|
3
|
+
*
|
|
4
|
+
* Never uses `dangerouslySetInnerHTML`, never renders raw HTML, and rejects
|
|
5
|
+
* unsafe link schemes (`javascript:`, `data:`, etc.). Internal `/...` links
|
|
6
|
+
* navigate via Inertia `router.visit` so the floating drawer stays alive.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { router } from '@inertiajs/react';
|
|
10
|
+
import type React from 'react';
|
|
11
|
+
|
|
12
|
+
type SafeUrl =
|
|
13
|
+
| { kind: 'internal'; href: string }
|
|
14
|
+
| { kind: 'external'; href: string }
|
|
15
|
+
| { kind: 'unsafe' };
|
|
16
|
+
|
|
17
|
+
export function classifyUrl(raw: string): SafeUrl {
|
|
18
|
+
const trimmed = raw.trim();
|
|
19
|
+
if (!trimmed) return { kind: 'unsafe' };
|
|
20
|
+
if (trimmed.startsWith('/') && !trimmed.startsWith('//')) {
|
|
21
|
+
return { kind: 'internal', href: trimmed };
|
|
22
|
+
}
|
|
23
|
+
if (/^https?:\/\//i.test(trimmed)) {
|
|
24
|
+
return { kind: 'external', href: trimmed };
|
|
25
|
+
}
|
|
26
|
+
return { kind: 'unsafe' };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const INLINE_TOKEN = /(`[^`]+`|\*\*[^*]+\*\*|\*[^*]+\*|\[[^\]]+\]\([^)]+\))/g;
|
|
30
|
+
|
|
31
|
+
function renderInline(text: string, keyPrefix: string): React.ReactNode[] {
|
|
32
|
+
const nodes: React.ReactNode[] = [];
|
|
33
|
+
let lastIndex = 0;
|
|
34
|
+
let tokenIdx = 0;
|
|
35
|
+
|
|
36
|
+
for (const match of text.matchAll(INLINE_TOKEN)) {
|
|
37
|
+
const idx = match.index ?? 0;
|
|
38
|
+
if (idx > lastIndex) {
|
|
39
|
+
nodes.push(text.slice(lastIndex, idx));
|
|
40
|
+
}
|
|
41
|
+
const token = match[0];
|
|
42
|
+
const key = `${keyPrefix}-${tokenIdx++}`;
|
|
43
|
+
|
|
44
|
+
if (token.startsWith('`') && token.endsWith('`')) {
|
|
45
|
+
nodes.push(
|
|
46
|
+
<code key={key} className="rounded bg-muted px-1 py-0.5 font-mono text-[0.85em]">
|
|
47
|
+
{token.slice(1, -1)}
|
|
48
|
+
</code>,
|
|
49
|
+
);
|
|
50
|
+
} else if (token.startsWith('**') && token.endsWith('**')) {
|
|
51
|
+
nodes.push(
|
|
52
|
+
<strong key={key} className="font-semibold">
|
|
53
|
+
{token.slice(2, -2)}
|
|
54
|
+
</strong>,
|
|
55
|
+
);
|
|
56
|
+
} else if (token.startsWith('*') && token.endsWith('*')) {
|
|
57
|
+
nodes.push(<em key={key}>{token.slice(1, -1)}</em>);
|
|
58
|
+
} else if (token.startsWith('[')) {
|
|
59
|
+
const sep = token.indexOf('](');
|
|
60
|
+
const label = token.slice(1, sep);
|
|
61
|
+
const url = token.slice(sep + 2, -1);
|
|
62
|
+
const safe = classifyUrl(url);
|
|
63
|
+
if (safe.kind === 'internal') {
|
|
64
|
+
nodes.push(
|
|
65
|
+
<a
|
|
66
|
+
key={key}
|
|
67
|
+
href={safe.href}
|
|
68
|
+
className="font-medium text-primary underline underline-offset-2 hover:opacity-80"
|
|
69
|
+
onClick={(event) => {
|
|
70
|
+
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
|
|
71
|
+
event.preventDefault();
|
|
72
|
+
router.visit(safe.href);
|
|
73
|
+
}}
|
|
74
|
+
>
|
|
75
|
+
{label}
|
|
76
|
+
</a>,
|
|
77
|
+
);
|
|
78
|
+
} else if (safe.kind === 'external') {
|
|
79
|
+
nodes.push(
|
|
80
|
+
<a
|
|
81
|
+
key={key}
|
|
82
|
+
href={safe.href}
|
|
83
|
+
target="_blank"
|
|
84
|
+
rel="noopener noreferrer"
|
|
85
|
+
className="font-medium text-primary underline underline-offset-2 hover:opacity-80"
|
|
86
|
+
>
|
|
87
|
+
{label}
|
|
88
|
+
</a>,
|
|
89
|
+
);
|
|
90
|
+
} else {
|
|
91
|
+
nodes.push(label);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
lastIndex = idx + token.length;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
if (lastIndex < text.length) {
|
|
98
|
+
nodes.push(text.slice(lastIndex));
|
|
99
|
+
}
|
|
100
|
+
return nodes;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
type ListItem = { id: string; text: string };
|
|
104
|
+
|
|
105
|
+
type Block =
|
|
106
|
+
| { id: string; kind: 'code'; lang: string; content: string }
|
|
107
|
+
| { id: string; kind: 'heading'; level: number; text: string }
|
|
108
|
+
| { id: string; kind: 'ul'; items: ListItem[] }
|
|
109
|
+
| { id: string; kind: 'ol'; items: ListItem[] }
|
|
110
|
+
| { id: string; kind: 'p'; text: string };
|
|
111
|
+
|
|
112
|
+
function parseBlocks(source: string): Block[] {
|
|
113
|
+
const lines = source.replace(/\r\n/g, '\n').split('\n');
|
|
114
|
+
const blocks: Block[] = [];
|
|
115
|
+
let i = 0;
|
|
116
|
+
|
|
117
|
+
while (i < lines.length) {
|
|
118
|
+
const startLine = i;
|
|
119
|
+
const line = lines[i];
|
|
120
|
+
if (!line.trim()) {
|
|
121
|
+
i += 1;
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
if (line.trimStart().startsWith('```')) {
|
|
126
|
+
const lang = line.trimStart().slice(3).trim();
|
|
127
|
+
const codeLines: string[] = [];
|
|
128
|
+
i += 1;
|
|
129
|
+
while (i < lines.length && !lines[i].trimStart().startsWith('```')) {
|
|
130
|
+
codeLines.push(lines[i]);
|
|
131
|
+
i += 1;
|
|
132
|
+
}
|
|
133
|
+
if (i < lines.length) i += 1;
|
|
134
|
+
blocks.push({ id: `code-${startLine}`, kind: 'code', lang, content: codeLines.join('\n') });
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const heading = line.match(/^(#{1,4})\s+(.+)$/);
|
|
139
|
+
if (heading) {
|
|
140
|
+
blocks.push({
|
|
141
|
+
id: `h-${startLine}`,
|
|
142
|
+
kind: 'heading',
|
|
143
|
+
level: heading[1].length,
|
|
144
|
+
text: heading[2].trim(),
|
|
145
|
+
});
|
|
146
|
+
i += 1;
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
if (/^\s*[-*]\s+/.test(line)) {
|
|
151
|
+
const items: ListItem[] = [];
|
|
152
|
+
while (i < lines.length && /^\s*[-*]\s+/.test(lines[i])) {
|
|
153
|
+
items.push({ id: `ul-${i}`, text: lines[i].replace(/^\s*[-*]\s+/, '') });
|
|
154
|
+
i += 1;
|
|
155
|
+
}
|
|
156
|
+
blocks.push({ id: `ul-${startLine}`, kind: 'ul', items });
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
if (/^\s*\d+\.\s+/.test(line)) {
|
|
161
|
+
const items: ListItem[] = [];
|
|
162
|
+
while (i < lines.length && /^\s*\d+\.\s+/.test(lines[i])) {
|
|
163
|
+
items.push({ id: `ol-${i}`, text: lines[i].replace(/^\s*\d+\.\s+/, '') });
|
|
164
|
+
i += 1;
|
|
165
|
+
}
|
|
166
|
+
blocks.push({ id: `ol-${startLine}`, kind: 'ol', items });
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const paraLines: string[] = [line];
|
|
171
|
+
i += 1;
|
|
172
|
+
while (
|
|
173
|
+
i < lines.length &&
|
|
174
|
+
lines[i].trim() !== '' &&
|
|
175
|
+
!lines[i].trimStart().startsWith('```') &&
|
|
176
|
+
!/^(#{1,4})\s+/.test(lines[i]) &&
|
|
177
|
+
!/^\s*[-*]\s+/.test(lines[i]) &&
|
|
178
|
+
!/^\s*\d+\.\s+/.test(lines[i])
|
|
179
|
+
) {
|
|
180
|
+
paraLines.push(lines[i]);
|
|
181
|
+
i += 1;
|
|
182
|
+
}
|
|
183
|
+
blocks.push({ id: `p-${startLine}`, kind: 'p', text: paraLines.join('\n') });
|
|
184
|
+
}
|
|
185
|
+
return blocks;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export function SafeMarkdown({ content }: { content: string }) {
|
|
189
|
+
const blocks = parseBlocks(content);
|
|
190
|
+
return (
|
|
191
|
+
<div className="space-y-2 text-sm leading-relaxed break-words">
|
|
192
|
+
{blocks.map((block) => {
|
|
193
|
+
if (block.kind === 'code') {
|
|
194
|
+
return (
|
|
195
|
+
<pre
|
|
196
|
+
key={block.id}
|
|
197
|
+
className="overflow-x-auto rounded-md border bg-muted/70 p-3 font-mono text-xs"
|
|
198
|
+
>
|
|
199
|
+
<code>{block.content}</code>
|
|
200
|
+
</pre>
|
|
201
|
+
);
|
|
202
|
+
}
|
|
203
|
+
if (block.kind === 'heading') {
|
|
204
|
+
const cls =
|
|
205
|
+
block.level <= 2 ? 'text-base font-semibold mt-2' : 'text-sm font-semibold mt-1.5';
|
|
206
|
+
return (
|
|
207
|
+
<p key={block.id} className={cls}>
|
|
208
|
+
{renderInline(block.text, block.id)}
|
|
209
|
+
</p>
|
|
210
|
+
);
|
|
211
|
+
}
|
|
212
|
+
if (block.kind === 'ul') {
|
|
213
|
+
return (
|
|
214
|
+
<ul key={block.id} className="list-disc space-y-1 pl-5">
|
|
215
|
+
{block.items.map((item) => (
|
|
216
|
+
<li key={item.id}>{renderInline(item.text, item.id)}</li>
|
|
217
|
+
))}
|
|
218
|
+
</ul>
|
|
219
|
+
);
|
|
220
|
+
}
|
|
221
|
+
if (block.kind === 'ol') {
|
|
222
|
+
return (
|
|
223
|
+
<ol key={block.id} className="list-decimal space-y-1 pl-5">
|
|
224
|
+
{block.items.map((item) => (
|
|
225
|
+
<li key={item.id}>{renderInline(item.text, item.id)}</li>
|
|
226
|
+
))}
|
|
227
|
+
</ol>
|
|
228
|
+
);
|
|
229
|
+
}
|
|
230
|
+
return (
|
|
231
|
+
<p key={block.id} className="whitespace-pre-wrap">
|
|
232
|
+
{renderInline(block.text, block.id)}
|
|
233
|
+
</p>
|
|
234
|
+
);
|
|
235
|
+
})}
|
|
236
|
+
</div>
|
|
237
|
+
);
|
|
238
|
+
}
|