« get me outta code hell

tui-app.js « util - tui-lib - Pure Node.js library for making visual command-line programs (ala vim, ncdu)
about summary refs log tree commit diff
path: root/util/tui-app.js
blob: 2f09818b3a09efef97a68c607c9063d9fd934a7a (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
// General-purpose wrapper code that can be used as the base of a tui-lib
// program. Contained to reduce boilerplate and improve consistency between
// programs.

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

import {CommandLineInterface, Flushable} from './interfaces/index.js'
import * as ansi from './ansi.js'

export default async function tuiApp(callback) {
    // TODO: Support other screen interfaces.
    const screenInterface = new CommandLineInterface();

    const flushable = new Flushable(process.stdout, true);

    const root = new Root(screenInterface);

    const size = await screenInterface.getScreenSize();
    root.w = size.width;
    root.h = size.height;
    flushable.resizeScreen(size);
    root.on('rendered', () => flushable.flush());

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

    const cleanTerminal = function () {
        process.stdout.write(ansi.cleanCursor());
        process.stdout.write(ansi.disableAlternateScreen());
    };

    const dirtyTerminal = function () {
        process.stdout.write(ansi.enableAlternateScreen());
        process.stdout.write(ansi.startTrackingMouse());
    };

    const quitProgram = function (status = 0) {
        cleanTerminal();
        process.exit(status);
    };

    const suspendProgram = function () {
        cleanTerminal();
        process.kill(process.pid, 'SIGTSTP');
    };

    process.on('SIGCONT', () => {
        flushable.clearLastFrame();
        process.stdin.setRawMode(false);
        process.stdin.setRawMode(true);
        dirtyTerminal();
    });

    dirtyTerminal();

    try {
        return await callback({
            root,
            suspendProgram,
            quitProgram
        });
    } catch (error) {
        cleanTerminal();
        console.error(error);
        process.exit(1);
    };
};