-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
1682 lines (1421 loc) · 57.9 KB
/
main.js
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
// @ts-check
function ttywtf() {
function addButtonHandlers() {
var buttonsArray = document.getElementsByTagName('button');
for (var i = 0; i < buttonsArray.length; i++) {
addHandler(buttonsArray[i]);
}
/** @param {HTMLButtonElement} btn */
function addHandler(btn) {
btn.onmousedown = btn_onmousedown;
btn.onmouseup = btn_mouseup;
btn.onclick = btn_click;
/** @param {MouseEvent} evt */
function btn_onmousedown(evt) {
if (evt.preventDefault) evt.preventDefault();
if (evt.stopPropagation) evt.stopPropagation();
if ('cancelBubble' in evt) evt.cancelBubble = true;
handleClick();
}
/** @param {MouseEvent} evt */
function btn_mouseup(evt) {
if (evt.preventDefault) evt.preventDefault();
if (evt.stopPropagation) evt.stopPropagation();
if ('cancelBubble' in evt) evt.cancelBubble = true;
}
/** @param {MouseEvent} evt */
function btn_click(evt) {
if (evt.preventDefault) evt.preventDefault();
if (evt.stopPropagation) evt.stopPropagation();
if ('cancelBubble' in evt) evt.cancelBubble = true;
}
function handleClick() {
var modifier = btn.id;
var remove = (btn.className || '').indexOf('pressed') >= 0;
applyModifierToSelection(modifier, remove);
}
}
}
// #region URL content handling
function getStorageText() {
return deriveTextFromLocation();
}
/** @param {string} text */
function mangleForURL(text) {
return encodeURIComponent(text)
.replace(/%3A/ig, ':')
.replace(/%20/ig, '+')
.replace(/%0A/gi, '/')
.replace(/%5E/gi, '^');
}
/** @param mangled {string} */
function unmangleFromURL(mangled) {
return decodeURIComponent(mangled
.replace(/\//g, '\n')
.replace(/\+/g, ' ')
);
}
function detectLocationBase(location) {
if (!location) location = window.location;
if (/http/.test(location.protocol)) {
if (/github\.io/i.test(location.host) || location.host.toLowerCase() === 'oyin.bo') {
return {
source: 'path',
path: location.pathname.slice(0, location.pathname.indexOf('/', 1) + 1),
encoded: '/' + location.pathname.slice(location.pathname.indexOf('/', 1) + 1)
};
} else if (/\.vscode/i.test(location.host)) {
var matchIndexHtml = /\/(index|404)\.html\b/i.exec(location.pathname || '');
if (!matchIndexHtml) return {
source: 'hash',
path: location.pathname,
encoded: location.hash.replace(/^#/, '')
};
return {
source: 'hash',
path: location.pathname.slice(0, matchIndexHtml.index + 1),
encoded: location.hash.replace(/^#/, '')
};
} else {
return {
source: 'path',
path: '/',
encoded: location.pathname.replace(/^\//, '')
};
}
} else {
return {
source: 'hash',
path: location.pathname,
encoded: location.hash.replace(/^#/, '')
};
}
}
function getLocationSource(location) {
var bases = detectLocationBase(location);
var source = bases.encoded;
if (source.charAt(0) === '/') source = source.slice(1);
return unmangleFromURL(source);
}
/**
* @param {typeof window.location=} location
**/
function deriveTextFromLocation(location) {
var decoded = decodeText(getLocationSource());
return decoded;
}
/** @param source {string} */
function decodeText(source) {
if (!source) return '';
if (/^txt~/.test(source)) {
return source.slice('txt~'.length);
} else if (/^md~/.test(source)) {
return convertFromMarkdown(source.slice('md~'.length));
} else if (/^b~/.test(source)) {
return convertFromCompressed(source.slice('b~'.length));
} else {
var fromMD = convertFromMarkdown(source);
if (convertToMarkdown(fromMD) === source) return fromMD;
else return source;
}
}
/**
* @param text {string}
* @param location {typeof window.location=}
**/
function updateLocationWithText(text, location) {
if (!location) location = window.location;
var existingText = deriveTextFromLocation(location);
if ((text || '') === (existingText || '')) return false;
var bases = detectLocationBase(location);
var encoded = mangleForURL(encodeText(text));
if (bases.source === 'hash') {
console.log('store in hash ', bases, ' --> ', encoded);
location.href = '#' + encoded;
return;
} else {
console.log('store with replaceState ', bases, ' --> ', encoded, ' as ' + location.protocol + '//' + location.hostname + (location.port ? ':' + location.port : '') + '/' + encoded);
history.replaceState(null, 'unused-string',
location.protocol + '//' + location.hostname + (location.port ? ':' + location.port : '') +
bases.path + encoded);
}
}
/** @param text {string} */
function encodeText(text) {
var encoded = convertToMarkdown(text);
if (encoded.length < 1900 && convertFromMarkdown(encoded) === text) return encoded;
if (text.length < 1900) return 'txt~' + text;
return 'b~' + convertToCompressed(text);
}
var regex_markdownDecorChunks = /([\*_]+)([^\*_\n]+)([\*_]+)/g;
/**
* @param markdown {string}
* @returns {string}
**/
function convertFromMarkdown(markdown) {
var formatted = markdown.replace(regex_markdownDecorChunks, convertFromMarkdownHelper);
formatted = formatted.replace(
/\^([a-z0-9])/i,
function (whole, char) { return applyModifierToPlainCh(char, ['super']); });
return formatted;
}
/**
* @param whole {string}
* @param openDecor {string}
* @param content {string}
* @param closeDecor {string}
**/
function convertFromMarkdownHelper(whole, openDecor, content, closeDecor) {
if (openDecor === '*' && closeDecor === '*') {
var italic = applyModifier(content, 'italic');
if (italic !== whole) return italic;
else return whole;
} else if (openDecor === '**' && closeDecor === '**') {
var bold = applyModifier(content, 'bold');
if (bold !== whole) return bold;
else return whole;
} else if (openDecor === '***' && closeDecor === '***') {
var bolditalic = applyModifier(applyModifier(content, 'bold'), 'italic');
if (bolditalic !== whole) return bolditalic;
else return whole;
} else if (openDecor === '_' && closeDecor === '_') {
var underline = applyModifier(content, 'underlined');
if (underline !== whole) return underline;
else return whole;
}
return whole;
}
/**
* @param formattedText {string}
* @returns {string}
**/
function convertToMarkdown(formattedText) {
var result = '';
var parsed = parseRanges(formattedText);
for (var i = 0; i < parsed.length; i++) {
var range = parsed[i];
if (typeof range === 'string') {
result += range;
} else {
var prefix = '';
var suffix = '';
var text = range.plain;
for (var j = 0; j < range.modifiers.length; j++) {
var mod = range.modifiers[j];
switch (mod) {
case 'bold':
prefix = '**' + prefix;
suffix = suffix + '**';
break;
case 'italic':
prefix = '*' + prefix;
suffix = suffix + '*';
break;
case 'underlined':
prefix = '_' + prefix;
suffix = suffix + '_';
break;
default:
if (range.fullModifiers === 'super' && range.plain.length === 1)
prefix = '^';
else
text = range.formatted;
}
}
result += prefix + text + suffix;
}
}
return result;
}
/**
* @param compressed {string}
* @returns {string}
**/
function convertFromCompressed(compressed) {
var pako = /** @type {*} */(window).pako;
var deflatedStr = atob(compressed);
var deflatedArr = typeof Uint8Array === 'function' ?
new Uint8Array(deflatedStr.length) :
/** @type {Uint8Array} */(/** @type {*} */([]));
for (var i = 0; i < deflatedStr.length; i++) {
deflatedArr[i] = deflatedStr.charCodeAt(i);
}
var arr = pako.inflate(deflatedArr);
var text = '';
for (var i = 0; i < arr.length; i++) {
text += String.fromCharCode(arr[i]);
}
return text;
}
/**
* @param text {string}
* @returns {string}
**/
function convertToCompressed(text) {
var pako = /** @type {*} */(window).pako;
var deflatedArr = pako.deflate(text);
var deflatedStr = '';
for (var i = 0; i < deflatedArr.length; i++) {
deflatedStr += String.fromCharCode(deflatedArr[i]);
}
var base64 = btoa(deflatedStr);
return base64;
}
// #endregion
/** @param evt {ClipboardEvent} */
function textarea_onpaste(evt) {
if (!evt || !evt.clipboardData || typeof evt.clipboardData.getData !== 'function') return;
var html = evt.clipboardData.getData('text/html');
if (!html) return;
var text = convertHtmlToText(html);
if (text && typeof evt.preventDefault === 'function') {
evt.preventDefault();
var currentText = textarea.value;
var unchangedPrefix = currentText.slice(0, textarea.selectionStart);
var unchangedSuffix = currentText.slice(textarea.selectionEnd);
var newText = unchangedPrefix + text + unchangedSuffix;
textarea.value = newText;
textarea.selectionStart = unchangedPrefix.length + text.length;
textarea.selectionEnd = unchangedPrefix.length + text.length;
textarea_onchange_debounced();
}
}
/** @param html {string} */
function convertHtmlToText(html) {
var tmpDIV = document.createElement('div');
tmpDIV.innerHTML = html;
tmpDIV.style.cssText = 'position: absolute; left: -1000px; top: -1000px; color: transparent; opacity: 0;'
document.body.appendChild(tmpDIV);
var result = '';
var breakAfter = false;
try {
visitElement(tmpDIV);
}
catch (err) {
console.error('handling paste ', err);
}
finally {
document.body.removeChild(tmpDIV);
}
return result;
/** @param {HTMLElement} el */
function visitElement(el) {
if (/script|head|style|meta/i.test(el.tagName)) return;
if (/br/i.test(el.tagName)) {
result += '\n';
breakAfter = false;
return;
}
if (/hr/i.test(el.tagName)) {
if (breakAfter) result += '\n----------------';
else result += '----------------';
breakAfter = true;
return;
}
if (!el.childNodes || !el.childNodes.length) {
visitChildlessElement(el, el.textContent || '');
breakAfter = isSeparateParagraphElement(el);
}
else {
visitElementChildren(el);
}
}
/** @param {HTMLElement} el */
function isSeparateParagraphElement(el) {
var separateParagraph = /div|pr|td|blockquote|p/i.test(el.tagName);
return separateParagraph;
}
/**
* @param {HTMLElement} el
* @param {string} text
**/
function visitChildlessElement(el, text) {
if (text) {
if (typeof getComputedStyle === 'function') {
var style = getComputedStyle(el);
if (style) {
if (/^(code|pre)$/i.test(el.tagName) || isTypewriter(style)) text = applyModifier(text, 'typewriter');
if (/^(b|strong)$/i.test(el.tagName) || isBold(style)) text = applyModifier(text, 'bold');
if (/^(i)$/i.test(el.tagName) || isItalic(style)) text = applyModifier(text, 'italic');
if (/^(sup)$/i.test(el.tagName) || isSuper(style)) text = applyModifier(text, 'super');
if (/^(u)$/i.test(el.tagName) || isUnderlined(style)) text = applyModifier(text, 'underlined');
}
}
result += breakAfter ? '\n' + text : text;
}
}
/** @param style {CSSStyleDeclaration} */
function isBold(style) {
if (/bold/i.test(style.fontWeight || '')) return true;
var num = parseFloat(style.fontWeight);
if (num >= 600) return true;
}
/** @param style {CSSStyleDeclaration} */
function isItalic(style) {
if (/italic/i.test(style.fontStyle || '')) return true;
}
/** @param style {CSSStyleDeclaration} */
function isUnderlined(style) {
if (/underline/i.test(style.textDecoration || '')) return true;
}
/** @param style {CSSStyleDeclaration} */
function isTypewriter(style) {
if (/pre/i.test(style.whiteSpace || '')) return true;
if (/mono|courier|terminal/i.test(style.fontFamily || '')) return true;
}
/** @param style {CSSStyleDeclaration} */
function isSuper(style) {
if (/super/i.test(style.verticalAlign || '')) return true;
if (style.fontSize) {
var num = parseFloat(style.fontSize);
if (num <= 13) return true;
}
}
/** @param el {HTMLElement} */
function visitElementChildren(el) {
for (var i = 0; i < el.childNodes.length; i++) {
var childNode = el.childNodes[i];
if (childNode.nodeType === 3 /* text */) {
visitChildlessElement(el, childNode.textContent || '');
breakAfter = false;
continue;
}
if (childNode.nodeType === 1 /* element */) {
visitElement(/** @type {HTMLElement} */(childNode));
continue;
}
}
}
}
function textarea_onchange() {
var textareaCurrentValue = textarea.value;
if (textareaCurrentValue === textareaLastValue) {
textarea_onselectionchange();
return;
}
var timestamp = Date.now();
var shortlyAfterKeydown = (Date.now() - textareaKeyEventTimestamp) < 50;
var formattingApplied = false;
if (textareaCurrentValue && shortlyAfterKeydown) {
if (textarea.selectionStart === textarea.selectionEnd) {
var unchangedPrefixLength = Math.max(0, textarea.selectionStart - 10);
var unchangedSuffixLength = Math.max(0, textareaCurrentValue.length - textarea.selectionStart - 2);
if (textareaCurrentValue.slice(0, unchangedPrefixLength) === textareaLastValue.slice(0, unchangedPrefixLength)
&& (!unchangedSuffixLength || textareaCurrentValue.slice(-unchangedSuffixLength) === textareaLastValue.slice(-unchangedSuffixLength))) {
// change is close to the cursor, good
// find where change starts exactly
while (unchangedPrefixLength + unchangedSuffixLength < textareaCurrentValue.length
&& unchangedPrefixLength + unchangedSuffixLength < textareaLastValue.length
&& textareaCurrentValue.charCodeAt(unchangedPrefixLength) === textareaLastValue.charCodeAt(unchangedPrefixLength)) {
unchangedPrefixLength++;
}
// find where change ends exactly
while (unchangedPrefixLength + unchangedSuffixLength < textareaCurrentValue.length
&& unchangedPrefixLength + unchangedSuffixLength < textareaLastValue.length
&& textareaCurrentValue.charCodeAt(textareaCurrentValue.length - unchangedSuffixLength - 1) === textareaLastValue.charCodeAt(textareaLastValue.length - unchangedSuffixLength - 1)) {
unchangedSuffixLength++;
}
// will be applying modifiers one by one, more important last
var modifiersParsed = getModifiersTextSection(
textareaLastValue,
unchangedPrefixLength,
textareaLastValue.length - unchangedSuffixLength
);
var modifiersChange = modifiersParsed && modifiersParsed.parsed && modifiersParsed.parsed.modifiers || [];
var modifiersLead = textareaLastValue.length === unchangedPrefixLength + unchangedSuffixLength ?
[] :
(modifiersParsed = getModifiersTextSection(
textareaLastValue,
unchangedPrefixLength,
unchangedPrefixLength + 2
)) && modifiersParsed.parsed && modifiersParsed.parsed.modifiers || [];
if (modifiersChange.length) {
var prevInnerText = textareaLastValue.slice(
unchangedPrefixLength,
unchangedSuffixLength ? -unchangedSuffixLength : textareaLastValue.length);
var editedInnerText = textareaCurrentValue.slice(
unchangedPrefixLength,
unchangedSuffixLength ? -unchangedSuffixLength : textareaCurrentValue.length);
var innerText = editedInnerText;
if (innerText) {
var applyModifierList = modifiersLead.slice().reverse();
for (var i = 0; i < modifiersChange.length; i++) {
var mod = modifiersChange[i];
if (applyModifierList.indexOf(mod) < 0) applyModifierList.unshift(mod);
}
for (var i = 0; i < applyModifierList.length; i++) {
innerText = applyModifier(innerText, applyModifierList[i],/* remove: */ false);
}
}
if (innerText !== editedInnerText) {
var newText =
textareaCurrentValue.slice(0, unchangedPrefixLength) +
innerText +
(unchangedSuffixLength ? textareaCurrentValue.slice(-unchangedSuffixLength) : '');
textareaLastValue = newText;
textarea.value = newText;
formattingApplied = true;
var restoreSelectionPos = unchangedPrefixLength + innerText.length;
if (textarea.selectionStart !== restoreSelectionPos || textarea.selectionEnd !== restoreSelectionPos) {
textarea.selectionStart = restoreSelectionPos;
textarea.selectionEnd = restoreSelectionPos;
}
}
}
}
}
}
if (!formattingApplied) {
textareaLastValue = textareaCurrentValue;
}
clearTimeout(save_timeout);
save_timeout = setTimeout(textarea_onchange_debounced, 200);
}
function textarea_onchange_debounced() {
clearTimeout(save_timeout);
updateLocationWithText(textarea.value);
textarea_onselectionchange_debounced();
updateFontSizeToContent();
}
function updateFontSizeToContent() {
var fontSize = Math.min(calculateFontSizeToContent(), 2.5);
var roundedFontSizeStr = !fontSize ? '' :
(Math.round(fontSize * 2) * 50) + '%';
if (textarea.style.fontSize !== roundedFontSizeStr) {
console.log('adjusting font size: ' + textarea.style.fontSize + ' --> ' + roundedFontSizeStr);
textarea.style.fontSize = roundedFontSizeStr;
}
}
/** @type {HTMLSpanElement} */
var invisibleSPAN;
/** @type {HTMLDivElement} */
var invisibleDIVParent;
function calculateFontSizeToContent() {
if (!textarea.value) return 2.5;
if (!invisibleSPAN) {
invisibleSPAN = document.createElement('span');
invisibleDIVParent = document.createElement('div');
invisibleDIVParent.appendChild(invisibleSPAN);
}
var textareaBounds = textarea.getBoundingClientRect();
invisibleDIVParent.style.cssText =
'position: absolute; left: -' + (textareaBounds.width * 2 | 0) + 'px; top: ' + (textareaBounds.height * 2 | 0) + 'px; ' +
'padding: 1em; ' +
'opacity: 0; pointer-events: none; z-index: -1000; ' +
'white-space: pre-wrap; ';
document.body.appendChild(invisibleDIVParent);
invisibleSPAN.textContent = textarea.value;
try {
var measuredBounds = invisibleSPAN.getBoundingClientRect();
var insetRatio = 0.6;
if (measuredBounds.width * measuredBounds.height > textareaBounds.width * textareaBounds.height * 0.4)
return; // too much text
var horizontalRatio = measuredBounds.width / (textareaBounds.width * insetRatio);
var verticalRatio = measuredBounds.height / (textareaBounds.height * insetRatio);
if (horizontalRatio < 1 && verticalRatio < 1) {
return Math.min(4, 1 / Math.max(horizontalRatio, verticalRatio));
}
if (verticalRatio < 1) {
invisibleDIVParent.style.width = (measuredBounds.width * insetRatio) + 'px';
measuredBounds = invisibleSPAN.getBoundingClientRect();
horizontalRatio = measuredBounds.width / (textareaBounds.width * insetRatio);
verticalRatio = measuredBounds.height / (textareaBounds.height * insetRatio);
if (horizontalRatio <= 1 && verticalRatio < 1) {
return Math.min(4, 1 / Math.max(horizontalRatio, verticalRatio));
}
}
}
catch (error) {
console.error('Failing to adjust font size to content. ', error);
}
finally {
document.body.removeChild(invisibleDIVParent);
invisibleSPAN.textContent = '';
invisibleDIVParent.style.width = '';
}
}
function textarea_onmousedown() {
textareaMouseDown = true;
textarea_onselectionchange();
}
function textarea_onmouseup() {
textareaMouseDown = false;
textarea_onselectionchange();
}
function textarea_onmousemove() {
if (!textareaMouseDown) return;
textarea_onselectionchange();
}
/** @param {KeyboardEvent} e */
function textarea_onkeydown(e) {
if (e.metaKey || e.ctrlKey) {
var letter = String.fromCharCode(e.keyCode);
var modifier =
letter === 'B' ? 'bold' :
letter === 'I' ? 'italic' :
letter === 'U' ? 'underlined' :
'';
if (modifier) {
var btn = document.getElementById(modifier);
if (btn) {
var remove = (btn.className || '').indexOf('pressed') >= 0;
applyModifierToSelection(modifier, remove);
}
}
}
textarea_onkeyevent();
}
/** @param {KeyboardEvent=} e */
function textarea_onkeyevent(e) {
textareaKeyEventTimestamp = Date.now();
textarea_onchange();
}
function textarea_onselectionchange() {
if (!selection_timeout_max) selection_timeout_max = setTimeout(textarea_onselectionchange_debounced, 200);
clearTimeout(selection_timeout_slide);
selection_timeout_slide = setTimeout(textarea_onselectionchange_debounced, 70);
}
function textarea_onselectionchange_debounced() {
clearTimeout(selection_timeout_slide);
clearTimeout(selection_timeout_max);
selection_timeout_max = 0;
//status.textContent = status.innerText = textarea.selectionStart + ':' + (textarea.selectionEnd - textarea.selectionStart);
var modTextSection = getModifiersTextSection(textarea.value, textarea.selectionStart, textarea.selectionEnd);
console.log('modTextSection: ', modTextSection);
var toggleButtons = document.querySelectorAll('#toolbar button');
for (var i = 0; i < toggleButtons.length; i++) {
var btn = /** @type {HTMLButtonElement} */(toggleButtons[i]);
if (btn.id) {
var pressed = modTextSection && modTextSection.parsed && modTextSection.parsed.modifiers.indexOf(btn.id) >= 0;
if (pressed) btn.className = (btn.className || '').replace(/\s*$/, '') + ' pressed';
else btn.className = btn.className.replace(/\s*\bpressed\b\s*/g, ' ');
}
}
}
function window_onunload() {
// save to local storage NOW
textarea_onchange_debounced();
}
var noteFonts = [
'Note Sans Math',
'Note Emoji',
'Noto Sans Symbols',
'Noto Sans Symbols 2',
'Note Sans'
];
function createLayout() {
var tableLayoutHTML =
'<table style="width: 100%; height: 100%;" cellspacing=0 cellpadding=0><tr><td width="100%" style="position: relative">' +
'<textarea id="textarea" autofocus>' +
'</textarea>' +
'</td><td width="1%" style="width: 1em; padding-right: 0.5em;" id="toolbar" valign=top>' +
createButtonLayout() +
'</td></tr></table>';
var tmpDIV = document.createElement('div');
tmpDIV.innerHTML = tableLayoutHTML;
var table = tmpDIV.getElementsByTagName('table')[0];
document.body.insertBefore(table, document.body.childNodes.item(0));
var styleCSS =
'html { box-sizing: border-box; width: 100%; height: 100%; overflow: hidden; padding: 0; margin: 0; } ' +
'body { background: white; color: black; font-family:\n' +
' "Arial Unicode", "' + noteFonts.join('", "') + '",\n' +
' -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; width: 100%; height: 100%; overflow: hidden; padding: 0; margin: 0; } ' +
'*, *:before, *:after { box-sizing: inherit; font-family: inherit; } ' +
'#toolbar button { width: 100%; height: 2.7em; padding-top:0; line-height:0; margin: 0.35em; margin-top: 0.25em; margin-bottom: 0; border-radius: 0.5em; background: white; border: solid 1px #d6d6d6; box-shadow: 2px 3px 6px rgb(0, 0, 0, 0.09); } ' +
'#toolbar button.pressed { background: gray; color: white; } ' +
'#toolbar button .symbol-formatted { font-size: 150%; position: relative; top: 0.05em; font-size: 150%; position: relative; top: 0.08em; left: -0.02em; } ' +
'#toolbar button#italic .symbol-formatted { left: -0.07em; } \n' +
'#toolbar button#cursive .symbol-formatted { left: 0.1em; } \n' +
'#toolbar button#box .symbol-formatted { left: 0.05em; top: 0.08em; } \n' +
'#toolbar button#plate .symbol-formatted { top: 0.14em; } \n' +
'#textarea { width: 100%; height: 100%; overflow: auto; border: none; padding: 1em; outline: none; font: inherit; resize: none; position: absolute; left: 0; top: 0; }';
var styleEl = document.createElement('style');
styleEl.innerHTML = styleCSS;
(document.head || document.getElementsByTagName('head')[0]).appendChild(styleEl);
function createButtonLayout() {
var buttonsHTML = '';
var addedSymbols = '';
var modList = [];
for (var mod in variants) {
if (mod !== 'bold' && /^bold/.test(mod)) continue;
modList.push(mod);
// underline is treated differently, keep track of it though
if (mod === 'italic') modList.push('underlined');
}
for (var i = 0; i < modList.length; i++) {
var mod = modList[i];
var symbolPlain = mod.charAt(0);
if (addedSymbols.indexOf(symbolPlain) >= 0) symbolPlain = mod.charAt(mod.length - 1);
addedSymbols += symbolPlain;
var symbolFormatted = applyModifierToPlainCh(symbolPlain.toUpperCase(), mod === 'fractur' || mod === 'cursive' ? ['bold' + mod] : [mod]);
var symbolHTML = symbolPlain === mod.charAt(0) ?
'<span class=symbol-formatted>' + symbolFormatted + '</span>' + mod.slice(1) :
mod.slice(0, mod.length - 1) + '<span class=symbol-formatted>' + symbolFormatted + '</span>';
buttonsHTML += '<button id=' + mod + '>' + symbolHTML + '</b>';
}
return buttonsHTML;
}
}
function initWithStorageText() {
textarea.value = getStorageText() || '';
//var status = document.getElementById('status');
textarea.onchange = textarea_onchange;
textarea.onselect = textarea_onselectionchange;
textarea.onselectionchange = textarea_onselectionchange;
textarea.onselectstart = textarea_onselectionchange;
textarea.onkeydown = textarea_onkeydown;
textarea.onkeyup = textarea_onkeyevent;
textarea.onkeypress = textarea_onkeyevent;
textarea.onmousedown = textarea_onmousedown;
textarea.onmouseup = textarea_onmouseup;
textarea.onmousemove = textarea_onmousemove;
textarea.onpaste = textarea_onpaste;
// firefox mobile fails to autoselect on doubleclick
if (navigator.userAgent.indexOf('Firefox') >= 0) {
textarea.ondblclick = function (evt) {
// textarea.selection
};
}
window.onunload = window_onunload;
addButtonHandlers();
textarea_onselectionchange();
updateFontSizeToContent();
}
var checkIfLoadedTimeout;
function checkIfLoaded() {
clearTimeout(checkIfLoadedTimeout);
if (!/** @type {*} */(window).pako) {
checkIfLoadedTimeout = setTimeout(checkIfLoaded, 600);
} else {
initWithStorageText();
}
}
function getStorageTextFirstTime() {
var source = getLocationSource();
if (!/^b~/.test(source)) {
initWithStorageText();
return;
}
textarea.onchange = ignoreEvent;
textarea.onselect = ignoreEvent;
textarea.onselectionchange = ignoreEvent;
textarea.onselectstart = ignoreEvent;
textarea.onkeydown = ignoreEvent;
textarea.onkeyup = ignoreEvent;
textarea.onkeypress = ignoreEvent;
textarea.onmousedown = ignoreEvent;
textarea.onmouseup = ignoreEvent;
textarea.onmousemove = ignoreEvent;
textarea.onpaste = ignoreEvent;
if (typeof window.addEventListener === 'function') {
window.addEventListener('load', checkIfLoaded);
checkIfLoadedTimeout = setTimeout(checkIfLoaded, 300);
}
/** @param {Event} evt */
function ignoreEvent(evt) {
if (typeof evt.preventDefault === 'function') evt.preventDefault();
}
}
function runInBrowser() {
parseRanges = runParseRanges;
createLayout();
textarea = /** @type {HTMLTextAreaElement} */(document.getElementById('textarea'));
getStorageTextFirstTime();
}
function runInLocalNodeScript() {
console.log('Running local DEV server...');
var fs = require('fs');
var path = require('path');
var http = require('http');
var useWatch = false;
if (useWatch) {
var restartTimeout;
fs.watch(
__filename,
function () {
clearTimeout(restartTimeout);
restartTimeout = setTimeout(function () {
// spurious change, ignore
if (fs.readFileSync(__filename).indexOf(ttywtf + '') >= 0) return;
console.log('file changed?...');
var child_process = require('child_process');
try {
var spawnRes = child_process.spawn('node', [__filename], {
cwd: __dirname,
argv0: __filename,
stdio: 'inherit'
}); ///
spawnRes.on('error', function (spawnErr) {
console.log('could not spawn new instance: ', spawnErr);
});
}
catch (error) {
console.log('could not start new instance: ', error);
}
}, 2000);
}
);
}
var port = 3458;
var server = http.createServer(nodeHandleRequest);
var serverStarted = new Date();
var serverUrl = 'http://localhost:' + port + '/';
http.get(serverUrl + 'shutdown', function () {
startServerListening();
}).on('error', function () {
startServerListening();
});
function startServerListening() {
serverStarted = new Date();
console.log(' ...listening on ' + serverUrl + '/');
server.listen(port);
}
/** @typedef {import ('http').IncomingMessage} NodeRequest */
/** @typedef {import('http').ServerResponse} NodeResponse */
/**
* @param {NodeRequest} req
* @param {NodeResponse} res
*/
function nodeHandleRequest(req, res) {
if (req.url === '/shutdown') {
console.log('exiting now.');
server.close();
process.exit(0);
return;
} else if (req.url === '/main.js' || req.url === '/pako.js') {
var file = fs.readFileSync(__dirname + req.url);
res.setHeader('Content-Type', 'application/javascript');
res.end(file);
return;
}
var context = {
log: console.log.bind(console)
};
/** @type {Request} */
var abstractRequest = {
url: 'http://localhost:' + port + req.url
};
var resultPromise = handleRequest(
serverUrl,
serverUrl,
context,
abstractRequest
);
resultPromise.then(
function (result) {
var html = false;
if (result.headers) {
for (var hdr in result.headers) {
var val = result.headers[hdr];
if (typeof val === 'string' || (val && Array.isArray(val))) {
try {
if (hdr === 'Content-Type' && val === 'text/html') html = true;
res.setHeader(hdr, val);
}
catch (error) {
// ignore header errors
}
}
}
}
if (html) res.end(result.body + '<!-- server started: ' + serverStarted + '-->');
else res.end(result.body);
},
function (error) {
res.statusCode = 500;
res.end(
error.message + '\n\n' +
error.stack);
});
}
}
function runAsModule() {
}
function runInAzure() {
module.exports = handleAzureRequest;
var scriptBaseURL = '//tty.wtf/';
var azureWebsite = 'tty-wtf-node';
var baseURL = 'https://' + azureWebsite + '.azurewebsites.net/api/azurefn?';
/**
* @param {Context} context
* @param {Request} req
*/
function handleAzureRequest(context, req) {
return handleRequest(baseURL, scriptBaseURL, context, req);
}
}
/** @typedef {{
* log(...args: any[]): void;
* }} Context
*/