Merge branch 'main' into feat/ohos-support
This commit is contained in:
commit
ca9472d447
88 changed files with 9805 additions and 2667 deletions
4
.github/workflows/ci.yml
vendored
4
.github/workflows/ci.yml
vendored
|
|
@ -27,8 +27,10 @@ jobs:
|
|||
- name: Linux
|
||||
os: namespace-profile-default
|
||||
|
||||
# Playwright 1.62+ dropped WebKit support for macOS 14, and hangs
|
||||
# instead of failing when launching WebKit on a macos-14 runner.
|
||||
- name: macOS
|
||||
os: macos-14
|
||||
os: macos-15
|
||||
|
||||
# Exclude windows and macos from being built on feature branches
|
||||
run-all:
|
||||
|
|
|
|||
27
CHANGELOG.md
27
CHANGELOG.md
|
|
@ -7,7 +7,32 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||
|
||||
## [Unreleased]
|
||||
|
||||
- Nothing yet!
|
||||
### Added
|
||||
|
||||
- Add `@tailwindcss/turbopack` package to run Tailwind CSS with Next.js ([20367](https://github.com/tailwindlabs/tailwindcss/pull/20367))
|
||||
|
||||
### Fixed
|
||||
|
||||
- Ensure watch mode detects changes to symlinked `@source` files whose real paths aren't otherwise scanned ([#20356](https://github.com/tailwindlabs/tailwindcss/pull/20356))
|
||||
- Ensure custom variants using `@scope` wrap the generated utilities instead of nesting inside them ([#20369](https://github.com/tailwindlabs/tailwindcss/pull/20369))
|
||||
- Fix flattening of `@scope` at-rules ([#20369](https://github.com/tailwindlabs/tailwindcss/pull/20369))
|
||||
- Fix standalone declarations in `@scope`, wrap them in `:where(:scope)` ([#20369](https://github.com/tailwindlabs/tailwindcss/pull/20369))
|
||||
- Always emit a space for empty fallback values in CSS variables (e.g. `var(--tw-blur,)` → `var(--tw-blur, )`) ([#20373](https://github.com/tailwindlabs/tailwindcss/pull/20373))
|
||||
- Canonicalization: convert arbitrary breakpoint and container query variants to named equivalents (e.g. `max-[64rem]` → `max-lg`) ([#20380](https://github.com/tailwindlabs/tailwindcss/pull/20380))
|
||||
- Prevent `@tailwindcss/vite` from crashing on every edit under Vite's experimental `bundledDev` mode ([#20379](https://github.com/tailwindlabs/tailwindcss/pull/20379))
|
||||
- Ensure `@tailwindcss/oxide` falls back to WASM on platforms without native bindings ([#20383](https://github.com/tailwindlabs/tailwindcss/pull/20383))
|
||||
- Detect classes in Ruby percent literals using angle brackets or custom delimiters (e.g. `%w<flex>`, `%w|flex|`), including in Slim and Haml templates ([#20387](https://github.com/tailwindlabs/tailwindcss/pull/20387))
|
||||
- Preserve whitespace in `--default(…)` values in custom functional utilities (e.g. `--default(box alphabetic)` no longer becomes `boxalphabetic`) ([#20392](https://github.com/tailwindlabs/tailwindcss/pull/20392))
|
||||
- Don't scan gitignored directories (e.g. `node_modules` and `.git`) when the project uses a safelist-style `.gitignore` (e.g. `/*` followed by `!/…` negations) ([#20397](https://github.com/tailwindlabs/tailwindcss/pull/20397))
|
||||
- Ensure root `theme('…')` namespace lookups in JavaScript plugins and config files return the full namespace object instead of the value of its `DEFAULT` key ([#20399](https://github.com/tailwindlabs/tailwindcss/pull/20399))
|
||||
- Skip ignored directories entirely when computing watch globs (`scanner.globs`), instead of walking their full contents on every rebuild ([#20408](https://github.com/tailwindlabs/tailwindcss/pull/20408))
|
||||
- Oxide: drop invalid UTF-8 candidates ([#20389](https://github.com/tailwindlabs/tailwindcss/pull/20389))
|
||||
- `@tailwindcss/vite` no longer forces a full page reload for external files (e.g.: `.php` files) ([#20414](https://github.com/tailwindlabs/tailwindcss/issues/20414))
|
||||
- Canonicalization: don't merge utilities that reference different theme variables set to CSS-wide keywords like `unset` ([#20417](https://github.com/tailwindlabs/tailwindcss/pull/20417))
|
||||
- Don't generate utilities when a modifier is used that would otherwise be silently ignored (e.g. `rounded-sm/[5]`, `shadow-sm/foo`, `stroke-2/50`) ([#20419](https://github.com/tailwindlabs/tailwindcss/pull/20419))
|
||||
- Only normalize top-level `and`, `or`, and `not` keywords in `supports-[…]` variants (e.g. `selector(a: not (.foo))` → `selector(a:not(.foo))`) ([#20420](https://github.com/tailwindlabs/tailwindcss/pull/20420))
|
||||
- Don't warn about Angular's `::ng-deep` and `:host-context()` when optimizing CSS ([#20434](https://github.com/tailwindlabs/tailwindcss/pull/20434))
|
||||
- Don't generate CSS for candidates containing an empty additional modifier (e.g. `bg-red-500/50/` and `group-hover/foo//bar:flex`) ([#20466](https://github.com/tailwindlabs/tailwindcss/pull/20466))
|
||||
|
||||
## [4.3.3] - 2026-07-16
|
||||
|
||||
|
|
|
|||
128
Cargo.lock
generated
128
Cargo.lock
generated
|
|
@ -40,7 +40,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||
checksum = "531a9155a481e2ee699d4f98f43c0ca4ff8ee1bfd55c31e9e98fb29d2b176fe0"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
"regex-automata 0.4.8",
|
||||
"regex-automata 0.4.18",
|
||||
"serde",
|
||||
]
|
||||
|
||||
|
|
@ -59,6 +59,17 @@ dependencies = [
|
|||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "console"
|
||||
version = "0.16.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4fe5f465a4f6fee88fad41b85d990f84c835335e85b5d9e6e63e0d06d28cba7c"
|
||||
dependencies = [
|
||||
"encode_unicode",
|
||||
"libc",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "convert_case"
|
||||
version = "0.11.0"
|
||||
|
|
@ -104,19 +115,9 @@ checksum = "22ec99545bb0ed0ea7bb9b8e1e9122ea386ff8a48c0922e43f36d45ab09e0e80"
|
|||
|
||||
[[package]]
|
||||
name = "ctor"
|
||||
version = "0.10.1"
|
||||
version = "1.0.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "83cf0d42651b16c6dfe68685716d18480d18a9c39c62d76e8cf3eb6ed5d8bcbf"
|
||||
dependencies = [
|
||||
"ctor-proc-macro",
|
||||
"dtor",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ctor-proc-macro"
|
||||
version = "0.0.13"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7a949c44fcacbbbb7ada007dc7acb34603dd97cd47de5d054f2b6493ecebb483"
|
||||
checksum = "2d83cb7e7a873830708d6b02a78cd36a592c6fa14bf267b68725103b85c0d77f"
|
||||
|
||||
[[package]]
|
||||
name = "diff"
|
||||
|
|
@ -124,21 +125,6 @@ version = "0.1.13"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8"
|
||||
|
||||
[[package]]
|
||||
name = "dtor"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "edf234dd1594d6dd434a8fb8cada51ddbbc593e40e4a01556a0b31c62da2775b"
|
||||
dependencies = [
|
||||
"dtor-proc-macro",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dtor-proc-macro"
|
||||
version = "0.0.13"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2647271c92754afcb174e758003cfd1cbf1e43e5a7853d7b1813e63e19e39a73"
|
||||
|
||||
[[package]]
|
||||
name = "dunce"
|
||||
version = "1.0.5"
|
||||
|
|
@ -151,6 +137,12 @@ version = "1.8.1"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7fcaabb2fef8c910e7f4c7ce9f67a1283a1715879a7c230ca9d6d1ae31f16d91"
|
||||
|
||||
[[package]]
|
||||
name = "encode_unicode"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0"
|
||||
|
||||
[[package]]
|
||||
name = "errno"
|
||||
version = "0.3.9"
|
||||
|
|
@ -266,14 +258,14 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "globset"
|
||||
version = "0.4.17"
|
||||
version = "0.4.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eab69130804d941f8075cfd713bf8848a2c3b3f201a9457a11e6f87e1ab62305"
|
||||
checksum = "07c34a9410465b45bd9787443bc7370f37735bad04b0f0cd57ff1a3186c98988"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"bstr",
|
||||
"log",
|
||||
"regex-automata 0.4.8",
|
||||
"regex-automata 0.4.18",
|
||||
"regex-syntax 0.8.5",
|
||||
]
|
||||
|
||||
|
|
@ -298,7 +290,7 @@ dependencies = [
|
|||
"globset",
|
||||
"log",
|
||||
"memchr",
|
||||
"regex-automata 0.4.8",
|
||||
"regex-automata 0.4.18",
|
||||
"same-file",
|
||||
"walkdir",
|
||||
"winapi-util",
|
||||
|
|
@ -306,7 +298,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "ignore"
|
||||
version = "0.4.24"
|
||||
version = "0.4.33"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"crossbeam-channel",
|
||||
|
|
@ -315,12 +307,24 @@ dependencies = [
|
|||
"globset",
|
||||
"log",
|
||||
"memchr",
|
||||
"regex-automata 0.4.8",
|
||||
"regex-automata 0.4.18",
|
||||
"same-file",
|
||||
"walkdir",
|
||||
"winapi-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "insta"
|
||||
version = "1.48.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "86f0f8fee8c926415c58d6ae43a08523a26faccb2323f5e6b644fe7dd4ef6b82"
|
||||
dependencies = [
|
||||
"console",
|
||||
"once_cell",
|
||||
"similar",
|
||||
"tempfile",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itertools"
|
||||
version = "0.11.0"
|
||||
|
|
@ -387,9 +391,9 @@ checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
|
|||
|
||||
[[package]]
|
||||
name = "napi"
|
||||
version = "3.8.5"
|
||||
version = "3.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fa73b028610e2b26e9e40bd2c8ff8a98e6d7ed5d67d89ebf4bfd2f992616b024"
|
||||
checksum = "de33522036981030a75c231829566bc63414e08101a6f5ff4ac6cef19c8e0941"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"ctor",
|
||||
|
|
@ -402,15 +406,15 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "napi-build"
|
||||
version = "2.3.1"
|
||||
version = "2.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d376940fd5b723c6893cd1ee3f33abbfd86acb1cd1ec079f3ab04a2a3bc4d3b1"
|
||||
checksum = "c9c366d2c8c60b86fa632df75f745509b52f9128f91a6bad4c796e44abb505e1"
|
||||
|
||||
[[package]]
|
||||
name = "napi-derive"
|
||||
version = "3.5.4"
|
||||
version = "3.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7430702d3cc05cf55f0a2c9e41d991c3b7a53f91e6146a8f282b1bfc7f3fd133"
|
||||
checksum = "a49c513341a61a16a10af6efcce46b30d0822ba2d4fb197d24d33dfc199c78d5"
|
||||
dependencies = [
|
||||
"convert_case",
|
||||
"ctor",
|
||||
|
|
@ -422,9 +426,9 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "napi-derive-backend"
|
||||
version = "5.0.3"
|
||||
version = "6.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1ca5a083f2c9b49a0c7d33ec75c083498849c6fcc46f5497317faa39ea77f5d5"
|
||||
checksum = "d60b5d773ad46c698c8cc2cd9fde0b283d39cbb7f71c04bee633c7bdba4423bd"
|
||||
dependencies = [
|
||||
"convert_case",
|
||||
"proc-macro2",
|
||||
|
|
@ -435,9 +439,9 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "napi-sys"
|
||||
version = "3.2.1"
|
||||
version = "3.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8eb602b84d7c1edae45e50bbf1374696548f36ae179dfa667f577e384bb90c2b"
|
||||
checksum = "85fbf1fa9f1babfe396d74bbbf52b3643770243e8f5b0b46715d4caf7f0dfc9a"
|
||||
dependencies = [
|
||||
"libloading",
|
||||
]
|
||||
|
|
@ -470,9 +474,9 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.19.0"
|
||||
version = "1.21.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92"
|
||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||
|
||||
[[package]]
|
||||
name = "overload"
|
||||
|
|
@ -516,9 +520,9 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "rayon"
|
||||
version = "1.10.0"
|
||||
version = "1.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b418a60154510ca1a002a752ca9714984e21e4241e804d32555251faf8b78ffa"
|
||||
checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"
|
||||
dependencies = [
|
||||
"either",
|
||||
"rayon-core",
|
||||
|
|
@ -526,9 +530,9 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "rayon-core"
|
||||
version = "1.12.1"
|
||||
version = "1.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1465873a3dfdaa8ae7cb14b4383657caab0b3e8a0aa9ae8e04b044854c8dfce2"
|
||||
checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"
|
||||
dependencies = [
|
||||
"crossbeam-deque",
|
||||
"crossbeam-utils",
|
||||
|
|
@ -542,7 +546,7 @@ checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191"
|
|||
dependencies = [
|
||||
"aho-corasick",
|
||||
"memchr",
|
||||
"regex-automata 0.4.8",
|
||||
"regex-automata 0.4.18",
|
||||
"regex-syntax 0.8.5",
|
||||
]
|
||||
|
||||
|
|
@ -557,9 +561,9 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "regex-automata"
|
||||
version = "0.4.8"
|
||||
version = "0.4.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "368758f23274712b504848e9d5a6f010445cc8b87a7cdb4d7cbee666c1288da3"
|
||||
checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"memchr",
|
||||
|
|
@ -627,6 +631,12 @@ dependencies = [
|
|||
"lazy_static",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "similar"
|
||||
version = "2.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa"
|
||||
|
||||
[[package]]
|
||||
name = "slab"
|
||||
version = "0.4.12"
|
||||
|
|
@ -671,7 +681,8 @@ dependencies = [
|
|||
"dunce",
|
||||
"fast-glob",
|
||||
"globwalk",
|
||||
"ignore 0.4.24",
|
||||
"ignore 0.4.33",
|
||||
"insta",
|
||||
"log",
|
||||
"pretty_assertions",
|
||||
"rayon",
|
||||
|
|
@ -857,6 +868,15 @@ dependencies = [
|
|||
"windows-targets",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.61.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-targets"
|
||||
version = "0.52.6"
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "ignore"
|
||||
version = "0.4.24" #:version
|
||||
version = "0.4.33" #:version
|
||||
authors = ["Andrew Gallant <jamslam@gmail.com>"]
|
||||
description = """
|
||||
A fast library for efficiently matching ignore files such as `.gitignore`
|
||||
|
|
@ -12,7 +12,10 @@ repository = "https://github.com/BurntSushi/ripgrep/tree/master/crates/ignore"
|
|||
readme = "README.md"
|
||||
keywords = ["glob", "ignore", "gitignore", "pattern", "file"]
|
||||
license = "Unlicense OR MIT"
|
||||
# CHANGED: Use an explicit edition instead of `edition.workspace = true` since this crate is
|
||||
# vendored into the Tailwind CSS workspace.
|
||||
edition = "2024"
|
||||
rust-version = "1.88"
|
||||
|
||||
[lib]
|
||||
name = "ignore"
|
||||
|
|
@ -20,15 +23,17 @@ bench = false
|
|||
|
||||
[dependencies]
|
||||
crossbeam-deque = "0.8.3"
|
||||
globset = "0.4.17"
|
||||
# CHANGED: Use the published globset crate instead of a path dependency.
|
||||
globset = "0.4.20"
|
||||
log = "0.4.20"
|
||||
memchr = "2.6.3"
|
||||
same-file = "1.0.6"
|
||||
walkdir = "2.4.0"
|
||||
# CHANGED: Added `dunce` to canonicalize paths without UNC prefixes on Windows.
|
||||
dunce = "1.0.5"
|
||||
|
||||
[dependencies.regex-automata]
|
||||
version = "0.4.0"
|
||||
version = "0.4.18"
|
||||
default-features = false
|
||||
features = ["std", "perf", "syntax", "meta", "nfa", "hybrid", "dfa-onepass"]
|
||||
|
||||
|
|
|
|||
|
|
@ -18,9 +18,7 @@ fn main() {
|
|||
let stdout_thread = std::thread::spawn(move || {
|
||||
let mut stdout = std::io::BufWriter::new(std::io::stdout());
|
||||
for dent in rx {
|
||||
stdout
|
||||
.write_all(&Vec::from_path_lossy(dent.path()))
|
||||
.unwrap();
|
||||
stdout.write_all(&Vec::from_path_lossy(dent.path())).unwrap();
|
||||
stdout.write_all(b"\n").unwrap();
|
||||
}
|
||||
});
|
||||
|
|
|
|||
|
|
@ -47,6 +47,7 @@ pub(crate) const DEFAULT_TYPES: &[(&[&str], &[&str])] = &[
|
|||
(&["cml"], &["*.cml"]),
|
||||
(&["coffeescript"], &["*.coffee"]),
|
||||
(&["config"], &["*.cfg", "*.conf", "*.config", "*.ini"]),
|
||||
(&["container"], &["*Containerfile*", "*Dockerfile*"]),
|
||||
(&["coq"], &["*.v"]),
|
||||
(&["cpp"], &[
|
||||
"*.[ChH]", "*.cc", "*.[ch]pp", "*.[ch]xx", "*.hh", "*.inl",
|
||||
|
|
@ -109,6 +110,7 @@ pub(crate) const DEFAULT_TYPES: &[(&[&str], &[&str])] = &[
|
|||
(&["hbs"], &["*.hbs"]),
|
||||
(&["hs"], &["*.hs", "*.lhs"]),
|
||||
(&["html"], &["*.htm", "*.html", "*.ejs"]),
|
||||
(&["hurl"], &["*.hurl"]),
|
||||
(&["hy"], &["*.hy"]),
|
||||
(&["idris"], &["*.idr", "*.lidr"]),
|
||||
(&["janet"], &["*.janet"]),
|
||||
|
|
@ -185,6 +187,7 @@ pub(crate) const DEFAULT_TYPES: &[(&[&str], &[&str])] = &[
|
|||
(&["mint"], &["*.mint"]),
|
||||
(&["mk"], &["mkfile"]),
|
||||
(&["ml"], &["*.ml"]),
|
||||
(&["mojo"], &["*.mojo"]),
|
||||
(&["motoko"], &["*.mo"]),
|
||||
(&["msbuild"], &[
|
||||
"*.csproj", "*.fsproj", "*.vcxproj", "*.proj", "*.props", "*.targets",
|
||||
|
|
@ -206,11 +209,12 @@ pub(crate) const DEFAULT_TYPES: &[(&[&str], &[&str])] = &[
|
|||
"*.php", "*.php3", "*.php4", "*.php5", "*.php7", "*.php8",
|
||||
"*.pht", "*.phtml"
|
||||
]),
|
||||
(&["pkgbuild"], &["PKGBUILD"]),
|
||||
(&["po"], &["*.po"]),
|
||||
(&["pod"], &["*.pod"]),
|
||||
(&["postscript"], &["*.eps", "*.ps"]),
|
||||
(&["prolog"], &["*.pl", "*.pro", "*.prolog", "*.P"]),
|
||||
(&["protobuf"], &["*.proto"]),
|
||||
(&["proto", "protobuf"], &["*.proto"]),
|
||||
(&["ps"], &["*.cdxml", "*.ps1", "*.ps1xml", "*.psd1", "*.psm1"]),
|
||||
(&["puppet"], &["*.epp", "*.erb", "*.pp", "*.rb"]),
|
||||
(&["purs"], &["*.purs"]),
|
||||
|
|
@ -231,6 +235,7 @@ pub(crate) const DEFAULT_TYPES: &[(&[&str], &[&str])] = &[
|
|||
(&["red"], &["*.r", "*.red", "*.reds"]),
|
||||
(&["rescript"], &["*.res", "*.resi"]),
|
||||
(&["robot"], &["*.robot"]),
|
||||
(&["rocq"], &["*.v"]),
|
||||
(&["rst"], &["*.rst"]),
|
||||
(&["ruby"], &[
|
||||
// Idiomatic files
|
||||
|
|
@ -274,6 +279,7 @@ pub(crate) const DEFAULT_TYPES: &[(&[&str], &[&str])] = &[
|
|||
(&["spark"], &["*.spark"]),
|
||||
(&["spec"], &["*.spec"]),
|
||||
(&["sql"], &["*.sql", "*.psql"]),
|
||||
(&["ssa"], &["*.ssa"]),
|
||||
(&["stylus"], &["*.styl"]),
|
||||
(&["sv"], &["*.v", "*.vg", "*.sv", "*.svh", "*.h"]),
|
||||
(&["svelte"], &["*.svelte", "*.svelte.ts"]),
|
||||
|
|
@ -359,4 +365,14 @@ mod tests {
|
|||
previous_name = name;
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_types_aliases_are_sorted() {
|
||||
for (aliases, _) in DEFAULT_TYPES.iter() {
|
||||
assert!(
|
||||
aliases.is_sorted(),
|
||||
"this alias list is not sorted: {aliases:?}",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -102,7 +102,9 @@ impl Gitignore {
|
|||
///
|
||||
/// Note that I/O errors are ignored. For more granular control over
|
||||
/// errors, use `GitignoreBuilder`.
|
||||
pub fn new<P: AsRef<Path>>(gitignore_path: P) -> (Gitignore, Option<Error>) {
|
||||
pub fn new<P: AsRef<Path>>(
|
||||
gitignore_path: P,
|
||||
) -> (Gitignore, Option<Error>) {
|
||||
let path = gitignore_path.as_ref();
|
||||
let parent = path.parent().unwrap_or(Path::new("/"));
|
||||
let mut builder = GitignoreBuilder::new(parent);
|
||||
|
|
@ -123,6 +125,17 @@ impl Gitignore {
|
|||
/// The global config file path is specified by git's `core.excludesFile`
|
||||
/// config option.
|
||||
///
|
||||
/// # Behavior
|
||||
///
|
||||
/// This routine does its best to discover any global git exclude files.
|
||||
/// This will try to parse out the `excludesFile` config option in your
|
||||
/// global git configuration, if necessary.
|
||||
///
|
||||
/// The specific things this routine tries (which are subject to change
|
||||
/// based on how git behaves) are:
|
||||
///
|
||||
///
|
||||
///
|
||||
/// Git's config file location is `$HOME/.gitconfig`. If `$HOME/.gitconfig`
|
||||
/// does not exist or does not specify `core.excludesFile`, then
|
||||
/// `$XDG_CONFIG_HOME/git/ignore` is read. If `$XDG_CONFIG_HOME` is not
|
||||
|
|
@ -145,7 +158,8 @@ impl Gitignore {
|
|||
num_ignores: 0,
|
||||
num_whitelists: 0,
|
||||
matches: None,
|
||||
// CHANGED: Add a flag to have Gitignore rules that apply only to files.
|
||||
// CHANGED: Add a flag to have Gitignore rules that apply only to
|
||||
// files.
|
||||
only_on_files: false,
|
||||
}
|
||||
}
|
||||
|
|
@ -190,7 +204,11 @@ impl Gitignore {
|
|||
/// determined by a common suffix of the directory containing this
|
||||
/// gitignore) is stripped. If there is no common suffix/prefix overlap,
|
||||
/// then `path` is assumed to be relative to this matcher.
|
||||
pub fn matched<P: AsRef<Path>>(&self, path: P, is_dir: bool) -> Match<&Glob> {
|
||||
pub fn matched<P: AsRef<Path>>(
|
||||
&self,
|
||||
path: P,
|
||||
is_dir: bool,
|
||||
) -> Match<&Glob> {
|
||||
if self.is_empty() {
|
||||
return Match::None;
|
||||
}
|
||||
|
|
@ -243,11 +261,16 @@ impl Gitignore {
|
|||
}
|
||||
|
||||
/// Like matched, but takes a path that has already been stripped.
|
||||
fn matched_stripped<P: AsRef<Path>>(&self, path: P, is_dir: bool) -> Match<&Glob> {
|
||||
fn matched_stripped<P: AsRef<Path>>(
|
||||
&self,
|
||||
path: P,
|
||||
is_dir: bool,
|
||||
) -> Match<&Glob> {
|
||||
if self.is_empty() {
|
||||
return Match::None;
|
||||
}
|
||||
// CHANGED: Rules marked as only_on_files can not match against directories.
|
||||
// CHANGED: Rules marked as only_on_files can not match against
|
||||
// directories.
|
||||
if self.only_on_files && is_dir {
|
||||
return Match::None;
|
||||
}
|
||||
|
|
@ -270,7 +293,10 @@ impl Gitignore {
|
|||
|
||||
/// Strips the given path such that it's suitable for matching with this
|
||||
/// gitignore matcher.
|
||||
fn strip<'a, P: 'a + AsRef<Path> + ?Sized>(&'a self, path: &'a P) -> &'a Path {
|
||||
fn strip<'a, P: 'a + AsRef<Path> + ?Sized>(
|
||||
&'a self,
|
||||
path: &'a P,
|
||||
) -> &'a Path {
|
||||
let mut path = path.as_ref();
|
||||
// A leading ./ is completely superfluous. We also strip it from
|
||||
// our gitignore root path, so we need to strip it from our candidate
|
||||
|
|
@ -326,7 +352,8 @@ impl GitignoreBuilder {
|
|||
globs: vec![],
|
||||
case_insensitive: false,
|
||||
allow_unclosed_class: true,
|
||||
// CHANGED: Add a flag to have Gitignore rules that apply only to files.
|
||||
// CHANGED: Add a flag to have Gitignore rules that apply only to
|
||||
// files.
|
||||
only_on_files: false,
|
||||
}
|
||||
}
|
||||
|
|
@ -337,18 +364,21 @@ impl GitignoreBuilder {
|
|||
pub fn build(&self) -> Result<Gitignore, Error> {
|
||||
let nignore = self.globs.iter().filter(|g| !g.is_whitelist()).count();
|
||||
let nwhite = self.globs.iter().filter(|g| g.is_whitelist()).count();
|
||||
let set = self.builder.build().map_err(|err| Error::Glob {
|
||||
glob: None,
|
||||
err: err.to_string(),
|
||||
})?;
|
||||
let set = self
|
||||
.builder
|
||||
.build()
|
||||
.map_err(|err| Error::Glob { glob: None, err: err.to_string() })?;
|
||||
Ok(Gitignore {
|
||||
set,
|
||||
root: self.root.clone(),
|
||||
globs: self.globs.clone(),
|
||||
num_ignores: nignore as u64,
|
||||
num_whitelists: nwhite as u64,
|
||||
matches: Some(Arc::new(Pool::new(|| vec![]))),
|
||||
// CHANGED: Add a flag to have Gitignore rules that apply only to files.
|
||||
matches: Some(Arc::new(
|
||||
Pool::with_available_parallelism_capacity(|| vec![]),
|
||||
)),
|
||||
// CHANGED: Add a flag to have Gitignore rules that apply only to
|
||||
// files.
|
||||
only_on_files: self.only_on_files,
|
||||
})
|
||||
}
|
||||
|
|
@ -411,11 +441,8 @@ impl GitignoreBuilder {
|
|||
|
||||
// Match Git's handling of .gitignore files that begin with the Unicode BOM
|
||||
const UTF8_BOM: &str = "\u{feff}";
|
||||
let line = if i == 0 {
|
||||
line.trim_start_matches(UTF8_BOM)
|
||||
} else {
|
||||
&line
|
||||
};
|
||||
let line =
|
||||
if i == 0 { line.trim_start_matches(UTF8_BOM) } else { &line };
|
||||
|
||||
if let Err(err) = self.add_line(Some(path.to_path_buf()), &line) {
|
||||
errs.push(err.tagged(path, lineno));
|
||||
|
|
@ -537,7 +564,10 @@ impl GitignoreBuilder {
|
|||
/// affected.
|
||||
///
|
||||
/// This is disabled by default.
|
||||
pub fn case_insensitive(&mut self, yes: bool) -> Result<&mut GitignoreBuilder, Error> {
|
||||
pub fn case_insensitive(
|
||||
&mut self,
|
||||
yes: bool,
|
||||
) -> Result<&mut GitignoreBuilder, Error> {
|
||||
// TODO: This should not return a `Result`. Fix this in the next semver
|
||||
// release.
|
||||
self.case_insensitive = yes;
|
||||
|
|
@ -556,7 +586,10 @@ impl GitignoreBuilder {
|
|||
/// modes since the glob parser becomes more permissive. You might want to
|
||||
/// enable this when compatibility (e.g., with POSIX glob implementations)
|
||||
/// is more important than good error messages.
|
||||
pub fn allow_unclosed_class(&mut self, yes: bool) -> &mut GitignoreBuilder {
|
||||
pub fn allow_unclosed_class(
|
||||
&mut self,
|
||||
yes: bool,
|
||||
) -> &mut GitignoreBuilder {
|
||||
self.allow_unclosed_class = yes;
|
||||
self
|
||||
}
|
||||
|
|
@ -576,32 +609,56 @@ impl GitignoreBuilder {
|
|||
///
|
||||
/// Note that the file path returned may not exist.
|
||||
pub fn gitconfig_excludes_path() -> Option<PathBuf> {
|
||||
// git supports $HOME/.gitconfig and $XDG_CONFIG_HOME/git/config. Notably,
|
||||
// both can be active at the same time, where $HOME/.gitconfig takes
|
||||
// precedent. So if $HOME/.gitconfig defines a `core.excludesFile`, then
|
||||
// we're done.
|
||||
match gitconfig_home_contents().and_then(|x| parse_excludes_file(&x)) {
|
||||
Some(path) => return Some(path),
|
||||
None => {}
|
||||
// When GIT_CONFIG_GLOBAL is set, it replaces both $HOME/.gitconfig and
|
||||
// $XDG_CONFIG_HOME/git/config (per git 2.32+). Otherwise, git supports
|
||||
// $HOME/.gitconfig and $XDG_CONFIG_HOME/git/config simultaneously, where
|
||||
// $HOME/.gitconfig takes precedent.
|
||||
gitconfig_global_env_contents()
|
||||
.and_then(|x| parse_excludes_file(&x))
|
||||
.or_else(|| {
|
||||
gitconfig_home_contents().and_then(|x| parse_excludes_file(&x))
|
||||
})
|
||||
.or_else(|| {
|
||||
gitconfig_xdg_contents().and_then(|x| parse_excludes_file(&x))
|
||||
})
|
||||
// System-level config has the lowest priority for core.excludesFile.
|
||||
// GIT_CONFIG_SYSTEM overrides the default /etc/gitconfig path.
|
||||
.or_else(|| {
|
||||
gitconfig_system_contents().and_then(|x| parse_excludes_file(&x))
|
||||
})
|
||||
.or_else(excludes_file_default)
|
||||
}
|
||||
|
||||
/// Returns the file contents of git's global config file from the path
|
||||
/// specified by the `GIT_CONFIG_GLOBAL` environment variable.
|
||||
fn gitconfig_global_env_contents() -> Option<Vec<u8>> {
|
||||
let path = std::env::var_os("GIT_CONFIG_GLOBAL").map(PathBuf::from)?;
|
||||
if path.as_os_str().is_empty() {
|
||||
return None;
|
||||
}
|
||||
match gitconfig_xdg_contents().and_then(|x| parse_excludes_file(&x)) {
|
||||
Some(path) => return Some(path),
|
||||
None => {}
|
||||
}
|
||||
excludes_file_default()
|
||||
let mut file = BufReader::new(File::open(path).ok()?);
|
||||
let mut contents = vec![];
|
||||
file.read_to_end(&mut contents).ok().map(|_| contents)
|
||||
}
|
||||
|
||||
/// Returns the file contents of git's system-level config file.
|
||||
///
|
||||
/// Checks `GIT_CONFIG_SYSTEM` first, then falls back to `/etc/gitconfig`.
|
||||
fn gitconfig_system_contents() -> Option<Vec<u8>> {
|
||||
let path = std::env::var_os("GIT_CONFIG_SYSTEM")
|
||||
.map(PathBuf::from)
|
||||
.filter(|x| !x.as_os_str().is_empty())
|
||||
.unwrap_or_else(|| PathBuf::from("/etc/gitconfig"));
|
||||
let mut file = BufReader::new(File::open(path).ok()?);
|
||||
let mut contents = vec![];
|
||||
file.read_to_end(&mut contents).ok().map(|_| contents)
|
||||
}
|
||||
|
||||
/// Returns the file contents of git's global config file, if one exists, in
|
||||
/// the user's home directory.
|
||||
fn gitconfig_home_contents() -> Option<Vec<u8>> {
|
||||
let home = match home_dir() {
|
||||
None => return None,
|
||||
Some(home) => home,
|
||||
};
|
||||
let mut file = match File::open(home.join(".gitconfig")) {
|
||||
Err(_) => return None,
|
||||
Ok(file) => BufReader::new(file),
|
||||
};
|
||||
let home = home_dir()?;
|
||||
let mut file = BufReader::new(File::open(home.join(".gitconfig")).ok()?);
|
||||
let mut contents = vec![];
|
||||
file.read_to_end(&mut contents).ok().map(|_| contents)
|
||||
}
|
||||
|
|
@ -610,19 +667,11 @@ fn gitconfig_home_contents() -> Option<Vec<u8>> {
|
|||
/// the user's XDG_CONFIG_HOME directory.
|
||||
fn gitconfig_xdg_contents() -> Option<Vec<u8>> {
|
||||
let path = std::env::var_os("XDG_CONFIG_HOME")
|
||||
.and_then(|x| {
|
||||
if x.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(PathBuf::from(x))
|
||||
}
|
||||
})
|
||||
.map(PathBuf::from)
|
||||
.filter(|x| !x.as_os_str().is_empty())
|
||||
.or_else(|| home_dir().map(|p| p.join(".config")))
|
||||
.map(|x| x.join("git/config"));
|
||||
let mut file = match path.and_then(|p| File::open(p).ok()) {
|
||||
None => return None,
|
||||
Some(file) => BufReader::new(file),
|
||||
};
|
||||
.map(|x| x.join("git/config"))?;
|
||||
let mut file = BufReader::new(File::open(path).ok()?);
|
||||
let mut contents = vec![];
|
||||
file.read_to_end(&mut contents).ok().map(|_| contents)
|
||||
}
|
||||
|
|
@ -632,13 +681,8 @@ fn gitconfig_xdg_contents() -> Option<Vec<u8>> {
|
|||
/// Specifically, this respects XDG_CONFIG_HOME.
|
||||
fn excludes_file_default() -> Option<PathBuf> {
|
||||
std::env::var_os("XDG_CONFIG_HOME")
|
||||
.and_then(|x| {
|
||||
if x.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(PathBuf::from(x))
|
||||
}
|
||||
})
|
||||
.map(PathBuf::from)
|
||||
.filter(|x| !x.as_os_str().is_empty())
|
||||
.or_else(|| home_dir().map(|p| p.join(".config")))
|
||||
.map(|x| x.join("git/ignore"))
|
||||
}
|
||||
|
|
@ -667,9 +711,7 @@ fn parse_excludes_file(data: &[u8]) -> Option<PathBuf> {
|
|||
re.captures(data, &mut caps);
|
||||
let span = caps.get_group(1)?;
|
||||
let candidate = &data[span];
|
||||
std::str::from_utf8(candidate)
|
||||
.ok()
|
||||
.map(|s| PathBuf::from(expand_tilde(s)))
|
||||
std::str::from_utf8(candidate).ok().map(|s| PathBuf::from(expand_tilde(s)))
|
||||
}
|
||||
|
||||
/// Expands ~ in file paths to the value of $HOME.
|
||||
|
|
@ -831,7 +873,10 @@ mod tests {
|
|||
fn parse_excludes_file4() {
|
||||
let data = bytes("[core]\nexcludesFile = \"~/foo/bar\"");
|
||||
let got = super::parse_excludes_file(&data);
|
||||
assert_eq!(path_string(got.unwrap()), super::expand_tilde("~/foo/bar"));
|
||||
assert_eq!(
|
||||
path_string(got.unwrap()),
|
||||
super::expand_tilde("~/foo/bar")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
|
|||
1286
crates/ignore/src/incremental.rs
Normal file
1286
crates/ignore/src/incremental.rs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -48,13 +48,16 @@ See the documentation for `WalkBuilder` for many other options.
|
|||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub use crate::incremental::{IncrementalIgnore, IncrementalMatch};
|
||||
pub use crate::walk::{
|
||||
DirEntry, ParallelVisitor, ParallelVisitorBuilder, Walk, WalkBuilder, WalkParallel, WalkState,
|
||||
DirEntry, ParallelVisitor, ParallelVisitorBuilder, Walk, WalkBuilder,
|
||||
WalkParallel, WalkState,
|
||||
};
|
||||
|
||||
mod default_types;
|
||||
mod dir;
|
||||
pub mod gitignore;
|
||||
mod incremental;
|
||||
pub mod overrides;
|
||||
mod pathutil;
|
||||
pub mod types;
|
||||
|
|
@ -120,34 +123,31 @@ impl Clone for Error {
|
|||
fn clone(&self) -> Error {
|
||||
match *self {
|
||||
Error::Partial(ref errs) => Error::Partial(errs.clone()),
|
||||
Error::WithLineNumber { line, ref err } => Error::WithLineNumber {
|
||||
line,
|
||||
err: err.clone(),
|
||||
},
|
||||
Error::WithPath { ref path, ref err } => Error::WithPath {
|
||||
path: path.clone(),
|
||||
err: err.clone(),
|
||||
},
|
||||
Error::WithDepth { depth, ref err } => Error::WithDepth {
|
||||
depth,
|
||||
err: err.clone(),
|
||||
},
|
||||
Error::Loop {
|
||||
ref ancestor,
|
||||
ref child,
|
||||
} => Error::Loop {
|
||||
Error::WithLineNumber { line, ref err } => {
|
||||
Error::WithLineNumber { line, err: err.clone() }
|
||||
}
|
||||
Error::WithPath { ref path, ref err } => {
|
||||
Error::WithPath { path: path.clone(), err: err.clone() }
|
||||
}
|
||||
Error::WithDepth { depth, ref err } => {
|
||||
Error::WithDepth { depth, err: err.clone() }
|
||||
}
|
||||
Error::Loop { ref ancestor, ref child } => Error::Loop {
|
||||
ancestor: ancestor.clone(),
|
||||
child: child.clone(),
|
||||
},
|
||||
Error::Io(ref err) => match err.raw_os_error() {
|
||||
Some(e) => Error::Io(std::io::Error::from_raw_os_error(e)),
|
||||
None => Error::Io(std::io::Error::new(err.kind(), err.to_string())),
|
||||
None => {
|
||||
Error::Io(std::io::Error::new(err.kind(), err.to_string()))
|
||||
}
|
||||
},
|
||||
Error::Glob { ref glob, ref err } => Error::Glob {
|
||||
glob: glob.clone(),
|
||||
err: err.clone(),
|
||||
},
|
||||
Error::UnrecognizedFileType(ref err) => Error::UnrecognizedFileType(err.clone()),
|
||||
Error::Glob { ref glob, ref err } => {
|
||||
Error::Glob { glob: glob.clone(), err: err.clone() }
|
||||
}
|
||||
Error::UnrecognizedFileType(ref err) => {
|
||||
Error::UnrecognizedFileType(err.clone())
|
||||
}
|
||||
Error::InvalidDefinition => Error::InvalidDefinition,
|
||||
}
|
||||
}
|
||||
|
|
@ -269,19 +269,14 @@ impl Error {
|
|||
|
||||
/// Turn an error into a tagged error with the given depth.
|
||||
fn with_depth(self, depth: usize) -> Error {
|
||||
Error::WithDepth {
|
||||
depth,
|
||||
err: Box::new(self),
|
||||
}
|
||||
Error::WithDepth { depth, err: Box::new(self) }
|
||||
}
|
||||
|
||||
/// Turn an error into a tagged error with the given file path and line
|
||||
/// number. If path is empty, then it is omitted from the error.
|
||||
fn tagged<P: AsRef<Path>>(self, path: P, lineno: u64) -> Error {
|
||||
let errline = Error::WithLineNumber {
|
||||
line: lineno,
|
||||
err: Box::new(self),
|
||||
};
|
||||
let errline =
|
||||
Error::WithLineNumber { line: lineno, err: Box::new(self) };
|
||||
if path.as_ref().as_os_str().is_empty() {
|
||||
return errline;
|
||||
}
|
||||
|
|
@ -301,12 +296,12 @@ impl Error {
|
|||
};
|
||||
}
|
||||
let path = err.path().map(|p| p.to_path_buf());
|
||||
let mut ig_err = Error::Io(std::io::Error::from(err));
|
||||
let mut ig_err = Error::WithDepth {
|
||||
depth,
|
||||
err: Box::new(Error::Io(std::io::Error::from(err))),
|
||||
};
|
||||
if let Some(path) = path {
|
||||
ig_err = Error::WithPath {
|
||||
path,
|
||||
err: Box::new(ig_err),
|
||||
};
|
||||
ig_err = Error::WithPath { path, err: Box::new(ig_err) };
|
||||
}
|
||||
ig_err
|
||||
}
|
||||
|
|
@ -333,7 +328,8 @@ impl std::fmt::Display for Error {
|
|||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match *self {
|
||||
Error::Partial(ref errs) => {
|
||||
let msgs: Vec<String> = errs.iter().map(|err| err.to_string()).collect();
|
||||
let msgs: Vec<String> =
|
||||
errs.iter().map(|err| err.to_string()).collect();
|
||||
write!(f, "{}", msgs.join("\n"))
|
||||
}
|
||||
Error::WithLineNumber { line, ref err } => {
|
||||
|
|
@ -343,10 +339,7 @@ impl std::fmt::Display for Error {
|
|||
write!(f, "{}: {}", path.display(), err)
|
||||
}
|
||||
Error::WithDepth { ref err, .. } => err.fmt(f),
|
||||
Error::Loop {
|
||||
ref ancestor,
|
||||
ref child,
|
||||
} => write!(
|
||||
Error::Loop { ref ancestor, ref child } => write!(
|
||||
f,
|
||||
"File system loop found: \
|
||||
{} points to an ancestor {}",
|
||||
|
|
@ -354,14 +347,8 @@ impl std::fmt::Display for Error {
|
|||
ancestor.display()
|
||||
),
|
||||
Error::Io(ref err) => err.fmt(f),
|
||||
Error::Glob {
|
||||
glob: None,
|
||||
ref err,
|
||||
} => write!(f, "{}", err),
|
||||
Error::Glob {
|
||||
glob: Some(ref glob),
|
||||
ref err,
|
||||
} => {
|
||||
Error::Glob { glob: None, ref err } => write!(f, "{}", err),
|
||||
Error::Glob { glob: Some(ref glob), ref err } => {
|
||||
write!(f, "error parsing glob '{}': {}", glob, err)
|
||||
}
|
||||
Error::UnrecognizedFileType(ref ty) => {
|
||||
|
|
@ -507,7 +494,8 @@ mod tests {
|
|||
};
|
||||
|
||||
/// A convenient result type alias.
|
||||
pub(crate) type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;
|
||||
pub(crate) type Result<T> =
|
||||
std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;
|
||||
|
||||
macro_rules! err {
|
||||
($($tt:tt)*) => {
|
||||
|
|
@ -545,8 +533,9 @@ mod tests {
|
|||
if path.is_dir() {
|
||||
continue;
|
||||
}
|
||||
fs::create_dir_all(&path)
|
||||
.map_err(|e| err!("failed to create {}: {}", path.display(), e))?;
|
||||
fs::create_dir_all(&path).map_err(|e| {
|
||||
err!("failed to create {}: {}", path.display(), e)
|
||||
})?;
|
||||
return Ok(TempDir(path));
|
||||
}
|
||||
Err(err!("failed to create temp dir after {} tries", TRIES))
|
||||
|
|
|
|||
|
|
@ -94,7 +94,11 @@ impl Override {
|
|||
/// given) is stripped. If there is no common suffix/prefix overlap, then
|
||||
/// `path` is assumed to reside in the same directory as the root path for
|
||||
/// this set of overrides.
|
||||
pub fn matched<'a, P: AsRef<Path>>(&'a self, path: P, is_dir: bool) -> Match<Glob<'a>> {
|
||||
pub fn matched<'a, P: AsRef<Path>>(
|
||||
&'a self,
|
||||
path: P,
|
||||
is_dir: bool,
|
||||
) -> Match<Glob<'a>> {
|
||||
if self.is_empty() {
|
||||
return Match::None;
|
||||
}
|
||||
|
|
@ -146,7 +150,10 @@ impl OverrideBuilder {
|
|||
/// affected.
|
||||
///
|
||||
/// This is disabled by default.
|
||||
pub fn case_insensitive(&mut self, yes: bool) -> Result<&mut OverrideBuilder, Error> {
|
||||
pub fn case_insensitive(
|
||||
&mut self,
|
||||
yes: bool,
|
||||
) -> Result<&mut OverrideBuilder, Error> {
|
||||
// TODO: This should not return a `Result`. Fix this in the next semver
|
||||
// release.
|
||||
self.builder.case_insensitive(yes)?;
|
||||
|
|
@ -276,11 +283,8 @@ mod tests {
|
|||
|
||||
#[test]
|
||||
fn default_case_sensitive() {
|
||||
let ov = OverrideBuilder::new(ROOT)
|
||||
.add("*.html")
|
||||
.unwrap()
|
||||
.build()
|
||||
.unwrap();
|
||||
let ov =
|
||||
OverrideBuilder::new(ROOT).add("*.html").unwrap().build().unwrap();
|
||||
assert!(ov.matched("foo.html", false).is_whitelist());
|
||||
assert!(ov.matched("foo.HTML", false).is_ignore());
|
||||
assert!(ov.matched("foo.htm", false).is_ignore());
|
||||
|
|
|
|||
|
|
@ -2,55 +2,89 @@ use std::{ffi::OsStr, path::Path};
|
|||
|
||||
use crate::walk::DirEntry;
|
||||
|
||||
/// Returns true if and only if this entry is considered to be hidden.
|
||||
/// Returns true if and only if this path is considered to be hidden.
|
||||
///
|
||||
/// This only returns true if the base name of the path starts with a `.`.
|
||||
/// # Platform behavior
|
||||
///
|
||||
/// On Unix, this implements a more optimized check.
|
||||
#[cfg(unix)]
|
||||
pub(crate) fn is_hidden(dent: &DirEntry) -> bool {
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
|
||||
if let Some(name) = file_name(dent.path()) {
|
||||
name.as_bytes().get(0) == Some(&b'.')
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true if and only if this entry is considered to be hidden.
|
||||
/// ## Windows
|
||||
///
|
||||
/// On Windows, this returns true if one of the following is true:
|
||||
/// This returns true if one of the following is true:
|
||||
///
|
||||
/// * The base name of the path starts with a `.`.
|
||||
/// * The file attributes have the `HIDDEN` property set.
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn is_hidden(dent: &DirEntry) -> bool {
|
||||
use std::os::windows::fs::MetadataExt;
|
||||
use winapi_util::file;
|
||||
|
||||
// This looks like we're doing an extra stat call, but on Windows, the
|
||||
// directory traverser reuses the metadata retrieved from each directory
|
||||
// entry and stores it on the DirEntry itself. So this is "free."
|
||||
if let Ok(md) = dent.metadata() {
|
||||
if file::is_hidden(md.file_attributes() as u64) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if let Some(name) = file_name(dent.path()) {
|
||||
name.to_str().map(|s| s.starts_with(".")).unwrap_or(false)
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true if and only if this entry is considered to be hidden.
|
||||
///
|
||||
/// ## All other platforms
|
||||
///
|
||||
/// This only returns true if the base name of the path starts with a `.`.
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
pub(crate) fn is_hidden(dent: &DirEntry) -> bool {
|
||||
if let Some(name) = file_name(dent.path()) {
|
||||
name.to_str().map(|s| s.starts_with(".")).unwrap_or(false)
|
||||
pub(crate) fn is_hidden_path(dent: &Path) -> bool {
|
||||
#[cfg(not(windows))]
|
||||
fn imp(path: &Path) -> bool {
|
||||
is_hidden_path_only(path)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn imp(path: &Path) -> bool {
|
||||
use std::os::windows::fs::MetadataExt;
|
||||
use winapi_util::file;
|
||||
|
||||
if let Ok(md) = path.metadata() {
|
||||
if file::is_hidden(md.file_attributes() as u64) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
is_hidden_path_only(path)
|
||||
}
|
||||
|
||||
imp(dent)
|
||||
}
|
||||
|
||||
/// Returns true if and only if this directory entry is considered to be
|
||||
/// hidden.
|
||||
///
|
||||
/// # Platform behavior
|
||||
///
|
||||
/// ## Windows
|
||||
///
|
||||
/// This returns true if one of the following is true:
|
||||
///
|
||||
/// * The base name of the path starts with a `.`.
|
||||
/// * The file attributes have the `HIDDEN` property set.
|
||||
///
|
||||
/// ## All other platforms
|
||||
///
|
||||
/// This only returns true if the base name of the path starts with a `.`.
|
||||
pub(crate) fn is_hidden_entry(dent: &DirEntry) -> bool {
|
||||
#[cfg(not(windows))]
|
||||
fn imp(dent: &DirEntry) -> bool {
|
||||
is_hidden_path_only(dent.path())
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn imp(dent: &DirEntry) -> bool {
|
||||
use std::os::windows::fs::MetadataExt;
|
||||
use winapi_util::file;
|
||||
|
||||
// This looks like we're doing an extra stat call, but on Windows, the
|
||||
// directory traverser reuses the metadata retrieved from each directory
|
||||
// entry and stores it on the DirEntry itself. So this is "free."
|
||||
if let Ok(md) = dent.metadata() {
|
||||
if file::is_hidden(md.file_attributes() as u64) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
is_hidden_path_only(dent.path())
|
||||
}
|
||||
|
||||
imp(dent)
|
||||
}
|
||||
|
||||
/// Returns true if and only if this path is considered to be hidden from only
|
||||
/// the path itself.
|
||||
///
|
||||
/// This has the same behavior on all platforms.
|
||||
fn is_hidden_path_only(path: &Path) -> bool {
|
||||
if let Some(name) = file_name(path) {
|
||||
name.as_encoded_bytes().starts_with(b".")
|
||||
} else {
|
||||
false
|
||||
}
|
||||
|
|
@ -59,83 +93,79 @@ pub(crate) fn is_hidden(dent: &DirEntry) -> bool {
|
|||
/// Strip `prefix` from the `path` and return the remainder.
|
||||
///
|
||||
/// If `path` doesn't have a prefix `prefix`, then return `None`.
|
||||
#[cfg(unix)]
|
||||
pub(crate) fn strip_prefix<'a, P: AsRef<Path> + ?Sized>(
|
||||
prefix: &'a P,
|
||||
path: &'a Path,
|
||||
) -> Option<&'a Path> {
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
#[cfg(unix)]
|
||||
fn imp<'a>(prefix: &'a Path, path: &'a Path) -> Option<&'a Path> {
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
|
||||
let prefix = prefix.as_ref().as_os_str().as_bytes();
|
||||
let path = path.as_os_str().as_bytes();
|
||||
if prefix.len() > path.len() || prefix != &path[0..prefix.len()] {
|
||||
None
|
||||
} else {
|
||||
Some(&Path::new(OsStr::from_bytes(&path[prefix.len()..])))
|
||||
let prefix = prefix.as_os_str().as_bytes();
|
||||
let path = path.as_os_str().as_bytes();
|
||||
if prefix.len() > path.len() || prefix != &path[0..prefix.len()] {
|
||||
None
|
||||
} else {
|
||||
Some(&Path::new(OsStr::from_bytes(&path[prefix.len()..])))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Strip `prefix` from the `path` and return the remainder.
|
||||
///
|
||||
/// If `path` doesn't have a prefix `prefix`, then return `None`.
|
||||
#[cfg(not(unix))]
|
||||
pub(crate) fn strip_prefix<'a, P: AsRef<Path> + ?Sized>(
|
||||
prefix: &'a P,
|
||||
path: &'a Path,
|
||||
) -> Option<&'a Path> {
|
||||
path.strip_prefix(prefix).ok()
|
||||
#[cfg(not(unix))]
|
||||
fn imp<'a>(prefix: &'a Path, path: &'a Path) -> Option<&'a Path> {
|
||||
path.strip_prefix(prefix).ok()
|
||||
}
|
||||
|
||||
imp(prefix.as_ref(), path)
|
||||
}
|
||||
|
||||
/// Returns true if this file path is just a file name. i.e., Its parent is
|
||||
/// the empty string.
|
||||
#[cfg(unix)]
|
||||
pub(crate) fn is_file_name<P: AsRef<Path>>(path: P) -> bool {
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
|
||||
use memchr::memchr;
|
||||
|
||||
let path = path.as_ref().as_os_str().as_bytes();
|
||||
memchr(b'/', path).is_none()
|
||||
}
|
||||
|
||||
/// Returns true if this file path is just a file name. i.e., Its parent is
|
||||
/// the empty string.
|
||||
#[cfg(not(unix))]
|
||||
pub(crate) fn is_file_name<P: AsRef<Path>>(path: P) -> bool {
|
||||
path.as_ref()
|
||||
.parent()
|
||||
.map(|p| p.as_os_str().is_empty())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// The final component of the path, if it is a normal file.
|
||||
///
|
||||
/// If the path terminates in ., .., or consists solely of a root of prefix,
|
||||
/// file_name will return None.
|
||||
#[cfg(unix)]
|
||||
pub(crate) fn file_name<'a, P: AsRef<Path> + ?Sized>(path: &'a P) -> Option<&'a OsStr> {
|
||||
use memchr::memrchr;
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
|
||||
let path = path.as_ref().as_os_str().as_bytes();
|
||||
if path.is_empty() {
|
||||
return None;
|
||||
} else if path.len() == 1 && path[0] == b'.' {
|
||||
return None;
|
||||
} else if path.last() == Some(&b'.') {
|
||||
return None;
|
||||
} else if path.len() >= 2 && &path[path.len() - 2..] == &b".."[..] {
|
||||
return None;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
memchr::memchr(b'/', path.as_ref().as_os_str().as_encoded_bytes())
|
||||
.is_none()
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
path.as_ref()
|
||||
.parent()
|
||||
.map(|p| p.as_os_str().is_empty())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
let last_slash = memrchr(b'/', path).map(|i| i + 1).unwrap_or(0);
|
||||
Some(OsStr::from_bytes(&path[last_slash..]))
|
||||
}
|
||||
|
||||
/// The final component of the path, if it is a normal file.
|
||||
///
|
||||
/// If the path terminates in ., .., or consists solely of a root of prefix,
|
||||
/// file_name will return None.
|
||||
#[cfg(not(unix))]
|
||||
pub(crate) fn file_name<'a, P: AsRef<Path> + ?Sized>(path: &'a P) -> Option<&'a OsStr> {
|
||||
path.as_ref().file_name()
|
||||
/// If the path terminates in `.`, `..`, or consists solely of a root of
|
||||
/// prefix, this will return `None`.
|
||||
pub(crate) fn file_name<'a, P: AsRef<Path> + ?Sized>(
|
||||
path: &'a P,
|
||||
) -> Option<&'a OsStr> {
|
||||
#[cfg(unix)]
|
||||
fn imp(path: &Path) -> Option<&OsStr> {
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
|
||||
use memchr::memrchr;
|
||||
|
||||
let path = path.as_os_str().as_bytes();
|
||||
if path.is_empty() {
|
||||
return None;
|
||||
} else if path.len() == 1 && path[0] == b'.' {
|
||||
return None;
|
||||
} else if path.last() == Some(&b'.') {
|
||||
return None;
|
||||
} else if path.len() >= 2 && &path[path.len() - 2..] == &b".."[..] {
|
||||
return None;
|
||||
}
|
||||
let last_slash = memrchr(b'/', path).map(|i| i + 1).unwrap_or(0);
|
||||
Some(OsStr::from_bytes(&path[last_slash..]))
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn imp(path: &Path) -> Option<&OsStr> {
|
||||
path.file_name()
|
||||
}
|
||||
|
||||
imp(path.as_ref())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -204,8 +204,12 @@ impl<T> Selection<T> {
|
|||
|
||||
fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Selection<U> {
|
||||
match self {
|
||||
Selection::Select(name, inner) => Selection::Select(name, f(inner)),
|
||||
Selection::Negate(name, inner) => Selection::Negate(name, f(inner)),
|
||||
Selection::Select(name, inner) => {
|
||||
Selection::Select(name, f(inner))
|
||||
}
|
||||
Selection::Negate(name, inner) => {
|
||||
Selection::Negate(name, f(inner))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -227,7 +231,9 @@ impl Types {
|
|||
has_selected: false,
|
||||
glob_to_selection: vec![],
|
||||
set: GlobSetBuilder::new().build().unwrap(),
|
||||
matches: Arc::new(Pool::new(|| vec![])),
|
||||
matches: Arc::new(Pool::with_available_parallelism_capacity(
|
||||
|| vec![],
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -254,7 +260,11 @@ impl Types {
|
|||
/// The path is considered ignored if it matches a negated file type.
|
||||
/// If at least one file type is selected and `path` doesn't match, then
|
||||
/// the path is also considered ignored.
|
||||
pub fn matched<'a, P: AsRef<Path>>(&'a self, path: P, is_dir: bool) -> Match<Glob<'a>> {
|
||||
pub fn matched<'a, P: AsRef<Path>>(
|
||||
&'a self,
|
||||
path: P,
|
||||
is_dir: bool,
|
||||
) -> Match<Glob<'a>> {
|
||||
// File types don't apply to directories, and we can't do anything
|
||||
// if our glob set is empty.
|
||||
if is_dir || self.set.is_empty() {
|
||||
|
|
@ -306,10 +316,7 @@ impl TypesBuilder {
|
|||
/// of default type definitions can be added with `add_defaults`, and
|
||||
/// additional type definitions can be added with `select` and `negate`.
|
||||
pub fn new() -> TypesBuilder {
|
||||
TypesBuilder {
|
||||
types: HashMap::new(),
|
||||
selections: vec![],
|
||||
}
|
||||
TypesBuilder { types: HashMap::new(), selections: vec![] }
|
||||
}
|
||||
|
||||
/// Build the current set of file type definitions *and* selections into
|
||||
|
|
@ -343,17 +350,18 @@ impl TypesBuilder {
|
|||
}
|
||||
selections.push(selection.clone().map(move |_| def));
|
||||
}
|
||||
let set = build_set.build().map_err(|err| Error::Glob {
|
||||
glob: None,
|
||||
err: err.to_string(),
|
||||
})?;
|
||||
let set = build_set
|
||||
.build()
|
||||
.map_err(|err| Error::Glob { glob: None, err: err.to_string() })?;
|
||||
Ok(Types {
|
||||
defs,
|
||||
selections,
|
||||
has_selected,
|
||||
glob_to_selection,
|
||||
set,
|
||||
matches: Arc::new(Pool::new(|| vec![])),
|
||||
matches: Arc::new(Pool::with_available_parallelism_capacity(
|
||||
|| vec![],
|
||||
)),
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -377,12 +385,10 @@ impl TypesBuilder {
|
|||
pub fn select(&mut self, name: &str) -> &mut TypesBuilder {
|
||||
if name == "all" {
|
||||
for name in self.types.keys() {
|
||||
self.selections
|
||||
.push(Selection::Select(name.to_string(), ()));
|
||||
self.selections.push(Selection::Select(name.to_string(), ()));
|
||||
}
|
||||
} else {
|
||||
self.selections
|
||||
.push(Selection::Select(name.to_string(), ()));
|
||||
self.selections.push(Selection::Select(name.to_string(), ()));
|
||||
}
|
||||
self
|
||||
}
|
||||
|
|
@ -393,12 +399,10 @@ impl TypesBuilder {
|
|||
pub fn negate(&mut self, name: &str) -> &mut TypesBuilder {
|
||||
if name == "all" {
|
||||
for name in self.types.keys() {
|
||||
self.selections
|
||||
.push(Selection::Negate(name.to_string(), ()));
|
||||
self.selections.push(Selection::Negate(name.to_string(), ()));
|
||||
}
|
||||
} else {
|
||||
self.selections
|
||||
.push(Selection::Negate(name.to_string(), ()));
|
||||
self.selections.push(Selection::Negate(name.to_string(), ()));
|
||||
}
|
||||
self
|
||||
}
|
||||
|
|
@ -453,7 +457,10 @@ impl TypesBuilder {
|
|||
3 => {
|
||||
let name = parts[0];
|
||||
let types_string = parts[2];
|
||||
if name.is_empty() || parts[1] != "include" || types_string.is_empty() {
|
||||
if name.is_empty()
|
||||
|| parts[1] != "include"
|
||||
|| types_string.is_empty()
|
||||
{
|
||||
return Err(Error::InvalidDefinition);
|
||||
}
|
||||
let types = types_string.split(',');
|
||||
|
|
@ -463,7 +470,8 @@ impl TypesBuilder {
|
|||
return Err(Error::InvalidDefinition);
|
||||
}
|
||||
for type_name in types {
|
||||
let globs = self.types.get(type_name).unwrap().globs.clone();
|
||||
let globs =
|
||||
self.types.get(type_name).unwrap().globs.clone();
|
||||
for glob in globs {
|
||||
self.add(name, &glob)?;
|
||||
}
|
||||
|
|
@ -549,30 +557,9 @@ mod tests {
|
|||
|
||||
matched!(not, matchnot1, types(), vec!["rust"], vec![], "index.html");
|
||||
matched!(not, matchnot2, types(), vec![], vec!["rust"], "main.rs");
|
||||
matched!(
|
||||
not,
|
||||
matchnot3,
|
||||
types(),
|
||||
vec!["foo"],
|
||||
vec!["rust"],
|
||||
"main.rs"
|
||||
);
|
||||
matched!(
|
||||
not,
|
||||
matchnot4,
|
||||
types(),
|
||||
vec!["rust"],
|
||||
vec!["foo"],
|
||||
"main.rs"
|
||||
);
|
||||
matched!(
|
||||
not,
|
||||
matchnot5,
|
||||
types(),
|
||||
vec!["rust"],
|
||||
vec!["foo"],
|
||||
"main.foo"
|
||||
);
|
||||
matched!(not, matchnot3, types(), vec!["foo"], vec!["rust"], "main.rs");
|
||||
matched!(not, matchnot4, types(), vec!["rust"], vec!["foo"], "main.rs");
|
||||
matched!(not, matchnot5, types(), vec!["rust"], vec!["foo"], "main.foo");
|
||||
matched!(not, matchnot6, types(), vec!["combo"], vec![], "leftpad.js");
|
||||
matched!(not, matchnot7, types(), vec!["py"], vec![], "index.html");
|
||||
matched!(not, matchnot8, types(), vec!["python"], vec![], "doc.md");
|
||||
|
|
|
|||
|
|
@ -17,7 +17,9 @@ use {
|
|||
use crate::{
|
||||
Error, PartialErrorBuilder,
|
||||
dir::{Ignore, IgnoreBuilder},
|
||||
// CHANGED: Also import `Gitignore` for `WalkBuilder::add_gitignore`.
|
||||
gitignore::{Gitignore, GitignoreBuilder},
|
||||
incremental::{IncrementalIgnore, IncrementalIgnoreOptions},
|
||||
overrides::Override,
|
||||
types::Types,
|
||||
};
|
||||
|
|
@ -104,24 +106,15 @@ impl DirEntry {
|
|||
}
|
||||
|
||||
fn new_stdin() -> DirEntry {
|
||||
DirEntry {
|
||||
dent: DirEntryInner::Stdin,
|
||||
err: None,
|
||||
}
|
||||
DirEntry { dent: DirEntryInner::Stdin, err: None }
|
||||
}
|
||||
|
||||
fn new_walkdir(dent: walkdir::DirEntry, err: Option<Error>) -> DirEntry {
|
||||
DirEntry {
|
||||
dent: DirEntryInner::Walkdir(dent),
|
||||
err,
|
||||
}
|
||||
DirEntry { dent: DirEntryInner::Walkdir(dent), err }
|
||||
}
|
||||
|
||||
fn new_raw(dent: DirEntryRaw, err: Option<Error>) -> DirEntry {
|
||||
DirEntry {
|
||||
dent: DirEntryInner::Raw(dent),
|
||||
err,
|
||||
}
|
||||
DirEntry { dent: DirEntryInner::Raw(dent), err }
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -187,9 +180,11 @@ impl DirEntryInner {
|
|||
));
|
||||
Err(err.with_path("<stdin>"))
|
||||
}
|
||||
Walkdir(ref x) => x
|
||||
.metadata()
|
||||
.map_err(|err| Error::Io(io::Error::from(err)).with_path(x.path())),
|
||||
Walkdir(ref x) => x.metadata().map_err(|err| {
|
||||
Error::Io(io::Error::from(err))
|
||||
.with_depth(x.depth())
|
||||
.with_path(x.path())
|
||||
}),
|
||||
Raw(ref x) => x.metadata(),
|
||||
}
|
||||
}
|
||||
|
|
@ -308,7 +303,9 @@ impl DirEntryRaw {
|
|||
} else {
|
||||
fs::symlink_metadata(&self.path)
|
||||
}
|
||||
.map_err(|err| Error::Io(io::Error::from(err)).with_path(&self.path))
|
||||
.map_err(|err| {
|
||||
Error::Io(err).with_depth(self.depth).with_path(&self.path)
|
||||
})
|
||||
}
|
||||
|
||||
fn file_type(&self) -> FileType {
|
||||
|
|
@ -316,9 +313,7 @@ impl DirEntryRaw {
|
|||
}
|
||||
|
||||
fn file_name(&self) -> &OsStr {
|
||||
self.path
|
||||
.file_name()
|
||||
.unwrap_or_else(|| self.path.as_os_str())
|
||||
self.path.file_name().unwrap_or_else(|| self.path.as_os_str())
|
||||
}
|
||||
|
||||
fn depth(&self) -> usize {
|
||||
|
|
@ -330,13 +325,13 @@ impl DirEntryRaw {
|
|||
self.ino
|
||||
}
|
||||
|
||||
fn from_entry(depth: usize, ent: &fs::DirEntry) -> Result<DirEntryRaw, Error> {
|
||||
fn from_entry(
|
||||
depth: usize,
|
||||
ent: &fs::DirEntry,
|
||||
) -> Result<DirEntryRaw, Error> {
|
||||
let ty = ent.file_type().map_err(|err| {
|
||||
let err = Error::Io(io::Error::from(err)).with_path(ent.path());
|
||||
Error::WithDepth {
|
||||
depth,
|
||||
err: Box::new(err),
|
||||
}
|
||||
let err = Error::Io(err).with_depth(depth).with_path(ent.path());
|
||||
Error::WithDepth { depth, err: Box::new(err) }
|
||||
})?;
|
||||
DirEntryRaw::from_entry_os(depth, ent, ty)
|
||||
}
|
||||
|
|
@ -348,11 +343,8 @@ impl DirEntryRaw {
|
|||
ty: fs::FileType,
|
||||
) -> Result<DirEntryRaw, Error> {
|
||||
let md = ent.metadata().map_err(|err| {
|
||||
let err = Error::Io(io::Error::from(err)).with_path(ent.path());
|
||||
Error::WithDepth {
|
||||
depth,
|
||||
err: Box::new(err),
|
||||
}
|
||||
let err = Error::Io(err).with_depth(depth).with_path(ent.path());
|
||||
Error::WithDepth { depth, err: Box::new(err) }
|
||||
})?;
|
||||
Ok(DirEntryRaw {
|
||||
path: ent.path(),
|
||||
|
|
@ -395,8 +387,13 @@ impl DirEntryRaw {
|
|||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn from_path(depth: usize, pb: PathBuf, link: bool) -> Result<DirEntryRaw, Error> {
|
||||
let md = fs::metadata(&pb).map_err(|err| Error::Io(err).with_path(&pb))?;
|
||||
fn from_path(
|
||||
depth: usize,
|
||||
pb: PathBuf,
|
||||
link: bool,
|
||||
) -> Result<DirEntryRaw, Error> {
|
||||
let md = fs::metadata(&pb)
|
||||
.map_err(|err| Error::Io(err).with_depth(depth).with_path(&pb))?;
|
||||
Ok(DirEntryRaw {
|
||||
path: pb,
|
||||
ty: md.file_type(),
|
||||
|
|
@ -407,10 +404,15 @@ impl DirEntryRaw {
|
|||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn from_path(depth: usize, pb: PathBuf, link: bool) -> Result<DirEntryRaw, Error> {
|
||||
fn from_path(
|
||||
depth: usize,
|
||||
pb: PathBuf,
|
||||
link: bool,
|
||||
) -> Result<DirEntryRaw, Error> {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
|
||||
let md = fs::metadata(&pb).map_err(|err| Error::Io(err).with_path(&pb))?;
|
||||
let md = fs::metadata(&pb)
|
||||
.map_err(|err| Error::Io(err).with_depth(depth).with_path(&pb))?;
|
||||
Ok(DirEntryRaw {
|
||||
path: pb,
|
||||
ty: md.file_type(),
|
||||
|
|
@ -423,7 +425,11 @@ impl DirEntryRaw {
|
|||
// Placeholder implementation to allow compiling on non-standard platforms
|
||||
// (e.g. wasm32).
|
||||
#[cfg(not(any(windows, unix)))]
|
||||
fn from_path(depth: usize, pb: PathBuf, link: bool) -> Result<DirEntryRaw, Error> {
|
||||
fn from_path(
|
||||
depth: usize,
|
||||
pb: PathBuf,
|
||||
link: bool,
|
||||
) -> Result<DirEntryRaw, Error> {
|
||||
Err(Error::Io(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
"unsupported platform",
|
||||
|
|
@ -502,7 +508,8 @@ pub struct WalkBuilder {
|
|||
///
|
||||
/// When `None`, the CWD is fetched from `std::env::current_dir()`. If
|
||||
/// that fails, then global gitignores are ignored (an error is logged).
|
||||
global_gitignores_relative_to: OnceLock<Result<PathBuf, Arc<std::io::Error>>>,
|
||||
global_gitignores_relative_to:
|
||||
OnceLock<Result<PathBuf, Arc<std::io::Error>>>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
|
|
@ -544,8 +551,16 @@ impl WalkBuilder {
|
|||
/// is better to call `add` on this builder than to create multiple
|
||||
/// `Walk` values.
|
||||
pub fn new<P: AsRef<Path>>(path: P) -> WalkBuilder {
|
||||
WalkBuilder::from_iter([path])
|
||||
}
|
||||
|
||||
/// Create an empty builder to which paths can be added.
|
||||
///
|
||||
/// Note that if you call `build` on this instance before calling `add`
|
||||
/// on it, it will return exactly zero items during iteration.
|
||||
pub fn empty() -> WalkBuilder {
|
||||
WalkBuilder {
|
||||
paths: vec![path.as_ref().to_path_buf()],
|
||||
paths: vec![],
|
||||
ig_builder: IgnoreBuilder::new(),
|
||||
max_depth: None,
|
||||
min_depth: None,
|
||||
|
|
@ -560,6 +575,21 @@ impl WalkBuilder {
|
|||
}
|
||||
}
|
||||
|
||||
/// Create a new builder for a recursive directory iterator from the
|
||||
/// sequence of paths.
|
||||
///
|
||||
/// Note that if the iterator is empty, this is the same as
|
||||
/// `WalkBuilder::empty`.
|
||||
pub fn from_iter<P: AsRef<Path>, I: IntoIterator<Item = P>>(
|
||||
paths: I,
|
||||
) -> WalkBuilder {
|
||||
let mut builder = WalkBuilder::empty();
|
||||
for path in paths.into_iter() {
|
||||
builder.add(path);
|
||||
}
|
||||
builder
|
||||
}
|
||||
|
||||
/// Build a new `Walk` iterator.
|
||||
pub fn build(&self) -> Walk {
|
||||
let follow_links = self.follow_links;
|
||||
|
|
@ -585,10 +615,14 @@ impl WalkBuilder {
|
|||
if let Some(ref sorter) = sorter {
|
||||
match sorter.clone() {
|
||||
Sorter::ByName(cmp) => {
|
||||
wd = wd.sort_by(move |a, b| cmp(a.file_name(), b.file_name()));
|
||||
wd = wd.sort_by(move |a, b| {
|
||||
cmp(a.file_name(), b.file_name())
|
||||
});
|
||||
}
|
||||
Sorter::ByPath(cmp) => {
|
||||
wd = wd.sort_by(move |a, b| cmp(a.path(), b.path()));
|
||||
wd = wd.sort_by(move |a, b| {
|
||||
cmp(a.path(), b.path())
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -597,31 +631,76 @@ impl WalkBuilder {
|
|||
})
|
||||
.collect::<Vec<_>>()
|
||||
.into_iter();
|
||||
let ig_root = self
|
||||
.get_or_set_current_dir()
|
||||
.map(|cwd| self.ig_builder.build_with_cwd(Some(cwd.to_path_buf())))
|
||||
.unwrap_or_else(|| self.ig_builder.build());
|
||||
let ig_root = self.build_ignore();
|
||||
Walk {
|
||||
its,
|
||||
it: None,
|
||||
ig_root: ig_root.clone(),
|
||||
ig: ig_root.clone(),
|
||||
max_depth: self.max_depth,
|
||||
max_filesize: self.max_filesize,
|
||||
skip: self.skip.clone(),
|
||||
filter: self.filter.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Build matchers for checking paths against ignore files without
|
||||
/// recursively walking the configured roots.
|
||||
///
|
||||
/// The returned matchers use the path-based filtering configuration
|
||||
/// on this builder, including glob overrides, file type selections,
|
||||
/// parent ignore files, `.ignore`, `.gitignore`, global Git
|
||||
/// ignore files, explicitly added ignore files and custom ignore
|
||||
/// file names. For example, ripgrep configures `.rgignore` via
|
||||
/// [`WalkBuilder::add_custom_ignore_filename`]. Minimum and maximum depth
|
||||
/// limits, maximum file size and hidden-file filtering are also applied.
|
||||
/// Other options that only control traversal or require a directory entry,
|
||||
/// such as custom entry predicates, are not applied.
|
||||
///
|
||||
/// One matcher is returned for each configured path, in the same order as
|
||||
/// the paths were added to this builder. Each matcher accepts paths
|
||||
/// relative to its own [`IncrementalIgnore::root`]. The matcher for the
|
||||
/// special `-` path representing standard input always returns a non-match
|
||||
/// for all inputs.
|
||||
///
|
||||
/// Ignore matchers are loaded lazily and cached by directory.
|
||||
/// Thus, the first query may read ignore files from the root and
|
||||
/// its parents, while later queries reuse the compiled matchers.
|
||||
/// Errors encountered while loading ignore files are returned by
|
||||
/// [`IncrementalIgnore::matched_with_errors`]. Once an ignore file has
|
||||
/// been loaded, changes to it are not observed. Build new matchers to
|
||||
/// reload changed ignore files.
|
||||
///
|
||||
/// Matchers built together share the builder's base ignore configuration
|
||||
/// and compiled parent matchers.
|
||||
pub fn build_matchers(&self) -> Vec<IncrementalIgnore> {
|
||||
let ignore = self.build_ignore();
|
||||
let options = IncrementalIgnoreOptions {
|
||||
min_depth: self.min_depth,
|
||||
max_depth: self.max_depth,
|
||||
max_filesize: self.max_filesize,
|
||||
hidden: self.ig_builder.is_hidden(),
|
||||
follow_links: self.follow_links,
|
||||
};
|
||||
self.paths
|
||||
.iter()
|
||||
.map(move |path| {
|
||||
IncrementalIgnore::new(
|
||||
path.clone(),
|
||||
ignore.clone(),
|
||||
options.clone(),
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Build a new `WalkParallel` iterator.
|
||||
///
|
||||
/// Note that this *doesn't* return something that implements `Iterator`.
|
||||
/// Instead, the returned value must be run with a closure. e.g.,
|
||||
/// `builder.build_parallel().run(|| |path| { println!("{path:?}"); WalkState::Continue })`.
|
||||
pub fn build_parallel(&self) -> WalkParallel {
|
||||
let ig_root = self
|
||||
.get_or_set_current_dir()
|
||||
.map(|cwd| self.ig_builder.build_with_cwd(Some(cwd.to_path_buf())))
|
||||
.unwrap_or_else(|| self.ig_builder.build());
|
||||
let ig_root = self.build_ignore();
|
||||
WalkParallel {
|
||||
paths: self.paths.clone().into_iter(),
|
||||
ig_root,
|
||||
|
|
@ -651,7 +730,10 @@ impl WalkBuilder {
|
|||
/// The default, `None`, imposes no depth restriction.
|
||||
pub fn max_depth(&mut self, depth: Option<usize>) -> &mut WalkBuilder {
|
||||
self.max_depth = depth;
|
||||
if self.min_depth.is_some() && self.max_depth.is_some() && self.max_depth < self.min_depth {
|
||||
if self.min_depth.is_some()
|
||||
&& self.max_depth.is_some()
|
||||
&& self.max_depth < self.min_depth
|
||||
{
|
||||
self.max_depth = self.min_depth;
|
||||
}
|
||||
self
|
||||
|
|
@ -662,7 +744,10 @@ impl WalkBuilder {
|
|||
/// The default, `None`, imposes no minimum depth restriction.
|
||||
pub fn min_depth(&mut self, depth: Option<usize>) -> &mut WalkBuilder {
|
||||
self.min_depth = depth;
|
||||
if self.max_depth.is_some() && self.min_depth.is_some() && self.min_depth > self.max_depth {
|
||||
if self.max_depth.is_some()
|
||||
&& self.min_depth.is_some()
|
||||
&& self.min_depth > self.max_depth
|
||||
{
|
||||
self.min_depth = self.max_depth;
|
||||
}
|
||||
self
|
||||
|
|
@ -705,7 +790,12 @@ impl WalkBuilder {
|
|||
/// An error will also occur if this walker could not get the current
|
||||
/// working directory (and `WalkBuilder::current_dir` isn't set).
|
||||
pub fn add_ignore<P: AsRef<Path>>(&mut self, path: P) -> Option<Error> {
|
||||
// CHANGED: Dropped this code
|
||||
// CHANGED: Root the ignore file at `""` instead of the current working
|
||||
// directory. Explicit ignores are scoped to the directory of the
|
||||
// ignore file (see `matched_ignore`), and a root of `""` makes the
|
||||
// rules apply to every walked path regardless of the walk root. This
|
||||
// also avoids depending on the current working directory entirely.
|
||||
//
|
||||
// let path = path.as_ref();
|
||||
// let Some(cwd) = self.get_or_set_current_dir() else {
|
||||
// let err = std::io::Error::other(format!(
|
||||
|
|
@ -729,7 +819,11 @@ impl WalkBuilder {
|
|||
errs.into_error_option()
|
||||
}
|
||||
|
||||
/// CHANGED: Add a Gitignore to the builder.
|
||||
/// CHANGED: Add a prebuilt Gitignore to the builder.
|
||||
///
|
||||
/// Like the ignore file added via `add_ignore`, these rules are matched
|
||||
/// against the full path of each walked entry, scoped to the `Gitignore`'s
|
||||
/// root path.
|
||||
pub fn add_gitignore(&mut self, gi: Gitignore) {
|
||||
self.ig_builder.add_ignore(gi);
|
||||
}
|
||||
|
|
@ -982,7 +1076,10 @@ impl WalkBuilder {
|
|||
///
|
||||
/// Global gitignore files come from things like a user's git configuration
|
||||
/// or from gitignore files added via [`WalkBuilder::add_ignore`].
|
||||
pub fn current_dir(&mut self, cwd: impl Into<PathBuf>) -> &mut WalkBuilder {
|
||||
pub fn current_dir(
|
||||
&mut self,
|
||||
cwd: impl Into<PathBuf>,
|
||||
) -> &mut WalkBuilder {
|
||||
let cwd = cwd.into();
|
||||
self.ig_builder.current_dir(cwd.clone());
|
||||
if let Err(cwd) = self.global_gitignores_relative_to.set(Ok(cwd)) {
|
||||
|
|
@ -1002,7 +1099,10 @@ impl WalkBuilder {
|
|||
let result = std::env::current_dir().map_err(Arc::new);
|
||||
match result {
|
||||
Ok(ref path) => {
|
||||
log::trace!("automatically discovered CWD: {}", path.display());
|
||||
log::trace!(
|
||||
"automatically discovered CWD: {}",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
Err(ref err) => {
|
||||
log::debug!(
|
||||
|
|
@ -1016,6 +1116,13 @@ impl WalkBuilder {
|
|||
});
|
||||
result.as_ref().ok().map(|path| &**path)
|
||||
}
|
||||
|
||||
/// Build the root ignore matcher shared by all consumers of this builder.
|
||||
fn build_ignore(&self) -> Ignore {
|
||||
self.get_or_set_current_dir()
|
||||
.map(|cwd| self.ig_builder.build_with_cwd(Some(cwd.to_path_buf())))
|
||||
.unwrap_or_else(|| self.ig_builder.build())
|
||||
}
|
||||
}
|
||||
|
||||
/// Walk is a recursive directory iterator over file paths in one or more
|
||||
|
|
@ -1029,6 +1136,7 @@ pub struct Walk {
|
|||
it: Option<WalkEventIter>,
|
||||
ig_root: Ignore,
|
||||
ig: Ignore,
|
||||
max_depth: Option<usize>,
|
||||
max_filesize: Option<u64>,
|
||||
skip: Option<Arc<Handle>>,
|
||||
filter: Option<Filter>,
|
||||
|
|
@ -1044,6 +1152,17 @@ impl Walk {
|
|||
WalkBuilder::new(path).build()
|
||||
}
|
||||
|
||||
/// Create a new recursive directory iterator from the sequence of paths
|
||||
/// given.
|
||||
///
|
||||
/// Note that if the provided iterator is empty, then `Walk` is guaranteed
|
||||
/// to yield zero entries.
|
||||
pub fn from_iter<P: AsRef<Path>, I: IntoIterator<Item = P>>(
|
||||
paths: I,
|
||||
) -> Walk {
|
||||
WalkBuilder::from_iter(paths).build()
|
||||
}
|
||||
|
||||
fn skip_entry(&self, ent: &DirEntry) -> Result<bool, Error> {
|
||||
if ent.depth() == 0 {
|
||||
return Ok(false);
|
||||
|
|
@ -1128,12 +1247,17 @@ impl Iterator for Walk {
|
|||
self.it.as_mut().unwrap().it.skip_current_dir();
|
||||
// Still need to push this on the stack because
|
||||
// we'll get a WalkEvent::Exit event for this dir.
|
||||
// We don't care if it errors though.
|
||||
let (igtmp, _) = self.ig.add_child(ent.path());
|
||||
// Its ignore files cannot apply to any visited entry.
|
||||
let (igtmp, _) =
|
||||
self.ig.add_child_with_entries(ent.path(), &[]);
|
||||
self.ig = igtmp;
|
||||
continue;
|
||||
}
|
||||
let (igtmp, err) = self.ig.add_child(ent.path());
|
||||
let (igtmp, err) = if self.max_depth == Some(ent.depth()) {
|
||||
self.ig.add_child_with_entries(ent.path(), &[])
|
||||
} else {
|
||||
self.ig.add_child(ent.path())
|
||||
};
|
||||
self.ig = igtmp;
|
||||
ent.err = err;
|
||||
return Some(Ok(ent));
|
||||
|
|
@ -1175,11 +1299,7 @@ enum WalkEvent {
|
|||
|
||||
impl From<WalkDir> for WalkEventIter {
|
||||
fn from(it: WalkDir) -> WalkEventIter {
|
||||
WalkEventIter {
|
||||
depth: 0,
|
||||
it: it.into_iter(),
|
||||
next: None,
|
||||
}
|
||||
WalkEventIter { depth: 0, it: it.into_iter(), next: None }
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1252,7 +1372,9 @@ pub trait ParallelVisitorBuilder<'s> {
|
|||
fn build(&mut self) -> Box<dyn ParallelVisitor + 's>;
|
||||
}
|
||||
|
||||
impl<'a, 's, P: ParallelVisitorBuilder<'s>> ParallelVisitorBuilder<'s> for &'a mut P {
|
||||
impl<'a, 's, P: ParallelVisitorBuilder<'s>> ParallelVisitorBuilder<'s>
|
||||
for &'a mut P
|
||||
{
|
||||
fn build(&mut self) -> Box<dyn ParallelVisitor + 's> {
|
||||
(**self).build()
|
||||
}
|
||||
|
|
@ -1273,14 +1395,17 @@ struct FnBuilder<F> {
|
|||
builder: F,
|
||||
}
|
||||
|
||||
impl<'s, F: FnMut() -> FnVisitor<'s>> ParallelVisitorBuilder<'s> for FnBuilder<F> {
|
||||
impl<'s, F: FnMut() -> FnVisitor<'s>> ParallelVisitorBuilder<'s>
|
||||
for FnBuilder<F>
|
||||
{
|
||||
fn build(&mut self) -> Box<dyn ParallelVisitor + 's> {
|
||||
let visitor = (self.builder)();
|
||||
Box::new(FnVisitorImp { visitor })
|
||||
}
|
||||
}
|
||||
|
||||
type FnVisitor<'s> = Box<dyn FnMut(Result<DirEntry, Error>) -> WalkState + Send + 's>;
|
||||
type FnVisitor<'s> =
|
||||
Box<dyn FnMut(Result<DirEntry, Error>) -> WalkState + Send + 's>;
|
||||
|
||||
struct FnVisitorImp<'s> {
|
||||
visitor: FnVisitor<'s>,
|
||||
|
|
@ -1370,7 +1495,9 @@ impl WalkParallel {
|
|||
}
|
||||
};
|
||||
match DirEntryRaw::from_path(0, path, false) {
|
||||
Ok(dent) => (DirEntry::new_raw(dent, None), root_device),
|
||||
Ok(dent) => {
|
||||
(DirEntry::new_raw(dent, None), root_device)
|
||||
}
|
||||
Err(err) => {
|
||||
if visitor.visit(Err(err)).is_quit() {
|
||||
return;
|
||||
|
|
@ -1394,21 +1521,28 @@ impl WalkParallel {
|
|||
let quit_now = Arc::new(AtomicBool::new(false));
|
||||
let active_workers = Arc::new(AtomicUsize::new(threads));
|
||||
let stacks = Stack::new_for_each_thread(threads, stack);
|
||||
// Collect all of the workers first. In the case that
|
||||
// `builder.build()` panics, we want that to happen and
|
||||
// propagate before we actually start to run any of the
|
||||
// workers.
|
||||
let workers: Vec<_> = stacks
|
||||
.into_iter()
|
||||
.map(|stack| Worker {
|
||||
visitor: builder.build(),
|
||||
stack,
|
||||
quit_now: quit_now.clone(),
|
||||
active_workers: active_workers.clone(),
|
||||
max_depth: self.max_depth,
|
||||
min_depth: self.min_depth,
|
||||
max_filesize: self.max_filesize,
|
||||
follow_links: self.follow_links,
|
||||
skip: self.skip.clone(),
|
||||
filter: self.filter.clone(),
|
||||
})
|
||||
.collect();
|
||||
std::thread::scope(|s| {
|
||||
let handles: Vec<_> = stacks
|
||||
let handles: Vec<_> = workers
|
||||
.into_iter()
|
||||
.map(|stack| Worker {
|
||||
visitor: builder.build(),
|
||||
stack,
|
||||
quit_now: quit_now.clone(),
|
||||
active_workers: active_workers.clone(),
|
||||
max_depth: self.max_depth,
|
||||
min_depth: self.min_depth,
|
||||
max_filesize: self.max_filesize,
|
||||
follow_links: self.follow_links,
|
||||
skip: self.skip.clone(),
|
||||
filter: self.filter.clone(),
|
||||
})
|
||||
.map(|worker| s.spawn(|| worker.run()))
|
||||
.collect();
|
||||
for handle in handles {
|
||||
|
|
@ -1419,9 +1553,7 @@ impl WalkParallel {
|
|||
|
||||
fn threads(&self) -> usize {
|
||||
if self.threads == 0 {
|
||||
std::thread::available_parallelism()
|
||||
.map_or(1, |n| n.get())
|
||||
.min(12)
|
||||
std::thread::available_parallelism().map_or(1, |n| n.get()).min(12)
|
||||
} else {
|
||||
self.threads
|
||||
}
|
||||
|
|
@ -1452,6 +1584,12 @@ struct Work {
|
|||
root_device: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ReadDirResult {
|
||||
entries: Vec<fs::DirEntry>,
|
||||
errors: Vec<Error>,
|
||||
}
|
||||
|
||||
impl Work {
|
||||
/// Returns true if and only if this work item is a directory.
|
||||
fn is_dir(&self) -> bool {
|
||||
|
|
@ -1478,6 +1616,13 @@ impl Work {
|
|||
err
|
||||
}
|
||||
|
||||
/// Adds ignore rules for this directory without reading its contents.
|
||||
fn add_ignore(&mut self) {
|
||||
let (ig, err) = self.ignore.add_child(self.dent.path());
|
||||
self.ignore = ig;
|
||||
self.dent.err = err;
|
||||
}
|
||||
|
||||
/// Reads the directory contents of this work item and adds ignore
|
||||
/// rules for this directory.
|
||||
///
|
||||
|
|
@ -1485,7 +1630,7 @@ impl Work {
|
|||
/// an error is returned. If there was a problem reading the ignore
|
||||
/// rules for this directory, then the error is attached to this
|
||||
/// work item's directory entry.
|
||||
fn read_dir(&mut self) -> Result<fs::ReadDir, Error> {
|
||||
fn read_dir(&mut self) -> Result<ReadDirResult, Error> {
|
||||
let readdir = match fs::read_dir(self.dent.path()) {
|
||||
Ok(readdir) => readdir,
|
||||
Err(err) => {
|
||||
|
|
@ -1495,10 +1640,24 @@ impl Work {
|
|||
return Err(err);
|
||||
}
|
||||
};
|
||||
let (ig, err) = self.ignore.add_child(self.dent.path());
|
||||
// Actually descend into the directory and read its contents
|
||||
let mut result = ReadDirResult::default();
|
||||
for entry in readdir {
|
||||
match entry {
|
||||
Ok(entry) => result.entries.push(entry),
|
||||
Err(err) => result.errors.push(
|
||||
Error::from(err)
|
||||
.with_path(self.dent.path())
|
||||
.with_depth(self.dent.depth() + 1),
|
||||
),
|
||||
}
|
||||
}
|
||||
let (ig, err) = self
|
||||
.ignore
|
||||
.add_child_with_entries(self.dent.path(), &result.entries);
|
||||
self.ignore = ig;
|
||||
self.dent.err = err;
|
||||
Ok(readdir)
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1522,11 +1681,11 @@ impl Stack {
|
|||
// breadth-first. We do depth-first because a breadth first traversal
|
||||
// on wide directories with a lot of gitignores is disastrous (for
|
||||
// example, searching a directory tree containing all of crates.io).
|
||||
let deques: Vec<Deque<Message>> = std::iter::repeat_with(Deque::new_lifo)
|
||||
.take(threads)
|
||||
.collect();
|
||||
let stealers =
|
||||
Arc::<[Stealer<Message>]>::from(deques.iter().map(Deque::stealer).collect::<Vec<_>>());
|
||||
let deques: Vec<Deque<Message>> =
|
||||
std::iter::repeat_with(Deque::new_lifo).take(threads).collect();
|
||||
let stealers = Arc::<[Stealer<Message>]>::from(
|
||||
deques.iter().map(Deque::stealer).collect::<Vec<_>>(),
|
||||
);
|
||||
let stacks: Vec<Stack> = deques
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
|
|
@ -1668,8 +1827,13 @@ impl<'s> Worker<'s> {
|
|||
// have sufficient read permissions to list the directory.
|
||||
// In that case we still want to provide the closure with a valid
|
||||
// entry before passing the error value.
|
||||
let readdir = work.read_dir();
|
||||
let depth = work.dent.depth();
|
||||
let readdir = if descend && self.max_depth.is_none_or(|m| depth < m) {
|
||||
Some(work.read_dir())
|
||||
} else {
|
||||
work.add_ignore();
|
||||
None
|
||||
};
|
||||
if should_visit {
|
||||
let state = self.visitor.visit(Ok(work.dent));
|
||||
if !state.is_continue() {
|
||||
|
|
@ -1680,6 +1844,10 @@ impl<'s> Worker<'s> {
|
|||
return WalkState::Skip;
|
||||
}
|
||||
|
||||
let readdir = match readdir {
|
||||
Some(readdir) => readdir,
|
||||
None => return WalkState::Skip,
|
||||
};
|
||||
let readdir = match readdir {
|
||||
Ok(readdir) => readdir,
|
||||
Err(err) => {
|
||||
|
|
@ -1687,11 +1855,19 @@ impl<'s> Worker<'s> {
|
|||
}
|
||||
};
|
||||
|
||||
if self.max_depth.map_or(false, |max| depth >= max) {
|
||||
return WalkState::Skip;
|
||||
for result in readdir.entries {
|
||||
let state = self.generate_work(
|
||||
&work.ignore,
|
||||
depth + 1,
|
||||
work.root_device,
|
||||
result,
|
||||
);
|
||||
if state.is_quit() {
|
||||
return state;
|
||||
}
|
||||
}
|
||||
for result in readdir {
|
||||
let state = self.generate_work(&work.ignore, depth + 1, work.root_device, result);
|
||||
for err in readdir.errors {
|
||||
let state = self.visitor.visit(Err(err));
|
||||
if state.is_quit() {
|
||||
return state;
|
||||
}
|
||||
|
|
@ -1717,14 +1893,8 @@ impl<'s> Worker<'s> {
|
|||
ig: &Ignore,
|
||||
depth: usize,
|
||||
root_device: Option<u64>,
|
||||
result: Result<fs::DirEntry, io::Error>,
|
||||
fs_dent: fs::DirEntry,
|
||||
) -> WalkState {
|
||||
let fs_dent = match result {
|
||||
Ok(fs_dent) => fs_dent,
|
||||
Err(err) => {
|
||||
return self.visitor.visit(Err(Error::from(err).with_depth(depth)));
|
||||
}
|
||||
};
|
||||
let mut dent = match DirEntryRaw::from_entry(depth, &fs_dent) {
|
||||
Ok(dent) => DirEntry::new_raw(dent, None),
|
||||
Err(err) => {
|
||||
|
|
@ -1760,26 +1930,24 @@ impl<'s> Worker<'s> {
|
|||
return WalkState::Continue;
|
||||
}
|
||||
}
|
||||
let should_skip_filesize = if self.max_filesize.is_some() && !dent.is_dir() {
|
||||
skip_filesize(
|
||||
self.max_filesize.unwrap(),
|
||||
dent.path(),
|
||||
&dent.metadata().ok(),
|
||||
)
|
||||
} else {
|
||||
false
|
||||
};
|
||||
let should_skip_filtered = if let Some(Filter(predicate)) = &self.filter {
|
||||
!predicate(&dent)
|
||||
} else {
|
||||
false
|
||||
};
|
||||
let should_skip_filesize =
|
||||
if self.max_filesize.is_some() && !dent.is_dir() {
|
||||
skip_filesize(
|
||||
self.max_filesize.unwrap(),
|
||||
dent.path(),
|
||||
&dent.metadata().ok(),
|
||||
)
|
||||
} else {
|
||||
false
|
||||
};
|
||||
let should_skip_filtered =
|
||||
if let Some(Filter(predicate)) = &self.filter {
|
||||
!predicate(&dent)
|
||||
} else {
|
||||
false
|
||||
};
|
||||
if !should_skip_filesize && !should_skip_filtered {
|
||||
self.send(Work {
|
||||
dent,
|
||||
ignore: ig.clone(),
|
||||
root_device,
|
||||
});
|
||||
self.send(Work { dent, ignore: ig.clone(), root_device });
|
||||
}
|
||||
WalkState::Continue
|
||||
}
|
||||
|
|
@ -1820,6 +1988,9 @@ impl<'s> Worker<'s> {
|
|||
}
|
||||
// Wait for next `Work` or `Quit` message.
|
||||
loop {
|
||||
if self.is_quit_now() {
|
||||
return None;
|
||||
}
|
||||
if let Some(v) = self.recv() {
|
||||
self.activate_worker();
|
||||
value = Some(v);
|
||||
|
|
@ -1873,24 +2044,25 @@ impl<'s> Worker<'s> {
|
|||
}
|
||||
}
|
||||
|
||||
impl<'s> Drop for Worker<'s> {
|
||||
fn drop(&mut self) {
|
||||
if std::thread::panicking() {
|
||||
self.quit_now();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn check_symlink_loop(
|
||||
ig_parent: &Ignore,
|
||||
child_path: &Path,
|
||||
child_depth: usize,
|
||||
) -> Result<(), Error> {
|
||||
let hchild = Handle::from_path(child_path).map_err(|err| {
|
||||
Error::from(err)
|
||||
.with_path(child_path)
|
||||
.with_depth(child_depth)
|
||||
Error::from(err).with_path(child_path).with_depth(child_depth)
|
||||
})?;
|
||||
for ig in ig_parent
|
||||
.parents()
|
||||
.take_while(|ig| !ig.is_absolute_parent())
|
||||
{
|
||||
for ig in ig_parent.parents().take_while(|ig| !ig.is_absolute_parent()) {
|
||||
let h = Handle::from_path(ig.path()).map_err(|err| {
|
||||
Error::from(err)
|
||||
.with_path(child_path)
|
||||
.with_depth(child_depth)
|
||||
Error::from(err).with_path(child_path).with_depth(child_depth)
|
||||
})?;
|
||||
if hchild == h {
|
||||
return Err(Error::Loop {
|
||||
|
|
@ -1905,7 +2077,11 @@ fn check_symlink_loop(
|
|||
|
||||
// Before calling this function, make sure that you ensure that is really
|
||||
// necessary as the arguments imply a file stat.
|
||||
fn skip_filesize(max_filesize: u64, path: &Path, ent: &Option<Metadata>) -> bool {
|
||||
fn skip_filesize(
|
||||
max_filesize: u64,
|
||||
path: &Path,
|
||||
ent: &Option<Metadata>,
|
||||
) -> bool {
|
||||
let filesize = match *ent {
|
||||
Some(ref md) => Some(md.len()),
|
||||
None => None,
|
||||
|
|
@ -1977,9 +2153,9 @@ fn path_equals(dent: &DirEntry, handle: &Handle) -> Result<bool, Error> {
|
|||
if dent.is_stdin() || never_equal(dent, handle) {
|
||||
return Ok(false);
|
||||
}
|
||||
Handle::from_path(dent.path())
|
||||
.map(|h| &h == handle)
|
||||
.map_err(|err| Error::Io(err).with_path(dent.path()))
|
||||
Handle::from_path(dent.path()).map(|h| &h == handle).map_err(|err| {
|
||||
Error::Io(err).with_depth(dent.depth()).with_path(dent.path())
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns true if the given walkdir entry corresponds to a directory.
|
||||
|
|
@ -1997,16 +2173,14 @@ fn walkdir_is_dir(dent: &walkdir::DirEntry) -> bool {
|
|||
if !dent.file_type().is_symlink() || dent.depth() > 0 {
|
||||
return false;
|
||||
}
|
||||
dent.path()
|
||||
.metadata()
|
||||
.ok()
|
||||
.map_or(false, |md| md.file_type().is_dir())
|
||||
dent.path().metadata().ok().map_or(false, |md| md.file_type().is_dir())
|
||||
}
|
||||
|
||||
/// Returns true if and only if the given path is on the same device as the
|
||||
/// given root device.
|
||||
fn is_same_file_system(root_device: u64, path: &Path) -> Result<bool, Error> {
|
||||
let dent_device = device_num(path).map_err(|err| Error::Io(err).with_path(path))?;
|
||||
let dent_device =
|
||||
device_num(path).map_err(|err| Error::Io(err).with_path(path))?;
|
||||
Ok(root_device == dent_device)
|
||||
}
|
||||
|
||||
|
|
@ -2065,11 +2239,7 @@ mod tests {
|
|||
}
|
||||
|
||||
fn normal_path(unix: &str) -> String {
|
||||
if cfg!(windows) {
|
||||
unix.replace("\\", "/")
|
||||
} else {
|
||||
unix.to_string()
|
||||
}
|
||||
if cfg!(windows) { unix.replace("\\", "/") } else { unix.to_string() }
|
||||
}
|
||||
|
||||
fn walk_collect(prefix: &Path, builder: &WalkBuilder) -> Vec<String> {
|
||||
|
|
@ -2089,7 +2259,10 @@ mod tests {
|
|||
paths
|
||||
}
|
||||
|
||||
fn walk_collect_parallel(prefix: &Path, builder: &WalkBuilder) -> Vec<String> {
|
||||
fn walk_collect_parallel(
|
||||
prefix: &Path,
|
||||
builder: &WalkBuilder,
|
||||
) -> Vec<String> {
|
||||
let mut paths = vec![];
|
||||
for dent in walk_collect_entries_parallel(builder) {
|
||||
let path = dent.path().strip_prefix(prefix).unwrap();
|
||||
|
|
@ -2278,6 +2451,27 @@ mod tests {
|
|||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn max_depth_does_not_load_unreachable_ignore_files() {
|
||||
let td = tmpdir();
|
||||
let leaf = td.path().join("leaf");
|
||||
mkdirp(&leaf);
|
||||
wfile(leaf.join(".ignore"), "{invalid\n");
|
||||
|
||||
let mut builder = WalkBuilder::new(td.path());
|
||||
builder.max_depth(Some(1));
|
||||
let entry = builder
|
||||
.build()
|
||||
.find_map(|result| {
|
||||
let entry = result.unwrap();
|
||||
(entry.path() == leaf).then_some(entry)
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
assert!(entry.error().is_none());
|
||||
assert_paths(td.path(), &builder, &["leaf"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn min_depth() {
|
||||
let td = tmpdir();
|
||||
|
|
@ -2388,7 +2582,9 @@ mod tests {
|
|||
assert_eq!(1, dents.len());
|
||||
assert!(!dents[0].path_is_symlink());
|
||||
|
||||
let dents = walk_collect_entries_parallel(&WalkBuilder::new(td.path().join("foo")));
|
||||
let dents = walk_collect_entries_parallel(&WalkBuilder::new(
|
||||
td.path().join("foo"),
|
||||
));
|
||||
assert_eq!(1, dents.len());
|
||||
assert!(!dents[0].path_is_symlink());
|
||||
}
|
||||
|
|
@ -2474,8 +2670,88 @@ mod tests {
|
|||
|
||||
assert_paths(
|
||||
td.path(),
|
||||
&WalkBuilder::new(td.path()).filter_entry(|entry| entry.file_name() != OsStr::new("a")),
|
||||
&WalkBuilder::new(td.path())
|
||||
.filter_entry(|entry| entry.file_name() != OsStr::new("a")),
|
||||
&["x", "x/y", "x/y/foo"],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty() {
|
||||
let td = tmpdir();
|
||||
assert_paths(td.path(), &WalkBuilder::empty(), &[]);
|
||||
|
||||
let empty_paths: Vec<&OsStr> = Vec::new();
|
||||
assert_paths(td.path(), &WalkBuilder::from_iter(empty_paths), &[]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_iter() {
|
||||
let td = tmpdir();
|
||||
mkdirp(td.path().join("a/b/c"));
|
||||
mkdirp(td.path().join("d/e/f"));
|
||||
mkdirp(td.path().join("x/y"));
|
||||
wfile(td.path().join("a/b/foo"), "");
|
||||
wfile(td.path().join("d/e/f/foo"), "");
|
||||
wfile(td.path().join("x/y/foo"), "");
|
||||
|
||||
let paths = vec![
|
||||
td.path().join("a"),
|
||||
td.path().join("d"),
|
||||
td.path().join("x"),
|
||||
];
|
||||
|
||||
assert_paths(
|
||||
td.path(),
|
||||
&WalkBuilder::from_iter(paths),
|
||||
&[
|
||||
"x",
|
||||
"x/y",
|
||||
"x/y/foo",
|
||||
"d",
|
||||
"d/e",
|
||||
"d/e/f",
|
||||
"d/e/f/foo",
|
||||
"a",
|
||||
"a/b",
|
||||
"a/b/foo",
|
||||
"a/b/c",
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
// This should always panic and never hang.
|
||||
//
|
||||
// Ref: https://github.com/BurntSushi/ripgrep/issues/3009
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn panic_in_parallel() {
|
||||
let td = tmpdir();
|
||||
wfile(td.path().join("foo.txt"), "");
|
||||
|
||||
WalkBuilder::new(td.path())
|
||||
.threads(40)
|
||||
.build_parallel()
|
||||
.run(|| Box::new(|_| panic!("oops!")));
|
||||
}
|
||||
|
||||
// This should always panic and never hang. The first call to the visitor
|
||||
// builder is used while processing the root paths. Previously, a panic on
|
||||
// the third call occurred after the first worker had already been spawned,
|
||||
// leaving it waiting indefinitely for workers that were never created.
|
||||
#[test]
|
||||
#[should_panic(expected = "builder panic")]
|
||||
fn panic_in_parallel_builder() {
|
||||
let td = tmpdir();
|
||||
wfile(td.path().join("foo.txt"), "");
|
||||
|
||||
let mut builds = 0;
|
||||
WalkBuilder::new(td.path()).threads(2).build_parallel().run(|| {
|
||||
builds += 1;
|
||||
if builds == 3 {
|
||||
panic!("builder panic");
|
||||
}
|
||||
Box::new(|_| WalkState::Continue)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,8 @@ use std::path::Path;
|
|||
|
||||
use ignore::gitignore::{Gitignore, GitignoreBuilder};
|
||||
|
||||
const IGNORE_FILE: &'static str = "tests/gitignore_matched_path_or_any_parents_tests.gitignore";
|
||||
const IGNORE_FILE: &'static str =
|
||||
"tests/gitignore_matched_path_or_any_parents_tests.gitignore";
|
||||
|
||||
fn get_gitignore() -> Gitignore {
|
||||
let mut builder = GitignoreBuilder::new("ROOT");
|
||||
|
|
@ -23,7 +24,9 @@ fn test_path_should_be_under_root() {
|
|||
#[test]
|
||||
fn test_files_in_root() {
|
||||
let gitignore = get_gitignore();
|
||||
let m = |path: &str| gitignore.matched_path_or_any_parents(Path::new(path), false);
|
||||
let m = |path: &str| {
|
||||
gitignore.matched_path_or_any_parents(Path::new(path), false)
|
||||
};
|
||||
|
||||
// 0x
|
||||
assert!(m("ROOT/file_root_00").is_ignore());
|
||||
|
|
@ -53,7 +56,9 @@ fn test_files_in_root() {
|
|||
#[test]
|
||||
fn test_files_in_deep() {
|
||||
let gitignore = get_gitignore();
|
||||
let m = |path: &str| gitignore.matched_path_or_any_parents(Path::new(path), false);
|
||||
let m = |path: &str| {
|
||||
gitignore.matched_path_or_any_parents(Path::new(path), false)
|
||||
};
|
||||
|
||||
// 0x
|
||||
assert!(m("ROOT/parent_dir/file_deep_00").is_ignore());
|
||||
|
|
@ -83,8 +88,9 @@ fn test_files_in_deep() {
|
|||
#[test]
|
||||
fn test_dirs_in_root() {
|
||||
let gitignore = get_gitignore();
|
||||
let m =
|
||||
|path: &str, is_dir: bool| gitignore.matched_path_or_any_parents(Path::new(path), is_dir);
|
||||
let m = |path: &str, is_dir: bool| {
|
||||
gitignore.matched_path_or_any_parents(Path::new(path), is_dir)
|
||||
};
|
||||
|
||||
// 00
|
||||
assert!(m("ROOT/dir_root_00", true).is_ignore());
|
||||
|
|
@ -186,20 +192,25 @@ fn test_dirs_in_root() {
|
|||
#[test]
|
||||
fn test_dirs_in_deep() {
|
||||
let gitignore = get_gitignore();
|
||||
let m =
|
||||
|path: &str, is_dir: bool| gitignore.matched_path_or_any_parents(Path::new(path), is_dir);
|
||||
let m = |path: &str, is_dir: bool| {
|
||||
gitignore.matched_path_or_any_parents(Path::new(path), is_dir)
|
||||
};
|
||||
|
||||
// 00
|
||||
assert!(m("ROOT/parent_dir/dir_deep_00", true).is_ignore());
|
||||
assert!(m("ROOT/parent_dir/dir_deep_00/file", false).is_ignore());
|
||||
assert!(m("ROOT/parent_dir/dir_deep_00/child_dir", true).is_ignore());
|
||||
assert!(m("ROOT/parent_dir/dir_deep_00/child_dir/file", false).is_ignore());
|
||||
assert!(
|
||||
m("ROOT/parent_dir/dir_deep_00/child_dir/file", false).is_ignore()
|
||||
);
|
||||
|
||||
// 01
|
||||
assert!(m("ROOT/parent_dir/dir_deep_01", true).is_ignore());
|
||||
assert!(m("ROOT/parent_dir/dir_deep_01/file", false).is_ignore());
|
||||
assert!(m("ROOT/parent_dir/dir_deep_01/child_dir", true).is_ignore());
|
||||
assert!(m("ROOT/parent_dir/dir_deep_01/child_dir/file", false).is_ignore());
|
||||
assert!(
|
||||
m("ROOT/parent_dir/dir_deep_01/child_dir/file", false).is_ignore()
|
||||
);
|
||||
|
||||
// 02
|
||||
assert!(m("ROOT/parent_dir/dir_deep_02", true).is_none());
|
||||
|
|
@ -241,51 +252,67 @@ fn test_dirs_in_deep() {
|
|||
assert!(m("ROOT/parent_dir/dir_deep_20", true).is_ignore());
|
||||
assert!(m("ROOT/parent_dir/dir_deep_20/file", false).is_ignore());
|
||||
assert!(m("ROOT/parent_dir/dir_deep_20/child_dir", true).is_ignore());
|
||||
assert!(m("ROOT/parent_dir/dir_deep_20/child_dir/file", false).is_ignore());
|
||||
assert!(
|
||||
m("ROOT/parent_dir/dir_deep_20/child_dir/file", false).is_ignore()
|
||||
);
|
||||
|
||||
// 21
|
||||
assert!(m("ROOT/parent_dir/dir_deep_21", true).is_ignore());
|
||||
assert!(m("ROOT/parent_dir/dir_deep_21/file", false).is_ignore());
|
||||
assert!(m("ROOT/parent_dir/dir_deep_21/child_dir", true).is_ignore());
|
||||
assert!(m("ROOT/parent_dir/dir_deep_21/child_dir/file", false).is_ignore());
|
||||
assert!(
|
||||
m("ROOT/parent_dir/dir_deep_21/child_dir/file", false).is_ignore()
|
||||
);
|
||||
|
||||
// 22
|
||||
// dir itself doesn't match
|
||||
assert!(m("ROOT/parent_dir/dir_deep_22", true).is_none());
|
||||
assert!(m("ROOT/parent_dir/dir_deep_22/file", false).is_ignore());
|
||||
assert!(m("ROOT/parent_dir/dir_deep_22/child_dir", true).is_ignore());
|
||||
assert!(m("ROOT/parent_dir/dir_deep_22/child_dir/file", false).is_ignore());
|
||||
assert!(
|
||||
m("ROOT/parent_dir/dir_deep_22/child_dir/file", false).is_ignore()
|
||||
);
|
||||
|
||||
// 23
|
||||
// dir itself doesn't match
|
||||
assert!(m("ROOT/parent_dir/dir_deep_23", true).is_none());
|
||||
assert!(m("ROOT/parent_dir/dir_deep_23/file", false).is_ignore());
|
||||
assert!(m("ROOT/parent_dir/dir_deep_23/child_dir", true).is_ignore());
|
||||
assert!(m("ROOT/parent_dir/dir_deep_23/child_dir/file", false).is_ignore());
|
||||
assert!(
|
||||
m("ROOT/parent_dir/dir_deep_23/child_dir/file", false).is_ignore()
|
||||
);
|
||||
|
||||
// 30
|
||||
assert!(m("ROOT/parent_dir/dir_deep_30", true).is_ignore());
|
||||
assert!(m("ROOT/parent_dir/dir_deep_30/file", false).is_ignore());
|
||||
assert!(m("ROOT/parent_dir/dir_deep_30/child_dir", true).is_ignore());
|
||||
assert!(m("ROOT/parent_dir/dir_deep_30/child_dir/file", false).is_ignore());
|
||||
assert!(
|
||||
m("ROOT/parent_dir/dir_deep_30/child_dir/file", false).is_ignore()
|
||||
);
|
||||
|
||||
// 31
|
||||
assert!(m("ROOT/parent_dir/dir_deep_31", true).is_ignore());
|
||||
assert!(m("ROOT/parent_dir/dir_deep_31/file", false).is_ignore());
|
||||
assert!(m("ROOT/parent_dir/dir_deep_31/child_dir", true).is_ignore());
|
||||
assert!(m("ROOT/parent_dir/dir_deep_31/child_dir/file", false).is_ignore());
|
||||
assert!(
|
||||
m("ROOT/parent_dir/dir_deep_31/child_dir/file", false).is_ignore()
|
||||
);
|
||||
|
||||
// 32
|
||||
// dir itself doesn't match
|
||||
assert!(m("ROOT/parent_dir/dir_deep_32", true).is_none());
|
||||
assert!(m("ROOT/parent_dir/dir_deep_32/file", false).is_ignore());
|
||||
assert!(m("ROOT/parent_dir/dir_deep_32/child_dir", true).is_ignore());
|
||||
assert!(m("ROOT/parent_dir/dir_deep_32/child_dir/file", false).is_ignore());
|
||||
assert!(
|
||||
m("ROOT/parent_dir/dir_deep_32/child_dir/file", false).is_ignore()
|
||||
);
|
||||
|
||||
// 33
|
||||
// dir itself doesn't match
|
||||
assert!(m("ROOT/parent_dir/dir_deep_33", true).is_none());
|
||||
assert!(m("ROOT/parent_dir/dir_deep_33/file", false).is_ignore());
|
||||
assert!(m("ROOT/parent_dir/dir_deep_33/child_dir", true).is_ignore());
|
||||
assert!(m("ROOT/parent_dir/dir_deep_33/child_dir/file", false).is_ignore());
|
||||
assert!(
|
||||
m("ROOT/parent_dir/dir_deep_33/child_dir/file", false).is_ignore()
|
||||
);
|
||||
}
|
||||
|
|
|
|||
1
crates/node/.gitignore
vendored
1
crates/node/.gitignore
vendored
|
|
@ -202,5 +202,6 @@ index.js
|
|||
browser.js
|
||||
tailwindcss-oxide.wasi-browser.js
|
||||
tailwindcss-oxide.wasi.cjs
|
||||
tailwindcss-oxide.wasi.d.cts
|
||||
wasi-worker-browser.mjs
|
||||
wasi-worker.mjs
|
||||
|
|
|
|||
|
|
@ -8,10 +8,10 @@ crate-type = ["cdylib"]
|
|||
|
||||
[dependencies]
|
||||
# Default enable napi4 feature, see https://nodejs.org/api/n-api.html#node-api-version-matrix
|
||||
napi = { version = "3.8.5", default-features = false, features = ["napi4"] }
|
||||
napi-derive = "3.5.4"
|
||||
napi = { version = "3.11.0", default-features = false, features = ["napi4"] }
|
||||
napi-derive = "3.6.0"
|
||||
tailwindcss-oxide = { path = "../oxide" }
|
||||
rayon = "1.10.0"
|
||||
rayon = "1.12.0"
|
||||
|
||||
[build-dependencies]
|
||||
napi-build = "2.3.1"
|
||||
napi-build = "2.3.2"
|
||||
|
|
|
|||
|
|
@ -1,3 +1,3 @@
|
|||
# `@tailwindcss/oxide-wasm32-wasi`
|
||||
|
||||
This is the **wasm32-wasip1-threads** binary for `@tailwindcss/oxide`
|
||||
This is the **wasm32-wasip1-threads** build of `@tailwindcss/oxide`
|
||||
|
|
|
|||
|
|
@ -1,9 +1,6 @@
|
|||
{
|
||||
"name": "@tailwindcss/oxide-wasm32-wasi",
|
||||
"version": "4.3.3",
|
||||
"cpu": [
|
||||
"wasm32"
|
||||
],
|
||||
"main": "tailwindcss-oxide.wasi.cjs",
|
||||
"files": [
|
||||
"tailwindcss-oxide.wasm32-wasi.wasm",
|
||||
|
|
@ -14,7 +11,7 @@
|
|||
],
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=14.0.0"
|
||||
"node": "^20.19.0 || ^22.13.0 || >=23.5.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"provenance": true,
|
||||
|
|
@ -27,11 +24,11 @@
|
|||
},
|
||||
"browser": "tailwindcss-oxide.wasi-browser.js",
|
||||
"dependencies": {
|
||||
"@napi-rs/wasm-runtime": "^1.1.4",
|
||||
"@emnapi/core": "^1.11.1",
|
||||
"@emnapi/runtime": "^1.11.1",
|
||||
"@tybys/wasm-util": "^0.10.2",
|
||||
"@emnapi/wasi-threads": "^1.2.2",
|
||||
"@napi-rs/wasm-runtime": "^1.2.2",
|
||||
"@emnapi/core": "^1.11.3",
|
||||
"@emnapi/runtime": "^1.11.3",
|
||||
"@tybys/wasm-util": "^0.10.3",
|
||||
"@emnapi/wasi-threads": "^1.2.3",
|
||||
"tslib": "^2.8.1"
|
||||
},
|
||||
"bundledDependencies": [
|
||||
|
|
|
|||
|
|
@ -34,9 +34,11 @@
|
|||
},
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@napi-rs/cli": "3.7.0",
|
||||
"@napi-rs/wasm-runtime": "^1.1.5",
|
||||
"emnapi": "1.11.1"
|
||||
"@emnapi/core": "1.11.3",
|
||||
"@emnapi/runtime": "1.11.3",
|
||||
"@napi-rs/cli": "3.7.4",
|
||||
"@napi-rs/wasm-runtime": "^1.2.2",
|
||||
"emnapi": "1.11.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 20"
|
||||
|
|
|
|||
|
|
@ -20,6 +20,7 @@ ignore = { path = "../ignore" }
|
|||
regex = "1.11.1"
|
||||
|
||||
[dev-dependencies]
|
||||
insta = "1.48.0"
|
||||
tempfile = "3.13.0"
|
||||
pretty_assertions = "1.4.1"
|
||||
unicode-width = "0.2.0"
|
||||
|
|
|
|||
|
|
@ -25,6 +25,7 @@ impl BracketStack {
|
|||
b'(' => b')',
|
||||
b'[' => b']',
|
||||
b'{' => b'}',
|
||||
b'<' => b'>',
|
||||
_ => std::hint::unreachable_unchecked(),
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -203,6 +203,81 @@ impl PreProcessor for Haml {
|
|||
}
|
||||
}
|
||||
|
||||
// Handle Ruby syntax with `%w[]` arrays embedded in Haml attribute hashes. E.g.:
|
||||
//
|
||||
// ```haml
|
||||
// %div{class: %w[bg-blue-500 w-10 h-10]}
|
||||
// ```
|
||||
//
|
||||
// A `%` that follows a value is not a percent literal. E.g.: the `50%w` in
|
||||
// `hit rate 50%w.`
|
||||
b'%' if matches!(cursor.next(), b'w' | b'W')
|
||||
&& !cursor.prev().is_ascii_alphanumeric()
|
||||
&& !matches!(cursor.prev(), b'_' | b')' | b']' | b'}') =>
|
||||
{
|
||||
// Boundary characters
|
||||
let (open, close) = match cursor.input.get(cursor.pos + 2) {
|
||||
Some(b'[') => (b'[', b']'),
|
||||
Some(b'(') => (b'(', b')'),
|
||||
Some(b'{') => (b'{', b'}'),
|
||||
Some(b'<') => (b'<', b'>'),
|
||||
|
||||
// Any other ASCII punctuation can be used as a custom delimiter
|
||||
Some(&c) if c.is_ascii_punctuation() => (c, c),
|
||||
|
||||
// Everything else is not a valid delimiter
|
||||
_ => {
|
||||
cursor.advance();
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
result[cursor.pos] = b' '; // Replace `%`
|
||||
cursor.advance();
|
||||
result[cursor.pos] = b' '; // Replace `w`
|
||||
cursor.advance();
|
||||
result[cursor.pos] = b' '; // Replace the opening delimiter
|
||||
cursor.advance();
|
||||
|
||||
// Paired delimiters can be nested as long as they are balanced. E.g.:
|
||||
// `%w[foo[bar]baz]` produces a flat array.
|
||||
let mut depth = 1_usize;
|
||||
|
||||
while cursor.pos < len {
|
||||
match cursor.curr() {
|
||||
// Skip escaped characters, unless the backslash is the delimiter
|
||||
// itself
|
||||
b'\\' if close != b'\\' => {
|
||||
// Use backslash to embed spaces in the strings.
|
||||
if cursor.next() == b' ' {
|
||||
result[cursor.pos] = b' ';
|
||||
}
|
||||
|
||||
cursor.advance();
|
||||
}
|
||||
|
||||
// Start of a nested delimiter pair
|
||||
c if c == open && open != close => depth += 1,
|
||||
|
||||
// Closing delimiter
|
||||
c if c == close => {
|
||||
depth -= 1;
|
||||
|
||||
// End of the literal, replace the closing delimiter with a space
|
||||
if depth == 0 {
|
||||
result[cursor.pos] = b' ';
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Everything else is valid content
|
||||
_ => {}
|
||||
}
|
||||
|
||||
cursor.advance();
|
||||
}
|
||||
}
|
||||
|
||||
// Replace following characters with spaces if they are not inside of brackets
|
||||
b'#' | b'=' if bracket_stack.is_empty() => {
|
||||
result[cursor.pos] = b' ';
|
||||
|
|
@ -424,6 +499,81 @@ mod tests {
|
|||
);
|
||||
}
|
||||
|
||||
// https://github.com/tailwindlabs/tailwindcss/issues/20386
|
||||
#[test]
|
||||
fn test_embedded_ruby_percent_w_delimiters() {
|
||||
for (input, expected) in [
|
||||
// %w[…] in an attribute hash
|
||||
(
|
||||
"%div{class: %w[flex px-2.5]}",
|
||||
"%div class: flex px-2.5 ",
|
||||
),
|
||||
// %w<…>
|
||||
(
|
||||
"%div{class: %w<flex px-2.5>}",
|
||||
"%div class: flex px-2.5 ",
|
||||
),
|
||||
// Nested `<…>` does not end the literal
|
||||
(
|
||||
"%div{class: %w<flex <nested> px-2.5>}",
|
||||
"%div class: flex <nested> px-2.5 ",
|
||||
),
|
||||
// Custom delimiters
|
||||
(
|
||||
"%div{class: %w|flex px-2.5|}",
|
||||
"%div class: flex px-2.5 ",
|
||||
),
|
||||
(
|
||||
"%div{class: %W!flex px-2.5!}",
|
||||
"%div class: flex px-2.5 ",
|
||||
),
|
||||
(
|
||||
"%div{class: %w#text-sm leading-6#}",
|
||||
"%div class: text-sm leading-6 ",
|
||||
),
|
||||
(
|
||||
"%div{class: %w=italic tracking-wide=}",
|
||||
"%div class: italic tracking-wide ",
|
||||
),
|
||||
// Nested paired delimiters stay balanced inside the literal
|
||||
(
|
||||
"%div{class: %w[content-['[hello]'] p-4]}",
|
||||
"%div class: content-['[hello]'] p-4 ",
|
||||
),
|
||||
// Escaped spaces embed a space in a single array element
|
||||
(
|
||||
r#"%div{class: %w[foo\ bar baz-1]}"#,
|
||||
r#"%div class: foo bar baz-1 "#,
|
||||
),
|
||||
// A `%` that follows a value is not a percent literal
|
||||
("%p hit rate 50%w.", "%p hit rate 50%w "),
|
||||
] {
|
||||
Haml::test(input, expected);
|
||||
}
|
||||
|
||||
let input = r#"
|
||||
%div{class: %w[bg-blue-500 w-10 h-10]}
|
||||
%div{class: %w<flex px-2.5>}
|
||||
%div{class: %w|underline font-bold|}
|
||||
- classes = %w<mt-4 grid>
|
||||
"#;
|
||||
|
||||
Haml::test_extract_contains(
|
||||
input,
|
||||
vec![
|
||||
"bg-blue-500",
|
||||
"w-10",
|
||||
"h-10",
|
||||
"flex",
|
||||
"px-2.5",
|
||||
"underline",
|
||||
"font-bold",
|
||||
"mt-4",
|
||||
"grid",
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
// https://github.com/tailwindlabs/tailwindcss/pull/17051#issuecomment-2711181352
|
||||
#[test]
|
||||
fn test_haml_full_file_17051() {
|
||||
|
|
|
|||
|
|
@ -158,6 +158,15 @@ impl PreProcessor for Ruby {
|
|||
continue;
|
||||
}
|
||||
|
||||
// A `%` that follows a value is a modulo operation, not a percent literal. E.g.: the
|
||||
// `50%w` in `hit rate 50%w.`
|
||||
if cursor.prev().is_ascii_alphanumeric()
|
||||
|| matches!(cursor.prev(), b'_' | b')' | b']' | b'}')
|
||||
{
|
||||
cursor.advance();
|
||||
continue;
|
||||
}
|
||||
|
||||
cursor.advance_twice();
|
||||
|
||||
// Boundary character
|
||||
|
|
@ -165,8 +174,13 @@ impl PreProcessor for Ruby {
|
|||
b'[' => b']',
|
||||
b'(' => b')',
|
||||
b'{' => b'}',
|
||||
b'#' => b'#',
|
||||
b'<' => b'>',
|
||||
b' ' => b'\n',
|
||||
|
||||
// Any other ASCII punctuation can be used as a custom delimiter
|
||||
c if c.is_ascii_punctuation() => c,
|
||||
|
||||
// Everything else is not a valid delimiter
|
||||
_ => {
|
||||
cursor.advance();
|
||||
continue;
|
||||
|
|
@ -183,8 +197,8 @@ impl PreProcessor for Ruby {
|
|||
|
||||
while cursor.pos < len {
|
||||
match cursor.curr() {
|
||||
// Skip escaped characters
|
||||
b'\\' => {
|
||||
// Skip escaped characters, unless the backslash is the delimiter itself
|
||||
b'\\' if boundary != b'\\' => {
|
||||
// Use backslash to embed spaces in the strings.
|
||||
if cursor.next() == b' ' {
|
||||
result[cursor.pos] = b' ';
|
||||
|
|
@ -198,6 +212,11 @@ impl PreProcessor for Ruby {
|
|||
bracket_stack.push(cursor.curr());
|
||||
}
|
||||
|
||||
// Start of a nested `<…>`, which Ruby allows inside a `%w<…>` literal
|
||||
b'<' if boundary == b'>' => {
|
||||
bracket_stack.push(cursor.curr());
|
||||
}
|
||||
|
||||
// End of a nested bracket
|
||||
b']' | b')' | b'}' if !bracket_stack.is_empty() => {
|
||||
if !bracket_stack.pop(cursor.curr()) {
|
||||
|
|
@ -206,6 +225,14 @@ impl PreProcessor for Ruby {
|
|||
}
|
||||
}
|
||||
|
||||
// End of a nested `<…>`
|
||||
b'>' if boundary == b'>' && !bracket_stack.is_empty() => {
|
||||
if !bracket_stack.pop(cursor.curr()) {
|
||||
// Unbalanced
|
||||
cursor.advance();
|
||||
}
|
||||
}
|
||||
|
||||
// End of the pattern, replace the boundary character with a space
|
||||
_ if cursor.curr() == boundary => {
|
||||
if boundary != b'\n' {
|
||||
|
|
@ -253,6 +280,24 @@ mod tests {
|
|||
"%w(flex data-[state=pending]:bg-(--my-color) flex-col)",
|
||||
"%w flex data-[state=pending]:bg-(--my-color) flex-col ",
|
||||
),
|
||||
// %w<…>
|
||||
("%w<flex px-2.5>", "%w flex px-2.5 "),
|
||||
(
|
||||
"%w<flex data-[state=pending]:bg-(--my-color) flex-col>",
|
||||
"%w flex data-[state=pending]:bg-(--my-color) flex-col ",
|
||||
),
|
||||
// Nested `<…>` does not end the literal
|
||||
("%w<flex <nested> px-2.5>", "%w flex <nested> px-2.5 "),
|
||||
// %w|…|, %w:…:, %w!…!
|
||||
("%w|flex px-2.5|", "%w flex px-2.5 "),
|
||||
("%w:flex px-2.5:", "%w flex px-2.5 "),
|
||||
("%w!flex px-2.5!", "%w flex px-2.5 "),
|
||||
(r#"%w\flex px-2.5\"#, r#"%w flex px-2.5 "#),
|
||||
// A `%` that follows a value is a modulo operation, not a percent literal
|
||||
(
|
||||
"hit rate 50%w.\n%w[flex px-2.5]",
|
||||
"hit rate 50%w.\n%w flex px-2.5 ",
|
||||
),
|
||||
|
||||
// %w …\n
|
||||
("%w flex px-2.5\n", "%w flex px-2.5\n"),
|
||||
|
|
@ -330,6 +375,20 @@ mod tests {
|
|||
"%w(flex data-[state=pending]:bg-(--my-color) flex-col)",
|
||||
vec!["flex", "data-[state=pending]:bg-(--my-color)", "flex-col"],
|
||||
),
|
||||
// %w<…>
|
||||
("%w<flex px-2.5>", vec!["flex", "px-2.5"]),
|
||||
("%w<px-2.5 flex>", vec!["flex", "px-2.5"]),
|
||||
("%w<2xl:flex>", vec!["2xl:flex"]),
|
||||
(
|
||||
"%w<flex data-[state=pending]:bg-(--my-color) flex-col>",
|
||||
vec!["flex", "data-[state=pending]:bg-(--my-color)", "flex-col"],
|
||||
),
|
||||
// Nested `<…>` does not end the literal
|
||||
("%w<flex <nested> px-2.5>", vec!["flex", "px-2.5"]),
|
||||
// %w|…|, %w:…:, %w!…!
|
||||
("%w|flex px-2.5|", vec!["flex", "px-2.5"]),
|
||||
("%w:flex px-2.5:", vec!["flex", "px-2.5"]),
|
||||
("%w!flex px-2.5!", vec!["flex", "px-2.5"]),
|
||||
|
||||
(
|
||||
"# test\n# test\n# {ActiveRecord::Base#save!}[rdoc-ref:Persistence#save!]\n%w[flex px-2.5]",
|
||||
|
|
|
|||
|
|
@ -65,17 +65,74 @@ impl PreProcessor for Slim {
|
|||
// class=%w[bg-blue-500 w-10 h-10]
|
||||
// ]
|
||||
// ```
|
||||
//
|
||||
// A `%` that follows a value is not a percent literal. E.g.: the `50%w` in
|
||||
// `hit rate 50%w.`
|
||||
b'%' if matches!(cursor.next(), b'w' | b'W')
|
||||
&& matches!(cursor.input.get(cursor.pos + 2), Some(b'[' | b'(' | b'{')) =>
|
||||
&& !cursor.prev().is_ascii_alphanumeric()
|
||||
&& !matches!(cursor.prev(), b'_' | b')' | b']' | b'}') =>
|
||||
{
|
||||
// Boundary characters
|
||||
let (open, close) = match cursor.input.get(cursor.pos + 2) {
|
||||
Some(b'[') => (b'[', b']'),
|
||||
Some(b'(') => (b'(', b')'),
|
||||
Some(b'{') => (b'{', b'}'),
|
||||
Some(b'<') => (b'<', b'>'),
|
||||
|
||||
// Any other ASCII punctuation can be used as a custom delimiter
|
||||
Some(&c) if c.is_ascii_punctuation() => (c, c),
|
||||
|
||||
// Everything else is not a valid delimiter
|
||||
_ => {
|
||||
cursor.advance();
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
result[cursor.pos] = b' '; // Replace `%`
|
||||
cursor.advance();
|
||||
result[cursor.pos] = b' '; // Replace `w`
|
||||
cursor.advance();
|
||||
result[cursor.pos] = b' '; // Replace `[` or `(` or `{`
|
||||
bracket_stack.push(cursor.curr());
|
||||
cursor.advance(); // Move past the bracket
|
||||
continue;
|
||||
result[cursor.pos] = b' '; // Replace the opening delimiter
|
||||
cursor.advance();
|
||||
|
||||
// Paired delimiters can be nested as long as they are balanced. E.g.:
|
||||
// `%w[foo[bar]baz]` produces a flat array.
|
||||
let mut depth = 1_usize;
|
||||
|
||||
while cursor.pos < len {
|
||||
match cursor.curr() {
|
||||
// Skip escaped characters, unless the backslash is the delimiter
|
||||
// itself
|
||||
b'\\' if close != b'\\' => {
|
||||
// Use backslash to embed spaces in the strings.
|
||||
if cursor.next() == b' ' {
|
||||
result[cursor.pos] = b' ';
|
||||
}
|
||||
|
||||
cursor.advance();
|
||||
}
|
||||
|
||||
// Start of a nested delimiter pair
|
||||
c if c == open && open != close => depth += 1,
|
||||
|
||||
// Closing delimiter
|
||||
c if c == close => {
|
||||
depth -= 1;
|
||||
|
||||
// End of the literal, replace the closing delimiter with a space
|
||||
if depth == 0 {
|
||||
result[cursor.pos] = b' ';
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Everything else is valid content
|
||||
_ => {}
|
||||
}
|
||||
|
||||
cursor.advance();
|
||||
}
|
||||
}
|
||||
|
||||
// Any `[` preceded by an alphanumeric value will not be part of a candidate.
|
||||
|
|
@ -316,16 +373,77 @@ mod tests {
|
|||
]
|
||||
"#;
|
||||
|
||||
let expected = r#"
|
||||
div
|
||||
class= bg-blue-500 w-10 h-10]
|
||||
]
|
||||
div
|
||||
class= w-10 bg-green-500 h-10]
|
||||
]
|
||||
"#;
|
||||
let expected = "
|
||||
div \n class= bg-blue-500 w-10 h-10 \n ]
|
||||
div \n class= w-10 bg-green-500 h-10 \n ]
|
||||
";
|
||||
|
||||
Slim::test(input, expected);
|
||||
Slim::test_extract_contains(input, vec!["bg-blue-500", "bg-green-500", "w-10", "h-10"]);
|
||||
}
|
||||
|
||||
// https://github.com/tailwindlabs/tailwindcss/issues/20386
|
||||
#[test]
|
||||
fn test_embedded_ruby_percent_w_delimiters() {
|
||||
for (input, expected) in [
|
||||
// %w<…>, Slim only counts `[({` nesting in attribute values, so the code must be
|
||||
// wrapped in parentheses to contain spaces
|
||||
(
|
||||
"div class=(%w<bg-blue-500 w-10 h-10>)",
|
||||
"div class= bg-blue-500 w-10 h-10 )",
|
||||
),
|
||||
// Nested `<…>` does not end the literal
|
||||
(
|
||||
"div class=(%w<flex <nested> px-2.5>)",
|
||||
"div class= flex <nested> px-2.5 )",
|
||||
),
|
||||
// Custom delimiters
|
||||
("div class=(%w|flex px-2.5|)", "div class= flex px-2.5 )"),
|
||||
("div class=(%W!flex px-2.5!)", "div class= flex px-2.5 )"),
|
||||
(
|
||||
"div class=(%w#text-sm leading-6#)",
|
||||
"div class= text-sm leading-6 )",
|
||||
),
|
||||
(
|
||||
"div class=(%w=italic tracking-wide=)",
|
||||
"div class= italic tracking-wide )",
|
||||
),
|
||||
// Nested paired delimiters stay balanced inside the literal
|
||||
(
|
||||
"div class=(%w[content-['[hello]'] p-4])",
|
||||
"div class= content-['[hello]'] p-4 )",
|
||||
),
|
||||
// Escaped spaces embed a space in a single array element
|
||||
(
|
||||
r#"div class=(%w[foo\ bar baz-1])"#,
|
||||
r#"div class= foo bar baz-1 )"#,
|
||||
),
|
||||
// Ruby control line, which is plain Ruby code
|
||||
("- classes = %w<mt-4 flex>", "- classes = mt-4 flex "),
|
||||
// A `%` that follows a value is not a percent literal
|
||||
("| hit rate 50%w.", "| hit rate 50%w "),
|
||||
] {
|
||||
Slim::test(input, expected);
|
||||
}
|
||||
|
||||
let input = r#"
|
||||
div[
|
||||
class=(%w<bg-blue-500 w-10 h-10>)
|
||||
]
|
||||
- classes = %w|w-10 bg-green-500 h-10|
|
||||
= tag.div class: %W!px-2.5 flex!
|
||||
"#;
|
||||
|
||||
Slim::test_extract_contains(
|
||||
input,
|
||||
vec![
|
||||
"bg-blue-500",
|
||||
"bg-green-500",
|
||||
"w-10",
|
||||
"h-10",
|
||||
"px-2.5",
|
||||
"flex",
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -112,6 +112,7 @@ pub fn resolve_globs(
|
|||
}
|
||||
|
||||
if !dirs.contains(path) {
|
||||
it.skip_current_dir();
|
||||
continue;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -37,20 +37,52 @@ pub fn init_tracing() {
|
|||
return;
|
||||
}
|
||||
|
||||
let file_path = format!("tailwindcss-{}.log", std::process::id());
|
||||
let file = OpenOptions::new()
|
||||
let root = Path::new(".tailwindcss");
|
||||
let logs_dir = root.join("logs");
|
||||
if let Err(err) = std::fs::create_dir_all(&logs_dir) {
|
||||
eprintln!(
|
||||
"{} Failed to create {}, skipping debug logs ({err})",
|
||||
dim("[DEBUG]"),
|
||||
highlight(&logs_dir.display().to_string())
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Ensure everything inside `.tailwindcss/` is ignored by git. The file is only created if it
|
||||
// doesn't exist yet, an existing `.gitignore` is left untouched.
|
||||
if let Ok(mut file) = std::fs::File::create_new(root.join(".gitignore")) {
|
||||
_ = file.write_all(b"*\n");
|
||||
}
|
||||
|
||||
let file_path = logs_dir.join(format!(
|
||||
"scanner-{}-{}.log",
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_millis())
|
||||
.unwrap_or(0),
|
||||
std::process::id()
|
||||
));
|
||||
let file = match OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(&file_path)
|
||||
.unwrap_or_else(|_| panic!("Failed to open {file_path}"));
|
||||
{
|
||||
Ok(file) => file,
|
||||
Err(err) => {
|
||||
eprintln!(
|
||||
"{} Failed to create {}, skipping debug logs ({err})",
|
||||
dim("[DEBUG]"),
|
||||
highlight(&file_path.display().to_string())
|
||||
);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let file_path = Path::new(&file_path);
|
||||
let absolute_file_path = dunce::canonicalize(file_path)
|
||||
.unwrap_or_else(|_| panic!("Failed to canonicalize {file_path:?}"));
|
||||
let absolute_file_path = dunce::canonicalize(&file_path).unwrap_or_else(|_| file_path.clone());
|
||||
eprintln!(
|
||||
"{} Writing debug info to: {}\n",
|
||||
dim("[DEBUG]"),
|
||||
highlight(absolute_file_path.as_path().to_str().unwrap())
|
||||
highlight(&absolute_file_path.display().to_string())
|
||||
);
|
||||
|
||||
let file = Arc::new(Mutex::new(file));
|
||||
|
|
|
|||
|
|
@ -181,6 +181,11 @@ impl Scanner {
|
|||
continue;
|
||||
}
|
||||
|
||||
// The walked path can contain symlinks, while the changed files have already
|
||||
// been canonicalized. Lazily canonicalize the walked path so we can compare
|
||||
// the real paths as well.
|
||||
let mut canonical_path: Option<PathBuf> = None;
|
||||
|
||||
let mut drop_file_indexes = vec![];
|
||||
for (idx, changed_file) in new_unknown_files.iter().enumerate().rev() {
|
||||
let ChangedContent::File(file, _) = changed_file else {
|
||||
|
|
@ -189,7 +194,15 @@ impl Scanner {
|
|||
|
||||
// When the file is found on disk it means that all the rules pass. We can
|
||||
// extract the current file and remove it from the list of passed in files.
|
||||
if file == path {
|
||||
let matches = file == path
|
||||
|| (file.file_name() == path.file_name() && {
|
||||
if canonical_path.is_none() {
|
||||
canonical_path = dunce::canonicalize(path).ok();
|
||||
}
|
||||
canonical_path.as_deref() == Some(file.as_path())
|
||||
});
|
||||
|
||||
if matches {
|
||||
self.files.insert(path.to_path_buf()); // Track for future use
|
||||
content_to_scan.push(changed_file.clone()); // Track for parsing
|
||||
drop_file_indexes.push(idx);
|
||||
|
|
@ -343,15 +356,14 @@ impl Scanner {
|
|||
let i = s.as_ptr() as usize - offset;
|
||||
let original = &original_content[i..i + s.len()];
|
||||
if original.contains_str("-[]") {
|
||||
return Some(unsafe {
|
||||
(String::from_utf8_unchecked(original.to_vec()), i)
|
||||
});
|
||||
return String::from_utf8(original.to_vec())
|
||||
.ok()
|
||||
.map(|candidate| (candidate, i));
|
||||
}
|
||||
|
||||
// SAFETY: When we parsed the candidates, we already guaranteed that the byte
|
||||
// slices are valid, therefore we don't have to re-check here when we want to
|
||||
// convert it back to a string.
|
||||
Some(unsafe { (String::from_utf8_unchecked(s.to_vec()), i) })
|
||||
String::from_utf8(s.to_vec())
|
||||
.ok()
|
||||
.map(|candidate| (candidate, i))
|
||||
}
|
||||
|
||||
_ => None,
|
||||
|
|
@ -388,47 +400,93 @@ impl Scanner {
|
|||
self.extensions.clear();
|
||||
self.globs = None;
|
||||
|
||||
for (path, is_dir, extension, mtime) in all_entries {
|
||||
if is_dir {
|
||||
self.dirs.insert(path);
|
||||
} else {
|
||||
// Deduplicate: parallel walk can visit the same file from multiple threads
|
||||
if !self.files.insert(path.clone()) {
|
||||
continue;
|
||||
}
|
||||
self.extensions.insert(extension.clone());
|
||||
// Cache canonicalized folders in case a file itself is not symlinked, but any of the parent
|
||||
// folders are symlinked.
|
||||
let mut cached_canonical_dirs: FxHashMap<PathBuf, PathBuf> = FxHashMap::default();
|
||||
|
||||
// On incremental scans, check mtime to skip unchanged files.
|
||||
// On the first scan, track mtimes while still scanning every file.
|
||||
let changed = if self.has_scanned_once {
|
||||
match mtime {
|
||||
Some(mtime) => {
|
||||
let prev = self.mtimes.insert(path.clone(), mtime);
|
||||
prev.is_none_or(|prev| prev != mtime)
|
||||
for entry in all_entries {
|
||||
match entry {
|
||||
WalkEntry::Dir(path) => {
|
||||
self.dirs.insert(path);
|
||||
}
|
||||
WalkEntry::File {
|
||||
path,
|
||||
mtime,
|
||||
is_symlink,
|
||||
} => {
|
||||
// Deduplicate: parallel walk can visit the same file from multiple threads
|
||||
if !self.files.insert(path.clone()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Track canonicalized paths in addition to potentially symlinked file paths
|
||||
let canonical = if is_symlink {
|
||||
dunce::canonicalize(&path).ok()
|
||||
} else {
|
||||
path.parent().and_then(|parent| {
|
||||
// Perf: cache the canonicalized parent path such that sibling files don't
|
||||
// have to canonicalize over and over again.
|
||||
let canonical_parent = cached_canonical_dirs
|
||||
.entry(parent.to_path_buf())
|
||||
.or_insert_with(|| {
|
||||
dunce::canonicalize(parent)
|
||||
.unwrap_or_else(|_| parent.to_path_buf())
|
||||
});
|
||||
|
||||
if canonical_parent.as_path() != parent {
|
||||
path.file_name()
|
||||
.map(|file_name| canonical_parent.join(file_name))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
};
|
||||
|
||||
if let Some(canonical) = canonical {
|
||||
if canonical != path {
|
||||
self.files.insert(canonical);
|
||||
}
|
||||
None => true,
|
||||
}
|
||||
} else {
|
||||
if let Some(mtime) = mtime {
|
||||
self.mtimes.insert(path.clone(), mtime);
|
||||
let extension = path
|
||||
.extension()
|
||||
.and_then(|x| x.to_str())
|
||||
.unwrap_or_default()
|
||||
.to_owned();
|
||||
|
||||
self.extensions.insert(extension.to_owned());
|
||||
|
||||
// On incremental scans, check mtime to skip unchanged files.
|
||||
// On the first scan, track mtimes while still scanning every file.
|
||||
let changed = if self.has_scanned_once {
|
||||
match mtime {
|
||||
Some(mtime) => {
|
||||
let prev = self.mtimes.insert(path.clone(), mtime);
|
||||
prev.is_none_or(|prev| prev != mtime)
|
||||
}
|
||||
None => true,
|
||||
}
|
||||
} else {
|
||||
if let Some(mtime) = mtime {
|
||||
self.mtimes.insert(path.clone(), mtime);
|
||||
}
|
||||
|
||||
true
|
||||
};
|
||||
|
||||
if !changed {
|
||||
continue;
|
||||
}
|
||||
|
||||
true
|
||||
};
|
||||
if let Ok(file) = path.clone().into_os_string().into_string() {
|
||||
changed_files.push(file);
|
||||
}
|
||||
|
||||
if !changed {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Ok(file) = path.clone().into_os_string().into_string() {
|
||||
changed_files.push(file);
|
||||
}
|
||||
|
||||
match extension.as_str() {
|
||||
// Special handing for CSS files, we don't want to extract candidates from
|
||||
// these files, but we do want to extract used CSS variables.
|
||||
"css" => css_files.push(path),
|
||||
_ => content_paths.push((path, extension)),
|
||||
match extension.as_str() {
|
||||
// Special handing for CSS files, we don't want to extract candidates from
|
||||
// these files, but we do want to extract used CSS variables.
|
||||
"css" => css_files.push(path),
|
||||
_ => content_paths.push((path, extension)),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -558,36 +616,50 @@ where
|
|||
a
|
||||
})
|
||||
.into_iter()
|
||||
.map(|s| unsafe { String::from_utf8_unchecked(s.to_vec()) })
|
||||
.filter_map(|s| String::from_utf8(s.to_vec()).ok())
|
||||
.collect()
|
||||
}
|
||||
|
||||
type WalkEntry = (PathBuf, bool, String, Option<SystemTime>);
|
||||
#[derive(Debug)]
|
||||
enum WalkEntry {
|
||||
Dir(PathBuf),
|
||||
File {
|
||||
path: PathBuf,
|
||||
mtime: Option<SystemTime>,
|
||||
|
||||
/// Whether the path itself is a symlink
|
||||
is_symlink: bool,
|
||||
},
|
||||
}
|
||||
|
||||
impl From<ignore::DirEntry> for WalkEntry {
|
||||
fn from(entry: ignore::DirEntry) -> Self {
|
||||
let is_dir = entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false);
|
||||
let is_symlink = entry.path_is_symlink();
|
||||
let path = entry.into_path();
|
||||
|
||||
if is_dir {
|
||||
WalkEntry::Dir(path)
|
||||
} else {
|
||||
let mtime = path.metadata().ok().and_then(|m| m.modified().ok());
|
||||
WalkEntry::File {
|
||||
path,
|
||||
mtime,
|
||||
is_symlink,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Walk the file system synchronously. Used for the initial build where the overhead of spawning
|
||||
/// parallel walker threads is not worth it.
|
||||
#[tracing::instrument(skip_all)]
|
||||
fn walk_synchronous(walker: &mut WalkBuilder) -> Vec<WalkEntry> {
|
||||
let mut entries = vec![];
|
||||
|
||||
for entry in walker.build().filter_map(Result::ok) {
|
||||
let is_dir = entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false);
|
||||
let path = entry.into_path();
|
||||
|
||||
if is_dir {
|
||||
entries.push((path, true, String::new(), None));
|
||||
} else {
|
||||
let ext = path
|
||||
.extension()
|
||||
.and_then(|x| x.to_str())
|
||||
.unwrap_or_default()
|
||||
.to_owned();
|
||||
let mtime = path.metadata().ok().and_then(|m| m.modified().ok());
|
||||
entries.push((path, false, ext, mtime));
|
||||
}
|
||||
}
|
||||
|
||||
entries
|
||||
walker
|
||||
.build()
|
||||
.filter_map(Result::ok)
|
||||
.map(WalkEntry::from)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Walk the file system in parallel. Used in watch mode where the parallel walker overhead is
|
||||
|
|
@ -620,20 +692,7 @@ fn walk_parallel(walker: &mut WalkBuilder) -> Vec<WalkEntry> {
|
|||
return ignore::WalkState::Continue;
|
||||
};
|
||||
|
||||
let is_dir = entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false);
|
||||
let path = entry.into_path();
|
||||
|
||||
if is_dir {
|
||||
buf.local.push((path, true, String::new(), None));
|
||||
} else {
|
||||
let ext = path
|
||||
.extension()
|
||||
.and_then(|x| x.to_str())
|
||||
.unwrap_or_default()
|
||||
.to_owned();
|
||||
let mtime = path.metadata().ok().and_then(|m| m.modified().ok());
|
||||
buf.local.push((path, false, ext, mtime));
|
||||
}
|
||||
buf.local.push(WalkEntry::from(entry));
|
||||
|
||||
if buf.local.len() >= 256 {
|
||||
buf.shared.lock().unwrap().append(&mut buf.local);
|
||||
|
|
|
|||
|
|
@ -763,12 +763,11 @@ pub fn public_source_entries_to_private_source_entries(
|
|||
.collect::<Vec<_>>();
|
||||
|
||||
// Compiled `.gitignore` matchers are cached per directory so we read and parse each
|
||||
// `.gitignore` file at most once, even though entries commonly share ancestor directories
|
||||
// (e.g. the repository root). A cached `None` means the directory has no `.gitignore` file.
|
||||
// `.gitignore` file at most once, even though entries commonly share ancestor directories (e.g.
|
||||
// the repository root). A cached `None` means the directory has no `.gitignore` file.
|
||||
let mut gitignores: FxHashMap<PathBuf, Option<Gitignore>> = FxHashMap::default();
|
||||
|
||||
// Boundary for the `.gitignore` walk when a source is not inside a git repository (see
|
||||
// below).
|
||||
// Boundary for the `.gitignore` walk when a source is not inside a git repository (see below).
|
||||
let cwd = std::env::current_dir()
|
||||
.map(|cwd| dunce::canonicalize(&cwd).unwrap_or(cwd))
|
||||
.ok();
|
||||
|
|
@ -790,18 +789,39 @@ pub fn public_source_entries_to_private_source_entries(
|
|||
let gitignore = gitignores.entry(dir.to_path_buf()).or_insert_with(|| {
|
||||
let path = dir.join(".gitignore");
|
||||
|
||||
// `Gitignore::new` roots the matcher at the directory
|
||||
// containing the file, so patterns match relative to it.
|
||||
// `Gitignore::new` roots the matcher at the directory containing the file,
|
||||
// so patterns match relative to it.
|
||||
path.is_file().then(|| Gitignore::new(&path).0)
|
||||
});
|
||||
|
||||
if let Some(gitignore) = gitignore {
|
||||
if gitignore
|
||||
.matched_path_or_any_parents(&base, true)
|
||||
.is_ignore()
|
||||
{
|
||||
source = SourceEntry::External { base: base.into() };
|
||||
break;
|
||||
// Only `.gitignore` files in ancestors of `base` can ignore `base` itself.
|
||||
// Patterns in `base`'s own `.gitignore` only match paths _inside_ `base`, never
|
||||
// `base` itself (the file walker still applies them to `base`'s contents).
|
||||
//
|
||||
// Skipping `base`'s own `.gitignore` also prevents a false positive for
|
||||
// whitelist style `.gitignore` files, because relativizing `base` against
|
||||
// itself yields the empty path, which incorrectly matches `/*`.
|
||||
//
|
||||
// E.g.:
|
||||
//
|
||||
// ```gitignore
|
||||
// /*
|
||||
// !/.gitignore
|
||||
// !/app
|
||||
// !/public
|
||||
// ```
|
||||
//
|
||||
// Everything inside `base` except `.gitignore`, `app` and `public` is ignored,
|
||||
// but `base` itself is not.
|
||||
if dir != base {
|
||||
if let Some(gitignore) = gitignore {
|
||||
if gitignore
|
||||
.matched_path_or_any_parents(&base, true)
|
||||
.is_ignore()
|
||||
{
|
||||
source = SourceEntry::External { base: base.into() };
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -810,12 +830,11 @@ pub fn public_source_entries_to_private_source_entries(
|
|||
break;
|
||||
}
|
||||
|
||||
// Without a git repository there is no repository root to stop at. Stop
|
||||
// once the directory contains the current working directory instead, so
|
||||
// `.gitignore` files outside of the project (e.g. in the user's home
|
||||
// directory) can never promote a source to an external source. Note that
|
||||
// the file walker still applies those `.gitignore` files when deciding
|
||||
// which files to scan.
|
||||
// Without a git repository there is no repository root to stop at. Stop once
|
||||
// the directory contains the current working directory instead, so `.gitignore`
|
||||
// files outside of the project (e.g. in the user's home directory) can never
|
||||
// promote a source to an external source. Note that the file walker still
|
||||
// applies those `.gitignore` files when deciding which files to scan.
|
||||
if !inside_git_repo && cwd.as_ref().is_some_and(|cwd| cwd.starts_with(dir)) {
|
||||
break;
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -2276,6 +2276,70 @@ test(
|
|||
},
|
||||
)
|
||||
|
||||
// https://github.com/tailwindlabs/tailwindcss/discussions/20382
|
||||
test(
|
||||
'auto source detection respects allow-list .gitignore files',
|
||||
{
|
||||
fs: {
|
||||
'package.json': json`
|
||||
{
|
||||
"dependencies": {
|
||||
"tailwindcss": "workspace:^",
|
||||
"@tailwindcss/cli": "workspace:^"
|
||||
}
|
||||
}
|
||||
`,
|
||||
'.gitignore': txt`
|
||||
/*
|
||||
!/.gitignore
|
||||
!/app
|
||||
!/public
|
||||
!/package.json
|
||||
`,
|
||||
'app/root.css': css` @import 'tailwindcss/utilities'; `,
|
||||
// Included by the `!/app` pattern in `.gitignore`
|
||||
//
|
||||
// → Should be included
|
||||
'app/index.html': html`
|
||||
<div class="content-['app/index.html']"></div>
|
||||
`,
|
||||
// Included by the `!/public` pattern in `.gitignore`
|
||||
//
|
||||
// → Should be included
|
||||
'public/index.html': html`
|
||||
<div class="content-['public/index.html']"></div>
|
||||
`,
|
||||
// Ignored by the `/*` in `.gitignore`
|
||||
//
|
||||
// → Should be ignored
|
||||
'build/index.html': html`
|
||||
<div class="content-['build/index.html']"></div>
|
||||
`,
|
||||
// Ignored by the `/*` in `.gitignore` and the default `node_modules` rules
|
||||
//
|
||||
// → Should be ignored
|
||||
'node_modules/my-ui-lib/index.html': html`
|
||||
<div
|
||||
class="content-['node_modules/my-ui-lib/index.html']"
|
||||
></div>
|
||||
`,
|
||||
},
|
||||
},
|
||||
async ({ fs, exec }) => {
|
||||
await exec('pnpm tailwindcss --input app/root.css --output dist/out.css')
|
||||
|
||||
await fs.expectFileToContain('dist/out.css', [
|
||||
candidate`content-['app/index.html']`,
|
||||
candidate`content-['public/index.html']`,
|
||||
])
|
||||
|
||||
await fs.expectFileNotToContain('dist/out.css', [
|
||||
candidate`content-['build/index.html']`,
|
||||
candidate`content-['node_modules/my-ui-lib/index.html']`,
|
||||
])
|
||||
},
|
||||
)
|
||||
|
||||
test(
|
||||
'@source works with symlinks (referencing folder in current folder)',
|
||||
{
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { css, js, json, test } from '../utils'
|
||||
import { css, js, json, test, yaml } from '../utils'
|
||||
|
||||
// This test runs the wasm build using the `node:wasi` runtime.
|
||||
//
|
||||
|
|
@ -57,3 +57,187 @@ testFn(
|
|||
`)
|
||||
},
|
||||
)
|
||||
|
||||
testFn(
|
||||
'`@tailwindcss/oxide` falls back to the wasm build when no native binding is available',
|
||||
{
|
||||
fs: {
|
||||
'package.json': json`
|
||||
{
|
||||
"dependencies": {
|
||||
"@tailwindcss/oxide": "workspace:^"
|
||||
}
|
||||
}
|
||||
`,
|
||||
'pnpm-workspace.yaml': yaml`
|
||||
# Trick pnpm in only supporting an architecture that @tailwindcss/oxide
|
||||
# doesn't support, and therefore should fallback to the wasm version.
|
||||
supportedArchitectures:
|
||||
os:
|
||||
- openbsd
|
||||
cpu:
|
||||
- x64
|
||||
`,
|
||||
'src/index.js': js`
|
||||
const className = "content-['src/index.js']"
|
||||
module.exports = { className }
|
||||
`,
|
||||
'index.mjs': js`
|
||||
import { createRequire } from 'node:module'
|
||||
import { join } from 'node:path'
|
||||
|
||||
let require = createRequire(import.meta.url)
|
||||
let { Scanner } = require('@tailwindcss/oxide')
|
||||
|
||||
let loaded = Object.keys(require.cache)
|
||||
|
||||
let scanner = new Scanner({
|
||||
sources: [
|
||||
{
|
||||
base: join(process.cwd(), 'src'),
|
||||
pattern: '**/*',
|
||||
negated: false,
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
native: loaded.filter((file) => file.endsWith('.node')),
|
||||
wasi: loaded.some((file) => file.endsWith('tailwindcss-oxide.wasi.cjs')),
|
||||
candidates: scanner.scan(),
|
||||
}),
|
||||
)
|
||||
process.exit()
|
||||
`,
|
||||
},
|
||||
},
|
||||
async ({ expect, exec }) => {
|
||||
// Since vitest runs under `pnpm run`, pnpm's bin shims export a NODE_PATH
|
||||
// that includes the repository's hidden hoist directory
|
||||
// (`node_modules/.pnpm/node_modules`), which links every workspace package,
|
||||
// including all native `@tailwindcss/oxide-*` bindings.
|
||||
//
|
||||
// Node uses `NODE_PATH` exactly when the local `node_modules` lookup fails,
|
||||
// which would defeat the simulated unsupported platform, so clear it.
|
||||
let output = await exec(`node index.mjs`, { env: { NODE_PATH: '' } })
|
||||
let { native, wasi, candidates } = JSON.parse(output)
|
||||
|
||||
// No native binding was installed or loaded, ...
|
||||
expect(native).toEqual([])
|
||||
|
||||
// ... the wasm32-wasi binding is what actually loaded, ...
|
||||
expect(wasi).toBe(true)
|
||||
|
||||
// ... and scanning real files on disk works through it.
|
||||
expect(candidates).toMatchInlineSnapshot(`
|
||||
[
|
||||
"className",
|
||||
"const",
|
||||
"content-['src/index.js']",
|
||||
"exports",
|
||||
]
|
||||
`)
|
||||
},
|
||||
)
|
||||
|
||||
testFn(
|
||||
'the wasm build loads even when preopening the filesystem root is denied',
|
||||
{
|
||||
fs: {
|
||||
'package.json': json`
|
||||
{
|
||||
"dependencies": {
|
||||
"@tailwindcss/oxide": "workspace:^"
|
||||
}
|
||||
}
|
||||
`,
|
||||
'pnpm-workspace.yaml': yaml`
|
||||
# Trick pnpm in only supporting an architecture that @tailwindcss/oxide
|
||||
# doesn't support, and therefore should fallback to the wasm version.
|
||||
supportedArchitectures:
|
||||
os:
|
||||
- openbsd
|
||||
cpu:
|
||||
- x64
|
||||
`,
|
||||
// The wasm bindings generated by `@napi-rs/cli` preopen the filesystem
|
||||
// root, which sandboxed platforms (e.g. OpenHarmony, Android) deny with
|
||||
// `UVWASI_EACCES`, making the wasm fallback fail to load on exactly the
|
||||
// platforms that need it.
|
||||
//
|
||||
// We patch `@napi-rs/cli`'s templates to retry with narrower preopens
|
||||
// (see `patches/@napi-rs__cli@3.7.4.patch`). Simulate such a sandbox by
|
||||
// denying `/` preopens.
|
||||
'preload.cjs': js`
|
||||
const wasi = require('node:wasi')
|
||||
const RealWASI = wasi.WASI
|
||||
|
||||
wasi.WASI = class WASI extends RealWASI {
|
||||
constructor(options) {
|
||||
if (options?.preopens?.['/'] !== undefined) {
|
||||
const error = new Error('UVWASI_EACCES, uvwasi_init')
|
||||
error.code = 'UVWASI_EACCES'
|
||||
error.syscall = 'uvwasi_init'
|
||||
throw error
|
||||
}
|
||||
super(options)
|
||||
}
|
||||
}
|
||||
`,
|
||||
'src/index.js': js`
|
||||
const className = "content-['src/index.js']"
|
||||
module.exports = { className }
|
||||
`,
|
||||
'index.mjs': js`
|
||||
import { createRequire } from 'node:module'
|
||||
import { join } from 'node:path'
|
||||
|
||||
let require = createRequire(import.meta.url)
|
||||
let { Scanner } = require('@tailwindcss/oxide')
|
||||
|
||||
let loaded = Object.keys(require.cache)
|
||||
|
||||
let scanner = new Scanner({
|
||||
sources: [
|
||||
{
|
||||
base: join(process.cwd(), 'src'),
|
||||
pattern: '**/*',
|
||||
negated: false,
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
wasi: loaded.some((file) => file.endsWith('tailwindcss-oxide.wasi.cjs')),
|
||||
candidates: scanner.scan(),
|
||||
}),
|
||||
)
|
||||
process.exit()
|
||||
`,
|
||||
},
|
||||
},
|
||||
async ({ expect, exec }) => {
|
||||
// See the note about NODE_PATH in the test above.
|
||||
let output = await exec(`node --require ./preload.cjs index.mjs`, { env: { NODE_PATH: '' } })
|
||||
|
||||
// Only parse the first line, because Node prints an `ExperimentalWarning`
|
||||
// about WASI to stderr, which `exec` appends to the output.
|
||||
let { wasi, candidates } = JSON.parse(output.trim().split('\n')[0])
|
||||
|
||||
// The wasm32-wasi binding loaded despite `/` being denied, ...
|
||||
expect(wasi).toBe(true)
|
||||
|
||||
// ... and scanning files under the current working directory still works
|
||||
// through the narrower preopen.
|
||||
expect(candidates).toMatchInlineSnapshot(`
|
||||
[
|
||||
"className",
|
||||
"const",
|
||||
"content-['src/index.js']",
|
||||
"exports",
|
||||
]
|
||||
`)
|
||||
},
|
||||
)
|
||||
|
|
|
|||
83
integrations/turbopack/loader.test.ts
Normal file
83
integrations/turbopack/loader.test.ts
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
import { candidate, css, fetchStyles, js, json, jsx, retryAssertion, test } from '../utils'
|
||||
|
||||
test(
|
||||
'@tailwindcss/turbopack loader (dev)',
|
||||
{
|
||||
timeout: 120_000,
|
||||
fs: {
|
||||
'package.json': json`
|
||||
{
|
||||
"dependencies": {
|
||||
"next": "^16.2.7",
|
||||
"react": "^19.2.7",
|
||||
"react-dom": "^19.2.7",
|
||||
"tailwindcss": "workspace:^",
|
||||
"@tailwindcss/turbopack": "workspace:^"
|
||||
}
|
||||
}
|
||||
`,
|
||||
'next.config.mjs': js`
|
||||
export default {
|
||||
turbopack: {
|
||||
rules: {
|
||||
'*.css': {
|
||||
loaders: ['@tailwindcss/turbopack'],
|
||||
as: '*.css',
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
`,
|
||||
'app/layout.js': jsx`
|
||||
import './globals.css'
|
||||
|
||||
export default function RootLayout({ children }) {
|
||||
return (
|
||||
<html>
|
||||
<body>{children}</body>
|
||||
</html>
|
||||
)
|
||||
}
|
||||
`,
|
||||
'app/page.js': jsx`
|
||||
export default function Page() {
|
||||
return <div className="flex">Hello, Next.js!</div>
|
||||
}
|
||||
`,
|
||||
'app/globals.css': css` @import 'tailwindcss'; `,
|
||||
},
|
||||
},
|
||||
async ({ fs, spawn, expect }) => {
|
||||
let process = await spawn('pnpm next dev')
|
||||
|
||||
let url = ''
|
||||
await process.onStdout((message) => {
|
||||
let match = /Local:\s*(http.*)/.exec(message)
|
||||
if (match) url = match[1]
|
||||
return Boolean(url)
|
||||
})
|
||||
|
||||
await process.onStdout((message) => message.includes('Ready in'))
|
||||
|
||||
await retryAssertion(async () => {
|
||||
let styles = await fetchStyles(url)
|
||||
expect(styles).toContain(candidate`flex`)
|
||||
expect(styles).not.toContain(candidate`underline`)
|
||||
})
|
||||
|
||||
await fs.write(
|
||||
'app/page.js',
|
||||
jsx`
|
||||
export default function Page() {
|
||||
return <div className="flex underline">Hello, Next.js!</div>
|
||||
}
|
||||
`,
|
||||
)
|
||||
|
||||
await retryAssertion(async () => {
|
||||
let styles = await fetchStyles(url)
|
||||
expect(styles).toContain(candidate`flex`)
|
||||
expect(styles).toContain(candidate`underline`)
|
||||
})
|
||||
},
|
||||
)
|
||||
|
|
@ -2557,7 +2557,7 @@ test(
|
|||
@import './utilities.css';
|
||||
@import './generated/ignore-me.css';
|
||||
`,
|
||||
'src/generated/.gitignore': `
|
||||
'src/generated/.gitignore': txt`
|
||||
*
|
||||
!.gitignore
|
||||
`,
|
||||
|
|
@ -2817,7 +2817,7 @@ test(
|
|||
<div class="ring-3"></div>
|
||||
|
||||
--- ./src/input.css ---
|
||||
@import 'tailwindcss';
|
||||
@import 'tailwindcss';
|
||||
|
||||
/*
|
||||
The default border color has changed to \`currentcolor\` in Tailwind CSS v4,
|
||||
|
|
|
|||
|
|
@ -612,6 +612,7 @@ function overwriteVersionsInPnpmWorkspace(content: string): string {
|
|||
workspace.overrides['@tailwindcss/upgrade>tailwindcss'] = resolveVersion(pkg)
|
||||
workspace.overrides['@tailwindcss/cli>tailwindcss'] = resolveVersion(pkg)
|
||||
workspace.overrides['@tailwindcss/postcss>tailwindcss'] = resolveVersion(pkg)
|
||||
workspace.overrides['@tailwindcss/turbopack>tailwindcss'] = resolveVersion(pkg)
|
||||
workspace.overrides['@tailwindcss/vite>tailwindcss'] = resolveVersion(pkg)
|
||||
workspace.overrides['@tailwindcss/webpack>tailwindcss'] = resolveVersion(pkg)
|
||||
} else {
|
||||
|
|
|
|||
193
integrations/vite/bundled-dev.test.ts
Normal file
193
integrations/vite/bundled-dev.test.ts
Normal file
|
|
@ -0,0 +1,193 @@
|
|||
import path from 'node:path'
|
||||
import { candidate, css, html, json, retryAssertion, test, ts, txt, yaml } from '../utils'
|
||||
|
||||
// Vite's experimental `bundledDev` mode invokes the `hotUpdate` hook without a
|
||||
// `server`, which used to crash the plugin on every file edit.
|
||||
//
|
||||
// - https://github.com/tailwindlabs/tailwindcss/issues/20378
|
||||
// - https://vite.dev/blog/announcing-vite8-1#experimental-bundled-dev-mode
|
||||
test(
|
||||
'dev mode (experimental `bundledDev`)',
|
||||
{
|
||||
fs: {
|
||||
'package.json': json`{}`,
|
||||
'pnpm-workspace.yaml': yaml`
|
||||
#
|
||||
packages:
|
||||
- project-a
|
||||
`,
|
||||
'project-a/package.json': txt`
|
||||
{
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@tailwindcss/vite": "workspace:^",
|
||||
"tailwindcss": "workspace:^"
|
||||
},
|
||||
"devDependencies": {
|
||||
"vite": "^8.1"
|
||||
}
|
||||
}
|
||||
`,
|
||||
'project-a/vite.config.ts': ts`
|
||||
import tailwindcss from '@tailwindcss/vite'
|
||||
import { defineConfig } from 'vite'
|
||||
|
||||
export default defineConfig({
|
||||
experimental: {
|
||||
bundledDev: true,
|
||||
},
|
||||
plugins: [tailwindcss()],
|
||||
})
|
||||
`,
|
||||
'project-a/index.html': html`
|
||||
<head>
|
||||
<link rel="stylesheet" href="./src/index.css" />
|
||||
</head>
|
||||
<body>
|
||||
<div class="underline">Hello, world!</div>
|
||||
</body>
|
||||
`,
|
||||
'project-a/src/index.css': css`
|
||||
@reference 'tailwindcss/theme';
|
||||
@import 'tailwindcss/utilities';
|
||||
@source '../../project-b/src/**/*.html';
|
||||
`,
|
||||
'project-b/src/index.html': html`
|
||||
<div class="flex" />
|
||||
`,
|
||||
},
|
||||
},
|
||||
async ({ root, spawn, fs, expect }) => {
|
||||
let process = await spawn('pnpm vite dev', {
|
||||
cwd: path.join(root, 'project-a'),
|
||||
env: {
|
||||
// Some CI machines have an upstream rolldown bug where its file watcher
|
||||
// never delivers a single event. The debug output is the only way to
|
||||
// tell that apart from a real regression (see below).
|
||||
DEBUG: 'vite:full-bundle-mode',
|
||||
},
|
||||
})
|
||||
|
||||
// Any debug output beyond the "INITIAL:" startup lines proves rolldown's
|
||||
// watcher delivered at least one file event.
|
||||
let watcherAlive = false
|
||||
|
||||
// `hotUpdate` errors don't kill the dev server, they are only printed to
|
||||
// stderr. Track them explicitly so a crash fails the test even if the
|
||||
// rebuild happens to succeed anyway.
|
||||
let pluginErrors: string[] = []
|
||||
process.onStderr((message) => {
|
||||
if (message.includes('vite:full-bundle-mode')) {
|
||||
if (!message.includes('INITIAL:')) watcherAlive = true
|
||||
} else if (message.includes('@tailwindcss/vite')) {
|
||||
pluginErrors.push(message)
|
||||
}
|
||||
return false
|
||||
})
|
||||
|
||||
let url = ''
|
||||
await process.onStdout((m) => {
|
||||
let match = /Local:\s*(http.*)\//.exec(m)
|
||||
if (match) url = match[1]
|
||||
return Boolean(url)
|
||||
})
|
||||
|
||||
// In `bundledDev` mode the stylesheet is not served separately. Instead the
|
||||
// generated CSS is embedded in the bundled JS and injected at runtime, so
|
||||
// extract the bundle from the served HTML. While the bundle is being built,
|
||||
// Vite serves a temporary fallback page instead.
|
||||
//
|
||||
// The bundle can be split into multiple chunks (e.g. the HMR client runtime
|
||||
// and the app itself), and the chunk containing the CSS is not always the
|
||||
// first one, so fetch every referenced script and stylesheet.
|
||||
async function fetchBundledStyles(): Promise<string> {
|
||||
let index = await fetch(`${url}/`)
|
||||
let html = await index.text()
|
||||
if (html.includes('__vite_is_fallback_page__')) {
|
||||
throw new Error('Bundling still in progress')
|
||||
}
|
||||
|
||||
let sources = [
|
||||
...html.matchAll(/<script[^>]*\ssrc="([^"]+)"/g),
|
||||
...html.matchAll(/<link[^>]*\srel="stylesheet"[^>]*\shref="([^"]+)"/g),
|
||||
].map((match) => match[1])
|
||||
if (sources.length === 0) throw new Error(`No scripts or stylesheets found in:\n\n${html}`)
|
||||
|
||||
let contents = await Promise.all(
|
||||
sources.map(async (src) => {
|
||||
let response = await fetch(new URL(src, `${url}/`))
|
||||
return await response.text()
|
||||
}),
|
||||
)
|
||||
return contents.join('\n')
|
||||
}
|
||||
|
||||
await retryAssertion(
|
||||
async () => {
|
||||
let styles = await fetchBundledStyles()
|
||||
expect(styles).toContain(candidate`underline`)
|
||||
expect(styles).toContain(candidate`flex`)
|
||||
},
|
||||
{ timeout: 10_000, delay: 100 },
|
||||
)
|
||||
|
||||
// Edit a module file and a manually `@source`d file. Without a connected
|
||||
// HMR websocket client (this test only uses HTTP fetches), a file change
|
||||
// does not trigger an eager rebuild — it only marks the bundle as stale,
|
||||
// and the next fetch kicks off the rebuild. So poll with fetches without
|
||||
// touching the files again: rewriting would re-mark the bundle stale right
|
||||
// before each fetch and the rebuild could never be observed.
|
||||
await fs.write(
|
||||
'project-a/index.html',
|
||||
html`
|
||||
<head>
|
||||
<link rel="stylesheet" href="./src/index.css" />
|
||||
</head>
|
||||
<body>
|
||||
<div class="underline m-2">Hello, world!</div>
|
||||
</body>
|
||||
`,
|
||||
)
|
||||
|
||||
await fs.write('project-b/src/index.html', html`
|
||||
<div class="flex font-bold" />
|
||||
`)
|
||||
|
||||
try {
|
||||
await retryAssertion(
|
||||
async () => {
|
||||
let styles = await fetchBundledStyles()
|
||||
expect(styles).toContain(candidate`underline`)
|
||||
expect(styles).toContain(candidate`flex`)
|
||||
expect(styles).toContain(candidate`m-2`)
|
||||
expect(styles).toContain(candidate`font-bold`)
|
||||
},
|
||||
{ timeout: 15_000, delay: 100 },
|
||||
)
|
||||
} catch (error) {
|
||||
// If rolldown's watcher delivered any file event, the updates were
|
||||
// genuinely dropped somewhere along the way — a real failure.
|
||||
if (watcherAlive) throw error
|
||||
|
||||
// Otherwise the watcher never delivered a single event, so the updates
|
||||
// can never be observed no matter how long we wait — an upstream
|
||||
// rolldown bug on some CI machines, not a plugin regression. The crash
|
||||
// regression this test guards is still covered: `hotUpdate` is driven
|
||||
// by Vite's own (working) chokidar watcher and asserted via
|
||||
// `pluginErrors` below.
|
||||
//
|
||||
// Skipping is only sound while the server still healthily serves the
|
||||
// original bundle. If it stopped serving (crashed, or wedged on the
|
||||
// fallback page), that's real breakage a silent watcher must not mask.
|
||||
console.log(error)
|
||||
let styles = await fetchBundledStyles()
|
||||
expect(styles).toContain(candidate`underline`)
|
||||
expect(styles).toContain(candidate`flex`)
|
||||
console.warn(
|
||||
'Skipping update assertions: rolldown’s file watcher delivered no events on this machine.',
|
||||
)
|
||||
}
|
||||
|
||||
expect(pluginErrors).toEqual([])
|
||||
},
|
||||
)
|
||||
|
|
@ -294,6 +294,113 @@ describe.each(['postcss', 'lightningcss'])('%s', (transformer) => {
|
|||
},
|
||||
)
|
||||
|
||||
// https://github.com/tailwindlabs/tailwindcss/issues/20346
|
||||
test(
|
||||
'dev mode + symlinked `@source` files pick up changes to the real file',
|
||||
{
|
||||
fs: {
|
||||
'package.json': json`{}`,
|
||||
'pnpm-workspace.yaml': yaml`
|
||||
#
|
||||
packages:
|
||||
- project-a
|
||||
- packages/*
|
||||
`,
|
||||
'project-a/package.json': txt`
|
||||
{
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@tailwindcss/vite": "workspace:^",
|
||||
"repro-package": "workspace:*",
|
||||
"tailwindcss": "workspace:^"
|
||||
},
|
||||
"devDependencies": {
|
||||
${transformer === 'lightningcss' ? `"lightningcss": "^1",` : ''}
|
||||
"vite": "^7"
|
||||
}
|
||||
}
|
||||
`,
|
||||
'project-a/vite.config.ts': ts`
|
||||
import tailwindcss from '@tailwindcss/vite'
|
||||
import { defineConfig } from 'vite'
|
||||
|
||||
export default defineConfig({
|
||||
css: ${transformer === 'postcss' ? '{}' : "{ transformer: 'lightningcss' }"},
|
||||
build: { cssMinify: false },
|
||||
plugins: [tailwindcss()],
|
||||
})
|
||||
`,
|
||||
'project-a/index.html': html`
|
||||
<head>
|
||||
<link rel="stylesheet" href="./src/index.css" />
|
||||
</head>
|
||||
<body>
|
||||
<div class="underline">Hello, world!</div>
|
||||
</body>
|
||||
`,
|
||||
|
||||
// The `@source` points through the `node_modules` symlink that pnpm
|
||||
// creates for the workspace package. Vite's file watcher ignores
|
||||
// `node_modules` by default, so the symlinked path can not be watched.
|
||||
// The real file (in `packages/repro-package`) has to be watched
|
||||
// instead.
|
||||
'project-a/src/index.css': css`
|
||||
@reference 'tailwindcss/theme';
|
||||
@import 'tailwindcss/utilities';
|
||||
@source '../node_modules/repro-package/source.html';
|
||||
`,
|
||||
'packages/repro-package/package.json': json`
|
||||
{
|
||||
"name": "repro-package",
|
||||
"private": true,
|
||||
"version": "1.0.0"
|
||||
}
|
||||
`,
|
||||
'packages/repro-package/source.html': html`
|
||||
<div class="content-['v1']">
|
||||
Hello, world!
|
||||
</div>
|
||||
`,
|
||||
},
|
||||
},
|
||||
async ({ root, spawn, fs, expect }) => {
|
||||
let process = await spawn('pnpm vite dev', {
|
||||
cwd: path.join(root, 'project-a'),
|
||||
})
|
||||
await process.onStdout((m) => m.includes('ready in'))
|
||||
|
||||
let url = ''
|
||||
await process.onStdout((m) => {
|
||||
let match = /Local:\s*(http.*)\//.exec(m)
|
||||
if (match) url = match[1]
|
||||
return Boolean(url)
|
||||
})
|
||||
|
||||
await retryAssertion(async () => {
|
||||
let styles = await fetchStyles(url, '/index.html')
|
||||
expect(styles).toContain(candidate`underline`)
|
||||
expect(styles).toContain(candidate`content-['v1']`)
|
||||
})
|
||||
|
||||
await retryAssertion(async () => {
|
||||
// Changes to the real file (behind the symlink) should be picked up
|
||||
await fs.write(
|
||||
'packages/repro-package/source.html',
|
||||
html`
|
||||
<div class="content-['v1'] content-['v2']">
|
||||
Hello, world!
|
||||
</div>
|
||||
`,
|
||||
)
|
||||
|
||||
let styles = await fetchStyles(url)
|
||||
expect(styles).toContain(candidate`underline`)
|
||||
expect(styles).toContain(candidate`content-['v1']`)
|
||||
expect(styles).toContain(candidate`content-['v2']`)
|
||||
})
|
||||
},
|
||||
)
|
||||
|
||||
test(
|
||||
'watch mode',
|
||||
{
|
||||
|
|
@ -473,11 +580,11 @@ describe.each(['postcss', 'lightningcss'])('%s', (transformer) => {
|
|||
},
|
||||
)
|
||||
|
||||
describe.sequential.each([['^6'], ['7.0.8'], ['7.1.12'], ['7.3.1'], ['8.0.0']])(
|
||||
describe.each([['^6'], ['7.0.8'], ['7.1.12'], ['7.3.1'], ['8.0.0']])(
|
||||
'Using Vite %s',
|
||||
(version) => {
|
||||
test(
|
||||
'external source file changes trigger a full reload',
|
||||
'external source file changes update the CSS',
|
||||
{
|
||||
fs: {
|
||||
'package.json': json`{}`,
|
||||
|
|
@ -554,26 +661,33 @@ describe.each(['postcss', 'lightningcss'])('%s', (transformer) => {
|
|||
expect(styles).toContain(candidate`content-['project-b/src/index.php']`)
|
||||
})
|
||||
|
||||
// Flush all messages so that we can be sure the next messages are from
|
||||
// the file changes we're about to make
|
||||
// Flush all messages so that we can be sure the next messages are
|
||||
// from the file changes we're about to make
|
||||
process.flush()
|
||||
|
||||
// Changing an external .php file should trigger a full reload
|
||||
// Changing an external .php file hot-updates the generated CSS
|
||||
{
|
||||
await fs.write(
|
||||
'project-b/src/index.php',
|
||||
txt`<div class="content-['updated:project-b/src/index.php']"></div>`,
|
||||
)
|
||||
|
||||
// Ensure the page reloaded
|
||||
// On Vite < 7.1, Vite itself hard-invalidates watched files that
|
||||
// aren't part of the module graph and reloads the page.
|
||||
//
|
||||
// On newer versions nothing reloads the page: the CSS hot-updates
|
||||
// through the regular pipeline because the changed file is a
|
||||
// watch dependency of the CSS root.
|
||||
//
|
||||
// Reloading the page for external template changes is the
|
||||
// responsibility of the backend integration (e.g. `laravel-vite-plugin`'s `refresh` option, or `vite-plugin-full-reload`).
|
||||
//
|
||||
// https://github.com/tailwindlabs/tailwindcss/issues/20411
|
||||
if (version === '^6' || version === '7.0.8') {
|
||||
await process.onStdout((m) => m.includes('page reload') && m.includes('index.php'))
|
||||
} else {
|
||||
await process.onStderr(
|
||||
(m) => m.includes('vite:hmr (client)') && m.includes('index.php'),
|
||||
)
|
||||
await process.onStdout((m) => m.includes('hmr update') && m.includes('index.css'))
|
||||
}
|
||||
await process.onStderr((m) => m.includes('vite:hmr (ssr)') && m.includes('index.php'))
|
||||
|
||||
// Ensure the styles were regenerated with the new content
|
||||
let styles = await fetchStyles(url, '/index.html')
|
||||
|
|
@ -746,7 +860,6 @@ describe.each(['postcss', 'lightningcss'])('%s', (transformer) => {
|
|||
let styles = await fetchStyles(url, '/index.html')
|
||||
expect(styles).toContain(candidate`content-['updated:src/lazy.tsx']`)
|
||||
})
|
||||
expect(await fs.read('project-a/hmr.log')).not.toContain('full-reload')
|
||||
}
|
||||
|
||||
// The same holds for a custom file type as long as some file of the
|
||||
|
|
@ -761,7 +874,6 @@ describe.each(['postcss', 'lightningcss'])('%s', (transformer) => {
|
|||
let styles = await fetchStyles(url, '/index.html')
|
||||
expect(styles).toContain(candidate`content-['updated:src/comp-b.custom']`)
|
||||
})
|
||||
expect(await fs.read('project-a/hmr.log')).not.toContain('full-reload')
|
||||
}
|
||||
|
||||
// Changing a scanned stylesheet that is not part of the module graph
|
||||
|
|
@ -786,23 +898,26 @@ describe.each(['postcss', 'lightningcss'])('%s', (transformer) => {
|
|||
let log = await fs.read('project-a/hmr.log')
|
||||
expect(log.split('"type":"update"').length).toBeGreaterThan(updates)
|
||||
})
|
||||
expect(await fs.read('project-a/hmr.log')).not.toContain('full-reload')
|
||||
}
|
||||
|
||||
// Changing an external file (e.g. a PHP template) should still trigger
|
||||
// a full reload. This must work even though `snippet.php` is part of
|
||||
// the module graph via the `?raw` import: a query import only pulls
|
||||
// the file's contents into the graph (and creates an untransformed
|
||||
// module node for the underlying file), it is not evidence that Vite
|
||||
// processes `.php` files as modules.
|
||||
// Changing an external file (e.g. a PHP template) hot-updates the
|
||||
// generated CSS but does not trigger a full reload either. Reloading the
|
||||
// page for external template changes is the responsibility of the backend
|
||||
// integration (e.g. `laravel-vite-plugin`'s `refresh` option, or
|
||||
// `vite-plugin-full-reload`).
|
||||
//
|
||||
// https://github.com/tailwindlabs/tailwindcss/issues/20411
|
||||
{
|
||||
let updates = (await fs.read('project-a/hmr.log')).split('"type":"update"').length
|
||||
|
||||
await fs.write(
|
||||
'project-b/src/index.php',
|
||||
html`<div class="content-['updated:project-b/src/index.php']"></div>`,
|
||||
)
|
||||
|
||||
await retryAssertion(async () => {
|
||||
expect(await fs.read('project-a/hmr.log')).toContain('full-reload')
|
||||
let log = await fs.read('project-a/hmr.log')
|
||||
expect(log.split('"type":"update"').length).toBeGreaterThan(updates)
|
||||
})
|
||||
|
||||
let styles = await fetchStyles(url, '/index.html')
|
||||
|
|
|
|||
165
integrations/vite/preact.test.ts
Normal file
165
integrations/vite/preact.test.ts
Normal file
|
|
@ -0,0 +1,165 @@
|
|||
import { candidate, css, fetchStyles, html, json, retryAssertion, test, ts, txt } from '../utils'
|
||||
|
||||
test(
|
||||
'dev mode',
|
||||
{
|
||||
fs: {
|
||||
'package.json': json`
|
||||
{
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"preact": "^10"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@preact/preset-vite": "^2",
|
||||
"@tailwindcss/vite": "workspace:^",
|
||||
"tailwindcss": "workspace:^",
|
||||
"vite": "^8"
|
||||
}
|
||||
}
|
||||
`,
|
||||
'vite.config.ts': ts`
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import preact from '@preact/preset-vite'
|
||||
import tailwindcss from '@tailwindcss/vite'
|
||||
import { defineConfig } from 'vite'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
tailwindcss(),
|
||||
preact(),
|
||||
{
|
||||
// Log all HMR payloads to a file so the test can assert on them
|
||||
name: 'hmr-wiretap',
|
||||
configureServer(server) {
|
||||
let logFile = path.resolve('hmr.log')
|
||||
fs.writeFileSync(logFile, '')
|
||||
for (let environment of Object.values(server.environments)) {
|
||||
let send = environment.hot.send.bind(environment.hot)
|
||||
environment.hot.send = (payload) => {
|
||||
fs.appendFileSync(logFile, JSON.stringify(payload) + '\\n')
|
||||
return send(payload)
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
],
|
||||
})
|
||||
`,
|
||||
'index.html': html`
|
||||
<html>
|
||||
<head>
|
||||
<link rel="stylesheet" href="./src/index.css" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="./src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
`,
|
||||
'src/main.tsx': ts`
|
||||
import { render } from 'preact'
|
||||
import { App } from './app'
|
||||
|
||||
render(<App />, document.getElementById('app')!)
|
||||
`,
|
||||
'src/app.tsx': ts`
|
||||
import { useState } from 'preact/hooks'
|
||||
|
||||
export function App() {
|
||||
const [count, setCount] = useState(0)
|
||||
return (
|
||||
<button className="underline" onClick={() => setCount((c) => c + 1)}>
|
||||
Count: {count}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
`,
|
||||
'src/index.css': css`@import 'tailwindcss';`,
|
||||
},
|
||||
},
|
||||
async ({ fs, spawn, expect }) => {
|
||||
let process = await spawn('pnpm vite dev')
|
||||
await process.onStdout((m) => m.includes('ready in'))
|
||||
|
||||
let url = ''
|
||||
await process.onStdout((m) => {
|
||||
let match = /Local:\s*(http.*)\//.exec(m)
|
||||
if (match) url = match[1]
|
||||
return Boolean(url)
|
||||
})
|
||||
|
||||
await retryAssertion(async () => {
|
||||
let styles = await fetchStyles(url)
|
||||
expect(styles).toContain(candidate`underline`)
|
||||
})
|
||||
|
||||
// Load the component modules, like a browser visiting the page would
|
||||
await fetch(`${url}/src/main.tsx`)
|
||||
await fetch(`${url}/src/app.tsx`)
|
||||
|
||||
// Editing a component keeps HMR intact: new classes are delivered through
|
||||
// a regular update, not a full page reload (which would lose all state)
|
||||
{
|
||||
await fs.write(
|
||||
'src/app.tsx',
|
||||
ts`
|
||||
import { useState } from 'preact/hooks'
|
||||
|
||||
export function App() {
|
||||
const [count, setCount] = useState(0)
|
||||
return (
|
||||
<button className="underline flex" onClick={() => setCount((c) => c + 1)}>
|
||||
Count: {count}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
`,
|
||||
)
|
||||
|
||||
await retryAssertion(async () => {
|
||||
let styles = await fetchStyles(url)
|
||||
expect(styles).toContain(candidate`underline`)
|
||||
expect(styles).toContain(candidate`flex`)
|
||||
})
|
||||
expect(await fs.read('hmr.log')).toContain('"type":"update"')
|
||||
expect(await fs.read('hmr.log')).not.toContain('full-reload')
|
||||
}
|
||||
|
||||
// Changing a scanned file that is not part of the module graph (e.g.
|
||||
// `package.json`, which package managers and other tooling write to while
|
||||
// the dev server is running) should not trigger a full reload either —
|
||||
// that would destroy client state. New candidates should still be picked
|
||||
// up because the file is a watch dependency of the CSS root, so the CSS
|
||||
// hot-updates through Vite's regular pipeline.
|
||||
//
|
||||
// https://github.com/tailwindlabs/tailwindcss/issues/20411
|
||||
{
|
||||
await fs.write(
|
||||
'package.json',
|
||||
txt`
|
||||
{
|
||||
"type": "module",
|
||||
"description": "content-['package.json']",
|
||||
"dependencies": {
|
||||
"preact": "^10"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@preact/preset-vite": "^2",
|
||||
"@tailwindcss/vite": "workspace:^",
|
||||
"tailwindcss": "workspace:^",
|
||||
"vite": "^8"
|
||||
}
|
||||
}
|
||||
`,
|
||||
)
|
||||
|
||||
await retryAssertion(async () => {
|
||||
let styles = await fetchStyles(url)
|
||||
expect(styles).toContain(candidate`content-['package.json']`)
|
||||
})
|
||||
expect(await fs.read('hmr.log')).not.toContain('full-reload')
|
||||
}
|
||||
},
|
||||
)
|
||||
|
|
@ -48,7 +48,7 @@
|
|||
},
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@playwright/test": "^1.61.1",
|
||||
"@playwright/test": "^1.62.1",
|
||||
"@types/node": "catalog:",
|
||||
"postcss": "catalog:",
|
||||
"postcss-import": "^16.1.1",
|
||||
|
|
@ -56,9 +56,9 @@
|
|||
"prettier-plugin-embed": "^0.5.1",
|
||||
"prettier-plugin-organize-imports": "^4.3.0",
|
||||
"tsup": "^8.5.1",
|
||||
"turbo": "^2.9.18",
|
||||
"turbo": "^2.10.8",
|
||||
"typescript": "^5.9.3",
|
||||
"vitest": "^4.1.9"
|
||||
"vitest": "^4.1.10"
|
||||
},
|
||||
"packageManager": "pnpm@11.9.0"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@
|
|||
},
|
||||
"devDependencies": {
|
||||
"h3": "^1.15.11",
|
||||
"listhen": "^1.10.0",
|
||||
"listhen": "^1.10.1",
|
||||
"tailwindcss": "workspace:*"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -29,7 +29,7 @@
|
|||
"access": "public"
|
||||
},
|
||||
"dependencies": {
|
||||
"@parcel/watcher": "2.5.1",
|
||||
"@parcel/watcher": "catalog:",
|
||||
"@tailwindcss/node": "workspace:*",
|
||||
"@tailwindcss/oxide": "workspace:*",
|
||||
"enhanced-resolve": "catalog:",
|
||||
|
|
|
|||
|
|
@ -57,7 +57,7 @@
|
|||
"enhanced-resolve": "catalog:",
|
||||
"jiti": "^2.7.0",
|
||||
"lightningcss": "catalog:",
|
||||
"magic-string": "^0.30.21",
|
||||
"magic-string": "^1.1.0",
|
||||
"source-map-js": "^1.2.1",
|
||||
"tailwindcss": "workspace:*"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -61,17 +61,14 @@ export function optimize(
|
|||
map = result.map?.toString()
|
||||
|
||||
result.warnings = result.warnings.filter((warning) => {
|
||||
// Ignore warnings about unknown pseudo-classes as they are likely caused
|
||||
// by the use of `:deep()`, `:slotted()`, and `:global()` which are not
|
||||
// standard CSS but are commonly used in frameworks like Vue.
|
||||
if (/'(deep|slotted|global)' is not recognized as a valid pseudo-/.test(warning.message)) {
|
||||
return false
|
||||
}
|
||||
|
||||
// Ignore warnings about unknown at-rules.
|
||||
//
|
||||
// TODO: drop `@position-try` once https://github.com/parcel-bundler/lightningcss/pull/1238 lands
|
||||
if (/Unknown at rule: @position-try/.test(warning.message)) {
|
||||
// Ignore warnings about unknown pseudo-classes that are used in frameworks
|
||||
// such as Vue or Angular and are handled by their own compilers, before
|
||||
// reaching the browser.
|
||||
if (
|
||||
/'(deep|slotted|global|ng-deep|host-context)' is not recognized as a valid pseudo-/.test(
|
||||
warning.message,
|
||||
)
|
||||
) {
|
||||
return false
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -56,6 +56,7 @@ describe('fixRelativePathsPlugin', () => {
|
|||
@plugin './plugin-in-sibling.ts';
|
||||
@plugin '../plugin-in-sibling.ts';
|
||||
@plugin 'plugin-in-sibling';
|
||||
|
||||
@plugin './plugin-in-root.ts';
|
||||
@plugin '../plugin-in-root.ts';
|
||||
@plugin 'plugin-in-root';
|
||||
|
|
|
|||
|
|
@ -35,13 +35,13 @@
|
|||
},
|
||||
"__notes": "These binary packages must be included so Bun can build the CLI for all supported platforms. We also rely on Lightning CSS and Parcel being patched so Bun can statically analyze the executables.",
|
||||
"devDependencies": {
|
||||
"@parcel/watcher-darwin-arm64": "^2.5.6",
|
||||
"@parcel/watcher-darwin-x64": "^2.5.6",
|
||||
"@parcel/watcher-linux-arm64-glibc": "^2.5.6",
|
||||
"@parcel/watcher-linux-arm64-musl": "^2.5.6",
|
||||
"@parcel/watcher-linux-x64-glibc": "^2.5.6",
|
||||
"@parcel/watcher-linux-x64-musl": "^2.5.6",
|
||||
"@parcel/watcher-win32-x64": "^2.5.6",
|
||||
"@parcel/watcher-darwin-arm64": "catalog:",
|
||||
"@parcel/watcher-darwin-x64": "catalog:",
|
||||
"@parcel/watcher-linux-arm64-glibc": "catalog:",
|
||||
"@parcel/watcher-linux-arm64-musl": "catalog:",
|
||||
"@parcel/watcher-linux-x64-glibc": "catalog:",
|
||||
"@parcel/watcher-linux-x64-musl": "catalog:",
|
||||
"@parcel/watcher-win32-x64": "catalog:",
|
||||
"@types/bun": "^1.3.14",
|
||||
"bun": "^1.3.14",
|
||||
"lightningcss-darwin-arm64": "catalog:",
|
||||
|
|
|
|||
99
packages/@tailwindcss-turbopack/README.md
Normal file
99
packages/@tailwindcss-turbopack/README.md
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
<p align="center">
|
||||
<a href="https://tailwindcss.com" target="_blank">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/tailwindlabs/tailwindcss/HEAD/.github/logo-dark.svg">
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/tailwindlabs/tailwindcss/HEAD/.github/logo-light.svg">
|
||||
<img alt="Tailwind CSS" src="https://raw.githubusercontent.com/tailwindlabs/tailwindcss/HEAD/.github/logo-light.svg" width="350" height="70" style="max-width: 100%;">
|
||||
</picture>
|
||||
</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
A utility-first CSS framework for rapidly building custom user interfaces.
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/tailwindlabs/tailwindcss/actions"><img src="https://img.shields.io/github/actions/workflow/status/tailwindlabs/tailwindcss/ci.yml?branch=main" alt="Build Status"></a>
|
||||
<a href="https://www.npmjs.com/package/tailwindcss"><img src="https://img.shields.io/npm/dt/tailwindcss.svg" alt="Total Downloads"></a>
|
||||
<a href="https://github.com/tailwindlabs/tailwindcss/releases"><img src="https://img.shields.io/npm/v/tailwindcss.svg" alt="Latest Release"></a>
|
||||
<a href="https://github.com/tailwindlabs/tailwindcss/blob/main/LICENSE"><img src="https://img.shields.io/npm/l/tailwindcss.svg" alt="License"></a>
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
## Documentation
|
||||
|
||||
For full documentation, visit [tailwindcss.com](https://tailwindcss.com).
|
||||
|
||||
## Community
|
||||
|
||||
For help, discussion about best practices, or feature ideas:
|
||||
|
||||
[Discuss Tailwind CSS on GitHub](https://github.com/tailwindlabs/tailwindcss/discussions)
|
||||
|
||||
## Contributing
|
||||
|
||||
If you're interested in contributing to Tailwind CSS, please read our [contributing docs](https://github.com/tailwindlabs/tailwindcss/blob/main/.github/CONTRIBUTING.md) **before submitting a pull request**.
|
||||
|
||||
---
|
||||
|
||||
## @tailwindcss/turbopack
|
||||
|
||||
A Turbopack loader for Tailwind CSS v4.
|
||||
|
||||
## Installation
|
||||
|
||||
```sh
|
||||
npm install @tailwindcss/turbopack
|
||||
```
|
||||
|
||||
### Usage
|
||||
|
||||
```javascript
|
||||
// next.config.js
|
||||
module.exports = {
|
||||
turbopack: {
|
||||
rules: {
|
||||
'*.css': {
|
||||
loaders: ['@tailwindcss/turbopack'],
|
||||
as: '*.css',
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Then create a CSS file that imports Tailwind:
|
||||
|
||||
```css
|
||||
/* src/index.css */
|
||||
@import 'tailwindcss';
|
||||
```
|
||||
|
||||
### Options
|
||||
|
||||
#### `base`
|
||||
|
||||
The base directory to scan for class candidates. Defaults to the current working directory.
|
||||
|
||||
```javascript
|
||||
{
|
||||
loader: '@tailwindcss/turbopack',
|
||||
options: {
|
||||
base: process.cwd(),
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
#### `optimize`
|
||||
|
||||
Whether to optimize and minify the output CSS. Defaults to `true` in production mode.
|
||||
|
||||
```javascript
|
||||
{
|
||||
loader: '@tailwindcss/turbopack',
|
||||
options: {
|
||||
optimize: true, // or { minify: true }
|
||||
},
|
||||
}
|
||||
```
|
||||
43
packages/@tailwindcss-turbopack/package.json
Normal file
43
packages/@tailwindcss-turbopack/package.json
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
{
|
||||
"name": "@tailwindcss/turbopack",
|
||||
"version": "4.3.3",
|
||||
"description": "A Turbopack loader for Tailwind CSS v4.",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/tailwindlabs/tailwindcss.git",
|
||||
"directory": "packages/@tailwindcss-turbopack"
|
||||
},
|
||||
"bugs": "https://github.com/tailwindlabs/tailwindcss/issues",
|
||||
"homepage": "https://tailwindcss.com",
|
||||
"scripts": {
|
||||
"build": "tsup-node",
|
||||
"dev": "pnpm run build -- --watch"
|
||||
},
|
||||
"files": [
|
||||
"dist/"
|
||||
],
|
||||
"publishConfig": {
|
||||
"provenance": true,
|
||||
"access": "public"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.mjs",
|
||||
"require": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"dependencies": {
|
||||
"@alloc/quick-lru": "^5.2.0",
|
||||
"@tailwindcss/node": "workspace:*",
|
||||
"@tailwindcss/oxide": "workspace:*",
|
||||
"tailwindcss": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "catalog:",
|
||||
"webpack": "catalog:"
|
||||
}
|
||||
}
|
||||
5
packages/@tailwindcss-turbopack/src/index.cts
Normal file
5
packages/@tailwindcss-turbopack/src/index.cts
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
import tailwindLoader from './index.ts'
|
||||
|
||||
// CommonJS export for webpack loaders - must be the function directly
|
||||
// @ts-ignore
|
||||
export = tailwindLoader
|
||||
287
packages/@tailwindcss-turbopack/src/index.ts
Normal file
287
packages/@tailwindcss-turbopack/src/index.ts
Normal file
|
|
@ -0,0 +1,287 @@
|
|||
import QuickLRU from '@alloc/quick-lru'
|
||||
import {
|
||||
compile,
|
||||
env,
|
||||
Features,
|
||||
Instrumentation,
|
||||
normalizePath,
|
||||
optimize,
|
||||
Polyfills,
|
||||
} from '@tailwindcss/node'
|
||||
import { clearRequireCache } from '@tailwindcss/node/require-cache'
|
||||
import { Scanner } from '@tailwindcss/oxide'
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import type { LoaderContext } from 'webpack'
|
||||
|
||||
const DEBUG = env.DEBUG
|
||||
|
||||
export interface LoaderOptions {
|
||||
/**
|
||||
* The base directory to scan for class candidates.
|
||||
*
|
||||
* Defaults to the current working directory.
|
||||
*/
|
||||
base?: string
|
||||
|
||||
/**
|
||||
* Optimize and minify the output CSS.
|
||||
*/
|
||||
optimize?: boolean | { minify?: boolean }
|
||||
}
|
||||
|
||||
interface CacheEntry {
|
||||
mtimes: Map<string, number>
|
||||
compiler: null | Awaited<ReturnType<typeof compile>>
|
||||
scanner: null | Scanner
|
||||
candidates: Set<string>
|
||||
fullRebuildPaths: string[]
|
||||
}
|
||||
|
||||
const cache = new QuickLRU<string, CacheEntry>({ maxSize: 50 })
|
||||
|
||||
function getCacheKey(resourceId: string, opts: LoaderOptions): string {
|
||||
return `${resourceId}:${opts.base ?? ''}:${JSON.stringify(opts.optimize)}`
|
||||
}
|
||||
|
||||
function getContextFromCache(resourceId: string, opts: LoaderOptions): CacheEntry {
|
||||
let key = getCacheKey(resourceId, opts)
|
||||
if (cache.has(key)) return cache.get(key)!
|
||||
let entry: CacheEntry = {
|
||||
mtimes: new Map<string, number>(),
|
||||
compiler: null,
|
||||
scanner: null,
|
||||
candidates: new Set<string>(),
|
||||
fullRebuildPaths: [],
|
||||
}
|
||||
cache.set(key, entry)
|
||||
return entry
|
||||
}
|
||||
|
||||
export default async function tailwindLoader(
|
||||
this: LoaderContext<LoaderOptions>,
|
||||
source: string,
|
||||
): Promise<void> {
|
||||
let callback = this.async()
|
||||
let options = this.getOptions() ?? {}
|
||||
let inputFile = this.resourcePath
|
||||
let resourceId = this.resource
|
||||
let base = options.base ?? process.cwd()
|
||||
let shouldOptimize = options.optimize ?? process.env.NODE_ENV === 'production'
|
||||
let isCSSModuleFile = inputFile.endsWith('.module.css')
|
||||
|
||||
using I = new Instrumentation()
|
||||
|
||||
DEBUG && I.start(`[@tailwindcss/turbopack] ${path.relative(base, inputFile)}`)
|
||||
|
||||
// Bail out early if this is guaranteed to be a non-Tailwind CSS file.
|
||||
{
|
||||
DEBUG && I.start('Quick bail check')
|
||||
let canBail = !/@(import|reference|theme|variant|config|plugin|apply|tailwind)\b/.test(source)
|
||||
if (canBail) {
|
||||
DEBUG && I.end('Quick bail check')
|
||||
DEBUG && I.end(`[@tailwindcss/turbopack] ${path.relative(base, inputFile)}`)
|
||||
callback(null, source)
|
||||
return
|
||||
}
|
||||
DEBUG && I.end('Quick bail check')
|
||||
}
|
||||
|
||||
try {
|
||||
let context = getContextFromCache(resourceId, options)
|
||||
let inputBasePath = path.dirname(path.resolve(inputFile))
|
||||
|
||||
// Whether this is the first build or not
|
||||
let isInitialBuild = context.compiler === null
|
||||
|
||||
async function createCompiler() {
|
||||
DEBUG && I.start('Setup compiler')
|
||||
if (context.fullRebuildPaths.length > 0 && !isInitialBuild) {
|
||||
clearRequireCache(context.fullRebuildPaths)
|
||||
}
|
||||
|
||||
context.fullRebuildPaths = []
|
||||
|
||||
DEBUG && I.start('Create compiler')
|
||||
let compiler = await compile(source, {
|
||||
from: inputFile,
|
||||
base: inputBasePath,
|
||||
shouldRewriteUrls: true,
|
||||
onDependency: (depPath) => context.fullRebuildPaths.push(depPath),
|
||||
// In CSS Module files, we have to disable the `@property` polyfill since these will
|
||||
// emit global `*` rules which are considered to be non-pure and will cause builds
|
||||
// to fail.
|
||||
polyfills: isCSSModuleFile ? Polyfills.All ^ Polyfills.AtProperty : Polyfills.All,
|
||||
})
|
||||
DEBUG && I.end('Create compiler')
|
||||
|
||||
DEBUG && I.end('Setup compiler')
|
||||
return compiler
|
||||
}
|
||||
|
||||
// Setup the compiler if it doesn't exist yet
|
||||
context.compiler ??= await createCompiler()
|
||||
|
||||
// Early exit if no Tailwind features are used
|
||||
if (context.compiler.features === Features.None) {
|
||||
DEBUG && I.end(`[@tailwindcss/turbopack] ${path.relative(base, inputFile)}`)
|
||||
callback(null, source)
|
||||
return
|
||||
}
|
||||
|
||||
let rebuildStrategy: 'full' | 'incremental' = 'incremental'
|
||||
|
||||
// Track file modification times to CSS files
|
||||
DEBUG && I.start('Register full rebuild paths')
|
||||
{
|
||||
// Report dependencies for config files, plugins, etc.
|
||||
for (let file of context.fullRebuildPaths) {
|
||||
this.addDependency(path.resolve(file))
|
||||
}
|
||||
|
||||
let files = [...context.fullRebuildPaths, inputFile]
|
||||
|
||||
for (let file of files) {
|
||||
let changedTime: number | null = null
|
||||
try {
|
||||
changedTime = fs.statSync(file)?.mtimeMs ?? null
|
||||
} catch {
|
||||
// File might not exist
|
||||
}
|
||||
|
||||
if (changedTime === null) {
|
||||
if (file === inputFile) {
|
||||
rebuildStrategy = 'full'
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
let prevTime = context.mtimes.get(file)
|
||||
if (prevTime === changedTime) continue
|
||||
|
||||
rebuildStrategy = 'full'
|
||||
context.mtimes.set(file, changedTime)
|
||||
}
|
||||
}
|
||||
DEBUG && I.end('Register full rebuild paths')
|
||||
|
||||
if (rebuildStrategy === 'full' && !isInitialBuild) {
|
||||
context.compiler = await createCompiler()
|
||||
}
|
||||
|
||||
let compiler = context.compiler
|
||||
|
||||
// Check if we need to process this file at all
|
||||
if (
|
||||
!(
|
||||
compiler.features &
|
||||
(Features.AtApply | Features.JsPluginCompat | Features.ThemeFunction | Features.Utilities)
|
||||
)
|
||||
) {
|
||||
DEBUG && I.end(`[@tailwindcss/turbopack] ${path.relative(base, inputFile)}`)
|
||||
callback(null, source)
|
||||
return
|
||||
}
|
||||
|
||||
// Setup or update scanner if needed
|
||||
if (context.scanner === null || rebuildStrategy === 'full') {
|
||||
DEBUG && I.start('Setup scanner')
|
||||
let sources = (() => {
|
||||
// Disable auto source detection
|
||||
if (compiler.root === 'none') {
|
||||
return []
|
||||
}
|
||||
|
||||
// No root specified, use the base directory
|
||||
if (compiler.root === null) {
|
||||
return [{ base, pattern: '**/*', negated: false }]
|
||||
}
|
||||
|
||||
// Use the specified root
|
||||
return [{ ...compiler.root, negated: false }]
|
||||
})().concat(compiler.sources)
|
||||
|
||||
context.scanner = new Scanner({ sources })
|
||||
DEBUG && I.end('Setup scanner')
|
||||
}
|
||||
|
||||
// Scan for candidates if utilities are used
|
||||
if (compiler.features & Features.Utilities) {
|
||||
DEBUG && I.start('Scan for candidates')
|
||||
for (let candidate of context.scanner.scan()) {
|
||||
context.candidates.add(candidate)
|
||||
}
|
||||
DEBUG && I.end('Scan for candidates')
|
||||
|
||||
DEBUG && I.start('Register dependency messages')
|
||||
// Add all found files as direct dependencies
|
||||
let resolvedInputFile = path.resolve(base, inputFile)
|
||||
for (let file of context.scanner.files) {
|
||||
let absolutePath = path.resolve(file)
|
||||
// The CSS file cannot be a dependency of itself
|
||||
if (absolutePath === resolvedInputFile) {
|
||||
continue
|
||||
}
|
||||
this.addDependency(absolutePath)
|
||||
}
|
||||
|
||||
// Register context dependencies for glob patterns
|
||||
for (let glob of context.scanner.globs) {
|
||||
// Skip negated patterns
|
||||
if (glob.pattern[0] === '!') continue
|
||||
|
||||
// Avoid adding a dependency on the base directory itself
|
||||
if (glob.pattern === '*' && base === glob.base) {
|
||||
continue
|
||||
}
|
||||
|
||||
this.addContextDependency(path.resolve(glob.base))
|
||||
}
|
||||
|
||||
// Validate that source(...) paths are directories
|
||||
let root = compiler.root
|
||||
if (root !== 'none' && root !== null) {
|
||||
let basePath = normalizePath(path.resolve(root.base, root.pattern))
|
||||
try {
|
||||
let stats = fs.statSync(basePath)
|
||||
if (!stats.isDirectory()) {
|
||||
throw new Error(
|
||||
`The path given to \`source(…)\` must be a directory but got \`source(${basePath})\` instead.`,
|
||||
)
|
||||
}
|
||||
} catch (err) {
|
||||
if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {
|
||||
throw err
|
||||
}
|
||||
// Directory doesn't exist yet, which is fine
|
||||
}
|
||||
}
|
||||
DEBUG && I.end('Register dependency messages')
|
||||
}
|
||||
|
||||
DEBUG && I.start('Build utilities')
|
||||
let css = compiler.build([...context.candidates])
|
||||
DEBUG && I.end('Build utilities')
|
||||
|
||||
// Optionally optimize the output
|
||||
let result = css
|
||||
if (shouldOptimize) {
|
||||
DEBUG && I.start('Optimization')
|
||||
let optimized = optimize(css, {
|
||||
minify: typeof shouldOptimize === 'object' ? shouldOptimize.minify : true,
|
||||
})
|
||||
result = optimized.code
|
||||
DEBUG && I.end('Optimization')
|
||||
}
|
||||
|
||||
DEBUG && I.end(`[@tailwindcss/turbopack] ${path.relative(base, inputFile)}`)
|
||||
callback(null, result)
|
||||
} catch (error) {
|
||||
// Clear the cache entry on error to force a full rebuild next time
|
||||
let key = getCacheKey(resourceId, options)
|
||||
cache.delete(key)
|
||||
|
||||
DEBUG && I.end(`[@tailwindcss/turbopack] ${path.relative(base, inputFile)}`)
|
||||
callback(error as Error)
|
||||
}
|
||||
}
|
||||
6
packages/@tailwindcss-turbopack/tsconfig.json
Normal file
6
packages/@tailwindcss-turbopack/tsconfig.json
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
{
|
||||
"extends": "../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"verbatimModuleSyntax": false,
|
||||
},
|
||||
}
|
||||
19
packages/@tailwindcss-turbopack/tsup.config.ts
Normal file
19
packages/@tailwindcss-turbopack/tsup.config.ts
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
import { defineConfig } from 'tsup'
|
||||
|
||||
export default defineConfig([
|
||||
{
|
||||
format: ['esm'],
|
||||
clean: true,
|
||||
minify: true,
|
||||
cjsInterop: true,
|
||||
dts: true,
|
||||
entry: ['src/index.ts'],
|
||||
},
|
||||
{
|
||||
format: ['cjs'],
|
||||
minify: true,
|
||||
cjsInterop: true,
|
||||
dts: true,
|
||||
entry: ['src/index.cts'],
|
||||
},
|
||||
])
|
||||
|
|
@ -31,7 +31,7 @@
|
|||
"@tailwindcss/oxide": "workspace:*",
|
||||
"dedent": "catalog:",
|
||||
"enhanced-resolve": "catalog:",
|
||||
"globby": "^16.2.0",
|
||||
"globby": "^16.2.2",
|
||||
"jiti": "^2.7.0",
|
||||
"mri": "^1.2.0",
|
||||
"picocolors": "^1.1.1",
|
||||
|
|
@ -39,14 +39,14 @@
|
|||
"postcss-import": "^16.1.1",
|
||||
"postcss-selector-parser": "^7.1.4",
|
||||
"prettier": "catalog:",
|
||||
"semver": "^7.8.4",
|
||||
"semver": "^7.8.5",
|
||||
"tailwindcss": "workspace:*",
|
||||
"tree-sitter": "^0.22.4",
|
||||
"tree-sitter": "^0.25.1",
|
||||
"tree-sitter-typescript": "^0.23.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "catalog:",
|
||||
"@types/postcss-import": "^14.0.3",
|
||||
"@types/semver": "^7.7.1"
|
||||
"@types/semver": "^7.8.0"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -769,6 +769,7 @@ describe('comments', () => {
|
|||
).toMatchInlineSnapshot(`
|
||||
"
|
||||
/* Start of utilities: */
|
||||
|
||||
@utility foo {
|
||||
/* Utility #1 */
|
||||
/* Declarations: */
|
||||
|
|
@ -793,6 +794,7 @@ describe('comments', () => {
|
|||
).toMatchInlineSnapshot(`
|
||||
"
|
||||
/* Start of utilities: */
|
||||
|
||||
@utility foo {
|
||||
/* Foo & Bar */
|
||||
& .bar {
|
||||
|
|
@ -800,6 +802,7 @@ describe('comments', () => {
|
|||
color: red;
|
||||
}
|
||||
}
|
||||
|
||||
@utility bar {
|
||||
/* Foo & Bar */
|
||||
.foo & {
|
||||
|
|
@ -829,6 +832,7 @@ describe('comments', () => {
|
|||
).toMatchInlineSnapshot(`
|
||||
"
|
||||
/* Start of utilities: */
|
||||
|
||||
@utility foo {
|
||||
/* Mobile only */
|
||||
@media (width <= 640px) {
|
||||
|
|
@ -878,6 +882,7 @@ describe('comments', () => {
|
|||
).toMatchInlineSnapshot(`
|
||||
"
|
||||
/* Tailwind Utilities: */
|
||||
|
||||
@utility no-scrollbar {
|
||||
/* Chrome, Safari and Opera */
|
||||
/* Second comment */
|
||||
|
|
|
|||
|
|
@ -16,8 +16,8 @@ export function migrateArbitraryVariants(
|
|||
rawCandidate: string,
|
||||
): string {
|
||||
let designSystem = prepareDesignSystemStorage(baseDesignSystem)
|
||||
let signatures = designSystem.storage[VARIANT_SIGNATURE_KEY]
|
||||
let variants = designSystem.storage[PRE_COMPUTED_VARIANTS_KEY]
|
||||
let signatures = designSystem.storage[VARIANT_SIGNATURE_KEY].get(null)
|
||||
let variants = designSystem.storage[PRE_COMPUTED_VARIANTS_KEY].get(null)
|
||||
|
||||
for (let readonlyCandidate of designSystem.parseCandidate(rawCandidate)) {
|
||||
// We are only interested in the variants
|
||||
|
|
@ -35,7 +35,11 @@ export function migrateArbitraryVariants(
|
|||
if (typeof targetSignature !== 'string') continue
|
||||
|
||||
let foundVariants = variants.get(targetSignature)
|
||||
if (foundVariants.length !== 1) continue
|
||||
if (foundVariants.length === 0) continue
|
||||
|
||||
// The variant is already in a canonical form, e.g.: `min-lg` and `lg`
|
||||
// produce the same CSS, but both are valid so we keep them as-is.
|
||||
if (foundVariants.includes(targetString)) continue
|
||||
|
||||
let foundVariant = foundVariants[0]
|
||||
let parsedVariant = designSystem.parseVariant(foundVariant)
|
||||
|
|
|
|||
|
|
@ -9,23 +9,15 @@ import {
|
|||
} from '@tailwindcss/node'
|
||||
import { clearRequireCache } from '@tailwindcss/node/require-cache'
|
||||
import { Scanner } from '@tailwindcss/oxide'
|
||||
import { realpathSync } from 'node:fs'
|
||||
import fs from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
import type {
|
||||
Environment,
|
||||
InternalResolveOptions,
|
||||
Plugin,
|
||||
ResolvedConfig,
|
||||
ViteDevServer,
|
||||
} from 'vite'
|
||||
import type { Environment, InternalResolveOptions, Plugin, ResolvedConfig } from 'vite'
|
||||
import * as vite from 'vite'
|
||||
|
||||
const DEBUG = env.DEBUG
|
||||
const SPECIAL_QUERY_RE = /[?&](?:worker|sharedworker|raw|url)\b/
|
||||
const COMMON_JS_PROXY_RE = /\?commonjs-proxy/
|
||||
const INLINE_STYLE_ID_RE = /[?&]index=\d+\.css$/
|
||||
const JS_EXTENSIONS_RE = /^\.[cm]?[jt]sx?$/
|
||||
|
||||
export type PluginOptions = {
|
||||
/**
|
||||
|
|
@ -73,17 +65,9 @@ function createCustomResolver(
|
|||
}
|
||||
|
||||
export default function tailwindcss(opts: PluginOptions = {}): Plugin[] {
|
||||
let servers: ViteDevServer[] = []
|
||||
let config: ResolvedConfig | null = null
|
||||
let rootsByEnv = new DefaultMap<string, Map<string, Root>>((env: string) => new Map())
|
||||
|
||||
// File extensions that Vite (or one of its plugins) has been seen to process
|
||||
// as a module. Plugins don't get added or removed while the dev server is
|
||||
// running (changing the Vite config restarts the server), so once we've seen
|
||||
// evidence for a file type we don't need to scan the module graphs for it
|
||||
// again.
|
||||
let viteProcessedExtensions = new Set<string>()
|
||||
|
||||
let isSSR = false
|
||||
let shouldOptimize = true
|
||||
let minify = true
|
||||
|
|
@ -196,10 +180,6 @@ export default function tailwindcss(opts: PluginOptions = {}): Plugin[] {
|
|||
name: '@tailwindcss/vite:scan',
|
||||
enforce: 'pre',
|
||||
|
||||
configureServer(server) {
|
||||
servers.push(server)
|
||||
},
|
||||
|
||||
async configResolved(_config) {
|
||||
config = _config
|
||||
isSSR = config.build.ssr !== false && config.build.ssr !== undefined
|
||||
|
|
@ -256,143 +236,6 @@ export default function tailwindcss(opts: PluginOptions = {}): Plugin[] {
|
|||
return result
|
||||
},
|
||||
},
|
||||
|
||||
hotUpdate({ file, modules, timestamp, server }) {
|
||||
// Ensure full-reloads are triggered for files that are being watched by
|
||||
// Tailwind but aren't part of the module graph (like PHP or HTML
|
||||
// files). If we don't do this, then changes to those files won't
|
||||
// trigger a reload at all since Vite doesn't know about them.
|
||||
{
|
||||
// It's a little bit confusing, because due to the `addWatchFile`
|
||||
// calls, it _is_ part of the module graph but nothing is really
|
||||
// handling those files. These modules typically have an id of
|
||||
// undefined and/or have a type of 'asset'.
|
||||
//
|
||||
// If we call `addWatchFile` on a file that is part of the actual
|
||||
// module graph, then we will see a module for it with a type of `js`
|
||||
// and a type of `asset`. We are only interested if _all_ of them are
|
||||
// missing an id and/or have a type of 'asset', which is a strong
|
||||
// signal that the changed file is not being handled by Vite or any of
|
||||
// the plugins.
|
||||
//
|
||||
// Note: in Vite v7.0.6 the modules here will have a type of `js`, not
|
||||
// 'asset'. But it will also have a `HARD_INVALIDATED` state and will
|
||||
// do a full page reload already.
|
||||
//
|
||||
// Empty modules can be skipped since it means it's not
|
||||
// `addWatchFile`d and thus irrelevant to Tailwind.
|
||||
let isExternalFile =
|
||||
modules.length > 0 &&
|
||||
modules.every((mod) => mod.type === 'asset' || mod.id === undefined)
|
||||
if (!isExternalFile) return
|
||||
|
||||
// Skip files that Vite (or one of its plugins) processes as a
|
||||
// module — in this environment (e.g. a lazily-loaded route that
|
||||
// hasn't been visited yet) or in another one (e.g. an SSR-only
|
||||
// module). Such a file can only affect the page through Vite's own
|
||||
// pipeline, so a full reload would only destroy client state. Any
|
||||
// changes to the generated CSS still go through the regular
|
||||
// `css-update` flow because the file is registered via
|
||||
// `addWatchFile`.
|
||||
//
|
||||
// If the file exists as a real module in another environment, then
|
||||
// that environment is responsible for it. E.g. an SSR framework
|
||||
// has its own server side hmr/reload mechanism when handling
|
||||
// server only modules. See https://v6.vite.dev/guide/migration.html
|
||||
// > Updates to an SSR-only module no longer triggers a full page reload in the client. ...
|
||||
for (let environment of Object.values(server.environments)) {
|
||||
if (environment.name === this.environment.name) continue
|
||||
|
||||
let modules = environment.moduleGraph.getModulesByFile(file)
|
||||
if (modules) {
|
||||
for (let mod of modules) {
|
||||
if (mod.type !== 'asset') {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Otherwise the file is not loaded as a module anywhere, so
|
||||
// determine whether its file _type_ would be processed by Vite
|
||||
// when requested by the browser (in which case the file just isn't
|
||||
// loaded yet, e.g. a lazily-loaded route that hasn't been visited).
|
||||
// Vite has no API to answer this without actually running the
|
||||
// plugin pipeline, so instead:
|
||||
//
|
||||
// Files Vite handles natively (the JS/TS and CSS families) are always
|
||||
// processed by Vite. This includes stylesheets that never show up as
|
||||
// their own module because a framework plugin compiles them into a
|
||||
// component (e.g. Angular), in which case that plugin owns their HMR.
|
||||
let extension = path.extname(file)
|
||||
if (JS_EXTENSIONS_RE.test(extension) || vite.isCSSRequest(file)) return
|
||||
|
||||
// For any other file type (e.g. `.vue`, `.svelte`, or `.md` with an
|
||||
// SSG plugin), if a file with the same extension exists as a real
|
||||
// module in any environment's module graph, then a plugin evidently
|
||||
// handles this file type and the changed file just isn't loaded
|
||||
// (yet).
|
||||
if (extension !== '') {
|
||||
if (viteProcessedExtensions.has(extension)) return
|
||||
|
||||
for (let environment of Object.values(server.environments)) {
|
||||
for (let mod of environment.moduleGraph.idToModuleMap.values()) {
|
||||
if (!mod.file?.endsWith(extension)) continue
|
||||
if (mod.type === 'asset') continue
|
||||
|
||||
// Only count modules that the plugin pipeline actually
|
||||
// transformed. Vite also creates untransformed placeholder
|
||||
// nodes (e.g. for the file underlying a `?raw` import) that
|
||||
// are not evidence that a plugin handles this file type.
|
||||
if (mod.transformResult == null) continue
|
||||
|
||||
// Similarly, ignore query imports (e.g. `./template.html?raw`,
|
||||
// or the `?html-proxy` modules Vite creates for inline
|
||||
// scripts): they pull a file's _contents_ into the graph
|
||||
// without a plugin processing the file type. A scanned
|
||||
// `.html` template must still trigger a full reload even if
|
||||
// some other `.html` file is imported with `?raw`.
|
||||
if (!mod.id || mod.id.includes('?')) continue
|
||||
|
||||
viteProcessedExtensions.add(extension)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (let env of new Set([this.environment.name, 'client'])) {
|
||||
let roots = rootsByEnv.get(env)
|
||||
if (roots.size === 0) continue
|
||||
|
||||
// If the file is not being watched by any of the roots, then we can
|
||||
// skip the reload since it's not relevant to Tailwind CSS.
|
||||
if (!isScannedFile(file, modules, roots)) {
|
||||
continue
|
||||
}
|
||||
|
||||
// https://vite.dev/changes/hotupdate-hook#migration-guide
|
||||
let invalidatedModules = new Set<vite.EnvironmentModuleNode>()
|
||||
for (let mod of modules) {
|
||||
this.environment.moduleGraph.invalidateModule(
|
||||
mod,
|
||||
invalidatedModules,
|
||||
timestamp,
|
||||
true,
|
||||
)
|
||||
}
|
||||
|
||||
if (env === this.environment.name) {
|
||||
this.environment.hot.send({ type: 'full-reload' })
|
||||
} else if (server.hot.send) {
|
||||
server.hot.send({ type: 'full-reload' })
|
||||
} else if (server.ws.send) {
|
||||
server.ws.send({ type: 'full-reload' })
|
||||
}
|
||||
|
||||
return []
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
|
|
@ -513,10 +356,6 @@ class Root {
|
|||
private customJsResolver: (id: string, base: string) => Promise<string | false | undefined>,
|
||||
) {}
|
||||
|
||||
get scannedFiles() {
|
||||
return this.scanner?.files ?? []
|
||||
}
|
||||
|
||||
// Generate the CSS for the root file. This can return false if the file is
|
||||
// not considered a Tailwind root. When this happened, the root can be GCed.
|
||||
public async generate(
|
||||
|
|
@ -702,54 +541,3 @@ class Root {
|
|||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function isScannedFile(
|
||||
file: string,
|
||||
modules: vite.EnvironmentModuleNode[],
|
||||
roots: Map<string, Root>,
|
||||
) {
|
||||
let seen = new Set()
|
||||
let q = [...modules]
|
||||
let checks = {
|
||||
file,
|
||||
get realpath() {
|
||||
try {
|
||||
let realpath = realpathSync(file)
|
||||
Object.defineProperty(checks, 'realpath', { value: realpath })
|
||||
return realpath
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
while (q.length > 0) {
|
||||
let module = q.shift()!
|
||||
if (seen.has(module)) continue
|
||||
seen.add(module)
|
||||
|
||||
if (module.id) {
|
||||
let root = roots.get(module.id)
|
||||
|
||||
if (root) {
|
||||
// If the file is part of the scanned files for this root, then we know
|
||||
// for sure that it's being watched by any of the Tailwind CSS roots. It
|
||||
// doesn't matter which root it is since it's only used to know whether
|
||||
// we should trigger a full reload or not.
|
||||
if (
|
||||
root.scannedFiles.includes(checks.file) ||
|
||||
(checks.realpath && root.scannedFiles.includes(checks.realpath))
|
||||
) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Keep walking up the tree until we find a root.
|
||||
for (let importer of module.importers) {
|
||||
q.push(importer)
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
|
|
|||
|
|
@ -132,7 +132,7 @@
|
|||
"@types/node": "catalog:",
|
||||
"dedent": "catalog:",
|
||||
"lightningcss": "catalog:",
|
||||
"magic-string": "^0.30.21",
|
||||
"magic-string": "^1.1.0",
|
||||
"source-map-js": "^1.2.1"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ import * as CSS from './css-parser'
|
|||
import { buildDesignSystem } from './design-system'
|
||||
import { pretty } from './test-utils/run'
|
||||
import { Theme } from './theme'
|
||||
import { walk } from './walk'
|
||||
import { walk, WalkAction } from './walk'
|
||||
|
||||
const css = String.raw
|
||||
const defaultDesignSystem = buildDesignSystem(new Theme())
|
||||
|
|
@ -308,7 +308,25 @@ it('should not emit color-mix() fallbacks inside @keyframes', () => {
|
|||
|
||||
describe('optimization', () => {
|
||||
function optimize(input: string) {
|
||||
return pretty(toCss(handleNesting(CSS.parse(input))))
|
||||
let ast = CSS.parse(input)
|
||||
walk(ast, {
|
||||
exit(node) {
|
||||
// Depending on where we use `@scope`, it's handled slightly differently:
|
||||
//
|
||||
// 1. In user authored CSS, we perform the normal CSS nesting and
|
||||
// hoisting of `@scope` rules
|
||||
// 2. In a `@custom-variant` definition, we need to swap the `@scope`
|
||||
// with the parent definition. Otherwise you'll never get the
|
||||
// expected "sandwich" effect.
|
||||
//
|
||||
// This little `@in-variant` hack is just a different way of
|
||||
// differentiating between both cases for these tests.
|
||||
if (node.kind === 'at-rule' && node.name === '@in-variant') {
|
||||
return WalkAction.Replace(context({ source: 'variant' }, node.nodes))
|
||||
}
|
||||
},
|
||||
})
|
||||
return pretty(toCss(handleNesting(ast)))
|
||||
}
|
||||
|
||||
// See: https://drafts.csswg.org/css-nesting-1/
|
||||
|
|
@ -1093,6 +1111,411 @@ describe('optimization', () => {
|
|||
`)
|
||||
})
|
||||
|
||||
it('should hoist `@scope` at-rules', async () => {
|
||||
expect(
|
||||
optimize(css`
|
||||
@layer utilities {
|
||||
.parent {
|
||||
@in-variant {
|
||||
@scope (.from) to (.to) {
|
||||
--x: 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`),
|
||||
).toMatchInlineSnapshot(`
|
||||
"
|
||||
@layer utilities {
|
||||
@scope (.from) to (.to) {
|
||||
.parent {
|
||||
--x: 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
"
|
||||
`)
|
||||
})
|
||||
|
||||
// We have an optimization where the moment we see a declaration that we
|
||||
// stop handling the nesting and emit everything as-is. This won't work when
|
||||
// we're dealing with `@scope` and we still want to hoist that out.
|
||||
it('should hoist `@scope` at-rules, even when sibling declarations are present', async () => {
|
||||
expect(
|
||||
optimize(css`
|
||||
@layer utilities {
|
||||
.parent {
|
||||
--x: 1;
|
||||
@in-variant {
|
||||
@scope (.from) {
|
||||
.inside {
|
||||
--y: 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`),
|
||||
).toMatchInlineSnapshot(`
|
||||
"
|
||||
@layer utilities {
|
||||
.parent {
|
||||
--x: 1;
|
||||
}
|
||||
@scope (.from) {
|
||||
.parent .inside {
|
||||
--y: 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
"
|
||||
`)
|
||||
})
|
||||
|
||||
it('should resolve `&` in the `@scope` prelude when hoisting', async () => {
|
||||
// `&` in the `<scope-start>` selector refers to the elements matched by
|
||||
// the nearest ancestor style rule, while `&` in the `<scope-end>`
|
||||
// selector refers to the scoping root.
|
||||
//
|
||||
// See: https://drafts.csswg.org/css-nesting-1/#nesting-at-scope
|
||||
expect(
|
||||
optimize(css`
|
||||
.parent {
|
||||
@scope (& > .scope) to (& .limit) {
|
||||
.content {
|
||||
--x: 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
`),
|
||||
).toMatchInlineSnapshot(`
|
||||
"
|
||||
@scope (.parent > .scope) to (:where(:scope) .limit) {
|
||||
.content {
|
||||
--x: 1;
|
||||
}
|
||||
}
|
||||
"
|
||||
`)
|
||||
|
||||
// Selector lists need `:is(…)` to keep their meaning
|
||||
expect(
|
||||
optimize(css`
|
||||
.parent-a,
|
||||
.parent-b {
|
||||
@scope (& > .from) {
|
||||
.inside {
|
||||
--x: 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
`),
|
||||
).toMatchInlineSnapshot(`
|
||||
"
|
||||
@scope (:is(.parent-a, .parent-b) > .from) {
|
||||
.inside {
|
||||
--x: 1;
|
||||
}
|
||||
}
|
||||
"
|
||||
`)
|
||||
|
||||
// The `<scope-start>` selector is optional, so the first group in the
|
||||
// prelude is not necessarily the `<scope-start>` selector.
|
||||
expect(
|
||||
optimize(css`
|
||||
.parent {
|
||||
@scope to (& .to) {
|
||||
.inside {
|
||||
--x: 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
`),
|
||||
).toMatchInlineSnapshot(`
|
||||
"
|
||||
@scope to (:where(:scope) .to) {
|
||||
.parent .inside {
|
||||
--x: 1;
|
||||
}
|
||||
}
|
||||
"
|
||||
`)
|
||||
|
||||
// The parent selector is substituted with the same logic as the nesting
|
||||
// selector in regular style rules: `:is(…)` is used when substituting the
|
||||
// parent as-is would change the meaning (e.g. a type selector cannot
|
||||
// appear after a class selector in a compound selector), …
|
||||
expect(
|
||||
optimize(css`
|
||||
main {
|
||||
@scope (.card&) {
|
||||
.inside {
|
||||
--x: 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
`),
|
||||
).toMatchInlineSnapshot(`
|
||||
"
|
||||
@scope (.card:is(main)) {
|
||||
.inside {
|
||||
--x: 1;
|
||||
}
|
||||
}
|
||||
"
|
||||
`)
|
||||
|
||||
// … and dropped when the substitution is provably equivalent, even for
|
||||
// complex parent selectors
|
||||
expect(
|
||||
optimize(css`
|
||||
.a .b {
|
||||
@scope (& > .from) {
|
||||
.inside {
|
||||
--x: 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
`),
|
||||
).toMatchInlineSnapshot(`
|
||||
"
|
||||
@scope (.a .b > .from) {
|
||||
.inside {
|
||||
--x: 1;
|
||||
}
|
||||
}
|
||||
"
|
||||
`)
|
||||
})
|
||||
|
||||
it('should wrap bare declarations inside `@scope` in a `&` rule', async () => {
|
||||
// A bug in Lightning CSS causes an error when there are declarations
|
||||
// directly in the `@scope`. To fix this we will ensure a rule with
|
||||
// `:where(:scope)` is available.
|
||||
expect(
|
||||
optimize(css`
|
||||
@scope (.from) to (.to) {
|
||||
--x: 1;
|
||||
}
|
||||
`),
|
||||
).toMatchInlineSnapshot(`
|
||||
"
|
||||
@scope (.from) to (.to) {
|
||||
:where(:scope) {
|
||||
--x: 1;
|
||||
}
|
||||
}
|
||||
"
|
||||
`)
|
||||
|
||||
// When generated by a variant, the declarations resolve against the
|
||||
// parent rule: the `@scope` rule scopes _where the utility applies_
|
||||
// (like nesting `@media` does, and like variants do).
|
||||
//
|
||||
// Note: this deviates from native CSS nesting, where the `<scope-start>`
|
||||
// selector would be relative to `.parent` and the declarations would
|
||||
// apply to the scoping root. User-authored `@scope` rules (without the
|
||||
// `@in-variant` marker) keep those native semantics.
|
||||
expect(
|
||||
optimize(css`
|
||||
.parent {
|
||||
@in-variant {
|
||||
@scope (.from) {
|
||||
--x: 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
`),
|
||||
).toMatchInlineSnapshot(`
|
||||
"
|
||||
@scope (.from) {
|
||||
.parent {
|
||||
--x: 1;
|
||||
}
|
||||
}
|
||||
"
|
||||
`)
|
||||
})
|
||||
|
||||
it('should replace `&` with `:where(:scope)` for rules directly inside `@scope`', async () => {
|
||||
// Inside an `@scope` rule, the nesting selector behaves like
|
||||
// `:where(:scope)` and matches the scoping root with zero specificity.
|
||||
expect(
|
||||
optimize(css`
|
||||
@scope (.from) {
|
||||
& > p {
|
||||
--x: 1;
|
||||
}
|
||||
}
|
||||
`),
|
||||
).toMatchInlineSnapshot(`
|
||||
"
|
||||
@scope (.from) {
|
||||
:where(:scope) > p {
|
||||
--x: 1;
|
||||
}
|
||||
}
|
||||
"
|
||||
`)
|
||||
})
|
||||
|
||||
it('should handle `&` deeply nested in `@scope` as normal references to a parent', async () => {
|
||||
expect(
|
||||
optimize(css`
|
||||
@scope (.from) {
|
||||
&,
|
||||
.inside {
|
||||
--x: 1;
|
||||
|
||||
&:hover {
|
||||
--x: 2;
|
||||
}
|
||||
|
||||
&:focus {
|
||||
--x: 3;
|
||||
}
|
||||
}
|
||||
}
|
||||
`),
|
||||
).toMatchInlineSnapshot(`
|
||||
"
|
||||
@scope (.from) {
|
||||
:where(:scope), .inside {
|
||||
--x: 1;
|
||||
&:hover {
|
||||
--x: 2;
|
||||
}
|
||||
&:focus {
|
||||
--x: 3;
|
||||
}
|
||||
}
|
||||
}
|
||||
"
|
||||
`)
|
||||
})
|
||||
|
||||
it('should compile user-authored `@scope` rules with their native CSS nesting semantics', async () => {
|
||||
// The `<scope-start>` selector is relative to the parent rule (like
|
||||
// nested style rule selectors are), the rules inside are relative to
|
||||
// the scoping root, and `&` refers to the scoping root
|
||||
expect(
|
||||
optimize(css`
|
||||
.parent {
|
||||
@scope (.from) to (.to) {
|
||||
.inside {
|
||||
--x: 1;
|
||||
}
|
||||
|
||||
& > .child {
|
||||
--x: 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
`),
|
||||
).toMatchInlineSnapshot(`
|
||||
"
|
||||
@scope (.parent .from) to (.to) {
|
||||
.inside {
|
||||
--x: 1;
|
||||
}
|
||||
:where(:scope) > .child {
|
||||
--x: 2;
|
||||
}
|
||||
}
|
||||
"
|
||||
`)
|
||||
|
||||
// A trailing `&` makes the parent rule the scoping root: the scoping
|
||||
// roots are `.parent` elements inside `.from` elements
|
||||
expect(
|
||||
optimize(css`
|
||||
.parent {
|
||||
@scope (.from &) to (.to) {
|
||||
.inside {
|
||||
--x: 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
`),
|
||||
).toMatchInlineSnapshot(`
|
||||
"
|
||||
@scope (.from .parent) to (.to) {
|
||||
.inside {
|
||||
--x: 1;
|
||||
}
|
||||
}
|
||||
"
|
||||
`)
|
||||
|
||||
// Bare declarations apply to the scoping root. They are wrapped in a
|
||||
// `:where(:scope)` rule, which is the spec's exact equivalent, because
|
||||
// Lightning CSS drops bare declarations inside `@scope` entirely.
|
||||
expect(
|
||||
optimize(css`
|
||||
.parent {
|
||||
@scope (.from) {
|
||||
--x: 1;
|
||||
}
|
||||
}
|
||||
`),
|
||||
).toMatchInlineSnapshot(`
|
||||
"
|
||||
@scope (.parent .from) {
|
||||
:where(:scope) {
|
||||
--x: 1;
|
||||
}
|
||||
}
|
||||
"
|
||||
`)
|
||||
|
||||
// Also at the top level
|
||||
expect(
|
||||
optimize(css`
|
||||
@scope (.from) to (.to) {
|
||||
--x: 1;
|
||||
|
||||
.inside {
|
||||
--x: 2;
|
||||
}
|
||||
}
|
||||
`),
|
||||
).toMatchInlineSnapshot(`
|
||||
"
|
||||
@scope (.from) to (.to) {
|
||||
:where(:scope) {
|
||||
--x: 1;
|
||||
}
|
||||
.inside {
|
||||
--x: 2;
|
||||
}
|
||||
}
|
||||
"
|
||||
`)
|
||||
|
||||
// Every selector in a `<scope-start>` selector list is relative to the
|
||||
// parent rule, whether it uses `&` or not
|
||||
expect(
|
||||
optimize(css`
|
||||
.parent {
|
||||
@scope (.a, & > .b) {
|
||||
.inside {
|
||||
--x: 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
`),
|
||||
).toMatchInlineSnapshot(`
|
||||
"
|
||||
@scope (.parent .a, .parent > .b) {
|
||||
.inside {
|
||||
--x: 1;
|
||||
}
|
||||
}
|
||||
"
|
||||
`)
|
||||
})
|
||||
|
||||
it('should leave `@property` and `@apply` alone', async () => {
|
||||
expect(
|
||||
optimize(css`
|
||||
|
|
|
|||
|
|
@ -401,6 +401,21 @@ export function optimizeAst(
|
|||
// Remove reference imports from printing
|
||||
if (node.context.reference) {
|
||||
return
|
||||
}
|
||||
|
||||
// Preserve context nodes that track the source of their subtree (variant
|
||||
// bodies and the user content slotted into them), so `handleNesting`
|
||||
// knows whether to compose `@scope` rules with the variant semantics or
|
||||
// their native CSS nesting semantics
|
||||
else if (node.context.source) {
|
||||
let copy = { ...node, nodes: [] as AstNode[] }
|
||||
for (let child of node.nodes) {
|
||||
transform(child, copy.nodes, { ...context, ...node.context }, depth)
|
||||
}
|
||||
|
||||
if (copy.nodes.length > 0) {
|
||||
parent.push(copy)
|
||||
}
|
||||
} else {
|
||||
for (let child of node.nodes) {
|
||||
transform(child, parent, { ...context, ...node.context }, depth)
|
||||
|
|
@ -658,6 +673,27 @@ export function optimizeAst(
|
|||
export function handleNesting(ast: AstNode[]): AstNode[] {
|
||||
let parseSelectorCache = new DefaultMap(SelectorParser.parse)
|
||||
|
||||
// Nodes with an `@scope` rule somewhere in their subtree. These cannot use
|
||||
// the "emit as-is" fast path for rules containing declarations, because
|
||||
// `@scope` rules change meaning when they stay nested inside a style rule and
|
||||
// must go through the hoisting machinery instead.
|
||||
let containsAtScope = new Set<AstNode>()
|
||||
{
|
||||
function scan(nodes: AstNode[]): boolean {
|
||||
let found = false
|
||||
for (let node of nodes) {
|
||||
if (node.kind === 'declaration' || node.kind === 'comment') continue
|
||||
|
||||
if (scan(node.nodes) || (node.kind === 'at-rule' && node.name === '@scope')) {
|
||||
containsAtScope.add(node)
|
||||
found = true
|
||||
}
|
||||
}
|
||||
return found
|
||||
}
|
||||
scan(ast)
|
||||
}
|
||||
|
||||
// Track `rule` selectors as we go
|
||||
let selectorStack: [
|
||||
selector: string,
|
||||
|
|
@ -690,6 +726,45 @@ export function handleNesting(ast: AstNode[]): AstNode[] {
|
|||
// Track whether we should skip a node in the `exit` phase
|
||||
let skipExit = new Set<AstNode>()
|
||||
|
||||
// Track the source of the subtree we are currently in. Variant bodies are
|
||||
// wrapped in a `context` node with `source: 'variant'`, and the user content
|
||||
// slotted into them is wrapped in `source: 'user'`. `@scope` rules whose
|
||||
// nearest source is a variant are hoisted with the variant semantics, all
|
||||
// other `@scope` rules use their native CSS nesting semantics.
|
||||
let sourceStack: (string | boolean)[] = []
|
||||
|
||||
// Selector stacks that are masked while inside an `@scope` rule whose
|
||||
// `<scope-start>` selector consumed the parent selector via `&`.
|
||||
//
|
||||
// Once the parent selector is part of the `<scope-start>` selector, the rules
|
||||
// inside the `@scope` are relative to the scoping root, not to the parent
|
||||
// rule. Selectors in scoped style rules only match elements in scope, and the
|
||||
// parent matches ancestors of the scoping root, so prefixing the rules with
|
||||
// the parent selector would make them match nothing at all.
|
||||
//
|
||||
// E.g.:
|
||||
//
|
||||
// ```css
|
||||
// .parent {
|
||||
// @scope (& > .scope) {
|
||||
// .content {
|
||||
// color: red;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// ```
|
||||
//
|
||||
// becomes:
|
||||
//
|
||||
// ```css
|
||||
// @scope (.parent > .scope) {
|
||||
// .content { /* ← not `.parent .content` */
|
||||
// color: red;
|
||||
// }
|
||||
// }
|
||||
// ```
|
||||
let maskedSelectorStacks = new Map<AstNode, typeof selectorStack>()
|
||||
|
||||
walk(ast, {
|
||||
enter(node) {
|
||||
switch (node.kind) {
|
||||
|
|
@ -705,13 +780,40 @@ export function handleNesting(ast: AstNode[]): AstNode[] {
|
|||
// part of a string inside an attribute selector. But the
|
||||
// SelectorParser will take care of that.
|
||||
if (node.selector.includes('&')) {
|
||||
// Inside an `@scope` rule, the nesting selector behaves like
|
||||
// `:where(:scope)` and matches the scoping root with zero
|
||||
// specificity. E.g.:
|
||||
//
|
||||
// ```css
|
||||
// @scope (.checkout) {
|
||||
// & > p {
|
||||
// color: red;
|
||||
// }
|
||||
// }
|
||||
// ```
|
||||
//
|
||||
// becomes:
|
||||
//
|
||||
// ```css
|
||||
// @scope (.checkout) {
|
||||
// :where(:scope) > p {
|
||||
// color: red;
|
||||
// }
|
||||
// }
|
||||
// ```
|
||||
//
|
||||
// See: https://drafts.csswg.org/css-nesting-1/#nesting-at-scope
|
||||
let replacement = atRuleStack.some(([name]) => name === '@scope')
|
||||
? ':where(:scope)'
|
||||
: ':scope'
|
||||
|
||||
let ast = SelectorParser.parse(node.selector)
|
||||
let changed = false
|
||||
|
||||
walk(ast, (node) => {
|
||||
if (node.kind === 'selector' && node.value === '&') {
|
||||
changed = true
|
||||
node.value = ':scope'
|
||||
node.value = replacement
|
||||
}
|
||||
})
|
||||
|
||||
|
|
@ -740,280 +842,7 @@ export function handleNesting(ast: AstNode[]): AstNode[] {
|
|||
|
||||
let lastSelector = selectorStack[selectorStack.length - 1][0]
|
||||
let selector = segment(node.selector, ',')
|
||||
.map((selector) => {
|
||||
// Fast path: we know there isn't an `&` so we can prepend the
|
||||
// parent selector immediately.
|
||||
if (!selector.includes('&')) {
|
||||
let lastAst = parseSelectorCache.get(lastSelector)
|
||||
return `${lastAst.length === 1 && lastAst[0].kind === 'list' ? `:is(${lastSelector})` : lastSelector} ${selector}`
|
||||
}
|
||||
|
||||
// Slow path: we need to replace the `&` with the parent
|
||||
// selector. A simple `replaceAll(…)` won't work because a `&`
|
||||
// could be escaped, or could be part of an attribute selector.
|
||||
//
|
||||
// Much safer to parse the selector and replace the `&` that way
|
||||
{
|
||||
let ast = SelectorParser.parse(selector)
|
||||
let changed = false
|
||||
walk(ast, {
|
||||
enter(node, ctx) {
|
||||
if (node.kind !== 'selector' || node.value !== '&') return
|
||||
|
||||
changed = true
|
||||
|
||||
// Safest option: use `is(…)` semantics when
|
||||
// substituting `&` for the parent selector.
|
||||
node.value = `:is(${lastSelector})`
|
||||
|
||||
// We should always have a parent, so this shouldn't happen
|
||||
if (ctx.parent === null) return
|
||||
|
||||
// Optimizations:
|
||||
let parentAst = parseSelectorCache.get(lastSelector)
|
||||
|
||||
// 1. If we're dealing with multiple selectors, then we
|
||||
// know that the `:is(…)` needs to stay. Nothing to optimize.
|
||||
if (parentAst.length === 1 && parentAst[0].kind === 'list') {
|
||||
return // Keep `:is(…)` semantics
|
||||
}
|
||||
|
||||
// 2. We know that `&` is standalone when it's inside of
|
||||
// a complex selector. E.g. `[before] & [after]`
|
||||
if (ctx.parent.kind === 'complex') {
|
||||
// `& [after]`
|
||||
//
|
||||
// `:is(…)` semantics are not required, because these
|
||||
// are equivalent:
|
||||
//
|
||||
// - `:is(div) [after]` → `div [after]`
|
||||
// - `:is(.x) [after]` → `.x [after]`
|
||||
// - `:is([before]) [after]` → `[before] [after]`
|
||||
// - `:is(.a > .b) [after]` → `.a > .b [after]`
|
||||
if (ctx.index === 0) {
|
||||
node.value = lastSelector
|
||||
return
|
||||
}
|
||||
|
||||
// `[before] &`
|
||||
//
|
||||
// `:is(…)` semantics are required if we're dealing
|
||||
// with a complex parent selector. Otherwise the
|
||||
// meaning of the selector could change:
|
||||
//
|
||||
// - `[before] :is(div)` → `[before] div`
|
||||
// - `[before] :is(.x)` → `[before] .x`
|
||||
// - `[before] :is([after])` → `[before] [after]`
|
||||
// - `[before] :is(.a > .b)` → `[before] :is(.a > .b)` (!)
|
||||
else if (ctx.index === ctx.siblings.length - 1) {
|
||||
if (parentAst[0].kind === 'complex') {
|
||||
return // Keep `:is(…)` semantics
|
||||
}
|
||||
|
||||
node.value = lastSelector
|
||||
return
|
||||
}
|
||||
|
||||
// `[before] & [after]`
|
||||
//
|
||||
// `:is(…)` semantics are required if we're dealing
|
||||
// with a complex parent selector. Otherwise the
|
||||
// meaning of the selector could change:
|
||||
//
|
||||
// - `[before] :is(div) [after]` → `[before] div [after]`
|
||||
// - `[before] :is(.x) [after]` → `[before] .x [after]`
|
||||
// - `[before] :is(.a > .b) [after]` → `[before] :is(.a > .b) [after]` (!)
|
||||
else {
|
||||
if (parentAst[0].kind === 'complex') {
|
||||
return // Keep `:is(…)` semantics
|
||||
}
|
||||
|
||||
node.value = lastSelector
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 3. We know that `&` is attached to some other
|
||||
// selector when it's inside of a compound selector.
|
||||
//
|
||||
// E.g. `[before]&[after]`
|
||||
//
|
||||
// We have to be careful that our parent, when it's
|
||||
// part of a complex selector, that the same rules apply
|
||||
//
|
||||
// E.g.: `[before] &[after]`
|
||||
// ^ current node
|
||||
// ^^^^^^^^ compound selector
|
||||
// ^^^^^^^^^^^^^^^^^ complex selector
|
||||
//
|
||||
else if (ctx.parent.kind === 'compound') {
|
||||
if (parentAst[0].kind === 'complex') {
|
||||
let path = ctx.path()
|
||||
let grandParent = path[path.length - 2]
|
||||
|
||||
// When our compound parent is part of a complex
|
||||
// selector, and it's not the very first node, then we
|
||||
// can't safely get rid of the `:is(…)` if the last
|
||||
// selector is a complex selector as well, unless the
|
||||
// `&` maps to a single selector or compound selector.
|
||||
//
|
||||
// ```css
|
||||
// .foo .bar { /* Complex selector */
|
||||
// .system &:focus { /* Complex selector + compound selecto*/
|
||||
// --x: 1;
|
||||
// }
|
||||
// }
|
||||
// .foo:hover { /* Compound selector */
|
||||
// .system &:focus { /* Complex selector + compound selector */
|
||||
// --x: 2;
|
||||
// }
|
||||
// }
|
||||
// ```
|
||||
//
|
||||
// ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
|
||||
//
|
||||
// ```css
|
||||
// .system :is(.foo .bar):focus { /* Cannot drop the `:is(…)`, otherwise `.system` and `.foo` can be swapped in the DOM */
|
||||
// --x: 1;
|
||||
// }
|
||||
// .system .foo:hover:focus {
|
||||
// --x: 2;
|
||||
// }
|
||||
// ```
|
||||
if (
|
||||
grandParent &&
|
||||
grandParent.kind === 'complex' &&
|
||||
grandParent.nodes[0] !== ctx.parent
|
||||
) {
|
||||
return // Keep `:is(…)` semantics
|
||||
}
|
||||
}
|
||||
|
||||
// `&*` and `&div` are invalid CSS so these should stay
|
||||
// invalid. They should be written as `*&` and `div&` instead.
|
||||
if (
|
||||
ctx.siblings
|
||||
.slice(ctx.index + 1)
|
||||
.some(
|
||||
(sibling) =>
|
||||
SelectorParser.isUniversalSelector(sibling) ||
|
||||
SelectorParser.isTypeSelector(sibling),
|
||||
)
|
||||
) {
|
||||
return // Keep `:is(…)` semantics
|
||||
}
|
||||
|
||||
// `&[after]`
|
||||
//
|
||||
// `:is(…)` semantics are not required, because these
|
||||
// are equivalent:
|
||||
//
|
||||
// - `:is(div)[after]` → `div[after]`
|
||||
// - `:is(.x)[after]` → `.x[after]`
|
||||
// - `:is([before])[after]` → `[before][after]`
|
||||
// - `:is(.a > .b)[after]` → `.a > .b[after]`
|
||||
if (ctx.index === 0) {
|
||||
node.value = lastSelector
|
||||
return
|
||||
}
|
||||
|
||||
// `[before]&`
|
||||
//
|
||||
// `:is(…)` semantics are required if we're dealing with a
|
||||
//
|
||||
// - complex parent selector, to prevent changing the meaning of the selector
|
||||
// - a universal selector, because `*` needs to be first
|
||||
// - a type selector, because `div` needs to be first
|
||||
//
|
||||
// - `[before]:is(div)` → `[before]:is(div)` (!)
|
||||
// - `[before]:is(*)` → `[before]:is(*)` (!)
|
||||
// - `[before]:is(.a > .b)` → `[before]:is(.a > .b)` (!)
|
||||
// - `[before]:is(.x)` → `[before].x`
|
||||
else if (ctx.index === ctx.siblings.length - 1) {
|
||||
if (
|
||||
parentAst[0].kind === 'complex' ||
|
||||
SelectorParser.isUniversalSelector(parentAst[0]) ||
|
||||
SelectorParser.isTypeSelector(parentAst[0])
|
||||
) {
|
||||
return // Keep `:is(…)` semantics
|
||||
}
|
||||
|
||||
node.value = lastSelector
|
||||
return
|
||||
}
|
||||
|
||||
// `[before]&[after]`
|
||||
//
|
||||
// `:is(…)` semantics are required if we're dealing with a
|
||||
//
|
||||
// - complex parent selector, to prevent changing the meaning of the selector
|
||||
// - a universal selector, because `*` needs to be first
|
||||
// - a type selector, because `div` needs to be first
|
||||
//
|
||||
// - `[before]:is(div)[after]` → `[before]:is(div)[after]` (!)
|
||||
// - `[before]:is(*)[after]` → `[before]:is(*)[after]` (!)
|
||||
// - `[before]:is(.a > .b)[after]` → `[before]:is(.a > .b)[after]` (!)
|
||||
// - `[before]:is(.x)[after]` → `[before].x[after]`
|
||||
else {
|
||||
if (
|
||||
parentAst[0].kind === 'complex' ||
|
||||
SelectorParser.isUniversalSelector(parentAst[0]) ||
|
||||
SelectorParser.isTypeSelector(parentAst[0])
|
||||
) {
|
||||
return // Keep `:is(…)` semantics
|
||||
}
|
||||
|
||||
node.value = lastSelector
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 4. When the current node is a function argument (e.g.
|
||||
// `:not(&))`, then we can drop the `:is(…)` entirely.
|
||||
//
|
||||
// The only exception is when the parent has multiple
|
||||
// selectors because then we would introduce multiple
|
||||
// arguments. Multiple selectors are already handled.
|
||||
else if (ctx.parent.kind === 'function') {
|
||||
node.value = lastSelector
|
||||
return
|
||||
}
|
||||
},
|
||||
exit(node, ctx) {
|
||||
// Optimization: We can remove the universal selector `*` if
|
||||
// they are part of a compound selector. E.g.:
|
||||
//
|
||||
// - `*:hover` → `:hover`
|
||||
// - `*[attribute]` → `[attribute]`
|
||||
//
|
||||
// Except when the `*` is a namespace, e.g.: `*|div`,
|
||||
// because `*|div` (any namespace) and `|div` (no
|
||||
// namespace) have different meanings.
|
||||
if (
|
||||
ctx.index === 0 &&
|
||||
ctx.siblings.length > 1 &&
|
||||
ctx.parent?.kind === 'compound' &&
|
||||
SelectorParser.isUniversalSelector(node)
|
||||
) {
|
||||
let next = ctx.siblings[1]
|
||||
if (next.kind === 'selector' && next.value.charCodeAt(0) === PIPE) {
|
||||
return
|
||||
}
|
||||
return WalkAction.ReplaceSkip([])
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
if (changed) {
|
||||
return SelectorParser.toCss(ast)
|
||||
}
|
||||
|
||||
// It could be that `&` was not found as an actual selector,
|
||||
// in that case we still have to prepend the parent selector.
|
||||
let lastAst = parseSelectorCache.get(lastSelector)
|
||||
return `${lastAst.length === 1 && lastAst[0].kind === 'list' ? `:is(${lastSelector})` : lastSelector} ${selector}`
|
||||
}
|
||||
})
|
||||
.map((selector) => substituteNestingSelector(selector, lastSelector))
|
||||
.join(', ')
|
||||
selectorStack.push([selector, node.src, node.dst])
|
||||
}
|
||||
|
|
@ -1048,7 +877,14 @@ export function handleNesting(ast: AstNode[]): AstNode[] {
|
|||
// }
|
||||
// }
|
||||
// ```
|
||||
if (node.nodes.some((child) => child.kind === 'declaration')) {
|
||||
//
|
||||
// The exception is when the rule contains an `@scope` rule somewhere,
|
||||
// because it must go through the normal hoisting machinery instead.
|
||||
// See `containsAtScope` for more details.
|
||||
if (
|
||||
node.nodes.some((child) => child.kind === 'declaration') &&
|
||||
!containsAtScope.has(node)
|
||||
) {
|
||||
// Emitting each child instead of the node itself because we do want
|
||||
// to flatten the current node and its selector that is already
|
||||
// pushed to the stack.
|
||||
|
|
@ -1072,7 +908,196 @@ export function handleNesting(ast: AstNode[]): AstNode[] {
|
|||
|
||||
// Hoist at-rules
|
||||
else if (HOISTABLE_AT_RULES.has(node.name)) {
|
||||
atRuleStack.push([node.name, node.params, node.src, node.dst])
|
||||
let params = node.params
|
||||
|
||||
// `@scope` is the only hoistable at-rule with selectors in its
|
||||
// prelude, and the only one that changes meaning when it stays
|
||||
// nested inside a style rule. Resolve the prelude and its contents
|
||||
// before hoisting, using one of two composition modes:
|
||||
//
|
||||
// 1. Variant-generated `@scope` rules attach the parent selector
|
||||
// (the utility) to the rules _inside_ the scope:
|
||||
//
|
||||
// ```css
|
||||
// .scoped\:underline {
|
||||
// @scope (.from) to (.to) {
|
||||
// text-decoration-line: underline;
|
||||
// }
|
||||
// }
|
||||
// ```
|
||||
//
|
||||
// becomes:
|
||||
//
|
||||
// ```css
|
||||
// @scope (.from) to (.to) {
|
||||
// .scoped\:underline {
|
||||
// text-decoration-line: underline;
|
||||
// }
|
||||
// }
|
||||
// ```
|
||||
// This way the utility is properly sandwiched between the
|
||||
// `.from` and `.to` boundaries.
|
||||
//
|
||||
// 2. User-authored `@scope` rules keep their native CSS nesting
|
||||
// semantics: the `<scope-start>` selector is relative to the parent
|
||||
// rule, and the rules inside are relative to the scoping root:
|
||||
//
|
||||
// ```css
|
||||
// .parent {
|
||||
// @scope (.from) {
|
||||
// color: red;
|
||||
// }
|
||||
// }
|
||||
// ```
|
||||
//
|
||||
// becomes:
|
||||
//
|
||||
// ```css
|
||||
// @scope (.parent .from) {
|
||||
// :where(:scope) {
|
||||
// color: red;
|
||||
// }
|
||||
// }
|
||||
// ```
|
||||
//
|
||||
// In a perfect world we leave this alone, but Lightning CSS
|
||||
// seems to incorrectly transform this into a version where the
|
||||
// `.parent` class is gone entirely:
|
||||
//
|
||||
// ```css
|
||||
// @scope (.from) {
|
||||
// color: red;
|
||||
// }
|
||||
// ```
|
||||
//
|
||||
// See: https://drafts.csswg.org/css-nesting-1/#nesting-at-scope
|
||||
if (node.name === '@scope') {
|
||||
let isVariant = sourceStack[sourceStack.length - 1] === 'variant'
|
||||
let hasParent = selectorStack.length > 0
|
||||
|
||||
// Lightning CSS bug: This snippet will error
|
||||
//
|
||||
// ```css
|
||||
// @scope {
|
||||
// --x: 1;
|
||||
// }
|
||||
// ```
|
||||
//
|
||||
// We will wrap these bare-declarations in a `&` rule to fix the crash:
|
||||
// ```css
|
||||
// @scope {
|
||||
// & {
|
||||
// --x: 1;
|
||||
// }
|
||||
// }
|
||||
// ```
|
||||
{
|
||||
let queue: (AtRule | Context)[] = [node]
|
||||
|
||||
for (let parent of queue) {
|
||||
let newNodes: AstNode[] = []
|
||||
let group: AstNode[] | null = null
|
||||
|
||||
for (let child of parent.nodes) {
|
||||
if (child.kind === 'context') queue.push(child)
|
||||
|
||||
if (child.kind === 'declaration' || child.kind === 'comment') {
|
||||
if (group === null) {
|
||||
group = []
|
||||
newNodes.push(styleRule('&', group))
|
||||
}
|
||||
group.push(child)
|
||||
} else {
|
||||
group = null
|
||||
newNodes.push(child)
|
||||
}
|
||||
}
|
||||
|
||||
parent.nodes = newNodes
|
||||
}
|
||||
}
|
||||
|
||||
if (params.includes('&') || (!isVariant && hasParent)) {
|
||||
// The selector to substitute for `&` in the `<scope-start>`
|
||||
// selector: the elements matched by the nearest ancestor style
|
||||
// rule, or `:scope` when there is none.
|
||||
let parentSelector = hasParent ? selectorStack[selectorStack.length - 1][0] : null
|
||||
|
||||
let paramsAst = ValueParser.parse(params)
|
||||
|
||||
// Whether the current `(…)` group is a `<scope-end>` selector.
|
||||
//
|
||||
// ```css
|
||||
// @scope (.from) to (.to)
|
||||
// ^^^^^^^ scope-start (optional)
|
||||
// ^^^^^ scope-end
|
||||
//
|
||||
// @scope to (.to)
|
||||
// ^^^^^ scope-end
|
||||
// ```
|
||||
let isScopeEnd = false
|
||||
|
||||
// Whether the `<scope-start>` selector consumed the parent
|
||||
// selector
|
||||
let consumedParent = false
|
||||
|
||||
for (let paramNode of paramsAst) {
|
||||
if (paramNode.kind === 'word' && paramNode.value === 'to') {
|
||||
isScopeEnd = true
|
||||
continue
|
||||
}
|
||||
|
||||
// A `(…)` group parses as a function call without a name
|
||||
if (paramNode.kind !== 'function' || paramNode.value !== '') continue
|
||||
|
||||
let selector = ValueParser.toCss(paramNode.nodes)
|
||||
|
||||
// A user-authored `<scope-start>` selector is relative to the
|
||||
// parent rule, and resolves exactly like nested style rule
|
||||
// selectors do: `&` refers to the elements matched by the
|
||||
// parent rule, and selectors without `&` are prefixed with
|
||||
// it.
|
||||
if (!isScopeEnd && !isVariant && parentSelector !== null) {
|
||||
paramNode.nodes = [
|
||||
ValueParser.word(
|
||||
segment(selector, ',')
|
||||
.map((part) => substituteNestingSelector(part.trim(), parentSelector))
|
||||
.join(', '),
|
||||
),
|
||||
]
|
||||
consumedParent = true
|
||||
}
|
||||
|
||||
// Otherwise, only an explicit `&` is resolved. In the
|
||||
// `<scope-start>` selector, `&` refers to the elements
|
||||
// matched by the nearest ancestor style rule (or `:scope`
|
||||
// when there is none). In the `<scope-end>` selector, `&`
|
||||
// refers to the scoping root and behaves like
|
||||
// `:where(:scope)`.
|
||||
else if (selector.includes('&')) {
|
||||
let replacement = isScopeEnd ? ':where(:scope)' : (parentSelector ?? ':scope')
|
||||
|
||||
paramNode.nodes = [
|
||||
ValueParser.word(substituteNestingSelector(selector, replacement)),
|
||||
]
|
||||
if (!isScopeEnd && hasParent) consumedParent = true
|
||||
}
|
||||
}
|
||||
|
||||
params = ValueParser.toCss(paramsAst)
|
||||
|
||||
// Mask the selector stack for the `@scope` rule's subtree, so
|
||||
// its rules resolve like top-level rules within the scope (and
|
||||
// `&` resolves to `:where(:scope)`). The stack is restored in
|
||||
// the exit phase. See `maskedSelectorStacks` for more details.
|
||||
if (consumedParent) {
|
||||
maskedSelectorStacks.set(node, selectorStack)
|
||||
selectorStack = []
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
atRuleStack.push([node.name, params, node.src, node.dst])
|
||||
}
|
||||
|
||||
// If we can't hoist them, emit them immediately as-is
|
||||
|
|
@ -1091,6 +1116,9 @@ export function handleNesting(ast: AstNode[]): AstNode[] {
|
|||
}
|
||||
|
||||
case 'context':
|
||||
if (node.context.source) sourceStack.push(node.context.source)
|
||||
break
|
||||
|
||||
case 'at-root':
|
||||
break
|
||||
|
||||
|
|
@ -1112,12 +1140,22 @@ export function handleNesting(ast: AstNode[]): AstNode[] {
|
|||
case 'at-rule': {
|
||||
nodes = null
|
||||
atRuleStack.pop()
|
||||
|
||||
// Restore the selector stack that was masked by this `@scope` rule
|
||||
let maskedSelectorStack = maskedSelectorStacks.get(node)
|
||||
if (maskedSelectorStack) {
|
||||
selectorStack = maskedSelectorStack
|
||||
maskedSelectorStacks.delete(node)
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
case 'context':
|
||||
if (node.context.source) sourceStack.pop()
|
||||
break
|
||||
|
||||
case 'declaration':
|
||||
case 'comment':
|
||||
case 'context':
|
||||
case 'at-root':
|
||||
break
|
||||
|
||||
|
|
@ -1301,6 +1339,274 @@ export function handleNesting(ast: AstNode[]): AstNode[] {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Substitutes the `&` selector with the parent selector with `:is(…)` semantics.
|
||||
//
|
||||
// If the `&` is not found, we will prepend it using a descendant combinator.
|
||||
// E.g.: `& ${selector}` → `${parentSelector} ${selector}`
|
||||
//
|
||||
// In some situations we can get rid of the `:is(…)` wrapper, but only if it's safe to do so.
|
||||
function substituteNestingSelector(selector: string, parentSelector: string): string {
|
||||
// Slow path: we need to replace the `&` with the parent selector. A simple
|
||||
// `replaceAll(…)` won't work because a `&` could be escaped, or could be
|
||||
// part of an attribute selector.
|
||||
//
|
||||
// Much safer to parse the selector and replace the `&` that way
|
||||
if (selector.includes('&')) {
|
||||
let ast = SelectorParser.parse(selector)
|
||||
let changed = false
|
||||
walk(ast, {
|
||||
enter(node, ctx) {
|
||||
if (node.kind !== 'selector' || node.value !== '&') return
|
||||
|
||||
changed = true
|
||||
|
||||
// Safest option: use `is(…)` semantics when substituting `&` for the
|
||||
// parent selector.
|
||||
node.value = `:is(${parentSelector})`
|
||||
|
||||
// We should always have a parent, so this shouldn't happen
|
||||
if (ctx.parent === null) return
|
||||
|
||||
// Optimizations:
|
||||
let parentAst = parseSelectorCache.get(parentSelector)
|
||||
|
||||
// 1. If we're dealing with multiple selectors, then we know that the
|
||||
// `:is(…)` needs to stay. Nothing to optimize.
|
||||
if (parentAst.length === 1 && parentAst[0].kind === 'list') {
|
||||
return // Keep `:is(…)` semantics
|
||||
}
|
||||
|
||||
// 2. We know that `&` is standalone when it's inside of a complex
|
||||
// selector. E.g. `[before] & [after]`
|
||||
if (ctx.parent.kind === 'complex') {
|
||||
// `& [after]`
|
||||
//
|
||||
// `:is(…)` semantics are not required, because these are equivalent:
|
||||
//
|
||||
// - `:is(div) [after]` → `div [after]`
|
||||
// - `:is(.x) [after]` → `.x [after]`
|
||||
// - `:is([before]) [after]` → `[before] [after]`
|
||||
// - `:is(.a > .b) [after]` → `.a > .b [after]`
|
||||
if (ctx.index === 0) {
|
||||
node.value = parentSelector
|
||||
return
|
||||
}
|
||||
|
||||
// `[before] &`
|
||||
//
|
||||
// `:is(…)` semantics are required if we're dealing with a complex
|
||||
// parent selector. Otherwise the meaning of the selector could
|
||||
// change:
|
||||
//
|
||||
// - `[before] :is(div)` → `[before] div`
|
||||
// - `[before] :is(.x)` → `[before] .x`
|
||||
// - `[before] :is([after])` → `[before] [after]`
|
||||
// - `[before] :is(.a > .b)` → `[before] :is(.a > .b)` (!)
|
||||
else if (ctx.index === ctx.siblings.length - 1) {
|
||||
if (parentAst[0].kind === 'complex') {
|
||||
return // Keep `:is(…)` semantics
|
||||
}
|
||||
|
||||
node.value = parentSelector
|
||||
return
|
||||
}
|
||||
|
||||
// `[before] & [after]`
|
||||
//
|
||||
// `:is(…)` semantics are required if we're dealing with a complex
|
||||
// parent selector. Otherwise the meaning of the selector could
|
||||
// change:
|
||||
//
|
||||
// - `[before] :is(div) [after]` → `[before] div [after]`
|
||||
// - `[before] :is(.x) [after]` → `[before] .x [after]`
|
||||
// - `[before] :is(.a > .b) [after]` → `[before] :is(.a > .b) [after]` (!)
|
||||
else {
|
||||
if (parentAst[0].kind === 'complex') {
|
||||
return // Keep `:is(…)` semantics
|
||||
}
|
||||
|
||||
node.value = parentSelector
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 3. We know that `&` is attached to some other selector when it's
|
||||
// inside of a compound selector.
|
||||
//
|
||||
// E.g. `[before]&[after]`
|
||||
//
|
||||
// We have to be careful that our parent, when it's part of a complex
|
||||
// selector, that the same rules apply
|
||||
//
|
||||
// E.g.: `[before] &[after]`
|
||||
// ^ current node
|
||||
// ^^^^^^^^ compound selector
|
||||
// ^^^^^^^^^^^^^^^^^ complex selector
|
||||
//
|
||||
else if (ctx.parent.kind === 'compound') {
|
||||
if (parentAst[0].kind === 'complex') {
|
||||
let path = ctx.path()
|
||||
let grandParent = path[path.length - 2]
|
||||
|
||||
// When our compound parent is part of a complex selector, and it's
|
||||
// not the very first node, then we can't safely get rid of the
|
||||
// `:is(…)` if the last selector is a complex selector as well,
|
||||
// unless the `&` maps to a single selector or compound selector.
|
||||
//
|
||||
// ```css
|
||||
// .foo .bar { /* Complex selector */
|
||||
// .system &:focus { /* Complex selector + compound selecto*/
|
||||
// --x: 1;
|
||||
// }
|
||||
// }
|
||||
// .foo:hover { /* Compound selector */
|
||||
// .system &:focus { /* Complex selector + compound selector */
|
||||
// --x: 2;
|
||||
// }
|
||||
// }
|
||||
// ```
|
||||
//
|
||||
// ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
|
||||
//
|
||||
// ```css
|
||||
// .system :is(.foo .bar):focus { /* Cannot drop the `:is(…)`, otherwise `.system` and `.foo` can be swapped in the DOM */
|
||||
// --x: 1;
|
||||
// }
|
||||
// .system .foo:hover:focus {
|
||||
// --x: 2;
|
||||
// }
|
||||
// ```
|
||||
if (
|
||||
grandParent &&
|
||||
grandParent.kind === 'complex' &&
|
||||
grandParent.nodes[0] !== ctx.parent
|
||||
) {
|
||||
return // Keep `:is(…)` semantics
|
||||
}
|
||||
}
|
||||
|
||||
// `&*` and `&div` are invalid CSS so these should stay invalid. They
|
||||
// should be written as `*&` and `div&` instead.
|
||||
if (
|
||||
ctx.siblings
|
||||
.slice(ctx.index + 1)
|
||||
.some(
|
||||
(sibling) =>
|
||||
SelectorParser.isUniversalSelector(sibling) ||
|
||||
SelectorParser.isTypeSelector(sibling),
|
||||
)
|
||||
) {
|
||||
return // Keep `:is(…)` semantics
|
||||
}
|
||||
|
||||
// `&[after]`
|
||||
//
|
||||
// `:is(…)` semantics are not required, because these are equivalent:
|
||||
//
|
||||
// - `:is(div)[after]` → `div[after]`
|
||||
// - `:is(.x)[after]` → `.x[after]`
|
||||
// - `:is([before])[after]` → `[before][after]`
|
||||
// - `:is(.a > .b)[after]` → `.a > .b[after]`
|
||||
if (ctx.index === 0) {
|
||||
node.value = parentSelector
|
||||
return
|
||||
}
|
||||
|
||||
// `[before]&`
|
||||
//
|
||||
// `:is(…)` semantics are required if we're dealing with a
|
||||
//
|
||||
// - complex parent selector, to prevent changing the meaning of the selector
|
||||
// - a universal selector, because `*` needs to be first
|
||||
// - a type selector, because `div` needs to be first
|
||||
//
|
||||
// - `[before]:is(div)` → `[before]:is(div)` (!)
|
||||
// - `[before]:is(*)` → `[before]:is(*)` (!)
|
||||
// - `[before]:is(.a > .b)` → `[before]:is(.a > .b)` (!)
|
||||
// - `[before]:is(.x)` → `[before].x`
|
||||
else if (ctx.index === ctx.siblings.length - 1) {
|
||||
if (
|
||||
parentAst[0].kind === 'complex' ||
|
||||
SelectorParser.isUniversalSelector(parentAst[0]) ||
|
||||
SelectorParser.isTypeSelector(parentAst[0])
|
||||
) {
|
||||
return // Keep `:is(…)` semantics
|
||||
}
|
||||
|
||||
node.value = parentSelector
|
||||
return
|
||||
}
|
||||
|
||||
// `[before]&[after]`
|
||||
//
|
||||
// `:is(…)` semantics are required if we're dealing with a
|
||||
//
|
||||
// - complex parent selector, to prevent changing the meaning of the selector
|
||||
// - a universal selector, because `*` needs to be first
|
||||
// - a type selector, because `div` needs to be first
|
||||
//
|
||||
// - `[before]:is(div)[after]` → `[before]:is(div)[after]` (!)
|
||||
// - `[before]:is(*)[after]` → `[before]:is(*)[after]` (!)
|
||||
// - `[before]:is(.a > .b)[after]` → `[before]:is(.a > .b)[after]` (!)
|
||||
// - `[before]:is(.x)[after]` → `[before].x[after]`
|
||||
else {
|
||||
if (
|
||||
parentAst[0].kind === 'complex' ||
|
||||
SelectorParser.isUniversalSelector(parentAst[0]) ||
|
||||
SelectorParser.isTypeSelector(parentAst[0])
|
||||
) {
|
||||
return // Keep `:is(…)` semantics
|
||||
}
|
||||
|
||||
node.value = parentSelector
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 4. When the current node is a function argument (e.g. `:not(&))`,
|
||||
// then we can drop the `:is(…)` entirely.
|
||||
//
|
||||
// The only exception is when the parent has multiple selectors
|
||||
// because then we would introduce multiple arguments. Multiple
|
||||
// selectors are already handled.
|
||||
else if (ctx.parent.kind === 'function') {
|
||||
node.value = parentSelector
|
||||
return
|
||||
}
|
||||
},
|
||||
exit(node, ctx) {
|
||||
// Optimization: We can remove the universal selector `*` if they are
|
||||
// part of a compound selector. E.g.:
|
||||
//
|
||||
// - `*:hover` → `:hover`
|
||||
// - `*[attribute]` → `[attribute]`
|
||||
//
|
||||
// Except when the `*` is a namespace, e.g.: `*|div`, because `*|div`
|
||||
// (any namespace) and `|div` (no namespace) have different meanings.
|
||||
if (
|
||||
ctx.index === 0 &&
|
||||
ctx.siblings.length > 1 &&
|
||||
ctx.parent?.kind === 'compound' &&
|
||||
SelectorParser.isUniversalSelector(node)
|
||||
) {
|
||||
let next = ctx.siblings[1]
|
||||
if (next.kind === 'selector' && next.value.charCodeAt(0) === PIPE) {
|
||||
return
|
||||
}
|
||||
return WalkAction.ReplaceSkip([])
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
if (changed) return SelectorParser.toCss(ast)
|
||||
}
|
||||
|
||||
// Fast path: we know there isn't an `&` so we can prepend the parent
|
||||
// selector immediately.
|
||||
let parentAst = parseSelectorCache.get(parentSelector)
|
||||
return `${parentAst.length === 1 && parentAst[0].kind === 'list' ? `:is(${parentSelector})` : parentSelector} ${selector}`
|
||||
}
|
||||
}
|
||||
|
||||
// A set of at-rules that can be hoisted to the top without any repercussions.
|
||||
|
|
@ -1311,6 +1617,7 @@ const HOISTABLE_AT_RULES = new Set([
|
|||
'@layer',
|
||||
'@media',
|
||||
'@page',
|
||||
'@scope',
|
||||
'@starting-style',
|
||||
'@supports',
|
||||
'@view-transition',
|
||||
|
|
@ -1323,6 +1630,7 @@ const DROPPABLE_IF_EMPTY_AT_RULES = new Set([
|
|||
'@container',
|
||||
'@media',
|
||||
'@page',
|
||||
'@scope',
|
||||
'@starting-style',
|
||||
'@supports',
|
||||
'@view-transition',
|
||||
|
|
|
|||
|
|
@ -516,6 +516,8 @@ it('should not parse functional utilities with multiple modifiers', () => {
|
|||
utilities.functional('bg', () => [])
|
||||
|
||||
expect(run('bg-red-1/2/3', { utilities })).toMatchInlineSnapshot(`[]`)
|
||||
expect(run('bg-red-500/50/', { utilities })).toMatchInlineSnapshot(`[]`)
|
||||
expect(run('bg-red-500/50//foo', { utilities })).toMatchInlineSnapshot(`[]`)
|
||||
})
|
||||
|
||||
it('should parse a utility with an arbitrary value', () => {
|
||||
|
|
@ -1416,6 +1418,19 @@ it('should parse a functional variant with a modifier', () => {
|
|||
`)
|
||||
})
|
||||
|
||||
it('should not parse variants with multiple modifiers', () => {
|
||||
let utilities = new Utilities()
|
||||
utilities.static('flex', () => [])
|
||||
|
||||
let variants = new Variants()
|
||||
variants.static('hover', () => {})
|
||||
variants.compound('group', Compounds.StyleRules, () => {})
|
||||
|
||||
expect(run('group-hover/foo:flex', { utilities, variants })).toHaveLength(1)
|
||||
expect(run('group-hover/foo/:flex', { utilities, variants })).toEqual([])
|
||||
expect(run('group-hover/foo//bar:flex', { utilities, variants })).toEqual([])
|
||||
})
|
||||
|
||||
it('should parse a functional variant starting with @', () => {
|
||||
let utilities = new Utilities()
|
||||
utilities.static('flex', () => [])
|
||||
|
|
|
|||
|
|
@ -372,6 +372,14 @@ export function* parseCandidate(input: string, designSystem: DesignSystem): Iter
|
|||
}
|
||||
}
|
||||
|
||||
// If there's more than one modifier, the utility is invalid.
|
||||
//
|
||||
// E.g.:
|
||||
//
|
||||
// - `bg-red-500/50/50`
|
||||
let parts = segment(base, '/')
|
||||
if (parts.length > 2) return
|
||||
|
||||
// Figure out the new base and the modifier segment if present.
|
||||
//
|
||||
// E.g.:
|
||||
|
|
@ -381,14 +389,7 @@ export function* parseCandidate(input: string, designSystem: DesignSystem): Iter
|
|||
// ^^^^^^^^^^ -> Base without modifier
|
||||
// ^^ -> Modifier segment
|
||||
// ```
|
||||
let [baseWithoutModifier, modifierSegment = null, additionalModifier] = segment(base, '/')
|
||||
|
||||
// If there's more than one modifier, the utility is invalid.
|
||||
//
|
||||
// E.g.:
|
||||
//
|
||||
// - `bg-red-500/50/50`
|
||||
if (additionalModifier) return
|
||||
let [baseWithoutModifier, modifierSegment = null] = parts
|
||||
|
||||
let parsedModifier = modifierSegment === null ? null : parseModifier(modifierSegment)
|
||||
|
||||
|
|
@ -707,17 +708,18 @@ export function parseVariant(variant: string, designSystem: DesignSystem): Varia
|
|||
|
||||
// Static, functional and compound variants
|
||||
{
|
||||
// group-hover/group-name
|
||||
// ^^^^^^^^^^^ -> Variant without modifier
|
||||
// ^^^^^^^^^^ -> Modifier
|
||||
let [variantWithoutModifier, modifier = null, additionalModifier] = segment(variant, '/')
|
||||
|
||||
// If there's more than one modifier, the variant is invalid.
|
||||
//
|
||||
// E.g.:
|
||||
//
|
||||
// - `group-hover/foo/bar`
|
||||
if (additionalModifier) return null
|
||||
let parts = segment(variant, '/')
|
||||
if (parts.length > 2) return null
|
||||
|
||||
// group-hover/group-name
|
||||
// ^^^^^^^^^^^ -> Variant without modifier
|
||||
// ^^^^^^^^^^ -> Modifier
|
||||
let [variantWithoutModifier, modifier = null] = parts
|
||||
|
||||
let roots = findRoots(variantWithoutModifier, (root) => {
|
||||
return designSystem.variants.has(root)
|
||||
|
|
|
|||
|
|
@ -414,9 +414,11 @@ describe.each([['default'], ['with-variant'], ['important'], ['prefix']])('%s',
|
|||
// This should still migrate the `theme(…)` syntax to the modern syntax.
|
||||
['bg-[theme(colors.red.500/50%)]/50', 'bg-[--theme(--color-red-500/50%)]/50'],
|
||||
|
||||
// Variants, we can't use `var(…)` especially inside of `@media(…)`. We can
|
||||
// still upgrade the `theme(…)` to the modern syntax.
|
||||
['max-[theme(screens.lg)]:flex', 'max-[--theme(--breakpoint-lg)]:flex'],
|
||||
// Variants, we can't use `var(…)` especially inside of `@media(…)`. But
|
||||
// since the value matches the `lg` breakpoint exactly, we can migrate to
|
||||
// the `max-lg` variant.
|
||||
['max-[theme(screens.lg)]:flex', 'max-lg:flex'],
|
||||
['min-[theme(screens.lg)]:flex', 'lg:flex'], // We could also map to `min-lg:flex`
|
||||
// There are no variables for `--spacing` multiples, so we can't convert this
|
||||
['max-[theme(spacing.4)]:flex', 'max-[theme(spacing.4)]:flex'],
|
||||
|
||||
|
|
@ -719,6 +721,7 @@ describe.each([['default'], ['with-variant'], ['important'], ['prefix']])('%s',
|
|||
@import 'tailwindcss';
|
||||
@theme {
|
||||
--*: initial;
|
||||
--breakpoint-lg: 64rem;
|
||||
}
|
||||
`
|
||||
|
||||
|
|
@ -735,6 +738,11 @@ describe.each([['default'], ['with-variant'], ['important'], ['prefix']])('%s',
|
|||
['[@media(scripting:_none)]:flex', 'noscript:flex'],
|
||||
['[@media_(scripting:_none)]:flex', 'noscript:flex'],
|
||||
|
||||
// Arbitrary variants with media queries cannot use `var(…)`, but if an
|
||||
// equivalent variant exists we can use that one instead.
|
||||
['[@media(width>=theme(screens.lg))]:flex', 'lg:flex'], // `min-lg:flex` would also be valid
|
||||
['[@media(width<theme(screens.lg))]:flex', 'max-lg:flex'],
|
||||
|
||||
// With compound variants
|
||||
['has-[&:focus]:flex', 'has-focus:flex'],
|
||||
['not-[&:focus]:flex', 'not-focus:flex'],
|
||||
|
|
@ -951,6 +959,67 @@ describe.each([['default'], ['with-variant'], ['important'], ['prefix']])('%s',
|
|||
})
|
||||
})
|
||||
|
||||
// https://github.com/tailwindlabs/tailwindcss/issues/20365
|
||||
describe('media query and container query variants', () => {
|
||||
test.each([
|
||||
// Breakpoints (`--breakpoint-lg: 64rem`, `--breakpoint-md: 48rem`)
|
||||
['min-[64rem]:flex', 'lg:flex'],
|
||||
['max-[64rem]:flex', 'max-lg:flex'],
|
||||
['min-[48rem]:flex', 'md:flex'],
|
||||
['max-[48rem]:flex', 'max-md:flex'],
|
||||
|
||||
// With the `rem` option set, equivalent `px` values should also be
|
||||
// canonicalized to the breakpoint variants.
|
||||
['min-[1024px]:flex', 'lg:flex'],
|
||||
['max-[1024px]:flex', 'max-lg:flex'],
|
||||
|
||||
// Container queries (`--container-md: 28rem`)
|
||||
['@min-[28rem]:flex', '@md:flex'],
|
||||
['@max-[28rem]:flex', '@max-md:flex'],
|
||||
['@min-[448px]:flex', '@md:flex'],
|
||||
['@max-[448px]:flex', '@max-md:flex'],
|
||||
|
||||
// Values that don't map to a known breakpoint or container size should
|
||||
// stay as-is.
|
||||
['min-[123px]:flex', 'min-[123px]:flex'],
|
||||
['max-[123px]:flex', 'max-[123px]:flex'],
|
||||
['@min-[123px]:flex', '@min-[123px]:flex'],
|
||||
['@max-[123px]:flex', '@max-[123px]:flex'],
|
||||
|
||||
// Named variants that produce the same CSS should be kept as-is
|
||||
['min-lg:flex', 'min-lg:flex'],
|
||||
['@min-md:flex', '@min-md:flex'],
|
||||
])(testName, { timeout }, async (candidate, expected) => {
|
||||
let input = css`
|
||||
@import 'tailwindcss';
|
||||
`
|
||||
|
||||
await expectCanonicalization(input, candidate, expected)
|
||||
})
|
||||
|
||||
test.each([
|
||||
// Without the `rem` option, `px` values cannot be safely converted to
|
||||
// `rem` based breakpoints.
|
||||
['min-[1024px]:flex', 'min-[1024px]:flex'],
|
||||
['@min-[448px]:flex', '@min-[448px]:flex'],
|
||||
|
||||
// Same unit still works without the `rem` option
|
||||
['min-[64rem]:flex', 'lg:flex'],
|
||||
['max-[64rem]:flex', 'max-lg:flex'],
|
||||
['@min-[28rem]:flex', '@md:flex'],
|
||||
['@max-[28rem]:flex', '@max-md:flex'],
|
||||
])(`${testName} (no rem option)`, { timeout }, async (candidate, expected) => {
|
||||
let input = css`
|
||||
@import 'tailwindcss';
|
||||
`
|
||||
|
||||
await expectCanonicalization(input, candidate, expected, {
|
||||
collapse: true,
|
||||
logicalToPhysical: true,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('modernize arbitrary variants', () => {
|
||||
test.each([
|
||||
// Arbitrary variants
|
||||
|
|
@ -1546,4 +1615,49 @@ describe('regressions', () => {
|
|||
'bg-brand-purple',
|
||||
])
|
||||
})
|
||||
|
||||
// https://github.com/tailwindlabs/tailwindcss/issues/20365
|
||||
test('canonicalizes min/max media query and container query variants', async () => {
|
||||
let designSystem = await __unstable__loadDesignSystem(
|
||||
css`
|
||||
@tailwind utilities;
|
||||
@theme {
|
||||
--breakpoint-lg: 64rem;
|
||||
--container-lg: 32rem;
|
||||
--spacing: 0.25rem;
|
||||
}
|
||||
`,
|
||||
{ base: __dirname },
|
||||
)
|
||||
|
||||
expect(designSystem.canonicalizeCandidates(['min-[64rem]:flex'])).toEqual(['lg:flex'])
|
||||
expect(designSystem.canonicalizeCandidates(['max-[64rem]:flex'])).toEqual(['max-lg:flex'])
|
||||
expect(designSystem.canonicalizeCandidates(['@min-[32rem]:flex'])).toEqual(['@lg:flex'])
|
||||
expect(designSystem.canonicalizeCandidates(['@max-[32rem]:flex'])).toEqual(['@max-lg:flex'])
|
||||
expect(designSystem.canonicalizeCandidates(['min-[1024px]:flex'], { rem: 16 })).toEqual([
|
||||
'lg:flex',
|
||||
])
|
||||
})
|
||||
|
||||
// https://github.com/tailwindlabs/tailwindcss-intellisense/issues/1610
|
||||
test('does not merge utilities whose theme variables resolve to CSS-wide keywords', async () => {
|
||||
let designSystem = await __unstable__loadDesignSystem(
|
||||
css`
|
||||
@tailwind utilities;
|
||||
@theme {
|
||||
--foreground: unset;
|
||||
--default: unset;
|
||||
}
|
||||
@theme inline {
|
||||
--color-foreground: var(--foreground);
|
||||
--color-default-soft-hover: color-mix(in oklab, var(--default) 60%, transparent);
|
||||
}
|
||||
`,
|
||||
{ base: __dirname },
|
||||
)
|
||||
|
||||
expect(
|
||||
designSystem.canonicalizeCandidates(['text-foreground/60', 'text-default-soft-hover']),
|
||||
).toEqual(['text-foreground/60', 'text-default-soft-hover'])
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -72,12 +72,11 @@ interface InternalCanonicalizeOptions {
|
|||
signatureOptions: SignatureOptions
|
||||
}
|
||||
|
||||
type RemValue = number | null
|
||||
|
||||
interface DesignSystem extends BaseDesignSystem {
|
||||
storage: {
|
||||
[SIGNATURE_OPTIONS_KEY]: DefaultMap<
|
||||
number | null, // Rem value
|
||||
DefaultMap<SignatureFeatures, SignatureOptions>
|
||||
>
|
||||
[SIGNATURE_OPTIONS_KEY]: DefaultMap<RemValue, DefaultMap<SignatureFeatures, SignatureOptions>>
|
||||
[COMPARE_CANDIDATES_KEY]: DefaultMap<
|
||||
SignatureOptions,
|
||||
(a: Candidate | string, b: Candidate | string) => boolean
|
||||
|
|
@ -107,8 +106,8 @@ interface DesignSystem extends BaseDesignSystem {
|
|||
DefaultMap<string, DefaultMap<string, Set<string>>>
|
||||
>
|
||||
[PRE_COMPUTED_UTILITIES_KEY]: DefaultMap<SignatureOptions, DefaultMap<string, string[]>>
|
||||
[VARIANT_SIGNATURE_KEY]: DefaultMap<string, string | symbol>
|
||||
[PRE_COMPUTED_VARIANTS_KEY]: DefaultMap<string, string[]>
|
||||
[VARIANT_SIGNATURE_KEY]: DefaultMap<RemValue, DefaultMap<string, string | symbol>>
|
||||
[PRE_COMPUTED_VARIANTS_KEY]: DefaultMap<RemValue, DefaultMap<string, string[]>>
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1537,8 +1536,8 @@ function arbitraryVariants(
|
|||
options: InternalCanonicalizeOptions,
|
||||
): Variant | Variant[] {
|
||||
let designSystem = options.designSystem
|
||||
let signatures = designSystem.storage[VARIANT_SIGNATURE_KEY]
|
||||
let variants = designSystem.storage[PRE_COMPUTED_VARIANTS_KEY]
|
||||
let signatures = designSystem.storage[VARIANT_SIGNATURE_KEY].get(options.signatureOptions.rem)
|
||||
let variants = designSystem.storage[PRE_COMPUTED_VARIANTS_KEY].get(options.signatureOptions.rem)
|
||||
|
||||
let iterator = walkVariants(variant)
|
||||
for (let [variant] of iterator) {
|
||||
|
|
@ -1549,7 +1548,11 @@ function arbitraryVariants(
|
|||
if (typeof targetSignature !== 'string') continue
|
||||
|
||||
let foundVariants = variants.get(targetSignature)
|
||||
if (foundVariants.length !== 1) continue
|
||||
if (foundVariants.length === 0) continue
|
||||
|
||||
// The variant is already in a canonical form, e.g.: `min-lg` and `lg`
|
||||
// produce the same CSS, but both are valid so we keep them as-is.
|
||||
if (foundVariants.includes(targetString)) continue
|
||||
|
||||
let foundVariant = foundVariants[0]
|
||||
let parsedVariant = designSystem.parseVariant(foundVariant)
|
||||
|
|
@ -1769,7 +1772,7 @@ function modernizeArbitraryValuesVariant(
|
|||
): Variant | Variant[] {
|
||||
let result = [variant]
|
||||
let designSystem = options.designSystem
|
||||
let signatures = designSystem.storage[VARIANT_SIGNATURE_KEY]
|
||||
let signatures = designSystem.storage[VARIANT_SIGNATURE_KEY].get(options.signatureOptions.rem)
|
||||
|
||||
let iterator = walkVariants(variant)
|
||||
for (let [variant, parent] of iterator) {
|
||||
|
|
@ -2560,6 +2563,25 @@ function canonicalizeAst(designSystem: DesignSystem, ast: AstNode[], options: Si
|
|||
return ast
|
||||
}
|
||||
|
||||
// Variables whose theme value is a CSS-wide keyword (e.g.: `unset`) are never
|
||||
// inlined. These are typically registered as a placeholder to be re-assigned at
|
||||
// runtime, so two variables that share such a value are not interchangeable.
|
||||
//
|
||||
// E.g.:
|
||||
//
|
||||
// ```css
|
||||
// @theme {
|
||||
// --foreground: unset;
|
||||
// --background: unset;
|
||||
// }
|
||||
// ```
|
||||
//
|
||||
// Inlining would make `text-(--foreground)` and `text-(--background)` produce
|
||||
// the same signature `color: unset`, even though they are different at runtime.
|
||||
//
|
||||
// https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Values/Data_types#css-wide_keywords
|
||||
const CSS_WIDE_KEYWORDS = ['initial', 'inherit', 'revert', 'revert-layer', 'revert-rule', 'unset']
|
||||
|
||||
// Resolve theme values to their inlined value.
|
||||
//
|
||||
// E.g.:
|
||||
|
|
@ -2575,8 +2597,8 @@ function canonicalizeAst(designSystem: DesignSystem, ast: AstNode[], options: Si
|
|||
// }
|
||||
// ```
|
||||
//
|
||||
// Which conveniently will be equivalent to: `text-red-500` when we inline
|
||||
// the value.
|
||||
// Which conveniently will be equivalent to: `text-red-500` when we inline the
|
||||
// value.
|
||||
//
|
||||
// Without inlining:
|
||||
// ```css
|
||||
|
|
@ -2592,13 +2614,13 @@ function canonicalizeAst(designSystem: DesignSystem, ast: AstNode[], options: Si
|
|||
// }
|
||||
// ```
|
||||
//
|
||||
// Recently we made sure that utilities like `text-red-500` also generate
|
||||
// the fallback value for usage in `@reference` mode.
|
||||
// Recently we made sure that utilities like `text-red-500` also generate the
|
||||
// fallback value for usage in `@reference` mode.
|
||||
//
|
||||
// The second assumption is that if you use `var(--key, fallback)` that
|
||||
// happens to match a known variable _and_ its inlined value. Then we can
|
||||
// replace it with the inlined variable. This allows us to handle custom
|
||||
// `@theme` and `@theme inline` definitions.
|
||||
// The second assumption is that if you use `var(--key, fallback)` that happens
|
||||
// to match a known variable _and_ its inlined value. Then we can replace it
|
||||
// with the inlined variable. This allows us to handle custom `@theme` and
|
||||
// `@theme inline` definitions.
|
||||
function resolveVariablesInValue(value: string, designSystem: DesignSystem): string {
|
||||
let changed = false
|
||||
let valueAst = ValueParser.parse(value)
|
||||
|
|
@ -2627,6 +2649,9 @@ function resolveVariablesInValue(value: string, designSystem: DesignSystem): str
|
|||
seen.add(variable)
|
||||
if (variableValue === undefined) return // Couldn't resolve the variable
|
||||
|
||||
// CSS-wide keywords are never inlined
|
||||
if (CSS_WIDE_KEYWORDS.includes(variableValue.toLowerCase())) return
|
||||
|
||||
// Inject variable fallbacks when no fallback is present yet.
|
||||
//
|
||||
// A fallback could consist of multiple values.
|
||||
|
|
@ -2785,100 +2810,110 @@ export const VARIANT_SIGNATURE_KEY = Symbol()
|
|||
function createVariantSignatureCache(
|
||||
designSystem: DesignSystem,
|
||||
): DesignSystem['storage'][typeof VARIANT_SIGNATURE_KEY] {
|
||||
return new DefaultMap<string, string | symbol>((variant) => {
|
||||
try {
|
||||
// Ensure the prefix is added to the utility if it is not already present.
|
||||
variant =
|
||||
designSystem.theme.prefix && !variant.startsWith(designSystem.theme.prefix)
|
||||
? `${designSystem.theme.prefix}:${variant}`
|
||||
: variant
|
||||
return new DefaultMap((rem: number | null) => {
|
||||
return new DefaultMap<string, string | symbol>((variant) => {
|
||||
try {
|
||||
// Ensure the prefix is added to the utility if it is not already present.
|
||||
variant =
|
||||
designSystem.theme.prefix && !variant.startsWith(designSystem.theme.prefix)
|
||||
? `${designSystem.theme.prefix}:${variant}`
|
||||
: variant
|
||||
|
||||
// Use `@apply` to normalize the selector to `.x`
|
||||
let ast: AstNode[] = [styleRule('.x', [atRule('@apply', `${variant}:flex`)])]
|
||||
substituteAtApply(ast, designSystem)
|
||||
// Use `@apply` to normalize the selector to `.x`
|
||||
let ast: AstNode[] = [styleRule('.x', [atRule('@apply', `${variant}:flex`)])]
|
||||
substituteAtApply(ast, designSystem)
|
||||
|
||||
// Canonicalize selectors to their minimal form
|
||||
walk(ast, (node) => {
|
||||
// At-rules
|
||||
if (node.kind === 'at-rule' && node.params.includes(' ')) {
|
||||
node.params = node.params.replaceAll(' ', '')
|
||||
}
|
||||
// Canonicalize selectors to their minimal form
|
||||
walk(ast, (node) => {
|
||||
// At-rules
|
||||
if (node.kind === 'at-rule') {
|
||||
// Normalize dimensions such that equivalent values in different
|
||||
// units are considered the same. E.g.: with a root font size of
|
||||
// `16px`, `@media (width >= 64rem)` and `@media (width >= 1024px)`
|
||||
// are equivalent.
|
||||
node.params = constantFoldDeclaration(node.params, rem)
|
||||
|
||||
// Style rules
|
||||
else if (node.kind === 'rule') {
|
||||
let selectorAst = SelectorParser.parse(node.selector)
|
||||
let changed = false
|
||||
walk(selectorAst, (node) => {
|
||||
// Assumption: when we have a list of selectors: `.foo, .bar` we
|
||||
// want to mark this as changed because this will be re-printed as
|
||||
// `.foo,.bar`.
|
||||
//
|
||||
// Similarly, when we receive a combinator like `.foo + .bar`, this
|
||||
// will be printed as `.foo+.bar`.
|
||||
//
|
||||
// It could be that this was already optimal, but then this would be
|
||||
// a no-op situation.
|
||||
if (node.kind === 'list' || node.kind === 'combinator') {
|
||||
changed = true
|
||||
if (node.params.includes(' ')) {
|
||||
node.params = node.params.replaceAll(' ', '')
|
||||
}
|
||||
}
|
||||
|
||||
// Remove unnecessary `:is(…)` selectors
|
||||
else if (node.kind === 'function' && node.value === ':is') {
|
||||
// A single selector inside of `:is(…)` can be replaced with the
|
||||
// selector itself.
|
||||
// Style rules
|
||||
else if (node.kind === 'rule') {
|
||||
let selectorAst = SelectorParser.parse(node.selector)
|
||||
let changed = false
|
||||
walk(selectorAst, (node) => {
|
||||
// Assumption: when we have a list of selectors: `.foo, .bar` we
|
||||
// want to mark this as changed because this will be re-printed as
|
||||
// `.foo,.bar`.
|
||||
//
|
||||
// E.g.: `:is(.foo)` → `.foo`
|
||||
if (node.nodes.length === 1) {
|
||||
// Similarly, when we receive a combinator like `.foo + .bar`, this
|
||||
// will be printed as `.foo+.bar`.
|
||||
//
|
||||
// It could be that this was already optimal, but then this would be
|
||||
// a no-op situation.
|
||||
if (node.kind === 'list' || node.kind === 'combinator') {
|
||||
changed = true
|
||||
return WalkAction.Replace(node.nodes)
|
||||
}
|
||||
|
||||
// A selector with the universal selector `*` followed by a pseudo
|
||||
// class, can be replaced with the pseudo class itself.
|
||||
// Remove unnecessary `:is(…)` selectors
|
||||
else if (node.kind === 'function' && node.value === ':is') {
|
||||
// A single selector inside of `:is(…)` can be replaced with the
|
||||
// selector itself.
|
||||
//
|
||||
// E.g.: `:is(.foo)` → `.foo`
|
||||
if (node.nodes.length === 1) {
|
||||
changed = true
|
||||
return WalkAction.Replace(node.nodes)
|
||||
}
|
||||
|
||||
// A selector with the universal selector `*` followed by a pseudo
|
||||
// class, can be replaced with the pseudo class itself.
|
||||
else if (
|
||||
node.nodes.length === 2 &&
|
||||
node.nodes[0].kind === 'selector' &&
|
||||
node.nodes[0].value === '*' &&
|
||||
node.nodes[1].kind === 'selector' &&
|
||||
node.nodes[1].value[0] === ':'
|
||||
) {
|
||||
changed = true
|
||||
return WalkAction.Replace(node.nodes[1])
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure `*` exists before pseudo selectors inside of `:not(…)`,
|
||||
// `:where(…)`, …
|
||||
//
|
||||
// E.g.:
|
||||
//
|
||||
// `:not(:first-child)` → `:not(*:first-child)`
|
||||
//
|
||||
else if (
|
||||
node.nodes.length === 2 &&
|
||||
node.nodes[0].kind === 'selector' &&
|
||||
node.nodes[0].value === '*' &&
|
||||
node.nodes[1].kind === 'selector' &&
|
||||
node.nodes[1].value[0] === ':'
|
||||
node.kind === 'function' &&
|
||||
node.value[0] === ':' &&
|
||||
node.nodes[0]?.kind === 'selector' &&
|
||||
node.nodes[0]?.value[0] === ':'
|
||||
) {
|
||||
changed = true
|
||||
return WalkAction.Replace(node.nodes[1])
|
||||
node.nodes.unshift({ kind: 'selector', value: '*' })
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// Ensure `*` exists before pseudo selectors inside of `:not(…)`,
|
||||
// `:where(…)`, …
|
||||
//
|
||||
// E.g.:
|
||||
//
|
||||
// `:not(:first-child)` → `:not(*:first-child)`
|
||||
//
|
||||
else if (
|
||||
node.kind === 'function' &&
|
||||
node.value[0] === ':' &&
|
||||
node.nodes[0]?.kind === 'selector' &&
|
||||
node.nodes[0]?.value[0] === ':'
|
||||
) {
|
||||
changed = true
|
||||
node.nodes.unshift({ kind: 'selector', value: '*' })
|
||||
if (changed) {
|
||||
node.selector = SelectorParser.toCss(selectorAst, true)
|
||||
}
|
||||
})
|
||||
|
||||
if (changed) {
|
||||
node.selector = SelectorParser.toCss(selectorAst, true)
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
// Compute the final signature, by generating the CSS for the variant
|
||||
let signature = toCss(ast)
|
||||
return signature
|
||||
} catch {
|
||||
// A unique symbol is returned to ensure that 2 signatures resulting in
|
||||
// `null` are not considered equal.
|
||||
return Symbol()
|
||||
}
|
||||
// Compute the final signature, by generating the CSS for the variant
|
||||
let signature = toCss(ast)
|
||||
return signature
|
||||
} catch {
|
||||
// A unique symbol is returned to ensure that 2 signatures resulting in
|
||||
// `null` are not considered equal.
|
||||
return Symbol()
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -2886,19 +2921,31 @@ export const PRE_COMPUTED_VARIANTS_KEY = Symbol()
|
|||
function createPreComputedVariantsCache(
|
||||
designSystem: DesignSystem,
|
||||
): DesignSystem['storage'][typeof PRE_COMPUTED_VARIANTS_KEY] {
|
||||
let signatures = designSystem.storage[VARIANT_SIGNATURE_KEY]
|
||||
let lookup = new DefaultMap<string, string[]>(() => [])
|
||||
return new DefaultMap((rem: number | null) => {
|
||||
let signatures = designSystem.storage[VARIANT_SIGNATURE_KEY].get(rem)
|
||||
let lookup = new DefaultMap<string, string[]>(() => [])
|
||||
|
||||
// Actual static variants
|
||||
for (let [root, variant] of designSystem.variants.entries()) {
|
||||
if (variant.kind === 'static') {
|
||||
let signature = signatures.get(root)
|
||||
if (typeof signature !== 'string') continue
|
||||
lookup.get(signature).push(root)
|
||||
for (let [root, variant] of designSystem.variants.entries()) {
|
||||
// Actual static variants
|
||||
if (variant.kind === 'static') {
|
||||
let signature = signatures.get(root)
|
||||
if (typeof signature !== 'string') continue
|
||||
lookup.get(signature).push(root)
|
||||
}
|
||||
|
||||
// Functional variants with known values, e.g.: `max-lg`, `@min-md`, …
|
||||
else if (variant.kind === 'functional') {
|
||||
for (let value of designSystem.variants.getCompletions(root)) {
|
||||
let name = root === '@' ? `@${value}` : `${root}-${value}`
|
||||
let signature = signatures.get(name)
|
||||
if (typeof signature !== 'string') continue
|
||||
lookup.get(signature).push(name)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return lookup
|
||||
return lookup
|
||||
})
|
||||
}
|
||||
|
||||
function temporarilyDisableThemeInline<T>(designSystem: DesignSystem, cb: () => T): T {
|
||||
|
|
|
|||
|
|
@ -309,6 +309,19 @@ function upgradeToFullPluginSupport({
|
|||
|
||||
let resolvedValue = sharedPluginApi.theme(path, undefined)
|
||||
|
||||
// If we're dealing with an object that has the `DEFAULT` key, unwrap it to
|
||||
// the default value first. This happens for namespace root lookups where
|
||||
// the CSS theme defines a bare value, e.g. `--shadow` resolved via
|
||||
// `theme('shadow')`.
|
||||
if (
|
||||
typeof resolvedValue === 'object' &&
|
||||
resolvedValue !== null &&
|
||||
!Array.isArray(resolvedValue) &&
|
||||
'DEFAULT' in resolvedValue
|
||||
) {
|
||||
resolvedValue = resolvedValue.DEFAULT
|
||||
}
|
||||
|
||||
// When a tuple is returned, return the first element
|
||||
if (Array.isArray(resolvedValue) && resolvedValue.length === 2) {
|
||||
return resolvedValue[0]
|
||||
|
|
@ -319,16 +332,6 @@ function upgradeToFullPluginSupport({
|
|||
return resolvedValue.join(', ')
|
||||
}
|
||||
|
||||
// If we're dealing with an object that has the `DEFAULT` key, return the
|
||||
// default value
|
||||
else if (
|
||||
typeof resolvedValue === 'object' &&
|
||||
resolvedValue !== null &&
|
||||
'DEFAULT' in resolvedValue
|
||||
) {
|
||||
return resolvedValue.DEFAULT
|
||||
}
|
||||
|
||||
// Otherwise only allow string values here, objects (and namespace maps)
|
||||
// are treated as non-resolved values for the CSS `theme()` function.
|
||||
else if (typeof resolvedValue === 'string') {
|
||||
|
|
|
|||
|
|
@ -1784,7 +1784,7 @@ test('The theme() function does not try indexing into strings', async () => {
|
|||
).toMatchInlineSnapshot(`
|
||||
"
|
||||
:root, :host {
|
||||
--color-what: light-dark(red, red);
|
||||
--color-what: red;
|
||||
}
|
||||
|
||||
.text-what {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,189 @@
|
|||
import { describe, expect, test } from 'vitest'
|
||||
import { buildDesignSystem } from '../../design-system'
|
||||
import { Theme } from '../../theme'
|
||||
import { createCompatConfig } from './create-compat-config'
|
||||
import { resolveConfig } from './resolve-config'
|
||||
|
||||
function buildCompatConfig(cssValues: Record<string, string>) {
|
||||
let theme = new Theme()
|
||||
for (let [key, value] of Object.entries(cssValues)) {
|
||||
theme.add(key, value)
|
||||
}
|
||||
let design = buildDesignSystem(theme)
|
||||
|
||||
let { resolvedConfig } = resolveConfig(design, [
|
||||
{ config: createCompatConfig(design.theme), base: '/root', reference: true, src: undefined },
|
||||
])
|
||||
|
||||
return resolvedConfig
|
||||
}
|
||||
|
||||
describe('theme namespace lookups', () => {
|
||||
test('a namespace that only defines a bare value resolves to `{ DEFAULT: … }`, not a string', () => {
|
||||
// When the CSS theme only defines `--text` (a single bare value),
|
||||
// `theme('text', {})` used to return the string `'1rem'`.
|
||||
//
|
||||
// Spreading that string, like the compat config does, produced char-indexed
|
||||
// garbage (`{ '0': '1', '1': 'r', … }`) instead of `{ DEFAULT: '1rem' }`.
|
||||
let config = buildCompatConfig({ '--text': '1rem' })
|
||||
|
||||
expect(config.theme?.fontSize?.DEFAULT).toBe('1rem')
|
||||
expect(config.theme?.fontSize).not.toHaveProperty('0')
|
||||
})
|
||||
|
||||
test('a bare value is kept alongside suffixed values in the same namespace', () => {
|
||||
let config = buildCompatConfig({
|
||||
'--text': '1rem',
|
||||
'--text-sm': '0.875rem',
|
||||
})
|
||||
|
||||
expect(config.theme?.fontSize?.DEFAULT).toBe('1rem')
|
||||
expect(config.theme?.fontSize?.sm).toBe('0.875rem')
|
||||
})
|
||||
|
||||
test('a naive spread of a theme namespace in a user config is safe', () => {
|
||||
let theme = new Theme()
|
||||
theme.add('--text', '1rem')
|
||||
let design = buildDesignSystem(theme)
|
||||
|
||||
let { resolvedConfig } = resolveConfig(design, [
|
||||
{
|
||||
config: {
|
||||
theme: {
|
||||
extend: {
|
||||
fontSize: ({ theme }: any) => ({ ...theme('text', {}) }),
|
||||
},
|
||||
},
|
||||
},
|
||||
base: '/root',
|
||||
reference: true,
|
||||
src: undefined,
|
||||
},
|
||||
])
|
||||
|
||||
expect(resolvedConfig.theme?.fontSize?.DEFAULT).toBe('1rem')
|
||||
expect(resolvedConfig.theme?.fontSize).not.toHaveProperty('0')
|
||||
})
|
||||
|
||||
test('namespace root lookups resolve to an object, key lookups resolve to the value', () => {
|
||||
let theme = new Theme()
|
||||
theme.add('--text', '1rem')
|
||||
theme.add('--animate-spin', 'spin 1s linear infinite')
|
||||
let design = buildDesignSystem(theme)
|
||||
|
||||
let root: unknown
|
||||
let rootWithDefault: unknown
|
||||
let leaf: unknown
|
||||
|
||||
resolveConfig(design, [
|
||||
{
|
||||
config: {
|
||||
theme: {
|
||||
extend: {
|
||||
fontSize: ({ theme }: any) => {
|
||||
root = theme('text')
|
||||
rootWithDefault = theme('text', {})
|
||||
leaf = theme('animate.spin')
|
||||
return {}
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
base: '/root',
|
||||
reference: true,
|
||||
src: undefined,
|
||||
},
|
||||
])
|
||||
|
||||
// A namespace root lookup always resolves to an object, like in v3, even
|
||||
// when the namespace only contains a bare value
|
||||
expect(root).toMatchObject({ DEFAULT: '1rem' })
|
||||
expect(rootWithDefault).toMatchObject({ DEFAULT: '1rem' })
|
||||
|
||||
// Lookups of a specific key resolve to the value itself
|
||||
expect(leaf).toBe('spin 1s linear infinite')
|
||||
})
|
||||
|
||||
test('lookups of a specific key still resolve to the value itself', () => {
|
||||
let theme = new Theme()
|
||||
theme.add('--animate-spin', 'spin 1s linear infinite')
|
||||
let design = buildDesignSystem(theme)
|
||||
|
||||
let { resolvedConfig } = resolveConfig(design, [
|
||||
{
|
||||
config: {
|
||||
theme: {
|
||||
extend: {
|
||||
animation: ({ theme }: any) => ({ spin: theme('animate.spin') }),
|
||||
},
|
||||
},
|
||||
},
|
||||
base: '/root',
|
||||
reference: true,
|
||||
src: undefined,
|
||||
},
|
||||
])
|
||||
|
||||
expect(resolvedConfig.theme?.animation?.spin).toBe('spin 1s linear infinite')
|
||||
})
|
||||
})
|
||||
|
||||
describe('createCompatConfig namespace mappings', () => {
|
||||
test('fontSize maps from CSS text namespace', () => {
|
||||
let config = buildCompatConfig({ '--text-base': '1rem' })
|
||||
expect(config.theme?.fontSize?.base).toBe('1rem')
|
||||
})
|
||||
|
||||
test('boxShadow maps from CSS shadow namespace', () => {
|
||||
let config = buildCompatConfig({ '--shadow-md': '0 4px 6px #000' })
|
||||
expect(config.theme?.boxShadow?.md).toBe('0 4px 6px #000')
|
||||
})
|
||||
|
||||
test('animation maps from CSS animate namespace', () => {
|
||||
let config = buildCompatConfig({ '--animate-spin': 'spin 1s linear infinite' })
|
||||
expect(config.theme?.animation?.spin).toBe('spin 1s linear infinite')
|
||||
})
|
||||
|
||||
test('aspectRatio maps from CSS aspect namespace', () => {
|
||||
let config = buildCompatConfig({ '--aspect-square': '1 / 1' })
|
||||
expect(config.theme?.aspectRatio?.square).toBe('1 / 1')
|
||||
})
|
||||
|
||||
test('borderRadius maps from CSS radius namespace', () => {
|
||||
let config = buildCompatConfig({ '--radius-lg': '0.5rem' })
|
||||
expect(config.theme?.borderRadius?.lg).toBe('0.5rem')
|
||||
})
|
||||
|
||||
test('screens maps from CSS breakpoint namespace', () => {
|
||||
let config = buildCompatConfig({ '--breakpoint-sm': '640px' })
|
||||
expect(config.theme?.screens?.sm).toBe('640px')
|
||||
})
|
||||
|
||||
test('letterSpacing maps from CSS tracking namespace', () => {
|
||||
let config = buildCompatConfig({ '--tracking-wide': '0.025em' })
|
||||
expect(config.theme?.letterSpacing?.wide).toBe('0.025em')
|
||||
})
|
||||
|
||||
test('lineHeight maps from CSS leading namespace', () => {
|
||||
let config = buildCompatConfig({ '--leading-relaxed': '1.75' })
|
||||
expect(config.theme?.lineHeight?.relaxed).toBe('1.75')
|
||||
})
|
||||
|
||||
test('maxWidth maps from the container namespace in the default theme', () => {
|
||||
let config = buildCompatConfig({})
|
||||
// The default theme has container.sm = '24rem'
|
||||
expect(config.theme?.maxWidth?.sm).toBe('24rem')
|
||||
})
|
||||
|
||||
test('transitionDuration gets DEFAULT from --default-transition-duration', () => {
|
||||
let config = buildCompatConfig({ '--default-transition-duration': '150ms' })
|
||||
expect(config.theme?.transitionDuration?.DEFAULT).toBe('150ms')
|
||||
})
|
||||
|
||||
test('transitionTimingFunction gets DEFAULT from --default-transition-timing-function', () => {
|
||||
let config = buildCompatConfig({
|
||||
'--default-transition-timing-function': 'cubic-bezier(0.4, 0, 0.2, 1)',
|
||||
})
|
||||
expect(config.theme?.transitionTimingFunction?.DEFAULT).toBe('cubic-bezier(0.4, 0, 0.2, 1)')
|
||||
})
|
||||
})
|
||||
|
|
@ -1642,6 +1642,83 @@ describe('addVariant', () => {
|
|||
`)
|
||||
})
|
||||
|
||||
test('addVariant with `@scope`', async () => {
|
||||
expect(
|
||||
await run(
|
||||
['blue:underline', 'green:underline'],
|
||||
css`
|
||||
@plugin "my-plugin";
|
||||
@layer utilities {
|
||||
@tailwind utilities;
|
||||
}
|
||||
`,
|
||||
{
|
||||
loadModule: async (_id, base) => {
|
||||
return {
|
||||
path: '',
|
||||
base,
|
||||
module: ({ addVariant }: PluginAPI) => {
|
||||
addVariant('blue', '@scope ([data-theme=blue]) to ([data-theme])')
|
||||
addVariant('green', '@scope ([data-theme=green]) to ([data-theme]) { & }')
|
||||
},
|
||||
}
|
||||
},
|
||||
},
|
||||
),
|
||||
).toMatchInlineSnapshot(`
|
||||
"
|
||||
@layer utilities {
|
||||
@scope ([data-theme="blue"]) to ([data-theme]) {
|
||||
.blue\\:underline {
|
||||
text-decoration-line: underline;
|
||||
}
|
||||
}
|
||||
|
||||
@scope ([data-theme="green"]) to ([data-theme]) {
|
||||
.green\\:underline {
|
||||
text-decoration-line: underline;
|
||||
}
|
||||
}
|
||||
}
|
||||
"
|
||||
`)
|
||||
})
|
||||
|
||||
test('matchVariant with `@scope`', async () => {
|
||||
expect(
|
||||
await run(
|
||||
['theme-[blue]:underline'],
|
||||
css`
|
||||
@plugin "my-plugin";
|
||||
@layer utilities {
|
||||
@tailwind utilities;
|
||||
}
|
||||
`,
|
||||
{
|
||||
loadModule: async (_id, base) => {
|
||||
return {
|
||||
path: '',
|
||||
base,
|
||||
module: ({ matchVariant }: PluginAPI) => {
|
||||
matchVariant('theme', (value) => `@scope ([data-theme=${value}]) to ([data-theme])`)
|
||||
},
|
||||
}
|
||||
},
|
||||
},
|
||||
),
|
||||
).toMatchInlineSnapshot(`
|
||||
"
|
||||
@layer utilities {
|
||||
@scope ([data-theme="blue"]) to ([data-theme]) {
|
||||
.theme-\\[blue\\]\\:underline {
|
||||
text-decoration-line: underline;
|
||||
}
|
||||
}
|
||||
}
|
||||
"
|
||||
`)
|
||||
})
|
||||
|
||||
test('addVariant with array of selectors', async () => {
|
||||
expect(
|
||||
await run(
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import type { Features } from '..'
|
||||
import { substituteAtApply } from '../apply'
|
||||
import { atRule, cloneAstNode, decl, rule, type AstNode } from '../ast'
|
||||
import { atRule, cloneAstNode, context, decl, rule, type AstNode } from '../ast'
|
||||
import type { Candidate, CandidateModifier, NamedUtilityValue } from '../candidate'
|
||||
import { substituteFunctions } from '../css-functions'
|
||||
import * as CSS from '../css-parser'
|
||||
|
|
@ -608,14 +608,28 @@ export function objectToAst(rules: CssInJs | CssInJs[]): AstNode[] {
|
|||
|
||||
function parseVariantValue(resolved: string | string[], nodes: AstNode[]): AstNode[] {
|
||||
let resolvedArray = typeof resolved === 'string' ? [resolved] : resolved
|
||||
return resolvedArray.flatMap((r) => {
|
||||
return resolvedArray.flatMap((r): AstNode | AstNode[] => {
|
||||
if (r.trim().endsWith('}')) {
|
||||
let usesAtScope = r.includes('@scope')
|
||||
let updatedCSS = r.replace('}', '{@slot}}')
|
||||
let ast = CSS.parse(updatedCSS)
|
||||
|
||||
if (usesAtScope) {
|
||||
substituteAtSlot(ast, [context({ source: 'user' }, nodes)])
|
||||
return context({ source: 'variant' }, ast)
|
||||
}
|
||||
|
||||
substituteAtSlot(ast, nodes)
|
||||
return ast
|
||||
} else {
|
||||
return rule(r, nodes)
|
||||
let node = rule(r, nodes)
|
||||
|
||||
if (node.kind === 'at-rule' && node.name === '@scope') {
|
||||
node.nodes = [context({ source: 'user' }, nodes)]
|
||||
return context({ source: 'variant' }, [node])
|
||||
}
|
||||
|
||||
return node
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -108,7 +108,12 @@ export function createThemeFn(
|
|||
// ```
|
||||
//
|
||||
// Prefer `DEFAULT` instead of exposing the object to plugin code.
|
||||
//
|
||||
// This only applies to lookups of a specific key (e.g. `colors.foo`). A
|
||||
// namespace root lookup (e.g. `theme('shadow')`) resolves to the whole
|
||||
// namespace as an object, like in v3.
|
||||
if (
|
||||
keypath.length > 1 &&
|
||||
cssValue !== null &&
|
||||
typeof cssValue === 'object' &&
|
||||
!Array.isArray(cssValue) &&
|
||||
|
|
@ -225,7 +230,12 @@ function readFromCss(
|
|||
// The request looked like `theme('animation.spin')` and was turned into a
|
||||
// lookup for `--animation-spin-*` which had only one entry which means it
|
||||
// should be returned directly.
|
||||
if ('DEFAULT' in obj && Object.keys(obj).length === 1) {
|
||||
//
|
||||
// This only applies to lookups of a specific key (`path.length > 1`). A
|
||||
// namespace root lookup like `theme('shadow')` resolves to the whole
|
||||
// namespace as an object, like in v3, so it must keep the object shape (`{
|
||||
// DEFAULT: … }`).
|
||||
if (path.length > 1 && 'DEFAULT' in obj && Object.keys(obj).length === 1) {
|
||||
return [obj.DEFAULT as any, optionsObj.DEFAULT ?? ThemeOptions.NONE] as const
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { atRule, decl, rule, type AstNode, type Rule, type StyleRule } from './ast'
|
||||
import { atRule, context, decl, rule, type AstNode, type Rule, type StyleRule } from './ast'
|
||||
import { type Candidate, type Variant } from './candidate'
|
||||
import { CompileAstFlags, type DesignSystem } from './design-system'
|
||||
import GLOBAL_PROPERTY_ORDER from './property-order'
|
||||
|
|
@ -187,7 +187,18 @@ export function applyVariant(
|
|||
// E.g. `[>img]:flex` is not valid, but `has-[>img]:flex` is
|
||||
if (variant.relative && depth === 0) return null
|
||||
|
||||
node.nodes = [rule(variant.selector, node.nodes)]
|
||||
let child: AstNode = rule(variant.selector, node.nodes)
|
||||
|
||||
// Wrap variant-generated `@scope` rules in a `context` marker, so they are
|
||||
// hoisted with the variant semantics instead of their native CSS nesting
|
||||
// semantics. The slotted content is marked as `user` content, so `@scope`
|
||||
// rules defined there keep their native CSS nesting semantics.
|
||||
if (child.kind === 'at-rule' && child.name === '@scope') {
|
||||
child.nodes = [context({ source: 'user' }, node.nodes)]
|
||||
child = context({ source: 'variant' }, [child])
|
||||
}
|
||||
|
||||
node.nodes = [child]
|
||||
return
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -203,7 +203,7 @@ describe.each(['Unix', 'Windows'])('Line endings: %s', (lineEndings) => {
|
|||
])
|
||||
})
|
||||
|
||||
it('should parse declarations with with strings and escaped string endings', () => {
|
||||
it('should parse declarations with strings and escaped string endings', () => {
|
||||
expect(
|
||||
parse(css`
|
||||
content: 'These are not the end "\' of the string';
|
||||
|
|
|
|||
|
|
@ -75,6 +75,8 @@ export function buildDesignSystem(
|
|||
let variants = createVariants(theme)
|
||||
|
||||
let parsedVariants = new DefaultMap((variant) => parseVariant(variant, designSystem))
|
||||
let cachedVariantOrder: Map<Variant, number> | null = null
|
||||
let cachedVariantOrderSize = -1
|
||||
let parsedCandidates = new DefaultMap((candidate) =>
|
||||
Array.from(parseCandidate(candidate, designSystem)),
|
||||
)
|
||||
|
|
@ -188,6 +190,11 @@ export function buildDesignSystem(
|
|||
},
|
||||
|
||||
getVariantOrder() {
|
||||
// parsedVariants only grows, so the cache should be reset only when the size changes
|
||||
if (cachedVariantOrder !== null && cachedVariantOrderSize === parsedVariants.size) {
|
||||
return cachedVariantOrder
|
||||
}
|
||||
|
||||
let variants = Array.from(parsedVariants.values())
|
||||
variants.sort((a, z) => this.variants.compare(a, z))
|
||||
|
||||
|
|
@ -209,6 +216,9 @@ export function buildDesignSystem(
|
|||
prevVariant = variant
|
||||
}
|
||||
|
||||
cachedVariantOrder = order
|
||||
cachedVariantOrderSize = parsedVariants.size
|
||||
|
||||
return order
|
||||
},
|
||||
|
||||
|
|
|
|||
|
|
@ -904,42 +904,17 @@ describe('@apply', () => {
|
|||
}
|
||||
`
|
||||
|
||||
// TODO: once Lightning CSS properly supports it, then we can drop this section:
|
||||
{
|
||||
let compiler = await compile(input)
|
||||
expect(compiler.build([])).toMatchInlineSnapshot(`
|
||||
".foo {
|
||||
text-decoration-line: underline;
|
||||
@apply --my-mixin-1;
|
||||
@apply --my-mixin-1();
|
||||
@apply --my-mixin-1 --my-mixin-2;
|
||||
@apply --my-mixin-1() --my-mixin-2();
|
||||
@apply --my-mixin-3 {
|
||||
color: red;
|
||||
}
|
||||
}
|
||||
"
|
||||
`)
|
||||
}
|
||||
|
||||
// TODO: this output is currently broken because Lightning CSS doesn't
|
||||
// handle this case correctly yet
|
||||
expect(await compileCss(input)).toMatchInlineSnapshot(`
|
||||
"
|
||||
.foo {
|
||||
text-decoration-line: underline;
|
||||
}
|
||||
|
||||
@apply --my-mixin-1;
|
||||
|
||||
@apply --my-mixin-1();
|
||||
|
||||
@apply --my-mixin-1 --my-mixin-2;
|
||||
|
||||
@apply --my-mixin-1() --my-mixin-2();
|
||||
|
||||
@apply --my-mixin-3 {
|
||||
color: red;
|
||||
@apply --my-mixin-1;
|
||||
@apply --my-mixin-1();
|
||||
@apply --my-mixin-1 --my-mixin-2;
|
||||
@apply --my-mixin-1() --my-mixin-2();
|
||||
@apply --my-mixin-3 {
|
||||
color: red;
|
||||
}
|
||||
}
|
||||
"
|
||||
`)
|
||||
|
|
@ -4685,6 +4660,319 @@ describe('@custom-variant', () => {
|
|||
})
|
||||
})
|
||||
|
||||
describe('@scope', () => {
|
||||
test('arbitrary variant', async () => {
|
||||
expect(await run(['[@scope_(.from)_to_(.to)]:underline'])).toMatchInlineSnapshot(`
|
||||
"
|
||||
@scope (.from) to (.to) {
|
||||
.\\[\\@scope_\\(\\.from\\)_to_\\(\\.to\\)\\]\\:underline {
|
||||
text-decoration-line: underline;
|
||||
}
|
||||
}
|
||||
"
|
||||
`)
|
||||
})
|
||||
|
||||
test('shorthand syntax', async () => {
|
||||
expect(
|
||||
await run(
|
||||
['scoped:underline'],
|
||||
css`
|
||||
@custom-variant scoped (@scope (.from) to (.to));
|
||||
|
||||
@layer utilities {
|
||||
@tailwind utilities;
|
||||
}
|
||||
`,
|
||||
),
|
||||
).toMatchInlineSnapshot(`
|
||||
"
|
||||
@layer utilities {
|
||||
@scope (.from) to (.to) {
|
||||
.scoped\\:underline {
|
||||
text-decoration-line: underline;
|
||||
}
|
||||
}
|
||||
}
|
||||
"
|
||||
`)
|
||||
})
|
||||
|
||||
test('with @slot syntax', async () => {
|
||||
expect(
|
||||
await run(
|
||||
['scoped:underline'],
|
||||
css`
|
||||
@custom-variant scoped {
|
||||
@scope (.from) to (.to) {
|
||||
@slot;
|
||||
}
|
||||
}
|
||||
|
||||
@layer utilities {
|
||||
@tailwind utilities;
|
||||
}
|
||||
`,
|
||||
),
|
||||
).toMatchInlineSnapshot(`
|
||||
"
|
||||
@layer utilities {
|
||||
@scope (.from) to (.to) {
|
||||
.scoped\\:underline {
|
||||
text-decoration-line: underline;
|
||||
}
|
||||
}
|
||||
}
|
||||
"
|
||||
`)
|
||||
})
|
||||
|
||||
test('@scope in a custom variant combined with user-authored `@scope` rules', async () => {
|
||||
expect(
|
||||
await run(
|
||||
['blue:bg-blue-500'],
|
||||
css`
|
||||
@layer utilities {
|
||||
@tailwind utilities;
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--color-blue-500: blue;
|
||||
}
|
||||
|
||||
/* In a variant */
|
||||
@custom-variant blue {
|
||||
@scope ([data-theme='blue']) to ([data-theme]) {
|
||||
@slot;
|
||||
}
|
||||
}
|
||||
|
||||
/* User CSS */
|
||||
.parent {
|
||||
/* @scope with bare declarations */
|
||||
@scope (.from) to (.to) {
|
||||
--x: 1;
|
||||
}
|
||||
|
||||
.child {
|
||||
.a {
|
||||
/* Variant with @scope used by @apply */
|
||||
@apply blue:[--x:2];
|
||||
}
|
||||
.b {
|
||||
/* Variant with @scope used by @apply combined with another variant */
|
||||
@apply blue:hover:[--x:3];
|
||||
}
|
||||
.c {
|
||||
/* Variant with @scoped used by @variant */
|
||||
@variant blue {
|
||||
--x: 4;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
),
|
||||
).toMatchInlineSnapshot(`
|
||||
"
|
||||
@layer utilities {
|
||||
@scope ([data-theme="blue"]) to ([data-theme]) {
|
||||
.blue\\:bg-blue-500 {
|
||||
background-color: #00f;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@scope (.parent .from) to (.to) {
|
||||
:where(:scope) {
|
||||
--x: 1;
|
||||
}
|
||||
}
|
||||
|
||||
@scope ([data-theme="blue"]) to ([data-theme]) {
|
||||
.parent .child .a {
|
||||
--x: 2;
|
||||
}
|
||||
|
||||
@media (hover: hover) {
|
||||
.parent .child .b:hover {
|
||||
--x: 3;
|
||||
}
|
||||
}
|
||||
|
||||
.parent .child .c {
|
||||
--x: 4;
|
||||
}
|
||||
}
|
||||
"
|
||||
`)
|
||||
})
|
||||
|
||||
test('`&` in the `@scope` prelude of a custom variant controls the composition', async () => {
|
||||
expect(
|
||||
await run(
|
||||
['in-blue:flex', 'blue-self:flex', 'scoped-panel:flex', 'in-blue:hover:flex'],
|
||||
css`
|
||||
/* Default: the utility applies to elements inside the scope */
|
||||
@custom-variant in-blue {
|
||||
@scope ([data-theme='blue']) to ([data-theme]) {
|
||||
@slot;
|
||||
}
|
||||
}
|
||||
|
||||
/* Trailing &: the utility itself becomes the scoping root */
|
||||
@custom-variant blue-self {
|
||||
@scope ([data-theme='blue'] &) to ([data-theme]) {
|
||||
@slot;
|
||||
}
|
||||
}
|
||||
|
||||
/* Leading &: the scoping roots are found inside the utility */
|
||||
@custom-variant scoped-panel {
|
||||
@scope (& .panel) {
|
||||
@slot;
|
||||
}
|
||||
}
|
||||
|
||||
@layer utilities {
|
||||
@tailwind utilities;
|
||||
}
|
||||
`,
|
||||
),
|
||||
).toMatchInlineSnapshot(`
|
||||
"
|
||||
@layer utilities {
|
||||
@scope ([data-theme="blue"]) to ([data-theme]) {
|
||||
.in-blue\\:flex {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
@media (hover: hover) {
|
||||
.in-blue\\:hover\\:flex:hover {
|
||||
display: flex;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@scope ([data-theme="blue"] .blue-self\\:flex) to ([data-theme]) {
|
||||
:where(:scope) {
|
||||
display: flex;
|
||||
}
|
||||
}
|
||||
|
||||
@scope (.scoped-panel\\:flex .panel) {
|
||||
:where(:scope) {
|
||||
display: flex;
|
||||
}
|
||||
}
|
||||
}
|
||||
"
|
||||
`)
|
||||
})
|
||||
|
||||
test('user-authored `@scope` inside `@variant` keeps its native semantics', async () => {
|
||||
// The `hocus` variant does not use `@scope` itself, so the inner `@scope`
|
||||
// is user CSS and compiles with the native CSS nesting semantics: the
|
||||
// parent selector moves into the prelude, and bare declarations apply to
|
||||
// the scoping root.
|
||||
expect(
|
||||
await compileCss(css`
|
||||
@custom-variant hocus (&:hover, &:focus);
|
||||
|
||||
.btn {
|
||||
@variant hocus {
|
||||
@scope (.from) to (.to) {
|
||||
--x: 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
`),
|
||||
).toMatchInlineSnapshot(`
|
||||
"
|
||||
@scope (:is(.btn:hover, .btn:focus) .from) to (.to) {
|
||||
:where(:scope) {
|
||||
--x: 1;
|
||||
}
|
||||
}
|
||||
"
|
||||
`)
|
||||
})
|
||||
|
||||
test('user-authored `@scope` inside a `@variant` that uses `@scope` keeps its native semantics', async () => {
|
||||
// The `blue` variant uses `@scope` itself, so its own `@scope` takes the
|
||||
// variant composition. But the user CSS slotted into its body is marked
|
||||
// as `user` content, so the inner `@scope` keeps its native CSS nesting
|
||||
// semantics: the parent selector moves into the prelude, and bare
|
||||
// declarations apply to the scoping root.
|
||||
expect(
|
||||
await compileCss(css`
|
||||
@custom-variant blue {
|
||||
@scope ([data-theme='blue']) to ([data-theme]) {
|
||||
@slot;
|
||||
}
|
||||
}
|
||||
|
||||
.btn {
|
||||
@variant blue {
|
||||
@scope (.from) to (.to) {
|
||||
--x: 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
`),
|
||||
).toMatchInlineSnapshot(`
|
||||
"
|
||||
@scope ([data-theme="blue"]) to ([data-theme]) {
|
||||
@scope (.btn .from) to (.to) {
|
||||
:where(:scope) {
|
||||
--x: 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
"
|
||||
`)
|
||||
})
|
||||
|
||||
test('@scope nested in a rule, nested in another @scope, with @slot', async () => {
|
||||
// Both `@scope` rules take the variant composition: neither prelude is
|
||||
// made relative to a parent, the outer/inner nesting order is preserved,
|
||||
// and the rule between them composes into the body with the utility's
|
||||
// selector.
|
||||
expect(
|
||||
await run(
|
||||
['foo:underline'],
|
||||
css`
|
||||
@custom-variant foo {
|
||||
@scope (.outer) to (.outer-limit) {
|
||||
.middle {
|
||||
@scope (.inner) to (.inner-limit) {
|
||||
@slot;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@layer utilities {
|
||||
@tailwind utilities;
|
||||
}
|
||||
`,
|
||||
),
|
||||
).toMatchInlineSnapshot(`
|
||||
"
|
||||
@layer utilities {
|
||||
@scope (.outer) to (.outer-limit) {
|
||||
@scope (.inner) to (.inner-limit) {
|
||||
.foo\\:underline .middle {
|
||||
text-decoration-line: underline;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"
|
||||
`)
|
||||
})
|
||||
})
|
||||
|
||||
test('built-in variants can be overridden while keeping their order', async () => {
|
||||
expect(
|
||||
await run(
|
||||
|
|
|
|||
|
|
@ -392,21 +392,25 @@ async function parseCss(
|
|||
}
|
||||
}
|
||||
|
||||
let usesAtScope = atRuleParams.some((param) => param.startsWith('@scope'))
|
||||
|
||||
customVariants.set(name, (designSystem) => {
|
||||
designSystem.variants.static(
|
||||
name,
|
||||
(r) => {
|
||||
let slot = usesAtScope ? [contextNode({ source: 'user' }, r.nodes)] : r.nodes
|
||||
|
||||
let nodes: AstNode[] = []
|
||||
|
||||
if (styleRuleSelectors.length > 0) {
|
||||
nodes.push(styleRule(styleRuleSelectors.join(', '), r.nodes))
|
||||
nodes.push(styleRule(styleRuleSelectors.join(', '), slot))
|
||||
}
|
||||
|
||||
for (let selector of atRuleParams) {
|
||||
nodes.push(rule(selector, r.nodes))
|
||||
nodes.push(rule(selector, slot))
|
||||
}
|
||||
|
||||
r.nodes = nodes
|
||||
r.nodes = usesAtScope ? [contextNode({ source: 'variant' }, nodes)] : nodes
|
||||
},
|
||||
{
|
||||
compounds: compoundsForSelectors([...styleRuleSelectors, ...atRuleParams]),
|
||||
|
|
|
|||
|
|
@ -12120,7 +12120,7 @@ test('rounded', async () => {
|
|||
}
|
||||
|
||||
.rounded-full {
|
||||
border-radius: 3.40282e38px;
|
||||
border-radius: 2147483647px;
|
||||
}
|
||||
|
||||
.rounded-none {
|
||||
|
|
@ -12154,18 +12154,28 @@ test('rounded', async () => {
|
|||
"
|
||||
`)
|
||||
expect(
|
||||
await run([
|
||||
'-rounded',
|
||||
'-rounded-full',
|
||||
'-rounded-none',
|
||||
'-rounded-sm',
|
||||
'-rounded-[4px]',
|
||||
'rounded/foo',
|
||||
'rounded-full/foo',
|
||||
'rounded-none/foo',
|
||||
'rounded-sm/foo',
|
||||
'rounded-[4px]/foo',
|
||||
]),
|
||||
await run(
|
||||
[
|
||||
'-rounded',
|
||||
'-rounded-full',
|
||||
'-rounded-none',
|
||||
'-rounded-sm',
|
||||
'-rounded-[4px]',
|
||||
'rounded/foo',
|
||||
'rounded-full/foo',
|
||||
'rounded-none/foo',
|
||||
'rounded-sm/foo',
|
||||
'rounded-[4px]/foo',
|
||||
'rounded-sm/[5]',
|
||||
'rounded-sm/(--foo)',
|
||||
],
|
||||
css`
|
||||
@theme {
|
||||
--radius-sm: 0.125rem;
|
||||
}
|
||||
@tailwind utilities;
|
||||
`,
|
||||
),
|
||||
).toEqual('')
|
||||
})
|
||||
|
||||
|
|
@ -22373,6 +22383,11 @@ test('stroke', async () => {
|
|||
// Width
|
||||
'-stroke-0',
|
||||
'stroke--1',
|
||||
'stroke-0/foo',
|
||||
'stroke-1/50',
|
||||
'stroke-2/[0.5]',
|
||||
'stroke-2/(--my-opacity)',
|
||||
'stroke-[12px]/foo',
|
||||
]),
|
||||
).toEqual('')
|
||||
})
|
||||
|
|
@ -24398,82 +24413,90 @@ test('filter', async () => {
|
|||
"
|
||||
`)
|
||||
expect(
|
||||
await run([
|
||||
'-filter',
|
||||
'-filter-none',
|
||||
'-filter-[var(--value)]',
|
||||
'-blur-xl',
|
||||
'-blur-[4px]',
|
||||
'brightness--50',
|
||||
'-brightness-50',
|
||||
'-brightness-[1.23]',
|
||||
'brightness-unknown',
|
||||
'contrast--50',
|
||||
'-contrast-50',
|
||||
'-contrast-[1.23]',
|
||||
'contrast-unknown',
|
||||
'-grayscale',
|
||||
'-grayscale-0',
|
||||
'grayscale--1',
|
||||
'-grayscale-[var(--value)]',
|
||||
'grayscale-unknown',
|
||||
'hue-rotate--5',
|
||||
'hue-rotate-unknown',
|
||||
'-invert',
|
||||
'invert--5',
|
||||
'-invert-0',
|
||||
'-invert-[var(--value)]',
|
||||
'invert-unknown',
|
||||
'-drop-shadow-xl',
|
||||
'-drop-shadow-[0_0_red]',
|
||||
await run(
|
||||
[
|
||||
'-filter',
|
||||
'-filter-none',
|
||||
'-filter-[var(--value)]',
|
||||
'-blur-xl',
|
||||
'-blur-[4px]',
|
||||
'brightness--50',
|
||||
'-brightness-50',
|
||||
'-brightness-[1.23]',
|
||||
'brightness-unknown',
|
||||
'contrast--50',
|
||||
'-contrast-50',
|
||||
'-contrast-[1.23]',
|
||||
'contrast-unknown',
|
||||
'-grayscale',
|
||||
'-grayscale-0',
|
||||
'grayscale--1',
|
||||
'-grayscale-[var(--value)]',
|
||||
'grayscale-unknown',
|
||||
'hue-rotate--5',
|
||||
'hue-rotate-unknown',
|
||||
'-invert',
|
||||
'invert--5',
|
||||
'-invert-0',
|
||||
'-invert-[var(--value)]',
|
||||
'invert-unknown',
|
||||
'-drop-shadow-xl',
|
||||
'-drop-shadow-[0_0_red]',
|
||||
|
||||
'drop-shadow/foo',
|
||||
'-drop-shadow/foo',
|
||||
'-drop-shadow/25',
|
||||
'-drop-shadow-red-500',
|
||||
'drop-shadow-red-500/foo',
|
||||
'-drop-shadow-red-500/foo',
|
||||
'-drop-shadow-red-500/50',
|
||||
'drop-shadow/foo',
|
||||
'-drop-shadow/foo',
|
||||
'-drop-shadow/25',
|
||||
'-drop-shadow-red-500',
|
||||
'drop-shadow-red-500/foo',
|
||||
'-drop-shadow-red-500/foo',
|
||||
'-drop-shadow-red-500/50',
|
||||
|
||||
'-saturate-0',
|
||||
'saturate--5',
|
||||
'-saturate-[1.75]',
|
||||
'-saturate-[var(--value)]',
|
||||
'saturate-saturate',
|
||||
'-sepia',
|
||||
'sepia--50',
|
||||
'-sepia-0',
|
||||
'-sepia-[50%]',
|
||||
'-sepia-[var(--value)]',
|
||||
'sepia-unknown',
|
||||
'filter/foo',
|
||||
'filter-none/foo',
|
||||
'filter-[var(--value)]/foo',
|
||||
'blur-xl/foo',
|
||||
'blur-none/foo',
|
||||
'blur-[4px]/foo',
|
||||
'brightness-50/foo',
|
||||
'brightness-[1.23]/foo',
|
||||
'contrast-50/foo',
|
||||
'contrast-[1.23]/foo',
|
||||
'grayscale/foo',
|
||||
'grayscale-0/foo',
|
||||
'grayscale-[var(--value)]/foo',
|
||||
'hue-rotate-15/foo',
|
||||
'hue-rotate-[45deg]/foo',
|
||||
'invert/foo',
|
||||
'invert-0/foo',
|
||||
'invert-[var(--value)]/foo',
|
||||
'drop-shadow-xl/foo',
|
||||
'drop-shadow-[0_0_red]/foo',
|
||||
'saturate-0/foo',
|
||||
'saturate-[1.75]/foo',
|
||||
'saturate-[var(--value)]/foo',
|
||||
'sepia/foo',
|
||||
'sepia-0/foo',
|
||||
'sepia-[50%]/foo',
|
||||
'sepia-[var(--value)]/foo',
|
||||
]),
|
||||
'-saturate-0',
|
||||
'saturate--5',
|
||||
'-saturate-[1.75]',
|
||||
'-saturate-[var(--value)]',
|
||||
'saturate-saturate',
|
||||
'-sepia',
|
||||
'sepia--50',
|
||||
'-sepia-0',
|
||||
'-sepia-[50%]',
|
||||
'-sepia-[var(--value)]',
|
||||
'sepia-unknown',
|
||||
'filter/foo',
|
||||
'filter-none/foo',
|
||||
'filter-[var(--value)]/foo',
|
||||
'blur-xl/foo',
|
||||
'blur-none/foo',
|
||||
'blur-[4px]/foo',
|
||||
'brightness-50/foo',
|
||||
'brightness-[1.23]/foo',
|
||||
'contrast-50/foo',
|
||||
'contrast-[1.23]/foo',
|
||||
'grayscale/foo',
|
||||
'grayscale-0/foo',
|
||||
'grayscale-[var(--value)]/foo',
|
||||
'hue-rotate-15/foo',
|
||||
'hue-rotate-[45deg]/foo',
|
||||
'invert/foo',
|
||||
'invert-0/foo',
|
||||
'invert-[var(--value)]/foo',
|
||||
'drop-shadow-xl/foo',
|
||||
'drop-shadow-[0_0_red]/foo',
|
||||
'saturate-0/foo',
|
||||
'saturate-[1.75]/foo',
|
||||
'saturate-[var(--value)]/foo',
|
||||
'sepia/foo',
|
||||
'sepia-0/foo',
|
||||
'sepia-[50%]/foo',
|
||||
'sepia-[var(--value)]/foo',
|
||||
],
|
||||
css`
|
||||
@theme {
|
||||
--drop-shadow: 0 1px 1px rgb(0 0 0 / 0.05);
|
||||
}
|
||||
@tailwind utilities;
|
||||
`,
|
||||
),
|
||||
).toEqual('')
|
||||
|
||||
expect(
|
||||
|
|
@ -27243,25 +27266,36 @@ test('text-shadow', async () => {
|
|||
"
|
||||
`)
|
||||
expect(
|
||||
await run([
|
||||
'-shadow-xl',
|
||||
'-shadow-none',
|
||||
'-shadow-red-500',
|
||||
'-shadow-red-500/50',
|
||||
'-shadow-red-500/[0.5]',
|
||||
'-shadow-red-500/[50%]',
|
||||
'-shadow-current',
|
||||
'-shadow-current/50',
|
||||
'-shadow-current/[0.5]',
|
||||
'-shadow-current/[50%]',
|
||||
'-shadow-inherit',
|
||||
'-shadow-transparent',
|
||||
'-shadow-[#0088cc]',
|
||||
'-shadow-[#0088cc]/50',
|
||||
'-shadow-[#0088cc]/[0.5]',
|
||||
'-shadow-[#0088cc]/[50%]',
|
||||
'-shadow-[var(--value)]',
|
||||
]),
|
||||
await run(
|
||||
[
|
||||
'-text-shadow-sm',
|
||||
'-text-shadow-none',
|
||||
'-text-shadow-red-500',
|
||||
'-text-shadow-red-500/50',
|
||||
'-text-shadow-red-500/[0.5]',
|
||||
'-text-shadow-red-500/[50%]',
|
||||
'-text-shadow-current',
|
||||
'-text-shadow-current/50',
|
||||
'-text-shadow-current/[0.5]',
|
||||
'-text-shadow-current/[50%]',
|
||||
'-text-shadow-inherit',
|
||||
'-text-shadow-transparent',
|
||||
'-text-shadow-[#0088cc]',
|
||||
'-text-shadow-[#0088cc]/50',
|
||||
'-text-shadow-[#0088cc]/[0.5]',
|
||||
'-text-shadow-[#0088cc]/[50%]',
|
||||
'-text-shadow-[var(--value)]',
|
||||
'text-shadow/foo',
|
||||
'text-shadow-sm/foo',
|
||||
],
|
||||
css`
|
||||
@theme {
|
||||
--text-shadow: 0 1px 1px rgb(0 0 0 / 0.05);
|
||||
--text-shadow-sm: 0 1px 2px rgb(0 0 0 / 0.06);
|
||||
}
|
||||
@tailwind utilities;
|
||||
`,
|
||||
),
|
||||
).toEqual('')
|
||||
})
|
||||
|
||||
|
|
@ -27725,25 +27759,38 @@ test('shadow', async () => {
|
|||
"
|
||||
`)
|
||||
expect(
|
||||
await run([
|
||||
'-shadow-xl',
|
||||
'-shadow-none',
|
||||
'-shadow-red-500',
|
||||
'-shadow-red-500/50',
|
||||
'-shadow-red-500/[0.5]',
|
||||
'-shadow-red-500/[50%]',
|
||||
'-shadow-current',
|
||||
'-shadow-current/50',
|
||||
'-shadow-current/[0.5]',
|
||||
'-shadow-current/[50%]',
|
||||
'-shadow-inherit',
|
||||
'-shadow-transparent',
|
||||
'-shadow-[#0088cc]',
|
||||
'-shadow-[#0088cc]/50',
|
||||
'-shadow-[#0088cc]/[0.5]',
|
||||
'-shadow-[#0088cc]/[50%]',
|
||||
'-shadow-[var(--value)]',
|
||||
]),
|
||||
await run(
|
||||
[
|
||||
'-shadow-sm',
|
||||
'-shadow-none',
|
||||
'-shadow-red-500',
|
||||
'-shadow-red-500/50',
|
||||
'-shadow-red-500/[0.5]',
|
||||
'-shadow-red-500/[50%]',
|
||||
'-shadow-current',
|
||||
'-shadow-current/50',
|
||||
'-shadow-current/[0.5]',
|
||||
'-shadow-current/[50%]',
|
||||
'-shadow-inherit',
|
||||
'-shadow-transparent',
|
||||
'-shadow-[#0088cc]',
|
||||
'-shadow-[#0088cc]/50',
|
||||
'-shadow-[#0088cc]/[0.5]',
|
||||
'-shadow-[#0088cc]/[50%]',
|
||||
'-shadow-[var(--value)]',
|
||||
'shadow/foo',
|
||||
'shadow-sm/foo',
|
||||
'shadow-[10px_10px]/foo',
|
||||
'shadow-[#0088cc]/foo',
|
||||
],
|
||||
css`
|
||||
@theme {
|
||||
--shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1);
|
||||
--shadow-sm: 0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1);
|
||||
}
|
||||
@tailwind utilities;
|
||||
`,
|
||||
),
|
||||
).toEqual('')
|
||||
})
|
||||
|
||||
|
|
@ -28216,25 +28263,37 @@ test('inset-shadow', async () => {
|
|||
"
|
||||
`)
|
||||
expect(
|
||||
await run([
|
||||
'-inset-shadow-sm',
|
||||
'-inset-shadow-none',
|
||||
'-inset-shadow-red-500',
|
||||
'-inset-shadow-red-500/50',
|
||||
'-inset-shadow-red-500/[0.5]',
|
||||
'-inset-shadow-red-500/[50%]',
|
||||
'-inset-shadow-current',
|
||||
'-inset-shadow-current/50',
|
||||
'-inset-shadow-current/[0.5]',
|
||||
'-inset-shadow-current/[50%]',
|
||||
'-inset-shadow-inherit',
|
||||
'-inset-shadow-transparent',
|
||||
'-inset-shadow-[#0088cc]',
|
||||
'-inset-shadow-[#0088cc]/50',
|
||||
'-inset-shadow-[#0088cc]/[0.5]',
|
||||
'-inset-shadow-[#0088cc]/[50%]',
|
||||
'-inset-shadow-[var(--value)]',
|
||||
]),
|
||||
await run(
|
||||
[
|
||||
'-inset-shadow-sm',
|
||||
'-inset-shadow-none',
|
||||
'-inset-shadow-red-500',
|
||||
'-inset-shadow-red-500/50',
|
||||
'-inset-shadow-red-500/[0.5]',
|
||||
'-inset-shadow-red-500/[50%]',
|
||||
'-inset-shadow-current',
|
||||
'-inset-shadow-current/50',
|
||||
'-inset-shadow-current/[0.5]',
|
||||
'-inset-shadow-current/[50%]',
|
||||
'-inset-shadow-inherit',
|
||||
'-inset-shadow-transparent',
|
||||
'-inset-shadow-[#0088cc]',
|
||||
'-inset-shadow-[#0088cc]/50',
|
||||
'-inset-shadow-[#0088cc]/[0.5]',
|
||||
'-inset-shadow-[#0088cc]/[50%]',
|
||||
'-inset-shadow-[var(--value)]',
|
||||
'inset-shadow/foo',
|
||||
'inset-shadow-sm/foo',
|
||||
'inset-shadow-[10px_10px]/foo',
|
||||
],
|
||||
css`
|
||||
@theme {
|
||||
--inset-shadow: inset 0 1px 3px 0 rgb(0 0 0 / 0.1);
|
||||
--inset-shadow-sm: inset 0 1px 1px rgb(0 0 0 / 0.05);
|
||||
}
|
||||
@tailwind utilities;
|
||||
`,
|
||||
),
|
||||
).toEqual('')
|
||||
})
|
||||
|
||||
|
|
@ -31000,6 +31059,34 @@ describe('custom utilities', () => {
|
|||
expect(await run(['example-123/foo'], input)).toEqual('')
|
||||
})
|
||||
|
||||
test('the value of `--default(…)` is emitted as-is', async () => {
|
||||
let input = css`
|
||||
@theme reference {
|
||||
--text-box-trim-trim-both: trim-both;
|
||||
--text-box-edge-cap: cap alphabetic;
|
||||
}
|
||||
|
||||
@utility trim-* {
|
||||
text-box: --value(--text-box-trim-*)
|
||||
--modifier(--text-box-edge-*, --default(box alphabetic));
|
||||
}
|
||||
|
||||
@tailwind utilities;
|
||||
`
|
||||
|
||||
expect(await run(['trim-trim-both', 'trim-trim-both/cap'], input)).toMatchInlineSnapshot(`
|
||||
"
|
||||
.trim-trim-both {
|
||||
text-box: var(--text-box-trim-trim-both, trim-both) box alphabetic;
|
||||
}
|
||||
|
||||
.trim-trim-both\\/cap {
|
||||
text-box: var(--text-box-trim-trim-both, trim-both) var(--text-box-edge-cap, cap alphabetic);
|
||||
}
|
||||
"
|
||||
`)
|
||||
})
|
||||
|
||||
test('modifiers', async () => {
|
||||
let input = css`
|
||||
@theme reference {
|
||||
|
|
|
|||
|
|
@ -421,6 +421,13 @@ export function createUtilities(theme: Theme) {
|
|||
desc.themeKeys ?? [],
|
||||
)
|
||||
|
||||
// If the theme value resolved without consuming the modifier, then
|
||||
// the modifier would be silently ignored and `w-4` and `w-4/foo`
|
||||
// would generate the same CSS.
|
||||
//
|
||||
// The modifier would be consumed if it's a fraction, e.g.: `w-1/2`
|
||||
if (value !== null && candidate.modifier && !candidate.value.fraction) return
|
||||
|
||||
// Automatically handle things like `w-1/2` without requiring `1/2` to
|
||||
// exist as a theme value.
|
||||
if (value === null && desc.supportsFractions && candidate.value.fraction) {
|
||||
|
|
@ -1561,11 +1568,11 @@ export function createUtilities(theme: Theme) {
|
|||
|
||||
{
|
||||
let transformValue = [
|
||||
'var(--tw-rotate-x,)',
|
||||
'var(--tw-rotate-y,)',
|
||||
'var(--tw-rotate-z,)',
|
||||
'var(--tw-skew-x,)',
|
||||
'var(--tw-skew-y,)',
|
||||
'var(--tw-rotate-x, )',
|
||||
'var(--tw-rotate-y, )',
|
||||
'var(--tw-rotate-z, )',
|
||||
'var(--tw-skew-x, )',
|
||||
'var(--tw-skew-y, )',
|
||||
].join(' ')
|
||||
|
||||
let transformProperties = () =>
|
||||
|
|
@ -1807,7 +1814,7 @@ export function createUtilities(theme: Theme) {
|
|||
staticUtility(`touch-pan-${value}`, [
|
||||
touchProperties,
|
||||
['--tw-pan-x', `pan-${value}`],
|
||||
['touch-action', 'var(--tw-pan-x,) var(--tw-pan-y,) var(--tw-pinch-zoom,)'],
|
||||
['touch-action', 'var(--tw-pan-x, ) var(--tw-pan-y, ) var(--tw-pinch-zoom, )'],
|
||||
])
|
||||
}
|
||||
|
||||
|
|
@ -1815,14 +1822,14 @@ export function createUtilities(theme: Theme) {
|
|||
staticUtility(`touch-pan-${value}`, [
|
||||
touchProperties,
|
||||
['--tw-pan-y', `pan-${value}`],
|
||||
['touch-action', 'var(--tw-pan-x,) var(--tw-pan-y,) var(--tw-pinch-zoom,)'],
|
||||
['touch-action', 'var(--tw-pan-x, ) var(--tw-pan-y, ) var(--tw-pinch-zoom, )'],
|
||||
])
|
||||
}
|
||||
|
||||
staticUtility('touch-pinch-zoom', [
|
||||
touchProperties,
|
||||
['--tw-pinch-zoom', `pinch-zoom`],
|
||||
['touch-action', 'var(--tw-pan-x,) var(--tw-pan-y,) var(--tw-pinch-zoom,)'],
|
||||
['touch-action', 'var(--tw-pan-x, ) var(--tw-pan-y, ) var(--tw-pinch-zoom, )'],
|
||||
])
|
||||
|
||||
/**
|
||||
|
|
@ -3888,6 +3895,10 @@ export function createUtilities(theme: Theme) {
|
|||
}
|
||||
|
||||
{
|
||||
// A modifier is only valid as the opacity of a stroke color. The value
|
||||
// did not resolve to a color, so a modifier would be silently ignored.
|
||||
if (candidate.modifier) return
|
||||
|
||||
let value = theme.resolve(candidate.value.value, ['--stroke-width'])
|
||||
if (value) {
|
||||
return [decl('stroke-width', value)]
|
||||
|
|
@ -4178,27 +4189,27 @@ export function createUtilities(theme: Theme) {
|
|||
|
||||
{
|
||||
let cssFilterValue = [
|
||||
'var(--tw-blur,)',
|
||||
'var(--tw-brightness,)',
|
||||
'var(--tw-contrast,)',
|
||||
'var(--tw-grayscale,)',
|
||||
'var(--tw-hue-rotate,)',
|
||||
'var(--tw-invert,)',
|
||||
'var(--tw-saturate,)',
|
||||
'var(--tw-sepia,)',
|
||||
'var(--tw-drop-shadow,)',
|
||||
'var(--tw-blur, )',
|
||||
'var(--tw-brightness, )',
|
||||
'var(--tw-contrast, )',
|
||||
'var(--tw-grayscale, )',
|
||||
'var(--tw-hue-rotate, )',
|
||||
'var(--tw-invert, )',
|
||||
'var(--tw-saturate, )',
|
||||
'var(--tw-sepia, )',
|
||||
'var(--tw-drop-shadow, )',
|
||||
].join(' ')
|
||||
|
||||
let cssBackdropFilterValue = [
|
||||
'var(--tw-backdrop-blur,)',
|
||||
'var(--tw-backdrop-brightness,)',
|
||||
'var(--tw-backdrop-contrast,)',
|
||||
'var(--tw-backdrop-grayscale,)',
|
||||
'var(--tw-backdrop-hue-rotate,)',
|
||||
'var(--tw-backdrop-invert,)',
|
||||
'var(--tw-backdrop-opacity,)',
|
||||
'var(--tw-backdrop-saturate,)',
|
||||
'var(--tw-backdrop-sepia,)',
|
||||
'var(--tw-backdrop-blur, )',
|
||||
'var(--tw-backdrop-brightness, )',
|
||||
'var(--tw-backdrop-contrast, )',
|
||||
'var(--tw-backdrop-grayscale, )',
|
||||
'var(--tw-backdrop-hue-rotate, )',
|
||||
'var(--tw-backdrop-invert, )',
|
||||
'var(--tw-backdrop-opacity, )',
|
||||
'var(--tw-backdrop-saturate, )',
|
||||
'var(--tw-backdrop-sepia, )',
|
||||
].join(' ')
|
||||
|
||||
let filterProperties = () => {
|
||||
|
|
@ -4628,6 +4639,7 @@ export function createUtilities(theme: Theme) {
|
|||
let value = theme.get(['--drop-shadow'])
|
||||
let resolved = theme.resolve(null, ['--drop-shadow'])
|
||||
if (value === null || resolved === null) return
|
||||
if (candidate.modifier && !alpha) return
|
||||
|
||||
return [
|
||||
filterProperties(),
|
||||
|
|
@ -4941,7 +4953,7 @@ export function createUtilities(theme: Theme) {
|
|||
|
||||
{
|
||||
let cssContainValue =
|
||||
'var(--tw-contain-size,) var(--tw-contain-layout,) var(--tw-contain-paint,) var(--tw-contain-style,)'
|
||||
'var(--tw-contain-size, ) var(--tw-contain-layout, ) var(--tw-contain-paint, ) var(--tw-contain-style, )'
|
||||
let cssContainProperties = () => {
|
||||
return atRoot([
|
||||
property('--tw-contain-size'),
|
||||
|
|
@ -5035,7 +5047,7 @@ export function createUtilities(theme: Theme) {
|
|||
|
||||
{
|
||||
let cssFontVariantNumericValue =
|
||||
'var(--tw-ordinal,) var(--tw-slashed-zero,) var(--tw-numeric-figure,) var(--tw-numeric-spacing,) var(--tw-numeric-fraction,)'
|
||||
'var(--tw-ordinal, ) var(--tw-slashed-zero, ) var(--tw-numeric-figure, ) var(--tw-numeric-spacing, ) var(--tw-numeric-fraction, )'
|
||||
let fontVariantNumericProperties = () => {
|
||||
return atRoot([
|
||||
property('--tw-ordinal'),
|
||||
|
|
@ -5436,6 +5448,7 @@ export function createUtilities(theme: Theme) {
|
|||
if (!candidate.value) {
|
||||
let value = theme.get(['--text-shadow'])
|
||||
if (value === null) return
|
||||
if (candidate.modifier && !alpha) return
|
||||
|
||||
return [
|
||||
textShadowProperties(),
|
||||
|
|
@ -5463,6 +5476,8 @@ export function createUtilities(theme: Theme) {
|
|||
]
|
||||
}
|
||||
default: {
|
||||
if (candidate.modifier && !alpha) return
|
||||
|
||||
return [
|
||||
textShadowProperties(),
|
||||
decl('--tw-text-shadow-alpha', alpha),
|
||||
|
|
@ -5491,6 +5506,8 @@ export function createUtilities(theme: Theme) {
|
|||
{
|
||||
let value = theme.get([`--text-shadow-${candidate.value.value}`])
|
||||
if (value) {
|
||||
if (candidate.modifier && !alpha) return
|
||||
|
||||
return [
|
||||
textShadowProperties(),
|
||||
decl('--tw-text-shadow-alpha', alpha),
|
||||
|
|
@ -5582,6 +5599,7 @@ export function createUtilities(theme: Theme) {
|
|||
if (!candidate.value) {
|
||||
let value = theme.get(['--shadow'])
|
||||
if (value === null) return
|
||||
if (candidate.modifier && !alpha) return
|
||||
|
||||
return [
|
||||
boxShadowProperties(),
|
||||
|
|
@ -5611,6 +5629,8 @@ export function createUtilities(theme: Theme) {
|
|||
]
|
||||
}
|
||||
default: {
|
||||
if (candidate.modifier && !alpha) return
|
||||
|
||||
return [
|
||||
boxShadowProperties(),
|
||||
decl('--tw-shadow-alpha', alpha),
|
||||
|
|
@ -5644,6 +5664,8 @@ export function createUtilities(theme: Theme) {
|
|||
{
|
||||
let value = theme.get([`--shadow-${candidate.value.value}`])
|
||||
if (value) {
|
||||
if (candidate.modifier && !alpha) return
|
||||
|
||||
return [
|
||||
boxShadowProperties(),
|
||||
decl('--tw-shadow-alpha', alpha),
|
||||
|
|
@ -5708,6 +5730,7 @@ export function createUtilities(theme: Theme) {
|
|||
if (!candidate.value) {
|
||||
let value = theme.get(['--inset-shadow'])
|
||||
if (value === null) return
|
||||
if (candidate.modifier && !alpha) return
|
||||
|
||||
return [
|
||||
boxShadowProperties(),
|
||||
|
|
@ -5737,6 +5760,8 @@ export function createUtilities(theme: Theme) {
|
|||
]
|
||||
}
|
||||
default: {
|
||||
if (candidate.modifier && !alpha) return
|
||||
|
||||
return [
|
||||
boxShadowProperties(),
|
||||
decl('--tw-inset-shadow-alpha', alpha),
|
||||
|
|
@ -5772,6 +5797,8 @@ export function createUtilities(theme: Theme) {
|
|||
let value = theme.get([`--inset-shadow-${candidate.value.value}`])
|
||||
|
||||
if (value) {
|
||||
if (candidate.modifier && !alpha) return
|
||||
|
||||
return [
|
||||
boxShadowProperties(),
|
||||
decl('--tw-inset-shadow-alpha', alpha),
|
||||
|
|
@ -5819,7 +5846,7 @@ export function createUtilities(theme: Theme) {
|
|||
|
||||
let defaultRingColor = theme.get(['--default-ring-color']) ?? 'currentcolor'
|
||||
function ringShadowValue(value: string) {
|
||||
return `var(--tw-ring-inset,) 0 0 0 calc(${value} + var(--tw-ring-offset-width)) var(--tw-ring-color, ${defaultRingColor})`
|
||||
return `var(--tw-ring-inset, ) 0 0 0 calc(${value} + var(--tw-ring-offset-width)) var(--tw-ring-color, ${defaultRingColor})`
|
||||
}
|
||||
utilities.functional('ring', (candidate) => {
|
||||
if (!candidate.value) {
|
||||
|
|
@ -5968,7 +5995,7 @@ export function createUtilities(theme: Theme) {
|
|||
])
|
||||
|
||||
let ringOffsetShadowValue =
|
||||
'var(--tw-ring-inset,) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color)'
|
||||
'var(--tw-ring-inset, ) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color)'
|
||||
utilities.functional('ring-offset', (candidate) => {
|
||||
if (!candidate.value) return
|
||||
|
||||
|
|
@ -6193,6 +6220,15 @@ export function createCssUtility(node: AtRule) {
|
|||
|
||||
let args = segment(ValueParser.toCss(fn.nodes), ',')
|
||||
for (let [idx, arg] of args.entries()) {
|
||||
arg = arg.trim()
|
||||
|
||||
// The value of `--default(…)` is emitted as-is, so it should not be
|
||||
// normalized.
|
||||
if (arg.startsWith('--default(')) {
|
||||
args[idx] = arg
|
||||
continue
|
||||
}
|
||||
|
||||
// Transform escaped `\\*` -> `*`
|
||||
arg = arg.replace(/\\\*/g, '*')
|
||||
|
||||
|
|
|
|||
|
|
@ -1435,6 +1435,17 @@ test('supports', async () => {
|
|||
'supports-[font-tech(color-COLRv1)]:flex',
|
||||
'supports-[var(--test)]:flex',
|
||||
'supports-[--test]:flex',
|
||||
|
||||
// Only top-level and/or/not should have spaces around them. We should
|
||||
// ignore and/or/not inside of `selector(…)`
|
||||
'supports-[selector(a:not(.foo))]:flex',
|
||||
'supports-[selector(a:is(.and,.or))]:flex',
|
||||
'supports-[(display:grid)or(display:flex)]:grid',
|
||||
'supports-[not(display:grid)]:flex',
|
||||
'supports-[foo-not(display:grid)]:flex',
|
||||
'supports-[selector([data-foo="("])or(display:grid)]:flex',
|
||||
'supports-[selector(.foo\\(bar)or(display:grid)]:flex',
|
||||
'supports-[((display:grid)or(display:flex))]:grid',
|
||||
]),
|
||||
).toMatchInlineSnapshot(`
|
||||
"
|
||||
|
|
@ -1444,12 +1455,24 @@ test('supports', async () => {
|
|||
}
|
||||
}
|
||||
|
||||
@supports (display: grid) or (display: flex) {
|
||||
.supports-\\[\\(\\(display\\:grid\\)or\\(display\\:flex\\)\\)\\]\\:grid {
|
||||
display: grid;
|
||||
}
|
||||
}
|
||||
|
||||
@supports (display: grid) and font-format(opentype) {
|
||||
.supports-\\[\\(display\\:grid\\)_and_font-format\\(opentype\\)\\]\\:grid {
|
||||
display: grid;
|
||||
}
|
||||
}
|
||||
|
||||
@supports (display: grid) or (display: flex) {
|
||||
.supports-\\[\\(display\\:grid\\)or\\(display\\:flex\\)\\]\\:grid {
|
||||
display: grid;
|
||||
}
|
||||
}
|
||||
|
||||
@supports (--test: var(--tw)) {
|
||||
.supports-\\[--test\\]\\:flex {
|
||||
display: flex;
|
||||
|
|
@ -1474,12 +1497,48 @@ test('supports', async () => {
|
|||
}
|
||||
}
|
||||
|
||||
@supports foo-not(display:grid) {
|
||||
.supports-\\[foo-not\\(display\\:grid\\)\\]\\:flex {
|
||||
display: flex;
|
||||
}
|
||||
}
|
||||
|
||||
@supports not (display: grid) {
|
||||
.supports-\\[not\\(display\\:grid\\)\\]\\:flex {
|
||||
display: flex;
|
||||
}
|
||||
}
|
||||
|
||||
@supports selector(.foo\\(bar) or (display: grid) {
|
||||
.supports-\\[selector\\(\\.foo\\\\\\(bar\\)or\\(display\\:grid\\)\\]\\:flex {
|
||||
display: flex;
|
||||
}
|
||||
}
|
||||
|
||||
@supports selector(A > B) {
|
||||
.supports-\\[selector\\(A_\\>_B\\)\\]\\:flex {
|
||||
display: flex;
|
||||
}
|
||||
}
|
||||
|
||||
@supports selector([data-foo="("]) or (display: grid) {
|
||||
.supports-\\[selector\\(\\[data-foo\\=\\"\\(\\"\\]\\)or\\(display\\:grid\\)\\]\\:flex {
|
||||
display: flex;
|
||||
}
|
||||
}
|
||||
|
||||
@supports selector(a:is(.and,.or)) {
|
||||
.supports-\\[selector\\(a\\:is\\(\\.and\\,\\.or\\)\\)\\]\\:flex {
|
||||
display: flex;
|
||||
}
|
||||
}
|
||||
|
||||
@supports selector(a:not(.foo)) {
|
||||
.supports-\\[selector\\(a\\:not\\(\\.foo\\)\\)\\]\\:flex {
|
||||
display: flex;
|
||||
}
|
||||
}
|
||||
|
||||
@supports var(--test) {
|
||||
.supports-\\[var\\(--test\\)\\]\\:flex {
|
||||
display: flex;
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import {
|
|||
atRoot,
|
||||
atRule,
|
||||
cloneAstNode,
|
||||
context,
|
||||
decl,
|
||||
rule,
|
||||
styleRule,
|
||||
|
|
@ -89,12 +90,14 @@ export class Variants {
|
|||
let selectors: string[] = []
|
||||
|
||||
let usesAtVariant = false
|
||||
let usesAtScope = false
|
||||
walk(ast, (node) => {
|
||||
if (node.kind === 'rule') {
|
||||
selectors.push(node.selector)
|
||||
} else if (node.kind === 'at-rule' && node.name === '@variant') {
|
||||
usesAtVariant = true
|
||||
} else if (node.kind === 'at-rule' && node.name !== '@slot') {
|
||||
if (node.name === '@scope') usesAtScope = true
|
||||
selectors.push(`${node.name} ${node.params}`)
|
||||
}
|
||||
})
|
||||
|
|
@ -104,8 +107,14 @@ export class Variants {
|
|||
(r) => {
|
||||
let body = ast.map(cloneAstNode)
|
||||
if (usesAtVariant) substituteAtVariant(body, designSystem)
|
||||
substituteAtSlot(body, r.nodes)
|
||||
r.nodes = body
|
||||
|
||||
if (usesAtScope) {
|
||||
substituteAtSlot(body, [context({ source: 'user' }, r.nodes)])
|
||||
r.nodes = [context({ source: 'variant' }, body)]
|
||||
} else {
|
||||
substituteAtSlot(body, r.nodes)
|
||||
r.nodes = body
|
||||
}
|
||||
},
|
||||
{ compounds: compoundsForSelectors(selectors) },
|
||||
)
|
||||
|
|
@ -929,7 +938,22 @@ export function createVariants(theme: Theme): Variants {
|
|||
if (/^[\w-]*\s*\(/.test(value)) {
|
||||
// Chrome has a bug where `(condition1)or(condition2)` is not valid, but
|
||||
// `(condition1) or (condition2)` is supported.
|
||||
let query = value.replace(/\b(and|or|not)\b/g, ' $1 ')
|
||||
let changed = false
|
||||
let ast = ValueParser.parse(value)
|
||||
walk(ast, (node) => {
|
||||
if (node.kind !== 'function') return
|
||||
|
||||
// Leave selectors as-is, they could contain `selector(a:not(b))`, and
|
||||
// in this case we don't want the space around the `not`.
|
||||
if (node.value === 'selector') return WalkAction.Skip
|
||||
|
||||
if (node.value === 'and' || node.value === 'or' || node.value === 'not') {
|
||||
changed = true
|
||||
node.value = ` ${node.value} `
|
||||
}
|
||||
})
|
||||
|
||||
let query = changed ? ValueParser.toCss(ast) : value
|
||||
|
||||
ruleNode.nodes = [atRule('@supports', query, ruleNode.nodes)]
|
||||
return
|
||||
|
|
|
|||
|
|
@ -2177,6 +2177,216 @@ test('shadow DOM has access to variables', async ({ page }) => {
|
|||
expect(gap).toBe('8px')
|
||||
})
|
||||
|
||||
// @scope related tests
|
||||
{
|
||||
test('custom variant using `@scope`', async ({ page }) => {
|
||||
let { getPropertyValue } = await render(
|
||||
page,
|
||||
html`
|
||||
<div class="checkout">
|
||||
<div id="in" class="in-checkout:underline">In scope</div>
|
||||
<div class="payment">
|
||||
<div id="beyond" class="in-checkout:underline">Beyond the limit</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="out" class="in-checkout:underline">Not in scope</div>
|
||||
`,
|
||||
css`
|
||||
@custom-variant in-checkout {
|
||||
@scope (.checkout) to (.payment) {
|
||||
@slot;
|
||||
}
|
||||
}
|
||||
`,
|
||||
)
|
||||
|
||||
test.skip(!(await supportsAtScope(page)), '`@scope` is not supported in this browser')
|
||||
|
||||
expect(await getPropertyValue('#in', 'text-decoration-line')).toEqual('underline')
|
||||
expect(await getPropertyValue('#beyond', 'text-decoration-line')).toEqual('none')
|
||||
expect(await getPropertyValue('#out', 'text-decoration-line')).toEqual('none')
|
||||
})
|
||||
|
||||
test('custom variant using `@scope` behaves like the equivalent authored CSS', async ({
|
||||
page,
|
||||
}) => {
|
||||
// Render the same structure twice:
|
||||
// - Once styled by authored CSS using `@scope`, like the "normal CSS"
|
||||
// reference in https://github.com/tailwindlabs/tailwindcss/issues/18961
|
||||
// - Once styled by utilities using an equivalent custom variant
|
||||
function structure(prefix: string, probe: string) {
|
||||
return html`
|
||||
<div class="checkout">
|
||||
<div id="${prefix}-in" class="${probe}">In scope</div>
|
||||
<div class="payment">
|
||||
<div id="${prefix}-beyond" class="${probe}">Beyond the limit</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="${prefix}-out" class="${probe}">Not in scope</div>
|
||||
`
|
||||
}
|
||||
|
||||
let { getPropertyValue } = await render(
|
||||
page,
|
||||
structure('a', 'a-probe') + structure('c', 'in-checkout:underline'),
|
||||
css`
|
||||
@custom-variant in-checkout {
|
||||
@scope (.checkout) to (.payment) {
|
||||
@slot;
|
||||
}
|
||||
}
|
||||
`,
|
||||
)
|
||||
|
||||
// The `a-*` structure is styled by the authored CSS as-is
|
||||
await page.addStyleTag({
|
||||
content: css`
|
||||
@scope (.checkout) to (.payment) {
|
||||
.a-probe {
|
||||
text-decoration-line: underline;
|
||||
}
|
||||
}
|
||||
`,
|
||||
})
|
||||
|
||||
test.skip(!(await supportsAtScope(page)), '`@scope` is not supported in this browser')
|
||||
|
||||
for (let prefix of ['a', 'c']) {
|
||||
expect(await getPropertyValue(`#${prefix}-in`, 'text-decoration-line')).toEqual('underline')
|
||||
expect(await getPropertyValue(`#${prefix}-beyond`, 'text-decoration-line')).toEqual('none')
|
||||
expect(await getPropertyValue(`#${prefix}-out`, 'text-decoration-line')).toEqual('none')
|
||||
}
|
||||
})
|
||||
|
||||
test('user-authored nested `@scope` behaves like the authored CSS', async ({ page }) => {
|
||||
// User-authored `@scope` rules are compiled to their native CSS nesting
|
||||
// semantics. Rendering the same structure twice:
|
||||
// - Once styled by the authored (nested) CSS as-is
|
||||
// - Once styled by the compiled output
|
||||
function structure(prefix: string) {
|
||||
return html`
|
||||
<div class="${prefix}-parent">
|
||||
<div class="${prefix}-scope">
|
||||
<span class="${prefix}-content" id="${prefix}-in">in scope</span>
|
||||
<div class="${prefix}-limit">
|
||||
<span class="${prefix}-content" id="${prefix}-beyond">beyond the limit</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="${prefix}-scope">
|
||||
<span class="${prefix}-content" id="${prefix}-out">scope not inside parent</span>
|
||||
</div>
|
||||
`
|
||||
}
|
||||
|
||||
function scopeCss(prefix: string) {
|
||||
return css`
|
||||
.${prefix}-parent {
|
||||
@scope (& > .${prefix}-scope) to (& .${prefix}-limit) {
|
||||
.${prefix}-content {
|
||||
text-decoration-line: underline;
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
}
|
||||
|
||||
// The `c-*` structure is styled by the compiled CSS
|
||||
let { getPropertyValue } = await render(page, structure('a') + structure('c'), scopeCss('c'))
|
||||
|
||||
// The `a-*` structure is styled by the authored CSS as-is
|
||||
await page.addStyleTag({ content: scopeCss('a') })
|
||||
|
||||
test.skip(!(await supportsAtScope(page)), '`@scope` is not supported in this browser')
|
||||
|
||||
// The compiled output only applies within the scope
|
||||
expect(await getPropertyValue('#c-in', 'text-decoration-line')).toEqual('underline')
|
||||
expect(await getPropertyValue('#c-beyond', 'text-decoration-line')).toEqual('none')
|
||||
expect(await getPropertyValue('#c-out', 'text-decoration-line')).toEqual('none')
|
||||
|
||||
// The authored CSS behaves the same
|
||||
expect(await getPropertyValue('#a-in', 'text-decoration-line')).toEqual('underline')
|
||||
expect(await getPropertyValue('#a-out', 'text-decoration-line')).toEqual('none')
|
||||
|
||||
// WebKit currently drops the `<scope-end>` limit entirely when it contains
|
||||
// `&`. Since we resolve the `&` at build time, the compiled output works
|
||||
// even though the authored CSS doesn't.
|
||||
if (test.info().project.name !== 'webkit') {
|
||||
expect(await getPropertyValue('#a-beyond', 'text-decoration-line')).toEqual('none')
|
||||
}
|
||||
})
|
||||
|
||||
test('user-authored `@scope` nested inside another `@scope`', async ({ page }) => {
|
||||
function structure(prefix: string) {
|
||||
return html`
|
||||
<!-- Control: outer > middle > inner -->
|
||||
<div class="${prefix}-outer">
|
||||
<div class="${prefix}-middle">
|
||||
<div class="${prefix}-inner" id="${prefix}-ctrl">ctrl</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Middle is an ancestor of the outer scope root -->
|
||||
<div class="${prefix}-middle">
|
||||
<div class="${prefix}-outer">
|
||||
<div class="${prefix}-inner" id="${prefix}-ancestor">ancestor</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Middle is beyond the outer limit -->
|
||||
<div class="${prefix}-outer">
|
||||
<div class="${prefix}-outer-limit">
|
||||
<div class="${prefix}-middle">
|
||||
<div class="${prefix}-inner" id="${prefix}-beyond">beyond</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
}
|
||||
|
||||
function scopeCss(prefix: string) {
|
||||
return css`
|
||||
@scope (.${prefix}-outer) to (.${prefix}-outer-limit) {
|
||||
.${prefix}-middle {
|
||||
@scope (.${prefix}-inner) to (.${prefix}-inner-limit) {
|
||||
text-decoration-line: underline;
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
}
|
||||
|
||||
// The `c-*` structure is styled by the compiled CSS
|
||||
let { getPropertyValue } = await render(page, structure('a') + structure('c'), scopeCss('c'))
|
||||
|
||||
// The `a-*` structure is styled by the authored CSS as-is
|
||||
await page.addStyleTag({ content: scopeCss('a') })
|
||||
|
||||
test.skip(!(await supportsAtScope(page)), '`@scope` is not supported in this browser')
|
||||
|
||||
// The compiled output behaves the same in every browser
|
||||
expect(await getPropertyValue('#c-ctrl', 'text-decoration-line')).toEqual('underline')
|
||||
expect(await getPropertyValue('#c-ancestor', 'text-decoration-line')).toEqual('none')
|
||||
expect(await getPropertyValue('#c-beyond', 'text-decoration-line')).toEqual('none')
|
||||
|
||||
// The authored CSS behaves the same …
|
||||
expect(await getPropertyValue('#a-ctrl', 'text-decoration-line')).toEqual('underline')
|
||||
expect(await getPropertyValue('#a-beyond', 'text-decoration-line')).toEqual('none')
|
||||
|
||||
// … except in Chromium, which resolves the nesting context of a
|
||||
// rule-nested `@scope` without the enclosing scope's constraint (Safari
|
||||
// and Firefox both constrain it). The compiled output normalizes this
|
||||
// browser difference.
|
||||
if (test.info().project.name !== 'chromium') {
|
||||
expect(await getPropertyValue('#a-ancestor', 'text-decoration-line')).toEqual('none')
|
||||
}
|
||||
})
|
||||
|
||||
function supportsAtScope(page: Page) {
|
||||
return page.evaluate(() => typeof CSSScopeRule !== 'undefined')
|
||||
}
|
||||
}
|
||||
|
||||
// ---
|
||||
|
||||
const preflight = fs.readFileSync(path.resolve(__dirname, '..', 'preflight.css'), 'utf-8')
|
||||
|
|
|
|||
80
patches/@napi-rs__cli@3.7.4.patch
Normal file
80
patches/@napi-rs__cli@3.7.4.patch
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
diff --git a/dist/cli.js b/dist/cli.js
|
||||
index c4c2d568bc070c07dbf3a1f9f4a0c946466668cf..353bbca86e3261a2ba9a8fc56dc612c7c84dab6d 100755
|
||||
--- a/dist/cli.js
|
||||
+++ b/dist/cli.js
|
||||
@@ -1,4 +1,13 @@
|
||||
#!/usr/bin/env node
|
||||
+// PATCHED (see patches/@napi-rs__cli@3.7.4.patch): the embedded wasi loader
|
||||
+// and worker templates below retry `new WASI(...)` with narrower preopens,
|
||||
+// because preopening `/` throws `UVWASI_EACCES` on sandboxed platforms (e.g.
|
||||
+// OpenHarmony), which would make the generated wasm binding fail to load.
|
||||
+//
|
||||
+// The same templates also exist in `dist/index.js` and `dist/index.cjs` (the
|
||||
+// programmatic API). Those are intentionally NOT patched because we only
|
||||
+// build through the `napi` bin, which runs this file. If we ever start using
|
||||
+// the programmatic API, update the patch to cover those bundles too.
|
||||
import { createRequire } from "node:module";
|
||||
import { Cli, Command, Option } from "clipanion";
|
||||
import path, { basename, dirname, isAbsolute, join, parse, resolve } from "node:path";
|
||||
@@ -1021,13 +1030,25 @@ const {
|
||||
|
||||
const __rootDir = __nodePath.parse(process.cwd()).root
|
||||
|
||||
-const __wasi = new __nodeWASI({
|
||||
- version: 'preview1',
|
||||
- env: process.env,
|
||||
- preopens: {
|
||||
- [__rootDir]: __rootDir,
|
||||
+const __wasi = (() => {
|
||||
+ // Preopening '/' fails with UVWASI_EACCES in sandboxed environments (e.g.
|
||||
+ // OpenHarmony, Android), which would prevent the wasm binding from loading
|
||||
+ // at all. Retry with narrower preopens instead. Without any preopens the
|
||||
+ // binding still loads; only file system access is unavailable.
|
||||
+ let lastError = null
|
||||
+ for (const dir of [__rootDir, process.cwd(), null]) {
|
||||
+ try {
|
||||
+ return new __nodeWASI({
|
||||
+ version: 'preview1',
|
||||
+ env: process.env,
|
||||
+ preopens: dir === null ? {} : { [dir]: dir },
|
||||
+ })
|
||||
+ } catch (error) {
|
||||
+ lastError = error
|
||||
+ }
|
||||
}
|
||||
-})
|
||||
+ throw lastError
|
||||
+})()
|
||||
|
||||
const __emnapiContext = __emnapiGetDefaultContext()
|
||||
|
||||
@@ -1151,13 +1172,22 @@ const __rootDir = parse(process.cwd()).root;
|
||||
|
||||
const handler = new MessageHandler({
|
||||
onLoad({ wasmModule, wasmMemory }) {
|
||||
- const wasi = new WASI({
|
||||
- version: 'preview1',
|
||||
- env: process.env,
|
||||
- preopens: {
|
||||
- [__rootDir]: __rootDir,
|
||||
- },
|
||||
- });
|
||||
+ // Keep in sync with the preopen fallback in the main-thread loader.
|
||||
+ const wasi = (() => {
|
||||
+ let lastError = null;
|
||||
+ for (const dir of [__rootDir, process.cwd(), null]) {
|
||||
+ try {
|
||||
+ return new WASI({
|
||||
+ version: 'preview1',
|
||||
+ env: process.env,
|
||||
+ preopens: dir === null ? {} : { [dir]: dir },
|
||||
+ });
|
||||
+ } catch (error) {
|
||||
+ lastError = error;
|
||||
+ }
|
||||
+ }
|
||||
+ throw lastError;
|
||||
+ })();
|
||||
|
||||
return instantiateNapiModuleSync(wasmModule, {
|
||||
childThread: true,
|
||||
|
|
@ -1,13 +1,14 @@
|
|||
diff --git a/index.js b/index.js
|
||||
index 8afb2b1126dcc687b7ff9b631589da252c1f9c22..f28fd092644ccfb8aff2618b966cb5219a181a02 100644
|
||||
index 78ee744d74900c39a839cafa46b295258fc86307..f28fd092644ccfb8aff2618b966cb5219a181a02 100644
|
||||
--- a/index.js
|
||||
+++ b/index.js
|
||||
@@ -1,40 +1,32 @@
|
||||
@@ -1,43 +1,32 @@
|
||||
const {createWrapper} = require('./wrapper');
|
||||
|
||||
-let name = `@parcel/watcher-${process.platform}-${process.arch}`;
|
||||
-if (process.platform === 'linux') {
|
||||
- const { MUSL, family } = require('detect-libc');
|
||||
- const {MUSL, familySync} = require('detect-libc');
|
||||
- const family = familySync();
|
||||
- if (family === MUSL) {
|
||||
- name += '-musl';
|
||||
- } else {
|
||||
|
|
@ -39,7 +40,9 @@ index 8afb2b1126dcc687b7ff9b631589da252c1f9c22..f28fd092644ccfb8aff2618b966cb521
|
|||
- binding = require('./build/Debug/watcher.node');
|
||||
- } catch (err) {
|
||||
- handleError(err);
|
||||
- throw new Error(`No prebuild or local build of @parcel/watcher found. Tried ${name}. Please ensure it is installed (don't use --no-optional when installing with npm). Otherwise it is possible we don't support your platform yet. If this is the case, please report an issue to https://github.com/parcel-bundler/watcher.`);
|
||||
- throw new Error(
|
||||
- `No prebuild or local build of @parcel/watcher found. Tried ${name}. Please ensure it is installed (don't use --no-optional when installing with npm). Otherwise it is possible we don't support your platform yet. If this is the case, please report an issue to https://github.com/parcel-bundler/watcher.`,
|
||||
- );
|
||||
- }
|
||||
- }
|
||||
-}
|
||||
1661
pnpm-lock.yaml
generated
1661
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load diff
|
|
@ -6,25 +6,34 @@ packages:
|
|||
- 'integrations'
|
||||
|
||||
patchedDependencies:
|
||||
'@parcel/watcher@2.5.1': patches/@parcel__watcher@2.5.1.patch
|
||||
lightningcss@1.32.0: patches/lightningcss@1.32.0.patch
|
||||
'@napi-rs/cli@3.7.4': patches/@napi-rs__cli@3.7.4.patch
|
||||
'@parcel/watcher@2.6.0': patches/@parcel__watcher@2.6.0.patch
|
||||
lightningcss@1.33.0: patches/lightningcss@1.33.0.patch
|
||||
|
||||
catalog:
|
||||
'@types/node': 22.19.21
|
||||
'@types/node': 22.20.1
|
||||
dedent: 1.7.2
|
||||
enhanced-resolve: ^5.24.1
|
||||
lightningcss-darwin-arm64: 1.32.0
|
||||
lightningcss-darwin-x64: 1.32.0
|
||||
lightningcss-linux-arm64-gnu: 1.32.0
|
||||
lightningcss-linux-arm64-musl: 1.32.0
|
||||
lightningcss-linux-x64-gnu: 1.32.0
|
||||
lightningcss-linux-x64-musl: 1.32.0
|
||||
lightningcss-win32-x64-msvc: 1.32.0
|
||||
lightningcss: 1.32.0
|
||||
postcss: ^8.5.16
|
||||
prettier: 3.9.4
|
||||
vite: ^8.1.2
|
||||
webpack: ^5.108.3
|
||||
enhanced-resolve: ^5.24.5
|
||||
lightningcss-darwin-arm64: 1.33.0
|
||||
lightningcss-darwin-x64: 1.33.0
|
||||
lightningcss-linux-arm64-gnu: 1.33.0
|
||||
lightningcss-linux-arm64-musl: 1.33.0
|
||||
lightningcss-linux-x64-gnu: 1.33.0
|
||||
lightningcss-linux-x64-musl: 1.33.0
|
||||
lightningcss-win32-x64-msvc: 1.33.0
|
||||
lightningcss: 1.33.0
|
||||
'@parcel/watcher-darwin-arm64': 2.6.0
|
||||
'@parcel/watcher-darwin-x64': 2.6.0
|
||||
'@parcel/watcher-linux-arm64-glibc': 2.6.0
|
||||
'@parcel/watcher-linux-arm64-musl': 2.6.0
|
||||
'@parcel/watcher-linux-x64-glibc': 2.6.0
|
||||
'@parcel/watcher-linux-x64-musl': 2.6.0
|
||||
'@parcel/watcher-win32-x64': 2.6.0
|
||||
'@parcel/watcher': 2.6.0
|
||||
postcss: ^8.5.25
|
||||
prettier: 3.9.6
|
||||
vite: ^8.2.0
|
||||
webpack: ^5.109.2
|
||||
|
||||
onlyBuiltDependencies:
|
||||
- '@parcel/watcher'
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
{
|
||||
"$schema": "https://turbo.build/schema.json",
|
||||
"$schema": "https://v2-10-8.turborepo.dev/schema.json",
|
||||
"ui": "tui",
|
||||
"tasks": {
|
||||
"@tailwindcss/oxide#build": {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue