-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
635 lines (556 loc) · 24.1 KB
/
index.js
File metadata and controls
635 lines (556 loc) · 24.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
// Import statements
import { eventSource, event_types, saveSettingsDebounced } from '../../../../script.js';
import { extension_settings } from '../../../extensions.js';
// Constants and Types
const CSS_THEME_STYLE_VAR = '--custom-theme-style-inputs';
const CTS_DRAWER_ID = 'ctsi-drawer';
const CTS_CONTENT_ID = 'ctsi-drawer-content';
const DEFAULT_CSS_TEMPLATE = `
:root {
--custom-theme-style-inputs: [
{
"type": "slider",
"varId": "customCSS-font-size",
"displayText": "CustomCSS font size",
"default": "5",
"min": 0,
"max": 32,
"step": 1
},
{
"type": "color",
"varId": "customCSS-background",
"displayText": "CustomCSS background",
"default": "rgba(149, 78, 178, 40)"
},
{
"type": "color",
"varId": "customCSS-Drawer-iconColor",
"displayText": "Drawer icon Color",
"default": "rgba(19, 78, 78, 30)"
},
{
"type": "text",
"varId": "customAnimation-duration",
"displayText": "animation duration",
"default": "0.1s"
},
{
"type": "select",
"varId": "expressionVisibility",
"displayText": "Expression Visibility",
"default": "visible",
"options": [
{
"label": "visible",
"value": "visible"
},
{
"label": "hidden",
"value": "hidden"
},
{
"label": "collapse",
"value": "collapse"
}
]
},
{
"type": "select",
"varId": "expressionWidth",
"displayText": "Expression size",
"default": "512px",
"options": [
{
"label": "512px",
"value": "512px"
},
{
"label": "0px",
"value": "0px"
}
]
}
]
}
/* !!! Exemples. If using slider always * 1(Unit) !!!*/
* {
--animation-duration: calc(var(--customAnimation-duration) * 1s);
}
.expression-holder {
width: var(--expressionWidth) !important;
height: var(--expressionWidth) !important;
min-width: var(--expressionWidth) !important;
min-height: var(--expressionWidth) !important;
}
.drawer-icon {
color: var(--customCSS-Drawer-iconColor) !important;
}
#expression-image {
visibility: var(--expressionVisibility);
}
#customCSS {
background: var(--customCSS-background);
font-size: calc(var(--customCSS-font-size) * 1px);
}
`;
class CustomThemeSettingsManager {
constructor() {
this.settings = this.initializeSettings();
this.previousStyleValue = null;
this.isAppReady = false;
// Bind methods for event listeners
this.handleDelegatedInput = this.handleDelegatedInput.bind(this);
this.handleDelegatedChange = this.handleDelegatedChange.bind(this);
this.handleDelegatedClick = this.handleDelegatedClick.bind(this);
}
/**
* Initialize extension settings from global storage
*/
initializeSettings() {
if (!extension_settings.CTSI) {
extension_settings.CTSI = {};
}
return extension_settings.CTSI;
}
/**
* Parse CSS variable content safely
* @param {string} cssVariable - The CSS variable name to parse
* @returns {Array} - Array of config objects
*/
_parseCSSConfig(cssVariable) {
try {
const cssContent = getComputedStyle(document.documentElement).getPropertyValue(cssVariable);
if (!cssContent || !cssContent.trim() || ['none', '""', "''"].includes(cssContent.trim())) {
return [];
}
const parsed = JSON.parse(cssContent);
if (!Array.isArray(parsed)) {
console.warn('[CTSI] CSS content is not an array');
return [];
}
const seenVarIds = new Set();
return parsed.filter(entry => {
if (!entry.type || !entry.varId || !entry.displayText) return false;
if (seenVarIds.has(entry.varId)) {
console.warn(`[CTSI] Duplicate varId ignored: ${entry.varId}`);
return false;
}
seenVarIds.add(entry.varId);
return true;
});
} catch (error) {
console.error(`[CTSI] Failed to parse ${cssVariable}:`, error);
return [];
}
}
/**
* Apply current settings to CSS variables in the DOM
* @param {Object} savedValues - Key-value map of settings
*/
updateCSSVariables(savedValues) {
Object.entries(savedValues).forEach(([varId, value]) => {
if (!varId || varId === 'undefined') return;
const unitKey = `${varId}-unit`;
const unit = savedValues[unitKey] || '';
const valueWithUnit = unit ? `${value}${unit}` : value;
if (valueWithUnit !== '') {
document.documentElement.style.setProperty(`--${varId}`, valueWithUnit);
}
});
}
/**
* Save settings to storage and update DOM
* @param {Object} entries
*/
saveSettings(entries) {
this.settings.entries = entries;
this.updateCSSVariables(entries);
saveSettingsDebounced();
}
/**
* Sanitize and synchronize settings with current CSS configuration
* @param {Array} parsedEntries
*/
syncSettingsWithConfig(parsedEntries) {
const currentVarIds = parsedEntries.map(entry => entry.varId);
// Cleanup obsolete entries
const entries = this.settings.entries || {};
Object.keys(entries).forEach(key => {
if (!currentVarIds.includes(key)) {
delete entries[key];
document.documentElement.style.removeProperty(`--${key}`);
}
});
// Initialize new entries
parsedEntries.forEach(entry => {
if (entries[entry.varId] === undefined) {
if (entry.type === 'select') {
const defaultOption = entry.options.find(opt => opt.value === entry.default) || entry.options[0];
entries[entry.varId] = defaultOption ? defaultOption.value : '';
} else if (entry.type === 'checkbox') {
entries[entry.varId] = entry.checked || false;
} else {
entries[entry.varId] = entry.default || '';
}
}
});
this.settings.entries = entries;
}
/**
* Generate HTML for a settings entry
*/
generateEntryHTML(entry, value) {
const safeValue = value !== undefined ? value : entry.default;
switch (entry.type) {
case 'slider':
return `
<div class="flex-container alignitemscenter">
<span data-i18n="${entry.displayText}">${entry.displayText}</span><br>
<div class="alignitemscenter flex-container flexFlowColumn flexBasis48p flexGrow flexShrink gap0">
<input class="neo-range-slider" type="range" data-var-id="${entry.varId}" min="${entry.min}" max="${entry.max}" value="${safeValue}" step="${entry.step || 1}">
<input class="neo-range-input" type="number" data-var-id="${entry.varId}" min="${entry.min}" max="${entry.max}" value="${safeValue}" step="${entry.step || 1}">
</div>
</div>`;
case 'color':
return `
<div class="flex-container alignItemsBaseline">
<span>${entry.displayText}</span>
<toolcool-color-picker data-var-id="${entry.varId}" color="${safeValue}"></toolcool-color-picker>
</div>`;
case 'text':
return `
<label class="flex-container alignItemsBaseline">
<span>${entry.displayText}</span><br>
<input type="text" class="text_pole wide100p widthNatural flex1 margin0" data-var-id="${entry.varId}" value="${safeValue}" />
</label>`;
case 'checkbox':
return `
<label class="checkbox_label alignItemsBaseline">
<span>${entry.displayText}</span>
<input type="checkbox" data-var-id="${entry.varId}" ${safeValue ? 'checked' : ''}>
</label>`;
case 'select':
const options = (entry.options || []).map(opt =>
`<option value="${opt.value}" ${opt.value === safeValue ? 'selected' : ''}>${opt.label}</option>`
).join('');
return `
<div class="flex-container alignItemsBaseline">
<span>${entry.displayText}</span>
<select class="widthNatural flex1 margin0" data-var-id="${entry.varId}">${options}</select>
</div>`;
default:
return '';
}
}
/**
* Event Handler: Input events (Text, Sliders, Numbers)
*/
handleDelegatedInput(event) {
const target = event.target;
const varId = target.dataset.varId;
if (!varId) return;
// Synchronize dual inputs (Slider + Number)
if (target.classList.contains('neo-range-slider') || target.classList.contains('neo-range-input')) {
const value = target.value;
const container = target.closest('.alignitemscenter'); // Parent container
const inputs = container.querySelectorAll(`[data-var-id="${varId}"]`);
inputs.forEach(input => {
if (input !== target) input.value = value;
});
this.settings.entries[varId] = value;
this.saveSettings(this.settings.entries);
}
// Text Inputs
else if (target.type === 'text') {
this.settings.entries[varId] = target.value;
this.saveSettings(this.settings.entries);
}
}
/**
* Event Handler: Change events (Select, Checkbox)
*/
handleDelegatedChange(event) {
const target = event.target;
const varId = target.dataset.varId;
if (!varId) return;
if (target.type === 'checkbox') {
this.settings.entries[varId] = target.checked;
this.saveSettings(this.settings.entries);
} else if (target.tagName === 'SELECT') {
this.settings.entries[varId] = target.value;
this.saveSettings(this.settings.entries);
}
}
/**
* Binds specific events to color pickers since they effectively use custom events
* that might not bubble correctly for delegation in all contexts.
*/
bindColorPickers() {
const pickers = document.querySelectorAll(`${CTS_CONTENT_ID} toolcool-color-picker`); // Use specific selector if possible, or query inside container
const container = document.getElementById(CTS_CONTENT_ID);
if (!container) return;
const containerPickers = container.querySelectorAll('toolcool-color-picker');
containerPickers.forEach(picker => {
// Remove old listener if any (safety, though we rebuild DOM)
// picker.replaceWith(picker.cloneNode(true)); // Heavy handed
picker.addEventListener('change', (evt) => {
const varId = picker.dataset.varId;
const color = evt.detail?.rgba || evt.detail?.hex || picker.color;
if (varId && color) {
this.settings.entries[varId] = color;
this.saveSettings(this.settings.entries);
}
});
});
}
/**
* Event Handler: Clicks (Buttons)
*/
handleDelegatedClick(event) {
const target = event.target.closest('.interactable, .ctsi-inline-drawer-maximize');
if (!target) return;
if (target.id === 'ctsi-copy-to-clipboard') {
this.copyToClipboard();
} else if (target.id === 'ctsi-update-customCSS') {
this.updateCustomCSSFile(); // Renamed to accurately reflect action
} else if (target.id === 'ctsi-reset-defaults') {
this.resetDefaults();
} else if (target.id === 'insert-default-css') { // ID for the empty state button
this.insertDefaultCSS();
} else if (target.classList.contains('ctsi-inline-drawer-maximize')) {
this.toggleMaximize(target);
}
}
toggleMaximize(btn) {
const icon = btn.querySelector('i');
const drawer = document.getElementById(CTS_DRAWER_ID);
const movingDivs = document.getElementById('movingDivs');
const originalParent = document.querySelector('[name="FontBlurChatWidthBlock"]'); // Fallback anchor
if (!drawer || !movingDivs) return;
if (icon.classList.contains('fa-window-maximize')) {
// Maximize
icon.classList.replace('fa-window-maximize', 'fa-window-restore');
// Store original parent if needed, but we know where it goes
drawer.dataset.originalParentIdx = Array.from(drawer.parentNode.children).indexOf(drawer);
movingDivs.appendChild(drawer);
drawer.classList.remove('inline-drawer');
drawer.classList.add('ctsi-drawer-content', 'flexGap5', 'maximized');
drawer.style.display = 'flex';
drawer.style.opacity = '1';
} else {
// Restore
icon.classList.replace('fa-window-restore', 'fa-window-maximize');
// Try to put it back exactly where it was, or append to original container
// Since we inject at specific point, simple append might displace it if multiple extensions
// But usually safe to append to the container found by selector
if (originalParent) {
originalParent.insertAdjacentElement('beforeend', drawer); // Or try to respect index
}
drawer.classList.add('inline-drawer');
drawer.classList.remove('ctsi-drawer-content', 'flexGap5', 'maximized');
drawer.style.display = '';
drawer.style.opacity = '';
}
}
copyToClipboard() {
const cssContent = this.generateCSSContent();
navigator.clipboard.writeText(cssContent).then(() => {
toastr.success('CSS content copied to clipboard');
}).catch(err => {
console.error('[CTSI] Clipboard error:', err);
toastr.error('Failed to copy to clipboard');
});
}
/**
* Updates the #customCSS element preserving existing content
*/
updateCustomCSSFile() {
const customCSSArea = document.getElementById('customCSS');
if (!customCSSArea) {
toastr.error('CustomCSS element not found');
return;
}
const currentContent = customCSSArea.value;
const generatedCSS = this.generateSettingsJSON();
let newContent = currentContent;
// Find the start of the variable definition
// We look for: --custom-theme-style-inputs : [
const keyMatch = /--custom-theme-style-inputs\s*:\s*\[/.exec(currentContent);
if (keyMatch) {
const tempStart = keyMatch.index + keyMatch[0].length - 1; // Index of the opening '['
let openBrackets = 0;
let closeBrackets = 0;
let endIndex = -1;
// Simple state machine to count matching brackets
// We start from the opening bracket we found
for (let i = tempStart; i < currentContent.length; i++) {
const char = currentContent[i];
if (char === '[') {
openBrackets++;
} else if (char === ']') {
closeBrackets++;
}
if (openBrackets > 0 && openBrackets === closeBrackets) {
endIndex = i + 1; // Include the closing ']'
break;
}
}
if (endIndex !== -1) {
// We found the full array block
const prefix = currentContent.substring(0, tempStart);
const suffix = currentContent.substring(endIndex);
// Reconstruct: prefix + new JSON + suffix
// We replaced currentContent.substring(tempStart, endIndex) with generatedCSS
newContent = prefix + generatedCSS + suffix;
} else {
console.warn('[CTSI] Could not find matching closing bracket for variable array');
// Fallback: Append or broken state
}
} else {
// Variable definition not found at all, try to find :root
const rootRegex = /:root\s*\{/;
if (rootRegex.test(currentContent)) {
// Insert into :root
newContent = currentContent.replace(rootRegex, `:root {\n --custom-theme-style-inputs: ${generatedCSS};\n`);
} else {
// Append new block
newContent = `${currentContent}\n:root {\n --custom-theme-style-inputs: ${generatedCSS};\n}`;
}
}
if (newContent !== currentContent) {
customCSSArea.value = newContent;
// Trigger input event to let other systems know (e.g., ST saving)
customCSSArea.dispatchEvent(new Event('input', { bubbles: true }));
toastr.success('CustomCSS updated');
} else {
// Even if content is same, user expected an update/save confirmation
toastr.success('CustomCSS is already up to date');
}
}
generateSettingsJSON() {
const entries = this.settings.entries;
const configEntries = this._parseCSSConfig(CSS_THEME_STYLE_VAR); // Get structure from CSS
// Map current settings values back to the config structure
const exportEntries = configEntries.map(config => {
const currentVal = entries[config.varId];
return {
...config,
default: currentVal !== undefined ? currentVal : config.default
};
});
return JSON.stringify(exportEntries, null, 2);
}
generateCSSContent() {
return `:root {\n --custom-theme-style-inputs: ${this.generateSettingsJSON()}\n}`;
}
insertDefaultCSS() {
const customCSSArea = document.getElementById('customCSS');
if (customCSSArea) {
customCSSArea.value = `${DEFAULT_CSS_TEMPLATE}\n${customCSSArea.value}`;
customCSSArea.dispatchEvent(new Event('input', { bubbles: true }));
this.buildUI(); // Rebuild UI after insertion
}
}
resetDefaults() {
if (!confirm('Are you sure you want to reset all theme inputs to their defaults?')) return;
this.settings.entries = {};
this.updateCSSVariables({});
this.previousStyleValue = null;
this.buildUI();
toastr.info('Settings reset to defaults');
}
/**
* Build the UI
*/
buildUI() {
const drawerContent = document.getElementById(CTS_CONTENT_ID);
if (!drawerContent) return;
// Container structure
drawerContent.innerHTML = `
<div class="flex-container ctsi-container flexFlowColumn">
<div class="flex-container ctsi-flex-container">
<div id="cts-row-1" class="flex-container flexFlowColumn" style="flex: 1;"></div>
<div id="cts-row-2" class="flex-container flexFlowColumn" style="flex: 1;"></div>
</div>
<div class="flex-container ctsi-button-container">
<div id="ctsi-copy-to-clipboard" title="Copy to Clipboard" class="menu_button margin0 interactable" tabindex="0"><i class="fa-solid fa-copy"></i></div>
<div id="ctsi-update-customCSS" title="Update customCSS" class="menu_button margin0 interactable" tabindex="0"><i class="fa-solid fa-save"></i></div>
<div id="ctsi-reset-defaults" title="Reset to Defaults" class="menu_button margin0 interactable" tabindex="0"><i class="fa-solid fa-undo"></i></div>
<div class="ctsi-inline-drawer-maximize"><i class="floating_panel_maximize fa-fw fa-solid fa-window-maximize"></i></div>
</div>
</div>`;
const row1 = document.getElementById('cts-row-1');
const row2 = document.getElementById('cts-row-2');
const parsedEntries = this._parseCSSConfig(CSS_THEME_STYLE_VAR);
if (parsedEntries.length === 0) {
row1.innerHTML = '<p class="alert-message">No custom theme styles found.</p>';
row2.innerHTML = '<button id="insert-default-css" class="menu_button menu_button_icon interactable flex1">Insert Default CSS Template</button>';
this.updateCSSVariables({});
return;
}
this.syncSettingsWithConfig(parsedEntries);
parsedEntries.forEach((entry, index) => {
const html = this.generateEntryHTML(entry, this.settings.entries[entry.varId]);
if (index < parsedEntries.length / 2) {
row1.insertAdjacentHTML('beforeend', html);
} else {
row2.insertAdjacentHTML('beforeend', html);
}
});
// Bind color pickers directly
this.bindColorPickers();
}
injectDrawer() {
if (document.getElementById(CTS_DRAWER_ID)) return;
const html = `
<div id="${CTS_DRAWER_ID}" class="inline-drawer wide100p flexFlowColumn">
<div class="inline-drawer-toggle inline-drawer-header userSettingsInnerExpandable">
<b>Custom Theme Inputs</b>
<div class="inline-drawer-icon fa-solid fa-circle-chevron-down down"></div>
</div>
<div id="${CTS_CONTENT_ID}" class="inline-drawer-content" style="font-size:small;"></div>
</div>
<hr>`;
const target = document.querySelector('[name="FontBlurChatWidthBlock"]');
if (target) {
target.insertAdjacentHTML('beforeend', html);
} else {
console.warn('[CTSI] Target container FontBlurChatWidthBlock not found');
}
}
setupDelegation() {
const container = document.getElementById(CTS_CONTENT_ID);
if (!container) return;
// Cleanup old if any (though usually we init once)
container.removeEventListener('input', this.handleDelegatedInput);
container.removeEventListener('change', this.handleDelegatedChange);
container.removeEventListener('click', this.handleDelegatedClick);
container.addEventListener('input', this.handleDelegatedInput);
container.addEventListener('change', this.handleDelegatedChange);
container.addEventListener('click', this.handleDelegatedClick);
}
initialize() {
eventSource.on(event_types.APP_READY, () => {
this.isAppReady = true;
this.injectDrawer();
this.buildUI();
this.setupDelegation();
// Apply initial settings
this.updateCSSVariables(this.settings.entries || {});
});
eventSource.on(event_types.SETTINGS_UPDATED, () => {
if (this.isAppReady) {
const currentConfig = this._parseCSSConfig(CSS_THEME_STYLE_VAR);
// Simple deep compare to see if we need to rebuild inputs
if (JSON.stringify(currentConfig) !== JSON.stringify(this.previousStyleValue)) {
this.previousStyleValue = currentConfig;
this.buildUI(); // Rebuilds UI and re-attaches if needed, but delegation on container persists
}
}
});
}
}
const customThemeManager = new CustomThemeSettingsManager();
customThemeManager.initialize();
export default customThemeManager;