* Apply an attribute change to an element in the HTML source.
( html: string, elementId: string, attr: string, value: string | null, )
| 341 | * Apply an attribute change to an element in the HTML source. |
| 342 | */ |
| 343 | function patchAttribute( |
| 344 | html: string, |
| 345 | elementId: string, |
| 346 | attr: string, |
| 347 | value: string | null, |
| 348 | ): string { |
| 349 | const idPattern = new RegExp(`(<[^>]*\\bid=(["'])${escapeRegex(elementId)}\\2[^>]*)>`, "i"); |
| 350 | const match = idPattern.exec(html); |
| 351 | if (!match) return html; |
| 352 | |
| 353 | const tag = match[1]; |
| 354 | const fullAttr = attr.startsWith("data-") ? attr : `data-${attr}`; |
| 355 | const attrPattern = new RegExp(`\\b${escapeRegex(fullAttr)}=(["'])([^"']*)\\1`); |
| 356 | |
| 357 | if (value === null) { |
| 358 | if (!attrPattern.test(tag)) return html; |
| 359 | const removePattern = new RegExp(`\\s+${escapeRegex(fullAttr)}=(["'])[^"']*\\1`); |
| 360 | const newTag = tag.replace(removePattern, ""); |
| 361 | return html.replace(tag, newTag); |
| 362 | } |
| 363 | |
| 364 | const escaped = escapeHtmlAttribute(value); |
| 365 | if (attrPattern.test(tag)) { |
| 366 | // Update existing attribute |
| 367 | const newTag = tag.replace(attrPattern, `${fullAttr}="${escaped}"`); |
| 368 | return html.replace(tag, newTag); |
| 369 | } else { |
| 370 | // Add new attribute |
| 371 | const newTag = tag + ` ${fullAttr}="${escaped}"`; |
| 372 | return html.replace(tag, newTag); |
| 373 | } |
| 374 | } |
| 375 | |
| 376 | /** |
| 377 | * Apply a text content change to an element. |
no test coverage detected