Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(web): add community code attachment previews (#463)

Gener3c51a5eab5ca
diff --git a/src/web/src/components/community/attachment-card.test.ts b/src/web/src/components/community/attachment-card.test.ts
index f5403889b..32e3fbe6d 100644
--- a/src/web/src/components/community/attachment-card.test.ts
+++ b/src/web/src/components/community/attachment-card.test.ts
@@ -55,4 +55,27 @@ describe("AttachmentCard", () => {
expect(onDownload).toHaveBeenCalledWith("/attachments/a1", "报告.pdf")
expect(onPreview).not.toHaveBeenCalled()
})
+
+ it.each([
+ ["source.ts", "application/octet-stream", "code"],
+ ["unsafe.svg", "image/svg+xml", "code"],
+ ])("opens %s through the source preview instead of download", (name, contentType, category) => {
+ const onPreview = vi.fn()
+ const onDownload = vi.fn()
+ const source = attachment({ name, contentType })
+ let renderer: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(React.createElement(AttachmentCard, {
+ attachment: source,
+ onPreview,
+ onDownload,
+ }))
+ })
+ const button = renderer!.root.findByType("button")
+ expect(button.props["data-attachment-category"]).toBe(category)
+ expect(button.props["aria-label"]).toBe(`Preview ${name}`)
+ act(() => button.props.onClick())
+ expect(onPreview).toHaveBeenCalledWith(source)
+ expect(onDownload).not.toHaveBeenCalled()
+ })
})
diff --git a/src/web/src/components/community/attachment-preview-sheet.test.ts b/src/web/src/components/community/attachment-preview-sheet.test.ts
index fe6a84e2d..0c8bf8fd6 100644
--- a/src/web/src/components/community/attachment-preview-sheet.test.ts
+++ b/src/web/src/components/community/attachment-preview-sheet.test.ts
@@ -27,6 +27,14 @@ vi.mock("./message-body", () => ({
MessageBody: ({ text }: { text: string }) => React.createElement("article", { "data-markdown": true }, text),
}))
+vi.mock("./code-preview", () => ({
+ CodePreview: ({ content, language }: { content: string; language: string | null }) => React.createElement(
+ "pre",
+ { "data-code-language": language ?? "plain" },
+ content,
+ ),
+}))
+
function file(overrides: Partial<FileAttachment> = {}): FileAttachment {
return {
kind: "file",
@@ -121,4 +129,60 @@ describe("AttachmentPreviewSheet", () => {
await flush()
expect(renderer!.root.findAllByType("pre")[0]?.children).toEqual(["second"])
})
+
+ it("passes the resolved source language to CodePreview", async () => {
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("const answer = 42", { status: 200 })))
+ let renderer: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(React.createElement(AttachmentPreviewSheet, {
+ attachment: file({ name: "answer.ts", contentType: "application/octet-stream" }),
+ open: true,
+ onOpenChange: vi.fn(),
+ }))
+ })
+ await flush()
+ const preview = renderer!.root.findByProps({ "data-code-language": "typescript" })
+ expect(preview.children).toEqual(["const answer = 42"])
+ expect(renderer!.root.findByProps({ "data-testid": "community-attachment-preview-content" }).props.className)
+ .toContain("p-0")
+ expect(renderer!.root.findByProps({ "data-testid": "community-attachment-preview-content" }).props.className)
+ .toContain("sm:p-0")
+ })
+
+ it("keeps the existing SheetBody spacing for Markdown", async () => {
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("# Hello", { status: 200 })))
+ let renderer: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(React.createElement(AttachmentPreviewSheet, {
+ attachment: file(),
+ open: true,
+ onOpenChange: vi.fn(),
+ }))
+ })
+ await flush()
+
+ expect(renderer!.root.findByProps({ "data-testid": "community-attachment-preview-content" }).props.className)
+ .not.toContain("p-0")
+ expect(renderer!.root.findByProps({ "data-testid": "community-attachment-preview-content" }).props.className)
+ .not.toContain("sm:p-0")
+ })
+
+ it("keeps the existing one MiB ceiling for code", async () => {
+ const fetchMock = vi.fn()
+ vi.stubGlobal("fetch", fetchMock)
+ let renderer: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(React.createElement(AttachmentPreviewSheet, {
+ attachment: file({
+ name: "large.ts",
+ contentType: "application/octet-stream",
+ sizeBytes: 1024 * 1024 + 1,
+ }),
+ open: true,
+ onOpenChange: vi.fn(),
+ }))
+ })
+ expect(fetchMock).not.toHaveBeenCalled()
+ expect(renderer!.root.findAllByType("p").some((node) => node.children.join("").includes("too large"))).toBe(true)
+ })
})
diff --git a/src/web/src/components/community/attachment-preview-sheet.tsx b/src/web/src/components/community/attachment-preview-sheet.tsx
index ecd1835cf..232daedb0 100644
--- a/src/web/src/components/community/attachment-preview-sheet.tsx
+++ b/src/web/src/components/community/attachment-preview-sheet.tsx
@@ -14,6 +14,7 @@ import {
import { SheetResizeHandle, useSheetResize } from "@/components/ui/sheet-resize-handle"
import { cn } from "@/lib/utils"
import { MessageBody } from "./message-body"
+import { CodePreview } from "./code-preview"
import type { FileAttachment } from "./_types"
import { tid } from "@/lib/community/testids"
import {
@@ -183,7 +184,13 @@ export function AttachmentPreviewSheet({
</button>
</div>
</SheetHeader>
- <SheetBody data-testid={tid.attachmentPreviewContent} className="min-h-0">
+ <SheetBody
+ data-testid={tid.attachmentPreviewContent}
+ className={cn(
+ "flex min-h-0 flex-col",
+ (presentation?.previewKind === "code" || presentation?.previewKind === "text") && "p-0 sm:p-0",
+ )}
+ >
{preview.status === "loading" && (
<div className="flex items-center justify-center gap-2 py-8 text-sm text-muted-foreground">
<Loader2 className="size-4 animate-spin" />
@@ -200,7 +207,7 @@ export function AttachmentPreviewSheet({
<MessageBody text={preview.content} />
)}
{preview.status === "ready" && presentation?.previewKind !== "markdown" && (
- <pre className="whitespace-pre-wrap wrap-break-word font-mono text-sm text-foreground">{preview.content}</pre>
+ <CodePreview content={preview.content} language={presentation?.shikiLanguage ?? null} />
)}
</SheetBody>
</SheetContent>
diff --git a/src/web/src/components/community/code-preview.test.ts b/src/web/src/components/community/code-preview.test.ts
new file mode 100644
index 000000000..39d1060d5
--- /dev/null
+++ b/src/web/src/components/community/code-preview.test.ts
@@ -0,0 +1,199 @@
+import React from "react"
+import TestRenderer, { act } from "react-test-renderer"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import type { CodeHighlightResult } from "@/lib/community/code-highlight"
+import { tid } from "@/lib/community/testids"
+import { CodePreview } from "./code-preview"
+
+const highlightCodeMock = vi.hoisted(() => vi.fn())
+
+vi.mock("@/lib/community/code-highlight", () => ({
+ MAX_CODE_HIGHLIGHT_LINES: 2_000,
+ highlightCode: highlightCodeMock,
+}))
+
+vi.mock("@/components/ui/button", () => ({
+ Button: ({ children, ...props }: React.ComponentProps<"button">) => React.createElement("button", props, children),
+}))
+
+function deferred<T>() {
+ let resolve!: (value: T) => void
+ const promise = new Promise<T>((resolvePromise) => {
+ resolve = resolvePromise
+ })
+ return { promise, resolve }
+}
+
+async function flush(): Promise<void> {
+ await act(async () => {
+ await Promise.resolve()
+ await Promise.resolve()
+ })
+}
+
+beforeEach(() => {
+ highlightCodeMock.mockReset().mockResolvedValue({ kind: "plain", lines: null, reason: null })
+})
+
+afterEach(() => {
+ vi.useRealTimers()
+ vi.unstubAllGlobals()
+})
+
+describe("CodePreview", () => {
+ it("renders as a flat Sheet panel without card chrome", async () => {
+ let renderer: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(React.createElement(CodePreview, {
+ content: "plain source",
+ language: null,
+ }))
+ })
+ await flush()
+
+ const preview = renderer!.root.findByProps({ "data-testid": tid.codePreview })
+ expect(preview.props.className).not.toMatch(/rounded|\bborder\b|bg-/)
+ const toolbar = preview.findAllByType("div")[0]!
+ expect(toolbar.props.className).not.toMatch(/\bborder\b|border-|bg-/)
+ })
+
+ it("renders language, line numbers, and theme-aware Shiki tokens", async () => {
+ highlightCodeMock.mockResolvedValue({
+ kind: "highlighted",
+ lines: [
+ [{ content: "const", light: { color: "#111111" }, dark: { color: "#eeeeee" } }],
+ [{ content: "answer", light: { color: "#222222" }, dark: { color: "#dddddd" } }],
+ ],
+ reason: null,
+ })
+ let renderer: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(React.createElement(CodePreview, {
+ content: "const\nanswer",
+ language: "typescript",
+ }))
+ })
+ await flush()
+
+ expect(renderer!.root.findByProps({ "data-testid": tid.codePreviewLanguage }).children).toEqual(["TypeScript"])
+ expect(renderer!.root.findAll((node) => node.type === "span" && node.props["aria-hidden"] === "true").map((node) => node.children[0]))
+ .toEqual(["1", "2"])
+ const token = renderer!.root.findAllByType("code")[0]!.findByType("span")
+ expect(token.props.style).toMatchObject({
+ "--code-token-light": "#111111",
+ "--code-token-dark": "#eeeeee",
+ })
+ expect(token.children).toEqual(["const"])
+ })
+
+ it("toggles wrapping and copies the exact original source", async () => {
+ vi.useFakeTimers()
+ const writeText = vi.fn().mockResolvedValue(undefined)
+ vi.stubGlobal("navigator", { clipboard: { writeText } })
+ const source = "{\n \"raw\": true\n}"
+ let renderer: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(React.createElement(CodePreview, { content: source, language: "json" }))
+ })
+ await flush()
+
+ const wrap = renderer!.root.findByProps({ "data-testid": tid.codePreviewWrap })
+ expect(wrap.props["aria-pressed"]).toBe(false)
+ act(() => wrap.props.onClick())
+ expect(renderer!.root.findByProps({ "data-testid": tid.codePreviewWrap }).props["aria-pressed"]).toBe(true)
+
+ const copy = renderer!.root.findByProps({ "data-testid": tid.codePreviewCopy })
+ await act(async () => copy.props.onClick())
+ expect(writeText).toHaveBeenCalledWith(source)
+ expect(renderer!.root.findByProps({ "data-testid": tid.codePreviewCopy }).props["aria-label"]).toBe("Copied")
+ })
+
+ it("offers retry feedback when clipboard access fails", async () => {
+ const writeText = vi.fn().mockRejectedValue(new Error("denied"))
+ vi.stubGlobal("navigator", { clipboard: { writeText } })
+ let renderer: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(React.createElement(CodePreview, {
+ content: "exact source",
+ language: null,
+ }))
+ })
+ await flush()
+
+ const copy = renderer!.root.findByProps({ "data-testid": tid.codePreviewCopy })
+ await act(async () => copy.props.onClick())
+ expect(writeText).toHaveBeenCalledWith("exact source")
+ expect(renderer!.root.findByProps({ "data-testid": tid.codePreviewCopy }).props["aria-label"]).toBe("Copy failed")
+ })
+
+ it("shows the highlight budget or loader failure while retaining plain text", async () => {
+ highlightCodeMock.mockResolvedValue({
+ kind: "plain",
+ lines: null,
+ reason: "Syntax highlighting disabled for large files",
+ })
+ let renderer: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(React.createElement(CodePreview, {
+ content: "still readable",
+ language: "json",
+ }))
+ })
+ await flush()
+
+ expect(renderer!.root.findByProps({ "data-testid": tid.codePreviewStatus }).children)
+ .toEqual(["Syntax highlighting disabled for large files"])
+ expect(renderer!.root.findByType("code").children).toEqual(["still readable"])
+ })
+
+ it("renders active source as text nodes without mounting uploaded elements", async () => {
+ const source = '<script>globalThis.pwned = true</script><iframe src="https://example.com"></iframe><svg onload="pwn()" />'
+ let renderer: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(React.createElement(CodePreview, { content: source, language: "html" }))
+ })
+ await flush()
+
+ expect(renderer!.root.findByType("code").children).toEqual([source])
+ expect(renderer!.root.findAllByType("script")).toHaveLength(0)
+ expect(renderer!.root.findAllByType("iframe")).toHaveLength(0)
+ expect(renderer!.root.findAll((node) => node.props.dangerouslySetInnerHTML !== undefined)).toHaveLength(0)
+ })
+
+ it("ignores a stale tokenization result after the attachment changes", async () => {
+ const first = deferred<CodeHighlightResult>()
+ const second = deferred<CodeHighlightResult>()
+ highlightCodeMock
+ .mockReturnValueOnce(first.promise)
+ .mockReturnValueOnce(second.promise)
+ let renderer: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(React.createElement(CodePreview, {
+ content: "old",
+ language: "typescript",
+ }))
+ })
+ await act(async () => {
+ renderer!.update(React.createElement(CodePreview, {
+ content: "new",
+ language: "typescript",
+ }))
+ })
+
+ second.resolve({
+ kind: "highlighted",
+ lines: [[{ content: "new-token", light: {}, dark: {} }]],
+ reason: null,
+ })
+ await flush()
+ expect(renderer!.root.findByType("code").findByType("span").children).toEqual(["new-token"])
+
+ first.resolve({
+ kind: "highlighted",
+ lines: [[{ content: "old-token", light: {}, dark: {} }]],
+ reason: null,
+ })
+ await flush()
+ expect(renderer!.root.findByType("code").findByType("span").children).toEqual(["new-token"])
+ })
+})
diff --git a/src/web/src/components/community/code-preview.tsx b/src/web/src/components/community/code-preview.tsx
new file mode 100644
index 000000000..f3125f964
--- /dev/null
+++ b/src/web/src/components/community/code-preview.tsx
@@ -0,0 +1,213 @@
+"use client"
+
+import { useEffect, useRef, useState, type CSSProperties } from "react"
+import { Check, Copy, WrapText } from "lucide-react"
+import { Button } from "@/components/ui/button"
+import { cn } from "@/lib/utils"
+import { highlightCode, MAX_CODE_HIGHLIGHT_LINES, type CodeHighlightResult, type CodeToken } from "@/lib/community/code-highlight"
+import type { ShikiLanguage } from "@/lib/community/attachment-presentation"
+import { tid } from "@/lib/community/testids"
+
+const LANGUAGE_LABELS: Record<ShikiLanguage, string> = {
+ bash: "Shell",
+ c: "C",
+ cpp: "C++",
+ csharp: "C#",
+ css: "CSS",
+ diff: "Diff",
+ dockerfile: "Dockerfile",
+ dotenv: "Environment",
+ go: "Go",
+ graphql: "GraphQL",
+ hcl: "HCL",
+ html: "HTML source",
+ ini: "Config",
+ java: "Java",
+ javascript: "JavaScript",
+ json: "JSON",
+ jsonl: "JSON Lines",
+ jsx: "JSX",
+ kotlin: "Kotlin",
+ log: "Log",
+ makefile: "Makefile",
+ mdx: "MDX source",
+ php: "PHP",
+ proto: "Protocol Buffers",
+ python: "Python",
+ ruby: "Ruby",
+ rust: "Rust",
+ scss: "SCSS",
+ sql: "SQL",
+ svelte: "Svelte",
+ swift: "Swift",
+ toml: "TOML",
+ tsx: "TSX",
+ typescript: "TypeScript",
+ vue: "Vue",
+ xml: "XML source",
+ yaml: "YAML",
+}
+
+type TokenStyle = CSSProperties & {
+ "--code-token-light"?: string
+ "--code-token-dark"?: string
+}
+
+function tokenStyle(token: CodeToken): TokenStyle {
+ const fontStyle = token.light.fontStyle ?? token.dark.fontStyle ?? 0
+ const decorations = [
+ fontStyle & 4 ? "underline" : "",
+ fontStyle & 8 ? "line-through" : "",
+ ].filter(Boolean).join(" ")
+ return {
+ "--code-token-light": token.light.color,
+ "--code-token-dark": token.dark.color,
+ fontStyle: fontStyle & 1 ? "italic" : undefined,
+ fontWeight: fontStyle & 2 ? 600 : undefined,
+ textDecoration: decorations || undefined,
+ }
+}
+
+function sourceLines(content: string): string[] {
+ return content.split("\n")
+}
+
+function lineNumbers(count: number): string {
+ return Array.from({ length: count }, (_, index) => String(index + 1)).join("\n")
+}
+
+export function CodePreview({
+ content,
+ language,
+}: {
+ content: string
+ language: ShikiLanguage | null
+}) {
+ const [highlight, setHighlight] = useState<CodeHighlightResult>({ kind: "plain", lines: null, reason: null })
+ const [highlighting, setHighlighting] = useState(false)
+ const [wrap, setWrap] = useState(false)
+ const [copyState, setCopyState] = useState<"idle" | "copied" | "failed">("idle")
+ const copyTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
+
+ useEffect(() => {
+ let active = true
+ setHighlight({ kind: "plain", lines: null, reason: null })
+ setHighlighting(language !== null)
+ setCopyState("idle")
+ if (copyTimer.current) clearTimeout(copyTimer.current)
+ void highlightCode(content, language).then((result) => {
+ if (!active) return
+ setHighlight(result)
+ setHighlighting(false)
+ })
+ return () => {
+ active = false
+ }
+ }, [content, language])
+
+ useEffect(() => () => {
+ if (copyTimer.current) clearTimeout(copyTimer.current)
+ }, [])
+
+ async function copyContent(): Promise<void> {
+ try {
+ await navigator.clipboard.writeText(content)
+ setCopyState("copied")
+ } catch {
+ setCopyState("failed")
+ }
+ if (copyTimer.current) clearTimeout(copyTimer.current)
+ copyTimer.current = setTimeout(() => setCopyState("idle"), 2_000)
+ }
+
+ const fallbackLines = sourceLines(content)
+ const lines = highlight.kind === "highlighted" ? highlight.lines : fallbackLines
+ const useCompactPlainText = highlight.kind === "plain" && fallbackLines.length > MAX_CODE_HIGHLIGHT_LINES
+ const label = language ? LANGUAGE_LABELS[language] : "Plain text"
+ const status = highlighting ? "Highlighting…" : highlight.reason
+
+ return (
+ <section
+ data-testid={tid.codePreview}
+ className="flex min-h-0 flex-1 flex-col overflow-hidden"
+ >
+ <div className="flex shrink-0 items-center gap-2 px-2 py-1">
+ <span data-testid={tid.codePreviewLanguage} className="min-w-0 flex-1 truncate text-xs font-medium text-muted-foreground">
+ {label}
+ </span>
+ {status && (
+ <span data-testid={tid.codePreviewStatus} role="status" className="truncate text-xs text-muted-foreground">
+ {status}
+ </span>
+ )}
+ <Button
+ data-testid={tid.codePreviewWrap}
+ type="button"
+ variant={wrap ? "secondary" : "ghost"}
+ size="sm"
+ className="h-11 sm:h-7"
+ aria-pressed={wrap}
+ onClick={() => setWrap((value) => !value)}
+ >
+ <WrapText className="size-3.5" />
+ Wrap
+ </Button>
+ <Button
+ data-testid={tid.codePreviewCopy}
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="h-11 sm:h-7"
+ onClick={() => void copyContent()}
+ aria-label={copyState === "failed" ? "Copy failed" : copyState === "copied" ? "Copied" : "Copy source"}
+ >
+ {copyState === "copied" ? <Check className="size-3.5" /> : <Copy className="size-3.5" />}
+ {copyState === "copied" ? "Copied" : copyState === "failed" ? "Retry copy" : "Copy"}
+ </Button>
+ </div>
+ <div className="min-h-0 flex-1 overflow-auto thin-scrollbar font-mono text-[13px] leading-6">
+ {useCompactPlainText ? (
+ <div className={cn("grid min-h-full grid-cols-[auto_minmax(0,1fr)] py-3", !wrap && "w-max min-w-full")}>
+ <pre
+ aria-hidden="true"
+ className="select-none border-r border-border/60 px-3 text-right text-muted-foreground/60"
+ >
+ {lineNumbers(fallbackLines.length)}
+ </pre>
+ <pre
+ className={cn(
+ "min-w-0 px-4 text-foreground",
+ wrap ? "whitespace-pre-wrap wrap-break-word" : "whitespace-pre",
+ )}
+ >
+ {content}
+ </pre>
+ </div>
+ ) : (
+ <div className={cn("min-w-max py-3", wrap && "min-w-0")}>
+ {lines.map((line, index) => (
+ <div key={index} className="grid min-h-6 grid-cols-[3.5rem_minmax(0,1fr)]">
+ <span aria-hidden="true" className="select-none border-r border-border/60 pr-3 text-right text-muted-foreground/60">
+ {index + 1}
+ </span>
+ <code className={cn("block min-w-0 px-4", wrap ? "whitespace-pre-wrap wrap-break-word" : "whitespace-pre")}>
+ {highlight.kind === "highlighted"
+ ? (line as CodeToken[]).map((token, tokenIndex) => (
+ <span
+ key={tokenIndex}
+ style={tokenStyle(token)}
+ className="text-(--code-token-light) dark:text-(--code-token-dark)"
+ >
+ {token.content}
+ </span>
+ ))
+ : (line as string) || "\u200b"}
+ </code>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ </section>
+ )
+}
diff --git a/src/web/src/lib/community/attachment-presentation.test.ts b/src/web/src/lib/community/attachment-presentation.test.ts
index 2f4aa127e..e3c426ef6 100644
--- a/src/web/src/lib/community/attachment-presentation.test.ts
+++ b/src/web/src/lib/community/attachment-presentation.test.ts
@@ -2,36 +2,103 @@ import { describe, expect, it } from "vitest"
import {
formatAttachmentSize,
resolveAttachmentPresentation,
+ type AttachmentPresentation,
} from "./attachment-presentation"
+const presentation = (
+ category: AttachmentPresentation["category"],
+ previewKind: AttachmentPresentation["previewKind"],
+ shikiLanguage: AttachmentPresentation["shikiLanguage"] = null,
+): AttachmentPresentation => ({ category, previewKind, shikiLanguage })
+
describe("resolveAttachmentPresentation", () => {
it.each([
- ["report.pdf", "application/pdf", "pdf", null],
- ["sheet.bin", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "spreadsheet", null],
- ["slides.bin", "application/vnd.ms-powerpoint", "presentation", null],
- ["voice.bin", "audio/mpeg", "audio", null],
- ["clip.bin", "video/mp4", "video", null],
- ["data.bin", "application/json; charset=utf-8", "code", "code"],
- ["readme.bin", "text/markdown", "text", "markdown"],
- ["notes.bin", "text/plain", "text", "text"],
- ])("uses MIME for %s", (filename, contentType, category, previewKind) => {
- expect(resolveAttachmentPresentation(filename, contentType)).toEqual({ category, previewKind })
+ ["report.pdf", "application/pdf", presentation("pdf", null)],
+ ["sheet.bin", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", presentation("spreadsheet", null)],
+ ["slides.bin", "application/vnd.ms-powerpoint", presentation("presentation", null)],
+ ["voice.bin", "audio/mpeg", presentation("audio", null)],
+ ["clip.bin", "video/mp4", presentation("video", null)],
+ ["data.bin", "application/json; charset=utf-8", presentation("code", "code", "json")],
+ ["readme.bin", "text/markdown", presentation("text", "markdown")],
+ ["notes.bin", "text/plain", presentation("text", "text")],
+ ["page.bin", "text/html", presentation("code", "code", "html")],
+ ["vector.bin", "image/svg+xml", presentation("code", "code", "xml")],
+ ["component.bin", "text/mdx", presentation("code", "code", "mdx")],
+ ])("uses MIME for %s", (filename, contentType, expected) => {
+ expect(resolveAttachmentPresentation(filename, contentType)).toEqual(expected)
+ })
+
+ it.each([
+ ["README.md", undefined, presentation("text", "markdown")],
+ ["config.json", "application/octet-stream", presentation("code", "code", "json")],
+ [".env.local", "", presentation("code", "code", "dotenv")],
+ ["Dockerfile", "binary/octet-stream", presentation("code", "code", "dockerfile")],
+ ["GNUmakefile", undefined, presentation("code", "code", "makefile")],
+ ["deck.pptx", undefined, presentation("presentation", null)],
+ ["bundle.zip", "binary/octet-stream", presentation("archive", null)],
+ ])("falls back to the filename for generic MIME: %s", (filename, contentType, expected) => {
+ expect(resolveAttachmentPresentation(filename, contentType)).toEqual(expected)
})
it.each([
- ["README.md", undefined, "text", "markdown"],
- ["config.json", "application/octet-stream", "code", "code"],
- [".env.local", "", "code", "code"],
- ["deck.pptx", undefined, "presentation", null],
- ["bundle.zip", "binary/octet-stream", "archive", null],
- ])("falls back to the extension for generic MIME: %s", (filename, contentType, category, previewKind) => {
- expect(resolveAttachmentPresentation(filename, contentType)).toEqual({ category, previewKind })
+ ["js", "javascript"],
+ ["jsx", "jsx"],
+ ["ts", "typescript"],
+ ["tsx", "tsx"],
+ ["css", "css"],
+ ["scss", "scss"],
+ ["sql", "sql"],
+ ["sh", "bash"],
+ ["py", "python"],
+ ["rb", "ruby"],
+ ["go", "go"],
+ ["rs", "rust"],
+ ["java", "java"],
+ ["c", "c"],
+ ["h", "c"],
+ ["cpp", "cpp"],
+ ["yaml", "yaml"],
+ ["yml", "yaml"],
+ ["toml", "toml"],
+ ["ini", "ini"],
+ ["conf", "ini"],
+ ["env", "dotenv"],
+ ["xml", "xml"],
+ ["json", "json"],
+ ["jsonl", "jsonl"],
+ ["cs", "csharp"],
+ ["php", "php"],
+ ["kt", "kotlin"],
+ ["swift", "swift"],
+ ["vue", "vue"],
+ ["svelte", "svelte"],
+ ["graphql", "graphql"],
+ ["gql", "graphql"],
+ ["proto", "proto"],
+ ["tf", "hcl"],
+ ["hcl", "hcl"],
+ ["diff", "diff"],
+ ["patch", "diff"],
+ ["html", "html"],
+ ["htm", "html"],
+ ["svg", "xml"],
+ ["mdx", "mdx"],
+ ["log", "log"],
+ ])("maps .%s to the %s grammar", (extension, language) => {
+ expect(resolveAttachmentPresentation(`source.${extension}`, "application/octet-stream"))
+ .toEqual(presentation("code", "code", language as AttachmentPresentation["shikiLanguage"]))
+ })
+
+ it("keeps plain text readable without a grammar", () => {
+ expect(resolveAttachmentPresentation("notes.txt", "application/octet-stream"))
+ .toEqual(presentation("text", "text"))
})
- it("does not execute active or unknown content", () => {
- expect(resolveAttachmentPresentation("page.html", "text/html")).toEqual({ category: "unknown", previewKind: null })
- expect(resolveAttachmentPresentation("vector.svg", "image/svg+xml")).toEqual({ category: "image", previewKind: null })
- expect(resolveAttachmentPresentation("payload.bin", "application/x-custom")).toEqual({ category: "unknown", previewKind: null })
+ it("does not let a misleading filename override a specific MIME", () => {
+ expect(resolveAttachmentPresentation("payload.html", "application/pdf"))
+ .toEqual(presentation("pdf", null))
+ expect(resolveAttachmentPresentation("payload.ts", "application/x-custom"))
+ .toEqual(presentation("unknown", null))
})
})
diff --git a/src/web/src/lib/community/attachment-presentation.ts b/src/web/src/lib/community/attachment-presentation.ts
index 31cdb0cf6..7f1d37795 100644
--- a/src/web/src/lib/community/attachment-presentation.ts
+++ b/src/web/src/lib/community/attachment-presentation.ts
@@ -15,113 +15,204 @@ export type AttachmentCategory =
type AttachmentPreviewKind = "markdown" | "text" | "code"
+export type ShikiLanguage =
+ | "bash"
+ | "c"
+ | "cpp"
+ | "csharp"
+ | "css"
+ | "diff"
+ | "dockerfile"
+ | "dotenv"
+ | "go"
+ | "graphql"
+ | "hcl"
+ | "html"
+ | "ini"
+ | "java"
+ | "javascript"
+ | "json"
+ | "jsonl"
+ | "jsx"
+ | "kotlin"
+ | "log"
+ | "makefile"
+ | "mdx"
+ | "php"
+ | "proto"
+ | "python"
+ | "ruby"
+ | "rust"
+ | "scss"
+ | "sql"
+ | "svelte"
+ | "swift"
+ | "toml"
+ | "tsx"
+ | "typescript"
+ | "vue"
+ | "xml"
+ | "yaml"
+
export type AttachmentPresentation = {
category: AttachmentCategory
previewKind: AttachmentPreviewKind | null
+ shikiLanguage: ShikiLanguage | null
}
const GENERIC_CONTENT_TYPES = new Set(["", "application/octet-stream", "binary/octet-stream"])
const MIME_PRESENTATIONS: ReadonlyArray<{
matches: (contentType: string) => boolean
- category: AttachmentCategory
- previewKind?: AttachmentPreviewKind
+ presentation: AttachmentPresentation
}> = [
- { matches: (type) => type === "text/markdown" || type === "text/x-markdown", category: "text", previewKind: "markdown" },
- { matches: (type) => type === "application/json" || type.endsWith("+json"), category: "code", previewKind: "code" },
- { matches: (type) => [
- "application/javascript",
- "application/typescript",
- "application/sql",
- "application/toml",
- "application/x-yaml",
- "application/yaml",
- "application/xml",
- "text/css",
- "text/javascript",
- "text/typescript",
- "text/x-python",
- "text/x-shellscript",
- "text/x-sql",
- "text/yaml",
- ].includes(type), category: "code", previewKind: "code" },
- { matches: (type) => type === "application/pdf", category: "pdf" },
- { matches: (type) => type.includes("spreadsheet") || type.includes("excel") || type === "text/csv", category: "spreadsheet" },
- { matches: (type) => type.includes("presentation") || type.includes("powerpoint"), category: "presentation" },
- { matches: (type) => type.includes("wordprocessing") || type === "application/msword" || type === "application/rtf", category: "document" },
- { matches: (type) => type.startsWith("audio/"), category: "audio" },
- { matches: (type) => type.startsWith("video/"), category: "video" },
- { matches: (type) => type.startsWith("image/"), category: "image" },
- { matches: (type) => type === "application/zip" || type === "application/x-7z-compressed" || type === "application/x-rar-compressed" || type === "application/gzip" || type === "application/x-tar", category: "archive" },
- { matches: (type) => type.startsWith("text/") && type !== "text/html", category: "text", previewKind: "text" },
+ { matches: (type) => type === "text/markdown" || type === "text/x-markdown", presentation: { category: "text", previewKind: "markdown", shikiLanguage: null } },
+ { matches: (type) => type === "text/mdx" || type === "application/mdx", presentation: { category: "code", previewKind: "code", shikiLanguage: "mdx" } },
+ { matches: (type) => type === "text/html" || type === "application/xhtml+xml", presentation: { category: "code", previewKind: "code", shikiLanguage: "html" } },
+ { matches: (type) => type === "image/svg+xml", presentation: { category: "code", previewKind: "code", shikiLanguage: "xml" } },
+ { matches: (type) => type === "application/json" || type.endsWith("+json"), presentation: { category: "code", previewKind: "code", shikiLanguage: "json" } },
+ { matches: (type) => type === "application/xml" || type === "text/xml" || type.endsWith("+xml"), presentation: { category: "code", previewKind: "code", shikiLanguage: "xml" } },
+ { matches: (type) => ["application/javascript", "text/javascript"].includes(type), presentation: { category: "code", previewKind: "code", shikiLanguage: "javascript" } },
+ { matches: (type) => ["application/typescript", "text/typescript"].includes(type), presentation: { category: "code", previewKind: "code", shikiLanguage: "typescript" } },
+ { matches: (type) => type === "text/css", presentation: { category: "code", previewKind: "code", shikiLanguage: "css" } },
+ { matches: (type) => type === "text/x-scss", presentation: { category: "code", previewKind: "code", shikiLanguage: "scss" } },
+ { matches: (type) => ["application/sql", "text/x-sql"].includes(type), presentation: { category: "code", previewKind: "code", shikiLanguage: "sql" } },
+ { matches: (type) => ["application/toml", "text/toml"].includes(type), presentation: { category: "code", previewKind: "code", shikiLanguage: "toml" } },
+ { matches: (type) => ["application/x-yaml", "application/yaml", "text/yaml", "text/x-yaml"].includes(type), presentation: { category: "code", previewKind: "code", shikiLanguage: "yaml" } },
+ { matches: (type) => ["application/x-sh", "text/x-shellscript"].includes(type), presentation: { category: "code", previewKind: "code", shikiLanguage: "bash" } },
+ { matches: (type) => type === "text/x-python", presentation: { category: "code", previewKind: "code", shikiLanguage: "python" } },
+ { matches: (type) => type === "text/x-ruby", presentation: { category: "code", previewKind: "code", shikiLanguage: "ruby" } },
+ { matches: (type) => type === "text/x-go", presentation: { category: "code", previewKind: "code", shikiLanguage: "go" } },
+ { matches: (type) => type === "text/x-rust", presentation: { category: "code", previewKind: "code", shikiLanguage: "rust" } },
+ { matches: (type) => type === "text/x-java-source", presentation: { category: "code", previewKind: "code", shikiLanguage: "java" } },
+ { matches: (type) => ["text/x-c", "text/x-csrc"].includes(type), presentation: { category: "code", previewKind: "code", shikiLanguage: "c" } },
+ { matches: (type) => ["text/x-c++", "text/x-c++src"].includes(type), presentation: { category: "code", previewKind: "code", shikiLanguage: "cpp" } },
+ { matches: (type) => ["text/x-csharp", "text/x-cs"].includes(type), presentation: { category: "code", previewKind: "code", shikiLanguage: "csharp" } },
+ { matches: (type) => type === "application/x-httpd-php", presentation: { category: "code", previewKind: "code", shikiLanguage: "php" } },
+ { matches: (type) => type === "text/x-kotlin", presentation: { category: "code", previewKind: "code", shikiLanguage: "kotlin" } },
+ { matches: (type) => type === "text/x-swift", presentation: { category: "code", previewKind: "code", shikiLanguage: "swift" } },
+ { matches: (type) => ["application/graphql", "text/graphql"].includes(type), presentation: { category: "code", previewKind: "code", shikiLanguage: "graphql" } },
+ { matches: (type) => ["application/protobuf", "application/x-protobuf", "text/x-proto"].includes(type), presentation: { category: "code", previewKind: "code", shikiLanguage: "proto" } },
+ { matches: (type) => ["application/x-terraform", "text/x-hcl"].includes(type), presentation: { category: "code", previewKind: "code", shikiLanguage: "hcl" } },
+ { matches: (type) => ["text/x-diff", "text/x-patch"].includes(type), presentation: { category: "code", previewKind: "code", shikiLanguage: "diff" } },
+ { matches: (type) => type === "text/x-log", presentation: { category: "code", previewKind: "code", shikiLanguage: "log" } },
+ { matches: (type) => type === "application/pdf", presentation: { category: "pdf", previewKind: null, shikiLanguage: null } },
+ { matches: (type) => type.includes("spreadsheet") || type.includes("excel") || type === "text/csv" || type === "text/tab-separated-values", presentation: { category: "spreadsheet", previewKind: null, shikiLanguage: null } },
+ { matches: (type) => type.includes("presentation") || type.includes("powerpoint"), presentation: { category: "presentation", previewKind: null, shikiLanguage: null } },
+ { matches: (type) => type.includes("wordprocessing") || type === "application/msword" || type === "application/rtf", presentation: { category: "document", previewKind: null, shikiLanguage: null } },
+ { matches: (type) => type.startsWith("audio/"), presentation: { category: "audio", previewKind: null, shikiLanguage: null } },
+ { matches: (type) => type.startsWith("video/"), presentation: { category: "video", previewKind: null, shikiLanguage: null } },
+ { matches: (type) => type.startsWith("image/"), presentation: { category: "image", previewKind: null, shikiLanguage: null } },
+ { matches: (type) => type === "application/zip" || type === "application/x-7z-compressed" || type === "application/x-rar-compressed" || type === "application/gzip" || type === "application/x-tar", presentation: { category: "archive", previewKind: null, shikiLanguage: null } },
+ { matches: (type) => type.startsWith("text/"), presentation: { category: "text", previewKind: "text", shikiLanguage: null } },
]
+const code = (shikiLanguage: ShikiLanguage): AttachmentPresentation => ({
+ category: "code",
+ previewKind: "code",
+ shikiLanguage,
+})
+
const EXTENSION_PRESENTATIONS: Readonly<Record<string, AttachmentPresentation>> = {
- md: { category: "text", previewKind: "markdown" },
- markdown: { category: "text", previewKind: "markdown" },
- txt: { category: "text", previewKind: "text" },
- log: { category: "text", previewKind: "text" },
- csv: { category: "spreadsheet", previewKind: null },
- json: { category: "code", previewKind: "code" },
- jsonl: { category: "code", previewKind: "code" },
- js: { category: "code", previewKind: "code" },
- jsx: { category: "code", previewKind: "code" },
- ts: { category: "code", previewKind: "code" },
- tsx: { category: "code", previewKind: "code" },
- css: { category: "code", previewKind: "code" },
- scss: { category: "code", previewKind: "code" },
- sql: { category: "code", previewKind: "code" },
- sh: { category: "code", previewKind: "code" },
- bash: { category: "code", previewKind: "code" },
- py: { category: "code", previewKind: "code" },
- rb: { category: "code", previewKind: "code" },
- go: { category: "code", previewKind: "code" },
- rs: { category: "code", previewKind: "code" },
- java: { category: "code", previewKind: "code" },
- c: { category: "code", previewKind: "code" },
- h: { category: "code", previewKind: "code" },
- cpp: { category: "code", previewKind: "code" },
- yaml: { category: "code", previewKind: "code" },
- yml: { category: "code", previewKind: "code" },
- toml: { category: "code", previewKind: "code" },
- ini: { category: "code", previewKind: "code" },
- conf: { category: "code", previewKind: "code" },
- env: { category: "code", previewKind: "code" },
- xml: { category: "code", previewKind: "code" },
- pdf: { category: "pdf", previewKind: null },
- doc: { category: "document", previewKind: null },
- docx: { category: "document", previewKind: null },
- rtf: { category: "document", previewKind: null },
- xls: { category: "spreadsheet", previewKind: null },
- xlsx: { category: "spreadsheet", previewKind: null },
- ppt: { category: "presentation", previewKind: null },
- pptx: { category: "presentation", previewKind: null },
- mp3: { category: "audio", previewKind: null },
- wav: { category: "audio", previewKind: null },
- m4a: { category: "audio", previewKind: null },
- mp4: { category: "video", previewKind: null },
- mov: { category: "video", previewKind: null },
- webm: { category: "video", previewKind: null },
- zip: { category: "archive", previewKind: null },
- gz: { category: "archive", previewKind: null },
- tar: { category: "archive", previewKind: null },
- rar: { category: "archive", previewKind: null },
- "7z": { category: "archive", previewKind: null },
- png: { category: "image", previewKind: null },
- jpg: { category: "image", previewKind: null },
- jpeg: { category: "image", previewKind: null },
- gif: { category: "image", previewKind: null },
- webp: { category: "image", previewKind: null },
- svg: { category: "image", previewKind: null },
- html: { category: "code", previewKind: null },
- htm: { category: "code", previewKind: null },
+ md: { category: "text", previewKind: "markdown", shikiLanguage: null },
+ markdown: { category: "text", previewKind: "markdown", shikiLanguage: null },
+ txt: { category: "text", previewKind: "text", shikiLanguage: null },
+ log: code("log"),
+ csv: { category: "spreadsheet", previewKind: null, shikiLanguage: null },
+ tsv: { category: "spreadsheet", previewKind: null, shikiLanguage: null },
+ json: code("json"),
+ jsonl: code("jsonl"),
+ js: code("javascript"),
+ mjs: code("javascript"),
+ cjs: code("javascript"),
+ jsx: code("jsx"),
+ ts: code("typescript"),
+ mts: code("typescript"),
+ cts: code("typescript"),
+ tsx: code("tsx"),
+ css: code("css"),
+ scss: code("scss"),
+ sql: code("sql"),
+ sh: code("bash"),
+ bash: code("bash"),
+ zsh: code("bash"),
+ py: code("python"),
+ rb: code("ruby"),
+ go: code("go"),
+ rs: code("rust"),
+ java: code("java"),
+ c: code("c"),
+ h: code("c"),
+ cc: code("cpp"),
+ cpp: code("cpp"),
+ cxx: code("cpp"),
+ hpp: code("cpp"),
+ cs: code("csharp"),
+ php: code("php"),
+ kt: code("kotlin"),
+ kts: code("kotlin"),
+ swift: code("swift"),
+ vue: code("vue"),
+ svelte: code("svelte"),
+ graphql: code("graphql"),
+ gql: code("graphql"),
+ proto: code("proto"),
+ tf: code("hcl"),
+ tfvars: code("hcl"),
+ hcl: code("hcl"),
+ diff: code("diff"),
+ patch: code("diff"),
+ yaml: code("yaml"),
+ yml: code("yaml"),
+ toml: code("toml"),
+ ini: code("ini"),
+ conf: code("ini"),
+ config: code("ini"),
+ properties: code("ini"),
+ env: code("dotenv"),
+ xml: code("xml"),
+ html: code("html"),
+ htm: code("html"),
+ svg: code("xml"),
+ mdx: code("mdx"),
+ pdf: { category: "pdf", previewKind: null, shikiLanguage: null },
+ doc: { category: "document", previewKind: null, shikiLanguage: null },
+ docx: { category: "document", previewKind: null, shikiLanguage: null },
+ rtf: { category: "document", previewKind: null, shikiLanguage: null },
+ xls: { category: "spreadsheet", previewKind: null, shikiLanguage: null },
+ xlsx: { category: "spreadsheet", previewKind: null, shikiLanguage: null },
+ ppt: { category: "presentation", previewKind: null, shikiLanguage: null },
+ pptx: { category: "presentation", previewKind: null, shikiLanguage: null },
+ mp3: { category: "audio", previewKind: null, shikiLanguage: null },
+ wav: { category: "audio", previewKind: null, shikiLanguage: null },
+ m4a: { category: "audio", previewKind: null, shikiLanguage: null },
+ ogg: { category: "audio", previewKind: null, shikiLanguage: null },
+ mp4: { category: "video", previewKind: null, shikiLanguage: null },
+ mov: { category: "video", previewKind: null, shikiLanguage: null },
+ webm: { category: "video", previewKind: null, shikiLanguage: null },
+ zip: { category: "archive", previewKind: null, shikiLanguage: null },
+ gz: { category: "archive", previewKind: null, shikiLanguage: null },
+ tar: { category: "archive", previewKind: null, shikiLanguage: null },
+ rar: { category: "archive", previewKind: null, shikiLanguage: null },
+ "7z": { category: "archive", previewKind: null, shikiLanguage: null },
+ png: { category: "image", previewKind: null, shikiLanguage: null },
+ jpg: { category: "image", previewKind: null, shikiLanguage: null },
+ jpeg: { category: "image", previewKind: null, shikiLanguage: null },
+ gif: { category: "image", previewKind: null, shikiLanguage: null },
+ webp: { category: "image", previewKind: null, shikiLanguage: null },
}
-function filenameExtension(filename: string): string {
+const BASENAME_PRESENTATIONS: Readonly<Record<string, AttachmentPresentation>> = {
+ dockerfile: code("dockerfile"),
+ makefile: code("makefile"),
+ gnumakefile: code("makefile"),
+}
+
+function filenameParts(filename: string): { basename: string; extension: string } {
const basename = filename.toLowerCase().split(/[\\/]/).pop() ?? ""
- if (basename.startsWith(".env")) return "env"
+ if (basename.startsWith(".env")) return { basename, extension: "env" }
const dot = basename.lastIndexOf(".")
- return dot > -1 ? basename.slice(dot + 1) : ""
+ return { basename, extension: dot > -1 ? basename.slice(dot + 1) : "" }
}
export function resolveAttachmentPresentation(
@@ -130,20 +221,15 @@ export function resolveAttachmentPresentation(
): AttachmentPresentation {
const normalizedType = contentType?.split(";", 1)[0]?.trim().toLowerCase() ?? ""
if (!GENERIC_CONTENT_TYPES.has(normalizedType)) {
- for (const presentation of MIME_PRESENTATIONS) {
- if (presentation.matches(normalizedType)) {
- return {
- category: presentation.category,
- previewKind: presentation.previewKind ?? null,
- }
- }
+ for (const { matches, presentation } of MIME_PRESENTATIONS) {
+ if (matches(normalizedType)) return presentation
}
- return { category: "unknown", previewKind: null }
- }
- return EXTENSION_PRESENTATIONS[filenameExtension(filename)] ?? {
- category: "unknown",
- previewKind: null,
+ return { category: "unknown", previewKind: null, shikiLanguage: null }
}
+ const { basename, extension } = filenameParts(filename)
+ return BASENAME_PRESENTATIONS[basename]
+ ?? EXTENSION_PRESENTATIONS[extension]
+ ?? { category: "unknown", previewKind: null, shikiLanguage: null }
}
export function formatAttachmentSize(bytes?: number): string {
diff --git a/src/web/src/lib/community/code-highlight.test.ts b/src/web/src/lib/community/code-highlight.test.ts
new file mode 100644
index 000000000..9df25234a
--- /dev/null
+++ b/src/web/src/lib/community/code-highlight.test.ts
@@ -0,0 +1,141 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+
+const shikiMocks = vi.hoisted(() => {
+ const highlighter = {
+ codeToTokensWithThemes: vi.fn(),
+ getLoadedLanguages: vi.fn((): string[] => []),
+ loadLanguage: vi.fn(async () => undefined),
+ }
+ return {
+ createHighlighterCore: vi.fn(async () => highlighter),
+ createOnigurumaEngine: vi.fn(() => ({ engine: true })),
+ highlighter,
+ }
+})
+
+vi.mock("shiki/core", () => ({
+ createHighlighterCore: shikiMocks.createHighlighterCore,
+}))
+
+vi.mock("shiki/engine/oniguruma", () => ({
+ createOnigurumaEngine: shikiMocks.createOnigurumaEngine,
+}))
+
+vi.mock("shiki/wasm", () => ({ default: { wasm: true } }))
+
+vi.mock("shiki/langs", () => ({
+ get bundledLanguages() {
+ throw new Error("Broad language registry must not load")
+ },
+}))
+
+vi.mock("shiki/themes", () => ({
+ get bundledThemes() {
+ throw new Error("Broad theme registry must not load")
+ },
+}))
+
+vi.mock("shiki/langs/json.mjs", () => ({ default: [{ id: "json" }] }))
+vi.mock("shiki/langs/typescript.mjs", () => ({ default: [{ id: "typescript" }] }))
+vi.mock("shiki/themes/github-light.mjs", () => ({ default: { name: "github-light" } }))
+vi.mock("shiki/themes/github-dark.mjs", () => ({ default: { name: "github-dark" } }))
+
+beforeEach(() => {
+ vi.resetModules()
+ shikiMocks.createHighlighterCore.mockClear()
+ shikiMocks.createOnigurumaEngine.mockClear()
+ shikiMocks.highlighter.codeToTokensWithThemes.mockReset()
+ shikiMocks.highlighter.getLoadedLanguages.mockReset().mockReturnValue([])
+ shikiMocks.highlighter.loadLanguage.mockReset().mockResolvedValue(undefined)
+})
+
+describe("highlightCode", () => {
+ it("does not initialize Shiki for plain text", async () => {
+ const { highlightCode } = await import("./code-highlight")
+ await expect(highlightCode("hello", null)).resolves.toEqual({
+ kind: "plain",
+ lines: null,
+ reason: null,
+ })
+ expect(shikiMocks.createHighlighterCore).not.toHaveBeenCalled()
+ })
+
+ it("lazily reuses one runtime and language load with light and dark tokens", async () => {
+ shikiMocks.highlighter.codeToTokensWithThemes.mockReturnValue([[
+ {
+ content: "const",
+ variants: {
+ light: { color: "#111111", fontStyle: 1 },
+ dark: { color: "#eeeeee", fontStyle: 1 },
+ },
+ },
+ ]])
+ const { highlightCode } = await import("./code-highlight")
+ const [first, second] = await Promise.all([
+ highlightCode("const", "typescript"),
+ highlightCode("let", "typescript"),
+ ])
+
+ expect(shikiMocks.createHighlighterCore).toHaveBeenCalledTimes(1)
+ expect(shikiMocks.createHighlighterCore).toHaveBeenCalledWith(expect.objectContaining({
+ themes: [{ name: "github-light" }, { name: "github-dark" }],
+ }))
+ expect(shikiMocks.highlighter.loadLanguage).toHaveBeenCalledTimes(1)
+ expect(shikiMocks.highlighter.loadLanguage).toHaveBeenCalledWith({ id: "typescript" })
+ expect(shikiMocks.highlighter.codeToTokensWithThemes).toHaveBeenCalledWith("const", {
+ lang: "typescript",
+ themes: { light: "github-light", dark: "github-dark" },
+ })
+ expect(first).toEqual({
+ kind: "highlighted",
+ lines: [[{
+ content: "const",
+ light: { color: "#111111", fontStyle: 1 },
+ dark: { color: "#eeeeee", fontStyle: 1 },
+ }]],
+ reason: null,
+ })
+ expect(second.kind).toBe("highlighted")
+ })
+
+ it("skips Shiki above the byte or line token budget", async () => {
+ const {
+ highlightCode,
+ MAX_CODE_HIGHLIGHT_BYTES,
+ MAX_CODE_HIGHLIGHT_LINES,
+ } = await import("./code-highlight")
+
+ await expect(highlightCode("é".repeat(MAX_CODE_HIGHLIGHT_BYTES / 2 + 1), "json"))
+ .resolves.toEqual({
+ kind: "plain",
+ lines: null,
+ reason: "Syntax highlighting disabled for large files",
+ })
+ await expect(highlightCode("line\n".repeat(MAX_CODE_HIGHLIGHT_LINES), "json"))
+ .resolves.toEqual({
+ kind: "plain",
+ lines: null,
+ reason: "Syntax highlighting disabled for long files",
+ })
+ expect(shikiMocks.createHighlighterCore).not.toHaveBeenCalled()
+ })
+
+ it("keeps readable plain text when a grammar or tokenizer fails", async () => {
+ const { highlightCode } = await import("./code-highlight")
+
+ await expect(highlightCode("source", "missing" as "json")).resolves.toEqual({
+ kind: "plain",
+ lines: null,
+ reason: "Syntax highlighting unavailable",
+ })
+
+ shikiMocks.highlighter.codeToTokensWithThemes.mockImplementation(() => {
+ throw new Error("tokenizer failed")
+ })
+ await expect(highlightCode("{}", "json")).resolves.toEqual({
+ kind: "plain",
+ lines: null,
+ reason: "Syntax highlighting unavailable",
+ })
+ })
+})
diff --git a/src/web/src/lib/community/code-highlight.ts b/src/web/src/lib/community/code-highlight.ts
new file mode 100644
index 000000000..6d2efc9bc
--- /dev/null
+++ b/src/web/src/lib/community/code-highlight.ts
@@ -0,0 +1,162 @@
+import type { ShikiLanguage } from "./attachment-presentation"
+import type { LanguageRegistration } from "shiki/core"
+
+export const MAX_CODE_HIGHLIGHT_BYTES = 256 * 1024
+export const MAX_CODE_HIGHLIGHT_LINES = 2_000
+
+type CodeTokenStyle = {
+ color?: string
+ fontStyle?: number
+}
+
+export type CodeToken = {
+ content: string
+ light: CodeTokenStyle
+ dark: CodeTokenStyle
+}
+
+export type CodeHighlightResult =
+ | { kind: "highlighted"; lines: CodeToken[][]; reason: null }
+ | { kind: "plain"; lines: null; reason: string | null }
+
+type Runtime = {
+ highlighter: {
+ codeToTokensWithThemes: (
+ content: string,
+ options: { lang: string; themes: { light: string; dark: string } },
+ ) => Array<Array<{
+ content: string
+ variants: Record<string, CodeTokenStyle>
+ }>>
+ getLoadedLanguages: () => string[]
+ loadLanguage: (...languages: unknown[]) => Promise<void>
+ }
+}
+
+let runtimePromise: Promise<Runtime> | null = null
+const languageLoads = new Map<ShikiLanguage, Promise<void>>()
+
+const LANGUAGE_LOADERS = {
+ bash: () => import("shiki/langs/bash.mjs").then((module) => module.default),
+ c: () => import("shiki/langs/c.mjs").then((module) => module.default),
+ cpp: () => import("shiki/langs/cpp.mjs").then((module) => module.default),
+ csharp: () => import("shiki/langs/csharp.mjs").then((module) => module.default),
+ css: () => import("shiki/langs/css.mjs").then((module) => module.default),
+ diff: () => import("shiki/langs/diff.mjs").then((module) => module.default),
+ dockerfile: () => import("shiki/langs/dockerfile.mjs").then((module) => module.default),
+ dotenv: () => import("shiki/langs/dotenv.mjs").then((module) => module.default),
+ go: () => import("shiki/langs/go.mjs").then((module) => module.default),
+ graphql: () => import("shiki/langs/graphql.mjs").then((module) => module.default),
+ hcl: () => import("shiki/langs/hcl.mjs").then((module) => module.default),
+ html: () => import("shiki/langs/html.mjs").then((module) => module.default),
+ ini: () => import("shiki/langs/ini.mjs").then((module) => module.default),
+ java: () => import("shiki/langs/java.mjs").then((module) => module.default),
+ javascript: () => import("shiki/langs/javascript.mjs").then((module) => module.default),
+ json: () => import("shiki/langs/json.mjs").then((module) => module.default),
+ jsonl: () => import("shiki/langs/jsonl.mjs").then((module) => module.default),
+ jsx: () => import("shiki/langs/jsx.mjs").then((module) => module.default),
+ kotlin: () => import("shiki/langs/kotlin.mjs").then((module) => module.default),
+ log: () => import("shiki/langs/log.mjs").then((module) => module.default),
+ makefile: () => import("shiki/langs/makefile.mjs").then((module) => module.default),
+ mdx: () => import("shiki/langs/mdx.mjs").then((module) => module.default),
+ php: () => import("shiki/langs/php.mjs").then((module) => module.default),
+ proto: () => import("shiki/langs/proto.mjs").then((module) => module.default),
+ python: () => import("shiki/langs/python.mjs").then((module) => module.default),
+ ruby: () => import("shiki/langs/ruby.mjs").then((module) => module.default),
+ rust: () => import("shiki/langs/rust.mjs").then((module) => module.default),
+ scss: () => import("shiki/langs/scss.mjs").then((module) => module.default),
+ sql: () => import("shiki/langs/sql.mjs").then((module) => module.default),
+ svelte: () => import("shiki/langs/svelte.mjs").then((module) => module.default),
+ swift: () => import("shiki/langs/swift.mjs").then((module) => module.default),
+ toml: () => import("shiki/langs/toml.mjs").then((module) => module.default),
+ tsx: () => import("shiki/langs/tsx.mjs").then((module) => module.default),
+ typescript: () => import("shiki/langs/typescript.mjs").then((module) => module.default),
+ vue: () => import("shiki/langs/vue.mjs").then((module) => module.default),
+ xml: () => import("shiki/langs/xml.mjs").then((module) => module.default),
+ yaml: () => import("shiki/langs/yaml.mjs").then((module) => module.default),
+} satisfies Record<ShikiLanguage, () => Promise<LanguageRegistration[]>>
+
+function lineCount(content: string): number {
+ if (content.length === 0) return 1
+ let count = 1
+ for (const character of content) {
+ if (character === "\n") count += 1
+ }
+ return count
+}
+
+function codeHighlightBudgetReason(content: string): string | null {
+ if (new TextEncoder().encode(content).byteLength > MAX_CODE_HIGHLIGHT_BYTES) {
+ return "Syntax highlighting disabled for large files"
+ }
+ if (lineCount(content) > MAX_CODE_HIGHLIGHT_LINES) {
+ return "Syntax highlighting disabled for long files"
+ }
+ return null
+}
+
+async function createRuntime(): Promise<Runtime> {
+ const [core, engine, wasm, lightTheme, darkTheme] = await Promise.all([
+ import("shiki/core"),
+ import("shiki/engine/oniguruma"),
+ import("shiki/wasm"),
+ import("shiki/themes/github-light.mjs").then((module) => module.default),
+ import("shiki/themes/github-dark.mjs").then((module) => module.default),
+ ])
+ const highlighter = await core.createHighlighterCore({
+ engine: engine.createOnigurumaEngine(wasm.default),
+ themes: [lightTheme, darkTheme],
+ langs: [],
+ warnings: false,
+ })
+ return { highlighter } as Runtime
+}
+
+async function getRuntime(): Promise<Runtime> {
+ runtimePromise ??= createRuntime()
+ return runtimePromise
+}
+
+async function ensureLanguage(runtime: Runtime, language: ShikiLanguage): Promise<void> {
+ if (runtime.highlighter.getLoadedLanguages().includes(language)) return
+ let pending = languageLoads.get(language)
+ if (!pending) {
+ pending = LANGUAGE_LOADERS[language]()
+ .then((registrations) => runtime.highlighter.loadLanguage(...registrations))
+ languageLoads.set(language, pending)
+ }
+ try {
+ await pending
+ } catch (error) {
+ languageLoads.delete(language)
+ throw error
+ }
+}
+
+export async function highlightCode(
+ content: string,
+ language: ShikiLanguage | null,
+): Promise<CodeHighlightResult> {
+ if (!language) return { kind: "plain", lines: null, reason: null }
+ const budgetReason = codeHighlightBudgetReason(content)
+ if (budgetReason) return { kind: "plain", lines: null, reason: budgetReason }
+ try {
+ const runtime = await getRuntime()
+ await ensureLanguage(runtime, language)
+ const lines = runtime.highlighter.codeToTokensWithThemes(content, {
+ lang: language,
+ themes: { light: "github-light", dark: "github-dark" },
+ }).map((line) => line.map((token) => ({
+ content: token.content,
+ light: token.variants.light ?? {},
+ dark: token.variants.dark ?? {},
+ })))
+ return { kind: "highlighted", lines, reason: null }
+ } catch {
+ return {
+ kind: "plain",
+ lines: null,
+ reason: "Syntax highlighting unavailable",
+ }
+ }
+}
diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.ts
index 0a5e175f9..eab1bf3b5 100644
--- a/src/web/src/lib/community/testids.ts
+++ b/src/web/src/lib/community/testids.ts
@@ -41,6 +41,11 @@ export const tid = {
attachmentPreviewSheet: "community-attachment-preview-sheet",
attachmentPreviewDownload: "community-attachment-preview-download",
attachmentPreviewContent: "community-attachment-preview-content",
+ codePreview: "community-code-preview",
+ codePreviewLanguage: "community-code-preview-language",
+ codePreviewCopy: "community-code-preview-copy",
+ codePreviewWrap: "community-code-preview-wrap",
+ codePreviewStatus: "community-code-preview-status",
channelRow: (id: string) => `community-channel-row-${id}`,
serverIcon: (id: string) => `community-server-icon-${id}`,
dmRow: (id: string) => `community-dm-row-${id}`,