@barqjs/ui-cli 0.0.0-stage → 0.2.0-next.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.
package/src/theme.ts ADDED
@@ -0,0 +1,227 @@
1
+ /**
2
+ * The theme module `init` writes into a project.
3
+ *
4
+ * A `globalCss` block with the chosen colours in it, which the barq compiler
5
+ * folds into a stylesheet at build time — so an application that picks its
6
+ * theme once pays nothing at run time for the twenty-three it did not pick.
7
+ * `installTheme` from `@barqjs/ui` is the other half, for an application that
8
+ * switches theme while it is running.
9
+ *
10
+ * It is written as SOURCE rather than fetched, because the values come from the
11
+ * registry's own theme data and the file is the project's to edit afterwards.
12
+ */
13
+
14
+ import type { CssRules, CssVars, ThemeChoice } from "./schema.ts";
15
+
16
+ export interface ThemeTokens {
17
+ readonly [token: string]: string;
18
+ }
19
+
20
+ export interface ThemeDefinition {
21
+ readonly name: string;
22
+ readonly title: string;
23
+ readonly kind: "base" | "accent";
24
+ readonly light: ThemeTokens;
25
+ readonly dark: ThemeTokens;
26
+ }
27
+
28
+ /**
29
+ * A chosen radius REPLACES the base's own, rather than following it.
30
+ *
31
+ * Every base declares `radius` among its tokens, so appending wrote `--radius`
32
+ * twice. The cascade took the second one and the page was right, but the file
33
+ * is the project's to read and edit and said two different things.
34
+ */
35
+ function declarations(tokens: ThemeTokens, radius: string | undefined, indent: string): string {
36
+ const all = radius === undefined ? tokens : { ...tokens, radius };
37
+ return Object.entries(all)
38
+ .map(([token, value]) => `${indent}--${token}: ${value};`)
39
+ .join("\n");
40
+ }
41
+
42
+ /**
43
+ * Rules as CSS text, nested the way the object is.
44
+ *
45
+ * A string is a declaration's value and an object is a rule, so
46
+ * `{ "@keyframes spin": { to: { rotate: "360deg" } } }` is written as it reads.
47
+ */
48
+ function rules(css: CssRules, indent: string): string {
49
+ return Object.entries(css)
50
+ .map(([key, value]) =>
51
+ typeof value === "string"
52
+ ? `${indent}${key}: ${value};`
53
+ : `${indent}${key} {\n${rules(value, `${indent} `)}\n${indent}}`,
54
+ )
55
+ .join("\n");
56
+ }
57
+
58
+ /**
59
+ * What one more item's `cssVars` and `css` make of what the project has.
60
+ *
61
+ * Later wins, token by token and rule by rule, which is the cascade's own
62
+ * answer and the one a person adding a second item over a first expects.
63
+ */
64
+ export function withItemCss(
65
+ choice: ThemeChoice,
66
+ added: { readonly cssVars?: CssVars; readonly css?: CssRules },
67
+ ): ThemeChoice {
68
+ // Upstream writes a token with or without its dashes; the theme module adds
69
+ // them, so one spelling is kept.
70
+ const bare = (tokens: Readonly<Record<string, string>> | undefined): Record<string, string> =>
71
+ Object.fromEntries(
72
+ Object.entries(tokens ?? {}).map(([token, value]) => [token.replace(/^--/, ""), value]),
73
+ );
74
+ const vars = added.cssVars;
75
+ const merged: CssVars = {
76
+ theme: { ...choice.cssVars?.theme, ...bare(vars?.theme) },
77
+ light: { ...choice.cssVars?.light, ...bare(vars?.light) },
78
+ dark: { ...choice.cssVars?.dark, ...bare(vars?.dark) },
79
+ };
80
+ const some = (tokens: Readonly<Record<string, string>> | undefined): boolean =>
81
+ tokens !== undefined && Object.keys(tokens).length > 0;
82
+ const kept: CssVars = {
83
+ ...(some(merged.theme) ? { theme: merged.theme } : {}),
84
+ ...(some(merged.light) ? { light: merged.light } : {}),
85
+ ...(some(merged.dark) ? { dark: merged.dark } : {}),
86
+ };
87
+ const css = mergeRules(choice.css ?? {}, added.css ?? {});
88
+
89
+ return {
90
+ ...choice,
91
+ ...(Object.keys(kept).length > 0 ? { cssVars: kept } : {}),
92
+ ...(Object.keys(css).length > 0 ? { css } : {}),
93
+ };
94
+ }
95
+
96
+ function mergeRules(base: CssRules, over: CssRules): CssRules {
97
+ const out: Record<string, string | CssRules> = { ...base };
98
+ for (const [key, value] of Object.entries(over)) {
99
+ const had = out[key];
100
+ out[key] =
101
+ typeof value === "string" || typeof had !== "object" ? value : mergeRules(had, value);
102
+ }
103
+ return out;
104
+ }
105
+
106
+ export interface ThemeModuleOptions {
107
+ /** Whether the reset was written beside it. */
108
+ readonly reset: boolean;
109
+ /** How this file reaches `base.ts`, which is written beside it. */
110
+ readonly base: string;
111
+ /** How it reaches `reset.ts`. */
112
+ readonly resetPath: string;
113
+ }
114
+
115
+ export interface ResolvedTheme {
116
+ readonly base: ThemeDefinition;
117
+ readonly accent?: ThemeDefinition;
118
+ /** What to call the pair, for a message a person reads. */
119
+ readonly title: string;
120
+ }
121
+
122
+ /**
123
+ * A length, or a function that produces one.
124
+ *
125
+ * `--radius` is written into the project's own stylesheet, where a typo is a
126
+ * corner that silently stops being round. The units are CSS's absolute and
127
+ * relative lengths; the functions are the four that can stand where a length
128
+ * can, plus `var`, because a project layering this over tokens of its own is
129
+ * the case the plain token names exist for.
130
+ */
131
+ const LENGTH =
132
+ /^(?:0|[+-]?(?:\d+\.?\d*|\.\d+)(?:px|rem|em|ex|ch|vw|vh|vmin|vmax|cm|mm|in|pt|pc|q)|(?:calc|clamp|min|max|var)\(.*\))$/i;
133
+
134
+ function names(themes: readonly ThemeDefinition[], kind: ThemeDefinition["kind"]): string {
135
+ return themes
136
+ .filter((theme) => theme.kind === kind)
137
+ .map((theme) => theme.name)
138
+ .join(", ");
139
+ }
140
+
141
+ /**
142
+ * The chosen pair, looked up, or an error naming what does exist.
143
+ *
144
+ * Separate from `themeModule` so a caller can check a selection BEFORE it acts
145
+ * on it. `init` writes four files before it reaches the theme, and a mistyped
146
+ * `--theme` used to leave all four on disk with no `components.json` beside
147
+ * them — a project too far in to `add` to and too far in for `init` to be the
148
+ * first thing you run.
149
+ */
150
+ export function resolveTheme(
151
+ choice: ThemeChoice,
152
+ themes: readonly ThemeDefinition[],
153
+ ): ResolvedTheme {
154
+ const base = themes.find((theme) => theme.name === choice.base && theme.kind === "base");
155
+ if (base === undefined) {
156
+ throw new Error(`no base theme named "${choice.base}". Try one of: ${names(themes, "base")}`);
157
+ }
158
+
159
+ const accent =
160
+ choice.accent === undefined
161
+ ? undefined
162
+ : themes.find((theme) => theme.name === choice.accent && theme.kind === "accent");
163
+ if (choice.accent !== undefined && accent === undefined) {
164
+ throw new Error(
165
+ `no accent theme named "${choice.accent}". Try one of: ${names(themes, "accent")}`,
166
+ );
167
+ }
168
+
169
+ if (choice.radius !== undefined && !LENGTH.test(choice.radius)) {
170
+ throw new Error(`--radius wants a CSS length, like 0.5rem or 8px, not "${choice.radius}"`);
171
+ }
172
+
173
+ return {
174
+ base,
175
+ ...(accent === undefined ? {} : { accent }),
176
+ title: accent === undefined ? base.title : `${base.title} with ${accent.title}`,
177
+ };
178
+ }
179
+
180
+ export function themeModule(
181
+ choice: ThemeChoice,
182
+ themes: readonly ThemeDefinition[],
183
+ options: ThemeModuleOptions,
184
+ ): string {
185
+ const { base, accent, title } = resolveTheme(choice, themes);
186
+
187
+ const light = {
188
+ ...base.light,
189
+ ...accent?.light,
190
+ ...choice.cssVars?.theme,
191
+ ...choice.cssVars?.light,
192
+ };
193
+ const dark = { ...base.dark, ...accent?.dark, ...choice.cssVars?.dark };
194
+ const darkSelector = choice.dark ?? ".dark";
195
+ const extra =
196
+ choice.css === undefined ? "" : `\n@layer barq.theme {\n${rules(choice.css, " ")}\n}`;
197
+
198
+ const darkRule =
199
+ darkSelector === "media"
200
+ ? ` @media (prefers-color-scheme: dark) {\n :root {\n${declarations(dark, undefined, " ")}\n }\n }`
201
+ : ` ${darkSelector} {\n${declarations(dark, undefined, " ")}\n }`;
202
+
203
+ return `/**
204
+ * The colour theme: ${title}.
205
+ *
206
+ * Written by \`barq-ui init\`, and yours to edit. The barq compiler folds this
207
+ * block into a stylesheet at build time, so nothing here reaches the browser as
208
+ * JavaScript.
209
+ *
210
+ * To change theme, run \`barq-ui theme <name>\` — or edit the values, which is
211
+ * what they are here for.
212
+ */
213
+
214
+ import { globalCss } from "@barqjs/css";
215
+
216
+ import ${JSON.stringify(options.base)};
217
+ ${options.reset ? `import ${JSON.stringify(options.resetPath)};\n` : ""}
218
+ globalCss\`
219
+ @layer barq.theme {
220
+ :root {
221
+ ${declarations(light, choice.radius, " ")}
222
+ }
223
+ ${darkRule}
224
+ }${extra}
225
+ \`;
226
+ `;
227
+ }
package/src/tty.ts ADDED
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Writing to a terminal, and asking it a question.
3
+ *
4
+ * No colour library and no prompt library: six escape codes are the whole of
5
+ * what this needs, and `readline/promises` asks a question in three lines. A
6
+ * package a person downloads in order to write eight files should not download
7
+ * eight of its own first.
8
+ */
9
+
10
+ import { createInterface } from "node:readline/promises";
11
+ import { stdin, stdout } from "node:process";
12
+
13
+ const CSI = "\u001B[";
14
+
15
+ /** `NO_COLOR` is the convention every tool honours, and a pipe is not a terminal. */
16
+ const styled = stdout.isTTY && process.env["NO_COLOR"] === undefined;
17
+
18
+ type Style = (text: string) => string;
19
+
20
+ const code = (open: string): Style =>
21
+ styled ? (text) => `${CSI}${open}m${text}${CSI}0m` : (text) => text;
22
+
23
+ export const dim: Style = code("2");
24
+ export const bold: Style = code("1");
25
+ export const green: Style = code("32");
26
+ export const red: Style = code("31");
27
+ export const yellow: Style = code("33");
28
+ export const cyan: Style = code("36");
29
+
30
+ export function say(line = ""): void {
31
+ stdout.write(`${line}\n`);
32
+ }
33
+
34
+ /** A diff, coloured. The marker in column one is what carries it without colour. */
35
+ export function paint(diff: string): string {
36
+ return diff
37
+ .split("\n")
38
+ .map((line) =>
39
+ line.startsWith("+") ? green(line) : line.startsWith("-") ? red(line) : dim(line),
40
+ )
41
+ .join("\n");
42
+ }
43
+
44
+ /** One line of a `choose` list: what is stored, and what is shown. */
45
+ export interface Option {
46
+ readonly value: string;
47
+ readonly label: string;
48
+ }
49
+
50
+ export interface Ask {
51
+ question(text: string, fallback: string): Promise<string>;
52
+ confirm(text: string, fallback: boolean): Promise<boolean>;
53
+ choose(text: string, options: readonly Option[], fallback: string): Promise<string>;
54
+ close(): void;
55
+ }
56
+
57
+ /**
58
+ * What one answer to a `choose` list means, or `undefined` to ask again.
59
+ *
60
+ * Separate from the reading so it can be tested without a terminal: this is
61
+ * where a list prompt is actually wrong or right, and the half above it is
62
+ * three lines of `readline`.
63
+ *
64
+ * A number picks a line and a name picks itself, because a person reading
65
+ * `1 Neutral` reasonably types either. An empty answer is the default, which
66
+ * is what makes the whole prompt skippable.
67
+ */
68
+ export function pick(
69
+ answer: string,
70
+ options: readonly Option[],
71
+ fallback: string,
72
+ ): string | undefined {
73
+ const trimmed = answer.trim();
74
+ if (trimmed === "") return fallback;
75
+
76
+ // `Number("")` is 0 and `Number(" 2 ")` is 2, so the emptiness test above has
77
+ // to come first and the trim has to happen before this.
78
+ const index = Number(trimmed);
79
+ if (Number.isInteger(index) && index >= 1 && index <= options.length) {
80
+ return options[index - 1]?.value;
81
+ }
82
+
83
+ return options.find((option) => option.value === trimmed)?.value;
84
+ }
85
+
86
+ /**
87
+ * Piped into a script there is nowhere to prompt, so every question takes its
88
+ * default. That is what makes `--yes` unnecessary in CI rather than merely
89
+ * available.
90
+ *
91
+ * `allowed` is the CALLER's opinion — `--yes` says do not ask — and it is
92
+ * ANDed with whether there is a terminal to ask on. Trusting the caller alone
93
+ * hung: `sync` in a pipeline opened a readline on a stdin that would never
94
+ * answer.
95
+ */
96
+ export function ask(allowed = true): Ask {
97
+ const rl = allowed && stdin.isTTY ? createInterface({ input: stdin, output: stdout }) : null;
98
+
99
+ return {
100
+ async question(text, fallback) {
101
+ if (rl === null) return fallback;
102
+ const answer = (await rl.question(`${text} ${dim(`(${fallback})`)} `)).trim();
103
+ return answer === "" ? fallback : answer;
104
+ },
105
+ async confirm(text, fallback) {
106
+ if (rl === null) return fallback;
107
+ const answer = (await rl.question(`${text} ${dim(fallback ? "(Y/n)" : "(y/N)")} `))
108
+ .trim()
109
+ .toLowerCase();
110
+ if (answer === "") return fallback;
111
+ return answer.startsWith("y");
112
+ },
113
+ async choose(text, options, fallback) {
114
+ if (rl === null) return fallback;
115
+ const width = String(options.length).length;
116
+ say(text);
117
+ for (const [index, option] of options.entries()) {
118
+ const number = String(index + 1).padStart(width);
119
+ const mark = option.value === fallback ? cyan("›") : " ";
120
+ say(` ${mark} ${dim(number)} ${option.label}`);
121
+ }
122
+ for (;;) {
123
+ const answer = await rl.question(`Which? ${dim(`(${fallback})`)} `);
124
+ const chosen = pick(answer, options, fallback);
125
+ if (chosen !== undefined) return chosen;
126
+ say(red(` Not one of them. A number from 1 to ${String(options.length)}.`));
127
+ }
128
+ },
129
+ close() {
130
+ rl?.close();
131
+ },
132
+ };
133
+ }