@actioneer/ads-lint 1.0.62 → 1.0.64

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/README.md CHANGED
@@ -46,7 +46,9 @@ error (`versionCheck: false` in the config turns this off for a deliberate pin).
46
46
  | `empty-state-table-header` — an `EmptyState` inside a `Table`, `TableBody` or `TableCell`: with nothing to list the table is not drawn (`emptyStates.tableAllow` exempts the library) | error | P8, empty states |
47
47
  | `shadow-static-surface` — `shadow-card` on a `div`/`section`/`Card` nobody can press (no `onClick`, `href`, `isPressable`, `role="button"`) | error | elevation |
48
48
  | `selected-edge-action` — a strong `border`/`ring`/`outline` on a selection prefix (`aria-selected:`, `data-[state=on]:` …) or in a `selected ? "…"` / `isActive && "…"` class | error | selection |
49
+ | `insight-findings-hand-rolled` (a "What changed" heading without `InsightFindings`), `insight-finding-action` (a button or link inside `InsightFindings`), `monitor-outcome-grid` ("Outcome distribution", an outcomes-by-day table) | error | charts, P15 Program dashboard |
49
50
  | `chart-dual-axis` (any `dualAxis` but `{false}`), `export-button-no-icon` (`Export`, `{"Export"}`, `{t("export")}`, "Download CSV"), `empty-state-no-description` (missing or empty) | error | charts, P8 |
51
+ | Screen kinds: every rule of the declared kind (`screen-collection-…`, `screen-monitor-…` — order, required parts, forbidden parts, one hero, charts in `ChartCard`), `screen-kind-unknown`, and `screen-kind-missing` (warn: a `BodyPageHeader` screen with a `Table`, `StatStrip` or `ChartCard` that never declares its kind). The rules are generated from `@actioneer/ads`'s `SCREEN_KINDS`, the same rules `AdsScreen` checks at runtime | error / warn | P16, screen kinds |
50
52
 
51
53
  Errors fail the run (exit 1); warnings don't unless `--strict`.
52
54
 
@@ -71,6 +73,19 @@ export default {
71
73
  };
72
74
  ```
73
75
 
76
+ Screens that do not wrap themselves in `<AdsScreen kind>` can be given a kind
77
+ by path — the whole file is then checked as that kind:
78
+
79
+ ```js
80
+ export default {
81
+ imports: { libraryPackage: "@actioneer/ads" },
82
+ screens: {
83
+ "src/app/segments/**": "collection",
84
+ "src/app/journeys/[id]/monitor/**": "monitor",
85
+ },
86
+ };
87
+ ```
88
+
74
89
  The ADS library repo itself runs in **library-dev mode** (see this repo's
75
90
  `ads-lint.config.mjs`): `libraryRoot: "src/components"` exempts the library's own
76
91
  internals, and `libraryPackage: "@/components"` matches the local alias. Its
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@actioneer/ads-lint",
3
- "version": "1.0.62",
3
+ "version": "1.0.64",
4
4
  "description": "Design linter for the Actioneer Design System (ADS 1.0). Ships in lockstep with @actioneer/ads: install the same version. Flags deviations from ADS principles on changed files.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/config.mjs CHANGED
@@ -26,6 +26,11 @@ export const DEFAULT_CONFIG = {
26
26
  // linter (they ship in lockstep). false only for a deliberate pin.
27
27
  versionCheck: true,
28
28
 
29
+ // Screen kinds by file, for screens that do not wrap themselves in
30
+ // <AdsScreen kind>: { "src/app/segments/**": "collection" }. The kinds and
31
+ // their rules come from @actioneer/ads (src/lib/screen-grammar.ts).
32
+ screens: {},
33
+
29
34
  // Root walked by `--all` when no explicit files are passed.
30
35
  root: "src",
31
36
 
package/src/index.mjs CHANGED
@@ -17,3 +17,5 @@ export { lintElevation, ELEVATION_RULES } from "./rules/elevation.mjs";
17
17
  export { lintControls, CONTROL_RULES } from "./rules/controls.mjs";
18
18
  export { staleLinterFinding, compareVersions, VERSION_RULE } from "./version-check.mjs";
19
19
  export { lintRecipes, RECIPE_RULES } from "./rules/recipes.mjs";
20
+ export { lintScreens, SCREEN_RULES } from "./rules/screens.mjs";
21
+ export { SCREEN_KINDS, validateScreen } from "./screen-grammar.gen.mjs";
@@ -15,6 +15,24 @@ export const CHART_RULES = [
15
15
  guidance:
16
16
  "One axis per chart. Put the second measure in its own chart over the same categories (e.g. Calls per day + Answer rate), or stack the parts so the ratio reads from the bars — never ComboChart dualAxis.",
17
17
  },
18
+ {
19
+ name: "insight-findings-hand-rolled",
20
+ severity: "error",
21
+ guidance:
22
+ "\"What changed\" on a monitor is the ADS InsightFindings card: <InsightFindings> with up to three <InsightFinding icon title detail /> rows (user-mandated 2026-11-30). Never a hand-built list of findings — it drifts from the rule, e.g. keeps a \"View … →\" action at each row's end.",
23
+ },
24
+ {
25
+ name: "insight-finding-action",
26
+ severity: "error",
27
+ guidance:
28
+ "A finding has no action (user-mandated 2026-11-30: \"remove these actions\"): no button or link (\"View answer trend →\") inside InsightFindings. The numbers it talks about are already on the page.",
29
+ },
30
+ {
31
+ name: "monitor-outcome-grid",
32
+ severity: "error",
33
+ guidance:
34
+ "Voice insights has no outcome-by-day grid or \"Outcome distribution\" section (user-mandated 2026-11-30: removed). The funnel and the What changed findings already carry the outcomes; delete the section.",
35
+ },
18
36
  ];
19
37
 
20
38
  const RULE = Object.fromEntries(CHART_RULES.map((r) => [r.name, r]));
@@ -39,5 +57,30 @@ export function lintCharts(relPath, source, cfg) {
39
57
  guidance: RULE["chart-dual-axis"].guidance,
40
58
  });
41
59
  }
60
+ const push = (rule, index, match) =>
61
+ findings.push({
62
+ line: source.slice(0, index).split("\n").length,
63
+ rule,
64
+ severity: RULE[rule].severity,
65
+ match: match.length > 80 ? `${match.slice(0, 77)}...` : match,
66
+ guidance: RULE[rule].guidance,
67
+ });
68
+
69
+ // A "What changed" heading built by hand instead of InsightFindings.
70
+ if (!/<InsightFindings\b/.test(source)) {
71
+ const m = /<(h[1-6]|p|span|div)\b[^<>]*>\s*What changed\s*</.exec(source);
72
+ if (m) push("insight-findings-hand-rolled", m.index, m[0].replace(/\s+/g, " "));
73
+ }
74
+ // A control inside the findings card.
75
+ for (const block of source.matchAll(/<InsightFindings\b[\s\S]*?<\/InsightFindings>/g)) {
76
+ const m = /<(Button|Link|a|TooltipIconButton)\b/.exec(block[0]);
77
+ if (m) push("insight-finding-action", block.index + m.index, openingTag(block[0], m.index).replace(/\s+/g, " "));
78
+ }
79
+ // The removed outcome-by-day section.
80
+ const grid =
81
+ /<(h[1-6]|p|span|div)\b[^<>]*>\s*Outcome distribution\s*</.exec(source) ??
82
+ /aria-label=["'{`]*(?:Call )?outcomes? (?:by|per) (?:day|period|date)/i.exec(source);
83
+ if (grid) push("monitor-outcome-grid", grid.index, grid[0].replace(/\s+/g, " "));
84
+
42
85
  return findings;
43
86
  }
@@ -27,19 +27,19 @@ export const RECIPE_RULES = [
27
27
  name: "call-panel-hand-rolled",
28
28
  severity: "error",
29
29
  guidance:
30
- "A call's review panel is the ADS CallPanel — map the call onto a CallPanelCall and render <CallPanel call={…} onClose={…} />. Pass `loading={{ number, pickedUp }}` while the details are fetched. Never rebuild it from Drawer, DrawerSection, Transcript and AudioWaveform.",
30
+ "A call's review panel is the ADS CallPanel — map the call onto a CallPanelCall and render <CallPanel call={…} onClose={…} />. Pass `loading={{ number, pickedUp }}` while the details are fetched. Inside your own Drawer (one that also shows other views), use <CallPanelContent call={…} /> — the same panel without a second Drawer. Never rebuild it from Drawer, DrawerSection, Transcript and AudioWaveform.",
31
31
  },
32
32
  {
33
33
  name: "filter-menu-hand-rolled",
34
34
  severity: "error",
35
35
  guidance:
36
- "A Popover of Checkboxes is a hand-made filter menu. Filter a table from its column header (TableColumn filterOptions + filterValue + onFilterChange: a multi-select \"Show only\" list with counts), or use Filters in the CollectionToolbar.",
36
+ "A Popover of Checkboxes is a hand-made filter menu. Filter a table from its column header (TableColumn filterOptions + filterValue + onFilterChange: a multi-select \"Show only\" list with counts), show what applies as TableFilterChip chips in a TableFilterChips row under the CollectionToolbar (hidden columns as TableHiddenColumnsChip), or use Filters in the CollectionToolbar.",
37
37
  },
38
38
  {
39
39
  name: "filter-chip-clear-button",
40
40
  severity: "error",
41
41
  guidance:
42
- "An applied filter is one Chip with its own ✕: pass `onClose` to the Chip instead of placing a separate clear or remove button beside it.",
42
+ "An applied table filter is a TableFilterChip in the TableFilterChips row under the toolbar — it carries its own ✕ and opens its own checklist; a hidden column is TableHiddenColumnsChip. Never a Chip with a separate clear or remove button beside it.",
43
43
  },
44
44
  {
45
45
  name: "script-character-limit",
@@ -53,6 +53,30 @@ export const RECIPE_RULES = [
53
53
  guidance:
54
54
  "The opening line is the ADS ScriptOpeningLine — editable on a draft, read-only once the campaign runs, with its word count and info icon. Never draw the \"Opening line\" label and field by hand.",
55
55
  },
56
+ {
57
+ name: "alert-hand-rolled",
58
+ severity: "error",
59
+ guidance:
60
+ "An inline warning, error, notice or success message is the ADS Alert: <Alert variant=\"warning\"><AlertTitle>…</AlertTitle><AlertDescription>…</AlertDescription><Button variant=\"outline\">…</Button></Alert> — the outlined card with the tone's soft wash, a neutral icon centred on the message and its action 16px below. Never a tinted strip (bg-warning/5, bg-danger-50) with a coloured icon.",
61
+ },
62
+ {
63
+ name: "copy-name-dialog",
64
+ severity: "error",
65
+ guidance:
66
+ "Copying a record is one click (2026-11-30): create the copy at once as a draft named \"<name> (copy)\" (the first free one), open it, and say so in a toast (\"Copied as …\"). It is renamed in place from its title (BreadcrumbTitle). Never a dialog asking for the copy's name first.",
67
+ },
68
+ {
69
+ name: "hover-dark-edge",
70
+ severity: "error",
71
+ guidance:
72
+ "No dark edge on hover, press, focus or open (2026-11-30: a near-black outline on hover read as harsh). Hover a field or card with the soft T1 wash and keep its edge, mark open or selected with the T5 edge (border-border-selected), and focus with the focus ring (ring-ring). Never border-, ring- or outline-foreground, n10–n12, t10–t12 or black in an interactive state.",
73
+ },
74
+ {
75
+ name: "field-trigger-hand-rolled",
76
+ severity: "error",
77
+ guidance:
78
+ "A field you click to pick a value (an audience, a number, an agent) is <FieldTrigger icon={…} value=\"…\" meta=\"1 user\" onClick={…} /> — the field's T4 edge, a soft teal wash on hover and the T5 edge while its picker is open. Never a ghost or outline Button given a border to look like a field: its hover is a button's, not a field's.",
79
+ },
56
80
  ];
57
81
 
58
82
  const RULE = Object.fromEntries(RECIPE_RULES.map((r) => [r.name, r]));
@@ -83,7 +107,7 @@ export function lintRecipes(relPath, source, cfg) {
83
107
  });
84
108
 
85
109
  // call-panel-hand-rolled: a Drawer that holds a Transcript or an AudioWaveform.
86
- if (/<Drawer(?![\w.])/.test(source) && /<(?:Transcript|AudioWaveform)(?![\w.])/.test(source) && !/<CallPanel(?![\w.])/.test(source)) {
110
+ if (/<Drawer(?![\w.])/.test(source) && /<(?:Transcript|AudioWaveform)(?![\w.])/.test(source) && !/<CallPanel(?:Content)?(?![\w.])/.test(source)) {
87
111
  for (const [start, end] of elements(source, "Drawer")) {
88
112
  const body = source.slice(start, end);
89
113
  const inner = /<(Transcript|AudioWaveform)(?![\w.])/.exec(body);
@@ -117,5 +141,36 @@ export function lintRecipes(relPath, source, cfg) {
117
141
  if (m) push("script-opening-line-hand-rolled", m.index, m[0]);
118
142
  }
119
143
 
144
+ // alert-hand-rolled: a status-tinted container holding a status glyph.
145
+ for (const m of source.matchAll(/<div\b[^>]*className=(?:"[^"]*|\{`[^`]*|\{cn\([^)]*)\bbg-(?:warning|danger|info|success)(?:-50|-100|\/\d+)\b/g)) {
146
+ // An icon disc (rounded-full) is an illustration, not a banner.
147
+ if (/\brounded-full\b/.test(source.slice(m.index, source.indexOf(">", m.index)))) continue;
148
+ const end = elementEnd(source, m.index, "div");
149
+ if (/<(?:Warning|WarningCircle|Info|CheckCircle|AlertTriangle|AlertCircle)\b/.test(source.slice(m.index, end)) && !/<Alert(?![\w.])/.test(source.slice(m.index, end))) {
150
+ push("alert-hand-rolled", m.index, source.slice(m.index, m.index + 70));
151
+ }
152
+ }
153
+
154
+ // copy-name-dialog: a modal or dialog titled "Copy …" / "Duplicate …".
155
+ for (const m of source.matchAll(/(?:<(?:ModalTitle|DialogTitle)\b[^>]*>\s*|\btitle=["'`{]\s*["'`]?)(?:Copy|Duplicate)\s+[A-Z]?[a-z]+/g)) {
156
+ push("copy-name-dialog", m.index, m[0]);
157
+ }
158
+
159
+ // hover-dark-edge: a dark border, ring or outline in an interactive state.
160
+ for (const m of source.matchAll(/\b(?:hover|active|focus|focus-visible|focus-within|aria-expanded|aria-selected|data-\[state=open\]|group-hover(?:\/[\w-]+)?|enabled:hover|enabled:active)(?::[\w-]+)*:(?:border|ring|outline)(?:-[trblxy])?-(?:foreground|n1[0-2]|t1[0-2]|black|on-white-primary)\b(?:\/\d+)?/g)) {
161
+ push("hover-dark-edge", m.index, m[0]);
162
+ }
163
+
164
+ // field-trigger-hand-rolled: a ghost Button drawn as a field (a full-width
165
+ // row with a chevron). An outline Button that opens a Dropdown is a menu trigger.
166
+ for (const [start, end] of elements(source, "Button")) {
167
+ const tag = source.slice(start, source.indexOf(">", start) + 1);
168
+ const open = /<Button\b(?:=>|[^<>])*?>/.exec(source.slice(start));
169
+ const head = open ? open[0] : tag;
170
+ if (!/variant=["']ghost["']/.test(head)) continue;
171
+ if (!/\bw-full\b/.test(head)) continue;
172
+ if (/<ChevronDown\b/.test(source.slice(start, end))) push("field-trigger-hand-rolled", start, head);
173
+ }
174
+
120
175
  return findings;
121
176
  }
@@ -0,0 +1,422 @@
1
+ // Screen-kind rules (user-mandated 2026-11-30: "set screen composition rules,
2
+ // and based on that they get implemented").
3
+ //
4
+ // A screen declares its kind with `<AdsScreen kind="collection">` or through
5
+ // `screens` in ads-lint.config.mjs ({ "src/app/segments/**": "collection" }).
6
+ // This reads the JSX of that screen into a tree and checks it with the SAME
7
+ // rules and checker the runtime uses (`screen-grammar.gen.mjs`, generated from
8
+ // src/lib/screen-grammar.ts). Product components the linter cannot see into
9
+ // make the screen "blind" for missing-part checks: it then reports only what
10
+ // it can prove (wrong order, forbidden parts, props).
11
+
12
+ import fs from "node:fs";
13
+ import path from "node:path";
14
+ import { matchesAny } from "../config.mjs";
15
+ import { elementEnd, openingTag } from "../jsx.mjs";
16
+ import { SCREEN_KINDS, validateScreen } from "../screen-grammar.gen.mjs";
17
+
18
+ const KIND_IDS = Object.keys(SCREEN_KINDS);
19
+
20
+ export const SCREEN_RULES = [
21
+ ...Object.values(SCREEN_KINDS).flatMap((kind) =>
22
+ kind.rules.map((rule) => ({ name: rule.id, severity: rule.severity, guidance: rule.says })),
23
+ ),
24
+ {
25
+ name: "screen-kind-unknown",
26
+ severity: "error",
27
+ guidance: `AdsScreen kind must be one of: ${KIND_IDS.join(", ")}.`,
28
+ },
29
+ {
30
+ name: "screen-kind-missing",
31
+ severity: "warn",
32
+ guidance:
33
+ "Declare the kind of this screen — wrap it in <AdsScreen kind=\"collection\"> (or \"monitor\"), or map the file in ads-lint.config.mjs `screens` — so ADS can hold it to that kind's composition rules.",
34
+ },
35
+ ];
36
+
37
+ const RULE = Object.fromEntries(SCREEN_RULES.map((r) => [r.name, r]));
38
+ const lineOf = (source, index) => source.slice(0, index).split("\n").length;
39
+
40
+ /** Local names imported from the ADS package, mapped to their exported names. */
41
+ function adsImports(source, pkg) {
42
+ const names = new Map();
43
+ const esc = pkg.replace(/[.*+?^${}()|[\]\\/@]/g, "\\$&");
44
+ const re = new RegExp(`import\\s+(?:type\\s+)?\\{([^}]*)\\}\\s*from\\s*["']${esc}["']`, "g");
45
+ for (const m of source.matchAll(re)) {
46
+ for (const part of m[1].split(",")) {
47
+ const spec = part.trim().replace(/^type\s+/, "");
48
+ if (!spec) continue;
49
+ const [exported, local] = spec.split(/\s+as\s+/).map((s) => s.trim());
50
+ names.set(local ?? exported, exported);
51
+ }
52
+ }
53
+ return names;
54
+ }
55
+
56
+ /** Attribute values of an opening tag: "literal" → string, {expr} or bare → true. */
57
+ function propsOf(tag) {
58
+ const props = {};
59
+ const body = tag.replace(/^<[\w.]*/, "").replace(/\/?>$/, "");
60
+ let i = 0;
61
+ while (i < body.length) {
62
+ const m = /^\s*([A-Za-z_][\w-]*)/.exec(body.slice(i));
63
+ if (!m) {
64
+ // skip a spread or stray character
65
+ if (body[i] === "{") {
66
+ let d = 0;
67
+ for (; i < body.length; i++) {
68
+ if (body[i] === "{") d++;
69
+ else if (body[i] === "}" && --d === 0) break;
70
+ }
71
+ }
72
+ i++;
73
+ continue;
74
+ }
75
+ const name = m[1];
76
+ i += m[0].length;
77
+ if (body[i] === "=") {
78
+ const open = body[i + 1];
79
+ if (open === '"' || open === "'") {
80
+ const close = body.indexOf(open, i + 2);
81
+ props[name] = body.slice(i + 2, close);
82
+ i = close + 1;
83
+ } else if (open === "{") {
84
+ let d = 0;
85
+ let j = i + 1;
86
+ for (; j < body.length; j++) {
87
+ if (body[j] === "{") d++;
88
+ else if (body[j] === "}" && --d === 0) break;
89
+ }
90
+ const expr = body.slice(i + 2, j).trim();
91
+ const literal = /^["'`]([^"'`$]*)["'`]$/.exec(expr);
92
+ props[name] = literal ? literal[1] : true;
93
+ i = j + 1;
94
+ } else i++;
95
+ } else props[name] = true;
96
+ }
97
+ return props;
98
+ }
99
+
100
+ /**
101
+ * JSX elements in `text` (code or a JSX body), outermost first. A `<` counts
102
+ * as JSX only when it does not follow an identifier, `)` or `]` — so
103
+ * `useState<Row[]>` and `a < b` are skipped.
104
+ */
105
+ function elementsIn(text, offset) {
106
+ const out = [];
107
+ const re = /<([A-Za-z][\w.]*)/g;
108
+ for (let m; (m = re.exec(text)); ) {
109
+ const before = text.slice(0, m.index).replace(/\s+$/, "").slice(-1);
110
+ if (/[\w.)\]]/.test(before)) continue;
111
+ const name = m[1];
112
+ const tag = openingTag(text, m.index);
113
+ const end = elementEnd(text, m.index, name);
114
+ const inner = tag.endsWith("/>") ? "" : text.slice(m.index + tag.length, Math.max(m.index + tag.length, end - name.length - 3));
115
+ out.push({ name, tag, inner, at: offset + m.index, innerAt: offset + m.index + tag.length, tagAt: offset + m.index });
116
+ re.lastIndex = Math.max(end, m.index + 1);
117
+ }
118
+ return out;
119
+ }
120
+
121
+ /* ---------- following product components into their source ---------- */
122
+
123
+ const EXTENSIONS = [".tsx", ".ts", ".jsx", ".js", "/index.tsx", "/index.ts"];
124
+ const aliasCache = new Map();
125
+
126
+ /** Path aliases: `screenAliases` in the config, else tsconfig.json `paths` ("@/*": ["./src/*"]). */
127
+ function aliasesFor(cwd, cfg) {
128
+ if (cfg.screenAliases) return cfg.screenAliases;
129
+ if (aliasCache.has(cwd)) return aliasCache.get(cwd);
130
+ const out = {};
131
+ try {
132
+ const raw = fs.readFileSync(path.join(cwd, "tsconfig.json"), "utf8").replace(/^\s*\/\/.*$/gm, "").replace(/,(\s*[}\]])/g, "$1");
133
+ const json = JSON.parse(raw);
134
+ const base = json.compilerOptions?.baseUrl ?? ".";
135
+ for (const [key, [target]] of Object.entries(json.compilerOptions?.paths ?? {})) {
136
+ out[key.replace(/\*$/, "")] = path.join(base, target.replace(/\*$/, ""));
137
+ }
138
+ } catch {
139
+ /* no tsconfig — relative imports only */
140
+ }
141
+ aliasCache.set(cwd, out);
142
+ return out;
143
+ }
144
+
145
+ /** Every import of the file: local name → { spec, name } ("default" for a default import). */
146
+ function importsOf(source) {
147
+ const map = new Map();
148
+ for (const m of source.matchAll(/import\s+(?!type\b)([\s\S]*?)\s+from\s+["']([^"']+)["']/g)) {
149
+ const [clause, spec] = [m[1], m[2]];
150
+ const def = /^([A-Za-z_$][\w$]*)/.exec(clause);
151
+ if (def && !clause.startsWith("{")) map.set(def[1], { spec, name: "default" });
152
+ const named = /\{([^}]*)\}/.exec(clause);
153
+ if (named) {
154
+ for (const part of named[1].split(",")) {
155
+ const p = part.trim().replace(/^type\s+/, "");
156
+ if (!p) continue;
157
+ const [exported, local] = p.split(/\s+as\s+/).map((x) => x.trim());
158
+ map.set(local ?? exported, { spec, name: exported });
159
+ }
160
+ }
161
+ }
162
+ return map;
163
+ }
164
+
165
+ function resolveFile(fromFile, spec, ctx) {
166
+ let base = null;
167
+ if (spec.startsWith(".")) base = path.resolve(path.dirname(fromFile), spec);
168
+ else {
169
+ const hit = Object.keys(ctx.aliases).sort((a, b) => b.length - a.length).find((a) => spec.startsWith(a));
170
+ if (hit) base = path.resolve(ctx.cwd, ctx.aliases[hit], spec.slice(hit.length));
171
+ }
172
+ if (!base) return null;
173
+ for (const ext of ["", ...EXTENSIONS]) {
174
+ const f = base + ext;
175
+ if (fs.existsSync(f) && fs.statSync(f).isFile() && /\.(tsx|jsx|ts|js)$/.test(f)) return f;
176
+ }
177
+ return null;
178
+ }
179
+
180
+ /** The source text of a component defined in `source`: from its declaration to the next top-level declaration. */
181
+ function componentBody(source, name) {
182
+ const esc = name.replace(/[$]/g, "\\$&");
183
+ const decl =
184
+ name === "default"
185
+ ? /^export\s+default\s+(?:async\s+)?function\b|^export\s+default\s+(?!function)/m
186
+ : new RegExp(`^(?:export\\s+)?(?:default\\s+)?(?:async\\s+)?(?:function\\s+${esc}\\b|(?:const|let)\\s+${esc}\\b)`, "m");
187
+ const m = decl.exec(source);
188
+ if (!m) return null;
189
+ if (name === "default" && !/function/.test(m[0])) {
190
+ // `export default Name;` → that component
191
+ const ref = /^export\s+default\s+([A-Z][\w$]*)\s*;?\s*$/m.exec(source);
192
+ return ref ? componentBody(source, ref[1]) : null;
193
+ }
194
+ const rest = source.slice(m.index + m[0].length);
195
+ const next = /\n(?=(?:export\s+|function\s|const\s|let\s|class\s|type\s|interface\s|\/\*\*|\/\/))/.exec(rest);
196
+ return { text: source.slice(m.index, m.index + m[0].length + (next ? next.index : rest.length)), at: m.index };
197
+ }
198
+
199
+ function contextFor(file, source, parent) {
200
+ return {
201
+ file,
202
+ source,
203
+ ads: adsImports(source, parent.pkg),
204
+ imports: importsOf(source),
205
+ pkg: parent.pkg,
206
+ cwd: parent.cwd,
207
+ aliases: parent.aliases,
208
+ depth: parent.depth,
209
+ seen: parent.seen,
210
+ root: parent.root ?? file,
211
+ };
212
+ }
213
+
214
+ /**
215
+ * The nodes a product component renders, read from its own source: a local
216
+ * function in the same file, or one imported through a relative path or a
217
+ * tsconfig alias. null when it cannot be found (then it stays opaque).
218
+ */
219
+ function expand(name, ctx, slot) {
220
+ if (ctx.depth > 8) return null;
221
+ let file = ctx.file;
222
+ let source = ctx.source;
223
+ let lookup = name;
224
+ const imp = ctx.imports.get(name);
225
+ if (imp) {
226
+ const target = resolveFile(ctx.file, imp.spec, ctx);
227
+ if (!target) return null;
228
+ file = target;
229
+ source = fs.readFileSync(target, "utf8");
230
+ lookup = imp.name;
231
+ }
232
+ const key = `${file}#${lookup}`;
233
+ if (ctx.seen.has(key)) return null;
234
+ const body = componentBody(source, lookup);
235
+ if (!body) {
236
+ // Re-exported from a package (an icon registry, a wrapper of a library
237
+ // component): it renders nothing the grammar tracks.
238
+ const reexport = new RegExp(`export\\s*(?:\\*|\\{[^}]*\\b${lookup}\\b[^}]*\\})\\s*from\\s*["']([^"']+)["']`).exec(source);
239
+ if (reexport && !reexport[1].startsWith(".")) return [];
240
+ if (/(?:^|\/)icons?(?:\.\w+)?$/.test(imp?.spec ?? "") || /createIcon\(/.test(source)) return [];
241
+ return null;
242
+ }
243
+ const next = contextFor(file, source, { ...ctx, depth: ctx.depth + 1, seen: new Set([...ctx.seen, key]) });
244
+ next.scope = body;
245
+ const main = mainReturn(body.text);
246
+ return buildNodes(main.text, body.at + main.at, next, slot, true);
247
+ }
248
+
249
+ /**
250
+ * The JSX a component renders in its normal state: the last top-level
251
+ * `return` of its body (earlier returns are loading, error and empty
252
+ * branches). Falls back to the whole body.
253
+ */
254
+ function mainReturn(text) {
255
+ const returns = [...text.matchAll(/\n([ \t]*)return\s*[(<]/g)];
256
+ if (!returns.length) return { text, at: 0 };
257
+ const indent = Math.min(...returns.map((m) => m[1].length));
258
+ const last = returns.filter((m) => m[1].length === indent).pop();
259
+ return { text: text.slice(last.index), at: last.index };
260
+ }
261
+
262
+ /** The JSX assigned to `const name = …` in the component's scope, or null. */
263
+ function declaredJsx(scope, name) {
264
+ if (!scope) return null;
265
+ const m = new RegExp(`\\b(?:const|let)\\s+${name.replace(/[$]/g, "\\$&")}\\s*(?::[^=]+)?=\\s*`).exec(scope.text);
266
+ if (!m) return null;
267
+ const from = m.index + m[0].length;
268
+ const rest = scope.text.slice(from);
269
+ const stop = /\n[ \t]*(?:const|let|return|if|function|for|while|switch|\/\/)\b/.exec(rest);
270
+ const text = rest.slice(0, stop ? stop.index : rest.length);
271
+ return /<[A-Z]/.test(text) ? { text, at: scope.at + from } : null;
272
+ }
273
+
274
+ /**
275
+ * A ScreenNode tree for the elements in `text`. Attribute JSX
276
+ * (actions={<Button/>}) counts as children. `slot` carries the children a
277
+ * wrapper component was given: they render where its body says `{children}`.
278
+ * `{content}` resolves to the JSX declared as `const content = …`; anything
279
+ * it cannot resolve (a prop, a render callback) leaves the screen "blind".
280
+ */
281
+ function buildNodes(text, offset, ctx, slot = null, body = false) {
282
+ const nodes = [];
283
+ const elements = elementsIn(text, offset);
284
+ const within = (at) => elements.some((el) => at > el.at && at < el.innerAt + el.inner.length);
285
+ const inJsx = (m) => /[>}]$/.test(text.slice(0, m.index).trimEnd());
286
+ const items = elements.map((el) => ({ at: el.at, el }));
287
+ if (body) {
288
+ for (const m of text.matchAll(/\{\s*((?:props\.)?[A-Za-z_$][\w$]*)\s*\}/g)) {
289
+ const at = offset + m.index;
290
+ if (!inJsx(m) || within(at)) continue;
291
+ const name = m[1].replace(/^props\./, "");
292
+ items.push({ at, name });
293
+ }
294
+ }
295
+ items.sort((a, b) => a.at - b.at);
296
+ for (const item of items) {
297
+ if (item.el) {
298
+ nodes.push(nodeFor(item.el, ctx, slot));
299
+ } else if (item.name === "children") {
300
+ if (slot && !slot.used) {
301
+ nodes.push(...slot.nodes);
302
+ slot.used = true;
303
+ }
304
+ } else {
305
+ const decl = declaredJsx(ctx.scope, item.name);
306
+ if (decl && !(ctx.resolving ?? new Set()).has(item.name)) {
307
+ const inner = { ...ctx, resolving: new Set([...(ctx.resolving ?? []), item.name]) };
308
+ nodes.push({ component: null, children: buildNodes(decl.text, decl.at, inner, slot, true) });
309
+ } else if (/^(?:content|body|view|main|panel|page|screen|list|table|rows|header|footer|section|element|node)$|^[A-Z]/.test(item.name)) {
310
+ nodes.push({ component: null, opaque: true, name: `{${item.name}}`, children: [] });
311
+ }
312
+ }
313
+ }
314
+ if (body && /\{\s*render\w*\([^)]*\)\s*\}/.test(text)) nodes.push({ component: null, opaque: true, children: [] });
315
+ return nodes;
316
+ }
317
+
318
+ function nodeFor(el, ctx, slot) {
319
+ const exported = ctx.ads.get(el.name);
320
+ const attrs = el.tag.replace(/^<[\w.]*/, "");
321
+ const line = ctx.file === ctx.root ? lineOf(ctx.source, el.at) : undefined;
322
+ const own = (pass) => [
323
+ ...buildNodes(attrs, el.tagAt + el.name.length + 1, ctx, pass),
324
+ ...buildNodes(el.inner, el.innerAt, ctx, pass, true),
325
+ ];
326
+ if (exported) return { component: exported, props: propsOf(el.tag), line, children: own(slot) };
327
+ if (/^[a-z]/.test(el.name) || el.name === "AdsScreen") return { component: null, line, children: own(slot) };
328
+ // A product component: follow it into its source, passing its children to {children}.
329
+ const imp = ctx.imports.get(el.name);
330
+ const thirdParty = imp && !imp.spec.startsWith(".") && !Object.keys(ctx.aliases).some((a) => imp.spec.startsWith(a));
331
+ if (thirdParty) return { component: null, line, children: own(slot) }; // a framework wrapper (Link, Suspense…) renders its children
332
+ if (/^(?:React\.)?Fragment$/.test(el.name)) return { component: null, line, children: own(slot) };
333
+ const given = { nodes: own(slot), used: false };
334
+ // A component held in a local variable (const Icon = item.icon): the linter
335
+ // cannot read it, but it is a leaf or a wrapper of its children, not a screen region.
336
+ if (!imp && !componentBody(ctx.source, el.name.split(".")[0]) && new RegExp(`\\b(?:const|let)\\s+(?:\\{[^}]*\\b)?${el.name.split(".")[0]}\\b|\\b${el.name.split(".")[0]}\\s*[,}:]`).test(ctx.scope?.text ?? ctx.source)) {
337
+ return { component: null, line, children: given.nodes };
338
+ }
339
+ const expanded = expand(el.name.split(".")[0], ctx, given);
340
+ if (expanded) {
341
+ if (!given.used) expanded.push(...given.nodes);
342
+ return { component: null, line, children: expanded };
343
+ }
344
+ return { component: null, opaque: true, name: el.name, line, children: given.nodes };
345
+ }
346
+
347
+ function findings(kind, root, source, match) {
348
+ if (process.env.ADS_LINT_SCREEN_TREE) {
349
+ const show = (n, d = 0) => `${" ".repeat(d)}${n.component ?? (n.opaque ? `?${n.name ?? ""}` : "·")}${n.props?.tone ? ` tone=${n.props.tone}` : ""}\n${n.children.map((c) => show(c, d + 1)).join("")}`;
350
+ process.stderr.write(`[ads-lint] ${match}\n${show(root)}`);
351
+ }
352
+ return validateScreen(kind, root, "static").map((v) => ({
353
+ rule: v.rule,
354
+ severity: v.severity,
355
+ line: v.line ?? root.line ?? 1,
356
+ match,
357
+ guidance: RULE[v.rule]?.guidance ?? v.message,
358
+ }));
359
+ }
360
+
361
+ export function lintScreens(file, source, cfg) {
362
+ if (!/\.(tsx|jsx)$/.test(file)) return [];
363
+ if (cfg.imports?.libraryRoot && file.startsWith(cfg.imports.libraryRoot)) return [];
364
+ const pkg = cfg.imports?.libraryPackage ?? "@actioneer/ads";
365
+ const ads = adsImports(source, pkg);
366
+ const cwd = cfg.cwd ?? process.cwd();
367
+ const abs = path.resolve(cwd, file);
368
+ const ctx = contextFor(abs, source, { pkg, cwd, aliases: aliasesFor(cwd, cfg), depth: 0, seen: new Set(), root: abs });
369
+ const out = [];
370
+ let declared = false;
371
+
372
+ // 1. <AdsScreen kind="…"> in the file.
373
+ const local = [...ads.entries()].find(([, exported]) => exported === "AdsScreen")?.[0] ?? "AdsScreen";
374
+ for (const m of source.matchAll(new RegExp(`<${local}(?![\\w.])`, "g"))) {
375
+ declared = true;
376
+ const tag = openingTag(source, m.index);
377
+ const kind = propsOf(tag).kind;
378
+ const line = lineOf(source, m.index);
379
+ if (typeof kind !== "string" || !KIND_IDS.includes(kind)) {
380
+ out.push({ rule: "screen-kind-unknown", severity: "error", line, match: tag.slice(0, 80), guidance: RULE["screen-kind-unknown"].guidance });
381
+ continue;
382
+ }
383
+ const end = elementEnd(source, m.index, local);
384
+ const inner = source.slice(m.index + tag.length, end - local.length - 3);
385
+ ctx.scope = { text: source, at: 0 };
386
+ const root = { component: null, line, children: buildNodes(inner, m.index + tag.length, ctx, null, true) };
387
+ out.push(...findings(kind, root, source, `<AdsScreen kind="${kind}">`));
388
+ }
389
+
390
+ // 2. A file mapped to a kind in the config: the whole file is the screen.
391
+ if (!declared) {
392
+ const mapped = Object.entries(cfg.screens ?? {}).find(([glob]) => matchesAny(file, [glob]));
393
+ if (mapped) {
394
+ declared = true;
395
+ const [, kind] = mapped;
396
+ if (!KIND_IDS.includes(kind)) {
397
+ out.push({ rule: "screen-kind-unknown", severity: "error", line: 1, match: `screens: ${kind}`, guidance: RULE["screen-kind-unknown"].guidance });
398
+ } else {
399
+ // The file's main component: its default export, else its first exported component.
400
+ const main = componentBody(source, "default") ?? (() => {
401
+ const first = /^export\s+(?:const|function)\s+([A-Z][\w$]*)/m.exec(source);
402
+ return first ? componentBody(source, first[1]) : null;
403
+ })();
404
+ let children;
405
+ if (main) {
406
+ ctx.scope = main;
407
+ const ret = mainReturn(main.text);
408
+ children = buildNodes(ret.text, main.at + ret.at, ctx, null, true);
409
+ } else children = buildNodes(source, 0, ctx);
410
+ const root = { component: null, line: 1, children };
411
+ out.push(...findings(kind, root, source, `screens → ${kind}`));
412
+ }
413
+ }
414
+ }
415
+
416
+ // 3. Looks like a screen but says nothing about its kind.
417
+ if (!declared && ads.has("BodyPageHeader") && [...ads.values()].some((n) => n === "Table" || n === "StatStrip" || n === "ChartCard")) {
418
+ const m = /<BodyPageHeader\b/.exec(source);
419
+ if (m) out.push({ rule: "screen-kind-missing", severity: "warn", line: lineOf(source, m.index), match: "<BodyPageHeader>", guidance: RULE["screen-kind-missing"].guidance });
420
+ }
421
+ return out;
422
+ }
@@ -38,6 +38,12 @@ export const TABLE_RULES = [
38
38
  guidance:
39
39
  'Name a shared unit once in the header (TableColumn unit="people") and pass the number as <TableCell value={n} /> — it right-aligns and compacts it ("5.02k"). Never repeat the unit in every row ("229 people").',
40
40
  },
41
+ {
42
+ name: "table-cell-number-text",
43
+ severity: "error",
44
+ guidance:
45
+ 'Pass a number as <TableCell value={n} />: the column then shares one unit (once any value reaches 1,000 it reads "0.84k" … "106.78k") and the exact figure goes in the tooltip. A hand-formatted number ({n.toLocaleString()}, formatNumber(n)) skips both and breaks the column\'s alignment.',
46
+ },
41
47
  {
42
48
  name: "table-actions-unelevated",
43
49
  severity: "error",
@@ -90,7 +96,19 @@ export const TABLE_RULES = [
90
96
  name: "table-record-name-missing",
91
97
  severity: "error",
92
98
  guidance:
93
- "This table opens a detail panel, so its record column is <TableRecordName onOpen={…}> — clicking the name opens the panel.",
99
+ "A row that opens its record (a page or a detail panel) shows its name as <TableRecordName onOpen={…} opens=\"page\"|\"panel\"> — the name underlines on hover and the open button says where it goes. A bare text name with a row onClick gives no visible way in.",
100
+ },
101
+ {
102
+ name: "table-cell-two-values",
103
+ severity: "error",
104
+ guidance:
105
+ "One value per cell: a number is <TableCell value={n} /> on its own. A change, a delta or a second figure beside it (\"2,669 — 0\") is a second value — give it its own column, or leave it out when there is nothing to report.",
106
+ },
107
+ {
108
+ name: "table-chip-column-no-filter",
109
+ severity: "error",
110
+ guidance:
111
+ "A column of Chips (a status, a type, a source) is filtered from its header: pass the column's values to TableColumn filterOptions (with row counts) plus filterValue / onFilterChange, and show what applies with TableFilterChips. Never a separate Filters menu for one column.",
94
112
  },
95
113
  ];
96
114
 
@@ -188,24 +206,57 @@ export function lintTables(relPath, source, cfg) {
188
206
  const rowsOnly = source.replace(/<TableSummary[\s\S]*?<\/TableSummary>/g, (block) => block.replace(/[^\n]/g, " "));
189
207
  for (const m of rowsOnly.matchAll(UNIT)) push("table-cell-repeated-unit", m.index, source.slice(m.index, m.index + m[0].length));
190
208
 
209
+ // A cell whose whole content is a hand-formatted number (2026-11-30: an
210
+ // outcome table printed "1,499 (22.2%)" through toLocaleString).
211
+ for (const m of source.matchAll(/<TableCell\b(?:=>|[^<>])*?>\s*\{\s*[\w.?[\]]+\s*\.toLocaleString\([^)]*\)\s*\}|<TableCell\b(?:=>|[^<>])*?>\s*\{\s*(?:formatNumber|formatCount|numberFormat\.format|nf\.format)\([^)]*\)\s*\}/g)) {
212
+ push("table-cell-number-text", m.index, m[0].slice(0, 80));
213
+ }
214
+
191
215
  TABLE_OPEN.lastIndex = 0;
192
216
  for (const m of source.matchAll(TABLE_OPEN)) {
193
217
  if (/(elevatedActionColumn|stickyActionHeader)=\{false\}/.test(m[0])) push("table-actions-unelevated", m.index, m[0]);
194
218
  }
195
219
 
196
- // The pinned actions cells.
197
- const ACTION_CELL = /<TableCell\b(?:=>|[^<>])*?sticky="right"(?:=>|[^<>])*?>([\s\S]*?)<\/TableCell>/g;
198
- for (const m of source.matchAll(ACTION_CELL)) {
199
- const body = m[1];
200
- const bodyAt = m.index + m[0].indexOf(body);
220
+ // The actions cells: every pinned (sticky="right") cell, and the last cell of
221
+ // a row when it holds a Button or TableRowAction — a product that never
222
+ // pinned its actions column must not slip past these rules (2026-11-30: a
223
+ // Knowledge Base row shipped a ghost "Edit" text button in an unpinned cell).
224
+ const CELL = /<TableCell\b((?:=>|[^<>])*?)>((?:(?!<TableCell\b)[\s\S])*?)<\/TableCell>/g;
225
+ const actionCells = new Map();
226
+ for (const m of source.matchAll(CELL)) {
227
+ if (/sticky="right"/.test(m[1])) actionCells.set(m.index, m);
228
+ }
229
+ for (const row of source.matchAll(/<TableRow\b(?:=>|[^<>])*?>([\s\S]*?)<\/TableRow>/g)) {
230
+ const rowAt = row.index + row[0].indexOf(row[1]);
231
+ const cells = [...row[1].matchAll(CELL)];
232
+ const last = cells[cells.length - 1];
233
+ // A single cell spanning the row (an empty state, a loading row) is not an actions column.
234
+ if (!last || cells.length < 2 || /\bcolSpan=/.test(last[1]) || !/<(?:Button|TableRowAction)\b/.test(last[2])) continue;
235
+ const at = rowAt + last.index;
236
+ if (!actionCells.has(at)) actionCells.set(at, Object.assign([...last], { index: at }));
237
+ }
238
+ // A visible label: plain text, a translated string ({t("edit")}) or a string
239
+ // literal ({"Edit"}) — not text inside an sr-only span.
240
+ const hasVisibleLabel = (children) => {
241
+ const shown = children.replace(/<span\b[^>]*\bsr-only\b[^>]*>[\s\S]*?<\/span>/g, "").replace(/<[^>]*>/g, "");
242
+ if (/\{\s*(?:t|i18n\.t|intl\.formatMessage|formatMessage)\(|\{\s*["'`][^"'`]*[A-Za-z]/.test(shown)) return true;
243
+ return /[A-Za-z]/.test(shown.replace(/\{[^{}]*\}/g, "").trim());
244
+ };
245
+ for (const m of [...actionCells.values()].sort((a, b) => a.index - b.index)) {
246
+ const body = m[2];
247
+ const bodyAt = m.index + m[0].indexOf(body, m[0].indexOf(">") + 1);
201
248
  for (const b of body.matchAll(/<Button\b((?:=>|[^<>])*?)>([\s\S]*?)<\/Button>/g)) {
202
- const text = b[2].replace(/<[^>]*>/g, "").replace(/\{[^{}]*\}/g, "").trim();
203
- if (/[A-Za-z]/.test(text)) push("table-action-labelled", bodyAt + b.index, b[0]);
249
+ if (hasVisibleLabel(b[2])) push("table-action-labelled", bodyAt + b.index, b[0]);
204
250
  if (/\bdisabled(?:=\{|\s|>|$)/.test(b[1])) push("table-action-disabled-no-reason", bodyAt + b.index, b[0]);
205
251
  }
206
252
  for (const h of body.matchAll(/(?:&&\s*\(?\s*<(?:Button|TableRowAction)\b|:\s*null\s*\}|\?\s*null\s*:)/g)) {
207
253
  push("table-action-hidden", bodyAt + h.index, h[0]);
208
254
  }
255
+ // A row that swaps one action for another ({doc ? <Button>›</Button> : <Button>Edit</Button>}).
256
+ const swap = /\?\s*\(?\s*<(?:Button|TableRowAction)\b/.exec(body);
257
+ if (swap && /:\s*\(?\s*<(?:Button|TableRowAction)\b/.test(body.slice(swap.index))) {
258
+ push("table-action-hidden", bodyAt + swap.index, swap[0]);
259
+ }
209
260
  }
210
261
 
211
262
  for (const m of source.matchAll(/<TableRecordName\b(?:=>|[^<>])*?>/g)) {
@@ -222,6 +273,14 @@ export function lintTables(relPath, source, cfg) {
222
273
  push("table-cell-stacked", bodyAt + avatar.index, "<Avatar> in a TableCell");
223
274
  continue;
224
275
  }
276
+ // A cell that wraps (whitespace-normal / break-words) runs onto a second
277
+ // line: one value per cell means one line per row (a colSpan cell holding
278
+ // an empty state may wrap).
279
+ const cellTag = m[0].slice(0, m[0].indexOf(m[1]));
280
+ if (/(?:^|[\s"'`])(?:whitespace-normal|whitespace-pre-wrap|break-words)(?![\w-])/.test(cellTag) && !/\bcolSpan=/.test(cellTag)) {
281
+ push("table-cell-stacked", m.index, "whitespace-normal: the cell wraps onto a second line");
282
+ continue;
283
+ }
225
284
  const br = /<br\s*\/?>/.exec(m[1]);
226
285
  if (br) {
227
286
  push("table-cell-stacked", bodyAt + br.index, br[0]);
@@ -243,11 +302,55 @@ export function lintTables(relPath, source, cfg) {
243
302
  (/>\s*(?:Previous|Prev)\s*</.test(tail) && />\s*Next\s*</.test(tail) ? />\s*(?:Previous|Prev)\s*</.exec(tail) : null);
244
303
  if (pager) push("table-pagination", firstTable + pager.index, pager[0].trim());
245
304
  }
246
- // A row that opens a detail panel: the name must be the visible way in.
247
- const opensPanel = /<TableRow\b(?:=>|[^<>])*?\bonClick=/.test(source) && /<(?:Drawer|InlineDrawer)\b/.test(source);
248
- if (opensPanel && !/<TableRecordName\b/.test(source)) {
305
+ // A row that opens its record (a page or a panel): the name must be the
306
+ // visible way in. A selection table's row click selects, so it is exempt.
307
+ const opensRecord =
308
+ /<TableRow\b(?:=>|[^<>])*?\bonClick=/.test(source) && !/\bselectionMode=/.test(source);
309
+ if (opensRecord && !/<TableRecordName\b/.test(source)) {
249
310
  const t = source.search(/<TableRow\b(?:=>|[^<>])*?\bonClick=/);
250
311
  push("table-record-name-missing", t, source.slice(t, t + 40));
251
312
  }
313
+ // Two values in one cell: a number (or text) and a second figure beside it —
314
+ // `{commafy(n)} <Delta delta={d} />`. Only right-aligned cells: numbers.
315
+ for (const m of source.matchAll(CELL)) {
316
+ if (!/\balign="right"/.test(m[1]) || /sticky="right"|\bcolSpan=/.test(m[1])) continue;
317
+ const kids = jsxChildren(m[2]).filter((k) => k.kind !== "text" || k.text.trim());
318
+ const isValue = (k) => {
319
+ if (k.kind === "text" || k.kind === "expression") return !/^\{\s*\/\*/.test(k.text);
320
+ if (k.kind !== "element") return false;
321
+ // An icon or a bare wrapper is not a value; an element fed data is.
322
+ const attrs = k.tag.replace(/^<[\w.]+/, "").replace(/\/?>$/, "");
323
+ return /\b(?!className|size|weight|aria-[\w-]+|title|style)[A-Za-z]+=/.test(attrs) || !!(k.inner && k.inner.trim());
324
+ };
325
+ // Text and expressions run together into one formatted value ("{n}s",
326
+ // "₹{n}"); each element fed data is one more value.
327
+ const values = (kids.some((k) => k.kind !== "element" && isValue(k)) ? 1 : 0) +
328
+ kids.filter((k) => k.kind === "element" && isValue(k)).length;
329
+ if (values >= 2) {
330
+ const bodyAt = m.index + m[0].indexOf(m[2], m[0].indexOf(">") + 1);
331
+ push("table-cell-two-values", bodyAt, m[2].trim().replace(/\s+/g, " "));
332
+ }
333
+ }
334
+
335
+ // A column of Chips with no header filter. Pair each header column with the
336
+ // same-position cell of the first data row that fills every column.
337
+ for (const t of source.matchAll(/<Table\b[\s\S]*?<\/Table>/g)) {
338
+ const header = /<TableHeader\b[\s\S]*?<\/TableHeader>/.exec(t[0]);
339
+ const body = /<TableBody\b[\s\S]*<\/TableBody>/.exec(t[0]);
340
+ if (!header || !body) continue;
341
+ const columns = [...header[0].matchAll(/<TableColumn\b/g)].map((c) => openingTag(header[0], c.index));
342
+ if (columns.length < 2) continue;
343
+ for (const row of body[0].matchAll(/<TableRow\b(?:=>|[^<>])*?>([\s\S]*?)<\/TableRow>/g)) {
344
+ const cells = [...row[1].matchAll(CELL)];
345
+ if (cells.length !== columns.length || cells.some((c) => /\bcolSpan=/.test(c[1]))) continue;
346
+ cells.forEach((cell, i) => {
347
+ // A spread ({...filters.column("status")}, useTableFilters) carries the filter props.
348
+ if (!/^\s*<Chip\b/.test(cell[2]) || /\bfilterOptions=|\{\s*\.\.\./.test(columns[i])) return;
349
+ const at = t.index + header.index + header[0].indexOf(columns[i]);
350
+ push("table-chip-column-no-filter", at, columns[i].replace(/\s+/g, " "));
351
+ });
352
+ break;
353
+ }
354
+ }
252
355
  return findings;
253
356
  }
package/src/runner.mjs CHANGED
@@ -17,8 +17,9 @@ import { lintSelection } from "./rules/selection.mjs";
17
17
  import { lintElevation } from "./rules/elevation.mjs";
18
18
  import { lintControls } from "./rules/controls.mjs";
19
19
  import { lintRecipes } from "./rules/recipes.mjs";
20
+ import { lintScreens } from "./rules/screens.mjs";
20
21
 
21
- const RULE_FNS = [lintImports, lintMotion, lintLiterals, lintModals, lintTables, lintEmptyStates, lintCharts, lintButtons, lintCollections, lintSelection, lintElevation, lintControls, lintRecipes];
22
+ const RULE_FNS = [lintImports, lintMotion, lintLiterals, lintModals, lintTables, lintEmptyStates, lintCharts, lintButtons, lintCollections, lintSelection, lintElevation, lintControls, lintRecipes, lintScreens];
22
23
 
23
24
  function toPosix(p) {
24
25
  return p.split(path.sep).join("/");
@@ -0,0 +1,226 @@
1
+ // GENERATED by scripts/gen-screen-grammar.mjs from src/lib/screen-grammar.ts — do not edit.
2
+ /**
3
+ * ADS screen grammar — composition rules for KINDS of screen (user-mandated
4
+ * 2026-11-30: "set screen composition rules, and based on that they get
5
+ * implemented").
6
+ *
7
+ * A product screen declares its kind (`<AdsScreen kind="collection">`, or a
8
+ * glob in `ads-lint.config.mjs`). Every rule below is then checked three ways,
9
+ * all from this one module:
10
+ * • `ads-lint` reads the JSX inside the screen (rule ids `screen-…`);
11
+ * • `AdsScreen` walks the rendered `data-slot` tree in development and
12
+ * reports violations in the console;
13
+ * • `validateScreenElement()` runs the same check in a Storybook play
14
+ * function or a product's Playwright test.
15
+ *
16
+ * Keep this module import-free: the manifest and lint generators transpile it
17
+ * on its own. Rules name ADS exports; the runtime check maps `data-slot`
18
+ * values back to those names through SLOT_COMPONENTS.
19
+ */
20
+ const CHARTS = [
21
+ "BarChart",
22
+ "LineChart",
23
+ "AreaChart",
24
+ "ComboChart",
25
+ "ComposedChart",
26
+ "PieChart",
27
+ "FunnelChart",
28
+ "FunnelViz",
29
+ "FunnelBarsHorizontal",
30
+ "ConversionFunnel",
31
+ "BarList",
32
+ ];
33
+ export const SCREEN_KINDS = {
34
+ collection: {
35
+ id: "collection",
36
+ name: "Collection",
37
+ description: "A list of records of one kind: campaigns, call logs, segments, knowledge entries. One header bar, one control row, the table (or its empty state), and a record panel when a record has no page of its own.",
38
+ regions: [
39
+ { name: "Header bar", components: ["BodyPageHeader"], note: "Title and ONE primary action. Search and filters never live here." },
40
+ { name: "Control row", components: ["CollectionToolbar"], note: "Tabs with counts (or All N) leading; SearchDisclosure, Filters and Columns trailing." },
41
+ { name: "What applies", components: ["TableFilterChips"], note: "One chip per applied column filter and the hidden-columns chip." },
42
+ { name: "Records", components: ["Table", "EmptyState"], note: "One value per cell; the name is TableRecordName; actions pinned right. With nothing to list, the EmptyState replaces the table." },
43
+ { name: "Record panel", components: ["Drawer", "CallPanel"], note: "Only for a record without its own page; attached beside the list, under the header bar." },
44
+ ],
45
+ rules: [
46
+ { id: "screen-collection-header", severity: "error", says: "A collection has exactly one header bar (BodyPageHeader).", check: { type: "count", component: "BodyPageHeader", min: 1, max: 1 } },
47
+ { id: "screen-collection-order", severity: "error", says: "Top to bottom: header bar, control row, filter chips, then the table or its empty state, then the record panel.", check: { type: "order", sequence: ["BodyPageHeader", "CollectionToolbar", "TableFilterChips", ["Table", "EmptyState"], ["Drawer", "CallPanel"]] } },
48
+ { id: "screen-collection-records", severity: "error", says: "A collection shows its records in a Table, or an EmptyState when there are none.", check: { type: "count", component: ["Table", "EmptyState"], min: 1 } },
49
+ { id: "screen-collection-toolbar", severity: "error", says: "A table of records sits under a CollectionToolbar (tabs or All N, search, filters).", check: { type: "count", component: "CollectionToolbar", min: 1, when: "Table" } },
50
+ { id: "screen-collection-record-name", severity: "error", says: "Each row names its record with TableRecordName, which opens it.", check: { type: "count", component: "TableRecordName", min: 1, when: "Table" } },
51
+ { id: "screen-collection-header-tools", severity: "error", says: "Search, filters and columns belong to the control row, never the header bar.", check: { type: "forbid", component: ["SearchDisclosure", "Filters", "TableColumnsMenu", "Input", "SearchField"], inside: "BodyPageHeader" } },
52
+ { id: "screen-collection-one-primary", severity: "error", says: "The header bar carries one primary (solid) action.", scope: "static", check: { type: "count", component: "Button", inside: "BodyPageHeader", props: { variant: "solid" }, max: 1 } },
53
+ { id: "screen-collection-no-stepper", severity: "error", says: "A status or stage is a Chip in its column, never a Stepper.", check: { type: "forbid", component: "Stepper" } },
54
+ ],
55
+ workflows: [
56
+ { id: "filter-column", says: "Clicking a header opens its column menu; a chosen value shows as a chip under the control row." },
57
+ { id: "open-record", says: "The record's name opens it: its page (opens=\"page\") or the attached panel (opens=\"panel\")." },
58
+ { id: "copy-one-click", says: "Copy makes \"<name> (copy)\" at once, opens it and names it in a toast; no naming dialog." },
59
+ { id: "delete-asks-once", says: "Deleting a record asks once in a small ConfirmDialog that names the kind; parts of a record go without asking." },
60
+ ],
61
+ example: "src/examples/campaigns-screen.tsx",
62
+ story: "ads-recipes-campaigns--list",
63
+ principles: ["collection-screens", "record-detail-panels", "minimal-information", "empty-states", "deleting"],
64
+ },
65
+ monitor: {
66
+ id: "monitor",
67
+ name: "Monitor",
68
+ description: "How something is doing: a program dashboard (Voice insights) or a live record's monitor (a journey, a campaign's analysis). Header, optional tabs, one hero stat strip, then charts in chart cards. A campaign's Analysis tab splits into category tabs — Business, Customer cohorts (Technical later) — each leading with its own numbers.",
69
+ regions: [
70
+ { name: "Header bar", components: ["BodyPageHeader", "Breadcrumbs"], note: "Title or trail — or none, when the monitor is a tab of a record page that owns the header. The status Chip carries any lock (\"Live · Locked\"); the scope (period, campaign) is said once here." },
71
+ { name: "Tabs", components: ["Tabs"], note: "Only on a record page." },
72
+ { name: "Hero numbers", components: ["StatStrip"], note: "ONE hero strip leads (T1 wash): the measures that matter most, each with its own chart colour and sparkline. Quiet strips may follow. The comparison is said once." },
73
+ { name: "Charts", components: ["ChartCard"], note: "Every chart sits in a ChartCard: title + scope on the left, controls on the right." },
74
+ ],
75
+ rules: [
76
+ { id: "screen-monitor-header", severity: "error", says: "A monitor has at most one header bar; a monitor that is a tab of a record page leaves the header to that page.", check: { type: "count", component: "BodyPageHeader", max: 1 } },
77
+ { id: "screen-monitor-order", severity: "error", says: "Top to bottom: header, tabs, the stat strips, then the chart cards.", check: { type: "order", sequence: [["BodyPageHeader", "Breadcrumbs"], "Tabs", "StatStrip", "ChartCard"] } },
78
+ { id: "screen-monitor-stats", severity: "error", says: "A monitor leads with its numbers in a StatStrip.", check: { type: "count", component: "StatStrip", min: 1 } },
79
+ { id: "screen-monitor-one-hero", severity: "error", says: "Only one stat strip is the hero; the rest are quiet.", check: { type: "count", component: "StatStrip", props: { tone: "hero" }, max: 1 } },
80
+ { id: "screen-monitor-hero-first", severity: "error", says: "When a tab has a hero stat strip, it comes before every other strip.", check: { type: "first", component: "StatStrip", props: { tone: "hero" }, ifAny: true } },
81
+ { id: "screen-monitor-comparison-once", severity: "error", says: "Say what changes are compared with once, on the first strip, not on every number.", scope: "static", check: { type: "count", component: "StatStrip", props: { comparison: "*" }, max: 1 } },
82
+ { id: "screen-monitor-charts-in-cards", severity: "error", says: "Every chart sits in a ChartCard (title and scope left, controls right).", scope: "static", check: { type: "inside", component: CHARTS, parent: "ChartCard" } },
83
+ { id: "screen-monitor-no-stepper", severity: "error", says: "A status is a Chip, never a Stepper.", check: { type: "forbid", component: "Stepper" } },
84
+ ],
85
+ workflows: [
86
+ { id: "scope-once", says: "The period and filters are set once in the header; no chart carries its own date pager." },
87
+ { id: "hide-always-zero", says: "A number that stays empty or 0 for nearly everyone (Outcome reached) is left out, not shown as a result." },
88
+ { id: "lock-in-status", says: "A live record says it is locked in its status chip (\"Live · Locked\", the way out in its tooltip); Pause makes it \"Paused\" and editable." },
89
+ ],
90
+ example: "src/examples/voice-insights-screen.tsx",
91
+ story: "ads-recipes-voice-insights--overview",
92
+ principles: ["analytics-surfaces", "colour-alive", "minimal-information"],
93
+ },
94
+ };
95
+ /** `data-slot` → ADS export, for checking the rendered tree. */
96
+ export const SLOT_COMPONENTS = {
97
+ "body-page-header": "BodyPageHeader",
98
+ breadcrumbs: "Breadcrumbs",
99
+ "collection-toolbar": "CollectionToolbar",
100
+ "table-filter-chips": "TableFilterChips",
101
+ table: "Table",
102
+ "table-record-name": "TableRecordName",
103
+ "empty-state": "EmptyState",
104
+ drawer: "Drawer",
105
+ "call-panel": "CallPanel",
106
+ tabs: "Tabs",
107
+ "search-disclosure": "SearchDisclosure",
108
+ filters: "Filters",
109
+ "table-columns-menu": "TableColumnsMenu",
110
+ stepper: "Stepper",
111
+ "stat-strip": "StatStrip",
112
+ "bar-list": "BarList",
113
+ "stat-strip-item": "StatStripItem",
114
+ "chart-card": "ChartCard",
115
+ "filter-bar": "FilterBar",
116
+ };
117
+ const list = (n) => (Array.isArray(n) ? n : [n]);
118
+ function flatten(root) {
119
+ const out = [];
120
+ const walk = (node, ancestors) => {
121
+ out.push({ node, ancestors });
122
+ for (const child of node.children)
123
+ walk(child, node.component ? [...ancestors, node] : ancestors);
124
+ };
125
+ walk(root, []);
126
+ return out.slice(1); // the screen itself is not one of its parts
127
+ }
128
+ function propsMatch(node, want) {
129
+ if (!want)
130
+ return true;
131
+ let unknown = false;
132
+ for (const [key, value] of Object.entries(want)) {
133
+ const has = node.props?.[key];
134
+ if (has === undefined)
135
+ return false;
136
+ if (value === "*")
137
+ continue;
138
+ if (has === true)
139
+ unknown = true;
140
+ else if (has !== value)
141
+ return false;
142
+ }
143
+ return unknown ? "unknown" : true;
144
+ }
145
+ /**
146
+ * Check a screen tree against its kind. `mode` says who built the tree: the
147
+ * linter (`static`, props known, product components opaque) or the rendered
148
+ * DOM (`rendered`, everything visible but few props).
149
+ */
150
+ export function validateScreen(kindId, root, mode = "rendered") {
151
+ const kind = SCREEN_KINDS[kindId];
152
+ if (!kind)
153
+ return [{ rule: "screen-kind-unknown", severity: "error", message: `Unknown screen kind "${kindId}". Use one of: ${Object.keys(SCREEN_KINDS).join(", ")}.` }];
154
+ const nodes = flatten(root);
155
+ // The linter cannot see inside product components, so it never claims a part is missing.
156
+ const blind = mode === "static" && nodes.some((n) => n.node.opaque);
157
+ const out = [];
158
+ const is = (n, names) => n.component != null && list(names).includes(n.component);
159
+ const within = (f, parent) => !parent || f.ancestors.some((a) => is(a, parent));
160
+ for (const rule of kind.rules) {
161
+ const scope = rule.scope ?? "both";
162
+ if (scope !== "both" && scope !== mode)
163
+ continue;
164
+ const c = rule.check;
165
+ const report = (line) => out.push({ rule: rule.id, severity: rule.severity, message: rule.says, line });
166
+ if (c.type === "count") {
167
+ if (c.when && !nodes.some((f) => is(f.node, c.when)))
168
+ continue;
169
+ const matches = nodes.filter((f) => is(f.node, c.component) && within(f, c.inside));
170
+ const sure = matches.filter((f) => propsMatch(f.node, c.props) === true);
171
+ const maybe = matches.filter((f) => propsMatch(f.node, c.props) !== false);
172
+ if (c.max != null && sure.length > c.max)
173
+ report(sure[c.max].node.line);
174
+ if (c.min != null && maybe.length < c.min && !blind)
175
+ report(root.line);
176
+ }
177
+ else if (c.type === "forbid") {
178
+ const hit = nodes.find((f) => is(f.node, c.component) && within(f, c.inside));
179
+ if (hit)
180
+ report(hit.node.line);
181
+ }
182
+ else if (c.type === "inside") {
183
+ const stray = nodes.find((f) => is(f.node, c.component) && !within(f, c.parent));
184
+ if (stray)
185
+ report(stray.node.line);
186
+ }
187
+ else if (c.type === "first") {
188
+ if (c.ifAny && !nodes.some((f) => is(f.node, c.component) && propsMatch(f.node, c.props) !== false))
189
+ continue;
190
+ const first = nodes.find((f) => is(f.node, c.component));
191
+ if (first && propsMatch(first.node, c.props) === false)
192
+ report(first.node.line);
193
+ }
194
+ else if (c.type === "order") {
195
+ let last = -1;
196
+ for (const step of c.sequence) {
197
+ const at = nodes.findIndex((f) => is(f.node, step));
198
+ if (at < 0)
199
+ continue;
200
+ if (at < last) {
201
+ report(nodes[at].node.line);
202
+ break;
203
+ }
204
+ last = at;
205
+ }
206
+ }
207
+ }
208
+ return out;
209
+ }
210
+ /** Build a ScreenNode tree from rendered DOM: `data-slot` values the grammar knows, `data-*` as props. */
211
+ export function screenTreeFromElement(el) {
212
+ const slot = el.getAttribute("data-slot") ?? "";
213
+ const component = SLOT_COMPONENTS[slot] ?? null;
214
+ const props = {};
215
+ if (component) {
216
+ for (const attr of Array.from(el.attributes)) {
217
+ if (attr.name.startsWith("data-") && attr.name !== "data-slot")
218
+ props[attr.name.slice(5)] = attr.value;
219
+ }
220
+ }
221
+ return { component, props, children: Array.from(el.children).map(screenTreeFromElement) };
222
+ }
223
+ /** Check a rendered screen (for Storybook play functions and product tests). */
224
+ export function validateScreenElement(el, kind) {
225
+ return validateScreen(kind, { ...screenTreeFromElement(el), component: null }, "rendered");
226
+ }