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

98% Statements 196/200
92.46% Branches 184/199
100% Functions 30/30
98.21% Lines 165/168

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                                                                                              8275x                             7x 7x   6x 6x 7x 1x 6x 6x 4x 3x 3x       6x                     4x 4x 2x 2x 3x               32904x 16398x     16506x 32904x 32904x 32904x 32904x   32904x 1x     65554x 16505x   32904x 32904x 16439x 16439x   66x 2x   64x                         16506x   16506x 16506x   16506x 16468x 8203x 8203x     16506x 65554x 65548x 65548x     16506x                   8230x 8230x   8230x 8230x 5x 2x   3x 3x     8227x 8230x 7x     8220x   8220x 3x 1x   2x 2x     8218x 8218x                           10x 10x 10x   10x     1x 1x 1x 1x 1x     1x                         18x 8x     10x       18x 18x 18x   7x 7x 18x                                   729180x 65548x 24579x     40969x 65548x 2x     40967x 65548x 40966x   1x             3x 3x 2x 2x 3x               16506x 16506x 8275x 8231x 19x   8212x 8212x 8211x     16506x 3x     16503x               40982x 1x   40981x       40982x 13x   40968x       10x 2x   8x 2x   6x 6x               24624x 24624x 6x       65598x 40980x   24618x 5x   4x 4x   2x           16505x 56x     16449x 16449x   16449x 73821x 8216x 65605x 7x 4x   65598x 24621x       16449x                 16399x 16400x 16400x 16396x 16400x         16398x       16398x   16399x 7x   16392x   16399x                 8220x 3x       8218x 17x 7x               73828x           65611x    
/**
 * 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 Eif (isComponent(child)) {
      if (rootComponentName && child.component === rootComponentName) continue;
      if (isPropForwardingChild(child, context)) continue;
      Eif (!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;
  Iif (!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];
  if (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; filled?: boolean },
  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];
  // `filled: true` form: render when the prop is set to any non-empty value. Used
  // for "conditional sub-tree gated on a parent-supplied prop" cases like Badge's
  // icon-wrapper rendering only when `iconName` is provided.
  if (renderWhen.filled) {
    return propValue === undefined || propValue === '';
  }
  return propValue !== renderWhen.eq;
}
 
function isComponentExcluded(child: ComposedComponentMetadata, context: StaticGenerationContext): boolean {
  if (typeof child.renderWhen === 'object') {
    return isPropMatchExcluded(child.renderWhen, child.name, context);
  }
  if (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]));
}
 
// A child that was duplicated into before/after placements because one of its variants
// declares option-level `position` renders only when the active variant selection
// matches this copy's gate. When no gate is set (any pre-existing UIF), returns false
// so the child renders unconditionally.
function isVariantPositionExcluded(child: StructureMetadata, context: StaticGenerationContext): boolean {
  const gate = child.variantPosition;
  if (!gate) return false;
  return context.state.variants[gate.variant] !== gate.value;
}
 
function isPropFilledExcluded(child: StructureMetadata, context: StaticGenerationContext): boolean {
  if (typeof child.renderWhen === 'object') {
    return isPropMatchExcluded(child.renderWhen, child.name, context);
  }
  if (child.renderWhen !== 'propFilled') return false;
  if (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)) {
      if (!isComponentExcluded(child, context)) {
        parts.push(renderComponentPlaceholder(child, childContext));
      }
    } else if (!isPropFilledExcluded(child, context) && !isVariantPositionExcluded(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';
}