diff options
author | Zander Hill <zander@xargs.io> | 2024-07-04 15:12:14 -0700 |
---|---|---|
committer | GitHub <noreply@github.com> | 2024-07-04 22:12:14 +0000 |
commit | f00f0f92983d6966a5b97e539ec3f3407c3d851f (patch) | |
tree | 73966bbfbd836dd3dd36ff22647c97d0f839baed /cli/js/40_jupyter.js | |
parent | 96b527b8df3c9e7e29c98a6a0d6876089b88bc09 (diff) |
feat(jupyter): support `confirm` and `prompt` in notebooks (#23592)
Closes: https://github.com/denoland/deno/issues/22633
This commit adds support for `confirm` and `prompt` APIs,
that instead of reading from stdin are using notebook frontend
to show modal boxes and wait for answers.
---------
Co-authored-by: Bartek IwaĆczuk <biwanczuk@gmail.com>
Diffstat (limited to 'cli/js/40_jupyter.js')
-rw-r--r-- | cli/js/40_jupyter.js | 48 |
1 files changed, 47 insertions, 1 deletions
diff --git a/cli/js/40_jupyter.js b/cli/js/40_jupyter.js index 0e0a4d7ac..ace50d6dc 100644 --- a/cli/js/40_jupyter.js +++ b/cli/js/40_jupyter.js @@ -337,7 +337,14 @@ async function formatInner(obj, raw) { internals.jupyter = { formatInner }; function enableJupyter() { - const { op_jupyter_broadcast } = core.ops; + const { op_jupyter_broadcast, op_jupyter_input } = core.ops; + + function input( + prompt, + password, + ) { + return op_jupyter_input(prompt, password); + } async function broadcast( msgType, @@ -412,6 +419,45 @@ function enableJupyter() { return; } + /** + * Prompt for user confirmation (in Jupyter Notebook context) + * Override confirm and prompt because they depend on a tty + * and in the Deno.jupyter environment that doesn't exist. + * @param {string} message - The message to display. + * @returns {Promise<boolean>} User confirmation. + */ + function confirm(message = "Confirm") { + const answer = input(`${message} [y/N] `, false); + return answer === "Y" || answer === "y"; + } + + /** + * Prompt for user input (in Jupyter Notebook context) + * @param {string} message - The message to display. + * @param {string} defaultValue - The value used if none is provided. + * @param {object} options Options + * @param {boolean} options.password Hide the output characters + * @returns {Promise<string>} The user input. + */ + function prompt( + message = "Prompt", + defaultValue = "", + { password = false } = {}, + ) { + if (defaultValue != "") { + message += ` [${defaultValue}]`; + } + const answer = input(`${message}`, password); + + if (answer === "") { + return defaultValue; + } + + return answer; + } + + globalThis.confirm = confirm; + globalThis.prompt = prompt; globalThis.Deno.jupyter = { broadcast, display, |