@behavioral-agentic-design-system/core 0.42.0 → 0.45.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/LICENSE +21 -0
- package/package.json +25 -9
- package/scripts/a11y-lint.cjs +25 -1
- package/scripts/check-spec.mjs +73 -0
- package/scripts/deal-directions.mjs +186 -0
- package/scripts/health-report.mjs +20 -14
- package/scripts/lib/counted-lint.mjs +100 -0
- package/scripts/lib/marketing-library.mjs +129 -0
- package/scripts/lib/on-system.mjs +249 -0
- package/scripts/lib/random.mjs +22 -0
- package/scripts/lib/spec-parse.d.mts +25 -0
- package/scripts/lib/spec-parse.mjs +188 -0
- package/scripts/lib/tells.mjs +128 -0
- package/scripts/lint-css-vars.mjs +175 -0
- package/scripts/lint-html-nesting.mjs +116 -0
- package/scripts/lint-live-ctas.mjs +138 -0
- package/scripts/on-system-score.mjs +95 -0
- package/scripts/slop-rules.mjs +1 -1
- package/scripts/source-images.mjs +180 -0
- package/scripts/ux-tells.mjs +78 -0
- package/src/api/brand-colors.ts +3 -0
- package/src/api/brand-fonts.ts +3 -0
- package/src/api/brand-mark.ts +6 -1
- package/src/api/dev-write-guard.ts +53 -0
- package/src/api/layers/file.ts +7 -4
- package/src/api/onboarding-extract.ts +85 -30
- package/src/api/onboarding.ts +3 -0
- package/src/api/save-tokens.ts +3 -0
- package/src/app/layout.tsx +6 -0
- package/src/app/preview/canvas/page.tsx +12 -0
- package/src/app/preview/components/page.tsx +734 -0
- package/src/app/preview/studio/blank-screen.tsx +143 -0
- package/src/app/preview/studio/page.tsx +7 -0
- package/src/app/shell.tsx +160 -44
- package/src/components/canvas/canvas.tsx +458 -0
- package/src/components/canvas/layout.ts +72 -0
- package/src/components/canvas/parse-canvas.ts +32 -0
- package/src/components/canvas/sample.ts +90 -0
- package/src/components/canvas/spec-frame.tsx +43 -0
- package/src/components/canvas/types.ts +33 -0
- package/src/components/docs-tab.tsx +7 -7
- package/src/components/home-recent.tsx +73 -0
- package/src/components/home-tab.tsx +13 -13
- package/src/components/layers-tab.tsx +2 -2
- package/src/components/markdown-preview.tsx +60 -12
- package/src/components/studio/control-panel.tsx +299 -0
- package/src/components/studio/control-row.tsx +77 -0
- package/src/components/studio/preview-frame.tsx +165 -0
- package/src/components/studio/preview-pane.tsx +247 -0
- package/src/components/studio/studio.tsx +133 -128
- package/src/components/studio/types.ts +218 -0
- package/src/components/studio/use-studio-tweaks.ts +128 -0
- package/src/components/studio/use-studio-view-state.ts +72 -0
- package/src/components/ui/autocomplete.tsx +1 -1
- package/src/components/ui/color-picker.tsx +20 -4
- package/src/components/ui/data-table.tsx +64 -3
- package/src/components/ui/date-field.tsx +1 -1
- package/src/components/ui/editable.tsx +1 -0
- package/src/components/ui/faceted-filter.tsx +187 -0
- package/src/components/ui/gauge-chart.tsx +18 -4
- package/src/components/ui/inline-edit.tsx +175 -0
- package/src/components/ui/month-picker.tsx +1 -1
- package/src/components/ui/number-input.tsx +28 -5
- package/src/components/ui/otp-input.tsx +208 -0
- package/src/components/ui/phone-input.tsx +274 -0
- package/src/components/ui/search-input.tsx +1 -1
- package/src/components/ui/tags-input.tsx +1 -1
- package/src/components/ui/timer.tsx +1 -0
- package/src/components/ui/transfer-list.tsx +13 -26
- package/src/components/ui/week-picker.tsx +1 -1
- package/src/components/ui/year-picker.tsx +1 -1
- package/src/data/component-added.json +958 -0
- package/src/data/docs-index.ts +13 -1
- package/src/hooks/use-global-mono-font.ts +1 -0
- package/src/hooks/use-global-primary-color.ts +1 -0
- package/src/hooks/use-global-sans-font.ts +1 -0
- package/src/hooks/use-global-serif-font.ts +1 -0
- package/src/hooks/use-global-type-scale.ts +17 -2
- package/src/hooks/use-mobile.ts +2 -0
- package/src/hooks/use-sync-type-scale.ts +7 -11
- package/src/lib/spec-parse.ts +4 -0
- package/src/lib/svg-sanitize.ts +19 -9
- package/src/stories/Autocomplete.stories.tsx +2 -0
- package/src/stories/Canvas.stories.tsx +45 -0
- package/src/stories/ColorPicker.stories.tsx +40 -0
- package/src/stories/DataTable.stories.tsx +30 -0
- package/src/stories/DateField.stories.tsx +21 -0
- package/src/stories/Editable.stories.tsx +2 -0
- package/src/stories/FacetedFilter.stories.tsx +197 -0
- package/src/stories/GaugeChart.stories.tsx +9 -3
- package/src/stories/InlineEdit.stories.tsx +106 -0
- package/src/stories/MarkdownPreview.stories.tsx +53 -0
- package/src/stories/MonthPicker.stories.tsx +21 -0
- package/src/stories/NumberInput.stories.tsx +25 -0
- package/src/stories/OtpInput.stories.tsx +110 -0
- package/src/stories/PhoneInput.stories.tsx +127 -0
- package/src/stories/SearchInput.stories.tsx +2 -0
- package/src/stories/TagsInput.stories.tsx +2 -0
- package/src/stories/Timer.stories.tsx +26 -0
- package/src/stories/TransferList.stories.tsx +4 -0
- package/src/stories/WeekPicker.stories.tsx +21 -0
- package/src/stories/YearPicker.stories.tsx +21 -0
- package/src/stories/story-groups.json +22 -16
- package/src/tokens.json +82 -54
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rendered "tells": the signals that a page was generated, read from computed
|
|
3
|
+
* styles in a real browser at several widths. lint-slop reads source text; this
|
|
4
|
+
* reads what paints, so it sees classes composed at runtime and the effect of the
|
|
5
|
+
* cascade. The registry's shape (dated, banned or warned) and the idea of
|
|
6
|
+
* checking the rendered page at three widths are from Leonxlnx/taste-skill (MIT);
|
|
7
|
+
* the rules are chosen to fit BADS's own registers and real-content rule.
|
|
8
|
+
*
|
|
9
|
+
* Two parts, kept apart so the logic is testable without a browser:
|
|
10
|
+
* probe() runs INSIDE the page and returns plain facts. Self-contained.
|
|
11
|
+
* classify() turns those facts into findings. Pure.
|
|
12
|
+
*
|
|
13
|
+
* What it does not flag, by design: eyebrow labels (sanctioned by the CTA size
|
|
14
|
+
* contract), editorial serif emphasis, and the terminal register. They are
|
|
15
|
+
* chosen design in BADS, as lint-slop's header explains.
|
|
16
|
+
*/
|
|
17
|
+
import { SLOP_EMOJI } from "../slop-rules.mjs";
|
|
18
|
+
|
|
19
|
+
export const WIDTHS = [375, 768, 1280];
|
|
20
|
+
|
|
21
|
+
/** code, name, status (banned fails the run; warned is reported), and why. */
|
|
22
|
+
export const TELLS = [
|
|
23
|
+
{ code: "BADS-TELL-1", name: "gradient-text", status: "banned", why: "Gradient-filled headline text. Carries no information. Use a solid foreground token." },
|
|
24
|
+
{ code: "BADS-TELL-2", name: "indigo-violet-gradient", status: "banned", why: "An indigo or violet gradient on a large surface or a button. The default machine palette." },
|
|
25
|
+
{ code: "BADS-TELL-3", name: "glass-panels", status: "warned", why: "Two or more translucent panels with backdrop blur. Use opaque surfaces one tone step from the ground." },
|
|
26
|
+
{ code: "BADS-TELL-4", name: "glow", status: "warned", why: "A box-shadow with a blur of 40px or more. Use a tone step, or no shadow." },
|
|
27
|
+
{ code: "BADS-TELL-5", name: "three-up-icon-cards", status: "warned", why: "Three equal cards in a row, each with a small icon and a heading. The stock feature row." },
|
|
28
|
+
{ code: "BADS-TELL-6", name: "pill-above-headline", status: "warned", why: "A small pill badge directly above the page headline ('New', 'Beta'). Say it in the supporting sentence." },
|
|
29
|
+
{ code: "BADS-TELL-7", name: "decorative-emoji", status: "banned", why: "Decorative emoji in page copy. Use words or a real picture." },
|
|
30
|
+
{ code: "BADS-TELL-8", name: "pulsing-status-dot", status: "warned", why: "A small dot that pulses forever with no live state behind it." },
|
|
31
|
+
{ code: "BADS-TELL-9", name: "placeholder-copy", status: "banned", why: "Placeholder text (Lorem ipsum, Jane Doe, Acme Inc., 555 numbers). The real-content rule: pull from content/personas/<brand>.json." },
|
|
32
|
+
{ code: "BADS-TELL-10", name: "placeholder-image", status: "banned", why: "An image from a placeholder service. Show the real product or a real picture of the client's world (bads-source-images)." },
|
|
33
|
+
{ code: "BADS-TELL-11", name: "horizontal-overflow", status: "banned", why: "The page scrolls sideways at this width. Fix the layout, not the rhythm." },
|
|
34
|
+
];
|
|
35
|
+
|
|
36
|
+
/** Runs in the browser. Returns plain, serializable facts. Must not reference anything outside itself. */
|
|
37
|
+
export function probe() {
|
|
38
|
+
const MAX = 4000;
|
|
39
|
+
const facts = { gradientText: [], gradients: [], glass: [], glow: [], cards: [], pills: [], emoji: [], pulse: [], copy: [], images: [], overflow: null };
|
|
40
|
+
const px = (v) => parseFloat(v) || 0;
|
|
41
|
+
const label = (el) => (el.tagName.toLowerCase() + (el.id ? "#" + el.id : "") + (typeof el.className === "string" && el.className.trim() ? "." + el.className.trim().split(/\s+/).slice(0, 2).join(".") : "")).slice(0, 80);
|
|
42
|
+
const canvas = document.createElement("canvas");
|
|
43
|
+
canvas.width = canvas.height = 1;
|
|
44
|
+
const cx = canvas.getContext("2d", { willReadFrequently: true });
|
|
45
|
+
const toRgb = (css) => { try { cx.clearRect(0, 0, 1, 1); cx.fillStyle = "#000"; cx.fillStyle = css; cx.fillRect(0, 0, 1, 1); const d = cx.getImageData(0, 0, 1, 1).data; return [d[0], d[1], d[2], d[3] / 255]; } catch { return null; } };
|
|
46
|
+
const hsl = ([r, g, b]) => { r /= 255; g /= 255; b /= 255; const mx = Math.max(r, g, b), mn = Math.min(r, g, b), l = (mx + mn) / 2, d = mx - mn; if (!d) return [0, 0, l]; const s = d / (1 - Math.abs(2 * l - 1)); const h = mx === r ? ((g - b) / d) % 6 : mx === g ? (b - r) / d + 2 : (r - g) / d + 4; return [(h * 60 + 360) % 360, s, l]; };
|
|
47
|
+
const COLOR = /(?:rgba?|hsla?|oklch|oklab|lab|lch|color)\([^)]*\)/g;
|
|
48
|
+
const vw = innerWidth, vh = innerHeight;
|
|
49
|
+
const els = [...document.body.querySelectorAll("*")].slice(0, MAX);
|
|
50
|
+
const visible = (el, r, cs) => r.width > 0 && r.height > 0 && cs.visibility !== "hidden" && cs.display !== "none" && cs.opacity !== "0";
|
|
51
|
+
|
|
52
|
+
for (const el of els) {
|
|
53
|
+
const cs = getComputedStyle(el), r = el.getBoundingClientRect();
|
|
54
|
+
if (!visible(el, r, cs)) continue;
|
|
55
|
+
if (/text/.test(cs.webkitBackgroundClip || cs.backgroundClip) && /gradient/.test(cs.backgroundImage) && (cs.webkitTextFillColor === "rgba(0, 0, 0, 0)" || cs.color === "rgba(0, 0, 0, 0)") && el.textContent.trim()) facts.gradientText.push({ el: label(el), text: el.textContent.trim().slice(0, 40) });
|
|
56
|
+
if (/gradient/.test(cs.backgroundImage) && !/text/.test(cs.webkitBackgroundClip || cs.backgroundClip)) {
|
|
57
|
+
const area = (r.width * r.height) / (vw * vh), isButton = el.matches("button, a, [role=button]");
|
|
58
|
+
if (area > 0.15 || isButton) {
|
|
59
|
+
const stops = (cs.backgroundImage.match(COLOR) || []).map(toRgb).filter((c) => c && c[3] > 0.3).map(hsl);
|
|
60
|
+
const violet = stops.filter(([h, s, l]) => h >= 235 && h <= 300 && s >= 0.4 && l > 0.15 && l < 0.85);
|
|
61
|
+
if (violet.length >= 2 || (violet.length >= 1 && stops.length <= 2 && violet.length === stops.length)) facts.gradients.push({ el: label(el), stops: stops.length });
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
if (/blur/.test(cs.backdropFilter || cs.webkitBackdropFilter || "")) { const bg = toRgb(cs.backgroundColor); if (bg && bg[3] > 0 && bg[3] < 0.95) facts.glass.push({ el: label(el) }); }
|
|
65
|
+
for (const sh of (cs.boxShadow || "").split(/,(?![^(]*\))/)) { const nums = (sh.replace(COLOR, "").match(/-?\d*\.?\d+px/g) || []).map(px); if (nums.length >= 3 && nums[2] >= 40 && sh.trim() !== "none") { facts.glow.push({ el: label(el), blur: nums[2] }); break; } }
|
|
66
|
+
if (cs.animationName !== "none" && cs.animationIterationCount === "infinite" && r.width <= 14 && r.height <= 14 && px(cs.borderTopLeftRadius) >= r.width / 2 - 1) facts.pulse.push({ el: label(el) });
|
|
67
|
+
if (el.tagName === "IMG" && /picsum\.photos|placehold\.|placeholder\.com|dummyimage|lorempixel|via\.placeholder|placekitten|loremflickr/i.test(el.currentSrc || el.src)) facts.images.push({ el: label(el), src: (el.currentSrc || el.src).slice(0, 80) });
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// Three equal cards, each with a small icon and a heading.
|
|
71
|
+
for (const parent of els) {
|
|
72
|
+
const kids = [...parent.children].filter((k) => { const r = k.getBoundingClientRect(); return r.width > 80 && r.height > 60; });
|
|
73
|
+
if (kids.length !== 3) continue;
|
|
74
|
+
const rs = kids.map((k) => k.getBoundingClientRect());
|
|
75
|
+
if (!(Math.abs(rs[0].width - rs[1].width) < 3 && Math.abs(rs[1].width - rs[2].width) < 3 && Math.abs(rs[0].top - rs[2].top) < 3)) continue;
|
|
76
|
+
const small = (k) => [...k.querySelectorAll("svg, img")].some((i) => { const b = i.getBoundingClientRect(); return b.width > 0 && b.width <= 64 && b.height <= 64; });
|
|
77
|
+
if (kids.every((k) => small(k) && k.querySelector("h2, h3, h4, strong"))) facts.cards.push({ el: label(parent) });
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// A small pill directly before the first h1.
|
|
81
|
+
const h1 = document.querySelector("h1");
|
|
82
|
+
if (h1) for (let el = h1.previousElementSibling; el; el = null) { const cs = getComputedStyle(el), r = el.getBoundingClientRect(); if (r.height > 0 && r.height <= 36 && px(cs.fontSize) <= 14 && px(cs.borderTopLeftRadius) >= r.height / 2 - 1 && el.textContent.trim().length <= 24) facts.pills.push({ text: el.textContent.trim() }); }
|
|
83
|
+
|
|
84
|
+
const text = document.body.innerText || "";
|
|
85
|
+
const emo = text.match(new RegExp(EMOJI_SOURCE, "gu"));
|
|
86
|
+
if (emo) facts.emoji = [...new Set(emo)];
|
|
87
|
+
const ph = text.match(/lorem ipsum|dolor sit amet|\bjane doe\b|\bjohn doe\b|acme inc|123 main st|555[-. ]?555/gi);
|
|
88
|
+
if (ph) facts.copy = [...new Set(ph.map((s) => s.toLowerCase()))];
|
|
89
|
+
facts.overflow = { scrollWidth: document.documentElement.scrollWidth, innerWidth: vw };
|
|
90
|
+
return facts;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// probe() is serialized into the page, so it can't import SLOP_EMOJI. The source is
|
|
94
|
+
// injected before serializing (see probeSource), keeping one definition of the set.
|
|
95
|
+
/** The source of probe() with the emoji set inlined, ready for page.evaluate. */
|
|
96
|
+
export function probeSource() {
|
|
97
|
+
return `(() => { const EMOJI_SOURCE = ${JSON.stringify(SLOP_EMOJI.source)}; return (${probe.toString()})(); })()`;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Turn one width's facts into findings. Pure. */
|
|
101
|
+
export function classify(facts, width) {
|
|
102
|
+
const out = [];
|
|
103
|
+
const add = (name, detail) => { const t = TELLS.find((x) => x.name === name); out.push({ code: t.code, name, status: t.status, width, detail, why: t.why }); };
|
|
104
|
+
for (const g of facts.gradientText || []) add("gradient-text", `${g.el}: "${g.text}"`);
|
|
105
|
+
for (const g of facts.gradients || []) add("indigo-violet-gradient", g.el);
|
|
106
|
+
if ((facts.glass || []).length >= 2) add("glass-panels", `${facts.glass.length} panels, e.g. ${facts.glass[0].el}`);
|
|
107
|
+
for (const g of (facts.glow || []).slice(0, 3)) add("glow", `${g.el}: ${g.blur}px blur`);
|
|
108
|
+
for (const c of facts.cards || []) add("three-up-icon-cards", c.el);
|
|
109
|
+
for (const p of facts.pills || []) add("pill-above-headline", `"${p.text}"`);
|
|
110
|
+
if ((facts.emoji || []).length) add("decorative-emoji", facts.emoji.join(" "));
|
|
111
|
+
for (const p of (facts.pulse || []).slice(0, 3)) add("pulsing-status-dot", p.el);
|
|
112
|
+
if ((facts.copy || []).length) add("placeholder-copy", facts.copy.join(", "));
|
|
113
|
+
for (const i of facts.images || []) add("placeholder-image", `${i.el}: ${i.src}`);
|
|
114
|
+
const o = facts.overflow;
|
|
115
|
+
if (o && o.scrollWidth > o.innerWidth + 1) add("horizontal-overflow", `${o.scrollWidth}px wide in a ${o.innerWidth}px window`);
|
|
116
|
+
return out;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Findings from every width, with a tell seen at several widths shown once. */
|
|
120
|
+
export function merge(perWidth) {
|
|
121
|
+
const seen = new Map();
|
|
122
|
+
for (const f of perWidth.flat()) {
|
|
123
|
+
const key = `${f.code}|${f.detail}`;
|
|
124
|
+
if (seen.has(key)) { if (!seen.get(key).widths.includes(f.width)) seen.get(key).widths.push(f.width); }
|
|
125
|
+
else seen.set(key, { ...f, widths: [f.width] });
|
|
126
|
+
}
|
|
127
|
+
return [...seen.values()].map(({ width, ...rest }) => rest);
|
|
128
|
+
}
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* lint-css-vars — a custom property that is referenced but never declared.
|
|
4
|
+
*
|
|
5
|
+
* Enforces layer-6-patterns-and-rules/declared-custom-properties.md. CSS does
|
|
6
|
+
* not error on `var(--missing)`. `border-radius: var(--missing)` computes to 0px
|
|
7
|
+
* and `color: var(--missing)` falls back to the inherited colour, so the page
|
|
8
|
+
* renders, the build passes, and the defect ships looking like a design
|
|
9
|
+
* decision. The case that wrote this: four radius properties were deleted from a
|
|
10
|
+
* brand stylesheet with a comment saying every call site now used a utility, ten
|
|
11
|
+
* call sites still referenced them, and eight pills and status circles shipped
|
|
12
|
+
* square while every check stayed green.
|
|
13
|
+
*
|
|
14
|
+
* What counts as declared:
|
|
15
|
+
* - `--name:` in any stylesheet the BUILD emitted. Read the built CSS, not the
|
|
16
|
+
* source: hundreds of properties come from a Tailwind `@theme` block at build
|
|
17
|
+
* time and appear in no stylesheet on disk.
|
|
18
|
+
* - `--name:` anywhere in source, which covers `@property`, a CSS file, a style
|
|
19
|
+
* prop key (`style={{ "--progress": "40%" }}`) and `setProperty("--name", …)`.
|
|
20
|
+
*
|
|
21
|
+
* What it skips: a reference with a fallback (`var(--x, 9999px)`), which cannot
|
|
22
|
+
* render as nothing by construction; a name built at runtime (`var(--color-${key})`);
|
|
23
|
+
* anything inside a comment; and, with a reason, a line marked
|
|
24
|
+
* `css-var-ok: <why this is set at runtime>`. Property families a library sets at
|
|
25
|
+
* runtime (a chart's `--color-<series>`) are named once with --allow; Radix's
|
|
26
|
+
* `--radix-*`, Tailwind's `--tw-*` and cmdk's `--cmdk-*` are built in.
|
|
27
|
+
*
|
|
28
|
+
* It fails rather than skips when there is no built CSS to read. A check that
|
|
29
|
+
* quietly passes when it could not run is how this defect survives in the first
|
|
30
|
+
* place.
|
|
31
|
+
*
|
|
32
|
+
* Run (after a build):
|
|
33
|
+
* npx bads-lint-css-vars # looks for out/, then .next/static
|
|
34
|
+
* npx bads-lint-css-vars --css dist/assets # name the built CSS directory
|
|
35
|
+
* npx bads-lint-css-vars --allow --color- # property families set at runtime (chart series)
|
|
36
|
+
* npx bads-lint-css-vars --warn | --init | --ratchet
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
import fs from "node:fs";
|
|
40
|
+
import path from "node:path";
|
|
41
|
+
import { finishCountedLint, flagValue, isMain } from "./lib/counted-lint.mjs";
|
|
42
|
+
|
|
43
|
+
/** Families that libraries set on elements at runtime, so no stylesheet declares them. */
|
|
44
|
+
export const RUNTIME_FAMILIES = ["--radix-", "--tw-", "--cmdk-"];
|
|
45
|
+
|
|
46
|
+
const SOURCE_ROOTS = ["app", "components", "src", "styles", "packages/core/src"];
|
|
47
|
+
const SOURCE_EXT = /\.(tsx?|jsx?|css|mdx?)$/;
|
|
48
|
+
const SKIP = new Set(["node_modules", ".next", "out", "dist", ".scratch", ".git", "vendor"]);
|
|
49
|
+
|
|
50
|
+
/** Strip comments, keeping line structure, so prose that names a property is not a reference. */
|
|
51
|
+
export function stripComments(src) {
|
|
52
|
+
return src
|
|
53
|
+
.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, " "))
|
|
54
|
+
.replace(/(^|[^:])\/\/.*$/gm, (m, pre) => pre + " ".repeat(m.length - pre.length));
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Every `--name` this text declares: `--name:` in CSS, a quoted style-prop key, or setProperty. */
|
|
58
|
+
export function extractDeclared(text) {
|
|
59
|
+
const out = new Set();
|
|
60
|
+
for (const m of text.matchAll(/(--[A-Za-z0-9_-]+)\s*:/g)) out.add(m[1]);
|
|
61
|
+
for (const m of text.matchAll(/["'`](--[A-Za-z0-9_-]+)["'`]\s*:/g)) out.add(m[1]);
|
|
62
|
+
for (const m of text.matchAll(/setProperty\(\s*["'`](--[A-Za-z0-9_-]+)["'`]/g)) out.add(m[1]);
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const MARKER = /css-var-ok:([^\n*]*)/;
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* @param {string} src
|
|
70
|
+
* @param {Set<string>} declared
|
|
71
|
+
* @param {{ allowPrefixes?: string[] }} [opts] property families set at runtime, e.g. ["--color-"] for chart series
|
|
72
|
+
* @returns {{line: number, prop: string, text?: string}[]}
|
|
73
|
+
*/
|
|
74
|
+
export function findUndeclared(src, declared, { allowPrefixes = [] } = {}) {
|
|
75
|
+
const raw = src.split("\n");
|
|
76
|
+
const findings = [];
|
|
77
|
+
stripComments(src)
|
|
78
|
+
.split("\n")
|
|
79
|
+
.forEach((line, i) => {
|
|
80
|
+
// group 2: `${` right after the name means var(--color-${key}), a name built at runtime.
|
|
81
|
+
for (const m of line.matchAll(/var\(\s*(--[A-Za-z0-9_-]+)(\$\{)?\s*(,)?/g)) {
|
|
82
|
+
if (m[3]) continue; // has a fallback: cannot render as nothing
|
|
83
|
+
if (m[2]) continue; // the name is built at runtime, so it cannot be checked statically
|
|
84
|
+
const name = m[1];
|
|
85
|
+
if (declared.has(name) || allowPrefixes.some((p) => name.startsWith(p))) continue;
|
|
86
|
+
const marker = [raw[i], raw[i - 1]].map((l) => (l ?? "").match(MARKER)).find(Boolean);
|
|
87
|
+
if (marker) {
|
|
88
|
+
if (marker[1].trim()) continue;
|
|
89
|
+
findings.push({ line: i + 1, prop: name, text: "css-var-ok marker needs a reason after the colon" });
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
findings.push({ line: i + 1, prop: name });
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
return findings;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function walk(dir, exts, out = []) {
|
|
99
|
+
let entries;
|
|
100
|
+
try {
|
|
101
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
102
|
+
} catch {
|
|
103
|
+
return out;
|
|
104
|
+
}
|
|
105
|
+
for (const e of entries) {
|
|
106
|
+
if (SKIP.has(e.name) || e.name.startsWith(".")) continue;
|
|
107
|
+
const p = path.join(dir, e.name);
|
|
108
|
+
if (e.isDirectory()) walk(p, exts, out);
|
|
109
|
+
else if (exts.test(e.name)) out.push(p);
|
|
110
|
+
}
|
|
111
|
+
return out;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
if (isMain(import.meta.url)) {
|
|
115
|
+
const root = process.cwd();
|
|
116
|
+
const argv = process.argv.slice(2);
|
|
117
|
+
const cssArg = flagValue(argv, "css", null);
|
|
118
|
+
const cssDirs = (cssArg ? [cssArg] : ["out", ".next/static"]).map((d) => path.join(root, d)).filter((d) => fs.existsSync(d));
|
|
119
|
+
|
|
120
|
+
if (!cssDirs.length) {
|
|
121
|
+
console.error("bads-lint-css-vars: no built CSS found (looked for out/ and .next/static).");
|
|
122
|
+
console.error(" This lint reads the BUILT stylesheet, because most custom properties are emitted at build time and appear in no file on disk.");
|
|
123
|
+
console.error(" Build first, or point at the output with --css <dir>. Failing rather than skipping on purpose.");
|
|
124
|
+
process.exit(1);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const declared = new Set();
|
|
128
|
+
let cssFiles = 0;
|
|
129
|
+
for (const d of cssDirs) {
|
|
130
|
+
for (const f of walkAll(d, /\.css$/)) {
|
|
131
|
+
cssFiles++;
|
|
132
|
+
for (const p of extractDeclared(fs.readFileSync(f, "utf8"))) declared.add(p);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
if (declared.size === 0) {
|
|
136
|
+
console.error(`bads-lint-css-vars: parsed 0 custom properties from ${cssFiles} built CSS file(s). The build output moved or the parser drifted. Not reporting success on an empty read.`);
|
|
137
|
+
process.exit(1);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// Prefix values start with "--", so the generic flag parser would read the value as another flag.
|
|
141
|
+
const allowIdx = argv.findIndex((a) => a === "--allow" || a.startsWith("--allow="));
|
|
142
|
+
const allowArg = allowIdx < 0 ? "" : argv[allowIdx].includes("=") ? argv[allowIdx].slice(argv[allowIdx].indexOf("=") + 1) : (argv[allowIdx + 1] ?? "");
|
|
143
|
+
const allowPrefixes = [...RUNTIME_FAMILIES, ...allowArg.split(",").map((x) => x.trim()).filter(Boolean)];
|
|
144
|
+
const sourceRoots = argv.filter((a) => !a.startsWith("--") && a !== cssArg && a !== allowArg);
|
|
145
|
+
const files = (sourceRoots.length ? sourceRoots : SOURCE_ROOTS).map((r) => path.join(root, r)).filter((r) => fs.existsSync(r)).flatMap((r) => (fs.statSync(r).isDirectory() ? walk(r, SOURCE_EXT) : [r]));
|
|
146
|
+
const sources = files.map((f) => ({ f, src: fs.readFileSync(f, "utf8") }));
|
|
147
|
+
for (const { src } of sources) for (const p of extractDeclared(src)) declared.add(p);
|
|
148
|
+
|
|
149
|
+
const findings = [];
|
|
150
|
+
const scanned = [];
|
|
151
|
+
for (const { f, src } of sources) {
|
|
152
|
+
const rel = path.relative(root, f);
|
|
153
|
+
scanned.push(rel);
|
|
154
|
+
for (const u of findUndeclared(src, declared, { allowPrefixes })) findings.push({ file: rel, line: u.line, text: u.text ?? `${u.prop} is referenced but never declared` });
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
process.exit(
|
|
158
|
+
finishCountedLint({
|
|
159
|
+
ruleId: "undeclared-css-vars",
|
|
160
|
+
bin: "bads-lint-css-vars",
|
|
161
|
+
findings,
|
|
162
|
+
scanned,
|
|
163
|
+
fix: "Declare the property, switch to a utility class that exists, or give the reference a fallback: var(--radius-pill, 9999px). See layer-6-patterns-and-rules/declared-custom-properties.md.",
|
|
164
|
+
}),
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function walkAll(dir, re, out = []) {
|
|
169
|
+
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
170
|
+
const p = path.join(dir, e.name);
|
|
171
|
+
if (e.isDirectory()) walkAll(p, re, out);
|
|
172
|
+
else if (re.test(e.name)) out.push(p);
|
|
173
|
+
}
|
|
174
|
+
return out;
|
|
175
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* lint-html-nesting — invalid HTML nesting in the built output.
|
|
4
|
+
*
|
|
5
|
+
* Enforces layer-6-patterns-and-rules/valid-html-nesting.md. `Separator` renders
|
|
6
|
+
* a <div>, so putting one inside a <p> is invalid HTML and throws React
|
|
7
|
+
* hydration error #418 in the browser, while `next build` reports success.
|
|
8
|
+
* Nothing in a component's documentation says what element it produces, so there
|
|
9
|
+
* is no way to know in advance, and the only signal is a console error someone
|
|
10
|
+
* has to be looking for. A passing build that emits a broken page is worse than
|
|
11
|
+
* a failing one, because people stop looking, so this reads the emitted HTML
|
|
12
|
+
* instead of trusting the build.
|
|
13
|
+
*
|
|
14
|
+
* It flags, per HTML file:
|
|
15
|
+
* <p> containing flow content (div, p, ul, ol, li, section, article, hr,
|
|
16
|
+
* table, h1-h6) a <p> may only hold phrasing content
|
|
17
|
+
* <button> inside <button> interactive content may not nest
|
|
18
|
+
* <a> inside <a> likewise
|
|
19
|
+
*
|
|
20
|
+
* <script> blocks are removed first: the framework payload is full of strings
|
|
21
|
+
* that look like markup.
|
|
22
|
+
*
|
|
23
|
+
* It fails rather than skips when there is no built HTML to read, because a
|
|
24
|
+
* check that quietly passes when it could not run is the anti-pattern it exists
|
|
25
|
+
* to catch. (Set BADS_ALLOW_MISSING_BUILD=1 to skip locally.)
|
|
26
|
+
*
|
|
27
|
+
* Run (after a build):
|
|
28
|
+
* npx bads-lint-html-nesting # looks for out/, then .next/server/app
|
|
29
|
+
* npx bads-lint-html-nesting --html dist # name the built HTML directory
|
|
30
|
+
* npx bads-lint-html-nesting --warn | --init | --ratchet
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
import fs from "node:fs";
|
|
34
|
+
import path from "node:path";
|
|
35
|
+
import { finishCountedLint, flagValue, isMain } from "./lib/counted-lint.mjs";
|
|
36
|
+
|
|
37
|
+
const FORBIDDEN_IN_P = ["div", "p", "ul", "ol", "li", "section", "article", "hr", "table", "h1", "h2", "h3", "h4", "h5", "h6"];
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* @param {string} html
|
|
41
|
+
* @returns {{tag: string, parent: string, snippet: string}[]}
|
|
42
|
+
*/
|
|
43
|
+
export function findInvalidNesting(html) {
|
|
44
|
+
const doc = html.replace(/<script\b[\s\S]*?<\/script>/gi, "").replace(/<style\b[\s\S]*?<\/style>/gi, "");
|
|
45
|
+
const found = [];
|
|
46
|
+
|
|
47
|
+
// <p> cannot nest, so the span from an opening <p> to the next </p> is its content.
|
|
48
|
+
for (const m of doc.matchAll(/<p(\s[^>]*)?>/g)) {
|
|
49
|
+
const start = m.index + m[0].length;
|
|
50
|
+
const close = doc.indexOf("</p>", start);
|
|
51
|
+
if (close === -1) continue;
|
|
52
|
+
const inner = doc.slice(start, close);
|
|
53
|
+
const tag = FORBIDDEN_IN_P.find((t) => new RegExp(`<${t}(\\s|>|/)`, "i").test(inner));
|
|
54
|
+
if (tag) found.push({ tag, parent: "p", snippet: doc.slice(m.index, Math.min(close + 4, m.index + 150)).replace(/\s+/g, " ") });
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
for (const t of ["button", "a"]) {
|
|
58
|
+
for (const m of doc.matchAll(new RegExp(`<${t}(\\s[^>]*)?>`, "gi"))) {
|
|
59
|
+
const start = m.index + m[0].length;
|
|
60
|
+
const close = doc.indexOf(`</${t}>`, start);
|
|
61
|
+
if (close === -1) continue;
|
|
62
|
+
if (new RegExp(`<${t}(\\s|>)`, "i").test(doc.slice(start, close))) {
|
|
63
|
+
found.push({ tag: t, parent: t, snippet: doc.slice(m.index, Math.min(close + t.length + 3, m.index + 150)).replace(/\s+/g, " ") });
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return found;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function walkHtml(dir, out = []) {
|
|
71
|
+
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
72
|
+
const p = path.join(dir, e.name);
|
|
73
|
+
if (e.isDirectory()) walkHtml(p, out);
|
|
74
|
+
else if (e.name.endsWith(".html")) out.push(p);
|
|
75
|
+
}
|
|
76
|
+
return out;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
if (isMain(import.meta.url)) {
|
|
80
|
+
const root = process.cwd();
|
|
81
|
+
const argv = process.argv.slice(2);
|
|
82
|
+
const htmlArg = flagValue(argv, "html", null);
|
|
83
|
+
const dirs = (htmlArg ? [htmlArg] : ["out", ".next/server/app"]).map((d) => path.join(root, d)).filter((d) => fs.existsSync(d));
|
|
84
|
+
|
|
85
|
+
if (!dirs.length) {
|
|
86
|
+
if (process.env.BADS_ALLOW_MISSING_BUILD && !process.env.CI) {
|
|
87
|
+
console.log("bads-lint-html-nesting: SKIPPED, no built HTML (BADS_ALLOW_MISSING_BUILD is set).");
|
|
88
|
+
process.exit(0);
|
|
89
|
+
}
|
|
90
|
+
console.error("bads-lint-html-nesting: no built HTML found (looked for out/ and .next/server/app).");
|
|
91
|
+
console.error(" This lint reads the HTML the build emitted. Build first, or point at it with --html <dir>.");
|
|
92
|
+
process.exit(1);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const findings = [];
|
|
96
|
+
const scanned = [];
|
|
97
|
+
for (const d of dirs) {
|
|
98
|
+
for (const f of walkHtml(d)) {
|
|
99
|
+
const rel = path.relative(root, f);
|
|
100
|
+
scanned.push(rel);
|
|
101
|
+
for (const n of findInvalidNesting(fs.readFileSync(f, "utf8"))) {
|
|
102
|
+
findings.push({ file: rel, text: `<${n.tag}> inside <${n.parent}>: ${n.snippet.slice(0, 110)}` });
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
process.exit(
|
|
108
|
+
finishCountedLint({
|
|
109
|
+
ruleId: "html-nesting",
|
|
110
|
+
bin: "bads-lint-html-nesting",
|
|
111
|
+
findings,
|
|
112
|
+
scanned,
|
|
113
|
+
fix: "Usually a component renders an element you did not expect (Separator renders a div). Check what it produces, and use a span, a wrapper outside the paragraph, or a different component. See layer-6-patterns-and-rules/valid-html-nesting.md.",
|
|
114
|
+
}),
|
|
115
|
+
);
|
|
116
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* lint-live-ctas — a call to action that does nothing when you press it.
|
|
4
|
+
*
|
|
5
|
+
* Enforces layer-6-patterns-and-rules/live-ctas.md. A dead button is
|
|
6
|
+
* indistinguishable from a live one to a compiler or a screenshot: it types, it
|
|
7
|
+
* renders, it has the right colour and the right label. The rule is that a
|
|
8
|
+
* button which does nothing has to SAY it does nothing.
|
|
9
|
+
*
|
|
10
|
+
* What counts as alive, on a `<Button>`:
|
|
11
|
+
* onClick it does something
|
|
12
|
+
* href it goes somewhere
|
|
13
|
+
* disabled deliberately inert, and saying so
|
|
14
|
+
* type="submit" it submits the form it sits in ("reset" likewise)
|
|
15
|
+
* asChild the child element is the control and owns its behaviour
|
|
16
|
+
* inside a <form> a button with no type submits it, which is HTML's default (type="button" opts out)
|
|
17
|
+
* {...spread} the props are not knowable here, so it is given the benefit
|
|
18
|
+
* a <…Trigger|Close|Action|Cancel asChild> parent
|
|
19
|
+
* the primitive wires the press: opening or closing a menu, popover or dialog
|
|
20
|
+
*
|
|
21
|
+
* Scenery is the honest exception: a prototype that draws app chrome around the
|
|
22
|
+
* thing under review has buttons that are inert on purpose, and `disabled` would
|
|
23
|
+
* be a false statement about the real page. Say so on the line or the line above:
|
|
24
|
+
*
|
|
25
|
+
* {/* live-cta-ok: app chrome, scenery around the screen under review *\/}
|
|
26
|
+
*
|
|
27
|
+
* A bare marker with no reason does not count. The reason is the mechanism.
|
|
28
|
+
*
|
|
29
|
+
* Why the tag is walked rather than matched with a regex: `icon={<Check />}`
|
|
30
|
+
* puts a `>` inside the attribute list, so `[^>]*` cuts the tag in half and the
|
|
31
|
+
* half without `onClick` reports as dead. The walker tracks brace depth and
|
|
32
|
+
* quotes and stops at the `>` that actually ends the tag.
|
|
33
|
+
*
|
|
34
|
+
* Run:
|
|
35
|
+
* npx bads-lint-live-ctas # report, exit 1 on any finding
|
|
36
|
+
* npx bads-lint-live-ctas --warn # report, exit 0
|
|
37
|
+
* npx bads-lint-live-ctas --init # record today's counts as a baseline
|
|
38
|
+
* npx bads-lint-live-ctas --ratchet # fail only on growth (see lib/counted-lint.mjs)
|
|
39
|
+
* npx bads-lint-live-ctas path/to.tsx # one file, or a directory
|
|
40
|
+
*/
|
|
41
|
+
|
|
42
|
+
import fs from "node:fs";
|
|
43
|
+
import path from "node:path";
|
|
44
|
+
import scanRootsLib from "./lib/scan-roots.cjs";
|
|
45
|
+
import { finishCountedLint, isMain } from "./lib/counted-lint.mjs";
|
|
46
|
+
|
|
47
|
+
const { resolveScanFiles } = scanRootsLib;
|
|
48
|
+
|
|
49
|
+
/** Blank comments with spaces so offsets and line numbers stay the same. */
|
|
50
|
+
export function blankComments(src) {
|
|
51
|
+
return src
|
|
52
|
+
.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, " "))
|
|
53
|
+
.replace(/(^|[^:])\/\/.*$/gm, (m, pre) => pre + " ".repeat(m.length - pre.length));
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const MARKER = /live-cta-ok:([^\n*]*)/;
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* @param {string} src
|
|
60
|
+
* @returns {{line: number, text: string}[]}
|
|
61
|
+
*/
|
|
62
|
+
export function findDeadCtas(src) {
|
|
63
|
+
const code = blankComments(src);
|
|
64
|
+
const lines = src.split("\n");
|
|
65
|
+
const findings = [];
|
|
66
|
+
|
|
67
|
+
for (const m of code.matchAll(/<Button\b/g)) {
|
|
68
|
+
let i = m.index + m[0].length;
|
|
69
|
+
let depth = 0;
|
|
70
|
+
let quote = null;
|
|
71
|
+
for (; i < code.length; i++) {
|
|
72
|
+
const c = code[i];
|
|
73
|
+
if (quote) {
|
|
74
|
+
if (c === quote) quote = null;
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
if (c === '"' || c === "'" || c === "`") quote = c;
|
|
78
|
+
else if (c === "{") depth++;
|
|
79
|
+
else if (c === "}") depth--;
|
|
80
|
+
else if (c === ">" && depth === 0) break;
|
|
81
|
+
}
|
|
82
|
+
const attrs = code.slice(m.index + m[0].length, i);
|
|
83
|
+
const line = code.slice(0, m.index).split("\n").length;
|
|
84
|
+
|
|
85
|
+
const alive =
|
|
86
|
+
/\bonClick\b|\bhref\b|\bdisabled\b|\basChild\b|\{\s*\.\.\./.test(attrs) ||
|
|
87
|
+
/\btype\s*=\s*\{?["'](submit|reset)["']/.test(attrs) ||
|
|
88
|
+
/<[\w.]*(?:Trigger|Close|Action|Cancel)\b[^>]*\basChild\b[^>]*>\s*$/.test(code.slice(Math.max(0, m.index - 160), m.index));
|
|
89
|
+
// A button inside a <form> with no type submits it, which is what HTML does by default.
|
|
90
|
+
const before = code.slice(0, m.index);
|
|
91
|
+
const inForm = (before.match(/<form\b/g) ?? []).length > (before.match(/<\/form>/g) ?? []).length;
|
|
92
|
+
const implicitSubmit = inForm && !/\btype\s*=\s*\{?["']button["']/.test(attrs);
|
|
93
|
+
if (alive || implicitSubmit) continue;
|
|
94
|
+
|
|
95
|
+
const marker = [lines[line - 1], lines[line - 2]].map((l) => (l ?? "").match(MARKER)).find(Boolean);
|
|
96
|
+
if (marker) {
|
|
97
|
+
if (marker[1].trim()) continue;
|
|
98
|
+
findings.push({ line, text: "live-cta-ok marker needs a reason after the colon" });
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const label = code
|
|
103
|
+
.slice(i + 1, i + 90)
|
|
104
|
+
.split("</Button>")[0]
|
|
105
|
+
.replace(/\s+/g, " ")
|
|
106
|
+
.trim()
|
|
107
|
+
.slice(0, 40);
|
|
108
|
+
findings.push({ line, text: `<Button> with no onClick, href, disabled, type="submit" or asChild: ${label ? `"${label}"` : "(dynamic label)"}` });
|
|
109
|
+
}
|
|
110
|
+
return findings;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
if (isMain(import.meta.url)) {
|
|
114
|
+
const root = process.cwd();
|
|
115
|
+
const scan = resolveScanFiles({ root, argv: process.argv.slice(2), excludeStories: true, allowDirArgs: true });
|
|
116
|
+
const findings = [];
|
|
117
|
+
const scanned = [];
|
|
118
|
+
for (const abs of scan.files) {
|
|
119
|
+
let src;
|
|
120
|
+
try {
|
|
121
|
+
src = fs.readFileSync(abs, "utf8");
|
|
122
|
+
} catch {
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
if (!/\.tsx$/.test(abs)) continue;
|
|
126
|
+
const rel = path.relative(root, abs);
|
|
127
|
+
scanned.push(rel);
|
|
128
|
+
for (const f of findDeadCtas(src)) findings.push({ file: rel, ...f });
|
|
129
|
+
}
|
|
130
|
+
const code = finishCountedLint({
|
|
131
|
+
ruleId: "live-ctas",
|
|
132
|
+
bin: "bads-lint-live-ctas",
|
|
133
|
+
findings,
|
|
134
|
+
scanned,
|
|
135
|
+
fix: 'Give it a handler, a destination, or `disabled`. A button that is inert on purpose can say so with `{/* live-cta-ok: <reason> */}` on the line above. See layer-6-patterns-and-rules/live-ctas.md.',
|
|
136
|
+
});
|
|
137
|
+
process.exit(code);
|
|
138
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* on-system-score: what share of your styling decisions use the design system.
|
|
4
|
+
*
|
|
5
|
+
* bads-on-system score the default roots (app, components, src)
|
|
6
|
+
* bads-on-system prototypes/foo score one folder or file
|
|
7
|
+
* bads-on-system --list also print every off-system decision with file:line
|
|
8
|
+
* bads-on-system --json machine-readable, for a dashboard or a CI summary
|
|
9
|
+
* bads-on-system --min 90 exit 1 when the overall score is below 90
|
|
10
|
+
*
|
|
11
|
+
* Counts color, spacing, type, radius and shadow. What counts as on or off, and what this cannot see, is written at
|
|
12
|
+
* the top of scripts/lib/on-system.mjs. It is a trend and a pointer to the files worth opening, not a verdict:
|
|
13
|
+
* informational by default, and only a gate if you pass --min. Escape hatch: `allow-off-system: <reason>` on the
|
|
14
|
+
* line, or the line above.
|
|
15
|
+
*
|
|
16
|
+
* It reads the source, so point it at product code (a screen, a prototype, an app folder), not at the design
|
|
17
|
+
* system's own primitives, which are where the tokens are applied in the first place.
|
|
18
|
+
*/
|
|
19
|
+
import fs from "node:fs";
|
|
20
|
+
import path from "node:path";
|
|
21
|
+
|
|
22
|
+
import scanRootsLib from "./lib/scan-roots.cjs";
|
|
23
|
+
import { CATEGORIES, addCounts, overall, percent, scoreSource } from "./lib/on-system.mjs";
|
|
24
|
+
|
|
25
|
+
const { resolveScanFiles, guardEmptyScan } = scanRootsLib;
|
|
26
|
+
|
|
27
|
+
const ROOT = process.cwd();
|
|
28
|
+
const argv = process.argv.slice(2);
|
|
29
|
+
const flag = (name) => argv.includes(name);
|
|
30
|
+
const valueOf = (name) => {
|
|
31
|
+
const i = argv.indexOf(name);
|
|
32
|
+
return i === -1 ? null : argv[i + 1];
|
|
33
|
+
};
|
|
34
|
+
const min = valueOf("--min") === null ? null : Number(valueOf("--min"));
|
|
35
|
+
const top = Number(valueOf("--top") ?? 5);
|
|
36
|
+
// A value after --min / --top is not a path.
|
|
37
|
+
const pathArgs = argv.filter((a, i) => !a.startsWith("--") && !["--min", "--top"].includes(argv[i - 1]));
|
|
38
|
+
|
|
39
|
+
const scan = resolveScanFiles({ root: ROOT, argv: pathArgs, excludeStories: true, allowDirArgs: true });
|
|
40
|
+
guardEmptyScan(scan, "on-system-score");
|
|
41
|
+
// UI files only: a server route or a data module is not a styling decision, and its color strings would read as one.
|
|
42
|
+
const files = scan.files.filter((f) => /\.(tsx|jsx)$/.test(f) && !/\.(test|spec)\./.test(f));
|
|
43
|
+
|
|
44
|
+
const total = Object.fromEntries(CATEGORIES.map((c) => [c, { on: 0, off: 0 }]));
|
|
45
|
+
const perFile = [];
|
|
46
|
+
for (const file of files) {
|
|
47
|
+
const { counts, offenders } = scoreSource(fs.readFileSync(file, "utf8"));
|
|
48
|
+
addCounts(total, counts);
|
|
49
|
+
const o = overall(counts);
|
|
50
|
+
if (o.on + o.off > 0) perFile.push({ file: path.relative(ROOT, file), ...o, offenders });
|
|
51
|
+
}
|
|
52
|
+
const all = overall(total);
|
|
53
|
+
|
|
54
|
+
if (flag("--json")) {
|
|
55
|
+
console.log(
|
|
56
|
+
JSON.stringify(
|
|
57
|
+
{
|
|
58
|
+
percent: all.percent,
|
|
59
|
+
decisions: all.on + all.off,
|
|
60
|
+
off: all.off,
|
|
61
|
+
categories: Object.fromEntries(CATEGORIES.map((c) => [c, { ...total[c], percent: percent(total[c]) }])),
|
|
62
|
+
files: perFile.map(({ file, percent: p, on, off, offenders }) => ({ file, percent: p, on, off, offenders })),
|
|
63
|
+
},
|
|
64
|
+
null,
|
|
65
|
+
2,
|
|
66
|
+
),
|
|
67
|
+
);
|
|
68
|
+
} else {
|
|
69
|
+
if (all.percent === null) {
|
|
70
|
+
console.log(`on-system: no styling decisions found in ${files.length} file(s).`);
|
|
71
|
+
process.exit(0);
|
|
72
|
+
}
|
|
73
|
+
const bar = (p) => (p === null ? " n/a" : `${String(p.toFixed(1)).padStart(5)}%`);
|
|
74
|
+
console.log(`On system: ${all.percent.toFixed(1)}% (${all.on.toLocaleString()} of ${(all.on + all.off).toLocaleString()} styling decisions, ${files.length} files)\n`);
|
|
75
|
+
for (const c of CATEGORIES) {
|
|
76
|
+
const t = total[c];
|
|
77
|
+
console.log(` ${c.padEnd(8)} ${bar(percent(t))} ${t.on}/${t.on + t.off}${t.off ? ` (${t.off} off)` : ""}`);
|
|
78
|
+
}
|
|
79
|
+
const worst = perFile.filter((f) => f.off > 0).sort((a, b) => b.off - a.off || a.percent - b.percent).slice(0, top);
|
|
80
|
+
if (worst.length) {
|
|
81
|
+
console.log(`\nMost off-system:`);
|
|
82
|
+
for (const f of worst) console.log(` ${f.file} ${f.percent.toFixed(1)}% (${f.off} off)`);
|
|
83
|
+
}
|
|
84
|
+
if (flag("--list")) {
|
|
85
|
+
console.log(`\nEvery off-system decision:`);
|
|
86
|
+
for (const f of perFile) for (const o of f.offenders) console.log(` ${f.file}:${o.line} [${o.category}] ${o.what}`);
|
|
87
|
+
} else if (all.off) {
|
|
88
|
+
console.log(`\nRun with --list to see each one.`);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
if (min !== null && all.percent !== null && all.percent < min) {
|
|
93
|
+
console.error(`\n✗ on-system: ${all.percent.toFixed(1)}% is below the --min of ${min}%.`);
|
|
94
|
+
process.exit(1);
|
|
95
|
+
}
|
package/scripts/slop-rules.mjs
CHANGED
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
* `test` is per-line, so a caller splits source on newlines and applies it.
|
|
25
25
|
*/
|
|
26
26
|
// Decorative-emoji set (BADS-SLOP-5). Lives here because only the rules use it.
|
|
27
|
-
const SLOP_EMOJI = /[\u{1F680}\u{2728}\u{26A1}\u{1F389}\u{1F525}\u{1F4A1}\u{1F3AF}\u{1F31F}\u{1F6A8}\u{1F4AA}\u{1F44B}\u{1F984}\u{1F4A5}\u{1F60D}]/u;
|
|
27
|
+
export const SLOP_EMOJI = /[\u{1F680}\u{2728}\u{26A1}\u{1F389}\u{1F525}\u{1F4A1}\u{1F3AF}\u{1F31F}\u{1F6A8}\u{1F4AA}\u{1F44B}\u{1F984}\u{1F4A5}\u{1F60D}]/u;
|
|
28
28
|
|
|
29
29
|
export const RULES = [
|
|
30
30
|
{
|