"use client"; import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext"; import { useLexicalEditable } from "@lexical/react/useLexicalEditable"; import { $getTableNodeFromLexicalNodeOrThrow, $getTableRowNodeFromTableCellNodeOrThrow, $isTableCellNode, getDOMCellFromTarget, TableNode, } from "@lexical/table"; import { $getNearestNodeFromDOMNode, type LexicalEditor, mergeRegister } from "lexical"; import { type JSX, useCallback, useEffect, useRef, useState } from "react"; const MIN_COLUMN_WIDTH = 50; const MIN_ROW_HEIGHT = 33; const RESIZER_COLOR_HOVER = "rgba(59,130,246,0.5)"; const RESIZER_COLOR_DRAG = "#3b82f6"; type ResizeDir = "right" | "bottom"; interface DragState { cellElem: HTMLElement; colIndex: number; startX: number; startY: number; dir: ResizeDir; } function getTableAvailableWidth(tableElem: HTMLElement): number { const parent = tableElem.parentElement; const parentWidth = parent?.getBoundingClientRect().width ?? tableElem.getBoundingClientRect().width; return Math.max(1, parentWidth); } function getMinimumColumnWidth(columnCount: number, availableWidth: number): number { return Math.max(1, Math.min(MIN_COLUMN_WIDTH, availableWidth / Math.max(1, columnCount))); } function fitColumnWidthsToAvailable(widths: number[], availableWidth: number): number[] { if (widths.length === 0) return widths; const minWidth = getMinimumColumnWidth(widths.length, availableWidth); const minTotal = minWidth * widths.length; const targetTotal = Math.max(availableWidth, minTotal); const normalized = widths.map((width) => Math.max(minWidth, width)); const total = normalized.reduce((sum, width) => sum + width, 0); if (total <= targetTotal) return normalized; const extraTotal = normalized.reduce((sum, width) => sum + Math.max(0, width - minWidth), 0); if (extraTotal <= 0) { return normalized.map(() => targetTotal / widths.length); } const extraScale = Math.max(0, targetTotal - minTotal) / extraTotal; return normalized.map((width) => minWidth + Math.max(0, width - minWidth) * extraScale); } function getCurrentColumnWidths(tableElem: HTMLElement): number[] { const cols = Array.from(tableElem.querySelectorAll(":scope > colgroup > col")) as HTMLElement[]; const colWidths = cols .map((col) => Number.parseFloat(col.style.width)) .filter((width) => Number.isFinite(width) && width > 0); if (colWidths.length > 0) return colWidths; const firstRow = tableElem.querySelector("tr"); const cells = firstRow ? (Array.from(firstRow.querySelectorAll("td, th")) as HTMLElement[]) : []; return cells.map((cell) => cell.getBoundingClientRect().width); } function resizeColumnWidths( widths: number[], colIndex: number, diffX: number, availableWidth: number, ): number[] { const nextWidths = fitColumnWidthsToAvailable(widths, availableWidth); const minWidth = getMinimumColumnWidth(nextWidths.length, availableWidth); const nextIndex = colIndex + 1; if (colIndex < 0 || colIndex >= nextWidths.length) return nextWidths; const current = nextWidths[colIndex] ?? minWidth; const next = nextWidths[nextIndex]; if (next !== undefined) { const minDelta = minWidth - current; const maxDelta = next - minWidth; const delta = Math.max(minDelta, Math.min(diffX, maxDelta)); nextWidths[colIndex] = current + delta; nextWidths[nextIndex] = next - delta; return fitColumnWidthsToAvailable(nextWidths, availableWidth); } const otherWidth = nextWidths.reduce( (sum, width, index) => (index === colIndex ? sum : sum + width), 0, ); const maxWidth = Math.max(minWidth, availableWidth - otherWidth); nextWidths[colIndex] = Math.max(minWidth, Math.min(current + diffX, maxWidth)); return fitColumnWidthsToAvailable(nextWidths, availableWidth); } function TableCellResizerInternal({ editor }: { editor: LexicalEditor }): JSX.Element | null { const [hasTable, setHasTable] = useState(false); const overlayRef = useRef(null); const dragRef = useRef(null); // Track table presence and set default colWidths useEffect(() => { const tableKeys = new Set(); return mergeRegister( editor.registerMutationListener(TableNode, (nodeMutations: Map) => { for (const [nodeKey, mutation] of nodeMutations) { if (mutation === "destroyed") tableKeys.delete(nodeKey); else tableKeys.add(nodeKey); } setHasTable(tableKeys.size > 0); }), editor.registerNodeTransform(TableNode, (tableNode: TableNode) => { if (tableNode.getColWidths()) return tableNode; const numCols = tableNode.getColumnCount(); tableNode.setColWidths(Array(numCols).fill(100)); return tableNode; }), ); }, [editor]); // Create overlay div once and append to body useEffect(() => { const div = document.createElement("div"); div.style.cssText = ` position: fixed; display: none; pointer-events: none; z-index: 10000; border-radius: 2px; background: ${RESIZER_COLOR_HOVER}; `; document.body.appendChild(div); overlayRef.current = div; return () => { document.body.removeChild(div); overlayRef.current = null; }; }, []); const showOverlay = useCallback( (dir: ResizeDir, cellRect: DOMRect, tableRect: DOMRect | null, isDragging: boolean) => { const div = overlayRef.current; if (!div) return; div.style.background = isDragging ? RESIZER_COLOR_DRAG : RESIZER_COLOR_HOVER; div.style.display = "block"; if (dir === "right") { div.style.width = "4px"; div.style.height = `${(tableRect ?? cellRect).height}px`; div.style.top = `${(tableRect ?? cellRect).top}px`; div.style.left = `${cellRect.right - 2}px`; div.style.cursor = "col-resize"; } else { div.style.height = "4px"; div.style.width = `${(tableRect ?? cellRect).width}px`; div.style.left = `${(tableRect ?? cellRect).left}px`; div.style.top = `${cellRect.bottom - 2}px`; div.style.cursor = "row-resize"; } }, [], ); const hideOverlay = useCallback(() => { const div = overlayRef.current; if (div) div.style.display = "none"; }, []); const clearResizeHover = useCallback(() => { if (dragRef.current) return; hideOverlay(); const editorRoot = editor.getRootElement() as HTMLElement | null; if (editorRoot) editorRoot.style.cursor = ""; }, [editor, hideOverlay]); const moveDragOverlay = useCallback((dir: ResizeDir, x: number, y: number) => { const div = overlayRef.current; if (!div) return; if (dir === "right") { div.style.left = `${x - 2}px`; } else { div.style.top = `${y - 2}px`; } }, []); // Main event handling useEffect(() => { if (!hasTable) return; const editorRoot = editor.getRootElement() as HTMLElement | null; if (!editorRoot) return; const onMouseMove = (e: MouseEvent) => { const target = e.target as HTMLElement; if (!target) return; // While dragging, move overlay if (dragRef.current) { e.preventDefault(); moveDragOverlay(dragRef.current.dir, e.clientX, e.clientY); return; } const domCell = getDOMCellFromTarget(target); if (!domCell) { hideOverlay(); editorRoot.style.cursor = ""; return; } const cellElem = domCell.elem as HTMLElement; const cellRect = cellElem.getBoundingClientRect(); const tableElem = cellElem.closest("table") as HTMLElement | null; const tableRect = tableElem ? tableElem.getBoundingClientRect() : null; const isRightEdge = e.clientX > cellRect.right - 8; const isBottomEdge = e.clientY > cellRect.bottom - 8; if (isRightEdge) { showOverlay("right", cellRect, tableRect, false); editorRoot.style.cursor = "col-resize"; } else if (isBottomEdge) { showOverlay("bottom", cellRect, tableRect, false); editorRoot.style.cursor = "row-resize"; } else { hideOverlay(); editorRoot.style.cursor = ""; } }; const onMouseDown = (e: MouseEvent) => { const target = e.target as HTMLElement; const domCell = getDOMCellFromTarget(target); if (!domCell) return; const cellElem = domCell.elem as HTMLElement; const cellRect = cellElem.getBoundingClientRect(); const isRightEdge = e.clientX > cellRect.right - 8; const isBottomEdge = e.clientY > cellRect.bottom - 8; if (!isRightEdge && !isBottomEdge) return; const dir: ResizeDir = isRightEdge ? "right" : "bottom"; dragRef.current = { cellElem, colIndex: domCell.x, startX: e.clientX, startY: e.clientY, dir, }; const tableElem = cellElem.closest("table") as HTMLElement | null; const tableRect = tableElem ? tableElem.getBoundingClientRect() : null; showOverlay(dir, cellRect, tableRect, true); e.preventDefault(); }; editorRoot.addEventListener("mousemove", onMouseMove); editorRoot.addEventListener("mousedown", onMouseDown); editorRoot.addEventListener("mouseleave", clearResizeHover); document.addEventListener("scroll", clearResizeHover, true); return () => { editorRoot.removeEventListener("mousemove", onMouseMove); editorRoot.removeEventListener("mousedown", onMouseDown); editorRoot.removeEventListener("mouseleave", clearResizeHover); document.removeEventListener("scroll", clearResizeHover, true); editorRoot.style.cursor = ""; }; }, [hasTable, editor, showOverlay, hideOverlay, moveDragOverlay, clearResizeHover]); // Global mouseup (attach once) useEffect(() => { const onMouseUp = (e: MouseEvent) => { const drag = dragRef.current; if (!drag) return; const diffX = e.clientX - drag.startX; const diffY = e.clientY - drag.startY; if (drag.dir === "right") { const tableElem = drag.cellElem.closest("table") as HTMLElement | null; if (tableElem) { const availableWidth = getTableAvailableWidth(tableElem); const currentWidths = getCurrentColumnWidths(tableElem); const nextWidths = resizeColumnWidths( currentWidths, drag.colIndex, diffX, availableWidth, ); editor.update(() => { const cellLex = $getNearestNodeFromDOMNode(drag.cellElem); if (!$isTableCellNode(cellLex)) return; const tNode = $getTableNodeFromLexicalNodeOrThrow(cellLex); tNode.setColWidths(nextWidths.map(Math.round)); }); } } else if (drag.dir === "bottom") { const row = drag.cellElem.closest("tr") as HTMLElement | null; if (row) { const current = row.getBoundingClientRect().height; const nextHeight = Math.round(Math.max(MIN_ROW_HEIGHT, current + diffY)); editor.update(() => { const cellLex = $getNearestNodeFromDOMNode(drag.cellElem); if (!$isTableCellNode(cellLex)) return; const rowNode = $getTableRowNodeFromTableCellNodeOrThrow(cellLex); rowNode.setHeight(nextHeight); }); } } dragRef.current = null; hideOverlay(); const editorRoot = editor.getRootElement() as HTMLElement | null; if (editorRoot) editorRoot.style.cursor = ""; }; document.addEventListener("mouseup", onMouseUp); return () => document.removeEventListener("mouseup", onMouseUp); }, [editor, hideOverlay]); return null; } export function TableCellResizerPlugin(): JSX.Element | null { const [editor] = useLexicalComposerContext(); const isEditable = useLexicalEditable(); return isEditable ? : null; }