From 54ba27683f1f2d09523b3c2ca8ccc482feaea289 Mon Sep 17 00:00:00 2001 From: Tom Scott Date: Mon, 23 Jan 2023 14:31:21 -0500 Subject: [PATCH] support system color scheme preference Currently, Radix Colors does not easily support the concept of a machine's own preference for dark/light mode. This poses a problem when trying to write CSS for dark mode without copying a whole bunch of variable definitions around. Inspired by the way Pico CSS handles things, and allowing compatibility between the two, this commit changes how dark mode is enabled for the document element by using a `data- theme` attribute rather than a class name. This attribute can be set to either "dark" or "light", and uses some clever CSS trickery (inspired by [@Zwyx's comment about Pico](https://github.com/radix-ui/colors/ issues/26#issuecomment-1375542488)) to achieve automatically setting color variables to the right settings when the system preference for dark or light mode is set. To maintain backwards compatibility, these new variants are built using a different file naming convention. The CSS with `.dark-theme` will still be available in `${scale}.css` files, but the "classless" variants that use data-attributes are now available in `${scale}.classless.css` files. Resolves: #26 --- scripts/build-css-modules.js | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/scripts/build-css-modules.js b/scripts/build-css-modules.js index f3b7031..a11601a 100644 --- a/scripts/build-css-modules.js +++ b/scripts/build-css-modules.js @@ -5,13 +5,31 @@ const allColorScales = require('../index'); const outputDir = require('../tsconfig.json').compilerOptions.outDir; Object.entries(allColorScales).forEach(([colorScaleName, scale]) => { - const selector = /DarkA?$/.test(colorScaleName) ? '.dark-theme' : ':root'; + const isDark = /DarkA?$/.test(colorScaleName); + const selector = isDark + ? '[data-theme="dark"]' + : '[data-theme="light"], :root:not([data-theme="dark"])'; + const classSelector = isDark ? '.dark-theme' : ':root'; const scaleAssCssProperties = Object.entries(scale) .map(([name, value]) => ` --${name}: ${value};`) .join('\n'); - const scaleAsCssFile = `${selector} {\n${scaleAssCssProperties}\n}`; + let scaleAsCssFile = `${selector} {\n${scaleAssCssProperties}\n}`; + const classyScaleAsCssFile = `${classSelector} {\n${scaleAssCssProperties}\n}`; + + if (isDark) { + const indented = scaleAssCssProperties + .split('\n') + .map((prop) => ` ${prop}`) + .join('\n'); + scaleAsCssFile += `\n\n@media only screen and (prefers-color-scheme: dark) {\n :root:not([data-theme="light"]) {\n${indented}\n }\n}`; + } + fs.writeFileSync( path.join(outputDir, colorScaleName + '.css'), + classyScaleAsCssFile + ); + fs.writeFileSync( + path.join(outputDir, colorScaleName + '.classless.css'), scaleAsCssFile ); });