Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

process._prompt for asking questions on the command line #25

Open
coolaj86 opened this issue Mar 8, 2022 · 0 comments
Open

process._prompt for asking questions on the command line #25

coolaj86 opened this issue Mar 8, 2022 · 0 comments
Labels
std Extends the Standard Library

Comments

@coolaj86
Copy link
Collaborator

coolaj86 commented Mar 8, 2022

I'm not quite sure this is the implementation, but probably something close to this.

I'd actually much prefer to have inline autocomplete, like fish, but I've done that before and it's no small feat - certainly outside of the "almost bare metal" approach of AjScript.

/**
 * @param {String} query
 * @param {Object} options
 * @param {Array<String>} [options.choices]
 * @param {Boolean} [options.mask]
 */
process._prompt = async function (query, options) {
  let Readline = require("readline");

  let completer;
  if (options?.choices) {
    /**
     * @param {String} line
     */
    completer = function (line) {
      let completions = options.choices || [];
      let hits = completions.filter(function (c) {
        return c.startsWith(line);
      });
      if (!hits.length) {
        hits = completions;
      }
      return [hits, line];
    };
  }

  let rl = Readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    completer,
  });

  if (options?.mask) {
    rl.input.on("keypress", function (_char, _modifiers) {
      // _char = "e"
      // _modifiers = { sequence: 'e', name: 'e', ctrl: false, meta: false, shift: false }
      let len = rl.line.length;
      // place cursor at the beginning of the prompt
      Readline.moveCursor(rl.output, -len, 0);
      // clear right of the cursor / prompt
      Readline.clearLine(rl.output, 1);
      // mask with "*"
      rl.output.write("*".repeat(len));
    });
  }

  let answer = await new Promise(function (resolve) {
    return rl.question(query ?? "", resolve);
  });

  // TODO what if we need control over closing?
  // ex: Promise.race([getPrompt, getFsEvent, getSocketEvent]);
  rl.close();
  return answer;
};

Inspired by https://github.com/google/zx/blob/51fb6d5d710fcd0bfcc7bc905066ac0fa042467c/index.mjs#L143.

@coolaj86 coolaj86 added the std Extends the Standard Library label Mar 8, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
std Extends the Standard Library
Projects
None yet
Development

No branches or pull requests

1 participant