DEV Community

Codemaster_121482
Codemaster_121482

Posted on

How I made NanoScript handle key combinations?

How I Made NanoScript Handle Key Combinations

Hey devs! 👋 If you are building your own custom JavaScript framework or lightweight utility library, you eventually hit a wall: keyboard events.

Writing raw event listeners with nested, messy conditions like if (e.ctrlKey && e.shiftKey && e.key === 'I') gets too verbose over time. That's why I built NanoScript (NS), my lightweight alternative library. I wanted to create a simple, declarative way to handle complex shortcut combinations (like intercepting Ctrl + Shift + I).

You can check it out here: https://github.com/Hfs2024/NanoScript

The Goal: A Clean, Declarative API

I wanted developers to be able to set up a complex key combination and more (It's not just designed for complex key combinations) by just passing a simple configuration objects. No raw event boilerplate required. It looks like this:

NS.combination({
  keys: ["i", "I"],
  selector: "body",
  control: true,
  shift: true,
  action: () => {
    alert("My page is never inspectable via this key combination 😈. Try F12");
  }
});
Enter fullscreen mode Exit fullscreen mode

How Does It Work Under the Hood?

First, the library selects the target element from the DOM. Then, you can configure the parameters (control, shift, alt) using boolean values (true or false).

To check if the pressed key matches your array, it uses this validation logic:

let isMatchKey = false;

for (let key of keys) {
  if (e.key !== key) continue;
  isMatchKey = true;
  break; // Break the chain immediately once matched!
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • It loops through your array of valid keys.
  • It checks if the pressed key matches the current array item.
  • If it does not match, it continues to the next item.
  • If it matches, it sets isMatchKey to true and breaks the loop immediately.

Finally, it runs this final check to validate the modifier keys and trigger your callback:

if (
  isMatchKey && 
  (e.ctrlKey === control) && 
  (e.altKey === alt) && 
  (e.shiftKey === shift)
) {
  // Stop the browser default action
  e.preventDefault();

  // Run the custom action if the dev provided one
  if (typeof action === "function") action();
}
Enter fullscreen mode Exit fullscreen mode

If you like this project, please drop a star on GitHub and feel free to share your thoughts!

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.