Merge remote-tracking branch 'origin/master' into xjt/readme-proofreading-batch-1

# Conflicts:
#	packages/client/ui-primitives/README.i18n.yaml
#	packages/client/ui-primitives/README.zh.md
This commit is contained in:
xjt
2026-07-29 20:21:48 +08:00
40 changed files with 3516 additions and 121 deletions

View File

@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/client/ui-primitives/README.md
README.md: 58e450451ab64f69762817dfb277b8a888e2177f
README.zh.md: d8947c6935f67566b9208d0f15af6dcf25326b01
README.md: 1236054d5a05464c43ad1bb0dcbe52b09281e68a
README.zh.md: 567881e8ca7d5e8017f82884cd638f08b13fc7e7

View File

@@ -2,12 +2,16 @@
English | [中文](README.zh.md)
Pure React atoms (zero cordis): StateDot, ic_ds_* icons, Button/Pill/Menu/Modal/Input, markdown family (MessageText/MarkdownText/JsonBlock). Contract: api-contracts v3 §8.
Pure React atoms (zero cordis): StateDot, ic_ds_* icons, Button/Pill/Menu/Modal/Input, markdown family (MessageText/MarkdownText/JsonBlock), TerminalBlock. Contract: api-contracts v3 §8.
## Markdown rendering
`MarkdownText` renders GFM from untrusted assistant output through React elements. It omits raw HTML, neutralizes relative and non-HTTP(S)/mailto links, opens HTTP(S) links with safe external-link attributes, and renders image alt text without loading remote resources; `MessageText` remains the literal-text primitive for user-authored content. Element spacing, tables, links, and inline code use the same `--dsw-alias-markdown-*` / `--dsw-font-markdown-*` tokens as deepsuite `@deepseek/md`. Fenced blocks render through `CodeBlock` (language banner, copy control, shiki for the registered grammars).
## Terminal output
`TerminalBlock` renders a shell command as a terminal surface: one prompt row per line of the command (the shortened `cwd` label on the first row only, since the view knows one working directory and a `cd` moves later lines elsewhere, then that line), the command's output, a status pill for a non-zero exit code or a terminating signal, and a copy control that writes the raw `output` prop. A run-state `StateDot` marks the call once, on the first row, out of flow in a gutter the card reserves as its own left padding, so the dot sits inside the card box yet left of the prompt text. It reaches three of `StateDot`'s states — the chase while `running`, red for the same exit status that renders the pill, green otherwise — so a card states whether its command is still running rather than leaving that to be inferred from the presence of output; it carries one visually hidden text label because `StateDot` is `aria-hidden`. One dot regardless of line count is deliberate: the exit status is the whole call's, so a dot per line would claim a per-line outcome the view does not carry. Command text is `white-space: pre`, so repeated spaces, tabs, and an indented continuation render verbatim while the row stays single-line and ellipsizes. ANSI escape sequences are parsed with the `anser` runtime dependency into React spans; cursor movements replay into a per-line column buffer before inert controls are stripped, since carriage return and backspace only MOVE the cursor: `100%` + CR + `OK` alone shows `OK0%`, while the `\x1b[K` a spinner writes with its redraw erases the tail so `100%\r\x1b[KOK` shows `OK`. Erase-in-line is honored in all three parameter forms, the cursor advances by terminal columns (8-column tab stops, two for emoji and CJK, none for a combining mark), and SGR state is normalized per cell as a terminal stores it, threading across lines and closing at the state the line ended in; basic-16 foreground colors map onto `--dsw-*` tokens, while 256-palette and truecolor values pass through as literal rgb. Output keeps `white-space: pre` with horizontal scrolling, so column-aligned output holds its alignment instead of soft-wrapping, and collapses to a head slice plus a tail slice past `maxLines` (default 16, the TUI transcript's split arithmetic) behind an expand button. Rationale: [the web terminal card note](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md).
## Model Experience
None, as the package renders pure React atoms in the browser; nothing here reaches a model request.
@@ -21,3 +25,5 @@ None; this package neither assembles nor sends a provider request.
- **Glyph-level icons are redrawn approximations** — the fish logo (and the sparkle held by ui-conversation) come from font glyphs whose vector geometry is not exportable from the local design data; hand-authored recreations stand in until an exact export path exists.
- **Pill and Input have no design source** — both atoms are self-defined; the sidebar search field and view-tab strip that resemble them are consumer-owned compositions, not these atoms.
- **StateDot `Active` variant is a hidden placeholder in the design** — not implemented; the four shipped states (done/warning/ongoing/error) are the complete P-I surface.
- **This package's user-facing copy is inline Chinese, not localized** — the atoms are zero-cordis and so cannot reach `ctx.locale`; `TerminalBlock`'s exit-code and signal pills, its copy and expand controls, and `CodeBlock`'s copy control are all hardcoded. This matches the repo-wide state the locale package records (only the Settings surface is translated); extracting these into the `zh`/`en` dictionaries needs a localization channel for zero-cordis atoms and belongs to that repo-wide extraction.
- **`TerminalBlock` is not a terminal emulator** — it renders settled or still-running command output, not an interactive session: SGR color and attributes are honored, and so are the in-line cursor movements a progress line uses — carriage return, backspace, erase-in-line, tab stops and character width. Absolute cursor positioning, screen clearing, and alternate-screen sequences are stripped. Basic-16 magenta and cyan have no token equivalent and stay literal rgb.

View File

@@ -2,12 +2,16 @@
[English](README.md) | 中文
纯 React 原子组件(零 cordisStateDot、ic_ds_* 图标、Button/Pill/Menu/Modal/Input,以及 markdown 家族MessageText/MarkdownText/JsonBlock。契约api-contracts v3 §8。
纯 React 原子组件(零 cordisStateDot、ic_ds_* 图标、Button/Pill/Menu/Modal/Inputmarkdown 家族MessageText/MarkdownText/JsonBlock,以及 TerminalBlock。契约api-contracts v3 §8。
## Markdown 渲染
`MarkdownText` 通过 React 元素渲染来自不受信任的 assistant 输出的 GFM。它会省略原始 HTML使相对链接及非 HTTP(S)/mailto 链接失效,以安全的外部链接属性打开 HTTP(S) 链接,并只渲染图片 alt 文本而不加载远程资源;`MessageText` 仍是用户创作内容使用的字面文本原语。元素间距、表格、链接与行内代码使用与 deepsuite `@deepseek/md` 相同的 `--dsw-alias-markdown-*` / `--dsw-font-markdown-*` token。围栏代码块通过 `CodeBlock` 渲染(语言横幅、复制控件,以及对已注册语法使用 shiki
## 终端输出
`TerminalBlock` 将一条 shell 命令渲染为终端表层:命令的每一行各占一个提示行(缩短后的 `cwd` 标签只出现在第一行,因为视图只知道一个工作目录,而一个 `cd` 就会让后面的行去到别处,标签之后是该行)、命令输出、非零退出码或终止信号对应的状态胶囊,以及写入原始 `output` prop 的复制控件。一枚运行状态 `StateDot` 为整次调用标记一次,位于第一行,以脱离文档流的方式落在卡片以自身左内边距预留的落区中,因此它位于卡片盒之内、提示文字之左。它用到 `StateDot` 的三种状态——`running` 期间为追逐动画,与渲染状态胶囊相同的退出状态为红色,其余为绿色——因此卡片直接陈述其命令是否仍在运行,而不是让人从有无输出中推断;由于 `StateDot``aria-hidden`,它携带一处视觉隐藏的文本标签。无论多少行都只有一枚状态点是有意为之:退出状态属于整次调用,因此每行一枚就会声称一个视图并不携带的逐行结果。命令文本使用 `white-space: pre`因此重复空格、制表符与缩进续行都原样呈现同时该行仍保持单行并以省略号截断。ANSI 转义序列通过运行时依赖 `anser` 解析为 React span光标移动在剥除无显示意义控制符之前先重放进逐行的列缓冲因为回车与退格**只移动**光标:单是 `100%` 加回车再加 `OK` 显示为 `OK0%`,而 spinner 随重绘写出的 `\x1b[K` 会擦掉尾巴,因此 `100%\r\x1b[KOK` 显示为 `OK`。行内擦除的三种参数形式都被遵循光标按终端列推进8 列制表位emoji 与 CJK 占两列组合标记不占列SGR 状态按单元格归一化存储,与终端一致,并跨行延续、在行结束时的状态处收束;基础 16 色前景色映射到 `--dsw-*` token而 256 色板与真彩色值按字面 rgb 透传。输出保持 `white-space: pre` 并支持横向滚动,因此按列对齐的输出保留其对齐而不会软换行;超过 `maxLines`(默认 16与 TUI 转录相同的切分算法)时折叠为头部切片加尾部切片,由展开按钮控制。原理:[Web 终端卡片笔记](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md)。
## 模型体验
无。该包package在浏览器中渲染纯 React 原子组件;这里没有任何内容进入模型请求。
@@ -20,4 +24,6 @@
- **字形级图标是重新绘制的近似版本**:鱼形标志(以及 ui-conversation 持有的闪光图标)来自字体字形,而本地设计数据无法导出其矢量几何;在获得精确导出路径前,使用手工重建版本代替。
- **Pill 与 Input 没有设计来源**:两个原子组件均自行定义;与其相似的侧边栏搜索字段和视图标签条由消费方组合,不是这些原子组件。
- **StateDot 的 `Active` 变体是设计中的隐藏占位符**尚未实现已交付的四种状态done/warning/ongoing/error就是 P-I 阶段对外提供的全部状态。
- **StateDot 的 `Active` 变体是设计中的隐藏占位符**尚未实现已交付的四种状态done/warning/ongoing/error构成完整的 P-I 表层。
- **本包面向用户的文案是内联中文,未做本地化**:这些原子组件是 zero-cordis 的,因此拿不到 `ctx.locale``TerminalBlock` 的退出码与信号胶囊、它的复制与展开控件,以及 `CodeBlock` 的复制控件全部硬编码。这与 locale 包记录的全仓现状一致(只有 Settings 表面做了翻译);把它们抽取进 `zh`/`en` 字典需要为 zero-cordis 原子组件提供一条本地化通道,属于那次全仓抽取的范围。
- **`TerminalBlock` 不是终端模拟器**它渲染已结束或仍在运行的命令输出而不是交互式会话SGR 颜色与属性会被遵循,进度行所用的行内光标移动同样被遵循——回车、退格、行内擦除、制表位与字符宽度。绝对光标定位、清屏与备用屏幕序列会被剥离。基础 16 色中的洋红与青色没有对应 token保持字面 rgb。

View File

@@ -21,6 +21,7 @@
"license": "BSD-3-Clause",
"dependencies": {
"@shikijs/langs": "^4.3.1",
"anser": "^2.3.5",
"clsx": "^2.0.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",

View File

@@ -12,7 +12,9 @@ import css from './Pill.module.css'
*/
export function Pill({ active = false, className, children, onClick, ...rest }: {
active?: boolean
className?: string
// `| undefined` so a caller can forward an optional class straight through
// under exactOptionalPropertyTypes (a CSS-module lookup is string|undefined).
className?: string | undefined
children?: ReactNode
} & ButtonHTMLAttributes<HTMLButtonElement>) {
if (!onClick) {

View File

@@ -23,8 +23,8 @@ const MATRIX_CELLS: readonly (readonly [number, number])[] = [
*/
export function StateDot({ state, size = 10, className }: {
state: StateDotState
size?: number
className?: string
size?: number | undefined
className?: string | undefined
}) {
if (state === 'ongoing') {
return (

View File

@@ -0,0 +1,152 @@
/* Geometry mirrors CodeBlock (12px radius, code-block surface + banner rows,
markdown code-block font) so a terminal card and a fenced code block read as
one family. The one deliberate divergence: output keeps `white-space: pre`
and scrolls horizontally, because folding a column-aligned command's output
destroys its alignment. */
.block {
--dsl-terminal-radius: 12px;
--dsl-terminal-line-height: 22px;
/* The card's own left inset, holding the run-state dot in a column of its own
so it never competes with the commands for horizontal space. */
--dsl-terminal-gutter: 30px;
position: relative;
margin: 16px 0;
/* The gutter is the card's OWN padding, not a margin: every consumer rewrites
`margin` wholesale (each render site sets its own indent), which silently
cancelled the reservation and let the dot fall outside the card into a
container that clips it. Owning the reservation here keeps the invariant
with the component that depends on it. */
padding-left: var(--dsl-terminal-gutter);
color: var(--dsw-alias-label-primary);
background: var(--dsw-alias-markdown-code-block);
border-radius: var(--dsl-terminal-radius);
}
/* Top-aligned: the status pill and copy control stay on the first prompt row
however many command lines the card carries. */
.header {
display: flex;
align-items: flex-start;
gap: 12px;
/* Pulled back across the card's gutter padding so the banner background and
its top-left radius span the FULL surface, then re-inset by the same amount
so the prompt text and the dot keep their positions. A plain block child
only reaches the content box, which left the gutter column painted in the
body color and drew the card's top-left corner in it — invisible in the
light theme, where banner and body share a token, and visible in the dark
one, where they do not. */
margin-left: calc(-1 * var(--dsl-terminal-gutter));
padding: 9px 14px 9px var(--dsl-terminal-gutter);
background: var(--dsw-alias-markdown-code-block-banner);
border-top-left-radius: var(--dsl-terminal-radius);
border-top-right-radius: var(--dsl-terminal-radius);
}
/* One row per command line. The prompt column is the only element allowed to
shrink; the status pill and the copy control keep their intrinsic width. */
.prompt {
display: flex;
flex-direction: column;
min-width: 0;
flex: 1;
font: var(--dsw-font-markdown-code-block);
}
.promptLine {
position: relative;
display: flex;
align-items: baseline;
gap: 8px;
min-width: 0;
line-height: var(--dsl-terminal-line-height);
}
/* Out of flow inside the card's own gutter padding, so the reservation and the
dot move together and no consumer margin can pull them apart; the dot neither
indents its command nor depends on the command's text metrics to line up.
Centered against the row's line box, not the code font's baseline. */
.runState {
position: absolute;
left: calc(-1 * var(--dsl-terminal-gutter) + 8px);
top: 50%;
transform: translateY(-50%);
}
/* The dot is aria-hidden; this is its text label for assistive technology. */
.runStateLabel {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
.cwd {
flex: none;
color: var(--dsw-alias-label-tertiary);
}
/* `pre`, not `nowrap`: the prompt row renders the command verbatim, and
`nowrap` collapses the repeated spaces, tabs, and alignment of an indented
continuation. Both hold the single row and the ellipsis. */
.command {
min-width: 0;
color: var(--dsw-alias-label-primary);
overflow: hidden;
text-overflow: ellipsis;
white-space: pre;
}
.status {
flex: none;
color: var(--dsw-alias-state-error-primary);
}
.copyButton {
flex: none;
background-color: transparent;
border: none;
padding: 0;
margin: 0;
color: var(--dsw-alias-label-secondary);
cursor: pointer;
font: var(--dsw-font-xs-13);
}
.output {
padding: 12px 14px 12px 0;
font: var(--dsw-font-markdown-code-block);
overflow-x: auto;
overflow-y: hidden;
}
/* No wrapping, no word-break: alignment is the payload of terminal output. */
.line {
min-height: var(--dsl-terminal-line-height);
white-space: pre;
}
.expand {
display: block;
width: 100%;
padding: 0;
border: none;
background-color: transparent;
color: var(--dsw-alias-label-tertiary);
cursor: pointer;
font: inherit;
text-align: left;
}
.expand:hover {
color: var(--dsw-alias-label-secondary);
}
.empty {
padding: 12px 14px 12px 0;
font: var(--dsw-font-markdown-code-block);
color: var(--dsw-alias-label-tertiary);
}

View File

@@ -0,0 +1,237 @@
// TerminalBlock: the terminal surface for a shell command and its output —
// prompt line (run-state dot + shortened cwd + command), ANSI-colored output,
// settled exit status, and a copy control for the raw output. Output never soft-wraps:
// column-aligned output (ls, tables, box drawing) keeps its alignment and
// scrolls horizontally instead of folding. Colors resolve through --dsw-*
// tokens; ANSI parsing lives in ansi.ts.
import { useCallback, useMemo, useState } from 'react'
import clsx from 'clsx'
import { parseAnsiLines, type AnsiLine } from './ansi.ts'
import { writeClipboard } from './clipboard.ts'
import { Pill } from './Pill.tsx'
import { StateDot, type StateDotState } from './StateDot.tsx'
import css from './TerminalBlock.module.css'
/**
* Output lines shown before the height cap collapses the middle. Matches the
* TUI transcript's default tool-output budget so both front ends cut a long
* command's output at the same place.
*/
export const DEFAULT_TERMINAL_MAX_LINES = 16
export interface TerminalBlockProps {
/** The command line, rendered verbatim after the prompt label. */
command: string
/** Working directory for the prompt label; absent renders a plain `$`. */
cwd?: string | undefined
/** Absolute home directory, so a cwd equal to it collapses to `~`; absent disables that collapse. */
home?: string | undefined
/** The command's output text; may contain ANSI escape sequences. */
output?: string | undefined
/** Settled exit code; a non-zero value renders the status pill. */
exitCode?: number | undefined
/** Settled terminating signal name; any value renders the status pill, taking precedence over the exit code. */
signal?: string | undefined
/** The command is still running: the block shows the prompt line alone. */
running?: boolean | undefined
/** Height cap in output lines before the middle collapses (default {@link DEFAULT_TERMINAL_MAX_LINES}). */
maxLines?: number | undefined
/** Extra class merged onto the wrapper (callers position; this component draws). */
className?: string | undefined
}
/**
* Prompt label for a working directory: `~` for the home directory itself,
* otherwise the path's last segment (both separators accepted, trailing
* separators ignored), falling back to the path itself when it has no
* segment.
* @param cwd - the working directory path.
* @param home - absolute home directory, when the caller knows it.
* @returns the prompt label.
*/
function promptLabel(cwd: string, home: string | undefined): string {
const trimmed = cwd.replace(/[/\\]+$/, '')
if (home !== undefined && trimmed === home.replace(/[/\\]+$/, '')) return '~'
const segment = trimmed.split(/[/\\]/).pop()
return segment === undefined || segment === '' ? cwd : segment
}
/**
* Status pill text for a settled command, or undefined when the command
* settled cleanly (exit 0, no signal) and needs no pill — the same
* distinction the bash tool's own exit-status markers draw.
* @param exitCode - settled exit code, when known.
* @param signal - settled terminating signal name, when known.
* @returns the pill text, or undefined for a clean exit.
*/
function statusText(exitCode: number | undefined, signal: string | undefined): string | undefined {
if (signal !== undefined) return `信号 ${signal}`
if (exitCode !== undefined && exitCode !== 0) return `退出码 ${exitCode}`
return undefined
}
/**
* Run-state indicator for the command, shown at the head of the prompt line so
* the card states whether the command is still running without the reader
* having to infer it from the presence of output. Three of {@link StateDotState}'s
* four states are reachable: the running chase (the same
* indicator a running tool row's leading icon uses, so the row and its card
* never disagree), green for a clean settle, red for a signal or a non-zero
* exit — the same status distinction {@link statusText} draws for the pill. A
* settled command whose exit status never reached the view counts as a clean
* settle: the view says it finished and says nothing went wrong.
* @param running - the command has not settled.
* @param exitCode - settled exit code, when known.
* @param signal - settled terminating signal name, when known.
* @returns the dot's state and its text label, since the dot is aria-hidden.
*/
function runState(
running: boolean,
exitCode: number | undefined,
signal: string | undefined,
): { state: StateDotState; label: string } {
if (running) return { state: 'ongoing', label: '运行中' }
if (statusText(exitCode, signal) !== undefined) return { state: 'error', label: '失败' }
return { state: 'done', label: '已完成' }
}
/**
* Render one parsed output line. Runs without SGR state render as bare text,
* so uncolored output carries no span wrappers.
* @param line - the line's styled runs.
* @returns the line's children.
*/
function renderLine(line: AnsiLine) {
return line.map((span, index) => span.style === undefined
? span.text
: <span key={index} style={span.style}>{span.text}</span>)
}
/**
* Render a shell command as a terminal surface.
* @param props - see {@link TerminalBlockProps}.
* @returns the terminal block element.
*/
export function TerminalBlock({
command,
cwd,
home,
output,
exitCode,
signal,
running = false,
maxLines = DEFAULT_TERMINAL_MAX_LINES,
className,
}: TerminalBlockProps) {
const text = output ?? ''
// A command's output ends with a newline; that terminator is not an extra
// blank line to draw or to count against the height cap. The check runs on the
// PARSED lines rather than on the raw text, because a reset after the final
// newline (`line\n\x1b[0m`) leaves the string not ending in one while still
// producing a last line with nothing visible in it. A genuinely blank final
// line — the double newline — survives, since it has a real empty line before
// the terminator. The copy control still copies `text` untouched.
const lines = useMemo(() => {
const parsed = parseAnsiLines(text)
const last = parsed[parsed.length - 1]
const terminated = parsed.length > 1 && last !== undefined
&& last.every(span => span.text === '')
return terminated ? parsed.slice(0, -1) : parsed
}, [text])
const [expanded, setExpanded] = useState(false)
const [copied, setCopied] = useState(false)
const onCopy = useCallback(() => {
if (copied) return
// The raw output, never the rendered tree: the prompt line and the status
// pill are chrome the user did not run.
void writeClipboard(text).then((ok) => {
if (!ok) return
setCopied(true)
window.setTimeout(() => { setCopied(false) }, 1000)
})
}, [copied, text])
const onToggle = useCallback(() => { setExpanded(value => !value) }, [])
const status = statusText(exitCode, signal)
const state = runState(running, exitCode, signal)
// A multi-line command gets one prompt row per line, so a two-command shell
// snippet reads as the two commands it is instead of collapsing into one
// ellipsized row. A trailing newline is a terminator, not an empty command.
const commandLines = useMemo(() => {
const body = command.endsWith('\n') ? command.slice(0, -1) : command
return body.split('\n')
}, [command])
// Read from the parsed lines the card actually renders, not from the raw text:
// output that is only escapes or control bytes (a lone reset, an OSC title, an
// erase) survives `text.trim()` yet parses to nothing visible. Judging it on
// the raw text drew an output box of blank rows plus a copy control for
// invisible bytes, and hid the placeholder that belongs there.
const empty = lines.every(line => line.every(span => span.text.trim() === ''))
const hidden = lines.length - maxLines
const capped = hidden > 0 && !expanded
// Same split arithmetic as the TUI transcript's collapsed tool card, so a
// command's head and tail slices agree between the two front ends.
const headLines = Math.ceil(maxLines / 2)
const tailLines = maxLines - headLines
return (
<div className={clsx(css.block, className)} data-terminal="" data-running={running ? '' : undefined}>
<div className={css.header}>
<div className={css.prompt}>
<span className={css.runStateLabel}>{state.label}</span>
{commandLines.map((line, index) => (
<div key={index} className={css.promptLine}>
{/* One dot for the card, on the first row: the exit status the
view carries is the whole call's, and bash reports no
per-command status, so a dot per row would assert a
per-line outcome nothing here knows. */}
{index === 0 && <StateDot state={state.state} className={css.runState} />}
{/* The cwd labels the CALL, so only its first row carries it. The
view knows one working directory — where the call started —
and a later line may well run somewhere else (a `cd` in the
command is enough), so repeating the label down the rows would
assert a directory per line that nothing here knows. Later
rows keep a bare `$` to stay aligned as prompts. */}
<span className={css.cwd}>
{index > 0 || cwd === undefined ? '$' : promptLabel(cwd, home)}
</span>
<span className={css.command}>{line}</span>
</div>
))}
</div>
{status !== undefined && <Pill className={css.status}>{status}</Pill>}
{!running && !empty && (
<button type="button" className={css.copyButton} onClick={onCopy}>
{copied ? '复制成功' : '复制'}
</button>
)}
</div>
{!running && (empty
? <div className={css.empty}></div>
: (
<div className={css.output}>
{(capped ? lines.slice(0, headLines) : lines).map((line, index) => (
<div key={index} className={css.line}>{renderLine(line)}</div>
))}
{hidden > 0 && (
<button
type="button"
className={css.expand}
aria-expanded={expanded}
aria-label={expanded ? '收起输出' : `展开其余 ${hidden} 行输出`}
onClick={onToggle}
>
{expanded ? '收起' : `… 其余 ${hidden}`}
</button>
)}
{capped && lines.slice(lines.length - tailLines).map((line, index) => (
<div key={index} className={css.line}>{renderLine(line)}</div>
))}
</div>
))}
</div>
)
}

View File

@@ -0,0 +1,447 @@
// ANSI model behind TerminalBlock: anser splits the SGR runs, this module
// resolves each run's colors and decorations into a plain style record and
// folds the runs into per-line span arrays so a height cap can slice whole
// lines. Sequences anser does not turn into color (OSC, cursor movement,
// other C0 controls) are removed before parsing so they never reach the DOM
// as literal characters.
import Anser from 'anser'
import type { CSSProperties } from 'react'
/**
* The subset of one anser JSON chunk this module reads. anser's own types
* declare `fg`/`bg` as `string`, but its parser leaves them `null` for a run
* that sets no color, so the null is spelled out here.
*/
interface AnsiChunk {
/** Run text with its SGR codes already removed. */
content: string
/** Foreground as an `r, g, b` triple, or null when the run sets none. */
fg: string | null
/** Background as an `r, g, b` triple, or null when the run sets none. */
bg: string | null
/** SGR attributes in effect for the run, in the order they were declared. */
decorations: readonly string[]
}
/** One run of terminal text; `style` is undefined for text that carries no SGR state. */
export interface AnsiSpan {
/** The run's plain text, free of escape sequences and newlines. */
text: string
/** Resolved inline style, or undefined when the run needs no wrapper. */
style: CSSProperties | undefined
}
/** The spans of one output line, in order. */
export type AnsiLine = readonly AnsiSpan[]
/**
* The 8/16 basic ANSI colors, keyed by the whitespace-free `r,g,b` triple
* anser emits for them, mapped onto the theme tokens that carry the same
* semantic. Black and white both resolve to the primary label color so text
* stays legible under either theme instead of matching the surface it sits
* on; bright black takes the tertiary label color (the muted-gray role).
* Magenta and cyan have no token equivalent in this design system and fall
* through to anser's literal rgb, as do all 256-palette and truecolor values.
*/
const TOKEN_BY_BASIC_RGB: Record<string, string> = {
'0,0,0': 'var(--dsw-alias-label-primary)',
'255,255,255': 'var(--dsw-alias-label-primary)',
'85,85,85': 'var(--dsw-alias-label-tertiary)',
'187,0,0': 'var(--dsw-alias-state-error-primary)',
'255,85,85': 'var(--dsw-alias-state-error-secondary)',
'0,187,0': 'var(--dsw-alias-state-success-primary)',
'0,255,0': 'var(--dsw-alias-state-success-secondary)',
'187,187,0': 'var(--dsw-alias-state-warn-primary)',
'255,255,85': 'var(--dsw-alias-state-warn-secondary)',
'0,0,187': 'var(--dsw-alias-state-business-primary)',
'85,85,255': 'var(--dsw-static-blue-400)',
}
/**
* CSS for each SGR attribute anser reports. `blink` is deliberately absent —
* animated text is not reproduced. `reverse` never arrives here: anser
* consumes it by swapping the run's foreground and background. Underline and
* strikethrough share `textDecoration`, so in a run declaring both, the
* later declaration wins.
*/
const STYLE_BY_DECORATION: Record<string, CSSProperties | undefined> = {
bold: { fontWeight: 700 },
dim: { opacity: 0.7 },
italic: { fontStyle: 'italic' },
underline: { textDecoration: 'underline' },
strikethrough: { textDecoration: 'line-through' },
hidden: { visibility: 'hidden' },
}
/** OSC strings (window title, hyperlinks), with or without their terminator. */
const OSC_SEQUENCE = /\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)?/g
/** Escape sequences other than CSI: charset selection, single-shift, reset. */
const NON_CSI_ESCAPE = /\u001b(?!\[)[\u0020-\u002f]*[\u0030-\u007e]?/g
/**
* C0 controls with no display meaning here. Tab, newline, backspace and ESC
* survive: the first two for layout, backspace for the cursor replay, ESC
* for anser's CSI split.
*/
const INERT_CONTROL = /[\u0000-\u0007\u000b-\u001a\u001c-\u001f\u007f]/g
/**
* Lines whose cursor movements have to be replayed: a carriage return, a
* backspace, or an erase-in-line. The erase pattern matches the SAME CSI shape
* `replayLine` parses (parameters may carry `;` and intermediate bytes), so a
* form like `\x1b[1;2K` cannot slip past this guard and skip its own erase.
*/
const NEEDS_REPLAY = /\r|\u0008|\u001b\[[\u0030-\u003f]*[\u0020-\u002f]*K/
/** SGR sequences alone, for folding state through a line that needs no replay. */
const SGR_SEQUENCE = /\u001b\[([\u0030-\u003f]*)[\u0020-\u002f]*m/g
/** Terminal tab stop width; a tab advances to the next multiple of this. */
const TAB_WIDTH = 8
/**
* Combining marks and other zero-width code points: a terminal advances no
* column for them, so `e` + U+0301 occupies one cell and a two-column redraw
* covers both code points.
*/
const ZERO_WIDTH = /^[\p{Mn}\p{Me}\p{Cf}\u200b-\u200f\u2060]$/u
/**
* Characters a terminal advances two columns for: CJK scripts, fullwidth forms,
* CJK punctuation, and characters with emoji presentation. Text-presentation
* symbols (`\u2713`, `\u26a0` and the rest of U+2600-U+27BF) are ONE column and
* must stay out of this set.
*/
const WIDE_CHAR = new RegExp(
'\\p{Script=Han}|\\p{Script=Hiragana}|\\p{Script=Katakana}|\\p{Script=Hangul}'
// Emoji presentation only: the U+2600-U+27BF symbol block is mostly SINGLE
// width — `\u2713` (the check every progress line writes, this fixture
// included) advances one column, verified against a real terminal, so taking
// the whole block as wide misaligned exactly the output this card exists for.
+ '|\\p{Emoji_Presentation}'
+ '|[\\uff01-\\uff60\\u3000-\\u303e]',
'u',
)
/**
* Whether a character occupies two terminal columns (CJK, fullwidth forms,
* emoji). Covers the ranges a command's output realistically carries; a
* narrower guess would misalign the columns this card exists to preserve.
* @param char - one character from the output.
* @returns true when the terminal advances two columns for it.
*/
function isWide(char: string): boolean {
const code = char.codePointAt(0)
if (code === undefined || code < 0x1100) return false
return WIDE_CHAR.test(char)
}
/**
* A cell's graphic state, normalized. Held as fields rather than as the raw
* sequence history because a terminal tracks CURRENT state, not a transcript:
* accumulating sequences made each state boundary re-emit the whole chain, so
* output that switches color without a full reset emitted O(n^2) characters
* (3200 such cells produced 25 MB and eventually a `RangeError`). It also makes
* the attribute closers every chalk-based tool writes — `39`, `49`, `22`, `23`,
* `24`, `27`, `29` — actually close their attribute instead of appending to it.
*/
interface SgrState {
fg: string
bg: string
/** Attribute parameters in force, e.g. `1` (bold) or `4` (underline). */
attrs: readonly string[]
}
/** The default state: no color, no attributes. */
const SGR_NONE: SgrState = { fg: '', bg: '', attrs: [] }
/** Attribute closers, mapped to the opener parameters each one turns off. */
const ATTR_CLOSERS: Record<string, readonly string[]> = {
22: ['1', '2'], 23: ['3'], 24: ['4'], 25: ['5', '6'], 27: ['7'], 28: ['8'], 29: ['9'],
}
/**
* Fold one SGR sequence's parameters into the state it produces.
* @param state - state in force before the sequence.
* @param params - the sequence's raw parameter string (`31`, `1;4`, `38;5;208`).
* @returns the state the sequence leaves in force.
*/
function foldSgr(state: SgrState, params: string): SgrState {
const codes = params === '' ? ['0'] : params.split(';')
let next = state
for (let index = 0; index < codes.length; index++) {
const code = String(codes[index])
if (code === '' || code === '0') { next = SGR_NONE; continue }
// Extended color: `38;5;N` / `38;2;R;G;B` and the `48` background pair
// consume their own arguments, so they are taken whole.
if (code === '38' || code === '48') {
const kind = codes[index + 1] ?? ''
const span = kind === '2' ? 4 : kind === '5' ? 2 : 0
const value = codes.slice(index, index + span + 1).join(';')
next = code === '38' ? { ...next, fg: value } : { ...next, bg: value }
index += span
continue
}
const closes = ATTR_CLOSERS[code]
if (closes !== undefined) {
next = { ...next, attrs: next.attrs.filter(attr => !closes.includes(attr)) }
continue
}
const numeric = Number(code)
if (code === '39') { next = { ...next, fg: '' }; continue }
if (code === '49') { next = { ...next, bg: '' }; continue }
if ((numeric >= 30 && numeric <= 37) || (numeric >= 90 && numeric <= 97)) { next = { ...next, fg: code }; continue }
if ((numeric >= 40 && numeric <= 47) || (numeric >= 100 && numeric <= 107)) { next = { ...next, bg: code }; continue }
if (!next.attrs.includes(code)) next = { ...next, attrs: [...next.attrs, code] }
}
return next
}
/**
* Render a state as the one canonical sequence that establishes it from the
* default, so a boundary emits a bounded string no matter how the state was
* reached.
* @param state - the state to open.
* @returns the SGR sequence, or the empty string for the default state.
*/
function openSgr(state: SgrState): string {
const codes = [...state.attrs]
if (state.fg !== '') codes.push(state.fg)
if (state.bg !== '') codes.push(state.bg)
return codes.length === 0 ? '' : `\u001b[${codes.join(';')}m`
}
/** Whether two states are the same, so a boundary is only emitted on a change. */
function sameSgr(a: SgrState, b: SgrState): boolean {
return a.fg === b.fg && a.bg === b.bg && a.attrs.length === b.attrs.length
&& a.attrs.every((attr, index) => attr === b.attrs[index])
}
/**
* Replay one line's cursor movements the way a terminal paints it, into a
* column buffer. Carriage return and backspace only MOVE the cursor — neither
* erases anything — so what a reader sees is whatever each column last had
* written to it. That distinction is the whole point of doing this as a buffer
* rather than as string surgery: `100%\rOK` shows `OK0%` because the redraw is
* shorter than the frame beneath it, and a trailing `abc\b` still shows `abc`
* because nothing ever overwrote the `c`.
*
* A CSI sequence occupies no column; it changes the state that the NEXT writes
* are stamped with, which is how a terminal stores color per cell. `red bad`
* then three backspaces then `ok` therefore shows `okd` with the `d` still red:
* `ok` overwrote two cells and the third kept the state it was written with.
* The columns are re-emitted as runs, so anser sees that same styling.
* @param line - one output line, still carrying its CSI sequences.
* @param entrySgr - SGR state in force when the line begins, since a newline
* does not reset it.
* @returns the line as the terminal would have it after every movement, plus the
* SGR state at its end for the next line to enter with.
*/
function replayLine(line: string, entrySgr: SgrState): { text: string; sgr: SgrState } {
// Same shape anser splits on, so a sequence is one unit here as well.
const csi = /\u001b\[([\u0030-\u003f]*)[\u0020-\u002f]*([\u0040-\u007e])/g
/** Per column: the state in force when it was written, and its character. */
const columns: (Cell | undefined)[] = []
let cursor = 0
// State is tracked exactly as a terminal tracks it: each cell is stamped with
// whatever was in force at the moment of the write, so a later redraw cannot
// restyle the cells it does not reach. It enters carrying the previous line's
// state, since a newline does not reset it.
let sgr = entrySgr
let at = 0
/** Clear a cell and, for a wide pair, its partner: a terminal erases both. */
const clear = (index: number, fill: string): void => {
const cell = columns[index]
if (cell?.spacer === true && index > 0) columns[index - 1] = { sgr, char: fill }
else if (cell !== undefined && isWide(cell.char) && columns[index + 1]?.spacer === true) {
columns[index + 1] = { sgr, char: fill }
}
columns[index] = { sgr, char: fill }
}
const consume = (chunk: string): void => {
for (const char of chunk) {
if (char === '\r') { cursor = 0; continue }
if (char === '\u0008') { cursor = Math.max(0, cursor - 1); continue }
if (char === '\t') {
// A tab advances to the next 8-column stop, leaving the cells it skips
// as they were — which is how a redraw can leave a tabbed column
// standing. Column alignment is the whole point of this card.
const stop = cursor + TAB_WIDTH - (cursor % TAB_WIDTH)
for (; cursor < stop; cursor++) columns[cursor] ??= { sgr, char: ' ' }
continue
}
if (ZERO_WIDTH.test(char)) {
// No column of its own: it attaches to the cell already written, so a
// redraw that covers that cell covers the mark with it. With no cell to
// attach to (line start, or straight after a redraw to column 0) a
// terminal shows nothing rather than a lone accent.
const base = cursor > 0 ? columns[cursor - 1] : undefined
if (base !== undefined) columns[cursor - 1] = { sgr: base.sgr, char: base.char + char }
continue
}
// Writing over either half of a wide pair blanks the other half, since a
// terminal cannot leave one cell of a two-cell glyph standing.
clear(cursor, ' ')
columns[cursor] = { sgr, char }
cursor++
// A wide character occupies two columns; the trailing one is a spacer,
// marked so that overwriting the lead cell leaves a blank behind instead
// of closing the gap and shifting everything after it left.
if (isWide(char)) { columns[cursor] = { sgr, char: '', spacer: true }; cursor++ }
}
}
for (const match of line.matchAll(csi)) {
consume(line.slice(at, match.index))
at = match.index + match[0].length
// Both groups are mandatory in the pattern, so destructuring types them as
// strings without a fallback that could never run.
const params = String(match[1])
const final = String(match[2])
if (final === 'K') {
// Erase in line: the fixed companion of `\r` in every spinner and progress
// bar. Without it a shorter redraw leaves the previous frame's tail
// standing, which is text the terminal never showed. `1` blanks from the
// line start THROUGH the cursor column (inclusive, per the CSI spec)
// rather than dropping those cells, since the cursor does not move and a
// later write can still land past them. Only the FIRST parameter selects
// the mode; a terminal ignores the rest (`1;2K` erases exactly as `1K`).
const mode = String(params.split(';')[0])
if (mode === '1') for (let index = 0; index <= cursor; index++) clear(index, ' ')
else columns.length = mode === '2' ? 0 : cursor
continue
}
// Only SGR carries graphic state; every other final byte is a cursor or
// erase action that must not affect a cell's style.
if (final !== 'm') continue
sgr = foldSgr(sgr, params)
}
consume(line.slice(at))
// Re-emit the columns, opening a run only where its state changes, so anser
// sees the same styling a terminal shows. Each boundary emits ONE canonical
// sequence for the state it opens, which is what keeps the output linear in
// the number of cells however the state was reached.
let out = ''
let active = entrySgr
for (let index = 0; index < columns.length; index++) {
const column = columns[index] ?? { sgr: SGR_NONE, char: ' ' }
if (!sameSgr(column.sgr, active)) {
if (!sameSgr(active, SGR_NONE)) out += '\u001b[0m'
out += openSgr(column.sgr)
active = column.sgr
}
// A spacer still holds its column. While its lead cell survives, the wide
// glyph spans both and the spacer emits nothing; once a later write replaced
// that lead, the terminal blanks the spacer instead of closing the gap, so
// emitting nothing would shift everything after it one column left.
const leadIntact = index > 0 && isWide(columns[index - 1]?.char ?? '')
out += column.spacer === true && !leadIntact ? ' ' : column.char
}
// Converge to the state the SCAN ended in, not the last written cell's: a
// sequence after the final write (the `\x1b[0m` closing a colored line) changes
// no cell yet still ends the run, and it has to reach both the DOM and the
// next line. Without this a line ending in a reset leaked its color onward.
if (!sameSgr(active, sgr)) {
if (!sameSgr(active, SGR_NONE)) out += '\u001b[0m'
out += openSgr(sgr)
}
return { text: out, sgr }
}
/** One replayed column: the state it was written with, and its character. */
interface Cell {
sgr: SgrState
char: string
/** The trailing half of a wide character's two-column pair. */
spacer?: boolean
}
/**
* Replay every line's cursor movements. A `\r` that only terminates a CRLF line
* is dropped first, so those lines keep their text instead of being redrawn onto
* themselves. SGR state threads across lines: a newline does not reset it, so a
* run opened before a redraw still colors the lines after it.
* @param text - output text, already free of OSC and non-CSI escapes.
* @returns the text with each line painted as the terminal would.
*/
function applyCursorMovements(text: string): string {
const replayed: string[] = []
let sgr = SGR_NONE
for (const raw of text.split('\n')) {
const line = raw.replace(/\r+$/, '')
if (NEEDS_REPLAY.test(line)) {
const result = replayLine(line, sgr)
replayed.push(result.text)
sgr = result.sgr
continue
}
// No cursor movement: the line needs no column buffer, and painting one
// would allocate a cell per character of output this card never redraws —
// an `ls -R` or a 5k-line log. Only its own SGR has to be folded, so a later
// line that DOES replay enters with the right state.
replayed.push(line)
for (const match of line.matchAll(SGR_SEQUENCE)) sgr = foldSgr(sgr, String(match[1]))
}
return replayed.join('\n')
}
/**
* Remove every escape sequence and control character that carries no color,
* leaving CSI sequences for anser and `\n`/`\t` for layout. Cursor movements
* (carriage return, backspace) replay first, since their effect on the visible
* text must land before the characters that expressed them are dropped.
* @param text - raw command output.
* @returns text whose only remaining escapes are CSI sequences.
*/
function sanitize(text: string): string {
const escaped = text.replace(OSC_SEQUENCE, '').replace(NON_CSI_ESCAPE, '')
return applyCursorMovements(escaped).replace(INERT_CONTROL, '')
}
/**
* Resolve one run's colors and decorations.
* @param chunk - the anser chunk to style.
* @returns the run's inline style, or undefined when it carries no SGR state.
*/
function resolveStyle(chunk: AnsiChunk): CSSProperties | undefined {
const style: CSSProperties = {}
const background = chunk.bg === null ? undefined : `rgb(${chunk.bg})`
if (background !== undefined) style.backgroundColor = background
if (chunk.fg !== null) {
const literal = `rgb(${chunk.fg})`
// A run that paints its own background keeps anser's literal pair so the
// authored foreground/background contrast survives; a foreground-only run
// maps onto a theme token, which adapts to light and dark surfaces.
style.color = background === undefined
? TOKEN_BY_BASIC_RGB[chunk.fg.replace(/\s+/g, '')] ?? literal
: literal
}
for (const decoration of chunk.decorations) Object.assign(style, STYLE_BY_DECORATION[decoration])
return Object.keys(style).length === 0 ? undefined : style
}
/**
* Parse command output into styled spans grouped by line.
* @param text - raw output text, which may contain ANSI escape sequences.
* @returns one entry per output line (always at least one, possibly empty).
*/
export function parseAnsiLines(text: string): AnsiLine[] {
let current: AnsiSpan[] = []
const lines: AnsiSpan[][] = [current]
for (const chunk of Anser.ansiToJson(sanitize(text), { json: true, remove_empty: true })) {
const style = resolveStyle(chunk)
for (const [index, part] of chunk.content.split('\n').entries()) {
if (index > 0) {
current = []
lines.push(current)
}
if (part !== '') current.push({ text: part, style })
}
}
return lines
}

View File

@@ -0,0 +1,48 @@
// Package-internal clipboard write, shared by every copy control in this
// package (CodeBlock's code copy, TerminalBlock's output copy). Not part of the
// public surface: consumers get the components, not the host detection.
/**
* Write text to the host clipboard, preferring the async Clipboard API and
* falling back to `execCommand('copy')` on hosts (jsdom, insecure contexts)
* that omit it.
* @param text - the exact text to place on the clipboard.
* @returns true only when the host accepted the write.
*/
export async function writeClipboard(text: string): Promise<boolean> {
// lib.dom types clipboard non-optional, but insecure contexts omit it —
// that runtime gap is exactly what this guard detects.
/* eslint-disable-next-line @typescript-eslint/no-unnecessary-condition */
if (navigator.clipboard?.writeText) {
try {
await navigator.clipboard.writeText(text)
return true
} catch {
// Denied permissions / iframe policy — do not claim success.
return false
}
}
// jsdom and older hosts: best-effort execCommand path when present.
// execCommand('copy') is the only clipboard fallback where the async API
// is missing; deprecated but deliberately retained.
/* eslint-disable @typescript-eslint/no-deprecated */
const exec = typeof document.execCommand === 'function'
? document.execCommand.bind(document)
: undefined
if (exec === undefined) return false
const el = document.createElement('textarea')
el.value = text
el.setAttribute('readonly', '')
el.style.position = 'fixed'
el.style.left = '-9999px'
document.body.appendChild(el)
el.select()
try {
return exec('copy')
} catch {
return false
} finally {
el.remove()
}
/* eslint-enable @typescript-eslint/no-deprecated */
}

View File

@@ -17,6 +17,8 @@ export { FishLogo } from './FishLogo.tsx'
export { BrandWordmark } from './BrandWordmark.tsx'
export { Tooltip } from './Tooltip.tsx'
export type { TooltipSide } from './Tooltip.tsx'
export { TerminalBlock, DEFAULT_TERMINAL_MAX_LINES } from './TerminalBlock.tsx'
export type { TerminalBlockProps } from './TerminalBlock.tsx'
export { CodeBlock } from './markdown/CodeBlock.tsx'
export { JsonBlock } from './markdown/JsonBlock.tsx'
export { MarkdownText } from './markdown/MarkdownText.tsx'

View File

@@ -6,6 +6,7 @@
import { useCallback, useMemo, useRef, useState } from 'react'
import clsx from 'clsx'
import { writeClipboard } from '../clipboard.ts'
import { highlightToHtml } from './highlight.ts'
import css from './CodeBlock.module.css'
@@ -18,45 +19,6 @@ export interface CodeBlockProps {
className?: string | undefined
}
/** @returns true only when the host accepted the write. */
async function writeClipboard(text: string): Promise<boolean> {
// lib.dom types clipboard non-optional, but insecure contexts omit it —
// that runtime gap is exactly what this guard detects.
/* eslint-disable-next-line @typescript-eslint/no-unnecessary-condition */
if (navigator.clipboard?.writeText) {
try {
await navigator.clipboard.writeText(text)
return true
} catch {
// Denied permissions / iframe policy — do not claim success.
return false
}
}
// jsdom and older hosts: best-effort execCommand path when present.
// execCommand('copy') is the only clipboard fallback where the async API
// is missing; deprecated but deliberately retained.
/* eslint-disable @typescript-eslint/no-deprecated */
const exec = typeof document.execCommand === 'function'
? document.execCommand.bind(document)
: undefined
if (exec === undefined) return false
const el = document.createElement('textarea')
el.value = text
el.setAttribute('readonly', '')
el.style.position = 'fixed'
el.style.left = '-9999px'
document.body.appendChild(el)
el.select()
try {
return exec('copy')
} catch {
return false
} finally {
el.remove()
}
/* eslint-enable @typescript-eslint/no-deprecated */
}
export function CodeBlock({ code, lang, className }: CodeBlockProps) {
const trimmed = code.endsWith('\n') ? code.slice(0, -1) : code
const html = useMemo(() => highlightToHtml(trimmed, lang), [trimmed, lang])

View File

@@ -0,0 +1,513 @@
// parseAnsiLines, the ANSI model behind TerminalBlock: anser's SGR runs
// resolved into inline styles and folded into per-line span arrays, with every
// escape and control character that carries no color removed first. The DOM
// side of the same model (which runs get a span wrapper) is in
// terminal-block.spec.tsx.
import { describe, expect, it } from 'vitest'
import { parseAnsiLines } from '../src/ansi.ts'
const ESC = '\u001b'
const BS = '\u0008'
/** A combining acute accent: zero-width, so it takes no terminal column. */
const ACCENT = '\u0301'
/** Paint `text` with the SGR `codes`, then reset. */
function sgr(codes: string, text: string): string {
return `${ESC}[${codes}m${text}${ESC}[0m`
}
/** The single span of a single-line, single-run parse. */
function onlySpan(text: string) {
const lines = parseAnsiLines(text)
expect(lines).toHaveLength(1)
expect(lines[0]).toHaveLength(1)
return lines[0]![0]!
}
describe('parseAnsiLines: text without SGR state', () => {
it('leaves plain text as one unstyled span', () => {
expect(parseAnsiLines('hello')).toEqual([[{ text: 'hello', style: undefined }]])
})
it('returns exactly one empty line for empty input', () => {
expect(parseAnsiLines('')).toEqual([[]])
})
it('splits a multi-line run and drops the empty line between two blocks', () => {
expect(parseAnsiLines('a\n\nb')).toEqual([
[{ text: 'a', style: undefined }],
[],
[{ text: 'b', style: undefined }],
])
})
it('keeps tabs, which the terminal surface needs for column layout', () => {
expect(onlySpan('a\tb')).toEqual({ text: 'a\tb', style: undefined })
})
})
describe('parseAnsiLines: basic colors mapped onto theme tokens', () => {
it.each<[string, string, string]>([
['30', 'black', 'var(--dsw-alias-label-primary)'],
['37', 'white', 'var(--dsw-alias-label-primary)'],
['90', 'bright black', 'var(--dsw-alias-label-tertiary)'],
['31', 'red', 'var(--dsw-alias-state-error-primary)'],
['91', 'bright red', 'var(--dsw-alias-state-error-secondary)'],
['32', 'green', 'var(--dsw-alias-state-success-primary)'],
['92', 'bright green', 'var(--dsw-alias-state-success-secondary)'],
['33', 'yellow', 'var(--dsw-alias-state-warn-primary)'],
['93', 'bright yellow', 'var(--dsw-alias-state-warn-secondary)'],
['34', 'blue', 'var(--dsw-alias-state-business-primary)'],
['94', 'bright blue', 'var(--dsw-static-blue-400)'],
])('SGR %s (%s) resolves to %s', (code, _name, token) => {
expect(onlySpan(sgr(code, 'x'))).toEqual({ text: 'x', style: { color: token } })
})
})
describe('parseAnsiLines: colors with no token equivalent', () => {
it.each<[string, string, string]>([
['35', 'magenta', 'rgb(187, 0, 187)'],
['36', 'cyan', 'rgb(0, 187, 187)'],
['38;5;208', '256-palette orange', 'rgb(255, 135, 0)'],
['38;2;10;20;30', 'truecolor', 'rgb(10, 20, 30)'],
])('SGR %s (%s) falls through to %s', (code, _name, literal) => {
expect(onlySpan(sgr(code, 'x')).style).toEqual({ color: literal })
})
})
describe('parseAnsiLines: backgrounds', () => {
it('sets backgroundColor for a background-only run', () => {
expect(onlySpan(sgr('44', 'x')).style).toEqual({ backgroundColor: 'rgb(0, 0, 187)' })
})
it('keeps the literal foreground when the run paints its own background', () => {
expect(onlySpan(sgr('41;37', 'x')).style).toEqual({
backgroundColor: 'rgb(187, 0, 0)',
color: 'rgb(255,255,255)',
})
})
it('renders reverse video as the swapped pair anser reports', () => {
expect(onlySpan(sgr('31;7', 'x')).style).toEqual({
backgroundColor: 'rgb(187, 0, 0)',
color: 'rgb(0, 0, 0)',
})
})
})
describe('parseAnsiLines: decorations', () => {
it.each<[string, string, Record<string, unknown>]>([
['1', 'bold', { fontWeight: 700 }],
['2', 'dim', { opacity: 0.7 }],
['3', 'italic', { fontStyle: 'italic' }],
['4', 'underline', { textDecoration: 'underline' }],
['9', 'strikethrough', { textDecoration: 'line-through' }],
['8', 'hidden', { visibility: 'hidden' }],
])('SGR %s (%s) resolves to %o', (code, _name, style) => {
expect(onlySpan(sgr(code, 'x')).style).toEqual(style)
})
it('lets the later textDecoration win when a run declares underline and strikethrough', () => {
expect(onlySpan(sgr('4;9', 'x')).style).toEqual({ textDecoration: 'line-through' })
expect(onlySpan(sgr('9;4', 'x')).style).toEqual({ textDecoration: 'underline' })
})
it('combines a color with several decorations in one style', () => {
expect(onlySpan(sgr('1;3;31', 'x')).style).toEqual({
color: 'var(--dsw-alias-state-error-primary)',
fontWeight: 700,
fontStyle: 'italic',
})
})
it('reproduces no animation for blink, leaving the run unstyled', () => {
expect(onlySpan(sgr('5', 'x'))).toEqual({ text: 'x', style: undefined })
})
})
describe('parseAnsiLines: sequences that carry no color', () => {
it('removes an OSC string with its BEL terminator', () => {
expect(onlySpan(`a${ESC}]0;window title\u0007b`)).toEqual({ text: 'ab', style: undefined })
})
it('removes an OSC string terminated by ST', () => {
expect(onlySpan(`a${ESC}]8;;https://example.com${ESC}\\b`)).toEqual({ text: 'ab', style: undefined })
})
it('removes non-CSI escapes such as charset selection and reset', () => {
expect(onlySpan(`x${ESC}(By${ESC}cz`)).toEqual({ text: 'xyz', style: undefined })
})
it('removes inert C0 controls', () => {
expect(onlySpan('\u0000ab\u001fc\u007f')).toEqual({ text: 'abc', style: undefined })
})
it('keeps CSI sequences that only move the cursor out of the text', () => {
expect(onlySpan(`${ESC}[2K${ESC}[1Adone`)).toEqual({ text: 'done', style: undefined })
})
})
describe('parseAnsiLines: carriage returns', () => {
it('keeps only the last redraw of a line', () => {
expect(onlySpan('10%\r55%\r100%')).toEqual({ text: '100%', style: undefined })
})
it('leaves the tail of a longer frame standing under a shorter redraw', () => {
// Verified against a real terminal: `100%\rOK` paints `OK0%`. A carriage
// return only moves the cursor, so the two columns the redraw never reaches
// still hold the frame beneath — truncating to the last `\r` would lose them.
expect(onlySpan('100%\rOK')).toEqual({ text: 'OK0%', style: undefined })
expect(onlySpan('abcdef\rXY')).toEqual({ text: 'XYcdef', style: undefined })
})
it('clamps a backspace run at the line start rather than going negative', () => {
// More backspaces than characters: the cursor stops at column 0, so the
// following write simply overwrites from there.
expect(onlySpan(`ab${BS}${BS}${BS}${BS}xyz`)).toEqual({ text: 'xyz', style: undefined })
})
it('keeps SGR state in force across a redraw, as a terminal does', () => {
// Verified against a real terminal: `\x1b[31mgone\rkept` paints `kept` RED.
// A carriage return moves the cursor; it does not reset the graphic state,
// so the redraw inherits the color the discarded frame was written with.
expect(onlySpan(`${ESC}[31mgone\rkept`))
.toEqual({ text: 'kept', style: { color: 'var(--dsw-alias-state-error-primary)' } })
})
it('preserves both lines of a CRLF pair instead of treating it as a redraw', () => {
expect(parseAnsiLines('a\r\r\nb\r\n')).toEqual([
[{ text: 'a', style: undefined }],
[{ text: 'b', style: undefined }],
[],
])
})
it('applies the redraw per line, not across the whole text', () => {
expect(parseAnsiLines('one\rtwo\nthree')).toEqual([
[{ text: 'two', style: undefined }],
[{ text: 'three', style: undefined }],
])
})
})
describe('parseAnsiLines: backspaces', () => {
it('applies a backspace as the overwrite a terminal draws', () => {
// `abc` then two backspaces then `XY` shows as `aXY`, not `abcXY`.
expect(onlySpan(`abc${BS}${BS}XY`)).toEqual({ text: 'aXY', style: undefined })
})
it('stops at the line start instead of eating the newline before it', () => {
expect(parseAnsiLines(`ab\n${BS}${BS}${BS}cd`)).toEqual([
[{ text: 'ab', style: undefined }],
[{ text: 'cd', style: undefined }],
])
})
it('treats a trailing backspace as a cursor move, not a delete', () => {
// Verified against a real terminal: `abc\b` still shows `abc`. Only a later
// write overwrites; a backspace with nothing after it erases nothing.
expect(onlySpan(`abc${BS}`)).toEqual({ text: 'abc', style: undefined })
// Same at a line boundary: the newline ends the line before any overwrite.
expect(parseAnsiLines(`abc${BS}\ndef`)).toEqual([
[{ text: 'abc', style: undefined }],
[{ text: 'def', style: undefined }],
])
})
it('steps over an SGR sequence instead of erasing its bytes', () => {
// `abc` reset then two backspaces then `XY`: erasing the reset's bytes would
// corrupt it and repaint the rest of the line with whatever the remainder
// parses as. The visible result is `aXY`, still red, with the reset intact.
expect(parseAnsiLines(`${sgr('31', 'abc')}${BS}${BS}XY`)).toEqual([[
{ text: 'a', style: { color: 'var(--dsw-alias-state-error-primary)' } },
{ text: 'XY', style: undefined },
]])
})
it('erases across a style boundary without dropping the styles between', () => {
// The backspace reaches back past the reset to the last printed character.
expect(parseAnsiLines(`${sgr('32', 'ok')}${ESC}[31m${BS}bad`)).toEqual([[
{ text: 'o', style: { color: 'var(--dsw-alias-state-success-primary)' } },
{ text: 'bad', style: { color: 'var(--dsw-alias-state-error-primary)' } },
]])
})
it('replays a redraw and a trailing backspace as pure cursor moves', () => {
// Verified against a real terminal: `old\rnew\b` shows `new`. The redraw
// repaints all three columns and the trailing backspace only moves the
// cursor left — nothing overwrites the `w`, so nothing is lost.
expect(onlySpan(`old\rnew${BS}`)).toEqual({ text: 'new', style: undefined })
})
it('overwrites only the columns the later write reaches, keeping the rest styled', () => {
// Verified against a real terminal: red `bad`, three backspaces, then `ok`
// shows `okd` — the cursor returned to column 0 and `ok` overwrote two of
// the three columns, so the untouched `d` keeps the run's red.
expect(parseAnsiLines(`${sgr('31', 'bad')}${BS}${BS}${BS}ok`)).toEqual([[
{ text: 'ok', style: undefined },
{ text: 'd', style: { color: 'var(--dsw-alias-state-error-primary)' } },
]])
})
})
describe('parseAnsiLines: erase and column arithmetic', () => {
it('erases the rest of the line, the fixed companion of a redraw', () => {
// Verified in a real terminal: `100%\r\x1b[KOK` shows `OK`. Every spinner and
// progress bar writes `\r\x1b[K`; without the erase the previous frame's tail
// stands and the card shows text the terminal never displayed.
expect(onlySpan(`100%\r${ESC}[KOK`)).toEqual({ text: 'OK', style: undefined })
// The parameterless form and `0` are the same erase.
expect(onlySpan(`100%\r${ESC}[0KOK`)).toEqual({ text: 'OK', style: undefined })
})
it('erases the whole line for the 2K form and to the cursor for 1K', () => {
expect(onlySpan(`ab\r${ESC}[2Kxy`)).toEqual({ text: 'xy', style: undefined })
// 1K clears left of the cursor without moving it, so those columns read as
// blanks — verified in a real terminal, which shows ` |` for this input.
expect(onlySpan(`abcd${ESC}[1K|`)).toEqual({ text: ' |', style: undefined })
})
it('paints columns a 2K dropped as blanks when a later write lands past them', () => {
// 2K clears the line but leaves the cursor where it was, so writing there
// leaves the columns before it unwritten — blanks, as a terminal shows.
expect(onlySpan(`abcd${ESC}[2Kx`)).toEqual({ text: ' x', style: undefined })
})
it('advances a redraw cursor by tab stops, leaving a tabbed column standing', () => {
// Verified in a real terminal: `a\tb\rXY` shows `XY b` — the `b` sits at
// column 8, which a two-character redraw cannot reach. Counting the tab as
// one column would have produced `XYb` and destroyed the alignment.
expect(onlySpan('a\tb\rXY')).toEqual({ text: 'XY b', style: undefined })
})
it('counts a wide character as the two columns a terminal advances', () => {
// `中` occupies two cells, so a two-character redraw covers exactly it.
expect(onlySpan('中x\rab')).toEqual({ text: 'abx', style: undefined })
})
it('does not accumulate a cursor or erase sequence into a cell style', () => {
// Only SGR carries graphic state. An erase folded into the style string
// would grow it per redraw and emit boundaries anser has to discard.
expect(parseAnsiLines(`${ESC}[31ma\r${ESC}[Kb`)).toEqual([[
{ text: 'b', style: { color: 'var(--dsw-alias-state-error-primary)' } },
]])
})
})
describe('parseAnsiLines: line-end state and column widths', () => {
it('closes a run whose reset lands after the last written cell', () => {
// Verified in a real terminal: `\x1b[32mdone\rok\x1b[0m` then `plain` shows
// `okne` GREEN and `plain` in the DEFAULT color. The reset changes no cell,
// so returning the last cell's state leaked green onto every later line —
// and this exact shape (`\r\x1b[K\x1b[32m✓ built\x1b[0m`) is what every
// build tool writes.
expect(parseAnsiLines(`${ESC}[32mdone\rok${ESC}[0m\nplain`)).toEqual([
[{ text: 'okne', style: { color: 'var(--dsw-alias-state-success-primary)' } }],
[{ text: 'plain', style: undefined }],
])
})
it('erases through the cursor column for 1K, not up to it', () => {
// Verified in a real terminal: `abcd\b\x1b[1K|` shows ` |` — the `d` under
// the cursor is erased too, which the CSI spec calls inclusive.
expect(onlySpan(`abcd${BS}${ESC}[1K|`)).toEqual({ text: ' |', style: undefined })
})
it('gives a combining mark no column of its own', () => {
// Verified in a real terminal: `é` (e + U+0301) then `x`, redrawn with `YZ`,
// shows `YZ`. Counting the mark as a column left the `x` standing.
expect(onlySpan('e\u0301x\rYZ')).toEqual({ text: 'YZ', style: undefined })
})
it('drops a combining mark left with no cell to attach to by a redraw', () => {
// Verified in a real terminal: `ab` then CR then U+0301 then `x` shows `xb`.
// The redraw puts the cursor at column 0, so the mark has no preceding cell
// and the terminal shows nothing for it rather than a lone accent.
expect(onlySpan(`ab\r${ACCENT}x`)).toEqual({ text: 'xb', style: undefined })
// A mark with no movement on its line never reaches the replay at all: it
// is width business, not a cursor move, so it stays as authored.
expect(onlySpan(`${ACCENT}abc`)).toEqual({ text: `${ACCENT}abc`, style: undefined })
})
it('carries a colour opened after the last write onto the next line', () => {
// The mirror of the reset case, verified in a real terminal: `ab` CR `X` then
// `\x1b[31m` with nothing after it shows `Xb` UNSTYLED and the next line red.
// The scan ends styled while the last cell is not, so the convergence has to
// open the run at the line end for it to reach the following line.
expect(parseAnsiLines(`ab\rX${ESC}[31m\nnext`)).toEqual([
[{ text: 'Xb', style: undefined }],
[{ text: 'next', style: { color: 'var(--dsw-alias-state-error-primary)' } }],
])
})
it('blanks a wide character\'s spacer once its lead cell is overwritten', () => {
// Verified in a real terminal: `中x` redrawn with `A` shows `A x` — the wide
// glyph's second cell becomes a blank rather than closing the gap, so the
// `x` keeps column 3.
expect(onlySpan('中x\rA')).toEqual({ text: 'A x', style: undefined })
// Covering both of its columns leaves no spacer behind.
expect(onlySpan('中x\rab')).toEqual({ text: 'abx', style: undefined })
})
it('replays an erase whose parameters carry a semicolon', () => {
// The replay guard has to match the same CSI shape the parser accepts, or a
// form like `\x1b[1;2K` skips the replay and its erase never happens.
expect(onlySpan(`abcd${ESC}[1;2K|`)).toEqual({ text: ' |', style: undefined })
})
})
describe('parseAnsiLines: bounded state and true widths', () => {
it('emits one canonical sequence per boundary however the state was reached', () => {
// Colors that never fully reset used to accumulate raw sequence history per
// cell, so every boundary re-emitted the whole chain: 3200 such cells
// produced 25 MB and eventually a RangeError. The state is normalized now,
// so the emitted text stays linear in the number of cells.
let input = ''
for (let index = 0; index < 2000; index += 1) input += `${ESC}[3${index % 6 + 1}mx`
const emitted = parseAnsiLines(`${input}\rz`)[0] ?? []
expect(emitted.reduce((total, span) => total + span.text.length, 0)).toBe(2000)
})
it('closes an attribute with its closer instead of appending to the state', () => {
// `1` then `22` is bold then not-bold, which every chalk-based tool writes;
// appending both left the cell bold and grew the chain.
// Verified in a real terminal: the `22` closes the bold, so the `x` written
// after the redraw is PLAIN. Appending both left it bold and grew the chain.
expect(parseAnsiLines(`${ESC}[1mbold${ESC}[22mplain\r${ESC}[Kx`)).toEqual([[
{ text: 'x', style: undefined },
]])
expect(parseAnsiLines(`${ESC}[1mA${ESC}[22mB`)).toEqual([[
{ text: 'A', style: { fontWeight: 700 } },
{ text: 'B', style: undefined },
]])
})
it('folds extended colors, backgrounds and every attribute closer', () => {
// The 256-palette and truecolor forms consume their own arguments, so the
// fold has to take them whole rather than as separate codes.
expect(parseAnsiLines(`${ESC}[38;5;208mA\r${ESC}[KB`)).toEqual([[
{ text: 'B', style: { color: 'rgb(255, 135, 0)' } },
]])
expect(parseAnsiLines(`${ESC}[38;2;10;20;30mA\r${ESC}[KB`)).toEqual([[
{ text: 'B', style: { color: 'rgb(10, 20, 30)' } },
]])
// A background survives the same way, and `49` closes it.
expect(parseAnsiLines(`${ESC}[41mA${ESC}[49mB\r${ESC}[KC`)).toEqual([[
{ text: 'C', style: undefined },
]])
// Each closer drops only its own attribute: `4` underline closed by `24`
// while the italic opened before it stays in force.
expect(parseAnsiLines(`${ESC}[3;4mA${ESC}[24mB\r${ESC}[KC`)).toEqual([[
{ text: 'C', style: { fontStyle: 'italic' } },
]])
// `39` closes a foreground without touching the background.
expect(parseAnsiLines(`${ESC}[31;42mA${ESC}[39mB\r${ESC}[KC`)).toEqual([[
{ text: 'C', style: { backgroundColor: 'rgb(0, 187, 0)' } },
]])
})
it('folds the remaining SGR shapes the model has to carry', () => {
// A 48-background in extended form, so the `48` arm and the `2`-span both run.
expect(parseAnsiLines(`${ESC}[48;2;1;2;3mA\r${ESC}[KB`)).toEqual([[
{ text: 'B', style: { backgroundColor: 'rgb(1, 2, 3)' } },
]])
// A bright foreground and a bright background, the 90-97 / 100-107 arms.
expect(parseAnsiLines(`${ESC}[91mA\r${ESC}[KB`)).toEqual([[
{ text: 'B', style: { color: 'var(--dsw-alias-state-error-secondary)' } },
]])
expect(parseAnsiLines(`${ESC}[101mA\r${ESC}[KB`)).toEqual([[
{ text: 'B', style: { backgroundColor: 'rgb(255, 85, 85)' } },
]])
// An extended form with no recognized kind byte consumes nothing extra.
expect(parseAnsiLines(`${ESC}[38mA\r${ESC}[KB`)).toEqual([[{ text: 'B', style: undefined }]])
// Re-opening an attribute already in force does not duplicate it, and a bare
// `\x1b[m` resets exactly as `\x1b[0m` does.
expect(parseAnsiLines(`${ESC}[1m${ESC}[1mA${ESC}[mB\r${ESC}[KC`)).toEqual([[
{ text: 'C', style: undefined },
]])
})
it('treats a text-presentation symbol as one column', () => {
// Verified in a real terminal: `A✓B` redrawn with `XY` shows `XYB`, so the
// check mark is ONE column. Taking the whole U+2600-U+27BF block as wide
// misaligned exactly the progress output this card exists to show.
expect(onlySpan('A\u2713B\rXY')).toEqual({ text: 'XYB', style: undefined })
// An emoji-presentation character is two, so the same redraw leaves a blank.
expect(onlySpan('A\u{1f600}B\rXY')).toEqual({ text: 'XY B', style: undefined })
})
it('clears a wide pair from either side, including through an erase', () => {
// Verified in a real terminal (`A x`): the redraw puts the cursor at column
// 0, the backspace clamps there, and writing `A` over the wide lead blanks
// its spacer rather than letting the `x` slide left.
expect(onlySpan(`\u4e2dx\r${BS}A`)).toEqual({ text: 'A x', style: undefined })
// An erase reaching the lead blanks its spacer through the same helper.
// Verified in a real terminal (` |`): 1K blanks through the cursor column,
// so the wide glyph's two cells and the `x` all become blanks.
expect(onlySpan(`\u4e2dx${ESC}[1K|`)).toEqual({ text: ' |', style: undefined })
})
it('clears the lead when the write lands on the spacer itself', () => {
// Two backspaces from after `中x` stop ON the wide glyph's second cell;
// writing there blanks the lead through the spacer side of the pair clear,
// so the glyph cannot survive as half a character.
expect(onlySpan(`中x${BS}${BS}A`)).toEqual({ text: ' Ax', style: undefined })
})
it('keeps a surviving spacer as a blank when its lead was replaced by a spacer', () => {
// `好` written over the first glyph's spacer puts its own spacer on the
// second glyph's lead cell — a write that goes down without a pair clear.
// The second glyph's spacer survives with a dead lead and must emit a
// blank, or everything after it shifts one column left.
expect(onlySpan(`中中${BS}${BS}${BS}`)).toEqual({ text: ' 好 ', style: undefined })
})
it('blanks both halves of a wide pair when either is overwritten', () => {
// A terminal cannot leave one cell of a two-cell glyph standing, so writing
// over the spacer clears the lead as well.
// Verified in a real terminal: two wide chars, CR, then `A` shows `A ` and
// the second glyph — writing the lead cell blanks its spacer, so the column
// stays occupied rather than collapsing.
expect(onlySpan('\u4e2d\u4e2d\rA')).toEqual({ text: 'A \u4e2d', style: undefined })
})
})
describe('parseAnsiLines: SGR across lines', () => {
it('carries active state past a newline, as a terminal does', () => {
// Verified in a real terminal: `\x1b[31mabc\rX\nnext` paints BOTH lines red.
// A newline does not reset the graphic state, so a replayed line must hand
// its state to the next one instead of closing it off.
expect(parseAnsiLines(`${ESC}[31mabc\rX\nnext`)).toEqual([
[{ text: 'Xbc', style: { color: 'var(--dsw-alias-state-error-primary)' } }],
[{ text: 'next', style: { color: 'var(--dsw-alias-state-error-primary)' } }],
])
})
it('tracks state through a line that needs no replay', () => {
// The middle line has no movement, so it is not replayed — but its own SGR
// still has to reach the line after it.
expect(parseAnsiLines(`a\r${ESC}[32mb\nplain\nc`)).toEqual([
[{ text: 'b', style: { color: 'var(--dsw-alias-state-success-primary)' } }],
[{ text: 'plain', style: { color: 'var(--dsw-alias-state-success-primary)' } }],
[{ text: 'c', style: { color: 'var(--dsw-alias-state-success-primary)' } }],
])
})
})
describe('parseAnsiLines: runs spanning lines', () => {
it('carries one run\'s style onto every line it covers', () => {
expect(parseAnsiLines(sgr('32', 'first\nsecond'))).toEqual([
[{ text: 'first', style: { color: 'var(--dsw-alias-state-success-primary)' } }],
[{ text: 'second', style: { color: 'var(--dsw-alias-state-success-primary)' } }],
])
})
it('keeps several runs of one line in order', () => {
expect(parseAnsiLines(`plain${sgr('31', 'red')}tail`)).toEqual([[
{ text: 'plain', style: undefined },
{ text: 'red', style: { color: 'var(--dsw-alias-state-error-primary)' } },
{ text: 'tail', style: undefined },
]])
})
})

View File

@@ -0,0 +1,430 @@
// @vitest-environment jsdom
// TerminalBlock: the prompt label's cwd shortening, the running/empty/settled
// arms, the prompt line's run-state dot, the exit-status pill, the head/tail height cap and its expand control,
// and the copy control writing the raw output on both the accepted and the
// refused clipboard paths. writeClipboard's own return contract is pinned here
// too, since it is the seam both copy controls in this package share; the
// resolution of ANSI runs into styles is pinned in ansi.spec.ts, so only its
// DOM consequence (which runs get a span wrapper) is asserted here.
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
import { DEFAULT_TERMINAL_MAX_LINES, TerminalBlock } from '../src/index.ts'
import { writeClipboard } from '../src/clipboard.ts'
const ESC = '\u001b'
afterEach(cleanup)
beforeEach(() => {
vi.useRealTimers()
})
/** The rendered output rows, one string per visible line (CSS-module class prefix). */
function outputLines(container: HTMLElement): string[] {
return [...container.querySelectorAll('[class^="_line_"]')].map(row => row.textContent ?? '')
}
/** The prompt line's run-state dot: its StateDot state plus the hidden text label beside it. */
function runStateOf(container: HTMLElement): { state: string | null; label: string | undefined } {
const dot = container.querySelector('[class*="_runState_"][data-state]')
return {
state: dot?.getAttribute('data-state') ?? null,
label: container.querySelector('[class^="_runStateLabel_"]')?.textContent ?? undefined,
}
}
/** The prompt rows as `<label><command>`, one per command line (the visual gap is CSS). */
function promptRows(container: HTMLElement): string[] {
return [...container.querySelectorAll('[class^="_promptLine_"]')].map(row => (row.textContent ?? '').trim())
}
/** `count` numbered output lines, without the terminating newline. */
function body(count: number): string {
return Array.from({ length: count }, (_value, index) => `line ${index + 1}`).join('\n')
}
describe('TerminalBlock prompt label', () => {
it('collapses the home directory itself to ~', () => {
render(<TerminalBlock command="ls" cwd="/Users/me" home="/Users/me" />)
expect(screen.getByText('~')).toBeTruthy()
})
it('shows only the last segment below home', () => {
render(<TerminalBlock command="ls" cwd="/Users/me/Documents" home="/Users/me" />)
expect(screen.getByText('Documents')).toBeTruthy()
})
it('ignores trailing separators on both the cwd and home', () => {
const view = render(<TerminalBlock command="ls" cwd="/Users/me/" home="/Users/me" />)
expect(view.getByText('~')).toBeTruthy()
view.rerender(<TerminalBlock command="ls" cwd="/Users/me" home="/Users/me/" />)
expect(view.getByText('~')).toBeTruthy()
})
it('drops trailing separators before taking the last segment', () => {
render(<TerminalBlock command="ls" cwd="/Users/me/Documents///" home="/Users/me" />)
expect(screen.getByText('Documents')).toBeTruthy()
})
it('takes the last segment when no home is known', () => {
render(<TerminalBlock command="ls" cwd="C:\\Users\\me\\Projects" />)
expect(screen.getByText('Projects')).toBeTruthy()
})
it('collapses a backslash home path to ~', () => {
render(<TerminalBlock command="ls" cwd="C:\\Users\\me" home="C:\\Users\\me" />)
expect(screen.getByText('~')).toBeTruthy()
})
it('falls back to the raw path when it has no segment', () => {
render(<TerminalBlock command="ls" cwd="/" home="/Users/me" />)
expect(screen.getByText('/')).toBeTruthy()
})
it('renders a plain $ with no cwd', () => {
render(<TerminalBlock command="ls" />)
expect(screen.getByText('$')).toBeTruthy()
})
it('renders the command verbatim after the label', () => {
render(<TerminalBlock command="git log --oneline | head -3" cwd="/Users/me/app" />)
expect(screen.getByText('git log --oneline | head -3')).toBeTruthy()
})
})
describe('TerminalBlock states', () => {
it('running shows the command line only: no output, no placeholder, no copy', () => {
const view = render(<TerminalBlock command="sleep 5" running output="partial" />)
expect(view.getByText('sleep 5')).toBeTruthy()
expect(view.queryByText('partial')).toBeNull()
expect(view.queryByText('无输出')).toBeNull()
expect(view.queryByRole('button')).toBeNull()
expect(view.container.firstElementChild?.getAttribute('data-running')).toBe('')
})
it('running still shows a settled-looking status pill when one is supplied', () => {
render(<TerminalBlock command="sleep 5" running signal="SIGINT" />)
expect(screen.getByText('信号 SIGINT')).toBeTruthy()
})
it('settled with whitespace-only output shows the dimmed placeholder', () => {
const view = render(<TerminalBlock command="true" output={' \n '} exitCode={0} />)
expect(view.getByText('无输出')).toBeTruthy()
expect(view.queryByRole('button', { name: '复制' })).toBeNull()
})
it('settled with absent output shows the placeholder', () => {
render(<TerminalBlock command="true" exitCode={0} />)
expect(screen.getByText('无输出')).toBeTruthy()
})
it('settled with an empty string shows the placeholder', () => {
render(<TerminalBlock command="true" output="" exitCode={0} />)
expect(screen.getByText('无输出')).toBeTruthy()
})
it('treats output that renders nothing visible as empty', () => {
// A lone reset, an OSC title, an erase: all survive `text.trim()` yet parse
// to nothing. Judging emptiness on the raw text drew a box of blank rows
// plus a copy control for invisible bytes, and hid the placeholder.
const view = render(<TerminalBlock command="true" output={`${ESC}[0m`} exitCode={0} />)
expect(view.getByText('无输出')).toBeTruthy()
expect(view.queryByText('复制')).toBeNull()
view.rerender(<TerminalBlock command="true" output={`${ESC}]0;title${ESC}\\`} exitCode={0} />)
expect(view.getByText('无输出')).toBeTruthy()
})
it('merges className onto the wrapper', () => {
const view = render(<TerminalBlock command="ls" className="x" output="a" />)
expect(view.container.firstElementChild?.classList.contains('x')).toBe(true)
expect(view.container.firstElementChild?.hasAttribute('data-running')).toBe(false)
})
it('drops the output text terminator instead of drawing a blank line', () => {
const view = render(<TerminalBlock command="ls" output={'a\nb\n'} />)
expect(outputLines(view.container)).toEqual(['a', 'b'])
})
it('drops the output terminator even when a reset follows the final newline', () => {
// `line\n\x1b[0m` does not end in a newline as a string, yet its last parsed
// line holds nothing visible — a common shape, since tools close their color
// after the last line. Judging the terminator on the raw text added a blank
// row and inflated both the card height and the collapse count.
const view = render(<TerminalBlock command="ls" output={`a\nb\n${ESC}[0m`} />)
expect(outputLines(view.container)).toEqual(['a', 'b'])
})
it('keeps a genuinely blank final line when the output ends with two newlines', () => {
const view = render(<TerminalBlock command="ls" output={'a\nb\n\n'} />)
expect(outputLines(view.container)).toEqual(['a', 'b', ''])
})
it('renders ANSI runs as styled spans and plain text bare', () => {
const view = render(<TerminalBlock command="ls" output={`${ESC}[31mbad${ESC}[39m ok`} />)
// Scoped to a line: the prompt line's run-state dot is a styled span too.
const span = view.container.querySelector('[class^="_line_"] span[style]')
expect(span?.textContent).toBe('bad')
expect(span?.getAttribute('style')).toContain('--dsw-alias-state-error-primary')
expect(outputLines(view.container)).toEqual(['bad ok'])
})
it('renders uncolored output with no span wrappers at all', () => {
const view = render(<TerminalBlock command="ls" output={'plain one\nplain two\n'} />)
expect(view.container.querySelectorAll('[class^="_line_"] span')).toHaveLength(0)
})
})
describe('TerminalBlock status pill', () => {
it('renders no pill for a clean exit', () => {
const view = render(<TerminalBlock command="true" output="a" exitCode={0} />)
expect(view.queryByText(/退|/u)).toBeNull()
})
it('renders no pill while the exit status is unknown', () => {
const view = render(<TerminalBlock command="ls" output="a" />)
expect(view.queryByText(/退|/u)).toBeNull()
})
it('renders the exit-code pill for a non-zero exit', () => {
render(<TerminalBlock command="false" output="a" exitCode={1} />)
expect(screen.getByText('退出码 1')).toBeTruthy()
})
it('renders the signal pill, which outranks the exit code', () => {
render(<TerminalBlock command="sleep 9" output="a" exitCode={0} signal="SIGKILL" />)
expect(screen.getByText('信号 SIGKILL')).toBeTruthy()
expect(screen.queryByText(/退/u)).toBeNull()
})
})
describe('TerminalBlock run-state dot', () => {
it('shows the running chase and its running label while the command runs', () => {
const view = render(<TerminalBlock command="sleep 5" running />)
expect(runStateOf(view.container)).toEqual({ state: 'ongoing', label: '运行中' })
})
it('shows the done dot for a clean settled exit', () => {
const view = render(<TerminalBlock command="true" output="a" exitCode={0} />)
expect(runStateOf(view.container)).toEqual({ state: 'done', label: '已完成' })
})
it('counts a settled command with no exit status as a clean settle', () => {
const view = render(<TerminalBlock command="ls" output="a" />)
expect(runStateOf(view.container)).toEqual({ state: 'done', label: '已完成' })
})
it('shows the error dot for a non-zero exit', () => {
const view = render(<TerminalBlock command="false" output="a" exitCode={1} />)
expect(runStateOf(view.container)).toEqual({ state: 'error', label: '失败' })
})
it('shows the error dot for a signal, whatever the exit code says', () => {
const view = render(<TerminalBlock command="sleep 9" output="a" exitCode={0} signal="SIGKILL" />)
expect(runStateOf(view.container)).toEqual({ state: 'error', label: '失败' })
})
// The dot precedes the prompt label, which is what makes it read as the
// state OF this command rather than of the card's chrome.
it('places the dot ahead of the prompt label and the command', () => {
const view = render(<TerminalBlock command="ls" cwd="/srv/app" output="a" />)
const row = view.container.querySelector('[class^="_promptLine_"]')
expect([...row!.children].map(node => node.textContent)).toEqual(['', 'app', 'ls'])
})
// The cwd labels the call, not each line: a `cd` in the command moves later
// lines elsewhere, so repeating the label would state a directory per line
// that the view does not know.
it('labels only the first row with the cwd, leaving later rows a bare $', () => {
const view = render(<TerminalBlock command={'cd ~\nls'} cwd="/srv/app" output="a" exitCode={0} />)
expect(promptRows(view.container)).toEqual(['appcd ~', '$ls'])
})
it('gives a multi-line command one row per line', () => {
const view = render(<TerminalBlock command={'echo one\necho two'} output="a" exitCode={0} />)
expect(promptRows(view.container)).toEqual(['$echo one', '$echo two'])
})
// A heredoc or an editor-authored command commonly ends in a newline; that
// terminator is not a further, empty command to draw a row for.
it('drops a trailing newline instead of drawing an empty final row', () => {
const view = render(<TerminalBlock command={'echo one\necho two\n'} output="a" exitCode={0} />)
expect(promptRows(view.container)).toEqual(['$echo one', '$echo two'])
})
it('keeps a genuinely blank command line when the command ends with two newlines', () => {
const view = render(<TerminalBlock command={'echo one\n\n'} output="a" exitCode={0} />)
expect(promptRows(view.container)).toEqual(['$echo one', '$'])
})
// The exit status the view carries is the whole call's — bash reports no
// per-command status — so exactly one dot and one label are correct however
// many lines the command spans. A dot per row would assert, of a line that
// succeeded inside a failing call, that the line itself failed.
it('marks the call once, on the first row, never per line', () => {
const view = render(<TerminalBlock command={'true\nfalse\ntrue'} output="x" exitCode={1} />)
expect(view.container.querySelectorAll('[class*="_runState_"][data-state]')).toHaveLength(1)
expect(view.container.querySelectorAll('[class^="_runStateLabel_"]')).toHaveLength(1)
expect(runStateOf(view.container)).toEqual({ state: 'error', label: '失败' })
const rows = view.container.querySelectorAll('[class^="_promptLine_"]')
expect(rows[0]!.querySelector('[data-state]')).not.toBeNull()
expect(rows[1]!.querySelector('[data-state]')).toBeNull()
expect(rows[2]!.querySelector('[data-state]')).toBeNull()
})
it('keeps the running dot even while a settled-looking status pill is supplied', () => {
const view = render(<TerminalBlock command="sleep 5" running signal="SIGINT" />)
expect(runStateOf(view.container)).toEqual({ state: 'ongoing', label: '运行中' })
})
})
describe('TerminalBlock height cap', () => {
it('renders every line and no expand control under the cap', () => {
const view = render(<TerminalBlock command="ls" output={body(4)} maxLines={4} />)
expect(outputLines(view.container)).toHaveLength(4)
expect(view.container.querySelector('[aria-expanded]')).toBeNull()
})
it('does not count the output terminator against the cap', () => {
const view = render(<TerminalBlock command="ls" output={`${body(4)}\n`} maxLines={4} />)
expect(outputLines(view.container)).toHaveLength(4)
expect(view.container.querySelector('[aria-expanded]')).toBeNull()
})
it('slices head and tail over the cap and expands on click', () => {
const view = render(<TerminalBlock command="ls" output={body(10)} maxLines={4} />)
// maxLines 4: head = ceil(4/2) = 2, tail = 4 - 2 = 2, 6 hidden.
expect(outputLines(view.container)).toEqual(['line 1', 'line 2', 'line 9', 'line 10'])
const toggle = view.getByRole('button', { name: '展开其余 6 行输出' })
expect(toggle.getAttribute('aria-expanded')).toBe('false')
expect(toggle.textContent).toBe('… 其余 6 行')
fireEvent.click(toggle)
expect(outputLines(view.container)).toHaveLength(10)
const collapse = view.getByRole('button', { name: '收起输出' })
expect(collapse.getAttribute('aria-expanded')).toBe('true')
expect(collapse.textContent).toBe('收起')
fireEvent.click(collapse)
expect(outputLines(view.container)).toEqual(['line 1', 'line 2', 'line 9', 'line 10'])
})
it('renders the head slice alone when the cap leaves no tail', () => {
const view = render(<TerminalBlock command="ls" output={body(5)} maxLines={1} />)
expect(outputLines(view.container)).toEqual(['line 1'])
expect(view.getByRole('button', { name: '展开其余 4 行输出' })).toBeTruthy()
})
it('caps at the documented default when maxLines is absent', () => {
const view = render(<TerminalBlock command="ls" output={body(DEFAULT_TERMINAL_MAX_LINES + 1)} />)
expect(outputLines(view.container)).toHaveLength(DEFAULT_TERMINAL_MAX_LINES)
expect(view.getByRole('button', { name: '展开其余 1 行输出' })).toBeTruthy()
})
})
describe('TerminalBlock copy', () => {
it('copies the raw output, never the prompt line or the pill', async () => {
vi.useFakeTimers()
const writeText = vi.fn().mockResolvedValue(undefined)
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } })
const output = `${ESC}[31mbad${ESC}[39m\n`
render(<TerminalBlock command="make" cwd="/Users/me/app" output={output} exitCode={2} />)
fireEvent.click(screen.getByRole('button', { name: '复制' }))
// Escape codes, the newline terminator, and nothing of the chrome around them.
expect(writeText).toHaveBeenCalledWith(output)
await act(async () => {
await Promise.resolve()
})
expect(screen.getByRole('button', { name: '复制成功' })).toBeTruthy()
// While the ok label is showing, further clicks are no-ops.
fireEvent.click(screen.getByRole('button', { name: '复制成功' }))
expect(writeText).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(1000)
expect(screen.getByRole('button', { name: '复制' })).toBeTruthy()
})
it('copies the whole output while the height cap hides its middle', async () => {
const writeText = vi.fn().mockResolvedValue(undefined)
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } })
const output = `${body(10)}\n`
render(<TerminalBlock command="ls" output={output} maxLines={4} exitCode={0} />)
fireEvent.click(screen.getByRole('button', { name: '复制' }))
expect(writeText).toHaveBeenCalledWith(output)
expect(await screen.findByRole('button', { name: '复制成功' })).toBeTruthy()
})
it('does not claim success when the host refuses the write', async () => {
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: { writeText: vi.fn().mockRejectedValue(new Error('denied')) },
})
render(<TerminalBlock command="ls" output="a" />)
fireEvent.click(screen.getByRole('button', { name: '复制' }))
await act(async () => {
await Promise.resolve()
})
expect(screen.getByRole('button', { name: '复制' })).toBeTruthy()
expect(screen.queryByRole('button', { name: '复制成功' })).toBeNull()
})
})
describe('writeClipboard', () => {
it('reports true after the async Clipboard API accepts the exact text', async () => {
const writeText = vi.fn().mockResolvedValue(undefined)
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } })
await expect(writeClipboard('payload')).resolves.toBe(true)
expect(writeText).toHaveBeenCalledWith('payload')
})
it('reports false when the Clipboard API rejects', async () => {
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: { writeText: vi.fn().mockRejectedValue(new Error('denied')) },
})
await expect(writeClipboard('payload')).resolves.toBe(false)
})
it('selects a detached textarea for the execCommand fallback and removes it after', async () => {
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: undefined })
let selected: string | undefined
const exec = vi.fn(() => {
selected = document.querySelector<HTMLTextAreaElement>('textarea[readonly]')?.value
return true
})
Object.defineProperty(document, 'execCommand', { configurable: true, value: exec })
await expect(writeClipboard('payload')).resolves.toBe(true)
expect(exec).toHaveBeenCalledWith('copy')
expect(selected).toBe('payload')
expect(document.querySelector('textarea')).toBeNull()
})
it('reports execCommand\'s own refusal verbatim', async () => {
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: undefined })
Object.defineProperty(document, 'execCommand', { configurable: true, value: vi.fn(() => false) })
await expect(writeClipboard('payload')).resolves.toBe(false)
})
it('reports false and still removes the textarea when execCommand throws', async () => {
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: undefined })
Object.defineProperty(document, 'execCommand', {
configurable: true,
value: () => {
throw new Error('denied')
},
})
await expect(writeClipboard('payload')).resolves.toBe(false)
expect(document.querySelector('textarea')).toBeNull()
})
it('reports false on a host with neither clipboard path', async () => {
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: undefined })
Object.defineProperty(document, 'execCommand', { configurable: true, value: undefined })
await expect(writeClipboard('payload')).resolves.toBe(false)
})
it('reports false when navigator.clipboard exists without writeText', async () => {
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: {} })
Object.defineProperty(document, 'execCommand', { configurable: true, value: undefined })
await expect(writeClipboard('payload')).resolves.toBe(false)
})
})