Initial commit
[yaffs-website] / node_modules / gauge / template-item.js
1 'use strict'
2 var stringWidth = require('string-width')
3
4 module.exports = TemplateItem
5
6 function isPercent (num) {
7   if (typeof num !== 'string') return false
8   return num.slice(-1) === '%'
9 }
10
11 function percent (num) {
12   return Number(num.slice(0, -1)) / 100
13 }
14
15 function TemplateItem (values, outputLength) {
16   this.overallOutputLength = outputLength
17   this.finished = false
18   this.type = null
19   this.value = null
20   this.length = null
21   this.maxLength = null
22   this.minLength = null
23   this.kerning = null
24   this.align = 'left'
25   this.padLeft = 0
26   this.padRight = 0
27   this.index = null
28   this.first = null
29   this.last = null
30   if (typeof values === 'string') {
31     this.value = values
32   } else {
33     for (var prop in values) this[prop] = values[prop]
34   }
35   // Realize percents
36   if (isPercent(this.length)) {
37     this.length = Math.round(this.overallOutputLength * percent(this.length))
38   }
39   if (isPercent(this.minLength)) {
40     this.minLength = Math.round(this.overallOutputLength * percent(this.minLength))
41   }
42   if (isPercent(this.maxLength)) {
43     this.maxLength = Math.round(this.overallOutputLength * percent(this.maxLength))
44   }
45   return this
46 }
47
48 TemplateItem.prototype = {}
49
50 TemplateItem.prototype.getBaseLength = function () {
51   var length = this.length
52   if (length == null && typeof this.value === 'string' && this.maxLength == null && this.minLength == null) {
53     length = stringWidth(this.value)
54   }
55   return length
56 }
57
58 TemplateItem.prototype.getLength = function () {
59   var length = this.getBaseLength()
60   if (length == null) return null
61   return length + this.padLeft + this.padRight
62 }
63
64 TemplateItem.prototype.getMaxLength = function () {
65   if (this.maxLength == null) return null
66   return this.maxLength + this.padLeft + this.padRight
67 }
68
69 TemplateItem.prototype.getMinLength = function () {
70   if (this.minLength == null) return null
71   return this.minLength + this.padLeft + this.padRight
72 }
73