All files / packages/fds-uif/generator-lwc/src generateTemplate.ts

94.49% Statements 103/109
83.82% Branches 57/68
100% Functions 17/17
95.87% Lines 93/97

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                            8x 8x                 16x 16x         16x 16x 16x 16x     176x 8x 338x               174x 5x     169x 169x     157x 143x 143x 142x   47x       160x 160x 147x 23x     23x     160x 160x 160x       160x   126x 12x 12x   12x       14x 14x 14x 1x 1x   1x 1x           14x 2x 2x 2x     14x 2x 2x     14x 14x 14x               174x 174x 21x     21x 21x 21x 21x               14x 14x 14x 14x                 167x 160x 160x       160x 160x 7x 7x 7x   7x   7x     7x 7x 7x 7x                   167x 100x 176x 11x     11x 11x 165x 13x   152x           16x           16x       16x 16x 1x   15x     16x     16x   16x    
import {
  type ComponentMetadata,
  type StructureMetadata,
  type SlotMetadata,
  PropMetadata,
  ComposedComponentMetadata,
} from '@fds-uif/generator-base';
import { serialize, defaultTreeAdapter, html } from 'parse5';
import type { DefaultTreeAdapterMap, Token } from 'parse5';
import { uppercaseFirstChar } from './utils/uppercaseFirstChar.js';
import { kebabCase } from './utils/kebabCase.js';
import { buildClassGetterPlan, type ClassGetterPlan } from './utils/classGetterPlan.js';
import { buildRenderWhenPlan, type RenderWhenPlan } from './utils/renderWhenPlan.js';
 
const NS = html.NS;
const treeAdapter = defaultTreeAdapter;
 
interface TemplateCtx {
  classPlan: ClassGetterPlan;
  rwPlan: RenderWhenPlan;
  props: PropMetadata[];
}
 
function createDocument() {
  const document = treeAdapter.createDocument();
  const templateElement = treeAdapter.createElement(
    'template',
    NS.HTML,
    [],
  ) as DefaultTreeAdapterMap['template'];
  const templateContent = treeAdapter.createDocumentFragment();
  treeAdapter.setTemplateContent(templateElement, templateContent);
  treeAdapter.appendChild(document, templateElement);
  return { document, template: templateContent };
}
 
const isSlotChild = (c: unknown): c is SlotMetadata => !!c && (c as SlotMetadata).type === 'slot';
const isComposedChild = (c: unknown): c is ComposedComponentMetadata =>
  !!c && (c as ComposedComponentMetadata).type === 'component';
 
function classAttrFor(
  node: StructureMetadata | ComposedComponentMetadata,
  ctx: TemplateCtx,
  isRoot: boolean,
): { name: 'class'; value: string } | null {
  // Dynamic root binding wins.
  if (isRoot && ctx.classPlan.rootGetterName) {
    return { name: 'class', value: `{${ctx.classPlan.rootGetterName}}` };
  }
  // Dynamic non-root binding.
  const dynamic = ctx.classPlan.nodes.get(node);
  if (dynamic) return { name: 'class', value: `{${dynamic.name}}` };
 
  // Static class on structure nodes only (composed have their own props.static).
  if (!isComposedChild(node)) {
    const cls = (node as StructureMetadata).attributes?.class;
    if (Array.isArray(cls)) return { name: 'class', value: cls.join(' ') };
    if (typeof cls === 'string' && cls.length > 0) return { name: 'class', value: cls };
  }
  return null;
}
 
function staticAttrsFor(node: StructureMetadata, ctx: TemplateCtx, isRoot: boolean): Token.Attribute[] {
  const out: Token.Attribute[] = [];
  for (const [attribute, value] of Object.entries(node.attributes)) {
    if (attribute === 'class') continue; // class handled separately
    Iif (Array.isArray(value)) {
      out.push({ name: attribute, value: value.join(' ') } as Token.Attribute);
    } else {
      out.push({ name: attribute, value: String(value) } as Token.Attribute);
    }
  }
  const classAttr = classAttrFor(node, ctx, isRoot);
  if (classAttr) out.push(classAttr as Token.Attribute);
  return out;
}
 
function boundAttrsFor(node: StructureMetadata, ctx: TemplateCtx): Token.Attribute[] {
  return (node.boundAttributes ?? [])
    .map((api) => {
      const known = ctx.props.find((p) => p.name === api.prop);
      Iif (!known) return null;
      return { name: api.attribute, value: `{${known.name}}` } as Token.Attribute;
    })
    .filter((x): x is Token.Attribute => x !== null);
}
 
function composedAttrsFor(node: ComposedComponentMetadata, ctx: TemplateCtx): Token.Attribute[] {
  const out: Token.Attribute[] = [];
  const { static: staticProps, bound, forwarded } = node.props ?? {};
  if (staticProps) {
    for (const [k, v] of Object.entries(staticProps)) {
      Iif (Array.isArray(v)) {
        out.push({ name: kebabCase(k), value: v.join(' ') });
      } else if (typeof v === 'boolean') {
        Eif (v) out.push({ name: kebabCase(k), value: '' });
      } else E{
        out.push({ name: kebabCase(k), value: String(v) });
      }
    }
  }
  if (bound) {
    for (const [propName, source] of Object.entries(bound)) {
      const sourceProp = typeof source === 'string' ? source : propName;
      out.push({ name: kebabCase(propName), value: `{${sourceProp}}` });
    }
  }
  if (forwarded) {
    for (const propName of forwarded) {
      out.push({ name: kebabCase(propName), value: `{${propName}}` });
    }
  }
  const classAttr = classAttrFor(node, ctx, false);
  Iif (classAttr) out.push(classAttr as Token.Attribute);
  return out;
}
 
function wrapWithRenderWhen(
  parent: DefaultTreeAdapterMap['parentNode'],
  node: StructureMetadata | ComposedComponentMetadata,
  ctx: TemplateCtx,
): DefaultTreeAdapterMap['parentNode'] {
  const binding = ctx.rwPlan.bindings.get(node);
  if (!binding) return parent;
  const tpl = treeAdapter.createElement('template', NS.HTML, [
    { name: 'lwc:if', value: `{${binding.expression}}` },
  ]) as DefaultTreeAdapterMap['template'];
  const frag = treeAdapter.createDocumentFragment();
  treeAdapter.setTemplateContent(tpl, frag);
  treeAdapter.appendChild(parent, tpl);
  return frag;
}
 
function appendComposed(
  parent: DefaultTreeAdapterMap['parentNode'],
  node: ComposedComponentMetadata,
  ctx: TemplateCtx,
): void {
  const host = wrapWithRenderWhen(parent, node, ctx);
  const tag = `c-${kebabCase(node.component)}`;
  const el = treeAdapter.createElement(tag, NS.HTML, composedAttrsFor(node, ctx));
  treeAdapter.appendChild(host, el);
}
 
function appendStructure(
  parent: DefaultTreeAdapterMap['parentNode'],
  node: StructureMetadata,
  ctx: TemplateCtx,
  isRoot: boolean,
): void {
  if (node.element) {
    const host = wrapWithRenderWhen(parent, node, ctx);
    const newElement = treeAdapter.createElement(node.element, NS.HTML, [
      ...staticAttrsFor(node, ctx, isRoot),
      ...boundAttrsFor(node, ctx),
    ]);
    treeAdapter.appendChild(host, newElement);
    createChildren(newElement, node.children, ctx);
  } else Eif (node.conditionals && node.conditionals.length > 0) {
    node.conditionals.forEach((condition) => {
      const lwcCondition = condition.condition
        .split(' || ')
        .map((x) => uppercaseFirstChar(x))
        .join('Or');
      const tpl = treeAdapter.createElement('template', NS.HTML, [
        { name: 'lwc:if', value: `{hasSlot${lwcCondition}}` },
      ]) as DefaultTreeAdapterMap['template'];
      const frag = treeAdapter.createDocumentFragment();
      treeAdapter.setTemplateContent(tpl, frag);
      treeAdapter.appendChild(parent, tpl);
      createChildren(frag, [condition.trueBranch], ctx);
    });
  }
}
 
function createChildren(
  parent: DefaultTreeAdapterMap['parentNode'],
  children: (SlotMetadata | StructureMetadata | ComposedComponentMetadata)[] | undefined,
  ctx: TemplateCtx,
): void {
  if (!children || children.length === 0) return;
  for (const child of children) {
    if (isSlotChild(child)) {
      Iif (parent.nodeName === 'svg') {
        throw new Error('LWC does not support svg>slot nesting');
      }
      const attrs = child.name === 'default' ? [] : [{ name: 'name', value: child.name }];
      treeAdapter.appendChild(parent, treeAdapter.createElement('slot', NS.HTML, attrs));
    } else if (isComposedChild(child)) {
      appendComposed(parent, child, ctx);
    } else {
      appendStructure(parent, child, ctx, false);
    }
  }
}
 
export function generateTemplate(metadata: ComponentMetadata): string {
  const ctx: TemplateCtx = {
    classPlan: buildClassGetterPlan(metadata),
    rwPlan: buildRenderWhenPlan(metadata),
    props: metadata.props,
  };
 
  const { document, template } = createDocument();
 
  // Emit the root. The root may itself be a composed component (analyzer
  // returns a ComposedComponentMetadata in that case).
  const root = metadata.structure as unknown as StructureMetadata | ComposedComponentMetadata;
  if (isComposedChild(root)) {
    appendComposed(template, root, ctx);
  } else {
    appendStructure(template, root, ctx, true);
  }
 
  let raw = serialize(document);
 
  // Convert ="{ident}" to ={ident} for LWC-style attribute bindings.
  raw = raw.replace(/="(\{[^"}]+\})"/g, '=$1');
 
  return raw;
}