iterate.com / kernel

git clone https://git.iterate.com/repos/kernel

kernel / core / lib / src / cli / device-login / qr.tsmain at 949894f

// A QR code for a phone's camera, drawn in a terminal.
import { encode, renderUnicodeCompact } from "uqr";

/** The terminal that the code is drawn in: `process.stderr` is one. No `columns` or `rows` (a
 *  pipe, an agent's transcript) is no limit. */
export type TerminalScreen = { columns?: number; rows?: number };

/** `text` as a QR code (uqr, https://github.com/unjs/uqr, error correction L), indented two
 *  spaces: a character is one module wide and two modules high. Or null when `screen` is too small
 *  for it: a code whose lines wrap, or whose top has scrolled away, does not scan, so the caller
 *  prints the link alone. `under` is the lines that the caller prints under the code: they, and
 *  the line that the cursor then waits on, push the code up.
 *
 *  With `colors`, a character is a half block in black (30) on a background color, black (40) or
 *  bright white (107; 47 first, for a terminal without bright colors). So dark is dark and light
 *  is light in any theme, and the background fills each line to the next, whatever the line
 *  height. The quiet zone is two modules.
 *
 *  Without colors (a pipe, an agent's transcript): Unicode half blocks in the text color, with a
 *  four-module quiet zone. They scan in a dark terminal whose lines touch; space between lines
 *  cuts through them, so the link is the fallback. */
export function terminalQrCode(
  text: string,
  colors: boolean,
  screen: TerminalScreen = {},
  under: string[] = [],
) {
  const lines = colors
    ? colorLines(text)
    : renderUnicodeCompact(text, { ecc: "L", border: 4 }).split("\n");
  const width = 2 + encode(text, { ecc: "L", border: colors ? 2 : 4 }).size;
  const { columns = Infinity, rows = Infinity } = screen;
  // a line that is wider than the screen takes more than one of its rows
  const rowsUnder = under.reduce(
    (sum, line) => sum + Math.max(1, Math.ceil(line.length / columns)),
    1,
  );
  if (width > columns || lines.length + rowsUnder > rows) return null;
  return lines.map((line) => `  ${line}`).join("\n");
}

function colorLines(text: string) {
  const { data, size } = encode(text, { ecc: "L", border: 2 });
  const lines: string[] = [];
  for (let y = 0; y < size; y += 2) {
    let line = "";
    let style = "";
    for (let x = 0; x < size; x++) {
      const top = data[y]![x]!;
      // under the last line of an odd code is the quiet zone
      const bottom = y + 1 < size && data[y + 1]![x]!;
      // a cell of one color is its background alone, which fills the whole line height
      const next = top && bottom ? "40" : "30;47;107";
      if (next !== style) line += `\u001b[${(style = next)}m`;
      line += top === bottom ? " " : top ? "▀" : "▄";
    }
    // a reset at the end of every line, so a line that is cut never colors the next
    lines.push(`${line}\u001b[0m`);
  }
  return lines;
}