UI API
UI APIは、Trae IDEでユーザーインターフェース要素を作成・管理するためのメソッドを提供します。パネル、ダイアログ、ステータスバー項目、カスタムビューなどが含まれます。
概要
UI APIでは以下のことができます:
- カスタムパネルとビューの作成
- ダイアログと入力ボックスの表示
- ステータスバー項目の追加
- ツリービューとWebビューパネルの作成
- IDEインターフェースのカスタマイズ
基本的な使用方法
メッセージの表示
typescript
import { TraeAPI } from '@trae/api';
// 情報メッセージを表示
TraeAPI.window.showInformationMessage('操作が正常に完了しました!');
// 警告メッセージを表示
TraeAPI.window.showWarningMessage('この操作は元に戻せません。');
// エラーメッセージを表示
TraeAPI.window.showErrorMessage('ファイルの保存に失敗しました。');
// アクション付きメッセージを表示
const result = await TraeAPI.window.showInformationMessage(
'変更を保存しますか?',
'保存',
'保存しない',
'キャンセル'
);
if (result === '保存') {
// 保存アクションを処理
}入力ダイアログ
typescript
// 入力ボックスを表示
const input = await TraeAPI.window.showInputBox({
prompt: 'ファイル名を入力してください',
placeHolder: 'example.txt',
validateInput: (value) => {
if (!value) {
return 'ファイル名は空にできません';
}
return null;
}
});
// クイックピックを表示
const selection = await TraeAPI.window.showQuickPick(
['オプション 1', 'オプション 2', 'オプション 3'],
{
placeHolder: 'オプションを選択してください',
canPickMany: false
}
);ステータスバー
typescript
// ステータスバー項目を作成
const statusBarItem = TraeAPI.window.createStatusBarItem(
TraeAPI.StatusBarAlignment.Left,
100
);
statusBarItem.text = '$(sync~spin) 処理中...';
statusBarItem.tooltip = 'クリックしてキャンセル';
statusBarItem.command = 'myExtension.cancelOperation';
statusBarItem.show();
// ステータスを更新
statusBarItem.text = '$(check) 完了';
statusBarItem.color = '#00ff00';カスタムパネル
Webビューパネルの作成
typescript
const panel = TraeAPI.window.createWebviewPanel(
'myExtension.panel',
'マイカスタムパネル',
TraeAPI.ViewColumn.One,
{
enableScripts: true,
retainContextWhenHidden: true
}
);
panel.webview.html = `
<!DOCTYPE html>
<html>
<head>
<title>マイパネル</title>
<style>
body { font-family: var(--vscode-font-family); }
.container { padding: 20px; }
</style>
</head>
<body>
<div class="container">
<h1>Webビューからこんにちは!</h1>
<button onclick="sendMessage()">メッセージを送信</button>
</div>
<script>
const vscode = acquireVsCodeApi();
function sendMessage() {
vscode.postMessage({ command: 'hello' });
}
</script>
</body>
</html>
`;
// Webビューからのメッセージを処理
panel.webview.onDidReceiveMessage((message) => {
if (message.command === 'hello') {
TraeAPI.window.showInformationMessage('Webビューからこんにちは!');
}
});ツリービュープロバイダー
typescript
class MyTreeDataProvider implements TraeAPI.TreeDataProvider<string> {
private _onDidChangeTreeData = new TraeAPI.EventEmitter<string | undefined>();
readonly onDidChangeTreeData = this._onDidChangeTreeData.event;
getTreeItem(element: string): TraeAPI.TreeItem {
return {
label: element,
collapsibleState: TraeAPI.TreeItemCollapsibleState.None,
command: {
command: 'myExtension.selectItem',
title: '選択',
arguments: [element]
}
};
}
getChildren(element?: string): string[] {
if (!element) {
return ['項目 1', '項目 2', '項目 3'];
}
return [];
}
refresh(): void {
this._onDidChangeTreeData.fire(undefined);
}
}
// ツリービューを登録
const treeDataProvider = new MyTreeDataProvider();
const treeView = TraeAPI.window.createTreeView('myExtension.treeView', {
treeDataProvider
});プログレスインジケーター
キャンセル可能なプログレス
typescript
TraeAPI.window.withProgress({
location: TraeAPI.ProgressLocation.Notification,
title: 'ファイルを処理中',
cancellable: true
}, async (progress, token) => {
const files = ['file1.txt', 'file2.txt', 'file3.txt'];
for (let i = 0; i < files.length; i++) {
if (token.isCancellationRequested) {
break;
}
progress.report({
increment: (100 / files.length),
message: `${files[i]}を処理中`
});
// 作業をシミュレート
await new Promise(resolve => setTimeout(resolve, 1000));
}
});ウィンドウプログレス
typescript
TraeAPI.window.withProgress({
location: TraeAPI.ProgressLocation.Window,
title: '読み込み中...'
}, async (progress) => {
progress.report({ increment: 0 });
// 何らかの作業を実行
await doSomeWork();
progress.report({ increment: 50, message: '半分完了...' });
// さらに作業を実行
await doMoreWork();
progress.report({ increment: 100, message: '完了!' });
});カスタムビュー
カスタムビューの登録
typescript
// package.jsonのcontributesセクション
{
"views": {
"explorer": [
{
"id": "myExtension.customView",
"name": "マイカスタムビュー",
"when": "workspaceFolderCount > 0"
}
]
},
"viewsContainers": {
"activitybar": [
{
"id": "myExtension.container",
"title": "マイ拡張機能",
"icon": "$(extensions)"
}
]
}
}テーマサポート
テーマカラーの使用
typescript
// CSS/HTMLで
const html = `
<style>
.error { color: var(--vscode-errorForeground); }
.warning { color: var(--vscode-warningForeground); }
.info { color: var(--vscode-infoForeground); }
.background { background-color: var(--vscode-editor-background); }
</style>
`;
// TypeScriptで
const errorColor = new TraeAPI.ThemeColor('errorForeground');
const decoration = TraeAPI.window.createTextEditorDecorationType({
color: errorColor,
backgroundColor: new TraeAPI.ThemeColor('editor.errorBackground')
});APIリファレンス
ウィンドウメソッド
showInformationMessage()
typescript
showInformationMessage<T extends string>(
message: string,
...items: T[]
): Thenable<T | undefined>;showInputBox()
typescript
showInputBox(options?: InputBoxOptions): Thenable<string | undefined>;createWebviewPanel()
typescript
createWebviewPanel(
viewType: string,
title: string,
showOptions: ViewColumn | { viewColumn: ViewColumn; preserveFocus?: boolean },
options?: WebviewPanelOptions & WebviewOptions
): WebviewPanel;createStatusBarItem()
typescript
createStatusBarItem(
alignment?: StatusBarAlignment,
priority?: number
): StatusBarItem;ベストプラクティス
- 適切なメッセージタイプを使用する(情報、警告、エラー)
- 明確で実行可能なメッセージを提供する
- 一貫した外観のためにテーマカラーをサポートする
- Webビューのライフサイクルを適切に処理する
- 不要になったUI要素は適切に破棄する
- 長時間実行される操作にはプログレスインジケーターを使用する
- VS Code UXガイドラインに従う
使用例
ファイルエクスプローラー拡張機能
typescript
class FileExplorerProvider implements TraeAPI.TreeDataProvider<FileItem> {
// カスタムファイルエクスプローラーの実装
}
const provider = new FileExplorerProvider();
TraeAPI.window.registerTreeDataProvider('myExtension.fileExplorer', provider);設定パネル
typescript
function createSettingsPanel() {
const panel = TraeAPI.window.createWebviewPanel(
'myExtension.settings',
'拡張機能設定',
TraeAPI.ViewColumn.One,
{ enableScripts: true }
);
panel.webview.html = getSettingsHtml();
panel.webview.onDidReceiveMessage(async (message) => {
switch (message.command) {
case 'saveSetting':
await saveExtensionSetting(message.key, message.value);
break;
}
});
}