All files / packages/sds-styling-hooks/src/formats zeroheight.js

100% Statements 27/27
100% Branches 14/14
100% Functions 4/4
100% Lines 25/25

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                  6x 1x     5x 5x 2x           3x       6x     2x 1x 1x   1x 3x 3x 3x 3x 3x   3x 3x 3x     3x     3x     3x   3x               1x       2x  
/**
 * @file zeroheight.js
 * @description A formatter for Theo that converts Theo props to a JSON object.
 * The JSON object is used to import the tokens into Zeroheight.
 */
 
import theo from 'theo';
 
export function getLightDarkColors(value) {
  if (!value || typeof value !== 'string') {
    return { light: value, dark: value };
  }
 
  const match = value.match(/light-dark\(([^,]+),\s*([^)]+)\)/);
  if (match) {
    return {
      light: match[1].trim(),
      dark: match[2].trim(),
    };
  }
 
  return { light: value, dark: value };
}
 
export function getTokenValue(ns, prefix, name) {
  return `--${ns}-${prefix}${name}`;
}
 
export const zhLightFormatter = (result) => {
  const props = result.get('props');
  const json = {};
 
  props.forEach((prop) => {
    const name = prop.get('name');
    const scope = prop.get('scope');
    const ns = prop.get('namespace');
    const category = prop.get('category');
    const inherits = prop.get('inherits');
 
    let prefix = '';
    if (scope === 'global') prefix = 'g-';
    if (scope === 'shared') prefix = 's-';
 
    // Extract the light and dark values from the prop.
    const { light } = getLightDarkColors(prop.get('value'));
 
    // Get the token key.
    const key = getTokenValue(ns, prefix, name);
 
    // If the prop inherits from another prop, use the value of the inherited prop.
    const value = typeof inherits === 'string' ? `{${getTokenValue(ns, prefix, inherits)}}` : `${light}`;
 
    json[key] = {
      $value: value,
 
      // Rename 'boxShadow' to avoid a Zeroheight 'shadow' validation error.
      $type: category === 'shadow' ? 'boxShadow' : category,
    };
  });
 
  return JSON.stringify(json, null, 2);
};
 
// Export the formatter so it can be used in unit tests.
theo.registerFormat('zh-light.json', zhLightFormatter);