« 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: ac511eda872be9d5c374aea3da6185e2d7914a3f (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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
const wcwidth = require('wcwidth')

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.stopTrackingMouse() +
      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])
  },

  setBackground(color) {
    // Sets the background color to print text with. Accepts the same arguments
    // as setForeground (C_(COLOR), C_RESET, etc).
    //
    // Note that attributes such as A_BRIGHT and A_DIM apply apply to only the
    // foreground, not the background. To set a bright or dim background, you
    // can set the appropriate color as the foreground and then invert.

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

    return ansi.setAttributes([color + 10])
  },

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

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

  invertOff() {
    // Un-inverts the foreground and backgrund colors.

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

  startTrackingMouse() {
    return `${ESC}[?1002h`
  },

  stopTrackingMouse() {
    return `${ESC}[?1002l`
  },

  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`
  },

  enableAlternateScreen() {
    // Enables alternate screen:
    // "Xterm maintains two screen buffers.  The normal screen buffer allows
    // you to scroll back to view saved lines of output up to the maximum set
    // by the saveLines resource.  The alternate screen buffer is exactly as
    // large as the display, contains no additional saved lines."

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

  disableAlternateScreen() {
    return `${ESC}[?1049l`
  },

  measureColumns(text) {
    // Returns the number of columns the given text takes.

    return wcwidth(text)
  },

  trimToColumns(text, cols) {
    // Trims off the end of the passed text so that its width doesn't exceed
    // the size passed in columns.

    let out = ''
    for (const char of text) {
      if (ansi.measureColumns(out + char) <= cols) {
        out += char
      } else {
        break
      }
    }
    return out
  },

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

  interpret(text, scrRows, scrCols, {
    oldChars = null, oldLastChar = null,
    oldScrRows = null, oldScrCols = null,
    oldCursorRow = 1, oldCursorCol = 1, oldShowCursor = true
  } = {}) {
    // Interprets the given ansi code, more or less.

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

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

    if (oldChars) {
      for (let row = 0; row < scrRows && row < oldScrRows; row++) {
        for (let col = 0; col < scrCols && col < oldScrCols; col++) {
          chars[row * scrCols + col] = oldChars[row * oldScrCols + col]
        }
      }
    }

    let showCursor = oldShowCursor
    let cursorRow = oldCursorRow
    let cursorCol = oldCursorCol
    let attributes = []

    for (let charI = 0; charI < text.length; charI++) {
      const cursorIndex = (cursorRow - 1) * scrCols + (cursorCol - 1)

      if (text[charI] === ESC) {
        charI++

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

        charI++

        // Selective control sequences (look them up) - we can just skip the
        // question mark.
        if (text[charI] === '?') {
          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 = parseInt(args[0])
          cursorCol = parseInt(args[1])
        }

        // SM - Set Mode
        if (text[charI] === 'h') {
          if (args[0] === '25') {
            showCursor = true
          }
        }

        // 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 < cursorIndex; i++) {
              chars[i * 2] = ' '
              chars[i * 2 + 1] = []
            }
          }

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

        // RM - Reset Mode
        if (text[charI] === 'l') {
          if (args[0] === '25') {
            showCursor = false
          }
        }

        // SGR - Select Graphic Rendition
        if (text[charI] === 'm') {
          const removeAttribute = attr => {
            if (attributes.includes(attr)) {
              attributes = attributes.slice()
              attributes.splice(attributes.indexOf(attr), 1)
            }
          }

          for (const arg of args) {
            if (arg === '0') {
              attributes = []
            } else if (arg === '22') { // Neither bold nor faint
              removeAttribute('1')
              removeAttribute('2')
            } else if (arg === '23') { // Neither italic nor Fraktur
              removeAttribute('3')
              removeAttribute('20')
            } else if (arg === '24') { // Not underlined
              removeAttribute('4')
            } else if (arg === '25') { // Blink off
              removeAttribute('5')
            } else if (arg === '27') { // Inverse off
              removeAttribute('7')
            } else if (arg === '28') { // Conceal off
              removeAttribute('8')
            } else if (arg === '29') { // Not crossed out
              removeAttribute('9')
            } else if (arg === '39') { // Default foreground
              for (let i = 0; i < 10; i++) {
                removeAttribute('3' + i)
              }
            } else if (arg === '49') { // Default background
              for (let i = 0; i < 10; i++) {
                removeAttribute('4' + i)
              }
            } else {
              attributes = attributes.concat([arg])
            }
          }
        }

        continue
      }

      chars[cursorIndex] = {
        char: text[charI], attributes
      }

      // Some characters take up multiple columns, e.g. Japanese text. Take
      // this into consideration when drawing.
      const charColumns = wcwidth(text[charI])
      cursorCol += charColumns

      // If the character takes up 2+ columns, treat columns past the first
      // one (where the character is) as empty. (Note this is different from
      // "blank", which represents an empty space character ' '.)
      for (let i = 1; i < charColumns; i++) {
        chars[cursorIndex + i] = {char: '', attributes: []}
      }

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

    // SPOooooOOoky diffing! -------------
    //
    // - Search for series of differences. This means a collection of characters
    //   which have different text or attribute properties.
    //
    // - Figure out how to print these differences. Move the cursor to the beginning
    //   character's row/column, then print the differences.

    const newChars = chars

    const differences = []

    if (oldChars === null) {
      differences.push(0)
      differences.push(newChars.slice())
    } else {
      const charsEqual = (oldChar, newChar) => {
        if (oldChar.char !== newChar.char) {
          return false
        }

        let oldAttrs = oldChar.attributes.slice()
        let newAttrs = newChar.attributes.slice()

        while (newAttrs.length) {
          const attr = newAttrs.shift()
          if (oldAttrs.includes(attr)) {
            oldAttrs.splice(oldAttrs.indexOf(attr), 1)
          } else {
            return false
          }
        }

        oldAttrs = oldChar.attributes.slice()
        newAttrs = newChar.attributes.slice()

        while (oldAttrs.length) {
          const attr = oldAttrs.shift()
          if (newAttrs.includes(attr)) {
            newAttrs.splice(newAttrs.indexOf(attr), 1)
          } else {
            return false
          }
        }

        return true
      }

      let curChars = null

      for (let i = 0; i < chars.length; i++) {
        const oldChar = oldChars[i]
        const newChar = newChars[i]

        // TODO: Some sort of "distance" before we should clear curDiff?
        // It may take *less* characters if this diff and the next are merged
        // (entering a single character is smaller than the length of the code
        // used to move past that character). Probably not very significant of
        // an impact, though.
        if (charsEqual(oldChar, newChar)) {
          curChars = null
        } else {
          if (curChars === null) {
            curChars = []
            differences.push(i, curChars)
          }

          curChars.push(newChar)
        }
      }
    }

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

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

    const result = []

    for (let parse = 0; parse < differences.length; parse += 2) {
      const i = differences[parse]
      const chars = differences[parse + 1]

      const col = i % scrCols
      const row = (i - col) / scrCols
      result.push(ansi.moveCursor(row, col))

      for (const 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) {
          result.push(ansi.resetAttributes())
          result.push(`${ESC}[${char.attributes.join(';')}m`)
        } else if (newAttributes.length) {
          result.push(`${ESC}[${newAttributes.join(';')}m`)
        }

        result.push(char.char)

        lastChar = char
      }
    }

    // If anything changed *or* the cursor moved, we need to put it back where
    // it was before:
    if (result.length || cursorCol !== oldCursorCol || cursorRow !== oldCursorRow) {
      result.push(ansi.moveCursor(cursorRow, cursorCol))
    }

    // If the cursor is visible and wasn't before, or vice versa, we need to
    // show that:
    if (showCursor && !oldShowCursor) {
      result.push(ansi.showCursor())
    } else if (!showCursor && oldShowCursor) {
      result.push(ansi.hideCursor())
    }

    return {
      oldChars: newChars.slice(),
      oldLastChar: Object.assign({}, lastChar),
      oldScrRows: scrRows,
      oldScrCols: scrCols,
      oldCursorRow: cursorRow,
      oldCursorCol: cursorCol,
      oldShowCursor: showCursor,
      screen: result.join('')
    }
  }
}

module.exports = ansi