fix(formatter): Trim trailing whitespace before breaking line (#19740)

This doesn't seem to be an issue with native js/ts format paths, but it appears to cause problems when converting Prettier Docs, such as with gql-in-js.

Without this change,

```gql
type Mutation {
    create__TYPE_NAME__(input: Create__TYPE_NAME__Input!): __TYPE_NAME__!
      @skipAuth
```

will be formatted:

```gql
type Mutation {
    create__TYPE_NAME__(input: Create__TYPE_NAME__Input!): __TYPE_NAME__!
      @skipAuth
```

See trailing ` ` after `__TYPE_NAME__!`.
This commit is contained in:
leaysgur committed 2026-02-26 15:24:02 +00:00
1 parent 72ce141c5a
commit 93bb861dc3
3 files changed
+24 -24

No files matched your search

@@ -12,33 +12,21 @@ describe("Prettier conformance for graphql-in-js", () => {
"format.test.js",
"comment-tag.js", // /* GraphQL */
]);
// TODO: Fix in next PR
// graphqlFixtures.push(
// {
// name: "inline/gql-trailing-space.js",
// content: `export const schema = gql\`
// type Mutation {
// create__TYPE_NAME__(input: Create__TYPE_NAME__Input!): __TYPE_NAME__!
// @skipAuth
// update__TYPE_NAME__(
// id: Int!
// input: Update__TYPE_NAME__Input!
// ): __TYPE_NAME__! @skipAuth
// delete__TYPE_NAME__(id: Int!): __TYPE_NAME__! @skipAuth
// }
// \`
// `,
// },
// );
graphqlFixtures.push({
name: "inline/gql-dummy.js",
name: "inline/gql-trailing-space.js",
content: `export const schema = gql\`
type Relation {
id: Int!
name: String!
type Mutation {
create__TYPE_NAME__(input: Create__TYPE_NAME__Input!): __TYPE_NAME__!
@skipAuth
update__TYPE_NAME__(
id: Int!
input: Update__TYPE_NAME__Input!
): __TYPE_NAME__! @skipAuth
delete__TYPE_NAME__(id: Int!): __TYPE_NAME__! @skipAuth
}
\`
`,
\`
`,
});
describe.concurrent.each(graphqlFixtures)("$name", ({ name, content }) => {
@@ -538,6 +538,17 @@ impl CodeBuffer {
unsafe { self.buf.set_len(len + bytes) };
}
/// Remove trailing whitespace (spaces and tabs) from the buffer.
///
/// This trims trailing whitespace before line breaks, matching Prettier's `trimEnd(out)` behavior.
/// <https://github.com/prettier/prettier/blob/90983f40dce5e20beea4e5618b5e0426a6a7f4f0/src/document/printer/printer.js#L535>
#[inline]
pub fn trim_trailing_ascii_whitespace(&mut self) {
while self.buf.last().is_some_and(|&b| b == b' ' || b == b'\t') {
self.buf.pop();
}
}
/// Get contents of buffer as a byte slice.
///
/// # Example
@@ -127,6 +127,7 @@ impl<'a> Printer<'a> {
// Only print a newline if the current line isn't already empty
if self.state.line_width > 0 {
self.state.buffer.trim_trailing_ascii_whitespace();
self.print_char('\n');
self.state.has_empty_line = false;
}