跳到主要内容

组件系统

源码: components/ 目录

1. 组件架构

Claude Code 的 UI 组件分为三层:

App (根组件)
├── Messages (消息列表)
│ ├── UserMessage (用户消息)
│ ├── AssistantMessage (助手消息)
│ │ ├── StreamingText (流式文本)
│ │ └── ToolCalls (工具调用)
│ └── SystemMessage (系统消息)
├── ToolCallList (工具调用列表)
│ └── ToolCallItem (单个工具调用)
└── InputPrompt (输入提示)
└── CommandInput (命令输入)

2. 消息组件

UserMessageAssistantMessage 是核心展示组件:

function UserMessage({ message }: Props) {
return (
<Box flexDirection="column" padding={1}>
<Text bold color="cyan">You:</Text>
<Text wrap="wrap">{message.content}</Text>
</Box>
)
}
function AssistantMessage({ message }: Props) {
return (
<Box flexDirection="column" padding={1}>
<Text bold color="green">Claude:</Text>
{message.text && <Text wrap="wrap">{message.text}</Text>}
{message.toolCalls && <ToolCallList calls={message.toolCalls} />}
</Box>
)
}

3. 工具调用展示

工具调用状态实时显示:

function ToolCallItem({ call }: Props) {
const statusIcon = call.status === 'running' ? '⠋' :
call.status === 'done' ? '✓' :
call.status === 'error' ? '✗' : '·'

return (
<Box flexDirection="column" paddingLeft={2}>
<Text>{statusIcon} {call.toolName}</Text>
{call.status === 'done' && (
<Text dimColor>{call.output.substring(0, 200)}</Text>
)}
</Box>
)
}

4. 流式文本组件

处理 LLM 流式输出:

function StreamingText({ text, isStreaming }: Props) {
return (
<Text wrap="wrap">
{text}
{isStreaming && <Spinner />}
</Text>
)
}

关键特性:

  • 文本自动换行(wrap="wrap"
  • 流式追加(React state 驱动)
  • Spinner 指示加载中

5. 输入提示组件

function InputPrompt() {
return (
<Box>
<Text bold color="magenta"></Text>
<TextInput
value={input}
onChange={setInput}
onSubmit={handleSubmit}
/>
</Box>
)
}

6. 布局系统

使用 Ink 的 Box 组件实现 Flexbox 布局:

// 垂直布局
<Box flexDirection="column" height="100%">
{/* 消息区域:占满剩余空间 */}
<Box flexDirection="column" flexGrow={1}>
<Messages />
</Box>
{/* 输入区域:固定底部 */}
<Box>
<InputPrompt />
</Box>
</Box>

7. 颜色系统

终端使用 ANSI 颜色码:

颜色用途
cyan用户消息
green助手消息
yellow工具调用中
red错误
magenta提示符
dimColor次要信息

上一节:Ink 引擎 | 下一节:Hooks 系统