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