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

97.72% Statements 43/44
0% Branches 0/2
100% Functions 1/1
97.67% Lines 42/43

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                                              16x     16x     16x                 16x 16x 16x 16x 16x 16x     16x 16x     16x                             16x                                   16x                                         16x     16x 16x   2x   16x 16x 16x 16x       15x         1x         1x     16x     16x 16x     16x 16x 16x     16x       1x 1x     16x 16x 16x 16x       1x   15x     16x                   2x    
/**
 * React Component Generator
 *
 * Main entry point for generating React components from UIF definitions.
 * Orchestrates the JSX, types, className, and conditional builders.
 */
 
import { analyzeUif, formatGeneratedCode, type ResolvedUIF } from '@fds-uif/generator-base/browser';
import type { ReactGeneratorOptions, ReactGeneratedCode, GenerationContext } from './types.js';
import { DEFAULT_OPTIONS } from './types.js';
import { buildRenderBody } from './jsx-builder.js';
import { buildPropsInterface, buildFunctionSignature, buildPropsDestructuring, getTypeImports } from './types-builder.js';
import { buildClassNameLogic } from './classname-builder.js';
import { analyzeRenderingVariants, buildVariantWrapper } from './conditional-builder.js';
 
/**
 * Generate a React component from a resolved UIF
 */
export async function generateReactComponent(
  uif: ResolvedUIF,
  options: ReactGeneratorOptions = {},
): Promise<ReactGeneratedCode> {
  // Merge with defaults
  const opts: ReactGeneratorOptions = { ...DEFAULT_OPTIONS, ...options };
 
  // Analyze UIF to get component metadata
  const metadata = analyzeUif(uif);
 
  // Create generation context
  const context: GenerationContext = {
    metadata,
    options: opts,
    indent: 0,
    imports: new Set(),
    typeImports: new Set(),
  };
 
  // Build component parts
  const propsInterface = buildPropsInterface(metadata, context);
  const functionSignature = buildFunctionSignature(metadata, context, { forwardRef: opts.forwardRef });
  const propsDestructuring = buildPropsDestructuring(metadata, context);
  const classNameLogic = buildClassNameLogic(metadata, context);
  const variantLogic = buildVariantWrapper(analyzeRenderingVariants(metadata), metadata.structure, context);
  const renderBody = buildRenderBody(metadata.structure, context);
 
  // Collect imports
  const typeImports = getTypeImports(context);
  const regularImports = Array.from(context.imports);
 
  // Build final component code
  const componentCode = buildComponentFile({
    name: metadata.name,
    description: metadata.description,
    propsInterface,
    functionSignature,
    propsDestructuring,
    classNameLogic,
    variantLogic,
    renderBody,
    typeImports,
    regularImports,
    options: opts,
  });
 
  // Create generated code structure
  const result: ReactGeneratedCode = {
    files: [
      {
        path: `${metadata.name}${opts.fileExtension}`,
        content: componentCode,
        type: 'typescript',
      },
    ],
    metadata,
    artifacts: {
      component: componentCode,
      propsInterface,
      imports: [...typeImports, ...regularImports],
    },
  };
 
  // Format with Prettier (unless skipped for debugging)
  if (opts.skipFormat) {
    return result;
  }
  return (await formatGeneratedCode(result)) as ReactGeneratedCode;
}
 
/**
 * Build the complete component file
 */
function buildComponentFile(parts: {
  name: string;
  description: string;
  propsInterface: string;
  functionSignature: string;
  propsDestructuring: string;
  classNameLogic: string;
  variantLogic: string;
  renderBody: string;
  typeImports: string[];
  regularImports: string[];
  options: ReactGeneratorOptions;
}): string {
  const lines: string[] = [];
 
  // File header
  lines.push('/**');
  lines.push(` * ${parts.name}`);
  if (parts.description) {
    lines.push(` * ${parts.description}`);
  }
  lines.push(' *');
  lines.push(' * @generated from UIF');
  lines.push(' */');
  lines.push('');
 
  // React import
  if (parts.options.includeReactImport) {
    lines.push("import * as React from 'react';");
  }
 
  // Type imports
  if (parts.typeImports.length > 0) {
    lines.push(...parts.typeImports);
  }
 
  // Regular imports
  if (parts.regularImports.length > 0) {
    lines.push(...parts.regularImports);
  }
 
  lines.push('');
 
  // Props interface
  lines.push(parts.propsInterface);
  lines.push('');
 
  // Component function
  lines.push(`${parts.functionSignature} {`);
  lines.push(`  ${parts.propsDestructuring}`);
  lines.push('');
 
  // ClassName logic
  lines.push(`  ${parts.classNameLogic}`);
 
  // Variant logic (if any)
  if (parts.variantLogic) {
    lines.push('');
    lines.push(parts.variantLogic);
  }
 
  lines.push('');
  lines.push('  return (');
  lines.push(parts.renderBody);
  lines.push('  );');
 
  // Close function
  if (parts.options.forwardRef) {
    lines.push('});');
  } else {
    lines.push('}');
  }
 
  return lines.join('\n');
}
 
/**
 * Generate multiple React components
 */
export async function generateReactComponents(
  uifs: ResolvedUIF[],
  options: ReactGeneratorOptions = {},
): Promise<ReactGeneratedCode[]> {
  return Promise.all(uifs.map((uif) => generateReactComponent(uif, options)));
}