The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Make table rows and columns easier to remove in the editor.
Cursor Agentd23117bba2d7
diff --git a/apps/web/tests/misc/table-controls.test.tsx b/apps/web/tests/misc/table-controls.test.tsxnew file mode 100644index 0000000000..49aaf112b3--- /dev/null+++ b/apps/web/tests/misc/table-controls.test.tsx@@ -0,0 +1,100 @@+/** @vitest-environment happy-dom */+(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;+import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, describe, expect, it } from "vitest";+import {+ RichTextArea,+ RichTextProvider,+ RichTextToolbar,+} from "../../../../packages/ui/src/rich-text-area";++const TWO_ROW_TABLE = `+ <table>+ <tbody>+ <tr><th><p></p></th><th><p></p></th></tr>+ <tr><td><p>Keep</p></td><td><p>Me</p></td></tr>+ </tbody>+ </table>+`;++let root: Root | null = null;++afterEach(() => {+ act(() => {+ root?.unmount();+ });+ root = null;+ document.body.innerHTML = "";+});++async function renderEditor() {+ const container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);++ await act(async () => {+ root?.render(+ <RichTextProvider+ features={[+ "bold",+ "italic",+ "strike",+ "headings",+ "lists",+ "tables",+ "quote",+ "links",+ ]}+ initialValue={TWO_ROW_TABLE}+ >+ <RichTextArea />+ <RichTextToolbar />+ </RichTextProvider>,+ );+ });++ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 0));+ });++ return container;+}++describe("landing page table controls", () => {+ it("shows toolbar tooltips and a delete button for the active row", async () => {+ const container = await renderEditor();++ for (const label of ["Bold", "Italic", "Table", "Link"]) {+ const button = container.querySelector(`button[aria-label="${label}"]`);+ expect(button, label).toBeTruthy();+ expect(button?.getAttribute("title")).toBeNull();+ }++ const editorDom = container.querySelector(".ProseMirror");+ expect(editorDom).toBeTruthy();++ await act(async () => {+ (editorDom as HTMLElement).focus();+ });++ const deleteRow = document.body.querySelector(+ 'button[aria-label="Delete row"]',+ );+ const deleteColumn = document.body.querySelector(+ 'button[aria-label="Delete column"]',+ );+ expect(deleteRow).toBeTruthy();+ expect(deleteColumn).toBeTruthy();++ await act(async () => {+ deleteRow?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });++ expect(container.textContent).toContain("Keep");+ expect(container.textContent).toContain("Me");+ expect(container.querySelectorAll("tr")).toHaveLength(1);+ });+});diff --git a/apps/web/tests/misc/table-keyboard.test.ts b/apps/web/tests/misc/table-keyboard.test.tsnew file mode 100644index 0000000000..8a654a6121--- /dev/null+++ b/apps/web/tests/misc/table-keyboard.test.ts@@ -0,0 +1,162 @@+/** @vitest-environment happy-dom */+import { afterEach, describe, expect, it } from "vitest";+import {+ deleteEditorColumn,+ deleteEditorRow,+ deleteTableStructureOnKey,+ textPosInCell,+} from "../../../../packages/ui/src/rich-text-area/table-keyboard";+import {+ columnCount,+ createTableEditor,+ rowCount,+ selectCellRange,+ setCaretAtText,+ setCaretInParagraph,+} from "../../../../packages/ui/src/rich-text-area/table-keyboard.harness";++const editors: ReturnType<typeof createTableEditor>[] = [];++function createEditor(html: string) {+ const editor = createTableEditor(html);+ editors.push(editor);+ return editor;+}++afterEach(() => {+ editors.splice(0).forEach((editor) => editor.destroy());+ document.body.innerHTML = "";+});++function key(name: string, modifiers: Partial<KeyboardEventInit> = {}) {+ return new KeyboardEvent("keydown", { key: name, ...modifiers });+}++const TWO_ROW_TABLE = `+ <table>+ <tbody>+ <tr><th><p></p></th><th><p></p></th></tr>+ <tr><td><p>Keep</p></td><td><p>Me</p></td></tr>+ </tbody>+ </table>+`;++describe("table keyboard deletion", () => {+ it("removes an empty row with Backspace or Delete and leaves the other row", () => {+ const editor = createEditor(TWO_ROW_TABLE);+ setCaretInParagraph(editor, 0);++ expect(deleteTableStructureOnKey(editor, key("Backspace"))).toBe(true);+ expect(rowCount(editor)).toBe(1);+ expect(editor.getText()).toContain("Keep");+ expect(editor.getText()).toContain("Me");++ const remaining = createEditor(TWO_ROW_TABLE);+ setCaretInParagraph(remaining, 0);+ expect(deleteTableStructureOnKey(remaining, key("Delete"))).toBe(true);+ expect(rowCount(remaining)).toBe(1);+ });++ it("does not remove a row that still has text", () => {+ const editor = createEditor(TWO_ROW_TABLE);+ setCaretAtText(editor, "Keep", 0);++ expect(deleteTableStructureOnKey(editor, key("Backspace"))).toBe(false);+ expect(rowCount(editor)).toBe(2);+ expect(editor.getText()).toContain("Keep");++ setCaretAtText(editor, "Keep", 2);+ expect(deleteTableStructureOnKey(editor, key("Backspace"))).toBe(false);+ expect(editor.getText()).toContain("Keep");+ });++ it("ignores Backspace outside a table and modified Backspace inside one", () => {+ const editor = createEditor("<p>Hello</p>");+ editor.commands.focus("start");+ expect(deleteTableStructureOnKey(editor, key("Backspace"))).toBe(false);+ expect(editor.getText()).toBe("Hello");++ const table = createEditor(TWO_ROW_TABLE);+ setCaretInParagraph(table, 0);+ expect(+ deleteTableStructureOnKey(table, key("Backspace", { metaKey: true })),+ ).toBe(false);+ expect(rowCount(table)).toBe(2);+ });++ it("treats a whitespace-only row as empty", () => {+ const editor = createEditor(`+ <table>+ <tbody>+ <tr><td><p> </p></td></tr>+ <tr><td><p>Stay</p></td></tr>+ </tbody>+ </table>+ `);+ setCaretInParagraph(editor, 0);++ expect(deleteTableStructureOnKey(editor, key("Backspace"))).toBe(true);+ expect(editor.getText()).toContain("Stay");+ expect(rowCount(editor)).toBe(1);+ });++ it("replaces a table with a paragraph when its last row is removed", () => {+ const editor = createEditor(`+ <table>+ <tbody>+ <tr><td><p></p></td><td><p></p></td></tr>+ </tbody>+ </table>+ `);+ setCaretInParagraph(editor, 0);++ expect(deleteTableStructureOnKey(editor, key("Backspace"))).toBe(true);+ expect(rowCount(editor)).toBe(0);+ expect(editor.getHTML()).toContain("<p>");+ expect(editor.getText()).toBe("");+ });++ it("deletes the hovered cell's row after resolving that cell in the editor", () => {+ const editor = createEditor(TWO_ROW_TABLE);+ const cell = editor.view.dom.querySelector("td");+ if (!(cell instanceof HTMLTableCellElement)) {+ throw new Error("Missing table cell");+ }++ const pos = textPosInCell(editor, editor.view.posAtDOM(cell, 0));+ editor.chain().focus().setTextSelection(pos).run();+ expect(editor.state.selection.$from.parent.textContent).toBe("Keep");+ expect(deleteEditorRow(editor)).toBe(true);+ expect(editor.getText()).not.toContain("Keep");+ expect(editor.getText()).not.toContain("Me");+ expect(rowCount(editor)).toBe(1);+ });++ it("deletes a row or column that still has text from the row and column actions", () => {+ const editor = createEditor(TWO_ROW_TABLE);+ setCaretAtText(editor, "Me", 1);++ expect(deleteEditorColumn(editor)).toBe(true);+ expect(columnCount(editor)).toBe(1);+ expect(editor.getText()).toContain("Keep");+ expect(editor.getText()).not.toContain("Me");++ setCaretAtText(editor, "Keep", 1);+ expect(deleteEditorRow(editor)).toBe(true);+ expect(rowCount(editor)).toBe(1);+ expect(editor.getText()).not.toContain("Keep");+ });++ it("removes a fully selected row and leaves the table alone when every cell is selected", () => {+ const editor = createEditor(TWO_ROW_TABLE);+ selectCellRange(editor, 0, 1);++ expect(deleteTableStructureOnKey(editor, key("Backspace"))).toBe(true);+ expect(rowCount(editor)).toBe(1);+ expect(editor.getText()).toContain("Keep");++ selectCellRange(editor, 0, 1);+ expect(deleteTableStructureOnKey(editor, key("Delete"))).toBe(false);+ expect(rowCount(editor)).toBe(1);+ });+});diff --git a/packages/ui/src/rich-text-area/icon-tooltip.tsx b/packages/ui/src/rich-text-area/icon-tooltip.tsxnew file mode 100644index 0000000000..e4eb131ed8--- /dev/null+++ b/packages/ui/src/rich-text-area/icon-tooltip.tsx@@ -0,0 +1,37 @@+"use client";++import * as TooltipPrimitive from "@radix-ui/react-tooltip";+import { ReactNode } from "react";++export function IconTooltipProvider({ children }: { children: ReactNode }) {+ return (+ <TooltipPrimitive.Provider delayDuration={250}>+ {children}+ </TooltipPrimitive.Provider>+ );+}++export function IconTooltip({+ label,+ side = "top",+ children,+}: {+ label: string;+ side?: "top" | "right" | "bottom" | "left";+ children: ReactNode;+}) {+ return (+ <TooltipPrimitive.Root disableHoverableContent>+ <TooltipPrimitive.Trigger asChild>{children}</TooltipPrimitive.Trigger>+ <TooltipPrimitive.Portal>+ <TooltipPrimitive.Content+ side={side}+ sideOffset={6}+ className="animate-slide-up-fade border-border-default bg-bg-default text-content-default z-[110] rounded-lg border px-2 py-1 text-xs font-medium shadow-sm"+ >+ {label}+ </TooltipPrimitive.Content>+ </TooltipPrimitive.Portal>+ </TooltipPrimitive.Root>+ );+}diff --git a/packages/ui/src/rich-text-area/rich-text-provider.tsx b/packages/ui/src/rich-text-area/rich-text-provider.tsxindex 38e48e85e0..17e3b2cac8 100644--- a/packages/ui/src/rich-text-area/rich-text-provider.tsx+++ b/packages/ui/src/rich-text-area/rich-text-provider.tsx@@ -24,6 +24,7 @@ import { configureCampaignEditorImage } from "./campaign-editor-image";import { RichTextLinkHoverTooltip } from "./link-hover-tooltip";import { RichTextLinkModal } from "./link-modal";import { TableHoverControls } from "./table-hover-controls";+import { deleteTableStructureOnKey } from "./table-keyboard";import { RichTextVariableInfo, suggestions } from "./variables";export const PROSE_STYLES = {@@ -416,6 +417,20 @@ export const RichTextProvider = forwardRef<);return true;},+ handleKeyDown: (view, event) => {+ if (editorProps?.handleKeyDown?.(view, event)) return true;++ const currentEditor = editorRef.current;+ if (+ currentEditor &&+ features.includes("tables") &&+ deleteTableStructureOnKey(currentEditor, event)+ ) {+ return true;+ }++ return false;+ },handleClick: (view, pos, event) => {if (editorProps?.handleClick?.(view, pos, event)) return true;diff --git a/packages/ui/src/rich-text-area/rich-text-toolbar.tsx b/packages/ui/src/rich-text-area/rich-text-toolbar.tsxindex 5d9b7d3d34..6bfb4812f0 100644--- a/packages/ui/src/rich-text-area/rich-text-toolbar.tsx+++ b/packages/ui/src/rich-text-area/rich-text-toolbar.tsx@@ -1,6 +1,12 @@import { cn, isSafeLinkHref } from "@dub/utils";import { useEditorState } from "@tiptap/react";-import { ReactNode, forwardRef, useRef } from "react";+import {+ ButtonHTMLAttributes,+ MouseEventHandler,+ ReactNode,+ forwardRef,+ useRef,+} from "react";import { toast } from "sonner";import {AtSign,@@ -18,6 +24,7 @@ import {TextItalic,TextStrike,} from "../icons";+import { IconTooltip, IconTooltipProvider } from "./icon-tooltip";import { useRichTextContext } from "./rich-text-provider";export function RichTextToolbar({@@ -51,147 +58,151 @@ export function RichTextToolbar({const inputImageRef = useRef<HTMLInputElement>(null);return (- <div- className={cn(- "flex gap-1",- isUploading && "pointer-events-none opacity-50",- className,- )}- >- {toolsStart}+ <IconTooltipProvider>+ <div+ className={cn(+ "flex gap-1",+ isUploading && "pointer-events-none opacity-50",+ className,+ )}+ >+ {toolsStart}- {features?.includes("bold") && (- <RichTextToolbarButton- icon={TextBold}- label="Bold"- isActive={editorState?.isBold}- onClick={() => editor?.chain().focus().toggleBold().run()}- />- )}- {features?.includes("italic") && (- <RichTextToolbarButton- icon={TextItalic}- label="Italic"- isActive={editorState?.isItalic}- onClick={() => editor?.chain().focus().toggleItalic().run()}- />- )}- {features?.includes("strike") && (- <RichTextToolbarButton- icon={TextStrike}- label="Strikethrough"- isActive={editorState?.isStrike}- onClick={() => editor?.chain().focus().toggleStrike().run()}- />- )}- {features?.includes("headings") && (- <>+ {features?.includes("bold") && (<RichTextToolbarButton- icon={Heading1}- label="Heading 1"- isActive={editorState?.isHeading1}- onClick={() =>- editor?.chain().focus().toggleHeading({ level: 1 }).run()- }+ icon={TextBold}+ label="Bold"+ isActive={editorState?.isBold}+ onClick={() => editor?.chain().focus().toggleBold().run()}/>+ )}+ {features?.includes("italic") && (<RichTextToolbarButton- icon={Heading2}- label="Heading 2"- isActive={editorState?.isHeading2}+ icon={TextItalic}+ label="Italic"+ isActive={editorState?.isItalic}+ onClick={() => editor?.chain().focus().toggleItalic().run()}+ />+ )}+ {features?.includes("strike") && (+ <RichTextToolbarButton+ icon={TextStrike}+ label="Strikethrough"+ isActive={editorState?.isStrike}+ onClick={() => editor?.chain().focus().toggleStrike().run()}+ />+ )}+ {features?.includes("headings") && (+ <>+ <RichTextToolbarButton+ icon={Heading1}+ label="Heading 1"+ isActive={editorState?.isHeading1}+ onClick={() =>+ editor?.chain().focus().toggleHeading({ level: 1 }).run()+ }+ />+ <RichTextToolbarButton+ icon={Heading2}+ label="Heading 2"+ isActive={editorState?.isHeading2}+ onClick={() =>+ editor?.chain().focus().toggleHeading({ level: 2 }).run()+ }+ />+ </>+ )}+ {features?.includes("lists") && (+ <>+ <RichTextToolbarButton+ icon={BulletList}+ label="Bullet list"+ isActive={editorState?.isBulletList}+ onClick={() => editor?.chain().focus().toggleBulletList().run()}+ />+ <RichTextToolbarButton+ icon={NumberedList}+ label="Numbered list"+ isActive={editorState?.isOrderedList}+ onClick={() => editor?.chain().focus().toggleOrderedList().run()}+ />+ </>+ )}+ {features?.includes("tables") && (+ <RichTextToolbarButton+ icon={TableIcon}+ label="Table"+ isActive={false}onClick={() =>- editor?.chain().focus().toggleHeading({ level: 2 }).run()+ editor+ ?.chain()+ .focus()+ .insertTable({ rows: 3, cols: 3, withHeaderRow: true })+ .run()}/>- </>- )}- {features?.includes("lists") && (- <>+ )}+ {features?.includes("quote") && (<RichTextToolbarButton- icon={BulletList}- label="Bullet list"- isActive={editorState?.isBulletList}- onClick={() => editor?.chain().focus().toggleBulletList().run()}+ icon={Quote}+ label="Quote"+ isActive={editorState?.isBlockquote}+ onClick={() => editor?.chain().focus().toggleBlockquote().run()}/>+ )}+ {features?.includes("code") && (<RichTextToolbarButton- icon={NumberedList}- label="Numbered list"- isActive={editorState?.isOrderedList}- onClick={() => editor?.chain().focus().toggleOrderedList().run()}- />- </>- )}- {features?.includes("tables") && (- <RichTextToolbarButton- icon={TableIcon}- label="Table"- isActive={false}- onClick={() =>- editor- ?.chain()- .focus()- .insertTable({ rows: 3, cols: 3, withHeaderRow: true })- .run()- }- />- )}- {features?.includes("quote") && (- <RichTextToolbarButton- icon={Quote}- label="Quote"- isActive={editorState?.isBlockquote}- onClick={() => editor?.chain().focus().toggleBlockquote().run()}- />- )}- {features?.includes("code") && (- <RichTextToolbarButton- icon={Code}- label="Inline code"- isActive={editorState?.isCode}- onClick={() => editor?.chain().focus().toggleCode().run()}- />- )}- {features?.includes("links") && <LinkButton />}- {features?.includes("variables") && (- <RichTextToolbarButton- icon={AtSign}- label="Variable"- isActive={false}- onClick={() => {- if (editor?.state.selection.$from.nodeBefore?.text?.endsWith("@")) {- editor?.commands.focus();- return;- }- editor?.chain().focus().insertContent("@").run();- }}- />- )}-- {features?.includes("images") && handleImageUpload && editor && (- <>- <input- ref={inputImageRef}- type="file"- accept={imageAccept}- className="hidden"- onChange={(e) => {- const file = e.target.files?.[0];- if (!file) return;-- handleImageUpload(file, editor, editor.state.selection.anchor);- e.target.value = "";- }}+ icon={Code}+ label="Inline code"+ isActive={editorState?.isCode}+ onClick={() => editor?.chain().focus().toggleCode().run()}/>+ )}+ {features?.includes("links") && <LinkButton />}+ {features?.includes("variables") && (<RichTextToolbarButton- icon={ImageIcon}- label="Image"+ icon={AtSign}+ label="Variable"isActive={false}- onClick={() => inputImageRef.current?.click()}+ onClick={() => {+ if (+ editor?.state.selection.$from.nodeBefore?.text?.endsWith("@")+ ) {+ editor?.commands.focus();+ return;+ }+ editor?.chain().focus().insertContent("@").run();+ }}/>- </>- )}+ )}++ {features?.includes("images") && handleImageUpload && editor && (+ <>+ <input+ ref={inputImageRef}+ type="file"+ accept={imageAccept}+ className="hidden"+ onChange={(e) => {+ const file = e.target.files?.[0];+ if (!file) return;- {toolsEnd}- </div>+ handleImageUpload(file, editor, editor.state.selection.anchor);+ e.target.value = "";+ }}+ />+ <RichTextToolbarButton+ icon={ImageIcon}+ label="Image"+ isActive={false}+ onClick={() => inputImageRef.current?.click()}+ />+ </>+ )}++ {toolsEnd}+ </div>+ </IconTooltipProvider>);}@@ -273,9 +284,9 @@ type RichTextToolbarButtonProps = {icon: Icon;label?: string;isActive?: boolean;- onClick?: () => void;+ onClick?: MouseEventHandler<HTMLButtonElement>;disabled?: boolean;-};+} & Omit<ButtonHTMLAttributes<HTMLButtonElement>, "onClick" | "disabled">;export const RichTextToolbarButton = forwardRef<HTMLButtonElement,@@ -288,26 +299,34 @@ export const RichTextToolbarButton = forwardRef<isActive,onClick,disabled,+ className,+ ...rest}: RichTextToolbarButtonProps,ref,) => {- return (+ const button = (<button+ {...rest}ref={ref}type="button"onClick={onClick}disabled={disabled}+ aria-label={label}className={cn("flex size-8 items-center justify-center rounded-md transition-colors duration-150 disabled:opacity-50",isActive? "bg-neutral-200": "hover:bg-neutral-50 active:bg-neutral-100",+ className,)}- title={label}><Icon className="size-4 shrink-0 text-neutral-700" />{label && <span className="sr-only">{label}</span>}</button>);++ if (!label) return button;++ return <IconTooltip label={label}>{button}</IconTooltip>;},);diff --git a/packages/ui/src/rich-text-area/table-hover-controls.tsx b/packages/ui/src/rich-text-area/table-hover-controls.tsxindex 41700543aa..ee104cfbf3 100644--- a/packages/ui/src/rich-text-area/table-hover-controls.tsx+++ b/packages/ui/src/rich-text-area/table-hover-controls.tsx@@ -1,76 +1,111 @@"use client";import { cn } from "@dub/utils";+import { CellSelection } from "@tiptap/pm/tables";import type { Editor } from "@tiptap/react";import { CSSProperties, ReactNode, useEffect, useState } from "react";import { createPortal } from "react-dom";-import { GripDotsVertical, Plus } from "../icons";+import { GripDotsVertical, Plus, Trash } from "../icons";+import { IconTooltip, IconTooltipProvider } from "./icon-tooltip";import { useRichTextContext } from "./rich-text-provider";+import {+ deleteEditorColumn,+ deleteEditorRow,+ deleteEditorTable,+ textPosInCell,+} from "./table-keyboard";const CONTROL_ATTR = "data-table-controls";const EDGE_PX = 10;-type HoverZone =- | {- kind: "add-row";- table: HTMLTableElement;- }- | {- kind: "add-col";- table: HTMLTableElement;- }- | {- kind: "row";- table: HTMLTableElement;- row: HTMLTableRowElement;- cell: HTMLTableCellElement;- }- | {- kind: "col";- table: HTMLTableElement;- cell: HTMLTableCellElement;- };+type CellTarget = {+ table: HTMLTableElement;+ row: HTMLTableRowElement;+ cell: HTMLTableCellElement;+};++type PointerTarget = {+ table: HTMLTableElement;+ cell: HTMLTableCellElement | null;+ addRow: boolean;+ addCol: boolean;+};type MenuState = {kind: "row" | "col";cellPos: number;+ target: CellTarget;};export function TableHoverControls() {const { editor, editable } = useRichTextContext();- const [zone, setZone] = useState<HoverZone | null>(null);+ const [pointer, setPointer] = useState<PointerTarget | null>(null);+ const [selectionTarget, setSelectionTarget] = useState<CellTarget | null>(+ null,+ );+ const [editorFocused, setEditorFocused] = useState(false);const [menu, setMenu] = useState<MenuState | null>(null);const [, setTick] = useState(0);useEffect(() => {- if (!editor || editable === false) return;+ if (!editor || editable === false || editor.isDestroyed) return;++ let editorDom: HTMLElement;+ try {+ editorDom = editor.view.dom as HTMLElement;+ } catch {+ return;+ }++ const remeasure = () => setTick((value) => value + 1);- const remasure = () => setTick((value) => value + 1);- const editorDom = editor.view.dom as HTMLElement;+ const syncSelection = () => {+ setSelectionTarget(cellTargetFromSelection(editor));+ setMenu((current) => (current?.target.cell.isConnected ? current : null));+ setPointer((current) => (current?.table.isConnected ? current : null));+ };++ const syncFocus = () => {+ const active = document.activeElement;+ setEditorFocused(active === editorDom || editorDom.contains(active));+ };const onMouseMove = (event: MouseEvent) => {const el = document.elementFromPoint(event.clientX, event.clientY);if (el instanceof Element && el.closest(`[${CONTROL_ATTR}]`)) return;if (menu) return;- setZone(getHoverZone(event.clientX, event.clientY, editorDom));+ setPointer((current) => {+ const next = getPointerTarget(event.clientX, event.clientY, editorDom);+ return samePointer(current, next) ? current : next;+ });};+ syncSelection();+ syncFocus();document.addEventListener("mousemove", onMouseMove);- window.addEventListener("scroll", remasure, true);- window.addEventListener("resize", remasure);- editor.on("update", remasure);+ editorDom.addEventListener("focusin", syncFocus);+ editorDom.addEventListener("focusout", syncFocus);+ window.addEventListener("scroll", remeasure, true);+ window.addEventListener("resize", remeasure);+ editor.on("selectionUpdate", syncSelection);+ editor.on("update", syncSelection);+ editor.on("update", remeasure);return () => {document.removeEventListener("mousemove", onMouseMove);- window.removeEventListener("scroll", remasure, true);- window.removeEventListener("resize", remasure);- editor.off("update", remasure);+ editorDom.removeEventListener("focusin", syncFocus);+ editorDom.removeEventListener("focusout", syncFocus);+ window.removeEventListener("scroll", remeasure, true);+ window.removeEventListener("resize", remeasure);+ editor.off("selectionUpdate", syncSelection);+ editor.off("update", syncSelection);+ editor.off("update", remeasure);};}, [editor, editable, menu]);useEffect(() => {- if (!menu) return;+ if (!menu || !editor) return;const onPointerDown = (event: PointerEvent) => {if (@@ -92,314 +127,409 @@ export function TableHoverControls() {document.removeEventListener("pointerdown", onPointerDown);document.removeEventListener("keydown", onKeyDown);};- }, [menu]);+ }, [menu, editor]);- if (!editor || editable === false || !zone?.table.isConnected) {+ if (!editor || editable === false || editor.isDestroyed) return null;++ let editorDom: HTMLElement;+ try {+ editorDom = editor.view.dom as HTMLElement;+ } catch {return null;}+ const pointerCell = pointer?.cell ? targetFromCell(pointer.cell) : null;+ const active =+ (menu?.target.cell.isConnected ? menu.target : null) ??+ (pointerCell?.cell.isConnected ? pointerCell : null) ??+ (editorFocused && selectionTarget?.cell.isConnected+ ? selectionTarget+ : null);- const tableRect = zone.table.getBoundingClientRect();- const visible = intersectRect(- tableRect,- (editor.view.dom as HTMLElement).getBoundingClientRect(),- );+ const edgeTable = pointer?.table.isConnected ? pointer.table : null;++ if (!active && !edgeTable) return null;const runOnCell = (cellPos: number, command: () => void) => {editor.chain().focus().setTextSelection(cellPos).run();command();setMenu(null);- setZone(null);+ setPointer(null);};- const lastRowCell = zone.table.rows[zone.table.rows.length - 1]?.cells[0];- const lastColCell =- zone.table.rows[0]?.cells[zone.table.rows[0].cells.length - 1];-- const addRowPos = visible && {- x: visible.left + visible.width / 2,- y: tableRect.bottom,- };-- const addColPos = visible && {- x: tableRect.right,- y: visible.top + visible.height / 2,- };+ const tableForEdge = edgeTable ?? active?.table ?? null;+ const lastRowCell =+ tableForEdge?.rows[tableForEdge.rows.length - 1]?.cells[0] ?? null;+ const lastColCell = tableForEdge?.rows[0]+ ? tableForEdge.rows[0].cells[tableForEdge.rows[0].cells.length - 1]+ : null;++ const tableRect = tableForEdge?.getBoundingClientRect();+ const visible =+ tableRect && intersectRect(tableRect, editorDom.getBoundingClientRect());++ const addRowPos =+ pointer?.addRow && visible && tableRect+ ? { x: visible.left + visible.width / 2, y: tableRect.bottom }+ : null;+ const addColPos =+ pointer?.addCol && visible && tableRect+ ? { x: tableRect.right, y: visible.top + visible.height / 2 }+ : null;let menuPos: { top: number; left: number } | null = null;- if (menu && zone.kind === "row") {- const rowRect = zone.row.getBoundingClientRect();- menuPos = {- top: rowRect.top + rowRect.height / 2,- left: tableRect.left - 16,- };- } else if (menu && zone.kind === "col") {- const colRect = getColumnRect(zone.table, zone.cell.cellIndex);- if (colRect) {+ if (menu && active) {+ const anchorRect = active.table.getBoundingClientRect();+ if (menu.kind === "row") {+ const rowRect = active.row.getBoundingClientRect();menuPos = {- top: tableRect.top - 16,- left: colRect.left + colRect.width / 2,+ top: rowRect.top + rowRect.height / 2,+ left: anchorRect.left - 16,};+ } else {+ const colRect = getColumnRect(active.table, active.cell.cellIndex);+ if (colRect) {+ menuPos = {+ top: anchorRect.top - 16,+ left: colRect.left + colRect.width / 2,+ };+ }}}return createPortal(- <div className="pointer-events-none fixed inset-0 z-[99]">- {zone.kind === "add-row" && lastRowCell && addRowPos && (- <ControlButton- label="Add row"- style={{- top: addRowPos.y,- left: addRowPos.x,- transform: "translate(-50%, -50%)",- }}- onClick={() =>- runOnCell(posAtCell(editor, lastRowCell), () =>- editor.chain().focus().addRowAfter().run(),- )- }- >- <Plus className="size-3.5" />- </ControlButton>- )}-- {zone.kind === "add-col" && lastColCell && addColPos && (- <ControlButton- label="Add column"- style={{- top: addColPos.y,- left: addColPos.x,- transform: "translate(-50%, -50%)",- }}- onClick={() =>- runOnCell(posAtCell(editor, lastColCell), () =>- editor.chain().focus().addColumnAfter().run(),- )- }- >- <Plus className="size-3.5" />- </ControlButton>- )}-- {zone.kind === "row" && (- <RowHandle editor={editor} zone={zone} menu={menu} setMenu={setMenu} />- )}-- {zone.kind === "col" && (- <ColumnHandle- editor={editor}- zone={zone}- menu={menu}- setMenu={setMenu}- />- )}-- {menu && menuPos && (- <div- data-table-controls=""- className="pointer-events-auto absolute min-w-36 rounded-lg border border-neutral-200 bg-white p-1 shadow-md"- style={{- top: menuPos.top,- left: menuPos.left,- transform:- menu.kind === "row"- ? "translate(-100%, -50%)"- : "translate(-50%, -100%)",- }}- >- {menu.kind === "row" ? (- <>- <MenuButton- onClick={() =>- runOnCell(menu.cellPos, () =>- editor.chain().focus().addRowBefore().run(),- )- }- >- Insert row above- </MenuButton>- <MenuButton- onClick={() =>- runOnCell(menu.cellPos, () =>- editor.chain().focus().addRowAfter().run(),- )- }- >- Insert row below- </MenuButton>- <MenuButton- danger- onClick={() =>- runOnCell(menu.cellPos, () =>- editor.chain().focus().deleteRow().run(),- )- }- >- Delete row- </MenuButton>- <div className="my-1 h-px bg-neutral-200" />- <MenuButton- danger- onClick={() =>- runOnCell(menu.cellPos, () =>- editor.chain().focus().deleteTable().run(),- )- }- >- Delete table- </MenuButton>- </>- ) : (- <>- <MenuButton- onClick={() =>- runOnCell(menu.cellPos, () =>- editor.chain().focus().addColumnBefore().run(),- )- }- >- Insert column left- </MenuButton>- <MenuButton- onClick={() =>- runOnCell(menu.cellPos, () =>- editor.chain().focus().addColumnAfter().run(),- )- }- >- Insert column right- </MenuButton>- <MenuButton- danger- onClick={() =>- runOnCell(menu.cellPos, () =>- editor.chain().focus().deleteColumn().run(),- )- }- >- Delete column- </MenuButton>- <div className="my-1 h-px bg-neutral-200" />- <MenuButton- danger- onClick={() =>- runOnCell(menu.cellPos, () =>- editor.chain().focus().deleteTable().run(),- )- }- >- Delete table- </MenuButton>- </>- )}- </div>- )}- </div>,+ <IconTooltipProvider>+ <div className="pointer-events-none fixed inset-0 z-[99]">+ {addRowPos && lastRowCell && (+ <ControlButton+ label="Add row"+ className="absolute"+ style={{+ top: addRowPos.y,+ left: addRowPos.x,+ transform: "translate(-50%, -50%)",+ }}+ onClick={() =>+ runOnCell(posAtCell(editor, lastRowCell), () =>+ editor.chain().focus().addRowAfter().run(),+ )+ }+ >+ <Plus className="size-3.5" />+ </ControlButton>+ )}++ {addColPos && lastColCell && (+ <ControlButton+ label="Add column"+ className="absolute"+ style={{+ top: addColPos.y,+ left: addColPos.x,+ transform: "translate(-50%, -50%)",+ }}+ onClick={() =>+ runOnCell(posAtCell(editor, lastColCell), () =>+ editor.chain().focus().addColumnAfter().run(),+ )+ }+ >+ <Plus className="size-3.5" />+ </ControlButton>+ )}++ {active && (+ <RowControls+ editor={editor}+ editorDom={editorDom}+ target={active}+ menu={menu}+ onDelete={(cellPos) =>+ runOnCell(cellPos, () => deleteEditorRow(editor))+ }+ onToggleMenu={(next) => setMenu(next)}+ />+ )}++ {active && (+ <ColumnControls+ editor={editor}+ editorDom={editorDom}+ target={active}+ menu={menu}+ onDelete={(cellPos) =>+ runOnCell(cellPos, () => deleteEditorColumn(editor))+ }+ onToggleMenu={(next) => setMenu(next)}+ />+ )}++ {menu && menuPos && (+ <div+ data-table-controls=""+ className="pointer-events-auto absolute min-w-36 rounded-lg border border-neutral-200 bg-white p-1 shadow-md"+ style={{+ top: menuPos.top,+ left: menuPos.left,+ transform:+ menu.kind === "row"+ ? "translate(-100%, -50%)"+ : "translate(-50%, -100%)",+ }}+ >+ {menu.kind === "row" ? (+ <>+ <MenuButton+ onClick={() =>+ runOnCell(menu.cellPos, () =>+ editor.chain().focus().addRowBefore().run(),+ )+ }+ >+ Insert row above+ </MenuButton>+ <MenuButton+ onClick={() =>+ runOnCell(menu.cellPos, () =>+ editor.chain().focus().addRowAfter().run(),+ )+ }+ >+ Insert row below+ </MenuButton>+ <MenuButton+ danger+ onClick={() =>+ runOnCell(menu.cellPos, () => deleteEditorRow(editor))+ }+ >+ Delete row+ </MenuButton>+ <div className="my-1 h-px bg-neutral-200" />+ <MenuButton+ danger+ onClick={() =>+ runOnCell(menu.cellPos, () => deleteEditorTable(editor))+ }+ >+ Delete table+ </MenuButton>+ </>+ ) : (+ <>+ <MenuButton+ onClick={() =>+ runOnCell(menu.cellPos, () =>+ editor.chain().focus().addColumnBefore().run(),+ )+ }+ >+ Insert column left+ </MenuButton>+ <MenuButton+ onClick={() =>+ runOnCell(menu.cellPos, () =>+ editor.chain().focus().addColumnAfter().run(),+ )+ }+ >+ Insert column right+ </MenuButton>+ <MenuButton+ danger+ onClick={() =>+ runOnCell(menu.cellPos, () => deleteEditorColumn(editor))+ }+ >+ Delete column+ </MenuButton>+ <div className="my-1 h-px bg-neutral-200" />+ <MenuButton+ danger+ onClick={() =>+ runOnCell(menu.cellPos, () => deleteEditorTable(editor))+ }+ >+ Delete table+ </MenuButton>+ </>+ )}+ </div>+ )}+ </div>+ </IconTooltipProvider>,document.body,);}-function RowHandle({+function RowControls({editor,- zone,+ editorDom,+ target,menu,- setMenu,+ onDelete,+ onToggleMenu,}: {editor: Editor;- zone: Extract<HoverZone, { kind: "row" }>;+ editorDom: HTMLElement;+ target: CellTarget;menu: MenuState | null;- setMenu: (menu: MenuState | null) => void;+ onDelete: (cellPos: number) => void;+ onToggleMenu: (menu: MenuState | null) => void;}) {- const tableRect = zone.table.getBoundingClientRect();- const rowRect = zone.row.getBoundingClientRect();+ const editorRect = editorDom.getBoundingClientRect();+ const tableRect = target.table.getBoundingClientRect();+ const rowRect = target.row.getBoundingClientRect();++ if (rowRect.bottom < editorRect.top || rowRect.top > editorRect.bottom) {+ return null;+ }+ if (tableRect.right < editorRect.left || tableRect.left > editorRect.right) {+ return null;+ }++ const top = Math.min(+ Math.max(rowRect.top + rowRect.height / 2, editorRect.top + 14),+ editorRect.bottom - 14,+ );+ const cellPos = posAtCell(editor, target.cell);return (- <ControlButton- label="Row options"+ <div+ data-table-controls=""+ className="pointer-events-auto absolute flex flex-col gap-0.5"style={{- top: rowRect.top + rowRect.height / 2,+ top,left: tableRect.left,transform: "translate(-50%, -50%)",}}- active={menu?.kind === "row"}- onClick={() => {- const cellPos = posAtCell(editor, zone.cell);- setMenu(menu?.kind === "row" ? null : { kind: "row", cellPos });- }}>- <GripDotsVertical className="size-3.5" />- </ControlButton>+ <ControlButton+ label="Delete row"+ danger+ onClick={() => onDelete(cellPos)}+ >+ <Trash className="size-3" />+ </ControlButton>+ <ControlButton+ label="Row options"+ active={menu?.kind === "row"}+ onClick={() =>+ onToggleMenu(+ menu?.kind === "row" ? null : { kind: "row", cellPos, target },+ )+ }+ >+ <GripDotsVertical className="size-3.5" />+ </ControlButton>+ </div>);}-function ColumnHandle({+function ColumnControls({editor,- zone,+ editorDom,+ target,menu,- setMenu,+ onDelete,+ onToggleMenu,}: {editor: Editor;- zone: Extract<HoverZone, { kind: "col" }>;+ editorDom: HTMLElement;+ target: CellTarget;menu: MenuState | null;- setMenu: (menu: MenuState | null) => void;+ onDelete: (cellPos: number) => void;+ onToggleMenu: (menu: MenuState | null) => void;}) {- const tableRect = zone.table.getBoundingClientRect();- const colRect = getColumnRect(zone.table, zone.cell.cellIndex);+ const editorRect = editorDom.getBoundingClientRect();+ const tableRect = target.table.getBoundingClientRect();+ const colRect = getColumnRect(target.table, target.cell.cellIndex);if (!colRect) return null;+ if (tableRect.bottom < editorRect.top || tableRect.top > editorRect.bottom) {+ return null;+ }+ if (colRect.right < editorRect.left || colRect.left > editorRect.right) {+ return null;+ }++ const cellPos = posAtCell(editor, target.cell);+ const top = Math.max(tableRect.top, editorRect.top + 10);+return (- <ControlButton- label="Column options"+ <div+ data-table-controls=""+ className="pointer-events-auto absolute flex gap-0.5"style={{- top: tableRect.top,+ top,left: colRect.left + colRect.width / 2,transform: "translate(-50%, -50%)",}}- active={menu?.kind === "col"}- onClick={() => {- const cellPos = posAtCell(editor, zone.cell);- setMenu(menu?.kind === "col" ? null : { kind: "col", cellPos });- }}>- <GripDotsVertical className="size-3.5 rotate-90" />- </ControlButton>+ <ControlButton+ label="Delete column"+ danger+ onClick={() => onDelete(cellPos)}+ >+ <Trash className="size-3" />+ </ControlButton>+ <ControlButton+ label="Column options"+ active={menu?.kind === "col"}+ onClick={() =>+ onToggleMenu(+ menu?.kind === "col" ? null : { kind: "col", cellPos, target },+ )+ }+ >+ <GripDotsVertical className="size-3.5 rotate-90" />+ </ControlButton>+ </div>);}function ControlButton({label,style,+ className,active,+ danger,onClick,children,}: {label: string;- style: CSSProperties;+ style?: CSSProperties;+ className?: string;active?: boolean;+ danger?: boolean;onClick: () => void;children: ReactNode;}) {return (- <button- type="button"- title={label}- style={style}- data-table-controls=""- onMouseDown={(event) => {- event.preventDefault();- event.stopPropagation();- }}- onClick={onClick}- className={cn(- "pointer-events-auto absolute flex size-5 items-center justify-center rounded-md border bg-white text-neutral-500 shadow-sm",- "hover:bg-neutral-50 hover:text-neutral-800",- active- ? "border-neutral-300 bg-neutral-50 text-neutral-800"- : "border-neutral-200",- )}- >- {children}- <span className="sr-only">{label}</span>- </button>+ <IconTooltip label={label}>+ <button+ type="button"+ style={style}+ aria-label={label}+ data-table-controls=""+ onMouseDown={(event) => {+ event.preventDefault();+ event.stopPropagation();+ }}+ onClick={onClick}+ className={cn(+ "pointer-events-auto flex size-5 items-center justify-center rounded-md border bg-white text-neutral-500 shadow-sm",+ "hover:bg-neutral-50 hover:text-neutral-800",+ danger && "hover:border-red-200 hover:bg-red-50 hover:text-red-600",+ active+ ? "border-neutral-300 bg-neutral-50 text-neutral-800"+ : "border-neutral-200",+ className,+ )}+ >+ {children}+ <span className="sr-only">{label}</span>+ </button>+ </IconTooltip>);}@@ -432,85 +562,164 @@ function MenuButton({);}-function getHoverZone(+function getPointerTarget(x: number,y: number,editorDom: HTMLElement,-): HoverZone | null {+): PointerTarget | null {+ const direct = document.elementFromPoint(x, y);+ const directCell =+ direct instanceof Element ? direct.closest("td, th") : null;++ if (+ directCell instanceof HTMLTableCellElement &&+ editorDom.contains(directCell)+ ) {+ const table = directCell.closest("table");+ if (table instanceof HTMLTableElement) {+ return {+ table,+ cell: directCell,+ ...edgeFlags(table, x, y, editorDom),+ };+ }+ }+const clip = editorDom.getBoundingClientRect();const tables = editorDom.querySelectorAll("table");- for (const table of tables) {+ for (let tableIndex = 0; tableIndex < tables.length; tableIndex++) {+ const table = tables[tableIndex];if (!(table instanceof HTMLTableElement)) continue;const rect = table.getBoundingClientRect();- const visible = intersectRect(rect, clip);- if (!visible) continue;-- const nearVisible =- x >= visible.left - EDGE_PX &&- x <= visible.right + EDGE_PX &&- y >= visible.top - EDGE_PX &&- y <= visible.bottom + EDGE_PX;-- if (!nearVisible) continue;-- const distBottom = Math.abs(y - rect.bottom);- const distRight = Math.abs(x - rect.right);- const distLeft = Math.abs(x - rect.left);- const distTop = Math.abs(y - rect.top);- const alongX = x >= visible.left && x <= visible.right;- const alongY = y >= visible.top && y <= visible.bottom;- const bottomVisible = rect.bottom >= clip.top && rect.bottom <= clip.bottom;- const rightVisible = rect.right >= clip.left && rect.right <= clip.right;- const leftVisible = rect.left >= clip.left && rect.left <= clip.right;- const topVisible = rect.top >= clip.top && rect.top <= clip.bottom;-- if (- bottomVisible &&- alongX &&- distBottom <= EDGE_PX &&- distBottom <= distRight- ) {- return { kind: "add-row", table };- }+ if (!intersectRect(rect, clip)) continue;- if (- rightVisible &&- alongY &&- distRight <= EDGE_PX &&- distRight <= distBottom- ) {- return { kind: "add-col", table };- }+ const near =+ x >= rect.left - EDGE_PX &&+ x <= rect.right + EDGE_PX &&+ y >= rect.top - EDGE_PX &&+ y <= rect.bottom + EDGE_PX;- if (leftVisible && alongY && distLeft <= EDGE_PX && distLeft < distRight) {- const row =- [...table.rows].find((candidate) => {- const rowRect = candidate.getBoundingClientRect();- return y >= rowRect.top && y <= rowRect.bottom;- }) ?? null;- const cell = row?.cells[0];- if (row && cell) return { kind: "row", table, row, cell };- }+ if (!near) continue;++ const { addRow, addCol } = edgeFlags(table, x, y, editorDom);+ if (!addRow && !addCol) continue;++ return { table, cell: cellNearPoint(table, x, y), addRow, addCol };+ }- if (topVisible && alongX && distTop <= EDGE_PX && distTop < distBottom) {- const header = table.rows[0];- const cell = header- ? [...header.cells].find((candidate) => {- const cellRect = candidate.getBoundingClientRect();- return x >= cellRect.left && x <= cellRect.right;- }) ?? null- : null;- if (cell) return { kind: "col", table, cell };+ return null;+}++function edgeFlags(+ table: HTMLTableElement,+ x: number,+ y: number,+ editorDom: HTMLElement,+) {+ const rect = table.getBoundingClientRect();+ const clip = editorDom.getBoundingClientRect();+ const visible = intersectRect(rect, clip);+ const alongX = !!visible && x >= visible.left && x <= visible.right;+ const alongY = !!visible && y >= visible.top && y <= visible.bottom;+ const bottomVisible = rect.bottom >= clip.top && rect.bottom <= clip.bottom;+ const rightVisible = rect.right >= clip.left && rect.right <= clip.right;++ return {+ addRow: bottomVisible && alongX && Math.abs(y - rect.bottom) <= EDGE_PX,+ addCol: rightVisible && alongY && Math.abs(x - rect.right) <= EDGE_PX,+ };+}++function cellNearPoint(table: HTMLTableElement, x: number, y: number) {+ let closest: HTMLTableCellElement | null = null;+ let best = Infinity;++ for (let rowIndex = 0; rowIndex < table.rows.length; rowIndex++) {+ const row = table.rows[rowIndex];+ const rowRect = row.getBoundingClientRect();+ if (y < rowRect.top - EDGE_PX || y > rowRect.bottom + EDGE_PX) continue;++ for (let cellIndex = 0; cellIndex < row.cells.length; cellIndex++) {+ const cell = row.cells[cellIndex];+ const cellRect = cell.getBoundingClientRect();+ const dx =+ x < cellRect.left+ ? cellRect.left - x+ : x > cellRect.right+ ? x - cellRect.right+ : 0;+ const dy =+ y < cellRect.top+ ? cellRect.top - y+ : y > cellRect.bottom+ ? y - cellRect.bottom+ : 0;+ const distance = dx + dy;+ if (distance < best) {+ best = distance;+ closest = cell;+ }}}+ return closest;+}++function samePointer(+ current: PointerTarget | null,+ next: PointerTarget | null,+) {+ if (current === next) return true;+ if (!current || !next) return false;+ return (+ current.table === next.table &&+ current.cell === next.cell &&+ current.addRow === next.addRow &&+ current.addCol === next.addCol+ );+}++function targetFromCell(cell: HTMLTableCellElement): CellTarget | null {+ const row = cell.parentElement;+ const table = cell.closest("table");+ if (+ !(row instanceof HTMLTableRowElement) ||+ !(table instanceof HTMLTableElement)+ ) {+ return null;+ }+ return { table, row, cell };+}++function cellTargetFromSelection(editor: Editor): CellTarget | null {+ if (editor.isDestroyed) return null;++ const { selection } = editor.state;+ const $pos =+ selection instanceof CellSelection+ ? selection.$anchorCell+ : selection.$from;++ for (let depth = $pos.depth; depth > 0; depth--) {+ const name = $pos.node(depth).type.name;+ if (name !== "tableCell" && name !== "tableHeader") continue;++ const dom = editor.view.nodeDOM($pos.before(depth));+ if (!(dom instanceof HTMLTableCellElement)) return null;+ return targetFromCell(dom);+ }+return null;}function posAtCell(editor: Editor, cell: HTMLTableCellElement) {- return editor.view.posAtDOM(cell, 0);+ try {+ return textPosInCell(editor, editor.view.posAtDOM(cell, 0));+ } catch {+ return editor.state.selection.from;+ }}function intersectRect(a: DOMRect, b: DOMRect) {@@ -525,9 +734,11 @@ function intersectRect(a: DOMRect, b: DOMRect) {}function getColumnRect(table: HTMLTableElement, columnIndex: number) {- const cells = [...table.rows]- .map((row) => row.cells[columnIndex])- .filter(Boolean);+ const cells: HTMLTableCellElement[] = [];+ for (let rowIndex = 0; rowIndex < table.rows.length; rowIndex++) {+ const cell = table.rows[rowIndex]?.cells[columnIndex];+ if (cell) cells.push(cell);+ }if (!cells.length) return null;diff --git a/packages/ui/src/rich-text-area/table-keyboard.harness.ts b/packages/ui/src/rich-text-area/table-keyboard.harness.tsnew file mode 100644index 0000000000..e0dcdb9cdb--- /dev/null+++ b/packages/ui/src/rich-text-area/table-keyboard.harness.ts@@ -0,0 +1,77 @@+// Test-only helpers. The UI package does not export this file.+import { TableKit } from "@tiptap/extension-table";+import { CellSelection } from "@tiptap/pm/tables";+import { Editor } from "@tiptap/react";+import StarterKit from "@tiptap/starter-kit";++export function createTableEditor(html: string) {+ const element = document.createElement("div");+ document.body.append(element);++ return new Editor({+ element,+ extensions: [StarterKit, TableKit],+ content: html,+ });+}++export function rowCount(editor: Editor) {+ let count = 0;+ editor.state.doc.descendants((node) => {+ if (node.type.name === "tableRow") count += 1;+ });+ return count;+}++export function columnCount(editor: Editor) {+ let count = 0;+ editor.state.doc.descendants((node) => {+ if (node.type.name !== "tableRow" || count > 0) return;+ count = node.childCount;+ });+ return count;+}++export function setCaretAtText(editor: Editor, text: string, offset = 0) {+ let found = -1;+ editor.state.doc.descendants((node, pos) => {+ if (found !== -1) return false;+ if (!node.isText || !node.text?.includes(text)) return;+ found = pos + node.text.indexOf(text) + offset;+ return false;+ });+ if (found < 0) throw new Error(`Couldn't find "${text}"`);+ editor.commands.setTextSelection(found);+}++export function setCaretInParagraph(editor: Editor, index: number) {+ let seen = 0;+ let found = -1;+ editor.state.doc.descendants((node, pos) => {+ if (found !== -1) return false;+ if (node.type.name !== "paragraph") return;+ if (seen === index) {+ found = pos + 1;+ return false;+ }+ seen += 1;+ });+ if (found < 0) throw new Error(`Couldn't find paragraph ${index}`);+ editor.commands.setTextSelection(found);+}++export function selectCellRange(editor: Editor, start: number, end: number) {+ const positions: number[] = [];+ editor.state.doc.descendants((node, pos) => {+ if (node.type.name === "tableCell" || node.type.name === "tableHeader") {+ positions.push(pos);+ }+ });++ const selection = CellSelection.create(+ editor.state.doc,+ positions[start],+ positions[end],+ );+ editor.view.dispatch(editor.state.tr.setSelection(selection));+}diff --git a/packages/ui/src/rich-text-area/table-keyboard.ts b/packages/ui/src/rich-text-area/table-keyboard.tsnew file mode 100644index 0000000000..a9fac9f316--- /dev/null+++ b/packages/ui/src/rich-text-area/table-keyboard.ts@@ -0,0 +1,123 @@+import type { Node as ProseMirrorNode, ResolvedPos } from "@tiptap/pm/model";+import { TextSelection } from "@tiptap/pm/state";+import { CellSelection } from "@tiptap/pm/tables";+import type { Editor } from "@tiptap/react";++const CELL_NODE_NAMES = new Set(["tableCell", "tableHeader"]);++function isVisuallyEmpty(node: ProseMirrorNode) {+ let empty = true;++ node.descendants((child) => {+ if (!empty) return false;++ if (child.isText) {+ if (child.text?.replace(/\u00a0/g, " ").trim()) empty = false;+ return false;+ }++ if (child.isAtom && child.type.name !== "hardBreak") {+ empty = false;+ return false;+ }+ });++ return empty;+}++function findParent(+ $pos: ResolvedPos,+ predicate: (node: ProseMirrorNode) => boolean,+) {+ for (let depth = $pos.depth; depth > 0; depth--) {+ const node = $pos.node(depth);+ if (predicate(node)) return { node, depth };+ }+ return null;+}++function entireTableSelected(selection: CellSelection) {+ const table = findParent(+ selection.$anchorCell,+ (node) => node.type.name === "table",+ );+ if (!table) return false;++ let cellCount = 0;+ table.node.descendants((node) => {+ if (node.type.name === "table") return false;+ if (CELL_NODE_NAMES.has(node.type.name)) cellCount += 1;+ });++ return cellCount > 0 && cellCount === selection.ranges.length;+}++export function textPosInCell(editor: Editor, pos: number) {+ const $pos = editor.state.doc.resolve(pos);+ return TextSelection.near($pos, 1).from;+}++export function deleteEditorTable(editor: Editor) {+ const { state, view } = editor;+ const $pos = state.selection.$from;++ for (let depth = $pos.depth; depth > 0; depth--) {+ if ($pos.node(depth).type.spec.tableRole !== "table") continue;++ const from = $pos.before(depth);+ const to = $pos.after(depth);+ const parent = $pos.node(depth - 1);+ const paragraph = state.schema.nodes.paragraph;++ if (parent.childCount === 1 && paragraph) {+ const tr = state.tr.replaceWith(from, to, paragraph.create());+ tr.setSelection(TextSelection.near(tr.doc.resolve(from + 1)));+ view.dispatch(tr.scrollIntoView());+ return true;+ }++ return editor.commands.deleteTable();+ }++ return false;+}++export function deleteEditorRow(editor: Editor) {+ if (editor.commands.deleteRow()) return true;+ return deleteEditorTable(editor);+}++export function deleteEditorColumn(editor: Editor) {+ if (editor.commands.deleteColumn()) return true;+ return deleteEditorTable(editor);+}++export function deleteTableStructureOnKey(+ editor: Editor,+ event: KeyboardEvent,+) {+ if (event.isComposing) return false;+ if (event.shiftKey || event.altKey || event.metaKey || event.ctrlKey) {+ return false;+ }+ if (event.key !== "Backspace" && event.key !== "Delete") return false;++ const { selection } = editor.state;++ if (selection instanceof CellSelection) {+ if (entireTableSelected(selection)) return false;+ if (selection.isRowSelection()) return deleteEditorRow(editor);+ if (selection.isColSelection()) return deleteEditorColumn(editor);+ return false;+ }++ if (!selection.empty || !editor.isActive("table")) return false;++ const row = findParent(+ selection.$from,+ (node) => node.type.name === "tableRow",+ );+ if (!row || !isVisuallyEmpty(row.node)) return false;++ return deleteEditorRow(editor);+}