tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

keypress.mjs (1497B)


      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 
      5 import { withSimpleController } from "./controllers.mjs";
      6 
      7 const useKeyEvent =
      8  keyEventName => (target, keyCombination, callback, options) => {
      9    const parts = keyCombination.split("+");
     10    const keys = parts.map(part => part.toLowerCase());
     11    const modifiers = ["ctrl", "alt", "shift", "meta"];
     12 
     13    const handleKeyEvent = event => {
     14      const isModifierCorrect = modifiers.every(
     15        modifier => keys.includes(modifier) === event[`${modifier}Key`]
     16      );
     17 
     18      const actualKey = keys.find(key => !modifiers.includes(key));
     19 
     20      // We check the code value rather than key since key value
     21      // can be missleading without prevent default e.g. option + N = ñ
     22      const isKeyCorrect =
     23        event.code.toLowerCase() === `key${actualKey}`.toLowerCase() ||
     24        event.code.toLowerCase() === actualKey.toLowerCase();
     25 
     26      if (isModifierCorrect && isKeyCorrect) {
     27        if (options?.preventDefault) {
     28          event.preventDefault();
     29        }
     30        callback?.(event);
     31      }
     32    };
     33 
     34    target.addEventListener(keyEventName, handleKeyEvent);
     35 
     36    return () => {
     37      target.removeEventListener(keyEventName, handleKeyEvent);
     38    };
     39  };
     40 
     41 export const handleKeyPress = (host, ...args) =>
     42  new (withSimpleController(host, useKeyEvent("keydown"), ...args))();