惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
Cyberwarzone
Cyberwarzone
The GitHub Blog
The GitHub Blog
云风的 BLOG
云风的 BLOG
P
Proofpoint News Feed
小众软件
小众软件
Recent Announcements
Recent Announcements
博客园 - 三生石上(FineUI控件)
Security Archives - TechRepublic
Security Archives - TechRepublic
W
WeLiveSecurity
Cloudbric
Cloudbric
博客园 - 司徒正美
美团技术团队
N
News and Events Feed by Topic
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
PCI Perspectives
PCI Perspectives
宝玉的分享
宝玉的分享
H
Help Net Security
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Google DeepMind News
Google DeepMind News
Help Net Security
Help Net Security
Last Week in AI
Last Week in AI
S
Schneier on Security
N
News | PayPal Newsroom
B
Blog RSS Feed
L
LINUX DO - 最新话题
T
Troy Hunt's Blog
S
Secure Thoughts
雷峰网
雷峰网
aimingoo的专栏
aimingoo的专栏
L
Lohrmann on Cybersecurity
G
Google Developers Blog
Microsoft Azure Blog
Microsoft Azure Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
T
Tenable Blog
S
Securelist
L
LangChain Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
I
InfoQ
H
Heimdal Security Blog
Cisco Talos Blog
Cisco Talos Blog
F
Full Disclosure
Y
Y Combinator Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
K
Kaspersky official blog
T
Tailwind CSS Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
阮一峰的网络日志
阮一峰的网络日志
C
Cisco Blogs

Hacker News: Show HN

PurrrrrFocus: Pomodoro Timer App - App Store Workflow Engine — Multi-Step Orchestration for Bun RapidPhoto: Pro Photo Editor App - App Store GitHub - DheerG/swarms: Achieve extraordinary results with claude code across a variety of tasks SPICE simulation → oscilloscope → verification with Claude Code — Lucas Gerads Show HN: VCoding – A 5 MB native Windows IDE with no dynamic dependencies Show HN: LLMs don't hallucinate because they're bad at math, it's the format GitHub - Agent-FM/agentfm-core: AgentFM is a peer-to-peer network that turns everyday computers into a decentralized AI supercomputer. AgentFM lets you run massive AI workloads directly across a global mesh of idle CPUs and GPUs. Show HN: Tracking Top US Science Olympiad Alumni over Last 25 Years GitHub - Potarix/agent-hub: One place to talk to all your agents Show HN: Runtime security for AI agents(injection,tool abuse, data exfiltration) GitHub - dubeyKartikay/lazyspotify: Terminal Spotify client for macOS and Linux GitHub - the-banana-tool/king-louie: Easy to use GUI Personal AI Assistant. Win/Linux/Mac. Show HN I made my vacation rental bookable by AI agents–no Airbnb, 0% commission GitHub - basteez/jsf-autoreload: maven plugin to enable hot reload on jsf projects uvm32/hosts/host-gdbstub at main · ringtailsoftware/uvm32 GitHub - labsai/EDDI: Config-driven engine that turns JSON into production-grade AI agents. Multi-agent orchestration, 12+ LLM providers, MCP/A2A protocols, RAG, persistent memory, and enterprise compliance (EU AI Act, GDPR, HIPAA). Built on Quarkus. GitHub - glitchnsec/fortyone-oss: AI Executive Assistant Platform Quickstart | Alien GitHub - muxshed/shed: One stream in, or many. Every destination, simultaneously. No cloud middleman, no per-channel fees, no limits. GitHub - ocrbase-hq/ocrbase: 📄 PDF/IMG ->.MD/JSON Document OCR API for PaddleOCR and GLMOCR. Self-hostable. GitHub - impactjo/home-memory: MCP server that lets your AI assistant remember everything about your home. GitHub - Sets88/dbcls: DbCls is a powerful terminal database client that supports various databases GitHub - neptun2000/heor-agent-mcp GitHub - SeanFDZ/macmind: Single-layer transformer in HyperTalk for the classic Macintosh RollQuation: Math Puzzles - Apps on Google Play GitHub - dropbox/witchcraft Show HN: Agent-cache – Multi-tier LLM/tool/session caching for Valkey and Redis GitHub - opentalon/opentalon: OpenTalon is an open-source platform built from the ground up in Go as a robust alternative to OpenClaw LinkedIn™ 职位抓取工具 - Chrome 应用商店 GitHub - EdoardoBambini/Agent-Armor-Iaga: AI agents are getting tool access — shell, file system, databases, APIs, secrets. But **nobody is governing what they actually do with it**. Frameworks like LangChain, CrewAI, AutoGen, and Claude Code give agents the power to execute. Agent Armor gives you the power to control, audit, and approve every single action before it happens. HN Vibes — Week 15, Apr 7–13 2026 GitHub - chojs23/ec: Easy terminal-native 3-way git mergetool vim-like workflow GitHub - SethPyle376/hiraeth: Local AWS emulator focused on fast integration testing, with SQS support, SQLite-backed state, and a debug-friendly web UI. GitHub - JakOb-dotcom/cloud-sandbox-security-analysis: Technical analysis and Proof of Concept (PoC) regarding environment variable exfiltration in containerized cloud sandboxes via side-channel data leaks. Springboards - Flint Alpha Show HN: A simpler coding agent harness GitHub - audiodude/sudomake-friends GitHub - 256thFission/mini-mythos: OSS clone of Anthropic’s Mythos harness to locate C/C++ memory vulnerabilities Show HN: OpenParallax: OS-level privilege separation for AI agent execution Hacker News Sorted - Chrome 应用商店 Show HN: How to Install Docker on Ubuntu 24.04 LTS: Complete 2026 Guide GitHub - himanshudongre/smriti GitHub - sverrirsig/claude-control: macOS desktop dashboard for monitoring and managing multiple Claude Code sessions GitHub - ory/dockertest: Write better integration tests! Dockertest helps you boot up ephermal docker images for your Go tests with minimal work. Chiral - Chrome 应用商店 Show HN: Two Claudes collaborating through shared memory on a $100 mini-PC GitHub - pmichaillat/latex-cv: Minimalist LaTeX template for academic CVs GitHub - oguzbilgic/posse: A web UI for Anthropic Managed Agents. GitHub - sshiraz/depsly: Dependency risk analysis tool for npm packages ABI Add safari/agent-harness — Safari browser automation via safari-mcp by achiya-automation · Pull Request #212 · HKUDS/CLI-Anything GitHub - Halfblood-Prince/trustcheck: Verify PyPI package attestations and improve Python supply-chain security GitHub - oguzbilgic/kern-ai: Agents that do the work and show it. GitHub - bruits/satteri: High-performance Markdown and MDX processing for the JavaScript ecosystem GitHub - tylergibbs1/feedstock: High-performance web crawler and scraper for TypeScript, powered by Bun and Playwright GitHub - Grimm67123/grimmbot: The self-improving sandboxed and open-source AI agent. With persistent memory and scheduling. GitHub - whitevanillaskies/whitebloom: Local whiteboard that blooms. GitHub - hwdsl2/docker-whisper: Docker image for a self-hosted Whisper speech-to-text server with speaker diarization and OpenAI-compatible transcription and translation APIs. Powered by faster-whisper. Supports all Whisper models, NVIDIA GPU (CUDA) acceleration, JSON/SRT/VTT output, SSE streaming, offline mode, and multi-arch (amd64, arm64). GitHub - yisding/reviewwiggum GitHub - MarwanAlsoltany/serrors: Structured errors for Go: sentinel hierarchies, typed data, custom formatting, and slog integration. GitHub - soatok/age-php GitHub - Luthiraa/markitme GitHub - stagas/rtdiff: realtime git diff gui and AI-assisted commits GitHub - tombedor/excalicharts GitHub - wh1le/excalidraw-edit: Open and edit .excalidraw files from the terminal. Offline, auto-saves to disk. MalExt Sentry - Malicious Extension Scanner - Chrome 应用商店 GitHub - syi0808/asciianimesvg: Generate animated ASCII art SVGs from text. CLI, Rust library, WASM, and web editor. GitHub - zaina-ml/ml_forge: A visual-based graph node editor for training computer vision models. GitHub - anakin87/llm-rl-environments-lil-course: 🌱 A little course on Reinforcement Learning Environments for evaluating and training Language Models GitHub - takaakit/superpowers-uml: Superpowers-UML modifies Superpowers to ensure a software development workflow in which AI agents design through UML modeling. AdriByte Studio - Sviluppo Web e Soluzioni Digitali GitHub - chouligi/angel-copilot: Your personalized Angel Investment Advisor Show HN: MoodSense AI (ML and FastAPI and Gradio, Deployed on Hugging Face) Moodsense Ai - a Hugging Face Space by aman179102 GitHub - agenteractai/lodmem: Level Of Detail Context Management for Agents GitHub - ostefani/subnetlens: A fast, concurrent network scanner with a TUI and plain-text CLI, built in Go. It discovers live hosts on your network, scans their open ports, resolves hostnames, and fingerprints operating systems—delivered. Cyber Pulse: Agentic Intel - Apps on Google Play Whisper API: Self-Hostable Speech to Text Transcription The Agent-Web Protocol Stack: A Research Thesis GitHub - msmarkgu/RelayFreeLLM: A restful API designed to route user prompts to various AI model providers. Show HN: Provepy – A Python decorator that proves your code using Lean and LLMs Show HN: Pardonned.com – A searchable database of US Pardons GitHub - patrickdappollonio/dux: Dux is a terminal UI that lets you run multiple AI coding agents side by side, each in its own git worktree, with full companion terminals, macros, commit generation, and a command palette that knows more tricks than you do. kMC Crystal Simulator Show HN: HyperFlow – A self-improving agent framework built on LangGraph GitHub - stef41/vibescore: 🎵 Grade your vibe-coded project. One command, instant letter grade across security, quality, dependencies, and testing. GitHub - stef41/lmscan: 🔍 Detect AI-generated text and fingerprint which LLM wrote it. Open-source GPTZero alternative. Zero dependencies, works offline. imgur.com GitHub - visionscaper/collabmem: Enabling long-term collaboration with Agentic AI - building up episodic and world model memory over time with in-context awareness 在 Steam 上购买 FriedrichAI: Offline AI 立省 10% GitHub - atripati/ark: AI Runtime Kernel — a context operating system for AI agents. Eliminates tool bloat, loads only what’s needed, and gives LLMs their reasoning space back. GitHub - nowork-studio/toprank: Open-source Claude Code skills for SEO, SEM, Google Ads GitHub - tacomanator/sash: Lightweight macOS menu bar app for reliably cycling through windows of the current application. Appents | Social Media Management for Product-First Teams GitHub - pnhoang/youtube-spam-blocker: Automatically detects and hides spam messages in YouTube Live chat. Set rate limits, keyword filters, and block repeat offenders. GitHub - decisionnode/DecisionNode: CLI + Local MCP - A shared structured memory store across Claude Code, Cursor, Windsurf, Antigravity, and every MCP client. Semantically queryable. GitHub - AvaCodeSolutions/django-email-learning: An open source Django app for creating email-based learning platforms with IMAP integration and React frontend components. The $100K Gap in Kubernetes Security Tooling Function Calling Harness: From 6.75% to 100%
GitHub - omranjamal/react-ink-textarea: A full-featured CLI textarea component for React Ink — Implement beautiful multi-line text input on the CLI
omranjamal · 2026-05-05 · via Hacker News: Show HN

A multiline textarea component for Ink

GitHub Issues or Pull Requests NPM Downloads NPM Version NPM License GitHub forks

Build rich CLI forms with a full-featured textarea that supports multi-line editing, cursor navigation, undo, and customizable line prefixes.

react-ink-textarea demo

Contents

  • Features
  • Install
  • Usage
    • 1. Basic
    • 2. Controlled mode with cursor labels
    • 3. Line numbers and active-line highlight
    • 4. Inline syntax highlighting
    • 5. Multi-field form with focus chaining
    • 6. Slash-command picker (arrow + tab handoff)
    • 7. Code-editor preset
  • Props
  • Imperative API (ref)
  • Keybindings
    • Keybinding Toggles
  • Caveats & limitations
  • Development
  • License

Features

  • 🎨 Polished feel — blinking cursor that pauses while typing, active-line highlight, multi-line placeholder, optional whitespace glyphs.
  • 🪪 Custom gutter via linePrefix render-prop, plus a drop-in <LineNumberPrefix />.
  • 🌈 Regex (or function) labels with per-label styles; cursor reports the label under it.
  • ⌨️ Readline keybindings, configurable per chord. Tab is a callback. Grouped undo and bracketed paste.
  • 🌐 Unicode-correct: grapheme cursor, visual-width wrapping, real tab expansion, CRLF normalized.
  • 📐 Built-in viewport virtualization; auto-scroll; resize-aware.
  • 🧭 Boundary callbacks (onFirstLineUp, onLastLineDown, onFirstCharacterLeft, onLastCharacterRight) for parent-owned focus chaining.
  • ⚛️ Controlled, uncontrolled, or mixed. Imperative ref.insert(text) for autocomplete pickers.
  • 🧷 Strict TypeScript, tree-shakable.
  • 🧪 Works with ink-testing-library; 250+ tests in-repo.

Install

Install react-ink-textarea via your JS package manager of choice.

npm install react-ink-textarea

# or
pnpm add react-ink-textarea

Usage

1. Basic

Uncontrolled mode. Submit on Enter, freeze on submit.

import { render } from "ink";
import { useState } from "react";
import { TextArea } from "react-ink-textarea";

const App = () => {
  const [submitted, setSubmitted] = useState("");
  const [focus, setFocus] = useState(true);

  return (
    <TextArea
      focus={focus}
      placeholder="Type your message here..."
      onSubmit={(value) => {
        setSubmitted(value);
        setFocus(false);
      }}
    />
  );
};

render(<App />);

2. Controlled mode with cursor labels

Own value and cursorPosition externally. onCursorChange reports the label and chunk index under the cursor — drive a status line, hover-card, or autocomplete from it.

import { Box, Text } from "ink";
import { useState } from "react";
import { TextArea, type TLabels } from "react-ink-textarea";

const labels: TLabels = [{ pattern: /#\w+/g, label: "tag" }];
const styles = { tag: { color: "magenta" } };

const Editor = () => {
  const [value, setValue] = useState("hello #world");
  const [cursor, setCursor] = useState<[number, number]>([0, 0]);
  const [info, setInfo] = useState("text");

  return (
    <Box flexDirection="column">
      <TextArea
        focus
        value={value}
        cursorPosition={cursor}
        labels={labels}
        styles={styles}
        onChange={setValue}
        // (pos, labelType, chunkIndex) — labelType is "text" outside any match
        onCursorChange={(pos, type, idx) => {
          setCursor(pos);
          setInfo(type === "text" ? "text" : `${type}#${idx}`);
        }}
        onSubmit={() => {}}
      />
      <Text dimColor>under cursor: {info}</Text>
    </Box>
  );
};

3. Line numbers and active-line highlight

Drop-in: pass the bundled LineNumberPrefix straight to linePrefix.

import { TextArea, LineNumberPrefix } from "react-ink-textarea";

<TextArea
  focus
  highlightActiveLine
  activeLineColor="#222"
  initialLineCount={6}
  onSubmit={() => {}}
  linePrefix={LineNumberPrefix}
/>;

Custom: linePrefix is a render prop. Handle isContinuationLine and isVirtualLine to draw clean gutters when wrapping or padding. Compose with the bundled LineNumber for the digits.

import { Text } from "ink";
import { TextArea, LineNumber } from "react-ink-textarea";

<TextArea
  focus
  highlightActiveLine
  initialLineCount={6}
  onSubmit={() => {}}
  linePrefix={({
    lineNumber,
    totalLines,
    isActiveLine,
    isContinuationLine,
    isVirtualLine,
  }) =>
    isContinuationLine ? (
      <Text color="gray"></Text>
    ) : (
      <Text>
        <LineNumber
          lineNumber={lineNumber}
          totalLines={totalLines}
          isActive={isActiveLine}
          padChar=" "
          activeColor="cyan"
        />
        <Text color={isVirtualLine ? "gray" : "white"}></Text>
      </Text>
    )
  }
/>;

4. Inline syntax highlighting

labels mixes regex rules with function-form rules for allowlists. First rule wins on overlap. styles.text and styles.invisibleCharacter are reserved keys; everything else maps to a label name.

import { useMemo } from "react";
import { TextArea, type TLabels } from "react-ink-textarea";

const KNOWN_USERS = new Set(["alice", "bob", "carol"]);

const Editor = () => {
  const labels = useMemo<TLabels>(
    () => [
      { pattern: /https?:\/\/\S+/g, label: "url" },
      { pattern: /#\w+/g, label: "tag" },
      // function form: leave unknown @handles unstyled by returning undefined
      {
        pattern: /@(\w+)/g,
        label: (m) => (KNOWN_USERS.has(m[1]) ? "mention" : undefined),
      },
    ],
    [],
  );

  return (
    <TextArea
      focus
      onSubmit={() => {}}
      showInvisibles={{ space: false, tab: true, newline: false }}
      labels={labels}
      styles={{
        text: { color: "white" },
        invisibleCharacter: { color: "gray", dim: true },
        url: { color: "blue", underline: true },
        tag: { color: "magenta" },
        mention: { color: "green", bold: true },
      }}
    />
  );
};

5. Multi-field form with focus chaining

Boundary callbacks let you escape the textarea cleanly: ↑ on the first row jumps to the field above, ↓ past the last line jumps below, and ←/→ at the absolute ends do the same horizontally.

import { Box, useFocusManager, useFocus } from "ink";
import { useState } from "react";
import { TextArea } from "react-ink-textarea";
import TextInput from "ink-text-input";

const Form = () => {
  const { focusNext, focusPrevious } = useFocusManager();
  const subject = useFocus({ id: "subject" });
  const body = useFocus({ id: "body" });
  const tags = useFocus({ id: "tags" });
  const [s, setS] = useState("");
  const [b, setB] = useState("");
  const [t, setT] = useState("");

  return (
    <Box flexDirection="column" gap={1}>
      <TextInput value={s} onChange={setS} focus={subject.isFocused} />
      <TextArea
        focus={body.isFocused}
        value={b}
        onChange={setB}
        onSubmit={() => {}}
        onFirstLineUp={focusPrevious}
        onLastLineDown={focusNext}
        onFirstCharacterLeft={focusPrevious}
        onLastCharacterRight={focusNext}
      />
      <TextInput value={t} onChange={setT} focus={tags.isFocused} />
    </Box>
  );
};

6. Slash-command picker (arrow + tab handoff)

When a menu opens, suspend cursor navigation with disableArrowNavigation and disable Enter so the picker — not the textarea — handles them. Re-enable on close.

import { Box, Text } from "ink";
import { useState } from "react";
import { TextArea } from "react-ink-textarea";

const COMMANDS = ["/help", "/quit", "/train"];

const Composer = () => {
  const [value, setValue] = useState("");
  const [sel, setSel] = useState(0);
  const open = value.startsWith("/");

  return (
    <Box flexDirection="column">
      <TextArea
        focus
        value={value}
        onChange={setValue}
        onSubmit={(v) => {
          if (!open) console.log(v);
        }}
        // While the picker is open, give it the arrows + Enter; typing still flows.
        disableArrowNavigation={open}
        keybindings={open ? { Enter: false } : undefined}
        onTab={(shift) =>
          setSel((i) => (i + (shift ? -1 : 1) + COMMANDS.length) % COMMANDS.length)
        }
      />
      {open && (
        <Box flexDirection="column">
          {COMMANDS.map((c, i) => (
            <Text key={c} color={i === sel ? "cyan" : undefined}>
              {i === sel ? "▸ " : "  "}
              {c}
            </Text>
          ))}
        </Box>
      )}
    </Box>
  );
};

7. Code-editor preset

Override the viewport explicitly, expand tabs, lock down ergonomic chords, and surface the measured content width to a status bar.

import { Box, Text } from "ink";
import { useState } from "react";
import { TextArea } from "react-ink-textarea";

const CodeEditor = () => {
  const [width, setWidth] = useState(0);

  return (
    <Box flexDirection="column">
      <TextArea
        focus
        onSubmit={() => {}}
        viewportLines={20}
        tabWidth={2}
        autoNewLineLimit={1}
        showInvisibles
        keybindings={{
          // Single-undo-stack ergonomics: defer undo to the host (e.g. file-level)
          "Ctrl+Z": false,
          // Keep Shift+Enter free for the parent's "submit-with-newline" gesture
          "Shift+Enter": false,
        }}
        onDimensions={setWidth}
      />
      <Text dimColor>width: {width} cols</Text>
    </Box>
  );
};

Props

Prop Type Description
focus boolean Whether the textarea is focused and receiving keyboard input.
onSubmit (value: string) => void Called when the user presses Enter. Receives the full text.
placeholder string Placeholder text shown when the textarea is empty.
linePrefix ReactNode | (props: TLinePrefixProps) => ReactNode Optional prefix rendered before each line. The function form receives { lineNumber, totalLines, isActiveLine, isVirtualLine, isContinuationLine, continuationIndex }. Use for line numbers, gutters, borders, etc.
highlightActiveLine boolean When true, the active line is highlighted with a subtle background color. Defaults to false.
activeLineColor string Background color for the active line highlight. Defaults to no color.
cursorInterval number Cursor blink interval in milliseconds. Defaults to 500.
typingPause number Milliseconds to wait after typing before resuming cursor blink. Defaults to 450.
maxUndo number Maximum number of undo steps to retain. Defaults to 128.
undoGroupDelay number Milliseconds to group consecutive edits into a single undo step. Defaults to 750.
autoNewLineLimit number Maximum number of empty lines allowed after the last line with content. Only applies to Down arrow navigation. Defaults to 3.
disableArrowNavigation boolean When true, disables cursor movement via arrow keys (and word/line jumps). Useful for implementing suggestion pickers. Defaults to false.
keybindings Partial<Record<TKeybinding, boolean>> Per-chord enable/disable map. Merged over defaults (all true). Set a chord to false to swallow it. disableArrowNavigation: true additionally forces all nav chords off. See Keybinding Toggles below.
initialLineCount number Number of lines to display initially. The textarea will maintain at least this many lines. Defaults to 2.
viewportLines number Maximum number of visual rows rendered at once. The textarea virtualizes rendering and auto-scrolls to keep the cursor visible. Defaults to floor(stdout.rows * 0.5) so blink re-renders don't scroll-jank tall buffers when the frame exceeds the terminal viewport. Pass an explicit number to override; Infinity renders every row.
tabWidth number Visual width of \t characters in cells. Tabs render as tabWidth spaces (or + spaces with showInvisibles.tab). The stored value keeps \t. Defaults to 4.
value string Controlled mode: The current value of the textarea. When provided, component operates in controlled mode.
cursorPosition [line: number, column: number] Controlled mode: The current cursor position as a [line, column] tuple. Use with value for full control.
onChange (value: string) => void Controlled mode: Called when the value changes.
onCursorChange (position: [line, column], type: string, chunkIndex: number) => void Controlled mode: Called when the cursor moves. type is the label at the cursor ("text" if no label matches); chunkIndex is the zero-based index of the labeled segment the cursor is in.
onFirstLineUp () => void Called when Up arrow is pressed on the first visual row. Useful for moving focus out of the textarea.
onLastLineDown () => void Called when Down arrow is pressed on the last line and trailing-empty-line limit is reached. Useful for moving focus out.
onFirstCharacterLeft () => void Called when Left arrow is pressed at the very start of the value (cursor === 0). Useful for moving focus to a previous field.
onLastCharacterRight () => void Called when Right arrow is pressed at the very end of the value (cursor === value.length). Useful for moving focus to a next field.
onTab (shift: boolean) => void Called when Tab is pressed. shift is true for Shift+Tab. Without this prop, Tab is silently swallowed (no value mutation).
onDimensions (width: number) => void Called with the measured content width whenever it changes.
showInvisibles boolean | { space?: boolean; tab?: boolean; newline?: boolean } Render whitespace glyphs (· for space, for tab, for newline). Defaults to false.
styles { text?, invisibleCharacter?, [labelName]? } of TStyleProps Style overrides for the default text run, invisible glyphs, and any user-defined labels. color and bgColor accept any value Ink's <Text> accepts — see the Ink color reference.
labels readonly { pattern: RegExp; label: string | ((match: RegExpMatchArray) => string | undefined) }[] Array of label rules. Each rule's pattern is matched against the value; matches receive the rule's label. Use a function form to allowlist matches — return undefined to leave a match unlabeled. First rule wins on overlap.

Imperative API (ref)

Pass a ref of type TextAreaHandle to insert text programmatically — typically from an autocomplete picker. Insertion happens at the current cursor and advances it. Works in both controlled and uncontrolled modes.

import { useRef } from "react";
import { TextArea, type TextAreaHandle } from "react-ink-textarea";

const Composer = () => {
  const ref = useRef<TextAreaHandle>(null);
  return (
    <TextArea
      ref={ref}
      focus
      onSubmit={() => {}}
      onTab={() => ref.current?.insert("/help ")}
    />
  );
};
Method Description
insert(text: string) Insert text at the current cursor and advance it past the inserted text. Empty string is a no-op.

Keybindings

Key Action
Ctrl+J Insert newline
Ctrl+Enter Insert newline
Shift+Enter Insert newline
Alt+Enter Insert newline (Option+Enter)
Enter Submit
/ Move cursor between lines
/ Move cursor left / right
Opt+← Jump to previous word
Opt+→ Jump to next word
Ctrl+A Start of current line
Ctrl+E End of current line
Ctrl+W Delete word before cursor
Ctrl+U Delete to start of line. At column 0, joins with previous line (matches Cmd+Backspace mapping in iTerm2/ghostty).
Ctrl+K Delete to end of line
Backspace Delete character before cursor
Delete Delete character before cursor (same as Backspace)
Opt+Backspace Delete word before cursor
Ctrl+Z Undo (up to 128 steps)

On macOS, Alt chords are pressed via the Option () key.

Keybinding Toggles

Pass a keybindings map to disable individual chords. Keys are the chord strings themselves; values are true (enabled) or false (disabled). Anything you don't list defaults to enabled.

<TextArea
  focus
  onSubmit={onSubmit}
  keybindings={{
    "Ctrl+Z": false,      // disable undo
    "Shift+Enter": false, // disable Shift+Enter newline (other newline chords still work)
    "Alt+B": false,       // disable previous-word jump
  }}
/>

The full chord catalog (every key is a TKeybinding):

Chord Action
Enter Submit
Ctrl+J Insert newline
Ctrl+Enter Insert newline
Shift+Enter Insert newline
Alt+Enter Insert newline
Up Cursor up
Down Cursor down
Left Cursor left
Right Cursor right
Alt+B Previous word
Alt+F Next word
Ctrl+A Start of line
Ctrl+E End of line
Ctrl+W Delete word before cursor
Ctrl+U Delete to start of line
Ctrl+K Delete to end of line
Backspace Delete grapheme before cursor
Delete Delete grapheme before cursor
Alt+Backspace Delete word before cursor
Ctrl+Z Undo

disableArrowNavigation: true additionally forces all nav chords (Up, Down, Left, Right, Alt+B, Alt+F, Ctrl+A, Ctrl+E) off regardless of the map.

Caveats & limitations

Things to know before shipping. Most are intrinsic to running a rich editor inside a terminal.

Environment
  • Terminal-only. Built on Ink — won't render in a browser. Requires Node 18+ for Intl.Segmenter. Peer deps: ink ^7, react ^18 || ^19.
  • Monospace assumption. Layout assumes every cell is one column wide and CJK / wide chars take two. Variable-width fonts in some emulators (rare) will break alignment.
  • Visual width via string-width. Emoji + ZWJ widths follow Unicode tables; some terminals (notably older macOS Terminal, tmux without set -g escape-time 0) render the same glyph at a different cell count and produce off-by-one cursor placement.
Keybinding edge cases
  • Modifier+Enter detection is terminal-dependent. Ctrl+Enter, Shift+Enter, Alt+Enter rely on modifyOtherKeys / CSI-u sequences. macOS Terminal.app and Windows console don't emit them by default — use iTerm2, WezTerm, Kitty, or Alacritty, or fall back to Ctrl+J for newline.
  • Alt on macOS. Option key inserts special chars (Opt+B) unless the terminal is set to "Use Option as Meta" (iTerm2: Profiles → Keys; Terminal.app: Profiles → Keyboard → Use Option as Meta key).
  • Tab is silently swallowed without onTab. No newline, no insert, no error. Provide the handler if you want any Tab behavior.
  • disableArrowNavigation is not read-only. Typing still mutates the buffer. Use focus={false} for true read-only.
  • Multiple focused TextAreas race. Ink's useInput delivers keys to every active hook; two textareas with focus={true} will both mutate. Gate via focus per instance.
Paste & clipboard
  • Bracketed paste required for one-step paste. Terminals that don't emit \x1b[200~ (Windows cmd, very old emulators) deliver pastes as individual keystrokes — slow, and each char becomes its own undo step (effectively breaking Ctrl+Z for the paste).
  • No programmatic clipboard. No copy API; no setter for paste content. Anything the terminal doesn't deliver, the textarea can't see.
  • No mouse. Click-to-position, drag-select, scroll wheel — none of it. Cursor moves only via keys.
Selection & search
  • No selection. Point cursor only. No range, no shift+arrow extension, no copy of a range.
  • No find/replace. Build it on top via controlled mode if you need it.
Undo
  • Time-grouped, not semantic. Edits within undoGroupDelay (default 2.5 s) collapse into one step. On a slow machine the boundary may land mid-word.
  • Bounded by maxUndo (default 128). Older history is dropped silently.
  • No redo. Ctrl+Y / Ctrl+Shift+Z are not bound. Add yourself if needed.
Labels & styles
  • Regex runs on every value change. O(value × rules). Heavy patterns on 100k+ char buffers will lag — debounce externally or scope rules.
  • Flat ranges, no nesting. A label can't contain another label. First rule wins on overlap; later rules silently lose.
  • Function-form undefined ≠ "fall through". Returning undefined leaves the match unlabeled (renders with text style). It does not let the next rule try.
  • color / bgColor strings are passed straight to Ink's <Text>. Invalid values fail silently — the terminal renders default. See the Ink color reference.
Performance
  • Cursor blink causes re-renders every cursorInterval ms (default 500). Tall frames + slow terminals can flicker. Bump cursorInterval or set it high to effectively disable.
  • viewportLines defaults to floor(stdout.rows * 0.5). Without virtualization, frames taller than the terminal trigger scroll-jank on every blink. The default trades render area for stability — override explicitly if you have height to spare.
  • Visual-row recompute is O(value) per keystroke. Acceptable for chat/comment buffers; pathological for full-file editing of large source files.
  • Resize listener is global. Every TextArea instance subscribes to stdout.resize. Dozens of simultaneous instances will fan out resize events.
Data model
  • CRLF/CR normalized to LF on paste and controlled values. onChange always reports LF. If your storage layer needs CRLF, convert on save.
  • value.length ≠ visual length. Tabs count as 1 char regardless of tabWidth; emoji count as their UTF-16 code-unit length, not 1 grapheme. Use Intl.Segmenter if you need grapheme counts externally.
  • Out-of-bounds cursorPosition is clamped silently. No throw, no warning — onCursorChange reports the clamped value.
  • Boundary callbacks fire on exact bounds only. onFirstLineUp only fires when the cursor is on row 0 and ↑ is pressed; not "the cursor moved past the top." Same for the other three.
  • onSubmit is sync. No promise return contract — coordinate async validation in your parent component.
Virtualization gotchas
  • Rows outside viewportLines are not rendered. Any consumer-side measurement on hidden rows (useBoxMetrics, refs in linePrefix) won't fire until the row scrolls in.
  • Wrapping happens at the measured content width. Constrain via a parent <Box width={...}> to wrap at a fixed column; otherwise wraps at stdout.columns.

Development

# Install dependencies
pnpm install

# Build
pnpm run build

# Watch mode
pnpm run dev

# Run tests
pnpm test

# Format code
pnpm run format

License

MIT