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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,16 @@
- Read a rule written without a space before `{`, such as `.a{`. The line regex
skipped it.

### Breaking changes

- In `--output-css-file` and `--vite-css`, classes that the CSS file does not
define now come first, in their input order, as in the built-in sorter and in
`prettier-plugin-tailwindcss`. They came last before. The placeholders `...`
and `…` now go last. The output of these options changes, so
`--check-formatted` reports files with custom classes after the upgrade, until
you run `--write`. `Sorter::CssSorter` documents the exceptions for classes
with a variant prefix.

## [0.28.1] - 2026-11-23

### Added
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -158,10 +158,10 @@ Options:
When set, RustyWind will use the config file to derive configurations. The config file current only supports json with one property sortOrder, e.g. { "sortOrder": ["class1", ...] }

--output-css-file <OUTPUT_CSS_FILE>
When set RustyWind will determine the sort order by the order the class appear in the given CSS file
When set RustyWind will determine the sort order by the order the class appear in the given CSS file. Classes that the CSS does not define go first, in input order. A class such as `hover:flex` that the CSS does not define, but whose part after the first built-in variant prefix it does, goes after the defined classes

--vite-css <VITE_CSS>
When set RustyWind will determine the sort order by the order the class appear in the CSS file that vite generates.
When set RustyWind will determine the sort order by the order the class appear in the CSS file that vite generates. Classes that the CSS does not define go first, in input order. A class such as `hover:flex` that the CSS does not define, but whose part after the first built-in variant prefix it does, goes after the defined classes.

Please provide the full URL to the CSS file ex: `rustywind --vite-css "http://127.0.0.1:5173/src/assets/main.css" . --dry-run`

Expand Down
4 changes: 2 additions & 2 deletions npm/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,10 +104,10 @@ Options:
When set, RustyWind will use the config file to derive configurations. The config file current only supports json with one property sortOrder, e.g. { "sortOrder": ["class1", ...] }

--output-css-file <OUTPUT_CSS_FILE>
When set RustyWind will determine the sort order by the order the class appear in the given CSS file
When set RustyWind will determine the sort order by the order the class appear in the given CSS file. Classes that the CSS does not define go first, in input order. A class such as `hover:flex` that the CSS does not define, but whose part after the first built-in variant prefix it does, goes after the defined classes

--vite-css <VITE_CSS>
When set RustyWind will determine the sort order by the order the class appear in the CSS file that vite generates.
When set RustyWind will determine the sort order by the order the class appear in the CSS file that vite generates. Classes that the CSS does not define go first, in input order. A class such as `hover:flex` that the CSS does not define, but whose part after the first built-in variant prefix it does, goes after the defined classes.

Please provide the full URL to the CSS file ex: `rustywind --vite-css "http://127.0.0.1:5173/src/assets/main.css" . --dry-run`

Expand Down
6 changes: 6 additions & 0 deletions rustywind-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,15 @@ pub struct Cli {
#[arg(long, conflicts_with_all = &["output_css_file"])]
config_file: Option<String>,
/// When set RustyWind will determine the sort order by the order the class appear in the given CSS file.
/// Classes that the CSS does not define go first, in input order. A class such as `hover:flex` that
/// the CSS does not define, but whose part after the first built-in variant prefix it does, goes
/// after the defined classes.
#[arg(long, conflicts_with_all = &["config_file", "vite_css"])]
output_css_file: Option<String>,
/// When set RustyWind will determine the sort order by the order the class appear in the CSS file that vite generates.
/// Classes that the CSS does not define go first, in input order. A class such as `hover:flex` that
/// the CSS does not define, but whose part after the first built-in variant prefix it does, goes
/// after the defined classes.
///
/// Please provide the full URL to the CSS file ex: `rustywind --vite-css "http://127.0.0.1:5173/src/assets/main.css" . --dry-run`
///
Expand Down
14 changes: 14 additions & 0 deletions rustywind-core/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,20 @@
- Read a rule written without a space before `{`, such as `.a{`. The line regex
skipped it.

### Breaking changes

- A sorter built from a CSS file puts the classes that the file does not name
first, in their input order, as the built-in sorter (`Sorter::PatternSorter`)
and `prettier-plugin-tailwindcss` do. They came last before. The placeholders
`...` and `…` now go last. `Sorter::CssSorter` documents the exceptions for
classes with a variant prefix.
- `Sorter` has a new variant, `CssSorter`, which `Sorter::new_from_reader` and
`Sorter::new_from_file` return. Code that matches `Sorter` exhaustively must
handle it. `Sorter::CustomSorter` keeps the old order: classes that the list
does not name come last.
- `Sorter` is now `#[non_exhaustive]`, so a later variant is not a breaking
change. A `match` on `Sorter` outside this crate needs a wildcard arm.

## [0.7.0] - 2026-08-25

### Added
Expand Down
135 changes: 119 additions & 16 deletions rustywind-core/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ static PREFIXED_PATTERN_SORTERS: LazyLock<RwLock<HashMap<String, Arc<HybridSorte
LazyLock::new(|| RwLock::new(HashMap::new()));

struct SortCandidate<'a> {
/// Index of the class in the class list, to restore the input order of unknown classes
position: usize,
original: &'a str,
lookup: Cow<'a, str>,
}
Expand Down Expand Up @@ -460,16 +462,26 @@ impl RustyWind {
}

// otherwise, use the old HashMap-based approach
let candidates = classes.map(|class| SortCandidate {
let candidates = classes.enumerate().map(|(position, class)| SortCandidate {
position,
original: class,
lookup: normalize_tailwind_prefix(class, self.tailwind_prefix.as_deref()),
});

let puts_unknown_classes_first = matches!(self.sorter, Sorter::CssSorter(_));
let mut tailwind_classes: Vec<(&str, &usize)> = vec![];
let mut custom_classes: Vec<&str> = vec![];
let mut custom_classes: Vec<(usize, &str)> = vec![];
let mut placeholders: Vec<&str> = vec![];
let mut variants: HashMap<&str, Vec<SortCandidate>> = HashMap::new();

for candidate in candidates {
// The placeholders `...` and `…` stay last, as in the built-in sorter, also when
// the CSS file names one of them as a class.
if puts_unknown_classes_first && is_ellipsis_placeholder(candidate.original) {
placeholders.push(candidate.original);
continue;
}

match self
.sorter
.get(candidate.original)
Expand All @@ -486,46 +498,52 @@ impl RustyWind {
let prefix = VARIANTS[prefix_match.pattern()];
variants.entry(prefix).or_default().push(candidate)
}
None => custom_classes.push(candidate.original),
None => custom_classes.push((candidate.position, candidate.original)),
}
}
}
}

tailwind_classes.sort_by_key(|&(_class, class_placement)| class_placement);

let sorted_tailwind_classes: Vec<&str> = tailwind_classes
let mut known: Vec<&str> = tailwind_classes
.iter()
.map(|(class, _index)| *class)
.collect();

let mut sorted_variant_classes = vec![];

for key in VARIANTS.iter() {
let (mut sorted_classes, new_custom_classes) = self.sort_variant_classes(
variants.remove(key).unwrap_or_default(),
custom_classes,
key.len() + 1,
);

sorted_variant_classes.append(&mut sorted_classes);
known.append(&mut sorted_classes);
custom_classes = new_custom_classes
}

[
&sorted_tailwind_classes[..],
&sorted_variant_classes[..],
&custom_classes[..],
]
.concat()
if puts_unknown_classes_first {
// Unknown classes keep their input order, as in prettier-plugin-tailwindcss.
custom_classes.sort_by_key(|&(position, _class)| position);
let mut sorted: Vec<&str> = custom_classes
.into_iter()
.map(|(_position, class)| class)
.collect();
sorted.extend(known);
sorted.extend(placeholders);
sorted
} else {
known.extend(custom_classes.into_iter().map(|(_position, class)| class));
known
}
}

fn sort_variant_classes<'a>(
&self,
classes: Vec<SortCandidate<'a>>,
mut custom_classes: Vec<&'a str>,
mut custom_classes: Vec<(usize, &'a str)>,
class_after: usize,
) -> (Vec<&'a str>, Vec<&'a str>) {
) -> (Vec<&'a str>, Vec<(usize, &'a str)>) {
let mut tailwind_classes = Vec::with_capacity(classes.len());

for candidate in classes {
Expand Down Expand Up @@ -557,7 +575,7 @@ impl RustyWind {
Some(class_placement) => {
tailwind_classes.push((candidate.original, class_placement))
}
None => custom_classes.push(candidate.original),
None => custom_classes.push((candidate.position, candidate.original)),
}
}

Expand Down Expand Up @@ -1417,6 +1435,91 @@ mod tests {
}
}

#[test]
fn css_sorter_puts_unknown_classes_first_and_custom_sorter_puts_them_last() {
let input = "p-4 zebra custom flex hover:custom";
let custom_app = RustyWind {
sorter: Sorter::new(HashMap::from([
("flex".to_string(), 0),
("p-4".to_string(), 1),
])),
..RUSTYWIND_DEFAULT
};
let css_app = css_sorter_app(".flex {\n}\n.p-4 {\n}\n");

assert_eq!(
custom_app.sort_classes(input),
"flex p-4 zebra custom hover:custom"
);
assert_eq!(
css_app.sort_classes(input),
"zebra custom hover:custom flex p-4"
);
}

#[test]
fn css_sorter_keeps_unknown_variant_classes_in_input_order() {
let app = css_sorter_app(".flex {\n}\n");

// `hover:custom` is a variant class that the CSS lacks. It must not move behind `zebra`.
assert_eq!(
app.sort_classes("hover:custom zebra flex"),
"hover:custom zebra flex"
);
}

#[test]
fn css_sorter_sorts_a_variant_of_a_known_class_with_the_variants() {
let app = css_sorter_app(".flex {\n}\n.p-4 {\n}\n");

// `hover:flex` is not in the CSS, but its base class `flex` is, so it is no unknown class.
// It goes after the known classes, in the variant group.
assert_eq!(
app.sort_classes("hover:flex zebra p-4 flex"),
"zebra flex p-4 hover:flex"
);
}

#[test]
fn css_sorter_removes_a_duplicate_unknown_class_when_duplicates_are_not_allowed() {
let app = RustyWind {
allow_duplicates: false,
..css_sorter_app(".flex {\n}\n")
};

assert_eq!(app.sort_classes("zebra flex yak zebra"), "zebra yak flex");
}

#[test]
fn css_sorter_keeps_ellipsis_placeholders_last() {
let app = css_sorter_app(".flex {\n}\n.p-4 {\n}\n");

assert_eq!(
app.sort_classes("p-4 … zebra ... flex"),
"zebra flex p-4 … ..."
);

// A CSS file can name `…` as a class. It stays a placeholder.
let app = css_sorter_app(".… {\n}\n.flex {\n}\n");
assert_eq!(app.sort_classes("flex … zebra"), "zebra flex …");
}

#[test]
fn css_sorter_treats_only_one_built_in_variant_prefix_as_a_known_class() {
let app = css_sorter_app(".flex {\n}\n.p-4 {\n}\n");

// `max-md:` is no built-in variant prefix, so `max-md:flex` is unknown and goes first.
assert_eq!(
app.sort_classes("p-4 max-md:flex flex"),
"max-md:flex flex p-4"
);
// Only one prefix is stripped, so a stacked `md:hover:flex` is unknown as well.
assert_eq!(
app.sort_classes("p-4 md:hover:flex flex"),
"md:hover:flex flex p-4"
);
}

#[test]
fn css_sorter_orders_classes_by_their_position_in_the_css() {
let app = css_sorter_app(
Expand Down
7 changes: 7 additions & 0 deletions rustywind-core/src/css_class_order.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,13 @@
//!
//! - The scan suits the selectors that Tailwind CSS emits. For hand-written component CSS such
//! as `.card .title { }`, it registers `title`, and `card` stays unknown.
//! - In the flat output of Tailwind CSS 4.3.3 and later, a utility whose only rule styles a
//! descendant class, such as `@utility btn { & .icon { width: 2rem; } }`, compiles to
//! `.btn .icon` and registers `icon`. `btn` stays unknown. A utility with declarations of its
//! own also emits `.btn { }`, which registers `btn`. Nested output keeps the outer `.btn` rule.
//! - In the same flat output, a custom variant whose selector names a class with a colon that is longer than the
//! candidate, such as `@custom-variant x (&:where(.md\:grid-cols-2 *))`, registers
//! `md:grid-cols-2` for that rule instead of `x:flex`.
//! - A nested rule without `&`, in the form `.a { .b { } }` or `.a { > .b { } }`, registers `a`
//! and `b`. Tailwind CSS does not emit this form.
//! - `cssparser` allows 75 nested blocks, and the block of a rule counts as one. The scan skips a
Expand Down
41 changes: 33 additions & 8 deletions rustywind-core/src/sorter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,13 +93,32 @@ impl Deref for FinderRegex {
}
}

/// Uses either pattern-based sorting or a custom sorter from a CSS file
/// Uses either pattern-based sorting or a sorter from a class list or a CSS file
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum Sorter {
/// Pattern-based sorting matching Tailwind CSS v4's canonical algorithm
PatternSorter,
/// Custom sorter loaded from a CSS file
/// Custom sorter from a list of classes, such as the `sortOrder` of a config file. A class
/// that is not in the list goes after the classes of the list.
CustomSorter(HashMap<String, usize>),
/// Sorter loaded from a CSS file that Tailwind generated.
///
/// A class that the file does not name is unknown. Unknown classes go before the classes of
/// the file, in input order, as in prettier-plugin-tailwindcss. The placeholders `...` and `…`
/// go last.
///
/// The sorter looks up the whole class first. A class that the file names itself, such as
/// `hover:bg-w` in Tailwind CSS output, keeps its own position.
///
/// A class with a built-in variant prefix, such as `hover:` or `md:`, that the file does not
/// name itself is not unknown when the file names the part after the prefix. `hover:flex` is
/// then known when the file names `flex` but not `hover:flex`. It goes after the classes of
/// the file, with the variants. Only the first prefix counts:
/// `md:hover:flex` is known when the file names `hover:flex`. A class with another prefix,
/// such as `max-md:flex` or `peer-hover:flex`, is unknown unless the file names the whole
/// class.
CssSorter(HashMap<String, usize>),
}

impl Deref for Sorter {
Expand All @@ -110,20 +129,24 @@ impl Deref for Sorter {
Self::PatternSorter => {
panic!("PatternSorter should not be used with HashMap-based sorting")
}
Self::CustomSorter(sorter) => sorter,
Self::CustomSorter(sorter) | Self::CssSorter(sorter) => sorter,
}
}
}

impl Sorter {
/// Creates a custom sorter from class positions
/// Creates a [`Sorter::CustomSorter`] from class positions
///
/// A class that the map lacks goes after the classes of the map. To put such classes first,
/// wrap the map in [`Sorter::CssSorter`] instead.
pub fn new(sorter: HashMap<String, usize>) -> Self {
Self::CustomSorter(sorter)
}

/// Creates the sorter from a [File]
/// Creates a [`Sorter::CssSorter`] from a [File]
///
/// See [`Sorter::new_from_reader`] for the order of the classes.
/// See [`Sorter::new_from_reader`] for the order of the classes, and [`Sorter::CssSorter`]
/// for the order of unknown classes.
///
/// # Errors
///
Expand All @@ -134,12 +157,14 @@ impl Sorter {
Self::new_from_reader(css_reader)
}

/// Creates the sorter from any [BufReader]
/// Creates a [`Sorter::CssSorter`] from any [BufReader]
///
/// The order is the order of the first rule that names a class. Each selector gives one class:
/// the longest one with a `:` in its name, else the first class of its last compound selector
/// that holds a class. A prelude with `&` and an at-rule prelude give none.
///
/// See [`Sorter::CssSorter`] for the order of unknown classes.
///
/// # Errors
///
/// Returns an error when reading fails, or when the input is not valid UTF-8
Expand All @@ -154,7 +179,7 @@ impl Sorter {
classes.entry(class).or_insert(next);
}

Ok(Self::new(classes))
Ok(Self::CssSorter(classes))
}
}

Expand Down
4 changes: 2 additions & 2 deletions rustywind-vite/src/sorter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,8 @@ mod tests {

#[test]
fn decodes_a_unicode_escape_of_the_javascript_string_literal() {
// The module line is literal text: `é` is the escape for `é`.
let sorter = sorter_from_module(r#"const __vite__css = ".é { }""#).unwrap();
// The module line is literal text: `\u00e9` is the JSON escape for `é`.
let sorter = sorter_from_module(r#"const __vite__css = ".\u00e9 { }""#).unwrap();

assert_eq!(sorter.get("é"), Some(&0));
assert_eq!(sorter.len(), 1);
Expand Down
Loading