« 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: aa854ed85dbaecbe840053a262864d5c104a6a13 (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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Generic code for setting up mtui and the UI for any command line client.

'use strict'

const AppElement = require('./ui')
const processSmartPlaylist = require('./smart-playlist')
const os = require('os')

const {
  ui: {
    Root
  },
  util: {
    ansi,
    Flushable,
    TelnetInterfacer
  }
} = require('tui-lib')

const setupClient = async ({backend, writable, interfacer, 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(interfacer, flushable)
  root.on('rendered', () => flushable.flush())

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

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

  interfacer.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()
  })

  let grouplike = {
    name: 'My ~/Music Library',
    comment: (
      '(Add tracks and folders to ~/Music to make them show up here,' +
      ' or pass mtui your own playlist.json file!)'),
    source: ['crawl-local', os.homedir() + '/Music']
  }
  await appElement.loadPlaylistOrSource(grouplike, true)

  root.select(appElement)

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

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

module.exports = setupClient