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 | 10x 10x 1x 9x 9x 19x 14x 14x 14x 14x 14x 13x 13x 11x 9x 46x 46x 17x 1x 1x 1x 26x 26x 34x 33x 34x 33x 33x 30x 22x 1x 2x 23x 23x 23x 23x 23x 23x 85x 85x 85x 85x 85x 43x 43x 43x 43x 85x 23x 23x 23x 23x 23x 32x 5x 5x 27x 8x 8x 19x 6x 5x 6x 13x 10x 9x 9x 4x 5x 9x 23x 4x 4x 4x 7x 7x 7x 4x 4x | /**
* CSF → UIF-preset extractor.
*
* Reads a `*.uif.stories.js` file's source, statically parses the named exports'
* `args` objects, and translates the flat args map into the four override buckets
* the sandbox catalog consumes (slotValues / variantOverrides / modifierOverrides /
* iconName). The translation needs the matching UIF to disambiguate: a given arg
* key is routed to the bucket whose schema declares it.
*
* Static parse via acorn so story files can `import` anything without the
* extractor having to evaluate (or stub) the imports. Dynamic args (functions,
* spreads from other exports) are silently skipped — those aren't preset material
* anyway and the safe behavior is "omit, don't crash."
*
* The expected CSF authoring shape (kept deliberately narrow):
*
* export default { title: 'Badge' };
*
* export const Success = {
* name: 'Success', // optional; falls back to export name
* parameters: { description: 'Theme: success' }, // optional
* args: {
* theme: 'success', // matches a variant or modifier name in the UIF
* default: 'Active', // matches a slot name
* iconName: 'utility:check',// reserved name; threads into iconName
* },
* };
*
* Keys that don't match any variant/modifier/slot in the UIF are dropped — same
* "silent omit" stance. This keeps story authoring forgiving while the catalog
* stays predictable.
*/
import * as acorn from 'acorn';
// ---------------------------------------------------------------------------
// Static AST extraction
// ---------------------------------------------------------------------------
/**
* Parse a story file's source and return its named exports' args as plain
* JS objects. Returns an array of `{exportName, displayName?, description?, args}`.
* Unparseable exports are dropped, not thrown — callers can move on without
* crashing the whole catalog build.
*/
export function parseStoryExports(source) {
let ast;
try {
ast = acorn.parse(source, {
ecmaVersion: 'latest',
sourceType: 'module',
allowImportExportEverywhere: false,
});
} catch {
return [];
}
const out = [];
for (const node of ast.body) {
if (node.type !== 'ExportNamedDeclaration') continue;
Iif (!node.declaration || node.declaration.type !== 'VariableDeclaration') continue;
for (const decl of node.declaration.declarations) {
Iif (decl.id.type !== 'Identifier') continue;
const exportName = decl.id.name;
if (!decl.init || decl.init.type !== 'ObjectExpression') continue;
const storyObj = evalLiteralObject(decl.init);
if (!storyObj || typeof storyObj !== 'object') continue;
out.push({
exportName,
displayName: typeof storyObj.name === 'string' ? storyObj.name : undefined,
description:
storyObj.parameters &&
typeof storyObj.parameters === 'object' &&
typeof storyObj.parameters.description === 'string'
? storyObj.parameters.description
: undefined,
args: storyObj.args && typeof storyObj.args === 'object' ? storyObj.args : {},
});
}
}
return out;
}
/**
* Evaluate an AST node that should resolve to a JS literal. Returns the value or
* undefined when the node isn't a literal shape (function, identifier, template
* with expressions, etc.). Used recursively on ObjectExpression / ArrayExpression
* so we can pull `args` objects directly out of the AST without `eval`.
*/
function evalLiteralObject(node) {
Iif (!node) return undefined;
switch (node.type) {
case 'Literal':
return node.value;
case 'TemplateLiteral':
// Only constant templates survive; with any ${expr} we'd need to evaluate.
return node.expressions.length === 0 ? node.quasis.map((q) => q.value.cooked).join('') : undefined;
case 'UnaryExpression':
Eif (
node.operator === '-' &&
node.argument.type === 'Literal' &&
typeof node.argument.value === 'number'
) {
return -node.argument.value;
}
return undefined;
case 'ArrayExpression': {
const out = [];
for (const el of node.elements) {
if (!el) return undefined;
const v = evalLiteralObject(el);
if (v === undefined) return undefined;
out.push(v);
}
return out;
}
case 'ObjectExpression': {
const out = {};
for (const prop of node.properties) {
if (prop.type !== 'Property' || prop.computed || prop.kind !== 'init') return undefined;
const key =
prop.key.type === 'Identifier'
? prop.key.name
: prop.key.type === 'Literal'
? String(prop.key.value)
: undefined;
Iif (key === undefined) return undefined;
const v = evalLiteralObject(prop.value);
if (v === undefined) return undefined;
out[key] = v;
}
return out;
}
default:
return undefined;
}
}
// ---------------------------------------------------------------------------
// Args → override-bucket translation
// ---------------------------------------------------------------------------
const RESERVED_ARG_ICON_NAME = 'iconName';
/**
* Build an index from a UIF structure of every arg key the catalog knows how to
* route. The same key cannot legitimately collide between variants/modifiers/slots
* for one component; precedence is variant > modifier > slot to match how Storybook
* controls usually layer them.
*
* Variants and modifiers are read both from the root structure node and from any
* nested child (the resolved UIF keeps some variants — e.g. positional ones — on
* the child that owns them rather than hoisting to the root). Slots are collected
* recursively via each node's `slot` declaration.
*
* Returns: {
* variants: Set<string>,
* modifiers: Set<string>,
* slots: Set<string>,
* slotRestrict: Map<slotName, Set<componentName>> — empty set for text slots,
* populated with PascalCase component names for restricted (component) slots.
* Used by translateArgs to decide whether a slot-arg value should fill the
* text override or the component override.
* }
*/
function buildArgIndex(uif) {
const structure = uif?.structure ?? {};
const variants = new Set();
const modifiers = new Set();
const slots = new Set();
const slotRestrict = new Map();
const walk = (n) => {
Iif (!n || typeof n !== 'object') return;
for (const v of n.variants ?? []) Eif (v?.name) variants.add(v.name);
for (const m of n.modifiers ?? []) Eif (m?.name) modifiers.add(m.name);
const slot = n.slot;
if (slot?.name) {
slots.add(slot.name);
const restrict = Array.isArray(slot.restrict) ? slot.restrict : [];
// PascalCase entries are component references; lowercase entries are HTML tag
// hints (e.g. "div", "span"). The catalog only treats component refs as
// component-slot fills — text slots accept arbitrary strings.
const components = new Set(restrict.filter((r) => typeof r === 'string' && /^[A-Z]/.test(r)));
slotRestrict.set(slot.name, components);
}
for (const c of n.children ?? []) walk(c);
};
walk(structure);
return { variants, modifiers, slots, slotRestrict };
}
/**
* Translate a single story's flat `args` map into the four override buckets.
* Unrecognized keys are dropped. The result shape matches what dataLoader.js
* (in the sandbox) expects: every bucket present, even if empty.
*/
export function translateArgs(args, uif) {
const idx = buildArgIndex(uif);
const out = {
slotValues: { overrides: {}, components: {} },
variantOverrides: {},
modifierOverrides: {},
iconName: null,
};
for (const [key, value] of Object.entries(args)) {
if (key === RESERVED_ARG_ICON_NAME) {
if (typeof value === 'string') out.iconName = value;
continue;
}
if (idx.variants.has(key)) {
if (typeof value === 'string') out.variantOverrides[key] = value;
continue;
}
if (idx.modifiers.has(key)) {
if (typeof value === 'string' || typeof value === 'boolean') {
out.modifierOverrides[key] = value;
}
continue;
}
if (idx.slots.has(key)) {
if (typeof value !== 'string') continue;
// Slot routing branches on whether the value matches a component name listed
// in the slot's `restrict`. A match opts the slot into its component-fill
// path (which also triggers UIF's `renderWhen: 'slotFilled'` on the parent
// node, so optional nodes like Badge's `icon` appear in the rendered DOM).
// Anything else is treated as text — the natural reading for slots whose
// restrict is empty or HTML-only.
const allowedComponents = idx.slotRestrict.get(key);
if (allowedComponents && allowedComponents.has(value)) {
out.slotValues.components[key] = value;
} else {
out.slotValues.overrides[key] = value;
}
continue;
}
// Unknown arg → silently dropped. See module-doc rationale.
}
return out;
}
/**
* High-level entry: extract every preset from a story file's source against its
* UIF, returning the array shape the catalog manifest expects. Stories without
* args at all are dropped (no point in a preset that does nothing).
*/
export function extractPresetsFromStorySource(source, uif) {
const exports = parseStoryExports(source);
const presets = [];
for (const entry of exports) {
const argsBuckets = translateArgs(entry.args, uif);
const anyApplied =
Object.keys(argsBuckets.slotValues.overrides).length > 0 ||
Object.keys(argsBuckets.slotValues.components).length > 0 ||
Object.keys(argsBuckets.variantOverrides).length > 0 ||
Object.keys(argsBuckets.modifierOverrides).length > 0 ||
argsBuckets.iconName !== null;
if (!anyApplied) continue;
presets.push({
name: entry.displayName ?? entry.exportName,
description: entry.description ?? '',
args: argsBuckets,
});
}
return presets;
}
|