3 const stringWidth = require('string-width')
5 function ansiAlign (text, opts) {
9 const align = opts.align || 'center'
11 // short-circuit `align: 'left'` as no-op
12 if (align === 'left') return text
14 const split = opts.split || '\n'
15 const pad = opts.pad || ' '
16 const widthDiffFn = align !== 'right' ? halfDiff : fullDiff
18 let returnString = false
19 if (!Array.isArray(text)) {
21 text = String(text).split(split)
26 text = text.map(function (str) {
28 width = stringWidth(str)
29 maxWidth = Math.max(width, maxWidth)
34 }).map(function (obj) {
35 return new Array(widthDiffFn(maxWidth, obj.width) + 1).join(pad) + obj.str
38 return returnString ? text.join(split) : text
41 ansiAlign.left = function left (text) {
42 return ansiAlign(text, { align: 'left' })
45 ansiAlign.center = function center (text) {
46 return ansiAlign(text, { align: 'center' })
49 ansiAlign.right = function right (text) {
50 return ansiAlign(text, { align: 'right' })
53 module.exports = ansiAlign
55 function halfDiff (maxWidth, curWidth) {
56 return Math.floor((maxWidth - curWidth) / 2)
59 function fullDiff (maxWidth, curWidth) {
60 return maxWidth - curWidth