Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

2.4 KB
Raw Blame
/** Resolve semantic CSS-variable chains per theme for token tests; keep this helper out of production imports. */

type Block = Record<string, string>;
type Layer = Record<string, Block>;

export interface TokenSystem {
  getTokenCss: () => Record<string, Layer>;
  tokens: { getByName: (name: string) => { extensions: { cssVar: { var: string } } } | undefined };
}

const BASE_SEL = '&:where(html, .chakra-theme)';
const DARK_SEL = '.dark &, .dark .chakra-theme:not(.light) &';
const LIGHT_SEL = ':root &, .light &';
const dataSel = (id: string): string => `&:root[data-theme=${id}]`;

/** Selectors that apply to each theme, HIGHEST CSS priority first. */
export const THEME_SELECTORS: Record<string, string[]> = {
  classic: [DARK_SEL, BASE_SEL], // default theme: no [data-theme=classic] rule
  light: [dataSel('light'), LIGHT_SEL, BASE_SEL],
  ultradark: [dataSel('ultradark'), DARK_SEL, BASE_SEL],
  mono: [dataSel('mono'), DARK_SEL, BASE_SEL],
  osakaJade: [dataSel('osakaJade'), DARK_SEL, BASE_SEL],
  catppuccinMocha: [dataSel('catppuccinMocha'), DARK_SEL, BASE_SEL],
};

export const THEMES = Object.keys(THEME_SELECTORS);

const VAR_REF = /var\((--chakra-colors-[A-Za-z0-9\\.-]+)\)/g;

const layerOf = (sys: TokenSystem): Layer => sys.getTokenCss()['@layer tokens'];

const resolveVar = (layer: Layer, theme: string, varName: string, seen: Set<string>): string | undefined => {
  for (const sel of THEME_SELECTORS[theme]) {
    const block = layer[sel];
    if (block && varName in block) {
      return resolveValue(layer, theme, block[varName], seen);
    }
  }
  return undefined;
};

const resolveValue = (layer: Layer, theme: string, value: string, seen: Set<string>): string =>
  value.replace(VAR_REF, (whole, varName: string) => {
    if (seen.has(varName)) {
      return whole;
    }
    const resolved = resolveVar(layer, theme, varName, new Set(seen).add(varName));
    return resolved ?? whole;
  });

/** Final literal value of `colors.<tokenName>` in `theme`. */
export const resolveToken = (sys: TokenSystem, theme: string, tokenName: string): string => {
  const token = sys.tokens.getByName(`colors.${tokenName}`);
  if (!token) {
    throw new Error(`token not found: colors.${tokenName}`);
  }
  const value = resolveVar(layerOf(sys), theme, token.extensions.cssVar.var, new Set());
  if (value === undefined) {
    throw new Error(`could not resolve colors.${tokenName} for theme ${theme}`);
  }
  return value;
};