( html: string, tag: string, prop: string, value: string | null, )
| 170 | } |
| 171 | |
| 172 | function patchInlineStyleInTag( |
| 173 | html: string, |
| 174 | tag: string, |
| 175 | prop: string, |
| 176 | value: string | null, |
| 177 | ): string { |
| 178 | if (!tag) return html; |
| 179 | |
| 180 | // Check if there's an existing style attribute |
| 181 | const styleMatch = /\bstyle=(["'])([\s\S]*?)\1/.exec(tag); |
| 182 | if (styleMatch) { |
| 183 | const existingStyle = styleMatch[2]; |
| 184 | const quote = styleMatch[1]; |
| 185 | // Parse existing properties |
| 186 | const props = new Map<string, string>(); |
| 187 | for (const part of splitInlineStyleDeclarations(existingStyle)) { |
| 188 | const colon = part.indexOf(":"); |
| 189 | if (colon < 0) continue; |
| 190 | const key = part.slice(0, colon).trim(); |
| 191 | const val = part.slice(colon + 1).trim(); |
| 192 | if (key) props.set(key, val); |
| 193 | } |
| 194 | // Update/add or remove the property |
| 195 | if (value === null) { |
| 196 | props.delete(prop); |
| 197 | } else { |
| 198 | props.set(prop, value); |
| 199 | } |
| 200 | // Rebuild style string; keep style="" if empty (harmless) |
| 201 | const newStyle = Array.from(props.entries()) |
| 202 | .map(([k, v]) => `${k}: ${escapeStyleAttributeValue(v, quote)}`) |
| 203 | .join("; "); |
| 204 | const newTag = tag.replace(styleMatch[0], `style=${quote}${newStyle}${quote}`); |
| 205 | return html.replace(tag, newTag); |
| 206 | } else { |
| 207 | // No existing style attribute |
| 208 | if (value === null) return html; // nothing to remove |
| 209 | const selfClosing = /\s*\/$/.test(tag); |
| 210 | const base = selfClosing ? tag.replace(/\s*\/$/, "") : tag; |
| 211 | const newTag = `${base} style="${prop}: ${escapeStyleAttributeValue(value, '"')}"${selfClosing ? " /" : ""}`; |
| 212 | return html.replace(tag, newTag); |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | function patchInlineStyleByTarget( |
| 217 | html: string, |
no test coverage detected