forked from aikohanasaki/SillyTavern-MemoryBooks
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclipManager.js
More file actions
2461 lines (2210 loc) · 109 KB
/
Copy pathclipManager.js
File metadata and controls
2461 lines (2210 loc) · 109 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
// Copyright (C) 2024–2026 Aiko Hanasaki
// SPDX-License-Identifier: AGPL-3.0-only
import { Popup, POPUP_RESULT, POPUP_TYPE } from '../../../popup.js';
import { chat_metadata, saveSettingsDebounced } from '../../../../script.js';
import { extension_settings } from '../../../extensions.js';
import {
createWorldInfoEntry,
loadWorldInfo,
METADATA_KEY,
reloadEditor,
saveWorldInfo,
world_names,
} from '../../../world-info.js';
import { DOMPurify } from '../../../../lib.js';
import { oai_settings } from '../../../openai.js';
import { translate } from '../../../i18n.js';
import { escapeHtml } from '../../../utils.js';
import { getEntryByTitle, isMemoryEntry } from './addlore.js';
import { validateLorebookRequirement } from './lorebookValidation.js';
import { getSceneMarkers } from './sceneManager.js';
import { isSidePromptEntryTitle } from './sidePrompts.js';
import { requestCompletion } from './stmemory.js';
import {
getCurrentApiInfo,
getCurrentManualLorebookResolution,
getUIModelSettings,
markStmbPopup,
normalizeCompletionSource,
readIntInput,
resolveEffectiveConnectionFromProfile,
withGoBackButton,
} from './utils.js';
import { withStmbWriteLane } from './stmbJobs.js';
// STMBC-HOOK(clipper): paired keyword-activated context entry on clip save (fork; plan §4.2).
import { maybeGeneratePairedContextEntry } from './clipperPlus.js';
import {
DEFAULT_COMPACTION_PROMPT_TEMPLATE,
DEFAULT_TOPICAL_CLIP_PROMPT_TEMPLATE,
} from './clipPromptDefaults.js';
export {
DEFAULT_COMPACTION_PROMPT_TEMPLATE,
DEFAULT_TOPICAL_CLIP_PROMPT_TEMPLATE,
} from './clipPromptDefaults.js';
const MODULE_NAME = 'STMemoryBooks-ClipManager';
const CREATE_NEW_VALUE = '__stmb_create_new_clip_entry__';
const TOKEN_WARNING_THRESHOLD = 500;
const FLOATING_CLIP_X_OFFSET = 6;
const FLOATING_CLIP_Y_OFFSET = -4;
const FLOATING_CLIP_VIEWPORT_PADDING = 8;
export const STMB_CLIP_TITLE_SUFFIX = ' [STMB Clip]';
let floatingClipButton = null;
let floatingClipListenersBound = false;
let floatingClipUpdateTimer = null;
function tr(key, fallback, params = null) {
let value = translate(fallback, key);
if (params) {
value = value.replace(/\{\{\s*(\w+)\s*\}\}/g, (_match, name) => {
const replacement = params[name];
return replacement === undefined || replacement === null ? '' : String(replacement);
});
}
return value;
}
function populateCompactionPromptButton(popup) {
const container = popup.dlg?.querySelector('#stmb-compaction-prompt-buttons');
if (!container) return;
const compactionPromptButtons = [
{
text: tr('STMemoryBooks_Compaction_EditPrompt', 'Edit Compaction Prompt'),
id: 'stmb-edit-compaction-prompt',
action: () => {
void showCompactionPromptEditorPopup();
},
},
];
container.innerHTML = '';
compactionPromptButtons.forEach((buttonConfig) => {
const button = document.createElement('div');
button.className = 'menu_button interactable whitespacenowrap';
button.id = buttonConfig.id;
button.textContent = buttonConfig.text;
button.addEventListener('click', buttonConfig.action);
container.appendChild(button);
});
}
function estimateTokens(content) {
return Math.ceil(String(content || '').length / 4);
}
export function isClipEntryTitle(title) {
return typeof title === 'string' && title.trimEnd().endsWith('[STMB Clip]');
}
export function getClipHeadlineFromTitle(title) {
const raw = String(title || '').trimEnd();
if (!isClipEntryTitle(raw)) return raw.trim();
return raw.slice(0, raw.length - '[STMB Clip]'.length).trim();
}
function validateClipHeadline(headline) {
const raw = String(headline || '').trim();
const clean = isClipEntryTitle(raw) ? getClipHeadlineFromTitle(raw) : raw;
if (!clean) {
throw new Error(tr('STMemoryBooks_Clip_ErrorEmptyHeadline', 'Entry title / section headline cannot be empty.'));
}
if (/[\r\n]/.test(clean) || /[\u0000-\u001F\u007F]/.test(clean)) {
throw new Error(tr('STMemoryBooks_Clip_ErrorInvalidHeadlineControl', 'Entry title / section headline cannot contain newlines or control characters.'));
}
if (clean.includes('[STMB Clip]')) {
throw new Error(tr('STMemoryBooks_Clip_ErrorInvalidHeadlineSuffix', 'Entry title / section headline cannot contain [STMB Clip].'));
}
if (clean.includes('===')) {
throw new Error(tr('STMemoryBooks_Clip_ErrorInvalidHeadlineMarker', 'Entry title / section headline cannot contain ===.'));
}
return clean;
}
export function makeClipEntryTitle(headline) {
const clean = validateClipHeadline(headline);
return `${clean}${STMB_CLIP_TITLE_SUFFIX}`;
}
export function makeClipStartMarker(headline) {
return `=== ${headline} ===`;
}
export function makeClipEndMarker(headline) {
return `=== END ${headline} ===`;
}
function stripLeadingBulletMarker(line) {
return String(line || '').replace(/^\s*(?:[-*•]\s+|\d+[.)]\s+)/, '');
}
function formatClipBullet(text) {
const lines = String(text || '')
.replace(/\r\n?/g, '\n')
.split('\n')
.map(line => stripLeadingBulletMarker(line).trim())
.filter(Boolean);
if (lines.length === 0) {
throw new Error(tr('STMemoryBooks_Clip_ErrorEmptySelectedText', 'Selected text cannot be empty.'));
}
const [first, ...rest] = lines;
return [`- ${first}`, ...rest.map(line => ` ${line}`)].join('\n');
}
export function createClipEntryContent(headline, bulletText) {
const startMarker = makeClipStartMarker(headline);
const endMarker = makeClipEndMarker(headline);
return `${startMarker}\n\n${formatClipBullet(bulletText)}\n\n${endMarker}`;
}
function normalizeBulletForDuplicate(text) {
return stripLeadingBulletMarker(String(text || ''))
.trim()
.replace(/\s+/g, ' ');
}
function collectBulletBlocks(content) {
const blocks = [];
let current = null;
const lines = String(content || '').replace(/\r\n?/g, '\n').split('\n');
for (const line of lines) {
if (/^\s*-\s+/.test(line)) {
if (current) blocks.push(current.join('\n'));
current = [line];
} else if (current && /^\s{2,}\S/.test(line)) {
current.push(line);
} else if (current) {
blocks.push(current.join('\n'));
current = null;
}
}
if (current) blocks.push(current.join('\n'));
return blocks;
}
function hasDuplicateBullet(content, bulletText) {
const target = normalizeBulletForDuplicate(bulletText);
return collectBulletBlocks(content).some(block => normalizeBulletForDuplicate(block) === target);
}
function appendBulletBeforeEndMarker(content, headline, bulletText) {
const endMarker = makeClipEndMarker(headline);
const endIndex = String(content || '').indexOf(endMarker);
if (endIndex < 0) {
throw new Error(tr('STMemoryBooks_Clip_ErrorMissingEndMarker', 'Expected clip end marker was not found.'));
}
const before = String(content || '').slice(0, endIndex).replace(/[ \t]*$/g, '');
const after = String(content || '').slice(endIndex);
const separator = before.endsWith('\n\n') ? '' : before.endsWith('\n') ? '\n' : '\n\n';
return `${before}${separator}${formatClipBullet(bulletText)}\n\n${after}`;
}
function getWrapperMarkerHeadlines(content, kind) {
const pattern = kind === 'end'
? /^=== END (.+) ===$/gm
: /^=== (?!END )(.+) ===$/gm;
return Array.from(String(content || '').matchAll(pattern), match => match[1]);
}
function analyzeClipWrapper(content, headline) {
const text = String(content || '');
const startMarker = makeClipStartMarker(headline);
const endMarker = makeClipEndMarker(headline);
const startIndex = text.indexOf(startMarker);
const endIndex = text.indexOf(endMarker);
const startHeadlines = getWrapperMarkerHeadlines(text, 'start');
const endHeadlines = getWrapperMarkerHeadlines(text, 'end');
if (startIndex >= 0 && endIndex > startIndex) {
return { type: 'valid' };
}
if (startHeadlines.length > 1 || endHeadlines.length > 1) {
return { type: 'multiple' };
}
if (startHeadlines.length === 1 && endHeadlines.length === 1) {
return { type: 'mismatch', wrapperHeadline: startHeadlines[0], wrapperEndHeadline: endHeadlines[0] };
}
return { type: 'none' };
}
function replaceSingleWrapperHeadline(content, fromHeadline, toHeadline, fromEndHeadline = fromHeadline) {
return String(content || '')
.replace(makeClipStartMarker(fromHeadline), makeClipStartMarker(toHeadline))
.replace(makeClipEndMarker(fromEndHeadline), makeClipEndMarker(toHeadline));
}
function stripWrapperMarkerLines(content) {
return String(content || '')
.replace(/^=== (?!END ).+ ===\s*$/gm, '')
.replace(/^=== END .+ ===\s*$/gm, '')
.replace(/\n{3,}/g, '\n\n')
.trim();
}
function convertExistingContentToWrappedContent(content, headline, bulletText) {
const existing = String(content || '').trim();
if (!existing) return createClipEntryContent(headline, bulletText);
return `${makeClipStartMarker(headline)}\n\n${existing}\n\n${formatClipBullet(bulletText)}\n\n${makeClipEndMarker(headline)}`;
}
function normalizeSelectedText(text) {
return String(text || '')
.replace(/\r\n?/g, '\n')
.replace(/[ \t\f\v]+/g, ' ')
.replace(/\n{3,}/g, '\n\n')
.trim();
}
function nodeIsInside(node, container) {
if (!node || !container) return false;
const element = node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement;
return !!element && container.contains(element);
}
function getElementForNode(node) {
if (!node) return null;
return node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement;
}
function getSelectionChatMessage(selection) {
const anchorMessage = getElementForNode(selection?.anchorNode)?.closest?.('#chat .mes[mesid]');
const focusMessage = getElementForNode(selection?.focusNode)?.closest?.('#chat .mes[mesid]');
return anchorMessage && anchorMessage === focusMessage ? anchorMessage : anchorMessage || focusMessage || null;
}
function getSelectionDirection(selection) {
const messageElement = getSelectionChatMessage(selection);
const element = getElementForNode(selection?.focusNode) || messageElement;
const direction = element ? getComputedStyle(element).direction : 'ltr';
return direction === 'rtl' ? 'rtl' : 'ltr';
}
function getSelectionAttachRect(range, direction = 'ltr') {
const rects = Array.from(range.getClientRects())
.filter(rect => rect.width > 0 && rect.height > 0);
if (rects.length > 0) {
return direction === 'rtl' ? rects[0] : rects[rects.length - 1];
}
return range.getBoundingClientRect();
}
function isFloatingClipEnabled() {
return extension_settings?.STMemoryBooks?.moduleSettings?.showFloatingClipButton !== false;
}
function getSelectedChatText(messageElement = null, options = {}) {
if (options.requireFloatingEnabled && !isFloatingClipEnabled()) {
throw new Error(tr('STMemoryBooks_Clip_FloatingDisabled', 'Floating Clip button is disabled.'));
}
const selection = window.getSelection?.();
if (!selection || selection.rangeCount === 0) {
throw new Error(tr('STMemoryBooks_Clip_NoHighlightedText', 'Highlight text in the chat first, then click Clip.'));
}
const rawText = selection?.toString?.() || '';
const selectedText = normalizeSelectedText(rawText);
if (!selectedText) {
throw new Error(tr('STMemoryBooks_Clip_NoHighlightedText', 'Highlight text in the chat first, then click Clip.'));
}
const chatElement = document.querySelector('#chat');
if (!chatElement || !nodeIsInside(selection.anchorNode, chatElement) || !nodeIsInside(selection.focusNode, chatElement)) {
throw new Error(tr('STMemoryBooks_Clip_SelectionOutsideChat', 'Selected text must be inside the chat.'));
}
if (messageElement && (!nodeIsInside(selection.anchorNode, messageElement) || !nodeIsInside(selection.focusNode, messageElement))) {
throw new Error(tr('STMemoryBooks_Clip_SelectionOutsideMessage', 'Select text inside the message you are clipping.'));
}
return selectedText;
}
function getFloatingSelectionState() {
if (!isFloatingClipEnabled()) return null;
const selection = document.getSelection?.();
if (!selection || selection.rangeCount === 0) return null;
const selectedText = normalizeSelectedText(selection.toString?.() || '');
if (!selectedText) return null;
const chatElement = document.querySelector('#chat');
if (!chatElement || !nodeIsInside(selection.anchorNode, chatElement) || !nodeIsInside(selection.focusNode, chatElement)) {
return null;
}
const messageElement = getSelectionChatMessage(selection);
if (!messageElement) return null;
const range = selection.getRangeAt(0);
const direction = getSelectionDirection(selection);
const rect = getSelectionAttachRect(range, direction);
if (!rect || (rect.width === 0 && rect.height === 0)) return null;
return { selectedText, rect, direction, messageElement };
}
function getClipEntries(lorebookData) {
return Object.values(lorebookData?.entries || {})
.filter(entry => isClipEntryTitle(entry?.comment || ''))
.sort((a, b) => String(a.comment || '').localeCompare(String(b.comment || '')));
}
function getClipEntryByFinalTitle(lorebookData, title) {
const exact = getEntryByTitle(lorebookData, title);
if (exact) return exact;
const normalizedTitle = String(title || '').trimEnd();
return Object.values(lorebookData?.entries || {})
.find(entry => isClipEntryTitle(entry?.comment || '') && String(entry.comment || '').trimEnd() === normalizedTitle) || null;
}
function parseKeywords(text) {
return String(text || '')
.split(',')
.map(keyword => keyword.trim())
.filter(Boolean);
}
function shouldRefreshEditor() {
return extension_settings?.STMemoryBooks?.moduleSettings?.refreshEditor !== false;
}
async function saveLorebook(lorebookName, lorebookData) {
await saveWorldInfo(lorebookName, lorebookData, true);
if (shouldRefreshEditor()) {
await Promise.resolve(reloadEditor(lorebookName));
}
}
async function confirmDuplicateBullet() {
const popup = new Popup(
DOMPurify.sanitize(`<h3>${escapeHtml(tr('STMemoryBooks_Clip_DuplicateTitle', 'Duplicate Clip'))}</h3><p>${escapeHtml(tr('STMemoryBooks_Clip_DuplicateMessage', 'This exact clip already exists in the selected entry.'))}</p>`),
POPUP_TYPE.CONFIRM,
'',
{
okButton: tr('STMemoryBooks_Clip_AddAnyway', 'Add Anyway'),
cancelButton: tr('STMemoryBooks_Cancel', 'Cancel'),
},
);
return await popup.show() === POPUP_RESULT.AFFIRMATIVE;
}
async function confirmConvertExistingContent() {
const popup = new Popup(
DOMPurify.sanitize(`<h3>${escapeHtml(tr('STMemoryBooks_Clip_ConvertTitle', 'Convert Clip Entry'))}</h3><p>${escapeHtml(tr('STMemoryBooks_Clip_ConvertMessage', 'This entry is marked as an STMB Clip entry but does not have the expected wrapper. Convert it to one wrapped section and preserve its current content?'))}</p>`),
POPUP_TYPE.CONFIRM,
'',
{
okButton: tr('STMemoryBooks_Clip_ConvertButton', 'Convert'),
cancelButton: tr('STMemoryBooks_Cancel', 'Cancel'),
},
);
return await popup.show() === POPUP_RESULT.AFFIRMATIVE;
}
async function confirmMultipleWrapperConversion() {
const popup = new Popup(
DOMPurify.sanitize(`<h3>${escapeHtml(tr('STMemoryBooks_Clip_MultipleWrappersTitle', 'Multiple Clip Sections'))}</h3><p>${escapeHtml(tr('STMemoryBooks_Clip_MultipleWrappersMessage', 'STMB Clip entries support one section per entry. Convert this entry to one section using the title-derived headline?'))}</p>`),
POPUP_TYPE.CONFIRM,
'',
{
okButton: tr('STMemoryBooks_Clip_ConvertOneSection', 'Convert to One Section'),
cancelButton: tr('STMemoryBooks_Cancel', 'Cancel'),
},
);
return await popup.show() === POPUP_RESULT.AFFIRMATIVE;
}
function buildUpdatedExistingContent(entry, bulletText, editedHeadline) {
const headline = validateClipHeadline(editedHeadline ?? getClipHeadlineFromTitle(entry.comment || ''));
const analysis = analyzeClipWrapper(entry.content || '', headline);
if (analysis.type === 'valid') return appendBulletBeforeEndMarker(entry.content || '', headline, bulletText);
if (analysis.type === 'multiple') return convertExistingContentToWrappedContent(stripWrapperMarkerLines(entry.content || ''), headline, bulletText);
if (analysis.type === 'mismatch') {
const repairedContent = replaceSingleWrapperHeadline(entry.content || '', analysis.wrapperHeadline, headline, analysis.wrapperEndHeadline);
return appendBulletBeforeEndMarker(repairedContent, headline, bulletText);
}
return convertExistingContentToWrappedContent(entry.content || '', headline, bulletText);
}
async function buildExistingContentForSave(entry, bulletText, headline) {
const analysis = analyzeClipWrapper(entry.content || '', headline);
if (analysis.type === 'valid') {
return appendBulletBeforeEndMarker(entry.content || '', headline, bulletText);
}
if (analysis.type === 'none') {
const hasExisting = !!String(entry.content || '').trim();
if (hasExisting && !await confirmConvertExistingContent()) return null;
return convertExistingContentToWrappedContent(entry.content || '', headline, bulletText);
}
if (analysis.type === 'multiple') {
if (!await confirmMultipleWrapperConversion()) return null;
return convertExistingContentToWrappedContent(stripWrapperMarkerLines(entry.content || ''), headline, bulletText);
}
const repairedContent = replaceSingleWrapperHeadline(entry.content || '', analysis.wrapperHeadline, headline, analysis.wrapperEndHeadline);
return appendBulletBeforeEndMarker(repairedContent, headline, bulletText);
}
function buildClipModalHtml(selectedText, clipEntries) {
const entryOptions = clipEntries.map((entry) => {
const title = String(entry.comment || '');
return `<option value="${escapeHtml(title)}">${escapeHtml(getClipHeadlineFromTitle(title))}</option>`;
}).join('');
return DOMPurify.sanitize(`
<h3>${escapeHtml(tr('STMemoryBooks_Clip_ModalTitle', 'Clip to Memory Book'))}</h3>
<div class="stmb-clip-modal">
<label class="world_entry_form_control">
<h4>${escapeHtml(tr('STMemoryBooks_Clip_SelectedText', 'Selected text'))}</h4>
<textarea id="stmb-clip-text" class="text_pole stmb-clip-textarea">${escapeHtml(selectedText)}</textarea>
</label>
<label class="world_entry_form_control">
<h4>${escapeHtml(tr('STMemoryBooks_Clip_ExistingEntry', 'Existing clip entry'))}</h4>
<select id="stmb-clip-entry-select" class="text_pole">
${entryOptions}
<option value="${CREATE_NEW_VALUE}" ${clipEntries.length ? '' : 'selected'}>${escapeHtml(tr('STMemoryBooks_Clip_CreateNewEntry', 'Create new clip entry'))}</option>
</select>
</label>
<label class="world_entry_form_control">
<h4>${escapeHtml(tr('STMemoryBooks_Clip_Headline', 'Entry title / section headline'))}</h4>
<input id="stmb-clip-headline" class="text_pole" type="text" />
</label>
<div id="stmb-clip-new-entry-fields" class="world_entry_form_control">
<div class="stmb-clip-activation">
<label><input type="radio" name="stmb-clip-activation" value="constant" checked /> ${escapeHtml(tr('STMemoryBooks_Clip_AlwaysInclude', 'Always include this entry'))}</label>
<label><input type="radio" name="stmb-clip-activation" value="keyword" /> ${escapeHtml(tr('STMemoryBooks_Clip_ActivateByKeywords', 'Activate by keywords'))}</label>
</div>
<label id="stmb-clip-keywords-row">
<h4>${escapeHtml(tr('STMemoryBooks_Clip_Keywords', 'Keywords'))}</h4>
<input id="stmb-clip-keywords" class="text_pole" type="text" />
</label>
</div>
<div class="world_entry_form_control">
<div class="stmb-clip-label-row">
<h4>${escapeHtml(tr('STMemoryBooks_Clip_CurrentContent', 'Current entry content'))}</h4>
<button id="stmb-clip-compact" type="button" class="menu_button stmb-clip-compact-btn">${escapeHtml(tr('STMemoryBooks_Compaction_Title', 'Compaction'))}</button>
</div>
<textarea id="stmb-clip-current-content" class="text_pole stmb-clip-preview" readonly></textarea>
</div>
<label class="world_entry_form_control">
<h4>${escapeHtml(tr('STMemoryBooks_Clip_UpdatedPreview', 'Updated entry preview'))}</h4>
<textarea id="stmb-clip-updated-preview" class="text_pole stmb-clip-preview" readonly></textarea>
</label>
<div id="stmb-clip-token-warning" class="info_block stmb-clip-warning" hidden>${escapeHtml(tr('STMemoryBooks_Clip_LongWarning', 'This clip entry is getting long. Long constant entries can waste context or crowd out more relevant memory. Review, edit, or compact it.'))}</div>
</div>
`);
}
function attachClipModalHandlers(popup, lorebookName, lorebookData, clipEntries) {
const dlg = popup.dlg;
if (!dlg) return;
const entrySelect = dlg.querySelector('#stmb-clip-entry-select');
const clipText = dlg.querySelector('#stmb-clip-text');
const headlineInput = dlg.querySelector('#stmb-clip-headline');
const keywordsRow = dlg.querySelector('#stmb-clip-keywords-row');
const currentContent = dlg.querySelector('#stmb-clip-current-content');
const updatedPreview = dlg.querySelector('#stmb-clip-updated-preview');
const tokenWarning = dlg.querySelector('#stmb-clip-token-warning');
const compactButton = dlg.querySelector('#stmb-clip-compact');
const newEntryFields = dlg.querySelector('#stmb-clip-new-entry-fields');
const getMode = () => entrySelect?.value === CREATE_NEW_VALUE ? 'new' : 'existing';
const getSelectedEntry = () => getEntryByTitle(lorebookData, entrySelect?.value || '');
const getBulletText = () => clipText?.value || '';
const syncHeadlineFromSelection = () => {
if (!headlineInput) return;
const entry = getSelectedEntry();
headlineInput.value = entry ? getClipHeadlineFromTitle(entry.comment || '') : '';
};
const syncActivation = () => {
const activation = dlg.querySelector('input[name="stmb-clip-activation"]:checked')?.value || 'constant';
if (keywordsRow) keywordsRow.style.display = activation === 'keyword' ? 'block' : 'none';
};
const refreshPreview = () => {
const mode = getMode();
if (newEntryFields) newEntryFields.style.display = mode === 'new' ? 'block' : 'none';
if (compactButton) compactButton.disabled = mode !== 'existing';
let preview = '';
let current = '';
try {
if (mode === 'existing') {
const entry = getSelectedEntry();
current = entry?.content || '';
preview = entry ? buildUpdatedExistingContent(entry, getBulletText(), headlineInput?.value || '') : '';
} else {
const headline = validateClipHeadline(headlineInput?.value || '');
preview = createClipEntryContent(headline, getBulletText());
}
} catch (error) {
preview = error.message || '';
}
if (currentContent) currentContent.value = current;
if (updatedPreview) updatedPreview.value = preview;
if (tokenWarning) tokenWarning.hidden = estimateTokens(preview) <= TOKEN_WARNING_THRESHOLD;
};
entrySelect?.addEventListener('change', () => {
syncHeadlineFromSelection();
refreshPreview();
});
clipText?.addEventListener('input', refreshPreview);
headlineInput?.addEventListener('input', refreshPreview);
dlg.querySelectorAll('input[name="stmb-clip-activation"]').forEach(input => {
input.addEventListener('change', () => {
syncActivation();
refreshPreview();
});
});
compactButton?.addEventListener('click', async () => {
const entry = getSelectedEntry();
if (!entry) return;
const replaced = await showCompactReviewPopup(lorebookName, lorebookData, entry);
if (replaced) refreshPreview();
});
syncActivation();
syncHeadlineFromSelection();
refreshPreview();
}
async function showLongEntryWarning(lorebookName, lorebookData, entry, content) {
if (estimateTokens(content) <= TOKEN_WARNING_THRESHOLD) return true;
const popup = new Popup(
DOMPurify.sanitize(`<h3>${escapeHtml(tr('STMemoryBooks_Clip_LongEntryTitle', 'Long Clip Entry'))}</h3><p>${escapeHtml(tr('STMemoryBooks_Clip_LongWarning', 'This clip entry is getting long. Long constant entries can waste context or crowd out more relevant memory. Review, edit, or compact it.'))}</p>`),
POPUP_TYPE.TEXT,
'',
{
okButton: false,
cancelButton: tr('STMemoryBooks_Cancel', 'Cancel'),
customButtons: [
{ text: tr('STMemoryBooks_Clip_ReviewEntry', 'Review Entry'), result: POPUP_RESULT.CUSTOM1, appendAtEnd: true },
{ text: tr('STMemoryBooks_Compaction_Button', 'Compact Entry'), result: POPUP_RESULT.CUSTOM2, appendAtEnd: true },
{ text: tr('STMemoryBooks_Clip_SaveAnyway', 'Save Anyway'), result: POPUP_RESULT.CUSTOM3, appendAtEnd: true },
],
},
);
markStmbPopup(popup);
const result = await popup.show();
if (result === POPUP_RESULT.CUSTOM3) return true;
if (result === POPUP_RESULT.CUSTOM2 && entry) {
await showCompactReviewPopup(lorebookName, lorebookData, entry, { pendingContent: content });
} else if (result === POPUP_RESULT.CUSTOM1) {
await new Popup(
DOMPurify.sanitize(`<h3>${escapeHtml(tr('STMemoryBooks_Clip_ReviewEntry', 'Review Entry'))}</h3><textarea class="text_pole stmb-clip-preview" readonly>${escapeHtml(content)}</textarea>`),
POPUP_TYPE.TEXT,
'',
{ wide: true, large: true, allowVerticalScrolling: true, okButton: tr('STMemoryBooks_Close', 'Close'), cancelButton: false },
).show();
}
return false;
}
async function saveExistingClip(lorebookName, lorebookData, title, bulletText, editedHeadline) {
const entry = getEntryByTitle(lorebookData, title);
if (!entry) throw new Error(tr('STMemoryBooks_Clip_ErrorEntryNotFound', 'Selected clip entry was not found.'));
const headline = validateClipHeadline(editedHeadline);
const newTitle = makeClipEntryTitle(headline);
const duplicate = getClipEntryByFinalTitle(lorebookData, newTitle);
if (duplicate && duplicate !== entry) {
throw new Error(tr('STMemoryBooks_Clip_ErrorDuplicateTitle', 'A clip entry with this title already exists.'));
}
const updatedContent = await buildExistingContentForSave(entry, bulletText, headline);
if (updatedContent == null) return false;
if (hasDuplicateBullet(entry.content || '', formatClipBullet(bulletText)) && !await confirmDuplicateBullet()) {
return false;
}
if (!await showLongEntryWarning(lorebookName, lorebookData, entry, updatedContent)) {
return false;
}
entry.comment = newTitle;
entry.content = updatedContent;
await saveLorebook(lorebookName, lorebookData);
// STMBC-HOOK(clipper): after the upstream [STMB Clip] entry is written, generate +
// write the paired context entry (fork; plan §4.2). No-op unless Clipper+ is enabled;
// self-contained (never throws), so the clip above is unaffected either way.
await maybeGeneratePairedContextEntry({ lorebookName, lorebookData, quote: bulletText, headline, quoteTitle: title });
return true;
}
async function saveNewClip(lorebookName, lorebookData, dlg) {
const headline = validateClipHeadline(dlg.querySelector('#stmb-clip-headline')?.value || '');
const title = makeClipEntryTitle(headline);
if (getClipEntryByFinalTitle(lorebookData, title)) {
throw new Error(tr('STMemoryBooks_Clip_ErrorDuplicateTitle', 'A clip entry with this title already exists.'));
}
const bulletText = dlg.querySelector('#stmb-clip-text')?.value || '';
const content = createClipEntryContent(headline, bulletText);
const activation = dlg.querySelector('input[name="stmb-clip-activation"]:checked')?.value || 'constant';
const keywords = parseKeywords(dlg.querySelector('#stmb-clip-keywords')?.value || '');
if (activation === 'keyword' && keywords.length === 0) {
throw new Error(tr('STMemoryBooks_Clip_ErrorKeywordsRequired', 'Keyword-activated clip entries require at least one keyword.'));
}
if (!await showLongEntryWarning(lorebookName, lorebookData, null, content)) {
return false;
}
const newEntry = createWorldInfoEntry(lorebookName, lorebookData);
if (!newEntry) {
throw new Error(tr('STMemoryBooks_Clip_ErrorCreateEntryFailed', 'Failed to create clip entry.'));
}
newEntry.comment = title;
newEntry.content = content;
newEntry.key = activation === 'keyword' ? keywords : [];
newEntry.keysecondary = Array.isArray(newEntry.keysecondary) ? newEntry.keysecondary : [];
newEntry.constant = activation === 'constant';
newEntry.vectorized = activation === 'keyword';
newEntry.selective = activation === 'keyword';
newEntry.disable = false;
newEntry.position = typeof newEntry.position === 'number' ? newEntry.position : 0;
newEntry.order = typeof newEntry.order === 'number' ? newEntry.order : 100;
await saveLorebook(lorebookName, lorebookData);
// STMBC-HOOK(clipper): after the upstream [STMB Clip] entry is written, generate +
// write the paired context entry (fork; plan §4.2). No-op unless Clipper+ is enabled;
// self-contained (never throws), so the clip above is unaffected either way.
await maybeGeneratePairedContextEntry({ lorebookName, lorebookData, quote: bulletText, headline, quoteTitle: title });
return true;
}
export async function openClipModalFromSelection({ selectedText, source = 'message' } = {}) {
if (source === 'floating') {
try {
getSelectedChatText(null, { requireFloatingEnabled: true });
} catch (error) {
hideFloatingClipButton();
if (error?.message !== tr('STMemoryBooks_Clip_FloatingDisabled', 'Floating Clip button is disabled.')) {
toastr.warning(error.message, 'STMemoryBooks');
}
return;
}
}
const normalizedSelectedText = normalizeSelectedText(selectedText || '');
if (!normalizedSelectedText) {
toastr.warning(tr('STMemoryBooks_Clip_NoHighlightedText', 'Highlight text in the chat first, then click Clip.'), 'STMemoryBooks');
return;
}
hideFloatingClipButton();
const validation = await validateLorebookRequirement({ createContext: 'clip' });
if (!validation?.valid || !validation?.data || !validation?.name) {
if (!validation?.handled) {
toastr.error(validation?.error || tr('STMemoryBooks_Error_NoValidLorebookAvailable', 'No valid lorebook available.'), 'STMemoryBooks');
}
return;
}
const { name: lorebookName, data: lorebookData } = validation;
const clipEntries = getClipEntries(lorebookData);
const popup = new Popup(buildClipModalHtml(normalizedSelectedText, clipEntries), POPUP_TYPE.TEXT, '', {
wide: true,
large: true,
allowVerticalScrolling: true,
okButton: tr('STMemoryBooks_Clip_SaveClip', 'Save Clip'),
cancelButton: tr('STMemoryBooks_Cancel', 'Cancel'),
});
const showPromise = popup.show();
attachClipModalHandlers(popup, lorebookName, lorebookData, clipEntries);
const result = await showPromise;
if (result !== POPUP_RESULT.AFFIRMATIVE) return;
try {
const dlg = popup.dlg;
const bulletText = dlg.querySelector('#stmb-clip-text')?.value || '';
formatClipBullet(bulletText); // Validates non-empty text, throws if invalid
const selectedTitle = dlg.querySelector('#stmb-clip-entry-select')?.value || CREATE_NEW_VALUE;
const editedHeadline = dlg.querySelector('#stmb-clip-headline')?.value || '';
const saved = selectedTitle === CREATE_NEW_VALUE
? await saveNewClip(lorebookName, lorebookData, dlg)
: await saveExistingClip(lorebookName, lorebookData, selectedTitle, bulletText, editedHeadline);
if (saved) {
toastr.success(tr('STMemoryBooks_Clip_SaveSuccess', 'Clip saved to Memory Book.'), 'STMemoryBooks');
}
} catch (error) {
console.error(`${MODULE_NAME}: Failed to save clip:`, error);
toastr.error(error?.message || tr('STMemoryBooks_Clip_SaveFailed', 'Failed to save clip.'), 'STMemoryBooks');
}
}
export async function handleClipButtonClick(messageElement) {
try {
const selectedText = getSelectedChatText(messageElement);
await openClipModalFromSelection({ selectedText, source: 'message' });
} catch (error) {
toastr.warning(error.message, 'STMemoryBooks');
}
}
export function hideFloatingClipButton() {
if (floatingClipUpdateTimer) {
clearTimeout(floatingClipUpdateTimer);
floatingClipUpdateTimer = null;
}
floatingClipButton?.remove();
floatingClipButton = null;
}
function scheduleFloatingClipUpdate() {
if (!isFloatingClipEnabled()) {
hideFloatingClipButton();
return;
}
if (floatingClipUpdateTimer) clearTimeout(floatingClipUpdateTimer);
floatingClipUpdateTimer = setTimeout(updateFloatingClipButton, 60);
}
function createFloatingClipButton() {
const button = document.createElement('div');
button.classList.add('stmb_floating_clip_button', 'fa-solid', 'fa-scissors', 'interactable');
button.title = tr('STMemoryBooks_Clip_ButtonTitle', 'Clip highlighted text to Memory Book');
button.setAttribute('tabindex', '0');
button.setAttribute('data-i18n', '[title]STMemoryBooks_Clip_ButtonTitle');
button.addEventListener('mousedown', (event) => {
event.preventDefault();
event.stopPropagation();
});
button.addEventListener('click', async (event) => {
event.preventDefault();
event.stopPropagation();
const state = getFloatingSelectionState();
if (!state) {
hideFloatingClipButton();
return;
}
await openClipModalFromSelection({ selectedText: state.selectedText, source: 'floating' });
});
document.body.appendChild(button);
return button;
}
function updateFloatingClipButton() {
floatingClipUpdateTimer = null;
const state = getFloatingSelectionState();
if (!state) {
hideFloatingClipButton();
return;
}
if (!floatingClipButton) {
floatingClipButton = createFloatingClipButton();
}
const buttonWidth = floatingClipButton.offsetWidth || 32;
const buttonHeight = floatingClipButton.offsetHeight || 32;
const edgeLeft = state.direction === 'rtl'
? state.rect.left - buttonWidth - FLOATING_CLIP_X_OFFSET
: state.rect.right + FLOATING_CLIP_X_OFFSET;
const edgeTop = state.rect.top + (state.rect.height / 2) - (buttonHeight / 2) + FLOATING_CLIP_Y_OFFSET;
const left = Math.min(
window.innerWidth - buttonWidth - FLOATING_CLIP_VIEWPORT_PADDING,
Math.max(FLOATING_CLIP_VIEWPORT_PADDING, edgeLeft),
);
const top = Math.min(
window.innerHeight - buttonHeight - FLOATING_CLIP_VIEWPORT_PADDING,
Math.max(FLOATING_CLIP_VIEWPORT_PADDING, edgeTop),
);
floatingClipButton.style.top = `${Math.round(top)}px`;
floatingClipButton.style.left = `${Math.round(left)}px`;
floatingClipButton.style.display = 'flex';
}
function handleFloatingClipDocumentMouseDown(event) {
if (floatingClipButton?.contains(event.target)) return;
hideFloatingClipButton();
}
function bindFloatingClipListeners() {
if (floatingClipListenersBound) return;
document.addEventListener('selectionchange', scheduleFloatingClipUpdate);
document.addEventListener('mouseup', scheduleFloatingClipUpdate);
document.addEventListener('keyup', scheduleFloatingClipUpdate);
document.addEventListener('mousedown', handleFloatingClipDocumentMouseDown, true);
window.addEventListener('scroll', hideFloatingClipButton, true);
floatingClipListenersBound = true;
}
function unbindFloatingClipListeners() {
if (!floatingClipListenersBound) return;
document.removeEventListener('selectionchange', scheduleFloatingClipUpdate);
document.removeEventListener('mouseup', scheduleFloatingClipUpdate);
document.removeEventListener('keyup', scheduleFloatingClipUpdate);
document.removeEventListener('mousedown', handleFloatingClipDocumentMouseDown, true);
window.removeEventListener('scroll', hideFloatingClipButton, true);
floatingClipListenersBound = false;
}
export function refreshFloatingClipButtonSetting() {
if (isFloatingClipEnabled()) {
bindFloatingClipListeners();
scheduleFloatingClipUpdate();
} else {
unbindFloatingClipListeners();
hideFloatingClipButton();
}
}
export function initializeFloatingClipButton() {
refreshFloatingClipButtonSetting();
}
function getModuleSettings() {
extension_settings.STMemoryBooks = extension_settings.STMemoryBooks || {};
extension_settings.STMemoryBooks.moduleSettings = extension_settings.STMemoryBooks.moduleSettings || {};
return extension_settings.STMemoryBooks.moduleSettings;
}
function getDefaultCompactionPromptTemplate() {
return tr('STMemoryBooks_Compaction_DefaultPrompt', DEFAULT_COMPACTION_PROMPT_TEMPLATE);
}
function hasCustomPromptTemplate(saved, englishDefault) {
if (typeof saved !== 'string' || !saved.trim()) return false;
const normalizedSaved = saved.replace(/\r\n?/g, '\n');
const normalizedDefault = String(englishDefault || '').replace(/\r\n?/g, '\n');
return normalizedSaved !== normalizedDefault;
}
function getCompactionPromptTemplate() {
const saved = getModuleSettings().compactionPromptTemplate;
return hasCustomPromptTemplate(saved, DEFAULT_COMPACTION_PROMPT_TEMPLATE)
? saved
: getDefaultCompactionPromptTemplate();
}
function setCompactionPromptTemplate(template) {
getModuleSettings().compactionPromptTemplate = String(template || '');
saveSettingsDebounced();
}
function getCompactionProfileIndex() {
const settings = extension_settings?.STMemoryBooks || {};
const profiles = Array.isArray(settings.profiles) ? settings.profiles : [];
if (profiles.length === 0) return 0;
const rawIndex = Number.parseInt(settings.moduleSettings?.compactionProfileIndex, 10);
if (Number.isFinite(rawIndex) && rawIndex >= 0 && rawIndex < profiles.length) {
return rawIndex;
}
const defaultIndex = Number.parseInt(settings.defaultProfile, 10);
return Number.isFinite(defaultIndex) && defaultIndex >= 0 && defaultIndex < profiles.length
? defaultIndex
: 0;
}
function setCompactionProfileIndex(profileIndex) {
const settings = extension_settings?.STMemoryBooks || {};
const profiles = Array.isArray(settings.profiles) ? settings.profiles : [];
const parsed = Number.parseInt(profileIndex, 10);
const fallback = getCompactionProfileIndex();
getModuleSettings().compactionProfileIndex = Number.isFinite(parsed) && parsed >= 0 && parsed < profiles.length
? parsed
: fallback;
saveSettingsDebounced();
}
function buildCompactionProfileOptions(selectedIndex = getCompactionProfileIndex()) {
const settings = extension_settings?.STMemoryBooks || {};
const profiles = Array.isArray(settings.profiles) ? settings.profiles : [];
return profiles.map((profile, index) => {
const displayName = profile?.isBuiltinCurrentST
? tr('STMemoryBooks_Profile_CurrentST', 'Current SillyTavern Settings')
: profile?.name || tr('STMemoryBooks_Profile', 'Profile');
return `<option value="${escapeHtml(String(index))}"${index === selectedIndex ? ' selected' : ''}>${escapeHtml(displayName)}</option>`;
}).join('');
}
function buildCompactionProfileControl(selectId, options = {}) {
const label = options.label || tr('STMemoryBooks_Compaction_Profile', 'Compaction Profile');
return `
<div class="world_entry_form_control">
<h4>${escapeHtml(label)}</h4>
<select id="${escapeHtml(selectId)}" class="text_pole stmb-compaction-profile-select">
${buildCompactionProfileOptions()}
</select>
</div>
`;
}
function initializeCompactionProfileSelect(popup, selectId, options = {}) {
const select = popup.dlg?.querySelector(`#${selectId}`);
if (!select || !window.jQuery || typeof window.jQuery.fn.select2 !== 'function') return;
const $select = window.jQuery(select);
if ($select.hasClass('select2-hidden-accessible')) {
$select.select2('destroy');
}
$select.select2({
width: '100%',
placeholder: options.placeholder || tr('STMemoryBooks_Compaction_SelectProfile', 'Select a Compaction profile...'),
allowClear: false,
dropdownParent: window.jQuery(popup.dlg),
});
}
function addCompactionSelectChangeListener(select, handler) {
if (!select || typeof handler !== 'function') return;
const $select = window.jQuery && typeof window.jQuery === 'function'
? window.jQuery(select)
: null;
if ($select?.length && $select.hasClass('select2-hidden-accessible')) {
$select.on('change.stmbCompaction', handler);
return;
}