-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.js
1484 lines (1371 loc) · 63.3 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
const replacements_id = {
"=y\n": "=т\n",
"ID table": "ID таблиця",
"ID_table": "ID таблиця",
"editions": "видання",
"{{edition|": "{{el|",
"firstcolumnname": "назвапершогостовпця",
"nonameid": "немаєназвиid",
"notnamespaced": "безінтервалуміжіменами",
"shownumericids": "показатичисловийid",
"showaliasids": "показатипсевдонімиid",
"showfluidtags": "показатитеґирідини",
"showblocktags": "показатитеґиблока",
"edition": "видання",
"showitemtags": "показатитеґипредмета",
"showentitytags": "показатитеґисутности",
"showforms": "показатиформи",
"notshowbeitemforms": "непоказуватиформипредмета",
"itemform": "формапредмета",
"itemform2": "формапредмета2",
"generatetranslationkeys": "генеруватиключіперекладу",
"nocat": "некат",
"displayname": "відображуванеім'я",
"spritename": "назваспрайту",
"nameid": "назваid",
"aliasid": "псевдонімиid",
"fluidtags": "теґирідини",
"blocktags": "теґиблока",
"itemtags": "теґипредмета",
"entitytags": "теґисутности",
"translationkey": "ключперекладу",
"translationtype": "типперекладу",
"foot=": "підвал=",
"foot =": "підвал =",
"spritetype=block": "типспрайту=блок",
"spritetype=item": "типспрайту=предмет",
"spritetype=entity": "типспрайту=сутність",
"spritetype=biome": "типспрайту=біом",
"spritetype=environment": "типспрайту=оточення",
"spritetype=env": "типспрайту=оточення",
"spritetype=effect": "типспрайту=ефект",
"form=block": "форма=блок",
"form=item": "форма=предмет",
"form=entity": "форма=сутність",
"form=biome": "форма=біом",
"form=environment": "форма=оточення",
"form=effect": "форма=ефект",
"form": "форма",
"Block entity": "Блок-сутність",
"No displayed name": "Немає відображуваного імені"
};
const replacements_sound = {
"SoundLine": "ЗвуковийРядок",
"SoundTable": "ЗвуковаТаблиця",
"Sound table": "Звукова таблиця",
"sound": "звук",
"sound1": "звук1",
"sound2": "звук2",
"sound3": "звук3",
"sound4": "звук4",
"sound5": "звук5",
"sound6": "звук6",
"sound7": "звук7",
"sound8": "звук8",
"subtitle=": "субтитри=",
"source=block": "джерело=блок",
"description": "опис",
"translationkeynote": "ключперекладунотатка",
"translationkey": "ключперекладу",
"pitch": "висотазвуку",
"distance": "відстань",
"rowspan": "рядки",
"volume": "гучність",
"foot=": "підвал=",
"nocat": "некат",
"type": "тип",
"title=": "назва=",
"title =": "назва =",
"Baby:": "Дитинча:",
"=''varies''": "=''варіюється''",
"=master": "=загальне",
"=music": "=музика",
"=record": "=платівка",
"=weather": "=погода",
"=hostile": "=ворожі",
"=neutral": "=нейтральні",
"=player": "=гравець",
"overridesource": "перевизначитиджерело",
"source": "джерело",
"=ambient": "=середовище",
"voice": "голос",
"dependent": "залежний",
"''None''": "''Немає''",
"templatepage": "сторінкашаблону",
"idnote": "idнотатка",
"Unused sound event": "Невикористана звукова подія",
"Once the block has broken": "Коли блок зламано",
"When the block is placed": "Коли блок розміщено",
"While the block is in the process of being broken": "Поки блок знаходиться в процесі руйнування",
"Falling on the block with fall damage": "Падіння на блок з отриманням шкоди",
"Walking on the block": "Ходіння по блоку",
"Jumping from the block": "Стрибання з блока",
"Falling on the block without fall damage": "Падіння на блок без отримання шкоди"
};
const replacements_vn = {
"Version nav": "Версія навігація",
"version nav": "Версія навігація",
"Infobox version": "Версія навігація",
"infobox version": "Версія навігація",
"othereditions": "іншівидання",
"edition": "видання",
"title": "назва",
"|server": "|сервер",
"| server": "| сервер",
"prefix": "префікс",
"image": "зобр",
"name": "ім'я",
"|client": "|клієнт",
"| client": "| клієнт",
"build": "збірка",
"internal": "внутрішній",
"versioncode": "кодверсії",
"prevparent": "поперверсія",
"|prev": "|попер",
"| prev": "| попер",
"nextparent": "настверсія",
"next": "наст",
"type": "тип",
"unreleased": "невипущено",
"planned": "заплановано",
"|date": "|дата",
"| date": "| дата",
"compiled": "скомпільований",
"devversions": "поперзбірки",
"version": "версія",
"hash": "хеш",
"downloads": "завантаження",
"file=": "файл=",
"file =": "файл =",
"other": "інше",
"maps": "карти",
"map": "карта",
"protocol_manual": "протокол_вручну",
"data_manual": "дані_вручну",
"no_protocol": "немає_протоколу",
"no_data": "немає_даних",
"no_": "немає_",
"_manual": "_вручну",
"parent": "знімокдля",
"{{vl": "{{вер",
"dl=": "зп=",
"dl =": "зп =",
"Client": "Клієнт",
"Server": "Сервер",
"editorver": "editorвер",
"No corresponding server": "Немає відповідного сервера",
"vernum": "версія"
};
const replacements_entity = {
"health": "здоров'я",
"armor": "обладунки",
"behavior": "поведінка",
"classification": "класифікація",
"family": "сімейство",
"damage": "атака",
"size": "розмір",
"group": "група",
"speed": "швидкість",
"knockbackresistance": "стійкістьдовіддачі",
"spawn": "спавн",
"equipment": "екіпірування",
"usableitems": "корисніпредмети",
"rarity": "рідкісність",
"notes": "примітки",
"extratext": "додатковийтекст",
"invimage": "інвзображення",
"image": "зобр",
"{{Infobox entity": "{{Сутність",
"{{Entity": "{{Сутність",
"{{hp": "{{оз",
"{{drop": "{{дроп",
"caption": "підпис"
};
const replacements_block = {
"Infobox block": "Блок",
"rarity": "рідкісність",
"renewable": "поновл",
"stackable": "склад",
"tool": "інструмент",
"title": "назва",
"hardness": "міцн",
"durability": "стійкість",
"light": "світ",
"transparent": "прозор",
"waterloggable": "затопл",
"heals": "відн",
"flammable": "займист",
"lavasusceptible": "загорвлави",
"= yes": "= так",
"= no": "= ні",
"=yes": "=так",
"=no": "=ні",
"Yes": "Так",
"No": "Ні",
"invimage": "інвзображення",
"image": "зобр",
"group": "група",
"caption": "підпис",
"extratext": "додатковийтекст",
"tntres": "вибухост",
"Common": "Звичайний",
"Uncommon": "Незвичайний",
"Rare": "Рідкісний",
"Epic": "Епічний",
"common": "звичайний",
"uncommon": "незвичайний",
"rare": "рідкісний",
"epic": "епічний"
};
const replacements_drops = {
"DropsTableHead": "Голова таблиці дропу",
"DropsLine": "Рядок дропу",
"DropsTableFoot": "Підвал таблиці дропу",
"version": "версія",
"image": "зобр",
"namelink": "посиланняназви",
"namenote": "нотатканазви",
"name": "назва",
"rollchancenote": "нотаткашансунауспіх",
"rollchance": "шанснауспіх",
"lootingquantity": "кількістьзграбунком",
"quantitylimit": "обмежкількости",
"dropchance": "шансдропу",
"lootingchance": "шансзграбунком",
"playerkill": "вбивствогравця",
"= yes": "= так",
"= no": "= ні",
"=yes": "=так",
"=no": "=ні",
"Yes": "Так",
"No": "Ні",
"quantity": "кількість"
};
const replacements_history = {
"HistoryTable": "ТаблицяІсторії",
"HistoryLine": "РядокІсторії",
"|dev": "|збірка",
"|slink": "|поперпосилання",
"|link": "|посилання",
"|experiment": "|експеримент",
"|exp": "|експ",
"[[File:": "[[Файл:",
"1.13/Flattening": "1.13 (Java Edition)/Flattening"
};
const replacements_looming = {
"{{Looming": "{{Ткацтво",
"{{looming": "{{ткацтво",
"|head": "|голова",
"| head": "| голова",
"|foot": "|підвал",
"| foot": "| підвал",
"name": "назва",
"Blink": "СтягПосилання",
"Olink": "ВихідПосилання",
"showdescription": "показатиопис",
"description": "опис",
"ingredients": "інгредієнти"
};
const replacements_biome = {
"{{Infobox biome": "{{Біом",
"title": "назва",
"imagesize": "зобр1розмір",
"image": "зобр",
"group": "група",
"caption": "підпис",
"extratext": "додатковийтекст",
"data": "дані",
"structures": "структури",
"features": "особливості",
"blocks": "блоки",
"temperature": "температура",
"downfall": "падіння",
"precipitation": "опади",
"snow_accumulation": "накопичення_снігу",
"skycolor": "колірнеба",
"underwaterfogcolor": "колірпідводноготуману",
"fogcolor": "коліртуману",
"grasscolor": "коліртрави",
"foliagecolor": "колірлистя",
"watercolor": "колірводи",
"EnvLink": "Посилання/Оточення",
"BlockLink": "Посилання/Блок",
"= yes": "= так",
"= no": "= ні",
"=yes": "=так",
"=no": "=ні",
"Yes": "Так",
"No": "Ні",
"{{only": "{{тільки",
"{{color": "{{колір",
"short=y": "короткий=т",
"short=1": "короткий=1"
};
const replacements_spawn = {
"Spawn attempt succeeds only in slime chunks.": "Спроба заспавнитися вдається лише в слимакових чанках.",
"{{Spawn table": "{{Таблиця появи",
"{{Spawn row": "{{Ряд появи",
"title": "назва",
"image": "зобр",
"group": "група",
"caption": "підпис",
"edition": "видання",
"watercreature": "водянаістота",
"waterambient": "воднеоточення",
"creature": "істота",
"monster": "монстр",
"ambient": "оточення",
"underground": "підземний",
"name": "ім'я",
"weight": "вага",
"size": "розмір",
"charge": "заряд",
"budget": "витрати",
"note": "примітка",
"notename": "назвапримітки",
"Upcoming": "Заплановане",
"Until": "Доки"
};
const replacements_item = {
"{{Infobox item": "{{Предмет",
"title": "назва",
"imagesize": "зобр1розмір",
"invimage": "інвзображення",
"image": "зобр",
"group": "група",
"caption": "підпис",
"extratext": "додатковийтекст",
"rarity": "рідкісність",
"durability": "міцн",
"armor": "захист",
"renewable": "поновл",
"stackable": "склад",
"heals": "відновлює",
"effects": "ефекти",
"Yes": "Так",
"No": "Ні",
"hunger": "голод",
"Renewable resource#Vault|except via ominous vault": "Поновлювані ресурси#Сховище|хіба що через зловісне сховище",
"Common": "Звичайний",
"Uncommon": "Незвичайний",
"Rare": "Рідкісний",
"Epic": "Епічний",
"common": "звичайний",
"uncommon": "незвичайний",
"rare": "рідкісний",
"epic": "епічний",
"only": "тільки",
"short": "короткий",
"upcoming": "заплановане",
"until": "доки",
"+1 in": "+1 у"
};
const replacements_itemEntity = {
"{{Infobox item entity": "{{Предмет-сутність",
"title": "назва",
"invimage": "інвзображення",
"image": "зобр",
"group": "група",
"caption": "підпис",
"extratext": "додатковийтекст",
"rarity": "рідкісність",
"durability": "міцн",
"renewable": "поновл",
"stackable": "склад",
"flammable": "займист",
"size": "розмір",
"networkid": "мережевийid",
"drops": "дроп",
"health": "здоров'я",
"type": "тип",
"Common": "Звичайний",
"Uncommon": "Незвичайний",
"Rare": "Рідкісний",
"Epic": "Епічний",
"common": "звичайний",
"uncommon": "незвичайний",
"rare": "рідкісний",
"epic": "епічний",
"= yes": "= так",
"= no": "= ні",
"=yes": "=так",
"=no": "=ні",
"Yes": "Так",
"No": "Ні"
};
const monthes = {
"January": "січня",
"February": "лютого",
"March": "березня",
"April": "квітня",
"May": "травня",
"June": "червня",
"July": "липня",
"August": "серпня",
"September": "вересня",
"October": "жовтня",
"November": "листопада",
"December": "грудня"
};
CodeMirror.defineSimpleMode("customMode", {
start: [
{ regex: /\<\-\-.*?\-\-\>/, token: "custom-comment" }, // Comments ( <-- something --> )
// { regex: /\{\{\#.*?\}\}/, token: "custom-parser" }, // Parser functions ( {{#something}} )
{ regex: /==.*==/, token: "custom-heading" }, // Headings ( == something == )
{ regex: /\{\{\{.*?\}\}\}/, token: "custom-parameter" }, // Parameters ( {{{something}}} )
{ regex: /\{\{/, token: "custom-template", next: "template" }, // Templates ( {{ )
{ regex: /\}\}/, token: "custom-template" }, // Templates ( }} )
{ regex: /\|/, token: "custom-template" }, // Pipes ( | )
{ regex: /\[\[(?:(?!\]\]|\|).)*\]\]/, token: "custom-link" }, // Links ( [[something]] )
{ regex: /\[\[(.*?)\|/, token: "custom-link" }, // Links ( [[something| )
{ regex: /\]\]/, token: "custom-link" }, // Links ( ]] )
{ regex: /\<.*?\>/, token: "custom-tag" }, // HTML tags ( <something></something> )
],
template: [
{ regex: /\b([^\|\}\n]+)/, token: "custom-template-name", next: "start" }, // Template name without {{ and |, until | or }}
{ regex: /#([^\|\}\n]+)/, token: "custom-parser-name", next: "start" }, // Parser name without {{ and |, until | or }}
{ regex: /\}\}/, token: "custom-template", next: "start" }, // Template closing ( }} )
{ regex: /\|/, token: "custom-template" }, // Pipes within template
]
});
var editor = CodeMirror.fromTextArea(document.getElementById("textareaInput"), {
lineNumbers: true,
lineWrapping: true,
mode: "customMode",
theme: "default"
});
var editor2 = CodeMirror.fromTextArea(document.getElementById("textareaInput2"), {
lineNumbers: true,
lineWrapping: true,
mode: "customMode",
theme: "default"
});
var output = CodeMirror.fromTextArea(document.getElementById("textareaOutput"), {
readOnly: true,
lineWrapping: true,
mode: "",
theme: "default"
});
var output2 = CodeMirror.fromTextArea(document.getElementById("textareaOutput2"), {
readOnly: true,
lineWrapping: true,
mode: "",
theme: "default"
});
var editorI = CodeMirror.fromTextArea(document.getElementById("textareaInputInterwiki"), {
lineNumbers: true,
lineWrapping: true,
mode: "",
theme: "default"
});
var outputI = CodeMirror.fromTextArea(document.getElementById("textareaOutputInterwiki"), {
readOnly: true,
lineWrapping: true,
mode: "",
theme: "default"
});
function translatetext() {
if (document.querySelector(".tab-btn-active").id === "mc-tmp") {
translateuk();
} else if (document.querySelector(".tab-btn-active").id === "mc-name") {
translateNames();
}
}
function translateuk() {
const text = editor.getValue();
let radioButtons = document.getElementsByName('templates');
for (let i = 0; i < radioButtons.length; i++) {
if (radioButtons[i].checked) {
let id = radioButtons[i].id;
console.log(id);
if (id === 'auto') {
console.log('yea')
console.log(text);
if (text.includes('{{ID table') || text.includes('{{ID_table')) {
id_table(text);
} else if (text.includes('{{Sound table') || text.includes('{{SoundTable')) {
sound_table(text);
} else if (text.includes('{{Version nav') || text.includes('{{Infobox version') || text.includes('{{infobox version')) {
version_nav(text);
} else if (text.includes('{{Entity') || text.includes('{{Infobox entity')) {
entity(text);
} else if (text.includes('{{Infobox block')) {
block(text);
} else if (text.includes('{{Drops')) {
dropsTable(text);
} else if (text.includes('{{History')) {
historyTable(text);
} else if (text.includes('{{Looming')) {
looming(text);
} else if (text.includes('{{Infobox biome')) {
biome(text);
} else if (text.includes('{{Spawn table') || text.includes('{{Spawn row')) {
spawnTable(text);
} else if (text.includes('{{Infobox item entity')) {
itemEntity(text);
} else if (text.includes('{{Infobox item')) {
item(text);
} else if (text === "") {
output.setValue("Введіть справжній текст шаблона, а не пустоту");
} else {
output.setValue("Неможливо розпізнати шаблон");
}
} else if (id === 'id') {
id_table(text);
} else if (id === 'sound') {
sound_table(text);
} else if (id === 'vn') {
version_nav(text);
} else if (id === 'entity') {
entity(text);
} else if (id === 'block') {
block(text);
} else if (id === 'drops') {
dropsTable(text);
} else if (id === 'historyTable') {
historyTable(text);
} else if (id === 'looming') {
looming(text);
} else if (id === 'biome') {
biome(text);
} else if (id === 'spawnTable') {
spawnTable(text);
} else if (id === 'item') {
item(text);
} else if (id === 'itemEntity') {
itemEntity(text);
}
return;
}
}
}
function performReplacements(text, replacementsObject) {
for (let key in replacementsObject) {
if (replacementsObject.hasOwnProperty(key)) {
let regex = new RegExp(key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g');
text = text.replace(regex, replacementsObject[key]);
}
}
return text;
}
function highlightAdditions(oldText, text, elClass) {
output.setValue(text);
let oldLines = oldText.split("\n");
let newLines = text.split("\n");
for (let i = 0; i < newLines.length; i++) {
if (i >= oldLines.length) {
// Якщо новий рядок довший ніж старий, виділити всю частину нового рядка
let pos = output.indexFromPos({line: i, ch: 0});
let from = output.posFromIndex(pos);
let to = output.posFromIndex(pos + newLines[i].length);
output.markText(from, to, {
className: elClass === undefined ? "cm-diff-added-green" : elClass,
inclusiveLeft: false,
inclusiveRight: false
});
continue;
}
let oldWords = oldLines[i].split(/\s+/);
let newWords = newLines[i].split(/\s+/);
let pos = output.indexFromPos({line: i, ch: 0});
for (let j = 0; j < newWords.length; j++) {
if (j >= oldWords.length || oldWords[j] !== newWords[j]) {
let from = output.posFromIndex(pos);
let to = output.posFromIndex(pos + newWords[j].length);
output.markText(from, to, {
className: elClass === undefined ? "cm-diff-added-green" : elClass,
inclusiveLeft: false,
inclusiveRight: false
});
}
pos += newWords[j].length + 1;
}
}
}
function id_table(text) {
let oldText = text;
let edition;
text = performReplacements(text, replacements_id);
text = text.split("\n");
for (let i = 1; i < text.length; i++) {
if (text[i].includes('java') || text[i].includes('je') || text[i].includes('JE')) {
edition = "java";
} if (text[i].includes('bedrock') || text[i].includes('be') || text[i].includes('BE')) {
edition = "bedrock";
}
if (text[i].includes("відображуванеім'я")) {
console.log(edition);
switch (edition) {
case "bedrock":
text[i] = translateBedrock(text[i]);
break;
default:
text[i] = translateJava(text[i], true);
break;
}
}
}
text = text.join("\n");
highlightAdditions(oldText, text);
}
function sound_table(text) {
highlightAdditions(text, text
.replace(/\{\{(.*)\[\[sound type\]\] / ,"[[Тип звуку]] {{$1")
.split("\n")
.map(segment => segment.includes("subtitle") ? translateJava(performReplacements(segment, replacements_sound), true) : performReplacements(segment, replacements_sound))
.join("\n"));
}
function version_nav(text) {
let oldText = text;
text = performReplacements(text, replacements_vn);
let lines = text.split("\n");
for (let line of lines) {
if (line.includes('зобр2')) {
image2_line = line;
let edition = null;
m = image2_line.replace('.png', 'Тут потрібно розрізати');
if (m.includes('Bedrock')) {
if (m.includes('Edition')) {
m = m.replace("Bedrock Edition ", "Тут потрібно розрізати");
} else {
m = m.replace("Bedrock ", "Тут потрібно розрізати");
}
edition = "Bedrock";
} else if (m.includes('Pocket')) {
m = m.replace("Pocket Edition ", "Тут потрібно розрізати");
edition = "Pocket";
} else if (m.includes('Windows 10')) {
m = m.replace("Windows 10 Edition ", "Тут потрібно розрізати");
edition = "Windows 10";
} else if (m.includes('Java')) {
m = m.replace("Java Edition ", "Тут потрібно розрізати");
edition = "Java";
}
m = m.split("Тут потрібно розрізати");
if (edition !== null) {
let changed_image_line = m[0] + m[1] + " (" + edition + " Edition) меню.png" + m[2];
text = text.replace(image2_line, changed_image_line)
}
} else if (line.includes('дата')) {
text = text.replace(line, dateTranslation(line));
}
}
highlightAdditions(oldText, text);
}
function entity(text) {
highlightAdditions(text, text
.split("\n")
.map(segment => (segment.includes("invimage") || segment.includes("usableitems") || segment.includes("{{drop")) ? translateJava(performReplacements(segment, replacements_entity), true) : performReplacements(segment, replacements_entity))
.join("\n"));
}
function block(text) {
highlightAdditions(text, text
.split("\n")
.map(segment => segment.includes("invimage") ? translateJava(performReplacements(segment, replacements_block), true) : performReplacements(segment, replacements_block))
.join("\n"));
}
function dropsTable(text) {
highlightAdditions(text, text
.split("|")
.map(segment => segment.includes("name") ? translateJava(performReplacements(segment, replacements_drops), true) : performReplacements(segment, replacements_drops))
.join("|"));
}
function historyTable(text) {
let oldText = text;
text = performReplacements(text, replacements_history);
text = text.split("|");
for (let i = 0; i < text.length; i++) {
for (let month in monthes) {
if (text[i].includes(month)) {
text[i] = dateTranslation(text[i]);
}
}
}
text = text.join("|");
highlightAdditions(oldText, text);
}
function looming(text) {
let oldText = text;
const colors = {
"White": { n: "Білий", f: "білою", m: "білим", pl: "білими" },
"Light Gray": { n: "Світло-сірий", f: "світло-сірою", m: "світло-сірим", pl: "світло-сірими" },
"Gray": { n: "Сірий", f: "сірою", m: "сірим", pl: "сірими" },
"Black": { n: "Чорний", f: "чорною", m: "чорним", pl: "чорними" },
"Brown": { n: "Коричневий", f: "коричневою", m: "коричневим", pl: "коричневими" },
"Red": { n: "Червоний", f: "червоною", m: "червоним", pl: "червоними" },
"Orange": { n: "Помаранчевий", f: "помаранчевою", m: "помаранчевим", pl: "помаранчевими" },
"Yellow": { n: "Жовтий", f: "жовтою", m: "жовтим", pl: "жовтими" },
"Lime": { n: "Лаймовий", f: "лаймовою", m: "лаймовим", pl: "лаймовими" },
"Green": { n: "Зелений", f: "зеленою", m: "зеленим", pl: "зеленими" },
"Cyan": { n: "Бірюзовий", f: "бірюзовою", m: "бірюзовим", pl: "бірюзовими" },
"Light Blue": { n: "Блакитний", f: "блакитною", m: "блакитним", pl: "блакитними" },
"Blue": { n: "Синій", f: "синьою", m: "синім", pl: "синіми" },
"Purple": { n: "Фіолетовий", f: "фіолетовою", m: "фіолетовим", pl: "фіолетовими" },
"Magenta": { n: "Пурпуровий", f: "пурпуровою", m: "пурпуровим", pl: "пурпуровими" },
"Pink": { n: "Рожевий", f: "рожевою", m: "рожевим", pl: "рожевими" }
};
const bannerPatterns = {
"Pale Dexter": { n: "Вертикальна смуга зліва", r: "вертикальною смугою зліва", vid: "f" },
"Pale Sinister": { n: "Вертикальна смуга справа", r: "вертикальною смугою справа", vid: "f" },
"Fess": { n: "Пояс", r: "поясом", vid: "m" },
"Paly": { n: "Вертикальні смуги", r: "вертикальними смугами", vid: "pl" },
"Saltire": { n: "Косий хрест", r: "косим хрестом", vid: "m" },
"Cross": { n: "Хрест", r: "хрестом", vid: "m" },
"Per Bend Sinister": { n: "Верхня ліва половина", r: "верхньою лівою половиною", vid: "f" },
"Per Bend Inverted": { n: "Нижня ліва половина", r: "нижньою лівою половиною", vid: "f" },
"Per Bend Sinister Inverted": { n: "Нижня права половина", r: "нижньою правою половиною", vid: "f" },
"Bend Sinister": { n: "Діагональ справа наліво", r: "діагоналлю справа наліво", vid: "f" },
"Per Bend": { n: "Верхня права половина", r: "верхньою правою половиною", vid: "f" },
"Per Pale Inverted": { n: "Права половина", r: "правою половиною", vid: "f" },
"Per Pale": { n: "Ліва половина", r: "лівою половиною", vid: "f" },
"Per Fess Inverted": { n: "Нижня половина", r: "нижньою половиною", vid: "f" },
"Per Fess": { n: "Верхня половина", r: "верхньою половиною", vid: "f" },
"Base Dexter Canton": { n: "Криж зліва знизу", r: "крижем зліва знизу", vid: "m" },
"Base Sinister Canton": { n: "Криж справа знизу", r: "крижем справа знизу", vid: "m" },
"Chief Dexter Canton": { n: "Криж зліва згори", r: "крижем зліва згори", vid: "m" },
"Chief Sinister Canton": { n: "Криж справа згори", r: "крижем зліва згори", vid: "m" },
"Inverted Chevron": { n: "Шеврон згори", r: "шевроном згори", vid: "m" },
"Chevron": { n: "Шеврон", r: "шевроном", vid: "m" },
"Base Indented": { n: "Зубці знизу", r: "зубцями знизу", vid: "pl" },
"Chief Indented": { n: "Зубці згори", r: "зубцями згори", vid: "pl" },
"Roundel": { n: "Круг", r: "кругом", vid: "m" },
"Lozenge": { n: "Ромб", r: "ромбом", vid: "m" },
"Bordure Indented": { n: "Зубчата рамка", r: "зубчатою рамкою", vid: "f" },
"Bordure": { n: "Рамка", r: "рамкою", vid: "f" },
"Field Masoned": { n: "Цегляне тло", r: "цегляним тлом", vid: "m" },
"Base Gradient": { n: "Градієнт знизу", r: "градієнтом знизу", vid: "m" },
"Gradient": { n: "Градієнт згори", r: "градієнтом згори", vid: "m" },
"Creeper Charge": { n: "Емблема кріпера", r: "емблемою кріпера", vid: "f" },
"Skull Charge": { n: "Емблема черепа", r: "емблемою черепа", vid: "f" },
"Flower Charge": { n: "Емблема квітки", r: "емблемою квітки", vid: "f" },
"Thing": { n: "Річ", r: "річчю", vid: "f" },
"Globe": { n: "Глобус", r: "глобусом", vid: "m" },
"Snout": { n: "Рило", r: "рилом", vid: "m" },
"Flow": { n: "Плин", r: "плином", vid: "m" },
"Guster": { n: "Порив", r: "поривом", vid: "m" },
"Base": { n: "Основа", r: "основою", vid: "f" },
"Bend": { n: "Діагональ зліва направо", r: "діагоналлю зліва направо", vid: "f" },
"Pale": { n: "Стовп", r: "стовпом", vid: "m" },
"Chief": { n: "Верх", r: "верхом", vid: "m" }
};
const regex = /(?:^|\[|=|\|)([^\|\]\[=\n]*?Banner[^\|\]\[=\n]*?)(?=\||\]|\n|$)/g;
const matches = [];
let match;
while ((match = regex.exec(text)) !== null) {
matches.push(match[1]);
}
for (let match of matches) {
let usedColor;
let usedPattern;
let vidm;
for (let color in colors) {
if (match.includes(color)) {
usedColor = color;
break;
}
}
for (let pattern in bannerPatterns) {
if (match.includes(pattern)) {
usedPattern = pattern;
vidm = bannerPatterns[pattern].vid;
break;
}
}
if (usedPattern !== undefined) {
if (usedColor !== undefined) {
if (match.includes("Dyed")) {
text = text.replace(match, `Пофарбований стяг з ${colors[usedColor][vidm]} ${bannerPatterns[usedPattern].r}`);
} else {
text = text.replace(match, `Стяг з ${colors[usedColor][vidm]} ${bannerPatterns[usedPattern].r}`);
}
} else if (match.includes("Dyed")) {
text = text.replace(match, `Пофарбований стяг з ${bannerPatterns[usedPattern].r}`);
} else if (match.includes("Banner Pattern")) {
text = text.replace(match, `Візерунок стяга «${bannerPatterns[usedPattern].n}»`);
} else {
text = text.replace(match, `Стяг з ${bannerPatterns[usedPattern].r}`);
}
} else if (usedColor !== undefined) {
text = text.replace(match, `${colors[usedColor].n} стяг`);
}
}
for (let pattern in bannerPatterns) {
if (text.includes(pattern)) {
text = text.replace(pattern, bannerPatterns[pattern].n);
}
}
text = text.split("\n");
for (let line of text) {
if (line.includes("Banner")) {
line = line.replace("Banner", "Стяг");
}
}
text = text.join("\n");
highlightAdditions(oldText, translateJava(performReplacements(text, replacements_looming)), true);
}
function biome(text) {
highlightAdditions(text, text
.split("\n")
.map(segment => (segment.includes("blocks") || segment.includes("title")) ? translateJava(performReplacements(segment, replacements_biome), true) : performReplacements(segment, replacements_biome))
.join("\n"));
}
function spawnTable(text) {
let oldText = text;
let edition;
text = performReplacements(text, replacements_spawn);
text = text.split("\n");
for (let i = 1; i < text.length; i++) {
if (text[i].includes('java') || text[i].includes('je') || text[i].includes('JE')) {
edition = "java";
} else if (text[i].includes('bedrock') || text[i].includes('be') || text[i].includes('BE')) {
edition = "bedrock";
}
if (text[i].includes("Ряд появи")) {
console.log(edition);
switch (edition) {
case "bedrock":
text[i] = translateBedrock(text[i], true);
break;
default:
text[i] = translateJava(text[i], true);
break;
}
}
}
text = text.join("\n");
highlightAdditions(oldText, text);
}
function item(text) {
highlightAdditions(text, text
.split("\n")
.map(segment => (segment.includes("invimage")) || segment.includes("title") ? translateJava(performReplacements(segment, replacements_item), true) : performReplacements(segment, replacements_item))
.join("\n"));
}
function itemEntity(text) {
highlightAdditions(text, text
.split("\n")
.map(segment => (segment.includes("invimage")) || segment.includes("title") ? translateJava(performReplacements(segment, replacements_itemEntity), true) : performReplacements(segment, replacements_itemEntity))
.join("\n"));
}
function dateTranslation(date) {
let lines1;
let date_line_new = date;
let date_line_after = "";
if (date.includes("<")) {
lines1 = date.split("<");
date_line_new = lines1[0];
date_line_after = '<' + lines1.slice(1).join('<');
} if (date.includes("{{")) {
lines1 = date.split("{{");
date_line_new = lines1[0];
date_line_after = '{{' + lines1.slice(1).join('{{');
} if (date.includes("}}")) {
lines1 = date.split("}}");
date_line_new = lines1[0];
date_line_after = '}}' + lines1.slice(1).join('}}');
}
for (let [engMonth, ukrMonth] of Object.entries(monthes)) {
if (date_line_new.includes(`${engMonth} `) && date_line_new.includes(',')) {
let d = date_line_new.replace(',', 'Розрізати');
d = d.replace(`${engMonth} `, 'Розрізати');
d = d.split('Розрізати');
let changed_date_line = d[0] + d[1] + ' ' + ukrMonth + d[2] + ' року' + date_line_after;
let regexDate = new RegExp('.*\\d{1,2}.+\\d{4} року', 'g');
if (regexDate.test(changed_date_line)) {
console.log(`success: ${date}`);
return changed_date_line;
} else {
console.log(`unsuccess: ${date}`);
return date;
}
}
}
return date;
}
document.getElementById('interwiki-button').addEventListener('click', async () => {
let value = editorI.getValue();
if (!value) {
alert('Будь ласка, введіть текст!');
return;
}
const matches = value.match(/\[\[(.*?)\]\]/g)?.map(match => match.slice(2, -2)) || [];
const templateMatches = value.match(/{{(.*?)}}/g)?.map(match => 'Template:' + match.slice(2, -2)) || [];
let newText = value;
// Масив для підсвічування
const highlights = [];
for (let match of matches) {
const apiUrl = `https://minecraft.wiki/api.php?action=query&titles=${encodeURIComponent(match)}&prop=langlinks&lllang=uk&format=json&origin=*`;
try {
const response = await fetch(apiUrl);
const data = await response.json();
// Отримання інтервікі на українську
const pages = data?.query?.pages || {};
const page = Object.values(pages)[0];
const langlink = page?.langlinks?.[0]?.['*'] || null;
if (langlink) {
newText = newText.replace(`[[${match}]]`, `[[${langlink}]]`);
// Зберігаємо інформацію про успішний переклад
highlights.push({
text: `[[${langlink}]]`,
className: 'cm-interwiki-green',
});
} else {
// Зберігаємо інформацію про невдалий переклад
highlights.push({
text: `[[${match}]]`,
className: 'cm-interwiki-red',
});
}
} catch (error) {
console.error('Помилка: ', error);
document.getElementById('interwiki-result').value = 'Не вдалося отримати дані. Перевірте з’єднання.';
}
}
for (let match of templateMatches) {
const apiUrl = `https://minecraft.wiki/api.php?action=query&titles=${encodeURIComponent(match)}&prop=langlinks&lllang=uk&format=json&origin=*`;
try {
const response = await fetch(apiUrl);
const data = await response.json();
// Отримання інтервікі на українську
const pages = data?.query?.pages || {};
const page = Object.values(pages)[0];
const langlink = page?.langlinks?.[0]?.['*'] || null;
if (langlink) {