ekurt 0.0.0-stage → 1.0.1

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.
@@ -0,0 +1,210 @@
1
+ /**
2
+ * Markdown → terminal lines, for blog posts, project pages and about-me.md.
3
+ * Covers what the site's content uses: headings, paragraphs, emphasis, inline code, links,
4
+ * lists (nested, ordered), fenced code, block quotes, tables and rules. Images are skipped:
5
+ * a terminal cannot show them, and `open` takes the reader to the page that can.
6
+ */
7
+ import { highlight } from "./highlight.js";
8
+ import { accent, bold, COLORS, hex, italic, link, muted, ok } from "./style.js";
9
+ import { pad, wrap, width } from "./text.js";
10
+ const compose = (outer, inner) => (outer ? (s) => outer(inner(s)) : inner);
11
+ const inlineCode = hex(COLORS.orange);
12
+ const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", "#39": "'", "#x27": "'", nbsp: " " };
13
+ const decode = (s) => s.replace(/&(#?\w+);/g, (m, name) => ENTITIES[name] ?? m);
14
+ const INLINE = /(`+)([\s\S]*?[^`])\1(?!`)|!\[([^\]]*)\]\(([^)]*)\)|\[([^\]]+)\]\(\s*<?([^)\s>]+)>?(?:\s+"[^"]*")?\s*\)|\*\*([\s\S]+?)\*\*|__([\s\S]+?)__|\*(?!\s)([^*]+?)\*|(?<![\w])_(?!\s)([^_]+?)_(?![\w])|<(https?:\/\/[^>\s]+)>|<\/?[a-zA-Z][^>]*>|\\([\\`*_{}[\]()#+\-.!>|])/g;
15
+ /** Inline markdown → styled pieces. */
16
+ export function inline(text, style) {
17
+ const pieces = [];
18
+ const plain = (s) => s && pieces.push({ text: decode(s), style });
19
+ let last = 0;
20
+ for (const m of text.matchAll(INLINE)) {
21
+ plain(text.slice(last, m.index));
22
+ last = m.index + m[0].length;
23
+ const [, , code, , , label, href, strong1, strong2, em1, em2, autolink, escaped] = m;
24
+ if (code !== undefined)
25
+ pieces.push({ text: code.trim(), style: compose(style, inlineCode) });
26
+ else if (label !== undefined) {
27
+ const linkStyle = (s) => link(accent.underline(s), href);
28
+ pieces.push(...inline(label, compose(style, linkStyle)));
29
+ }
30
+ else if (strong1 !== undefined || strong2 !== undefined)
31
+ pieces.push(...inline(strong1 ?? strong2, compose(style, bold)));
32
+ else if (em1 !== undefined || em2 !== undefined)
33
+ pieces.push(...inline(em1 ?? em2, compose(style, italic)));
34
+ else if (autolink !== undefined)
35
+ pieces.push({ text: autolink, style: (s) => link(accent.underline(s), autolink) });
36
+ else if (escaped !== undefined)
37
+ plain(escaped);
38
+ // Images and raw HTML tags are dropped.
39
+ }
40
+ plain(text.slice(last));
41
+ return pieces;
42
+ }
43
+ const FENCE = /^(\s*)(`{3,}|~{3,})\s*([\w+#-]*)/;
44
+ const HEADING = /^(#{1,6})\s+(.*?)\s*#*\s*$/;
45
+ const RULE = /^\s*([-*_])(\s*\1){2,}\s*$/;
46
+ const QUOTE = /^\s*>\s?/;
47
+ const ITEM = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/;
48
+ const IMAGE_LINE = /^\s*!\[[^\]]*\]\([^)]*\)\s*$/;
49
+ const TABLE_SEPARATOR = /^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$/;
50
+ const startsBlock = (line) => FENCE.test(line) || HEADING.test(line) || RULE.test(line) || QUOTE.test(line) || ITEM.test(line) || IMAGE_LINE.test(line);
51
+ const cells = (row) => row
52
+ .trim()
53
+ .replace(/^\|/, "")
54
+ .replace(/\|$/, "")
55
+ .split(/(?<!\\)\|/)
56
+ .map((c) => c.trim());
57
+ /** Joins paragraph lines, keeping hard breaks (two trailing spaces or a backslash). */
58
+ function joinLines(lines) {
59
+ const pieces = [];
60
+ lines.forEach((line, i) => {
61
+ const hard = /( {2,}|\\)$/.test(line) && i < lines.length - 1;
62
+ pieces.push(...inline(line.replace(/( {2,}|\\)$/, "").trim()));
63
+ pieces.push({ text: hard ? "\n" : " " });
64
+ });
65
+ return pieces;
66
+ }
67
+ function codeBlock(code, lang) {
68
+ const gutter = muted("│ ");
69
+ const label = lang ? muted(`╭─ ${lang}`) : muted("╭─");
70
+ const body = highlight(code.replace(/\n+$/, ""), lang).map((l) => `${gutter}${l}`);
71
+ return [label, ...body, muted("╰─")];
72
+ }
73
+ function table(rows, max) {
74
+ const styled = rows.map((row, r) => row.map((c) => inline(c, r === 0 ? bold : undefined)));
75
+ const text = styled.map((row) => row.map((pieces) => pieces.map((p) => (p.style ? p.style(p.text) : p.text)).join("")));
76
+ const cols = Math.max(...text.map((r) => r.length));
77
+ const widths = Array.from({ length: cols }, (_, c) => Math.max(...text.map((r) => width(r[c] ?? ""))));
78
+ const total = widths.reduce((a, b) => a + b, 0) + (cols - 1) * 3;
79
+ if (total > max) {
80
+ // Too wide for the terminal: one block per row, "header: value".
81
+ const [head, ...body] = text;
82
+ return body.flatMap((row, i) => [
83
+ ...(i ? [""] : []),
84
+ ...row.flatMap((cell, c) => wrap([{ text: `${head[c] ?? ""}: `, style: muted }, ...styled[i + 1][c]], max, " ")),
85
+ ]);
86
+ }
87
+ const line = (row) => row.map((c, i) => pad(c ?? "", widths[i])).join(muted(" │ ")).trimEnd();
88
+ return [line(text[0]), muted(widths.map((w) => "─".repeat(w)).join("─┼─")), ...text.slice(1).map(line)];
89
+ }
90
+ const BULLETS = ["•", "◦", "▪"];
91
+ /** Renders a markdown document to lines no wider than `max` columns (code is never wrapped). */
92
+ export function renderMarkdown(source, max) {
93
+ const lines = source.replace(/\r\n/g, "\n").replace(/\t/g, " ").split("\n");
94
+ const out = [];
95
+ const gap = () => {
96
+ if (out.length && out.at(-1) !== "")
97
+ out.push("");
98
+ };
99
+ let i = 0;
100
+ while (i < lines.length) {
101
+ const line = lines[i];
102
+ const fence = FENCE.exec(line);
103
+ if (fence) {
104
+ const close = new RegExp(`^\\s*${fence[2][0]}{${fence[2].length},}\\s*$`);
105
+ const code = [];
106
+ i++;
107
+ while (i < lines.length && !close.test(lines[i]))
108
+ code.push(lines[i++].slice(fence[1].length));
109
+ i++;
110
+ gap();
111
+ out.push(...codeBlock(code.join("\n"), fence[3]));
112
+ gap();
113
+ continue;
114
+ }
115
+ if (!line.trim() || IMAGE_LINE.test(line)) {
116
+ i++;
117
+ continue;
118
+ }
119
+ const heading = HEADING.exec(line);
120
+ if (heading) {
121
+ const level = heading[1].length;
122
+ const style = level <= 2 ? (s) => ok(bold(s)) : (s) => accent(bold(s));
123
+ gap();
124
+ out.push(...wrap(inline(heading[2], style), max, "", muted(`${heading[1]} `)));
125
+ out.push("");
126
+ i++;
127
+ continue;
128
+ }
129
+ if (RULE.test(line)) {
130
+ gap();
131
+ out.push(muted("─".repeat(Math.min(max, 48))));
132
+ gap();
133
+ i++;
134
+ continue;
135
+ }
136
+ if (QUOTE.test(line)) {
137
+ const quoted = [];
138
+ while (i < lines.length && QUOTE.test(lines[i]))
139
+ quoted.push(lines[i++].replace(QUOTE, ""));
140
+ gap();
141
+ const bar = muted("▌ ");
142
+ out.push(...renderMarkdown(quoted.join("\n"), max - 2).map((l) => (l ? bar + muted(l) : bar.trimEnd())));
143
+ gap();
144
+ continue;
145
+ }
146
+ if (line.trim().startsWith("|") && i + 1 < lines.length && TABLE_SEPARATOR.test(lines[i + 1])) {
147
+ const rows = [cells(line)];
148
+ i += 2;
149
+ while (i < lines.length && lines[i].trim().startsWith("|"))
150
+ rows.push(cells(lines[i++]));
151
+ gap();
152
+ out.push(...table(rows, max));
153
+ gap();
154
+ continue;
155
+ }
156
+ if (ITEM.test(line)) {
157
+ gap();
158
+ const indents = [];
159
+ while (i < lines.length) {
160
+ const item = ITEM.exec(lines[i]);
161
+ if (!item) {
162
+ // A blank line followed by another item keeps the list going.
163
+ if (!lines[i].trim() && i + 1 < lines.length && ITEM.test(lines[i + 1])) {
164
+ i++;
165
+ continue;
166
+ }
167
+ break;
168
+ }
169
+ const indent = item[1].length;
170
+ while (indents.length && indents.at(-1) > indent)
171
+ indents.pop();
172
+ if (!indents.length || indents.at(-1) < indent)
173
+ indents.push(indent);
174
+ const depth = Math.max(0, indents.length - 1);
175
+ const marker = /\d/.test(item[2]) ? muted(item[2].replace(")", ".")) : muted(BULLETS[depth % BULLETS.length]);
176
+ const lead = " ".repeat(depth);
177
+ const text = [item[3]];
178
+ i++;
179
+ // Continuation lines: indented, not a new item or block.
180
+ while (i < lines.length && lines[i].trim() && !ITEM.test(lines[i]) && !startsBlock(lines[i]) && /^\s+/.test(lines[i])) {
181
+ text.push(lines[i++].trim());
182
+ }
183
+ const first = `${lead}${marker} `;
184
+ out.push(...wrap(joinLines(text), max, " ".repeat(width(first)), first));
185
+ }
186
+ gap();
187
+ continue;
188
+ }
189
+ const paragraph = [];
190
+ while (i < lines.length && lines[i].trim() && !startsBlock(lines[i]) && !lines[i].trim().startsWith("|")) {
191
+ paragraph.push(lines[i++]);
192
+ }
193
+ if (!paragraph.length) {
194
+ // A line no other rule takes (e.g. a stray "|"): print it as text.
195
+ paragraph.push(lines[i++]);
196
+ }
197
+ // Raw HTML blocks (rare outside code) are dropped when nothing visible is left.
198
+ const pieces = joinLines(paragraph);
199
+ if (pieces.some((p) => p.text.trim())) {
200
+ gap();
201
+ out.push(...wrap(pieces, max));
202
+ gap();
203
+ }
204
+ }
205
+ while (out.at(-1) === "")
206
+ out.pop();
207
+ while (out[0] === "")
208
+ out.shift();
209
+ return out;
210
+ }
@@ -0,0 +1,156 @@
1
+ /** Full-page views: what `cat`, `cv` and the welcome print. */
2
+ import { about, BOOKMARK_CATEGORIES, bookmarks, CATEGORY_LABELS, cv, postsIn, profile, SERIES, } from "../content.js";
3
+ import { display, postPath, projectPath, urlFor } from "../shell/fs.js";
4
+ import { renderMarkdown } from "./markdown.js";
5
+ import { accent, bold, dir, hex, hint, italic, muted, ok, orange, shortUrl, url } from "./style.js";
6
+ import { pad, truncate, width, wrap, wrapText } from "./text.js";
7
+ const title = (s) => ok(bold(s));
8
+ const rule = (max) => muted("─".repeat(Math.min(max, 48)));
9
+ /** A document body without a closing rule of its own (the page adds one). */
10
+ function body(markdown, max) {
11
+ const lines = renderMarkdown(markdown, max);
12
+ while (lines.length && (lines.at(-1) === "" || lines.at(-1) === rule(max)))
13
+ lines.pop();
14
+ return lines;
15
+ }
16
+ /** `e_`, the site's mark, with the blinking underscore in green. */
17
+ export const mark = () => bold("e") + ok(bold("_"));
18
+ /** Key–value rows with the keys in one column. */
19
+ export function rows(entries, indent = " ", keyStyle = muted) {
20
+ const w = Math.max(...entries.map(([k]) => width(k))) + 2;
21
+ return entries.map(([k, v]) => `${indent}${keyStyle(pad(k, w))}${v}`);
22
+ }
23
+ export function contactRows(indent = " ") {
24
+ const p = profile();
25
+ return rows([
26
+ ["web", url(p.url)],
27
+ ["mail", url(`mailto:${p.email}`, p.email)],
28
+ ...p.socials.map((s) => [s.label.toLowerCase(), url(s.href)]),
29
+ ], indent);
30
+ }
31
+ /** What greets the visitor before the first prompt. */
32
+ export function welcome(max) {
33
+ const p = profile();
34
+ const indent = " ";
35
+ const links = [url(p.url), url(`mailto:${p.email}`, p.email), ...p.socials.map((s) => url(s.href))].join(muted(" · "));
36
+ return [
37
+ "",
38
+ ` ${mark()} ${bold(p.name)} ${muted("·")} ${p.role}`,
39
+ ...wrapText(p.tagline, max, indent, indent, muted),
40
+ ...wrap([{ text: links }], max + 200, indent),
41
+ "",
42
+ `${ok("ekurtsh")} — the ekurtOS shell. Last login: just now.`,
43
+ muted("Type ") + accent("help") + muted(" to begin, or try ") + [accent("ls"), accent("cv"), accent("neofetch"), accent("cat about-me.md")].join(muted(", ")) + muted("."),
44
+ ];
45
+ }
46
+ export function aboutPage(max) {
47
+ return [title("# About me"), "", ...renderMarkdown(about(), max), "", hint("cv", "the résumé, right here"), hint("contact", "write me a message")];
48
+ }
49
+ export function bookmarksPage(max) {
50
+ const all = bookmarks();
51
+ const w = Math.min(26, Math.max(...all.map((b) => width(b.title))) + 2);
52
+ const out = [];
53
+ for (const category of BOOKMARK_CATEGORIES) {
54
+ const items = all.filter((b) => b.category === category.id);
55
+ if (!items.length)
56
+ continue;
57
+ if (out.length)
58
+ out.push("");
59
+ out.push(title(`# ${category.label}`) + muted(` ${items.length}`));
60
+ for (const b of items)
61
+ out.push(`${pad(b.title, w)}${url(b.url, truncate(shortUrl(b.url), Math.max(12, max - w)))}`);
62
+ }
63
+ return [...out, "", muted(`${all.length} links · `) + hint("open bookmarks", "with descriptions, on ekurt.dev")];
64
+ }
65
+ export function projectPage(project, max) {
66
+ const path = projectPath(project);
67
+ const facts = [project.category ? CATEGORY_LABELS[project.category] : null, project.badge, project.date?.slice(0, 4)].filter(Boolean);
68
+ const meta = [];
69
+ if (project.url)
70
+ meta.push(["site", url(project.url)]);
71
+ if (project.repository)
72
+ meta.push(["source", url(`https://github.com/${project.repository}`)]);
73
+ meta.push(["page", url(urlFor(path))]);
74
+ return [
75
+ title(`# ${project.title}`),
76
+ ...wrapText(project.description, max, "", "", muted),
77
+ muted(facts.join(" · ")),
78
+ "",
79
+ ...rows(meta, ""),
80
+ rule(max),
81
+ "",
82
+ ...body(project.body, max),
83
+ "",
84
+ ...(project.url ? [hint(`visit ${project.slug}`, `open ${shortUrl(project.url)}`)] : []),
85
+ hint(`open ${display(path)}`, "with screenshots, on ekurt.dev"),
86
+ ...(project.support ? [hint("coffee", "free, no ads: a coffee keeps it that way")] : []),
87
+ ];
88
+ }
89
+ export function postPage(post, max) {
90
+ const series = SERIES[post.series];
91
+ const siblings = postsIn(post.series);
92
+ const index = siblings.findIndex((p) => p.slug === post.slug);
93
+ const prev = siblings[index - 1];
94
+ const next = siblings[index + 1];
95
+ const facts = [post.lesson, `${series.label}${post.series === "notes" ? "" : " series"}`, `${post.readingMinutes} min read`, post.date].filter(Boolean);
96
+ return [
97
+ title(`# ${post.shortTitle}`),
98
+ hex(series.color)("● ") + muted(facts.join(" · ")),
99
+ ...(post.description ? ["", ...wrapText(post.description, max, "", "", (s) => italic(muted(s)))] : []),
100
+ rule(max),
101
+ "",
102
+ ...body(post.body, max),
103
+ "",
104
+ rule(max),
105
+ ...(prev ? [muted("prev ") + accent(`cat ${display(postPath(prev))}`)] : []),
106
+ ...(next ? [muted("next ") + accent(`cat ${display(postPath(next))}`)] : []),
107
+ hint(`open ${display(postPath(post))}`, "read it on ekurt.dev"),
108
+ ];
109
+ }
110
+ export function cvPage(max) {
111
+ const p = profile();
112
+ const c = cv();
113
+ const section = (name) => ["", bold(muted("~/") + ok(name))];
114
+ const out = [
115
+ ` ${mark()} ${bold(p.name)}`,
116
+ ` ${p.role} ${muted("·")} ${bold(p.focus)}`,
117
+ "",
118
+ ...contactRows(),
119
+ ` ${muted(pad("based in", 10))}${c.basedIn}`,
120
+ "",
121
+ ...wrapText(c.summary, max),
122
+ ...section("skills"),
123
+ ];
124
+ out.push(...c.skills.flatMap((s) => wrapText(s.items.join(", "), max, " ".repeat(13), ` ${accent(pad(s.group, 11))}`)));
125
+ out.push(...section("experience"));
126
+ for (const job of c.experience) {
127
+ out.push("");
128
+ out.push(` ${bold(job.company)} ${muted("·")} ${job.role}${job.link ? " " + url(job.link) : ""}`);
129
+ out.push(` ${muted(`${job.when} · ${job.where}`)}`);
130
+ for (const point of job.points)
131
+ out.push(...wrapText(point, max, " ", ` ${muted("•")} `));
132
+ }
133
+ out.push(...section("projects"));
134
+ for (const project of c.projects) {
135
+ out.push("");
136
+ const tag = project.tag ? " " + orange(project.tag.toLowerCase()) : "";
137
+ out.push(` ${bold(project.title)}${tag} ${url(project.url)}`);
138
+ out.push(...wrapText(project.summary, max, " "));
139
+ out.push(` ${dir(project.stack)}`);
140
+ }
141
+ out.push(...section("education"));
142
+ for (const school of c.education) {
143
+ out.push("");
144
+ out.push(` ${bold(school.school)}${school.degree ? muted(" · ") + school.degree : ""}`);
145
+ out.push(` ${school.field} ${muted("· " + school.when)}`);
146
+ }
147
+ out.push(...section("languages"));
148
+ const lw = Math.max(...c.languages.map((l) => l.name.length)) + 2;
149
+ const levelW = Math.max(...c.languages.map((l) => l.level.length)) + 2;
150
+ for (const lang of c.languages) {
151
+ const dots = ok("●".repeat(lang.dots)) + muted("○".repeat(5 - lang.dots));
152
+ out.push(` ${pad(lang.name, lw)}${muted(pad(lang.level, levelW))}${dots}`);
153
+ }
154
+ out.push("", hint("open cv.pdf", "the one-page PDF"), hint("npx ekurt --export md", "save it as Markdown (or json)"));
155
+ return out;
156
+ }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Full-screen views (boot screen, games, kernel panic) on the terminal's alternate screen, so the
3
+ * shell's scrollback is untouched when they close. Keys arrive as readline keypress events.
4
+ */
5
+ import { emitKeypressEvents } from "node:readline";
6
+ import { width } from "./text.js";
7
+ const out = process.stdout;
8
+ export const enterScreen = () => out.write("\u001B[?1049h\u001B[?25l\u001B[2J");
9
+ export const leaveScreen = () => out.write("\u001B[2J\u001B[?25h\u001B[?1049l");
10
+ export function draw(lines, center = true, frameWidth) {
11
+ const cols = out.columns || 80;
12
+ const rows = out.rows || 24;
13
+ const w = frameWidth ?? Math.max(0, ...lines.map(width));
14
+ const left = center ? " ".repeat(Math.max(0, Math.floor((cols - w) / 2))) : "";
15
+ const top = center ? Math.max(0, Math.floor((rows - lines.length) / 2)) : 0;
16
+ const visible = lines.slice(0, rows - top);
17
+ let frame = "\u001B[H" + "\u001B[K\n".repeat(top);
18
+ frame += visible.map((l) => `${left}${l}\u001B[K`).join("\n");
19
+ out.write(frame + "\u001B[J");
20
+ }
21
+ /** Arrow keys, hjkl and wasd as directions. */
22
+ export function direction(key) {
23
+ switch (key.name) {
24
+ case "up":
25
+ case "k":
26
+ case "w":
27
+ return "up";
28
+ case "down":
29
+ case "j":
30
+ case "s":
31
+ return "down";
32
+ case "left":
33
+ case "h":
34
+ case "a":
35
+ return "left";
36
+ case "right":
37
+ case "l":
38
+ case "d":
39
+ return "right";
40
+ default:
41
+ return null;
42
+ }
43
+ }
44
+ export const isQuit = (key) => key.name === "q" || key.name === "escape" || (key.ctrl && key.name === "c");
45
+ /** Shows `view` until it returns "quit". Needs an interactive terminal. */
46
+ export function fullscreen(view) {
47
+ return new Promise((resolve) => {
48
+ const stdin = process.stdin;
49
+ emitKeypressEvents(stdin);
50
+ const wasRaw = stdin.isRaw;
51
+ stdin.setRawMode(true);
52
+ stdin.resume();
53
+ enterScreen();
54
+ const redraw = () => draw(view.render(), view.center !== false, view.frameWidth?.());
55
+ const onKey = (input, key) => {
56
+ const result = view.key(key ?? { sequence: input }, input ?? "");
57
+ if (result === "quit")
58
+ finish();
59
+ else
60
+ redraw();
61
+ };
62
+ const onResize = () => {
63
+ out.write("\u001B[2J");
64
+ redraw();
65
+ };
66
+ const timer = view.tick ? setInterval(redraw, view.tick) : null;
67
+ function finish() {
68
+ if (timer)
69
+ clearInterval(timer);
70
+ stdin.off("keypress", onKey);
71
+ out.off("resize", onResize);
72
+ leaveScreen();
73
+ stdin.setRawMode(wasRaw);
74
+ stdin.pause();
75
+ resolve();
76
+ }
77
+ view.attach?.(redraw);
78
+ stdin.on("keypress", onKey);
79
+ out.on("resize", onResize);
80
+ redraw();
81
+ });
82
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * The palette of the ekurt.dev Terminal app (GitHub dark), so both shells look alike.
3
+ * Plain text keeps the terminal's own colour; only tones are coloured.
4
+ */
5
+ import chalk from "chalk";
6
+ export const COLORS = {
7
+ text: "#e6edf3",
8
+ muted: "#8b93a3",
9
+ error: "#ff7b72",
10
+ accent: "#79c0ff",
11
+ dir: "#d2a8ff",
12
+ ok: "#7ee787",
13
+ string: "#a5d6ff",
14
+ orange: "#ffa657",
15
+ comment: "#8b949e",
16
+ surface: "#21262d",
17
+ surfaceHi: "#30363d",
18
+ focus: "#388bfd",
19
+ };
20
+ export const muted = chalk.hex(COLORS.muted);
21
+ export const error = chalk.hex(COLORS.error);
22
+ export const accent = chalk.hex(COLORS.accent);
23
+ export const dir = chalk.hex(COLORS.dir);
24
+ export const ok = chalk.hex(COLORS.ok);
25
+ export const orange = chalk.hex(COLORS.orange);
26
+ export const bold = chalk.bold;
27
+ export const italic = chalk.italic;
28
+ export const hex = (color) => chalk.hex(color);
29
+ export const bg = (color) => chalk.bgHex(color);
30
+ export const colorLevel = () => chalk.level;
31
+ let hyperlinkSupport;
32
+ /** OSC 8 links: terminals that understand them make the text clickable; others would print junk. */
33
+ export function supportsHyperlinks() {
34
+ if (hyperlinkSupport !== undefined)
35
+ return hyperlinkSupport;
36
+ const env = process.env;
37
+ const decide = () => {
38
+ if (env.FORCE_HYPERLINK)
39
+ return env.FORCE_HYPERLINK !== "0";
40
+ if (!process.stdout.isTTY || chalk.level === 0 || env.CI)
41
+ return false;
42
+ if (env.WT_SESSION || env.KONSOLE_VERSION || env.DOMTERM)
43
+ return true;
44
+ if (["iTerm.app", "vscode", "WezTerm", "ghostty", "Hyper", "Tabby", "rio"].includes(env.TERM_PROGRAM ?? ""))
45
+ return true;
46
+ if (env.TERM === "xterm-kitty" || env.TERM === "alacritty" || env.TERM?.startsWith("foot"))
47
+ return true;
48
+ if (env.VTE_VERSION)
49
+ return Number(env.VTE_VERSION) >= 5000;
50
+ return false;
51
+ };
52
+ hyperlinkSupport = decide();
53
+ return hyperlinkSupport;
54
+ }
55
+ export const link = (text, url) => supportsHyperlinks() ? `\u001B]8;;${url}\u0007${text}\u001B]8;;\u0007` : text;
56
+ /** "ruta.tr" for https://ruta.tr, clickable where the terminal allows. */
57
+ export const shortUrl = (url) => url.replace(/^https?:\/\/(www\.)?/, "").replace(/\/$/, "").replace(/\?.*$/, "");
58
+ export const url = (href, text = shortUrl(href)) => link(accent.underline(text), href);
59
+ /** "→ cat about-me.md": a command the reader can type next, styled like the site's clickable lines. */
60
+ export const hint = (command, note) => accent(`→ ${command}`) + (note ? muted(` ${note}`) : "");
@@ -0,0 +1,139 @@
1
+ /** Measuring, padding and word-wrapping text that carries ANSI styles. */
2
+ import { stripVTControlCharacters } from "node:util";
3
+ export const strip = (s) => stripVTControlCharacters(s);
4
+ function charWidth(code) {
5
+ if (code < 0x20 || (code >= 0x7f && code < 0xa0))
6
+ return 0;
7
+ if ((code >= 0x300 && code <= 0x36f) || (code >= 0x200b && code <= 0x200f) || code === 0xfe0f)
8
+ return 0;
9
+ if ((code >= 0x1100 && code <= 0x115f) ||
10
+ (code >= 0x2e80 && code <= 0xa4cf) ||
11
+ (code >= 0xac00 && code <= 0xd7a3) ||
12
+ (code >= 0xf900 && code <= 0xfaff) ||
13
+ (code >= 0xfe30 && code <= 0xfe4f) ||
14
+ (code >= 0xff00 && code <= 0xff60) ||
15
+ (code >= 0xffe0 && code <= 0xffe6) ||
16
+ (code >= 0x1f300 && code <= 0x1faff) ||
17
+ (code >= 0x20000 && code <= 0x3fffd)) {
18
+ return 2;
19
+ }
20
+ return 1;
21
+ }
22
+ const EMOJI = /\p{Emoji_Presentation}/u;
23
+ /** Columns a string takes on screen. */
24
+ export function width(s) {
25
+ let w = 0;
26
+ for (const ch of strip(s))
27
+ w += EMOJI.test(ch) ? 2 : charWidth(ch.codePointAt(0));
28
+ return w;
29
+ }
30
+ export const pad = (s, w) => s + " ".repeat(Math.max(0, w - width(s)));
31
+ export const padStart = (s, w) => " ".repeat(Math.max(0, w - width(s))) + s;
32
+ /** Terminal width, with a comfortable reading measure on top. */
33
+ export const columns = () => process.stdout.columns || 80;
34
+ export const measure = (max = 88) => Math.max(40, Math.min(columns() - 1, max));
35
+ /** Plain text cut to `max` columns with an ellipsis. */
36
+ export function truncate(s, max) {
37
+ if (width(s) <= max)
38
+ return s;
39
+ let out = "";
40
+ for (const ch of s) {
41
+ if (width(out + ch) > max - 1)
42
+ break;
43
+ out += ch;
44
+ }
45
+ return out + "…";
46
+ }
47
+ /** Splits pieces into words; a word can span pieces (e.g. a bold word followed by a comma). */
48
+ function words(pieces) {
49
+ const out = [];
50
+ let current = [];
51
+ const flush = () => {
52
+ if (current.length)
53
+ out.push(current);
54
+ current = [];
55
+ };
56
+ for (const piece of pieces) {
57
+ if (piece.text === "\n") {
58
+ flush();
59
+ out.push("\n");
60
+ continue;
61
+ }
62
+ for (const part of piece.text.split(/(\s+)/)) {
63
+ if (!part)
64
+ continue;
65
+ if (/^\s+$/.test(part))
66
+ flush();
67
+ else
68
+ current.push({ text: part, style: piece.style });
69
+ }
70
+ }
71
+ flush();
72
+ return out;
73
+ }
74
+ const plainWidth = (word) => word.reduce((n, p) => n + width(p.text), 0);
75
+ const paint = (word) => word.map((p) => (p.style ? p.style(p.text) : p.text)).join("");
76
+ /** Breaks a word that is wider than a whole line into line-sized parts. */
77
+ function split(word, room) {
78
+ const parts = [[]];
79
+ let used = 0;
80
+ for (const piece of word) {
81
+ for (const ch of piece.text) {
82
+ const w = width(ch);
83
+ if (used + w > room && used > 0) {
84
+ parts.push([]);
85
+ used = 0;
86
+ }
87
+ const last = parts.at(-1);
88
+ const prev = last.at(-1);
89
+ if (prev && prev.style === piece.style)
90
+ prev.text += ch;
91
+ else
92
+ last.push({ text: ch, style: piece.style });
93
+ used += w;
94
+ }
95
+ }
96
+ return parts;
97
+ }
98
+ /** Greedy word wrap. `first` prefixes the first line, `rest` every later one (e.g. list bullets). */
99
+ export function wrap(pieces, max, rest = "", first = rest) {
100
+ const lines = [];
101
+ let line = first;
102
+ let used = width(first);
103
+ let empty = true;
104
+ const room = () => max - width(rest);
105
+ const newline = () => {
106
+ lines.push(line.trimEnd());
107
+ line = rest;
108
+ used = width(rest);
109
+ empty = true;
110
+ };
111
+ for (const item of words(pieces)) {
112
+ if (item === "\n") {
113
+ newline();
114
+ continue;
115
+ }
116
+ const w = plainWidth(item);
117
+ const needed = empty ? w : w + 1;
118
+ if (used + needed > max && !empty)
119
+ newline();
120
+ if (w > room()) {
121
+ for (const part of split(item, room())) {
122
+ if (!empty)
123
+ newline();
124
+ line += paint(part);
125
+ used += plainWidth(part);
126
+ empty = false;
127
+ }
128
+ continue;
129
+ }
130
+ line += (empty ? "" : " ") + paint(item);
131
+ used += empty ? w : w + 1;
132
+ empty = false;
133
+ }
134
+ if (!empty || line.trim())
135
+ lines.push(line.trimEnd());
136
+ return lines;
137
+ }
138
+ /** Wraps one plain or pre-styled string (styles inside words survive; words never break mid-style). */
139
+ export const wrapText = (text, max, rest = "", first = rest, style) => wrap([{ text, style }], max, rest, first);