-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
1568 lines (1452 loc) · 127 KB
/
content.js
File metadata and controls
1568 lines (1452 loc) · 127 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
/* StyleCraft v1.0.9 — Content Script / Editor */
(function () {
if (window.__stylecraft_editor_loaded) return;
window.__stylecraft_editor_loaded = true;
const PANEL_WIDTH = 520;
const THEME_ID = 'stylecraft-theme-styles';
const CUSTOM_ID = 'stylecraft-custom-styles';
const PREVIEW_ID = 'stylecraft-preview-styles';
const SC_EDITOR_THEMES = {
catppuccin: {bg:'#11111b',surface:'#1e1e2e',text:'#cdd6f4',subtext:'#bac2de',muted:'#585b70',faint:'#45475a',accent:'#cba6f7',blue:'#89b4fa',green:'#a6e3a1',red:'#f38ba8',pink:'#f5c2e7',yellow:'#f9e2af',aD:'rgba(203,166,247,0.08)',aM:'rgba(203,166,247,0.15)',border:'rgba(203,166,247,0.08)',inputBg:'rgba(17,17,27,0.7)',toggleBg:'rgba(69,71,90,0.6)',toggleOn:'rgba(203,166,247,0.5)',codeFg:'#f5c2e7',ddBg:'#1e1e2e',tagM:'rgba(243,180,107,0.12)',tagB:'rgba(249,226,175,0.1)',tagP:'rgba(166,227,161,0.1)',tagC:'rgba(137,180,250,0.12)'},
dark: {bg:'#0d1117',surface:'#161b22',text:'#e6edf3',subtext:'#b1bac4',muted:'#7d8590',faint:'#484f58',accent:'#58a6ff',blue:'#58a6ff',green:'#3fb950',red:'#f85149',pink:'#db61a2',yellow:'#d29922',aD:'rgba(88,166,255,0.08)',aM:'rgba(88,166,255,0.15)',border:'rgba(88,166,255,0.08)',inputBg:'rgba(13,17,23,0.7)',toggleBg:'rgba(110,118,129,0.4)',toggleOn:'rgba(88,166,255,0.5)',codeFg:'#79c0ff',ddBg:'#161b22',tagM:'rgba(227,179,65,0.12)',tagB:'rgba(210,153,34,0.1)',tagP:'rgba(63,185,80,0.1)',tagC:'rgba(88,166,255,0.12)'},
light: {bg:'#ffffff',surface:'#f6f8fa',text:'#1f2328',subtext:'#424a53',muted:'#656d76',faint:'#afb8c1',accent:'#8250df',blue:'#0969da',green:'#1a7f37',red:'#cf222e',pink:'#bf3989',yellow:'#9a6700',aD:'rgba(130,80,223,0.06)',aM:'rgba(130,80,223,0.12)',border:'rgba(130,80,223,0.12)',inputBg:'#ffffff',toggleBg:'rgba(175,184,193,0.5)',toggleOn:'rgba(130,80,223,0.5)',codeFg:'#953800',ddBg:'#f6f8fa',tagM:'rgba(188,76,0,0.08)',tagB:'rgba(154,103,0,0.08)',tagP:'rgba(26,127,55,0.08)',tagC:'rgba(9,105,218,0.08)'}
};
let currentEditorTheme = 'catppuccin';
function applyEditorTheme(name) {
const t = SC_EDITOR_THEMES[name] || SC_EDITOR_THEMES.catppuccin;
currentEditorTheme = name;
const el = shadow.querySelector('#sc-theme-vars');
if (!el) return;
el.textContent = `:host{--sc-bg:${t.bg};--sc-surface:${t.surface};--sc-text:${t.text};--sc-subtext:${t.subtext};--sc-muted:${t.muted};--sc-faint:${t.faint};--sc-accent:${t.accent};--sc-blue:${t.blue};--sc-green:${t.green};--sc-red:${t.red};--sc-pink:${t.pink};--sc-yellow:${t.yellow};--sc-accent-dim:${t.aD};--sc-accent-med:${t.aM};--sc-border:${t.border};--sc-input-bg:${t.inputBg};--sc-toggle-bg:${t.toggleBg};--sc-toggle-on:${t.toggleOn};--sc-code-fg:${t.codeFg};--sc-tag-margin:${t.tagM};--sc-tag-border:${t.tagB};--sc-tag-padding:${t.tagP};--sc-tag-content:${t.tagC};}` +
`#sc-panel{background:${t.bg};color:${t.text};border-color:${t.border};}` +
`.sc-header-row{border-bottom:1px solid ${t.border};}` +
`.sc-logo{background:linear-gradient(135deg,${t.accent},${t.blue});-webkit-background-clip:text;-webkit-text-fill-color:transparent;}` +
`.sc-ibtn{background:${t.aD};border-color:${t.border};color:${t.muted};}` +
`.sc-ibtn:hover,.sc-ibtn.active{background:${t.aM};color:${t.accent};}` +
`.sc-theme-dd{background:${t.inputBg};border-color:${t.border};color:${t.muted};}` +
`.sc-theme-dd option{background:${t.ddBg};color:${t.text};}` +
`.sc-tab{color:${t.muted};}.sc-tab.active,.sc-tab:hover{color:${t.accent};}` +
`.sc-tab.active::after{background:${t.accent};}` +
`.sc-group-header{color:${t.muted};}.sc-group-header:hover{color:${t.subtext};background:${t.aD};}` +
`.sc-prop-label{color:${t.muted};}` +
`.sc-prop-input,.sc-select-input{background:${t.inputBg};border-color:${t.border};color:${t.text};}` +
`.sc-prop-input:focus,.sc-select-input:focus{border-color:${t.accent};}` +
`#sc-code-editor{color:${t.codeFg};}` +
`#sc-code-editor::placeholder{color:${t.faint};}` +
`.sc-code-wrap{background:${t.inputBg};border-color:${t.border};}` +
`#sc-domain,.sc-selector-bar input{background:${t.inputBg};border-color:${t.border};color:${t.blue};}` +
`.sc-toggle-sl{background:${t.toggleBg};}.sc-toggle input:checked+.sc-toggle-sl{background:${t.toggleOn};}` +
`.sc-toggle input:checked+.sc-toggle-sl::before{background:${t.accent};}` +
`.sc-theme-item{border-color:${t.border};}.sc-theme-item:hover{background:${t.aD};}` +
`.sc-theme-btn{border-color:${t.border};color:${t.muted};background:${t.aD};}` +
`.sc-theme-textarea{background:${t.inputBg};border-color:${t.border};color:${t.codeFg};}` +
`.sc-bm-margin{background:${t.tagM};}.sc-bm-border{background:${t.tagB};}.sc-bm-padding{background:${t.tagP};}.sc-bm-content{background:${t.tagC};color:${t.blue};}` +
`.sc-bm-cell,.sc-bm-vcell{color:${t.subtext};}.sc-bm-cell:hover,.sc-bm-vcell:hover{background:${t.aM};}` +
`.sc-bm-edit{background:${t.inputBg};border-color:${t.accent};color:${t.codeFg};}` +
`#sc-toast{background:${t.surface};border-color:${t.border};color:${t.accent};}` +
`.sc-prop-group{border-color:${t.border};}` +
`.sc-quick-pick{background:${t.inputBg};border-color:${t.border};}.sc-quick-pick-label{color:${t.muted};}.sc-quick-pick-label.has-sel{color:${t.green};}`;
}
let state = {
open: false, picking: false, previewing: false,
activeTab: 'selector',
domain: '', customCSS: '', customEnabled: true,
themes: {}, // { id: { name, rawCSS, enabled } }
selector: '',
readability: false, grayscale: false,
undoStack: [], redoStack: [], basicProps: {},
pickedElement: null, pickerAncestors: [], pickerDepth: 0,
pickerSpecificity: 0, pickerCandidates: [],
hiddenElements: []
};
/* ─── Overlays ─── */
const highlightOverlay = document.createElement('div');
Object.assign(highlightOverlay.style, {position:'fixed',pointerEvents:'none',zIndex:'2147483644',background:'rgba(137,180,250,0.18)',border:'2px solid rgba(137,180,250,0.6)',borderRadius:'2px',display:'none',transition:'all 0.08s ease'});
document.documentElement.appendChild(highlightOverlay);
const selectorLabel = document.createElement('div');
Object.assign(selectorLabel.style, {position:'fixed',pointerEvents:'none',zIndex:'2147483645',background:'rgba(30,30,46,0.95)',color:'#a6e3a1',padding:'2px 8px',borderRadius:'4px',fontSize:'11px',fontFamily:"'SFMono-Regular','Cascadia Code','Consolas','Liberation Mono','Menlo',monospace",maxWidth:'400px',overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap',display:'none',backdropFilter:'blur(8px)',border:'1px solid rgba(166,227,161,0.2)'});
document.documentElement.appendChild(selectorLabel);
const persistentHighlight = document.createElement('div');
persistentHighlight.id = 'sc-persistent-highlight';
Object.assign(persistentHighlight.style, {position:'absolute',pointerEvents:'none',zIndex:'2147483643',border:'2px dashed rgba(137,180,250,0.5)',borderRadius:'2px',display:'none',background:'rgba(137,180,250,0.04)'});
document.documentElement.appendChild(persistentHighlight);
function showPersistentHighlight() {
const el = getCurrentDepthElement();
if (!el) { persistentHighlight.style.display='none'; return; }
const r = el.getBoundingClientRect();
Object.assign(persistentHighlight.style, {display:'block',left:(r.left+window.scrollX)+'px',top:(r.top+window.scrollY)+'px',width:r.width+'px',height:r.height+'px'});
}
function hidePersistentHighlight() { persistentHighlight.style.display='none'; }
function updatePersistentHighlight() { if(state.pickedElement) showPersistentHighlight(); }
window.addEventListener('scroll', updatePersistentHighlight);
window.addEventListener('resize', updatePersistentHighlight);
/* ─── Panel Host ─── */
const panelHost = document.createElement('div');
Object.assign(panelHost.style, {position:'fixed',top:'0',right:'-540px',width:PANEL_WIDTH+'px',height:'100vh',zIndex:'2147483646',transition:'right 0.3s cubic-bezier(0.4,0,0.2,1)'});
document.documentElement.appendChild(panelHost);
const shadow = panelHost.attachShadow({mode:'open'});
let refs = {};
function init() {
shadow.innerHTML = buildPanelHTML();
const $ = s => shadow.querySelector(s);
const $$ = s => shadow.querySelectorAll(s);
refs = {
closeBtn: $('#sc-close-btn'), pickBtn: $('#sc-pick-btn'), previewBtn: $('#sc-preview-btn'),
createBtn: $('#sc-create-btn'), undoBtn: $('#sc-undo-btn'), redoBtn: $('#sc-redo-btn'),
resetBtn: $('#sc-reset-btn'), hideBtn: $('#sc-hide-btn'), readBtn: $('#sc-readability-btn'), grayBtn: $('#sc-grayscale-btn'),
searchBtn: $('#sc-search-btn'), settingsBtn: $('#sc-settings-btn'),
editorTheme: $('#sc-editor-theme'),
domainInput: $('#sc-domain'), selectorInput: $('#sc-selector-input'),
depthSlider: $('#sc-depth-slider'), depthVal: $('#sc-depth-val'),
specSlider: $('#sc-spec-slider'), specVal: $('#sc-spec-val'),
matchCount: $('#sc-match-count'), filterList: $('#sc-filter-list'),
codeEditor: $('#sc-code-editor'), customToggle: $('#sc-custom-toggle'),
themeList: $('#sc-theme-list'),
quickPickBtn: $('#sc-quick-pick-btn'), quickPickLabel: $('#sc-quick-pick-label'),
toastEl: $('#sc-toast'), $$, $
};
wireEvents();
wireBoxModelEditing();
loadStyles();
}
async function loadStyles() {
return new Promise(resolve => {
chrome.runtime.sendMessage({action:'sc-get-domain-data',domain:state.domain||extractPageDomain()}, res=>{
if(chrome.runtime.lastError||!res){resolve();return;}
state.customCSS=res.customCSS||'';
state.customEnabled=res.customEnabled!==false;
state.themes=res.themes||{};
if(!state.domain) state.domain=extractPageDomain();
refs.domainInput.value=state.domain;
if(refs.codeEditor) refs.codeEditor.value=state.customCSS;
refs.customToggle.checked=state.customEnabled;
parseCSStoBasic(state.customCSS); updateLineNumbers(); renderThemeList();
resolve();
});
});
}
function extractPageDomain() {
try { return new URL(location.href).hostname; } catch { return location.hostname; }
}
/* ═══════ EVENTS ═══════ */
function wireEvents() {
refs.closeBtn.addEventListener('click', closeEditor);
refs.searchBtn.addEventListener('click', () => { chrome.runtime.sendMessage({action:'sc-open-options', tab:'browse'}); });
refs.settingsBtn.addEventListener('click', () => { chrome.runtime.sendMessage({action:'sc-open-options', tab:'settings'}); });
// Theme dropdown
if (refs.editorTheme) {
refs.editorTheme.addEventListener('change', () => {
applyEditorTheme(refs.editorTheme.value);
chrome.runtime.sendMessage({action:'sc-get-settings'}, s => {
const settings = s || {};
settings.theme = refs.editorTheme.value;
chrome.runtime.sendMessage({action:'sc-save-settings', settings});
chrome.runtime.sendMessage({action:'sc-theme-changed', theme: refs.editorTheme.value});
});
});
}
// Load theme from settings
chrome.runtime.sendMessage({action:'sc-get-settings'}, s => {
if (chrome.runtime.lastError || !s) return;
const theme = s.theme || 'catppuccin';
applyEditorTheme(theme);
if (refs.editorTheme) refs.editorTheme.value = theme;
});
// Listen for theme changes from other UIs
chrome.runtime.onMessage.addListener(msg => {
if (msg.action === 'sc-theme-changed' && msg.theme) {
applyEditorTheme(msg.theme);
if (refs.editorTheme) refs.editorTheme.value = msg.theme;
}
});
refs.pickBtn.addEventListener('click', togglePicker);
refs.quickPickBtn.addEventListener('click', togglePicker);
refs.previewBtn.addEventListener('click', togglePreview);
refs.createBtn.addEventListener('click', createFromSelector);
refs.undoBtn.addEventListener('click', undo);
refs.redoBtn.addEventListener('click', redo);
refs.resetBtn.addEventListener('click', resetStyles);
refs.customToggle.addEventListener('change', () => {
state.customEnabled=refs.customToggle.checked; applyLiveCSS(); saveCustomCSS();
});
refs.domainInput.addEventListener('change', () => { state.domain=refs.domainInput.value.trim(); loadStyles(); });
refs.$$('.sc-main-tab').forEach(t => t.addEventListener('click', () => switchTab(t.dataset.tab)));
refs.selectorInput.addEventListener('input', onSelectorChange);
refs.depthSlider.addEventListener('input', () => {
state.pickerDepth=parseInt(refs.depthSlider.value); refs.depthVal.textContent=state.pickerDepth; rebuildFromSliders();
});
refs.specSlider.addEventListener('input', () => {
state.pickerSpecificity=parseInt(refs.specSlider.value); refs.specVal.textContent=state.pickerSpecificity; rebuildFromSliders();
});
if (refs.codeEditor) {
refs.codeEditor.addEventListener('input', onCodeChange);
refs.codeEditor.addEventListener('keydown', onCodeKeydown);
refs.codeEditor.addEventListener('scroll', syncScroll);
}
refs.hideBtn.addEventListener('click', () => {
if (!state.selector) { toast('Pick an element first'); return; }
const el = getCurrentDepthElement();
if (!el) return;
const orig = el.style.display;
const alreadyHidden = state.hiddenElements.find(h => h.selector === state.selector);
if (alreadyHidden) { el.style.display = alreadyHidden.originalDisplay||''; state.hiddenElements = state.hiddenElements.filter(h=>h.selector!==state.selector); }
else { state.hiddenElements.push({selector:state.selector, originalDisplay:orig}); el.style.display='none'; }
updateHideBtn();
});
refs.readBtn.addEventListener('click', toggleReadability);
refs.grayBtn.addEventListener('click', toggleGrayscale);
// Box model visibility button
const bmVisBtn = shadow.querySelector('#sc-bm-vis-btn');
if (bmVisBtn) {
bmVisBtn.addEventListener('click', () => {
if (!state.selector) { toast('Pick an element first'); return; }
const el = getCurrentDepthElement(); if (!el) return;
const hidden = state.hiddenElements.find(h => h.selector === state.selector);
if (hidden) { el.style.display = hidden.originalDisplay||''; state.hiddenElements = state.hiddenElements.filter(h=>h.selector!==state.selector); }
else { state.hiddenElements.push({selector:state.selector, originalDisplay:el.style.display}); el.style.display='none'; }
updateHideBtn(); updateBoxModel(el);
});
}
// Visual tab
refs.$$('.sc-prop-input').forEach(input => {
input.addEventListener('change', () => { if(!state.selector) return; pushUndo(); state.basicProps[input.dataset.prop]=input.value; state.customCSS=basicToCSS(); refs.codeEditor.value=state.customCSS; applyLiveCSS(); saveCustomCSS(); });
});
refs.$$('.sc-select-input').forEach(sel => {
sel.addEventListener('change', () => { if(!state.selector) return; pushUndo(); state.basicProps[sel.dataset.prop]=sel.value; state.customCSS=basicToCSS(); refs.codeEditor.value=state.customCSS; applyLiveCSS(); saveCustomCSS(); });
});
refs.$$('.sc-color-input').forEach(ci => {
ci.addEventListener('input', () => { if(!state.selector) return; pushUndo(); state.basicProps[ci.dataset.prop]=ci.value; const ti=ci.parentElement.querySelector('.sc-prop-input[data-prop="'+ci.dataset.prop+'"]'); if(ti)ti.value=ci.value; state.customCSS=basicToCSS(); refs.codeEditor.value=state.customCSS; applyLiveCSS(); saveCustomCSS(); });
});
refs.$$('.sc-range-input').forEach(ri => {
ri.addEventListener('input', () => {
if(!state.selector) return;
pushUndo(); const val=parseFloat(ri.value); const unit=ri.dataset.unit||''; const display=unit?val+unit:val;
ri.nextElementSibling.textContent=display; state.basicProps[ri.dataset.prop]=String(display);
const ti=ri.closest('.sc-group-body')?.querySelector('.sc-prop-input[data-prop="'+ri.dataset.prop+'"]'); if(ti)ti.value=display;
state.customCSS=basicToCSS(); refs.codeEditor.value=state.customCSS; applyLiveCSS(); saveCustomCSS();
});
});
refs.$$('.sc-group-header').forEach(gh => {
gh.addEventListener('click', () => gh.parentElement.classList.toggle('collapsed'));
});
}
function switchTab(tab) {
state.activeTab = tab;
refs.$$('.sc-main-tab').forEach(t => t.classList.toggle('active', t.dataset.tab === tab));
refs.$$('.sc-tab-panel').forEach(p => p.style.display = p.dataset.panel === tab ? 'flex' : 'none');
if (tab === 'code') { refs.codeEditor.value = state.customCSS; updateLineNumbers(); }
if (tab === 'themes') renderThemeList();
if (tab === 'presets') renderPresets();
}
/* ═══════ PRESETS ENGINE ═══════ */
function applyPresetCSS(css) {
pushUndo();
const sel = state.selector || 'body';
const full = sel + ' {\n' + css + '\n}';
state.customCSS = (state.customCSS ? state.customCSS + '\n\n' : '') + full;
refs.codeEditor.value = state.customCSS;
applyLiveCSS(); saveCustomCSS();
toast('Preset applied');
}
function applyGlobalCSS(css) {
pushUndo();
state.customCSS = (state.customCSS ? state.customCSS + '\n\n' : '') + css;
refs.codeEditor.value = state.customCSS;
applyLiveCSS(); saveCustomCSS();
toast('Preset applied');
}
function renderPresets() {
const el = shadow.getElementById('sc-presets-content');
if (!el) return;
const sel = state.selector;
const selLabel = sel ? '<code style="color:#a6e3a1;font-size:9px;background:rgba(166,227,161,0.1);padding:1px 5px;border-radius:3px;">' + escHTML(sel.length > 40 ? sel.slice(0,37)+'...' : sel) + '</code>' : '<span style="color:#f38ba8;font-size:9px;">No element selected</span>';
el.innerHTML = '<div class="sc-preset-note">Pick an element first (Selector tab), then click a preset to apply. Global presets apply to the whole page.</div>' +
'<div style="padding:4px 14px 2px;font-size:9px;color:#585b70;">Target: ' + selLabel + '</div>' +
/* ── QUICK ACTIONS ── */
'<div class="sc-preset-section"><div class="sc-preset-title"><svg viewBox="0 0 24 24"><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z"/></svg>Quick Actions</div>' +
'<div class="sc-preset-grid">' +
pb('Hide Element','display: none !important;') +
pb('Make Invisible','visibility: hidden;') +
pb('Full Width','width: 100% !important; max-width: 100% !important;') +
pb('Center Block','margin-left: auto !important; margin-right: auto !important;') +
pb('Center Text','text-align: center !important;') +
pb('Remove Border','border: none !important;') +
pb('Remove Shadow','box-shadow: none !important;') +
pb('Remove Background','background: transparent !important;') +
pb('Remove Padding','padding: 0 !important;') +
pb('Remove Margin','margin: 0 !important;') +
pb('Make Rounded','border-radius: 12px !important;') +
pb('Make Pill','border-radius: 9999px !important;') +
pb('Make Circle','border-radius: 50% !important;') +
pb('Force Wrap','word-wrap: break-word !important; overflow-wrap: break-word !important;') +
'</div></div>' +
/* ── TYPOGRAPHY ── */
'<div class="sc-preset-section"><div class="sc-preset-title"><svg viewBox="0 0 24 24"><polyline points="4 7 4 4 20 4 20 7"/><line x1="9" y1="20" x2="15" y2="20"/><line x1="12" y1="4" x2="12" y2="20"/></svg>Typography</div>' +
'<div class="sc-preset-grid">' +
pb('Bigger Text','font-size: 18px !important;') +
pb('Smaller Text','font-size: 13px !important;') +
pb('Bold','font-weight: 700 !important;') +
pb('Light Weight','font-weight: 300 !important;') +
pb('Italic','font-style: italic !important;') +
pb('Uppercase','text-transform: uppercase !important; letter-spacing: 1px !important;') +
pb('Lowercase','text-transform: lowercase !important;') +
pb('Small Caps','font-variant: small-caps !important;') +
pb('Wide Spacing','letter-spacing: 2px !important;') +
pb('Tight Spacing','letter-spacing: -0.5px !important;') +
pb('Relaxed Lines','line-height: 1.8 !important;') +
pb('Tight Lines','line-height: 1.2 !important;') +
pb('No Underline','text-decoration: none !important;') +
pb('Underline','text-decoration: underline !important;') +
pb('Strikethrough','text-decoration: line-through !important;') +
pb('Text Shadow','text-shadow: 1px 1px 2px rgba(0,0,0,0.3) !important;') +
pb('Glow Text','text-shadow: 0 0 8px currentColor !important;','pink') +
pb('Neon Text','text-shadow: 0 0 5px #fff, 0 0 10px #fff, 0 0 20px #0ff, 0 0 40px #0ff !important;','pink') +
pb('Gradient Text','background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important; -webkit-background-clip: text !important; -webkit-text-fill-color: transparent !important;','pink') +
pb('Monospace','font-family: Consolas, Monaco, monospace !important;') +
pb('Serif','font-family: Georgia, "Times New Roman", serif !important;') +
pb('System Sans','font-family: system-ui, -apple-system, sans-serif !important;') +
'</div></div>' +
/* ── COLORS ── */
'<div class="sc-preset-section"><div class="sc-preset-title"><svg viewBox="0 0 24 24"><circle cx="13.5" cy="6.5" r="2.5"/><circle cx="17.5" cy="10.5" r="2.5"/><circle cx="8.5" cy="7.5" r="2.5"/><path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.93 0 1.5-.67 1.5-1.5 0-.39-.15-.74-.39-1.04-.24-.3-.39-.65-.39-1.04 0-.83.67-1.5 1.5-1.5H16c3.31 0 6-2.69 6-6 0-5.17-4.5-9-10-9z"/></svg>Color & Background</div>' +
'<div class="sc-preset-grid">' +
pb('White Text','color: #ffffff !important;') +
pb('Black Text','color: #000000 !important;') +
pb('Red Text','color: #ef4444 !important;','red') +
pb('Blue Text','color: #3b82f6 !important;','blue') +
pb('Green Text','color: #22c55e !important;','green') +
pb('Purple Text','color: #a855f7 !important;') +
pb('Gold Text','color: #f59e0b !important;','yellow') +
pb('Dark BG','background-color: #1a1a2e !important; color: #e0e0e0 !important;') +
pb('Light BG','background-color: #fafafa !important; color: #1a1a1a !important;') +
pb('Frosted Glass','background: rgba(255,255,255,0.08) !important; backdrop-filter: blur(12px) !important; -webkit-backdrop-filter: blur(12px) !important;','blue') +
pb('Dark Glass','background: rgba(0,0,0,0.5) !important; backdrop-filter: blur(16px) !important; -webkit-backdrop-filter: blur(16px) !important;','blue') +
pb('Gradient Sunset','background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%) !important;','pink') +
pb('Gradient Ocean','background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;','blue') +
pb('Gradient Forest','background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%) !important;','green') +
pb('Gradient Fire','background: linear-gradient(135deg, #f12711 0%, #f5af19 100%) !important;','red') +
pb('Gradient Northern Lights','background: linear-gradient(135deg, #43e97b 0%, #38f9d7 30%, #fa8bff 100%) !important;','pink') +
pb('Gradient Cyber','background: linear-gradient(135deg, #0f0c29, #302b63, #24243e) !important;') +
pb('Mesh Gradient','background: radial-gradient(at 40% 20%, #1a1a2e 0, transparent 50%), radial-gradient(at 80% 0%, #3b0764 0, transparent 50%), radial-gradient(at 0% 50%, #172554 0, transparent 50%) !important; background-color: #0a0a1a !important;','pink') +
'</div></div>' +
/* ── SHADOWS & EFFECTS ── */
'<div class="sc-preset-section"><div class="sc-preset-title"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="4"/><path d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.36-5.36l-.7.7M6.34 17.66l-.7.7m12.02.7l-.7-.7M6.34 6.34l-.7-.7"/></svg>Shadows & Effects</div>' +
'<div class="sc-preset-grid">' +
pb('Subtle Shadow','box-shadow: 0 1px 3px rgba(0,0,0,0.12) !important;') +
pb('Medium Shadow','box-shadow: 0 4px 12px rgba(0,0,0,0.15) !important;') +
pb('Heavy Shadow','box-shadow: 0 10px 40px rgba(0,0,0,0.3) !important;') +
pb('Inner Shadow','box-shadow: inset 0 2px 6px rgba(0,0,0,0.2) !important;') +
pb('Glow Purple','box-shadow: 0 0 15px rgba(168,85,247,0.5), 0 0 30px rgba(168,85,247,0.2) !important;','pink') +
pb('Glow Blue','box-shadow: 0 0 15px rgba(59,130,246,0.5), 0 0 30px rgba(59,130,246,0.2) !important;','blue') +
pb('Glow Green','box-shadow: 0 0 15px rgba(34,197,94,0.5), 0 0 30px rgba(34,197,94,0.2) !important;','green') +
pb('Glow Red','box-shadow: 0 0 15px rgba(239,68,68,0.5), 0 0 30px rgba(239,68,68,0.2) !important;','red') +
pb('Neon Border','box-shadow: 0 0 5px #0ff, 0 0 10px #0ff, inset 0 0 5px #0ff !important; border: 1px solid #0ff !important;','pink') +
pb('Ring Accent','box-shadow: 0 0 0 3px rgba(168,85,247,0.5) !important;') +
pb('Blur 4px','filter: blur(4px) !important;') +
pb('Blur 10px','filter: blur(10px) !important;') +
pb('Grayscale','filter: grayscale(100%) !important;') +
pb('Sepia','filter: sepia(100%) !important;','yellow') +
pb('Invert','filter: invert(100%) !important;') +
pb('Saturate','filter: saturate(200%) !important;') +
pb('Desaturate','filter: saturate(50%) !important;') +
pb('Brightness Up','filter: brightness(1.3) !important;') +
pb('Brightness Down','filter: brightness(0.7) !important;') +
pb('Contrast Up','filter: contrast(1.4) !important;') +
pb('Hue Rotate 90','filter: hue-rotate(90deg) !important;') +
pb('Hue Rotate 180','filter: hue-rotate(180deg) !important;') +
pb('Drop Shadow','filter: drop-shadow(4px 4px 8px rgba(0,0,0,0.4)) !important;') +
'</div></div>' +
/* ── BORDERS ── */
'<div class="sc-preset-section"><div class="sc-preset-title"><svg viewBox="0 0 24 24"><rect x="3" y="3" width="18" height="18" rx="3"/></svg>Borders</div>' +
'<div class="sc-preset-grid">' +
pb('Thin Border','border: 1px solid rgba(128,128,128,0.3) !important;') +
pb('Medium Border','border: 2px solid rgba(128,128,128,0.4) !important;') +
pb('Accent Border','border: 2px solid #a855f7 !important;') +
pb('Dashed','border: 2px dashed rgba(128,128,128,0.4) !important;') +
pb('Dotted','border: 2px dotted rgba(128,128,128,0.4) !important;') +
pb('Double','border: 4px double rgba(128,128,128,0.4) !important;') +
pb('Left Accent','border-left: 3px solid #a855f7 !important;') +
pb('Bottom Accent','border-bottom: 2px solid #a855f7 !important;') +
pb('Gradient Border','border: 2px solid transparent !important; background-clip: padding-box !important; outline: 2px solid #a855f7 !important;','pink') +
pb('Round 4px','border-radius: 4px !important;') +
pb('Round 8px','border-radius: 8px !important;') +
pb('Round 16px','border-radius: 16px !important;') +
pb('Round 24px','border-radius: 24px !important;') +
'</div></div>' +
/* ── LAYOUT ── */
'<div class="sc-preset-section"><div class="sc-preset-title"><svg viewBox="0 0 24 24"><rect x="2" y="2" width="20" height="20" rx="2"/><line x1="2" y1="12" x2="22" y2="12"/><line x1="12" y1="2" x2="12" y2="22"/></svg>Layout & Spacing</div>' +
'<div class="sc-preset-grid">' +
pb('Padding SM','padding: 8px !important;') +
pb('Padding MD','padding: 16px !important;') +
pb('Padding LG','padding: 24px !important;') +
pb('Padding XL','padding: 40px !important;') +
pb('Margin SM','margin: 8px !important;') +
pb('Margin MD','margin: 16px !important;') +
pb('Gap 8px','gap: 8px !important;') +
pb('Gap 16px','gap: 16px !important;') +
pb('Flex Row','display: flex !important; flex-direction: row !important; gap: 8px !important;') +
pb('Flex Column','display: flex !important; flex-direction: column !important; gap: 8px !important;') +
pb('Flex Center','display: flex !important; align-items: center !important; justify-content: center !important;') +
pb('Grid 2-Col','display: grid !important; grid-template-columns: 1fr 1fr !important; gap: 12px !important;') +
pb('Grid 3-Col','display: grid !important; grid-template-columns: repeat(3, 1fr) !important; gap: 12px !important;') +
pb('Max Width 800','max-width: 800px !important; margin-left: auto !important; margin-right: auto !important;') +
pb('Sticky Top','position: sticky !important; top: 0 !important; z-index: 100 !important;') +
pb('Fixed Bottom','position: fixed !important; bottom: 0 !important; left: 0 !important; right: 0 !important; z-index: 100 !important;') +
'</div></div>' +
/* ── ANIMATIONS ── */
'<div class="sc-preset-section"><div class="sc-preset-title"><svg viewBox="0 0 24 24"><polyline points="15 3 21 3 21 9"/><polyline points="9 21 3 21 3 15"/><line x1="21" y1="3" x2="14" y2="10"/><line x1="3" y1="21" x2="10" y2="14"/></svg>Animations & Transitions</div>' +
'<div class="sc-preset-grid">' +
pb('Smooth Hover','transition: all 0.3s ease !important;') +
pb('Fast Hover','transition: all 0.15s ease !important;') +
pb('Spring','transition: all 0.4s cubic-bezier(0.34, 1.56, 0.64, 1) !important;','pink') +
pb('Hover Lift','transition: all 0.2s ease !important;','blue') +
pb('Hover Scale','transition: transform 0.2s ease !important;','blue') +
pb('Hover Glow','transition: box-shadow 0.3s ease !important;','blue') +
apb('Pulse','sc-pulse','2s ease-in-out infinite','0%,100%{opacity:1}50%{opacity:0.5}','pink') +
apb('Float','sc-float','3s ease-in-out infinite','0%,100%{transform:translateY(0)}50%{transform:translateY(-8px)}','pink') +
apb('Shake','sc-shake','0.5s ease-in-out','0%,100%{transform:translateX(0)}25%{transform:translateX(-4px)}75%{transform:translateX(4px)}','red') +
apb('Spin','sc-spin','2s linear infinite','to{transform:rotate(360deg)}','pink') +
apb('Bounce','sc-bounce','1s ease infinite','0%,100%{transform:translateY(0)}50%{transform:translateY(-12px)}','green') +
apb('Fade In','sc-fadeIn','0.5s ease-out','from{opacity:0}to{opacity:1}','') +
apb('Slide In Left','sc-slideInLeft','0.4s ease-out','from{opacity:0;transform:translateX(-20px)}to{opacity:1;transform:translateX(0)}','') +
apb('Slide In Up','sc-slideInUp','0.4s ease-out','from{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}','') +
'</div></div>' +
/* ── CSS TRICKS ── */
'<div class="sc-preset-section"><div class="sc-preset-title"><svg viewBox="0 0 24 24"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/></svg>CSS Tricks & Fun</div>' +
'<div class="sc-preset-grid">' +
pb('Glassmorphism','background: rgba(255,255,255,0.1) !important; backdrop-filter: blur(16px) saturate(180%) !important; -webkit-backdrop-filter: blur(16px) saturate(180%) !important; border: 1px solid rgba(255,255,255,0.18) !important; border-radius: 12px !important;','pink') +
pb('Neumorphism Light','background: #e0e5ec !important; box-shadow: 8px 8px 16px #b8bec7, -8px -8px 16px #ffffff !important; border-radius: 12px !important; border: none !important;','blue') +
pb('Neumorphism Dark','background: #2d2d3f !important; box-shadow: 8px 8px 16px #1a1a28, -8px -8px 16px #404056 !important; border-radius: 12px !important; border: none !important;') +
pb('Claymorphism','background: rgba(168,85,247,0.25) !important; border-radius: 24px !important; box-shadow: inset 0 -4px 6px rgba(0,0,0,0.2), 0 8px 20px rgba(168,85,247,0.2) !important; border: 2px solid rgba(255,255,255,0.2) !important;','pink') +
pb('Retro Pixel','image-rendering: pixelated !important; font-family: "Courier New", monospace !important; border: 3px solid #333 !important;','yellow') +
pb('Outline Mode','background: transparent !important; border: 1px solid red !important; box-shadow: none !important;','red') +
pb('Clip Circle','clip-path: circle(50%) !important;','pink') +
pb('Clip Diamond','clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%) !important;','pink') +
pb('Clip Hexagon','clip-path: polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%) !important;','pink') +
pb('Rainbow Border','border-image: linear-gradient(135deg, #f00, #ff0, #0f0, #0ff, #00f, #f0f, #f00) 1 !important; border-width: 3px !important; border-style: solid !important;','pink') +
pb('Mirror Flip','transform: scaleX(-1) !important;') +
pb('Upside Down','transform: rotate(180deg) !important;') +
pb('Tilt 3D','transform: perspective(800px) rotateY(-8deg) !important;','blue') +
pb('Skew','transform: skewX(-5deg) !important;') +
pb('Hover Tilt 3D','transform: perspective(600px) rotateX(2deg) rotateY(-2deg) !important; transition: transform 0.3s ease !important;','blue') +
pb('Vintage','filter: sepia(60%) contrast(90%) brightness(90%) !important;','yellow') +
pb('Film Noir','filter: grayscale(100%) contrast(130%) brightness(80%) !important;') +
pb('Cyberpunk','filter: hue-rotate(300deg) saturate(150%) contrast(120%) !important;','pink') +
pb('Vaporwave','filter: hue-rotate(180deg) saturate(200%) brightness(110%) !important;','pink') +
pb('Frosted Noise','background: rgba(0,0,0,0.4) !important; backdrop-filter: blur(20px) saturate(160%) contrast(110%) !important;','blue') +
pb('Text Stroke','color: transparent !important; -webkit-text-stroke: 1px currentColor !important;','pink') +
gpb('Selection Color','::selection{background:#a855f7!important;color:#fff!important}::-moz-selection{background:#a855f7!important;color:#fff!important}','blue') +
pb('Smooth Scroll','scroll-behavior: smooth !important;') +
pb('Hide Scrollbar','scrollbar-width: none !important; -ms-overflow-style: none !important;') +
pb('Snap Scroll','scroll-snap-type: y mandatory !important;') +
'</div></div>' +
/* ── GLOBAL: DARK THEMES ── */
'<div class="sc-preset-section"><div class="sc-preset-title"><svg viewBox="0 0 24 24"><path d="M21 12.79A9 9 0 1111.21 3 7 7 0 0021 12.79z"/></svg>Global Dark Themes (Full Page)</div>' +
'<div class="sc-preset-grid">' +
gpb('Midnight','html,body{background:#0d1117!important;color:#c9d1d9!important}a{color:#58a6ff!important}img{opacity:0.9!important}*{border-color:#30363d!important;scrollbar-color:#30363d #0d1117}input,textarea,select,button{background:#161b22!important;color:#c9d1d9!important;border-color:#30363d!important}div,section,article,main,aside,header,footer,nav{background-color:transparent!important}table,th,td{border-color:#30363d!important;background:transparent!important;color:#c9d1d9!important}') +
gpb('Catppuccin Mocha','html,body{background:#1e1e2e!important;color:#cdd6f4!important}a{color:#89b4fa!important}img{opacity:0.92!important}*{border-color:#313244!important;scrollbar-color:#45475a #1e1e2e}input,textarea,select,button{background:#313244!important;color:#cdd6f4!important;border-color:#45475a!important}div,section,article,main,aside,header,footer,nav{background-color:transparent!important}table,th,td{border-color:#45475a!important;background:transparent!important;color:#cdd6f4!important}') +
gpb('Dracula','html,body{background:#282a36!important;color:#f8f8f2!important}a{color:#bd93f9!important}img{opacity:0.92!important}*{border-color:#44475a!important;scrollbar-color:#44475a #282a36}input,textarea,select,button{background:#44475a!important;color:#f8f8f2!important;border-color:#6272a4!important}div,section,article,main,aside,header,footer,nav{background-color:transparent!important}table,th,td{border-color:#44475a!important;background:transparent!important;color:#f8f8f2!important}') +
gpb('Nord','html,body{background:#2e3440!important;color:#d8dee9!important}a{color:#88c0d0!important}img{opacity:0.92!important}*{border-color:#3b4252!important;scrollbar-color:#4c566a #2e3440}input,textarea,select,button{background:#3b4252!important;color:#d8dee9!important;border-color:#4c566a!important}div,section,article,main,aside,header,footer,nav{background-color:transparent!important}table,th,td{border-color:#4c566a!important;background:transparent!important;color:#d8dee9!important}') +
gpb('Gruvbox Dark','html,body{background:#282828!important;color:#ebdbb2!important}a{color:#83a598!important}img{opacity:0.92!important}*{border-color:#3c3836!important;scrollbar-color:#504945 #282828}input,textarea,select,button{background:#3c3836!important;color:#ebdbb2!important;border-color:#504945!important}div,section,article,main,aside,header,footer,nav{background-color:transparent!important}table,th,td{border-color:#504945!important;background:transparent!important;color:#ebdbb2!important}') +
gpb('Solarized Dark','html,body{background:#002b36!important;color:#839496!important}a{color:#268bd2!important}img{opacity:0.92!important}*{border-color:#073642!important;scrollbar-color:#073642 #002b36}input,textarea,select,button{background:#073642!important;color:#839496!important;border-color:#586e75!important}div,section,article,main,aside,header,footer,nav{background-color:transparent!important}table,th,td{border-color:#073642!important;background:transparent!important;color:#839496!important}') +
gpb('Tokyo Night','html,body{background:#1a1b26!important;color:#a9b1d6!important}a{color:#7aa2f7!important}img{opacity:0.92!important}*{border-color:#24283b!important;scrollbar-color:#414868 #1a1b26}input,textarea,select,button{background:#24283b!important;color:#a9b1d6!important;border-color:#414868!important}div,section,article,main,aside,header,footer,nav{background-color:transparent!important}table,th,td{border-color:#414868!important;background:transparent!important;color:#a9b1d6!important}') +
gpb('One Dark','html,body{background:#282c34!important;color:#abb2bf!important}a{color:#61afef!important}img{opacity:0.92!important}*{border-color:#3e4451!important;scrollbar-color:#4b5263 #282c34}input,textarea,select,button{background:#3e4451!important;color:#abb2bf!important;border-color:#4b5263!important}div,section,article,main,aside,header,footer,nav{background-color:transparent!important}table,th,td{border-color:#3e4451!important;background:transparent!important;color:#abb2bf!important}') +
gpb('OLED Black','html,body{background:#000000!important;color:#e0e0e0!important}a{color:#bb86fc!important}img{opacity:0.88!important}*{border-color:#1a1a1a!important;scrollbar-color:#333 #000}input,textarea,select,button{background:#121212!important;color:#e0e0e0!important;border-color:#333!important}div,section,article,main,aside,header,footer,nav{background-color:transparent!important}table,th,td{border-color:#1a1a1a!important;background:transparent!important;color:#e0e0e0!important}') +
gpb('Material Dark','html,body{background:#121212!important;color:#e0e0e0!important}a{color:#bb86fc!important}img{opacity:0.9!important}*{border-color:#2c2c2c!important;scrollbar-color:#424242 #121212}input,textarea,select,button{background:#1e1e1e!important;color:#e0e0e0!important;border-color:#424242!important}div,section,article,main,aside,header,footer,nav{background-color:transparent!important}table,th,td{border-color:#2c2c2c!important;background:transparent!important;color:#e0e0e0!important}') +
'</div></div>' +
/* ── GLOBAL: LIGHT THEMES ── */
'<div class="sc-preset-section"><div class="sc-preset-title"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg>Global Light Themes (Full Page)</div>' +
'<div class="sc-preset-grid">' +
gpb('Clean White','html,body{background:#ffffff!important;color:#1f2937!important}a{color:#2563eb!important}*{border-color:#e5e7eb!important;scrollbar-color:#d1d5db #f9fafb}input,textarea,select,button{background:#f9fafb!important;color:#1f2937!important;border-color:#d1d5db!important}div,section,article,main,aside,header,footer,nav{background-color:transparent!important}','green') +
gpb('Warm Paper','html,body{background:#fdf6e3!important;color:#657b83!important}a{color:#268bd2!important}*{border-color:#eee8d5!important;scrollbar-color:#93a1a1 #fdf6e3}input,textarea,select,button{background:#eee8d5!important;color:#657b83!important;border-color:#93a1a1!important}div,section,article,main,aside,header,footer,nav{background-color:transparent!important}','yellow') +
gpb('Latte','html,body{background:#eff1f5!important;color:#4c4f69!important}a{color:#1e66f5!important}*{border-color:#dce0e8!important;scrollbar-color:#bcc0cc #eff1f5}input,textarea,select,button{background:#e6e9ef!important;color:#4c4f69!important;border-color:#bcc0cc!important}div,section,article,main,aside,header,footer,nav{background-color:transparent!important}','blue') +
gpb('Rose Pine Dawn','html,body{background:#faf4ed!important;color:#575279!important}a{color:#907aa9!important}*{border-color:#dfdad9!important;scrollbar-color:#9893a5 #faf4ed}input,textarea,select,button{background:#fffaf3!important;color:#575279!important;border-color:#dfdad9!important}div,section,article,main,aside,header,footer,nav{background-color:transparent!important}','pink') +
gpb('Gruvbox Light','html,body{background:#fbf1c7!important;color:#3c3836!important}a{color:#458588!important}*{border-color:#d5c4a1!important;scrollbar-color:#bdae93 #fbf1c7}input,textarea,select,button{background:#ebdbb2!important;color:#3c3836!important;border-color:#bdae93!important}div,section,article,main,aside,header,footer,nav{background-color:transparent!important}','yellow') +
'</div></div>' +
/* ── GLOBAL: UTILITY ── */
'<div class="sc-preset-section"><div class="sc-preset-title"><svg viewBox="0 0 24 24"><path d="M14.7 6.3a1 1 0 000 1.4l1.6 1.6a1 1 0 001.4 0l3.77-3.77a6 6 0 01-7.94 7.94l-6.91 6.91a2.12 2.12 0 01-3-3l6.91-6.91a6 6 0 017.94-7.94l-3.76 3.76z"/></svg>Global Utilities (Full Page)</div>' +
'<div class="sc-preset-grid">' +
gpb('Remove All Ads','[class*="ad-"],[class*="Ad"],[class*="advert"],[id*="ad-"],[id*="Ad"],ins.adsbygoogle,[data-ad],iframe[src*="doubleclick"],iframe[src*="googlesyndication"]{display:none!important}','red') +
gpb('Remove Popups','[class*="popup"],[class*="modal"],[class*="overlay"],[class*="cookie"],[class*="consent"],[id*="popup"],[id*="modal"]{display:none!important}body{overflow:auto!important}','red') +
gpb('Remove Sticky Headers','header,[class*="header"],[class*="navbar"],[class*="nav-bar"],[class*="topbar"],[role="banner"]{position:relative!important;top:auto!important}','red') +
gpb('Remove Sidebars','aside,[class*="sidebar"],[role="complementary"],[class*="side-bar"]{display:none!important}main,[role="main"],[class*="content"],[class*="main"]{max-width:100%!important;width:100%!important}') +
gpb('Remove Footers','footer,[class*="footer"],[role="contentinfo"]{display:none!important}','red') +
gpb('Wider Content','main,[role="main"],article,.content,.post,.entry-content,.article-content{max-width:95vw!important;width:95vw!important;margin:0 auto!important}') +
gpb('Focus Mode','header,footer,aside,nav,[class*="sidebar"],[class*="header"],[class*="footer"],[class*="nav"],[role="banner"],[role="navigation"],[role="complementary"],[role="contentinfo"],.comments,.social{display:none!important}main,[role="main"],article{max-width:750px!important;margin:0 auto!important;padding:20px!important}','blue') +
gpb('Readable Text','*{font-size:clamp(16px,1.1em,22px)!important;line-height:1.7!important}p,li,td,span,div{max-width:75ch!important}','green') +
gpb('Page Grayscale','html{filter:grayscale(100%)!important}') +
gpb('Page Sepia','html{filter:sepia(40%)!important}','yellow') +
gpb('Page Invert','html{filter:invert(1) hue-rotate(180deg)!important}img,video,picture,svg,.emoji{filter:invert(1) hue-rotate(180deg)!important}') +
gpb('Force Dark (Invert)','html{filter:invert(0.9) hue-rotate(180deg)!important;background:#111!important}img,video,picture,canvas,svg,iframe,[style*="background-image"]{filter:invert(1) hue-rotate(180deg)!important}') +
gpb('Force Fonts: Sans','*{font-family:system-ui,-apple-system,"Segoe UI",Roboto,sans-serif!important}') +
gpb('Force Fonts: Serif','*{font-family:Georgia,"Times New Roman",serif!important}') +
gpb('Force Fonts: Mono','*{font-family:Consolas,Monaco,"Courier New",monospace!important}') +
gpb('Disable Animations','*,*::before,*::after{animation:none!important;transition:none!important}') +
gpb('Custom Scrollbar','*{scrollbar-width:thin!important;scrollbar-color:rgba(168,85,247,0.4) transparent!important}::-webkit-scrollbar{width:8px!important}::-webkit-scrollbar-track{background:transparent!important}::-webkit-scrollbar-thumb{background:rgba(168,85,247,0.4)!important;border-radius:4px!important}::-webkit-scrollbar-thumb:hover{background:rgba(168,85,247,0.6)!important}') +
gpb('Night Shift','html{filter:brightness(0.85) sepia(20%)!important}','yellow') +
gpb('High Contrast','html{filter:contrast(140%)!important}') +
'</div></div>';
// Wire up preset buttons
el.querySelectorAll('.sc-preset-btn[data-css]').forEach(btn => {
btn.addEventListener('click', () => {
const css = btn.dataset.css;
if (btn.dataset.global === '1') { applyGlobalCSS(css); }
else if (state.selector) { applyPresetCSS(css); }
else { toast('Select an element first'); }
});
});
// Wire up animation preset buttons
el.querySelectorAll('.sc-preset-btn[data-anim]').forEach(btn => {
btn.addEventListener('click', () => {
if (!state.selector) { toast('Select an element first'); return; }
const name = btn.dataset.anim;
const timing = btn.dataset.timing;
const frames = btn.dataset.frames;
const css = '@keyframes ' + name + '{' + frames + '}\n' + state.selector + '{animation:' + name + ' ' + timing + ' !important;}';
applyGlobalCSS(css);
});
});
}
function pb(label, css, color) {
const c = color ? ' ' + color : '';
return '<button class="sc-preset-btn' + c + '" data-css="' + escHTML(css) + '">' + escHTML(label) + '</button>';
}
function gpb(label, css, color) {
const c = color ? ' ' + color : '';
return '<button class="sc-preset-btn' + c + '" data-css="' + escHTML(css) + '" data-global="1">' + escHTML(label) + '</button>';
}
function apb(label, name, timing, frames, color) {
const c = color ? ' ' + color : '';
return '<button class="sc-preset-btn' + c + '" data-anim="' + escHTML(name) + '" data-timing="' + escHTML(timing) + '" data-frames="' + escHTML(frames) + '">' + escHTML(label) + '</button>';
}
/* ═══════ EDITOR OPEN/CLOSE ═══════ */
function openEditor() { state.open=true; panelHost.style.right='0'; document.documentElement.style.transition='margin-right 0.3s cubic-bezier(0.4,0,0.2,1)'; document.documentElement.style.marginRight=PANEL_WIDTH+'px'; loadStyles(); }
function closeEditor() { state.open=false; stopPicker(); stopPreview(); hidePersistentHighlight(); panelHost.style.right='-540px'; document.documentElement.style.marginRight='0'; setTimeout(()=>{document.documentElement.style.transition='';},300); }
function toggleEditor() { state.open ? closeEditor() : openEditor(); }
/* ═══════ PICKER ═══════ */
function togglePicker() { state.picking ? stopPicker() : startPicker(); }
function startPicker() { state.picking=true; refs.pickBtn.classList.add('active'); refs.quickPickBtn.classList.add('active'); document.addEventListener('mousemove',onPickerMove,true); document.addEventListener('click',onPickerClick,true); document.addEventListener('keydown',onPickerKey,true); document.body.style.cursor='crosshair'; }
function stopPicker() { state.picking=false; refs.pickBtn.classList.remove('active'); refs.quickPickBtn.classList.remove('active'); document.removeEventListener('mousemove',onPickerMove,true); document.removeEventListener('click',onPickerClick,true); document.removeEventListener('keydown',onPickerKey,true); document.body.style.cursor=''; highlightOverlay.style.display='none'; selectorLabel.style.display='none'; }
function onPickerMove(e) {
const el=document.elementFromPoint(e.clientX,e.clientY);
if(!el||el===panelHost||panelHost.contains(el)||el===highlightOverlay||el===selectorLabel||el===persistentHighlight) return;
const r=el.getBoundingClientRect();
Object.assign(highlightOverlay.style,{display:'block',left:r.left+'px',top:r.top+'px',width:r.width+'px',height:r.height+'px'});
const sel=generateBestSelector(el); selectorLabel.textContent=sel;
Object.assign(selectorLabel.style,{display:'block',left:Math.min(r.left,window.innerWidth-420)+'px',top:Math.max(0,r.top-26)+'px'});
}
function onPickerClick(e) {
e.preventDefault();e.stopPropagation();e.stopImmediatePropagation();
const el=document.elementFromPoint(e.clientX,e.clientY);
if(!el||el===panelHost||panelHost.contains(el)||el===persistentHighlight) return;
state.pickedElement=el; state.pickerAncestors=buildAncestorChain(el);
state.pickerDepth=0; state.pickerSpecificity=0;
refs.depthSlider.max=Math.max(0,state.pickerAncestors.length-1); refs.depthSlider.value=0; refs.depthVal.textContent='0';
rebuildFromSliders(); stopPicker();
showPersistentHighlight();
updateHideBtn();
populateVisualFromElement(getCurrentDepthElement());
if (state.activeTab !== 'selector') switchTab('selector');
}
function onPickerKey(e) { if(e.key==='Escape'){e.preventDefault();stopPicker();} }
function buildAncestorChain(el) { const c=[]; let cur=el; while(cur&&cur!==document.documentElement&&cur!==document){c.push(cur);cur=cur.parentElement;} return c; }
function rebuildFromSliders() {
const el = getCurrentDepthElement();
if(!el) return;
state.pickerCandidates=generateAllCandidates(el);
refs.specSlider.max=Math.max(0,state.pickerCandidates.length-1);
if(state.pickerSpecificity>=state.pickerCandidates.length){state.pickerSpecificity=0;refs.specSlider.value=0;refs.specVal.textContent='0';}
state.selector=state.pickerCandidates[state.pickerSpecificity]||'';
refs.selectorInput.value=state.selector;
showPersistentHighlight();
updateMatchCount(); renderFilterList(); updateHideBtn();
populateVisualFromElement(el);
}
function getCurrentDepthElement() { return state.pickerAncestors[state.pickerDepth]||state.pickedElement; }
function generateBestSelector(el) {
if(el.id) return '#'+CSS.escape(el.id);
const classes=[...el.classList].filter(c=>!c.startsWith('sc-')&&c.length<40);
if(classes.length) return el.tagName.toLowerCase()+'.'+classes.map(CSS.escape).join('.');
return el.tagName.toLowerCase();
}
function generateAllCandidates(el) {
const c = new Set();
if(el.id) c.add('#'+CSS.escape(el.id));
const tag=el.tagName.toLowerCase();
const classes=[...el.classList].filter(cl=>!cl.startsWith('sc-')&&cl.length<40);
c.add(tag);
classes.forEach(cl=>c.add('.'+CSS.escape(cl)));
classes.forEach(cl=>c.add(tag+'.'+CSS.escape(cl)));
if(classes.length>1) c.add(tag+'.'+classes.map(CSS.escape).join('.'));
const parent=el.parentElement;
if(parent){
const psel=generateBestSelector(parent);
c.add(psel+' > '+tag);
if(classes.length) c.add(psel+' > '+tag+'.'+CSS.escape(classes[0]));
const idx=[...parent.children].filter(ch=>ch.tagName===el.tagName).indexOf(el);
if(idx>=0) c.add(psel+' > '+tag+':nth-of-type('+(idx+1)+')');
}
const attrs=['role','type','name','data-testid','aria-label'];
attrs.forEach(a=>{const v=el.getAttribute(a);if(v&&v.length<50)c.add(tag+'['+a+'="'+CSS.escape(v)+'"]');});
return [...c];
}
function onSelectorChange() { state.selector=refs.selectorInput.value; updateMatchCount(); }
function updateMatchCount() { try{const n=document.querySelectorAll(state.selector).length;refs.matchCount.textContent=n+' match'+(n!==1?'es':'');}catch{refs.matchCount.textContent='Invalid selector';} updateQuickPickLabel(); }
function updateQuickPickLabel() { if(!refs.quickPickLabel) return; if(state.selector){refs.quickPickLabel.textContent=state.selector;refs.quickPickLabel.classList.add('has-sel');}else{refs.quickPickLabel.textContent='No element selected';refs.quickPickLabel.classList.remove('has-sel');} }
function updateHideBtn() {
const isHidden = state.hiddenElements.some(h=>h.selector===state.selector);
refs.hideBtn.textContent = isHidden ? 'Unhide' : 'Hide';
}
function renderFilterList() {
refs.filterList.innerHTML='';
state.pickerCandidates.forEach((sel,i)=>{
const item=document.createElement('div');
item.className='sc-filter-item'+(i===state.pickerSpecificity?' active':'');
item.innerHTML=`<span class="sc-filter-sel">${escHTML(sel)}</span><span class="sc-filter-badge">${countMatches(sel)}</span>`;
item.addEventListener('click',()=>{
state.pickerSpecificity=i;refs.specSlider.value=i;refs.specVal.textContent=i;
state.selector=sel;refs.selectorInput.value=sel;
updateMatchCount();renderFilterList();
});
refs.filterList.appendChild(item);
});
}
function countMatches(sel){try{return document.querySelectorAll(sel).length;}catch{return 0;}}
/* ═══════ PREVIEW ═══════ */
function togglePreview(){state.previewing=!state.previewing;refs.previewBtn.classList.toggle('active',state.previewing);if(state.previewing){applyLiveCSS();}else{removeLiveCSS();}}
function stopPreview(){if(state.previewing){state.previewing=false;refs.previewBtn.classList.remove('active');removeLiveCSS();}}
/* ═══════ CREATE RULE ═══════ */
function createFromSelector(){
if(!state.selector){toast('Pick an element first');return;}
pushUndo();
const rule = state.selector + ' {\n \n}';
state.customCSS = state.customCSS ? state.customCSS + '\n\n' + rule : rule;
refs.codeEditor.value=state.customCSS;
applyLiveCSS(); parseCSStoBasic(state.customCSS); saveCustomCSS(); updateLineNumbers();
switchTab('code');
setTimeout(()=>{
const pos=state.customCSS.lastIndexOf(state.selector+' {\n ');
if(pos>=0){refs.codeEditor.selectionStart=refs.codeEditor.selectionEnd=pos+state.selector.length+5;refs.codeEditor.focus();}
},50);
}
/* ═══════ VISUAL <-> CSS ═══════ */
function populateVisualFromElement(el) {
if(!el) return;
const cs = getComputedStyle(el);
refs.$$('.sc-prop-input').forEach(input => { input.value=''; });
refs.$$('.sc-select-input').forEach(sel => { sel.value=''; });
refs.$$('.sc-color-input').forEach(ci => {
const val=cs.getPropertyValue(ci.dataset.prop);
if(val){const hex=rgbToHex(val);if(hex)ci.value=hex;}
});
refs.$$('.sc-range-input').forEach(ri => {
const val=cs.getPropertyValue(ri.dataset.prop);
if(val){const num=parseFloat(val);if(!isNaN(num)){ri.value=num;ri.nextElementSibling.textContent=ri.dataset.unit?num+ri.dataset.unit:num;}}
});
state.basicProps={};
updateBoxModel(el);
}
function updateBoxModel(el, skipCell) {
if (!el) { clearBoxModel(); return; }
const cs = getComputedStyle(el);
const p = v => { const n = parseFloat(cs.getPropertyValue(v)); return isNaN(n) ? '-' : Math.round(n); };
const vals = {
mt: p('margin-top'), mr: p('margin-right'), mb: p('margin-bottom'), ml: p('margin-left'),
bt: p('border-top-width'), br: p('border-right-width'), bb: p('border-bottom-width'), bl: p('border-left-width'),
pt: p('padding-top'), pr: p('padding-right'), pb: p('padding-bottom'), pl: p('padding-left'),
w: Math.round(el.offsetWidth || parseFloat(cs.width) || 0),
h: Math.round(el.offsetHeight || parseFloat(cs.height) || 0)
};
for (const [k, v] of Object.entries(vals)) {
const cell = shadow.querySelector(`[data-bm="${k}"]`);
if (!cell || cell === skipCell || cell.querySelector('input')) continue;
cell.textContent = (v === 0 || v === '-') ? '-' : v;
}
const contentEl = shadow.querySelector('[data-bm="content"]');
if (contentEl && !contentEl.querySelector('input')) contentEl.textContent = vals.w + ' x ' + vals.h;
const dispEl = shadow.querySelector('[data-bm="display"]');
if (dispEl) dispEl.textContent = cs.display || '-';
const visEl = shadow.querySelector('[data-bm="visibility"]');
if (visEl) visEl.textContent = cs.display === 'none' ? 'Show' : 'Hide';
}
function clearBoxModel() {
shadow.querySelectorAll('[data-bm]').forEach(el => {
if (el.dataset.bm === 'content') el.textContent = '- x -';
else if (el.dataset.bm === 'display') el.textContent = '-';
else if (el.dataset.bm === 'visibility') el.textContent = 'Hide';
else el.textContent = '-';
});
}
const bmPropMap = {
mt:'margin-top',mr:'margin-right',mb:'margin-bottom',ml:'margin-left',
bt:'border-top-width',br:'border-right-width',bb:'border-bottom-width',bl:'border-left-width',
pt:'padding-top',pr:'padding-right',pb:'padding-bottom',pl:'padding-left'
};
function wireBoxModelEditing() {
const bmWrap = shadow.querySelector('.sc-bm-wrap');
if (!bmWrap) return;
bmWrap.addEventListener('click', (e) => {
const cell = e.target.closest('[data-bm]');
if (!cell || cell.querySelector('input')) return;
e.stopPropagation();
const key = cell.dataset.bm;
if (key === 'content') { editContentSize(cell); return; }
if (!bmPropMap[key]) return;
if (!state.selector) { toast('Pick an element first'); return; }
openBMEdit(cell, key);
});
}
function openBMEdit(cell, key) {
const current = cell.textContent.trim();
const num = (current === '-' || current === '') ? 0 : (parseInt(current) || 0);
cell.textContent = '';
const input = document.createElement('input');
input.className = 'sc-bm-edit';
input.type = 'number';
input.value = num;
input.setAttribute('step', '1');
cell.appendChild(input);
requestAnimationFrame(() => { input.focus(); input.select(); });
let lastApplied = num;
const liveApply = () => {
const v = parseInt(input.value);
if (isNaN(v) || v === lastApplied) return;
lastApplied = v;
state.basicProps[bmPropMap[key]] = v + 'px';
state.customCSS = basicToCSS();
refs.codeEditor.value = state.customCSS;
applyLiveCSS();
const el = getCurrentDepthElement();
if (el) updateBoxModel(el, cell);
};
input.addEventListener('input', liveApply);
let done = false;
const commit = () => {
if (done) return; done = true;
const v = parseInt(input.value);
if (isNaN(v) || v === 0) {
delete state.basicProps[bmPropMap[key]];
} else {
state.basicProps[bmPropMap[key]] = v + 'px';
}
pushUndo();
state.customCSS = basicToCSS();
refs.codeEditor.value = state.customCSS;
applyLiveCSS(); saveCustomCSS();
const el = getCurrentDepthElement();
if (el) updateBoxModel(el);
else cell.textContent = (v || 0) === 0 ? '-' : v;
};
input.addEventListener('blur', commit);
input.addEventListener('keydown', ev => {
ev.stopPropagation();
if (ev.key === 'Enter') { ev.preventDefault(); input.blur(); }
if (ev.key === 'Escape') { ev.preventDefault(); done = true; cell.textContent = current === '' ? '-' : current; delete state.basicProps[bmPropMap[key]]; state.customCSS = basicToCSS(); refs.codeEditor.value = state.customCSS; applyLiveCSS(); }
if (ev.key === 'ArrowUp' || ev.key === 'ArrowDown') {
ev.preventDefault();
const step = ev.shiftKey ? 10 : 1;
const cur = parseInt(input.value) || 0;
input.value = ev.key === 'ArrowUp' ? cur + step : cur - step;
liveApply();
}
});
}
function editContentSize(cell) {
if (!state.selector) { toast('Pick an element first'); return; }
const el = getCurrentDepthElement();
const cs = el ? getComputedStyle(el) : null;
const curW = cs ? Math.round(parseFloat(cs.width) || 0) : 0;
const curH = cs ? Math.round(parseFloat(cs.height) || 0) : 0;
cell.textContent = '';
cell.style.cssText += 'display:flex;gap:2px;align-items:center;justify-content:center;';
const wIn = document.createElement('input');
wIn.className = 'sc-bm-edit'; wIn.style.width = '36px'; wIn.type = 'number'; wIn.value = curW; wIn.placeholder = 'W';
const sep = document.createElement('span');
sep.textContent = 'x'; sep.style.cssText = 'font-size:9px;color:var(--sc-muted,#585b70);';
const hIn = document.createElement('input');
hIn.className = 'sc-bm-edit'; hIn.style.width = '36px'; hIn.type = 'number'; hIn.value = curH; hIn.placeholder = 'H';
cell.append(wIn, sep, hIn);
requestAnimationFrame(() => { wIn.focus(); wIn.select(); });
const liveApply = () => {
const w = parseInt(wIn.value), h = parseInt(hIn.value);
if (!isNaN(w)) state.basicProps['width'] = w + 'px';
if (!isNaN(h)) state.basicProps['height'] = h + 'px';
state.customCSS = basicToCSS();
refs.codeEditor.value = state.customCSS;
applyLiveCSS();
};
[wIn, hIn].forEach(inp => inp.addEventListener('input', liveApply));
let done = false;
const commit = () => {
if (done) return;
requestAnimationFrame(() => {
if (shadow.activeElement === wIn || shadow.activeElement === hIn) return;
done = true;
cell.style.display = ''; cell.style.gap = ''; cell.style.alignItems = ''; cell.style.justifyContent = '';
pushUndo(); saveCustomCSS();
if (el) updateBoxModel(el);
else cell.textContent = (wIn.value || curW) + ' x ' + (hIn.value || curH);
});
};
wIn.addEventListener('blur', commit);
hIn.addEventListener('blur', commit);
[wIn, hIn].forEach(inp => inp.addEventListener('keydown', ev => {
ev.stopPropagation();
if (ev.key === 'Enter') { ev.preventDefault(); inp.blur(); }
if (ev.key === 'Escape') { done = true; cell.style.display = ''; cell.textContent = curW + ' x ' + curH; }
if (ev.key === 'Tab') { ev.preventDefault(); (inp === wIn ? hIn : wIn).focus(); }
if (ev.key === 'ArrowUp' || ev.key === 'ArrowDown') {
ev.preventDefault();
const step = ev.shiftKey ? 10 : 1;
const cur = parseInt(inp.value) || 0;
inp.value = ev.key === 'ArrowUp' ? cur + step : cur - step;
liveApply();
}
}));
}
function basicToCSS() {
const lines = [];
const props = Object.entries(state.basicProps).filter(([,v])=>v);
if (props.length > 0 && state.selector) {
lines.push(state.selector + ' {');
props.forEach(([k,v]) => lines.push(' ' + k + ': ' + v + ';'));
lines.push('}');
}
// Preserve other rules not from the visual editor
const existing = state.customCSS;
if (existing) {
const stripped = existing.replace(new RegExp(escRegex(state.selector)+'\\s*\\{[^}]*\\}','g'),'').trim();
if (stripped) lines.unshift(stripped);
}
return lines.join('\n');
}
function parseCSStoBasic(css) {
state.basicProps={};
if(!state.selector||!css) return;
const re = new RegExp(escRegex(state.selector)+'\\s*\\{([^}]*)\\}');
const m = css.match(re);
if(!m) return;
m[1].split(';').forEach(decl => {
const [k,...vArr] = decl.split(':');
if(k&&vArr.length) state.basicProps[k.trim()] = vArr.join(':').trim();
});
}
function escRegex(s) { return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); }
/* ═══════ UNDO/REDO ═══════ */
function pushUndo() { state.undoStack.push(state.customCSS); if(state.undoStack.length>50)state.undoStack.shift(); state.redoStack=[]; }
function undo() { if(!state.undoStack.length)return; state.redoStack.push(state.customCSS); state.customCSS=state.undoStack.pop(); refs.codeEditor.value=state.customCSS; applyLiveCSS(); saveCustomCSS(); parseCSStoBasic(state.customCSS); updateLineNumbers(); }
function redo() { if(!state.redoStack.length)return; state.undoStack.push(state.customCSS); state.customCSS=state.redoStack.pop(); refs.codeEditor.value=state.customCSS; applyLiveCSS(); saveCustomCSS(); parseCSStoBasic(state.customCSS); updateLineNumbers(); }
/* ═══════ RESET ═══════ */
function resetStyles() { pushUndo(); state.customCSS=''; refs.codeEditor.value=''; applyLiveCSS(); saveCustomCSS(); parseCSStoBasic(''); updateLineNumbers(); toast('Custom CSS reset'); }
/* ═══════ READABILITY / GRAYSCALE ═══════ */
/* Enhanced Readability Mode */
const readThemes = {
dark: { bg: '#1a1a2e', text: '#e0e0e0', link: '#89b4fa' },
sepia: { bg: '#f4ecd8', text: '#5b4636', link: '#8b4513' },
light: { bg: '#ffffff', text: '#333333', link: '#1a73e8' },
oled: { bg: '#000000', text: '#cccccc', link: '#7aa2f7' }
};
let readSettings = { theme: 'dark', fontSize: 18, lineHeight: 1.7, fontFamily: 'Georgia, serif', maxWidth: 720 };
function buildReadabilityCSS() {
const t = readThemes[readSettings.theme] || readThemes.dark;
const s = readSettings;
return 'aside,nav,footer,.sidebar,.ad,.ads,.advertisement,[role="complementary"],[role="banner"],[role="navigation"],.social-share,.comments,.related-posts,iframe:not([src*="youtube"]):not([src*="vimeo"]){display:none!important}' +
'article,main,[role="main"],.post-content,.article-content,.entry-content,body>div>div{max-width:' + s.maxWidth + 'px!important;margin:0 auto!important;font-size:' + s.fontSize + 'px!important;line-height:' + s.lineHeight + '!important;color:' + t.text + '!important;font-family:' + s.fontFamily + '!important}' +
'a{color:' + t.link + '!important}' +
'body{background:' + t.bg + '!important}' +
'img,video,figure{max-width:100%!important;height:auto!important}' +
'h1,h2,h3,h4,h5,h6{color:' + t.text + '!important;font-family:' + s.fontFamily + '!important}';
}
function applyReadability() {
let el = document.getElementById('sc-readability-style');
if (state.readability) {
if (!el) { el = document.createElement('style'); el.id = 'sc-readability-style'; document.head.appendChild(el); }
el.textContent = buildReadabilityCSS();
} else if (el) el.remove();
}
function toggleReadability(newSettings) {
if (newSettings) Object.assign(readSettings, newSettings);
state.readability = !state.readability;
refs.readBtn.classList.toggle('active', state.readability);
applyReadability();
toast(state.readability ? 'Readability ON' : 'Readability OFF');
}
function updateReadSettings(newSettings) {
Object.assign(readSettings, newSettings);
if (state.readability) applyReadability();
}
function toggleGrayscale(){state.grayscale=!state.grayscale;refs.grayBtn.classList.toggle('active',state.grayscale);let el=document.getElementById('sc-grayscale-style');if(state.grayscale){if(!el){el=document.createElement('style');el.id='sc-grayscale-style';document.head.appendChild(el);}el.textContent='html{filter:grayscale(100%)!important}';}else if(el)el.remove();toast(state.grayscale?'Grayscale ON':'Grayscale OFF');}
/* ═══════ CODE EDITOR ═══════ */
function onCodeChange(){pushUndo();state.customCSS=refs.codeEditor.value;applyLiveCSS();parseCSStoBasic(state.customCSS);saveCustomCSS();updateLineNumbers();}
const pairs={'(':')','[':']','{':'}','"':'"',"'":"'"};
function onCodeKeydown(e){
if(e.key==='Tab'){e.preventDefault();const s=refs.codeEditor.selectionStart,end=refs.codeEditor.selectionEnd;refs.codeEditor.value=refs.codeEditor.value.substring(0,s)+' '+refs.codeEditor.value.substring(end);refs.codeEditor.selectionStart=refs.codeEditor.selectionEnd=s+2;onCodeChange();}
if(pairs[e.key]){const s=refs.codeEditor.selectionStart,end=refs.codeEditor.selectionEnd;if(s!==end){e.preventDefault();const sel=refs.codeEditor.value.substring(s,end);refs.codeEditor.value=refs.codeEditor.value.substring(0,s)+e.key+sel+pairs[e.key]+refs.codeEditor.value.substring(end);refs.codeEditor.selectionStart=s+1;refs.codeEditor.selectionEnd=end+1;onCodeChange();}}
if(e.key==='Enter'){const pos=refs.codeEditor.selectionStart;if(refs.codeEditor.value[pos-1]==='{'&&refs.codeEditor.value[pos]==='}'){e.preventDefault();const indent=getLineIndent(refs.codeEditor.value,pos),ins='\n'+indent+' \n'+indent;refs.codeEditor.value=refs.codeEditor.value.substring(0,pos)+ins+refs.codeEditor.value.substring(pos);refs.codeEditor.selectionStart=refs.codeEditor.selectionEnd=pos+indent.length+3;onCodeChange();}}
}
function getLineIndent(text,pos){const lineStart=text.lastIndexOf('\n',pos-1)+1;const line=text.substring(lineStart,pos);const m=line.match(/^(\s*)/);return m?m[1]:'';}
function syncScroll(){const ln=shadow.querySelector('#sc-line-numbers');if(ln&&refs.codeEditor)ln.scrollTop=refs.codeEditor.scrollTop;}
function updateLineNumbers(){const ln=shadow.querySelector('#sc-line-numbers');if(!ln)return;const lines=(refs.codeEditor?.value||'').split('\n').length;ln.innerHTML=Array.from({length:Math.max(lines,20)},(_,i)=>'<div class="sc-ln">'+(i+1)+'</div>').join('');}
/* ═══════ THEMES TAB ═══════ */
function renderThemeList() {
const list = refs.themeList;
if (!list) return;
const ids = Object.keys(state.themes);
if (ids.length === 0) {
list.innerHTML = '<div class="sc-themes-empty">No themes installed. Use the popup to browse and install themes from UserStyles.world.</div>';
return;
}
list.innerHTML = '';
ids.forEach(id => {
const t = state.themes[id];
const item = document.createElement('div');
item.className = 'sc-theme-item' + (t.enabled !== false ? ' enabled' : '');
item.innerHTML = `
<div class="sc-theme-row">
<span class="sc-theme-name">${escHTML(t.name||'Theme #'+id)}</span>
<label class="sc-toggle sc-theme-toggle"><input type="checkbox" ${t.enabled!==false?'checked':''}/><span class="sc-toggle-sl"></span></label>
</div>
<div class="sc-theme-actions">
<button class="sc-theme-btn edit">Edit CSS</button>
<button class="sc-theme-btn uninstall">Uninstall</button>
</div>
<div class="sc-theme-editor" style="display:none">
<textarea class="sc-theme-textarea" spellcheck="false"></textarea>
<div class="sc-theme-editor-actions">
<button class="sc-theme-btn save">Save</button>
<button class="sc-theme-btn cancel">Cancel</button>
</div>
</div>`;
item.querySelector('input[type="checkbox"]').addEventListener('change', (e) => {
state.themes[id].enabled = e.target.checked;
item.classList.toggle('enabled', e.target.checked);
saveThemeToggle(id, e.target.checked);
applyLiveCSS();
});
const editBtn = item.querySelector('.edit');
const editorDiv = item.querySelector('.sc-theme-editor');
const textarea = item.querySelector('.sc-theme-textarea');
editBtn.addEventListener('click', () => {
const showing = editorDiv.style.display !== 'none';