estruyf / vscode-community-ui-toolkit

Visual Studio Code - Community UI Toolkit
MIT License
21 stars 6 forks source link

CSS variable constants #22

Open estruyf opened 3 months ago

estruyf commented 3 months ago

Create a script to generate a list of CSS variables that can be used in the components.

Check if we can retrieve defaults.

estruyf commented 3 months ago

The CSS variable script should better be part of the dev extension #15

const doc = await vscode.workspace.openTextDocument(
  vscode.Uri.parse('vscode://schemas/workbench-colors')
);
const contents = JSON.parse(doc.getText());

const cssVariables: { id: string; value: string }[] = Object.entries<{
  oneOf: { defaultSnippets: { body: string }[] }[];
}>(contents.properties).map(([key, value]) => {
  const cssValue = `--vscode-${key.split('.').join('-')}`;
  const cssVariableName = key
    .split('.')
    .map((part, idx) => {
      if (idx === 0) {
        return part;
      }
      return part.charAt(0).toUpperCase() + part.slice(1);
    })
    .join('');

  const oneOf = value.oneOf;
  if (!oneOf) {
    return {
      id: cssVariableName,
      value: `var(${cssValue})`,
    };
  }

  const snippets = oneOf[0].defaultSnippets;
  if (!snippets) {
    return {
      id: cssVariableName,
      value: `var(${cssValue})`,
    };
  }

  const defaultValue = snippets[0].body;
  const colorValue = defaultValue.replace(/\$\{1:(.*)\}/, '$1');
  return {
    id: cssVariableName,
    value: `var(${cssValue}, ${colorValue})`,
  };
});

// Remove duplicates
const cssVariablesMap = new Map<string, string>();
cssVariables.forEach((variable) => {
  cssVariablesMap.set(variable.id, variable.value);
});

const cssVariablesTxt = Array.from(cssVariablesMap).map(
  ([id, value]) => `export const ${id} = '${value}';`
);

const fsWorkspace = vscode.workspace.workspaceFolders?.[0].uri.fsPath;
const cssVariablesPath = path.join(fsWorkspace || '', 'css-variables.ts');
fs.writeFileSync(cssVariablesPath, cssVariablesTxt.join(`\n`), 'utf8');