« get me outta code hell

telnet-interface.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/telnet-interface.js
blob: 319786faa7385d044a34d2857b4d0628b34281e0 (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
// Telnet demo:
// - Basic telnet socket handling using the TelnetInterface
// - Handling client's screen size
// - Handling socket being closed by client
// - Handling cleanly closing the socket by hand

import net from 'node:net'

import {Root} from 'tui-lib/ui/primitives'

import {TelnetInterface} from 'tui-lib/util/interfaces'

import AppElement from './basic-app.js'

const server = new net.Server(socket => {
  const telnetInterface = new TelnetInterface(socket)

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

    telnetInterface.on('resize', 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) {
        telnetInterface.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)