All files / packages/fds-uif/generator-static/src class-resolver.ts

100% Statements 13/13
100% Branches 8/8
100% Functions 2/2
100% Lines 13/13

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                                    586x 27x     559x 559x   559x 6690x 1994x       559x                     6695x 6695x 3601x 3601x     3094x    
/**
 * Class Resolver
 *
 * Resolves CSS class names for a specific permutation state.
 * Unlike framework generators that emit runtime conditionals,
 * the static generator evaluates conditions at generation time
 * to produce the final class string.
 */
 
import type { ClassNameRule } from '@fds-uif/generator-base/browser';
import type { PermutationState } from './types.js';
 
/**
 * Resolve the final CSS class string for a given permutation state.
 * Starts with base classes and appends each conditional class
 * whose condition evaluates to true against the state.
 */
export function resolveClasses(classNames: ClassNameRule[], state: PermutationState): string {
  if (!classNames || classNames.length === 0) {
    return '';
  }
 
  const rule = classNames[0];
  const resolved = [...rule.base];
 
  for (const cond of rule.conditional) {
    if (evaluateCondition(cond.condition, state)) {
      resolved.push(...cond.classes);
    }
  }
 
  return resolved.join(' ');
}
 
/**
 * Evaluate a condition string against the current permutation state.
 *
 * Supports two forms:
 *   - Boolean modifier:  "inverse"               → state.modifiers.inverse
 *   - Variant equality:  "variant === 'success'"  → state.variants.variant === 'success'
 */
export function evaluateCondition(condition: string, state: PermutationState): boolean {
  const equalityMatch = condition.match(/^(\w+)\s*===\s*'([^']+)'$/);
  if (equalityMatch) {
    const [, prop, value] = equalityMatch;
    return state.variants[prop] === value;
  }
 
  return state.modifiers[condition] === true;
}