@mccaskie-labs/workbench-ui 0.3.2 → 0.4.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,20 @@
1
1
  # @mccaskie-labs/workbench-ui
2
2
 
3
+ ## 0.4.1
4
+
5
+ ### Patch Changes
6
+
7
+ - `npx workbench-ui styles` finds every `@mccaskie-labs/workbench-*` package the project depends on whose package.json exports `./styles`, so a new tool's classes join workbench.css without a workbench-ui release (workbench-pdf 0.2.0 and workbench-email 0.3.0 are the next). `STYLED_PACKAGES` is replaced by `STYLED_SCOPE`.
8
+
9
+ ## 0.4.0
10
+
11
+ ### Minor Changes
12
+
13
+ - `npx workbench-ui styles [--check] [dir]` writes a project's `public/styles/workbench.css`: the page look in `@layer workbench.page`, then every installed tool's classes and `--wb-*` variables in `@layer workbench.tools`, each with a comment saying what it is. It also writes `public/styles/project.css` when the project has none; that file is the project's own and is never overwritten. It loads after workbench.css and isn't in a layer, so its rules always win. `--check` fails when workbench.css is out of date with the installed packages, or when project.css names a `wb-` class or variable no tool draws any more (docs/capabilities-manifest.md §10).
14
+ - `shell({ stylesheets })` links stylesheets (such as `STYLESHEETS`: `/styles/workbench.css` then `/styles/project.css`) instead of the inline look.
15
+ - `renderStyles`, `starterProjectCss`, `styleProblems`, `styleNames`, `unknownNames`, `STYLE_FILES`, `STYLED_PACKAGES` and the `ToolStyles` types.
16
+ - Breaking: the form rules leave `CSS` and `STYLE` (they are workbench-forms 0.6.0's `FORM_STYLES` now), and FORM_SCRIPT adds the `wb-form-*` names: `wb-form-error`, `wb-form-live`, `wb-form-summary` with `wb-form-summary-title`, `-list`, `-item` and `-link`, and `wb-form-counter` with `wb-form-counter-over` (was `over`). A page that puts forms on Workbench's inline look adds `renderStyles` output, or uses the generated stylesheet.
17
+
3
18
  ## 0.3.2
4
19
 
5
20
  ### Patch Changes
package/dist/cli.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env node
2
+ import { type InstalledStyles } from "./styles.ts";
3
+ /** The styles of each Workbench tool the project at `dir` has installed, and the workbench-ui version. */
4
+ export declare function installedStyles(dir: string): Promise<{
5
+ tools: InstalledStyles[];
6
+ uiVersion: string;
7
+ }>;
8
+ export interface StylesPlan {
9
+ /** Files to write, by path relative to the project. */
10
+ files: Record<string, string>;
11
+ /** Why --check fails. */
12
+ problems: string[];
13
+ }
14
+ /** What `styles` writes in `dir`, and what --check would fail on, without touching the disk. */
15
+ export declare function planStyles(dir: string, tools: readonly InstalledStyles[], uiVersion: string): StylesPlan;
package/dist/cli.js ADDED
@@ -0,0 +1,121 @@
1
+ #!/usr/bin/env node
2
+ // `npx workbench-ui styles [--check] [dir]`: writes <dir>/public/styles/workbench.css
3
+ // from the styles of every Workbench tool installed in the project
4
+ // (docs/capabilities-manifest.md §10), and public/styles/project.css if the
5
+ // project has none yet (it is the project's own, so never overwritten). With
6
+ // --check it writes nothing and fails when workbench.css differs from what the
7
+ // installed packages draw, or when project.css names a wb- class or variable
8
+ // that no installed tool draws any more (a rename after an update).
9
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
10
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
11
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
12
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
13
+ });
14
+ }
15
+ return path;
16
+ };
17
+ import { existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
18
+ import { createRequire } from "node:module";
19
+ import { dirname, join, resolve } from "node:path";
20
+ import { fileURLToPath, pathToFileURL } from "node:url";
21
+ import { renderStyles, STYLE_FILES, STYLED_SCOPE, starterProjectCss, unknownNames } from "./styles.js";
22
+ const USAGE = "usage: workbench-ui styles [--check] [dir]";
23
+ const read = (path) => readFileSync(path, "utf8").replace(/\r\n/g, "\n");
24
+ /** The styles of each Workbench tool the project at `dir` has installed, and the workbench-ui version. */
25
+ export async function installedStyles(dir) {
26
+ const req = createRequire(join(dir, "package.json"));
27
+ const version = (pkg) => {
28
+ try {
29
+ return JSON.parse(read(req.resolve(`${pkg}/package.json`))).version;
30
+ }
31
+ catch {
32
+ return null;
33
+ }
34
+ };
35
+ // Every Workbench package the project depends on whose package.json exports "./styles".
36
+ const project = JSON.parse(read(join(dir, "package.json")));
37
+ const names = [...new Set([...Object.keys(project.dependencies ?? {}), ...Object.keys(project.devDependencies ?? {})])].filter((n) => n.startsWith(STYLED_SCOPE)).sort();
38
+ const tools = [];
39
+ for (const name of names) {
40
+ // Found by folder, not through its exports, which needn't list ./package.json.
41
+ const at = (req.resolve.paths(name) ?? []).map((d) => join(d, name, "package.json")).find((f) => existsSync(f));
42
+ if (!at)
43
+ throw new Error(`${name} isn't installed: run npm install`);
44
+ const manifest = JSON.parse(read(at));
45
+ if (!manifest.exports || !Object.hasOwn(manifest.exports, "./styles"))
46
+ continue;
47
+ const mod = (await import(__rewriteRelativeImportExtension(pathToFileURL(req.resolve(`${name}/styles`)).href)));
48
+ const found = Object.values(mod).filter((x) => !!x && typeof x === "object" && x.format === 1 && typeof x.prefix === "string");
49
+ if (found.length !== 1)
50
+ throw new Error(`${name}/styles must export exactly one ToolStyles`);
51
+ tools.push({ styles: found[0], version: manifest.version });
52
+ }
53
+ const own = JSON.parse(read(resolve(dirname(fileURLToPath(import.meta.url)), "../package.json")));
54
+ return { tools, uiVersion: version("@mccaskie-labs/workbench-ui") ?? own.version };
55
+ }
56
+ /** What `styles` writes in `dir`, and what --check would fail on, without touching the disk. */
57
+ export function planStyles(dir, tools, uiVersion) {
58
+ const files = {};
59
+ const problems = [];
60
+ const generated = renderStyles(tools, uiVersion);
61
+ const genPath = join(dir, STYLE_FILES.generated);
62
+ if (!existsSync(genPath) || read(genPath) !== generated) {
63
+ files[STYLE_FILES.generated] = generated;
64
+ problems.push(`${STYLE_FILES.generated} is out of date with the installed Workbench packages`);
65
+ }
66
+ const projPath = join(dir, STYLE_FILES.project);
67
+ if (!existsSync(projPath)) {
68
+ files[STYLE_FILES.project] = starterProjectCss(tools);
69
+ problems.push(`${STYLE_FILES.project} is missing`);
70
+ }
71
+ else {
72
+ const unknown = unknownNames(read(projPath), tools);
73
+ if (unknown.length)
74
+ problems.push(`${STYLE_FILES.project} names ${unknown.join(", ")}, which no installed Workbench tool draws (renamed or removed: see workbench.css)`);
75
+ }
76
+ return { files, problems };
77
+ }
78
+ async function main(argv) {
79
+ const [command, ...rest] = argv;
80
+ if (command !== "styles") {
81
+ console.error(USAGE);
82
+ return 2;
83
+ }
84
+ const check = rest.includes("--check");
85
+ const dirs = rest.filter((a) => a !== "--check");
86
+ if (dirs.length > 1 || dirs.some((d) => d.startsWith("-"))) {
87
+ console.error(USAGE);
88
+ return 2;
89
+ }
90
+ const dir = resolve(dirs[0] ?? ".");
91
+ const { tools, uiVersion } = await installedStyles(dir);
92
+ const plan = planStyles(dir, tools, uiVersion);
93
+ if (check) {
94
+ if (!plan.problems.length) {
95
+ console.log(`${STYLE_FILES.generated} is current (${tools.map((t) => `${t.styles.package} ${t.version}`).join(", ") || "no styled tools"})`);
96
+ return 0;
97
+ }
98
+ for (const p of plan.problems)
99
+ console.error(p);
100
+ console.error("Run `npx workbench-ui styles` and commit the result; fix project.css by hand.");
101
+ return 1;
102
+ }
103
+ for (const [path, text] of Object.entries(plan.files)) {
104
+ mkdirSync(dirname(join(dir, path)), { recursive: true });
105
+ writeFileSync(join(dir, path), text);
106
+ console.log(`wrote ${path}`);
107
+ }
108
+ const left = plan.problems.filter((p) => p.startsWith(STYLE_FILES.project) && !plan.files[STYLE_FILES.project]);
109
+ for (const p of left)
110
+ console.error(p);
111
+ return left.length ? 1 : 0;
112
+ }
113
+ // Run only when this file is the program, compared by resolved path: a test that imports it must never write files.
114
+ const self = realpathSync(fileURLToPath(import.meta.url));
115
+ const program = process.argv[1] ? realpathSync(resolve(process.argv[1])) : "";
116
+ if (self === program) {
117
+ process.exitCode = await main(process.argv.slice(2)).catch((e) => {
118
+ console.error(e.message);
119
+ return 1;
120
+ });
121
+ }
@@ -21,6 +21,9 @@
21
21
  * sent, and its message clears. This updates as the person types.
22
22
  * - Reset clears every message, the summary and the counters.
23
23
  *
24
+ * Every element it adds carries a \`wb-form-*\` class (workbench-forms'
25
+ * FORM_STYLES), the same names renderForm uses.
26
+ *
24
27
  * Messages come only from the config (already in the visitor's language) and
25
28
  * are written as text, never as HTML. Without WorkbenchForms of the same
26
29
  * version on the page it does nothing: the endpoint still checks everything.
@@ -21,6 +21,9 @@
21
21
  * sent, and its message clears. This updates as the person types.
22
22
  * - Reset clears every message, the summary and the counters.
23
23
  *
24
+ * Every element it adds carries a \`wb-form-*\` class (workbench-forms'
25
+ * FORM_STYLES), the same names renderForm uses.
26
+ *
24
27
  * Messages come only from the config (already in the visitor's language) and
25
28
  * are written as text, never as HTML. Without WorkbenchForms of the same
26
29
  * version on the page it does nothing: the endpoint still checks everything.
@@ -82,7 +85,7 @@ export const FORM_SCRIPT = `(() => {
82
85
  if (!els.length) return null;
83
86
  p = document.createElement("p");
84
87
  p.id = id;
85
- p.className = "field-error";
88
+ p.className = "wb-form-error";
86
89
  const last = els[els.length - 1];
87
90
  const anchor = last.closest("fieldset") && els.length > 1 ? last.closest("fieldset") : last;
88
91
  anchor.insertAdjacentElement("afterend", p);
@@ -116,9 +119,9 @@ export const FORM_SCRIPT = `(() => {
116
119
  for (const n of names) input[n] = read(n);
117
120
  try { return F.validate(cfg.form, input, cfg.context); } catch (e) { console.error("workbench-ui: form " + name + ": " + e.message); return null; }
118
121
  };
119
- let live = form.querySelector(".wb-live");
120
- if (!live) { live = document.createElement("p"); live.className = "wb-live"; live.setAttribute("role", "status"); live.setAttribute("aria-live", "polite"); form.prepend(live); }
121
- const summary = form.hasAttribute("data-wb-summary") ? (form.querySelector(".wb-summary") || form.insertBefore(Object.assign(document.createElement("div"), { className: "wb-summary", tabIndex: -1 }), form.firstChild)) : null;
122
+ let live = form.querySelector(".wb-form-live");
123
+ if (!live) { live = document.createElement("p"); live.className = "wb-form-live"; live.setAttribute("role", "status"); live.setAttribute("aria-live", "polite"); form.prepend(live); }
124
+ const summary = form.hasAttribute("data-wb-summary") ? (form.querySelector(".wb-form-summary") || form.insertBefore(Object.assign(document.createElement("div"), { className: "wb-form-summary", tabIndex: -1 }), form.firstChild)) : null;
122
125
  // A summary the server drew after a failed submit takes focus, so it is read out once.
123
126
  if (summary && !summary.hidden && summary.textContent.trim()) summary.focus();
124
127
  const say = (key, count) => { const text = Object.prototype.hasOwnProperty.call(messages, key) ? fill(messages[key], { count }) : ""; live.textContent = ""; setTimeout(() => { live.textContent = text; }, 50); return text; };
@@ -126,12 +129,12 @@ export const FORM_SCRIPT = `(() => {
126
129
  for (const el of form.querySelectorAll("[data-wb-max]")) {
127
130
  const id = "wb-count-" + name + "-" + el.name;
128
131
  let c = document.getElementById(id);
129
- if (!c) { c = document.createElement("span"); c.id = id; c.className = "wb-counter"; c.setAttribute("aria-hidden", "true"); el.insertAdjacentElement("afterend", c); }
132
+ if (!c) { c = document.createElement("span"); c.id = id; c.className = "wb-form-counter"; c.setAttribute("aria-hidden", "true"); el.insertAdjacentElement("afterend", c); }
130
133
  const def = fields[el.name];
131
134
  const tidied = def && def.kind === "long_text" ? F.tidyText(el.value) : F.tidyLine(el.value);
132
135
  const n = Array.from(tidied).length;
133
136
  c.textContent = n + " / " + el.getAttribute("data-wb-max");
134
- c.classList.toggle("over", n > Number(el.getAttribute("data-wb-max")));
137
+ c.classList.toggle("wb-form-counter-over", n > Number(el.getAttribute("data-wb-max")));
135
138
  }
136
139
  };
137
140
  const wrapper = (n) => form.querySelector('[data-wb-field="' + n + '"]');
@@ -210,11 +213,15 @@ export const FORM_SCRIPT = `(() => {
210
213
  if (summary) {
211
214
  summary.textContent = "";
212
215
  const head = document.createElement("p");
216
+ head.className = "wb-form-summary-title";
213
217
  head.textContent = text;
214
218
  const list = document.createElement("ul");
219
+ list.className = "wb-form-summary-list";
215
220
  for (const p of r.problems) {
216
221
  const li = document.createElement("li");
222
+ li.className = "wb-form-summary-item";
217
223
  const a = document.createElement("a");
224
+ a.className = "wb-form-summary-link";
218
225
  a.href = "#" + idFor(p.field);
219
226
  a.textContent = words(p);
220
227
  li.append(a);
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export { CSS, STYLE } from "./style.ts";
2
2
  export { FORM_SCRIPT } from "./form-script.ts";
3
+ export { renderStyles, STYLE_FILES, STYLED_SCOPE, styleNames, styleProblems, STYLESHEETS, starterProjectCss, unknownNames, type InstalledStyles, type StyleClass, type StyleState, type StyleVariable, type ToolStyles, } from "./styles.ts";
3
4
  /** Plain text made safe to put in HTML, in text or in a quoted attribute. */
4
5
  export declare const escape: (value: string) => string;
5
6
  /** The outcome colours: a pill's class and, prefixed with o-, a table row's left edge. */
@@ -111,6 +112,12 @@ export interface ShellOptions {
111
112
  body: string;
112
113
  /** HTML for the end of the head, such as a page's own <style> after the shared one. */
113
114
  head?: string;
115
+ /**
116
+ * Stylesheets to link instead of the inline shared look, such as STYLESHEETS in
117
+ * a project: its generated workbench.css (the look and every tool's classes)
118
+ * then its own project.css.
119
+ */
120
+ stylesheets?: readonly string[];
114
121
  /** HTML after the page, such as a <script> with the response's nonce. */
115
122
  tail?: string;
116
123
  }
package/dist/index.js CHANGED
@@ -5,6 +5,7 @@
5
5
  import { STYLE } from "./style.js";
6
6
  export { CSS, STYLE } from "./style.js";
7
7
  export { FORM_SCRIPT } from "./form-script.js";
8
+ export { renderStyles, STYLE_FILES, STYLED_SCOPE, styleNames, styleProblems, STYLESHEETS, starterProjectCss, unknownNames, } from "./styles.js";
8
9
  /** Plain text made safe to put in HTML, in text or in a quoted attribute. */
9
10
  export const escape = (value) => value.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
10
11
  /** A coloured outcome pill. `text` is plain text. */
@@ -157,7 +158,7 @@ export function topBar(opts) {
157
158
  /** A whole page: the shared look, the top bar, the heading, then `body`. */
158
159
  export function shell(opts) {
159
160
  return `<!doctype html><html lang="en-AU"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="dark">
160
- <title>${escape(opts.title)} · ${escape(opts.site)}</title>${STYLE}${opts.head ?? ""}
161
+ <title>${escape(opts.title)} · ${escape(opts.site)}</title>${opts.stylesheets ? opts.stylesheets.map((href) => `<link rel="stylesheet" href="${escape(href)}">`).join("") : STYLE}${opts.head ?? ""}
161
162
  ${opts.top}
162
163
  <main class="wrap"><h1>${escape(opts.title)}</h1>${opts.body}</main>${opts.tail ?? ""}</html>`;
163
164
  }
package/dist/style.js CHANGED
@@ -152,24 +152,10 @@ dl.plain dl.plain>dd{margin-bottom:.5rem}dl.plain dl.plain>dd:last-child{margin-
152
152
  @media (max-width:640px){dl.plain{grid-template-columns:1fr;gap:.1rem}dl.plain dd{margin-bottom:.5rem}}
153
153
  @media (prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}
154
154
  textarea,select{font:inherit;color:var(--text);background:var(--surface);border:1px solid var(--line);border-radius:6px;padding:.45rem .6rem;min-height:2.75rem}
155
- textarea{width:100%;min-height:6rem;max-height:var(--wb-textarea-cap);field-sizing:content;resize:vertical}
155
+ textarea{width:100%;min-height:6rem;max-height:20rem;field-sizing:content;resize:vertical}
156
156
  textarea:focus-visible,select:focus-visible{outline:none;box-shadow:0 0 0 3px var(--focus)}
157
- :root{--wb-w-xs:6ch;--wb-w-s:12ch;--wb-w-m:24ch;--wb-w-l:40ch;--wb-textarea-cap:20rem}
158
- .wb-w-xs{width:calc(var(--wb-w-xs) + 1.4rem)}.wb-w-s{width:calc(var(--wb-w-s) + 1.4rem)}.wb-w-m{width:calc(var(--wb-w-m) + 1.4rem)}
159
- .wb-w-l{width:min(100%,calc(var(--wb-w-l) + 1.4rem))}.wb-w-full{width:100%}
160
157
  input:not([type=hidden]):not([type=checkbox]):not([type=radio]){min-height:2.75rem}
161
158
  [aria-invalid=true]{border-color:var(--fail)}
162
- .field-error{margin:.3rem 0 0;color:var(--fail);font-size:.875rem}
163
- .field-error:empty{display:none}
164
- .wb-counter{display:block;margin-top:.2rem;color:var(--muted);font-size:.78rem;font-variant-numeric:tabular-nums}
165
- .wb-counter.over{color:var(--fail)}
166
- .wb-summary{margin:0 0 1rem;padding:.6rem .75rem;border-left:3px solid var(--fail);background:var(--fail-bg);border-radius:6px}
167
- .wb-summary[hidden],.wb-summary:empty{display:none}
168
- .wb-summary p{margin:0 0 .3rem;font-weight:600}.wb-summary ul{margin:0;padding-left:1.1rem}
169
- .wb-field{margin:0 0 1rem}.wb-field>label,.wb-field legend{display:block;font-weight:600;margin:0 0 .3rem}
170
- .wb-field fieldset{border:0;margin:0;padding:0;min-width:0}.wb-option{display:flex;gap:.5rem;align-items:center;min-height:2.75rem;font-weight:400}
171
- .wb-optional{font-weight:400;color:var(--muted)}.wb-hint{margin:0 0 .35rem;color:var(--muted);font-size:.875rem}
172
- .wb-live{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap}
173
159
  @media (max-width:640px){nav.links{margin-left:0}th,td{padding:.55rem .7rem}table.kv th{width:auto}}
174
160
  `;
175
161
  /** The shared rules as a <style> tag. */
@@ -0,0 +1,65 @@
1
+ /** One CSS custom property a tool's rules read, with its default. */
2
+ export interface StyleVariable {
3
+ name: string;
4
+ value: string;
5
+ about: string;
6
+ }
7
+ /** A rule for a class in another state, appended to its selector (`[aria-invalid=true]`, `:hover`). */
8
+ export interface StyleState {
9
+ selector: string;
10
+ about: string;
11
+ css: string;
12
+ }
13
+ /** One class a tool puts on an element, with its default declarations. */
14
+ export interface StyleClass {
15
+ name: string;
16
+ element: string;
17
+ about: string;
18
+ css: string;
19
+ states?: readonly StyleState[];
20
+ }
21
+ /** Every class and variable one tool draws with (workbench-forms' FORM_STYLES, for one). */
22
+ export interface ToolStyles {
23
+ format: 1;
24
+ tool: string;
25
+ package: string;
26
+ title: string;
27
+ prefix: string;
28
+ variables: readonly StyleVariable[];
29
+ classes: readonly StyleClass[];
30
+ }
31
+ /** A tool's styles with the version of the package installed. */
32
+ export interface InstalledStyles {
33
+ styles: ToolStyles;
34
+ version: string;
35
+ }
36
+ /** Where the generated stylesheet and the project's own sit, from the project's root. */
37
+ export declare const STYLE_FILES: {
38
+ readonly generated: "public/styles/workbench.css";
39
+ readonly project: "public/styles/project.css";
40
+ };
41
+ /** The addresses a page links, in order: Workbench's defaults, then the project's own rules. */
42
+ export declare const STYLESHEETS: readonly string[];
43
+ /**
44
+ * The scope searched for tools that draw on a project's pages: every package
45
+ * the project depends on in it whose package.json exports "./styles", which
46
+ * exports one ToolStyles (workbench-forms' FORM_STYLES, workbench-pdf's PDF_STYLES).
47
+ */
48
+ export declare const STYLED_SCOPE = "@mccaskie-labs/workbench-";
49
+ /** What is wrong with a tool's styles: a name off its prefix, a class with no default rule, a variable used but not listed. */
50
+ export declare function styleProblems(s: ToolStyles): string[];
51
+ /**
52
+ * The project's generated stylesheet: workbench-ui's page look in
53
+ * `@layer workbench.page`, then each tool's classes in `@layer workbench.tools`,
54
+ * which wins over the page look.
55
+ */
56
+ export declare function renderStyles(tools: readonly InstalledStyles[], uiVersion: string): string;
57
+ /** The starting project.css: empty rules the project fills, with every variable listed in a comment. */
58
+ export declare function starterProjectCss(tools: readonly InstalledStyles[]): string;
59
+ /** Every wb- class and variable the tools draw with: what a project's own CSS may name. */
60
+ export declare function styleNames(tools: readonly InstalledStyles[]): {
61
+ classes: Set<string>;
62
+ variables: Set<string>;
63
+ };
64
+ /** The wb- classes and variables a project's stylesheet names that no installed tool draws (comments ignored). */
65
+ export declare function unknownNames(projectCss: string, tools: readonly InstalledStyles[]): string[];
package/dist/styles.js ADDED
@@ -0,0 +1,160 @@
1
+ // Restyling what Workbench tools draw in a project (docs/capabilities-manifest.md
2
+ // §10, Robert, 12 November 2026). Every element a tool puts on a project's
3
+ // pages carries a `wb-<tool>-<part>` class with a default rule, and colours and
4
+ // sizes are `--wb-<tool>-*` variables. `npx workbench-ui styles` writes them all,
5
+ // each with a comment saying what it is, into the project's
6
+ // public/styles/workbench.css inside `@layer workbench`, so any rule in the
7
+ // project's own public/styles/project.css wins without !important. This file
8
+ // renders that stylesheet and lists the names a project may use.
9
+ import { CSS } from "./style.js";
10
+ /** Where the generated stylesheet and the project's own sit, from the project's root. */
11
+ export const STYLE_FILES = { generated: "public/styles/workbench.css", project: "public/styles/project.css" };
12
+ /** The addresses a page links, in order: Workbench's defaults, then the project's own rules. */
13
+ export const STYLESHEETS = ["/styles/workbench.css", "/styles/project.css"];
14
+ /**
15
+ * The scope searched for tools that draw on a project's pages: every package
16
+ * the project depends on in it whose package.json exports "./styles", which
17
+ * exports one ToolStyles (workbench-forms' FORM_STYLES, workbench-pdf's PDF_STYLES).
18
+ */
19
+ export const STYLED_SCOPE = "@mccaskie-labs/workbench-";
20
+ const NAME = /^[a-z][a-z0-9-]*$/;
21
+ /** What is wrong with a tool's styles: a name off its prefix, a class with no default rule, a variable used but not listed. */
22
+ export function styleProblems(s) {
23
+ const out = [];
24
+ if (s.format !== 1)
25
+ out.push(`${s.tool}: format must be 1`);
26
+ if (!/^wb-[a-z]+-$/.test(s.prefix))
27
+ out.push(`${s.tool}: prefix must look like wb-<tool>-`);
28
+ const base = s.prefix.slice(0, -1);
29
+ const vars = new Set();
30
+ for (const v of s.variables) {
31
+ if (!v.name.startsWith(`--${s.prefix}`) || !NAME.test(v.name.slice(2)))
32
+ out.push(`${s.tool}: variable ${v.name} must start with --${s.prefix}`);
33
+ if (vars.has(v.name))
34
+ out.push(`${s.tool}: variable ${v.name} is listed twice`);
35
+ if (!v.value.trim() || !v.about.trim())
36
+ out.push(`${s.tool}: variable ${v.name} needs a value and what it is for`);
37
+ vars.add(v.name);
38
+ }
39
+ const classes = new Set();
40
+ for (const c of s.classes) {
41
+ if ((c.name !== base && !c.name.startsWith(s.prefix)) || !NAME.test(c.name))
42
+ out.push(`${s.tool}: class ${c.name} must be ${base} or start with ${s.prefix}`);
43
+ if (classes.has(c.name))
44
+ out.push(`${s.tool}: class ${c.name} is listed twice`);
45
+ classes.add(c.name);
46
+ if (!c.css.trim())
47
+ out.push(`${s.tool}: class ${c.name} has no default rule`);
48
+ if (!c.about.trim() || !c.element.trim())
49
+ out.push(`${s.tool}: class ${c.name} needs its element and what it is for`);
50
+ for (const st of c.states ?? []) {
51
+ if (!st.css.trim() || !st.about.trim())
52
+ out.push(`${s.tool}: ${c.name}${st.selector} needs a rule and what it is for`);
53
+ if (/[{}]/.test(st.selector))
54
+ out.push(`${s.tool}: ${c.name}${st.selector} can't hold braces`);
55
+ }
56
+ for (const css of [c.css, ...(c.states ?? []).map((st) => st.css)]) {
57
+ if (/[{}]/.test(css))
58
+ out.push(`${s.tool}: ${c.name}'s rule can't hold braces`);
59
+ for (const m of css.matchAll(/var\((--[a-z0-9-]+)/g))
60
+ if (!vars.has(m[1]))
61
+ out.push(`${s.tool}: ${c.name} reads ${m[1]}, which isn't listed`);
62
+ }
63
+ }
64
+ return out;
65
+ }
66
+ const comment = (text) => `/* ${text.replace(/\*\//g, "* /")} */`;
67
+ const decls = (css, indent) => css
68
+ .split(";")
69
+ .map((d) => d.trim())
70
+ .filter(Boolean)
71
+ .map((d) => `${indent}${d};`)
72
+ .join("\n");
73
+ /** One tool's block: its variables on :root, then each class and its states, each with a comment. */
74
+ function toolBlock({ styles: s, version }) {
75
+ const out = [` ${comment(`${s.title}: ${s.package} ${version}. Every class starts ${s.prefix} or is ${s.prefix.slice(0, -1)}.`)}`, " :root {"];
76
+ for (const v of s.variables)
77
+ out.push(` ${comment(v.about)}`, ` ${v.name}: ${v.value};`);
78
+ out.push(" }");
79
+ for (const c of s.classes) {
80
+ out.push("", ` ${comment(`<${c.element}> ${c.about}`)}`, ` .${c.name} {`, decls(c.css, " "), " }");
81
+ for (const st of c.states ?? [])
82
+ out.push(` ${comment(st.about)}`, ` .${c.name}${st.selector} {`, decls(st.css, " "), " }");
83
+ }
84
+ return out.join("\n");
85
+ }
86
+ const HEADER = [
87
+ "/*",
88
+ " * Generated by `npx workbench-ui styles`. Don't edit: `npx workbench-ui styles --check` fails when this file differs.",
89
+ " *",
90
+ " * Every element a Workbench tool draws on this project's pages has a class listed below, with its default look,",
91
+ " * and colours and sizes are the --wb-* variables. To restyle one, write a rule for the same class, or set the",
92
+ " * variable, in project.css. It loads after this file and isn't in a layer, so its rules always win.",
93
+ " */",
94
+ ];
95
+ /**
96
+ * The project's generated stylesheet: workbench-ui's page look in
97
+ * `@layer workbench.page`, then each tool's classes in `@layer workbench.tools`,
98
+ * which wins over the page look.
99
+ */
100
+ export function renderStyles(tools, uiVersion) {
101
+ const problems = tools.flatMap((t) => styleProblems(t.styles));
102
+ if (problems.length)
103
+ throw new Error(`workbench-ui styles: ${problems.join("; ")}`);
104
+ const page = CSS.trim().replace(/^/gm, " ");
105
+ return [
106
+ ...HEADER,
107
+ "@layer workbench.page, workbench.tools;",
108
+ "",
109
+ comment(`The page look: @mccaskie-labs/workbench-ui ${uiVersion} (shell, topBar, card and the rest). Not yet split into wb- classes.`),
110
+ "@layer workbench.page {",
111
+ page,
112
+ "}",
113
+ "",
114
+ "@layer workbench.tools {",
115
+ tools.map(toolBlock).join("\n\n"),
116
+ "}",
117
+ "",
118
+ ].join("\n");
119
+ }
120
+ /** The starting project.css: empty rules the project fills, with every variable listed in a comment. */
121
+ export function starterProjectCss(tools) {
122
+ const vars = tools.flatMap(({ styles: s }) => s.variables.map((v) => ` * ${v.name}: ${v.value}; ${v.about}`));
123
+ return [
124
+ "/*",
125
+ " * This project's own look for what Workbench tools draw. Yours to edit; `npx workbench-ui styles` never",
126
+ " * overwrites it. It loads after workbench.css, which lists every wb- class and variable with its default.",
127
+ " * Rules here always win. Restyle by class (.wb-form-submit { ... }) or map a variable to your own:",
128
+ " *",
129
+ " * :root {",
130
+ ...vars,
131
+ " * }",
132
+ " */",
133
+ "",
134
+ ].join("\n");
135
+ }
136
+ /** Every wb- class and variable the tools draw with: what a project's own CSS may name. */
137
+ export function styleNames(tools) {
138
+ const classes = new Set();
139
+ const variables = new Set();
140
+ for (const { styles: s } of tools) {
141
+ for (const c of s.classes)
142
+ classes.add(c.name);
143
+ for (const v of s.variables)
144
+ variables.add(v.name);
145
+ }
146
+ return { classes, variables };
147
+ }
148
+ /** The wb- classes and variables a project's stylesheet names that no installed tool draws (comments ignored). */
149
+ export function unknownNames(projectCss, tools) {
150
+ const known = styleNames(tools);
151
+ const css = projectCss.replace(/\/\*[\s\S]*?\*\//g, "");
152
+ const out = new Set();
153
+ for (const m of css.matchAll(/\.(wb-[a-z0-9-]+)/g))
154
+ if (!known.classes.has(m[1]))
155
+ out.add(`.${m[1]}`);
156
+ for (const m of css.matchAll(/(--wb-[a-z0-9-]+)/g))
157
+ if (!known.variables.has(m[1]))
158
+ out.add(m[1]);
159
+ return [...out];
160
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mccaskie-labs/workbench-ui",
3
- "version": "0.3.2",
3
+ "version": "0.4.1",
4
4
  "description": "Workbench pages: one dark look, a top bar with the environment tag, cards, outcome pills, and one format for times, money and durations.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
@@ -20,6 +20,9 @@
20
20
  },
21
21
  "./package.json": "./package.json"
22
22
  },
23
+ "bin": {
24
+ "workbench-ui": "./dist/cli.js"
25
+ },
23
26
  "files": [
24
27
  "dist",
25
28
  "README.md",