Skip to content

Commit

Permalink
fix: js runtime explode in edge case with involving multiple builds (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
barak007 authored Jul 20, 2022
1 parent e4d0a25 commit 44524d4
Showing 1 changed file with 13 additions and 13 deletions.
26 changes: 13 additions & 13 deletions packages/runtime/src/inject-styles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,45 +2,45 @@
import type { Host } from './types';

export function injectStyles(host: Host) {
function stylableRuntime(
namespace: string,
css: string,
depth: number,
runtimeId: string
): void {
function stylableRuntime(id: string, css: string, depth: number, runtimeId: string): void {
if (typeof document === 'undefined') {
return;
}
var d = document;
var head = d.head;
var style = d.createElement('style');
style.setAttribute('st_id', namespace);
style.setAttribute('st_id', id);
style.setAttribute('st_depth', depth as unknown as string);
style.setAttribute('st_runtime', runtimeId);
style.textContent = css;
var loadedStyleElements = head.querySelectorAll<HTMLStyleElement>(
'style[st_runtime="' + runtimeId + '"]'
);
var inserted = false;
var insertAfter: HTMLElement | undefined;
for (var i = 0; i < loadedStyleElements.length; i++) {
var styleElement = loadedStyleElements[i];
var stId = styleElement.getAttribute('st_id');
var stDepth = Number(styleElement.getAttribute('st_depth'));
if (stId === namespace) {
if (stDepth === depth) {
var existingStId = styleElement.getAttribute('st_id');
var existingStDepth = Number(styleElement.getAttribute('st_depth'));
if (existingStId === id) {
if (existingStDepth === depth) {
head.replaceChild(style, styleElement);
return;
} else {
styleElement.parentElement!.removeChild(styleElement);
continue;
}
}
if (!inserted && depth < stDepth) {
if (!inserted && depth < existingStDepth) {
head.insertBefore(style, styleElement);
inserted = true;
}
insertAfter = styleElement;
}
if (!inserted) {
head.append(style);
insertAfter
? head.insertBefore(style, insertAfter.nextElementSibling)
: head.appendChild(style);
}
}
host.sti = stylableRuntime;
Expand Down

0 comments on commit 44524d4

Please sign in to comment.