Unverified Commit 7c9be45a authored by Robert Webb's avatar Robert Webb Committed by GitHub

[Turbopack] Include CSS URL attributes, including Layer, Media and Supports (#89300)

Note that this is my first contribution in Rust, so let me know if I
missed anything idiomatic or if there is a particularly better way to do
something.

Also, I did not use AI to create this at all, although I did chat a bit
to try to wrap my head around types.


- Related issues linked using Fixes
https://github.com/vercel/next.js/issues/88533
- Tests added. 
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md


Summary of changes: Adds support for all of the attributes of `@import`
for Turbopack, by modifying the turbopack-css package, including Layer,
Media and Supports. [W3
Reference](https://www.w3.org/TR/css-cascade-5/#at-import)

---------
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent 9ce72507
@import url('https://cdn.jsdelivr.net/npm/modern-css-reset/dist/reset.min.css')
layer(default);
/* Any external stylesheet should work. Using this css-reset because it is very small and backed by CDN */
@layer default, new;
@layer new {
h1 {
margin: 5px;
}
}
import './external-layer.css'
export default function Home() {
return <h1>Hello</h1>
}
import './relative-layer.css'
export default function Home() {
return <h2>Hello</h2>
}
@import './import.css' layer(new);
@layer default, new;
@layer default {
h2 {
color: rgb(255, 0, 0);
}
}
body {
background: black;
}
h1 {
color: rgb(255, 255, 255);
}
body {
background: white;
}
h1 {
color: rgb(0, 0, 0);
}
import './url-media.css'
export default function Home() {
return <h1>Hello</h1>
}
@import url('./mobile-only.css') screen and (max-width: 400px);
@import url('./desktop-only.css') screen and (min-width: 401px);
h1 {
color: rgb(0, 100, 0) !important;
}
import './url-supports.css'
export default function Home() {
return <h1>Hello</h1>
}
h1 {
color: rgb(255, 0, 0) !important;
}
@import url('./not-loaded.css') supports(display: not-real-value);
@import url('./should-load.css') supports(display: flex);
h1 {
/* this should be overwritten by the should-load css */
color: rgb(0, 0, 255);
}
...@@ -327,6 +327,54 @@ describe('app dir - css', () => { ...@@ -327,6 +327,54 @@ describe('app dir - css', () => {
}) })
}) })
describe('css import URLs', () => {
it('should not mangle external layers', async () => {
const browser = await next.browser('/externalLayer')
expect(
await browser.eval(
`window.getComputedStyle(document.querySelector('h1')).margin`
)
).toBe('5px')
})
it('should not mangle relative layers', async () => {
const browser = await next.browser('/relativeLayer')
expect(
await browser.eval(
`window.getComputedStyle(document.querySelector('h2')).color`
)
).toBe('rgb(255, 0, 0)')
})
// Broken in webpack, see https://github.com/vercel/next.js/issues/89602
if (process.env.IS_TURBOPACK_TEST) {
it('should allow the supports attribute', async () => {
const browser = await next.browser('/urlSupports')
expect(
await browser.eval(
`window.getComputedStyle(document.querySelector('h1')).color`
)
).toBe('rgb(255, 0, 0)')
})
}
it('should work with the media attribute', async () => {
const browser = await next.browser('/urlMedia')
await browser.setDimensions({ width: 1000, height: 1000 })
expect(
await browser.eval(
`window.getComputedStyle(document.querySelector('h1')).color`
)
).toBe('rgb(255, 255, 255)')
await browser.setDimensions({ width: 300, height: 300 })
expect(
await browser.eval(
`window.getComputedStyle(document.querySelector('h1')).color`
)
).toBe('rgb(0, 0, 0)')
})
})
if (isNextDev) { if (isNextDev) {
it('should not affect css orders during HMR', async () => { it('should not affect css orders during HMR', async () => {
const filePath = 'app/ordering/page.js' const filePath = 'app/ordering/page.js'
......
...@@ -36,7 +36,7 @@ use turbopack_core::{ ...@@ -36,7 +36,7 @@ use turbopack_core::{
}; };
use self::{single_item_chunk::chunk::SingleItemCssChunk, source_map::CssChunkSourceMapAsset}; use self::{single_item_chunk::chunk::SingleItemCssChunk, source_map::CssChunkSourceMapAsset};
use crate::{ImportAssetReference, util::stringify_js}; use crate::ImportAssetReference;
#[turbo_tasks::value] #[turbo_tasks::value]
pub struct CssChunk { pub struct CssChunk {
...@@ -130,7 +130,7 @@ impl CssChunk { ...@@ -130,7 +130,7 @@ impl CssChunk {
} }
for external_import in external_imports { for external_import in external_imports {
writeln!(code, "@import {};", stringify_js(&external_import))?; writeln!(code, "{}", &external_import)?;
} }
let built = &body.build(); let built = &body.build();
......
...@@ -13,7 +13,6 @@ mod lifetime_util; ...@@ -13,7 +13,6 @@ mod lifetime_util;
mod module_asset; mod module_asset;
pub(crate) mod process; pub(crate) mod process;
pub(crate) mod references; pub(crate) mod references;
pub(crate) mod util;
use bincode::{Decode, Encode}; use bincode::{Decode, Encode};
use turbo_tasks::{NonLocalValue, TaskInput, trace::TraceRawVcs}; use turbo_tasks::{NonLocalValue, TaskInput, trace::TraceRawVcs};
......
use anyhow::Result; use anyhow::Result;
use lightningcss::{ use lightningcss::{
media_query::MediaList, media_query::MediaList,
rules::{import::ImportRule, layer::LayerName, supports::SupportsCondition}, printer::PrinterOptions,
rules::{Location, import::ImportRule, layer::LayerName, supports::SupportsCondition},
traits::ToCss, traits::ToCss,
values::string::CowArcStr,
}; };
use turbo_rcstr::RcStr; use turbo_rcstr::RcStr;
use turbo_tasks::{ResolvedVc, ValueToString, Vc}; use turbo_tasks::{ResolvedVc, ValueToString, Vc};
...@@ -159,15 +161,45 @@ impl CodeGenerateable for ImportAssetReference { ...@@ -159,15 +161,45 @@ impl CodeGenerateable for ImportAssetReference {
_context: Vc<Box<dyn ChunkingContext>>, _context: Vc<Box<dyn ChunkingContext>>,
) -> Result<Vc<CodeGeneration>> { ) -> Result<Vc<CodeGeneration>> {
let mut imports = vec![]; let mut imports = vec![];
if let Request::Uri { if let Request::Uri {
protocol, protocol,
remainder, remainder,
.. ..
} = &*self.request.await? } = &*self.request.await?
{ {
imports.push(CssImport::External(ResolvedVc::cell( match &*self.attributes.await? {
format!("{protocol}{remainder}").into(), ImportAttributes::LightningCss {
))) layer_name,
supports,
media,
} => {
let layer = if layer_name.is_none() {
None
} else {
Some(layer_name.clone())
};
let css_rule = ImportRule {
url: CowArcStr::from(format!("{protocol}{remainder}")),
layer,
supports: supports.clone(),
media: media.clone(),
loc: Location {
source_index: 0,
line: 0,
column: 0,
},
};
let css = css_rule
.to_css_string(PrinterOptions {
minify: true,
..PrinterOptions::default()
})
.unwrap();
imports.push(CssImport::External(ResolvedVc::cell(css.into())));
}
}
} }
Ok(CodeGeneration { imports }.cell()) Ok(CodeGeneration { imports }.cell())
......
pub fn stringify_js(str: &str) -> String {
let mut escaped = String::with_capacity(str.len());
for char in str.chars() {
match char {
// Escape the following characters required for strings by the CSS scanner:
// https://www.w3.org/TR/CSS21/grammar.html#scanner
// https://github.com/vercel/turbo/pull/2598#discussion_r1022625909
//
// Note that the form feed character is not representable as \f in Rust strings, so
// the unicode representation \u{0c} is used.
'\\' => escaped.push_str(r"\\"),
'\n' => escaped.push_str(r"\n"),
'\r' => escaped.push_str(r"\r"),
'"' => escaped.push_str(r#"\""#),
'\u{0c}' => escaped.push_str(r"\f"),
_ => escaped.push(char),
}
}
format!("\"{escaped}\"")
}
#[cfg(test)]
mod tests {
use crate::util::stringify_js;
#[test]
fn surrounds_with_double_quotes() {
assert_eq!(stringify_js("foo"), r#""foo""#);
}
#[test]
fn escapes_double_quotes() {
assert_eq!(stringify_js(r#""""#), r#""\"\"""#);
}
#[test]
fn escapes_backslash() {
assert_eq!(stringify_js(r"\"), r#""\\""#);
assert_eq!(stringify_js(r"\\"), r#""\\\\""#);
assert_eq!(stringify_js(r"\n"), r#""\\n""#);
}
#[test]
fn escapes_newlines() {
assert_eq!(stringify_js("\n"), r#""\n""#);
}
#[test]
fn escapes_mixed() {
assert_eq!(stringify_js("\n\r\u{0c}"), r#""\n\r\f""#);
}
}
@import './import.css' layer(new);
@layer default, new;
@layer default {
h2 {
color: rgb(255, 0, 0);
}
}
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/aaf3a_crates_turbopack-tests_tests_snapshot_css_import-url_input_index_37fc1f24.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/css/import-url/input/index.js [test] (ecmascript)", ((__turbopack_context__) => {
"use strict";
__turbopack_context__.s([]);
;
}),
]);
//# sourceMappingURL=aaf3a_crates_turbopack-tests_tests_snapshot_css_import-url_input_index_37fc1f24.js.map
{
"version": 3,
"sources": [],
"sections": [
{"offset": {"line": 4, "column": 0}, "map": {"version":3,"sources":[],"names":[],"mappings":""}}]
}
\ No newline at end of file
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([
"output/ba425_crates_turbopack-tests_tests_snapshot_css_import-url_input_index_11ff7a96.js",
{"otherChunks":["output/turbopack_crates_turbopack-tests_tests_snapshot_css_import-url_input_fccef668._.css","output/aaf3a_crates_turbopack-tests_tests_snapshot_css_import-url_input_index_37fc1f24.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/css/import-url/input/index.js [test] (ecmascript)"]}
]);
// Dummy runtime
/* [project]/turbopack/crates/turbopack-tests/tests/snapshot/css/import-url/input/import.css [test] (css, layer(new)) */
@layer new {
h2 {
color: #00f;
}
}
/* [project]/turbopack/crates/turbopack-tests/tests/snapshot/css/import-url/input/index.css [test] (css) */
@layer default {
h2 {
color: red;
}
}
/*# sourceMappingURL=turbopack_crates_turbopack-tests_tests_snapshot_css_import-url_input_fccef668._.css.map*/
\ No newline at end of file
{
"version": 3,
"sources": [],
"sections": [
{"offset": {"line": 2, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/css/import-url/input/import.css"],"sourcesContent":["h2 {\n color: rgb(0, 0, 255);\n}\n"],"names":[],"mappings":"AAAA"}},
{"offset": {"line": 9, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/css/import-url/input/index.css"],"sourcesContent":["@import './import.css' layer(new);\n\n@layer default, new;\n\n@layer default {\n h2 {\n color: rgb(255, 0, 0);\n }\n}\n"],"names":[],"mappings":"AAEA;EAGE"}}]
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment