Skip to content

Commit

Permalink
Emit resize events for TTYWriteStreams
Browse files Browse the repository at this point in the history
Closes #4
  • Loading branch information
kasperisager committed Jun 2, 2024
1 parent ae5534a commit f9a150b
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
30 changes: 30 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/* global Bare */
const { Readable, Writable } = require('bare-stream')
const Signal = require('bare-signals')
const binding = require('./binding')
const constants = require('./lib/constants')

Expand Down Expand Up @@ -107,6 +108,7 @@ exports.WriteStream = class TTYWriteStream extends Writable {
super()

this._state = 0
this._size = null

this._pendingWrite = null
this._pendingDestroy = null
Expand All @@ -117,13 +119,24 @@ exports.WriteStream = class TTYWriteStream extends Writable {
this._onclose
)

this._size = this.getWindowSize()

if (TTYWriteStream._streams.size === 0) TTYWriteStream._resize.start()
TTYWriteStream._streams.add(this)
}

get isTTY () {
return true
}

get columns () {
return this._size[0]
}

get rows () {
return this._size[1]
}

getWindowSize () {
return binding.getWindowSize(this._handle)
}
Expand All @@ -138,6 +151,7 @@ exports.WriteStream = class TTYWriteStream extends Writable {
this._state |= constants.state.CLOSING
binding.close(this._handle)
TTYWriteStream._streams.delete(this)
if (TTYWriteStream._streams.size === 0) TTYWriteStream._resize.stop()
}

_destroy (err, cb) {
Expand All @@ -146,6 +160,7 @@ exports.WriteStream = class TTYWriteStream extends Writable {
this._pendingDestroy = cb
binding.close(this._handle)
TTYWriteStream._streams.delete(this)
if (TTYWriteStream._streams.size === 0) TTYWriteStream._resize.stop()
}

_continueWrite (err) {
Expand All @@ -171,7 +186,14 @@ exports.WriteStream = class TTYWriteStream extends Writable {
this._continueDestroy()
}

_onresize () {
this._size = this.getWindowSize()
this.emit('resize')
}

static _streams = new Set()

static _resize = new Signal('SIGWINCH')
}

exports.constants = constants
Expand All @@ -180,6 +202,14 @@ exports.isTTY = binding.isTTY

exports.isatty = exports.isTTY // For Node.js compatibility

exports.WriteStream._resize
.on('signal', () => {
for (const stream of exports.WriteStream._streams) {
stream._onresize()
}
})
.unref()

Bare
.on('exit', () => {
for (const stream of exports.ReadStream._streams) {
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"homepage": "https://github.com/holepunchto/bare-tty#readme",
"dependencies": {
"bare-events": "^2.2.0",
"bare-signals": "^2.2.0",
"bare-stream": "^2.0.0"
},
"devDependencies": {
Expand Down

0 comments on commit f9a150b

Please sign in to comment.