@@ -6,14 +6,53 @@ type TextPosition = {
66} ;
77
88type ChangeType = "insertText" | "removeText" ;
9- type RemoveMode = "forward" | "backward" ;
109
1110type Change = {
1211 type : ChangeType ;
1312 text : string ;
1413 position : TextPosition ;
1514} ;
1615
16+ type RemoveMode = "forward" | "backward" ;
17+
18+ class History {
19+ private past : Change [ ] = [ ] ;
20+ private future : Change [ ] = [ ] ;
21+
22+ push ( change : Change ) {
23+ this . past . push ( change ) ;
24+ this . future = [ ] ;
25+ }
26+
27+ canUndo ( ) {
28+ return this . past . length > 0 ;
29+ }
30+
31+ canRedo ( ) {
32+ return this . future . length > 0 ;
33+ }
34+
35+ undo ( ) : Change | null {
36+ if ( this . past . length === 0 ) {
37+ return null ;
38+ }
39+
40+ const lastChange = this . past . pop ( ) ;
41+ this . future . push ( lastChange ) ;
42+ return lastChange ;
43+ }
44+
45+ redo ( ) : Change | null {
46+ if ( this . future . length === 0 ) {
47+ return null ;
48+ }
49+
50+ const nextChange = this . future . pop ( ) ;
51+ this . past . push ( nextChange ) ;
52+ return nextChange ;
53+ }
54+ }
55+
1756function updateLineNumberHeight ( ) {
1857 const nrCells = document . querySelectorAll < HTMLElement > ( ".odr-text-nr > div" ) ;
1958 const textCells = document . querySelectorAll < HTMLElement > ( ".odr-text-body > div" ) ;
@@ -27,8 +66,7 @@ function updateLineNumberHeight() {
2766
2867const textNr = document . querySelector < HTMLElement > ( ".odr-text-nr" ) ;
2968const textBody = document . querySelector < HTMLElement > ( ".odr-text-body" ) ;
30- const changeHistory : Change [ ] = [ ] ;
31- const changeFuture : Change [ ] = [ ] ;
69+ const changeHistory = new History ( ) ;
3270
3371const resizeObserver = new ResizeObserver ( entries => {
3472 updateLineNumberHeight ( ) ;
@@ -255,23 +293,19 @@ function undoChange(change: Change) {
255293}
256294
257295function undo ( ) {
258- if ( changeHistory . length === 0 ) {
296+ if ( ! changeHistory . canUndo ( ) ) {
259297 return ;
260298 }
261-
262- const lastChange = changeHistory . pop ( ) ;
299+ const lastChange = changeHistory . undo ( ) ;
263300 undoChange ( lastChange ) ;
264- changeFuture . push ( lastChange ) ;
265301}
266302
267303function redo ( ) {
268- if ( changeFuture . length === 0 ) {
304+ if ( ! changeHistory . canRedo ( ) ) {
269305 return ;
270306 }
271-
272- const nextChange = changeFuture . pop ( ) ;
307+ const nextChange = changeHistory . redo ( ) ;
273308 doChange ( nextChange ) ;
274- changeHistory . push ( nextChange ) ;
275309}
276310
277311function insertTextAction ( text : string ) {
@@ -293,7 +327,6 @@ function insertTextAction(text: string) {
293327 text : text ,
294328 position : position ,
295329 } ) ;
296- console . log ( "changeHistory" , changeHistory ) ;
297330
298331 placeCursorAt ( newPosition ) ;
299332}
0 commit comments