-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgithub-russian-l10n.user.js
More file actions
2621 lines (2280 loc) · 124 KB
/
github-russian-l10n.user.js
File metadata and controls
2621 lines (2280 loc) · 124 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
// ==UserScript==
// @name GitHub Russian Localization
// @name:ru Русская локализация GitHub
// @author Deflecat
// @contributionURL https://boosty.to/rushanm
// @description Localizes GitHub websites into Russian
// @description:ru Локализует сайты GitHub на русский язык
// @downloadURL https://github.com/RushanM/GitHub-Russian-Localization/raw/master/github-russian-l10n.user.js
// @grant none
// @homepageURL https://github.com/RushanM/GitHub-Russian-Localization
// @icon https://github.githubassets.com/favicons/favicon.png
// @license MIT
// @match https://*.github.com/*
// @match https://education.github.com/*
// @match https://github.blog/*
// @match https://github.com/*
// @run-at document-end
// @namespace githubrussianlocalization
// @supportURL https://github.com/RushanM/GitHub-Russian-Localization/issues
// @updateURL https://github.com/RushanM/GitHub-Russian-Localization/raw/master/github-russian-l10n.user.js
// @version P37
// ==/UserScript==
(function() {
'use strict';
// ссылка на локализационный файл формата FTL l10n/ru.ftl в репозитории
const FTL_URL = 'https://raw.githubusercontent.com/RushanM/GitHub-Russian-Localization/master/l10n/ru.ftl';
const LOG_PREFIX = '[GHRL10N]';
/**
* синтаксический анализатор FTL
* считывает сообщения в формате «ключ = значение»
*/
class SimpleFTLParser {
constructor(ftlContent) {
this.messages = new Map();
this.parse(ftlContent);
}
parse(content) {
const lines = content.split('\n');
for (let line of lines) {
line = line.trim();
// пропуск комментариев и пустых строк
if (!line || line.startsWith('#') || line.startsWith('##')) {
continue;
}
// считывание сообщений формата «ключ = значение»
const match = line.match(/^([a-zA-Z0-9-_]+)\s*=\s*(.+)$/);
if (match) {
const [, key, value] = match;
this.messages.set(key, value);
}
}
}
getMessage(key) {
return this.messages.get(key) || null;
}
hasMessage(key) {
return this.messages.has(key);
}
}
/**
* локализация Гитхаба
*/
class GitHubLocalizer {
constructor(ftlContent) {
this.parser = new SimpleFTLParser(ftlContent);
this.observer = null;
this.protectedElements = new Map(); // элементы под защитой от изменений
console.info(`${LOG_PREFIX} Localizer initialized with ${this.parser.messages.size} messages.`);
}
getTranslation(key, fallback = null) {
const message = this.parser.getMessage(key);
return message != null ? message : fallback;
}
/**
* локализация элемента по его текстовому содержимому
*/
localizeByText(element, originalText, messageKey) {
if (!element || !element.textContent) return false;
const currentText = element.textContent.trim();
// получение локализации
const translation = this.getTranslation(messageKey);
if (!translation) return false;
// если текст уже переведён, добавляем защиту и пропускаем
if (currentText === translation) {
this.protectElement(element, translation);
return false;
}
// если текст не совпадает с оригиналом, пропускаем
if (currentText !== originalText) return false;
// переводим
element.textContent = translation;
element.setAttribute('data-ru-localized', 'true');
// защищаем элемент от изменений
this.protectElement(element, translation);
return true;
}
/**
* локализация элемента БЕЗ защиты от изменений
* используется для элементов, которые могут динамически меняться (например, Ask/Task)
*/
localizeByTextDynamic(element, translations) {
if (!element || !element.textContent) return false;
const currentText = element.textContent.trim();
// проверяем каждую пару оригинал → перевод
for (const { original, key } of translations) {
const translation = this.getTranslation(key);
if (!translation) continue;
// если текст уже переведён, пропускаем
if (currentText === translation) return false;
// если текст совпадает с оригиналом, переводим
if (currentText === original) {
element.textContent = translation;
return true;
}
}
return false;
}
/**
* защита элемента от изменения текста обратно на английский
*/
protectElement(element, translatedText) {
// если элемент уже под защитой, пропускаем
if (this.protectedElements.has(element)) return;
// создание наблюдателя для этого элемента
const protectionObserver = new MutationObserver((mutations) => {
for (let mutation of mutations) {
if (mutation.type === 'characterData' || mutation.type === 'childList') {
const currentText = element.textContent.trim();
// если текст изменился с перевода на что-то другое
if (currentText !== translatedText) {
// немедленно восстанавливаем перевод
element.textContent = translatedText;
}
}
}
});
// наблюдение за изменениями текста и дочерних элементов
protectionObserver.observe(element, {
characterData: true,
childList: true,
subtree: true
});
// сохранение наблюдателя
this.protectedElements.set(element, {
observer: protectionObserver,
translation: translatedText
});
}
/**
* локализация хлебной крошки Dashboard
*/
localizeDashboard() {
// старый селектор
const dashboardElements = document.querySelectorAll('.AppHeader-context-item-label');
dashboardElements.forEach(el => {
this.localizeByText(el, 'Dashboard', 'dashboard');
});
// новый селектор для хлебных крошек
const breadcrumbElements = document.querySelectorAll('.styles-module__contextCrumbLast__cE7QReI');
breadcrumbElements.forEach(el => {
this.localizeByText(el, 'Dashboard', 'dashboard');
});
}
normalizeSearchPlaceholderText(translation) {
if (typeof translation !== 'string') {
return null;
}
if (!translation.includes('{{kbd}}')) {
return translation.replace(/\s+/g, ' ').trim();
}
const normalized = translation.replace('{{kbd}}', '/');
return normalized.replace(/\s+/g, ' ').trim();
}
renderSearchPlaceholder(target, translation) {
if (!target || typeof translation !== 'string') {
return;
}
if (!translation.includes('{{kbd}}')) {
target.textContent = translation;
return;
}
const [beforeKbd, afterKbd] = translation.split('{{kbd}}');
const existingKbd = target.querySelector('kbd');
const kbdElement = existingKbd ?? (() => {
const newKbd = document.createElement('kbd');
newKbd.className = 'AppHeader-search-kbd';
newKbd.textContent = '/';
return newKbd;
})();
const fragment = document.createDocumentFragment();
fragment.appendChild(document.createTextNode(beforeKbd ?? ''));
fragment.appendChild(kbdElement);
fragment.appendChild(document.createTextNode(typeof afterKbd === 'string' ? afterKbd : ''));
target.replaceChildren(fragment);
}
resolveKbdElement(identifier, kbdMap) {
if (!(kbdMap instanceof Map) || kbdMap.size === 0) {
return null;
}
const normalized = (identifier ?? '').trim();
if (!normalized) {
const firstEntry = kbdMap.entries().next();
if (!firstEntry.done) {
const [firstKey, element] = firstEntry.value;
kbdMap.delete(firstKey);
return element;
}
return null;
}
if (kbdMap.has(normalized)) {
const element = kbdMap.get(normalized);
kbdMap.delete(normalized);
return element;
}
const lower = normalized.toLowerCase();
for (const [key, element] of kbdMap.entries()) {
if (key.trim().toLowerCase() === lower) {
kbdMap.delete(key);
return element;
}
}
const fallback = kbdMap.entries().next();
if (!fallback.done) {
const [fallbackKey, element] = fallback.value;
kbdMap.delete(fallbackKey);
return element;
}
return null;
}
createFragmentFromKbdTranslation(translation, kbdElements) {
if (typeof translation !== 'string') {
return null;
}
const fragment = document.createDocumentFragment();
const map = kbdElements instanceof Map
? new Map(kbdElements)
: new Map(Array.isArray(kbdElements) ? kbdElements : []);
const regex = /\[kbd\](.*?)\[\/kbd\]/g;
let lastIndex = 0;
let match;
let hasPlaceholders = false;
while ((match = regex.exec(translation)) !== null) {
hasPlaceholders = true;
const textPart = translation.slice(lastIndex, match.index);
if (textPart) {
fragment.appendChild(document.createTextNode(textPart));
}
const placeholderContent = match[1] ?? '';
const kbdElement = this.resolveKbdElement(placeholderContent, map);
if (kbdElement) {
const displayText = placeholderContent.trim();
if (displayText) {
kbdElement.textContent = displayText;
}
fragment.appendChild(kbdElement);
} else if (placeholderContent) {
fragment.appendChild(document.createTextNode(placeholderContent));
}
lastIndex = regex.lastIndex;
}
if (!hasPlaceholders) {
fragment.appendChild(document.createTextNode(translation));
return fragment;
}
const remainder = translation.slice(lastIndex);
if (remainder) {
fragment.appendChild(document.createTextNode(remainder));
}
return fragment;
}
replaceContentWithKbdTranslation(target, translationKey, kbdElements) {
if (!target) {
return false;
}
const translation = this.getTranslation(translationKey);
if (!translation) {
return false;
}
const fragment = this.createFragmentFromKbdTranslation(translation, kbdElements);
if (!fragment) {
return false;
}
target.replaceChildren(fragment);
target.setAttribute('data-ru-localized', 'true');
return true;
}
/**
* локализация поисковой строки «Type / to search»
*/
localizeSearchPlaceholder() {
// новый селектор для поисковой строки в шапке
const searchPlaceholder = document.querySelector('.Search-module__placeholder__Ke68F3b');
if (searchPlaceholder) {
const translation = this.getTranslation('type-slash-to-search');
if (translation) {
const currentText = searchPlaceholder.textContent.replace(/\s+/g, ' ').trim();
const hasOriginalText = currentText.includes('Type') && currentText.includes('to search');
const normalizedTranslation = this.normalizeSearchPlaceholderText(translation);
if (searchPlaceholder.getAttribute('data-ru-localized') === 'true') {
if (hasOriginalText || !searchPlaceholder.querySelector('kbd')) {
this.renderSearchPlaceholder(searchPlaceholder, translation);
}
return;
}
if (hasOriginalText) {
this.renderSearchPlaceholder(searchPlaceholder, translation);
searchPlaceholder.setAttribute('data-ru-localized', 'true');
}
}
return;
}
// старый селектор (для совместимости)
const searchInput = document.querySelector('#qb-input-query');
if (!searchInput) return;
const translation = this.getTranslation('type-slash-to-search');
if (!translation) return;
const normalizedTranslation = this.normalizeSearchPlaceholderText(translation);
if (!normalizedTranslation) {
return;
}
const currentText = searchInput.textContent.replace(/\s+/g, ' ').trim();
const hasOriginalText = currentText.includes('Type') && currentText.includes('to search');
if (searchInput.getAttribute('data-ru-localized') === 'true') {
if (!currentText || currentText !== normalizedTranslation || (translation.includes('{{kbd}}') && !searchInput.querySelector('kbd'))) {
this.renderSearchPlaceholder(searchInput, translation);
}
this.protectSearchElement(searchInput, translation, normalizedTranslation);
return;
}
if (!hasOriginalText) {
return;
}
this.renderSearchPlaceholder(searchInput, translation);
searchInput.setAttribute('data-ru-localized', 'true');
this.protectSearchElement(searchInput, translation, normalizedTranslation);
}
/**
* защита поискового элемента
*/
protectSearchElement(element, translation, normalizedTranslation = null) {
if (this.protectedElements.has(element)) return;
const expectedText = normalizedTranslation ?? this.normalizeSearchPlaceholderText(translation) ?? '';
const protectionObserver = new MutationObserver(() => {
const currentText = element.textContent.replace(/\s+/g, ' ').trim();
const hasOriginalText = currentText.includes('Type') && currentText.includes('to search');
const hasKbd = Boolean(element.querySelector('kbd'));
if (!hasOriginalText && currentText === expectedText && (!translation.includes('{{kbd}}') || hasKbd)) {
return;
}
this.renderSearchPlaceholder(element, translation);
element.setAttribute('data-ru-localized', 'true');
});
protectionObserver.observe(element, {
characterData: true,
childList: true,
subtree: true
});
this.protectedElements.set(element, {
observer: protectionObserver,
translation: translation
});
}
/**
* локализация всплывающих подсказок (tooltips)
*/
localizeTooltips() {
// «Command palette»
const commandPaletteTooltips = document.querySelectorAll('tool-tip[for="AppHeader-commandPalette-button"]');
commandPaletteTooltips.forEach(tooltip => {
this.localizeByText(tooltip, 'Command palette', 'command-palette');
});
// «Chat with Copilot»
const copilotTooltips = document.querySelectorAll('tool-tip[for="copilot-chat-header-button"]');
copilotTooltips.forEach(tooltip => {
this.localizeByText(tooltip, 'Chat with Copilot', 'chat-with-copilot');
});
}
/**
* локализация всплывающих подсказок шапки страницы (AppHeader)
* обрабатывает tooltips с горячими клавишами и без них
*/
localizeAppHeaderTooltips() {
// маппирование латинских клавиш на русские (по позиции на клавиатуре)
const keyboardMap = {
'G': 'П', 'g': 'п',
'I': 'Ш', 'i': 'ш',
'K': 'Л', 'k': 'л',
'P': 'З', 'p': 'з',
'N': 'Т', 'n': 'т',
'D': 'В', 'd': 'в'
};
// конфигурация подсказок для локализации
const tooltipConfigs = [
// простые подсказки (без клавиш или клавиши не переводятся)
{ text: 'Open menu', key: 'open-menu', translateKeys: false },
{ text: 'Homepage', key: 'homepage', translateKeys: false },
{ text: 'Chat with Copilot', key: 'chat-with-copilot', translateKeys: false },
{ text: 'Create new...', key: 'create-new', translateKeys: false },
{ text: 'Repositories', key: 'repositories', translateKeys: false },
{ text: 'Open user navigation menu', key: 'open-user-navigation-menu', translateKeys: false },
{ text: 'Search for repositories', key: 'search-for-repositories', translateKeys: false },
{ text: 'Add repositories, files, and spaces', key: 'add-repositories-files-spaces', translateKeys: false },
// подсказки с клавишами, которые нужно перевести
{ text: 'Command palette', key: 'command-palette', translateKeys: true },
{ text: 'Issues', key: 'issues', translateKeys: true },
{ text: 'Pull requests', key: 'pull-requests', translateKeys: true },
{ text: 'You have no unread notifications', key: 'you-have-no-notifications', translateKeys: true },
// подсказки с клавишами, которые не нужно переводить (пиктограмма клавиши ввода, символы и т. п.)
{ text: 'Send now', key: 'send-now', translateKeys: false, preserveKbd: true }
];
// находим все tooltips в шапке
const tooltips = document.querySelectorAll('.prc-TooltipV2-Tooltip-tLeuB');
tooltips.forEach(tooltip => {
if (tooltip.hasAttribute('data-ru-localized')) return;
// находим span с id (основной текст подсказки)
const textSpan = tooltip.querySelector('span[id]');
if (!textSpan) {
// структура без вложенных элементов
const tooltipText = tooltip.textContent.trim();
const config = tooltipConfigs.find(c => c.text === tooltipText);
if (config) {
const translation = this.getTranslation(config.key);
if (translation) {
tooltip.textContent = translation;
tooltip.setAttribute('data-ru-localized', 'true');
}
}
return;
}
// извлекаем видимый текст (без скрытых элементов и kbd)
const hiddenSpan = textSpan.querySelector('.prc-src-InternalVisuallyHidden-2YaI6');
const kbdElement = textSpan.querySelector('kbd');
let visibleText = textSpan.textContent.trim();
if (hiddenSpan) {
visibleText = visibleText.replace(hiddenSpan.textContent, '').trim();
}
if (kbdElement) {
visibleText = visibleText.replace(kbdElement.textContent, '').trim();
}
// ищем подходящую конфигурацию
const config = tooltipConfigs.find(c => c.text === visibleText);
if (!config) return;
const translation = this.getTranslation(config.key);
if (!translation) return;
// заменяем текст
if (config.preserveKbd) {
// сохраняем элемент kbd при замене текста
const kbdElement = textSpan.querySelector('kbd');
if (kbdElement) {
const kbdClone = kbdElement.cloneNode(true);
textSpan.textContent = translation + ' ';
textSpan.appendChild(kbdClone);
} else {
textSpan.textContent = translation;
}
} else if (hiddenSpan) {
// сохраняем скрытый span и заменяем текстовые узлы
const hiddenClone = hiddenSpan.cloneNode(true);
textSpan.textContent = translation + ' ';
textSpan.appendChild(hiddenClone);
} else {
textSpan.textContent = translation;
}
// переводим клавиши, если нужно
if (config.translateKeys) {
// обрабатываем элементы kbd с горячими клавишами
const kbdContainer = tooltip.querySelector('.prc-TooltipV2-KeybindingHintContainer-Ymj-3');
if (kbdContainer) {
// находим все отображаемые буквы клавиш
const keySpans = kbdContainer.querySelectorAll('[data-kbd-chord] span[aria-hidden="true"]');
keySpans.forEach(keySpan => {
const keyText = keySpan.textContent.trim();
if (keyboardMap[keyText]) {
keySpan.textContent = keyboardMap[keyText];
}
});
// обновляем скрытые тексты для доступности
const hiddenKeySpans = kbdContainer.querySelectorAll('.prc-src-InternalVisuallyHidden-2YaI6');
hiddenKeySpans.forEach(span => {
const keyText = span.textContent.trim();
if (keyboardMap[keyText]) {
span.textContent = keyboardMap[keyText];
}
});
}
}
tooltip.setAttribute('data-ru-localized', 'true');
});
}
/**
* метод для локализации элементов ActionListItem-label
*/
localizeActionListItems() {
const translationMap = new Map([
['Home', 'home'],
['Feed', 'feed'],
['Issues', 'issues'],
['Pull requests', 'pull-requests'],
['Projects', 'projects'],
['Discussions', 'discussions'],
['Codespaces', 'codespaces'],
['Copilot', 'copilot'],
['Explore', 'explore'],
['Marketplace', 'marketplace'],
['MCP registry', 'mcp-registry'],
['New issue', 'new-issue'],
['New repository', 'new-repository'],
['Import repository', 'import-repository'],
['New agent task', 'new-agent-task'],
['New codespace', 'new-codespace'],
['New gist', 'new-gist'],
['New organization', 'new-organization'],
['New project', 'new-project'],
['Profile', 'profile'],
['Repositories', 'repositories'],
['Stars', 'stars'],
['Gists', 'gists'],
['Organizations', 'organizations'],
['Enterprises', 'enterprises'],
['Sponsors', 'sponsors'],
['Settings', 'settings'],
['Copilot settings', 'copilot-settings'],
['Feature preview', 'feature-preview'],
['Appearance', 'appearance'],
['Accessibility', 'accessibility'],
['Try Enterprise', 'try-enterprise'],
['Sign out', 'sign-out'],
['Open', 'open'],
['Closed', 'closed'],
['Authored', 'authored'],
['Mentioned', 'mentioned'],
['Review requested', 'review-requested'],
['Reviewed', 'reviewed'],
['Assigned to me', 'assigned-to-me'],
['Involves me', 'involves-me'],
['Repositories…', 'copilot-repositories'],
['Files and folders…', 'files-and-folders'],
['Spaces…', 'spaces'],
['Upload from computer', 'upload-from-computer'],
['Extensions…', 'extensions'],
['New agent session', 'new-agent-session'],
['Basic Git commands', 'basic-git-commands'],
['Git branching', 'git-branching'],
['Advanced Git commands', 'advanced-git-commands']
]);
const selectors = ['.ActionListItem-label', '.prc-ActionList-ItemLabel-TmBhn'];
const items = document.querySelectorAll(selectors.join(', '));
items.forEach(item => {
const text = item.textContent.trim();
if (!translationMap.has(text)) {
return;
}
const key = translationMap.get(text);
this.localizeByText(item, text, key);
});
const headingTranslationMap = new Map([
['Agent sessions to include', 'agent-sessions-to-include'],
['Number of results', 'number-of-results'],
['Pull requests to include', 'pull-requests-to-include'],
['Issues to include', 'issues-to-include'],
['Models', 'models'],
['Fast and cost-efficient', 'fast-and-cost-efficient'],
['Versatile and highly intelligent', 'versatile-and-highly-intelligent'],
['Most powerful at complex tasks', 'most-powerful-at-complex']
]);
const headingSelectors = ['.prc-ActionList-GroupHeading-eahp0', '.ModelPicker-module__menuHeading--PBTLv'];
const headings = document.querySelectorAll(headingSelectors.join(', '));
headings.forEach(heading => {
const text = heading.textContent.trim();
if (!headingTranslationMap.has(text)) {
return;
}
const key = headingTranslationMap.get(text);
this.localizeByText(heading, text, key);
});
}
/**
* метод для локализации всплывающих подсказок (tooltips)
*/
localizeAllTooltips() {
const tooltipTranslations = [
{ selector: 'tool-tip[for="global-copilot-agent-button"]', text: 'Open agents panel', key: 'open-agents-panel' },
{ selector: 'tool-tip[for="global-create-menu-anchor"]', text: 'Create new…', key: 'create-new' },
{ selector: 'tool-tip#notification-indicator-tooltip', text: 'You have no unread notifications', key: 'you-have-no-notifications' }
];
tooltipTranslations.forEach(({ selector, text, key }) => {
const tooltips = document.querySelectorAll(selector);
tooltips.forEach(tooltip => {
this.localizeByText(tooltip, text, key);
});
});
// динамические подсказки с изменяемыми идентификаторами
this.localizeDynamicTooltips();
}
/**
* локализация подсказок с динамическими идентификаторами
*/
localizeDynamicTooltips() {
const dynamicTranslations = [
{ text: 'Your issues', key: 'your-issues' },
{ text: 'Your pull requests', key: 'your-pull-requests' },
{ text: 'Account switcher', key: 'account-switcher' },
{ text: 'Repositories', key: 'repositories' }
];
const allTooltips = document.querySelectorAll('tool-tip, .prc-TooltipV2-Tooltip-cYMVY');
allTooltips.forEach(tooltip => {
const text = tooltip.textContent.trim();
const translation = dynamicTranslations.find(t => t.text === text);
if (translation) {
this.localizeByText(tooltip, translation.text, translation.key);
}
});
}
/**
* локализация приветствия с учётом времени суток
*/
localizeGreeting() {
// поддержка нескольких вариантов классов
const selectors = [
'.h2.prc-Heading-Heading-6CmGO',
'.h2.prc-Heading-Heading-MtWFE'
];
const greetingElements = document.querySelectorAll(selectors.join(', '));
greetingElements.forEach(el => {
const text = el.textContent.trim();
// установки для разных приветствий
const patterns = [
{ regex: /^Good night,\s*(.+)!$/, key: 'good-night' },
{ regex: /^Good morning,\s*(.+)!$/, key: 'good-morning' },
{ regex: /^Good afternoon,\s*(.+)!$/, key: 'good-afternoon' },
{ regex: /^Good evening,\s*(.+)!$/, key: 'good-evening' }
];
const alreadyLocalized = patterns.some(pattern => {
const translation = this.getTranslation(pattern.key);
return translation ? text.startsWith(translation) : false;
});
if (alreadyLocalized) {
return;
}
for (const pattern of patterns) {
const match = text.match(pattern.regex);
if (match) {
const username = match[1];
const translation = this.getTranslation(pattern.key);
if (translation) {
el.textContent = `${translation}, ${username}!`;
el.setAttribute('data-ru-localized', 'true');
break;
}
}
}
});
}
/**
* локализация элементов «GitHub Education»
*/
localizeGitHubEducation() {
// заголовок
const taglines = document.querySelectorAll('.h4');
taglines.forEach(el => {
this.localizeByText(el, 'Learn. Collaborate. Grow.', 'learn-collaborate-grow');
});
// описание
const descriptions = document.querySelectorAll('p.my-3.text-small');
descriptions.forEach(el => {
const text = el.textContent.trim().replace(/\s+/g, ' ');
const translation = this.getTranslation('github-education-gives-here');
if (!translation) return;
if (text === translation) {
el.setAttribute('data-ru-localized', 'true');
return;
}
if (text.includes('GitHub Education gives you the tools')) {
el.textContent = translation;
el.setAttribute('data-ru-localized', 'true');
}
});
// кнопка
const buttons = document.querySelectorAll('.Button-label');
buttons.forEach(button => {
this.localizeByText(button, 'Go to GitHub Education', 'go-to-github-education');
});
}
/**
* локализация элементов Копайлота и части левой боковой панели
*/
localizeCopilotChatAndLeftBarPart() {
// textarea placeholder и aria-label
const chatTextarea = document.querySelector('#copilot-chat-textarea');
if (chatTextarea) {
const translation = this.getTranslation('ask-anything');
if (translation) {
const currentPlaceholder = chatTextarea.getAttribute('placeholder');
if (currentPlaceholder !== translation) {
chatTextarea.setAttribute('placeholder', translation);
chatTextarea.setAttribute('aria-label', translation);
chatTextarea.setAttribute('data-ru-localized', 'true');
}
}
}
// «Top repositories»
const topReposElements = document.querySelectorAll('div');
topReposElements.forEach(el => {
if (el.textContent.trim() === 'Top repositories') {
this.localizeByText(el, 'Top repositories', 'top-repositories');
}
});
// поле ввода «Search for repositories»
const repoSearchInputs = document.querySelectorAll('input[aria-label="Search for repositories"], input[placeholder="Search for repositories"]');
if (repoSearchInputs.length) {
const placeholderTranslation = this.getTranslation('search-for-repositories');
if (placeholderTranslation) {
repoSearchInputs.forEach(input => {
if (input.getAttribute('placeholder') !== placeholderTranslation) {
input.setAttribute('placeholder', placeholderTranslation);
}
if (input.getAttribute('aria-label') !== placeholderTranslation) {
input.setAttribute('aria-label', placeholderTranslation);
}
input.setAttribute('data-ru-localized', 'true');
});
}
}
// «Add repositories, files, and spaces»
const attachmentButtons = document.querySelectorAll('.ChatInput-module__attachmentButtonText--fVuEs');
attachmentButtons.forEach(button => {
this.localizeByText(button, 'Add repositories, files, and spaces', 'add-repositories-files-spaces');
});
// кнопка режима Ask/Task. Без защиты, чтобы динамически менялось
const askTaskTranslations = [
{ original: 'Ask', key: 'ask' },
{ original: 'Task', key: 'task' }
];
const modeButtons = document.querySelectorAll('.ChatInput-module__modeSelectButton__gV9F1kA .prc-Button-Label-FWkx3');
modeButtons.forEach(button => {
this.localizeByTextDynamic(button, askTaskTranslations);
});
// Ask/Task во всплывающем меню
const menuLabels = document.querySelectorAll('.prc-ActionList-ItemLabel-81ohH');
menuLabels.forEach(label => {
this.localizeByTextDynamic(label, askTaskTranslations);
});
}
/**
* локализация меток и статусов
*/
localizeLabelsStatusesAndLinks() {
// метка о предварительной версии (старый и новый селекторы)
const previewSelectors = [
'.prc-Label-Label--LG6X[data-size="small"][data-variant="success"]',
'.prc-Label-Label-qG-Zu[data-size="small"][data-variant="success"]'
];
const previewLabels = document.querySelectorAll(previewSelectors.join(', '));
previewLabels.forEach(label => {
this.localizeByText(label, 'Preview', 'preview');
});
const modelPreviewLabels = document.querySelectorAll('.ModelPicker-module__modelMetaLabel--zMick');
modelPreviewLabels.forEach(label => {
this.localizeByText(label, 'Preview', 'preview');
});
// метка New («Новинка»), старый и новый селекторы
const newSelectors = [
'.prc-Label-Label--LG6X[data-size="small"][data-variant="accent"]',
'.prc-Label-Label-qG-Zu[data-size="small"][data-variant="accent"]'
];
const newLabels = document.querySelectorAll(newSelectors.join(', '));
newLabels.forEach(label => {
this.localizeByText(label, 'New', 'new');
});
// метка Free («Бесплатно»), старый и новый селекторы
const freeSelectors = [
'.prc-Label-Label--LG6X[data-size="small"][data-variant="primary"]',
'.prc-Label-Label-qG-Zu[data-size="small"][data-variant="primary"]'
];
const freeLabels = document.querySelectorAll(freeSelectors.join(', '));
freeLabels.forEach(label => {
this.localizeByText(label, 'Free', 'free');
});
// ссылка обратной связи
const feedbackLinks = document.querySelectorAll('a.CopilotHeaderBase-module__feedbackLink--fnf2R');
feedbackLinks.forEach(link => {
this.localizeByText(link, 'Feedback', 'feedback');
});
// кнопки Give feedback и Switch back (старый и новый селекторы)
const linkButtonSelectors = [
'button.prc-Link-Link-85e08',
'button.prc-Link-Link-9ZwDx'
];
const linkButtons = document.querySelectorAll(linkButtonSelectors.join(', '));
linkButtons.forEach(button => {
this.localizeByText(button, 'Give feedback', 'give-feedback');
this.localizeByText(button, 'Switch back', 'switch-back');
});
const autoButtons = document.querySelectorAll('.ModelPicker-module__buttonName--Iid1H');
autoButtons.forEach(button => {
this.localizeByText(button, 'Auto', 'auto');
});
// уведомление о лимите премиум-запросов
const footerElements = document.querySelectorAll('.ModelPicker-module__footer--yCNLJ');
footerElements.forEach(footer => {
if (footer.hasAttribute('data-ru-localized')) return;
const text = footer.textContent.trim();
if (text.includes('You have used 80%') && text.includes('premium requests')) {
const translation = this.getTranslation('you-have-used-eighty');
if (!translation) return;
const link = footer.querySelector('a');
if (!link) return;
const parts = translation.split(/\[link\]|\[\/link\]/);
if (parts.length >= 3) {
const prefix = parts[0] ?? '';
const linkText = parts[1] ?? '';
const suffix = parts.slice(2).join('');
const fragment = document.createDocumentFragment();
if (prefix) fragment.appendChild(document.createTextNode(prefix));
link.textContent = linkText;
fragment.appendChild(link);
if (suffix) fragment.appendChild(document.createTextNode(suffix));
footer.replaceChildren(fragment);
footer.setAttribute('data-ru-localized', 'true');
}
}
});
}
/**
* локализация элементов CommandPill (команды)
*/
localizeCommandPills() {
const commandTranslations = [
{ text: 'Task', key: 'cw3-task' },
{ text: 'Create issue', key: 'create-issue' },
{ text: 'Spark', key: 'spark' }
];
// старый и новый селекторы
const commandPillSelectors = [
'.CommandPill-module__text--ggGhT',
'.CommandPill-module__text__degaI4N'
];
const commandPills = document.querySelectorAll(commandPillSelectors.join(', '));
commandPills.forEach(pill => {
commandTranslations.forEach(({ text, key }) => {
this.localizeByText(pill, text, key);
});
});
}
/**
* локализация заголовков и элементов панели управления
*/
localizeDashboardElements() {
// «Latest from our changelog»
const changelogTitles = document.querySelectorAll('.dashboard-changelog__title');
changelogTitles.forEach(title => {
this.localizeByText(title, 'Latest from our changelog', 'latest-from-our-changelog');
});
// «Agent sessions», «Pull requests», «Issues»
const stackLabels = document.querySelectorAll('.prc-Stack-Stack-WJVsK[data-gap="condensed"]');
stackLabels.forEach(label => {
const text = label.textContent.trim();
if (text === 'Agent sessions') {
this.localizeByText(label, 'Agent sessions', 'agent-sessions');
} else if (text === 'Pull requests') {
this.localizeByText(label, 'Pull requests', 'pull-requests');
} else if (text === 'Issues') {
this.localizeByText(label, 'Issues', 'issues');
}
});
// «View all»
const viewAllLinks = document.querySelectorAll('a.prc-Link-Link-85e08');