Skip to content

Commit

Permalink
refactor: isolated util file
Browse files Browse the repository at this point in the history
  • Loading branch information
brianacnguyen committed May 28, 2024
1 parent 7d71150 commit f47acc5
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 18 deletions.
20 changes: 2 additions & 18 deletions src/css/brandColors.test.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,13 @@
/* eslint-disable n/no-sync */
/* eslint-disable jsdoc/require-jsdoc */
import fs from 'fs';
import path from 'path';

import { getCssColorVariables } from '../../utils';
import jsonData from '../figma/brandColors.json';

// Function to load the generated CSS file
function loadCssVariables(filePath: string): { [key: string]: string } {
const cssContent = fs.readFileSync(filePath, 'utf8');
const regex = /--brand-colors-([\w-]+):\s*(#\w+);/gu;
const variables: { [key: string]: string } = {};
let match;

while ((match = regex.exec(cssContent)) !== null) {
if (match[1] && match[2]) {
variables[match[1]] = match[2];
}
}

return variables;
}

describe('CSS Variables', () => {
const cssFilePath = path.join(__dirname, 'generated-brand-colors.css');
const cssVariables = loadCssVariables(cssFilePath);
const cssVariables = getCssColorVariables(cssFilePath, 'brand-colors');

it('should match JSON values', () => {
for (const [colorGroup, shades] of Object.entries(jsonData)) {
Expand Down
30 changes: 30 additions & 0 deletions utils/getCssColorVariables.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/* eslint-disable import/no-nodejs-modules */
import fs from 'fs';

type ColorValue = {
[key: string]: string;
};

/**
* Function to load the generated color CSS file.
* @param filePath - The file path to the CSS file.
* @param prefix - The prefix string to parse the colors. Example: brand-colors, color.
* @returns An object with the `${colorGroup}-${shade}` as keys and hex values as values.
*/
export function getCssColorVariables(
filePath: string,
prefix: string,
): ColorValue {
const cssContent = fs.readFileSync(filePath, 'utf8');
const regex = new RegExp(`--${prefix}-([\\w-]+):\\s*(#[\\w]+);`, 'gu');
const variables: { [key: string]: string } = {};
let match: RegExpExecArray | null;

while ((match = regex.exec(cssContent)) !== null) {
if (match[1] && match[2]) {
variables[match[1]] = match[2];
}
}

return variables;
}
1 change: 1 addition & 0 deletions utils/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { getCssColorVariables } from './getCssColorVariables';

0 comments on commit f47acc5

Please sign in to comment.