fix(ui): keep theme text and selections readable (#6226)
* fix(ui): keep theme text and selections readable * fix(tui): theme the blank composer cursor cell * refactor(webui): centralize diff theme colors * fix(tui): keep conversation selections readable * fix(ui): preserve nested syntax colors and selection lifetimes
This commit is contained in:
1 parent
73c2441abc
commit
c24153db86
32 files changed
+451
-165
No files matched your search
@@ -90,6 +90,7 @@ import {
|
||||
} from "../views/footer-hints"
|
||||
import { copyWithSystemClipboard } from "../platform/clipboard"
|
||||
import { configureOpenTuiEnvironment, createTuiHost, type TuiHost } from "../platform/host"
|
||||
import { applySelectionColors } from "../platform/selection"
|
||||
import { LOCAL_COMMANDS } from "./commands"
|
||||
import { CooperativeEventQueue } from "./event-queue"
|
||||
import {
|
||||
@@ -404,6 +405,10 @@ export class NanobotTui {
|
||||
this.status = layout.status
|
||||
this.meta = layout.meta
|
||||
this.renderer.root.add(this.shell)
|
||||
this.shell.renderBefore = () => {
|
||||
const selection = this.renderer.getSelection()
|
||||
if (selection) applySelectionColors(selection, this.palette.selection)
|
||||
}
|
||||
|
||||
this.renderer.keyInput.on("keypress", this.handleKey)
|
||||
this.renderer.on(CliRenderEvents.THEME_MODE, this.handleTheme)
|
||||
@@ -1729,6 +1734,8 @@ export class NanobotTui {
|
||||
this.composerFrame.borderColor = this.palette.accent
|
||||
this.composer.backgroundColor = surface
|
||||
this.composer.focusedBackgroundColor = surface
|
||||
this.composer.selectionBg = this.palette.selection.background
|
||||
this.composer.selectionFg = this.palette.selection.foreground
|
||||
this.composer.placeholderColor = this.palette.muted
|
||||
}
|
||||
|
||||
|
||||
+121
-8
@@ -1,5 +1,5 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test"
|
||||
import { BoxRenderable, CliRenderEvents, StyledText, TextareaRenderable, TextAttributes, TextRenderable } from "@opentui/core"
|
||||
import { BoxRenderable, CliRenderEvents, StyledText, TextareaRenderable, TextAttributes, TextRenderable, rgbToHex } from "@opentui/core"
|
||||
import { MockTreeSitterClient, TestRecorder, setRendererCapabilities, createTestRenderer, type TestRendererSetup } from "@opentui/core/testing"
|
||||
import { NanobotTui } from "./app"
|
||||
import type { Transcript } from "../rendering/transcript"
|
||||
@@ -515,7 +515,7 @@ describe("NanobotTui layout and themes", () => {
|
||||
expect(internals.composerFrame.borderColor.toInts().slice(0, 3)).toEqual([185, 77, 11])
|
||||
expect(internals.composerFrame.backgroundColor.toInts().slice(0, 3)).toEqual([240, 240, 240])
|
||||
expect(internals.composer.backgroundColor.toInts().slice(0, 3)).toEqual([240, 240, 240])
|
||||
expect(internals.composer.placeholderColor.toInts().slice(0, 3)).toEqual([111, 111, 120])
|
||||
expect(internals.composer.placeholderColor.toInts().slice(0, 3)).toEqual([98, 98, 107])
|
||||
|
||||
app.accept({ event: "attached", chat_id: "chat" })
|
||||
await waitUntil(() => internals.ready)
|
||||
@@ -528,6 +528,118 @@ describe("NanobotTui layout and themes", () => {
|
||||
expect(composerLine).not.toContain("┐")
|
||||
})
|
||||
|
||||
test.each(["light", "dark", "auto"] as const)(
|
||||
"keeps the %s composer cursor cell readable at the end of input",
|
||||
async (theme) => {
|
||||
setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })
|
||||
const app = NanobotTui.mount(
|
||||
setup.renderer,
|
||||
{ ...options, theme },
|
||||
client(),
|
||||
new MockTreeSitterClient({ autoResolveTimeout: 0 }),
|
||||
)
|
||||
const ui = app as unknown as { ready: boolean; composer: TextareaRenderable }
|
||||
app.accept({ event: "attached", chat_id: "chat" })
|
||||
await waitUntil(() => ui.ready)
|
||||
await setup.mockInput.pressKeys([..."Draft 中文🙂"])
|
||||
|
||||
const expectCursorCell = async () => {
|
||||
await setup!.flush()
|
||||
const cursor = setup!.renderer.getCursorState()
|
||||
const spans = setup!.captureSpans().lines[cursor.y - 1]!.spans
|
||||
let column = 1
|
||||
const cell = spans.find((span) => {
|
||||
const containsCursor = column <= cursor.x && cursor.x < column + span.width
|
||||
column += span.width
|
||||
return containsCursor
|
||||
})!
|
||||
expect(cursor.visible).toBe(true)
|
||||
const buffer = setup!.renderer.currentRenderBuffer
|
||||
expect(buffer.buffers.char[(cursor.y - 1) * buffer.width + cursor.x - 1]).toBe(32)
|
||||
expect(cell.fg.equals(ui.composer.textColor)).toBe(true)
|
||||
expect(cell.bg.equals(ui.composer.backgroundColor)).toBe(true)
|
||||
}
|
||||
|
||||
await expectCursorCell()
|
||||
setup.mockInput.pressKey("HOME")
|
||||
setup.mockInput.pressKey("END")
|
||||
await expectCursorCell()
|
||||
setup.mockInput.pressArrow("left")
|
||||
setup.mockInput.pressArrow("right")
|
||||
await expectCursorCell()
|
||||
setup.mockInput.pressBackspace()
|
||||
await expectCursorCell()
|
||||
expect(ui.composer.plainText).toBe("Draft 中文")
|
||||
setup.resize(18, 20)
|
||||
await expectCursorCell()
|
||||
},
|
||||
)
|
||||
|
||||
test.each(["light", "dark", "auto"] as const)(
|
||||
"keeps %s conversation selections readable across Markdown blocks",
|
||||
async (theme) => {
|
||||
setup = await createRenderer({ width: 96, height: 48, screenMode: "alternate-screen" })
|
||||
const app = NanobotTui.mount(
|
||||
setup.renderer,
|
||||
{ ...options, theme },
|
||||
client(),
|
||||
new MockTreeSitterClient({ autoResolveTimeout: 0 }),
|
||||
)
|
||||
const ui = app as unknown as { transcript: Transcript; composer: TextareaRenderable }
|
||||
ui.transcript.user("User selection text")
|
||||
ui.transcript.assistant([
|
||||
"Normal selection text",
|
||||
"**Bold selection text**",
|
||||
"- List selection text",
|
||||
"```text\nCode selection text\n```",
|
||||
"| Heading |\n| --- |\n| Table selection text |",
|
||||
].join("\n\n"))
|
||||
await setup.flush()
|
||||
|
||||
for (const text of [
|
||||
"User selection text", "Normal selection text", "Bold selection text",
|
||||
"List selection text", "Code selection text", "Table selection text",
|
||||
]) {
|
||||
setup.renderer.clearSelection()
|
||||
await setup.flush()
|
||||
const lines = setup.captureCharFrame().split("\n")
|
||||
const y = lines.findIndex((line) => line.includes(text))
|
||||
const x = lines[y]!.indexOf(text)
|
||||
await setup.mockMouse.drag(x, y, x + text.length, y)
|
||||
await setup.flush()
|
||||
expect(setup.renderer.getSelection()?.getSelectedText()).toContain(text)
|
||||
const selected = setup.captureSpans().lines[y]!.spans.find((span) => span.text.includes(text))!
|
||||
expect(selected.fg.intent).toBe("rgb")
|
||||
expect(selected.bg.intent).toBe("rgb")
|
||||
expect(contrastRatio(rgbToHex(selected.fg), rgbToHex(selected.bg))).toBeGreaterThanOrEqual(4.5)
|
||||
}
|
||||
|
||||
if (theme === "auto") {
|
||||
for (const mode of ["light", "dark"] as const) {
|
||||
setup.renderer.emit(CliRenderEvents.THEME_MODE, mode)
|
||||
await setup.flush()
|
||||
expect(setup.renderer.getSelection()?.getSelectedText()).toContain("Table selection text")
|
||||
const selected = setup.captureSpans().lines.flatMap((line) => line.spans)
|
||||
.find((span) => span.text.includes("Table selection text"))!
|
||||
expect(selected.fg.intent).toBe("rgb")
|
||||
expect(selected.bg.intent).toBe("rgb")
|
||||
expect(contrastRatio(rgbToHex(selected.fg), rgbToHex(selected.bg))).toBeGreaterThanOrEqual(4.5)
|
||||
}
|
||||
}
|
||||
|
||||
setup.renderer.clearSelection()
|
||||
await setup.mockInput.typeText("Composer selection text")
|
||||
setup.mockInput.pressKey("HOME", { shift: true })
|
||||
await setup.flush()
|
||||
expect(ui.composer.getSelectedText()).toBe("Composer selection text")
|
||||
const selected = setup.captureSpans().lines.flatMap((line) => line.spans)
|
||||
.find((span) => span.text.includes("Composer selection text"))!
|
||||
expect(selected.fg.intent).toBe("rgb")
|
||||
expect(selected.bg.intent).toBe("rgb")
|
||||
expect(contrastRatio(rgbToHex(selected.fg), rgbToHex(selected.bg))).toBeGreaterThanOrEqual(4.5)
|
||||
},
|
||||
)
|
||||
|
||||
test("uses asymmetric roles instead of chat bubbles", async () => {
|
||||
setup = await createRenderer({ width: 72, height: 24, screenMode: "alternate-screen" })
|
||||
const app = NanobotTui.mount(
|
||||
@@ -750,11 +862,12 @@ describe("NanobotTui layout and themes", () => {
|
||||
const internals = app as unknown as {
|
||||
palette: Record<string, string> & { referenceBackground: string; faint: string }
|
||||
}
|
||||
const assertContrast = () => {
|
||||
for (const tone of ["text", "muted", "accent", "link", "success", "error", "user", "warm", "cool"]) {
|
||||
expect(contrastRatio(internals.palette[tone] ?? "", internals.palette.referenceBackground)).toBeGreaterThanOrEqual(4.5)
|
||||
const assertContrast = (backgrounds: string[]) => {
|
||||
for (const background of backgrounds) {
|
||||
for (const tone of ["text", "muted", "faint", "accent", "link", "success", "error", "user", "warm", "cool"]) {
|
||||
expect(contrastRatio(internals.palette[tone] ?? "", background)).toBeGreaterThanOrEqual(4.5)
|
||||
}
|
||||
}
|
||||
expect(contrastRatio(internals.palette.faint, internals.palette.referenceBackground)).toBeGreaterThanOrEqual(3)
|
||||
const turnContrast = contrastRatio(
|
||||
internals.palette.userBackground ?? "",
|
||||
internals.palette.referenceBackground,
|
||||
@@ -764,11 +877,11 @@ describe("NanobotTui layout and themes", () => {
|
||||
}
|
||||
|
||||
setup.renderer.emit(CliRenderEvents.THEME_MODE, "dark")
|
||||
assertContrast()
|
||||
assertContrast([internals.palette.referenceBackground, "#282C34", "#282A36", "#282828", "#002B36"])
|
||||
expect(internals.palette.accent).toBe("#EF8E30")
|
||||
expect(internals.palette.user).toBe("#EF8E30")
|
||||
setup.renderer.emit(CliRenderEvents.THEME_MODE, "light")
|
||||
assertContrast()
|
||||
assertContrast([internals.palette.referenceBackground, "#FDF6E3"])
|
||||
expect(internals.palette.accent).toBe("#B94D0B")
|
||||
expect(internals.palette.user).toBe("#B94D0B")
|
||||
})
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import {
|
||||
BoxRenderable,
|
||||
RGBA,
|
||||
TextareaRenderable,
|
||||
TextRenderable,
|
||||
type CliRenderer,
|
||||
type PasteEvent,
|
||||
@@ -9,6 +8,7 @@ import {
|
||||
} from "@opentui/core"
|
||||
|
||||
import type { QueuePreview } from "../composer/queue-preview"
|
||||
import { ComposerTextarea } from "../composer/textarea"
|
||||
import type { BranchMenu } from "../menus/branch-menu"
|
||||
import type { CommandMenu } from "../menus/command-menu"
|
||||
import type { MentionMenu } from "../menus/mention-menu"
|
||||
@@ -57,7 +57,7 @@ export interface AppLayout {
|
||||
shell: BoxRenderable
|
||||
title: BoxRenderable
|
||||
composerFrame: BoxRenderable
|
||||
composer: TextareaRenderable
|
||||
composer: ComposerTextarea
|
||||
status: TextRenderable
|
||||
meta: TextRenderable
|
||||
}
|
||||
@@ -116,7 +116,7 @@ export function createAppLayout(
|
||||
paddingRight: 1,
|
||||
backgroundColor: composerSurface,
|
||||
})
|
||||
const composer = new TextareaRenderable(renderer, {
|
||||
const composer = new ComposerTextarea(renderer, {
|
||||
id: "nanobot-tui-composer",
|
||||
width: "100%",
|
||||
minHeight: 1,
|
||||
@@ -128,10 +128,10 @@ export function createAppLayout(
|
||||
focusedTextColor: palette.text,
|
||||
backgroundColor: composerSurface,
|
||||
focusedBackgroundColor: composerSurface,
|
||||
selectionBg: palette.selection.background,
|
||||
selectionFg: palette.selection.foreground,
|
||||
cursorColor: palette.accent,
|
||||
syntaxStyle: composerSyntax,
|
||||
// A steady line cursor avoids the block-cell trails produced by some
|
||||
// terminals when a retained full-screen UI redraws around the composer.
|
||||
cursorStyle: { style: "line", blinking: false },
|
||||
showCursor: true,
|
||||
keyBindings: [
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test"
|
||||
import { CliRenderEvents, TextareaRenderable, TextRenderable } from "@opentui/core"
|
||||
import { CliRenderEvents, TextareaRenderable, TextRenderable, rgbToHex } from "@opentui/core"
|
||||
import { MockTreeSitterClient, createTestRenderer, type TestRendererSetup } from "@opentui/core/testing"
|
||||
import { NanobotTui } from "./app"
|
||||
import type { RecoveryState, SlashCommand, WorkspaceScopePayload } from "../client"
|
||||
import { options, client, mount, waitUntil, occurrences } from "./test-support"
|
||||
import { options, client, mount, waitUntil, occurrences, contrastRatio } from "./test-support"
|
||||
|
||||
describe("NanobotTui session navigation", () => {
|
||||
let setup: TestRendererSetup | undefined
|
||||
@@ -907,7 +907,7 @@ describe("NanobotTui session navigation", () => {
|
||||
})
|
||||
|
||||
test("opens the latest turn diff as a full-screen, navigable view", async () => {
|
||||
setup = await createRenderer({ width: 96, height: 28, screenMode: "alternate-screen" })
|
||||
setup = await createRenderer({ width: 96, height: 28, screenMode: "alternate-screen", consoleMode: "disabled" })
|
||||
const app = mount(setup)
|
||||
app.accept({ event: "attached", chat_id: "chat" })
|
||||
await waitUntil(() => (app as unknown as { ready: boolean }).ready)
|
||||
@@ -972,6 +972,23 @@ describe("NanobotTui session navigation", () => {
|
||||
expect(frame).toContain("Diff truncated by the gateway")
|
||||
expect(frame).not.toContain("Ask nanobot anything")
|
||||
|
||||
const rows = frame.split("\n")
|
||||
const y = rows.findIndex((row) => row.includes("const newValue = 2"))
|
||||
const x = rows[y]!.indexOf("const newValue = 2")
|
||||
await setup.mockMouse.drag(x, y, x + "const newValue = 2".length, y)
|
||||
await setup.flush()
|
||||
expect(setup.renderer.getSelection()?.getSelectedText()).toBe("const newValue = 2")
|
||||
const selected = setup.captureSpans().lines[y]!.spans.find((span) => span.text.includes("const newValue = 2"))!
|
||||
expect(selected.fg.intent).toBe("rgb")
|
||||
expect(selected.bg.intent).toBe("rgb")
|
||||
expect(contrastRatio(rgbToHex(selected.fg), rgbToHex(selected.bg))).toBeGreaterThanOrEqual(4.5)
|
||||
|
||||
setup.renderer.emit(CliRenderEvents.THEME_MODE, "light")
|
||||
await setup.flush()
|
||||
expect(setup.renderer.console.visible).toBe(false)
|
||||
expect(setup.captureCharFrame()).toContain("const newValue = 2")
|
||||
setup.renderer.clearSelection()
|
||||
|
||||
setup.mockInput.pressArrow("right")
|
||||
await setup.flush()
|
||||
frame = setup.captureCharFrame()
|
||||
|
||||
+12
-5
@@ -16,6 +16,7 @@ import type { DiffViewerTheme } from "../views/diff-viewer"
|
||||
import type { FooterHintTheme } from "../views/footer-hints"
|
||||
import type { RecoveryNoticeTheme } from "../views/recovery-notice"
|
||||
import type { UsagePanelTheme } from "../views/usage-panel"
|
||||
import type { SelectionColors } from "../platform/selection"
|
||||
|
||||
export const IMAGE_PLACEHOLDER_STYLE = "image.placeholder"
|
||||
export const SHIMMER_INTERVAL_MS = 80
|
||||
@@ -38,13 +39,14 @@ export interface Palette {
|
||||
userBackground: ColorInput
|
||||
warm: ColorInput
|
||||
cool: ColorInput
|
||||
selection: SelectionColors
|
||||
}
|
||||
|
||||
export const DARK: Palette = {
|
||||
referenceBackground: "#0E0F11",
|
||||
text: "#ECEDEE",
|
||||
muted: "#A1A1AA",
|
||||
faint: "#71717A",
|
||||
faint: "#A1A1AA",
|
||||
border: "#3F3F46",
|
||||
accent: "#EF8E30",
|
||||
link: "#60A5FA",
|
||||
@@ -54,15 +56,16 @@ export const DARK: Palette = {
|
||||
user: "#EF8E30",
|
||||
// Codex-style turn anchor: 12% white over the reference dark background.
|
||||
userBackground: "#2B2C2E",
|
||||
warm: "#C26A25",
|
||||
cool: "#1795A2",
|
||||
warm: "#E9965A",
|
||||
cool: "#36B8C7",
|
||||
selection: { background: RGBA.fromHex("#3F3F46"), foreground: RGBA.fromHex("#ECEDEE") },
|
||||
}
|
||||
|
||||
export const LIGHT: Palette = {
|
||||
referenceBackground: "#FAFAFA",
|
||||
text: "#18181B",
|
||||
muted: "#6F6F78",
|
||||
faint: "#8A8A94",
|
||||
muted: "#62626B",
|
||||
faint: "#62626B",
|
||||
border: "#D4D4D8",
|
||||
accent: "#B94D0B",
|
||||
link: "#1D4ED8",
|
||||
@@ -74,6 +77,7 @@ export const LIGHT: Palette = {
|
||||
userBackground: "#F0F0F0",
|
||||
warm: "#C2410C",
|
||||
cool: "#0F766E",
|
||||
selection: { background: RGBA.fromHex("#D4D4D8"), foreground: RGBA.fromHex("#18181B") },
|
||||
}
|
||||
|
||||
// Until the terminal answers OSC 10/11, its default foreground is the only
|
||||
@@ -93,6 +97,7 @@ export const TERMINAL: Palette = {
|
||||
userBackground: RGBA.defaultBackground(),
|
||||
warm: RGBA.defaultForeground(),
|
||||
cool: RGBA.defaultForeground(),
|
||||
selection: { background: RGBA.fromHex("#93C5FD"), foreground: RGBA.fromHex("#18181B") },
|
||||
}
|
||||
|
||||
|
||||
@@ -182,6 +187,8 @@ export function diffViewerTheme(palette: Palette, backgroundKnown: boolean): Dif
|
||||
error: palette.error,
|
||||
addedBackground: backgroundKnown ? light ? "#E7F6EC" : "#142D22" : null,
|
||||
removedBackground: backgroundKnown ? light ? "#FCE8EA" : "#352024" : null,
|
||||
selectionBackground: palette.selection.background,
|
||||
selectionForeground: palette.selection.foreground,
|
||||
syntax: syntaxStyle(palette),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { TextareaRenderable, type OptimizedBuffer } from "@opentui/core"
|
||||
|
||||
export class ComposerTextarea extends TextareaRenderable {
|
||||
override renderCursor(buffer: OptimizedBuffer): void {
|
||||
if (this.focused && this.showCursor) {
|
||||
const { visualCol, visualRow } = this.visualCursor
|
||||
const x = this.x + visualCol
|
||||
const y = this.y + visualRow
|
||||
if (x >= 0 && x < buffer.width && y >= 0 && y < buffer.height) {
|
||||
const index = y * buffer.width + x
|
||||
const { char, fg } = buffer.buffers
|
||||
// OpenTUI clears unused editor cells with a white foreground. Hosts
|
||||
// that draw a cursor by reversing the cell use that color as its fill.
|
||||
if (char[index] === 32) fg.set(this.textColor.buffer, index * 4)
|
||||
}
|
||||
}
|
||||
super.renderCursor(buffer)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import {
|
||||
EditBufferRenderable,
|
||||
TextBufferRenderable,
|
||||
TextTableRenderable,
|
||||
type RGBA,
|
||||
type Selection,
|
||||
} from "@opentui/core"
|
||||
|
||||
export interface SelectionColors {
|
||||
background: RGBA
|
||||
foreground: RGBA
|
||||
}
|
||||
|
||||
export function applySelectionColors(selection: Selection, colors: SelectionColors): void {
|
||||
for (const renderable of selection.selectedRenderables) {
|
||||
if (renderable.isDestroyed) continue
|
||||
if (renderable instanceof TextBufferRenderable || renderable instanceof EditBufferRenderable) {
|
||||
renderable.selectionBg = colors.background
|
||||
renderable.selectionFg = colors.foreground
|
||||
} else if (renderable instanceof TextTableRenderable) {
|
||||
// OpenTUI 0.5.11 exposes table selection colors only at construction.
|
||||
// Update its retained palette without replacing streaming table cells.
|
||||
const table = renderable as unknown as { _selectionBg?: RGBA; _selectionFg?: RGBA }
|
||||
if (table._selectionBg === colors.background && table._selectionFg === colors.foreground) continue
|
||||
table._selectionBg = colors.background
|
||||
table._selectionFg = colors.foreground
|
||||
renderable.onSelectionChanged(selection)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,8 @@ export interface DiffViewerTheme {
|
||||
error: ColorInput
|
||||
addedBackground: ColorInput | null
|
||||
removedBackground: ColorInput | null
|
||||
selectionBackground: ColorInput
|
||||
selectionForeground: ColorInput
|
||||
syntax: SyntaxStyle
|
||||
}
|
||||
|
||||
@@ -295,8 +297,8 @@ export class DiffViewer {
|
||||
removedLineNumberBg: this.theme.removedBackground || RGBA.defaultBackground(),
|
||||
addedSignColor: this.theme.success,
|
||||
removedSignColor: this.theme.error,
|
||||
selectionBg: this.theme.border,
|
||||
selectionFg: this.theme.text,
|
||||
selectionBg: this.theme.selectionBackground,
|
||||
selectionFg: this.theme.selectionForeground,
|
||||
}))
|
||||
if (edit.diff?.truncated) {
|
||||
this.scroll.add(this.text("… Diff truncated by the gateway; line counts may be larger.", "accent"))
|
||||
|
||||
@@ -179,7 +179,6 @@ function CliAppMentionToken({
|
||||
isHero?: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const color = app.brand_color || INLINE_TOKEN_HIGHLIGHT_COLOR;
|
||||
const displayName = app.display_name?.trim() || app.name;
|
||||
const mentionName = variant === "message"
|
||||
? displayName
|
||||
@@ -195,7 +194,6 @@ function CliAppMentionToken({
|
||||
title={t("thread.composer.mentions.cliTitle", {
|
||||
name: variant === "message" ? `${displayName} (${label})` : displayName,
|
||||
})}
|
||||
color={color}
|
||||
className={variant === "composer" ? "font-normal" : "inline-flex max-w-full items-baseline [overflow-wrap:anywhere]"}
|
||||
>
|
||||
<span
|
||||
@@ -250,7 +248,6 @@ function McpPresetMentionToken({
|
||||
isHero?: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const color = preset.brand_color || INLINE_TOKEN_HIGHLIGHT_COLOR;
|
||||
const displayName = preset.display_name?.trim() || preset.name;
|
||||
const mentionName = variant === "message"
|
||||
? displayName
|
||||
@@ -266,7 +263,6 @@ function McpPresetMentionToken({
|
||||
title={t("thread.composer.mentions.mcpTitle", {
|
||||
name: variant === "message" ? `${displayName} (${label})` : displayName,
|
||||
})}
|
||||
color={color}
|
||||
className={variant === "composer" ? "font-normal" : "inline-flex max-w-full items-baseline [overflow-wrap:anywhere]"}
|
||||
>
|
||||
<span
|
||||
|
||||
@@ -22,7 +22,6 @@ interface CodeBlockProps {
|
||||
interface HighlightedCodeProps {
|
||||
language?: string;
|
||||
code: string;
|
||||
isDark: boolean;
|
||||
chrome: "default" | "none";
|
||||
showLineNumbers: boolean;
|
||||
wrapLongLines: boolean;
|
||||
@@ -46,13 +45,9 @@ const ANSI_LANGUAGES = new Set(["ansi", "ansi-output"]);
|
||||
const LazyHighlightedCode = lazy(async () => {
|
||||
const [
|
||||
{ default: SyntaxHighlighter },
|
||||
{ default: oneDark },
|
||||
{ default: oneLight },
|
||||
{ ViewportCodeRows },
|
||||
] = await Promise.all([
|
||||
import("react-syntax-highlighter/dist/esm/prism-async-light"),
|
||||
import("react-syntax-highlighter/dist/esm/styles/prism/one-dark"),
|
||||
import("react-syntax-highlighter/dist/esm/styles/prism/one-light"),
|
||||
import("@/components/ViewportCodeRows"),
|
||||
]);
|
||||
|
||||
@@ -60,29 +55,16 @@ const LazyHighlightedCode = lazy(async () => {
|
||||
default({
|
||||
language,
|
||||
code,
|
||||
isDark,
|
||||
chrome,
|
||||
showLineNumbers,
|
||||
wrapLongLines,
|
||||
viewportHighlight,
|
||||
}: HighlightedCodeProps) {
|
||||
const theme = isDark ? oneDark : oneLight;
|
||||
const transparentTheme = chrome === "none" ? {
|
||||
...theme,
|
||||
'pre[class*="language-"]': {
|
||||
...theme['pre[class*="language-"]'],
|
||||
background: "transparent",
|
||||
},
|
||||
'code[class*="language-"]': {
|
||||
...theme['code[class*="language-"]'],
|
||||
background: "transparent",
|
||||
},
|
||||
} : theme;
|
||||
|
||||
return (
|
||||
<SyntaxHighlighter
|
||||
language={language || "text"}
|
||||
style={transparentTheme}
|
||||
useInlineStyles={false}
|
||||
style={{}}
|
||||
customStyle={{
|
||||
background: "transparent",
|
||||
margin: 0,
|
||||
@@ -105,7 +87,7 @@ const LazyHighlightedCode = lazy(async () => {
|
||||
lineNumberStyle={{
|
||||
minWidth: "2.6em",
|
||||
paddingRight: "1.15rem",
|
||||
color: isDark ? "rgba(212, 212, 216, 0.45)" : "rgba(63, 63, 70, 0.68)",
|
||||
color: "var(--code-comment)",
|
||||
fontFamily: CODE_FONT_STACK,
|
||||
userSelect: "none",
|
||||
}}
|
||||
@@ -125,8 +107,8 @@ function renderPlainText(value: string): ReactNode {
|
||||
return value;
|
||||
}
|
||||
|
||||
function renderAnsiText(value: string): ReactNode {
|
||||
return parseAnsiSegments(value).map((segment, index) => (
|
||||
function renderAnsiText(value: string, theme: "light" | "dark"): ReactNode {
|
||||
return parseAnsiSegments(value, theme).map((segment, index) => (
|
||||
<span key={index} style={segment.style}>
|
||||
{segment.text}
|
||||
</span>
|
||||
@@ -168,14 +150,14 @@ function CodeTextBlock({
|
||||
<code className="text-inherit">
|
||||
{showLineNumbers && compact ? (
|
||||
<span className="flex min-w-max">
|
||||
<span aria-hidden className="shrink-0 select-none pr-[1.15rem] text-right text-muted-foreground/60"
|
||||
<span aria-hidden className="shrink-0 select-none pr-[1.15rem] text-right text-muted-foreground"
|
||||
style={{ minWidth: "4.25em" }}>{lines.map((_, index) => index + 1).join("\n")}</span>
|
||||
<span>{renderText(code)}</span>
|
||||
</span>
|
||||
) : showLineNumbers ? (
|
||||
lines.map((line, index) => (
|
||||
<span key={index} className="flex min-w-max">
|
||||
<span className="w-10 shrink-0 select-none pr-4 text-right text-muted-foreground/60">
|
||||
<span className="w-10 shrink-0 select-none pr-4 text-right text-muted-foreground">
|
||||
{index + 1}
|
||||
</span>
|
||||
<span className="whitespace-pre">{renderText(line || " ")}</span>
|
||||
@@ -264,7 +246,7 @@ export const CodeBlock = memo(function CodeBlock({
|
||||
<div
|
||||
ref={rootRef}
|
||||
className={cn(
|
||||
"not-prose relative",
|
||||
"not-prose relative code-content",
|
||||
useViewportHighlight ? "overflow-visible" : "overflow-hidden",
|
||||
hasChrome && "rounded-floating bg-secondary/70",
|
||||
className,
|
||||
@@ -277,7 +259,7 @@ export const CodeBlock = memo(function CodeBlock({
|
||||
chrome={chrome}
|
||||
showLineNumbers={showLineNumbers}
|
||||
testId="ansi-code"
|
||||
renderText={renderAnsiText}
|
||||
renderText={(value) => renderAnsiText(value, isDark ? "dark" : "light")}
|
||||
compact={useViewportHighlight}
|
||||
/>
|
||||
) : highlight && withinHighlightBudget && (!deferHighlight || highlightedSource === code) ? (
|
||||
@@ -295,7 +277,6 @@ export const CodeBlock = memo(function CodeBlock({
|
||||
<LazyHighlightedCode
|
||||
language={syntaxLanguage}
|
||||
code={code}
|
||||
isDark={isDark}
|
||||
chrome={chrome}
|
||||
showLineNumbers={showLineNumbers}
|
||||
wrapLongLines={wrapLongLines}
|
||||
@@ -317,7 +298,7 @@ export const CodeBlock = memo(function CodeBlock({
|
||||
onClick={onCopy}
|
||||
className={cn(
|
||||
"absolute right-2.5 top-2.5 z-10 inline-flex h-8 w-8 items-center justify-center rounded-full",
|
||||
"text-muted-foreground/75 transition-colors hover:text-foreground",
|
||||
"text-muted-foreground transition-colors hover:text-foreground",
|
||||
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/60",
|
||||
)}
|
||||
aria-label={copyLabel}
|
||||
|
||||
@@ -108,7 +108,7 @@ export function FileReferenceChip({
|
||||
>
|
||||
{display === "path" && directory ? (
|
||||
<>
|
||||
<span className="text-muted-foreground/65">{directory}</span>
|
||||
<span className="text-muted-foreground">{directory}</span>
|
||||
<span className={cn("font-semibold", interactive && "text-sky-700 dark:text-sky-200")}>{name}</span>
|
||||
</>
|
||||
) : (
|
||||
|
||||
@@ -13,7 +13,7 @@ export function InlineTokenHighlight({
|
||||
}: {
|
||||
children: ReactNode;
|
||||
className?: string;
|
||||
color: string;
|
||||
color?: string;
|
||||
testId?: string;
|
||||
title?: string;
|
||||
}) {
|
||||
@@ -22,7 +22,7 @@ export function InlineTokenHighlight({
|
||||
data-testid={testId}
|
||||
title={title}
|
||||
className={cn(
|
||||
"relative inline font-[550] transition-colors duration-150",
|
||||
"relative inline font-[550] text-foreground transition-colors duration-150",
|
||||
className,
|
||||
)}
|
||||
style={{ color }}
|
||||
|
||||
@@ -261,7 +261,7 @@ export function MessageBlockMenuActions({
|
||||
{timestampLabel || automationSourceLabel ? (
|
||||
<div
|
||||
data-message-block-metadata
|
||||
className={cn("mt-0.5 w-full border-t border-border/45 px-1.5 pt-1 leading-4", sheet ? "px-2 text-xs text-muted-foreground" : "text-[10px] text-muted-foreground/45")}
|
||||
className={cn("mt-0.5 w-full border-t border-border/45 px-1.5 pt-1 leading-4 text-muted-foreground", sheet ? "px-2 text-xs" : "text-[10px]")}
|
||||
>
|
||||
{timestampLabel ? (
|
||||
<time
|
||||
|
||||
@@ -17,7 +17,7 @@ const CodeChunk = memo(function CodeChunk({ rows, text, start, stylesheet, useIn
|
||||
}) {
|
||||
return (
|
||||
<span data-code-chunk={start / CHUNK_LINES} className="flex min-w-max">
|
||||
<span aria-hidden className="shrink-0 select-none pr-[1.15rem] text-right text-muted-foreground/60"
|
||||
<span aria-hidden className="shrink-0 select-none pr-[1.15rem] text-right text-muted-foreground"
|
||||
style={{ minWidth: "4.25em" }}>
|
||||
{rows.map((_, index) => start + index + 1).join("\n")}
|
||||
</span>
|
||||
|
||||
@@ -131,7 +131,7 @@ export function ComposerUsagePopover({
|
||||
aria-label={triggerLabel}
|
||||
className={cn(
|
||||
"touch-target inline-flex size-5 shrink-0 items-center justify-center rounded-full",
|
||||
"text-muted-foreground/75 transition-colors hover:text-foreground/85",
|
||||
"text-muted-foreground transition-colors hover:text-foreground",
|
||||
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
|
||||
showLabel && "w-auto gap-1.5 px-2 text-xs",
|
||||
)}
|
||||
@@ -154,7 +154,7 @@ export function ComposerUsagePopover({
|
||||
"size-[15px] shrink-0 -rotate-90",
|
||||
status === "critical" && "text-destructive",
|
||||
status === "caution" && "text-amber-600 dark:text-amber-400",
|
||||
status === "normal" && "text-muted-foreground/75",
|
||||
status === "normal" && "text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
<circle
|
||||
|
||||
@@ -38,7 +38,7 @@ export function StreamErrorNotice({ error, onDismiss }: StreamErrorNoticeProps)
|
||||
/>
|
||||
<div className="flex-1">
|
||||
<p className="font-medium">{title}</p>
|
||||
<p className="mt-0.5 text-destructive/80">{body}</p>
|
||||
<p className="mt-0.5 text-destructive">{body}</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
|
||||
@@ -2645,7 +2645,7 @@ export function ThreadComposer({
|
||||
aria-label={inputAriaLabel ?? t("thread.composer.inputAria")}
|
||||
className={cn(
|
||||
inputTextClasses,
|
||||
"relative z-10 block caret-foreground placeholder:text-muted-foreground/70",
|
||||
"relative z-10 block caret-foreground placeholder:text-muted-foreground",
|
||||
"focus:outline-none focus-visible:outline-none",
|
||||
"disabled:cursor-not-allowed",
|
||||
hasMentionDecorations && "text-transparent selection:bg-primary/20",
|
||||
|
||||
@@ -9,12 +9,12 @@ export function DiffPair({ added, deleted }: { added: number; deleted: number })
|
||||
<DiffValue
|
||||
sign="+"
|
||||
value={added}
|
||||
className="text-emerald-600/75 dark:text-emerald-300/75"
|
||||
className="text-diff-added-foreground"
|
||||
/>
|
||||
<DiffValue
|
||||
sign="-"
|
||||
value={deleted}
|
||||
className="text-rose-600/70 dark:text-rose-300/75"
|
||||
className="text-diff-deleted-foreground"
|
||||
/>
|
||||
</span>
|
||||
);
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { Suspense, lazy, type ReactNode } from "react";
|
||||
import type { SyntaxHighlighterProps } from "react-syntax-highlighter";
|
||||
|
||||
import { useThemeValue } from "@/hooks/useTheme";
|
||||
import type { RenderableFileDiffLine } from "@/lib/file-diff";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
@@ -10,10 +9,6 @@ interface DiffSyntaxHighlightProps {
|
||||
lines: RenderableFileDiffLine[];
|
||||
}
|
||||
|
||||
interface LoadedDiffSyntaxHighlightProps extends DiffSyntaxHighlightProps {
|
||||
isDark: boolean;
|
||||
}
|
||||
|
||||
type RendererArgs = Parameters<NonNullable<SyntaxHighlighterProps["renderer"]>>[0];
|
||||
type SyntaxNode = RendererArgs["rows"][number];
|
||||
|
||||
@@ -33,26 +28,21 @@ const LazyDiffSyntaxHighlight = lazy(async () => {
|
||||
const [
|
||||
{ default: SyntaxHighlighter },
|
||||
{ default: createSyntaxElement },
|
||||
{ default: oneDark },
|
||||
{ default: oneLight },
|
||||
] = await Promise.all([
|
||||
import("react-syntax-highlighter/dist/esm/prism-async-light"),
|
||||
import("react-syntax-highlighter/dist/esm/create-element"),
|
||||
import("react-syntax-highlighter/dist/esm/styles/prism/one-dark"),
|
||||
import("react-syntax-highlighter/dist/esm/styles/prism/one-light"),
|
||||
]);
|
||||
return {
|
||||
default: function LoadedDiffSyntaxHighlight({
|
||||
language,
|
||||
lines,
|
||||
isDark,
|
||||
}: LoadedDiffSyntaxHighlightProps) {
|
||||
const theme = isDark ? oneDark : oneLight;
|
||||
}: DiffSyntaxHighlightProps) {
|
||||
const code = lines.map((line) => line.content || " ").join("\n");
|
||||
return (
|
||||
<SyntaxHighlighter
|
||||
language={language}
|
||||
style={theme}
|
||||
useInlineStyles={false}
|
||||
style={{}}
|
||||
PreTag="div"
|
||||
CodeTag="div"
|
||||
customStyle={{
|
||||
@@ -71,6 +61,7 @@ const LazyDiffSyntaxHighlight = lazy(async () => {
|
||||
},
|
||||
}}
|
||||
data-language={language}
|
||||
className="code-content"
|
||||
data-testid="syntax-highlighted-diff-hunk"
|
||||
renderer={({ rows, stylesheet, useInlineStyles }) => (
|
||||
<DiffLineTable
|
||||
@@ -96,10 +87,9 @@ const LazyDiffSyntaxHighlight = lazy(async () => {
|
||||
});
|
||||
|
||||
export function DiffSyntaxHighlight({ language, lines }: DiffSyntaxHighlightProps) {
|
||||
const isDark = useThemeValue() === "dark";
|
||||
return (
|
||||
<Suspense fallback={<PlainDiffLines lines={lines} />}>
|
||||
<LazyDiffSyntaxHighlight language={language} lines={lines} isDark={isDark} />
|
||||
<LazyDiffSyntaxHighlight language={language} lines={lines} />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
@@ -148,22 +138,22 @@ function DiffLineRow({
|
||||
<tr
|
||||
className={cn(
|
||||
"border-0",
|
||||
kind === "add" && "bg-emerald-500/[0.09] dark:bg-emerald-300/[0.11]",
|
||||
kind === "delete" && "bg-rose-500/[0.09] dark:bg-rose-300/[0.11]",
|
||||
kind === "add" && "bg-diff-added",
|
||||
kind === "delete" && "bg-diff-deleted",
|
||||
)}
|
||||
>
|
||||
<td className="w-10 select-none border-r border-border/35 px-1.5 text-right text-muted-foreground/55">
|
||||
<td className="w-10 select-none border-r border-border/35 px-1.5 text-right text-muted-foreground">
|
||||
{line.old_lineno ?? ""}
|
||||
</td>
|
||||
<td className="w-10 select-none border-r border-border/35 px-1.5 text-right text-muted-foreground/55">
|
||||
<td className="w-10 select-none border-r border-border/35 px-1.5 text-right text-muted-foreground">
|
||||
{line.new_lineno ?? ""}
|
||||
</td>
|
||||
<td
|
||||
className={cn(
|
||||
"w-5 select-none px-1 text-center",
|
||||
kind === "add" && "text-emerald-600/80 dark:text-emerald-300/85",
|
||||
kind === "delete" && "text-rose-600/80 dark:text-rose-300/85",
|
||||
kind === "context" && "text-muted-foreground/45",
|
||||
kind === "add" && "text-diff-added-foreground",
|
||||
kind === "delete" && "text-diff-deleted-foreground",
|
||||
kind === "context" && "text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
{marker}
|
||||
|
||||
@@ -326,7 +326,7 @@ function FileUnifiedDiff({
|
||||
aria-hidden
|
||||
/>
|
||||
<span className="min-w-0 flex-1">{viewDiffLabel}</span>
|
||||
<span className="shrink-0 text-muted-foreground/65">{lineCountLabel}</span>
|
||||
<span className="shrink-0 text-muted-foreground">{lineCountLabel}</span>
|
||||
</button>
|
||||
<DisclosureContent id={contentId} open={open} onExitComplete={releaseBody}>
|
||||
{shouldRenderBody ? renderBody() : null}
|
||||
|
||||
@@ -35,13 +35,13 @@ export function ThinkingReasoningShell({
|
||||
const headerClassName = "touch-target inline-flex h-7 min-w-0 items-center gap-1.5 rounded-md px-1.5";
|
||||
const headerContent = (
|
||||
<>
|
||||
<Activity className={cn("h-3.5 w-3.5 shrink-0", active ? "activity-current" : "text-muted-foreground/65")} strokeWidth={1.5} aria-hidden>
|
||||
<Activity className={cn("h-3.5 w-3.5 shrink-0", active ? "activity-current" : "text-muted-foreground")} strokeWidth={1.5} aria-hidden>
|
||||
{active ? <path className="activity-current-trace" pathLength={100} d="M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2" /> : null}
|
||||
</Activity>
|
||||
<span
|
||||
data-sheen-text={active ? label : undefined}
|
||||
className={cn(
|
||||
"min-w-0 truncate text-[12px] font-normal leading-4 text-muted-foreground/65",
|
||||
"min-w-0 truncate text-[12px] font-normal leading-4 text-muted-foreground",
|
||||
active && "streaming-text-sheen",
|
||||
)}
|
||||
>
|
||||
|
||||
+55
-4
@@ -24,15 +24,24 @@
|
||||
--secondary: 0 0% 96.1%;
|
||||
--secondary-foreground: 0 0% 9%;
|
||||
--muted: 0 0% 96.1%;
|
||||
--muted-foreground: 0 0% 45.1%;
|
||||
--muted-foreground: 240 4% 40%;
|
||||
--accent: 0 0% 96.1%;
|
||||
--accent-foreground: 0 0% 9%;
|
||||
--destructive: 0 84.2% 60.2%;
|
||||
--destructive: 0 73.7% 41.8%;
|
||||
--destructive-foreground: 0 0% 98%;
|
||||
--border: 40 8% 90.5%;
|
||||
--input: 40 8% 90.5%;
|
||||
--ring: 0 0% 3.9%;
|
||||
--inline-token-highlight: #ef8e30;
|
||||
--inline-token-highlight: #ad450b;
|
||||
--code-comment: #62626b;
|
||||
--code-string: #166534;
|
||||
--code-keyword: #7e22ce;
|
||||
--code-function: #1d4ed8;
|
||||
--code-property: #854d0e;
|
||||
--diff-added: rgb(16 185 129 / 0.09);
|
||||
--diff-added-foreground: #047857;
|
||||
--diff-deleted: rgb(244 63 94 / 0.09);
|
||||
--diff-deleted-foreground: #be123c;
|
||||
--usage-token: 29 86% 56%;
|
||||
--session-handle-lightness: 0.5;
|
||||
--session-handle-chroma: 0.12;
|
||||
@@ -78,7 +87,7 @@
|
||||
--secondary: var(--card);
|
||||
--secondary-foreground: 0 0% 98%;
|
||||
--muted: var(--card);
|
||||
--muted-foreground: 0 0% 65%;
|
||||
--muted-foreground: 0 0% 72%;
|
||||
--accent: 0 0% 25%;
|
||||
--accent-foreground: 0 0% 98%;
|
||||
/* Destructive text needs contrast on dark surfaces; filled controls use a dark label. */
|
||||
@@ -88,6 +97,15 @@
|
||||
--input: var(--border);
|
||||
--ring: 0 0% 83.1%;
|
||||
--inline-token-highlight: #ef8e30;
|
||||
--code-comment: #c8c8d0;
|
||||
--code-string: #b5d99c;
|
||||
--code-keyword: #e3a5f7;
|
||||
--code-function: #93c5fd;
|
||||
--code-property: #f6c177;
|
||||
--diff-added: rgb(110 231 183 / 0.11);
|
||||
--diff-added-foreground: #6ee7b7;
|
||||
--diff-deleted: rgb(253 164 175 / 0.11);
|
||||
--diff-deleted-foreground: #fda4af;
|
||||
--session-handle-lightness: 0.75;
|
||||
--session-handle-chroma: 0.11;
|
||||
--temporary-control-active: #ef8e30;
|
||||
@@ -1617,3 +1635,36 @@
|
||||
@keyframes workspace-directory-shimmer {
|
||||
to { transform: translateX(100%); }
|
||||
}
|
||||
|
||||
/* Prism classes are generated at runtime, outside Tailwind's source inventory. */
|
||||
.code-content {
|
||||
color: hsl(var(--foreground));
|
||||
}
|
||||
/* Flattened JSX tokens retain the ancestor tag class; let inner token types win. */
|
||||
.code-content .token.tag {
|
||||
color: var(--code-property);
|
||||
}
|
||||
.code-content :is(.token.comment, .token.prolog, .token.doctype, .token.cdata, .linenumber) {
|
||||
color: var(--code-comment);
|
||||
}
|
||||
.code-content .token.comment {
|
||||
font-style: italic;
|
||||
}
|
||||
.code-content :is(.token.string, .token.char, .token.attr-value, .token.regex, .token.inserted) {
|
||||
color: var(--code-string);
|
||||
}
|
||||
.code-content :is(.token.keyword, .token.selector, .token.important, .token.atrule) {
|
||||
color: var(--code-keyword);
|
||||
}
|
||||
.code-content :is(.token.function, .token.operator, .token.entity, .token.url) {
|
||||
color: var(--code-function);
|
||||
}
|
||||
.code-content :is(.token.number, .token.boolean, .token.constant, .token.symbol, .token.attr-name, .token.class-name, .token.builtin, .token.property, .token.deleted) {
|
||||
color: var(--code-property);
|
||||
}
|
||||
.code-content :is(.token.bold, .token.important) {
|
||||
font-weight: 600;
|
||||
}
|
||||
.code-content .token.italic {
|
||||
font-style: italic;
|
||||
}
|
||||
+47
-18
@@ -13,15 +13,18 @@ type AnsiStyle = {
|
||||
};
|
||||
|
||||
type AnsiState = {
|
||||
backgroundColor?: string;
|
||||
backgroundColor?: AnsiColor;
|
||||
bold: boolean;
|
||||
color?: string;
|
||||
color?: AnsiColor;
|
||||
dim: boolean;
|
||||
inverse: boolean;
|
||||
italic: boolean;
|
||||
underline: boolean;
|
||||
};
|
||||
|
||||
type AnsiColor = number | string;
|
||||
type AnsiTheme = "light" | "dark";
|
||||
|
||||
const ESC = String.fromCharCode(27);
|
||||
const ANSI_PATTERN = new RegExp(`${ESC}\\[[0-?]*[ -/]*[@-~]`, "g");
|
||||
|
||||
@@ -47,6 +50,22 @@ const ANSI_BRIGHT_COLORS = [
|
||||
"#ffffff",
|
||||
];
|
||||
|
||||
const ANSI_PALETTE = [...ANSI_COLORS, ...ANSI_BRIGHT_COLORS];
|
||||
const ANSI_FOREGROUNDS: Record<AnsiTheme, string[]> = {
|
||||
light: [
|
||||
"#18181b", "#b91c1c", "#166534", "#854d0e",
|
||||
"#1d4ed8", "#7e22ce", "#0e7490", "#52525b",
|
||||
"#62626b", "#b91c1c", "#166534", "#854d0e",
|
||||
"#1d4ed8", "#86198f", "#155e75", "#3f3f46",
|
||||
],
|
||||
dark: [
|
||||
"#a1a1aa", "#fca5a5", "#86efac", "#fde047",
|
||||
"#93c5fd", "#d8b4fe", "#67e8f9", "#e5e7eb",
|
||||
"#a1a1aa", "#fca5a5", "#86efac", "#fef08a",
|
||||
"#93c5fd", "#e9d5ff", "#a5f3fc", "#ffffff",
|
||||
],
|
||||
};
|
||||
|
||||
const RGB_STEPS = [0, 95, 135, 175, 215, 255];
|
||||
|
||||
export function hasAnsi(value: string): boolean {
|
||||
@@ -61,6 +80,8 @@ export function stripAnsi(value: string): string {
|
||||
|
||||
function initialState(): AnsiState {
|
||||
return {
|
||||
backgroundColor: undefined,
|
||||
color: undefined,
|
||||
bold: false,
|
||||
dim: false,
|
||||
inverse: false,
|
||||
@@ -69,10 +90,9 @@ function initialState(): AnsiState {
|
||||
};
|
||||
}
|
||||
|
||||
function colorFrom256(value: number): string | undefined {
|
||||
function colorFrom256(value: number): AnsiColor | undefined {
|
||||
if (value < 0 || value > 255) return undefined;
|
||||
if (value < 8) return ANSI_COLORS[value];
|
||||
if (value < 16) return ANSI_BRIGHT_COLORS[value - 8];
|
||||
if (value < 16) return value;
|
||||
if (value < 232) {
|
||||
const offset = value - 16;
|
||||
const red = RGB_STEPS[Math.floor(offset / 36)];
|
||||
@@ -110,7 +130,7 @@ function applyExtendedColor(
|
||||
const mode = params[index + 1];
|
||||
if (mode === 5) {
|
||||
const color = colorFrom256(params[index + 2]);
|
||||
if (color) state[key] = color;
|
||||
if (color !== undefined) state[key] = color;
|
||||
return index + 2;
|
||||
}
|
||||
if (mode === 2) {
|
||||
@@ -152,13 +172,13 @@ function applySgrParams(state: AnsiState, params: number[]): void {
|
||||
} else if (code === 49) {
|
||||
delete state.backgroundColor;
|
||||
} else if (code >= 30 && code <= 37) {
|
||||
state.color = ANSI_COLORS[code - 30];
|
||||
state.color = code - 30;
|
||||
} else if (code >= 40 && code <= 47) {
|
||||
state.backgroundColor = ANSI_COLORS[code - 40];
|
||||
state.backgroundColor = code - 40;
|
||||
} else if (code >= 90 && code <= 97) {
|
||||
state.color = ANSI_BRIGHT_COLORS[code - 90];
|
||||
state.color = code - 90 + 8;
|
||||
} else if (code >= 100 && code <= 107) {
|
||||
state.backgroundColor = ANSI_BRIGHT_COLORS[code - 100];
|
||||
state.backgroundColor = code - 100 + 8;
|
||||
} else if (code === 38) {
|
||||
index = applyExtendedColor(state, params, index, "color");
|
||||
} else if (code === 48) {
|
||||
@@ -167,12 +187,21 @@ function applySgrParams(state: AnsiState, params: number[]): void {
|
||||
}
|
||||
}
|
||||
|
||||
function styleFromState(state: AnsiState): AnsiStyle | undefined {
|
||||
const foreground = state.inverse ? state.backgroundColor : state.color;
|
||||
const background = state.inverse ? state.color : state.backgroundColor;
|
||||
function styleFromState(state: AnsiState, theme: AnsiTheme): AnsiStyle | undefined {
|
||||
// Explicit color pairs retain the output's palette; standalone foregrounds
|
||||
// use colors selected for the UI surface. RGB and extended colors stay literal.
|
||||
const palette = state.backgroundColor === undefined ? ANSI_FOREGROUNDS[theme] : ANSI_PALETTE;
|
||||
const foreground = typeof state.color === "number" ? palette[state.color] : state.color;
|
||||
const background = typeof state.backgroundColor === "number"
|
||||
? ANSI_PALETTE[state.backgroundColor] : state.backgroundColor;
|
||||
const style: AnsiStyle = {};
|
||||
if (foreground) style.color = foreground;
|
||||
if (background) style.backgroundColor = background;
|
||||
if (state.inverse) {
|
||||
style.color = background ?? "hsl(var(--background))";
|
||||
style.backgroundColor = foreground ?? "hsl(var(--foreground))";
|
||||
} else {
|
||||
if (foreground) style.color = foreground;
|
||||
if (background) style.backgroundColor = background;
|
||||
}
|
||||
if (state.bold) style.fontWeight = 700;
|
||||
if (state.dim) style.opacity = 0.72;
|
||||
if (state.italic) style.fontStyle = "italic";
|
||||
@@ -180,7 +209,7 @@ function styleFromState(state: AnsiState): AnsiStyle | undefined {
|
||||
return Object.keys(style).length ? style : undefined;
|
||||
}
|
||||
|
||||
export function parseAnsiSegments(value: string): AnsiSegment[] {
|
||||
export function parseAnsiSegments(value: string, theme: AnsiTheme): AnsiSegment[] {
|
||||
const segments: AnsiSegment[] = [];
|
||||
const state = initialState();
|
||||
let cursor = 0;
|
||||
@@ -191,7 +220,7 @@ export function parseAnsiSegments(value: string): AnsiSegment[] {
|
||||
if (index > cursor) {
|
||||
segments.push({
|
||||
text: value.slice(cursor, index),
|
||||
style: styleFromState(state),
|
||||
style: styleFromState(state, theme),
|
||||
});
|
||||
}
|
||||
const params = normalizedSgrParams(match[0]);
|
||||
@@ -202,7 +231,7 @@ export function parseAnsiSegments(value: string): AnsiSegment[] {
|
||||
if (cursor < value.length) {
|
||||
segments.push({
|
||||
text: value.slice(cursor),
|
||||
style: styleFromState(state),
|
||||
style: styleFromState(state, theme),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1611,7 +1611,7 @@ describe("AgentActivityCluster", () => {
|
||||
<AgentActivityCluster messages={messages} isTurnStreaming={false} hasBodyBelow={false} />,
|
||||
);
|
||||
expect(screen.getByText(/^Worked/)).toBe(header);
|
||||
expect(header).toHaveClass("text-muted-foreground/65");
|
||||
expect(header).toHaveClass("text-muted-foreground");
|
||||
expect(header).not.toHaveAttribute("data-sheen-text");
|
||||
});
|
||||
|
||||
|
||||
@@ -5,27 +5,19 @@ import { describe, expect, it, vi } from "vitest";
|
||||
import { CodeBlock } from "@/components/CodeBlock";
|
||||
import { ThemeProvider } from "@/hooks/useTheme";
|
||||
|
||||
const mockedStyles = vi.hoisted(() => ({
|
||||
dark: { pre: { background: "#111" } },
|
||||
light: { pre: { background: "#fff" } },
|
||||
}));
|
||||
|
||||
vi.mock("react-syntax-highlighter/dist/esm/prism-async-light", () => ({
|
||||
default: ({
|
||||
children,
|
||||
language,
|
||||
style,
|
||||
customStyle,
|
||||
}: {
|
||||
children: string;
|
||||
language?: string;
|
||||
style: Record<string, unknown>;
|
||||
customStyle?: React.CSSProperties;
|
||||
}) => (
|
||||
<pre
|
||||
data-testid="highlighted-code"
|
||||
data-language={language}
|
||||
data-theme={style === mockedStyles.dark ? "dark" : "light"}
|
||||
style={customStyle}
|
||||
>
|
||||
<code>{children}</code>
|
||||
@@ -33,14 +25,6 @@ vi.mock("react-syntax-highlighter/dist/esm/prism-async-light", () => ({
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("react-syntax-highlighter/dist/esm/styles/prism/one-dark", () => ({
|
||||
default: mockedStyles.dark,
|
||||
}));
|
||||
|
||||
vi.mock("react-syntax-highlighter/dist/esm/styles/prism/one-light", () => ({
|
||||
default: mockedStyles.light,
|
||||
}));
|
||||
|
||||
describe("CodeBlock", () => {
|
||||
it("renders and copies a large code block in full without pagination", async () => {
|
||||
const user = userEvent.setup();
|
||||
@@ -220,7 +204,7 @@ describe("CodeBlock", () => {
|
||||
"ansi",
|
||||
);
|
||||
expect(screen.queryByText("ansi")).not.toBeInTheDocument();
|
||||
expect(screen.getByText("PASS")).toHaveStyle({ color: "#0dbc79" });
|
||||
expect(screen.getByText("PASS")).toHaveStyle({ color: "#86efac" });
|
||||
expect(screen.getByText("<script>alert(1)</script>")).toBeInTheDocument();
|
||||
expect(document.querySelector("script")).toBeNull();
|
||||
});
|
||||
@@ -241,6 +225,13 @@ describe("CodeBlock", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("clears ANSI foreground and background colors on reset", () => {
|
||||
render(<CodeBlock language="ansi" code={"\x1b[31;47merror\x1b[0m normal"} />);
|
||||
|
||||
expect(screen.getByText("error")).toHaveStyle({ color: "#cd3131", backgroundColor: "#e5e5e5" });
|
||||
expect(screen.getByText("normal")).not.toHaveAttribute("style");
|
||||
});
|
||||
|
||||
it("copies ANSI output as clean text", async () => {
|
||||
const user = userEvent.setup();
|
||||
const writeText = vi.fn().mockResolvedValue(undefined);
|
||||
@@ -314,7 +305,7 @@ describe("CodeBlock", () => {
|
||||
try {
|
||||
const { rerender } = render(
|
||||
<ThemeProvider theme="dark">
|
||||
<CodeBlock language="ts" code="const value = 1;" />
|
||||
<CodeBlock language="ansi" code={"\x1b[32mPASS\x1b[0m"} />
|
||||
</ThemeProvider>,
|
||||
);
|
||||
|
||||
@@ -323,14 +314,11 @@ describe("CodeBlock", () => {
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
expect(screen.getByTestId("highlighted-code")).toHaveAttribute(
|
||||
"data-theme",
|
||||
"dark",
|
||||
);
|
||||
expect(screen.getByText("PASS")).toHaveStyle({ color: "#86efac" });
|
||||
|
||||
rerender(
|
||||
<ThemeProvider theme="light">
|
||||
<CodeBlock language="ts" code="const value = 1;" />
|
||||
<CodeBlock language="ansi" code={"\x1b[32mPASS\x1b[0m"} />
|
||||
</ThemeProvider>,
|
||||
);
|
||||
|
||||
@@ -338,10 +326,7 @@ describe("CodeBlock", () => {
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
expect(screen.getByTestId("highlighted-code")).toHaveAttribute(
|
||||
"data-theme",
|
||||
"light",
|
||||
);
|
||||
expect(screen.getByText("PASS")).toHaveStyle({ color: "#166534" });
|
||||
expect(observer).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
vi.stubGlobal("MutationObserver", originalMutationObserver);
|
||||
|
||||
@@ -1,9 +1,18 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import { parse } from "postcss";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { DiffSyntaxHighlight } from "@/components/thread/activity/DiffSyntaxHighlight";
|
||||
import { ThemeProvider } from "@/hooks/useTheme";
|
||||
|
||||
const globalStyles = parse(readFileSync(resolve(process.cwd(), "src/globals.css"), "utf8"));
|
||||
// happy-dom does not apply cascade layers; retain the real rules and their order.
|
||||
globalStyles.walkAtRules("layer", (layer) => {
|
||||
layer.replaceWith(...(layer.nodes ?? []));
|
||||
});
|
||||
|
||||
describe("DiffSyntaxHighlight with Prism", () => {
|
||||
it("loads the TSX grammar and renders styled syntax tokens", async () => {
|
||||
render(
|
||||
@@ -50,10 +59,11 @@ describe("DiffSyntaxHighlight with Prism", () => {
|
||||
await waitFor(
|
||||
() => {
|
||||
const tokens = highlighted.querySelectorAll<HTMLElement>(
|
||||
'td:last-child span[style*="color"]',
|
||||
"td:last-child .token",
|
||||
);
|
||||
expect(tokens).not.toHaveLength(0);
|
||||
expect(new Set([...tokens].map((token) => token.style.color)).size).toBeGreaterThan(1);
|
||||
expect(highlighted.querySelector(".token.keyword")).not.toBeNull();
|
||||
expect(highlighted.querySelector(".token.string")).not.toBeNull();
|
||||
},
|
||||
{ timeout: 10_000 },
|
||||
);
|
||||
@@ -62,6 +72,56 @@ describe("DiffSyntaxHighlight with Prism", () => {
|
||||
expect(highlighted.querySelectorAll("tbody tr")).toHaveLength(4);
|
||||
});
|
||||
|
||||
it.each(["light", "dark"] as const)(
|
||||
"preserves nested JSX token colors in the %s appearance",
|
||||
async (appearance) => {
|
||||
const { container } = render(
|
||||
<div className={appearance === "dark" ? "dark" : ""}>
|
||||
<style>{globalStyles.toString()}</style>
|
||||
<DiffSyntaxHighlight
|
||||
language="tsx"
|
||||
lines={[{
|
||||
kind: "add",
|
||||
old_lineno: null,
|
||||
new_lineno: 1,
|
||||
content: '<span className={enabled ? "yes" : "no"} onClick={() => save(new Event("ok"))}>ready</span>',
|
||||
}]}
|
||||
/>
|
||||
</div>,
|
||||
);
|
||||
|
||||
const highlighted = await screen.findByTestId(
|
||||
"syntax-highlighted-diff-hunk",
|
||||
{},
|
||||
{ timeout: 10_000 },
|
||||
);
|
||||
await waitFor(() => {
|
||||
expect(highlighted.querySelector(".token.function")).not.toBeNull();
|
||||
}, { timeout: 10_000 });
|
||||
|
||||
const colors = getComputedStyle(
|
||||
appearance === "dark" ? container.firstElementChild! : document.documentElement,
|
||||
);
|
||||
const tokens = [...highlighted.querySelectorAll<HTMLElement>(".token")];
|
||||
for (const [text, category, variable] of [
|
||||
['"yes"', "string", "--code-string"],
|
||||
["new", "keyword", "--code-keyword"],
|
||||
["save", "function", "--code-function"],
|
||||
["=>", "operator", "--code-function"],
|
||||
["className", "attr-name", "--code-property"],
|
||||
["span", "tag", "--code-property"],
|
||||
]) {
|
||||
const token = tokens.find(
|
||||
(node) => node.textContent === text && node.classList.contains(category),
|
||||
);
|
||||
const expectedColor = colors.getPropertyValue(variable).trim();
|
||||
expect(token, `${category}: ${text}`).toBeDefined();
|
||||
expect(expectedColor).not.toBe("");
|
||||
expect.soft(getComputedStyle(token!).color, `${category}: ${text}`).toBe(expectedColor);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("preserves markdown table line boundaries", async () => {
|
||||
const lines = [
|
||||
"## 发布安排",
|
||||
|
||||
@@ -48,14 +48,6 @@ vi.mock("react-syntax-highlighter/dist/esm/create-element", () => ({
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("react-syntax-highlighter/dist/esm/styles/prism/one-dark", () => ({
|
||||
default: { dark: { color: "#fff" } },
|
||||
}));
|
||||
|
||||
vi.mock("react-syntax-highlighter/dist/esm/styles/prism/one-light", () => ({
|
||||
default: { light: { color: "#111" } },
|
||||
}));
|
||||
|
||||
describe("DiffSyntaxHighlight", () => {
|
||||
it("highlights a complete hunk while preserving diff rows and line numbers", async () => {
|
||||
render(
|
||||
@@ -81,10 +73,10 @@ describe("DiffSyntaxHighlight", () => {
|
||||
expect(highlighted).toHaveAttribute("data-language", "typescript");
|
||||
expect(screen.getAllByTestId("syntax-token")).toHaveLength(3);
|
||||
expect(screen.getByText("return oldValue;", { exact: false }).closest("tr")).toHaveClass(
|
||||
"bg-rose-500/[0.09]",
|
||||
"bg-diff-deleted",
|
||||
);
|
||||
expect(screen.getByText("return newValue;", { exact: false }).closest("tr")).toHaveClass(
|
||||
"bg-emerald-500/[0.09]",
|
||||
"bg-diff-added",
|
||||
);
|
||||
expect(screen.getAllByText("5")).toHaveLength(2);
|
||||
expect(screen.getAllByTestId("syntax-token").some((node) => node.textContent?.endsWith("\n"))).toBe(false);
|
||||
|
||||
@@ -663,8 +663,8 @@ describe("MessageBubble", () => {
|
||||
expect(token).toHaveClass("font-[550]");
|
||||
expect(token.className).not.toContain("rounded");
|
||||
expect(token.className).not.toContain("px-");
|
||||
expect(token.getAttribute("style")).toContain("color: #0B5CFF");
|
||||
expect(token.getAttribute("style")).not.toContain("text-shadow");
|
||||
expect(token).toHaveClass("text-foreground");
|
||||
expect(token.style.textShadow).toBe("");
|
||||
const logo = screen.getByTestId("message-cli-mention-logo-zoom");
|
||||
expect(logo).toHaveClass("h-[1.1em]", "w-[1.1em]", "rounded-[0.25em]", "top-1/2", "-translate-y-1/2");
|
||||
expect(logo.parentElement).toHaveClass("mr-1", "w-[1.1em]");
|
||||
@@ -716,7 +716,7 @@ describe("MessageBubble", () => {
|
||||
expect(token).toHaveTextContent("@Draw.io");
|
||||
expect(token.className).not.toContain("rounded");
|
||||
expect(token.className).not.toContain("px-");
|
||||
expect(token.getAttribute("style")).toContain("color: #F08705");
|
||||
expect(token).toHaveClass("text-foreground");
|
||||
expect(screen.getByTestId("message-cli-mention-logo-drawio")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -733,7 +733,7 @@ describe("MessageBubble", () => {
|
||||
const token = screen.getByTestId("message-mcp-mention-browserbase");
|
||||
expect(token).toHaveTextContent("@Browserbase");
|
||||
expect(token).toHaveAttribute("title", "MCP server: Browserbase (@browserbase)");
|
||||
expect(token.getAttribute("style")).toContain("color: #111827");
|
||||
expect(token).toHaveClass("text-foreground");
|
||||
const logo = screen.getByTestId("message-mcp-mention-logo-browserbase");
|
||||
expect(logo).toHaveClass("h-[1.1em]", "w-[1.1em]", "rounded-[0.25em]", "top-1/2", "-translate-y-1/2");
|
||||
expect(logo.parentElement).toHaveClass("mr-1", "w-[1.1em]");
|
||||
|
||||
@@ -57,7 +57,7 @@ describe("ThinkingReasoningShell", () => {
|
||||
view.rerender(shell(false));
|
||||
|
||||
expect(screen.getByRole("button", { name: "Worked, Collapse activity details" })).toBe(button);
|
||||
expect(screen.getByText("Worked")).toHaveClass("text-muted-foreground/65");
|
||||
expect(screen.getByText("Worked")).toHaveClass("text-muted-foreground");
|
||||
expect(screen.getByText("Worked")).not.toHaveAttribute("data-sheen-text");
|
||||
expect(button.className).toBe(headerClass);
|
||||
expect(screen.getByTestId("agent-activity-content")).toBe(content);
|
||||
|
||||
@@ -2506,8 +2506,8 @@ describe("ThreadComposer", () => {
|
||||
expect(token.className).not.toContain("zoom-in");
|
||||
expect(token.className).not.toContain("px-");
|
||||
expect(token.className).not.toContain("mx-");
|
||||
expect(token.getAttribute("style")).toContain("color: #5C5543");
|
||||
expect(token.getAttribute("style")).not.toContain("text-shadow");
|
||||
expect(token).toHaveClass("text-foreground");
|
||||
expect(token.style.textShadow).toBe("");
|
||||
expect(screen.queryByTestId("composer-cli-app-tray")).not.toBeInTheDocument();
|
||||
const logo = screen.getByTestId("composer-cli-mention-logo-gimp");
|
||||
expect(logo.className).toContain("top-1/2");
|
||||
@@ -2543,7 +2543,7 @@ describe("ThreadComposer", () => {
|
||||
expect(name).toHaveClass("[-webkit-text-stroke:0.4px_currentColor]");
|
||||
});
|
||||
|
||||
it("uses the shared accent when an installed CLI app has no brand metadata", () => {
|
||||
it("uses the theme foreground when an installed CLI app has no brand metadata", () => {
|
||||
const mention = "@obsidian-agent-cli";
|
||||
const app: CliAppInfo = {
|
||||
name: "obsidian-agent-cli",
|
||||
@@ -2575,8 +2575,7 @@ describe("ThreadComposer", () => {
|
||||
});
|
||||
|
||||
const token = screen.getByTestId("composer-cli-mention-obsidian-agent-cli");
|
||||
expect(token.getAttribute("style")).toContain("var(--inline-token-highlight)");
|
||||
expect(token.getAttribute("style")).not.toContain("var(--primary)");
|
||||
expect(token).toHaveClass("text-foreground");
|
||||
});
|
||||
|
||||
it.each([
|
||||
|
||||
@@ -765,7 +765,7 @@ describe("ThreadMessages", () => {
|
||||
const timestamp = menu.querySelector<HTMLElement>("[data-message-timestamp]")!;
|
||||
expect(timestamp).toBeInTheDocument();
|
||||
expect(timestamp).toHaveClass("min-h-[var(--message-block-control-size)]");
|
||||
expect(timestamp.parentElement).toHaveClass("border-t", "text-muted-foreground/45");
|
||||
expect(timestamp.parentElement).toHaveClass("border-t", "text-muted-foreground");
|
||||
expect(toolbar).not.toContainElement(timestamp);
|
||||
expect(timestamp).not.toHaveAttribute("tabindex");
|
||||
expect(timestamp.querySelector("svg")).not.toBeInTheDocument();
|
||||
|
||||
@@ -92,6 +92,14 @@ export default {
|
||||
DEFAULT: "hsl(var(--destructive))",
|
||||
foreground: "hsl(var(--destructive-foreground))",
|
||||
},
|
||||
"diff-added": {
|
||||
DEFAULT: "var(--diff-added)",
|
||||
foreground: "var(--diff-added-foreground)",
|
||||
},
|
||||
"diff-deleted": {
|
||||
DEFAULT: "var(--diff-deleted)",
|
||||
foreground: "var(--diff-deleted-foreground)",
|
||||
},
|
||||
border: "hsl(var(--border))",
|
||||
input: "hsl(var(--input))",
|
||||
ring: "hsl(var(--ring))",
|
||||
|
||||
Reference in new issue
Block a user