From feb6675d898980a1f0fcc1f4245f5684ba455915 Mon Sep 17 00:00:00 2001 From: Derek Gray Date: Thu, 12 Sep 2024 18:52:30 -0500 Subject: [PATCH 1/2] Fix #242: keep id,media,title attributes on replaced link elements --- src/transform.ts | 5 ++++- tests/unit/transform.test.ts | 20 ++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/transform.ts b/src/transform.ts index 3a7ebdcf..45a86dd9 100644 --- a/src/transform.ts +++ b/src/transform.ts @@ -12,13 +12,16 @@ export async function transformCSS( if (el.tagName.toLowerCase() === 'style') { // Handle inline stylesheets el.innerHTML = css; - } else if (el.tagName.toLowerCase() === 'link') { + } else if (el instanceof HTMLLinkElement) { // Create new link const blob = new Blob([css], { type: 'text/css' }); const url = URL.createObjectURL(blob); const link = document.createElement('link'); link.rel = 'stylesheet'; link.href = url; + link.id = el.id; + link.media = el.media; + link.title = el.title; const promise = new Promise((res) => { link.onload = res; }); diff --git a/tests/unit/transform.test.ts b/tests/unit/transform.test.ts index d6afc725..735e2f31 100644 --- a/tests/unit/transform.test.ts +++ b/tests/unit/transform.test.ts @@ -49,4 +49,24 @@ describe('transformCSS', () => { expect(div.hasAttribute('data-has-inline-styles')).toBeFalsy(); expect(div2.hasAttribute('data-has-inline-styles')).toBeFalsy(); }); + + it('preserves id, media, and title attributes when replacing link elements', async () => { + document.head.innerHTML = ` + + `; + let link = document.querySelector('link') as HTMLLinkElement; + const styleData = [ + { el: link, css: 'html { margin: 0; }', changed: true }, + ]; + const inlineStyles = new Map(); + const promise = transformCSS(styleData, inlineStyles, true); + link = document.querySelector('link') as HTMLLinkElement; + link.dispatchEvent(new Event('load')); + await promise; + + expect(link.href).toContain('/updated.css'); + expect(link.id).toBe('the-link'); + expect(link.media).toBe('screen'); + expect(link.title).toBe('stylish'); + }); }); From c167df489c7e7c0957b2b06f95409808ac0972f6 Mon Sep 17 00:00:00 2001 From: Derek Gray Date: Fri, 13 Sep 2024 08:33:49 -0500 Subject: [PATCH 2/2] format cleanup to appease prettier --check --- tests/unit/transform.test.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/tests/unit/transform.test.ts b/tests/unit/transform.test.ts index 735e2f31..ea43ba32 100644 --- a/tests/unit/transform.test.ts +++ b/tests/unit/transform.test.ts @@ -55,9 +55,7 @@ describe('transformCSS', () => { `; let link = document.querySelector('link') as HTMLLinkElement; - const styleData = [ - { el: link, css: 'html { margin: 0; }', changed: true }, - ]; + const styleData = [{ el: link, css: 'html { margin: 0; }', changed: true }]; const inlineStyles = new Map(); const promise = transformCSS(styleData, inlineStyles, true); link = document.querySelector('link') as HTMLLinkElement;