Toukey Documentation

website·Indexed 29 days ago

https://toukey.vercel.app/

A simple tool featuring a subscription API that allows users to unsubscribe from events.

Tokens
611
Snippets
6
Records
7
Agent score
25%

What's inside Toukey

  1. Manage event subscriptions with Turkey

    Turkey provides a subscription API that allows users to subscribe to events and returns a mechanism to unsubscribe from those events.
  2. Subscribe to keyboard events and unsubscribe

    Use the subscribe function to listen for a specific key. The subscribe function returns an unsubscribe function that can be called to remove the event listener.
    import { subscribe } from "toukey";
    
    // Subscribe to a key
    const unsubscribe = subscribe("scope", () => {
      console.log("scope");
    });
    
    // Cancel the listener
    unsubscribe();
  3. Listen for multiple keys or key combinations

    Toukey supports listening for multiple keys using a comma-separated string (OR logic) and key combinations using the + symbol.
    import { subscribe } from "toukey";
    
    // Trigger if either 'scope' or 'a' is pressed
    subscribe("scope, a", () => {
      console.log("scope or a");
    });
    
    // Trigger on key combination (e.g., Ctrl+A)
    subscribe("ctrl+a", () => {
      console.log("ctrl+a");
    });
  4. Manage event scopes in Toukey

    The third parameter of subscribe allows you to specify the scope of the event. The default scope is "default". You can pass a string or a configuration object { scope: "name" }.

    If the scope is set to "*", the listener will trigger regardless of the current active scope setting.

    import { subscribe, setScope } from "toukey";
    
    // Standard scope
    subscribe("scope", () => console.log("default"), "default");
    subscribe("scope", () => console.log("sub"), { scope: "sub" });
    
    // Global scope (ignores current scope setting)
    subscribe("scope", () => console.log("always triggers"), "*");
    
    // Change the active scope
    setScope("sub");
  5. Subscribe to keyboard events in the browser

    Toukey can be used in the browser by linking the UMD bundle from UNPKG or jsDelivr. The toukey.subscribe method is used to listen for specific key presses.
    <script src="https://unpkg.com/toukey/dist/toukey.umd.min.js"></script>
    <script>
      toukey.subscribe('space', function() {
        console.log('space');
      });
    </script>
  6. Use Toukey with React

    In React, use subscribe within a useEffect hook. Since subscribe returns an unsubscribe function, you can return it directly from the useEffect cleanup function to prevent memory leaks.
    import { useEffect } from "react";
    import { subscribe } from "toukey";
    
    function App() {
      useEffect(() => {
        return subscribe("scope", () => {
          console.log("scope");
        });
      }, []);
    
      return <div>hello world</div>;
    }