All files / src index.js

100% Statements 28/28
100% Branches 14/14
100% Functions 13/13
100% Lines 27/27

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 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        7x     7x 7x     7x 9x     7x         3x 2x   1x   3x       24x       2x       2x       14x 14x     14x 2x       12x   2x   2x   2x   6x         12x       3x       1x       3x       2x      
import objectGet from 'object-get'
 
export default class DesignSystem {
  constructor(system, options) {
    const defaultOptions = {
      fontSizeUnit: undefined,
    }
    this.options = Object.assign({}, defaultOptions, options)
    this.ds = system
 
    // Converts px to rem/em
    this.pxTo = (value, base = 20, unit = 'rem') =>
      `${parseFloat(value) / base}${unit}`
 
    // Converts rem/em to px
    this.toPx = (value, base = 20) => `${parseFloat(value) * base}px`
  }
 
  multiply(initial, multiplier) {
    let initialVal
    if (typeof initial === 'string') {
      initialVal = parseFloat(this.get(initial))
    } else {
      initialVal = initial
    }
    return initialVal * multiplier
  }
 
  get(value, obj = this.ds) {
    return objectGet(obj, value)
  }
 
  bp(bp) {
    return this.get(bp, this.ds.breakpoints)
  }
 
  z(z) {
    return this.get(z, this.ds.zIndex)
  }
 
  fontSize(size) {
    const output = `${this.get(size, this.ds.type.sizes)}`
    const baseFontSize = parseFloat(this.ds.type.baseFontSize)
 
    // Don't convert the value if we don't have to
    if (output.indexOf(this.options.fontSizeUnit) !== -1) {
      return output
    }
 
    // Convert font-size to the specified unit
    switch (this.options.fontSizeUnit) {
      case 'rem':
        return this.pxTo(output, baseFontSize, 'rem')
      case 'em':
        return this.pxTo(output, baseFontSize, 'em')
      case 'px':
        return this.toPx(output, baseFontSize)
      default:
        return output
    }
  }
 
  fs(size) {
    return this.fontSize(size)
  }
 
  spacing(index = 0) {
    return `${this.ds.spacing.scale[index]}px`
  }
 
  space(index) {
    return this.spacing(index)
  }
 
  color(hue, value = 'base') {
    return this.ds.colors.colorPalette[hue][value]
  }
 
  brand(color) {
    return this.get(color, this.ds.colors.brand)
  }
}