« get me outta code hell

ansi.js « util - tui-lib - Pure Node.js library for making visual command-line programs (ala vim, ncdu)
about summary refs log tree commit diff
path: root/util/ansi.js
blob: 0ee1bc14486455a1693eb0ab683f1feb04c50a17 (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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
const ESC = '\x1b'

const isDigit = char => '0123456789'.indexOf(char) >= 0

const ansi = {
  ESC,

  // Attributes
  A_RESET:    0,
  A_BRIGHT:   1,
  A_DIM:      2,
  A_INVERT:   7,
  C_BLACK:   30,
  C_RED:     31,
  C_GREEN:   32,
  C_YELLOW:  33,
  C_BLUE:    34,
  C_MAGENTA: 35,
  C_CYAN:    36,
  C_WHITE:   37,
  C_RESET:   39,

  clearScreen() {
    // Clears the screen, removing any characters displayed, and resets the
    // cursor position.

    return `${ESC}[2J`
  },

  moveCursorRaw(line, col) {
    // Moves the cursor to the given line and column on the screen.
    // Returns the pure ANSI code, with no modification to line or col.

    return `${ESC}[${line};${col}H`
  },

  moveCursor(line, col) {
    // Moves the cursor to the given line and column on the screen.
    // Note that since in JavaScript indexes start at 0, but in ANSI codes
    // the top left of the screen is (1, 1), this function adjusts the
    // arguments to act as if the top left of the screen is (0, 0).

    return `${ESC}[${line + 1};${col + 1}H`
  },

  cleanCursor() {
    // A combination of codes that generally cleans up the cursor.

    return ansi.resetAttributes() + ansi.showCursor()
  },

  hideCursor() {
    // Makes the cursor invisible.

    return `${ESC}[?25l`
  },

  showCursor() {
    // Makes the cursor visible.

    return `${ESC}[?25h`
  },

  resetAttributes() {
    // Resets all attributes, including text decorations, foreground and
    // background color.

    return `${ESC}[0m`
  },

  setAttributes(attrs) {
    // Set some raw attributes. See the attributes section of the ansi.js
    // source code for attributes that can be used with this; A_RESET resets
    // all attributes.

    return `${ESC}[${attrs.join(';')}m`
  },

  setForeground(color) {
    // Sets the foreground color to print text with. See C_(COLOR) for colors
    // that can be used with this; C_RESET resets the foreground.
    //
    // If null or undefined is passed, this function will return a blank
    // string (no ANSI escape codes).

    if (typeof color === 'undefined' || color === null) {
      return ''
    }

    return ansi.setAttributes([color])
  },

  invert() {
    // Inverts the foreground and background colors.

    return `${ESC}[7m`
  },

  requestCursorPosition() {
    // Requests the position of the cursor.
    // Expect a stdin-result '\ESC[l;cR', where l is the line number (1-based),
    // c is the column number (also 1-based), and R is the literal character
    // 'R' (decimal code 82).

    return `${ESC}[6n`
  },

  isANSICommand(buffer, code = null) {
    return (
      buffer[0] === 0x1b && buffer[1] === 0x5b &&
      (code ? buffer[buffer.length - 1] === code : true)
    )
  },


  interpret(text, scrRows, scrCols) {
    // Interprets the given ansi code, more or less.

    const blank = {
      attributes: [],
      char: ' '
    }

    const chars = new Array(scrRows * scrCols).fill(blank)

    let cursorRow = 1
    let cursorCol = 1
    const attributes = []
    const getCursorIndex = () => (cursorRow - 1) * scrCols + (cursorCol - 1)

    for (let charI = 0; charI < text.length; charI++) {
      if (text[charI] === ESC) {
        charI++

        if (text[charI] !== '[') {
          throw new Error('ESC not followed by [')
        }

        charI++

        const args = []
        let val = ''
        while (isDigit(text[charI])) {
          val += text[charI]
          charI++

          if (text[charI] === ';') {
            charI++
            args.push(val)
            val = ''
            continue
          }
        }
        args.push(val)

        // CUP - Cursor Position (moveCursor)
        if (text[charI] === 'H') {
          cursorRow = args[0]
          cursorCol = args[1]
        }

        // ED - Erase Display (clearScreen)
        if (text[charI] === 'J') {
          // ESC[2J - erase whole display
          if (args[0] === '2') {
            chars.fill(blank)
            charI += 3
            cursorCol = 1
            cursorRow = 1
          }

          // ESC[1J - erase to beginning
          else if (args[0] === '1') {
            for (let i = 0; i < getCursorIndex(); i++) {
              chars[i] = blank
            }
          }

          // ESC[0J - erase to end
          else if (args.length === 0 || args[0] === '0') {
            for (let i = getCursorIndex(); i < chars.length; i++) {
              chars[i] = blank
            }
          }
        }

        // SGR - Select Graphic Rendition
        if (text[charI] === 'm') {
          for (let arg of args) {
            if (arg === '0') {
              attributes.splice(0, attributes.length)
            } else {
              attributes.push(arg)
            }
          }
        }

        continue
      }

      // debug
      /*
      if (text[charI] === '.') {
        console.log(
          `#1-char "${text[charI]}" at ` +
          `(${cursorRow},${cursorCol}):${getCursorIndex()} ` +
          ` attr:[${attributes.join(';')}]`
        )
      }
      */

      chars[getCursorIndex()] = {
        char: text[charI],
        attributes: attributes.slice()
      }

      cursorCol++

      if (cursorCol > scrCols) {
        cursorCol = 1
        cursorRow++
      }
    }

    // Character concatenation -----------

    // Move to the top left of the screen initially.
    const result = [ ansi.moveCursorRaw(1, 1) ]

    let lastChar = {
      char: '',
      attributes: []
    }

    //let n = 1 // debug

    for (let char of chars) {
      const newAttributes = (
        char.attributes.filter(attr => !(lastChar.attributes.includes(attr)))
      )

      const removedAttributes = (
        lastChar.attributes.filter(attr => !(char.attributes.includes(attr)))
      )

      // The only way to practically remove any character attribute is to
      // reset all of its attributes and then re-add its existing attributes.
      // If we do that, there's no need to add new attributes.
      if (removedAttributes.length) {
        // console.log(
        //   `removed some attributes "${char.char}"`, removedAttributes
        // )
        result.push(ansi.resetAttributes())
        result.push(`${ESC}[${char.attributes.join(';')}m`)
      } else if (newAttributes.length) {
        result.push(`${ESC}[${newAttributes.join(';')}m`)
      }

      // debug
      /*
      if (char.char !== ' ') {
        console.log(
          `#2-char ${char.char}; ${chars.indexOf(char) - n} inbetween`
        )
        n = chars.indexOf(char)
      }
      */

      result.push(char.char)

      lastChar = char
    }

    return result.join('')
  }
}

module.exports = ansi