-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
139 lines (110 loc) · 6.67 KB
/
script.js
File metadata and controls
139 lines (110 loc) · 6.67 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
/*
подсветка sql кода самодельная
*/
document.addEventListener('DOMContentLoaded', () => {
const textarea = document.getElementById('codeInput');
const container = document.getElementById('container');
const mirror = document.createElement('pre');
mirror.classList.add('mirror');
container.appendChild(mirror);
// Функция копирования стилей
const copyStyles = () => {
const styles = window.getComputedStyle(textarea);
['border', 'fontFamily', 'fontSize', 'fontWeight', 'lineHeight', 'padding', 'borderRadius', 'wordWrap', 'whiteSpace']
.forEach((prop) => mirror.style[prop] = styles[prop]);
mirror.style.borderColor = 'transparent';
};
// Функция синхронизации текста с подсветкой
const syncMirror = () => {
// + \n чтобы рассинхрона не было с mirror
mirror.innerHTML = Prism.highlight(textarea.value + "\n", Prism.languages.sql, 'sql');
mirror.scrollTop = textarea.scrollTop;
};
// Функция вставки текста через execCommand
const insertText = (text) => {
document.execCommand('insertText', false, text);
};
// Функция комментирования строк через --
const toggleLineComment = () => {
const start = textarea.selectionStart;
const end = textarea.selectionEnd;
const value = textarea.value;
// Определим строки с курсором и выделением
const beforeCursor = value.substring(0, start);
console.log("beforeCursor:", beforeCursor);
// const afterCursor = value.substring(start, end);
const afterSelection = value.substring(end);
// Определяем начало и конец выделенных строк
const lineStart = beforeCursor.lastIndexOf('\n') + 1;
const lineEnd = afterSelection.indexOf('\n') !== -1 ? end + afterSelection.indexOf('\n') : value.length;
// Получаем все строки в выделенной области
const selectedLines = value.substring(lineStart, lineEnd).split('\n');
// Проверяем, закомментированы ли все строки
const allCommented = selectedLines.every(line => line.trim().startsWith('--'));
let newText = '';
let commentOffset = 0;
if (allCommented) {
// Если все строки закомментированы, убираем комментарии
newText = selectedLines.map(line => line.replace(/^--\s?/, '')).join('\n');
commentOffset = -3; // Сдвиг назад на 3 символа (длина "-- ")
} else {
// Если не все строки закомментированы, добавляем комментарии
newText = selectedLines.map(line => `-- ${line}`).join('\n');
commentOffset = 3; // Сдвиг вперёд на 3 символа (добавляем "-- ")
}
// Считаем количество строк
const numLines = selectedLines.length;
// Заменяем старый текст новым
textarea.setSelectionRange(lineStart, lineEnd);
insertText(newText);
// Обновляем позицию курсора, чтобы сохранить исходное выделение
const newStart = start + commentOffset;
const newEnd = end + commentOffset * numLines;
textarea.setSelectionRange(newStart, newEnd); // Сохраняем выделение
syncMirror(); // Обновляем подсветку
};
// Событие для однострочного комментирования --
textarea.addEventListener('keydown', (e) => {
if ((e.ctrlKey || e.metaKey) && e.key === '/') {
e.preventDefault(); // Предотвращаем стандартное поведение
toggleLineComment(); // Комментируем строки через --
}
// Обработка нажатия Tab для вставки 4 пробелов
if (e.key === 'Tab' && !e.shiftKey) {
e.preventDefault(); // Предотвращаем стандартное поведение (переключение между элементами)
const start = textarea.selectionStart;
const end = textarea.selectionEnd;
// Вставляем 4 пробела на место курсора или заменяем выделенный текст
insertText(' ');
// Обновляем позицию курсора после вставки
textarea.setSelectionRange(start + 4, start + 4); // Ставим курсор после вставки 4 пробелов
}
// Обработка Shift + Tab для удаления 4 пробелов перед курсором
if (e.key === 'Tab' && e.shiftKey) {
e.preventDefault(); // Предотвращаем стандартное поведение
const start = textarea.selectionStart;
const value = textarea.value;
// Определяем начало текущей строки (или предыдущей)
const lineStart = value.lastIndexOf('\n', start - 1) + 1;
const lineBeforeCursor = value.substring(lineStart, start);
// Проверяем, есть ли перед курсором 4 пробела
if (lineBeforeCursor.endsWith(' ')) {
// Удаляем 4 пробела перед курсором
textarea.setSelectionRange(lineStart + lineBeforeCursor.length - 4, start);
insertText(''); // Заменяем 4 пробела на пустоту
// Обновляем позицию курсора после удаления пробелов
textarea.setSelectionRange(start - 4, start - 4);
}
}
});
// Подписка на события
textarea.addEventListener('input', syncMirror);
textarea.addEventListener('scroll', () => {
mirror.scrollTop = textarea.scrollTop; // Синхронизация вертикальной прокрутки
mirror.scrollLeft = textarea.scrollLeft; // Синхронизация горизонтальной прокрутки
syncMirror(); // Обновление подсветки
});
// Инициализация
copyStyles();
syncMirror();
});