-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathforum.js
More file actions
2621 lines (2324 loc) · 111 KB
/
forum.js
File metadata and controls
2621 lines (2324 loc) · 111 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ==================== 论坛 - 多世界系统 ====================
// forum_worlds: [{id, name, desc, theme, boards}]
// forum_active_world: worldId
// forum_posts_{worldId}: [{id, boardId, authorType, authorId, authorName, title, content, likes, pinned, replies, createdAt}]
function getS(k, d) { try { return JSON.parse(localStorage.getItem(k)) || d; } catch { return d; } }
function setS(k, v) { localStorage.setItem(k, JSON.stringify(v)); }
function esc(s) { const d = document.createElement('div'); d.textContent = s; return d.innerHTML; }
// JS字符串转义(用于onclick属性中的字符串参数)
function escJs(s) { return String(s).replace(/\\/g,'\\\\').replace(/'/g,"\\'").replace(/"/g,'\\"').replace(/</g,'\\x3c').replace(/>/g,'\\x3e'); }
// 预设主题
const THEMES = {
light: { name: '白色', accent: '#1a1a1a', bg: '#f5f5f5', card: '#fff', text: '#1a1a1a', textSub: '#999', headerBg: '#fff', inputBg: '#fafafa', tagBg: '#f0f0f0' },
dark: { name: '黑色', accent: '#6366f1', bg: '#0f0f0f', card: '#1a1a1a', text: '#e5e5e5', textSub: '#777', headerBg: '#111', inputBg: '#222', tagBg: '#2a2a2a' },
ocean: { name: '海洋', accent: '#0ea5e9', bg: '#f0f9ff', card: '#fff', text: '#0c4a6e', textSub: '#7dd3fc', headerBg: '#e0f2fe', inputBg: '#f0f9ff', tagBg: '#e0f2fe' },
forest: { name: '森林', accent: '#16a34a', bg: '#f0fdf4', card: '#fff', text: '#14532d', textSub: '#86efac', headerBg: '#dcfce7', inputBg: '#f0fdf4', tagBg: '#dcfce7' },
sunset: { name: '日落', accent: '#ea580c', bg: '#fff7ed', card: '#fff', text: '#7c2d12', textSub: '#fdba74', headerBg: '#ffedd5', inputBg: '#fff7ed', tagBg: '#ffedd5' },
purple: { name: '紫夜', accent: '#a855f7', bg: '#0a0014', card: '#1a0a2e', text: '#e9d5ff', textSub: '#7c3aed', headerBg: '#120026', inputBg: '#1a0a2e', tagBg: '#2d1050' },
rose: { name: '玫瑰', accent: '#e11d48', bg: '#fff1f2', card: '#fff', text: '#881337', textSub: '#fda4af', headerBg: '#ffe4e6', inputBg: '#fff1f2', tagBg: '#ffe4e6' },
cyber: { name: '赛博', accent: '#06b6d4', bg: '#020617', card: '#0f172a', text: '#22d3ee', textSub: '#475569', headerBg: '#0f172a', inputBg: '#1e293b', tagBg: '#1e293b' },
};
const DEFAULT_BOARDS = [
{ id: 'general', name: '综合', emoji: '💬' },
{ id: 'daily', name: '日常', emoji: '☀️' },
{ id: 'funny', name: '搞笑', emoji: '😂' },
{ id: 'question', name: '提问', emoji: '❓' },
{ id: 'share', name: '分享', emoji: '📎' }
];
let currentBoard = 'all';
let currentPostId = null;
let editingWorldId = null;
let isRefreshingReplies = false;
// ==================== 初始化 ====================
document.addEventListener('DOMContentLoaded', () => {
initWorlds();
renderWorldBar();
applyTheme();
renderBoards();
renderPosts();
renderNewWorldThemes('newWorldThemeRow');
});
function initWorlds() {
const worlds = getS('forum_worlds', null);
if (!worlds) {
// 首次:创建默认世界
setS('forum_worlds', [{
id: 'default',
name: '默认论坛',
desc: '',
themeId: 'light',
customTheme: null,
boards: DEFAULT_BOARDS
}]);
setS('forum_active_world', 'default');
}
}
function getWorlds() { return getS('forum_worlds', []); }
function getActiveWorldId() { return getS('forum_active_world', 'default'); }
function getActiveWorld() { return getWorlds().find(w => w.id === getActiveWorldId()) || getWorlds()[0]; }
// ==================== 世界切换栏 ====================
function renderWorldBar() {
const worlds = getWorlds();
const activeId = getActiveWorldId();
const bar = document.getElementById('worldBar');
bar.innerHTML = worlds.map(w => {
const active = w.id === activeId ? 'active' : '';
const themeColor = getWorldAccent(w);
const dot = `<span style="display:inline-block;width:8px;height:8px;border-radius:50%;background:${themeColor};margin-right:6px;"></span>`;
return `<button class="forum-world-chip ${active}" onclick="switchWorld('${w.id}')">${dot}${esc(w.name)}</button>`;
}).join('') + `<button class="forum-world-add" onclick="openWorldManager()" title="新建世界">+</button>`;
// 更新标题和描述
const world = getActiveWorld();
if (world) {
document.getElementById('forumTitle').textContent = world.name;
const descEl = document.getElementById('worldDesc');
if (world.desc) {
descEl.textContent = world.desc;
descEl.style.display = 'block';
} else {
descEl.style.display = 'none';
}
}
}
function getWorldAccent(world) {
if (world.customTheme) return world.customTheme;
const t = THEMES[world.themeId];
return t ? t.accent : '#1a1a1a';
}
function switchWorld(worldId) {
setS('forum_active_world', worldId);
currentBoard = 'all';
applyTheme();
renderWorldBar();
renderBoards();
renderPosts();
}
// ==================== 主题应用 ====================
function applyTheme() {
const world = getActiveWorld();
if (!world) return;
const root = document.documentElement;
if (world.customTheme) {
// 自定义单色 → 自动生成明暗
const hex = world.customTheme;
const isDark = isColorDark(hex);
if (isDark) {
root.style.setProperty('--forum-bg', '#0f0f0f');
root.style.setProperty('--forum-text', '#e5e5e5');
root.style.setProperty('--forum-text-sub', '#777');
root.style.setProperty('--forum-card-bg', '#1a1a1a');
root.style.setProperty('--forum-card-border', '#333');
root.style.setProperty('--forum-header-bg', '#111');
root.style.setProperty('--forum-header-border', '#333');
root.style.setProperty('--forum-accent', hex);
root.style.setProperty('--forum-accent-text', '#fff');
root.style.setProperty('--forum-tag-bg', '#2a2a2a');
root.style.setProperty('--forum-input-bg', '#222');
root.style.setProperty('--forum-input-border', '#444');
root.style.setProperty('--forum-modal-bg', '#1a1a1a');
root.style.setProperty('--forum-divider', '#333');
} else {
root.style.setProperty('--forum-bg', '#f5f5f5');
root.style.setProperty('--forum-text', '#1a1a1a');
root.style.setProperty('--forum-text-sub', '#999');
root.style.setProperty('--forum-card-bg', '#fff');
root.style.setProperty('--forum-card-border', '#eee');
root.style.setProperty('--forum-header-bg', '#fff');
root.style.setProperty('--forum-header-border', '#e5e5e5');
root.style.setProperty('--forum-accent', hex);
root.style.setProperty('--forum-accent-text', '#fff');
root.style.setProperty('--forum-tag-bg', '#f0f0f0');
root.style.setProperty('--forum-input-bg', '#fafafa');
root.style.setProperty('--forum-input-border', '#ddd');
root.style.setProperty('--forum-modal-bg', '#fff');
root.style.setProperty('--forum-divider', '#f0f0f0');
}
} else {
const t = THEMES[world.themeId] || THEMES.light;
root.style.setProperty('--forum-bg', t.bg);
root.style.setProperty('--forum-text', t.text);
root.style.setProperty('--forum-text-sub', t.textSub);
root.style.setProperty('--forum-card-bg', t.card);
root.style.setProperty('--forum-card-border', isColorDark(t.bg) ? '#333' : '#eee');
root.style.setProperty('--forum-header-bg', t.headerBg);
root.style.setProperty('--forum-header-border', isColorDark(t.bg) ? '#333' : '#e5e5e5');
root.style.setProperty('--forum-accent', t.accent);
root.style.setProperty('--forum-accent-text', isColorDark(t.accent) ? '#fff' : '#fff');
root.style.setProperty('--forum-tag-bg', t.tagBg);
root.style.setProperty('--forum-input-bg', t.inputBg);
root.style.setProperty('--forum-input-border', isColorDark(t.bg) ? '#444' : '#ddd');
root.style.setProperty('--forum-modal-bg', t.card);
root.style.setProperty('--forum-divider', isColorDark(t.bg) ? '#333' : '#f0f0f0');
}
}
function isColorDark(hex) {
hex = hex.replace('#', '');
if (hex.length === 3) hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];
const r = parseInt(hex.substr(0,2),16), g = parseInt(hex.substr(2,2),16), b = parseInt(hex.substr(4,2),16);
return (r*299 + g*587 + b*114) / 1000 < 128;
}
// ==================== 板块 ====================
function getBoards() {
const world = getActiveWorld();
return world ? world.boards : DEFAULT_BOARDS;
}
function renderBoards() {
const boards = getBoards();
const nav = document.getElementById('forumBoards');
const allActive = currentBoard === 'all' ? 'active' : '';
nav.innerHTML = `<button class="forum-board-tag ${allActive}" onclick="filterBoard('all')">全部</button>` +
boards.map(b => {
const active = currentBoard === b.id ? 'active' : '';
return `<button class="forum-board-tag ${active}" onclick="filterBoard('${b.id}')">${b.emoji} ${b.name}</button>`;
}).join('');
}
function filterBoard(boardId) {
currentBoard = boardId;
renderBoards();
renderPosts();
}
// ==================== 帖子 ====================
function getPosts() {
const worldId = getActiveWorldId();
return getS(`forum_posts_${worldId}`, []);
}
function savePosts(posts) {
const worldId = getActiveWorldId();
setS(`forum_posts_${worldId}`, posts);
}
function renderPosts() {
let posts = getPosts();
if (currentBoard !== 'all') posts = posts.filter(p => p.boardId === currentBoard);
posts.sort((a, b) => (b.pinned ? 1 : 0) - (a.pinned ? 1 : 0) || b.createdAt - a.createdAt);
const list = document.getElementById('forumList');
const empty = document.getElementById('forumEmpty');
if (!posts.length) { list.innerHTML = ''; empty.style.display = 'block'; return; }
empty.style.display = 'none';
const boards = getBoards();
const contacts = getS('vibe_contacts', []);
const npcs = getNpcs();
list.innerHTML = posts.map(p => {
const board = boards.find(b => b.id === p.boardId);
const boardTag = board ? `<span class="forum-post-board-tag">${board.emoji} ${board.name}</span>` : '';
const avatar = getAvatar(p, contacts);
const replyCount = (p.replies || []).length;
const pinIcon = p.pinned ? '📌 ' : '';
const bmClass = p.bookmarked ? 'bookmarked' : '';
// NPC点击和星标
const isNpc = p.authorType === 'npc';
const npc = isNpc ? npcs.find(n => n.name === p.authorName) : null;
const starBadge = (npc && npc.followed) ? '<span class="npc-follow-star-badge">⭐</span>' : '';
const avatarClick = isNpc ? `onclick="event.stopPropagation();openNpcProfile('${escJs(p.authorName)}')" style="cursor:pointer;"` : '';
const nameClick = isNpc ? `onclick="event.stopPropagation();openNpcProfile('${escJs(p.authorName)}')" style="cursor:pointer;"` : '';
return `
<div class="forum-post-card" onclick="openPostDetail('${p.id}')">
<span class="forum-bookmark-icon ${bmClass}" onclick="event.stopPropagation();toggleBookmarkFromList('${p.id}')" title="追更">🔖</span>
<div class="forum-post-card-header">
<div class="forum-post-avatar" ${avatarClick}>${avatar}${starBadge}</div>
<div class="forum-post-meta">
<div class="forum-post-author" ${nameClick}>${esc(p.authorName || '匿名')}</div>
<div class="forum-post-info"><span>${timeAgo(p.createdAt)}</span>${boardTag}</div>
</div>
</div>
<div class="forum-post-title">${pinIcon}${esc(p.title)}</div>
<div class="forum-post-preview">${esc(p.content)}</div>
<div class="forum-post-footer"><span>💬 ${replyCount}</span><span>👍 ${p.likes || 0}</span>${p.attachments && p.attachments.length ? '<span>📎 ' + p.attachments.length + '</span>' : ''}</div>
</div>`;
}).join('');
}
// ==================== 帖子详情 ====================
function openPostDetail(postId) {
currentPostId = postId;
const posts = getPosts();
const post = posts.find(p => p.id === postId);
if (!post) return;
const contacts = getS('vibe_contacts', []);
const boards = getBoards();
const board = boards.find(b => b.id === post.boardId);
const avatar = getAvatar(post, contacts);
const npcs = getNpcs();
// 更新书签按钮状态
const bmBtn = document.getElementById('bookmarkBtn');
if (bmBtn) bmBtn.className = `forum-btn-icon${post.bookmarked ? ' active' : ''}`;
// 帖子作者NPC点击
const isPostNpc = post.authorType === 'npc';
const postNpc = isPostNpc ? npcs.find(n => n.name === post.authorName) : null;
const postStar = (postNpc && postNpc.followed) ? '<span class="npc-follow-star-badge">⭐</span>' : '';
const postAvatarClick = isPostNpc ? `onclick="openNpcProfile('${escJs(post.authorName)}')" style="cursor:pointer;"` : '';
const postNameClick = isPostNpc ? `onclick="openNpcProfile('${escJs(post.authorName)}')" style="cursor:pointer;"` : '';
let html = '';
// 总结条
if (post.summary) {
html += `<div class="forum-summary-bar"><span class="summary-label">🧠 长期记忆:</span><span class="summary-text">${esc(post.summary)}</span></div>`;
}
html += `
<div class="forum-detail-post">
<div class="forum-post-card-header">
<div class="forum-post-avatar" ${postAvatarClick}>${avatar}${postStar}</div>
<div class="forum-post-meta">
<div class="forum-post-author" ${postNameClick}>${esc(post.authorName || '匿名')}</div>
<div class="forum-post-info"><span>${timeAgo(post.createdAt)}</span>${board ? `<span class="forum-post-board-tag">${board.emoji} ${board.name}</span>` : ''}</div>
</div>
</div>
<div class="forum-detail-title">${esc(post.title)}</div>
<div class="forum-detail-content">${esc(post.content)}</div>
${renderAttachments(post.attachments)}
<div class="forum-detail-footer">
<span onclick="toggleLike('${post.id}')" style="cursor:pointer;">👍 ${post.likes || 0}</span>
<span>💬 ${(post.replies || []).length}</span>
</div>
</div>`;
const replies = post.replies || [];
html += `<div class="forum-replies"><div class="forum-replies-title">回复 (${replies.length})</div>`;
if (replies.length) {
html += replies.map(r => {
const rAvatar = getReplyAvatar(r, contacts);
const isReplyNpc = r.authorType === 'npc';
const replyNpc = isReplyNpc ? npcs.find(n => n.name === r.authorName) : null;
const replyStar = (replyNpc && replyNpc.followed) ? '<span class="npc-follow-star-badge">⭐</span>' : '';
const replyAvatarClick = isReplyNpc ? `onclick="openNpcProfile('${escJs(r.authorName)}')" style="cursor:pointer;"` : '';
const replyNameClick = isReplyNpc ? `onclick="openNpcProfile('${escJs(r.authorName)}')" style="cursor:pointer;"` : '';
return `<div class="forum-reply-item"><div class="forum-reply-avatar" ${replyAvatarClick}>${rAvatar}${replyStar}</div><div class="forum-reply-body"><span class="forum-reply-author" ${replyNameClick}>${esc(r.authorName || '匿名')}</span><span class="forum-reply-time">${timeAgo(r.createdAt)}</span><div class="forum-reply-text">${esc(r.content)}</div>${renderAttachments(r.attachments)}</div></div>`;
}).join('');
} else {
html += `<div style="padding:20px 0;text-align:center;font-size:13px;">暂无回复</div>`;
}
html += `</div>`;
document.getElementById('postDetailContent').innerHTML = html;
document.getElementById('postDetailTitle').textContent = post.title;
showModal('postDetail');
}
function closePostDetail() { hideModal('postDetail'); currentPostId = null; }
function toggleLike(postId) {
const posts = getPosts();
const post = posts.find(p => p.id === postId);
if (!post) return;
post.likes = (post.likes || 0) + 1;
savePosts(posts);
if (currentPostId === postId) openPostDetail(postId);
renderPosts();
}
function submitReply() {
const input = document.getElementById('replyInput');
const text = input.value.trim();
if (!text || !currentPostId) return;
const posts = getPosts();
const post = posts.find(p => p.id === currentPostId);
if (!post) return;
if (!post.replies) post.replies = [];
const reply = { id: 'r_' + Date.now(), authorType: 'user', authorName: 'USER', content: text, createdAt: Date.now() };
// 检查附件
const attachPanel = document.getElementById('replyAttachPanel');
if (attachPanel.style.display !== 'none') {
const url = document.getElementById('replyAttachUrl').value.trim();
const type = document.getElementById('replyAttachType').value;
const desc = document.getElementById('replyAttachDesc').value.trim();
if (url) {
reply.attachments = [{ type, url, desc }];
}
}
post.replies.push(reply);
savePosts(posts);
input.value = '';
document.getElementById('replyAttachUrl').value = '';
document.getElementById('replyAttachDesc').value = '';
document.getElementById('replyAttachPanel').style.display = 'none';
// 自动总结触发检查
const trigger = post.autoSumTrigger || 0;
if (trigger > 0) {
const lastSumAt = post._lastSumAt || 0;
if (post.replies.length - lastSumAt >= trigger) {
triggerAutoSummarize(post, posts);
}
}
openPostDetail(currentPostId);
renderPosts();
}
// ==================== 发帖 ====================
function openNewPost() {
const contacts = getS('vibe_contacts', []);
const boards = getBoards();
document.getElementById('newPostAuthor').innerHTML = `<option value="user">👤 我自己</option>` +
contacts.map(c => `<option value="${c.id}">${esc(c.nickname || c.name || 'CHAR')}</option>`).join('');
document.getElementById('newPostBoard').innerHTML = boards.map(b => `<option value="${b.id}">${b.emoji} ${b.name}</option>`).join('');
document.getElementById('newPostTitle').value = '';
document.getElementById('newPostContent').value = '';
document.getElementById('newPostAttachments').innerHTML = '';
showModal('newPost');
}
function closeNewPost() { hideModal('newPost'); }
function submitNewPost() {
const authorVal = document.getElementById('newPostAuthor').value;
const boardId = document.getElementById('newPostBoard').value;
const title = document.getElementById('newPostTitle').value.trim();
const content = document.getElementById('newPostContent').value.trim();
if (!title) { alert('请输入标题'); return; }
if (!content) { alert('请输入内容'); return; }
const contacts = getS('vibe_contacts', []);
let authorName = 'USER', authorType = 'user', authorId = null;
if (authorVal !== 'user') {
const c = contacts.find(ct => String(ct.id) === String(authorVal));
if (c) { authorName = c.nickname || c.name || 'CHAR'; authorType = 'char'; authorId = c.id; }
}
const posts = getPosts();
const newPost = { id: 'p_' + Date.now(), boardId, authorType, authorId, authorName, title, content, likes: 0, pinned: false, replies: [], createdAt: Date.now() };
// 收集附件
const attachRows = document.querySelectorAll('#newPostAttachments .forum-attach-edit-row');
if (attachRows.length) {
newPost.attachments = [];
attachRows.forEach(row => {
const url = row.querySelector('.attach-url').value.trim();
const type = row.querySelector('.attach-type').value;
const desc = row.querySelector('.attach-desc').value.trim();
if (url) newPost.attachments.push({ type, url, desc });
});
if (!newPost.attachments.length) delete newPost.attachments;
}
posts.unshift(newPost);
savePosts(posts);
closeNewPost();
renderPosts();
}
// ==================== 板块管理 ====================
function openBoardManager() { renderBoardList(); showModal('boardManager'); }
function closeBoardManager() { hideModal('boardManager'); }
function renderBoardList() {
const boards = getBoards();
document.getElementById('boardList').innerHTML = boards.map(b => `
<div class="board-item">
<span>${b.emoji}</span>
<span class="board-item-name">${esc(b.name)}</span>
<button class="board-item-delete" onclick="deleteBoard('${b.id}')" title="删除">🗑️</button>
</div>`).join('');
}
function addBoard() {
const name = document.getElementById('newBoardName').value.trim();
const emoji = document.getElementById('newBoardEmoji').value.trim() || '📌';
if (!name) { alert('请输入板块名称'); return; }
const worlds = getWorlds();
const world = worlds.find(w => w.id === getActiveWorldId());
if (!world) return;
world.boards.push({ id: 'b_' + Date.now(), name, emoji });
setS('forum_worlds', worlds);
document.getElementById('newBoardName').value = '';
document.getElementById('newBoardEmoji').value = '';
renderBoardList();
renderBoards();
}
function deleteBoard(boardId) {
if (!confirm('确认删除此板块?')) return;
const worlds = getWorlds();
const world = worlds.find(w => w.id === getActiveWorldId());
if (!world) return;
world.boards = world.boards.filter(b => b.id !== boardId);
setS('forum_worlds', worlds);
if (currentBoard === boardId) currentBoard = 'all';
renderBoardList();
renderBoards();
renderPosts();
}
// ==================== 世界管理 ====================
function openWorldManager() {
renderNewWorldThemes('newWorldThemeRow');
renderWorldList();
document.getElementById('newWorldName').value = '';
document.getElementById('newWorldDesc').value = '';
document.getElementById('newWorldThemeCustom').value = '';
showModal('worldManager');
}
function closeWorldManager() { hideModal('worldManager'); }
function renderNewWorldThemes(containerId) {
const container = document.getElementById(containerId);
container.innerHTML = Object.entries(THEMES).map(([id, t]) =>
`<button class="theme-color-btn" data-theme="${id}" style="background:${t.accent};" onclick="selectTheme(this,'${containerId}')" title="${t.name}"></button>`
).join('');
}
function selectTheme(btn, containerId) {
document.querySelectorAll(`#${containerId} .theme-color-btn`).forEach(b => b.classList.remove('active'));
btn.classList.add('active');
}
function getSelectedTheme(containerId, customInputId) {
const custom = document.getElementById(customInputId).value.trim();
if (custom && /^#[0-9a-fA-F]{3,6}$/.test(custom)) {
return { themeId: null, customTheme: custom };
}
const active = document.querySelector(`#${containerId} .theme-color-btn.active`);
if (active) return { themeId: active.dataset.theme, customTheme: null };
return { themeId: 'light', customTheme: null };
}
function addWorld() {
const name = document.getElementById('newWorldName').value.trim();
if (!name) { alert('请输入世界名称'); return; }
const desc = document.getElementById('newWorldDesc').value.trim();
const { themeId, customTheme } = getSelectedTheme('newWorldThemeRow', 'newWorldThemeCustom');
const worlds = getWorlds();
const newId = 'w_' + Date.now();
worlds.push({
id: newId, name, desc,
themeId: themeId || 'light',
customTheme,
boards: [...DEFAULT_BOARDS]
});
setS('forum_worlds', worlds);
setS('forum_active_world', newId);
closeWorldManager();
currentBoard = 'all';
applyTheme();
renderWorldBar();
renderBoards();
renderPosts();
}
function renderWorldList() {
const worlds = getWorlds();
document.getElementById('worldList').innerHTML = worlds.map(w => {
const color = getWorldAccent(w);
return `
<div class="world-item">
<span class="world-item-color" style="background:${color};"></span>
<span class="world-item-name">${esc(w.name)}</span>
<button class="world-item-btn" onclick="openEditWorld('${w.id}')" title="编辑">✏️</button>
</div>`;
}).join('');
}
// ==================== 编辑世界 ====================
function openEditWorld(worldId) {
editingWorldId = worldId;
const world = getWorlds().find(w => w.id === worldId);
if (!world) return;
document.getElementById('editWorldName').value = world.name;
document.getElementById('editWorldDesc').value = world.desc || '';
document.getElementById('editWorldThemeCustom').value = world.customTheme || '';
renderNewWorldThemes('editWorldThemeRow');
if (world.themeId) {
const btn = document.querySelector(`#editWorldThemeRow .theme-color-btn[data-theme="${world.themeId}"]`);
if (btn) btn.classList.add('active');
}
showModal('editWorld');
}
function closeEditWorld() { hideModal('editWorld'); editingWorldId = null; }
function saveEditWorld() {
if (!editingWorldId) return;
const worlds = getWorlds();
const world = worlds.find(w => w.id === editingWorldId);
if (!world) return;
world.name = document.getElementById('editWorldName').value.trim() || world.name;
world.desc = document.getElementById('editWorldDesc').value.trim();
const { themeId, customTheme } = getSelectedTheme('editWorldThemeRow', 'editWorldThemeCustom');
world.themeId = themeId || world.themeId;
world.customTheme = customTheme;
setS('forum_worlds', worlds);
closeEditWorld();
applyTheme();
renderWorldBar();
renderWorldList();
}
function deleteCurrentEditWorld() {
if (!editingWorldId) return;
const worlds = getWorlds();
if (worlds.length <= 1) { alert('至少保留一个世界'); return; }
if (!confirm('确认删除此世界?所有帖子将被清除。')) return;
// 删除帖子
localStorage.removeItem(`forum_posts_${editingWorldId}`);
const newWorlds = worlds.filter(w => w.id !== editingWorldId);
setS('forum_worlds', newWorlds);
// 如果删的是当前世界,切到第一个
if (getActiveWorldId() === editingWorldId) {
setS('forum_active_world', newWorlds[0].id);
}
closeEditWorld();
currentBoard = 'all';
applyTheme();
renderWorldBar();
renderBoards();
renderPosts();
renderWorldList();
}
// ==================== 弹窗工具 ====================
function showModal(name) {
document.getElementById(name + 'Overlay').style.display = 'block';
document.getElementById(name + 'Modal').style.display = 'flex';
}
function hideModal(name) {
document.getElementById(name + 'Overlay').style.display = 'none';
document.getElementById(name + 'Modal').style.display = 'none';
}
// ==================== 时间格式化 ====================
function timeAgo(ts) {
const diff = Date.now() - ts;
const mins = Math.floor(diff / 60000);
if (mins < 1) return '刚刚';
if (mins < 60) return mins + '分钟前';
const hours = Math.floor(mins / 60);
if (hours < 24) return hours + '小时前';
const days = Math.floor(hours / 24);
if (days < 30) return days + '天前';
return new Date(ts).toLocaleDateString('zh-CN');
}
// ==================== LLM 调用 ====================
function getApiConfig() {
const contacts = getS('vibe_contacts', []);
// 尝试从第一个有 API 方案的 CHAR 获取配置
for (const c of contacts) {
if (c.apiScheme) {
const schemes = getS('vibe_api_schemes', []);
const scheme = schemes.find(s => s.id === c.apiScheme);
if (scheme && scheme.apiUrl && scheme.apiKey) {
return { apiUrl: scheme.apiUrl, apiKey: scheme.apiKey, model: scheme.model };
}
}
}
// fallback: 全局配置
const apiUrl = localStorage.getItem('apiUrl');
const apiKey = localStorage.getItem('apiKey');
const model = localStorage.getItem('selectedModel');
return { apiUrl, apiKey, model };
}
async function callLLM(apiUrl, apiKey, model, prompt, temperature, systemPrompt) {
const messages = [];
if (systemPrompt) messages.push({ role: 'system', content: systemPrompt });
messages.push({ role: 'user', content: prompt });
let resp;
try {
resp = await fetch(`${apiUrl}/chat/completions`.replace(/([^:]\/)\/+/g, '$1'), {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` },
body: JSON.stringify({ model, messages, temperature: temperature || 0.7 })
});
} catch (e) {
throw new Error('网络连接失败');
}
if (!resp.ok) {
let detail = ''; try { detail = await resp.text(); } catch (_) {}
throw new Error(`API请求失败(${resp.status}): ${detail.slice(0, 200)}`);
}
const ct = resp.headers.get('content-type') || '';
if (!ct.includes('application/json')) throw new Error('API返回非JSON');
const data = await resp.json();
if (!data.choices || !data.choices[0] || !data.choices[0].message) throw new Error('API返回格式异常');
return data.choices[0].message.content.trim();
}
// 支持多轮对话的LLM调用(私信用)
async function callLLMMultiTurn(apiUrl, apiKey, model, messages, temperature) {
let resp;
try {
resp = await fetch(`${apiUrl}/chat/completions`.replace(/([^:]\/)\/+/g, '$1'), {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` },
body: JSON.stringify({ model, messages, temperature: temperature || 0.7 })
});
} catch (e) {
throw new Error('网络连接失败');
}
if (!resp.ok) {
let detail = ''; try { detail = await resp.text(); } catch (_) {}
throw new Error(`API请求失败(${resp.status}): ${detail.slice(0, 200)}`);
}
const ct = resp.headers.get('content-type') || '';
if (!ct.includes('application/json')) throw new Error('API返回非JSON');
const data = await resp.json();
if (!data.choices || !data.choices[0] || !data.choices[0].message) throw new Error('API返回格式异常');
return data.choices[0].message.content.trim();
}
// ==================== 路人 NPC 池 ====================
function getNpcs() {
const worldId = getActiveWorldId();
return getS(`forum_npcs_${worldId}`, []);
}
function saveNpcs(npcs) {
const worldId = getActiveWorldId();
setS(`forum_npcs_${worldId}`, npcs);
}
const NPC_EMOJIS = ['🧑','👩','👨','🧔','👱','🧑🦰','👩🦳','🧑🦱','👴','👵','🧒','👦','👧','🤓','😎','🥸','🤠','👻','🐱','🐶','🦊','🐻','🐼','🐨','🐯','🦁','🐸','🐧','🦉','🐝'];
const NPC_MAX_POOL = 50; // NPC池上限
// ==================== 时区与时间感知 ====================
const COMMON_TIMEZONES = [
{ offset: 8, label: '东八区 (中国/新加坡)', cities: '北京/上海/新加坡' },
{ offset: 9, label: '东九区 (日本/韩国)', cities: '东京/首尔' },
{ offset: -5, label: '西五区 (美东)', cities: '纽约/华盛顿' },
{ offset: -8, label: '西八区 (美西)', cities: '洛杉矶/旧金山' },
{ offset: 0, label: 'UTC+0 (英国)', cities: '伦敦' },
{ offset: 1, label: '东一区 (中欧)', cities: '巴黎/柏林' },
{ offset: 3, label: '东三区 (莫斯科)', cities: '莫斯科' },
{ offset: 5.5, label: '东五半区 (印度)', cities: '孟买/新德里' },
{ offset: -3, label: '西三区 (巴西)', cities: '圣保罗' },
{ offset: 10, label: '东十区 (澳洲)', cities: '悉尼' },
{ offset: 7, label: '东七区 (泰国)', cities: '曼谷' },
{ offset: -6, label: '西六区 (美中)', cities: '芝加哥' },
];
function getTimePeriod(hour) {
if (hour >= 0 && hour < 5) return '深夜';
if (hour < 8) return '早晨';
if (hour < 12) return '上午';
if (hour < 14) return '中午';
if (hour < 18) return '下午';
if (hour < 20) return '傍晚';
return '晚上';
}
function getTimeContext() {
const now = new Date();
const h = now.getHours(), m = now.getMinutes();
const pad = n => String(n).padStart(2, '0');
const weekdays = ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'];
const localTime = `${pad(h)}:${pad(m)}`;
const date = `${now.getFullYear()}-${pad(now.getMonth()+1)}-${pad(now.getDate())}`;
const weekday = weekdays[now.getDay()];
const period = getTimePeriod(h);
return { localTime, date, weekday, period, description: `${date} ${weekday} ${period}${localTime}` };
}
function getLocalTimeForTimezone(utcOffset) {
const now = new Date();
const utcMs = now.getTime() + now.getTimezoneOffset() * 60000;
const targetMs = utcMs + utcOffset * 3600000;
const target = new Date(targetMs);
const h = target.getHours(), m = target.getMinutes();
const pad = n => String(n).padStart(2, '0');
return { hour: h, minute: m, period: getTimePeriod(h), time: `${pad(h)}:${pad(m)}` };
}
function formatTimezoneLabel(offset) {
const tz = COMMON_TIMEZONES.find(t => t.offset === offset);
const sign = offset >= 0 ? '+' : '';
const offsetStr = Number.isInteger(offset) ? `${offset}` : `${offset}`;
return tz ? `UTC${sign}${offsetStr} ${tz.cities}` : `UTC${sign}${offsetStr}`;
}
function buildTimeContextPrompt(sampledNpcs) {
const tc = getTimeContext();
let prompt = `\n【当前时间】\n用户本地时间:${tc.description}\n`;
if (sampledNpcs && sampledNpcs.length) {
prompt += '\n【NPC时区参考】\n论坛用户来自世界各地,以下是部分用户的当地时间:\n';
for (const npc of sampledNpcs) {
const offset = npc.timezone != null ? npc.timezone : 8;
const lt = getLocalTimeForTimezone(offset);
const tzLabel = formatTimezoneLabel(offset);
prompt += `- ${npc.name}(${tzLabel}):${lt.period}${lt.time}\n`;
}
}
prompt += '\n请根据每个角色的当地时间生成符合时间氛围的内容。例如:\n';
prompt += '- 深夜的用户可能发emo帖、失眠吐槽、深夜放毒\n';
prompt += '- 早晨的用户可能发早安帖、通勤吐槽\n';
prompt += '- 中午的用户可能讨论午饭、摸鱼\n';
prompt += '- 周末和工作日的话题也应有所不同\n';
return prompt;
}
// ==================== 发帖记忆系统 ====================
const DEFAULT_CHAR_POST_MEMORY_LIMIT = 20;
const DEFAULT_NPC_POST_MEMORY_LIMIT = 15;
function getForumSettings() {
return getS('forum_settings', { charPostMemoryLimit: DEFAULT_CHAR_POST_MEMORY_LIMIT, npcPostMemoryLimit: DEFAULT_NPC_POST_MEMORY_LIMIT });
}
function saveForumSettings(settings) { setS('forum_settings', settings); }
function getCharPostMemory(charId) {
const worldId = getActiveWorldId();
return getS(`forum_char_post_memory_${worldId}_${charId}`, []);
}
function saveCharPostMemory(charId, entries) {
const worldId = getActiveWorldId();
const limit = getForumSettings().charPostMemoryLimit || DEFAULT_CHAR_POST_MEMORY_LIMIT;
if (entries.length > limit) entries = entries.slice(-limit);
setS(`forum_char_post_memory_${worldId}_${charId}`, entries);
}
function getNpcPostMemory(npcId) {
const npcs = getNpcs();
const npc = npcs.find(n => n.id === npcId);
return (npc && npc.postMemory) ? npc.postMemory : [];
}
function saveNpcPostMemory(npcId, entries) {
const npcs = getNpcs();
const npc = npcs.find(n => n.id === npcId);
if (!npc) return;
const limit = getForumSettings().npcPostMemoryLimit || DEFAULT_NPC_POST_MEMORY_LIMIT;
if (entries.length > limit) entries = entries.slice(-limit);
npc.postMemory = entries;
saveNpcs(npcs);
}
function generatePostSummary(type, title, content) {
const short = (content || '').slice(0, 30) + ((content || '').length > 30 ? '...' : '');
if (type === 'post') return `发帖「${title}」:${short}`;
return `在「${title}」中回复:${short}`;
}
function addPostMemoryEntry(targetType, targetId, summary, timestamp, postTitle, type) {
const entry = { id: Date.now() + Math.floor(Math.random() * 1000), summary, timestamp: timestamp || Date.now(), postTitle: postTitle || '', type: type || 'post' };
if (targetType === 'char') {
const entries = getCharPostMemory(targetId);
entries.push(entry);
saveCharPostMemory(targetId, entries);
} else {
const entries = getNpcPostMemory(targetId);
entries.push(entry);
saveNpcPostMemory(targetId, entries);
}
return entry;
}
function editPostMemoryEntry(targetType, targetId, entryId, summary) {
let entries = targetType === 'char' ? getCharPostMemory(targetId) : getNpcPostMemory(targetId);
const entry = entries.find(e => e.id === entryId);
if (!entry) return false;
entry.summary = summary;
if (targetType === 'char') saveCharPostMemory(targetId, entries);
else saveNpcPostMemory(targetId, entries);
return true;
}
function deletePostMemoryEntry(targetType, targetId, entryId) {
let entries = targetType === 'char' ? getCharPostMemory(targetId) : getNpcPostMemory(targetId);
entries = entries.filter(e => e.id !== entryId);
if (targetType === 'char') saveCharPostMemory(targetId, entries);
else saveNpcPostMemory(targetId, entries);
}
function scanAndSavePostMemory(newPosts) {
const contacts = getS('vibe_contacts', []);
const npcs = getNpcs();
const followedNpcNames = new Set(npcs.filter(n => n.followed).map(n => n.name));
for (const post of newPosts) {
// 帖子作者
if (post.authorType === 'char' && post.authorId) {
const summary = generatePostSummary('post', post.title, post.content);
addPostMemoryEntry('char', post.authorId, summary, post.createdAt, post.title, 'post');
} else if (post.authorType === 'npc' && followedNpcNames.has(post.authorName)) {
const npc = npcs.find(n => n.name === post.authorName);
if (npc) {
const summary = generatePostSummary('post', post.title, post.content);
addPostMemoryEntry('npc', npc.id, summary, post.createdAt, post.title, 'post');
}
}
// 回复
for (const reply of (post.replies || [])) {
if (reply.authorType === 'char' && reply.authorId) {
const summary = generatePostSummary('reply', post.title, reply.content);
addPostMemoryEntry('char', reply.authorId, summary, reply.createdAt, post.title, 'reply');
} else if (reply.authorType === 'npc' && followedNpcNames.has(reply.authorName)) {
const npc = npcs.find(n => n.name === reply.authorName);
if (npc) {
const summary = generatePostSummary('reply', post.title, reply.content);
addPostMemoryEntry('npc', npc.id, summary, reply.createdAt, post.title, 'reply');
}
}
}
}
}
function scanAndSaveReplyMemory(postTitle, newReplies) {
const npcs = getNpcs();
const followedNpcNames = new Set(npcs.filter(n => n.followed).map(n => n.name));
for (const reply of newReplies) {
if (reply.authorType === 'char' && reply.authorId) {
const summary = generatePostSummary('reply', postTitle, reply.content);
addPostMemoryEntry('char', reply.authorId, summary, reply.createdAt, postTitle, 'reply');
} else if (reply.authorType === 'npc' && followedNpcNames.has(reply.authorName)) {
const npc = npcs.find(n => n.name === reply.authorName);
if (npc) {
const summary = generatePostSummary('reply', postTitle, reply.content);
addPostMemoryEntry('npc', npc.id, summary, reply.createdAt, postTitle, 'reply');
}
}
}
}
function buildPostMemoryPrompt(contacts, followedNpcs) {
let sections = [];
// CHAR 发帖记忆
for (const c of contacts) {
const charId = c.id;
const name = c.nickname || c.name || 'CHAR';
const entries = getCharPostMemory(charId);
if (!entries.length) continue;
let lines = `${name}(CHAR)最近的论坛动态:\n`;
for (const e of entries.slice(-10)) {
const dateStr = new Date(e.timestamp).toLocaleDateString('zh-CN', { month: 'long', day: 'numeric' });
lines += `- ${e.summary} (${dateStr})\n`;
}
sections.push(lines);
}
// 已关注 NPC 发帖记忆
for (const npc of followedNpcs) {
const entries = getNpcPostMemory(npc.id);
if (!entries.length) continue;
let lines = `${npc.name}(已关注NPC)最近的论坛动态:\n`;
for (const e of entries.slice(-8)) {
const dateStr = new Date(e.timestamp).toLocaleDateString('zh-CN', { month: 'long', day: 'numeric' });
lines += `- ${e.summary} (${dateStr})\n`;
}
sections.push(lines);
}
if (!sections.length) return '';
return '\n【角色发帖历史】\n以下角色之前在论坛发过的内容,请保持连贯性:\n\n' + sections.join('\n');
}
function getOrCreateNpc(name, personality) {
let npcs = getNpcs();
let npc = npcs.find(n => n.name === name);
if (!npc) {
// 从头像池随机选取
const avatarPool = getS('forum_avatar_pool', []);
let avatarUrl = null;
if (avatarPool.length) {
avatarUrl = avatarPool[Math.floor(Math.random() * avatarPool.length)];
}
// 随机分配时区
const tz = COMMON_TIMEZONES[Math.floor(Math.random() * COMMON_TIMEZONES.length)];
npc = {
id: 'npc_' + Date.now() + '_' + Math.random().toString(36).slice(2, 6),
name,
emoji: NPC_EMOJIS[Math.floor(Math.random() * NPC_EMOJIS.length)],
avatarUrl,
personality: personality || '',
timezone: tz.offset,
createdAt: Date.now(),
lastActiveAt: Date.now()
};
npcs.push(npc);
// 超过上限时淘汰最久没活跃的
if (npcs.length > NPC_MAX_POOL) {
npcs = pruneNpcs(npcs);
}
saveNpcs(npcs);
} else {
// 更新活跃时间
npc.lastActiveAt = Date.now();
if (personality && !npc.personality) npc.personality = personality;
saveNpcs(npcs);
}
return npc;
}
// 淘汰不活跃的NPC,保留被当前帖子引用的和已关注的
function pruneNpcs(npcs) {
const posts = getPosts();
// 收集当前帖子中引用的NPC名字
const activeNames = new Set();
posts.forEach(p => {
if (p.authorType === 'npc') activeNames.add(p.authorName);
(p.replies || []).forEach(r => {
if (r.authorType === 'npc') activeNames.add(r.authorName);
});
});
// 已关注的NPC必须保留
const followed = npcs.filter(n => n.followed);
// 被帖子引用的必须保留(排除已在followed中的)
const referenced = npcs.filter(n => !n.followed && activeNames.has(n.name));
// 其余按lastActiveAt排序淘汰
const unreferenced = npcs.filter(n => !n.followed && !activeNames.has(n.name));
unreferenced.sort((a, b) => (b.lastActiveAt || b.createdAt) - (a.lastActiveAt || a.createdAt));
const keep = NPC_MAX_POOL - followed.length - referenced.length;
return [...followed, ...referenced, ...unreferenced.slice(0, Math.max(0, keep))];
}