Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

4.2 KB
Raw Blame
import { existsSync, readFileSync } from 'node:fs';
import path from 'node:path';

import { DENSITY_SCALE, type DensityScale } from '../src/styles/densityScale';

type DensityTokenKey = keyof DensityScale;

const GENERATED_HEADER = `// @generated by scripts/densityTokens.mts from src/styles/densityScale.ts
// Do not edit by hand — run \`pnpm gen:density\` after changing the spec.`;

/**
 * Everything after this marker in density.stylex.ts is hand-written (the semantic
 * `sidebarRow` layer) and is carried over verbatim on regeneration.
 */
const HAND_MAINTAINED_MARKER =
  '// --- hand-maintained below this line (preserved by the generator) ---';

const STYLEX_RELATIVE_PATH = 'src/styles/density.stylex.ts';
const THEME_RELATIVE_PATH = 'src/styles/densityTheme.ts';
const VARS_RELATIVE_PATH = 'src/styles/densityVars.ts';

export const toVarName = (key: string): string =>
  `--lobe-density-${key.replaceAll(/[A-Z]/g, (char) => `-${char.toLowerCase()}`)}`;

const scaleEntryKeys = (): DensityTokenKey[] =>
  (Object.keys(DENSITY_SCALE.loose) as DensityTokenKey[]).sort((a, b) =>
    toVarName(a).localeCompare(toVarName(b)),
  );

/** Every CSS variable owned by the generated token file, in generated order. */
export const DENSITY_VARS: string[] = scaleEntryKeys().map(toVarName);

/**
 * `defineVars` keys are the literal `--lobe-density-*` names (global.css overrides them by
 * name), so the VarGroup exposes those strings as properties. densityVars.ts carries the
 * camelCase handles over the same variables; `stylex-enforce` forbids exporting anything but
 * variables from the defineVars module, hence the separate file.
 */
const renderVarAliases = (): string =>
  Object.keys(DENSITY_SCALE.loose)
    .sort()
    .map((key) => `  ${key}: densityTokens['${toVarName(key)}'],`)
    .join('\n');

const renderVarLines = (density: 'compact' | 'loose'): string =>
  scaleEntryKeys()
    .map((key) => `  '${toVarName(key)}': '${DENSITY_SCALE[density][key]}px',`)
    .join('\n');

const renderStylexDensity = (tail: string): string =>
  `${GENERATED_HEADER}
import * as stylex from '@stylexjs/stylex';

export const densityTokens = stylex.defineVars({
${renderVarLines('loose')}
});

${HAND_MAINTAINED_MARKER}

${tail}
`;

const renderDensityVars = (): string =>
  `${GENERATED_HEADER}
import { densityTokens } from './density.stylex';

/** camelCase handles over the same variables, for stylesheets and inline styles. */
export const densityVars = {
${renderVarAliases()}
};
`;

const renderDensityTheme = (): string =>
  `${GENERATED_HEADER}
import * as stylex from '@stylexjs/stylex';

import { densityTokens } from './density.stylex';

export const compactDensityTheme = stylex.createTheme(densityTokens, {
${renderVarLines('compact')}
});
`;

const readHandMaintainedTail = (root: string): string => {
  const file = path.join(root, STYLEX_RELATIVE_PATH);
  if (!existsSync(file)) {
    throw new Error(
      `${STYLEX_RELATIVE_PATH} is missing. Restore it from git before running the generator — ` +
        `its hand-maintained tail cannot be reconstructed.`,
    );
  }

  const source = readFileSync(file, 'utf8');
  const markerIndex = source.indexOf(HAND_MAINTAINED_MARKER);
  if (markerIndex === -1) {
    throw new Error(
      `${STYLEX_RELATIVE_PATH} is missing "${HAND_MAINTAINED_MARKER}". ` +
        `Add the marker back so the generator can preserve your hand-written tokens.`,
    );
  }

  return source
    .slice(markerIndex + HAND_MAINTAINED_MARKER.length)
    .replace(/^\n+/, '')
    .trimEnd();
};

export interface GeneratedFile {
  content: string;
  /** Absolute path on disk. */
  filePath: string;
  /** Repo-relative path, for reporting. */
  relativePath: string;
}

export const generateDensityTokenFiles = (root: string): GeneratedFile[] => {
  const tail = readHandMaintainedTail(root);

  return [
    {
      content: renderStylexDensity(tail),
      filePath: path.join(root, STYLEX_RELATIVE_PATH),
      relativePath: STYLEX_RELATIVE_PATH,
    },
    {
      content: renderDensityVars(),
      filePath: path.join(root, VARS_RELATIVE_PATH),
      relativePath: VARS_RELATIVE_PATH,
    },
    {
      content: renderDensityTheme(),
      filePath: path.join(root, THEME_RELATIVE_PATH),
      relativePath: THEME_RELATIVE_PATH,
    },
  ];
};