« get me outta code hell

Flushable.js - tui-lib - Pure Node.js library for making visual command-line programs (ala vim, ncdu)
about summary refs log tree commit diff
path: root/Flushable.js
blob: 0e73b6d15978fb133da64abd4104464dc904db6f (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
const ansi = require('./ansi')

module.exports = class Flushable {
  // A writable that can be used to collect chunks of data before writing
  // them.

  constructor(writable, shouldCompress = false) {
    this.target = writable

    // Use the magical ANSI self-made compression method that probably
    // doesn't *quite* work but should drastically decrease write size?
    this.shouldCompress = shouldCompress

    // Update these if you plan on using the ANSI compressor!
    this.screenLines = 24
    this.screenCols = 80

    this.ended = false

    this.chunks = []
  }

  write(what) {
    this.chunks.push(what)
  }

  flush() {
    // Don't write if we've ended.
    if (this.ended) {
      return
    }

    // End if the target is destroyed.
    // Yes, this relies on the target having a destroyed property
    // Don't worry, it'll still work if there is no destroyed property though
    // (I think)
    if (this.target.destroyed) {
      this.end()
      return
    }

    let toWrite = this.chunks.join('')

    if (this.shouldCompress) {
      toWrite = this.compress(toWrite)
    }

    try {
      this.target.write(toWrite)
    } catch(err) {
      console.error('Flushable write error (ending):', err.message)
      this.end()
    }

    this.chunks = []
  }

  end() {
    this.ended = true
  }

  compress(toWrite) {
    // TODO: customize screen size
    const screen = ansi.interpret(toWrite, this.screenLines, this.screenCols)

    /*
    const pcSaved = Math.round(100 - (100 / toWrite.length * screen.length))
    console.log(
      '\x1b[1A' +
      `${toWrite.length} - ${screen.length} ${pcSaved}% saved   `
    )
    */

    return screen
  }
}