template-item.js 1.9 KB

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