@kaynooo/cli-view 0.3.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 (3) hide show
  1. package/README.md +1 -1
  2. package/dist/view.js +113 -28
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -8,7 +8,7 @@ bun add -g @kaynooo/cli-view
8
8
 
9
9
  | Command | What it does |
10
10
  | --- | --- |
11
- | `view README.md` | headings with their `#` marks, emphasis, lists with bullets by depth, numbers and task boxes, quotes and code blocks behind a bar, tables with wrapped cells, links as OSC 8 links |
11
+ | `view README.md` | headings with their `#` marks shaded by level, emphasis, lists with dashes and numbers that copy as plain text, task boxes, quotes behind a mark, code blocks between rules, tables with wrapped cells, links as OSC 8 links |
12
12
  | `view src/app.ts`, `view config.yaml` | source highlighted (comments, strings, numbers, keywords, keys) behind line numbers on a terminal; ts, js, json, yaml, toml, ini, py, sh, css, html, sql, rs, go, php, java, c, rb, lua, Dockerfile, Makefile |
13
13
  | `view --lang ts`, `--no-lines` | read stdin as that language; leave the line numbers off |
14
14
  | `git diff \| view` | file headers, hunk ranges, added and removed lines coloured; a `git log -p` or `git show` too |
package/dist/view.js CHANGED
@@ -326,19 +326,53 @@ function userConfigPath(bin, where = {}) {
326
326
  }
327
327
 
328
328
  // ../kit/src/theme.ts
329
+ function toLinear(channel) {
330
+ const value = channel / 255;
331
+ return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
332
+ }
333
+ var fromLinear = (value) => Math.round(255 * Math.min(1, Math.max(0, value <= 0.0031308 ? value * 12.92 : 1.055 * value ** (1 / 2.4) - 0.055)));
334
+ function toOklab(hex) {
335
+ const [r, g, b] = [1, 3, 5].map((at) => toLinear(Number.parseInt(hex.slice(at, at + 2), 16)));
336
+ const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
337
+ const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
338
+ const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
339
+ return [0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s, 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s, 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s];
340
+ }
341
+ function fromOklab([lightness, a, b]) {
342
+ const l = (lightness + 0.3963377774 * a + 0.2158037573 * b) ** 3;
343
+ const m = (lightness - 0.1055613458 * a - 0.0638541728 * b) ** 3;
344
+ const s = (lightness - 0.0894841775 * a - 1.291485548 * b) ** 3;
345
+ const channels = [4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s, -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s, -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s];
346
+ return `#${channels.map((channel) => fromLinear(channel).toString(16).padStart(2, "0")).join("")}`;
347
+ }
348
+ var ENDS = new Map;
349
+ function gradientAt(theme, ratio) {
350
+ if (theme.gradient === undefined)
351
+ return;
352
+ const key = theme.gradient.join();
353
+ let ends = ENDS.get(key);
354
+ if (ends === undefined) {
355
+ ends = [toOklab(theme.gradient[0]), toOklab(theme.gradient[1])];
356
+ ENDS.set(key, ends);
357
+ }
358
+ const at = Math.min(1, Math.max(0, ratio));
359
+ const [from, to] = ends;
360
+ return fromOklab(from.map((start, index) => start + (to[index] - start) * at));
361
+ }
329
362
  var DEFAULT = {
330
363
  colors: { accent: "cyan", id: "yellow", path: "blue", label: "dim", value: "bold", ok: "green", warn: "yellow", problem: "red", note: "dim", passed: "green", failed: "red", running: "cyan", queued: "yellow", skipped: "dim" },
331
- glyphs: { ok: "\u2713", warn: "\u25B2", problem: "\u2717", note: "\u203A", passed: "\u2713", failed: "\u2717", running: "\u25CF", queued: "\u25CB", skipped: "-", bar: "\u2501" },
364
+ glyphs: { ok: "\u2713", warn: "\u25B2", problem: "\u2717", note: "\u203A", passed: "\u2713", failed: "\u2717", running: "\u25CF", queued: "\u25CB", skipped: "-", bar: "\u2501", rule: "\u2500", corner: "\u256D", open: "\u2022", leaf: "\xB7", guide: "\u2502" },
332
365
  accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
333
- bins: {}
366
+ bins: {},
367
+ gradient: ["#c084fc", "#67e8f9"]
334
368
  };
335
369
  var BRIGHT = { accent: "cyanBright", id: "yellowBright", path: "blueBright", label: "white", value: "bold whiteBright", ok: "greenBright", warn: "yellowBright", problem: "redBright", note: "white", passed: "greenBright", failed: "redBright", running: "cyanBright", queued: "yellowBright", skipped: "white" };
336
370
  var MONO = { accent: "bold", id: "bold", path: "underline", label: "dim", value: "bold", ok: "bold", warn: "bold", problem: "bold", note: "dim", passed: "bold", failed: "bold", running: "bold", queued: "dim", skipped: "dim" };
337
- var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#" };
371
+ var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
338
372
  var PRESETS = {
339
373
  default: {},
340
- "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"] },
341
- mono: { colors: MONO, accents: ["bold"] },
374
+ "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
375
+ mono: { colors: MONO, accents: ["bold"], gradient: undefined },
342
376
  ascii: { glyphs: ASCII }
343
377
  };
344
378
  var STYLES = new Set(["bold", "dim", "italic", "underline", "inverse", "strikethrough", "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "gray", "grey", "blackBright", "redBright", "greenBright", "yellowBright", "blueBright", "magentaBright", "cyanBright", "whiteBright"]);
@@ -409,6 +443,8 @@ function applyPreset(theme, name, warn, where) {
409
443
  Object.assign(theme.glyphs, preset.glyphs);
410
444
  if (preset.accents !== undefined)
411
445
  theme.accents = [...preset.accents];
446
+ if (Object.hasOwn(preset, "gradient"))
447
+ theme.gradient = preset.gradient;
412
448
  return name;
413
449
  }
414
450
  function applyFile(theme, file, where, warn) {
@@ -436,6 +472,12 @@ function applyFile(theme, file, where, warn) {
436
472
  theme.accents = [...file.accents];
437
473
  else if (file.accents !== undefined)
438
474
  warn(`${where}: accents must be a non-empty list of colours`);
475
+ if (file.gradient === null)
476
+ theme.gradient = undefined;
477
+ else if (Array.isArray(file.gradient) && file.gradient.length === 2 && file.gradient.every((end) => typeof end === "string" && HEX.test(end)))
478
+ theme.gradient = [file.gradient[0], file.gradient[1]];
479
+ else if (file.gradient !== undefined)
480
+ warn(`${where}: gradient must be two \`#rrggbb\` colours, or null for none`);
439
481
  if (isRecord(file.bins)) {
440
482
  for (const [bin, value] of Object.entries(file.bins)) {
441
483
  if (isColorSpec(value))
@@ -459,7 +501,7 @@ function isPath(chosen) {
459
501
  return chosen.includes("/") || chosen.endsWith(".json");
460
502
  }
461
503
  function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(), warn = warnOnce } = {}) {
462
- const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null) };
504
+ const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null), gradient: DEFAULT.gradient };
463
505
  const sources = [];
464
506
  const chosen = env.KIT_THEME ?? "";
465
507
  const wanted = chosen === "" ? [userConfigPath("theme", { home, xdg: env.XDG_CONFIG_HOME }), findUp(join3(".kaynooo", "theme.json"), from, endsWalk(home))] : [];
@@ -1037,6 +1079,8 @@ async function runMain({ name, version, run, redact, usage }, argv = process12.a
1037
1079
  }
1038
1080
  return code;
1039
1081
  }
1082
+ // ../kit/src/folders.ts
1083
+ var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
1040
1084
  // ../kit/src/secrets.ts
1041
1085
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
1042
1086
  // ../kit/src/sessions.ts
@@ -1052,6 +1096,10 @@ var AFTER_KEY = /^\s*:/;
1052
1096
  var YAML_KEY = /^(\s*(?:- )?)([\w.\-/]+)(?=:(?:\s|$))/;
1053
1097
  var SETTING_KEY = /^(\s*)([\w.-]+)(?=\s*[=:])/;
1054
1098
  var SECTION = /^\s*\[.*\]\s*$/;
1099
+ var WHITESPACE = /\s/;
1100
+ var FLAG = /^--?[a-z][\w-]*/i;
1101
+ var COMMAND_END = /[|&;(]\s*$/;
1102
+ var PROMPT = /^\s*(?:[$>]\s*)?$/;
1055
1103
  var DIGIT = /\d/;
1056
1104
  var TRAILING_NEWLINE = /\n$/;
1057
1105
  var LEADING_DOT = /^\./;
@@ -1069,7 +1117,7 @@ var LANGUAGES = {
1069
1117
  json: { line: [], quotes: '"', keywords: words("true false null"), quotedKeys: true },
1070
1118
  jsonc: { ...SLASHES, quotes: '"', keywords: words("true false null"), quotedKeys: true },
1071
1119
  python: { ...HASH, quotes: `"'`, keywords: words("def class return if elif else for while in not and or is import from as with try except finally raise pass break continue lambda yield async await global nonlocal del assert None True False self") },
1072
- shell: { ...HASH, quotes: "\"'`", keywords: words("if then else elif fi for while until do done case esac in function return exit local export set unset source alias echo cd end switch begin and or not") },
1120
+ shell: { ...HASH, commands: true, quotes: "\"'`", keywords: words("if then else elif fi for while until do done case esac in function return exit local export set unset source alias echo cd end switch begin and or not") },
1073
1121
  yaml: { ...HASH, quotes: `"'`, keywords: words("true false null yes no"), key: YAML_KEY, quotedKeys: true },
1074
1122
  toml: { ...HASH, quotes: `"'`, keywords: words("true false"), key: SETTING_KEY, section: SECTION },
1075
1123
  ini: { line: ["#", ";"], quotes: `"'`, keywords: words("true false yes no on off"), key: SETTING_KEY, section: SECTION },
@@ -1194,9 +1242,19 @@ function highlight(source, name, theme) {
1194
1242
  const number = NUMBER.exec(text.slice(at))?.[0] ?? char;
1195
1243
  out += theme.number(number);
1196
1244
  at += number.length;
1245
+ } else if (language.commands === true && char === "-" && (at === 0 || WHITESPACE.test(text.charAt(at - 1))) && FLAG.test(text.slice(at))) {
1246
+ const flag = FLAG.exec(text.slice(at))?.[0] ?? char;
1247
+ out += theme.number(flag);
1248
+ at += flag.length;
1197
1249
  } else if (WORD_START.test(char)) {
1198
1250
  const word = WORD.exec(text.slice(at))?.[0] ?? char;
1199
- out += language.keywords.has(word) ? theme.keyword(word) : word;
1251
+ const before = text.slice(text.lastIndexOf(`
1252
+ `, at - 1) + 1, at);
1253
+ const command = language.commands === true && (PROMPT.test(before) || COMMAND_END.test(before));
1254
+ if (language.keywords.has(word))
1255
+ out += theme.keyword(word);
1256
+ else
1257
+ out += command && !word.startsWith("$") ? theme.accent(word) : word;
1200
1258
  at += word.length;
1201
1259
  } else {
1202
1260
  out += char;
@@ -1283,10 +1341,13 @@ var NESTED = "\x05";
1283
1341
  var CELL = "\x06";
1284
1342
  var ROW = "\x07";
1285
1343
  var BLOCK = "\b";
1286
- var BULLETS = ["\u2022", "\u25E6", "\u25AA"];
1287
1344
  var MAX_RULE = 60;
1345
+ var MAX_CODE_RULE = 12;
1346
+ var MIN_CODE_RULE = 8;
1347
+ var HEADING_SHADES = [0, 0.35, 0.7, 1];
1288
1348
  var MIN_ROOM = 20;
1289
1349
  var MIN_COLUMN = 8;
1350
+ var TYPICAL = 1.4;
1290
1351
  var COLUMN_GAP = 2;
1291
1352
  var TRAILING_BREAKS = /\n+$/;
1292
1353
  function block(text) {
@@ -1326,8 +1387,23 @@ function finish(block, width) {
1326
1387
  `);
1327
1388
  }
1328
1389
  function columnWidths(rows, width) {
1329
- const widths = rows[0]?.map((_, column) => Math.max(...rows.map((row) => textWidth(row[column] ?? "")))) ?? [];
1330
- const total = () => widths.reduce((sum, each) => sum + each, 0) + COLUMN_GAP * Math.max(0, widths.length - 1);
1390
+ const longest = rows[0]?.map((_, column) => Math.max(...rows.map((row) => textWidth(row[column] ?? "")))) ?? [];
1391
+ const gaps = COLUMN_GAP * Math.max(0, longest.length - 1);
1392
+ const sum = (list) => list.reduce((total, each) => total + each, 0);
1393
+ if (sum(longest) + gaps <= width)
1394
+ return longest;
1395
+ const typical = longest.map((most, column) => Math.min(most, Math.max(MIN_COLUMN, Math.ceil(TYPICAL * sum(rows.map((row) => textWidth(row[column] ?? ""))) / rows.length))));
1396
+ const widths = [...typical];
1397
+ const room = width - gaps - sum(typical);
1398
+ const wanting = longest.map((most, column) => most - typical[column]);
1399
+ if (room > 0 && sum(wanting) > 0) {
1400
+ for (const [column, want] of wanting.entries())
1401
+ widths[column] += Math.min(want, Math.floor(room * want / sum(wanting)));
1402
+ const left = width - gaps - sum(widths);
1403
+ const hungriest = wanting.indexOf(Math.max(...wanting));
1404
+ widths[hungriest] += Math.max(0, Math.min(left, longest[hungriest] - widths[hungriest]));
1405
+ }
1406
+ const total = () => sum(widths) + gaps;
1331
1407
  while (total() > width) {
1332
1408
  const widest = widths.indexOf(Math.max(...widths));
1333
1409
  if ((widths[widest] ?? 0) <= MIN_COLUMN)
@@ -1338,17 +1414,21 @@ function columnWidths(rows, width) {
1338
1414
  }
1339
1415
  function renderTable(rows, aligns, width, theme) {
1340
1416
  const widths = columnWidths(rows, width);
1341
- const lines = rows.flatMap((row, index) => {
1342
- const cells = widths.map((each, column) => Bun.wrapAnsi(row[column] ?? "", each, { hard: true }).split(`
1343
- `));
1417
+ const wrapped = rows.map((row) => widths.map((each, column) => Bun.wrapAnsi(row[column] ?? "", each, { hard: true }).split(`
1418
+ `)));
1419
+ const spaced = wrapped.some((cells) => cells.some((cell) => cell.length > 1));
1420
+ const lines = rows.flatMap((_, index) => {
1421
+ const cells = wrapped[index];
1344
1422
  const height = Math.max(...cells.map((cell) => cell.length));
1345
1423
  const drawn = Array.from({ length: height }, (_, at) => cells.map((cell, column) => {
1346
1424
  const text = cell[at] ?? "";
1347
1425
  const gap = " ".repeat(Math.max(0, (widths[column] ?? 0) - textWidth(text)));
1348
1426
  const aligned = aligns[column] === "right" ? `${gap}${text}` : `${text}${gap}`;
1349
- return index === 0 ? theme.bold(aligned) : aligned;
1427
+ return index === 0 ? theme.heading(aligned) : aligned;
1350
1428
  }).join(" ".repeat(COLUMN_GAP)).trimEnd());
1351
- return index === 0 ? [...drawn, theme.dim("\u2500".repeat(Math.min(width, widths.reduce((sum, each) => sum + each, 0) + COLUMN_GAP * Math.max(0, widths.length - 1))))] : drawn;
1429
+ if (index === 0)
1430
+ return [...drawn, theme.dim("\u2500".repeat(Math.min(width, widths.reduce((sum, each) => sum + each, 0) + COLUMN_GAP * Math.max(0, widths.length - 1))))];
1431
+ return spaced && index > 1 ? ["", ...drawn] : drawn;
1352
1432
  });
1353
1433
  return lines.join(`
1354
1434
  `);
@@ -1360,21 +1440,20 @@ function printable(source) {
1360
1440
  ` || char === "\t").join("");
1361
1441
  }
1362
1442
  function renderMarkdown(source, { theme, width }) {
1363
- const bar = theme.dim("\u2502 ");
1364
- const quote = theme.dim("\u258E ");
1443
+ const quote = [`${theme.shade("\u275D", 0)} `, " "];
1365
1444
  let aligns = [];
1366
1445
  const rendered = Bun.markdown.render(printable(source), {
1367
- heading: (children, { level }) => block(`${reflow(theme.heading(children), theme.dim(`${"#".repeat(level)} `), " ".repeat(level + 1))}
1446
+ heading: (children, { level }) => block(`${reflow(theme.shade(theme.bold(children), HEADING_SHADES[Math.min(level, HEADING_SHADES.length) - 1] ?? 1), theme.dim(`${"#".repeat(level)} `), " ".repeat(level + 1))}
1368
1447
 
1369
1448
  `),
1370
1449
  paragraph: (children) => block(`${reflow(children.replaceAll(`
1371
1450
  `, " "))}
1372
1451
 
1373
1452
  `),
1374
- strong: theme.bold,
1453
+ strong: (text) => theme.shade(theme.bold(text), 0),
1375
1454
  emphasis: theme.italic,
1376
1455
  strikethrough: theme.strike,
1377
- codespan: theme.code,
1456
+ codespan: (text) => `${theme.dim("`")}${theme.accent(text)}${theme.dim("`")}`,
1378
1457
  link: (children, { href }) => theme.link(children, href),
1379
1458
  image: (children, { src }) => theme.dim(`[image: ${children === "" ? src : children}]`),
1380
1459
  html: (children) => block(`${theme.dim(trimmed(children))}
@@ -1383,13 +1462,18 @@ function renderMarkdown(source, { theme, width }) {
1383
1462
  code: (children, meta) => {
1384
1463
  const language = languageOf(meta?.language ?? "");
1385
1464
  const body = trimmed(children);
1386
- return block(`${(language === undefined ? body : highlight(body, language, theme)).split(`
1387
- `).map((line) => `${bar}${line}`).join(`
1465
+ const lines = (language === undefined ? body : highlight(body, language, theme)).split(`
1466
+ `);
1467
+ const rule = Math.min(width, MAX_CODE_RULE, Math.max(MIN_CODE_RULE, ...lines.map((line) => textWidth(line))));
1468
+ const label = meta?.language === undefined || meta.language === "" ? "" : `${meta.language} `;
1469
+ return block(`${theme.dim(`${label}${"\u2500".repeat(Math.max(0, rule - textWidth(label)))}`)}
1470
+ ${lines.join(`
1388
1471
  `)}
1472
+ ${theme.dim("\u2500".repeat(rule))}
1389
1473
 
1390
1474
  `);
1391
1475
  },
1392
- blockquote: (children) => block(`${indent(trimmed(children.replaceAll(BLOCK, "")), quote, quote)}
1476
+ blockquote: (children) => block(`${indent(trimmed(children.replaceAll(BLOCK, "")), quote[0], quote[1])}
1393
1477
 
1394
1478
  `),
1395
1479
  hr: () => block(`${theme.dim("\u2500".repeat(Math.min(width, MAX_RULE)))}
@@ -1400,7 +1484,7 @@ function renderMarkdown(source, { theme, width }) {
1400
1484
  ` : block(`${trimmed(children)}
1401
1485
 
1402
1486
  `),
1403
- listItem: (children, { index, ordered, start, depth, checked }) => {
1487
+ listItem: (children, { index, ordered, start, checked }) => {
1404
1488
  const [head = "", ...nested] = children.split(NESTED);
1405
1489
  const blocksAt = head.indexOf(BLOCK);
1406
1490
  const inline = (blocksAt === -1 ? head : head.slice(0, blocksAt)).trim();
@@ -1408,11 +1492,11 @@ function renderMarkdown(source, { theme, width }) {
1408
1492
  const text = [inline === "" ? "" : reflow(inline.replaceAll(`
1409
1493
  `, " ")), blocks].filter((part) => part !== "").join(`
1410
1494
  `) || reflow("");
1411
- let marker = theme.accent(BULLETS[depth % BULLETS.length] ?? "\u2022");
1495
+ let marker = theme.dim("-");
1412
1496
  if (checked !== undefined)
1413
1497
  marker = checked ? theme.added("\u2713") : theme.dim("\u25CB");
1414
1498
  else if (ordered)
1415
- marker = theme.accent(`${(start ?? 1) + index}.`);
1499
+ marker = theme.dim(`${(start ?? 1) + index}.`);
1416
1500
  return `${indent([text, ...nested.map(trimmed)].join(`
1417
1501
  `), `${marker} `, " ".repeat(textWidth(marker) + 1))}
1418
1502
  `;
@@ -1457,7 +1541,8 @@ function themeFor(stream = process14.stdout, env = process14.env) {
1457
1541
  keyword: colors.magenta,
1458
1542
  string: colors.green,
1459
1543
  number: colors.yellow,
1460
- link: (text, url) => path(colors.underline(link(text, url, stream, env)))
1544
+ link: (text, url) => path(colors.underline(link(text, url, stream, env))),
1545
+ shade: (text, ratio) => takesControlCodes(stream, env) ? tinted(colors, gradientAt(activeTheme().theme, ratio) ?? activeTheme().theme.colors.accent, env)(text) : text
1461
1546
  };
1462
1547
  }
1463
1548
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-view",
3
3
  "type": "module",
4
- "version": "0.3.0",
4
+ "version": "0.5.0",
5
5
  "description": "view: markdown files and git diffs shown in the colours of the other @kaynooo CLIs, paged when long.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
@@ -35,6 +35,6 @@
35
35
  "view": "$npm_execpath src/view.ts"
36
36
  },
37
37
  "devDependencies": {
38
- "@kaynooo/cli-kit": "0.25.0"
38
+ "@kaynooo/cli-kit": "0.35.0"
39
39
  }
40
40
  }