From f47acc58578ebcdc9bd41b3ee2315bd2567a28f1 Mon Sep 17 00:00:00 2001 From: Brian Nguyen Date: Tue, 28 May 2024 10:45:33 -0700 Subject: [PATCH] refactor: isolated util file --- src/css/brandColors.test.ts | 20 ++------------------ utils/getCssColorVariables.ts | 30 ++++++++++++++++++++++++++++++ utils/index.ts | 1 + 3 files changed, 33 insertions(+), 18 deletions(-) create mode 100644 utils/getCssColorVariables.ts create mode 100644 utils/index.ts diff --git a/src/css/brandColors.test.ts b/src/css/brandColors.test.ts index fbb2ec2..801419d 100644 --- a/src/css/brandColors.test.ts +++ b/src/css/brandColors.test.ts @@ -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)) { diff --git a/utils/getCssColorVariables.ts b/utils/getCssColorVariables.ts new file mode 100644 index 0000000..5213e73 --- /dev/null +++ b/utils/getCssColorVariables.ts @@ -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; +} diff --git a/utils/index.ts b/utils/index.ts new file mode 100644 index 0000000..ea2e610 --- /dev/null +++ b/utils/index.ts @@ -0,0 +1 @@ +export { getCssColorVariables } from './getCssColorVariables';