keys.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. "use strict";
  5. module.metadata = {
  6. "stability": "unstable"
  7. };
  8. const { emit } = require("../events");
  9. const { getCodeForKey, toJSON } = require("../../keyboard/utils");
  10. const { has } = require("../../util/array");
  11. const { isString } = require("../../lang/type");
  12. const INITIALIZER = "initKeyEvent";
  13. const CATEGORY = "KeyboardEvent";
  14. function Options(options) {
  15. if (!isString(options))
  16. return options;
  17. var { key, modifiers } = toJSON(options);
  18. return {
  19. key: key,
  20. control: has(modifiers, "control"),
  21. alt: has(modifiers, "alt"),
  22. shift: has(modifiers, "shift"),
  23. meta: has(modifiers, "meta")
  24. };
  25. }
  26. var keyEvent = exports.keyEvent = function keyEvent(element, type, options) {
  27. emit(element, type, {
  28. initializer: INITIALIZER,
  29. category: CATEGORY,
  30. settings: [
  31. !("bubbles" in options) || options.bubbles !== false,
  32. !("cancelable" in options) || options.cancelable !== false,
  33. "window" in options && options.window ? options.window : null,
  34. "control" in options && !!options.control,
  35. "alt" in options && !!options.alt,
  36. "shift" in options && !!options.shift,
  37. "meta" in options && !!options.meta,
  38. getCodeForKey(options.key) || 0,
  39. options.key.length === 1 ? options.key.charCodeAt(0) : 0
  40. ]
  41. });
  42. }
  43. exports.keyDown = function keyDown(element, options) {
  44. keyEvent(element, "keydown", Options(options));
  45. };
  46. exports.keyUp = function keyUp(element, options) {
  47. keyEvent(element, "keyup", Options(options));
  48. };
  49. exports.keyPress = function keyPress(element, options) {
  50. keyEvent(element, "keypress", Options(options));
  51. };