« get me outta code hell

interfacer-telnet.js « examples - tui-lib - Pure Node.js library for making visual command-line programs (ala vim, ncdu)
about summary refs log tree commit diff
path: root/examples/interfacer-telnet.js
blob: 8cb804b7187257717d27e11deb50f00b4c5b5831 (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
// Telnet demo:
// - Basic telnet socket handling using the TelnetInterfacer
// - Handling client's screen size
// - Handling socket being closed by client
// - Handling cleanly closing the socket by hand

const net = require('net')
const Root = require('../ui/Root')
const TelnetInterfacer = require('../TelnetInterfacer')
const AppElement = require('./basic-app')

const server = new net.Server(socket => {
  const interfacer = new TelnetInterfacer(socket)

  interfacer.getScreenSize().then(size => {
    const root = new Root(interfacer)
    root.w = size.width
    root.h = size.height

    interfacer.on('screenSizeUpdated', newSize => {
      root.w = newSize.width
      root.h = newSize.height
      root.fixAllLayout()
    })

    const appElement = new AppElement()
    root.addChild(appElement)
    root.select(appElement)

    let closed = false

    appElement.on('quitRequested', () => {
      if (!closed) {
        interfacer.cleanTelnetOptions()
        socket.write('Goodbye!\n')
        socket.end()
        clearInterval(interval)
        closed = true
      }
    })

    socket.on('close', () => {
      if (!closed) {
        clearInterval(interval)
        closed = true
      }
    })

    const interval = setInterval(() => root.render(), 100)
  }).catch(error => {
    console.error(error)
    process.exit(1)
  })
})

server.listen(8008)