Cliffy

Cliffy ❯ KeyCode

Version Build status issues Deno version doc Discord License
Discord nest.land badge

ANSI key code parser for Deno
>_ Used by cliffy's prompt module.

❯ Content§

❯ Install§

This module can be imported directly from the repo and from following registries.

Deno Registry

import {
  KeyCode,
  parse,
} from "https://deno.land/x/cliffy@<version>/keycode/mod.ts";

Nest Registry

import {
  KeyCode,
  parse,
} from "https://x.nest.land/cliffy@<version>/keycode/mod.ts";

Github

import {
  KeyCode,
  parse,
} from "https://raw.githubusercontent.com/c4spar/deno-cliffy/<version>/keycode/mod.ts";

❯ Usage§

import { parse } from "https://deno.land/x/cliffy/keycode/mod.ts";

console.log(
  parse(
    "\x1b[A\x1b[B\x1b[C\x1b[D\x1b[E\x1b[F\x1b[H",
  ),
);

Output:

[
  { name: "up", sequence: "\x1b[A", code: "[A", ctrl: false, meta: false, shift: false },
  { name: "down", sequence: "\x1b[B", code: "[B", ctrl: false, meta: false, shift: false },
  { name: "right", sequence: "\x1b[C", code: "[C", ctrl: false, meta: false, shift: false },
  { name: "left", sequence: "\x1b[D", code: "[D", ctrl: false, meta: false, shift: false },
  { name: "clear", sequence: "\x1b[E", code: "[E", ctrl: false, meta: false, shift: false },
  { name: "end", sequence: "\x1b[F", code: "[F", ctrl: false, meta: false, shift: false },
  { name: "home", sequence: "\x1b[H", code: "[H", ctrl: false, meta: false, shift: false }
]

❯ Example§

import { KeyCode, parse } from "https://deno.land/x/cliffy/keycode/mod.ts";

async function* keypress(): AsyncGenerator<KeyCode, void> {
  while (true) {
    const data = new Uint8Array(8);

    Deno.setRaw(Deno.stdin.rid, true);
    const nread = await Deno.stdin.read(data);
    Deno.setRaw(Deno.stdin.rid, false);

    if (nread === null) {
      return;
    }

    const keys: Array<KeyCode> = parse(data.subarray(0, nread));

    for (const key of keys) {
      yield key;
    }
  }
}

console.log("Hit ctrl + c to exit.");

for await (const key of keypress()) {
  if (key.ctrl && key.name === "c") {
    console.log("exit");
    break;
  }
  console.log(key);
}

--unstable is required for Deno.setRaw

$ deno run --unstable https://deno.land/x/cliffy/examples/keycode/read_key.ts

❯ API§

parse()§

  • parse( data: Uint8Array | string ): Array<KeyCode>

KeyCode§

  • name?: string
  • sequence?: string
  • code?: string
  • ctrl: boolean
  • meta: boolean
  • shift: boolean

❯ Contributing§

Any kind of contribution is welcome! Please take a look at the contributing guidelines.

❯ License§

MIT