editingkeystrokehandler.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /**
  2. * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module core/editingkeystrokehandler
  7. */
  8. import KeystrokeHandler from '@ckeditor/ckeditor5-utils/src/keystrokehandler';
  9. /**
  10. * A keystroke handler for editor editing. Its instance is available
  11. * in {@link module:core/editor/standardeditor~StandardEditor#keystrokes} so plugins
  12. * can register their keystrokes.
  13. *
  14. * E.g. an undo plugin would do this:
  15. *
  16. * editor.keystrokes.set( 'ctrl + Z', 'undo' );
  17. * editor.keystrokes.set( 'ctrl + shift + Z', 'redo' );
  18. * editor.keystrokes.set( 'ctrl + Y', 'redo' );
  19. *
  20. * @extends utils/keystrokehandler~KeystrokeHandler
  21. */
  22. export default class EditingKeystrokeHandler extends KeystrokeHandler {
  23. /**
  24. * Creates an instance of the keystroke handler.
  25. *
  26. * @param {module:core/editor/editor~Editor} editor
  27. */
  28. constructor( editor ) {
  29. super();
  30. /**
  31. * The editor instance.
  32. *
  33. * @readonly
  34. * @member {module:core/editor/editor~Editor}
  35. */
  36. this.editor = editor;
  37. }
  38. /**
  39. * Registers a handler for the specified keystroke.
  40. *
  41. * * The handler can be specified as a command name or a callback.
  42. *
  43. * @param {String|Array.<String|Number>} keystroke Keystroke defined in a format accepted by
  44. * the {@link module:utils/keyboard~parseKeystroke} function.
  45. * @param {Function} callback If a string is passed, then the keystroke will
  46. * {@link module:core/editor/editor~Editor#execute execute a command}.
  47. * If a function, then it will be called with the
  48. * {@link module:engine/view/observer/keyobserver~KeyEventData key event data} object and
  49. * a helper to both `preventDefault` and `stopPropagation` of the event.
  50. */
  51. set( keystroke, callback ) {
  52. if ( typeof callback == 'string' ) {
  53. const commandName = callback;
  54. callback = () => {
  55. this.editor.execute( commandName );
  56. };
  57. }
  58. super.set( keystroke, callback );
  59. }
  60. /**
  61. * @inheritDoc
  62. */
  63. listenTo( emitter ) {
  64. this._listener.listenTo( emitter, 'keydown', ( evt, data ) => {
  65. const handled = this.press( data );
  66. if ( handled ) {
  67. data.preventDefault();
  68. }
  69. } );
  70. }
  71. }