From ce30d6ece58147bed85b352bdab49b1648779b41 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Prod=27homme?= Date: Tue, 5 Nov 2024 17:38:55 +0100 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Generate=20css=20from=20JS=20variab?= =?UTF-8?q?les?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/cherry-sea/package.json | 1 + packages/cherry-sea/src/generate-css-vars.ts | 35 ++++++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 packages/cherry-sea/src/generate-css-vars.ts diff --git a/packages/cherry-sea/package.json b/packages/cherry-sea/package.json index af8af1d..2fd9f24 100644 --- a/packages/cherry-sea/package.json +++ b/packages/cherry-sea/package.json @@ -22,6 +22,7 @@ ], "scripts": { "build": "npx run-p \"build:*\"", + "build-css-vars": "tsc && node dist/generate-css-vars.js", "build:tsc": "tsc -b tsconfig.build.json", "clean": "npx run-p \"clean:*\"", "clean:tsc": "rm -rf dist", diff --git a/packages/cherry-sea/src/generate-css-vars.ts b/packages/cherry-sea/src/generate-css-vars.ts new file mode 100644 index 0000000..b9e6aab --- /dev/null +++ b/packages/cherry-sea/src/generate-css-vars.ts @@ -0,0 +1,35 @@ +/* eslint-disable no-console */ +import fs from 'node:fs'; +import { colors, fonts, spacing } from './index.js'; + +function toCSSVariables(obj: object, prefix = ''): string { + let cssVars = ''; + + // Utilise Object.entries pour itérer uniquement sur les propriétés propres de l'objet + Object.entries(obj).forEach(([key, value]) => { + if (typeof value === 'object' && !Array.isArray(value)) { + // Appel récursif pour les objets imbriqués + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + cssVars += toCSSVariables(value, `${prefix}-${key}`); + } else { + // Formate le nom de la variable CSS + const cssVarName = `${prefix}-${key}`.replaceAll('_', '-').toLowerCase(); + cssVars += ` --${cssVarName}: ${Array.isArray(value) ? value.join(',') : value};\n`; + } + }); + + return cssVars; +} + +function generateCSSFile(variables: object, dist: string) { + const cssVariables = `:root {\n${toCSSVariables(variables, '')}}\n`; + + fs.writeFile(dist, cssVariables, (err) => { + if (err != null) throw err; + console.log(`Le fichier CSS a été généré avec succès : ${dist}`); + }); +} + +generateCSSFile(colors, 'dist/colors.css'); +generateCSSFile(fonts, 'dist/fonts.css'); +generateCSSFile(spacing, 'dist/spacing.css');