|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright 2025 Google LLC |
| 4 | + * SPDX-License-Identifier: Apache-2.0 |
| 5 | + */ |
| 6 | + |
| 7 | +import {ShortcutRegistry, WorkspaceSvg, utils} from 'blockly/core'; |
| 8 | +import * as Constants from '../constants'; |
| 9 | + |
| 10 | +/** |
| 11 | + * Class for registering a shortcut for quick movement between top level bounds |
| 12 | + * in the workspace. |
| 13 | + */ |
| 14 | +export class StackNavigationAction { |
| 15 | + private stackShortcuts: ShortcutRegistry.KeyboardShortcut[] = []; |
| 16 | + |
| 17 | + install() { |
| 18 | + const preconditionFn = (workspace: WorkspaceSvg) => |
| 19 | + !!getCurNodeRoot(workspace); |
| 20 | + |
| 21 | + function getCurNodeRoot(workspace: WorkspaceSvg) { |
| 22 | + const cursor = workspace.getCursor(); |
| 23 | + // The fallback case includes workspace comments. |
| 24 | + return cursor.getSourceBlock()?.getRootBlock() ?? cursor.getCurNode(); |
| 25 | + } |
| 26 | + |
| 27 | + const previousStackShortcut: ShortcutRegistry.KeyboardShortcut = { |
| 28 | + name: Constants.SHORTCUT_NAMES.PREVIOUS_STACK, |
| 29 | + preconditionFn, |
| 30 | + callback: (workspace) => { |
| 31 | + const curNodeRoot = getCurNodeRoot(workspace); |
| 32 | + if (!curNodeRoot) return false; |
| 33 | + const prevRoot = workspace |
| 34 | + .getNavigator() |
| 35 | + .getPreviousSibling(curNodeRoot); |
| 36 | + if (!prevRoot) return false; |
| 37 | + workspace.getCursor().setCurNode(prevRoot); |
| 38 | + return true; |
| 39 | + }, |
| 40 | + keyCodes: [utils.KeyCodes.B], |
| 41 | + }; |
| 42 | + |
| 43 | + const nextStackShortcut: ShortcutRegistry.KeyboardShortcut = { |
| 44 | + name: Constants.SHORTCUT_NAMES.NEXT_STACK, |
| 45 | + preconditionFn, |
| 46 | + callback: (workspace) => { |
| 47 | + const curNodeRoot = getCurNodeRoot(workspace); |
| 48 | + if (!curNodeRoot) return false; |
| 49 | + const nextRoot = workspace.getNavigator().getNextSibling(curNodeRoot); |
| 50 | + if (!nextRoot) return false; |
| 51 | + workspace.getCursor().setCurNode(nextRoot); |
| 52 | + return true; |
| 53 | + }, |
| 54 | + keyCodes: [utils.KeyCodes.N], |
| 55 | + }; |
| 56 | + |
| 57 | + ShortcutRegistry.registry.register(previousStackShortcut); |
| 58 | + this.stackShortcuts.push(previousStackShortcut); |
| 59 | + ShortcutRegistry.registry.register(nextStackShortcut); |
| 60 | + this.stackShortcuts.push(nextStackShortcut); |
| 61 | + } |
| 62 | + |
| 63 | + /** |
| 64 | + * Unregisters the shortcut. |
| 65 | + */ |
| 66 | + uninstall() { |
| 67 | + this.stackShortcuts.forEach((shortcut) => |
| 68 | + ShortcutRegistry.registry.unregister(shortcut.name), |
| 69 | + ); |
| 70 | + this.stackShortcuts.length = 0; |
| 71 | + } |
| 72 | +} |
0 commit comments