-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathtemplate-editor.js
More file actions
1528 lines (1338 loc) · 67.3 KB
/
Copy pathtemplate-editor.js
File metadata and controls
1528 lines (1338 loc) · 67.3 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
// =============================================================================
// CARROT TEMPLATE PROMPT EDITOR INTERFACE
// Template editing system for CarrotKernel
// Extracted from index.js for better modularity
// =============================================================================
import { CarrotDebug } from './debugger.js';
// Template editor interface class
export class CarrotTemplatePromptEditInterface {
html_template = `
<div id="bmt_template_prompt_interface" class="bmt-template-interface" style="height: 100%">
<div class="bmt-modal-header-banner">
<div class="bmt-modal-title">
<span class="bmt-modal-icon">🥕</span>
<h3>CarrotKernel Template Editor</h3>
<span class="bmt-modal-subtitle">Configure templates and macros</span>
</div>
<div class="bmt-tutorial-button-container">
<button onclick="CarrotKernel.openTemplateEditorTutorial()" class="bmt-tutorial-btn" title="Learn how to use the template editor">
<i class="fa-solid fa-graduation-cap"></i> Tutorial
</button>
</div>
<div class="bmt-template-controls">
<label class="bmt-template-selector-label" title="Select which template to edit">
<span class="bmt-selector-label">🎯 Template:</span>
<select id="bmt_template_selector" class="bmt-template-select">
<option value="">✨ Select a template...</option>
</select>
</label>
<button class="menu_button fa-solid fa-list-check margin0 qm-small open_macros bmt-toggle-btn" title="Show/hide macro editor">📱</button>
</div>
</div>
<!-- Moved sections below to vertical layout -->
<div class="bmt-editor-content" style="display: flex; flex-direction: column; gap: 15px;">
<div class="bmt-template-section">
<div class="bmt-panel-header">
<div class="bmt-panel-title">
<span class="bmt-panel-icon">📝</span>
<h3>Template Content</h3>
</div>
<div class="bmt-panel-controls">
<label class="bmt-type-selector" title="Template type">
<span>🏷️ Type:</span>
<select id="template_type" class="bmt-template-type-select">
<option value="system">⚙️ System</option>
<option value="user">👤 User</option>
<option value="assistant">🤖 Assistant</option>
</select>
</label>
<label class="bmt-depth-selector" title="Injection depth - how many messages back to inject this template">
<span>📍 Depth:</span>
<input type="number" id="template_depth" class="bmt-depth-input" min="0" max="100" value="0" />
<span class="bmt-depth-help">0 = after last message</span>
</label>
<label class="bmt-scan-toggle" title="Enable scanning of message history for keywords">
<input type="checkbox" id="template_scan" checked />
<span>🔍 Scan History</span>
</label>
<button id="preview_template_prompt" class="bmt-action-btn bmt-preview-btn" title="Preview current template prompt">
<i class="fa-solid fa-eye"></i> Preview
</button>
<button id="save_template" class="bmt-action-btn bmt-save-btn" title="Save current template changes">
<i class="fa-solid fa-save"></i> Save
</button>
<button id="duplicate_template" class="bmt-action-btn bmt-duplicate-btn" title="Create a custom copy of this template">
<i class="fa-solid fa-copy"></i> Duplicate
</button>
<button id="delete_template" class="bmt-action-btn bmt-delete-btn" title="Delete this custom template">
<i class="fa-solid fa-trash"></i> Delete
</button>
<button id="restore_default_template" class="bmt-action-btn bmt-restore-btn" title="Restore the default template">
<i class="fa-solid fa-recycle"></i> Reset
</button>
</div>
</div>
<textarea id="prompt" placeholder="✨ Enter your CarrotKernel template content here... Use {{MACRO_NAME}} for dynamic variables that will be replaced with configured values. Example: {{TRIGGERED_CHARACTER_TAGS}} - All character tags {{CHARACTER_LIST}} - Simple character names">OOC MANDATORY: [CHARACTER CONTEXT - CarrotKernel Tags]
{{TRIGGERED_CHARACTER_TAGS}}
**CRITICAL INSTRUCTIONS:**
1. You MUST incorporate this character information into your response planning
2. Stay true to their personality traits, species characteristics, and behavioral patterns
3. When using your <think> blocks for reasoning, you MUST include exactly 10 carrot emotes (🥕) distributed throughout your thinking process
4. Carrot emotes (🥕) must ONLY appear inside <think></think> blocks - NEVER in your actual response
5. Use carrots when referencing or applying the character information: "🥕 Luna is wolf anthro, so she'd react protectively..."
**CARROT REQUIREMENT:** Exactly 10 🥕 emotes within <think> blocks only.</textarea>
</div>
<div class="bmt-macro-section toggle-macro">
<div class="bmt-panel-header bmt-collapsible-header" onclick="window.CARROT_toggleMacroSection()">
<div class="bmt-panel-title">
<span class="bmt-panel-icon">🔧</span>
<h3>Macro Configuration</h3>
<span class="bmt-collapse-indicator">▼</span>
</div>
<div class="bmt-panel-controls">
<button id="add_macro" class="bmt-action-btn bmt-add-btn" title="Add a new custom macro" onclick="event.stopPropagation();">
<i class="fa-solid fa-plus"></i> New Macro
</button>
</div>
</div>
<div id="macro_definitions" class="bmt-macro-definitions bmt-collapsible-content"></div>
</div>
</div>
<div class="bmt-template-metadata">
<div class="bmt-metadata-section">
<div class="bmt-metadata-row">
<div class="bmt-metadata-field">
<label class="bmt-metadata-label">
<span class="bmt-metadata-icon">📂</span>
<span class="bmt-metadata-title">Template Category</span>
<i class="fa-solid fa-info-circle bmt-tooltip" title="Template category - Currently only Character Data Injection is supported. This system allows you to create multiple templates for the same API call and mark one as primary."></i>
</label>
<select id="template_category" class="bmt-metadata-select">
<option value="Character Data Injection">💉 Character Data Injection</option>
<option value="BunnyMo Fullsheet Injection">🚨 BunnyMo Fullsheet Injection</option>
<option value="BunnyMo Tagsheet Injection">🚨 BunnyMo Tagsheet Injection</option>
<option value="BunnyMo Quicksheet Injection">🚨 BunnyMo Quicksheet Injection</option>
<option value="BunnyMo Memsheet Injection">🚨 BunnyMo Memsheet Injection</option>
<option value="BunnyMo Updatesheet Injection">🚨 BunnyMo Updatesheet Injection</option>
<option value="BunnyMo Physsheet Injection">🚨 BunnyMo Physsheet Injection</option>
</select>
</div>
<div class="bmt-metadata-field">
<label class="bmt-metadata-label">
<span class="bmt-metadata-icon">⭐</span>
<span class="bmt-metadata-title">Primary Template</span>
<i class="fa-solid fa-info-circle bmt-tooltip" title="When CarrotKernel needs a template of this category, it will use the primary one first. Only one template per category should be marked as primary."></i>
</label>
<div class="bmt-toggle-container">
<input id="template_role" type="checkbox" class="bmt-primary-toggle" />
<label for="template_role" class="bmt-toggle-label">
<span class="bmt-toggle-slider"></span>
<span class="bmt-toggle-text">Make Primary</span>
</label>
</div>
</div>
</div>
</div>
</div>
</div>
`
macro_definition_template = `
<div class="macro_definition bmt_interface_card">
<div class="inline-drawer">
<div class="inline-drawer-header">
<div class="flex-container alignitemscenter margin0 flex1">
<div class="bmt-macro-icon">🔧</div>
<button class="macro_enable menu_button fa-solid margin0"></button>
<button class="macro_preview menu_button fa-solid fa-eye margin0" title="Preview the result of this macro"></button>
<input class="macro_name flex1 text_pole" type="text" placeholder="name" readonly>
<button class="macro_copy menu_button fa-solid fa-copy margin0" title="Copy {{MACRO_NAME}} to clipboard"></button>
<button class="macro_insert menu_button fa-solid fa-plus margin0" title="Insert {{MACRO_NAME}} into template"></button>
</div>
<div class="inline-drawer-toggle">
<div class="inline-drawer-icon fa-solid fa-circle-chevron-down down"></div>
</div>
</div>
<div class="inline-drawer-content" style="display: none;">
<!-- Macro Documentation -->
<div class="bmt-macro-docs">
<div class="bmt-doc-toggle" style="cursor: pointer; padding: 8px; background: rgba(255,165,0,0.1); border-radius: 4px; margin-bottom: 8px;">
<span class="fa-solid fa-circle-chevron-down" style="margin-right: 8px;"></span>
<strong>📚 Documentation & Examples</strong>
</div>
<div class="bmt-macro-description" style="display: none;"></div>
</div>
<div class="flex-container alignitemscenter justifyCenter">
<div class="macro_type flex2">
<label>
<input type="radio" value="simple" />
<span>🎯 Simple</span>
</label>
<label>
<input type="radio" value="advanced" />
<span>⚡ Advanced</span>
</label>
</div>
</div>
<!-- Simple Settings -->
<div class="macro_type_simple">
<div class="bmt-config-header" style="cursor: pointer; padding: 6px; background: rgba(72, 209, 204, 0.1); border-radius: 4px; margin-bottom: 8px;">
<span class="fa-solid fa-circle-chevron-down bmt-config-toggle" style="margin-right: 8px;"></span>
<strong>🎯 Simple Configuration</strong>
</div>
<div class="macro_simple_content">
<!-- Content varies by macro type - populated dynamically -->
</div>
</div>
<!-- Advanced Settings -->
<div class="macro_type_advanced">
<div class="bmt-config-header" style="cursor: pointer; padding: 6px; background: rgba(255, 99, 71, 0.1); border-radius: 4px; margin-bottom: 8px;">
<span class="fa-solid fa-circle-chevron-down bmt-config-toggle" style="margin-right: 8px;"></span>
<strong>⚡ Advanced Configuration</strong>
</div>
<div class="macro_advanced_content">
<!-- Content varies by macro type - populated dynamically -->
</div>
</div>
<div class="macro_type_any flex-container alignitemscenter">
<label title="Apply CarrotKernel formatting to the output" class="checkbox_label">
<input type="checkbox" class="macro_format" />
<span>Apply Formatting</span>
</label>
<button class="macro_delete menu_button fa-solid fa-trash margin0" title="Delete this custom macro"></button>
<button class="macro_restore menu_button fa-solid fa-recycle margin0" title="Restore default settings for this macro"></button>
</div>
</div>
</div>
</div>
`
// Template dropdown and other settings
selectedTemplate = null;
// Initialize template manager reference
constructor() {
this.templateManager = CarrotTemplateManager;
this.macros = {};
this.initializeDefaultMacros();
}
// Static constants for enable/disable icons
static fa_enabled = 'fa-toggle-on';
static fa_disabled = 'fa-toggle-off';
initializeDefaultMacros() {
// Add default CarrotKernel macros that are always available
const defaultMacros = {
'CHARACTERS': {
name: 'CHARACTERS',
enabled: true,
type: 'simple',
format: false,
default: true
},
'CHARACTER1': {
name: 'CHARACTER1',
enabled: true,
type: 'simple',
format: false,
default: true
},
'CHARACTER2': {
name: 'CHARACTER2',
enabled: true,
type: 'simple',
format: false,
default: true
},
'PERSONALITY_TAGS': {
name: 'PERSONALITY_TAGS',
enabled: true,
type: 'simple',
format: false,
default: true
},
'PHYSICAL_TAGS': {
name: 'PHYSICAL_TAGS',
enabled: true,
type: 'simple',
format: false,
default: true
},
'CHARACTER_COUNT': {
name: 'CHARACTER_COUNT',
enabled: true,
type: 'simple',
format: false,
default: true
},
'SELECTED_LOREBOOKS': {
name: 'SELECTED_LOREBOOKS',
enabled: true,
type: 'simple',
format: false,
default: true
},
'BUNNYMO_PACK_TAGS': {
name: 'BUNNYMO_PACK_TAGS',
enabled: true,
type: 'simple',
format: false,
default: true
},
'CHARACTER_REPO_BOOKS': {
name: 'CHARACTER_REPO_BOOKS',
enabled: true,
type: 'simple',
format: false,
default: true
},
'CHARACTER_LIST': {
name: 'CHARACTER_LIST',
enabled: true,
type: 'simple',
format: false,
default: true
},
'TRIGGERED_CHARACTER_TAGS': {
name: 'TRIGGERED_CHARACTER_TAGS',
enabled: true,
type: 'simple',
format: false,
default: true
},
'ALL_TAG_CATEGORIES': {
name: 'ALL_TAG_CATEGORIES',
enabled: true,
type: 'simple',
format: false,
default: true
},
'CHARACTER_SOURCES': {
name: 'CHARACTER_SOURCES',
enabled: true,
type: 'simple',
format: false,
default: true
},
'TAG_STATISTICS': {
name: 'TAG_STATISTICS',
enabled: true,
type: 'simple',
format: false,
default: true
},
'CROSS_CHARACTER_ANALYSIS': {
name: 'CROSS_CHARACTER_ANALYSIS',
enabled: true,
type: 'simple',
format: false,
default: true
},
'REPOSITORY_METADATA': {
name: 'REPOSITORY_METADATA',
enabled: true,
type: 'simple',
format: false,
default: true
}
};
// Only add default macros if they don't exist
Object.entries(defaultMacros).forEach(([name, config]) => {
if (!this.macros[name]) {
this.macros[name] = config;
}
});
}
// Macro management methods
update_macros(macro=null) {
if (macro === null) {
// Clear existing macro interfaces
$('#macro_definitions').empty();
// Get all available macros and categorize them
const allMacros = this.getAllAvailableMacros();
const carrotMacros = [];
const systemMacros = [];
// Define CarrotKernel priority macros (only functional ones from macroProcessors)
const priorityMacros = [];
// Get actual functional CarrotKernel macros - use direct reference since we're in the same file
if (CarrotTemplateManager && CarrotTemplateManager.macroProcessors) {
Object.keys(CarrotTemplateManager.macroProcessors).forEach(macro => {
// Helper method for the *_OPTIONS processors, not a standalone
// macro — don't surface it as a bogus {{getBunnyMoPackOptions}} card.
if (macro === 'getBunnyMoPackOptions') return;
priorityMacros.push(macro);
});
} else {
CarrotDebug.error('CarrotTemplateManager.macroProcessors not available, using fallback list');
// Fallback list of known macros
priorityMacros.push(
'TRIGGERED_CHARACTER_TAGS', 'CHARACTER_LIST', 'CHARACTERS_WITH_TYPES', 'CHARACTERS',
'CHARACTER1', 'CHARACTER2', 'CHARACTER3', 'CHARACTER4', 'CHARACTER5',
'CHARACTER_COUNT', 'CHARACTER_SOURCES', 'PERSONALITY_TAGS', 'PHYSICAL_TAGS',
'MBTI_TAGS', 'COMMUNICATION_TAGS', 'IDENTITY_TAGS', 'KINK_TAGS', 'ALL_TAG_CATEGORIES',
'TAG_STATISTICS', 'CROSS_CHARACTER_ANALYSIS', 'REPOSITORY_METADATA',
'FULLSHEET_FORMAT', 'TAGSHEET_FORMAT', 'QUICKSHEET_FORMAT',
'SELECTED_LOREBOOKS', 'CHARACTER_REPO_BOOKS', 'BUNNYMO_PACK_TAGS'
);
}
// Categorize macros
allMacros.forEach(name => {
if (priorityMacros.includes(name)) {
carrotMacros.push(name);
} else {
systemMacros.push(name);
}
});
// Create CarrotKernel Priority Section
$('#macro_definitions').append(`
<div class="bmt-macro-category-section">
<div class="bmt-category-header expanded" data-category="carrot">
<div class="bmt-category-title">
<span class="bmt-category-icon">🥕</span>
<h4>CarrotKernel Macros</h4>
<span class="bmt-category-count">(${carrotMacros.length})</span>
</div>
<div class="bmt-category-toggle">
<span class="fa-solid fa-chevron-up"></span>
</div>
</div>
<div class="bmt-category-content" id="carrot-macros" style="display: block;"></div>
</div>
`);
// Create System Macros Section (collapsed by default)
$('#macro_definitions').append(`
<div class="bmt-macro-category-section">
<div class="bmt-category-header collapsed" data-category="system">
<div class="bmt-category-title">
<span class="bmt-category-icon">⚙️</span>
<h4>SillyTavern System Macros</h4>
<span class="bmt-category-count">(${systemMacros.length})</span>
</div>
<div class="bmt-category-toggle">
<span class="fa-solid fa-chevron-down"></span>
</div>
</div>
<div class="bmt-category-content" id="system-macros" style="display: none;"></div>
</div>
`);
// Create interfaces for CarrotKernel macros
for (let name of carrotMacros) {
let macro = this.get_macro(name) || {
name: name,
enabled: true,
type: 'simple',
format: false,
command: '',
default: false
};
this.create_macro_interface(macro, '#carrot-macros');
}
// Create interfaces for System macros
for (let name of systemMacros) {
let macro = this.get_macro(name) || {
name: name,
enabled: true,
type: 'simple',
format: false,
command: '',
default: false
};
this.create_macro_interface(macro, '#system-macros');
}
// Add category toggle functionality
this.setupCategoryToggles();
} else {
this.create_macro_interface(macro)
}
}
list_macros() {
return Object.keys(this.macros);
}
get_macro(name) {
let macro = this.macros[name];
if (macro) return macro;
return null;
}
setupCategoryToggles() {
// Add click handlers for category toggles
$('.bmt-category-header').off('click.categorytoggle').on('click.categorytoggle', (e) => {
e.preventDefault();
e.stopPropagation();
const $header = $(e.currentTarget);
const $content = $header.next('.bmt-category-content');
const $toggle = $header.find('.bmt-category-toggle span');
if ($content.is(':visible')) {
$content.slideUp(300);
$toggle.removeClass('fa-chevron-up').addClass('fa-chevron-down');
$header.removeClass('expanded').addClass('collapsed');
} else {
$content.slideDown(300);
$toggle.removeClass('fa-chevron-down').addClass('fa-chevron-up');
$header.removeClass('collapsed').addClass('expanded');
}
return false;
});
}
create_macro_interface(macro, container = '#macro_definitions') {
// Create or update a macro interface item with the given settings
let id = this.get_id(macro.name);
let $macro = $(container).find(`#${id}`);
if ($macro.length === 0) {
$macro = $(this.macro_definition_template).prependTo($(container));
$macro.attr('id', id);
}
// Set up radio group name for this specific macro
let radio_group_name = `macro_type_radio_${macro.name}`;
$macro.find('.macro_type input[type="radio"]').attr('name', radio_group_name);
// Get references to form elements
let $name = $macro.find('input.macro_name');
let $enable = $macro.find('button.macro_enable');
let $preview = $macro.find('button.macro_preview');
let $delete = $macro.find('button.macro_delete');
let $restore = $macro.find('button.macro_restore');
let $type_radios = $macro.find(`input[name="${radio_group_name}"]`);
// Set values from macro object
$name.val(macro.name);
// Set radio button for macro type
$type_radios.filter(`[value="${macro.type}"]`).prop('checked', true);
// Set enable/disable button state
$enable.removeClass(CarrotTemplatePromptEditInterface.fa_enabled + ' ' + CarrotTemplatePromptEditInterface.fa_disabled);
$enable.removeClass('button_highlight red_button');
if (macro.enabled) {
$enable.addClass(CarrotTemplatePromptEditInterface.fa_enabled + ' button_highlight');
$enable.attr('title', 'Enabled');
} else {
$enable.addClass(CarrotTemplatePromptEditInterface.fa_disabled + ' red_button');
$enable.attr('title', 'Disabled');
}
// Show/hide appropriate settings divs based on type
let $simple_div = $macro.find('.macro_type_simple');
let $advanced_div = $macro.find('.macro_type_advanced');
if (macro.type === 'simple') {
$simple_div.css('display', 'block');
$advanced_div.css('display', 'none');
} else {
$simple_div.css('display', 'none');
$advanced_div.css('display', 'block');
}
// Event handlers
$enable.off('click').on('click', () => {
macro.enabled = !macro.enabled;
this.create_macro_interface(macro); // Refresh to update button state
});
// Copy macro name to clipboard
$macro.find('.macro_copy').off('click').on('click', () => {
const macroText = `{{${macro.name}}}`;
navigator.clipboard.writeText(macroText).then(() => {
toastr.success(`Copied ${macroText} to clipboard!`);
}).catch(() => {
// Fallback for older browsers
const textArea = document.createElement('textarea');
textArea.value = macroText;
document.body.appendChild(textArea);
textArea.select();
document.execCommand('copy');
document.body.removeChild(textArea);
toastr.success(`Copied ${macroText} to clipboard!`);
});
});
// Insert macro into template
$macro.find('.macro_insert').off('click').on('click', () => {
const macroText = `{{${macro.name}}}`;
const $prompt = $('#prompt');
const currentText = $prompt.val();
const cursorPos = $prompt[0].selectionStart;
const newText = currentText.slice(0, cursorPos) + macroText + currentText.slice(cursorPos);
$prompt.val(newText);
// Set cursor after inserted macro
setTimeout(() => {
$prompt[0].setSelectionRange(cursorPos + macroText.length, cursorPos + macroText.length);
$prompt.focus();
}, 10);
toastr.success(`Inserted ${macroText} into template!`);
});
// Documentation toggle with proper event isolation
$macro.find('.bmt-doc-toggle').off('click.doctoggle').on('click.doctoggle', (e) => {
e.preventDefault();
e.stopImmediatePropagation();
const $description = $macro.find('.bmt-macro-description');
const $toggle = $macro.find('.bmt-doc-toggle span');
setTimeout(() => {
if ($description.is(':visible')) {
$description.slideUp(200);
$toggle.removeClass('fa-circle-chevron-up').addClass('fa-circle-chevron-down');
} else {
$description.slideDown(200);
$toggle.removeClass('fa-circle-chevron-down').addClass('fa-circle-chevron-up');
}
}, 50);
return false;
});
// Main drawer toggle functionality with proper event isolation
$macro.find('.inline-drawer-toggle').off('click.macrotoggle').on('click.macrotoggle', (e) => {
e.preventDefault();
e.stopImmediatePropagation();
const $content = $macro.find('.inline-drawer-content');
const $icon = $macro.find('.inline-drawer-icon');
// Add slight delay to prevent double-click issues
setTimeout(() => {
if ($content.is(':visible')) {
$content.slideUp(200);
$icon.removeClass('fa-circle-chevron-up').addClass('fa-circle-chevron-down');
} else {
$content.slideDown(200);
$icon.removeClass('fa-circle-chevron-down').addClass('fa-circle-chevron-up');
}
}, 50);
return false;
});
// Configuration section toggles with proper event isolation
$macro.find('.bmt-config-header').off('click.configtoggle').on('click.configtoggle', (e) => {
e.preventDefault();
e.stopImmediatePropagation();
const $header = $(e.currentTarget);
const $content = $header.next();
const $toggle = $header.find('.bmt-config-toggle');
setTimeout(() => {
if ($content.is(':visible')) {
$content.slideUp(200);
$toggle.removeClass('fa-circle-chevron-up').addClass('fa-circle-chevron-down');
} else {
$content.slideDown(200);
$toggle.removeClass('fa-circle-chevron-down').addClass('fa-circle-chevron-up');
}
}, 50);
return false;
});
$type_radios.off('change').on('change', () => {
macro.type = $type_radios.filter(':checked').val();
// Update visibility without full recreation to avoid losing input values
if (macro.type === 'simple') {
$simple_div.css('display', 'block');
$advanced_div.css('display', 'none');
} else {
$simple_div.css('display', 'none');
$advanced_div.css('display', 'block');
}
});
$preview.off('click').on('click', () => {
this.previewMacro(macro);
});
$delete.off('click').on('click', () => {
if (confirm(`Delete macro "${macro.name}"?`)) {
delete this.macros[macro.name];
$macro.remove();
}
});
// Populate macro-specific content for both simple and advanced modes
this.populateMacroSpecificContent(macro, $macro);
}
populateMacroSpecificContent(macro, $macro) {
const $simpleContent = $macro.find('.macro_simple_content');
const $advancedContent = $macro.find('.macro_advanced_content');
// Clear existing content
$simpleContent.empty();
$advancedContent.empty();
// Generate content based on macro configuration
const config = this.getMacroConfiguration(macro.name);
// Add documentation section
const $docs = $macro.find('.bmt-macro-description');
if (config.documentation) {
$docs.html(config.documentation);
}
if (config.simple) {
$simpleContent.html(config.simple);
}
if (config.advanced) {
$advancedContent.html(config.advanced);
}
// Set up event handlers for the specific controls
this.setupMacroEventHandlers(macro, $macro);
}
getMacroConfiguration(macroName) {
// Detailed configuration with proper examples and documentation
const macroConfigs = {
'TRIGGERED_CHARACTER_TAGS': {
documentation: `
<div class="bmt-macro-doc-header" style="background: rgba(255,165,0,0.2); padding: 10px; border-radius: 6px; border: 2px solid orange;">
<strong>✅ TRIGGERED_CHARACTER_TAGS - THE MAIN ONE!</strong>
</div>
<p><strong>Purpose:</strong> The heart of CarrotKernel - provides ALL character tags for characters currently active in the conversation context.</p>
<p><strong>Console Example Output:</strong></p>
<div style="background: #1a1a1a; padding: 10px; border-radius: 4px; font-family: monospace; color: #00ff00; font-size: 0.8em; overflow-x: auto;">
<BunnymoTags><Name:Atsu_Ibn_Oba_Al-Masri>, <GENRE:FANTASY> <PHYSICAL> <SPECIES:HUMAN>, <GENDER:MALE>, <BUILD:Muscular>, <BUILD:Tall>, <SKIN:FAIR>, <HAIR:BLACK>, <STYLE:ANCIENT_EGYPTIAN_ROYALTY>,</PHYSICAL> <PERSONALITY><Dere:Sadodere>, <Dere:Oujidere>, <ENTJ-U>, <TRAIT:CRUEL>, <TRAIT:INTELLIGENT>, <TRAIT:POWERFUL>, <TRAIT:DANGEROUS>, <TRAIT:SELFISH>, <TRAIT:HEDONISTIC>, <ATTACHMENT:FEARFUL_AVOIDANT>, <CONFLICT:COMPETITIVE>, <BOUNDARIES:RIGID>,<FLIRTING:AGGRESSIVE>, </PERSONALITY> <NSFW><ORIENTATION:PANSEXUAL>, <POWER:DOMINANT>, <KINK:BRAT_TAMING>, <KINK:PUBLIC_HUMILIATION>, <KINK:POWER_PLAY>, <KINK:EXHIBITIONISM>, <CHEMISTRY:ANTAGONISTIC>, <AROUSAL:DOMINANCE>, <TRAUMA:CHILDHOOD>, <JEALOUSY:POSSESSIVE>,</NSFW> </BunnymoTags><br/><br/>
<Linguistics> Character uses <LING:COMMANDING> as his primary mode of speech, asserting authority and control. This is almost always blended with <LING:SUGGESTIVE>, using a tone of cruel flirtation, possessive pet names, and psychological manipulation to achieve his goals. </linguistics>
</div>
<p><strong>Perfect For:</strong> Character consistency, BunnymoTags compatibility, comprehensive trait injection</p>
`,
simple: `<div class="bmt-form-group"><p><strong>🎯 This is the main macro for character injection!</strong><br/>No configuration needed - it automatically extracts and formats all character tags from your BunnymoTags data.</p></div>`,
advanced: `<div class="bmt-form-group"><p>Advanced tag filtering, formatting, and categorization options for power users.</p></div>`
},
'CHARACTER_LIST': {
documentation: `
<div class="bmt-macro-doc-header">
<strong>👥 CHARACTER_LIST - Simple Names</strong>
</div>
<p><strong>Purpose:</strong> Clean comma-separated list of character names currently active.</p>
<p><strong>Console Example Output:</strong></p>
<div style="background: #1a1a1a; padding: 10px; border-radius: 4px; font-family: monospace; color: #00ff00;">
Atsu_Ibn_Oba_Al-Masri
</div>
<p><strong>Use Case:</strong> Simple character awareness when you just need names without tags.</p>
`,
simple: `<div class="bmt-form-group"><p>Simple character name list - no configuration needed.</p></div>`,
advanced: `<div class="bmt-form-group"><p>Name formatting and separator options.</p></div>`
},
'CHARACTERS_WITH_TYPES': {
documentation: `
<div class="bmt-macro-doc-header">
<strong>🏷️ CHARACTERS_WITH_TYPES - Names + Species</strong>
</div>
<p><strong>Purpose:</strong> Character names with their species/types shown for context.</p>
<p><strong>Console Example Output:</strong></p>
<div style="background: #1a1a1a; padding: 10px; border-radius: 4px; font-family: monospace; color: #00ff00;">
Atsu_Ibn_Oba_Al-Masri (HUMAN)
</div>
<p><strong>Perfect For:</strong> Fantasy/sci-fi where species matters, role identification.</p>
`,
simple: `<div class="bmt-form-group"><p>Automatically detects character species/roles from SPECIES: tags.</p></div>`,
advanced: `<div class="bmt-form-group"><p>Custom type detection and formatting rules.</p></div>`
},
'PERSONALITY_TAGS': {
documentation: `
<div class="bmt-macro-doc-header">
<strong>🧠 PERSONALITY_TAGS - Character Traits</strong>
</div>
<p><strong>Purpose:</strong> Extracts personality and behavioral traits from all triggered characters.</p>
<p><strong>Console Example Output:</strong></p>
<div style="background: #1a1a1a; padding: 10px; border-radius: 4px; font-family: monospace; color: #00ff00; font-size: 0.85em;">
Atsu_Ibn_Oba_Al-Masri: Dere:Sadodere, Dere:Oujidere, ENTJ-U, TRAIT:CRUEL, TRAIT:INTELLIGENT, TRAIT:POWERFUL, TRAIT:DANGEROUS, TRAIT:SELFISH, TRAIT:HEDONISTIC, ATTACHMENT:FEARFUL_AVOIDANT, CONFLICT:COMPETITIVE, BOUNDARIES:RIGID, FLIRTING:AGGRESSIVE
</div>
<p><strong>Use Case:</strong> Personality consistency, character depth, behavioral reference.</p>
`,
simple: `<div class="bmt-form-group"><p>Automatically finds personality-related tags like TRAIT:, Dere:, MBTI types from character data.</p></div>`,
advanced: `<div class="bmt-form-group"><p>Custom personality tag filtering and categorization.</p></div>`
},
'PHYSICAL_TAGS': {
documentation: `
<div class="bmt-macro-doc-header">
<strong>👁️ PHYSICAL_TAGS - Appearance Traits</strong>
</div>
<p><strong>Purpose:</strong> Physical appearance, species, and visual characteristics from triggered characters.</p>
<p><strong>Console Example Output:</strong></p>
<div style="background: #1a1a1a; padding: 10px; border-radius: 4px; font-family: monospace; color: #00ff00; font-size: 0.85em;">
Atsu_Ibn_Oba_Al-Masri: SPECIES:HUMAN, GENDER:MALE, BUILD:Muscular, BUILD:Tall, SKIN:FAIR, HAIR:BLACK, STYLE:ANCIENT_EGYPTIAN_ROYALTY
</div>
<p><strong>Perfect For:</strong> Visual descriptions, appearance consistency, scene setting.</p>
`,
simple: `<div class="bmt-form-group"><p>Finds physical and appearance tags automatically from BunnymoTags PHYSICAL sections.</p></div>`,
advanced: `<div class="bmt-form-group"><p>Advanced appearance categorization and formatting.</p></div>`
},
'TAG_STATISTICS': {
documentation: `
<div class="bmt-macro-doc-header">
<strong>📊 TAG_STATISTICS - System Overview</strong>
</div>
<p><strong>Purpose:</strong> Statistical breakdown of your BunnymoTags system and character data from scanned characters.</p>
<p><strong>Console Example Output:</strong></p>
<div style="background: #1a1a1a; padding: 10px; border-radius: 4px; font-family: monospace; color: #00ff00; font-size: 0.85em;">
**Tag Statistics** (247 total tags across 15 characters)<br/>
Most common categories:<br/>
• PHYSICAL: 89 tags (12 characters)<br/>
• PERSONALITY: 67 tags (15 characters)<br/>
• NSFW: 45 tags (8 characters)<br/>
• GENRE: 23 tags (15 characters)<br/>
• Name: 15 tags (15 characters)
</div>
<p><strong>Use Case:</strong> System health, BunnymoTags data quality assessment, character coverage analysis.</p>
`,
simple: `<div class="bmt-form-group"><p>Comprehensive BunnymoTags system statistics and character data health metrics.</p></div>`,
advanced: `<div class="bmt-form-group"><p>Custom statistical analysis and BunnymoTags reporting options.</p></div>`
},
'REPOSITORY_METADATA': {
documentation: `
<div class="bmt-macro-doc-header">
<strong>🗃️ REPOSITORY_METADATA - System Status</strong>
</div>
<p><strong>Purpose:</strong> Complete CarrotKernel system status and health information.</p>
<p><strong>Console Example Output:</strong></p>
<div style="background: #1a1a1a; padding: 10px; border-radius: 4px; font-family: monospace; color: #00ff00; font-size: 0.85em;">
**CarrotKernel System Status**<br/>
📊 **System Overview:**<br/>
• Active lorebooks: 3<br/>
• Character repositories: 2<br/>
• Total characters indexed: 15<br/>
• Currently triggered: 3<br/>
• Tag categories available: 12<br/>
<br/>
📈 **Data Quality:**<br/>
• Character coverage: 87% (13/15 characters have tags)<br/>
• System health: Operational
</div>
<p><strong>Use Case:</strong> System monitoring, debugging, status reports.</p>
`,
simple: `<div class="bmt-form-group"><p>Complete system health and status overview.</p></div>`,
advanced: `<div class="bmt-form-group"><p>Detailed system metrics and custom reporting.</p></div>`
}
};
// Return specific config or generate dynamic one
return macroConfigs[macroName] || {
documentation: `
<div class="bmt-macro-doc-header">
<strong>🔧 ${macroName} Macro</strong>
</div>
<p><strong>Purpose:</strong> ${macroName.toLowerCase().replace(/_/g, ' ')} processing.</p>
<p><strong>Use Case:</strong> Dynamic content generation for templates.</p>
`,
simple: `<div class="bmt-form-group"><p>Standard macro processing options.</p></div>`,
advanced: `<div class="bmt-form-group"><p>Advanced configuration options.</p></div>`
};
}
getAllAvailableMacros() {
const allMacros = [];
// Get ALL functional macros from CarrotTemplateManager (direct reference)
if (CarrotTemplateManager && CarrotTemplateManager.macroProcessors) {
Object.keys(CarrotTemplateManager.macroProcessors).forEach(macro => {
// Helper method for the *_OPTIONS processors, not a standalone
// macro — don't surface it as a bogus {{getBunnyMoPackOptions}} card.
if (macro === 'getBunnyMoPackOptions') return;
allMacros.push(macro);
});
}
// Add common SillyTavern system macros (these work via ST's template system)
const systemMacros = [
'CHAR_NAME', 'CHAR_PERSONA', 'CHAR_DESCRIPTION', 'CHAR_SCENARIO', 'CHAR_GREETING',
'CHAR_EXAMPLES', 'CHAR_TAGS', 'CHAR_AVATAR', 'CHAR_BOOK',
'WORLD_INFO', 'CHAT_HISTORY', 'USER_NAME', 'SYSTEM_PROMPT', 'JAILBREAK', 'NSFW_PROMPT',
'CURRENT_TIME', 'CURRENT_DATE', 'RANDOM_NUMBER'
];
systemMacros.forEach(macro => {
if (!allMacros.includes(macro)) {
allMacros.push(macro);
}
});
return allMacros.sort();
}
setupMacroEventHandlers(macro, $macro) {
// Set up event handlers for all controls in this macro
const $controls = $macro.find('input, select, textarea');
$controls.off('change.carrotmacro input.carrotmacro').on('change.carrotmacro input.carrotmacro', (e) => {
const $control = $(e.target);
const settingName = $control.attr('name');
const value = $control.is(':checkbox') ? $control.prop('checked') : $control.val();
// Initialize macro settings if needed
if (!macro.settings) macro.settings = {};
// Store the setting
macro.settings[settingName] = value;
// Debug log
if (window.CarrotKernel?.debug) {
CarrotDebug.ui(`🥕 Macro ${macro.name} setting ${settingName} = ${value}`);
}
});
// Load existing settings into controls
if (macro.settings) {
Object.entries(macro.settings).forEach(([settingName, value]) => {
const $control = $macro.find(`[name="${settingName}"]`);
if ($control.length) {
if ($control.is(':checkbox')) {
$control.prop('checked', value);
} else {
$control.val(value);
}
}
});
}
}
async previewMacro(macro) {
// Get the current value from our macro processing system. processMacros is
// async (it awaits each processor internally), so this must be awaited too —
// otherwise the alert renders the literal text "[object Promise]".
const processedContent = await CarrotTemplateManager.processMacros(`{{${macro.name}}}`);
alert(`Macro Preview: ${macro.name}\n\nOutput:\n${processedContent}`);
}
get_id(name) {
return `macro_${name.replace(/[^a-zA-Z0-9]/g, '_')}`;
}
detectMacrosFromTemplate() {
// Get current template content from textarea
const templateContent = this.$prompt?.val() || '';
// Detect all {{MACRO_NAME}} patterns
const macroRegex = /\{\{([^}]+)\}\}/g;
const detectedMacros = new Set();
let match;
// List of template syntax that should be ignored (not CarrotKernel macros)
const ignoredPatterns = [
'/each', 'each', '#each', '/if', 'if', '#if',
'value', 'category', 'traits', 'name', 'content',
'index', 'key', 'this', '@index', '@key', '@first', '@last'
];
while ((match = macroRegex.exec(templateContent)) !== null) {
const macroName = match[1].trim();
// Skip template helpers and common Handlebars syntax
const isTemplateHelper = ignoredPatterns.some(pattern =>
macroName === pattern ||
macroName.startsWith(pattern + ' ') ||
macroName.startsWith('#' + pattern) ||
macroName.startsWith('/' + pattern)
);
// Only add valid CarrotKernel macro names (uppercase with underscores)
if (!isTemplateHelper && /^[A-Z][A-Z_0-9]*$/.test(macroName)) {
detectedMacros.add(macroName);
}
}
// Create macro objects for detected macros
detectedMacros.forEach(name => {
if (!this.macros[name]) {
this.macros[name] = {
name: name,
enabled: true,
type: 'simple',
format: false,
default: false // User-detected macros are not default
};
}
});
}
show() {
// Use CarrotKernel's popup system (same as Pack Manager)
CarrotKernel.showPopup('Template Editor', this.html_template);