All files / packages/design-system-2/.storybook/decorators apply-main-stylesheet.ts

100% Statements 13/13
100% Branches 6/6
100% Functions 3/3
100% Lines 13/13

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 372x                                       11x 11x 11x 11x 6x   6x 6x 6x     11x 3x   8x 6x  
export const MAIN_STYLESHEET = {
  ID: 'slds-main-stylesheet',
  DEFAULT_HREF: '/css/slds2.base.css',
  THEME_LAYER_HREF: '/theme-layer/slds2.theme-layer.base.css',
} as const;
 
/**
 * Ensures a <link> element for the main stylesheet exists in <head>.
 * Swaps the href when toggling between default and theme-layer mode.
 * Returns a promise that resolves once the stylesheet has loaded.
 *
 * @param {boolean} useThemeLayer Whether to load the theme-layer base stylesheet.
 * @returns {Promise<void>}
 */
export function applyMainStylesheet(useThemeLayer: boolean): Promise<void> {
  const { ID, DEFAULT_HREF, THEME_LAYER_HREF } = MAIN_STYLESHEET;
  const href = useThemeLayer ? THEME_LAYER_HREF : DEFAULT_HREF;
  let link = document.getElementById(ID) as HTMLLinkElement | null;
 
  if (!link) {
    link = document.createElement('link');
    link.id = ID;
    link.rel = 'stylesheet';
    document.head.appendChild(link);
  }
 
  if (link.getAttribute('href') === href) {
    return Promise.resolve();
  }
 
  return new Promise((resolve) => {
    link.onload = () => resolve();
    link.onerror = () => resolve();
    link.setAttribute('href', href);
  });
}