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 | 90x 53x 42x 42x 42x 42x 42x 42x 30x 12x 42x 42x 42x 42x 42x 35x 42x 42x 42x 35x 6x 29x 29x 7x 1x 6x 42x 1x 5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 42x 42x 42x 42x 18x 5x 5x 5x 42x 7x 3x 4x 4x 42x 42x 12x 12x 12x 3x 9x 3x 6x 6x 12x 3x 3x 1x 4x 4x 4x 4x 4x 4x 4x 4x 2x 2x 2x 4x 2x 2x 2x 4x 2x 3x 4x 1x 1x 4x 1x 1x 2x 1x 45x 2x 2x 1x 1x 1x 1x 45x 4x 4x 2x 2x 2x 4x 1x 41x 41x 1x 40x 13x 13x 9x 36x 36x 1x 35x | /**
* JSX Builder
*
* Transforms UIF structure definitions into JSX syntax.
*/
import type {
StructureMetadata,
SlotMetadata,
ComposedComponentMetadata,
ClassNameRule,
RenderWhen,
RenderWhenPropMatch,
} from '@fds-uif/generator-base/browser';
import type { GenerationContext } from './types.js';
type Child = StructureMetadata | SlotMetadata | ComposedComponentMetadata;
function isComposedComponent(child: Child): child is ComposedComponentMetadata {
return 'type' in child && (child as ComposedComponentMetadata).type === 'component';
}
function isSlotMetadata(child: Child): child is SlotMetadata {
return 'type' in child && (child as SlotMetadata).type === 'slot';
}
/**
* Build JSX for a structure node.
*
* `isRoot` opts the node into the component-level computed className
* (`{computedClassName}`) and the `style={style}` pass-through. Non-root nodes
* use their own `node.classNames` to derive a per-node className expression
* (or fall back to a static class).
*/
export function buildJsx(structure: StructureMetadata, context: GenerationContext, isRoot = false): string {
const { indent } = context;
const spaces = ' '.repeat(indent);
const element = structure.element || 'div';
const attrs = buildAttributes(structure, context, isRoot);
const children = buildChildren(structure, { ...context, indent: indent + 1 });
if (!children) {
return `${spaces}<${element}${attrs} />`;
}
return `${spaces}<${element}${attrs}>\n${children}\n${spaces}</${element}>`;
}
/**
* Build JSX attributes string for a structure node.
*/
function buildAttributes(structure: StructureMetadata, context: GenerationContext, isRoot: boolean): string {
const attrs: string[] = [];
const classNameAttr = buildClassNameAttribute(structure, isRoot);
if (classNameAttr) attrs.push(classNameAttr);
attrs.push(...buildStaticAttributes(structure));
if (isRoot) {
attrs.push('style={style}');
}
attrs.push(...buildBoundAttributes(structure));
return attrs.length > 0 ? ' ' + attrs.join(' ') : '';
}
/**
* Build the className attribute for a node.
*
* - Root: `className={computedClassName}` — driven by `metadata.classNames`.
* - Non-root with conditional rules: inline template literal that mixes the
* node's base classes with prop-driven conditional fragments.
* - Otherwise: a plain static `className="..."`. `attributes.class` may be a
* string or a string[] (joined with spaces).
*/
function buildClassNameAttribute(structure: StructureMetadata, isRoot: boolean): string | null {
if (isRoot) {
if (structure.attributes && (structure.attributes as Record<string, unknown>).class) {
return 'className={computedClassName}';
}
Iif (structure.classNames && hasConditionalRules(structure.classNames)) {
return 'className={computedClassName}';
}
return null;
}
if (structure.classNames && hasConditionalRules(structure.classNames)) {
return `className={${buildInlineClassExpr(structure.classNames)}}`;
}
const cls = (structure.attributes as Record<string, unknown> | undefined)?.class;
if (Array.isArray(cls)) {
return `className="${cls.join(' ')}"`;
}
Eif (typeof cls === 'string' && cls.length > 0) {
return `className="${cls}"`;
}
return null;
}
function hasConditionalRules(rules: ClassNameRule[]): boolean {
return rules.some((r) => r.conditional && r.conditional.length > 0);
}
/**
* Compose an inline JSX expression of the form
* `\`base ${cond ? ' modifier' : ''} ...\``.
*
* The conditions are emitted verbatim because the analyzer already produces
* valid JS expressions over the component's own props (which are destructured
* in scope from `props` at the top of the component body).
*/
function buildInlineClassExpr(rules: ClassNameRule[]): string {
const baseClasses: string[] = [];
const conditionals: string[] = [];
for (const rule of rules) {
baseClasses.push(...rule.base);
for (const c of rule.conditional) {
conditionals.push(`\${${c.condition} ? ' ${c.classes.join(' ')}' : ''}`);
}
}
return `\`${baseClasses.join(' ')}${conditionals.join('')}\``;
}
/**
* Build static attributes (excluding class, which `buildClassNameAttribute`
* owns). Class arrays are joined; other arrays/objects are JSON-stringified.
*/
function buildStaticAttributes(structure: StructureMetadata): string[] {
const attrs: string[] = [];
Iif (!structure.attributes || typeof structure.attributes !== 'object') {
return attrs;
}
const staticAttrs = structure.attributes as Record<string, unknown>;
for (const [key, value] of Object.entries(staticAttrs)) {
if (key === 'class') continue;
const jsxKey = convertToJsxAttribute(key);
const attr = buildStaticAttribute(jsxKey, value);
if (attr) attrs.push(attr);
}
return attrs;
}
function buildStaticAttribute(jsxKey: string, value: unknown): string | null {
if (typeof value === 'boolean') {
return value ? jsxKey : null;
}
Eif (typeof value === 'string') {
return `${jsxKey}="${value}"`;
}
if (Array.isArray(value)) {
return `${jsxKey}="${value.join(' ')}"`;
}
if (value !== undefined && value !== null) {
return `${jsxKey}={${JSON.stringify(value)}}`;
}
return null;
}
function buildBoundAttributes(structure: StructureMetadata): string[] {
return (structure.boundAttributes ?? []).map((b) => `${convertToJsxAttribute(b.attribute)}={${b.prop}}`);
}
/**
* Build the JSX children for a structure node.
*
* Recognises three child shapes:
* - SlotMetadata → `{children}` or `{slotName}`
* - ComposedComponentMetadata → `<ComponentName ...props />` (with auto-import)
* - StructureMetadata → recursive `buildJsx`
*
* Each child may carry a `renderWhen` clause that wraps the emitted JSX in a
* truthy guard. (`'slotFilled'` is intentionally a no-op in React: an empty
* `{slotProp}` already renders nothing.)
*/
function buildChildren(structure: StructureMetadata, context: GenerationContext): string {
if (!structure.children || structure.children.length === 0) return '';
const parts: string[] = [];
for (const child of structure.children) {
if (isSlotMetadata(child)) {
parts.push(buildSlot(child, context));
} else if (isComposedComponent(child)) {
parts.push(
wrapWithRenderWhen(
buildComposed(child, context),
child.renderWhen,
context,
inferPropFilledSource(child),
),
);
} else {
// A common UIF pattern is a structural wrapper whose only child is a
// slot — render the slot directly to keep the tree flat in JSX, which
// avoids generating an unnecessary wrapper element when the parent is
// just a passthrough. The wrapper's `renderWhen` (if any) is preserved.
Iif (child.children?.length === 1 && isSlotMetadata(child.children[0])) {
parts.push(
wrapWithRenderWhen(
buildSlot(child.children[0], context),
child.renderWhen,
context,
inferPropFilledSource(child),
),
);
} else {
parts.push(
wrapWithRenderWhen(
buildJsx(child, context, false),
child.renderWhen,
context,
inferPropFilledSource(child),
),
);
}
}
}
return parts.join('\n');
}
function buildSlot(slot: SlotMetadata, context: GenerationContext): string {
const spaces = ' '.repeat(context.indent);
if (slot.name === 'default') return `${spaces}{children}`;
return `${spaces}{${slot.name}}`;
}
/**
* Build JSX for a composed-component child.
*
* Emits `<ComponentName attr=... />` and registers an import for the
* component. The import path defaults to a sibling-file convention
* (`./ComponentName`); the consumer can adjust the path if needed.
*
* Prop sources:
* - `static` → literal attribute values
* - `bound` → `propName={sourceProp}` from the parent's props
* - `forwarded` → `propName={propName}` (same-name pass-through)
* - `byVariant` → spread of a switch over the active variant
*/
export function buildComposed(composed: ComposedComponentMetadata, context: GenerationContext): string {
const spaces = ' '.repeat(context.indent);
const Tag = composed.component;
context.imports.add(`import { ${Tag} } from './${Tag}';`);
const attrs = buildComposedAttributes(composed);
return attrs.length > 0 ? `${spaces}<${Tag} ${attrs.join(' ')} />` : `${spaces}<${Tag} />`;
}
function buildComposedAttributes(composed: ComposedComponentMetadata): string[] {
const out: string[] = [];
const { static: staticProps, bound, forwarded, byVariant } = composed.props ?? {};
if (staticProps) {
for (const [k, v] of Object.entries(staticProps)) {
const attr = buildStaticAttribute(convertToJsxAttribute(k), v);
Eif (attr) out.push(attr);
}
}
if (bound) {
for (const [propName, source] of Object.entries(bound)) {
const sourceProp = typeof source === 'string' ? source : propName;
out.push(`${convertToJsxAttribute(propName)}={${sourceProp}}`);
}
}
if (forwarded) {
for (const propName of forwarded) {
out.push(`${convertToJsxAttribute(propName)}={${propName}}`);
}
}
if (byVariant) {
for (const [variantProp, options] of Object.entries(byVariant)) {
out.push(buildByVariantSpread(variantProp, options as Record<string, Record<string, unknown>>));
}
}
return out;
}
/**
* Build a JSX spread expression that picks props based on the active
* variant's value:
*
* {...(appearance === 'brand' ? { color: 'brand' }
* : appearance === 'neutral' ? { color: 'neutral' }
* : {})}
*/
function buildByVariantSpread(variantProp: string, options: Record<string, Record<string, unknown>>): string {
const entries = Object.entries(options);
Iif (entries.length === 0) return '';
const cases = entries.map(([value, props]) => `${variantProp} === '${value}' ? ${JSON.stringify(props)}`);
return `{...(${cases.join(' : ')} : {})}`;
}
/**
* Wrap a piece of JSX in a `renderWhen` truthy guard.
*
* - `'propFilled'` → `{driver && (<jsx/>)}`. The driving prop name is
* inferred by `inferPropFilledSource` from the originating node.
* - `{ prop, eq }` → `{prop === 'eq' && (<jsx/>)}`.
* - `'slotFilled'` → no-op (React already renders nothing for an empty
* `{slotProp}`).
*/
export function wrapWithRenderWhen(
jsx: string,
renderWhen: RenderWhen | undefined,
context: GenerationContext,
propFilledDriver?: string,
): string {
if (!renderWhen || renderWhen === 'slotFilled') return jsx;
const spaces = ' '.repeat(context.indent);
if (renderWhen === 'propFilled') {
const driver = propFilledDriver ?? 'true';
return `${spaces}{${driver} && (\n${jsx}\n${spaces})}`;
}
const m = renderWhen as RenderWhenPropMatch;
return `${spaces}{${m.prop} === '${m.eq}' && (\n${jsx}\n${spaces})}`;
}
/**
* Best-effort resolution of the prop driving a `'propFilled'` renderWhen.
*
* Order of preference: first bound attribute (structural node) or first bound
* prop (composed node) → first forwarded prop (composed node) → the node's
* own `name`. This mirrors how generator-lwc resolves the same signal.
*/
function inferPropFilledSource(child: Child): string | undefined {
if (isComposedComponent(child)) {
const bound = child.props?.bound;
if (bound) {
const first = Object.values(bound)[0];
Eif (typeof first === 'string') return first;
}
const forwarded = child.props?.forwarded;
if (forwarded && forwarded.length > 0) return forwarded[0];
return child.name;
}
Eif (!isSlotMetadata(child)) {
if (child.boundAttributes && child.boundAttributes.length > 0) {
return child.boundAttributes[0].prop;
}
return child.name;
}
return undefined;
}
/**
* Convert HTML attribute names to JSX attribute names.
*/
function convertToJsxAttribute(attr: string): string {
const jsxAttributeMap: Record<string, string> = {
class: 'className',
for: 'htmlFor',
tabindex: 'tabIndex',
readonly: 'readOnly',
maxlength: 'maxLength',
minlength: 'minLength',
colspan: 'colSpan',
rowspan: 'rowSpan',
cellpadding: 'cellPadding',
cellspacing: 'cellSpacing',
usemap: 'useMap',
frameborder: 'frameBorder',
contenteditable: 'contentEditable',
crossorigin: 'crossOrigin',
datetime: 'dateTime',
enctype: 'encType',
formaction: 'formAction',
formenctype: 'formEncType',
formmethod: 'formMethod',
formnovalidate: 'formNoValidate',
formtarget: 'formTarget',
hreflang: 'hrefLang',
inputmode: 'inputMode',
srcdoc: 'srcDoc',
srclang: 'srcLang',
srcset: 'srcSet',
accesskey: 'accessKey',
autocomplete: 'autoComplete',
autofocus: 'autoFocus',
autoplay: 'autoPlay',
charset: 'charSet',
novalidate: 'noValidate',
spellcheck: 'spellCheck',
};
if (attr.startsWith('data-') || attr.startsWith('aria-')) return attr;
return jsxAttributeMap[attr.toLowerCase()] || attr;
}
/**
* Build the complete render body. Handles a composed root (when the root
* structure is itself a `ComposedComponentMetadata`).
*/
export function buildRenderBody(
structure: StructureMetadata | ComposedComponentMetadata,
context: GenerationContext,
): string {
const ctx = { ...context, indent: 2 };
if (isComposedComponent(structure)) {
return wrapWithRenderWhen(
buildComposed(structure, ctx),
structure.renderWhen,
ctx,
inferPropFilledSource(structure),
);
}
return wrapWithRenderWhen(
buildJsx(structure, ctx, true),
(structure as StructureMetadata).renderWhen,
ctx,
inferPropFilledSource(structure),
);
}
|