Misc markdown styling improvements (#3017)
Co-authored-by: ss <[email protected]> Co-authored-by: Claude Opus 4.8 <[email protected]> Co-authored-by: codex <[email protected]> Co-authored-by: Cursor Agent <[email protected]> Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
This commit is contained in:
36 files changed
+2934
-612
No files matched your search
@@ -10,7 +10,7 @@ import type {
|
||||
import {
|
||||
detectComposerTrigger,
|
||||
replaceTextRange,
|
||||
serializeComposerMentionPath,
|
||||
serializeComposerFileLink,
|
||||
type ComposerTrigger,
|
||||
} from "@t3tools/shared/composerTrigger";
|
||||
import { TextInputWrapper } from "expo-paste-input";
|
||||
@@ -419,7 +419,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
|
||||
let replacement = "";
|
||||
if (item.type === "path") {
|
||||
replacement = `@${serializeComposerMentionPath(item.path)} `;
|
||||
replacement = `${serializeComposerFileLink(item.path)} `;
|
||||
} else if (item.type === "skill") {
|
||||
replacement = `$${item.skill.name} `;
|
||||
} else if (item.type === "slash-command") {
|
||||
|
||||
@@ -43,6 +43,9 @@
|
||||
"react": "19.2.6",
|
||||
"react-dom": "19.2.6",
|
||||
"react-markdown": "^10.1.0",
|
||||
"rehype-raw": "^7.0.0",
|
||||
"rehype-sanitize": "^6.0.0",
|
||||
"remark-breaks": "^4.0.0",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"tailwind-merge": "^3.4.0",
|
||||
"zustand": "^5.0.11"
|
||||
|
||||
@@ -24,6 +24,7 @@ vi.mock("../localApi", () => ({
|
||||
}));
|
||||
|
||||
import ChatMarkdown from "./ChatMarkdown";
|
||||
import { serializeTableElementToCsv, serializeTableElementToMarkdown } from "../markdown-clipboard";
|
||||
|
||||
describe("ChatMarkdown", () => {
|
||||
afterEach(() => {
|
||||
@@ -134,8 +135,550 @@ describe("ChatMarkdown", () => {
|
||||
await expect.element(link).toBeInTheDocument();
|
||||
await expect.element(link).toHaveAttribute("href", "https://openai.com/docs");
|
||||
await expect.element(link).toHaveAttribute("target", "_blank");
|
||||
const favicon = link.element().querySelector<HTMLElement>(".chat-markdown-link-favicon");
|
||||
const leading = link.element().querySelector<HTMLElement>(".chat-markdown-link-leading");
|
||||
expect(favicon).not.toBeNull();
|
||||
expect(leading).not.toBeNull();
|
||||
expect(leading?.contains(favicon)).toBe(true);
|
||||
expect(getComputedStyle(leading!).display).toBe("inline");
|
||||
expect(getComputedStyle(leading!).whiteSpace).toBe("nowrap");
|
||||
expect(getComputedStyle(favicon!).verticalAlign).not.toBe("baseline");
|
||||
expect(leading?.textContent).toBe("O");
|
||||
expect(link.element().textContent).toBe("OpenAI");
|
||||
expect(getComputedStyle(link.element()).textDecorationLine).toBe("none");
|
||||
expect(link.element().querySelector("img, svg")?.getBoundingClientRect().width).toBe(14);
|
||||
await link.hover();
|
||||
expect(getComputedStyle(link.element()).backgroundImage).not.toBe("none");
|
||||
await expect.element(page.getByText("https://openai.com/docs")).toBeVisible();
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps a favicon with the leading segment of a wrapping URL", async () => {
|
||||
const url = "https://github.com/pingdotgg/t3code/pull/3017/changes";
|
||||
const screen = await render(
|
||||
<div style={{ width: 180 }}>
|
||||
<ChatMarkdown text={`[${url}](${url})`} cwd="/repo/project" />
|
||||
</div>,
|
||||
);
|
||||
|
||||
try {
|
||||
const link = page.getByRole("link", { name: url });
|
||||
const leading = link.element().querySelector<HTMLElement>(".chat-markdown-link-leading");
|
||||
const favicon = link.element().querySelector<HTMLElement>(".chat-markdown-link-favicon");
|
||||
expect(leading).not.toBeNull();
|
||||
expect(favicon).not.toBeNull();
|
||||
expect(leading?.contains(favicon)).toBe(true);
|
||||
expect(leading?.textContent).toBe("https://");
|
||||
expect(getComputedStyle(leading!).display).toBe("inline");
|
||||
expect(getComputedStyle(leading!).whiteSpace).toBe("nowrap");
|
||||
expect(getComputedStyle(favicon!).verticalAlign).not.toBe("baseline");
|
||||
expect(link.element().textContent).toBe(url);
|
||||
expect(link.element().querySelectorAll("wbr").length).toBeGreaterThan(0);
|
||||
const markdownRoot = link.element().closest<HTMLElement>(".chat-markdown");
|
||||
expect(markdownRoot).not.toBeNull();
|
||||
expect(markdownRoot!.scrollWidth).toBeLessThanOrEqual(markdownRoot!.clientWidth);
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
it("renders file links with the shared file tag chip treatment", async () => {
|
||||
const screen = await render(
|
||||
<ChatMarkdown text="[package.json](path/to/package.json)" cwd="/repo/project" />,
|
||||
);
|
||||
|
||||
try {
|
||||
const link = page.getByRole("link", { name: "package.json" });
|
||||
await expect.element(link).toHaveClass(/chat-markdown-file-link/);
|
||||
const element = document.querySelector<HTMLElement>(".chat-markdown-file-link");
|
||||
expect(element?.querySelector("img, svg")).not.toBeNull();
|
||||
expect(getComputedStyle(element!).display).toBe("inline-flex");
|
||||
expect(getComputedStyle(element!).textDecorationLine).toBe("none");
|
||||
expect(getComputedStyle(element!).borderStyle).toBe("solid");
|
||||
expect(getComputedStyle(element!).userSelect).not.toBe("none");
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
it("renders sanitized details with the design-system collapsible", async () => {
|
||||
const source = [
|
||||
"<details open>",
|
||||
"<summary>Expandable details section</summary>",
|
||||
"",
|
||||
"This content includes **formatted text**.",
|
||||
"",
|
||||
'<span title="native tooltip should be stripped">Safe inline HTML</span>',
|
||||
"<script>window.__unsafeMarkdownScript = true</script>",
|
||||
"</details>",
|
||||
].join("\n");
|
||||
const screen = await render(<ChatMarkdown text={source} cwd="/repo/project" />);
|
||||
|
||||
try {
|
||||
const details = document.querySelector<HTMLElement>("[data-markdown-details]");
|
||||
const trigger = page.getByRole("button", { name: "Expandable details section" });
|
||||
expect(details).not.toBeNull();
|
||||
expect(details?.tagName).toBe("DIV");
|
||||
await expect.element(trigger).toHaveAttribute("aria-expanded", "true");
|
||||
expect(details?.querySelector("strong")?.textContent).toBe("formatted text");
|
||||
expect(details?.querySelector("script")).toBeNull();
|
||||
expect(details?.querySelector("[title]")).toBeNull();
|
||||
|
||||
await trigger.click();
|
||||
await expect.element(trigger).toHaveAttribute("aria-expanded", "false");
|
||||
await trigger.click();
|
||||
await expect.element(trigger).toHaveAttribute("aria-expanded", "true");
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
it("renders footnotes as same-document references", async () => {
|
||||
const source = [
|
||||
"A claim with supporting context.[^context]",
|
||||
"",
|
||||
"[^context]: Supporting **footnote text**.",
|
||||
].join("\n");
|
||||
const screen = await render(<ChatMarkdown text={source} cwd="/repo/project" />);
|
||||
|
||||
try {
|
||||
const reference = document.querySelector<HTMLAnchorElement>(
|
||||
'.chat-markdown a[data-footnote-ref=""]',
|
||||
);
|
||||
const footnotes = document.querySelector<HTMLElement>(
|
||||
".chat-markdown section[data-footnotes]",
|
||||
);
|
||||
expect(reference).not.toBeNull();
|
||||
expect(reference?.getAttribute("href")).toMatch(/^#user-content-fn-/);
|
||||
expect(reference?.hasAttribute("target")).toBe(false);
|
||||
expect(footnotes).not.toBeNull();
|
||||
expect(footnotes?.querySelector("strong")?.textContent).toBe("footnote text");
|
||||
expect(footnotes?.querySelector<HTMLAnchorElement>("a[data-footnote-backref]")?.target).toBe(
|
||||
"",
|
||||
);
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
it("navigates hash links within the clicked markdown message", async () => {
|
||||
const source = [
|
||||
"A claim with supporting context.[^context]",
|
||||
"",
|
||||
"[^context]: Supporting footnote text.",
|
||||
].join("\n");
|
||||
const originalUrl = window.location.href;
|
||||
const scrollIntoView = vi
|
||||
.spyOn(HTMLElement.prototype, "scrollIntoView")
|
||||
.mockImplementation(() => undefined);
|
||||
const screen = await render(
|
||||
<div>
|
||||
<ChatMarkdown text={source} cwd="/repo/project" />
|
||||
<ChatMarkdown text={source} cwd="/repo/project" />
|
||||
</div>,
|
||||
);
|
||||
|
||||
try {
|
||||
const markdownRoots = document.querySelectorAll<HTMLElement>(".chat-markdown");
|
||||
const secondRoot = markdownRoots[1];
|
||||
const secondReference =
|
||||
secondRoot?.querySelector<HTMLAnchorElement>('a[data-footnote-ref=""]');
|
||||
const secondFootnote = secondRoot?.querySelector<HTMLElement>(
|
||||
"section[data-footnotes] li[id]",
|
||||
);
|
||||
expect(secondReference).not.toBeNull();
|
||||
expect(secondFootnote).not.toBeNull();
|
||||
|
||||
secondReference?.click();
|
||||
|
||||
expect(scrollIntoView).toHaveBeenCalledTimes(1);
|
||||
expect(scrollIntoView.mock.instances[0]).toBe(secondFootnote);
|
||||
expect(window.location.hash).toBe(secondReference?.hash);
|
||||
|
||||
const secondBackref = secondRoot?.querySelector<HTMLAnchorElement>(
|
||||
"a[data-footnote-backref]",
|
||||
);
|
||||
expect(secondBackref).not.toBeNull();
|
||||
secondBackref?.click();
|
||||
|
||||
const secondReferenceTarget = secondReference?.closest<HTMLElement>("[id]");
|
||||
expect(scrollIntoView).toHaveBeenCalledTimes(2);
|
||||
expect(scrollIntoView.mock.instances[1]).toBe(secondReferenceTarget);
|
||||
} finally {
|
||||
scrollIntoView.mockRestore();
|
||||
window.history.replaceState(window.history.state, "", originalUrl);
|
||||
await screen.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
describe("code block chrome", () => {
|
||||
it("shows icon-only language titles, text fallbacks, and filename overrides", async () => {
|
||||
const source = [
|
||||
"```ts",
|
||||
"const a = 1;",
|
||||
"```",
|
||||
"",
|
||||
'```ts title="src/main.ts"',
|
||||
"const b = 2;",
|
||||
"```",
|
||||
"",
|
||||
"```text",
|
||||
"plain",
|
||||
"```",
|
||||
].join("\n");
|
||||
const screen = await render(<ChatMarkdown text={source} cwd="/repo/project" />);
|
||||
|
||||
try {
|
||||
const titles = [...document.querySelectorAll(".chat-markdown-codeblock-title")];
|
||||
expect(titles).toHaveLength(3);
|
||||
|
||||
// Language with a known icon: icon XOR text — never the redundant pair.
|
||||
const languageOnly = titles[0]!;
|
||||
const hasIcon = languageOnly.querySelector("img") != null;
|
||||
const hasText = (languageOnly.textContent ?? "").includes("ts");
|
||||
expect(hasIcon || hasText).toBe(true);
|
||||
expect(hasIcon && hasText).toBe(false);
|
||||
if (hasIcon) {
|
||||
const languageTrigger = page.getByLabelText("Language: ts").first();
|
||||
await languageTrigger.hover();
|
||||
await vi.waitFor(() => {
|
||||
const tooltip = document.querySelector<HTMLElement>('[data-slot="tooltip-popup"]');
|
||||
expect(tooltip?.textContent).toContain("ts");
|
||||
});
|
||||
}
|
||||
|
||||
// Explicit filename: text always shown.
|
||||
expect(titles[1]!.textContent).toBe("src/main.ts");
|
||||
|
||||
// Unknown language: no icon attempt, text label.
|
||||
expect(titles[2]!.querySelector("img")).toBeNull();
|
||||
expect(titles[2]!.textContent).toBe("text");
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
it("toggles line wrapping per block", async () => {
|
||||
const screen = await render(
|
||||
<ChatMarkdown text={'```ts\nconst x = "long";\n```'} cwd="/repo/project" />,
|
||||
);
|
||||
|
||||
try {
|
||||
const block = document.querySelector(".chat-markdown-codeblock");
|
||||
expect(block?.getAttribute("data-wrap")).toBe("false");
|
||||
|
||||
const toggle = page.getByRole("button", { name: "Wrap lines" });
|
||||
await expect.element(toggle).not.toHaveAttribute("title");
|
||||
await toggle.hover();
|
||||
await vi.waitFor(() => {
|
||||
const tooltip = document.querySelector<HTMLElement>('[data-slot="tooltip-popup"]');
|
||||
expect(tooltip?.textContent).toContain("Wrap lines");
|
||||
});
|
||||
await toggle.click();
|
||||
expect(block?.getAttribute("data-wrap")).toBe("true");
|
||||
|
||||
await page.getByRole("button", { name: "Disable line wrap" }).click();
|
||||
expect(block?.getAttribute("data-wrap")).toBe("false");
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it("scrolls wide tables horizontally instead of letter-wrapping cells", async () => {
|
||||
const header = `| ${Array.from({ length: 8 }, (_, i) => `ColumnHeading${i}`).join(" | ")} |`;
|
||||
const separator = `| ${Array.from({ length: 8 }, () => "---").join(" | ")} |`;
|
||||
const row = `| ${Array.from({ length: 8 }, () => "[email protected]").join(" | ")} |`;
|
||||
const screen = await render(
|
||||
<ChatMarkdown text={[header, separator, row].join("\n")} cwd="/repo/project" />,
|
||||
);
|
||||
|
||||
try {
|
||||
const viewport = document.querySelector(
|
||||
'.chat-markdown-table-container [data-slot="scroll-area-viewport"]',
|
||||
);
|
||||
expect(viewport).not.toBeNull();
|
||||
expect(viewport!.querySelector("table")).not.toBeNull();
|
||||
// Content exceeds the container — the scroll-fade viewport scrolls
|
||||
// horizontally rather than squishing columns.
|
||||
expect(viewport!.scrollWidth).toBeGreaterThan(viewport!.clientWidth);
|
||||
// And cells keep their longest word intact instead of breaking mid-word.
|
||||
const cell = viewport!.querySelector("td");
|
||||
expect(cell!.getBoundingClientRect().width).toBeGreaterThan(100);
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
describe("table chrome", () => {
|
||||
const longCell =
|
||||
"This service has been experiencing intermittent latency spikes during peak traffic hours and the on-call team is investigating.";
|
||||
|
||||
it("truncates cells by default and expands them from the footer toggle", async () => {
|
||||
const source = ["| Name | Notes |", "| --- | --- |", `| api | ${longCell} |`].join("\n");
|
||||
const screen = await render(<ChatMarkdown text={source} cwd="/repo/project" />);
|
||||
|
||||
try {
|
||||
const container = document.querySelector(".chat-markdown-table-container");
|
||||
expect(container?.getAttribute("data-expanded")).toBe("false");
|
||||
|
||||
const noteCell = [...document.querySelectorAll(".chat-markdown td")].at(-1)!;
|
||||
expect(getComputedStyle(noteCell).whiteSpace).toBe("nowrap");
|
||||
expect(noteCell.scrollWidth).toBeGreaterThan(noteCell.clientWidth);
|
||||
|
||||
const expandButton = page.getByRole("button", { name: "Expand table cells" });
|
||||
await expect.element(expandButton).not.toHaveAttribute("title");
|
||||
await expandButton.hover();
|
||||
await vi.waitFor(() => {
|
||||
const tooltip = document.querySelector<HTMLElement>('[data-slot="tooltip-popup"]');
|
||||
expect(tooltip?.textContent).toContain("Expand table cells");
|
||||
});
|
||||
await expandButton.click();
|
||||
expect(container?.getAttribute("data-expanded")).toBe("true");
|
||||
expect(getComputedStyle(noteCell).whiteSpace).not.toBe("nowrap");
|
||||
|
||||
await page.getByRole("button", { name: "Collapse table cells" }).click();
|
||||
expect(container?.getAttribute("data-expanded")).toBe("false");
|
||||
|
||||
const copyButton = page.getByRole("button", { name: "Copy table" });
|
||||
await expect.element(copyButton).not.toHaveAttribute("title");
|
||||
await copyButton.hover();
|
||||
await vi.waitFor(() => {
|
||||
const tooltip = document.querySelector<HTMLElement>('[data-slot="tooltip-popup"]');
|
||||
expect(tooltip?.textContent).toContain("Copy table");
|
||||
});
|
||||
expect(document.querySelector(".chat-markdown [title]")).toBeNull();
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
it("retains column widths when cells expand", async () => {
|
||||
const source = [
|
||||
"| ID | Owner | Status | Priority | Region | Summary | Long Description | Metrics | Payload | Notes |",
|
||||
"| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |",
|
||||
'| 1001 | Ada Lovelace | Active | High | us-west-2 | Payment workflow migration | This cell has enough text to wrap across several lines when expanded without shrinking its column. | Requests: 128,440; Error rate: 0.04%; P95: 212ms | `{ "feature": "billing", "version": 3 }` | Needs post-release monitoring for 24 hours. |',
|
||||
].join("\n");
|
||||
const screen = await render(<ChatMarkdown text={source} cwd="/repo/project" />);
|
||||
|
||||
try {
|
||||
const viewport = document.querySelector(
|
||||
'.chat-markdown-table-container [data-slot="scroll-area-viewport"]',
|
||||
)!;
|
||||
const table = viewport.querySelector("table")!;
|
||||
const collapsedWidths = [...table.querySelectorAll("thead th")].map(
|
||||
(cell) => cell.getBoundingClientRect().width,
|
||||
);
|
||||
expect(viewport.scrollWidth).toBeGreaterThan(viewport.clientWidth);
|
||||
|
||||
await page.getByRole("button", { name: "Expand table cells" }).click();
|
||||
|
||||
const expandedWidths = [...table.querySelectorAll("thead th")].map(
|
||||
(cell) => cell.getBoundingClientRect().width,
|
||||
);
|
||||
expect(expandedWidths).toHaveLength(collapsedWidths.length);
|
||||
expandedWidths.forEach((width, index) => {
|
||||
expect(width).toBeGreaterThanOrEqual(collapsedWidths[index]! - 1);
|
||||
});
|
||||
expect(viewport.scrollWidth).toBeGreaterThan(viewport.clientWidth);
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
it("exports tables as markdown and csv", async () => {
|
||||
const source = [
|
||||
"| Name | Count |",
|
||||
"| --- | ---: |",
|
||||
'| widget, "deluxe" | 2 |',
|
||||
"| plain | 1 |",
|
||||
].join("\n");
|
||||
const screen = await render(<ChatMarkdown text={source} cwd="/repo/project" />);
|
||||
|
||||
try {
|
||||
const table = document.querySelector(".chat-markdown table")!;
|
||||
expect(serializeTableElementToMarkdown(table)).toBe(
|
||||
["| Name | Count |", "| --- | ---: |", '| widget, "deluxe" | 2 |', "| plain | 1 |"].join(
|
||||
"\n",
|
||||
),
|
||||
);
|
||||
expect(serializeTableElementToCsv(table)).toBe(
|
||||
["Name,Count", '"widget, ""deluxe""",2', "plain,1"].join("\n"),
|
||||
);
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("copying rendered markdown", () => {
|
||||
function copySelectedMarkdown(): { text: string; html: string } {
|
||||
const root = document.querySelector(".chat-markdown");
|
||||
if (!root) throw new Error("chat-markdown root not rendered");
|
||||
const selection = window.getSelection();
|
||||
if (!selection) throw new Error("selection unavailable");
|
||||
selection.removeAllRanges();
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(root);
|
||||
selection.addRange(range);
|
||||
|
||||
const clipboardData = new DataTransfer();
|
||||
root.dispatchEvent(
|
||||
new ClipboardEvent("copy", { clipboardData, bubbles: true, cancelable: true }),
|
||||
);
|
||||
selection.removeAllRanges();
|
||||
return {
|
||||
text: clipboardData.getData("text/plain"),
|
||||
html: clipboardData.getData("text/html"),
|
||||
};
|
||||
}
|
||||
|
||||
it("round-trips links, emphasis, and inline code", async () => {
|
||||
const screen = await render(
|
||||
<ChatMarkdown
|
||||
text="Check out [Anthropic](https://anthropic.com), **bold**, *italic*, and `code`."
|
||||
cwd="/repo/project"
|
||||
/>,
|
||||
);
|
||||
|
||||
try {
|
||||
const { text, html } = copySelectedMarkdown();
|
||||
expect(text).toBe(
|
||||
"Check out [Anthropic](https://anthropic.com), **bold**, *italic*, and `code`.",
|
||||
);
|
||||
expect(html).toContain('href="https://anthropic.com"');
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
it("round-trips block structure: headings, lists, quotes, and fences", async () => {
|
||||
const source = [
|
||||
"## Heading",
|
||||
"",
|
||||
"- first",
|
||||
"- second",
|
||||
" - nested",
|
||||
"",
|
||||
"1. one",
|
||||
"2. two",
|
||||
"",
|
||||
"- [x] done",
|
||||
"- [ ] todo",
|
||||
"",
|
||||
"> quoted",
|
||||
"",
|
||||
"```ts",
|
||||
"const x = 1;",
|
||||
"",
|
||||
"const y = 2;",
|
||||
"```",
|
||||
].join("\n");
|
||||
const screen = await render(<ChatMarkdown text={source} cwd="/repo/project" />);
|
||||
|
||||
try {
|
||||
const { text } = copySelectedMarkdown();
|
||||
expect(text).toBe(source);
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
it("round-trips tables with alignment", async () => {
|
||||
const source = ["| Name | Count |", "| --- | ---: |", "| a | 1 |", "| b | 2 |"].join("\n");
|
||||
const screen = await render(<ChatMarkdown text={source} cwd="/repo/project" />);
|
||||
|
||||
try {
|
||||
const { text } = copySelectedMarkdown();
|
||||
expect(text).toBe(source);
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
it("round-trips details rendered through the collapsible", async () => {
|
||||
const source = [
|
||||
"<details open>",
|
||||
"<summary>Expandable details section</summary>",
|
||||
"",
|
||||
"This content includes **formatted text**.",
|
||||
"</details>",
|
||||
].join("\n");
|
||||
const screen = await render(<ChatMarkdown text={source} cwd="/repo/project" />);
|
||||
|
||||
try {
|
||||
const { text } = copySelectedMarkdown();
|
||||
expect(text).toBe(source);
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
it("excludes the code block header chrome from copied markdown", async () => {
|
||||
const source = ["```ts", "const x = 1;", "```"].join("\n");
|
||||
const screen = await render(<ChatMarkdown text={source} cwd="/repo/project" />);
|
||||
|
||||
try {
|
||||
const { text } = copySelectedMarkdown();
|
||||
expect(text).toBe(source);
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
it("copies file links as markdown and skips UI affordances", async () => {
|
||||
const filePath = "/Users/yashsingh/p/t3code/src/utils/permissions/PermissionRule.ts";
|
||||
const screen = await render(
|
||||
<ChatMarkdown
|
||||
text={`See [PermissionRule.ts](file://${filePath}) for details.`}
|
||||
cwd="/repo/project"
|
||||
/>,
|
||||
);
|
||||
|
||||
try {
|
||||
const { text, html } = copySelectedMarkdown();
|
||||
expect(text).toBe(
|
||||
`See [PermissionRule.ts](/Users/yashsingh/p/t3code/src/utils/permissions/PermissionRule.ts) for details.`,
|
||||
);
|
||||
expect(html).toContain("PermissionRule.ts");
|
||||
expect(html).not.toContain("<img");
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
it("copies skill and file chips with source encodings that recreate composer chips", async () => {
|
||||
const source =
|
||||
"Use $agent-browser with [package.json](path/to/package.json) before continuing.";
|
||||
const screen = await render(
|
||||
<ChatMarkdown
|
||||
text={source}
|
||||
cwd="/repo/project"
|
||||
skills={[{ name: "agent-browser", displayName: "Agent Browser" }]}
|
||||
/>,
|
||||
);
|
||||
|
||||
try {
|
||||
const root = document.querySelector(".chat-markdown")!;
|
||||
const selection = window.getSelection()!;
|
||||
selection.removeAllRanges();
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(root);
|
||||
selection.addRange(range);
|
||||
expect(selection.toString()).toContain("Agent Browser");
|
||||
expect(selection.toString()).toContain("package.json");
|
||||
selection.removeAllRanges();
|
||||
|
||||
const { text, html } = copySelectedMarkdown();
|
||||
expect(text).toBe(source);
|
||||
expect(html).toContain("Agent Browser");
|
||||
expect(html).toContain("package.json");
|
||||
expect(html).not.toContain("<img");
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,18 @@
|
||||
import { DiffsHighlighter, getSharedHighlighter, SupportedLanguages } from "@pierre/diffs";
|
||||
import { CheckIcon, CopyIcon } from "lucide-react";
|
||||
import {
|
||||
CheckIcon,
|
||||
ChevronRightIcon,
|
||||
CopyIcon,
|
||||
GlobeIcon,
|
||||
Maximize2Icon,
|
||||
Minimize2Icon,
|
||||
WrapTextIcon,
|
||||
} from "lucide-react";
|
||||
import type { ServerProviderSkill } from "@t3tools/contracts";
|
||||
import React, {
|
||||
Children,
|
||||
Suspense,
|
||||
type ClipboardEvent as ReactClipboardEvent,
|
||||
type MouseEvent as ReactMouseEvent,
|
||||
isValidElement,
|
||||
use,
|
||||
@@ -18,16 +27,34 @@ import React, {
|
||||
import type { Components } from "react-markdown";
|
||||
import ReactMarkdown from "react-markdown";
|
||||
import { defaultUrlTransform } from "react-markdown";
|
||||
import rehypeRaw from "rehype-raw";
|
||||
import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
|
||||
import remarkBreaks from "remark-breaks";
|
||||
import remarkGfm from "remark-gfm";
|
||||
import { VscodeEntryIcon } from "./chat/VscodeEntryIcon";
|
||||
import { renderSkillInlineMarkdownChildren } from "./chat/SkillInlineText";
|
||||
import { CHAT_FILE_TAG_CHIP_CLASS_NAME, FileTagChipContent } from "./chat/FileTagChip";
|
||||
import { VscodeEntryIcon } from "./chat/VscodeEntryIcon";
|
||||
import {
|
||||
getVscodeIconUrlForEntry,
|
||||
hasSpecificVscodeIconForFileName,
|
||||
syntheticFileNameForLanguageId,
|
||||
} from "../vscode-icons";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
import { Button } from "./ui/button";
|
||||
import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "./ui/collapsible";
|
||||
import { ScrollArea } from "./ui/scroll-area";
|
||||
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "./ui/menu";
|
||||
import { stackedThreadToast, toastManager } from "./ui/toast";
|
||||
import { openInPreferredEditor } from "../editorPreferences";
|
||||
import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
|
||||
import { fnv1a32 } from "../lib/diffRendering";
|
||||
import { LRUCache } from "../lib/lruCache";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import {
|
||||
chatMarkdownClipboardPayload,
|
||||
serializeTableElementToCsv,
|
||||
serializeTableElementToMarkdown,
|
||||
} from "../markdown-clipboard";
|
||||
import {
|
||||
normalizeMarkdownLinkDestination,
|
||||
resolveMarkdownFileLinkMeta,
|
||||
@@ -62,6 +89,9 @@ interface ChatMarkdownProps {
|
||||
cwd: string | undefined;
|
||||
isStreaming?: boolean;
|
||||
skills?: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">>;
|
||||
className?: string;
|
||||
/** Treat single newlines as hard breaks — chat-style user input. */
|
||||
lineBreaks?: boolean;
|
||||
}
|
||||
|
||||
const EMPTY_MARKDOWN_SKILLS: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">> = [];
|
||||
@@ -74,6 +104,18 @@ const highlightedCodeCache = new LRUCache<string>(
|
||||
MAX_HIGHLIGHT_CACHE_MEMORY_BYTES,
|
||||
);
|
||||
const highlighterPromiseCache = new Map<string, Promise<DiffsHighlighter>>();
|
||||
const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
|
||||
...defaultSchema,
|
||||
attributes: {
|
||||
...defaultSchema.attributes,
|
||||
"*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"),
|
||||
code: [...(defaultSchema.attributes?.code ?? []), "dataCodeMeta"],
|
||||
},
|
||||
protocols: {
|
||||
...defaultSchema.protocols,
|
||||
href: [...(defaultSchema.protocols?.href ?? []), "file"],
|
||||
},
|
||||
} satisfies Parameters<typeof rehypeSanitize>[0];
|
||||
|
||||
function extractFenceLanguage(className: string | undefined): string {
|
||||
const match = className?.match(CODE_FENCE_LANGUAGE_REGEX);
|
||||
@@ -82,6 +124,64 @@ function extractFenceLanguage(className: string | undefined): string {
|
||||
return raw === "gitignore" ? "ini" : raw;
|
||||
}
|
||||
|
||||
const FENCE_TITLE_ATTR_REGEX = /(?:^|\s)(?:title|file(?:name)?)=(?:"([^"]+)"|'([^']+)'|(\S+))/i;
|
||||
const FENCE_FILENAME_TOKEN_REGEX = /^[\w@][\w@./-]*\.[A-Za-z0-9]+$/;
|
||||
|
||||
/** Pulls a filename out of fence meta: ```ts title="x.ts" / ```ts src/main.ts */
|
||||
function extractFenceTitle(meta: string | undefined): string | null {
|
||||
if (!meta) return null;
|
||||
const attrMatch = FENCE_TITLE_ATTR_REGEX.exec(meta);
|
||||
const attrTitle = attrMatch?.[1] ?? attrMatch?.[2] ?? attrMatch?.[3];
|
||||
if (attrTitle) return attrTitle;
|
||||
return meta.split(/\s+/).find((candidate) => FENCE_FILENAME_TOKEN_REGEX.test(candidate)) ?? null;
|
||||
}
|
||||
|
||||
function extractPreCodeMeta(node: unknown): string | undefined {
|
||||
const children = (
|
||||
node as
|
||||
| {
|
||||
children?: Array<{
|
||||
type?: string;
|
||||
tagName?: string;
|
||||
data?: { meta?: unknown };
|
||||
properties?: { dataCodeMeta?: unknown };
|
||||
}>;
|
||||
}
|
||||
| undefined
|
||||
)?.children;
|
||||
const codeNode = children?.find((child) => child?.type === "element" && child.tagName === "code");
|
||||
const meta = codeNode?.properties?.dataCodeMeta ?? codeNode?.data?.meta;
|
||||
return typeof meta === "string" && meta.trim().length > 0 ? meta.trim() : undefined;
|
||||
}
|
||||
|
||||
type MarkdownAstNode = {
|
||||
type?: string;
|
||||
meta?: unknown;
|
||||
data?: {
|
||||
hProperties?: Record<string, unknown>;
|
||||
};
|
||||
children?: MarkdownAstNode[];
|
||||
};
|
||||
|
||||
function remarkPreserveCodeMeta() {
|
||||
return (tree: MarkdownAstNode) => {
|
||||
const visit = (node: MarkdownAstNode) => {
|
||||
if (node.type === "code" && typeof node.meta === "string" && node.meta.trim().length > 0) {
|
||||
node.data = {
|
||||
...node.data,
|
||||
hProperties: {
|
||||
...node.data?.hProperties,
|
||||
dataCodeMeta: node.meta.trim(),
|
||||
},
|
||||
};
|
||||
}
|
||||
node.children?.forEach(visit);
|
||||
};
|
||||
|
||||
visit(tree);
|
||||
};
|
||||
}
|
||||
|
||||
function nodeToPlainText(node: ReactNode): string {
|
||||
if (typeof node === "string" || typeof node === "number") {
|
||||
return String(node);
|
||||
@@ -146,9 +246,254 @@ function getHighlighterPromise(language: string): Promise<DiffsHighlighter> {
|
||||
return promise;
|
||||
}
|
||||
|
||||
function MarkdownCodeBlock({ code, children }: { code: string; children: ReactNode }) {
|
||||
function MarkdownTable({ children, ...props }: React.ComponentProps<"table">) {
|
||||
const containerRef = useRef<HTMLDivElement | null>(null);
|
||||
const tableRef = useRef<HTMLTableElement | null>(null);
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const [copied, setCopied] = useState(false);
|
||||
const copiedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const expandLabel = expanded ? "Collapse table cells" : "Expand table cells";
|
||||
const copyLabel = copied ? "Copied" : "Copy table";
|
||||
|
||||
function toggleExpanded() {
|
||||
const table = tableRef.current;
|
||||
if (!table) return;
|
||||
|
||||
if (!expanded) {
|
||||
const rows = [...table.rows];
|
||||
const columnWidths = rows.reduce<number[]>((widths, row) => {
|
||||
[...row.cells].forEach((cell, columnIndex) => {
|
||||
widths[columnIndex] = Math.max(
|
||||
widths[columnIndex] ?? 0,
|
||||
cell.getBoundingClientRect().width,
|
||||
);
|
||||
});
|
||||
return widths;
|
||||
}, []);
|
||||
|
||||
[...(table.tHead?.rows[0]?.cells ?? [])].forEach((cell, columnIndex) => {
|
||||
cell.style.minWidth = `${columnWidths[columnIndex] ?? cell.getBoundingClientRect().width}px`;
|
||||
});
|
||||
}
|
||||
|
||||
setExpanded((value) => !value);
|
||||
}
|
||||
|
||||
const handleCopy = useCallback((format: "markdown" | "csv") => {
|
||||
const table = containerRef.current?.querySelector("table");
|
||||
if (!table || typeof navigator === "undefined" || navigator.clipboard == null) {
|
||||
return;
|
||||
}
|
||||
const text =
|
||||
format === "markdown"
|
||||
? serializeTableElementToMarkdown(table)
|
||||
: serializeTableElementToCsv(table);
|
||||
void navigator.clipboard
|
||||
.writeText(text)
|
||||
.then(() => {
|
||||
if (copiedTimerRef.current != null) {
|
||||
clearTimeout(copiedTimerRef.current);
|
||||
}
|
||||
setCopied(true);
|
||||
copiedTimerRef.current = setTimeout(() => {
|
||||
setCopied(false);
|
||||
copiedTimerRef.current = null;
|
||||
}, 1200);
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}, []);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (copiedTimerRef.current != null) {
|
||||
clearTimeout(copiedTimerRef.current);
|
||||
copiedTimerRef.current = null;
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
className="chat-markdown-table-container"
|
||||
data-expanded={expanded ? "true" : "false"}
|
||||
>
|
||||
<ScrollArea
|
||||
chainVerticalScroll
|
||||
scrollFade
|
||||
hideScrollbars
|
||||
className="w-full max-w-full rounded-none"
|
||||
>
|
||||
<table ref={tableRef} {...props}>
|
||||
{children}
|
||||
</table>
|
||||
</ScrollArea>
|
||||
<div className="chat-markdown-table-footer select-none">
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
className="chat-markdown-chrome-action"
|
||||
aria-pressed={expanded}
|
||||
onClick={toggleExpanded}
|
||||
aria-label={expandLabel}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{expanded ? <Minimize2Icon className="size-3" /> : <Maximize2Icon className="size-3" />}
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">{expandLabel}</TooltipPopup>
|
||||
</Tooltip>
|
||||
<Menu>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<MenuTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
className="chat-markdown-chrome-action"
|
||||
aria-label={copyLabel}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{copied ? <CheckIcon className="size-3" /> : <CopyIcon className="size-3" />}
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">{copyLabel}</TooltipPopup>
|
||||
</Tooltip>
|
||||
<MenuPopup align="end">
|
||||
<MenuItem onClick={() => handleCopy("markdown")}>Copy as Markdown</MenuItem>
|
||||
<MenuItem onClick={() => handleCopy("csv")}>Copy as CSV</MenuItem>
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MarkdownDetails({
|
||||
children,
|
||||
open = false,
|
||||
}: Pick<React.ComponentProps<"details">, "children" | "open">) {
|
||||
const [isOpen, setIsOpen] = useState(open);
|
||||
const childNodes = Children.toArray(children);
|
||||
const summaryIndex = childNodes.findIndex(
|
||||
(child) => isValidElement(child) && child.type === "summary",
|
||||
);
|
||||
const summaryNode = summaryIndex >= 0 ? childNodes[summaryIndex] : null;
|
||||
const summary =
|
||||
isValidElement<{ children?: ReactNode }>(summaryNode) && summaryNode.props.children
|
||||
? summaryNode.props.children
|
||||
: "Details";
|
||||
const content = childNodes.filter((_, index) => index !== summaryIndex);
|
||||
|
||||
return (
|
||||
<Collapsible
|
||||
defaultOpen={open}
|
||||
onOpenChange={setIsOpen}
|
||||
className="chat-markdown-details my-2 border-y border-border/60"
|
||||
data-markdown-details=""
|
||||
data-markdown-details-open={isOpen ? "true" : "false"}
|
||||
>
|
||||
<CollapsibleTrigger
|
||||
className="flex w-full items-center gap-2 py-2 text-left text-sm font-medium text-foreground data-panel-open:[&_svg]:rotate-90"
|
||||
data-markdown-details-summary=""
|
||||
>
|
||||
<ChevronRightIcon
|
||||
className="size-4 shrink-0 text-muted-foreground transition-transform"
|
||||
aria-hidden
|
||||
/>
|
||||
<span>{summary}</span>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsiblePanel>
|
||||
<div className="pb-3 ps-6 text-foreground/80" data-markdown-details-content="">
|
||||
{content}
|
||||
</div>
|
||||
</CollapsiblePanel>
|
||||
</Collapsible>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Filename titles render icon + text; language-only titles render just the
|
||||
* icon (redundant next to its own name) and fall back to the language text
|
||||
* when no specific icon exists or it fails to load.
|
||||
*/
|
||||
function MarkdownCodeBlockTitleContent({
|
||||
fenceTitle,
|
||||
language,
|
||||
theme,
|
||||
}: {
|
||||
fenceTitle: string | null;
|
||||
language: string;
|
||||
theme: "light" | "dark";
|
||||
}) {
|
||||
const [failedIconUrl, setFailedIconUrl] = useState<string | null>(null);
|
||||
|
||||
if (fenceTitle) {
|
||||
return (
|
||||
<>
|
||||
<VscodeEntryIcon pathValue={fenceTitle} kind="file" theme={theme} className="size-3.5" />
|
||||
<span className="truncate">{fenceTitle}</span>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const fileName = syntheticFileNameForLanguageId(language);
|
||||
const iconUrl = hasSpecificVscodeIconForFileName(fileName, theme)
|
||||
? getVscodeIconUrlForEntry(fileName, "file", theme)
|
||||
: null;
|
||||
if (!iconUrl || failedIconUrl === iconUrl) {
|
||||
return <span className="truncate">{language}</span>;
|
||||
}
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<span className="inline-flex shrink-0 rounded-sm" aria-label={`Language: ${language}`} />
|
||||
}
|
||||
>
|
||||
<img
|
||||
src={iconUrl}
|
||||
alt=""
|
||||
aria-hidden
|
||||
className="size-3.5 shrink-0"
|
||||
loading="lazy"
|
||||
draggable={false}
|
||||
onError={() => setFailedIconUrl(iconUrl)}
|
||||
/>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">{language}</TooltipPopup>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
function MarkdownCodeBlock({
|
||||
code,
|
||||
language,
|
||||
fenceTitle,
|
||||
theme,
|
||||
children,
|
||||
}: {
|
||||
code: string;
|
||||
language: string;
|
||||
fenceTitle: string | null;
|
||||
theme: "light" | "dark";
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [wrapped, setWrapped] = useState(false);
|
||||
const copiedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const wrapLabel = wrapped ? "Disable line wrap" : "Wrap lines";
|
||||
const copyLabel = copied ? "Copied" : "Copy code";
|
||||
const handleCopy = useCallback(() => {
|
||||
if (typeof navigator === "undefined" || navigator.clipboard == null) {
|
||||
return;
|
||||
@@ -179,16 +524,57 @@ function MarkdownCodeBlock({ code, children }: { code: string; children: ReactNo
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="chat-markdown-codeblock leading-snug">
|
||||
<button
|
||||
type="button"
|
||||
className="chat-markdown-copy-button"
|
||||
onClick={handleCopy}
|
||||
title={copied ? "Copied" : "Copy code"}
|
||||
aria-label={copied ? "Copied" : "Copy code"}
|
||||
>
|
||||
{copied ? <CheckIcon className="size-3" /> : <CopyIcon className="size-3" />}
|
||||
</button>
|
||||
<div
|
||||
className="chat-markdown-codeblock leading-snug"
|
||||
data-language={language}
|
||||
data-wrap={wrapped ? "true" : "false"}
|
||||
>
|
||||
<div className="chat-markdown-codeblock-header select-none">
|
||||
<span className="chat-markdown-codeblock-title">
|
||||
<MarkdownCodeBlockTitleContent
|
||||
fenceTitle={fenceTitle}
|
||||
language={language}
|
||||
theme={theme}
|
||||
/>
|
||||
</span>
|
||||
<span className="flex items-center gap-0.5">
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
className="chat-markdown-chrome-action"
|
||||
aria-pressed={wrapped}
|
||||
onClick={() => setWrapped((value) => !value)}
|
||||
aria-label={wrapLabel}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<WrapTextIcon className="size-3" />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">{wrapLabel}</TooltipPopup>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
className="chat-markdown-chrome-action"
|
||||
onClick={handleCopy}
|
||||
aria-label={copyLabel}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{copied ? <CheckIcon className="size-3" /> : <CopyIcon className="size-3" />}
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">{copyLabel}</TooltipPopup>
|
||||
</Tooltip>
|
||||
</span>
|
||||
</div>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
@@ -280,17 +666,15 @@ interface MarkdownFileLinkProps {
|
||||
href: string;
|
||||
targetPath: string;
|
||||
displayPath: string;
|
||||
filePath: string;
|
||||
label: string;
|
||||
copyMarkdown: string;
|
||||
theme: "light" | "dark";
|
||||
className?: string | undefined;
|
||||
}
|
||||
|
||||
const MARKDOWN_LINK_HREF_PATTERN = /\[[^\]]*]\(([^)\s]+)(?:\s+["'][^"']*["'])?\)/g;
|
||||
const MARKDOWN_FILE_LINK_CLASS_NAME =
|
||||
"chat-markdown-file-link relative top-[2px] max-w-full no-underline";
|
||||
const MARKDOWN_FILE_LINK_ICON_CLASS_NAME = "chat-markdown-file-link-icon size-3.5 shrink-0";
|
||||
const MARKDOWN_FILE_LINK_LABEL_CLASS_NAME = "chat-markdown-file-link-label truncate";
|
||||
"chat-markdown-file-link cursor-pointer transition-colors hover:bg-accent/70";
|
||||
|
||||
function pathParentSegments(path: string): string[] {
|
||||
const normalized = path.replaceAll("\\", "/");
|
||||
@@ -367,12 +751,196 @@ function normalizeMarkdownLinkHrefKey(href: string): string {
|
||||
return rewriteMarkdownFileUriHref(normalizedHref) ?? normalizedHref;
|
||||
}
|
||||
|
||||
const MARKDOWN_LINK_FAVICON_CLASS_NAME = "block size-full shrink-0 select-none";
|
||||
|
||||
/** Hosts whose favicon request already failed this session — skip straight to the globe. */
|
||||
const failedFaviconHosts = new Set<string>();
|
||||
|
||||
function resolveExternalLinkHost(href: string | undefined): string | null {
|
||||
if (!href) return null;
|
||||
try {
|
||||
const url = new URL(href);
|
||||
if (url.protocol !== "http:" && url.protocol !== "https:") return null;
|
||||
return url.hostname || null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const MarkdownLinkFavicon = memo(function MarkdownLinkFavicon({ host }: { host: string }) {
|
||||
const [failedHost, setFailedHost] = useState<string | null>(null);
|
||||
return (
|
||||
<span className="chat-markdown-link-favicon" aria-hidden>
|
||||
{failedHost === host || failedFaviconHosts.has(host) ? (
|
||||
<GlobeIcon className={MARKDOWN_LINK_FAVICON_CLASS_NAME} />
|
||||
) : (
|
||||
<img
|
||||
src={`https://www.google.com/s2/favicons?domain=${encodeURIComponent(host)}&sz=32`}
|
||||
alt=""
|
||||
loading="lazy"
|
||||
draggable={false}
|
||||
className={cn(MARKDOWN_LINK_FAVICON_CLASS_NAME, "rounded-sm")}
|
||||
onError={() => {
|
||||
failedFaviconHosts.add(host);
|
||||
setFailedHost(host);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
});
|
||||
|
||||
function leadingExternalLinkTextLength(text: string): number {
|
||||
const protocol = /^(?:https?:\/\/)/i.exec(text)?.[0];
|
||||
if (protocol) return protocol.length;
|
||||
return Math.min(text.length, 1);
|
||||
}
|
||||
|
||||
function breakableExternalLinkText(text: string): ReactNode[] {
|
||||
return Array.from(text, (character, index) => (
|
||||
<React.Fragment key={`${index}:${character}`}>
|
||||
{character}
|
||||
<wbr />
|
||||
</React.Fragment>
|
||||
));
|
||||
}
|
||||
|
||||
function plainHastText(node: unknown): string | null {
|
||||
if (!node || typeof node !== "object" || !("children" in node) || !Array.isArray(node.children)) {
|
||||
return null;
|
||||
}
|
||||
const parts = node.children.map((child) => {
|
||||
if (
|
||||
child &&
|
||||
typeof child === "object" &&
|
||||
"type" in child &&
|
||||
child.type === "text" &&
|
||||
"value" in child &&
|
||||
typeof child.value === "string"
|
||||
) {
|
||||
return child.value;
|
||||
}
|
||||
return null;
|
||||
});
|
||||
return parts.every((part) => part !== null) ? parts.join("") : null;
|
||||
}
|
||||
|
||||
const SANITIZED_FRAGMENT_PREFIX = "user-content-";
|
||||
|
||||
function decodeMarkdownFragmentId(href: string): string {
|
||||
const encodedId = href.slice(1);
|
||||
try {
|
||||
return decodeURIComponent(encodedId);
|
||||
} catch {
|
||||
return encodedId;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeSanitizedFragmentId(id: string): string {
|
||||
let normalizedId = id;
|
||||
while (normalizedId.startsWith(SANITIZED_FRAGMENT_PREFIX)) {
|
||||
normalizedId = normalizedId.slice(SANITIZED_FRAGMENT_PREFIX.length);
|
||||
}
|
||||
return normalizedId;
|
||||
}
|
||||
|
||||
function findMarkdownFragmentTarget(anchor: HTMLAnchorElement, href: string): HTMLElement | null {
|
||||
const decodedId = decodeMarkdownFragmentId(href);
|
||||
const normalizedId = normalizeSanitizedFragmentId(decodedId);
|
||||
const matchesFragment = (element: HTMLElement) =>
|
||||
element.id === decodedId || normalizeSanitizedFragmentId(element.id) === normalizedId;
|
||||
const markdownRoot = anchor.closest<HTMLElement>(".chat-markdown");
|
||||
if (markdownRoot) {
|
||||
const localTargets = Array.from(markdownRoot.querySelectorAll<HTMLElement>("[id]"));
|
||||
const localTarget = localTargets.find(matchesFragment);
|
||||
if (localTarget) return localTarget;
|
||||
}
|
||||
|
||||
return (
|
||||
document.getElementById(decodedId) ??
|
||||
Array.from(document.querySelectorAll<HTMLElement>("[id]")).find(matchesFragment) ??
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
function handleMarkdownFragmentClick(event: ReactMouseEvent<HTMLAnchorElement>, href: string) {
|
||||
if (
|
||||
event.defaultPrevented ||
|
||||
event.button !== 0 ||
|
||||
event.metaKey ||
|
||||
event.ctrlKey ||
|
||||
event.shiftKey ||
|
||||
event.altKey
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const target = findMarkdownFragmentTarget(event.currentTarget, href);
|
||||
if (!target) return;
|
||||
|
||||
event.preventDefault();
|
||||
const nextUrl = new URL(window.location.href);
|
||||
nextUrl.hash = href.slice(1);
|
||||
window.history.pushState(window.history.state, "", nextUrl);
|
||||
target.scrollIntoView({ block: "nearest" });
|
||||
}
|
||||
|
||||
function MarkdownExternalLinkContent({
|
||||
host,
|
||||
plainText,
|
||||
children,
|
||||
}: {
|
||||
host: string;
|
||||
plainText: string | null;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
if (plainText) {
|
||||
const leadingLength = leadingExternalLinkTextLength(plainText);
|
||||
return (
|
||||
<>
|
||||
<span className="chat-markdown-link-leading">
|
||||
<MarkdownLinkFavicon host={host} />
|
||||
{plainText.slice(0, leadingLength)}
|
||||
</span>
|
||||
{breakableExternalLinkText(plainText.slice(leadingLength))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const childNodes = Children.toArray(children);
|
||||
const firstChild = childNodes[0];
|
||||
|
||||
if (typeof firstChild === "string" && firstChild.length > 0) {
|
||||
const leadingLength = leadingExternalLinkTextLength(firstChild);
|
||||
return (
|
||||
<>
|
||||
<span className="chat-markdown-link-leading">
|
||||
<MarkdownLinkFavicon host={host} />
|
||||
{firstChild.slice(0, leadingLength)}
|
||||
</span>
|
||||
{breakableExternalLinkText(firstChild.slice(leadingLength))}
|
||||
{childNodes.slice(1)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<span className="chat-markdown-link-leading">
|
||||
<MarkdownLinkFavicon host={host} />
|
||||
{firstChild}
|
||||
</span>
|
||||
{childNodes.slice(1)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const MarkdownFileLink = memo(function MarkdownFileLink({
|
||||
href,
|
||||
targetPath,
|
||||
displayPath,
|
||||
filePath,
|
||||
label,
|
||||
copyMarkdown,
|
||||
theme,
|
||||
className,
|
||||
}: MarkdownFileLinkProps) {
|
||||
@@ -467,7 +1035,8 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
|
||||
render={
|
||||
<a
|
||||
href={href}
|
||||
className={cn(MARKDOWN_FILE_LINK_CLASS_NAME, className)}
|
||||
className={cn(CHAT_FILE_TAG_CHIP_CLASS_NAME, MARKDOWN_FILE_LINK_CLASS_NAME, className)}
|
||||
data-markdown-copy={copyMarkdown}
|
||||
onClick={(event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
@@ -475,13 +1044,7 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
|
||||
}}
|
||||
onContextMenu={handleContextMenu}
|
||||
>
|
||||
<VscodeEntryIcon
|
||||
pathValue={filePath}
|
||||
kind="file"
|
||||
theme={theme}
|
||||
className={cn(MARKDOWN_FILE_LINK_ICON_CLASS_NAME, "text-current")}
|
||||
/>
|
||||
<span className={MARKDOWN_FILE_LINK_LABEL_CLASS_NAME}>{label}</span>
|
||||
<FileTagChipContent path={targetPath} label={label} theme={theme} selectable />
|
||||
</a>
|
||||
}
|
||||
/>
|
||||
@@ -505,8 +1068,8 @@ function areMarkdownFileLinkPropsEqual(
|
||||
previous.href === next.href &&
|
||||
previous.targetPath === next.targetPath &&
|
||||
previous.displayPath === next.displayPath &&
|
||||
previous.filePath === next.filePath &&
|
||||
previous.label === next.label &&
|
||||
previous.copyMarkdown === next.copyMarkdown &&
|
||||
previous.theme === next.theme &&
|
||||
previous.className === next.className
|
||||
);
|
||||
@@ -517,6 +1080,8 @@ function ChatMarkdown({
|
||||
cwd,
|
||||
isStreaming = false,
|
||||
skills = EMPTY_MARKDOWN_SKILLS,
|
||||
className,
|
||||
lineBreaks = false,
|
||||
}: ChatMarkdownProps) {
|
||||
const { resolvedTheme } = useTheme();
|
||||
const diffThemeName = resolveDiffThemeName(resolvedTheme);
|
||||
@@ -542,6 +1107,17 @@ function ChatMarkdown({
|
||||
const markdownUrlTransform = useCallback((href: string) => {
|
||||
return rewriteMarkdownFileUriHref(href) ?? defaultUrlTransform(href);
|
||||
}, []);
|
||||
// Re-emit highlighted content as markdown so copying out of the rendered
|
||||
// view keeps links, emphasis, lists, and code fences intact.
|
||||
const handleCopy = useCallback((event: ReactClipboardEvent<HTMLDivElement>) => {
|
||||
const selection = window.getSelection();
|
||||
if (!selection || selection.isCollapsed || !event.clipboardData) return;
|
||||
const payload = chatMarkdownClipboardPayload(selection);
|
||||
if (!payload) return;
|
||||
event.preventDefault();
|
||||
event.clipboardData.setData("text/plain", payload.text);
|
||||
event.clipboardData.setData("text/html", payload.html);
|
||||
}, []);
|
||||
const markdownComponents = useMemo<Components>(
|
||||
() => ({
|
||||
p({ node: _node, children, ...props }) {
|
||||
@@ -550,11 +1126,49 @@ function ChatMarkdown({
|
||||
li({ node: _node, children, ...props }) {
|
||||
return <li {...props}>{renderSkillInlineMarkdownChildren(children, skills)}</li>;
|
||||
},
|
||||
a({ node: _node, href, ...props }) {
|
||||
a({ node, href, children, ...props }) {
|
||||
const normalizedHref = href ? normalizeMarkdownLinkHrefKey(href) : "";
|
||||
const fileLinkMeta = normalizedHref ? markdownFileLinkMetaByHref.get(normalizedHref) : null;
|
||||
if (!fileLinkMeta) {
|
||||
return <a {...props} href={href} target="_blank" rel="noopener noreferrer" />;
|
||||
const faviconHost = resolveExternalLinkHost(href);
|
||||
const isSameDocumentLink = href?.startsWith("#") ?? false;
|
||||
const onClick = props.onClick;
|
||||
const link = (
|
||||
<a
|
||||
{...props}
|
||||
href={href}
|
||||
target={isSameDocumentLink ? undefined : "_blank"}
|
||||
rel={isSameDocumentLink ? undefined : "noopener noreferrer"}
|
||||
onClick={(event) => {
|
||||
onClick?.(event);
|
||||
if (isSameDocumentLink && href) {
|
||||
handleMarkdownFragmentClick(event, href);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{faviconHost ? (
|
||||
<MarkdownExternalLinkContent host={faviconHost} plainText={plainHastText(node)}>
|
||||
{children}
|
||||
</MarkdownExternalLinkContent>
|
||||
) : (
|
||||
children
|
||||
)}
|
||||
</a>
|
||||
);
|
||||
if (!faviconHost || !href) {
|
||||
return link;
|
||||
}
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger render={link} />
|
||||
<TooltipPopup
|
||||
side="top"
|
||||
className="max-w-[min(36rem,calc(100vw-2rem))] whitespace-normal leading-tight wrap-anywhere"
|
||||
>
|
||||
{href}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
const parentSuffix = fileLinkParentSuffixByPath.get(fileLinkMeta.filePath);
|
||||
@@ -573,21 +1187,34 @@ function ChatMarkdown({
|
||||
href={fileLinkMeta.targetPath}
|
||||
targetPath={fileLinkMeta.targetPath}
|
||||
displayPath={fileLinkMeta.displayPath}
|
||||
filePath={fileLinkMeta.filePath}
|
||||
label={labelParts.join(" · ")}
|
||||
copyMarkdown={`[${fileLinkMeta.basename}](${normalizedHref})`}
|
||||
theme={resolvedTheme}
|
||||
className={props.className}
|
||||
/>
|
||||
);
|
||||
},
|
||||
pre({ node: _node, children, ...props }) {
|
||||
table({ node: _node, ...props }) {
|
||||
return <MarkdownTable {...props} />;
|
||||
},
|
||||
details({ node: _node, children, open: detailsOpen }) {
|
||||
return <MarkdownDetails open={detailsOpen}>{children}</MarkdownDetails>;
|
||||
},
|
||||
pre({ node, children, ...props }) {
|
||||
const codeBlock = extractCodeBlock(children);
|
||||
if (!codeBlock) {
|
||||
return <pre {...props}>{children}</pre>;
|
||||
}
|
||||
|
||||
const language = extractFenceLanguage(codeBlock.className);
|
||||
const fenceTitle = extractFenceTitle(extractPreCodeMeta(node));
|
||||
return (
|
||||
<MarkdownCodeBlock code={codeBlock.code}>
|
||||
<MarkdownCodeBlock
|
||||
code={codeBlock.code}
|
||||
language={language}
|
||||
fenceTitle={fenceTitle}
|
||||
theme={resolvedTheme}
|
||||
>
|
||||
<CodeHighlightErrorBoundary fallback={<pre {...props}>{children}</pre>}>
|
||||
<Suspense fallback={<pre {...props}>{children}</pre>}>
|
||||
<SuspenseShikiCodeBlock
|
||||
@@ -613,9 +1240,20 @@ function ChatMarkdown({
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="chat-markdown w-full min-w-0 text-sm leading-relaxed text-foreground/80">
|
||||
<div
|
||||
className={cn(
|
||||
"chat-markdown w-full min-w-0 text-sm leading-relaxed text-foreground/80",
|
||||
className,
|
||||
)}
|
||||
onCopy={handleCopy}
|
||||
>
|
||||
<ReactMarkdown
|
||||
remarkPlugins={[remarkGfm]}
|
||||
remarkPlugins={
|
||||
lineBreaks
|
||||
? [remarkGfm, remarkBreaks, remarkPreserveCodeMeta]
|
||||
: [remarkGfm, remarkPreserveCodeMeta]
|
||||
}
|
||||
rehypePlugins={[rehypeRaw, [rehypeSanitize, CHAT_MARKDOWN_SANITIZE_SCHEMA]]}
|
||||
components={markdownComponents}
|
||||
urlTransform={markdownUrlTransform}
|
||||
>
|
||||
|
||||
@@ -2341,7 +2341,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
const runButton = await waitForElement(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll("button")).find(
|
||||
(button) => button.title === "Run Lint",
|
||||
(button) => button.getAttribute("aria-label") === "Run Lint",
|
||||
) as HTMLButtonElement | null,
|
||||
"Unable to find Run Lint button.",
|
||||
);
|
||||
@@ -2420,7 +2420,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
const runButton = await waitForElement(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll("button")).find(
|
||||
(button) => button.title === "Run Test",
|
||||
(button) => button.getAttribute("aria-label") === "Run Test",
|
||||
) as HTMLButtonElement | null,
|
||||
"Unable to find Run Test button.",
|
||||
);
|
||||
@@ -3160,7 +3160,8 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
|
||||
try {
|
||||
const initialModeButton = await waitForInteractionModeButton("Build");
|
||||
expect(initialModeButton.title).toContain("enter plan mode");
|
||||
expect(initialModeButton.getAttribute("aria-label")).toContain("enter plan mode");
|
||||
expect(initialModeButton.hasAttribute("title")).toBe(false);
|
||||
|
||||
window.dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
@@ -3172,7 +3173,9 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
);
|
||||
await waitForLayout();
|
||||
|
||||
expect((await waitForInteractionModeButton("Build")).title).toContain("enter plan mode");
|
||||
expect((await waitForInteractionModeButton("Build")).getAttribute("aria-label")).toContain(
|
||||
"enter plan mode",
|
||||
);
|
||||
|
||||
const composerEditor = await waitForComposerEditor();
|
||||
composerEditor.focus();
|
||||
@@ -3187,7 +3190,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
|
||||
await vi.waitFor(
|
||||
async () => {
|
||||
expect((await waitForInteractionModeButton("Plan")).title).toContain(
|
||||
expect((await waitForInteractionModeButton("Plan")).getAttribute("aria-label")).toContain(
|
||||
"return to normal build mode",
|
||||
);
|
||||
},
|
||||
@@ -3205,7 +3208,9 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
|
||||
await vi.waitFor(
|
||||
async () => {
|
||||
expect((await waitForInteractionModeButton("Build")).title).toContain("enter plan mode");
|
||||
expect(
|
||||
(await waitForInteractionModeButton("Build")).getAttribute("aria-label"),
|
||||
).toContain("enter plan mode");
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
@@ -3587,13 +3592,13 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
await waitForComposerText("hi @package.json there");
|
||||
await waitForComposerText("hi [package.json](package.json) there");
|
||||
await setComposerSelectionByTextOffsets({
|
||||
start: "hi package.json ".length,
|
||||
end: "hi package.json there".length,
|
||||
});
|
||||
await pressComposerKey("(");
|
||||
await waitForComposerText("hi @package.json (there)");
|
||||
await waitForComposerText("hi [package.json](package.json) (there)");
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
@@ -3625,6 +3630,47 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("stores selected file tags as markdown links while keeping the composer chip", async () => {
|
||||
useComposerDraftStore.getState().setPrompt(THREAD_REF, "@pack");
|
||||
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-file-tag-encoding" as MessageId,
|
||||
targetText: "file tag encoding",
|
||||
}),
|
||||
resolveRpc: (body) => {
|
||||
if (body._tag !== WS_METHODS.projectsSearchEntries) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
entries: [
|
||||
{
|
||||
path: "path/to/package.json",
|
||||
kind: "file",
|
||||
parentPath: "path/to",
|
||||
},
|
||||
],
|
||||
truncated: false,
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const item = await waitForComposerMenuItem("path:file:path/to/package.json");
|
||||
item.click();
|
||||
|
||||
await waitForComposerText("[package.json](path/to/package.json) ");
|
||||
const chip = await waitForElement(
|
||||
() => document.querySelector<HTMLElement>('[data-composer-mention-chip="true"]'),
|
||||
"Unable to find rendered composer file chip.",
|
||||
);
|
||||
expect(chip.textContent).toContain("package.json");
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("shows runtime mode descriptions in the desktop composer access select", async () => {
|
||||
setDraftThreadWithoutWorktree();
|
||||
|
||||
|
||||
@@ -1570,61 +1570,78 @@ function OpenCommandPaletteDialog() {
|
||||
onKeyDown={handleKeyDown}
|
||||
/>
|
||||
{addProjectCloneFlow?.step === "repository" ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="xs"
|
||||
tabIndex={-1}
|
||||
className="absolute inset-e-2.5 top-1/2 gap-1.5 pe-1 ps-2 -translate-y-1/2"
|
||||
aria-label={`${remoteProjectButtonLabel ?? "Continue"} (Enter)`}
|
||||
disabled={!canSubmitRemoteProjectFlow}
|
||||
onMouseDown={(event) => {
|
||||
event.preventDefault();
|
||||
}}
|
||||
onClick={() => {
|
||||
void submitAddProjectCloneFlow();
|
||||
}}
|
||||
title={`${remoteProjectButtonLabel ?? "Continue"} (Enter)`}
|
||||
>
|
||||
<span>{isRemoteProjectPending ? "Working" : remoteProjectButtonLabel}</span>
|
||||
<KbdGroup className="pointer-events-none -me-0.5 items-center gap-1">
|
||||
<Kbd>Enter</Kbd>
|
||||
</KbdGroup>
|
||||
</Button>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
variant="outline"
|
||||
size="xs"
|
||||
tabIndex={-1}
|
||||
className="absolute inset-e-2.5 top-1/2 gap-1.5 pe-1 ps-2 -translate-y-1/2"
|
||||
aria-label={`${remoteProjectButtonLabel ?? "Continue"} (Enter)`}
|
||||
disabled={!canSubmitRemoteProjectFlow}
|
||||
onMouseDown={(event) => {
|
||||
event.preventDefault();
|
||||
}}
|
||||
onClick={() => {
|
||||
void submitAddProjectCloneFlow();
|
||||
}}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<span>{isRemoteProjectPending ? "Working" : remoteProjectButtonLabel}</span>
|
||||
<KbdGroup className="pointer-events-none -me-0.5 items-center gap-1">
|
||||
<Kbd>Enter</Kbd>
|
||||
</KbdGroup>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">
|
||||
{remoteProjectButtonLabel ?? "Continue"} (Enter)
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : isBrowsing ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="xs"
|
||||
tabIndex={-1}
|
||||
className={cn(
|
||||
"absolute inset-e-2.5 top-1/2 pe-1 ps-2 -translate-y-1/2",
|
||||
hasHighlightedBrowseItem ? "gap-1" : "gap-1.5",
|
||||
)}
|
||||
aria-label={`${submitActionLabel} (${addShortcutLabel})`}
|
||||
disabled={
|
||||
relativePathNeedsActiveProject || (isCloneDestinationStep && isRemoteProjectPending)
|
||||
}
|
||||
onMouseDown={(event) => {
|
||||
event.preventDefault();
|
||||
}}
|
||||
onClick={() => {
|
||||
if (relativePathNeedsActiveProject) {
|
||||
return;
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
variant="outline"
|
||||
size="xs"
|
||||
tabIndex={-1}
|
||||
className={cn(
|
||||
"absolute inset-e-2.5 top-1/2 pe-1 ps-2 -translate-y-1/2",
|
||||
hasHighlightedBrowseItem ? "gap-1" : "gap-1.5",
|
||||
)}
|
||||
aria-label={`${submitActionLabel} (${addShortcutLabel})`}
|
||||
disabled={
|
||||
relativePathNeedsActiveProject ||
|
||||
(isCloneDestinationStep && isRemoteProjectPending)
|
||||
}
|
||||
onMouseDown={(event) => {
|
||||
event.preventDefault();
|
||||
}}
|
||||
onClick={() => {
|
||||
if (relativePathNeedsActiveProject) {
|
||||
return;
|
||||
}
|
||||
if (isCloneDestinationStep) {
|
||||
void submitAddProjectCloneFlow(resolvedAddProjectPath);
|
||||
} else {
|
||||
void handleAddProject(resolvedAddProjectPath);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
}
|
||||
if (isCloneDestinationStep) {
|
||||
void submitAddProjectCloneFlow(resolvedAddProjectPath);
|
||||
} else {
|
||||
void handleAddProject(resolvedAddProjectPath);
|
||||
}
|
||||
}}
|
||||
title={`${submitActionLabel} (${addShortcutLabel})`}
|
||||
>
|
||||
<span>
|
||||
{isCloneDestinationStep && isRemoteProjectPending ? "Cloning" : submitActionLabel}
|
||||
</span>
|
||||
<KbdGroup className="pointer-events-none -me-0.5 items-center gap-1">
|
||||
<Kbd>{hasHighlightedBrowseItem ? `${submitModifierLabel} Enter` : "Enter"}</Kbd>
|
||||
</KbdGroup>
|
||||
</Button>
|
||||
>
|
||||
<span>
|
||||
{isCloneDestinationStep && isRemoteProjectPending ? "Cloning" : submitActionLabel}
|
||||
</span>
|
||||
<KbdGroup className="pointer-events-none -me-0.5 items-center gap-1">
|
||||
<Kbd>{hasHighlightedBrowseItem ? `${submitModifierLabel} Enter` : "Enter"}</Kbd>
|
||||
</KbdGroup>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">
|
||||
{submitActionLabel} ({addShortcutLabel})
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
</div>
|
||||
<CommandPanel className="max-h-[min(28rem,70vh)]">
|
||||
|
||||
@@ -6,7 +6,7 @@ import { HistoryPlugin } from "@lexical/react/LexicalHistoryPlugin";
|
||||
import { OnChangePlugin } from "@lexical/react/LexicalOnChangePlugin";
|
||||
import { PlainTextPlugin } from "@lexical/react/LexicalPlainTextPlugin";
|
||||
import { type ServerProviderSkill } from "@t3tools/contracts";
|
||||
import { serializeComposerMentionPath } from "@t3tools/shared/composerTrigger";
|
||||
import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger";
|
||||
import {
|
||||
$applyNodeReplacement,
|
||||
$createRangeSelection,
|
||||
@@ -64,14 +64,14 @@ import {
|
||||
type TerminalContextDraft,
|
||||
} from "~/lib/terminalContext";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { basenameOfPath, getVscodeIconUrlForEntry, inferEntryKindFromPath } from "~/vscode-icons";
|
||||
import { basenameOfPath } from "~/vscode-icons";
|
||||
import {
|
||||
COMPOSER_INLINE_CHIP_CLASS_NAME,
|
||||
COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
|
||||
COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME,
|
||||
COMPOSER_INLINE_SKILL_CHIP_CLASS_NAME,
|
||||
SKILL_CHIP_ICON_SVG,
|
||||
} from "./composerInlineChip";
|
||||
import { FILE_TAG_CHIP_CLASS_NAME, FileTagChipContent } from "./chat/FileTagChip";
|
||||
import { ComposerPendingTerminalContextChip } from "./chat/ComposerPendingTerminalContexts";
|
||||
import { formatProviderSkillDisplayName } from "~/providerSkillPresentation";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
@@ -132,19 +132,12 @@ function ComposerMentionDecorator(props: { path: string }) {
|
||||
const theme = resolvedThemeFromDocument();
|
||||
const chip = (
|
||||
<span
|
||||
className={COMPOSER_INLINE_CHIP_CLASS_NAME}
|
||||
className={FILE_TAG_CHIP_CLASS_NAME}
|
||||
contentEditable={false}
|
||||
spellCheck={false}
|
||||
data-composer-mention-chip="true"
|
||||
>
|
||||
<img
|
||||
alt=""
|
||||
aria-hidden="true"
|
||||
className={COMPOSER_INLINE_CHIP_ICON_CLASS_NAME}
|
||||
loading="lazy"
|
||||
src={getVscodeIconUrlForEntry(props.path, inferEntryKindFromPath(props.path), theme)}
|
||||
/>
|
||||
<span className={COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME}>{basenameOfPath(props.path)}</span>
|
||||
<FileTagChipContent path={props.path} label={basenameOfPath(props.path)} theme={theme} />
|
||||
</span>
|
||||
);
|
||||
|
||||
@@ -175,8 +168,7 @@ class ComposerMentionNode extends DecoratorNode<React.ReactElement> {
|
||||
|
||||
constructor(path: string, key?: NodeKey) {
|
||||
super(key);
|
||||
const normalizedPath = path.startsWith("@") ? path.slice(1) : path;
|
||||
this.__path = normalizedPath;
|
||||
this.__path = path;
|
||||
}
|
||||
|
||||
override exportJSON(): SerializedComposerMentionNode {
|
||||
@@ -199,7 +191,7 @@ class ComposerMentionNode extends DecoratorNode<React.ReactElement> {
|
||||
}
|
||||
|
||||
override getTextContent(): string {
|
||||
return `@${serializeComposerMentionPath(this.__path)}`;
|
||||
return serializeComposerFileLink(this.__path);
|
||||
}
|
||||
|
||||
override isInline(): true {
|
||||
|
||||
@@ -42,6 +42,7 @@ import { useSettings } from "../hooks/useSettings";
|
||||
import { formatShortTimestamp } from "../timestampFormat";
|
||||
import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell";
|
||||
import { ToggleGroup, Toggle } from "./ui/toggle-group";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
|
||||
type DiffRenderMode = "stacked" | "split";
|
||||
type DiffThemeType = "light" | "dark";
|
||||
@@ -460,35 +461,41 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
</div>
|
||||
</button>
|
||||
{orderedTurnDiffSummaries.map((summary) => (
|
||||
<button
|
||||
key={summary.turnId}
|
||||
type="button"
|
||||
className="shrink-0 rounded-md"
|
||||
onClick={() => selectTurn(summary.turnId)}
|
||||
title={summary.turnId}
|
||||
data-turn-chip-selected={summary.turnId === selectedTurn?.turnId}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"rounded-md border px-2 py-1 text-left transition-colors",
|
||||
summary.turnId === selectedTurn?.turnId
|
||||
? "border-border bg-accent text-accent-foreground"
|
||||
: "border-border/70 bg-background/70 text-muted-foreground/80 hover:border-border hover:text-foreground/80",
|
||||
)}
|
||||
<Tooltip key={summary.turnId}>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
aria-label={summary.turnId}
|
||||
className="shrink-0 rounded-md"
|
||||
onClick={() => selectTurn(summary.turnId)}
|
||||
data-turn-chip-selected={summary.turnId === selectedTurn?.turnId}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<div className="flex items-center gap-1">
|
||||
<span className="text-[10px] leading-tight font-medium">
|
||||
Turn{" "}
|
||||
{summary.checkpointTurnCount ??
|
||||
inferredCheckpointTurnCountByTurnId[summary.turnId] ??
|
||||
"?"}
|
||||
</span>
|
||||
<span className="text-[9px] leading-tight opacity-70">
|
||||
{formatShortTimestamp(summary.completedAt, settings.timestampFormat)}
|
||||
</span>
|
||||
<div
|
||||
className={cn(
|
||||
"rounded-md border px-2 py-1 text-left transition-colors",
|
||||
summary.turnId === selectedTurn?.turnId
|
||||
? "border-border bg-accent text-accent-foreground"
|
||||
: "border-border/70 bg-background/70 text-muted-foreground/80 hover:border-border hover:text-foreground/80",
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-1">
|
||||
<span className="text-[10px] leading-tight font-medium">
|
||||
Turn{" "}
|
||||
{summary.checkpointTurnCount ??
|
||||
inferredCheckpointTurnCountByTurnId[summary.turnId] ??
|
||||
"?"}
|
||||
</span>
|
||||
<span className="text-[9px] leading-tight opacity-70">
|
||||
{formatShortTimestamp(summary.completedAt, settings.timestampFormat)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">{summary.turnId}</TooltipPopup>
|
||||
</Tooltip>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
@@ -512,30 +519,50 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
<Columns2Icon className="size-3" />
|
||||
</Toggle>
|
||||
</ToggleGroup>
|
||||
<Toggle
|
||||
aria-label={diffWordWrap ? "Disable diff line wrapping" : "Enable diff line wrapping"}
|
||||
title={diffWordWrap ? "Disable line wrapping" : "Enable line wrapping"}
|
||||
variant="outline"
|
||||
size="xs"
|
||||
pressed={diffWordWrap}
|
||||
onPressedChange={(pressed) => {
|
||||
setDiffWordWrap(Boolean(pressed));
|
||||
}}
|
||||
>
|
||||
<TextWrapIcon className="size-3" />
|
||||
</Toggle>
|
||||
<Toggle
|
||||
aria-label={diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"}
|
||||
title={diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"}
|
||||
variant="outline"
|
||||
size="xs"
|
||||
pressed={diffIgnoreWhitespace}
|
||||
onPressedChange={(pressed) => {
|
||||
setDiffIgnoreWhitespace(Boolean(pressed));
|
||||
}}
|
||||
>
|
||||
<PilcrowIcon className="size-3" />
|
||||
</Toggle>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Toggle
|
||||
aria-label={
|
||||
diffWordWrap ? "Disable diff line wrapping" : "Enable diff line wrapping"
|
||||
}
|
||||
variant="outline"
|
||||
size="xs"
|
||||
pressed={diffWordWrap}
|
||||
onPressedChange={(pressed) => {
|
||||
setDiffWordWrap(Boolean(pressed));
|
||||
}}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<TextWrapIcon className="size-3" />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">
|
||||
{diffWordWrap ? "Disable line wrapping" : "Enable line wrapping"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Toggle
|
||||
aria-label={
|
||||
diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"
|
||||
}
|
||||
variant="outline"
|
||||
size="xs"
|
||||
pressed={diffIgnoreWhitespace}
|
||||
onPressedChange={(pressed) => {
|
||||
setDiffIgnoreWhitespace(Boolean(pressed));
|
||||
}}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<PilcrowIcon className="size-3" />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">
|
||||
{diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
@@ -609,26 +636,36 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
<FileDiff
|
||||
fileDiff={fileDiff}
|
||||
renderHeaderPrefix={() => (
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
"inline-flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-sm border-0 bg-transparent p-0 transition-colors hover:bg-foreground/10 focus-visible:outline-hidden",
|
||||
getDiffCollapseIconClassName(fileDiff),
|
||||
)}
|
||||
aria-label={collapsed ? `Expand ${filePath}` : `Collapse ${filePath}`}
|
||||
aria-expanded={!collapsed}
|
||||
title={collapsed ? "Expand diff" : "Collapse diff"}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
toggleDiffFileCollapsed(fileKey);
|
||||
}}
|
||||
>
|
||||
{collapsed ? (
|
||||
<ChevronRightIcon className="size-4" />
|
||||
) : (
|
||||
<ChevronDownIcon className="size-4" />
|
||||
)}
|
||||
</button>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
"inline-flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-sm border-0 bg-transparent p-0 transition-colors hover:bg-foreground/10 focus-visible:outline-hidden",
|
||||
getDiffCollapseIconClassName(fileDiff),
|
||||
)}
|
||||
aria-label={
|
||||
collapsed ? `Expand ${filePath}` : `Collapse ${filePath}`
|
||||
}
|
||||
aria-expanded={!collapsed}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
toggleDiffFileCollapsed(fileKey);
|
||||
}}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{collapsed ? (
|
||||
<ChevronRightIcon className="size-4" />
|
||||
) : (
|
||||
<ChevronDownIcon className="size-4" />
|
||||
)}
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">
|
||||
{collapsed ? "Expand diff" : "Collapse diff"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
)}
|
||||
options={{
|
||||
collapsed,
|
||||
|
||||
@@ -53,6 +53,7 @@ import { Menu, MenuItem, MenuPopup, MenuShortcut, MenuTrigger } from "./ui/menu"
|
||||
import { Popover, PopoverPopup, PopoverTrigger } from "./ui/popover";
|
||||
import { Switch } from "./ui/switch";
|
||||
import { Textarea } from "./ui/textarea";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
|
||||
const SCRIPT_ICONS: Array<{ id: ProjectScriptIcon; label: string }> = [
|
||||
{ id: "play", label: "Play" },
|
||||
@@ -219,17 +220,24 @@ export default function ProjectScriptsControl({
|
||||
<>
|
||||
{primaryScript ? (
|
||||
<Group aria-label="Project scripts">
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() => onRunScript(primaryScript)}
|
||||
title={`Run ${primaryScript.name}`}
|
||||
>
|
||||
<ScriptIcon icon={primaryScript.icon} />
|
||||
<span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
|
||||
{primaryScript.name}
|
||||
</span>
|
||||
</Button>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
aria-label={`Run ${primaryScript.name}`}
|
||||
onClick={() => onRunScript(primaryScript)}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<ScriptIcon icon={primaryScript.icon} />
|
||||
<span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
|
||||
{primaryScript.name}
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">Run {primaryScript.name}</TooltipPopup>
|
||||
</Tooltip>
|
||||
<GroupSeparator className="hidden @3xl/header-actions:block" />
|
||||
<Menu highlightItemOnHover={false}>
|
||||
<MenuTrigger
|
||||
@@ -289,12 +297,19 @@ export default function ProjectScriptsControl({
|
||||
</Menu>
|
||||
</Group>
|
||||
) : (
|
||||
<Button size="xs" variant="outline" onClick={openAddDialog} title="Add action">
|
||||
<PlusIcon className="size-3.5" />
|
||||
<span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
|
||||
Add action
|
||||
</span>
|
||||
</Button>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button size="xs" variant="outline" aria-label="Add action" onClick={openAddDialog} />
|
||||
}
|
||||
>
|
||||
<PlusIcon className="size-3.5" />
|
||||
<span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
|
||||
Add action
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">Add action</TooltipPopup>
|
||||
</Tooltip>
|
||||
)}
|
||||
|
||||
<Dialog
|
||||
|
||||
@@ -608,14 +608,20 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
|
||||
</div>
|
||||
<div className="ml-auto flex shrink-0 items-center gap-1.5">
|
||||
{terminalStatus && (
|
||||
<span
|
||||
role="img"
|
||||
aria-label={terminalStatus.label}
|
||||
title={terminalStatus.label}
|
||||
className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
|
||||
>
|
||||
<TerminalIcon className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`} />
|
||||
</span>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<span
|
||||
role="img"
|
||||
aria-label={terminalStatus.label}
|
||||
className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<TerminalIcon className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`} />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">{terminalStatus.label}</TooltipPopup>
|
||||
</Tooltip>
|
||||
)}
|
||||
<div
|
||||
className={`flex min-w-12 justify-end ${
|
||||
@@ -691,12 +697,19 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
|
||||
</Tooltip>
|
||||
)}
|
||||
{jumpLabel ? (
|
||||
<span
|
||||
className="inline-flex h-5 items-center rounded-full border border-border/80 bg-background/90 px-1.5 font-mono text-[10px] font-medium tracking-tight text-foreground shadow-sm"
|
||||
title={jumpLabel}
|
||||
>
|
||||
{jumpLabel}
|
||||
</span>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<span
|
||||
aria-label={jumpLabel}
|
||||
className="inline-flex h-5 items-center rounded-full border border-border/80 bg-background/90 px-1.5 font-mono text-[10px] font-medium tracking-tight text-foreground shadow-sm"
|
||||
/>
|
||||
}
|
||||
>
|
||||
{jumpLabel}
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">{jumpLabel}</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<span
|
||||
className={`text-[10px] ${
|
||||
@@ -1994,20 +2007,26 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
onContextMenu={handleProjectButtonContextMenu}
|
||||
>
|
||||
{!projectExpanded && projectStatus ? (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
title={projectStatus.label}
|
||||
className={`-ml-0.5 relative inline-flex size-3.5 shrink-0 items-center justify-center ${projectStatus.colorClass}`}
|
||||
>
|
||||
<span className="absolute inset-0 flex items-center justify-center transition-opacity duration-150 group-hover/project-header:opacity-0">
|
||||
<span
|
||||
className={`size-[9px] rounded-full ${projectStatus.dotClass} ${
|
||||
projectStatus.pulse ? "animate-pulse" : ""
|
||||
}`}
|
||||
/>
|
||||
</span>
|
||||
<ChevronRightIcon className="absolute inset-0 m-auto size-3.5 text-muted-foreground/70 opacity-0 transition-opacity duration-150 group-hover/project-header:opacity-100" />
|
||||
</span>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<span
|
||||
aria-label={projectStatus.label}
|
||||
className={`-ml-0.5 relative inline-flex size-3.5 shrink-0 items-center justify-center ${projectStatus.colorClass}`}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<span className="absolute inset-0 flex items-center justify-center transition-opacity duration-150 group-hover/project-header:opacity-0">
|
||||
<span
|
||||
className={`size-[9px] rounded-full ${projectStatus.dotClass} ${
|
||||
projectStatus.pulse ? "animate-pulse" : ""
|
||||
}`}
|
||||
/>
|
||||
</span>
|
||||
<ChevronRightIcon className="absolute inset-0 m-auto size-3.5 text-muted-foreground/70 opacity-0 transition-opacity duration-150 group-hover/project-header:opacity-100" />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">{projectStatus.label}</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<ChevronRightIcon
|
||||
className={`-ml-0.5 size-3.5 shrink-0 text-muted-foreground/70 transition-transform duration-150 ${
|
||||
|
||||
@@ -102,32 +102,45 @@ export function ThreadStatusLabel({
|
||||
}) {
|
||||
if (compact) {
|
||||
return (
|
||||
<span
|
||||
title={status.label}
|
||||
className={`inline-flex size-3.5 shrink-0 items-center justify-center ${status.colorClass}`}
|
||||
>
|
||||
<span
|
||||
className={`size-[9px] rounded-full ${status.dotClass} ${
|
||||
status.pulse ? "animate-pulse" : ""
|
||||
}`}
|
||||
/>
|
||||
<span className="sr-only">{status.label}</span>
|
||||
</span>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<span
|
||||
aria-label={status.label}
|
||||
className={`inline-flex size-3.5 shrink-0 items-center justify-center ${status.colorClass}`}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<span
|
||||
className={`size-[9px] rounded-full ${status.dotClass} ${
|
||||
status.pulse ? "animate-pulse" : ""
|
||||
}`}
|
||||
/>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">{status.label}</TooltipPopup>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<span
|
||||
title={status.label}
|
||||
className={`inline-flex items-center gap-1 text-[10px] ${status.colorClass}`}
|
||||
>
|
||||
<span
|
||||
className={`h-1.5 w-1.5 rounded-full ${status.dotClass} ${
|
||||
status.pulse ? "animate-pulse" : ""
|
||||
}`}
|
||||
/>
|
||||
<span className="hidden md:inline">{status.label}</span>
|
||||
</span>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<span
|
||||
aria-label={status.label}
|
||||
className={`inline-flex items-center gap-1 text-[10px] ${status.colorClass}`}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<span
|
||||
className={`h-1.5 w-1.5 rounded-full ${status.dotClass} ${
|
||||
status.pulse ? "animate-pulse" : ""
|
||||
}`}
|
||||
/>
|
||||
<span className="hidden md:inline">{status.label}</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">{status.label}</TooltipPopup>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -220,14 +233,20 @@ export function ThreadRowTrailingStatus({ thread }: { thread: SidebarThreadSumma
|
||||
return (
|
||||
<span className="inline-flex shrink-0 items-center gap-1.5">
|
||||
{terminalStatus ? (
|
||||
<span
|
||||
role="img"
|
||||
aria-label={terminalStatus.label}
|
||||
title={terminalStatus.label}
|
||||
className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
|
||||
>
|
||||
<TerminalIcon className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`} />
|
||||
</span>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<span
|
||||
role="img"
|
||||
aria-label={terminalStatus.label}
|
||||
className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<TerminalIcon className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`} />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">{terminalStatus.label}</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
{isRemoteThread ? (
|
||||
<Tooltip>
|
||||
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
} from "@t3tools/contracts";
|
||||
import { serializeComposerMentionPath } from "@t3tools/shared/composerTrigger";
|
||||
import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger";
|
||||
import { createModelSelection, normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import {
|
||||
memo,
|
||||
@@ -187,6 +187,13 @@ const ComposerFooterModeControls = memo(function ComposerFooterModeControls(prop
|
||||
}) {
|
||||
const runtimeModeOption = runtimeModeConfig[props.runtimeMode];
|
||||
const RuntimeModeIcon = runtimeModeOption.icon;
|
||||
const interactionModeTooltip =
|
||||
props.interactionMode === "plan"
|
||||
? "Plan mode — click to return to normal build mode"
|
||||
: "Default mode — click to enter plan mode";
|
||||
const planSidebarTooltip = props.planSidebarOpen
|
||||
? `Hide ${props.planSidebarLabel.toLowerCase()} sidebar`
|
||||
: `Show ${props.planSidebarLabel.toLowerCase()} sidebar`;
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -194,86 +201,98 @@ const ComposerFooterModeControls = memo(function ComposerFooterModeControls(prop
|
||||
|
||||
{props.showInteractionModeToggle ? (
|
||||
<>
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="shrink-0 whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80 sm:px-3"
|
||||
size="sm"
|
||||
type="button"
|
||||
onClick={props.onToggleInteractionMode}
|
||||
title={
|
||||
props.interactionMode === "plan"
|
||||
? "Plan mode — click to return to normal build mode"
|
||||
: "Default mode — click to enter plan mode"
|
||||
}
|
||||
>
|
||||
<BotIcon />
|
||||
<span className="sr-only sm:not-sr-only">
|
||||
{props.interactionMode === "plan" ? "Plan" : "Build"}
|
||||
</span>
|
||||
</Button>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="shrink-0 whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80 sm:px-3"
|
||||
size="sm"
|
||||
type="button"
|
||||
onClick={props.onToggleInteractionMode}
|
||||
aria-label={interactionModeTooltip}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<BotIcon />
|
||||
<span className="sr-only sm:not-sr-only">
|
||||
{props.interactionMode === "plan" ? "Plan" : "Build"}
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">{interactionModeTooltip}</TooltipPopup>
|
||||
</Tooltip>
|
||||
|
||||
<Separator orientation="vertical" className="mx-0.5 hidden h-4 sm:block" />
|
||||
</>
|
||||
) : null}
|
||||
|
||||
<Select
|
||||
value={props.runtimeMode}
|
||||
onValueChange={(value) => props.onRuntimeModeChange(value!)}
|
||||
>
|
||||
<SelectTrigger
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="font-medium"
|
||||
aria-label="Runtime mode"
|
||||
title={runtimeModeOption.description}
|
||||
<Tooltip>
|
||||
<Select
|
||||
value={props.runtimeMode}
|
||||
onValueChange={(value) => props.onRuntimeModeChange(value!)}
|
||||
>
|
||||
<RuntimeModeIcon className="size-4" />
|
||||
<SelectValue>{runtimeModeOption.label}</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectPopup alignItemWithTrigger={false}>
|
||||
{runtimeModeOptions.map((mode) => {
|
||||
const option = runtimeModeConfig[mode];
|
||||
const OptionIcon = option.icon;
|
||||
return (
|
||||
<SelectItem key={mode} value={mode} className="min-w-64 py-2">
|
||||
<div className="grid min-w-0 gap-0.5">
|
||||
<span className="inline-flex items-center gap-1.5 font-medium text-foreground">
|
||||
<OptionIcon className="size-3.5 shrink-0 text-muted-foreground" />
|
||||
{option.label}
|
||||
</span>
|
||||
<span className="text-muted-foreground text-xs leading-4">
|
||||
{option.description}
|
||||
</span>
|
||||
</div>
|
||||
</SelectItem>
|
||||
);
|
||||
})}
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<SelectTrigger
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="font-medium"
|
||||
aria-label="Runtime mode"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<RuntimeModeIcon className="size-4" />
|
||||
<SelectValue>{runtimeModeOption.label}</SelectValue>
|
||||
</TooltipTrigger>
|
||||
<SelectPopup alignItemWithTrigger={false}>
|
||||
{runtimeModeOptions.map((mode) => {
|
||||
const option = runtimeModeConfig[mode];
|
||||
const OptionIcon = option.icon;
|
||||
return (
|
||||
<SelectItem key={mode} value={mode} className="min-w-64 py-2">
|
||||
<div className="grid min-w-0 gap-0.5">
|
||||
<span className="inline-flex items-center gap-1.5 font-medium text-foreground">
|
||||
<OptionIcon className="size-3.5 shrink-0 text-muted-foreground" />
|
||||
{option.label}
|
||||
</span>
|
||||
<span className="text-muted-foreground text-xs leading-4">
|
||||
{option.description}
|
||||
</span>
|
||||
</div>
|
||||
</SelectItem>
|
||||
);
|
||||
})}
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
<TooltipPopup side="top">{runtimeModeOption.description}</TooltipPopup>
|
||||
</Tooltip>
|
||||
|
||||
{props.showPlanToggle ? (
|
||||
<>
|
||||
<Separator orientation="vertical" className="mx-0.5 hidden h-4 sm:block" />
|
||||
<Button
|
||||
variant="ghost"
|
||||
className={cn(
|
||||
"shrink-0 whitespace-nowrap px-2 sm:px-3",
|
||||
props.planSidebarOpen
|
||||
? "text-blue-400 hover:text-blue-300"
|
||||
: "text-muted-foreground/70 hover:text-foreground/80",
|
||||
)}
|
||||
size="sm"
|
||||
type="button"
|
||||
onClick={props.onTogglePlanSidebar}
|
||||
title={
|
||||
props.planSidebarOpen
|
||||
? `Hide ${props.planSidebarLabel.toLowerCase()} sidebar`
|
||||
: `Show ${props.planSidebarLabel.toLowerCase()} sidebar`
|
||||
}
|
||||
>
|
||||
<ListTodoIcon />
|
||||
<span className="sr-only sm:not-sr-only">{props.planSidebarLabel}</span>
|
||||
</Button>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
variant="ghost"
|
||||
className={cn(
|
||||
"shrink-0 whitespace-nowrap px-2 sm:px-3",
|
||||
props.planSidebarOpen
|
||||
? "text-blue-400 hover:text-blue-300"
|
||||
: "text-muted-foreground/70 hover:text-foreground/80",
|
||||
)}
|
||||
size="sm"
|
||||
type="button"
|
||||
onClick={props.onTogglePlanSidebar}
|
||||
aria-label={planSidebarTooltip}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<ListTodoIcon />
|
||||
<span className="sr-only sm:not-sr-only">{props.planSidebarLabel}</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">{planSidebarTooltip}</TooltipPopup>
|
||||
</Tooltip>
|
||||
</>
|
||||
) : null}
|
||||
</>
|
||||
@@ -1472,7 +1491,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
const { snapshot, trigger } = resolveActiveComposerTrigger();
|
||||
if (!trigger) return;
|
||||
if (item.type === "path") {
|
||||
const replacement = `@${serializeComposerMentionPath(item.path)} `;
|
||||
const replacement = `${serializeComposerFileLink(item.path)} `;
|
||||
const replacementRangeEnd = extendReplacementRangeForTrailingSpace(
|
||||
snapshot.value,
|
||||
trigger.rangeEnd,
|
||||
|
||||
@@ -92,12 +92,19 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
<div className="@container/header-actions flex min-w-0 flex-1 flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="flex min-w-0 flex-wrap items-center gap-2 overflow-hidden sm:flex-1 sm:flex-nowrap sm:gap-3">
|
||||
<SidebarTrigger className="size-7 shrink-0 md:hidden" />
|
||||
<h2
|
||||
className="min-w-0 flex-1 basis-40 truncate text-sm font-medium text-foreground"
|
||||
title={activeThreadTitle}
|
||||
>
|
||||
{activeThreadTitle}
|
||||
</h2>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<h2
|
||||
aria-label={activeThreadTitle}
|
||||
className="min-w-0 flex-1 basis-40 truncate text-sm font-medium text-foreground"
|
||||
>
|
||||
{activeThreadTitle}
|
||||
</h2>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top">{activeThreadTitle}</TooltipPopup>
|
||||
</Tooltip>
|
||||
{activeProjectName && (
|
||||
<Badge
|
||||
variant="outline"
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { inferEntryKindFromPath } from "../../vscode-icons";
|
||||
import {
|
||||
CHAT_INLINE_CHIP_CLASS_NAME,
|
||||
CHAT_INLINE_CHIP_LABEL_CLASS_NAME,
|
||||
COMPOSER_INLINE_CHIP_CLASS_NAME,
|
||||
COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
|
||||
COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME,
|
||||
} from "../composerInlineChip";
|
||||
import { VscodeEntryIcon } from "./VscodeEntryIcon";
|
||||
|
||||
export const FILE_TAG_CHIP_CLASS_NAME = COMPOSER_INLINE_CHIP_CLASS_NAME;
|
||||
export const CHAT_FILE_TAG_CHIP_CLASS_NAME = CHAT_INLINE_CHIP_CLASS_NAME;
|
||||
|
||||
export function FileTagChipContent(props: {
|
||||
path: string;
|
||||
label: string;
|
||||
theme: "light" | "dark";
|
||||
selectable?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
<VscodeEntryIcon
|
||||
pathValue={props.path}
|
||||
kind={inferEntryKindFromPath(props.path)}
|
||||
theme={props.theme}
|
||||
className={COMPOSER_INLINE_CHIP_ICON_CLASS_NAME}
|
||||
/>
|
||||
<span
|
||||
className={
|
||||
props.selectable
|
||||
? CHAT_INLINE_CHIP_LABEL_CLASS_NAME
|
||||
: COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME
|
||||
}
|
||||
>
|
||||
{props.label}
|
||||
</span>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -94,6 +94,21 @@ function buildUserTimelineEntry(text: string) {
|
||||
};
|
||||
}
|
||||
|
||||
function buildAssistantTimelineEntry(text: string) {
|
||||
return {
|
||||
id: "entry-assistant-1",
|
||||
kind: "message" as const,
|
||||
createdAt: MESSAGE_CREATED_AT,
|
||||
message: {
|
||||
id: "message-assistant-1" as never,
|
||||
role: "assistant" as const,
|
||||
text,
|
||||
createdAt: MESSAGE_CREATED_AT,
|
||||
streaming: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("MessagesTimeline", () => {
|
||||
afterEach(() => {
|
||||
scrollToEndSpy.mockReset();
|
||||
@@ -128,6 +143,59 @@ describe("MessagesTimeline", () => {
|
||||
.element(page.getByText("Send a message to start the conversation."))
|
||||
.not.toBeInTheDocument();
|
||||
await expect.element(page.getByText("Thinking - Inspecting repository state")).toBeVisible();
|
||||
expect(document.querySelector('[data-testid="legend-list"] [title]')).toBeNull();
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
it("uses accessible tooltips instead of native titles for work entry details", async () => {
|
||||
const screen = await render(
|
||||
<MessagesTimeline
|
||||
{...buildProps()}
|
||||
workspaceRoot="/repo"
|
||||
timelineEntries={[
|
||||
{
|
||||
id: "work-command",
|
||||
kind: "work",
|
||||
createdAt: MESSAGE_CREATED_AT,
|
||||
entry: {
|
||||
id: "work-command",
|
||||
createdAt: MESSAGE_CREATED_AT,
|
||||
label: "command",
|
||||
detail: "Inspecting generated output",
|
||||
command: "git diff -- apps/web/src/components/ChatMarkdown.tsx",
|
||||
rawCommand: "git diff -- apps/web/src/components/ChatMarkdown.tsx --stat",
|
||||
changedFiles: ["/repo/apps/web/src/components/ChatMarkdown.tsx"],
|
||||
tone: "tool",
|
||||
},
|
||||
},
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
|
||||
try {
|
||||
expect(document.querySelector('[data-testid="legend-list"] [title]')).toBeNull();
|
||||
|
||||
const commandTrigger = page.getByLabelText(
|
||||
"Command - git diff -- apps/web/src/components/ChatMarkdown.tsx",
|
||||
);
|
||||
await commandTrigger.hover();
|
||||
await vi.waitFor(() => {
|
||||
const tooltip = document.querySelector<HTMLElement>('[data-slot="tooltip-popup"]');
|
||||
expect(tooltip?.textContent).toContain(
|
||||
"git diff -- apps/web/src/components/ChatMarkdown.tsx --stat",
|
||||
);
|
||||
});
|
||||
|
||||
const fileTrigger = page.getByLabelText("repo/apps/web/src/components/ChatMarkdown.tsx", {
|
||||
exact: true,
|
||||
});
|
||||
await fileTrigger.hover();
|
||||
await vi.waitFor(() => {
|
||||
const tooltip = document.querySelector<HTMLElement>('[data-slot="tooltip-popup"]');
|
||||
expect(tooltip?.textContent).toContain("apps/web/src/components/ChatMarkdown.tsx");
|
||||
});
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
}
|
||||
@@ -261,4 +329,61 @@ describe("MessagesTimeline", () => {
|
||||
await screen.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
it("renders user messages as markdown with chat-style line breaks", async () => {
|
||||
const screen = await render(
|
||||
<MessagesTimeline
|
||||
{...buildProps()}
|
||||
timelineEntries={[
|
||||
buildUserTimelineEntry(
|
||||
"## Plan\nuse **bold** and [a link](https://example.com)\nsecond line",
|
||||
),
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
|
||||
try {
|
||||
await expect.element(page.getByRole("heading", { level: 2, name: "Plan" })).toBeVisible();
|
||||
await expect
|
||||
.element(page.getByRole("link", { name: "a link" }))
|
||||
.toHaveAttribute("href", "https://example.com");
|
||||
|
||||
const messageBody = document.querySelector("[data-user-message-body='true']");
|
||||
expect(messageBody?.querySelector("strong")?.textContent).toBe("bold");
|
||||
// remark-breaks: the single newline between the inline runs is a <br>.
|
||||
expect(messageBody?.querySelectorAll("p br").length).toBe(1);
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
it("renders markdown file tags in user and assistant messages", async () => {
|
||||
const fileLink = "[package.json](path/to/package.json)";
|
||||
const screen = await render(
|
||||
<MessagesTimeline
|
||||
{...buildProps()}
|
||||
markdownCwd="/repo/project"
|
||||
timelineEntries={[
|
||||
buildUserTimelineEntry(`Review ${fileLink}`),
|
||||
buildAssistantTimelineEntry(`I reviewed ${fileLink}`),
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
|
||||
try {
|
||||
const userFileLink = document.querySelector(
|
||||
'[data-message-role="user"] .chat-markdown-file-link',
|
||||
);
|
||||
const assistantFileLink = document.querySelector(
|
||||
'[data-message-role="assistant"] .chat-markdown-file-link',
|
||||
);
|
||||
|
||||
expect(userFileLink?.textContent).toContain("package.json");
|
||||
expect(userFileLink?.getAttribute("href")).toBe("/repo/project/path/to/package.json");
|
||||
expect(assistantFileLink?.textContent).toContain("package.json");
|
||||
expect(assistantFileLink?.getAttribute("href")).toBe("/repo/project/path/to/package.json");
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -188,7 +188,8 @@ describe("MessagesTimeline", () => {
|
||||
|
||||
expect(markup).toContain("Terminal 1 lines 1-5");
|
||||
expect(markup).toContain("lucide-terminal");
|
||||
expect(markup).toContain("yoo what's ");
|
||||
expect(markup).toContain("yoo what's</p>");
|
||||
expect(markup).toContain('<span aria-hidden="true"> </span>');
|
||||
expect(markup).toContain("Show full message");
|
||||
}, 20_000);
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
use,
|
||||
useCallback,
|
||||
useEffect,
|
||||
Fragment,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
@@ -380,6 +381,7 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
|
||||
text={displayedUserMessage.visibleText}
|
||||
terminalContexts={terminalContexts}
|
||||
skills={ctx.skills}
|
||||
markdownCwd={ctx.markdownCwd}
|
||||
footer={
|
||||
<>
|
||||
<div className="flex items-center gap-1.5 opacity-0 transition-opacity duration-200 focus-within:opacity-100 group-hover:opacity-100">
|
||||
@@ -404,16 +406,23 @@ function RevertUserMessageButton({ messageId }: { messageId: MessageId }) {
|
||||
const activity = use(TimelineRowActivityCtx);
|
||||
|
||||
return (
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
disabled={activity.isRevertingCheckpoint || activity.isWorking}
|
||||
onClick={() => ctx.onRevertUserMessage(messageId)}
|
||||
title="Revert to this message"
|
||||
>
|
||||
<Undo2Icon className="size-3" />
|
||||
</Button>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
disabled={activity.isRevertingCheckpoint || activity.isWorking}
|
||||
onClick={() => ctx.onRevertUserMessage(messageId)}
|
||||
aria-label="Revert to this message"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<Undo2Icon className="size-3" />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">Revert to this message</TooltipPopup>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -781,6 +790,7 @@ const CollapsibleUserMessageBody = memo(function CollapsibleUserMessageBody(prop
|
||||
text: string;
|
||||
terminalContexts: ParsedTerminalContextEntry[];
|
||||
skills: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">>;
|
||||
markdownCwd: string | undefined;
|
||||
footer?: ReactNode;
|
||||
}) {
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
@@ -810,6 +820,7 @@ const CollapsibleUserMessageBody = memo(function CollapsibleUserMessageBody(prop
|
||||
text={props.text}
|
||||
terminalContexts={props.terminalContexts}
|
||||
skills={props.skills}
|
||||
markdownCwd={props.markdownCwd}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
@@ -847,7 +858,34 @@ const UserMessageBody = memo(function UserMessageBody(props: {
|
||||
text: string;
|
||||
terminalContexts: ParsedTerminalContextEntry[];
|
||||
skills: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">>;
|
||||
markdownCwd: string | undefined;
|
||||
}) {
|
||||
const renderInlineMarkdownSegment = (text: string, key: string) => {
|
||||
const leadingWhitespace = /^\s+/.exec(text)?.[0] ?? "";
|
||||
const textWithoutLeadingWhitespace = text.slice(leadingWhitespace.length);
|
||||
const trailingWhitespace = /\s+$/.exec(textWithoutLeadingWhitespace)?.[0] ?? "";
|
||||
const content = textWithoutLeadingWhitespace.slice(
|
||||
0,
|
||||
textWithoutLeadingWhitespace.length - trailingWhitespace.length,
|
||||
);
|
||||
|
||||
return (
|
||||
<Fragment key={key}>
|
||||
{leadingWhitespace ? <span aria-hidden="true">{leadingWhitespace}</span> : null}
|
||||
{content ? (
|
||||
<ChatMarkdown
|
||||
text={content}
|
||||
cwd={props.markdownCwd}
|
||||
skills={props.skills}
|
||||
className="text-foreground"
|
||||
lineBreaks
|
||||
/>
|
||||
) : null}
|
||||
{trailingWhitespace ? <span aria-hidden="true">{trailingWhitespace}</span> : null}
|
||||
</Fragment>
|
||||
);
|
||||
};
|
||||
|
||||
const reviewCommentSegments = parseReviewCommentMessageSegments(props.text);
|
||||
if (reviewCommentSegments.some((segment) => segment.kind === "review-comment")) {
|
||||
return (
|
||||
@@ -855,8 +893,14 @@ const UserMessageBody = memo(function UserMessageBody(props: {
|
||||
{reviewCommentSegments.map((segment) =>
|
||||
segment.kind === "text" ? (
|
||||
segment.text.trim().length > 0 ? (
|
||||
<div key={segment.id} className="whitespace-pre-wrap wrap-break-word">
|
||||
<SkillInlineText text={segment.text.trim()} skills={props.skills} />
|
||||
<div key={segment.id} className="wrap-break-word">
|
||||
<ChatMarkdown
|
||||
text={segment.text.trim()}
|
||||
cwd={props.markdownCwd}
|
||||
skills={props.skills}
|
||||
className="text-foreground"
|
||||
lineBreaks
|
||||
/>
|
||||
</div>
|
||||
) : null
|
||||
) : (
|
||||
@@ -887,9 +931,10 @@ const UserMessageBody = memo(function UserMessageBody(props: {
|
||||
}
|
||||
if (matchIndex > cursor) {
|
||||
inlineNodes.push(
|
||||
<span key={`user-terminal-context-inline-before:${context.header}:${cursor}`}>
|
||||
<SkillInlineText text={props.text.slice(cursor, matchIndex)} skills={props.skills} />
|
||||
</span>,
|
||||
renderInlineMarkdownSegment(
|
||||
props.text.slice(cursor, matchIndex),
|
||||
`user-terminal-context-inline-before:${context.header}:${cursor}`,
|
||||
),
|
||||
);
|
||||
}
|
||||
inlineNodes.push(
|
||||
@@ -904,9 +949,10 @@ const UserMessageBody = memo(function UserMessageBody(props: {
|
||||
if (inlineNodes.length > 0) {
|
||||
if (cursor < props.text.length) {
|
||||
inlineNodes.push(
|
||||
<span key={`user-message-terminal-context-inline-rest:${cursor}`}>
|
||||
<SkillInlineText text={props.text.slice(cursor)} skills={props.skills} />
|
||||
</span>,
|
||||
renderInlineMarkdownSegment(
|
||||
props.text.slice(cursor),
|
||||
`user-message-terminal-context-inline-rest:${cursor}`,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -934,9 +980,14 @@ const UserMessageBody = memo(function UserMessageBody(props: {
|
||||
|
||||
if (props.text.length > 0) {
|
||||
inlineNodes.push(
|
||||
<span key="user-message-terminal-context-inline-text">
|
||||
<SkillInlineText text={props.text} skills={props.skills} />
|
||||
</span>,
|
||||
<ChatMarkdown
|
||||
key="user-message-terminal-context-inline-text"
|
||||
text={props.text}
|
||||
cwd={props.markdownCwd}
|
||||
skills={props.skills}
|
||||
className="text-foreground"
|
||||
lineBreaks
|
||||
/>,
|
||||
);
|
||||
} else if (inlinePrefix.length === 0) {
|
||||
return null;
|
||||
@@ -954,9 +1005,13 @@ const UserMessageBody = memo(function UserMessageBody(props: {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="whitespace-pre-wrap wrap-break-word text-sm leading-relaxed text-foreground">
|
||||
<SkillInlineText text={props.text} skills={props.skills} />
|
||||
</div>
|
||||
<ChatMarkdown
|
||||
text={props.text}
|
||||
cwd={props.markdownCwd}
|
||||
skills={props.skills}
|
||||
className="text-foreground"
|
||||
lineBreaks
|
||||
/>
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1203,49 +1258,40 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
|
||||
<div className="min-w-0 flex-1 overflow-hidden">
|
||||
{rawCommand ? (
|
||||
<div className="max-w-full">
|
||||
<p
|
||||
className={cn(
|
||||
"truncate text-xs leading-5",
|
||||
workToneClass(workEntry.tone),
|
||||
preview ? "text-muted-foreground/70" : "",
|
||||
)}
|
||||
title={displayText}
|
||||
>
|
||||
<span className={cn("text-foreground/80", workToneClass(workEntry.tone))}>
|
||||
{heading}
|
||||
</span>
|
||||
{preview && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
closeDelay={0}
|
||||
delay={75}
|
||||
render={
|
||||
<span className="max-w-full cursor-default text-muted-foreground/55 transition-colors hover:text-muted-foreground/75 focus-visible:text-muted-foreground/75">
|
||||
{" "}
|
||||
- {preview}
|
||||
</span>
|
||||
}
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
closeDelay={0}
|
||||
delay={75}
|
||||
render={
|
||||
<p
|
||||
className={cn(
|
||||
"truncate rounded-sm text-xs leading-5",
|
||||
workToneClass(workEntry.tone),
|
||||
preview ? "text-muted-foreground/70" : "",
|
||||
)}
|
||||
aria-label={displayText}
|
||||
/>
|
||||
<TooltipPopup
|
||||
align="start"
|
||||
className="max-w-[min(56rem,calc(100vw-2rem))] px-0 py-0"
|
||||
side="top"
|
||||
>
|
||||
<div className="max-w-[min(56rem,calc(100vw-2rem))] overflow-x-auto px-1.5 py-1 font-mono text-[11px] leading-4 whitespace-nowrap">
|
||||
{rawCommand}
|
||||
</div>
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
)}
|
||||
</p>
|
||||
}
|
||||
>
|
||||
<span className={cn("text-foreground/80", workToneClass(workEntry.tone))}>
|
||||
{heading}
|
||||
</span>
|
||||
{preview && <span className="text-muted-foreground/55"> - {preview}</span>}
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup
|
||||
align="start"
|
||||
className="max-w-[min(56rem,calc(100vw-2rem))] px-0 py-0"
|
||||
side="top"
|
||||
>
|
||||
<div className="max-w-[min(56rem,calc(100vw-2rem))] overflow-x-auto px-1.5 py-1 font-mono text-[11px] leading-4 whitespace-nowrap">
|
||||
{rawCommand}
|
||||
</div>
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
) : (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
className="block min-w-0 w-full text-left"
|
||||
title={displayText}
|
||||
aria-label={displayText}
|
||||
>
|
||||
<TooltipTrigger className="block min-w-0 w-full text-left" aria-label={displayText}>
|
||||
<p
|
||||
className={cn(
|
||||
"truncate text-[11px] leading-5",
|
||||
@@ -1273,13 +1319,21 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
|
||||
{workEntry.changedFiles?.slice(0, 4).map((filePath) => {
|
||||
const displayPath = formatWorkspaceRelativePath(filePath, workspaceRoot);
|
||||
return (
|
||||
<span
|
||||
key={`${workEntry.id}:${filePath}`}
|
||||
className="rounded-md border border-border/55 bg-background/75 px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground/75"
|
||||
title={displayPath}
|
||||
>
|
||||
{displayPath}
|
||||
</span>
|
||||
<Tooltip key={`${workEntry.id}:${filePath}`}>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<span
|
||||
className="rounded-md border border-border/55 bg-background/75 px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground/75"
|
||||
aria-label={displayPath}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{displayPath}
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top" className="max-w-[min(40rem,calc(100vw-2rem))]">
|
||||
<span className="font-mono text-[11px] whitespace-nowrap">{displayPath}</span>
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
);
|
||||
})}
|
||||
{(workEntry.changedFiles?.length ?? 0) > 4 && (
|
||||
|
||||
@@ -3,6 +3,7 @@ import { memo } from "react";
|
||||
import { InfoIcon } from "lucide-react";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { formatProviderDriverKindLabel } from "../../providerModels";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
|
||||
export const ProviderStatusBanner = memo(function ProviderStatusBanner({
|
||||
status,
|
||||
@@ -39,9 +40,14 @@ export const ProviderStatusBanner = memo(function ProviderStatusBanner({
|
||||
<InfoIcon className="size-4 shrink-0" aria-hidden />
|
||||
<div className="flex min-w-0 flex-col gap-1">
|
||||
<div className="font-medium">{title}</div>
|
||||
<div className="line-clamp-3 text-muted-foreground" title={message}>
|
||||
{message}
|
||||
</div>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={<div className="line-clamp-3 text-muted-foreground">{message}</div>}
|
||||
/>
|
||||
<TooltipPopup side="top" className="max-w-96 whitespace-pre-wrap">
|
||||
{message}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -3,11 +3,12 @@ import type { ServerProviderSkill } from "@t3tools/contracts";
|
||||
|
||||
import { formatProviderSkillDisplayName } from "../../providerSkillPresentation";
|
||||
import {
|
||||
CHAT_INLINE_CHIP_CLASS_NAME,
|
||||
CHAT_INLINE_CHIP_LABEL_CLASS_NAME,
|
||||
COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
|
||||
COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME,
|
||||
COMPOSER_INLINE_SKILL_CHIP_CLASS_NAME,
|
||||
SKILL_CHIP_ICON_SVG,
|
||||
} from "../composerInlineChip";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
const SKILL_TOKEN_REGEX = /(^|\s)\$([a-zA-Z][a-zA-Z0-9:_-]*)(?=\s|$)/g;
|
||||
|
||||
@@ -70,15 +71,19 @@ export function renderSkillInlineMarkdownChildren(
|
||||
|
||||
function SkillChip(props: { skill: InlineSkill; rawText: string }) {
|
||||
return (
|
||||
<span className="inline-flex align-middle leading-none">
|
||||
<span className="sr-only">{props.rawText}</span>
|
||||
<span aria-hidden="true" className={COMPOSER_INLINE_SKILL_CHIP_CLASS_NAME}>
|
||||
<span className="inline-flex align-middle leading-none" data-markdown-copy={props.rawText}>
|
||||
<span
|
||||
className={cn(
|
||||
CHAT_INLINE_CHIP_CLASS_NAME,
|
||||
"border-fuchsia-500/25 bg-fuchsia-500/12 text-fuchsia-700 dark:text-fuchsia-300",
|
||||
)}
|
||||
>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className={COMPOSER_INLINE_CHIP_ICON_CLASS_NAME}
|
||||
dangerouslySetInnerHTML={{ __html: SKILL_CHIP_ICON_SVG }}
|
||||
/>
|
||||
<span className={COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME}>
|
||||
<span className={CHAT_INLINE_CHIP_LABEL_CLASS_NAME}>
|
||||
{formatProviderSkillDisplayName(props.skill)}
|
||||
</span>
|
||||
</span>
|
||||
|
||||
@@ -2,6 +2,7 @@ import { memo } from "react";
|
||||
import { Alert, AlertAction, AlertDescription } from "../ui/alert";
|
||||
import { Button } from "../ui/button";
|
||||
import { CircleAlertIcon, XIcon } from "lucide-react";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
|
||||
export const ThreadErrorBanner = memo(function ThreadErrorBanner({
|
||||
error,
|
||||
@@ -15,9 +16,14 @@ export const ThreadErrorBanner = memo(function ThreadErrorBanner({
|
||||
<div className="pt-3 mx-auto max-w-3xl">
|
||||
<Alert variant="error">
|
||||
<CircleAlertIcon />
|
||||
<AlertDescription className="line-clamp-3" title={error}>
|
||||
{error}
|
||||
</AlertDescription>
|
||||
<Tooltip>
|
||||
<TooltipTrigger render={<AlertDescription className="line-clamp-3" />}>
|
||||
{error}
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top" className="max-w-96 whitespace-pre-wrap">
|
||||
{error}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
{onDismiss && (
|
||||
<AlertAction>
|
||||
<Button variant="ghost" size="icon-xs" aria-label="Dismiss error" onClick={onDismiss}>
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
export const COMPOSER_INLINE_CHIP_CLASS_NAME =
|
||||
"inline-flex max-w-full select-none items-center gap-1 rounded-md border border-border/70 bg-accent/40 px-1.5 py-px font-medium text-[12px] leading-[1.1] text-foreground align-middle";
|
||||
const INLINE_CHIP_CLASS_NAME =
|
||||
"inline-flex max-w-full items-center gap-1 rounded-md border border-border/70 bg-accent/40 px-1.5 py-px font-medium text-[12px] leading-[1.1] text-foreground align-middle";
|
||||
|
||||
export const CHAT_INLINE_CHIP_CLASS_NAME = INLINE_CHIP_CLASS_NAME;
|
||||
|
||||
export const COMPOSER_INLINE_CHIP_CLASS_NAME = `${INLINE_CHIP_CLASS_NAME} select-none`;
|
||||
|
||||
export const COMPOSER_INLINE_CHIP_ICON_CLASS_NAME = "size-3.5 shrink-0 opacity-85";
|
||||
|
||||
export const COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME = "truncate select-none leading-tight";
|
||||
export const CHAT_INLINE_CHIP_LABEL_CLASS_NAME = "truncate leading-tight";
|
||||
|
||||
export const COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME = `${CHAT_INLINE_CHIP_LABEL_CLASS_NAME} select-none`;
|
||||
|
||||
export const COMPOSER_INLINE_SKILL_CHIP_CLASS_NAME =
|
||||
"inline-flex max-w-full select-none items-center gap-1 rounded-md border border-fuchsia-500/25 bg-fuchsia-500/12 px-1.5 py-px font-medium text-[12px] leading-[1.1] text-fuchsia-700 align-middle dark:text-fuchsia-300";
|
||||
|
||||
@@ -274,7 +274,6 @@ function ConnectionStatusDot({
|
||||
const dot = (
|
||||
<button
|
||||
type="button"
|
||||
title={tooltipText}
|
||||
aria-label={tooltipText}
|
||||
className="relative flex size-3 shrink-0 cursor-help items-center justify-center rounded-full outline-hidden"
|
||||
>
|
||||
@@ -881,11 +880,16 @@ const PairingLinkListRow = memo(function PairingLinkListRow({
|
||||
) : null}
|
||||
</Popover>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground" title={expiresAbsolute}>
|
||||
{formatExpiresInLabel(pairingLink.expiresAt, nowMs)}
|
||||
<span aria-hidden> · </span>
|
||||
<AccessScopeSummary scopes={pairingLink.scopes} label="Pairing link scopes" />
|
||||
</p>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={<p aria-label={expiresAbsolute} className="text-xs text-muted-foreground" />}
|
||||
>
|
||||
{formatExpiresInLabel(pairingLink.expiresAt, nowMs)}
|
||||
<span aria-hidden> · </span>
|
||||
<AccessScopeSummary scopes={pairingLink.scopes} label="Pairing link scopes" />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">{expiresAbsolute}</TooltipPopup>
|
||||
</Tooltip>
|
||||
{shareablePairingUrl === null ? (
|
||||
<p className="text-[11px] text-muted-foreground/70">
|
||||
Copy the token and pair from another client using this backend's reachable host.
|
||||
@@ -898,17 +902,26 @@ const PairingLinkListRow = memo(function PairingLinkListRow({
|
||||
<>
|
||||
{shareablePairingUrl ? (
|
||||
<Group aria-label="Copy selected endpoint">
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
className="max-w-56"
|
||||
title={`Copy pairing URL for: ${defaultEndpointCopyLabel}`}
|
||||
onClick={handleCopyDefaultLink}
|
||||
>
|
||||
<span className="truncate">
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
className="max-w-56"
|
||||
aria-label={`Copy pairing URL for: ${defaultEndpointCopyLabel}`}
|
||||
onClick={handleCopyDefaultLink}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<span className="truncate">
|
||||
Copy pairing URL for: {defaultEndpointCopyLabel}
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">
|
||||
Copy pairing URL for: {defaultEndpointCopyLabel}
|
||||
</span>
|
||||
</Button>
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
<GroupSeparator />
|
||||
<Menu>
|
||||
<MenuTrigger
|
||||
@@ -1353,12 +1366,19 @@ const AdvertisedEndpointListRow = memo(function AdvertisedEndpointListRow({
|
||||
{endpoint.label}
|
||||
</h3>
|
||||
{shouldShowEndpointUrl ? (
|
||||
<p
|
||||
className="min-w-0 truncate text-xs leading-5 text-muted-foreground"
|
||||
title={endpoint.httpBaseUrl}
|
||||
>
|
||||
{endpoint.httpBaseUrl}
|
||||
</p>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<p
|
||||
aria-label={endpoint.httpBaseUrl}
|
||||
className="min-w-0 truncate text-xs leading-5 text-muted-foreground"
|
||||
/>
|
||||
}
|
||||
>
|
||||
{endpoint.httpBaseUrl}
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">{endpoint.httpBaseUrl}</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
{!isAvailable ? (
|
||||
<span className="shrink-0 rounded-md border border-border/70 px-1 py-0.5 text-[10px] text-muted-foreground">
|
||||
@@ -3116,12 +3136,21 @@ export function ConnectionsSettings() {
|
||||
) : null}
|
||||
<div className="rounded-md border border-border/70 bg-muted/20 px-3 py-2">
|
||||
<p className="text-xs font-medium text-muted-foreground">HTTPS endpoint</p>
|
||||
<p
|
||||
className="mt-1 truncate text-sm text-foreground"
|
||||
title={pendingTailscaleServeBaseUrl ?? undefined}
|
||||
>
|
||||
{pendingTailscaleServeBaseUrl ?? "Pending MagicDNS endpoint"}
|
||||
</p>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<p
|
||||
aria-label={pendingTailscaleServeBaseUrl ?? "Pending MagicDNS endpoint"}
|
||||
className="mt-1 truncate text-sm text-foreground"
|
||||
/>
|
||||
}
|
||||
>
|
||||
{pendingTailscaleServeBaseUrl ?? "Pending MagicDNS endpoint"}
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">
|
||||
{pendingTailscaleServeBaseUrl ?? "Pending MagicDNS endpoint"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</DialogPanel>
|
||||
<DialogFooter>
|
||||
|
||||
@@ -805,9 +805,19 @@ function KeybindingTableRow({
|
||||
<div className="grid grid-cols-[minmax(190px,1.1fr)_minmax(220px,0.85fr)_minmax(210px,1fr)_60px] items-center px-4 py-1.5 text-sm even:bg-muted/15 hover:bg-accent/40">
|
||||
<div className="min-w-0 pr-4">
|
||||
<div className="flex min-w-0 items-center gap-1.5">
|
||||
<div className="truncate text-[13px] font-medium text-foreground" title={row.command}>
|
||||
{commandLabel(row.command)}
|
||||
</div>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<div
|
||||
aria-label={row.command}
|
||||
className="truncate text-[13px] font-medium text-foreground"
|
||||
/>
|
||||
}
|
||||
>
|
||||
{commandLabel(row.command)}
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">{row.command}</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex min-w-0 items-center gap-2 pr-4">
|
||||
|
||||
@@ -572,31 +572,37 @@ function SidebarRail({
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<button
|
||||
aria-label={railLabel}
|
||||
className={cn(
|
||||
/* disable pointer events only when offcanvas sidebar is collapsed, that's when the rail sits over the native scrollbar on windows and linux. icon mode stays fully clickable. */
|
||||
"-translate-x-1/2 group-data-[side=left]:-right-4 absolute inset-y-0 z-20 hidden w-4 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] hover:after:bg-sidebar-border group-data-[side=right]:left-0 sm:flex [[data-collapsible=offcanvas][data-state=collapsed]_&]:pointer-events-none",
|
||||
"in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
|
||||
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
|
||||
"group-data-[collapsible=offcanvas]:translate-x-0 hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:after:left-full",
|
||||
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
|
||||
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
|
||||
className,
|
||||
)}
|
||||
data-sidebar="rail"
|
||||
data-slot="sidebar-rail"
|
||||
onClick={handleClick}
|
||||
onPointerCancel={handlePointerCancel}
|
||||
onPointerDown={handlePointerDown}
|
||||
onPointerMove={handlePointerMove}
|
||||
onPointerUp={handlePointerUp}
|
||||
ref={railRef}
|
||||
tabIndex={-1}
|
||||
title={railTitle}
|
||||
type="button"
|
||||
{...props}
|
||||
/>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<button
|
||||
aria-label={railLabel}
|
||||
className={cn(
|
||||
/* disable pointer events only when offcanvas sidebar is collapsed, that's when the rail sits over the native scrollbar on windows and linux. icon mode stays fully clickable. */
|
||||
"-translate-x-1/2 group-data-[side=left]:-right-4 absolute inset-y-0 z-20 hidden w-4 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] hover:after:bg-sidebar-border group-data-[side=right]:left-0 sm:flex [[data-collapsible=offcanvas][data-state=collapsed]_&]:pointer-events-none",
|
||||
"in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
|
||||
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
|
||||
"group-data-[collapsible=offcanvas]:translate-x-0 hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:after:left-full",
|
||||
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
|
||||
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
|
||||
className,
|
||||
)}
|
||||
data-sidebar="rail"
|
||||
data-slot="sidebar-rail"
|
||||
onClick={handleClick}
|
||||
onPointerCancel={handlePointerCancel}
|
||||
onPointerDown={handlePointerDown}
|
||||
onPointerMove={handlePointerMove}
|
||||
onPointerUp={handlePointerUp}
|
||||
ref={railRef}
|
||||
tabIndex={-1}
|
||||
type="button"
|
||||
{...props}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="right">{railTitle}</TooltipPopup>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@ import {
|
||||
shouldHideCollapsedToastContent,
|
||||
shouldRenderThreadScopedToast,
|
||||
} from "./toast.logic";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./tooltip";
|
||||
|
||||
export type ThreadToastData = {
|
||||
threadRef?: ScopedThreadRef | null;
|
||||
@@ -113,16 +114,24 @@ function handleToastDismissClick(
|
||||
|
||||
function CopyErrorButton({ text }: { text: string }) {
|
||||
const { copyToClipboard, isCopied } = useCopyToClipboard();
|
||||
const label = isCopied ? "Copied error" : "Copy error";
|
||||
|
||||
return (
|
||||
<button
|
||||
className="inline-flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-md p-0 text-muted-foreground/80 transition-colors hover:text-muted-foreground"
|
||||
onClick={() => copyToClipboard(text)}
|
||||
title="Copy error"
|
||||
type="button"
|
||||
>
|
||||
{isCopied ? <CheckIcon className="size-3 text-success" /> : <CopyIcon className="size-3" />}
|
||||
</button>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<button
|
||||
aria-label={label}
|
||||
className="inline-flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-md p-0 text-muted-foreground/80 transition-colors hover:text-muted-foreground"
|
||||
onClick={() => copyToClipboard(text)}
|
||||
type="button"
|
||||
/>
|
||||
}
|
||||
>
|
||||
{isCopied ? <CheckIcon className="size-3 text-success" /> : <CopyIcon className="size-3" />}
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">{label}</TooltipPopup>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -205,43 +214,50 @@ function ToastDescriptionAndExpandable({
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
aria-expanded={open}
|
||||
className={cn(
|
||||
"group flex min-w-0 w-full cursor-pointer select-none items-start gap-1.5 rounded-sm text-left outline-none ring-offset-background",
|
||||
"transition-colors hover:bg-muted/40",
|
||||
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
|
||||
)}
|
||||
onClick={toggle}
|
||||
onKeyDown={onKeyDown}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
title={open ? collapseLabel : expandLabel}
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<Toast.Description
|
||||
className={cn(
|
||||
"min-w-0 select-none wrap-break-word text-muted-foreground",
|
||||
errorDescriptionClampClass(toastType, toastDescription),
|
||||
"underline-offset-2 decoration-muted-foreground/60 group-hover:underline",
|
||||
)}
|
||||
data-slot="toast-description"
|
||||
/>
|
||||
</div>
|
||||
{open ? (
|
||||
<ChevronUpIcon
|
||||
aria-hidden
|
||||
className="mt-0.5 size-3.5 shrink-0 text-muted-foreground opacity-80"
|
||||
strokeWidth={2.25}
|
||||
/>
|
||||
) : (
|
||||
<ChevronDownIcon
|
||||
aria-hidden
|
||||
className="mt-0.5 size-3.5 shrink-0 text-muted-foreground opacity-80"
|
||||
strokeWidth={2.25}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<div
|
||||
aria-label={open ? collapseLabel : expandLabel}
|
||||
aria-expanded={open}
|
||||
className={cn(
|
||||
"group flex min-w-0 w-full cursor-pointer select-none items-start gap-1.5 rounded-sm text-left outline-none ring-offset-background",
|
||||
"transition-colors hover:bg-muted/40",
|
||||
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
|
||||
)}
|
||||
onClick={toggle}
|
||||
onKeyDown={onKeyDown}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<Toast.Description
|
||||
className={cn(
|
||||
"min-w-0 select-none wrap-break-word text-muted-foreground",
|
||||
errorDescriptionClampClass(toastType, toastDescription),
|
||||
"underline-offset-2 decoration-muted-foreground/60 group-hover:underline",
|
||||
)}
|
||||
data-slot="toast-description"
|
||||
/>
|
||||
</div>
|
||||
{open ? (
|
||||
<ChevronUpIcon
|
||||
aria-hidden
|
||||
className="mt-0.5 size-3.5 shrink-0 text-muted-foreground opacity-80"
|
||||
strokeWidth={2.25}
|
||||
/>
|
||||
) : (
|
||||
<ChevronDownIcon
|
||||
aria-hidden
|
||||
className="mt-0.5 size-3.5 shrink-0 text-muted-foreground opacity-80"
|
||||
strokeWidth={2.25}
|
||||
/>
|
||||
)}
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">{open ? collapseLabel : expandLabel}</TooltipPopup>
|
||||
</Tooltip>
|
||||
{open ? <div className={toastExpandablePanelClassName}>{expandableContent}</div> : null}
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -31,7 +31,7 @@ function TooltipPopup({
|
||||
<TooltipPrimitive.Positioner
|
||||
align={align}
|
||||
anchor={anchor}
|
||||
className="z-50 h-(--positioner-height) w-(--positioner-width) max-w-(--available-width) transition-[top,left,right,bottom,transform] data-instant:transition-none"
|
||||
className="pointer-events-none z-50 h-(--positioner-height) w-(--positioner-width) max-w-(--available-width) transition-[top,left,right,bottom,transform] data-instant:transition-none"
|
||||
data-slot="tooltip-positioner"
|
||||
side={side}
|
||||
sideOffset={sideOffset}
|
||||
|
||||
@@ -10,7 +10,7 @@ describe("splitPromptIntoComposerSegments", () => {
|
||||
it("splits mention tokens followed by whitespace into mention segments", () => {
|
||||
expect(splitPromptIntoComposerSegments("Inspect @AGENTS.md please")).toEqual([
|
||||
{ type: "text", text: "Inspect " },
|
||||
{ type: "mention", path: "AGENTS.md" },
|
||||
{ type: "mention", path: "AGENTS.md", source: "@AGENTS.md" },
|
||||
{ type: "text", text: " please" },
|
||||
]);
|
||||
});
|
||||
@@ -24,7 +24,7 @@ describe("splitPromptIntoComposerSegments", () => {
|
||||
it("keeps newlines around mention tokens", () => {
|
||||
expect(splitPromptIntoComposerSegments("one\n@src/index.ts \ntwo")).toEqual([
|
||||
{ type: "text", text: "one\n" },
|
||||
{ type: "mention", path: "src/index.ts" },
|
||||
{ type: "mention", path: "src/index.ts", source: "@src/index.ts" },
|
||||
{ type: "text", text: " \ntwo" },
|
||||
]);
|
||||
});
|
||||
@@ -32,7 +32,7 @@ describe("splitPromptIntoComposerSegments", () => {
|
||||
it("splits quoted mention tokens containing whitespace", () => {
|
||||
expect(splitPromptIntoComposerSegments('Inspect @"My File.md" please')).toEqual([
|
||||
{ type: "text", text: "Inspect " },
|
||||
{ type: "mention", path: "My File.md" },
|
||||
{ type: "mention", path: "My File.md", source: '@"My File.md"' },
|
||||
{ type: "text", text: " please" },
|
||||
]);
|
||||
});
|
||||
@@ -40,11 +40,53 @@ describe("splitPromptIntoComposerSegments", () => {
|
||||
it("unescapes quoted mention token content", () => {
|
||||
expect(splitPromptIntoComposerSegments('Inspect @"docs/My \\"File\\".md" please')).toEqual([
|
||||
{ type: "text", text: "Inspect " },
|
||||
{ type: "mention", path: 'docs/My "File".md' },
|
||||
{
|
||||
type: "mention",
|
||||
path: 'docs/My "File".md',
|
||||
source: '@"docs/My \\"File\\".md"',
|
||||
},
|
||||
{ type: "text", text: " please" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("splits generated markdown file links into mention segments", () => {
|
||||
expect(
|
||||
splitPromptIntoComposerSegments(
|
||||
"Inspect [package.json](path/to/package.json) before continuing",
|
||||
),
|
||||
).toEqual([
|
||||
{ type: "text", text: "Inspect " },
|
||||
{
|
||||
type: "mention",
|
||||
path: "path/to/package.json",
|
||||
source: "[package.json](path/to/package.json)",
|
||||
},
|
||||
{ type: "text", text: " before continuing" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not turn normal web links into file mention segments", () => {
|
||||
expect(
|
||||
splitPromptIntoComposerSegments("Read [the docs](https://example.com/docs) first"),
|
||||
).toEqual([{ type: "text", text: "Read [the docs](https://example.com/docs) first" }]);
|
||||
});
|
||||
|
||||
it("decodes reserved path characters from generated links", () => {
|
||||
expect(
|
||||
splitPromptIntoComposerSegments(
|
||||
"Inspect [config#draft?.json](config%23draft%3F.json) before continuing",
|
||||
),
|
||||
).toEqual([
|
||||
{ type: "text", text: "Inspect " },
|
||||
{
|
||||
type: "mention",
|
||||
path: "config#draft?.json",
|
||||
source: "[config#draft?.json](config%23draft%3F.json)",
|
||||
},
|
||||
{ type: "text", text: " before continuing" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("splits skill tokens followed by whitespace into skill segments", () => {
|
||||
expect(splitPromptIntoComposerSegments("Use $review-follow-up please")).toEqual([
|
||||
{ type: "text", text: "Use " },
|
||||
@@ -67,7 +109,7 @@ describe("splitPromptIntoComposerSegments", () => {
|
||||
).toEqual([
|
||||
{ type: "text", text: "Inspect " },
|
||||
{ type: "terminal-context", context: null },
|
||||
{ type: "mention", path: "AGENTS.md" },
|
||||
{ type: "mention", path: "AGENTS.md", source: "@AGENTS.md" },
|
||||
{ type: "text", text: " please" },
|
||||
]);
|
||||
});
|
||||
@@ -94,7 +136,7 @@ describe("splitPromptIntoComposerSegments", () => {
|
||||
{ type: "terminal-context", context: null },
|
||||
{ type: "skill", name: "review-follow-up" },
|
||||
{ type: "text", text: " after " },
|
||||
{ type: "mention", path: "AGENTS.md" },
|
||||
{ type: "mention", path: "AGENTS.md", source: "@AGENTS.md" },
|
||||
{ type: "text", text: " " },
|
||||
]);
|
||||
});
|
||||
@@ -151,4 +193,15 @@ describe("selectionTouchesMentionBoundary", () => {
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("returns true when selection includes whitespace after a markdown file link", () => {
|
||||
const prompt = "hi [package.json](path/to/package.json) there";
|
||||
expect(
|
||||
selectionTouchesMentionBoundary(
|
||||
prompt,
|
||||
"hi [package.json](path/to/package.json)".length,
|
||||
prompt.length,
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -11,6 +11,7 @@ export type ComposerPromptSegment =
|
||||
| {
|
||||
type: "mention";
|
||||
path: string;
|
||||
source: string;
|
||||
}
|
||||
| {
|
||||
type: "skill";
|
||||
@@ -23,6 +24,9 @@ export type ComposerPromptSegment =
|
||||
|
||||
const SKILL_TOKEN_REGEX = /(^|\s)\$([a-zA-Z][a-zA-Z0-9:_-]*)(?=\s)/g;
|
||||
const MENTION_TOKEN_REGEX = /(^|\s)@(?:"((?:\\.|[^"\\])*)"|([^\s@"]+))(?=\s)/g;
|
||||
const FILE_LINK_TOKEN_REGEX = /(^|\s)\[((?:\\.|[^\]\\])*)\]\(([^)\s]+)\)(?=\s)/g;
|
||||
const URI_SCHEME_REGEX = /^[A-Za-z][A-Za-z0-9+.-]*:/;
|
||||
const WINDOWS_DRIVE_PATH_REGEX = /^[A-Za-z]:[\\/]/;
|
||||
|
||||
function rangeIncludesIndex(start: number, end: number, index: number): boolean {
|
||||
return start <= index && index < end;
|
||||
@@ -57,6 +61,29 @@ type MentionTokenMatch = Extract<InlineTokenMatch, { type: "mention" }>;
|
||||
function collectMentionTokenMatches(text: string): MentionTokenMatch[] {
|
||||
const matches: MentionTokenMatch[] = [];
|
||||
|
||||
for (const match of text.matchAll(FILE_LINK_TOKEN_REGEX)) {
|
||||
const fullMatch = match[0];
|
||||
const prefix = match[1] ?? "";
|
||||
const label = (match[2] ?? "").replace(/\\(.)/g, "$1");
|
||||
const encodedPath = match[3] ?? "";
|
||||
let path = encodedPath;
|
||||
try {
|
||||
path = decodeURIComponent(encodedPath);
|
||||
} catch {
|
||||
// Keep the source value when malformed percent escapes are present.
|
||||
}
|
||||
const separatorIndex = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
|
||||
const basename = separatorIndex >= 0 ? path.slice(separatorIndex + 1) : path;
|
||||
const hasExternalScheme = URI_SCHEME_REGEX.test(path) && !WINDOWS_DRIVE_PATH_REGEX.test(path);
|
||||
if (!path || hasExternalScheme || label !== basename) {
|
||||
continue;
|
||||
}
|
||||
const matchIndex = match.index ?? 0;
|
||||
const start = matchIndex + prefix.length;
|
||||
const end = start + fullMatch.length - prefix.length;
|
||||
matches.push({ type: "mention", value: path, start, end });
|
||||
}
|
||||
|
||||
for (const match of text.matchAll(MENTION_TOKEN_REGEX)) {
|
||||
const fullMatch = match[0];
|
||||
const prefix = match[1] ?? "";
|
||||
@@ -189,7 +216,11 @@ function splitPromptTextIntoComposerSegments(text: string): ComposerPromptSegmen
|
||||
}
|
||||
|
||||
if (match.type === "mention") {
|
||||
segments.push({ type: "mention", path: match.value });
|
||||
segments.push({
|
||||
type: "mention",
|
||||
path: match.value,
|
||||
source: text.slice(match.start, match.end),
|
||||
});
|
||||
} else {
|
||||
segments.push({ type: "skill", name: match.value });
|
||||
}
|
||||
|
||||
@@ -167,6 +167,16 @@ describe("expandCollapsedComposerCursor", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("maps collapsed markdown file links to their expanded source offsets", () => {
|
||||
const text = "what's in [AGENTS.md](AGENTS.md) please";
|
||||
const collapsedCursorAfterMention = "what's in ".length + 2;
|
||||
const expandedCursorAfterMention = "what's in [AGENTS.md](AGENTS.md) ".length;
|
||||
|
||||
expect(expandCollapsedComposerCursor(text, collapsedCursorAfterMention)).toBe(
|
||||
expandedCursorAfterMention,
|
||||
);
|
||||
});
|
||||
|
||||
it("allows path trigger detection to close after selecting a mention", () => {
|
||||
const text = "what's in my @AGENTS.md ";
|
||||
const collapsedCursorAfterMention = "what's in my ".length + 2;
|
||||
@@ -211,6 +221,16 @@ describe("collapseExpandedComposerCursor", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("maps expanded markdown file link cursors back to collapsed offsets", () => {
|
||||
const text = "what's in [AGENTS.md](AGENTS.md) please";
|
||||
const collapsedCursorAfterMention = "what's in ".length + 2;
|
||||
const expandedCursorAfterMention = "what's in [AGENTS.md](AGENTS.md) ".length;
|
||||
|
||||
expect(collapseExpandedComposerCursor(text, expandedCursorAfterMention)).toBe(
|
||||
collapsedCursorAfterMention,
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps replacement cursors aligned when another mention already exists earlier", () => {
|
||||
const text = "open @AGENTS.md then @src/index.ts ";
|
||||
const expandedCursor = text.length;
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { serializeComposerMentionPath } from "@t3tools/shared/composerTrigger";
|
||||
import { splitPromptIntoComposerSegments } from "./composer-editor-mentions";
|
||||
import { INLINE_TERMINAL_CONTEXT_PLACEHOLDER } from "./lib/terminalContext";
|
||||
|
||||
@@ -55,7 +54,7 @@ export function expandCollapsedComposerCursor(text: string, cursorInput: number)
|
||||
|
||||
for (const segment of segments) {
|
||||
if (segment.type === "mention") {
|
||||
const expandedLength = serializeComposerMentionPath(segment.path).length + 1;
|
||||
const expandedLength = segment.source.length;
|
||||
if (remaining <= 1) {
|
||||
return expandedCursor + (remaining === 0 ? 0 : expandedLength);
|
||||
}
|
||||
@@ -143,7 +142,7 @@ export function collapseExpandedComposerCursor(text: string, cursorInput: number
|
||||
|
||||
for (const segment of segments) {
|
||||
if (segment.type === "mention") {
|
||||
const expandedLength = serializeComposerMentionPath(segment.path).length + 1;
|
||||
const expandedLength = segment.source.length;
|
||||
if (remaining === 0) {
|
||||
return collapsedCursor;
|
||||
}
|
||||
|
||||
+206
-77
@@ -305,10 +305,44 @@ label:has(> select#reasoning-effort) select {
|
||||
.chat-markdown ol,
|
||||
.chat-markdown blockquote,
|
||||
.chat-markdown pre,
|
||||
.chat-markdown table {
|
||||
.chat-markdown .chat-markdown-table-container {
|
||||
margin: 0.65rem 0;
|
||||
}
|
||||
|
||||
.chat-markdown h1,
|
||||
.chat-markdown h2,
|
||||
.chat-markdown h3,
|
||||
.chat-markdown h4,
|
||||
.chat-markdown h5,
|
||||
.chat-markdown h6 {
|
||||
margin: 1.25rem 0 0.5rem;
|
||||
font-weight: 600;
|
||||
line-height: 1.3;
|
||||
color: var(--foreground);
|
||||
}
|
||||
|
||||
.chat-markdown h1 {
|
||||
font-size: 1.25rem;
|
||||
}
|
||||
|
||||
.chat-markdown h2 {
|
||||
font-size: 1.125rem;
|
||||
}
|
||||
|
||||
.chat-markdown h3 {
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.chat-markdown h4,
|
||||
.chat-markdown h5,
|
||||
.chat-markdown h6 {
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.chat-markdown h6 {
|
||||
color: var(--muted-foreground);
|
||||
}
|
||||
|
||||
.chat-markdown ul {
|
||||
padding-left: 1.25rem;
|
||||
list-style-type: disc;
|
||||
@@ -339,14 +373,39 @@ label:has(> select#reasoning-effort) select {
|
||||
margin-top: 0.25rem;
|
||||
}
|
||||
|
||||
.chat-markdown a {
|
||||
color: var(--info-foreground);
|
||||
text-decoration: underline;
|
||||
text-decoration-color: color-mix(in srgb, var(--info-foreground) 40%, transparent);
|
||||
/* GitHub-style task lists: the checkbox replaces the list marker. */
|
||||
.chat-markdown li.task-list-item {
|
||||
list-style-type: none;
|
||||
}
|
||||
|
||||
.chat-markdown a:hover {
|
||||
opacity: 0.8;
|
||||
.chat-markdown li.task-list-item input[type="checkbox"] {
|
||||
margin: 0 0.35em 0.15em -1.25rem;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.chat-markdown a {
|
||||
color: var(--info-foreground);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.chat-markdown a:not(.chat-markdown-file-link):hover,
|
||||
.chat-markdown a:not(.chat-markdown-file-link):focus-visible {
|
||||
background-image: radial-gradient(circle, currentcolor 0.75px, transparent 1px);
|
||||
background-position: left bottom;
|
||||
background-repeat: repeat-x;
|
||||
background-size: 4px 2px;
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-link-favicon {
|
||||
@apply inline-flex;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
margin-inline: 0.25em 0.2em;
|
||||
vertical-align: -0.125em;
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-link-leading {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.chat-markdown blockquote {
|
||||
@@ -355,6 +414,35 @@ label:has(> select#reasoning-effort) select {
|
||||
color: var(--muted-foreground);
|
||||
}
|
||||
|
||||
.chat-markdown section[data-footnotes] {
|
||||
margin-top: 1.25rem;
|
||||
border-top: 1px solid var(--border);
|
||||
padding-top: 0.75rem;
|
||||
color: var(--muted-foreground);
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.chat-markdown section[data-footnotes] ol {
|
||||
margin: 0;
|
||||
padding-left: 1.25rem;
|
||||
}
|
||||
|
||||
.chat-markdown section[data-footnotes] li + li {
|
||||
margin-top: 0.35rem;
|
||||
}
|
||||
|
||||
.chat-markdown a[data-footnote-ref],
|
||||
.chat-markdown a[data-footnote-backref] {
|
||||
display: inline-flex;
|
||||
min-width: 1rem;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 0.25rem;
|
||||
text-decoration: none;
|
||||
font-size: 0.6875rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.chat-markdown :not(pre) > code {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 0.375rem;
|
||||
@@ -364,45 +452,19 @@ label:has(> select#reasoning-effort) select {
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.chat-markdown-file-link {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.28rem;
|
||||
border: 1px solid color-mix(in srgb, var(--border) 92%, transparent);
|
||||
border-radius: 0.375rem;
|
||||
background: color-mix(in srgb, var(--muted) 88%, var(--background));
|
||||
padding: 0.08rem 0.34rem;
|
||||
.chat-markdown a.chat-markdown-file-link {
|
||||
color: var(--foreground);
|
||||
font-family: var(--font-mono, ui-monospace, monospace);
|
||||
font-size: 0.75rem;
|
||||
line-height: 1.15;
|
||||
vertical-align: text-bottom;
|
||||
transition:
|
||||
background-color 120ms ease,
|
||||
border-color 120ms ease,
|
||||
color 120ms ease,
|
||||
opacity 120ms ease;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.chat-markdown-file-link:hover {
|
||||
opacity: 1;
|
||||
.chat-markdown a.chat-markdown-file-link:hover {
|
||||
color: var(--foreground);
|
||||
border-color: color-mix(in srgb, var(--border) 65%, var(--foreground));
|
||||
background: color-mix(in srgb, var(--muted) 72%, var(--background));
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.chat-markdown-file-link:focus-visible {
|
||||
.chat-markdown a.chat-markdown-file-link:focus-visible {
|
||||
outline: none;
|
||||
box-shadow: 0 0 0 1px color-mix(in srgb, var(--ring) 70%, transparent);
|
||||
}
|
||||
|
||||
.chat-markdown-file-link-icon {
|
||||
opacity: 0.72;
|
||||
}
|
||||
|
||||
.chat-markdown-file-link-label {
|
||||
color: color-mix(in srgb, var(--foreground) 88%, transparent);
|
||||
line-height: 1.1;
|
||||
box-shadow: 0 0 0 2px color-mix(in srgb, var(--ring) 70%, transparent);
|
||||
}
|
||||
|
||||
.chat-markdown pre {
|
||||
@@ -421,6 +483,24 @@ label:has(> select#reasoning-effort) select {
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.chat-markdown pre {
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: color-mix(in srgb, var(--border) 78%, transparent) transparent;
|
||||
}
|
||||
|
||||
.chat-markdown pre::-webkit-scrollbar {
|
||||
height: 7px;
|
||||
}
|
||||
|
||||
.chat-markdown pre::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.chat-markdown pre::-webkit-scrollbar-thumb {
|
||||
border-radius: 999px;
|
||||
background: color-mix(in srgb, var(--border) 78%, transparent);
|
||||
}
|
||||
|
||||
.markdown-file-link-tooltip-scroll {
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: color-mix(in srgb, var(--border) 78%, transparent) transparent;
|
||||
@@ -440,66 +520,115 @@ label:has(> select#reasoning-effort) select {
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-codeblock {
|
||||
--chat-markdown-codeblock-copy-button-space: 1.5rem;
|
||||
position: relative;
|
||||
margin: 0.65rem 0;
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 0.75rem;
|
||||
background: color-mix(in srgb, var(--muted) 78%, var(--background));
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-codeblock-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.5rem;
|
||||
border-bottom: 1px solid var(--border);
|
||||
background: var(--muted);
|
||||
padding: 0.25rem 0.375rem 0.25rem 0.7rem;
|
||||
color: var(--muted-foreground);
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-codeblock-title {
|
||||
display: inline-flex;
|
||||
min-width: 0;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
font-family: var(--font-mono, ui-monospace, SFMono-Regular, monospace);
|
||||
font-size: 0.6875rem;
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-chrome-action {
|
||||
color: var(--muted-foreground);
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-chrome-action:hover {
|
||||
color: var(--foreground);
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-chrome-action[aria-pressed="true"] {
|
||||
color: var(--foreground);
|
||||
background: color-mix(in srgb, var(--foreground) 8%, transparent);
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-codeblock pre {
|
||||
margin: 0;
|
||||
padding-right: calc(0.9rem + var(--chat-markdown-codeblock-copy-button-space));
|
||||
border: none;
|
||||
border-radius: 0;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-copy-button {
|
||||
position: absolute;
|
||||
top: 0.5rem;
|
||||
right: 0.5rem;
|
||||
z-index: 1;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 1.5rem;
|
||||
width: 1.5rem;
|
||||
border-radius: 0.375rem;
|
||||
border: 1px solid var(--border);
|
||||
background: color-mix(in srgb, var(--background) 82%, transparent);
|
||||
color: var(--muted-foreground);
|
||||
cursor: pointer;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transition:
|
||||
opacity 120ms ease,
|
||||
color 120ms ease,
|
||||
border-color 120ms ease;
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-codeblock:hover .chat-markdown-copy-button,
|
||||
.chat-markdown .chat-markdown-codeblock:focus-within .chat-markdown-copy-button {
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-copy-button:hover {
|
||||
color: var(--foreground);
|
||||
border-color: color-mix(in srgb, var(--border) 70%, var(--foreground));
|
||||
.chat-markdown .chat-markdown-codeblock[data-wrap="true"] pre {
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-shiki .shiki {
|
||||
background: color-mix(in srgb, var(--muted) 78%, var(--background)) !important;
|
||||
background: transparent !important;
|
||||
}
|
||||
|
||||
/* Diagnostics-style tables: row separators only, uppercase headers, and a
|
||||
scroll-fade container for horizontal overflow. The root chat-markdown
|
||||
wrapping rules (overflow-wrap: anywhere) would let columns shrink to single
|
||||
characters and defeat the overflow — restore word-boundary wrapping so the
|
||||
min column width is the longest word. */
|
||||
.chat-markdown table {
|
||||
width: 100%;
|
||||
min-width: max-content;
|
||||
border-collapse: collapse;
|
||||
overflow-wrap: normal;
|
||||
word-break: normal;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.chat-markdown th,
|
||||
.chat-markdown td {
|
||||
border: 1px solid var(--border);
|
||||
padding: 0.35rem 0.45rem;
|
||||
padding: 0.45rem 0.75rem;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.chat-markdown thead th {
|
||||
border-bottom: 1px solid color-mix(in srgb, var(--border) 60%, transparent);
|
||||
padding-block: 0.55rem;
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.chat-markdown tbody td {
|
||||
border-bottom: 1px solid color-mix(in srgb, var(--border) 60%, transparent);
|
||||
}
|
||||
|
||||
/* Collapsed (default): single-line cells truncate so arbitrary chat content
|
||||
cannot blow the column out; the footer toggle expands cells to wrap. */
|
||||
.chat-markdown .chat-markdown-table-container[data-expanded="false"] th,
|
||||
.chat-markdown .chat-markdown-table-container[data-expanded="false"] td {
|
||||
overflow: hidden;
|
||||
max-width: 24rem;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-table-container[data-expanded="true"] td {
|
||||
max-width: 24rem;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-table-footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-top: 0.125rem;
|
||||
}
|
||||
|
||||
@keyframes provider-update-pill-countdown {
|
||||
from {
|
||||
transform: scaleX(1);
|
||||
|
||||
@@ -0,0 +1,311 @@
|
||||
/**
|
||||
* Converts a DOM selection inside rendered chat markdown back into markdown
|
||||
* source so highlight-and-copy keeps formatting (links, emphasis, lists,
|
||||
* fences, tables) instead of flattening to plain text. The `text/plain`
|
||||
* clipboard flavor carries the markdown; `text/html` carries a sanitized
|
||||
* copy of the rendered fragment for rich-paste targets.
|
||||
*/
|
||||
|
||||
const SKIPPED_TAGS = new Set(["BUTTON", "INPUT", "SCRIPT", "STYLE", "TEMPLATE"]);
|
||||
const SKIPPED_CLASS_NAMES = ["select-none", "sr-only"];
|
||||
const SANITIZED_HTML_SELECTOR = [
|
||||
"button",
|
||||
"input",
|
||||
"script",
|
||||
"style",
|
||||
"svg",
|
||||
'[aria-hidden="true"]',
|
||||
...SKIPPED_CLASS_NAMES.map((className) => `.${className}`),
|
||||
].join(", ");
|
||||
|
||||
export interface MarkdownClipboardPayload {
|
||||
text: string;
|
||||
html: string;
|
||||
}
|
||||
|
||||
function isSkippedElement(element: Element): boolean {
|
||||
if (SKIPPED_TAGS.has(element.tagName) || element.localName === "svg") return true;
|
||||
if (element.getAttribute("aria-hidden") === "true") return true;
|
||||
return SKIPPED_CLASS_NAMES.some((className) => element.classList.contains(className));
|
||||
}
|
||||
|
||||
/** Hoists surrounding whitespace outside the markers: "` bold `" → " **bold** ". */
|
||||
function wrapInlineMarker(content: string, marker: string): string {
|
||||
const match = /^(\s*)([\s\S]*?)(\s*)$/.exec(content);
|
||||
const core = match?.[2] ?? "";
|
||||
if (!core) return content;
|
||||
return `${match?.[1] ?? ""}${marker}${core}${marker}${match?.[3] ?? ""}`;
|
||||
}
|
||||
|
||||
function wrapInlineCode(code: string): string {
|
||||
const longestRun = [...(code.match(/`+/g) ?? [])].reduce(
|
||||
(max, run) => Math.max(max, run.length),
|
||||
0,
|
||||
);
|
||||
const fence = "`".repeat(Math.max(1, longestRun + (longestRun > 0 ? 1 : 0)));
|
||||
const pad = code.startsWith("`") || code.endsWith("`") ? " " : "";
|
||||
return `${fence}${pad}${code}${pad}${fence}`;
|
||||
}
|
||||
|
||||
function codeFenceFor(code: string): string {
|
||||
const longestRun = [...(code.match(/`{3,}/g) ?? [])].reduce(
|
||||
(max, run) => Math.max(max, run.length),
|
||||
0,
|
||||
);
|
||||
return "`".repeat(Math.max(3, longestRun + 1));
|
||||
}
|
||||
|
||||
function resolveCodeBlockLanguage(pre: Element): string | null {
|
||||
const declared =
|
||||
pre.closest("[data-language]")?.getAttribute("data-language") ??
|
||||
/(?:^|\s)language-(\S+)/.exec(pre.querySelector("code")?.className ?? "")?.[1] ??
|
||||
null;
|
||||
return declared && declared !== "text" ? declared : null;
|
||||
}
|
||||
|
||||
function serializeCodeBlock(pre: Element): string {
|
||||
const code = (pre.textContent ?? "").replace(/\n$/, "");
|
||||
const fence = codeFenceFor(code);
|
||||
return `${fence}${resolveCodeBlockLanguage(pre) ?? ""}\n${code}\n${fence}\n\n`;
|
||||
}
|
||||
|
||||
function serializeTableCell(cell: Element): string {
|
||||
return serializeChildren(cell).replace(/\n+/g, " ").trim().replaceAll("|", "\\|");
|
||||
}
|
||||
|
||||
function tableSeparatorFor(headerCells: Element[]): string {
|
||||
const markers = headerCells.map((cell) => {
|
||||
const align = (cell as HTMLElement).style?.textAlign ?? cell.getAttribute("align") ?? "";
|
||||
if (align === "center") return ":---:";
|
||||
if (align === "right") return "---:";
|
||||
return "---";
|
||||
});
|
||||
return `| ${markers.join(" | ")} |`;
|
||||
}
|
||||
|
||||
function serializeTable(table: Element): string {
|
||||
const rows = [...table.querySelectorAll(":scope > thead > tr, :scope > tbody > tr, :scope > tr")];
|
||||
if (rows.length === 0) return "";
|
||||
const lines: string[] = [];
|
||||
let emittedSeparator = false;
|
||||
for (const row of rows) {
|
||||
const cells = [...row.children].filter(
|
||||
(cell) => cell.tagName === "TH" || cell.tagName === "TD",
|
||||
);
|
||||
if (cells.length === 0) continue;
|
||||
lines.push(`| ${cells.map((cell) => serializeTableCell(cell)).join(" | ")} |`);
|
||||
if (!emittedSeparator) {
|
||||
lines.push(tableSeparatorFor(cells));
|
||||
emittedSeparator = true;
|
||||
}
|
||||
}
|
||||
return `${lines.join("\n")}\n\n`;
|
||||
}
|
||||
|
||||
function serializeListItem(item: Element, ordered: boolean, index: number): string {
|
||||
const checkbox = item.querySelector('input[type="checkbox"]');
|
||||
const task = checkbox ? `[${(checkbox as HTMLInputElement).checked ? "x" : " "}] ` : "";
|
||||
const marker = ordered ? `${index}. ${task}` : `- ${task}`;
|
||||
let content = serializeChildren(item)
|
||||
.replace(/\n{3,}/g, "\n\n")
|
||||
.trim();
|
||||
// Tight list items (no paragraph children) keep nested lists on adjacent lines.
|
||||
if (!item.querySelector(":scope > p")) {
|
||||
content = content.replace(/\n{2,}/g, "\n");
|
||||
}
|
||||
const continuationIndent = " ".repeat(marker.length);
|
||||
const [first = "", ...rest] = content.split("\n");
|
||||
return [
|
||||
`${marker}${first}`,
|
||||
...rest.map((line) => (line.length > 0 ? `${continuationIndent}${line}` : line)),
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
function serializeList(list: Element, ordered: boolean): string {
|
||||
const start = Number.parseInt(list.getAttribute("start") ?? "1", 10) || 1;
|
||||
const items = [...list.children].filter((child) => child.tagName === "LI");
|
||||
if (items.length === 0) return "";
|
||||
return `${items.map((item, index) => serializeListItem(item, ordered, start + index)).join("\n")}\n\n`;
|
||||
}
|
||||
|
||||
function serializeBlockquote(quote: Element): string {
|
||||
const content = serializeChildren(quote)
|
||||
.replace(/\n{3,}/g, "\n\n")
|
||||
.trim();
|
||||
if (!content) return "";
|
||||
const quoted = content
|
||||
.split("\n")
|
||||
.map((line) => (line.length > 0 ? `> ${line}` : ">"))
|
||||
.join("\n");
|
||||
return `${quoted}\n\n`;
|
||||
}
|
||||
|
||||
function serializeDetails(details: Element): string {
|
||||
const summary =
|
||||
details.querySelector(":scope > [data-markdown-details-summary]")?.textContent?.trim() ??
|
||||
"Details";
|
||||
const contentNode = details.querySelector(":scope > * [data-markdown-details-content]");
|
||||
const content = contentNode ? serializeChildren(contentNode).trim() : "";
|
||||
const open = details.getAttribute("data-markdown-details-open") === "true" ? " open" : "";
|
||||
return `<details${open}>\n<summary>${summary}</summary>${content ? `\n\n${content}` : ""}\n</details>\n\n`;
|
||||
}
|
||||
|
||||
function serializeAnchor(anchor: Element): string {
|
||||
const markdownCopy = anchor.getAttribute("data-markdown-copy");
|
||||
if (markdownCopy !== null) return markdownCopy;
|
||||
const content = serializeChildren(anchor);
|
||||
const href = anchor.getAttribute("href") ?? "";
|
||||
if (!/^https?:\/\//i.test(href)) return content;
|
||||
const label = content.trim();
|
||||
if (!label) return "";
|
||||
if (label === href) return href;
|
||||
return `[${label}](${href})`;
|
||||
}
|
||||
|
||||
function serializeChildren(node: Node): string {
|
||||
let out = "";
|
||||
for (const child of node.childNodes) {
|
||||
out += serializeNode(child);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function serializeNode(node: Node): string {
|
||||
if (node.nodeType === Node.TEXT_NODE) {
|
||||
const text = node.textContent ?? "";
|
||||
// Inter-block formatting whitespace from the renderer collapses to a
|
||||
// newline; real inline whitespace passes through untouched.
|
||||
if (text.includes("\n") && text.trim().length === 0) return "\n";
|
||||
return text;
|
||||
}
|
||||
if (node.nodeType !== Node.ELEMENT_NODE) return "";
|
||||
const element = node as Element;
|
||||
if (element.hasAttribute("data-markdown-details")) {
|
||||
return serializeDetails(element);
|
||||
}
|
||||
const markdownCopy = element.getAttribute("data-markdown-copy");
|
||||
if (markdownCopy !== null) return markdownCopy;
|
||||
if (isSkippedElement(element)) return "";
|
||||
|
||||
const headingLevel = /^H([1-6])$/.exec(element.tagName)?.[1];
|
||||
if (headingLevel) {
|
||||
return `${"#".repeat(Number(headingLevel))} ${serializeChildren(element).trim()}\n\n`;
|
||||
}
|
||||
|
||||
switch (element.tagName) {
|
||||
case "BR":
|
||||
return "\n";
|
||||
case "HR":
|
||||
return "---\n\n";
|
||||
case "P":
|
||||
return `${serializeChildren(element).trim()}\n\n`;
|
||||
case "PRE":
|
||||
return serializeCodeBlock(element);
|
||||
case "CODE":
|
||||
return wrapInlineCode(element.textContent ?? "");
|
||||
case "STRONG":
|
||||
case "B":
|
||||
return wrapInlineMarker(serializeChildren(element), "**");
|
||||
case "EM":
|
||||
case "I":
|
||||
return wrapInlineMarker(serializeChildren(element), "*");
|
||||
case "DEL":
|
||||
case "S":
|
||||
return wrapInlineMarker(serializeChildren(element), "~~");
|
||||
case "A":
|
||||
return serializeAnchor(element);
|
||||
case "IMG": {
|
||||
const alt = element.getAttribute("alt") ?? "";
|
||||
const src = element.getAttribute("src") ?? "";
|
||||
return alt && src ? `` : "";
|
||||
}
|
||||
case "UL":
|
||||
return serializeList(element, false);
|
||||
case "OL":
|
||||
return serializeList(element, true);
|
||||
case "BLOCKQUOTE":
|
||||
return serializeBlockquote(element);
|
||||
case "TABLE":
|
||||
return serializeTable(element);
|
||||
case "DIV":
|
||||
case "SECTION":
|
||||
case "ARTICLE": {
|
||||
const content = serializeChildren(element);
|
||||
return content && !content.endsWith("\n") ? `${content}\n` : content;
|
||||
}
|
||||
default:
|
||||
return serializeChildren(element);
|
||||
}
|
||||
}
|
||||
|
||||
/** Collapses serializer spacing artifacts without touching fenced code content. */
|
||||
function tidyMarkdown(markdown: string): string {
|
||||
return markdown
|
||||
.split(/(```[\s\S]*?(?:```|$))/)
|
||||
.map((part, index) =>
|
||||
index % 2 === 1 ? part : part.replace(/[ \t]+(?=\n)/g, "").replace(/\n{3,}/g, "\n\n"),
|
||||
)
|
||||
.join("")
|
||||
.trim();
|
||||
}
|
||||
|
||||
export function serializeRenderedMarkdownFragment(container: Node): string {
|
||||
return tidyMarkdown(serializeChildren(container));
|
||||
}
|
||||
|
||||
export function serializeTableElementToMarkdown(table: Element): string {
|
||||
return serializeTable(table).trim();
|
||||
}
|
||||
|
||||
function csvCell(value: string): string {
|
||||
const normalized = value.replace(/\s+/g, " ").trim();
|
||||
return /[",\n]/.test(normalized) ? `"${normalized.replaceAll('"', '""')}"` : normalized;
|
||||
}
|
||||
|
||||
export function serializeTableElementToCsv(table: Element): string {
|
||||
const rows = [...table.querySelectorAll(":scope > thead > tr, :scope > tbody > tr, :scope > tr")];
|
||||
const lines: string[] = [];
|
||||
for (const row of rows) {
|
||||
const cells = [...row.children].filter(
|
||||
(cell) => cell.tagName === "TH" || cell.tagName === "TD",
|
||||
);
|
||||
if (cells.length === 0) continue;
|
||||
lines.push(cells.map((cell) => csvCell(cell.textContent ?? "")).join(","));
|
||||
}
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
function sanitizedHtmlFrom(container: Element): string {
|
||||
for (const node of container.querySelectorAll(SANITIZED_HTML_SELECTOR)) {
|
||||
if (
|
||||
node.classList.contains("chat-markdown-file-link") ||
|
||||
node.closest(".chat-markdown-file-link")
|
||||
) {
|
||||
if (node.getAttribute("aria-hidden") === "true" || node.localName === "svg") {
|
||||
node.remove();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
node.remove();
|
||||
}
|
||||
return `<meta charset="utf-8">${container.innerHTML}`;
|
||||
}
|
||||
|
||||
export function chatMarkdownClipboardPayload(
|
||||
selection: Selection,
|
||||
): MarkdownClipboardPayload | null {
|
||||
const texts: string[] = [];
|
||||
const htmls: string[] = [];
|
||||
for (let index = 0; index < selection.rangeCount; index += 1) {
|
||||
const range = selection.getRangeAt(index);
|
||||
if (range.collapsed) continue;
|
||||
const container = document.createElement("div");
|
||||
container.appendChild(range.cloneContents());
|
||||
const text = serializeRenderedMarkdownFragment(container);
|
||||
if (!text) continue;
|
||||
texts.push(text);
|
||||
htmls.push(sanitizedHtmlFrom(container));
|
||||
}
|
||||
if (texts.length === 0) return null;
|
||||
return { text: texts.join("\n\n"), html: htmls.join("") };
|
||||
}
|
||||
@@ -69,6 +69,24 @@ function toLowercaseLookup(source: Record<string, string>): Record<string, strin
|
||||
return lookup;
|
||||
}
|
||||
|
||||
const extensionByLanguageId: Record<string, string> = {};
|
||||
for (const [extension, languageId] of Object.entries(languageAssociations.extensionToLanguageId)) {
|
||||
const key = languageId.toLowerCase();
|
||||
if (!(key in extensionByLanguageId)) {
|
||||
extensionByLanguageId[key] = extension.toLowerCase();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Synthesizes a file name whose icon resolution best represents a markdown
|
||||
* fence language id — handles both extension-style ids ("ts", "py") and
|
||||
* language ids ("typescript", "python", "shellscript").
|
||||
*/
|
||||
export function syntheticFileNameForLanguageId(languageId: string): string {
|
||||
const normalized = languageId.toLowerCase();
|
||||
return `file.${extensionByLanguageId[normalized] ?? normalized}`;
|
||||
}
|
||||
|
||||
export function basenameOfPath(pathValue: string): string {
|
||||
const slashIndex = pathValue.lastIndexOf("/");
|
||||
if (slashIndex === -1) return pathValue;
|
||||
@@ -166,6 +184,17 @@ function resolveFolderDefinition(pathValue: string, theme: "light" | "dark"): st
|
||||
);
|
||||
}
|
||||
|
||||
/** True when the file name resolves to a real icon rather than the generic default. */
|
||||
export function hasSpecificVscodeIconForFileName(
|
||||
fileName: string,
|
||||
theme: "light" | "dark",
|
||||
): boolean {
|
||||
const definition = resolveFileDefinition(fileName, theme);
|
||||
return (
|
||||
definition !== defaultDarkFileIconDefinition && definition !== defaultLightFileIconDefinition
|
||||
);
|
||||
}
|
||||
|
||||
export function getVscodeIconUrlForEntry(
|
||||
pathValue: string,
|
||||
kind: "file" | "directory",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { serializeComposerMentionPath } from "./composerTrigger.ts";
|
||||
import { serializeComposerFileLink, serializeComposerMentionPath } from "./composerTrigger.ts";
|
||||
|
||||
describe("serializeComposerMentionPath", () => {
|
||||
it("keeps simple mention paths unquoted", () => {
|
||||
@@ -15,3 +15,29 @@ describe("serializeComposerMentionPath", () => {
|
||||
expect(serializeComposerMentionPath('docs/My "File".md')).toBe('"docs/My \\"File\\".md"');
|
||||
});
|
||||
});
|
||||
|
||||
describe("serializeComposerFileLink", () => {
|
||||
it("uses the basename as the markdown label", () => {
|
||||
expect(serializeComposerFileLink("path/to/package.json")).toBe(
|
||||
"[package.json](path/to/package.json)",
|
||||
);
|
||||
});
|
||||
|
||||
it("encodes markdown-sensitive destination characters", () => {
|
||||
expect(serializeComposerFileLink("docs/My File (draft).md")).toBe(
|
||||
"[My File (draft).md](docs/My%20File%20%28draft%29.md)",
|
||||
);
|
||||
});
|
||||
|
||||
it("supports windows paths", () => {
|
||||
expect(serializeComposerFileLink("C:\\repo\\src\\index.ts")).toBe(
|
||||
"[index.ts](C:%5Crepo%5Csrc%5Cindex.ts)",
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves paths that legitimately start with an at sign", () => {
|
||||
expect(serializeComposerFileLink("@scope/package.json")).toBe(
|
||||
"[package.json](@scope/package.json)",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -17,6 +17,29 @@ export function serializeComposerMentionPath(path: string): string {
|
||||
return `"${path.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
|
||||
}
|
||||
|
||||
function composerFileLinkBasename(path: string): string {
|
||||
const separatorIndex = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
|
||||
return separatorIndex >= 0 ? path.slice(separatorIndex + 1) : path;
|
||||
}
|
||||
|
||||
function escapeMarkdownLinkLabel(label: string): string {
|
||||
return label.replaceAll("\\", "\\\\").replaceAll("[", "\\[").replaceAll("]", "\\]");
|
||||
}
|
||||
|
||||
function encodeMarkdownLinkDestination(path: string): string {
|
||||
return encodeURI(path)
|
||||
.replaceAll("(", "%28")
|
||||
.replaceAll(")", "%29")
|
||||
.replaceAll("#", "%23")
|
||||
.replaceAll("?", "%3F")
|
||||
.replaceAll("\\", "%5C");
|
||||
}
|
||||
|
||||
export function serializeComposerFileLink(path: string): string {
|
||||
const label = escapeMarkdownLinkLabel(composerFileLinkBasename(path));
|
||||
return `[${label}](${encodeMarkdownLinkDestination(path)})`;
|
||||
}
|
||||
|
||||
function clampCursor(text: string, cursor: number): number {
|
||||
if (!Number.isFinite(cursor)) return text.length;
|
||||
return Math.max(0, Math.min(text.length, Math.floor(cursor)));
|
||||
|
||||
Generated
+43
@@ -521,6 +521,15 @@ importers:
|
||||
react-markdown:
|
||||
specifier: ^10.1.0
|
||||
version: 10.1.0(@types/[email protected])([email protected])
|
||||
rehype-raw:
|
||||
specifier: ^7.0.0
|
||||
version: 7.0.0
|
||||
rehype-sanitize:
|
||||
specifier: ^6.0.0
|
||||
version: 6.0.0
|
||||
remark-breaks:
|
||||
specifier: ^4.0.0
|
||||
version: 4.0.0
|
||||
remark-gfm:
|
||||
specifier: ^4.0.1
|
||||
version: 4.0.1
|
||||
@@ -6483,6 +6492,9 @@ packages:
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-Y8/SBAHkZGoNkpzqqfCldijcuUKh7/su31kEBp67cFY09Wy0mTRgtsLYsiIxMJxlu0f6AA5SUTbDR8K0rxnbUw==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-3yTWghByc50aGS7JlGhk61SPenfE/p1oaFeNwkOOyrscaOkMGrcW9+Cy/QAIOBpZxP1yqDIzFMR0+Np0i0+usg==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw==}
|
||||
|
||||
@@ -7238,6 +7250,9 @@ packages:
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-EcmOpxsZ96CvlP03NghtH1EsLtr0n9Tm4lPUJUBccV9RwUOneqSycg19n5HGzCf+10LozMRSObtVr3ee1WoHtg==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-MbgeFca0hLYIEx/2zGsszCSEJJ1JSCdiY5xQxRcLDDGa8EPvlLPupJ4DSajbMPAnC0je8jfb9TiUATnxxrHUog==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-TqICwyvJJpBwvGAMZjj4J2n0X8QWp21b9l0o7eXyVJ25YNWYbJDVIyD1bZXE6WtV6RmKJVYmQAKWa0zWOABz2w==}
|
||||
|
||||
@@ -8350,12 +8365,18 @@ packages:
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-/aE8hCfKlQeA8LmyeyQvQF3eBiLRGNlfBJEvWH7ivp9sBqs7TNqBL5X3v157rM4IFETqDnIOO+z5M/biZbo9Ww==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-CsnhKNsyI8Tub6L4sm5ZFsme4puGfc6pYylvXo1AeqaGbjOYyzNv3qZPwvs0oMJ39eryyeOdmxwUIo94IpEhqg==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-k9ecfXHmIPuFVI61B9DeLPN0qFHfawM6RsuX48hoqlaKSF61RskNjSm1lI8PhBEM0MRdLxVVm4WmTqJQccH9mA==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-j31mdaRFrwFRUIlxGeuPXXKWQxet52RBQRvCmzl5eCefn/KGbomK5GMHNMsOJf55fgo3qw5tST5neDuarDYR2A==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-IjEjJOkH4FuJvHZVIW0QCDWxcG96kCq7An/KVH2NfJe6rKZU2AsHeB3OEjPNRxi4QC34Xdx7I2KGYn6IpT7gxQ==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg==}
|
||||
|
||||
@@ -15786,6 +15807,12 @@ snapshots:
|
||||
web-namespaces: 2.0.1
|
||||
zwitch: 2.0.4
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
'@types/hast': 3.0.4
|
||||
'@ungap/structured-clone': 1.3.1
|
||||
unist-util-position: 5.0.0
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
'@types/hast': 3.0.4
|
||||
@@ -16580,6 +16607,11 @@ snapshots:
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
'@types/mdast': 4.0.4
|
||||
mdast-util-find-and-replace: 3.0.2
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
'@types/mdast': 4.0.4
|
||||
@@ -17962,6 +17994,11 @@ snapshots:
|
||||
hast-util-raw: 9.1.0
|
||||
vfile: 6.0.3
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
'@types/hast': 3.0.4
|
||||
hast-util-sanitize: 5.0.2
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
'@types/hast': 3.0.4
|
||||
@@ -17975,6 +18012,12 @@ snapshots:
|
||||
rehype-stringify: 10.0.1
|
||||
unified: 11.0.5
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
'@types/mdast': 4.0.4
|
||||
mdast-util-newline-to-break: 2.0.0
|
||||
unified: 11.0.5
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
'@types/mdast': 4.0.4
|
||||
|
||||
Reference in new issue
Block a user