dsh-share-chat 0.9.0 → 0.29.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 CHANGED
@@ -35,6 +35,19 @@ window.__ModuleLoader__.load({
35
35
 
36
36
  // ───────────────────────── 存取 ─────────────────────────
37
37
 
38
+ /** 每个会话各自的聊天背景,存在本地 */
39
+ const BG_KEY = 'dsh-share-chat.bg'
40
+ const BG_COLORS = ['#f7f3ea', '#eaf2fb', '#f0f7ee', '#fdf0f3', '#f3f0fb', '#fff8e6', '#eef6f7', '#f4f4f5']
41
+ const BG_GRADS = [
42
+ 'linear-gradient(160deg,#e8f3ff,#f8fcff)',
43
+ 'linear-gradient(160deg,#fff1e6,#fff9f4)',
44
+ 'linear-gradient(160deg,#eaf7ee,#f7fdf9)',
45
+ 'linear-gradient(160deg,#f3ecff,#fbf8ff)',
46
+ ]
47
+
48
+ /** 记住上次打开的会话,下次进来自动落在那儿 */
49
+ const LAST_CONV_KEY = 'dsh-share-chat.lastConv'
50
+
38
51
  function readJson(key) {
39
52
  try {
40
53
  return JSON.parse(window.localStorage.getItem(key) || 'null')
@@ -292,8 +305,8 @@ window.__ModuleLoader__.load({
292
305
  .sc-foot{color:var(--dsw-alias-label-tertiary,#8b949e);font-size:11.5px;margin-top:14px;line-height:1.6}
293
306
 
294
307
  /* 聊天外壳 */
295
- .sc-chat{flex:1;min-height:0;display:flex;flex-direction:column}
296
- .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}
308
+ .sc-chat{flex:1;min-height:0;display:flex;flex-direction:column;position:relative}
309
+ .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;position:absolute;top:0;left:0;right:0;z-index:6;background:var(--dsw-alias-bg-l1,Canvas)}
297
310
  .sc-chat-name{font-size:13.5px;font-weight:600;line-height:1.2}
298
311
  .sc-chat-sub{font-size:11.5px;color:var(--dsw-alias-label-tertiary,#8b949e);line-height:1.3}
299
312
  .sc-chat-body{flex:1;min-height:0;display:flex}
@@ -315,6 +328,10 @@ window.__ModuleLoader__.load({
315
328
  .sc-thread-inner{max-width:760px;margin:0 auto;display:flex;flex-direction:column;gap:10px}
316
329
  .sc-msg{display:flex;flex-direction:column;align-items:flex-start;gap:3px;max-width:100%}
317
330
  .sc-msg.mine{align-items:flex-end}
331
+ .sc-msg-row{display:flex;gap:8px;align-items:flex-start;max-width:100%}
332
+ .sc-msg-row.mine{flex-direction:row-reverse}
333
+ .sc-msg-row>.sc-avatar{margin-top:2px}
334
+ .sc-msg-row .sc-msg{flex:1 1 auto;min-width:0;max-width:none}
318
335
  .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}
319
336
  .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}
320
337
  .sc-time{font-size:10.5px;color:var(--dsw-alias-label-quaternary,#a0a8b0);padding:0 4px}
@@ -334,7 +351,7 @@ window.__ModuleLoader__.load({
334
351
  .sc-empty-hint{font-size:11.5px;opacity:.8}
335
352
 
336
353
  /* 输入区 */
337
- .sc-composer{flex:0 0 auto;border-top:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.20));padding:10px 14px 12px}
354
+ .sc-composer{position:absolute;left:0;right:0;bottom:0;z-index:6;flex:0 0 auto;border-top:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.20));padding:10px 14px 12px;background:var(--dsw-alias-bg-l1,Canvas)}
338
355
  .sc-composer-inner{max-width:760px;margin:0 auto;display:flex;flex-direction:column;gap:8px}
339
356
  .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)}
340
357
  .sc-emoji button{border:0;background:transparent;font-size:17px;line-height:1;padding:4px 5px;border-radius:7px;cursor:pointer}
@@ -454,15 +471,81 @@ window.__ModuleLoader__.load({
454
471
  .sc-login{padding:12px}
455
472
  .sc-login-card{padding:20px 16px 16px;border-radius:16px}
456
473
  }
474
+ `
475
+
476
+ /** 多巴胺主题:叠在基础样式之后,只改观感不动布局 */
477
+ const DOPAMINE_CSS = `
478
+ .sc-root{
479
+ --dopa-pink:#ff5fa2; --dopa-pink-soft:#ffe3ef; --dopa-violet:#a86bff;
480
+ --dopa-blue:#4d9fff; --dopa-mint:#3ddc97; --dopa-yellow:#ffcf3d; --dopa-ink:#3b2b45;
481
+ background:linear-gradient(180deg,#fff8fc 0%,#f7faff 100%);
482
+ }
483
+ /* 顶栏 */
484
+ .sc-chat-head{background:linear-gradient(96deg,#ffeaf4 0%,#fff7e8 45%,#eaf4ff 100%);border-bottom:2px solid #ffd9ec;box-shadow:0 4px 14px rgba(255,120,180,.10)}
485
+ .sc-chat-name{color:#4a2b52}
486
+ .sc-chat-sub{color:#a184b3}
487
+ /* 按钮 */
488
+ .sc-btn{border-radius:12px;border:1.5px solid #ffd3e6;background:#fff;font-weight:650;color:#5b3a63;transition:background .15s,border-color .15s,transform .1s}
489
+ .sc-btn:hover{background:#fff2f9;border-color:#ff9ec4}
490
+ .sc-btn:active{transform:scale(.97)}
491
+ .sc-btn-ghost{border-color:#e8e2f0;background:transparent;color:#8a7a95}
492
+ .sc-btn-primary{background:linear-gradient(135deg,#ff5fa2,#a86bff);color:#fff;border-color:transparent;box-shadow:0 6px 16px rgba(255,95,162,.30)}
493
+ .sc-btn-primary:hover{background:linear-gradient(135deg,#ff4b96,#9a58ff);border-color:transparent}
494
+ /* 侧栏 */
495
+ .sc-side{background:linear-gradient(180deg,#fff5fa 0%,#f4f9ff 100%);border-right:2px solid #ffe3f0}
496
+ .sc-contacts{display:flex;flex-direction:column;flex:1;min-height:0;overflow:hidden}
497
+ .sc-side-title{color:#b14a86;letter-spacing:.6px}
498
+ .sc-add .sc-input{border:1.5px solid #ffd3e6;border-radius:12px;background:#fff}
499
+ .sc-add .sc-input:focus{border-color:#ff9ec4;box-shadow:0 0 0 3px rgba(255,158,196,.25);outline:none}
500
+ .sc-friend{border-radius:14px;transition:background .15s,box-shadow .15s}
501
+ .sc-friend:hover{background:#fff6fb}
502
+ .sc-friend.on{background:linear-gradient(135deg,#ffe3f0,#e0f0ff);box-shadow:inset 0 0 0 2px #ffb3d4,0 6px 14px rgba(255,120,180,.16)}
503
+ .sc-friend-name{color:#4a2b52;font-weight:650}
504
+ .sc-friend-last{color:#a184b3}
505
+ /* 消息 */
506
+ .sc-thread{background:transparent}
507
+ .sc-bubble{background:#fff;border:1.5px solid #ffdcea;box-shadow:0 3px 10px rgba(168,107,255,.10)}
508
+ .sc-msg.mine .sc-bubble{background:linear-gradient(135deg,#ff5fa2,#a86bff);border-color:transparent;color:#fff;box-shadow:0 8px 20px rgba(255,95,162,.28)}
509
+ .sc-time{color:#a78bb5}
510
+ .sc-avatar{box-shadow:0 0 0 2px #fff,0 2px 8px rgba(60,40,80,.16)}
511
+ /* 文件卡片 */
512
+ .sc-file{background:linear-gradient(135deg,#f3f8ff,#fff4fb);border:1.5px solid #d6e6ff;border-radius:14px;transition:box-shadow .15s,transform .1s}
513
+ .sc-file:hover{box-shadow:0 6px 18px rgba(77,159,255,.20);transform:translateY(-1px)}
514
+ .sc-file-name{color:#2f4a6b;font-weight:600}
515
+ .sc-file-size{color:#8fa6bf}
516
+ /* 输入区 */
517
+ .sc-composer{background:linear-gradient(180deg,#ffffff,#fff8fc);border-top:2px solid #ffd9ec;box-shadow:0 -4px 14px rgba(255,120,180,.08)}
518
+ .sc-composer input,.sc-composer textarea{border:1.5px solid #ffd3e6;border-radius:16px;background:#fff;outline:none}
519
+ .sc-composer input:focus,.sc-composer textarea:focus{border-color:#ff9ec4;box-shadow:0 0 0 3px rgba(255,158,196,.22)}
520
+ .sc-emoji{border:1.5px solid #ffd3e6;border-radius:16px;background:#fff}
521
+ /* 空状态 / 报错 */
522
+ .sc-err{background:#fff0f5;border-radius:10px;padding:2px 8px}
523
+ /* 滚动条 */
524
+ .sc-thread::-webkit-scrollbar,.sc-friends::-webkit-scrollbar,.sc-side::-webkit-scrollbar{width:9px}
525
+ .sc-thread::-webkit-scrollbar-thumb,.sc-friends::-webkit-scrollbar-thumb,.sc-side::-webkit-scrollbar-thumb{background:#ffd0e6;border-radius:9px;border:2px solid transparent;background-clip:content-box}
526
+ .sc-thread::-webkit-scrollbar-thumb:hover{background:#ffb3d4;background-clip:content-box}
527
+ .sc-thread::-webkit-scrollbar-track,.sc-friends::-webkit-scrollbar-track{background:transparent}
528
+ /* 登录卡片 */
529
+ .sc-login-card{border:2px solid #ffe0ee;border-radius:24px;box-shadow:0 22px 60px rgba(255,120,180,.18)}
530
+ .sc-logo{background:linear-gradient(135deg,#ffd6e8,#e6f0ff);border-radius:16px}
531
+ .sc-login-title{color:#4a2b52}
457
532
  `
458
533
 
459
534
  function ensureStyles() {
460
535
  if (typeof document === 'undefined') return
461
- if (document.getElementById(STYLE_ID)) return
462
- const el = document.createElement('style')
463
- el.id = STYLE_ID
464
- el.textContent = CSS
465
- document.head.appendChild(el)
536
+ if (!document.getElementById(STYLE_ID)) {
537
+ const el = document.createElement('style')
538
+ el.id = STYLE_ID
539
+ el.textContent = CSS
540
+ document.head.appendChild(el)
541
+ }
542
+ const dopaId = STYLE_ID + '-dopa'
543
+ if (!document.getElementById(dopaId)) {
544
+ const t = document.createElement('style')
545
+ t.id = dopaId
546
+ t.textContent = DOPAMINE_CSS
547
+ document.head.appendChild(t)
548
+ }
466
549
  }
467
550
 
468
551
  const LINE = '1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.22))'
@@ -474,9 +557,24 @@ window.__ModuleLoader__.load({
474
557
  return x
475
558
  }
476
559
 
477
- function avatar(name, id, size) {
560
+ /** 当前 relay 地址,头像 URL 要拼它(插件页面和 relay 不同源) */
561
+ let avatarBase = ''
562
+
563
+ function avatar(name, id, size, avatarId, isGroup) {
478
564
  const sz = size || 30
565
+ if (avatarId) {
566
+ return h('img', {
567
+ className: 'sc-avatar',
568
+ src: avatarBase + '/f/' + avatarId,
569
+ alt: String(name || id || ''),
570
+ loading: 'lazy',
571
+ style: { width: sz + 'px', height: sz + 'px', objectFit: 'cover', display: 'block' },
572
+ })
573
+ }
479
574
  const hue = hueOf(id || name)
575
+ const initial = isGroup
576
+ ? '👥'
577
+ : String(name || id || '?').trim().charAt(0).toUpperCase()
480
578
  return h(
481
579
  'span',
482
580
  {
@@ -493,7 +591,7 @@ window.__ModuleLoader__.load({
493
591
  ' 58% 44%))',
494
592
  },
495
593
  },
496
- String(name || id || '?').trim().charAt(0).toUpperCase(),
594
+ initial,
497
595
  )
498
596
  }
499
597
 
@@ -757,30 +855,60 @@ window.__ModuleLoader__.load({
757
855
  function ChatPanel(props) {
758
856
  const auth = props.auth
759
857
  const [friends, setFriends] = useState([])
760
- const [active, setActive] = useState(null)
858
+ const [active, setActive] = useState(() => readJson(LAST_CONV_KEY) || null)
761
859
  const [messages, setMessages] = useState([])
762
860
  const [draft, setDraft] = useState('')
763
861
  const [newFriend, setNewFriend] = useState('')
764
862
  const [err, setErr] = useState('')
765
863
  const [sending, setSending] = useState(false)
766
864
  const [uploading, setUploading] = useState(false)
865
+ // 正在上传的附件:先占一个气泡,成功就撤掉(真消息由 pull 补上),失败就留在原地标红
866
+ const [pending, setPending] = useState([])
767
867
  const [emojiOpen, setEmojiOpen] = useState(false)
768
868
  const [campMode, setCampMode] = useState(false)
869
+ avatarBase = auth.server
870
+ const [groups, setGroups] = useState([])
871
+ const [hiddenChats, setHiddenChats] = useState([])
872
+ const [sideTab, setSideTab] = useState('chats')
873
+ const [myAvatar, setMyAvatar] = useState('')
874
+ // Electron 里 window.prompt 不可用,所有需要输入的地方都走这个内联框
875
+ const [inline, setInline] = useState(null)
876
+ const [askMode, setAskMode] = useState(() => readJson('dsh-share-chat.ask') === true)
877
+ useEffect(() => {
878
+ writeJson('dsh-share-chat.ask', askMode)
879
+ }, [askMode])
880
+ const [bgMap, setBgMap] = useState(() => readJson(BG_KEY) || {})
881
+ const [bgOpen, setBgOpen] = useState(false)
769
882
 
770
883
  const cursorRef = useRef(0)
771
884
  const listRef = useRef(null)
885
+ const headRef = useRef(null)
886
+ const composerRef = useRef(null)
887
+ const chatRef = useRef(null)
772
888
  const activeRef = useRef(null)
773
889
  const friendsKeyRef = useRef('')
774
890
  const fileRef = useRef(null)
775
891
 
776
892
  useEffect(() => {
777
893
  activeRef.current = active
894
+ if (active) writeJson(LAST_CONV_KEY, active)
778
895
  }, [active])
779
896
 
780
897
  const loadFriends = useCallback(async () => {
781
898
  try {
782
899
  const r = await api(auth.server, '/api/friends', { token: auth.token })
783
900
  setFriends(r.friends || [])
901
+ setGroups(r.groups || [])
902
+ setHiddenChats(Array.isArray(r.hidden) ? r.hidden : [])
903
+ // 上次那个会话没了(退群/删好友)就退回第一个
904
+ const keys = (r.friends || []).map((f) => f.id)
905
+ for (const g of r.groups || []) keys.push('g:' + g.id)
906
+ const cur = activeRef.current
907
+ if (cur && keys.indexOf(cur) < 0) {
908
+ setActive(keys[0] || null)
909
+ } else if (!cur && keys.length) {
910
+ setActive(keys[0])
911
+ }
784
912
  return r.friends || []
785
913
  } catch (e) {
786
914
  setErr(friendly(e))
@@ -793,6 +921,22 @@ window.__ModuleLoader__.load({
793
921
  loadFriends().then((list) => {
794
922
  if (alive && list.length && !active) setActive(list[0].id)
795
923
  })
924
+ api(auth.server, '/api/me', { token: auth.token })
925
+ .then((me) => {
926
+ if (alive && me && me.avatar) setMyAvatar(me.avatar)
927
+ })
928
+ .catch(() => {})
929
+ // 背景以服务端为准(跨设备),本地只是缓存
930
+ api(auth.server, '/api/bg', { token: auth.token })
931
+ .then((r) => {
932
+ if (!alive || !r || !r.bgs) return
933
+ setBgMap((prev) => {
934
+ const merged = Object.assign({}, prev, r.bgs)
935
+ writeJson(BG_KEY, merged)
936
+ return merged
937
+ })
938
+ })
939
+ .catch(() => {})
796
940
  return () => {
797
941
  alive = false
798
942
  }
@@ -830,10 +974,17 @@ window.__ModuleLoader__.load({
830
974
  const f = await api(auth.server, '/api/friends', { token: auth.token })
831
975
  if (!alive) return
832
976
  const list = f.friends || []
833
- const key = list.map((x) => x.id + ':' + (x.displayName || '')).join('|')
977
+ const glist = f.groups || []
978
+ const key =
979
+ list.map((x) => x.id + ':' + (x.displayName || '') + ':' + (x.avatar || '')).join('|') +
980
+ '§' +
981
+ glist
982
+ .map((g) => g.id + ':' + g.name + ':' + (g.avatar || '') + ':' + (g.members || []).length)
983
+ .join('|')
834
984
  if (key !== friendsKeyRef.current) {
835
985
  friendsKeyRef.current = key
836
986
  setFriends(list)
987
+ setGroups(glist)
837
988
  if (!activeRef.current && list.length) setActive(list[0].id)
838
989
  }
839
990
  } catch (e) {
@@ -848,11 +999,144 @@ window.__ModuleLoader__.load({
848
999
  }
849
1000
  }, [auth.server, auth.token])
850
1001
 
851
- // 新消息贴底
1002
+ // 新消息贴底;切回社交面板时列表可能是隐藏的(高度 0),
1003
+ // 所以除了立即贴底,还要在布局稳定后和高度变化时再贴一次
852
1004
  useEffect(() => {
853
1005
  const el = listRef.current
854
- if (el) el.scrollTop = el.scrollHeight
855
- }, [messages, active])
1006
+ if (!el) return
1007
+ const toBottom = () => {
1008
+ el.scrollTop = el.scrollHeight
1009
+ }
1010
+ toBottom()
1011
+ const t1 = window.setTimeout(toBottom, 50)
1012
+ const t2 = window.setTimeout(toBottom, 260)
1013
+ let ro = null
1014
+ if (typeof ResizeObserver !== 'undefined') {
1015
+ ro = new ResizeObserver(() => {
1016
+ if (el.scrollHeight > el.clientHeight) toBottom()
1017
+ })
1018
+ ro.observe(el)
1019
+ }
1020
+ return () => {
1021
+ window.clearTimeout(t1)
1022
+ window.clearTimeout(t2)
1023
+ if (ro) ro.disconnect()
1024
+ }
1025
+ }, [active, messages.length])
1026
+
1027
+ // 顶栏和输入框是绝对定位钉住的;给整个主体让出位置,
1028
+ // 这样侧栏顶部那排(对方 ID / 添加 / 建群)不会被顶栏盖住
1029
+ useEffect(() => {
1030
+ const measure = () => {
1031
+ const chat = chatRef.current
1032
+ const head = headRef.current
1033
+ const comp = composerRef.current
1034
+ if (chat) {
1035
+ chat.style.paddingTop = (head ? head.offsetHeight : 0) + 'px'
1036
+ chat.style.paddingBottom = (comp ? comp.offsetHeight : 0) + 'px'
1037
+ }
1038
+ }
1039
+ measure()
1040
+ const timers = [80, 350].map((d) => window.setTimeout(measure, d))
1041
+ window.addEventListener('resize', measure)
1042
+ let ro = null
1043
+ if (typeof ResizeObserver !== 'undefined') {
1044
+ ro = new ResizeObserver(() => measure())
1045
+ if (headRef.current) ro.observe(headRef.current)
1046
+ if (composerRef.current) ro.observe(composerRef.current)
1047
+ }
1048
+ return () => {
1049
+ for (const t of timers) window.clearTimeout(t)
1050
+ window.removeEventListener('resize', measure)
1051
+ if (ro) ro.disconnect()
1052
+ }
1053
+ }, [active])
1054
+
1055
+ /** 右键菜单:打开 / 不显示该聊天 / 恢复显示 */
1056
+ const showConvMenu = (x, y, conv) => {
1057
+ const old = document.getElementById('dsh-conv-menu')
1058
+ if (old) old.remove()
1059
+ const menu = document.createElement('div')
1060
+ menu.id = 'dsh-conv-menu'
1061
+ menu.style.cssText = [
1062
+ 'position:fixed',
1063
+ 'left:' + Math.min(x, window.innerWidth - 170) + 'px',
1064
+ 'top:' + Math.min(y, window.innerHeight - 90) + 'px',
1065
+ 'z-index:2147483647',
1066
+ 'min-width:150px',
1067
+ 'padding:6px',
1068
+ 'border-radius:10px',
1069
+ 'background:rgba(28,30,34,.96)',
1070
+ 'border:1px solid rgba(255,255,255,.14)',
1071
+ 'box-shadow:0 14px 34px rgba(0,0,0,.35)',
1072
+ 'display:flex',
1073
+ 'flex-direction:column',
1074
+ 'gap:2px',
1075
+ ].join(';')
1076
+
1077
+ let closed = false
1078
+ const close = () => {
1079
+ if (closed) return
1080
+ closed = true
1081
+ menu.remove()
1082
+ document.removeEventListener('mousedown', onDown, true)
1083
+ }
1084
+ // 点菜单外面才关;点菜单里的项交给按钮自己处理
1085
+ const onDown = (ev) => {
1086
+ if (!menu.contains(ev.target)) close()
1087
+ }
1088
+
1089
+ const mk = (label, fn, danger) => {
1090
+ const b = document.createElement('button')
1091
+ b.textContent = label
1092
+ b.style.cssText =
1093
+ 'text-align:left;padding:7px 10px;border-radius:7px;border:none;background:transparent;color:' +
1094
+ (danger ? '#ffb4c8' : '#e8eaed') +
1095
+ ';font:13px system-ui;cursor:pointer'
1096
+ b.addEventListener('mouseenter', () => (b.style.background = 'rgba(255,255,255,.1)'))
1097
+ b.addEventListener('mouseleave', () => (b.style.background = 'transparent'))
1098
+ b.addEventListener('click', () => {
1099
+ close()
1100
+ fn()
1101
+ })
1102
+ return b
1103
+ }
1104
+
1105
+ menu.appendChild(
1106
+ mk('打开聊天', () => {
1107
+ setSideTab('chats')
1108
+ setActive(conv.key)
1109
+ if (conv.hidden) hideChat(conv.key, false)
1110
+ }),
1111
+ )
1112
+ if (conv.hidden) {
1113
+ menu.appendChild(mk('恢复显示该聊天', () => hideChat(conv.key, false)))
1114
+ } else {
1115
+ menu.appendChild(mk('不显示该聊天', () => hideChat(conv.key, true), true))
1116
+ }
1117
+ document.body.appendChild(menu)
1118
+ setTimeout(() => {
1119
+ if (!closed) document.addEventListener('mousedown', onDown, true)
1120
+ }, 0)
1121
+ }
1122
+
1123
+ /** 不显示 / 恢复某个会话(只影响列表,好友关系不动) */
1124
+ const hideChat = async (key, hidden) => {
1125
+ try {
1126
+ // 先本地生效,界面立刻反应;失败再回滚
1127
+ if (hidden) setHiddenChats((prev) => (prev.indexOf(key) >= 0 ? prev : prev.concat(key)))
1128
+ else setHiddenChats((prev) => prev.filter((x) => x !== key))
1129
+ if (hidden && activeRef.current === key) setActive(null)
1130
+ const r = await api(auth.server, '/api/hidden', {
1131
+ method: 'POST',
1132
+ token: auth.token,
1133
+ body: { key, hidden },
1134
+ })
1135
+ setHiddenChats(Array.isArray(r.hidden) ? r.hidden : [])
1136
+ } catch (e) {
1137
+ setErr(friendly(e))
1138
+ }
1139
+ }
856
1140
 
857
1141
  const addFriend = async () => {
858
1142
  const target = newFriend.trim()
@@ -878,10 +1162,25 @@ window.__ModuleLoader__.load({
878
1162
  setSending(true)
879
1163
  setErr('')
880
1164
  try {
1165
+ let out = text
1166
+ if (askMode) {
1167
+ // 先用 DSH 的模型回答,再把回答发给对方
1168
+ const res = await fetch('/api/share-chat/ask', {
1169
+ method: 'POST',
1170
+ headers: { 'content-type': 'application/json' },
1171
+ body: JSON.stringify({ prompt: text }),
1172
+ })
1173
+ const j = await res.json().catch(() => null)
1174
+ if (!res.ok || !j || !j.text) {
1175
+ setErr('模型没答上来:' + ((j && (j.detail || j.error)) || res.status))
1176
+ return
1177
+ }
1178
+ out = j.text
1179
+ }
881
1180
  await api(auth.server, '/api/messages', {
882
1181
  method: 'POST',
883
1182
  token: auth.token,
884
- body: { to: active, text },
1183
+ body: { to: active, text: out },
885
1184
  })
886
1185
  setDraft('')
887
1186
  await pull()
@@ -895,6 +1194,19 @@ window.__ModuleLoader__.load({
895
1194
  /** 选中的文件:先上传,再发一条 image / file 消息 */
896
1195
  const uploadAndSend = async (file) => {
897
1196
  if (!active || !file) return
1197
+ const pid = 'p' + Date.now() + Math.random().toString(36).slice(2, 6)
1198
+ const mark = (patch) =>
1199
+ setPending((prev) => prev.map((x) => (x.id === pid ? Object.assign({}, x, patch) : x)))
1200
+ setPending((prev) =>
1201
+ prev.concat({
1202
+ id: pid,
1203
+ name: file.name || '附件',
1204
+ type: file.type || '',
1205
+ size: file.size || 0,
1206
+ status: 'uploading',
1207
+ error: '',
1208
+ }),
1209
+ )
898
1210
  setUploading(true)
899
1211
  setErr('')
900
1212
  try {
@@ -914,8 +1226,10 @@ window.__ModuleLoader__.load({
914
1226
  } catch (e) {
915
1227
  /* 非 JSON */
916
1228
  }
917
- if (!res.ok) {
918
- setErr(up && up.error === 'too-large' ? '文件太大(服务器上限 50 MB)' : '上传失败')
1229
+ if (!res.ok || !up) {
1230
+ const why = up && up.error === 'too-large' ? '文件太大(服务器上限 50 MB)' : '上传失败'
1231
+ mark({ status: 'failed', error: why })
1232
+ setErr(why + ':' + (file.name || ''))
919
1233
  return
920
1234
  }
921
1235
  const isImage = String(file.type || '').startsWith('image/')
@@ -924,8 +1238,10 @@ window.__ModuleLoader__.load({
924
1238
  token: auth.token,
925
1239
  body: isImage ? { to: active, image: { uploadId: up.id } } : { to: active, file: { uploadId: up.id } },
926
1240
  })
1241
+ setPending((prev) => prev.filter((x) => x.id !== pid))
927
1242
  await pull()
928
1243
  } catch (e) {
1244
+ mark({ status: 'failed', error: friendly(e) })
929
1245
  setErr(friendly(e))
930
1246
  } finally {
931
1247
  setUploading(false)
@@ -940,6 +1256,178 @@ window.__ModuleLoader__.load({
940
1256
  }
941
1257
 
942
1258
  /* 好友列表里的「最后一条」摘要 */
1259
+ /* ---------- 聊天背景(按会话,存本地) ---------- */
1260
+ const bgOf = (key) => (key && bgMap[key]) || null
1261
+ const setBgFor = (key, bg) => {
1262
+ if (!key) return
1263
+ setBgMap((prev) => {
1264
+ const next = Object.assign({}, prev)
1265
+ if (bg) next[key] = bg
1266
+ else delete next[key]
1267
+ writeJson(BG_KEY, next)
1268
+ return next
1269
+ })
1270
+ // 同步到账号上,换设备也跟着走
1271
+ api(auth.server, '/api/bg', {
1272
+ method: 'POST',
1273
+ token: auth.token,
1274
+ body: { key, bg: bg || null },
1275
+ }).catch(() => setErr('背景同步失败,仅本机生效'))
1276
+ }
1277
+ const bgStyle = (bg) => {
1278
+ if (!bg) return {}
1279
+ if (bg.type === 'color') return { background: bg.v }
1280
+ if (bg.type === 'grad') return { backgroundImage: bg.v }
1281
+ if (bg.type === 'image') {
1282
+ return {
1283
+ backgroundImage: 'url(' + auth.server + bg.v + ')',
1284
+ backgroundSize: 'cover',
1285
+ backgroundPosition: 'center',
1286
+ }
1287
+ }
1288
+ return {}
1289
+ }
1290
+ /** 侧栏卡片:背景铺满 + 左侧白色蒙版,保证名字和摘要读得清 */
1291
+ const cardStyle = (bg, isActive) => {
1292
+ const active = isActive
1293
+ ? { boxShadow: 'inset 0 0 0 2px var(--dsw-alias-brand-primary,#5aa9e6)' }
1294
+ : {}
1295
+ if (!bg) return active
1296
+ const layer =
1297
+ bg.type === 'color'
1298
+ ? 'linear-gradient(' + bg.v + ',' + bg.v + ')'
1299
+ : bg.type === 'grad'
1300
+ ? bg.v
1301
+ : 'url(' + auth.server + bg.v + ')'
1302
+ return Object.assign(
1303
+ {
1304
+ backgroundImage:
1305
+ 'linear-gradient(90deg, rgba(255,255,255,.78), rgba(255,255,255,.28))' + ',' + layer,
1306
+ backgroundSize: 'cover',
1307
+ backgroundPosition: 'center',
1308
+ overflow: 'hidden',
1309
+ },
1310
+ active,
1311
+ )
1312
+ }
1313
+
1314
+ const bgThumb = (bg, size) => {
1315
+ if (!bg) return null
1316
+ const s = size || 18
1317
+ const st = {
1318
+ width: s + 'px',
1319
+ height: s + 'px',
1320
+ borderRadius: '5px',
1321
+ flex: '0 0 auto',
1322
+ border: '1px solid rgba(128,128,128,.35)',
1323
+ display: 'block',
1324
+ }
1325
+ if (bg.type === 'color') st.background = bg.v
1326
+ else if (bg.type === 'grad') st.backgroundImage = bg.v
1327
+ else if (bg.type === 'image') {
1328
+ st.backgroundImage = 'url(' + auth.server + bg.v + ')'
1329
+ st.backgroundSize = 'cover'
1330
+ st.backgroundPosition = 'center'
1331
+ }
1332
+ return h('span', { style: st, title: '聊天背景' })
1333
+ }
1334
+ const uploadBg = (file) => {
1335
+ if (!file || !active) return
1336
+ const key = active
1337
+ file
1338
+ .arrayBuffer()
1339
+ .then((buf) =>
1340
+ fetch(auth.server + '/api/upload', {
1341
+ method: 'POST',
1342
+ headers: {
1343
+ authorization: 'Bearer ' + auth.token,
1344
+ 'content-type': file.type || 'application/octet-stream',
1345
+ 'x-filename': encodeURIComponent(file.name || 'bg'),
1346
+ },
1347
+ body: buf,
1348
+ }),
1349
+ )
1350
+ .then((r) => r.json())
1351
+ .then((up) => {
1352
+ if (up && up.id) {
1353
+ setBgFor(key, { type: 'image', v: '/f/' + up.id })
1354
+ setBgOpen(false)
1355
+ } else {
1356
+ setErr('背景上传失败')
1357
+ }
1358
+ })
1359
+ .catch(() => setErr('背景上传失败'))
1360
+ }
1361
+
1362
+ /** 建群 / 拉人共用同一个内联输入框(Electron 没有 window.prompt) */
1363
+ const submitInline = async () => {
1364
+ const it = inline
1365
+ if (!it) return
1366
+ const v = String(it.value || '').trim()
1367
+ if (!v) return
1368
+ setErr('')
1369
+ try {
1370
+ if (it.mode === 'group') {
1371
+ const r = await api(auth.server, '/api/groups', {
1372
+ method: 'POST',
1373
+ token: auth.token,
1374
+ body: { name: v },
1375
+ })
1376
+ await loadFriends()
1377
+ setActive('g:' + r.group.id)
1378
+ cursorRef.current = 0
1379
+ setMessages([])
1380
+ } else if (it.mode === 'member') {
1381
+ if (!active || active.indexOf('g:') !== 0) return
1382
+ await api(auth.server, '/api/groups/' + active.slice(2) + '/members', {
1383
+ method: 'POST',
1384
+ token: auth.token,
1385
+ body: { id: v },
1386
+ })
1387
+ await loadFriends()
1388
+ }
1389
+ setInline(null)
1390
+ } catch (e) {
1391
+ setErr(friendly(e))
1392
+ }
1393
+ }
1394
+
1395
+ const avatarInputRef = useRef(null)
1396
+ const uploadAvatar = async (file) => {
1397
+ if (!file) return
1398
+ setErr('')
1399
+ try {
1400
+ const buf = await file.arrayBuffer()
1401
+ const res = await fetch(auth.server + '/api/upload', {
1402
+ method: 'POST',
1403
+ headers: {
1404
+ authorization: 'Bearer ' + auth.token,
1405
+ 'content-type': file.type || 'application/octet-stream',
1406
+ 'x-filename': encodeURIComponent(file.name || ''),
1407
+ },
1408
+ body: buf,
1409
+ })
1410
+ let up = null
1411
+ try {
1412
+ up = await res.json()
1413
+ } catch {
1414
+ up = null
1415
+ }
1416
+ if (!res.ok || !up) {
1417
+ setErr('头像上传失败')
1418
+ return
1419
+ }
1420
+ await api(auth.server, '/api/avatar', {
1421
+ method: 'POST',
1422
+ token: auth.token,
1423
+ body: { uploadId: up.id },
1424
+ })
1425
+ setMyAvatar(up.id)
1426
+ } catch (e) {
1427
+ setErr(friendly(e))
1428
+ }
1429
+ }
1430
+
943
1431
  const lastOf = (fid) => {
944
1432
  for (let i = messages.length - 1; i >= 0; i--) {
945
1433
  const m = messages[i]
@@ -956,8 +1444,70 @@ window.__ModuleLoader__.load({
956
1444
  return String(b.text || '')
957
1445
  }
958
1446
 
1447
+ /** 会话 = 好友 + 群,统一成一种形状给侧栏和标题用 */
1448
+ const convs = [
1449
+ ...friends.map((f) => ({
1450
+ kind: 'dm',
1451
+ key: f.id,
1452
+ title: f.displayName || f.id,
1453
+ avatar: f.avatar || '',
1454
+ members: [],
1455
+ hidden: hiddenChats.indexOf(f.id) >= 0,
1456
+ })),
1457
+ ...groups.map((g) => ({
1458
+ kind: 'group',
1459
+ key: 'g:' + g.id,
1460
+ title: g.name,
1461
+ avatar: g.avatar || '',
1462
+ members: g.members || [],
1463
+ hidden: hiddenChats.indexOf('g:' + g.id) >= 0,
1464
+ })),
1465
+ ]
1466
+ const shownConvs = sideTab === 'contacts' ? convs : convs.filter((c) => !c.hidden)
1467
+ const current = convs.find((c) => c.key === active) || null
1468
+ const isGroup = !!(current && current.kind === 'group')
1469
+ const nameOf = (id) => {
1470
+ const mem = current && (current.members || []).find((x) => x.id === id)
1471
+ if (mem) return mem.displayName || id
1472
+ const dm = convs.find((c) => c.kind === 'dm' && c.key === id)
1473
+ return dm ? dm.title : id
1474
+ }
1475
+ const avatarOfSender = (id) => {
1476
+ const mem = current && (current.members || []).find((x) => x.id === id)
1477
+ if (mem) return mem.avatar || ''
1478
+ const dm = convs.find((c) => c.kind === 'dm' && c.key === id)
1479
+ return dm ? dm.avatar || '' : ''
1480
+ }
1481
+
959
1482
  const thread = messages.filter((m) => m.from === active || m.to === active)
960
1483
 
1484
+ /** 正在上传 / 上传失败的附件,先占位显示,避免「点了没反应」 */
1485
+ const renderPending = (p) => {
1486
+ const failed = p.status === 'failed'
1487
+ return h(
1488
+ 'div',
1489
+ { key: p.id, className: 'sc-msg mine' },
1490
+ h(
1491
+ 'div',
1492
+ {
1493
+ className: 'sc-file',
1494
+ style: failed ? { borderColor: '#d9534f' } : { opacity: 0.7 },
1495
+ },
1496
+ h('span', { className: 'sc-file-ico' }, failed ? '⚠️' : fileIcon(p.type, p.name)),
1497
+ h(
1498
+ 'span',
1499
+ { className: 'sc-file-main' },
1500
+ h('span', { className: 'sc-file-name' }, p.name),
1501
+ h(
1502
+ 'span',
1503
+ { className: 'sc-file-size' },
1504
+ failed ? '失败:' + (p.error || '上传出错') : '上传中… ' + kbText(p.size),
1505
+ ),
1506
+ ),
1507
+ ),
1508
+ )
1509
+ }
1510
+
961
1511
  const renderMessage = (m) => {
962
1512
  const b = m.body || {}
963
1513
  const kind = b.kind || 'text'
@@ -966,16 +1516,21 @@ window.__ModuleLoader__.load({
966
1516
  if (kind === 'snapshot') {
967
1517
  content = h(SnapshotCard, { snapshotId: b.snapshotId, auth })
968
1518
  } else if (kind === 'image') {
969
- content = h('img', {
970
- className: 'sc-msg-img',
971
- src: auth.server + b.url,
972
- alt: b.caption || '图片',
973
- })
1519
+ const src = auth.server + b.url
1520
+ content = h(
1521
+ 'a',
1522
+ { href: src + '?download=1', target: '_blank', rel: 'noreferrer', title: '点开保存' },
1523
+ h('img', { className: 'sc-msg-img', src, alt: b.caption || '图片' }),
1524
+ )
974
1525
  } else if (kind === 'file') {
975
1526
  const t = String(b.type || '')
976
1527
  const src = auth.server + b.url
977
1528
  if (t.startsWith('image/')) {
978
- content = h('img', { className: 'sc-msg-img', src, alt: b.name || '图片' })
1529
+ content = h(
1530
+ 'a',
1531
+ { href: src + '?download=1', target: '_blank', rel: 'noreferrer', title: '点开保存' },
1532
+ h('img', { className: 'sc-msg-img', src, alt: b.name || '图片' }),
1533
+ )
979
1534
  } else if (t.startsWith('video/')) {
980
1535
  content = h('video', { src, controls: true, style: MEDIA_STYLE })
981
1536
  } else if (t.startsWith('audio/')) {
@@ -985,7 +1540,7 @@ window.__ModuleLoader__.load({
985
1540
  'a',
986
1541
  {
987
1542
  className: 'sc-file',
988
- href: src,
1543
+ href: src + '?download=1',
989
1544
  target: '_blank',
990
1545
  rel: 'noreferrer',
991
1546
  download: b.name || undefined,
@@ -995,7 +1550,11 @@ window.__ModuleLoader__.load({
995
1550
  'span',
996
1551
  { className: 'sc-file-main' },
997
1552
  h('span', { className: 'sc-file-name' }, b.name || '附件'),
998
- h('span', { className: 'sc-file-size' }, (b.type || '未知类型') + ' · ' + kbText(b.size)),
1553
+ h(
1554
+ 'span',
1555
+ { className: 'sc-file-size' },
1556
+ (b.type || '未知类型') + ' · ' + kbText(b.size) + ' · 点击下载',
1557
+ ),
999
1558
  ),
1000
1559
  )
1001
1560
  }
@@ -1004,20 +1563,82 @@ window.__ModuleLoader__.load({
1004
1563
  }
1005
1564
  return h(
1006
1565
  'div',
1007
- { key: m.seq, className: 'sc-msg' + (mine ? ' mine' : '') },
1008
- content,
1009
- h('div', { className: 'sc-time' }, clockText(m.at)),
1566
+ { key: m.seq, className: 'sc-msg-row' + (mine ? ' mine' : '') },
1567
+ avatar(
1568
+ mine ? auth.displayName || auth.id : nameOf(m.from),
1569
+ mine ? auth.id : m.from,
1570
+ 32,
1571
+ mine ? myAvatar : avatarOfSender(m.from),
1572
+ ),
1573
+ h(
1574
+ 'div',
1575
+ { className: 'sc-msg' + (mine ? ' mine' : '') },
1576
+ isGroup && !mine
1577
+ ? h('div', { className: 'sc-time', style: { marginBottom: '2px' } }, nameOf(m.from))
1578
+ : null,
1579
+ content,
1580
+ h('div', { className: 'sc-time' }, clockText(m.at)),
1581
+ ),
1010
1582
  )
1011
1583
  }
1012
1584
 
1585
+ /** 通讯录页:右侧内容区整块变成好友列表 */
1586
+ const contactsPane =
1587
+ sideTab === 'contacts'
1588
+ ? h(
1589
+ 'div',
1590
+ { className: 'sc-contacts' },
1591
+ h('div', { className: 'sc-side-title', style: { padding: '14px 16px 6px' } }, '通讯录'),
1592
+ h(
1593
+ 'div',
1594
+ { style: { flex: 1, minHeight: 0, overflow: 'auto', padding: '0 12px 12px' } },
1595
+ convs.length === 0
1596
+ ? emptyState('👥', '通讯录是空的', '在左边输入对方 ID 加好友,或者建一个群')
1597
+ : convs.map((c) =>
1598
+ h(
1599
+ 'div',
1600
+ {
1601
+ key: 'ct-' + c.key,
1602
+ className: 'sc-friend',
1603
+ title: c.key,
1604
+ onClick: () => {
1605
+ setActive(c.key)
1606
+ setSideTab('chats')
1607
+ if (c.hidden) hideChat(c.key, false)
1608
+ },
1609
+ onContextMenu: (e) => {
1610
+ e.preventDefault()
1611
+ showConvMenu(e.clientX, e.clientY, c)
1612
+ },
1613
+ },
1614
+ c.kind === 'group'
1615
+ ? avatar(c.title, c.key, 34, c.avatar, true)
1616
+ : avatar(c.title, c.key, 34, c.avatar),
1617
+ h(
1618
+ 'div',
1619
+ { className: 'sc-friend-main' },
1620
+ h('div', { className: 'sc-friend-name' }, c.title),
1621
+ h(
1622
+ 'div',
1623
+ { className: 'sc-friend-last' },
1624
+ c.kind === 'group' ? c.members.length + ' 人' : '@' + c.key,
1625
+ ),
1626
+ ),
1627
+ c.hidden ? h('span', { className: 'sc-chip' }, '已隐藏') : null,
1628
+ ),
1629
+ ),
1630
+ ),
1631
+ )
1632
+ : null
1633
+
1013
1634
  return h(
1014
1635
  'div',
1015
- { className: 'sc-chat' },
1636
+ { className: 'sc-chat', ref: chatRef },
1016
1637
  /* 顶栏 */
1017
1638
  h(
1018
1639
  'div',
1019
- { className: 'sc-chat-head' },
1020
- h(Character, { id: auth.id, ch: readMyCharacter(), size: 30 }),
1640
+ { className: 'sc-chat-head', ref: headRef },
1641
+ avatar(auth.displayName || auth.id, auth.id, 30, myAvatar),
1021
1642
  h(
1022
1643
  'div',
1023
1644
  { style: { minWidth: 0 } },
@@ -1035,6 +1656,24 @@ window.__ModuleLoader__.load({
1035
1656
  err,
1036
1657
  )
1037
1658
  : null,
1659
+ h(
1660
+ 'button',
1661
+ {
1662
+ className: 'sc-btn' + (sideTab === 'chats' ? ' sc-btn-primary' : ''),
1663
+ onClick: () => setSideTab('chats'),
1664
+ title: '会话列表',
1665
+ },
1666
+ '💬 会话',
1667
+ ),
1668
+ h(
1669
+ 'button',
1670
+ {
1671
+ className: 'sc-btn' + (sideTab === 'contacts' ? ' sc-btn-primary' : ''),
1672
+ onClick: () => setSideTab('contacts'),
1673
+ title: '通讯录',
1674
+ },
1675
+ '👥 通讯录',
1676
+ ),
1038
1677
  h(
1039
1678
  'button',
1040
1679
  {
@@ -1053,7 +1692,47 @@ window.__ModuleLoader__.load({
1053
1692
  },
1054
1693
  '📹 开会',
1055
1694
  ),
1056
- h('button', { className: 'sc-btn', onClick: props.onOpenGame, title: '玩一把鱼塘摸鱼' }, '🎮 摸鱼'),
1695
+ h('button', { className: 'sc-btn', onClick: props.onOpenGame, title: '玩一把鱼塘钓鱼' }, '🎮 钓鱼'),
1696
+ h(
1697
+ 'button',
1698
+ {
1699
+ className: 'sc-btn',
1700
+ onClick: () => openKtv({ auth, onToast: (m) => setErr(m), target: active }),
1701
+ title: '一起唱歌:同步伴奏 + 语音',
1702
+ },
1703
+ '🎤 KTV',
1704
+ ),
1705
+ h(
1706
+ 'button',
1707
+ {
1708
+ className: 'sc-btn',
1709
+ onClick: () => {
1710
+ try {
1711
+ window.dispatchEvent(new CustomEvent('dsh-share-chat:pet-show'))
1712
+ } catch (e) {}
1713
+ },
1714
+ title: '叫出桌宠(形象独立浮在界面上)',
1715
+ },
1716
+ '🐳',
1717
+ ),
1718
+ h(
1719
+ 'button',
1720
+ {
1721
+ className: 'sc-btn',
1722
+ onClick: () => openMahjong({ auth, onToast: (m) => setErr(m) }),
1723
+ title: '开一桌麻将(缺的位置机器人补)',
1724
+ },
1725
+ '🀄 麻将',
1726
+ ),
1727
+ h(
1728
+ 'button',
1729
+ {
1730
+ className: 'sc-btn',
1731
+ onClick: () => openKiller({ auth, onToast: (m) => setErr(m) }),
1732
+ title: '每日杀手数独',
1733
+ },
1734
+ '🧩 数独',
1735
+ ),
1057
1736
  h('button', { className: 'sc-btn sc-btn-ghost', onClick: props.onLogout }, '退出'),
1058
1737
  ),
1059
1738
  /* 主体 */
@@ -1064,8 +1743,8 @@ window.__ModuleLoader__.load({
1064
1743
  { className: 'sc-chat-body' },
1065
1744
  h(
1066
1745
  'div',
1067
- { className: 'sc-side' },
1068
- h('div', { className: 'sc-side-title' }, '好友'),
1746
+ { className: 'sc-side', style: sideTab === 'contacts' ? { display: 'none' } : undefined },
1747
+ h('div', { className: 'sc-side-title' }, '会话'),
1069
1748
  h(
1070
1749
  'div',
1071
1750
  { className: 'sc-add' },
@@ -1079,27 +1758,86 @@ window.__ModuleLoader__.load({
1079
1758
  },
1080
1759
  }),
1081
1760
  h('button', { className: 'sc-btn sc-btn-sm', onClick: addFriend }, '添加'),
1761
+ h(
1762
+ 'button',
1763
+ {
1764
+ className: 'sc-btn sc-btn-sm',
1765
+ onClick: () => setInline({ mode: 'group', value: '' }),
1766
+ title: '建一个群',
1767
+ },
1768
+ '建群',
1769
+ ),
1082
1770
  ),
1771
+ inline
1772
+ ? h(
1773
+ 'div',
1774
+ { className: 'sc-add' },
1775
+ h('input', {
1776
+ className: 'sc-input',
1777
+ autoFocus: true,
1778
+ placeholder: inline.mode === 'group' ? '群名' : '对方 ID',
1779
+ value: inline.value,
1780
+ onChange: (e) => setInline({ mode: inline.mode, value: e.target.value }),
1781
+ onKeyDown: (e) => {
1782
+ if (e.key === 'Enter') submitInline()
1783
+ if (e.key === 'Escape') setInline(null)
1784
+ },
1785
+ }),
1786
+ h(
1787
+ 'button',
1788
+ { className: 'sc-btn sc-btn-sm', onClick: submitInline },
1789
+ inline.mode === 'group' ? '创建' : '拉入',
1790
+ ),
1791
+ h(
1792
+ 'button',
1793
+ {
1794
+ className: 'sc-btn sc-btn-sm sc-btn-ghost',
1795
+ onClick: () => setInline(null),
1796
+ },
1797
+ '取消',
1798
+ ),
1799
+ )
1800
+ : null,
1083
1801
  h(
1084
1802
  'div',
1085
1803
  { className: 'sc-friends' },
1086
- friends.length === 0
1087
- ? emptyState('👥', '还没有好友', '在上面输入对方 ID 加一个')
1088
- : friends.map((f) =>
1804
+ shownConvs.length === 0
1805
+ ? emptyState(
1806
+ '👥',
1807
+ sideTab === 'contacts' ? '通讯录是空的' : '没有显示的会话',
1808
+ sideTab === 'contacts' ? '在上面加好友,或者点「建群」' : '被隐起来的会话在「通讯录」里',
1809
+ )
1810
+ : shownConvs.map((c) =>
1089
1811
  h(
1090
1812
  'div',
1091
1813
  {
1092
- key: f.id,
1093
- className: 'sc-friend' + (active === f.id ? ' on' : ''),
1094
- onClick: () => setActive(f.id),
1095
- title: f.id,
1814
+ key: c.key,
1815
+ className: 'sc-friend' + (active === c.key ? ' on' : ''),
1816
+ onClick: () => {
1817
+ setActive(c.key)
1818
+ setSideTab('chats')
1819
+ if (c.hidden) hideChat(c.key, false)
1820
+ },
1821
+ onContextMenu: (e) => {
1822
+ e.preventDefault()
1823
+ showConvMenu(e.clientX, e.clientY, c)
1824
+ },
1825
+ title: c.key,
1826
+ // 会话卡片直接用这个会话的聊天背景铺满
1827
+ style: cardStyle(bgOf(c.key), active === c.key),
1096
1828
  },
1097
- h(Character, { id: f.id, size: 30 }),
1829
+ c.kind === 'group'
1830
+ ? avatar(c.title, c.key, 30, c.avatar, true)
1831
+ : avatar(c.title, c.key, 30, c.avatar),
1098
1832
  h(
1099
1833
  'div',
1100
1834
  { className: 'sc-friend-main' },
1101
- h('div', { className: 'sc-friend-name' }, f.displayName || f.id),
1102
- h('div', { className: 'sc-friend-last' }, previewOf(lastOf(f.id)) || '还没有消息'),
1835
+ h(
1836
+ 'div',
1837
+ { className: 'sc-friend-name' },
1838
+ c.title + (c.kind === 'group' ? ' (' + c.members.length + ')' : ''),
1839
+ ),
1840
+ h('div', { className: 'sc-friend-last' }, previewOf(lastOf(c.key)) || '还没有消息'),
1103
1841
  ),
1104
1842
  ),
1105
1843
  ),
@@ -1108,22 +1846,127 @@ window.__ModuleLoader__.load({
1108
1846
  h(
1109
1847
  'div',
1110
1848
  { className: 'sc-main' },
1849
+ sideTab === 'contacts' ? contactsPane : null,
1850
+ current
1851
+ ? h(
1852
+ 'div',
1853
+ { style: { flex: '0 0 auto' } },
1854
+ h(
1855
+ 'div',
1856
+ {
1857
+ className: 'sc-side-title',
1858
+ style: { display: 'flex', alignItems: 'center', gap: '8px' },
1859
+ },
1860
+ h('span', null, current.title + (isGroup ? ' · ' + current.members.length + ' 人' : '')),
1861
+ h('span', { className: 'sc-grow' }),
1862
+ isGroup
1863
+ ? h(
1864
+ 'button',
1865
+ {
1866
+ className: 'sc-btn sc-btn-sm',
1867
+ onClick: () => setInline({ mode: 'member', value: '' }),
1868
+ title: '拉人进群',
1869
+ },
1870
+ '+人',
1871
+ )
1872
+ : null,
1873
+ h(
1874
+ 'button',
1875
+ {
1876
+ className: 'sc-btn sc-btn-sm' + (bgOpen ? ' sc-btn-primary' : ''),
1877
+ onClick: () => setBgOpen((v) => !v),
1878
+ title: '换这个会话的聊天背景',
1879
+ },
1880
+ '🖼',
1881
+ ),
1882
+ ),
1883
+ bgOpen
1884
+ ? h(
1885
+ 'div',
1886
+ {
1887
+ style: {
1888
+ display: 'flex',
1889
+ alignItems: 'center',
1890
+ flexWrap: 'wrap',
1891
+ gap: '6px',
1892
+ padding: '4px 14px 8px',
1893
+ },
1894
+ },
1895
+ BG_COLORS.map((c) =>
1896
+ h('span', {
1897
+ key: c,
1898
+ title: c,
1899
+ onClick: () => setBgFor(active, { type: 'color', v: c }),
1900
+ style: {
1901
+ width: '20px',
1902
+ height: '20px',
1903
+ borderRadius: '5px',
1904
+ cursor: 'pointer',
1905
+ background: c,
1906
+ border: '1px solid rgba(128,128,128,.35)',
1907
+ },
1908
+ }),
1909
+ ),
1910
+ BG_GRADS.map((g) =>
1911
+ h('span', {
1912
+ key: g,
1913
+ title: '渐变',
1914
+ onClick: () => setBgFor(active, { type: 'grad', v: g }),
1915
+ style: {
1916
+ width: '20px',
1917
+ height: '20px',
1918
+ borderRadius: '5px',
1919
+ cursor: 'pointer',
1920
+ backgroundImage: g,
1921
+ border: '1px solid rgba(128,128,128,.35)',
1922
+ },
1923
+ }),
1924
+ ),
1925
+ h(
1926
+ 'button',
1927
+ {
1928
+ className: 'sc-btn sc-btn-sm',
1929
+ onClick: () => {
1930
+ const inp = document.createElement('input')
1931
+ inp.type = 'file'
1932
+ inp.accept = 'image/*'
1933
+ inp.addEventListener('change', () => {
1934
+ const f = inp.files && inp.files[0]
1935
+ if (f) uploadBg(f)
1936
+ })
1937
+ inp.click()
1938
+ },
1939
+ },
1940
+ '上传图片',
1941
+ ),
1942
+ h(
1943
+ 'button',
1944
+ {
1945
+ className: 'sc-btn sc-btn-sm sc-btn-ghost',
1946
+ onClick: () => setBgFor(active, null),
1947
+ },
1948
+ '默认',
1949
+ ),
1950
+ )
1951
+ : null,
1952
+ )
1953
+ : null,
1111
1954
  h(
1112
1955
  'div',
1113
- { className: 'sc-thread', ref: listRef },
1114
- h(
1115
- 'div',
1116
- { className: 'sc-thread-inner' },
1117
- !active
1118
- ? emptyState('💬', '选一个好友开始聊天', '左边是好友列表,点一下就进来')
1119
- : thread.length === 0
1120
- ? emptyState('🐟', '还没有消息', '说点什么,或者在上面的「分享这一轮」把对话发过去')
1121
- : thread.map(renderMessage),
1122
- ),
1123
- ),
1124
- h(
1125
- 'div',
1126
- { className: 'sc-composer' },
1956
+ { className: 'sc-thread', ref: listRef, style: Object.assign({}, bgStyle(bgOf(active)), sideTab === 'contacts' ? { display: 'none' } : {}) },
1957
+ h(
1958
+ 'div',
1959
+ { className: 'sc-thread-inner' },
1960
+ !active
1961
+ ? emptyState('💬', '选一个会话开始聊天', '左边是会话列表,点一下就进来')
1962
+ : thread.length === 0 && pending.length === 0
1963
+ ? emptyState('🐟', '还没有消息', '说点什么,或者在上面的「分享这一轮」把对话发过去')
1964
+ : thread.map(renderMessage).concat(pending.map(renderPending)),
1965
+ ),
1966
+ ),
1967
+ h(
1968
+ 'div',
1969
+ { className: 'sc-composer', ref: composerRef, style: sideTab === 'contacts' ? { display: 'none' } : undefined },
1127
1970
  h(
1128
1971
  'div',
1129
1972
  { className: 'sc-composer-inner' },
@@ -1175,6 +2018,18 @@ window.__ModuleLoader__.load({
1175
2018
  e.target.value = ''
1176
2019
  },
1177
2020
  }),
2021
+ h(
2022
+ 'button',
2023
+ {
2024
+ className:
2025
+ 'sc-btn ' + (askMode ? 'sc-btn-primary' : 'sc-btn-ghost') + ' sc-icon-btn',
2026
+ title: askMode
2027
+ ? '问模型已开:发出去的是模型的回答'
2028
+ : '打开后,你发的内容会先问模型,再把它的回答发出去',
2029
+ onClick: () => setAskMode((v) => !v),
2030
+ },
2031
+ askMode ? '🔮 问模型' : '🔮',
2032
+ ),
1178
2033
  h('textarea', {
1179
2034
  className: 'sc-textarea',
1180
2035
  placeholder: active ? 'Enter 发送,Shift+Enter 换行' : '先选一个好友',
@@ -1284,7 +2139,7 @@ window.__ModuleLoader__.load({
1284
2139
  ].join(';')
1285
2140
 
1286
2141
  const title = document.createElement('strong')
1287
- title.textContent = '鱼塘摸鱼'
2142
+ title.textContent = '鱼塘钓鱼'
1288
2143
  title.style.cssText = 'font-size:12.5px'
1289
2144
 
1290
2145
  const meta = document.createElement('span')
@@ -1316,7 +2171,7 @@ window.__ModuleLoader__.load({
1316
2171
 
1317
2172
  const frame = document.createElement('iframe')
1318
2173
  frame.src = GAME_URL
1319
- frame.title = '鱼塘摸鱼'
2174
+ frame.title = '鱼塘钓鱼'
1320
2175
  frame.setAttribute('allow', 'autoplay; clipboard-write')
1321
2176
  frame.style.cssText =
1322
2177
  'position:absolute;inset:0;width:100%;height:100%;border:0;background:#0b1d24'
@@ -1463,7 +2318,7 @@ window.__ModuleLoader__.load({
1463
2318
  h(
1464
2319
  'div',
1465
2320
  { className: 'sc-set-desc', style: { marginTop: '6px' } },
1466
- '「🎮 摸鱼」打开的窗口大小。窗口可以拖标题栏移动、拖右下角临时改大小;这里设的是默认值,保存在这台电脑的浏览器里。',
2321
+ '「🎮 钓鱼」打开的窗口大小。窗口可以拖标题栏移动、拖右下角临时改大小;这里设的是默认值,保存在这台电脑的浏览器里。',
1467
2322
  ),
1468
2323
  ),
1469
2324
  h(
@@ -3894,6 +4749,15 @@ window.__ModuleLoader__.load({
3894
4749
  /* ---------- 进出房间 ---------- */
3895
4750
  async function ensureMedia() {
3896
4751
  if (localStream) return
4752
+ if (opts.audioOnly) {
4753
+ // KTV:只要麦克风,别开摄像头
4754
+ localStream = await navigator.mediaDevices.getUserMedia({ audio: true })
4755
+ camOn = false
4756
+ tile('self', '我', localStream, true)
4757
+ relayout()
4758
+ renderToolbar()
4759
+ return
4760
+ }
3897
4761
  try {
3898
4762
  localStream = await navigator.mediaDevices.getUserMedia({
3899
4763
  audio: true,
@@ -3942,6 +4806,13 @@ window.__ModuleLoader__.load({
3942
4806
  }
3943
4807
  }
3944
4808
 
4809
+ // KTV 用:带房间号直接进,不用再点「加入」
4810
+ if (opts.roomId) {
4811
+ window.setTimeout(() => {
4812
+ startMeeting('join', String(opts.roomId)).catch(() => {})
4813
+ }, 250)
4814
+ }
4815
+
3945
4816
  async function leave() {
3946
4817
  if (closed) return
3947
4818
  closed = true
@@ -4014,139 +4885,2371 @@ window.__ModuleLoader__.load({
4014
4885
 
4015
4886
  // ───────────────────────── 入口 ─────────────────────────
4016
4887
 
4017
- function SocialView(props) {
4018
- const [auth, setAuth] = useState(() => readJson(K_AUTH))
4019
- const [gameOpen, setGameOpen] = useState(false)
4020
- const rootRef = useRef(null)
4888
+ /* ---------- KTV ---------- */
4889
+ /**
4890
+ * 房间里的伴奏同步:服务端存锚点(第几秒、是否在放、锚点时刻),
4891
+ * 客户端只用自己的本地时间差推算该播到哪,偶发漂移超过 0.45 秒才校正,
4892
+ * 这样既不会各唱各的,也不会因为网络抖动一直卡。
4893
+ */
4894
+ function openKtv(opts) {
4895
+ const auth = opts.auth
4896
+ const onToast = opts.onToast || (() => {})
4897
+ const target = opts.target || ''
4898
+
4899
+ const B =
4900
+ 'padding:6px 10px;border-radius:8px;border:1px solid rgba(255,255,255,.16);background:rgba(255,255,255,.06);color:inherit;font-size:12px;cursor:pointer;white-space:nowrap'
4901
+ const IN =
4902
+ 'flex:1;min-width:0;padding:6px 9px;border-radius:8px;border:1px solid rgba(255,255,255,.16);background:rgba(255,255,255,.04);color:inherit;font-size:12px'
4903
+
4904
+ const wrap = document.createElement('div')
4905
+ wrap.style.cssText = [
4906
+ 'position:fixed',
4907
+ 'right:18px',
4908
+ 'bottom:18px',
4909
+ 'width:400px',
4910
+ 'max-width:calc(100vw - 20px)',
4911
+ 'height:540px',
4912
+ 'max-height:calc(100vh - 30px)',
4913
+ 'z-index:2147483646',
4914
+ 'display:flex',
4915
+ 'flex-direction:column',
4916
+ 'overflow:hidden',
4917
+ 'border-radius:16px',
4918
+ 'background:#1b1d22',
4919
+ 'color:#e8eaed',
4920
+ 'border:1px solid rgba(255,255,255,.12)',
4921
+ 'box-shadow:0 24px 60px rgba(0,0,0,.5)',
4922
+ 'font:13px/1.5 system-ui,-apple-system,"Segoe UI",sans-serif',
4923
+ ].join(';')
4021
4924
 
4022
- useEffect(() => {
4023
- const el = rootRef.current
4024
- if (!el) return
4025
- adaptSurfaceTokens(el)
4026
- // 主题切换/面板尺寸变化后再校一次
4027
- const timer = window.setTimeout(() => adaptSurfaceTokens(el), 400)
4028
- return () => window.clearTimeout(timer)
4029
- }, [])
4925
+ wrap.innerHTML =
4926
+ '<div style="display:flex;align-items:center;gap:8px;padding:10px 12px;border-bottom:1px solid rgba(255,255,255,.1)">' +
4927
+ '<b style="font-size:14px">🎤 KTV</b>' +
4928
+ '<span data-code style="opacity:.6;font-size:12px"></span>' +
4929
+ '<span style="flex:1"></span>' +
4930
+ '<button data-close style="' +
4931
+ B +
4932
+ '">✕</button>' +
4933
+ '</div>' +
4934
+ '<div style="padding:10px 12px;display:flex;flex-direction:column;gap:8px;overflow:auto;flex:1">' +
4935
+ '<div style="display:flex;gap:6px">' +
4936
+ '<input data-room placeholder="房间号" style="' +
4937
+ IN +
4938
+ '">' +
4939
+ '<button data-join style="' +
4940
+ B +
4941
+ '">加入</button>' +
4942
+ '<button data-create style="' +
4943
+ B +
4944
+ '">建房</button>' +
4945
+ '</div>' +
4946
+ '<div style="display:flex;gap:6px;align-items:center">' +
4947
+ '<button data-upload style="' +
4948
+ B +
4949
+ '">+ 上传伴奏</button>' +
4950
+ '<span data-hint style="opacity:.55;font-size:11px">mp3 / m4a / wav,≤50 MB</span>' +
4951
+ '</div>' +
4952
+ '<div data-tracks style="display:flex;flex-direction:column;gap:3px"></div>' +
4953
+ '</div>' +
4954
+ '<div style="border-top:1px solid rgba(255,255,255,.1);padding:10px 12px">' +
4955
+ '<div data-now style="font-size:12px;opacity:.75;margin-bottom:6px">还没选伴奏</div>' +
4956
+ '<input data-seek type="range" min="0" max="1000" value="0" style="width:100%;accent-color:#5aa9e6">' +
4957
+ '<div style="display:flex;gap:6px;align-items:center;margin-top:6px">' +
4958
+ '<button data-play style="' +
4959
+ B +
4960
+ '">▶ 播放</button>' +
4961
+ '<span data-time style="font-size:11px;opacity:.65">0:00 / 0:00</span>' +
4962
+ '<span style="flex:1"></span>' +
4963
+ '<button data-mic style="' +
4964
+ B +
4965
+ '">🎙 开麦</button>' +
4966
+ '<button data-share style="' +
4967
+ B +
4968
+ '">发到群里</button>' +
4969
+ '</div>' +
4970
+ '</div>'
4971
+
4972
+ document.body.appendChild(wrap)
4973
+ attachScaler(wrap, 'ktv')
4974
+ attachDragger(wrap, 'ktv')
4975
+
4976
+ const $ = (s) => wrap.querySelector(s)
4977
+ const codeEl = $('[data-code]')
4978
+ const hintEl = $('[data-hint]')
4979
+ const tracksEl = $('[data-tracks]')
4980
+ const nowEl = $('[data-now]')
4981
+ const seekEl = $('[data-seek]')
4982
+ const timeEl = $('[data-time]')
4983
+ const playBtn = $('[data-play]')
4030
4984
 
4031
- const body = !auth
4032
- ? h(LoginPanel, { onDone: (next) => setAuth(next) })
4033
- : h(ChatPanel, {
4034
- auth,
4035
- onOpenGame: () => setGameOpen(true),
4036
- onLogout: () => {
4037
- dropKey(K_AUTH)
4038
- setAuth(null)
4039
- setGameOpen(false)
4040
- },
4041
- })
4985
+ let roomId = ''
4986
+ let tracks = []
4987
+ let current = null
4988
+ let sync = { playing: false, pos: 0, t0: 0 }
4989
+ let closeTimer = null
4990
+ let tickTimer = null
4991
+ let seekBusy = false
4992
+
4993
+ const audio = new Audio()
4994
+ audio.preload = 'auto'
4995
+ audio.crossOrigin = 'anonymous'
4996
+
4997
+ const fmt = (s) => {
4998
+ const n = Math.max(0, Math.floor(Number(s) || 0))
4999
+ return Math.floor(n / 60) + ':' + String(n % 60).padStart(2, '0')
5000
+ }
4042
5001
 
4043
- // 只有会话里的 View 才拿得到会话数据;全局面板没有 props
4044
- const canShare = !!(props && props.sessionId && typeof props.useChat === 'function')
5002
+ const setHint = (t) => {
5003
+ hintEl.textContent = t
5004
+ }
4045
5005
 
4046
- return h(
4047
- 'div',
4048
- { className: 'sc-root', ref: rootRef },
4049
- canShare && auth ? h(Boundary, null, h(ShareBar, { chatProps: props, auth })) : null,
4050
- h('div', { style: { flex: 1, minHeight: 0, display: 'flex' } }, body),
4051
- gameOpen ? h(GameWindow, { onClose: () => setGameOpen(false) }) : null,
4052
- )
4053
- }
5006
+ const renderTracks = () => {
5007
+ tracksEl.textContent = ''
5008
+ if (!tracks.length) {
5009
+ const d = document.createElement('div')
5010
+ d.style.cssText = 'opacity:.5;font-size:12px;padding:6px 2px'
5011
+ d.textContent = '伴奏库是空的,先上传一首'
5012
+ tracksEl.appendChild(d)
5013
+ return
5014
+ }
5015
+ for (const t of tracks) {
5016
+ const row = document.createElement('div')
5017
+ row.style.cssText =
5018
+ 'display:flex;align-items:center;gap:8px;padding:6px 8px;border-radius:8px;cursor:pointer;' +
5019
+ (current && current.id === t.id ? 'background:rgba(90,169,230,.22)' : 'background:rgba(255,255,255,.04)')
5020
+ const name = document.createElement('div')
5021
+ name.style.cssText = 'flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap'
5022
+ name.textContent = '♪ ' + t.title + (t.artist ? ' — ' + t.artist : '')
5023
+ name.title = (t.title || '') + ' · ' + (t.by || '')
5024
+ row.appendChild(name)
5025
+ row.addEventListener('click', () => choose(t))
5026
+ tracksEl.appendChild(row)
5027
+ }
5028
+ }
4054
5029
 
4055
- // ─────────────────────── 一键分享 ───────────────────────
5030
+ const loadTracks = async () => {
5031
+ try {
5032
+ const r = await api(auth.server, '/api/ktv/tracks', { token: auth.token })
5033
+ tracks = r.tracks || []
5034
+ renderTracks()
5035
+ } catch (e) {
5036
+ setHint('伴奏库读取失败')
5037
+ }
5038
+ }
4056
5039
 
4057
- /** 兜住探针/适配器的异常,别让整个 slot 变空白 */
4058
- class Boundary extends React.Component {
4059
- constructor(p) {
4060
- super(p)
4061
- this.state = { err: null }
5040
+ const postKtv = async (patch) => {
5041
+ if (!roomId) {
5042
+ onToast('先建房或加入房间')
5043
+ return
5044
+ }
5045
+ try {
5046
+ const body = {
5047
+ trackId: current ? current.id : '',
5048
+ playing: sync.playing,
5049
+ position: sync.playing ? sync.pos + (performance.now() - sync.t0) / 1000 : sync.pos,
5050
+ ...patch,
5051
+ }
5052
+ const r = await api(auth.server, '/api/meet/rooms/' + roomId + '/ktv', {
5053
+ method: 'POST',
5054
+ token: auth.token,
5055
+ body,
5056
+ })
5057
+ applySync(r.ktv)
5058
+ } catch (e) {
5059
+ onToast('同步失败:' + friendly(e))
5060
+ }
4062
5061
  }
4063
- static getDerivedStateFromError(e) {
4064
- return { err: String((e && e.message) || e) }
5062
+
5063
+ const applySync = (ktv) => {
5064
+ if (!ktv || !ktv.trackId) return
5065
+ const t = tracks.find((x) => x.id === ktv.trackId)
5066
+ if (t && (!current || current.id !== t.id)) {
5067
+ current = t
5068
+ audio.src = auth.server + t.url
5069
+ renderTracks()
5070
+ }
5071
+ sync = { playing: !!ktv.playing, pos: Number(ktv.elapsed) || 0, t0: performance.now() }
5072
+ nowEl.textContent = current ? '正在放:' + current.title : '还没选伴奏'
5073
+ playBtn.textContent = sync.playing ? '⏸ 暂停' : '▶ 播放'
4065
5074
  }
4066
- render() {
4067
- if (this.state.err) {
4068
- return h(
4069
- 'div',
4070
- { style: { padding: '6px 12px', fontSize: '11px', color: '#d9534f', borderBottom: LINE } },
4071
- '分享组件出错:' + this.state.err,
4072
- )
5075
+
5076
+ const tick = () => {
5077
+ if (!current) return
5078
+ const pos = sync.playing ? sync.pos + (performance.now() - sync.t0) / 1000 : sync.pos
5079
+ const dur = Number.isFinite(audio.duration) ? audio.duration : 0
5080
+ if (dur > 0 && !seekBusy) {
5081
+ seekEl.value = String(Math.round((pos / dur) * 1000))
5082
+ timeEl.textContent = fmt(pos) + ' / ' + fmt(dur)
5083
+ }
5084
+ if (sync.playing) {
5085
+ if (audio.paused) audio.play().catch(() => {})
5086
+ if (dur > 0 && Math.abs(audio.currentTime - pos) > 0.45) audio.currentTime = Math.min(pos, dur - 0.05)
5087
+ } else if (!audio.paused) {
5088
+ audio.pause()
5089
+ if (dur > 0) audio.currentTime = Math.min(pos, dur - 0.05)
4073
5090
  }
4074
- return this.props.children
4075
5091
  }
4076
- }
4077
5092
 
4078
- function shapeOf(v) {
4079
- if (v === null) return 'null'
4080
- if (v === undefined) return 'undefined'
4081
- if (Array.isArray(v)) {
4082
- const first = v.length ? Object.keys(v[0] || {}).join(',') : ''
4083
- return `array(${v.length})` + (first ? ` item: {${first}}` : '')
5093
+ const choose = (t) => {
5094
+ current = t
5095
+ sync = { playing: false, pos: 0, t0: performance.now() }
5096
+ audio.src = auth.server + t.url
5097
+ renderTracks()
5098
+ nowEl.textContent = '正在放:' + t.title
5099
+ playBtn.textContent = '▶ 播放'
5100
+ if (roomId) postKtv({ trackId: t.id, playing: false, position: 0 })
4084
5101
  }
4085
- if (typeof v === 'object') return 'object { ' + Object.keys(v).join(', ') + ' }'
4086
- return typeof v + ' = ' + String(v).slice(0, 80)
4087
- }
4088
5102
 
4089
- /** 在几种常见形状里找出条目数组 */
4090
- function pickArray(v) {
4091
- if (Array.isArray(v)) return v
4092
- if (!v || typeof v !== 'object') return null
4093
- const keys = [
4094
- 'rows',
4095
- 'nodes',
4096
- 'messages',
4097
- 'items',
4098
- 'entries',
4099
- 'turns',
4100
- 'data',
4101
- 'list',
4102
- 'chat',
4103
- 'snapshot',
4104
- 'timeline',
4105
- 'events',
4106
- 'groups',
4107
- ]
4108
- for (const k of keys) if (Array.isArray(v[k])) return v[k]
4109
- // 兜底:只有唯一一个数组字段时就用它
4110
- const arrays = Object.keys(v).filter((k) => Array.isArray(v[k]))
4111
- if (arrays.length === 1) return v[arrays[0]]
4112
- return null
4113
- }
5103
+ const joinRoom = async (id) => {
5104
+ if (!id) return
5105
+ try {
5106
+ const r = await api(auth.server, '/api/meet/rooms/' + id, { token: auth.token })
5107
+ roomId = id
5108
+ codeEl.textContent = '房间 ' + id
5109
+ applySync(r.room && r.room.ktv)
5110
+ onToast('已进入 KTV 房间 ' + id)
5111
+ } catch (e) {
5112
+ onToast('房间不存在:' + id)
5113
+ }
5114
+ }
4114
5115
 
4115
- function textOf(it) {
4116
- if (typeof it === 'string') return it
4117
- if (!it || typeof it !== 'object') return ''
4118
- const cand = it.text ?? it.markdown ?? it.plain ?? it.content ?? it.body
4119
- if (typeof cand === 'string') return cand
4120
- if (Array.isArray(cand)) {
4121
- return cand
4122
- .map((c) => (typeof c === 'string' ? c : (c && (c.text || c.content)) || ''))
4123
- .join('')
5116
+ const refresh = async () => {
5117
+ if (!roomId) return
5118
+ try {
5119
+ const r = await api(auth.server, '/api/meet/rooms/' + roomId, { token: auth.token })
5120
+ const ktv = r.room && r.room.ktv
5121
+ if (ktv && ktv.trackId) {
5122
+ const same = current && current.id === ktv.trackId
5123
+ const drift = Math.abs((Number(ktv.elapsed) || 0) - (sync.playing ? sync.pos + (performance.now() - sync.t0) / 1000 : sync.pos))
5124
+ if (!same || ktv.playing !== sync.playing || drift > 0.6) applySync(ktv)
5125
+ }
5126
+ } catch (e) {
5127
+ /* 房间没了就算了 */
5128
+ }
4124
5129
  }
4125
- if (cand && typeof cand === 'object') {
4126
- const t = cand.text ?? cand.content
4127
- if (typeof t === 'string') return t
5130
+
5131
+ const upload = async (file) => {
5132
+ if (!file) return
5133
+ setHint('上传中…')
5134
+ try {
5135
+ const buf = await file.arrayBuffer()
5136
+ const res = await fetch(auth.server + '/api/upload', {
5137
+ method: 'POST',
5138
+ headers: {
5139
+ authorization: 'Bearer ' + auth.token,
5140
+ 'content-type': file.type || 'application/octet-stream',
5141
+ 'x-filename': encodeURIComponent(file.name || '伴奏'),
5142
+ },
5143
+ body: buf,
5144
+ })
5145
+ const up = await res.json().catch(() => null)
5146
+ if (!res.ok || !up) {
5147
+ setHint(up && up.error === 'too-large' ? '文件太大(≤50 MB)' : '上传失败')
5148
+ return
5149
+ }
5150
+ const title = String(file.name || '伴奏').replace(/\.[^.]+$/, '')
5151
+ await api(auth.server, '/api/ktv/tracks', {
5152
+ method: 'POST',
5153
+ token: auth.token,
5154
+ body: { uploadId: up.id, title },
5155
+ })
5156
+ setHint('已加入伴奏库')
5157
+ await loadTracks()
5158
+ } catch (e) {
5159
+ setHint('上传失败:' + friendly(e))
5160
+ }
4128
5161
  }
4129
- return ''
4130
- }
4131
5162
 
4132
- /** 长得像内部 id 的字符串,不能当正文用 */
4133
- const ID_LIKE = /^(\d+:[a-z]|[0-9a-f]{8}-[0-9a-f]{4}|call_|toolu_|msg_|req_|turn-|step-)/i
5163
+ /* 事件绑定 */
5164
+ $('[data-close]').addEventListener('click', () => {
5165
+ window.clearInterval(tickTimer)
5166
+ window.clearInterval(closeTimer)
5167
+ try {
5168
+ audio.pause()
5169
+ audio.src = ''
5170
+ } catch (e) {}
5171
+ wrap.remove()
5172
+ })
5173
+ $('[data-join]').addEventListener('click', () => joinRoom(String($('[data-room]').value || '').trim()))
5174
+ $('[data-create]').addEventListener('click', async () => {
5175
+ try {
5176
+ const r = await api(auth.server, '/api/meet/rooms', {
5177
+ method: 'POST',
5178
+ token: auth.token,
5179
+ body: { title: (auth.displayName || auth.id) + ' 的 KTV' },
5180
+ })
5181
+ await joinRoom(r.room.id)
5182
+ } catch (e) {
5183
+ onToast('建房失败:' + friendly(e))
5184
+ }
5185
+ })
5186
+ $('[data-upload]').addEventListener('click', () => {
5187
+ const inp = document.createElement('input')
5188
+ inp.type = 'file'
5189
+ inp.accept = 'audio/*'
5190
+ inp.addEventListener('change', () => {
5191
+ const f = inp.files && inp.files[0]
5192
+ if (f) upload(f)
5193
+ })
5194
+ inp.click()
5195
+ })
5196
+ playBtn.addEventListener('click', () => {
5197
+ if (!current) {
5198
+ onToast('先选一首伴奏')
5199
+ return
5200
+ }
5201
+ postKtv({ playing: !sync.playing })
5202
+ })
5203
+ seekEl.addEventListener('input', () => {
5204
+ seekBusy = true
5205
+ })
5206
+ seekEl.addEventListener('change', () => {
5207
+ seekBusy = false
5208
+ const dur = Number.isFinite(audio.duration) ? audio.duration : 0
5209
+ if (dur > 0) postKtv({ position: (Number(seekEl.value) / 1000) * dur })
5210
+ })
5211
+ $('[data-mic]').addEventListener('click', () => {
5212
+ if (!roomId) {
5213
+ onToast('先建房或加入房间')
5214
+ return
5215
+ }
5216
+ openMeeting({ auth, roomId, audioOnly: true, onToast })
5217
+ })
5218
+ $('[data-share]').addEventListener('click', async () => {
5219
+ if (!roomId) {
5220
+ onToast('先建房或加入房间')
5221
+ return
5222
+ }
5223
+ if (!target) {
5224
+ onToast('先在左边选一个群')
5225
+ return
5226
+ }
5227
+ try {
5228
+ await api(auth.server, '/api/messages', {
5229
+ method: 'POST',
5230
+ token: auth.token,
5231
+ body: { to: target, text: '🎤 来唱K!房间号 ' + roomId + '(点右上「KTV」→ 加入)' },
5232
+ })
5233
+ onToast('已发到群里')
5234
+ } catch (e) {
5235
+ onToast('发送失败:' + friendly(e))
5236
+ }
5237
+ })
4134
5238
 
4135
- function looksLikeIdText(s) {
4136
- const t = String(s).trim()
4137
- if (!t) return false
4138
- if (ID_LIKE.test(t)) return true
4139
- // 长串、无空格、只有 id 字符
4140
- if (t.length > 24 && !/\s/.test(t) && /^[0-9a-zA-Z:_-]+$/.test(t)) return true
4141
- return false
5239
+ loadTracks()
5240
+ tickTimer = window.setInterval(tick, 400)
5241
+ closeTimer = window.setInterval(refresh, 2000)
5242
+
5243
+ return { close: () => wrap.remove() }
4142
5244
  }
4143
5245
 
4144
- /** 这些键装的是元数据,不是正文 */
4145
- const SKIP_KEY =
4146
- /^(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
5246
+ /* ---------- 桌宠:形象独立挂在 UI 上 ---------- */
5247
+ const K_PET = 'dsh-share-chat.pet'
5248
+ const PET_ID = 'dsh-share-chat-pet'
4147
5249
 
4148
- /** 思考过程的键名——绝不能分享出去 */
4149
- const REASON_KEY = /reason|think|thought|scratch|cot$/i
5250
+ function PetWidget() {
5251
+ const [face, setFace] = useState(() => readMyCharacter())
5252
+ const [pos, setPos] = useState(() => {
5253
+ const p = readJson(K_PET)
5254
+ return p && typeof p.x === 'number' ? p : { x: null, y: null, hidden: false }
5255
+ })
5256
+ const [menu, setMenu] = useState(false)
5257
+ const dragRef = useRef(null)
5258
+ const nodeRef = useRef(null)
5259
+
5260
+ // 设置页换了形象,这里跟上
5261
+ useEffect(() => {
5262
+ const t = window.setInterval(() => {
5263
+ const next = readMyCharacter()
5264
+ setFace((prev) => (JSON.stringify(prev) === JSON.stringify(next) ? prev : next))
5265
+ }, 1500)
5266
+ return () => window.clearInterval(t)
5267
+ }, [])
5268
+
5269
+ useEffect(() => {
5270
+ writeJson(K_PET, pos)
5271
+ }, [pos])
5272
+
5273
+ // 从聊天里点 🐳 把它叫回来
5274
+ useEffect(() => {
5275
+ const show = () => setPos((p) => Object.assign({}, p, { hidden: false }))
5276
+ window.addEventListener('dsh-share-chat:pet-show', show)
5277
+ return () => window.removeEventListener('dsh-share-chat:pet-show', show)
5278
+ }, [])
5279
+
5280
+ if (pos.hidden) return null
5281
+
5282
+ const startDrag = (e) => {
5283
+ const el = nodeRef.current
5284
+ if (!el) return
5285
+ const r = el.getBoundingClientRect()
5286
+ dragRef.current = {
5287
+ dx: e.clientX - r.left,
5288
+ dy: e.clientY - r.top,
5289
+ sx: e.clientX,
5290
+ sy: e.clientY,
5291
+ moved: false,
5292
+ captured: false,
5293
+ }
5294
+ }
5295
+ const onMove = (e) => {
5296
+ const d = dragRef.current
5297
+ if (!d) return
5298
+ if (Math.abs(e.clientX - d.sx) + Math.abs(e.clientY - d.sy) > 4) d.moved = true
5299
+ if (!d.moved) return
5300
+ // 真的开始拖了才捕获指针;一按下就捕获会把按钮的 click 吃掉
5301
+ if (!d.captured) {
5302
+ d.captured = true
5303
+ try {
5304
+ nodeRef.current.setPointerCapture(e.pointerId)
5305
+ } catch (err) {}
5306
+ }
5307
+ setPos((p) => ({
5308
+ ...p,
5309
+ x: Math.max(2, Math.min(window.innerWidth - 66, e.clientX - d.dx)),
5310
+ y: Math.max(2, Math.min(window.innerHeight - 82, e.clientY - d.dy)),
5311
+ }))
5312
+ }
5313
+ const onUp = () => {
5314
+ const d = dragRef.current
5315
+ dragRef.current = null
5316
+ if (d && !d.moved) setMenu((v) => !v)
5317
+ }
5318
+
5319
+ const style = {
5320
+ position: 'fixed',
5321
+ zIndex: 2147483000,
5322
+ width: '60px',
5323
+ height: '74px',
5324
+ display: 'flex',
5325
+ alignItems: 'flex-end',
5326
+ justifyContent: 'center',
5327
+ cursor: 'grab',
5328
+ userSelect: 'none',
5329
+ touchAction: 'none',
5330
+ filter: 'drop-shadow(0 6px 10px rgba(0,0,0,.28))',
5331
+ }
5332
+ if (pos.x === null) {
5333
+ style.right = '22px'
5334
+ style.bottom = '92px'
5335
+ } else {
5336
+ style.left = pos.x + 'px'
5337
+ style.top = pos.y + 'px'
5338
+ }
5339
+
5340
+ const bubble = {
5341
+ position: 'absolute',
5342
+ bottom: '100%',
5343
+ right: 0,
5344
+ marginBottom: '6px',
5345
+ display: 'flex',
5346
+ flexDirection: 'column',
5347
+ gap: '4px',
5348
+ padding: '6px',
5349
+ borderRadius: '10px',
5350
+ background: 'rgba(28,30,34,.92)',
5351
+ border: '1px solid rgba(255,255,255,.16)',
5352
+ boxShadow: '0 10px 24px rgba(0,0,0,.35)',
5353
+ }
5354
+ const bstyle = {
5355
+ padding: '5px 10px',
5356
+ borderRadius: '7px',
5357
+ border: '1px solid rgba(255,255,255,.18)',
5358
+ background: 'rgba(255,255,255,.08)',
5359
+ color: '#e8eaed',
5360
+ fontSize: '12px',
5361
+ cursor: 'pointer',
5362
+ whiteSpace: 'nowrap',
5363
+ }
5364
+
5365
+ return h(
5366
+ 'div',
5367
+ {
5368
+ ref: nodeRef,
5369
+ style,
5370
+ title: '点一下有菜单,按住可以拖走',
5371
+ onPointerDown: startDrag,
5372
+ onPointerMove: onMove,
5373
+ onPointerUp: onUp,
5374
+ onPointerCancel: onUp,
5375
+ },
5376
+ menu
5377
+ ? h(
5378
+ 'div',
5379
+ { style: bubble },
5380
+ h(
5381
+ 'button',
5382
+ {
5383
+ style: bstyle,
5384
+ onPointerDown: (e) => e.stopPropagation(),
5385
+ onClick: (e) => {
5386
+ e.stopPropagation()
5387
+ const next = randomCharacter(face)
5388
+ setFace(next)
5389
+ writeJson(K_CHARACTER, next)
5390
+ },
5391
+ },
5392
+ '换形象',
5393
+ ),
5394
+ h(
5395
+ 'button',
5396
+ {
5397
+ style: bstyle,
5398
+ onPointerDown: (e) => e.stopPropagation(),
5399
+ onClick: (e) => {
5400
+ e.stopPropagation()
5401
+ setMenu(false)
5402
+ setPos((p) => Object.assign({}, p, { hidden: true }))
5403
+ try {
5404
+ writeJson(K_PET, Object.assign({}, pos, { hidden: true }))
5405
+ } catch (err) {}
5406
+ },
5407
+ },
5408
+ '藏起来',
5409
+ ),
5410
+ )
5411
+ : null,
5412
+ h('div', { className: 'sc-pet-bob' }, h(Character, { face, size: 56 })),
5413
+ )
5414
+ }
5415
+
5416
+ /** 挂到 document.body 上,不跟着任何面板卸载;拿不到 react-dom 就退化 */
5417
+ function mountPet() {
5418
+ if (typeof document === 'undefined') return () => {}
5419
+ if (document.getElementById(PET_ID)) return () => {}
5420
+ const host = document.createElement('div')
5421
+ host.id = PET_ID
5422
+ document.body.appendChild(host)
5423
+
5424
+ const css = document.createElement('style')
5425
+ css.id = PET_ID + '-css'
5426
+ css.textContent =
5427
+ '@keyframes sc-pet-bob{0%,100%{transform:translateY(0)}50%{transform:translateY(-5px)}}' +
5428
+ '.sc-pet-bob{animation:sc-pet-bob 2.6s ease-in-out infinite}'
5429
+ document.head.appendChild(css)
5430
+
5431
+ let root = null
5432
+ try {
5433
+ const rd = require('react-dom/client')
5434
+ if (rd && rd.createRoot) {
5435
+ root = rd.createRoot(host)
5436
+ root.render(h(PetWidget))
5437
+ }
5438
+ } catch (e) {
5439
+ root = null
5440
+ }
5441
+
5442
+ if (!root) {
5443
+ host.textContent = '🐳'
5444
+ host.title = '拿不到 react-dom,先放个占位'
5445
+ host.style.cssText =
5446
+ 'position:fixed;right:22px;bottom:92px;z-index:2147483000;font-size:44px;cursor:default;user-select:none;filter:drop-shadow(0 6px 10px rgba(0,0,0,.28))'
5447
+ }
5448
+
5449
+ return () => {
5450
+ try {
5451
+ if (root) root.unmount()
5452
+ } catch (e) {}
5453
+ host.remove()
5454
+ css.remove()
5455
+ }
5456
+ }
5457
+
5458
+ /* ---------- 麻将 ---------- */
5459
+ const MJ_SUITS = ['万', '条', '筒']
5460
+ const MJ_RANKS = ['一', '二', '三', '四', '五', '六', '七', '八', '九']
5461
+ const MJ_SUIT_COLOR = ['#c0392b', '#1e8449', '#1f5fa8']
5462
+
5463
+ function mjShort(t) {
5464
+ return String((t % 9) + 1) + MJ_SUITS[Math.floor(t / 9)]
5465
+ }
5466
+
5467
+ /** 一张牌:图片存在就用图(<kind>.png),没有就显示文字 */
5468
+ function mjTileEl(base, t, size, opts) {
5469
+ const o = opts || {}
5470
+ const w = size || 34
5471
+ const el = document.createElement(o.button ? 'button' : 'span')
5472
+ el.style.cssText = [
5473
+ 'position:relative',
5474
+ 'display:inline-flex',
5475
+ 'align-items:center',
5476
+ 'justify-content:center',
5477
+ 'width:' + w + 'px',
5478
+ 'height:' + Math.round(w * 1.38) + 'px',
5479
+ 'border-radius:6px',
5480
+ 'background:#fffdf7',
5481
+ 'border:1px solid #e4d9c4',
5482
+ 'box-shadow:0 2px 0 #e4d9c4,0 3px 8px rgba(0,0,0,.12)',
5483
+ 'overflow:hidden',
5484
+ 'flex:0 0 auto',
5485
+ 'padding:0',
5486
+ 'font:700 ' + Math.max(10, Math.round(w * 0.4)) + 'px/1 system-ui,sans-serif',
5487
+ 'color:' + MJ_SUIT_COLOR[Math.floor(t / 9)],
5488
+ 'cursor:' + (o.onClick ? 'pointer' : 'default'),
5489
+ o.selected ? 'outline:3px solid #ff5fa2;outline-offset:1px' : '',
5490
+ o.dim ? 'opacity:.5' : '',
5491
+ ]
5492
+ .filter(Boolean)
5493
+ .join(';')
5494
+ const txt = document.createElement('span')
5495
+ txt.textContent = mjShort(t)
5496
+ el.appendChild(txt)
5497
+ const img = new Image()
5498
+ img.alt = ''
5499
+ img.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;object-fit:cover'
5500
+ img.onload = () => {
5501
+ txt.style.visibility = 'hidden'
5502
+ el.appendChild(img)
5503
+ }
5504
+ img.src = base + t + '.png'
5505
+ if (o.onClick) el.addEventListener('click', o.onClick)
5506
+ return el
5507
+ }
5508
+
5509
+ function openMahjong(opts) {
5510
+ const auth = opts.auth
5511
+ const onToast = opts.onToast || (() => {})
5512
+ const base = auth.server.replace(/\/+$/, '')
5513
+ const tileBase = base + '/mj/'
5514
+
5515
+ const B =
5516
+ 'padding:6px 10px;border-radius:9px;border:1.5px solid #ffd3e6;background:#fff;color:#5b3a63;font-size:12px;font-weight:650;cursor:pointer'
5517
+ const wrap = document.createElement('div')
5518
+ wrap.style.cssText = [
5519
+ 'position:fixed',
5520
+ 'right:18px',
5521
+ 'bottom:18px',
5522
+ 'width:520px',
5523
+ 'max-width:calc(100vw - 20px)',
5524
+ 'height:600px',
5525
+ 'max-height:calc(100vh - 30px)',
5526
+ 'z-index:2147483646',
5527
+ 'display:flex',
5528
+ 'flex-direction:column',
5529
+ 'border-radius:18px',
5530
+ 'background:linear-gradient(180deg,#fff8fc,#f4f9ff)',
5531
+ 'border:2px solid #ffd3e6',
5532
+ 'box-shadow:0 26px 70px rgba(255,95,162,.28)',
5533
+ 'font:13px/1.5 system-ui,-apple-system,"Segoe UI",sans-serif',
5534
+ 'color:#3b2b45',
5535
+ 'overflow:hidden',
5536
+ ].join(';')
5537
+ wrap.innerHTML =
5538
+ '<div style="display:flex;align-items:center;gap:8px;padding:10px 12px;border-bottom:2px solid #ffd9ec">' +
5539
+ '<b style="font-size:14px">🀄 麻将</b>' +
5540
+ '<span data-room style="font-size:12px;color:#a184b3"></span>' +
5541
+ '<span data-score style="font-size:12px;color:#b14a86;font-weight:700"></span>' +
5542
+ '<span style="flex:1"></span>' +
5543
+ '<button data-close style="' +
5544
+ B +
5545
+ '">✕</button>' +
5546
+ '</div>' +
5547
+ '<div data-body style="flex:1;min-height:0;overflow:auto;padding:10px 12px"></div>'
5548
+ document.body.appendChild(wrap)
5549
+ attachScaler(wrap, 'mahjong')
5550
+ attachDragger(wrap, 'mahjong')
5551
+
5552
+ const $ = (s) => wrap.querySelector(s)
5553
+ const bodyEl = $('[data-body]')
5554
+ const roomEl = $('[data-room]')
5555
+ const hint = document.createElement('div')
5556
+ hint.style.cssText = 'font-size:11px;color:#b0629a;padding:2px 4px 6px'
5557
+
5558
+ let roomId = ''
5559
+ let seat = -1
5560
+ let state = null
5561
+ let room = null
5562
+ let timer = null
5563
+ let stopped = false
5564
+
5565
+ const api2 = (m, path, b) =>
5566
+ api(auth.server, path, { method: m, token: auth.token, body: b })
5567
+
5568
+ const chip = (t) => {
5569
+ const s = document.createElement('span')
5570
+ s.textContent = t
5571
+ s.style.cssText =
5572
+ 'font-size:11px;padding:1px 7px;border-radius:99px;background:#ffe3f0;color:#b14a86;border:1px solid #ffd3e6'
5573
+ return s
5574
+ }
5575
+
5576
+ const btn = (t, fn, primary) => {
5577
+ const b = document.createElement('button')
5578
+ b.textContent = t
5579
+ b.style.cssText = primary
5580
+ ? 'padding:7px 14px;border-radius:10px;border:none;background:linear-gradient(135deg,#ff5fa2,#a86bff);color:#fff;font-size:12.5px;font-weight:700;cursor:pointer;box-shadow:0 6px 16px rgba(255,95,162,.3)'
5581
+ : B
5582
+ b.addEventListener('click', fn)
5583
+ return b
5584
+ }
5585
+
5586
+ /* ---------- 大厅 ---------- */
5587
+ const renderLobby = async () => {
5588
+ bodyEl.textContent = ''
5589
+ roomEl.textContent = ''
5590
+ const title = document.createElement('div')
5591
+ title.textContent = '开一桌(缺的位置由机器人补)'
5592
+ title.style.cssText = 'font-size:12px;color:#a184b3;margin:2px 0 10px'
5593
+ bodyEl.appendChild(title)
5594
+ bodyEl.appendChild(btn('+ 新建牌桌', async () => {
5595
+ try {
5596
+ const r = await api2('POST', '/api/mj/rooms')
5597
+ roomId = r.room.id
5598
+ seat = 0
5599
+ render()
5600
+ } catch (e) {
5601
+ onToast('建房失败:' + friendly(e))
5602
+ }
5603
+ }, true))
5604
+
5605
+ const listWrap = document.createElement('div')
5606
+ listWrap.style.cssText = 'margin-top:14px;display:flex;flex-direction:column;gap:6px'
5607
+ bodyEl.appendChild(listWrap)
5608
+ try {
5609
+ const r = await api2('GET', '/api/mj/rooms')
5610
+ const rooms = (r.rooms || []).filter((x) => !x.ended)
5611
+ if (!rooms.length) {
5612
+ const e = document.createElement('div')
5613
+ e.textContent = '还没有牌桌,点上面新建一个'
5614
+ e.style.cssText = 'font-size:12px;color:#b39fc4;padding:6px 2px'
5615
+ listWrap.appendChild(e)
5616
+ }
5617
+ for (const rm of rooms) {
5618
+ const row = document.createElement('div')
5619
+ row.style.cssText =
5620
+ 'display:flex;align-items:center;gap:8px;padding:7px 9px;border-radius:10px;background:#fff;border:1.5px solid #ffe3f0'
5621
+ const t = document.createElement('span')
5622
+ t.textContent = '#' + rm.id + (rm.started ? ' · 进行中' : ' · 等人')
5623
+ t.style.cssText = 'flex:1;font-size:12px'
5624
+ row.appendChild(t)
5625
+ row.appendChild(chip(rm.players.filter((p) => p.id).length + '/4'))
5626
+ row.appendChild(
5627
+ btn('加入', async () => {
5628
+ try {
5629
+ const j = await api2('POST', '/api/mj/rooms/' + rm.id + '/join')
5630
+ roomId = rm.id
5631
+ seat = j.seat
5632
+ render()
5633
+ } catch (e) {
5634
+ onToast('加入失败:' + friendly(e))
5635
+ }
5636
+ }),
5637
+ )
5638
+ listWrap.appendChild(row)
5639
+ }
5640
+ } catch (e) {
5641
+ hint.textContent = '房间列表读取失败'
5642
+ }
5643
+ }
5644
+
5645
+ /* ---------- 牌桌 ---------- */
5646
+ const renderTable = () => {
5647
+ bodyEl.textContent = ''
5648
+ roomEl.textContent = '房间 ' + roomId
5649
+ const s = state
5650
+ if (!s) return
5651
+
5652
+ const meInfo = room.players[seat] || { name: '我' }
5653
+
5654
+ // 对家
5655
+ const top = document.createElement('div')
5656
+ top.style.cssText = 'display:flex;align-items:center;gap:8px;justify-content:center;margin-bottom:8px'
5657
+ const opp2 = room.players[2] || { name: '空位' }
5658
+ top.appendChild(
5659
+ chip(opp2.name + ' · ' + (opp2.score || 0) + '分 · ' + (s.seats[2].handCount || 0) + ' 张'),
5660
+ )
5661
+ if (s.turn === 2 && !s.ended) top.appendChild(chip('出牌中'))
5662
+ bodyEl.appendChild(top)
5663
+
5664
+ // 左右 + 牌河
5665
+ const mid = document.createElement('div')
5666
+ mid.style.cssText = 'display:flex;gap:8px;align-items:flex-start'
5667
+ const side = (i) => {
5668
+ const box = document.createElement('div')
5669
+ box.style.cssText = 'width:78px;flex:0 0 auto;display:flex;flex-direction:column;gap:4px'
5670
+ const p = room.players[i] || { name: '空位' }
5671
+ box.appendChild(chip(p.name))
5672
+ box.appendChild(chip((p.score || 0) + ' 分'))
5673
+ box.appendChild(chip((s.seats[i].handCount || 0) + ' 张'))
5674
+ if (s.turn === i && !s.ended) box.appendChild(chip('出牌中'))
5675
+ return box
5676
+ }
5677
+ mid.appendChild(side(3))
5678
+
5679
+ const pool = document.createElement('div')
5680
+ pool.style.cssText =
5681
+ 'flex:1;min-width:0;background:#024d3a;border-radius:12px;padding:6px;display:flex;flex-wrap:wrap;gap:2px;align-content:flex-start;min-height:96px'
5682
+ s.discards.forEach((arr, i) => {
5683
+ for (const t of arr) {
5684
+ const tile = mjTileEl(tileBase, t, 20)
5685
+ if (s.lastDiscard && s.lastDiscard.tile === t && i === s.lastDiscard.seat) {
5686
+ tile.style.outline = '2px solid #ffcf3d'
5687
+ }
5688
+ pool.appendChild(tile)
5689
+ }
5690
+ })
5691
+ mid.appendChild(pool)
5692
+ mid.appendChild(side(1))
5693
+ bodyEl.appendChild(mid)
5694
+
5695
+ // 我的副露
5696
+ const melds = document.createElement('div')
5697
+ melds.style.cssText = 'display:flex;gap:4px;flex-wrap:wrap;margin:8px 0 4px;min-height:26px'
5698
+ for (const m of s.seats[seat].melds || []) {
5699
+ const g = document.createElement('div')
5700
+ g.style.cssText = 'display:flex;gap:1px'
5701
+ const n = m.type === 'gang' ? 4 : 3
5702
+ for (let k = 0; k < n; k++) g.appendChild(mjTileEl(tileBase, m.tile, 22))
5703
+ melds.appendChild(g)
5704
+ }
5705
+ bodyEl.appendChild(melds)
5706
+
5707
+ // 顶部状态
5708
+ const status = document.createElement('div')
5709
+ status.style.cssText = 'display:flex;gap:6px;align-items:center;margin:2px 0 6px'
5710
+ status.appendChild(chip('牌墙 ' + s.wallCount))
5711
+ status.appendChild(chip(meInfo.name))
5712
+ if (s.ended) {
5713
+ status.appendChild(
5714
+ chip(s.winner === null ? '流局' : (room.players[s.winner] || {}).name + ' 胡了'),
5715
+ )
5716
+ } else if (s.turn === seat) {
5717
+ status.appendChild(chip('轮到你了'))
5718
+ }
5719
+ bodyEl.appendChild(status)
5720
+
5721
+ // 结算:谁赢谁输,各加减多少分
5722
+ if (s.ended && room.deltas) {
5723
+ const settleRow = document.createElement('div')
5724
+ settleRow.style.cssText = 'display:flex;gap:6px;flex-wrap:wrap;margin:0 0 8px'
5725
+ room.players.forEach((p, i) => {
5726
+ const d = room.deltas[i] || 0
5727
+ const c = document.createElement('span')
5728
+ c.textContent = p.name + ' ' + (d > 0 ? '+' : '') + d
5729
+ c.style.cssText =
5730
+ 'font-size:11.5px;padding:2px 8px;border-radius:99px;border:1px solid ' +
5731
+ (d > 0 ? '#3ddc97' : d < 0 ? '#ff5fa2' : '#e4dbe8') +
5732
+ ';background:' +
5733
+ (d > 0 ? '#e9fbf2' : d < 0 ? '#ffeaf3' : '#faf7fb') +
5734
+ ';color:' +
5735
+ (d > 0 ? '#12855a' : d < 0 ? '#c0295f' : '#9a8ba6')
5736
+ settleRow.appendChild(c)
5737
+ })
5738
+ bodyEl.appendChild(settleRow)
5739
+ }
5740
+
5741
+ // 我的手牌
5742
+ const handWrap = document.createElement('div')
5743
+ handWrap.style.cssText = 'display:flex;gap:3px;flex-wrap:wrap;margin-bottom:8px'
5744
+ const hand = s.seats[seat].hand || []
5745
+ for (const t of hand) {
5746
+ handWrap.appendChild(
5747
+ mjTileEl(tileBase, t, 34, {
5748
+ button: true,
5749
+ dim: !(s.turn === seat && s.phase === 'discard' && !s.ended),
5750
+ onClick:
5751
+ s.turn === seat && s.phase === 'discard' && !s.ended
5752
+ ? () => act({ type: 'discard', tile: t })
5753
+ : null,
5754
+ }),
5755
+ )
5756
+ }
5757
+ bodyEl.appendChild(handWrap)
5758
+
5759
+ // 操作
5760
+ const acts = document.createElement('div')
5761
+ acts.style.cssText = 'display:flex;gap:6px;flex-wrap:wrap;align-items:center'
5762
+ if (!s.ended) {
5763
+ for (const op of s.options || []) {
5764
+ const label = op === 'hu' ? '胡' : op === 'gang' ? '杠' : '碰'
5765
+ acts.appendChild(btn(label, () => act({ type: op }), true))
5766
+ }
5767
+ if ((s.options || []).length) acts.appendChild(btn('过', () => act({ type: 'pass' })))
5768
+ if (s.turn === seat && s.phase === 'discard' && s.seats[seat].drawn !== null) {
5769
+ acts.appendChild(btn('自摸', () => act({ type: 'zimo' })))
5770
+ }
5771
+ } else {
5772
+ acts.appendChild(btn('再来一局', () => act({ type: 'restart' }), true))
5773
+ acts.appendChild(btn('回大厅', () => {
5774
+ state = null
5775
+ room = null
5776
+ roomId = ''
5777
+ seat = -1
5778
+ renderLobby()
5779
+ }))
5780
+ }
5781
+ bodyEl.appendChild(acts)
5782
+ }
5783
+
5784
+ const render = async () => {
5785
+ if (stopped || !roomId) return
5786
+ try {
5787
+ const r = await api2('GET', '/api/mj/rooms/' + roomId + '/state')
5788
+ room = r.room
5789
+ seat = r.seat
5790
+ state = r.state
5791
+ if (room && seat >= 0 && room.players[seat]) {
5792
+ $('[data-score]').textContent = '积分 ' + (room.players[seat].score || 0)
5793
+ }
5794
+ if (!state) renderWaiting()
5795
+ else renderTable()
5796
+ } catch (e) {
5797
+ hint.textContent = '状态读取失败'
5798
+ }
5799
+ }
5800
+
5801
+ const renderWaiting = () => {
5802
+ bodyEl.textContent = ''
5803
+ roomEl.textContent = '房间 ' + roomId
5804
+ const t = document.createElement('div')
5805
+ t.textContent = '等房主开局(房间号 ' + roomId + ',发给朋友就能进)'
5806
+ t.style.cssText = 'font-size:12px;color:#a184b3;margin:6px 2px'
5807
+ bodyEl.appendChild(t)
5808
+ const who = document.createElement('div')
5809
+ who.style.cssText = 'display:flex;flex-direction:column;gap:4px;margin:8px 0'
5810
+ for (const p of room.players) who.appendChild(chip(p.seat + 1 + ' 号位 ' + p.name))
5811
+ bodyEl.appendChild(who)
5812
+ if (room.owner === auth.id) {
5813
+ bodyEl.appendChild(
5814
+ btn('开局', async () => {
5815
+ try {
5816
+ await api2('POST', '/api/mj/rooms/' + roomId + '/start')
5817
+ render()
5818
+ } catch (e) {
5819
+ onToast('开局失败:' + friendly(e))
5820
+ }
5821
+ }, true),
5822
+ )
5823
+ }
5824
+ }
5825
+
5826
+ const act = async (payload) => {
5827
+ try {
5828
+ if (payload.type === 'restart') {
5829
+ await api2('POST', '/api/mj/rooms/' + roomId + '/start')
5830
+ } else {
5831
+ await api2('POST', '/api/mj/rooms/' + roomId + '/act', payload)
5832
+ }
5833
+ await render()
5834
+ } catch (e) {
5835
+ onToast('操作失败:' + friendly(e))
5836
+ }
5837
+ }
5838
+
5839
+ // 只轮询牌桌;大厅不刷,避免列表一直闪
5840
+ const tick = async () => {
5841
+ if (stopped || !roomId) return
5842
+ await render()
5843
+ }
5844
+
5845
+ $('[data-close]').addEventListener('click', () => {
5846
+ stopped = true
5847
+ window.clearInterval(timer)
5848
+ wrap.remove()
5849
+ })
5850
+
5851
+ renderLobby()
5852
+ timer = window.setInterval(tick, 1300)
5853
+ return { close: () => wrap.remove() }
5854
+ }
5855
+
5856
+
5857
+
5858
+ /**
5859
+ * 让浮动窗口能用标题栏拖动,位置按窗口分别记在本地。
5860
+ * 注意:窗口上有 transform: scale(),getBoundingClientRect 拿到的是缩放后的坐标,
5861
+ * 拿它回写 left/top 会形成偏移反馈(越拖越偏左上)。所以全程用未变换的 offsetLeft/Top。
5862
+ */
5863
+ function attachDragger(el, key) {
5864
+ const SK = 'dsh-share-chat.pos.' + key
5865
+ const handle = el.firstElementChild
5866
+ if (!handle) return
5867
+ const place = (x, y) => {
5868
+ const w = el.offsetWidth || 200
5869
+ x = Math.min(Math.max(-w + 80, x), window.innerWidth - 80)
5870
+ y = Math.min(Math.max(0, y), window.innerHeight - 44)
5871
+ el.style.left = x + 'px'
5872
+ el.style.top = y + 'px'
5873
+ el.style.right = 'auto'
5874
+ el.style.bottom = 'auto'
5875
+ }
5876
+ const saved = readJson(SK)
5877
+ if (saved && typeof saved.x === 'number' && typeof saved.y === 'number') {
5878
+ place(saved.x, saved.y)
5879
+ } else {
5880
+ const r = el.getBoundingClientRect()
5881
+ const sc = el.__scale || 1
5882
+ place(r.left, r.top)
5883
+ if (sc !== 1) {
5884
+ // 首次接管时把缩放造成的视觉偏移换算回布局坐标
5885
+ place(el.offsetLeft, el.offsetTop)
5886
+ }
5887
+ }
5888
+
5889
+ handle.style.cursor = 'move'
5890
+ handle.style.userSelect = 'none'
5891
+ handle.addEventListener('mousedown', (e) => {
5892
+ if (e.target && e.target.closest && e.target.closest('button')) return
5893
+ e.preventDefault()
5894
+ const startX = el.offsetLeft
5895
+ const startY = el.offsetTop
5896
+ const mx = e.clientX
5897
+ const my = e.clientY
5898
+ const move = (ev) => {
5899
+ const sc = el.__scale || 1
5900
+ place(startX + (ev.clientX - mx) / sc, startY + (ev.clientY - my) / sc)
5901
+ }
5902
+ const up = () => {
5903
+ document.removeEventListener('mousemove', move)
5904
+ document.removeEventListener('mouseup', up)
5905
+ writeJson(SK, { x: el.offsetLeft, y: el.offsetTop })
5906
+ }
5907
+ document.addEventListener('mousemove', move)
5908
+ document.addEventListener('mouseup', up)
5909
+ })
5910
+ }
5911
+
5912
+ /** 给浮动窗口加一个等比缩放手柄(右下角),比例按窗口分别记在本地 */
5913
+ function attachScaler(el, key) {
5914
+ const SK = 'dsh-share-chat.scale.' + key
5915
+ let scale = Number(readJson(SK)) || 1
5916
+ if (!(scale >= 0.6 && scale <= 1.6)) scale = 1
5917
+ el.style.transformOrigin = 'bottom right'
5918
+ const apply = () => {
5919
+ el.__scale = scale
5920
+ el.style.transform = scale === 1 ? '' : 'scale(' + scale.toFixed(3) + ')'
5921
+ }
5922
+ apply()
5923
+ const h = document.createElement('div')
5924
+ h.title = '拖动改变大小'
5925
+ h.style.cssText =
5926
+ 'position:absolute;right:2px;bottom:2px;width:14px;height:14px;cursor:nwse-resize;' +
5927
+ 'border-radius:3px;background:rgba(0,0,0,.10);z-index:2147483647'
5928
+ el.appendChild(h)
5929
+ h.addEventListener('mousedown', (e) => {
5930
+ e.preventDefault()
5931
+ e.stopPropagation()
5932
+ const sx = e.clientX
5933
+ const sy = e.clientY
5934
+ const start = scale
5935
+ const move = (ev) => {
5936
+ const d = ev.clientX - sx + (ev.clientY - sy)
5937
+ scale = Math.min(1.6, Math.max(0.6, start + d / 500))
5938
+ apply()
5939
+ }
5940
+ const up = () => {
5941
+ document.removeEventListener('mousemove', move)
5942
+ document.removeEventListener('mouseup', up)
5943
+ writeJson(SK, scale)
5944
+ }
5945
+ document.addEventListener('mousemove', move)
5946
+ document.addEventListener('mouseup', up)
5947
+ })
5948
+ }
5949
+
5950
+ /* ---------- 每日杀手数独 ---------- */
5951
+ /* ---------- 每日杀手数独 ---------- */
5952
+ function openKiller(opts) {
5953
+ const auth = opts.auth
5954
+ const onToast = opts.onToast || (() => {})
5955
+
5956
+ // 组合枚举:从 1..9 里挑 n 个数,和等于 s
5957
+ const combos = (s, n) => {
5958
+ const out = []
5959
+ const cur = []
5960
+ const go = (start, left, sum) => {
5961
+ if (left === 0) {
5962
+ if (sum === s) out.push(cur.slice())
5963
+ return
5964
+ }
5965
+ for (let d = start; d <= 9; d++) {
5966
+ if (sum + d > s) break
5967
+ if (sum + d + ((left - 1) * (d + 1 + (d + left - 1))) / 2 > s + 0.5) {
5968
+ /* 粗略上界剪枝,交给下面继续 */
5969
+ }
5970
+ cur.push(d)
5971
+ go(d + 1, left - 1, sum + d)
5972
+ cur.pop()
5973
+ }
5974
+ }
5975
+ if (n > 0 && n <= 9) go(1, n, 0)
5976
+ return out
5977
+ }
5978
+
5979
+ const wrap = document.createElement('div')
5980
+ wrap.style.cssText = [
5981
+ 'position:fixed', 'right:18px', 'bottom:18px', 'width:820px', 'max-width:calc(100vw - 16px)',
5982
+ 'height:640px', 'max-height:calc(100vh - 24px)', 'z-index:2147483646', 'display:flex', 'flex-direction:column',
5983
+ 'border-radius:16px', 'background:#fbfcfe', 'border:2px solid #dbe4f0',
5984
+ 'box-shadow:0 24px 60px rgba(30,50,90,.28)',
5985
+ 'font:13px/1.5 system-ui,-apple-system,"Segoe UI",sans-serif', 'color:#1f2a37', 'overflow:hidden',
5986
+ ].join(';')
5987
+ wrap.innerHTML =
5988
+ '<div style="display:flex;align-items:center;gap:8px;padding:10px 12px;border-bottom:1px solid #e3eaf4;flex:0 0 auto">' +
5989
+ '<b style="font-size:14px">🧩 杀手数独</b>' +
5990
+ '<span data-day style="font-size:12px;color:#7b8ca6"></span>' +
5991
+ '<span data-stars style="font-size:12px;color:#d99a1f;font-weight:600"></span>' +
5992
+ '<button data-shop style="padding:4px 9px;border-radius:8px;border:1px solid #ffdca8;background:#fff8ec;color:#9a6a12;font:600 12px system-ui;cursor:pointer">🛍 商店</button>' +
5993
+ '<button data-cal style="padding:4px 9px;border-radius:8px;border:1px solid #dbe4f0;background:#fff;font:600 12px system-ui;cursor:pointer">📅 日历</button>' +
5994
+ '<span data-timer style="font-size:12px;color:#7b8ca6;margin-left:auto"></span>' +
5995
+ '<button data-close style="padding:5px 9px;border-radius:8px;border:1px solid #dbe4f0;background:#fff;cursor:pointer">✕</button>' +
5996
+ '</div>' +
5997
+ '<div style="display:flex;flex:1;min-height:0;position:relative">' +
5998
+ '<div data-left style="flex:0 0 auto;overflow:auto;padding:10px 12px 12px;background:#fff">' +
5999
+ '<div data-sel></div>' +
6000
+ '<div data-body></div>' +
6001
+ '</div>' +
6002
+ '<div data-panel style="flex:1;min-width:0;border-left:1px solid #e3eaf4;overflow:auto;padding:12px">' +
6003
+ '<div data-dyn></div>' +
6004
+ '<div data-calc style="border:1px solid #e6edf6;border-radius:10px;padding:8px 10px;background:#fff"></div>' +
6005
+ '</div>' +
6006
+ '</div>'
6007
+ document.body.appendChild(wrap)
6008
+ attachScaler(wrap, 'killer')
6009
+ attachDragger(wrap, 'killer')
6010
+
6011
+ const $ = (s) => wrap.querySelector(s)
6012
+ const bodyEl = $('[data-body]')
6013
+ const selEl = $('[data-sel]')
6014
+ const dynEl = $('[data-dyn]')
6015
+ const calcEl = $('[data-calc]')
6016
+ const leftEl = $('[data-left]')
6017
+
6018
+ const ROW = (i) => (i / 9) | 0
6019
+ const COL = (i) => i % 9
6020
+ const BOX = (i) => ((ROW(i) / 3) | 0) * 3 + ((COL(i) / 3) | 0)
6021
+
6022
+ let day = ''
6023
+ let curSource = ''
6024
+ let curStale = false
6025
+ let puzzles = []
6026
+ let curIdx = 0
6027
+ let cages = []
6028
+ let owner = null
6029
+ let marks = [] // { v, p:[], u:[] }
6030
+ let selSet = new Set()
6031
+ let cells = []
6032
+ let baseMs = 0 // 之前累计的用时
6033
+ let runFrom = 0 // 本次开始计时的时刻;0 = 停表状态
6034
+ let timer = null
6035
+ let done = false
6036
+ let pencilMode = false
6037
+ let dragSel = null
6038
+ let myStars = 0
6039
+ const starsFor = (d) => Math.min(5, Math.max(1, Math.ceil((Number(d) || 1) / 2)))
6040
+ const renderStars = () => {
6041
+ const el = $('[data-stars]')
6042
+ if (el) el.textContent = myStars > 0 ? '★ ' + myStars : ''
6043
+ }
6044
+ // 被玩家判定为「不可能」的组合:key = c<笼号>:<数字> 或 k<和>-<格数>:<数字>
6045
+ let offCombos = new Set()
6046
+
6047
+ /** 组合做成开关按钮:亮=可能,灰=已排除;点一下切换,状态跨选格保留 */
6048
+ const comboBtn = (digits, key) => {
6049
+ const b = document.createElement('button')
6050
+ const isOff = offCombos.has(key)
6051
+ b.textContent = digits
6052
+ b.style.cssText = [
6053
+ 'font:600 12.5px ui-monospace,monospace',
6054
+ 'padding:5px 10px',
6055
+ 'border-radius:9px',
6056
+ 'cursor:pointer',
6057
+ 'letter-spacing:0.5px',
6058
+ 'transition:background .12s,color .12s,border-color .12s',
6059
+ 'border:1px solid ' + (isOff ? '#dfe5ee' : '#a9c6ee'),
6060
+ 'background:' + (isOff ? '#f1f4f8' : '#e8f1ff'),
6061
+ 'color:' + (isOff ? '#b3bfcf' : '#2f558a'),
6062
+ isOff ? 'text-decoration:line-through' : '',
6063
+ ]
6064
+ .filter(Boolean)
6065
+ .join(';')
6066
+ b.addEventListener('click', () => {
6067
+ if (offCombos.has(key)) offCombos.delete(key)
6068
+ else offCombos.add(key)
6069
+ save()
6070
+ paint()
6071
+ })
6072
+ return b
6073
+ }
6074
+
6075
+ // 松开鼠标就结束拖选(不管松在哪个格子)
6076
+ const endDrag = () => {
6077
+ dragSel = null
6078
+ }
6079
+ window.addEventListener('mouseup', endDrag)
6080
+
6081
+ const fmt = (ms) => {
6082
+ const s = Math.floor(ms / 1000)
6083
+ return String(Math.floor(s / 60)).padStart(2, '0') + ':' + String(s % 60).padStart(2, '0')
6084
+ }
6085
+
6086
+ const puzzleKey = () =>
6087
+ 'dsh-share-chat.killer.' + day + '.' + (puzzles[curIdx] ? puzzles[curIdx].number : 'x')
6088
+
6089
+ const blankMarks = () => Array.from({ length: 81 }, () => ({ v: 0, p: [], u: [] }))
6090
+
6091
+ const values = () => marks.map((m) => m.v)
6092
+
6093
+ const save = () => {
6094
+ try {
6095
+ writeJson(puzzleKey(), {
6096
+ marks: marks.map((m) => ({ v: m.v, p: m.p, u: m.u })),
6097
+ off: [...offCombos],
6098
+ elapsed: currentMs(),
6099
+ })
6100
+ } catch (e) {}
6101
+ }
6102
+
6103
+ const tickTimer = () => {
6104
+ window.clearInterval(timer)
6105
+ if (!runFrom) return
6106
+ timer = window.setInterval(() => {
6107
+ $('[data-timer]').textContent = fmt(currentMs())
6108
+ }, 1000)
6109
+ }
6110
+
6111
+ /** 当前累计用时(关窗后不再增长) */
6112
+ const currentMs = () => baseMs + (runFrom ? Date.now() - runFrom : 0)
6113
+
6114
+ const startClock = () => {
6115
+ if (runFrom) return
6116
+ runFrom = Date.now()
6117
+ tickTimer()
6118
+ }
6119
+
6120
+ /** 停表:把本次这一段并入 baseMs */
6121
+ const stopClock = () => {
6122
+ if (runFrom) {
6123
+ baseMs += Date.now() - runFrom
6124
+ runFrom = 0
6125
+ }
6126
+ window.clearInterval(timer)
6127
+ timer = null
6128
+ $('[data-timer]').textContent = baseMs ? fmt(baseMs) : ''
6129
+ }
6130
+
6131
+ const conflicts = () => {
6132
+ const g = values()
6133
+ const bad = new Set()
6134
+ for (let i = 0; i < 81; i++) {
6135
+ const v = g[i]
6136
+ if (!v) continue
6137
+ for (let j = 0; j < 81; j++) {
6138
+ if (j === i || g[j] !== v) continue
6139
+ if (ROW(j) === ROW(i) || COL(j) === COL(i) || BOX(j) === BOX(i)) bad.add(i).add(j)
6140
+ }
6141
+ }
6142
+ for (const cage of cages) {
6143
+ const seen = new Map()
6144
+ for (const i of cage.cells) {
6145
+ const v = g[i]
6146
+ if (!v) continue
6147
+ if (seen.has(v)) {
6148
+ bad.add(i)
6149
+ bad.add(seen.get(v))
6150
+ } else seen.set(v, i)
6151
+ }
6152
+ if (cage.cells.every((i) => g[i] > 0)) {
6153
+ const s = cage.cells.reduce((a, i) => a + g[i], 0)
6154
+ if (s !== cage.sum) for (const i of cage.cells) bad.add(i)
6155
+ }
6156
+ }
6157
+ return bad
6158
+ }
6159
+
6160
+ const paint = () => {
6161
+ const g = values()
6162
+ // 填满之前不给对错提示,否则靠试凑就能试出来
6163
+ const bad = new Set()
6164
+ const single = selSet.size === 1 ? [...selSet][0] : -1
6165
+ const selVal = single >= 0 ? g[single] : 0
6166
+ for (let i = 0; i < 81; i++) {
6167
+ const cell = cells[i]
6168
+ const m = marks[i]
6169
+ cell.textContent = ''
6170
+ if (m.v) {
6171
+ const span = document.createElement('span')
6172
+ span.textContent = String(m.v)
6173
+ span.style.cssText =
6174
+ 'font:600 21px system-ui;color:' + (bad.has(i) ? '#d9534f' : '#1f2a37')
6175
+ cell.appendChild(span)
6176
+ } else if (m.p.length) {
6177
+ const grid = document.createElement('div')
6178
+ grid.style.cssText =
6179
+ 'position:absolute;inset:2px;display:grid;grid-template-columns:repeat(3,1fr);grid-template-rows:repeat(3,1fr);font:600 8.5px/1 system-ui;color:#5b7194'
6180
+ for (let d = 1; d <= 9; d++) {
6181
+ const c = document.createElement('span')
6182
+ c.style.cssText =
6183
+ 'display:flex;align-items:center;justify-content:center;' +
6184
+ (m.p.includes(d) ? '' : 'opacity:0')
6185
+ c.textContent = String(d)
6186
+ if (m.p.includes(d) && m.u.includes(d)) c.style.textDecoration = 'underline'
6187
+ grid.appendChild(c)
6188
+ }
6189
+ cell.appendChild(grid)
6190
+ }
6191
+ if (cageStart.has(i)) {
6192
+ const lab = document.createElement('span')
6193
+ lab.textContent = String(cageSum.get(i))
6194
+ lab.style.cssText =
6195
+ 'position:absolute;top:0px;left:2px;font:600 9.5px/1 ui-monospace,monospace;color:#6b7f9e'
6196
+ cell.appendChild(lab)
6197
+ }
6198
+ let bg = '#fff'
6199
+ if (bad.has(i)) bg = '#fde8e8'
6200
+ else if (selSet.has(i)) bg = '#dbe9ff'
6201
+ else if (m.v && selVal && m.v === selVal) bg = '#eef4ff'
6202
+ cell.style.background = bg
6203
+ }
6204
+ renderPanel()
6205
+ }
6206
+
6207
+ let cageStart = new Set()
6208
+ let cageSum = new Map()
6209
+
6210
+ const renderPanel = () => {
6211
+ dynEl.textContent = ''
6212
+ const g = values()
6213
+ const box = document.createElement('div')
6214
+ box.style.cssText = 'display:flex;flex-direction:column;gap:8px'
6215
+
6216
+ // 选中信息:这一行位置固定。
6217
+ // 只有当选中范围完整覆盖了它碰到的每一个笼时,和才是「用笼能算出来」的;
6218
+ // 只要有一格所在的笼没被选全,就算不出,直接留空。
6219
+ const selList = [...selSet]
6220
+ const line = document.createElement('div')
6221
+ line.style.cssText = 'font-size:12px;min-height:19px;font-weight:600;color:#4a6a92'
6222
+ if (!selList.length) {
6223
+ line.textContent = '还没选格子 · 按住左键拖过去可以选多格'
6224
+ line.style.color = '#a7b6c9'
6225
+ line.style.fontWeight = '400'
6226
+ } else {
6227
+ const touched = new Set(selList.map((k) => owner[k]))
6228
+ const allCovered = [...touched].every(
6229
+ (ci) => cages[ci] && cages[ci].cells.every((k) => selSet.has(k)),
6230
+ )
6231
+ if (allCovered) {
6232
+ let sum = 0
6233
+ for (const ci of touched) sum += cages[ci].sum
6234
+ line.textContent = '选中 ' + selList.length + ' 格 · 和 ' + sum
6235
+ } else {
6236
+ line.textContent = ''
6237
+ }
6238
+ }
6239
+ const selBox = document.createElement('div')
6240
+ selBox.style.cssText = 'border:1px solid #e6edf6;border-radius:10px;padding:8px 10px;background:#fff;margin-bottom:8px'
6241
+ selBox.appendChild(line)
6242
+ box.appendChild(selBox)
6243
+
6244
+ // 组合提示:常显。没选格子就留个说明,选一个格子就列它所在笼的组合
6245
+ {
6246
+ const head = document.createElement('div')
6247
+ head.style.cssText = 'font-size:12px;color:#4a6a92;font-weight:600;margin-top:2px'
6248
+ const bodyC = document.createElement('div')
6249
+ bodyC.style.cssText = 'display:flex;flex-wrap:wrap;gap:4px;min-height:20px'
6250
+
6251
+ let list = null
6252
+ let label = ''
6253
+ let cageId = -1
6254
+ // 选中都在同一个笼里时,永远按「笼最初的和与格数」给全部组合:
6255
+ // 不管选了几格、也不管已经填了什么。跨笼选择则不显示组合。
6256
+ if (selSet.size >= 1) {
6257
+ const owners = new Set([...selSet].map((k) => owner[k]))
6258
+ if (owners.size === 1) {
6259
+ const ci = [...owners][0]
6260
+ const cage = cages[ci]
6261
+ if (cage) {
6262
+ cageId = ci
6263
+ list = combos(cage.sum, cage.cells.length)
6264
+ label =
6265
+ '这个笼的组合(' +
6266
+ cage.sum +
6267
+ ' / ' +
6268
+ cage.cells.length +
6269
+ ' 格)' +
6270
+ (list.length ? ':' + list.length + ' 种' : ':无解')
6271
+ }
6272
+ }
6273
+ }
6274
+
6275
+ if (!label) {
6276
+ head.textContent = '这个笼的组合'
6277
+ const hint = document.createElement('span')
6278
+ hint.textContent =
6279
+ selSet.size > 1 ? '选中一格看组合' : '点一个格子,看它所在的笼能填哪些组合'
6280
+ hint.style.cssText = 'font-size:11.5px;color:#a7b6c9'
6281
+ bodyC.appendChild(hint)
6282
+ } else {
6283
+ head.textContent = label
6284
+ if (list && list.length) {
6285
+ for (const c of list.slice(0, 60)) {
6286
+ bodyC.appendChild(comboBtn(c.join(''), 'c' + cageId + ':' + c.join('')))
6287
+ }
6288
+ } else if (list) {
6289
+ const t = document.createElement('span')
6290
+ t.textContent = '没有可行组合'
6291
+ t.style.cssText = 'font-size:11.5px;color:#d9534f'
6292
+ bodyC.appendChild(t)
6293
+ }
6294
+ }
6295
+
6296
+ const comboBox = document.createElement('div')
6297
+ comboBox.style.cssText = 'border:1px solid #e6edf6;border-radius:10px;padding:8px 10px;background:#fff;margin-bottom:8px'
6298
+ comboBox.appendChild(head)
6299
+ comboBox.appendChild(bodyC)
6300
+ box.appendChild(comboBox)
6301
+ }
6302
+
6303
+ dynEl.appendChild(box)
6304
+ }
6305
+
6306
+ const inpStyle = () =>
6307
+ 'width:56px;padding:4px 6px;border-radius:7px;border:1px solid #dbe4f0;background:#fff;font:12px system-ui'
6308
+
6309
+ /**
6310
+ * 计算器只建一次,放在独立的 data-calc 容器里。
6311
+ * 以前它长在 renderPanel 里,每次点格子就重建一次,输入和结果全被清掉。
6312
+ */
6313
+ const buildCalc = () => {
6314
+ calcEl.textContent = ''
6315
+ const calc = document.createElement('div')
6316
+ calc.style.cssText = 'display:flex;align-items:center;gap:6px'
6317
+ const lab = document.createElement('span')
6318
+ lab.textContent = '计算器'
6319
+ lab.style.cssText = 'font-size:12px;color:#7b8ca6'
6320
+ const inSum = document.createElement('input')
6321
+ inSum.placeholder = '和'
6322
+ inSum.style.cssText = inpStyle()
6323
+ const inN = document.createElement('input')
6324
+ inN.placeholder = '格数'
6325
+ inN.style.cssText = inpStyle()
6326
+ const btn = document.createElement('button')
6327
+ btn.textContent = '算'
6328
+ btn.style.cssText =
6329
+ 'padding:4px 10px;border-radius:7px;border:1px solid #dbe4f0;background:#fff;font:600 12px system-ui;cursor:pointer'
6330
+ const outC = document.createElement('div')
6331
+ outC.style.cssText = 'display:flex;flex-wrap:wrap;gap:4px;min-height:20px;margin-top:8px'
6332
+ btn.addEventListener('click', () => {
6333
+ outC.textContent = ''
6334
+ const s = Number(inSum.value)
6335
+ const n = Number(inN.value)
6336
+ if (!s || !n) return
6337
+ const list = combos(s, n)
6338
+ if (!list.length) {
6339
+ outC.textContent = '没有组合'
6340
+ outC.style.cssText = 'font-size:12px;color:#d9534f;min-height:20px;margin-top:8px'
6341
+ return
6342
+ }
6343
+ outC.style.cssText = 'display:flex;flex-wrap:wrap;gap:4px;min-height:20px;margin-top:8px'
6344
+ for (const c of list.slice(0, 60)) {
6345
+ outC.appendChild(comboBtn(c.join(''), 'k' + s + '-' + n + ':' + c.join('')))
6346
+ }
6347
+ })
6348
+ calc.appendChild(lab)
6349
+ calc.appendChild(inSum)
6350
+ calc.appendChild(inN)
6351
+ calc.appendChild(btn)
6352
+
6353
+ const tip = document.createElement('div')
6354
+ tip.style.cssText = 'font-size:11px;color:#93a3ba;line-height:1.6;margin-top:10px'
6355
+ tip.innerHTML =
6356
+ '<b>按住左键拖过去</b>刷选多格(Shift 拖 = 取消选)· 1–9 填数(再按取消)· <b>Shift+1–9</b> 加候选 · <b>U</b> 划线 · <b>C</b> 清空选中 · <b>P</b> 铅笔模式 · 方向键移动'
6357
+
6358
+ calcEl.appendChild(calc)
6359
+ calcEl.appendChild(outC)
6360
+ calcEl.appendChild(tip)
6361
+ }
6362
+
6363
+ buildCalc()
6364
+
6365
+ /* ---------- 背景商店 ---------- */
6366
+ let shop = { items: [], owned: ['plain'], equipped: 'plain' }
6367
+
6368
+ const applyBg = () => {
6369
+ const item = shop.items.find((x) => x.id === shop.equipped) || { css: '#ffffff' }
6370
+ leftEl.style.background = item.css
6371
+ }
6372
+
6373
+ const loadShop = async () => {
6374
+ try {
6375
+ const r = await api(auth.server, '/api/killer/shop', { token: auth.token })
6376
+ shop = { items: r.items || [], owned: r.owned || ['plain'], equipped: r.equipped || 'plain' }
6377
+ myStars = Number(r.myStars) || myStars
6378
+ renderStars()
6379
+ applyBg()
6380
+ } catch (e) {}
6381
+ }
6382
+
6383
+ const openShop = () => {
6384
+ const old = wrap.querySelector('[data-shop-panel]')
6385
+ if (old) {
6386
+ old.remove()
6387
+ return
6388
+ }
6389
+ const panel = document.createElement('div')
6390
+ panel.setAttribute('data-shop-panel', '1')
6391
+ panel.style.cssText = [
6392
+ 'position:absolute',
6393
+ 'inset:0',
6394
+ 'z-index:5',
6395
+ 'background:rgba(251,252,254,.98)',
6396
+ 'padding:14px',
6397
+ 'overflow:auto',
6398
+ ].join(';')
6399
+
6400
+ const head = document.createElement('div')
6401
+ head.style.cssText = 'display:flex;align-items:center;gap:8px;margin-bottom:10px'
6402
+ const t = document.createElement('b')
6403
+ t.textContent = '⭐ 星星兑换'
6404
+ t.style.cssText = 'font-size:13px'
6405
+ const cnt = document.createElement('span')
6406
+ cnt.textContent = '我的星星 ' + myStars
6407
+ cnt.style.cssText = 'font-size:12px;color:#d99a1f;font-weight:600'
6408
+ const close = document.createElement('button')
6409
+ close.textContent = '返回'
6410
+ close.style.cssText =
6411
+ 'margin-left:auto;padding:4px 10px;border-radius:8px;border:1px solid #dbe4f0;background:#fff;font:600 12px system-ui;cursor:pointer'
6412
+ close.addEventListener('click', () => panel.remove())
6413
+ head.appendChild(t)
6414
+ head.appendChild(cnt)
6415
+ head.appendChild(close)
6416
+ panel.appendChild(head)
6417
+
6418
+ const grid = document.createElement('div')
6419
+ grid.style.cssText = 'display:grid;grid-template-columns:repeat(3,1fr);gap:10px'
6420
+ for (const item of shop.items) {
6421
+ const owned = shop.owned.includes(item.id)
6422
+ const equipped = shop.equipped === item.id
6423
+ const card = document.createElement('div')
6424
+ card.style.cssText =
6425
+ 'border:1px solid ' +
6426
+ (equipped ? '#7ea8e0' : '#e3eaf4') +
6427
+ ';border-radius:12px;overflow:hidden;background:#fff;display:flex;flex-direction:column'
6428
+ const prev = document.createElement('div')
6429
+ prev.style.cssText = 'height:76px;background:' + item.css + ';border-bottom:1px solid #eef2f8'
6430
+ card.appendChild(prev)
6431
+ const nm = document.createElement('div')
6432
+ nm.textContent = item.name
6433
+ nm.style.cssText = 'font-size:12px;font-weight:600;padding:6px 8px 0'
6434
+ card.appendChild(nm)
6435
+ const cost = document.createElement('div')
6436
+ cost.textContent = item.cost ? '★ ' + item.cost : '默认'
6437
+ cost.style.cssText = 'font-size:11px;color:#93a3ba;padding:0 8px 6px'
6438
+ card.appendChild(cost)
6439
+ const btn = document.createElement('button')
6440
+ btn.textContent = equipped ? '使用中' : owned ? '使用' : myStars >= item.cost ? '兑换' : '星星不足'
6441
+ btn.disabled = equipped || (!owned && myStars < item.cost)
6442
+ btn.style.cssText =
6443
+ 'margin:0 8px 8px;padding:5px 0;border-radius:8px;border:1px solid ' +
6444
+ (equipped ? '#7ea8e0' : '#dbe4f0') +
6445
+ ';background:' +
6446
+ (equipped ? '#e6f0ff' : owned ? '#fff' : '#fff8ec') +
6447
+ ';color:' +
6448
+ (equipped ? '#3f6fa8' : owned ? '#1f2a37' : '#9a6a12') +
6449
+ ';font:600 12px system-ui;cursor:pointer;opacity:' +
6450
+ (btn.disabled ? '0.6' : '1')
6451
+ btn.addEventListener('click', async () => {
6452
+ try {
6453
+ if (!owned) {
6454
+ const r = await api(auth.server, '/api/killer/buy', {
6455
+ method: 'POST',
6456
+ token: auth.token,
6457
+ body: { id: item.id },
6458
+ })
6459
+ shop.owned = r.owned
6460
+ myStars = Number(r.myStars) || myStars - item.cost
6461
+ renderStars()
6462
+ }
6463
+ const e2 = await api(auth.server, '/api/killer/equip', {
6464
+ method: 'POST',
6465
+ token: auth.token,
6466
+ body: { id: item.id },
6467
+ })
6468
+ shop.equipped = e2.equipped || item.id
6469
+ applyBg()
6470
+ panel.remove()
6471
+ openShop()
6472
+ } catch (err) {
6473
+ onToast('没换成:' + friendly(err))
6474
+ }
6475
+ })
6476
+ card.appendChild(btn)
6477
+ grid.appendChild(card)
6478
+ }
6479
+ panel.appendChild(grid)
6480
+ const hint = document.createElement('div')
6481
+ hint.textContent = '星星来自每天解出的题:难度越高,给的星越多。'
6482
+ hint.style.cssText = 'font-size:11px;color:#a7b6c9;margin-top:10px'
6483
+ panel.appendChild(hint)
6484
+ $('[data-body]').parentElement.parentElement.appendChild(panel)
6485
+ }
6486
+
6487
+ $('[data-shop]').addEventListener('click', openShop)
6488
+
6489
+ /* ---------- 历史题日历 ---------- */
6490
+ const openCalendar = async () => {
6491
+ const old = wrap.querySelector('[data-cal-panel]')
6492
+ if (old) {
6493
+ old.remove()
6494
+ return
6495
+ }
6496
+ let info = null
6497
+ try {
6498
+ info = await api(auth.server, '/api/killer/days', { token: auth.token })
6499
+ } catch (e) {
6500
+ onToast('日历没加载出来')
6501
+ return
6502
+ }
6503
+ const map = new Map()
6504
+ for (const d of info.days || []) map.set(d.day, d)
6505
+ const solvedMap = info.solved || {}
6506
+ let ym = (day || '').slice(0, 6) || '202601'
6507
+
6508
+ const panel = document.createElement('div')
6509
+ panel.setAttribute('data-cal-panel', '1')
6510
+ panel.style.cssText = [
6511
+ 'position:absolute',
6512
+ 'inset:0',
6513
+ 'z-index:6',
6514
+ 'background:rgba(251,252,254,.98)',
6515
+ 'padding:14px',
6516
+ 'overflow:auto',
6517
+ ].join(';')
6518
+
6519
+ const render = () => {
6520
+ panel.textContent = ''
6521
+ const head = document.createElement('div')
6522
+ head.style.cssText = 'display:flex;align-items:center;gap:8px;margin-bottom:10px'
6523
+ const prev = document.createElement('button')
6524
+ prev.textContent = '‹'
6525
+ const next = document.createElement('button')
6526
+ next.textContent = '›'
6527
+ for (const b of [prev, next]) {
6528
+ b.style.cssText =
6529
+ 'width:26px;height:26px;border-radius:8px;border:1px solid #dbe4f0;background:#fff;font:600 14px system-ui;cursor:pointer'
6530
+ }
6531
+ const shift = (n) => {
6532
+ let y = Number(ym.slice(0, 4))
6533
+ let m = Number(ym.slice(4, 6)) + n
6534
+ if (m < 1) {
6535
+ m = 12
6536
+ y -= 1
6537
+ }
6538
+ if (m > 12) {
6539
+ m = 1
6540
+ y += 1
6541
+ }
6542
+ ym = String(y) + String(m).padStart(2, '0')
6543
+ render()
6544
+ }
6545
+ prev.addEventListener('click', () => shift(-1))
6546
+ next.addEventListener('click', () => shift(1))
6547
+ const title = document.createElement('b')
6548
+ title.textContent = ym.slice(0, 4) + ' 年 ' + Number(ym.slice(4, 6)) + ' 月'
6549
+ title.style.cssText = 'font-size:13px'
6550
+ const close = document.createElement('button')
6551
+ close.textContent = '返回'
6552
+ close.style.cssText =
6553
+ 'margin-left:auto;padding:4px 10px;border-radius:8px;border:1px solid #dbe4f0;background:#fff;font:600 12px system-ui;cursor:pointer'
6554
+ close.addEventListener('click', () => panel.remove())
6555
+ head.appendChild(prev)
6556
+ head.appendChild(title)
6557
+ head.appendChild(next)
6558
+ head.appendChild(close)
6559
+ panel.appendChild(head)
6560
+
6561
+ const grid = document.createElement('div')
6562
+ grid.style.cssText = 'display:grid;grid-template-columns:repeat(7,1fr);gap:6px'
6563
+ for (const w of ['日', '一', '二', '三', '四', '五', '六']) {
6564
+ const c = document.createElement('div')
6565
+ c.textContent = w
6566
+ c.style.cssText = 'text-align:center;font-size:11px;color:#a7b6c9;padding-bottom:2px'
6567
+ grid.appendChild(c)
6568
+ }
6569
+ const y = Number(ym.slice(0, 4))
6570
+ const m = Number(ym.slice(4, 6))
6571
+ const first = new Date(y, m - 1, 1).getDay()
6572
+ const total = new Date(y, m, 0).getDate()
6573
+ for (let i = 0; i < first; i++) grid.appendChild(document.createElement('div'))
6574
+ for (let d = 1; d <= total; d++) {
6575
+ const key = String(y) + String(m).padStart(2, '0') + String(d).padStart(2, '0')
6576
+ const rec = map.get(key)
6577
+ const b = document.createElement('button')
6578
+ b.textContent = String(d)
6579
+ const done = rec ? rec.numbers.filter((n) => solvedMap[key + ':' + n]).length : 0
6580
+ b.style.cssText =
6581
+ 'height:44px;border-radius:9px;font:600 12.5px system-ui;cursor:' +
6582
+ (rec ? 'pointer' : 'default') +
6583
+ ';border:1px solid ' +
6584
+ (rec ? '#dbe4f0' : 'transparent') +
6585
+ ';background:' +
6586
+ (rec ? (key === day ? '#e6f0ff' : '#fff') : 'transparent') +
6587
+ ';color:' +
6588
+ (rec ? '#1f2a37' : '#c7d2df') +
6589
+ ';display:flex;flex-direction:column;align-items:center;justify-content:center;gap:2px'
6590
+ if (rec) {
6591
+ const tag = document.createElement('span')
6592
+ tag.textContent = done ? '★'.repeat(done) : '有题'
6593
+ tag.style.cssText = 'font-size:9px;color:' + (done ? '#d99a1f' : '#93a3ba')
6594
+ b.appendChild(tag)
6595
+ b.addEventListener('click', async () => {
6596
+ try {
6597
+ const r = await api(auth.server, '/api/killer/day?d=' + key, { token: auth.token })
6598
+ day = r.day || key
6599
+ curSource = r.source || ''
6600
+ curStale = false
6601
+ myStars = Number(r.myStars) || myStars
6602
+ renderStars()
6603
+ puzzles = Array.isArray(r.puzzles) ? r.puzzles : []
6604
+ panel.remove()
6605
+ if (puzzles.length) applyPuzzle(0, true)
6606
+ } catch (e) {
6607
+ onToast('这天的题没取到')
6608
+ }
6609
+ })
6610
+ }
6611
+ grid.appendChild(b)
6612
+ }
6613
+ panel.appendChild(grid)
6614
+
6615
+ const tip = document.createElement('div')
6616
+ tip.textContent = '有题的日子点进去可以做;每道题第一次做对给一次星星,之后不再给。'
6617
+ tip.style.cssText = 'font-size:11px;color:#a7b6c9;margin-top:10px;line-height:1.6'
6618
+ panel.appendChild(tip)
6619
+ }
6620
+
6621
+ render()
6622
+ wrap.appendChild(panel)
6623
+ }
6624
+
6625
+ $('[data-cal]').addEventListener('click', openCalendar)
6626
+
6627
+
6628
+
6629
+ const select = (i, additive) => {
6630
+ if (!additive) selSet = new Set([i])
6631
+ else if (selSet.has(i)) selSet.delete(i)
6632
+ else selSet.add(i)
6633
+ paint()
6634
+ }
6635
+
6636
+ const touchStarted = () => {
6637
+ startClock()
6638
+ }
6639
+
6640
+ /**
6641
+ * 输入一个数字:
6642
+ * 空格打一个数 → 直接是大字(当确定值)
6643
+ * 已经有数字再打别的 → 自动变成候选小字(1、4、5 那种排布)
6644
+ * 候选只剩一个 → 自动变回大字
6645
+ * 不再需要「铅笔模式」开关。
6646
+ */
6647
+ const put = (v) => {
6648
+ if (!selSet.size) return
6649
+ touchStarted()
6650
+ for (const i of selSet) {
6651
+ const m = marks[i]
6652
+ if (m.v) {
6653
+ if (m.v === v) {
6654
+ m.v = 0
6655
+ m.p = []
6656
+ m.u = []
6657
+ } else {
6658
+ m.p = [m.v, v].filter((x, k, a) => a.indexOf(x) === k).sort((a, b) => a - b)
6659
+ m.v = 0
6660
+ m.u = []
6661
+ }
6662
+ continue
6663
+ }
6664
+ const at = m.p.indexOf(v)
6665
+ if (at >= 0) m.p.splice(at, 1)
6666
+ else {
6667
+ m.p.push(v)
6668
+ m.p.sort((a, b) => a - b)
6669
+ }
6670
+ m.u = m.u.filter((x) => m.p.indexOf(x) >= 0)
6671
+ if (m.p.length === 1) {
6672
+ m.v = m.p[0]
6673
+ m.p = []
6674
+ m.u = []
6675
+ }
6676
+ }
6677
+ save()
6678
+ paint()
6679
+ // 只有全部格子都是「单个数」且完全合法,才算解出
6680
+ const g = values()
6681
+ if (g.every((x) => x > 0) && conflicts().size === 0) {
6682
+ done = true
6683
+ stopClock()
6684
+ const ms = currentMs()
6685
+ showWin(ms)
6686
+ awardStars()
6687
+ }
6688
+ }
6689
+
6690
+ /** 通关弹窗:用时 + 恭喜;结果留在棋盘上 */
6691
+ const showWin = (ms) => {
6692
+ const old = wrap.querySelector('[data-win]')
6693
+ if (old) old.remove()
6694
+ const box = document.createElement('div')
6695
+ box.setAttribute('data-win', '1')
6696
+ box.style.cssText = [
6697
+ 'position:absolute', 'inset:0', 'z-index:6',
6698
+ 'background:rgba(251,252,254,.92)',
6699
+ 'display:flex', 'flex-direction:column',
6700
+ 'align-items:center', 'justify-content:center', 'gap:10px',
6701
+ ].join(';')
6702
+ const t = document.createElement('div')
6703
+ t.textContent = '解出来了'
6704
+ t.style.cssText = 'font:600 22px system-ui;color:#1f2a37'
6705
+ const tm = document.createElement('div')
6706
+ tm.textContent = '用时 ' + fmt(ms)
6707
+ tm.style.cssText = 'font:600 16px ui-monospace,monospace;color:#3f6fa8'
6708
+ const b = document.createElement('button')
6709
+ b.textContent = '回到题目'
6710
+ b.style.cssText =
6711
+ 'margin-top:6px;padding:8px 18px;border-radius:10px;border:1px solid #dbe4f0;background:#fff;font:600 13px system-ui;cursor:pointer'
6712
+ b.addEventListener('click', () => box.remove())
6713
+ box.appendChild(t)
6714
+ box.appendChild(tm)
6715
+ box.appendChild(b)
6716
+ wrap.appendChild(box)
6717
+ }
6718
+
6719
+ /** 复原:清空成初始状态(星星不会重复给) */
6720
+ const resetPuzzle = () => {
6721
+ marks = blankMarks()
6722
+ selSet = new Set()
6723
+ done = false
6724
+ baseMs = 0
6725
+ runFrom = 0
6726
+ window.clearInterval(timer)
6727
+ $('[data-timer]').textContent = ''
6728
+ const w = wrap.querySelector('[data-win]')
6729
+ if (w) w.remove()
6730
+ save()
6731
+ build()
6732
+ }
6733
+
6734
+ /** 通关:难度 1-10 → 1-5 星,同一盘每天只算一次 */
6735
+ let awarding = false
6736
+ const awardStars = async () => {
6737
+ if (awarding) return
6738
+ awarding = true
6739
+ try {
6740
+ const pz = puzzles[curIdx] || {}
6741
+ const r = await api(auth.server, '/api/killer/solve', {
6742
+ method: 'POST',
6743
+ token: auth.token,
6744
+ body: { day, number: pz.number, difficulty: pz.difficulty || 1 },
6745
+ })
6746
+ myStars = Number(r.total) || 0
6747
+ renderStars()
6748
+ onToast(r.already ? '这盘已经算过星星了' : '解出来了 🎉 +' + r.stars + ' 星')
6749
+ } catch (e) {
6750
+ onToast('解出来了 🎉(星星没记上)')
6751
+ } finally {
6752
+ awarding = false
6753
+ }
6754
+ }
6755
+
6756
+ const togglePencil = (v) => {
6757
+ if (!selSet.size || done) return
6758
+ touchStarted()
6759
+ for (const i of selSet) {
6760
+ const m = marks[i]
6761
+ if (m.v) continue
6762
+ const at = m.p.indexOf(v)
6763
+ if (at >= 0) {
6764
+ m.p.splice(at, 1)
6765
+ m.u = m.u.filter((d) => d !== v)
6766
+ } else {
6767
+ m.p.push(v)
6768
+ m.p.sort((a, b) => a - b)
6769
+ }
6770
+ }
6771
+ save()
6772
+ paint()
6773
+ }
6774
+
6775
+ const clearSelected = () => {
6776
+ if (!selSet.size) return
6777
+ for (const i of selSet) {
6778
+ marks[i] = { v: 0, p: [], u: [] }
6779
+ }
6780
+ done = false
6781
+ save()
6782
+ paint()
6783
+ }
6784
+
6785
+ const underline = () => {
6786
+ if (!selSet.size) return
6787
+ for (const i of selSet) {
6788
+ const m = marks[i]
6789
+ if (m.v || !m.p.length) continue
6790
+ if (m.u.length === m.p.length) m.u = []
6791
+ else m.u = m.p.slice()
6792
+ }
6793
+ save()
6794
+ paint()
6795
+ }
6796
+
6797
+ const build = () => {
6798
+ bodyEl.textContent = ''
6799
+ owner = new Int8Array(81).fill(-1)
6800
+ cages.forEach((c, ci) => c.cells.forEach((i) => (owner[i] = ci)))
6801
+
6802
+ const CELL = 46
6803
+ const board = document.createElement('div')
6804
+ board.style.cssText =
6805
+ 'position:relative;display:grid;grid-template-columns:repeat(9,' +
6806
+ CELL +
6807
+ 'px);grid-template-rows:repeat(9,' +
6808
+ CELL +
6809
+ 'px);border:3px solid #1f2a37;margin:0 auto;width:max-content;background:#fbfcfe'
6810
+
6811
+ cells = []
6812
+ for (let i = 0; i < 81; i++) {
6813
+ const boxRight = i % 9 === 8 || COL(i) % 3 === 2
6814
+ const boxBottom = i >= 72 || ROW(i) % 3 === 2
6815
+ const cell = document.createElement('div')
6816
+ cell.style.cssText = [
6817
+ 'position:relative',
6818
+ 'display:flex',
6819
+ 'align-items:center',
6820
+ 'justify-content:center',
6821
+ 'cursor:pointer',
6822
+ 'user-select:none',
6823
+ 'border-right:' + (boxRight ? '2px solid #1f2a37' : '1px solid #1f2a37'),
6824
+ 'border-bottom:' + (boxBottom ? '2px solid #1f2a37' : '1px solid #1f2a37'),
6825
+ i % 9 === 8 ? 'border-right:none' : '',
6826
+ i >= 72 ? 'border-bottom:none' : '',
6827
+ ]
6828
+ .filter(Boolean)
6829
+ .join(';')
6830
+ cell.addEventListener('mousedown', (e) => {
6831
+ if (e.button !== 0) return
6832
+ e.preventDefault()
6833
+ dragSel = { add: !e.shiftKey }
6834
+ if (!e.shiftKey) selSet = new Set([i])
6835
+ else if (selSet.has(i)) selSet.delete(i)
6836
+ else selSet.add(i)
6837
+ paint()
6838
+ })
6839
+ cell.addEventListener('mouseenter', () => {
6840
+ if (!dragSel) return
6841
+ if (dragSel.add) selSet.add(i)
6842
+ else selSet.delete(i)
6843
+ paint()
6844
+ })
6845
+ board.appendChild(cell)
6846
+ cells.push(cell)
6847
+ }
6848
+
6849
+ // 笼用一层 SVG 单独画虚线轮廓,和九宫格的实线分开
6850
+ const NS = 'http://www.w3.org/2000/svg'
6851
+ const svg = document.createElementNS(NS, 'svg')
6852
+ svg.setAttribute('width', String(CELL * 9))
6853
+ svg.setAttribute('height', String(CELL * 9))
6854
+ svg.style.cssText = 'position:absolute;left:0;top:0;pointer-events:none;overflow:visible'
6855
+ const seg = (x1, y1, x2, y2) => {
6856
+ const l = document.createElementNS(NS, 'line')
6857
+ l.setAttribute('x1', x1)
6858
+ l.setAttribute('y1', y1)
6859
+ l.setAttribute('x2', x2)
6860
+ l.setAttribute('y2', y2)
6861
+ l.setAttribute('stroke', '#7b93b5')
6862
+ l.setAttribute('stroke-width', '1.15')
6863
+ l.setAttribute('stroke-dasharray', '4 3')
6864
+ l.setAttribute('stroke-linecap', 'round')
6865
+ svg.appendChild(l)
6866
+ }
6867
+ // 虚线整体内缩 3.5px;笼左上角那一格从数字右边/下边起笔,绕开数字
6868
+ const PAD = 3.5
6869
+ const NUM_W = 17
6870
+ const NUM_H = 14
6871
+ for (let i = 0; i < 81; i++) {
6872
+ const ci = owner[i]
6873
+ const x = COL(i) * CELL
6874
+ const y = ROW(i) * CELL
6875
+ const l = x + PAD
6876
+ const r = x + CELL - PAD
6877
+ const t = y + PAD
6878
+ const bo = y + CELL - PAD
6879
+ const anchor = cageStart.has(i)
6880
+ const topFrom = anchor ? Math.max(l, x + NUM_W) : l
6881
+ const leftFrom = anchor ? Math.max(t, y + NUM_H) : t
6882
+ if (ROW(i) === 0 || owner[i - 9] !== ci) seg(topFrom, t, r, t)
6883
+ if (ROW(i) === 8 || owner[i + 9] !== ci) seg(l, bo, r, bo)
6884
+ if (COL(i) === 0 || owner[i - 1] !== ci) seg(l, leftFrom, l, bo)
6885
+ if (COL(i) === 8 || owner[i + 1] !== ci) seg(r, t, r, bo)
6886
+ }
6887
+
6888
+ board.appendChild(svg)
6889
+
6890
+ bodyEl.appendChild(board)
6891
+
6892
+ const pad = document.createElement('div')
6893
+ pad.style.cssText = 'display:grid;grid-template-columns:repeat(5,1fr);gap:6px;margin-top:10px'
6894
+ for (let v = 1; v <= 9; v++) {
6895
+ const b = document.createElement('button')
6896
+ b.textContent = String(v)
6897
+ b.style.cssText =
6898
+ 'padding:8px 0;border-radius:9px;border:1px solid #dbe4f0;background:#fff;font:600 15px system-ui;cursor:pointer'
6899
+ b.addEventListener('click', () => put(v))
6900
+ pad.appendChild(b)
6901
+ }
6902
+ const mk = (label, fn, color) => {
6903
+ const b = document.createElement('button')
6904
+ b.textContent = label
6905
+ b.style.cssText =
6906
+ 'padding:8px 0;border-radius:9px;border:1px solid ' +
6907
+ (color || '#dbe4f0') +
6908
+ ';background:#fff;font:600 12px system-ui;cursor:pointer'
6909
+ b.addEventListener('click', fn)
6910
+ return b
6911
+ }
6912
+ pad.appendChild(mk('清除', clearSelected, '#ffd3e6'))
6913
+ pad.appendChild(mk('复原', resetPuzzle))
6914
+ bodyEl.appendChild(pad)
6915
+ paint()
6916
+ }
6917
+
6918
+ const onKey = (e) => {
6919
+ if (!document.body.contains(wrap)) return
6920
+ const t = e.target
6921
+ if (t && (/^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName) || t.isContentEditable)) return
6922
+ if (t && t.closest && t.closest('[contenteditable="true"]')) return
6923
+ const k = e.key
6924
+ if (k >= '1' && k <= '9') {
6925
+ put(Number(k))
6926
+ e.preventDefault()
6927
+ return
6928
+ }
6929
+ if (k === 'u' || k === 'U') {
6930
+ underline()
6931
+ e.preventDefault()
6932
+ return
6933
+ }
6934
+ if (k === 'c' || k === 'C') {
6935
+ clearSelected()
6936
+ e.preventDefault()
6937
+ return
6938
+ }
6939
+ if (k === 'Backspace' || k === 'Delete' || k === '0') {
6940
+ clearSelected()
6941
+ e.preventDefault()
6942
+ return
6943
+ }
6944
+ const move = { ArrowUp: -9, ArrowDown: 9, ArrowLeft: -1, ArrowRight: 1 }[k]
6945
+ if (move !== undefined) {
6946
+ e.preventDefault()
6947
+ if (!selSet.size) return select(0, false)
6948
+ const i = [...selSet][selSet.size - 1]
6949
+ const r = ROW(i)
6950
+ const c = COL(i)
6951
+ if (k === 'ArrowLeft' && c === 0) return
6952
+ if (k === 'ArrowRight' && c === 8) return
6953
+ if (k === 'ArrowUp' && r === 0) return
6954
+ if (k === 'ArrowDown' && r === 8) return
6955
+ select(i + move, e.shiftKey)
6956
+ }
6957
+ }
6958
+
6959
+ window.addEventListener('keydown', onKey, true)
6960
+ $('[data-close]').addEventListener('click', () => {
6961
+ window.removeEventListener('keydown', onKey, true)
6962
+ // 关窗前把这一段用时并进累计值,再存盘:再打开就是停表时的数字
6963
+ stopClock()
6964
+ save()
6965
+ wrap.remove()
6966
+ })
6967
+
6968
+ const applyPuzzle = (idx, keepProgress) => {
6969
+ curIdx = idx
6970
+ const pz = puzzles[idx] || {}
6971
+ cages = pz.cages || []
6972
+ cageStart = new Set()
6973
+ cageSum = new Map()
6974
+ cages.forEach((c) => {
6975
+ const start = Math.min(...c.cells)
6976
+ cageStart.add(start)
6977
+ cageSum.set(start, c.sum)
6978
+ })
6979
+ marks = blankMarks()
6980
+ selSet = new Set()
6981
+ done = false
6982
+ baseMs = 0
6983
+ runFrom = 0
6984
+ window.clearInterval(timer)
6985
+ $('[data-timer]').textContent = ''
6986
+ if (keepProgress) {
6987
+ const saved = readJson(puzzleKey())
6988
+ offCombos = new Set(Array.isArray(saved && saved.off) ? saved.off : [])
6989
+ if (saved && Array.isArray(saved.marks) && saved.marks.length === 81) {
6990
+ marks = saved.marks.map((m) => ({
6991
+ v: Number(m && m.v) || 0,
6992
+ p: Array.isArray(m && m.p) ? m.p.slice() : [],
6993
+ u: Array.isArray(m && m.u) ? m.u.slice() : [],
6994
+ }))
6995
+ baseMs = Number(saved.elapsed) || 0
6996
+ if (baseMs) {
6997
+ startClock()
6998
+ $('[data-timer]').textContent = fmt(baseMs)
6999
+ }
7000
+ }
7001
+ }
7002
+ $('[data-day]').textContent =
7003
+ day + (pz.number ? ' · #' + pz.number : '') + (curSource === 'generated' ? ' · 自动出题' : '') + (curStale ? ' · 未更新' : '')
7004
+ renderSel()
7005
+ build()
7006
+ }
7007
+
7008
+ const renderSel = () => {
7009
+ selEl.textContent = ''
7010
+ if (puzzles.length < 2) return
7011
+ const bar = document.createElement('div')
7012
+ bar.style.cssText = 'display:flex;gap:6px;justify-content:center;padding:8px 0 0'
7013
+ puzzles.forEach((pz, idx) => {
7014
+ const b = document.createElement('button')
7015
+ const st = starsFor(pz.difficulty)
7016
+ b.textContent = String(idx + 1) + (pz.difficulty ? ' · 难度' + pz.difficulty : '')
7017
+ b.title = '#' + pz.number + (pz.difficulty ? ' 难度 ' + pz.difficulty + '/10' : '') + ' 通关得 ' + st + ' 星'
7018
+ b.style.cssText =
7019
+ 'padding:0 10px;height:27px;border-radius:8px;border:1px solid ' +
7020
+ (idx === curIdx ? '#7ea8e0' : '#dbe4f0') +
7021
+ ';background:' +
7022
+ (idx === curIdx ? '#e6f0ff' : '#fff') +
7023
+ ';font:600 12px system-ui;cursor:pointer'
7024
+ b.addEventListener('click', () => {
7025
+ if (idx !== curIdx) applyPuzzle(idx, true)
7026
+ })
7027
+ bar.appendChild(b)
7028
+ })
7029
+ selEl.appendChild(bar)
7030
+ }
7031
+
7032
+ api(auth.server, '/api/killer/today', { token: auth.token })
7033
+ .then((r) => {
7034
+ day = r.day || ''
7035
+ curSource = r.source || ''
7036
+ curStale = !!r.stale
7037
+ myStars = Number(r.myStars) || 0
7038
+ renderStars()
7039
+ loadShop()
7040
+ puzzles = Array.isArray(r.puzzles) ? r.puzzles : []
7041
+ if (!puzzles.length) {
7042
+ bodyEl.textContent = '今天没有题目'
7043
+ return
7044
+ }
7045
+ applyPuzzle(0, true)
7046
+ })
7047
+ .catch((e) => {
7048
+ bodyEl.textContent = '题目加载失败:' + friendly(e)
7049
+ })
7050
+ }
7051
+ function SocialView(props) {
7052
+ const [auth, setAuth] = useState(() => readJson(K_AUTH))
7053
+ const [gameOpen, setGameOpen] = useState(false)
7054
+ const rootRef = useRef(null)
7055
+ // 只有会话里的 View 才拿得到会话数据;全局面板没有 props
7056
+ const canShare = !!(props && props.sessionId && typeof props.useChat === 'function')
7057
+
7058
+ useEffect(() => {
7059
+ const el = rootRef.current
7060
+ if (!el) return
7061
+ adaptSurfaceTokens(el)
7062
+ // 主题切换/面板尺寸变化后再校一次
7063
+ const timer = window.setTimeout(() => adaptSurfaceTokens(el), 400)
7064
+ return () => window.clearTimeout(timer)
7065
+ }, [])
7066
+
7067
+ /**
7068
+ * 把面板钉成「视口剩余高度」。
7069
+ * slot 容器不一定给确定高度,`height:100%` 会退化成内容高度,
7070
+ * 结果是整个面板比窗口还高、滚的是外层页面,输入框被顶到视口外。
7071
+ * 这里按 root 的实际 top 量一次,剩下的都交给内部列表自己滚。
7072
+ */
7073
+ useEffect(() => {
7074
+ const el = rootRef.current
7075
+ if (!el) return
7076
+
7077
+ // 真正的滚动容器不一定是 documentElement,也可能是 DSH 的某个内层 div
7078
+ const findScroller = (node) => {
7079
+ let p = node.parentElement
7080
+ while (p && p !== document.body && p !== document.documentElement) {
7081
+ const cs = window.getComputedStyle(p)
7082
+ if (/(auto|scroll)/.test(cs.overflowY)) return p
7083
+ p = p.parentElement
7084
+ }
7085
+ return null
7086
+ }
7087
+
7088
+ const fit = () => {
7089
+ const rect = el.getBoundingClientRect()
7090
+ const sc = findScroller(el)
7091
+ let h
7092
+ if (sc) {
7093
+ const sr = sc.getBoundingClientRect()
7094
+ const offTop = Math.max(0, Math.round(rect.top - sr.top))
7095
+ h = Math.round(sr.height - offTop - 4)
7096
+ } else {
7097
+ h = Math.round(window.innerHeight - Math.max(0, Math.round(rect.top)) - 6)
7098
+ }
7099
+ h = Math.max(280, h)
7100
+ // 嵌在对话流里的版本会跟着整页滚:如果块比视口还高,
7101
+ // 底部的输入框就被推到屏幕外,怎么钉都没用。这里直接压到视口内。
7102
+ if (canShare) {
7103
+ h = Math.min(h, Math.round(window.innerHeight * 0.86))
7104
+ }
7105
+ el.style.height = h + 'px'
7106
+ el.style.maxHeight = h + 'px'
7107
+ el.style.overflow = 'hidden'
7108
+
7109
+ // 万一还是把外层撑出滚动条,再按超出量回缩
7110
+ const doc = document.documentElement
7111
+ const contentH = Math.max(doc.scrollHeight, document.body ? document.body.scrollHeight : 0)
7112
+ const viewH = Math.max(doc.clientHeight, window.innerHeight)
7113
+ const over = contentH - viewH
7114
+ if (over > 2) {
7115
+ h = Math.max(280, h - over - 2)
7116
+ el.style.height = h + 'px'
7117
+ el.style.maxHeight = h + 'px'
7118
+ }
7119
+ }
7120
+
7121
+ fit()
7122
+ const timers = [60, 260, 900].map((d) => window.setTimeout(fit, d))
7123
+ window.addEventListener('resize', fit)
7124
+ let ro = null
7125
+ const parent = el.parentElement
7126
+ if (parent && typeof ResizeObserver !== 'undefined') {
7127
+ ro = new ResizeObserver(() => fit())
7128
+ ro.observe(parent)
7129
+ }
7130
+ return () => {
7131
+ for (const t of timers) window.clearTimeout(t)
7132
+ window.removeEventListener('resize', fit)
7133
+ if (ro) ro.disconnect()
7134
+ }
7135
+ }, [auth, canShare])
7136
+
7137
+ const body = !auth
7138
+ ? h(LoginPanel, { onDone: (next) => setAuth(next) })
7139
+ : h(ChatPanel, {
7140
+ auth,
7141
+ onOpenGame: () => setGameOpen(true),
7142
+ onLogout: () => {
7143
+ dropKey(K_AUTH)
7144
+ setAuth(null)
7145
+ setGameOpen(false)
7146
+ },
7147
+ })
7148
+
7149
+ return h(
7150
+ 'div',
7151
+ { className: 'sc-root', ref: rootRef },
7152
+ canShare && auth ? h(Boundary, null, h(ShareBar, { chatProps: props, auth })) : null,
7153
+ h('div', { style: { flex: 1, minHeight: 0, display: 'flex' } }, body),
7154
+ gameOpen ? h(GameWindow, { onClose: () => setGameOpen(false) }) : null,
7155
+ )
7156
+ }
7157
+
7158
+ // ─────────────────────── 一键分享 ───────────────────────
7159
+
7160
+ /** 兜住探针/适配器的异常,别让整个 slot 变空白 */
7161
+ class Boundary extends React.Component {
7162
+ constructor(p) {
7163
+ super(p)
7164
+ this.state = { err: null }
7165
+ }
7166
+ static getDerivedStateFromError(e) {
7167
+ return { err: String((e && e.message) || e) }
7168
+ }
7169
+ render() {
7170
+ if (this.state.err) {
7171
+ return h(
7172
+ 'div',
7173
+ { style: { padding: '6px 12px', fontSize: '11px', color: '#d9534f', borderBottom: LINE } },
7174
+ '分享组件出错:' + this.state.err,
7175
+ )
7176
+ }
7177
+ return this.props.children
7178
+ }
7179
+ }
7180
+
7181
+ function shapeOf(v) {
7182
+ if (v === null) return 'null'
7183
+ if (v === undefined) return 'undefined'
7184
+ if (Array.isArray(v)) {
7185
+ const first = v.length ? Object.keys(v[0] || {}).join(',') : ''
7186
+ return `array(${v.length})` + (first ? ` item: {${first}}` : '')
7187
+ }
7188
+ if (typeof v === 'object') return 'object { ' + Object.keys(v).join(', ') + ' }'
7189
+ return typeof v + ' = ' + String(v).slice(0, 80)
7190
+ }
7191
+
7192
+ /** 在几种常见形状里找出条目数组 */
7193
+ function pickArray(v) {
7194
+ if (Array.isArray(v)) return v
7195
+ if (!v || typeof v !== 'object') return null
7196
+ const keys = [
7197
+ 'rows',
7198
+ 'nodes',
7199
+ 'messages',
7200
+ 'items',
7201
+ 'entries',
7202
+ 'turns',
7203
+ 'data',
7204
+ 'list',
7205
+ 'chat',
7206
+ 'snapshot',
7207
+ 'timeline',
7208
+ 'events',
7209
+ 'groups',
7210
+ ]
7211
+ for (const k of keys) if (Array.isArray(v[k])) return v[k]
7212
+ // 兜底:只有唯一一个数组字段时就用它
7213
+ const arrays = Object.keys(v).filter((k) => Array.isArray(v[k]))
7214
+ if (arrays.length === 1) return v[arrays[0]]
7215
+ return null
7216
+ }
7217
+
7218
+ function textOf(it) {
7219
+ if (typeof it === 'string') return it
7220
+ if (!it || typeof it !== 'object') return ''
7221
+ const cand = it.text ?? it.markdown ?? it.plain ?? it.content ?? it.body
7222
+ if (typeof cand === 'string') return cand
7223
+ if (Array.isArray(cand)) {
7224
+ return cand
7225
+ .map((c) => (typeof c === 'string' ? c : (c && (c.text || c.content)) || ''))
7226
+ .join('')
7227
+ }
7228
+ if (cand && typeof cand === 'object') {
7229
+ const t = cand.text ?? cand.content
7230
+ if (typeof t === 'string') return t
7231
+ }
7232
+ return ''
7233
+ }
7234
+
7235
+ /** 长得像内部 id 的字符串,不能当正文用 */
7236
+ const ID_LIKE = /^(\d+:[a-z]|[0-9a-f]{8}-[0-9a-f]{4}|call_|toolu_|msg_|req_|turn-|step-)/i
7237
+
7238
+ function looksLikeIdText(s) {
7239
+ const t = String(s).trim()
7240
+ if (!t) return false
7241
+ if (ID_LIKE.test(t)) return true
7242
+ // 长串、无空格、只有 id 字符
7243
+ if (t.length > 24 && !/\s/.test(t) && /^[0-9a-zA-Z:_-]+$/.test(t)) return true
7244
+ return false
7245
+ }
7246
+
7247
+ /** 这些键装的是元数据,不是正文 */
7248
+ const SKIP_KEY =
7249
+ /^(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
7250
+
7251
+ /** 思考过程的键名——绝不能分享出去 */
7252
+ const REASON_KEY = /reason|think|thought|scratch|cot$/i
4150
7253
 
4151
7254
  /**
4152
7255
  * 分组/分段结构里的枚举值,单个单词出现时必是噪音。
@@ -4616,12 +7719,18 @@ window.__ModuleLoader__.load({
4616
7719
  return {
4617
7720
  inject: ['slots'],
4618
7721
  apply(ctx) {
7722
+ // 桌宠:挂在 body 上,和面板解耦
7723
+ ctx.effect(() => mountPet())
7724
+
4619
7725
  // 样式表:跟着插件生命周期建立/移除
4620
7726
  ctx.effect(() => {
4621
7727
  ensureStyles()
4622
7728
  return () => {
4623
- const el = typeof document !== 'undefined' ? document.getElementById(STYLE_ID) : null
4624
- if (el && el.parentNode) el.parentNode.removeChild(el)
7729
+ if (typeof document === 'undefined') return
7730
+ for (const id of [STYLE_ID, STYLE_ID + '-dopa']) {
7731
+ const el = document.getElementById(id)
7732
+ if (el && el.parentNode) el.parentNode.removeChild(el)
7733
+ }
4625
7734
  }
4626
7735
  })
4627
7736
 
@@ -4662,7 +7771,7 @@ window.__ModuleLoader__.load({
4662
7771
  ),
4663
7772
  )
4664
7773
 
4665
- // 4) 设置 → 社交小游戏:改「🎮 摸鱼」窗口的默认大小
7774
+ // 4) 设置 → 社交小游戏:改「🎮 钓鱼」窗口的默认大小
4666
7775
  ctx.slots.inject('settings.section', () =>
4667
7776
  ctx.slots.register(
4668
7777
  {