All files / roosterjs-content-model-core/lib/corePlugin/undo UndoPlugin.ts

91.84% Statements 90/98
83.33% Branches 75/90
88.24% Functions 15/17
91.84% Lines 90/98

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 2641x 1x 1x                   1x 1x 1x         1x 136x               136x                       1x               1x 134x           1x 106x           1x 139x             1x 13x                         1x 420x       420x   102x 102x 102x   102x     100x   102x   7x 7x   6x 6x   1x 1x 1x   62x 62x   2x 2x     2x 1x   2x       1x 7x         7x 3x 1x 1x 1x 1x 2x 2x           2x             1x       2x 2x   4x           4x 1x 1x         1x 6x           6x   6x         4x   4x     2x     2x     6x     1x       2x 1x     2x 2x     1x 62x               58x       1x 61x 61x 61x     1x 7x   7x                 1x 109x 109x     1x         1x             1x 136x    
import { ChangeSource, isCursorMovingKey } from 'roosterjs-content-model-dom';
import { createSnapshotsManager } from './SnapshotsManagerImpl';
import { undo } from '../../command/undo/undo';
import type {
    ContentChangedEvent,
    IEditor,
    PluginEvent,
    PluginWithState,
    EditorOptions,
    UndoPluginState,
} from 'roosterjs-content-model-types';
 
const Backspace = 'Backspace';
const Delete = 'Delete';
const Enter = 'Enter';
 
/**
 * Provides snapshot based undo service for Editor
 */
class UndoPlugin implements PluginWithState<UndoPluginState> {
    private editor: IEditor | null = null;
    private state: UndoPluginState;
 
    /**
     * Construct a new instance of UndoPlugin
     * @param options The wrapper of the state object
     */
    constructor(options: EditorOptions) {
        this.state = {
            snapshotsManager: createSnapshotsManager(options.snapshots),
            isRestoring: false,
            isNested: false,
            autoCompleteInsertPoint: null,
            lastKeyPress: null,
        };
    }
 
    /**
     * Get a friendly name of  this plugin
     */
    getName() {
        return 'Undo';
    }
 
    /**
     * Initialize this plugin. This should only be called from Editor
     * @param editor Editor instance
     */
    initialize(editor: IEditor): void {
        this.editor = editor;
    }
 
    /**
     * Dispose this plugin
     */
    dispose() {
        this.editor = null;
    }
 
    /**
     * Get plugin state object
     */
    getState() {
        return this.state;
    }
 
    /**
     * Check if the plugin should handle the given event exclusively.
     * @param event The event to check
     */
    willHandleEventExclusively(event: PluginEvent) {
        return (
            !!this.editor &&
            event.eventType == 'keyDown' &&
            event.rawEvent.key == Backspace &&
            !event.rawEvent.ctrlKey &&
            this.canUndoAutoComplete(this.editor)
        );
    }
 
    /**
     * Handle events triggered from editor
     * @param event PluginEvent object
     */
    onPluginEvent(event: PluginEvent): void {
        Iif (!this.editor) {
            return;
        }
 
        switch (event.eventType) {
            case 'editorReady':
                const manager = this.state.snapshotsManager;
                const canUndo = manager.hasNewContent || manager.canMove(-1);
                const canRedo = manager.canMove(1);
 
                if (!canUndo && !canRedo) {
                    // Only add initial snapshot when there is no existing snapshot
                    // Otherwise preserved undo/redo state may be ruined
                    this.addUndoSnapshot();
                }
                break;
            case 'keyDown':
                this.onKeyDown(this.editor, event.rawEvent);
                break;
            case 'keyPress':
                this.onKeyPress(this.editor, event.rawEvent);
                break;
            case 'compositionEnd':
                this.clearRedoForInput();
                this.addUndoSnapshot();
                break;
            case 'contentChanged':
                this.onContentChanged(event);
                break;
            case 'beforeKeyboardEditing':
                this.onBeforeKeyboardEditing(event.rawEvent);
                break;
 
            case 'mouseDown':
                if (this.state.snapshotsManager.hasNewContent) {
                    this.addUndoSnapshot();
                }
                break;
        }
    }
 
    private onKeyDown(editor: IEditor, evt: KeyboardEvent): void {
        const { snapshotsManager } = this.state;
 
        // Handle backspace/delete when there is a selection to take a snapshot
        // since we want the state prior to deletion restorable
        // Ignore if keycombo is ALT+BACKSPACE
        if ((evt.key == Backspace && !evt.altKey) || evt.key == Delete) {
            if (evt.key == Backspace && !evt.ctrlKey && this.canUndoAutoComplete(editor)) {
                evt.preventDefault();
                undo(editor);
                this.state.autoCompleteInsertPoint = null;
                this.state.lastKeyPress = evt.key;
            } else Eif (!evt.defaultPrevented) {
                const selection = editor.getDOMSelection();
 
                // Add snapshot when
                // 1. Something has been selected (not collapsed), or
                // 2. It has a different key code from the last keyDown event (to prevent adding too many snapshot when keeping press the same key), or
                // 3. Ctrl/Meta key is pressed so that a whole word will be deleted
                if (
                    selection &&
                    (selection.type != 'range' ||
                        !selection.range.collapsed ||
                        this.state.lastKeyPress != evt.key ||
                        this.isCtrlOrMetaPressed(editor, evt))
                ) {
                    this.addUndoSnapshot();
                }
 
                // Since some content is deleted, always set hasNewContent to true so that we will take undo snapshot next time
                snapshotsManager.hasNewContent = true;
                this.state.lastKeyPress = evt.key;
            }
        } else Iif (isCursorMovingKey(evt)) {
            // PageUp, PageDown, Home, End, Left, Right, Up, Down
            if (snapshotsManager.hasNewContent) {
                this.addUndoSnapshot();
            }
            this.state.lastKeyPress = null;
        } else if (this.state.lastKeyPress == Backspace || this.state.lastKeyPress == Delete) {
            Eif (snapshotsManager.hasNewContent) {
                this.addUndoSnapshot();
            }
        }
    }
 
    private onKeyPress(editor: IEditor, evt: KeyboardEvent): void {
        Iif (evt.metaKey) {
            // if metaKey is pressed, simply return since no actual effect will be taken on the editor.
            // this is to prevent changing hasNewContent to true when meta + v to paste on Safari.
            return;
        }
 
        const selection = editor.getDOMSelection();
 
        if (
            (selection && (selection.type != 'range' || !selection.range.collapsed)) ||
            (evt.key == ' ' && this.state.lastKeyPress != ' ') ||
            evt.key == Enter
        ) {
            this.addUndoSnapshot();
 
            if (evt.key == Enter) {
                // Treat ENTER as new content so if there is no input after ENTER and undo,
                // we restore the snapshot before ENTER
                this.state.snapshotsManager.hasNewContent = true;
            }
        } else {
            this.clearRedoForInput();
        }
 
        this.state.lastKeyPress = evt.key;
    }
 
    private onBeforeKeyboardEditing(event: KeyboardEvent) {
        // For keyboard event (triggered from Content Model), we can get its keycode from event.data
        // And when user is keep pressing the same key, mark editor with "hasNewContent" so that next time user
        // do some other action or press a different key, we will add undo snapshot
        if (event.key != this.state.lastKeyPress) {
            this.addUndoSnapshot();
        }
 
        this.state.lastKeyPress = event.key;
        this.state.snapshotsManager.hasNewContent = true;
    }
 
    private onContentChanged(event: ContentChangedEvent) {
        if (
            !(
                this.state.isRestoring ||
                event.source == ChangeSource.SwitchToDarkMode ||
                event.source == ChangeSource.SwitchToLightMode ||
                event.source == ChangeSource.Keyboard
            )
        ) {
            this.clearRedoForInput();
        }
    }
 
    private clearRedoForInput() {
        this.state.snapshotsManager.clearRedo();
        this.state.lastKeyPress = null;
        this.state.snapshotsManager.hasNewContent = true;
    }
 
    private canUndoAutoComplete(editor: IEditor) {
        const selection = editor.getDOMSelection();
 
        return (
            this.state.snapshotsManager.canUndoAutoComplete() &&
            selection?.type == 'range' &&
            selection.range.collapsed &&
            selection.range.startContainer == this.state.autoCompleteInsertPoint?.node &&
            selection.range.startOffset == this.state.autoCompleteInsertPoint.offset
        );
    }
 
    private addUndoSnapshot() {
        this.editor?.takeSnapshot();
        this.state.autoCompleteInsertPoint = null;
    }
 
    private isCtrlOrMetaPressed(editor: IEditor, event: KeyboardEvent) {
        const env = editor.getEnvironment();
 
        return env.isMac ? event.metaKey : event.ctrlKey;
    }
}
 
/**
 * @internal
 * Create a new instance of UndoPlugin.
 * @param option The editor option
 */
export function createUndoPlugin(option: EditorOptions): PluginWithState<UndoPluginState> {
    return new UndoPlugin(option);
}