mousetrap.js 32 KB

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