-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
677 lines (572 loc) · 22.4 KB
/
index.js
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
const {
eventSource,
event_types,
getCurrentChatId,
renameChat,
getRequestHeaders,
openGroupChat,
openCharacterChat,
executeSlashCommandsWithOptions,
Popup,
} = SillyTavern.getContext();
import { addJQueryHighlight } from './jquery-highlight.js';
import { getGroupPastChats } from '../../../group-chats.js';
import { getPastCharacterChats, animation_duration, animation_easing, getGeneratingApi } from '../../../../script.js';
import { debounce, timestampToMoment, sortMoments, uuidv4, waitUntilCondition } from '../../../utils.js';
import { t } from '../../../i18n.js';
const movingDivs = /** @type {HTMLDivElement} */ (document.getElementById('movingDivs'));
const sheld = /** @type {HTMLDivElement} */ (document.getElementById('sheld'));
const chat = /** @type {HTMLDivElement} */ (document.getElementById('chat'));
const draggableTemplate = /** @type {HTMLTemplateElement} */ (document.getElementById('generic_draggable_template'));
const apiBlock = /** @type {HTMLDivElement} */ (document.getElementById('rm_api_block'));
const topBar = document.createElement('div');
const chatName = document.createElement('select');
const searchInput = document.createElement('input');
const connectionProfiles = document.createElement('div');
const connectionProfilesStatus = document.createElement('div');
const connectionProfilesSelect = document.createElement('select');
const connectionProfilesIcon = document.createElement('img');
const icons = [
{
id: 'extensionTopBarToggleSidebar',
icon: 'fa-fw fa-solid fa-box-archive',
position: 'left',
title: t`Toggle sidebar`,
onClick: onToggleSidebarClick,
},
{
id: 'extensionTopBarToggleConnectionProfiles',
icon: 'fa-fw fa-solid fa-plug',
position: 'left',
title: t`Show connection profiles`,
onClick: onToggleConnectionProfilesClick,
},
{
id: 'extensionTopBarChatManager',
icon: 'fa-fw fa-solid fa-address-book',
position: 'right',
title: t`View chat files`,
onClick: onChatManagerClick,
},
{
id: 'extensionTopBarNewChat',
icon: 'fa-fw fa-solid fa-comments',
position: 'right',
title: t`New chat`,
onClick: onNewChatClick,
},
{
id: 'extensionTopBarRenameChat',
icon: 'fa-fw fa-solid fa-edit',
position: 'right',
title: t`Rename chat`,
onClick: onRenameChatClick,
},
{
id: 'extensionTopBarDeleteChat',
icon: 'fa-fw fa-solid fa-trash',
position: 'right',
title: t`Delete chat`,
onClick: async () => {
const confirm = await Popup.show.confirm(t`Are you sure?`);
if (confirm) {
await executeSlashCommandsWithOptions('/delchat');
}
},
},
{
id: 'extensionTopBarCloseChat',
icon: 'fa-fw fa-solid fa-times',
position: 'right',
title: t`Close chat`,
onClick: onCloseChatClick,
},
];
function onChatManagerClick() {
document.getElementById('option_select_chat')?.click();
}
function onCloseChatClick() {
document.getElementById('option_close_chat')?.click();
}
function onNewChatClick() {
document.getElementById('option_start_new_chat')?.click();
}
async function onRenameChatClick() {
const currentChatName = getCurrentChatId();
if (!currentChatName) {
return;
}
const newChatName = await Popup.show.input(t`Enter new chat name`, null, currentChatName);
if (!newChatName || newChatName === currentChatName) {
return;
}
await renameChat(currentChatName, String(newChatName));
}
function patchSheldIfNeeded() {
// Fun fact: sheld is a typo. It should be shell.
// It was fixed in OG TAI long ago, but we still have it here.
if (!sheld) {
console.error('Sheld not found. Did you finally rename it?');
return;
}
const computedStyle = getComputedStyle(sheld);
// Alert: We're not in a version that switched sheld to flex yet.
if (computedStyle.display === 'grid') {
sheld.classList.add('flexPatch');
}
}
function setChatName(name) {
const isNotInChat = !name;
chatName.innerHTML = '';
const selectedOption = document.createElement('option');
selectedOption.innerText = name || t`No chat selected`;
selectedOption.selected = true;
chatName.appendChild(selectedOption);
chatName.disabled = true;
icons.forEach(icon => {
const iconElement = document.getElementById(icon.id);
if (iconElement) {
iconElement.classList.toggle('not-in-chat', isNotInChat);
}
});
if (!isNotInChat && typeof openGroupChat === 'function' && typeof openCharacterChat === 'function') {
setTimeout(async () => {
const list = [];
const context = SillyTavern.getContext();
if (context.groupId) {
const group = context.groups.find(x => x.id == context.groupId);
if (group) {
list.push(...group.chats);
}
}
else {
const characterAvatar = context.characters[context.characterId]?.avatar;
list.push(...await getListOfCharacterChats(characterAvatar));
}
if (list.length > 0) {
chatName.innerHTML = '';
list.sort((a, b) => a.localeCompare(b)).forEach((x) => {
const option = document.createElement('option');
option.innerText = x;
option.value = x;
option.selected = x === name;
chatName.appendChild(option);
});
chatName.disabled = false;
}
await populateSideBar();
}, 0);
}
if (isNotInChat) {
setTimeout(() => populateSideBar(), 0);
}
}
/**
* Get list of chat names for a character.
* @param {string} avatar Avatar name of the character
* @returns {Promise<string[]>} List of chat names
*/
async function getListOfCharacterChats(avatar) {
try {
const result = await fetch('/api/characters/chats', {
method: 'POST',
headers: getRequestHeaders(),
body: JSON.stringify({ avatar_url: avatar, simple: true }),
});
if (!result.ok) {
return [];
}
const data = await result.json();
return data.map(x => String(x.file_name).replace('.jsonl', ''));
} catch (error) {
console.error('Failed to get list of character chats', error);
return [];
}
}
async function getChatFiles() {
const context = SillyTavern.getContext();
const chatId = getCurrentChatId();
if (!chatId) {
return [];
}
if (context.groupId) {
return await getGroupPastChats(context.groupId);
}
if (context.characterId !== undefined) {
return await getPastCharacterChats(context.characterId);
}
return [];
}
/**
* Highlight search query in chat messages
* @param {string} query Search query
* @returns {void}
*/
function searchInChat(query) {
const options = { element: 'mark', className: 'highlight' };
const messages = jQuery(chat).find('.mes_text');
messages.unhighlight(options);
if (!query) {
return;
}
const splitQuery = query.split(/\s|\b/);
messages.highlight(splitQuery, options);
}
const searchDebounced = debounce((x) => searchInChat(x), 500);
const updateStatusDebounced = debounce(onOnlineStatusChange, 1000);
function addTopBar() {
chatName.id = 'extensionTopBarChatName';
topBar.id = 'extensionTopBar';
searchInput.id = 'extensionTopBarSearchInput';
searchInput.placeholder = 'Search...';
searchInput.classList.add('text_pole');
searchInput.type = 'search';
searchInput.addEventListener('input', () => searchDebounced(searchInput.value.trim()));
topBar.append(chatName, searchInput);
sheld.insertBefore(topBar, chat);
}
function addIcons() {
icons.forEach(icon => {
const iconElement = document.createElement('i');
iconElement.id = icon.id;
iconElement.className = icon.icon;
iconElement.title = icon.title;
iconElement.tabIndex = 0;
iconElement.classList.add('right_menu_button');
iconElement.addEventListener('click', () => {
if (iconElement.classList.contains('not-in-chat')) {
return;
}
icon.onClick();
});
if (icon.position === 'left') {
topBar.insertBefore(iconElement, chatName);
return;
}
if (icon.position === 'right') {
topBar.appendChild(iconElement);
return;
}
if (icon.position === 'middle') {
topBar.insertBefore(iconElement, searchInput);
return;
}
if (icon.id === 'extensionTopBarRenameChat' && typeof renameChat !== 'function') {
iconElement.classList.add('displayNone');
}
});
}
function addSideBar() {
if (!draggableTemplate) {
console.warn(t`Draggable template not found. Side bar will not be added.`);
return;
}
const fragment = /** @type {DocumentFragment} */ (draggableTemplate.content.cloneNode(true));
const draggable = fragment.querySelector('.draggable');
const closeButton = fragment.querySelector('.dragClose');
if (!draggable || !closeButton) {
console.warn(t`Failed to find draggable or close button. Side bar will not be added.`);
return;
}
draggable.id = 'extensionSideBar';
closeButton.addEventListener('click', onToggleSidebarClick);
const scrollContainer = document.createElement('div');
scrollContainer.id = 'extensionSideBarContainer';
draggable.appendChild(scrollContainer);
const loaderContainer = document.createElement('div');
loaderContainer.id = 'extensionSideBarLoader';
draggable.appendChild(loaderContainer);
const loaderIcon = document.createElement('i');
loaderIcon.className = 'fa-2x fa-solid fa-gear fa-spin';
loaderContainer.appendChild(loaderIcon);
movingDivs.appendChild(draggable);
}
function addConnectionProfiles() {
connectionProfiles.id = 'extensionConnectionProfiles';
connectionProfilesStatus.id = 'extensionConnectionProfilesStatus';
connectionProfilesSelect.id = 'extensionConnectionProfilesSelect';
connectionProfilesSelect.title = t`Switch connection profile`;
const connectionProfilesServerIcon = document.createElement('i');
connectionProfilesServerIcon.id = 'extensionConnectionProfilesIcon';
connectionProfilesServerIcon.className = 'fa-fw fa-solid fa-network-wired';
connectionProfiles.append(connectionProfilesServerIcon, connectionProfilesSelect, connectionProfilesStatus, connectionProfilesIcon);
sheld.insertBefore(connectionProfiles, chat);
apiBlock.querySelectorAll('select').forEach(select => {
select.addEventListener('input', () => updateStatusDebounced());
});
}
function bindConnectionProfilesSelect() {
waitUntilCondition(() => document.getElementById('connection_profiles') !== null).then(() => {
const connectionProfilesMainSelect = /** @type {HTMLSelectElement} */ (document.getElementById('connection_profiles'));
if (!connectionProfilesMainSelect) {
return;
}
connectionProfilesSelect.addEventListener('change', async () => {
connectionProfilesMainSelect.value = connectionProfilesSelect.value;
connectionProfilesMainSelect.dispatchEvent(new Event('change'));
});
connectionProfilesMainSelect.addEventListener('change', async () => {
connectionProfilesSelect.value = connectionProfilesMainSelect.value;
});
const observer = new MutationObserver(() => {
connectionProfilesSelect.innerHTML = connectionProfilesMainSelect.innerHTML;
connectionProfilesSelect.value = connectionProfilesMainSelect.value;
});
observer.observe(connectionProfilesMainSelect, { childList: true });
});
}
async function onToggleSidebarClick() {
const sidebar = document.getElementById('extensionSideBar');
const toggle = document.getElementById('extensionTopBarToggleSidebar');
if (!sidebar || !toggle) {
console.warn(t`Sidebar or toggle button not found`);
return;
}
toggle.classList.toggle('active');
const alreadyVisible = sidebar.classList.contains('visible');
const keyframes = [
{ opacity: alreadyVisible ? 1 : 0 },
{ opacity: alreadyVisible ? 0 : 1 },
];
const options = {
duration: animation_duration,
easing: animation_easing,
};
const animation = sidebar.animate(keyframes, options);
if (alreadyVisible) {
await animation.finished;
sidebar.classList.toggle('visible');
await populateSideBar();
} else {
sidebar.classList.toggle('visible');
await populateSideBar();
await animation.finished;
}
savePanelsState();
}
async function populateSideBar() {
const sidebar = document.getElementById('extensionSideBar');
const loader = document.getElementById('extensionSideBarLoader');
const container = document.getElementById('extensionSideBarContainer');
if (!loader || !container || !sidebar) {
return;
}
if (!sidebar.classList.contains('visible')) {
container.innerHTML = '';
return;
}
loader.classList.add('displayNone');
const processId = uuidv4();
const scrollTop = container.scrollTop;
const prettify = x => {
x.last_mes = timestampToMoment(x.last_mes);
x.file_name = String(x.file_name).replace('.jsonl', '');
return x;
};
container.dataset.processId = processId;
const chatId = getCurrentChatId();
const chats = (await getChatFiles()).map(prettify).sort((a, b) => sortMoments(a.last_mes, b.last_mes));
if (container.dataset.processId !== processId) {
console.log(t`Aborting populateSideBar due to process id mismatch`);
return;
}
container.innerHTML = '';
for (const chat of chats) {
const sideBarItem = document.createElement('div');
sideBarItem.classList.add('sideBarItem');
sideBarItem.addEventListener('click', async () => {
if (chat.file_name === chatId || sideBarItem.classList.contains('selected')) {
return;
}
container.childNodes.forEach(x => x instanceof HTMLElement && x.classList.remove('selected'));
sideBarItem.classList.add('selected');
await openChatById(chat.file_name);
});
const isSelected = chat.file_name === chatId;
sideBarItem.classList.toggle('selected', isSelected);
const chatName = document.createElement('div');
chatName.classList.add('chatName');
chatName.textContent = chat.file_name;
chatName.title = chat.file_name;
const chatDate = document.createElement('small');
chatDate.classList.add('chatDate');
chatDate.textContent = chat.last_mes.format('l');
chatDate.title = chat.last_mes.format('LL LT');
const chatNameContainer = document.createElement('div');
chatNameContainer.classList.add('chatNameContainer');
chatNameContainer.append(chatName, chatDate);
const chatMessage = document.createElement('div');
chatMessage.classList.add('chatMessage');
chatMessage.textContent = chat.mes;
chatMessage.title = chat.mes;
const chatStats = document.createElement('div');
chatStats.classList.add('chatStats');
const counterBlock = document.createElement('div');
counterBlock.classList.add('counterBlock');
const counterIcon = document.createElement('i');
counterIcon.classList.add('fa-solid', 'fa-comment', 'fa-xs');
const counterText = document.createElement('small');
counterText.textContent = chat.chat_items;
counterBlock.append(counterIcon, counterText);
const fileSizeText = document.createElement('small');
fileSizeText.classList.add('fileSize');
fileSizeText.textContent = chat.file_size;
chatStats.append(counterBlock, fileSizeText);
const chatMessageContainer = document.createElement('div');
chatMessageContainer.classList.add('chatMessageContainer');
chatMessageContainer.append(chatMessage, chatStats);
sideBarItem.append(chatNameContainer, chatMessageContainer);
container.appendChild(sideBarItem);
}
container.scrollTop = scrollTop;
/** @type {HTMLElement} */
const selectedElement = container.querySelector('.selected');
const isSelectedElementVisible = selectedElement && selectedElement.offsetTop >= container.scrollTop && selectedElement.offsetTop <= container.scrollTop + container.clientHeight;
if (!isSelectedElementVisible) {
container.scrollTop = selectedElement.offsetTop - container.clientHeight / 2;
}
loader.classList.add('displayNone');
}
async function openChatById(chatId) {
const context = SillyTavern.getContext();
if (!chatId) {
return;
}
if (typeof openGroupChat === 'function' && context.groupId) {
await openGroupChat(context.groupId, chatId);
return;
}
if (typeof openCharacterChat === 'function' && context.characterId !== undefined) {
await openCharacterChat(chatId);
return;
}
}
async function onChatNameChange() {
const chatId = chatName.value;
await openChatById(chatId);
}
async function onToggleConnectionProfilesClick() {
const button = document.getElementById('extensionTopBarToggleConnectionProfiles');
if (!button) {
console.warn('Connection profiles button not found');
return;
}
button.classList.toggle('active');
connectionProfiles.classList.toggle('visible');
savePanelsState();
await onOnlineStatusChange();
}
async function onOnlineStatusChange() {
if (!connectionProfiles.classList.contains('visible')) {
return;
}
const connectionProfilesMainSelect = /** @type {HTMLSelectElement} */ (document.getElementById('connection_profiles'));
if (connectionProfilesMainSelect) {
connectionProfilesSelect.innerHTML = connectionProfilesMainSelect.innerHTML;
connectionProfilesSelect.value = connectionProfilesMainSelect.value;
} else {
connectionProfilesSelect.classList.add('displayNone');
}
if (connectionProfilesStatus.nextElementSibling?.classList?.contains('icon-svg')) {
connectionProfilesStatus.nextElementSibling.remove();
}
const { SlashCommandParser, onlineStatus, mainApi } = SillyTavern.getContext();
if (onlineStatus === 'no_connection') {
connectionProfilesStatus.classList.add('offline');
connectionProfilesStatus.textContent = t`No connection...`;
const nullIcon = new Image();
nullIcon.classList.add('icon-svg', 'null-icon');
connectionProfilesStatus.insertAdjacentElement('afterend', nullIcon);
return;
}
async function getCurrentAPI() {
let currentAPI = mainApi;
try {
const commandResult = await SlashCommandParser.commands['api'].callback({ quiet: 'true' }, '');
if (commandResult) {
currentAPI = commandResult;
}
} catch (error) {
console.error(t`Failed to get current API`, error);
}
const fancyNameOption = apiBlock.querySelector(`select:not(#main_api) option[value="${currentAPI}"]`) ?? apiBlock.querySelector(`select#main_api option[value="${currentAPI}"]`);
if (fancyNameOption) {
// Remove text in parentheses or brackets
return fancyNameOption.textContent.replace(/[[(].*[\])]/, '').trim();
}
return currentAPI;
}
async function getCurrentModel() {
let currentModel = onlineStatus;
try {
const commandResult = await SlashCommandParser.commands['model'].callback({ quiet: 'true' }, '');
if (commandResult && typeof commandResult === 'string') {
currentModel = commandResult;
}
} catch (error) {
console.error(t`Failed to get current model`, error);
}
const fancyNameOption = apiBlock.querySelector(`option[value="${currentModel}"]`);
if (fancyNameOption) {
return fancyNameOption.textContent.trim();
}
return currentModel;
}
const [currentAPI, currentModel] = await Promise.all([getCurrentAPI(), getCurrentModel()]);
await addConnectionProfileIcon();
connectionProfilesStatus.classList.remove('offline');
connectionProfilesStatus.textContent = `${currentAPI} – ${currentModel}`;
}
async function addConnectionProfileIcon() {
return new Promise((resolve) => {
const modelName = getGeneratingApi();
const image = new Image();
image.classList.add('icon-svg');
image.src = `/img/${modelName}.svg`;
image.onload = async function () {
connectionProfilesStatus.insertAdjacentElement('afterend', image);
await SVGInject(image);
resolve();
};
image.onerror = function () {
resolve();
};
// Prevent infinite waiting
setTimeout(() => resolve(), 500);
});
}
function savePanelsState() {
localStorage.setItem('topBarPanelsState', JSON.stringify({
sidebarVisible: document.getElementById('extensionSideBar')?.classList.contains('visible'),
connectionProfilesVisible: document.getElementById('extensionConnectionProfiles')?.classList.contains('visible'),
}));
}
function restorePanelsState() {
const state = JSON.parse(localStorage.getItem('topBarPanelsState'));
if (!state) {
return;
}
if (state.sidebarVisible) {
document.getElementById('extensionTopBarToggleSidebar')?.click();
}
if (state.connectionProfilesVisible) {
document.getElementById('extensionTopBarToggleConnectionProfiles')?.click();
}
}
// Init extension on load
(async function () {
addJQueryHighlight();
patchSheldIfNeeded();
addTopBar();
addIcons();
addSideBar();
addConnectionProfiles();
setChatName(getCurrentChatId());
chatName.addEventListener('change', onChatNameChange);
eventSource.on(event_types.CHAT_CHANGED, setChatName);
eventSource.once(event_types.APP_READY, () => {
bindConnectionProfilesSelect();
restorePanelsState();
});
eventSource.on(event_types.ONLINE_STATUS_CHANGED, updateStatusDebounced);
})();