Skip to content

Commit

Permalink
fix: trim replaced content with space (#257)
Browse files Browse the repository at this point in the history
Co-authored-by: poyoho <panyoho@gamil.com>
  • Loading branch information
poyoho and poyoho committed Aug 21, 2023
1 parent 962192c commit 8088f53
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
17 changes: 16 additions & 1 deletion src/Chunk.js
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
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

0 comments on commit 8088f53

Please sign in to comment.