Skip to content

Commit

Permalink
support system color scheme preference
Browse files Browse the repository at this point in the history
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: radix-ui#26
  • Loading branch information
tubbo committed Jan 23, 2023
1 parent 19e08e0 commit 54ba276
Showing 1 changed file with 20 additions and 2 deletions.
22 changes: 20 additions & 2 deletions scripts/build-css-modules.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
);
});

0 comments on commit 54ba276

Please sign in to comment.