Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 2 additions & 35 deletions docs/bundler/css.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ Bun's CSS bundler converts these formats for older browsers:

### light-dark() color function

The `light-dark()` function takes two colors and applies one based on the current color scheme, so styles respect the user's system preference without media queries.
The `light-dark()` function takes two colors and applies one based on the used color scheme of the element. A page opts in to dark mode with the `color-scheme` property or with `<meta name="color-scheme">`, so styles respect the user's system preference without media queries.

```css title="styles.css" icon="file-code"
:root {
Expand All @@ -303,40 +303,7 @@ The `light-dark()` function takes two colors and applies one based on the curren
}
```

For browsers that don't support `light-dark()`, Bun's CSS bundler converts it to CSS variables with fallbacks:

```css title="styles.css" icon="file-code"
:root {
--buncss-light: initial;
--buncss-dark: ;
color-scheme: light dark;
}

@media (prefers-color-scheme: dark) {
:root {
--buncss-light: ;
--buncss-dark: initial;
}
}

.light-theme {
--buncss-light: initial;
--buncss-dark: ;
color-scheme: light;
}

.dark-theme {
--buncss-light: ;
--buncss-dark: initial;
color-scheme: dark;
}

.themed-component {
background-color: var(--buncss-light, #ffffff) var(--buncss-dark, #121212);
color: var(--buncss-light, #333333) var(--buncss-dark, #eeeeee);
border-color: var(--buncss-light, #dddddd) var(--buncss-dark, #555555);
}
```
Under the default browser targets, Bun's CSS bundler keeps `light-dark()` and `color-scheme` as written. All major browsers support `light-dark()` natively since Chrome 123, Firefox 120, and Safari 17.5. The lowering for older browsers rewrites each call into `var(--buncss-light, <light>) var(--buncss-dark, <dark>)` and defines those two variables next to each compiled `color-scheme` declaration that names `light` or `dark`. It only resolves when such a declaration applies to the element or one of its ancestors, and it produces an invalid value when the color scheme comes from `<meta name="color-scheme">`, from a stylesheet Bun did not compile, or from an inline style. For that reason the default targets leave it out.

### Logical properties

Expand Down
11 changes: 10 additions & 1 deletion src/css/build-prefixes.js
Original file line number Diff line number Diff line change
Expand Up @@ -474,11 +474,20 @@ let flags = [
"double_position_gradients",
"vendor_prefixes",
"logical_properties",
"light_dark",
["selectors", ["nesting", "not_selector_list", "dir_selector", "lang_selector_list", "is_selector"]],
["media_queries", ["media_interval_syntax", "media_range_syntax", "custom_media_queries"]],
[
"colors",
["color_function", "oklab_colors", "lab_colors", "p3_colors", "hex_alpha_colors", "space_separated_color_notation"],
[
"color_function",
"oklab_colors",
"lab_colors",
"p3_colors",
"hex_alpha_colors",
"space_separated_color_notation",
"light_dark",
],
],
];

Expand Down
5 changes: 4 additions & 1 deletion src/css/properties/custom.rs
Original file line number Diff line number Diff line change
Expand Up @@ -943,7 +943,10 @@ impl UnresolvedColor {
dest.write_char(b')')
}
UnresolvedColor::LightDark { light, dark } => {
if !dest.targets.is_compatible(css::compat::Feature::LightDark) {
if dest
.targets
.should_compile_same(css::compat::Feature::LightDark)
{
dest.write_str("var(--buncss-light")?;
dest.delim(b',', false)?;
light.to_css(dest, is_custom_property)?;
Expand Down
4 changes: 2 additions & 2 deletions src/css/properties/ui.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,9 +115,9 @@ impl ColorSchemeHandler {
match property {
Property::ColorScheme(color_scheme_) => {
let color_scheme: ColorScheme = *color_scheme_;
if !context
if context
.targets
.is_compatible(css::compat::Feature::LightDark)
.should_compile_same(css::compat::Feature::LightDark)
{
if color_scheme.contains(ColorScheme::LIGHT) {
dest.push(define_var(b"--buncss-light", css::Token::Ident(b"initial")));
Expand Down
7 changes: 6 additions & 1 deletion src/css/targets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ impl Targets {
pub(crate) fn browser_default() -> Targets {
Targets {
browsers: Some(*BROWSER_DEFAULT),
// The light-dark() polyfill depends on a compiled `color-scheme` rule (docs/bundler/css.mdx).
exclude: Features::LIGHT_DARK,
Comment thread
robobun marked this conversation as resolved.
Resolved
..Default::default()
}
}
Expand Down Expand Up @@ -435,6 +437,7 @@ bitflags::bitflags! {
const DOUBLE_POSITION_GRADIENTS = 1 << 17;
const VENDOR_PREFIXES = 1 << 18;
const LOGICAL_PROPERTIES = 1 << 19;
const LIGHT_DARK = 1 << 20;

const SELECTORS = Self::NESTING.bits()
| Self::NOT_SELECTOR_LIST.bits()
Expand All @@ -451,7 +454,8 @@ bitflags::bitflags! {
| Self::LAB_COLORS.bits()
| Self::P3_COLORS.bits()
| Self::HEX_ALPHA_COLORS.bits()
| Self::SPACE_SEPARATED_COLOR_NOTATION.bits();
| Self::SPACE_SEPARATED_COLOR_NOTATION.bits()
| Self::LIGHT_DARK.bits();
}
}

Expand Down Expand Up @@ -488,6 +492,7 @@ impl Features {
Feature::SpaceSeparatedColorNotation => Features::SPACE_SEPARATED_COLOR_NOTATION,
Feature::FontFamilySystemUi => Features::FONT_FAMILY_SYSTEM_UI,
Feature::DoublePositionGradients => Features::DOUBLE_POSITION_GRADIENTS,
Feature::LightDark => Features::LIGHT_DARK,
// A tag with no matching `Features` field is a programmer error,
// guarded by a runtime unreachable.
_ => unreachable!(
Expand Down
2 changes: 1 addition & 1 deletion src/css/values/color.rs
Original file line number Diff line number Diff line change
Expand Up @@ -508,7 +508,7 @@ impl CssColor {
// `as_css_color` drops here.
}
CssColor::LightDark { light, dark } => {
if !dest.targets.is_compatible(Feature::LightDark) {
if dest.targets.should_compile_same(Feature::LightDark) {
dest.write_str("var(--buncss-light")?;
dest.delim(b',', false)?;
light.to_css(dest)?;
Expand Down
61 changes: 60 additions & 1 deletion test/js/bun/css/css.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */

import { describe, expect, test } from "bun:test";
import { bunEnv, bunExe } from "harness";
import { bunEnv, bunExe, tempDir } from "harness";
import { join } from "path";
import {
cssTest,
Expand Down Expand Up @@ -7635,6 +7635,65 @@ describe("css tests", () => {
`,
{ chrome: Some(90 << 16) },
);

// The bundler's built-in browser targets are below light-dark() support, but they leave this
// lowering out: the variables only resolve under a `color-scheme` rule compiled in the same CSS.
describe("bundler default targets", () => {
async function bundle(css: string, minify = false) {
using dir = tempDir("css-light-dark-default-targets", { "index.css": css });
const result = await Bun.build({ entrypoints: [join(String(dir), "index.css")], minify });
const output = await result.outputs[0].text();
// The leading `/* path */` banner holds the temporary directory.
return output.replace(/^\/\*.*\*\/\n/, "").trim();
}

test("light-dark() is kept as written", async () => {
const output = await bundle(`
.b { color: light-dark(#102030, #d0e0f0); background-color: light-dark(white, black) }
.c { accent-color: light-dark(red, blue); --c: light-dark(red, blue) }
`);
expect(output).toBe(indoc`
.b {
color: light-dark(#102030, #d0e0f0);
background-color: light-dark(#fff, #000);
}

.c {
accent-color: light-dark(red, #00f);
--c: light-dark(red, #00f);
}
`);
});

test("light-dark() is kept as written when minified", async () => {
const output = await bundle(
".b { color: light-dark(#102030, #d0e0f0) } .c { --c: light-dark(red, blue) }",
true,
);
expect(output).toBe(".b{color:light-dark(#102030,#d0e0f0)}.c{--c:light-dark(red,#00f)}");
});

test("color-scheme does not define the fallback variables", async () => {
const output = await bundle(`
:root { color-scheme: light dark }
.dark { color-scheme: dark }
.b { color: light-dark(red, blue) }
`);
expect(output).toBe(indoc`
:root {
color-scheme: light dark;
}

.dark {
color-scheme: dark;
}

.b {
color: light-dark(red, #00f);
}
`);
});
});
});

describe("page", () => {
Expand Down
Loading