TUI コンポーネント
pi は TUI コンポーネントを作成できます。あなたのユースケースに合わせて構築するよう依頼してください。
Extensions およびカスタム ツールは、対話型ユーザー インターフェイス用のカスタム TUI コンポーネントをレンダリングできます。このページでは、コンポーネント システムと利用可能なビルディング ブロックについて説明します。
コンポーネントインターフェース
すべてのコンポーネントは以下を実装します。
interface Component {
render(width: number): string[];
handleInput?(data: string): void;
wantsKeyRelease?: boolean;
invalidate(): void;
}| 方法 | 説明 |
|---|---|
render(width) |
文字列の配列を返します (1 行に 1 つ)。各行は width を超えてはなりません。 |
handleInput?(data) |
コンポーネントにフォーカスがあるときにキーボード入力を受け取ります。 |
wantsKeyRelease? |
true の場合、コンポーネントはキーリリースイベント (Kitty プロトコル) を受信します。デフォルト: false。 |
invalidate() |
キャッシュされたレンダリング状態をクリアします。テーマの変更時に呼び出されます。 |
TUI は、レンダリングされた各行の最後に完全な SGR リセットと OSC 8 リセットを追加します。スタイルは複数の行を超えて継承されません。スタイルを設定して複数行のテキストを出力する場合は、行ごとにスタイルを再適用するか、wrapTextWithAnsi() を使用して折り返された各行のスタイルが保持されるようにします。
フォーカス可能なインターフェイス (IME サポート)
テキスト カーソルを表示し、IME (インプット メソッド エディター) のサポートを必要とするコンポーネントは、Focusable インターフェイスを実装する必要があります。
import { CURSOR_MARKER, type Component, type Focusable } from "@earendil-works/pi-tui";
class MyInput implements Component, Focusable {
focused: boolean = false; // Set by TUI when focus changes
render(width: number): string[] {
const marker = this.focused ? CURSOR_MARKER : "";
// Emit marker right before the fake cursor
return [`> ${beforeCursor}${marker}\x1b[7m${atCursor}\x1b[27m${afterCursor}`];
}
}Focusable コンポーネントにフォーカスがある場合、TUI:
- コンポーネントに
focused = trueを設定します CURSOR_MARKER(ゼロ幅 APC エスケープ シーケンス) のレンダリングされた出力をスキャンします。- ハードウェア端末カーソルをその位置に配置します
showHardwareCursorが有効な場合にのみハードウェア カーソルを表示します
カーソルはデフォルトでは非表示のままです。これにより、隠しカーソルで IME 候補ウィンドウを追跡する端末のハードウェア カーソルを配置しながら、偽のカーソルのレンダリングが維持されます。一部の端末では、IME の位置決めに目に見えるハードウェア カーソルが必要です。 showHardwareCursor、setShowHardwareCursor(true)、または PI_HARDWARE_CURSOR=1 で有効にします。 Editor および Input 組み込みコンポーネントは、このインターフェイスをすでに実装しています。
入力が埋め込まれたコンテナコンポーネント
コンテナコンポーネント (ダイアログ、セレクタなど) に Input または Editor の子が含まれる場合、コンテナは Focusable を実装し、フォーカス状態を子に伝播する必要があります。そうしないと、ハードウェア カーソルが IME 入力に対して正しく配置されません。
import { Container, type Focusable, Input } from "@earendil-works/pi-tui";
class SearchDialog extends Container implements Focusable {
private searchInput: Input;
// Focusable implementation - propagate to child input for IME cursor positioning
private _focused = false;
get focused(): boolean {
return this._focused;
}
set focused(value: boolean) {
this._focused = value;
this.searchInput.focused = value;
}
constructor() {
super();
this.searchInput = new Input();
this.addChild(this.searchInput);
}
}この伝播がないと、IME (中国語、日本語、韓国語など) で入力すると、画面上の間違った位置に候補ウィンドウが表示されます。
コンポーネントの使用
拡張機能内 ctx.ui.custom() 経由:
pi.on("session_start", async (_event, ctx) => {
const result = await ctx.ui.custom<string | null>((tui, theme, keybindings, done) =>
new MyComponent({
theme,
keybindings,
onChange: () => tui.requestRender(),
onSelect: (value) => done(value),
onCancel: () => done(null),
})
);
});カスタム ツール内 ctx.ui.custom() 経由:
async execute(toolCallId, params, signal, onUpdate, ctx) {
const result = await ctx.ui.custom<string | null>((tui, theme, keybindings, done) =>
new MyComponent({
theme,
keybindings,
onChange: () => tui.requestRender(),
onSelect: (value) => done(value),
onCancel: () => done(null),
})
);
// Use result...
}オーバーレイ
オーバーレイは、画面をクリアせずに、既存のコンテンツの上にコンポーネントをレンダリングします。 { overlay: true } を ctx.ui.custom() に渡します:
const result = await ctx.ui.custom<string | null>(
(tui, theme, keybindings, done) => new MyDialog({ onClose: done }),
{ overlay: true }
);位置決めとサイズ変更には、overlayOptions を使用します。
const result = await ctx.ui.custom<string | null>(
(tui, theme, keybindings, done) => new SidePanel({ onClose: done }),
{
overlay: true,
overlayOptions: {
// Size: number or percentage string
width: "50%", // 50% of terminal width
minWidth: 40, // minimum 40 columns
maxHeight: "80%", // max 80% of terminal height
// Position: anchor-based (default: "center")
anchor: "right-center", // 9 positions: center, top-left, top-center, etc.
offsetX: -2, // offset from anchor
offsetY: 0,
// Or percentage/absolute positioning
row: "25%", // 25% from top
col: 10, // column 10
// Margins
margin: 2, // all sides, or { top, right, bottom, left }
// Responsive: hide on narrow terminals
visible: (termWidth, termHeight) => termWidth >= 80,
},
// Get handle for programmatic focus and visibility control
onHandle: (handle) => {
// handle.focus() - focus this overlay and bring it to the visual front
// handle.unfocus() - release input to normal fallback
// handle.unfocus({ target }) - release input to a specific component or null
// handle.setHidden(true/false) - toggle visibility
// handle.hide() - permanently remove
},
}
);オーバーレイフォーカス
フォーカスされた表示オーバーレイは、一時的な非オーバーレイ UI 全体で入力の所有権を保持します。オーバーレイが { overlay: true } を持たずに別の ctx.ui.custom() コンポーネントを開いた場合、その置換 UI はアクティブな間入力を受け取ります。閉じると、フォーカスされたオーバーレイは入力を再利用できます。
表示されているオーバーレイが入力の所有を停止し、TUI が別の表示されているキャプチャ オーバーレイまたは前のフォーカス ターゲットにフォールバックする必要がある場合は、handle.unfocus() を使用します。オーバーレイが表示されている間に特定のコンポーネントが入力を受信する必要がある場合は、handle.unfocus({ target }) を使用します。 { target: null } を渡すと、フォーカスが再度設定されるまで、フォーカスされたコンポーネントが意図的に残されません。
オーバーレイのライフサイクル
オーバーレイ コンポーネントは閉じると破棄されます。参照を再利用しないでください - 新しいインスタンスを作成します。
// Wrong - stale reference
let menu: MenuComponent;
await ctx.ui.custom((_, __, ___, done) => {
menu = new MenuComponent(done);
return menu;
}, { overlay: true });
setActiveComponent(menu); // Disposed
// Correct - re-call to re-show
const showMenu = () => ctx.ui.custom((_, __, ___, done) =>
new MenuComponent(done), { overlay: true });
await showMenu(); // First show
await showMenu(); // "Back" = just call againアンカー、マージン、スタッキング、応答性の高い可視性、およびアニメーションをカバーする包括的な例については、overlay-qa-tests.ts を参照してください。
内蔵コンポーネント
@earendil-works/pi-tui からインポート:
import { Text, Box, Container, Spacer, Markdown } from "@earendil-works/pi-tui";文章
ワードラップされた複数行のテキスト。
const text = new Text(
"Hello World", // content
1, // paddingX (default: 1)
1, // paddingY (default: 1)
(s) => bgGray(s) // optional background function
);
text.setText("Updated");箱
パディングと背景色のコンテナー。
const box = new Box(
1, // paddingX
1, // paddingY
(s) => bgGray(s) // background function
);
box.addChild(new Text("Content", 0, 0));
box.setBgFn((s) => bgBlue(s));容器
子コンポーネントを垂直方向にグループ化します。
const container = new Container();
container.addChild(component1);
container.addChild(component2);
container.removeChild(component1);スペーサー
空の垂直スペース。
const spacer = new Spacer(2); // 2 empty linesMarkdown
構文を強調表示してマークダウンをレンダリングします。
const md = new Markdown(
"# Title\n\nSome **bold** text",
1, // paddingX
1, // paddingY
theme // MarkdownTheme (see below)
);
md.setText("Updated markdown");画像
サポートされている端末 (Kitty、iTerm2、Ghostty、WezTerm、Warp) でイメージをレンダリングします。
const image = new Image(
base64Data, // base64-encoded image
"image/png", // MIME type
theme, // ImageTheme
{ maxWidthCells: 80, maxHeightCells: 24 }
);キーボード入力
キー検出には matchesKey() を使用します。
import { matchesKey, Key } from "@earendil-works/pi-tui";
handleInput(data: string) {
if (matchesKey(data, Key.up)) {
this.selectedIndex--;
} else if (matchesKey(data, Key.enter)) {
this.onSelect?.(this.selectedIndex);
} else if (matchesKey(data, Key.escape)) {
this.onCancel?.();
} else if (matchesKey(data, Key.ctrl("c"))) {
// Ctrl+C
}
}キー識別子 (オートコンプリートまたは文字列リテラルには Key.* を使用します):
- 基本キー:
Key.enter、Key.escape、Key.tab、Key.space、Key.backspace、Key.delete、Key.home、Key.end - 矢印キー:
Key.up、Key.down、Key.left、Key.right - 修飾子あり:
Key.ctrl("c")、Key.shift("tab")、Key.alt("left")、Key.ctrlShift("p") - 文字列形式も機能します:
"enter"、"ctrl+c"、"shift+tab"、"ctrl+shift+p"
線幅
重要: render() からの各行は、width パラメータを超えてはなりません。
import { visibleWidth, truncateToWidth } from "@earendil-works/pi-tui";
render(width: number): string[] {
// Truncate long lines
return [truncateToWidth(this.text, width)];
}ユーティリティ:
visibleWidth(str)- 表示幅を取得します (ANSI コードを無視します)truncateToWidth(str, width, ellipsis?)- オプションの省略記号を使用して切り詰めますwrapTextWithAnsi(str, width)- ANSI コードを保持するワードラップ
カスタムコンポーネントの作成
例: インタラクティブセレクター
import {
matchesKey, Key,
truncateToWidth, visibleWidth
} from "@earendil-works/pi-tui";
class MySelector {
private items: string[];
private selected = 0;
private cachedWidth?: number;
private cachedLines?: string[];
public onSelect?: (item: string) => void;
public onCancel?: () => void;
constructor(items: string[]) {
this.items = items;
}
handleInput(data: string): void {
if (matchesKey(data, Key.up) && this.selected > 0) {
this.selected--;
this.invalidate();
} else if (matchesKey(data, Key.down) && this.selected < this.items.length - 1) {
this.selected++;
this.invalidate();
} else if (matchesKey(data, Key.enter)) {
this.onSelect?.(this.items[this.selected]);
} else if (matchesKey(data, Key.escape)) {
this.onCancel?.();
}
}
render(width: number): string[] {
if (this.cachedLines && this.cachedWidth === width) {
return this.cachedLines;
}
this.cachedLines = this.items.map((item, i) => {
const prefix = i === this.selected ? "> " : " ";
return truncateToWidth(prefix + item, width);
});
this.cachedWidth = width;
return this.cachedLines;
}
invalidate(): void {
this.cachedWidth = undefined;
this.cachedLines = undefined;
}
}拡張機能での使用法:
pi.registerCommand("pick", {
description: "Pick an item",
handler: async (_args, ctx) => {
const items = ["Option A", "Option B", "Option C"];
const selected = await ctx.ui.custom<string | null>((tui, _theme, _keybindings, done) => {
const selector = new MySelector(items);
selector.onSelect = done;
selector.onCancel = () => done(null);
return {
render: (width) => selector.render(width),
handleInput: (data) => {
selector.handleInput(data);
tui.requestRender();
},
invalidate: () => selector.invalidate(),
};
});
if (selected !== null) {
ctx.ui.notify(`Selected: ${selected}`, "info");
}
}
});テーマ設定
コンポーネントはスタイル設定用のテーマ オブジェクトを受け入れます。
renderCall/renderResult では、theme パラメータを使用します。
renderResult(result, options, theme, context) {
// Use theme.fg() for foreground colors
return new Text(theme.fg("success", "Done!"), 0, 0);
// Use theme.bg() for background colors
const styled = theme.bg("toolPendingBg", theme.fg("accent", "text"));
}前景色 (theme.fg(color, text)):
| カテゴリ | 色 |
|---|---|
| 一般的な | text, accent, muted, dim |
| 状態 | success, error, warning |
| 国境 | border, borderAccent, borderMuted |
| メッセージ | userMessageText, customMessageText, customMessageLabel |
| ツール | toolTitle, toolOutput |
| 差分 | toolDiffAdded, toolDiffRemoved, toolDiffContext |
| Markdown | mdHeading, mdLink, mdLinkUrl, mdCode, mdCodeBlock, mdCodeBlockBorder, mdQuote, mdQuoteBorder, mdHr, mdListBullet |
| 構文 | syntaxComment, syntaxKeyword, syntaxFunction, syntaxVariable, syntaxString, syntaxNumber, syntaxType, syntaxOperator, syntaxPunctuation |
| 考え | thinkingOff, thinkingMinimal, thinkingLow, thinkingMedium, thinkingHigh, thinkingXhigh, thinkingMax |
| モード | bashMode |
背景色 (theme.bg(color, text)):
selectedBg, userMessageBg, customMessageBg, toolPendingBg, toolSuccessBg, toolErrorBg
Markdown には、getMarkdownTheme() を使用します:
import { getMarkdownTheme } from "@earendil-works/pi-coding-agent";
import { Markdown } from "@earendil-works/pi-tui";
renderResult(result, options, theme, context) {
const mdTheme = getMarkdownTheme();
return new Markdown(result.details.markdown, 0, 0, mdTheme);
}カスタム コンポーネントの場合、独自のテーマ インターフェイスを定義します。
interface MyTheme {
selected: (s: string) => string;
normal: (s: string) => string;
}デバッグログ
stdout に書き込まれた生の ANSI ストリームをキャプチャするには、PI_TUI_WRITE_LOG を設定します。
PI_TUI_WRITE_LOG=/tmp/tui-ansi.log npx tsx packages/tui/test/chat-simple.tsパフォーマンス
可能であれば、レンダリングされた出力をキャッシュします。
class CachedComponent {
private cachedWidth?: number;
private cachedLines?: string[];
render(width: number): string[] {
if (this.cachedLines && this.cachedWidth === width) {
return this.cachedLines;
}
// ... compute lines ...
this.cachedWidth = width;
this.cachedLines = lines;
return lines;
}
invalidate(): void {
this.cachedWidth = undefined;
this.cachedLines = undefined;
}
}状態が変化したときに invalidate() を呼び出し、挿入された tui.requestRender() を使用して再レンダリングをトリガーします。
無効化とテーマの変更
テーマが変更されると、TUI はすべてのコンポーネントで invalidate() を呼び出してキャッシュをクリアします。テーマの変更を確実に有効にするために、コンポーネントは invalidate() を適切に実装する必要があります。
問題
コンポーネントがテーマの色を文字列にプリベイクし (theme.fg()、theme.bg() などを介して) キャッシュする場合、キャッシュされた文字列には古いテーマの ANSI エスケープ コードが含まれます。コンポーネントがテーマ別コンテンツを個別に保存している場合、レンダー キャッシュをクリアするだけでは十分ではありません。
間違ったアプローチ (テーマの色は更新されません):
class BadComponent extends Container {
private content: Text;
constructor(message: string, theme: Theme) {
super();
// Pre-baked theme colors stored in Text component
this.content = new Text(theme.fg("accent", message), 1, 0);
this.addChild(this.content);
}
// No invalidate override - parent's invalidate only clears
// child render caches, not the pre-baked content
}解決策
テーマカラーを使用してコンテンツを構築するコンポーネントは、 invalidate() が呼び出されたときにそのコンテンツを再構築する必要があります。
class GoodComponent extends Container {
private message: string;
private content: Text;
constructor(message: string) {
super();
this.message = message;
this.content = new Text("", 1, 0);
this.addChild(this.content);
this.updateDisplay();
}
private updateDisplay(): void {
// Rebuild content with current theme
this.content.setText(theme.fg("accent", this.message));
}
override invalidate(): void {
super.invalidate(); // Clear child caches
this.updateDisplay(); // Rebuild with new theme
}
}パターン: 無効化時に再構築
複雑なコンテンツを含むコンポーネントの場合:
class ComplexComponent extends Container {
private data: SomeData;
constructor(data: SomeData) {
super();
this.data = data;
this.rebuild();
}
private rebuild(): void {
this.clear(); // Remove all children
// Build UI with current theme
this.addChild(new Text(theme.fg("accent", theme.bold("Title")), 1, 0));
this.addChild(new Spacer(1));
for (const item of this.data.items) {
const color = item.active ? "success" : "muted";
this.addChild(new Text(theme.fg(color, item.label), 1, 0));
}
}
override invalidate(): void {
super.invalidate();
this.rebuild();
}
}これが重要な場合
このパターンは次の場合に必要です。
- テーマカラーのプリベイク -
theme.fg()またはtheme.bg()を使用して、子コンポーネントに保存されるスタイル付き文字列を作成します - 構文の強調表示 - テーマベースの構文の色を適用する
highlightCode()の使用 - 複雑なレイアウト - テーマカラーを埋め込む子コンポーネントツリーの構築
このパターンは、次の場合には必要ありません。
- テーマ コールバックの使用 - レンダリング中に呼び出される
(text) => theme.fg("accent", text)などの関数を渡す - シンプルなコンテナ - テーマ別コンテンツを追加せずに、他のコンポーネントをグループ化するだけです
- ステートレス レンダリング -
render()呼び出しごとにテーマに合わせた出力を新たに計算します (キャッシュなし)
よくあるパターン
これらのパターンは、拡張機能における最も一般的な UI ニーズをカバーします。 最初から構築するのではなく、これらのパターンをコピーします。
パターン1:選択ダイアログ(SelectList)
ユーザーがオプションのリストから選択できるようにするため。 @earendil-works/pi-tui の SelectList と DynamicBorder をフレームに使用します。
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
import { DynamicBorder } from "@earendil-works/pi-coding-agent";
import { Container, type SelectItem, SelectList, Text } from "@earendil-works/pi-tui";
pi.registerCommand("pick", {
handler: async (_args, ctx) => {
const items: SelectItem[] = [
{ value: "opt1", label: "Option 1", description: "First option" },
{ value: "opt2", label: "Option 2", description: "Second option" },
{ value: "opt3", label: "Option 3" }, // description is optional
];
const result = await ctx.ui.custom<string | null>((tui, theme, _kb, done) => {
const container = new Container();
// Top border
container.addChild(new DynamicBorder((s: string) => theme.fg("accent", s)));
// Title
container.addChild(new Text(theme.fg("accent", theme.bold("Pick an Option")), 1, 0));
// SelectList with theme
const selectList = new SelectList(items, Math.min(items.length, 10), {
selectedPrefix: (t) => theme.fg("accent", t),
selectedText: (t) => theme.fg("accent", t),
description: (t) => theme.fg("muted", t),
scrollInfo: (t) => theme.fg("dim", t),
noMatch: (t) => theme.fg("warning", t),
});
selectList.onSelect = (item) => done(item.value);
selectList.onCancel = () => done(null);
container.addChild(selectList);
// Help text
container.addChild(new Text(theme.fg("dim", "↑↓ navigate • enter select • esc cancel"), 1, 0));
// Bottom border
container.addChild(new DynamicBorder((s: string) => theme.fg("accent", s)));
return {
render: (w) => container.render(w),
invalidate: () => container.invalidate(),
handleInput: (data) => { selectList.handleInput(data); tui.requestRender(); },
};
});
if (result) {
ctx.ui.notify(`Selected: ${result}`, "info");
}
},
});
パターン 2: キャンセル付きの非同期操作 (BorderLoader)
時間がかかり、キャンセルできる必要がある操作の場合。 BorderedLoader はスピナーを表示し、エスケープをハンドルしてキャンセルします。
import { BorderedLoader } from "@earendil-works/pi-coding-agent";
pi.registerCommand("fetch", {
handler: async (_args, ctx) => {
const result = await ctx.ui.custom<string | null>((tui, theme, _kb, done) => {
const loader = new BorderedLoader(tui, theme, "Fetching data...");
loader.onAbort = () => done(null);
// Do async work
fetchData(loader.signal)
.then((data) => done(data))
.catch(() => done(null));
return loader;
});
if (result === null) {
ctx.ui.notify("Cancelled", "info");
} else {
ctx.ui.setEditorText(result);
}
},
});例: qna.ts、handoff.ts
パターン 3: 設定/切り替え (SettingsList)
複数の設定を切り替えます。 @earendil-works/pi-tui から getSettingsListTheme() までの SettingsList を使用します。
import { getSettingsListTheme } from "@earendil-works/pi-coding-agent";
import { Container, type SettingItem, SettingsList, Text } from "@earendil-works/pi-tui";
pi.registerCommand("settings", {
handler: async (_args, ctx) => {
const items: SettingItem[] = [
{ id: "verbose", label: "Verbose mode", currentValue: "off", values: ["on", "off"] },
{ id: "color", label: "Color output", currentValue: "on", values: ["on", "off"] },
];
await ctx.ui.custom((_tui, theme, _kb, done) => {
const container = new Container();
container.addChild(new Text(theme.fg("accent", theme.bold("Settings")), 1, 1));
const settingsList = new SettingsList(
items,
Math.min(items.length + 2, 15),
getSettingsListTheme(),
(id, newValue) => {
// Handle value change
ctx.ui.notify(`${id} = ${newValue}`, "info");
},
() => done(undefined), // On close
{ enableSearch: true }, // Optional: enable fuzzy search by label
);
container.addChild(settingsList);
return {
render: (w) => container.render(w),
invalidate: () => container.invalidate(),
handleInput: (data) => settingsList.handleInput?.(data),
};
});
},
});例: tools.ts
パターン 4: 永続的なステータス インジケーター
レンダリング間で維持されるステータスをフッターに表示します。モードインジケーターに適しています。
// Set status (shown in footer)
ctx.ui.setStatus("my-ext", ctx.ui.theme.fg("accent", "● active"));
// Clear status
ctx.ui.setStatus("my-ext", undefined);例: status-line.ts、plan-mode/index.ts、preset.ts
パターン 4b: 動作インジケーターのカスタマイズ
pi が応答をストリーミングしている間に表示されるインライン作業インジケーターをカスタマイズします。
// Static indicator
ctx.ui.setWorkingIndicator({ frames: [ctx.ui.theme.fg("accent", "●")] });
// Custom animated indicator
ctx.ui.setWorkingIndicator({
frames: [
ctx.ui.theme.fg("dim", "·"),
ctx.ui.theme.fg("muted", "•"),
ctx.ui.theme.fg("accent", "●"),
ctx.ui.theme.fg("muted", "•"),
],
intervalMs: 120,
});
// Hide the indicator entirely
ctx.ui.setWorkingIndicator({ frames: [] });
// Restore pi's default spinner
ctx.ui.setWorkingIndicator();これは、通常のストリーミング動作インジケーターにのみ影響します。圧縮および再試行ローダーは、組み込みのスタイルを維持します。カスタム フレームはそのままレンダリングされるため、拡張機能は必要に応じて独自の色を追加する必要があります。
パターン 5: エディターの上/下のウィジェット
入力エディターの上または下に永続的なコンテンツを表示します。 ToDo リストや進捗状況に適しています。
// Simple string array (above editor by default)
ctx.ui.setWidget("my-widget", ["Line 1", "Line 2"]);
// Render below the editor
ctx.ui.setWidget("my-widget", ["Line 1", "Line 2"], { placement: "belowEditor" });
// Or with theme
ctx.ui.setWidget("my-widget", (_tui, theme) => {
const lines = items.map((item, i) =>
item.done
? theme.fg("success", "✓ ") + theme.fg("muted", item.text)
: theme.fg("dim", "○ ") + item.text
);
return {
render: () => lines,
invalidate: () => {},
};
});
// Clear
ctx.ui.setWidget("my-widget", undefined);
パターン6: カスタムフッター
フッターを置き換えます。 footerData は、他の方法では拡張機能にアクセスできないデータを公開します。
ctx.ui.setFooter((tui, theme, footerData) => ({
invalidate() {},
render(width: number): string[] {
// footerData.getGitBranch(): string | null
// footerData.getExtensionStatuses(): ReadonlyMap<string, string>
return [`${ctx.model?.id} (${footerData.getGitBranch() || "no git"})`];
},
dispose: footerData.onBranchChange(() => tui.requestRender()), // reactive
}));
ctx.ui.setFooter(undefined); // restore defaultトークンの統計は ctx.sessionManager.getBranch() および ctx.model から入手できます。
パターン7:カスタムエディター(vimモードなど)
メインの入力エディタをカスタム実装に置き換えます。モーダル編集 (vim)、さまざまなキーバインド (emacs)、または特殊な入力処理に役立ちます。
import { CustomEditor, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
import { matchesKey, truncateToWidth } from "@earendil-works/pi-tui";
type Mode = "normal" | "insert";
class VimEditor extends CustomEditor {
private mode: Mode = "insert";
handleInput(data: string): void {
// Escape: switch to normal mode, or pass through for app handling
if (matchesKey(data, "escape")) {
if (this.mode === "insert") {
this.mode = "normal";
return;
}
// In normal mode, escape aborts agent (handled by CustomEditor)
super.handleInput(data);
return;
}
// Insert mode: pass everything to CustomEditor
if (this.mode === "insert") {
super.handleInput(data);
return;
}
// Normal mode: vim-style navigation
switch (data) {
case "i": this.mode = "insert"; return;
case "h": super.handleInput("\x1b[D"); return; // Left
case "j": super.handleInput("\x1b[B"); return; // Down
case "k": super.handleInput("\x1b[A"); return; // Up
case "l": super.handleInput("\x1b[C"); return; // Right
}
// Pass unhandled keys to super (ctrl+c, etc.), but filter printable chars
if (data.length === 1 && data.charCodeAt(0) >= 32) return;
super.handleInput(data);
}
render(width: number): string[] {
const lines = super.render(width);
// Add mode indicator to bottom border (use truncateToWidth for ANSI-safe truncation)
if (lines.length > 0) {
const label = this.mode === "normal" ? " NORMAL " : " INSERT ";
const lastLine = lines[lines.length - 1]!;
// Pass "" as ellipsis to avoid adding "..." when truncating
lines[lines.length - 1] = truncateToWidth(lastLine, width - label.length, "") + label;
}
return lines;
}
}
export default function (pi: ExtensionAPI) {
pi.on("session_start", (_event, ctx) => {
// Factory receives the TUI, theme, and keybindings from the app
ctx.ui.setEditorComponent((tui, theme, keybindings) =>
new VimEditor(tui, theme, keybindings)
);
});
}重要なポイント:
- **
CustomEditor** (ベースEditorではなく) を拡張して、アプリのキーバインドを取得します (中止するには Escape、終了するには Ctrl+D、モデルの切り替えなど) - 扱っていないキーについては、
super.handleInput(data)にお電話ください。 - ファクトリ パターン:
setEditorComponentは、tui、theme、およびkeybindingsを取得するファクトリ関数を受け取ります - デフォルトのエディターを復元するには、
undefinedを渡します:ctx.ui.setEditorComponent(undefined)
重要なルール
常にコールバックからテーマを使用してください - テーマを直接インポートしないでください。
ctx.ui.custom((tui, theme, keybindings, done) =>...)コールバックからthemeを使用します。常に DynamicBorder color パラメータを入力してください -
(s) => theme.fg("accent", s)ではなく、(s: string) => theme.fg("accent", s)と入力します。状態変更後に tui.requestRender() を呼び出す -
handleInputでは、状態を更新した後にtui.requestRender()を呼び出します。3 つのメソッド オブジェクトを返します - カスタム コンポーネントには
{ render, invalidate, handleInput }が必要です。既存のコンポーネントを使用 -
SelectList、SettingsList、BorderedLoaderがケースの 90% をカバーします。再構築しないでください。
例
- 選択 UI: examples/extensions/preset.ts - DynamicBorder フレームを使用した SelectList
- キャンセル付き非同期: examples/extensions/qna.ts - LLM 呼び出し用の BorderLoader
- 設定切り替え: examples/extensions/tools.ts - ツールの有効化/無効化の設定リスト
- ステータス インジケーター: examples/extensions/plan-mode/index.ts - setStatus および setWidget
- 作業インジケーター: examples/extensions/working-indicator.ts - setWorkingIndicator
- カスタム フッター: examples/extensions/custom-footer.ts - 統計情報を含む setFooter
- カスタム エディタ: examples/extensions/modal-editor.ts - Vim のようなモーダル編集
- スネーク ゲーム: examples/extensions/snake.ts - キーボード入力付きの完全なゲーム、ゲーム ループ
- カスタム ツール レンダリング: examples/extensions/todo.ts - renderCall および renderResult