diff options
author | liam4 <towerofnix@gmail.com> | 2017-07-03 18:59:57 -0300 |
---|---|---|
committer | liam4 <towerofnix@gmail.com> | 2017-07-03 19:00:01 -0300 |
commit | 769413468e88acba1a180baa0113139d929a3b9f (patch) | |
tree | f29af36826077178259b7bcc8bf9927cebfe71e3 /util/Flushable.js | |
parent | 489e4d0c78d5f393729cda0e1f6ac9a0a1237b4a (diff) |
A long-due cleanup + examples + things
..Obviously this breaks old things (particularly, see changes in FocusElement).
Diffstat (limited to 'util/Flushable.js')
-rw-r--r-- | util/Flushable.js | 97 |
1 files changed, 97 insertions, 0 deletions
diff --git a/util/Flushable.js b/util/Flushable.js new file mode 100644 index 0000000..b031677 --- /dev/null +++ b/util/Flushable.js @@ -0,0 +1,97 @@ +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.paused = false + this.requestedFlush = false + + this.chunks = [] + } + + write(what) { + this.chunks.push(what) + } + + flush() { + // If we're paused, we don't want to write, but we will keep a note that a + // flush was requested for when we unpause. + if (this.paused) { + this.requestedFlush = true + return + } + + // 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 = [] + } + + pause() { + this.paused = true + } + + resume() { + this.paused = false + + if (this.requestedFlush) { + this.flush() + } + } + + 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 + } +} |