@kaynooo/cli-pick 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/pick.js +101 -42
  2. package/package.json +2 -2
package/dist/pick.js CHANGED
@@ -2,11 +2,14 @@
2
2
  // @bun
3
3
 
4
4
  // src/pick.ts
5
- import process14 from "process";
5
+ import process15 from "process";
6
6
  // ../kit/src/args.ts
7
- import process8 from "process";
7
+ import process9 from "process";
8
8
  import { parseArgs } from "util";
9
9
 
10
+ // ../kit/src/format.ts
11
+ import process7 from "process";
12
+
10
13
  // ../kit/src/mode.ts
11
14
  import process2 from "process";
12
15
  var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
@@ -519,29 +522,35 @@ function upTo(text, separator) {
519
522
  return end === -1 ? text : text.slice(0, end);
520
523
  }
521
524
  var ESCAPE = String.fromCharCode(27);
525
+ function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
526
+ return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
527
+ }
528
+ function printJson(value) {
529
+ console.log(jsonText(value));
530
+ }
522
531
 
523
532
  // ../kit/src/help.ts
524
- import process7 from "process";
533
+ import process8 from "process";
525
534
  var OPTIONAL = /\[[^\]]+\]/g;
526
535
  var USAGE_PREFIX = /^usage:\s*/i;
527
536
  var FULL_STOP = /\.$/;
528
- function usageLine(usage, colors = paint(process7.stdout)) {
537
+ function usageLine(usage, colors = paint(process8.stdout)) {
529
538
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
530
539
  }
531
- function helpText(usage, options, colors = paint(process7.stdout), { examples = [], replaces, exits = [] } = {}) {
540
+ function helpText(usage, options, colors = paint(process8.stdout), { examples = [], replaces, exits = [] } = {}) {
532
541
  return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
533
542
  `);
534
543
  }
535
- function exitRows(exits, colors = paint(process7.stdout)) {
544
+ function exitRows(exits, colors = paint(process8.stdout)) {
536
545
  if (exits.length === 0)
537
546
  return [];
538
547
  const width = Math.max(...exits.map(([code]) => String(code).length));
539
548
  return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
540
549
  }
541
- function replacesRows(replaces, colors = paint(process7.stdout)) {
550
+ function replacesRows(replaces, colors = paint(process8.stdout)) {
542
551
  return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
543
552
  }
544
- function wantsHelpJson(env = process7.env) {
553
+ function wantsHelpJson(env = process8.env) {
545
554
  return env.KIT_HELP === "json";
546
555
  }
547
556
  function description(usage, { examples = [], replaces, exits } = {}, options) {
@@ -560,12 +569,12 @@ function description(usage, { examples = [], replaces, exits } = {}, options) {
560
569
  ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
561
570
  };
562
571
  }
563
- function exampleRows(examples, colors = paint(process7.stdout)) {
572
+ function exampleRows(examples, colors = paint(process8.stdout)) {
564
573
  if (examples.length === 0 || outputMode() === "agent")
565
574
  return [];
566
575
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
567
576
  }
568
- function optionRows(options, colors = paint(process7.stdout)) {
577
+ function optionRows(options, colors = paint(process8.stdout)) {
569
578
  const rows = Object.entries(options).map(([name, option]) => {
570
579
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
571
580
  const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
@@ -599,6 +608,9 @@ function closest(name, names) {
599
608
 
600
609
  // ../kit/src/args.ts
601
610
  var DASHES = /^-+/;
611
+ function jsonOption(holds) {
612
+ return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
613
+ }
602
614
  class Exit extends Error {
603
615
  code;
604
616
  hint;
@@ -642,7 +654,7 @@ var OUTPUT_OPTIONS = {
642
654
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
643
655
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
644
656
  };
645
- function applyOutput(color, plain, env = process8.env) {
657
+ function applyOutput(color, plain, env = process9.env) {
646
658
  const when = plain === true ? "never" : color ?? "auto";
647
659
  if (when === "auto")
648
660
  return;
@@ -819,13 +831,13 @@ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
819
831
  // ../kit/src/cli.ts
820
832
  import { readFileSync as readFileSync2, realpathSync } from "fs";
821
833
  import { dirname as dirname3, join as join5 } from "path";
822
- import process10 from "process";
834
+ import process11 from "process";
823
835
 
824
836
  // ../kit/src/usage.ts
825
837
  import { appendFileSync, mkdirSync } from "fs";
826
838
  import { homedir as homedir3 } from "os";
827
839
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
828
- import process9 from "process";
840
+ import process10 from "process";
829
841
 
830
842
  // ../kit/src/logs.ts
831
843
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -839,14 +851,14 @@ var usageError;
839
851
  function noteUsageError(message) {
840
852
  usageError = message;
841
853
  }
842
- function stateHome(env = process9.env) {
854
+ function stateHome(env = process10.env) {
843
855
  const dir = env.XDG_STATE_HOME;
844
856
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
845
857
  }
846
- function usagePath(env = process9.env) {
858
+ function usagePath(env = process10.env) {
847
859
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
848
860
  }
849
- function usageRecorded(env = process9.env) {
861
+ function usageRecorded(env = process10.env) {
850
862
  const off = env.KAYNOOO_CLI_NO_USAGE;
851
863
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
852
864
  }
@@ -860,7 +872,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
860
872
  usageError = undefined;
861
873
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
862
874
  }
863
- function recordUsage(entry, env = process9.env) {
875
+ function recordUsage(entry, env = process10.env) {
864
876
  if (!usageRecorded(env))
865
877
  return;
866
878
  try {
@@ -878,8 +890,8 @@ var LEVEL_OPTIONS = {
878
890
  };
879
891
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
880
892
  function printError(prefix, message, hint, cause) {
881
- const colors = paint(process10.stderr);
882
- const styled = takesControlCodes(process10.stderr);
893
+ const colors = paint(process11.stderr);
894
+ const styled = takesControlCodes(process11.stderr);
883
895
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
884
896
  const under = (label, text, tint) => text === undefined ? "" : `
885
897
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -972,7 +984,7 @@ function packageVersion(entry = Bun.main) {
972
984
  return "0.0.0";
973
985
  }
974
986
  }
975
- async function runMain({ name, version, run, redact, usage }, argv = process10.argv.slice(2)) {
987
+ async function runMain({ name, version, run, redact, usage }, argv = process11.argv.slice(2)) {
976
988
  if (argv[0] === COMPLETE)
977
989
  return printCandidates(leafCandidates(run, argv.slice(1)));
978
990
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
@@ -1099,6 +1111,14 @@ var KEYS = {
1099
1111
  "\x1B[B": "down",
1100
1112
  "\x1BOB": "down",
1101
1113
  "\x0E": "down",
1114
+ "\x1B[5~": "pageup",
1115
+ "\x1B[6~": "pagedown",
1116
+ "\x1B[H": "home",
1117
+ "\x1B[1~": "home",
1118
+ "\x1BOH": "home",
1119
+ "\x1B[F": "end",
1120
+ "\x1B[4~": "end",
1121
+ "\x1BOF": "end",
1102
1122
  "\r": "enter",
1103
1123
  "\n": "enter",
1104
1124
  "\x03": "cancel",
@@ -1176,7 +1196,7 @@ function parseKeys(input, paste = { active: false }, ctrls = []) {
1176
1196
  });
1177
1197
  }
1178
1198
  function createState(rows, { multi = false, prompt = "> ", query = "", header = "", expect = [], searched = Number.POSITIVE_INFINITY } = {}) {
1179
- const state = { rows: [], items: [], styles: [], searchable: [], searched, header, expect, key: "", status: "", query, matches: [], cursor: 0, marked: new Set, multi, prompt, done: undefined };
1199
+ const state = { rows: [], items: [], styles: [], searchable: [], searched, header, expect, key: "", status: "", query, matches: [], cursor: 0, page: 10, marked: new Set, multi, prompt, done: undefined };
1180
1200
  return withRows(state, rows);
1181
1201
  }
1182
1202
  function withRows(state, rows, header = state.header) {
@@ -1208,6 +1228,14 @@ function press(state, key) {
1208
1228
  return move(state, -1);
1209
1229
  case "down":
1210
1230
  return move(state, 1);
1231
+ case "pageup":
1232
+ return move(state, -state.page);
1233
+ case "pagedown":
1234
+ return move(state, state.page);
1235
+ case "home":
1236
+ return move(state, -state.matches.length);
1237
+ case "end":
1238
+ return move(state, state.matches.length);
1211
1239
  case "cancel":
1212
1240
  return { ...state, done: "cancel" };
1213
1241
  case "erase":
@@ -1238,11 +1266,11 @@ function chosen(state) {
1238
1266
 
1239
1267
  // ../kit/src/picker/terminal.ts
1240
1268
  import { openSync } from "fs";
1241
- import process13 from "process";
1269
+ import process14 from "process";
1242
1270
  import tty from "tty";
1243
1271
 
1244
1272
  // ../kit/src/picker/preview.ts
1245
- import process12 from "process";
1273
+ import process13 from "process";
1246
1274
 
1247
1275
  // ../kit/src/shell.ts
1248
1276
  var SEPARATORS = new Set([`
@@ -1311,7 +1339,7 @@ async function runPreview(template, line, signal, hidden = []) {
1311
1339
  ${previewCommand(template, line, hidden)}`], { stdin: "ignore", stdout: "pipe", stderr: "ignore", detached: true });
1312
1340
  const stop = () => {
1313
1341
  try {
1314
- process12.kill(-proc.pid, "SIGKILL");
1342
+ process13.kill(-proc.pid, "SIGKILL");
1315
1343
  } catch {
1316
1344
  proc.kill();
1317
1345
  }
@@ -1399,7 +1427,8 @@ function listLines(state, layout, theme) {
1399
1427
  const marks = (state.marked.size > 0 ? ` (${state.marked.size} marked)` : "") + (state.status === "" ? "" : ` ${state.status}`);
1400
1428
  const promptWidth = Bun.stringWidth(state.prompt);
1401
1429
  const query = fit(state.query, Math.max(1, layout.listWidth - promptWidth), identity);
1402
- const count = fit(` ${state.matches.length}/${state.items.length}${marks}`, layout.listWidth, theme.label);
1430
+ const place = state.matches.length > rows ? ` (${state.cursor + 1} of ${state.matches.length})` : "";
1431
+ const count = fit(` ${state.matches.length}/${state.items.length}${place}${marks}`, layout.listWidth, theme.label);
1403
1432
  const lines = [{ text: theme.accent(state.prompt) + query.text, width: promptWidth + query.width }, count, ...header];
1404
1433
  if (state.matches.length === 0)
1405
1434
  lines.push(fit(" no match", layout.listWidth, theme.label));
@@ -1426,6 +1455,7 @@ function render(state, layout, theme, preview = []) {
1426
1455
 
1427
1456
  // ../kit/src/picker/terminal.ts
1428
1457
  var PREVIEW_DELAY_MS = 120;
1458
+ var ESCAPE_WAIT_MS = 30;
1429
1459
  var OPEN = { ctrl: "open" };
1430
1460
  var HIDE_CURSOR = "\x1B[?25l";
1431
1461
  var SHOW_CURSOR = "\x1B[?25h";
@@ -1443,7 +1473,7 @@ function openTerminal() {
1443
1473
  } catch {
1444
1474
  return fail("no terminal to read keys from (/dev/tty)");
1445
1475
  }
1446
- const out = process13.stderr;
1476
+ const out = process14.stderr;
1447
1477
  let resize;
1448
1478
  return {
1449
1479
  get columns() {
@@ -1481,20 +1511,29 @@ async function select(rows, settings, terminal = openTerminal()) {
1481
1511
  let shownLine;
1482
1512
  let finish;
1483
1513
  let restored = false;
1514
+ let escape;
1515
+ let caret;
1484
1516
  function draw(clear = false) {
1485
1517
  if (restored)
1486
1518
  return;
1487
1519
  const layout = layoutFor({ columns: terminal.columns, rows: terminal.rows }, settings.height, settings.preview !== undefined, settings.previewPosition);
1488
1520
  let frame = HIDE_CURSOR;
1489
1521
  if (reserved !== layout.height || clear) {
1522
+ frame += clear && caret !== undefined ? up(Math.floor((caret - 1) / terminal.columns)) : "";
1490
1523
  frame += CLEAR_BELOW + `
1491
1524
  `.repeat(layout.height - 1) + up(layout.height - 1);
1492
1525
  reserved = layout.height;
1493
1526
  }
1527
+ caret = caretColumn(state, layout);
1494
1528
  frame += `\r${render(state, layout, theme, preview).map((line) => `\x1B[2K${line}`).join(`
1495
- `)}${up(layout.height - 1)}\r\x1B[${caretColumn(state, layout)}G${SHOW_CURSOR}`;
1529
+ `)}${up(layout.height - 1)}\r\x1B[${caret}G${SHOW_CURSOR}`;
1496
1530
  terminal.write(frame);
1497
1531
  }
1532
+ function pageSize() {
1533
+ const headerLines = state.header === "" ? 0 : state.header.split(`
1534
+ `).length;
1535
+ return Math.max(1, layoutFor({ columns: terminal.columns, rows: terminal.rows }, settings.height, settings.preview !== undefined, settings.previewPosition).listHeight - 2 - headerLines);
1536
+ }
1498
1537
  function refreshPreview() {
1499
1538
  const at = highlighted(state);
1500
1539
  if (settings.preview === undefined || at === shownLine)
@@ -1524,6 +1563,7 @@ async function select(rows, settings, terminal = openTerminal()) {
1524
1563
  return;
1525
1564
  restored = true;
1526
1565
  clearTimeout(previewTimer);
1566
+ clearTimeout(escape);
1527
1567
  previewing.abort();
1528
1568
  terminal.write(`${CLEAR_BELOW}${PASTE_OFF}${SHOW_CURSOR}`);
1529
1569
  terminal.close();
@@ -1562,7 +1602,7 @@ async function select(rows, settings, terminal = openTerminal()) {
1562
1602
  if (key === OPEN || typeof key === "object" && "ctrl" in key && key.ctrl === reload?.key)
1563
1603
  await reloadRows();
1564
1604
  else
1565
- state = press(state, key);
1605
+ state = press({ ...state, page: pageSize() }, key);
1566
1606
  }
1567
1607
  } finally {
1568
1608
  draining = false;
@@ -1575,6 +1615,20 @@ async function select(rows, settings, terminal = openTerminal()) {
1575
1615
  draw();
1576
1616
  }
1577
1617
  function onChunk(chunk) {
1618
+ if (escape !== undefined) {
1619
+ clearTimeout(escape);
1620
+ escape = undefined;
1621
+ chunk = `\x1B${chunk}`;
1622
+ } else if (chunk === "\x1B") {
1623
+ escape = setTimeout(() => {
1624
+ escape = undefined;
1625
+ takeKeys("\x1B");
1626
+ }, ESCAPE_WAIT_MS);
1627
+ return;
1628
+ }
1629
+ takeKeys(chunk);
1630
+ }
1631
+ function takeKeys(chunk) {
1578
1632
  const keys = parseKeys(chunk, paste, [...settings.expect ?? [], ...reload?.key === undefined ? [] : [reload.key]]);
1579
1633
  if (busy && keys.includes("cancel")) {
1580
1634
  stop();
@@ -1586,9 +1640,9 @@ async function select(rows, settings, terminal = openTerminal()) {
1586
1640
  const ended = new Promise((resolve) => {
1587
1641
  finish = resolve;
1588
1642
  });
1589
- process13.once("exit", restore);
1643
+ process14.once("exit", restore);
1590
1644
  for (const signal of SIGNALS)
1591
- process13.once(signal, stop);
1645
+ process14.once(signal, stop);
1592
1646
  try {
1593
1647
  terminal.write(PASTE_ON);
1594
1648
  terminal.listen(onChunk, () => draw(true));
@@ -1601,8 +1655,8 @@ async function select(rows, settings, terminal = openTerminal()) {
1601
1655
  await ended;
1602
1656
  } finally {
1603
1657
  for (const signal of SIGNALS)
1604
- process13.off(signal, stop);
1605
- process13.off("exit", restore);
1658
+ process14.off(signal, stop);
1659
+ process14.off("exit", restore);
1606
1660
  restore();
1607
1661
  }
1608
1662
  return state.done === "accept" ? { rows: chosen(state), key: state.key, query: state.query } : undefined;
@@ -1633,8 +1687,17 @@ var OPTIONS = {
1633
1687
  prompt: { type: "string", short: "p", description: "the prompt before the query (> )" },
1634
1688
  query: { type: "string", short: "q", description: "the query to start with" },
1635
1689
  preview: { type: "string", description: "a command shown for the highlighted line, {} standing for it" },
1636
- height: { type: "string", description: "lines or a percentage of the terminal to draw in (40%)" }
1690
+ height: { type: "string", description: "lines or a percentage of the terminal to draw in (40%)" },
1691
+ json: jsonOption("{picked: [lines]}, the choice or the marked lines in input order")
1637
1692
  };
1693
+ function print(chosen, json) {
1694
+ if (json)
1695
+ printJson({ picked: chosen });
1696
+ else
1697
+ process15.stdout.write(`${chosen.join(`
1698
+ `)}
1699
+ `);
1700
+ }
1638
1701
  async function main(args) {
1639
1702
  const { values, positionals } = parse(args, USAGE, OPTIONS, { replaces: "fzf for a quick choice in a pipe, select in a shell script", examples: ["git branch --format='%(refname:short)' | pick", "ls | pick --multi --preview 'head -20 {}'"] });
1640
1703
  if (positionals.length > 0)
@@ -1642,28 +1705,24 @@ async function main(args) {
1642
1705
  const height = values.height === undefined ? DEFAULT_HEIGHT : parseHeight(values.height);
1643
1706
  if (height === undefined)
1644
1707
  badUsage(`--height takes a number of lines or a percentage such as 40%, not ${values.height}`);
1645
- if (process14.stdin.isTTY)
1708
+ if (process15.stdin.isTTY)
1646
1709
  badUsage("pipe the lines to pick on stdin");
1647
1710
  const lines = (await Bun.stdin.text()).split(`
1648
1711
  `).filter((line) => line !== "");
1649
1712
  if (lines.length === 0)
1650
1713
  fail("nothing to pick from", 1);
1651
- if (!process14.stderr.isTTY) {
1714
+ if (!process15.stderr.isTTY) {
1652
1715
  const query = (values.query ?? "").toLowerCase();
1653
1716
  const matching = lines.filter((line) => line.toLowerCase().includes(query));
1654
1717
  if (matching.length === 0)
1655
1718
  return 1;
1656
- process14.stdout.write(`${(values.multi === true ? matching : matching.slice(0, 1)).join(`
1657
- `)}
1658
- `);
1719
+ print(values.multi === true ? matching : matching.slice(0, 1), values.json === true);
1659
1720
  return 0;
1660
1721
  }
1661
1722
  const picked = await choose(lines, { multi: values.multi === true, prompt: values.prompt ?? "> ", query: values.query ?? "", height, preview: values.preview });
1662
1723
  if (picked === undefined)
1663
1724
  return 1;
1664
- process14.stdout.write(`${picked.join(`
1665
- `)}
1666
- `);
1725
+ print(picked, values.json === true);
1667
1726
  return 0;
1668
1727
  }
1669
- process14.exitCode = await runMain({ name: "pick", run: main });
1728
+ process15.exitCode = await runMain({ name: "pick", run: main });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-pick",
3
3
  "type": "module",
4
- "version": "0.4.0",
4
+ "version": "0.5.0",
5
5
  "description": "pick: a themed fuzzy selector, lines on stdin, the chosen one on stdout.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
@@ -35,6 +35,6 @@
35
35
  "pick": "$npm_execpath src/pick.ts"
36
36
  },
37
37
  "devDependencies": {
38
- "@kaynooo/cli-kit": "0.23.0"
38
+ "@kaynooo/cli-kit": "0.25.0"
39
39
  }
40
40
  }