Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

🌈 React for interactive command-line apps

License

NotificationsYou must be signed in to change notification settings

vadimdemedes/ink

Repository files navigation




Ink


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

Build Statusnpm

Ink provides the same component-based UI building experience that React offers in the browser, but for command-line apps.It usesYoga 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 toReact website for documentation on how to use it.Only Ink's methods will be documented in this readme.

Note: This is documentation for Ink 4 and 5. If you're looking for docs on Ink 3, check outthis release.


Install

npm install ink react

Usage

importReact,{useState,useEffect}from'react';import{render,Text}from'ink';constCounter=()=>{const[counter,setCounter]=useState(0);useEffect(()=>{consttimer=setInterval(()=>{setCounter(previousCounter=>previousCounter+1);},100);return()=>{clearInterval(timer);};},[]);return<Textcolor="green">{counter} tests passed</Text>;};render(<Counter/>);

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

Who's Using Ink?

  • Claude Code - An agentic coding tool made by Anthropic.
  • GitHub Copilot for CLI - Just say what you want the shell to do.
  • Cloudflare's Wrangler - The CLI for Cloudflare Workers.
  • Linear - Linear built an internal CLI for managing deployments, configs and other housekeeping tasks.
  • Gatsby - Gatsby is a modern web framework for blazing fast websites.
  • tap - A Test-Anything-Protocol library for JavaScript.
  • Terraform CDK - CDK (Cloud Development Kit) for HashiCorp Terraform.
  • Specify CLI - Automate the distribution of your design tokens.
  • Twilio's SIGNAL - CLI for Twilio's SIGNAL conference.Blog post.
  • Typewriter - Generates strongly-typedSegment analytics clients from arbitrary JSON Schema.
  • Prisma - The unified data layer for modern applications.
  • Blitz - The Fullstack React Framework.
  • New York Times - NYT uses Inkkyt - a toolkit that encapsulates and manages the configuration for web apps.
  • tink - Next-generation runtime and package manager.
  • Inkle - Wordle game.
  • loki - Visual regression testing for Storybook.
  • Bit - Build, distribute and collaborate on components.
  • Remirror - Your friendly, world-class editor toolkit.
  • Prime - Open source GraphQL CMS.
  • emoj - Find relevant emojis.
  • emma - Find and install npm packages.
  • npm-check-extras - Check for outdated and unused dependencies, and run update/delete action over selected ones.
  • swiff - Multi-environment command line tools for time-saving web developers.
  • share - Quickly share files.
  • Kubelive - CLI for Kubernetes to provide live data about the cluster and its resources.
  • changelog-view - View changelogs.
  • cfpush - An interactive Cloud Foundry tutorial.
  • startd - Turn your React component into a web app.
  • wiki-cli - Search Wikipedia and read summaries.
  • garson - Build interactive config-based command-line interfaces.
  • git-contrib-calendar - Display a contributions calendar for any git repository.
  • gitgud - An interactive command-line GUI for Git.
  • Autarky - Find and delete oldnode_modules directories in order to free up disk space.
  • fast-cli - Test your download and upload speed.
  • tasuku - Minimal task runner.
  • mnswpr - Minesweeper game.
  • lrn - Learning by repetition.
  • turdle - Wordle game.
  • Shopify CLI - Build apps, themes, and storefronts for Shopify.
  • ToDesktop CLI - An all-in-one platform for building Electron apps.
  • Walle - Full-featured crypto wallet for EVM networks.
  • Sudoku - Sudoku game.
  • Sea Trader - Taipan! inspired trading simulator game.

Contents

Getting Started

Usecreate-ink-app to quickly scaffold a new Ink-based CLI.

npx create-ink-app my-ink-cli

Alternatively, create a TypeScript project:

npx create-ink-app --typescript my-ink-cli
Manual JavaScript setup

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.Afterinstalling Babel, install@babel/preset-react and insert the following configuration inbabel.config.json:

npm install --save-dev @babel/preset-react
{"presets": ["@babel/preset-react"]}

Next, create a filesource.js, where you'll type code that uses Ink:

importReactfrom'react';import{render,Text}from'ink';constDemo=()=><Text>Hello World</Text>;render(<Demo/>);

Then, transpile this file with Babel:

npx babel source.js -o cli.js

Now you can runcli.js with Node.js:

node cli

If you don't like transpiling files during development, you can useimport-jsx or@esbuild-kit/esm-loader toimport a JSX file and transpile it on the fly.

Ink usesYoga - 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 haddisplay: flex.See<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> component.

Components

<Text>

This component can display text, and change its style to make it bold, underline, italic or strikethrough.

import{render,Text}from'ink';constExample=()=>(<><Textcolor="green">I am green</Text><Textcolor="black"backgroundColor="white">I am black on white</Text><Textcolor="#ffffff">I am white</Text><Textbold>I am bold</Text><Textitalic>I am italic</Text><Textunderline>I am underline</Text><Textstrikethrough>I am strikethrough</Text><Textinverse>I am inversed</Text></>);render(<Example/>);

Note:<Text> allows only text nodes and nested<Text> components inside of it. For example,<Box> component can't be used inside<Text>.

color

Type:string

Change text color.Ink useschalk under the hood, so all its functionality is supported.

<Textcolor="green">Green</Text><Textcolor="#005cc5">Blue</Text><Textcolor="rgb(232, 131, 136)">Red</Text>

backgroundColor

Type:string

Same ascolor above, but for background.

<TextbackgroundColor="green"color="white">Green</Text><TextbackgroundColor="#005cc5"color="white">Blue</Text><TextbackgroundColor="rgb(232, 131, 136)"color="white">Red</Text>

dimColor

Type:boolean
Default:false

Dim the color (emit a small amount of light).

<Textcolor="red"dimColor>Dimmed Red</Text>

bold

Type:boolean
Default:false

Make the text bold.

italic

Type:boolean
Default:false

Make the text italic.

underline

Type:boolean
Default:false

Make the text underlined.

strikethrough

Type:boolean
Default:false

Make the text crossed with a line.

inverse

Type:boolean
Default:false

Inverse background and foreground colors.

<Textinversecolor="yellow">Inversed Yellow</Text>

wrap

Type:string
Allowed values:wraptruncatetruncate-starttruncate-middletruncate-end
Default:wrap

This property tells Ink to wrap or truncate text if its width is larger than container.Ifwrap is passed (by default), Ink will wrap text and split it into multiple lines.Iftruncate-* is passed, Ink will truncate text instead, which will result in one line of text with the rest cut off.

<Boxwidth={7}><Text>Hello World</Text></Box>//=> 'Hello\nWorld'// `truncate` is an alias to `truncate-end`<Boxwidth={7}><Textwrap="truncate">Hello World</Text></Box>//=> 'Hello…'<Boxwidth={7}><Textwrap="truncate-middle">Hello World</Text></Box>//=> 'He…ld'<Boxwidth={7}><Textwrap="truncate-start">Hello World</Text></Box>//=> '…World'

<Box>

<Box> is an essential Ink component to build your layout.It's like<div> in the browser.

import{render,Box,Text}from'ink';constExample=()=>(<Boxmargin={2}><Text>This is a box with margin</Text></Box>);render(<Example/>);

Dimensions

width

Type:numberstring

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.

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

Type:numberstring

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.

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

Type:number

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

minHeight

Type:number

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

Padding

paddingTop

Type:number
Default:0

Top padding.

paddingBottom

Type:number
Default:0

Bottom padding.

paddingLeft

Type:number
Default:0

Left padding.

paddingRight

Type:number
Default:0

Right padding.

paddingX

Type:number
Default:0

Horizontal padding. Equivalent to settingpaddingLeft andpaddingRight.

paddingY

Type:number
Default:0

Vertical padding. Equivalent to settingpaddingTop andpaddingBottom.

padding

Type:number
Default:0

Padding on all sides. Equivalent to settingpaddingTop,paddingBottom,paddingLeft andpaddingRight.

<BoxpaddingTop={2}>Top</Box><BoxpaddingBottom={2}>Bottom</Box><BoxpaddingLeft={2}>Left</Box><BoxpaddingRight={2}>Right</Box><BoxpaddingX={2}>Left and right</Box><BoxpaddingY={2}>Topandbottom</Box><Boxpadding={2}>Top, bottom, left and right</Box>

Margin

marginTop

Type:number
Default:0

Top margin.

marginBottom

Type:number
Default:0

Bottom margin.

marginLeft

Type:number
Default:0

Left margin.

marginRight

Type:number
Default:0

Right margin.

marginX

Type:number
Default:0

Horizontal margin. Equivalent to settingmarginLeft andmarginRight.

marginY

Type:number
Default:0

Vertical margin. Equivalent to settingmarginTop andmarginBottom.

margin

Type:number
Default:0

Margin on all sides. Equivalent to settingmarginTop,marginBottom,marginLeft andmarginRight.

<BoxmarginTop={2}>Top</Box><BoxmarginBottom={2}>Bottom</Box><BoxmarginLeft={2}>Left</Box><BoxmarginRight={2}>Right</Box><BoxmarginX={2}>Left and right</Box><BoxmarginY={2}>Topandbottom</Box><Boxmargin={2}>Top, bottom, left and right</Box>

Gap

gap

Type:number
Default:0

Size of the gap between an element's columns and rows. Shorthand forcolumnGap androwGap.

<Boxgap={1}width={3}flexWrap="wrap"><Text>A</Text><Text>B</Text><Text>C</Text></Box>// A B//// C

columnGap

Type:number
Default:0

Size of the gap between an element's columns.

<BoxcolumnGap={1}><Text>A</Text><Text>B</Text></Box>// A B

rowGap

Type:number
Default:0

Size of the gap between element's rows.

<BoxflexDirection="column"rowGap={1}><Text>A</Text><Text>B</Text></Box>// A//// B

Flex

flexGrow

Type:number
Default:0

Seeflex-grow.

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

Type:number
Default:1

Seeflex-shrink.

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

Type:numberstring

Seeflex-basis.

<Boxwidth={6}><BoxflexBasis={3}><Text>X</Text></Box><Text>Y</Text></Box>//=> 'X  Y'
<Boxwidth={6}><BoxflexBasis="50%"><Text>X</Text></Box><Text>Y</Text></Box>//=> 'X  Y'
flexDirection

Type:string
Allowed values:rowrow-reversecolumncolumn-reverse

Seeflex-direction.

<Box><BoxmarginRight={1}><Text>X</Text></Box><Text>Y</Text></Box>// X Y<BoxflexDirection="row-reverse"><Text>X</Text><BoxmarginRight={1}><Text>Y</Text></Box></Box>// Y X<BoxflexDirection="column"><Text>X</Text><Text>Y</Text></Box>// X// Y<BoxflexDirection="column-reverse"><Text>X</Text><Text>Y</Text></Box>// Y// X
flexWrap

Type:string
Allowed values:nowrapwrapwrap-reverse

Seeflex-wrap.

<Boxwidth={2}flexWrap="wrap"><Text>A</Text><Text>BC</Text></Box>// A// B C
<BoxflexDirection="column"height={2}flexWrap="wrap"><Text>A</Text><Text>B</Text><Text>C</Text></Box>// A C// B
alignItems

Type:string
Allowed values:flex-startcenterflex-end

Seealign-items.

<BoxalignItems="flex-start"><BoxmarginRight={1}><Text>X</Text></Box><Text>A<Newline/>B<Newline/>C</Text></Box>// X A//   B//   C<BoxalignItems="center"><BoxmarginRight={1}><Text>X</Text></Box><Text>A<Newline/>B<Newline/>C</Text></Box>//   A// X B//   C<BoxalignItems="flex-end"><BoxmarginRight={1}><Text>X</Text></Box><Text>A<Newline/>B<Newline/>C</Text></Box>//   A//   B// X C
alignSelf

Type:string
Default:auto
Allowed values:autoflex-startcenterflex-end

Seealign-self.

<Boxheight={3}><BoxalignSelf="flex-start"><Text>X</Text></Box></Box>// X////<Boxheight={3}><BoxalignSelf="center"><Text>X</Text></Box></Box>//// X//<Boxheight={3}><BoxalignSelf="flex-end"><Text>X</Text></Box></Box>////// X
justifyContent

Type:string
Allowed values:flex-startcenterflex-endspace-betweenspace-aroundspace-evenly

Seejustify-content.

<BoxjustifyContent="flex-start"><Text>X</Text></Box>// [X      ]<BoxjustifyContent="center"><Text>X</Text></Box>// [   X   ]<BoxjustifyContent="flex-end"><Text>X</Text></Box>// [      X]<BoxjustifyContent="space-between"><Text>X</Text><Text>Y</Text></Box>// [X      Y]<BoxjustifyContent="space-around"><Text>X</Text><Text>Y</Text></Box>// [  X   Y  ]<BoxjustifyContent="space-evenly"><Text>X</Text><Text>Y</Text></Box>// [   X   Y   ]

Visibility

display

Type:string
Allowed values:flexnone
Default:flex

Set this property tonone to hide the element.

overflowX

Type:string
Allowed values:visiblehidden
Default:visible

Behavior for an element's overflow in horizontal direction.

overflowY

Type:string
Allowed values:visiblehidden
Default:visible

Behavior for an element's overflow in vertical direction.

overflow

Type:string
Allowed values:visiblehidden
Default:visible

Shortcut for settingoverflowX andoverflowY at the same time.

Borders

borderStyle

Type:string
Allowed values:singledoubleroundboldsingleDoubledoubleSingleclassic |BoxStyle

Add a border with a specified style.IfborderStyle isundefined (which it is by default), no border will be added.Ink uses border styles fromcli-boxes module.

<BoxflexDirection="column"><Box><BoxborderStyle="single"marginRight={2}><Text>single</Text></Box><BoxborderStyle="double"marginRight={2}><Text>double</Text></Box><BoxborderStyle="round"marginRight={2}><Text>round</Text></Box><BoxborderStyle="bold"><Text>bold</Text></Box></Box><BoxmarginTop={1}><BoxborderStyle="singleDouble"marginRight={2}><Text>singleDouble</Text></Box><BoxborderStyle="doubleSingle"marginRight={2}><Text>doubleSingle</Text></Box><BoxborderStyle="classic"><Text>classic</Text></Box></Box></Box>

Alternatively, pass a custom border style like so:

<BoxborderStyle={{topLeft:'↘',top:'↓',topRight:'↙',left:'→',bottomLeft:'↗',bottom:'↑',bottomRight:'↖',right:'←'}}><Text>Custom</Text></Box>

See example inexamples/borders.

borderColor

Type:string

Change border color.Shorthand for settingborderTopColor,borderRightColor,borderBottomColor andborderLeftColor.

<BoxborderStyle="round"borderColor="green"><Text>Green Rounded Box</Text></Box>

borderTopColor

Type:string

Change top border color.Accepts the same values ascolor in<Text> component.

<BoxborderStyle="round"borderTopColor="green"><Text>Hello world</Text></Box>
borderRightColor

Type:string

Change right border color.Accepts the same values ascolor in<Text> component.

<BoxborderStyle="round"borderRightColor="green"><Text>Hello world</Text></Box>
borderRightColor

Type:string

Change right border color.Accepts the same values ascolor in<Text> component.

<BoxborderStyle="round"borderRightColor="green"><Text>Hello world</Text></Box>
borderBottomColor

Type:string

Change bottom border color.Accepts the same values ascolor in<Text> component.

<BoxborderStyle="round"borderBottomColor="green"><Text>Hello world</Text></Box>
borderLeftColor

Type:string

Change left border color.Accepts the same values ascolor in<Text> component.

<BoxborderStyle="round"borderLeftColor="green"><Text>Hello world</Text></Box>
borderDimColor

Type:boolean
Default:false

Dim the border color.Shorthand for settingborderTopDimColor,borderBottomDimColor,borderLeftDimColor andborderRightDimColor.

<BoxborderStyle="round"borderDimColor><Text>Hello world</Text></Box>
borderTopDimColor

Type:boolean
Default:false

Dim the top border color.

<BoxborderStyle="round"borderTopDimColor><Text>Hello world</Text></Box>
borderBottomDimColor

Type:boolean
Default:false

Dim the bottom border color.

<BoxborderStyle="round"borderBottomDimColor><Text>Hello world</Text></Box>
borderLeftDimColor

Type:boolean
Default:false

Dim the left border color.

<BoxborderStyle="round"borderLeftDimColor><Text>Hello world</Text></Box>
borderRightDimColor

Type:boolean
Default:false

Dim the right border color.

<BoxborderStyle="round"borderRightDimColor><Text>Hello world</Text></Box>
borderTop

Type:boolean
Default:true

Determines whether top border is visible.

borderRight

Type:boolean
Default:true

Determines whether right border is visible.

borderBottom

Type:boolean
Default:true

Determines whether bottom border is visible.

borderLeft

Type:boolean
Default:true

Determines whether left border is visible.

<Newline>

Adds one or more newline (\n) characters.Must be used within<Text> components.

count

Type:number
Default:1

Number of newlines to insert.

import{render,Text,Newline}from'ink';constExample=()=>(<Text><Textcolor="green">Hello</Text><Newline/><Textcolor="red">World</Text></Text>);render(<Example/>);

Output:

HelloWorld

<Spacer>

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.

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.

import{render,Box,Text,Spacer}from'ink';constExample=()=>(<Box><Text>Left</Text><Spacer/><Text>Right</Text></Box>);render(<Example/>);

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.

import{render,Box,Text,Spacer}from'ink';constExample=()=>(<BoxflexDirection="column"height={10}><Text>Top</Text><Spacer/><Text>Bottom</Text></Box>);render(<Example/>);

<Static>

<Static> component permanently renders its output above everything else.It's useful for displaying activity like completed tasks or logs - things thatare 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 knowor control the amount of items that need to be rendered.

For example,Tap uses<Static> to displaya list of completed tests.Gatsby uses itto display a list of generated pages, while still displaying a live progress bar.

importReact,{useState,useEffect}from'react';import{render,Static,Box,Text}from'ink';constExample=()=>{const[tests,setTests]=useState([]);useEffect(()=>{letcompletedTests=0;lettimer;construn=()=>{// Fake 10 completed testsif(completedTests++<10){setTests(previousTests=>[...previousTests,{id:previousTests.length,title:`Test #${previousTests.length+1}`}]);timer=setTimeout(run,100);}};run();return()=>{clearTimeout(timer);};},[]);return(<>{/* This part will be rendered once to the terminal */}<Staticitems={tests}>{test=>(<Boxkey={test.id}><Textcolor="green">{test.title}</Text></Box>)}</Static>{/* This part keeps updating as state changes */}<BoxmarginTop={1}><TextdimColor>Completed tests:{tests.length}</Text></Box></>);};render(<Example/>);

Note:<Static> only renders new items initems prop and ignores itemsthat were previously rendered. This means that when you add new items toitemsarray, changes you make to previous items will not trigger a rerender.

Seeexamples/static for an example usage of<Static> component.

items

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> for supported properties.

<Staticitems={...}style={{padding:1}}>{...}</Static>

children(item)

Type:Function

Function that is called to render every item initems array.First argument is an item itself and second argument is index of that item initems array.

Note thatkey must be assigned to the root component.

<Staticitems={['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, 2return(<Boxkey={index}><Text>Item:{item}</Text></Box>);}}</Static>

<Transform>

Transform a string representation of React components before they are written to output.For example, you might want to apply agradient to text,add a clickable link orcreate some text effects.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.

Note:<Transform> must be applied only to<Text> children components and shouldn't change the dimensions of the output, otherwise layout will be incorrect.

import{render,Transform}from'ink';constExample=()=>(<Transformtransform={output=>output.toUpperCase()}><Text>Hello World</Text></Transform>);render(<Example/>);

Sincetransform function converts all characters to upper case, final output that's rendered to the terminal will be "HELLO WORLD", not "Hello World".

When the output wraps to multiple lines, it can be helpful to know which line is being processed.

For example, to implement a hanging indent component, you can indent all the lines except for the first.

import{render,Transform}from'ink';constHangingIndent=({content, indent=4, children, ...props})=>(<Transformtransform={(line,index)=>index===0 ?line :' '.repeat(indent)+line}{...props}>{children}</Transform>);consttext='WHEN I WROTE the following pages, or rather the bulk of them, '+'I lived alone, in the woods, a mile from any neighbor, in a '+'house which I had built myself, on the shore of Walden Pond, '+'in Concord, Massachusetts, and earned my living by the labor '+'of my hands only. I lived there two years and two months. At '+'present I am a sojourner in civilized life again.';// Other text properties are allowed as wellrender(<HangingIndentbolddimColorindent={4}>{text}</HangingIndent>);

transform(outputLine, index)

Type:Function

Function which transforms children output.It accepts children and must return transformed children too.

children

Type:string

Output of child components.

index

Type:number

The zero-indexed line number of the line currently being transformed.

Hooks

useInput(inputHandler, options?)

This hook is used for handling user input.It's a more convenient alternative to usinguseStdin and listening todata events.The callback you pass touseInput 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 asinput.You can find a full example of usinguseInput atexamples/use-input.

import{useInput}from'ink';constUserInput=()=>{useInput((input,key)=>{if(input==='q'){// Exit program}if(key.leftArrow){// Left arrow key pressed}});return};

inputHandler(input, key)

Type:Function

The handler function that you pass touseInput 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 betrue.For example, if user presses left arrow key,key.leftArrow equalstrue.

key.return

Type:boolean
Default:false

Return (Enter) key was pressed.

key.escape

Type:boolean
Default:false

Escape key was pressed.

key.ctrl

Type:boolean
Default:false

Ctrl key was pressed.

key.shift

Type:boolean
Default:false

Shift key was pressed.

key.tab

Type:boolean
Default:false

Tab key was pressed.

key.backspace

Type:boolean
Default:false

Backspace key was pressed.

key.delete

Type:boolean
Default:false

Delete key was pressed.

key.pageDown
key.pageUp

Type:boolean
Default:false

If Page Up or Page Down key was pressed, the corresponding property will betrue.For example, if user presses Page Down,key.pageDown equalstrue.

key.meta

Type:boolean
Default:false

Meta key was pressed.

options

Type:object

isActive

Type:boolean
Default:true

Enable or disable capturing of user input.Useful when there are multipleuseInput 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 will reject with that error.

import{useApp}from'ink';constExample=()=>{const{exit}=useApp();// Exit the app after 5 secondsuseEffect(()=>{setTimeout(()=>{exit();},5000);},[]);return};

useStdin()

useStdin is a React hook, which exposes stdin stream.

stdin

Type:stream.Readable
Default:process.stdin

Stdin stream passed torender() inoptions.stdin orprocess.stdin by default.Useful if your app needs to handle user input.

import{useStdin}from'ink';constExample=()=>{const{stdin}=useStdin();return};

isRawModeSupported

Type:boolean

A boolean flag determining if the currentstdin supportssetRawMode.A component usingsetRawMode might want to useisRawModeSupported to nicely fall back in environments where raw mode is not supported.

import{useStdin}from'ink';constExample=()=>{const{isRawModeSupported}=useStdin();returnisRawModeSupported ?(<MyInputComponent/>) :(<MyComponentThatDoesntUseInput/>);};

setRawMode(isRawModeEnabled)

Type:function

isRawModeEnabled

Type:boolean

SeesetRawMode.Ink exposes this function to be able to handleCtrl+C, that's why you should use Ink'ssetRawMode instead ofprocess.stdin.setRawMode.

Warning: This function will throw unless the currentstdin supportssetRawMode. UseisRawModeSupported to detectsetRawMode support.

import{useStdin}from'ink';constExample=()=>{const{setRawMode}=useStdin();useEffect(()=>{setRawMode(true);return()=>{setRawMode(false);};});return};

useStdout()

useStdout is a React hook, which exposes stdout stream, where Ink renders your app.

stdout

Type:stream.Writable
Default:process.stdout

import{useStdout}from'ink';constExample=()=>{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.

import{useStdout}from'ink';constExample=()=>{const{write}=useStdout();useEffect(()=>{// Write a single message to stdout, above Ink's outputwrite('Hello from Ink to stdout\n');},[]);return};

See additional usage example inexamples/use-stdout.

useStderr()

useStderr is a React hook, which exposes stderr stream.

stderr

Type:stream.Writable
Default:process.stderr

Stderr stream.

import{useStderr}from'ink';constExample=()=>{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.

import{useStderr}from'ink';constExample=()=>{const{write}=useStderr();useEffect(()=>{// Write a single message to stderr, above Ink's outputwrite('Hello from Ink to stderr\n');},[]);return};

useFocus(options?)

Component that usesuseFocus hook becomes "focusable" to Ink, so when user pressesTab, Ink will switch focus to this component.If there are multiple components that executeuseFocus hook, focus will be given to them in the order that these components are rendered in.This hook returns an object withisFocused 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.

id

Type:string
Required:false

Set a component's focus ID, which can be used to programmatically focus the component. This is useful for large interfaces with many focusable elements, to avoid having to cycle through all of them.

import{render,useFocus,Text}from'ink';constExample=()=>{const{isFocused}=useFocus();return<Text>{isFocused ?'I am focused' :'I am not focused'}</Text>;};render(<Example/>);

See example inexamples/use-focus andexamples/use-focus-with-id.

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.

import{useFocusManager}from'ink';constExample=()=>{const{enableFocus}=useFocusManager();useEffect(()=>{enableFocus();},[]);return};

disableFocus()

Disable focus management for all components.Currently active component (if there's one) will lose its focus.

import{useFocusManager}from'ink';constExample=()=>{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 active component.

Note: Ink calls this method when user pressesTab.

import{useFocusManager}from'ink';constExample=()=>{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 pressesShift+Tab.

import{useFocusManager}from'ink';constExample=()=>{const{focusPrevious}=useFocusManager();useEffect(()=>{focusPrevious();},[]);return};

focus(id)

id

Type:string

Switch focus to the component with the givenid.If there's no component with that ID, focus will be given to the next focusable component.

import{useFocusManager,useInput}from'ink';constExample=()=>{const{focus}=useFocusManager();useInput(input=>{if(input==='s'){// Focus the component with focus ID 'someId'focus('someId');}});return};

API

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 caseprocess.stdin is inraw 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 ofconsole.* methods are called (likeconsole.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 bypatch-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

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

Instance

This is the object thatrender() returns.

rerender(tree)

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

tree

Type:ReactElement

// Update props of the root nodeconst{rerender}=render(<Countercount={1}/>);rerender(<Countercount={2}/>);// Replace root nodeconst{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);awaitwaitUntilExit();// resolves after `unmount()` is called
clear()

Clear output.

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

measureElement(ref)

Measure the dimensions of a particular<Box> element.It returns an object withwidth andheight 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 andheight equal to zero. It's recommended to callmeasureElement() in auseEffect hook, which fires after the component has rendered.

ref

Type:MutableRef

A reference to a<Box> element captured with aref property.SeeRefs for more information on how to capture references.

import{render,measureElement,Box,Text}from'ink';constExample=()=>{constref=useRef();useEffect(()=>{const{width, height}=measureElement(ref.current);// width = 100, height = 1},[]);return(<Boxwidth={100}><Boxref={ref}><Text>This box will stretch to 100 width</Text></Box></Box>);};render(<Example/>);

Testing

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

importReactfrom'react';import{Text}from'ink';import{render}from'ink-testing-library';constTest=()=><Text>Hello World</Text>;const{lastFrame}=render(<Test/>);lastFrame()==='Hello World';//=> true

Check outink-testing-library for more examples and full documentation.

Using React Devtools

Ink supportsReact Devtools out-of-the-box. To enable integration with React Devtools in your Ink-based CLI, first ensure you have installed the optionalreact-devtools-core dependency, and then run your app withDEV=true environment variable:

DEV=true my-cli

Then, start React Devtools itself:

npx react-devtools

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.

Note: You must manually quit your CLI viaCtrl+C after you're done testing.

Useful Components

Useful Hooks

Examples

Theexamples directory contains a set of real examples. You can run them with:

npm run example examples/[example name]# e.g. npm run example examples/borders

Maintainers


[8]ページ先頭

©2009-2025 Movatter.jp