client.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Generic code for setting up mtui and the UI for any command line client.
  2. import AppElement from './ui.js'
  3. import {Root} from 'tui-lib/ui/primitives'
  4. import {Flushable} from 'tui-lib/util/interfaces'
  5. import * as ansi from 'tui-lib/util/ansi'
  6. export default async function setupClient({
  7. backend,
  8. writable,
  9. screenInterface,
  10. appConfig,
  11. }) {
  12. const cleanTerminal = () => {
  13. writable.write(ansi.cleanCursor())
  14. writable.write(ansi.disableAlternateScreen())
  15. }
  16. const dirtyTerminal = () => {
  17. writable.write(ansi.enableAlternateScreen())
  18. writable.write(ansi.startTrackingMouse())
  19. }
  20. dirtyTerminal()
  21. const flushable = new Flushable(writable, true)
  22. const root = new Root(screenInterface, flushable)
  23. root.on('rendered', () => flushable.flush())
  24. const size = await screenInterface.getScreenSize()
  25. root.w = size.width
  26. root.h = size.height
  27. root.fixAllLayout()
  28. flushable.resizeScreen(size)
  29. flushable.write(ansi.clearScreen())
  30. flushable.flush()
  31. screenInterface.on('resize', newSize => {
  32. root.w = newSize.width
  33. root.h = newSize.height
  34. flushable.resizeScreen(newSize)
  35. root.fixAllLayout()
  36. })
  37. const appElement = new AppElement(backend, appConfig)
  38. root.addChild(appElement)
  39. root.select(appElement)
  40. appElement.on('quitRequested', () => {
  41. appElement.removeListeners()
  42. cleanTerminal()
  43. })
  44. appElement.on('suspendRequested', () => {
  45. cleanTerminal()
  46. })
  47. root.select(appElement)
  48. // Load up initial state
  49. appElement.queueListingElement.buildItems()
  50. return {appElement, cleanTerminal, dirtyTerminal, flushable, root}
  51. }