|
| 1 | +import fs from "fs"; |
| 2 | +import path from "path"; |
| 3 | +import { fileURLToPath } from "url"; |
| 4 | + |
| 5 | +const __filename = fileURLToPath(import.meta.url); |
| 6 | +const __dirname = path.dirname(__filename); |
| 7 | + |
| 8 | +/** |
| 9 | + * Determine the paths based on setup mode (theme vs project) |
| 10 | + * @returns {Object} Configuration object with paths and mode info |
| 11 | + */ |
| 12 | +function determinePaths() { |
| 13 | + const themePath = path.join(__dirname, "../src/config/theme.json"); |
| 14 | + const outputPath = path.join(__dirname, "../src/styles/generated-theme.css"); |
| 15 | + |
| 16 | + if (!fs.existsSync(themePath)) { |
| 17 | + throw new Error(`Could not find theme.json at: ${themePath}`); |
| 18 | + } |
| 19 | + |
| 20 | + return { themePath, outputPath }; |
| 21 | +} |
| 22 | + |
| 23 | +const { themePath, outputPath } = determinePaths(); |
| 24 | + |
| 25 | +// Helper to convert color name from snake_case to kebab-case |
| 26 | +const toKebab = (str) => str.replace(/_/g, "-"); |
| 27 | + |
| 28 | +// Helper to extract a clean font name |
| 29 | +const findFont = (fontStr) => |
| 30 | + fontStr.replace(/\+/g, " ").replace(/:[^:]+/g, ""); |
| 31 | + |
| 32 | +/** |
| 33 | + * Add color entries to CSS array |
| 34 | + * @param {Array} cssLines - Array of CSS lines to append to |
| 35 | + * @param {Object} colors - Color object to process |
| 36 | + * @param {string} prefix - Optional prefix for color variable names |
| 37 | + */ |
| 38 | +function addColorsToCss(cssLines, colors, prefix = "") { |
| 39 | + Object.entries(colors).forEach(([key, value]) => { |
| 40 | + const colorName = prefix |
| 41 | + ? `--color-${prefix}-${toKebab(key)}` |
| 42 | + : `--color-${toKebab(key)}`; |
| 43 | + cssLines.push(` ${colorName}: ${value};`); |
| 44 | + }); |
| 45 | +} |
| 46 | + |
| 47 | +/** |
| 48 | + * Generate theme CSS from theme.json configuration |
| 49 | + * @throws {Error} If theme.json is missing or invalid |
| 50 | + */ |
| 51 | +function generateThemeCSS() { |
| 52 | + // Validate that theme.json exists |
| 53 | + if (!fs.existsSync(themePath)) { |
| 54 | + throw new Error(`Theme configuration not found: ${themePath}`); |
| 55 | + } |
| 56 | + |
| 57 | + try { |
| 58 | + // Read and parse theme configuration |
| 59 | + const themeConfig = JSON.parse(fs.readFileSync(themePath, "utf8")); |
| 60 | + |
| 61 | + // Validate required theme structure |
| 62 | + if (!themeConfig.colors || !themeConfig.fonts) { |
| 63 | + throw new Error( |
| 64 | + "Invalid theme.json: missing 'colors' or 'fonts' section", |
| 65 | + ); |
| 66 | + } |
| 67 | + |
| 68 | + // Build CSS using array for better performance |
| 69 | + const cssLines = [ |
| 70 | + "/**", |
| 71 | + ' * Auto-generated from "src/config/theme.json"', |
| 72 | + " * DO NOT EDIT THIS FILE MANUALLY", |
| 73 | + " * Run: node scripts/themeGenerator.js", |
| 74 | + " */", |
| 75 | + "", |
| 76 | + "@theme {", |
| 77 | + " /* === Colors === */", |
| 78 | + ]; |
| 79 | + |
| 80 | + // Add default theme colors |
| 81 | + if (themeConfig.colors.default?.theme_color) { |
| 82 | + addColorsToCss(cssLines, themeConfig.colors.default.theme_color); |
| 83 | + } |
| 84 | + |
| 85 | + // Add default text colors |
| 86 | + if (themeConfig.colors.default?.text_color) { |
| 87 | + addColorsToCss(cssLines, themeConfig.colors.default.text_color); |
| 88 | + } |
| 89 | + |
| 90 | + // Add darkmode colors (if available) |
| 91 | + if (themeConfig.colors.darkmode) { |
| 92 | + cssLines.push("", " /* === Darkmode Colors === */"); |
| 93 | + |
| 94 | + if (themeConfig.colors.darkmode.theme_color) { |
| 95 | + addColorsToCss( |
| 96 | + cssLines, |
| 97 | + themeConfig.colors.darkmode.theme_color, |
| 98 | + "darkmode", |
| 99 | + ); |
| 100 | + } |
| 101 | + |
| 102 | + if (themeConfig.colors.darkmode.text_color) { |
| 103 | + addColorsToCss( |
| 104 | + cssLines, |
| 105 | + themeConfig.colors.darkmode.text_color, |
| 106 | + "darkmode", |
| 107 | + ); |
| 108 | + } |
| 109 | + } |
| 110 | + |
| 111 | + // Add font families |
| 112 | + cssLines.push("", " /* === Font Families === */"); |
| 113 | + const fontFamily = themeConfig.fonts.font_family || {}; |
| 114 | + Object.entries(fontFamily) |
| 115 | + .filter(([key]) => !key.includes("type")) |
| 116 | + .forEach(([key, font]) => { |
| 117 | + const fontFallback = fontFamily[`${key}_type`] || "sans-serif"; |
| 118 | + const fontValue = `${findFont(font)}, ${fontFallback}`; |
| 119 | + cssLines.push(` --font-${toKebab(key)}: ${fontValue};`); |
| 120 | + }); |
| 121 | + |
| 122 | + // Add font sizes |
| 123 | + cssLines.push("", " /* === Font Sizes === */"); |
| 124 | + const baseSize = Number(themeConfig.fonts.font_size?.base || 16); |
| 125 | + const scale = Number(themeConfig.fonts.font_size?.scale || 1.25); |
| 126 | + |
| 127 | + cssLines.push(` --text-base: ${baseSize}px;`); |
| 128 | + cssLines.push(` --text-base-sm: ${baseSize * 0.8}px;`); |
| 129 | + |
| 130 | + let currentSize = scale; |
| 131 | + for (let i = 6; i >= 1; i--) { |
| 132 | + cssLines.push(` --text-h${i}: ${currentSize}rem;`); |
| 133 | + cssLines.push(` --text-h${i}-sm: ${currentSize * 0.9}rem;`); |
| 134 | + currentSize *= scale; |
| 135 | + } |
| 136 | + |
| 137 | + cssLines.push("}"); |
| 138 | + |
| 139 | + // Ensure output directory exists |
| 140 | + const outputDir = path.dirname(outputPath); |
| 141 | + if (!fs.existsSync(outputDir)) { |
| 142 | + fs.mkdirSync(outputDir, { recursive: true }); |
| 143 | + } |
| 144 | + |
| 145 | + // Write the file |
| 146 | + fs.writeFileSync(outputPath, cssLines.join("\n") + "\n"); |
| 147 | + console.log("✅ Theme CSS generated successfully at:", outputPath); |
| 148 | + } catch (error) { |
| 149 | + throw new Error(`Failed to generate theme CSS: ${error.message}`); |
| 150 | + } |
| 151 | +} |
| 152 | + |
| 153 | +// Generate CSS on startup |
| 154 | +try { |
| 155 | + generateThemeCSS(); |
| 156 | +} catch (error) { |
| 157 | + console.error("❌ Error:", error.message); |
| 158 | + process.exit(1); |
| 159 | +} |
| 160 | + |
| 161 | +// Check for --watch flag |
| 162 | +if (process.argv.includes("--watch")) { |
| 163 | + let debounceTimer; |
| 164 | + |
| 165 | + const watcher = fs.watch(themePath, (eventType) => { |
| 166 | + if (eventType === "change") { |
| 167 | + // Debounce to avoid multiple triggers |
| 168 | + clearTimeout(debounceTimer); |
| 169 | + debounceTimer = setTimeout(() => { |
| 170 | + try { |
| 171 | + generateThemeCSS(); |
| 172 | + } catch (error) { |
| 173 | + console.error("❌ Error regenerating theme CSS:", error.message); |
| 174 | + } |
| 175 | + }, 300); |
| 176 | + } |
| 177 | + }); |
| 178 | + |
| 179 | + // Handle graceful shutdown |
| 180 | + process.on("SIGINT", () => { |
| 181 | + clearTimeout(debounceTimer); |
| 182 | + watcher.close(); |
| 183 | + console.log("\n👋 Watcher stopped"); |
| 184 | + process.exit(0); |
| 185 | + }); |
| 186 | + |
| 187 | + console.log("👁️ Watching for changes to:", themePath); |
| 188 | +} |
0 commit comments