From aa38d1beb78635e5273b89b76c6a2b91428dd62c Mon Sep 17 00:00:00 2001 From: Florrie Date: Tue, 5 Feb 2019 20:13:53 -0400 Subject: App boilerplate code --- util/tui-app.js | 60 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 util/tui-app.js (limited to 'util/tui-app.js') diff --git a/util/tui-app.js b/util/tui-app.js new file mode 100644 index 0000000..7ee0480 --- /dev/null +++ b/util/tui-app.js @@ -0,0 +1,60 @@ +// 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); + + const size = await interfacer.getScreenSize(); + root.w = size.width; + root.h = size.height; + flushable.resizeScreen(size); + + interfacer.on('resize', newSize => { + root.w = newSize.width; + root.h = newSize.height; + flushable.resizeScreen(newSize); + root.fixAllLayout(); + }); + + const clean = function() { + process.stdout.write(ansi.cleanCursor()); + process.stdout.write(ansi.disableAlternateScreen()); + }; + + const quitProgram = function(status = 0) { + clean(); + process.exit(status); + }; + + const startRenderLoop = function() { + process.stdout.write(ansi.enableAlternateScreen()); + setInterval(() => { + root.renderTo(flushable); + flushable.flush(); + }); + }; + + try { + return await callback({ + root, + startRenderLoop, + quitProgram + }); + } catch (error) { + clean(); + console.error(error); + process.exit(1); + }; +}; -- cgit 1.3.0-6-gf8a5