Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(artifacts): a fence with no language tag is a block, not inline code

rubenluetke10-beep6e06331c9f7d
diff --git a/jarvis/ui/web/frontend/src/components/outputs/AsciiTableFence.test.tsx b/jarvis/ui/web/frontend/src/components/outputs/AsciiTableFence.test.tsx
new file mode 100644
index 0000000000..45283b8c7c
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/outputs/AsciiTableFence.test.tsx
@@ -0,0 +1,73 @@
+/**
+ * A fence in a Markdown deliverable always renders as a BLOCK — the defect
+ * this pins is a fence with no language tag escaping as a bare `<code>` with
+ * no `<pre>` around it, which folds every line break away and turns a drawn
+ * table into one run-on line. An ASCII grid goes further and becomes a real
+ * table, with the original art behind the Source switch.
+ */
+import { afterEach, describe, expect, it } from "vitest";
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+
+import { MarkdownProse } from "@/components/outputs/MarkdownProse";
+
+afterEach(() => cleanup());
+
+const GRID = [
+ "+------+----------+",
+ "| ID | Priority |",
+ "+------+----------+",
+ "| 01 | P1 |",
+ "+------+----------+",
+].join("\n");
+
+function draw(text: string) {
+ return render(<MarkdownProse slug="run" path="a/report.md" files={[]} text={text} />);
+}
+
+describe("fences in an artifact document", () => {
+ it("keeps a fence with no language tag a block, not inline code", () => {
+ const { container } = draw("```\nfirst line\nsecond line\n```\n");
+ const pre = container.querySelector("pre");
+ expect(pre).not.toBeNull();
+ expect(pre?.textContent).toContain("first line\nsecond line");
+ // The bare `<code>` the bug produced sat directly under the article.
+ expect(container.querySelector("article > code")).toBeNull();
+ });
+
+ it("never writes react-markdown's syntax tree into the DOM", () => {
+ const { container } = draw("`inline` and [a link](https://example.com)\n");
+ expect(container.querySelector("[node]")).toBeNull();
+ });
+
+ it("draws an unfenced grid as a table", () => {
+ draw(`## Matrix\n\n${GRID}\n`);
+ expect(screen.getByRole("columnheader", { name: "Priority" })).toBeTruthy();
+ expect(screen.getByRole("cell", { name: "01" })).toBeTruthy();
+ });
+
+ it("draws a plain-text fence holding a grid as a table", () => {
+ draw(`\`\`\`text\n${GRID}\n\`\`\`\n`);
+ expect(screen.getByTestId("ascii-table-fence")).toBeTruthy();
+ expect(screen.getByRole("columnheader", { name: "ID" })).toBeTruthy();
+ });
+
+ it("shows the original art behind the Source switch", () => {
+ draw(`\`\`\`\n${GRID}\n\`\`\`\n`);
+ const fence = screen.getByTestId("ascii-table-fence");
+ expect(fence.getAttribute("data-mode")).toBe("rendered");
+ fireEvent.click(screen.getByRole("button", { name: "Source" }));
+ expect(fence.getAttribute("data-mode")).toBe("source");
+ expect(fence.textContent).toContain("+------+----------+");
+ });
+
+ it("leaves a code fence a code block", () => {
+ draw("```python\nprint('hi')\n```\n");
+ expect(screen.queryByTestId("ascii-table-fence")).toBeNull();
+ });
+
+ it("leaves a GFM table to Markdown", () => {
+ const { container } = draw("| a | b |\n|---|---|\n| 1 | 2 |\n");
+ expect(screen.queryByTestId("ascii-table-fence")).toBeNull();
+ expect(container.querySelector("table")).not.toBeNull();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/outputs/AsciiTableFence.tsx b/jarvis/ui/web/frontend/src/components/outputs/AsciiTableFence.tsx
new file mode 100644
index 0000000000..2377767ff6
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/outputs/AsciiTableFence.tsx
@@ -0,0 +1,136 @@
+/**
+ * An ASCII grid table drawn as a real table, with the original art one click
+ * away.
+ *
+ * A worker writing plain text builds a table out of `+---+` and `|` — the
+ * shape a terminal understands. In a document that art is not a table: the
+ * columns only line up while the pane is wider than the widest row, nothing
+ * can be scanned by eye, and a single long cell pushes the whole grid apart.
+ * Here the parsed rows become a `<table>` the reader can scroll, and the
+ * Rendered / Source switch — the same control a drawn `html`/`svg` fence
+ * carries — keeps the original text available and copyable.
+ *
+ * All colour comes from theme tokens, so the table reads in both palettes.
+ */
+import { useState } from "react";
+import { Check, Copy } from "lucide-react";
+
+import { cn } from "@/lib/utils";
+import { robustCopy } from "@/lib/clipboard";
+import { useT } from "@/i18n";
+import { CodeBlock } from "@/components/docs/CodeBlock";
+import type { AsciiGrid } from "@/lib/asciiTable";
+
+const CELL = "px-3 py-1.5 align-top text-foreground/90";
+
+export function AsciiTableFence({ grid, code }: { grid: AsciiGrid; code: string }) {
+ const t = useT();
+ const [mode, setMode] = useState<"rendered" | "source">("rendered");
+ const [copied, setCopied] = useState(false);
+
+ const copy = () => {
+ void robustCopy(code).then((ok) => {
+ if (!ok) return;
+ setCopied(true);
+ window.setTimeout(() => setCopied(false), 1500);
+ });
+ };
+
+ const segment = (value: "rendered" | "source", label: string) => (
+ <button
+ type="button"
+ aria-pressed={mode === value}
+ onClick={() => setMode(value)}
+ className={cn(
+ "rounded-sm px-2 py-0.5 text-[10px] font-medium transition-colors",
+ mode === value
+ ? "bg-background text-foreground"
+ : "text-muted-foreground hover:text-foreground",
+ )}
+ >
+ {label}
+ </button>
+ );
+
+ return (
+ <div
+ className="not-prose my-4 overflow-hidden rounded-md border border-border bg-muted/40"
+ data-testid="ascii-table-fence"
+ data-mode={mode}
+ >
+ <div className="flex items-center justify-between gap-2 border-b border-border/40 bg-muted/20 px-3 py-1">
+ <span className="text-[10px] uppercase tracking-wider text-muted-foreground">table</span>
+ <div className="flex items-center gap-1.5">
+ <div role="group" className="inline-flex rounded border border-border/60 bg-muted/40 p-0.5">
+ {segment("rendered", t("outputs_view.fence_rendered"))}
+ {segment("source", t("outputs_view.fence_source"))}
+ </div>
+ <button
+ type="button"
+ onClick={copy}
+ className="rounded p-1 text-muted-foreground transition hover:bg-muted hover:text-foreground"
+ title={t("docs_content.copy_code")}
+ aria-label={copied ? t("docs_content.code_copied") : t("docs_content.copy_code")}
+ >
+ {copied ? (
+ <Check className="h-3 w-3 text-muted-foreground" aria-hidden="true" />
+ ) : (
+ <Copy className="h-3 w-3" aria-hidden="true" />
+ )}
+ </button>
+ </div>
+ </div>
+ {mode === "source" ? (
+ <CodeBlock language="text" code={code} chrome={false} />
+ ) : (
+ <div className="overflow-x-auto bg-card">
+ <table className="w-full border-collapse text-[13px] leading-snug">
+ {grid.caption !== null && (
+ <caption className="border-b border-border/40 bg-muted/20 px-3 py-1.5 text-left text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">
+ {grid.caption}
+ </caption>
+ )}
+ {grid.head !== null && (
+ <thead className="bg-muted/30">
+ <tr>
+ {grid.head.map((cell, i) => (
+ <th
+ key={i}
+ scope="col"
+ className={cn(CELL, "text-left font-semibold text-foreground")}
+ >
+ {cell}
+ </th>
+ ))}
+ </tr>
+ </thead>
+ )}
+ <tbody>
+ {grid.rows.map((row, ri) => (
+ <tr key={ri} className="border-t border-border/60">
+ {row.length === 1 && grid.columns > 1 ? (
+ // A one-cell row inside a wider grid is a section banner in
+ // the original art — keep it spanning rather than dropping
+ // it into the first column.
+ <td
+ colSpan={grid.columns}
+ className={cn(CELL, "bg-muted/20 font-medium text-foreground")}
+ >
+ {row[0]}
+ </td>
+ ) : (
+ Array.from({ length: grid.columns }, (_, ci) => (
+ <td key={ci} className={CELL}>
+ {row[ci] ?? ""}
+ </td>
+ ))
+ )}
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/outputs/MarkdownProse.tsx b/jarvis/ui/web/frontend/src/components/outputs/MarkdownProse.tsx
index e1127f2c74..f150b1dfae 100644
--- a/jarvis/ui/web/frontend/src/components/outputs/MarkdownProse.tsx
+++ b/jarvis/ui/web/frontend/src/components/outputs/MarkdownProse.tsx
@@ -7,14 +7,16 @@
* Shiki `CodeBlock`, except an `html` or `svg` fence, which is DRAWN
* (`RenderedFence`: a chart the worker wrote as inline SVG is a chart, a
* snippet of HTML runs in a sandbox, the markup one click away behind its
- * Source switch); a link to a sibling file in the same run selects that
+ * Source switch), and a plain-text fence holding an ASCII grid table, which
+ * becomes a real table (`AsciiTableFence`); a link to a sibling file in the
+ * same run selects that
* file instead of navigating; an external link opens in the user's real
* browser through the open-external bridge (the desktop WebView drops a bare
* `target="_blank"`); an image next to the document is served from the run
* archive. The typography is the caller's — the reader passes its own
* classes, the output page the artifact standard's.
*/
-import { useMemo } from "react";
+import { Children, isValidElement, useMemo, type ReactNode } from "react";
import ReactMarkdown, { type Components } from "react-markdown";
import remarkGfm from "remark-gfm";
@@ -23,6 +25,8 @@ import { openExternalUrl } from "@/lib/openExternal";
import { artifactInlineUrl, type ArtifactSummary } from "@/hooks/useOutputs";
import { CodeBlock } from "@/components/docs/CodeBlock";
import { RenderedFence } from "@/components/outputs/RenderedFence";
+import { AsciiTableFence } from "@/components/outputs/AsciiTableFence";
+import { fenceLooseAsciiTables, parseAsciiTable } from "@/lib/asciiTable";
/**
* Split a leading YAML front matter block (`---` … `---`) off a document.
@@ -57,6 +61,33 @@ export function resolveSiblingPath(fromPath: string, href: string): string | nul
return base.join("/");
}
+/** Languages whose fences may hold an ASCII grid table rather than code. */
+const PLAIN_FENCE_LANGUAGES = new Set(["", "text", "txt", "plain", "plaintext", "ascii"]);
+
+/**
+ * Read the fence back out of a Markdown `<pre>`.
+ *
+ * The fence has to be handled HERE and not in the `code` component, because
+ * react-markdown 9 dropped the `inline` prop: the same `code` component serves
+ * inline `` `code` `` and block fences and cannot tell them apart. The parent
+ * element can — a fence is the only `code` inside a `pre`. What arrives as
+ * `children` is our own `code` component still unrendered, so its props are the
+ * ORIGINAL ones: the `language-…` class and the raw fence text.
+ *
+ * A fence with no language tag lands here with `language: ""`. That case is
+ * exactly what used to escape as a bare `<code>` with no `<pre>` around it,
+ * which collapses every line break and renders a table as one run-on line.
+ */
+export function readFence(children: ReactNode): { language: string; code: string } | null {
+ const element = Children.toArray(children).find((child) => isValidElement(child));
+ if (!isValidElement<{ className?: string; children?: ReactNode }>(element)) return null;
+ const match = /language-([\w+#.-]+)/.exec(element.props.className ?? "");
+ return {
+ language: match ? match[1].toLowerCase() : "",
+ code: String(element.props.children ?? "").replace(/\n$/, ""),
+ };
+}
+
/**
* The typographic base every Markdown document shares: Tailwind's prose in
* both themes, links in the accent, inline code on a quiet chip, tables and
@@ -91,31 +122,43 @@ export function MarkdownProse({
testId?: string;
}) {
const known = useMemo(() => new Set(files.map((f) => f.path)), [files]);
- const { meta, body } = useMemo(() => splitFrontMatter(text), [text]);
+ // An ASCII grid table the author never fenced is folded into a paragraph by
+ // Markdown, losing every line break; fencing it first hands it to the `pre`
+ // handler, which draws it as a table. GFM tables are left untouched.
+ const { meta, body } = useMemo(() => {
+ const split = splitFrontMatter(text);
+ return { meta: split.meta, body: fenceLooseAsciiTables(split.body) };
+ }, [text]);
const components = useMemo<Components>(
() => ({
- // Fenced blocks render their own complete container; unwrapping the
- // Markdown ``pre`` avoids invalid ``pre > div`` nesting around CodeBlock.
+ // EVERY fence is replaced here, whether or not it carries a language
+ // tag: each replacement brings its own complete container, so the
+ // Markdown ``pre`` is dropped rather than left to wrap a ``div``.
pre({ children }) {
- return <>{children}</>;
- },
- code({ className: codeClass, children, ...rest }) {
- const match = /language-(\w+)/.exec(codeClass || "");
- if (!match) {
- return (
- <code className={codeClass} {...rest}>
- {children}
- </code>
- );
- }
- const language = match[1].toLowerCase();
- const code = String(children).replace(/\n$/, "");
+ const fence = readFence(children);
+ if (fence === null) return <pre>{children}</pre>;
+ const { language, code } = fence;
if (language === "html" || language === "svg") {
return <RenderedFence language={language} code={code} />;
}
+ if (PLAIN_FENCE_LANGUAGES.has(language)) {
+ const grid = parseAsciiTable(code);
+ if (grid !== null) return <AsciiTableFence grid={grid} code={code} />;
+ }
return <CodeBlock language={language} code={code} />;
},
- a({ href, children, ...rest }) {
+ // Inline code only — a fence never reaches this, `pre` consumed it.
+ // ``node`` is dropped from the spread on every element below: it is
+ // react-markdown's syntax tree, and React would write it into the DOM
+ // as ``node="[object Object]"``.
+ code({ node: _node, className: codeClass, children, ...rest }) {
+ return (
+ <code className={codeClass} {...rest}>
+ {children}
+ </code>
+ );
+ },
+ a({ node: _node, href, children, ...rest }) {
const sibling = href ? resolveSiblingPath(path, href) : null;
if (sibling && known.has(sibling) && onSelectSibling) {
return (
@@ -152,7 +195,7 @@ export function MarkdownProse({
</a>
);
},
- img({ src, alt, ...rest }) {
+ img({ node: _node, src, alt, ...rest }) {
const sibling = typeof src === "string" ? resolveSiblingPath(path, src) : null;
const resolved =
sibling && known.has(sibling) ? artifactInlineUrl(slug, sibling) : src;
diff --git a/jarvis/ui/web/frontend/src/lib/asciiTable.test.ts b/jarvis/ui/web/frontend/src/lib/asciiTable.test.ts
new file mode 100644
index 0000000000..1217206d21
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/asciiTable.test.ts
@@ -0,0 +1,106 @@
+/**
+ * The ASCII grid parser: it recognises the `+---+` / `| a | b |` art a worker
+ * writes as a table, and — just as importantly — refuses everything else, so
+ * ordinary code and prose never get mangled into a table.
+ */
+import { describe, expect, it } from "vitest";
+
+import { fenceLooseAsciiTables, parseAsciiTable } from "@/lib/asciiTable";
+
+const lines = (...rows: string[]) => rows.join("\n");
+
+const SIMPLE = lines(
+ "+------+----------+",
+ "| ID | Priority |",
+ "+------+----------+",
+ "| 01 | P1 |",
+ "| 02 | P2 |",
+ "+------+----------+",
+);
+
+describe("parseAsciiTable", () => {
+ it("reads head and body out of a drawn grid", () => {
+ const grid = parseAsciiTable(SIMPLE);
+ expect(grid).not.toBeNull();
+ expect(grid?.columns).toBe(2);
+ expect(grid?.head).toEqual(["ID", "Priority"]);
+ expect(grid?.rows).toEqual([
+ ["01", "P1"],
+ ["02", "P2"],
+ ]);
+ expect(grid?.caption).toBeNull();
+ });
+
+ it("takes a one-cell opening row as the banner above the head", () => {
+ const grid = parseAsciiTable(
+ lines(
+ "+---------------------------+",
+ "| MASTER EXECUTION MATRIX |",
+ "+------+----------+---------+",
+ "| ID | Priority | Item |",
+ "+------+----------+---------+",
+ "| 01 | P1 | Fix CI |",
+ "+------+----------+---------+",
+ ),
+ );
+ expect(grid?.caption).toBe("MASTER EXECUTION MATRIX");
+ expect(grid?.head).toEqual(["ID", "Priority", "Item"]);
+ expect(grid?.rows).toEqual([["01", "P1", "Fix CI"]]);
+ });
+
+ it("keeps a one-cell row inside the body as a spanning row", () => {
+ const grid = parseAsciiTable(
+ lines(
+ "+------+----------+",
+ "| ID | Priority |",
+ "+------+----------+",
+ "| 01 | P1 |",
+ "| Later this week |",
+ "| 02 | P3 |",
+ "+------+----------+",
+ ),
+ );
+ expect(grid?.columns).toBe(2);
+ expect(grid?.rows).toEqual([["01", "P1"], ["Later this week"], ["02", "P3"]]);
+ });
+
+ it("accepts a GFM table that ended up inside a fence", () => {
+ const grid = parseAsciiTable(lines("| a | b |", "|---|---|", "| 1 | 2 |"));
+ expect(grid?.head).toEqual(["a", "b"]);
+ expect(grid?.rows).toEqual([["1", "2"]]);
+ });
+
+ it("refuses anything that is not a pure grid", () => {
+ // Prose and code must never be read as a table.
+ expect(parseAsciiTable("hello\nworld\nagain")).toBeNull();
+ expect(parseAsciiTable(lines("| a | b |", "|---|---|", "not a row"))).toBeNull();
+ // A box drawn around a paragraph is one column, not a table.
+ expect(parseAsciiTable(lines("+-------+", "| hi |", "+-------+"))).toBeNull();
+ // Rows with no rule between them are just pipes in text.
+ expect(parseAsciiTable(lines("| a | b |", "| 1 | 2 |", "| 3 | 4 |"))).toBeNull();
+ expect(parseAsciiTable("")).toBeNull();
+ });
+});
+
+describe("fenceLooseAsciiTables", () => {
+ it("fences a drawn grid the author left bare", () => {
+ const out = fenceLooseAsciiTables(`## Matrix\n\n${SIMPLE}\n\ndone`);
+ expect(out).toContain("```\n+------+----------+");
+ expect(out.endsWith("+------+----------+\n```\n\ndone")).toBe(true);
+ });
+
+ it("leaves a GFM table alone — Markdown already renders it", () => {
+ const gfm = lines("| a | b |", "|---|---|", "| 1 | 2 |");
+ expect(fenceLooseAsciiTables(gfm)).toBe(gfm);
+ });
+
+ it("never reaches inside an existing fence", () => {
+ const doc = `\`\`\`python\n${SIMPLE}\n\`\`\`\n`;
+ expect(fenceLooseAsciiTables(doc)).toBe(doc);
+ });
+
+ it("leaves a document with no grid byte-identical", () => {
+ const doc = "# Title\n\nSome prose with a | pipe in it.\n\n- a\n- b\n";
+ expect(fenceLooseAsciiTables(doc)).toBe(doc);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/lib/asciiTable.ts b/jarvis/ui/web/frontend/src/lib/asciiTable.ts
new file mode 100644
index 0000000000..440a68db97
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/asciiTable.ts
@@ -0,0 +1,155 @@
+/**
+ * ASCII grid tables — the `+---+---+` / `| a | b |` art a model writes when it
+ * wants a table but is producing plain text — parsed into rows a real
+ * `<table>` can be drawn from.
+ *
+ * Why this exists: such a grid only survives in a monospace block with its
+ * line breaks intact, and even then it stays a PICTURE of a table — nothing
+ * the reader can scan at reading width or copy a row out of. Recognising the
+ * shape lets the artifact renderer draw the table the author actually meant.
+ *
+ * The grammar accepted is deliberately narrow, because a false positive turns
+ * ordinary text into a mangled table:
+ * - a RULE line ends in `+` or `|` on both sides, carries only `-`, `=`, `+`,
+ * `|` and spaces between them, and contains at least one `-` or `=`;
+ * - a ROW line starts and ends with `|`;
+ * - EVERY non-blank line must be one or the other, and at least one rule must
+ * be present. Anything else returns `null` and the caller leaves the text
+ * exactly as it found it.
+ */
+
+export interface AsciiGrid {
+ /** A single full-width banner row the grid opens with, if it has one. */
+ caption: string | null;
+ /** Header cells, when a rule separates the first row from the body. */
+ head: string[] | null;
+ /** Body rows. A one-cell row in a multi-column grid spans the whole table. */
+ rows: string[][];
+ /** The widest row — the column count a spanning row spans. */
+ columns: number;
+}
+
+const RULE_SHAPE = /^[+|][-=+|\s]*[+|]$/;
+
+/** A horizontal border line of the grid. */
+function isRule(line: string): boolean {
+ return RULE_SHAPE.test(line) && /[-=]/.test(line);
+}
+
+/** A content line of the grid. Rules are tested first, so they never reach this. */
+function isRow(line: string): boolean {
+ return line.length > 2 && line.startsWith("|") && line.endsWith("|");
+}
+
+/**
+ * Split a row into trimmed cells. A `|` inside a cell would split it wrongly,
+ * which is the one ambiguity ASCII art cannot express and we do not try to.
+ */
+function cellsOf(line: string): string[] {
+ return line
+ .slice(1, -1)
+ .split("|")
+ .map((cell) => cell.trim());
+}
+
+/**
+ * Parse *text* as an ASCII grid table, or return `null` when it is not one.
+ *
+ * Also accepts a GFM table (`|---|---|` rules, no `+` corners) that ended up
+ * inside a code fence, where Markdown would never have rendered it as a table.
+ */
+export function parseAsciiTable(text: string): AsciiGrid | null {
+ const lines = text
+ .split(/\r?\n/)
+ .map((line) => line.trim())
+ .filter((line) => line.length > 0);
+ if (lines.length < 3) return null;
+
+ // Rules cut the grid into sections: an optional banner, an optional header,
+ // and the body. Which section is which is decided once they are all in.
+ const sections: string[][][] = [];
+ let current: string[][] = [];
+ let rules = 0;
+ for (const line of lines) {
+ if (isRule(line)) {
+ rules += 1;
+ if (current.length > 0) {
+ sections.push(current);
+ current = [];
+ }
+ continue;
+ }
+ if (!isRow(line)) return null;
+ current.push(cellsOf(line));
+ }
+ if (current.length > 0) sections.push(current);
+ if (rules === 0 || sections.length === 0) return null;
+
+ const columns = Math.max(...sections.flat().map((row) => row.length));
+ // A one-column "grid" is a box drawn around a paragraph, not a table.
+ if (columns < 2) return null;
+
+ let rest = sections;
+ let caption: string | null = null;
+ if (rest[0].length === 1 && rest[0][0].length === 1) {
+ caption = rest[0][0][0];
+ rest = rest.slice(1);
+ }
+ let head: string[] | null = null;
+ if (rest.length > 1 && rest[0].length === 1 && rest[0][0].length === columns) {
+ head = rest[0][0];
+ rest = rest.slice(1);
+ }
+
+ const rows = rest.flat();
+ if (rows.length === 0) return null;
+ return { caption, head, rows, columns };
+}
+
+const FENCE_MARKER = /^\s*(?:```|~~~)/;
+
+/**
+ * Wrap ASCII grid tables the author never fenced in a fence, so the Markdown
+ * parser stops folding them into one run-on paragraph.
+ *
+ * Only a block whose rule lines carry a `+` corner is touched. A GFM table
+ * (`|---|---|`) is left exactly as it is — Markdown already renders that as a
+ * real table, and fencing it would be a downgrade.
+ */
+export function fenceLooseAsciiTables(text: string): string {
+ const out: string[] = [];
+ let block: string[] = [];
+ let insideFence = false;
+
+ const flush = () => {
+ if (block.length === 0) return;
+ const looksDrawn = block.some((line) => {
+ const trimmed = line.trim();
+ return isRule(trimmed) && trimmed.includes("+");
+ });
+ if (looksDrawn && parseAsciiTable(block.join("\n")) !== null) {
+ out.push("```", ...block, "```");
+ } else {
+ out.push(...block);
+ }
+ block = [];
+ };
+
+ for (const raw of text.split("\n")) {
+ const line = raw.trim();
+ if (FENCE_MARKER.test(raw)) {
+ flush();
+ insideFence = !insideFence;
+ out.push(raw);
+ continue;
+ }
+ if (!insideFence && (isRule(line) || isRow(line))) {
+ block.push(raw);
+ continue;
+ }
+ flush();
+ out.push(raw);
+ }
+ flush();
+ return out.join("\n");
+}