keyboard.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. /**
  2. * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /**
  6. * Set of utils related to keyboard support.
  7. *
  8. * @module utils/keyboard
  9. */
  10. import CKEditorError from './ckeditorerror';
  11. import env from './env';
  12. const macGlyphsToModifiers = {
  13. '⌘': 'ctrl',
  14. '⇧': 'shift',
  15. '⌥': 'alt'
  16. };
  17. const modifiersToMacGlyphs = {
  18. 'ctrl': '⌘',
  19. 'shift': '⇧',
  20. 'alt': '⌥'
  21. };
  22. /**
  23. * Object with `keyName => keyCode` pairs for a set of known keys.
  24. *
  25. * Contains:
  26. *
  27. * * `a-z`,
  28. * * `0-9`,
  29. * * `f1-f12`,
  30. * * `arrow(left|up|right|bottom)`,
  31. * * `backspace`, `delete`, `enter`, `esc`, `tab`,
  32. * * `ctrl`, `cmd`, `shift`, `alt`.
  33. */
  34. export const keyCodes = generateKnownKeyCodes();
  35. /**
  36. * Converts a key name or a {@link module:utils/keyboard~KeystrokeInfo keystroke info} into a key code.
  37. *
  38. * Note: Key names are matched with {@link module:utils/keyboard~keyCodes} in a case-insensitive way.
  39. *
  40. * @param {String|module:utils/keyboard~KeystrokeInfo} Key name (see {@link module:utils/keyboard~keyCodes})
  41. * or a keystroke data object.
  42. * @returns {Number} Key or keystroke code.
  43. */
  44. export function getCode( key ) {
  45. let keyCode;
  46. if ( typeof key == 'string' ) {
  47. keyCode = keyCodes[ key.toLowerCase() ];
  48. if ( !keyCode ) {
  49. /**
  50. * Unknown key name. Only key names contained by the {@link module:utils/keyboard~keyCodes} can be used.
  51. *
  52. * @error keyboard-unknown-key
  53. * @param {String} key
  54. */
  55. throw new CKEditorError( 'keyboard-unknown-key', null, { key } );
  56. }
  57. } else {
  58. keyCode = key.keyCode +
  59. ( key.altKey ? keyCodes.alt : 0 ) +
  60. ( key.ctrlKey ? keyCodes.ctrl : 0 ) +
  61. ( key.shiftKey ? keyCodes.shift : 0 );
  62. }
  63. return keyCode;
  64. }
  65. /**
  66. * Parses keystroke and returns a keystroke code that will match the code returned by
  67. * link {@link module:utils/keyboard~getCode} for a corresponding {@link module:utils/keyboard~KeystrokeInfo keystroke info}.
  68. *
  69. * The keystroke can be passed in two formats:
  70. *
  71. * * as a single string – e.g. `ctrl + A`,
  72. * * as an array of {@link module:utils/keyboard~keyCodes known key names} and key codes – e.g.:
  73. * * `[ 'ctrl', 32 ]` (ctrl + space),
  74. * * `[ 'ctrl', 'a' ]` (ctrl + A).
  75. *
  76. * Note: Key names are matched with {@link module:utils/keyboard~keyCodes} in a case-insensitive way.
  77. *
  78. * Note: Only keystrokes with a single non-modifier key are supported (e.g. `ctrl+A` is OK, but `ctrl+A+B` is not).
  79. *
  80. * @param {String|Array.<Number|String>} keystroke Keystroke definition.
  81. * @returns {Number} Keystroke code.
  82. */
  83. export function parseKeystroke( keystroke ) {
  84. if ( typeof keystroke == 'string' ) {
  85. keystroke = splitKeystrokeText( keystroke );
  86. }
  87. return keystroke
  88. .map( key => ( typeof key == 'string' ) ? getCode( key ) : key )
  89. .reduce( ( key, sum ) => sum + key, 0 );
  90. }
  91. /**
  92. * It translates any keystroke string text like `"CTRL+A"` to an
  93. * environment–specific keystroke, i.e. `"⌘A"` on Mac OSX.
  94. *
  95. * @param {String} keystroke Keystroke text.
  96. * @returns {String} Keystroke text specific for the environment.
  97. */
  98. export function getEnvKeystrokeText( keystroke ) {
  99. if ( !env.isMac ) {
  100. return keystroke;
  101. }
  102. return splitKeystrokeText( keystroke )
  103. // Replace modifiers (e.g. "ctrl") with Mac glyphs (e.g. "⌘") first.
  104. .map( key => modifiersToMacGlyphs[ key.toLowerCase() ] || key )
  105. // Decide whether to put "+" between keys in the keystroke or not.
  106. .reduce( ( value, key ) => {
  107. if ( value.slice( -1 ) in macGlyphsToModifiers ) {
  108. return value + key;
  109. } else {
  110. return value + '+' + key;
  111. }
  112. } );
  113. }
  114. /**
  115. * Returns `true` if the provided key code represents one of the arrow keys.
  116. *
  117. * @param {Number} keyCode A key code as in {@link module:utils/keyboard~KeystrokeInfo#keyCode}.
  118. * @returns {Boolean}
  119. */
  120. export function isArrowKeyCode( keyCode ) {
  121. return keyCode == keyCodes.arrowright ||
  122. keyCode == keyCodes.arrowleft ||
  123. keyCode == keyCodes.arrowup ||
  124. keyCode == keyCodes.arrowdown;
  125. }
  126. /**
  127. * Returns the direction in which the {@link module:engine/model/documentselection~DocumentSelection selection}
  128. * will move when a provided arrow key code is pressed considering the language direction of the editor content.
  129. *
  130. * For instance, in right–to–left (RTL) content languages, pressing the left arrow means moving selection right (forward)
  131. * in the model structure. Similarly, pressing the right arrow moves the selection left (backward).
  132. *
  133. * @param {Number} keyCode A key code as in {@link module:utils/keyboard~KeystrokeInfo#keyCode}.
  134. * @param {'ltr'|'rtl'} contentLanguageDirection The content language direction, corresponding to
  135. * {@link module:utils/locale~Locale#contentLanguageDirection}.
  136. * @returns {'left'|'up'|'right'|'down'} Localized arrow direction.
  137. */
  138. export function getLocalizedArrowKeyCodeDirection( keyCode, contentLanguageDirection ) {
  139. const isLtrContent = contentLanguageDirection === 'ltr';
  140. switch ( keyCode ) {
  141. case keyCodes.arrowleft:
  142. return isLtrContent ? 'left' : 'right';
  143. case keyCodes.arrowright:
  144. return isLtrContent ? 'right' : 'left';
  145. case keyCodes.arrowup:
  146. return 'up';
  147. case keyCodes.arrowdown:
  148. return 'down';
  149. }
  150. }
  151. /**
  152. * Determines if the provided key code moves the {@link module:engine/model/documentselection~DocumentSelection selection}
  153. * forward or backward considering the language direction of the editor content.
  154. *
  155. * For instance, in right–to–left (RTL) languages, pressing the left arrow means moving forward
  156. * in the model structure. Similarly, pressing the right arrow moves the selection backward.
  157. *
  158. * @param {Number} keyCode A key code as in {@link module:utils/keyboard~KeystrokeInfo#keyCode}.
  159. * @param {'ltr'|'rtl'} contentLanguageDirection The content language direction, corresponding to
  160. * {@link module:utils/locale~Locale#contentLanguageDirection}.
  161. * @returns {Boolean}
  162. */
  163. export function isForwardArrowKeyCode( keyCode, contentLanguageDirection ) {
  164. const localizedKeyCodeDirection = getLocalizedArrowKeyCodeDirection( keyCode, contentLanguageDirection );
  165. return localizedKeyCodeDirection === 'down' || localizedKeyCodeDirection === 'right';
  166. }
  167. function generateKnownKeyCodes() {
  168. const keyCodes = {
  169. arrowleft: 37,
  170. arrowup: 38,
  171. arrowright: 39,
  172. arrowdown: 40,
  173. backspace: 8,
  174. delete: 46,
  175. enter: 13,
  176. space: 32,
  177. esc: 27,
  178. tab: 9,
  179. // The idea about these numbers is that they do not collide with any real key codes, so we can use them
  180. // like bit masks.
  181. ctrl: 0x110000,
  182. // Has the same code as ctrl, because their behaviour should be unified across the editor.
  183. // See http://ckeditor.github.io/editor-recommendations/general-policies#ctrl-vs-cmd
  184. cmd: 0x110000,
  185. shift: 0x220000,
  186. alt: 0x440000
  187. };
  188. // a-z
  189. for ( let code = 65; code <= 90; code++ ) {
  190. const letter = String.fromCharCode( code );
  191. keyCodes[ letter.toLowerCase() ] = code;
  192. }
  193. // 0-9
  194. for ( let code = 48; code <= 57; code++ ) {
  195. keyCodes[ code - 48 ] = code;
  196. }
  197. // F1-F12
  198. for ( let code = 112; code <= 123; code++ ) {
  199. keyCodes[ 'f' + ( code - 111 ) ] = code;
  200. }
  201. return keyCodes;
  202. }
  203. function splitKeystrokeText( keystroke ) {
  204. return keystroke.split( /\s*\+\s*/ );
  205. }
  206. /**
  207. * Information about a keystroke.
  208. *
  209. * @interface module:utils/keyboard~KeystrokeInfo
  210. */
  211. /**
  212. * The [key code](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode).
  213. *
  214. * @member {Number} module:utils/keyboard~KeystrokeInfo#keyCode
  215. */
  216. /**
  217. * Whether the <kbd>Alt</kbd> modifier was pressed.
  218. *
  219. * @member {Bolean} module:utils/keyboard~KeystrokeInfo#altKey
  220. */
  221. /**
  222. * Whether the <kbd>Ctrl</kbd> or <kbd>Cmd</kbd> modifier was pressed.
  223. *
  224. * @member {Bolean} module:utils/keyboard~KeystrokeInfo#ctrlKey
  225. */
  226. /**
  227. * Whether the <kbd>Shift</kbd> modifier was pressed.
  228. *
  229. * @member {Bolean} module:utils/keyboard~KeystrokeInfo#shiftKey
  230. */