@behavioral-agentic-design-system/core 0.45.0 → 0.47.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 (237) hide show
  1. package/package.json +17 -3
  2. package/scripts/a11y-lint.cjs +78 -15
  3. package/scripts/bads-sync.mjs +1 -1
  4. package/scripts/build-tokens.cjs +122 -7
  5. package/scripts/check-dark-contrast.mjs +204 -0
  6. package/scripts/check-flush-edges.mjs +245 -0
  7. package/scripts/design-system-advisory/README.md +239 -0
  8. package/scripts/design-system-advisory/check-copy-punctuation.mjs +44 -0
  9. package/scripts/design-system-advisory/check-even-padding.mjs +35 -0
  10. package/scripts/design-system-advisory/check-hand-built-button.mjs +46 -0
  11. package/scripts/design-system-advisory/check-html-nesting.mjs +51 -0
  12. package/scripts/design-system-advisory/check-icon-sizing.mjs +79 -0
  13. package/scripts/design-system-advisory/check-label-case.mjs +92 -0
  14. package/scripts/design-system-advisory/check-native-form-controls.mjs +53 -0
  15. package/scripts/design-system-advisory/check-radius.mjs +56 -0
  16. package/scripts/design-system-advisory/check-raw-values.mjs +61 -0
  17. package/scripts/design-system-advisory/check-small-text.mjs +72 -0
  18. package/scripts/design-system-advisory/check-tap-target.mjs +70 -0
  19. package/scripts/design-system-advisory/defaults.mjs +90 -0
  20. package/scripts/design-system-advisory/fixtures/clean.tsx.fixture +12 -0
  21. package/scripts/design-system-advisory/fixtures/violations.tsx.fixture +19 -0
  22. package/scripts/design-system-advisory/lib.mjs +255 -0
  23. package/scripts/design-system-advisory/run.mjs +189 -0
  24. package/scripts/design-system-advisory/workflow.yml +82 -0
  25. package/scripts/lib/copy-strings.mjs +146 -0
  26. package/scripts/lib/dark-contrast.mjs +120 -0
  27. package/scripts/lib/flush-edges.mjs +294 -0
  28. package/scripts/lib/lab-lint.mjs +62 -0
  29. package/scripts/lib/mount-page.mjs +25 -0
  30. package/scripts/lib/source-scan.mjs +173 -0
  31. package/scripts/lib/tells.mjs +240 -2
  32. package/scripts/lint-arbitrary-tokens.mjs +47 -0
  33. package/scripts/lint-component-token-refs.mjs +63 -0
  34. package/scripts/lint-content-hierarchy.mjs +114 -0
  35. package/scripts/lint-control-baseline.mjs +72 -0
  36. package/scripts/lint-copy-punctuation.mjs +60 -0
  37. package/scripts/lint-even-padding.mjs +58 -0
  38. package/scripts/lint-label-case.mjs +219 -0
  39. package/scripts/lint-microanimation.mjs +2 -2
  40. package/scripts/lint-proximity.mjs +181 -0
  41. package/scripts/lint-slop.mjs +1 -1
  42. package/scripts/lint-spacing-scale.mjs +78 -0
  43. package/scripts/lint-target-size.cjs +132 -0
  44. package/scripts/lint-token-primitives.mjs +307 -0
  45. package/scripts/size-audit.cjs +2 -2
  46. package/scripts/ux-tells.mjs +8 -6
  47. package/scripts/wcag-audit.cjs +25 -4
  48. package/src/api/layers/file.ts +2 -0
  49. package/src/api/site-auth.ts +14 -2
  50. package/src/app/preview/components/page.tsx +94 -14
  51. package/src/app/preview/sticker-sheet/page.tsx +329 -0
  52. package/src/app/preview/sticker-sheet/specimens.tsx +296 -0
  53. package/src/app/shell.tsx +4 -3
  54. package/src/components/Foundations/Colors.stories.tsx +119 -8
  55. package/src/components/home-tab.tsx +6 -1
  56. package/src/components/onboarding-wizard.tsx +1 -1
  57. package/src/components/ui/avatar.tsx +4 -0
  58. package/src/components/ui/chart.tsx +134 -42
  59. package/src/components/ui/checkbox-group.tsx +1 -1
  60. package/src/components/ui/checkbox.tsx +1 -1
  61. package/src/components/ui/combobox.tsx +1 -0
  62. package/src/components/ui/command.tsx +1 -1
  63. package/src/components/ui/date-picker.tsx +2 -0
  64. package/src/components/ui/date-range-picker.tsx +4 -0
  65. package/src/components/ui/file-upload.tsx +21 -2
  66. package/src/components/ui/heatmap.tsx +3 -1
  67. package/src/components/ui/input-group.tsx +5 -2
  68. package/src/components/ui/multi-select.tsx +1 -0
  69. package/src/components/ui/radio-group.tsx +2 -2
  70. package/src/components/ui/sparkline.tsx +33 -4
  71. package/src/components/ui/spinner.tsx +23 -4
  72. package/src/components/ui/table.tsx +9 -0
  73. package/src/components/ui/week-picker.tsx +0 -12
  74. package/src/data/component-added.json +8 -0
  75. package/src/data/docs-index.ts +22 -1
  76. package/src/data/history.json +161 -161
  77. package/src/data/sticker-sheet.json +9244 -0
  78. package/src/docs-trace-globs.json +1 -0
  79. package/src/lib/chart-motion.ts +41 -0
  80. package/src/lib/get-icon-color.ts +1 -1
  81. package/src/stories/Accordion.stories.tsx +7 -0
  82. package/src/stories/ActionBar.stories.tsx +5 -0
  83. package/src/stories/Affix.stories.tsx +4 -0
  84. package/src/stories/AiBadge.stories.tsx +9 -7
  85. package/src/stories/Alert.stories.tsx +13 -0
  86. package/src/stories/AlertDialog.stories.tsx +4 -0
  87. package/src/stories/Anchor.stories.tsx +5 -0
  88. package/src/stories/AngleSlider.stories.tsx +6 -3
  89. package/src/stories/AspectRatio.stories.tsx +4 -0
  90. package/src/stories/Autocomplete.stories.tsx +6 -0
  91. package/src/stories/Avatar.stories.tsx +10 -0
  92. package/src/stories/Badge.stories.tsx +14 -6
  93. package/src/stories/Blockquote.stories.tsx +6 -0
  94. package/src/stories/BottomNavigation.stories.tsx +4 -0
  95. package/src/stories/Breadcrumb.stories.tsx +3 -0
  96. package/src/stories/Burger.stories.tsx +1 -0
  97. package/src/stories/Button.stories.tsx +24 -0
  98. package/src/stories/ButtonGroup.stories.tsx +9 -0
  99. package/src/stories/Calendar.stories.tsx +3 -0
  100. package/src/stories/Card.stories.tsx +4 -0
  101. package/src/stories/Carousel.stories.tsx +6 -0
  102. package/src/stories/Cascader.stories.tsx +4 -0
  103. package/src/stories/Chart.stories.tsx +46 -1
  104. package/src/stories/ChatBubble.stories.tsx +8 -2
  105. package/src/stories/ChatMarker.stories.tsx +1 -0
  106. package/src/stories/Checkbox.stories.tsx +40 -0
  107. package/src/stories/CheckboxCard.stories.tsx +8 -0
  108. package/src/stories/CheckboxGroup.stories.tsx +19 -0
  109. package/src/stories/Chip.stories.tsx +10 -19
  110. package/src/stories/CircularProgress.stories.tsx +13 -27
  111. package/src/stories/Clipboard.stories.tsx +6 -0
  112. package/src/stories/CloseButton.stories.tsx +6 -4
  113. package/src/stories/Code.stories.tsx +8 -1
  114. package/src/stories/Collapsible.stories.tsx +2 -0
  115. package/src/stories/ColorPicker.stories.tsx +6 -0
  116. package/src/stories/ColorSwatch.stories.tsx +1 -0
  117. package/src/stories/Combobox.stories.tsx +9 -0
  118. package/src/stories/Command.stories.tsx +2 -0
  119. package/src/stories/Container.stories.tsx +8 -0
  120. package/src/stories/ContextMenu.stories.tsx +9 -0
  121. package/src/stories/CopyButton.stories.tsx +12 -36
  122. package/src/stories/DataList.stories.tsx +8 -0
  123. package/src/stories/DataTable.stories.tsx +9 -0
  124. package/src/stories/DateField.stories.tsx +7 -0
  125. package/src/stories/DatePicker.stories.tsx +34 -0
  126. package/src/stories/DateRangePicker.stories.tsx +32 -0
  127. package/src/stories/Dialog.stories.tsx +8 -0
  128. package/src/stories/Drawer.stories.tsx +6 -0
  129. package/src/stories/DropdownMenu.stories.tsx +2 -0
  130. package/src/stories/Editable.stories.tsx +10 -0
  131. package/src/stories/EmptyState.stories.tsx +9 -0
  132. package/src/stories/Field.stories.tsx +7 -0
  133. package/src/stories/Fieldset.stories.tsx +8 -0
  134. package/src/stories/FileButton.stories.tsx +4 -0
  135. package/src/stories/FileUpload.stories.tsx +16 -17
  136. package/src/stories/FloatLabel.stories.tsx +3 -8
  137. package/src/stories/FloatingActionButton.stories.tsx +10 -0
  138. package/src/stories/FloatingIndicator.stories.tsx +4 -0
  139. package/src/stories/FloatingPanel.stories.tsx +6 -0
  140. package/src/stories/FocusTrap.stories.tsx +5 -0
  141. package/src/stories/FormatByte.stories.tsx +6 -0
  142. package/src/stories/FormatDate.stories.tsx +8 -0
  143. package/src/stories/FormatNumber.stories.tsx +9 -0
  144. package/src/stories/Heatmap.stories.tsx +11 -0
  145. package/src/stories/Highlight.stories.tsx +6 -0
  146. package/src/stories/HoverCard.stories.tsx +4 -0
  147. package/src/stories/Image.stories.tsx +9 -0
  148. package/src/stories/Indicator.stories.tsx +19 -0
  149. package/src/stories/Input.stories.tsx +7 -0
  150. package/src/stories/InputClearButton.stories.tsx +3 -0
  151. package/src/stories/InputGroup.stories.tsx +40 -0
  152. package/src/stories/Kbd.stories.tsx +7 -1
  153. package/src/stories/KeyboardShortcut.stories.tsx +2 -0
  154. package/src/stories/Label.stories.tsx +2 -0
  155. package/src/stories/Link.stories.tsx +9 -0
  156. package/src/stories/List.stories.tsx +8 -0
  157. package/src/stories/Listbox.stories.tsx +1 -0
  158. package/src/stories/LoadingDots.stories.tsx +5 -3
  159. package/src/stories/LoadingOverlay.stories.tsx +5 -1
  160. package/src/stories/Mark.stories.tsx +5 -0
  161. package/src/stories/Marquee.stories.tsx +4 -0
  162. package/src/stories/Masonry.stories.tsx +5 -0
  163. package/src/stories/Menubar.stories.tsx +3 -0
  164. package/src/stories/Meter.stories.tsx +11 -17
  165. package/src/stories/MonthPicker.stories.tsx +5 -1
  166. package/src/stories/MotionToggle.stories.tsx +1 -0
  167. package/src/stories/MultiSelect.stories.tsx +9 -0
  168. package/src/stories/NativeSelect.stories.tsx +1 -0
  169. package/src/stories/NavLink.stories.tsx +7 -0
  170. package/src/stories/NavigationMenu.stories.tsx +5 -0
  171. package/src/stories/NavigationRail.stories.tsx +10 -0
  172. package/src/stories/Notification.stories.tsx +13 -34
  173. package/src/stories/NumberInput.stories.tsx +8 -1
  174. package/src/stories/Overlay.stories.tsx +5 -1
  175. package/src/stories/Pagination.stories.tsx +8 -0
  176. package/src/stories/PasswordInput.stories.tsx +2 -0
  177. package/src/stories/PinInput.stories.tsx +9 -2
  178. package/src/stories/Popover.stories.tsx +2 -0
  179. package/src/stories/Progress.stories.tsx +6 -1
  180. package/src/stories/Prose.stories.tsx +8 -0
  181. package/src/stories/QrCode.stories.tsx +2 -0
  182. package/src/stories/Questionnaire.stories.tsx +7 -0
  183. package/src/stories/RadioGroup.stories.tsx +40 -0
  184. package/src/stories/RatingGroup.stories.tsx +8 -4
  185. package/src/stories/Resizable.stories.tsx +4 -2
  186. package/src/stories/Result.stories.tsx +3 -0
  187. package/src/stories/Reveal.stories.tsx +2 -0
  188. package/src/stories/RollingNumber.stories.tsx +5 -0
  189. package/src/stories/ScrollArea.stories.tsx +3 -1
  190. package/src/stories/SearchInput.stories.tsx +8 -6
  191. package/src/stories/SegmentedControl.stories.tsx +11 -0
  192. package/src/stories/Select.stories.tsx +7 -0
  193. package/src/stories/Separator.stories.tsx +6 -0
  194. package/src/stories/Sheet.stories.tsx +5 -0
  195. package/src/stories/Sidebar.stories.tsx +40 -1
  196. package/src/stories/SimpleGrid.stories.tsx +5 -0
  197. package/src/stories/Skeleton.stories.tsx +8 -0
  198. package/src/stories/SkeletonTable.stories.tsx +6 -5
  199. package/src/stories/SkipLink.stories.tsx +3 -0
  200. package/src/stories/Slider.stories.tsx +2 -1
  201. package/src/stories/Sonner.stories.tsx +7 -0
  202. package/src/stories/Sparkline.stories.tsx +14 -1
  203. package/src/stories/Spinner.stories.tsx +20 -10
  204. package/src/stories/Spoiler.stories.tsx +5 -0
  205. package/src/stories/Squircle.stories.tsx +7 -0
  206. package/src/stories/Stack.stories.tsx +7 -0
  207. package/src/stories/StatusBadge.stories.tsx +12 -6
  208. package/src/stories/Stepper.stories.tsx +5 -0
  209. package/src/stories/Switch.stories.tsx +4 -0
  210. package/src/stories/Table.stories.tsx +10 -1
  211. package/src/stories/Tabs.stories.tsx +8 -0
  212. package/src/stories/Tag.stories.tsx +13 -5
  213. package/src/stories/TagsInput.stories.tsx +13 -0
  214. package/src/stories/Text.stories.tsx +12 -0
  215. package/src/stories/Textarea.stories.tsx +9 -0
  216. package/src/stories/ThemeIcon.stories.tsx +6 -3
  217. package/src/stories/TimePicker.stories.tsx +2 -0
  218. package/src/stories/Timeline.stories.tsx +12 -0
  219. package/src/stories/Timer.stories.tsx +4 -0
  220. package/src/stories/Toggle.stories.tsx +7 -5
  221. package/src/stories/ToggleGroup.stories.tsx +5 -0
  222. package/src/stories/ToggleTip.stories.tsx +4 -0
  223. package/src/stories/Toolbar.stories.tsx +6 -0
  224. package/src/stories/Tooltip.stories.tsx +3 -0
  225. package/src/stories/Tour.stories.tsx +3 -0
  226. package/src/stories/TransferList.stories.tsx +3 -0
  227. package/src/stories/TreeSelect.stories.tsx +4 -0
  228. package/src/stories/TreeView.stories.tsx +5 -0
  229. package/src/stories/TypingIndicator.stories.tsx +4 -0
  230. package/src/stories/VisuallyHidden.stories.tsx +3 -0
  231. package/src/stories/Watermark.stories.tsx +6 -0
  232. package/src/stories/WeekPicker.stories.tsx +4 -1
  233. package/src/stories/WordRotate.stories.tsx +5 -0
  234. package/src/stories/YearPicker.stories.tsx +5 -11
  235. package/src/styles.css +50 -2
  236. package/src/tokens.json +4 -4
  237. package/LICENSE +0 -21
@@ -3,9 +3,16 @@
3
3
  * styles in a real browser at several widths. lint-slop reads source text; this
4
4
  * reads what paints, so it sees classes composed at runtime and the effect of the
5
5
  * cascade. The registry's shape (dated, banned or warned) and the idea of
6
- * checking the rendered page at three widths are from Leonxlnx/taste-skill (MIT);
6
+ * checking the rendered page at several widths are from Leonxlnx/taste-skill (MIT);
7
7
  * the rules are chosen to fit BADS's own registers and real-content rule.
8
8
  *
9
+ * The four LAYOUT tells (BADS-TELL-12 to 15) adapt measurements from the render tier of nutlope/hallmark
10
+ * (MIT, gates 71, 72, 73 and 49): a heading nearer what precedes it than what it heads, text crowding the edge
11
+ * of its box, text painted under another element, and a button label that wraps or is clipped. BADS already
12
+ * wrote three of those as rules with no lint behind them (proximity-and-grouping, even-padding, and the
13
+ * label-fit rule that docs/agent-rules/button-label-fit.md said could not be linted). Thresholds are Hallmark's, kept until they are
14
+ * re-measured against BADS's own pages. All four start as `warned`.
15
+ *
9
16
  * Two parts, kept apart so the logic is testable without a browser:
10
17
  * probe() runs INSIDE the page and returns plain facts. Self-contained.
11
18
  * classify() turns those facts into findings. Pure.
@@ -16,7 +23,12 @@
16
23
  */
17
24
  import { SLOP_EMOJI } from "../slop-rules.mjs";
18
25
 
19
- export const WIDTHS = [375, 768, 1280];
26
+ /**
27
+ * 320 is WCAG 1.4.10 Reflow (AA, so inside BADS's AAA floor): the width a 1280px window reaches at 400% zoom. Agents
28
+ * and screenshot pipelines default to about 390px, so 320 is the state that goes unrendered. The horizontal-overflow
29
+ * tell runs at every width, so adding 320 here is what makes it a reflow check.
30
+ */
31
+ export const WIDTHS = [320, 375, 768, 1280];
20
32
 
21
33
  /** code, name, status (banned fails the run; warned is reported), and why. */
22
34
  export const TELLS = [
@@ -31,6 +43,12 @@ export const TELLS = [
31
43
  { code: "BADS-TELL-9", name: "placeholder-copy", status: "banned", why: "Placeholder text (Lorem ipsum, Jane Doe, Acme Inc., 555 numbers). The real-content rule: pull from content/personas/<brand>.json." },
32
44
  { code: "BADS-TELL-10", name: "placeholder-image", status: "banned", why: "An image from a placeholder service. Show the real product or a real picture of the client's world (bads-source-images)." },
33
45
  { code: "BADS-TELL-11", name: "horizontal-overflow", status: "banned", why: "The page scrolls sideways at this width. Fix the layout, not the rhythm." },
46
+ { code: "BADS-TELL-12", name: "crowded-heading", status: "warned", why: "Two or more headings sit nearer the content above them than the content they head. Space above a heading should be at least twice the space below it (layer-6 proximity-and-grouping)." },
47
+ { code: "BADS-TELL-13", name: "cramped-box", status: "warned", why: "Text sits closer to the edge of its filled or bordered box than max(8px, 0.5em) at the sides or max(4px, 0.3em) above and below (layer-6 even-padding)." },
48
+ { code: "BADS-TELL-14", name: "covered-text", status: "warned", why: "Text is painted under another element, so part of it cannot be read or clicked. Give it its own space (corrections #001)." },
49
+ { code: "BADS-TELL-15", name: "wrapped-button-label", status: "warned", why: "A button label wraps to a second line or is clipped at this width. The label does not fit its container: shorten it, widen the button, or accept the wrap for a dynamic label (CLAUDE.md, Button label fit)." },
50
+ { code: "BADS-TELL-16", name: "zoom-blocked", status: "banned", why: "The viewport meta tag stops people zooming (user-scalable=no, or maximum-scale below 2). Zoom is how a low-vision user reaches the 320px reflow state, and blocking it fails WCAG 1.4.4 and 1.4.10." },
51
+ { code: "BADS-TELL-17", name: "unreachable-scroll-region", status: "warned", why: "A region that scrolls sideways cannot be reached by keyboard, or has no role and name. Give it tabindex=0, role=region and an aria-label so a keyboard or screen reader user can find and scroll it (WCAG 1.4.10 table pattern)." },
34
52
  ];
35
53
 
36
54
  /** Runs in the browser. Returns plain, serializable facts. Must not reference anything outside itself. */
@@ -87,9 +105,217 @@ export function probe() {
87
105
  const ph = text.match(/lorem ipsum|dolor sit amet|\bjane doe\b|\bjohn doe\b|acme inc|123 main st|555[-. ]?555/gi);
88
106
  if (ph) facts.copy = [...new Set(ph.map((s) => s.toLowerCase()))];
89
107
  facts.overflow = { scrollWidth: document.documentElement.scrollWidth, innerWidth: vw };
108
+ // The viewport meta tag must not block zoom: ACT rule b4f0c3, and the precondition for testing reflow at all.
109
+ const vp = document.querySelector('meta[name="viewport" i]');
110
+ if (vp) {
111
+ const c = vp.getAttribute("content") || "";
112
+ const scalable = /user-scalable\s*=\s*(no|0)\b/i.test(c);
113
+ const max = /maximum-scale\s*=\s*([\d.]+)/i.exec(c);
114
+ if (scalable || (max && parseFloat(max[1]) < 2)) facts.zoom = { content: c };
115
+ }
90
116
  return facts;
91
117
  }
92
118
 
119
+ /**
120
+ * Runs in the browser. The four layout tells (12 to 15). Async because covered text needs to scroll the page and
121
+ * sample what is painted at each text position. Self-contained like probe(), and it puts the scroll back.
122
+ */
123
+ export async function probeLayout() {
124
+ const MAX = 4000;
125
+ const out = { crowded: [], cramped: [], covered: [], wrapped: [] };
126
+ const px = (v) => parseFloat(v) || 0;
127
+ const name = (el) => el.tagName.toLowerCase() + (typeof el.className === "string" && el.className.trim() ? "." + el.className.trim().split(/\s+/)[0] : "");
128
+ const clear = (c) => !c || c === "transparent" || /^rgba\(\s*0,\s*0,\s*0,\s*0\s*\)$/.test(c);
129
+ const vis = (el) => { const cs = getComputedStyle(el); if (cs.display === "none" || cs.visibility === "hidden" || px(cs.opacity) === 0) return false; const r = el.getBoundingClientRect(); return r.width > 3 && r.height > 3; };
130
+ const els = [...document.body.querySelectorAll("*")].slice(0, MAX);
131
+ const sx = scrollX, sy = scrollY;
132
+ const page = (r) => ({ left: r.left + sx, right: r.right + sx, top: r.top + sy, bottom: r.bottom + sy });
133
+
134
+ // 12. Crowded heading: more space below a heading than above it means it reads as belonging to what precedes it.
135
+ const boxes = [];
136
+ for (const el of els) {
137
+ if (!vis(el)) continue;
138
+ // A heading heads content. A button or link below it is an action, so it does not set the heading's spacing.
139
+ if (el.closest("button, a, [role='button'], input, select, textarea")) continue;
140
+ const media = /^(IMG|SVG|VIDEO|CANVAS|PICTURE)$/i.test(el.tagName);
141
+ if (!media && ![...el.childNodes].some((n) => n.nodeType === 3 && n.textContent.trim())) continue;
142
+ boxes.push({ el, ...page(el.getBoundingClientRect()) });
143
+ }
144
+ const overlapX = (a, b) => Math.min(a.right, b.right) - Math.max(a.left, b.left) > 8;
145
+ for (const h of document.querySelectorAll("h2, h3, h4")) {
146
+ if (!vis(h) || !(h.innerText || "").trim() || h.closest("nav, footer, table, header")) continue;
147
+ // A card title sits inside a small filled box; its spacing is the card's, not the page's.
148
+ let small = false;
149
+ for (let p = h.parentElement; p && p !== document.body; p = p.parentElement) {
150
+ const cs = getComputedStyle(p);
151
+ if (!clear(cs.backgroundColor) || px(cs.borderTopWidth) > 0 || cs.boxShadow !== "none") { small = p.getBoundingClientRect().height < 200; break; }
152
+ }
153
+ if (small) continue;
154
+ const hb = page(h.getBoundingClientRect());
155
+ // What a heading heads is inside its own block: the nearest section, article, list item, or filled/bordered box.
156
+ // Without this, a heading with nothing under it reached into the next card.
157
+ let scope = document.body;
158
+ for (let p = h.parentElement; p && p !== document.body; p = p.parentElement) {
159
+ const cs = getComputedStyle(p);
160
+ if (/^(SECTION|ARTICLE|LI|ASIDE|FIGURE)$/.test(p.tagName) || !clear(cs.backgroundColor) || px(cs.borderTopWidth) > 0 || cs.boxShadow !== "none") { scope = p; break; }
161
+ }
162
+ let above = null, below = null;
163
+ for (const b of boxes) {
164
+ if (h.contains(b.el) || b.el.contains(h) || !overlapX(b, hb)) continue;
165
+ if (b.bottom <= hb.top + 1 && (!above || b.bottom > above.bottom)) above = b;
166
+ if (b.top >= hb.bottom - 1 && scope.contains(b.el) && (!below || b.top < below.top)) below = b;
167
+ }
168
+ if (!above || !below) continue;
169
+ const up = hb.top - above.bottom, down = below.top - hb.bottom;
170
+ if (down < 6 || down > 160) continue;
171
+ if (up < 0.75 * down && down - up >= 12) out.crowded.push({ el: name(h), text: (h.innerText || "").trim().slice(0, 18), up: Math.round(up), down: Math.round(down) });
172
+ }
173
+
174
+ // 13. Cramped box: text closer to the edge of its filled or bordered box than the even-padding floor.
175
+ for (const el of els) {
176
+ const r = el.getBoundingClientRect();
177
+ if (r.width <= 100 || r.height <= 30 || r.width > innerWidth * 0.9) continue;
178
+ const cs = getComputedStyle(el);
179
+ if (cs.display === "inline" || /auto|scroll/.test(cs.overflowX + cs.overflowY) || !vis(el)) continue;
180
+ const bw = ["Top", "Right", "Bottom", "Left"].map((k) => px(cs["border" + k + "Width"]));
181
+ const inked = (k) => bw[k] >= 1 && !clear(cs["border" + ["Top", "Right", "Bottom", "Left"][k] + "Color"]);
182
+ let under = "rgb(255, 255, 255)";
183
+ for (let p = el.parentElement; p; p = p.parentElement) { const c = getComputedStyle(p).backgroundColor; if (!clear(c)) { under = c; break; } }
184
+ const filled = !clear(cs.backgroundColor) && cs.backgroundColor !== under;
185
+ if (!filled && !(inked(1) && inked(3))) continue;
186
+ let L = Infinity, T = Infinity, R = -Infinity, B = -Infinity, fs = px(cs.fontSize) || 16;
187
+ const walk = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
188
+ for (let t = walk.nextNode(); t; t = walk.nextNode()) {
189
+ const host = t.parentElement;
190
+ if (!t.textContent.trim() || !host || host.closest("svg") || !vis(host)) continue;
191
+ let nested = false;
192
+ for (let p = host; p && p !== el; p = p.parentElement) {
193
+ const ps = getComputedStyle(p);
194
+ if (/absolute|fixed/.test(ps.position) || (!clear(ps.backgroundColor) && ps.backgroundColor !== cs.backgroundColor) || (px(ps.borderTopWidth) >= 1 && px(ps.borderLeftWidth) >= 1)) { nested = true; break; }
195
+ }
196
+ if (nested) continue;
197
+ const rg = document.createRange(); rg.selectNodeContents(t);
198
+ const hf = px(getComputedStyle(host).fontSize) || 16, trim = hf >= 40 ? 0.2 * hf : 0;
199
+ for (const q of rg.getClientRects()) { if (!q.width || !q.height) continue; L = Math.min(L, q.left); T = Math.min(T, q.top + trim); R = Math.max(R, q.right); B = Math.max(B, q.bottom - trim); fs = hf; }
200
+ }
201
+ if (L === Infinity) continue;
202
+ const side = Math.max(8, Math.min(0.5 * fs, 24)) - 0.5, end = Math.max(4, Math.min(0.3 * fs, 12)) - 0.5;
203
+ const inset = { left: L - (r.left + bw[3]), right: r.right - bw[1] - R, top: T - (r.top + bw[0]), bottom: r.bottom - bw[2] - B };
204
+ // A negative inset means the text sits OUTSIDE the box (an overflowing or scrolling container), which is an
205
+ // overflow matter and not a padding one; only text inside the box but too close counts.
206
+ const short = Object.entries(inset).filter(([k, v]) => v >= 0 && v < (k === "left" || k === "right" ? side : end));
207
+ if (short.length) out.cramped.push({ el: name(el), sides: short.map(([k, v]) => k + " " + Math.round(v) + "px").join(", ") });
208
+ }
209
+
210
+ // 14. Covered text: sample what is painted at the middle of each text run, scrolling through the page.
211
+ const pinned = (el) => { for (let p = el; p && p !== document.body; p = p.parentElement) if (/fixed|sticky/.test(getComputedStyle(p).position)) return true; return false; };
212
+ const unseen = (el) => { const cs = getComputedStyle(el); return px(cs.opacity) < 0.05 || (clear(cs.backgroundColor) && cs.backgroundImage === "none" && !(el.innerText || "").trim() && !/^(IMG|SVG|CANVAS|VIDEO|PICTURE)$/i.test(el.tagName) && !el.querySelector("img, svg, canvas, video")); };
213
+ // Text scrolled or clipped out of its own container is hidden, not covered: whatever the point lands on is the
214
+ // next thing on the page.
215
+ const clippedAt = (host, x, y) => {
216
+ for (let p = host; p && p !== document.body; p = p.parentElement) {
217
+ const ps = getComputedStyle(p);
218
+ if (/auto|scroll|hidden|clip/.test(ps.overflowX + ps.overflowY)) { const b = p.getBoundingClientRect(); if (x < b.left || x > b.right || y < b.top || y > b.bottom) return true; }
219
+ }
220
+ return false;
221
+ };
222
+ const paints = (el) => { const cs = getComputedStyle(el); return !clear(cs.backgroundColor) || cs.backgroundImage !== "none" || /^(IMG|SVG|CANVAS|VIDEO|PICTURE)$/i.test(el.tagName) || [...el.childNodes].some((n) => n.nodeType === 3 && n.textContent.trim()); };
223
+ const runs = [];
224
+ const tw = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
225
+ for (let t = tw.nextNode(); t && runs.length < 1500; t = tw.nextNode()) {
226
+ const host = t.parentElement;
227
+ if (!t.textContent.trim() || !host || host.closest("script, style, noscript, svg, [aria-hidden='true'], nav, header, dialog, [popover], [role='menu'], details:not([open]), [hidden]")) continue;
228
+ if (vis(host) && !pinned(host)) runs.push({ t, host });
229
+ }
230
+ const H = document.documentElement.scrollHeight;
231
+ for (let y = 0; y < H && out.covered.length < 3; y += Math.max(200, innerHeight - 100)) {
232
+ window.scrollTo(0, y);
233
+ await new Promise((res) => requestAnimationFrame(() => requestAnimationFrame(res)));
234
+ for (const { t, host } of runs) {
235
+ if (out.covered.length >= 3) break;
236
+ const rg = document.createRange(); rg.selectNodeContents(t);
237
+ for (const q of rg.getClientRects()) {
238
+ if (q.width < 6 || q.height < 6) continue;
239
+ const cx = q.left + q.width / 2, cy = q.top + q.height / 2;
240
+ if (cy < 0 || cy >= innerHeight || cx < 0 || cx >= innerWidth) continue;
241
+ const ghost = getComputedStyle(host).pointerEvents === "none";
242
+ if (ghost) host.style.setProperty("pointer-events", "auto", "important");
243
+ const top = document.elementFromPoint(cx, cy);
244
+ if (ghost) host.style.removeProperty("pointer-events");
245
+ if (!top || top === host || host.contains(top) || top.contains(host) || pinned(top) || unseen(top)) continue;
246
+ if (clippedAt(host, cx, cy)) continue;
247
+ // A transparent wrapper (a calendar's nav row, a click-catching layer) sits over text without painting
248
+ // anything there. It is covering only if something it contains paints at that point.
249
+ if (!paints(top)) {
250
+ let hit = false;
251
+ for (const d of top.querySelectorAll("*")) {
252
+ if (!paints(d)) continue;
253
+ const b = d.getBoundingClientRect();
254
+ if (cx >= b.left && cx <= b.right && cy >= b.top && cy <= b.bottom) { hit = true; break; }
255
+ }
256
+ if (!hit) continue;
257
+ }
258
+ // elementFromPoint can return an element whose own box does not contain the point (a pseudo-element or an
259
+ // overflowing child). Count it only if it paints something there.
260
+ const tr = top.getBoundingClientRect();
261
+ if (!(cx >= tr.left && cx <= tr.right && cy >= tr.top && cy <= tr.bottom)) {
262
+ const bare = (ps) => /^(none|normal)$/.test(ps.content) || (clear(ps.backgroundColor) && ps.backgroundImage === "none");
263
+ if (bare(getComputedStyle(top, "::after")) && bare(getComputedStyle(top, "::before"))) continue;
264
+ }
265
+ out.covered.push({ el: name(top), text: t.textContent.trim().slice(0, 16) });
266
+ break;
267
+ }
268
+ }
269
+ }
270
+ window.scrollTo(sx, sy);
271
+
272
+ // 17. A region that scrolls sideways must be reachable by keyboard and have a role and a name. Content that
273
+ // needs two-dimensional layout may scroll (a table, a code block), but only inside a region a person can find.
274
+ out.regions = [];
275
+ for (const el of els) {
276
+ if (el === document.body || el === document.documentElement || !vis(el)) continue;
277
+ const cs = getComputedStyle(el);
278
+ if (!/auto|scroll/.test(cs.overflowX) || el.scrollWidth <= el.clientWidth + 1) continue;
279
+ const focusable = el.tabIndex >= 0 || !!el.querySelector("a[href], button, input, select, textarea, [tabindex]:not([tabindex='-1'])");
280
+ const named = !!(el.getAttribute("aria-label") || el.getAttribute("aria-labelledby"));
281
+ const role = el.getAttribute("role");
282
+ const missing = [];
283
+ if (!focusable) missing.push("keyboard focus (tabindex=0)");
284
+ // Any real role is enough (a tab list, a toolbar, a table); a bare div needs role=region. Every one needs a name.
285
+ const hasRole = role && !/^(none|presentation)$/i.test(role);
286
+ if (!hasRole) missing.push("role=region and a name");
287
+ else if (!named) missing.push("a name (aria-label)");
288
+ if (missing.length) out.regions.push({ el: name(el), missing: [...new Set(missing)].join(" and ") });
289
+ }
290
+
291
+ // 15. Wrapped or clipped button label: a control whose label does not fit its container.
292
+ for (const el of els) {
293
+ const isButton = el.tagName === "BUTTON" || el.getAttribute("role") === "button" || (el.tagName === "A" && /\bbtn\b|\bbutton\b/i.test(typeof el.className === "string" ? el.className : ""));
294
+ if (!isButton || !vis(el)) continue;
295
+ const text = (el.textContent || "").trim();
296
+ // A label is short and flows inline. A role=button that holds paragraphs, a heading or a list (a dropzone, a
297
+ // card that opens) is a surface, and wrapping is what its text is supposed to do.
298
+ if (!text || text.length > 60) continue;
299
+ if ([...el.querySelectorAll("*")].some((d) => !d.closest("svg") && /^(block|flex|grid|list-item|table)$/.test(getComputedStyle(d).display))) continue;
300
+ const cs = getComputedStyle(el);
301
+ const lh = px(cs.lineHeight) || px(cs.fontSize) * 1.4;
302
+ const tops = [];
303
+ const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
304
+ for (let n = walker.nextNode(); n; n = walker.nextNode()) {
305
+ const host = n.parentElement;
306
+ if (!n.textContent.trim() || !host || host.closest("svg") || host.closest("[aria-hidden='true'], .sr-only")) continue;
307
+ const rg = document.createRange(); rg.selectNodeContents(n);
308
+ for (const q of rg.getClientRects()) if (q.width > 0 && q.height > 0) tops.push(q.top);
309
+ }
310
+ tops.sort((a, b) => a - b);
311
+ let lines = tops.length ? 1 : 0;
312
+ for (let i = 1; i < tops.length; i++) if (tops[i] - tops[i - 1] > lh * 0.6) lines++;
313
+ const clipped = /hidden|clip/.test(cs.overflowX) && el.scrollWidth > el.clientWidth + 1;
314
+ if (lines > 1 || clipped) out.wrapped.push({ el: name(el), text: text.slice(0, 32), lines, clipped });
315
+ }
316
+ return out;
317
+ }
318
+
93
319
  // probe() is serialized into the page, so it can't import SLOP_EMOJI. The source is
94
320
  // injected before serializing (see probeSource), keeping one definition of the set.
95
321
  /** The source of probe() with the emoji set inlined, ready for page.evaluate. */
@@ -97,6 +323,11 @@ export function probeSource() {
97
323
  return `(() => { const EMOJI_SOURCE = ${JSON.stringify(SLOP_EMOJI.source)}; return (${probe.toString()})(); })()`;
98
324
  }
99
325
 
326
+ /** The source of probeLayout(), ready for page.evaluate (it returns a promise). */
327
+ export function probeLayoutSource() {
328
+ return `(${probeLayout.toString()})()`;
329
+ }
330
+
100
331
  /** Turn one width's facts into findings. Pure. */
101
332
  export function classify(facts, width) {
102
333
  const out = [];
@@ -111,6 +342,13 @@ export function classify(facts, width) {
111
342
  for (const p of (facts.pulse || []).slice(0, 3)) add("pulsing-status-dot", p.el);
112
343
  if ((facts.copy || []).length) add("placeholder-copy", facts.copy.join(", "));
113
344
  for (const i of facts.images || []) add("placeholder-image", `${i.el}: ${i.src}`);
345
+ // Layout tells. One crowded heading is a judgment call; two on a page is a pattern (Hallmark's threshold).
346
+ if ((facts.crowded || []).length >= 2) add("crowded-heading", facts.crowded.slice(0, 2).map((c) => `${c.el} "${c.text}" ${c.up}px above, ${c.down}px below`).join("; "));
347
+ for (const c of (facts.cramped || []).slice(0, 3)) add("cramped-box", `${c.el}: ${c.sides}`);
348
+ for (const c of (facts.covered || []).slice(0, 3)) add("covered-text", `${c.el} over "${c.text}"`);
349
+ for (const w of (facts.wrapped || []).slice(0, 3)) add("wrapped-button-label", `${w.el} "${w.text}"${w.clipped ? " clipped" : ""}${w.lines > 1 ? ` on ${w.lines} lines` : ""}`);
350
+ if (facts.zoom) add("zoom-blocked", `viewport content "${facts.zoom.content}"`);
351
+ for (const r of (facts.regions || []).slice(0, 3)) add("unreachable-scroll-region", `${r.el} scrolls sideways without ${r.missing}`);
114
352
  const o = facts.overflow;
115
353
  if (o && o.scrollWidth > o.innerWidth + 1) add("horizontal-overflow", `${o.scrollWidth}px wide in a ${o.innerWidth}px window`);
116
354
  return out;
@@ -0,0 +1,47 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * lint-arbitrary-tokens: `rounded-[--radius-pill]` and friends.
4
+ *
5
+ * In Tailwind v4 a square-bracket arbitrary value is emitted verbatim, so `rounded-[--radius-pill]`
6
+ * compiles to `border-radius: --radius-pill`, which is not valid CSS: a bare custom-property NAME is
7
+ * not a value. The browser drops the declaration and the element renders with no radius at all.
8
+ * Nothing errors. The class exists, the build passes, the rule is in the stylesheet, and the element
9
+ * is simply square. lint-unknown-classes passes it (the class compiles) and lint-css-vars passes it
10
+ * (there is no var() to resolve), so this shape needs its own check.
11
+ *
12
+ * The correct spellings are `rounded-[var(--radius-pill)]` or Tailwind v4's shorthand
13
+ * `rounded-(--radius-pill)`. This lint requires the explicit `var(...)` form, because it reads
14
+ * correctly to someone who does not know the shorthand exists.
15
+ *
16
+ * node packages/core/scripts/lint-arbitrary-tokens.mjs [--warn | --init | --ratchet] [paths]
17
+ */
18
+ import { codeAndClasses } from "./lib/source-scan.mjs";
19
+ import { runLint } from "./lib/lab-lint.mjs";
20
+ import { isMain } from "./lib/counted-lint.mjs";
21
+
22
+ /** A utility ending in -[--token]: brackets wrapping a bare custom property. */
23
+ const BAD = /[a-z][a-z-]*-\[--[a-z0-9-]+\]/gi;
24
+
25
+ export function findBareTokens(src) {
26
+ const findings = [];
27
+ codeAndClasses(src)
28
+ .split("\n")
29
+ .forEach((line, i) => {
30
+ for (const m of line.matchAll(BAD)) {
31
+ const token = m[0].slice(m[0].indexOf("[") + 1, -1);
32
+ findings.push({ line: i + 1, text: `${m[0]} -> ${m[0].replace(`[${token}]`, `[var(${token})]`)}` });
33
+ }
34
+ });
35
+ return findings;
36
+ }
37
+
38
+ if (isMain(import.meta.url)) {
39
+ process.exit(
40
+ runLint({
41
+ ruleId: "arbitrary-tokens",
42
+ bin: "bads-lint-arbitrary-tokens",
43
+ detect: (src) => findBareTokens(src),
44
+ fix: "A bracketed bare custom property compiles to invalid CSS and the style silently does not apply. Wrap it: `[var(--token)]`.",
45
+ }),
46
+ );
47
+ }
@@ -0,0 +1,63 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * lint-component-token-refs.mjs: a component token's colour must come from the SEMANTIC layer.
4
+ *
5
+ * The three layers are primitive (a value: blue-600), semantic (an intent: action.primary), and component (a use:
6
+ * button.primary.background). The layering only pays off if each layer points one step down. A component token
7
+ * that points straight at a primitive, or holds a raw hex, skips the semantic layer, so a rebrand that re-points
8
+ * `action.primary` leaves that component behind, and dark mode (which re-maps semantics, not primitives) breaks
9
+ * for it. Today every component colour token goes through `color.semantic`; this keeps it that way.
10
+ *
11
+ * RULE. In tokens.json under `component`, any token whose $type is "color" must have a $value that is either a
12
+ * reference to `{color.semantic.*}` or a CSS colour keyword (transparent, currentColor, inherit). A reference to
13
+ * any other colour path, or a literal colour, fails. Non-colour tokens (radius, spacing, shadow) point at their
14
+ * scales and are not checked: those scales are the semantic layer for those types.
15
+ *
16
+ * Pattern from Jens Merkel, "Design token naming that scales" (2026): component tokens reference semantic tokens,
17
+ * never primitives.
18
+ *
19
+ * Strict (exits 1): it has no violations to grandfather. Escape hatch: none, because the fix is always to add or
20
+ * pick a semantic token.
21
+ *
22
+ * pnpm lint:component-token-refs
23
+ */
24
+ import { readFileSync } from "node:fs";
25
+ import { join } from "node:path";
26
+
27
+ const KEYWORDS = new Set(["transparent", "currentcolor", "inherit"]);
28
+
29
+ /** Every violation as { path, value, why }. `tokens` is the parsed tokens.json. */
30
+ export function findViolations(tokens) {
31
+ const out = [];
32
+ (function walk(node, path) {
33
+ for (const [key, v] of Object.entries(node ?? {})) {
34
+ if (key.startsWith("$") || !v || typeof v !== "object") continue;
35
+ if (!("$value" in v)) {
36
+ walk(v, [...path, key]);
37
+ continue;
38
+ }
39
+ if (v.$type !== "color") continue;
40
+ const value = String(v.$value).trim();
41
+ const here = ["component", ...path, key].join(".");
42
+ if (KEYWORDS.has(value.toLowerCase())) continue;
43
+ const ref = /^\{([^}]+)\}$/.exec(value);
44
+ if (!ref) out.push({ path: here, value, why: "a literal colour; reference a color.semantic token" });
45
+ else if (!ref[1].startsWith("color.semantic.")) out.push({ path: here, value, why: `points at ${ref[1].split(".").slice(0, 2).join(".")}, not the semantic layer` });
46
+ }
47
+ })(tokens.component, []);
48
+ return out;
49
+ }
50
+
51
+ function main() {
52
+ const file = join(process.cwd(), "packages/core/src/tokens.json");
53
+ const violations = findViolations(JSON.parse(readFileSync(file, "utf8")));
54
+ if (violations.length) {
55
+ console.error(`✗ component-token-refs: ${violations.length} component colour token(s) skip the semantic layer:\n`);
56
+ for (const v of violations) console.error(` ${v.path} = ${v.value}\n ${v.why}`);
57
+ console.error("\nFix: reference a {color.semantic.*} token. If none says what you mean, add a semantic token first.");
58
+ process.exit(1);
59
+ }
60
+ console.log("✓ component-token-refs: every component colour token goes through color.semantic");
61
+ }
62
+
63
+ if (import.meta.url === `file://${process.argv[1]}`) main();
@@ -0,0 +1,114 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * lint-content-hierarchy: semantic hierarchy is decided before typography, and two roles never share one treatment.
4
+ *
5
+ * Enforces layer-6-patterns-and-rules/content-hierarchy.md.
6
+ *
7
+ * WHY. A card's own title and the titles of the two options inside it rendered at the SAME font size.
8
+ * Nothing looked broken: both were legible, both correctly bold. What was lost is containment. The
9
+ * card's subject and the options inside it read as three equal headings rather than one statement with
10
+ * two choices under it. It is a structural failure with no visual symptom, which is exactly the kind a
11
+ * lint earns its place on.
12
+ *
13
+ * WHAT IT ASSERTS
14
+ * R1 A component that names itself a title or a heading must RENDER one. `<span className="text-sm
15
+ * font-semibold">` is not a heading, and the moment it has to be `<h3>` the author is forced to
16
+ * choose a level, which is the point. Deciding the level is the work; the size is the consequence.
17
+ * R2 Two different heading levels in one file must not share a type-size class.
18
+ * R3 Heading levels must not skip. h2 straight to h4 leaves a reader (and a screen reader) guessing.
19
+ * R4 One primary heading per file. Two h1s means the surface is about two things.
20
+ * R5 One heading level must not carry two different type sizes ("same role = same treatment").
21
+ *
22
+ * WHAT IT DELIBERATELY DOES NOT ASSERT. "Same role = same treatment" for peers (two cards in a row, two
23
+ * rows in a list) is not checked: peers are nearly always emitted from one `.map()` over one component,
24
+ * so they agree by construction, and the static signal for a hand-written pair is too weak to be worth
25
+ * the false positives.
26
+ *
27
+ * ESCAPE HATCH. R2 and R5 compare file-wide, so a file holding two genuinely separate documents (a docs
28
+ * page wrapping a simulated screen whose card titles belong to the simulation) trips them. Put
29
+ * `hierarchy-ok: <reason>` on the heading's line or the line above. A bare marker does not count.
30
+ *
31
+ * node packages/core/scripts/lint-content-hierarchy.mjs [--warn | --init | --ratchet] [paths]
32
+ */
33
+ import { withoutComments } from "./lib/source-scan.mjs";
34
+ import { runLint, markedNear, lineAt } from "./lib/lab-lint.mjs";
35
+ import { isMain } from "./lib/counted-lint.mjs";
36
+
37
+ /**
38
+ * Tailwind type-size utilities, the size half of "treatment". The lookbehind excludes a
39
+ * breakpoint-prefixed size: `text-4xl md:text-5xl` is ONE treatment expressed responsively.
40
+ */
41
+ const SIZE = /(?<![\w:-])text-(xs|sm|base|lg|xl|[2-9]xl)\b/g;
42
+
43
+ /** Comments and template literals blanked, so prose explaining a rule can never trip it. */
44
+ const blankNonCode = (src) => withoutComments(src).replace(/`(?:[^`\\]|\\.)*`/g, (m) => m.replace(/[^\n]/g, " "));
45
+
46
+ export function findHierarchyProblems(raw) {
47
+ const src = blankNonCode(raw);
48
+ const rawLines = raw.split("\n");
49
+ const problems = [];
50
+ const add = (rule, line, what) => problems.push({ line, text: `[${rule}] ${what}` });
51
+
52
+ // R1: a component named *Title / *Heading must render a heading.
53
+ const decl = /(?:function|const)\s+([A-Z][A-Za-z0-9]*(?:Title|Heading)[A-Za-z0-9]*)\s*[=(]/g;
54
+ for (const m of src.matchAll(decl)) {
55
+ const rest = src.slice(m.index + 1);
56
+ const nextDecl = rest.search(/\n(?:export\s+)?(?:function|const)\s+[A-Z]/);
57
+ const body = rest.slice(0, nextDecl === -1 ? rest.length : nextDecl);
58
+ const name = m[1];
59
+ // shadcn-style primitives leave the heading level to the caller (Radix's Title renders its own).
60
+ if (/^(?:Card|Dialog|AlertDialog|Drawer|Sheet)Title$/.test(name)) continue;
61
+ const rendersHeading =
62
+ /<\s*h[1-6][\s>]/.test(body) ||
63
+ /`h\$\{/.test(raw.slice(m.index, m.index + body.length)) ||
64
+ /\bas\s*=\s*\{?["'`]?h[1-6]/.test(body) ||
65
+ /role\s*=\s*["']heading["']/.test(body) ||
66
+ /\bHeading\b\s*[\s/>]/.test(body) ||
67
+ // A wrapper that forwards to another *Title component: the level is that component's problem.
68
+ /<\s*[A-Z][A-Za-z0-9]*(?:Title|Heading)/.test(body);
69
+ if (!rendersHeading) add("R1", lineAt(src, m.index), `${name} is named a title but renders no heading element (a title that is a span has no level, so nothing forces a decision about where it sits)`);
70
+ }
71
+
72
+ // R2/R3/R4/R5: the heading elements actually present in this file.
73
+ const levels = new Map(); // level -> Set of size classes
74
+ const seen = [];
75
+ for (const m of src.matchAll(/<\s*h([1-6])\b([^>]*)>/g)) {
76
+ const level = Number(m[1]);
77
+ const line = lineAt(src, m.index);
78
+ if (markedNear(rawLines, line, "hierarchy-ok:")) continue;
79
+ seen.push({ level, line });
80
+ if (!levels.has(level)) levels.set(level, new Set());
81
+ for (const s of m[2].match(SIZE) ?? []) levels.get(level).add(s);
82
+ }
83
+ const firstLine = (pred) => seen.find(pred)?.line ?? 1;
84
+
85
+ const bySize = new Map();
86
+ for (const [level, sizes] of levels) {
87
+ for (const s of sizes) bySize.set(s, (bySize.get(s) ?? new Set()).add(level));
88
+ }
89
+ for (const [size, lv] of bySize) {
90
+ if (lv.size > 1) add("R2", firstLine((s) => lv.has(s.level)), `h${[...lv].sort().join(" and h")} both use "${size}" (two roles, one treatment)`);
91
+ }
92
+ const present = [...levels.keys()].sort((a, b) => a - b);
93
+ for (let i = 1; i < present.length; i++) {
94
+ if (present[i] - present[i - 1] > 1) add("R3", firstLine((s) => s.level === present[i]), `h${present[i - 1]} jumps straight to h${present[i]}`);
95
+ }
96
+ for (const [level, sizes] of levels) {
97
+ if (sizes.size > 1) add("R5", firstLine((s) => s.level === level), `h${level} uses ${[...sizes].sort().map((s) => `"${s}"`).join(" and ")} (same role, two treatments)`);
98
+ }
99
+ const h1s = seen.filter((s) => s.level === 1);
100
+ if (h1s.length > 1) add("R4", h1s[1].line, `${h1s.length} h1 elements in one file (a surface is about one thing)`);
101
+ return problems;
102
+ }
103
+
104
+ if (isMain(import.meta.url)) {
105
+ process.exit(
106
+ runLint({
107
+ ruleId: "content-hierarchy",
108
+ bin: "bads-lint-content-hierarchy",
109
+ tsxOnly: true,
110
+ detect: (src) => findHierarchyProblems(src),
111
+ fix: "Decide the structure first: name the one primary heading, then what is subordinate to it, then which things are peers. The type scale follows. Genuine exceptions: `{/* hierarchy-ok: <why> */}`. See layer-6-patterns-and-rules/content-hierarchy.md.",
112
+ }),
113
+ );
114
+ }
@@ -0,0 +1,72 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * lint-control-baseline: a button beside text in a row aligned to the top.
4
+ *
5
+ * WHY. A tap target is at least 44px tall; a line of label text is about 20px. A button centres its
6
+ * own label, so in a row set to `items-start` the two BOXES line up at the top and the button's word
7
+ * lands (44 - 20) / 2 = 12px below the line it belongs to. A constant offset is a rule being followed,
8
+ * not a mistake being made, which is why it is easy to miss and always the same.
9
+ *
10
+ * The trap is that `items-start` is the obviously correct choice: the label can wrap to two lines, so
11
+ * centring would float the button in the middle of a paragraph. `items-start` fixes the wrapping case
12
+ * and silently breaks the alignment case, and nothing complains, because both boxes really are flush
13
+ * at the top.
14
+ *
15
+ * WHAT IT FLAGS. A flex ROW (not a column) set to `items-start` with a button among its children.
16
+ *
17
+ * THE FIX is `items-baseline`. It aligns the TEXT rather than the boxes, so it is right whether the
18
+ * label is one line or four, and the button keeps its 44px. It is NOT a top margin on the button:
19
+ * that is a hand-tuned nudge that is right at one size and wrong at every other, and pulling a 44px
20
+ * target upward clips the thing it exists for.
21
+ *
22
+ * ESCAPE HATCH. `control-baseline-ok: <reason>` on the line directly above the row. A genuine case:
23
+ * a dismiss X meant to sit level with the top of a block, not with a line of text.
24
+ *
25
+ * Children are found by indentation (a child is more indented than the tag that opened it). That is
26
+ * crude next to a parser and right for formatter-written code.
27
+ *
28
+ * node packages/core/scripts/lint-control-baseline.mjs [--warn | --init | --ratchet] [paths]
29
+ */
30
+ import { codeAndClasses } from "./lib/source-scan.mjs";
31
+ import { runLint, markedNear } from "./lib/lab-lint.mjs";
32
+ import { isMain } from "./lib/counted-lint.mjs";
33
+
34
+ /** Anything that renders as a control tall enough to out-measure a line of text. */
35
+ const CONTROLS = /<(Button|CloseButton|ActionButton|IconButton|button)\b/;
36
+
37
+ export function findTopAlignedControls(src) {
38
+ const rawLines = src.split("\n");
39
+ const lines = codeAndClasses(src).split("\n");
40
+ const findings = [];
41
+ for (let i = 0; i < lines.length; i++) {
42
+ const line = lines[i];
43
+ if (!/\bitems-start\b/.test(line) || /\bflex-col\b/.test(line)) continue;
44
+ const indent = line.length - line.trimStart().length;
45
+ let found = null;
46
+ for (let j = i + 1; j < lines.length; j++) {
47
+ const child = lines[j];
48
+ if (!child.trim()) continue;
49
+ if (child.length - child.trimStart().length <= indent) break;
50
+ if (CONTROLS.test(child)) {
51
+ found = j + 1;
52
+ break;
53
+ }
54
+ }
55
+ if (!found) continue;
56
+ if (markedNear(rawLines, i + 1, "control-baseline-ok:", { lines: 1 })) continue;
57
+ findings.push({ line: i + 1, text: `items-start row with a button on line ${found} (its label sits ~12px below the text beside it)` });
58
+ }
59
+ return findings;
60
+ }
61
+
62
+ if (isMain(import.meta.url)) {
63
+ process.exit(
64
+ runLint({
65
+ ruleId: "control-baseline",
66
+ bin: "bads-lint-control-baseline",
67
+ tsxOnly: true,
68
+ detect: (src) => findTopAlignedControls(src),
69
+ fix: "Use `items-baseline`, or mark the line above `control-baseline-ok: <why>`. Do not nudge the button with a top margin.",
70
+ }),
71
+ );
72
+ }
@@ -0,0 +1,60 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * lint-copy-punctuation: the punctuation mistakes that read as unfinished typing, caught where the copy lives.
4
+ *
5
+ * language-lint already enforces BADS-3a (banned terms) and BADS-3b (no em dash). This covers two
6
+ * adjacent mistakes it does not:
7
+ *
8
+ * P2 Three periods where an ellipsis belongs. `…` (U+2026), never `...`. Three periods are wider,
9
+ * break awkwardly at the end of a line, and read as unfinished typing.
10
+ * P3 A literal `\uXXXX` escape sitting in copy: the six characters, not the character they stand
11
+ * for. Nobody types this by hand. It comes from writing TSX through a script or a heredoc, and it
12
+ * renders to the reader exactly as written while every other check passes.
13
+ *
14
+ * WHAT COUNTS AS COPY is defined once in lib/copy-strings.mjs: JSX text, the values of copy-carrying
15
+ * props and keys, and the items of copy lists. Comments are blanked first. It reads `.ts` as well as
16
+ * `.tsx`, because a copy file (`copy.ts`, a scenario file) is where the most-read strings often live.
17
+ *
18
+ * ESCAPE HATCH. `copy-ok: <reason>` on the line or the line above, for strings read by the team rather
19
+ * than by a user. The reason is the mechanism.
20
+ *
21
+ * node packages/core/scripts/lint-copy-punctuation.mjs [--warn | --init | --ratchet] [paths]
22
+ */
23
+ import { blankComments, copyStrings } from "./lib/copy-strings.mjs";
24
+ import { runLint, markedNear, lineAt } from "./lib/lab-lint.mjs";
25
+ import { isMain } from "./lib/counted-lint.mjs";
26
+
27
+ const RULES = [
28
+ { id: "P2", test: (t) => (t.includes("...") ? "..." : null), message: "three periods where an ellipsis belongs; use the glyph … (U+2026)" },
29
+ {
30
+ id: "P3",
31
+ test: (t) => t.match(/\\u[0-9a-fA-F]{4}/)?.[0] ?? null,
32
+ message: "a literal \\uXXXX escape in copy: the escape sequence as six characters, not the character it stands for",
33
+ },
34
+ ];
35
+
36
+ export function findCopyPunctuation(raw) {
37
+ const rawLines = raw.split("\n");
38
+ const src = blankComments(raw);
39
+ const findings = [];
40
+ for (const { text, index } of copyStrings(src)) {
41
+ const line = lineAt(src, index);
42
+ if (markedNear(rawLines, line, "copy-ok:")) continue;
43
+ for (const rule of RULES) {
44
+ if (!rule.test(text)) continue;
45
+ findings.push({ line, text: `[${rule.id}] ${rule.message}: "${text.length > 80 ? `${text.slice(0, 80)}…` : text}"` });
46
+ }
47
+ }
48
+ return findings;
49
+ }
50
+
51
+ if (isMain(import.meta.url)) {
52
+ process.exit(
53
+ runLint({
54
+ ruleId: "copy-punctuation",
55
+ bin: "bads-lint-copy-punctuation",
56
+ detect: (src) => findCopyPunctuation(src),
57
+ fix: "Rewrite it. If the string is read by the team rather than by a user: `{/* copy-ok: <why> */}` on the line above.",
58
+ }),
59
+ );
60
+ }