-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCodeMirror6V2Final.html
More file actions
866 lines (795 loc) · 33.3 KB
/
Copy pathCodeMirror6V2Final.html
File metadata and controls
866 lines (795 loc) · 33.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Filter Editor — BlazeFTL</title>
<script type="importmap">
{
"imports": {
"@codemirror/state": "https://esm.sh/@codemirror/state@6.4.1?bundle",
"@codemirror/view": "https://esm.sh/@codemirror/view@6.26.3?bundle&external=@codemirror/state",
"@codemirror/commands": "https://esm.sh/@codemirror/commands@6.3.3?bundle&external=@codemirror/state,@codemirror/view",
"@codemirror/search": "https://esm.sh/@codemirror/search@6.5.6?bundle&external=@codemirror/state,@codemirror/view,@codemirror/commands",
"@codemirror/language": "https://esm.sh/@codemirror/language@6.10.1?bundle&external=@codemirror/state,@codemirror/view"
}
}
</script>
<style>
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&family=Roboto+Mono:wght@400;500&display=swap');
:root {
--bg:#FAFAFA; --surface:#FFFFFF; --surface2:#F5F5F5;
--border:#E0E0E0; --border2:#BDBDBD;
--primary:#1565C0; --primary-light:#E3F2FD; --primary-dark:#0D47A1;
--warn:#F57F17; --danger:#C62828; --success:#2E7D32;
--text:#212121; --text2:#757575; --text3:#BDBDBD;
--shadow:0 1px 3px rgba(0,0,0,0.14); --shadow2:0 2px 8px rgba(0,0,0,0.18);
--fn:13px; --lh:21px;
--c-comment:#6A737D; --c-title:#005CC5; --c-except:#B31D28;
--c-network:#005CC5; --c-cosmetic:#22863A; --c-scriptlet:#6F42C1;
--c-domain:#E36209; --c-option:#032F62; --c-plain:#24292E;
}
* { box-sizing:border-box; margin:0; padding:0; -webkit-tap-highlight-color:transparent; }
html,body { height:100%; overflow:hidden; }
body { background:var(--bg); color:var(--text); font-family:'Roboto',sans-serif; display:flex; flex-direction:column; }
/* ── TOP BAR ─────────────────────────────────────────── */
#topBar {
flex-shrink:0; background:var(--primary); color:white;
padding:0 10px 0 14px; height:52px;
display:flex; align-items:center; justify-content:space-between;
box-shadow:var(--shadow2); z-index:100; gap:8px;
}
.app-info { flex:1; min-width:0; }
.app-title { font-size:16px; font-weight:500; }
.app-file { font-size:10px; opacity:0.7; font-family:'Roboto Mono',monospace;
white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
.top-right { display:flex; align-items:center; gap:6px; flex-shrink:0; }
#statusChip {
display:flex; align-items:center; gap:5px;
background:rgba(255,255,255,0.18);
border-radius:12px; padding:4px 10px; font-size:11px; white-space:nowrap;
}
#sDot { width:7px;height:7px;border-radius:50%;background:rgba(255,255,255,0.35);transition:background 0.3s; }
#sDot.ok { background:#69F0AE; }
#sDot.err { background:#FF5252; }
#sDot.loading { background:#FFD740; animation:blink 0.8s infinite; }
@keyframes blink{0%,100%{opacity:1}50%{opacity:0.2}}
#patTopBtn {
display:flex; align-items:center; gap:5px;
background:rgba(255,255,255,0.15); border:none; color:white;
border-radius:8px; padding:5px 10px; font-family:'Roboto',sans-serif;
font-size:12px; font-weight:500; cursor:pointer; white-space:nowrap;
}
#patTopBtn:active { opacity:0.7; }
#patDot { width:10px;height:10px;border-radius:50%;background:#FF5252;flex-shrink:0;transition:background 0.3s; }
#patDot.set { background:#69F0AE; }
/* ── TOOLBAR ─────────────────────────────────────────── */
#toolbar {
flex-shrink:0; background:var(--surface);
border-bottom:2px solid var(--border);
padding:5px 8px; display:flex; gap:4px; flex-wrap:wrap; align-items:center;
}
.btn {
font-family:'Roboto',sans-serif; font-size:12px; font-weight:500;
padding:6px 10px; border-radius:4px; border:none; cursor:pointer;
white-space:nowrap; letter-spacing:0.3px; text-transform:uppercase;
transition:background 0.12s; min-height:32px;
display:inline-flex; align-items:center; gap:4px;
}
.btn:active { opacity:0.75; transform:scale(0.96); }
.btn-flat { background:transparent; color:var(--primary); }
.btn-flat:hover { background:var(--primary-light); }
.btn-raised { background:var(--primary); color:white; box-shadow:var(--shadow); }
.btn-green { background:#388E3C; color:white; box-shadow:var(--shadow); }
.btn:disabled { opacity:0.3; pointer-events:none; }
#modBadge {
display:none; font-size:10px; font-weight:700;
background:#FF8F00; color:white;
border-radius:10px; padding:2px 8px; letter-spacing:0.5px;
}
#modBadge.show { display:inline-block; }
/* ── SEARCH PANEL (custom, top-anchored, Material) ────── */
#searchPanel {
display:none; flex-shrink:0;
background:#FFFFFF;
border-bottom:2px solid var(--primary);
padding:8px 10px;
box-shadow:0 2px 8px rgba(21,101,192,0.12);
z-index:90;
flex-direction:column; gap:6px;
}
#searchPanel.open { display:flex; }
.sp-row { display:flex; gap:6px; align-items:center; }
.sp-field {
flex:1; position:relative; display:flex; align-items:center;
}
.sp-field input {
width:100%; font-family:'Roboto Mono',monospace; font-size:13px;
padding:8px 70px 8px 12px;
border:1.5px solid var(--border2); border-radius:6px;
background:var(--surface2); color:var(--text); outline:none;
transition:border-color 0.15s, box-shadow 0.15s;
}
.sp-field input:focus {
border-color:var(--primary);
box-shadow:0 0 0 3px rgba(21,101,192,0.12);
background:#fff;
}
.sp-field input::placeholder { color:var(--text3); }
.sp-match-count {
position:absolute; right:8px;
font-size:11px; font-weight:600; color:var(--primary);
pointer-events:none; white-space:nowrap;
}
.sp-toggles { display:flex; gap:2px; position:absolute; right:8px; }
.sp-tog {
font-family:'Roboto Mono',monospace; font-size:10px; font-weight:700;
padding:3px 6px; border-radius:3px; border:1px solid var(--border);
background:transparent; color:var(--text2); cursor:pointer;
transition:all 0.12s; line-height:1;
}
.sp-tog.on { background:var(--primary); border-color:var(--primary); color:white; }
.sp-nav-btns { display:flex; gap:4px; flex-shrink:0; }
.sp-nav-btn {
width:32px; height:32px; border-radius:6px; border:1.5px solid var(--border2);
background:var(--surface2); color:var(--primary); font-size:16px;
cursor:pointer; display:flex; align-items:center; justify-content:center;
transition:all 0.12s; font-weight:700;
}
.sp-nav-btn:active { background:var(--primary-light); border-color:var(--primary); }
.sp-close-btn {
width:32px; height:32px; border-radius:6px; border:none;
background:transparent; color:var(--text2); font-size:18px;
cursor:pointer; display:flex; align-items:center; justify-content:center;
flex-shrink:0;
}
.sp-close-btn:active { background:var(--surface2); }
.sp-replace-row { display:flex; gap:6px; align-items:center; }
.sp-replace-row input {
flex:1; font-family:'Roboto Mono',monospace; font-size:13px;
padding:8px 12px;
border:1.5px solid var(--border2); border-radius:6px;
background:var(--surface2); color:var(--text); outline:none;
transition:border-color 0.15s;
}
.sp-replace-row input:focus { border-color:#388E3C; box-shadow:0 0 0 3px rgba(56,142,60,0.12); background:#fff; }
.sp-rep-btn {
font-family:'Roboto',sans-serif; font-size:11px; font-weight:500;
padding:6px 10px; border-radius:6px; border:1.5px solid var(--border2);
background:var(--surface2); color:#388E3C; cursor:pointer;
white-space:nowrap; text-transform:uppercase; letter-spacing:0.3px;
transition:all 0.12s;
}
.sp-rep-btn:active { background:#E8F5E9; border-color:#388E3C; }
#spToggleReplace {
font-size:11px; font-weight:500; color:var(--text2);
background:none; border:none; cursor:pointer; padding:0 4px;
white-space:nowrap; letter-spacing:0.3px; text-transform:uppercase;
font-family:'Roboto',sans-serif;
}
#spToggleReplace:active { color:var(--primary); }
/* ── EDITOR AREA ─────────────────────────────────────── */
#editorArea { flex:1; overflow:hidden; position:relative; }
#cmHost {
width:100%; height:100%;
overflow:auto;
font-family:'Roboto Mono',monospace;
font-size:var(--fn);
}
/* ── CodeMirror 6 theme overrides ───────────────────── */
.cm-editor {
height:100%;
background:var(--surface) !important;
font-family:'Roboto Mono',monospace !important;
font-size:var(--fn) !important;
}
.cm-editor.cm-focused { outline:none !important; }
.cm-scroller { overflow:auto !important; }
.cm-content { padding:8px 12px 250px 8px !important; }
.cm-lineNumbers .cm-gutterElement {
font-family:'Roboto Mono',monospace;
font-size:var(--fn); color:var(--text3);
padding:0 6px 0 8px; min-width:40px;
}
.cm-gutters {
background:var(--surface2) !important;
border-right:1px solid var(--border) !important;
color:var(--text3);
}
.cm-activeLine { background:rgba(21,101,192,0.05) !important; }
.cm-activeLineGutter { background:rgba(21,101,192,0.08) !important; }
.cm-selectionBackground,
.cm-focused .cm-selectionBackground { background:rgba(21,101,192,0.2) !important; }
.cm-cursor { border-left-color:var(--primary) !important; }
.cm-searchMatch { background:#FFF176 !important; border-radius:2px; }
.cm-searchMatch-selected { background:#FFD740 !important; outline:2px solid #F57F17; }
/* Hide CM6's own built-in search panel — we use our custom one */
.cm-search { display:none !important; }
/* ── uBO syntax token classes ───────────────────────── */
.ub-comment { color:var(--c-comment); font-style:italic; }
.ub-title { color:var(--c-title); font-weight:500; }
.ub-except { color:var(--c-except); }
.ub-network { color:var(--c-network); }
.ub-cosmetic { color:var(--c-cosmetic); }
.ub-scriptlet{ color:var(--c-scriptlet); }
.ub-domain { color:var(--c-domain); }
.ub-option { color:var(--c-option); }
.ub-plain { color:var(--c-plain); }
/* ── COMMIT BAR ──────────────────────────────────────── */
#commitBar {
display:none; position:fixed; left:0; right:0;
background:var(--surface); border-top:2px solid #388E3C;
padding:10px; gap:8px; align-items:center;
box-shadow:0 -2px 8px rgba(0,0,0,0.12); z-index:150;
}
#commitBar.show { display:flex; }
#commitMsg {
flex:1; font-family:'Roboto',sans-serif; font-size:15px;
padding:12px 14px; border:1px solid var(--border2); border-radius:6px;
outline:none; color:var(--text); background:var(--surface); min-height:48px;
}
#commitMsg:focus { border-color:#388E3C; box-shadow:0 0 0 2px #C8E6C9; }
/* ── PAT SHEET ───────────────────────────────────────── */
#patModal {
display:none; position:fixed; inset:0;
background:rgba(0,0,0,0.45); z-index:200;
align-items:flex-end; justify-content:center;
}
#patModal.show { display:flex; }
.modal-sheet {
background:white; border-radius:16px 16px 0 0;
padding:22px 20px 36px; width:100%; max-width:520px;
}
.modal-sheet h2 { font-size:16px; font-weight:500; margin-bottom:6px; }
.modal-sheet p { font-size:12px; color:var(--text2); margin-bottom:14px; line-height:1.5; }
.modal-sheet input {
width:100%; font-family:'Roboto Mono',monospace; font-size:13px;
padding:10px 12px; border:1px solid var(--border2); border-radius:4px;
outline:none; margin-bottom:14px; background:var(--surface2); color:var(--text);
}
.modal-sheet input:focus { border-color:var(--primary); }
.modal-actions { display:flex; gap:8px; justify-content:flex-end; }
/* ── TOAST ───────────────────────────────────────────── */
#toast {
position:fixed; bottom:20px; left:50%;
transform:translateX(-50%) translateY(64px);
background:#323232; color:white; border-radius:4px;
padding:10px 18px; font-size:13px; font-weight:500;
transition:transform 0.22s ease; z-index:400;
white-space:nowrap; box-shadow:var(--shadow2); pointer-events:none;
}
#toast.show { transform:translateX(-50%) translateY(0); }
</style>
</head>
<body>
<div id="topBar">
<div class="app-info">
<div class="app-title">Filter Editor</div>
<div class="app-file">My-Filters_Static_Sites.txt</div>
</div>
<div class="top-right">
<div id="statusChip"><div id="sDot"></div><span id="sText">Not loaded</span></div>
<button id="patTopBtn" onclick="showPat()">
<div id="patDot"></div> PAT
</button>
</div>
</div>
<div id="toolbar">
<button class="btn btn-raised" onclick="loadFile()">⬇ Load</button>
<button class="btn btn-green" id="saveBtn" onclick="showCommit()" disabled>⬆ Save</button>
<button class="btn btn-flat" onclick="openSearchPanel()">🔍 Find</button>
<button class="btn btn-flat" onclick="pasteToEditor()">📋 Paste</button>
<button class="btn btn-flat" onclick="copySelection()">⎘ Copy</button>
<button class="btn btn-flat" onclick="goToLine()"># Line</button>
<span id="modBadge">UNSAVED</span>
</div>
<div id="searchPanel">
<div class="sp-row">
<div class="sp-field">
<input id="spFind" type="text" placeholder="Find…" oninput="spSearch()" onkeydown="spKey(event)" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" />
<div class="sp-toggles">
<button class="sp-tog" id="togCase" title="Match case" onclick="spToggle('case')">Aa</button>
<button class="sp-tog" id="togWord" title="Whole word" onclick="spToggle('word')">W</button>
<button class="sp-tog" id="togRe" title="Regex" onclick="spToggle('re')">.*</button>
</div>
</div>
<div class="sp-nav-btns">
<button class="sp-nav-btn" title="Previous (Shift+Enter)" onclick="spPrev()">↑</button>
<button class="sp-nav-btn" title="Next (Enter)" onclick="spNext()">↓</button>
</div>
<span id="spCount" style="font-size:11px;font-weight:600;color:var(--primary);white-space:nowrap;min-width:52px;text-align:right"></span>
<button id="spToggleReplace" onclick="spToggleReplaceRow()">Replace</button>
<button class="sp-close-btn" onclick="closeSearchPanel()">✕</button>
</div>
<div class="sp-replace-row" id="spReplaceRow" style="display:none">
<input id="spReplace" type="text" placeholder="Replace with…" onkeydown="spRepKey(event)" autocomplete="off" spellcheck="false" />
<button class="sp-rep-btn" onclick="spReplaceOne()">Replace</button>
<button class="sp-rep-btn" onclick="spReplaceAll()">All</button>
</div>
</div>
<div id="editorArea">
<div id="cmHost"></div>
</div>
<div id="commitBar">
<input id="commitMsg" type="text" placeholder="Commit message..." value="Update My-Filters" />
<button class="btn btn-green" style="min-height:48px;font-size:14px;padding:10px 16px" onclick="saveFile()">✔ Commit</button>
<button class="btn btn-flat" style="min-height:48px;font-size:13px;color:#C62828" onclick="hideCommit()">Cancel ✕</button>
</div>
<div id="patModal">
<div class="modal-sheet">
<h2>GitHub Token (PAT)</h2>
<p>Required for saving only. Needs <b>repo</b> scope.<br>Stored in your browser — never committed to GitHub.</p>
<input type="password" id="patInput" placeholder="ghp_xxxxxxxxxxxxxxxxxxxx" />
<div class="modal-actions">
<button class="btn btn-flat" onclick="closePat()">Cancel</button>
<button class="btn btn-raised" onclick="savePat()">Save Token</button>
</div>
</div>
</div>
<div id="toast"></div>
<script type="module">
import { EditorState } from '@codemirror/state';
import {
EditorView, lineNumbers, highlightActiveLine,
highlightActiveLineGutter, drawSelection,
keymap, ViewPlugin, Decoration,
rectangularSelection, crosshairCursor,
highlightSpecialChars, dropCursor
} from '@codemirror/view';
import {
defaultKeymap, history, historyKeymap, indentWithTab,
selectAll, deleteLine, moveLineUp, moveLineDown,
copyLineUp, copyLineDown,
cursorLineBoundaryForward, cursorLineBoundaryBackward
} from '@codemirror/commands';
import {
search, searchKeymap,
SearchQuery, setSearchQuery,
findNext, findPrevious,
replaceNext, replaceAll as cmReplaceAll,
openSearchPanel as cmOpenPanel, closeSearchPanel as cmClosePanel,
getSearchQuery, selectNextOccurrence
} from '@codemirror/search';
import { HighlightStyle, syntaxHighlighting } from '@codemirror/language';
// ── GitHub config ──────────────────────────────────────
const OWNER = 'BlazeFTL', REPO = 'My-Filters';
const FILE = 'My-Filters_Static_Sites.txt';
const RAW = `https://raw.githubusercontent.com/${OWNER}/${REPO}/refs/heads/master/${FILE}`;
const API = `https://api.github.com/repos/${OWNER}/${REPO}/contents/${FILE}`;
let fileSha = null, originalContent = '';
// ── PAT helpers ───────────────────────────────────────
function getPat() { return localStorage.getItem('blaze_pat') || ''; }
function updatePatIndicator() {
document.getElementById('patDot').className = getPat() ? 'set' : '';
}
window.showPat = function() {
document.getElementById('patModal').classList.add('show');
document.getElementById('patInput').value = getPat();
};
window.closePat = function() { document.getElementById('patModal').classList.remove('show'); };
window.savePat = function() {
const v = document.getElementById('patInput').value.trim();
if (v) { localStorage.setItem('blaze_pat', v); toast('Token saved'); }
else { localStorage.removeItem('blaze_pat'); toast('Token cleared'); }
updatePatIndicator();
closePat();
};
// ── uBO Syntax Highlighter ────────────────────────────
const uboHighlighter = ViewPlugin.fromClass(
class {
constructor(view) { this.decorations = buildDecos(view); }
update(u) {
if (u.docChanged || u.viewportChanged) this.decorations = buildDecos(u.view);
}
},
{ decorations: v => v.decorations }
);
function buildDecos(view) {
const builder = [];
const { from: vpFrom, to: vpTo } = view.viewport;
const doc = view.state.doc;
for (let pos = vpFrom; pos <= vpTo; ) {
const line = doc.lineAt(pos);
addLineDecos(builder, line.from, line.text);
pos = line.to + 1;
}
builder.sort((a, b) => a.from - b.from || a.startSide - b.startSide);
return Decoration.set(builder, true);
}
function mark(cls) { return Decoration.mark({ class: cls }); }
function span(builder, from, to, cls) {
if (from < to) builder.push(mark(cls).range(from, to));
}
function addLineDecos(builder, base, text) {
if (!text.trim()) return;
if (/^[!#]/.test(text)) {
if (/^!\s*(Title|Version|Last modified|Expires|Description|License|Homepage|Forums):/i.test(text)) {
const m = text.match(/^(!\s*[^:]+:)(.*)/);
if (m) {
span(builder, base, base + m[1].length, 'ub-title');
span(builder, base + m[1].length, base + text.length, 'ub-comment');
return;
}
}
span(builder, base, base + text.length, 'ub-comment');
return;
}
if (text.startsWith('@@')) {
span(builder, base, base + 2, 'ub-except');
addNetworkDecos(builder, base + 2, text.slice(2));
return;
}
const htmlIdx = text.indexOf('##^');
if (htmlIdx > 0) {
span(builder, base, base + htmlIdx, 'ub-domain');
span(builder, base + htmlIdx, base + htmlIdx + 3, 'ub-cosmetic');
span(builder, base + htmlIdx + 3, base + text.length, 'ub-scriptlet');
return;
}
const scriptletRe = /^(.+?)(#[@+]?#\+js\(|#\+js\()(.*)/;
const sm = text.match(scriptletRe);
if (sm) {
span(builder, base, base + sm[1].length, 'ub-domain');
span(builder, base + sm[1].length, base + sm[1].length + sm[2].length, 'ub-cosmetic');
span(builder, base + sm[1].length + sm[2].length, base + text.length, 'ub-scriptlet');
return;
}
const cosmeticRe = /^(.+?)(#@?#)(.*)/;
const cm_ = text.match(cosmeticRe);
if (cm_) {
span(builder, base, base + cm_[1].length, 'ub-domain');
span(builder, base + cm_[1].length, base + text.length, 'ub-cosmetic');
return;
}
if (/^\|\||^\*|^\^/.test(text) || /\$[a-z]/.test(text)) {
addNetworkDecos(builder, base, text);
return;
}
span(builder, base, base + text.length, 'ub-plain');
}
function addNetworkDecos(builder, base, text) {
const i = text.lastIndexOf('$');
if (i > 0 && !/^https?:\/\//.test(text)) {
span(builder, base, base + i, 'ub-network');
span(builder, base + i, base + text.length, 'ub-option');
} else {
span(builder, base, base + text.length, 'ub-network');
}
}
// ── scrollMatchToCenter: scrolls CM6 so the found position
// sits at ~35% from top — visible above the on-screen keyboard.
function scrollMatchToCenter(pos) {
view.dispatch({
effects: EditorView.scrollIntoView(pos, { y: 'center', yMargin: 80 }),
});
}
// ── Build the editor ──────────────────────────────────
const updateListener = EditorView.updateListener.of(u => {
if (u.docChanged) {
const cur = u.state.doc.toString();
document.getElementById('modBadge').classList.toggle('show', cur !== originalContent);
if (document.getElementById('searchPanel').classList.contains('open')) {
updateMatchCount();
}
}
});
const view = new EditorView({
state: EditorState.create({
doc: '',
extensions: [
lineNumbers(),
highlightActiveLine(),
highlightActiveLineGutter(),
highlightSpecialChars(),
drawSelection(),
dropCursor(),
rectangularSelection(),
crosshairCursor(),
history(),
search({ top: true }),
keymap.of([
...defaultKeymap,
...historyKeymap,
...searchKeymap,
indentWithTab,
{ key: 'Mod-d', run: selectNextOccurrence },
{ key: 'Ctrl-l', run: view => { goToLine(); return true; } },
{ key: 'Alt-ArrowUp', run: moveLineUp },
{ key: 'Alt-ArrowDown', run: moveLineDown },
{ key: 'Shift-Alt-ArrowUp', run: copyLineUp },
{ key: 'Shift-Alt-ArrowDown', run: copyLineDown },
{ key: 'Mod-Shift-k', run: deleteLine },
{ key: 'Escape', run: view => { closeSearchPanel(); return false; } },
{ key: 'Mod-f', run: view => { openSearchPanel(); return true; } },
{ key: 'Mod-h', run: view => { openSearchPanel(true); return true; } },
]),
EditorView.lineWrapping,
uboHighlighter,
updateListener,
EditorView.theme({
'&': { height: '100%', background: 'var(--surface)' },
'.cm-scroller': { fontFamily: "'Roboto Mono',monospace", fontSize: 'var(--fn)' },
}),
],
}),
parent: document.getElementById('cmHost'),
});
window._view = view;
// ── Custom Search Panel Logic ─────────────────────────
let spState = { caseSensitive: false, wholeWord: false, regexp: false, replaceVisible: false };
window.openSearchPanel = function(withReplace = false) {
const panel = document.getElementById('searchPanel');
panel.classList.add('open');
if (withReplace) {
spState.replaceVisible = true;
document.getElementById('spReplaceRow').style.display = 'flex';
}
const sel = view.state.sliceDoc(
view.state.selection.main.from,
view.state.selection.main.to
);
const findEl = document.getElementById('spFind');
if (sel && sel.length < 200 && !sel.includes('\n')) {
findEl.value = sel;
}
setTimeout(() => { findEl.focus(); findEl.select(); }, 30);
spSearch();
};
window.closeSearchPanel = function() {
document.getElementById('searchPanel').classList.remove('open');
document.getElementById('spCount').textContent = '';
view.focus();
};
window.spToggleReplaceRow = function() {
spState.replaceVisible = !spState.replaceVisible;
document.getElementById('spReplaceRow').style.display = spState.replaceVisible ? 'flex' : 'none';
if (spState.replaceVisible) document.getElementById('spReplace').focus();
};
window.spToggle = function(type) {
if (type === 'case') spState.caseSensitive = !spState.caseSensitive;
if (type === 'word') spState.wholeWord = !spState.wholeWord;
if (type === 're') spState.regexp = !spState.regexp;
document.getElementById('togCase').classList.toggle('on', spState.caseSensitive);
document.getElementById('togWord').classList.toggle('on', spState.wholeWord);
document.getElementById('togRe').classList.toggle('on', spState.regexp);
spSearch();
};
function buildSearchQuery(searchStr, replaceStr = '') {
return new SearchQuery({
search: searchStr,
replace: replaceStr,
caseSensitive: spState.caseSensitive,
wholeWord: spState.wholeWord,
regexp: spState.regexp,
});
}
// Count matches and return position of first match (or -1)
function countMatchesAndFirst(q) {
try {
const query = buildSearchQuery(q);
if (!query.valid) return { count: 0, firstPos: -1 };
const cursor = query.getCursor(view.state.doc);
let count = 0, firstPos = -1;
while (!cursor.next().done) {
if (count === 0) firstPos = cursor.value.from;
count++;
}
return { count, firstPos };
} catch(e) {
return { count: 0, firstPos: -1 };
}
}
function updateMatchCount() {
const q = document.getElementById('spFind').value;
if (!q) { document.getElementById('spCount').textContent = ''; return; }
const { count } = countMatchesAndFirst(q);
document.getElementById('spCount').textContent = count === 0 ? 'No matches' : count + ' matches';
}
window.spSearch = function() {
const q = document.getElementById('spFind').value;
if (!q) {
document.getElementById('spCount').textContent = '';
view.dispatch({ effects: setSearchQuery.of(buildSearchQuery('')) });
return;
}
try {
const query = buildSearchQuery(q);
view.dispatch({ effects: setSearchQuery.of(query) });
// Immediately scroll to + highlight first match as user types
const { count, firstPos } = countMatchesAndFirst(q);
document.getElementById('spCount').textContent = count === 0 ? 'No matches' : count + ' matches';
if (firstPos >= 0) {
scrollMatchToCenter(firstPos);
}
} catch(e) {}
};
window.spNext = function() {
const q = document.getElementById('spFind').value;
if (!q) return;
view.dispatch({ effects: setSearchQuery.of(buildSearchQuery(q)) });
findNext(view);
// After CM6 moves selection, scroll the new cursor pos to center
requestAnimationFrame(() => {
const pos = view.state.selection.main.from;
scrollMatchToCenter(pos);
setTimeout(() => { document.getElementById('spFind').focus(); }, 30);
});
};
window.spPrev = function() {
const q = document.getElementById('spFind').value;
if (!q) return;
view.dispatch({ effects: setSearchQuery.of(buildSearchQuery(q)) });
findPrevious(view);
requestAnimationFrame(() => {
const pos = view.state.selection.main.from;
scrollMatchToCenter(pos);
setTimeout(() => { document.getElementById('spFind').focus(); }, 30);
});
};
window.spReplaceOne = function() {
const q = document.getElementById('spFind').value;
const r = document.getElementById('spReplace').value;
if (!q) return;
view.dispatch({ effects: setSearchQuery.of(buildSearchQuery(q, r)) });
replaceNext(view);
updateMatchCount();
};
window.spReplaceAll = function() {
const q = document.getElementById('spFind').value;
const r = document.getElementById('spReplace').value;
if (!q) return;
view.dispatch({ effects: setSearchQuery.of(buildSearchQuery(q, r)) });
const result = cmReplaceAll(view);
if (result) toast('Replaced all occurrences');
updateMatchCount();
};
window.spKey = function(e) {
if (e.key === 'Enter') { e.shiftKey ? spPrev() : spNext(); e.preventDefault(); }
if (e.key === 'Escape') { closeSearchPanel(); e.preventDefault(); }
};
window.spRepKey = function(e) {
if (e.key === 'Enter') { spReplaceOne(); e.preventDefault(); }
if (e.key === 'Escape') { closeSearchPanel(); e.preventDefault(); }
};
// ── Toolbar: Go to line ───────────────────────────────
window.goToLine = function() {
const total = view.state.doc.lines;
const cur = view.state.doc.lineAt(view.state.selection.main.head).number;
const n = prompt(`Go to line (1–${total}):`, cur);
if (!n || isNaN(n)) return;
const lineNum = Math.max(1, Math.min(parseInt(n), total));
const line = view.state.doc.line(lineNum);
view.dispatch({
selection: { anchor: line.from, head: line.to },
scrollIntoView: true,
effects: EditorView.scrollIntoView(line.from, { y: 'center' }),
});
view.focus();
};
// ── Toolbar: Copy selection ───────────────────────────
window.copySelection = function() {
const sel = view.state.sliceDoc(
view.state.selection.main.from,
view.state.selection.main.to
);
if (!sel) { toast('No text selected'); return; }
navigator.clipboard.writeText(sel)
.then(() => toast(`Copied ${sel.split('\n').length} line(s)`))
.catch(() => toast('Copy failed'));
};
// ── Toolbar: Paste ────────────────────────────────────
window.pasteToEditor = async function() {
try {
const text = await navigator.clipboard.readText();
const { from, to } = view.state.selection.main;
view.dispatch({
changes: { from, to, insert: text },
selection: { anchor: from + text.length },
});
toast(`Pasted ${text.split('\n').length} line(s)`);
} catch(e) {
toast('Paste failed — use long-press instead');
}
};
// ── Load / Save ───────────────────────────────────────
window.loadFile = async function(force) {
const cur = view.state.doc.toString();
if (!force && cur !== originalContent && cur.trim()) {
if (!confirm('Unsaved changes. Load from GitHub and discard?')) return;
}
setStatus('loading', 'Fetching...');
try {
const r = await fetch(RAW + '?t=' + Date.now());
if (!r.ok) throw new Error('HTTP ' + r.status);
const text = await r.text();
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: text } });
originalContent = text;
document.getElementById('modBadge').classList.remove('show');
const lc = text.split('\n').length;
setStatus('ok', lc + ' lines');
document.getElementById('saveBtn').disabled = false;
fetchSha();
toast('Loaded — ' + lc + ' lines');
requestAnimationFrame(() => {
view.dispatch({ effects: EditorView.scrollIntoView(view.state.doc.length) });
});
} catch(e) {
setStatus('err', 'Load failed');
toast('Load failed: ' + e.message);
}
};
async function fetchSha() {
const pat = getPat();
if (!pat) return;
try {
const r = await fetch(API, { headers: { Authorization: 'token ' + pat } });
if (!r.ok) return;
const j = await r.json();
fileSha = j.sha;
} catch(e) {}
}
window.showCommit = function() {
if (!getPat()) { showPat(); return; }
document.getElementById('commitBar').classList.add('show');
positionCommitBar();
setTimeout(() => document.getElementById('commitMsg').focus(), 50);
};
window.hideCommit = function() { document.getElementById('commitBar').classList.remove('show'); };
function positionCommitBar() {
const bar = document.getElementById('commitBar');
if (!bar.classList.contains('show')) return;
if (window.visualViewport) {
const vv = window.visualViewport;
bar.style.bottom = (window.innerHeight - vv.height - vv.offsetTop) + 'px';
} else {
bar.style.bottom = '0px';
}
}
if (window.visualViewport) {
window.visualViewport.addEventListener('resize', positionCommitBar);
window.visualViewport.addEventListener('scroll', positionCommitBar);
}
window.saveFile = async function() {
const pat = getPat();
if (!pat) { toast('No PAT — tap PAT button'); return; }
if (!fileSha) { toast('Load file first'); return; }
const msg = document.getElementById('commitMsg').value || 'Update filters';
const content = btoa(unescape(encodeURIComponent(view.state.doc.toString())));
setStatus('loading', 'Saving...');
try {
const r = await fetch(API, {
method: 'PUT',
headers: { Authorization: 'token ' + pat, 'Content-Type': 'application/json' },
body: JSON.stringify({ message: msg, content, sha: fileSha }),
});
if (!r.ok) { const j = await r.json(); throw new Error(j.message || r.status); }
const j = await r.json();
fileSha = j.content.sha;
originalContent = view.state.doc.toString();
document.getElementById('modBadge').classList.remove('show');
setStatus('ok', view.state.doc.lines + ' lines');
hideCommit();
toast('Saved to GitHub ✓');
} catch(e) {
setStatus('err', 'Save failed');
toast('Save failed: ' + e.message);
}
};
// ── Helpers ───────────────────────────────────────────
function setStatus(state, text) {
document.getElementById('sDot').className = state;
document.getElementById('sText').textContent = text;
}
function toast(msg) {
const t = document.getElementById('toast');
t.textContent = msg;
t.classList.add('show');
clearTimeout(t._t);
t._t = setTimeout(() => t.classList.remove('show'), 2500);
}
// ── Init ──────────────────────────────────────────────
updatePatIndicator();
loadFile(true);
</script>
</body>
</html>