8946c789c6882ca2e1947c9784d0903acdeca908.svn-base 25.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
<h1 align="center">
	<br>
	<br>
	<img width="300" alt="Ink" src="media/logo.png">
	<br>
	<br>
	<br>
</h1>

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

![Build Status](https://github.com/vadimdemedes/ink/workflows/tests/badge.svg)

## Install

```
$ npm install ink react
```

## Usage

```jsx
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 />);
```

<img src="media/demo.svg" width="600">

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

## Who's Using Ink?

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

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

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.

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](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`:

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

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

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

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

render(<Demo />);
```

## 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) - Using framework agnostic form library, [🏁 Final Form](https://github.com/final-form/final-form#-final-form) to manage input state.

## API

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.

#### render(tree, options)

Returns: `Instance`

Mount a component and render the output.

##### tree

Type: `ReactElement`

##### options

Type: `Object`

###### stdout

Type: `stream.Writable`<br>
Default: `process.stdout`

Output stream where app will be rendered.

###### stdin

Type: `stream.Readable`<br>
Default: `process.stdin`

Input stream where app will listen for input.

###### exitOnCtrlC

Type: `boolean`<br>
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.

###### debug

Type: `boolean`<br>
Default: `false`

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

###### experimental

Type: `boolean`<br>
Default: `false`

Enables [experimental mode](#experimental-mode).

```jsx
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:

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

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

## Building Layouts

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.

### 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:

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

```jsx
<Box width={4}>X</Box> //=> 'X   '
```

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

```jsx
<Box height={4}>X</Box> //=> 'X\n\n\n'
```

```jsx
<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 https://github.com/facebook/yoga/issues/872.

###### minHeight

Type: `number`

Sets a minimum height of the element. Percentages aren't supported yet, see https://github.com/facebook/yoga/issues/872.

##### Wrapping

###### textWrap

Type: `string`<br>
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.

```jsx
<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`<br>
Default: `0`

###### paddingBottom

Type: `number`<br>
Default: `0`

###### paddingLeft

Type: `number`<br>
Default: `0`

###### paddingRight

Type: `number`<br>
Default: `0`

###### paddingX

Type: `number`<br>
Default: `0`

###### paddingY

Type: `number`<br>
Default: `0`

###### padding

Type: `number`<br>
Default: `0`

```jsx
<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`<br>
Default: `0`

###### marginBottom

Type: `number`<br>
Default: `0`

###### marginLeft

Type: `number`<br>
Default: `0`

###### marginRight

Type: `number`<br>
Default: `0`

###### marginX

Type: `number`<br>
Default: `0`

###### marginY

Type: `number`<br>
Default: `0`

###### margin

Type: `number`<br>
Default: `0`

```jsx
<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`<br>
Default: `0`

See [flex-grow](https://css-tricks.com/almanac/properties/f/flex-grow/).

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

###### flexShrink

Type: `number`<br>
Default: `1`

See [flex-shrink](https://css-tricks.com/almanac/properties/f/flex-shrink/).

```jsx
<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`<br>

See [flex-basis](https://css-tricks.com/almanac/properties/f/flex-basis/).

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

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

###### flexDirection

Type: `string`<br>
Allowed values: `row`, `row-reverse`, `column` and `column-reverse`

See [flex-direction](https://css-tricks.com/almanac/properties/f/flex-direction/).

```jsx
<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`<br>
Allowed values: `flex-start`, `center` and `flex-end`

See [align-items](https://css-tricks.com/almanac/properties/f/align-items/).

```jsx
<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`<br>
Allowed values: `flex-start`, `center`, `flex-end`, `space-between` and `space-around`.

See [justify-content](https://css-tricks.com/almanac/properties/f/justify-content/).

```jsx
<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](https://github.com/chalk/chalk#api).
It supports all of the chalk's methods as `props`.

Import:

```js
import { Color } from "ink";
```

Usage:

```jsx
<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:

```js
import { Text } from "ink";
```

##### bold

Type: `boolean`<br>
Default: `false`

##### italic

Type: `boolean`<br>
Default: `false`

##### underline

Type: `boolean`<br>
Default: `false`

##### strikethrough

Type: `boolean`<br>
Default: `false`

Usage:

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

#### `<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:

![](https://jestjs.io/img/content/feature-fast.png)

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>

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

See [examples/jest](examples/jest/jest.js) for a basic implementation of Jest's UI.

#### `<AppContext>`

`<AppContext>` is a [React context](https://reactjs.org/docs/context.html#reactcreatecontext), which exposes a method to manually exit the app (unmount).

Import:

```js
import { AppContext } from "ink";
```

##### exit

Type: `Function`

Exit (unmount) the whole Ink app.

Usage:

```jsx
<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](https://reactjs.org/docs/context.html#reactcreatecontext), which exposes input stream.

Import:

```js
import { StdinContext } from "ink";
```

##### stdin

Type: `stream.Readable`<br>
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:

```jsx
<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:

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

##### setRawMode

Type: `function`<br>

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

**Warning:** This function will throw unless the current `stdin` supports `setRawMode`. Use [`isRawModeSupported`](#israwmodesupported) to detect `setRawMode` support.

Usage:

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

#### `<StdoutContext>`

`<StdoutContext>` is a [React context](https://reactjs.org/docs/context.html#reactcreatecontext), which exposes stdout stream, where Ink renders your app.

Import:

```js
import { StdoutContext } from "ink";
```

##### stdout

Type: `stream.Writable`<br>
Default: `process.stdout`

Usage:

```jsx
<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](examples/useinput/useinput.js).

```jsx
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`<br>
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`<br>
Default: `false`

Return (Enter) key was pressed.

##### key.ctrl

Type: `boolean`<br>
Default: `false`

Ctrl key was pressed.

##### key.shift

Type: `boolean`<br>
Default: `false`

Shift key was pressed.

##### key.meta

Type: `boolean`<br>
Default: `false`

[Meta key](https://en.wikipedia.org/wiki/Meta_key) was pressed.

### useApp

`useApp` is a React hook, which exposes props of [`AppContext`](#appcontext).

```js
import { useApp } from "ink";

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

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

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

### useStdin

`useStdin` is a React hook, which exposes props of [`StdinContext`](#stdincontext).
Similar to `useApp`, it's equivalent to consuming `StdinContext` directly.

### useStdout

`useStdout` is a React hook, which exposes props of [`StdoutContext`](#stdoutcontext).
Similar to `useApp`, it's equivalent to consuming `StdoutContext` directly.

## Useful Hooks

-   [ink-use-stdout-dimensions](https://github.com/cameronhunter/ink-monorepo/tree/master/packages/ink-use-stdout-dimensions) - Subscribe to stdout dimensions.

## Useful Components

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

### Incompatible components

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

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

## Testing

Ink components are simple to test with [ink-testing-library](https://github.com/vadimdemedes/ink-testing-library).
Here's a simple example that checks how component is rendered:

```jsx
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](https://github.com/vadimdemedes/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:

```jsx
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

-   [Vadim Demedes](https://github.com/vadimdemedes)
-   [Sindre Sorhus](https://github.com/sindresorhus)