« 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: fe1cd03d089708b526775694804970d6b7f381b4 (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
// 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.

const ansi = require('./ansi');

const CommandLineInterfacer = require('./CommandLineInterfacer');
const Flushable = require('./Flushable');
const Root = require('../ui/Root');

module.exports = async function tuiApp(callback) {
    // TODO: Support other interfacers.
    const interfacer = new CommandLineInterfacer();

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

    const root = new Root(interfacer, flushable);

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

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