-
Notifications
You must be signed in to change notification settings - Fork 1
/
quickReplace.html
1320 lines (1188 loc) · 49.7 KB
/
quickReplace.html
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
<!--
This app is completely self-contained. You don't even need a web server, you can just open the html
file in a browser from your local machine and run it directly.
@author Kip Robinson, https://github.com/kiprobinson
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>QuickReplace</title>
<link rel="shortcut icon" type="image/png" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAOwwAADsMBx2+oZAAAABl0RVh0U29mdHdhcmUAcGFpbnQubmV0IDQuMC4xOdTWsmQAAAG+SURBVDhPYzjw//+u3783f/++9tOnZe/eLXj1atazZ5MfPuy9e7ft5s2Gq1erLlwoPnMm98SJtCNHEg4cYCBJddTu3QwkqQ7evp0BqHre48feeXnSGhoMYCCqpOSQlVVy7Bimat/NmxmAZgNVA9X5lJQ0nDhRefQoUDWQa5aQgKnabf16BqBLIGanL1oEcUn0nDlArrCyMlA1kAEBXGJiBhUVDqtWMQDdzcTCAhSqO30a4u6c/fuBXCZmZlCYMDBAzDZpbmbm4LBatowB6EuQCQwMyL6EiIDChIEBqNp1zRqd0lIeJSXjRYsYgGECkYb7MhGsDghAYQIGQLOlfHz0p07VnTePAehuITk5oGjYzJkQX3pMmADk8khJgcKEgcFm/nwuWVn1mhqgarWZM0EuMQgKAkqYpaTEbNoUunq1bmwskKsWGQkKEwYGoLu1Ozs5pKVV+vsVpk5lALo7a88eo+hoUQ0NTiEhoAoIALobFCYMDEB3A82WzsvjMTOTmjiRATN2WLm5geqs584Fmg1RDXQJ0GygauHeXgbM2NFITWViZWVkZsZUzdvRwYAZl0CXYDUbqJqtpYWBNNUNDQAdSWk4PGhQVwAAAABJRU5ErkJggg=="/>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Fira+Code:wght@300&family=Open+Sans:ital,wght@0,300;0,700;1,300;1,700&display=block" rel="stylesheet" />
<style type="text/css">
/* Copied from: http://yui.yahooapis.com/3.18.1/build/cssreset/cssreset-min.css */
html{color:#000;background:#FFF}body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,textarea,p,blockquote,th,td{margin:0;padding:0}table{border-collapse:collapse;border-spacing:0}fieldset,img{border:0}address,caption,cite,code,dfn,em,strong,th,var{font-style:normal;font-weight:normal}ol,ul{list-style:none}caption,th{text-align:left}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal}q:before,q:after{content:''}abbr,acronym{border:0;font-variant:normal}sup{vertical-align:text-top}sub{vertical-align:text-bottom}input,textarea,select,button{font-family:inherit;font-size:inherit;font-weight:inherit;*font-size:100%}legend{color:#000}#yui3-css-stamp.cssreset{display:none}
/* --- end Yahoo reset script --- */
*{box-sizing: border-box}
html {
background-color: #cdc;
}
body {
font-family: "Open Sans",sans-serif;
font-size: 0.9em;
font-weight: 300;
padding: 1px;
padding-right: 5px;
}
textarea,input[type=text] {
font-family: "Fira Code",monospace,serif;
font-size: 0.8em;
font-weight: 300;
border: 1px solid black;
margin: 1px;
resize: none;
}
input {
padding-left: 2px;
padding-right: 2px;
}
strong,b {
color: #666;
font-weight: 700;
}
#input, #output {
width: 100%;
height: 250px;
border: 1px solid black;
padding: 3px;
}
#output {
color: #888;
}
#copyright {
text-align: center;
font-size: 0.8em;
font-weight: 300;
padding-bottom: 2px;
}
textarea:focus, input[type=text]:focus {
background-color: #ffb;
}
.example {
font-size: 0.75em;
color: #888;
}
.example, label {
white-space: nowrap;
}
.options-input {
width: 1.75rem;
}
label.radio {
margin-right: 0.75em;
}
.button {
border: 1px solid black;
background-color: #ccc;
cursor: default;
padding-left: 2px;
padding-right: 2px;
}
.button:hover {
background-color: #ffb;
}
.handle {
cursor: move;
}
.disabled {
opacity: 0.5;
}
td {
padding-left: 2px;
padding-right: 2px;
}
a, a:visited {
color: blue;
}
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script type="text/javascript">
//<![CDATA[
const FILTER_TYPES = {
PREPEND: 0,
SIMPLE: 1,
REGEX: 2,
GREP: 3,
SORT: 4,
CASE: 5,
}
class BitWriter {
bytes = [];
offset = 0;
/**
* Returns number of bits in the stream currently.
* @return {number}
*/
getNumBits() {
return this.bytes.length*8 + (this.offset > 0 ? this.offset - 8 : 0);
}
/**
* Writes the given number of bits to the stream.
* @param numBits Number of bits to write (max 32)
* @param value {number} One-byte value to be written. If numBits is less than 8, the bits to
* be written should be in the lower bits. For example, `write(3, 0b10100010)` will
* only write the final three bits (010).
*/
write(numBits, value) {
numBits &= 0xff;
if(numBits < 1 || numBits > 32)
throw new Error(`Illegal numBits: ${numBits}`);
//if writing more than one byte, recurseively write first byte, then the rest. (I could definitely optimize this)
if(numBits > 8) {
this.write(8, value >> (numBits - 8));
this.write(numBits - 8, value);
return;
}
//apply mask to ensure only desired bits are present
value &= (1 << numBits) - 1;
//amount of left shift in order to put the first bit immediately after the last bit in the stream
const shift = 8 - numBits - this.offset;
if(this.offset === 0) {
//start a new byte. since we can never have more than 8 bits added, no chance of failing over into next byte.
this.bytes.push(value << shift);
}
else if(shift >= 0) {
//we are shifting left (or not shifting), which means this value fits into the last byte in the stream.
this.bytes[this.bytes.length - 1] |= (value << shift);
}
else {
//we have to shift right, which means some bits go onto the end of last byte, and remaining bits go onto a new byte.
this.bytes[this.bytes.length - 1] |= (value >> -shift);
this.bytes.push((value << (8 + shift)) & 0xff);
}
//logic to increment offset is always the same, regardless which of the above cases we fell into.
this.offset = (this.offset + numBits) % 8;
}
/**
* Returns the byte array generated by this stream.
* The final byte may have padding.
* @return {number[]}
*/
getBytes() {
return [...this.bytes];
}
}
class BitReader {
bytes;
offset = 0;
index = 0;
/**
* @param bytes {number[]} Array of one-byte values
*/
constructor(bytes) {
this.bytes = bytes.map(b => b & 0xff); //ensure we have valid bytes
}
/**
* Returns the number of bits remaining in the stream.
* @return {number}
*/
getRemainingBits() {
return Math.max(0, (this.bytes.length - this.index)*8 - this.offset);
}
/**
* Reads the given number of bits from the stream.
* @param numBits {number} Number of bits to read. Max=32
* @return {number}
*/
read(numBits) {
numBits &= 0xff;
if(numBits < 1 || numBits > 32)
throw new Error(`Illegal numBits: ${numBits}`);
if(numBits > 8)
return ((this.read(8) << (numBits - 8)) | this.read(numBits - 8));
if(numBits > this.getRemainingBits())
throw new Error(`End of stream. Requested ${numBits} but remaining bits is ${this.getRemainingBits()}`);
let value = 0;
const mask = (1 << numBits) - 1;
//how far to the right we need to shift the last byte to get the last bit to align with the first bit in the mask
const shift = 8 - this.offset - numBits;
if(shift >= 0) {
//we can get all of the bits from the last byte
value = (this.bytes[this.index] >> shift) & mask;
}
else {
//we have to get some of the bits from the last byte, and some of the bits from the next byte
value = ((this.bytes[this.index] << -shift) & mask)
| (((this.bytes[this.index + 1]) >> (8 + shift)) & mask);
}
this.offset += numBits;
if(this.offset >= 8) {
this.offset -= 8;
this.index++;
}
return value;
}
}
class Base64Url {
static base64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
static map = [...Base64Url.base64chars];
static revMap = Base64Url.map.reduce((m, c, i) => { m[c] = i; return m; }, {});
constructor() {
throw new Error('Cannot instantiate Base64Url');
}
/**
* Encodes an array of bytes in base64-url encoding, with no trailing characters.
* @param bytes {number[]}
* @return {string}
*/
static encode(bytes) {
const bitReader = new BitReader(bytes);
let encoded = '';
while(bitReader.getRemainingBits() >= 6)
encoded += Base64Url.map[bitReader.read(6)];
const finalBits = bitReader.getRemainingBits();
if(finalBits > 0)
encoded += Base64Url.map[bitReader.read(finalBits) << (6 - finalBits)];
return encoded;
}
/**
* Decodes base64-url string to an array of bytes.
* @param encoded {string}
* @return {number[]}
*/
static decode(encoded) {
if('string' !== typeof encoded || /[^a-zA-Z0-9\-_]/.test(encoded))
throw new Error(`Not a valid Base64Url string: ${encoded}`);
const bitWriter = new BitWriter();
for(let c of encoded)
bitWriter.write(6, Base64Url.revMap[c])
return bitWriter.getBytes();
}
}
class Permalink {
//Markers 000 and 001 are for these specific markers.
//Markers 010-111 are for filter-specific fields (defined in fieldDefsByType)
static endOfFileMarker = 0b000;
static filterStartMarker = 0b001;
static fieldDefsByType = {
[FILTER_TYPES.PREPEND]: {
append: { marker: 0b010, type: 'string' },
ignoreBlanks: { marker: 0b011, type: 'boolean' },
prepend: { marker: 0b100, type: 'string' },
},
[FILTER_TYPES.SIMPLE]: {
find: { marker: 0b010, type: 'string' },
options: { marker: 0b011, type: 'string' },
replace: { marker: 0b100, type: 'string' },
},
[FILTER_TYPES.REGEX]: {
options: { marker: 0b010, type: 'string' },
regex: { marker: 0b011, type: 'string' },
replacement: { marker: 0b100, type: 'string' },
},
[FILTER_TYPES.GREP]: {
caseSensitive: { marker: 0b010, type: 'boolean' },
invert: { marker: 0b011, type: 'boolean' },
onlyMatched: { marker: 0b100, type: 'boolean' },
regex: { marker: 0b101, type: 'string' },
},
[FILTER_TYPES.SORT]: {
caseSensitive: { marker: 0b010, type: 'boolean' },
removeDupes: { marker: 0b011, type: 'boolean' },
reverse: { marker: 0b100, type: 'boolean' },
},
[FILTER_TYPES.CASE]: {
caseOption: { marker: 0b010, type: 'enum', numBits: 3, map: {upper: 0b000, lower: 0b001, title: 0b010} },
options: { marker: 0b011, type: 'string' },
regex: { marker: 0b100, type: 'string' },
},
};
/**
* Returns a properly escaped/encoded permalink to the current filters.
* @param filters {any[]} filters from the app
* @return {string} url to permalink
*/
static build(filters) {
//legacy ("v1") code:
//return '?filters=' + encodeURIComponent(JSON.stringify(filters));
const writer = new BitWriter();
for(const filter of filters) {
//new filter always starts with start marker (except first filter),
//followed by type value, followed by enabled flag
if(writer.getNumBits() > 0)
writer.write(3, Permalink.filterStartMarker);
writer.write(3, filter.type);
writer.write(1, filter.enabled);
const fieldDefs = Permalink.fieldDefsByType[filter.type];
if(!fieldDefs) {
console.error(`Unknown field type: ${filter.type}`);
continue;
}
//Next we loop through fields, writing field marker then field value
for(const field of Object.keys(filter)) {
//No need to preserve the id field, and type/enabled are handled above
if(field === 'id' || field === 'type' || field === 'enabled')
continue;
const fieldDef = fieldDefs[field];
if(!fieldDef) {
console.error(`Unknown field: ${field}`);
continue;
}
if(fieldDef.type === 'number') {
writer.write(3, fieldDef.marker);
writer.write(fieldDef.numBits, filter[field]);
}
else if(fieldDef.type === 'enum') {
writer.write(3, fieldDef.marker);
if(fieldDef.map[filter[field]] === undefined)
console.error(`value not in map: ${filter[field]}`);
writer.write(fieldDef.numBits, fieldDef.map[filter[field]]);
}
else if(fieldDef.type === 'boolean') {
writer.write(3, fieldDef.marker);
writer.write(1, filter[field]);
}
else if(fieldDef.type === 'string') {
const utf8Bytes = new TextEncoder().encode(filter[field]);
if(utf8Bytes.length >= (1 << 14))
throw new Error(`String exceeds maximum length ${1<<14}`);
writer.write(3, fieldDef.marker);
//String format:
// 1-bit flag: 0=short string (followed by 5-bit length), 1=long string (followed by 14-bit length)
// length (numBits determined by above logic)
// utf-8 bytes
const isLongString = utf8Bytes.length >= (1 << 5);
writer.write(1, isLongString);
writer.write(isLongString ? 14 : 5, utf8Bytes.length);
utf8Bytes.forEach(b => writer.write(8, b));
}
else {
console.error('unknown field type: ' + fieldDef.type);
}
}
}
return '?filters=v2.' + (Base64Url.encode(writer.getBytes()));
}
/**
* Parses permalink from URL href. Throws exception on parse error.
* @param permalink {string} permalink url parameter
* @return {any[]} parsed filters
*/
static parse(permalink) {
if(!permalink)
return undefined;
if(permalink.startsWith('v2.')) {
const bytes = Base64Url.decode(permalink.replace(/^v2./, ''));
if(bytes.length <= 0)
return null;
const reader = new BitReader(bytes);
const filters = [];
let id = 0;
let filter = {
id: ++id,
type: reader.read(3),
enabled: !!reader.read(1),
};
let fieldDefs = Permalink.fieldDefsByType[filter.type];
while(reader.getRemainingBits() >= 3) {
const marker = reader.read(3);
if(marker === Permalink.endOfFileMarker)
break;
if (marker === Permalink.filterStartMarker) {
filters.push(filter);
filter = {
id: ++id,
type: reader.read(3),
enabled: !!reader.read(1),
};
fieldDefs = Permalink.fieldDefsByType[filter.type];
continue;
}
const fieldDefKey = Object.keys(fieldDefs).find(k => fieldDefs[k].marker === marker);
const fieldDef = fieldDefKey ? fieldDefs[fieldDefKey] : null;
if(!fieldDef) {
throw new Error(`No fieldDef for marker ${marker}`);
}
if(fieldDef.type === 'number') {
filter[fieldDefKey] = reader.read(fieldDef.numBits);
}
else if(fieldDef.type === 'boolean') {
filter[fieldDefKey] = !!reader.read(1);
}
else if(fieldDef.type === 'enum') {
const enumVal = reader.read(fieldDef.numBits);
filter[fieldDefKey] = Object.keys(fieldDef.map).find(k => fieldDef.map[k] === enumVal);
}
else if(fieldDef.type === 'string') {
const isLongString = !!reader.read(1);
const length = reader.read(isLongString ? 14 : 5);
const utf8Bytes = [];
for(let i = 0; i < length; i++)
utf8Bytes.push(reader.read(8));
filter[fieldDefKey] = new TextDecoder("utf-8").decode(new Uint8Array(utf8Bytes));
}
else {
console.error(`Unknown fieldDef.type: ${fieldDef.type}`);
}
}
//add the final filter from the loop
filters.push(filter);
return filters;
}
//legacy permalink - just url-encoded JSON
return $.parseJSON(permalink);
}
}
$(function() {
//globals
var _G = {
...FILTER_TYPES,
maxFilterId: 0,
filters: null,
idleTimer: null,
rb: loadResourceBundle(),
};
document.title = _G.rb.pageTitle;
$('#addFilterLabel').text(_G.rb.addFilter);
$('#addFilterPrepend').val(_G.rb.prependType);
$('#addFilterSimple').val(_G.rb.simpleType);
$('#addFilterRegex').val(_G.rb.regexType);
$('#addFilterGrep').val(_G.rb.grepType);
$('#addFilterSort').val(_G.rb.sortType);
$('#addFilterCase').val(_G.rb.caseType);
$('#permalink').text(_G.rb.permalink).attr('title', _G.rb.permalinkTooltip);
$('#download').text(_G.rb.download).attr('title', _G.rb.downloadTooltip).toggle(supportsBlobUrl());
$('#copy').text(_G.rb.copy).attr('title', _G.rb.copyTooltip);
$('#copyUp').val(_G.rb.copyUp).attr('title', _G.rb.copyUpTooltip);
//---------------------------------------------------------------------------
// Initialization
//---------------------------------------------------------------------------
$('#input').focus();
$('body').css('overflow', 'hidden');
$('#filters').sortable({revert:100, helper:'clone', opacity: 0.75, handle: '.handle', axis: 'y', stop: updateFilters});
try {
_G.filters = Permalink.parse(getUrlParam('filters'));
} catch (e) {
console.error(e);
}
if(!$.isArray(_G.filters)) {
_G.filters = [
{type: _G.REGEX},
{type: _G.SIMPLE},
{type: _G.PREPEND}
]
}
initFilters(_G.filters);
//---------------------------------------------------------------------------
// Listeners
//---------------------------------------------------------------------------
$(window).resize(resizeInputs);
$('#addFilterPrepend').click(function() { return addFilter(_G.PREPEND); });
$('#addFilterSimple') .click(function() { return addFilter(_G.SIMPLE ); });
$('#addFilterRegex') .click(function() { return addFilter(_G.REGEX ); });
$('#addFilterGrep') .click(function() { return addFilter(_G.GREP ); });
$('#addFilterSort') .click(function() { return addFilter(_G.SORT ); });
$('#addFilterCase') .click(function() { return addFilter(_G.CASE ); });
$('#filters').on('input', 'input[type=text]', updateFilters);
$('#filters').on('change', 'input[type=checkbox]', updateFilters);
$('#filters').on('change', 'input[type=radio]', updateFilters);
$('#input').on('input', applyFilters);
$('#filters').on('click', '.remove-filter', function() {
$(this).closest('tr').remove();
updateFilters();
resizeInputs();
});
//hack because webfont load has issues when running from localhost
//Note to self: purely CSS based layout would avoid this issue, but when I tried to use CSS flex-grid
//the drag/drop was not working. Will need more work later...
setTimeout(resizeInputs, 0);
setTimeout(resizeInputs, 100);
setTimeout(resizeInputs, 200);
setTimeout(resizeInputs, 300);
setTimeout(resizeInputs, 400);
setTimeout(resizeInputs, 500);
//Select all text in output when it gets focus
$('#output').focus(function(){
$(this).select();
//workaround required b/c of this webkit bug: http://code.google.com/p/chromium/issues/detail?id=4505
if(navigator.userAgent.search('WebKit') > -1) {
$(this).mouseup(function(e) {
e.preventDefault();
$(this).unbind('mouseup');
});
}
});
//Copy content from output to input, and rerun filter.
$('#copyUp').click(function(){
$('#input').val($('#output').val());
applyFilters();
});
$('#download').on('click', function(e) {
e.preventDefault();
const text = $('#output').val();
const a = document.createElement("a");
a.style = "display: none";
const url = window.URL.createObjectURL(new Blob([text], {type:'text/plain'}));
a.href = url;
a.download = 'replaced.txt';
a.click();
window.URL.revokeObjectURL(url);
a.remove();
});
$('#copy').on('click', function(e) {
e.preventDefault();
const text = $('#output').val();
navigator.clipboard.writeText(text).then(() => {}, (err) => console.error('copy error! ' + err));
});
//Utilize history API if available
if(supportsHistoryApi()){
$(window).bind('popstate', function(e) {
var state = e.originalEvent.state;
if(state != null)
initFilters(e.originalEvent.state);
});
//Add Ctrl+S event mapping to save to address bar
$(document).keydown(function(e) {
if(e.ctrlKey && !e.altKey && (e.which == 83)) {
e.preventDefault();
saveState();
}
});
}
//---------------------------------------------------------------------------
// Core functions
//---------------------------------------------------------------------------
function initFilters(filters) {
$('#filters').empty();
$.each(filters, function() {
addFilter(this.type, this, true);
});
updateFilters();
resizeInputs();
}
/**
* Appends a filter to the filter controls.
* @param type: One of the global constants PREPEND, SIMPLE, or REGEX.
* @param args: Initial values for parameter arguments. Any unspecified paramters will use defaults.
* @param isStartup: If set and true, skips call to updateFilters and resizeInputs. Pass true during startup, to prevent
* redundant work when loading default or passed-in filters.
*/
function addFilter(type, args, isStartup) {
var filter = '';
if(!$.isPlainObject(args))
args = {};
if(typeof args.enabled == 'undefined')
args.enabled = true;
if(type == _G.PREPEND) {
if (typeof args.prepend == 'undefined')
args.prepend = '';
if (typeof args.append == 'undefined')
args.append = '';
if (typeof args.ignoreBlanks == 'undefined')
args.ignoreBlanks = false;
filter = renderTemplate($('#prependTemplate').text(), {
rb: _G.rb,
maxFilterId: ++_G.maxFilterId,
argsEnabled: args.enabled ? 'checked' : '',
argsPrepend: escapeHtml(escapeJS(args.prepend)),
argsAppend: escapeHtml(escapeJS(args.append)),
argsIgnoreBlanks: args.ignoreBlanks ? 'checked' : ''
});
}
else if (type == _G.SIMPLE) {
if (typeof args.find == 'undefined')
args.find = '';
if (typeof args.replace == 'undefined')
args.replace = '';
if (typeof args.options == 'undefined')
args.options = 'gim';
filter = renderTemplate($('#simpleTemplate').text(), {
rb: _G.rb,
maxFilterId: ++_G.maxFilterId,
argsEnabled: args.enabled ? 'checked' : '',
argsFind: escapeHtml(escapeJS(args.find)),
argsReplace: escapeHtml(escapeJS(args.replace)),
argsOptions: escapeHtml(args.options)
});
}
else if (type == _G.REGEX) {
if (typeof args.regex == 'undefined')
args.regex = '';
if (typeof args.replacement == 'undefined')
args.replacement = '';
if (typeof args.options == 'undefined')
args.options = 'gim';
filter = renderTemplate($('#regexTemplate').text(), {
rb: _G.rb,
maxFilterId: ++_G.maxFilterId,
argsEnabled: args.enabled ? 'checked' : '',
argsRegex: escapeHtml(args.regex),
argsReplacement: escapeHtml(escapeJS(args.replacement)),
argsOptions: escapeHtml(args.options)
});
}
else if (type == _G.GREP) {
if (typeof args.regex == 'undefined')
args.regex = '';
if (typeof args.caseSensitive == 'undefined')
args.caseSensitive = false;
if (typeof args.invert == 'undefined')
args.invert = false;
if (typeof args.onlyMatched == 'undefined')
args.onlyMatched = false;
filter = renderTemplate($('#grepTemplate').text(), {
rb: _G.rb,
maxFilterId: ++_G.maxFilterId,
argsEnabled: args.enabled ? 'checked' : '',
argsRegex: escapeHtml(args.regex),
argsCaseSensitive: args.caseSensitive ? 'checked' : '',
argsInvert: args.invert ? 'checked' : '',
argsOnlyMatched: args.onlyMatched ? 'checked' : ''
});
}
else if (type == _G.SORT) {
if (typeof args.caseSensitive == 'undefined')
args.caseSensitive = false;
if (typeof args.reverse == 'undefined')
args.reverse = false;
filter = renderTemplate($('#sortTemplate').text(), {
rb: _G.rb,
maxFilterId: ++_G.maxFilterId,
argsEnabled: args.enabled ? 'checked' : '',
argsCaseSensitive: args.caseSensitive ? 'checked' : '',
argsReverse: args.reverse ? 'checked' : '',
argsRemoveDupes: args.removeDupes ? 'checked' : ''
});
}
else if (type == _G.CASE) {
if (typeof args.regex == 'undefined')
args.regex = '';
if (typeof args.caseOption == 'undefined')
args.caseOption = 'upper'
if (typeof args.options == 'undefined')
args.options = 'gim';
// handling for radio options
args.caseOptionUpper = (args.caseOption === 'upper');
args.caseOptionLower = (args.caseOption === 'lower');
args.caseOptionTitle = (args.caseOption === 'title');
filter = renderTemplate($('#caseTemplate').text(), {
rb: _G.rb,
maxFilterId: ++_G.maxFilterId,
argsEnabled: args.enabled ? 'checked' : '',
argsRegex: escapeHtml(args.regex),
argsCaseOptionUpper: args.caseOptionUpper ? 'checked' : '',
argsCaseOptionLower: args.caseOptionLower ? 'checked' : '',
argsCaseOptionTitle: args.caseOptionTitle ? 'checked' : '',
argsOptions: escapeHtml(args.options),
});
}
if(filter) {
$('#filters').append(filter);
if(!isStartup) {
updateFilters();
resizeInputs();
}
}
return false;
}
/**
* Updates the _G.filters array based on current arrangement/values.
*/
function updateFilters()
{
_G.filters = [];
$('#filters>.filter').each(function() {
var id = this.id.substr(this.id.lastIndexOf('_') + 1);
var filter = {id: id};
if($(this).hasClass('prepend-filter')) {
filter.type = _G.PREPEND;
filter.enabled = $('#enabled_' + id)[0].checked;
filter.prepend = unescapeJS($('#prepend_' + id).val());
filter.append = unescapeJS($('#append_' + id).val());
filter.ignoreBlanks = $('#ignoreBlanks_' + id)[0].checked;
}
else if($(this).hasClass('simple-filter')) {
filter.type = _G.SIMPLE;
filter.enabled = $('#enabled_' + id)[0].checked;
filter.find = unescapeJS($('#find_' + id).val());
filter.replace = unescapeJS($('#replace_' + id).val());
filter.options = $('#options_' + id).val();
}
else if($(this).hasClass('regex-filter')) {
filter.type = _G.REGEX;
filter.enabled = $('#enabled_' + id)[0].checked;
filter.regex = $('#regex_' + id).val();
filter.replacement = unescapeJS($('#replacement_' + id).val());
filter.options = $('#options_' + id).val();
}
else if($(this).hasClass('grep-filter')) {
filter.type = _G.GREP;
filter.enabled = $('#enabled_' + id)[0].checked;
filter.regex = $('#regex_' + id).val();
filter.caseSensitive = $('#caseSensitive_' + id)[0].checked;
filter.invert = $('#invert_' + id)[0].checked;
filter.onlyMatched = $('#onlyMatched_' + id)[0].checked;
}
else if($(this).hasClass('sort-filter')) {
filter.type = _G.SORT;
filter.enabled = $('#enabled_' + id)[0].checked;
filter.caseSensitive = $('#caseSensitive_' + id)[0].checked;
filter.reverse = $('#reverse_' + id)[0].checked;
filter.removeDupes = $('#removeDupes_' + id)[0].checked;
}
else if($(this).hasClass('case-filter')) {
filter.type = _G.CASE;
filter.enabled = $('#enabled_' + id)[0].checked;
filter.regex = $('#regex_' + id).val();
filter.caseOption = $(`input[name="caseOption_${id}"]:checked`).val() || 'upper';
filter.options = $('#options_' + id).val();
}
if(typeof filter.type != 'undefined') {
_G.filters.push(filter);
$('#filter_' + id).toggleClass('disabled', !filter.enabled);
}
});
$('#permalink').attr('href', Permalink.build(_G.filters));
setIdleTimer();
applyFilters();
}
/**
* Applies all filters to the current input text.
*/
function applyFilters()
{
var text = $('#input').val();
try
{
$.each(_G.filters, function(i, filter)
{
if(filter.enabled)
{
if(filter.type == _G.PREPEND)
{
if(filter.prepend.length > 0 || filter.append.length > 0)
{
var regex = new RegExp(filter.ignoreBlanks ? '^(.+)$' : '^(.*)$', 'gm');
var replace = filter.prepend.replace(/\$/g, '$$$$') + '$1' + filter.append.replace(/\$/g, '$$$$');
text = text.replace(regex, replace);
}
}
else if(filter.type == _G.SIMPLE)
{
if(filter.find.length > 0)
text = text.replace(new RegExp(regexQuote(filter.find), filter.options), filter.replace);
}
else if(filter.type == _G.REGEX)
{
if(filter.regex.length > 0)
text = text.replace(new RegExp(filter.regex, filter.options), filter.replacement);
}
else if(filter.type == _G.GREP)
{
if(filter.regex.length > 0) {
var regex = new RegExp(filter.regex, filter.caseSensitive ? '' : 'i');
var lines = text.split('\n');
text = '';
for(var i = 0; i < lines.length; i++) {
var lineToAdd = '';
if(filter.onlyMatched && !filter.invert) {
var matches = lines[i].match(regex);
if(matches != null)
lineToAdd = matches[0];
}
else if(regex.test(lines[i]) != filter.invert) {
lineToAdd = lines[i];
}
if(lineToAdd != '')
text += (text.length > 0 ? '\n' : '') + lineToAdd;
}
}
}
else if(filter.type == _G.SORT)
{
var options = { usage: 'sort', sensitivity: filter.caseSensitive ? 'case' : 'base' };
var comparator = new Intl.Collator(navigator.language, options);
var lines = text.split('\n');
lines.sort(function(a,b){return (filter.reverse ? -1 : 1) * comparator.compare(a,b)});
text = '';
for(var i = 0; i < lines.length; i++) {
if(filter.removeDupes && i > 0 && comparator.compare(lines[i], lines[i-1]) == 0)
continue;
text += (text.length > 0 ? '\n' : '') + lines[i];
}
}
else if(filter.type == _G.CASE)
{
if(filter.regex.length > 0) {
const regex = new RegExp(filter.regex, filter.options);
const replacement = s => {
if(filter.caseOption === 'upper')
return s.toUpperCase();
else if(filter.caseOption === 'lower')
return s.toLowerCase();
else if(filter.caseOption === 'title')
return s.replace(/(^|\W)(\w)(\w*)/g, (s, m1, m2, m3) => m1 + m2.toUpperCase() + m3.toLowerCase());
};
text = text.replace(regex, replacement);
}
}
}
});
$('#output').val(text);
}
catch(err)
{
$('#output').val("ERROR:\n" + err);
}
}
/**
* Adjusts the size of the input controls so that they will fill up the whole screen.
*/
function resizeInputs() {
//The text areas should fill the whole vertical space
var minHeight = 50;
var newHeight = $(window).height() - ($('body').height() - $('#input').height() - $('#output').height());
newHeight = Math.max(Math.floor(newHeight/2), minHeight);
$('textarea').height(newHeight);
//The flex-input elements should fill the whole horizontal space
var minFlexWidth = 100;
var newFlexWidth = $('body').width() - $('#filters').width() + 2 * Number($('.flex-input:first').width());
newFlexWidth = Math.max(Math.floor(newFlexWidth/2), minFlexWidth);
$('.flex-input').width(newFlexWidth);
}
function setIdleTimer() {
if(_G.idleTimer !== null)
clearTimeout(_G.idleTimer);
_G.idleTimer = setTimeout(function() {
saveState();
}, 10000);
}
/**
* Saves current filter state to the browser's address bar, if supported.
*/
function saveState() {
if(supportsHistoryApi()) {
history.pushState(_G.filters, 'QuickReplace', getPermalink());
if(_G.idleTimer !== null) {
clearTimeout(_G.idleTimer);
_G.idleTimer = null;
}
}
}
//---------------------------------------------------------------------------
// Helper functions
//---------------------------------------------------------------------------
/**
* A very very simple templating engine. Mimics basic funcionality of Underscore.js templates.
* @param template Template content
* @param params Object where keys are strings to be searched, and values are replacements to make.
* This may contain nested objects.
* @params prefix Only used when recursing.
*/
function renderTemplate(template, params, prefix)
{
prefix = prefix || '';
$.each(params, function(k,v) {
if($.isPlainObject(v))
template = renderTemplate(template, v, k + '.');
else
template = template.replace(new RegExp('<%=\\s*' + regexQuote(prefix + k) + '\\s*%>', 'g'), String(v).replace(/\$/g, '$$$$'));
});
//if this was not recursive call, clean up any unused template strings
if(prefix=='')
template = template.replace(/<%(.*?)%>/g, '');//'MISSING: [$1]');
return template;
}