@zhin.js/adapter-sandbox 5.0.4 → 5.0.6
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/CHANGELOG.md +45 -0
- package/README.md +22 -1
- package/adapters/sandbox.ts +26 -0
- package/lib/endpoint.d.ts +25 -0
- package/lib/endpoint.js +155 -0
- package/lib/index.d.ts +2 -22
- package/lib/index.js +2 -67
- package/lib/protocol.d.ts +52 -0
- package/lib/protocol.js +135 -0
- package/package.json +49 -28
- package/pages/sandbox.tsx +95 -0
- package/plugin.ts +8 -0
- package/schema.json +20 -0
- package/src/endpoint.ts +188 -0
- package/src/index.ts +12 -101
- package/src/protocol.ts +200 -0
- package/client/RichTextEditor.tsx +0 -429
- package/client/Sandbox.tsx +0 -588
- package/client/index.tsx +0 -11
- package/client/sandboxTransport.ts +0 -28
- package/client/tsconfig.json +0 -7
- package/dist/index.js +0 -45
- package/lib/index.d.ts.map +0 -1
- package/lib/index.js.map +0 -1
- package/lib/sandbox-ws.d.ts +0 -86
- package/lib/sandbox-ws.d.ts.map +0 -1
- package/lib/sandbox-ws.js +0 -295
- package/lib/sandbox-ws.js.map +0 -1
- package/lib/segment-mapper.d.ts +0 -2
- package/lib/segment-mapper.d.ts.map +0 -1
- package/lib/segment-mapper.js +0 -2
- package/lib/segment-mapper.js.map +0 -1
- package/src/sandbox-ws.ts +0 -404
- package/src/segment-mapper.ts +0 -1
- /package/{skills/sandbox/SKILL.md → agent/skills/sandbox.md} +0 -0
package/src/protocol.ts
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
/** Sandbox WebSocket wire protocol helpers (no legacy Adapter/Endpoint). */
|
|
2
|
+
|
|
3
|
+
export type MessageType = 'private' | 'group' | 'guild' | 'direct' | 'channel';
|
|
4
|
+
|
|
5
|
+
export interface MessageElement {
|
|
6
|
+
readonly type: string;
|
|
7
|
+
readonly data?: Record<string, unknown>;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export interface SandboxWsSocket {
|
|
11
|
+
send(data: string): void;
|
|
12
|
+
close(code?: number, reason?: string): void;
|
|
13
|
+
on?(event: 'message' | 'close' | 'error', listener: (...args: unknown[]) => void): void;
|
|
14
|
+
off?(
|
|
15
|
+
event: 'message' | 'close' | 'error',
|
|
16
|
+
listener: (...args: unknown[]) => void,
|
|
17
|
+
): void;
|
|
18
|
+
addEventListener?(
|
|
19
|
+
type: 'message' | 'close' | 'error',
|
|
20
|
+
listener: (ev: Event | MessageEvent | CloseEvent) => void,
|
|
21
|
+
): void;
|
|
22
|
+
removeEventListener?(
|
|
23
|
+
type: 'message' | 'close' | 'error',
|
|
24
|
+
listener: (ev: Event | MessageEvent | CloseEvent) => void,
|
|
25
|
+
): void;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export type ResolvedSandboxBot = {
|
|
29
|
+
readonly context: 'sandbox';
|
|
30
|
+
readonly name: string;
|
|
31
|
+
readonly owner: string;
|
|
32
|
+
readonly randomNamePerConnection: boolean;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
export interface SandboxAdapterConfig {
|
|
36
|
+
readonly endpoints?: ReadonlyArray<{
|
|
37
|
+
readonly context?: string;
|
|
38
|
+
readonly name?: string;
|
|
39
|
+
readonly owner?: string;
|
|
40
|
+
}>;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function resolveSandboxEndpoint(
|
|
44
|
+
appConfig: SandboxAdapterConfig,
|
|
45
|
+
): ResolvedSandboxBot {
|
|
46
|
+
const entry = appConfig.endpoints?.find((item) => item.context === 'sandbox');
|
|
47
|
+
const fixedName = typeof entry?.name === 'string' ? entry.name : undefined;
|
|
48
|
+
const name = fixedName || process.env.SANDBOX_BOT_NAME || 'sandbox-bot';
|
|
49
|
+
const owner = (typeof entry?.owner === 'string' && entry.owner)
|
|
50
|
+
|| process.env.SANDBOX_BOT_OWNER
|
|
51
|
+
|| 'sandbox-user';
|
|
52
|
+
return {
|
|
53
|
+
context: 'sandbox',
|
|
54
|
+
name,
|
|
55
|
+
owner,
|
|
56
|
+
randomNamePerConnection: !fixedName,
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function bindSandboxWsSocket(
|
|
61
|
+
ws: SandboxWsSocket,
|
|
62
|
+
handlers: {
|
|
63
|
+
onMessage: (raw: string) => void;
|
|
64
|
+
onClose: () => void;
|
|
65
|
+
onError?: (err: unknown) => void;
|
|
66
|
+
},
|
|
67
|
+
): () => void {
|
|
68
|
+
if (typeof ws.on === 'function') {
|
|
69
|
+
const onMessage = (...args: unknown[]) => {
|
|
70
|
+
const data = args[0];
|
|
71
|
+
const raw = typeof data === 'string'
|
|
72
|
+
? data
|
|
73
|
+
: data instanceof ArrayBuffer
|
|
74
|
+
? new TextDecoder().decode(data)
|
|
75
|
+
: Buffer.isBuffer(data)
|
|
76
|
+
? data.toString()
|
|
77
|
+
: String(data ?? '');
|
|
78
|
+
handlers.onMessage(raw);
|
|
79
|
+
};
|
|
80
|
+
ws.on('message', onMessage);
|
|
81
|
+
ws.on('close', handlers.onClose);
|
|
82
|
+
if (handlers.onError) ws.on('error', handlers.onError);
|
|
83
|
+
return () => {
|
|
84
|
+
ws.off?.('message', onMessage);
|
|
85
|
+
ws.off?.('close', handlers.onClose);
|
|
86
|
+
if (handlers.onError) ws.off?.('error', handlers.onError);
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
const onMessage = (ev: Event) => {
|
|
90
|
+
const data = (ev as MessageEvent).data;
|
|
91
|
+
handlers.onMessage(typeof data === 'string' ? data : '');
|
|
92
|
+
};
|
|
93
|
+
const onClose = () => handlers.onClose();
|
|
94
|
+
const onError = handlers.onError
|
|
95
|
+
? () => handlers.onError?.(new Error('WebSocket error'))
|
|
96
|
+
: undefined;
|
|
97
|
+
ws.addEventListener!('message', onMessage);
|
|
98
|
+
ws.addEventListener!('close', onClose);
|
|
99
|
+
if (onError) ws.addEventListener!('error', onError);
|
|
100
|
+
return () => {
|
|
101
|
+
ws.removeEventListener!('message', onMessage);
|
|
102
|
+
ws.removeEventListener!('close', onClose);
|
|
103
|
+
if (onError) ws.removeEventListener!('error', onError);
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function parseSandboxWsPayload(raw: string): {
|
|
108
|
+
type: MessageType;
|
|
109
|
+
id: string;
|
|
110
|
+
content: MessageElement[];
|
|
111
|
+
timestamp: number;
|
|
112
|
+
text: string;
|
|
113
|
+
action?: { id: string; payload: string };
|
|
114
|
+
} {
|
|
115
|
+
let payload: {
|
|
116
|
+
type?: MessageType;
|
|
117
|
+
id?: string;
|
|
118
|
+
content?: MessageElement[] | string;
|
|
119
|
+
text?: string;
|
|
120
|
+
timestamp?: number;
|
|
121
|
+
};
|
|
122
|
+
try {
|
|
123
|
+
payload = JSON.parse(raw) as typeof payload;
|
|
124
|
+
} catch {
|
|
125
|
+
payload = { text: raw };
|
|
126
|
+
}
|
|
127
|
+
const type = payload.type ?? 'private';
|
|
128
|
+
const id = payload.id ?? 'sandbox-user';
|
|
129
|
+
const content: MessageElement[] = typeof payload.content === 'string'
|
|
130
|
+
? [{ type: 'text', data: { text: payload.content } }]
|
|
131
|
+
: Array.isArray(payload.content)
|
|
132
|
+
? payload.content
|
|
133
|
+
: [{ type: 'text', data: { text: payload.text ?? raw } }];
|
|
134
|
+
|
|
135
|
+
const actionSegment = content.find((segment) => segment.type === 'action');
|
|
136
|
+
let action: { id: string; payload: string } | undefined;
|
|
137
|
+
if (actionSegment?.data) {
|
|
138
|
+
const actionPayload = typeof actionSegment.data.payload === 'string'
|
|
139
|
+
? actionSegment.data.payload
|
|
140
|
+
: typeof actionSegment.data.id === 'string'
|
|
141
|
+
? actionSegment.data.id
|
|
142
|
+
: '';
|
|
143
|
+
const actionId = typeof actionSegment.data.id === 'string'
|
|
144
|
+
? actionSegment.data.id
|
|
145
|
+
: actionPayload;
|
|
146
|
+
if (actionId || actionPayload) {
|
|
147
|
+
action = { id: actionId || actionPayload, payload: actionPayload || actionId };
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
let text = content
|
|
152
|
+
.flatMap((segment) => (segment.type === 'text' && typeof segment.data?.text === 'string'
|
|
153
|
+
? [segment.data.text]
|
|
154
|
+
: []))
|
|
155
|
+
.join('\n');
|
|
156
|
+
if (!text.trim()) {
|
|
157
|
+
text = (typeof payload.text === 'string' && payload.text.trim())
|
|
158
|
+
? payload.text
|
|
159
|
+
: action?.payload ?? raw;
|
|
160
|
+
}
|
|
161
|
+
return { type, id, content, timestamp: payload.timestamp ?? Date.now(), text, action };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Wire-encode an already-rendered outbound payload.
|
|
166
|
+
* Canonical segment mapping (old `segment-mapper` re-export of `to/fromCanonicalSegments`
|
|
167
|
+
* from legacy `zhin.js`) is intentionally not done here — the gateway/core render path
|
|
168
|
+
* owns that before `endpoint.send`.
|
|
169
|
+
*/
|
|
170
|
+
export function formatSandboxOutbound(payload: unknown): string {
|
|
171
|
+
if (typeof payload === 'string') {
|
|
172
|
+
return JSON.stringify({
|
|
173
|
+
content: [{ type: 'text', data: { text: payload } }],
|
|
174
|
+
timestamp: Date.now(),
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
if (Array.isArray(payload)) {
|
|
178
|
+
return JSON.stringify({
|
|
179
|
+
content: payload,
|
|
180
|
+
timestamp: Date.now(),
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
return JSON.stringify({ content: payload, timestamp: Date.now() });
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** WebSocket.OPEN 常量值;Node <22 无全局 WebSocket,不能用 WebSocket.OPEN。 */
|
|
187
|
+
const WS_OPEN = 1;
|
|
188
|
+
|
|
189
|
+
export function whenWsOpen(ws: SandboxWsSocket, fn: () => void): void {
|
|
190
|
+
const std = ws as WebSocket;
|
|
191
|
+
if (typeof std.readyState === 'number') {
|
|
192
|
+
if (std.readyState === WS_OPEN) {
|
|
193
|
+
fn();
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
std.addEventListener('open', fn, { once: true });
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
fn();
|
|
200
|
+
}
|
|
@@ -1,429 +0,0 @@
|
|
|
1
|
-
import { useRef, useEffect, forwardRef, useImperativeHandle } from 'react'
|
|
2
|
-
|
|
3
|
-
export interface MessageSegment {
|
|
4
|
-
type: 'text' | 'mention' | 'at' | 'face' | 'image' | 'video' | 'audio' | 'record' | 'file'
|
|
5
|
-
data: Record<string, any>
|
|
6
|
-
}
|
|
7
|
-
|
|
8
|
-
export interface RichTextEditorProps {
|
|
9
|
-
placeholder?: string
|
|
10
|
-
onSend?: (text: string, segments: MessageSegment[]) => void
|
|
11
|
-
onChange?: (text: string, segments: MessageSegment[]) => void
|
|
12
|
-
onAtTrigger?: (show: boolean, searchQuery: string, position?: { top: number; left: number }) => void
|
|
13
|
-
minHeight?: string
|
|
14
|
-
maxHeight?: string
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
export interface RichTextEditorRef {
|
|
18
|
-
focus: () => void
|
|
19
|
-
clear: () => void
|
|
20
|
-
insertFace: (faceId: number) => void
|
|
21
|
-
insertImage: (url: string) => void
|
|
22
|
-
insertVideo: (url: string) => void
|
|
23
|
-
insertAudio: (url: string) => void
|
|
24
|
-
insertAt: (name: string, id?: string) => void
|
|
25
|
-
replaceAtTrigger: (name: string, id?: string) => void
|
|
26
|
-
getContent: () => { text: string; segments: MessageSegment[] }
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
const RichTextEditor = forwardRef<RichTextEditorRef, RichTextEditorProps>(
|
|
30
|
-
({ placeholder = '输入消息...', onSend, onChange, onAtTrigger, minHeight = '44px', maxHeight = '200px' }, ref) => {
|
|
31
|
-
const editorRef = useRef<HTMLDivElement>(null)
|
|
32
|
-
const atTriggerTextRef = useRef<Text | null>(null)
|
|
33
|
-
|
|
34
|
-
// 解析编辑器内容为文本和消息段
|
|
35
|
-
const parseEditorContent = (): { text: string; segments: MessageSegment[] } => {
|
|
36
|
-
if (!editorRef.current) return { text: '', segments: [] }
|
|
37
|
-
|
|
38
|
-
let text = ''
|
|
39
|
-
const segments: MessageSegment[] = []
|
|
40
|
-
const nodes = Array.from(editorRef.current.childNodes)
|
|
41
|
-
|
|
42
|
-
for (const node of nodes) {
|
|
43
|
-
if (node.nodeType === Node.TEXT_NODE) {
|
|
44
|
-
const textContent = node.textContent || ''
|
|
45
|
-
if (textContent) {
|
|
46
|
-
text += textContent
|
|
47
|
-
segments.push({ type: 'text', data: { text: textContent } })
|
|
48
|
-
}
|
|
49
|
-
} else if (node.nodeType === Node.ELEMENT_NODE) {
|
|
50
|
-
const el = node as HTMLElement
|
|
51
|
-
|
|
52
|
-
if (el.classList.contains('editor-face')) {
|
|
53
|
-
const faceId = el.dataset.id
|
|
54
|
-
text += `[face:${faceId}]`
|
|
55
|
-
segments.push({ type: 'face', data: { id: Number(faceId) } })
|
|
56
|
-
} else if (el.classList.contains('editor-image')) {
|
|
57
|
-
const imageUrl = el.dataset.url
|
|
58
|
-
text += `[image:${imageUrl}]`
|
|
59
|
-
segments.push({ type: 'image', data: { url: imageUrl } })
|
|
60
|
-
} else if (el.classList.contains('editor-video')) {
|
|
61
|
-
const u = el.dataset.url || ''
|
|
62
|
-
text += `[video:${u}]`
|
|
63
|
-
segments.push({ type: 'video', data: { url: u } })
|
|
64
|
-
} else if (el.classList.contains('editor-audio')) {
|
|
65
|
-
const u = el.dataset.url || ''
|
|
66
|
-
text += `[audio:${u}]`
|
|
67
|
-
segments.push({ type: 'audio', data: { url: u } })
|
|
68
|
-
} else if (el.classList.contains('editor-at')) {
|
|
69
|
-
const name = el.dataset.name
|
|
70
|
-
const id = el.dataset.id
|
|
71
|
-
text += `[@${name}]`
|
|
72
|
-
segments.push({
|
|
73
|
-
type: 'mention',
|
|
74
|
-
data: id ? { target: id, name } : { target: name, name },
|
|
75
|
-
})
|
|
76
|
-
} else if (el.tagName === 'BR') {
|
|
77
|
-
text += '\n'
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
return { text, segments }
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
// 插入表情
|
|
86
|
-
const insertFace = (faceId: number) => {
|
|
87
|
-
if (!editorRef.current) return
|
|
88
|
-
|
|
89
|
-
const img = document.createElement('img')
|
|
90
|
-
img.src = `https://face.viki.moe/apng/${faceId}.png`
|
|
91
|
-
img.alt = `[face:${faceId}]`
|
|
92
|
-
img.dataset.type = 'face'
|
|
93
|
-
img.dataset.id = String(faceId)
|
|
94
|
-
img.className = 'editor-face'
|
|
95
|
-
|
|
96
|
-
insertNodeAtCursor(img)
|
|
97
|
-
handleChange()
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
// 插入图片
|
|
101
|
-
const insertImage = (url: string) => {
|
|
102
|
-
if (!editorRef.current || !url.trim()) return
|
|
103
|
-
|
|
104
|
-
const img = document.createElement('img')
|
|
105
|
-
img.src = url.trim()
|
|
106
|
-
img.alt = `[image:${url.trim()}]`
|
|
107
|
-
img.dataset.type = 'image'
|
|
108
|
-
img.dataset.url = url.trim()
|
|
109
|
-
img.className = 'editor-image'
|
|
110
|
-
|
|
111
|
-
insertNodeAtCursor(img)
|
|
112
|
-
handleChange()
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
const insertVideo = (url: string) => {
|
|
116
|
-
if (!editorRef.current || !url.trim()) return
|
|
117
|
-
const u = url.trim()
|
|
118
|
-
const span = document.createElement('span')
|
|
119
|
-
span.className = 'editor-video'
|
|
120
|
-
span.dataset.url = u
|
|
121
|
-
span.contentEditable = 'false'
|
|
122
|
-
span.textContent = '📹 视频'
|
|
123
|
-
insertNodeAtCursor(span)
|
|
124
|
-
handleChange()
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
const insertAudio = (url: string) => {
|
|
128
|
-
if (!editorRef.current || !url.trim()) return
|
|
129
|
-
const u = url.trim()
|
|
130
|
-
const span = document.createElement('span')
|
|
131
|
-
span.className = 'editor-audio'
|
|
132
|
-
span.dataset.url = u
|
|
133
|
-
span.contentEditable = 'false'
|
|
134
|
-
span.textContent = '🎵 音频'
|
|
135
|
-
insertNodeAtCursor(span)
|
|
136
|
-
handleChange()
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
// 插入 @ 提及
|
|
140
|
-
const insertAt = (name: string, id?: string) => {
|
|
141
|
-
if (!editorRef.current || !name.trim()) return
|
|
142
|
-
|
|
143
|
-
// 创建 @ 标签容器
|
|
144
|
-
const atBox = document.createElement('span')
|
|
145
|
-
atBox.dataset.type = 'at'
|
|
146
|
-
atBox.dataset.name = name
|
|
147
|
-
if (id) atBox.dataset.id = id
|
|
148
|
-
atBox.className = 'editor-at'
|
|
149
|
-
atBox.contentEditable = 'false' // 不可编辑
|
|
150
|
-
|
|
151
|
-
// 创建 @ 符号
|
|
152
|
-
const atSymbol = document.createElement('span')
|
|
153
|
-
atSymbol.textContent = '@'
|
|
154
|
-
atSymbol.className = 'editor-at-symbol'
|
|
155
|
-
|
|
156
|
-
// 创建名称
|
|
157
|
-
const nameText = document.createElement('span')
|
|
158
|
-
nameText.textContent = name
|
|
159
|
-
nameText.className = 'editor-at-name'
|
|
160
|
-
|
|
161
|
-
atBox.appendChild(atSymbol)
|
|
162
|
-
atBox.appendChild(nameText)
|
|
163
|
-
|
|
164
|
-
insertNodeAtCursor(atBox)
|
|
165
|
-
handleChange()
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
// 在光标位置插入节点
|
|
169
|
-
const insertNodeAtCursor = (node: Node) => {
|
|
170
|
-
if (!editorRef.current) return
|
|
171
|
-
|
|
172
|
-
// 先聚焦编辑器
|
|
173
|
-
editorRef.current.focus()
|
|
174
|
-
const selection = window.getSelection()
|
|
175
|
-
if (selection && selection.rangeCount > 0) {
|
|
176
|
-
const range = selection.getRangeAt(0)
|
|
177
|
-
|
|
178
|
-
// 检查光标是否在编辑器内部
|
|
179
|
-
const isInsideEditor = editorRef.current.contains(range.commonAncestorContainer)
|
|
180
|
-
|
|
181
|
-
if (isInsideEditor) {
|
|
182
|
-
// 光标在编辑器内,插入到光标位置
|
|
183
|
-
range.deleteContents()
|
|
184
|
-
range.insertNode(node)
|
|
185
|
-
range.collapse(false)
|
|
186
|
-
selection.removeAllRanges()
|
|
187
|
-
selection.addRange(range)
|
|
188
|
-
} else {
|
|
189
|
-
// 光标不在编辑器内,追加到末尾
|
|
190
|
-
editorRef.current.appendChild(node)
|
|
191
|
-
|
|
192
|
-
// 移动光标到新插入的节点后面
|
|
193
|
-
const newRange = document.createRange()
|
|
194
|
-
newRange.setStartAfter(node)
|
|
195
|
-
newRange.collapse(true)
|
|
196
|
-
selection.removeAllRanges()
|
|
197
|
-
selection.addRange(newRange)
|
|
198
|
-
}
|
|
199
|
-
} else {
|
|
200
|
-
// 没有选区,直接追加到末尾
|
|
201
|
-
editorRef.current.appendChild(node)
|
|
202
|
-
|
|
203
|
-
// 创建新选区并移动光标到末尾
|
|
204
|
-
const selection = window.getSelection()
|
|
205
|
-
if (selection) {
|
|
206
|
-
const newRange = document.createRange()
|
|
207
|
-
newRange.setStartAfter(node)
|
|
208
|
-
newRange.collapse(true)
|
|
209
|
-
selection.removeAllRanges()
|
|
210
|
-
selection.addRange(newRange)
|
|
211
|
-
}
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
// 清空编辑器
|
|
217
|
-
const clear = () => {
|
|
218
|
-
if (editorRef.current) {
|
|
219
|
-
editorRef.current.innerHTML = ''
|
|
220
|
-
handleChange()
|
|
221
|
-
}
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
// 聚焦编辑器
|
|
225
|
-
const focus = () => {
|
|
226
|
-
editorRef.current?.focus()
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
// 获取内容
|
|
230
|
-
const getContent = () => {
|
|
231
|
-
return parseEditorContent()
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
// 检测 @ 输入
|
|
235
|
-
const checkAtTrigger = () => {
|
|
236
|
-
if (!editorRef.current || !onAtTrigger) return
|
|
237
|
-
|
|
238
|
-
const selection = window.getSelection()
|
|
239
|
-
if (!selection || selection.rangeCount === 0) {
|
|
240
|
-
onAtTrigger(false, '')
|
|
241
|
-
atTriggerTextRef.current = null
|
|
242
|
-
return
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
const range = selection.getRangeAt(0)
|
|
246
|
-
|
|
247
|
-
// 检查光标是否在编辑器内
|
|
248
|
-
if (!editorRef.current.contains(range.commonAncestorContainer)) {
|
|
249
|
-
onAtTrigger(false, '')
|
|
250
|
-
atTriggerTextRef.current = null
|
|
251
|
-
return
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
// 获取光标前的文本节点
|
|
255
|
-
const node = range.startContainer
|
|
256
|
-
if (node.nodeType !== Node.TEXT_NODE) {
|
|
257
|
-
onAtTrigger(false, '')
|
|
258
|
-
atTriggerTextRef.current = null
|
|
259
|
-
return
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
const textNode = node as Text
|
|
263
|
-
const textBeforeCursor = textNode.textContent?.substring(0, range.startOffset) || ''
|
|
264
|
-
|
|
265
|
-
// 查找最近的 @ 符号位置
|
|
266
|
-
const atIndex = textBeforeCursor.lastIndexOf('@')
|
|
267
|
-
|
|
268
|
-
// 检查是否找到 @ 且后面没有空格(表示仍在输入 @提及)
|
|
269
|
-
if (atIndex !== -1) {
|
|
270
|
-
const textAfterAt = textBeforeCursor.substring(atIndex + 1)
|
|
271
|
-
|
|
272
|
-
// 如果 @ 后面有空格,则不触发
|
|
273
|
-
if (textAfterAt.includes(' ') || textAfterAt.includes('\n')) {
|
|
274
|
-
onAtTrigger(false, '')
|
|
275
|
-
atTriggerTextRef.current = null
|
|
276
|
-
return
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
atTriggerTextRef.current = textNode
|
|
280
|
-
|
|
281
|
-
// 计算 @ 位置
|
|
282
|
-
const tempRange = document.createRange()
|
|
283
|
-
tempRange.setStart(textNode, atIndex)
|
|
284
|
-
tempRange.setEnd(textNode, atIndex + 1)
|
|
285
|
-
const rect = tempRange.getBoundingClientRect()
|
|
286
|
-
const editorRect = editorRef.current.getBoundingClientRect()
|
|
287
|
-
|
|
288
|
-
// 传递搜索查询(@ 后面的文本)
|
|
289
|
-
onAtTrigger(true, textAfterAt, {
|
|
290
|
-
top: rect.bottom - editorRect.top,
|
|
291
|
-
left: rect.left - editorRect.left
|
|
292
|
-
})
|
|
293
|
-
} else {
|
|
294
|
-
onAtTrigger(false, '')
|
|
295
|
-
atTriggerTextRef.current = null
|
|
296
|
-
}
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
// 处理内容变化
|
|
300
|
-
const handleChange = () => {
|
|
301
|
-
checkAtTrigger()
|
|
302
|
-
|
|
303
|
-
if (onChange) {
|
|
304
|
-
const { text, segments } = parseEditorContent()
|
|
305
|
-
onChange(text, segments)
|
|
306
|
-
}
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
// 删除触发的 @ 符号和搜索文本并插入用户
|
|
310
|
-
const replaceAtTrigger = (name: string, id?: string) => {
|
|
311
|
-
if (!atTriggerTextRef.current) return
|
|
312
|
-
|
|
313
|
-
const textNode = atTriggerTextRef.current
|
|
314
|
-
const text = textNode.textContent || ''
|
|
315
|
-
const atIndex = text.lastIndexOf('@')
|
|
316
|
-
|
|
317
|
-
if (atIndex !== -1) {
|
|
318
|
-
// 找到 @ 后面的内容(搜索文本)
|
|
319
|
-
const textAfter = text.substring(atIndex + 1)
|
|
320
|
-
const endIndex = atIndex + 1 + textAfter.split(/[\s\n]/)[0].length
|
|
321
|
-
|
|
322
|
-
// 删除 @ 符号和搜索文本
|
|
323
|
-
const beforeAt = text.substring(0, atIndex)
|
|
324
|
-
const afterSearch = text.substring(endIndex)
|
|
325
|
-
textNode.textContent = beforeAt + afterSearch
|
|
326
|
-
|
|
327
|
-
// 移动光标到删除位置
|
|
328
|
-
const selection = window.getSelection()
|
|
329
|
-
if (selection) {
|
|
330
|
-
const range = document.createRange()
|
|
331
|
-
range.setStart(textNode, atIndex)
|
|
332
|
-
range.collapse(true)
|
|
333
|
-
selection.removeAllRanges()
|
|
334
|
-
selection.addRange(range)
|
|
335
|
-
}
|
|
336
|
-
}
|
|
337
|
-
|
|
338
|
-
atTriggerTextRef.current = null
|
|
339
|
-
insertAt(name, id)
|
|
340
|
-
}
|
|
341
|
-
|
|
342
|
-
// 处理粘贴事件
|
|
343
|
-
const handlePaste = (e: React.ClipboardEvent<HTMLDivElement>) => {
|
|
344
|
-
e.preventDefault()
|
|
345
|
-
const clipboardData = e.clipboardData
|
|
346
|
-
|
|
347
|
-
// 优先处理图片粘贴
|
|
348
|
-
const items = Array.from(clipboardData.items)
|
|
349
|
-
const imageItem = items.find((item) => item.type.startsWith('image/'))
|
|
350
|
-
if (imageItem) {
|
|
351
|
-
const file = imageItem.getAsFile()
|
|
352
|
-
if (file) {
|
|
353
|
-
const reader = new FileReader()
|
|
354
|
-
reader.onload = () => {
|
|
355
|
-
if (typeof reader.result === 'string') {
|
|
356
|
-
insertImage(reader.result)
|
|
357
|
-
}
|
|
358
|
-
}
|
|
359
|
-
reader.readAsDataURL(file)
|
|
360
|
-
}
|
|
361
|
-
return
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
// 纯文本粘贴(去除富文本格式)
|
|
365
|
-
const text = clipboardData.getData('text/plain')
|
|
366
|
-
if (text) {
|
|
367
|
-
document.execCommand('insertText', false, text)
|
|
368
|
-
handleChange()
|
|
369
|
-
}
|
|
370
|
-
}
|
|
371
|
-
|
|
372
|
-
// 处理键盘事件
|
|
373
|
-
const handleKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
|
|
374
|
-
if (e.key === 'Enter' && !e.shiftKey) {
|
|
375
|
-
e.preventDefault()
|
|
376
|
-
if (onSend) {
|
|
377
|
-
const { text, segments } = parseEditorContent()
|
|
378
|
-
onSend(text, segments)
|
|
379
|
-
}
|
|
380
|
-
}
|
|
381
|
-
}
|
|
382
|
-
|
|
383
|
-
// 暴露方法给父组件
|
|
384
|
-
useImperativeHandle(ref, () => ({
|
|
385
|
-
focus,
|
|
386
|
-
clear,
|
|
387
|
-
insertFace,
|
|
388
|
-
insertImage,
|
|
389
|
-
insertVideo,
|
|
390
|
-
insertAudio,
|
|
391
|
-
insertAt,
|
|
392
|
-
replaceAtTrigger,
|
|
393
|
-
getContent
|
|
394
|
-
}))
|
|
395
|
-
|
|
396
|
-
return (
|
|
397
|
-
<div
|
|
398
|
-
ref={editorRef}
|
|
399
|
-
contentEditable
|
|
400
|
-
suppressContentEditableWarning
|
|
401
|
-
onInput={handleChange}
|
|
402
|
-
onKeyDown={handleKeyDown}
|
|
403
|
-
onPaste={handlePaste}
|
|
404
|
-
data-placeholder={placeholder}
|
|
405
|
-
className="rich-text-editor"
|
|
406
|
-
style={{
|
|
407
|
-
width: '100%',
|
|
408
|
-
minHeight,
|
|
409
|
-
maxHeight,
|
|
410
|
-
padding: '0.5rem 0.75rem',
|
|
411
|
-
border: '1px solid var(--gray-6)',
|
|
412
|
-
borderRadius: '6px',
|
|
413
|
-
backgroundColor: 'var(--gray-1)',
|
|
414
|
-
fontSize: 'var(--font-size-2)',
|
|
415
|
-
outline: 'none',
|
|
416
|
-
overflowY: 'auto',
|
|
417
|
-
lineHeight: '1.5',
|
|
418
|
-
wordWrap: 'break-word',
|
|
419
|
-
color: 'var(--gray-12)'
|
|
420
|
-
}}
|
|
421
|
-
/>
|
|
422
|
-
)
|
|
423
|
-
}
|
|
424
|
-
)
|
|
425
|
-
|
|
426
|
-
RichTextEditor.displayName = 'RichTextEditor'
|
|
427
|
-
|
|
428
|
-
export default RichTextEditor
|
|
429
|
-
|