Introduce

Toukey is a simple and efficient keyboard events library. That's toukey's doc site.

Installation

npm
yarn
pnpm
npm install toukey -S

Useage

Browser

You could download and link toukey.js in your HTML, It can also be downloaded via UNPKG | jsDelivr

<script src="https://unpkg.com/toukey/dist/toukey.umd.min.js"></script>
<script>
  toukey.subscribe('space', function() {
    console.log('space');
  });
</script>

React

It is easy to use with react.

import { useEffect } from "react";
import { subscribe } from "toukey";

function App() {
  useEffect(() => {
    return subscribe("scope", () => {
      console.log("scope");
    });
  });

  return <div>hello world</div>;
}

And here is a library named react-toukey-hook which build with toukey for react hook.

Basic Use

You will need Node.js installed on your system.

import { subscribe } from "toukey";

subscribe("scope", () => {
  console.log("scope");
});

Unsubscribe

The subscribe interface returns a function that can be called to cancel the current event listener.

import { subscribe } from "toukey";

const unsubscribe = subscribe("scope", () => {
  console.log("scope");
});

unsubscribe();

Multiple Key

Multiple event listeners can be created at once when using toukey.

import { subscribe } from "toukey";

subscribe("scope, a", () => {
  console.log("scope or a");
});

Compose Key

Through '+', you can monitor the key combination, and you can also customize the key combination separator.

import { subscribe } from "toukey";

subscribe("ctrl+a", () => {
  console.log("ctrl+a");
});

Scope

When calling, the third parameter can specify the scope of the event. "default" is the default scope.

import { subscribe, setScope } from "toukey";

const defaultHandler = () => {
  console.log("scope in default");
};

const subHandler = () => {
  console.log("scope in sub");
};

subscribe("scope", defaultHandler, "default");
subscribe("scope", subHandler, { scope: "sub" });

Special Scope *

If scope is specified as "*", the listener function will ignore the scope setting.

import { subscribe, setScope } from "toukey";

const handler = () => {
  console.log("scope in default");
};

const subHandler = () => {
  console.log("scope in sub");
};

subscribe("scope", defaultHandler, "*");
subscribe("scope", subHandler, "sub");
setScope("sub");