Skip to content
forked from vadimdemedes/ink

🌈 React for interactive command-line apps

License

Notifications You must be signed in to change notification settings

josecatalani/ink

Β 
Β 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation



Ink


React for CLIs. Build and test your CLI output using components.

Build Status

Install

$ npm install ink react

Usage

import React, { Component } from "react";
import { render, Color } from "ink";

class Counter extends Component {
	constructor() {
		super();

		this.state = {
			i: 0
		};
	}

	render() {
		return <Color green>{this.state.i} tests passed</Color>;
	}

	componentDidMount() {
		this.timer = setInterval(() => {
			this.setState({
				i: this.state.i + 1
			});
		}, 100);
	}

	componentWillUnmount() {
		clearInterval(this.timer);
	}
}

render(<Counter />);

You can also check it out live on repl.it sandbox. Feel free to play around with the code and fork this repl at https://repl.it/@vadimdemedes/ink-counter-demo.

Who's Using Ink?

  • Gatsby - Gatsby is a modern web framework for blazing fast websites.
  • Parcel - Blazing fast, zero configuration web application bundler.
  • tap - A Test-Anything-Protocol library for JavaScript.
  • Typewriter - Generates strongly-typed Segment analytics clients from arbitrary JSON Schema.
  • Prisma - The unified data layer for modern applications.
  • Wallace - Pretty CSS analytics on the CLI.
  • tink - Next-generation runtime and package manager.
  • Splash - Observe the splash zone of a change across the Shopify's Polaris component library.
  • emoj - Find relevant emoji on the command-line.
  • emma - Terminal assistant to find and install npm packages.
  • sindresorhus - The Sindre Sorhus CLI.
  • swiff - Multi-environment command line tools for time-saving web developers.
  • share - Quickly share files from your command line.
  • Kubelive - CLI for Kubernetes to provide live data about the cluster and its resources.
  • changelog-view - Tool view changelog in console.
  • gomoku-terminal - Play online Gomoku in the terminal.
  • cfpush - An interactive Cloud Foundry tutorial in your terminal.
  • startd - Turn your React component into a web app from the command-line.
  • wiki-cli - Search Wikipedia and read summaries directly in your terminal.

Contents

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 to allow Flexbox layouts in the terminal. If you are already familiar with React, you already know Ink.

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.

To get started with Ink quickly, use 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, configure it in package.json:

{
	"babel": {
		"presets": [
			"@babel/preset-react",
			[
				"@babel/preset-env",
				{
					"targets": {
						"node": true
					}
				}
			]
		]
	}
}

Don't forget to import React into every file that contains JSX:

import React from "react";
import { render, Box } from "ink";

const Demo = () => <Box>Hello World</Box>;

render(<Demo />);

Examples

API

Since Ink is a React renderer, it means that all features of React are supported. Head over to React website for documentation on how to use it. In this readme only Ink's methods will be documented.

render(tree, options)

Returns: 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, because then Ctrl+C is ignored by default and process is expected to handle it manually.

debug

Type: boolean
Default: false

If true, each update will be rendered as a separate output, without replacing the previous one.

experimental

Type: boolean
Default: false

Enables experimental mode.

import React, { Component } from "react";
import { render, Box } from "ink";

class Counter extends Component {
	constructor() {
		super();

		this.state = {
			i: 0
		};
	}

	render() {
		return <Box>Iteration #{this.state.i}</Box>;
	}

	componentDidMount() {
		this.timer = setInterval(() => {
			this.setState(prevState => ({
				i: prevState.i + 1
			}));
		}, 100);
	}

	componentWillUnmount() {
		clearInterval(this.timer);
	}
}

const app = render(<Counter />);

setTimeout(() => {
	// Enough counting
	app.unmount();
}, 1000);

There's also a shortcut to avoid passing options object:

render(<Counter>, process.stdout);

Instance

This is the object that render() returns.

rerender

Replace previous root node with a new one or update props of the current root node.

// 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.

const { unmount } = render(<MyApp />);
unmount();
waitUntilExit

Returns a promise, which resolves when app is unmounted.

const { unmount, waitUntilExit } = render(<MyApp />);

setTimeout(unmount, 1000);

await waitUntilExit(); // resolves after `unmount()` is called

Building Layouts

Ink uses 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.

Built-in Components

<Box>

<Box> it's an essential Ink component to build your layout. It's like a <div style="display: flex"> in a browser.

Import:

import { Box } from "ink";
Dimensions
width

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.

<Box width={4}>X</Box> //=> 'X   '
<Box width={10}>
	<Box width="50%">X</Box>Y
</Box> //=> 'X    Y'
height

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.

<Box height={4}>X</Box> //=> 'X\n\n\n'
<Box height={6} flexDirection="column">
	<Box height="50%">X</Box>Y
</Box> //=> 'X\n\n\nY\n\n'
minWidth

Type: number

Sets a minimum width of the element. Percentages aren't supported yet, see facebook/yoga#872.

minHeight

Type: number

Sets a minimum height of the element. Percentages aren't supported yet, see facebook/yoga#872.

Wrapping
textWrap

Type: string
Values: wrap truncate truncate-start truncate-middle truncate-end

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.

Note: Ink doesn't wrap text by default.

<Box textWrap="wrap">Hello World</Box>
//=> 'Hello\nWorld'

// `truncate` is an alias to `truncate-end`
<Box textWrap="truncate">Hello World</Box>
//=> 'Hello…'

<Box textWrap="truncate-middle">Hello World</Box>
//=> 'He…ld'

<Box textWrap="truncate-start">Hello World</Box>
//=> '…World'
Padding
paddingTop

Type: number
Default: 0

paddingBottom

Type: number
Default: 0

paddingLeft

Type: number
Default: 0

paddingRight

Type: number
Default: 0

paddingX

Type: number
Default: 0

paddingY

Type: number
Default: 0

padding

Type: number
Default: 0

<Box paddingTop={2}>Top</Box>
<Box paddingBottom={2}>Bottom</Box>
<Box paddingLeft={2}>Left</Box>
<Box paddingRight={2}>Right</Box>
<Box paddingX={2}>Left and right</Box>
<Box paddingY={2}>Top and bottom</Box>
<Box padding={2}>Top, bottom, left and right</Box>
Margin
marginTop

Type: number
Default: 0

marginBottom

Type: number
Default: 0

marginLeft

Type: number
Default: 0

marginRight

Type: number
Default: 0

marginX

Type: number
Default: 0

marginY

Type: number
Default: 0

margin

Type: number
Default: 0

<Box marginTop={2}>Top</Box>
<Box marginBottom={2}>Bottom</Box>
<Box marginLeft={2}>Left</Box>
<Box marginRight={2}>Right</Box>
<Box marginX={2}>Left and right</Box>
<Box marginY={2}>Top and bottom</Box>
<Box margin={2}>Top, bottom, left and right</Box>
Flex
flexGrow

Type: number
Default: 0

See flex-grow.

<Box>
	Label:
	<Box flexGrow={1}>Fills all remaining space</Box>
</Box>
flexShrink

Type: number
Default: 1

See flex-shrink.

<Box width={20}>
	<Box flexShrink={2} width={10}>
		Will be 1/4
	</Box>
	<Box width={10}>Will be 3/4</Box>
</Box>
flexBasis

Type: number, string

See flex-basis.

<Box width={6}>
	<Box flexBasis={3}>X</Box>Y
</Box> //=> 'X  Y'
<Box width={6}>
	<Box flexBasis="50%">X</Box>Y
</Box> //=> 'X  Y'
flexDirection

Type: string
Allowed values: row, row-reverse, column and column-reverse

See flex-direction.

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

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

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

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

Type: string
Allowed values: flex-start, center and flex-end

See align-items.

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

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

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

Type: string
Allowed values: flex-start, center, flex-end, space-between and space-around.

See justify-content.

<Box justifyContent="flex-start">
	<Box>X</Box>
</Box>
// [X      ]

<Box justifyContent="center">
	<Box>X</Box>
</Box>
// [   X   ]

<Box justifyContent="flex-end">
	<Box>X</Box>
</Box>
// [      X]

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

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

<Color>

The <Color> component is a simple wrapper around the chalk API. It supports all of the chalk's methods as props.

Import:

import { Color } from "ink";

Usage:

<Color rgb={[255, 255, 255]} bgKeyword="magenta">
	Hello!
</Color>

<Color hex="#000000" bgHex="#FFFFFF">
	Hey there
</Color>

<Color blue>
	I'm blue
</Color>

<Text>

This component can change the style of the text, make it bold, underline, italic or strikethrough.

Import:

import { Text } from "ink";
bold

Type: boolean
Default: false

italic

Type: boolean
Default: false

underline

Type: boolean
Default: false

strikethrough

Type: boolean
Default: false

Usage:

<Text bold>I am bold</Text>
<Text italic>I am italic</Text>
<Text underline>I am underline</Text>
<Text strikethrough>I am strikethrough</Text>

<Static>

<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.

Note: <Static> accepts only an array of children and each of them must have a unique key.

Example use case for this component is Jest's output:

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:

<>
	<Static>
		{tests.map(test => (
			<Test key={test.id} title={test.title} />
		))}
	</Static>

	<Box marginTop={1}>
		<TestResults passed={results.passed} failed={results.failed} />
	</Box>
</>

See examples/jest for a basic implementation of Jest's UI.

<AppContext>

<AppContext> is a React context, which exposes a method to manually exit the app (unmount).

Import:

import { AppContext } from "ink";
exit

Type: Function

Exit (unmount) the whole Ink app.

Usage:

<AppContext.Consumer>
	{({ exit }) => (
		{/* Calling `onExit()` from within <MyApp> will unmount the app */}
		<MyApp onExit={exit}/>
	)}
</AppContext.Consumer>

If exit is called with an Error, waitUntilExit will reject with that error.

<StdinContext>

<StdinContext> is a React context, which exposes input stream.

Import:

import { StdinContext } from "ink";
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.

Usage:

<StdinContext.Consumer>
	{({ stdin }) => <MyComponent stdin={stdin} />}
</StdinContext.Consumer>
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.

Usage:

<StdinContext.Consumer>
	{({ isRawModeSupported, setRawMode, stdin }) =>
		isRawModeSupported ? (
			<MyInputComponent setRawMode={setRawMode} stdin={stdin} />
		) : (
			<MyComponentThatDoesntUseInput />
		)
	}
</StdinContext.Consumer>
setRawMode

Type: function

See setRawMode. Ink exposes this function via own <StdinContext> to be able to handle Ctrl+C, that's why you should use Ink's setRawMode instead of process.stdin.setRawMode.

Warning: This function will throw unless the current stdin supports setRawMode. Use isRawModeSupported to detect setRawMode support.

Usage:

<StdinContext.Consumer>
	{({ setRawMode }) => <MyComponent setRawMode={setRawMode} />}
</StdinContext.Consumer>

<StdoutContext>

<StdoutContext> is a React context, which exposes stdout stream, where Ink renders your app.

Import:

import { StdoutContext } from "ink";
stdout

Type: stream.Writable
Default: process.stdout

Usage:

<StdoutContext.Consumer>
	{({ stdout }) => <MyComponent stdout={stdout} />}
</StdoutContext.Consumer>

Hooks

useInput

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. You can find a full example of using useInput at examples/useinput.

import {useInput} from 'ink';

const UserInput = () => {
	useInput((input, key) => {
		if (input === 'q') {
			// Exit program
		}

		if (key.leftArrow) {
			// Left arrow key pressed
		}
	});

	return …
};

The handler function that you pass to useInput receives two arguments:

input

Type: string

The input that the program received.

key

Type: object

Handy information about a key that was pressed.

key.leftArrow
key.rightArrow
key.upArrow
key.downArrow

Type: boolean
Default: false

If an arrow key was pressed, the corresponding property will be true. For example, if user presses left arrow key, key.leftArrow equals true.

key.return

Type: boolean
Default: false

Return (Enter) key was pressed.

key.ctrl

Type: boolean
Default: false

Ctrl key was pressed.

key.shift

Type: boolean
Default: false

Shift key was pressed.

key.meta

Type: boolean
Default: false

Meta key was pressed.

useApp

useApp is a React hook, which exposes props of AppContext.

import { useApp } from "ink";

const MyApp = () => {
	const { exit } = useApp();
};

It's equivalent to consuming AppContext props via AppContext.Consumer:

<AppContext.Consumer>
	{({ exit }) => {
		// …
	}}
</AppContext.Consumer>

useStdin

useStdin is a React hook, which exposes props of StdinContext. Similar to useApp, it's equivalent to consuming StdinContext directly.

useStdout

useStdout is a React hook, which exposes props of StdoutContext. Similar to useApp, it's equivalent to consuming StdoutContext directly.

Useful Hooks

Useful Components

Incompatible components

These are components that haven't migrated to Ink 2 yet:

Testing

Ink components are simple to test with ink-testing-library. Here's a simple example that checks how component is rendered:

import React from "react";
import { Text } from "ink";
import { render } from "ink-testing-library";

const Test = () => <Text>Hello World</Text>;
const { lastFrame } = render(<Test />);

lastFrame() === "Hello World"; //=> true

Visit ink-testing-library for more examples and full documentation.

Experimental Mode

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.

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:

render(<App />, { experimental: true });

Feel free to use experimental mode in development and I would appreciate if you reported any regressions you might see.

More efficient reconciler and renderer

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.

Automatic handling of oversized output

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.

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:

  • Output can become janky, since erasing terminal is not a "cheap" operation.
  • Entire scrollback history in that terminal session will be lost.

It is, however, the only way known now to handle this.

Maintainers

About

🌈 React for interactive command-line apps

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 99.7%
  • TypeScript 0.3%