peppa/apps/web/components/Markdown.tsx
Асель 4a80d9dc6b PEP-32/33/37: story page tabs, live agent step feed, SSE live updates instead of 5 s polling
- PEP-37: change hub (runner/live.ts) woken by notify() (new 'web' subscriber) and
  PRAGMA data_version; per-scope fingerprints; GET /api/live SSE (no-transform, ping 15 s);
  LiveRefresh replaces AutoRefresh with a connection indicator and polling fallback
- PEP-33: async PostToolUse/PostToolUseFailure hook -> 'step' events (last 200 per
  session), AgentSteps live feed on the story page and runner panel, tasks.md progress
  on board cards and the story header
- PEP-32: story page header + tabs Proposal/Design/Specs/Tasks/Comments/Tests/Merge
  request/Activity, safe Markdown renderer, PM comments visible in get_task, edit
  title/description/epic, accept-and-merge (acceptStory)
- OpenSpec changes archived; specs live-updates, agent-steps, story-page

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 05:59:15 +05:00

173 lines
7.7 KiB
TypeScript

// Safe Markdown for OpenSpec artifacts (PEP-32): the subset proposals and designs use —
// headings, paragraphs, lists with checkboxes, code blocks, tables, quotes, rules, inline
// code/bold/italic/links. Everything becomes React elements; no HTML from the file is
// ever injected, and only http(s), mailto and relative links are kept.
import { Fragment, type ReactNode } from "react";
import { cn } from "@/lib/utils";
type Block =
| { t: "h"; level: number; text: string }
| { t: "p"; text: string }
| { t: "code"; lang: string; text: string }
| { t: "list"; ordered: boolean; items: Array<{ text: string; checked: boolean | null; depth: number }> }
| { t: "quote"; text: string }
| { t: "table"; head: string[]; rows: string[][] }
| { t: "hr" };
const LIST_RE = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/;
const splitRow = (l: string) => l.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((c) => c.trim());
export function parseMarkdown(src: string): Block[] {
const lines = src.replace(/\r\n?/g, "\n").split("\n");
const out: Block[] = [];
let i = 0;
while (i < lines.length) {
const line = lines[i]!;
if (!line.trim()) {
i++;
continue;
}
const fence = line.match(/^\s*(```|~~~)\s*(\S*)/);
if (fence) {
const body: string[] = [];
i++;
while (i < lines.length && !lines[i]!.trim().startsWith(fence[1]!)) body.push(lines[i++]!);
i++;
out.push({ t: "code", lang: fence[2] ?? "", text: body.join("\n") });
continue;
}
const h = line.match(/^(#{1,6})\s+(.*?)\s*#*\s*$/);
if (h) {
out.push({ t: "h", level: h[1]!.length, text: h[2]! });
i++;
continue;
}
if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(line)) {
out.push({ t: "hr" });
i++;
continue;
}
if (line.includes("|") && /^\s*\|?\s*:?-{2,}/.test(lines[i + 1] ?? "") && (lines[i + 1] ?? "").includes("-")) {
const head = splitRow(line);
const rows: string[][] = [];
i += 2;
while (i < lines.length && lines[i]!.includes("|") && lines[i]!.trim()) rows.push(splitRow(lines[i++]!));
out.push({ t: "table", head, rows });
continue;
}
if (/^\s*>/.test(line)) {
const body: string[] = [];
while (i < lines.length && /^\s*>/.test(lines[i]!)) body.push(lines[i++]!.replace(/^\s*>\s?/, ""));
out.push({ t: "quote", text: body.join("\n") });
continue;
}
const li = line.match(LIST_RE);
if (li) {
const ordered = /\d/.test(li[2]!);
const items: Array<{ text: string; checked: boolean | null; depth: number }> = [];
while (i < lines.length) {
const m = lines[i]!.match(LIST_RE);
if (m) {
const box = m[3]!.match(/^\[([ xX])\]\s+(.*)$/);
items.push({ text: box ? box[2]! : m[3]!, checked: box ? box[1] !== " " : null, depth: Math.min(3, Math.floor(m[1]!.replace(/\t/g, " ").length / 2)) });
i++;
} else if (lines[i]!.trim() && /^\s{2,}/.test(lines[i]!) && items.length) {
items.at(-1)!.text += ` ${lines[i++]!.trim()}`; // continuation line
} else break;
}
out.push({ t: "list", ordered, items });
continue;
}
const para: string[] = [];
while (i < lines.length && lines[i]!.trim() && !/^(#{1,6}\s|\s*```|\s*~~~|\s*>)/.test(lines[i]!) && !LIST_RE.test(lines[i]!)) para.push(lines[i++]!.trim());
out.push({ t: "p", text: para.join(" ") });
}
return out;
}
export function safeHref(href: string): string | null {
const h = href.trim();
if (/^(https?:|mailto:)/i.test(h)) return h;
if (/^[a-z][a-z0-9+.-]*:/i.test(h) || h.startsWith("//")) return null; // javascript:, data:, protocol-relative…
return h;
}
// Inline: `code`, **bold**, *italic* or _italic_, [text](url), bare https links.
export function inline(text: string, key = "i"): ReactNode[] {
const out: ReactNode[] = [];
const re = /(`+)([^`]+?)\1|\*\*([^*]+)\*\*|__([^_]+)__|\[([^\]]+)\]\(([^)\s]+)\)|(?<![\w*])\*([^*\s][^*]*?)\*(?!\w)|(?<![\w_])_([^_\s][^_]*?)_(?!\w)|(https?:\/\/[^\s)<]+)/g;
let last = 0;
let n = 0;
for (const m of text.matchAll(re)) {
if (m.index! > last) out.push(text.slice(last, m.index));
const k = `${key}-${n++}`;
if (m[2] != null) out.push(<code key={k} className="rounded bg-muted px-1 py-0.5 font-mono text-[0.85em]">{m[2]}</code>);
else if (m[3] != null || m[4] != null) out.push(<strong key={k}>{inline(m[3] ?? m[4]!, k)}</strong>);
else if (m[5] != null) {
const href = safeHref(m[6]!);
out.push(href ? <a key={k} href={href} className="text-primary" rel="noreferrer">{inline(m[5], k)}</a> : <Fragment key={k}>{m[5]}</Fragment>);
} else if (m[7] != null || m[8] != null) out.push(<em key={k}>{inline(m[7] ?? m[8]!, k)}</em>);
else if (m[9] != null) out.push(<a key={k} href={m[9]} className="text-primary [overflow-wrap:anywhere]" rel="noreferrer">{m[9]}</a>);
last = m.index! + m[0].length;
}
if (last < text.length) out.push(text.slice(last));
return out;
}
const H = ["h2", "h3", "h4", "h5", "h6", "h6"] as const;
const H_CLASS = ["text-lg", "text-base", "text-sm", "text-sm", "text-xs", "text-xs"];
export function Markdown({ text, className }: { text: string; className?: string }) {
const blocks = parseMarkdown(text);
return (
<div className={cn("flex min-w-0 flex-col gap-3 text-sm leading-relaxed [overflow-wrap:anywhere]", className)}>
{blocks.map((b, i) => {
const k = `b${i}`;
switch (b.t) {
case "h": {
const Tag = H[b.level - 1]!;
return <Tag key={k} className={cn("m-0 mt-2 font-semibold first:mt-0", H_CLASS[b.level - 1])}>{inline(b.text, k)}</Tag>;
}
case "p":
return <p key={k} className="m-0">{inline(b.text, k)}</p>;
case "code":
return <pre key={k} className="m-0 max-h-[32em] overflow-auto rounded-md border bg-muted/50 p-3 font-mono text-xs leading-relaxed whitespace-pre">{b.text}</pre>;
case "quote":
return <blockquote key={k} className="m-0 border-l-2 pl-3 text-muted-foreground">{inline(b.text, k)}</blockquote>;
case "hr":
return <hr key={k} className="border-border" />;
case "table":
return (
<div key={k} className="overflow-auto">
<table className="w-full border-collapse text-xs">
<thead>
<tr>{b.head.map((c, j) => <th key={j} className="border px-2 py-1 text-left font-semibold">{inline(c, `${k}h${j}`)}</th>)}</tr>
</thead>
<tbody>
{b.rows.map((r, ri) => (
<tr key={ri}>{r.map((c, j) => <td key={j} className="border px-2 py-1 align-top">{inline(c, `${k}r${ri}c${j}`)}</td>)}</tr>
))}
</tbody>
</table>
</div>
);
case "list": {
const Tag = b.ordered ? "ol" : "ul";
const checklist = b.items.some((it) => it.checked != null);
return (
<Tag key={k} className={cn("m-0 flex flex-col gap-1", checklist ? "list-none p-0" : b.ordered ? "list-decimal pl-5" : "list-disc pl-5")}>
{b.items.map((it, j) => (
<li key={j} style={it.depth ? { marginLeft: `${it.depth * 1.25}rem` } : undefined} className={cn(it.checked != null && "flex items-start gap-2")}>
{it.checked != null && <input type="checkbox" checked={it.checked} readOnly disabled className="mt-1 size-3.5 shrink-0 accent-primary" />}
<span className={cn(it.checked && "text-muted-foreground")}>{inline(it.text, `${k}l${j}`)}</span>
</li>
))}
</Tag>
);
}
}
})}
</div>
);
}