@behavioral-agentic-design-system/core 0.40.0 → 0.45.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/package.json +41 -9
- package/scripts/a11y-lint.cjs +66 -3
- package/scripts/check-spec.mjs +73 -0
- package/scripts/deal-directions.mjs +186 -0
- package/scripts/health-report.mjs +23 -3
- package/scripts/lib/counted-lint.mjs +100 -0
- package/scripts/lib/marketing-library.mjs +129 -0
- package/scripts/lib/on-system.mjs +249 -0
- package/scripts/lib/random.mjs +22 -0
- package/scripts/lib/spec-parse.d.mts +25 -0
- package/scripts/lib/spec-parse.mjs +188 -0
- package/scripts/lib/tells.mjs +128 -0
- package/scripts/lint-css-vars.mjs +175 -0
- package/scripts/lint-html-nesting.mjs +116 -0
- package/scripts/lint-live-ctas.mjs +138 -0
- package/scripts/lint-slop.mjs +25 -1
- package/scripts/on-system-score.mjs +95 -0
- package/scripts/slop-rules.mjs +1 -1
- package/scripts/source-images.mjs +180 -0
- package/scripts/ux-tells.mjs +78 -0
- package/scripts/wcag-audit.cjs +72 -5
- package/src/api/brand-colors.ts +3 -0
- package/src/api/brand-fonts.ts +3 -0
- package/src/api/brand-mark.ts +6 -1
- package/src/api/dev-write-guard.ts +53 -0
- package/src/api/layers/file.ts +7 -4
- package/src/api/onboarding-extract.ts +85 -30
- package/src/api/onboarding.ts +3 -0
- package/src/api/save-tokens.ts +3 -0
- package/src/app/layout.tsx +6 -0
- package/src/app/opengraph-image.tsx +5 -0
- package/src/app/preview/canvas/page.tsx +12 -0
- package/src/app/preview/components/page.tsx +2003 -2
- package/src/app/preview/studio/blank-screen.tsx +143 -0
- package/src/app/preview/studio/page.tsx +7 -0
- package/src/app/shell.tsx +168 -49
- package/src/components/Foundations/Motion.stories.tsx +1 -0
- package/src/components/canvas/canvas.tsx +458 -0
- package/src/components/canvas/layout.ts +72 -0
- package/src/components/canvas/parse-canvas.ts +32 -0
- package/src/components/canvas/sample.ts +90 -0
- package/src/components/canvas/spec-frame.tsx +43 -0
- package/src/components/canvas/types.ts +33 -0
- package/src/components/customize/design-controls.tsx +16 -1
- package/src/components/docs-tab.tsx +7 -7
- package/src/components/home-recent.tsx +73 -0
- package/src/components/home-tab.tsx +13 -13
- package/src/components/layers-tab.tsx +2 -2
- package/src/components/markdown-preview.tsx +60 -12
- package/src/components/studio/control-panel.tsx +299 -0
- package/src/components/studio/control-row.tsx +77 -0
- package/src/components/studio/preview-frame.tsx +165 -0
- package/src/components/studio/preview-pane.tsx +247 -0
- package/src/components/studio/studio.tsx +158 -0
- package/src/components/studio/types.ts +218 -0
- package/src/components/studio/use-studio-tweaks.ts +128 -0
- package/src/components/studio/use-studio-view-state.ts +72 -0
- package/src/components/ui/anchor.tsx +37 -3
- package/src/components/ui/attachment.tsx +211 -0
- package/src/components/ui/autocomplete.tsx +1 -1
- package/src/components/ui/chart.tsx +3 -0
- package/src/components/ui/code.tsx +1 -1
- package/src/components/ui/color-picker.tsx +21 -5
- package/src/components/ui/data-table.tsx +64 -3
- package/src/components/ui/date-field.tsx +1 -1
- package/src/components/ui/editable.tsx +1 -0
- package/src/components/ui/faceted-filter.tsx +187 -0
- package/src/components/ui/gauge-chart.tsx +252 -0
- package/src/components/ui/heatmap.tsx +256 -0
- package/src/components/ui/index.ts +9 -0
- package/src/components/ui/infinite-scroll.tsx +103 -0
- package/src/components/ui/inline-edit.tsx +175 -0
- package/src/components/ui/json-input.tsx +351 -0
- package/src/components/ui/month-picker.tsx +1 -1
- package/src/components/ui/navigation-progress.tsx +281 -0
- package/src/components/ui/number-input.tsx +27 -7
- package/src/components/ui/otp-input.tsx +208 -0
- package/src/components/ui/password-input.tsx +2 -1
- package/src/components/ui/password-strength-input.tsx +288 -0
- package/src/components/ui/phone-input.tsx +274 -0
- package/src/components/ui/pill.tsx +140 -0
- package/src/components/ui/popover.tsx +27 -4
- package/src/components/ui/scroll-progress.tsx +100 -0
- package/src/components/ui/search-input.tsx +1 -1
- package/src/components/ui/snackbar.tsx +393 -0
- package/src/components/ui/sortable-list.tsx +342 -0
- package/src/components/ui/squircle.tsx +1 -1
- package/src/components/ui/table.tsx +1 -1
- package/src/components/ui/tags-input.tsx +1 -1
- package/src/components/ui/timer.tsx +1 -0
- package/src/components/ui/tour.tsx +1 -3
- package/src/components/ui/transfer-list.tsx +13 -26
- package/src/components/ui/week-picker.tsx +1 -1
- package/src/components/ui/year-picker.tsx +1 -1
- package/src/data/component-added.json +958 -0
- package/src/data/docs-index.ts +36 -0
- package/src/hooks/use-global-mono-font.ts +1 -0
- package/src/hooks/use-global-primary-color.ts +1 -0
- package/src/hooks/use-global-sans-font.ts +1 -0
- package/src/hooks/use-global-serif-font.ts +1 -0
- package/src/hooks/use-global-type-scale.ts +17 -2
- package/src/hooks/use-mobile.ts +2 -0
- package/src/hooks/use-sync-type-scale.ts +7 -11
- package/src/lib/clamp.ts +2 -0
- package/src/lib/spec-parse.ts +4 -0
- package/src/lib/svg-sanitize.ts +19 -9
- package/src/stories/Anchor.stories.tsx +54 -0
- package/src/stories/Attachment.stories.tsx +189 -0
- package/src/stories/Autocomplete.stories.tsx +2 -0
- package/src/stories/Canvas.stories.tsx +45 -0
- package/src/stories/Chart.stories.tsx +4 -0
- package/src/stories/Code.stories.tsx +1 -0
- package/src/stories/ColorPicker.stories.tsx +41 -0
- package/src/stories/DataTable.stories.tsx +30 -0
- package/src/stories/DateField.stories.tsx +21 -0
- package/src/stories/Editable.stories.tsx +2 -0
- package/src/stories/FacetedFilter.stories.tsx +197 -0
- package/src/stories/GaugeChart.stories.tsx +169 -0
- package/src/stories/Heatmap.stories.tsx +172 -0
- package/src/stories/InfiniteScroll.stories.tsx +225 -0
- package/src/stories/InlineEdit.stories.tsx +106 -0
- package/src/stories/JsonInput.stories.tsx +212 -0
- package/src/stories/MarkdownPreview.stories.tsx +53 -0
- package/src/stories/MonthPicker.stories.tsx +21 -0
- package/src/stories/NavigationProgress.stories.tsx +159 -0
- package/src/stories/NumberInput.stories.tsx +26 -0
- package/src/stories/OtpInput.stories.tsx +110 -0
- package/src/stories/PasswordInput.stories.tsx +4 -0
- package/src/stories/PasswordStrengthInput.stories.tsx +211 -0
- package/src/stories/PhoneInput.stories.tsx +127 -0
- package/src/stories/Pill.stories.tsx +201 -0
- package/src/stories/Popover.stories.tsx +29 -1
- package/src/stories/Portal.stories.tsx +3 -1
- package/src/stories/ScrollProgress.stories.tsx +117 -0
- package/src/stories/SearchInput.stories.tsx +2 -0
- package/src/stories/Snackbar.stories.tsx +315 -0
- package/src/stories/SortableList.stories.tsx +263 -0
- package/src/stories/Squircle.stories.tsx +1 -0
- package/src/stories/Table.stories.tsx +1 -0
- package/src/stories/TagsInput.stories.tsx +2 -0
- package/src/stories/Timer.stories.tsx +26 -0
- package/src/stories/Tour.stories.tsx +1 -0
- package/src/stories/TransferList.stories.tsx +4 -0
- package/src/stories/WeekPicker.stories.tsx +21 -0
- package/src/stories/YearPicker.stories.tsx +21 -0
- package/src/stories/story-groups.json +33 -16
- package/src/tokens.json +82 -54
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Prototype spec parser. One source for the rules that read `spec.md`:
|
|
3
|
+
* the `bads-check-spec` gate (Node) and the canvas Spec frame (React, through
|
|
4
|
+
* `src/lib/spec-parse.ts`). Plain ESM with no dependencies so both can import it.
|
|
5
|
+
*
|
|
6
|
+
* A spec is markdown with a small front matter block and fixed `##` headings.
|
|
7
|
+
* See templates/prototype-repo/spec.template.md.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export const REQUIRED_HEADINGS = [
|
|
11
|
+
"Audience and problem",
|
|
12
|
+
"What it does",
|
|
13
|
+
"Element inventory",
|
|
14
|
+
"States",
|
|
15
|
+
"Decisions",
|
|
16
|
+
"Open questions",
|
|
17
|
+
"Out of scope",
|
|
18
|
+
"Handoff",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
const BUILT_VALUES = new Set(["yes", "deferred", "dropped"])
|
|
22
|
+
const APPROVER = /approved by\s+([^\s<][^\n]*?)\s+on\s+(\d{4}-\d{2}-\d{2})/i
|
|
23
|
+
const PLACEHOLDER = /<[A-Za-z][^>\n]*>/
|
|
24
|
+
|
|
25
|
+
/** Heading text to an anchor id. GitHub-style: lowercase, words joined by hyphens. */
|
|
26
|
+
export function slugify(text) {
|
|
27
|
+
return String(text)
|
|
28
|
+
.toLowerCase()
|
|
29
|
+
.replace(/[`*_~]/g, "")
|
|
30
|
+
.replace(/[^a-z0-9\s-]/g, "")
|
|
31
|
+
.trim()
|
|
32
|
+
.replace(/\s+/g, "-")
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Split a leading `---` block into key/value pairs. Values are plain strings. */
|
|
36
|
+
export function parseFrontMatter(source) {
|
|
37
|
+
const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(source)
|
|
38
|
+
if (!match) return { data: {}, body: source }
|
|
39
|
+
const data = {}
|
|
40
|
+
for (const line of match[1].split(/\r?\n/)) {
|
|
41
|
+
const kv = /^([A-Za-z][\w-]*)\s*:\s*(.*)$/.exec(line)
|
|
42
|
+
if (kv) data[kv[1]] = kv[2].trim()
|
|
43
|
+
}
|
|
44
|
+
return { data, body: source.slice(match[0].length) }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function stripComments(text) {
|
|
48
|
+
return text.replace(/<!--[\s\S]*?-->/g, "")
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Level 1 to 6 headings outside code fences, in order. */
|
|
52
|
+
export function parseHeadings(body) {
|
|
53
|
+
const out = []
|
|
54
|
+
let fenced = false
|
|
55
|
+
body.split(/\r?\n/).forEach((line, index) => {
|
|
56
|
+
if (/^\s*```/.test(line)) fenced = !fenced
|
|
57
|
+
if (fenced) return
|
|
58
|
+
const m = /^(#{1,6})\s+(.+?)\s*#*\s*$/.exec(line)
|
|
59
|
+
if (m) out.push({ level: m[1].length, title: m[2], slug: slugify(m[2]), line: index })
|
|
60
|
+
})
|
|
61
|
+
return out
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The text under a `##` heading, up to the next `##` or `#`. Null when absent. */
|
|
65
|
+
export function sectionText(body, title) {
|
|
66
|
+
const lines = body.split(/\r?\n/)
|
|
67
|
+
const heads = parseHeadings(body).filter((h) => h.level <= 2)
|
|
68
|
+
const at = heads.findIndex((h) => h.level === 2 && h.title.toLowerCase() === title.toLowerCase())
|
|
69
|
+
if (at === -1) return null
|
|
70
|
+
const end = heads[at + 1] ? heads[at + 1].line : lines.length
|
|
71
|
+
return lines.slice(heads[at].line + 1, end).join("\n")
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** GitHub-flavored table to rows of objects keyed by lowercase header. */
|
|
75
|
+
export function parseTable(text) {
|
|
76
|
+
const rows = text
|
|
77
|
+
.split(/\r?\n/)
|
|
78
|
+
.filter((l) => l.trim().startsWith("|"))
|
|
79
|
+
.map((l) => l.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((c) => c.trim()))
|
|
80
|
+
if (rows.length < 2) return []
|
|
81
|
+
const header = rows[0].map((h) => h.toLowerCase())
|
|
82
|
+
return rows
|
|
83
|
+
.slice(2)
|
|
84
|
+
.map((cells) => Object.fromEntries(header.map((h, i) => [h, cells[i] ?? ""])))
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function bullets(text) {
|
|
88
|
+
return text
|
|
89
|
+
.split(/\r?\n/)
|
|
90
|
+
.map((l) => /^\s*[-*]\s+(.*)$/.exec(l))
|
|
91
|
+
.filter(Boolean)
|
|
92
|
+
.map((m) => m[1].trim())
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Read a spec and report what is wrong with it. `problems` lists every defect;
|
|
97
|
+
* the gate treats them as errors only for a prototype at review or later.
|
|
98
|
+
*/
|
|
99
|
+
export function analyzeSpec(source) {
|
|
100
|
+
const { data, body: raw } = parseFrontMatter(source)
|
|
101
|
+
const body = stripComments(raw)
|
|
102
|
+
const problems = []
|
|
103
|
+
|
|
104
|
+
for (const key of ["prototype", "path"]) {
|
|
105
|
+
if (!data[key]) problems.push(`front matter is missing \`${key}\``)
|
|
106
|
+
else if (PLACEHOLDER.test(data[key])) problems.push(`front matter \`${key}\` is still a placeholder`)
|
|
107
|
+
}
|
|
108
|
+
if (data.path && !["A", "B"].includes(data.path)) problems.push("front matter `path` must be A or B")
|
|
109
|
+
|
|
110
|
+
const headings = parseHeadings(body)
|
|
111
|
+
for (const title of REQUIRED_HEADINGS) {
|
|
112
|
+
if (!headings.some((h) => h.level === 2 && h.title.toLowerCase() === title.toLowerCase())) {
|
|
113
|
+
problems.push(`missing the \`## ${title}\` section`)
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const inventoryText = sectionText(body, "Element inventory") ?? ""
|
|
118
|
+
const inventory = parseTable(inventoryText).map((row) => {
|
|
119
|
+
const built = (row.built ?? "").toLowerCase()
|
|
120
|
+
const approver = APPROVER.exec(row.notes ?? "")
|
|
121
|
+
return {
|
|
122
|
+
element: row.element ?? "",
|
|
123
|
+
source: row.source ?? "",
|
|
124
|
+
built: BUILT_VALUES.has(built) ? built : "unmarked",
|
|
125
|
+
notes: row.notes ?? "",
|
|
126
|
+
view: row.view || null,
|
|
127
|
+
approvedBy: approver ? approver[1] : null,
|
|
128
|
+
approvedOn: approver ? approver[2] : null,
|
|
129
|
+
}
|
|
130
|
+
})
|
|
131
|
+
if (inventory.length === 0 && sectionText(body, "Element inventory") !== null) {
|
|
132
|
+
problems.push("the element inventory has no rows")
|
|
133
|
+
}
|
|
134
|
+
for (const row of inventory) {
|
|
135
|
+
const label = row.element || "(blank element)"
|
|
136
|
+
if (row.built === "unmarked") problems.push(`inventory row "${label}" is not marked yes, deferred, or dropped`)
|
|
137
|
+
if ((row.built === "deferred" || row.built === "dropped") && !row.approvedBy) {
|
|
138
|
+
problems.push(`inventory row "${label}" is ${row.built} but names no approver ("Approved by <name> on YYYY-MM-DD")`)
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const questionsText = sectionText(body, "Open questions") ?? ""
|
|
143
|
+
const questions = bullets(questionsText)
|
|
144
|
+
.filter((q) => !/^none\.?$/i.test(q))
|
|
145
|
+
.map((q) => {
|
|
146
|
+
const m = /^([^:<][^:]{0,40}):\s+(\S.*)$/.exec(q)
|
|
147
|
+
return { text: q, owner: m ? m[1].trim() : null }
|
|
148
|
+
})
|
|
149
|
+
for (const q of questions) {
|
|
150
|
+
if (!q.owner) problems.push(`open question has no owner: "${q.text}"`)
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
return { frontMatter: data, headings, inventory, questions, problems }
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Turn each name in the inventory's `View` column into a `frame:` link, so the
|
|
158
|
+
* rendered Spec frame can pan the canvas to that frame. Leaves every other part of
|
|
159
|
+
* the markdown untouched. Rows with an empty View cell stay plain.
|
|
160
|
+
*/
|
|
161
|
+
export function linkInventoryViews(body) {
|
|
162
|
+
const lines = body.split(/\r?\n/)
|
|
163
|
+
const heads = parseHeadings(body).filter((h) => h.level <= 2)
|
|
164
|
+
const at = heads.findIndex((h) => h.level === 2 && h.title.toLowerCase() === "element inventory")
|
|
165
|
+
if (at === -1) return body
|
|
166
|
+
const end = heads[at + 1] ? heads[at + 1].line : lines.length
|
|
167
|
+
let viewCol = -1
|
|
168
|
+
let seenSeparator = false
|
|
169
|
+
for (let i = heads[at].line + 1; i < end; i++) {
|
|
170
|
+
const line = lines[i]
|
|
171
|
+
if (!line.trim().startsWith("|")) continue
|
|
172
|
+
const cells = line.trim().replace(/^\|/, "").replace(/\|$/, "").split("|")
|
|
173
|
+
if (viewCol === -1 && !seenSeparator) {
|
|
174
|
+
viewCol = cells.findIndex((c) => c.trim().toLowerCase() === "view")
|
|
175
|
+
continue
|
|
176
|
+
}
|
|
177
|
+
if (!seenSeparator) {
|
|
178
|
+
seenSeparator = true
|
|
179
|
+
continue
|
|
180
|
+
}
|
|
181
|
+
if (viewCol === -1 || viewCol >= cells.length) continue
|
|
182
|
+
const name = cells[viewCol].trim()
|
|
183
|
+
if (!name || name.startsWith("[")) continue
|
|
184
|
+
cells[viewCol] = ` [${name}](frame:${name}) `
|
|
185
|
+
lines[i] = "|" + cells.join("|") + "|"
|
|
186
|
+
}
|
|
187
|
+
return lines.join("\n")
|
|
188
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rendered "tells": the signals that a page was generated, read from computed
|
|
3
|
+
* styles in a real browser at several widths. lint-slop reads source text; this
|
|
4
|
+
* reads what paints, so it sees classes composed at runtime and the effect of the
|
|
5
|
+
* cascade. The registry's shape (dated, banned or warned) and the idea of
|
|
6
|
+
* checking the rendered page at three widths are from Leonxlnx/taste-skill (MIT);
|
|
7
|
+
* the rules are chosen to fit BADS's own registers and real-content rule.
|
|
8
|
+
*
|
|
9
|
+
* Two parts, kept apart so the logic is testable without a browser:
|
|
10
|
+
* probe() runs INSIDE the page and returns plain facts. Self-contained.
|
|
11
|
+
* classify() turns those facts into findings. Pure.
|
|
12
|
+
*
|
|
13
|
+
* What it does not flag, by design: eyebrow labels (sanctioned by the CTA size
|
|
14
|
+
* contract), editorial serif emphasis, and the terminal register. They are
|
|
15
|
+
* chosen design in BADS, as lint-slop's header explains.
|
|
16
|
+
*/
|
|
17
|
+
import { SLOP_EMOJI } from "../slop-rules.mjs";
|
|
18
|
+
|
|
19
|
+
export const WIDTHS = [375, 768, 1280];
|
|
20
|
+
|
|
21
|
+
/** code, name, status (banned fails the run; warned is reported), and why. */
|
|
22
|
+
export const TELLS = [
|
|
23
|
+
{ code: "BADS-TELL-1", name: "gradient-text", status: "banned", why: "Gradient-filled headline text. Carries no information. Use a solid foreground token." },
|
|
24
|
+
{ code: "BADS-TELL-2", name: "indigo-violet-gradient", status: "banned", why: "An indigo or violet gradient on a large surface or a button. The default machine palette." },
|
|
25
|
+
{ code: "BADS-TELL-3", name: "glass-panels", status: "warned", why: "Two or more translucent panels with backdrop blur. Use opaque surfaces one tone step from the ground." },
|
|
26
|
+
{ code: "BADS-TELL-4", name: "glow", status: "warned", why: "A box-shadow with a blur of 40px or more. Use a tone step, or no shadow." },
|
|
27
|
+
{ code: "BADS-TELL-5", name: "three-up-icon-cards", status: "warned", why: "Three equal cards in a row, each with a small icon and a heading. The stock feature row." },
|
|
28
|
+
{ code: "BADS-TELL-6", name: "pill-above-headline", status: "warned", why: "A small pill badge directly above the page headline ('New', 'Beta'). Say it in the supporting sentence." },
|
|
29
|
+
{ code: "BADS-TELL-7", name: "decorative-emoji", status: "banned", why: "Decorative emoji in page copy. Use words or a real picture." },
|
|
30
|
+
{ code: "BADS-TELL-8", name: "pulsing-status-dot", status: "warned", why: "A small dot that pulses forever with no live state behind it." },
|
|
31
|
+
{ code: "BADS-TELL-9", name: "placeholder-copy", status: "banned", why: "Placeholder text (Lorem ipsum, Jane Doe, Acme Inc., 555 numbers). The real-content rule: pull from content/personas/<brand>.json." },
|
|
32
|
+
{ code: "BADS-TELL-10", name: "placeholder-image", status: "banned", why: "An image from a placeholder service. Show the real product or a real picture of the client's world (bads-source-images)." },
|
|
33
|
+
{ code: "BADS-TELL-11", name: "horizontal-overflow", status: "banned", why: "The page scrolls sideways at this width. Fix the layout, not the rhythm." },
|
|
34
|
+
];
|
|
35
|
+
|
|
36
|
+
/** Runs in the browser. Returns plain, serializable facts. Must not reference anything outside itself. */
|
|
37
|
+
export function probe() {
|
|
38
|
+
const MAX = 4000;
|
|
39
|
+
const facts = { gradientText: [], gradients: [], glass: [], glow: [], cards: [], pills: [], emoji: [], pulse: [], copy: [], images: [], overflow: null };
|
|
40
|
+
const px = (v) => parseFloat(v) || 0;
|
|
41
|
+
const label = (el) => (el.tagName.toLowerCase() + (el.id ? "#" + el.id : "") + (typeof el.className === "string" && el.className.trim() ? "." + el.className.trim().split(/\s+/).slice(0, 2).join(".") : "")).slice(0, 80);
|
|
42
|
+
const canvas = document.createElement("canvas");
|
|
43
|
+
canvas.width = canvas.height = 1;
|
|
44
|
+
const cx = canvas.getContext("2d", { willReadFrequently: true });
|
|
45
|
+
const toRgb = (css) => { try { cx.clearRect(0, 0, 1, 1); cx.fillStyle = "#000"; cx.fillStyle = css; cx.fillRect(0, 0, 1, 1); const d = cx.getImageData(0, 0, 1, 1).data; return [d[0], d[1], d[2], d[3] / 255]; } catch { return null; } };
|
|
46
|
+
const hsl = ([r, g, b]) => { r /= 255; g /= 255; b /= 255; const mx = Math.max(r, g, b), mn = Math.min(r, g, b), l = (mx + mn) / 2, d = mx - mn; if (!d) return [0, 0, l]; const s = d / (1 - Math.abs(2 * l - 1)); const h = mx === r ? ((g - b) / d) % 6 : mx === g ? (b - r) / d + 2 : (r - g) / d + 4; return [(h * 60 + 360) % 360, s, l]; };
|
|
47
|
+
const COLOR = /(?:rgba?|hsla?|oklch|oklab|lab|lch|color)\([^)]*\)/g;
|
|
48
|
+
const vw = innerWidth, vh = innerHeight;
|
|
49
|
+
const els = [...document.body.querySelectorAll("*")].slice(0, MAX);
|
|
50
|
+
const visible = (el, r, cs) => r.width > 0 && r.height > 0 && cs.visibility !== "hidden" && cs.display !== "none" && cs.opacity !== "0";
|
|
51
|
+
|
|
52
|
+
for (const el of els) {
|
|
53
|
+
const cs = getComputedStyle(el), r = el.getBoundingClientRect();
|
|
54
|
+
if (!visible(el, r, cs)) continue;
|
|
55
|
+
if (/text/.test(cs.webkitBackgroundClip || cs.backgroundClip) && /gradient/.test(cs.backgroundImage) && (cs.webkitTextFillColor === "rgba(0, 0, 0, 0)" || cs.color === "rgba(0, 0, 0, 0)") && el.textContent.trim()) facts.gradientText.push({ el: label(el), text: el.textContent.trim().slice(0, 40) });
|
|
56
|
+
if (/gradient/.test(cs.backgroundImage) && !/text/.test(cs.webkitBackgroundClip || cs.backgroundClip)) {
|
|
57
|
+
const area = (r.width * r.height) / (vw * vh), isButton = el.matches("button, a, [role=button]");
|
|
58
|
+
if (area > 0.15 || isButton) {
|
|
59
|
+
const stops = (cs.backgroundImage.match(COLOR) || []).map(toRgb).filter((c) => c && c[3] > 0.3).map(hsl);
|
|
60
|
+
const violet = stops.filter(([h, s, l]) => h >= 235 && h <= 300 && s >= 0.4 && l > 0.15 && l < 0.85);
|
|
61
|
+
if (violet.length >= 2 || (violet.length >= 1 && stops.length <= 2 && violet.length === stops.length)) facts.gradients.push({ el: label(el), stops: stops.length });
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
if (/blur/.test(cs.backdropFilter || cs.webkitBackdropFilter || "")) { const bg = toRgb(cs.backgroundColor); if (bg && bg[3] > 0 && bg[3] < 0.95) facts.glass.push({ el: label(el) }); }
|
|
65
|
+
for (const sh of (cs.boxShadow || "").split(/,(?![^(]*\))/)) { const nums = (sh.replace(COLOR, "").match(/-?\d*\.?\d+px/g) || []).map(px); if (nums.length >= 3 && nums[2] >= 40 && sh.trim() !== "none") { facts.glow.push({ el: label(el), blur: nums[2] }); break; } }
|
|
66
|
+
if (cs.animationName !== "none" && cs.animationIterationCount === "infinite" && r.width <= 14 && r.height <= 14 && px(cs.borderTopLeftRadius) >= r.width / 2 - 1) facts.pulse.push({ el: label(el) });
|
|
67
|
+
if (el.tagName === "IMG" && /picsum\.photos|placehold\.|placeholder\.com|dummyimage|lorempixel|via\.placeholder|placekitten|loremflickr/i.test(el.currentSrc || el.src)) facts.images.push({ el: label(el), src: (el.currentSrc || el.src).slice(0, 80) });
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// Three equal cards, each with a small icon and a heading.
|
|
71
|
+
for (const parent of els) {
|
|
72
|
+
const kids = [...parent.children].filter((k) => { const r = k.getBoundingClientRect(); return r.width > 80 && r.height > 60; });
|
|
73
|
+
if (kids.length !== 3) continue;
|
|
74
|
+
const rs = kids.map((k) => k.getBoundingClientRect());
|
|
75
|
+
if (!(Math.abs(rs[0].width - rs[1].width) < 3 && Math.abs(rs[1].width - rs[2].width) < 3 && Math.abs(rs[0].top - rs[2].top) < 3)) continue;
|
|
76
|
+
const small = (k) => [...k.querySelectorAll("svg, img")].some((i) => { const b = i.getBoundingClientRect(); return b.width > 0 && b.width <= 64 && b.height <= 64; });
|
|
77
|
+
if (kids.every((k) => small(k) && k.querySelector("h2, h3, h4, strong"))) facts.cards.push({ el: label(parent) });
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// A small pill directly before the first h1.
|
|
81
|
+
const h1 = document.querySelector("h1");
|
|
82
|
+
if (h1) for (let el = h1.previousElementSibling; el; el = null) { const cs = getComputedStyle(el), r = el.getBoundingClientRect(); if (r.height > 0 && r.height <= 36 && px(cs.fontSize) <= 14 && px(cs.borderTopLeftRadius) >= r.height / 2 - 1 && el.textContent.trim().length <= 24) facts.pills.push({ text: el.textContent.trim() }); }
|
|
83
|
+
|
|
84
|
+
const text = document.body.innerText || "";
|
|
85
|
+
const emo = text.match(new RegExp(EMOJI_SOURCE, "gu"));
|
|
86
|
+
if (emo) facts.emoji = [...new Set(emo)];
|
|
87
|
+
const ph = text.match(/lorem ipsum|dolor sit amet|\bjane doe\b|\bjohn doe\b|acme inc|123 main st|555[-. ]?555/gi);
|
|
88
|
+
if (ph) facts.copy = [...new Set(ph.map((s) => s.toLowerCase()))];
|
|
89
|
+
facts.overflow = { scrollWidth: document.documentElement.scrollWidth, innerWidth: vw };
|
|
90
|
+
return facts;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// probe() is serialized into the page, so it can't import SLOP_EMOJI. The source is
|
|
94
|
+
// injected before serializing (see probeSource), keeping one definition of the set.
|
|
95
|
+
/** The source of probe() with the emoji set inlined, ready for page.evaluate. */
|
|
96
|
+
export function probeSource() {
|
|
97
|
+
return `(() => { const EMOJI_SOURCE = ${JSON.stringify(SLOP_EMOJI.source)}; return (${probe.toString()})(); })()`;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Turn one width's facts into findings. Pure. */
|
|
101
|
+
export function classify(facts, width) {
|
|
102
|
+
const out = [];
|
|
103
|
+
const add = (name, detail) => { const t = TELLS.find((x) => x.name === name); out.push({ code: t.code, name, status: t.status, width, detail, why: t.why }); };
|
|
104
|
+
for (const g of facts.gradientText || []) add("gradient-text", `${g.el}: "${g.text}"`);
|
|
105
|
+
for (const g of facts.gradients || []) add("indigo-violet-gradient", g.el);
|
|
106
|
+
if ((facts.glass || []).length >= 2) add("glass-panels", `${facts.glass.length} panels, e.g. ${facts.glass[0].el}`);
|
|
107
|
+
for (const g of (facts.glow || []).slice(0, 3)) add("glow", `${g.el}: ${g.blur}px blur`);
|
|
108
|
+
for (const c of facts.cards || []) add("three-up-icon-cards", c.el);
|
|
109
|
+
for (const p of facts.pills || []) add("pill-above-headline", `"${p.text}"`);
|
|
110
|
+
if ((facts.emoji || []).length) add("decorative-emoji", facts.emoji.join(" "));
|
|
111
|
+
for (const p of (facts.pulse || []).slice(0, 3)) add("pulsing-status-dot", p.el);
|
|
112
|
+
if ((facts.copy || []).length) add("placeholder-copy", facts.copy.join(", "));
|
|
113
|
+
for (const i of facts.images || []) add("placeholder-image", `${i.el}: ${i.src}`);
|
|
114
|
+
const o = facts.overflow;
|
|
115
|
+
if (o && o.scrollWidth > o.innerWidth + 1) add("horizontal-overflow", `${o.scrollWidth}px wide in a ${o.innerWidth}px window`);
|
|
116
|
+
return out;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Findings from every width, with a tell seen at several widths shown once. */
|
|
120
|
+
export function merge(perWidth) {
|
|
121
|
+
const seen = new Map();
|
|
122
|
+
for (const f of perWidth.flat()) {
|
|
123
|
+
const key = `${f.code}|${f.detail}`;
|
|
124
|
+
if (seen.has(key)) { if (!seen.get(key).widths.includes(f.width)) seen.get(key).widths.push(f.width); }
|
|
125
|
+
else seen.set(key, { ...f, widths: [f.width] });
|
|
126
|
+
}
|
|
127
|
+
return [...seen.values()].map(({ width, ...rest }) => rest);
|
|
128
|
+
}
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* lint-css-vars — a custom property that is referenced but never declared.
|
|
4
|
+
*
|
|
5
|
+
* Enforces layer-6-patterns-and-rules/declared-custom-properties.md. CSS does
|
|
6
|
+
* not error on `var(--missing)`. `border-radius: var(--missing)` computes to 0px
|
|
7
|
+
* and `color: var(--missing)` falls back to the inherited colour, so the page
|
|
8
|
+
* renders, the build passes, and the defect ships looking like a design
|
|
9
|
+
* decision. The case that wrote this: four radius properties were deleted from a
|
|
10
|
+
* brand stylesheet with a comment saying every call site now used a utility, ten
|
|
11
|
+
* call sites still referenced them, and eight pills and status circles shipped
|
|
12
|
+
* square while every check stayed green.
|
|
13
|
+
*
|
|
14
|
+
* What counts as declared:
|
|
15
|
+
* - `--name:` in any stylesheet the BUILD emitted. Read the built CSS, not the
|
|
16
|
+
* source: hundreds of properties come from a Tailwind `@theme` block at build
|
|
17
|
+
* time and appear in no stylesheet on disk.
|
|
18
|
+
* - `--name:` anywhere in source, which covers `@property`, a CSS file, a style
|
|
19
|
+
* prop key (`style={{ "--progress": "40%" }}`) and `setProperty("--name", …)`.
|
|
20
|
+
*
|
|
21
|
+
* What it skips: a reference with a fallback (`var(--x, 9999px)`), which cannot
|
|
22
|
+
* render as nothing by construction; a name built at runtime (`var(--color-${key})`);
|
|
23
|
+
* anything inside a comment; and, with a reason, a line marked
|
|
24
|
+
* `css-var-ok: <why this is set at runtime>`. Property families a library sets at
|
|
25
|
+
* runtime (a chart's `--color-<series>`) are named once with --allow; Radix's
|
|
26
|
+
* `--radix-*`, Tailwind's `--tw-*` and cmdk's `--cmdk-*` are built in.
|
|
27
|
+
*
|
|
28
|
+
* It fails rather than skips when there is no built CSS to read. A check that
|
|
29
|
+
* quietly passes when it could not run is how this defect survives in the first
|
|
30
|
+
* place.
|
|
31
|
+
*
|
|
32
|
+
* Run (after a build):
|
|
33
|
+
* npx bads-lint-css-vars # looks for out/, then .next/static
|
|
34
|
+
* npx bads-lint-css-vars --css dist/assets # name the built CSS directory
|
|
35
|
+
* npx bads-lint-css-vars --allow --color- # property families set at runtime (chart series)
|
|
36
|
+
* npx bads-lint-css-vars --warn | --init | --ratchet
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
import fs from "node:fs";
|
|
40
|
+
import path from "node:path";
|
|
41
|
+
import { finishCountedLint, flagValue, isMain } from "./lib/counted-lint.mjs";
|
|
42
|
+
|
|
43
|
+
/** Families that libraries set on elements at runtime, so no stylesheet declares them. */
|
|
44
|
+
export const RUNTIME_FAMILIES = ["--radix-", "--tw-", "--cmdk-"];
|
|
45
|
+
|
|
46
|
+
const SOURCE_ROOTS = ["app", "components", "src", "styles", "packages/core/src"];
|
|
47
|
+
const SOURCE_EXT = /\.(tsx?|jsx?|css|mdx?)$/;
|
|
48
|
+
const SKIP = new Set(["node_modules", ".next", "out", "dist", ".scratch", ".git", "vendor"]);
|
|
49
|
+
|
|
50
|
+
/** Strip comments, keeping line structure, so prose that names a property is not a reference. */
|
|
51
|
+
export function stripComments(src) {
|
|
52
|
+
return src
|
|
53
|
+
.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, " "))
|
|
54
|
+
.replace(/(^|[^:])\/\/.*$/gm, (m, pre) => pre + " ".repeat(m.length - pre.length));
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Every `--name` this text declares: `--name:` in CSS, a quoted style-prop key, or setProperty. */
|
|
58
|
+
export function extractDeclared(text) {
|
|
59
|
+
const out = new Set();
|
|
60
|
+
for (const m of text.matchAll(/(--[A-Za-z0-9_-]+)\s*:/g)) out.add(m[1]);
|
|
61
|
+
for (const m of text.matchAll(/["'`](--[A-Za-z0-9_-]+)["'`]\s*:/g)) out.add(m[1]);
|
|
62
|
+
for (const m of text.matchAll(/setProperty\(\s*["'`](--[A-Za-z0-9_-]+)["'`]/g)) out.add(m[1]);
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const MARKER = /css-var-ok:([^\n*]*)/;
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* @param {string} src
|
|
70
|
+
* @param {Set<string>} declared
|
|
71
|
+
* @param {{ allowPrefixes?: string[] }} [opts] property families set at runtime, e.g. ["--color-"] for chart series
|
|
72
|
+
* @returns {{line: number, prop: string, text?: string}[]}
|
|
73
|
+
*/
|
|
74
|
+
export function findUndeclared(src, declared, { allowPrefixes = [] } = {}) {
|
|
75
|
+
const raw = src.split("\n");
|
|
76
|
+
const findings = [];
|
|
77
|
+
stripComments(src)
|
|
78
|
+
.split("\n")
|
|
79
|
+
.forEach((line, i) => {
|
|
80
|
+
// group 2: `${` right after the name means var(--color-${key}), a name built at runtime.
|
|
81
|
+
for (const m of line.matchAll(/var\(\s*(--[A-Za-z0-9_-]+)(\$\{)?\s*(,)?/g)) {
|
|
82
|
+
if (m[3]) continue; // has a fallback: cannot render as nothing
|
|
83
|
+
if (m[2]) continue; // the name is built at runtime, so it cannot be checked statically
|
|
84
|
+
const name = m[1];
|
|
85
|
+
if (declared.has(name) || allowPrefixes.some((p) => name.startsWith(p))) continue;
|
|
86
|
+
const marker = [raw[i], raw[i - 1]].map((l) => (l ?? "").match(MARKER)).find(Boolean);
|
|
87
|
+
if (marker) {
|
|
88
|
+
if (marker[1].trim()) continue;
|
|
89
|
+
findings.push({ line: i + 1, prop: name, text: "css-var-ok marker needs a reason after the colon" });
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
findings.push({ line: i + 1, prop: name });
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
return findings;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function walk(dir, exts, out = []) {
|
|
99
|
+
let entries;
|
|
100
|
+
try {
|
|
101
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
102
|
+
} catch {
|
|
103
|
+
return out;
|
|
104
|
+
}
|
|
105
|
+
for (const e of entries) {
|
|
106
|
+
if (SKIP.has(e.name) || e.name.startsWith(".")) continue;
|
|
107
|
+
const p = path.join(dir, e.name);
|
|
108
|
+
if (e.isDirectory()) walk(p, exts, out);
|
|
109
|
+
else if (exts.test(e.name)) out.push(p);
|
|
110
|
+
}
|
|
111
|
+
return out;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
if (isMain(import.meta.url)) {
|
|
115
|
+
const root = process.cwd();
|
|
116
|
+
const argv = process.argv.slice(2);
|
|
117
|
+
const cssArg = flagValue(argv, "css", null);
|
|
118
|
+
const cssDirs = (cssArg ? [cssArg] : ["out", ".next/static"]).map((d) => path.join(root, d)).filter((d) => fs.existsSync(d));
|
|
119
|
+
|
|
120
|
+
if (!cssDirs.length) {
|
|
121
|
+
console.error("bads-lint-css-vars: no built CSS found (looked for out/ and .next/static).");
|
|
122
|
+
console.error(" This lint reads the BUILT stylesheet, because most custom properties are emitted at build time and appear in no file on disk.");
|
|
123
|
+
console.error(" Build first, or point at the output with --css <dir>. Failing rather than skipping on purpose.");
|
|
124
|
+
process.exit(1);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const declared = new Set();
|
|
128
|
+
let cssFiles = 0;
|
|
129
|
+
for (const d of cssDirs) {
|
|
130
|
+
for (const f of walkAll(d, /\.css$/)) {
|
|
131
|
+
cssFiles++;
|
|
132
|
+
for (const p of extractDeclared(fs.readFileSync(f, "utf8"))) declared.add(p);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
if (declared.size === 0) {
|
|
136
|
+
console.error(`bads-lint-css-vars: parsed 0 custom properties from ${cssFiles} built CSS file(s). The build output moved or the parser drifted. Not reporting success on an empty read.`);
|
|
137
|
+
process.exit(1);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// Prefix values start with "--", so the generic flag parser would read the value as another flag.
|
|
141
|
+
const allowIdx = argv.findIndex((a) => a === "--allow" || a.startsWith("--allow="));
|
|
142
|
+
const allowArg = allowIdx < 0 ? "" : argv[allowIdx].includes("=") ? argv[allowIdx].slice(argv[allowIdx].indexOf("=") + 1) : (argv[allowIdx + 1] ?? "");
|
|
143
|
+
const allowPrefixes = [...RUNTIME_FAMILIES, ...allowArg.split(",").map((x) => x.trim()).filter(Boolean)];
|
|
144
|
+
const sourceRoots = argv.filter((a) => !a.startsWith("--") && a !== cssArg && a !== allowArg);
|
|
145
|
+
const files = (sourceRoots.length ? sourceRoots : SOURCE_ROOTS).map((r) => path.join(root, r)).filter((r) => fs.existsSync(r)).flatMap((r) => (fs.statSync(r).isDirectory() ? walk(r, SOURCE_EXT) : [r]));
|
|
146
|
+
const sources = files.map((f) => ({ f, src: fs.readFileSync(f, "utf8") }));
|
|
147
|
+
for (const { src } of sources) for (const p of extractDeclared(src)) declared.add(p);
|
|
148
|
+
|
|
149
|
+
const findings = [];
|
|
150
|
+
const scanned = [];
|
|
151
|
+
for (const { f, src } of sources) {
|
|
152
|
+
const rel = path.relative(root, f);
|
|
153
|
+
scanned.push(rel);
|
|
154
|
+
for (const u of findUndeclared(src, declared, { allowPrefixes })) findings.push({ file: rel, line: u.line, text: u.text ?? `${u.prop} is referenced but never declared` });
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
process.exit(
|
|
158
|
+
finishCountedLint({
|
|
159
|
+
ruleId: "undeclared-css-vars",
|
|
160
|
+
bin: "bads-lint-css-vars",
|
|
161
|
+
findings,
|
|
162
|
+
scanned,
|
|
163
|
+
fix: "Declare the property, switch to a utility class that exists, or give the reference a fallback: var(--radius-pill, 9999px). See layer-6-patterns-and-rules/declared-custom-properties.md.",
|
|
164
|
+
}),
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function walkAll(dir, re, out = []) {
|
|
169
|
+
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
170
|
+
const p = path.join(dir, e.name);
|
|
171
|
+
if (e.isDirectory()) walkAll(p, re, out);
|
|
172
|
+
else if (re.test(e.name)) out.push(p);
|
|
173
|
+
}
|
|
174
|
+
return out;
|
|
175
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* lint-html-nesting — invalid HTML nesting in the built output.
|
|
4
|
+
*
|
|
5
|
+
* Enforces layer-6-patterns-and-rules/valid-html-nesting.md. `Separator` renders
|
|
6
|
+
* a <div>, so putting one inside a <p> is invalid HTML and throws React
|
|
7
|
+
* hydration error #418 in the browser, while `next build` reports success.
|
|
8
|
+
* Nothing in a component's documentation says what element it produces, so there
|
|
9
|
+
* is no way to know in advance, and the only signal is a console error someone
|
|
10
|
+
* has to be looking for. A passing build that emits a broken page is worse than
|
|
11
|
+
* a failing one, because people stop looking, so this reads the emitted HTML
|
|
12
|
+
* instead of trusting the build.
|
|
13
|
+
*
|
|
14
|
+
* It flags, per HTML file:
|
|
15
|
+
* <p> containing flow content (div, p, ul, ol, li, section, article, hr,
|
|
16
|
+
* table, h1-h6) a <p> may only hold phrasing content
|
|
17
|
+
* <button> inside <button> interactive content may not nest
|
|
18
|
+
* <a> inside <a> likewise
|
|
19
|
+
*
|
|
20
|
+
* <script> blocks are removed first: the framework payload is full of strings
|
|
21
|
+
* that look like markup.
|
|
22
|
+
*
|
|
23
|
+
* It fails rather than skips when there is no built HTML to read, because a
|
|
24
|
+
* check that quietly passes when it could not run is the anti-pattern it exists
|
|
25
|
+
* to catch. (Set BADS_ALLOW_MISSING_BUILD=1 to skip locally.)
|
|
26
|
+
*
|
|
27
|
+
* Run (after a build):
|
|
28
|
+
* npx bads-lint-html-nesting # looks for out/, then .next/server/app
|
|
29
|
+
* npx bads-lint-html-nesting --html dist # name the built HTML directory
|
|
30
|
+
* npx bads-lint-html-nesting --warn | --init | --ratchet
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
import fs from "node:fs";
|
|
34
|
+
import path from "node:path";
|
|
35
|
+
import { finishCountedLint, flagValue, isMain } from "./lib/counted-lint.mjs";
|
|
36
|
+
|
|
37
|
+
const FORBIDDEN_IN_P = ["div", "p", "ul", "ol", "li", "section", "article", "hr", "table", "h1", "h2", "h3", "h4", "h5", "h6"];
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* @param {string} html
|
|
41
|
+
* @returns {{tag: string, parent: string, snippet: string}[]}
|
|
42
|
+
*/
|
|
43
|
+
export function findInvalidNesting(html) {
|
|
44
|
+
const doc = html.replace(/<script\b[\s\S]*?<\/script>/gi, "").replace(/<style\b[\s\S]*?<\/style>/gi, "");
|
|
45
|
+
const found = [];
|
|
46
|
+
|
|
47
|
+
// <p> cannot nest, so the span from an opening <p> to the next </p> is its content.
|
|
48
|
+
for (const m of doc.matchAll(/<p(\s[^>]*)?>/g)) {
|
|
49
|
+
const start = m.index + m[0].length;
|
|
50
|
+
const close = doc.indexOf("</p>", start);
|
|
51
|
+
if (close === -1) continue;
|
|
52
|
+
const inner = doc.slice(start, close);
|
|
53
|
+
const tag = FORBIDDEN_IN_P.find((t) => new RegExp(`<${t}(\\s|>|/)`, "i").test(inner));
|
|
54
|
+
if (tag) found.push({ tag, parent: "p", snippet: doc.slice(m.index, Math.min(close + 4, m.index + 150)).replace(/\s+/g, " ") });
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
for (const t of ["button", "a"]) {
|
|
58
|
+
for (const m of doc.matchAll(new RegExp(`<${t}(\\s[^>]*)?>`, "gi"))) {
|
|
59
|
+
const start = m.index + m[0].length;
|
|
60
|
+
const close = doc.indexOf(`</${t}>`, start);
|
|
61
|
+
if (close === -1) continue;
|
|
62
|
+
if (new RegExp(`<${t}(\\s|>)`, "i").test(doc.slice(start, close))) {
|
|
63
|
+
found.push({ tag: t, parent: t, snippet: doc.slice(m.index, Math.min(close + t.length + 3, m.index + 150)).replace(/\s+/g, " ") });
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return found;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function walkHtml(dir, out = []) {
|
|
71
|
+
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
72
|
+
const p = path.join(dir, e.name);
|
|
73
|
+
if (e.isDirectory()) walkHtml(p, out);
|
|
74
|
+
else if (e.name.endsWith(".html")) out.push(p);
|
|
75
|
+
}
|
|
76
|
+
return out;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
if (isMain(import.meta.url)) {
|
|
80
|
+
const root = process.cwd();
|
|
81
|
+
const argv = process.argv.slice(2);
|
|
82
|
+
const htmlArg = flagValue(argv, "html", null);
|
|
83
|
+
const dirs = (htmlArg ? [htmlArg] : ["out", ".next/server/app"]).map((d) => path.join(root, d)).filter((d) => fs.existsSync(d));
|
|
84
|
+
|
|
85
|
+
if (!dirs.length) {
|
|
86
|
+
if (process.env.BADS_ALLOW_MISSING_BUILD && !process.env.CI) {
|
|
87
|
+
console.log("bads-lint-html-nesting: SKIPPED, no built HTML (BADS_ALLOW_MISSING_BUILD is set).");
|
|
88
|
+
process.exit(0);
|
|
89
|
+
}
|
|
90
|
+
console.error("bads-lint-html-nesting: no built HTML found (looked for out/ and .next/server/app).");
|
|
91
|
+
console.error(" This lint reads the HTML the build emitted. Build first, or point at it with --html <dir>.");
|
|
92
|
+
process.exit(1);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const findings = [];
|
|
96
|
+
const scanned = [];
|
|
97
|
+
for (const d of dirs) {
|
|
98
|
+
for (const f of walkHtml(d)) {
|
|
99
|
+
const rel = path.relative(root, f);
|
|
100
|
+
scanned.push(rel);
|
|
101
|
+
for (const n of findInvalidNesting(fs.readFileSync(f, "utf8"))) {
|
|
102
|
+
findings.push({ file: rel, text: `<${n.tag}> inside <${n.parent}>: ${n.snippet.slice(0, 110)}` });
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
process.exit(
|
|
108
|
+
finishCountedLint({
|
|
109
|
+
ruleId: "html-nesting",
|
|
110
|
+
bin: "bads-lint-html-nesting",
|
|
111
|
+
findings,
|
|
112
|
+
scanned,
|
|
113
|
+
fix: "Usually a component renders an element you did not expect (Separator renders a div). Check what it produces, and use a span, a wrapper outside the paragraph, or a different component. See layer-6-patterns-and-rules/valid-html-nesting.md.",
|
|
114
|
+
}),
|
|
115
|
+
);
|
|
116
|
+
}
|