This repository has been archived by the owner on Nov 29, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheditor.html
427 lines (338 loc) · 11 KB
/
editor.html
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
<style>
* {
padding: 0;
margin: 0;
}
.editor {
direction: rtl;
text-align: right;
width: 100%;
height: 100vh;
display: flex;
flex-direction: row;
line-height: 1.5;
font-size: 1.5rem;
font-family: sans-serif;
}
.editor-lines {
width: auto;
min-width: 20px;
background-color: #f5f5f5;
color: #6c6c6c;
border-right: 1px solid #ddd;
list-style: none;
overflow: hidden;
height: 100%;
padding-right: 10px;
padding-left: 20px;
}
.editor-code {
width: calc(100% - 20px);
padding-right: 10px;
padding-left: 10px;
height: 100%;
overflow-y: auto;
/* white-space: pre-wrap; */
white-space: nowrap;
}
.editor-code .line {
display: block;
}
.editor-code .line .string {
color: #d14;
}
.editor-code .line .operator {
color: gold;
}
.editor-code .line .comment {
color: #999;
font-style: italic;
}
.editor-code .line .number {
color: pink;
}
.editor-code .line .keyword {
color: #0086b3;
font-weight: bold;
}
</style>
<div class="editor">
<div class="editor-lines">
<li>1</li>
<li>2</li>
<li>3</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
</div>
<div contenteditable="true" class="editor-code">
<div class=line>صفحه:</div>
<div class=line> محتوا = ۳۴۵</div>
<div class=line>تمام</div>
</div>
</div>
<script>
const keywords = ['تمام'];
const ops = ['\\+', '\\-', '\\:', '\\=', '\\.'];
const commands = ['صفحه', 'قطعه', 'جعبه', 'پاراگراف'];
const argumentsList = ['منبع', 'مقصد', 'محتوا'];
const editor = document.querySelector('.editor');
const editor_code = editor.querySelector('.editor-code');
const editor_lines = editor.querySelector('.editor-lines');
const highlight = (code) => {
// First, handle operators to avoid interfering with other patterns
const opsReg = `(${ops.join('|')})`;
const opsRegex = new RegExp(opsReg, 'g');
code = code.replace(opsRegex, '<span class=operator>$&</span>');
// Handle strings (single or double quoted)
code = code.replace(/(["'])(?:(?=(\\?))\2.)*?\1/g, '<span class=string>$&</span>');
// Handle single-line comments (starting with //)
code = code.replace(/\/\/[^\n]*/g, '<span class=comment>$&</span>');
// Handle multi-line comments (/* */)
code = code.replace(/\/\*[\s\S]*?\*\//g, '<span class=comment>$&</span>');
// Handle english, persian, arabic numbers
code = code.replace(/([0-9٠١٢٣٤٥٦٧٨٩۰۱۲۳۴۵۶۷۸۹]+)/g, '<span class=number>$&</span>');
// Regex for keywords, commands, and arguments (handling Persian/Arabic characters)
const keywordReg = `(?:^|[^\\w\u0600-\u06FF])(${[...keywords, ...commands, ...argumentsList].join('|')})(?=[^\\w\u0600-\u06FF]|$)`;
const keywordRegex = new RegExp(keywordReg, 'g');
code = code.replace(keywordRegex, (match, p1) => {
// Only wrap the actual keyword and not the surrounding characters
return match.replace(p1, `<span class=keyword>${p1}</span>`);
});
return code;
};
const handleBlur = () => {
editor_code.querySelectorAll('.line').forEach(line => line.classList.remove('active'));
editor_lines.querySelectorAll('li').forEach(li => li.classList.remove('active'));
};
const updateLineNumbers = () => {
// const selection = window.getSelection();
// const range = selection.getRangeAt(0);
// const activeLine = range.startContainer ? range.startContainer.closest('.line') : null;
editor_code.querySelectorAll('.line').forEach(line => line.classList.remove('active'));
editor_lines.querySelectorAll('li').forEach(li => li.classList.remove('active'));
// if (activeLine) {
// activeLine.classList.add('active');
//
// const lineIndex = Array.from(editor_code.children).indexOf(activeLine);
// const lineNumber = editor_lines.children[lineIndex];
// if (lineNumber) {
// lineNumber.classList.add('active');
// }
// }
const lines = editor_code.querySelectorAll('.line');
editor_lines.innerHTML = '';
lines.forEach((_, index) => {
const lineItem = document.createElement('li');
lineItem.textContent = index + 1;
editor_lines.appendChild(lineItem);
});
};
const getLeadingSpaces = (lineElement) => {
const lineText = lineElement.textContent;
const leadingSpaces = lineText.match(/^\s*/)[0].length;
return leadingSpaces;
};
const handleKeyTab = (event) => {
const selection = window.getSelection();
const range = selection.getRangeAt(0);
const tabNode = document.createTextNode('\u00a0\u00a0\u00a0\u00a0');
range.insertNode(tabNode);
range.setStartAfter(tabNode);
range.setEndAfter(tabNode);
selection.removeAllRanges();
selection.addRange(range);
};
const scrollIntoViewIfNeeded = (element) => {
const rect = element.getBoundingClientRect();
const isVisible = (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
if (!isVisible) {
element.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'center' });
}
};
const handleKeyLine = (event) => {
const selection = window.getSelection();
const range = selection.getRangeAt(0);
const newLine = document.createElement('div');
newLine.classList.add('line');
newLine.innerHTML = '<br>';
// newLine.innerHTML = '​';
let currentLine = range.startContainer.parentElement;
if (currentLine) {
console.log("Now CurrentLine: ", currentLine);
let isCurrentLineEditor = false;
while (currentLine && !currentLine.classList.contains('line')) {
if (currentLine.classList.contains('editor-code')) {
isCurrentLineEditor = true;
break;
}
currentLine = currentLine.parentElement;
}
console.log("CurrentLine: ", currentLine);
if (currentLine) {
if (isCurrentLineEditor) {
currentLine.appendChild(newLine);
}
else {
currentLine.parentElement.insertBefore(newLine, currentLine.nextSibling);
}
scrollIntoViewIfNeeded(newLine);
const newRange = document.createRange();
// newRange.setStart(newLine, 1);
// newRange.setEnd(newLine, 1);
// or?
newRange.setStart(newLine, 0);
newRange.setEnd(newLine, 0);
const newSelection = window.getSelection();
newSelection.removeAllRanges();
newSelection.addRange(newRange);
}
}
};
const handleKey = (event) => {
if (event.key === 'Enter') {
event.preventDefault();
handleKeyLine();
updateLineNumbers();
}
else if (event.key === 'Tab') {
event.preventDefault();
handleKeyTab();
}
};
const stripHTML = (string) => {
const doc = new DOMParser().parseFromString(string, 'text/html');
const textLines = [];
doc.body.childNodes.forEach((childNode) => {
textLines.push(childNode.textContent || '');
});
return textLines.join('<br>');
};
// const saveCursorPosition = () => {
// const selection = window.getSelection();
// if (selection.rangeCount > 0) {
// return selection.getRangeAt(0).cloneRange();
// }
// return null;
// };
// const restoreCursorPosition = (range) => {
// if (range) {
// const selection = window.getSelection();
// selection.removeAllRanges();
// selection.addRange(range);
// }
// };
// const getCursorPosition = (editor) => {
// const selection = window.getSelection();
// if (!selection.rangeCount) return { lineIndex: null, offset: 0 };
// const range = selection.getRangeAt(0);
// const line = range.startContainer.parentElement;
// const lineIndex = Array.from(editor.querySelectorAll(".line")).indexOf(line);
// const offset = range.startOffset;
// return { lineIndex, offset };
// };
// const setCursorPosition = (editor, lineIndex, offset) => {
// const lines = editor.querySelectorAll(".line");
// if (lineIndex >= 0 && lineIndex < lines.length) {
// const line = lines[lineIndex];
// const range = document.createRange();
// const selection = window.getSelection();
// const textNode = line.firstChild || document.createTextNode('');
// range.setStart(textNode, offset);
// range.collapse(true);
// selection.removeAllRanges();
// selection.addRange(range);
// }
// };
const saveCursorPosition = () => {
const selection = window.getSelection();
if (selection.rangeCount > 0) {
return selection.getRangeAt(0).cloneRange();
}
return null;
};
const restoreCursorPosition = (range) => {
if (range) {
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
}
};
const getCaretPosition = () => {
const selection = document.getSelection();
if (!selection || !editor_code) return 0;
selection.collapseToEnd();
const range = selection.getRangeAt(0);
const clone = range.cloneRange();
clone.selectNodeContents(editor_code);
clone.setEnd(range.startContainer, range.startOffset);
console.log("clone:", clone, clone.toString(), clone.toString().length);
return clone.toString().length;
}
const highlightCodeInLines = () => {
console.log("highlightCodeInLines");
console.log(getCaretPosition());
const lines = editor_code.querySelectorAll(".line");
// console.log("saveCursorPosition");
const cursorRange = saveCursorPosition();
console.log("cursorRange: ", cursorRange);
// let cursorPos = { line: null, offset: 0 };
// let cursorPos = getCursorPosition(editor);
lines.forEach((line) => {
if (line.textContent === "") {
h = "<br>";
}
else {
const code = line.textContent;
// console.log("Code: ", code);
const h = highlight(code);
if (h !== line.textContent) {
// if (line === cursorPos.line) {
// cursorPos.offset = cursorPos.offset < highlightedCode.length ? cursorPos.offset : highlightedCode.length;
// }
line.innerHTML = h;
}
}
});
// console.log("restoreCursorPosition");
// restoreCursorPosition(cursorRange);
// if (cursorPos.lineIndex !== null) {
// setCursorPosition(editor, cursorPos.lineIndex, cursorPos.offset);
// }
// if (cursorPos.line) {
// setCursorPosition(cursorPos.line, cursorPos.offset);
// }
updateLineNumbers();
};
const synchronizeScroll = () => {
editor_lines.scrollTop = editor_code.scrollTop;
};
const handlePaste = (event) => {
event.preventDefault();
const text = (event.clipboardData || window.clipboardData).getData('text');
document.execCommand('insertText', false, text);
};
const handleFocus = () => {
// updateLineNumbers();
// const selection = window.getSelection();
// const activeLine = selection.anchorNode ? selection.anchorNode.closest('.line') : null;
// if (activeLine) {
// activeLine.classList.add('active');
// }
};
editor_code.addEventListener('paste', handlePaste);
editor_code.addEventListener('scroll', synchronizeScroll);
editor_code.addEventListener('focus', handleFocus);
editor_code.addEventListener('blur', handleBlur);
editor_code.addEventListener('keydown', handleKey);
editor_code.addEventListener('input', highlightCodeInLines);
// editor_code.innerHTML = '<div class="line"><br></div>';
editor_code.focus();
highlightCodeInLines();
</script>