dsh-share-chat 0.0.0-stage → 0.3.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/client.js ADDED
@@ -0,0 +1,2500 @@
1
+ /**
2
+ * 社交 —— DSH 对话流里的一个 View
3
+ *
4
+ * 全部逻辑在浏览器里:直接调 relay 的 HTTPS API。
5
+ * 主页面没有 CSP,relay 已开 CORS 预检,所以不需要 Host 代理。
6
+ *
7
+ * v0 范围:注册/登录、好友、私聊、快照渲染。
8
+ */
9
+ window.__ModuleLoader__.load({
10
+ id: 'dsh-share-chat',
11
+ factory(require) {
12
+ const React = require('react')
13
+ const h = React.createElement
14
+ const { useCallback, useEffect, useRef, useState } = React
15
+
16
+ const K_AUTH = 'dsh-share-chat.auth'
17
+ const K_SERVER = 'dsh-share-chat.server'
18
+ const K_DEV = 'dsh-share-chat.dev'
19
+ const DEFAULT_SERVER = 'https://xdxy-pet.com/relay'
20
+ const POLL_MS = 5000
21
+ /** 内嵌小游戏(微信小游戏的浏览器移植版,和 /api/fish/ 同源) */
22
+ const GAME_URL = 'https://xdxy-pet.com/game/'
23
+
24
+ /**
25
+ * 开发开关:只有本地把 dsh-share-chat.dev 设成 '1' 才显示未完成的调试入口。
26
+ * 发给朋友的版本里这些入口默认不可见。
27
+ */
28
+ const DEV = (() => {
29
+ try {
30
+ return window.localStorage.getItem(K_DEV) === '1'
31
+ } catch {
32
+ return false
33
+ }
34
+ })()
35
+
36
+ // ───────────────────────── 存取 ─────────────────────────
37
+
38
+ function readJson(key) {
39
+ try {
40
+ return JSON.parse(window.localStorage.getItem(key) || 'null')
41
+ } catch {
42
+ return null
43
+ }
44
+ }
45
+ function writeJson(key, value) {
46
+ try {
47
+ window.localStorage.setItem(key, JSON.stringify(value))
48
+ } catch {
49
+ /* 隐私模式下写不进去,忽略 */
50
+ }
51
+ }
52
+ function dropKey(key) {
53
+ try {
54
+ window.localStorage.removeItem(key)
55
+ } catch {
56
+ /* 同上 */
57
+ }
58
+ }
59
+
60
+ // ───────────────────────── API ─────────────────────────
61
+
62
+ async function api(server, path, options) {
63
+ const opts = options || {}
64
+ const headers = {}
65
+ if (opts.body !== undefined) headers['content-type'] = 'application/json'
66
+ if (opts.token) headers.authorization = 'Bearer ' + opts.token
67
+ const res = await fetch(String(server).replace(/\/+$/, '') + path, {
68
+ method: opts.method || 'GET',
69
+ headers,
70
+ body: opts.body === undefined ? undefined : JSON.stringify(opts.body),
71
+ })
72
+ let data = null
73
+ try {
74
+ data = await res.json()
75
+ } catch {
76
+ /* 非 JSON 响应 */
77
+ }
78
+ if (!res.ok) {
79
+ const err = new Error((data && data.error) || 'http-' + res.status)
80
+ err.code = (data && data.error) || 'http-' + res.status
81
+ throw err
82
+ }
83
+ return data
84
+ }
85
+
86
+ const MESSAGES = {
87
+ 'invalid-invite': '邀请码不对',
88
+ 'invalid-id': '账号名不合法(2–20 个字母/数字/下划线/连字符)',
89
+ 'id-taken': '这个账号已经被注册了',
90
+ 'unauthorized': '登录已失效,请重新登录',
91
+ 'bad-credentials': '账号或密码不对',
92
+ 'password-too-short': '密码至少 6 位',
93
+ 'no-such-user': '没有这个账号',
94
+ 'not-friend': '你们还不是好友',
95
+ 'not-allowed': '无权查看这段内容',
96
+ 'expired': '这段内容已过期',
97
+ 'not-found': '内容不存在',
98
+ 'empty': '不能发空消息',
99
+ }
100
+ function friendly(err) {
101
+ const code = (err && err.code) || ''
102
+ if (MESSAGES[code]) return MESSAGES[code]
103
+ if (err && /Failed to fetch|NetworkError|load failed/i.test(err.message || '')) {
104
+ return '连不上服务器,检查地址和网络'
105
+ }
106
+ return code || (err && err.message) || '出错了'
107
+ }
108
+
109
+ /** 表情面板里的一批常用表情(unicode,直接当文字发) */
110
+ const EMOJIS = [
111
+ '😀', '😄', '😁', '😂', '🤣', '😊', '😍', '🤔', '😅', '😭',
112
+ '😡', '😱', '🥳', '😴', '🤤', '🤝', '👍', '👎', '👏', '🙏',
113
+ '💪', '🔥', '✨', '🎉', '❤️', '💔', '💡', '✅', '❌', '⚠️',
114
+ '🐳', '🐱', '🐶', '🍜', '☕', '🌙', '☀️', '🚀', '👀', '🤯',
115
+ ]
116
+
117
+ function kbText(size) {
118
+ const n = Number(size) || 0
119
+ if (n < 1024) return n + ' B'
120
+ if (n < 1024 * 1024) return (n / 1024).toFixed(1) + ' KB'
121
+ return (n / 1024 / 1024).toFixed(1) + ' MB'
122
+ }
123
+
124
+ /** 图片 / 视频缩略图的统一尺寸(0.1.6 起) */
125
+ const MEDIA_STYLE = {
126
+ maxWidth: '100%',
127
+ maxHeight: '340px',
128
+ borderRadius: '14px',
129
+ display: 'block',
130
+ border: '1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.2))',
131
+ }
132
+
133
+ /** 按类型/扩展名给一个图标,充当非图片文件的「缩略图」(0.1.6 起) */
134
+ function fileIcon(type, name) {
135
+ const t = String(type || '')
136
+ const ext = String(name || '')
137
+ .toLowerCase()
138
+ .split('.')
139
+ .pop()
140
+ if (t.startsWith('image/')) return '🖼️'
141
+ if (t.startsWith('video/')) return '🎬'
142
+ if (t.startsWith('audio/')) return '🎵'
143
+ if (t === 'application/pdf' || ext === 'pdf') return '📕'
144
+ if (/zip|rar|7z|tar|gzip|xz/.test(t) || ['zip', 'rar', '7z', 'tar', 'gz', 'xz'].includes(ext)) {
145
+ return '📦'
146
+ }
147
+ if (/^(xls|xlsx|csv|ods)$/.test(ext) || t.includes('spreadsheet')) return '📊'
148
+ if (/^(doc|docx|rtf)$/.test(ext) || t.includes('word')) return '📝'
149
+ if (/^(ppt|pptx|key)$/.test(ext) || t.includes('presentation')) return '📽️'
150
+ if (
151
+ /^(js|ts|tsx|jsx|mjs|json|py|go|rs|java|c|h|cpp|css|html|sh|ps1|bat|yml|yaml|toml|md)$/.test(
152
+ ext,
153
+ )
154
+ ) {
155
+ return '💻'
156
+ }
157
+ if (/^application\/(json|xml|javascript)/.test(t)) return '💻'
158
+ return '📄'
159
+ }
160
+
161
+ // ───────────────────────── 样式 ─────────────────────────
162
+
163
+ const STYLE_ID = 'dsh-share-chat-style'
164
+
165
+ /** 全部用 DSH 主题 token(--dsw-alias-*),带亮/暗两套都能用的兜底值 */
166
+ const CSS = `
167
+ .sc-root{display:flex;flex-direction:column;height:100%;min-height:0;color:var(--dsw-alias-label-primary,#1f2328);font-size:13px;line-height:1.55;-webkit-font-smoothing:antialiased}
168
+ .sc-root *{box-sizing:border-box}
169
+ .sc-root ::-webkit-scrollbar{width:8px;height:8px}
170
+ .sc-root ::-webkit-scrollbar-thumb{background:var(--dsw-alias-scrollbar-hover-l1,rgba(128,128,128,.32));border-radius:99px}
171
+ .sc-root ::-webkit-scrollbar-track{background:transparent}
172
+ .sc-grow{flex:1;min-width:0}
173
+
174
+ .sc-btn{display:inline-flex;align-items:center;justify-content:center;gap:6px;height:30px;padding:0 12px;border-radius:9px;border:1px solid var(--dsw-alias-border-l3,rgba(128,128,128,.30));background:transparent;color:inherit;font:inherit;font-size:12.5px;cursor:pointer;transition:background .15s,border-color .15s,transform .08s;white-space:nowrap}
175
+ .sc-btn:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(128,128,128,.10))}
176
+ .sc-btn:active{transform:scale(.97)}
177
+ .sc-btn:disabled{opacity:.42;cursor:default;transform:none}
178
+ .sc-btn-primary{border-color:transparent;background:var(--dsw-alias-brand-primary,#247bbf);color:var(--dsw-alias-label-on-color,#fff)}
179
+ .sc-btn-primary:hover{background:var(--dsw-alias-button-primary-hover,#1f6cab)}
180
+ .sc-btn-ghost{border-color:transparent}
181
+ .sc-btn-ghost:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(128,128,128,.10))}
182
+ .sc-icon-btn{width:30px;padding:0;font-size:15px}
183
+ .sc-btn-sm{height:26px;padding:0 9px;font-size:12px;border-radius:8px}
184
+
185
+ .sc-input,.sc-textarea{width:100%;padding:8px 12px;border-radius:10px;border:1px solid var(--dsw-alias-border-l3,rgba(128,128,128,.30));background:var(--dsw-alias-bg-base,transparent);color:inherit;font:inherit;font-size:13px;outline:none;transition:border-color .15s,box-shadow .15s}
186
+ .sc-input:focus,.sc-textarea:focus{border-color:var(--dsw-alias-brand-primary,#247bbf);box-shadow:0 0 0 3px rgba(36,123,191,.15)}
187
+ .sc-input::placeholder,.sc-textarea::placeholder{color:var(--dsw-alias-label-tertiary,#8b949e)}
188
+
189
+ .sc-avatar{flex:0 0 auto;display:inline-flex;align-items:center;justify-content:center;border-radius:50%;font-weight:600;color:#fff;user-select:none;overflow:hidden}
190
+ .sc-chip{display:inline-flex;align-items:center;gap:5px;height:22px;padding:0 8px;border-radius:99px;background:var(--dsw-alias-fill-l2,rgba(128,128,128,.10));color:var(--dsw-alias-label-secondary,#5b6570);font-size:11px;white-space:nowrap}
191
+ .sc-err{color:var(--dsw-alias-label-error,#d9534f);font-size:12px}
192
+
193
+ /* 登录 */
194
+ .sc-login{flex:1;min-height:0;display:flex;align-items:center;justify-content:center;padding:24px;overflow:auto}
195
+ .sc-login-card{width:100%;max-width:400px;background:var(--dsw-alias-bg-elevated,var(--dsw-alias-card-fill,#fff));border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.20));border-radius:20px;padding:26px 24px 20px;box-shadow:0 18px 50px rgba(0,0,0,.10)}
196
+ .sc-logo{width:44px;height:44px;border-radius:14px;display:flex;align-items:center;justify-content:center;font-size:22px;background:linear-gradient(135deg,rgba(36,123,191,.18),rgba(36,123,191,.06));margin-bottom:14px}
197
+ .sc-login-title{font-size:19px;font-weight:650;letter-spacing:.2px}
198
+ .sc-login-sub{color:var(--dsw-alias-label-secondary,#5b6570);font-size:12.5px;margin-top:4px;margin-bottom:18px}
199
+ .sc-tabs{display:flex;gap:3px;padding:3px;border-radius:11px;background:var(--dsw-alias-fill-l1,rgba(128,128,128,.08));margin-bottom:16px}
200
+ .sc-tab{flex:1;height:28px;border:0;border-radius:8px;background:transparent;color:var(--dsw-alias-label-secondary,#5b6570);font:inherit;font-size:12.5px;cursor:pointer;transition:background .15s,color .15s}
201
+ .sc-tab.on{background:var(--dsw-alias-bg-base,#fff);color:var(--dsw-alias-label-primary,#1f2328);box-shadow:0 1px 3px rgba(0,0,0,.10)}
202
+ .sc-field{display:flex;flex-direction:column;gap:6px;margin-bottom:12px}
203
+ .sc-field label{font-size:12px;color:var(--dsw-alias-label-secondary,#5b6570)}
204
+ .sc-login-actions{display:flex;align-items:center;gap:10px;margin-top:6px}
205
+ .sc-link{border:0;background:transparent;color:var(--dsw-alias-link,#247bbf);font:inherit;font-size:12px;cursor:pointer;padding:0}
206
+ .sc-link:hover{text-decoration:underline}
207
+ .sc-foot{color:var(--dsw-alias-label-tertiary,#8b949e);font-size:11.5px;margin-top:14px;line-height:1.6}
208
+
209
+ /* 聊天外壳 */
210
+ .sc-chat{flex:1;min-height:0;display:flex;flex-direction:column}
211
+ .sc-chat-head{display:flex;align-items:center;gap:10px;padding:10px 14px;border-bottom:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.20));flex:0 0 auto}
212
+ .sc-chat-name{font-size:13.5px;font-weight:600;line-height:1.2}
213
+ .sc-chat-sub{font-size:11.5px;color:var(--dsw-alias-label-tertiary,#8b949e);line-height:1.3}
214
+ .sc-chat-body{flex:1;min-height:0;display:flex}
215
+
216
+ .sc-side{width:236px;flex:0 0 236px;display:flex;flex-direction:column;border-right:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.20));background:var(--dsw-alias-fill-l1,rgba(128,128,128,.035))}
217
+ .sc-side-title{padding:12px 14px 6px;font-size:11.5px;font-weight:600;letter-spacing:.4px;text-transform:uppercase;color:var(--dsw-alias-label-tertiary,#8b949e)}
218
+ .sc-add{display:flex;gap:6px;padding:0 10px 8px}
219
+ .sc-add .sc-input{height:30px;padding:0 10px;font-size:12.5px}
220
+ .sc-friends{flex:1;min-height:0;overflow:auto;padding:0 8px 10px;display:flex;flex-direction:column;gap:2px}
221
+ .sc-friend{display:flex;align-items:center;gap:9px;padding:7px 8px;border-radius:10px;cursor:pointer;transition:background .15s;border:1px solid transparent}
222
+ .sc-friend:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(128,128,128,.10))}
223
+ .sc-friend.on{background:rgba(36,123,191,.10);border-color:rgba(36,123,191,.28)}
224
+ .sc-friend-main{flex:1;min-width:0}
225
+ .sc-friend-name{font-size:12.5px;font-weight:550;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
226
+ .sc-friend-last{font-size:11px;color:var(--dsw-alias-label-tertiary,#8b949e);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
227
+
228
+ .sc-main{flex:1;min-width:0;display:flex;flex-direction:column}
229
+ .sc-thread{flex:1;min-height:0;overflow:auto;padding:18px}
230
+ .sc-thread-inner{max-width:760px;margin:0 auto;display:flex;flex-direction:column;gap:10px}
231
+ .sc-msg{display:flex;flex-direction:column;align-items:flex-start;gap:3px;max-width:100%}
232
+ .sc-msg.mine{align-items:flex-end}
233
+ .sc-bubble{max-width:min(78%,560px);padding:8px 12px;border-radius:14px 14px 14px 4px;background:var(--dsw-alias-fill-l2,rgba(128,128,128,.12));white-space:pre-wrap;word-break:break-word}
234
+ .sc-msg.mine .sc-bubble{background:var(--dsw-alias-brand-primary,#247bbf);color:var(--dsw-alias-label-on-color,#fff);border-radius:14px 14px 4px 14px}
235
+ .sc-time{font-size:10.5px;color:var(--dsw-alias-label-quaternary,#a0a8b0);padding:0 4px}
236
+ .sc-msg-img{max-width:min(78%,420px);max-height:340px;border-radius:14px;display:block;border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.2))}
237
+ .sc-file{display:inline-flex;align-items:center;gap:10px;padding:8px 12px;border-radius:12px;border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.22));background:var(--dsw-alias-card-fill,rgba(128,128,128,.06));color:inherit;text-decoration:none;max-width:320px}
238
+ .sc-file:hover{background:var(--dsw-alias-card-fill-hover,rgba(128,128,128,.12))}
239
+ .sc-file-ico{font-size:24px;line-height:1}
240
+ .sc-file-main{display:flex;flex-direction:column;min-width:0}
241
+ .sc-file-name{font-size:12.5px;text-decoration:underline;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
242
+ .sc-file:hover{background:var(--dsw-alias-card-fill-hover,rgba(128,128,128,.12))}
243
+ .sc-file-name{font-size:12.5px}
244
+ .sc-file-size{font-size:11px;color:var(--dsw-alias-label-tertiary,#8b949e)}
245
+
246
+ .sc-empty{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:6px;color:var(--dsw-alias-label-tertiary,#8b949e);padding:40px 20px;text-align:center}
247
+ .sc-empty-ico{font-size:30px;opacity:.75;line-height:1}
248
+ .sc-empty-title{font-size:13px;color:var(--dsw-alias-label-secondary,#5b6570)}
249
+ .sc-empty-hint{font-size:11.5px;opacity:.8}
250
+
251
+ /* 输入区 */
252
+ .sc-composer{flex:0 0 auto;border-top:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.20));padding:10px 14px 12px}
253
+ .sc-composer-inner{max-width:760px;margin:0 auto;display:flex;flex-direction:column;gap:8px}
254
+ .sc-emoji{display:flex;flex-wrap:wrap;gap:2px;max-height:112px;overflow:auto;border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.20));border-radius:12px;padding:6px;background:var(--dsw-alias-bg-elevated,transparent)}
255
+ .sc-emoji button{border:0;background:transparent;font-size:17px;line-height:1;padding:4px 5px;border-radius:7px;cursor:pointer}
256
+ .sc-emoji button:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(128,128,128,.14))}
257
+ .sc-composer-box{display:flex;align-items:flex-end;gap:6px;border:1px solid var(--dsw-alias-border-l3,rgba(128,128,128,.30));border-radius:16px;padding:5px 6px;background:var(--dsw-alias-bg-base,transparent);transition:border-color .15s,box-shadow .15s}
258
+ .sc-composer-box:focus-within{border-color:var(--dsw-alias-brand-primary,#247bbf);box-shadow:0 0 0 3px rgba(36,123,191,.13)}
259
+ .sc-textarea{flex:1;min-height:34px;max-height:140px;padding:6px 6px 6px 8px;border:0;background:transparent;resize:none;outline:none;box-shadow:none}
260
+ .sc-textarea:focus{box-shadow:none;border:0}
261
+ .sc-send{height:30px;padding:0 14px;border-radius:10px}
262
+
263
+ /* 快照卡片 */
264
+ .sc-snap{max-width:min(88%,560px);border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.24));border-radius:14px;overflow:hidden;background:var(--dsw-alias-card-fill,rgba(128,128,128,.05))}
265
+ .sc-snap-head{display:flex;align-items:center;gap:8px;padding:9px 12px;border-bottom:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.20));background:var(--dsw-alias-fill-l1,rgba(128,128,128,.05))}
266
+ .sc-snap-badge{display:inline-flex;align-items:center;gap:4px;font-size:11px;font-weight:600;color:var(--dsw-alias-brand-primary,#247bbf)}
267
+ .sc-snap-title{font-size:11.5px;color:var(--dsw-alias-label-tertiary,#8b949e);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
268
+ .sc-snap-body{padding:10px 12px;display:flex;flex-direction:column;gap:8px}
269
+ .sc-blk{white-space:pre-wrap;word-break:break-word;font-size:12.5px}
270
+ .sc-blk-user{padding-left:9px;border-left:2px solid rgba(36,123,191,.55)}
271
+ .sc-blk-tool{padding:6px 9px;border-radius:8px;background:var(--dsw-alias-fill-l1,rgba(128,128,128,.08));font-family:ui-monospace,Consolas,monospace;font-size:11.5px;color:var(--dsw-alias-label-secondary,#5b6570)}
272
+ .sc-snap-skeleton{padding:14px 12px;font-size:12px;color:var(--dsw-alias-label-tertiary,#8b949e)}
273
+
274
+ /* 分享条 */
275
+ .sc-share{border-bottom:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.20));padding:8px 14px;flex:0 0 auto;background:var(--dsw-alias-fill-l1,rgba(128,128,128,.03))}
276
+ .sc-share-row{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
277
+ .sc-share-note{font-size:11.5px;color:var(--dsw-alias-label-tertiary,#8b949e)}
278
+ .sc-preview{margin-top:8px;border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.22));border-radius:12px;max-height:190px;overflow:auto;padding:8px 10px;display:flex;flex-direction:column;gap:5px;background:var(--dsw-alias-bg-base,transparent)}
279
+ .sc-preview-cap{font-size:11px;color:var(--dsw-alias-label-tertiary,#8b949e)}
280
+ .sc-preview-line{font-size:11px;line-height:1.5;font-family:ui-monospace,Consolas,monospace;opacity:.85;white-space:pre-wrap;word-break:break-word}
281
+ .sc-preview-line.tool{opacity:.55}
282
+ .sc-share-err{color:var(--dsw-alias-label-error,#d9534f);font-size:11.5px}
283
+
284
+ /* 设置页 */
285
+ .sc-set{display:flex;flex-direction:column;gap:14px;padding:4px 2px}
286
+ .sc-set-title{font-size:15px;font-weight:600}
287
+ .sc-set-desc{font-size:12px;color:var(--dsw-alias-label-secondary,#5b6570);line-height:1.65}
288
+ .sc-set-group{border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.22));border-radius:14px;padding:14px}
289
+ .sc-set-label{font-size:12px;color:var(--dsw-alias-label-secondary,#5b6570);margin-bottom:8px}
290
+ .sc-cards{display:flex;gap:8px;flex-wrap:wrap}
291
+ .sc-card-btn{flex:1 1 120px;min-width:112px;display:flex;flex-direction:column;align-items:center;gap:3px;padding:12px 10px;border-radius:12px;border:1px solid var(--dsw-alias-border-l3,rgba(128,128,128,.28));background:transparent;color:inherit;cursor:pointer;font:inherit;transition:background .15s,border-color .15s}
292
+ .sc-card-btn:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(128,128,128,.08))}
293
+ .sc-card-btn.on{border-color:var(--dsw-alias-brand-primary,#247bbf);background:rgba(36,123,191,.08)}
294
+ .sc-card-btn b{font-size:12.5px;font-weight:600}
295
+ .sc-card-btn span{font-size:11px;color:var(--dsw-alias-label-tertiary,#8b949e)}
296
+ .sc-inline{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
297
+ .sc-inline .sc-input{width:88px;height:30px;padding:0 10px}
298
+ .sc-ok{font-size:11.5px;color:var(--dsw-alias-state-success-primary,#2f8f65)}
299
+ .sc-hint{font-size:11px;color:var(--dsw-alias-label-tertiary,#8b949e)}
300
+
301
+ @media (max-width: 720px){
302
+ .sc-side{width:152px;flex-basis:152px}
303
+ .sc-side-title{padding:10px 10px 4px}
304
+ .sc-friend-last{display:none}
305
+ .sc-chat-sub{display:none}
306
+ .sc-thread{padding:12px}
307
+ .sc-thread-inner{gap:8px}
308
+ .sc-composer{padding:8px 10px 10px}
309
+ .sc-share{padding:6px 10px}
310
+ .sc-login{padding:12px}
311
+ .sc-login-card{padding:20px 16px 16px;border-radius:16px}
312
+ }
313
+ `
314
+
315
+ function ensureStyles() {
316
+ if (typeof document === 'undefined') return
317
+ if (document.getElementById(STYLE_ID)) return
318
+ const el = document.createElement('style')
319
+ el.id = STYLE_ID
320
+ el.textContent = CSS
321
+ document.head.appendChild(el)
322
+ }
323
+
324
+ const LINE = '1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.22))'
325
+
326
+ function hueOf(id) {
327
+ const s = String(id || '?')
328
+ let x = 0
329
+ for (let i = 0; i < s.length; i++) x = (x * 31 + s.charCodeAt(i)) % 360
330
+ return x
331
+ }
332
+
333
+ function avatar(name, id, size) {
334
+ const sz = size || 30
335
+ const hue = hueOf(id || name)
336
+ return h(
337
+ 'span',
338
+ {
339
+ className: 'sc-avatar',
340
+ style: {
341
+ width: sz + 'px',
342
+ height: sz + 'px',
343
+ fontSize: Math.max(11, Math.round(sz * 0.42)) + 'px',
344
+ background:
345
+ 'linear-gradient(135deg,hsl(' +
346
+ hue +
347
+ ' 58% 52%),hsl(' +
348
+ ((hue + 34) % 360) +
349
+ ' 58% 44%))',
350
+ },
351
+ },
352
+ String(name || id || '?').trim().charAt(0).toUpperCase(),
353
+ )
354
+ }
355
+
356
+ function clockText(at) {
357
+ try {
358
+ return new Date(at).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
359
+ } catch (e) {
360
+ return ''
361
+ }
362
+ }
363
+
364
+ function emptyState(ico, title, hint) {
365
+ return h(
366
+ 'div',
367
+ { className: 'sc-empty' },
368
+ h('div', { className: 'sc-empty-ico' }, ico),
369
+ h('div', { className: 'sc-empty-title' }, title),
370
+ hint ? h('div', { className: 'sc-empty-hint' }, hint) : null,
371
+ )
372
+ }
373
+
374
+ // ───────────────────────── 快照 ─────────────────────────
375
+
376
+ /** 对方发来的对话快照:只读卡片,块按「用户 / 工具 / 回复」三种样式渲染 */
377
+ function SnapshotCard(props) {
378
+ const { snapshotId, auth } = props
379
+ const [snap, setSnap] = useState(null)
380
+ const [err, setErr] = useState('')
381
+
382
+ useEffect(() => {
383
+ let alive = true
384
+ api(auth.server, '/api/snapshots/' + encodeURIComponent(snapshotId), { token: auth.token })
385
+ .then((data) => {
386
+ if (alive) setSnap(data.snapshot)
387
+ })
388
+ .catch((e) => {
389
+ if (alive) setErr(friendly(e))
390
+ })
391
+ return () => {
392
+ alive = false
393
+ }
394
+ }, [snapshotId, auth.server, auth.token])
395
+
396
+ const head = (title) =>
397
+ h(
398
+ 'div',
399
+ { className: 'sc-snap-head' },
400
+ h('span', { className: 'sc-snap-badge' }, '🐟 对话快照'),
401
+ h('span', { className: 'sc-snap-title' }, title || ''),
402
+ )
403
+
404
+ if (err) {
405
+ return h(
406
+ 'div',
407
+ { className: 'sc-snap' },
408
+ head('打不开'),
409
+ h('div', { className: 'sc-snap-body' }, h('div', { className: 'sc-err' }, err)),
410
+ )
411
+ }
412
+ if (!snap) {
413
+ return h('div', { className: 'sc-snap' }, head(''), h('div', { className: 'sc-snap-skeleton' }, '正在加载快照…'))
414
+ }
415
+
416
+ const blocks = Array.isArray(snap.blocks) ? snap.blocks : []
417
+ return h(
418
+ 'div',
419
+ { className: 'sc-snap' },
420
+ head(snap.title || ''),
421
+ h(
422
+ 'div',
423
+ { className: 'sc-snap-body' },
424
+ blocks.map((b, i) =>
425
+ h(
426
+ 'div',
427
+ { key: i, className: 'sc-blk sc-blk-' + (b.t || 'assistant') },
428
+ b.t === 'tool'
429
+ ? h('span', null, h('b', null, b.name || '工具'), ' ' + String(b.text || ''))
430
+ : String(b.text || ''),
431
+ ),
432
+ ),
433
+ ),
434
+ )
435
+ }
436
+
437
+ // ───────────────────────── 登录 ─────────────────────────
438
+
439
+ const MODE_HINTS = {
440
+ login: '账号在服务器上,换端口、换电脑都只认密码。',
441
+ register: '需要邀请码。密码至少 6 位,设了以后就不怕掉登录。',
442
+ setpw: '给已有账号补一个密码,用邀请码授权。',
443
+ token: '粘贴之前保存的 token,临时登录用。',
444
+ }
445
+
446
+ function LoginPanel(props) {
447
+ const [server, setServer] = useState(() => {
448
+ try {
449
+ return window.localStorage.getItem(K_SERVER) || DEFAULT_SERVER
450
+ } catch (e) {
451
+ return DEFAULT_SERVER
452
+ }
453
+ })
454
+ const [mode, setMode] = useState('login')
455
+ const [id, setId] = useState('')
456
+ const [invite, setInvite] = useState('')
457
+ const [password, setPassword] = useState('')
458
+ const [token, setToken] = useState('')
459
+ const [busy, setBusy] = useState(false)
460
+ const [err, setErr] = useState('')
461
+
462
+ const submit = async () => {
463
+ if (busy) return
464
+ setErr('')
465
+ setBusy(true)
466
+ try {
467
+ window.localStorage.setItem(K_SERVER, server)
468
+ let auth
469
+ if (mode === 'login') {
470
+ const r = await api(server, '/api/login', { method: 'POST', body: { id, password } })
471
+ auth = { id: r.id, displayName: r.displayName, token: r.token, server }
472
+ } else if (mode === 'register') {
473
+ const r = await api(server, '/api/register', {
474
+ method: 'POST',
475
+ body: { invite, id, displayName: id, password },
476
+ })
477
+ auth = { id: r.id, displayName: r.displayName, token: r.token, server }
478
+ } else if (mode === 'setpw') {
479
+ const r = await api(server, '/api/password', {
480
+ method: 'POST',
481
+ body: { invite, id, password },
482
+ })
483
+ auth = { id: r.id, displayName: r.displayName, token: r.token, server }
484
+ } else {
485
+ const me = await api(server, '/api/me', { token })
486
+ auth = { id: me.id, displayName: me.displayName, token, server }
487
+ }
488
+ writeJson(K_AUTH, auth)
489
+ props.onDone(auth)
490
+ } catch (e) {
491
+ setErr(friendly(e))
492
+ } finally {
493
+ setBusy(false)
494
+ }
495
+ }
496
+
497
+ const tab = (value, label) =>
498
+ h(
499
+ 'button',
500
+ {
501
+ className: 'sc-tab' + (mode === value ? ' on' : ''),
502
+ onClick: () => {
503
+ setMode(value)
504
+ setErr('')
505
+ },
506
+ },
507
+ label,
508
+ )
509
+
510
+ const field = (label, placeholder, value, onChange, extra) =>
511
+ h(
512
+ 'div',
513
+ { className: 'sc-field' },
514
+ h('label', null, label),
515
+ h('input', {
516
+ className: 'sc-input',
517
+ placeholder,
518
+ value,
519
+ onChange: (e) => onChange(e.target.value),
520
+ ...(extra || {}),
521
+ }),
522
+ )
523
+
524
+ const buttonLabel =
525
+ mode === 'login'
526
+ ? '登录'
527
+ : mode === 'register'
528
+ ? '注册并进入'
529
+ : mode === 'setpw'
530
+ ? '设置密码并登录'
531
+ : '用 token 登录'
532
+
533
+ return h(
534
+ 'div',
535
+ { className: 'sc-login' },
536
+ h(
537
+ 'div',
538
+ { className: 'sc-login-card' },
539
+ h('div', { className: 'sc-logo' }, '🐟'),
540
+ h('div', { className: 'sc-login-title' }, '社交'),
541
+ h('div', { className: 'sc-login-sub' }, MODE_HINTS[mode]),
542
+
543
+ h(
544
+ 'div',
545
+ { className: 'sc-tabs' },
546
+ tab('login', '登录'),
547
+ tab('register', '注册'),
548
+ tab('token', 'Token'),
549
+ ),
550
+
551
+ field('服务器', 'https://…', server, setServer),
552
+ mode === 'register' || mode === 'setpw'
553
+ ? field('邀请码', '找发插件的人要', invite, setInvite)
554
+ : null,
555
+ mode === 'token' ? null : field('账号名', '2–20 位,中文可以', id, setId),
556
+ mode === 'token'
557
+ ? h(
558
+ 'div',
559
+ { className: 'sc-field' },
560
+ h('label', null, 'Token'),
561
+ h('textarea', {
562
+ className: 'sc-textarea',
563
+ style: { minHeight: '76px' },
564
+ placeholder: '粘贴 token',
565
+ value: token,
566
+ onChange: (e) => setToken(e.target.value),
567
+ }),
568
+ )
569
+ : field(mode === 'setpw' ? '新密码' : '密码', mode === 'setpw' ? '至少 6 位' : '密码', password, setPassword, {
570
+ type: 'password',
571
+ onKeyDown: (e) => {
572
+ if (e.key === 'Enter') submit()
573
+ },
574
+ }),
575
+
576
+ err ? h('div', { className: 'sc-err', style: { marginBottom: '10px' } }, err) : null,
577
+
578
+ h(
579
+ 'div',
580
+ { className: 'sc-login-actions' },
581
+ h(
582
+ 'button',
583
+ {
584
+ className: 'sc-btn sc-btn-primary',
585
+ style: { height: '34px', padding: '0 18px', flex: 1 },
586
+ onClick: submit,
587
+ disabled: busy,
588
+ },
589
+ busy ? '请稍候…' : buttonLabel,
590
+ ),
591
+ mode === 'login'
592
+ ? h(
593
+ 'button',
594
+ {
595
+ className: 'sc-link',
596
+ onClick: () => {
597
+ setMode('setpw')
598
+ setErr('')
599
+ },
600
+ },
601
+ '没设过密码?',
602
+ )
603
+ : null,
604
+ ),
605
+
606
+ h('div', { className: 'sc-foot' }, '消息和快照都留在你自己的服务器上,不经过模型,不消耗 token。'),
607
+ ),
608
+ )
609
+ }
610
+
611
+ // ───────────────────────── 聊天 ─────────────────────────
612
+
613
+ function ChatPanel(props) {
614
+ const auth = props.auth
615
+ const [friends, setFriends] = useState([])
616
+ const [active, setActive] = useState(null)
617
+ const [messages, setMessages] = useState([])
618
+ const [draft, setDraft] = useState('')
619
+ const [newFriend, setNewFriend] = useState('')
620
+ const [err, setErr] = useState('')
621
+ const [sending, setSending] = useState(false)
622
+ const [uploading, setUploading] = useState(false)
623
+ const [emojiOpen, setEmojiOpen] = useState(false)
624
+
625
+ const cursorRef = useRef(0)
626
+ const listRef = useRef(null)
627
+ const activeRef = useRef(null)
628
+ const friendsKeyRef = useRef('')
629
+ const fileRef = useRef(null)
630
+
631
+ useEffect(() => {
632
+ activeRef.current = active
633
+ }, [active])
634
+
635
+ const loadFriends = useCallback(async () => {
636
+ try {
637
+ const r = await api(auth.server, '/api/friends', { token: auth.token })
638
+ setFriends(r.friends || [])
639
+ return r.friends || []
640
+ } catch (e) {
641
+ setErr(friendly(e))
642
+ return []
643
+ }
644
+ }, [auth.server, auth.token])
645
+
646
+ useEffect(() => {
647
+ let alive = true
648
+ loadFriends().then((list) => {
649
+ if (alive && list.length && !active) setActive(list[0].id)
650
+ })
651
+ return () => {
652
+ alive = false
653
+ }
654
+ // eslint-disable-next-line react-hooks/exhaustive-deps
655
+ }, [loadFriends])
656
+
657
+ /** 上次之后的新消息,拉一次并追加 */
658
+ const pull = async () => {
659
+ const r = await api(auth.server, '/api/messages?since=' + cursorRef.current, {
660
+ token: auth.token,
661
+ })
662
+ if (r.messages && r.messages.length) {
663
+ cursorRef.current = r.cursor
664
+ setMessages((prev) => prev.concat(r.messages))
665
+ }
666
+ }
667
+
668
+ // 5 秒轮询:消息 + 好友列表(对方加了你这边才看得见)
669
+ useEffect(() => {
670
+ let alive = true
671
+ const tick = async () => {
672
+ try {
673
+ const r = await api(auth.server, '/api/messages?since=' + cursorRef.current, {
674
+ token: auth.token,
675
+ })
676
+ if (!alive) return
677
+ if (r.messages && r.messages.length) {
678
+ cursorRef.current = r.cursor
679
+ setMessages((prev) => prev.concat(r.messages))
680
+ }
681
+ } catch (e) {
682
+ /* 消息拉取失败不打扰用户,下次再来 */
683
+ }
684
+ try {
685
+ const f = await api(auth.server, '/api/friends', { token: auth.token })
686
+ if (!alive) return
687
+ const list = f.friends || []
688
+ const key = list.map((x) => x.id + ':' + (x.displayName || '')).join('|')
689
+ if (key !== friendsKeyRef.current) {
690
+ friendsKeyRef.current = key
691
+ setFriends(list)
692
+ if (!activeRef.current && list.length) setActive(list[0].id)
693
+ }
694
+ } catch (e) {
695
+ /* 同上 */
696
+ }
697
+ }
698
+ tick()
699
+ const timer = window.setInterval(tick, POLL_MS)
700
+ return () => {
701
+ alive = false
702
+ window.clearInterval(timer)
703
+ }
704
+ }, [auth.server, auth.token])
705
+
706
+ // 新消息贴底
707
+ useEffect(() => {
708
+ const el = listRef.current
709
+ if (el) el.scrollTop = el.scrollHeight
710
+ }, [messages, active])
711
+
712
+ const addFriend = async () => {
713
+ const target = newFriend.trim()
714
+ if (!target) return
715
+ setErr('')
716
+ try {
717
+ await api(auth.server, '/api/friends', {
718
+ method: 'POST',
719
+ token: auth.token,
720
+ body: { id: target },
721
+ })
722
+ setNewFriend('')
723
+ const list = await loadFriends()
724
+ setActive(list.find((f) => f.id === target) ? target : active)
725
+ } catch (e) {
726
+ setErr(friendly(e))
727
+ }
728
+ }
729
+
730
+ const send = async () => {
731
+ const text = draft.trim()
732
+ if (!text || !active || sending) return
733
+ setSending(true)
734
+ setErr('')
735
+ try {
736
+ await api(auth.server, '/api/messages', {
737
+ method: 'POST',
738
+ token: auth.token,
739
+ body: { to: active, text },
740
+ })
741
+ setDraft('')
742
+ await pull()
743
+ } catch (e) {
744
+ setErr(friendly(e))
745
+ } finally {
746
+ setSending(false)
747
+ }
748
+ }
749
+
750
+ /** 选中的文件:先上传,再发一条 image / file 消息 */
751
+ const uploadAndSend = async (file) => {
752
+ if (!active || !file) return
753
+ setUploading(true)
754
+ setErr('')
755
+ try {
756
+ const buf = await file.arrayBuffer()
757
+ const res = await fetch(auth.server + '/api/upload', {
758
+ method: 'POST',
759
+ headers: {
760
+ authorization: 'Bearer ' + auth.token,
761
+ 'content-type': file.type || 'application/octet-stream',
762
+ 'x-filename': encodeURIComponent(file.name || ''),
763
+ },
764
+ body: buf,
765
+ })
766
+ let up = null
767
+ try {
768
+ up = await res.json()
769
+ } catch (e) {
770
+ /* 非 JSON */
771
+ }
772
+ if (!res.ok) {
773
+ setErr(up && up.error === 'too-large' ? '文件太大(服务器上限 50 MB)' : '上传失败')
774
+ return
775
+ }
776
+ const isImage = String(file.type || '').startsWith('image/')
777
+ await api(auth.server, '/api/messages', {
778
+ method: 'POST',
779
+ token: auth.token,
780
+ body: isImage ? { to: active, image: { uploadId: up.id } } : { to: active, file: { uploadId: up.id } },
781
+ })
782
+ await pull()
783
+ } catch (e) {
784
+ setErr(friendly(e))
785
+ } finally {
786
+ setUploading(false)
787
+ }
788
+ }
789
+
790
+ const keyDown = (e) => {
791
+ if (e.key === 'Enter' && !e.shiftKey) {
792
+ e.preventDefault()
793
+ send()
794
+ }
795
+ }
796
+
797
+ /* 好友列表里的「最后一条」摘要 */
798
+ const lastOf = (fid) => {
799
+ for (let i = messages.length - 1; i >= 0; i--) {
800
+ const m = messages[i]
801
+ if (m.from === fid || m.to === fid) return m
802
+ }
803
+ return null
804
+ }
805
+ const previewOf = (m) => {
806
+ if (!m) return ''
807
+ const b = m.body || {}
808
+ if (b.kind === 'snapshot') return '🐟 对话快照'
809
+ if (b.kind === 'image') return '🖼 图片'
810
+ if (b.kind === 'file') return '📎 ' + (b.name || '文件')
811
+ return String(b.text || '')
812
+ }
813
+
814
+ const thread = messages.filter((m) => m.from === active || m.to === active)
815
+
816
+ const renderMessage = (m) => {
817
+ const b = m.body || {}
818
+ const kind = b.kind || 'text'
819
+ const mine = m.from === auth.id
820
+ let content
821
+ if (kind === 'snapshot') {
822
+ content = h(SnapshotCard, { snapshotId: b.snapshotId, auth })
823
+ } else if (kind === 'image') {
824
+ content = h('img', {
825
+ className: 'sc-msg-img',
826
+ src: auth.server + b.url,
827
+ alt: b.caption || '图片',
828
+ })
829
+ } else if (kind === 'file') {
830
+ const t = String(b.type || '')
831
+ const src = auth.server + b.url
832
+ if (t.startsWith('image/')) {
833
+ content = h('img', { className: 'sc-msg-img', src, alt: b.name || '图片' })
834
+ } else if (t.startsWith('video/')) {
835
+ content = h('video', { src, controls: true, style: MEDIA_STYLE })
836
+ } else if (t.startsWith('audio/')) {
837
+ content = h('audio', { src, controls: true, style: { maxWidth: '100%' } })
838
+ } else {
839
+ content = h(
840
+ 'a',
841
+ {
842
+ className: 'sc-file',
843
+ href: src,
844
+ target: '_blank',
845
+ rel: 'noreferrer',
846
+ download: b.name || undefined,
847
+ },
848
+ h('span', { className: 'sc-file-ico' }, fileIcon(t, b.name)),
849
+ h(
850
+ 'span',
851
+ { className: 'sc-file-main' },
852
+ h('span', { className: 'sc-file-name' }, b.name || '附件'),
853
+ h('span', { className: 'sc-file-size' }, (b.type || '未知类型') + ' · ' + kbText(b.size)),
854
+ ),
855
+ )
856
+ }
857
+ } else {
858
+ content = h('div', { className: 'sc-bubble' }, String(b.text || ''))
859
+ }
860
+ return h(
861
+ 'div',
862
+ { key: m.seq, className: 'sc-msg' + (mine ? ' mine' : '') },
863
+ content,
864
+ h('div', { className: 'sc-time' }, clockText(m.at)),
865
+ )
866
+ }
867
+
868
+ return h(
869
+ 'div',
870
+ { className: 'sc-chat' },
871
+ /* 顶栏 */
872
+ h(
873
+ 'div',
874
+ { className: 'sc-chat-head' },
875
+ avatar(auth.displayName || auth.id, auth.id, 30),
876
+ h(
877
+ 'div',
878
+ { style: { minWidth: 0 } },
879
+ h('div', { className: 'sc-chat-name' }, '@' + (auth.displayName || auth.id)),
880
+ h('div', { className: 'sc-chat-sub' }, auth.server.replace(/^https?:\/\//, '')),
881
+ ),
882
+ h('span', { className: 'sc-grow' }),
883
+ err
884
+ ? h(
885
+ 'span',
886
+ {
887
+ className: 'sc-err',
888
+ style: { maxWidth: '240px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
889
+ },
890
+ err,
891
+ )
892
+ : null,
893
+ h(
894
+ 'button',
895
+ {
896
+ className: 'sc-btn',
897
+ onClick: () => openMeeting({ auth, onToast: (m) => setErr(m) }),
898
+ title: '音视频会议(点对点,无时长限制)',
899
+ },
900
+ '📹 开会',
901
+ ),
902
+ h('button', { className: 'sc-btn', onClick: props.onOpenGame, title: '玩一把鱼塘摸鱼' }, '🎮 摸鱼'),
903
+ h('button', { className: 'sc-btn sc-btn-ghost', onClick: props.onLogout }, '退出'),
904
+ ),
905
+ /* 主体 */
906
+ h(
907
+ 'div',
908
+ { className: 'sc-chat-body' },
909
+ h(
910
+ 'div',
911
+ { className: 'sc-side' },
912
+ h('div', { className: 'sc-side-title' }, '好友'),
913
+ h(
914
+ 'div',
915
+ { className: 'sc-add' },
916
+ h('input', {
917
+ className: 'sc-input',
918
+ placeholder: '对方 ID',
919
+ value: newFriend,
920
+ onChange: (e) => setNewFriend(e.target.value),
921
+ onKeyDown: (e) => {
922
+ if (e.key === 'Enter') addFriend()
923
+ },
924
+ }),
925
+ h('button', { className: 'sc-btn sc-btn-sm', onClick: addFriend }, '添加'),
926
+ ),
927
+ h(
928
+ 'div',
929
+ { className: 'sc-friends' },
930
+ friends.length === 0
931
+ ? emptyState('👥', '还没有好友', '在上面输入对方 ID 加一个')
932
+ : friends.map((f) =>
933
+ h(
934
+ 'div',
935
+ {
936
+ key: f.id,
937
+ className: 'sc-friend' + (active === f.id ? ' on' : ''),
938
+ onClick: () => setActive(f.id),
939
+ title: f.id,
940
+ },
941
+ avatar(f.displayName || f.id, f.id, 28),
942
+ h(
943
+ 'div',
944
+ { className: 'sc-friend-main' },
945
+ h('div', { className: 'sc-friend-name' }, f.displayName || f.id),
946
+ h('div', { className: 'sc-friend-last' }, previewOf(lastOf(f.id)) || '还没有消息'),
947
+ ),
948
+ ),
949
+ ),
950
+ ),
951
+ ),
952
+ h(
953
+ 'div',
954
+ { className: 'sc-main' },
955
+ h(
956
+ 'div',
957
+ { className: 'sc-thread', ref: listRef },
958
+ h(
959
+ 'div',
960
+ { className: 'sc-thread-inner' },
961
+ !active
962
+ ? emptyState('💬', '选一个好友开始聊天', '左边是好友列表,点一下就进来')
963
+ : thread.length === 0
964
+ ? emptyState('🐟', '还没有消息', '说点什么,或者在上面的「分享这一轮」把对话发过去')
965
+ : thread.map(renderMessage),
966
+ ),
967
+ ),
968
+ h(
969
+ 'div',
970
+ { className: 'sc-composer' },
971
+ h(
972
+ 'div',
973
+ { className: 'sc-composer-inner' },
974
+ emojiOpen
975
+ ? h(
976
+ 'div',
977
+ { className: 'sc-emoji' },
978
+ EMOJIS.map((em) =>
979
+ h(
980
+ 'button',
981
+ {
982
+ key: em,
983
+ onClick: () => setDraft((d) => d + em),
984
+ },
985
+ em,
986
+ ),
987
+ ),
988
+ )
989
+ : null,
990
+ h(
991
+ 'div',
992
+ { className: 'sc-composer-box' },
993
+ h(
994
+ 'button',
995
+ {
996
+ className: 'sc-btn sc-btn-ghost sc-icon-btn',
997
+ title: '表情',
998
+ onClick: () => setEmojiOpen((v) => !v),
999
+ },
1000
+ '😀',
1001
+ ),
1002
+ h(
1003
+ 'button',
1004
+ {
1005
+ className: 'sc-btn sc-btn-ghost sc-icon-btn',
1006
+ title: '发送图片或文件(任意类型,≤50 MB)',
1007
+ disabled: !active || uploading,
1008
+ onClick: () => fileRef.current && fileRef.current.click(),
1009
+ },
1010
+ uploading ? '…' : '📎',
1011
+ ),
1012
+ h('input', {
1013
+ ref: fileRef,
1014
+ type: 'file',
1015
+ style: { display: 'none' },
1016
+ onChange: (e) => {
1017
+ const f = e.target.files && e.target.files[0]
1018
+ if (f) uploadAndSend(f)
1019
+ e.target.value = ''
1020
+ },
1021
+ }),
1022
+ h('textarea', {
1023
+ className: 'sc-textarea',
1024
+ placeholder: active ? 'Enter 发送,Shift+Enter 换行' : '先选一个好友',
1025
+ value: draft,
1026
+ disabled: !active,
1027
+ onChange: (e) => setDraft(e.target.value),
1028
+ onKeyDown: keyDown,
1029
+ }),
1030
+ h(
1031
+ 'button',
1032
+ {
1033
+ className: 'sc-btn sc-btn-primary sc-send',
1034
+ disabled: !active || sending || !draft.trim(),
1035
+ onClick: send,
1036
+ },
1037
+ sending ? '发送中' : '发送',
1038
+ ),
1039
+ ),
1040
+ ),
1041
+ ),
1042
+ ),
1043
+ ),
1044
+ )
1045
+ }
1046
+
1047
+ // ───────────────────────── 小游戏 ─────────────────────────
1048
+
1049
+ /** 小游戏窗口尺寸:本机显示偏好,存浏览器本地,不进 profile 配置 */
1050
+ const K_GAME_SIZE = 'dsh-share-chat.game.size'
1051
+ const GAME_MIN = { w: 300, h: 420 }
1052
+ const GAME_DEFAULT = { w: 390, h: 760 }
1053
+ const GAME_PRESETS = [
1054
+ { label: '手机竖屏', w: 390, h: 760 },
1055
+ { label: '小窗', w: 340, h: 600 },
1056
+ { label: '大窗', w: 480, h: 900 },
1057
+ ]
1058
+ const GAME_SIZE_EVENT = 'dsh-share-chat:game-size'
1059
+
1060
+ function clampGameSize(size) {
1061
+ const vw = typeof window === 'undefined' ? 1280 : window.innerWidth
1062
+ const vh = typeof window === 'undefined' ? 900 : window.innerHeight
1063
+ const w = Number(size && size.w) || GAME_DEFAULT.w
1064
+ const h = Number(size && size.h) || GAME_DEFAULT.h
1065
+ return {
1066
+ w: Math.round(Math.min(Math.max(w, GAME_MIN.w), Math.max(GAME_MIN.w, vw - 32))),
1067
+ h: Math.round(Math.min(Math.max(h, GAME_MIN.h), Math.max(GAME_MIN.h, vh - 96))),
1068
+ }
1069
+ }
1070
+ function readGameSize() {
1071
+ return clampGameSize(readJson(K_GAME_SIZE) || GAME_DEFAULT)
1072
+ }
1073
+ function writeGameSize(size) {
1074
+ const next = clampGameSize(size)
1075
+ writeJson(K_GAME_SIZE, next)
1076
+ try {
1077
+ window.dispatchEvent(new CustomEvent(GAME_SIZE_EVENT, { detail: next }))
1078
+ } catch (e) {
1079
+ /* 老浏览器没有 CustomEvent 构造器,忽略 */
1080
+ }
1081
+ return next
1082
+ }
1083
+
1084
+ /**
1085
+ * 小游戏窗口:用原生 DOM 挂到 document.body 上(不进 React 树、不在插件的容器里),
1086
+ * 这样它不会被 DSH 面板的 stacking context / overflow 裁切,也不会被别的层抢走点击。
1087
+ * 可拖标题栏移动、拉右下角改大小;默认尺寸来自 设置 → 社交小游戏。
1088
+ */
1089
+ function GameWindow(props) {
1090
+ const onClose = props.onClose
1091
+
1092
+ useEffect(() => {
1093
+ let size = readGameSize()
1094
+ const vw = () => window.innerWidth
1095
+ const vh = () => window.innerHeight
1096
+ const place = (s) => ({ x: Math.max(8, vw() - s.w - 16), y: Math.max(8, vh() - s.h - 16) })
1097
+ let pos = place(size)
1098
+ let scene = ''
1099
+ let tap = null
1100
+
1101
+ const root = document.createElement('div')
1102
+ root.style.cssText = [
1103
+ 'position:fixed',
1104
+ 'display:flex',
1105
+ 'flex-direction:column',
1106
+ 'background:#0b1d24',
1107
+ 'border:1px solid rgba(128,128,128,.45)',
1108
+ 'border-radius:12px',
1109
+ 'overflow:hidden',
1110
+ 'box-shadow:0 18px 48px rgba(0,0,0,.45)',
1111
+ 'z-index:2147483647',
1112
+ ].join(';')
1113
+
1114
+ const head = document.createElement('div')
1115
+ head.title = '拖动窗口'
1116
+ head.style.cssText = [
1117
+ 'display:flex',
1118
+ 'align-items:center',
1119
+ 'gap:8px',
1120
+ 'padding:7px 10px',
1121
+ 'border-bottom:1px solid rgba(128,128,128,.28)',
1122
+ 'background:rgba(0,0,0,.25)',
1123
+ 'color:#eaf3f6',
1124
+ 'flex:0 0 auto',
1125
+ 'cursor:move',
1126
+ 'user-select:none',
1127
+ 'font:12px/1.4 -apple-system,Segoe UI,Microsoft YaHei,sans-serif',
1128
+ ].join(';')
1129
+
1130
+ const title = document.createElement('strong')
1131
+ title.textContent = '鱼塘摸鱼'
1132
+ title.style.cssText = 'font-size:12.5px'
1133
+
1134
+ const meta = document.createElement('span')
1135
+ meta.style.cssText = 'opacity:.55;font-size:11px'
1136
+
1137
+ const tapInfo = document.createElement('span')
1138
+ tapInfo.title = '最近一次点击:页面坐标 → 游戏命中区域(空表示没命中)'
1139
+ tapInfo.style.cssText = 'opacity:.7;font-size:10.5px;font-family:ui-monospace,Consolas,monospace'
1140
+
1141
+ const spacer = document.createElement('span')
1142
+ spacer.style.cssText = 'flex:1'
1143
+
1144
+ const openLink = document.createElement('a')
1145
+ openLink.href = GAME_URL
1146
+ openLink.target = '_blank'
1147
+ openLink.rel = 'noreferrer'
1148
+ openLink.textContent = '新窗口'
1149
+ openLink.style.cssText = 'color:inherit;font-size:11px;opacity:.7'
1150
+
1151
+ const closeBtn = document.createElement('button')
1152
+ closeBtn.textContent = '关闭'
1153
+ closeBtn.style.cssText =
1154
+ 'padding:3px 9px;font-size:11px;border-radius:8px;border:1px solid rgba(255,255,255,.3);background:transparent;color:#eaf3f6;cursor:pointer'
1155
+
1156
+ head.append(title, meta, tapInfo, spacer, openLink, closeBtn)
1157
+
1158
+ const bodyBox = document.createElement('div')
1159
+ bodyBox.style.cssText = 'position:relative;flex:1;min-height:0'
1160
+
1161
+ const frame = document.createElement('iframe')
1162
+ frame.src = GAME_URL
1163
+ frame.title = '鱼塘摸鱼'
1164
+ frame.setAttribute('allow', 'autoplay; clipboard-write')
1165
+ frame.style.cssText =
1166
+ 'position:absolute;inset:0;width:100%;height:100%;border:0;background:#0b1d24'
1167
+ bodyBox.appendChild(frame)
1168
+
1169
+ const grip = document.createElement('div')
1170
+ grip.title = '拖动调整窗口大小(也可以在 设置 → 社交小游戏 里改默认值)'
1171
+ grip.style.cssText =
1172
+ 'position:absolute;right:0;bottom:0;width:18px;height:18px;cursor:nwse-resize;background:linear-gradient(135deg,transparent 50%,rgba(255,255,255,.35) 50%)'
1173
+
1174
+ root.append(head, bodyBox, grip)
1175
+ document.body.appendChild(root)
1176
+
1177
+ const paint = () => {
1178
+ root.style.left = pos.x + 'px'
1179
+ root.style.top = pos.y + 'px'
1180
+ root.style.width = size.w + 'px'
1181
+ root.style.height = size.h + 'px'
1182
+ meta.textContent = (scene ? scene + ' · ' : '') + size.w + '×' + size.h
1183
+ tapInfo.textContent = tap ? tap.x + ',' + tap.y + ' → ' + (tap.hit || '空') : ''
1184
+ }
1185
+ paint()
1186
+
1187
+ closeBtn.addEventListener('click', () => onClose())
1188
+
1189
+ /* 拖标题栏移动 */
1190
+ head.addEventListener('pointerdown', (e) => {
1191
+ if (e.target && e.target.closest && e.target.closest('button,a')) return
1192
+ if (e.button !== 0) return
1193
+ e.preventDefault()
1194
+ const start = { px: e.clientX, py: e.clientY, x: pos.x, y: pos.y }
1195
+ const move = (ev) => {
1196
+ pos = {
1197
+ x: Math.min(Math.max(4, start.x + ev.clientX - start.px), Math.max(4, vw() - size.w - 4)),
1198
+ y: Math.min(Math.max(4, start.y + ev.clientY - start.py), Math.max(4, vh() - size.h - 4)),
1199
+ }
1200
+ paint()
1201
+ }
1202
+ const up = () => {
1203
+ window.removeEventListener('pointermove', move)
1204
+ window.removeEventListener('pointerup', up)
1205
+ }
1206
+ window.addEventListener('pointermove', move)
1207
+ window.addEventListener('pointerup', up)
1208
+ })
1209
+
1210
+ /* 拉右下角改大小 */
1211
+ grip.addEventListener('pointerdown', (e) => {
1212
+ if (e.button !== 0) return
1213
+ e.preventDefault()
1214
+ e.stopPropagation()
1215
+ const start = { px: e.clientX, py: e.clientY, w: size.w, h: size.h }
1216
+ const move = (ev) => {
1217
+ size = clampGameSize({
1218
+ w: start.w + ev.clientX - start.px,
1219
+ h: start.h + ev.clientY - start.py,
1220
+ })
1221
+ paint()
1222
+ }
1223
+ const up = () => {
1224
+ window.removeEventListener('pointermove', move)
1225
+ window.removeEventListener('pointerup', up)
1226
+ writeGameSize(size)
1227
+ }
1228
+ window.addEventListener('pointermove', move)
1229
+ window.addEventListener('pointerup', up)
1230
+ })
1231
+
1232
+ /* 游戏回传的场景 / 点击诊断 */
1233
+ const onMessage = (e) => {
1234
+ const d = e && e.data
1235
+ if (!d || d.source !== 'fishgame') return
1236
+ if (d.type === 'scene') {
1237
+ scene = d.scene || ''
1238
+ paint()
1239
+ } else if (d.type === 'tap') {
1240
+ tap = d
1241
+ paint()
1242
+ }
1243
+ }
1244
+
1245
+ /* 设置页改尺寸 / 页面窗口变化 */
1246
+ const onSizeEvent = (e) => {
1247
+ size = clampGameSize((e && e.detail) || readGameSize())
1248
+ pos = place(size)
1249
+ paint()
1250
+ }
1251
+ const onWinResize = () => {
1252
+ size = clampGameSize(size)
1253
+ pos = {
1254
+ x: Math.min(pos.x, Math.max(4, vw() - size.w - 4)),
1255
+ y: Math.min(pos.y, Math.max(4, vh() - size.h - 4)),
1256
+ }
1257
+ paint()
1258
+ }
1259
+ const onKey = (e) => {
1260
+ if (e.key === 'Escape') onClose()
1261
+ }
1262
+
1263
+ window.addEventListener('message', onMessage)
1264
+ window.addEventListener(GAME_SIZE_EVENT, onSizeEvent)
1265
+ window.addEventListener('storage', onSizeEvent)
1266
+ window.addEventListener('resize', onWinResize)
1267
+ window.addEventListener('keydown', onKey)
1268
+
1269
+ return () => {
1270
+ window.removeEventListener('message', onMessage)
1271
+ window.removeEventListener(GAME_SIZE_EVENT, onSizeEvent)
1272
+ window.removeEventListener('storage', onSizeEvent)
1273
+ window.removeEventListener('resize', onWinResize)
1274
+ window.removeEventListener('keydown', onKey)
1275
+ if (root.parentNode) root.parentNode.removeChild(root)
1276
+ }
1277
+ }, [])
1278
+
1279
+ return null
1280
+ }
1281
+
1282
+ /** 设置 → 社交小游戏:改窗口大小(写 localStorage,已打开的窗口立即跟着变) */
1283
+ function GameSettingsSection() {
1284
+ const [size, setSize] = useState(() => readGameSize())
1285
+ const [wIn, setWIn] = useState(() => String(readGameSize().w))
1286
+ const [hIn, setHIn] = useState(() => String(readGameSize().h))
1287
+ const [note, setNote] = useState('')
1288
+
1289
+ const apply = (next) => {
1290
+ const saved = writeGameSize(next)
1291
+ setSize(saved)
1292
+ setWIn(String(saved.w))
1293
+ setHIn(String(saved.h))
1294
+ setNote('已保存 ' + saved.w + ' × ' + saved.h)
1295
+ }
1296
+
1297
+ const isPreset = (p) => {
1298
+ const c = clampGameSize(p)
1299
+ return size.w === c.w && size.h === c.h
1300
+ }
1301
+
1302
+ return h(
1303
+ 'div',
1304
+ { className: 'sc-set' },
1305
+ h('div', null,
1306
+ h('div', { className: 'sc-set-title' }, '社交小游戏'),
1307
+ h(
1308
+ 'div',
1309
+ { className: 'sc-set-desc', style: { marginTop: '6px' } },
1310
+ '「🎮 摸鱼」打开的窗口大小。窗口可以拖标题栏移动、拖右下角临时改大小;这里设的是默认值,保存在这台电脑的浏览器里。',
1311
+ ),
1312
+ ),
1313
+ h(
1314
+ 'div',
1315
+ { className: 'sc-set-group' },
1316
+ h('div', { className: 'sc-set-label' }, '预设尺寸'),
1317
+ h(
1318
+ 'div',
1319
+ { className: 'sc-cards' },
1320
+ GAME_PRESETS.map((p) =>
1321
+ h(
1322
+ 'button',
1323
+ {
1324
+ key: p.label,
1325
+ className: 'sc-card-btn' + (isPreset(p) ? ' on' : ''),
1326
+ onClick: () => apply(p),
1327
+ },
1328
+ h('b', null, p.label),
1329
+ h('span', null, p.w + ' × ' + p.h),
1330
+ ),
1331
+ ),
1332
+ ),
1333
+ ),
1334
+ h(
1335
+ 'div',
1336
+ { className: 'sc-set-group' },
1337
+ h('div', { className: 'sc-set-label' }, '自定义'),
1338
+ h(
1339
+ 'div',
1340
+ { className: 'sc-inline' },
1341
+ h('input', {
1342
+ className: 'sc-input',
1343
+ value: wIn,
1344
+ inputMode: 'numeric',
1345
+ onChange: (e) => setWIn(e.target.value.replace(/[^0-9]/g, '')),
1346
+ }),
1347
+ h('span', { className: 'sc-hint' }, '×'),
1348
+ h('input', {
1349
+ className: 'sc-input',
1350
+ value: hIn,
1351
+ inputMode: 'numeric',
1352
+ onChange: (e) => setHIn(e.target.value.replace(/[^0-9]/g, '')),
1353
+ }),
1354
+ h('button', { className: 'sc-btn sc-btn-primary sc-btn-sm', onClick: () => apply({ w: Number(wIn), h: Number(hIn) }) }, '保存'),
1355
+ h('button', { className: 'sc-btn sc-btn-sm', onClick: () => apply(GAME_DEFAULT) }, '恢复默认'),
1356
+ note ? h('span', { className: 'sc-ok' }, note) : null,
1357
+ ),
1358
+ h('div', { className: 'sc-hint', style: { marginTop: '8px' } }, '最小 300×420;超过页面窗口会自动收进可视范围。'),
1359
+ ),
1360
+ )
1361
+ }
1362
+
1363
+ // ───────────────────────── 会议 ─────────────────────────
1364
+
1365
+ /**
1366
+ * 会议:纯浏览器 WebRTC 网状直连(≤6 人),relay 只做房间状态和 SDP/ICE 转发。
1367
+ * 没有媒体服务器,所以没有时长限制;代价是走 P2P,NAT 太差时需要 TURN。
1368
+ */
1369
+ const MEET_ICE = [
1370
+ { urls: ['stun:stun.cloudflare.com:3478', 'stun:stun.l.google.com:19302'] },
1371
+ // 以后加 TURN:{ urls: 'turn:turn.example.com:3478', username: 'u', credential: 'p' }
1372
+ ]
1373
+
1374
+ function openMeeting(opts) {
1375
+ const auth = opts.auth
1376
+ const onToast = opts.onToast || (() => {})
1377
+
1378
+ if (typeof RTCPeerConnection === 'undefined') {
1379
+ onToast('这个浏览器不支持 WebRTC,开不了会')
1380
+ return { close() {} }
1381
+ }
1382
+
1383
+ let roomId = ''
1384
+ let peerId = ''
1385
+ let localStream = null
1386
+ let camTrack = null
1387
+ let sharing = false
1388
+ let muted = false
1389
+ let camOn = true
1390
+ let sse = null
1391
+ let closed = false
1392
+ const pcs = new Map() // remotePeerId -> { pc, el, name, pending: [] }
1393
+ const peers = new Map() // remotePeerId -> { id, name, muted, cam, sharing }
1394
+
1395
+ /* ---------- DOM ---------- */
1396
+ const root = document.createElement('div')
1397
+ root.style.cssText = [
1398
+ 'position:fixed', 'display:flex', 'flex-direction:column', 'background:#0e1116',
1399
+ 'color:#eaf3f6', 'border:1px solid rgba(128,128,128,.45)', 'border-radius:14px',
1400
+ 'overflow:hidden', 'box-shadow:0 24px 64px rgba(0,0,0,.5)', 'z-index:2147483646',
1401
+ 'font:13px/1.5 -apple-system,Segoe UI,Microsoft YaHei,sans-serif',
1402
+ ].join(';')
1403
+ const W0 = Math.min(760, window.innerWidth - 40)
1404
+ const H0 = Math.min(540, window.innerHeight - 80)
1405
+ let pos = { x: Math.max(16, (window.innerWidth - W0) / 2), y: Math.max(48, (window.innerHeight - H0) / 2) }
1406
+ const size = { w: W0, h: H0 }
1407
+
1408
+ const head = document.createElement('div')
1409
+ head.style.cssText =
1410
+ 'display:flex;align-items:center;gap:8px;padding:9px 12px;background:rgba(255,255,255,.05);border-bottom:1px solid rgba(128,128,128,.25);cursor:move;user-select:none'
1411
+ const titleEl = document.createElement('strong')
1412
+ titleEl.textContent = '📹 会议'
1413
+ titleEl.style.cssText = 'font-size:13px'
1414
+ const codeEl = document.createElement('span')
1415
+ codeEl.style.cssText = 'font-size:11px;opacity:.6;font-family:ui-monospace,Consolas,monospace'
1416
+ const spacer = document.createElement('span')
1417
+ spacer.style.cssText = 'flex:1'
1418
+ const closeBtn = document.createElement('button')
1419
+ closeBtn.textContent = '关闭'
1420
+ closeBtn.style.cssText =
1421
+ 'padding:3px 10px;font-size:11px;border-radius:8px;border:1px solid rgba(255,255,255,.3);background:transparent;color:#eaf3f6;cursor:pointer'
1422
+ head.append(titleEl, codeEl, spacer, closeBtn)
1423
+
1424
+ const stage = document.createElement('div')
1425
+ stage.style.cssText = 'flex:1;min-height:0;display:grid;gap:8px;padding:10px;overflow:auto;grid-template-columns:1fr'
1426
+
1427
+ const tools = document.createElement('div')
1428
+ tools.style.cssText =
1429
+ 'display:flex;align-items:center;justify-content:center;gap:8px;padding:9px 12px;border-top:1px solid rgba(128,128,128,.25);background:rgba(0,0,0,.25)'
1430
+
1431
+ const grip = document.createElement('div')
1432
+ grip.style.cssText =
1433
+ 'position:absolute;right:0;bottom:0;width:16px;height:16px;cursor:nwse-resize;background:linear-gradient(135deg,transparent 50%,rgba(255,255,255,.3) 50%)'
1434
+
1435
+ root.append(head, stage, tools, grip)
1436
+ document.body.appendChild(root)
1437
+
1438
+ function paint() {
1439
+ root.style.left = pos.x + 'px'
1440
+ root.style.top = pos.y + 'px'
1441
+ root.style.width = size.w + 'px'
1442
+ root.style.height = size.h + 'px'
1443
+ }
1444
+ paint()
1445
+
1446
+ /* ---------- 小工具 ---------- */
1447
+ function btn(text, label, onClick, primary) {
1448
+ const b = document.createElement('button')
1449
+ b.textContent = text
1450
+ if (label) b.title = label
1451
+ b.style.cssText =
1452
+ 'height:32px;min-width:36px;padding:0 12px;border-radius:10px;cursor:pointer;font:inherit;font-size:12.5px;' +
1453
+ (primary
1454
+ ? 'border:0;background:#247bbf;color:#fff'
1455
+ : 'border:1px solid rgba(255,255,255,.22);background:rgba(255,255,255,.06);color:#eaf3f6')
1456
+ b.addEventListener('click', onClick)
1457
+ return b
1458
+ }
1459
+
1460
+ function tile(id, name, stream, isSelf) {
1461
+ const box = document.createElement('div')
1462
+ box.style.cssText =
1463
+ 'position:relative;border-radius:12px;overflow:hidden;background:#000;min-height:120px;display:flex;align-items:center;justify-content:center'
1464
+ const v = document.createElement('video')
1465
+ v.autoplay = true
1466
+ v.playsInline = true
1467
+ v.muted = !!isSelf
1468
+ v.style.cssText = 'width:100%;height:100%;object-fit:cover'
1469
+ if (stream) v.srcObject = stream
1470
+ const tag = document.createElement('div')
1471
+ tag.style.cssText =
1472
+ 'position:absolute;left:8px;bottom:8px;padding:2px 8px;border-radius:8px;background:rgba(0,0,0,.55);font-size:11px'
1473
+ tag.textContent = name + (isSelf ? '(我)' : '')
1474
+ box.append(v, tag)
1475
+ stage.appendChild(box)
1476
+ return { box, video: v, tag }
1477
+ }
1478
+
1479
+ function relayout() {
1480
+ const n = stage.children.length
1481
+ const cols = n <= 1 ? 1 : n <= 4 ? 2 : 3
1482
+ stage.style.gridTemplateColumns = 'repeat(' + cols + ',1fr)'
1483
+ }
1484
+
1485
+ /* ---------- 信令 / 媒体 ---------- */
1486
+ async function post(path, body) {
1487
+ return api(auth.server, path, { method: 'POST', token: auth.token, body })
1488
+ }
1489
+
1490
+ function sendSignal(to, data) {
1491
+ return post('/api/meet/rooms/' + roomId + '/signal', { from: peerId, to, data }).catch(() => {})
1492
+ }
1493
+
1494
+ function pcFor(remote) {
1495
+ if (pcs.has(remote)) return pcs.get(remote)
1496
+ const entry = { pc: null, el: null, name: '', pending: [], iceTried: 0 }
1497
+ const pc = new RTCPeerConnection({ iceServers: MEET_ICE })
1498
+ entry.pc = pc
1499
+ pc.onicecandidate = (e) => {
1500
+ if (e.candidate) sendSignal(remote, { type: 'ice', candidate: e.candidate })
1501
+ }
1502
+ pc.ontrack = (e) => {
1503
+ const stream = e.streams && e.streams[0]
1504
+ if (!stream) return
1505
+ if (!entry.el) {
1506
+ entry.el = tile(remote, entry.name || '好友', stream, false)
1507
+ relayout()
1508
+ } else {
1509
+ entry.el.video.srcObject = stream
1510
+ }
1511
+ }
1512
+ pc.onconnectionstatechange = () => {
1513
+ if (pc.connectionState === 'failed') {
1514
+ const p = peers.get(remote)
1515
+ if (p) p.failed = true
1516
+ refreshTags()
1517
+ }
1518
+ }
1519
+ if (localStream) for (const t of localStream.getTracks()) pc.addTrack(t, localStream)
1520
+ pcs.set(remote, entry)
1521
+ return entry
1522
+ }
1523
+
1524
+ function refreshTags() {
1525
+ for (const [id, entry] of pcs) {
1526
+ const p = peers.get(id)
1527
+ if (!entry.el) continue
1528
+ const flags = []
1529
+ if (p && p.muted) flags.push('🔇')
1530
+ if (p && p.sharing) flags.push('🖥')
1531
+ if (p && p.failed) flags.push('⚠ 可能需要对端 TURN')
1532
+ entry.el.tag.textContent = (entry.name || (p && p.name) || '好友') + (flags.length ? ' ' + flags.join(' ') : '')
1533
+ }
1534
+ }
1535
+
1536
+ async function makeOffer(remote) {
1537
+ const entry = pcFor(remote)
1538
+ const offer = await entry.pc.createOffer()
1539
+ await entry.pc.setLocalDescription(offer)
1540
+ await sendSignal(remote, { type: 'offer', sdp: offer.sdp })
1541
+ }
1542
+
1543
+ async function onSignal(from, data) {
1544
+ if (!data || !data.type) return
1545
+ const entry = pcFor(from)
1546
+ const pc = entry.pc
1547
+ try {
1548
+ if (data.type === 'offer') {
1549
+ await pc.setRemoteDescription({ type: 'offer', sdp: data.sdp })
1550
+ for (const c of entry.pending.splice(0)) await pc.addIceCandidate(c).catch(() => {})
1551
+ const answer = await pc.createAnswer()
1552
+ await pc.setLocalDescription(answer)
1553
+ await sendSignal(from, { type: 'answer', sdp: answer.sdp })
1554
+ } else if (data.type === 'answer') {
1555
+ await pc.setRemoteDescription({ type: 'answer', sdp: data.sdp })
1556
+ for (const c of entry.pending.splice(0)) await pc.addIceCandidate(c).catch(() => {})
1557
+ } else if (data.type === 'ice') {
1558
+ if (pc.remoteDescription && pc.remoteDescription.type) {
1559
+ await pc.addIceCandidate(data.candidate).catch(() => {})
1560
+ } else {
1561
+ entry.pending.push(data.candidate)
1562
+ }
1563
+ }
1564
+ } catch (e) {
1565
+ console.error('[meet] 处理信令失败', e)
1566
+ }
1567
+ }
1568
+
1569
+ function dropPeer(id) {
1570
+ const entry = pcs.get(id)
1571
+ if (entry) {
1572
+ try {
1573
+ entry.pc.close()
1574
+ } catch (e) {}
1575
+ if (entry.el && entry.el.box.parentNode) entry.el.box.parentNode.removeChild(entry.el.box)
1576
+ pcs.delete(id)
1577
+ relayout()
1578
+ }
1579
+ peers.delete(id)
1580
+ renderToolbar()
1581
+ }
1582
+
1583
+ function upsertPeer(p) {
1584
+ peers.set(p.id, p)
1585
+ const entry = pcs.get(p.id)
1586
+ if (entry) entry.name = p.name
1587
+ refreshTags()
1588
+ }
1589
+
1590
+ /* ---------- SSE ---------- */
1591
+ function openStream() {
1592
+ const url =
1593
+ String(auth.server).replace(/\/+$/, '') +
1594
+ '/api/meet/rooms/' + roomId + '/events?peer=' + encodeURIComponent(peerId) +
1595
+ '&token=' + encodeURIComponent(auth.token)
1596
+ sse = new EventSource(url)
1597
+ sse.addEventListener('snapshot', async (e) => {
1598
+ const d = JSON.parse(e.data)
1599
+ peers.clear()
1600
+ for (const p of d.room.peers) if (p.id !== peerId) upsertPeer(p)
1601
+ titleEl.textContent = '📹 ' + (d.room.title || '会议')
1602
+ for (const p of d.room.peers) {
1603
+ if (p.id === peerId) continue
1604
+ if (!pcs.has(p.id)) makeOffer(p.id)
1605
+ }
1606
+ renderToolbar()
1607
+ })
1608
+ sse.addEventListener('peer-joined', (e) => {
1609
+ const d = JSON.parse(e.data)
1610
+ if (d.peer && d.peer.id !== peerId) {
1611
+ upsertPeer(d.peer)
1612
+ if (!d.peer.el) tile(d.peer.id, d.peer.name || '好友', null, false)
1613
+ relayout()
1614
+ }
1615
+ })
1616
+ sse.addEventListener('peer-left', (e) => {
1617
+ const d = JSON.parse(e.data)
1618
+ if (d.peerId) dropPeer(d.peerId)
1619
+ })
1620
+ sse.addEventListener('peer-state', (e) => {
1621
+ const d = JSON.parse(e.data)
1622
+ if (d.peer) upsertPeer(d.peer)
1623
+ })
1624
+ sse.addEventListener('signal', (e) => {
1625
+ const d = JSON.parse(e.data)
1626
+ if (d.from) onSignal(d.from, d.data)
1627
+ })
1628
+ sse.addEventListener('error', () => {
1629
+ if (closed) return
1630
+ /* EventSource 自己会重连(relay 里 retry: 3000) */
1631
+ })
1632
+ }
1633
+
1634
+ async function publishState() {
1635
+ if (!roomId || !peerId) return
1636
+ await post('/api/meet/rooms/' + roomId + '/state', {
1637
+ peerId,
1638
+ muted,
1639
+ cam: camOn,
1640
+ sharing,
1641
+ }).catch(() => {})
1642
+ }
1643
+
1644
+ /* ---------- 工具栏 ---------- */
1645
+ function renderToolbar() {
1646
+ tools.textContent = ''
1647
+ if (!roomId) {
1648
+ tools.append(btn('+ 新建会议', '开一个房间', () => startMeeting('create'), true))
1649
+ const input = document.createElement('input')
1650
+ input.placeholder = '房间号'
1651
+ input.style.cssText =
1652
+ 'height:32px;width:110px;padding:0 10px;border-radius:10px;border:1px solid rgba(255,255,255,.22);background:rgba(255,255,255,.06);color:inherit;font:inherit;outline:none'
1653
+ const go = btn('加入', '加入会议', () => startMeeting('join', input.value.trim()), true)
1654
+ tools.append(input, go)
1655
+ return
1656
+ }
1657
+ tools.append(
1658
+ btn(muted ? '🔇 已静音' : '🎤 麦克风', '切换麦克风', () => {
1659
+ if (!localStream) return
1660
+ muted = !muted
1661
+ for (const t of localStream.getAudioTracks()) t.enabled = !muted
1662
+ publishState()
1663
+ renderToolbar()
1664
+ }),
1665
+ btn(camOn ? '🎥 摄像头' : '🎥 已关', '切换摄像头', () => {
1666
+ const t = localStream && localStream.getVideoTracks()[0]
1667
+ if (!t) return
1668
+ camOn = !camOn
1669
+ t.enabled = camOn
1670
+ publishState()
1671
+ renderToolbar()
1672
+ }),
1673
+ btn(sharing ? '🖥 停止共享' : '🖥 共享屏幕', '共享屏幕', toggleShare),
1674
+ btn('📋 ' + roomId, '复制房间号', () => {
1675
+ navigator.clipboard && navigator.clipboard.writeText(roomId).then(
1676
+ () => onToast('房间号已复制:' + roomId),
1677
+ () => onToast('房间号:' + roomId),
1678
+ )
1679
+ }),
1680
+ btn('🚪 离开', '离开会议', leave, true),
1681
+ )
1682
+ }
1683
+
1684
+ async function toggleShare() {
1685
+ if (!navigator.mediaDevices || !navigator.mediaDevices.getDisplayMedia) {
1686
+ onToast('这个浏览器不支持屏幕共享')
1687
+ return
1688
+ }
1689
+ if (sharing) {
1690
+ stopShare()
1691
+ return
1692
+ }
1693
+ try {
1694
+ const ds = await navigator.mediaDevices.getDisplayMedia({ video: true })
1695
+ const track = ds.getVideoTracks()[0]
1696
+ sharing = true
1697
+ const self = [...stage.children][0]
1698
+ for (const [, entry] of pcs) {
1699
+ const sender = entry.pc.getSenders().find((s) => s.track && s.track.kind === 'video')
1700
+ if (sender) await sender.replaceTrack(track)
1701
+ }
1702
+ track.onended = stopShare
1703
+ if (self) self.querySelector('video').srcObject = new MediaStream([track])
1704
+ publishState()
1705
+ renderToolbar()
1706
+ } catch (e) {
1707
+ onToast('共享屏幕被取消或失败')
1708
+ }
1709
+ }
1710
+
1711
+ function stopShare() {
1712
+ sharing = false
1713
+ const t = localStream && localStream.getVideoTracks()[0]
1714
+ for (const [, entry] of pcs) {
1715
+ const sender = entry.pc.getSenders().find((s) => s.track && s.track.kind === 'video')
1716
+ if (sender && t) sender.replaceTrack(t).catch(() => {})
1717
+ }
1718
+ const self = [...stage.children][0]
1719
+ if (self && localStream) self.querySelector('video').srcObject = localStream
1720
+ publishState()
1721
+ renderToolbar()
1722
+ }
1723
+
1724
+ /* ---------- 进出房间 ---------- */
1725
+ async function ensureMedia() {
1726
+ if (localStream) return
1727
+ try {
1728
+ localStream = await navigator.mediaDevices.getUserMedia({
1729
+ audio: true,
1730
+ video: { width: { ideal: 640 }, height: { ideal: 480 } },
1731
+ })
1732
+ camOn = true
1733
+ } catch (e) {
1734
+ try {
1735
+ localStream = await navigator.mediaDevices.getUserMedia({ audio: true })
1736
+ camOn = false
1737
+ onToast('摄像头不可用,先只开麦克风')
1738
+ } catch (e2) {
1739
+ throw new Error('拿不到麦克风/摄像头:' + ((e2 && e2.message) || e2))
1740
+ }
1741
+ }
1742
+ tile('self', '我', localStream, true)
1743
+ relayout()
1744
+ }
1745
+
1746
+ async function startMeeting(mode, code) {
1747
+ try {
1748
+ await ensureMedia()
1749
+ } catch (e) {
1750
+ alert(String(e.message || e))
1751
+ return
1752
+ }
1753
+ try {
1754
+ let room
1755
+ if (mode === 'create') {
1756
+ const r = await post('/api/meet/rooms', { title: (auth.displayName || auth.id) + ' 的会议' })
1757
+ room = r.room
1758
+ }
1759
+ if (mode === 'join' || mode === 'create') {
1760
+ const id = mode === 'create' ? room.id : String(code || '')
1761
+ if (!id) return
1762
+ const j = await post('/api/meet/rooms/' + id + '/join', { name: auth.displayName || auth.id })
1763
+ roomId = id
1764
+ peerId = j.peerId
1765
+ codeEl.textContent = '房间号 ' + roomId + '(发给好友就能进)'
1766
+ titleEl.textContent = '📹 ' + (j.room.title || '会议')
1767
+ openStream()
1768
+ renderToolbar()
1769
+ }
1770
+ } catch (e) {
1771
+ alert('进不去:' + friendly(e))
1772
+ }
1773
+ }
1774
+
1775
+ async function leave() {
1776
+ if (closed) return
1777
+ closed = true
1778
+ try {
1779
+ if (sse) sse.close()
1780
+ } catch (e) {}
1781
+ sse = null
1782
+ if (roomId && peerId) {
1783
+ await post('/api/meet/rooms/' + roomId + '/leave', { peerId }).catch(() => {})
1784
+ }
1785
+ for (const [, entry] of pcs) {
1786
+ try {
1787
+ entry.pc.close()
1788
+ } catch (e) {}
1789
+ }
1790
+ pcs.clear()
1791
+ if (localStream) {
1792
+ for (const t of localStream.getTracks()) t.stop()
1793
+ localStream = null
1794
+ }
1795
+ if (root.parentNode) root.parentNode.removeChild(root)
1796
+ onToast('已离开会议')
1797
+ }
1798
+
1799
+ /* ---------- 窗口交互 ---------- */
1800
+ closeBtn.addEventListener('click', leave)
1801
+ head.addEventListener('pointerdown', (e) => {
1802
+ if (e.target && e.target.closest && e.target.closest('button')) return
1803
+ if (e.button !== 0) return
1804
+ e.preventDefault()
1805
+ const start = { px: e.clientX, py: e.clientY, x: pos.x, y: pos.y }
1806
+ const move = (ev) => {
1807
+ pos = {
1808
+ x: Math.min(Math.max(0, start.x + ev.clientX - start.px), Math.max(0, window.innerWidth - 120)),
1809
+ y: Math.min(Math.max(0, start.y + ev.clientY - start.py), Math.max(0, window.innerHeight - 80)),
1810
+ }
1811
+ paint()
1812
+ }
1813
+ const up = () => {
1814
+ window.removeEventListener('pointermove', move)
1815
+ window.removeEventListener('pointerup', up)
1816
+ }
1817
+ window.addEventListener('pointermove', move)
1818
+ window.addEventListener('pointerup', up)
1819
+ })
1820
+ grip.addEventListener('pointerdown', (e) => {
1821
+ e.preventDefault()
1822
+ e.stopPropagation()
1823
+ const start = { px: e.clientX, py: e.clientY, w: size.w, h: size.h }
1824
+ const move = (ev) => {
1825
+ size.w = Math.max(420, Math.min(start.w + ev.clientX - start.px, window.innerWidth - 20))
1826
+ size.h = Math.max(320, Math.min(start.h + ev.clientY - start.py, window.innerHeight - 20))
1827
+ paint()
1828
+ }
1829
+ const up = () => {
1830
+ window.removeEventListener('pointermove', move)
1831
+ window.removeEventListener('pointerup', up)
1832
+ }
1833
+ window.addEventListener('pointermove', move)
1834
+ window.addEventListener('pointerup', up)
1835
+ })
1836
+ const onKey = (e) => {
1837
+ if (e.key === 'Escape') leave()
1838
+ }
1839
+ window.addEventListener('keydown', onKey)
1840
+
1841
+ renderToolbar()
1842
+ return { close: leave }
1843
+ }
1844
+
1845
+ // ───────────────────────── 入口 ─────────────────────────
1846
+
1847
+ function SocialView(props) {
1848
+ const [auth, setAuth] = useState(() => readJson(K_AUTH))
1849
+ const [gameOpen, setGameOpen] = useState(false)
1850
+
1851
+ const body = !auth
1852
+ ? h(LoginPanel, { onDone: (next) => setAuth(next) })
1853
+ : h(ChatPanel, {
1854
+ auth,
1855
+ onOpenGame: () => setGameOpen(true),
1856
+ onLogout: () => {
1857
+ dropKey(K_AUTH)
1858
+ setAuth(null)
1859
+ setGameOpen(false)
1860
+ },
1861
+ })
1862
+
1863
+ // 只有会话里的 View 才拿得到会话数据;全局面板没有 props
1864
+ const canShare = !!(props && props.sessionId && typeof props.useChat === 'function')
1865
+
1866
+ return h(
1867
+ 'div',
1868
+ { className: 'sc-root' },
1869
+ canShare && auth ? h(Boundary, null, h(ShareBar, { chatProps: props, auth })) : null,
1870
+ h('div', { style: { flex: 1, minHeight: 0, display: 'flex' } }, body),
1871
+ gameOpen ? h(GameWindow, { onClose: () => setGameOpen(false) }) : null,
1872
+ )
1873
+ }
1874
+
1875
+ // ─────────────────────── 一键分享 ───────────────────────
1876
+
1877
+ /** 兜住探针/适配器的异常,别让整个 slot 变空白 */
1878
+ class Boundary extends React.Component {
1879
+ constructor(p) {
1880
+ super(p)
1881
+ this.state = { err: null }
1882
+ }
1883
+ static getDerivedStateFromError(e) {
1884
+ return { err: String((e && e.message) || e) }
1885
+ }
1886
+ render() {
1887
+ if (this.state.err) {
1888
+ return h(
1889
+ 'div',
1890
+ { style: { padding: '6px 12px', fontSize: '11px', color: '#d9534f', borderBottom: LINE } },
1891
+ '分享组件出错:' + this.state.err,
1892
+ )
1893
+ }
1894
+ return this.props.children
1895
+ }
1896
+ }
1897
+
1898
+ function shapeOf(v) {
1899
+ if (v === null) return 'null'
1900
+ if (v === undefined) return 'undefined'
1901
+ if (Array.isArray(v)) {
1902
+ const first = v.length ? Object.keys(v[0] || {}).join(',') : ''
1903
+ return `array(${v.length})` + (first ? ` item: {${first}}` : '')
1904
+ }
1905
+ if (typeof v === 'object') return 'object { ' + Object.keys(v).join(', ') + ' }'
1906
+ return typeof v + ' = ' + String(v).slice(0, 80)
1907
+ }
1908
+
1909
+ /** 在几种常见形状里找出条目数组 */
1910
+ function pickArray(v) {
1911
+ if (Array.isArray(v)) return v
1912
+ if (!v || typeof v !== 'object') return null
1913
+ const keys = [
1914
+ 'rows',
1915
+ 'nodes',
1916
+ 'messages',
1917
+ 'items',
1918
+ 'entries',
1919
+ 'turns',
1920
+ 'data',
1921
+ 'list',
1922
+ 'chat',
1923
+ 'snapshot',
1924
+ 'timeline',
1925
+ 'events',
1926
+ 'groups',
1927
+ ]
1928
+ for (const k of keys) if (Array.isArray(v[k])) return v[k]
1929
+ // 兜底:只有唯一一个数组字段时就用它
1930
+ const arrays = Object.keys(v).filter((k) => Array.isArray(v[k]))
1931
+ if (arrays.length === 1) return v[arrays[0]]
1932
+ return null
1933
+ }
1934
+
1935
+ function textOf(it) {
1936
+ if (typeof it === 'string') return it
1937
+ if (!it || typeof it !== 'object') return ''
1938
+ const cand = it.text ?? it.markdown ?? it.plain ?? it.content ?? it.body
1939
+ if (typeof cand === 'string') return cand
1940
+ if (Array.isArray(cand)) {
1941
+ return cand
1942
+ .map((c) => (typeof c === 'string' ? c : (c && (c.text || c.content)) || ''))
1943
+ .join('')
1944
+ }
1945
+ if (cand && typeof cand === 'object') {
1946
+ const t = cand.text ?? cand.content
1947
+ if (typeof t === 'string') return t
1948
+ }
1949
+ return ''
1950
+ }
1951
+
1952
+ /** 长得像内部 id 的字符串,不能当正文用 */
1953
+ const ID_LIKE = /^(\d+:[a-z]|[0-9a-f]{8}-[0-9a-f]{4}|call_|toolu_|msg_|req_|turn-|step-)/i
1954
+
1955
+ function looksLikeIdText(s) {
1956
+ const t = String(s).trim()
1957
+ if (!t) return false
1958
+ if (ID_LIKE.test(t)) return true
1959
+ // 长串、无空格、只有 id 字符
1960
+ if (t.length > 24 && !/\s/.test(t) && /^[0-9a-zA-Z:_-]+$/.test(t)) return true
1961
+ return false
1962
+ }
1963
+
1964
+ /** 这些键装的是元数据,不是正文 */
1965
+ const SKIP_KEY =
1966
+ /^(id|ids|key|nodeId|eventId|kind|type|role|seq|at|ts|time|status|state|phase|channel|visibility|variant|surface|stage|mode|level|turnId|stepId|requestId|callId|toolCallId|parentId|sessionId|hash|signature|uri|url|path|name|toolName|model|usage|timing|duration|error|code)$/i
1967
+
1968
+ /** 思考过程的键名——绝不能分享出去 */
1969
+ const REASON_KEY = /reason|think|thought|scratch|cot$/i
1970
+
1971
+ /**
1972
+ * 分组/分段结构里的枚举值,单个单词出现时必是噪音。
1973
+ * 中文回复不受影响(不在这个表里)。
1974
+ */
1975
+ const NOISE_WORDS = new Set([
1976
+ 'chat',
1977
+ 'visible',
1978
+ 'hidden',
1979
+ 'exchange',
1980
+ 'tool',
1981
+ 'tools',
1982
+ 'assistant',
1983
+ 'user',
1984
+ 'system',
1985
+ 'reasoning',
1986
+ 'text',
1987
+ 'markdown',
1988
+ 'plain',
1989
+ 'js',
1990
+ 'json',
1991
+ 'html',
1992
+ 'css',
1993
+ 'null',
1994
+ 'true',
1995
+ 'false',
1996
+ 'queued',
1997
+ 'pending',
1998
+ 'done',
1999
+ 'notice',
2000
+ 'stream',
2001
+ 'delta',
2002
+ 'start',
2003
+ 'end',
2004
+ 'input',
2005
+ 'output',
2006
+ 'call',
2007
+ 'result',
2008
+ 'content',
2009
+ 'step',
2010
+ 'turn',
2011
+ ])
2012
+
2013
+ function isNoiseWord(s) {
2014
+ if (s.length > 14) return false
2015
+ return NOISE_WORDS.has(String(s).toLowerCase())
2016
+ }
2017
+
2018
+ function collectText(node, depth, out) {
2019
+ if (depth > 4 || out.length > 300) return
2020
+ if (typeof node === 'string') {
2021
+ const s = node.trim()
2022
+ if (!s || looksLikeIdText(s) || isNoiseWord(s)) return
2023
+ // 大段 JSON 是工具参数,不是正文
2024
+ if ((s.startsWith('{') || s.startsWith('[')) && s.length > 60) return
2025
+ out.push(s)
2026
+ return
2027
+ }
2028
+ if (Array.isArray(node)) {
2029
+ for (const v of node) collectText(v, depth + 1, out)
2030
+ return
2031
+ }
2032
+ if (!node || typeof node !== 'object') return
2033
+ // 整棵子树是思考过程就整段跳过
2034
+ const sig = node.kind || node.type || node.role
2035
+ if (typeof sig === 'string' && /reason|think|thought/i.test(sig)) return
2036
+ for (const k of Object.keys(node)) {
2037
+ if (SKIP_KEY.test(k) || REASON_KEY.test(k)) continue
2038
+ const v = node[k]
2039
+ if (typeof v === 'string' || (v && typeof v === 'object')) collectText(v, depth + 1, out)
2040
+ }
2041
+ }
2042
+
2043
+ /**
2044
+ * 去掉运行时注入的上下文。
2045
+ * 用户消息节点里会带着 system-reminder 那一整块,分享出去是噪音。
2046
+ */
2047
+ function stripInjected(text) {
2048
+ let t = String(text || '')
2049
+ t = t.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/gi, '')
2050
+ t = t.replace(/<system-reminder>[\s\S]*$/gi, '')
2051
+ const dropLine =
2052
+ /^(Time sampled|Browser time zone|Elapsed since|Current working directory|Current DSH file policy|Current DeepSeek Harness|You are the root agent|You are an AI agent|You are a coding agent|To message other agents|When you are asked|A skill is a reusable|Non-zero exits|Tokens prefixed with|Use the read tool|Use the glob tool|Use the grep tool|Use the workflow tool|Only create or modify scheduled)/i
2053
+ return t
2054
+ .split(/\r?\n/)
2055
+ .filter((line) => !dropLine.test(line.trim()))
2056
+ .join('\n')
2057
+ .trim()
2058
+ }
2059
+
2060
+ /** 从节点对象里挖正文:先试常用字段,不行就整节点深扫 */
2061
+ function textFromNode(node) {
2062
+ if (node === null || node === undefined) return ''
2063
+ for (const k of ['text', 'markdown', 'plain', 'content', 'message', 'body']) {
2064
+ const v = node[k]
2065
+ if (v === undefined || v === null) continue
2066
+ const out = []
2067
+ collectText(v, 0, out)
2068
+ const t = out.join('\n').trim()
2069
+ if (t) return t
2070
+ }
2071
+ const out = []
2072
+ collectText(node, 0, out)
2073
+ // 去重相邻重复行
2074
+ const seen = []
2075
+ for (const line of out) if (seen[seen.length - 1] !== line) seen.push(line)
2076
+ return seen.join('\n').trim()
2077
+ }
2078
+
2079
+ /** state 里哪些字段是对象型 map(不是数组) */
2080
+ function mapFields(state) {
2081
+ if (!state || typeof state !== 'object') return []
2082
+ return Object.keys(state).filter((k) => {
2083
+ const v = state[k]
2084
+ return v && typeof v === 'object' && !Array.isArray(v)
2085
+ })
2086
+ }
2087
+
2088
+ /** 看起来像节点的对象(有 id / kind / seq 之一) */
2089
+ function looksLikeNode(v) {
2090
+ return (
2091
+ !!v &&
2092
+ typeof v === 'object' &&
2093
+ !Array.isArray(v) &&
2094
+ (typeof v.id === 'string' ||
2095
+ typeof v.kind === 'string' ||
2096
+ typeof v.seq === 'number' ||
2097
+ typeof v.type === 'string')
2098
+ )
2099
+ }
2100
+
2101
+ /**
2102
+ * 递归收集「id → 节点」索引。
2103
+ * 关键:state.nodes.byKey 是 Map,不是普通对象,必须用 instanceof Map 处理。
2104
+ */
2105
+ function buildLookup(state) {
2106
+ const idx = new Map()
2107
+ let nodeCount = 0
2108
+ const put = (key, val) => {
2109
+ if (key !== undefined && key !== null) idx.set(String(key), val)
2110
+ const idf = val.id || val.nodeId || val.key
2111
+ if (typeof idf === 'string') idx.set(idf, val)
2112
+ nodeCount += 1
2113
+ }
2114
+ const visit = (v, depth) => {
2115
+ if (depth > 3 || !v || typeof v !== 'object') return
2116
+ if (v instanceof Map) {
2117
+ for (const [k, val] of v) {
2118
+ if (looksLikeNode(val)) put(k, val)
2119
+ }
2120
+ // Map 的值里还可能套着 Map
2121
+ for (const [, val] of v) if (val && typeof val === 'object') visit(val, depth + 1)
2122
+ return
2123
+ }
2124
+ if (Array.isArray(v)) {
2125
+ for (const item of v) if (item && typeof item === 'object') visit(item, depth + 1)
2126
+ return
2127
+ }
2128
+ for (const [k, val] of Object.entries(v)) {
2129
+ if (!val || typeof val !== 'object') continue
2130
+ if (looksLikeNode(val)) put(k, val)
2131
+ else visit(val, depth + 1)
2132
+ }
2133
+ }
2134
+ visit(state, 0)
2135
+ return { idx, nodeCount }
2136
+ }
2137
+
2138
+ /** 按 id 里的关键字给节点分类;分不出就是 null(结构节点,跳过) */
2139
+ function kindOfId(id) {
2140
+ const s = String(id)
2141
+ if (/input-message|user/i.test(s)) return 'user'
2142
+ if (/tool-call|tool-result|toolCall/i.test(s)) return 'tool'
2143
+ if (/assistant|reason/i.test(s)) return 'assistant'
2144
+ return null
2145
+ }
2146
+
2147
+ /**
2148
+ * 把会话 state 折成快照块。
2149
+ * 只取「最后一轮」:order 里的 turn-tail 是轮次边界,从倒数第二个之后开始。
2150
+ */
2151
+ function extractBlocks(state, limit) {
2152
+ const ids = pickArray(state)
2153
+ if (!ids) return null
2154
+ const lookup = buildLookup(state)
2155
+ if (lookup.idx.size === 0) return null
2156
+
2157
+ const tails = []
2158
+ for (let i = 0; i < ids.length; i++) {
2159
+ if (typeof ids[i] === 'string' && /turn-tail/i.test(ids[i])) tails.push(i)
2160
+ }
2161
+ const start = tails.length >= 2 ? tails[tails.length - 2] + 1 : 0
2162
+ const window = ids.slice(start)
2163
+
2164
+ const out = []
2165
+ let lastText = ''
2166
+ for (const id of window) {
2167
+ if (typeof id !== 'string') continue
2168
+ const kind = kindOfId(id)
2169
+ if (!kind) continue
2170
+ const node = lookup.idx.get(id)
2171
+ if (!node) continue
2172
+
2173
+ // 工具节点不深扫:只要名字 + 一行短摘要,避免把参数 JSON 全带出去
2174
+ if (kind === 'tool') {
2175
+ const rawName = node.name || node.toolName || node.tool?.name || ''
2176
+ const rawArg = node.args ?? node.input ?? node.arguments
2177
+ let preview = ''
2178
+ if (typeof rawArg === 'string') preview = rawArg
2179
+ else if (rawArg && typeof rawArg === 'object') {
2180
+ try {
2181
+ preview = JSON.stringify(rawArg)
2182
+ } catch {
2183
+ preview = ''
2184
+ }
2185
+ }
2186
+ preview = stripInjected(preview).replace(/\s+/g, ' ').trim().slice(0, 140)
2187
+ // 名字和摘要都拿不到,这个工具节点没信息量,别占位置
2188
+ if (!rawName && !preview) continue
2189
+ out.push({ t: 'tool', name: String(rawName || 'tool').slice(0, 40), text: preview })
2190
+ continue
2191
+ }
2192
+
2193
+ const text = stripInjected(textFromNode(node))
2194
+ if (!text) continue
2195
+ if (text === lastText) continue
2196
+ lastText = text
2197
+ out.push({ t: kind, text: text.slice(0, 1500) })
2198
+ }
2199
+ return out.slice(-limit)
2200
+ }
2201
+
2202
+ /** 挖不出来时,把一个真实消息节点的形状摊开 */
2203
+ function diagnose(state) {
2204
+ const lines = ['state: ' + shapeOf(state)]
2205
+ const ids = pickArray(state)
2206
+ const lookup = buildLookup(state)
2207
+ if (ids) {
2208
+ lines.push('id 数组长度 ' + ids.length + ',末项 ' + shapeOf(ids[ids.length - 1]))
2209
+ }
2210
+ lines.push('索引到节点数: ' + lookup.idx.size)
2211
+ lines.push('nodes.byKey 是 Map? ' + (state && state.nodes && state.nodes.byKey instanceof Map))
2212
+ if (ids) {
2213
+ // 优先取样「回复」节点——它是最可能挖不出文本的那类
2214
+ const pickProbe = (re) => {
2215
+ for (let i = ids.length - 1; i >= 0; i--) {
2216
+ if (typeof ids[i] === 'string' && re.test(ids[i])) return ids[i]
2217
+ }
2218
+ return null
2219
+ }
2220
+ const probeId =
2221
+ pickProbe(/assistant/i) || pickProbe(/tool-call/i) || pickProbe(/input-message/i)
2222
+ lines.push('取样 id: ' + String(probeId))
2223
+ if (probeId) {
2224
+ const node = lookup.idx.get(probeId)
2225
+ if (!node) {
2226
+ lines.push('索引里没有这个 id')
2227
+ } else {
2228
+ lines.push('节点字段: ' + Object.keys(node).join(', '))
2229
+ lines.push('提取文本长度: ' + stripInjected(textFromNode(node)).length)
2230
+ try {
2231
+ lines.push('节点 JSON: ' + JSON.stringify(node).slice(0, 700))
2232
+ } catch {
2233
+ lines.push('节点 JSON: <无法序列化>')
2234
+ }
2235
+ }
2236
+ }
2237
+ }
2238
+ return lines.join('\n')
2239
+ }
2240
+
2241
+ function ShareBar(props) {
2242
+ const { chatProps, auth } = props
2243
+ // 这些是 selector hook:必须传选择器。先要整个 state,不猜字段名。
2244
+ const chat = chatProps.useChat((s) => s)
2245
+ const [open, setOpen] = useState(false)
2246
+ const [friends, setFriends] = useState([])
2247
+ const [target, setTarget] = useState('')
2248
+ const [busy, setBusy] = useState(false)
2249
+ const [note, setNote] = useState('')
2250
+
2251
+ useEffect(() => {
2252
+ if (!open) return
2253
+ let alive = true
2254
+ api(auth.server, '/api/friends', { token: auth.token })
2255
+ .then((r) => {
2256
+ if (!alive) return
2257
+ const list = r.friends || []
2258
+ setFriends(list)
2259
+ if (!target && list.length) setTarget(list[0].id)
2260
+ if (!list.length) setNote('还没有好友,先在左边的「好友」里加一个')
2261
+ })
2262
+ .catch((e) => {
2263
+ if (alive) setNote(friendly(e))
2264
+ })
2265
+ return () => {
2266
+ alive = false
2267
+ }
2268
+ // eslint-disable-next-line react-hooks/exhaustive-deps
2269
+ }, [open, auth.server, auth.token])
2270
+
2271
+ const blocks = extractBlocks(chat, 8)
2272
+ const looksLikeIds =
2273
+ !!blocks && blocks.length > 0 && blocks.every((b) => /^\d+:[a-z]/i.test(String(b.text)))
2274
+ const broke = !blocks || blocks.length === 0 || looksLikeIds
2275
+
2276
+ const send = async () => {
2277
+ if (!target || busy) return
2278
+ if (!blocks || blocks.length === 0) {
2279
+ setNote('没读到会话内容,形状:' + shapeOf(chat))
2280
+ return
2281
+ }
2282
+ setBusy(true)
2283
+ setNote('')
2284
+ try {
2285
+ await api(auth.server, '/api/messages', {
2286
+ method: 'POST',
2287
+ token: auth.token,
2288
+ body: {
2289
+ to: target,
2290
+ snapshot: {
2291
+ v: 0,
2292
+ title: '从 DSH 分享 · ' + new Date().toLocaleString('zh-CN'),
2293
+ blocks,
2294
+ },
2295
+ },
2296
+ })
2297
+ setNote('已发给 ' + target + ',共 ' + blocks.length + ' 段')
2298
+ setOpen(false)
2299
+ } catch (e) {
2300
+ setNote(friendly(e))
2301
+ } finally {
2302
+ setBusy(false)
2303
+ }
2304
+ }
2305
+
2306
+ if (!open) {
2307
+ return h(
2308
+ 'div',
2309
+ { className: 'sc-share' },
2310
+ h(
2311
+ 'div',
2312
+ { className: 'sc-share-row' },
2313
+ h(
2314
+ 'button',
2315
+ { className: 'sc-btn sc-btn-sm', onClick: () => setOpen(true) },
2316
+ '🐟 分享这一轮',
2317
+ ),
2318
+ h('span', { className: 'sc-share-note' }, '把这一问一答发给好友,不带思考过程和运行时上下文'),
2319
+ note ? h('span', { className: 'sc-share-err' }, note) : null,
2320
+ ),
2321
+ )
2322
+ }
2323
+
2324
+ return h(
2325
+ 'div',
2326
+ { className: 'sc-share' },
2327
+ h(
2328
+ 'div',
2329
+ { className: 'sc-share-row' },
2330
+ h('span', { className: 'sc-share-note' }, broke ? '没读到会话内容' : blocks.length + ' 段'),
2331
+ friends.length
2332
+ ? h(
2333
+ 'select',
2334
+ {
2335
+ className: 'sc-input',
2336
+ style: { height: '28px', width: 'auto', padding: '0 10px' },
2337
+ value: target,
2338
+ onChange: (e) => setTarget(e.target.value),
2339
+ },
2340
+ friends.map((f) => h('option', { key: f.id, value: f.id }, f.displayName || f.id)),
2341
+ )
2342
+ : null,
2343
+ h(
2344
+ 'button',
2345
+ {
2346
+ className: 'sc-btn sc-btn-primary sc-btn-sm',
2347
+ disabled: busy || broke || !target,
2348
+ onClick: send,
2349
+ },
2350
+ busy ? '发送中' : '发送',
2351
+ ),
2352
+ h('button', { className: 'sc-btn sc-btn-sm sc-btn-ghost', onClick: () => setOpen(false) }, '取消'),
2353
+ note ? h('span', { className: 'sc-share-err' }, note) : null,
2354
+ ),
2355
+ broke
2356
+ ? h(
2357
+ 'pre',
2358
+ {
2359
+ style: {
2360
+ margin: '8px 0 0',
2361
+ fontSize: '10px',
2362
+ lineHeight: 1.45,
2363
+ maxHeight: '180px',
2364
+ overflow: 'auto',
2365
+ opacity: 0.7,
2366
+ whiteSpace: 'pre-wrap',
2367
+ wordBreak: 'break-all',
2368
+ },
2369
+ },
2370
+ diagnose(chat),
2371
+ )
2372
+ : h(
2373
+ 'div',
2374
+ { className: 'sc-preview' },
2375
+ h('div', { className: 'sc-preview-cap' }, '预览 · 发送前扫一眼,别把不该发的带出去'),
2376
+ blocks.slice(0, 12).map((b, i) =>
2377
+ h(
2378
+ 'div',
2379
+ { key: i, className: 'sc-preview-line' + (b.t === 'tool' ? ' tool' : '') },
2380
+ '[' + b.t + '] ' + (b.name ? b.name + ' ' : '') + String(b.text || '').slice(0, 160),
2381
+ ),
2382
+ ),
2383
+ ),
2384
+ )
2385
+ }
2386
+
2387
+ // ───────────── 全局面板(左侧栏常驻入口,不依赖会话)─────────────
2388
+
2389
+ const PANEL_ID = 'dsh-share-chat'
2390
+
2391
+ /** 左侧栏图标:用 currentColor,跟着主题走 */
2392
+ function SocialIcon() {
2393
+ return h(
2394
+ 'svg',
2395
+ {
2396
+ viewBox: '0 0 24 24',
2397
+ width: 18,
2398
+ height: 18,
2399
+ 'aria-hidden': true,
2400
+ style: { display: 'block' },
2401
+ },
2402
+ h('path', {
2403
+ d: 'M4.2 5h15.6A1.7 1.7 0 0 1 21.5 6.7v9.1a1.7 1.7 0 0 1-1.7 1.7h-8.1l-3.9 3v-3H4.2a1.7 1.7 0 0 1-1.7-1.7V6.7A1.7 1.7 0 0 1 4.2 5Z',
2404
+ fill: 'none',
2405
+ stroke: 'currentColor',
2406
+ strokeWidth: 1.6,
2407
+ strokeLinejoin: 'round',
2408
+ }),
2409
+ h('circle', { cx: 8.6, cy: 11.2, r: 1.15, fill: 'currentColor' }),
2410
+ h('circle', { cx: 12, cy: 11.2, r: 1.15, fill: 'currentColor' }),
2411
+ h('circle', { cx: 15.4, cy: 11.2, r: 1.15, fill: 'currentColor' }),
2412
+ )
2413
+ }
2414
+
2415
+ /** 主区域的整页版本:给标题栏让出 top clearance */
2416
+ function SocialPanel() {
2417
+ return h(
2418
+ 'div',
2419
+ {
2420
+ style: {
2421
+ height: '100%',
2422
+ width: '100%',
2423
+ minHeight: 0,
2424
+ minWidth: 0,
2425
+ display: 'flex',
2426
+ flexDirection: 'column',
2427
+ paddingTop: 'var(--dsh-frame-top-clearance, 0px)',
2428
+ boxSizing: 'border-box',
2429
+ overflow: 'hidden',
2430
+ },
2431
+ },
2432
+ h(SocialView),
2433
+ )
2434
+ }
2435
+
2436
+ return {
2437
+ inject: ['slots'],
2438
+ apply(ctx) {
2439
+ // 样式表:跟着插件生命周期建立/移除
2440
+ ctx.effect(() => {
2441
+ ensureStyles()
2442
+ return () => {
2443
+ const el = typeof document !== 'undefined' ? document.getElementById(STYLE_ID) : null
2444
+ if (el && el.parentNode) el.parentNode.removeChild(el)
2445
+ }
2446
+ })
2447
+
2448
+ // 1) 会话里的 View:保留,顺手能在某个会话里看一眼
2449
+ ctx.slots.inject('conversation.view', () =>
2450
+ ctx.slots.register(
2451
+ {
2452
+ name: 'conversation.view',
2453
+ id: 'dsh-share-chat',
2454
+ order: 40,
2455
+ label: '社交',
2456
+ },
2457
+ SocialView,
2458
+ ),
2459
+ )
2460
+
2461
+ // 2) 左侧栏常驻入口
2462
+ ctx.slots.inject('sidebar.panellist', () =>
2463
+ ctx.slots.register(
2464
+ {
2465
+ name: 'sidebar.panellist',
2466
+ id: PANEL_ID,
2467
+ order: 20,
2468
+ label: () => '社交',
2469
+ },
2470
+ SocialIcon,
2471
+ ),
2472
+ )
2473
+
2474
+ // 3) 全局面板:和侧栏入口同一个 id,点入口就切到这个面板
2475
+ ctx.slots.inject('main', () =>
2476
+ ctx.slots.register(
2477
+ {
2478
+ name: 'main',
2479
+ key: PANEL_ID,
2480
+ },
2481
+ SocialPanel,
2482
+ ),
2483
+ )
2484
+
2485
+ // 4) 设置 → 社交小游戏:改「🎮 摸鱼」窗口的默认大小
2486
+ ctx.slots.inject('settings.section', () =>
2487
+ ctx.slots.register(
2488
+ {
2489
+ name: 'settings.section',
2490
+ id: 'share-chat-game',
2491
+ order: 60,
2492
+ label: () => '社交小游戏',
2493
+ },
2494
+ GameSettingsSection,
2495
+ ),
2496
+ )
2497
+ },
2498
+ }
2499
+ },
2500
+ })