Repository navigation
Expand file tree
/
Copy pathmcfunction.html
More file actions
1099 lines (1012 loc) · 46.2 KB
/
Copy pathmcfunction.html
File metadata and controls
1099 lines (1012 loc) · 46.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#232323">
<meta name="description" content="A focused editor for Minecraft Bedrock mcfunction files.">
<link rel="manifest" href="/app/manifest.json">
<link rel="icon" href="/theme/favicon.png">
<link rel="stylesheet" href="https://mcbcode.com/theme/site.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.css">
<link id="theme-link" rel="stylesheet" href="https://mcbcode.com/theme/editor/default.css">
<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@400;500&display=swap" rel="stylesheet">
<title>mcbcode | mcfunction editor</title>
<style>
:root {
color-scheme: dark;
--page: #0c0c0c;
--bar: #323232;
--panel: #232323;
--panel-hover: #414141;
--text: #f0f0f0;
--muted: #bcbcbc;
--quiet: #868686;
--border: #454545;
--accent: #05ee93;
--blue: #00b2ff;
--pink: #e7007b;
--top-height: 48px;
--toolbar-height: 42px;
--status-height: 25px;
--radius: 6px;
}
* { box-sizing: border-box; }
html, body { width: 100%; height: 100%; margin: 0; overflow: hidden; }
[hidden] { display: none !important; }
body {
display: flex;
flex-direction: column;
background: var(--page);
color: var(--text);
font-family: mcfont, sans-serif;
font-size: 14px;
}
button, input, select { font: inherit; }
button { color: inherit; }
button:focus-visible, input:focus-visible, select:focus-visible, a:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
.titlebar {
height: var(--top-height);
flex: 0 0 var(--top-height);
display: flex;
align-items: center;
gap: 14px;
padding: 0 14px;
background: var(--bar);
border-bottom: 1px solid #202020;
}
.brand {
display: inline-flex;
align-items: center;
gap: 8px;
min-width: max-content;
color: var(--text);
font-family: mcfontb, mcfont, sans-serif;
font-size: 15px;
text-decoration: none;
}
.brand img { width: 25px; height: 25px; }
.brand span span { color: var(--accent); }
.divider { width: 1px; height: 22px; flex: 0 0 1px; background: #555; }
.file-title {
display: flex;
align-items: center;
min-width: 0;
flex: 1;
color: var(--muted);
}
.file-title input {
width: 190px;
min-width: 60px;
padding: 6px 8px;
border: 1px solid transparent;
border-radius: var(--radius) 0 0 var(--radius);
background: transparent;
color: var(--text);
font-family: mcfontb, mcfont, sans-serif;
outline: none;
}
.file-title input:hover, .file-title input:focus { border-color: #595959; background: #292929; }
.file-extension { padding: 7px 8px 7px 3px; color: var(--muted); white-space: nowrap; }
.top-actions { display: flex; align-items: center; gap: 7px; }
.top-actions a { color: var(--muted); text-decoration: none; }
.button {
min-height: 30px;
display: inline-flex;
align-items: center;
justify-content: center;
gap: 7px;
padding: 4px 10px;
border: 1px solid transparent;
border-radius: var(--radius);
background: transparent;
color: var(--text);
cursor: pointer;
font-family: mcfont, sans-serif;
white-space: nowrap;
}
.button:hover { background: var(--panel-hover); }
.button.subtle { color: var(--muted); }
.button.primary { background: var(--accent); color: #092318; font-family: mcfontb, mcfont, sans-serif; }
.button.primary:hover { background: #39f5ae; }
.button:disabled { opacity: .6; cursor: default; }
.toolbar {
height: var(--toolbar-height);
flex: 0 0 var(--toolbar-height);
display: flex;
align-items: center;
gap: 5px;
padding: 0 12px;
background: var(--bar);
border-bottom: 1px solid var(--border);
}
.toolbar .button { min-height: 29px; padding: 3px 9px; }
.toolbar-spacer { flex: 1; }
.toolbar-label { padding: 0 4px; color: var(--muted); font-size: 12px; }
.toolbar select {
height: 29px;
max-width: 148px;
padding: 2px 25px 2px 9px;
border: 1px solid #565656;
border-radius: var(--radius);
background: #292929;
color: var(--text);
cursor: pointer;
font-family: mcfont, sans-serif;
}
.editor-area { display: flex; flex: 1; min-height: 0; position: relative; background: var(--page); }
#editor-host { display: flex; flex: 1; min-width: 0; min-height: 0; }
.CodeMirror {
width: 100%;
height: 100%;
background: var(--page);
color: #ededed;
font-family: "Fira Code", Consolas, monospace;
font-size: 15px;
line-height: 1.55;
}
.CodeMirror-scroll { min-height: 0; padding: 12px 0 28px; }
.CodeMirror-gutters { border-right: 1px solid #202020; background: var(--page); }
.CodeMirror-linenumber { min-width: 44px; padding: 0 12px 0 8px; color: #747474; }
.CodeMirror-cursor { border-left: 2px solid var(--accent); }
.CodeMirror-selected { background: #05ee9340 !important; }
.CodeMirror-focused .CodeMirror-selected { background: #05ee9340 !important; }
.CodeMirror-matchingbracket { color: var(--accent) !important; outline: 1px solid #05ee9366; }
.CodeMirror-focused { outline: none; }
.CodeMirror textarea { font-family: "Fira Code", Consolas, monospace; }
.CodeMirror-hscrollbar, .CodeMirror-vscrollbar { outline: none; }
.statusbar {
height: var(--status-height);
flex: 0 0 var(--status-height);
display: flex;
align-items: center;
gap: 16px;
padding: 0 11px;
background: #252525;
color: #d0d0d0;
font-size: 11px;
}
.status-file { color: var(--accent); font-family: mcfontb, mcfont, sans-serif; }
.status-spacer { flex: 1; }
#save-status { color: var(--quiet); }
.statusbar button { padding: 0; border: 0; background: transparent; color: inherit; cursor: pointer; font-family: mcfont, sans-serif; }
.statusbar button:hover { color: var(--accent); }
.syntax-progress {
position: fixed;
z-index: 12;
left: 50%;
bottom: calc(var(--status-height) + 12px);
width: min(360px, calc(100vw - 24px));
display: flex;
align-items: center;
gap: 10px;
padding: 10px 12px;
transform: translateX(-50%);
border: 1px solid #505050;
border-radius: var(--radius);
background: #292929;
box-shadow: 0 8px 28px #0008;
color: var(--text);
font-size: 12px;
}
.syntax-progress-mark { width: 8px; height: 8px; flex: 0 0 8px; border-radius: 50%; background: var(--accent); }
.syntax-progress-body { flex: 1; min-width: 0; }
.syntax-progress-message { margin-bottom: 6px; }
.syntax-progress-track { height: 3px; overflow: hidden; border-radius: 2px; background: #4b4b4b; }
.syntax-progress-bar { width: 0; height: 100%; background: var(--accent); transition: width .15s ease; }
.syntax-progress-count { min-width: 34px; color: var(--muted); font: 11px "Fira Code", monospace; text-align: right; }
.find-panel {
position: absolute;
top: 10px;
right: 18px;
z-index: 5;
width: min(440px, calc(100vw - 30px));
padding: 10px;
border: 1px solid #555;
border-radius: var(--radius);
background: #262626;
box-shadow: 0 8px 28px #0009;
}
.find-row { display: flex; gap: 6px; margin-bottom: 7px; }
.find-row:last-child { margin-bottom: 0; }
.find-row input {
min-width: 0;
flex: 1;
padding: 7px 8px;
border: 1px solid #555;
border-radius: var(--radius);
background: #141414;
color: var(--text);
font-family: mcfont, sans-serif;
}
.find-row .button { min-height: 30px; padding: 4px 8px; background: #383838; border-color: #515151; }
.find-row .button:hover { background: #494949; }
#find-count { min-width: 55px; align-self: center; color: var(--muted); font-size: 11px; text-align: center; }
.modal-backdrop {
position: fixed;
inset: 0;
z-index: 20;
display: flex;
align-items: flex-start;
justify-content: center;
padding: 13vh 16px 16px;
background: #0009;
}
.dialog {
width: min(560px, 100%);
max-height: 75vh;
overflow: auto;
border: 1px solid #555;
border-radius: var(--radius);
background: #252525;
box-shadow: 0 18px 60px #0009;
}
.dialog-title { padding: 14px 16px 10px; color: #ededed; font-family: mcfontb, mcfont, sans-serif; font-size: 15px; }
.command-search { width: calc(100% - 28px); margin: 0 14px 11px; padding: 9px 10px; border: 1px solid #555; border-radius: var(--radius); background: #151515; color: var(--text); font-family: mcfont, sans-serif; }
.command-list { padding: 0 7px 8px; }
.command-option { width: 100%; display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 9px 10px; border: 0; border-radius: var(--radius); background: transparent; color: var(--text); text-align: left; cursor: pointer; font-family: mcfont, sans-serif; }
.command-option:hover, .command-option:focus { background: #3b3b3b; outline: none; }
.command-option kbd, kbd { padding: 2px 5px; border: 1px solid #555; border-radius: 4px; background: #171717; color: #d4d4d4; font: 11px "Fira Code", monospace; white-space: nowrap; }
.dialog-footer { padding: 9px 15px; border-top: 1px solid #444; color: #929292; font-size: 11px; }
.shortcut-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 0 22px; padding: 0 16px 14px; }
.shortcut-row { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 8px 0; border-bottom: 1px solid #3b3b3b; color: #d8d8d8; }
.visually-hidden { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0; }
@media (max-width: 700px) {
.titlebar { gap: 8px; padding: 0 8px; }
.brand span { display: none; }
.file-title input { width: 130px; }
.top-actions .account-link { display: none; }
.toolbar { gap: 2px; padding: 0 6px; }
.toolbar .button { padding: 3px 6px; }
.toolbar-label { display: none; }
.toolbar select { max-width: 112px; }
.shortcut-grid { grid-template-columns: 1fr; }
.statusbar { gap: 9px; }
.status-hide-small { display: none; }
}
@media (max-width: 460px) {
.titlebar { gap: 6px; }
.brand img { width: 21px; height: 21px; }
.divider { display: none; }
.file-title input { width: min(29vw, 105px); padding-left: 4px; }
.file-extension { padding-right: 1px; }
.toolbar .copy-action { display: none; }
.toolbar .shortcuts-action { display: none; }
.CodeMirror { font-size: 13px; }
.statusbar { gap: 7px; padding: 0 7px; font-size: 10px; }
}
</style>
</head>
<body>
<header class="titlebar">
<a class="brand" href="https://mcbcode.com" aria-label="mcbcode home">
<img src="https://mcbcode.com/theme/favicon.png" alt="">
<span>mcb<span>code</span></span>
</a>
<span class="divider" aria-hidden="true"></span>
<div class="file-title">
<label class="visually-hidden" for="filename">file name</label>
<input id="filename" maxlength="72" value="untitled" spellcheck="false" autocomplete="off">
<span class="file-extension">.mcfunction</span>
</div>
<div class="top-actions">
<a class="button subtle account-link" href="https://mcbcode.com/account">account</a>
<button class="button primary" id="save-button" type="button" hidden>save</button>
</div>
</header>
<nav class="toolbar" aria-label="editor actions">
<button class="button subtle" type="button" data-action="open">open file</button>
<button class="button subtle" type="button" data-action="download">download</button>
<button class="button subtle copy-action" type="button" data-action="copy">copy code</button>
<span class="toolbar-spacer"></span>
<button class="button subtle shortcuts-action" type="button" data-action="shortcuts">shortcuts</button>
<button class="button subtle" type="button" data-action="palette" title="command palette (ctrl+shift+p)">commands</button>
<label class="toolbar-label" for="theme-select">syntax</label>
<select id="theme-select" aria-label="syntax theme">
<option value="default">default</option>
<option value="neon">neon</option>
<option value="blue">blue</option>
<option value="soft">soft</option>
<option value="grayscale">grayscale</option>
<option value="solid">solid</option>
<option value="summer">summer</option>
<option value="modern">modern</option>
</select>
</nav>
<main class="editor-area" aria-label="mcfunction editor">
<div id="editor-host">
<label class="visually-hidden" for="editor-fallback">mcfunction code</label>
<textarea id="editor-fallback" spellcheck="false"># welcome to mcbcode
# remove this text to start coding
tellraw @a {"rawtext":[{"text":"§aThis is §2mcbCode"}]}</textarea>
</div>
<section class="find-panel" id="find-panel" hidden aria-label="find and replace">
<div class="find-row">
<label class="visually-hidden" for="find-query">find</label>
<input id="find-query" type="text" placeholder="find" autocomplete="off">
<span id="find-count" aria-live="polite"></span>
<button class="button" type="button" data-action="find-previous" title="previous match">up</button>
<button class="button" type="button" data-action="find-next" title="next match">down</button>
<button class="button" type="button" data-action="close-find" aria-label="close find">close</button>
</div>
<div class="find-row">
<label class="visually-hidden" for="replace-query">replace with</label>
<input id="replace-query" type="text" placeholder="replace with" autocomplete="off">
<button class="button" type="button" data-action="replace">replace</button>
<button class="button" type="button" data-action="replace-all">replace all</button>
</div>
</section>
</main>
<div class="syntax-progress" id="syntax-progress" role="status" aria-live="polite" hidden>
<span class="syntax-progress-mark" aria-hidden="true"></span>
<div class="syntax-progress-body">
<div class="syntax-progress-message" id="syntax-progress-message">loading command syntax</div>
<div class="syntax-progress-track"><div class="syntax-progress-bar" id="syntax-progress-bar"></div></div>
</div>
<span class="syntax-progress-count" id="syntax-progress-count">0/0</span>
</div>
<footer class="statusbar">
<span class="status-file">mcfunction</span>
<span id="cursor-position">line 1, col 1</span>
<span class="status-hide-small" id="selection-status">spaces: 4</span>
<span class="status-spacer"></span>
<span class="status-hide-small" id="save-status">local draft</span>
<button type="button" data-action="shortcuts">keyboard shortcuts</button>
</footer>
<input id="open-file" class="visually-hidden" type="file" accept=".mcfunction,.txt,text/plain">
<div class="modal-backdrop" id="palette-backdrop" hidden>
<section class="dialog" role="dialog" aria-modal="true" aria-labelledby="palette-title">
<div class="dialog-title" id="palette-title">command palette</div>
<input class="command-search" id="command-search" type="text" placeholder="type a command" autocomplete="off" aria-label="filter commands">
<div class="command-list" id="command-list"></div>
<div class="dialog-footer">use the arrow keys to choose an action, enter to run, escape to close</div>
</section>
</div>
<div class="modal-backdrop" id="shortcuts-backdrop" hidden>
<section class="dialog" role="dialog" aria-modal="true" aria-labelledby="shortcuts-title" tabindex="-1">
<div class="dialog-title" id="shortcuts-title">keyboard shortcuts</div>
<div class="shortcut-grid">
<div class="shortcut-row"><span>command palette</span><kbd>ctrl+shift+p</kbd></div>
<div class="shortcut-row"><span>find / replace</span><kbd>ctrl+f</kbd></div>
<div class="shortcut-row"><span>save to account</span><kbd>ctrl+shift+s</kbd></div>
<div class="shortcut-row"><span>download .mcfunction</span><kbd>ctrl+s</kbd></div>
<div class="shortcut-row"><span>open local file</span><kbd>ctrl+o</kbd></div>
<div class="shortcut-row"><span>copy code</span><kbd>ctrl+shift+c</kbd></div>
<div class="shortcut-row"><span>undo / redo</span><kbd>ctrl+z / ctrl+y</kbd></div>
<div class="shortcut-row"><span>select next occurrence</span><kbd>ctrl+d</kbd></div>
<div class="shortcut-row"><span>toggle line comment</span><kbd>ctrl+/</kbd></div>
<div class="shortcut-row"><span>duplicate line</span><kbd>alt+shift+up/down</kbd></div>
<div class="shortcut-row"><span>move line</span><kbd>alt+up/down</kbd></div>
<div class="shortcut-row"><span>delete line</span><kbd>ctrl+shift+k</kbd></div>
<div class="shortcut-row"><span>select line</span><kbd>ctrl+l</kbd></div>
<div class="shortcut-row"><span>indent / outdent</span><kbd>tab / shift+tab</kbd></div>
<div class="shortcut-row"><span>toggle word wrap</span><kbd>alt+z</kbd></div>
<div class="shortcut-row"><span>delete all code</span><kbd>ctrl+alt+d</kbd></div>
</div>
<div class="dialog-footer">on mac, use command instead of ctrl</div>
</section>
</div>
<script src="https://mcbcode.com/backend/grammar.js"></script>
<script src="https://mcbcode.com/backend/highlight.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/addon/edit/closebrackets.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/addon/search/searchcursor.min.js"></script>
<script>
(() => {
const $ = (selector) => document.querySelector(selector);
const authBase = 'https://auth.mcbcode.com';
const themeNames = ['default', 'neon', 'blue', 'soft', 'grayscale', 'solid', 'summer', 'modern'];
const draftKey = 'mcbcode-mcfunction-draft-v3';
const params = new URLSearchParams(window.location.search);
const originalGrammarLoader = window.fetchCommandGrammar;
let editor;
let currentSaveId = null;
let currentUserId = null;
let highlightRequest = 0;
let highlightMarks = [];
let highlightTimer;
let draftTimer;
let grammarHideTimer;
let grammarActive = 0;
let grammarCompleted = 0;
let grammarTotal = 0;
const grammarTasks = new Map();
let wordWrap = false;
const fallback = $('#editor-fallback');
let startingText = fallback.value;
let startingFilename = 'untitled';
try {
const draft = JSON.parse(localStorage.getItem(draftKey) || 'null');
if (draft && typeof draft.text === 'string' && !params.has('save')) {
startingText = draft.text;
startingFilename = draft.filename || 'untitled';
}
} catch {}
$('#filename').value = startingFilename;
const setLocalStatus = (message) => { $('#save-status').textContent = message; };
function hasCommandGrammar(command) {
try { return Boolean(commandCache[command]); } catch { return false; }
}
function updateGrammarProgress() {
const popup = $('#syntax-progress');
const finished = grammarActive === 0 && grammarTotal > 0 && grammarCompleted >= grammarTotal;
const completed = Math.min(grammarCompleted, grammarTotal);
$('#syntax-progress-message').textContent = finished ? 'command syntax ready' : 'loading command syntax';
$('#syntax-progress-count').textContent = `${completed}/${grammarTotal}`;
$('#syntax-progress-bar').style.width = `${grammarTotal ? (completed / grammarTotal) * 100 : 0}%`;
popup.hidden = false;
clearTimeout(grammarHideTimer);
if (finished) grammarHideTimer = setTimeout(() => { popup.hidden = true; }, 1000);
}
function resetGrammarProgress() {
if (grammarActive === 0 && grammarCompleted >= grammarTotal) {
grammarCompleted = 0;
grammarTotal = 0;
clearTimeout(grammarHideTimer);
}
}
function requestCommandGrammar(command, reserved = false) {
if (!command || hasCommandGrammar(command)) return Promise.resolve();
if (grammarTasks.has(command)) return grammarTasks.get(command);
if (!reserved) {
resetGrammarProgress();
grammarTotal += 1;
}
grammarActive += 1;
updateGrammarProgress();
const task = Promise.resolve()
.then(() => typeof originalGrammarLoader === 'function' ? originalGrammarLoader(command) : undefined)
.catch(() => {})
.finally(() => {
grammarActive -= 1;
grammarCompleted += 1;
updateGrammarProgress();
});
grammarTasks.set(command, task);
return task;
}
if (typeof originalGrammarLoader === 'function') {
window.fetchCommandGrammar = (command) => requestCommandGrammar(command);
}
function commandsInText(text) {
const commands = new Set();
for (const rawLine of text.split('\n')) {
const line = rawLine.trim();
if (!line || line.startsWith('#') || line.startsWith('/')) continue;
const first = line.match(/^([a-z0-9_]+)/i)?.[1]?.toLowerCase();
if (first && first.length > 1) commands.add(first);
if (first === 'execute') {
for (const match of line.matchAll(/\brun\s+([a-z0-9_]+)/gi)) {
if (match[1].length > 1) commands.add(match[1].toLowerCase());
}
}
}
return [...commands];
}
async function preloadCommandGrammars(text) {
if (typeof originalGrammarLoader !== 'function') return;
const commands = commandsInText(text);
const toLoad = commands.filter((command) => !hasCommandGrammar(command) && !grammarTasks.has(command));
const existingTasks = commands.map((command) => grammarTasks.get(command)).filter(Boolean);
if (toLoad.length) {
resetGrammarProgress();
grammarTotal += toLoad.length;
updateGrammarProgress();
let next = 0;
const workers = Array.from({ length: Math.min(4, toLoad.length) }, async () => {
while (next < toLoad.length) {
const command = toLoad[next++];
await requestCommandGrammar(command, true);
}
});
await Promise.all([...workers, ...existingTasks]);
} else if (existingTasks.length) {
await Promise.all(existingTasks);
}
}
function getFilename() {
return ($('#filename').value || 'untitled').replace(/[^a-z0-9_-]/gi, '_').slice(0, 72) || 'untitled';
}
function updateTitle() {
document.title = `${getFilename()}.mcfunction | mcbcode`;
}
function setTheme(name) {
const theme = themeNames.includes(name) ? name : 'default';
const link = $('#theme-link');
link.href = `https://mcbcode.com/theme/editor/${theme}.css`;
$('#theme-select').value = theme;
try { localStorage.setItem('selected-editor-theme', theme); } catch {}
}
function downloadFile(extension = 'mcfunction') {
const value = editor ? editor.getValue() : fallback.value;
const blob = new Blob([value], { type: 'text/plain;charset=utf-8' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = `${getFilename()}.${extension}`;
document.body.append(link);
link.click();
link.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
async function copyCode() {
const value = editor ? editor.getValue() : fallback.value;
try {
await navigator.clipboard.writeText(value);
setLocalStatus('copied');
setTimeout(() => setLocalStatus('local draft'), 1500);
} catch {
setLocalStatus('clipboard access denied');
}
}
function saveDraft() {
try {
localStorage.setItem(draftKey, JSON.stringify({ text: editor.getValue(), filename: getFilename() }));
setLocalStatus('local draft');
} catch { setLocalStatus('local storage unavailable'); }
}
function scheduleDraftSave() {
setLocalStatus('saving');
clearTimeout(draftTimer);
draftTimer = setTimeout(saveDraft, 300);
}
async function saveToAccount() {
const button = $('#save-button');
if (!currentUserId || button.disabled || button.hidden) return;
button.disabled = true;
button.textContent = 'saving…';
try {
const response = await fetch(`${authBase}/save`, {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ save_id: currentSaveId, content: editor.getValue(), filename: getFilename() })
});
const data = await response.json();
if (!response.ok || !data.save_id) throw new Error('save failed');
currentSaveId = data.save_id;
const url = new URL(window.location.href);
url.searchParams.set('save', currentSaveId);
window.history.replaceState({}, '', url.toString());
button.textContent = 'saved';
setLocalStatus('saved to account');
setTimeout(() => { button.textContent = 'save'; }, 1800);
} catch {
button.textContent = 'save failed';
setTimeout(() => { button.textContent = 'save'; }, 2200);
} finally { button.disabled = false; }
}
function updateSaveButton(ownerId) {
const button = $('#save-button');
button.hidden = !(currentUserId !== null && (currentUserId === ownerId || ownerId === null));
}
async function loadSharedSave(saveId) {
try {
const response = await fetch(`${authBase}/save?id=${encodeURIComponent(saveId)}`, { credentials: 'include' });
if (!response.ok) throw new Error('share not found');
const data = await response.json();
currentSaveId = data.save_id;
editor.setValue(data.content || '');
if (data.filename) $('#filename').value = data.filename;
updateTitle();
updateSaveButton(data.owner_id);
setLocalStatus('shared file');
} catch {
editor.setValue('# this share code does not exist');
$('#save-button').hidden = true;
setLocalStatus('share code not found');
}
}
async function initializeAccount() {
try {
const response = await fetch(`${authBase}/me`, { credentials: 'include' });
if (response.ok) currentUserId = (await response.json()).id;
} catch {}
const shareId = params.get('save');
if (shareId) await loadSharedSave(shareId);
else updateSaveButton(null);
}
function clearHighlights() {
for (const mark of highlightMarks) mark.clear();
highlightMarks = [];
}
function applyLanguageMarks(source, html, requestId) {
if (!editor || requestId !== highlightRequest || source !== editor.getValue()) return;
clearHighlights();
const rows = html.split('\n');
const parser = new DOMParser();
const allowedClasses = new Set(['hl-command', 'hl-selector', 'hl-item', 'hl-number', 'hl-comment', 'hl-error', 'hl-word', 'hl-colorcode']);
function visit(node, classes, color, absoluteStart, offset) {
if (node.nodeType === Node.TEXT_NODE) {
const text = node.nodeValue || '';
if (!text) return;
const from = absoluteStart + offset.value;
offset.value += text.length;
const markOptions = {};
const safeClasses = classes.filter((name) => allowedClasses.has(name));
if (safeClasses.length) markOptions.className = safeClasses.join(' ');
if (color && /^(#[\da-f]{3,8}|rgb\([\d, .%]+\))$/i.test(color)) markOptions.css = `color:${color}`;
if (Object.keys(markOptions).length) highlightMarks.push(editor.markText(editor.posFromIndex(from), editor.posFromIndex(from + text.length), markOptions));
return;
}
if (node.nodeType !== Node.ELEMENT_NODE) return;
const nestedClasses = classes.slice();
for (const name of node.classList) if (allowedClasses.has(name)) nestedClasses.push(name);
const nestedColor = node.style?.color || color;
for (const child of node.childNodes) visit(child, nestedClasses, nestedColor, absoluteStart, offset);
}
for (let line = 0; line < editor.lineCount(); line += 1) {
const parsed = parser.parseFromString(rows[line] || '', 'text/html');
const offset = { value: 0 };
const absoluteStart = editor.indexFromPos({ line, ch: 0 });
for (const child of parsed.body.childNodes) visit(child, [], null, absoluteStart, offset);
}
}
function updateHighlighting() {
const requestId = ++highlightRequest;
clearTimeout(highlightTimer);
highlightTimer = setTimeout(async () => {
const source = editor ? editor.getValue() : '';
if (typeof window.applyHighlighting !== 'function') return;
clearHighlights();
await preloadCommandGrammars(source);
if (requestId !== highlightRequest || !editor || source !== editor.getValue()) return;
try {
const html = await window.applyHighlighting(source);
applyLanguageMarks(source, html, requestId);
} catch {}
}, 120);
}
window.updateHighlighting = updateHighlighting;
function saveCurrentDraft() {
if (!editor) return;
try { localStorage.setItem(draftKey, JSON.stringify({ text: editor.getValue(), filename: getFilename() })); } catch {}
}
function updatePosition() {
if (!editor) return;
const cursor = editor.getCursor();
$('#cursor-position').textContent = `line ${cursor.line + 1}, col ${cursor.ch + 1}`;
const selection = editor.getSelection();
$('#selection-status').textContent = selection ? `${selection.length} selected` : 'spaces: 4';
}
function showFind(replace = false) {
const panel = $('#find-panel');
panel.hidden = false;
const field = $('#find-query');
field.focus();
field.select();
if (replace) $('#replace-query').focus();
}
function closeFind() {
$('#find-panel').hidden = true;
if (editor) editor.focus();
}
function searchCursor(query, start) {
if (!query) return null;
return editor.getSearchCursor(query, start, { caseFold: true });
}
function findMatch(direction = 1) {
const query = $('#find-query').value;
if (!query) return;
const start = direction > 0 ? editor.getCursor('to') : editor.getCursor('from');
const cursor = searchCursor(query, start);
const found = direction > 0 ? cursor.findNext() : cursor.findPrevious();
if (found) {
editor.setSelection(cursor.from(), cursor.to());
editor.scrollIntoView({ from: cursor.from(), to: cursor.to() }, 80);
$('#find-count').textContent = 'match';
return;
}
const lastLine = editor.lastLine();
const wrapStart = direction > 0 ? CodeMirror.Pos(0, 0) : CodeMirror.Pos(lastLine, editor.getLine(lastLine).length);
const wrapped = searchCursor(query, wrapStart);
const wrapFound = direction > 0 ? wrapped.findNext() : wrapped.findPrevious();
if (wrapFound) {
editor.setSelection(wrapped.from(), wrapped.to());
editor.scrollIntoView({ from: wrapped.from(), to: wrapped.to() }, 80);
$('#find-count').textContent = 'wrapped';
} else $('#find-count').textContent = 'no match';
}
function replaceCurrent() {
const query = $('#find-query').value;
if (!query) return;
const selection = editor.getSelection();
if (selection && selection.toLowerCase() === query.toLowerCase()) {
editor.replaceSelection($('#replace-query').value, 'around');
}
findMatch(1);
}
function replaceAll() {
const query = $('#find-query').value;
if (!query) return;
const replacement = $('#replace-query').value;
const cursor = searchCursor(query, CodeMirror.Pos(0, 0));
let count = 0;
editor.operation(() => {
while (cursor.findNext()) {
cursor.replace(replacement);
count += 1;
}
});
$('#find-count').textContent = `${count} replaced`;
}
function selectNextOccurrence() {
let query = editor.getSelection();
let start = editor.getCursor('to');
if (!query) {
const word = editor.findWordAt(editor.getCursor());
query = editor.getRange(word.anchor, word.head);
if (!query) return;
editor.setSelection(word.anchor, word.head);
start = word.head;
}
const cursor = searchCursor(query, start);
if (cursor.findNext()) editor.addSelection(cursor.from(), cursor.to());
}
function toggleLineComment() {
const selections = editor.listSelections();
const lines = new Set();
for (const range of selections) {
const first = Math.min(range.anchor.line, range.head.line);
const last = Math.max(range.anchor.line, range.head.line);
for (let line = first; line <= last; line += 1) lines.add(line);
}
const numbers = [...lines].sort((a, b) => a - b);
const allCommented = numbers.every((line) => /^\s*#/.test(editor.getLine(line)));
editor.operation(() => {
for (const line of numbers.reverse()) {
const text = editor.getLine(line);
const indent = text.match(/^\s*/)[0].length;
if (allCommented) {
const removeAt = text.indexOf('#', indent);
editor.replaceRange('', CodeMirror.Pos(line, removeAt), CodeMirror.Pos(line, removeAt + 1));
if (text[removeAt + 1] === ' ') editor.replaceRange('', CodeMirror.Pos(line, removeAt), CodeMirror.Pos(line, removeAt + 1));
} else editor.replaceRange('# ', CodeMirror.Pos(line, indent));
}
});
}
function moveLine(direction, duplicate = false) {
const selections = editor.listSelections();
const first = Math.min(...selections.map((range) => Math.min(range.anchor.line, range.head.line)));
const last = Math.max(...selections.map((range) => Math.max(range.anchor.line, range.head.line)));
const doc = editor.getDoc();
const allLines = doc.getValue().split('\n');
const moving = allLines.slice(first, last + 1);
if (duplicate) {
const copied = direction < 0
? [...allLines.slice(0, first), ...moving, ...allLines.slice(first)].join('\n')
: [...allLines.slice(0, last + 1), ...moving, ...allLines.slice(last + 1)].join('\n');
editor.replaceRange(copied, CodeMirror.Pos(0, 0), CodeMirror.Pos(doc.lastLine(), doc.getLine(doc.lastLine()).length));
return;
}
if ((direction < 0 && first === 0) || (direction > 0 && last === doc.lastLine())) return;
const reordered = allLines.slice();
if (direction < 0) reordered.splice(first - 1, last - first + 2, ...moving, allLines[first - 1]);
else reordered.splice(first, last - first + 2, allLines[last + 1], ...moving);
const newFirst = first + direction;
const newLast = last + direction;
editor.operation(() => {
editor.replaceRange(reordered.join('\n'), CodeMirror.Pos(0, 0), CodeMirror.Pos(doc.lastLine(), doc.getLine(doc.lastLine()).length));
editor.setSelection(CodeMirror.Pos(newFirst, 0), CodeMirror.Pos(newLast, editor.getLine(newLast).length));
});
}
function deleteCurrentLine() {
const line = editor.getCursor().line;
if (editor.lineCount() === 1) editor.setValue('');
else editor.replaceRange('', CodeMirror.Pos(line, 0), CodeMirror.Pos(line + 1, 0));
}
function addLine(direction) {
const cursor = editor.getCursor();
if (direction > 0) {
editor.replaceRange('\n', CodeMirror.Pos(cursor.line, editor.getLine(cursor.line).length));
editor.setCursor(cursor.line + 1, 0);
} else {
editor.replaceRange('\n', CodeMirror.Pos(cursor.line, 0));
editor.setCursor(cursor.line, 0);
}
}
function clearCode() {
if (window.confirm('delete all code in this file?')) editor.setValue('');
}
function openFilePicker() { $('#open-file').click(); }
function openPalette() {
$('#palette-backdrop').hidden = false;
$('#command-search').value = '';
renderCommands('');
$('#command-search').focus();
}
function closePalette() { $('#palette-backdrop').hidden = true; editor.focus(); }
function openShortcuts() {
$('#shortcuts-backdrop').hidden = false;
$('#shortcuts-backdrop').querySelector('.dialog').focus();
}
function closeShortcuts() { $('#shortcuts-backdrop').hidden = true; editor.focus(); }
const paletteActions = [
['download .mcfunction', 'ctrl+s', () => downloadFile('mcfunction')],
['download as .txt', '', () => downloadFile('txt')],
['open local file', 'ctrl+o', openFilePicker],
['copy code', 'ctrl+shift+c', copyCode],
['find and replace', 'ctrl+f', () => showFind(false)],
['toggle word wrap', 'alt+z', () => { wordWrap = !wordWrap; editor.setOption('lineWrapping', wordWrap); }],
['toggle line comment', 'ctrl+/', toggleLineComment],
['keyboard shortcuts', '', openShortcuts]
];
function renderCommands(filter) {
const list = $('#command-list');
list.replaceChildren();
const matches = paletteActions.filter(([label]) => label.includes(filter.toLowerCase()));
for (const [label, shortcut, action] of matches) {
const button = document.createElement('button');
button.type = 'button';
button.className = 'command-option';
const name = document.createElement('span');
name.textContent = label;
const shortcutText = document.createElement('kbd');
shortcutText.textContent = shortcut;
button.append(name, shortcutText);
button.addEventListener('click', () => { closePalette(); action(); });
list.append(button);
}
if (!matches.length) {
const empty = document.createElement('div');
empty.className = 'command-option';
empty.textContent = 'no matching commands';
list.append(empty);
}
}
function buildEditor() {
if (!window.CodeMirror) {
fallback.style.width = '100%';
fallback.style.height = '100%';
fallback.style.resize = 'none';
fallback.style.background = '#0c0c0c';
fallback.style.color = '#eee';
fallback.style.border = '0';
fallback.style.padding = '16px';
fallback.style.font = '15px "Fira Code", monospace';
setLocalStatus('editor library unavailable; plain text mode');
return;
}
CodeMirror.defineMode('mcfunction', () => ({
startState: () => ({}),
token: (stream) => { stream.skipToEnd(); return null; }
}));
editor = CodeMirror($('#editor-host'), {
value: startingText,
mode: 'mcfunction',
lineNumbers: true,
lineWrapping: wordWrap,
tabSize: 4,
indentUnit: 4,
indentWithTabs: false,
matchBrackets: true,
autoCloseBrackets: true,
autofocus: true,
viewportMargin: 20,
extraKeys: {
'Ctrl-S': () => downloadFile('mcfunction'),
'Cmd-S': () => downloadFile('mcfunction'),
'Ctrl-Shift-S': saveToAccount,
'Cmd-Shift-S': saveToAccount,
'Ctrl-Shift-C': copyCode,
'Cmd-Shift-C': copyCode,
'Ctrl-Shift-P': openPalette,
'Cmd-Shift-P': openPalette,
'Ctrl-F': () => showFind(false),
'Cmd-F': () => showFind(false),
'Ctrl-H': () => showFind(true),
'Cmd-Alt-F': () => showFind(true),
'Ctrl-O': openFilePicker,
'Cmd-O': openFilePicker,
'Ctrl-D': selectNextOccurrence,
'Cmd-D': selectNextOccurrence,
'Ctrl-/': toggleLineComment,
'Cmd-/': toggleLineComment,
'Ctrl-Shift-K': deleteCurrentLine,
'Cmd-Shift-K': deleteCurrentLine,
'Ctrl-L': () => { const line = editor.getCursor().line; editor.setSelection(CodeMirror.Pos(line, 0), CodeMirror.Pos(line, editor.getLine(line).length)); },
'Cmd-L': () => { const line = editor.getCursor().line; editor.setSelection(CodeMirror.Pos(line, 0), CodeMirror.Pos(line, editor.getLine(line).length)); },
'Alt-Up': () => moveLine(-1),
'Alt-Down': () => moveLine(1),
'Alt-Shift-Up': () => moveLine(-1, true),
'Alt-Shift-Down': () => moveLine(1, true),