All files / packages/fds-uif/generator-react/src conditional-builder.ts

96.15% Statements 25/26
80% Branches 12/15
100% Functions 3/3
100% Lines 24/24

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                                                                  21x     9x       5x     4x                   21x             4x     4x   8x 8x                         1x       5x     9x 9x 9x 9x                           9x                                 9x                                                                     16x     2x       2x       2x             3x 3x   3x      
/**
 * Conditional Builder
 *
 * Generates conditional rendering logic for UIF variants that alter structure.
 */
 
import type { ComponentMetadata, PropMetadata, StructureMetadata } from '@fds-uif/generator-base/browser';
import type { GenerationContext } from './types.js';
 
/**
 * Analyze variants that affect rendering
 */
export interface VariantRenderInfo {
  /** Variant prop name */
  name: string;
 
  /** Whether variant changes element type */
  changesElement: boolean;
 
  /** Whether variant adds/removes children */
  changesChildren: boolean;
 
  /** Whether variant changes slots */
  changesSlots: boolean;
 
  /** Possible values */
  options: string[];
}
 
/**
 * Analyze which variants affect rendering
 */
export function analyzeRenderingVariants(metadata: ComponentMetadata): VariantRenderInfo[] {
  const renderingVariants: VariantRenderInfo[] = [];
 
  for (const prop of metadata.props) {
    if (prop.source !== 'variant') continue;
 
    // Check if this variant has structural implications
    // For now, we detect variants that might change element types
    const isRenderingVariant = prop.name === 'element' || prop.name === 'as' || prop.name.includes('type');
 
    if (isRenderingVariant) {
      renderingVariants.push({
        name: prop.name,
        changesElement: prop.name === 'element' || prop.name === 'as',
        changesChildren: false,
        changesSlots: false,
        options: extractOptions(prop),
      });
    }
  }
 
  return renderingVariants;
}
 
/**
 * Extract variant options from prop type
 */
function extractOptions(prop: PropMetadata): string[] {
  Iif (!prop.type) return [];
 
  // Parse union type: 'button' | 'link' | 'reset'
  return prop.type
    .split('|')
    .map((s) => s.trim().replace(/^'/, '').replace(/'$/, ''))
    .filter((s) => s && !s.includes(' '));
}
 
/**
 * Build conditional rendering for element variants
 */
export function buildElementConditional(
  variantName: string,
  options: string[],
  structure: StructureMetadata,
  context: GenerationContext,
): string {
  if (options.length === 0) {
    return '';
  }
 
  // Generate a switch-based element selection
  const cases: string[] = [];
 
  for (const option of options) {
    const element = mapOptionToElement(option);
    cases.push(`    case '${option}':`);
    cases.push(`      Element = '${element}';`);
    cases.push('      break;');
  }
 
  return `  // Determine element type based on ${variantName}
  let Element: keyof JSX.IntrinsicElements = '${structure.element || 'div'}';
  switch (${variantName}) {
${cases.join('\n')}
  }`;
}
 
/**
 * Map variant option to HTML element
 */
function mapOptionToElement(option: string): string {
  const elementMap: Record<string, string> = {
    button: 'button',
    link: 'a',
    submit: 'button',
    reset: 'button',
    anchor: 'a',
    span: 'span',
    div: 'div',
    section: 'section',
    article: 'article',
    nav: 'nav',
    header: 'header',
    footer: 'footer',
    main: 'main',
    aside: 'aside',
  };
 
  return elementMap[option.toLowerCase()] || option;
}
 
/**
 * Build conditional children rendering
 */
export function buildChildrenConditional(
  condition: string,
  trueContent: string,
  falseContent?: string,
  context?: GenerationContext,
): string {
  if (falseContent) {
    return `{${condition} ? (
${indent(trueContent, 3)}
    ) : (
${indent(falseContent, 3)}
    )}`;
  }
 
  return `{${condition} && (
${indent(trueContent, 3)}
  )}`;
}
 
/**
 * Build conditional wrapper for variant-based structure changes
 */
export function buildVariantWrapper(
  variants: VariantRenderInfo[],
  structure: StructureMetadata,
  context: GenerationContext,
): string {
  // If no variants affect rendering, return empty
  if (variants.length === 0) {
    return '';
  }
 
  const parts: string[] = [];
 
  for (const variant of variants) {
    if (variant.changesElement) {
      parts.push(buildElementConditional(variant.name, variant.options, structure, context));
    }
  }
 
  return parts.join('\n\n');
}
 
/**
 * Utility: indent multiline string
 */
function indent(str: string, levels: number): string {
  const spaces = '  '.repeat(levels);
  return str
    .split('\n')
    .map((line) => spaces + line)
    .join('\n');
}