(editor: HTMLElement, highlight: (e: HTMLElement, pos?: Position) => void, opt: Partial<Options> = {})
| 30 | export type CodeJar = ReturnType<typeof CodeJar> |
| 31 | |
| 32 | export function CodeJar(editor: HTMLElement, highlight: (e: HTMLElement, pos?: Position) => void, opt: Partial<Options> = {}) { |
| 33 | const options: Options = { |
| 34 | tab: '\t', |
| 35 | indentOn: /[({\[]$/, |
| 36 | moveToNewLine: /^[)}\]]/, |
| 37 | spellcheck: false, |
| 38 | catchTab: true, |
| 39 | preserveIdent: true, |
| 40 | addClosing: true, |
| 41 | history: true, |
| 42 | window: globalWindow, |
| 43 | autoclose: { |
| 44 | open: `([{'"`, |
| 45 | close: `)]}'"` |
| 46 | }, |
| 47 | ...opt, |
| 48 | } |
| 49 | |
| 50 | const window = options.window |
| 51 | const document = window.document |
| 52 | |
| 53 | const listeners: [string, any][] = [] |
| 54 | const history: HistoryRecord[] = [] |
| 55 | let at = -1 |
| 56 | let focus = false |
| 57 | let onUpdate: (code: string) => void | undefined = () => void 0 |
| 58 | let prev: string // code content prior keydown event |
| 59 | |
| 60 | editor.setAttribute('contenteditable', 'plaintext-only') |
| 61 | editor.setAttribute('spellcheck', options.spellcheck ? 'true' : 'false') |
| 62 | editor.style.outline = 'none' |
| 63 | editor.style.overflowWrap = 'break-word' |
| 64 | editor.style.overflowY = 'auto' |
| 65 | editor.style.whiteSpace = 'pre-wrap' |
| 66 | |
| 67 | const doHighlight = (editor: HTMLElement, pos?: Position) => { |
| 68 | highlight(editor, pos) |
| 69 | } |
| 70 | |
| 71 | const matchFirefoxVersion = |
| 72 | window.navigator.userAgent.match(/Firefox\/([0-9]+)\./); |
| 73 | const firefoxVersion = matchFirefoxVersion |
| 74 | ? parseInt(matchFirefoxVersion[1]) |
| 75 | : 0; |
| 76 | let isLegacy = false; // true if plaintext-only is not supported |
| 77 | if (editor.contentEditable !== "plaintext-only" || firefoxVersion >= 136) |
| 78 | isLegacy = true; |
| 79 | if (isLegacy) editor.setAttribute("contenteditable", "true"); |
| 80 | |
| 81 | const debounceHighlight = debounce(() => { |
| 82 | const pos = save() |
| 83 | doHighlight(editor, pos) |
| 84 | restore(pos) |
| 85 | }, 30) |
| 86 | |
| 87 | let recording = false |
| 88 | const shouldRecord = (event: KeyboardEvent): boolean => { |
| 89 | return !isUndo(event) && !isRedo(event) |
nothing calls this directly
no test coverage detected