Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: trim replaced content with space #257

Merged
merged 8 commits into from
Aug 21, 2023
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
17 changes: 16 additions & 1 deletion src/Chunk.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,13 @@ export default class Chunk {
this.end = index;

if (this.edited) {
// after split we should save the edit content record into the correct chunk
// to make sure sourcemap correct
// For example:
// ' test'.trim()
// split -> ' ' + 'test'
// ✔️ edit -> '' + 'test'
// ✖️ edit -> 'test' + ''
// TODO is this block necessary?...
newChunk.edit('', false);
this.content = '';
Expand Down Expand Up @@ -127,6 +134,10 @@ export default class Chunk {
if (trimmed.length) {
if (trimmed !== this.content) {
this.split(this.start + trimmed.length).edit('', undefined, true);
if (this.edited) {
// save the change, if it has been edited
this.edit(trimmed, this.storeName, true);
}
}
return true;
} else {
Expand All @@ -145,7 +156,11 @@ export default class Chunk {

if (trimmed.length) {
if (trimmed !== this.content) {
this.split(this.end - trimmed.length);
const newChunk = this.split(this.end - trimmed.length);
if (this.edited) {
// save the change, if it has been edited
newChunk.edit(trimmed, this.storeName, true);
}
this.edit('', undefined, true);
}
return true;
Expand Down
21 changes: 21 additions & 0 deletions test/MagicString.js
Original file line number Diff line number Diff line change
Expand Up @@ -1338,6 +1338,27 @@ describe('MagicString', () => {
assert.equal(s.toString(), 'defghi');
});

it('should trim replaced content with end space', () => {
const s = new MagicString(' test ');
s.overwrite(2, 6, 'abcd ');
s.trimEnd();
assert.equal(s.toString(), ' abcd');
});

it('should trim replaced content with start space', () => {
const s = new MagicString(' test ');
s.overwrite(0, 6, ' abcd');
s.trimStart();
assert.equal(s.toString(), 'abcd ');
});

it('should trim replaced content with start space', () => {
const s = new MagicString(' test ');
s.overwrite(0, 8, ' abcd ');
s.trim();
assert.equal(s.toString(), 'abcd');
});

it('should trim original content before replaced content', () => {
const s = new MagicString('abc def');

Expand Down
Loading