All files / packages/fds-uif/generator-static/src html-builder.ts

81.95% Statements 159/194
74.86% Branches 143/191
86.2% Functions 25/29
82.82% Lines 135/163

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                                                                                              573x                                                                                                         2147x 1040x     1107x 2147x 2147x 2147x 2147x   2147x 1x     3083x 1106x   2147x 2147x 1061x 1061x   45x 2x   43x                         1107x   1107x 1107x   1107x 1073x 519x 519x     1107x 3083x 3080x 3080x     1107x                   544x 544x   544x 544x 5x 2x   3x 3x     541x 544x 4x     537x   537x 5x 2x   3x 3x     534x 534x                           9x 9x 9x   9x     1x 1x 1x 1x 1x     1x                         12x 3x     9x       12x 12x 12x   6x 6x 12x                                   26677x 3080x 1026x     2054x 3080x       2054x 3080x 2053x   1x             3x 3x 2x 2x 3x               1107x 1107x 573x 534x 4x   530x 530x 529x     1107x 1x     1106x                               1x     1x     1x 1x       1567x     1567x 2x   2x 2x   1x           1106x 42x     1064x 1064x   1064x 2099x 531x 1568x 1x 1x   1567x 1566x       1064x                 1041x 1042x 1042x 1038x 1042x         1040x       1040x   1041x 7x   1034x   1041x                 537x 5x       534x 16x 7x               2099x           1568x    
/**
 * HTML Builder
 *
 * HTML-target serialization stage of the static generator. Converts UIF
 * ComponentMetadata into HTML strings:
 *   UIF JSON → analyzer (generator-base) → ComponentMetadata → **html-builder** → HTML string
 *
 * Supports two composition strategies (controlled via the `compose` option):
 *   - `'expand'`     – child components are recursively expanded into full HTML markup
 *                      (Pure Blueprint output).
 *   - `'reference'`  – child components are rendered as `<lightning-*>` custom element
 *                      tags (Pure LBC / LBC Recipe output).
 *
 * Slots are filled with either resolved component HTML/tags (when restrict
 * references exist in the registry) or placeholder text derived from metadata.
 */
 
import type {
  StructureMetadata,
  SlotMetadata,
  ComposedComponentMetadata,
} from '@fds-uif/generator-base/browser';
import type { StaticGenerationContext } from './types.js';
import { resolveClasses } from './class-resolver.js';
import { formatAttribute, formatStateAttribute, VOID_ELEMENTS, indent, humanize } from './attribute-utils.js';
import type { AttributeValue } from './attribute-utils.js';
import { isReferenceMode, renderLbcElement, toLbcTagName } from './lbc-tags.js';
import { resolveComponentHtml } from './component-resolver.js';
 
// Re-export public API from extracted modules for backward compatibility
export {
  formatAttribute,
  formatStateAttribute,
  escapeAttributeValue,
  toLbcTagName,
} from './attribute-utils.js';
export { buildLbcRootElement } from './lbc-tags.js';
 
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
 
/**
 * Build the complete HTML fragment for a component.
 * Entry point that resets indentation to zero.
 */
export function buildHtmlFragment(structure: StructureMetadata, context: StaticGenerationContext): string {
  return buildElement(structure, { ...context, indent: 0 });
}
 
/**
 * Render only slot and composed-component children for an LBC root element.
 *
 * In reference mode the custom element handles its own internal DOM, so
 * structural HTML children (e.g. `<ol>`, `<li>`) are skipped. Only slot
 * children (which accept external component content like
 * `<lightning-breadcrumb>`) and composed component references are rendered.
 *
 * `rootComponentName` filters out the self-referencing composed component
 * the analyzer creates when a structure has both `restrict` and `component`.
 */
export function buildLbcSlotChildren(context: StaticGenerationContext, rootComponentName?: string): string {
  const { children } = context.metadata.structure;
  if (!children || children.length === 0) return '';
 
  const parts: string[] = [];
  for (const child of children) {
    if (isSlot(child)) {
      parts.push(renderSlot(child, context));
    } else if (isComponent(child)) {
      if (rootComponentName && child.component === rootComponentName) continue;
      if (isPropForwardingChild(child, context)) continue;
      if (!isComponentExcluded(child, context)) {
        parts.push(renderComponentPlaceholder(child, context));
      }
    }
  }
  return parts.join('\n');
}
 
/**
 * A composed component child is "prop-forwarding" when all its bound props
 * overlap with the root LBC element's bound props.  These children exist to
 * describe how the prop maps through to a sub-component (e.g. Button.iconLeft
 * forwards iconName to PrimitiveIcon) — the root LBC tag already carries the
 * attribute, so rendering the child as a nested element would duplicate it.
 */
function isPropForwardingChild(child: ComposedComponentMetadata, context: StaticGenerationContext): boolean {
  const rootKeys = context.rootBoundPropKeys;
  if (!rootKeys?.size) return false;
  const childBound = child.props.bound;
  if (!childBound || Object.keys(childBound).length === 0) return false;
  return Object.values(childBound).every((uifRef) => rootKeys.has(uifRef));
}
 
/**
 * Build an HTML element from structure metadata.
 * Handles void elements, children, and conditionals.
 */
export function buildElement(structure: StructureMetadata, context: StaticGenerationContext): string {
  if (structure.conditionals && structure.conditionals.length > 0) {
    return buildConditional(structure, context);
  }
 
  const element = structure.element || 'div';
  const isRoot = context.indent === 0;
  const pad = indent(context.indent);
  const attrs = buildAttributeString(structure, context, isRoot);
  const attrStr = attrs ? ` ${attrs}` : '';
 
  if (VOID_ELEMENTS.has(element)) {
    return `${pad}<${element}${attrStr}>`;
  }
 
  const textBound = structure.boundAttributes.find((b) => b.attribute === 'textContent');
  const textContent = textBound ? resolveTextContent(textBound, context) : undefined;
 
  const children = buildChildren(structure, context);
  if (children) {
    const inner = textContent ? `${indent(context.indent + 1)}${textContent}\n${children}` : children;
    return `${pad}<${element}${attrStr}>\n${inner}\n${pad}</${element}>`;
  }
  if (textContent) {
    return `${pad}<${element}${attrStr}>${textContent}</${element}>`;
  }
  return `${pad}<${element}${attrStr}></${element}>`;
}
 
/**
 * Build the attribute string for an HTML element.
 * Root elements use resolved classes (from the permutation state);
 * child elements use their static class directly.
 */
export function buildAttributeString(
  structure: StructureMetadata,
  context: StaticGenerationContext,
  isRoot: boolean,
): string {
  const attrs: string[] = [];
 
  const classValue = resolveClassAttribute(structure, context, isRoot);
  if (classValue) attrs.push(`class="${classValue}"`);
 
  for (const [key, value] of Object.entries(structure.attributes)) {
    if (key === 'class' || Array.isArray(value)) continue;
    const formatted = formatAttribute(key, value as AttributeValue);
    Eif (formatted) attrs.push(formatted);
  }
 
  for (const bound of structure.boundAttributes) {
    if (bound.attribute === 'class' || bound.attribute === 'textContent') continue;
    const formatted = resolveBoundAttribute(bound, context);
    if (formatted) attrs.push(formatted);
  }
 
  return attrs.join(' ');
}
 
/**
 * Render a slot. When a componentRegistry is available and the slot
 * restricts to a known component, resolves inline content for that component.
 * In reference mode, component slots render as custom element tags.
 * Otherwise falls back to descriptive placeholder text or a comment.
 */
export function renderSlot(slot: SlotMetadata, context: StaticGenerationContext): string {
  const pad = indent(context.indent);
  const label = `${pad}<!-- slot: ${slot.name} -->`;
 
  const componentOverride = context.options.slotComponentOverrides?.[slot.name];
  if (componentOverride) {
    if (isReferenceMode(context)) {
      return `${label}\n${pad}<${toLbcTagName(componentOverride)}></${toLbcTagName(componentOverride)}>`;
    }
    const resolved = resolveComponentHtml(componentOverride, context);
    if (resolved) return `${label}\n${resolved}`;
  }
 
  const contentOverride = context.options.slotOverrides?.[slot.name];
  if (contentOverride !== undefined) {
    return contentOverride ? `${label}\n${pad}${contentOverride}` : label;
  }
 
  const componentRef = findComponentRestriction(slot);
 
  if (componentRef) {
    if (isReferenceMode(context)) {
      return `${label}\n${pad}<${toLbcTagName(componentRef)}></${toLbcTagName(componentRef)}>`;
    }
    const resolved = resolveComponentHtml(componentRef, context);
    if (resolved) return `${label}\n${resolved}`;
  }
 
  const placeholder = deriveSlotPlaceholder(slot, context);
  Eif (placeholder) return `${label}\n${pad}${placeholder}`;
 
  return label;
}
 
/**
 * Merge static props with dynamically bound prop values resolved from
 * slotOverrides. Bound entries map child-prop → parent-UIF-prop; we look
 * up each parent UIF prop in slotOverrides to get the current value.
 */
function resolveCompositionProps(
  component: ComposedComponentMetadata,
  context: StaticGenerationContext,
): Record<string, unknown> | undefined {
  const staticProps = component.props.static;
  const boundMap = component.props.bound;
  const overrides = context.options.slotOverrides;
 
  if (!boundMap || !overrides) return staticProps;
 
  let merged: Record<string, unknown> | undefined;
  for (const [childProp, parentProp] of Object.entries(boundMap)) {
    const val = overrides[parentProp];
    Eif (val !== undefined && val !== '') {
      merged ??= { ...staticProps };
      merged[childProp] = val;
    }
  }
  return merged ?? staticProps;
}
 
/**
 * Render a composed component reference. In reference mode, renders as a
 * `<lightning-*>` custom element tag with componentProps.static as
 * attributes. In expand mode, recursively expands to full inline markup via
 * the registry.
 */
export function renderComponentPlaceholder(
  component: ComposedComponentMetadata,
  context: StaticGenerationContext,
): string {
  if (isReferenceMode(context)) {
    return renderLbcElement(component, context);
  }
 
  const parentClasses = component.classNames
    ? resolveClasses(component.classNames, context.state)
    : undefined;
 
  const effectiveProps = resolveCompositionProps(component, context);
  const resolved = resolveComponentHtml(component.component, context, effectiveProps, parentClasses);
  if (resolved) return resolved;
 
  const pad = indent(context.indent);
  const propsJson = effectiveProps ? ` ${JSON.stringify(effectiveProps)}` : '';
  return `${pad}<!-- component: ${component.component}${propsJson} -->`;
}
 
// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------
 
/**
 * Resolve a single bound attribute to its formatted string, or null if it
 * should be omitted. Priority:
 *   1. State/modifier-driven attributes use the active permutation state.
 *   2. Slot overrides (prop values provided by the consumer/preview UI).
 *   3. The prop's static default from metadata.
 */
function resolveBoundAttribute(
  bound: { attribute: string; prop: string },
  context: StaticGenerationContext,
): string | null {
  const propMeta = context.metadata.props.find((p) => p.name === bound.prop);
  if (propMeta?.source === 'state' || propMeta?.source === 'modifier') {
    return formatStateAttribute(bound.attribute, context.state.modifiers[bound.prop] ?? false);
  }
 
  const override = context.options.slotOverrides?.[bound.prop];
  Iif (override !== undefined && override !== '') {
    return formatAttribute(bound.attribute, override);
  }
 
  const defaultValue = propMeta?.default;
  if (defaultValue === undefined || defaultValue === false || defaultValue === null || defaultValue === '') {
    return null;
  }
  return formatAttribute(bound.attribute, defaultValue as AttributeValue);
}
 
function resolveTextContent(
  bound: { attribute: string; prop: string },
  context: StaticGenerationContext,
): string | undefined {
  const override = context.options.slotOverrides?.[bound.prop];
  if (override) return override;
  const propMeta = context.metadata.props.find((p) => p.name === bound.prop);
  const defaultValue = propMeta?.default;
  return typeof defaultValue === 'string' && defaultValue ? defaultValue : undefined;
}
 
function resolveClassAttribute(
  structure: StructureMetadata,
  context: StaticGenerationContext,
  isRoot: boolean,
): string {
  let resolved = '';
  if (isRoot) {
    resolved = resolveClasses(context.metadata.classNames, context.state);
  } else if (structure.classNames && structure.classNames.length > 0) {
    resolved = resolveClasses(structure.classNames, context.state);
  } else {
    const staticClass = structure.attributes?.class;
    if (Array.isArray(staticClass)) resolved = staticClass.join(' ');
    else if (typeof staticClass === 'string') resolved = staticClass;
  }
 
  if (isRoot && context.extraClasses?.length) {
    return context.extraClasses.join(' ');
  }
 
  return resolved;
}
 
function isPropMatchExcluded(
  renderWhen: { prop: string; eq: string },
  name: string | undefined,
  context: StaticGenerationContext,
): boolean {
  if (name && context.options.componentOverrides?.[name] !== undefined) {
    return !context.options.componentOverrides[name];
  }
  const propValue = context.options.slotOverrides?.[renderWhen.prop];
  return propValue !== renderWhen.eq;
}
 
function isComponentExcluded(child: ComposedComponentMetadata, context: StaticGenerationContext): boolean {
  Iif (typeof child.renderWhen === 'object') {
    return isPropMatchExcluded(child.renderWhen, child.name, context);
  }
  Iif (child.renderWhen === 'propFilled') {
    return !child.name || !context.options.componentOverrides?.[child.name];
  }
  const overrides = context.options.componentOverrides;
  return Boolean(child.name && overrides && !(child.name in overrides && overrides[child.name]));
}
 
function isPropFilledExcluded(child: StructureMetadata, context: StaticGenerationContext): boolean {
  Iif (typeof child.renderWhen === 'object') {
    return isPropMatchExcluded(child.renderWhen, child.name, context);
  }
  if (child.renderWhen !== 'propFilled') return false;
  Iif (child.name && context.options.componentOverrides?.[child.name]) return false;
 
  const overrides = context.options.slotOverrides;
  if (!overrides) return true;
 
  Eif (child.name && overrides[child.name]) return false;
 
  return true;
}
 
function buildChildren(structure: StructureMetadata, context: StaticGenerationContext): string {
  if (!structure.children || structure.children.length === 0) {
    return '';
  }
 
  const childContext: StaticGenerationContext = { ...context, indent: context.indent + 1 };
  const parts: string[] = [];
 
  for (const child of structure.children) {
    if (isSlot(child)) {
      parts.push(renderSlot(child, childContext));
    } else if (isComponent(child)) {
      Eif (!isComponentExcluded(child, context)) {
        parts.push(renderComponentPlaceholder(child, childContext));
      }
    } else if (!isPropFilledExcluded(child, context)) {
      parts.push(buildElement(child, childContext));
    }
  }
 
  return parts.join('\n');
}
 
/**
 * Evaluate a slotFilled condition against the active generation options.
 * A slot is considered filled when the caller has supplied either a
 * component override or a non-empty text override for it.
 */
function isSlotFilled(condition: string, context: StaticGenerationContext): boolean {
  return condition.split('||').some((raw) => {
    const name = raw.trim();
    if (context.options.slotComponentOverrides?.[name]) return true;
    const text = context.options.slotOverrides?.[name];
    return text !== undefined && text !== '';
  });
}
 
function buildConditional(structure: StructureMetadata, context: StaticGenerationContext): string {
  Iif (!structure.conditionals || structure.conditionals.length === 0) {
    return '';
  }
 
  return structure.conditionals
    .map((cond) => {
      if (isSlotFilled(cond.condition, context)) {
        return buildElement(cond.trueBranch, context);
      }
      return cond.falseBranch ? buildElement(cond.falseBranch, context) : '';
    })
    .filter((s) => s !== '')
    .join('\n');
}
 
// ---------------------------------------------------------------------------
// Slot content derivation
// ---------------------------------------------------------------------------
 
function findComponentRestriction(slot: SlotMetadata): string | null {
  if (!slot.restrict) return null;
  return slot.restrict.find((r) => /^[A-Z]/.test(r)) ?? null;
}
 
function deriveSlotPlaceholder(slot: SlotMetadata, context: StaticGenerationContext): string | null {
  if (slot.description) return slot.description;
  if (slot.name === 'default') return `${context.metadata.name} content`;
  return humanize(slot.name);
}
 
// ---------------------------------------------------------------------------
// Type guards
// ---------------------------------------------------------------------------
 
function isSlot(child: StructureMetadata | SlotMetadata | ComposedComponentMetadata): child is SlotMetadata {
  return 'type' in child && child.type === 'slot';
}
 
function isComponent(
  child: StructureMetadata | SlotMetadata | ComposedComponentMetadata,
): child is ComposedComponentMetadata {
  return 'type' in child && child.type === 'component';
}