index.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. 'use strict'
  2. const stringWidth = require('string-width')
  3. function ansiAlign (text, opts) {
  4. if (!text) return text
  5. opts = opts || {}
  6. const align = opts.align || 'center'
  7. // short-circuit `align: 'left'` as no-op
  8. if (align === 'left') return text
  9. const split = opts.split || '\n'
  10. const pad = opts.pad || ' '
  11. const widthDiffFn = align !== 'right' ? halfDiff : fullDiff
  12. let returnString = false
  13. if (!Array.isArray(text)) {
  14. returnString = true
  15. text = String(text).split(split)
  16. }
  17. let width
  18. let maxWidth = 0
  19. text = text.map(function (str) {
  20. str = String(str)
  21. width = stringWidth(str)
  22. maxWidth = Math.max(width, maxWidth)
  23. return {
  24. str,
  25. width
  26. }
  27. }).map(function (obj) {
  28. return new Array(widthDiffFn(maxWidth, obj.width) + 1).join(pad) + obj.str
  29. })
  30. return returnString ? text.join(split) : text
  31. }
  32. ansiAlign.left = function left (text) {
  33. return ansiAlign(text, { align: 'left' })
  34. }
  35. ansiAlign.center = function center (text) {
  36. return ansiAlign(text, { align: 'center' })
  37. }
  38. ansiAlign.right = function right (text) {
  39. return ansiAlign(text, { align: 'right' })
  40. }
  41. module.exports = ansiAlign
  42. function halfDiff (maxWidth, curWidth) {
  43. return Math.floor((maxWidth - curWidth) / 2)
  44. }
  45. function fullDiff (maxWidth, curWidth) {
  46. return maxWidth - curWidth
  47. }