Commit 1ccf10d4 authored by Eduardo Sanz García's avatar Eduardo Sanz García Committed by Eduardo

Find annotation.css in a more robust way

As indicated by @robertknight `document.styleSheets` is complete only when stylessheets are processed. This can take a while for certain heavy pages.

The alternative approach presented here to find `annotation.css` is warranted to find the url when the code is run.

Closes #2752
parent 91f36486
...@@ -2,9 +2,13 @@ ...@@ -2,9 +2,13 @@
* Load stylesheets for annotator UI components into the shadow DOM root. * Load stylesheets for annotator UI components into the shadow DOM root.
*/ */
function loadStyles(shadowRoot) { function loadStyles(shadowRoot) {
const adderStyles = Array.from(document.styleSheets) const url = /** @type {HTMLLinkElement|undefined} */ (document.querySelector(
.map(sheet => sheet.href) 'link[rel="stylesheet"][href*="/build/styles/annotator.css"]'
.filter(url => (url || '').match(/annotator\.css/)); ))?.href;
if (!url) {
return;
}
// Stylesheet <link> elements are inert inside shadow roots [1]. Until // Stylesheet <link> elements are inert inside shadow roots [1]. Until
// Shadow DOM implementations support external stylesheets [2], grab the // Shadow DOM implementations support external stylesheets [2], grab the
...@@ -18,7 +22,7 @@ function loadStyles(shadowRoot) { ...@@ -18,7 +22,7 @@ function loadStyles(shadowRoot) {
// get a usable adder, albeit one that uses browser default styles for the // get a usable adder, albeit one that uses browser default styles for the
// toolbar. // toolbar.
const styleEl = document.createElement('style'); const styleEl = document.createElement('style');
styleEl.textContent = adderStyles.map(url => `@import "${url}";`).join('\n'); styleEl.textContent = `@import "${url}";`;
shadowRoot.appendChild(styleEl); shadowRoot.appendChild(styleEl);
} }
......
...@@ -29,5 +29,21 @@ describe('annotator/util/shadow-root', () => { ...@@ -29,5 +29,21 @@ describe('annotator/util/shadow-root', () => {
assert.ok(styleEl); assert.ok(styleEl);
assert.match(styleEl.textContent, /@import ".*annotator\.css.*"/); assert.match(styleEl.textContent, /@import ".*annotator\.css.*"/);
}); });
it('does not inject stylesheets into the shadow root if style is not found', () => {
const container = document.createElement('div');
const link = document.querySelector(
'link[rel="stylesheet"][href*="/build/styles/annotator.css"]'
);
// Removing the `rel` attribute is enough for the URL to not be found
link.removeAttribute('rel');
createShadowRoot(container);
const styleEl = container.shadowRoot.querySelector('style');
assert.isNull(styleEl);
link.setAttribute('rel', 'stylesheet');
});
}); });
}); });
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment