| 1 |
const globalWindow = window; |
| 2 |
export function CodeJar(editor, highlight, opt = {}) { |
| 3 |
const options = { |
| 4 |
tab: '\t', |
| 5 |
indentOn: /[({\[]$/, |
| 6 |
moveToNewLine: /^[)}\]]/, |
| 7 |
spellcheck: false, |
| 8 |
catchTab: true, |
| 9 |
preserveIdent: true, |
| 10 |
addClosing: true, |
| 11 |
history: true, |
| 12 |
window: globalWindow, |
| 13 |
autoclose: { |
| 14 |
open: `([{'"`, |
| 15 |
close: `)]}'"` |
| 16 |
}, |
| 17 |
...opt, |
| 18 |
}; |
| 19 |
const window = options.window; |
| 20 |
const document = window.document; |
| 21 |
const listeners = []; |
| 22 |
const history = []; |
| 23 |
let at = -1; |
| 24 |
let focus = false; |
| 25 |
let onUpdate = () => void 0; |
| 26 |
let prev; // code content prior keydown event |
| 27 |
editor.setAttribute('contenteditable', 'plaintext-only'); |
| 28 |
editor.setAttribute('spellcheck', options.spellcheck ? 'true' : 'false'); |
| 29 |
editor.style.outline = 'none'; |
| 30 |
editor.style.overflowWrap = 'break-word'; |
| 31 |
editor.style.overflowY = 'auto'; |
| 32 |
editor.style.whiteSpace = 'pre-wrap'; |
| 33 |
const doHighlight = (editor, pos) => { |
| 34 |
highlight(editor, pos); |
| 35 |
}; |
| 36 |
const matchFirefoxVersion = window.navigator.userAgent.match(/Firefox\/([0-9]+)\./); |
| 37 |
const firefoxVersion = matchFirefoxVersion |
| 38 |
? parseInt(matchFirefoxVersion[1]) |
| 39 |
: 0; |
| 40 |
let isLegacy = false; // true if plaintext-only is not supported |
| 41 |
if (editor.contentEditable !== "plaintext-only" || firefoxVersion >= 136) |
| 42 |
isLegacy = true; |
| 43 |
if (isLegacy) |
| 44 |
editor.setAttribute("contenteditable", "true"); |
| 45 |
const debounceHighlight = debounce(() => { |
| 46 |
const pos = save(); |
| 47 |
doHighlight(editor, pos); |
| 48 |
restore(pos); |
| 49 |
}, 30); |
| 50 |
let recording = false; |
| 51 |
const shouldRecord = (event) => { |
| 52 |
return !isUndo(event) && !isRedo(event) |
| 53 |
&& event.key !== 'Meta' |
| 54 |
&& event.key !== 'Control' |
| 55 |
&& event.key !== 'Alt' |
| 56 |
&& !event.key.startsWith('Arrow'); |
| 57 |
}; |
| 58 |
const debounceRecordHistory = debounce((event) => { |
| 59 |
if (shouldRecord(event)) { |
| 60 |
recordHistory(); |
| 61 |
recording = false; |
| 62 |
} |
| 63 |
}, 300); |
| 64 |
const on = (type, fn) => { |
| 65 |
listeners.push([type, fn]); |
| 66 |
editor.addEventListener(type, fn); |
| 67 |
}; |
| 68 |
on('keydown', event => { |
| 69 |
if (event.defaultPrevented) |
| 70 |
return; |
| 71 |
prev = toString(); |
| 72 |
if (options.preserveIdent) |
| 73 |
handleNewLine(event); |
| 74 |
else |
| 75 |
legacyNewLineFix(event); |
| 76 |
if (options.catchTab) |
| 77 |
handleTabCharacters(event); |
| 78 |
if (options.addClosing) |
| 79 |
handleSelfClosingCharacters(event); |
| 80 |
if (options.history) { |
| 81 |
handleUndoRedo(event); |
| 82 |
if (shouldRecord(event) && !recording) { |
| 83 |
recordHistory(); |
| 84 |
recording = true; |
| 85 |
} |
| 86 |
} |
| 87 |
if (isLegacy && !isCopy(event)) |
| 88 |
restore(save()); |
| 89 |
}); |
| 90 |
on('keyup', event => { |
| 91 |
if (event.defaultPrevented) |
| 92 |
return; |
| 93 |
if (event.isComposing) |
| 94 |
return; |
| 95 |
if (prev !== toString()) |
| 96 |
debounceHighlight(); |
| 97 |
debounceRecordHistory(event); |
| 98 |
onUpdate(toString()); |
| 99 |
}); |
| 100 |
on('focus', _event => { |
| 101 |
focus = true; |
| 102 |
}); |
| 103 |
on('blur', _event => { |
| 104 |
focus = false; |
| 105 |
}); |
| 106 |
on('paste', event => { |
| 107 |
recordHistory(); |
| 108 |
handlePaste(event); |
| 109 |
recordHistory(); |
| 110 |
onUpdate(toString()); |
| 111 |
}); |
| 112 |
on('cut', event => { |
| 113 |
recordHistory(); |
| 114 |
handleCut(event); |
| 115 |
recordHistory(); |
| 116 |
onUpdate(toString()); |
| 117 |
}); |
| 118 |
function save() { |
| 119 |
const s = getSelection(); |
| 120 |
const pos = { start: 0, end: 0, dir: undefined }; |
| 121 |
let { anchorNode, anchorOffset, focusNode, focusOffset } = s; |
| 122 |
if (!anchorNode || !focusNode) |
| 123 |
throw 'error1'; |
| 124 |
// If the anchor and focus are the editor element, return either a full |
| 125 |
// highlight or a start/end cursor position depending on the selection |
| 126 |
if (anchorNode === editor && focusNode === editor) { |
| 127 |
pos.start = (anchorOffset > 0 && editor.textContent) ? editor.textContent.length : 0; |
| 128 |
pos.end = (focusOffset > 0 && editor.textContent) ? editor.textContent.length : 0; |
| 129 |
pos.dir = (focusOffset >= anchorOffset) ? '->' : '<-'; |
| 130 |
return pos; |
| 131 |
} |
| 132 |
// Selection anchor and focus are expected to be text nodes, |
| 133 |
// so normalize them. |
| 134 |
if (anchorNode.nodeType === Node.ELEMENT_NODE) { |
| 135 |
const node = document.createTextNode(''); |
| 136 |
anchorNode.insertBefore(node, anchorNode.childNodes[anchorOffset]); |
| 137 |
anchorNode = node; |
| 138 |
anchorOffset = 0; |
| 139 |
} |
| 140 |
if (focusNode.nodeType === Node.ELEMENT_NODE) { |
| 141 |
const node = document.createTextNode(''); |
| 142 |
focusNode.insertBefore(node, focusNode.childNodes[focusOffset]); |
| 143 |
focusNode = node; |
| 144 |
focusOffset = 0; |
| 145 |
} |
| 146 |
visit(editor, el => { |
| 147 |
if (el === anchorNode && el === focusNode) { |
| 148 |
pos.start += anchorOffset; |
| 149 |
pos.end += focusOffset; |
| 150 |
pos.dir = anchorOffset <= focusOffset ? '->' : '<-'; |
| 151 |
return 'stop'; |
| 152 |
} |
| 153 |
if (el === anchorNode) { |
| 154 |
pos.start += anchorOffset; |
| 155 |
if (!pos.dir) { |
| 156 |
pos.dir = '->'; |
| 157 |
} |
| 158 |
else { |
| 159 |
return 'stop'; |
| 160 |
} |
| 161 |
} |
| 162 |
else if (el === focusNode) { |
| 163 |
pos.end += focusOffset; |
| 164 |
if (!pos.dir) { |
| 165 |
pos.dir = '<-'; |
| 166 |
} |
| 167 |
else { |
| 168 |
return 'stop'; |
| 169 |
} |
| 170 |
} |
| 171 |
if (el.nodeType === Node.TEXT_NODE) { |
| 172 |
if (pos.dir != '->') |
| 173 |
pos.start += el.nodeValue.length; |
| 174 |
if (pos.dir != '<-') |
| 175 |
pos.end += el.nodeValue.length; |
| 176 |
} |
| 177 |
}); |
| 178 |
editor.normalize(); // collapse empty text nodes |
| 179 |
return pos; |
| 180 |
} |
| 181 |
function restore(pos) { |
| 182 |
const s = getSelection(); |
| 183 |
let startNode, startOffset = 0; |
| 184 |
let endNode, endOffset = 0; |
| 185 |
if (!pos.dir) |
| 186 |
pos.dir = '->'; |
| 187 |
if (pos.start < 0) |
| 188 |
pos.start = 0; |
| 189 |
if (pos.end < 0) |
| 190 |
pos.end = 0; |
| 191 |
// Flip start and end if the direction reversed |
| 192 |
if (pos.dir == '<-') { |
| 193 |
const { start, end } = pos; |
| 194 |
pos.start = end; |
| 195 |
pos.end = start; |
| 196 |
} |
| 197 |
let current = 0; |
| 198 |
visit(editor, el => { |
| 199 |
if (el.nodeType !== Node.TEXT_NODE) |
| 200 |
return; |
| 201 |
const len = (el.nodeValue || '').length; |
| 202 |
if (current + len > pos.start) { |
| 203 |
if (!startNode) { |
| 204 |
startNode = el; |
| 205 |
startOffset = pos.start - current; |
| 206 |
} |
| 207 |
if (current + len > pos.end) { |
| 208 |
endNode = el; |
| 209 |
endOffset = pos.end - current; |
| 210 |
return 'stop'; |
| 211 |
} |
| 212 |
} |
| 213 |
current += len; |
| 214 |
}); |
| 215 |
if (!startNode) |
| 216 |
startNode = editor, startOffset = editor.childNodes.length; |
| 217 |
if (!endNode) |
| 218 |
endNode = editor, endOffset = editor.childNodes.length; |
| 219 |
// Flip back the selection |
| 220 |
if (pos.dir == '<-') { |
| 221 |
[startNode, startOffset, endNode, endOffset] = [endNode, endOffset, startNode, startOffset]; |
| 222 |
} |
| 223 |
{ |
| 224 |
// If nodes not editable, create a text node. |
| 225 |
const startEl = uneditable(startNode); |
| 226 |
if (startEl) { |
| 227 |
const node = document.createTextNode(''); |
| 228 |
startEl.parentNode?.insertBefore(node, startEl); |
| 229 |
startNode = node; |
| 230 |
startOffset = 0; |
| 231 |
} |
| 232 |
const endEl = uneditable(endNode); |
| 233 |
if (endEl) { |
| 234 |
const node = document.createTextNode(''); |
| 235 |
endEl.parentNode?.insertBefore(node, endEl); |
| 236 |
endNode = node; |
| 237 |
endOffset = 0; |
| 238 |
} |
| 239 |
} |
| 240 |
s.setBaseAndExtent(startNode, startOffset, endNode, endOffset); |
| 241 |
editor.normalize(); // collapse empty text nodes |
| 242 |
} |
| 243 |
function uneditable(node) { |
| 244 |
while (node && node !== editor) { |
| 245 |
if (node.nodeType === Node.ELEMENT_NODE) { |
| 246 |
const el = node; |
| 247 |
if (el.getAttribute('contenteditable') == 'false') { |
| 248 |
return el; |
| 249 |
} |
| 250 |
} |
| 251 |
node = node.parentNode; |
| 252 |
} |
| 253 |
} |
| 254 |
function beforeCursor() { |
| 255 |
const s = getSelection(); |
| 256 |
const r0 = s.getRangeAt(0); |
| 257 |
const r = document.createRange(); |
| 258 |
r.selectNodeContents(editor); |
| 259 |
r.setEnd(r0.startContainer, r0.startOffset); |
| 260 |
return r.toString(); |
| 261 |
} |
| 262 |
function afterCursor() { |
| 263 |
const s = getSelection(); |
| 264 |
const r0 = s.getRangeAt(0); |
| 265 |
const r = document.createRange(); |
| 266 |
r.selectNodeContents(editor); |
| 267 |
r.setStart(r0.endContainer, r0.endOffset); |
| 268 |
return r.toString(); |
| 269 |
} |
| 270 |
function handleNewLine(event) { |
| 271 |
if (event.key === 'Enter') { |
| 272 |
const before = beforeCursor(); |
| 273 |
const after = afterCursor(); |
| 274 |
let [padding] = findPadding(before); |
| 275 |
let newLinePadding = padding; |
| 276 |
// If last symbol is "{" ident new line |
| 277 |
if (options.indentOn.test(before)) { |
| 278 |
newLinePadding += options.tab; |
| 279 |
} |
| 280 |
// Preserve padding |
| 281 |
if (newLinePadding.length > 0) { |
| 282 |
preventDefault(event); |
| 283 |
event.stopPropagation(); |
| 284 |
insert('\n' + newLinePadding); |
| 285 |
} |
| 286 |
else { |
| 287 |
legacyNewLineFix(event); |
| 288 |
} |
| 289 |
// Place adjacent "}" on next line |
| 290 |
if (newLinePadding !== padding && options.moveToNewLine.test(after)) { |
| 291 |
const pos = save(); |
| 292 |
insert('\n' + padding); |
| 293 |
restore(pos); |
| 294 |
} |
| 295 |
} |
| 296 |
} |
| 297 |
function legacyNewLineFix(event) { |
| 298 |
// Firefox does not support plaintext-only mode |
| 299 |
// and puts <div><br></div> on Enter. Let's help. |
| 300 |
if (isLegacy && event.key === 'Enter') { |
| 301 |
preventDefault(event); |
| 302 |
event.stopPropagation(); |
| 303 |
if (afterCursor() == '') { |
| 304 |
insert('\n '); |
| 305 |
const pos = save(); |
| 306 |
pos.start = --pos.end; |
| 307 |
restore(pos); |
| 308 |
} |
| 309 |
else { |
| 310 |
insert('\n'); |
| 311 |
} |
| 312 |
} |
| 313 |
} |
| 314 |
function handleSelfClosingCharacters(event) { |
| 315 |
const open = options.autoclose.open; |
| 316 |
const close = options.autoclose.close; |
| 317 |
if (open.includes(event.key)) { |
| 318 |
preventDefault(event); |
| 319 |
const pos = save(); |
| 320 |
const wrapText = pos.start == pos.end ? '' : getSelection().toString(); |
| 321 |
const text = event.key + wrapText + (close[open.indexOf(event.key)] ?? ""); |
| 322 |
insert(text); |
| 323 |
pos.start++; |
| 324 |
pos.end++; |
| 325 |
restore(pos); |
| 326 |
} |
| 327 |
} |
| 328 |
function handleTabCharacters(event) { |
| 329 |
if (event.key === 'Tab') { |
| 330 |
preventDefault(event); |
| 331 |
if (event.shiftKey) { |
| 332 |
const before = beforeCursor(); |
| 333 |
let [padding, start] = findPadding(before); |
| 334 |
if (padding.length > 0) { |
| 335 |
const pos = save(); |
| 336 |
// Remove full length tab or just remaining padding |
| 337 |
const len = Math.min(options.tab.length, padding.length); |
| 338 |
restore({ start, end: start + len }); |
| 339 |
document.execCommand('delete'); |
| 340 |
pos.start -= len; |
| 341 |
pos.end -= len; |
| 342 |
restore(pos); |
| 343 |
} |
| 344 |
} |
| 345 |
else { |
| 346 |
insert(options.tab); |
| 347 |
} |
| 348 |
} |
| 349 |
} |
| 350 |
function handleUndoRedo(event) { |
| 351 |
if (isUndo(event)) { |
| 352 |
preventDefault(event); |
| 353 |
at--; |
| 354 |
const record = history[at]; |
| 355 |
if (record) { |
| 356 |
editor.innerHTML = record.html; |
| 357 |
restore(record.pos); |
| 358 |
} |
| 359 |
if (at < 0) |
| 360 |
at = 0; |
| 361 |
} |
| 362 |
if (isRedo(event)) { |
| 363 |
preventDefault(event); |
| 364 |
at++; |
| 365 |
const record = history[at]; |
| 366 |
if (record) { |
| 367 |
editor.innerHTML = record.html; |
| 368 |
restore(record.pos); |
| 369 |
} |
| 370 |
if (at >= history.length) |
| 371 |
at--; |
| 372 |
} |
| 373 |
} |
| 374 |
function recordHistory() { |
| 375 |
if (!focus) |
| 376 |
return; |
| 377 |
const html = editor.innerHTML; |
| 378 |
const pos = save(); |
| 379 |
const lastRecord = history[at]; |
| 380 |
if (lastRecord) { |
| 381 |
if (lastRecord.html === html |
| 382 |
&& lastRecord.pos.start === pos.start |
| 383 |
&& lastRecord.pos.end === pos.end) |
| 384 |
return; |
| 385 |
} |
| 386 |
at++; |
| 387 |
history[at] = { html, pos }; |
| 388 |
history.splice(at + 1); |
| 389 |
const maxHistory = 300; |
| 390 |
if (at > maxHistory) { |
| 391 |
at = maxHistory; |
| 392 |
history.splice(0, 1); |
| 393 |
} |
| 394 |
} |
| 395 |
function handlePaste(event) { |
| 396 |
if (event.defaultPrevented) |
| 397 |
return; |
| 398 |
preventDefault(event); |
| 399 |
const originalEvent = event.originalEvent ?? event; |
| 400 |
const text = originalEvent.clipboardData.getData('text/plain').replace(/\r\n?/g, '\n'); |
| 401 |
const pos = save(); |
| 402 |
insert(text); |
| 403 |
doHighlight(editor); |
| 404 |
restore({ |
| 405 |
start: Math.min(pos.start, pos.end) + text.length, |
| 406 |
end: Math.min(pos.start, pos.end) + text.length, |
| 407 |
dir: '<-', |
| 408 |
}); |
| 409 |
} |
| 410 |
function handleCut(event) { |
| 411 |
const pos = save(); |
| 412 |
const selection = getSelection(); |
| 413 |
const originalEvent = event.originalEvent ?? event; |
| 414 |
originalEvent.clipboardData.setData('text/plain', selection.toString()); |
| 415 |
document.execCommand('delete'); |
| 416 |
doHighlight(editor); |
| 417 |
restore({ |
| 418 |
start: Math.min(pos.start, pos.end), |
| 419 |
end: Math.min(pos.start, pos.end), |
| 420 |
dir: '<-', |
| 421 |
}); |
| 422 |
preventDefault(event); |
| 423 |
} |
| 424 |
function visit(editor, visitor) { |
| 425 |
const queue = []; |
| 426 |
if (editor.firstChild) |
| 427 |
queue.push(editor.firstChild); |
| 428 |
let el = queue.pop(); |
| 429 |
while (el) { |
| 430 |
if (visitor(el) === 'stop') |
| 431 |
break; |
| 432 |
if (el.nextSibling) |
| 433 |
queue.push(el.nextSibling); |
| 434 |
if (el.firstChild) |
| 435 |
queue.push(el.firstChild); |
| 436 |
el = queue.pop(); |
| 437 |
} |
| 438 |
} |
| 439 |
function isCtrl(event) { |
| 440 |
return event.metaKey || event.ctrlKey; |
| 441 |
} |
| 442 |
function isUndo(event) { |
| 443 |
return isCtrl(event) && !event.shiftKey && getKeyCode(event) === 'Z'; |
| 444 |
} |
| 445 |
function isRedo(event) { |
| 446 |
return isCtrl(event) && event.shiftKey && getKeyCode(event) === 'Z'; |
| 447 |
} |
| 448 |
function isCopy(event) { |
| 449 |
return isCtrl(event) && getKeyCode(event) === 'C'; |
| 450 |
} |
| 451 |
function getKeyCode(event) { |
| 452 |
let key = event.key || event.keyCode || event.which; |
| 453 |
if (!key) |
| 454 |
return undefined; |
| 455 |
return (typeof key === 'string' ? key : String.fromCharCode(key)).toUpperCase(); |
| 456 |
} |
| 457 |
function insert(text) { |
| 458 |
text = text |
| 459 |
.replace(/&/g, '&') |
| 460 |
.replace(/</g, '<') |
| 461 |
.replace(/>/g, '>') |
| 462 |
.replace(/"/g, '"') |
| 463 |
.replace(/'/g, '''); |
| 464 |
document.execCommand('insertHTML', false, text); |
| 465 |
} |
| 466 |
function debounce(cb, wait) { |
| 467 |
let timeout = 0; |
| 468 |
return (...args) => { |
| 469 |
clearTimeout(timeout); |
| 470 |
timeout = window.setTimeout(() => cb(...args), wait); |
| 471 |
}; |
| 472 |
} |
| 473 |
function findPadding(text) { |
| 474 |
// Find beginning of previous line. |
| 475 |
let i = text.length - 1; |
| 476 |
while (i >= 0 && text[i] !== '\n') |
| 477 |
i--; |
| 478 |
i++; |
| 479 |
// Find padding of the line. |
| 480 |
let j = i; |
| 481 |
while (j < text.length && /[ \t]/.test(text[j])) |
| 482 |
j++; |
| 483 |
return [text.substring(i, j) || '', i, j]; |
| 484 |
} |
| 485 |
function toString() { |
| 486 |
return editor.textContent || ''; |
| 487 |
} |
| 488 |
function preventDefault(event) { |
| 489 |
event.preventDefault(); |
| 490 |
} |
| 491 |
function getSelection() { |
| 492 |
// @ts-ignore |
| 493 |
return editor.getRootNode().getSelection(); |
| 494 |
} |
| 495 |
return { |
| 496 |
updateOptions(newOptions) { |
| 497 |
Object.assign(options, newOptions); |
| 498 |
}, |
| 499 |
updateCode(code, callOnUpdate = true) { |
| 500 |
editor.textContent = code; |
| 501 |
doHighlight(editor); |
| 502 |
callOnUpdate && onUpdate(code); |
| 503 |
}, |
| 504 |
onUpdate(callback) { |
| 505 |
onUpdate = callback; |
| 506 |
}, |
| 507 |
toString, |
| 508 |
save, |
| 509 |
restore, |
| 510 |
recordHistory, |
| 511 |
destroy() { |
| 512 |
for (let [type, fn] of listeners) { |
| 513 |
editor.removeEventListener(type, fn); |
| 514 |
} |
| 515 |
}, |
| 516 |
}; |
| 517 |
} |