mousetrap.js 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058
  1. /*global define:false */
  2. /**
  3. * Copyright 2012-2017 Craig Campbell
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. * Mousetrap is a simple keyboard shortcut library for Javascript with
  18. * no external dependencies
  19. *
  20. * @version 1.6.5
  21. * @url craig.is/killing/mice
  22. */
  23. (function(window, document, undefined) {
  24. // Check if mousetrap is used inside browser, if not, return
  25. if (!window) {
  26. return;
  27. }
  28. /**
  29. * mapping of special keycodes to their corresponding keys
  30. *
  31. * everything in this dictionary cannot use keypress events
  32. * so it has to be here to map to the correct keycodes for
  33. * keyup/keydown events
  34. *
  35. * @type {Object}
  36. */
  37. var _MAP = {
  38. 8: 'backspace',
  39. 9: 'tab',
  40. 13: 'enter',
  41. 16: 'shift',
  42. 17: 'ctrl',
  43. 18: 'alt',
  44. 20: 'capslock',
  45. 27: 'esc',
  46. 32: 'space',
  47. 33: 'pageup',
  48. 34: 'pagedown',
  49. 35: 'end',
  50. 36: 'home',
  51. 37: 'left',
  52. 38: 'up',
  53. 39: 'right',
  54. 40: 'down',
  55. 45: 'ins',
  56. 46: 'del',
  57. 91: 'meta',
  58. 93: 'meta',
  59. 224: 'meta'
  60. };
  61. /**
  62. * mapping for special characters so they can support
  63. *
  64. * this dictionary is only used incase you want to bind a
  65. * keyup or keydown event to one of these keys
  66. *
  67. * @type {Object}
  68. */
  69. var _KEYCODE_MAP = {
  70. 106: '*',
  71. 107: '+',
  72. 109: '-',
  73. 110: '.',
  74. 111 : '/',
  75. 186: ';',
  76. 187: '=',
  77. 188: ',',
  78. 189: '-',
  79. 190: '.',
  80. 191: '/',
  81. 192: '`',
  82. 219: '[',
  83. 220: '\\',
  84. 221: ']',
  85. 222: '\''
  86. };
  87. /**
  88. * this is a mapping of keys that require shift on a US keypad
  89. * back to the non shift equivelents
  90. *
  91. * this is so you can use keyup events with these keys
  92. *
  93. * note that this will only work reliably on US keyboards
  94. *
  95. * @type {Object}
  96. */
  97. var _SHIFT_MAP = {
  98. '~': '`',
  99. '!': '1',
  100. '@': '2',
  101. '#': '3',
  102. '$': '4',
  103. '%': '5',
  104. '^': '6',
  105. '&': '7',
  106. '*': '8',
  107. '(': '9',
  108. ')': '0',
  109. '_': '-',
  110. '+': '=',
  111. ':': ';',
  112. '\"': '\'',
  113. '<': ',',
  114. '>': '.',
  115. '?': '/',
  116. '|': '\\'
  117. };
  118. /**
  119. * this is a list of special strings you can use to map
  120. * to modifier keys when you specify your keyboard shortcuts
  121. *
  122. * @type {Object}
  123. */
  124. var _SPECIAL_ALIASES = {
  125. 'option': 'alt',
  126. 'command': 'meta',
  127. 'return': 'enter',
  128. 'escape': 'esc',
  129. 'plus': '+',
  130. 'mod': /Mac|iPod|iPhone|iPad/.test(navigator.platform) ? 'meta' : 'ctrl'
  131. };
  132. /**
  133. * variable to store the flipped version of _MAP from above
  134. * needed to check if we should use keypress or not when no action
  135. * is specified
  136. *
  137. * @type {Object|undefined}
  138. */
  139. var _REVERSE_MAP;
  140. /**
  141. * loop through the f keys, f1 to f19 and add them to the map
  142. * programatically
  143. */
  144. for (var i = 1; i < 20; ++i) {
  145. _MAP[111 + i] = 'f' + i;
  146. }
  147. /**
  148. * loop through to map numbers on the numeric keypad
  149. */
  150. for (i = 0; i <= 9; ++i) {
  151. // This needs to use a string cause otherwise since 0 is falsey
  152. // mousetrap will never fire for numpad 0 pressed as part of a keydown
  153. // event.
  154. //
  155. // @see https://github.com/ccampbell/mousetrap/pull/258
  156. _MAP[i + 96] = i.toString();
  157. }
  158. /**
  159. * cross browser add event method
  160. *
  161. * @param {Element|HTMLDocument} object
  162. * @param {string} type
  163. * @param {Function} callback
  164. * @returns void
  165. */
  166. function _addEvent(object, type, callback) {
  167. if (object.addEventListener) {
  168. object.addEventListener(type, callback, false);
  169. return;
  170. }
  171. object.attachEvent('on' + type, callback);
  172. }
  173. /**
  174. * takes the event and returns the key character
  175. *
  176. * @param {Event} e
  177. * @return {string}
  178. */
  179. function _characterFromEvent(e) {
  180. // for keypress events we should return the character as is
  181. if (e.type == 'keypress') {
  182. var character = String.fromCharCode(e.which);
  183. // if the shift key is not pressed then it is safe to assume
  184. // that we want the character to be lowercase. this means if
  185. // you accidentally have caps lock on then your key bindings
  186. // will continue to work
  187. //
  188. // the only side effect that might not be desired is if you
  189. // bind something like 'A' cause you want to trigger an
  190. // event when capital A is pressed caps lock will no longer
  191. // trigger the event. shift+a will though.
  192. if (!e.shiftKey) {
  193. character = character.toLowerCase();
  194. }
  195. return character;
  196. }
  197. // for non keypress events the special maps are needed
  198. if (_MAP[e.which]) {
  199. return _MAP[e.which];
  200. }
  201. if (_KEYCODE_MAP[e.which]) {
  202. return _KEYCODE_MAP[e.which];
  203. }
  204. // if it is not in the special map
  205. // with keydown and keyup events the character seems to always
  206. // come in as an uppercase character whether you are pressing shift
  207. // or not. we should make sure it is always lowercase for comparisons
  208. return String.fromCharCode(e.which).toLowerCase();
  209. }
  210. /**
  211. * checks if two arrays are equal
  212. *
  213. * @param {Array} modifiers1
  214. * @param {Array} modifiers2
  215. * @returns {boolean}
  216. */
  217. function _modifiersMatch(modifiers1, modifiers2) {
  218. return modifiers1.sort().join(',') === modifiers2.sort().join(',');
  219. }
  220. /**
  221. * takes a key event and figures out what the modifiers are
  222. *
  223. * @param {Event} e
  224. * @returns {Array}
  225. */
  226. function _eventModifiers(e) {
  227. var modifiers = [];
  228. if (e.shiftKey) {
  229. modifiers.push('shift');
  230. }
  231. if (e.altKey) {
  232. modifiers.push('alt');
  233. }
  234. if (e.ctrlKey) {
  235. modifiers.push('ctrl');
  236. }
  237. if (e.metaKey) {
  238. modifiers.push('meta');
  239. }
  240. return modifiers;
  241. }
  242. /**
  243. * prevents default for this event
  244. *
  245. * @param {Event} e
  246. * @returns void
  247. */
  248. function _preventDefault(e) {
  249. if (e.preventDefault) {
  250. e.preventDefault();
  251. return;
  252. }
  253. e.returnValue = false;
  254. }
  255. /**
  256. * stops propogation for this event
  257. *
  258. * @param {Event} e
  259. * @returns void
  260. */
  261. function _stopPropagation(e) {
  262. if (e.stopPropagation) {
  263. e.stopPropagation();
  264. return;
  265. }
  266. e.cancelBubble = true;
  267. }
  268. /**
  269. * determines if the keycode specified is a modifier key or not
  270. *
  271. * @param {string} key
  272. * @returns {boolean}
  273. */
  274. function _isModifier(key) {
  275. return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta';
  276. }
  277. /**
  278. * reverses the map lookup so that we can look for specific keys
  279. * to see what can and can't use keypress
  280. *
  281. * @return {Object}
  282. */
  283. function _getReverseMap() {
  284. if (!_REVERSE_MAP) {
  285. _REVERSE_MAP = {};
  286. for (var key in _MAP) {
  287. // pull out the numeric keypad from here cause keypress should
  288. // be able to detect the keys from the character
  289. if (key > 95 && key < 112) {
  290. continue;
  291. }
  292. if (_MAP.hasOwnProperty(key)) {
  293. _REVERSE_MAP[_MAP[key]] = key;
  294. }
  295. }
  296. }
  297. return _REVERSE_MAP;
  298. }
  299. /**
  300. * picks the best action based on the key combination
  301. *
  302. * @param {string} key - character for key
  303. * @param {Array} modifiers
  304. * @param {string=} action passed in
  305. */
  306. function _pickBestAction(key, modifiers, action) {
  307. // if no action was picked in we should try to pick the one
  308. // that we think would work best for this key
  309. if (!action) {
  310. action = _getReverseMap()[key] ? 'keydown' : 'keypress';
  311. }
  312. // modifier keys don't work as expected with keypress,
  313. // switch to keydown
  314. if (action == 'keypress' && modifiers.length) {
  315. action = 'keydown';
  316. }
  317. return action;
  318. }
  319. /**
  320. * Converts from a string key combination to an array
  321. *
  322. * @param {string} combination like "command+shift+l"
  323. * @return {Array}
  324. */
  325. function _keysFromString(combination) {
  326. if (combination === '+') {
  327. return ['+'];
  328. }
  329. combination = combination.replace(/\+{2}/g, '+plus');
  330. return combination.split('+');
  331. }
  332. /**
  333. * Gets info for a specific key combination
  334. *
  335. * @param {string} combination key combination ("command+s" or "a" or "*")
  336. * @param {string=} action
  337. * @returns {Object}
  338. */
  339. function _getKeyInfo(combination, action) {
  340. var keys;
  341. var key;
  342. var i;
  343. var modifiers = [];
  344. // take the keys from this pattern and figure out what the actual
  345. // pattern is all about
  346. keys = _keysFromString(combination);
  347. for (i = 0; i < keys.length; ++i) {
  348. key = keys[i];
  349. // normalize key names
  350. if (_SPECIAL_ALIASES[key]) {
  351. key = _SPECIAL_ALIASES[key];
  352. }
  353. // if this is not a keypress event then we should
  354. // be smart about using shift keys
  355. // this will only work for US keyboards however
  356. if (action && action != 'keypress' && _SHIFT_MAP[key]) {
  357. key = _SHIFT_MAP[key];
  358. modifiers.push('shift');
  359. }
  360. // if this key is a modifier then add it to the list of modifiers
  361. if (_isModifier(key)) {
  362. modifiers.push(key);
  363. }
  364. }
  365. // depending on what the key combination is
  366. // we will try to pick the best event for it
  367. action = _pickBestAction(key, modifiers, action);
  368. return {
  369. key: key,
  370. modifiers: modifiers,
  371. action: action
  372. };
  373. }
  374. function _belongsTo(element, ancestor) {
  375. if (element === null || element === document) {
  376. return false;
  377. }
  378. if (element === ancestor) {
  379. return true;
  380. }
  381. return _belongsTo(element.parentNode, ancestor);
  382. }
  383. function Mousetrap(targetElement) {
  384. var self = this;
  385. targetElement = targetElement || document;
  386. if (!(self instanceof Mousetrap)) {
  387. return new Mousetrap(targetElement);
  388. }
  389. /**
  390. * element to attach key events to
  391. *
  392. * @type {Element}
  393. */
  394. self.target = targetElement;
  395. /**
  396. * a list of all the callbacks setup via Mousetrap.bind()
  397. *
  398. * @type {Object}
  399. */
  400. self._callbacks = {};
  401. /**
  402. * direct map of string combinations to callbacks used for trigger()
  403. *
  404. * @type {Object}
  405. */
  406. self._directMap = {};
  407. /**
  408. * keeps track of what level each sequence is at since multiple
  409. * sequences can start out with the same sequence
  410. *
  411. * @type {Object}
  412. */
  413. var _sequenceLevels = {};
  414. /**
  415. * variable to store the setTimeout call
  416. *
  417. * @type {null|number}
  418. */
  419. var _resetTimer;
  420. /**
  421. * temporary state where we will ignore the next keyup
  422. *
  423. * @type {boolean|string}
  424. */
  425. var _ignoreNextKeyup = false;
  426. /**
  427. * temporary state where we will ignore the next keypress
  428. *
  429. * @type {boolean}
  430. */
  431. var _ignoreNextKeypress = false;
  432. /**
  433. * are we currently inside of a sequence?
  434. * type of action ("keyup" or "keydown" or "keypress") or false
  435. *
  436. * @type {boolean|string}
  437. */
  438. var _nextExpectedAction = false;
  439. /**
  440. * resets all sequence counters except for the ones passed in
  441. *
  442. * @param {Object} doNotReset
  443. * @returns void
  444. */
  445. function _resetSequences(doNotReset) {
  446. doNotReset = doNotReset || {};
  447. var activeSequences = false,
  448. key;
  449. for (key in _sequenceLevels) {
  450. if (doNotReset[key]) {
  451. activeSequences = true;
  452. continue;
  453. }
  454. _sequenceLevels[key] = 0;
  455. }
  456. if (!activeSequences) {
  457. _nextExpectedAction = false;
  458. }
  459. }
  460. /**
  461. * finds all callbacks that match based on the keycode, modifiers,
  462. * and action
  463. *
  464. * @param {string} character
  465. * @param {Array} modifiers
  466. * @param {Event|Object} e
  467. * @param {string=} sequenceName - name of the sequence we are looking for
  468. * @param {string=} combination
  469. * @param {number=} level
  470. * @returns {Array}
  471. */
  472. function _getMatches(character, modifiers, e, sequenceName, combination, level) {
  473. var i;
  474. var callback;
  475. var matches = [];
  476. var action = e.type;
  477. // if there are no events related to this keycode
  478. if (!self._callbacks[character]) {
  479. return [];
  480. }
  481. // if a modifier key is coming up on its own we should allow it
  482. if (action == 'keyup' && _isModifier(character)) {
  483. modifiers = [character];
  484. }
  485. // loop through all callbacks for the key that was pressed
  486. // and see if any of them match
  487. for (i = 0; i < self._callbacks[character].length; ++i) {
  488. callback = self._callbacks[character][i];
  489. // if a sequence name is not specified, but this is a sequence at
  490. // the wrong level then move onto the next match
  491. if (!sequenceName && callback.seq && _sequenceLevels[callback.seq] != callback.level) {
  492. continue;
  493. }
  494. // if the action we are looking for doesn't match the action we got
  495. // then we should keep going
  496. if (action != callback.action) {
  497. continue;
  498. }
  499. // if this is a keypress event and the meta key and control key
  500. // are not pressed that means that we need to only look at the
  501. // character, otherwise check the modifiers as well
  502. //
  503. // chrome will not fire a keypress if meta or control is down
  504. // safari will fire a keypress if meta or meta+shift is down
  505. // firefox will fire a keypress if meta or control is down
  506. if ((action == 'keypress' && !e.metaKey && !e.ctrlKey) || _modifiersMatch(modifiers, callback.modifiers)) {
  507. // when you bind a combination or sequence a second time it
  508. // should overwrite the first one. if a sequenceName or
  509. // combination is specified in this call it does just that
  510. //
  511. // @todo make deleting its own method?
  512. var deleteCombo = !sequenceName && callback.combo == combination;
  513. var deleteSequence = sequenceName && callback.seq == sequenceName && callback.level == level;
  514. if (deleteCombo || deleteSequence) {
  515. self._callbacks[character].splice(i, 1);
  516. }
  517. matches.push(callback);
  518. }
  519. }
  520. return matches;
  521. }
  522. /**
  523. * actually calls the callback function
  524. *
  525. * if your callback function returns false this will use the jquery
  526. * convention - prevent default and stop propogation on the event
  527. *
  528. * @param {Function} callback
  529. * @param {Event} e
  530. * @returns void
  531. */
  532. function _fireCallback(callback, e, combo, sequence) {
  533. // if this event should not happen stop here
  534. if (self.stopCallback(e, e.target || e.srcElement, combo, sequence)) {
  535. return;
  536. }
  537. if (callback(e, combo) === false) {
  538. _preventDefault(e);
  539. _stopPropagation(e);
  540. }
  541. }
  542. /**
  543. * handles a character key event
  544. *
  545. * @param {string} character
  546. * @param {Array} modifiers
  547. * @param {Event} e
  548. * @returns void
  549. */
  550. self._handleKey = function(character, modifiers, e) {
  551. var callbacks = _getMatches(character, modifiers, e);
  552. var i;
  553. var doNotReset = {};
  554. var maxLevel = 0;
  555. var processedSequenceCallback = false;
  556. // Calculate the maxLevel for sequences so we can only execute the longest callback sequence
  557. for (i = 0; i < callbacks.length; ++i) {
  558. if (callbacks[i].seq) {
  559. maxLevel = Math.max(maxLevel, callbacks[i].level);
  560. }
  561. }
  562. // loop through matching callbacks for this key event
  563. for (i = 0; i < callbacks.length; ++i) {
  564. // fire for all sequence callbacks
  565. // this is because if for example you have multiple sequences
  566. // bound such as "g i" and "g t" they both need to fire the
  567. // callback for matching g cause otherwise you can only ever
  568. // match the first one
  569. if (callbacks[i].seq) {
  570. // only fire callbacks for the maxLevel to prevent
  571. // subsequences from also firing
  572. //
  573. // for example 'a option b' should not cause 'option b' to fire
  574. // even though 'option b' is part of the other sequence
  575. //
  576. // any sequences that do not match here will be discarded
  577. // below by the _resetSequences call
  578. if (callbacks[i].level != maxLevel) {
  579. continue;
  580. }
  581. processedSequenceCallback = true;
  582. // keep a list of which sequences were matches for later
  583. doNotReset[callbacks[i].seq] = 1;
  584. _fireCallback(callbacks[i].callback, e, callbacks[i].combo, callbacks[i].seq);
  585. continue;
  586. }
  587. // if there were no sequence matches but we are still here
  588. // that means this is a regular match so we should fire that
  589. if (!processedSequenceCallback) {
  590. _fireCallback(callbacks[i].callback, e, callbacks[i].combo);
  591. }
  592. }
  593. // if the key you pressed matches the type of sequence without
  594. // being a modifier (ie "keyup" or "keypress") then we should
  595. // reset all sequences that were not matched by this event
  596. //
  597. // this is so, for example, if you have the sequence "h a t" and you
  598. // type "h e a r t" it does not match. in this case the "e" will
  599. // cause the sequence to reset
  600. //
  601. // modifier keys are ignored because you can have a sequence
  602. // that contains modifiers such as "enter ctrl+space" and in most
  603. // cases the modifier key will be pressed before the next key
  604. //
  605. // also if you have a sequence such as "ctrl+b a" then pressing the
  606. // "b" key will trigger a "keypress" and a "keydown"
  607. //
  608. // the "keydown" is expected when there is a modifier, but the
  609. // "keypress" ends up matching the _nextExpectedAction since it occurs
  610. // after and that causes the sequence to reset
  611. //
  612. // we ignore keypresses in a sequence that directly follow a keydown
  613. // for the same character
  614. var ignoreThisKeypress = e.type == 'keypress' && _ignoreNextKeypress;
  615. if (e.type == _nextExpectedAction && !_isModifier(character) && !ignoreThisKeypress) {
  616. _resetSequences(doNotReset);
  617. }
  618. _ignoreNextKeypress = processedSequenceCallback && e.type == 'keydown';
  619. };
  620. /**
  621. * handles a keydown event
  622. *
  623. * @param {Event} e
  624. * @returns void
  625. */
  626. function _handleKeyEvent(e) {
  627. // normalize e.which for key events
  628. // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
  629. if (typeof e.which !== 'number') {
  630. e.which = e.keyCode;
  631. }
  632. var character = _characterFromEvent(e);
  633. // no character found then stop
  634. if (!character) {
  635. return;
  636. }
  637. // need to use === for the character check because the character can be 0
  638. if (e.type == 'keyup' && _ignoreNextKeyup === character) {
  639. _ignoreNextKeyup = false;
  640. return;
  641. }
  642. self.handleKey(character, _eventModifiers(e), e);
  643. }
  644. /**
  645. * called to set a 1 second timeout on the specified sequence
  646. *
  647. * this is so after each key press in the sequence you have 1 second
  648. * to press the next key before you have to start over
  649. *
  650. * @returns void
  651. */
  652. function _resetSequenceTimer() {
  653. clearTimeout(_resetTimer);
  654. _resetTimer = setTimeout(_resetSequences, 1000);
  655. }
  656. /**
  657. * binds a key sequence to an event
  658. *
  659. * @param {string} combo - combo specified in bind call
  660. * @param {Array} keys
  661. * @param {Function} callback
  662. * @param {string=} action
  663. * @returns void
  664. */
  665. function _bindSequence(combo, keys, callback, action) {
  666. // start off by adding a sequence level record for this combination
  667. // and setting the level to 0
  668. _sequenceLevels[combo] = 0;
  669. /**
  670. * callback to increase the sequence level for this sequence and reset
  671. * all other sequences that were active
  672. *
  673. * @param {string} nextAction
  674. * @returns {Function}
  675. */
  676. function _increaseSequence(nextAction) {
  677. return function() {
  678. _nextExpectedAction = nextAction;
  679. ++_sequenceLevels[combo];
  680. _resetSequenceTimer();
  681. };
  682. }
  683. /**
  684. * wraps the specified callback inside of another function in order
  685. * to reset all sequence counters as soon as this sequence is done
  686. *
  687. * @param {Event} e
  688. * @returns void
  689. */
  690. function _callbackAndReset(e) {
  691. _fireCallback(callback, e, combo);
  692. // we should ignore the next key up if the action is key down
  693. // or keypress. this is so if you finish a sequence and
  694. // release the key the final key will not trigger a keyup
  695. if (action !== 'keyup') {
  696. _ignoreNextKeyup = _characterFromEvent(e);
  697. }
  698. // weird race condition if a sequence ends with the key
  699. // another sequence begins with
  700. setTimeout(_resetSequences, 10);
  701. }
  702. // loop through keys one at a time and bind the appropriate callback
  703. // function. for any key leading up to the final one it should
  704. // increase the sequence. after the final, it should reset all sequences
  705. //
  706. // if an action is specified in the original bind call then that will
  707. // be used throughout. otherwise we will pass the action that the
  708. // next key in the sequence should match. this allows a sequence
  709. // to mix and match keypress and keydown events depending on which
  710. // ones are better suited to the key provided
  711. for (var i = 0; i < keys.length; ++i) {
  712. var isFinal = i + 1 === keys.length;
  713. var wrappedCallback = isFinal ? _callbackAndReset : _increaseSequence(action || _getKeyInfo(keys[i + 1]).action);
  714. _bindSingle(keys[i], wrappedCallback, action, combo, i);
  715. }
  716. }
  717. /**
  718. * binds a single keyboard combination
  719. *
  720. * @param {string} combination
  721. * @param {Function} callback
  722. * @param {string=} action
  723. * @param {string=} sequenceName - name of sequence if part of sequence
  724. * @param {number=} level - what part of the sequence the command is
  725. * @returns void
  726. */
  727. function _bindSingle(combination, callback, action, sequenceName, level) {
  728. // store a direct mapped reference for use with Mousetrap.trigger
  729. self._directMap[combination + ':' + action] = callback;
  730. // make sure multiple spaces in a row become a single space
  731. combination = combination.replace(/\s+/g, ' ');
  732. var sequence = combination.split(' ');
  733. var info;
  734. // if this pattern is a sequence of keys then run through this method
  735. // to reprocess each pattern one key at a time
  736. if (sequence.length > 1) {
  737. _bindSequence(combination, sequence, callback, action);
  738. return;
  739. }
  740. info = _getKeyInfo(combination, action);
  741. // make sure to initialize array if this is the first time
  742. // a callback is added for this key
  743. self._callbacks[info.key] = self._callbacks[info.key] || [];
  744. // remove an existing match if there is one
  745. _getMatches(info.key, info.modifiers, {type: info.action}, sequenceName, combination, level);
  746. // add this call back to the array
  747. // if it is a sequence put it at the beginning
  748. // if not put it at the end
  749. //
  750. // this is important because the way these are processed expects
  751. // the sequence ones to come first
  752. self._callbacks[info.key][sequenceName ? 'unshift' : 'push']({
  753. callback: callback,
  754. modifiers: info.modifiers,
  755. action: info.action,
  756. seq: sequenceName,
  757. level: level,
  758. combo: combination
  759. });
  760. }
  761. /**
  762. * binds multiple combinations to the same callback
  763. *
  764. * @param {Array} combinations
  765. * @param {Function} callback
  766. * @param {string|undefined} action
  767. * @returns void
  768. */
  769. self._bindMultiple = function(combinations, callback, action) {
  770. for (var i = 0; i < combinations.length; ++i) {
  771. _bindSingle(combinations[i], callback, action);
  772. }
  773. };
  774. // start!
  775. _addEvent(targetElement, 'keypress', _handleKeyEvent);
  776. _addEvent(targetElement, 'keydown', _handleKeyEvent);
  777. _addEvent(targetElement, 'keyup', _handleKeyEvent);
  778. }
  779. /**
  780. * binds an event to mousetrap
  781. *
  782. * can be a single key, a combination of keys separated with +,
  783. * an array of keys, or a sequence of keys separated by spaces
  784. *
  785. * be sure to list the modifier keys first to make sure that the
  786. * correct key ends up getting bound (the last key in the pattern)
  787. *
  788. * @param {string|Array} keys
  789. * @param {Function} callback
  790. * @param {string=} action - 'keypress', 'keydown', or 'keyup'
  791. * @returns void
  792. */
  793. Mousetrap.prototype.bind = function(keys, callback, action) {
  794. var self = this;
  795. keys = keys instanceof Array ? keys : [keys];
  796. self._bindMultiple.call(self, keys, callback, action);
  797. return self;
  798. };
  799. /**
  800. * unbinds an event to mousetrap
  801. *
  802. * the unbinding sets the callback function of the specified key combo
  803. * to an empty function and deletes the corresponding key in the
  804. * _directMap dict.
  805. *
  806. * TODO: actually remove this from the _callbacks dictionary instead
  807. * of binding an empty function
  808. *
  809. * the keycombo+action has to be exactly the same as
  810. * it was defined in the bind method
  811. *
  812. * @param {string|Array} keys
  813. * @param {string} action
  814. * @returns void
  815. */
  816. Mousetrap.prototype.unbind = function(keys, action) {
  817. var self = this;
  818. return self.bind.call(self, keys, function() {}, action);
  819. };
  820. /**
  821. * triggers an event that has already been bound
  822. *
  823. * @param {string} keys
  824. * @param {string=} action
  825. * @returns void
  826. */
  827. Mousetrap.prototype.trigger = function(keys, action) {
  828. var self = this;
  829. if (self._directMap[keys + ':' + action]) {
  830. self._directMap[keys + ':' + action]({}, keys);
  831. }
  832. return self;
  833. };
  834. /**
  835. * resets the library back to its initial state. this is useful
  836. * if you want to clear out the current keyboard shortcuts and bind
  837. * new ones - for example if you switch to another page
  838. *
  839. * @returns void
  840. */
  841. Mousetrap.prototype.reset = function() {
  842. var self = this;
  843. self._callbacks = {};
  844. self._directMap = {};
  845. return self;
  846. };
  847. /**
  848. * should we stop this event before firing off callbacks
  849. *
  850. * @param {Event} e
  851. * @param {Element} element
  852. * @return {boolean}
  853. */
  854. Mousetrap.prototype.stopCallback = function(e, element) {
  855. var self = this;
  856. // if the element has the class "mousetrap" then no need to stop
  857. if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
  858. return false;
  859. }
  860. if (_belongsTo(element, self.target)) {
  861. return false;
  862. }
  863. // Events originating from a shadow DOM are re-targetted and `e.target` is the shadow host,
  864. // not the initial event target in the shadow tree. Note that not all events cross the
  865. // shadow boundary.
  866. // For shadow trees with `mode: 'open'`, the initial event target is the first element in
  867. // the event’s composed path. For shadow trees with `mode: 'closed'`, the initial event
  868. // target cannot be obtained.
  869. if ('composedPath' in e && typeof e.composedPath === 'function') {
  870. // For open shadow trees, update `element` so that the following check works.
  871. var initialEventTarget = e.composedPath()[0];
  872. if (initialEventTarget !== e.target) {
  873. element = initialEventTarget;
  874. }
  875. }
  876. // stop for input, select, and textarea
  877. return element.tagName == 'INPUT' || element.tagName == 'SELECT' || element.tagName == 'TEXTAREA' || element.isContentEditable;
  878. };
  879. /**
  880. * exposes _handleKey publicly so it can be overwritten by extensions
  881. */
  882. Mousetrap.prototype.handleKey = function() {
  883. var self = this;
  884. return self._handleKey.apply(self, arguments);
  885. };
  886. /**
  887. * allow custom key mappings
  888. */
  889. Mousetrap.addKeycodes = function(object) {
  890. for (var key in object) {
  891. if (object.hasOwnProperty(key)) {
  892. _MAP[key] = object[key];
  893. }
  894. }
  895. _REVERSE_MAP = null;
  896. };
  897. /**
  898. * Init the global mousetrap functions
  899. *
  900. * This method is needed to allow the global mousetrap functions to work
  901. * now that mousetrap is a constructor function.
  902. */
  903. Mousetrap.init = function() {
  904. var documentMousetrap = Mousetrap(document);
  905. for (var method in documentMousetrap) {
  906. if (method.charAt(0) !== '_') {
  907. Mousetrap[method] = (function(method) {
  908. return function() {
  909. return documentMousetrap[method].apply(documentMousetrap, arguments);
  910. };
  911. } (method));
  912. }
  913. }
  914. };
  915. Mousetrap.init();
  916. // expose mousetrap to the global object
  917. window.Mousetrap = Mousetrap;
  918. // expose as a common js module
  919. if (typeof module !== 'undefined' && module.exports) {
  920. module.exports = Mousetrap;
  921. }
  922. // expose mousetrap as an AMD module
  923. if (typeof define === 'function' && define.amd) {
  924. define(function() {
  925. return Mousetrap;
  926. });
  927. }
  928. }) (typeof window !== 'undefined' ? window : null, typeof window !== 'undefined' ? document : null);