diff --git a/.changepacks/changepack_log_vanilla_extract_css_utils.json b/.changepacks/changepack_log_vanilla_extract_css_utils.json new file mode 100644 index 000000000..583aaa154 --- /dev/null +++ b/.changepacks/changepack_log_vanilla_extract_css_utils.json @@ -0,0 +1,11 @@ +{ + "changes": { + "bindings/devup-ui-wasm/package.json": "Patch", + "bindings/devup-ui-binding/package.json": "Patch", + "packages/plugin-utils/package.json": "Patch", + "packages/eslint-plugin/package.json": "Patch", + "packages/react/package.json": "Patch" + }, + "note": "`@vanilla-extract/css-utils` is aliased by default and its `calc` compiles to the strings the package builds (`calc.add/subtract/multiply/divide/negate`, chained `calc(x)` with `.toString()` or template interpolation, nested operations only parenthesized). A `.css.ts` stylesheet evaluates it without a module resolver, so its operands may be anything the stylesheet computes; elsewhere each call is written as its string and its operands must be literals, module-level `const`s holding a literal or other `calc` results. `@devup-ui/react/compat/vanilla-extract-css-utils` types it, and css-utils-literal-only reads its calls as the build does. New build errors: a `calc` operand outside a stylesheet the build cannot read, a `calc` read without being called, a `calc(x)` used as a value without `.toString()` (also in a stylesheet), an export other than `calc`, and a namespace import, `require()` or re-export of the package outside a stylesheet. Set `importAliases: { '@vanilla-extract/css-utils': false }` to keep the package", + "date": "2026-11-15T00:00:00.000Z" +} diff --git a/apps/landing/src/app/(detail)/docs/migration/vanilla-extract/page.mdx b/apps/landing/src/app/(detail)/docs/migration/vanilla-extract/page.mdx index 4f6d04fcb..4ac93d23c 100644 --- a/apps/landing/src/app/(detail)/docs/migration/vanilla-extract/page.mdx +++ b/apps/landing/src/app/(detail)/docs/migration/vanilla-extract/page.mdx @@ -171,6 +171,21 @@ They are not evaluated by the ordinary-module extraction path. Moving those calls into a `.css.ts` file — where vanilla-extract wants them anyway — removes the dependency. +## `@vanilla-extract/css-utils` + +`calc` builds the same strings `@vanilla-extract/css-utils` does, so the package need not be installed. `calc.add`, `calc.subtract`, `calc.multiply`, `calc.divide` and `calc.negate` give a string; `calc(x)` gives an expression whose `add`, `subtract`, `multiply`, `divide` and `negate` chain, and which is a CSS value once `.toString()` is called or it is interpolated in a template. As in the package, an operand that is itself a `calc` is only parenthesized: + +```ts +import { calc } from '@vanilla-extract/css-utils' + +calc.add('100%', '-4px') // 'calc(100% + -4px)' +calc.negate('4px') // 'calc(4px * -1)' +calc('10px').add('5px').multiply(2).toString() // 'calc((10px + 5px) * 2)' +calc.add(calc.multiply('2px', 3), '1px') // 'calc((2px * 3) + 1px)' +``` + +A `.css.ts` stylesheet evaluates `calc`, so its operands can be anything the stylesheet computes, such as `vars.space.md` or a `createVar()`. Any other module is not evaluated: each `calc` there is written as the string it gives, so its operands must be literals, module-level `const`s holding a literal, or other `calc` results. Anything else is a build error at the operand, as is a `calc` read without being called, a `calc(x)` used as a value without `.toString()`, a namespace or default import, and a `require()` or re-export of the package. To use the package itself, set `importAliases: { '@vanilla-extract/css-utils': false }`. + ## Namespace imports A namespace stands for many named exports whose Devup UI counterparts are renamed (`style` → `css`), which a namespace access cannot express, so it is left alone: diff --git a/libs/extractor/src/import_alias_visit.rs b/libs/extractor/src/import_alias_visit.rs index a1ce2b503..4479776d8 100644 --- a/libs/extractor/src/import_alias_visit.rs +++ b/libs/extractor/src/import_alias_visit.rs @@ -729,7 +729,19 @@ pub fn transform_import_aliases_with_edits<'a>( // Collect import transformations let mut transformations: Vec<(usize, usize, String)> = Vec::new(); + // One analysis for the whole pass: building it sets the AST's symbol and + // reference IDs, which every later reader resolves against this table let mut scoping = None; + if !redirect_every_name && crate::vanilla_extract_calc::reads(code, import_aliases) { + let built = scoping.insert( + SemanticBuilder::new() + .build(&program) + .semantic + .into_scoping(), + ); + transformations + .extend(crate::vanilla_extract_calc::compile(&program, built, false).replacements); + } let may_take_css = CssProp::of(import_aliases, code, false) != CssProp::Off; let mut symbol = |local: &BindingIdentifier<'_>| { scoping.get_or_insert_with(|| { @@ -797,6 +809,7 @@ pub fn transform_import_aliases_with_edits<'a>( format!("\"{runtime}\""), )); } else if let Some(alias) = import_aliases.get(source_value) + && source_value != crate::vanilla_extract_calc::CSS_UTILS && !import_decl.import_kind.is_type() { let span = import_decl.span; diff --git a/libs/extractor/src/lib.rs b/libs/extractor/src/lib.rs index fe1bb8dc4..4253383c5 100644 --- a/libs/extractor/src/lib.rs +++ b/libs/extractor/src/lib.rs @@ -158,6 +158,7 @@ mod util_type; mod utils; mod vanilla_extract; pub use vanilla_extract::ExtractorCaches; +mod vanilla_extract_calc; #[cfg(test)] mod vanilla_extract_theme_import_tests; mod visit; @@ -514,6 +515,11 @@ fn extract_source( filename, &option.import_aliases, )); + errors.extend(vanilla_extract_calc::errors( + code, + filename, + &option.import_aliases, + )); if evaluated.is_none() && !errors.is_empty() { return Err(located_errors(filename, code, &[], errors).into()); } diff --git a/libs/extractor/src/module_loader.rs b/libs/extractor/src/module_loader.rs index a38b76415..905a9c29a 100644 --- a/libs/extractor/src/module_loader.rs +++ b/libs/extractor/src/module_loader.rs @@ -16,6 +16,7 @@ use rustc_hash::{FxHashMap, FxHashSet}; use crate::{ExtractOption, ModuleResolver, utils::is_vanilla_extract_file}; +pub(crate) mod css_utils; mod import_bindings; pub(crate) mod operations; mod retained_css; @@ -24,6 +25,7 @@ mod script; mod tests; mod validate; +use css_utils::{CSS_UTILS, CSS_UTILS_BINDING, CSS_UTILS_MODULE}; use import_bindings::{BindingSource, ImportBindings}; use retained_css::{CssImport, RetainedCss}; pub(crate) use script::{Body, Origin, SCRIPT_PATH, Script, Unit}; @@ -153,6 +155,9 @@ pub(crate) struct ModuleLoader<'r> { /// What the stylesheet imports for its side effects, and the stylesheets it /// imports, which emit their own styles: its output keeps importing them pub kept_imports: Vec, + /// Whether the stylesheet loads `@vanilla-extract/css-utils`, which it + /// evaluates as written here + css_utils: bool, } impl<'r> ModuleLoader<'r> { @@ -185,6 +190,7 @@ impl<'r> ModuleLoader<'r> { css_bindings: FxHashMap::default(), dependencies: BTreeSet::new(), kept_imports: Vec::new(), + css_utils: false, } } @@ -207,6 +213,9 @@ impl<'r> ModuleLoader<'r> { /// stylesheet pub(crate) fn script(&self, entry: &ModuleScript) -> Script { let mut script = Script::default(); + if self.css_utils { + script.generated(CSS_UTILS_MODULE); + } for definition in &self.definitions { match definition { Definition::Generated(text) => script.generated(text), @@ -228,6 +237,10 @@ impl<'r> ModuleLoader<'r> { /// The name of the exports object of `specifier` imported by `importer` fn load(&mut self, specifier: &str, importer: &str, direct: bool) -> Result { + if specifier == CSS_UTILS && self.option.import_aliases.contains_key(CSS_UTILS) { + self.css_utils = true; + return Ok(CSS_UTILS_BINDING.to_string()); + } let resolver = self.resolver.ok_or(LoadError::NoResolver)?; let module = resolver(specifier, importer).ok_or(LoadError::Unresolved)?; if retained_css::is_css(&module.path) { diff --git a/libs/extractor/src/module_loader/css_utils.rs b/libs/extractor/src/module_loader/css_utils.rs new file mode 100644 index 000000000..c25ff5358 --- /dev/null +++ b/libs/extractor/src/module_loader/css_utils.rs @@ -0,0 +1,34 @@ +//! `@vanilla-extract/css-utils`, which a stylesheet evaluates as the package +//! itself would: its `calc` builds the same strings, without a resolver + +/// The package's specifier +pub(crate) const CSS_UTILS: &str = "@vanilla-extract/css-utils"; + +/// The object the package's exports are bound to while a stylesheet runs +pub(super) const CSS_UTILS_BINDING: &str = "__vanilla_extract_css_utils__"; + +/// What the error a `calc(x)` written as a CSS value throws says +pub(crate) const CHAIN_VALUE: &str = "of '@vanilla-extract/css-utils' builds an expression"; + +/// The package's `calc`, as `@vanilla-extract/css-utils` 0.1 writes it: the +/// operands of each operation are joined by the operator, every `calc` in +/// them dropped, so a nested operation is only parenthesized +pub(super) const CSS_UTILS_MODULE: &str = r#"const __vanilla_extract_css_utils__ = (() => { +const toExpression = (operator, ...operands) => operands.map((operand) => "".concat(operand)).join(" ".concat(operator, " ")).replace(/calc/g, ""); +const add = (...operands) => "calc(".concat(toExpression("+", ...operands), ")"); +const subtract = (...operands) => "calc(".concat(toExpression("-", ...operands), ")"); +const multiply = (...operands) => "calc(".concat(toExpression("*", ...operands), ")"); +const divide = (...operands) => "calc(".concat(toExpression("/", ...operands), ")"); +const negate = (x) => multiply(x, -1); +const calc = Object.assign((x) => ({ + add: (...operands) => calc(add(x, ...operands)), + subtract: (...operands) => calc(subtract(x, ...operands)), + multiply: (...operands) => calc(multiply(x, ...operands)), + divide: (...operands) => calc(divide(x, ...operands)), + negate: () => calc(negate(x)), + toString: () => x.toString(), + toJSON: () => { throw new TypeError("`calc(x)` of '@vanilla-extract/css-utils' builds an expression, which is a CSS value only once `.toString()` is called or it is interpolated in a template"); }, +}), { add, subtract, multiply, divide, negate }); +return Object.freeze({ calc }); +})(); +"#; diff --git a/libs/extractor/src/module_loader/script/explain.rs b/libs/extractor/src/module_loader/script/explain.rs index c72aad1dd..74e5cc7c3 100644 --- a/libs/extractor/src/module_loader/script/explain.rs +++ b/libs/extractor/src/module_loader/script/explain.rs @@ -122,6 +122,9 @@ fn fix(cause: &str) -> String { "declare or import `{name}` before this code reads it; it is not available when the stylesheet is evaluated at build time" ); } + if cause.contains(crate::module_loader::css_utils::CHAIN_VALUE) { + return "call `.toString()` on it, as `calc(x).multiply(2).toString()`, or interpolate it in a template".to_string(); + } if cause.starts_with("SyntaxError") { return "correct the syntax at this location".to_string(); } diff --git a/libs/extractor/src/snapshots/extractor__vanilla_extract_calc__tests__calc_expression_written_as_a_stylesheet_value_is_a_located_error.snap b/libs/extractor/src/snapshots/extractor__vanilla_extract_calc__tests__calc_expression_written_as_a_stylesheet_value_is_a_located_error.snap new file mode 100644 index 000000000..7817f226d --- /dev/null +++ b/libs/extractor/src/snapshots/extractor__vanilla_extract_calc__tests__calc_expression_written_as_a_stylesheet_value_is_a_located_error.snap @@ -0,0 +1,8 @@ +--- +source: libs/extractor/src/vanilla_extract_calc_tests.rs +expression: message +--- +theme.css.ts:3:23: JS execution error: TypeError: `calc(x)` of '@vanilla-extract/css-utils' builds an expression, which is a CSS value only once `.toString()` is called or it is interpolated in a template. Fix: call `.toString()` on it, as `calc(x).multiply(2).toString()`, or interpolate it in a template + at stringify (native) + at style (native) + at
(theme.css.ts:3:23) diff --git a/libs/extractor/src/snapshots/extractor__vanilla_extract_calc__tests__calc_in_a_stylesheet_reads_what_the_stylesheet_evaluates.snap b/libs/extractor/src/snapshots/extractor__vanilla_extract_calc__tests__calc_in_a_stylesheet_reads_what_the_stylesheet_evaluates.snap new file mode 100644 index 000000000..068687da5 --- /dev/null +++ b/libs/extractor/src/snapshots/extractor__vanilla_extract_calc__tests__calc_in_a_stylesheet_reads_what_the_stylesheet_evaluates.snap @@ -0,0 +1,12 @@ +--- +source: libs/extractor/src/vanilla_extract_calc_tests.rs +expression: "format!(\"{compiled:#?}\")" +--- +Ok( + ( + "import \"@devup-ui/react/devup-ui-0.css\";\nexport const a = \"a-a a-b\";\n;\nexport const theme = \"theme-0-1\";\nexport const vars = { \"space\": { \"md\": \"var(--space-md-0-2)\" } };\n", + [ + "calc((var(--space-md-0-2) * 2) + (var(--var-0-0) * -1))", + ], + ), +) diff --git a/libs/extractor/src/snapshots/extractor__vanilla_extract_calc__tests__calc_outside_styles_is_written_as_its_string.snap b/libs/extractor/src/snapshots/extractor__vanilla_extract_calc__tests__calc_outside_styles_is_written_as_its_string.snap new file mode 100644 index 000000000..edcd2054e --- /dev/null +++ b/libs/extractor/src/snapshots/extractor__vanilla_extract_calc__tests__calc_outside_styles_is_written_as_its_string.snap @@ -0,0 +1,10 @@ +--- +source: libs/extractor/src/vanilla_extract_calc_tests.rs +expression: "format!(\"{compiled:#?}\")" +--- +Ok( + ( + "import type { Unused } from \"@vanilla-extract/css-utils\";\nexport const gap: typeof calc = \"calc(1px + 2px)\" as never;\nexport const half = `calc(100% / 2) - 1px`;\n", + [], + ), +) diff --git a/libs/extractor/src/style_values/absence.rs b/libs/extractor/src/style_values/absence.rs index 779d4f9a8..82e42140e 100644 --- a/libs/extractor/src/style_values/absence.rs +++ b/libs/extractor/src/style_values/absence.rs @@ -1,5 +1,6 @@ use super::StyleValues; use crate::utils::unwrap_syntax_only; +use oxc_allocator::{Allocator, CloneIn}; use oxc_ast::ast::{Expression, IdentifierReference, Program}; use oxc_ast_visit::Visit; use oxc_semantic::{Scoping, SemanticBuilder}; @@ -37,25 +38,32 @@ impl StyleValues<'_> { if !program.source_text.contains("undefined") { return; } - let temporary; - let scoping: &Scoping = if let Some(scoping) = &self.scoping { - scoping - } else { - temporary = SemanticBuilder::new() - .build(program) - .semantic - .into_scoping(); - &temporary - }; - let mut references = AbsenceReferences { - scoping, - spans: FxHashSet::default(), + self.absent_references = match &self.scoping { + Some(scoping) => absent_references(scoping, program), + None => absent_in_copy(program), }; - references.visit_program(program); - self.absent_references = references.spans; } } +fn absent_references(scoping: &Scoping, program: &Program<'_>) -> FxHashSet { + let mut references = AbsenceReferences { + scoping, + spans: FxHashSet::default(), + }; + references.visit_program(program); + references.spans +} + +/// The proof for a program the visit reads with no analysis: built on a copy, +/// since analysing the program itself would give it IDs no table of the visit +/// resolves +fn absent_in_copy(program: &Program<'_>) -> FxHashSet { + let allocator = Allocator::default(); + let copy = program.clone_in(&allocator); + let scoping = SemanticBuilder::new().build(©).semantic.into_scoping(); + absent_references(&scoping, ©) +} + struct AbsenceReferences<'s> { scoping: &'s Scoping, spans: FxHashSet, @@ -155,6 +163,26 @@ mod tests { assert!(!values.is_unbound_undefined(&statement.expression)); } + #[test] + fn recording_without_scoping_leaves_the_program_without_ids() { + // Given a program the visit reads with no semantic analysis. + let arena = Allocator::default(); + let parsed = Parser::new(&arena, "undefined;", SourceType::tsx()).parse(); + let mut values = StyleValues::default(); + // When the absence proof is recorded. + values.record_absence(&parsed.program); + // Then the proof holds while the program keeps no reference ID, which + // the visit's empty table could not resolve. + let Statement::ExpressionStatement(statement) = &parsed.program.body[0] else { + panic!("expected expression"); + }; + let Expression::Identifier(identifier) = &statement.expression else { + panic!("expected identifier"); + }; + assert_eq!(identifier.reference_id.get(), None); + assert!(values.is_unbound_undefined(&statement.expression)); + } + #[test] fn recording_requires_reference_metadata_when_scoping_is_supplied() { // Given real scoping whose authored reference ID was cleared before recording. diff --git a/libs/extractor/src/vanilla_extract_calc.rs b/libs/extractor/src/vanilla_extract_calc.rs new file mode 100644 index 000000000..4a459b26d --- /dev/null +++ b/libs/extractor/src/vanilla_extract_calc.rs @@ -0,0 +1,455 @@ +//! `calc` of `@vanilla-extract/css-utils`, compiled to the strings the +//! package builds. +//! +//! A `.css.ts` stylesheet is evaluated, and evaluates the package's own +//! `calc` (see `module_loader::css_utils`). Any other module is not, so each +//! `calc` there is written as the string it gives, which only literal +//! operands let the build know; whatever else reads `calc` is a build error. + +use oxc_allocator::Allocator; +use oxc_ast::ast::{ + Argument, BindingPattern, CallExpression, Declaration, Expression, IdentifierReference, + ImportDeclaration, ImportDeclarationSpecifier, Program, Statement, TaggedTemplateExpression, + TemplateLiteral, VariableDeclaration, VariableDeclarationKind, +}; +use oxc_ast_visit::{Visit, walk}; +use oxc_parser::Parser; +use oxc_semantic::{Scoping, SemanticBuilder}; +use oxc_span::GetSpan; +use oxc_syntax::symbol::SymbolId; +use rustc_hash::{FxHashMap, FxHashSet}; +use std::collections::HashMap; + +use crate::ImportAlias; +pub(crate) use crate::module_loader::css_utils::CSS_UTILS; +use crate::utils::{ + get_string_by_literal_expression, is_vanilla_extract_file, readable_code, unwrap_syntax_only, +}; +use crate::vanilla_extract::json_string; + +#[cfg(test)] +#[path = "vanilla_extract_calc_tests.rs"] +mod tests; + +type Error = (u32, String); + +/// What compiling `calc` writes: the replacements of the source it makes, +/// and the errors where it cannot +#[derive(Default)] +pub(crate) struct Compiled { + pub replacements: Vec<(usize, usize, String)>, + pub errors: Vec, +} + +/// What a `calc` expression gives: a string, or the chainable expression +/// `calc(x)` builds, which is `x` as a string +#[derive(Debug, PartialEq)] +enum Value { + Text(String), + Chain(String), +} + +impl Value { + fn text(self) -> String { + match self { + Self::Text(text) | Self::Chain(text) => text, + } + } +} + +/// The operator of the `calc` operation `name` +fn operator(name: &str) -> Option<&'static str> { + match name { + "add" => Some("+"), + "subtract" => Some("-"), + "multiply" => Some("*"), + "divide" => Some("/"), + _ => None, + } +} + +/// `calc.add(...)` and its siblings as the package writes them: the operands +/// joined by the operator, with every `calc` in them dropped +fn operation(operator: &str, operands: &[String]) -> String { + let joined = operands.join(&format!(" {operator} ")).replace("calc", ""); + format!("calc({joined})") +} + +fn error(expression: &Expression<'_>, requirement: &str) -> Error { + ( + expression.span().start, + format!( + "`{CSS_UTILS}` cannot compile `{}` at build time outside a `.css.ts` stylesheet: {requirement}. Fix: write it with literal operands, as `calc.add('100%', '-4px')` or `calc('4px').multiply(2).toString()`, or build it in a `.css.ts` stylesheet, where vanilla-extract values are evaluated", + readable_code(expression) + ), + ) +} + +fn chain_error(expression: &Expression<'_>) -> Error { + ( + expression.span().start, + format!( + "`{CSS_UTILS}` cannot use `{}` as a value: `calc(x)` builds an expression, which is a string only once `.toString()` is called or it is interpolated in a template. Fix: call `.toString()` on it, as `calc(x).multiply(2).toString()`", + readable_code(expression) + ), + ) +} + +fn import_error(at: u32, requirement: &str) -> Error { + ( + at, + format!( + "`{CSS_UTILS}` {requirement}. Fix: import `calc` by name, as `import {{ calc }} from '{CSS_UTILS}'`, or set `importAliases: {{ '{CSS_UTILS}': false }}`" + ), + ) +} + +/// Whether `code` may read `@vanilla-extract/css-utils`, which the build +/// compiles while it is aliased +pub(crate) fn reads(code: &str, import_aliases: &HashMap) -> bool { + import_aliases.contains_key(CSS_UTILS) && code.contains(CSS_UTILS) +} + +/// Where `code` of `filename` uses `@vanilla-extract/css-utils` in a way the +/// build cannot compile +pub(crate) fn errors( + code: &str, + filename: &str, + import_aliases: &HashMap, +) -> Vec { + if !reads(code, import_aliases) { + return Vec::new(); + } + let allocator = Allocator::default(); + let source_type = crate::parsing::source_type(filename).unwrap_or_default(); + let program = Parser::new(&allocator, code, source_type).parse().program; + let scoping = SemanticBuilder::new() + .build(&program) + .semantic + .into_scoping(); + compile(&program, &scoping, is_vanilla_extract_file(filename)).errors +} + +/// The declaration `statement` makes of variables, exported or not +fn variables<'s, 'a>(statement: &'s Statement<'a>) -> Option<&'s VariableDeclaration<'a>> { + match statement { + Statement::VariableDeclaration(declaration) => Some(declaration), + Statement::ExportDeclaration(export) => match &export.declaration { + Declaration::VariableDeclaration(declaration) => Some(declaration), + _ => None, + }, + _ => None, + } +} + +/// The strings the module-level `const`s of `program` hold as literals, +/// which no code can change +fn constants(program: &Program<'_>) -> FxHashMap { + program + .body + .iter() + .filter_map(variables) + .filter(|declaration| declaration.kind == VariableDeclarationKind::Const) + .flat_map(|declaration| &declaration.declarations) + .filter_map(|declarator| match (&declarator.id, &declarator.init) { + (BindingPattern::BindingIdentifier(id), Some(init)) => Some(( + id.symbol_id.get()?, + get_string_by_literal_expression(unwrap_syntax_only(init))?.into_owned(), + )), + _ => None, + }) + .collect() +} + +/// Compile the `calc` of `program`, whose symbols `scoping` resolves; a +/// `stylesheet` evaluates it, so only what it imports is checked there +pub(crate) fn compile(program: &Program<'_>, scoping: &Scoping, stylesheet: bool) -> Compiled { + let mut compiler = Compiler { + scoping, + calc: FxHashSet::default(), + constants: constants(program), + interpolated: false, + compiled: Compiled::default(), + }; + for statement in &program.body { + if let Statement::ImportDeclaration(import) = statement + && import.source.value == CSS_UTILS + && !import.import_kind.is_type() + { + compiler.import(import, stylesheet); + } + } + if stylesheet { + return compiler.compiled; + } + let imports: FxHashSet = program + .body + .iter() + .filter_map(|statement| match statement { + Statement::ImportDeclaration(import) => Some(import.span.start), + _ => None, + }) + .collect(); + for (at, _) in crate::module_loads::module_loads(program, &[CSS_UTILS]) { + if !imports.contains(&at) { + compiler.compiled.errors.push(import_error( + at, + "is loaded where the build cannot read `calc`", + )); + } + } + compiler.visit_program(program); + compiler.compiled +} + +struct Compiler<'s> { + scoping: &'s Scoping, + /// The import bindings of `calc` + calc: FxHashSet, + /// The strings module-level `const`s hold as literals + constants: FxHashMap, + /// Whether the expression visited next is interpolated in a template, + /// which reads it as a string + interpolated: bool, + compiled: Compiled, +} + +impl Compiler<'_> { + fn import(&mut self, import: &ImportDeclaration<'_>, stylesheet: bool) { + for specifier in import.specifiers.iter().flatten() { + match specifier { + ImportDeclarationSpecifier::ImportSpecifier(named) + if named.import_kind.is_type() => {} + ImportDeclarationSpecifier::ImportSpecifier(named) + if named.imported.name() == "calc" => + { + self.calc.extend(named.local.symbol_id.get()); + } + ImportDeclarationSpecifier::ImportNamespaceSpecifier(_) if stylesheet => {} + ImportDeclarationSpecifier::ImportNamespaceSpecifier(namespace) => { + self.compiled.errors.push(import_error( + namespace.span.start, + "is imported whole where the build reads only `calc` imported by name", + )); + } + specifier => { + let name = match specifier { + ImportDeclarationSpecifier::ImportSpecifier(named) => { + named.imported.name().to_string() + } + _ => "default".to_string(), + }; + self.compiled.errors.push(import_error( + specifier.span().start, + &format!("has no export `{name}`: it exports only `calc`"), + )); + } + } + } + if !stylesheet { + self.compiled.replacements.push(( + import.span.start as usize, + import.span.end as usize, + String::new(), + )); + } + } + + fn is_calc(&self, identifier: &IdentifierReference<'_>) -> bool { + identifier + .reference_id + .get() + .and_then(|reference| self.scoping.get_reference(reference).symbol_id()) + .is_some_and(|symbol| self.calc.contains(&symbol)) + } + + /// The string `expression` reads when it names a constant of the module + fn constant(&self, expression: &Expression<'_>) -> Option<&String> { + let Expression::Identifier(identifier) = unwrap_syntax_only(expression) else { + return None; + }; + let reference = self.scoping.get_reference(identifier.reference_id.get()?); + self.constants.get(&reference.symbol_id()?) + } + + /// Whether `expression` reads a binding of `calc` + fn reads_calc(&self, expression: &Expression<'_>) -> bool { + matches!(unwrap_syntax_only(expression), Expression::Identifier(identifier) if self.is_calc(identifier)) + } + + /// What `expression` gives when it is a call of `calc`, `calc.add`, ... + /// or of a method of what `calc(x)` gives + fn evaluate(&mut self, expression: &Expression<'_>) -> Option> { + let Expression::CallExpression(call) = unwrap_syntax_only(expression) else { + return None; + }; + if self.reads_calc(&call.callee) { + return Some(self.chain(expression, call)); + } + let Expression::StaticMemberExpression(member) = unwrap_syntax_only(&call.callee) else { + return None; + }; + let name = member.property.name.as_str(); + if self.reads_calc(&member.object) { + return Some(self.static_operation(expression, name, call)); + } + let object = self.evaluate(&member.object)?; + Some(object.and_then(|object| self.method(expression, object, name, call))) + } + + /// `calc(x)` + fn chain( + &mut self, + expression: &Expression<'_>, + call: &CallExpression<'_>, + ) -> Result { + let [operand] = self + .operands(expression, &call.arguments)? + .try_into() + .map_err(|_| { + error( + expression, + "`calc()` takes the one value it builds an expression of", + ) + })?; + Ok(Value::Chain(operand)) + } + + /// `calc.add(...)`, `calc.negate(x)`, ... + fn static_operation( + &mut self, + expression: &Expression<'_>, + name: &str, + call: &CallExpression<'_>, + ) -> Result { + let operands = self.operands(expression, &call.arguments)?; + if let Some(operator) = operator(name) { + return Ok(Value::Text(operation(operator, &operands))); + } + match (name, operands.as_slice()) { + ("negate", [operand]) => { + Ok(Value::Text(operation("*", &[operand.clone(), "-1".into()]))) + } + ("negate", _) => Err(error( + expression, + "`calc.negate()` takes the one value it negates", + )), + _ => Err(error(expression, &format!("`calc` has no `{name}`"))), + } + } + + /// `name` called on `object`, which `calc(x)` or a string gives + fn method( + &mut self, + expression: &Expression<'_>, + object: Value, + name: &str, + call: &CallExpression<'_>, + ) -> Result { + let operands = self.operands(expression, &call.arguments)?; + match (object, name, operator(name)) { + (object, "toString", _) if operands.is_empty() => Ok(Value::Text(object.text())), + (Value::Chain(x), "negate", _) if operands.is_empty() => { + Ok(Value::Chain(operation("*", &[x, "-1".into()]))) + } + (Value::Chain(x), _, Some(operator)) => { + let operands: Vec = std::iter::once(x).chain(operands).collect(); + Ok(Value::Chain(operation(operator, &operands))) + } + _ => Err(error( + expression, + &format!( + "`.{name}()` is not one the build compiles, which are `add`, `subtract`, `multiply`, `divide` and `negate` of `calc(x)`, and `toString()`" + ), + )), + } + } + + /// The strings `arguments` pass as operands + fn operands( + &mut self, + expression: &Expression<'_>, + arguments: &[Argument<'_>], + ) -> Result, Error> { + arguments + .iter() + .map(|argument| { + let operand = argument + .as_expression() + .ok_or_else(|| error(expression, "its operands cannot be spread"))?; + self.operand(operand) + }) + .collect() + } + + /// The string `operand` gives, as the package concatenates it + fn operand(&mut self, operand: &Expression<'_>) -> Result { + if let Some(text) = get_string_by_literal_expression(unwrap_syntax_only(operand)) { + return Ok(text.into_owned()); + } + if let Some(text) = self.constant(operand) { + return Ok(text.clone()); + } + self.evaluate(operand).map_or_else( + || { + Err(error( + operand, + "its operands must be literals, module-level `const`s holding a literal, or other `calc` results", + )) + }, + |value| value.map(Value::text), + ) + } +} + +impl<'a> Visit<'a> for Compiler<'_> { + fn visit_expression(&mut self, expression: &Expression<'a>) { + let interpolated = std::mem::take(&mut self.interpolated); + match self.evaluate(expression) { + Some(Ok(Value::Chain(_))) if !interpolated => { + self.compiled.errors.push(chain_error(expression)); + } + Some(Ok(value)) => { + let span = unwrap_syntax_only(expression).span(); + self.compiled.replacements.push(( + span.start as usize, + span.end as usize, + json_string(&value.text()), + )); + } + Some(Err(error)) => self.compiled.errors.push(error), + None => walk::walk_expression(self, expression), + } + } + + fn visit_template_literal(&mut self, template: &TemplateLiteral<'a>) { + for expression in &template.expressions { + self.interpolated = true; + self.visit_expression(expression); + } + } + + fn visit_tagged_template_expression(&mut self, tagged: &TaggedTemplateExpression<'a>) { + // A tag takes the interpolated values as they are + self.visit_expression(&tagged.tag); + for expression in &tagged.quasi.expressions { + self.visit_expression(expression); + } + } + + /// Types are erased, so what they read stays + fn visit_ts_type(&mut self, _: &oxc_ast::ast::TSType<'a>) {} + + /// `calc` read by what the build does not compile, which a call it + /// compiles never walks into + fn visit_identifier_reference(&mut self, identifier: &IdentifierReference<'a>) { + if self.is_calc(identifier) { + self.compiled.errors.push(( + identifier.span.start, + format!( + "`calc` of `{CSS_UTILS}` is read at runtime, where it does not exist: the build compiles it only where it is called. Fix: call `calc.add(...)`, `calc.negate(...)` or `calc(x)` with its methods and `.toString()` where the value is used" + ), + )); + } + } +} diff --git a/libs/extractor/src/vanilla_extract_calc_tests.rs b/libs/extractor/src/vanilla_extract_calc_tests.rs new file mode 100644 index 000000000..00091a4f4 --- /dev/null +++ b/libs/extractor/src/vanilla_extract_calc_tests.rs @@ -0,0 +1,274 @@ +//! `@vanilla-extract/css-utils` compiles to the strings the package builds +//! (VE-05): the expected values are what `@vanilla-extract/css-utils` 0.1.6 +//! returns for each expression +use std::collections::HashMap; + +use css::{class_map::reset_class_map, file_map::reset_file_map}; +use insta::assert_snapshot; +use rstest::rstest; +use serial_test::serial; + +use crate::extract_style::extract_style_value::ExtractStyleValue; +use crate::{ExtractOption, ImportAlias, extract}; + +const UTILS: &str = "import { calc } from '@vanilla-extract/css-utils';"; + +/// Constants a `calc` may read, beside bindings it may not +const CONSTANTS: &str = "const GAP = '4px';\nexport const HALF = `50%`;\nconst SCALE = 2;\nlet loose = '1px';\nconst { picked } = { picked: '1px' };\nconst computed = [1].length;\nexport function f() {}\nexport default 1;"; + +fn aliases(css_utils: bool) -> ExtractOption { + let mut import_aliases = HashMap::from([( + "@vanilla-extract/css".to_string(), + ImportAlias::NamedToNamed, + )]); + if css_utils { + import_aliases.insert( + "@vanilla-extract/css-utils".to_string(), + ImportAlias::NamedToNamed, + ); + } + ExtractOption { + import_aliases, + ..ExtractOption::default() + } +} + +/// The code `code` of `filename` compiles to, with the `width` it styles, +/// or the error it fails with. +/// +/// A call nested in a chained call takes the unoptimized stylesheet pipeline +/// more than the 2 MiB of a test thread, whatever it calls, so it runs on a +/// larger one +fn compiled(filename: &str, code: &str) -> Result<(String, Vec), String> { + std::thread::scope(|scope| { + std::thread::Builder::new() + .stack_size(8 << 20) + .spawn_scoped(scope, || compiled_here(filename, code)) + .map_err(|error| error.to_string())? + .join() + .map_err(|_| "the extraction panicked".to_string())? + }) +} + +fn compiled_here(filename: &str, code: &str) -> Result<(String, Vec), String> { + reset_class_map(); + reset_file_map(); + let output = extract(filename, code, aliases(true)).map_err(|error| error.to_string())?; + let mut widths: Vec = output + .styles + .iter() + .filter_map(|style| match style { + ExtractStyleValue::Static(style) if style.property == "width" => { + Some(style.value.clone()) + } + _ => None, + }) + .collect(); + widths.sort(); + Ok((output.code, widths)) +} + +fn error(filename: &str, code: &str) -> String { + compiled(filename, code).err().unwrap_or_default() +} + +#[rstest] +#[case("calc.add('1px', '2px')", "calc(1px + 2px)")] +#[case("calc.subtract('100%', '4px', '2px')", "calc(100% - 4px - 2px)")] +#[case("calc.multiply('var(--x)', 2)", "calc(var(--x) * 2)")] +#[case("calc.divide('100%', 3)", "calc(100% / 3)")] +#[case("calc.negate('4px')", "calc(4px * -1)")] +#[case("calc.add(calc.multiply('2px', 3), '1px')", "calc((2px * 3) + 1px)")] +#[case( + "calc('10px').add('5px').multiply(2).toString()", + "calc((10px + 5px) * 2)" +)] +#[case("calc('10px').negate().toString()", "calc(10px * -1)")] +#[case( + "calc('1px').add(2).divide(3, calc.subtract('1px', '-2px')).toString()", + "calc((1px + 2) / 3 / (1px - -2px))" +)] +#[case( + "calc(-1.5).subtract(calc('1px').add('2px')).toString()", + "calc(-1.5 - (1px + 2px))" +)] +#[case("`${calc('1rem').multiply(2)}`", "calc(1rem * 2)")] +#[case("calc.add('var(--calc-gap)', `1px`)", "calc(var(---gap) + 1px)")] +#[case("calc.add(true, 1e21)", "calc(true + 1e+21)")] +#[case("calc.add('1px', '2px').toString()", "calc(1px + 2px)")] +#[case("calc.add(GAP, HALF, SCALE)", "calc(4px + 50% + 2)")] +#[case("(calc as typeof calc).add('1px', '2px')", "calc(1px + 2px)")] +#[serial] +fn calc_gives_the_string_the_package_builds(#[case] expression: &str, #[case] expected: &str) { + // Outside a stylesheet each call is written as its string + let (code, widths) = compiled( + "app.tsx", + &format!( + "import {{ css }} from '@devup-ui/react';\n{UTILS}\nexport const joined = [1].join('-');\n{CONSTANTS}\nexport const a = css({{ width: {expression} }});" + ), + ) + .unwrap_or_default(); + assert_eq!(widths, [expected], "{expression}\n{code}"); + assert!(!code.contains("css-utils"), "{code}"); + // A stylesheet evaluates the package's own `calc` + let stylesheet = format!( + "import {{ style }} from '@vanilla-extract/css';\n{UTILS}\n{CONSTANTS}\nexport const a = style({{ width: {expression} }});" + ); + let (code, widths) = compiled("theme.css.ts", &stylesheet).unwrap_or_default(); + assert_eq!(widths, [expected], "{expression}\n{code}"); +} + +#[test] +#[serial] +fn calc_outside_styles_is_written_as_its_string() { + let compiled = compiled( + "app.ts", + "import type { Unused } from '@vanilla-extract/css-utils'; +import { calc, type Calc } from '@vanilla-extract/css-utils'; +export const gap: typeof calc = calc.add('1px', '2px') as never; +export const half = `${calc('100%').divide(2)} - 1px`;", + ); + assert_snapshot!(format!("{compiled:#?}")); +} + +#[test] +#[serial] +fn calc_in_a_stylesheet_reads_what_the_stylesheet_evaluates() { + let compiled = compiled( + "theme.css.ts", + "import { createTheme, createVar, style } from '@vanilla-extract/css';\nimport * as utils from '@vanilla-extract/css-utils';\nimport { calc } from '@vanilla-extract/css-utils';\nconst gap = createVar();\nexport const [theme, vars] = createTheme({ space: { md: '8px' } });\nexport const a = style({ width: utils.calc(vars.space.md).multiply(2).add(calc.negate(gap)).toString(), vars: { [gap]: '4px' } });", + ); + assert_snapshot!(format!("{compiled:#?}")); +} + +#[rstest] +#[case("calc.add('1px', gap)", "app.tsx:3:47: ")] +#[case("calc.add(picked)", "app.tsx:3:40: ")] +#[case("calc.add(theme.gap)", "app.tsx:3:40: ")] +#[case("calc.add(window)", "app.tsx:3:40: ")] +#[case("calc.add(...parts)", "app.tsx:3:31: ")] +#[case("calc()", "app.tsx:3:31: ")] +#[case("calc('1px', '2px').toString()", "app.tsx:3:31: ")] +#[case("calc.negate()", "app.tsx:3:31: ")] +#[case("calc.percent('1px')", "app.tsx:3:31: ")] +#[case("calc('1px').percent()", "app.tsx:3:31: ")] +#[case("calc('1px').toString('x')", "app.tsx:3:31: ")] +#[case("calc('1px').negate('x').toString()", "app.tsx:3:31: ")] +#[case("calc.add('1px', '2px').trim()", "app.tsx:3:31: ")] +#[case("calc('1px').multiply(2)", "app.tsx:3:31: ")] +#[case("css`width: ${calc('1px')};`", "app.tsx:3:44: ")] +#[case("calc", "app.tsx:3:31: ")] +#[case("calc.add", "app.tsx:3:31: ")] +#[case("[calc].map(String)[0]", "app.tsx:3:32: ")] +#[serial] +fn calc_the_build_cannot_compute_is_a_located_error( + #[case] expression: &str, + #[case] location: &str, +) { + let message = error( + "app.tsx", + &format!( + "import {{ css }} from '@devup-ui/react';\n{UTILS}\nexport const a = css({{ width: {expression} }});\nlet gap = '4px';\nconst {{ picked }} = {{ picked: '1px' }};\nconst theme = {{ gap: '1px' }};\nconst parts = ['1px'];" + ), + ); + assert!(message.starts_with(location), "{expression}\n{message}"); + assert!(message.contains("Fix: "), "{expression}\n{message}"); +} + +#[rstest] +#[case("app.tsx", "import * as utils from '@vanilla-extract/css-utils';")] +#[case("app.tsx", "import utils from '@vanilla-extract/css-utils';")] +#[case("app.tsx", "import { percent } from '@vanilla-extract/css-utils';")] +#[case("app.tsx", "export { calc } from '@vanilla-extract/css-utils';")] +#[case("app.tsx", "const utils = require('@vanilla-extract/css-utils');")] +#[case("theme.css.ts", "import utils from '@vanilla-extract/css-utils';")] +#[case( + "theme.css.ts", + "import { percent } from '@vanilla-extract/css-utils';" +)] +#[serial] +fn css_utils_loaded_but_as_calc_by_name_is_a_located_error( + #[case] filename: &str, + #[case] load: &str, +) { + let message = error( + filename, + &format!( + "import {{ style }} from '@vanilla-extract/css';\n{load}\nexport const a = style({{ width: '1px' }});" + ), + ); + assert!( + message.starts_with(&format!("{filename}:2:")), + "{load}\n{message}" + ); + assert!( + message.contains("Fix: import `calc` by name"), + "{load}\n{message}" + ); +} + +#[test] +#[serial] +fn calc_expression_written_as_a_stylesheet_value_is_a_located_error() { + let message = error( + "theme.css.ts", + &format!( + "import {{ style }} from '@vanilla-extract/css';\n{UTILS}\nexport const a = style({{ width: calc('1px').multiply(2) }});" + ), + ); + assert_snapshot!(message); +} + +#[test] +#[serial] +fn css_utils_left_unaliased_stays_as_written() { + reset_class_map(); + reset_file_map(); + let source = format!("{UTILS}\nexport const a = calc.add(gap, '1px');"); + let output = extract("app.tsx", &source, aliases(false)).map_err(|error| error.to_string()); + assert!(output.is_ok_and(|output| output.code.contains("@vanilla-extract/css-utils"))); + let message = extract( + "theme.css.ts", + &format!("import {{ style }} from '@vanilla-extract/css';\n{UTILS}\nexport const a = style({{ width: calc.add('1px', '2px') }});"), + aliases(false), + ) + .err() + .map_or_default(|error| error.to_string()); + assert!(message.contains("without a module resolver"), "{message}"); +} + +/// The analysis `calc` is compiled with is the one the rest of the alias pass +/// reads the program by: a module naming the package with no import of it, +/// whose calls the pass then reads for Emotion's `css` prop, once panicked +/// resolving their IDs against an empty table (`bun test`, on the sources of +/// the lint plugin, under the bun plugin) +#[rstest] +#[case("export const f = (node) => node.read({ css: '@vanilla-extract/css-utils' });")] +#[case( + "import { calc } from '@vanilla-extract/css-utils';\nexport const f = (node) => node.read({ css: calc.add('1px', '2px') });" +)] +#[serial] +fn calc_shares_its_analysis_with_the_alias_pass(#[case] source: &str) { + reset_class_map(); + reset_file_map(); + let mut option = aliases(true); + option + .import_aliases + .insert("@emotion/react".to_string(), ImportAlias::NamedToNamed); + let output = extract("src/rule.ts", source, option).map_err(|error| error.to_string()); + assert!(output.is_ok(), "{output:?}"); +} + +/// A module the visit reads with no analysis, which once panicked once the +/// `undefined` proof analysed the program itself: its IDs met the visit's +/// empty table +#[test] +#[serial] +fn undefined_proof_leaves_an_unanalysed_program_without_ids() { + reset_class_map(); + reset_file_map(); + let source = "const name = '@devup-ui/react';\nconst value = node.member;\nexport const absent = undefined;"; + let output = + extract("src/rule.ts", source, ExtractOption::default()).map_err(|error| error.to_string()); + assert!(output.is_ok(), "{output:?}"); +} diff --git a/packages/eslint-plugin/src/rules/css-utils-literal-only/README.md b/packages/eslint-plugin/src/rules/css-utils-literal-only/README.md index 4f6f2e6f8..a35a29660 100644 --- a/packages/eslint-plugin/src/rules/css-utils-literal-only/README.md +++ b/packages/eslint-plugin/src/rules/css-utils-literal-only/README.md @@ -13,6 +13,7 @@ The build knows: - literals, and constants: imports and module-level `const`s - what those compute through exact built-ins (`String`, `Number`, `JSON`, string and array methods, `Math.max`, `Math.round`, ... — not `Math.random`, `Math.sin` or `Math.pow`) and through functions this file declares that only compute - what StyleX functions give: `defineVars()` variables, `keyframes()` names, `firstThatWorks()` +- what `calc` of `@vanilla-extract/css-utils` gives, which the build writes as its string (`calc.add('1px', GAP)`, `calc('2px').multiply(2).toString()`); outside a `.css.ts` stylesheet the build reads only literals and `const`s holding one as its operands - the class a devup-ui `css()` and the name a `keyframes()` give, held in a `const` of any scope (`const fade = keyframes({ ... }); css({ animationName: fade })`, also inside a component), also through the package imported whole (`Devup.keyframes`) The build inlines constants, folds `Math` and runs the file's own functions at build time. It never runs another module's code, so calling an imported function is reported. diff --git a/packages/eslint-plugin/src/rules/css-utils-literal-only/__tests__/sources.test.ts b/packages/eslint-plugin/src/rules/css-utils-literal-only/__tests__/sources.test.ts index d67ea7f01..00e62373b 100644 --- a/packages/eslint-plugin/src/rules/css-utils-literal-only/__tests__/sources.test.ts +++ b/packages/eslint-plugin/src/rules/css-utils-literal-only/__tests__/sources.test.ts @@ -14,6 +14,7 @@ describe('css-utils-literal-only rule: libraries the build reads as Devup UI', ( const emotion = `import { css, keyframes, Global } from "@emotion/react";\nimport styled from "@emotion/styled";\n` const styledComponents = `import styled, { css, keyframes, createGlobalStyle } from "styled-components";\n` const vanilla = `import { style, globalStyle, keyframes } from "@vanilla-extract/css";\n` + const cssUtils = `import { calc } from "@vanilla-extract/css-utils";\n` const devup = `import { css, globalCss } from "@devup-ui/react";\n` const emotionCss = `import { css, cx, injectGlobal } from "@emotion/css";\n` const error = { messageId: 'cssUtilsLiteralOnly' as const } @@ -54,6 +55,15 @@ describe('css-utils-literal-only rule: libraries the build reads as Devup UI', ( [styledComponents, 'styled.div`color: ${(props) => props.color};`'], [vanilla, 'style({ color: "red" })'], [vanilla, 'globalStyle("body", { color: "red" })'], + [ + vanilla + cssUtils, + 'const GAP = "4px";\nstyle({ width: calc.add("1px", GAP), height: calc("2px").multiply(2).toString() })', + ], + [ + devup + + `import { "calc" as c, other } from "@vanilla-extract/css-utils";\n`, + 'css({ width: c.negate("1px") })', + ], [devup, 'globalCss({ body: { color: "red" } })'], [emotionCss, 'css({ color: "red" })'], [emotionCss, 'injectGlobal({ body: { color: "red" } })'], @@ -114,6 +124,11 @@ describe('css-utils-literal-only rule: libraries the build reads as Devup UI', ( [vanilla, 'style({ color: window.name })'], [vanilla, 'let v = 1;\nglobalStyle("body", { color: v })'], [vanilla, 'let v = 1;\nkeyframes({ from: { opacity: v } })'], + [vanilla + cssUtils, 'let v = "1px";\nstyle({ width: calc.add(v) })'], + [ + `import * as utils from "@vanilla-extract/css-utils";\n` + vanilla, + 'style({ width: utils.calc.add("1px") })', + ], [devup, 'let v = 1;\nglobalCss({ body: { color: v } })'], [emotionCss, 'css({ color: window.name })'], [emotionCss, 'let v = 1;\ninjectGlobal({ body: { color: v } })'], diff --git a/packages/eslint-plugin/src/rules/css-utils-literal-only/index.ts b/packages/eslint-plugin/src/rules/css-utils-literal-only/index.ts index cf2a59551..2c0d8066d 100644 --- a/packages/eslint-plugin/src/rules/css-utils-literal-only/index.ts +++ b/packages/eslint-plugin/src/rules/css-utils-literal-only/index.ts @@ -627,6 +627,8 @@ class Values { private readonly stylex: (name: string) => boolean, /** Whether calling `callee` gives the class of `css()` or the name of `keyframes()`, which the build writes in its place */ private readonly givesStyleName: (callee: TSESTree.Node) => boolean, + /** Whether a name binds the `calc` of `@vanilla-extract/css-utils`, whose calls the build writes as the string they give */ + private readonly calc: (name: string) => boolean, ) {} /** Whether `init` is a call of `css()` or `keyframes()`, whose result the build writes in place of a `const` holding it in any scope */ @@ -726,7 +728,8 @@ class Values { const callee = call.callee const root = rootOf(callee) if ( - (root.type === AST_NODE_TYPES.Identifier && this.stylex(root.name)) || + (root.type === AST_NODE_TYPES.Identifier && + (this.stylex(root.name) || this.calc(root.name))) || this.givesStyleName(callee) ) return true @@ -1070,7 +1073,13 @@ export const cssUtilsLiteralOnly = createRule({ : undefined return name === 'css' || name === 'keyframes' } - const values = new Values(changes, scopeOf, isStylex, givesStyleName) + const values = new Values( + changes, + scopeOf, + isStylex, + givesStyleName, + (name) => importStorage.isCalc(name), + ) /** Whether `attribute` is the `styles` of Emotion's `Global`, which the build reads as rules */ const isGlobalStyles = (attribute: TSESTree.JSXAttribute) => attribute.name.type === AST_NODE_TYPES.JSXIdentifier && diff --git a/packages/eslint-plugin/src/utils/__tests__/import-settings.test.ts b/packages/eslint-plugin/src/utils/__tests__/import-settings.test.ts index 6a985fb9f..a77405d4e 100644 --- a/packages/eslint-plugin/src/utils/__tests__/import-settings.test.ts +++ b/packages/eslint-plugin/src/utils/__tests__/import-settings.test.ts @@ -22,6 +22,7 @@ const settings = { 'acme-other': 'notAnExport', '@emotion/styled': false, 'styled-components': true, + '@vanilla-extract/css-utils': false, }, }, } @@ -62,6 +63,7 @@ describe('import settings', () => { 'import * as U from "@acme/ui/compat";', 'import { css as x } from "@devup-ui/react";', 'import { css as g } from "@emotion/react";', + 'import { calc } from "@vanilla-extract/css-utils";', ].join('\n'), (storage) => { expect(Object.fromEntries(storage.bindings())).toEqual({ @@ -73,6 +75,8 @@ describe('import settings', () => { g: 'css', }) expect(storage.isImportObject('U')).toBe(true) + // Turned off, the build leaves `calc` to the package + expect(storage.isCalc('calc')).toBe(false) }, ) diff --git a/packages/eslint-plugin/src/utils/import-storage.ts b/packages/eslint-plugin/src/utils/import-storage.ts index c04b425ff..290db823a 100644 --- a/packages/eslint-plugin/src/utils/import-storage.ts +++ b/packages/eslint-plugin/src/utils/import-storage.ts @@ -19,8 +19,19 @@ const DEFAULT_IMPORT_ALIASES: ReadonlyMap = new Map([ ['@emotion/css', null], ['styled-components', 'styled'], ['@vanilla-extract/css', null], + ['@vanilla-extract/css-utils', null], ]) +/** The package whose `calc` the build writes as the string it gives, as `vanilla_extract_calc` in `libs/extractor` compiles it */ +const CSS_UTILS = '@vanilla-extract/css-utils' + +/** The name `specifier` imports */ +function specifierName(specifier: TSESTree.ImportSpecifier): string { + return specifier.imported.type === AST_NODE_TYPES.Literal + ? specifier.imported.value + : specifier.imported.name +} + /** What the build is configured to read as Devup UI */ export interface ImportConfig { readonly package: string @@ -140,6 +151,7 @@ export interface StorageContext { export class ImportStorage { private imports = new Map() private importObject = new Set() + private calc = new Set() readonly vanilla: boolean private readonly config: ImportConfig @@ -159,6 +171,17 @@ export class ImportStorage { const source = node.source.value // A vanilla-extract stylesheet runs as it is: no import is compiled away if (this.vanilla) return + if (source === CSS_UTILS) { + // Turned off with `importAliases`, the build leaves `calc` to the package + if (!this.config.aliases.has(CSS_UTILS)) return + for (const specifier of node.specifiers) + if ( + specifier.type === AST_NODE_TYPES.ImportSpecifier && + specifierName(specifier) === 'calc' + ) + this.calc.add(specifier.local.name) + return + } const isDevup = source === this.config.package || source === `${this.config.package}/compat` @@ -168,10 +191,7 @@ export class ImportStorage { for (const specifier of node.specifiers) { switch (specifier.type) { case AST_NODE_TYPES.ImportSpecifier: { - const imported = - specifier.imported.type === AST_NODE_TYPES.Literal - ? specifier.imported.value - : specifier.imported.name + const imported = specifierName(specifier) const name = isDevup ? imported : devupEquivalent(source, imported) if (name !== undefined) this.addImport(specifier.local.name, name) break @@ -200,6 +220,11 @@ export class ImportStorage { return this.imports.get(local) } + /** Whether `local` binds the `calc` of `@vanilla-extract/css-utils`, whose calls the build writes as the string they give */ + public isCalc(local: string): boolean { + return this.calc.has(local) + } + /** Whether `local` is the package imported whole, as a namespace or default */ public isImportObject(local: string): boolean { return this.importObject.has(local) diff --git a/packages/next-plugin/src/__tests__/plugin.test.ts b/packages/next-plugin/src/__tests__/plugin.test.ts index e495fca8e..1df1b3168 100644 --- a/packages/next-plugin/src/__tests__/plugin.test.ts +++ b/packages/next-plugin/src/__tests__/plugin.test.ts @@ -752,6 +752,7 @@ describe('DevupUINextPlugin', () => { '@emotion/styled': 'styled', '@emotion/css': null, '@vanilla-extract/css': null, + '@vanilla-extract/css-utils': null, 'styled-components': 'styled', }, defaultSheet: { @@ -837,6 +838,7 @@ describe('DevupUINextPlugin', () => { '@emotion/styled': 'styled', '@emotion/css': null, '@vanilla-extract/css': null, + '@vanilla-extract/css-utils': null, 'styled-components': 'styled', }, watch: false, @@ -935,6 +937,7 @@ describe('DevupUINextPlugin', () => { '@emotion/styled': 'styled', '@emotion/css': null, '@vanilla-extract/css': null, + '@vanilla-extract/css-utils': null, 'styled-components': 'styled', }, defaultSheet: { @@ -989,6 +992,7 @@ describe('DevupUINextPlugin', () => { '@emotion/styled': 'styled', '@emotion/css': null, '@vanilla-extract/css': null, + '@vanilla-extract/css-utils': null, 'styled-components': 'styled', }, coordinatorPortFile: join('df', 'coordinator.port'), @@ -1348,6 +1352,7 @@ export const box = style({ color: 'red' })` '@emotion/styled': 'styled', '@emotion/css': null, '@vanilla-extract/css': null, + '@vanilla-extract/css-utils': null, 'styled-components': 'styled', }, coordinatorPortFile: join('df', 'coordinator.port'), diff --git a/packages/plugin-utils/src/__tests__/create-compat-types.test.ts b/packages/plugin-utils/src/__tests__/create-compat-types.test.ts index e796b6ada..d11107487 100644 --- a/packages/plugin-utils/src/__tests__/create-compat-types.test.ts +++ b/packages/plugin-utils/src/__tests__/create-compat-types.test.ts @@ -10,6 +10,7 @@ describe('createCompatTypes', () => { '/// ', '/// ', '/// ', + '/// ', ].join('\n') + '\n', ) }) @@ -22,6 +23,7 @@ describe('createCompatTypes', () => { '@emotion/styled': false, '@emotion/css': false, '@vanilla-extract/css': false, + '@vanilla-extract/css-utils': false, }), ), ).toBe( @@ -57,6 +59,7 @@ describe('createCompatTypes', () => { '/// ', '/// ', '/// ', + '/// ', ].join('\n') + '\n', ) }) diff --git a/packages/plugin-utils/src/__tests__/merge-import-aliases.test.ts b/packages/plugin-utils/src/__tests__/merge-import-aliases.test.ts index d7d6cf7e2..3f4cf1ea5 100644 --- a/packages/plugin-utils/src/__tests__/merge-import-aliases.test.ts +++ b/packages/plugin-utils/src/__tests__/merge-import-aliases.test.ts @@ -16,6 +16,7 @@ describe('mergeImportAliases', () => { '@emotion/css': null, 'styled-components': 'styled', '@vanilla-extract/css': null, + '@vanilla-extract/css-utils': null, }) }) @@ -30,6 +31,7 @@ describe('mergeImportAliases', () => { '@emotion/css': null, 'styled-components': 'styled', '@vanilla-extract/css': null, + '@vanilla-extract/css-utils': null, 'my-lib': 'customExport', }) }) @@ -66,6 +68,7 @@ describe('mergeImportAliases', () => { '@emotion/css': false, 'styled-components': false, '@vanilla-extract/css': false, + '@vanilla-extract/css-utils': false, }) expect(result).toEqual({}) @@ -91,6 +94,7 @@ describe('mergeImportAliases', () => { '@emotion/css': null, 'styled-components': 'styled', '@vanilla-extract/css': null, + '@vanilla-extract/css-utils': null, }) expect( mergeImportAliases({ '@emotion/react': false }, '@emotion/react'), @@ -115,6 +119,7 @@ describe('DEFAULT_IMPORT_ALIASES', () => { '@emotion/css': true, 'styled-components': 'styled', '@vanilla-extract/css': true, + '@vanilla-extract/css-utils': true, }) }) }) diff --git a/packages/plugin-utils/src/types.ts b/packages/plugin-utils/src/types.ts index bc8d5d65c..628716fe5 100644 --- a/packages/plugin-utils/src/types.ts +++ b/packages/plugin-utils/src/types.ts @@ -126,6 +126,7 @@ export const DEFAULT_IMPORT_ALIASES: ImportAliases = { '@emotion/css': true, 'styled-components': 'styled', '@vanilla-extract/css': true, + '@vanilla-extract/css-utils': true, } /** @@ -184,6 +185,7 @@ const COMPAT_TYPE_ENTRIES: Record = { '@emotion/styled': 'emotion', '@emotion/css': 'emotion', '@vanilla-extract/css': 'vanilla-extract', + '@vanilla-extract/css-utils': 'vanilla-extract-css-utils', 'styled-components': 'styled-components', } diff --git a/packages/react/package.json b/packages/react/package.json index 667038727..4ee7c5da4 100644 --- a/packages/react/package.json +++ b/packages/react/package.json @@ -61,6 +61,9 @@ "./compat/vanilla-extract": { "types": "./dist/compat/vanilla-extract.d.ts" }, + "./compat/vanilla-extract-css-utils": { + "types": "./dist/compat/vanilla-extract-css-utils.d.ts" + }, "./stylex": { "types": "./dist/utils/stylex.d.ts", "import": "./dist/utils/stylex.js", diff --git a/packages/react/src/compat/types.d.ts b/packages/react/src/compat/types.d.ts index 2736c2d77..177f4e0a5 100644 --- a/packages/react/src/compat/types.d.ts +++ b/packages/react/src/compat/types.d.ts @@ -26,3 +26,4 @@ /// /// /// +/// diff --git a/packages/react/src/compat/vanilla-extract-css-utils.d.ts b/packages/react/src/compat/vanilla-extract-css-utils.d.ts new file mode 100644 index 000000000..6f684bfe6 --- /dev/null +++ b/packages/react/src/compat/vanilla-extract-css-utils.d.ts @@ -0,0 +1,29 @@ +declare module '@vanilla-extract/css-utils' { + /** + * The build compiles `calc` to the string it gives: in a `.css.ts` + * stylesheet it is evaluated, elsewhere its operands must be literals or + * module-level constants holding one. + */ + type Operand = string | number | CalcChain + + /** What `calc(x)` builds, a CSS value once `toString()` is called */ + interface CalcChain { + add: (...operands: Operand[]) => CalcChain + subtract: (...operands: Operand[]) => CalcChain + multiply: (...operands: Operand[]) => CalcChain + divide: (...operands: Operand[]) => CalcChain + negate: () => CalcChain + toString: () => string + } + + interface Calc { + (x: Operand): CalcChain + add: (...operands: Operand[]) => string + subtract: (...operands: Operand[]) => string + multiply: (...operands: Operand[]) => string + divide: (...operands: Operand[]) => string + negate: (x: Operand) => string + } + + export const calc: Calc +} diff --git a/packages/react/type-tests/compat.tsx b/packages/react/type-tests/compat.tsx index fa15b975b..3a0304c8b 100644 --- a/packages/react/type-tests/compat.tsx +++ b/packages/react/type-tests/compat.tsx @@ -25,6 +25,7 @@ import { style, styleVariants, } from '@vanilla-extract/css' +import { calc } from '@vanilla-extract/css-utils' import styled, { createGlobalStyle, css as styledCss, @@ -174,6 +175,10 @@ export const family = fontFace({ src: 'url(font.woff2)' }) globalStyle('body', { margin: 0 }) globalFontFace('Inter', { src: 'url(font.woff2)' }) export const vanillaAnimation = vanillaKeyframes({ from: { opacity: 0 } }) +export const gutter: string = calc.add('1px', calc('2px').multiply(2)) +export const half: string = calc('100%').divide(2).negate().toString() +// @ts-expect-error `calc(x)` is a CSS value only once `toString()` is called +export const unfinished: string = calc('100%').divide(2) // @ts-expect-error the evaluator registers no `globalKeyframes` export { globalKeyframes } from '@vanilla-extract/css' diff --git a/packages/react/type-tests/tsconfig.json b/packages/react/type-tests/tsconfig.json index 063831d01..0ed02103d 100644 --- a/packages/react/type-tests/tsconfig.json +++ b/packages/react/type-tests/tsconfig.json @@ -18,6 +18,7 @@ "../src/compat/emotion.d.ts", "../src/compat/styled-components.d.ts", "../src/compat/vanilla-extract.d.ts", + "../src/compat/vanilla-extract-css-utils.d.ts", "../src/compat/stylex.d.ts" ], "include": ["*.ts", "*.tsx"] diff --git a/packages/vite-plugin/src/__tests__/plugin.test.ts b/packages/vite-plugin/src/__tests__/plugin.test.ts index 1a57ef539..3a59b67f2 100644 --- a/packages/vite-plugin/src/__tests__/plugin.test.ts +++ b/packages/vite-plugin/src/__tests__/plugin.test.ts @@ -612,6 +612,7 @@ describe('devupUIVitePlugin', () => { '@emotion/css': null, 'styled-components': 'styled', '@vanilla-extract/css': null, + '@vanilla-extract/css-utils': null, }, needles: expect.arrayContaining([ '@devup-ui/react', @@ -2281,6 +2282,7 @@ export const a =
` '@emotion/styled': 'styled', '@emotion/css': null, '@vanilla-extract/css': null, + '@vanilla-extract/css-utils': null, 'styled-components': 'styled', }, ) @@ -2300,6 +2302,7 @@ export const a =
` '@emotion/styled': 'styled', '@emotion/css': null, '@vanilla-extract/css': null, + '@vanilla-extract/css-utils': null, 'styled-components': 'styled', }, )