|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright 2025 Google LLC |
| 4 | + * SPDX-License-Identifier: Apache-2.0 |
| 5 | + */ |
| 6 | + |
| 7 | +import { |
| 8 | + ShortcutRegistry, |
| 9 | + utils as BlocklyUtils, |
| 10 | + ShortcutItems, |
| 11 | + WorkspaceSvg, |
| 12 | +} from 'blockly/core'; |
| 13 | + |
| 14 | +import * as Constants from '../constants'; |
| 15 | +import type {Navigation} from '../navigation'; |
| 16 | + |
| 17 | +const KeyCodes = BlocklyUtils.KeyCodes; |
| 18 | + |
| 19 | +/** |
| 20 | + * Class for registering a shortcut for undo/redo actions. |
| 21 | + */ |
| 22 | +export class UndoRedoAction { |
| 23 | + private originalUndo?: ShortcutRegistry.KeyboardShortcut; |
| 24 | + private originalRedo?: ShortcutRegistry.KeyboardShortcut; |
| 25 | + /** |
| 26 | + * Patches the existing undo/redo shortcuts in the registry. |
| 27 | + */ |
| 28 | + install() { |
| 29 | + const undo = |
| 30 | + ShortcutRegistry.registry.getRegistry()[ShortcutItems.names.UNDO]; |
| 31 | + if (undo) { |
| 32 | + this.originalUndo = undo; |
| 33 | + const patchedUndo = { |
| 34 | + ...this.originalUndo, |
| 35 | + preconditionFn: (workspace: WorkspaceSvg) => { |
| 36 | + return !!( |
| 37 | + !workspace.isDragging() && undo.preconditionFn?.(workspace) |
| 38 | + ); |
| 39 | + }, |
| 40 | + allowCollision: true, |
| 41 | + }; |
| 42 | + |
| 43 | + ShortcutRegistry.registry.register(patchedUndo, true); |
| 44 | + } |
| 45 | + |
| 46 | + const redo = |
| 47 | + ShortcutRegistry.registry.getRegistry()[ShortcutItems.names.REDO]; |
| 48 | + if (redo) { |
| 49 | + this.originalRedo = redo; |
| 50 | + const patchedRedo = { |
| 51 | + ...this.originalRedo, |
| 52 | + preconditionFn: (workspace: WorkspaceSvg) => { |
| 53 | + return !!( |
| 54 | + !workspace.isDragging() && redo.preconditionFn?.(workspace) |
| 55 | + ); |
| 56 | + }, |
| 57 | + allowCollision: true, |
| 58 | + }; |
| 59 | + |
| 60 | + ShortcutRegistry.registry.register(patchedRedo, true); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + /** |
| 65 | + * Reverts the patched undo/redo shortcuts in the registry. |
| 66 | + */ |
| 67 | + uninstall() { |
| 68 | + if (this.originalUndo) { |
| 69 | + ShortcutRegistry.registry.register(this.originalUndo, true); |
| 70 | + this.originalUndo = undefined; |
| 71 | + } |
| 72 | + if (this.originalRedo) { |
| 73 | + ShortcutRegistry.registry.register(this.originalRedo, true); |
| 74 | + this.originalRedo = undefined; |
| 75 | + } |
| 76 | + } |
| 77 | +} |
0 commit comments