division-ds 0.0.0-stage → 0.1.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/AGENTS.md +190 -0
- package/LICENSE +21 -0
- package/README.md +18 -2
- package/package.json +20 -4
- package/public/manifest/components.json +10550 -0
- package/public/manifest/tokens.json +932 -0
- package/scripts/division-ds.mjs +188 -0
- package/scripts/lib/agent-docs.mjs +510 -0
- package/scripts/lib/button-spacing.mjs +416 -0
- package/scripts/lib/component-props.mjs +181 -0
- package/scripts/lib/props-validator.mjs +320 -0
- package/scripts/lib/rules-installer.mjs +132 -0
- package/scripts/lib/token-discipline.mjs +125 -0
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
// The touching-buttons matcher: a lightweight JSX tag scanner, the button-like/asChild-wrapper
|
|
2
|
+
// definition, and the parent-className check. `scripts/check-button-spacing.mjs` is the CLI that
|
|
3
|
+
// walks src/**/*.tsx and owns the exit code; this file is the pure function it wraps, the same
|
|
4
|
+
// split `check-contrast.mjs` and `check-vocabulary.mjs` both use, so the matching rules can be
|
|
5
|
+
// unit-tested without a filesystem.
|
|
6
|
+
//
|
|
7
|
+
// Why a gate at all. `Button` and `IconButton` render `inline-flex` (see
|
|
8
|
+
// src/components/atoms/button/Button.tsx), never a block element with its own margin. Two of them
|
|
9
|
+
// as bare JSX siblings, with no flex/grid parent carrying a `gap-` utility, land flush against each
|
|
10
|
+
// other on the same line -- JSX drops a whitespace-only line between two elements entirely, so
|
|
11
|
+
// there is no rendered space either. That is exactly what shipped in
|
|
12
|
+
// src/components/organisms/sheet/SheetDocs.tsx's "Filters on the right" example: a `Button` and a
|
|
13
|
+
// `SheetClose asChild` (its own single child a `Button`) as direct children of `SheetContent`, each
|
|
14
|
+
// carrying only `mt-6` (top margin, no horizontal gap), with no wrapping element at all.
|
|
15
|
+
//
|
|
16
|
+
// This is not a full JSX/TSX parser. It tokenizes `<Tag ...>`, `</Tag>` and `<Tag ... />` using a
|
|
17
|
+
// brace/paren/string-depth-aware scan of each tag's attribute text (so `onClick={() => f({a:1})}`
|
|
18
|
+
// does not confuse it about where the tag ends), builds a tree from that token stream, and asks two
|
|
19
|
+
// questions of every element: how many of its direct children are "button-like", and does its own
|
|
20
|
+
// className give it a real, nonzero, horizontal gap on an actual flex/grid container
|
|
21
|
+
// (`hasWorkingGap` below -- `gap-0`, a `gap-y-*`-only value, or a bare `gap-3` on an element with
|
|
22
|
+
// no `flex`/`grid` token all correctly fail this). Anything JSX can do that a real parser would
|
|
23
|
+
// resolve and this cannot -- conditional/mapped children, spread children, fragments standing in
|
|
24
|
+
// for a parent -- is out of scope; see button-spacing.test.mjs for what is deliberately not
|
|
25
|
+
// claimed. One specific accepted false negative, not worth a heuristic that would risk a worse
|
|
26
|
+
// false positive: a mutually-exclusive ternary (`{open ? <Button/> : <Button/>}`, where only one
|
|
27
|
+
// side ever renders) is invisible to this checker as two simultaneous children, same as it is to
|
|
28
|
+
// a reader skimming the JSX -- there is no touching bug there to catch in the first place.
|
|
29
|
+
|
|
30
|
+
const TAG_NAME = /[A-Za-z][A-Za-z0-9.]*/y
|
|
31
|
+
|
|
32
|
+
/** True at `text[i]` when a JSX tag plausibly starts there. A closing tag (`</Name>`) is always
|
|
33
|
+
* accepted: `</` right next to text content (`<Button>Apply</Button>`, no separating whitespace)
|
|
34
|
+
* is the ordinary JSX shape, not the ambiguous case. An opening tag (`<Name`) is accepted only
|
|
35
|
+
* when NOT immediately preceded by an identifier character -- that is what keeps `Array<string>`,
|
|
36
|
+
* `a < b` and `identity<T>()` from being read as tags, since in each of those the character right
|
|
37
|
+
* before `<` is part of an identifier, which a real JSX open tag never has. */
|
|
38
|
+
function isTagStart(text, i) {
|
|
39
|
+
if (text[i] !== '<') return false
|
|
40
|
+
const next = text[i + 1]
|
|
41
|
+
if (next === '/') return true
|
|
42
|
+
const prev = text[i - 1]
|
|
43
|
+
if (prev && /[A-Za-z0-9_$]/.test(prev)) return false
|
|
44
|
+
return /[A-Za-z]/.test(next)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Scans an opening or self-closing tag's attribute text starting right after the tag name, depth-
|
|
48
|
+
* and quote-aware so nested `{}` `()` `[]` and quoted strings inside attribute expressions never
|
|
49
|
+
* get mistaken for the tag's own closing `>`. Returns the raw attrs text, whether the tag was
|
|
50
|
+
* self-closing, and the index just past the whole tag. */
|
|
51
|
+
function scanAttrs(text, start) {
|
|
52
|
+
let i = start
|
|
53
|
+
let depth = 0
|
|
54
|
+
let quote = null
|
|
55
|
+
while (i < text.length) {
|
|
56
|
+
const c = text[i]
|
|
57
|
+
if (quote) {
|
|
58
|
+
if (c === '\\') {
|
|
59
|
+
i += 2
|
|
60
|
+
continue
|
|
61
|
+
}
|
|
62
|
+
if (c === quote) quote = null
|
|
63
|
+
i++
|
|
64
|
+
continue
|
|
65
|
+
}
|
|
66
|
+
if (c === '"' || c === "'" || c === '`') {
|
|
67
|
+
quote = c
|
|
68
|
+
i++
|
|
69
|
+
continue
|
|
70
|
+
}
|
|
71
|
+
if (c === '{' || c === '(' || c === '[') {
|
|
72
|
+
depth++
|
|
73
|
+
i++
|
|
74
|
+
continue
|
|
75
|
+
}
|
|
76
|
+
if (c === '}' || c === ')' || c === ']') {
|
|
77
|
+
depth--
|
|
78
|
+
i++
|
|
79
|
+
continue
|
|
80
|
+
}
|
|
81
|
+
if (depth <= 0 && c === '/' && text[i + 1] === '>') {
|
|
82
|
+
return { attrsText: text.slice(start, i), selfClosing: true, end: i + 2 }
|
|
83
|
+
}
|
|
84
|
+
if (depth <= 0 && c === '>') {
|
|
85
|
+
return { attrsText: text.slice(start, i), selfClosing: false, end: i + 1 }
|
|
86
|
+
}
|
|
87
|
+
i++
|
|
88
|
+
}
|
|
89
|
+
return { attrsText: text.slice(start), selfClosing: false, end: text.length }
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Every JSX tag token in `text`, in source order: `{ type: 'open' | 'close' | 'self', name,
|
|
93
|
+
* attrsText, start }`. `start` is the index of the tag's leading `<`. */
|
|
94
|
+
function tokenizeTags(text) {
|
|
95
|
+
const tokens = []
|
|
96
|
+
let i = 0
|
|
97
|
+
while (i < text.length) {
|
|
98
|
+
if (!isTagStart(text, i)) {
|
|
99
|
+
i++
|
|
100
|
+
continue
|
|
101
|
+
}
|
|
102
|
+
const start = i
|
|
103
|
+
if (text[i + 1] === '/') {
|
|
104
|
+
const nameStart = i + 2
|
|
105
|
+
TAG_NAME.lastIndex = nameStart
|
|
106
|
+
const match = TAG_NAME.exec(text)
|
|
107
|
+
if (!match) {
|
|
108
|
+
i++
|
|
109
|
+
continue
|
|
110
|
+
}
|
|
111
|
+
const close = text.indexOf('>', TAG_NAME.lastIndex)
|
|
112
|
+
if (close === -1) break
|
|
113
|
+
tokens.push({ type: 'close', name: match[0], attrsText: '', start })
|
|
114
|
+
i = close + 1
|
|
115
|
+
continue
|
|
116
|
+
}
|
|
117
|
+
const nameStart = i + 1
|
|
118
|
+
TAG_NAME.lastIndex = nameStart
|
|
119
|
+
const match = TAG_NAME.exec(text)
|
|
120
|
+
if (!match) {
|
|
121
|
+
i++
|
|
122
|
+
continue
|
|
123
|
+
}
|
|
124
|
+
const { attrsText, selfClosing, end } = scanAttrs(text, TAG_NAME.lastIndex)
|
|
125
|
+
tokens.push({ type: selfClosing ? 'self' : 'open', name: match[0], attrsText, start })
|
|
126
|
+
i = end
|
|
127
|
+
}
|
|
128
|
+
return tokens
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Parses one tag's attribute text into `name -> raw value text` (quotes/braces stripped, so a
|
|
132
|
+
* string attr and an expression attr are both just the inner text). A boolean shorthand attribute
|
|
133
|
+
* (`asChild` with no `=`) maps to `'true'`. Spread attributes (`{...rest}`) carry no name and are
|
|
134
|
+
* skipped -- this checker only ever looks up specific attribute names, never enumerates all of
|
|
135
|
+
* them, so a spread is invisible to it by construction (see button-spacing.test.mjs). */
|
|
136
|
+
function parseAttributes(attrsText) {
|
|
137
|
+
const attrs = new Map()
|
|
138
|
+
const NAME = /[A-Za-z_][A-Za-z0-9_-]*/y
|
|
139
|
+
let i = 0
|
|
140
|
+
while (i < attrsText.length) {
|
|
141
|
+
const c = attrsText[i]
|
|
142
|
+
if (/\s/.test(c)) {
|
|
143
|
+
i++
|
|
144
|
+
continue
|
|
145
|
+
}
|
|
146
|
+
if (c === '{') {
|
|
147
|
+
// A spread (`{...x}`) or a stray expression between attributes -- skip the balanced group.
|
|
148
|
+
let depth = 0
|
|
149
|
+
let quote = null
|
|
150
|
+
while (i < attrsText.length) {
|
|
151
|
+
const ch = attrsText[i]
|
|
152
|
+
if (quote) {
|
|
153
|
+
if (ch === '\\') {
|
|
154
|
+
i += 2
|
|
155
|
+
continue
|
|
156
|
+
}
|
|
157
|
+
if (ch === quote) quote = null
|
|
158
|
+
i++
|
|
159
|
+
continue
|
|
160
|
+
}
|
|
161
|
+
if (ch === '"' || ch === "'" || ch === '`') {
|
|
162
|
+
quote = ch
|
|
163
|
+
i++
|
|
164
|
+
continue
|
|
165
|
+
}
|
|
166
|
+
if (ch === '{') depth++
|
|
167
|
+
if (ch === '}') {
|
|
168
|
+
depth--
|
|
169
|
+
i++
|
|
170
|
+
if (depth === 0) break
|
|
171
|
+
continue
|
|
172
|
+
}
|
|
173
|
+
i++
|
|
174
|
+
}
|
|
175
|
+
continue
|
|
176
|
+
}
|
|
177
|
+
NAME.lastIndex = i
|
|
178
|
+
const match = NAME.exec(attrsText)
|
|
179
|
+
if (!match) {
|
|
180
|
+
i++
|
|
181
|
+
continue
|
|
182
|
+
}
|
|
183
|
+
const name = match[0]
|
|
184
|
+
i = NAME.lastIndex
|
|
185
|
+
while (/\s/.test(attrsText[i])) i++
|
|
186
|
+
if (attrsText[i] !== '=') {
|
|
187
|
+
attrs.set(name, 'true')
|
|
188
|
+
continue
|
|
189
|
+
}
|
|
190
|
+
i++
|
|
191
|
+
while (/\s/.test(attrsText[i])) i++
|
|
192
|
+
const quoteChar = attrsText[i]
|
|
193
|
+
if (quoteChar === '"' || quoteChar === "'") {
|
|
194
|
+
const valStart = i + 1
|
|
195
|
+
let j = valStart
|
|
196
|
+
while (j < attrsText.length && attrsText[j] !== quoteChar) j++
|
|
197
|
+
attrs.set(name, attrsText.slice(valStart, j))
|
|
198
|
+
i = j + 1
|
|
199
|
+
continue
|
|
200
|
+
}
|
|
201
|
+
if (quoteChar === '{') {
|
|
202
|
+
let depth = 0
|
|
203
|
+
let j = i
|
|
204
|
+
let quote = null
|
|
205
|
+
const valStart = i + 1
|
|
206
|
+
while (j < attrsText.length) {
|
|
207
|
+
const ch = attrsText[j]
|
|
208
|
+
if (quote) {
|
|
209
|
+
if (ch === '\\') {
|
|
210
|
+
j += 2
|
|
211
|
+
continue
|
|
212
|
+
}
|
|
213
|
+
if (ch === quote) quote = null
|
|
214
|
+
j++
|
|
215
|
+
continue
|
|
216
|
+
}
|
|
217
|
+
if (ch === '"' || ch === "'" || ch === '`') {
|
|
218
|
+
quote = ch
|
|
219
|
+
j++
|
|
220
|
+
continue
|
|
221
|
+
}
|
|
222
|
+
if (ch === '{') depth++
|
|
223
|
+
if (ch === '}') {
|
|
224
|
+
depth--
|
|
225
|
+
j++
|
|
226
|
+
if (depth === 0) break
|
|
227
|
+
continue
|
|
228
|
+
}
|
|
229
|
+
j++
|
|
230
|
+
}
|
|
231
|
+
attrs.set(name, attrsText.slice(valStart, j - 1))
|
|
232
|
+
i = j
|
|
233
|
+
continue
|
|
234
|
+
}
|
|
235
|
+
// An unquoted, unbraced value shouldn't occur in valid TSX; skip one token defensively.
|
|
236
|
+
i++
|
|
237
|
+
}
|
|
238
|
+
return attrs
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** Element nodes that render `inline-flex` with no self-contained horizontal gap of their own. */
|
|
242
|
+
const BUTTON_TAGS = new Set(['Button', 'IconButton'])
|
|
243
|
+
|
|
244
|
+
/** Components whose own implementation already wraps `children` (or `...rest`, which children
|
|
245
|
+
* land in) in an element carrying a `gap-` utility, so a call site is correct with no `gap-` of
|
|
246
|
+
* its own -- the component *is* the gap-bearing wrapper. Checking a call site's className alone
|
|
247
|
+
* cannot see this (the gap lives in the component's source, not the call site's JSX), so without
|
|
248
|
+
* this list every real use of these components with 2+ button-like children would be a false
|
|
249
|
+
* positive. Narrow and exact by design, the same shape as `ALLOWED_IDIOMS` in vocabulary.mjs: an
|
|
250
|
+
* entry here is a claim about one named component's current source, verified by reading it, not a
|
|
251
|
+
* blanket exemption. Re-verify the cited line before trusting an existing entry, and re-check
|
|
252
|
+
* whether an entry is still needed if that component's implementation changes.
|
|
253
|
+
*
|
|
254
|
+
* This exemption is NOT unconditional: `breaksExemption` below still checks the call site's own
|
|
255
|
+
* className for a `cn(...)`/tailwind-merge display or zero-gap override (`className="block"`,
|
|
256
|
+
* common across this codebase's own *Docs.tsx files) that would silently defeat the internal
|
|
257
|
+
* `flex ... gap-` these components render -- both merge the call site's className last, so
|
|
258
|
+
* `block` wins the `display` conflict and turns the internal flex row off entirely.
|
|
259
|
+
*
|
|
260
|
+
* - `DialogFooter` (src/components/organisms/dialog/Dialog.tsx) renders
|
|
261
|
+
* `<div className={cn('flex flex-wrap items-center justify-end gap-3 mt-6', className)} ...>`.
|
|
262
|
+
* - `Example` (src/components/docs/Example.tsx) renders its children inside
|
|
263
|
+
* `<Panel className={cn('flex flex-wrap items-center gap-4', className)}>`.
|
|
264
|
+
* - `CardFooter` and `CardActions` (src/components/molecules/card/Card.tsx) both render a
|
|
265
|
+
* `flex flex-wrap ... gap-3` row. */
|
|
266
|
+
const GAP_PROVIDING_COMPONENTS = new Set(['DialogFooter', 'Example', 'CardFooter', 'CardActions'])
|
|
267
|
+
|
|
268
|
+
/** A whole class token, bounded by whitespace/quote/backtick on both sides (so `inline` never
|
|
269
|
+
* matches inside `inline-flex`, and `gap-0` never matches inside `gap-0.5` or `sm:gap-0`). */
|
|
270
|
+
function hasToken(className, token) {
|
|
271
|
+
return new RegExp(`(^|[\\s'"\`])${token}(?=[\\s'"\`]|$)`).test(className)
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** True when the call site's own className carries a token that would override the internal
|
|
275
|
+
* `flex ... gap-` a `GAP_PROVIDING_COMPONENTS` entry renders -- `block`/`inline`/`contents` win
|
|
276
|
+
* the `display` conflict under tailwind-merge (the call site's className is merged last), and a
|
|
277
|
+
* literal `gap-0`/`gap-x-0` passed at the call site wins the same way on the `gap` property. */
|
|
278
|
+
function breaksExemption(className) {
|
|
279
|
+
return ['block', 'inline', 'contents', 'gap-0', 'gap-x-0'].some(token => hasToken(className, token))
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** True when `className` carries a real, nonzero, HORIZONTAL gap token (`gap-<n>` or
|
|
283
|
+
* `gap-x-<n>`, never `gap-y-<n>` alone -- vertical spacing does nothing for two elements sitting
|
|
284
|
+
* side by side in a row) on an element that actually establishes a flex/grid formatting context.
|
|
285
|
+
* Both halves matter on their own: a `gap-` utility on an element with no `flex`/`grid`/
|
|
286
|
+
* `inline-flex`/`inline-grid` does nothing (a plain block `<div>` ignores `gap-3` entirely), and
|
|
287
|
+
* `flex-1`/`flex-none`/`flex-auto` (flex-ITEM properties, not `display: flex`) must not be
|
|
288
|
+
* mistaken for a flex container -- both are excluded by requiring the exact token, bounded on
|
|
289
|
+
* both sides, not merely `/\bflex\b/` (which `flex-1` also satisfies). */
|
|
290
|
+
function hasWorkingGap(className) {
|
|
291
|
+
const gapTokens = className.match(/gap(?:-x|-y)?-[\w.[\]-]+/g) ?? []
|
|
292
|
+
const hasRealHorizontalGap = gapTokens.some(token => {
|
|
293
|
+
if (token.startsWith('gap-y-')) return false
|
|
294
|
+
const value = token.match(/^gap(?:-x)?-(.+)$/)?.[1]
|
|
295
|
+
return value !== undefined && value !== '0'
|
|
296
|
+
})
|
|
297
|
+
if (!hasRealHorizontalGap) return false
|
|
298
|
+
return ['flex', 'inline-flex', 'grid', 'inline-grid'].some(token => hasToken(className, token))
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Builds the element tree from a token stream. Each node: `{ name, attrsText, attrs, start,
|
|
303
|
+
* children }`, where `children` holds only child *elements* in source order (text and expression
|
|
304
|
+
* children carry no structure this checker can reason about, so they're not represented at all).
|
|
305
|
+
* A stray/mismatched closing tag pops back to the nearest matching ancestor by name if one exists
|
|
306
|
+
* on the stack, otherwise it is ignored -- real TSX is always balanced; this only has to not throw
|
|
307
|
+
* on the odd case this scanner misreads.
|
|
308
|
+
*/
|
|
309
|
+
function buildTree(tokens) {
|
|
310
|
+
const root = { name: null, attrsText: '', attrs: new Map(), start: -1, children: [] }
|
|
311
|
+
const stack = [root]
|
|
312
|
+
for (const token of tokens) {
|
|
313
|
+
if (token.type === 'open') {
|
|
314
|
+
const node = {
|
|
315
|
+
name: token.name,
|
|
316
|
+
attrsText: token.attrsText,
|
|
317
|
+
attrs: parseAttributes(token.attrsText),
|
|
318
|
+
start: token.start,
|
|
319
|
+
children: [],
|
|
320
|
+
}
|
|
321
|
+
stack[stack.length - 1].children.push(node)
|
|
322
|
+
stack.push(node)
|
|
323
|
+
continue
|
|
324
|
+
}
|
|
325
|
+
if (token.type === 'self') {
|
|
326
|
+
stack[stack.length - 1].children.push({
|
|
327
|
+
name: token.name,
|
|
328
|
+
attrsText: token.attrsText,
|
|
329
|
+
attrs: parseAttributes(token.attrsText),
|
|
330
|
+
start: token.start,
|
|
331
|
+
children: [],
|
|
332
|
+
})
|
|
333
|
+
continue
|
|
334
|
+
}
|
|
335
|
+
// close
|
|
336
|
+
const idx = stack.map(n => n.name).lastIndexOf(token.name)
|
|
337
|
+
if (idx > 0) stack.length = idx
|
|
338
|
+
}
|
|
339
|
+
return root
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/** True when `node` is itself a button, or is some other element carrying `asChild` whose one and
|
|
343
|
+
* only child element is a button -- the `SheetClose asChild><Button/></SheetClose>` shape that is
|
|
344
|
+
* exactly what shipped broken. Only one level of unwrapping: an `asChild` wrapper around an
|
|
345
|
+
* `asChild` wrapper is not chased further. */
|
|
346
|
+
function isButtonLike(node) {
|
|
347
|
+
if (BUTTON_TAGS.has(node.name)) return true
|
|
348
|
+
if (node.attrs.get('asChild') === 'true' && node.children.length === 1) {
|
|
349
|
+
return BUTTON_TAGS.has(node.children[0].name)
|
|
350
|
+
}
|
|
351
|
+
return false
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
function lineIndex(text) {
|
|
355
|
+
const offsets = [0]
|
|
356
|
+
for (let i = 0; i < text.length; i++) {
|
|
357
|
+
if (text[i] === '\n') offsets.push(i + 1)
|
|
358
|
+
}
|
|
359
|
+
return offsets
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
function lineColAt(offsets, index) {
|
|
363
|
+
let lo = 0
|
|
364
|
+
let hi = offsets.length - 1
|
|
365
|
+
while (lo < hi) {
|
|
366
|
+
const mid = (lo + hi + 1) >> 1
|
|
367
|
+
if (offsets[mid] <= index) lo = mid
|
|
368
|
+
else hi = mid - 1
|
|
369
|
+
}
|
|
370
|
+
return { line: lo + 1, column: index - offsets[lo] + 1 }
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/**
|
|
374
|
+
* Every parent element in `text` with 2+ direct button-like children and no `gap-` in its own
|
|
375
|
+
* `className`, as `{ file, line, column, tag, count, excerpt }`.
|
|
376
|
+
*/
|
|
377
|
+
export function findViolations(text, file = '<input>') {
|
|
378
|
+
const tree = buildTree(tokenizeTags(text))
|
|
379
|
+
const offsets = lineIndex(text)
|
|
380
|
+
const violations = []
|
|
381
|
+
const lines = text.split(/\r?\n/)
|
|
382
|
+
|
|
383
|
+
function visit(node) {
|
|
384
|
+
if (node.name !== null) {
|
|
385
|
+
const buttonLikeCount = node.children.filter(isButtonLike).length
|
|
386
|
+
if (buttonLikeCount >= 2) {
|
|
387
|
+
const className = node.attrs.get('className') ?? ''
|
|
388
|
+
const exempt = GAP_PROVIDING_COMPONENTS.has(node.name) && !breaksExemption(className)
|
|
389
|
+
if (!exempt && !hasWorkingGap(className)) {
|
|
390
|
+
const { line, column } = lineColAt(offsets, node.start)
|
|
391
|
+
violations.push({
|
|
392
|
+
file,
|
|
393
|
+
line,
|
|
394
|
+
column,
|
|
395
|
+
tag: node.name,
|
|
396
|
+
count: buttonLikeCount,
|
|
397
|
+
excerpt: (lines[line - 1] ?? '').trim().slice(0, 120),
|
|
398
|
+
})
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
for (const child of node.children) visit(child)
|
|
403
|
+
}
|
|
404
|
+
visit(tree)
|
|
405
|
+
|
|
406
|
+
return violations.sort((a, b) => a.line - b.line || a.column - b.column)
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/** The one-line form the CLI prints per violation. */
|
|
410
|
+
export function formatViolation({ file, line, column, tag, count, excerpt }) {
|
|
411
|
+
return (
|
|
412
|
+
`${file}:${line}:${column} <${tag}> has ${count} button-like children with no working, ` +
|
|
413
|
+
`horizontal "gap-" on a flex/grid className\n` +
|
|
414
|
+
` ${excerpt}`
|
|
415
|
+
)
|
|
416
|
+
}
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
// Reads each component's real props from the TypeScript program, so a docs table can be checked
|
|
2
|
+
// against them. Used by src/components/docs/meta.test.ts and scripts/build-agent-docs.mjs.
|
|
3
|
+
import fs from 'node:fs'
|
|
4
|
+
import path from 'node:path'
|
|
5
|
+
import { fileURLToPath } from 'node:url'
|
|
6
|
+
import ts from 'typescript'
|
|
7
|
+
|
|
8
|
+
export const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..')
|
|
9
|
+
|
|
10
|
+
export const TIERS = ['atoms', 'molecules', 'organisms']
|
|
11
|
+
|
|
12
|
+
/** The Type cell of a row that documents a prop as deliberately not offered. */
|
|
13
|
+
export const NOT_OFFERED = '—'
|
|
14
|
+
|
|
15
|
+
/** Every component folder: `{ tier, slug, dir, metaFile, sourceFiles }`. */
|
|
16
|
+
export function componentFolders(root) {
|
|
17
|
+
const folders = []
|
|
18
|
+
for (const tier of TIERS) {
|
|
19
|
+
const tierDir = path.join(root, 'src/components', tier)
|
|
20
|
+
for (const slug of fs.readdirSync(tierDir).sort()) {
|
|
21
|
+
const dir = path.join(tierDir, slug)
|
|
22
|
+
if (!fs.statSync(dir).isDirectory()) continue
|
|
23
|
+
const files = fs.readdirSync(dir)
|
|
24
|
+
folders.push({
|
|
25
|
+
tier,
|
|
26
|
+
slug,
|
|
27
|
+
dir,
|
|
28
|
+
metaFile: files.filter(f => f.endsWith('.meta.ts')).map(f => path.join(dir, f))[0],
|
|
29
|
+
sourceFiles: files
|
|
30
|
+
.filter(f => f.endsWith('.tsx') && !f.endsWith('.test.tsx') && !f.endsWith('Docs.tsx'))
|
|
31
|
+
.map(f => path.join(dir, f)),
|
|
32
|
+
})
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return folders
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function createProgram(root) {
|
|
39
|
+
const config = ts.readConfigFile(path.join(root, 'tsconfig.app.json'), ts.sys.readFile)
|
|
40
|
+
const parsed = ts.parseJsonConfigFileContent(config.config, ts.sys, root)
|
|
41
|
+
return ts.createProgram(parsed.fileNames, parsed.options)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const isOwn = (declaration, root) => {
|
|
45
|
+
const file = path.resolve(declaration.getSourceFile().fileName)
|
|
46
|
+
return file.startsWith(path.resolve(root, 'src')) && !file.includes('node_modules')
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** What a tier's barrel exports from each folder: `{ [slug]: { values, types } }`. The barrel is
|
|
50
|
+
* the public surface; anything a component file exports for its neighbours only is not in it. */
|
|
51
|
+
export function publicExports(root, tier) {
|
|
52
|
+
const file = path.join(root, 'src/components', tier, 'index.ts')
|
|
53
|
+
const source = ts.createSourceFile(file, fs.readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, true)
|
|
54
|
+
const bySlug = {}
|
|
55
|
+
for (const statement of source.statements) {
|
|
56
|
+
if (!ts.isExportDeclaration(statement) || !statement.exportClause || !statement.moduleSpecifier) continue
|
|
57
|
+
const slug = statement.moduleSpecifier.text.split('/')[1]
|
|
58
|
+
const entry = (bySlug[slug] ??= { values: [], types: [], from: [] })
|
|
59
|
+
entry.from.push(statement.moduleSpecifier.text)
|
|
60
|
+
for (const element of statement.exportClause.elements) {
|
|
61
|
+
const isType = statement.isTypeOnly || element.isTypeOnly
|
|
62
|
+
entry[isType ? 'types' : 'values'].push(element.name.text)
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return bySlug
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** What a folder's files export, read from the type checker:
|
|
69
|
+
* - `components[name] = { all, own }` for everything callable with a props object. `all` is every
|
|
70
|
+
* prop the type accepts; `own` is the subset declared in this repository, which is what a docs
|
|
71
|
+
* table has to cover (nobody lists every native attribute). A prop typed `never` is one a
|
|
72
|
+
* union member forbids, not one it takes, so it is in neither.
|
|
73
|
+
* - `types[name] = [members]` for exported object types, such as the options a hook takes. */
|
|
74
|
+
export function exportsOfFolder(program, root, sourceFiles) {
|
|
75
|
+
const checker = program.getTypeChecker()
|
|
76
|
+
const components = {}
|
|
77
|
+
const types = {}
|
|
78
|
+
for (const file of sourceFiles) {
|
|
79
|
+
const source = program.getSourceFile(file)
|
|
80
|
+
const moduleSymbol = source && checker.getSymbolAtLocation(source)
|
|
81
|
+
if (!moduleSymbol) continue
|
|
82
|
+
for (const exported of checker.getExportsOfModule(moduleSymbol)) {
|
|
83
|
+
const symbol = exported.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(exported) : exported
|
|
84
|
+
if (symbol.flags & (ts.SymbolFlags.TypeAlias | ts.SymbolFlags.Interface)) {
|
|
85
|
+
types[exported.name] = checker.getPropertiesOfType(checker.getDeclaredTypeOfSymbol(symbol)).map(p => p.name)
|
|
86
|
+
continue
|
|
87
|
+
}
|
|
88
|
+
const declaration = symbol.valueDeclaration
|
|
89
|
+
if (!declaration || !/^[A-Z]/.test(exported.name)) continue
|
|
90
|
+
const signature = checker.getTypeOfSymbolAtLocation(symbol, declaration).getCallSignatures()[0]
|
|
91
|
+
if (!signature || signature.parameters.length === 0) continue
|
|
92
|
+
const propsType = checker.getTypeOfSymbolAtLocation(signature.parameters[0], declaration)
|
|
93
|
+
const all = new Set()
|
|
94
|
+
const own = new Set()
|
|
95
|
+
for (const member of propsType.isUnion() ? propsType.types : [propsType]) {
|
|
96
|
+
for (const prop of checker.getPropertiesOfType(member)) {
|
|
97
|
+
const type = checker.getNonNullableType(checker.getTypeOfSymbolAtLocation(prop, declaration))
|
|
98
|
+
if (type.flags & ts.TypeFlags.Never) continue
|
|
99
|
+
all.add(prop.name)
|
|
100
|
+
if ((prop.declarations ?? []).some(d => isOwn(d, root))) own.add(prop.name)
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
components[exported.name] = { all: [...all].sort(), own: [...own].sort() }
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return { components, types }
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** One docs row name, in the forms the tables use:
|
|
110
|
+
* `'...rest'` -> `{ rest: true }`; `'useToast()'` -> `{ call: 'useToast' }`;
|
|
111
|
+
* `'side (Content)'` -> `{ props: ['side'], part: 'Content' }`;
|
|
112
|
+
* `'aria-label / aria-labelledby'` -> `{ props: ['aria-label', 'aria-labelledby'] }`. */
|
|
113
|
+
export function parseRowName(name) {
|
|
114
|
+
if (name.startsWith('...')) return { rest: true }
|
|
115
|
+
if (name.endsWith('()')) return { call: name.slice(0, -2) }
|
|
116
|
+
const match = name.match(/^(.+) \(([^)]+)\)$/)
|
|
117
|
+
const props = (match ? match[1] : name).split(' / ')
|
|
118
|
+
return match ? { props, part: match[2] } : { props }
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const pascal = text => text.replace(/(^|\s+)(\w)/g, (_, _space, letter) => letter.toUpperCase())
|
|
122
|
+
|
|
123
|
+
/** Which export a `(Part)` qualifier names. Tried in order: the part as written, prefixed with
|
|
124
|
+
* the component's name, `Root` for the component itself, then the one export ending in it
|
|
125
|
+
* (`Grid` -> `ProductGrid`). Returns `{ kind: 'component' | 'type', name }` or undefined. */
|
|
126
|
+
export function resolvePart(part, componentName, { components, types }) {
|
|
127
|
+
const names = [part, componentName + part, pascal(part), componentName + pascal(part)]
|
|
128
|
+
for (const name of names) if (components[name]) return { kind: 'component', name }
|
|
129
|
+
for (const name of names) if (types[name]) return { kind: 'type', name }
|
|
130
|
+
if (part === 'Root' && components[componentName]) return { kind: 'component', name: componentName }
|
|
131
|
+
const ending = Object.keys(components).filter(name => name.endsWith(pascal(part)))
|
|
132
|
+
return ending.length === 1 ? { kind: 'component', name: ending[0] } : undefined
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Every disagreement between one docs props table and the real props, as sentences that say
|
|
136
|
+
* what to change. An empty array is a pass. `publicNames` is the barrel's value exports for the
|
|
137
|
+
* folder: an unqualified row is looked up on those, and coverage is asked of those only. */
|
|
138
|
+
export function checkPropsTable(meta, folderExports, publicNames) {
|
|
139
|
+
const { components, types } = folderExports
|
|
140
|
+
const publicComponents = publicNames.filter(name => components[name])
|
|
141
|
+
const problems = []
|
|
142
|
+
const listed = new Set()
|
|
143
|
+
for (const row of meta.props) {
|
|
144
|
+
const parsed = parseRowName(row.name)
|
|
145
|
+
if (parsed.rest) continue
|
|
146
|
+
if (parsed.call) {
|
|
147
|
+
if (!publicNames.includes(parsed.call)) {
|
|
148
|
+
problems.push(`"${row.name}": nothing named ${parsed.call} is exported from the barrel.`)
|
|
149
|
+
}
|
|
150
|
+
continue
|
|
151
|
+
}
|
|
152
|
+
let holders = publicComponents
|
|
153
|
+
let members
|
|
154
|
+
if (parsed.part) {
|
|
155
|
+
const target = resolvePart(parsed.part, meta.name, folderExports)
|
|
156
|
+
if (!target) {
|
|
157
|
+
problems.push(`"${row.name}": no export matches the part "${parsed.part}". Name an exported component or type.`)
|
|
158
|
+
continue
|
|
159
|
+
}
|
|
160
|
+
if (target.kind === 'type') members = types[target.name]
|
|
161
|
+
holders = target.kind === 'component' ? [target.name] : []
|
|
162
|
+
}
|
|
163
|
+
const absent = row.type === NOT_OFFERED
|
|
164
|
+
for (const prop of parsed.props) {
|
|
165
|
+
const accepted = members ? members.includes(prop) : holders.some(name => components[name].all.includes(prop))
|
|
166
|
+
if (absent && accepted) problems.push(`"${row.name}" is documented as not offered, but the type accepts it.`)
|
|
167
|
+
if (!absent && !accepted) {
|
|
168
|
+
problems.push(`"${row.name}": no such prop on ${members ? parsed.part : holders.join(', ')}. Remove the row or fix the name.`)
|
|
169
|
+
}
|
|
170
|
+
for (const name of holders) listed.add(`${name}.${prop}`)
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
for (const name of publicComponents) {
|
|
174
|
+
for (const prop of components[name].own) {
|
|
175
|
+
if (prop !== 'children' && !listed.has(`${name}.${prop}`)) {
|
|
176
|
+
problems.push(`${name} takes "${prop}", which the props table does not list. Add a row.`)
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
return problems
|
|
181
|
+
}
|