-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrender.js
More file actions
675 lines (593 loc) · 22.1 KB
/
render.js
File metadata and controls
675 lines (593 loc) · 22.1 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
(function () {
let deepthink = document.createElement('style');
// make deepseek <think> look like <blockquote>
deepthink.textContent = `
think {
display: block;
margin: 1rem 0;
padding: 0.5rem 1rem;
border-left: 0.25rem solid #ccc;
background-color: #f9f9f9;
border-radius: 0.25rem;
font-size: 0.9rem;
line-height: 1.5;
color: #333;
}
think::before {
content: '🤔';
margin-right: 0.5rem;
font-size: 1rem;
color: #666;
}
.vbtn {
background-color: #4299e1;
border: none;
color: #333;
padding: 0.5rem 1rem;
border-radius: 0.25rem;
cursor: pointer;
font-size: 0.9rem;
margin-right: 0.5rem;
}
.vbtn.ignore-btn.ignored {
background-color: #ccc;
color: #666;
}
.message .message-content em {
color: #4299e1;
font-style: italic;
// smaller size
font-size: 0.8rem;
}
`;
document.head.appendChild(deepthink);
})()
function renderMessages() {
const messagesDiv = document.getElementById('messages');
messagesDiv.innerHTML = '';
state.chatHistory.forEach((msg, index) => {
const msgDiv = document.createElement('div');
msgDiv.className = `message ${msg.role}`;
msgDiv.style.marginBottom = '1rem';
msgDiv.style.padding = '0.5rem';
msgDiv.style.borderRadius = '0.25rem';
msgDiv.style.backgroundColor = msg.role === 'user' ? '#e3f2fd' : '#f5f5f5';
const isLast = index === state.chatHistory.length - 1;
const lastButton = isLast ? `<button class='resend-btn vbtn' style='border: none; cursor: pointer; font-size: 0.8rem;'>重发</button>` : '';
// 如果是loading消息,直接使用content中的HTML
if (msg.isLoading) {
msgDiv.innerHTML = `
<div style="font-size: 0.8rem; color: #666; margin-bottom: 0.3rem; display: flex; justify-content: space-between; align-items: center;">
<span>${msg.name} - ${new Date(msg.timestamp).toLocaleString()}</span>
</div>
<div class="message-content"></div>
`;
} else {
let content;
try {
content = marked.parse(msg.content);
} catch (e) {
content = msg.content;
}
msgDiv.innerHTML = `
<div style="font-size: 0.8rem; color: #666; margin-bottom: 0.3rem; display: flex; justify-content: space-between; align-items: center;">
<span>${msg.name} - ${new Date(msg.timestamp).toLocaleString()}</span>
<div class="message-actions" style="display: flex; gap: 0.5rem;">
<span class="text-length" style="font-size: 0.8rem; color: #666;">${msg.content.length}字</span>
<button class="ignore-btn vbtn" style="border: none; cursor: pointer; font-size: 0.8rem;">忽略</button>
<button class="edit-btn vbtn" style="border: none; cursor: pointer; font-size: 0.8rem;">修改</button>
<button class="delete-btn vbtn" style="border: none; cursor: pointer; font-size: 0.8rem;">删除</button>
<button class="add-btn vbtn" style="border: none; cursor: pointer; font-size: 0.8rem;">添加</button>
<button class="compress-btn vbtn" style="border: cursor: pointer; font-size: 0.8rem;">压缩</button>
<button class="fork-btn vbtn" style="border: none; cursor: pointer; font-size: 0.8rem;">分叉</button>
${lastButton}
</div>
</div>
<div class="message-content"></div>
`;
if (msg.reasoning_content) {
content = '<think>' + msg.reasoning_content + '</think>' + content;
}
msgDiv.querySelector('.message-content').innerHTML = content;
msgDiv.querySelector('.message-content').addEventListener('dblclick', () => {
// edit
showMessageDialog('edit', index, msg);
})
/*
for (let think of msgDiv.querySelectorAll('think')) {
// deepseek special tag, make it clickable and collapsible
think.addEventListener('click', () => {
think.classList.toggle('deepseek-collapsed-think');
});
}
*/
// 添加事件监听器
const editBtn = msgDiv.querySelector('.edit-btn');
const deleteBtn = msgDiv.querySelector('.delete-btn');
const addBtn = msgDiv.querySelector('.add-btn');
const resendBtn = msgDiv.querySelector('.resend-btn');
const compressBtn = msgDiv.querySelector('.compress-btn');
const forkBtn = msgDiv.querySelector('.fork-btn');
const ignoreBtn = msgDiv.querySelector('.ignore-btn');
if (msg.ignored) {
ignoreBtn.innerText = '取消忽略';
ignoreBtn.classList.add('ignored');
} else {
ignoreBtn.innerText = '忽略';
ignoreBtn.classList.remove('ignored');
}
ignoreBtn.addEventListener('click', () => {
msg.ignored = !msg.ignored;
if (msg.ignored) {
ignoreBtn.innerText = '取消忽略';
ignoreBtn.classList.add('ignored');
} else {
ignoreBtn.innerText = '忽略';
ignoreBtn.classList.remove('ignored');
}
saveState();
})
forkBtn.addEventListener('click', async () => {
// 调用window.exportChat, 需要await
// 然后删除这条消息后面的全部消息
try {
await window.exportChat();
state.chatHistory.splice(index + 1);
renderMessages();
} catch (e){
pageAlert('分叉失败', '分叉按钮');
}
})
compressBtn.addEventListener('click', async () => {
const text = msg.content;
const compressedText = await compress(text, msg.compressed);
if (compressedText != null) {
msg.compressed = compressedText
saveState();
renderMessages();
}
});
editBtn.addEventListener('click', () => {
showMessageDialog('edit', index, msg);
});
deleteBtn.addEventListener('click', () => {
if (confirm('确定要删除这条消息吗?')) {
state.trash.push(state.chatHistory[index]);
state.chatHistory.splice(index, 1);
saveState();
renderMessages();
}
});
addBtn.addEventListener('click', () => {
showMessageDialog('add', index);
});
if (resendBtn) {
resendBtn.addEventListener('click', resendMessage);
}
}
messagesDiv.appendChild(msgDiv);
});
// 滚动到底部
setTimeout(() => {
messagesDiv.scrollTop = messagesDiv.scrollHeight;
}, 0);
// 代码高亮
document.querySelectorAll('pre code').forEach((block) => {
hljs.highlightElement(block);
});
}
function resendMessage() {
if (state.chatHistory.length > 0 && state.chatHistory[state.chatHistory.length - 1].role == 'assistant') {
state.trash.push(state.chatHistory[state.chatHistory.length - 1]);
state.chatHistory.splice(state.chatHistory.length - 1, 1);
saveState();
nextMessage();
}
}
// 添加消息对话框函数
function showMessageDialog(type, index, msg = null) {
// 创建对话框
const dialog = document.createElement('div');
dialog.style.cssText = `
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: white;
padding: 1rem;
border-radius: 0.5rem;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
z-index: 100000;
width: 80%;
max-width: 500px;
`;
// 对话框内容
dialog.innerHTML = `
<h3 style="margin: 0 0 1rem 0">${type === 'edit' ? '修改消息' : '添加消息'}</h3>
<div style="margin-bottom: 1rem">
<label style="display: block; margin-bottom: 0.5rem">角色:</label>
<input type="text" id="role-input" value=""
style="width: 95%; padding: 0.5rem; border: 1px solid #ddd; border-radius: 0.25rem;">
</div>
<div style="margin-bottom: 1rem">
<label style="display: block; margin-bottom: 0.5rem">角色名:</label>
<input type="text" id="name-input" value=""
style="width: 95%; padding: 0.5rem; border: 1px solid #ddd; border-radius: 0.25rem;">
</div>
<div style="margin-bottom: 1rem">
<label style="display: block; margin-bottom: 0.5rem">内容:</label>
<textarea id="content-input" style="width: 95%; height: 200px; padding: 0.5rem; border: 1px solid #ddd; border-radius: 0.25rem;"></textarea>
</div>
<div style="margin-bottom: 1rem">
<label style="display: block; margin-bottom: 0.5rem">压缩内容:</label>
<textarea id="compressed-input" style="width: 95%; height: 200px; padding: 0.5rem; border: 1px solid #ddd; border-radius: 0.25rem;"></textarea>
</div>
<div style="display: flex; justify-content: flex-end; gap: 0.5rem;">
<button id="cancel-btn" style="padding: 0.5rem 1rem; border: 1px solid #ddd; border-radius: 0.25rem; background: white; cursor: pointer;">取消</button>
<button id="confirm-btn" style="padding: 0.5rem 1rem; border: none; border-radius: 0.25rem; background: #1976d2; color: white; cursor: pointer;">确定</button>
</div>
`;
makeCopyContentButton(dialog)
// 创建遮罩
const overlay = document.createElement('div');
overlay.style.cssText = `
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0,0,0,0.5);
z-index: 100000;
`;
// 添加到文档
document.body.appendChild(overlay);
document.body.appendChild(dialog);
// 事件处理
const cancelBtn = dialog.querySelector('#cancel-btn');
const confirmBtn = dialog.querySelector('#confirm-btn');
const roleInput = dialog.querySelector('#role-input');
const contentInput = dialog.querySelector('#content-input');
const compressedInput = dialog.querySelector('#compressed-input');
const nameInput = dialog.querySelector('#name-input');
contentInput.value = msg ? msg.content : '';
compressedInput.value = msg ? (msg.compressed || '') : '';
nameInput.value = msg ? (msg.name || msg.role) : 'user'
roleInput.value = msg ? msg.role : 'user';
cancelBtn.addEventListener('click', () => {
overlay.remove();
dialog.remove();
});
confirmBtn.addEventListener('click', () => {
const role = roleInput.value.trim();
const content = contentInput.value.trim();
const name = nameInput.value.trim();
const compressed = compressedInput.value.trim();
if (!role || !content) {
alert('角色和内容不能为空');
return;
}
if (type === 'edit') {
// 修改消息
state.chatHistory[index] = {
...msg,
role,
content,
name,
compressed,
timestamp: Date.now()
};
} else {
// 添加消息
state.chatHistory.splice(index, 0, {
role,
content,
name,
compressed,
timestamp: Date.now()
});
}
saveState();
renderMessages();
overlay.remove();
dialog.remove();
});
}
async function compress(originText, previous) {
// Create modal container
const modal = document.createElement('div');
modal.style.cssText = `
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.5);
display: flex;
align-items: center;
justify-content: center;
z-index: 100000;
`;
// Create modal content
const content = document.createElement('div');
content.style.cssText = `
background: white;
padding: 20px;
border-radius: 8px;
width: 80%;
max-width: 800px;
max-height: 90vh;
overflow-y: auto;
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
`;
makeCopyContentButton(modal)
// Left column
const leftColumn = document.createElement('div');
const promptLabel = document.createElement('div');
promptLabel.textContent = '压缩提示:';
const promptText = document.createElement('textarea');
promptText.style.cssText = `
width: 100%;
height: 150px;
margin: 10px 0;
padding: 8px;
`;
promptText.value = state.compress.prompt || `请按照以下要求对提供的小说章节或对话进行压缩处理,确保为后续生成新章节提供参考背景,同时结合新的生成要求创作新章节:
1. **压缩目标**:将原文压缩至约原文长度的40%,约800字符左右,确保文本连贯,重点突出关键剧情、人物关系及伏笔。细节描写和冗长对话只需简略带过。
2. **章节结构**:保留原章节标题(如“第一季 第二章”)不做修改。
3. **文风概述**:用方括号简要概括原文风格及修辞特点,体现文笔特征。
4. **原文摘录**:从原文中摘录1-2段最具代表性的语句(以主角和主要人物的语言为主),标注为「原文摘录」,以免风格丢失。
5. **剧情要求**:剧情需精炼但完整,保留主要伏笔、人物设定、互动方式与整体氛围,不遗漏关键情节。
压缩后的文本将作为背景材料,在后续新章节生成时与新的要求结合,确保文风、节奏和人物延续,并适当铺垫后续情节。
---
### 输出格式
**正文 第?季 第?章**(如适用)
**概述1**:概述原文风格与修辞特点
**概述2**: 概述这一章的人物的主要观点和意图
**压缩剧情**:精炼后的关键情节和人物关系描述
**原文摘录**:「(摘录体现文笔风格的语句)」
**[End]
### 原文
{{input}}
请完成上述压缩任务(约400字符左右)
`; // Default prompt
/*
const endpointLabel = document.createElement('div');
endpointLabel.textContent = 'API Endpoint:';
const endpointInput = document.createElement('input');
endpointInput.style.cssText = `
width: 100%;
margin: 10px 0;
padding: 8px;
`;
endpointInput.value = state.compress.endpoint || 'http://localhost:5001';
const endpointParse = document.createElement('button')
endpointParse.textContent = '解析';
endpointParse.style.cssText = `
padding: 8px 16px;
background: #2196F3;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
`;
endpointParse.addEventListener('click', async () => {
try {
const config = await parseEndpoint(endpointInput.value || '')
endpointInput.value = JSON.stringify(config)
endpointInput.dispatchEvent(new Event('input'))
} catch (error) {
pageAlert(error.message)
}
});
*/
const inputLabel = document.createElement('div');
inputLabel.textContent = '待压缩内容:';
const inputText = document.createElement('textarea');
inputText.style.cssText = `
width: 100%;
height: 150px;
margin: 10px 0;
padding: 8px;
`;
inputText.value = originText;
// Right column - Result
const rightColumn = document.createElement('div');
const resultLabel = document.createElement('div');
resultLabel.textContent = '压缩结果:';
const resultText = document.createElement('textarea');
resultText.style.cssText = `
width: 100%;
height: 400px;
margin: 10px 0;
padding: 8px;
`;
// Buttons
const buttonContainer = document.createElement('div');
buttonContainer.style.cssText = `
grid-column: span 2;
display: flex;
justify-content: flex-end;
gap: 10px;
margin-top: 10px;
`;
const compressBtn = document.createElement('button');
compressBtn.textContent = '压缩';
compressBtn.style.cssText = `
padding: 8px 16px;
background: #2196F3;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
`;
const compressAIConfigBtn = document.createElement('button');
compressAIConfigBtn.style.cssText = `
padding: 8px 16px;
background: #2196F3;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
`;
AIHub.drawButton(compressAIConfigBtn, "compress")
const confirmBtn = document.createElement('button');
confirmBtn.textContent = '确认';
confirmBtn.style.cssText = `
padding: 8px 16px;
background: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
`;
const cancelBtn = document.createElement('button');
cancelBtn.textContent = '取消';
cancelBtn.style.cssText = `
padding: 8px 16px;
background: #f44336;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
`;
// Handle events
promptText.addEventListener('input', () => {
state.compress.prompt = promptText.value;
});
/*
endpointInput.addEventListener('input', () => {
state.compress.endpoint = endpointInput.value;
});
*/
resultText.value = previous || '';
let resolvePromise;
const promise = new Promise(resolve => {
resolvePromise = resolve;
});
compressBtn.onclick = async () => {
async function copyToClipboard (element, button) {
try {
await navigator.clipboard.writeText(element.value);
const originalText = button.textContent;
button.textContent = '已复制!';
button.style.background = '#4CAF50';
setTimeout(() => {
button.textContent = originalText;
button.style.background = '#2196F3';
}, 1000);
} catch (err) {
console.error('复制失败:', err);
alert('复制失败,请手动复制');
}
};
try {
compressBtn.disabled = true;
compressBtn.textContent = '压缩中...';
// 创建浮层
const compressInfoDiv = document.createElement('div');
compressInfoDiv.style.cssText = `
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: rgba(0, 0, 0, 0.7);
color: white;
padding: 20px;
border-radius: 8px;
z-index: 100000;
font-size: 16px;
`;
compressInfoDiv.textContent = '压缩中,请稍候...';
document.body.appendChild(compressInfoDiv);
const context = await processContextV2(inputText.value, promptText.value);
const messages = parseMessages(context)
console.log(messages, context)
await AIHub.callAPI('compress', messages, {
onToken: (token, fullContent) => {
compressInfoDiv.textContent = '压缩中:' + fullContent;
},
onComplete: async (fullContent) => {
resultText.value = fullContent;
compressBtn.disabled = false;
compressBtn.textContent = '压缩';
document.body.removeChild(compressInfoDiv); // 移除浮层
},
onError: (err) => {
pageAlert('Error: ' + err.message);
document.body.removeChild(compressInfoDiv); // 移除浮层
}
})
/*
if (endpointInput.value !== 'manual') {
const config = await parseEndpoint(endpointInput.value || '');
if (config) {
endpointInput.value = JSON.stringify(config);
// dispatch onInput
endpointInput.dispatchEvent(new Event('input'));
}
let headers = {
'Content-Type': 'application/json'
}
if (config.key) {
headers['Authorization'] = 'Bearer ' + config.key
};
const response = await fetch(config.url + '/v1/chat/completions', {
method: 'POST',
headers,
body: JSON.stringify({
model: config.model,
messages: [
{role: "user", content: await processContextV2(inputText.value, promptText.value)},
],
...config.params, // Spread additional parameters
max_tokens: config.params.max_tokens || 800,
temperature: config.params.temperature || 0.4,
})
});
const result = await response.json();
resultText.value = result?.choices?.[0]?.message?.content || '';
} else {
resultText.value = await processContextV2(inputText.value, promptText.value);
await copyToClipboard(resultText, compressBtn);
pageAlert('已复制到剪贴板');
}*/
} catch(err) {
pageAlert('Error: ' + err.message);
compressBtn.disabled = false;
compressBtn.textContent = '压缩';
} finally {
}
};
confirmBtn.onclick = () => {
modal.remove();
resolvePromise(resultText.value);
};
cancelBtn.onclick = () => {
modal.remove();
resolvePromise(null);
};
// Assemble modal
buttonContainer.appendChild(cancelBtn);
buttonContainer.appendChild(compressBtn);
buttonContainer.appendChild(compressAIConfigBtn);
buttonContainer.appendChild(confirmBtn);
leftColumn.appendChild(promptLabel);
leftColumn.appendChild(promptText);
/*
leftColumn.appendChild(endpointLabel);
leftColumn.appendChild(endpointInput);
leftColumn.appendChild(endpointParse);
*/
leftColumn.appendChild(inputLabel);
leftColumn.appendChild(inputText);
rightColumn.appendChild(resultLabel);
rightColumn.appendChild(resultText);
content.appendChild(leftColumn);
content.appendChild(rightColumn);
content.appendChild(buttonContainer);
modal.appendChild(content);
document.body.appendChild(modal);
return promise;
}