Socket
Socket
Sign inDemoInstall

ink

Package Overview
Dependencies
66
Maintainers
2
Versions
75
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 2.7.1 to 3.0.0-0

build/apply-styles.d.ts

301

build/apply-styles.js
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _yogaLayoutPrebuilt = _interopRequireDefault(require("yoga-layout-prebuilt"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.applyStyles = void 0;
/* eslint-disable @typescript-eslint/prefer-nullish-coalescing */
const yoga_layout_prebuilt_1 = __importDefault(require("yoga-layout-prebuilt"));
const applyPositionStyles = (node, style) => {
if ('position' in style) {
node.setPositionType(style.position === 'absolute'
? yoga_layout_prebuilt_1.default.POSITION_TYPE_ABSOLUTE
: yoga_layout_prebuilt_1.default.POSITION_TYPE_RELATIVE);
}
};
const applyMarginStyles = (node, style) => {
if (style.margin) {
node.setMargin(_yogaLayoutPrebuilt.default.EDGE_TOP, style.margin);
node.setMargin(_yogaLayoutPrebuilt.default.EDGE_BOTTOM, style.margin);
node.setMargin(_yogaLayoutPrebuilt.default.EDGE_START, style.margin);
node.setMargin(_yogaLayoutPrebuilt.default.EDGE_END, style.margin);
}
if (style.marginX) {
node.setMargin(_yogaLayoutPrebuilt.default.EDGE_START, style.marginX);
node.setMargin(_yogaLayoutPrebuilt.default.EDGE_END, style.marginX);
}
if (style.marginY) {
node.setMargin(_yogaLayoutPrebuilt.default.EDGE_TOP, style.marginY);
node.setMargin(_yogaLayoutPrebuilt.default.EDGE_BOTTOM, style.marginY);
}
if (style.marginTop) {
node.setMargin(_yogaLayoutPrebuilt.default.EDGE_TOP, style.marginTop);
}
if (style.marginBottom) {
node.setMargin(_yogaLayoutPrebuilt.default.EDGE_BOTTOM, style.marginBottom);
}
if (style.marginLeft) {
node.setMargin(_yogaLayoutPrebuilt.default.EDGE_START, style.marginLeft);
}
if (style.marginRight) {
node.setMargin(_yogaLayoutPrebuilt.default.EDGE_END, style.marginRight);
}
if ('marginLeft' in style) {
node.setMargin(yoga_layout_prebuilt_1.default.EDGE_START, style.marginLeft || 0);
}
if ('marginRight' in style) {
node.setMargin(yoga_layout_prebuilt_1.default.EDGE_END, style.marginRight || 0);
}
if ('marginTop' in style) {
node.setMargin(yoga_layout_prebuilt_1.default.EDGE_TOP, style.marginTop || 0);
}
if ('marginBottom' in style) {
node.setMargin(yoga_layout_prebuilt_1.default.EDGE_BOTTOM, style.marginBottom || 0);
}
};
const applyPaddingStyles = (node, style) => {
if (style.padding) {
node.setPadding(_yogaLayoutPrebuilt.default.EDGE_TOP, style.padding);
node.setPadding(_yogaLayoutPrebuilt.default.EDGE_BOTTOM, style.padding);
node.setPadding(_yogaLayoutPrebuilt.default.EDGE_LEFT, style.padding);
node.setPadding(_yogaLayoutPrebuilt.default.EDGE_RIGHT, style.padding);
}
if (style.paddingX) {
node.setPadding(_yogaLayoutPrebuilt.default.EDGE_LEFT, style.paddingX);
node.setPadding(_yogaLayoutPrebuilt.default.EDGE_RIGHT, style.paddingX);
}
if (style.paddingY) {
node.setPadding(_yogaLayoutPrebuilt.default.EDGE_TOP, style.paddingY);
node.setPadding(_yogaLayoutPrebuilt.default.EDGE_BOTTOM, style.paddingY);
}
if (style.paddingTop) {
node.setPadding(_yogaLayoutPrebuilt.default.EDGE_TOP, style.paddingTop);
}
if (style.paddingBottom) {
node.setPadding(_yogaLayoutPrebuilt.default.EDGE_BOTTOM, style.paddingBottom);
}
if (style.paddingLeft) {
node.setPadding(_yogaLayoutPrebuilt.default.EDGE_LEFT, style.paddingLeft);
}
if (style.paddingRight) {
node.setPadding(_yogaLayoutPrebuilt.default.EDGE_RIGHT, style.paddingRight);
}
if ('paddingLeft' in style) {
node.setPadding(yoga_layout_prebuilt_1.default.EDGE_LEFT, style.paddingLeft || 0);
}
if ('paddingRight' in style) {
node.setPadding(yoga_layout_prebuilt_1.default.EDGE_RIGHT, style.paddingRight || 0);
}
if ('paddingTop' in style) {
node.setPadding(yoga_layout_prebuilt_1.default.EDGE_TOP, style.paddingTop || 0);
}
if ('paddingBottom' in style) {
node.setPadding(yoga_layout_prebuilt_1.default.EDGE_BOTTOM, style.paddingBottom || 0);
}
};
const applyFlexStyles = (node, style) => {
if (style.flexGrow) {
node.setFlexGrow(style.flexGrow);
}
if (style.flexShrink) {
node.setFlexShrink(style.flexShrink);
}
if (style.flexDirection) {
if (style.flexDirection === 'row') {
node.setFlexDirection(_yogaLayoutPrebuilt.default.FLEX_DIRECTION_ROW);
var _a;
if ('flexGrow' in style) {
node.setFlexGrow((_a = style.flexGrow) !== null && _a !== void 0 ? _a : 0);
}
if (style.flexDirection === 'row-reverse') {
node.setFlexDirection(_yogaLayoutPrebuilt.default.FLEX_DIRECTION_ROW_REVERSE);
if ('flexShrink' in style) {
node.setFlexShrink(typeof style.flexShrink === 'number' ? style.flexShrink : 1);
}
if (style.flexDirection === 'column') {
node.setFlexDirection(_yogaLayoutPrebuilt.default.FLEX_DIRECTION_COLUMN);
if ('flexDirection' in style) {
if (style.flexDirection === 'row') {
node.setFlexDirection(yoga_layout_prebuilt_1.default.FLEX_DIRECTION_ROW);
}
if (style.flexDirection === 'row-reverse') {
node.setFlexDirection(yoga_layout_prebuilt_1.default.FLEX_DIRECTION_ROW_REVERSE);
}
if (style.flexDirection === 'column') {
node.setFlexDirection(yoga_layout_prebuilt_1.default.FLEX_DIRECTION_COLUMN);
}
if (style.flexDirection === 'column-reverse') {
node.setFlexDirection(yoga_layout_prebuilt_1.default.FLEX_DIRECTION_COLUMN_REVERSE);
}
}
if (style.flexDirection === 'column-reverse') {
node.setFlexDirection(_yogaLayoutPrebuilt.default.FLEX_DIRECTION_COLUMN_REVERSE);
if ('flexBasis' in style) {
if (typeof style.flexBasis === 'number') {
node.setFlexBasis(style.flexBasis);
}
else if (typeof style.flexBasis === 'string') {
node.setFlexBasisPercent(Number.parseInt(style.flexBasis, 10));
}
else {
// This should be replaced with node.setFlexBasisAuto() when new Yoga release is out
node.setFlexBasis(NaN);
}
}
}
if (style.flexBasis !== undefined) {
node.setFlexBasis(style.flexBasis);
}
if (style.alignItems) {
if (style.alignItems === 'flex-start') {
node.setAlignItems(_yogaLayoutPrebuilt.default.ALIGN_FLEX_START);
if ('alignItems' in style) {
if (style.alignItems === 'stretch' || !style.alignItems) {
node.setAlignItems(yoga_layout_prebuilt_1.default.ALIGN_STRETCH);
}
if (style.alignItems === 'flex-start') {
node.setAlignItems(yoga_layout_prebuilt_1.default.ALIGN_FLEX_START);
}
if (style.alignItems === 'center') {
node.setAlignItems(yoga_layout_prebuilt_1.default.ALIGN_CENTER);
}
if (style.alignItems === 'flex-end') {
node.setAlignItems(yoga_layout_prebuilt_1.default.ALIGN_FLEX_END);
}
}
if (style.alignItems === 'center') {
node.setAlignItems(_yogaLayoutPrebuilt.default.ALIGN_CENTER);
if ('justifyContent' in style) {
if (style.justifyContent === 'flex-start' || !style.justifyContent) {
node.setJustifyContent(yoga_layout_prebuilt_1.default.JUSTIFY_FLEX_START);
}
if (style.justifyContent === 'center') {
node.setJustifyContent(yoga_layout_prebuilt_1.default.JUSTIFY_CENTER);
}
if (style.justifyContent === 'flex-end') {
node.setJustifyContent(yoga_layout_prebuilt_1.default.JUSTIFY_FLEX_END);
}
if (style.justifyContent === 'space-between') {
node.setJustifyContent(yoga_layout_prebuilt_1.default.JUSTIFY_SPACE_BETWEEN);
}
if (style.justifyContent === 'space-around') {
node.setJustifyContent(yoga_layout_prebuilt_1.default.JUSTIFY_SPACE_AROUND);
}
}
if (style.alignItems === 'flex-end') {
node.setAlignItems(_yogaLayoutPrebuilt.default.ALIGN_FLEX_END);
};
const applyDimensionStyles = (node, style) => {
var _a, _b;
if ('width' in style) {
if (typeof style.width === 'number') {
node.setWidth(style.width);
}
else if (typeof style.width === 'string') {
node.setWidthPercent(Number.parseInt(style.width, 10));
}
else {
node.setWidthAuto();
}
}
}
if (style.justifyContent) {
if (style.justifyContent === 'flex-start') {
node.setJustifyContent(_yogaLayoutPrebuilt.default.JUSTIFY_FLEX_START);
if ('height' in style) {
if (typeof style.height === 'number') {
node.setHeight(style.height);
}
else if (typeof style.height === 'string') {
node.setHeightPercent(Number.parseInt(style.height, 10));
}
else {
node.setHeightAuto();
}
}
if (style.justifyContent === 'center') {
node.setJustifyContent(_yogaLayoutPrebuilt.default.JUSTIFY_CENTER);
if ('minWidth' in style) {
if (typeof style.minWidth === 'string') {
node.setMinWidthPercent(Number.parseInt(style.minWidth, 10));
}
else {
node.setMinWidth((_a = style.minWidth) !== null && _a !== void 0 ? _a : 0);
}
}
if (style.justifyContent === 'flex-end') {
node.setJustifyContent(_yogaLayoutPrebuilt.default.JUSTIFY_FLEX_END);
if ('minHeight' in style) {
if (typeof style.minHeight === 'string') {
node.setMinHeightPercent(Number.parseInt(style.minHeight, 10));
}
else {
node.setMinHeight((_b = style.minHeight) !== null && _b !== void 0 ? _b : 0);
}
}
if (style.justifyContent === 'space-between') {
node.setJustifyContent(_yogaLayoutPrebuilt.default.JUSTIFY_SPACE_BETWEEN);
};
const applyDisplayStyles = (node, style) => {
if ('display' in style) {
node.setDisplay(style.display === 'flex' ? yoga_layout_prebuilt_1.default.DISPLAY_FLEX : yoga_layout_prebuilt_1.default.DISPLAY_NONE);
}
if (style.justifyContent === 'space-around') {
node.setJustifyContent(_yogaLayoutPrebuilt.default.JUSTIFY_SPACE_AROUND);
}
}
};
const applyDimensionStyles = (node, style) => {
if (style.width !== undefined) {
node.setWidth(style.width);
}
if (style.height !== undefined) {
node.setHeight(style.height);
}
if (style.minWidth !== undefined) {
node.setMinWidth(style.minWidth);
}
if (style.minHeight !== undefined) {
node.setMinHeight(style.minHeight);
}
exports.applyStyles = (node, style = {}) => {
applyPositionStyles(node, style);
applyMarginStyles(node, style);
applyPaddingStyles(node, style);
applyFlexStyles(node, style);
applyDimensionStyles(node, style);
applyDisplayStyles(node, style);
};
var _default = (node, style = {}) => {
applyMarginStyles(node, style);
applyPaddingStyles(node, style);
applyFlexStyles(node, style);
applyDimensionStyles(node, style);
};
exports.default = _default;
//# sourceMappingURL=apply-styles.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _yogaLayoutPrebuilt = _interopRequireDefault(require("yoga-layout-prebuilt"));
var _applyStyles = _interopRequireDefault(require("./apply-styles"));
var _measureText = _interopRequireDefault(require("./measure-text"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const yoga_layout_prebuilt_1 = __importDefault(require("yoga-layout-prebuilt"));
const apply_styles_1 = require("./apply-styles");
const measure_text_1 = require("./measure-text");
// Traverse the node tree, create Yoga nodes and assign styles to each Yoga node
const buildLayout = (node, options) => {
const {
config,
terminalWidth,
skipStaticElements
} = options;
const yogaNode = _yogaLayoutPrebuilt.default.Node.create(config);
node.yogaNode = yogaNode;
const style = node.style || {}; // Root node of the tree
if (node.nodeName === 'ROOT') {
// `terminalWidth` can be `undefined` if env isn't a TTY
yogaNode.setWidth(terminalWidth || 100);
if (node.childNodes.length > 0) {
const childNodes = node.childNodes.filter(childNode => {
return skipStaticElements ? !childNode.unstable__static : true;
});
for (const [index, childNode] of Object.entries(childNodes)) {
const childYogaNode = buildLayout(childNode, options).yogaNode;
yogaNode.insertChild(childYogaNode, index);
}
exports.buildLayout = (node, options) => {
const { config, terminalWidth, skipStaticElements } = options;
const yogaNode = yoga_layout_prebuilt_1.default.Node.createWithConfig(config);
node.yogaNode = yogaNode;
const { style } = node;
console.log('HERE');
// Root node of the tree
if (node.nodeName === 'ROOT') {
// `terminalWidth` can be `undefined` if env isn't a TTY
yogaNode.setWidth(terminalWidth || 100);
if (node.childNodes.length > 0) {
const childNodes = node.childNodes.filter(childNode => {
return skipStaticElements ? !childNode.unstable__static : true;
});
for (const [index, childNode] of Object.entries(childNodes)) {
const { yogaNode: childYogaNode } = exports.buildLayout(childNode, options);
if (childYogaNode) {
yogaNode.insertChild(childYogaNode, Number.parseInt(index, 10));
}
}
}
return node;
}
// Apply margin, padding, flex, etc styles
apply_styles_1.applyStyles(yogaNode, style);
if (node.nodeName === '#text') {
// Nodes with only text have a child Yoga node dedicated for that text
if (node.nodeValue) {
applySize(yogaNode, node.nodeValue, style.width, style.height);
}
}
else if (node.textContent) {
// Nodes with only text have a child Yoga node dedicated for that text
applySize(yogaNode, node.textContent, style.width, style.height);
}
else {
const childNodes = node.childNodes.filter(childNode => {
return skipStaticElements ? !childNode.unstable__static : true;
});
for (const [index, childNode] of Object.entries(childNodes)) {
const { yogaNode: childYogaNode } = exports.buildLayout(childNode, options);
if (childYogaNode) {
yogaNode.insertChild(childYogaNode, Number.parseInt(index, 10));
}
}
}
return node;
} // Apply margin, padding, flex, etc styles
(0, _applyStyles.default)(yogaNode, style); // Nodes with only text have a child Yoga node dedicated for that text
if (node.textContent || node.nodeValue) {
const {
width,
height
} = (0, _measureText.default)(node.textContent || node.nodeValue);
yogaNode.setWidth(style.width || width);
yogaNode.setHeight(style.height || height);
return node;
}
if (Array.isArray(node.childNodes) && node.childNodes.length > 0) {
const childNodes = node.childNodes.filter(childNode => {
return skipStaticElements ? !childNode.unstable__static : true;
});
for (const [index, childNode] of Object.entries(childNodes)) {
const {
yogaNode: childYogaNode
} = buildLayout(childNode, options);
yogaNode.insertChild(childYogaNode, index);
}
}
return node;
};
var _default = buildLayout;
exports.default = _default;
const applySize = (yogaNode, text, nodeWidth, nodeHeight) => {
const { width, height } = measure_text_1.measureText(text);
yogaNode.setWidth(nodeWidth !== null && nodeWidth !== void 0 ? nodeWidth : width);
yogaNode.setHeight(nodeHeight !== null && nodeHeight !== void 0 ? nodeHeight : height);
};
//# sourceMappingURL=build-layout.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _measureText = _interopRequireDefault(require("./measure-text"));
var _wrapText = _interopRequireDefault(require("./wrap-text"));
var _getMaxWidth = _interopRequireDefault(require("./get-max-width"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
Object.defineProperty(exports, "__esModule", { value: true });
const measure_text_1 = require("./measure-text");
const wrap_text_1 = require("./wrap-text");
const get_max_width_1 = require("./get-max-width");
// Since we need to know the width of text container to wrap text, we have to calculate layout twice
// This function is executed after first layout calculation to reassign width and height of text nodes
const calculateWrappedText = node => {
if (node.textContent && typeof node.parentNode.style.textWrap === 'string') {
const {
yogaNode
} = node;
const parentYogaNode = node.parentNode.yogaNode;
const maxWidth = (0, _getMaxWidth.default)(parentYogaNode);
const currentWidth = yogaNode.getComputedWidth();
if (currentWidth > maxWidth) {
const {
textWrap
} = node.parentNode.style;
const wrappedText = (0, _wrapText.default)(node.textContent, maxWidth, {
textWrap
});
const {
width,
height
} = (0, _measureText.default)(wrappedText);
yogaNode.setWidth(width);
yogaNode.setHeight(height);
exports.calculateWrappedText = (node) => {
var _a;
if (node.nodeName !== '#text') {
if (node.textContent &&
typeof ((_a = node.parentNode) === null || _a === void 0 ? void 0 : _a.style.textWrap) === 'string') {
const { yogaNode: parentYogaNode } = node.parentNode;
const maxWidth = parentYogaNode ? get_max_width_1.getMaxWidth(parentYogaNode) : 0;
const { yogaNode } = node;
if (yogaNode) {
const currentWidth = yogaNode.getComputedWidth();
if (currentWidth > maxWidth) {
const { textWrap } = node.parentNode.style;
const wrappedText = wrap_text_1.wrapText(node.textContent, maxWidth, {
textWrap
});
const { width, height } = measure_text_1.measureText(wrappedText);
yogaNode.setWidth(width);
yogaNode.setHeight(height);
}
}
}
for (const childNode of node.childNodes) {
exports.calculateWrappedText(childNode);
}
}
return;
}
if (Array.isArray(node.childNodes) && node.childNodes.length > 0) {
for (const childNode of node.childNodes) {
calculateWrappedText(childNode);
}
}
};
var _default = calculateWrappedText;
exports.default = _default;
//# sourceMappingURL=calculate-wrapped-text.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
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;
});
exports.default = void 0;
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _cliCursor = _interopRequireDefault(require("cli-cursor"));
var _AppContext = _interopRequireDefault(require("./AppContext"));
var _StdinContext = _interopRequireDefault(require("./StdinContext"));
var _StdoutContext = _interopRequireDefault(require("./StdoutContext"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
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.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 });
/* eslint-disable @typescript-eslint/prefer-nullish-coalescing */
const react_1 = __importStar(require("react"));
const cli_cursor_1 = __importDefault(require("cli-cursor"));
const AppContext_1 = __importDefault(require("./AppContext"));
const StdinContext_1 = __importDefault(require("./StdinContext"));
const StdoutContext_1 = __importDefault(require("./StdoutContext"));
const StderrContext_1 = __importDefault(require("./StderrContext"));
const FocusContext_1 = __importDefault(require("./FocusContext"));
const ErrorOverview_1 = __importDefault(require("./ErrorOverview"));
const TAB = '\t';
const SHIFT_TAB = '\u001B[Z';
const ESC = '\u001B';
// Root component for all Ink apps
// It renders stdin and stdout contexts, so that children can access them if needed
// It also handles Ctrl+C exiting and cursor visibility
class App extends _react.PureComponent {
// Determines if TTY is supported on the provided stdin
isRawModeSupported() {
return this.props.stdin.isTTY;
}
constructor() {
super(); // Count how many components enabled raw mode to avoid disabling
// raw mode until all components don't need it anymore
_defineProperty(this, "handleSetRawMode", isEnabled => {
const {
stdin
} = this.props;
if (!this.isRawModeSupported()) {
if (stdin === process.stdin) {
throw new Error('Raw mode is not supported on the current process.stdin, which Ink uses as input stream by default.\nRead about how to prevent this error on https://github.com/vadimdemedes/ink/#israwmodesupported');
} else {
throw new Error('Raw mode is not supported on the stdin provided to Ink.\nRead about how to prevent this error on https://github.com/vadimdemedes/ink/#israwmodesupported');
class App extends react_1.PureComponent {
constructor() {
super(...arguments);
this.state = {
isFocusEnabled: true,
activeFocusId: undefined,
focusables: [],
error: undefined
};
// Count how many components enabled raw mode to avoid disabling
// raw mode until all components don't need it anymore
this.rawModeEnabledCount = 0;
this.handleSetRawMode = (isEnabled) => {
const { stdin } = this.props;
if (!this.isRawModeSupported()) {
if (stdin === process.stdin) {
throw new Error('Raw mode is not supported on the current process.stdin, which Ink uses as input stream by default.\nRead about how to prevent this error on https://github.com/vadimdemedes/ink/#israwmodesupported');
}
else {
throw new Error('Raw mode is not supported on the stdin provided to Ink.\nRead about how to prevent this error on https://github.com/vadimdemedes/ink/#israwmodesupported');
}
}
stdin.setEncoding('utf8');
if (isEnabled) {
// Ensure raw mode is enabled only once
if (this.rawModeEnabledCount === 0) {
stdin.addListener('data', this.handleInput);
stdin.resume();
stdin.setRawMode(true);
}
this.rawModeEnabledCount++;
return;
}
// Disable raw mode only when no components left that are using it
if (--this.rawModeEnabledCount === 0) {
stdin.setRawMode(false);
stdin.removeListener('data', this.handleInput);
stdin.pause();
}
};
this.handleInput = (input) => {
// Exit on Ctrl+C
// eslint-disable-next-line unicorn/no-hex-escape
if (input === '\x03' && this.props.exitOnCtrlC) {
this.handleExit();
}
// Reset focus when there's an active focused component on Esc
if (input === ESC && this.state.activeFocusId) {
this.setState({
activeFocusId: undefined
});
}
if (this.state.isFocusEnabled && this.state.focusables.length > 0) {
if (input === TAB) {
this.focusNext();
}
if (input === SHIFT_TAB) {
this.focusPrevious();
}
}
};
this.handleExit = (error) => {
if (this.isRawModeSupported()) {
this.handleSetRawMode(false);
}
this.props.onExit(error);
};
this.enableFocus = () => {
this.setState({
isFocusEnabled: true
});
};
this.disableFocus = () => {
this.setState({
isFocusEnabled: false
});
};
this.focusNext = () => {
this.setState(previousState => {
const firstFocusableId = previousState.focusables[0].id;
const nextFocusableId = this.findNextFocusable(previousState);
return {
activeFocusId: nextFocusableId || firstFocusableId
};
});
};
this.focusPrevious = () => {
this.setState(previousState => {
const lastFocusableId = previousState.focusables[previousState.focusables.length - 1].id;
const previousFocusableId = this.findPreviousFocusable(previousState);
return {
activeFocusId: previousFocusableId || lastFocusableId
};
});
};
this.addFocusable = (id, { autoFocus }) => {
this.setState(previousState => {
let nextFocusId = previousState.activeFocusId;
if (!nextFocusId && autoFocus) {
nextFocusId = id;
}
return {
activeFocusId: nextFocusId,
focusables: [
...previousState.focusables,
{
id,
isActive: true
}
]
};
});
};
this.removeFocusable = (id) => {
this.setState(previousState => ({
activeFocusId: previousState.activeFocusId === id
? undefined
: previousState.activeFocusId,
focusables: previousState.focusables.filter(focusable => {
return focusable.id !== id;
})
}));
};
this.activateFocusable = (id) => {
this.setState(previousState => ({
focusables: previousState.focusables.map(focusable => {
if (focusable.id !== id) {
return focusable;
}
return {
id,
isActive: true
};
})
}));
};
this.deactivateFocusable = (id) => {
this.setState(previousState => ({
activeFocusId: previousState.activeFocusId === id
? undefined
: previousState.activeFocusId,
focusables: previousState.focusables.map(focusable => {
if (focusable.id !== id) {
return focusable;
}
return {
id,
isActive: false
};
})
}));
};
this.findNextFocusable = (state) => {
const activeIndex = state.focusables.findIndex(focusable => {
return focusable.id === state.activeFocusId;
});
for (let index = activeIndex + 1; index < state.focusables.length; index++) {
if (state.focusables[index].isActive) {
return state.focusables[index].id;
}
}
return undefined;
};
this.findPreviousFocusable = (state) => {
const activeIndex = state.focusables.findIndex(focusable => {
return focusable.id === state.activeFocusId;
});
for (let index = activeIndex - 1; index >= 0; index--) {
if (state.focusables[index].isActive) {
return state.focusables[index].id;
}
}
return undefined;
};
}
static getDerivedStateFromError(error) {
return { error };
}
// Determines if TTY is supported on the provided stdin
isRawModeSupported() {
return this.props.stdin.isTTY;
}
render() {
return (react_1.default.createElement(AppContext_1.default.Provider, { value: {
exit: this.handleExit
} },
react_1.default.createElement(StdinContext_1.default.Provider, { value: {
stdin: this.props.stdin,
setRawMode: this.handleSetRawMode,
isRawModeSupported: this.isRawModeSupported()
} },
react_1.default.createElement(StdoutContext_1.default.Provider, { value: {
stdout: this.props.stdout,
write: this.props.writeToStdout
} },
react_1.default.createElement(StderrContext_1.default.Provider, { value: {
stderr: this.props.stderr,
write: this.props.writeToStderr
} },
react_1.default.createElement(FocusContext_1.default.Provider, { value: {
activeId: this.state.activeFocusId,
add: this.addFocusable,
remove: this.removeFocusable,
activate: this.activateFocusable,
deactivate: this.deactivateFocusable,
enableFocus: this.enableFocus,
disableFocus: this.disableFocus,
focusNext: this.focusNext,
focusPrevious: this.focusPrevious
} }, this.state.error ? (react_1.default.createElement(ErrorOverview_1.default, { error: this.state.error })) : (this.props.children)))))));
}
componentDidMount() {
cli_cursor_1.default.hide(this.props.stdout);
}
componentWillUnmount() {
cli_cursor_1.default.show(this.props.stdout);
// ignore calling setRawMode on an handle stdin it cannot be called
if (this.isRawModeSupported()) {
this.handleSetRawMode(false);
}
}
stdin.setEncoding('utf8');
if (isEnabled) {
// Ensure raw mode is enabled only once
if (this.rawModeEnabledCount === 0) {
stdin.addListener('data', this.handleInput);
stdin.resume();
stdin.setRawMode(true);
}
this.rawModeEnabledCount++;
return;
} // Disable raw mode only when no components left that are using it
if (--this.rawModeEnabledCount === 0) {
stdin.setRawMode(false);
stdin.removeListener('data', this.handleInput);
stdin.pause();
}
});
_defineProperty(this, "handleInput", input => {
// Exit on Ctrl+C
if (input === '\x03' && this.props.exitOnCtrlC) {
// eslint-disable-line unicorn/no-hex-escape
this.handleExit();
}
});
_defineProperty(this, "handleExit", error => {
if (this.isRawModeSupported()) {
this.handleSetRawMode(false);
}
this.props.onExit(error);
});
this.rawModeEnabledCount = 0;
}
render() {
return _react.default.createElement(_AppContext.default.Provider, {
value: {
exit: this.handleExit
}
}, _react.default.createElement(_StdinContext.default.Provider, {
value: {
stdin: this.props.stdin,
setRawMode: this.handleSetRawMode,
isRawModeSupported: this.isRawModeSupported()
}
}, _react.default.createElement(_StdoutContext.default.Provider, {
value: {
stdout: this.props.stdout
}
}, this.props.children)));
}
componentDidMount() {
_cliCursor.default.hide(this.props.stdout);
}
componentWillUnmount() {
_cliCursor.default.show(this.props.stdout); // ignore calling setRawMode on an handle stdin it cannot be called
if (this.isRawModeSupported()) {
this.handleSetRawMode(false);
}
}
componentDidCatch(error) {
this.handleExit(error);
}
componentDidCatch(error) {
this.handleExit(error);
}
}
exports.default = App;
_defineProperty(App, "propTypes", {
children: _propTypes.default.node.isRequired,
stdin: _propTypes.default.object.isRequired,
stdout: _propTypes.default.object.isRequired,
exitOnCtrlC: _propTypes.default.bool.isRequired,
// eslint-disable-line react/boolean-prop-naming
onExit: _propTypes.default.func.isRequired
});
App.displayName = 'InternalApp';
//# sourceMappingURL=App.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
Object.defineProperty(exports, "__esModule", { value: true });
const react_1 = require("react");
/**
* `AppContext` is a React context, which exposes a method to manually exit the app (unmount).
*/
const AppContext = react_1.createContext({
exit: () => { }
});
exports.default = void 0;
var _react = _interopRequireDefault(require("react"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _default = _react.default.createContext({
exit() {}
});
exports.default = _default;
AppContext.displayName = 'InternalAppContext';
exports.default = AppContext;
//# sourceMappingURL=AppContext.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
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;
});
exports.default = void 0;
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
class Box extends _react.PureComponent {
constructor() {
super();
this.nodeRef = _react.default.createRef();
}
render() {
const _this$props = this.props,
{
children,
unstable__transformChildren
} = _this$props,
style = _objectWithoutProperties(_this$props, ["children", "unstable__transformChildren"]);
return _react.default.createElement("div", {
ref: this.nodeRef,
style: style,
unstable__transformChildren: unstable__transformChildren
}, children);
}
unstable__getComputedWidth() {
return this.nodeRef.current.yogaNode.getComputedWidth();
}
}
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.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
/* eslint-disable @typescript-eslint/prefer-nullish-coalescing */
const react_1 = __importStar(require("react"));
/**
* `<Box>` is an essential Ink component to build your layout. It's like `<div style="display: flex">` in the browser.
*/
const Box = react_1.forwardRef((_a, ref) => {
var { children } = _a, style = __rest(_a, ["children"]);
const transformedStyle = Object.assign(Object.assign({}, style), { marginLeft: style.marginLeft || style.marginX || style.margin || 0, marginRight: style.marginRight || style.marginX || style.margin || 0, marginTop: style.marginTop || style.marginY || style.margin || 0, marginBottom: style.marginBottom || style.marginY || style.margin || 0, paddingLeft: style.paddingLeft || style.paddingX || style.padding || 0, paddingRight: style.paddingRight || style.paddingX || style.padding || 0, paddingTop: style.paddingTop || style.paddingY || style.padding || 0, paddingBottom: style.paddingBottom || style.paddingY || style.padding || 0 });
return (react_1.default.createElement("ink-box", { ref: ref, style: transformedStyle }, children));
});
Box.displayName = 'Box';
Box.defaultProps = {
flexDirection: 'row',
flexGrow: 0,
flexShrink: 1
};
exports.default = Box;
_defineProperty(Box, "propTypes", {
margin: _propTypes.default.number,
marginX: _propTypes.default.number,
marginY: _propTypes.default.number,
marginTop: _propTypes.default.number,
marginBottom: _propTypes.default.number,
marginLeft: _propTypes.default.number,
marginRight: _propTypes.default.number,
padding: _propTypes.default.number,
paddingX: _propTypes.default.number,
paddingY: _propTypes.default.number,
paddingTop: _propTypes.default.number,
paddingBottom: _propTypes.default.number,
paddingLeft: _propTypes.default.number,
paddingRight: _propTypes.default.number,
width: _propTypes.default.oneOfType([_propTypes.default.number, _propTypes.default.string]),
minWidth: _propTypes.default.number,
height: _propTypes.default.oneOfType([_propTypes.default.number, _propTypes.default.string]),
minHeight: _propTypes.default.number,
flexGrow: _propTypes.default.number,
flexShrink: _propTypes.default.number,
flexDirection: _propTypes.default.oneOf(['row', 'row-reverse', 'column', 'column-reverse']),
flexBasis: _propTypes.default.oneOfType([_propTypes.default.number, _propTypes.default.string]),
alignItems: _propTypes.default.oneOf(['stretch', 'flex-start', 'center', 'flex-end']),
justifyContent: _propTypes.default.oneOf(['flex-start', 'center', 'flex-end', 'space-between', 'space-around']),
textWrap: _propTypes.default.oneOf(['wrap', 'truncate', 'truncate-start', 'truncate-middle', 'truncate-end']),
unstable__transformChildren: _propTypes.default.func,
children: _propTypes.default.node
});
_defineProperty(Box, "defaultProps", {
flexDirection: 'row',
flexGrow: 0,
flexShrink: 1
});
//# sourceMappingURL=Box.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
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;
});
exports.default = void 0;
var _react = _interopRequireDefault(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _arrify = _interopRequireDefault(require("arrify"));
var _chalk = _interopRequireDefault(require("chalk"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
const methods = ['hex', 'hsl', 'hsv', 'hwb', 'rgb', 'keyword', 'bgHex', 'bgHsl', 'bgHsv', 'bgHwb', 'bgRgb', 'bgKeyword'];
const Color = (_ref) => {
let {
children
} = _ref,
colorProps = _objectWithoutProperties(_ref, ["children"]);
if (children === '') {
return null;
}
const transformChildren = children => {
Object.keys(colorProps).forEach(method => {
if (colorProps[method]) {
if (methods.includes(method)) {
children = _chalk.default[method](...(0, _arrify.default)(colorProps[method]))(children);
} else if (typeof _chalk.default[method] === 'function') {
children = _chalk.default[method](children);
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
}
});
return children;
};
return _react.default.createElement("span", {
style: {
flexDirection: 'row'
},
unstable__transformChildren: transformChildren
}, children);
return t;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const react_1 = __importStar(require("react"));
const prop_types_1 = __importDefault(require("prop-types"));
const arrify_1 = __importDefault(require("arrify"));
const chalk_1 = __importDefault(require("chalk"));
const Transform_1 = __importDefault(require("./Transform"));
const methods = [
'hex',
'hsl',
'hsv',
'hwb',
'rgb',
'keyword',
'bgHex',
'bgHsl',
'bgHsv',
'bgHwb',
'bgRgb',
'bgKeyword',
'ansi',
'ansi256',
'bgAnsi',
'bgAnsi256'
];
/**
* The `<Color>` compoment is a simple wrapper around the `chalk` API. It supports all of the `chalk`'s methods as `props`.
*/
const Color = (_a) => {
var { children } = _a, colorProps = __rest(_a, ["children"]);
if (children === '') {
return null;
}
const transform = (children) => {
// @ts-ignore
Object.keys(colorProps).forEach((method) => {
if (colorProps[method]) {
if (methods.includes(method)) {
children = chalk_1.default[method](...arrify_1.default(colorProps[method]))(children);
}
else if (typeof chalk_1.default[method] === 'function') {
children = chalk_1.default[method](children);
}
}
});
return children;
};
return react_1.default.createElement(Transform_1.default, { transform: transform }, children);
};
Color.displayName = 'Color';
Color.propTypes = {
children: _propTypes.default.node
children: prop_types_1.default.node
};
Color.defaultProps = {
children: ''
children: ''
};
var _default = Color;
exports.default = _default;
exports.default = react_1.memo(Color);
//# sourceMappingURL=Color.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
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;
});
exports.default = void 0;
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
const childrenToArray = children => Array.isArray(children) ? children : [children]; // This component allows developers to render output before main output from all the other components.
// The reason it's called <Static> is it's append-only output. Output from <Static> components
// is written permanently to stdout and is never updated afterwards. If <Static> component
// receives new children, Ink will detect the changes and write them to stdout.
// In order for this mechanism to work perfectly, <Static> children must never update their output
// once they've been appended to <Static>.
//
// A good example of where this component might be useful is interface like Jest's.
// When running tests, Jest keeps writing completed tests to output, while continuously
// rendering test stats at the end of the output.
class Static extends _react.Component {
constructor(...args) {
super(...args);
_defineProperty(this, "state", {
lastIndex: null
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.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const react_1 = __importStar(require("react"));
/**
* `<Static>` component permanently renders its output above everything else.
* It's useful for displaying activity like completed tasks or logs - things that
* are not changing after they're rendered (hence the name "Static").
*
* It's preferred to use `<Static>` for use cases like these, when you can't know
* or control the amount of items that need to be rendered.
*
* For example, [Tap](https://github.com/tapjs/node-tap) uses `<Static>` to display
* a list of completed tests. [Gatsby](https://github.com/gatsbyjs/gatsby) uses it
* to display a list of generated pages, while still displaying a live progress bar.
*/
const Static = (props) => {
const { items, children: render, style: customStyle } = props;
const [index, setIndex] = react_1.useState(0);
const itemsToRender = react_1.useMemo(() => {
return items.slice(index);
}, [items, index]);
react_1.useEffect(() => {
setIndex(items.length);
}, [items.length]);
const children = itemsToRender.map((item, itemIndex) => {
return render(item, index + itemIndex);
});
}
render() {
const _this$props = this.props,
{
children
} = _this$props,
otherProps = _objectWithoutProperties(_this$props, ["children"]);
const {
lastIndex
} = this.state;
let newChildren = children;
if (typeof lastIndex === 'number') {
newChildren = childrenToArray(children).slice(lastIndex);
}
return _react.default.createElement("div", {
unstable__static: true,
style: _objectSpread({
position: 'absolute',
flexDirection: 'column'
}, otherProps)
}, newChildren);
}
componentDidMount() {
this.saveLastIndex(this.props.children);
}
componentDidUpdate(prevProps, prevState) {
if (prevState.lastIndex === this.state.lastIndex) {
this.saveLastIndex(this.props.children);
}
}
saveLastIndex(children) {
const nextIndex = childrenToArray(children).length;
if (this.state.lastIndex !== nextIndex) {
this.setState({
lastIndex: nextIndex
});
}
}
}
const style = react_1.useMemo(() => (Object.assign({ position: 'absolute', flexDirection: 'column' }, customStyle)), [customStyle]);
return (react_1.default.createElement("ink-box", {
// @ts-ignore
internal_static: true, style: style }, children));
};
Static.displayName = 'Static';
exports.default = Static;
_defineProperty(Static, "propTypes", {
children: _propTypes.default.node
});
//# sourceMappingURL=Static.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
Object.defineProperty(exports, "__esModule", { value: true });
const react_1 = require("react");
/**
* `StdinContext` is a React context, which exposes input stream.
*/
const StdinContext = react_1.createContext({
stdin: undefined,
setRawMode: () => { },
isRawModeSupported: false
});
exports.default = void 0;
var _react = _interopRequireDefault(require("react"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _default = _react.default.createContext({
stdin: undefined,
setRawMode: undefined
});
exports.default = _default;
StdinContext.displayName = 'InternalStdinContext';
exports.default = StdinContext;
//# sourceMappingURL=StdinContext.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
Object.defineProperty(exports, "__esModule", { value: true });
const react_1 = require("react");
/**
* `StdoutContext` is a React context, which exposes stdout stream, where Ink renders your app.
*/
const StdoutContext = react_1.createContext({
stdout: undefined,
write: () => { }
});
exports.default = void 0;
var _react = _interopRequireDefault(require("react"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _default = _react.default.createContext({
stdout: undefined
});
exports.default = _default;
StdoutContext.displayName = 'InternalStdoutContext';
exports.default = StdoutContext;
//# sourceMappingURL=StdoutContext.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _react = _interopRequireDefault(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _chalk = _interopRequireDefault(require("chalk"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* eslint-disable camelcase */
const Text = ({
bold,
italic,
underline,
strikethrough,
children,
unstable__transformChildren
}) => {
const transformChildren = children => {
if (bold) {
children = _chalk.default.bold(children);
}
if (italic) {
children = _chalk.default.italic(children);
}
if (underline) {
children = _chalk.default.underline(children);
}
if (strikethrough) {
children = _chalk.default.strikethrough(children);
}
if (unstable__transformChildren) {
children = unstable__transformChildren(children);
}
return children;
};
return _react.default.createElement("span", {
style: {
flexDirection: 'row'
},
unstable__transformChildren: transformChildren
}, children);
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
/* eslint-disable react/boolean-prop-naming */
Text.propTypes = {
bold: _propTypes.default.bool,
italic: _propTypes.default.bool,
underline: _propTypes.default.bool,
strikethrough: _propTypes.default.bool,
children: _propTypes.default.node.isRequired,
unstable__transformChildren: _propTypes.default.func
Object.defineProperty(exports, "__esModule", { value: true });
const react_1 = __importDefault(require("react"));
const chalk_1 = __importDefault(require("chalk"));
const colorize_1 = __importDefault(require("../colorize"));
/**
* This component can display text, and change its style to make it colorful, bold, underline, italic or strikethrough.
*/
const Text = ({ color, backgroundColor, dimColor, bold, italic, underline, strikethrough, wrap, children }) => {
const transform = (children) => {
if (dimColor) {
children = chalk_1.default.dim(children);
}
if (color) {
children = colorize_1.default(children, color, 'foreground');
}
if (backgroundColor) {
children = colorize_1.default(children, backgroundColor, 'background');
}
if (bold) {
children = chalk_1.default.bold(children);
}
if (italic) {
children = chalk_1.default.italic(children);
}
if (underline) {
children = chalk_1.default.underline(children);
}
if (strikethrough) {
children = chalk_1.default.strikethrough(children);
}
return children;
};
return (react_1.default.createElement("ink-text", { style: { flexGrow: 0, flexShrink: 1, flexDirection: 'row', textWrap: wrap }, internal_transform: transform }, children));
};
/* eslint-enable react/boolean-prop-naming */
Text.displayName = 'Text';
Text.defaultProps = {
bold: false,
italic: false,
underline: false,
strikethrough: false,
unstable__transformChildren: undefined
dimColor: false,
bold: false,
italic: false,
underline: false,
strikethrough: false,
wrap: 'wrap'
};
var _default = Text;
exports.default = _default;
exports.default = Text;
//# sourceMappingURL=Text.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createTextNode = exports.setAttribute = exports.removeChildNode = exports.insertBeforeNode = exports.appendStaticNode = exports.appendChildNode = exports.createNode = void 0;
// Helper utilities implementing some common DOM methods to simplify reconciliation code
const createNode = tagName => ({
nodeName: tagName.toUpperCase(),
style: {},
attributes: {},
childNodes: [],
parentNode: null
});
exports.createNode = createNode;
const appendChildNode = (node, childNode) => {
if (childNode.parentNode) {
removeChildNode(childNode.parentNode, childNode);
}
childNode.parentNode = node;
node.childNodes.push(childNode);
}; // Same as `appendChildNode`, but without removing child node from parent node
exports.appendChildNode = appendChildNode;
const appendStaticNode = (node, childNode) => {
node.childNodes.push(childNode);
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
exports.appendStaticNode = appendStaticNode;
const insertBeforeNode = (node, newChildNode, beforeChildNode) => {
if (newChildNode.parentNode) {
removeChildNode(newChildNode.parentNode, newChildNode);
}
newChildNode.parentNode = node;
const index = node.childNodes.indexOf(beforeChildNode);
if (index >= 0) {
node.childNodes.splice(index, 0, newChildNode);
return;
}
node.childNodes.push(newChildNode);
Object.defineProperty(exports, "__esModule", { value: true });
exports.setTextNodeValue = exports.createTextNode = exports.setStyle = exports.setAttribute = exports.removeChildNode = exports.insertBeforeNode = exports.appendChildNode = exports.createNode = exports.TEXT_NAME = void 0;
const yoga_layout_prebuilt_1 = __importDefault(require("yoga-layout-prebuilt"));
const measure_text_1 = __importDefault(require("./measure-text"));
const styles_1 = __importDefault(require("./styles"));
const wrap_text_1 = __importDefault(require("./wrap-text"));
const squash_text_nodes_1 = __importDefault(require("./squash-text-nodes"));
exports.TEXT_NAME = '#text';
exports.createNode = (nodeName) => {
var _a;
const node = {
nodeName,
style: {},
attributes: {},
childNodes: [],
parentNode: null,
yogaNode: nodeName === 'ink-virtual-text' ? undefined : yoga_layout_prebuilt_1.default.Node.create()
};
if (nodeName === 'ink-text') {
(_a = node.yogaNode) === null || _a === void 0 ? void 0 : _a.setMeasureFunc(measureTextNode.bind(null, node));
}
return node;
};
exports.insertBeforeNode = insertBeforeNode;
const removeChildNode = (node, removeNode) => {
removeNode.parentNode = null;
const index = node.childNodes.indexOf(removeNode);
if (index >= 0) {
node.childNodes.splice(index, 1);
}
exports.appendChildNode = (node, childNode) => {
var _a;
if (childNode.parentNode) {
exports.removeChildNode(childNode.parentNode, childNode);
}
childNode.parentNode = node;
node.childNodes.push(childNode);
if (childNode.yogaNode) {
(_a = node.yogaNode) === null || _a === void 0 ? void 0 : _a.insertChild(childNode.yogaNode, node.yogaNode.getChildCount());
}
};
exports.removeChildNode = removeChildNode;
const setAttribute = (node, key, value) => {
node.attributes[key] = value;
exports.insertBeforeNode = (node, newChildNode, beforeChildNode) => {
var _a, _b;
if (newChildNode.parentNode) {
exports.removeChildNode(newChildNode.parentNode, newChildNode);
}
newChildNode.parentNode = node;
const index = node.childNodes.indexOf(beforeChildNode);
if (index >= 0) {
node.childNodes.splice(index, 0, newChildNode);
if (newChildNode.yogaNode) {
(_a = node.yogaNode) === null || _a === void 0 ? void 0 : _a.insertChild(newChildNode.yogaNode, index);
}
return;
}
node.childNodes.push(newChildNode);
if (newChildNode.yogaNode) {
(_b = node.yogaNode) === null || _b === void 0 ? void 0 : _b.insertChild(newChildNode.yogaNode, node.yogaNode.getChildCount());
}
};
exports.setAttribute = setAttribute;
const createTextNode = text => ({
nodeName: '#text',
nodeValue: text
});
exports.createTextNode = createTextNode;
exports.removeChildNode = (node, removeNode) => {
var _a, _b;
if (removeNode.yogaNode) {
(_b = (_a = removeNode.parentNode) === null || _a === void 0 ? void 0 : _a.yogaNode) === null || _b === void 0 ? void 0 : _b.removeChild(removeNode.yogaNode);
}
removeNode.parentNode = null;
const index = node.childNodes.indexOf(removeNode);
if (index >= 0) {
node.childNodes.splice(index, 1);
}
};
exports.setAttribute = (node, key, value) => {
node.attributes[key] = value;
};
exports.setStyle = (node, style) => {
node.style = style;
if (node.yogaNode) {
styles_1.default(node.yogaNode, style);
}
};
exports.createTextNode = (text) => {
const node = {
nodeName: '#text',
nodeValue: text,
yogaNode: undefined,
parentNode: null,
style: {}
};
exports.setTextNodeValue(node, text);
return node;
};
const measureTextNode = function (node, width) {
var _a, _b;
const text = node.nodeName === '#text' ? node.nodeValue : squash_text_nodes_1.default(node);
const dimensions = measure_text_1.default(text);
// Text fits into container, no need to wrap
if (dimensions.width <= width) {
return dimensions;
}
// This is happening when <Box> is shrinking child nodes and Yoga asks
// if we can fit this text node in a <1px space, so we just tell Yoga "no"
if (dimensions.width >= 1 && width > 0 && width < 1) {
return dimensions;
}
const textWrap = (_b = (_a = node.style) === null || _a === void 0 ? void 0 : _a.textWrap) !== null && _b !== void 0 ? _b : 'wrap';
const wrappedText = wrap_text_1.default(text, width, textWrap);
return measure_text_1.default(wrappedText);
};
const findParentYogaNode = (node) => {
var _a;
if (!node || !node.parentNode) {
return undefined;
}
return (_a = node.yogaNode) !== null && _a !== void 0 ? _a : findParentYogaNode(node.parentNode);
};
exports.setTextNodeValue = (node, text) => {
if (typeof text !== 'string') {
text = String(text);
}
node.nodeValue = text;
// Mark parent Yoga node as dirty to measure text dimensions again
const parentYogaNode = findParentYogaNode(node);
parentYogaNode === null || parentYogaNode === void 0 ? void 0 : parentYogaNode.markDirty();
};
//# sourceMappingURL=dom.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _default = yogaNode => {
return yogaNode.getComputedWidth() - yogaNode.getComputedPadding() * 2;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
exports.default = _default;
Object.defineProperty(exports, "__esModule", { value: true });
const yoga_layout_prebuilt_1 = __importDefault(require("yoga-layout-prebuilt"));
exports.default = (yogaNode) => {
return (yogaNode.getComputedWidth() -
yogaNode.getComputedPadding(yoga_layout_prebuilt_1.default.EDGE_LEFT) -
yogaNode.getComputedPadding(yoga_layout_prebuilt_1.default.EDGE_RIGHT) -
yogaNode.getComputedBorder(yoga_layout_prebuilt_1.default.EDGE_LEFT) -
yogaNode.getComputedBorder(yoga_layout_prebuilt_1.default.EDGE_RIGHT));
};
//# sourceMappingURL=get-max-width.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _react = require("react");
var _AppContext = _interopRequireDefault(require("../components/AppContext"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _default = () => (0, _react.useContext)(_AppContext.default);
exports.default = _default;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const react_1 = require("react");
const AppContext_1 = __importDefault(require("../components/AppContext"));
/**
* `useApp` is a React hook, which exposes a method to manually exit the app (unmount).
*/
const useApp = () => react_1.useContext(AppContext_1.default);
exports.default = useApp;
//# sourceMappingURL=use-app.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _react = require("react");
var _ = require("..");
var _default = inputHandler => {
const {
stdin,
setRawMode
} = (0, _react.useContext)(_.StdinContext);
(0, _react.useEffect)(() => {
setRawMode(true);
return () => {
setRawMode(false);
};
}, [setRawMode]);
(0, _react.useEffect)(() => {
const handleData = data => {
let input = String(data);
const key = {
upArrow: input === '\u001B[A',
downArrow: input === '\u001B[B',
leftArrow: input === '\u001B[D',
rightArrow: input === '\u001B[C',
return: input === '\r',
escape: input === '\u001B',
ctrl: false,
shift: false,
meta: false
}; // Copied from `keypress` module
if (input <= '\u001A' && !key.return) {
input = String.fromCharCode(input.charCodeAt(0) + 'a'.charCodeAt(0) - 1);
key.ctrl = true;
}
if (input[0] === '\u001B') {
input = input.slice(1);
key.meta = true;
}
const isLatinUppercase = input >= 'A' && input <= 'Z';
const isCyrillicUppercase = input >= 'А' && input <= 'Я';
if (input.length === 1 && (isLatinUppercase || isCyrillicUppercase)) {
key.shift = true;
}
inputHandler(input, key);
};
stdin.on('data', handleData);
return () => {
stdin.off('data', handleData);
};
}, [stdin, inputHandler]);
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
exports.default = _default;
Object.defineProperty(exports, "__esModule", { value: true });
const react_1 = require("react");
const use_stdin_1 = __importDefault(require("./use-stdin"));
/**
* This hook is used for handling user input.
* It's a more convienient alternative to using `StdinContext` and listening to `data` events.
* The callback you pass to `useInput` is called for each character when user enters any input.
* However, if user pastes text and it's more than one character, the callback will be called only once and the whole string will be passed as `input`.
*
* ```
* import {useInput} from 'ink';
*
* const UserInput = () => {
* useInput((input, key) => {
* if (input === 'q') {
* // Exit program
* }
*
* if (key.leftArrow) {
* // Left arrow key pressed
* }
* });
*
* return …
* };
* ```
*/
const useInput = (inputHandler, options = {}) => {
const { stdin, setRawMode } = use_stdin_1.default();
react_1.useEffect(() => {
if (options.isActive === false) {
return;
}
setRawMode(true);
return () => {
setRawMode(false);
};
}, [options.isActive, setRawMode]);
react_1.useEffect(() => {
if (options.isActive === false) {
return;
}
const handleData = (data) => {
let input = String(data);
const key = {
upArrow: input === '\u001B[A',
downArrow: input === '\u001B[B',
leftArrow: input === '\u001B[D',
rightArrow: input === '\u001B[C',
return: input === '\r',
escape: input === '\u001B',
ctrl: false,
shift: false,
meta: false
};
// Copied from `keypress` module
if (input <= '\u001A' && !key.return) {
input = String.fromCharCode(input.charCodeAt(0) + 'a'.charCodeAt(0) - 1);
key.ctrl = true;
}
if (input.startsWith('\u001B')) {
input = input.slice(1);
key.meta = true;
}
const isLatinUppercase = input >= 'A' && input <= 'Z';
const isCyrillicUppercase = input >= 'А' && input <= 'Я';
if (input.length === 1 && (isLatinUppercase || isCyrillicUppercase)) {
key.shift = true;
}
inputHandler(input, key);
};
stdin === null || stdin === void 0 ? void 0 : stdin.on('data', handleData);
return () => {
stdin === null || stdin === void 0 ? void 0 : stdin.off('data', handleData);
};
}, [options.isActive, stdin, inputHandler]);
};
exports.default = useInput;
//# sourceMappingURL=use-input.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _react = require("react");
var _StdinContext = _interopRequireDefault(require("../components/StdinContext"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _default = () => (0, _react.useContext)(_StdinContext.default);
exports.default = _default;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const react_1 = require("react");
const StdinContext_1 = __importDefault(require("../components/StdinContext"));
/**
* `useStdin` is a React hook, which exposes stdin stream.
*/
const useStdin = () => react_1.useContext(StdinContext_1.default);
exports.default = useStdin;
//# sourceMappingURL=use-stdin.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _react = require("react");
var _StdoutContext = _interopRequireDefault(require("../components/StdoutContext"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _default = () => (0, _react.useContext)(_StdoutContext.default);
exports.default = _default;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const react_1 = require("react");
const StdoutContext_1 = __importDefault(require("../components/StdoutContext"));
/**
* `useStdout` is a React hook, which exposes stdout stream.
*/
const useStdout = () => react_1.useContext(StdoutContext_1.default);
exports.default = useStdout;
//# sourceMappingURL=use-stdout.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "render", {
enumerable: true,
get: function () {
return _render.default;
}
});
Object.defineProperty(exports, "Box", {
enumerable: true,
get: function () {
return _Box.default;
}
});
Object.defineProperty(exports, "Text", {
enumerable: true,
get: function () {
return _Text.default;
}
});
Object.defineProperty(exports, "Color", {
enumerable: true,
get: function () {
return _Color.default;
}
});
Object.defineProperty(exports, "AppContext", {
enumerable: true,
get: function () {
return _AppContext.default;
}
});
Object.defineProperty(exports, "StdinContext", {
enumerable: true,
get: function () {
return _StdinContext.default;
}
});
Object.defineProperty(exports, "StdoutContext", {
enumerable: true,
get: function () {
return _StdoutContext.default;
}
});
Object.defineProperty(exports, "Static", {
enumerable: true,
get: function () {
return _Static.default;
}
});
Object.defineProperty(exports, "useInput", {
enumerable: true,
get: function () {
return _useInput.default;
}
});
Object.defineProperty(exports, "useApp", {
enumerable: true,
get: function () {
return _useApp.default;
}
});
Object.defineProperty(exports, "useStdin", {
enumerable: true,
get: function () {
return _useStdin.default;
}
});
Object.defineProperty(exports, "useStdout", {
enumerable: true,
get: function () {
return _useStdout.default;
}
});
var _render = _interopRequireDefault(require("./render"));
var _Box = _interopRequireDefault(require("./components/Box"));
var _Text = _interopRequireDefault(require("./components/Text"));
var _Color = _interopRequireDefault(require("./components/Color"));
var _AppContext = _interopRequireDefault(require("./components/AppContext"));
var _StdinContext = _interopRequireDefault(require("./components/StdinContext"));
var _StdoutContext = _interopRequireDefault(require("./components/StdoutContext"));
var _Static = _interopRequireDefault(require("./components/Static"));
var _useInput = _interopRequireDefault(require("./hooks/use-input"));
var _useApp = _interopRequireDefault(require("./hooks/use-app"));
var _useStdin = _interopRequireDefault(require("./hooks/use-stdin"));
var _useStdout = _interopRequireDefault(require("./hooks/use-stdout"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
Object.defineProperty(exports, "__esModule", { value: true });
var render_1 = require("./render");
Object.defineProperty(exports, "render", { enumerable: true, get: function () { return render_1.default; } });
var Box_1 = require("./components/Box");
Object.defineProperty(exports, "Box", { enumerable: true, get: function () { return Box_1.default; } });
var Text_1 = require("./components/Text");
Object.defineProperty(exports, "Text", { enumerable: true, get: function () { return Text_1.default; } });
var Static_1 = require("./components/Static");
Object.defineProperty(exports, "Static", { enumerable: true, get: function () { return Static_1.default; } });
var Transform_1 = require("./components/Transform");
Object.defineProperty(exports, "Transform", { enumerable: true, get: function () { return Transform_1.default; } });
var Newline_1 = require("./components/Newline");
Object.defineProperty(exports, "Newline", { enumerable: true, get: function () { return Newline_1.default; } });
var Spacer_1 = require("./components/Spacer");
Object.defineProperty(exports, "Spacer", { enumerable: true, get: function () { return Spacer_1.default; } });
var use_input_1 = require("./hooks/use-input");
Object.defineProperty(exports, "useInput", { enumerable: true, get: function () { return use_input_1.default; } });
var use_app_1 = require("./hooks/use-app");
Object.defineProperty(exports, "useApp", { enumerable: true, get: function () { return use_app_1.default; } });
var use_stdin_1 = require("./hooks/use-stdin");
Object.defineProperty(exports, "useStdin", { enumerable: true, get: function () { return use_stdin_1.default; } });
var use_stdout_1 = require("./hooks/use-stdout");
Object.defineProperty(exports, "useStdout", { enumerable: true, get: function () { return use_stdout_1.default; } });
var use_stderr_1 = require("./hooks/use-stderr");
Object.defineProperty(exports, "useStderr", { enumerable: true, get: function () { return use_stderr_1.default; } });
var use_focus_1 = require("./hooks/use-focus");
Object.defineProperty(exports, "useFocus", { enumerable: true, get: function () { return use_focus_1.default; } });
var use_focus_manager_1 = require("./hooks/use-focus-manager");
Object.defineProperty(exports, "useFocusManager", { enumerable: true, get: function () { return use_focus_manager_1.default; } });
var measure_element_1 = require("./measure-element");
Object.defineProperty(exports, "measureElement", { enumerable: true, get: function () { return measure_element_1.default; } });
//# sourceMappingURL=index.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
Object.defineProperty(exports, "__esModule", { value: true });
// Store all instances of Ink (instance.js) to ensure that consecutive render() calls

@@ -13,4 +8,3 @@ // use the same instance of Ink and don't create a new one

// but instance.js should delete itself from the map on unmount
var _default = new WeakMap();
exports.default = _default;
exports.default = new WeakMap();
//# sourceMappingURL=instances.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _widestLine = _interopRequireDefault(require("widest-line"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _default = text => {
const width = (0, _widestLine.default)(text);
const height = text.split('\n').length;
return {
width,
height
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
exports.default = _default;
Object.defineProperty(exports, "__esModule", { value: true });
const widest_line_1 = __importDefault(require("widest-line"));
const cache = {};
exports.default = (text) => {
if (text.length === 0) {
return {
width: 0,
height: 0
};
}
if (cache[text]) {
return cache[text];
}
const width = widest_line_1.default(text);
const height = text.split('\n').length;
cache[text] = { width, height };
return { width, height };
};
//# sourceMappingURL=measure-text.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _stringLength = _interopRequireDefault(require("string-length"));
var _sliceAnsi = _interopRequireDefault(require("slice-ansi"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* "Virtual" output class
*
* Handles the positioning and saving of the output of each node in the tree.
* Also responsible for applying transformations to each character of the output.
*
* Used to generate the final output of all nodes before writing it to actual output stream (e.g. stdout)
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const slice_ansi_1 = __importDefault(require("slice-ansi"));
const string_length_1 = __importDefault(require("string-length"));
class Output {
constructor({
width,
height
}) {
// Initialize output array with a specific set of rows, so that margin/padding at the bottom is preserved
const output = [];
for (let y = 0; y < height; y++) {
output.push(' '.repeat(width));
constructor(options) {
// Initialize output array with a specific set of rows, so that margin/padding at the bottom is preserved
this.writes = [];
const { width, height } = options;
this.width = width;
this.height = height;
}
this.output = output;
}
write(x, y, text, {
transformers
}) {
if (!text) {
return;
write(x, y, text, options) {
const { transformers } = options;
if (!text) {
return;
}
this.writes.push({ x, y, text, transformers });
}
const lines = text.split('\n');
let offsetY = 0;
for (let line of lines) {
const length = (0, _stringLength.default)(line);
const currentLine = this.output[y + offsetY]; // Line can be missing if `text` is taller than height of pre-initialized `this.output`
if (!currentLine) {
continue;
}
for (const transformer of transformers) {
line = transformer(line);
}
this.output[y + offsetY] = (0, _sliceAnsi.default)(currentLine, 0, x) + line + (0, _sliceAnsi.default)(currentLine, x + length);
offsetY++;
get() {
const output = [];
for (let y = 0; y < this.height; y++) {
output.push(' '.repeat(this.width));
}
for (const write of this.writes) {
const { x, y, text, transformers } = write;
const lines = text.split('\n');
let offsetY = 0;
for (let line of lines) {
const currentLine = output[y + offsetY];
// Line can be missing if `text` is taller than height of pre-initialized `this.output`
if (!currentLine) {
continue;
}
const length = string_length_1.default(line);
for (const transformer of transformers) {
line = transformer(line);
}
output[y + offsetY] =
slice_ansi_1.default(currentLine, 0, x) +
line +
slice_ansi_1.default(currentLine, x + length);
offsetY++;
}
}
// eslint-disable-next-line unicorn/prefer-trim-start-end
const generatedOutput = output.map(line => line.trimRight()).join('\n');
return {
output: generatedOutput,
height: output.length
};
}
}
get() {
return this.output.map(line => line.trimRight()).join('\n');
}
getHeight() {
return this.output.length;
}
}
exports.default = Output;
exports.default = Output;
//# sourceMappingURL=output.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _scheduler = require("scheduler");
var _reactReconciler = _interopRequireDefault(require("react-reconciler"));
var _dom = require("./dom");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const NO_CONTEXT = true;
const hostConfig = {
schedulePassiveEffects: _scheduler.unstable_scheduleCallback,
cancelPassiveEffects: _scheduler.unstable_cancelCallback,
now: Date.now,
getRootHostContext: () => NO_CONTEXT,
prepareForCommit: () => {},
resetAfterCommit: rootNode => {
rootNode.onRender();
},
getChildHostContext: () => NO_CONTEXT,
shouldSetTextContent: (type, props) => {
return typeof props.children === 'string' || typeof props.children === 'number';
},
createInstance: (type, newProps) => {
const node = (0, _dom.createNode)(type);
for (const [key, value] of Object.entries(newProps)) {
if (key === 'children') {
if (typeof value === 'string' || typeof value === 'number') {
if (type === 'div') {
// Text node must be wrapped in another node, so that text can be aligned within container
const textElement = (0, _dom.createNode)('div');
textElement.textContent = String(value);
(0, _dom.appendChildNode)(node, textElement);
}
if (type === 'span') {
node.textContent = String(value);
}
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const scheduler_1 = require("scheduler");
const react_reconciler_1 = __importDefault(require("react-reconciler"));
const yoga_layout_prebuilt_1 = __importDefault(require("yoga-layout-prebuilt"));
const dom_1 = require("./dom");
// eslint-disable-next-line import/no-unassigned-import
require("./devtools");
const cleanupYogaNode = (node) => {
node === null || node === void 0 ? void 0 : node.unsetMeasureFunc();
node === null || node === void 0 ? void 0 : node.freeRecursive();
};
exports.default = react_reconciler_1.default({
// @ts-ignore
schedulePassiveEffects: scheduler_1.unstable_scheduleCallback,
cancelPassiveEffects: scheduler_1.unstable_cancelCallback,
now: Date.now,
getRootHostContext: () => ({
isInsideText: false
}),
prepareForCommit: () => { },
resetAfterCommit: rootNode => {
// Since renders are throttled at the instance level and <Static> component children
// are rendered only once and then get deleted, we need an escape hatch to
// trigger an immediate render to ensure <Static> children are written to output before they get erased
if (rootNode.isStaticDirty) {
rootNode.isStaticDirty = false;
if (typeof rootNode.onImmediateRender === 'function') {
rootNode.onImmediateRender();
}
return;
}
} else if (key === 'style') {
node.style = value;
} else if (key === 'unstable__transformChildren') {
node.unstable__transformChildren = value; // eslint-disable-line camelcase
} else if (key === 'unstable__static') {
node.unstable__static = true; // eslint-disable-line camelcase
} else {
(0, _dom.setAttribute)(node, key, value);
}
}
return node;
},
createTextInstance: _dom.createTextNode,
resetTextContent: node => {
if (node.textContent) {
node.textContent = '';
}
if (node.childNodes.length > 0) {
for (const childNode of node.childNodes) {
childNode.yogaNode.free();
(0, _dom.removeChildNode)(node, childNode);
}
}
},
getPublicInstance: instance => instance,
appendInitialChild: _dom.appendChildNode,
appendChild: _dom.appendChildNode,
insertBefore: _dom.insertBeforeNode,
finalizeInitialChildren: () => {},
supportsMutation: true,
appendChildToContainer: _dom.appendChildNode,
insertInContainerBefore: _dom.insertBeforeNode,
removeChildFromContainer: _dom.removeChildNode,
prepareUpdate: () => true,
commitUpdate: (node, updatePayload, type, oldProps, newProps) => {
for (const [key, value] of Object.entries(newProps)) {
if (key === 'children') {
if (typeof value === 'string' || typeof value === 'number') {
if (type === 'div') {
// Text node must be wrapped in another node, so that text can be aligned within container
// If there's no such node, a new one must be created
if (node.childNodes.length === 0) {
const textElement = (0, _dom.createNode)('div');
textElement.textContent = String(value);
(0, _dom.appendChildNode)(node, textElement);
} else {
node.childNodes[0].textContent = String(value);
if (typeof rootNode.onRender === 'function') {
rootNode.onRender();
}
},
getChildHostContext: (parentHostContext, type) => {
const previousIsInsideText = parentHostContext.isInsideText;
const isInsideText = type === 'ink-text' || type === 'ink-virtual-text';
if (previousIsInsideText === isInsideText) {
return parentHostContext;
}
return { isInsideText };
},
shouldSetTextContent: () => false,
createInstance: (originalType, newProps, _root, hostContext) => {
const type = originalType === 'ink-text' && hostContext.isInsideText
? 'ink-virtual-text'
: originalType;
const node = dom_1.createNode(type);
for (const [key, value] of Object.entries(newProps)) {
if (key === 'children') {
continue;
}
}
if (type === 'span') {
node.textContent = String(value);
}
else if (key === 'style') {
dom_1.setStyle(node, value);
}
else if (key === 'internal_transform') {
node.internal_transform = value;
}
else if (key === 'internal_static') {
node.internal_static = true;
}
else {
dom_1.setAttribute(node, key, value);
}
}
} else if (key === 'style') {
node.style = value;
} else if (key === 'unstable__transformChildren') {
node.unstable__transformChildren = value; // eslint-disable-line camelcase
} else if (key === 'unstable__static') {
node.unstable__static = true; // eslint-disable-line camelcase
} else {
(0, _dom.setAttribute)(node, key, value);
}
return node;
},
createTextInstance: (text, _root, hostContext) => {
if (!hostContext.isInsideText) {
throw new Error(`Text string "${text}" must be rendered inside <Text> component`);
}
return dom_1.createTextNode(text);
},
resetTextContent: () => { },
hideTextInstance: (node) => {
dom_1.setTextNodeValue(node, '');
},
unhideTextInstance: (node, text) => {
dom_1.setTextNodeValue(node, text);
},
getPublicInstance: instance => instance,
hideInstance: (node) => {
var _a;
(_a = node.yogaNode) === null || _a === void 0 ? void 0 : _a.setDisplay(yoga_layout_prebuilt_1.default.DISPLAY_NONE);
},
unhideInstance: (node) => {
var _a;
(_a = node.yogaNode) === null || _a === void 0 ? void 0 : _a.setDisplay(yoga_layout_prebuilt_1.default.DISPLAY_FLEX);
},
appendInitialChild: dom_1.appendChildNode,
appendChild: dom_1.appendChildNode,
insertBefore: dom_1.insertBeforeNode,
finalizeInitialChildren: (node, _type, _props, rootNode) => {
if (node.internal_static) {
rootNode.isStaticDirty = true;
// Save reference to <Static> node to skip traversal of entire
// node tree to find it
rootNode.staticNode = node;
}
return false;
},
supportsMutation: true,
appendChildToContainer: dom_1.appendChildNode,
insertInContainerBefore: dom_1.insertBeforeNode,
removeChildFromContainer: (node, removeNode) => {
dom_1.removeChildNode(node, removeNode);
cleanupYogaNode(removeNode.yogaNode);
},
prepareUpdate: (node, _type, oldProps, newProps, rootNode) => {
if (node.internal_static) {
rootNode.isStaticDirty = true;
}
const updatePayload = {};
const keys = Object.keys(newProps);
for (const key of keys) {
if (newProps[key] !== oldProps[key]) {
const isStyle = key === 'style' &&
typeof newProps.style === 'object' &&
typeof oldProps.style === 'object';
if (isStyle) {
const newStyle = newProps.style;
const oldStyle = oldProps.style;
const styleKeys = Object.keys(newStyle);
for (const styleKey of styleKeys) {
if (newStyle[styleKey] !== oldStyle[styleKey]) {
if (typeof updatePayload.style !== 'object') {
// Linter didn't like `= {} as Style`
const style = {};
updatePayload.style = style;
}
updatePayload.style[styleKey] = newStyle[styleKey];
}
}
continue;
}
updatePayload[key] = newProps[key];
}
}
return updatePayload;
},
commitUpdate: (node, updatePayload) => {
for (const [key, value] of Object.entries(updatePayload)) {
if (key === 'children') {
continue;
}
else if (key === 'style') {
dom_1.setStyle(node, value);
}
else if (key === 'internal_transform') {
node.internal_transform = value;
}
else if (key === 'internal_static') {
node.internal_static = true;
}
else {
dom_1.setAttribute(node, key, value);
}
}
},
commitTextUpdate: (node, _oldText, newText) => {
dom_1.setTextNodeValue(node, newText);
},
removeChild: (node, removeNode) => {
dom_1.removeChildNode(node, removeNode);
cleanupYogaNode(removeNode.yogaNode);
}
},
commitTextUpdate: (node, oldText, newText) => {
if (node.nodeName === '#text') {
node.nodeValue = newText;
} else {
node.textContent = newText;
}
},
removeChild: _dom.removeChildNode
};
var _default = (0, _reactReconciler.default)(hostConfig); // eslint-disable-line new-cap
exports.default = _default;
});
//# sourceMappingURL=reconciler.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _widestLine = _interopRequireDefault(require("widest-line"));
var _wrapText = _interopRequireDefault(require("./wrap-text"));
var _getMaxWidth = _interopRequireDefault(require("./get-max-width"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const isAllTextNodes = node => {
if (node.nodeName === '#text') {
return true;
}
if (node.nodeName === 'SPAN') {
if (node.textContent) {
return true;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const yoga_layout_prebuilt_1 = __importDefault(require("yoga-layout-prebuilt"));
const widest_line_1 = __importDefault(require("widest-line"));
const indent_string_1 = __importDefault(require("indent-string"));
const wrap_text_1 = __importDefault(require("./wrap-text"));
const get_max_width_1 = __importDefault(require("./get-max-width"));
const squash_text_nodes_1 = __importDefault(require("./squash-text-nodes"));
const render_border_1 = __importDefault(require("./render-border"));
// If parent container is `<Box>`, text nodes will be treated as separate nodes in
// the tree and will have their own coordinates in the layout.
// To ensure text nodes are aligned correctly, take X and Y of the first text node
// and use it as offset for the rest of the nodes
// Only first node is taken into account, because other text nodes can't have margin or padding,
// so their coordinates will be relative to the first node anyway
const applyPaddingToText = (node, text) => {
var _a;
const yogaNode = (_a = node.childNodes[0]) === null || _a === void 0 ? void 0 : _a.yogaNode;
if (yogaNode) {
const offsetX = yogaNode.getComputedLeft();
const offsetY = yogaNode.getComputedTop();
text = '\n'.repeat(offsetY) + indent_string_1.default(text, offsetX);
}
if (Array.isArray(node.childNodes)) {
return node.childNodes.every(isAllTextNodes);
return text;
};
// After nodes are laid out, render each to output object, which later gets rendered to terminal
const renderNodeToOutput = (node, output, options) => {
var _a;
const { offsetX = 0, offsetY = 0, transformers = [], skipStaticElements } = options;
if (skipStaticElements && node.internal_static) {
return;
}
}
return false;
}; // Squashing text nodes allows to combine multiple text nodes into one and write
// to `Output` instance only once. For example, <Text>hello{' '}world</Text>
// is actually 3 text nodes, which would result 3 writes to `Output`.
//
// Also, this is necessary for libraries like ink-link (https://github.com/sindresorhus/ink-link),
// which need to wrap all children at once, instead of wrapping 3 text nodes separately.
const squashTextNodes = node => {
if (node.childNodes.length === 0) {
return '';
} // If parent container is `<Box>`, text nodes will be treated as separate nodes in
// the tree and will have their own coordinates in the layout.
// To ensure text nodes are aligned correctly, take X and Y of the first text node
// and use them as offset for the rest of the nodes
// Only first node is taken into account, because other text nodes can't have margin or padding,
// so their coordinates will be relative to the first node anyway
const offsetX = node.childNodes[0].yogaNode.getComputedLeft();
const offsetY = node.childNodes[0].yogaNode.getComputedTop();
let text = '\n'.repeat(offsetY) + ' '.repeat(offsetX);
for (const childNode of node.childNodes) {
let nodeText;
if (childNode.nodeName === '#text') {
nodeText = childNode.nodeValue;
}
if (childNode.nodeName === 'SPAN') {
nodeText = childNode.textContent || squashTextNodes(childNode);
} // Since these text nodes are being concatenated, `Output` instance won't be able to
// apply children transform, so we have to do it manually here for each text node
if (childNode.unstable__transformChildren) {
nodeText = childNode.unstable__transformChildren(nodeText);
}
text += nodeText;
}
return text;
}; // After nodes are laid out, render each to output object, which later gets rendered to terminal
const renderNodeToOutput = (node, output, {
offsetX = 0,
offsetY = 0,
transformers = [],
skipStaticElements
}) => {
if (node.unstable__static && skipStaticElements) {
return;
}
const {
yogaNode
} = node; // Left and top positions in Yoga are relative to their parent node
const x = offsetX + yogaNode.getComputedLeft();
const y = offsetY + yogaNode.getComputedTop(); // Transformers are functions that transform final text output of each component
// See Output class for logic that applies transformers
let newTransformers = transformers;
if (node.unstable__transformChildren) {
newTransformers = [node.unstable__transformChildren, ...transformers];
} // Nodes with only text inside
if (node.textContent) {
let text = node.textContent; // Since text nodes are always wrapped in an additional node, parent node
// is where we should look for attributes
if (node.parentNode.style.textWrap) {
const currentWidth = (0, _widestLine.default)(text);
const maxWidth = (0, _getMaxWidth.default)(node.parentNode.yogaNode);
if (currentWidth > maxWidth) {
text = (0, _wrapText.default)(text, maxWidth, {
textWrap: node.parentNode.style.textWrap
});
}
}
output.write(x, y, text, {
transformers: newTransformers
});
return;
} // Text nodes
if (node.nodeName === '#text') {
output.write(x, y, node.nodeValue, {
transformers: newTransformers
});
return;
} // Nodes that have other nodes as children
if (Array.isArray(node.childNodes) && node.childNodes.length > 0) {
const isFlexDirectionRow = node.style.flexDirection === 'row';
if (isFlexDirectionRow && node.childNodes.every(isAllTextNodes)) {
let text = squashTextNodes(node);
if (node.style.textWrap) {
const currentWidth = (0, _widestLine.default)(text);
const maxWidth = (0, _getMaxWidth.default)(yogaNode);
if (currentWidth > maxWidth) {
text = (0, _wrapText.default)(text, maxWidth, {
textWrap: node.style.textWrap
});
const { yogaNode } = node;
if (yogaNode) {
if (yogaNode.getDisplay() === yoga_layout_prebuilt_1.default.DISPLAY_NONE) {
return;
}
}
output.write(x, y, text, {
transformers: newTransformers
});
return;
// Left and top positions in Yoga are relative to their parent node
const x = offsetX + yogaNode.getComputedLeft();
const y = offsetY + yogaNode.getComputedTop();
// Transformers are functions that transform final text output of each component
// See Output class for logic that applies transformers
let newTransformers = transformers;
if (typeof node.internal_transform === 'function') {
newTransformers = [node.internal_transform, ...transformers];
}
if (node.nodeName === 'ink-text') {
let text = squash_text_nodes_1.default(node);
if (text.length > 0) {
const currentWidth = widest_line_1.default(text);
const maxWidth = get_max_width_1.default(yogaNode);
if (currentWidth > maxWidth) {
const textWrap = (_a = node.style.textWrap) !== null && _a !== void 0 ? _a : 'wrap';
text = wrap_text_1.default(text, maxWidth, textWrap);
}
text = applyPaddingToText(node, text);
output.write(x, y, text, { transformers: newTransformers });
}
return;
}
if (node.nodeName === 'ink-box') {
render_border_1.default(x, y, node, output);
}
if (node.nodeName === 'ink-root' || node.nodeName === 'ink-box') {
for (const childNode of node.childNodes) {
renderNodeToOutput(childNode, output, {
offsetX: x,
offsetY: y,
transformers: newTransformers,
skipStaticElements
});
}
}
}
for (const childNode of node.childNodes) {
renderNodeToOutput(childNode, output, {
offsetX: x,
offsetY: y,
transformers: newTransformers,
skipStaticElements
});
}
}
};
var _default = renderNodeToOutput;
exports.default = _default;
exports.default = renderNodeToOutput;
//# sourceMappingURL=render-node-to-output.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _instance = _interopRequireDefault(require("./instance"));
var _instances = _interopRequireDefault(require("./instances"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var _default = (node, options = {}) => {
// Stream was passed instead of `options` object
if (typeof options.write === 'function') {
options = {
stdout: options,
stdin: process.stdin
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const ink_1 = __importDefault(require("./ink"));
const instances_1 = __importDefault(require("./instances"));
const stream_1 = require("stream");
/**
* Mount a component and render the output.
*/
const render = (node, options) => {
const inkOptions = Object.assign({ stdout: process.stdout, stdin: process.stdin, stderr: process.stderr, debug: false, exitOnCtrlC: true, patchConsole: true }, getOptions(options));
const instance = getInstance(inkOptions.stdout, () => new ink_1.default(inkOptions));
instance.render(node);
return {
rerender: instance.render,
unmount: () => instance.unmount(),
waitUntilExit: instance.waitUntilExit,
cleanup: () => instances_1.default.delete(inkOptions.stdout),
clear: instance.clear
};
}
options = _objectSpread({
stdout: process.stdout,
stdin: process.stdin,
debug: false,
exitOnCtrlC: true,
experimental: false
}, options);
let instance;
if (_instances.default.has(options.stdout)) {
instance = _instances.default.get(options.stdout);
} else {
instance = new _instance.default(options);
_instances.default.set(options.stdout, instance);
}
instance.render(node);
return {
rerender: instance.render,
unmount: () => instance.unmount(),
waitUntilExit: instance.waitUntilExit,
cleanup: () => _instances.default.delete(options.stdout)
};
};
exports.default = _default;
exports.default = render;
const getOptions = (stdout = {}) => {
if (stdout instanceof stream_1.Stream) {
return {
stdout,
stdin: process.stdin
};
}
return stdout;
};
const getInstance = (stdout, createInstance) => {
let instance;
if (instances_1.default.has(stdout)) {
instance = instances_1.default.get(stdout);
}
else {
instance = createInstance();
instances_1.default.set(stdout, instance);
}
return instance;
};
//# sourceMappingURL=render.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _yogaLayoutPrebuilt = _interopRequireDefault(require("yoga-layout-prebuilt"));
var _output = _interopRequireDefault(require("./output"));
var _dom = require("./dom");
var _buildLayout = _interopRequireDefault(require("./build-layout"));
var _renderNodeToOutput = _interopRequireDefault(require("./render-node-to-output"));
var _calculateWrappedText = _interopRequireDefault(require("./calculate-wrapped-text"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Since <Static> components can be placed anywhere in the tree, this helper finds and returns them
const getStaticNodes = element => {
const staticNodes = [];
for (const childNode of element.childNodes) {
if (childNode.unstable__static) {
staticNodes.push(childNode);
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const yoga_layout_prebuilt_1 = __importDefault(require("yoga-layout-prebuilt"));
const render_node_to_output_1 = __importDefault(require("./render-node-to-output"));
const output_1 = __importDefault(require("./output"));
exports.default = (node, terminalWidth) => {
var _a;
node.yogaNode.setWidth(terminalWidth);
if (node.yogaNode) {
node.yogaNode.calculateLayout(undefined, undefined, yoga_layout_prebuilt_1.default.DIRECTION_LTR);
const output = new output_1.default({
width: node.yogaNode.getComputedWidth(),
height: node.yogaNode.getComputedHeight()
});
render_node_to_output_1.default(node, output, { skipStaticElements: true });
let staticOutput;
if ((_a = node.staticNode) === null || _a === void 0 ? void 0 : _a.yogaNode) {
staticOutput = new output_1.default({
width: node.staticNode.yogaNode.getComputedWidth(),
height: node.staticNode.yogaNode.getComputedHeight()
});
render_node_to_output_1.default(node.staticNode, staticOutput, {
skipStaticElements: false
});
}
const { output: generatedOutput, height: outputHeight } = output.get();
return {
output: generatedOutput,
outputHeight,
// Newline at the end is needed, because static output doesn't have one, so
// interactive output will override last line of static output
staticOutput: staticOutput ? `${staticOutput.get().output}\n` : ''
};
}
if (Array.isArray(childNode.childNodes) && childNode.childNodes.length > 0) {
staticNodes.push(...getStaticNodes(childNode));
}
}
return staticNodes;
}; // Build layout, apply styles, build text output of all nodes and return it
var _default = ({
terminalWidth
}) => {
const config = _yogaLayoutPrebuilt.default.Config.create(); // Used to free up memory used by last Yoga node tree
let lastYogaNode;
let lastStaticYogaNode;
return node => {
if (lastYogaNode) {
lastYogaNode.freeRecursive();
}
if (lastStaticYogaNode) {
lastStaticYogaNode.freeRecursive();
}
const staticElements = getStaticNodes(node);
if (staticElements.length > 1) {
if (process.env.NODE_ENV !== 'production') {
console.error('Warning: There can only be one <Static> component');
}
} // <Static> component must be built and rendered separately, so that the layout of the other output is unaffected
let staticOutput;
if (staticElements.length === 1) {
const rootNode = (0, _dom.createNode)('root');
(0, _dom.appendStaticNode)(rootNode, staticElements[0]);
const {
yogaNode: staticYogaNode
} = (0, _buildLayout.default)(rootNode, {
config,
terminalWidth,
skipStaticElements: false
});
staticYogaNode.calculateLayout(_yogaLayoutPrebuilt.default.UNDEFINED, _yogaLayoutPrebuilt.default.UNDEFINED, _yogaLayoutPrebuilt.default.DIRECTION_LTR);
(0, _calculateWrappedText.default)(rootNode);
staticYogaNode.calculateLayout(_yogaLayoutPrebuilt.default.UNDEFINED, _yogaLayoutPrebuilt.default.UNDEFINED, _yogaLayoutPrebuilt.default.DIRECTION_LTR); // Save current Yoga node tree to free up memory later
lastStaticYogaNode = staticYogaNode;
staticOutput = new _output.default({
width: staticYogaNode.getComputedWidth(),
height: staticYogaNode.getComputedHeight()
});
(0, _renderNodeToOutput.default)(rootNode, staticOutput, {
skipStaticElements: false
});
}
const {
yogaNode
} = (0, _buildLayout.default)(node, {
config,
terminalWidth,
skipStaticElements: true
});
yogaNode.calculateLayout(_yogaLayoutPrebuilt.default.UNDEFINED, _yogaLayoutPrebuilt.default.UNDEFINED, _yogaLayoutPrebuilt.default.DIRECTION_LTR);
(0, _calculateWrappedText.default)(node);
yogaNode.calculateLayout(_yogaLayoutPrebuilt.default.UNDEFINED, _yogaLayoutPrebuilt.default.UNDEFINED, _yogaLayoutPrebuilt.default.DIRECTION_LTR); // Save current node tree to free up memory later
lastYogaNode = yogaNode;
const output = new _output.default({
width: yogaNode.getComputedWidth(),
height: yogaNode.getComputedHeight()
});
(0, _renderNodeToOutput.default)(node, output, {
skipStaticElements: true
});
return {
output: output.get(),
outputHeight: output.getHeight(),
staticOutput: staticOutput ? `${staticOutput.get()}\n` : undefined
output: '',
outputHeight: 0,
staticOutput: ''
};
};
};
exports.default = _default;
//# sourceMappingURL=renderer.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _wrapAnsi = _interopRequireDefault(require("wrap-ansi"));
var _cliTruncate = _interopRequireDefault(require("cli-truncate"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _default = (text, maxWidth, {
textWrap
} = {}) => {
if (textWrap === 'wrap') {
return (0, _wrapAnsi.default)(text, maxWidth, {
trim: false,
hard: true
});
}
if (String(textWrap).startsWith('truncate')) {
let position;
if (textWrap === 'truncate' || textWrap === 'truncate-end') {
position = 'end';
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const wrap_ansi_1 = __importDefault(require("wrap-ansi"));
const cli_truncate_1 = __importDefault(require("cli-truncate"));
const cache = {};
exports.default = (text, maxWidth, wrapType) => {
const cacheKey = text + String(maxWidth) + String(wrapType);
if (cache[cacheKey]) {
return cache[cacheKey];
}
if (textWrap === 'truncate-middle') {
position = 'middle';
let wrappedText = text;
if (wrapType === 'wrap') {
wrappedText = wrap_ansi_1.default(text, maxWidth, {
trim: false,
hard: true
});
}
if (textWrap === 'truncate-start') {
position = 'start';
if (wrapType.startsWith('truncate')) {
let position = 'end';
if (wrapType === 'truncate-middle') {
position = 'middle';
}
if (wrapType === 'truncate-start') {
position = 'start';
}
wrappedText = cli_truncate_1.default(text, maxWidth, { position });
}
return (0, _cliTruncate.default)(text, maxWidth, {
position
});
}
return text;
cache[cacheKey] = wrappedText;
return wrappedText;
};
exports.default = _default;
//# sourceMappingURL=wrap-text.js.map
{
"name": "ink",
"version": "2.7.1",
"version": "3.0.0-0",
"description": "React for CLI",

@@ -10,19 +10,17 @@ "license": "MIT",

"email": "vdemedes@gmail.com",
"url": "github.com/vadimdemedes"
"url": "https://github.com/vadimdemedes"
},
"main": "build",
"types": "build/index.d.ts",
"engines": {
"node": ">=8"
"node": ">=10"
},
"scripts": {
"build": "babel src --out-dir=build",
"build": "tsc",
"prepare": "npm run build",
"test": "xo && FORCE_COLOR=true EXPERIMENTAL=true ava && FORCE_COLOR=true ava && tsd",
"pretest": "npm run build",
"test": "tsc --noEmit && xo && FORCE_COLOR=true ava",
"cast": "svg-term --command='node media/demo.js' --out=media/demo.svg --from=100 --window --width=50 --height=8 --term=iterm2 --profile=Snazzy"
},
"types": "index.d.ts",
"files": [
"build",
"index.d.ts"
"build"
],

@@ -44,12 +42,25 @@ "keywords": [

"dependencies": {
"@types/is-ci": "^2.0.0",
"@types/lodash.throttle": "^4.1.6",
"@types/node": "^13.9.1",
"@types/react": "^16.9.19",
"@types/react-reconciler": "^0.18.0",
"@types/scheduler": "^0.16.1",
"@types/signal-exit": "^3.0.0",
"@types/sinon": "^7.5.2",
"@types/slice-ansi": "^2.0.0",
"@types/stack-utils": "^1.0.1",
"@types/wrap-ansi": "^3.0.0",
"ansi-escapes": "^4.2.1",
"arrify": "^2.0.1",
"auto-bind": "^4.0.0",
"auto-bind": "4.0.0",
"chalk": "^3.0.0",
"cli-boxes": "^2.2.0",
"cli-cursor": "^3.1.0",
"cli-truncate": "^2.1.0",
"code-excerpt": "^3.0.0",
"indent-string": "^4.0.0",
"is-ci": "^2.0.0",
"lodash.throttle": "^4.1.1",
"log-update": "^3.0.0",
"prop-types": "^15.6.2",
"patch-console": "^1.0.0",
"react-devtools-core": "^4.6.0",
"react-reconciler": "^0.24.0",

@@ -59,24 +70,28 @@ "scheduler": "^0.18.0",

"slice-ansi": "^3.0.0",
"stack-utils": "^2.0.2",
"string-length": "^3.1.0",
"type-fest": "^0.12.0",
"widest-line": "^3.1.0",
"wrap-ansi": "^6.2.0",
"yoga-layout-prebuilt": "^1.9.3"
"ws": "^7.2.5",
"yoga-layout-prebuilt": "^1.9.6"
},
"devDependencies": {
"@babel/cli": "^7.8.3",
"@babel/core": "^7.8.3",
"@babel/plugin-proposal-class-properties": "^7.8.3",
"@babel/plugin-proposal-object-rest-spread": "^7.8.3",
"@babel/preset-react": "^7.8.3",
"@types/react": "^16.9.19",
"ava": "^2.4.0",
"@sindresorhus/tsconfig": "0.7.0",
"ava": "^3.5.0",
"babel-eslint": "^10.0.1",
"benchmark": "^2.1.4",
"boxen": "^4.2.0",
"chance": "^1.1.6",
"delay": "^4.1.0",
"eslint-config-xo": "0.29.1",
"eslint-config-xo-react": "^0.22.0",
"eslint-plugin-prettier": "^3.1.2",
"eslint-plugin-react": "^7.18.0",
"eslint-plugin-react-hooks": "^2.3.0",
"import-jsx": "^3.1.0",
"import-jsx": "3.1.0",
"ms": "^2.1.1",
"node-pty": "^0.9.0",
"p-queue": "^6.2.1",
"prettier": "^2.0.4",
"react": "^16.9.0",

@@ -86,4 +101,5 @@ "sinon": "^8.1.1",

"svg-term-cli": "^2.1.1",
"tsd": "^0.11.0",
"xo": "^0.25.3"
"ts-node": "7.0.0",
"typescript": "^3.8.3",
"xo": "^0.28.0"
},

@@ -99,34 +115,12 @@ "peerDependencies": {

},
"babel": {
"plugins": [
"@babel/plugin-proposal-class-properties",
"@babel/plugin-proposal-object-rest-spread",
"@babel/plugin-transform-modules-commonjs"
],
"presets": [
"@babel/preset-react"
]
},
"ava": {
"babel": {
"testOptions": {
"plugins": [
"@babel/plugin-proposal-class-properties",
"@babel/plugin-proposal-object-rest-spread",
"@babel/plugin-transform-modules-commonjs"
],
"presets": [
"@babel/preset-react"
]
}
},
"files": [
"test/*.js"
"extensions": [
"ts",
"tsx"
],
"helpers": [
"test/helpers/*.js"
"require": [
"ts-node/register/transpile-only"
]
},
"xo": {
"parser": "babel-eslint",
"extends": [

@@ -138,2 +132,3 @@ "xo-react"

],
"prettier": true,
"rules": {

@@ -147,12 +142,45 @@ "react/no-unescaped-entities": "off",

"files": [
"src/components/*.js",
"src/hooks/*.js"
"src/**/*.{ts,tsx}",
"test/**/*.{ts,tsx}"
],
"rules": {
"no-unused-expressions": "off",
"camelcase": [
"error",
{
"allow": [
"^unstable__",
"^internal_"
]
}
],
"unicorn/filename-case": "off",
"react/require-default-props": "warn"
"react/prop-types": "off",
"unicorn/prevent-abbreviations": "off",
"react/require-default-props": "warn",
"react/jsx-curly-brace-presence": "off",
"@typescript-eslint/no-empty-function": "warn",
"@typescript-eslint/promise-function-async": "warn",
"@typescript-eslint/explicit-function-return": "off",
"@typescript-eslint/explicit-function-return-type": "off"
}
},
{
"files": [
"examples/**/*.js"
],
"rules": {
"react/prop-types": "off"
}
}
]
},
"prettier": {
"useTabs": true,
"singleQuote": true,
"quoteProps": "as-needed",
"trailingComma": "none",
"bracketSpacing": false,
"arrowParens": "avoid"
}
}

@@ -14,2 +14,12 @@ <h1 align="center">

Ink provides the same component-based UI building experience that React offers in the browser, but for command-line apps.
It uses [Yoga](https://github.com/facebook/yoga) to build Flexbox layouts in the terminal, so most CSS-like props are available in Ink as well.
If you are already familiar with React, you already know Ink.
Since Ink is a React renderer, it means that all features of React are supported.
Head over to [React](https://reactjs.org) website for documentation on how to use it.
Only Ink's methods will be documented in this readme.
**Note:** This is documentation for Ink 3, which is unreleased yet. If you're looking for docs on Ink 2, go to https://github.com/vadimdemedes/ink/tree/v2.7.1.
## Install

@@ -24,31 +34,21 @@

```jsx
import React, { Component } from "react";
import { render, Color } from "ink";
import React, {useState, useEffect} from 'react';
import {render, Text} from 'ink';
class Counter extends Component {
constructor() {
super();
const Counter = () => {
const [counter, setCounter] = useState(0);
this.state = {
i: 0
useEffect(() => {
const timer = setInterval(() => {
setCounter(previousCounter => previousCounter + 1);
}, 100);
return () => {
clearInterval(timer);
};
}
}, []);
render() {
return <Color green>{this.state.i} tests passed</Color>;
}
return <Text color="green">{counter} tests passed</Text>;
};
componentDidMount() {
this.timer = setInterval(() => {
this.setState({
i: this.state.i + 1
});
}, 100);
}
componentWillUnmount() {
clearInterval(this.timer);
}
}
render(<Counter />);

@@ -64,67 +64,92 @@ ```

- [Gatsby](https://www.gatsbyjs.org) - Gatsby is a modern web framework for blazing fast websites.
- [Parcel](https://parceljs.org) - Blazing fast, zero configuration web application bundler.
- [tap](https://node-tap.org) - A Test-Anything-Protocol library for JavaScript.
- [Typewriter](https://github.com/segmentio/typewriter) - Generates strongly-typed [Segment](https://segment.com) analytics clients from arbitrary JSON Schema.
- [Prisma](https://www.prisma.io) - The unified data layer for modern applications.
- [Wallace](https://www.projectwallace.com) - Pretty CSS analytics on the CLI.
- [tink](https://github.com/npm/tink) - Next-generation runtime and package manager.
- [Splash](https://github.com/Shopify/polaris-react/tree/master/scripts/splash) - Observe the splash zone of a change across the Shopify's [Polaris](https://polaris.shopify.com) component library.
- [emoj](https://github.com/sindresorhus/emoj) - Find relevant emoji on the command-line.
- [emma](https://github.com/maticzav/emma-cli) - Terminal assistant to find and install npm packages.
- [sindresorhus](https://github.com/sindresorhus/sindresorhus) - The Sindre Sorhus CLI.
- [swiff](https://github.com/simple-integrated-marketing/swiff) - Multi-environment command line tools for time-saving web developers.
- [share](https://github.com/marionebl/share-cli) - Quickly share files from your command line.
- [Kubelive](https://github.com/ameerthehacker/kubelive) - CLI for Kubernetes to provide live data about the cluster and its resources.
- [changelog-view](https://github.com/jdeniau/changelog-view) - Tool view changelog in console.
- [gomoku-terminal](https://github.com/acrazing/gomoku-terminal) - Play online Gomoku in the terminal.
- [cfpush](https://github.com/mamachanko/cfpush) - An interactive Cloud Foundry tutorial in your terminal.
- [startd](https://github.com/mgrip/startd) - Turn your React component into a web app from the command-line.
- [wiki-cli](https://github.com/hexrcs/wiki-cli) - Search Wikipedia and read summaries directly in your terminal.
- [Gatsby](https://www.gatsbyjs.org) - Gatsby is a modern web framework for blazing fast websites.
- [Parcel](https://parceljs.org) - Blazing fast, zero configuration web application bundler.
- [tap](https://node-tap.org) - A Test-Anything-Protocol library for JavaScript.
- [Typewriter](https://github.com/segmentio/typewriter) - Generates strongly-typed [Segment](https://segment.com) analytics clients from arbitrary JSON Schema.
- [Prisma](https://www.prisma.io) - The unified data layer for modern applications.
- [Wallace](https://www.projectwallace.com) - Pretty CSS analytics on the CLI.
- [tink](https://github.com/npm/tink) - Next-generation runtime and package manager.
- [Splash](https://github.com/Shopify/polaris-react/tree/master/scripts/splash) - Observe the splash zone of a change across the Shopify's [Polaris](https://polaris.shopify.com) component library.
- [emoj](https://github.com/sindresorhus/emoj) - Find relevant emoji on the command-line.
- [emma](https://github.com/maticzav/emma-cli) - Terminal assistant to find and install npm packages.
- [sindresorhus](https://github.com/sindresorhus/sindresorhus) - The Sindre Sorhus CLI.
- [swiff](https://github.com/simple-integrated-marketing/swiff) - Multi-environment command line tools for time-saving web developers.
- [share](https://github.com/marionebl/share-cli) - Quickly share files from your command line.
- [Kubelive](https://github.com/ameerthehacker/kubelive) - CLI for Kubernetes to provide live data about the cluster and its resources.
- [changelog-view](https://github.com/jdeniau/changelog-view) - Tool view changelog in console.
- [gomoku-terminal](https://github.com/acrazing/gomoku-terminal) - Play online Gomoku in the terminal.
- [cfpush](https://github.com/mamachanko/cfpush) - An interactive Cloud Foundry tutorial in your terminal.
- [startd](https://github.com/mgrip/startd) - Turn your React component into a web app from the command-line.
- [wiki-cli](https://github.com/hexrcs/wiki-cli) - Search Wikipedia and read summaries directly in your terminal.
- [garson](https://github.com/goliney/garson) - Build interactive config-based command-line interfaces.
## Contents
- [Getting Started](#getting-started)
- [Examples](#examples)
- [API](#api)
- [Building Layouts](#building-layouts)
- [Built-in Components](#built-in-components)
- [Hooks](#hooks)
- [Useful Components](#useful-components)
- [Testing](#testing)
- [Experimental mode](#experimental-mode)
- [Getting Started](#getting-started)
- [Components](#components)
- [`<Text>`](#text)
- [`<Box>`](#box)
- [`<Newline>`](#newline)
- [`<Spacer>`](#spacer)
- [`<Static>`](#static)
- [`<Transform>`](#transform)
- [Hooks](#hooks)
- [`useInput`](#useinputinputhandler-options)
- [`useApp`](#useapp)
- [`useStdin`](#usestdin)
- [`useStdout`](#usestdout)
- [`useStderr`](#usestderr)
- [`useFocus`](#usefocusoptions)
- [`useFocusManager`](#usefocusmanager)
- [API](#api)
- [Testing](#testing)
- [Using React Devtools](#using-react-devtools)
- [Useful Components](#useful-components)
- [Useful Hooks](#useful-hooks)
- [Examples](#examples)
## Getting Started
Ink's goal is to provide the same component-based UI building experience that React provides, but for command-line apps. It uses [yoga-layout](https://github.com/facebook/yoga) to allow Flexbox layouts in the terminal. If you are already familiar with React, you already know Ink.
Use [create-ink-app](https://github.com/vadimdemedes/create-ink-app) to quickly scaffold a new Ink-based CLI.
The key difference you have to remember is that the rendering result isn't a DOM, but a string, which Ink writes to the output.
```
$ mkdir my-ink-cli
$ cd my-ink-cli
$ npx create-ink-app
```
To get started with Ink quickly, use [create-ink-app](https://github.com/vadimdemedes/create-ink-app) to quickly scaffold a new Ink-based CLI. Alternatively, here's how to configure Babel to work with Ink. To ensure all examples work and you can begin your adventure, make sure to set up Babel with a React preset. After [installing Babel](https://babeljs.io/docs/en/usage), configure it in `package.json`:
<details><summary>Manual setup</summary>
<p>
Ink requires the same Babel setup as you would do for regular React-based apps in the browser.
Set up Babel with a React preset to ensure all examples in this readme work as expected.
After [installing Babel](https://babeljs.io/docs/en/usage), install `@babel/preset-react` and insert the following configuration in `babel.config.json`:
```
$ npm install --save-dev @babel/preset-react
```
```json
{
"babel": {
"presets": [
"@babel/preset-react",
[
"@babel/preset-env",
{
"targets": {
"node": true
}
"presets": [
"@babel/preset-react",
[
"@babel/preset-env",
{
"targets": {
"node": true
}
]
}
]
}
]
}
```
Don't forget to import `React` into every file that contains JSX:
Next, create a file `source.js`, where you'll type code that uses Ink:
```jsx
import React from "react";
import { render, Box } from "ink";
import React from 'react';
import {render, Text} from 'ink';
const Demo = () => <Box>Hello World</Box>;
const Demo = () => <Text>Hello World</Text>;

@@ -134,176 +159,187 @@ render(<Demo />);

## Examples
Then, transpile this file with Babel:
- [Jest](examples/jest/jest.js) - Implementation of basic Jest UI [(live demo)](https://ink-jest-demo.vadimdemedes.repl.run/).
- [Counter](examples/counter/counter.js) - Simple counter that increments every 100ms [(live demo)](https://ink-counter-demo.vadimdemedes.repl.run/).
- [Form with Validation](https://github.com/final-form/rff-cli-example) - Using framework agnostic form library, [🏁 Final Form](https://github.com/final-form/final-form#-final-form) to manage input state.
```
$ npx babel source.js -o cli.js
```
## API
Now you can run `cli.js` with Node.js:
Since Ink is a React renderer, it means that all features of React are supported.
Head over to [React](https://reactjs.org) website for documentation on how to use it.
In this readme only Ink's methods will be documented.
```
$ node cli
```
#### render(tree, options)
If you don't like transpiling files during development, you can use [import-jsx](https://github.com/vadimdemedes/import-jsx) to `require()` a JSX file and transpile it on the fly.
Returns: `Instance`
</p>
</details>
Mount a component and render the output.
Ink uses [Yoga](https://github.com/facebook/yoga) - a Flexbox layout engine to build great user interfaces for your CLIs using familiar CSS-like props you've used when building apps for the browser.
It's important to remember that each element is a Flexbox container.
Think of it as if each `<div>` in the browser had `display: flex`.
See [`<Box>`](#box) built-in component below for documentation on how to use Flexbox layouts in Ink.
Note that all text must be wrapped in a [`<Text>`](#text) component.
##### tree
## Components
Type: `ReactElement`
### `<Text>`
##### options
This component can display text, and change its style to make it bold, underline, italic or strikethrough.
Type: `Object`
```jsx
import {render, Text} from 'ink';
###### stdout
const Example = () => (
<>
<Text color="green">I am green</Text>
<Text color="black" backgroundColor="white">
I am black on white
</Text>
<Text color="#ffffff">I am white</Text>
<Text bold>I am bold</Text>
<Text italic>I am italic</Text>
<Text underline>I am underline</Text>
<Text strikethrough>I am strikethrough</Text>
</>
);
Type: `stream.Writable`<br>
Default: `process.stdout`
render(<Example />);
```
Output stream where app will be rendered.
#### color
###### stdin
Type: `string`
Type: `stream.Readable`<br>
Default: `process.stdin`
Change text color.
Ink uses [chalk](https://github.com/chalk/chalk) under the hood, so all its functionality is supported.
Input stream where app will listen for input.
```jsx
<Text color="green">Green</Text>
<Text color="#005cc5">Blue</Text>
<Text color="rgb(232, 131, 136)">Red</Text>
```
###### exitOnCtrlC
<img src="media/text-color.jpg" width="247">
Type: `boolean`<br>
Default: `true`
#### backgroundColor
Configure whether Ink should listen to Ctrl+C keyboard input and exit the app.
This is needed in case `process.stdin` is in [raw mode](https://nodejs.org/api/tty.html#tty_readstream_setrawmode_mode), because then Ctrl+C is ignored by default and process is expected to handle it manually.
Type: `string`
###### debug
Same as `color` above, but for background.
Type: `boolean`<br>
Default: `false`
```jsx
<Text backgroundColor="green" color="white">Green</Text>
<Text backgroundColor="#005cc5" color="white">Blue</Text>
<Text backgroundColor="rgb(232, 131, 136)" color="white">Red</Text>
```
If `true`, each update will be rendered as a separate output, without replacing the previous one.
<img src="media/text-backgroundColor.jpg" width="226">
###### experimental
#### dimColor
Type: `boolean`<br>
Type: `boolean`\
Default: `false`
Enables [experimental mode](#experimental-mode).
Dim the color (emit a small amount of light).
```jsx
import React, { Component } from "react";
import { render, Box } from "ink";
<Text color="red" dimColor>
Dimmed Red
</Text>
```
class Counter extends Component {
constructor() {
super();
<img src="media/text-dimColor.jpg" width="138">
this.state = {
i: 0
};
}
#### bold
render() {
return <Box>Iteration #{this.state.i}</Box>;
}
Type: `boolean`\
Default: `false`
componentDidMount() {
this.timer = setInterval(() => {
this.setState(prevState => ({
i: prevState.i + 1
}));
}, 100);
}
Make the text bold.
componentWillUnmount() {
clearInterval(this.timer);
}
}
#### italic
const app = render(<Counter />);
Type: `boolean`\
Default: `false`
setTimeout(() => {
// Enough counting
app.unmount();
}, 1000);
```
Make the text italic.
There's also a shortcut to avoid passing `options` object:
#### underline
```jsx
render(<Counter>, process.stdout);
```
Type: `boolean`\
Default: `false`
#### Instance
Make the text underlined.
This is the object that `render()` returns.
#### strikethrough
##### rerender
Type: `boolean`\
Default: `false`
Replace previous root node with a new one or update props of the current root node.
Make the text crossed with a line.
```jsx
// Update props of the root node
const { rerender } = render(<Counter count={1} />);
rerender(<Counter count={2} />);
#### wrap
// Replace root node
const { rerender } = render(<OldCounter />);
rerender(<NewCounter />);
```
Type: `string`\
Allowed values: `wrap` `truncate` `truncate-start` `truncate-middle` `truncate-end`\
Default: `wrap`
##### unmount
This property tells Ink to wrap or truncate text if its width is larger than container.
If `wrap` is passed (by default), Ink will wrap text and split it into multiple lines.
If `truncate-*` is passed, Ink will truncate text instead, which will result in one line of text with the rest cut off.
Manually unmount the whole Ink app.
```jsx
const { unmount } = render(<MyApp />);
unmount();
```
<Box width={7}>
<Text>Hello World</Text>
</Box>
//=> 'Hello\nWorld'
##### waitUntilExit
// `truncate` is an alias to `truncate-end`
<Box width={7}>
<Text wrap="truncate">Hello World</Text>
</Box>
//=> 'Hello…'
Returns a promise, which resolves when app is unmounted.
<Box width={7}>
<Text wrap="truncate-middle">Hello World</Text>
</Box>
//=> 'He…ld'
```jsx
const { unmount, waitUntilExit } = render(<MyApp />);
setTimeout(unmount, 1000);
await waitUntilExit(); // resolves after `unmount()` is called
<Box width={7}>
<Text wrap="truncate-start">Hello World</Text>
</Box>
//=> '…World'
```
## Building Layouts
### `<Box>`
Ink uses [Yoga](https://github.com/facebook/yoga) - a Flexbox layout engine to build great user interfaces for your CLIs.
It's important to remember that each element is a Flexbox container.
Think of it as if each `<div>` in the browser had `display: flex`.
See `<Box>` built-in component below for documentation on how to use Flexbox layouts in Ink.
`<Box>` is an essential Ink component to build your layout.
It's like `<div style="display: flex">` in the browser.
### Built-in Components
```jsx
import {render, Box, Text} from 'ink';
#### `<Box>`
const Example = () => {
<Box margin={2}>
<Text>This is a box with margin</Text>
</Box>;
};
`<Box>` it's an essential Ink component to build your layout. It's like a `<div style="display: flex">` in a browser.
Import:
```js
import { Box } from "ink";
render(<Example />);
```
##### Dimensions
#### Dimensions
###### width
##### width
Type: `number`, `string`
Type: `number` `string`
Width of the element in spaces. You can also set it in percent, which will calculate the width based on the width of parent element.
Width of the element in spaces.
You can also set it in percent, which will calculate the width based on the width of parent element.
```jsx
<Box width={4}>X</Box> //=> 'X '
<Box width={4}>
<Text>X</Text>
</Box>
//=> 'X '
```

@@ -313,14 +349,22 @@

<Box width={10}>
<Box width="50%">X</Box>Y
</Box> //=> 'X Y'
<Box width="50%">
<Text>X</Text>
</Box>
<Text>Y</Text>
</Box>
//=> 'X Y'
```
###### height
##### height
Type: `number`, `string`
Type: `number` `string`
Height of the element in lines (rows). You can also set it in percent, which will calculate the height based on the height of parent element.
Height of the element in lines (rows).
You can also set it in percent, which will calculate the height based on the height of parent element.
```jsx
<Box height={4}>X</Box> //=> 'X\n\n\n'
<Box height={4}>
<Text>X</Text>
</Box>
//=> 'X\n\n\n'
```

@@ -330,81 +374,75 @@

<Box height={6} flexDirection="column">
<Box height="50%">X</Box>Y
</Box> //=> 'X\n\n\nY\n\n'
<Box height="50%">
<Text>X</Text>
</Box>
<Text>Y</Text>
</Box>
//=> 'X\n\n\nY\n\n'
```
###### minWidth
##### minWidth
Type: `number`
Sets a minimum width of the element. Percentages aren't supported yet, see https://github.com/facebook/yoga/issues/872.
Sets a minimum width of the element.
Percentages aren't supported yet, see https://github.com/facebook/yoga/issues/872.
###### minHeight
##### minHeight
Type: `number`
Sets a minimum height of the element. Percentages aren't supported yet, see https://github.com/facebook/yoga/issues/872.
Sets a minimum height of the element.
Percentages aren't supported yet, see https://github.com/facebook/yoga/issues/872.
##### Wrapping
#### Padding
###### textWrap
##### paddingTop
Type: `string`<br>
Values: `wrap` `truncate` `truncate-start` `truncate-middle` `truncate-end`
Type: `number`\
Default: `0`
This property tells Ink to wrap or truncate text content of `<Box>` if its width is larger than container. If `wrap` is passed, Ink will wrap text and split it into multiple lines. If `truncate-*` is passed, Ink will truncate text instead, which will result in one line of text with the rest cut off.
Top padding.
_Note:_ Ink doesn't wrap text by default.
##### paddingBottom
```jsx
<Box textWrap="wrap">Hello World</Box>
//=> 'Hello\nWorld'
Type: `number`\
Default: `0`
// `truncate` is an alias to `truncate-end`
<Box textWrap="truncate">Hello World</Box>
//=> 'Hello…'
Bottom padding.
<Box textWrap="truncate-middle">Hello World</Box>
//=> 'He…ld'
##### paddingLeft
<Box textWrap="truncate-start">Hello World</Box>
//=> '…World'
```
Type: `number`\
Default: `0`
##### Padding
Left padding.
###### paddingTop
##### paddingRight
Type: `number`<br>
Type: `number`\
Default: `0`
###### paddingBottom
Right padding.
Type: `number`<br>
##### paddingX
Type: `number`\
Default: `0`
###### paddingLeft
Horizontal padding. Equivalent to setting `paddingLeft` and `paddingRight`.
Type: `number`<br>
Default: `0`
##### paddingY
###### paddingRight
Type: `number`<br>
Type: `number`\
Default: `0`
###### paddingX
Vertical padding. Equivalent to setting `paddingTop` and `paddingBottom`.
Type: `number`<br>
Default: `0`
##### padding
###### paddingY
Type: `number`<br>
Type: `number`\
Default: `0`
###### padding
Padding on all sides. Equivalent to setting `paddingTop`, `paddingBottom`, `paddingLeft` and `paddingRight`.
Type: `number`<br>
Default: `0`
```jsx

@@ -420,39 +458,53 @@ <Box paddingTop={2}>Top</Box>

##### Margin
#### Margin
###### marginTop
##### marginTop
Type: `number`<br>
Type: `number`\
Default: `0`
###### marginBottom
Top margin.
Type: `number`<br>
##### marginBottom
Type: `number`\
Default: `0`
###### marginLeft
Bottom margin.
Type: `number`<br>
##### marginLeft
Type: `number`\
Default: `0`
###### marginRight
Left margin.
Type: `number`<br>
##### marginRight
Type: `number`\
Default: `0`
###### marginX
Right margin.
Type: `number`<br>
##### marginX
Type: `number`\
Default: `0`
###### marginY
Horizontal margin. Equivalent to setting `marginLeft` and `marginRight`.
Type: `number`<br>
##### marginY
Type: `number`\
Default: `0`
###### margin
Vertical margin. Equivalent to setting `marginTop` and `marginBottom`.
Type: `number`<br>
##### margin
Type: `number`\
Default: `0`
Margin on all sides. Equivalent to setting `marginTop`, `marginBottom`, `marginLeft` and `marginRight`.
```jsx

@@ -468,7 +520,7 @@ <Box marginTop={2}>Top</Box>

##### Flex
#### Flex
###### flexGrow
##### flexGrow
Type: `number`<br>
Type: `number`\
Default: `0`

@@ -480,10 +532,12 @@

<Box>
Label:
<Box flexGrow={1}>Fills all remaining space</Box>
<Text>Label:</Text>
<Box flexGrow={1}>
<Text>Fills all remaining space</Text>
</Box>
</Box>
```
###### flexShrink
##### flexShrink
Type: `number`<br>
Type: `number`\
Default: `1`

@@ -496,11 +550,13 @@

<Box flexShrink={2} width={10}>
Will be 1/4
<Text>Will be 1/4</Text>
</Box>
<Box width={10}>Will be 3/4</Box>
<Box width={10}>
<Text>Will be 3/4</Text>
</Box>
</Box>
```
###### flexBasis
##### flexBasis
Type: `number`, `string`<br>
Type: `number` `string`

@@ -511,4 +567,8 @@ See [flex-basis](https://css-tricks.com/almanac/properties/f/flex-basis/).

<Box width={6}>
<Box flexBasis={3}>X</Box>Y
</Box> //=> 'X Y'
<Box flexBasis={3}>
<Text>X</Text>
</Box>
<Text>Y</Text>
</Box>
//=> 'X Y'
```

@@ -518,10 +578,14 @@

<Box width={6}>
<Box flexBasis="50%">X</Box>Y
</Box> //=> 'X Y'
<Box flexBasis="50%">
<Text>X</Text>
</Box>
<Text>Y</Text>
</Box>
//=> 'X Y'
```
###### flexDirection
##### flexDirection
Type: `string`<br>
Allowed values: `row`, `row-reverse`, `column` and `column-reverse`
Type: `string`\
Allowed values: `row` `row-reverse` `column` `column-reverse`

@@ -532,4 +596,6 @@ See [flex-direction](https://css-tricks.com/almanac/properties/f/flex-direction/).

<Box>
<Box marginRight={1}>X</Box>
<Box>Y</Box>
<Box marginRight={1}>
<Text>X</Text>
</Box>
<Text>Y</Text>
</Box>

@@ -539,4 +605,6 @@ // X Y

<Box flexDirection="row-reverse">
<Box>X</Box>
<Box marginRight={1}>Y</Box>
<Text>X</Text>
<Box marginRight={1}>
<Text>Y</Text>
</Box>
</Box>

@@ -546,4 +614,4 @@ // Y X

<Box flexDirection="column">
<Box>X</Box>
<Box>Y</Box>
<Text>X</Text>
<Text>Y</Text>
</Box>

@@ -554,4 +622,4 @@ // X

<Box flexDirection="column-reverse">
<Box>X</Box>
<Box>Y</Box>
<Text>X</Text>
<Text>Y</Text>
</Box>

@@ -562,13 +630,21 @@ // Y

###### alignItems
##### alignItems
Type: `string`<br>
Allowed values: `flex-start`, `center` and `flex-end`
Type: `string`\
Allowed values: `flex-start` `center` `flex-end`
See [align-items](https://css-tricks.com/almanac/properties/f/align-items/).
See [align-items](https://css-tricks.com/almanac/properties/a/align-items/).
```jsx
<Box alignItems="flex-start">
<Box marginRight={1}>X</Box>
<Box>{`A\nB\nC`}</Box>
<Box marginRight={1}>
<Text>X</Text>
</Box>
<Text>
A
<Newline/>
B
<Newline/>
C
</Text>
</Box>

@@ -580,4 +656,12 @@ // X A

<Box alignItems="center">
<Box marginRight={1}>X</Box>
<Box>{`A\nB\nC`}</Box>
<Box marginRight={1}>
<Text>X</Text>
</Box>
<Text>
A
<Newline/>
B
<Newline/>
C
</Text>
</Box>

@@ -589,4 +673,12 @@ // A

<Box alignItems="flex-end">
<Box marginRight={1}>X</Box>
<Box>{`A\nB\nC`}</Box>
<Box marginRight={1}>
<Text>X</Text>
</Box>
<Text>
A
<Newline/>
B
<Newline/>
C
</Text>
</Box>

@@ -598,12 +690,49 @@ // A

###### justifyContent
##### alignSelf
Type: `string`<br>
Allowed values: `flex-start`, `center`, `flex-end`, `space-between` and `space-around`.
Type: `string`\
Default: `auto`\
Allowed vales: `auto` `flex-start` `center` `flex-end`
See [justify-content](https://css-tricks.com/almanac/properties/f/justify-content/).
See [align-self](https://css-tricks.com/almanac/properties/a/align-self/).
```jsx
<Box height={3}>
<Box alignSelf="flex-start">
<Text>X</Text>
</Box>
</Box>
// X
//
//
<Box height={3}>
<Box alignSelf="center">
<Text>X</Text>
</Box>
</Box>
//
// X
//
<Box height={3}>
<Box alignSelf="flex-end">
<Text>X</Text>
</Box>
</Box>
//
//
// X
```
##### justifyContent
Type: `string`\
Allowed values: `flex-start` `center` `flex-end` `space-between` `space-around`
See [justify-content](https://css-tricks.com/almanac/properties/j/justify-content/).
```jsx
<Box justifyContent="flex-start">
<Box>X</Box>
<Text>X</Text>
</Box>

@@ -613,3 +742,3 @@ // [X ]

<Box justifyContent="center">
<Box>X</Box>
<Text>X</Text>
</Box>

@@ -619,3 +748,3 @@ // [ X ]

<Box justifyContent="flex-end">
<Box>X</Box>
<Text>X</Text>
</Box>

@@ -625,4 +754,4 @@ // [ X]

<Box justifyContent="space-between">
<Box>X</Box>
<Box>Y</Box>
<Text>X</Text>
<Text>Y</Text>
</Box>

@@ -632,4 +761,4 @@ // [X Y]

<Box justifyContent="space-around">
<Box>X</Box>
<Box>Y</Box>
<Text>X</Text>
<Text>Y</Text>
</Box>

@@ -639,224 +768,312 @@ // [ X Y ]

#### `<Color>`
#### Visibility
The `<Color>` component is a simple wrapper around [the `chalk` API](https://github.com/chalk/chalk#api).
It supports all of the chalk's methods as `props`.
##### display
Import:
Type: `string`\
Allowed values: `flex` `none`\
Default: `flex`
```js
import { Color } from "ink";
```
Set this property to `none` to hide the element.
Usage:
#### Borders
##### borderStyle
Type: `string`\
Allowed values: `single` `double` `round` `bold` `singleDouble` `doubleSingle` `classic`
Add a border with a specified style.
If `borderStyle` is `undefined` (which it is by default), no border will be added.
Ink uses border styles from [`cli-boxes`](https://github.com/sindresorhus/cli-boxes) module.
```jsx
<Color rgb={[255, 255, 255]} bgKeyword="magenta">
Hello!
</Color>
<Box flexDirection="column">
<Box>
<Box borderStyle="single" marginRight={2}>
<Text>single</Text>
</Box>
<Color hex="#000000" bgHex="#FFFFFF">
Hey there
</Color>
<Box borderStyle="double" marginRight={2}>
<Text>double</Text>
</Box>
<Color blue>
I'm blue
</Color>
```
<Box borderStyle="round" marginRight={2}>
<Text>round</Text>
</Box>
#### `<Text>`
<Box borderStyle="bold">
<Text>bold</Text>
</Box>
</Box>
This component can change the style of the text, make it bold, underline, italic or strikethrough.
<Box marginTop={1}>
<Box borderStyle="singleDouble" marginRight={2}>
<Text>singleDouble</Text>
</Box>
Import:
<Box borderStyle="doubleSingle" marginRight={2}>
<Text>doubleSingle</Text>
</Box>
```js
import { Text } from "ink";
<Box borderStyle="classic">
<Text>classic</Text>
</Box>
</Box>
</Box>
```
##### bold
<img src="media/box-borderStyle.jpg" width="521">
Type: `boolean`<br>
Default: `false`
See example in [examples/borders](examples/borders/borders.js).
##### italic
##### borderColor
Type: `boolean`<br>
Default: `false`
Type: `string`
##### underline
Change border color.
Accepts the same values as [`color`](#color) in `<Text>` component.
Type: `boolean`<br>
Default: `false`
```jsx
<Box borderStyle="round" borderColor="green">
<Text>Green Rounded Box</Text>
</Box>
```
##### strikethrough
<img src="media/box-borderColor.jpg" width="228">
Type: `boolean`<br>
Default: `false`
### `<Newline>`
Usage:
Adds one or more newline (`\n`) characters.
Must be used within `<Text>` components.
#### count
Type: `number`\
Default: `1`
Number of newlines to insert.
```jsx
<Text bold>I am bold</Text>
<Text italic>I am italic</Text>
<Text underline>I am underline</Text>
<Text strikethrough>I am strikethrough</Text>
import {render, Text, Newline} from 'ink';
const Example = () => (
<Text>
<Text color="green">Hello</Text>
<Newline />
<Text color="red">World</Text>
</Text>
);
render(<Example />);
```
#### `<Static>`
Output:
`<Static>` component allows permanently rendering output to stdout and preserving it across renders.
Components passed to `<Static>` as children will be written to stdout only once and will never be rerendered.
`<Static>` output comes first, before any other output from your components, no matter where it is in the tree.
In order for this mechanism to work properly, at most one `<Static>` component must be present in your node tree and components that were rendered must never update their output. Ink will detect new children appended to `<Static>` and render them to stdout.
```
Hello
World
```
**Note:** `<Static>` accepts only an array of children and each of them must have a unique key.
### `<Spacer>`
Example use case for this component is Jest's output:
A flexible space that expands along the major axis of its containing layout.
It's useful as a shortcut for filling all the available spaces between elements.
![](https://jestjs.io/img/content/feature-fast.png)
For example, using `<Spacer>` in a `<Box>` with default flex direction (`row`) will position "Left" on the left side and will push "Right" to the right side.
Jest continuously writes the list of completed tests to the output, while updating test results at the bottom of the output in real-time. Here's how this user interface could be implemented with Ink:
```jsx
<>
<Static>
{tests.map(test => (
<Test key={test.id} title={test.title} />
))}
</Static>
import {render, Box, Text, Spacer} from 'ink';
<Box marginTop={1}>
<TestResults passed={results.passed} failed={results.failed} />
const Example = () => (
<Box>
<Text>Left</Text>
<Spacer />
<Text>Right</Text>
</Box>
</>
);
render(<Example />);
```
See [examples/jest](examples/jest/jest.js) for a basic implementation of Jest's UI.
In a vertical flex direction (`column`), it will position "Top" to the top of the container and push "Bottom" to the bottom of it.
Note, that container needs to be tall to enough to see this in effect.
#### `<AppContext>`
```jsx
import {render, Box, Text, Spacer} from 'ink';
`<AppContext>` is a [React context](https://reactjs.org/docs/context.html#reactcreatecontext), which exposes a method to manually exit the app (unmount).
const Example = () => (
<Box flexDirection="column" height={10}>
<Text>Top</Text>
<Spacer />
<Text>Bottom</Text>
</Box>
);
Import:
```js
import { AppContext } from "ink";
render(<Example />);
```
##### exit
### `<Static>`
Type: `Function`
`<Static>` component permanently renders its output above everything else.
It's useful for displaying activity like completed tasks or logs - things that
are not changing after they're rendered (hence the name "Static").
Exit (unmount) the whole Ink app.
It's preferred to use `<Static>` for use cases like these, when you can't know
or control the amount of items that need to be rendered.
Usage:
For example, [Tap](https://github.com/tapjs/node-tap) uses `<Static>` to display
a list of completed tests. [Gatsby](https://github.com/gatsbyjs/gatsby) uses it
to display a list of generated pages, while still displaying a live progress bar.
```jsx
<AppContext.Consumer>
{({ exit }) => (
{/* Calling `onExit()` from within <MyApp> will unmount the app */}
<MyApp onExit={exit}/>
)}
</AppContext.Consumer>
```
import React, {useState, useEffect} from 'react';
import {render, Static, Box, Text} from 'ink';
If `exit` is called with an Error, `waitUntilExit` will reject with that error.
const Example = () => {
const [tests, setTests] = useState([]);
#### `<StdinContext>`
useEffect(() => {
let completedTests = 0;
let timer;
`<StdinContext>` is a [React context](https://reactjs.org/docs/context.html#reactcreatecontext), which exposes input stream.
const run = () => {
// Fake 10 completed tests
if (completedTests++ < 10) {
setTests(previousTests => [
...previousTests,
{
id: previousTests.length,
title: `Test #${previousTests.length + 1}`
}
]);
Import:
setTimeout(run, 100);
}
};
```js
import { StdinContext } from "ink";
run();
return () => {
clearTimeout(timer);
};
}, []);
return (
<>
{/* This part will be rendered once to the terminal */}
<Static items={tests}>
{test => (
<Box key={test.id}>
<Text color="green">✔ {test.title}</Text>
</Box>
)}
</Static>
{/* This part keeps updating as state changes */}
<Box marginTop={1}>
<Text dimColor>Completed tests: {tests.length}</Text>
</Box>
</>
);
};
render(<Example />);
```
##### stdin
**Note:** `<Static>` only renders new items in `items` prop and ignores items
that were previously rendered. This means that when you add new items to `items`
array, changes you make to previous items will not trigger a rerender.
Type: `stream.Readable`<br>
Default: `process.stdin`
See [examples/static](examples/static/static.js) for an example usage of `<Static>` component.
Stdin stream passed to `render()` in `options.stdin` or `process.stdin` by default.
Useful if your app needs to handle user input.
#### items
Usage:
Type: `Array`
Array of items of any type to render using a function you pass as a component child.
#### style
Type: `object`
Styles to apply to a container of child elements.
See [`<Box>`](#box) for supported properties.
```jsx
<StdinContext.Consumer>
{({ stdin }) => <MyComponent stdin={stdin} />}
</StdinContext.Consumer>
<Static items={...} style={{padding: 1}}>
{...}
</Static>
```
##### isRawModeSupported
#### children(item)
Type: `boolean`
Type: `Function`
A boolean flag determining if the current `stdin` supports `setRawMode`.
A component using `setRawMode` might want to use `isRawModeSupported` to nicely fall back in environments where raw mode is not supported.
Function that is called to render every item in `items` array.
First argument is an item itself and second argument is index of that item in
`items` array.
Usage:
Note that `key` must be assigned to the root component.
```jsx
<StdinContext.Consumer>
{({ isRawModeSupported, setRawMode, stdin }) =>
isRawModeSupported ? (
<MyInputComponent setRawMode={setRawMode} stdin={stdin} />
) : (
<MyComponentThatDoesntUseInput />
)
}
</StdinContext.Consumer>
<Static items={['a', 'b', 'c']}>
{(item, index) => {
// This function is called for every item in ['a', 'b', 'c']
// `item` is 'a', 'b', 'c'
// `index` is 0, 1, 2
return (
<Box key={index}>
<Text>Item: {item}</Text>
</Box>
);
}}
</Static>
```
##### setRawMode
### `<Transform>`
Type: `function`<br>
Transform a string representation of React components before they are written to output.
For example, you might want to apply a [gradient to text](https://github.com/sindresorhus/ink-gradient), [add a clickable link](https://github.com/sindresorhus/ink-link) or [create some text effects](https://github.com/sindresorhus/ink-big-text).
These use cases can't accept React nodes as input, they are expecting a string.
That's what `<Transform>` component does, it gives you an output string of its child components and lets you transform it in any way.
See [`setRawMode`](https://nodejs.org/api/tty.html#tty_readstream_setrawmode_mode).
Ink exposes this function via own `<StdinContext>` to be able to handle <kbd>Ctrl</kbd>+<kbd>C</kbd>, that's why you should use Ink's `setRawMode` instead of `process.stdin.setRawMode`.
**Note:** `<Transform>` must be applied only to `<Text>` children components and shouldn't change the dimensions of the output, otherwise layout will be incorrect.
**Warning:** This function will throw unless the current `stdin` supports `setRawMode`. Use [`isRawModeSupported`](#israwmodesupported) to detect `setRawMode` support.
```jsx
import {render, Transform} from 'ink';
Usage:
const Example = () => (
<Transform transform={output => output.toUpperCase()}>
<Text>Hello World</Text>
</Transform>
);
```jsx
<StdinContext.Consumer>
{({ setRawMode }) => <MyComponent setRawMode={setRawMode} />}
</StdinContext.Consumer>
render(<Example />);
```
#### `<StdoutContext>`
Since `transform` function converts all characters to upper case, final output that's rendered to the terminal will be "HELLO WORLD", not "Hello World".
`<StdoutContext>` is a [React context](https://reactjs.org/docs/context.html#reactcreatecontext), which exposes stdout stream, where Ink renders your app.
#### transform(children)
Import:
Type: `Function`
```js
import { StdoutContext } from "ink";
```
Function which transforms children output.
It accepts children and must return transformed children too.
##### stdout
##### children
Type: `stream.Writable`<br>
Default: `process.stdout`
Type: `string`
Usage:
Output of child components.
```jsx
<StdoutContext.Consumer>
{({ stdout }) => <MyComponent stdout={stdout} />}
</StdoutContext.Consumer>
```
## Hooks
### useInput
### useInput(inputHandler, options?)
This hook is used for handling user input.
It's a more convienient alternative to using `StdinContext` and listening to `data` events.
It's a more convienient alternative to using `useStdin` and listening to `data` events.
The callback you pass to `useInput` is called for each character when user enters any input.
However, if user pastes text and it's more than one character, the callback will be called only once and the whole string will be passed as `input`.
You can find a full example of using `useInput` at [examples/useinput](examples/useinput/useinput.js).
You can find a full example of using `useInput` at [examples/use-input](examples/use-input/use-input.js).

@@ -881,5 +1098,9 @@ ```jsx

#### inputHandler(input, key)
Type: `Function`
The handler function that you pass to `useInput` receives two arguments:
#### input
##### input

@@ -890,3 +1111,3 @@ Type: `string`

#### key
##### key

@@ -897,11 +1118,11 @@ Type: `object`

##### key.leftArrow
###### key.leftArrow
##### key.rightArrow
###### key.rightArrow
##### key.upArrow
###### key.upArrow
##### key.downArrow
###### key.downArrow
Type: `boolean`<br>
Type: `boolean`\
Default: `false`

@@ -912,5 +1133,5 @@

##### key.return
###### key.return
Type: `boolean`<br>
Type: `boolean`\
Default: `false`

@@ -920,12 +1141,19 @@

##### key.ctrl
###### key.escape
Type: `boolean`<br>
Type: `boolean`\
Default: `false`
Escape key was pressed.
###### key.ctrl
Type: `boolean`\
Default: `false`
Ctrl key was pressed.
##### key.shift
###### key.shift
Type: `boolean`<br>
Type: `boolean`\
Default: `false`

@@ -935,5 +1163,5 @@

##### key.meta
###### key.meta
Type: `boolean`<br>
Type: `boolean`\
Default: `false`

@@ -943,73 +1171,488 @@

### useApp
#### options
`useApp` is a React hook, which exposes props of [`AppContext`](#appcontext).
Type: `object`
##### isActive
Type: `boolean`\
Default: `true`
Enable or disable capturing of user input.
Useful when there are multiple `useInput` hooks used at once to avoid handling the same input several times.
### useApp()
`useApp` is a React hook, which exposes a method to manually exit the app (unmount).
#### exit(error?)
Type: `Function`
Exit (unmount) the whole Ink app.
##### error
Type: `Error`
Optional error. If passed, [`waitUntilExit`](waituntilexit) will reject with that error.
```js
import { useApp } from "ink";
import {useApp} from 'ink';
const MyApp = () => {
const { exit } = useApp();
const Example = () => {
const {exit} = useApp();
// Exit the app after 5 seconds
useEffect(() => {
setTimeout(() => {
exit();
}, 5000);
}, []);
return …
};
```
It's equivalent to consuming `AppContext` props via `AppContext.Consumer`:
### useStdin()
`useStdin` is a React hook, which exposes stdin stream.
#### stdin
Type: `stream.Readable`\
Default: `process.stdin`
Stdin stream passed to `render()` in `options.stdin` or `process.stdin` by default.
Useful if your app needs to handle user input.
```js
import {useStdin} from 'ink';
const Example = () => {
const {stdin} = useStdin();
return …
};
```
#### isRawModeSupported
Type: `boolean`
A boolean flag determining if the current `stdin` supports `setRawMode`.
A component using `setRawMode` might want to use `isRawModeSupported` to nicely fall back in environments where raw mode is not supported.
```jsx
<AppContext.Consumer>
{({ exit }) => {
// …
}}
</AppContext.Consumer>
import {useStdin} from 'ink';
const Example = () => {
const {isRawModeSupported} = useStdin();
return isRawModeSupported ? (
<MyInputComponent />
) : (
<MyComponentThatDoesntUseInput />
);
};
```
### useStdin
#### setRawMode(isRawModeEnabled)
`useStdin` is a React hook, which exposes props of [`StdinContext`](#stdincontext).
Similar to `useApp`, it's equivalent to consuming `StdinContext` directly.
Type: `function`
### useStdout
##### isRawModeEnabled
`useStdout` is a React hook, which exposes props of [`StdoutContext`](#stdoutcontext).
Similar to `useApp`, it's equivalent to consuming `StdoutContext` directly.
Type: `boolean`
## Useful Hooks
See [`setRawMode`](https://nodejs.org/api/tty.html#tty_readstream_setrawmode_mode).
Ink exposes this function to be able to handle <kbd>Ctrl</kbd>+<kbd>C</kbd>, that's why you should use Ink's `setRawMode` instead of `process.stdin.setRawMode`.
- [ink-use-stdout-dimensions](https://github.com/cameronhunter/ink-monorepo/tree/master/packages/ink-use-stdout-dimensions) - Subscribe to stdout dimensions.
**Warning:** This function will throw unless the current `stdin` supports `setRawMode`. Use [`isRawModeSupported`](#israwmodesupported) to detect `setRawMode` support.
## Useful Components
```js
import {useStdin} from 'ink';
- [ink-text-input](https://github.com/vadimdemedes/ink-text-input) - Text input.
- [ink-spinner](https://github.com/vadimdemedes/ink-spinner) - Spinner.
- [ink-select-input](https://github.com/vadimdemedes/ink-select-input) - Select (dropdown) input.
- [ink-link](https://github.com/sindresorhus/ink-link) - Link component.
- [ink-box](https://github.com/sindresorhus/ink-box) - Styled box component.
- [ink-gradient](https://github.com/sindresorhus/ink-gradient) - Gradient color component.
- [ink-big-text](https://github.com/sindresorhus/ink-big-text) - Awesome text component.
- [ink-image](https://github.com/kevva/ink-image) - Display images inside the terminal.
- [ink-tab](https://github.com/jdeniau/ink-tab) - Tab component.
- [ink-color-pipe](https://github.com/LitoMore/ink-color-pipe) - Create color text with simpler style strings in Ink.
- [ink-multi-select](https://github.com/karaggeorge/ink-multi-select) - Select one or more values from a list
- [ink-divider](https://github.com/JureSotosek/ink-divider) - A divider component.
- [ink-progress-bar](https://github.com/brigand/ink-progress-bar) - Configurable component for rendering progress bars.
- [ink-table](https://github.com/maticzav/ink-table) - Table component.
- [ink-ascii](https://github.com/hexrcs/ink-ascii) - Awesome text component with more font choices, based on Figlet.
- [ink-markdown](https://github.com/cameronhunter/ink-markdown) - Render syntax highlighted Markdown.
const Example = () => {
const {setRawMode} = useStdin();
### Incompatible components
useEffect(() => {
setRawMode(true);
These are components that haven't migrated to Ink 2 yet:
return () => {
setRawMode(false);
};
});
- [ink-console](https://github.com/ForbesLindesay/ink-console) - Render output from `console[method]` calls in a scrollable panel.
- [ink-confirm-input](https://github.com/kevva/ink-confirm-input) - Yes/No confirmation input.
- [ink-checkbox-list](https://github.com/MaxMEllon/ink-checkbox-list) - Checkbox.
- [ink-quicksearch](https://github.com/aicioara/ink-quicksearch) - Select Component with fast quicksearch-like navigation
- [ink-autocomplete](https://github.com/maticzav/ink-autocomplete) - Autocomplete.
- [ink-broadcast](https://github.com/jimmed/ink-broadcast) - Implementation of react-broadcast for Ink.
- [ink-router](https://github.com/jimmed/ink-router) - Implementation of react-router for Ink.
- [ink-select](https://github.com/karaggeorge/ink-select) - Select component.
- [ink-scrollbar](https://github.com/karaggeorge/ink-scrollbar) - Scrollbar component.
- [ink-text-animation](https://github.com/yardnsm/ink-text-animation) - Text animation component.
- [ink-figlet](https://github.com/KimotoYanke/ink-figlet) - Large text component with Figlet fonts.
return …
};
```
### useStdout()
`useStdout` is a React hook, which exposes stdout stream, where Ink renders your app.
#### stdout
Type: `stream.Writable`\
Default: `process.stdout`
```js
import {useStdout} from 'ink';
const Example = () => {
const {stdout} = useStdout;
return …
};
```
#### write(data)
Write any string to stdout, while preserving Ink's output.
It's useful when you want to display some external information outside of Ink's rendering and ensure there's no conflict between the two.
It's similar to `<Static>`, except it can't accept components, it only works with strings.
##### data
Type: `string`
Data to write to stdout.
```js
import {useStdout} from 'ink';
const Example = () => {
const {write} = useStdout();
useEffect(() => {
// Write a single message to stdout, above Ink's output
write('Hello from Ink to stdout\n');
}, []);
return …
};
```
See additional usage example in [examples/use-stdout](examples/use-stdout/use-stdout.js).
### useStderr()
`useStderr` is a React hook, which exposes stderr stream.
#### stderr
Type: `stream.Writable`\
Default: `process.stderr`
Stderr stream.
```js
import {useStderr} from 'ink';
const Example = () => {
const {stderr} = useStderr();
return …
};
```
#### write(data)
Write any string to stderr, while preserving Ink's output.
It's useful when you want to display some external information outside of Ink's rendering and ensure there's no conflict between the two.
It's similar to `<Static>`, except it can't accept components, it only works with strings.
##### data
Type: `string`
Data to write to stderr.
```js
import {useStderr} from 'ink';
const Example = () => {
const {write} = useStderr();
useEffect(() => {
// Write a single message to stderr, above Ink's output
write('Hello from Ink to stderr\n');
}, []);
return …
};
```
### useFocus(options?)
Component that uses `useFocus` hook becomes "focusable" to Ink, so when user presses <kbd>Tab</kbd>, Ink will switch focus to this component.
If there are multiple components that execute `useFocus` hook, focus will be given to them in the order that these components are rendered in.
This hook returns an object with `isFocused` boolean property, which determines if this component is focused or not.
#### options
##### autoFocus
Type: `boolean`\
Default: `false`
Auto focus this component, if there's no active (focused) component right now.
##### isActive
Type: `boolean`\
Default: `true`
Enable or disable this component's focus, while still maintaining its position in the list of focusable components.
This is useful for inputs that are temporarily disabled.
```jsx
import {render, useFocus, Text} from 'ink';
const Example = () => {
const {isFocused} = useFocus();
return <Text>{isFocused ? 'I am focused' : 'I am not focused'}</Text>;
};
render(<Example />);
```
See example in [examples/use-focus](examples/use-focus/use-focus.js).
### useFocusManager()
This hook exposes methods to enable or disable focus management for all components or manually switch focus to next or previous components.
#### enableFocus()
Enable focus management for all components.
**Note:** You don't need to call this method manually, unless you've disabled focus management. Focus management is enabled by default.
```js
import {useFocusManager} from 'ink';
const Example = () => {
const {enableFocus} = useFocusManager();
useEffect(() => {
enableFocus();
}, []);
return …
};
```
#### disableFocus()
Disable focus management for all components.
Currently active component (if there's one) will lose its focus.
```js
import {useFocusManager} from 'ink';
const Example = () => {
const {disableFocus} = useFocusManager();
useEffect(() => {
disableFocus();
}, []);
return …
};
```
#### focusNext()
Switch focus to the next focusable component.
If there's no active component right now, focus will be given to the first focusable component.
If active component is the last in the list of focusable components, focus will be switched to the first component.
**Note:** Ink calls this method when user presses <kbd>Tab</kbd>.
```js
import {useFocusManager} from 'ink';
const Example = () => {
const {focusNext} = useFocusManager();
useEffect(() => {
focusNext();
}, []);
return …
};
```
#### focusPrevious()
Switch focus to the previous focusable component.
If there's no active component right now, focus will be given to the first focusable component.
If active component is the first in the list of focusable components, focus will be switched to the last component.
**Note:** Ink calls this method when user presses <kbd>Shift</kbd>+<kbd>Tab</kbd>.
```js
import {useFocusManager} from 'ink';
const Example = () => {
const {focusPrevious} = useFocusManager();
useEffect(() => {
focusPrevious();
}, []);
return …
};
```
## API
#### render(tree, options?)
Returns: [`Instance`](#instance)
Mount a component and render the output.
##### tree
Type: `ReactElement`
##### options
Type: `object`
###### stdout
Type: `stream.Writable`\
Default: `process.stdout`
Output stream where app will be rendered.
###### stdin
Type: `stream.Readable`\
Default: `process.stdin`
Input stream where app will listen for input.
###### exitOnCtrlC
Type: `boolean`\
Default: `true`
Configure whether Ink should listen to Ctrl+C keyboard input and exit the app.
This is needed in case `process.stdin` is in [raw mode](https://nodejs.org/api/tty.html#tty_readstream_setrawmode_mode), because then Ctrl+C is ignored by default and process is expected to handle it manually.
###### patchConsole
Type: `boolean`\
Default: `true`
Patch console methods to ensure console output doesn't mix with Ink output.
When any of `console.*` methods are called (like `console.log()`), Ink intercepts their output, clears main output, renders output from the console method and then rerenders main output again.
That way both are visible and are not overlapping each other.
This functionality is powered by [patch-console](https://github.com/vadimdemedes/patch-console), so if you need to disable Ink's interception of output but want to build something custom, you can use it.
###### debug
Type: `boolean`\
Default: `false`
If `true`, each update will be rendered as a separate output, without replacing the previous one.
#### Instance
This is the object that `render()` returns.
##### rerender(tree)
Replace previous root node with a new one or update props of the current root node.
###### tree
Type: `ReactElement`
```jsx
// Update props of the root node
const {rerender} = render(<Counter count={1} />);
rerender(<Counter count={2} />);
// Replace root node
const {rerender} = render(<OldCounter />);
rerender(<NewCounter />);
```
##### unmount()
Manually unmount the whole Ink app.
```jsx
const {unmount} = render(<MyApp />);
unmount();
```
##### waitUntilExit()
Returns a promise, which resolves when app is unmounted.
```jsx
const {unmount, waitUntilExit} = render(<MyApp />);
setTimeout(unmount, 1000);
await waitUntilExit(); // resolves after `unmount()` is called
```
##### clear()
Clear output.
```jsx
const {clear} = render(<MyApp />);
clear();
```
#### measureElement(ref)
Measure the dimensions of a particular `<Box>` element.
It returns an object with `width` and `height` properties.
This function is useful when your component needs to know the amount of available space it has. You could use it when you need to change the layout based on the length of its content.
**Note:** `measureElement()` returns correct results only after the initial render, when layout has been calculated. Until then, `width` and `height` equal to zero. It's recommended to call `measureElement()` in a `useEffect` hook, which fires after the component has rendered.
##### ref
Type: `MutableRef`
A reference to a `<Box>` element captured with a `ref` property.
See [Refs](https://reactjs.org/docs/refs-and-the-dom.html) for more information on how to capture references.
```jsx
import {render, measureElement, Box, Text} from 'ink';
const Example = () => {
const ref = useRef();
useEffect(() => {
const {width, height} = measureElement(ref.current);
// width = 100, height = 1
}, []);
return (
<Box width={100}>
<Box ref={ref}>
<Text>This box will stretch to 100 width</Text>
</Box>
</Box>
);
};
render(<Example />);
```
## Testing

@@ -1021,49 +1664,78 @@

```jsx
import React from "react";
import { Text } from "ink";
import { render } from "ink-testing-library";
import React from 'react';
import {Text} from 'ink';
import {render} from 'ink-testing-library';
const Test = () => <Text>Hello World</Text>;
const { lastFrame } = render(<Test />);
const {lastFrame} = render(<Test />);
lastFrame() === "Hello World"; //=> true
lastFrame() === 'Hello World'; //=> true
```
Visit [ink-testing-library](https://github.com/vadimdemedes/ink-testing-library) for more examples and full documentation.
Check out [ink-testing-library](https://github.com/vadimdemedes/ink-testing-library) for more examples and full documentation.
## Experimental Mode
## Using React Devtools
Ink has experimental mode, which includes stable new features behind a flag.
They're exposed behind a flag, because I want to be extra sure that it doesn't introduce regressions before shipping this new code for everyone and making it a default.
![](media/devtools.jpg)
Instead of shipping it under `next` tag or something similar, Ink ships it as part of a regular release.
It can be enabled simply by passing `experimental` parameter to `render()` function:
Ink supports [React Devtools](https://github.com/facebook/react/tree/master/packages/react-devtools) out-of-the-box.
To enable integration with React Devtools in your Ink-based CLI, run it with `DEV=true` environment variable:
```jsx
render(<App />, { experimental: true });
```
$ DEV=true my-cli
```
Feel free to use experimental mode in development and I would appreciate if you reported any regressions you might see.
Then, start React Devtools itself:
### More efficient reconciler and renderer
```
$ npx react-devtools
```
Experimental mode enables a new reconciler and renderer, which should significantly improve the rendering performance of your Ink apps.
Ink rebuilds the entire layout and output on every update, which can be taxing if there's a high frequency of updates.
Experimental mode ensures only necessary parts of the layout are updated and limits the number of renders to 60 frames per second.
After it starts up, you should see the component tree of your CLI.
You can even inspect and change the props of components, and see the results immediatelly in the CLI, without restarting it.
### Automatic handling of oversized output
**Note**: You must manually quit your CLI via <kbd>Ctrl</kbd>+<kbd>C</kbd> after you're done testing.
Unfortunately, terminals can't rerender output that is taller than terminal window.
So if your app output has a height of 60 rows, but user resized terminal window to 50 rows, first 10 rows won't be rerendered, because they're out of viewport.
## Useful Components
Experimental mode adopts the same workaround that Jest does, it erases the entire terminal content if output is taller than terminal window. It comes with tradeoffs though:
- [ink-text-input](https://github.com/vadimdemedes/ink-text-input) - Text input.
- [ink-spinner](https://github.com/vadimdemedes/ink-spinner) - Spinner.
- [ink-select-input](https://github.com/vadimdemedes/ink-select-input) - Select (dropdown) input.
- [ink-link](https://github.com/sindresorhus/ink-link) - Link component.
- [ink-box](https://github.com/sindresorhus/ink-box) - Styled box component.
- [ink-gradient](https://github.com/sindresorhus/ink-gradient) - Gradient color component.
- [ink-big-text](https://github.com/sindresorhus/ink-big-text) - Awesome text component.
- [ink-image](https://github.com/kevva/ink-image) - Display images inside the terminal.
- [ink-tab](https://github.com/jdeniau/ink-tab) - Tab component.
- [ink-color-pipe](https://github.com/LitoMore/ink-color-pipe) - Create color text with simpler style strings in Ink.
- [ink-multi-select](https://github.com/karaggeorge/ink-multi-select) - Select one or more values from a list
- [ink-divider](https://github.com/JureSotosek/ink-divider) - A divider component.
- [ink-progress-bar](https://github.com/brigand/ink-progress-bar) - Configurable component for rendering progress bars.
- [ink-table](https://github.com/maticzav/ink-table) - Table component.
- [ink-ascii](https://github.com/hexrcs/ink-ascii) - Awesome text component with more font choices, based on Figlet.
- [ink-markdown](https://github.com/cameronhunter/ink-markdown) - Render syntax highlighted Markdown.
- [ink-quicksearch-input](https://github.com/Eximchain/ink-quicksearch-input) - Select component with fast quicksearch-like navigation.
- [ink-confirm-input](https://github.com/kevva/ink-confirm-input) - Yes/No confirmation input.
- Output can become janky, since erasing terminal is not a "cheap" operation.
- Entire scrollback history in that terminal session will be lost.
## Useful Hooks
It is, however, the only way known now to handle this.
- [ink-use-stdout-dimensions](https://github.com/cameronhunter/ink-monorepo/tree/master/packages/ink-use-stdout-dimensions) - Subscribe to stdout dimensions.
## Examples
- [Jest](examples/jest/jest.js) - Implementation of basic Jest UI [(live demo)](https://ink-jest-demo.vadimdemedes.repl.run/).
- [Counter](examples/counter/counter.js) - Simple counter that increments every 100ms [(live demo)](https://ink-counter-demo.vadimdemedes.repl.run/).
- [Form with Validation](https://github.com/final-form/rff-cli-example) - Manage form state using [Final Form](https://github.com/final-form/final-form#-final-form).
- [Borders](examples/borders/border.js) - Add borders to `<Box>` component.
- [Suspense](examples/suspense/suspenes.js) - Use React Suspense.
- [Table](examples/table/table.js) - Render a table with multiple columns and rows.
- [Focus Management](examples/use-focus/use-focus.js) - Use `useFocus` hook to manage focus between components.
- [User Input](examples/use-input/use-input.js) - Listen to user input.
- [Write to stdout](examples/use-stdout/use-stdout.js) - Write to stdout bypassing main Ink output.
- [Write to stderr](examples/use-stderr/use-stderr.js) - Write to stderr bypassing main Ink output.
- [Static](examples/static/static.js) - Use `<Static>` to render permanent output.
## Maintainers
- [Vadim Demedes](https://github.com/vadimdemedes)
- [Sindre Sorhus](https://github.com/sindresorhus)
- [Vadim Demedes](https://github.com/vadimdemedes)
- [Sindre Sorhus](https://github.com/sindresorhus)
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc