|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright 2025 Google LLC |
| 4 | + * SPDX-License-Identifier: Apache-2.0 |
| 5 | + */ |
| 6 | + |
| 7 | +/** |
| 8 | + * The KeyboardNavigationController handles coordinating Blockly-wide |
| 9 | + * keyboard navigation behavior, such as enabling/disabling full |
| 10 | + * cursor visualization. |
| 11 | + */ |
| 12 | +export class KeyboardNavigationController { |
| 13 | + /** Whether the user is actively using keyboard navigation. */ |
| 14 | + private isActive = false; |
| 15 | + /** Css class name added to body if keyboard nav is active. */ |
| 16 | + private activeClassName = 'blocklyKeyboardNavigation'; |
| 17 | + |
| 18 | + /** |
| 19 | + * Sets whether a user is actively using keyboard navigation. |
| 20 | + * |
| 21 | + * If they are, apply a css class to the entire page so that |
| 22 | + * focused items can apply additional styling for keyboard users. |
| 23 | + * |
| 24 | + * Note that since enabling keyboard navigation presents significant UX changes |
| 25 | + * (such as cursor visualization and move mode), callers should take care to |
| 26 | + * only set active keyboard navigation when they have a high confidence in that |
| 27 | + * being the correct state. In general, in any given mouse or key input situation |
| 28 | + * callers can choose one of three paths: |
| 29 | + * 1. Do nothing. This should be the choice for neutral actions that don't |
| 30 | + * predominantly imply keyboard or mouse usage (such as clicking to select a block). |
| 31 | + * 2. Disable keyboard navigation. This is the best choice when a user is definitely |
| 32 | + * predominantly using the mouse (such as using a right click to open the context menu). |
| 33 | + * 3. Enable keyboard navigation. This is the best choice when there's high confidence |
| 34 | + * a user actually intends to use it (such as attempting to use the arrow keys to move |
| 35 | + * around). |
| 36 | + * |
| 37 | + * @param isUsing |
| 38 | + */ |
| 39 | + setIsActive(isUsing: boolean = true) { |
| 40 | + this.isActive = isUsing; |
| 41 | + this.updateActiveVisualization(); |
| 42 | + } |
| 43 | + |
| 44 | + /** |
| 45 | + * @returns true if the user is actively using keyboard navigation |
| 46 | + * (e.g., has recently taken some action that is only relevant to keyboard users) |
| 47 | + */ |
| 48 | + getIsActive(): boolean { |
| 49 | + return this.isActive; |
| 50 | + } |
| 51 | + |
| 52 | + /** Adds or removes the css class that indicates keyboard navigation is active. */ |
| 53 | + private updateActiveVisualization() { |
| 54 | + if (this.isActive) { |
| 55 | + document.body.classList.add(this.activeClassName); |
| 56 | + } else { |
| 57 | + document.body.classList.remove(this.activeClassName); |
| 58 | + } |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +/** Singleton instance of the keyboard navigation controller. */ |
| 63 | +export const keyboardNavigationController = new KeyboardNavigationController(); |
0 commit comments