mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-20 18:57:17 +03:00
fix(app): show Markdown frontmatter as a properties list in file preview (#60333)
Co-authored-by: exe.dev user <exedev@opencode-dev.exe.xyz>
This commit is contained in:
@@ -770,6 +770,29 @@ test("artifact actions copy and download content, switch source, and follow the
|
||||
const source = '<svg xmlns="http://www.w3.org/2000/svg" width="120" height="80"><rect width="120" height="80"/></svg>'
|
||||
const table = 'name,role\n"Jensen, Oliver",Researcher\nIsabella,Support'
|
||||
|
||||
const notes = [
|
||||
"---",
|
||||
"description: Release checklist",
|
||||
"mode: primary",
|
||||
"model: opencode/test",
|
||||
"temperature: 0.2",
|
||||
"steps: 12",
|
||||
"color: accent",
|
||||
"hidden: false",
|
||||
'title: "Release"',
|
||||
"tools:",
|
||||
" write: false",
|
||||
"---",
|
||||
"",
|
||||
"# Notes",
|
||||
"",
|
||||
"A document with a visible top edge.",
|
||||
"",
|
||||
"---",
|
||||
"",
|
||||
"Trailing section.",
|
||||
].join("\n")
|
||||
|
||||
const workspace = await openSession(page, {
|
||||
name: "ArtifactActions",
|
||||
fileList: () => [],
|
||||
@@ -778,7 +801,7 @@ test("artifact actions copy and download content, switch source, and follow the
|
||||
|
||||
if (path === "data.csv") return { content: table }
|
||||
|
||||
if (path === "notes.md") return { content: "# Notes\n\nA document with a visible top edge." }
|
||||
if (path === "notes.md") return { content: notes }
|
||||
|
||||
return { type: "binary", content: "AAEC", encoding: "base64" }
|
||||
},
|
||||
@@ -790,7 +813,10 @@ test("artifact actions copy and download content, switch source, and follow the
|
||||
agent: "build",
|
||||
model: { id: "test", providerID: "opencode" },
|
||||
content: [
|
||||
{ type: "text", text: "[Vector](vector.svg) [Table](data.csv) [Notes](notes.md) [Binary](sample.bin)" },
|
||||
{
|
||||
type: "text",
|
||||
text: "---\ndescription: Chat heading\n---\n\n[Vector](vector.svg) [Table](data.csv) [Notes](notes.md) [Binary](sample.bin)",
|
||||
},
|
||||
],
|
||||
time: { created: 1, completed: 2 },
|
||||
},
|
||||
@@ -866,9 +892,38 @@ test("artifact actions copy and download content, switch source, and follow the
|
||||
expect(download.suggestedFilename()).toBe("data.csv")
|
||||
expect(await readFile((await download.path())!, "utf8")).toBe(table)
|
||||
|
||||
await expect(page.getByRole("heading", { name: "description: Chat heading", exact: true })).toBeVisible()
|
||||
await page.getByRole("link", { name: "Notes", exact: true }).click()
|
||||
await expect(panel.getByRole("heading", { name: "Notes", exact: true })).toBeVisible()
|
||||
const paper = panel.locator('[data-slot="artifact-markdown-page"]')
|
||||
await expect(paper.getByRole("heading")).toHaveText(["Notes"])
|
||||
await expect(paper.locator("code.language-yaml")).toHaveCount(0)
|
||||
await expect(paper.locator("hr")).toHaveCount(1)
|
||||
const terms = paper.getByRole("term")
|
||||
await expect(terms).toHaveText(["description", "mode", "model", "temperature", "steps", "color"])
|
||||
await paper.getByRole("button", { name: "Show all 9 properties", exact: true }).click()
|
||||
await expect(terms).toHaveText([
|
||||
"description",
|
||||
"mode",
|
||||
"model",
|
||||
"temperature",
|
||||
"steps",
|
||||
"color",
|
||||
"hidden",
|
||||
"title",
|
||||
"tools",
|
||||
])
|
||||
await expect(paper.getByRole("definition")).toHaveText([
|
||||
"Release checklist",
|
||||
"primary",
|
||||
"opencode/test",
|
||||
"0.2",
|
||||
"12",
|
||||
"accent",
|
||||
"false",
|
||||
"Release",
|
||||
"write: false",
|
||||
])
|
||||
await expect(paper).toHaveCSS("border-radius", "8px")
|
||||
await expect(paper).toHaveAttribute("data-component", "document-surface")
|
||||
expect(await paper.evaluate((element) => getComputedStyle(element, "::after").borderTopStyle)).toBe("solid")
|
||||
@@ -876,6 +931,16 @@ test("artifact actions copy and download content, switch source, and follow the
|
||||
const bar = (await toolbar.boundingBox())!
|
||||
expect(surface.y - bar.y - bar.height).toBe(1)
|
||||
await expect(panel.getByRole("group", { name: "Preview controls", exact: true })).toHaveCount(0)
|
||||
await copy.click()
|
||||
// Chromium writes CRLF to the Windows clipboard.
|
||||
await expect
|
||||
.poll(() => page.evaluate(() => navigator.clipboard.readText()).then((text) => text.replace(/\r\n/g, "\n")))
|
||||
.toBe(notes)
|
||||
await page.getByRole("button", { name: "Dismiss", exact: true }).click()
|
||||
await sourceAction.click()
|
||||
await expect(paper).toHaveCount(0)
|
||||
await expect(panel.locator('diffs-container [data-line="1"]')).toHaveText("---")
|
||||
await expect(panel.locator('diffs-container [data-line="2"]')).toContainText("description: Release checklist")
|
||||
|
||||
await page.getByRole("link", { name: "Binary", exact: true }).click()
|
||||
await expect(panel.getByText(/Binary file/)).toBeVisible()
|
||||
|
||||
@@ -244,6 +244,58 @@ img[data-slot="artifact-media"] {
|
||||
margin-inline: auto;
|
||||
}
|
||||
|
||||
[data-slot="artifact-properties"] {
|
||||
margin-block-end: 28px;
|
||||
padding-block-end: 20px;
|
||||
border-block-end: 1px solid var(--v2-border-border-muted);
|
||||
font-size: 13px;
|
||||
line-height: 20px;
|
||||
|
||||
dl {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, max-content) minmax(0, 1fr);
|
||||
gap: 6px 24px;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
dt {
|
||||
overflow-wrap: anywhere;
|
||||
color: var(--v2-text-text-muted);
|
||||
}
|
||||
|
||||
dd {
|
||||
margin: 0;
|
||||
overflow-wrap: anywhere;
|
||||
white-space: pre-wrap;
|
||||
color: var(--v2-text-text-base);
|
||||
}
|
||||
|
||||
dd[data-code] {
|
||||
font-family: var(--font-family-mono);
|
||||
font-size: 12px;
|
||||
}
|
||||
}
|
||||
|
||||
[data-slot="artifact-properties-more"] {
|
||||
margin-block-start: 10px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: var(--v2-text-text-muted);
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
|
||||
&:hover {
|
||||
color: var(--v2-text-text-base);
|
||||
}
|
||||
|
||||
&:focus-visible {
|
||||
border-radius: 4px;
|
||||
outline: 2px solid var(--v2-border-border-focus);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
[data-slot="artifact-diagram"] {
|
||||
min-width: 0;
|
||||
padding: 24px 32px;
|
||||
|
||||
@@ -26,7 +26,15 @@ import { MarkdownProvider, useMarkdown } from "@opencode/session-ui/context/mark
|
||||
import { artifactKind, type ArtifactKind } from "@opencode/util/artifact"
|
||||
import { getDirectory, getFilename } from "@opencode/util/path"
|
||||
import { createKeyed, usePlugin, type FileContent, type MountedSession, type SessionScreen } from "@opencode/plugin/gui"
|
||||
import { blobUrlFromContent, bytesFromContent, contentBytes, parseDelimited, resolveArtifactPath } from "./artifact"
|
||||
import {
|
||||
blobUrlFromContent,
|
||||
bytesFromContent,
|
||||
contentBytes,
|
||||
parseDelimited,
|
||||
resolveArtifactPath,
|
||||
splitFrontmatter,
|
||||
type FrontmatterProperty,
|
||||
} from "./artifact"
|
||||
import { FileViewer } from "@opencode/plugin/gui/file"
|
||||
import { ArtifactToolbar } from "./artifact-toolbar"
|
||||
|
||||
@@ -647,6 +655,7 @@ function ArtifactMarkdown(props: { session: MountedSession; path: string; text:
|
||||
const dir = createMemo(() => (props.path.includes("/") || props.path.includes("\\") ? getDirectory(props.path) : ""))
|
||||
// Absolute references bypass the file's directory; relative ones resolve against it.
|
||||
const resolve = (href: string) => (/^([a-z]:)?\//i.test(href) ? href : (resolveArtifactPath(dir(), href) ?? href))
|
||||
const split = createMemo(() => splitFrontmatter(props.text))
|
||||
|
||||
return (
|
||||
<MarkdownProvider
|
||||
@@ -656,13 +665,41 @@ function ArtifactMarkdown(props: { session: MountedSession; path: string; text:
|
||||
>
|
||||
<div data-slot="artifact-markdown-page" data-component="document-surface">
|
||||
<div data-slot="artifact-markdown-content">
|
||||
<Markdown text={props.text} cacheKey={props.cacheKey} />
|
||||
<Show when={split().properties}>{(properties) => <ArtifactProperties properties={properties()} />}</Show>
|
||||
<Markdown text={split().body} cacheKey={props.cacheKey} />
|
||||
</div>
|
||||
</div>
|
||||
</MarkdownProvider>
|
||||
)
|
||||
}
|
||||
|
||||
function ArtifactProperties(props: { properties: FrontmatterProperty[] }) {
|
||||
const ctx = usePlugin()
|
||||
const [expanded, setExpanded] = createSignal(false)
|
||||
// Long frontmatter shows its first entries until the reader asks for the rest.
|
||||
const shown = () => (expanded() || props.properties.length <= 8 ? props.properties : props.properties.slice(0, 6))
|
||||
|
||||
return (
|
||||
<div data-slot="artifact-properties">
|
||||
<dl aria-label={ctx.t("view.properties")}>
|
||||
<For each={shown()}>
|
||||
{(property) => (
|
||||
<>
|
||||
<dt>{property.key}</dt>
|
||||
<dd data-code={property.code ? "" : undefined}>{property.value}</dd>
|
||||
</>
|
||||
)}
|
||||
</For>
|
||||
</dl>
|
||||
<Show when={shown().length < props.properties.length}>
|
||||
<button type="button" data-slot="artifact-properties-more" onClick={() => setExpanded(true)}>
|
||||
{ctx.t("view.properties.showAll", { count: props.properties.length })}
|
||||
</button>
|
||||
</Show>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Mermaid sources render through the same fenced-block pipeline the timeline uses. */
|
||||
function ArtifactMermaid(props: { text: string; cacheKey?: string }) {
|
||||
const [view, setView] = createStore({ zoom: 1, width: 0 })
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { bytesFromContent, contentBytes, parseDelimited, resolveArtifactPath } from "./artifact"
|
||||
import { bytesFromContent, contentBytes, parseDelimited, resolveArtifactPath, splitFrontmatter } from "./artifact"
|
||||
|
||||
describe("binary content helpers", () => {
|
||||
test("reads size and independent byte copies from raw bytes", () => {
|
||||
@@ -57,3 +57,106 @@ describe("resolveArtifactPath", () => {
|
||||
expect(resolveArtifactPath(base, href)).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe("splitFrontmatter", () => {
|
||||
const release = [{ key: "description", value: "Release", code: false }]
|
||||
const primary = [{ key: "mode", value: "primary", code: false }]
|
||||
|
||||
test.each([
|
||||
["LF frontmatter and body", "---\ndescription: Release\n---\n# Title", { properties: release, body: "# Title" }],
|
||||
[
|
||||
"CRLF and UTF-8 BOM",
|
||||
"\uFEFF---\r\ndescription: Release\r\n---\r\n# Title\r\n",
|
||||
{ properties: release, body: "# Title\r\n" },
|
||||
],
|
||||
["frontmatter at EOF", "---\nmode: primary\n---", { properties: primary, body: "" }],
|
||||
["frontmatter with trailing blank lines only", "---\nmode: primary\n---\n\n", { properties: primary, body: "\n" }],
|
||||
[
|
||||
"empty frontmatter before a later thematic break",
|
||||
"---\n---\n\nBody\n\n---\n\nFooter",
|
||||
{ body: "\nBody\n\n---\n\nFooter" },
|
||||
],
|
||||
["whitespace-only frontmatter", "---\n \n---\n# Title", { body: "# Title" }],
|
||||
])("splits %s", (_, input, expected) => {
|
||||
expect(splitFrontmatter(input)).toEqual(expected)
|
||||
})
|
||||
|
||||
test("reads scalars, block scalars, and nested values", () => {
|
||||
const yaml = [
|
||||
"# reviewer agent",
|
||||
'description: "Reviews code"',
|
||||
"tools:",
|
||||
" write: false",
|
||||
" bash: false",
|
||||
"skills:",
|
||||
"- review",
|
||||
"prompt: |",
|
||||
" Line one",
|
||||
"",
|
||||
" Line two",
|
||||
"summary: >",
|
||||
" Folded",
|
||||
" text",
|
||||
"note: first",
|
||||
" second",
|
||||
"empty:",
|
||||
"",
|
||||
].join("\n")
|
||||
|
||||
expect(splitFrontmatter(`---\n${yaml}\n---\nBody`).properties).toEqual([
|
||||
{ key: "description", value: "Reviews code", code: false },
|
||||
{ key: "tools", value: "write: false\nbash: false", code: true },
|
||||
{ key: "skills", value: "- review", code: true },
|
||||
{ key: "prompt", value: "Line one\n\nLine two", code: false },
|
||||
{ key: "summary", value: "Folded text", code: false },
|
||||
{ key: "note", value: "first second", code: false },
|
||||
{ key: "empty", value: "", code: false },
|
||||
])
|
||||
})
|
||||
|
||||
test.each([
|
||||
["a line that is not a key", "---\njust text\n---\n# Title", { body: "```yaml\njust text\n```\n\n# Title" }],
|
||||
["a top-level list", "---\n- one\n- two\n---", { body: "```yaml\n- one\n- two\n```" }],
|
||||
[
|
||||
"backticks in unreadable frontmatter",
|
||||
"---\n- ```ts\n---\n# Title",
|
||||
{ body: "````yaml\n- ```ts\n````\n\n# Title" },
|
||||
],
|
||||
])("keeps %s as a YAML block", (_, input, expected) => {
|
||||
expect(splitFrontmatter(input)).toEqual(expected)
|
||||
})
|
||||
|
||||
test.each([
|
||||
["a trailing comment", "temperature: 0.2 # lower"],
|
||||
["a comment in a plain multi-line value", "note: first\n second # more"],
|
||||
["a comment after a block scalar indicator", "prompt: | # keep\n Line"],
|
||||
["an escaped double-quoted value", 'title: "a \\"b\\""'],
|
||||
["an escaped single-quoted value", "title: 'it''s'"],
|
||||
["a quoted value that wraps", 'description: "foo\n bar"'],
|
||||
["a quoted value followed by a comment", 'title: "a" # note'],
|
||||
])("keeps %s as a YAML block", (_, yaml) => {
|
||||
expect(splitFrontmatter(`---\n${yaml}\n---\nBody`)).toEqual({ body: `\`\`\`yaml\n${yaml}\n\`\`\`\n\nBody` })
|
||||
})
|
||||
|
||||
test("reads hashes that are not comments", () => {
|
||||
const yaml = ['title: "a # b"', "tag: C#", "summary: >", " # not a comment", "prompt: |", " # heading"].join("\n")
|
||||
|
||||
expect(splitFrontmatter(`---\n${yaml}\n---\nBody`).properties).toEqual([
|
||||
{ key: "title", value: "a # b", code: false },
|
||||
{ key: "tag", value: "C#", code: false },
|
||||
{ key: "summary", value: "# not a comment", code: false },
|
||||
{ key: "prompt", value: "# heading", code: false },
|
||||
])
|
||||
})
|
||||
|
||||
test.each([
|
||||
["plain markdown", "# Title\n\n---\n\nSection"],
|
||||
["unclosed opening delimiter", "---\ndescription: Release\n# Title"],
|
||||
["four-dash thematic break on line 1", "----\ndescription: Release\n---\n# Title"],
|
||||
["four-dash line instead of closing delimiter", "---\ndescription: Release\n----\n# Title"],
|
||||
["leading blank line before delimiter", "\n---\ndescription: Release\n---\n# Title"],
|
||||
["delimiter after prose", "Intro\n---\ndescription: Release\n---\n# Title"],
|
||||
])("leaves %s untouched", (_, input) => {
|
||||
expect(splitFrontmatter(input)).toEqual({ body: input })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -141,3 +141,85 @@ export function resolveArtifactPath(base: string, href: string) {
|
||||
|
||||
return `${dir.startsWith("/") ? "/" : ""}${segments.join("/")}`
|
||||
}
|
||||
|
||||
const frontmatter = /^\uFEFF?---[ \t]*\r?\n(?:([\s\S]*?)\r?\n)??---[ \t]*(?:\r?\n|$)/
|
||||
|
||||
/**
|
||||
* Split a leading YAML frontmatter block from Markdown so preview does not render its closing `---`
|
||||
* as a setext heading. Top-level `key: value` entries come back as properties; frontmatter this
|
||||
* reader cannot split stays in the body as a fenced `yaml` code block. Empty frontmatter is dropped.
|
||||
*/
|
||||
export function splitFrontmatter(text: string) {
|
||||
const match = frontmatter.exec(text)
|
||||
|
||||
if (!match) return { body: text }
|
||||
const body = text.slice(match[0].length)
|
||||
const yaml = (match[1] ?? "").replace(/\r\n?/g, "\n")
|
||||
|
||||
if (!yaml.trim()) return { body }
|
||||
const properties = readProperties(yaml)
|
||||
|
||||
if (properties) return { properties, body }
|
||||
const longest = Array.from(yaml.matchAll(/`+/g)).reduce((max, run) => Math.max(max, run[0].length), 0)
|
||||
const fence = "`".repeat(Math.max(3, longest + 1))
|
||||
const block = `${fence}yaml\n${yaml}\n${fence}`
|
||||
|
||||
return { body: body.trim() ? `${block}\n\n${body}` : block }
|
||||
}
|
||||
|
||||
/** One top-level frontmatter entry. `code` marks a nested map or list, shown as its YAML source. */
|
||||
export type FrontmatterProperty = { key: string; value: string; code: boolean }
|
||||
|
||||
function readProperties(yaml: string) {
|
||||
const lines = yaml.split("\n").filter((line) => !line.startsWith("#"))
|
||||
// A top-level key starts at column 0; a column-0 "- " item belongs to the key above it.
|
||||
const starts = lines.flatMap((line, index) => (/^[^\s-]|^-[^\s]/.test(line) ? [index] : []))
|
||||
|
||||
if (starts.length === 0 || lines.slice(0, starts[0]).some((line) => line.trim())) return
|
||||
const properties = starts.map((start, index) => readProperty(lines[start], lines.slice(start + 1, starts[index + 1])))
|
||||
|
||||
if (!properties.every((property) => property !== undefined)) return
|
||||
|
||||
return properties
|
||||
}
|
||||
|
||||
// A `#` at the start or after whitespace begins a YAML comment in a plain scalar.
|
||||
const comment = /(?:^|\s)#/
|
||||
|
||||
function readProperty(head: string, rest: string[]): FrontmatterProperty | undefined {
|
||||
const match = /^([^\s:][^:]*?):(?:[ \t]+(.*))?$/.exec(head)
|
||||
|
||||
if (!match) return
|
||||
const key = match[1]
|
||||
const value = (match[2] ?? "").trim()
|
||||
const block = rest.slice(0, rest.findLastIndex((line) => line.trim()) + 1)
|
||||
|
||||
// Only quoted values that close on this line without escapes are read; others fall back to the YAML block.
|
||||
if (/^["']/.test(value)) {
|
||||
const quoted = /^"([^"\\]*)"$|^'([^']*)'$/.exec(value)
|
||||
|
||||
if (!quoted || block.length > 0) return
|
||||
|
||||
return { key, value: quoted[1] ?? quoted[2], code: false }
|
||||
}
|
||||
|
||||
if (comment.test(value)) return
|
||||
|
||||
if (block.length === 0) return { key, value, code: false }
|
||||
const indent = Math.min(...block.flatMap((line) => (line.trim() ? [line.length - line.trimStart().length] : [])))
|
||||
const lines = block.map((line) => line.slice(indent))
|
||||
|
||||
if (/^\|[+-]?\d?$/.test(value)) return { key, value: lines.join("\n"), code: false }
|
||||
|
||||
// Folded (`>`) and plain multi-line scalars read as one line.
|
||||
if (value) {
|
||||
const folded = /^>[+-]?\d?$/.test(value)
|
||||
|
||||
if (!folded && lines.some((line) => comment.test(line))) return
|
||||
const words = [folded ? "" : value, ...lines.map((line) => line.trim())]
|
||||
|
||||
return { key, value: words.filter(Boolean).join(" "), code: false }
|
||||
}
|
||||
|
||||
return { key, value: lines.join("\n"), code: true }
|
||||
}
|
||||
|
||||
@@ -24,6 +24,8 @@ export default {
|
||||
"view.table.copyCell": "Copy cell",
|
||||
"view.table.copyFailed": "Couldn't copy this cell.",
|
||||
"view.fontSample": "Sphinx of black quartz, judge my vow.",
|
||||
"view.properties": "Properties",
|
||||
"view.properties.showAll": "Show all {{count}} properties",
|
||||
"open.in": "Open in",
|
||||
"open.ariaLabel": "Open in {{app}}",
|
||||
"open.menu": "Open options",
|
||||
|
||||
Reference in New Issue
Block a user