dthree / vorpal

Node's framework for interactive CLIs
http://vorpal.js.org
MIT License
5.64k stars 280 forks source link

End vorpal.ui.redraw loop on keypress? #173

Closed lsjroberts closed 8 years ago

lsjroberts commented 8 years ago

I have a command like:

.action(function (args, next) {
  const drawInterval = setInterval(() => {
    // ...
    vorpal.ui.redraw(stuffToDraw);
  }, 10);
})

How would I listen to a keypress, say q, and then run vorpal.ui.redraw.done()?

I have tried using

process.stdin.on('readable', () => {
  const chunk = process.stdin.read();
  if (chunk === 'q') {
    vorpal.ui.redraw.done();
  }
});

However the chunk doesn't come out with just the q character. Is there a built-in way of doing this? The only option so far is to press Ctrl+C and exit the whole of vorpal.

lsjroberts commented 8 years ago

I've found a solution for this. My primary problem was that I was forgetting to call the callback next().

This allowed me to read process.stdin.on('keypress', ...) correctly and listen for Ctrl+C.

.action(function (args, next) {
  const drawInterval = setInterval(() => {
    // ...
    vorpal.ui.redraw(stuffToDraw)
  }, 10);

  next();

  process.stdin.on('keypress', (letter, key) => {
    if (key.sequence && key.sequence === '\u0003') {
      clearInterval(drawInterval);
      vorpal.ui.redraw.done();
    }
  });
})
dthree commented 8 years ago

Smart! Thanks for sharing the solution. :+1:

BTW the closest thing I've done to this is vorpal-less:

https://github.com/vorpaljs/vorpal-less/blob/master/src/less.js