All files / packages/design-system-2/.storybook/decorators apply-theme-stylesheets.js

0% Statements 0/20
0% Branches 0/6
0% Functions 0/3
0% Lines 0/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43                                                                                     
const LINK_CLASS = 'slds-theme-link';
 
/**
 * Loads an array of theme CSS paths as <link> elements in <head>.
 * Removes any previously managed theme links that are no longer needed.
 * Returns a promise that resolves once every new stylesheet has loaded.
 *
 * @param {string[]} hrefs CSS paths to load (served from Storybook staticDirs).
 * @returns {Promise<void>}
 */
export function applyThemeStylesheets(hrefs) {
  const existing = document.querySelectorAll(`link.${LINK_CLASS}`);
  const currentHrefs = new Set(Array.from(existing).map((l) => l.getAttribute('href')));
  const desiredHrefs = new Set(hrefs);
 
  // Remove links that are no longer needed.
  for (const link of existing) {
    if (!desiredHrefs.has(link.getAttribute('href'))) {
      link.remove();
    }
  }
 
  // Add missing links and collect load promises for new ones.
  const loadPromises = [];
  for (const href of hrefs) {
    if (!currentHrefs.has(href)) {
      const link = document.createElement('link');
      link.rel = 'stylesheet';
      link.className = LINK_CLASS;
      link.setAttribute('href', href);
      loadPromises.push(
        new Promise((resolve) => {
          link.onload = resolve;
          link.onerror = resolve;
        }),
      );
      document.head.appendChild(link);
    }
  }
 
  return loadPromises.length > 0 ? Promise.all(loadPromises) : Promise.resolve();
}