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
14 changes: 14 additions & 0 deletions src/lib/remap-html.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,20 @@ test('remaps a single style block', () => {
})
})

test('remaps correctly when two style blocks have identical content', () => {
let css = `h1 { color: red; }`
// Two style tags with identical CSS — indexOf always finds the first occurrence,
// so a range inside the second block falls outside [first_start, first_end] and gets dropped
let html = `<style>${css}</style><style>${css}</style>`
let second_start = html.lastIndexOf('<style>') + '<style>'.length
let range = { start: second_start, end: second_start + css.length }
let result = remap_html(html, [range])
expect(result).toEqual({
css: css + css,
ranges: [{ start: css.length, end: css.length * 2 }],
})
})

test('remaps multiple style blocks', () => {
let css_head = `h1 { color: red; }`
let css_body = `h2 { font-size: 24px; }`
Expand Down
7 changes: 5 additions & 2 deletions src/lib/remap-html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export function remap_html(html: string, old_ranges: Range[]) {
let new_ranges = []
let current_offset = 0
let style_elements = doc.querySelectorAll('style')
let search_from = 0

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

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

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