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