-
-
Notifications
You must be signed in to change notification settings - Fork 116
/
codejar.ts
571 lines (500 loc) · 14.9 KB
/
codejar.ts
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
const globalWindow = window
type Options = {
tab: string
indentOn: RegExp
moveToNewLine: RegExp
spellcheck: boolean
catchTab: boolean
preserveIdent: boolean
addClosing: boolean
history: boolean
window: typeof window
autoclose: {
open: string;
close: string;
}
}
type HistoryRecord = {
html: string
pos: Position
}
export type Position = {
start: number
end: number
dir?: '->' | '<-'
}
export type CodeJar = ReturnType<typeof CodeJar>
export function CodeJar(editor: HTMLElement, highlight: (e: HTMLElement, pos?: Position) => void, opt: Partial<Options> = {}) {
const options: Options = {
tab: '\t',
indentOn: /[({\[]$/,
moveToNewLine: /^[)}\]]/,
spellcheck: false,
catchTab: true,
preserveIdent: true,
addClosing: true,
history: true,
window: globalWindow,
autoclose: {
open: `([{'"`,
close: `)]}'"`
},
...opt,
}
const window = options.window
const document = window.document
const listeners: [string, any][] = []
const history: HistoryRecord[] = []
let at = -1
let focus = false
let onUpdate: (code: string) => void | undefined = () => void 0
let prev: string // code content prior keydown event
editor.setAttribute('contenteditable', 'plaintext-only')
editor.setAttribute('spellcheck', options.spellcheck ? 'true' : 'false')
editor.style.outline = 'none'
editor.style.overflowWrap = 'break-word'
editor.style.overflowY = 'auto'
editor.style.whiteSpace = 'pre-wrap'
const doHighlight = (editor: HTMLElement, pos?: Position) => {
highlight(editor, pos)
}
let isLegacy = false // true if plaintext-only is not supported
if (editor.contentEditable !== 'plaintext-only') isLegacy = true
if (isLegacy) editor.setAttribute('contenteditable', 'true')
const debounceHighlight = debounce(() => {
const pos = save()
doHighlight(editor, pos)
restore(pos)
}, 30)
let recording = false
const shouldRecord = (event: KeyboardEvent): boolean => {
return !isUndo(event) && !isRedo(event)
&& event.key !== 'Meta'
&& event.key !== 'Control'
&& event.key !== 'Alt'
&& !event.key.startsWith('Arrow')
}
const debounceRecordHistory = debounce((event: KeyboardEvent) => {
if (shouldRecord(event)) {
recordHistory()
recording = false
}
}, 300)
const on = <K extends keyof HTMLElementEventMap>(type: K, fn: (event: HTMLElementEventMap[K]) => void) => {
listeners.push([type, fn])
editor.addEventListener(type, fn)
}
on('keydown', event => {
if (event.defaultPrevented) return
prev = toString()
if (options.preserveIdent) handleNewLine(event)
else legacyNewLineFix(event)
if (options.catchTab) handleTabCharacters(event)
if (options.addClosing) handleSelfClosingCharacters(event)
if (options.history) {
handleUndoRedo(event)
if (shouldRecord(event) && !recording) {
recordHistory()
recording = true
}
}
if (isLegacy && !isCopy(event)) restore(save())
})
on('keyup', event => {
if (event.defaultPrevented) return
if (event.isComposing) return
if (prev !== toString()) debounceHighlight()
debounceRecordHistory(event)
onUpdate(toString())
})
on('focus', _event => {
focus = true
})
on('blur', _event => {
focus = false
})
on('paste', event => {
recordHistory()
handlePaste(event)
recordHistory()
onUpdate(toString())
})
on('cut', event => {
recordHistory()
handleCut(event)
recordHistory()
onUpdate(toString())
})
function save(): Position {
const s = getSelection()
const pos: Position = {start: 0, end: 0, dir: undefined}
let {anchorNode, anchorOffset, focusNode, focusOffset} = s
if (!anchorNode || !focusNode) throw 'error1'
// If the anchor and focus are the editor element, return either a full
// highlight or a start/end cursor position depending on the selection
if (anchorNode === editor && focusNode === editor) {
pos.start = (anchorOffset > 0 && editor.textContent) ? editor.textContent.length : 0
pos.end = (focusOffset > 0 && editor.textContent) ? editor.textContent.length : 0
pos.dir = (focusOffset >= anchorOffset) ? '->' : '<-'
return pos
}
// Selection anchor and focus are expected to be text nodes,
// so normalize them.
if (anchorNode.nodeType === Node.ELEMENT_NODE) {
const node = document.createTextNode('')
anchorNode.insertBefore(node, anchorNode.childNodes[anchorOffset])
anchorNode = node
anchorOffset = 0
}
if (focusNode.nodeType === Node.ELEMENT_NODE) {
const node = document.createTextNode('')
focusNode.insertBefore(node, focusNode.childNodes[focusOffset])
focusNode = node
focusOffset = 0
}
visit(editor, el => {
if (el === anchorNode && el === focusNode) {
pos.start += anchorOffset
pos.end += focusOffset
pos.dir = anchorOffset <= focusOffset ? '->' : '<-'
return 'stop'
}
if (el === anchorNode) {
pos.start += anchorOffset
if (!pos.dir) {
pos.dir = '->'
} else {
return 'stop'
}
} else if (el === focusNode) {
pos.end += focusOffset
if (!pos.dir) {
pos.dir = '<-'
} else {
return 'stop'
}
}
if (el.nodeType === Node.TEXT_NODE) {
if (pos.dir != '->') pos.start += el.nodeValue!.length
if (pos.dir != '<-') pos.end += el.nodeValue!.length
}
})
editor.normalize() // collapse empty text nodes
return pos
}
function restore(pos: Position) {
const s = getSelection()
let startNode: Node | undefined, startOffset = 0
let endNode: Node | undefined, endOffset = 0
if (!pos.dir) pos.dir = '->'
if (pos.start < 0) pos.start = 0
if (pos.end < 0) pos.end = 0
// Flip start and end if the direction reversed
if (pos.dir == '<-') {
const {start, end} = pos
pos.start = end
pos.end = start
}
let current = 0
visit(editor, el => {
if (el.nodeType !== Node.TEXT_NODE) return
const len = (el.nodeValue || '').length
if (current + len > pos.start) {
if (!startNode) {
startNode = el
startOffset = pos.start - current
}
if (current + len > pos.end) {
endNode = el
endOffset = pos.end - current
return 'stop'
}
}
current += len
})
if (!startNode) startNode = editor, startOffset = editor.childNodes.length
if (!endNode) endNode = editor, endOffset = editor.childNodes.length
// Flip back the selection
if (pos.dir == '<-') {
[startNode, startOffset, endNode, endOffset] = [endNode, endOffset, startNode, startOffset]
}
{
// If nodes not editable, create a text node.
const startEl = uneditable(startNode)
if (startEl) {
const node = document.createTextNode('')
startEl.parentNode?.insertBefore(node, startEl)
startNode = node
startOffset = 0
}
const endEl = uneditable(endNode)
if (endEl) {
const node = document.createTextNode('')
endEl.parentNode?.insertBefore(node, endEl)
endNode = node
endOffset = 0
}
}
s.setBaseAndExtent(startNode, startOffset, endNode, endOffset)
editor.normalize() // collapse empty text nodes
}
function uneditable(node: Node): Element | undefined {
while (node && node !== editor) {
if (node.nodeType === Node.ELEMENT_NODE) {
const el = node as Element
if (el.getAttribute('contenteditable') == 'false') {
return el
}
}
node = node.parentNode!
}
}
function beforeCursor() {
const s = getSelection()
const r0 = s.getRangeAt(0)
const r = document.createRange()
r.selectNodeContents(editor)
r.setEnd(r0.startContainer, r0.startOffset)
return r.toString()
}
function afterCursor() {
const s = getSelection()
const r0 = s.getRangeAt(0)
const r = document.createRange()
r.selectNodeContents(editor)
r.setStart(r0.endContainer, r0.endOffset)
return r.toString()
}
function handleNewLine(event: KeyboardEvent) {
if (event.key === 'Enter') {
const before = beforeCursor()
const after = afterCursor()
let [padding] = findPadding(before)
let newLinePadding = padding
// If last symbol is "{" ident new line
if (options.indentOn.test(before)) {
newLinePadding += options.tab
}
// Preserve padding
if (newLinePadding.length > 0) {
preventDefault(event)
event.stopPropagation()
insert('\n' + newLinePadding)
} else {
legacyNewLineFix(event)
}
// Place adjacent "}" on next line
if (newLinePadding !== padding && options.moveToNewLine.test(after)) {
const pos = save()
insert('\n' + padding)
restore(pos)
}
}
}
function legacyNewLineFix(event: KeyboardEvent) {
// Firefox does not support plaintext-only mode
// and puts <div><br></div> on Enter. Let's help.
if (isLegacy && event.key === 'Enter') {
preventDefault(event)
event.stopPropagation()
if (afterCursor() == '') {
insert('\n ')
const pos = save()
pos.start = --pos.end
restore(pos)
} else {
insert('\n')
}
}
}
function handleSelfClosingCharacters(event: KeyboardEvent) {
const open = options.autoclose.open;
const close = options.autoclose.close;
if (open.includes(event.key)) {
preventDefault(event)
const pos = save()
const wrapText = pos.start == pos.end ? '' : getSelection().toString()
const text = event.key + wrapText + (close[open.indexOf(event.key)] ?? "")
insert(text)
pos.start++
pos.end++
restore(pos)
}
}
function handleTabCharacters(event: KeyboardEvent) {
if (event.key === 'Tab') {
preventDefault(event)
if (event.shiftKey) {
const before = beforeCursor()
let [padding, start] = findPadding(before)
if (padding.length > 0) {
const pos = save()
// Remove full length tab or just remaining padding
const len = Math.min(options.tab.length, padding.length)
restore({start, end: start + len})
document.execCommand('delete')
pos.start -= len
pos.end -= len
restore(pos)
}
} else {
insert(options.tab)
}
}
}
function handleUndoRedo(event: KeyboardEvent) {
if (isUndo(event)) {
preventDefault(event)
at--
const record = history[at]
if (record) {
editor.innerHTML = record.html
restore(record.pos)
}
if (at < 0) at = 0
}
if (isRedo(event)) {
preventDefault(event)
at++
const record = history[at]
if (record) {
editor.innerHTML = record.html
restore(record.pos)
}
if (at >= history.length) at--
}
}
function recordHistory() {
if (!focus) return
const html = editor.innerHTML
const pos = save()
const lastRecord = history[at]
if (lastRecord) {
if (lastRecord.html === html
&& lastRecord.pos.start === pos.start
&& lastRecord.pos.end === pos.end) return
}
at++
history[at] = {html, pos}
history.splice(at + 1)
const maxHistory = 300
if (at > maxHistory) {
at = maxHistory
history.splice(0, 1)
}
}
function handlePaste(event: ClipboardEvent) {
if (event.defaultPrevented) return
preventDefault(event)
const originalEvent = (event as any).originalEvent ?? event
const text = originalEvent.clipboardData.getData('text/plain').replace(/\r\n?/g, '\n')
const pos = save()
insert(text)
doHighlight(editor)
restore({
start: Math.min(pos.start, pos.end) + text.length,
end: Math.min(pos.start, pos.end) + text.length,
dir: '<-',
})
}
function handleCut(event: ClipboardEvent) {
const pos = save()
const selection = getSelection()
const originalEvent = (event as any).originalEvent ?? event
originalEvent.clipboardData.setData('text/plain', selection.toString())
document.execCommand('delete')
doHighlight(editor)
restore({
start: Math.min(pos.start, pos.end),
end: Math.min(pos.start, pos.end),
dir: '<-',
})
preventDefault(event)
}
function visit(editor: HTMLElement, visitor: (el: Node) => 'stop' | undefined) {
const queue: Node[] = []
if (editor.firstChild) queue.push(editor.firstChild)
let el = queue.pop()
while (el) {
if (visitor(el) === 'stop') break
if (el.nextSibling) queue.push(el.nextSibling)
if (el.firstChild) queue.push(el.firstChild)
el = queue.pop()
}
}
function isCtrl(event: KeyboardEvent) {
return event.metaKey || event.ctrlKey
}
function isUndo(event: KeyboardEvent) {
return isCtrl(event) && !event.shiftKey && getKeyCode(event) === 'Z'
}
function isRedo(event: KeyboardEvent) {
return isCtrl(event) && event.shiftKey && getKeyCode(event) === 'Z'
}
function isCopy(event: KeyboardEvent) {
return isCtrl(event) && getKeyCode(event) === 'C'
}
function getKeyCode(event: KeyboardEvent): string | undefined {
let key = event.key || event.keyCode || event.which
if (!key) return undefined
return (typeof key === 'string' ? key : String.fromCharCode(key)).toUpperCase()
}
function insert(text: string) {
text = text
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''')
document.execCommand('insertHTML', false, text)
}
function debounce(cb: any, wait: number) {
let timeout = 0
return (...args: any) => {
clearTimeout(timeout)
timeout = window.setTimeout(() => cb(...args), wait)
}
}
function findPadding(text: string): [string, number, number] {
// Find beginning of previous line.
let i = text.length - 1
while (i >= 0 && text[i] !== '\n') i--
i++
// Find padding of the line.
let j = i
while (j < text.length && /[ \t]/.test(text[j])) j++
return [text.substring(i, j) || '', i, j]
}
function toString() {
return editor.textContent || ''
}
function preventDefault(event: Event) {
event.preventDefault()
}
function getSelection() {
// @ts-ignore
return editor.getRootNode().getSelection() as Selection
}
return {
updateOptions(newOptions: Partial<Options>) {
Object.assign(options, newOptions)
},
updateCode(code: string, callOnUpdate: boolean = true) {
editor.textContent = code
doHighlight(editor)
callOnUpdate && onUpdate(code)
},
onUpdate(callback: (code: string) => void) {
onUpdate = callback
},
toString,
save,
restore,
recordHistory,
destroy() {
for (let [type, fn] of listeners) {
editor.removeEventListener(type, fn)
}
},
}
}