summaryrefslogtreecommitdiff
path: root/deps/npm/node_modules/update-notifier/node_modules/boxen/node_modules/ansi-align/index.js
blob: 16a98fc38f0cbf415a74f811b77eef369a0ed2a1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
'use strict'

var stringWidth = require('string-width')

function ansiAlign (text, opts) {
  if (!text) return text

  opts = opts || {}
  var align = opts.align || 'center'

  // short-circuit `align: 'left'` as no-op
  if (align === 'left') return text

  var split = opts.split || '\n'
  var pad = opts.pad || ' '
  var widthDiffFn = align !== 'right' ? halfDiff : fullDiff

  var returnString = false
  if (!Array.isArray(text)) {
    returnString = true
    text = String(text).split(split)
  }

  var width
  var maxWidth = 0
  text = text.map(function (str) {
    str = String(str)
    width = stringWidth(str)
    maxWidth = Math.max(width, maxWidth)
    return {
      str: str,
      width: width
    }
  }).map(function (obj) {
    return new Array(widthDiffFn(maxWidth, obj.width) + 1).join(pad) + obj.str
  })

  return returnString ? text.join(split) : text
}

ansiAlign.left = function left (text) {
  return ansiAlign(text, { align: 'left' })
}

ansiAlign.center = function center (text) {
  return ansiAlign(text, { align: 'center' })
}

ansiAlign.right = function right (text) {
  return ansiAlign(text, { align: 'right' })
}

module.exports = ansiAlign

function halfDiff (maxWidth, curWidth) {
  return Math.floor((maxWidth - curWidth) / 2)
}

function fullDiff (maxWidth, curWidth) {
  return maxWidth - curWidth
}