( html: string, target: PatchTarget, attr: string, value: string | null, )
| 307 | } |
| 308 | |
| 309 | function patchAttributeByTarget( |
| 310 | html: string, |
| 311 | target: PatchTarget, |
| 312 | attr: string, |
| 313 | value: string | null, |
| 314 | ): string { |
| 315 | const match = findTagByTarget(html, target); |
| 316 | if (!match) return html; |
| 317 | |
| 318 | const fullAttr = attr.startsWith("data-") ? attr : `data-${attr}`; |
| 319 | const attrPattern = new RegExp(`\\b${escapeRegex(fullAttr)}=(["'])([^"']*)\\1`); |
| 320 | const tag = match.tag; |
| 321 | |
| 322 | if (value === null) { |
| 323 | // Remove the attribute if present |
| 324 | if (!attrPattern.test(tag)) return html; |
| 325 | const removePattern = new RegExp(`\\s+${escapeRegex(fullAttr)}=(["'])[^"']*\\1`); |
| 326 | const newTag = tag.replace(removePattern, ""); |
| 327 | return replaceTagAtMatch(html, match, newTag); |
| 328 | } |
| 329 | |
| 330 | const escaped = escapeHtmlAttribute(value); |
| 331 | if (attrPattern.test(tag)) { |
| 332 | const newTag = tag.replace(attrPattern, `${fullAttr}="${escaped}"`); |
| 333 | return replaceTagAtMatch(html, match, newTag); |
| 334 | } |
| 335 | |
| 336 | const newTag = tag + ` ${fullAttr}="${escaped}"`; |
| 337 | return replaceTagAtMatch(html, match, newTag); |
| 338 | } |
| 339 | |
| 340 | /** |
| 341 | * Apply an attribute change to an element in the HTML source. |
no test coverage detected