| 1 |
/** |
| 2 |
* Common functions that are used in TablePress JS. |
| 3 |
* |
| 4 |
* @package TablePress |
| 5 |
* @subpackage Views JavaScript |
| 6 |
* @author Tobias Bäthge |
| 7 |
* @since 2.2.0 |
| 8 |
*/ |
| 9 |
|
| 10 |
/** |
| 11 |
* WordPress dependencies. |
| 12 |
*/ |
| 13 |
import { __, _x, sprintf } from '@wordpress/i18n'; |
| 14 |
|
| 15 |
/** |
| 16 |
* Registers a "Save Changes" keyboard shortcut for a button. |
| 17 |
* |
| 18 |
* @since 2.2.0 |
| 19 |
* |
| 20 |
* @param {HTMLElement} $button DOM element for the button. |
| 21 |
*/ |
| 22 |
export const register_save_changes_keyboard_shortcut = ( $button ) => { |
| 23 |
// Add keyboard shortcut as title attribute to the "Save Changes" button, with correct modifier key for Mac/non-Mac. |
| 24 |
const modifier_key = ( window?.navigator?.platform?.includes( 'Mac' ) ) ? |
| 25 |
_x( '⌘', 'keyboard shortcut modifier key on a Mac keyboard', 'tablepress' ) : |
| 26 |
_x( 'Ctrl+', 'keyboard shortcut modifier key on a non-Mac keyboard', 'tablepress' ); |
| 27 |
const shortcut = sprintf( $button.dataset.shortcut, modifier_key ); // eslint-disable-line @wordpress/valid-sprintf |
| 28 |
$button.title = sprintf( __( 'Keyboard Shortcut: %s', 'tablepress' ), shortcut ); |
| 29 |
|
| 30 |
/** |
| 31 |
* Registers keyboard events and triggers corresponding actions by emulating button clicks. |
| 32 |
* |
| 33 |
* @since 2.2.0 |
| 34 |
* |
| 35 |
* @param {Event} event Keyboard event. |
| 36 |
*/ |
| 37 |
const keyboard_shortcuts = ( event ) => { |
| 38 |
let action = ''; |
| 39 |
|
| 40 |
if ( event.ctrlKey || event.metaKey ) { |
| 41 |
if ( 83 === event.keyCode ) { |
| 42 |
// Save Changes: Ctrl/Cmd + S. |
| 43 |
action = 'save-changes'; |
| 44 |
} |
| 45 |
} |
| 46 |
|
| 47 |
if ( 'save-changes' === action ) { |
| 48 |
// Blur the focussed element to make sure that all change events were triggered. |
| 49 |
document.activeElement.blur(); // eslint-disable-line @wordpress/no-global-active-element |
| 50 |
|
| 51 |
// Emulate a click on the button corresponding to the action. |
| 52 |
$button.click(); |
| 53 |
|
| 54 |
// Prevent the browser's native handling of the shortcut, i.e. showing the Save or Print dialogs. |
| 55 |
event.preventDefault(); |
| 56 |
} |
| 57 |
}; |
| 58 |
// Register keyboard shortcut handler. |
| 59 |
window.addEventListener( 'keydown', keyboard_shortcuts, true ); |
| 60 |
}; |
| 61 |
|