From 44524d410c89dabe9af3c4a553ae9565becc85d5 Mon Sep 17 00:00:00 2001 From: barak igal Date: Wed, 20 Jul 2022 09:55:43 +0300 Subject: [PATCH] fix: js runtime explode in edge case with involving multiple builds (#2620) --- packages/runtime/src/inject-styles.ts | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/packages/runtime/src/inject-styles.ts b/packages/runtime/src/inject-styles.ts index d5a1e00f3..7b18ff5c6 100644 --- a/packages/runtime/src/inject-styles.ts +++ b/packages/runtime/src/inject-styles.ts @@ -2,19 +2,14 @@ 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; @@ -22,25 +17,30 @@ export function injectStyles(host: Host) { '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;