-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinject.js
More file actions
431 lines (368 loc) · 14.1 KB
/
inject.js
File metadata and controls
431 lines (368 loc) · 14.1 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
// HTML Academy Vim Mode Activator - Injected Script
(function () {
"use strict";
console.log("[Vim Mode] Injected script started");
// Хранилище для всех редакторов
const editors = new Set();
let currentMode = "normal"; // 'normal' или 'insert' (начинаем с normal)
function activateVimMode() {
// Проверяем наличие ace
if (typeof ace === "undefined") {
return false;
}
// Ищем все редакторы
const editorElements = document.querySelectorAll(".ace_editor");
if (editorElements.length === 0) {
return false;
}
let activatedCount = 0;
editorElements.forEach((editorElement) => {
const editor = editorElement.env?.editor;
if (!editor) {
return;
}
// Проверяем, не активирован ли уже Vim mode для этого редактора
const handlers = editor.keyBinding?.$handlers;
if (handlers && handlers.some((h) => h.$id === "ace/keyboard/vim")) {
editors.add(editor);
return; // Уже активирован
}
console.log("[Vim Mode] Activating for editor:", editor.id || "unknown");
// Настраиваем basePath (только один раз)
if (activatedCount === 0) {
ace.config.set(
"basePath",
"https://unpkg.com/ace-builds@1.15.2/src-noconflict/",
);
}
// Отключаем read only режим
editor.setReadOnly(false);
// Устанавливаем Vim keyboard handler
editor.setKeyboardHandler("ace/keyboard/vim");
// Добавляем в набор редакторов
editors.add(editor);
// Устанавливаем обработчик для отслеживания изменения режима
setupModeSync(editor);
// Фокусируем страницу с теорией чтобы можно было скролить стрелками.
if (document.querySelector(".course-theory__content")) {
document.querySelector(".course-theory__content").focus();
}
activatedCount++;
});
if (activatedCount > 0) {
console.log(
`[Vim Mode] ✓ Activated Vim mode for ${activatedCount} editor(s)`,
);
// Показываем уведомление (редакторы остаются в normal mode)
setTimeout(function () {
showNotification(
`✓ Vim mode активирован для ${editors.size} редактора(ов)!`,
);
}, 200);
return true;
}
return false;
}
function setupModeSync(editor) {
// Отслеживаем изменения режима через события клавиатуры
const originalHandleKeyboard = editor.keyBinding.onCommandKey.bind(
editor.keyBinding,
);
editor.keyBinding.onCommandKey = function (e, hashId, keyCode) {
const result = originalHandleKeyboard(e, hashId, keyCode);
// Проверяем текущий режим
setTimeout(() => {
const vimState = editor.state?.cm?.state?.vim;
if (vimState) {
const newMode = vimState.insertMode ? "insert" : "normal";
// Если режим изменился, синхронизируем все редакторы
if (newMode !== currentMode) {
console.log("[Vim Mode] Mode changed to:", newMode);
currentMode = newMode;
syncModeToAll(editor);
}
}
}, 0);
return result;
};
}
function syncModeToAll(sourceEditor) {
const vimState = sourceEditor.state?.cm?.state?.vim;
if (!vimState) return;
const targetInsertMode = vimState.insertMode;
editors.forEach((editor) => {
if (editor === sourceEditor) return; // Пропускаем источник
const editorVimState = editor.state?.cm?.state?.vim;
if (!editorVimState) return;
// Синхронизируем режим
if (editorVimState.insertMode !== targetInsertMode) {
try {
const CodeMirror = editor.state.cm.constructor;
if (targetInsertMode) {
// Входим в insert mode
CodeMirror.Vim.handleKey(editor.state.cm, "i");
} else {
// Выходим в normal mode (ESC)
CodeMirror.Vim.handleKey(editor.state.cm, "<Esc>");
}
} catch (e) {
console.error("[Vim Mode] Sync error:", e);
}
}
});
}
function showNotification(message) {
const notification = document.createElement("div");
notification.textContent = message;
notification.style.cssText = `
position: fixed;
top: 20px;
right: 20px;
background: #4CAF50;
color: white;
padding: 15px 20px;
border-radius: 5px;
box-shadow: 0 2px 10px rgba(0,0,0,0.2);
z-index: 10000;
font-family: Arial, sans-serif;
font-size: 14px;
animation: slideIn 0.3s ease-out;
`;
if (!document.getElementById("vim-mode-style")) {
const style = document.createElement("style");
style.id = "vim-mode-style";
style.textContent = `
@keyframes slideIn {
from {
transform: translateX(400px);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}
`;
document.head.appendChild(style);
}
document.body.appendChild(notification);
setTimeout(() => {
notification.style.transition = "opacity 0.3s";
notification.style.opacity = "0";
setTimeout(() => notification.remove(), 300);
}, 3000);
}
// Пытаемся активировать с повторными попытками
let attempts = 0;
const maxAttempts = 40;
const retryInterval = 500;
const tryActivate = setInterval(function () {
attempts++;
if (activateVimMode()) {
clearInterval(tryActivate);
} else if (attempts >= maxAttempts) {
console.log("[Vim Mode] Failed after", maxAttempts, "attempts");
clearInterval(tryActivate);
}
}, retryInterval);
// Устанавливаем глобальные клавиатурные сочетания (отложенно)
setTimeout(setupGlobalKeyBindings, 1000);
// Функция для проверки, находится ли активный редактор в insert mode
function isActiveEditorInInsertMode() {
const activeElement = document.activeElement;
// Проверяем, является ли активный элемент ace редактором
const aceEditor = activeElement.closest(".ace_editor");
if (!aceEditor || !aceEditor.env || !aceEditor.env.editor) {
return false;
}
const editor = aceEditor.env.editor;
const vimState = editor.state?.cm?.state?.vim;
// Возвращаем true если редактор в insert mode
return vimState && vimState.insertMode;
}
// Вспомогательная функция для фокуса на редакторе
function focusEditor(editorSelector, containerId) {
document.querySelector(editorSelector).click();
const editorContainer = document.getElementById(containerId);
if (editorContainer) {
// Сам контейнер может быть ace editor
if (
editorContainer.classList.contains("ace_editor") &&
editorContainer.env &&
editorContainer.env.editor
) {
editorContainer.env.editor.focus();
return;
}
// Или ищем внутри контейнера
const aceEditor = editorContainer.querySelector(".ace_editor");
if (aceEditor && aceEditor.env && aceEditor.env.editor) {
aceEditor.env.editor.focus();
return;
}
}
}
// Глобальный обработчик клавиш для фокуса на редакторе
function setupGlobalKeyBindings() {
console.log("[Vim Mode] Setting up global key bindings");
document.addEventListener(
"keydown",
function (e) {
// Отладка - логируем все Shift+клавиши
if (e.shiftKey && !e.ctrlKey && !e.altKey && !e.metaKey) {
console.log("[Vim Mode] Key pressed: Shift+" + e.key);
}
// Shift + H - клик по теории (только если активный редактор не в insert mode)
if (
e.shiftKey &&
e.key === "H" &&
!e.ctrlKey &&
!e.altKey &&
!e.metaKey
) {
// Проверяем, не находится ли активный редактор в insert mode
if (isActiveEditorInInsertMode()) {
return; // Разрешаем ввод заглавной H
}
e.preventDefault();
const theoryButton = document.querySelector(".course-theory");
if (theoryButton) {
theoryButton.click();
}
document.querySelector(".course-theory__content").focus(); // Фокусируем теории чтобы можно было скроллить стрелочками.
return;
}
// Shift + Space - клик по кнопке "Далее"
if (
e.shiftKey &&
e.key === " " &&
!e.ctrlKey &&
!e.altKey &&
!e.metaKey
) {
console.log(
"[Vim Mode] Shift+Space pressed, looking for next button",
);
// Не блокируем если в insert mode
if (isActiveEditorInInsertMode()) {
console.log("[Vim Mode] In insert mode, allowing default behavior");
return;
}
e.preventDefault();
e.stopPropagation();
const nextButton = document.querySelector(
".course-goals__button--next",
);
const submitChalangeButton = document.querySelector(
".course-challenge-controls__button",
);
if (nextButton) {
console.log("[Vim Mode] Found next button, clicking");
nextButton.click();
setTimeout(() => nextButton.click(), 50);
} else if (submitChalangeButton) {
if (submitChalangeButton.classList.contains("button--inactive")) {
document
.querySelector(".main-nav__course-button--active")
.click();
} else {
console.log("[Vim Mode] Found submit challenge button, clicking");
submitChalangeButton.click();
}
setTimeout(() => submitChalangeButton.click(), 50);
} else {
console.log(
"[Vim Mode] Next button not found. Available buttons:",
document.querySelectorAll('button, [role="button"]'),
);
}
return;
}
// Shift + J - фокус на html-editor (только если активный редактор не в insert mode)
if (
e.shiftKey &&
e.key === "J" &&
!e.ctrlKey &&
!e.altKey &&
!e.metaKey
) {
// Проверяем, не находится ли активный редактор в insert mode
if (isActiveEditorInInsertMode()) {
return; // Разрешаем ввод заглавной J
}
e.preventDefault();
focusEditor("[data-editor='html']", "html-editor");
return;
}
// Shift + K - фокус на css-editor (только если активный редактор не в insert mode)
if (
e.shiftKey &&
e.key === "K" &&
!e.ctrlKey &&
!e.altKey &&
!e.metaKey
) {
// Проверяем, не находится ли активный редактор в insert mode
if (isActiveEditorInInsertMode()) {
return; // Разрешаем ввод заглавной K
}
e.preventDefault();
focusEditor("[data-editor='css']", "css-editor");
return;
}
// Shift + L - фокус на js-editor (только если активный редактор не в insert mode)
if (
e.shiftKey &&
e.key === "L" &&
!e.ctrlKey &&
!e.altKey &&
!e.metaKey
) {
// Проверяем, не находится ли активный редактор в insert mode
if (isActiveEditorInInsertMode()) {
return; // Разрешаем ввод заглавной L
}
e.preventDefault();
focusEditor("[data-editor='js']", "js-editor");
return;
}
},
true,
); // Capture phase
}
// Следим за изменениями DOM (новые редакторы)
const observer = new MutationObserver(function () {
const editorElements = document.querySelectorAll(".ace_editor");
editorElements.forEach((editorElement) => {
const editorId = editorElement.id;
const editor = editorElement.env?.editor;
if (!editor) return;
// Если редактор новый, активируем Vim mode
if (!editors.has(editor)) {
console.log("[Vim Mode] New editor detected, activating...");
setTimeout(activateVimMode, 100);
} else {
// Проверяем, не сбросился ли Vim mode
const handlers = editor.keyBinding?.$handlers;
if (handlers && !handlers.some((h) => h.$id === "ace/keyboard/vim")) {
console.log("[Vim Mode] Vim mode was reset, reactivating...");
editors.delete(editor);
setTimeout(activateVimMode, 100);
}
}
});
});
if (document.body) {
observer.observe(document.body, {
childList: true,
subtree: true,
});
} else {
window.addEventListener("load", function () {
observer.observe(document.body, {
childList: true,
subtree: true,
});
});
}
})();