Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8067: feat(views): readable, resizable and expandable markdown tables (#9321)
Jiayuan Zhang9b43430438e3
diff --git a/packages/views/editor/content-editor.tsx b/packages/views/editor/content-editor.tsxindex e321e742ac..cdafbd7534 100644--- a/packages/views/editor/content-editor.tsx+++ b/packages/views/editor/content-editor.tsx@@ -113,6 +113,15 @@ function hasUploadingNode(editor: Editor): boolean {return found;}+/** Inside a NodeView's own controls, which handle their clicks. The editable+ * content a NodeView hosts (a table's cells) is not: its links are the+ * editor's, unless they sit in a NodeView of their own (a mention). */+function isInNodeViewChrome(target: HTMLElement): boolean {+ const wrapper = target.closest("[data-node-view-wrapper]");+ const content = target.closest("[data-node-view-content-react]");+ return wrapper !== null && !(content !== null && wrapper.contains(content));+}+// Typesinterface ContentEditorBaseProps {@@ -641,7 +650,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(click(_view, event) {const target = event.target as HTMLElement;// Skip links inside NodeView wrappers — they handle their own clicks- if (target.closest("[data-node-view-wrapper]")) return false;+ if (isInNodeViewChrome(target)) return false;const link = target.closest("a");const href = link?.getAttribute("href");@@ -662,7 +671,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(auxclick(_view, event) {if (event.button !== 1) return false;const target = event.target as HTMLElement;- if (target.closest("[data-node-view-wrapper]")) return false;+ if (isInNodeViewChrome(target)) return false;const href = target.closest("a")?.getAttribute("href");if (!href || isMentionHref(href)) return false;event.preventDefault();diff --git a/packages/views/editor/extensions/index.ts b/packages/views/editor/extensions/index.tsindex 9661a4d35d..72a9259a3c 100644--- a/packages/views/editor/extensions/index.ts+++ b/packages/views/editor/extensions/index.ts@@ -48,6 +48,8 @@ import { createSlashCommandSuggestion, createBuiltinCommandSuggestion } from "./import type { BuiltinCommandSuggestionOptions } from "./slash-command-suggestion";import { SuggestionTriggerArmingExtension } from "./suggestion-trigger-arming";import { CodeBlockView } from "./code-block-view";+import { TableView } from "./table-view";+import { RICH_TABLE_CHROME_ATTRIBUTE } from "../../rich-content/rich-table";import { PatchedListItem, PatchedTaskItem } from "./list-item";import { createMarkdownPasteExtension } from "./markdown-paste";import { createMarkdownCopyExtension } from "./markdown-copy";@@ -243,8 +245,19 @@ export function createEditorExtensions(// wrapper the resizable NodeView emits), which prose.css styles with// `overflow-x: auto`. Without it a wide table is a bare <table> that can't// shrink below min-content, so the horizontal scrollbar lands on the- // page-level scroll container instead of the table itself.- Table.configure({ resizable: false, renderWrapper: true }),+ // page-level scroll container instead of the table itself. That covers+ // renderHTML; the editor itself draws TableView, the readonly tables' frame.+ Table.extend({+ addNodeView() {+ return ReactNodeViewRenderer(TableView, {+ contentDOMElementTag: "tbody",+ // The frame's toolbar and resize handles are controls, not content.+ stopEvent: ({ event }) =>+ event.target instanceof Element &&+ event.target.closest(`[${RICH_TABLE_CHROME_ATTRIBUTE}]`) !== null,+ });+ },+ }).configure({ resizable: false, renderWrapper: true }),TableRow,TableHeader,TableCell,diff --git a/packages/views/editor/extensions/mention-extension.ts b/packages/views/editor/extensions/mention-extension.tsindex 40f7519aec..abb8717877 100644--- a/packages/views/editor/extensions/mention-extension.ts+++ b/packages/views/editor/extensions/mention-extension.ts@@ -41,13 +41,18 @@ function findMentionStart(src: string): number {return -1;}+/** A mention as text, the way its pill reads: issues and projects by name. */+export function mentionText(attrs: Record<string, unknown>): string {+ const type = attrs.type ?? "member";+ const prefix = type === "issue" || type === "project" ? "" : "@";+ return `${prefix}${String(attrs.label ?? attrs.id ?? "")}`;+}+export const BaseMentionExtension = Mention.extend({addNodeView() {return ReactNodeViewRenderer(MentionView);},renderHTML({ node, HTMLAttributes }) {- const type = node.attrs.type ?? "member";- const prefix = type === "issue" || type === "project" ? "" : "@";return ["span",mergeAttributes(@@ -59,7 +64,7 @@ export const BaseMentionExtension = Mention.extend({"data-mention-id": node.attrs.id,},),- `${prefix}${node.attrs.label ?? node.attrs.id}`,+ mentionText(node.attrs),];},addAttributes() {diff --git a/packages/views/editor/extensions/table-view.test.tsx b/packages/views/editor/extensions/table-view.test.tsxnew file mode 100644index 0000000000..deb668796b--- /dev/null+++ b/packages/views/editor/extensions/table-view.test.tsx@@ -0,0 +1,159 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { EditorContent, useEditor, type Editor } from "@tiptap/react";++const copyText = vi.hoisted(() => vi.fn(async () => true));+vi.mock("@multica/ui/lib/clipboard", () => ({ copyText }));++vi.mock("../../issues/hooks", () => ({+ useResolveIssueIdentifier: () => null,+}));++vi.mock("../../i18n", async () => {+ const editor: Record<string, Record<string, unknown>> = (await import("../../locales/en/editor.json")).default;+ const t = (select: (bundle: unknown) => unknown, values: Record<string, unknown> = {}) => {+ const path: string[] = [];+ const recorder: unknown = new Proxy({}, { get: (_, key: string) => (path.push(key), recorder) });+ select(recorder);+ const [section = "", key = ""] = path;+ const strings = editor[section] ?? {};+ const plural = values.count === 1 ? `${key}_one` : `${key}_other`;+ const template = String(strings[key] ?? strings[plural] ?? "");+ return template.replace(/\{\{(\w+)\}\}/g, (_, name: string) => String(values[name] ?? ""));+ };+ return { useT: () => ({ t }), useTimeAgo: () => "just now" };+});++vi.mock("@multica/core/api", () => ({+ api: { getAttachmentTextContent: vi.fn() },+ PreviewTooLargeError: class extends Error {},+ PreviewUnsupportedError: class extends Error {},+}));++vi.mock("@multica/core/paths", () => ({+ useWorkspacePaths: () => ({ issueDetail: (id: string) => `/acme/issues/${id}` }),+ useWorkspaceSlug: () => "acme",+}));++vi.mock("../../issues/components/issue-mention-card", () => ({+ IssueMentionCard: ({ issueId, fallbackLabel }: { issueId: string; fallbackLabel?: string }) => (+ <span>{fallbackLabel ?? issueId}</span>+ ),+}));++vi.mock("../../projects/components/project-mention-card", () => ({+ ProjectMentionCard: () => <span />,+}));++vi.mock("../link-hover-card", () => ({+ useLinkHover: () => ({}),+ LinkHoverCard: () => null,+}));++import { createEditorExtensions } from ".";++const TABLE = [+ "| GitHub | Relation | Count |",+ "| --- | --- | --- |",+ "| harness switch | tracks it | 10 |",+ "| agent registry | see `code` | 9 |",+].join("\n");++let current: Editor | null = null;++function TestEditor({ content = TABLE }: { content?: string }) {+ const editor = useEditor({+ extensions: createEditorExtensions({+ placeholder: "",+ disableMentions: true,+ onUploadFileRef: { current: undefined },+ }),+ content,+ contentType: "markdown",+ immediatelyRender: true,+ });+ current = editor;+ return <EditorContent editor={editor} className="rich-text-editor" />;+}++async function renderEditor(content?: string, column = "Relation") {+ const view = render(<TestEditor content={content} />);+ const handle = await screen.findByRole("separator", { name: `Resize ${column} column` });+ const table = view.container.querySelector<HTMLTableElement>(".rich-table table");+ if (!table || !current) throw new Error("table not rendered");+ return { ...view, table, handle, editor: current };+}++afterEach(() => {+ current?.destroy();+ current = null;+ window.localStorage.clear();+ copyText.mockClear();+});++describe("editor TableView", () => {+ it("puts ProseMirror's rows inside the shared table frame", async () => {+ const { table } = await renderEditor();+ expect(table.firstElementChild?.tagName).toBe("COLGROUP");+ expect(table.querySelector<HTMLTableSectionElement>(":scope > tbody")?.rows).toHaveLength(3);+ expect(table.rows[0]?.cells[1]?.tagName).toBe("TH");+ });++ it("resizes columns without editing the document, and keeps widths while typing", async () => {+ const { table, handle, editor } = await renderEditor();+ const before = editor.getMarkdown();++ fireEvent.keyDown(handle, { key: "ArrowRight", shiftKey: true });+ await waitFor(() => expect(table).toHaveAttribute("data-column-widths"));+ expect(table.querySelectorAll("colgroup col")).toHaveLength(3);+ expect(editor.getMarkdown()).toBe(before);++ // Typing changes the table's text, and with it the key its widths are+ // stored under; the widths stay.+ let cellPos = -1;+ editor.state.doc.descendants((node, pos) => {+ if (cellPos < 0 && node.type.name === "paragraph" && node.textContent === "tracks it") cellPos = pos + 1;+ });+ act(() => {+ editor.chain().insertContentAt(cellPos, "now ").run();+ });+ expect(editor.getMarkdown()).toContain("now tracks it");+ expect(table).toHaveAttribute("data-column-widths");+ expect(Object.keys(JSON.parse(window.localStorage.getItem("multica:rich-table-widths") ?? "{}"))).toHaveLength(1);+ });++ it("copies the table's Markdown", async () => {+ await renderEditor();+ await userEvent.click(screen.getByRole("button", { name: "Copy as Markdown" }));+ expect(copyText).toHaveBeenCalledWith(expect.stringContaining("| GitHub"));+ expect(copyText).toHaveBeenCalledWith(expect.stringContaining("`code`"));+ });++ it("filters and exports mentions as they display", async () => {+ await renderEditor(+ [+ "| Owner | Issue |",+ "| --- | --- |",+ "| [@Alice](mention://member/u1) | [DEV-1](mention://issue/i1) |",+ "| [@Bob](mention://member/u2) | none |",+ ].join("\n"),+ "Owner",+ );+ await userEvent.click(screen.getByRole("button", { name: "Expand table" }));+ const dialog = await screen.findByRole("dialog");+ await userEvent.click(within(dialog).getByRole("button", { name: "Copy as CSV" }));+ expect(copyText).toHaveBeenCalledWith("Owner,Issue\n@Alice,DEV-1\n@Bob,none");++ await userEvent.type(within(dialog).getByRole("searchbox"), "Alice");+ expect(within(dialog).getAllByRole("row")).toHaveLength(2);+ });++ it("expands into the dialog with the cells rendered", async () => {+ await renderEditor();+ await userEvent.click(screen.getByRole("button", { name: "Expand table" }));+ const dialog = await screen.findByRole("dialog");+ expect(dialog.querySelector("code")?.textContent).toBe("code");+ expect(dialog).toHaveTextContent("harness switch");+ });+});diff --git a/packages/views/editor/extensions/table-view.tsx b/packages/views/editor/extensions/table-view.tsxnew file mode 100644index 0000000000..84f4f9f1cc--- /dev/null+++ b/packages/views/editor/extensions/table-view.tsx@@ -0,0 +1,83 @@+"use client";++import { useMemo } from "react";+import {+ getTextBetween,+ getTextSerializersFromSchema,+ type Editor,+ type TextSerializer,+} from "@tiptap/core";+import type { Node as ProseMirrorNode } from "@tiptap/pm/model";+import { NodeViewWrapper, useReactNodeView, type NodeViewProps } from "@tiptap/react";+import { RichContent } from "../../rich-content/rich-content";+import { RichTableFrame } from "../../rich-content/rich-table";+import type { RichTableModel } from "../../rich-content/rich-table-model";+import { BaseMentionExtension, mentionText } from "./mention-extension";++function serialize(editor: Editor, content: ProseMirrorNode[]): string {+ return (+ editor.markdown?.serialize({ type: "doc", content: content.map((node) => node.toJSON()) }).trim() ?? ""+ );+}++// Serialized only when the expanded view renders it, not on every keystroke.+function TableCellContent({ cell, editor }: { cell: ProseMirrorNode; editor: Editor }) {+ const markdown = useMemo(() => {+ const blocks: ProseMirrorNode[] = [];+ cell.forEach((block) => {+ blocks.push(block);+ });+ return serialize(editor, blocks);+ }, [cell, editor]);+ return <RichContent content={markdown} density="compact" />;+}++// The text sorting, filtering and CSV read. Atom nodes such as mentions have+// no text content, so they are written out the way they display.+function cellText(cell: ProseMirrorNode, textSerializers: Record<string, TextSerializer>): string {+ return getTextBetween(cell, { from: 0, to: cell.content.size }, { blockSeparator: " ", textSerializers }).trim();+}++export function tableModelFromNode(node: ProseMirrorNode, editor: Editor): RichTableModel {+ const grid: ProseMirrorNode[][] = [];+ node.forEach((row) => {+ const cells: ProseMirrorNode[] = [];+ row.forEach((cell) => {+ cells.push(cell);+ });+ grid.push(cells);+ });+ const [head = [], ...body] = grid;+ const serializers: Record<string, TextSerializer> = {+ ...getTextSerializersFromSchema(editor.schema),+ [BaseMentionExtension.name]: ({ node: mention }) => mentionText(mention.attrs),+ };+ const text = (cell: ProseMirrorNode) => cellText(cell, serializers);+ const render = (cell: ProseMirrorNode, index: number) => (+ <TableCellContent key={index} cell={cell} editor={editor} />+ );+ return {+ header: head.map(render),+ rows: body.map((row) => row.map(render)),+ headerText: head.map(text),+ rowText: body.map((row) => row.map(text)),+ };+}++/**+ * The editor's table, in the same frame as readonly tables. ProseMirror keeps+ * owning the rows: its `<tbody>` is handed to the frame's `<table>`.+ */+export function TableView({ node, editor }: NodeViewProps) {+ const { nodeViewContentRef } = useReactNodeView();+ const model = useMemo(() => tableModelFromNode(node, editor), [node, editor]);+ return (+ <NodeViewWrapper className="table-node">+ <RichTableFrame+ model={model}+ getMarkdown={() => serialize(editor, [node])}+ tableRef={nodeViewContentRef}+ />+ </NodeViewWrapper>+ );+}diff --git a/packages/views/editor/styles/prose.css b/packages/views/editor/styles/prose.cssindex 30582e19b8..a33861bf26 100644--- a/packages/views/editor/styles/prose.css+++ b/packages/views/editor/styles/prose.css@@ -339,8 +339,9 @@}/* Tiptap tables have no <thead>, so their header row is tbody's first row —- without this it draws a border-top right against the wrapper's own border. */-.rich-text-editor table > tbody:first-child > tr:first-child {+ without this it draws a border-top right against the wrapper's own border.+ The table frame renders a <colgroup> ahead of the editor's rows. */+.rich-text-editor :is(table > tbody:first-child, table > colgroup:first-child + tbody) > tr:first-child {border-top: 0;}@@ -352,7 +353,12 @@.rich-text-editor th,.rich-text-editor td {text-align: left;- padding: 0.625rem 1rem;+ vertical-align: top;+ padding: 0.5rem 0.75rem;+ /* Chinese text may break between any two characters, so a column of it+ reports a one-character minimum and gets squeezed to that whenever+ another column wants the space. */+ min-width: 6rem;font-size: var(--text-body);/* Match body-paragraph line-height. Tiptap wraps cell content in <p>(which carries 1.625); the readonly render keeps bare text in the cell,@@ -361,8 +367,120 @@line-height: 1.625;}+/* The header label sets its column's minimum width rather than wrapping. */.rich-text-editor th {- font-weight: 600;+ font-size: var(--text-label);+ font-weight: 500;+ color: var(--muted-foreground);+ white-space: nowrap;+}++/* Mention chips truncate inside a cell instead of widening its column. Column+ widths start from each cell's min-content, where the chip's percentage+ max-width does not apply, so its whole title became the column's minimum+ and squeezed every other column. As a grid whose title track may shrink to+ zero, the chip asks only for its icon and identifier. */+.rich-text-editor :is(td, th) span.issue-mention:has(> :nth-child(3)) {+ display: inline-grid;+ grid-template-columns: auto auto minmax(0, max-content);+ max-width: 18rem;+}++.rich-text-editor :is(td, th) span.project-chip {+ display: inline-grid;+ grid-template-columns: auto minmax(0, max-content);+ max-width: 18rem;+}++/* Table frame (RichTableFrame): the outer box carries the margin, and its+ toolbar row takes the place of most of the top margin. The wrapper anchors+ the resize handles, so they scroll with the columns. */+.rich-text-editor .rich-table {+ margin: 0.25rem 0 1rem;+}++.rich-text-editor .rich-table .tableWrapper {+ position: relative;+ margin: 0;+}++/* Explicit column widths (a viewer's resize, or the overflow fit): fixed+ layout at those widths. */+.rich-text-editor table[data-column-widths] {+ table-layout: fixed;+ min-width: 0;+}++.rich-text-editor table[data-column-widths] colgroup {+ display: table-column-group;+}++.rich-text-editor table[data-column-widths] th {+ white-space: normal;+}++/* Resized by the viewer: the box hugs the table so the border and toolbar+ follow a table narrower than the column. */+.rich-text-editor .rich-table[data-resized] {+ width: fit-content;+ max-width: 100%;+}++/* Placed over a column edge by RichTableFrame, which sets left, top and+ height from the header row. */+.rich-text-editor .rich-table-resize-handle {+ position: absolute;+ z-index: 10;+ width: 8px;+ cursor: col-resize;+ touch-action: none;+ user-select: none;+ outline: none;+}++.rich-text-editor .rich-table-resize-handle::after {+ content: "";+ position: absolute;+ inset-block: 0;+ left: 3px;+ width: 2px;+ background: transparent;+ transition: background-color 100ms;+}++.rich-text-editor .rich-table-resize-handle[data-edge="end"]::after {+ left: auto;+ right: 0;+}++.rich-text-editor .rich-table-resize-handle:hover::after,+.rich-text-editor .rich-table-resize-handle:focus-visible::after {+ background: color-mix(in srgb, var(--brand) 60%, transparent);+}++.rich-text-editor .rich-table-resize-handle[data-resizing]::after {+ background: var(--brand);+ transition: none;+}++.rich-text-editor .rich-table-resize-handle [data-width-badge] {+ display: none;+}++.rich-text-editor .rich-table-resize-handle[data-resizing] [data-width-badge] {+ display: block;+ position: absolute;+ top: 0.375rem;+ right: 0.625rem;+ padding: 0.125rem 0.375rem;+ border-radius: var(--radius-sm);+ background: var(--primary);+ color: var(--primary-foreground);+ font-size: var(--text-caption);+ font-weight: 500;+ line-height: 1rem;+ font-variant-numeric: tabular-nums;+ white-space: nowrap;}/* Remove paragraph margin inside table cells */diff --git a/packages/views/editor/styles/shell.css b/packages/views/editor/styles/shell.cssindex 7eed909540..3ed074e8da 100644--- a/packages/views/editor/styles/shell.css+++ b/packages/views/editor/styles/shell.css@@ -40,6 +40,16 @@display: block !important;}+/* The table NodeView (TableView) is a block, and Tiptap marks ProseMirror's+ <tbody> inside it as a wrapper too; it keeps its table display. */+.rich-text-editor [data-node-view-wrapper].table-node {+ display: block;+}++.rich-text-editor tbody[data-node-view-wrapper] {+ display: table-row-group;+}+/* Bubble menu — floating toolbar pill */.bubble-menu {display: flex;diff --git a/packages/views/editor/table-preview.tsx b/packages/views/editor/table-preview.tsxindex 252df94b8a..b7ed8d929b 100644--- a/packages/views/editor/table-preview.tsx+++ b/packages/views/editor/table-preview.tsx@@ -54,7 +54,7 @@ const SCROLLBAR_SLACK = 16;// Rendered width of `value` at `fontPx`, in em-fractions per character class// of a proportional UI face: figures and capitals run wide (and figures are// tabular), lowercase and punctuation narrower, CJK glyphs a full em.-function textWidth(value: string, fontPx: number): number {+export function textWidth(value: string, fontPx: number): number {let ems = 0;for (const char of value) {if ((char.codePointAt(0) ?? 0) > 0x2e80) ems += 1;@@ -230,7 +230,7 @@ export function TablePreview({ text, delimiter }: TablePreviewProps) {);}-function SortHeader({+export function SortHeader({title,numeric,sorted,diff --git a/packages/views/locales/en/editor.json b/packages/views/locales/en/editor.jsonindex b6c0792b3b..2fe807d2e4 100644--- a/packages/views/locales/en/editor.json+++ b/packages/views/locales/en/editor.json@@ -168,5 +168,18 @@"export_png": "Download PNG","export_svg": "Download SVG","export_source": "Download .mmd"+ },+ "table": {+ "reset_widths": "Reset widths",+ "expand": "Expand table",+ "copy_markdown": "Copy as Markdown",+ "copy_csv": "Copy as CSV",+ "copied": "Copied",+ "resize_column": "Resize {{name}} column",+ "expanded_title": "Table",+ "filter_placeholder": "Filter rows",+ "clear_filter": "Clear filter",+ "no_matches": "No matching rows",+ "close": "Close"}}diff --git a/packages/views/locales/fr/editor.json b/packages/views/locales/fr/editor.jsonindex 35dbc80375..29e13b2feb 100644--- a/packages/views/locales/fr/editor.json+++ b/packages/views/locales/fr/editor.json@@ -168,5 +168,18 @@"export_png": "Télécharger en PNG","export_svg": "Télécharger en SVG","export_source": "Télécharger le .mmd"+ },+ "table": {+ "reset_widths": "Réinitialiser les largeurs",+ "expand": "Agrandir le tableau",+ "copy_markdown": "Copier en Markdown",+ "copy_csv": "Copier en CSV",+ "copied": "Copié",+ "resize_column": "Redimensionner la colonne {{name}}",+ "expanded_title": "Tableau",+ "filter_placeholder": "Filtrer les lignes",+ "clear_filter": "Effacer le filtre",+ "no_matches": "Aucune ligne correspondante",+ "close": "Fermer"}}diff --git a/packages/views/locales/ja/editor.json b/packages/views/locales/ja/editor.jsonindex 3b7ac510f0..ac3f5aa7e2 100644--- a/packages/views/locales/ja/editor.json+++ b/packages/views/locales/ja/editor.json@@ -164,5 +164,18 @@"commands": {"note": "メモを追加 — エージェントをトリガーしません"}+ },+ "table": {+ "reset_widths": "列幅をリセット",+ "expand": "表を展開",+ "copy_markdown": "Markdown としてコピー",+ "copy_csv": "CSV としてコピー",+ "copied": "コピーしました",+ "resize_column": "「{{name}}」列の幅を変更",+ "expanded_title": "表",+ "filter_placeholder": "行を絞り込む",+ "clear_filter": "絞り込みを解除",+ "no_matches": "一致する行がありません",+ "close": "閉じる"}}diff --git a/packages/views/locales/ko/editor.json b/packages/views/locales/ko/editor.jsonindex e33ece2917..e836966973 100644--- a/packages/views/locales/ko/editor.json+++ b/packages/views/locales/ko/editor.json@@ -164,5 +164,18 @@"commands": {"note": "메모 추가 — 에이전트를 트리거하지 않음"}+ },+ "table": {+ "reset_widths": "열 너비 초기화",+ "expand": "표 펼치기",+ "copy_markdown": "Markdown으로 복사",+ "copy_csv": "CSV로 복사",+ "copied": "복사됨",+ "resize_column": "'{{name}}' 열 너비 조정",+ "expanded_title": "표",+ "filter_placeholder": "행 필터",+ "clear_filter": "필터 지우기",+ "no_matches": "일치하는 행이 없습니다",+ "close": "닫기"}}diff --git a/packages/views/locales/zh-Hans/editor.json b/packages/views/locales/zh-Hans/editor.jsonindex 2953271426..19c91d6e7f 100644--- a/packages/views/locales/zh-Hans/editor.json+++ b/packages/views/locales/zh-Hans/editor.json@@ -164,5 +164,18 @@"export_png": "下载 PNG","export_svg": "下载 SVG","export_source": "下载 .mmd"+ },+ "table": {+ "reset_widths": "重置列宽",+ "expand": "展开表格",+ "copy_markdown": "复制为 Markdown",+ "copy_csv": "复制为 CSV",+ "copied": "已复制",+ "resize_column": "调整“{{name}}”列宽",+ "expanded_title": "表格",+ "filter_placeholder": "筛选行",+ "clear_filter": "清除筛选",+ "no_matches": "没有匹配的行",+ "close": "关闭"}}diff --git a/packages/views/package.json b/packages/views/package.jsonindex 633af494f3..f46d5a87b0 100644--- a/packages/views/package.json+++ b/packages/views/package.json@@ -100,7 +100,11 @@"katex": "catalog:","lowlight": "^3.3.0","mdast-util-from-markdown": "^2.0.3",+ "mdast-util-gfm-table": "^2.0.0",+ "mdast-util-math": "^3.0.0","mermaid": "catalog:",+ "micromark-extension-gfm-table": "^2.1.1",+ "micromark-extension-math": "^3.1.0","motion": "^12.38.0","pinyin-pro": "3.26.0","react-easy-crop": "^6.2.0",diff --git a/packages/views/rich-content/rich-content.tsx b/packages/views/rich-content/rich-content.tsxindex 5bcde7aa03..54369bf480 100644--- a/packages/views/rich-content/rich-content.tsx+++ b/packages/views/rich-content/rich-content.tsx@@ -80,6 +80,8 @@ import {isRichFenceLanguage,shouldUpgradeFence,} from "./rich-code-block";+import { RichTable, RichTableSourceContext } from "./rich-table";+import { getTextContent } from "./rich-table-model";import "katex/dist/katex.min.css";import "../editor/styles/index.css";import "./rich-content.css";@@ -354,16 +356,6 @@ function RichLink({ href, children }: { href?: string; children?: ReactNode }) {// Fenced code-function getTextContent(node: ReactNode): string {- if (node == null || typeof node === "boolean") return "";- if (typeof node === "string" || typeof node === "number") return String(node);- if (Array.isArray(node)) return node.map(getTextContent).join("");- if (isValidElement<{ children?: ReactNode }>(node)) {- return getTextContent(node.props.children);- }- return "";-}-// Props react-markdown actually passes to a component override: the intrinsic// element's own props plus the source hast node (`ExtraProps`). Deriving them// keeps the renderers checked against react-markdown's real contract instead of@@ -516,12 +508,9 @@ const COMPONENTS: Partial<Components> = {return <div {...props}>{children}</div>;},- // Tables — wrap in tableWrapper div for border/radius/scroll (matches Tiptap)- table: ({ children }) => (- <div className="tableWrapper">- <table>{children}</table>- </div>- ),+ // Tables keep Tiptap's tableWrapper (border/radius/scroll) and add column+ // resizing, an expanded view and copy.+ table: RichTable,code: RichCode,pre: RichPre,@@ -595,6 +584,7 @@ export const RichContent = memo(function RichContent({// with the hast node positions the `code`/`pre` renderers observe. Computing// it from the raw pre-preprocess text would mis-match every rewritten node.const closedFences = useMemo(() => computeClosedFences(processed), [processed]);+ const tableSource = useMemo(() => ({ source: content, rendered: processed }), [content, processed]);const wrapperRef = useRef<HTMLDivElement>(null);const hover = useLinkHover(wrapperRef);@@ -609,17 +599,19 @@ export const RichContent = memo(function RichContent({const markdown = useMemo(() => (<ClosedFenceContext.Provider value={closedFences}>- <ReactMarkdown- remarkPlugins={REMARK_PLUGINS}- rehypePlugins={REHYPE_PLUGINS}- urlTransform={markdownUrlTransform}- components={COMPONENTS}- >- {processed}- </ReactMarkdown>+ <RichTableSourceContext.Provider value={tableSource}>+ <ReactMarkdown+ remarkPlugins={REMARK_PLUGINS}+ rehypePlugins={REHYPE_PLUGINS}+ urlTransform={markdownUrlTransform}+ components={COMPONENTS}+ >+ {processed}+ </ReactMarkdown>+ </RichTableSourceContext.Provider></ClosedFenceContext.Provider>),- [processed, closedFences],+ [processed, closedFences, tableSource],);return (diff --git a/packages/views/rich-content/rich-table-dialog.tsx b/packages/views/rich-content/rich-table-dialog.tsxnew file mode 100644index 0000000000..bcf5f12d75--- /dev/null+++ b/packages/views/rich-content/rich-table-dialog.tsx@@ -0,0 +1,232 @@+"use client";++/**+ * A Markdown table at dialog size. Rendered by the shared DataTable — the same+ * shell as the CSV attachment preview — so the header stays pinned, columns+ * resize by dragging and sort by clicking their header, and the row-number+ * column keeps each row's position in the source. Cells are the rendered+ * Markdown cells, so links, mentions and inline code behave as they do inline.+ */++import { useMemo, useState, type ReactNode } from "react";+import {+ getCoreRowModel,+ getFilteredRowModel,+ getSortedRowModel,+ useReactTable,+ type ColumnDef,+ type FilterFn,+ type Row,+ type SortingState,+} from "@tanstack/react-table";+import { Check, Copy, Search, X } from "lucide-react";+import { Button } from "@multica/ui/components/ui/button";+import { DataTable } from "@multica/ui/components/ui/data-table";+import {+ Dialog,+ DialogClose,+ DialogContent,+ DialogTitle,+} from "@multica/ui/components/ui/dialog";+import { Input } from "@multica/ui/components/ui/input";+import { copyText } from "@multica/ui/lib/clipboard";+import { cn } from "@multica/ui/lib/utils";+import { useT } from "../i18n";+import { SortHeader, compareCells, textWidth } from "../editor/table-preview";+import { tableToCsv, type RichTableModel } from "./rich-table-model";++const ROW_NUMBER_COLUMN = "__row";+const BODY_FONT_PX = 14;+const HEADER_FONT_PX = 13;+const CELL_PADDING = 32;+const SORT_ICON_ROOM = 18;+const MIN_COLUMN_WIDTH = 96;+const MAX_COLUMN_WIDTH = 480;++interface DialogRow {+ index: number;+ cells: ReactNode[];+ text: string[];+}++const matchesFilter: FilterFn<DialogRow> = (row, _columnId, filter: string) => {+ const needle = filter.trim().toLocaleLowerCase();+ return !needle || row.original.text.some((text) => text.toLocaleLowerCase().includes(needle));+};++function sortByCell(rowA: Row<DialogRow>, rowB: Row<DialogRow>, columnId: string) {+ return compareCells(rowA.getValue<string>(columnId), rowB.getValue<string>(columnId));+}++function isNumeric(values: string[]): boolean {+ const filled = values.filter((value) => value !== "");+ return filled.length > 0 && filled.every((value) => Number.isFinite(Number(value)));+}++function useCopyFeedback() {+ const [copied, setCopied] = useState<string | null>(null);+ const copy = async (id: string, text: string) => {+ if (await copyText(text)) {+ setCopied(id);+ setTimeout(() => setCopied((current) => (current === id ? null : current)), 2000);+ }+ };+ return { copied, copy };+}++interface RichTableDialogProps {+ model: RichTableModel;+ open: boolean;+ onOpenChange: (open: boolean) => void;+ getMarkdown: () => string;+}++export function RichTableDialog({ model, open, onOpenChange, getMarkdown }: RichTableDialogProps) {+ const { t } = useT("editor");+ const [sorting, setSorting] = useState<SortingState>([]);+ const [filter, setFilter] = useState("");+ const { copied, copy } = useCopyFeedback();++ const data = useMemo<DialogRow[]>(+ () => model.rows.map((cells, index) => ({ index, cells, text: model.rowText[index] ?? [] })),+ [model],+ );++ const columns = useMemo<ColumnDef<DialogRow>[]>(() => {+ const digits = String(model.rows.length).length;+ const rowNumber: ColumnDef<DialogRow> = {+ id: ROW_NUMBER_COLUMN,+ header: "#",+ cell: ({ row }) => (+ <span className="block text-right tabular-nums text-muted-foreground">+ {row.original.index + 1}+ </span>+ ),+ size: Math.max(48, Math.ceil(digits * 0.64 * BODY_FONT_PX) + CELL_PADDING),+ enableSorting: false,+ enableResizing: false,+ enableGlobalFilter: false,+ };+ return [+ rowNumber,+ ...model.headerText.map<ColumnDef<DialogRow>>((title, index) => {+ const values = model.rowText.map((row) => row[index] ?? "");+ const numeric = isNumeric(values);+ const widest = Math.max(+ textWidth(title, HEADER_FONT_PX) + SORT_ICON_ROOM,+ ...values.slice(0, 200).map((value) => textWidth(value, BODY_FONT_PX)),+ );+ return {+ id: `c${index}`,+ accessorFn: (row) => (row.text[index] ? row.text[index] : undefined),+ header: ({ column }) => (+ <SortHeader+ title={title}+ numeric={numeric}+ sorted={column.getIsSorted()}+ onToggle={column.getToggleSortingHandler()}+ />+ ),+ cell: ({ row }) => (+ <div className={cn("rich-text-editor readonly whitespace-normal", numeric && "text-right tabular-nums")}>+ {row.original.cells[index]}+ </div>+ ),+ size: Math.min(MAX_COLUMN_WIDTH, Math.max(MIN_COLUMN_WIDTH, Math.ceil(widest + CELL_PADDING))),+ minSize: 64,+ sortingFn: sortByCell,+ sortUndefined: "last",+ };+ }),+ ];+ }, [model]);++ const table = useReactTable({+ data,+ columns,+ state: { sorting, globalFilter: filter },+ onSortingChange: setSorting,+ onGlobalFilterChange: setFilter,+ globalFilterFn: matchesFilter,+ getColumnCanGlobalFilter: (column) => column.id !== ROW_NUMBER_COLUMN,+ getCoreRowModel: getCoreRowModel(),+ getSortedRowModel: getSortedRowModel(),+ getFilteredRowModel: getFilteredRowModel(),+ initialState: { columnPinning: { left: [ROW_NUMBER_COLUMN] } },+ columnResizeMode: "onChange",+ });++ const shownRows = table.getRowModel().rows.length;++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent+ showCloseButton={false}+ className="flex h-[min(85dvh,56rem)] w-[min(72rem,calc(100vw-4rem))] max-w-none flex-col gap-0 overflow-hidden p-0 sm:max-w-none"+ >+ <div className="flex shrink-0 items-center gap-2 border-b border-border py-2 pr-2 pl-4">+ <DialogTitle className="mr-auto text-body font-medium">+ {t(($) => $.table.expanded_title)}+ </DialogTitle>+ <div className="relative w-56 shrink-0">+ <Search+ aria-hidden+ className="pointer-events-none absolute top-1/2 left-2 size-3.5 -translate-y-1/2 text-muted-foreground"+ />+ <Input+ type="text"+ role="searchbox"+ inputMode="search"+ value={filter}+ onChange={(event) => setFilter(event.target.value)}+ aria-label={t(($) => $.table.filter_placeholder)}+ placeholder={t(($) => $.table.filter_placeholder)}+ className="h-7 pr-7 pl-7 text-caption"+ />+ {filter && (+ <Button+ type="button"+ variant="ghost"+ size="icon-xs"+ aria-label={t(($) => $.table.clear_filter)}+ onClick={() => setFilter("")}+ className="absolute top-0.5 right-0.5 text-muted-foreground"+ >+ <X className="size-3" />+ </Button>+ )}+ </div>+ <Button type="button" variant="outline" size="sm" onClick={() => copy("markdown", getMarkdown())}>+ {copied === "markdown" ? <Check /> : <Copy />}+ {t(($) => $.table.copy_markdown)}+ </Button>+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={() => copy("csv", tableToCsv(model.headerText, model.rowText))}+ >+ {copied === "csv" ? <Check /> : <Copy />}+ {t(($) => $.table.copy_csv)}+ </Button>+ <DialogClose+ render={<Button variant="ghost" size="icon-sm" aria-label={t(($) => $.table.close)} />}+ >+ <X />+ </DialogClose>+ </div>+ <DataTable+ table={table}+ emptyMessage={t(($) => $.table.no_matches)}+ className="[&_td]:align-top"+ />+ <p className="shrink-0 border-t border-border px-4 py-1.5 text-caption tabular-nums text-muted-foreground">+ {filter && shownRows !== model.rows.length ? `${shownRows} / ` : null}+ {t(($) => $.attachment.table_rows, { count: model.rows.length })}+ {" · "}+ {t(($) => $.attachment.table_columns, { count: model.headerText.length })}+ </p>+ </DialogContent>+ </Dialog>+ );+}diff --git a/packages/views/rich-content/rich-table-model.test.ts b/packages/views/rich-content/rich-table-model.test.tsnew file mode 100644index 0000000000..ed540ea6b9--- /dev/null+++ b/packages/views/rich-content/rich-table-model.test.ts@@ -0,0 +1,127 @@+import { createElement } from "react";+import { afterEach, describe, expect, it } from "vitest";+import {+ columnWidthKey,+ readColumnWidths,+ readTableModel,+ tableMarkdownFromSource,+ tableToCsv,+ writeColumnWidths,+} from "./rich-table-model";++const h = createElement;++describe("readTableModel", () => {+ it("reads header and body cells from react-markdown's table children", () => {+ const children = [+ h("thead", { key: "h" }, "\n", h("tr", null, h("th", null, "Name"), h("th", null, "Note"))),+ "\n",+ h(+ "tbody",+ { key: "b" },+ h("tr", null, h("td", null, "a"), h("td", null, "see ", h("code", null, "cursor-agent"))),+ h("tr", null, h("td", null, "b"), h("td", null)),+ ),+ ];+ const model = readTableModel(children);+ expect(model.headerText).toEqual(["Name", "Note"]);+ expect(model.rowText).toEqual([+ ["a", "see cursor-agent"],+ ["b", ""],+ ]);+ expect(model.rows).toHaveLength(2);+ });+});++describe("tableMarkdownFromSource", () => {+ const source = [+ "intro MUL-1",+ "",+ "| Issue | Link | Note |",+ "| --- | --- | --- |",+ "| MUL-12 | https://example.com | ==hot== |",+ "| [https://x.com](https://x.com) | `<mark>hello</mark>` | `[a](b)` |",+ ].join("\n");+ const rendered = [+ "intro [MUL-1](mention://issue/MUL-1)",+ "",+ "| Issue | Link | Note |",+ "| --- | --- | --- |",+ "| [MUL-12](mention://issue/MUL-12) | [https://example.com](https://example.com) | <mark>hot</mark> |",+ "| [https://x.com](https://x.com) | `<mark>hello</mark>` | `[a](b)` |",+ ].join("\n");++ it("copies the table from the source, not the preprocessed copy", () => {+ const start = rendered.indexOf("| Issue");+ expect(tableMarkdownFromSource(source, rendered, start, rendered.length)).toBe(+ source.slice(source.indexOf("| Issue")),+ );+ });++ it("finds the table by its place among the tables", () => {+ const second = "| A | B |\n| - | - |\n| 1 | 2 |";+ const withTwo = (text: string) => `${text}\n\n${second}`;+ const start = withTwo(rendered).lastIndexOf("| A");+ expect(tableMarkdownFromSource(withTwo(source), withTwo(rendered), start, withTwo(rendered).length)).toBe(second);+ });++ it("drops a blockquote's or list item's markers so the copy is a table", () => {+ const quoted = "> | A | B |\n> | - | - |\n> | 1 | 2 |";+ expect(tableMarkdownFromSource(quoted, quoted, 2, quoted.length)).toBe("| A | B |\n| - | - |\n| 1 | 2 |");+ const listed = "- item\n\n | A | B |\n | - | - |\n | 1 | 2 |";+ const start = listed.indexOf("| A");+ expect(tableMarkdownFromSource(listed, listed, start, listed.length)).toBe("| A | B |\n| - | - |\n| 1 | 2 |");+ });++ it("returns nothing without a source position", () => {+ expect(tableMarkdownFromSource("| a |", "| a |", undefined, 5)).toBe("");+ });+});++describe("tableToCsv", () => {+ it("quotes fields that contain a separator, quote or newline", () => {+ expect(tableToCsv(["a", "b"], [["1,2", 'say "hi"'], ["x\ny", "plain"]])).toBe(+ 'a,b\n"1,2","say ""hi"""\n"x\ny",plain',+ );+ });+});++describe("column width storage", () => {+ afterEach(() => window.localStorage.clear());++ const model = { headerText: ["a", "b"], rowText: [["1", "2"]] };++ it("round-trips widths and forgets them on reset", () => {+ const key = columnWidthKey(model);+ writeColumnWidths(key, [120, 240]);+ expect(readColumnWidths(key, 2)).toEqual([120, 240]);+ writeColumnWidths(key, null);+ expect(readColumnWidths(key, 2)).toBeNull();+ });++ it("ignores widths stored for a different column count", () => {+ const key = columnWidthKey(model);+ writeColumnWidths(key, [120, 240]);+ expect(readColumnWidths(key, 3)).toBeNull();+ });++ it("keys a table by its content", () => {+ expect(columnWidthKey(model)).toBe(columnWidthKey({ ...model }));+ expect(columnWidthKey(model)).not.toBe(+ columnWidthKey({ headerText: ["a", "b"], rowText: [["1", "3"]] }),+ );+ });++ it("keeps only the most recently used tables", () => {+ for (let i = 0; i < 205; i++) writeColumnWidths(`k${i}`, [100]);+ const stored = JSON.parse(window.localStorage.getItem("multica:rich-table-widths") ?? "{}");+ expect(Object.keys(stored)).toHaveLength(200);+ });++ it("survives a corrupt entry", () => {+ window.localStorage.setItem("multica:rich-table-widths", "{not json");+ expect(readColumnWidths("k", 1)).toBeNull();+ writeColumnWidths("k", [90]);+ expect(readColumnWidths("k", 1)).toEqual([90]);+ });+});diff --git a/packages/views/rich-content/rich-table-model.ts b/packages/views/rich-content/rich-table-model.tsnew file mode 100644index 0000000000..490dfffbc1--- /dev/null+++ b/packages/views/rich-content/rich-table-model.ts@@ -0,0 +1,214 @@+import { Children, isValidElement, type ReactElement, type ReactNode } from "react";+import type { Nodes as MdastNodes } from "mdast";+import { fromMarkdown } from "mdast-util-from-markdown";+import { gfmTableFromMarkdown } from "mdast-util-gfm-table";+import { mathFromMarkdown } from "mdast-util-math";+import { gfmTable } from "micromark-extension-gfm-table";+import { math } from "micromark-extension-math";++type ElementWithChildren = ReactElement<{ children?: ReactNode }>;++export function getTextContent(node: ReactNode): string {+ if (node == null || typeof node === "boolean") return "";+ if (typeof node === "string" || typeof node === "number") return String(node);+ if (Array.isArray(node)) return node.map(getTextContent).join("");+ if (isValidElement<{ children?: ReactNode }>(node)) {+ return getTextContent(node.props.children);+ }+ return "";+}++function childElements(node: ReactNode): ElementWithChildren[] {+ return Children.toArray(node).filter(+ (child): child is ElementWithChildren => isValidElement(child),+ );+}++export interface RichTableModel {+ header: ReactNode[];+ rows: ReactNode[][];+ /** Plain text of every cell, for sorting, filtering, CSV and the width key. */+ headerText: string[];+ rowText: string[][];+}++/**+ * Reads the cells out of the elements react-markdown hands a `table` override:+ * `thead` and `tbody`, each holding `tr` elements. The cells stay the rendered+ * elements, so links, mentions and inline code keep their own renderers+ * wherever the cells are shown again.+ */+export function readTableModel(children: ReactNode): RichTableModel {+ let header: ReactNode[] = [];+ const rows: ReactNode[][] = [];+ for (const section of childElements(children)) {+ for (const row of childElements(section.props.children)) {+ const cells = childElements(row.props.children).map(+ (cell) => cell.props.children,+ );+ if (section.type === "thead") header = cells;+ else rows.push(cells);+ }+ }+ return {+ header,+ rows,+ headerText: header.map((cell) => getTextContent(cell).trim()),+ rowText: rows.map((row) => row.map((cell) => getTextContent(cell).trim())),+ };+}++type Span = [start: number, end: number];++function collectTables(node: MdastNodes, out: Span[]): void {+ if (node.type === "table") {+ const { start, end } = node.position ?? {};+ if (start?.offset != null && end?.offset != null) out.push([start.offset, end.offset]);+ return;+ }+ if ("children" in node) for (const child of node.children) collectTables(child, out);+}++// The block syntax RichContent's own parse sees (remark-gfm, remark-math), so+// both find the same tables: a `|` line inside `$$` is not one.+function tableSpans(markdown: string): Span[] {+ const tree = fromMarkdown(markdown, {+ extensions: [gfmTable(), math()],+ mdastExtensions: [gfmTableFromMarkdown(), mathFromMarkdown()],+ });+ const spans: Span[] = [];+ collectTables(tree, spans);+ return spans;+}++const QUOTE_MARKER = /^ {0,3}> ?/;++// A table inside a blockquote or list item starts after the container's+// markers, and every later line repeats them; without them it is a table again.+function standaloneTable(source: string, [start, end]: Span): string {+ const lineStart = source.lastIndexOf("\n", start - 1) + 1;+ let prefix = source.slice(lineStart, start);+ let quoteDepth = 0;+ while (QUOTE_MARKER.test(prefix)) {+ prefix = prefix.replace(QUOTE_MARKER, "");+ quoteDepth++;+ }+ const indent = new RegExp(`^ {0,${prefix.length}}`);+ const [first = "", ...rest] = source.slice(start, end).split("\n");+ return [+ first,+ ...rest.map((line) => {+ let unquoted = line;+ for (let i = 0; i < quoteDepth; i++) unquoted = unquoted.replace(QUOTE_MARKER, "");+ return unquoted.replace(indent, "");+ }),+ ].join("\n");+}++/**+ * The table's Markdown as the author wrote it. RichContent renders a+ * preprocessed copy of the content (issue identifiers and bare URLs become+ * links, `==text==` becomes `<mark>`), and the rendered table's position+ * indexes into that copy. Preprocessing never adds or removes a table, so the+ * table at the same place among the copy's tables is this one in the source.+ */+export function tableMarkdownFromSource(+ source: string,+ rendered: string,+ start: number | undefined,+ end: number | undefined,+): string {+ if (start == null || end == null || end <= start) return "";+ const renderedSpans = tableSpans(rendered);+ const index = renderedSpans.findIndex(([spanStart]) => spanStart === start);+ const sourceSpans = source === rendered ? renderedSpans : tableSpans(source);+ const span = index >= 0 && sourceSpans.length === renderedSpans.length ? sourceSpans[index] : undefined;+ return span ? standaloneTable(source, span) : standaloneTable(rendered, [start, end]);+}++function csvField(value: string): string {+ return /[",\n\r]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value;+}++export function tableToCsv(header: string[], rows: string[][]): string {+ return [header, ...rows].map((row) => row.map(csvField).join(",")).join("\n");+}++// Column widths a viewer chose by dragging. They belong to this device, not to+// the content: an agent's comment can be resized by someone who cannot edit it.+// A table is identified by its own text, so the widths follow it into every+// place it renders and lapse once its content changes.+const WIDTHS_STORAGE_KEY = "multica:rich-table-widths";+const MAX_STORED_TABLES = 200;++interface StoredWidths {+ widths: number[];+ usedAt: number;+}++function getStorage(): Storage | null {+ if (typeof window === "undefined") return null;+ try {+ return window.localStorage;+ } catch {+ return null;+ }+}++function readStore(storage: Storage): Record<string, StoredWidths> {+ try {+ const parsed: unknown = JSON.parse(storage.getItem(WIDTHS_STORAGE_KEY) ?? "{}");+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {+ return parsed as Record<string, StoredWidths>;+ }+ } catch {+ // A corrupt entry is replaced on the next write.+ }+ return {};+}++function isWidthList(value: unknown, columnCount: number): value is number[] {+ return (+ Array.isArray(value) &&+ value.length === columnCount &&+ value.every((width) => typeof width === "number" && Number.isFinite(width) && width > 0)+ );+}++// FNV-1a: short, stable keys; a collision only shares one table's widths.+function hash(text: string): string {+ let h = 0x811c9dc5;+ for (let i = 0; i < text.length; i++) {+ h ^= text.charCodeAt(i);+ h = Math.imul(h, 0x01000193);+ }+ return (h >>> 0).toString(36);+}++export function columnWidthKey(model: Pick<RichTableModel, "headerText" | "rowText">): string {+ const text = JSON.stringify([model.headerText, model.rowText]);+ return `${model.headerText.length}:${text.length}:${hash(text)}`;+}++export function readColumnWidths(key: string, columnCount: number): number[] | null {+ const storage = getStorage();+ if (!storage || columnCount === 0) return null;+ const widths = readStore(storage)[key]?.widths;+ return isWidthList(widths, columnCount) ? widths : null;+}++export function writeColumnWidths(key: string, widths: number[] | null): void {+ const storage = getStorage();+ if (!storage) return;+ const store = readStore(storage);+ if (widths) store[key] = { widths, usedAt: Date.now() };+ else delete store[key];+ const kept = Object.entries(store)+ .sort(([, a], [, b]) => (b.usedAt ?? 0) - (a.usedAt ?? 0))+ .slice(0, MAX_STORED_TABLES);+ try {+ storage.setItem(WIDTHS_STORAGE_KEY, JSON.stringify(Object.fromEntries(kept)));+ } catch {+ // Quota exceeded or storage disabled: the widths last for this view only.+ }+}diff --git a/packages/views/rich-content/rich-table.test.tsx b/packages/views/rich-content/rich-table.test.tsxnew file mode 100644index 0000000000..7a5830c05f--- /dev/null+++ b/packages/views/rich-content/rich-table.test.tsx@@ -0,0 +1,190 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";++const copyText = vi.hoisted(() => vi.fn(async () => true));+vi.mock("@multica/ui/lib/clipboard", () => ({ copyText }));++vi.mock("../issues/hooks", () => ({+ useResolveIssueIdentifier: () => null,+}));++vi.mock("../i18n", async () => {+ const editor: Record<string, Record<string, unknown>> = (await import("../locales/en/editor.json")).default;+ // Records the selected key path so plural keys resolve the way i18next does.+ const t = (select: (bundle: unknown) => unknown, values: Record<string, unknown> = {}) => {+ const path: string[] = [];+ const recorder: unknown = new Proxy({}, { get: (_, key: string) => (path.push(key), recorder) });+ select(recorder);+ const [section = "", key = ""] = path;+ const strings = editor[section] ?? {};+ const plural = values.count === 1 ? `${key}_one` : `${key}_other`;+ const template = String(strings[key] ?? strings[plural] ?? "");+ return template.replace(/\{\{(\w+)\}\}/g, (_, name: string) => String(values[name] ?? ""));+ };+ return { useT: () => ({ t }), useTimeAgo: () => "just now" };+});++vi.mock("@multica/core/api", () => ({+ api: { getAttachmentTextContent: vi.fn() },+ PreviewTooLargeError: class extends Error {},+ PreviewUnsupportedError: class extends Error {},+}));++vi.mock("@multica/core/paths", () => ({+ useWorkspacePaths: () => ({ issueDetail: (id: string) => `/acme/issues/${id}` }),+ useWorkspaceSlug: () => "acme",+}));++vi.mock("../editor/link-hover-card", () => ({+ useLinkHover: () => ({}),+ LinkHoverCard: () => null,+}));++import { RichContent } from "./rich-content";++const TABLE = [+ "Intro paragraph.",+ "",+ "| GitHub | Relation | Count |",+ "| --- | --- | --- |",+ "| #7738 harness switch | MUL-12 tracks it | 10 |",+ "| #4753 agent registry | see ==hot== | 9 |",+ "| #9250 PATH key | none | 100 |",+].join("\n");++function renderTable() {+ const view = render(<RichContent content={TABLE} />);+ const table = view.container.querySelector("table");+ if (!table) throw new Error("table not rendered");+ return { ...view, table };+}++afterEach(() => {+ window.localStorage.clear();+ copyText.mockClear();+});++describe("RichTable", () => {+ it("keeps the browser's layout until a column is resized", () => {+ const { table } = renderTable();+ expect(table.closest(".tableWrapper")).not.toBeNull();+ expect(table).not.toHaveAttribute("data-column-widths");+ expect(table.querySelectorAll("colgroup col")).toHaveLength(0);+ expect(screen.queryByRole("button", { name: "Reset widths" })).toBeNull();+ });++ it("gives an overflowing table capped content widths without saving them", () => {+ const natural = { "max-content": [500, 260, 90], "min-content": [200, 330, 64] } as const;+ const rect = vi+ .spyOn(HTMLTableCellElement.prototype, "getBoundingClientRect")+ .mockImplementation(function (this: HTMLTableCellElement) {+ const widths = natural[this.closest("table")?.style.width as keyof typeof natural];+ return { width: widths?.[this.cellIndex] ?? 0 } as DOMRect;+ });+ const clientWidth = vi.spyOn(HTMLElement.prototype, "clientWidth", "get").mockReturnValue(560);+ try {+ const { table } = renderTable();+ const cols = Array.from(table.querySelectorAll<HTMLElement>("colgroup col"), (col) => col.style.width);+ // Content width up to 320px, never below a column's minimum.+ expect(cols).toEqual(["320px", "330px", "90px"]);+ expect(table).toHaveAttribute("data-column-widths");+ expect(table.closest(".rich-table")).not.toHaveAttribute("data-resized");+ expect(screen.queryByRole("button", { name: "Reset widths" })).toBeNull();+ expect(window.localStorage.getItem("multica:rich-table-widths")).toBeNull();+ } finally {+ rect.mockRestore();+ clientWidth.mockRestore();+ }+ });++ it("resizes a column from the keyboard, persists it, and resets", async () => {+ const { table, unmount } = renderTable();+ const handle = screen.getByRole("separator", { name: "Resize Relation column" });++ fireEvent.keyDown(handle, { key: "ArrowRight", shiftKey: true });++ expect(table).toHaveAttribute("data-column-widths");+ expect(table.querySelectorAll("colgroup col")).toHaveLength(3);+ expect(window.localStorage.getItem("multica:rich-table-widths")).toContain("widths");++ // Widths belong to the table's content, so a fresh mount restores them.+ unmount();+ const remounted = renderTable();+ expect(remounted.table).toHaveAttribute("data-column-widths");++ await userEvent.click(screen.getByRole("button", { name: "Reset widths" }));+ expect(remounted.table).not.toHaveAttribute("data-column-widths");+ expect(remounted.table.querySelectorAll("colgroup col")).toHaveLength(0);+ expect(window.localStorage.getItem("multica:rich-table-widths")).toBe("{}");+ });++ it("keeps a handle's height after a click, so a double-click lands", () => {+ renderTable();+ const handle = screen.getByRole("separator", { name: "Resize Relation column" });+ handle.style.height = "38px";+ fireEvent.pointerDown(handle, { clientX: 100, pointerId: 1 });+ fireEvent.pointerUp(window, { clientX: 100, pointerId: 1 });+ expect(handle.style.height).toBe("38px");+ });++ it("copies the table as the author wrote it", async () => {+ renderTable();+ await userEvent.click(screen.getByRole("button", { name: "Copy as Markdown" }));+ expect(copyText).toHaveBeenCalledWith(+ [+ "| GitHub | Relation | Count |",+ "| --- | --- | --- |",+ "| #7738 harness switch | MUL-12 tracks it | 10 |",+ "| #4753 agent registry | see ==hot== | 9 |",+ "| #9250 PATH key | none | 100 |",+ ].join("\n"),+ );+ });++ it("copies code, explicit links and quoted tables unchanged", async () => {+ const table = [+ "| Code | Link |",+ "| --- | --- |",+ "| `<mark>hello</mark>` and `[a](b)` | [https://x.com](https://x.com) |",+ ];+ render(<RichContent content={["Quoted:", "", ...table.map((line) => `> ${line}`)].join("\n")} />);+ await userEvent.click(screen.getByRole("button", { name: "Copy as Markdown" }));+ expect(copyText).toHaveBeenCalledWith(table.join("\n"));+ });++ it("expands into a sortable, filterable view of the same cells", async () => {+ renderTable();+ await userEvent.click(screen.getByRole("button", { name: "Expand table" }));++ const dialog = await screen.findByRole("dialog");+ const bodyRows = () =>+ within(dialog)+ .getAllByRole("row")+ .slice(1)+ .map((row) => within(row).getAllByRole("cell").map((cell) => cell.textContent));++ expect(bodyRows()).toEqual([+ ["1", "#7738 harness switch", "MUL-12 tracks it", "10"],+ ["2", "#4753 agent registry", "see hot", "9"],+ ["3", "#9250 PATH key", "none", "100"],+ ]);+ // Inline Markdown keeps its renderer inside the dialog.+ expect(within(dialog).getByText("hot").tagName).toBe("MARK");++ // Numbers sort as numbers; row numbers keep the source position.+ await userEvent.click(within(dialog).getByRole("button", { name: "Count" }));+ expect(bodyRows().map((row) => row[0])).toEqual(["2", "1", "3"]);++ await userEvent.type(within(dialog).getByRole("searchbox", { name: "Filter rows" }), "path");+ expect(bodyRows()).toEqual([["3", "#9250 PATH key", "none", "100"]]);++ await userEvent.click(within(dialog).getByRole("button", { name: "Copy as CSV" }));+ expect(copyText).toHaveBeenCalledWith(+ "GitHub,Relation,Count\n#7738 harness switch,MUL-12 tracks it,10\n#4753 agent registry,see hot,9\n#9250 PATH key,none,100",+ );++ await userEvent.click(within(dialog).getByRole("button", { name: "Close" }));+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());+ });+});diff --git a/packages/views/rich-content/rich-table.tsx b/packages/views/rich-content/rich-table.tsxnew file mode 100644index 0000000000..f93dfcc2a3--- /dev/null+++ b/packages/views/rich-content/rich-table.tsx@@ -0,0 +1,516 @@+"use client";++/**+ * Markdown tables: column resizing, an expanded view and copy. One frame+ * serves both renderers — RichContent's readonly tables and the editor's+ * table node view, whose rows ProseMirror owns — so everything it adds sits+ * outside the rows: the toolbar, a layer of resize handles over the column+ * edges, and the column widths on the `<table>` itself.+ *+ * The table keeps the browser's automatic layout while its columns fit (see+ * `overflowWidths` for when they do not). A viewer's first drag pins every+ * column at the width it renders at and switches to fixed layout, so only the+ * dragged column moves. Those widths are the viewer's own (see+ * `writeColumnWidths`) and never touch the content.+ */++import {+ createContext,+ memo,+ useCallback,+ useContext,+ useEffect,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+ type ComponentPropsWithoutRef,+ type KeyboardEvent as ReactKeyboardEvent,+ type PointerEvent as ReactPointerEvent,+ type ReactNode,+} from "react";+import { createPortal } from "react-dom";+import type { ExtraProps } from "react-markdown";+import { Check, Copy, Maximize2, RotateCcw } from "lucide-react";+import { copyText } from "@multica/ui/lib/clipboard";+import { cn } from "@multica/ui/lib/utils";+import { useT } from "../i18n";+import { RichTableDialog } from "./rich-table-dialog";+import {+ columnWidthKey,+ readColumnWidths,+ readTableModel,+ tableMarkdownFromSource,+ writeColumnWidths,+ type RichTableModel,+} from "./rich-table-model";++export interface RichTableSource {+ /** The content as written. */+ source: string;+ /** The preprocessed copy RichContent rendered, which node offsets index into. */+ rendered: string;+}++export const RichTableSourceContext = createContext<RichTableSource>({ source: "", rendered: "" });++/** Marks the frame's own controls, which the editor must leave to the browser. */+export const RICH_TABLE_CHROME_ATTRIBUTE = "data-rich-table-chrome";++const RESIZE_DRAG_THRESHOLD = 4;+const MIN_COLUMN_WIDTH = 64;+const MAX_COLUMN_WIDTH = 1200;+// A double-click fits the content, but a paragraph-long cell would otherwise+// claim its full single-line width.+const MAX_AUTO_FIT_WIDTH = 480;+const KEYBOARD_STEP = 8;+const KEYBOARD_STEP_LARGE = 32;+const HANDLE_WIDTH = 8;+const SCROLL_SHADOW = "color-mix(in oklab, var(--foreground) 8%, transparent)";++function clampWidth(width: number, max = MAX_COLUMN_WIDTH): number {+ return Math.min(max, Math.max(MIN_COLUMN_WIDTH, Math.round(width)));+}++function sum(widths: number[]): number {+ return widths.reduce((total, width) => total + width, 0);+}++function sameWidths(a: number[] | null, b: number[] | null): boolean {+ return a === b || (!!a && !!b && a.length === b.length && a.every((w, i) => w === b[i]));+}++// The editor keeps its header row in <tbody>, so the first row stands for the+// columns in both renderers.+function headerCells(table: HTMLTableElement): HTMLTableCellElement[] {+ return Array.from(table.rows[0]?.cells ?? []);+}++// Each column's min-content and max-content width, read with the table's own+// sizing lifted and restored within the same task, so the browser paints only+// the restored layout. Only the <table> and its <col>s are touched: in the+// editor, a style written to a cell would reach ProseMirror as an edit.+function measureColumns(table: HTMLTableElement): { min: number[]; max: number[] } {+ const { style } = table;+ const saved = { layout: style.tableLayout, width: style.width, minWidth: style.minWidth };+ const fixed = table.hasAttribute("data-column-widths");+ const cols = Array.from(table.querySelectorAll<HTMLElement>("colgroup > col"));+ const colWidths = cols.map((col) => col.style.width);+ const read = () => headerCells(table).map((cell) => Math.ceil(cell.getBoundingClientRect().width));++ if (fixed) table.removeAttribute("data-column-widths");+ for (const col of cols) col.style.width = "";+ style.tableLayout = "auto";+ style.minWidth = "0";+ style.width = "max-content";+ const max = read();+ style.width = "min-content";+ const min = read();++ style.tableLayout = saved.layout;+ style.width = saved.width;+ style.minWidth = saved.minWidth;+ cols.forEach((col, i) => {+ col.style.width = colWidths[i] ?? "";+ });+ if (fixed) table.setAttribute("data-column-widths", "");+ return { min, max };+}++// The browser's automatic layout reads well while the columns' minimums fit.+// Once they do not, it shrinks every column to its minimum, which leaves a+// prose column a few characters wide beside a column of unbreakable paths.+// Past that point each column gets its content width, capped so one long cell+// cannot claim the table, and the table scrolls.+const PREFERRED_MAX_COLUMN_WIDTH = 320;++function overflowWidths(table: HTMLTableElement, available: number): number[] | null {+ const { min, max } = measureColumns(table);+ if (min.length === 0 || sum(min) <= available) return null;+ return min.map((least, i) => Math.max(least, Math.min(max[i] ?? least, PREFERRED_MAX_COLUMN_WIDTH)));+}++interface ColumnEdges {+ /** Left offset of each column's handle within the wrapper's scroll area. */+ lefts: number[];+ top: number;+ headerHeight: number;+}++const NO_EDGES: ColumnEdges = { lefts: [], top: 0, headerHeight: 0 };++function sameEdges(a: ColumnEdges, b: ColumnEdges): boolean {+ return (+ a.top === b.top &&+ a.headerHeight === b.headerHeight &&+ a.lefts.length === b.lefts.length &&+ a.lefts.every((left, i) => left === b.lefts[i])+ );+}++function measureEdges(wrapper: HTMLElement, table: HTMLTableElement): ColumnEdges {+ const cells = headerCells(table);+ if (cells.length === 0) return NO_EDGES;+ const box = wrapper.getBoundingClientRect();+ const originX = box.left + wrapper.clientLeft - wrapper.scrollLeft;+ const originY = box.top + wrapper.clientTop - wrapper.scrollTop;+ const row = cells[0]!.parentElement!.getBoundingClientRect();+ return {+ // Centred on the edge, except the last, which stays inside the scroll box:+ // overhanging it would add a few pixels of horizontal scroll to every table.+ lefts: cells.map((cell, i) => {+ const right = Math.round(cell.getBoundingClientRect().right - originX);+ return i === cells.length - 1 ? right - HANDLE_WIDTH : right - HANDLE_WIDTH / 2;+ }),+ top: Math.round(row.top - originY),+ headerHeight: Math.round(row.height),+ };+}++export interface RichTableFrameProps {+ model: RichTableModel;+ /** The table's Markdown, read when it is copied. */+ getMarkdown: () => string;+ /** Receives the `<table>`, for rows rendered outside React. */+ tableRef?: (table: HTMLTableElement | null) => void;+ children?: ReactNode;+}++export function RichTableFrame({ model, getMarkdown, tableRef: onTable, children }: RichTableFrameProps) {+ const { t } = useT("editor");+ const columnCount = model.headerText.length;+ const storageKey = useMemo(() => columnWidthKey(model), [model]);++ const [widths, setWidths] = useState<number[] | null>(null);+ const [dragging, setDragging] = useState(false);+ const [expanded, setExpanded] = useState(false);+ const [copied, setCopied] = useState(false);+ const tableRef = useRef<HTMLTableElement | null>(null);+ const wrapperRef = useRef<HTMLDivElement>(null);+ const setTable = useCallback(+ (table: HTMLTableElement | null) => {+ tableRef.current = table;+ onTable?.(table);+ },+ [onTable],+ );+ const widthsRef = useRef(widths);+ useLayoutEffect(() => {+ widthsRef.current = widths;+ }, [widths]);++ // Layout effect: stored widths apply before the first paint, so a resized+ // table does not flash at its automatic layout on every mount. A table being+ // edited changes its key with every keystroke; its widths move to the new+ // key as long as the columns stay the same.+ const keyRef = useRef(storageKey);+ useLayoutEffect(() => {+ const previousKey = keyRef.current;+ keyRef.current = storageKey;+ const stored = readColumnWidths(storageKey, columnCount);+ const carried =+ !stored && previousKey !== storageKey && widthsRef.current?.length === columnCount+ ? widthsRef.current+ : null;+ if (carried) {+ writeColumnWidths(previousKey, null);+ writeColumnWidths(storageKey, carried);+ }+ setWidths(stored ?? carried);+ }, [storageKey, columnCount]);++ const [autoWidths, setAutoWidths] = useState<number[] | null>(null);+ useLayoutEffect(() => {+ const wrapper = wrapperRef.current;+ const table = tableRef.current;+ if (!wrapper || !table || widths) return;+ let measuredAt = -1;+ let active = true;+ const fit = () => {+ const available = wrapper.clientWidth;+ if (!active || available === measuredAt) return;+ measuredAt = available;+ const next = overflowWidths(table, available);+ setAutoWidths((prev) => (sameWidths(prev, next) ? prev : next));+ };+ fit();+ const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(fit);+ observer?.observe(wrapper);+ // Content widths change when a web font replaces its fallback.+ void document.fonts?.ready.then(() => {+ measuredAt = -1;+ fit();+ });+ return () => {+ active = false;+ observer?.disconnect();+ };+ }, [widths, model]);++ const userWidths = widths?.length === columnCount ? widths : null;+ const resized = userWidths !== null;+ const columnWidths = userWidths ?? (autoWidths?.length === columnCount ? autoWidths : null);++ const [edges, setEdges] = useState(NO_EDGES);+ const syncEdges = useCallback(() => {+ const wrapper = wrapperRef.current;+ const table = tableRef.current;+ if (!wrapper || !table) return;+ const next = measureEdges(wrapper, table);+ setEdges((prev) => (sameEdges(prev, next) ? prev : next));+ }, []);+ useLayoutEffect(syncEdges, [syncEdges, columnWidths, model]);+ useEffect(() => {+ const table = tableRef.current;+ if (!table || typeof ResizeObserver === "undefined") return;+ const observer = new ResizeObserver(syncEdges);+ observer.observe(table);+ return () => observer.disconnect();+ }, [syncEdges]);++ const [overflow, setOverflow] = useState({ start: false, end: false });+ useEffect(() => {+ const wrapper = wrapperRef.current;+ if (!wrapper) return;+ const sync = () => {+ const start = wrapper.scrollLeft > 0;+ const end = wrapper.scrollLeft + wrapper.clientWidth < wrapper.scrollWidth - 1;+ setOverflow((prev) => (prev.start === start && prev.end === end ? prev : { start, end }));+ };+ sync();+ wrapper.addEventListener("scroll", sync, { passive: true });+ const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(sync);+ observer?.observe(wrapper);+ if (tableRef.current) observer?.observe(tableRef.current);+ return () => {+ wrapper.removeEventListener("scroll", sync);+ observer?.disconnect();+ };+ }, []);++ const resize = useMemo(() => {+ const renderedWidths = (): number[] => {+ const table = tableRef.current;+ return table ? headerCells(table).map((cell) => clampWidth(cell.getBoundingClientRect().width)) : [];+ };+ const baseWidths = () => widthsRef.current ?? renderedWidths();+ const commit = (next: number[]) => {+ setWidths(next);+ writeColumnWidths(storageKey, next);+ };+ const columnOf = (handle: HTMLElement) => Number(handle.dataset.column ?? -1);++ return {+ begin(event: ReactPointerEvent<HTMLElement>) {+ const handle = event.currentTarget;+ const index = columnOf(handle);+ if (index < 0) return;+ event.preventDefault();+ event.stopPropagation();++ const startX = event.clientX;+ const { pointerId } = event;+ const table = tableRef.current;+ const badge = handle.querySelector<HTMLElement>("[data-width-badge]");+ const restingHeight = handle.style.height;+ let base: number[] | null = null;+ let latest: number[] | null = null;++ const move = (pointerEvent: PointerEvent) => {+ const delta = pointerEvent.clientX - startX;+ if (!base && Math.abs(delta) < RESIZE_DRAG_THRESHOLD) return;+ if (!base) {+ base = baseWidths();+ handle.dataset.resizing = "";+ if (table) handle.style.height = `${table.offsetHeight}px`;+ setDragging(true);+ }+ const width = clampWidth((base[index] ?? 0) + delta);+ latest = base.map((w, i) => (i === index ? width : w));+ if (badge) badge.textContent = `${width}px`;+ setWidths(latest);+ };+ const stop = () => {+ window.removeEventListener("pointermove", move);+ window.removeEventListener("pointerup", stop);+ window.removeEventListener("pointercancel", stop);+ window.removeEventListener("blur", stop);+ handle.removeEventListener("lostpointercapture", stop);+ if (handle.hasPointerCapture?.(pointerId)) handle.releasePointerCapture?.(pointerId);+ delete handle.dataset.resizing;+ handle.style.height = restingHeight;+ setDragging(false);+ if (latest) commit(latest);+ };++ window.addEventListener("pointermove", move);+ window.addEventListener("pointerup", stop);+ window.addEventListener("pointercancel", stop);+ // Releasing outside the window never delivers pointerup.+ window.addEventListener("blur", stop);+ handle.addEventListener("lostpointercapture", stop);+ handle.setPointerCapture?.(pointerId);+ },++ autoFit(handle: HTMLElement) {+ const table = tableRef.current;+ const index = columnOf(handle);+ if (!table || index < 0) return;+ const base = baseWidths();+ const widest = measureColumns(table).max[index] ?? 0;+ if (widest > 0) {+ commit(base.map((w, i) => (i === index ? clampWidth(widest, MAX_AUTO_FIT_WIDTH) : w)));+ }+ },++ nudge(event: ReactKeyboardEvent<HTMLElement>) {+ if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return;+ const index = columnOf(event.currentTarget);+ if (index < 0) return;+ event.preventDefault();+ const step = event.shiftKey ? KEYBOARD_STEP_LARGE : KEYBOARD_STEP;+ const delta = event.key === "ArrowRight" ? step : -step;+ commit(baseWidths().map((w, i) => (i === index ? clampWidth(w + delta) : w)));+ },+ };+ }, [storageKey]);++ const resetWidths = () => {+ setWidths(null);+ writeColumnWidths(storageKey, null);+ };++ const copyMarkdown = async () => {+ if (await copyText(getMarkdown())) {+ setCopied(true);+ setTimeout(() => setCopied(false), 2000);+ }+ };++ const chrome = { [RICH_TABLE_CHROME_ATTRIBUTE]: "", contentEditable: false } as const;+ const toolbarButton =+ "flex h-6 items-center justify-center gap-1 rounded-sm text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";++ return (+ <div className="rich-table group/table" data-resized={resized ? "" : undefined}>+ {/* A row of its own above the table: over the table it would cover the+ last columns' headers and resize handles. */}+ <div+ {...chrome}+ className="rich-table-toolbar flex h-7 items-center justify-end gap-0.5 opacity-0 transition-opacity group-hover/table:opacity-100 focus-within:opacity-100 [@media(hover:none)]:opacity-100"+ >+ {resized && (+ <button type="button" onClick={resetWidths} className={cn(toolbarButton, "px-1.5 text-caption")}>+ <RotateCcw className="size-3.5" />+ {t(($) => $.table.reset_widths)}+ </button>+ )}+ <button+ type="button"+ onClick={() => setExpanded(true)}+ className={cn(toolbarButton, "w-6")}+ title={t(($) => $.table.expand)}+ aria-label={t(($) => $.table.expand)}+ >+ <Maximize2 className="size-3.5" />+ </button>+ <button+ type="button"+ onClick={copyMarkdown}+ className={cn(toolbarButton, "w-6")}+ title={copied ? t(($) => $.table.copied) : t(($) => $.table.copy_markdown)}+ aria-label={t(($) => $.table.copy_markdown)}+ >+ {copied ? <Check className="size-3.5" /> : <Copy className="size-3.5" />}+ </button>+ </div>+ <div className="relative">+ <div ref={wrapperRef} className="tableWrapper">+ <table+ ref={setTable}+ data-column-widths={columnWidths ? "" : undefined}+ style={columnWidths ? { width: sum(columnWidths) } : undefined}+ >+ {/* Always rendered, so it stays ahead of rows appended outside React. */}+ <colgroup>+ {columnWidths?.map((width, index) => (+ <col key={index} style={{ width }} />+ ))}+ </colgroup>+ {children}+ </table>+ {model.headerText.map((name, index) => (+ <div+ key={index}+ {...chrome}+ role="separator"+ aria-orientation="vertical"+ aria-label={t(($) => $.table.resize_column, { name })}+ tabIndex={0}+ data-column={index}+ data-edge={index === columnCount - 1 ? "end" : undefined}+ className="rich-table-resize-handle"+ style={{ left: edges.lefts[index] ?? 0, top: edges.top, height: edges.headerHeight || undefined }}+ onPointerDown={resize.begin}+ onDoubleClick={(event) => {+ event.preventDefault();+ resize.autoFit(event.currentTarget);+ }}+ onKeyDown={resize.nudge}+ >+ <span data-width-badge="" aria-hidden />+ </div>+ ))}+ </div>+ {/* Columns continue past the edge: a shadow, not a fade to a background+ colour, because the same table renders on cards, pages and chat. */}+ {overflow.start && (+ <div+ aria-hidden+ className="pointer-events-none absolute inset-y-px left-px w-3 rounded-l-[var(--radius)]"+ style={{ background: `linear-gradient(to right, ${SCROLL_SHADOW}, transparent)` }}+ />+ )}+ {overflow.end && (+ <div+ aria-hidden+ className="pointer-events-none absolute inset-y-px right-px w-3 rounded-r-[var(--radius)]"+ style={{ background: `linear-gradient(to left, ${SCROLL_SHADOW}, transparent)` }}+ />+ )}+ </div>+ {expanded && (+ <RichTableDialog model={model} open={expanded} onOpenChange={setExpanded} getMarkdown={getMarkdown} />+ )}+ {/* Owns the cursor for the whole drag, so cells that declare their own+ (links, text) cannot override it, and keeps text unselectable. */}+ {dragging &&+ typeof document !== "undefined" &&+ createPortal(+ <div aria-hidden className="fixed inset-0 z-50 cursor-col-resize touch-none select-none" />,+ document.body,+ )}+ </div>+ );+}++// Rendered children of the table. Memoized on their identity so a drag, which+// re-renders the frame every frame for its widths, never re-renders the cells.+const TableContent = memo(function TableContent({ children }: { children: ReactNode }) {+ return <>{children}</>;+});++type RichTableProps = ComponentPropsWithoutRef<"table"> & ExtraProps;++/** react-markdown's `table` override. */+export function RichTable({ children, node }: RichTableProps) {+ const { source, rendered } = useContext(RichTableSourceContext);+ const model = useMemo(() => readTableModel(children), [children]);+ const getMarkdown = () =>+ tableMarkdownFromSource(source, rendered, node?.position?.start.offset, node?.position?.end.offset);+ return (+ <RichTableFrame model={model} getMarkdown={getMarkdown}>+ <TableContent>{children}</TableContent>+ </RichTableFrame>+ );+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 8393d9dc77..7b5bbcce13 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1055,9 +1055,21 @@ importers:mdast-util-from-markdown:specifier: ^2.0.3version: 2.0.3+ mdast-util-gfm-table:+ specifier: ^2.0.0+ version: 2.0.0+ mdast-util-math:+ specifier: ^3.0.0+ version: 3.0.0mermaid:specifier: 'catalog:'version: 11.14.0+ micromark-extension-gfm-table:+ specifier: ^2.1.1+ version: 2.1.1+ micromark-extension-math:+ specifier: ^3.1.0+ version: 3.1.0motion:specifier: ^12.38.0