@behavioral-agentic-design-system/core 0.40.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.
Files changed (148) hide show
  1. package/README.md +2 -0
  2. package/package.json +41 -9
  3. package/scripts/a11y-lint.cjs +66 -3
  4. package/scripts/check-spec.mjs +73 -0
  5. package/scripts/deal-directions.mjs +186 -0
  6. package/scripts/health-report.mjs +23 -3
  7. package/scripts/lib/counted-lint.mjs +100 -0
  8. package/scripts/lib/marketing-library.mjs +129 -0
  9. package/scripts/lib/on-system.mjs +249 -0
  10. package/scripts/lib/random.mjs +22 -0
  11. package/scripts/lib/spec-parse.d.mts +25 -0
  12. package/scripts/lib/spec-parse.mjs +188 -0
  13. package/scripts/lib/tells.mjs +128 -0
  14. package/scripts/lint-css-vars.mjs +175 -0
  15. package/scripts/lint-html-nesting.mjs +116 -0
  16. package/scripts/lint-live-ctas.mjs +138 -0
  17. package/scripts/lint-slop.mjs +25 -1
  18. package/scripts/on-system-score.mjs +95 -0
  19. package/scripts/slop-rules.mjs +1 -1
  20. package/scripts/source-images.mjs +180 -0
  21. package/scripts/ux-tells.mjs +78 -0
  22. package/scripts/wcag-audit.cjs +72 -5
  23. package/src/api/brand-colors.ts +3 -0
  24. package/src/api/brand-fonts.ts +3 -0
  25. package/src/api/brand-mark.ts +6 -1
  26. package/src/api/dev-write-guard.ts +53 -0
  27. package/src/api/layers/file.ts +7 -4
  28. package/src/api/onboarding-extract.ts +85 -30
  29. package/src/api/onboarding.ts +3 -0
  30. package/src/api/save-tokens.ts +3 -0
  31. package/src/app/layout.tsx +6 -0
  32. package/src/app/opengraph-image.tsx +5 -0
  33. package/src/app/preview/canvas/page.tsx +12 -0
  34. package/src/app/preview/components/page.tsx +2003 -2
  35. package/src/app/preview/studio/blank-screen.tsx +143 -0
  36. package/src/app/preview/studio/page.tsx +7 -0
  37. package/src/app/shell.tsx +168 -49
  38. package/src/components/Foundations/Motion.stories.tsx +1 -0
  39. package/src/components/canvas/canvas.tsx +458 -0
  40. package/src/components/canvas/layout.ts +72 -0
  41. package/src/components/canvas/parse-canvas.ts +32 -0
  42. package/src/components/canvas/sample.ts +90 -0
  43. package/src/components/canvas/spec-frame.tsx +43 -0
  44. package/src/components/canvas/types.ts +33 -0
  45. package/src/components/customize/design-controls.tsx +16 -1
  46. package/src/components/docs-tab.tsx +7 -7
  47. package/src/components/home-recent.tsx +73 -0
  48. package/src/components/home-tab.tsx +13 -13
  49. package/src/components/layers-tab.tsx +2 -2
  50. package/src/components/markdown-preview.tsx +60 -12
  51. package/src/components/studio/control-panel.tsx +299 -0
  52. package/src/components/studio/control-row.tsx +77 -0
  53. package/src/components/studio/preview-frame.tsx +165 -0
  54. package/src/components/studio/preview-pane.tsx +247 -0
  55. package/src/components/studio/studio.tsx +158 -0
  56. package/src/components/studio/types.ts +218 -0
  57. package/src/components/studio/use-studio-tweaks.ts +128 -0
  58. package/src/components/studio/use-studio-view-state.ts +72 -0
  59. package/src/components/ui/anchor.tsx +37 -3
  60. package/src/components/ui/attachment.tsx +211 -0
  61. package/src/components/ui/autocomplete.tsx +1 -1
  62. package/src/components/ui/chart.tsx +3 -0
  63. package/src/components/ui/code.tsx +1 -1
  64. package/src/components/ui/color-picker.tsx +21 -5
  65. package/src/components/ui/data-table.tsx +64 -3
  66. package/src/components/ui/date-field.tsx +1 -1
  67. package/src/components/ui/editable.tsx +1 -0
  68. package/src/components/ui/faceted-filter.tsx +187 -0
  69. package/src/components/ui/gauge-chart.tsx +252 -0
  70. package/src/components/ui/heatmap.tsx +256 -0
  71. package/src/components/ui/index.ts +9 -0
  72. package/src/components/ui/infinite-scroll.tsx +103 -0
  73. package/src/components/ui/inline-edit.tsx +175 -0
  74. package/src/components/ui/json-input.tsx +351 -0
  75. package/src/components/ui/month-picker.tsx +1 -1
  76. package/src/components/ui/navigation-progress.tsx +281 -0
  77. package/src/components/ui/number-input.tsx +27 -7
  78. package/src/components/ui/otp-input.tsx +208 -0
  79. package/src/components/ui/password-input.tsx +2 -1
  80. package/src/components/ui/password-strength-input.tsx +288 -0
  81. package/src/components/ui/phone-input.tsx +274 -0
  82. package/src/components/ui/pill.tsx +140 -0
  83. package/src/components/ui/popover.tsx +27 -4
  84. package/src/components/ui/scroll-progress.tsx +100 -0
  85. package/src/components/ui/search-input.tsx +1 -1
  86. package/src/components/ui/snackbar.tsx +393 -0
  87. package/src/components/ui/sortable-list.tsx +342 -0
  88. package/src/components/ui/squircle.tsx +1 -1
  89. package/src/components/ui/table.tsx +1 -1
  90. package/src/components/ui/tags-input.tsx +1 -1
  91. package/src/components/ui/timer.tsx +1 -0
  92. package/src/components/ui/tour.tsx +1 -3
  93. package/src/components/ui/transfer-list.tsx +13 -26
  94. package/src/components/ui/week-picker.tsx +1 -1
  95. package/src/components/ui/year-picker.tsx +1 -1
  96. package/src/data/component-added.json +958 -0
  97. package/src/data/docs-index.ts +36 -0
  98. package/src/hooks/use-global-mono-font.ts +1 -0
  99. package/src/hooks/use-global-primary-color.ts +1 -0
  100. package/src/hooks/use-global-sans-font.ts +1 -0
  101. package/src/hooks/use-global-serif-font.ts +1 -0
  102. package/src/hooks/use-global-type-scale.ts +17 -2
  103. package/src/hooks/use-mobile.ts +2 -0
  104. package/src/hooks/use-sync-type-scale.ts +7 -11
  105. package/src/lib/clamp.ts +2 -0
  106. package/src/lib/spec-parse.ts +4 -0
  107. package/src/lib/svg-sanitize.ts +19 -9
  108. package/src/stories/Anchor.stories.tsx +54 -0
  109. package/src/stories/Attachment.stories.tsx +189 -0
  110. package/src/stories/Autocomplete.stories.tsx +2 -0
  111. package/src/stories/Canvas.stories.tsx +45 -0
  112. package/src/stories/Chart.stories.tsx +4 -0
  113. package/src/stories/Code.stories.tsx +1 -0
  114. package/src/stories/ColorPicker.stories.tsx +41 -0
  115. package/src/stories/DataTable.stories.tsx +30 -0
  116. package/src/stories/DateField.stories.tsx +21 -0
  117. package/src/stories/Editable.stories.tsx +2 -0
  118. package/src/stories/FacetedFilter.stories.tsx +197 -0
  119. package/src/stories/GaugeChart.stories.tsx +169 -0
  120. package/src/stories/Heatmap.stories.tsx +172 -0
  121. package/src/stories/InfiniteScroll.stories.tsx +225 -0
  122. package/src/stories/InlineEdit.stories.tsx +106 -0
  123. package/src/stories/JsonInput.stories.tsx +212 -0
  124. package/src/stories/MarkdownPreview.stories.tsx +53 -0
  125. package/src/stories/MonthPicker.stories.tsx +21 -0
  126. package/src/stories/NavigationProgress.stories.tsx +159 -0
  127. package/src/stories/NumberInput.stories.tsx +26 -0
  128. package/src/stories/OtpInput.stories.tsx +110 -0
  129. package/src/stories/PasswordInput.stories.tsx +4 -0
  130. package/src/stories/PasswordStrengthInput.stories.tsx +211 -0
  131. package/src/stories/PhoneInput.stories.tsx +127 -0
  132. package/src/stories/Pill.stories.tsx +201 -0
  133. package/src/stories/Popover.stories.tsx +29 -1
  134. package/src/stories/Portal.stories.tsx +3 -1
  135. package/src/stories/ScrollProgress.stories.tsx +117 -0
  136. package/src/stories/SearchInput.stories.tsx +2 -0
  137. package/src/stories/Snackbar.stories.tsx +315 -0
  138. package/src/stories/SortableList.stories.tsx +263 -0
  139. package/src/stories/Squircle.stories.tsx +1 -0
  140. package/src/stories/Table.stories.tsx +1 -0
  141. package/src/stories/TagsInput.stories.tsx +2 -0
  142. package/src/stories/Timer.stories.tsx +26 -0
  143. package/src/stories/Tour.stories.tsx +1 -0
  144. package/src/stories/TransferList.stories.tsx +4 -0
  145. package/src/stories/WeekPicker.stories.tsx +21 -0
  146. package/src/stories/YearPicker.stories.tsx +21 -0
  147. package/src/stories/story-groups.json +33 -16
  148. package/src/tokens.json +82 -54
@@ -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
+ }
@@ -68,6 +68,7 @@
68
68
  * pnpm lint:slop # report, exit 1 on any finding
69
69
  * pnpm lint:slop:warn # report, exit 0 (advisory; used in the a11y umbrella)
70
70
  * node packages/core/scripts/lint-slop.mjs path/to.tsx # scan a specific file
71
+ * node packages/core/scripts/lint-slop.mjs path/to/dir # scan every file under a directory
71
72
  */
72
73
 
73
74
  import fs from "node:fs";
@@ -91,10 +92,20 @@ const advisory = process.argv.includes("--warn");
91
92
  // a11y-lint.cjs, size-audit.cjs, a11y-ratchet.mjs and lint-token-intent.mjs
92
93
  // used to each keep a drifted copy of the same root list. Set
93
94
  // BADS_LINT_ROOTS to point this at a non-standard tree.
95
+ //
96
+ // allowDirArgs: without this, a directory positional argument fell into
97
+ // resolveScanFiles' "explicit path" branch, went straight to fs.readFileSync,
98
+ // threw EISDIR, and the per-file try/catch below silently swallowed it —
99
+ // `node lint-slop.mjs <directory>` reported clean having read zero files.
100
+ // Same bug, same fix, as a11y-lint.cjs (found 2026-09-15 from a real consumer
101
+ // fork run scanning a11y-lint specifically; lint-slop shared the identical
102
+ // scan-roots call shape so it carried the same gap even though nobody had
103
+ // hit it yet).
94
104
  const scan = resolveScanFiles({
95
105
  root: ROOT,
96
106
  argv: process.argv.slice(2),
97
107
  excludeStories: true,
108
+ allowDirArgs: true,
98
109
  });
99
110
 
100
111
  function fileList() {
@@ -102,12 +113,14 @@ function fileList() {
102
113
  }
103
114
 
104
115
  const findings = [];
116
+ const unreadableExplicitPaths = [];
105
117
 
106
118
  for (const file of fileList()) {
107
119
  let src;
108
120
  try {
109
121
  src = fs.readFileSync(file, "utf8");
110
- } catch {
122
+ } catch (err) {
123
+ if (scan.mode === "explicit") unreadableExplicitPaths.push({ file, message: err.message });
111
124
  continue;
112
125
  }
113
126
  const lines = src.split("\n");
@@ -171,6 +184,17 @@ for (const file of fileList()) {
171
184
  }
172
185
  }
173
186
 
187
+ if (unreadableExplicitPaths.length) {
188
+ console.error(
189
+ `lint-slop: ${unreadableExplicitPaths.length} path argument${unreadableExplicitPaths.length === 1 ? "" : "s"} ` +
190
+ `could not be read — nothing under ${unreadableExplicitPaths.length === 1 ? "it was" : "them was"} scanned:\n\n` +
191
+ unreadableExplicitPaths.map((p) => ` ${p.file} — ${p.message}`).join("\n") +
192
+ `\n\nA directory argument is walked automatically now — this means the path doesn't exist, ` +
193
+ `isn't readable, or is neither a file nor a directory.`
194
+ );
195
+ process.exit(1);
196
+ }
197
+
174
198
  if (findings.length === 0) {
175
199
  if (guardEmptyScan(scan, "lint-slop")) { /* exited */ }
176
200
  console.log(
@@ -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
+ }
@@ -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
  {
@@ -0,0 +1,180 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * source-images — find real, openly licensed pictures of a client's world and
4
+ * record the credit that has to appear on the page.
5
+ *
6
+ * Why: the anti-defaults say stock or abstract imagery standing in for the
7
+ * product is placeholder content, but until now BADS had no way to find the
8
+ * real thing. A marketing page for a harbor cafe is better with the harbor than
9
+ * with a gradient. The approach, searching open archives with the credit kept
10
+ * beside the file, is from Leonxlnx/taste-skill (MIT). This is a separate,
11
+ * smaller implementation: three key-free sources, an explicit license allowlist,
12
+ * and a credits file that can't be skipped.
13
+ *
14
+ * Sources (no API keys):
15
+ * openverse api.openverse.org CC-licensed photographs
16
+ * met Metropolitan Museum Open Access, public domain only
17
+ * commons Wikimedia Commons license read from each file's metadata
18
+ *
19
+ * Licenses allowed by default: CC0, public domain, CC BY.
20
+ * --allow-sa also allows CC BY-SA. Its share-alike term applies to adaptations
21
+ * of the picture, so confirm with the client before using it.
22
+ * Never allowed: NonCommercial, NoDerivatives, or a license it can't identify.
23
+ *
24
+ * Usage (from the project root):
25
+ * bads-source-images --query "cork harbour ferry" search, print candidates
26
+ * bads-source-images --query "cork harbour ferry" --download also save them
27
+ * options: --source openverse,met,commons --count 6 --out public/images/sourced --allow-sa
28
+ *
29
+ * A downloaded picture is only usable with its credit. credits.json in the output
30
+ * folder holds it; put the attribution on the page near the image, and write real
31
+ * alt text. Check each picture yourself: an open license says nothing about who
32
+ * is in it or whether the scene is right for the client.
33
+ *
34
+ * Network: this needs internet. The hosts above must be reachable.
35
+ */
36
+ import fs from "node:fs";
37
+ import path from "node:path";
38
+ import { fileURLToPath } from "node:url";
39
+
40
+ export const SOURCES = ["openverse", "met", "commons"];
41
+ export const MAX_BYTES = 15 * 1024 * 1024;
42
+ export const IMAGE_TYPES = { "image/jpeg": "jpg", "image/png": "png", "image/webp": "webp" };
43
+ const UA = "bads-source-images/1.0 (design-system tooling; contact: see the project's repository)";
44
+
45
+ /** Classify a license string from any source into one code. */
46
+ export function licenseCode(raw) {
47
+ const s = String(raw || "").toLowerCase().replace(/[_\s]+/g, "-");
48
+ if (!s) return "unknown";
49
+ if (/(^|-)nc(-|$)|noncommercial/.test(s)) return "nc";
50
+ if (/(^|-)nd(-|$)|noderiv/.test(s)) return "nd";
51
+ if (/cc0|cc-zero|zero|publicdomain\/zero/.test(s)) return "cc0";
52
+ if (/(^|-)pdm(-|$)|public-?domain/.test(s)) return "pdm";
53
+ if (/by-sa|sharealike/.test(s)) return "by-sa";
54
+ if (/(^|-)by(-|$)|attribution/.test(s)) return "by";
55
+ return "unknown";
56
+ }
57
+
58
+ export function isAllowed(code, { allowSa = false } = {}) {
59
+ return ["cc0", "pdm", "by"].includes(code) || (allowSa && code === "by-sa");
60
+ }
61
+
62
+ const stripHtml = (s) => String(s || "").replace(/<[^>]*>/g, "").replace(/&amp;/g, "&").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/\s+/g, " ").trim();
63
+ export const slugify = (s) => String(s || "image").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 60) || "image";
64
+
65
+ /** The credit line a page should show next to the picture. */
66
+ export function attributionLine(c) {
67
+ if (c.license === "cc0" || c.license === "pdm") return `${c.title}${c.creator ? ` by ${c.creator}` : ""} (${c.sourceName}, public domain)`;
68
+ const lic = { by: "CC BY", "by-sa": "CC BY-SA" }[c.license] || c.license;
69
+ return `"${c.title}"${c.creator ? ` by ${c.creator}` : ""}, ${lic}${c.licenseUrl ? ` (${c.licenseUrl})` : ""}, via ${c.sourceName}`;
70
+ }
71
+
72
+ async function getJson(fetchFn, url) {
73
+ const res = await fetchFn(url, { headers: { "User-Agent": UA, Accept: "application/json" } });
74
+ if (!res.ok) throw new Error(`${new URL(url).host} answered ${res.status}`);
75
+ return res.json();
76
+ }
77
+
78
+ export async function searchOpenverse(q, { fetch: f = fetch, count = 6 } = {}) {
79
+ const url = `https://api.openverse.org/v1/images/?${new URLSearchParams({ q, license_type: "commercial", category: "photograph", page_size: String(Math.min(20, count * 3)) })}`;
80
+ const data = await getJson(f, url);
81
+ return (data.results || []).filter((r) => r.url).map((r) => ({
82
+ source: "openverse", sourceName: r.source || "Openverse", id: String(r.id), title: stripHtml(r.title) || "Untitled", creator: stripHtml(r.creator),
83
+ license: licenseCode(r.license), licenseUrl: r.license_url || "", landingUrl: r.foreign_landing_url || "", imageUrl: r.url, width: r.width, height: r.height,
84
+ }));
85
+ }
86
+
87
+ export async function searchMet(q, { fetch: f = fetch, count = 6 } = {}) {
88
+ const found = await getJson(f, `https://collectionapi.metmuseum.org/public/collection/v1/search?${new URLSearchParams({ q, hasImages: "true", isPublicDomain: "true" })}`);
89
+ const ids = (found.objectIDs || []).slice(0, count * 2);
90
+ const out = [];
91
+ for (const id of ids) {
92
+ try {
93
+ const o = await getJson(f, `https://collectionapi.metmuseum.org/public/collection/v1/objects/${id}`);
94
+ if (!o.isPublicDomain || !o.primaryImage) continue;
95
+ out.push({ source: "met", sourceName: "The Metropolitan Museum of Art", id: String(id), title: o.title || "Untitled", creator: o.artistDisplayName || "", license: "pdm", licenseUrl: "https://www.metmuseum.org/about-the-met/policies-and-documents/open-access", landingUrl: o.objectURL || "", imageUrl: o.primaryImage, width: undefined, height: undefined });
96
+ } catch { /* one bad object shouldn't sink the search */ }
97
+ }
98
+ return out;
99
+ }
100
+
101
+ export async function searchCommons(q, { fetch: f = fetch, count = 6 } = {}) {
102
+ const params = new URLSearchParams({ action: "query", generator: "search", gsrnamespace: "6", gsrsearch: `${q} filetype:bitmap`, gsrlimit: String(Math.min(30, count * 3)), prop: "imageinfo", iiprop: "url|extmetadata|size|mime", iiurlwidth: "1600", format: "json", origin: "*" });
103
+ const data = await getJson(f, `https://commons.wikimedia.org/w/api.php?${params}`);
104
+ return Object.values(data.query?.pages || {}).map((p) => {
105
+ const ii = p.imageinfo?.[0];
106
+ if (!ii || !(ii.mime in IMAGE_TYPES)) return null;
107
+ const m = ii.extmetadata || {};
108
+ const lic = m.LicenseShortName?.value || m.License?.value || "";
109
+ return { source: "commons", sourceName: "Wikimedia Commons", id: String(p.pageid), title: stripHtml(p.title).replace(/^File:/, "").replace(/\.[a-z]+$/i, ""), creator: stripHtml(m.Artist?.value), license: licenseCode(lic), licenseUrl: m.LicenseUrl?.value || "", landingUrl: ii.descriptionurl || "", imageUrl: ii.thumburl || ii.url, width: ii.thumbwidth || ii.width, height: ii.thumbheight || ii.height };
110
+ }).filter(Boolean);
111
+ }
112
+
113
+ const SEARCHERS = { openverse: searchOpenverse, met: searchMet, commons: searchCommons };
114
+
115
+ /** Search the chosen sources, drop anything the license rules reject, and report why. */
116
+ export async function search(q, { sources = SOURCES, count = 6, allowSa = false, fetch: f = fetch } = {}) {
117
+ const candidates = [], rejected = { license: 0 }, errors = [];
118
+ for (const s of sources) {
119
+ try {
120
+ for (const c of await SEARCHERS[s](q, { fetch: f, count })) {
121
+ if (isAllowed(c.license, { allowSa })) candidates.push(c);
122
+ else rejected.license += 1;
123
+ }
124
+ } catch (e) { errors.push(`${s}: ${e.message}`); }
125
+ }
126
+ // Spread across sources, so one source with many hits doesn't crowd out the rest.
127
+ const bySource = sources.map((s) => candidates.filter((c) => c.source === s));
128
+ const picked = [];
129
+ for (let i = 0; picked.length < count && bySource.some((l) => i < l.length); i++) for (const l of bySource) if (l[i] && picked.length < count) picked.push(l[i]);
130
+ return { candidates: picked, rejected, errors };
131
+ }
132
+
133
+ /** Save one candidate. Throws on a wrong type or an oversize file, and never leaves a partial file. */
134
+ export async function download(c, dir, { fetch: f = fetch } = {}) {
135
+ const res = await f(c.imageUrl, { headers: { "User-Agent": UA } });
136
+ if (!res.ok) throw new Error(`download answered ${res.status}`);
137
+ const type = (res.headers.get("content-type") || "").split(";")[0].trim().toLowerCase();
138
+ if (!(type in IMAGE_TYPES)) throw new Error(`unexpected type "${type}", only jpeg, png and webp are saved`);
139
+ const buf = Buffer.from(await res.arrayBuffer());
140
+ if (buf.length > MAX_BYTES) throw new Error(`${(buf.length / 1048576).toFixed(1)} MB is over the ${MAX_BYTES / 1048576} MB limit`);
141
+ fs.mkdirSync(dir, { recursive: true });
142
+ const file = path.join(dir, `${c.source}-${slugify(c.title)}-${slugify(c.id).slice(0, 12)}.${IMAGE_TYPES[type]}`);
143
+ fs.writeFileSync(file, buf);
144
+ return file;
145
+ }
146
+
147
+ /** Add an entry to credits.json, replacing one for the same file. */
148
+ export function recordCredit(dir, c, file, now = new Date()) {
149
+ const p = path.join(dir, "credits.json");
150
+ const all = fs.existsSync(p) ? JSON.parse(fs.readFileSync(p, "utf8")) : [];
151
+ const entry = { file: path.basename(file), title: c.title, creator: c.creator, license: c.license, licenseUrl: c.licenseUrl, source: c.sourceName, landingUrl: c.landingUrl, attribution: attributionLine(c), retrievedAt: now.toISOString().slice(0, 10) };
152
+ fs.writeFileSync(p, JSON.stringify([...all.filter((e) => e.file !== entry.file), entry], null, 2) + "\n");
153
+ return entry;
154
+ }
155
+
156
+ async function main(argv) {
157
+ const arg = (n, d) => { const i = argv.indexOf(n); return i >= 0 ? argv[i + 1] : d; };
158
+ const q = arg("--query");
159
+ if (!q) { console.error('usage: bads-source-images --query "..." [--download] [--source openverse,met,commons] [--count 6] [--out public/images/sourced] [--allow-sa]'); return 2; }
160
+ const sources = arg("--source", SOURCES.join(",")).split(",").map((s) => s.trim()).filter(Boolean);
161
+ const bad = sources.filter((s) => !SOURCES.includes(s));
162
+ if (bad.length) { console.error(`unknown source: ${bad.join(", ")}. Use ${SOURCES.join(", ")}.`); return 2; }
163
+ const count = Number(arg("--count", 6)), out = path.resolve(arg("--out", "public/images/sourced")), allowSa = argv.includes("--allow-sa");
164
+ const { candidates, rejected, errors } = await search(q, { sources, count, allowSa });
165
+ for (const e of errors) console.error(` ! ${e}`);
166
+ if (!candidates.length) { console.log(`No usable pictures for "${q}".${rejected.license ? ` ${rejected.license} found with a license that isn't allowed.` : ""}${errors.length ? " Some sources failed (above)." : ""}`); return errors.length === sources.length ? 1 : 0; }
167
+ console.log(`${candidates.length} candidate${candidates.length === 1 ? "" : "s"} for "${q}" (${rejected.license} skipped for license):\n`);
168
+ for (const [i, c] of candidates.entries()) {
169
+ console.log(`${i + 1}. ${c.title}${c.creator ? ` — ${c.creator}` : ""}\n ${c.sourceName} · ${c.license.toUpperCase()}${c.width ? ` · ${c.width}×${c.height}` : ""}\n ${c.landingUrl || c.imageUrl}`);
170
+ if (argv.includes("--download")) {
171
+ try { const file = await download(c, out); recordCredit(out, c, file); console.log(` saved ${path.relative(process.cwd(), file)}`); } catch (e) { console.log(` not saved: ${e.message}`); }
172
+ }
173
+ }
174
+ console.log(argv.includes("--download")
175
+ ? `\nCredits are in ${path.relative(process.cwd(), path.join(out, "credits.json"))}. Show each credit near its picture, write real alt text, and check the picture fits the client.`
176
+ : "\nNothing saved. Add --download to save these with their credits.");
177
+ return 0;
178
+ }
179
+
180
+ if (process.argv[1] && fileURLToPath(import.meta.url) === path.resolve(process.argv[1])) process.exit(await main(process.argv.slice(2)));
@@ -0,0 +1,78 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * ux-tells — open a page in a real browser at three widths and fail it on the
4
+ * signals that make a page read as generated: gradient text, indigo gradients,
5
+ * stacks of glass panels, glows, the stock three-icon-card row, a pill above the
6
+ * headline, decorative emoji, pulsing dots, placeholder copy and images, and
7
+ * sideways scrolling. It saves a screenshot of each width so someone can look.
8
+ *
9
+ * It reads computed styles, so it catches what lint-slop's source scan can't:
10
+ * classes built at runtime and the effect of the cascade. It runs on any URL, so
11
+ * a client's marketing page, a preview route, or a deployed site all work.
12
+ * Reduced motion is emulated, so a reading doesn't depend on an animation frame.
13
+ *
14
+ * Usage:
15
+ * bads-ux-tells <url> [--widths 375,768,1280] [--out .ux-tells] [--json] [--warn]
16
+ *
17
+ * Exit 1 when any banned tell is found (0 with --warn). Warned tells are listed
18
+ * and need a reason, not a fix. Rules and rationale: lib/tells.mjs.
19
+ *
20
+ * Needs Playwright and a Chromium: `pnpm install` in the repo, or set PW_CHROMIUM.
21
+ */
22
+ import fs from "node:fs";
23
+ import path from "node:path";
24
+ import { fileURLToPath } from "node:url";
25
+ import { WIDTHS, TELLS, probeSource, classify, merge } from "./lib/tells.mjs";
26
+
27
+ function chromiumExecutable() {
28
+ if (process.env.PW_CHROMIUM && fs.existsSync(process.env.PW_CHROMIUM)) return process.env.PW_CHROMIUM;
29
+ for (const c of ["/opt/pw-browsers/chromium-1194/chrome-linux/chrome", "/opt/pw-browsers/chromium/chrome-linux/chrome"]) if (fs.existsSync(c)) return c;
30
+ return undefined;
31
+ }
32
+
33
+ /** Check one URL at each width. Returns { findings, screenshots }. */
34
+ export async function check(url, { widths = WIDTHS, out = ".ux-tells", chromium } = {}) {
35
+ if (!chromium) ({ chromium } = await import("playwright"));
36
+ fs.mkdirSync(out, { recursive: true });
37
+ const exe = chromiumExecutable();
38
+ const browser = await chromium.launch(exe ? { executablePath: exe } : {});
39
+ const perWidth = [], screenshots = [];
40
+ try {
41
+ for (const width of widths) {
42
+ const ctx = await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce", deviceScaleFactor: 1 });
43
+ const page = await ctx.newPage();
44
+ const res = await page.goto(url, { waitUntil: "networkidle", timeout: 60000 }).catch(() => null);
45
+ if (!res || !res.ok()) { await ctx.close(); throw new Error(`could not load ${url} at ${width}px`); }
46
+ await page.evaluate(() => document.fonts && document.fonts.ready);
47
+ perWidth.push(classify(await page.evaluate(probeSource()), width));
48
+ for (const [kind, full] of [["fold", false], ["page", true]]) {
49
+ const file = path.join(out, `${width}-${kind}.jpg`);
50
+ await page.screenshot({ path: file, fullPage: full, type: "jpeg", quality: 80 });
51
+ screenshots.push(file);
52
+ }
53
+ await ctx.close();
54
+ }
55
+ } finally { await browser.close(); }
56
+ return { findings: merge(perWidth), screenshots };
57
+ }
58
+
59
+ async function main(argv) {
60
+ const url = argv.find((a) => /^https?:\/\/|^file:\/\//.test(a));
61
+ if (!url) { console.error("usage: bads-ux-tells <url> [--widths 375,768,1280] [--out .ux-tells] [--json] [--warn]"); return 2; }
62
+ const arg = (n, d) => { const i = argv.indexOf(n); return i >= 0 ? argv[i + 1] : d; };
63
+ const widths = arg("--widths", WIDTHS.join(",")).split(",").map(Number).filter((n) => n >= 280 && n <= 3000);
64
+ let result;
65
+ try { result = await check(url, { widths, out: arg("--out", ".ux-tells") }); } catch (e) { console.error(`ux-tells: ${e.message}`); return 2; }
66
+ const banned = result.findings.filter((f) => f.status === "banned"), warned = result.findings.filter((f) => f.status === "warned");
67
+ if (argv.includes("--json")) console.log(JSON.stringify(result, null, 2));
68
+ else {
69
+ console.log(`ux-tells ${url} (${widths.join(", ")}px)`);
70
+ for (const f of [...banned, ...warned]) console.log(` ${f.status === "banned" ? "✗ banned" : "⚠ warned"} ${f.name} [${f.code}] at ${f.widths.join("/")}px: ${f.detail}\n ${f.why}`);
71
+ console.log(banned.length || warned.length ? "" : " No tells found.");
72
+ console.log(`${banned.length} banned, ${warned.length} warned. ${TELLS.length} rules. Screenshots: ${path.dirname(result.screenshots[0])}`);
73
+ console.log("Look at the screenshots too. This finds the objective tells, and says nothing about whether the page is any good.");
74
+ }
75
+ return banned.length && !argv.includes("--warn") ? 1 : 0;
76
+ }
77
+
78
+ if (process.argv[1] && fileURLToPath(import.meta.url) === path.resolve(process.argv[1])) process.exit(await main(process.argv.slice(2)));