@@ -66,6 +66,8 @@ export function CodeJar(editor: HTMLElement, highlight: (e: HTMLElement, pos?: P
6666  if  ( editor . contentEditable  !==  'plaintext-only' )  isLegacy  =  true 
6767  if  ( isLegacy )  editor . setAttribute ( 'contenteditable' ,  'true' ) 
6868
69+   recordHistory ( ) 
70+ 
6971  const  debounceHighlight  =  debounce ( ( )  =>  { 
7072    const  pos  =  save ( ) 
7173    highlight ( editor ,  pos ) 
@@ -105,10 +107,10 @@ export function CodeJar(editor: HTMLElement, highlight: (e: HTMLElement, pos?: P
105107
106108  function  save ( ) : Position  { 
107109    const  s  =  getSelection ( ) 
108-     const  pos : Position  =  { start : 0 ,  end : 0 ,   dir :  undefined } 
110+     const  pos : Position  =  { start : 0 ,  end : 0 } 
109111
110112    let  { anchorNode,  anchorOffset,  focusNode,  focusOffset}  =  s 
111-     if  ( ! anchorNode  ||  ! focusNode )  throw   'error1' 
113+     if  ( ! anchorNode  ||  ! focusNode )  return   history [ at ] ?. pos   ??   pos 
112114
113115    // Selection anchor and focus are expected to be text nodes, 
114116    // so normalize them. 
@@ -285,14 +287,7 @@ export function CodeJar(editor: HTMLElement, highlight: (e: HTMLElement, pos?: P
285287    if  ( isLegacy  &&  event . key  ===  'Enter' )  { 
286288      event . preventDefault ( ) 
287289      event . stopPropagation ( ) 
288-       if  ( aroundCursor ( ) . after  ===  '' )  { 
289-         insert ( '\n ' ) 
290-         const  pos  =  save ( ) 
291-         pos . start  =  -- pos . end 
292-         restore ( pos ) 
293-       }  else  { 
294-         insert ( '\n' ) 
295-       } 
290+       insert ( '\n' ) 
296291    } 
297292  } 
298293
@@ -415,8 +410,13 @@ export function CodeJar(editor: HTMLElement, highlight: (e: HTMLElement, pos?: P
415410  function  insert ( text : string )  { 
416411    let  { start}  =  save ( ) 
417412    const  { before,  after}  =  aroundCursor ( ) 
418-     editor . textContent  =  before  +  text  +  after 
419413    start  +=  text . length 
414+ 
415+     // the last line break isn't shown and it can cause editing issues 
416+     // so, add an extra line break in order to avoid those issues 
417+     if  ( after  ===  ''  &&  text . endsWith ( '\n' ) )  text  +=  '\n' 
418+ 
419+     editor . textContent  =  before  +  text  +  after 
420420    restore ( { start,  end : start } ) 
421421  } 
422422
@@ -452,7 +452,9 @@ export function CodeJar(editor: HTMLElement, highlight: (e: HTMLElement, pos?: P
452452      Object . assign ( options ,  newOptions ) 
453453    } , 
454454    updateCode ( code : string ,  callOnUpdate : boolean  =  true )  { 
455-       editor . textContent  =  code 
455+       recordHistory ( ) 
456+       editor . textContent  =  '' 
457+       insert ( code ) 
456458      highlight ( editor ) 
457459      if  ( callOnUpdate )  onUpdate ( code ) 
458460    } , 
0 commit comments