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 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 | 1x 1x 1x 1x 1x 1x 1x 35x 35x 35x 35x 37x 35x 1x 1x 1x 1x 34x 35x 35x 35x 35x 24x 2x 35x 35x 35x 35x 24x 24x 35x 35x 35x 24x 24x 35x 35x 35x 35x 35x 23x 24x 35x 24x 48x 48x 70x 70x 70x 12x 12x 12x 12x 12x 35x 35x 33x 33x 33x 12x 12x 11x 11x 11x 11x 11x 12x 35x 2x 2x 2x 2x 11x 11x 11x 11x 1x 2x 2x 11x 12x 12x 12x 12x 22x 22x 22x 12x 22x 23x 66x 66x 35x 35x 66x 66x 66x 35x 35x 66x 66x 35x 35x 66x 35x 35x 70x 70x 35x 35x 35x 35x 35x 35x 35x 35x 70x 70x 35x 35x 66x 35x 35x 35x 35x 35x 35x 35x 35x 35x 70x 35x 66x 156x 12x 24x 12x 24x 24x 24x 24x 24x 24x 64x 35x 24x 24x 24x 24x 35x 24x | /**
* Pure hook-surface taxonomy. Walks a built `themeData/{name}.json`
* payload and produces:
*
* 1. A nested `category → element → propertyAxis → [hook names]`
* tree, restricted to the public hook contract (hooks read by
* `themes/base.css` plus per-theme paint-only files).
* 2. A separate "theme-scoped" tree for hooks declared and read
* inside one theme only (path 3 of the three mechanism paths).
* 3. Cross-theme coverage info: which themes assign each hook, and
* the assigned values per-selector so a chip can call out
* `Same value` (the hook is doing no work) vs. `Value varies`.
*
* Browser-safe: no Node APIs, no postcss imports. Used by the
* storybook docs panel (`HookAPI.jsx`) and the sandbox migration
* planner's hook-surface view; both render the same data through
* different presentation layers.
*/
/* ------------------------------------------------------------------
* Public types
* ------------------------------------------------------------------ */
export type ThemeData = {
/** camelCase component directory name (e.g. `progressBar`). */
component?: string;
themes?: Record<string, ThemeBlock | undefined>;
editableSurfaces?: ReadonlyArray<EditableSurface>;
selectors?: Record<string, Record<string, Record<string, string>>>;
};
export interface ThemeBlock {
/**
* Per-selector hook assignments. Keyed by selector then hook name.
*/
selectors?: Record<string, Record<string, string>>;
/**
* `category → property-axis → hookName[]` of every hook the theme
* file *reads* via `var()`. Used to scope theme-private hooks to the
* active theme.
*/
reads?: Record<string, Record<string, ReadonlyArray<string>>>;
}
export interface EditableSurface {
hooks?: Record<string, ReadonlyArray<EditableSurfaceHookEntry>>;
}
export type EditableSurfaceHookEntry = string | { name: string; source?: 'base' | 'theme' };
/**
* `category → element-key → property-axis → [hook names]`. Keys are
* `Map`s rather than plain objects so insertion order and per-bucket
* sorting can be controlled deterministically. Element key is the raw
* BEM-element segment (`'remove'`, `'icon'`); the synthetic key
* `'__component__'` represents the no-element / component-root group.
*/
export type HookTree = Map<string, Map<string, Map<string, string[]>>>;
export interface ThemeCoverage {
/** Sorted theme names. */
themes: string[];
/** hook → set of theme names that assign it on at least one selector. */
coverage: Map<string, Set<string>>;
/** hook → selector → theme → assigned raw value. */
valuesByHook: Map<string, Map<string, Map<string, string>>>;
}
export interface CoverageVerdict {
have: number;
total: number;
themes: string[];
present: string[];
missing: string[];
}
export interface ValueDivergenceThemeValue {
/** Theme name (e.g. `cosmos`). */
theme: string;
/**
* Raw assigned value as authored in the theme's CSS, or `null` when
* the theme doesn't assign at this selector (partial coverage).
* Renderers display `null` as `(not assigned)` so the divergence
* popover stays informative even when a theme is silent.
*/
value: string | null;
}
export interface ValueDivergenceRow {
/** Selector at which the comparison is made (root or modifier compound). */
selector: string;
/**
* True when every theme assigns the same non-null value at this
* selector. False when values differ OR one or more themes are
* silent (partial coverage at this selector).
*/
same: boolean;
/**
* Per-theme values at this selector. Includes every theme in the
* portfolio (themes that don't assign appear with `value: null`),
* so partial-coverage hooks render as a meaningful comparison
* instead of being hidden.
*/
values: ValueDivergenceThemeValue[];
}
export interface ValueDivergenceVerdict {
/** True when every theme assigns the same value at every shared selector. */
allSame: boolean;
/**
* Structured per-selector breakdown: each entry lists which theme
* assigned what value at the selector. Renderers use this to build
* a tooltip / popover; a tabular layout reads better than the old
* flattened string.
*/
rows: ValueDivergenceRow[];
/**
* Plain-text fallback for environments without rich-tooltip support
* (or as the `aria-label` for the chip). Mirrors the structured
* `rows` data flattened for screen readers.
*/
tooltip: string;
}
/* ------------------------------------------------------------------
* Category + property-axis taxonomy
* ------------------------------------------------------------------ */
export const CATEGORY_ORDER: ReadonlyArray<string> = [
'color',
'spacing',
'margin',
'sizing',
'radius',
'font',
'shadow',
'image',
'position',
'gap',
'opacity',
'display',
'other',
];
export const CATEGORY_LABEL: Readonly<Record<string, string>> = {
color: 'Color',
spacing: 'Spacing',
margin: 'Margin',
sizing: 'Sizing',
radius: 'Radius',
font: 'Font',
shadow: 'Shadow',
image: 'Image',
position: 'Position',
gap: 'Gap',
opacity: 'Opacity',
display: 'Display',
other: 'Other',
};
const CATEGORY_TOKENS = new Set(CATEGORY_ORDER);
export interface PropertyAxisDef {
order: ReadonlyArray<string>;
labels: Readonly<Record<string, string>>;
}
/**
* Per-category property axes. The first segment after the category
* token in a hook name is the property axis; we group hooks by it
* inside each category card so e.g. "Foreground" / "Background" /
* "Border" become readable subheadings under Color.
*
* Categories absent from this map fall back to the raw axis token,
* humanised as "first segment after the category token".
*/
export const PROPERTY_AXES: Readonly<Record<string, PropertyAxisDef>> = {
color: {
order: ['foreground', 'background', 'border'],
labels: { foreground: 'Foreground', background: 'Background', border: 'Border' },
},
spacing: {
order: ['block', 'inline'],
labels: { block: 'Block axis', inline: 'Inline axis' },
},
margin: {
order: ['block', 'inline'],
labels: { block: 'Block axis', inline: 'Inline axis' },
},
font: {
order: ['size', 'weight', 'line-height', 'family', 'style'],
labels: {
size: 'Size',
weight: 'Weight',
'line-height': 'Line height',
family: 'Family',
style: 'Style',
},
},
sizing: {
order: ['border', 'height', 'width', 'min', 'max', 'size'],
labels: {
border: 'Border',
height: 'Height',
width: 'Width',
min: 'Min',
max: 'Max',
size: 'Size',
},
},
radius: { order: ['border'], labels: { border: 'Border' } },
shadow: { order: ['default'], labels: { default: 'Shadow' } },
};
const ELEMENT_LABELS_OVERRIDE: Readonly<Record<string, string>> = {
remove: 'Remove button',
icon: 'Icon',
'icon-group': 'Icon group',
'icon-group-spinner': 'Icon group spinner',
container: 'Container',
action: 'Action',
label: 'Label',
initials: 'Initials',
thumb: 'Thumb',
track: 'Track',
value: 'Value',
};
const STATE_SUFFIXES = new Set(['hover', 'focus', 'active', 'disabled']);
/** Synthetic key under `byElement` for the no-element / root group. */
export const COMPONENT_ROOT_KEY = '__component__';
/* ------------------------------------------------------------------
* Hook-name parsing
* ------------------------------------------------------------------ */
export interface ParsedHookName {
/** BEM element segment (`'remove'`, `'icon'`) or `null` for component-level. */
element: string | null;
/** Property axis after the category token; `'default'` when none applies. */
propertyAxis: string;
}
/**
* Parse a hook name into `{ element, propertyAxis }`.
* `--slds-c-pill-remove-color-foreground` →
* { element: 'remove', propertyAxis: 'foreground' }
* `--slds-c-pill-color-background-hover` →
* { element: null, propertyAxis: 'background' }
* `--slds-c-pill-icon-size` →
* { element: 'icon', propertyAxis: 'size' } (special-case: hooks
* ending in `-size` without a category token).
* `--slds-c-pill-shadow` →
* { element: null, propertyAxis: 'default' }
*/
export function parseHookName(componentPrefix: string, hookName: string): ParsedHookName {
const fullPrefix = `--slds-c-${componentPrefix}-`;
Iif (!hookName.startsWith(fullPrefix)) {
return { element: null, propertyAxis: 'default' };
}
const rest = hookName.slice(fullPrefix.length);
const parts = rest.split('-');
const catIdx = parts.findIndex((p) => CATEGORY_TOKENS.has(p));
if (catIdx === -1) {
Eif (parts.length >= 2) {
const tail = parts.at(-1) ?? 'default';
const head = parts.slice(0, -1).join('-');
return { element: head || null, propertyAxis: tail };
}
return { element: null, propertyAxis: parts[0] ?? 'default' };
}
const element = catIdx === 0 ? null : parts.slice(0, catIdx).join('-');
const afterCategory = parts.slice(catIdx + 1);
const axisParts = afterCategory.filter((p) => !STATE_SUFFIXES.has(p));
const propertyAxis = axisParts.length > 0 ? axisParts.join('-') : 'default';
return { element, propertyAxis };
}
export function humanizeElement(element: string | null): string {
if (!element) return 'Component';
Eif (ELEMENT_LABELS_OVERRIDE[element]) return ELEMENT_LABELS_OVERRIDE[element];
return element
.split('-')
.map((p) => (p.length ? p[0].toUpperCase() + p.slice(1) : p))
.join(' ');
}
export function humanizeProperty(category: string, propertyAxis: string): string | null {
const axis = PROPERTY_AXES[category];
Eif (axis?.labels?.[propertyAxis]) return axis.labels[propertyAxis];
if (propertyAxis === 'default') return null;
return propertyAxis.charAt(0).toUpperCase() + propertyAxis.slice(1).replaceAll('-', ' ');
}
/* ------------------------------------------------------------------
* Tree assembly
* ------------------------------------------------------------------ */
function placeHook(
tree: HookTree,
category: string,
element: string | null,
propertyAxis: string,
name: string,
): void {
let byElement = tree.get(category);
if (!byElement) {
byElement = new Map();
tree.set(category, byElement);
}
const elKey = element ?? COMPONENT_ROOT_KEY;
let byProperty = byElement.get(elKey);
if (!byProperty) {
byProperty = new Map();
byElement.set(elKey, byProperty);
}
let list = byProperty.get(propertyAxis);
Eif (!list) {
list = [];
byProperty.set(propertyAxis, list);
}
list.push(name);
}
function sortHookLists(tree: HookTree): void {
for (const byElement of tree.values()) {
for (const byProperty of byElement.values()) {
for (const list of byProperty.values()) list.sort((a, b) => a.localeCompare(b));
}
}
}
type SurfaceHookTriple = readonly [category: string, name: string, source: string | undefined];
function* iterateSurfaceHooks(surface: EditableSurface): Generator<SurfaceHookTriple> {
for (const [category, entries] of Object.entries(surface.hooks ?? {})) {
Iif (!Array.isArray(entries)) continue;
for (const entry of entries) {
Iif (typeof entry === 'string') {
yield [category, entry, undefined];
} else Eif (entry && typeof entry === 'object' && entry.name) {
yield [category, entry.name, entry.source];
}
}
}
}
/**
* Build the public hook tree (hooks the base contract reads — `source:
* 'base'` or a bare-string entry for back-compat). Theme-scoped hooks
* (`source: 'theme'`) are excluded; use `buildThemeScopedHookTree` for
* those.
*/
export function buildHookTree(themeData: ThemeData | null | undefined, componentPrefix: string): HookTree {
const tree: HookTree = new Map();
const seen = new Set<string>();
const surfaces = Array.isArray(themeData?.editableSurfaces) ? themeData.editableSurfaces : [];
for (const surface of surfaces) {
for (const [category, name, source] of iterateSurfaceHooks(surface)) {
Iif (seen.has(name)) continue;
if (source === 'theme') continue;
seen.add(name);
const { element, propertyAxis } = parseHookName(componentPrefix, name);
placeHook(tree, category, element, propertyAxis, name);
}
}
sortHookLists(tree);
return tree;
}
/**
* Hooks that only the named theme reads via `var()` — declared and
* consumed inside one theme, never reached by the base contract
* (path 3). Returns the same shape as `buildHookTree`. Pass
* `themeName` to scope to the active storybook theme so e.g.
* lightning-blue's panel doesn't surface cosmos-only hooks.
*/
export function buildThemeScopedHookTree(
themeData: ThemeData | null | undefined,
themeName: string,
componentPrefix: string,
): HookTree {
const tree: HookTree = new Map();
const seen = new Set<string>();
const themeReads = collectThemeReadHookNames(themeData?.themes?.[themeName] ?? null);
const surfaces = Array.isArray(themeData?.editableSurfaces) ? themeData.editableSurfaces : [];
for (const surface of surfaces) {
for (const [category, name, source] of iterateSurfaceHooks(surface)) {
if (seen.has(name) || source !== 'theme') continue;
Iif (!themeReads.has(name)) continue;
seen.add(name);
const { element, propertyAxis } = parseHookName(componentPrefix, name);
placeHook(tree, category, element, propertyAxis, name);
}
}
sortHookLists(tree);
return tree;
}
function collectThemeReadHookNames(themeBlock: ThemeBlock | null): Set<string> {
const out = new Set<string>();
for (const cats of Object.values(themeBlock?.reads ?? {})) {
for (const hooks of Object.values(cats ?? {})) {
Iif (!Array.isArray(hooks)) continue;
for (const name of hooks) Eif (name) out.add(name);
}
}
return out;
}
/* ------------------------------------------------------------------
* Theme coverage + value divergence
* ------------------------------------------------------------------ */
/**
* Walk every theme's per-selector assignment map and capture (a) which
* themes assign each hook, and (b) the assigned values per-selector
* for the divergence comparison. The divergence verdict compares
* per-selector across themes (root vs. each modifier compound
* separately) so modifier-scoped reassignments don't get mistaken for
* cross-theme divergence on the base contract.
*/
export function buildThemeCoverage(themeData: ThemeData | null | undefined): ThemeCoverage {
const themeNames = Object.keys(themeData?.themes ?? {}).sort((a, b) => a.localeCompare(b));
const coverage = new Map<string, Set<string>>();
const valuesByHook = new Map<string, Map<string, Map<string, string>>>();
for (const themeName of themeNames) {
const block = themeData?.themes?.[themeName];
Iif (!block) continue;
ingestThemeAssignments(block, themeName, coverage, valuesByHook);
}
return { themes: themeNames, coverage, valuesByHook };
}
function ingestThemeAssignments(
tBlock: ThemeBlock,
themeName: string,
coverage: Map<string, Set<string>>,
valuesByHook: Map<string, Map<string, Map<string, string>>>,
): void {
for (const [selector, hookMap] of Object.entries(tBlock.selectors ?? {})) {
for (const [hook, value] of Object.entries(hookMap ?? {})) {
let presentIn = coverage.get(hook);
if (!presentIn) {
presentIn = new Set();
coverage.set(hook, presentIn);
}
presentIn.add(themeName);
let bySelector = valuesByHook.get(hook);
if (!bySelector) {
bySelector = new Map();
valuesByHook.set(hook, bySelector);
}
let perTheme = bySelector.get(selector);
if (!perTheme) {
perTheme = new Map();
bySelector.set(selector, perTheme);
}
Eif (!perTheme.has(themeName)) perTheme.set(themeName, value);
}
}
}
/**
* Coverage shape `{ have, total, themes, present, missing }` for a
* single hook. Same shape `recommendForHook` accepts.
*/
export function computeCoverage(name: string, themeCoverage: ThemeCoverage): CoverageVerdict {
const themes = themeCoverage.themes;
const setForHook = themeCoverage.coverage.get(name) ?? new Set<string>();
const present = themes.filter((t) => setForHook.has(t));
const missing = themes.filter((t) => !setForHook.has(t));
return { have: present.length, total: themes.length, themes, present, missing };
}
/**
* Walk every selector at least one theme assigns at and produce a
* per-selector breakdown of every theme's value. Themes that don't
* assign at a given selector show up with `value: null` so the
* verdict is informative for partial-coverage hooks too (where one
* theme paints and the other is silent — that's a meaningful kind
* of "value varies"). Returns `null` only when no theme assigns the
* hook anywhere.
*
* `allSame` is `true` only when every theme assigns the same
* non-null value at every selector. Any partial coverage flips it
* to `false`.
*/
export function computeValueDivergence(
name: string,
themeCoverage: ThemeCoverage,
): ValueDivergenceVerdict | null {
const bySelector = themeCoverage.valuesByHook.get(name);
Iif (!bySelector || bySelector.size === 0) return null;
const themeNames = themeCoverage.themes;
Iif (themeNames.length < 2) return null;
let allSame = true;
const rows: ValueDivergenceRow[] = [];
for (const [selector, perTheme] of bySelector) {
const themeValues: ValueDivergenceThemeValue[] = themeNames.map((t) => ({
theme: t,
value: perTheme.get(t) ?? null,
}));
const assignedValues = themeValues.map((tv) => tv.value).filter((v): v is string => v !== null);
const partialAtSelector = assignedValues.length < themeValues.length;
const normalized = assignedValues.map(normalizeValueForCompare);
const allAssignedMatch = normalized.length > 0 && normalized.every((v) => v === normalized[0]);
const selectorSame = !partialAtSelector && allAssignedMatch;
if (!selectorSame) allSame = false;
rows.push({ selector, same: selectorSame, values: themeValues });
}
Iif (rows.length === 0) return null;
return { allSame, rows, tooltip: flattenRowsForTooltip(rows) };
}
function flattenRowsForTooltip(rows: ReadonlyArray<ValueDivergenceRow>): string {
const lines: string[] = [];
for (const row of rows) {
lines.push(`${row.selector} ${row.same ? '·' : '⚠'}`);
for (const { theme, value } of row.values) {
lines.push(` ${theme}: ${value ?? '(not assigned)'}`);
}
}
return lines.join('\n');
}
function normalizeValueForCompare(value: string | null | undefined): string {
return String(value ?? '')
.replace(/\s+/g, ' ')
.trim()
.toLowerCase();
}
/* ------------------------------------------------------------------
* Display ordering
* ------------------------------------------------------------------ */
/** Stable category order: known categories first, then any extras. */
export function orderedCategoryKeys(tree: HookTree): string[] {
const out = CATEGORY_ORDER.filter((c) => tree.has(c));
for (const cat of tree.keys()) {
Iif (!out.includes(cat)) out.push(cat);
}
return out;
}
/** Component first, then alphabetical by humanised label. */
export function orderedElementKeys(byElement: Map<string, unknown>): string[] {
const keys = [...byElement.keys()];
keys.sort((a, b) => {
if (a === COMPONENT_ROOT_KEY) return -1;
if (b === COMPONENT_ROOT_KEY) return 1;
return humanizeElement(a).localeCompare(humanizeElement(b));
});
return keys;
}
/**
* Stable property-axis order inside a category: known axes first
* (per `PROPERTY_AXES[category].order`), then any extras alphabetically.
*/
export function orderedPropertyKeys(category: string, byProperty: Map<string, unknown>): string[] {
const axes = PROPERTY_AXES[category];
Iif (!axes) return [...byProperty.keys()].sort((a, b) => a.localeCompare(b));
const out: string[] = [];
for (const key of axes.order) if (byProperty.has(key)) out.push(key);
for (const key of byProperty.keys()) Iif (!out.includes(key)) out.push(key);
return out;
}
/** Total hook count under one category bucket. */
export function totalHooksInCategory(byElement: Map<string, Map<string, string[]>> | undefined): number {
Iif (!byElement) return 0;
let sum = 0;
for (const byProperty of byElement.values()) {
for (const list of byProperty.values()) sum += list.length;
}
return sum;
}
|