« get me outta code hell

client.js - mtui - Music Text User Interface - user-friendly command line music player
about summary refs log tree commit diff
path: root/client.js
blob: 0af45f6b5be369da6e1544d3a3e5f2ccd23403aa (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
// Generic code for setting up mtui and the UI for any command line client.

import AppElement from './ui.js'

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

import {Flushable} from 'tui-lib/util/interfaces'
import * as ansi from 'tui-lib/util/ansi'

export default async function setupClient({
  backend,
  writable,
  screenInterface,
  appConfig,
}) {
  const cleanTerminal = () => {
    writable.write(ansi.cleanCursor())
    writable.write(ansi.disableAlternateScreen())
  }

  const dirtyTerminal = () => {
    writable.write(ansi.enableAlternateScreen())
    writable.write(ansi.startTrackingMouse())
  }

  dirtyTerminal()

  const flushable = new Flushable(writable, true)
  const root = new Root(screenInterface, flushable)
  root.on('rendered', () => flushable.flush())

  const size = await screenInterface.getScreenSize()
  root.w = size.width
  root.h = size.height
  root.fixAllLayout()

  flushable.resizeScreen(size)
  flushable.write(ansi.clearScreen())
  flushable.flush()

  screenInterface.on('resize', newSize => {
    root.w = newSize.width
    root.h = newSize.height
    flushable.resizeScreen(newSize)
    root.fixAllLayout()
  })

  const appElement = new AppElement(backend, appConfig)
  root.addChild(appElement)
  root.select(appElement)

  appElement.on('quitRequested', () => {
    appElement.removeListeners()
    cleanTerminal()
  })

  appElement.on('suspendRequested', () => {
    cleanTerminal()
  })

  root.select(appElement)

  // Load up initial state
  appElement.queueListingElement.buildItems()

  return {appElement, cleanTerminal, dirtyTerminal, flushable, root}
}