All files / src/designs design-processor.ts

29.41% Statements 10/34
0% Branches 0/10
22.22% Functions 2/9
24.14% Lines 7/29
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              1x 1x   1x                                               1x             1x                           1x                     1x            
import { inject } from 'aurelia-dependency-injection';
import { ObserverLocator } from 'aurelia-binding';
import { Design } from '../designs/design';
import { swatches } from '../colors/swatches';
import { GlobalStyleEngine } from '../styles/global-style-engine';
 
@inject(ObserverLocator, GlobalStyleEngine)
export class DesignProcessor {
  constructor(private observerLocator: ObserverLocator, private globalStyleEngine: GlobalStyleEngine) { }
 
  public setSwatchVariables() {
    let swatchClasses = '';
 
    for (const swatch in swatches) {
      if (swatches.hasOwnProperty(swatch)) {
        if (typeof swatches[swatch] === 'string') {
          swatchClasses += `  --ux-swatch--${kebabCase(swatch)}: ${swatches[swatch]};\r\n`;
          continue;
        }
 
        for (const key in swatches[swatch]) {
          if (swatches[swatch].hasOwnProperty(key)) {
            swatchClasses += `  --ux-swatch--${kebabCase(swatch)}-${kebabCase(key)}: ${swatches[swatch][key]};\r\n`;
          }
        }
      }
    }
 
    this.globalStyleEngine.addOrUpdateGlobalStyle(
      `aurelia-ux swatches`,
      swatchClasses,
      ':root');
  }
 
  public setDesignVariables(design: Design) {
    this.globalStyleEngine.addOrUpdateGlobalStyle(
      `aurelia-ux design styles`,
      this.buildInnerHTML(design),
      ':root');
  }
 
  public setDesignWatches(design: Design) {
    for (const key in design) {
      if (design.hasOwnProperty(key)) {
        this.observerLocator.getObserver(design, key)
          .subscribe(() => {
            this.globalStyleEngine.addOrUpdateGlobalStyle(
              `aurelia-ux design styles`,
              this.buildInnerHTML(design),
              ':root');
          });
      }
    }
  }
 
  private buildInnerHTML(design: Design) {
    let designInnerHtml = '';
 
    for (const key in design) {
      if (design.hasOwnProperty(key)) {
        designInnerHtml += `  --aurelia-ux--design-${kebabCase(key)}: ${(design as any)[key]};\r\n`;
      }
    }
 
    return designInnerHtml;
  }
}
 
function kebabCase(value: string) {
  value = value.charAt(0).toLowerCase() + value.slice(1);
  return value.replace(/([A-Z])/g, (match) => `-${match[0].toLowerCase()}`);
}