Skip to content

Commit 5e4f4c9

Browse files
committed
make small stability improvements
1 parent 0bdd46d commit 5e4f4c9

File tree

1 file changed

+14
-12
lines changed

1 file changed

+14
-12
lines changed

codejar.ts

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,8 @@ export function CodeJar(editor: HTMLElement, highlight: (e: HTMLElement, pos?: P
5858
if (editor.contentEditable !== 'plaintext-only') isLegacy = true
5959
if (isLegacy) editor.setAttribute('contenteditable', 'true')
6060

61+
recordHistory()
62+
6163
const debounceHighlight = debounce(() => {
6264
const pos = save()
6365
highlight(editor, pos)
@@ -97,10 +99,10 @@ export function CodeJar(editor: HTMLElement, highlight: (e: HTMLElement, pos?: P
9799

98100
function save(): Position {
99101
const s = getSelection()
100-
const pos: Position = {start: 0, end: 0, dir: undefined}
102+
const pos: Position = {start: 0, end: 0}
101103

102104
let {anchorNode, anchorOffset, focusNode, focusOffset} = s
103-
if (!anchorNode || !focusNode) throw 'error1'
105+
if (!anchorNode || !focusNode) return history[at]?.pos ?? pos
104106

105107
// Selection anchor and focus are expected to be text nodes,
106108
// so normalize them.
@@ -277,14 +279,7 @@ export function CodeJar(editor: HTMLElement, highlight: (e: HTMLElement, pos?: P
277279
if (isLegacy && event.key === 'Enter') {
278280
event.preventDefault()
279281
event.stopPropagation()
280-
if (aroundCursor().after === '') {
281-
insert('\n ')
282-
const pos = save()
283-
pos.start = --pos.end
284-
restore(pos)
285-
} else {
286-
insert('\n')
287-
}
282+
insert('\n')
288283
}
289284
}
290285

@@ -407,8 +402,13 @@ export function CodeJar(editor: HTMLElement, highlight: (e: HTMLElement, pos?: P
407402
function insert(text: string) {
408403
let {start} = save()
409404
const {before, after} = aroundCursor()
410-
editor.textContent = before + text + after
411405
start += text.length
406+
407+
// the last line break isn't shown and it can cause editing issues
408+
// so, add an extra line break in order to avoid those issues
409+
if (after === '' && text.endsWith('\n')) text += '\n'
410+
411+
editor.textContent = before + text + after
412412
restore({start, end: start})
413413
}
414414

@@ -444,7 +444,9 @@ export function CodeJar(editor: HTMLElement, highlight: (e: HTMLElement, pos?: P
444444
Object.assign(options, newOptions)
445445
},
446446
updateCode(code: string, callOnUpdate: boolean = true) {
447-
editor.textContent = code
447+
recordHistory()
448+
editor.textContent = ''
449+
insert(code)
448450
highlight(editor)
449451
if (callOnUpdate) onUpdate(code)
450452
},

0 commit comments

Comments
 (0)