UNPKG

r3bl-ts-utils

Version:

The `r3bl-ts-utils` package is a set of useful TypeScript functions and classes that can be used in Node.js and browser environments. They are inspired by Kotlin stdlib, and Rust to write code as expressions rather than statements, colorized text, powerfu

244 lines (238 loc) 11.8 kB
"use strict"; /* * Copyright (c) 2022 R3BL LLC. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.useKeyboardCompatInkWithMapCached = exports.useKeyboardCompatInkWithMap = exports.useKeyboardCompatInk = exports.useKeyboardWithMapCached = exports.useKeyboardWithMap = exports.useKeyboard = exports.useKeyboardBuilder = exports.UseKeyboardReturnValue = exports.createNewShortcutToActionMap = exports.usePreventUseInputFromSettingRawModeToFalseAndExiting = exports.UseKeyboardWrapper = void 0; const ink_1 = require("ink"); const StdinContext_1 = __importDefault(require("ink/build/components/StdinContext")); const lodash_1 = require("lodash"); const react_1 = __importStar(require("react")); const lang_utils_1 = require("../lang-utils"); const expression_lang_utils_1 = require("../lang-utils/expression-lang-utils"); const rust_lang_utils_1 = require("../lang-utils/rust-lang-utils"); const tui_core_1 = require("../tui-core"); const keypress_1 = require("./keypress"); const keypress_builder_ink_1 = require("./keypress-builder-ink"); const keypress_builder_readline_1 = require("./keypress-builder-readline"); const use_keyboard_internal_1 = require("./use-keyboard-internal"); const use_node_keypress_1 = require("./use-node-keypress"); const utils_1 = require("./utils"); /** Ink has a hook that is supposed to be used to get user input from the keyboard called `useInput`, which comes from the `ink` package. `TextInput` is built on top of this hook. `TextInput` comes from the npm package `ink-text-input`. 1. [useInput sets raw mode to false](https://github.com/vadimdemedes/ink/blob/master/src/hooks/use-input.ts#L126) 2. [TextInput uses useInput](https://github.com/vadimdemedes/ink-text-input/blob/master/source/index.tsx#L117) The `useKeyboard` hook makes some assumptions. 1. It will set raw mode to true when used. 2. It will turn raw mode to false when unmounted. The problem w/ `TextInput` using `useInput` and then turning raw mode to off when focus changes on `TextInput` simply causes the Node.js process to exit, since there are no active listeners attached to it 🤯. To mitigate this problem is really simple - just make sure to call `useInput(noop)` somewhere in the component that includes `TextInput`! ⚠ However, this does not get rid of the default "ctrl+c" handling, which is to exit the app (this is how useInput behaves by default). You can override it by wrapping your Ink components in a Provider, like so: ``` <StdinContext.Provider value={{ stdin: process.stdin, setRawMode: noop, isRawModeSupported: true, internal_exitOnCtrlC: false }} > <App/> </StdinContext.Provider> ``` or simply: ``` <UseKeyboardWrapper> <App/> </UseKeyboardWrapper> ``` */ const UseKeyboardWrapper = ({ children }) => { // https://www.carlrippon.com/react-children-with-typescript/ return (react_1.default.createElement(StdinContext_1.default.Provider, { value: { stdin: process.stdin, setRawMode: lodash_1.noop, isRawModeSupported: true, internal_exitOnCtrlC: false } }, children)); }; exports.UseKeyboardWrapper = UseKeyboardWrapper; /** @deprecated Please use UseKeyboardWrapper instead. */ const usePreventUseInputFromSettingRawModeToFalseAndExiting = () => (0, ink_1.useInput)(lodash_1.noop); exports.usePreventUseInputFromSettingRawModeToFalseAndExiting = usePreventUseInputFromSettingRawModeToFalseAndExiting; const createNewShortcutToActionMap = () => new Map(); exports.createNewShortcutToActionMap = createNewShortcutToActionMap; class UseKeyboardReturnValue { keyPress; inRawMode; constructor(keyPress, inRawMode) { this.keyPress = keyPress; this.inRawMode = inRawMode; } toArray() { return [this.keyPress, this.inRawMode]; } } exports.UseKeyboardReturnValue = UseKeyboardReturnValue; // Hooks. const useKeyboardBuilder = (config) => { switch (config.type) { case "node-keypress": { switch (config.args.type) { case "fun": return (0, exports.useKeyboard)(config.args.matchKeypressFn, config.args.options, config.testing); case "map-cached": return (0, exports.useKeyboardWithMapCached)(config.args.createShortcutsFn, config.args.options, config.testing); case "map": return (0, exports.useKeyboardWithMap)(config.args.map, config.args.options, config.testing); } } case "ink-compat": { switch (config.args.type) { case "fun": return (0, exports.useKeyboardCompatInk)(config.args.matchKeypressFn, config.args.options); case "map-cached": return (0, exports.useKeyboardCompatInkWithMapCached)(config.args.createShortcutsFn, config.args.options); case "map": return (0, exports.useKeyboardCompatInkWithMap)(config.args.map, config.args.options); } } } }; exports.useKeyboardBuilder = useKeyboardBuilder; /** * @return [keyPress, inRawMode] - inRawMode is false means keyboard input is disabled in * terminal. keyPress is the key that the user pressed (eg: "ctrl+k", "backspace", "shift+A"). */ const useKeyboard = (processKeypressFn, options = { isActive: true }, testing) => { const [keyPress, setKeyPress] = (0, tui_core_1.useStateSafely)(rust_lang_utils_1.Option.none()).asArray(); const dispatchKeypressOption = (keypressOption) => { setKeyPress(keypressOption); processKeypressFn(keypressOption); }; // Testing bypass process.stdin as the event emitter for "keypress" events (via readline). // @see multi-select-input.tsx return (0, expression_lang_utils_1._callIfTruthyWithReturn)(testing, // Testing mode. ({ emitter, eventName }) => { const eventListener = (args) => { const arg = args[0]; const argIsKeypress = arg instanceof keypress_1.Keypress; if (argIsKeypress) { const keypress = arg; dispatchKeypressOption(rust_lang_utils_1.Option.create(keypress)); } else { const msg = (0, lang_utils_1.anyToString)(arg); let error = new Error(`Expected keypress event, got ${msg}`); console.error(error); } }; (0, tui_core_1.useEventEmitter)(emitter, eventName, eventListener, options); return new UseKeyboardReturnValue(keyPress, true); }, // Production mode. () => { if (!(0, utils_1.isTTY)()) return new UseKeyboardReturnValue(rust_lang_utils_1.Option.none(), false); const onKeypress = (input, key) => { const keypressOption = rust_lang_utils_1.Option.create((0, keypress_builder_readline_1.createFromKeypress)(key, input)); dispatchKeypressOption(keypressOption); }; (0, use_node_keypress_1.useNodeKeypress)(onKeypress, options); return new UseKeyboardReturnValue(keyPress, true); }); }; exports.useKeyboard = useKeyboard; /** * @return [keyPress, inRawMode] - inRawMode is false means keyboard input is disabled in * terminal. keyPress is the key that the user pressed (eg: "ctrl+k", "backspace", "shift+A"). */ const useKeyboardWithMap = (map, options = { isActive: true }, testing) => (0, exports.useKeyboard)(keyPress => (0, use_keyboard_internal_1.tryToRunActionForShortcut)(keyPress, map), options, testing); exports.useKeyboardWithMap = useKeyboardWithMap; /** * @return [keyPress, inRawMode] - inRawMode is false means keyboard input is disabled in * terminal. keyPress is the key that the user pressed (eg: "ctrl+k", "backspace", "shift+A"). */ const useKeyboardWithMapCached = (createMapFn, options = { isActive: true }, testing) => { const cachedMap = (0, react_1.useMemo)(() => createMapFn(), [options.isActive]); return (0, exports.useKeyboardWithMap)(cachedMap, options, testing); }; exports.useKeyboardWithMapCached = useKeyboardWithMapCached; /** * @return [keyPress, inRawMode] - inRawMode is false means keyboard input is disabled in * terminal. keyPress is the key that the user pressed (eg: "ctrl+k", "backspace", "shift+A"). */ const useKeyboardCompatInk = (processKeypressFn, options = { isActive: true }) => { const [keyPress, setKeyPress] = (0, tui_core_1.useStateSafely)(rust_lang_utils_1.Option.none()).asArray(); const { isRawModeSupported: inRawMode } = (0, ink_1.useStdin)(); // Can only call useInput in raw mode. if (!inRawMode) return new UseKeyboardReturnValue(rust_lang_utils_1.Option.none(), false); const onKeypress = (input, key) => { const userInputKeyPressOption = rust_lang_utils_1.Option.create((0, keypress_builder_ink_1.createFromInk)(key, input)); setKeyPress(userInputKeyPressOption); processKeypressFn(userInputKeyPressOption); }; (0, ink_1.useInput)(onKeypress, options); return new UseKeyboardReturnValue(keyPress, inRawMode); }; exports.useKeyboardCompatInk = useKeyboardCompatInk; /** * @return [keyPress, inRawMode] - inRawMode is false means keyboard input is disabled in * terminal. keyPress is the key that the user pressed (eg: "ctrl+k", "backspace", "shift+A"). */ const useKeyboardCompatInkWithMap = (map, options = { isActive: true }) => (0, exports.useKeyboardCompatInk)(keyPress => (0, use_keyboard_internal_1.tryToRunActionForShortcut)(keyPress, map), options); exports.useKeyboardCompatInkWithMap = useKeyboardCompatInkWithMap; /** * @return [keyPress, inRawMode] - inRawMode is false means keyboard input is disabled in * terminal. keyPress is the key that the user pressed (eg: "ctrl+k", "backspace", "shift+A"). */ const useKeyboardCompatInkWithMapCached = (createMapFn, options = { isActive: true }) => { const cachedMap = (0, react_1.useMemo)(() => createMapFn(), [options.isActive]); return (0, exports.useKeyboardCompatInkWithMap)(cachedMap); }; exports.useKeyboardCompatInkWithMapCached = useKeyboardCompatInkWithMapCached; //# sourceMappingURL=use-keyboard.js.map