All files / packages/core/src/themes/css helpers.ts

90% Statements 63/70
84.12% Branches 53/63
100% Functions 14/14
89.55% Lines 60/67

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                                                      6423x 6423x   6423x 15298x 398x       14900x     6025x                       6024x     6024x     6024x 6024x 5451x       573x 399x 399x 399x       174x               3794x                       2280x 1500x     780x                 379x 379x               152x 148x     4x 4x 2x 2x                 608x 2x     606x   606x 606x                                                   532x 3192x 3192x 146x   3192x               76x 76x   75x 75x                     76x 380x 380x 379x                     76x 76x   76x 2280x     2280x 608x 608x 608x         2280x 76x   2204x     2280x     76x    
// SPDX-License-Identifier: MIT
// Helper functions for CSS generation
 
import { hexToHsl } from '../bulma.js';
import type { ThemeTokens } from '../types.js';
import type {
  CSSVariableMapping,
  HSLVariableMapping,
  HSLColorMapping,
  ComponentTokenMapping,
} from './types.js';
 
/**
 * Unified token path resolver options.
 */
interface ResolveTokenOptions {
  /** Optional path prefix (e.g., 'components' for component tokens) */
  prefix?: string;
  /** Fallback path to try if primary path fails */
  fallbackPath?: string;
}
 
/**
 * Traverses an object using a dot-separated path.
 * Internal helper used by all token resolution functions.
 */
function traversePath(obj: unknown, path: string): unknown {
  const parts = path.split('.');
  let current = obj;
 
  for (const part of parts) {
    if (current === null || current === undefined || typeof current !== 'object') {
      return undefined;
    }
    // Safe: path is from hardcoded TOKEN_MAPPINGS, not user input
    // nosemgrep: prototype-pollution-loop
    current = (current as Record<string, unknown>)[part];
  }
 
  return current;
}
 
/**
 * Unified token path resolver.
 * Gets a value from tokens using a dot-separated path with optional prefix and fallback.
 */
export function resolveTokenPath(
  tokens: ThemeTokens,
  path: string,
  options?: ResolveTokenOptions
): string | undefined {
  const { prefix, fallbackPath } = options ?? {};
 
  // Build full path with optional prefix
  const fullPath = prefix ? `${prefix}.${path}` : path;
 
  // Try primary path
  const value = traversePath(tokens, fullPath);
  if (typeof value === 'string') {
    return value;
  }
 
  // Try fallback path if provided
  if (fallbackPath) {
    const fallbackValue = traversePath(tokens, fallbackPath);
    Eif (typeof fallbackValue === 'string') {
      return fallbackValue;
    }
  }
 
  return undefined;
}
 
/**
 * Gets a nested value from an object using a dot-separated path.
 * Convenience wrapper around resolveTokenPath.
 */
export function getTokenValue(tokens: ThemeTokens, path: string): string | undefined {
  return resolveTokenPath(tokens, path);
}
 
/**
 * Gets a component token value with fallback.
 * Convenience wrapper around resolveTokenPath for component tokens.
 */
export function getComponentTokenValue(
  tokens: ThemeTokens,
  componentPath: string,
  fallbackPath: string
): string {
  if (!tokens.components) {
    return fallbackPath ? (resolveTokenPath(tokens, fallbackPath) ?? '') : '';
  }
 
  return (
    resolveTokenPath(tokens, componentPath, { prefix: 'components', fallbackPath }) ?? ''
  );
}
 
/**
 * Converts a hex color to an HSL string.
 */
export function hexToHslString(hex: string): string {
  const hsl = hexToHsl(hex);
  return `hsl(${hsl.h}, ${hsl.s}%, ${hsl.l}%)`;
}
 
/**
 * Escapes a string for use in CSS selectors.
 * Fallback implements CSS.escape algorithm per CSSOM spec when native is unavailable.
 */
export function escapeCssId(id: string): string {
  if (typeof CSS !== 'undefined' && CSS.escape) {
    return CSS.escape(id);
  }
  // Fallback: escape per CSSOM spec (simplified for valid identifier chars)
  return id.replace(/[\0-\x1f\x7f]|^-?[0-9]|[^a-zA-Z0-9_-]/g, (char) => {
    if (char === '\0') return '\uFFFD';
    const code = char.charCodeAt(0);
    return '\\' + code.toString(16) + ' ';
  });
}
 
/**
 * Validates and sanitizes a CSS color value.
 * Returns the value if valid, or a transparent fallback if invalid.
 */
export function sanitizeCssColor(value: string | undefined): string {
  if (!value || typeof value !== 'string') {
    return 'transparent';
  }
  // Allow hex colors, rgb/rgba/hsl/hsla functions, and named colors
  const trimmed = value.trim();
  // Hex color validation
  Eif (/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/.test(trimmed)) {
    return trimmed;
  }
  // RGB/RGBA/HSL/HSLA function validation
  if (/^(rgb|rgba|hsl|hsla)\([^)]+\)$/i.test(trimmed)) {
    // Additional check: no semicolons or braces in the value
    if (!/[;{}]/.test(trimmed)) {
      return trimmed;
    }
  }
  // Named color validation (common named colors only)
  const namedColors = new Set([
    'transparent', 'inherit', 'currentColor', 'initial', 'unset',
    'black', 'white', 'red', 'green', 'blue', 'yellow', 'orange',
    'purple', 'gray', 'grey', 'pink', 'brown', 'cyan', 'magenta',
  ]);
  if (namedColors.has(trimmed.toLowerCase())) {
    return trimmed;
  }
  // Default fallback for invalid values
  return 'transparent';
}
 
/**
 * Generates CSS variable declarations from a mapping array.
 */
export function generateVariables(tokens: ThemeTokens, mappings: CSSVariableMapping[]): string[] {
  return mappings.map((mapping) => {
    let value = getTokenValue(tokens, mapping.tokenPath);
    if (value === undefined && mapping.fallbackPath) {
      value = getTokenValue(tokens, mapping.fallbackPath);
    }
    return `  ${mapping.cssVar}: ${value ?? ''};`;
  });
}
 
/**
 * Generates HSL component variables (h, s%, l%).
 */
export function generateHSLComponents(tokens: ThemeTokens, mapping: HSLVariableMapping): string[] {
  const hex = getTokenValue(tokens, mapping.tokenPath);
  if (!hex) return [];
 
  const hsl = hexToHsl(hex);
  return [
    `  ${mapping.hVar}: ${hsl.h};`,
    `  ${mapping.sVar}: ${hsl.s}%;`,
    `  ${mapping.lVar}: ${hsl.l}%;`,
  ];
}
 
/**
 * Generates HSL color variables.
 */
export function generateHSLColors(tokens: ThemeTokens, mappings: HSLColorMapping[]): string[] {
  return mappings.map((mapping) => {
    const hex = getTokenValue(tokens, mapping.tokenPath);
    if (!hex) return `  ${mapping.cssVar}: ;`;
    return `  ${mapping.cssVar}: ${hexToHslString(hex)};`;
  });
}
 
/**
 * Generates component token variables with fallbacks.
 */
export function generateComponentVariables(
  tokens: ThemeTokens,
  mappings: ComponentTokenMapping[]
): string[] {
  const lines: string[] = [];
  let currentComponent = '';
 
  for (const mapping of mappings) {
    const component = mapping.componentPath.split('.')[0] ?? '';
 
    // Add comment for new component section
    if (component && component !== currentComponent) {
      const componentName = component.charAt(0).toUpperCase() + component.slice(1);
      lines.push(`  /* ${componentName} component tokens */`);
      currentComponent = component;
    }
 
    // Special case for modal.bg which has a non-token fallback
    let value: string;
    if (mapping.componentPath === 'modal.bg' && !mapping.fallbackPath) {
      value = getComponentTokenValue(tokens, mapping.componentPath, '') || 'rgba(10, 10, 10, 0.86)';
    } else {
      value = getComponentTokenValue(tokens, mapping.componentPath, mapping.fallbackPath);
    }
 
    lines.push(`  ${mapping.cssVar}: ${value};`);
  }
 
  return lines;
}