dsherret / dsherret/ts-morph

Weird formatting issue with prependWhitespace() for a JsxAttribute

Open
#897 2 comments 0 reactions 0 assignees View on GitHub
bug domain: formatting
Dominant language
TypeScript
Stars
6.2k
Forks
238
Avg merge
2m
Merged PRs (30d)
1

Description

**Describe the bug**

Version: 9.1.0

Hey @dsherret. I'm getting a weird formatting issue when trying to add some whitespace before a `JsxAttribute` node.

I'm trying to get a new attribute to be on its own line. So I have this (minimal example) tag:

```


Text

```

Adding a new attribute (`align="center"`) with the `.addAttribute()` API results in the following: (attribute on same line)

```ts


Text

```

So I'm trying to prepend a line break and 4 spaces before the new 'align' attribute node (`newAttr.prependWhitespace('\n    ')`), but the formatting ends up like this:

```


Text

```

If I prepend just a single line break (`\n`) without any spaces, I get this:

```


Text

```

And if I prepend a line break and just a single space (`'\n '`):

```


Text

```

I think the formatter is trying to align the new attribute vertically with the previous attribute, but then adding spaces after that.

**To Reproduce**

```ts
import { JsxOpeningElement, Project, SyntaxKind, ts } from 'ts-morph';

console.log(ts.version); // 4.1.2

const project = new Project();
const sourceFile = project.createSourceFile('tmp.tsx', `
const MyComponent = () => {
return (


Text

);
};
`);

const jsxEl = sourceFile.getFirstDescendantByKindOrThrow(SyntaxKind.JsxOpeningElement) as JsxOpeningElement;
const newAttr = jsxEl.addAttribute({ name: 'align', initializer: '"center"' });
newAttr.prependWhitespace('\n '); // somehow inserts 16 spaces in this case

console.log(sourceFile.getFullText());
```

Output from this particular example:

```
const MyComponent = () => {
return (


Text

);
};
```

**Expected behavior**

I would have expected the line break and the exact 4 spaces I put in to be present after I call `prependWhitespace('\n    ')`.

However, if there's some formatting that's supposed to go on here, it seems that maybe it should trigger from just adding a `\n` char?

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.