Skip to content

fix(formatter): decide JSX opening element layout from collapsed Tailwind class string - #28744

Merged
leaysgur merged 3 commits into
oxc-project:mainfrom
jaehafe:fix/oxfmt-tailwind-jsx-multiline-idempotent
Nov 4, 2026
Merged

leaysgur merged 3 commits into
oxc-project:mainfrom
jaehafe:fix/oxfmt-tailwind-jsx-multiline-idempotent

Conversation

@jaehafe

@jaehafe jaehafe commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary

With sortTailwindcss enabled (and preserveWhitespace off), formatting a JSX element whose Tailwind class string spans multiple lines is not idempotent. It takes two runs to reach a stable output.

Input ({"sortTailwindcss": {}}):

const A = (
  <div
    className="p-4
      flex"
  >
    Hello
  </div>
);

1st run:

const A = (
  <div
    className="flex p-4"
  >
    Hello
  </div>
);

2nd run:

const A = <div className="flex p-4">Hello</div>;

Cause

FormatOpeningElement decides its layout from the attribute's source string value:

  • SingleStringAttribute is used only if the value has no line break.
  • Otherwise the attributes group is forced to expand if any string value has a line break.

But for a Tailwind attribute without preserveWhitespace, write_tailwind_string_literal collapses all whitespace (including line breaks) into single spaces. So the printed value has no line break while the layout was decided as if it had one. The next run sees a single-line value and joins the element.

prettier-plugin-tailwindcss rewrites the attribute value in the AST before printing, so Prettier makes the layout decision on the collapsed value and gets the 2nd-run output in one pass.

Fix

Decide the layout from whether the printed value has a line break. A Tailwind attribute (per is_tailwind_jsx_attribute) with preserveWhitespace off is treated as single-line. Nothing changes when sortTailwindcss is off, with preserveWhitespace: true, or for non-Tailwind attributes.

Test

  • Added 3 cases to apps/oxfmt/test/api/sort_tailwindcss.test.ts:
    • multiline class string in a single-attribute and a multi-attribute element: formats in one run, and a 2nd run doesn't change the output. Fails without this fix.
    • preserveWhitespace: true: still keeps line breaks and expands the element (unchanged).
    • multiline non-Tailwind attribute (title) next to a className: still expands the element (unchanged).
  • apps/oxfmt: vitest run β†’ 553 passed
  • cargo test -p oxc_formatter, CARGO_BUILD_WARNINGS=deny cargo lint -p oxc_formatter, cargo fmt --check, node --run fmt pass
  • I didn't run conformance:prettier (fixtures not downloaded locally). It doesn't enable sortTailwindcss, so this code path behaves the same as before there.
  • Found while migrating a real Next.js app to oxfmt: 42 files needed a second oxfmt --write run.

@jaehafe
jaehafe requested a review from leaysgur as a code owner November 3, 2026 07:30
…wind class string

When `sortTailwindcss` is enabled (without `preserveWhitespace`), a multiline
class string in a Tailwind attribute is printed on one line, because all
whitespace is collapsed. But the opening element layout was decided from the
source value, which still contains line breaks, so the element was expanded:

    <div
      className="flex p-4"
    >

and only the next run joined it into `<div className="flex p-4">`.

Decide the layout from whether the printed value has a line break, so the
output is stable after one run.
@github-actions github-actions Bot added A-cli Area - oxlint / oxfmt common CLI behavior: flags, ignore files, oxc_config A-formatter Area - Formatter (oxfmt). Add F-* labels for details labels Nov 4, 2026
@codspeed

codspeed Bot commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

βœ… 77 untouched benchmarks
⏩ 19 skipped benchmarks1


Comparing jaehafe:fix/oxfmt-tailwind-jsx-multiline-idempotent (7cd8ebe) with main (45d86c3)2

Open in CodSpeed

Footnotes

  1. 19 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

  2. No successful run was found on main (2766d07) during the generation of this report, so 45d86c3 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@leaysgur
leaysgur merged commit 0b44164 into oxc-project:main Nov 4, 2026
40 checks passed
@leaysgur

leaysgur commented Nov 4, 2026

Copy link
Copy Markdown
Member

Thank you!

leaysgur added a commit that referenced this pull request Nov 4, 2026
… Tailwind classes (#28791)

Follow-up to #28744, same root cause in other places.

With `sortTailwindcss` on and `preserveWhitespace` off, Tailwind class
strings and templates are printed with their whitespace collapsed, but
these layout decisions read the source text, so formatting took two
runs:

```ts
// Sole template argument of a Tailwind call
const a = clsx(`
  p-4 flex items-center ${active ? "bg-white" : "bg-black"} text-black
`);
// Arrow body tagged with a Tailwind function
const b = () => tw`
  p-4 flex items-center bg-white text-black
`;
// Short object key (tabWidth: 4)
const c = clsx({ "a   b": someLongCondition });
```

- `is_multiline_template_starting_on_same_line` now returns `false` for
a template whose line breaks are collapsed
- It reads the current Tailwind context (what `TemplateElement` reads)
or the one a Tailwind tag pushes, so the arrow body, sole argument and
member chain routing callers follow the print
- `write_tailwind_string_literal` returns its printed width, and
`write_member_name` uses it for the short key decision
  - An upper bound: the sorter also drops duplicates of known classes
- `tailwind_context_for_callee` is shared by the call and tagged
template pushes and the layout check, like
`tailwind_context_for_jsx_attribute` in #28744

Outputs match Prettier + prettier-plugin-tailwindcss and are idempotent.

Not covered here: `is_short_argument` (#28745), Tailwind calls through
`MemberChain` never pushing the context, and computed keys.

AI assistance (Claude Code) was used for this change. I reviewed and
tested it.

πŸ€– Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
leaysgur added a commit that referenced this pull request Nov 4, 2026
…espace (#28745)

## Summary

Follow-up to #28744, same kind of issue in a different place.

With `sortTailwindcss` enabled, an assignment whose right side is a
Tailwind function call can take two runs to reach a stable output,
because the "short argument" check measures the argument's **source**
text while the printed text has its whitespace collapsed.

Input (`{"sortTailwindcss": {"functions": ["cn"]}}`, default
`printWidth: 100`):

```ts
const vaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = cn("p-4                           flex");
```

1st run:

```ts
const vaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = cn(
  "flex p-4",
);
```

2nd run (also what Prettier + prettier-plugin-tailwindcss prints in one
run):

```ts
const vaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =
  cn("flex p-4");
```

The same happens for `a.b = cn(...)`, `{ key: cn(...) }` and
`cn(...).trim()`.

### Cause

`is_poorly_breakable_member_or_call_chain` uses `is_short_argument`
(Prettier's `isLoneShortArgument`) to check if the only argument is at
most `printWidth / 4` wide. For a string or template literal it measures
the source text. When the argument is sorted as Tailwind classes,
whitespace is collapsed when printed, so the source can be "long" while
the printed text is "short". Prettier sees the already rewritten value,
so it decides on the printed text.

### Fix

When the call is a Tailwind function call and `preserveWhitespace` is
off, measure the string / template literal argument after collapsing
whitespace (`collapsed_class_list_width`).

### Known limitation: duplicate classes

Duplicate removal also shortens the printed text, e.g. `cn("flex flex
flex flex flex p-4")` still takes two runs. I didn't handle it, because
the sorter removes duplicates only for classes known to Tailwind CSS
(`sortClassList` in prettier-plugin-tailwindcss: `if (order !== null)
seenClasses.add(cls)`), and the formatter can't know which classes are
known while building the IR.

The options I could think of:

1. Leave it (this PR). Duplicates are rare in real code, and the result
is still valid. It just settles on the 2nd run.
2. Also dedupe all classes when measuring. This fixes the common case
but can measure too short when unknown classes are duplicated.
3. Make the sorted text available before the layout decision, which is a
larger change to how sorting is batched.

I went with 1 to keep this small. If you prefer another approach, please
let me know and I'll update it.

## Test

- Added cases to `apps/oxfmt/test/api/sort_tailwindcss.test.ts`:
- string and template literal arguments with extra whitespace format in
one run, and a 2nd run doesn't change the output. These fail without
this fix.
- `preserveWhitespace: true`: the source text is still measured
(unchanged).
- `apps/oxfmt`: `vitest run` β†’ 553 passed
- `cargo test -p oxc_formatter`, `CARGO_BUILD_WARNINGS=deny cargo lint
-p oxc_formatter`, `cargo fmt --check`, `node --run fmt` pass
- I also formatted 7 code shapes Γ— 5 class strings Γ— identifier lengths
1–100 twice and compared the runs. All whitespace cases are now stable;
only the duplicate-class cases above remain.

---------

Co-authored-by: leaysgur <6259812+leaysgur@users.noreply.github.com>
graphite-app Bot pushed a commit that referenced this pull request Nov 6, 2026
# Oxlint
### πŸš€ Features

- 4a52ba2 oxlint: Discover tsrs for type-aware linting (#28751) (camc314)
- b7d2c75 linter/eslint/no-redeclare: Add `ignoreDeclarationMerge` option (#28816) (Cam McHenry)

### πŸ› Bug Fixes

- fa66fde oxlint,oxfmt: Resolve Vite+ config root from the config file directory (#28801) (MK (fengmk2))
- 2091564 linter/jsdoc/require-param: Ignore enclosing function JSDoc (#28866) (camc314)
- c6ec50b linter/react/only-export-components: Classify JSX values as non-components (#28761) (camc314)
- 3c051ab linter/vitest/prefer-called-exactly-once-with: Preserve neighboring code in autofix (#28864) (camc314)
- 674b962 linter/eslint/no-misleading-character-class: Use lazy regex for combining marks (#28822) (Sysix)
- 838d339 linter/vitest/prefer-called-exactly-once-with: Avoid panic on non-ASCII text (#28850) (YT)
- 8d24c26 linter/jsx-a11y/aria-role: Allow role={undefined} (#28804) (Abhay Godavarthy)
- a7143bf linter/eslint/no-restricted-imports: Respect allowTypeImports correctly for empty patterns (#28842) (Cam McHenry)
- 3d3a6f4 react-compiler: Ignore callback-local reassignments (#28820) (camc314)
- 0cc6515 linter/unicorn/prefer-type-error: Report throws in unbraced if branches (#28819) (camc314)
- ae43c80 linter/unicorn/prefer-single-call: Remove duplicate fix status (#28763) (Mikhail Baev)
- a8a621a linter/eslint/no-fallthrough: Ignore unreachable exits from infinite loops (#28755) (camc314)
- 7a17a80 linter/eslint/prefer-spread: Report calls on non-member expressions (#28753) (camc314)
- 28442f7 oxlint: Prevent --init from overwriting existing configs (#28754) (camc314)
- 0ae350d linter/unicorn/no-zero-fractions: Preserve exponent case (#28752) (camc314)
- b5b3f3f linter/eslint/no-misleading-character-class: Detect more combining characters (#28733) (Sysix)

### ⚑ Performance

- 74d50c1 linter: Overlap import graph batches instead of polling on a pool worker (#28323) (Dunqing)
# Oxfmt
### πŸ’₯ BREAKING CHANGES

- 00d1a67 oxfmt: [**BREAKING**] Format `parser:vue` files by `oxc_formatter_htmlish` (#28848) (leaysgur)

### πŸš€ Features

- 9a81e58 formatter_htmlish: Format Vue templates (#28847) (leaysgur)
- 119d82f formatter: Format a template's expressions and handlers as `JsRoot` (#28846) (leaysgur)

### πŸ› Bug Fixes

- fa66fde oxlint,oxfmt: Resolve Vite+ config root from the config file directory (#28801) (MK (fengmk2))
- 4d4104d formatter_htmlish: Preserve `doctype` case in embedded (#28797) (leaysgur)
- ebfd40a formatter: Sort Tailwind calls printed as member chains (#28800) (Yuji Sugiura)
- e62e5cb formatter: Decide quotes of a Tailwind key printed as one class (#28798) (Yuji Sugiura)
- 959edc1 formatter: Don't sort templates in nested non-Tailwind calls (#28794) (Yuji Sugiura)
- 6ffbe32 formatter/jsdoc: Prevent `@tag` from being moved to the line start (#28835) (leaysgur)
- 94fbef5 formatter_css: Treat comments in `style` attr as fill items (#28832) (leaysgur)
- e4a80f7 formatter_css: Normalize selectors inside `:deep`, `:slotted` and `:local` (#28805) (leaysgur)
- 255c5cc formatter: Measure Tailwind class argument after collapsing whitespace (#28745) (Lee Jaeha / Adam)
- e6c4fef formatter: Decide template and object key layouts from collapsed Tailwind classes (#28791) (Yuji Sugiura)
- 0b44164 formatter: Decide JSX opening element layout from collapsed Tailwind class string (#28744) (Lee Jaeha / Adam)
- b8ba9ae formatter: Print decorators on rest parameters (#28731) (YT)

### ⚑ Performance

- 2766d07 oxfmt: Spawn Prettier workers on demand (#28789) (YT)
- 07627f7 oxfmt: Use worker_threads for tinypool again (#28787) (Yuji Sugiura)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

A-cli Area - oxlint / oxfmt common CLI behavior: flags, ignore files, oxc_config A-formatter Area - Formatter (oxfmt). Add F-* labels for details

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants