template-item.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. 'use strict'
  2. var stringWidth = require('string-width')
  3. module.exports = TemplateItem
  4. function isPercent (num) {
  5. if (typeof num !== 'string') {
  6. return false
  7. }
  8. return num.slice(-1) === '%'
  9. }
  10. function percent (num) {
  11. return Number(num.slice(0, -1)) / 100
  12. }
  13. function TemplateItem (values, outputLength) {
  14. this.overallOutputLength = outputLength
  15. this.finished = false
  16. this.type = null
  17. this.value = null
  18. this.length = null
  19. this.maxLength = null
  20. this.minLength = null
  21. this.kerning = null
  22. this.align = 'left'
  23. this.padLeft = 0
  24. this.padRight = 0
  25. this.index = null
  26. this.first = null
  27. this.last = null
  28. if (typeof values === 'string') {
  29. this.value = values
  30. } else {
  31. for (var prop in values) {
  32. this[prop] = values[prop]
  33. }
  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. TemplateItem.prototype = {}
  48. TemplateItem.prototype.getBaseLength = function () {
  49. var length = this.length
  50. if (
  51. length == null &&
  52. typeof this.value === 'string' &&
  53. this.maxLength == null &&
  54. this.minLength == null
  55. ) {
  56. length = stringWidth(this.value)
  57. }
  58. return length
  59. }
  60. TemplateItem.prototype.getLength = function () {
  61. var length = this.getBaseLength()
  62. if (length == null) {
  63. return null
  64. }
  65. return length + this.padLeft + this.padRight
  66. }
  67. TemplateItem.prototype.getMaxLength = function () {
  68. if (this.maxLength == null) {
  69. return null
  70. }
  71. return this.maxLength + this.padLeft + this.padRight
  72. }
  73. TemplateItem.prototype.getMinLength = function () {
  74. if (this.minLength == null) {
  75. return null
  76. }
  77. return this.minLength + this.padLeft + this.padRight
  78. }