Skip to content

Commit

Permalink
🐛 do not ignore @import rules pointing to inaccessible stylesheets
Browse files Browse the repository at this point in the history
We follow @import rules and inline their content so the player can uses
its strategy to emulate :hover states. But if the external stylesheet is
inaccessible, we should still take the @import rule into account, so the
external stylesheet can be loaded in the player.
  • Loading branch information
BenoitZugmeyer committed Aug 29, 2023
1 parent ef8f6ca commit 98431dd
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { getCssRulesString } from './serializeAttributes'

describe('getCssRulesString', () => {
let styleNode: HTMLStyleElement

beforeEach(() => {
styleNode = document.createElement('style')
document.body.appendChild(styleNode)
})
afterEach(() => {
document.body.removeChild(styleNode)
})

it('returns the CSS rules as a string', () => {
styleNode.sheet!.insertRule('body { color: red; }')

expect(getCssRulesString(styleNode.sheet)).toBe('body { color: red; }')
})

it('inlines imported external stylesheets', () => {
styleNode.sheet!.insertRule('@import url("toto.css");')

// Simulates an accessible external stylesheet
spyOnProperty(styleNode.sheet!.cssRules[0] as CSSImportRule, 'styleSheet').and.returnValue({
cssRules: [{ cssText: 'p { margin: 0; }' } as CSSRule] as unknown as CSSRuleList,
} as CSSStyleSheet)

expect(getCssRulesString(styleNode.sheet)).toBe('p { margin: 0; }')
})

it('does not skip the @import rules if the external stylesheet is inaccessible', () => {
styleNode.sheet!.insertRule('@import url("toto.css");')

// Simulates an inaccessible external stylesheet
spyOnProperty(styleNode.sheet!.cssRules[0] as CSSImportRule, 'styleSheet').and.returnValue({
get cssRules(): CSSRuleList {
throw new Error('Cannot access rules')
},
} as CSSStyleSheet)

expect(getCssRulesString(styleNode.sheet)).toBe('@import url("toto.css");')
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ export function serializeAttributes(
return safeAttrs
}

function getCssRulesString(cssStyleSheet: CSSStyleSheet | undefined | null): string | null {
export function getCssRulesString(cssStyleSheet: CSSStyleSheet | undefined | null): string | null {
if (!cssStyleSheet) {
return null
}
Expand All @@ -144,7 +144,7 @@ function getCssRulesString(cssStyleSheet: CSSStyleSheet | undefined | null): str
}

function getCssRuleString(rule: CSSRule): string {
return isCSSImportRule(rule) ? getCssRulesString(rule.styleSheet) || '' : rule.cssText
return (isCSSImportRule(rule) && getCssRulesString(rule.styleSheet)) || rule.cssText
}

function isCSSImportRule(rule: CSSRule): rule is CSSImportRule {
Expand Down

0 comments on commit 98431dd

Please sign in to comment.