feat: add table editor dialog for visual table editing

Add a dialog-based table editor that makes creating and editing markdown
tables much easier than manipulating raw pipe-delimited text.

Features:
- Visual grid of input fields for editing headers and cells
- Add and remove rows and columns
- Sort columns ascending/descending (supports both text and numeric)
- Tab key navigation between cells (auto-creates new rows at the end)
- Properly formatted/aligned markdown output on confirm
- Row numbers with hover-to-delete interaction
- Column sort indicators and remove buttons

Integration points:
1. Toolbar: New 'Table' button in the InsertMenu (+) dropdown opens the
   dialog for creating new tables from the editor
2. Slash command: /table now opens the dialog instead of inserting raw
   markdown, via new Command.action callback support
3. Rendered tables: Edit pencil icon appears on hover over rendered tables
   in MemoContent, opens dialog pre-populated with parsed table data,
   and saves changes directly via updateMemo mutation (same pattern as
   TaskListItem checkbox toggling)

New files:
- utils/markdown-table.ts: Parse, serialize, find/replace markdown tables
- components/TableEditorDialog.tsx: Reusable table editor dialog component

Modified:
- Extended Command interface with optional action callback for dialogs
- SlashCommands handles action-based commands (skips text insertion)
- Editor accepts custom commands via props
- EditorContent creates commands with table editor wired in
- MemoEditor manages table dialog state shared between slash cmd and toolbar
- InsertMenu includes Table entry and its own dialog for toolbar flow
- Table.tsx (MemoContent) adds edit button and dialog for rendered tables

Co-authored-by: milvasic <milvasic@users.noreply.github.com>
This commit is contained in:
Cursor Agent 2026-02-06 22:44:15 +00:00
parent bab7a53d7a
commit f95e4452a5
11 changed files with 735 additions and 16 deletions

View File

@ -1,20 +1,101 @@
import { PencilIcon } from "lucide-react";
import { useCallback, useRef, useState } from "react";
import TableEditorDialog from "@/components/TableEditorDialog";
import { useUpdateMemo } from "@/hooks/useMemoQueries";
import { cn } from "@/lib/utils";
import type { TableData } from "@/utils/markdown-table";
import { findAllTables, parseMarkdownTable, replaceNthTable } from "@/utils/markdown-table";
import { useMemoViewContext, useMemoViewDerived } from "../MemoView/MemoViewContext";
import type { ReactMarkdownProps } from "./markdown/types";
// ---------------------------------------------------------------------------
// Table (root wrapper with edit button)
// ---------------------------------------------------------------------------
interface TableProps extends React.HTMLAttributes<HTMLTableElement>, ReactMarkdownProps {
children: React.ReactNode;
}
export const Table = ({ children, className, node: _node, ...props }: TableProps) => {
const tableRef = useRef<HTMLDivElement>(null);
const [dialogOpen, setDialogOpen] = useState(false);
const [tableData, setTableData] = useState<TableData | null>(null);
const [tableIndex, setTableIndex] = useState(-1);
const { memo } = useMemoViewContext();
const { readonly } = useMemoViewDerived();
const { mutate: updateMemo } = useUpdateMemo();
const handleEditClick = useCallback(
(e: React.MouseEvent) => {
e.stopPropagation();
e.preventDefault();
// Determine which table this is in the memo content by walking the DOM.
const container = tableRef.current?.closest('[class*="wrap-break-word"]');
if (!container) return;
const allTables = container.querySelectorAll("table");
let idx = 0;
for (let i = 0; i < allTables.length; i++) {
if (tableRef.current?.contains(allTables[i])) {
idx = i;
break;
}
}
// Find and parse the corresponding markdown table.
const tables = findAllTables(memo.content);
if (idx >= tables.length) return;
const parsed = parseMarkdownTable(tables[idx].text);
if (!parsed) return;
setTableData(parsed);
setTableIndex(idx);
setDialogOpen(true);
},
[memo.content],
);
const handleConfirm = useCallback(
(markdown: string) => {
if (tableIndex < 0) return;
const newContent = replaceNthTable(memo.content, tableIndex, markdown);
updateMemo({
update: { name: memo.name, content: newContent },
updateMask: ["content"],
});
},
[memo.content, memo.name, tableIndex, updateMemo],
);
return (
<div className="w-full overflow-x-auto rounded-lg border border-border my-2">
<table className={cn("w-full border-collapse text-sm", className)} {...props}>
{children}
</table>
</div>
<>
<div ref={tableRef} className="group/table relative w-full overflow-x-auto rounded-lg border border-border my-2">
<table className={cn("w-full border-collapse text-sm", className)} {...props}>
{children}
</table>
{!readonly && (
<button
type="button"
className="absolute top-1.5 right-1.5 p-1 rounded bg-accent/80 text-muted-foreground opacity-0 group-hover/table:opacity-100 hover:bg-accent hover:text-foreground transition-all"
onClick={handleEditClick}
title="Edit table"
>
<PencilIcon className="size-3.5" />
</button>
)}
</div>
<TableEditorDialog open={dialogOpen} onOpenChange={setDialogOpen} initialData={tableData} onConfirm={handleConfirm} />
</>
);
};
// ---------------------------------------------------------------------------
// Sub-components (unchanged)
// ---------------------------------------------------------------------------
interface TableHeadProps extends React.HTMLAttributes<HTMLTableSectionElement>, ReactMarkdownProps {
children: React.ReactNode;
}

View File

@ -5,10 +5,18 @@ import { useSuggestions } from "./useSuggestions";
const SlashCommands = ({ editorRef, editorActions, commands }: SlashCommandsProps) => {
const handleCommandAutocomplete = (cmd: (typeof commands)[0], word: string, index: number, actions: EditorRefActions) => {
// Remove trigger char + word, then insert command output
// Remove trigger char + word.
actions.removeText(index, word.length);
// If the command has a dialog action, invoke it instead of inserting text.
if (cmd.action) {
cmd.action();
return;
}
// Otherwise insert the command output text.
actions.insertText(cmd.run());
// Position cursor relative to insertion point, if specified
// Position cursor relative to insertion point, if specified.
if (cmd.cursorOffset) {
actions.setCursorPosition(index + cmd.cursorOffset);
}

View File

@ -1,7 +1,10 @@
export interface Command {
name: string;
/** Returns text to insert. Ignored if `action` is set. */
run: () => string;
cursorOffset?: number;
/** If set, called instead of inserting run() text. Used for dialog-based commands. */
action?: () => void;
}
export const editorCommands: Command[] = [
@ -26,3 +29,18 @@ export const editorCommands: Command[] = [
cursorOffset: 1,
},
];
/**
* Create the full editor commands list, with the table command
* wired to open the table editor dialog instead of inserting raw markdown.
*/
export function createEditorCommands(onOpenTableEditor?: () => void): Command[] {
if (!onOpenTableEditor) return editorCommands;
return editorCommands.map((cmd) => {
if (cmd.name === "table") {
return { ...cmd, action: onOpenTableEditor };
}
return cmd;
});
}

View File

@ -35,6 +35,7 @@ const Editor = forwardRef(function Editor(props: EditorProps, ref: React.Forward
isInIME = false,
onCompositionStart,
onCompositionEnd,
commands: customCommands,
} = props;
const editorRef = useRef<HTMLTextAreaElement>(null);
@ -205,7 +206,7 @@ const Editor = forwardRef(function Editor(props: EditorProps, ref: React.Forward
onCompositionEnd={onCompositionEnd}
></textarea>
<TagSuggestions editorRef={editorRef} editorActions={ref} />
<SlashCommands editorRef={editorRef} editorActions={ref} commands={editorCommands} />
<SlashCommands editorRef={editorRef} editorActions={ref} commands={customCommands || editorCommands} />
</div>
);
});

View File

@ -1,9 +1,20 @@
import { LatLng } from "leaflet";
import { uniqBy } from "lodash-es";
import { FileIcon, LinkIcon, LoaderIcon, type LucideIcon, MapPinIcon, Maximize2Icon, MoreHorizontalIcon, PlusIcon } from "lucide-react";
import {
FileIcon,
LinkIcon,
LoaderIcon,
type LucideIcon,
MapPinIcon,
Maximize2Icon,
MoreHorizontalIcon,
PlusIcon,
TableIcon,
} from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useDebounce } from "react-use";
import { useReverseGeocoding } from "@/components/map";
import TableEditorDialog from "@/components/TableEditorDialog";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
@ -30,6 +41,7 @@ const InsertMenu = (props: InsertMenuProps) => {
const [linkDialogOpen, setLinkDialogOpen] = useState(false);
const [locationDialogOpen, setLocationDialogOpen] = useState(false);
const [tableDialogOpen, setTableDialogOpen] = useState(false);
const [moreSubmenuOpen, setMoreSubmenuOpen] = useState(false);
const { handleTriggerEnter, handleTriggerLeave, handleContentEnter, handleContentLeave } = useDropdownMenuSubHoverDelay(
@ -77,6 +89,17 @@ const InsertMenu = (props: InsertMenuProps) => {
setLinkDialogOpen(true);
}, []);
const handleOpenTableDialog = useCallback(() => {
setTableDialogOpen(true);
}, []);
const handleTableConfirm = useCallback(
(markdown: string) => {
props.onInsertText?.(markdown);
},
[props],
);
const handleLocationClick = useCallback(() => {
setLocationDialogOpen(true);
if (!initialLocation && !location.locationInitialized) {
@ -127,6 +150,12 @@ const InsertMenu = (props: InsertMenuProps) => {
icon: FileIcon,
onClick: handleUploadClick,
},
{
key: "table",
label: "Table",
icon: TableIcon,
onClick: handleOpenTableDialog,
},
{
key: "link",
label: t("tooltip.link-memo"),
@ -140,7 +169,7 @@ const InsertMenu = (props: InsertMenuProps) => {
onClick: handleLocationClick,
},
] satisfies Array<{ key: string; label: string; icon: LucideIcon; onClick: () => void }>,
[handleLocationClick, handleOpenLinkDialog, handleUploadClick, t],
[handleLocationClick, handleOpenLinkDialog, handleOpenTableDialog, handleUploadClick, t],
);
return (
@ -207,6 +236,8 @@ const InsertMenu = (props: InsertMenuProps) => {
onCancel={handleLocationCancel}
onConfirm={handleLocationConfirm}
/>
<TableEditorDialog open={tableDialogOpen} onOpenChange={setTableDialogOpen} onConfirm={handleTableConfirm} />
</>
);
};

View File

@ -1,11 +1,12 @@
import { forwardRef } from "react";
import { forwardRef, useMemo } from "react";
import Editor, { type EditorRefActions } from "../Editor";
import { createEditorCommands } from "../Editor/commands";
import { useBlobUrls, useDragAndDrop } from "../hooks";
import { useEditorContext } from "../state";
import type { EditorContentProps } from "../types";
import type { LocalFile } from "../types/attachment";
export const EditorContent = forwardRef<EditorRefActions, EditorContentProps>(({ placeholder }, ref) => {
export const EditorContent = forwardRef<EditorRefActions, EditorContentProps>(({ placeholder, onOpenTableEditor }, ref) => {
const { state, actions, dispatch } = useEditorContext();
const { createBlobUrl } = useBlobUrls();
@ -54,6 +55,9 @@ export const EditorContent = forwardRef<EditorRefActions, EditorContentProps>(({
event.preventDefault();
};
// Build commands with the table editor action wired in.
const commands = useMemo(() => createEditorCommands(onOpenTableEditor), [onOpenTableEditor]);
return (
<div className="w-full flex flex-col flex-1" {...dragHandlers}>
<Editor
@ -67,6 +71,7 @@ export const EditorContent = forwardRef<EditorRefActions, EditorContentProps>(({
onPaste={handlePaste}
onCompositionStart={handleCompositionStart}
onCompositionEnd={handleCompositionEnd}
commands={commands}
/>
</div>
);

View File

@ -7,7 +7,7 @@ import InsertMenu from "../Toolbar/InsertMenu";
import VisibilitySelector from "../Toolbar/VisibilitySelector";
import type { EditorToolbarProps } from "../types";
export const EditorToolbar: FC<EditorToolbarProps> = ({ onSave, onCancel, memoName }) => {
export const EditorToolbar: FC<EditorToolbarProps> = ({ onSave, onCancel, memoName, onInsertText }) => {
const t = useTranslate();
const { state, actions, dispatch } = useEditorContext();
const { valid } = validationService.canSave(state);
@ -34,6 +34,7 @@ export const EditorToolbar: FC<EditorToolbarProps> = ({ onSave, onCancel, memoNa
location={state.metadata.location}
onLocationChange={handleLocationChange}
onToggleFocusMode={handleToggleFocusMode}
onInsertText={onInsertText}
memoName={memoName}
/>
</div>

View File

@ -1,6 +1,7 @@
import { useQueryClient } from "@tanstack/react-query";
import { useRef } from "react";
import { useCallback, useRef, useState } from "react";
import { toast } from "react-hot-toast";
import TableEditorDialog from "@/components/TableEditorDialog";
import { useAuth } from "@/contexts/AuthContext";
import useCurrentUser from "@/hooks/useCurrentUser";
import { memoKeys } from "@/hooks/useMemoQueries";
@ -68,6 +69,17 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
dispatch(actions.toggleFocusMode());
};
// Table editor dialog (shared by slash command and toolbar).
const [tableDialogOpen, setTableDialogOpen] = useState(false);
const handleOpenTableEditor = useCallback(() => {
setTableDialogOpen(true);
}, []);
const handleTableConfirm = useCallback((markdown: string) => {
editorRef.current?.insertText(markdown);
}, []);
useKeyboard(editorRef, { onSave: handleSave });
async function handleSave() {
@ -142,14 +154,21 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
<FocusModeExitButton isActive={state.ui.isFocusMode} onToggle={handleToggleFocusMode} title={t("editor.exit-focus-mode")} />
{/* Editor content grows to fill available space in focus mode */}
<EditorContent ref={editorRef} placeholder={placeholder} autoFocus={autoFocus} />
<EditorContent ref={editorRef} placeholder={placeholder} autoFocus={autoFocus} onOpenTableEditor={handleOpenTableEditor} />
{/* Metadata and toolbar grouped together at bottom */}
<div className="w-full flex flex-col gap-2">
<EditorMetadata memoName={memoName} />
<EditorToolbar onSave={handleSave} onCancel={onCancel} memoName={memoName} />
<EditorToolbar
onSave={handleSave}
onCancel={onCancel}
memoName={memoName}
onInsertText={(text) => editorRef.current?.insertText(text)}
/>
</div>
</div>
<TableEditorDialog open={tableDialogOpen} onOpenChange={setTableDialogOpen} onConfirm={handleTableConfirm} />
</>
);
};

View File

@ -18,12 +18,14 @@ export interface MemoEditorProps {
export interface EditorContentProps {
placeholder?: string;
autoFocus?: boolean;
onOpenTableEditor?: () => void;
}
export interface EditorToolbarProps {
onSave: () => void;
onCancel?: () => void;
memoName?: string;
onInsertText?: (text: string) => void;
}
export interface EditorMetadataProps {
@ -68,6 +70,7 @@ export interface InsertMenuProps {
location?: Location;
onLocationChange: (location?: Location) => void;
onToggleFocusMode?: () => void;
onInsertText?: (text: string) => void;
memoName?: string;
}
@ -92,6 +95,8 @@ export interface EditorProps {
isInIME?: boolean;
onCompositionStart?: () => void;
onCompositionEnd?: () => void;
/** Custom commands for slash menu. If not provided, defaults are used. */
commands?: import("../Editor/commands").Command[];
}
export interface VisibilitySelectorProps {

View File

@ -0,0 +1,347 @@
import { ArrowDownIcon, ArrowUpDownIcon, ArrowUpIcon, PlusIcon, TrashIcon } from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react";
import { cn } from "@/lib/utils";
import type { ColumnAlignment, TableData } from "@/utils/markdown-table";
import { createEmptyTable, serializeMarkdownTable } from "@/utils/markdown-table";
import { Button } from "./ui/button";
import { Dialog, DialogClose, DialogContent, DialogDescription, DialogTitle } from "./ui/dialog";
import { Tooltip, TooltipContent, TooltipTrigger } from "./ui/tooltip";
import { VisuallyHidden } from "./ui/visually-hidden";
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
interface TableEditorDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
/** Initial table data when editing an existing table. */
initialData?: TableData | null;
/** Called with the formatted markdown table string on confirm. */
onConfirm: (markdown: string) => void;
}
type SortState = { col: number; dir: "asc" | "desc" } | null;
// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------
const TableEditorDialog = ({ open, onOpenChange, initialData, onConfirm }: TableEditorDialogProps) => {
const [headers, setHeaders] = useState<string[]>([]);
const [rows, setRows] = useState<string[][]>([]);
const [alignments, setAlignments] = useState<ColumnAlignment[]>([]);
const [sortState, setSortState] = useState<SortState>(null);
// Ref grid for Tab navigation: inputRefs[row][col] (row -1 = headers).
const inputRefs = useRef<Map<string, HTMLInputElement>>(new Map());
const setInputRef = useCallback((key: string, el: HTMLInputElement | null) => {
if (el) {
inputRefs.current.set(key, el);
} else {
inputRefs.current.delete(key);
}
}, []);
// Initialize state when dialog opens.
useEffect(() => {
if (open) {
if (initialData) {
setHeaders([...initialData.headers]);
setRows(initialData.rows.map((r) => [...r]));
setAlignments([...initialData.alignments]);
} else {
const empty = createEmptyTable(3, 2);
setHeaders(empty.headers);
setRows(empty.rows);
setAlignments(empty.alignments);
}
setSortState(null);
}
}, [open, initialData]);
const colCount = headers.length;
const rowCount = rows.length;
// ---- Cell editing ----
const updateHeader = (col: number, value: string) => {
setHeaders((prev) => {
const next = [...prev];
next[col] = value;
return next;
});
};
const updateCell = (row: number, col: number, value: string) => {
setRows((prev) => {
const next = prev.map((r) => [...r]);
next[row][col] = value;
return next;
});
};
// ---- Add / Remove ----
const addColumn = () => {
setHeaders((prev) => [...prev, ""]);
setRows((prev) => prev.map((r) => [...r, ""]));
setAlignments((prev) => [...prev, "none"]);
setSortState(null);
};
const removeColumn = (col: number) => {
if (colCount <= 1) return;
setHeaders((prev) => prev.filter((_, i) => i !== col));
setRows((prev) => prev.map((r) => r.filter((_, i) => i !== col)));
setAlignments((prev) => prev.filter((_, i) => i !== col));
setSortState(null);
};
const addRow = () => {
setRows((prev) => [...prev, Array.from({ length: colCount }, () => "")]);
};
const removeRow = (row: number) => {
if (rowCount <= 1) return;
setRows((prev) => prev.filter((_, i) => i !== row));
};
// ---- Sorting ----
const sortByColumn = (col: number) => {
let newDir: "asc" | "desc" = "asc";
if (sortState && sortState.col === col && sortState.dir === "asc") {
newDir = "desc";
}
setSortState({ col, dir: newDir });
setRows((prev) => {
const sorted = [...prev].sort((a, b) => {
const va = (a[col] || "").toLowerCase();
const vb = (b[col] || "").toLowerCase();
// Try numeric comparison first.
const na = Number(va);
const nb = Number(vb);
if (!Number.isNaN(na) && !Number.isNaN(nb)) {
return newDir === "asc" ? na - nb : nb - na;
}
const cmp = va.localeCompare(vb);
return newDir === "asc" ? cmp : -cmp;
});
return sorted;
});
};
// ---- Tab / keyboard navigation ----
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>, row: number, col: number) => {
if (e.key === "Tab") {
e.preventDefault();
const nextCol = e.shiftKey ? col - 1 : col + 1;
let nextRow = row;
if (nextCol >= colCount) {
// Move to first cell of next row.
if (row < rowCount - 1) {
nextRow = row + 1;
focusCell(nextRow, 0);
} else {
// At last cell add a new row and focus it.
addRow();
// Need to wait for state update; use setTimeout.
setTimeout(() => focusCell(rowCount, 0), 0);
}
} else if (nextCol < 0) {
// Move to last cell of previous row.
if (row > 0) {
nextRow = row - 1;
focusCell(nextRow, colCount - 1);
} else {
// Move to header row.
focusCell(-1, colCount - 1);
}
} else {
focusCell(nextRow, nextCol);
}
}
};
const focusCell = (row: number, col: number) => {
const key = `${row}:${col}`;
const el = inputRefs.current.get(key);
el?.focus();
};
// ---- Confirm ----
const handleConfirm = () => {
const data: TableData = { headers, rows, alignments };
const md = serializeMarkdownTable(data);
onConfirm(md);
onOpenChange(false);
};
// ---- Sort indicator ----
const SortIndicator = ({ col }: { col: number }) => {
if (sortState?.col === col) {
return sortState.dir === "asc" ? <ArrowUpIcon className="size-3 text-primary" /> : <ArrowDownIcon className="size-3 text-primary" />;
}
return <ArrowUpDownIcon className="size-3 opacity-0 group-hover/sort:opacity-60" />;
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent size="2xl" className="p-0!" showCloseButton={false}>
<VisuallyHidden>
<DialogClose />
</VisuallyHidden>
<VisuallyHidden>
<DialogTitle>Table Editor</DialogTitle>
</VisuallyHidden>
<VisuallyHidden>
<DialogDescription>Edit table headers, rows, columns and sort data</DialogDescription>
</VisuallyHidden>
<div className="flex flex-col gap-0">
{/* Scrollable table area */}
<div className="overflow-auto max-h-[60vh] p-4 pb-2">
<table className="w-full border-collapse text-sm">
{/* Header row */}
<thead>
<tr>
{/* Row number column */}
<th className="w-8 min-w-8" />
{headers.map((header, col) => (
<th key={col} className="p-0 min-w-[120px]">
<div className="flex flex-col">
<div className="flex items-center gap-0.5">
<input
ref={(el) => setInputRef(`-1:${col}`, el)}
className="flex-1 min-w-0 px-2 py-1.5 font-semibold text-xs uppercase tracking-wide bg-accent/50 border border-border rounded-tl-md focus:outline-none focus:ring-1 focus:ring-primary/40"
value={header}
onChange={(e) => updateHeader(col, e.target.value)}
onKeyDown={(e) => handleKeyDown(e, -1, col)}
placeholder={`Col ${col + 1}`}
/>
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
className="group/sort flex items-center justify-center size-7 rounded hover:bg-accent transition-colors"
onClick={() => sortByColumn(col)}
>
<SortIndicator col={col} />
</button>
</TooltipTrigger>
<TooltipContent>Sort column</TooltipContent>
</Tooltip>
{colCount > 1 && (
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
className="flex items-center justify-center size-7 rounded opacity-0 hover:opacity-100 focus:opacity-100 group-hover:opacity-60 hover:bg-destructive/10 hover:text-destructive transition-all"
onClick={() => removeColumn(col)}
>
<TrashIcon className="size-3" />
</button>
</TooltipTrigger>
<TooltipContent>Remove column</TooltipContent>
</Tooltip>
)}
</div>
</div>
</th>
))}
{/* Add column button */}
<th className="w-8 min-w-8 align-middle">
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
className="flex items-center justify-center size-7 rounded hover:bg-accent transition-colors text-muted-foreground hover:text-foreground"
onClick={addColumn}
>
<PlusIcon className="size-3.5" />
</button>
</TooltipTrigger>
<TooltipContent>Add column</TooltipContent>
</Tooltip>
</th>
</tr>
</thead>
{/* Data rows */}
<tbody>
{rows.map((row, rowIdx) => (
<tr key={rowIdx} className="group">
{/* Row number + remove */}
<td className="w-8 min-w-8 text-center align-middle">
<div className="flex items-center justify-center">
<span className="text-xs text-muted-foreground group-hover:hidden">{rowIdx + 1}</span>
{rowCount > 1 && (
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
className="hidden group-hover:flex items-center justify-center size-6 rounded hover:bg-destructive/10 hover:text-destructive text-muted-foreground transition-all"
onClick={() => removeRow(rowIdx)}
>
<TrashIcon className="size-3" />
</button>
</TooltipTrigger>
<TooltipContent>Remove row</TooltipContent>
</Tooltip>
)}
</div>
</td>
{row.map((cell, col) => (
<td key={col} className="p-0">
<input
ref={(el) => setInputRef(`${rowIdx}:${col}`, el)}
className={cn(
"w-full px-2 py-1.5 text-sm bg-transparent border border-border focus:outline-none focus:ring-1 focus:ring-primary/40",
rowIdx === rowCount - 1 && "rounded-bl-md",
)}
value={cell}
onChange={(e) => updateCell(rowIdx, col, e.target.value)}
onKeyDown={(e) => handleKeyDown(e, rowIdx, col)}
placeholder="..."
/>
</td>
))}
<td className="w-8 min-w-8" />
</tr>
))}
</tbody>
</table>
{/* Add row button */}
<div className="flex justify-center mt-2">
<Button variant="ghost" size="sm" className="text-xs text-muted-foreground" onClick={addRow}>
<PlusIcon className="size-3.5" />
Add row
</Button>
</div>
</div>
{/* Footer */}
<div className="flex items-center justify-between px-4 py-3 border-t border-border">
<span className="text-xs text-muted-foreground">
{colCount} {colCount === 1 ? "column" : "columns"} · {rowCount} {rowCount === 1 ? "row" : "rows"}
</span>
<div className="flex items-center gap-2">
<Button variant="ghost" onClick={() => onOpenChange(false)}>
Cancel
</Button>
<Button onClick={handleConfirm}>Confirm</Button>
</div>
</div>
</div>
</DialogContent>
</Dialog>
);
};
export default TableEditorDialog;

View File

@ -0,0 +1,203 @@
/**
* Utilities for parsing, serializing, and manipulating markdown tables.
*/
export interface TableData {
headers: string[];
rows: string[][];
/** Column alignments: "left" | "center" | "right" | "none". */
alignments: ColumnAlignment[];
}
export type ColumnAlignment = "left" | "center" | "right" | "none";
// ---------------------------------------------------------------------------
// Parsing
// ---------------------------------------------------------------------------
/**
* Parse a markdown table string into structured TableData.
*
* Expects a standard GFM table:
* | Header1 | Header2 |
* | ------- | ------- |
* | cell | cell |
*/
export function parseMarkdownTable(md: string): TableData | null {
const lines = md
.trim()
.split("\n")
.map((l) => l.trim())
.filter((l) => l.length > 0);
if (lines.length < 2) return null;
const parseRow = (line: string): string[] => {
// Strip leading/trailing pipes and split by pipe.
let trimmed = line;
if (trimmed.startsWith("|")) trimmed = trimmed.slice(1);
if (trimmed.endsWith("|")) trimmed = trimmed.slice(0, -1);
return trimmed.split("|").map((cell) => cell.trim());
};
const headers = parseRow(lines[0]);
// Parse the separator line for alignments.
const sepCells = parseRow(lines[1]);
const isSeparator = sepCells.every((cell) => /^:?-+:?$/.test(cell.trim()));
if (!isSeparator) return null;
const alignments: ColumnAlignment[] = sepCells.map((cell) => {
const c = cell.trim();
const left = c.startsWith(":");
const right = c.endsWith(":");
if (left && right) return "center";
if (right) return "right";
if (left) return "left";
return "none";
});
const rows: string[][] = [];
for (let i = 2; i < lines.length; i++) {
const cells = parseRow(lines[i]);
// Pad or trim to match header count.
while (cells.length < headers.length) cells.push("");
if (cells.length > headers.length) cells.length = headers.length;
rows.push(cells);
}
return { headers, rows, alignments };
}
// ---------------------------------------------------------------------------
// Serialization
// ---------------------------------------------------------------------------
/**
* Serialize TableData into a properly-aligned markdown table string.
*/
export function serializeMarkdownTable(data: TableData): string {
const { headers, rows, alignments } = data;
const colCount = headers.length;
// Calculate maximum width per column (minimum 3 for the separator).
const widths: number[] = [];
for (let c = 0; c < colCount; c++) {
let max = Math.max(3, headers[c].length);
for (const row of rows) {
max = Math.max(max, (row[c] || "").length);
}
widths.push(max);
}
const padCell = (text: string, width: number, align: ColumnAlignment): string => {
const t = text || "";
const padding = width - t.length;
if (padding <= 0) return t;
if (align === "right") return " ".repeat(padding) + t;
if (align === "center") {
const left = Math.floor(padding / 2);
const right = padding - left;
return " ".repeat(left) + t + " ".repeat(right);
}
return t + " ".repeat(padding);
};
const formatRow = (cells: string[]): string => {
const formatted = cells.map((cell, i) => {
const align = alignments[i] || "none";
return padCell(cell, widths[i], align);
});
return "| " + formatted.join(" | ") + " |";
};
const separator = widths.map((w, i) => {
const align = alignments[i] || "none";
const dashes = "-".repeat(w);
if (align === "center") return ":" + dashes.slice(1, -1) + ":";
if (align === "right") return dashes.slice(0, -1) + ":";
if (align === "left") return ":" + dashes.slice(1);
return dashes;
});
const separatorLine = "| " + separator.join(" | ") + " |";
const headerLine = formatRow(headers);
const rowLines = rows.map((row) => formatRow(row));
return [headerLine, separatorLine, ...rowLines].join("\n");
}
// ---------------------------------------------------------------------------
// Find & Replace
// ---------------------------------------------------------------------------
/** Regex that matches a full markdown table block (one or more table lines). */
const TABLE_LINE = /^\s*\|.+\|\s*$/;
export interface TableMatch {
/** The raw markdown of the table. */
text: string;
/** Start index in the source string. */
start: number;
/** End index (exclusive) in the source string. */
end: number;
}
/**
* Find all markdown table blocks in a content string.
*/
export function findAllTables(content: string): TableMatch[] {
const lines = content.split("\n");
const tables: TableMatch[] = [];
let i = 0;
let offset = 0;
while (i < lines.length) {
if (TABLE_LINE.test(lines[i])) {
const startLine = i;
const startOffset = offset;
// Consume all consecutive table lines.
while (i < lines.length && TABLE_LINE.test(lines[i])) {
offset += lines[i].length + 1; // +1 for newline
i++;
}
const endOffset = offset - 1; // exclude trailing newline
const text = lines.slice(startLine, i).join("\n");
// Only count if it has at least a header + separator (2 lines).
if (i - startLine >= 2) {
tables.push({ text, start: startOffset, end: endOffset });
}
} else {
offset += lines[i].length + 1;
i++;
}
}
return tables;
}
/**
* Replace the nth table in the content with new markdown.
*/
export function replaceNthTable(content: string, tableIndex: number, newTableMarkdown: string): string {
const tables = findAllTables(content);
if (tableIndex < 0 || tableIndex >= tables.length) return content;
const table = tables[tableIndex];
return content.slice(0, table.start) + newTableMarkdown + content.slice(table.end);
}
// ---------------------------------------------------------------------------
// Default empty table
// ---------------------------------------------------------------------------
/**
* Create a default empty table with the given dimensions.
*/
export function createEmptyTable(cols = 2, rows = 2): TableData {
return {
headers: Array.from({ length: cols }, (_, i) => `Header ${i + 1}`),
rows: Array.from({ length: rows }, () => Array.from({ length: cols }, () => "")),
alignments: Array.from({ length: cols }, () => "none" as ColumnAlignment),
};
}