Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ function runTests() {
async function getRuleMatchingClassName(className) {
const selector = `.${CSS.escape(className)}`;

let matchingRule;
for (const stylesheet of document.querySelectorAll("link[rel=stylesheet]")) {
if (stylesheet.sheet == null) {
// Wait for the stylesheet to load completely if it hasn't already
Expand All @@ -64,13 +63,30 @@ async function getRuleMatchingClassName(className) {
});
}

for (const rule of stylesheet.sheet.cssRules) {
if (rule.selectorText === selector) {
matchingRule = rule;
break;
const sheet = stylesheet.sheet;

const res = getRuleMatchingClassNameRec(selector, sheet.cssRules);
if (res != null) {
return res;
}
}

return null;
}

function getRuleMatchingClassNameRec(selector, rules) {
for (const rule of rules) {
if (rule instanceof CSSStyleRule && rule.selectorText === selector) {
return rule;
}

if (rule instanceof CSSLayerBlockRule) {
const res = getRuleMatchingClassNameRec(selector, rule.cssRules);
if (res != null) {
return res;
}
}
}

return matchingRule;
return null;
}
25 changes: 23 additions & 2 deletions crates/turbopack-css/src/chunk/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ pub(crate) mod optimize;
pub mod source_map;
pub(crate) mod writer;

use std::io::Write;

use anyhow::{anyhow, Result};
use indexmap::IndexSet;
use turbo_tasks::{primitives::StringVc, TryJoinIterExt, ValueToString, ValueToStringVc};
Expand All @@ -16,6 +14,7 @@ use turbopack_core::{
optimize::{ChunkOptimizerVc, OptimizableChunk, OptimizableChunkVc},
Chunk, ChunkContentResult, ChunkGroupReferenceVc, ChunkGroupVc, ChunkItem, ChunkItemVc,
ChunkReferenceVc, ChunkVc, ChunkableAssetVc, ChunkingContextVc, FromChunkableAsset,
ModuleId, ModuleIdVc,
},
code_builder::{CodeBuilder, CodeVc},
reference::{AssetReferenceVc, AssetReferencesVc},
Expand Down Expand Up @@ -113,6 +112,8 @@ impl CssChunkContentVc {

#[turbo_tasks::function]
async fn code(self) -> Result<CodeVc> {
use std::io::Write;

let this = self.await?;
let chunk_name = this.chunk_path.to_string();

Expand Down Expand Up @@ -345,6 +346,23 @@ impl CssChunkContextVc {
pub fn of(context: ChunkingContextVc) -> CssChunkContextVc {
CssChunkContext { context }.cell()
}

#[turbo_tasks::function]
pub async fn chunk_item_id(self, chunk_item: CssChunkItemVc) -> Result<ModuleIdVc> {
use std::fmt::Write;

let layer = &*self.await?.context.layer().await?;
let mut s = chunk_item.to_string().await?.clone_value();
if !layer.is_empty() {
if s.ends_with(')') {
s.pop();
write!(s, ", {layer})")?;
} else {
write!(s, " ({layer})")?;
}
}
Ok(ModuleId::String(s).cell())
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This implementation is shared with EcmascriptChunkContextVc.

}
}

#[turbo_tasks::value_trait]
Expand Down Expand Up @@ -373,6 +391,9 @@ pub struct CssChunkItemContent {
pub trait CssChunkItem: ChunkItem + ValueToString {
fn content(&self) -> CssChunkItemContentVc;
fn chunking_context(&self) -> ChunkingContextVc;
fn id(&self) -> ModuleIdVc {
CssChunkContextVc::of(self.chunking_context()).chunk_item_id(*self)
}
}

#[async_trait::async_trait]
Expand Down
80 changes: 77 additions & 3 deletions crates/turbopack-css/src/chunk/writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::{collections::VecDeque, io::Write};

use anyhow::Result;
use turbo_tasks::{primitives::StringVc, ValueToString};
use turbopack_core::code_builder::CodeBuilder;
use turbopack_core::{chunk::ModuleId, code_builder::CodeBuilder};

use super::{CssChunkItemVc, CssImport};

Expand Down Expand Up @@ -39,14 +39,24 @@ pub async fn expand_imports(
external_imports.push(url_vc);
}
None => {
let id = &*chunk_item.to_string().await?;
writeln!(code, "/* {} */", id)?;
let id = module_id_to_css_ident(&*chunk_item.id().await?);

// CSS chunk items can be duplicated across chunks. This can cause precedence
// issues (WEB-456). We use CSS layers to make sure that the first occurrence of
// a CSS chunk item determines its precedence.
// TODO(alexkirsz) This currently breaks users using @layer. We can fix that by
// moving our @layer into the user layer.
writeln!(code, "@layer {id} {{")?;

let content = chunk_item.content().await?;
code.push_source(
&content.inner_code,
content.source_map.map(|sm| sm.as_generate_source_map()),
);

// Closing @layer.
writeln!(code, "\n}}")?;

writeln!(code, "\n{}", close)?;

stack.pop();
Expand All @@ -56,3 +66,67 @@ pub async fn expand_imports(

Ok(external_imports)
}

fn module_id_to_css_ident(id: &ModuleId) -> String {
match id {
ModuleId::Number(n) => format!("n{}", n),
ModuleId::String(s) => format!("s{}", escape_css_ident(s)),
}
}

/// Escapes a string to be a valid CSS identifier, according to the rules
/// defined in https://developer.mozilla.org/en-US/docs/Web/CSS/ident
fn escape_css_ident(s: &str) -> String {
let mut escaped = String::new();

let mut starts_as_a_number = true;
for char in s.chars() {
if starts_as_a_number {
if char.is_ascii_digit() {
escaped.push('_');
starts_as_a_number = false;
} else if char != '-' {
starts_as_a_number = false;
}
}

if char.is_ascii_alphanumeric() || char == '-' || char == '_' {
escaped.push(char);
} else {
escaped.push('\\');
escaped.push(char);
}
}

escaped
}

#[cfg(test)]
mod tests {
//! These cases are taken from https://developer.mozilla.org/en-US/docs/Web/CSS/ident#examples.

use super::*;

#[test]
fn test_escape_css_ident_noop() {
assert_eq!(escape_css_ident("nono79"), "nono79");
assert_eq!(escape_css_ident("ground-level"), "ground-level");
assert_eq!(escape_css_ident("-test"), "-test");
assert_eq!(escape_css_ident("--toto"), "--toto");
assert_eq!(escape_css_ident("_internal"), "_internal");
// TODO(alexkirsz) Support unicode characters?
// assert_eq!(escape_css_ident("\\22 toto"), "\\22 toto");
// TODO(alexkirsz) This CSS identifier is already valid, but we escape
// it anyway.
assert_eq!(escape_css_ident("bili\\.bob"), "bili\\\\\\.bob");
}

#[test]
fn test_escape_css_ident() {
assert_eq!(escape_css_ident("34rem"), "_34rem");
assert_eq!(escape_css_ident("-12rad"), "-_12rad");
assert_eq!(escape_css_ident("bili.bob"), "bili\\.bob");
assert_eq!(escape_css_ident("'bilibob'"), "\\'bilibob\\'");
assert_eq!(escape_css_ident("\"bilibob\""), "\\\"bilibob\\\"");
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.