Skip to content

Commit

Permalink
Use injectStyles
Browse files Browse the repository at this point in the history
  • Loading branch information
lahmatiy committed Feb 17, 2021
1 parent f6bbc4e commit 70479d5
Showing 1 changed file with 2 additions and 63 deletions.
65 changes: 2 additions & 63 deletions src/widget/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import Publisher from '../core/publisher.js';
import * as views from '../views/index.js';
import * as pages from '../pages/index.js';
import { createElement } from '../core/utils/dom.js';
import injectStyles from '../core/utils/inject-styles.js';
import attachViewInspector from '../inspector/index.js';
import { equal, fuzzyStringCompare } from '../core/utils/compare.js';
import { DarkModeController } from '../core/darkmode.js';
Expand Down Expand Up @@ -479,72 +480,10 @@ export default class Widget extends Emitter {
initDom() {
const wrapper = createElement('div', 'discovery');
const shadow = wrapper.attachShadow({ mode: 'open' });
let readyStyles = Promise.resolve();
const readyStyles = injectStyles(shadow, this.options.styles);

wrapper.style.opacity = 0; // FIXME: there must be a better way to hide a widget until everything is ready

if (Array.isArray(this.options.styles)) {
const foucFix = createElement('style', null, ':host{display:none}');
const awaitingStyles = new Set();

shadow.append(...this.options.styles.map(style => {
if (typeof style === 'string') {
style = {
type: 'style',
content: style
};
}

switch (style.type) {
case 'style':
return createElement('style', null, style.content);

case 'link': {
let resolveStyle;
let rejectStyle;
let state = new Promise((resolve, reject) => {
resolveStyle = resolve;
rejectStyle = reject;
});

awaitingStyles.add(state);

const linkEl = createElement('link', {
rel: 'stylesheet',
href: style.href,
media: style.media,
onerror(err) {
awaitingStyles.delete(state);
rejectStyle(err);

if (!awaitingStyles.size) {
foucFix.remove();
}
},
onload() {
awaitingStyles.delete(state);
resolveStyle();

if (!awaitingStyles.size) {
foucFix.remove();
}
}
});

return linkEl;
}

default:
throw new Error(`Unknown type "${style.type}" in options.styles`);
}
}));

if (awaitingStyles.size) {
readyStyles = Promise.all(awaitingStyles);
shadow.append(foucFix);
}
}

const container = shadow.appendChild(createElement('div'));
this.dom = {};
this.dom.ready = Promise.all([readyStyles]);
Expand Down

0 comments on commit 70479d5

Please sign in to comment.