All files / packages/fds-uif/generator-base/src/analyzer structure.ts

97.95% Statements 96/98
93.97% Branches 78/83
100% Functions 13/13
98.92% Lines 92/93

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                                25x                 27x 27x 33x 19x 19x   14x 7x   7x 7x           7x 1x 1x   1x         27x         343x 35x               52x           52x 9x   52x 21x   52x                 19x             19x   19x 19x 1x     18x 19x                     19x 19x 19x 19x 19x 19x                                                             343x 343x 343x 265x 265x 7x 7x 14x 14x 14x 14x   7x   258x 253x   343x                         265x 29x 7x     258x                                           399x 35x     364x       399x 21x     343x                     399x 7x     343x 343x 12x   343x 31x   343x 260x     343x 343x 227x     343x 27x     343x 19x     342x                   272x 272x 14x   272x         42x           42x 7x   42x 42x 30x   42x             42x 32x     10x                
/**
 * Structure Analysis
 *
 * Analyzes UIF structure trees and extracts rendering metadata.
 */
 
import type { ResolvedStructure } from '@fds-uif/schema';
 
import type {
  StructureMetadata,
  SlotMetadata,
  ComposedComponentMetadata,
  CompositionPropsMetadata,
} from '../types/index.js';
import { buildNodeClassNameRules } from './classNames.js';
 
const DEFAULT_ELEMENT = 'div';
 
/**
 * Get nested slot names from structure metadata.
 * Note: Consider moving to @fds-uif/core if needed by other packages.
 */
function structureToSlotNames(
  metadatas: (StructureMetadata | SlotMetadata | ComposedComponentMetadata)[],
): string[] {
  let slotNames: string[] = [];
  metadatas.forEach((metadata) => {
    if ('type' in metadata && (metadata as SlotMetadata).type === 'slot') {
      slotNames.push((metadata as SlotMetadata).name);
      return;
    }
    if ('type' in metadata && (metadata as ComposedComponentMetadata).type === 'component') {
      return;
    }
    const structure = metadata as StructureMetadata;
    slotNames = [...slotNames, ...structureToSlotNames(structure.children)];
    // A nested `slotFilled` child has already been rewritten (see
    // applySlotFilledConditional): its slots were moved out of `children` and
    // into `conditionals[].trueBranch/falseBranch`, and `children` cleared. Walk
    // those branches too so an outer slotFilled node can still discover slots
    // that live behind an inner conditional.
    for (const conditional of structure.conditionals ?? []) {
      Eif (conditional.trueBranch) {
        slotNames = [...slotNames, ...structureToSlotNames(conditional.trueBranch.children)];
      }
      Iif (conditional.falseBranch) {
        slotNames = [...slotNames, ...structureToSlotNames(conditional.falseBranch.children)];
      }
    }
  });
  return slotNames;
}
 
/** Extract bound attributes from a structure node into attribute/prop pairs. */
function buildBoundAttributes(structure: ResolvedStructure): Array<{ attribute: string; prop: string }> {
  if (!structure.attributes?.bound) return [];
  return Object.entries(structure.attributes.bound).map(([attr, config]) => ({
    attribute: attr,
    prop: config.prop,
  }));
}
 
/** Build SlotMetadata from a structure node that declares a slot. */
function buildSlotMetadata(structure: ResolvedStructure): SlotMetadata {
  const slotMeta: SlotMetadata = {
    type: 'slot',
    name: structure.slot!.name,
    required: structure.slot!.required ?? false,
    multiple: false,
  };
  if (structure.slot!.restrict) {
    slotMeta.restrict = structure.slot!.restrict;
  }
  if (structure.description) {
    slotMeta.description = structure.description;
  }
  return slotMeta;
}
 
/**
 * Transform a `renderWhen: "slotFilled"` node into a conditional structure.
 * The original element is moved into the conditional's trueBranch and the
 * metadata becomes a wrapper with empty element/attributes.
 */
function applySlotFilledConditional(metadata: StructureMetadata): void {
  Iif (metadata.children.length === 0) return;
 
  const {
    element: parentElement,
    attributes: parentAttributes,
    boundAttributes: parentBoundAttributes,
    conditionalAttributes: parentConditionalAttributes,
  } = metadata;
 
  const slotNames = structureToSlotNames(metadata.children);
  if (slotNames.length === 0) {
    throw new Error('slotFilled must have atleast one child slot');
  }
 
  const conditionals = metadata.conditionals ?? [];
  conditionals.push({
    condition: slotNames.join(' || '),
    trueBranch: {
      element: parentElement,
      attributes: parentAttributes,
      boundAttributes: parentBoundAttributes,
      children: [...metadata.children],
      conditionalAttributes: parentConditionalAttributes,
    },
  });
 
  metadata.element = undefined;
  metadata.attributes = {};
  metadata.boundAttributes = [];
  metadata.renderWhen = undefined;
  metadata.conditionals = conditionals;
  metadata.children = [];
}
 
type AnalyzedNode = StructureMetadata | SlotMetadata | ComposedComponentMetadata;
 
/**
 * Partition a node's children by their `position` field. Children whose UIF
 * declares `position: "before-slot"` render before the parent's own slot fill;
 * everything else renders after. This lets canonical patterns like
 * `<Badge><Icon/>label text</Badge>` (icon prepends, text from the slot follows)
 * co-exist with `<Badge>label text<em>emphasis</em></Badge>` (text from the slot,
 * then a trailing emphasis child). Default is "after-slot" — slot-first ordering
 * preserves historical behavior; opt-in per child where canonical markup wants
 * pre-slot positioning.
 *
 * Variant-driven position: a child whose variants declare `position` on their options
 * (e.g. `iconPosition: { left: before-slot, right: after-slot }`) is duplicated into
 * BOTH partitions and each copy is tagged with a `variantPositionGate` so the html
 * builder can render only the placement whose variant option is active. Only one
 * variant per child may drive position — the first one that declares any `position`
 * on any option wins. Options without `position` fall back to the child's own
 * declared `position` (or `after-slot` if unset).
 */
type PositionedChild = ResolvedStructure & {
  variantPositionGate?: { variant: string; value: string };
};
 
function partitionChildrenByPosition(children: readonly ResolvedStructure[] | undefined): {
  before: PositionedChild[];
  after: PositionedChild[];
} {
  const before: PositionedChild[] = [];
  const after: PositionedChild[] = [];
  for (const child of children ?? []) {
    const positionalVariant = findPositionalVariant(child);
    if (positionalVariant) {
      const fallback = child.position === 'before-slot' ? 'before-slot' : 'after-slot';
      for (const option of positionalVariant.options) {
        const gate = { variant: positionalVariant.name, value: option.value };
        const copy: PositionedChild = { ...child, variantPositionGate: gate };
        const target = (option.position ?? fallback) === 'before-slot' ? before : after;
        target.push(copy);
      }
      continue;
    }
    if (child.position === 'before-slot') before.push(child);
    else after.push(child);
  }
  return { before, after };
}
 
/**
 * The first variant on this child whose options declare `position`. Returning it
 * (rather than a boolean) so the caller can enumerate the options and their gates.
 * Only the first positional variant is honored — declaring `position` on multiple
 * variants at the same node would create a combinatorial placement matrix, which is
 * not a shape we support today.
 */
function findPositionalVariant(
  child: ResolvedStructure,
): { name: string; options: Array<{ value: string; position?: 'before-slot' | 'after-slot' }> } | undefined {
  for (const variant of child.variants ?? []) {
    if (variant.options?.some((o) => o.position === 'before-slot' || o.position === 'after-slot')) {
      return { name: variant.name, options: variant.options };
    }
  }
  return undefined;
}
 
/**
 * Analyze a resolved structure and extract rendering metadata.
 *
 * Returns one of three shapes:
 *
 *   - `ComposedComponentMetadata` — when the node declares `component` and no
 *     wrapper element (`restrict`). The node IS a composed component.
 *
 *   - `SlotMetadata` — when the node is a pure slot host (declares `slot` but
 *     no element shape of its own). The node collapses to its slot.
 *
 *   - `StructureMetadata` — every other shape: a real element with children,
 *     a wrapper around a composed component, or a node with attributes.
 */
export function analyzeStructure(
  structure: ResolvedStructure,
  defaultElement: string = DEFAULT_ELEMENT,
): AnalyzedNode {
  // Pure composed-component node (component reference with no wrapper element).
  if (structure.component && !structure.restrict?.length) {
    return buildComposedComponentMetadata(structure);
  }
 
  const element = structure.restrict?.[0] ?? (structure.slot ? undefined : defaultElement);
 
  // Pure slot host — collapse to its slot metadata. The cast-free return path; previous
  // code mis-typed this as a StructureMetadata.
  if (structure.slot && !element) {
    return buildSlotMetadata(structure);
  }
 
  const metadata: StructureMetadata = {
    name: structure.name,
    element,
    attributes: structure.attributes?.static ?? {},
    boundAttributes: buildBoundAttributes(structure),
    renderWhen: structure.renderWhen,
    children: [],
  };
 
  // Composed-component children always come first. (Today only one is supported per
  // structure node via `structure.component`.)
  if (structure.component && structure.restrict?.length) {
    metadata.children.push(buildComposedComponentMetadata(structure));
  }
 
  const { before, after } = partitionChildrenByPosition(structure.children);
  for (const child of before) {
    metadata.children.push(analyzeChildWithGate(child, defaultElement));
  }
  if (structure.slot) {
    metadata.children.push(buildSlotMetadata(structure));
  }
  for (const child of after) {
    metadata.children.push(analyzeChildWithGate(child, defaultElement));
  }
 
  const nodeClassNames = buildNodeClassNameRules(structure);
  if (nodeClassNames.length > 0) {
    metadata.classNames = nodeClassNames;
  }
 
  if (structure.variants?.length) {
    metadata.conditionals = [];
  }
 
  if (structure.renderWhen === 'slotFilled') {
    applySlotFilledConditional(metadata);
  }
 
  return metadata;
}
 
/**
 * Analyze a partitioned child and thread its variant-position gate (if any) onto the
 * resulting metadata. The gate is what `partitionChildrenByPosition` stamped on the
 * child copy; the html builder reads it at render time to pick the placement matching
 * the active variant option.
 */
function analyzeChildWithGate(child: PositionedChild, defaultElement: string): AnalyzedNode {
  const analyzed = analyzeStructure(child, defaultElement);
  if (child.variantPositionGate && 'children' in analyzed) {
    (analyzed as StructureMetadata).variantPosition = child.variantPositionGate;
  }
  return analyzed;
}
 
/** Build a ComposedComponentMetadata from a structure node that has `component`. */
function buildComposedComponentMetadata(structure: ResolvedStructure): ComposedComponentMetadata {
  const meta: ComposedComponentMetadata = {
    type: 'component',
    name: structure.name,
    component: structure.component!,
    props: extractComponentPropsMetadata(structure.componentProps),
  };
  if (structure.renderWhen) {
    meta.renderWhen = structure.renderWhen;
  }
  const nodeClassNames = buildNodeClassNameRules(structure);
  if (nodeClassNames.length > 0) {
    meta.classNames = nodeClassNames;
  }
  return meta;
}
 
/** Extract component props configuration from ResolvedComponentProps. */
export function extractComponentPropsMetadata(
  componentProps: ResolvedStructure['componentProps'],
): CompositionPropsMetadata {
  if (!componentProps) {
    return {};
  }
 
  return {
    static: componentProps.static,
    bound: componentProps.bound,
    forwarded: componentProps.forwarded,
    byVariant: componentProps.byVariant,
    restrict: componentProps.restrict,
  };
}