Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 | 1x 1x 1x 1x 1x 1x 1x 1x 24x 1x 11x 13x 11x 1x 1x 11x 11x 11x 11x 11x 2x 2x 2x 2x 1x 20x 23x 23x 23x 17x 17x 23x 23x 2x 2x 21x 1x 11x 11x 11x 11x 11x 11x 11x 2x 2x 2x 1x 10x 10x 2x 8x 1x 8x 10x 10x 10x 10x 10x 18x 18x 21x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 1x 8x 1x 1x 1x 1x 1x 1x 8x 8x 10x 10x 9x 9x 10x 8x 8x 8x 8x 8x 8x 9x 9x 108x 108x 9x 9x 9x 1x 1x 1x 1x 44x 44x 50x 2x 2x 2x 2x 1x 10x 10x 21x 21x 21x 10x 120x 10x 10x 1x 9x 9x 9x 12x 12x 12x 24x 3x 24x 24x 12x 12x 12x 12x 12x 10x 21x 10x 12x 2x 9x 9x 10x 9x 1x 9x 9x 9x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 9x 8x 1x 8x 8x 1x 8x 8x 8x 8x 8x 1x 8x 8x 8x 1x 1x 1x 1x 9x 9x 1x 1x 1x 8x 8x 8x | /**
* Theme-data build.
*
* For every theme-layer base file (src/{system}/<component>/themes/base.css),
* extracts:
* - hook *references* in base.css (the public API surface)
* - hook *assignments* in base.css (binds under state/composition selectors)
* - hook *assignments* per theme (cosmos, lightning-blue, …)
*
* Writes one JSON report per component to build/themeData/<component>.json.
*
* `selectors` and `themes[*].selectors` are kept verbatim; `editableSurfaces`
* is a Rule-5-canonical projection (idle root, modifier compounds, descendants)
* for consumers that need an authoring-surface view.
*/
import path from 'node:path';
import fs from 'fs-extra';
import * as glob from 'glob';
import postcss from 'postcss';
import postcssAtImport from 'postcss-import';
import postcssNested from 'postcss-nested';
import postcssRemoveComments from 'postcss-discard-comments';
import { args } from './args.js';
import { root } from './config.js';
const flattenPlugins = [postcssAtImport({ cache: false }), postcssRemoveComments(), postcssNested()];
const HOOK_TOKEN_RE = /--slds-c-[a-z0-9-]+/gi;
const HOOK_PROP_RE = /^--slds-c-[a-z0-9-]+$/i;
const PSEUDO_STATE_RE =
/:(?:focus-visible|focus-within|placeholder-shown|hover|focus|active|disabled|checked|target|visited|empty|link)\b/g;
const DISABLED_ATTR_RE = /\[disabled\]/g;
const NOT_PSEUDO_RE = /:not\([^)]*\)/g;
const WHITESPACE_RUN_RE = /\s+/g;
/** Strip state qualifiers from one comma branch to produce its idle form. */
const idleFormOfBranch = (branch) =>
branch
.replaceAll(NOT_PSEUDO_RE, '')
.replaceAll(PSEUDO_STATE_RE, '')
.replaceAll(DISABLED_ATTR_RE, '')
.replaceAll(WHITESPACE_RUN_RE, ' ')
.trim();
/** Strip state qualifiers from every comma branch and dedupe. */
const idleFormOfSelector = (selector) => {
const parts = selector
.split(',')
.map((s) => idleFormOfBranch(s))
.filter(Boolean);
return Array.from(new Set(parts)).join(', ');
};
/** BEM modifier class — single underscore (`_`), not BEM element (`__`). */
const MODIFIER_CLASS_RE = /\.slds-([a-z][a-z0-9]*)_(?!_)([a-z][a-z0-9-]*)/g;
/**
* Return the Rule 5 compound form (`.slds-{root}.slds-{root}_{mod}`) for a
* branch that targets a single modifier on `component`. `null` otherwise.
*/
const compoundFormForModifier = (branch, component) => {
const idle = idleFormOfBranch(branch);
Iif (!idle) return null;
const modifierClassRe = new RegExp(`\\.slds-${component}_(?!_)([a-z][a-z0-9-]*)`);
const match = idle.match(modifierClassRe);
if (!match) return null;
const modifier = match[1];
const compound = `.slds-${component}.slds-${component}_${modifier}`;
// Theme files may already author the compound form directly.
Iif (idle.includes(compound)) return idle;
return idle.replace(new RegExp(`\\.slds-${component}_${modifier}`), compound);
};
/**
* Add hooks to a surface, bucketed by category. `source` is `'base'` (read by
* base.css) or `'theme'` (theme-only write). `'base'` always wins on conflict.
*
* Internally, `surface.hooks` is a `Map<category, Map<hookName, entry>>` for
* O(1) dedup; `buildEditableSurfaces` materializes it to the array form on
* its way out.
*/
const addHooksToSurface = (surface, hooks, source) => {
for (const hook of hooks) {
const cat = categorizeHook(hook);
let bucket = surface.hooks.get(cat);
if (!bucket) {
bucket = new Map();
surface.hooks.set(cat, bucket);
}
const existing = bucket.get(hook);
if (existing) {
Iif (source === 'base' && existing.source !== 'base') existing.source = 'base';
continue;
}
bucket.set(hook, { name: hook, source });
}
};
/**
* Resolve a comma-list to its single Rule-5 compound, or `null` if any branch
* isn't a modifier of `component` or branches disagree on which modifier.
*/
const resolveModifierCompound = (selector, component) => {
const branches = selector
.split(',')
.map((s) => s.trim())
.filter(Boolean);
Iif (branches.length === 0) return null;
const compounds = new Set();
for (const b of branches) {
const compound = compoundFormForModifier(b, component);
if (!compound) return null;
compounds.add(compound);
}
Iif (compounds.size !== 1) return null;
return [...compounds][0];
};
const surfaceShapeForRead = (idle, component, componentRoot) => {
const compoundKey = resolveModifierCompound(idle, component);
if (compoundKey) {
return { surfaceKey: compoundKey, role: 'modifier', targetSelector: compoundKey };
}
return {
surfaceKey: idle,
role: idle === componentRoot ? 'component-base' : 'descendant',
targetSelector: idle.split(',')[0]?.trim() ?? idle,
};
};
const ingestBaseReadSites = ({ selectors, component, componentRoot, ensureSurface, baseContractHooks }) => {
for (const [readSelector, categories] of Object.entries(selectors ?? {})) {
const idle = idleFormOfSelector(readSelector);
Iif (!idle) continue;
const { surfaceKey, role, targetSelector } = surfaceShapeForRead(idle, component, componentRoot);
const surface = ensureSurface(surfaceKey, role, targetSelector);
for (const hooks of Object.values(categories)) {
Iif (!Array.isArray(hooks)) continue;
addHooksToSurface(surface, hooks, 'base');
for (const hook of hooks) baseContractHooks.add(hook);
}
}
};
const surfaceForThemeWrite = ({ themeSelector, component, surfaces, ensureSurface }) => {
const compoundKey = resolveModifierCompound(themeSelector, component);
Iif (compoundKey) return ensureSurface(compoundKey, 'modifier', compoundKey);
const idle = idleFormOfSelector(themeSelector);
Iif (!idle) return null;
return surfaces.get(idle) ?? null;
};
const writeHooksToSurface = ({ surface, hookMap, baseContractHooks }) => {
for (const hook of Object.keys(hookMap)) {
const source = baseContractHooks.has(hook) ? 'base' : 'theme';
addHooksToSurface(surface, [hook], source);
}
};
const ingestThemeWrites = ({ themes, component, surfaces, ensureSurface, baseContractHooks }) => {
for (const tBlock of Object.values(themes ?? {})) {
for (const [themeSelector, hookMap] of Object.entries(tBlock?.selectors ?? {})) {
const surface = surfaceForThemeWrite({ themeSelector, component, surfaces, ensureSurface });
Iif (!surface) continue;
writeHooksToSurface({ surface, hookMap, baseContractHooks });
}
}
};
/**
* Build editable-surface entries: one per Rule-5-canonical authoring surface.
* Output: `[{ surface, targetSelector, role, hooks: { [cat]: [...] } }]`.
*/
const ROLE_ORDER = { 'component-base': 0, modifier: 1, descendant: 2 };
const buildEditableSurfaces = (component, selectors, themes) => {
const surfaces = new Map();
const ensureSurface = (key, role, targetSelector) => {
let entry = surfaces.get(key);
if (!entry) {
entry = { surface: key, targetSelector, role, hooks: new Map() };
surfaces.set(key, entry);
}
return entry;
};
const componentRoot = `.slds-${component}`;
const baseContractHooks = new Set();
ingestBaseReadSites({ selectors, component, componentRoot, ensureSurface, baseContractHooks });
ingestThemeWrites({ themes, component, surfaces, ensureSurface, baseContractHooks });
const ordered = Array.from(surfaces.values()).sort((a, b) => ROLE_ORDER[a.role] - ROLE_ORDER[b.role]);
return ordered.map(({ surface, targetSelector, role, hooks }) => {
const orderedHooks = {};
for (const cat of CATEGORIES) {
const bucket = hooks.get(cat);
if (bucket && bucket.size > 0) orderedHooks[cat] = Array.from(bucket.values());
}
const otherBucket = hooks.get('other');
Iif (otherBucket && otherBucket.size > 0) orderedHooks.other = Array.from(otherBucket.values());
return { surface, targetSelector, role, hooks: orderedHooks };
});
};
const CATEGORIES = [
'color',
'spacing',
'margin',
'sizing',
'radius',
'font',
'shadow',
'image',
'position',
'gap',
'opacity',
'display',
];
const CATEGORY_SET = new Set(CATEGORIES);
/** Suffixes that resolve to `sizing` without the literal token. */
const SIZING_SHORTHAND_SUFFIXES = new Set(['size', 'height', 'width']);
const categorizeHook = (hook) => {
const parts = hook.slice('--slds-c-'.length).split('-');
for (let i = 1; i < parts.length; i++) {
if (CATEGORY_SET.has(parts[i])) return parts[i];
}
const tail = parts.at(-1);
const prev = parts.at(-2);
// `line-height` is font, not sizing.
Eif (tail && SIZING_SHORTHAND_SUFFIXES.has(tail) && !(tail === 'height' && prev === 'line')) {
return 'sizing';
}
if (tail === 'height' && prev === 'line') return 'font';
return 'other';
};
const groupHooksByCategory = (hooks) => {
const buckets = {};
for (const hook of hooks) {
const cat = categorizeHook(hook);
if (!buckets[cat]) buckets[cat] = [];
buckets[cat].push(hook);
}
const ordered = {};
for (const cat of CATEGORIES) if (buckets[cat]) ordered[cat] = buckets[cat];
Iif (buckets.other) ordered.other = buckets.other;
return ordered;
};
/**
* Single walk over the PostCSS root. For every rule, collects:
* - `reads`: `{ [selector]: { [category]: [hook, ...] } }`
* hooks referenced inside `var()` calls
* - `assignments`: `{ [selector]: { [hookProp]: value } }`
* `--slds-c-*: value` writes (last-writer-wins per selector)
*/
const extractHooks = (rootNode) => {
const reads = {};
const assignments = {};
rootNode.walkRules((rule) => {
const readsForRule = new Set();
const writesForRule = {};
rule.walkDecls((decl) => {
if (HOOK_PROP_RE.test(decl.prop)) {
writesForRule[decl.prop] = decl.value.trim();
}
const matches = decl.value.match(HOOK_TOKEN_RE);
if (matches) for (const m of matches) readsForRule.add(m);
});
const hasReads = readsForRule.size > 0;
const hasWrites = Object.keys(writesForRule).length > 0;
Iif (!hasReads && !hasWrites) return;
const selector = rule.selector.replace(/\s+/g, ' ').trim();
if (hasReads) {
const existing = reads[selector] ?? new Set();
for (const hook of readsForRule) existing.add(hook);
reads[selector] = existing;
}
if (hasWrites) {
assignments[selector] = { ...(assignments[selector] ?? {}), ...writesForRule };
}
});
const categorizedReads = {};
for (const [selector, hookSet] of Object.entries(reads)) {
categorizedReads[selector] = groupHooksByCategory(hookSet);
}
return { reads: categorizedReads, assignments };
};
/** Read + flatten one CSS file → its extracted reads/assignments. */
const extractFromCssFile = async (filePath) => {
const css = await fs.readFile(filePath, 'utf8');
const result = await postcss(flattenPlugins).process(css, { from: filePath });
return extractHooks(result.root);
};
/** Read + flatten one theme file → { selectors, reads, source } or null. */
const buildThemeAssignments = async (themeFilePath) => {
const { reads, assignments } = await extractFromCssFile(themeFilePath);
Iif (Object.keys(assignments).length === 0 && Object.keys(reads).length === 0) return null;
return { source: path.relative(root, themeFilePath), selectors: assignments, reads };
};
const buildOne = async (baseFilePath, outputDir) => {
const component = path.basename(path.dirname(path.dirname(baseFilePath)));
const source = path.relative(root, baseFilePath);
const { reads: selectors, assignments: baseAssignments } = await extractFromCssFile(baseFilePath);
const themesDir = path.dirname(baseFilePath);
const themeFiles = glob
.sync(path.resolve(themesDir, '*.css'))
.filter((f) => path.basename(f) !== 'base.css')
.sort();
const themeResults = await Promise.all(
themeFiles.map(async (themeFile) => ({
name: path.basename(themeFile, '.css'),
data: await buildThemeAssignments(themeFile),
})),
);
const themes = {};
for (const { name, data } of themeResults) {
Eif (data) themes[name] = data;
}
const editableSurfaces = buildEditableSurfaces(component, selectors, themes);
const outputPath = path.resolve(outputDir, `${component}.json`);
const payload = { component, source, selectors, baseAssignments, themes, editableSurfaces };
await fs.outputFile(outputPath, `${JSON.stringify(payload, null, 2)}\n`);
const baseAssignmentCount = Object.values(baseAssignments).reduce(
(sum, hooks) => sum + Object.keys(hooks).length,
0,
);
const baseAssignmentSummary = baseAssignmentCount > 0 ? ` + ${baseAssignmentCount} base assignments` : '';
const themeSummary = Object.keys(themes).length > 0 ? ` + themes: ${Object.keys(themes).join(', ')}` : '';
console.info(
` ✓ ${component} (${Object.keys(selectors).length} selectors${baseAssignmentSummary}${themeSummary})`,
);
};
const COMPONENT_CONCURRENCY = 8;
const runWithConcurrency = async (items, limit, worker) => {
let cursor = 0;
const runners = Array.from({ length: Math.min(limit, items.length) }, async () => {
while (cursor < items.length) {
const i = cursor++;
await worker(items[i]);
}
});
await Promise.all(runners);
};
export const buildThemeData = async () => {
const system = args['--system'];
const outputDir = path.resolve(root, 'build/themeData');
const baseFiles = glob.sync(path.resolve(root, `src/${system}/**/themes/base.css`)).sort();
if (baseFiles.length === 0) {
console.info('buildThemeData: no themes/base.css files found.');
return;
}
console.info(
`Extracting component hook references + per-theme assignments from ${baseFiles.length} components...`,
);
await fs.emptyDir(outputDir);
await runWithConcurrency(baseFiles, COMPONENT_CONCURRENCY, (file) => buildOne(file, outputDir));
};
/** Rebuild themeData for a single component (used by the watch loop). */
export const buildOneThemeData = async (componentDir) => {
const baseFilePath = path.resolve(componentDir, 'themes/base.css');
if (!(await fs.pathExists(baseFilePath))) {
const component = path.basename(componentDir);
console.info(` · ${component} (skipped: no themes/base.css)`);
return;
}
const outputDir = path.resolve(root, 'build/themeData');
await fs.ensureDir(outputDir);
await buildOne(baseFilePath, outputDir);
};
|