All files / src/styles global-style-engine.ts

77.08% Statements 37/48
70% Branches 14/20
75% Functions 6/8
76.74% Lines 33/43
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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87        1x 2x   2x       2x   2x 1x   1x 1x   1x       1x 3x       3x   3x           3x     3x     1x                           1x 3x 6x   6x 6x   6x     3x   5x 5x 2x     6x 6x 6x     5x 2x       3x   1x  
import { getLogger } from 'aurelia-logging';
import { DOM } from 'aurelia-pal';
import { GlobalStyle } from './global-style';
 
export class GlobalStyleEngine {
  private logger = getLogger('aurelia-ux');
 
  private globalStyles: GlobalStyle[] = [];
  private styleTag: HTMLStyleElement;
 
  constructor() {
    this.styleTag = DOM.querySelector('#aurelia-ux-core') as HTMLStyleElement;
 
    if (this.styleTag == null) {
      this.styleTag = DOM.createElement('style') as HTMLStyleElement;
 
      this.styleTag.type = 'text/css';
      this.styleTag.id = 'aurelia-ux-core';
 
      DOM.appendNode(this.styleTag, document.head);
    }
  }
 
  public addOrUpdateGlobalStyle(id: string, css: string, tagGroup?: string) {
    Iif (id === undefined || css === undefined) {
      this.logger.warn('AddOrUpdateGlobalStyle: The parameters id and css must both be provided.', { id, css });
    }
 
    const index = this.globalStyles.findIndex(t => t.id === id);
 
    Iif (index > -1) {
      const globalStyle = this.globalStyles[index];
 
      globalStyle.css = css;
      globalStyle.tagGroup = tagGroup;
    } else {
      this.globalStyles.push({ id, css, tagGroup });
    }
 
    this.updateGlobalStyleElement();
  }
 
  public removeGlobalStyle(id: string) {
    if (id === undefined) {
      this.logger.warn('removeGlobalStyle: The id parameter must be provided.', { id });
    }
 
    const index = this.globalStyles.findIndex(t => t.id === id);
 
    if (index > -1) {
      this.globalStyles.splice(index, 1);
    }
 
    this.updateGlobalStyleElement();
  }
 
  private updateGlobalStyleElement() {
    const globalStyleGroups = this.globalStyles.reduce((groups: any, globalStyle: GlobalStyle) => {
      const tagGroup = globalStyle['tagGroup'] || '';
 
      groups[tagGroup] = groups[tagGroup] || [];
      groups[tagGroup].push(globalStyle);
 
      return groups;
    }, {});
 
    let innerHtml = '';
 
    for (const key of Object.keys(globalStyleGroups)) {
      if (key !== '') {
        innerHtml += `${key} {\r\n`;
      }
 
      for (const globalStyle of globalStyleGroups[key]) {
        innerHtml += `/*** ${globalStyle.id} styles ***/\r\n`;
        innerHtml += `${globalStyle.css}\r\n\r\n`;
      }
 
      if (key !== '') {
        innerHtml += '}';
      }
    }
 
    this.styleTag.innerHTML = innerHtml;
  }
}