Skip to content

Commit 5daa536

Browse files
authored
fix: use search_from offset in indexOf to correctly locate duplicate style blocks (#96)
1 parent dfaabbd commit 5daa536

2 files changed

Lines changed: 19 additions & 2 deletions

File tree

‎src/lib/remap-html.test.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,20 @@ test('remaps a single style block', () => {
4444
})
4545
})
4646

47+
test('remaps correctly when two style blocks have identical content', () => {
48+
let css = `h1 { color: red; }`
49+
// Two style tags with identical CSS — indexOf always finds the first occurrence,
50+
// so a range inside the second block falls outside [first_start, first_end] and gets dropped
51+
let html = `<style>${css}</style><style>${css}</style>`
52+
let second_start = html.lastIndexOf('<style>') + '<style>'.length
53+
let range = { start: second_start, end: second_start + css.length }
54+
let result = remap_html(html, [range])
55+
expect(result).toEqual({
56+
css: css + css,
57+
ranges: [{ start: css.length, end: css.length * 2 }],
58+
})
59+
})
60+
4761
test('remaps multiple style blocks', () => {
4862
let css_head = `h1 { color: red; }`
4963
let css_body = `h2 { font-size: 24px; }`

‎src/lib/remap-html.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ export function remap_html(html: string, old_ranges: Range[]) {
1616
let new_ranges = []
1717
let current_offset = 0
1818
let style_elements = doc.querySelectorAll('style')
19+
let search_from = 0
1920

2021
for (let style_element of Array.from(style_elements)) {
2122
let style_content = style_element.textContent
@@ -24,9 +25,11 @@ export function remap_html(html: string, old_ranges: Range[]) {
2425
// Append the style content directly to the combined CSS
2526
combined_css += style_content
2627

27-
// Find the offsets of this style element's content in the original HTML
28-
let start_index = html.indexOf(style_content)
28+
// Find the offsets of this style element's content in the original HTML,
29+
// starting after the previous style block to avoid matching an earlier occurrence
30+
let start_index = html.indexOf(style_content, search_from)
2931
let end_index = start_index + style_content.length
32+
search_from = end_index
3033

3134
// Iterate through ranges and adjust if they fall within the current style tag
3235
for (let range of old_ranges) {

0 commit comments

Comments
 (0)