Skip to content
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
18 changes: 12 additions & 6 deletions src/Chunk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,11 +164,14 @@ 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
// the content of an edited chunk no longer lines up with its range in the
// original string, so there is no index to split at - trim it in place
this.edit(trimmed, this.storeName, true)
}
else {
this.split(this.start + trimmed.length).edit('', undefined, true)
}
}
return true
}
Expand All @@ -190,12 +193,15 @@ export default class Chunk {

if (trimmed.length) {
if (trimmed !== this.content) {
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)
// the content of an edited chunk no longer lines up with its range in the
// original string, so there is no index to split at - trim it in place
this.edit(trimmed, this.storeName, true)
}
else {
this.split(this.end - trimmed.length)
this.edit('', undefined, true)
}
this.edit('', undefined, true)
}
return true
}
Expand Down
25 changes: 25 additions & 0 deletions test/MagicString.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1675,6 +1675,31 @@ describe('magicString', () => {
assert.equal(s.toString(), 'abcd')
})

it('should trim a replacement that is longer than the range it replaces', () => {
const s = new MagicString('ab')
s.overwrite(0, 1, ' xyz')
s.trimStart()

assert.equal(s.toString(), 'xyzb')

for (const line of s.generateDecodedMap({ source: 'in.js' }).mappings) {
for (const segment of line) {
if (segment.length > 1) {
assert.ok(segment[1]! >= 0 && segment[2]! >= 0 && segment[3]! >= 0, `segment ${JSON.stringify(segment)} points outside the original`)
}
}
}
})

it('should trim the end of a replacement that is longer than the range it replaces', () => {
const s = new MagicString('ab')
s.overwrite(1, 2, 'xyz ')
s.trimEnd()

assert.equal(s.toString(), 'axyz')
assert.equal(s.slice(0, 2), 'axyz')
})

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

Expand Down
Loading