import * as React from 'react'; import { AuthoredPlugin } from '../../../authored'; import { BaseParagraphPlugin, ElementApi, type NodeKey, type Path, TextApi, } from '../../../core'; import type { TableCellInfo, TableElement, TableResize, TableResizeTarget, } from '../../../features/table'; import { compileTableGrid } from '../../../features/table/lib/internal/grid'; import { useEditor, useEditorReadOnly, useEditorSelector, usePluginStore, } from '../../core'; import { getContentTableRows, measureTableColumnWidths, resolveMeasuredTableColumnWidths, } from './measureTableColumnWidths.internal'; import { TablePlugin } from './TablePlugin'; import { type TableResizeHandle, useTableResize } from './useTableResize'; const TABLE_RESIZE_EDGE = 8; const TABLE_TOUCH_RESIZE_EDGE = 6; const TABLE_RESIZE_STEP = 16; const TABLE_EXTEND_DRAG_THRESHOLD = 8; const TABLE_EXTEND_ROW_STEP = 36; const TABLE_EXTEND_COLUMN_STEP = 80; const TABLE_CELL_SELECTOR = 'td[data-editor-node-key], th[data-editor-node-key]'; type TableEdgeTarget = { cell: HTMLTableCellElement; colAtStart: boolean; gripCol: number | null; gripRow: number | null; rowAtStart: boolean; }; /** Live preview state while dragging a table `+` row or column extend bar. */ export type TableControlsExtendPreview = Readonly<{ axis: 'column' | 'row'; /** Positive adds rows/columns; negative crops empty trailing rows/columns. */ delta: number; }>; /** Resolved geometry for the currently hovered or focused table cell edge. */ export type TableControlsPlaced = Readonly<{ colIndex: number; columnX: number; gripCol: number; gripRow: number; rowIndex: number; }>; /** Live `NodeKey` anchor preserving a column or row index across concurrent edits. */ export type TableControlsAxisAnchor = Readonly<{ colOffset: number; key: NodeKey; }>; /** Context passed to {@link TableControlsOptions.onColumnHandleClick}. */ export type TableControlsColumnClickEvent = Readonly<{ anchor: TableControlsAxisAnchor | null; cellPaths: Path[]; colIndex: number; deleteTarget: Path | null; insertAfter: Path | null; insertBefore: Path | null; rtl: boolean; setMenuOpen: (open: boolean) => void; }>; /** Options for {@link useTableControls}. */ export type TableControlsOptions = Readonly<{ /** Width in pixels reserved for a leading row-handle control column. */ controlColumnWidth?: number; /** When true, column resize indicators paint on the drag indicator line instead of hover line. */ deferColumnResize?: boolean; /** The table element rendered by the host component. */ element: TableElement; /** Optional lock predicate (for example wired to `BaseLockPlugin` in app UI). */ isAxisLocked?: (axis: 'column' | 'row', index: number) => boolean; /** Called on a clean click (non-drag) of the column grip button. */ onColumnHandleClick?: (event: TableControlsColumnClickEvent) => void; /** Called during active resize drags with the computed preview. */ onResize: (resize: TableResize) => void; /** Called when a resize drag commits or cancels. */ onResizeEnd: () => void; /** Called right after a pointer resize session starts. */ onResizeStart?: (handle: TableResizeHandle) => void; /** Ref to the rendered `` element. */ tableRef: React.RefObject; /** Ref to the table controls wrapper element. */ wrapperRef: React.RefObject; }>; /** Headless state and ref-carrying element prop getters returned by {@link useTableControls}. */ export type TableControlsResult = Readonly<{ authoredPreview: boolean; columnCount: number; columnHandleContainerProps: React.ComponentPropsWithRef<'div'>; columnHandleProps: React.ButtonHTMLAttributes; columnResizeProps: React.ComponentPropsWithRef<'div'> & { 'data-table-resize-handle': 'column-end'; }; columnsResizable: boolean; dragIndicatorProps: React.ComponentPropsWithRef<'div'>; extendAxis: (axis: 'column' | 'row', delta?: number) => boolean; extendPreview: TableControlsExtendPreview | null; getAxisAnchor: ( axis: 'column' | 'row', index: number ) => TableControlsAxisAnchor | null; getColumnCellPaths: (colIndex: number) => Path[]; getColumnDeleteTarget: (colIndex: number) => Path | null; getColumnInsertTarget: (colIndex: number, before: boolean) => Path | null; getExtendBarProps: ( axis: 'column' | 'row' ) => React.ButtonHTMLAttributes & { 'data-table-extend-bar': 'column' | 'row'; }; getPlaced: () => TableControlsPlaced | null; gridLocked: boolean; hasMultiRowSelection: boolean; hoverIndicatorProps: React.ComponentPropsWithRef<'div'>; overlayProps: React.ComponentPropsWithRef<'div'>; refresh: () => void; resolveAxisIndex: ( axis: 'column' | 'row', anchor: TableControlsAxisAnchor | null, fallback: number ) => number | null; rowCount: number; rowResizeProps: React.ComponentPropsWithRef<'div'> & { 'data-table-resize-handle': 'row-end'; }; rowsResizable: boolean; setMenuOpen: (open: boolean) => void; suggesting: boolean; wrapperProps: React.HTMLAttributes & { 'data-table-wrapper': 'true'; }; }>; const isRtlTable = (table: HTMLElement) => table.ownerDocument.defaultView?.getComputedStyle(table).direction === 'rtl'; const sumWidths = (widths: readonly number[], end: number) => widths.slice(0, end).reduce((total, width) => total + width, 0); const paintIndicator = ( ref: React.RefObject, offset: number | null ) => { const indicator = ref.current; if (!indicator) return; indicator.style.display = offset === null ? 'none' : 'block'; if (offset === null) indicator.style.removeProperty('left'); else indicator.style.left = `${offset}px`; }; const paintLogicalIndicator = ( ref: React.RefObject, table: HTMLTableElement | null, logicalOffset: number | null ) => { const wrapper = ref.current?.parentElement; paintIndicator( ref, logicalOffset !== null && table && wrapper && isRtlTable(table) ? wrapper.clientWidth - logicalOffset : logicalOffset ); }; const placeBox = ( element: HTMLElement | null, box: Partial> | null ) => { if (!element) return; if (!box) { element.style.display = 'none'; return; } element.style.display = 'block'; for (const [side, value] of Object.entries(box)) { element.style.setProperty(side, `${value}px`); } }; /** * UI-neutral table controller managing edge hit-testing, resize sessions, * column drag reordering, keyboard resize stepping, and `+` extend-bar drag/click. */ export const useTableControls = ({ controlColumnWidth = 0, deferColumnResize = false, element, isAxisLocked, onColumnHandleClick, onResize, onResizeEnd, onResizeStart, tableRef, wrapperRef, }: TableControlsOptions): TableControlsResult => { const editor = useEditor(); const readOnly = useEditorReadOnly(); const tableNodeKey = editor.key(element); const { api } = editor.plugin(TablePlugin); const authored = editor.plugin(AuthoredPlugin).installed ? editor.plugin(AuthoredPlugin).read : null; const authoredView = useEditorSelector( (current) => { const currentAuthored = current.plugin(AuthoredPlugin); return currentAuthored.installed ? currentAuthored.read.view() : null; }, { dependsOn: 'authored' } ); const authoredPreview = authoredView !== null && 'preview' in authoredView; const suggesting = authoredView !== null && 'intent' in authoredView && authoredView.intent === 'propose'; const gridLocked = useEditorSelector( (innerEditor) => { const table = tableNodeKey ? innerEditor.read.nodes.get(tableNodeKey)?.[0] : undefined; return Boolean(table && authored?.gridLocked(table)); }, { dependsOn: ['document', 'authored'] } ); const selectedCellKey = useEditorSelector((innerEditor) => { const view = innerEditor.plugin(TablePlugin).read.selection(); return tableNodeKey && view?.tableKey === tableNodeKey ? view.focus : null; }); const hasMultiRowSelection = useEditorSelector((innerEditor) => { const view = innerEditor.plugin(TablePlugin).read.selection(); return Boolean( tableNodeKey && view?.rectangular && view.tableKey === tableNodeKey && view.cells.length > 1 && view.bounds.maxRow > view.bounds.minRow ); }); const baseColSizes = usePluginStore( TablePlugin, () => api.columnWidths(element), { equalityFn: (left, right) => left.length === right.length && left.every((width, index) => width === right[index]), } ); const columnCount = baseColSizes.length; const rowCount = element.children.length; const rowsResizable = !readOnly && !gridLocked && !authoredPreview; const columnsResizable = rowsResizable && !suggesting; const extendLocked = readOnly || authoredPreview || gridLocked; const [extendPreview, setExtendPreview] = React.useState(null); const [prevExtendLocked, setPrevExtendLocked] = React.useState(extendLocked); const [menuOpen, setMenuOpenState] = React.useState(false); const [resizeEndVersion, setResizeEndVersion] = React.useState(0); if (extendLocked !== prevExtendLocked) { setPrevExtendLocked(extendLocked); if (extendLocked) { setExtendPreview(null); } } const overlayRef = React.useRef(null); const columnResizeRef = React.useRef(null); const rowResizeRef = React.useRef(null); const columnHandleRef = React.useRef(null); const dragIndicatorRef = React.useRef(null); const hoverIndicatorRef = React.useRef(null); const resizeStartWidthsRef = React.useRef(null); const activeRef = React.useRef(null); const placedRef = React.useRef(null); const cellInfoRef = React.useRef<{ cell: HTMLTableCellElement; element: TableElement; info: TableCellInfo | null; } | null>(null); const columnDragRef = React.useRef<{ admitted: boolean; dragging: boolean; from: number; fromAnchor: TableControlsAxisAnchor | null; locked: boolean; pointerId: number; startX: number; to: number; } | null>(null); const extendDragRef = React.useRef<{ axis: 'column' | 'row'; delta: number; dragging: boolean; pointerId: number; rtl: boolean; startPos: number; } | null>(null); const clearHeldRef = React.useRef<(() => void) | null>(null); const focusWithinRef = React.useRef(false); const heldRef = React.useRef(false); const menuOpenRef = React.useRef(false); const pointerInsideRef = React.useRef(false); const resizingRef = React.useRef(false); const suppressClickRef = React.useRef(false); const suppressClickTimerRef = React.useRef | null>(null); const suppressExtendClickRef = React.useRef(false); const suppressExtendClickTimerRef = React.useRef | null>(null); React.useEffect( () => () => { if (suppressClickTimerRef.current !== null) { clearTimeout(suppressClickTimerRef.current); suppressClickTimerRef.current = null; } if (suppressExtendClickTimerRef.current !== null) { clearTimeout(suppressExtendClickTimerRef.current); suppressExtendClickTimerRef.current = null; } }, [] ); const callbacksRef = React.useRef({ isAxisLocked, onColumnHandleClick, onResizeStart, }); React.useLayoutEffect(() => { callbacksRef.current = { isAxisLocked, onColumnHandleClick, onResizeStart, }; }, [isAxisLocked, onColumnHandleClick, onResizeStart]); React.useEffect( () => () => { clearHeldRef.current?.(); clearHeldRef.current = null; columnDragRef.current = null; extendDragRef.current = null; }, [] ); React.useEffect(() => { if (readOnly || authoredPreview || gridLocked) { extendDragRef.current = null; } }, [authoredPreview, gridLocked, readOnly]); const setMenuOpen = React.useCallback((open: boolean) => { menuOpenRef.current = open; setMenuOpenState(open); }, []); const isOwnTarget = (target: Element | null) => target?.closest('[data-table-wrapper="true"]') === wrapperRef.current; const getRenderedWidths = () => { const table = tableRef.current; const measured = table ? measureTableColumnWidths(table, columnCount) : undefined; return measured ?? baseColSizes; }; const readCell = (cell: HTMLTableCellElement) => { const node = editor.api.dom.resolveNode(cell); const path = node ? editor.read.nodes.path(node) : null; return path ? editor.plugin(TablePlugin).read.cell({ at: path }) : null; }; const cellInfo = (cell: HTMLTableCellElement) => { const cached = cellInfoRef.current; if (cached?.cell === cell && cached.element === element) { return cached.info; } const info = readCell(cell); cellInfoRef.current = { cell, element, info }; return info; }; const ownedCell = (target: Element | null) => { if (!isOwnTarget(target)) return null; const cell = target?.closest(TABLE_CELL_SELECTOR); return cell && cell.closest('table') === tableRef.current ? cell : null; }; const columnOffset = (index: number, widths = getRenderedWidths()) => controlColumnWidth + sumWidths(widths, index); const columnAt = (clientX: number) => { const table = tableRef.current; const widths = getRenderedWidths(); if (!table || widths.length === 0) return null; const rect = table.getBoundingClientRect(); const offset = (isRtlTable(table) ? rect.right - clientX : clientX - rect.left) - controlColumnWidth; let end = 0; for (const [index, width] of widths.entries()) { end += width; if (offset < end) return index; } return widths.length - 1; }; const getColumnCells = (colIndex: number) => { const table = tableRef.current; if (!table) return []; const widths = getRenderedWidths(); const rect = table.getBoundingClientRect(); const middle = columnOffset(colIndex, widths) + (widths[colIndex] ?? 0) / 2; const x = isRtlTable(table) ? rect.right - middle : rect.left + middle; return Array.from( table.querySelectorAll(TABLE_CELL_SELECTOR) ).filter((cell) => { if (cell.closest('table') !== table) return false; const cellRect = cell.getBoundingClientRect(); return cellRect.left <= x && x < cellRect.right; }); }; const getColumnCellPaths = (colIndex: number): Path[] => getColumnCells(colIndex).flatMap((cell) => { const node = editor.api.dom.resolveNode(cell); const path = node ? editor.read.nodes.path(node) : null; return path ? [path] : []; }); const getColumnCellEntries = (colIndex: number) => getColumnCellPaths(colIndex).flatMap((path) => { const info = editor.plugin(TablePlugin).read.cell({ at: path }); return info ? [{ info, path }] : []; }); const getColumnInsertTarget = (colIndex: number, before: boolean) => { const entries = getColumnCellEntries(colIndex); return ( entries.find(({ info }) => before ? info.col === colIndex : info.col + info.colSpan - 1 === colIndex )?.path ?? null ); }; const getColumnDeleteTarget = (colIndex: number) => { const entries = getColumnCellEntries(colIndex); return entries.length > 0 && entries.every(({ info }) => info.colSpan === 1) ? entries[0].path : null; }; const getAxisAnchor = ( axis: 'column' | 'row', index: number ): TableControlsAxisAnchor | null => { if (axis === 'row') { if (!tableNodeKey) return null; const tableEntry = editor.read.nodes.get(tableNodeKey, { type: TablePlugin, }); const rowNode = tableEntry?.[0].children[index]; const key = rowNode ? editor.key(rowNode) : null; return key ? { colOffset: 0, key } : null; } const entries = getColumnCellEntries(index); const entry = entries.find(({ info }) => info.col === index && info.colSpan === 1) ?? entries.find(({ info }) => info.col === index) ?? entries[0]; const key = entry ? editor.key(entry.path) : null; return entry && key ? { colOffset: index - entry.info.col, key } : null; }; const resolveAxisIndex = ( axis: 'column' | 'row', anchor: TableControlsAxisAnchor | null, fallback: number ): number | null => { if (!anchor) return fallback; if (!tableNodeKey) return null; const nodeEntry = editor.read.nodes.get(anchor.key); if (!nodeEntry) return null; const ownerTable = editor.read.nodes.above({ at: nodeEntry[0], type: TablePlugin, }); if (!ownerTable || editor.key(ownerTable[1]) !== tableNodeKey) { return null; } if (axis === 'row') { return nodeEntry[1].at(-1) ?? null; } const info = editor.plugin(TablePlugin).read.cell({ at: nodeEntry[1] }); if (!info || anchor.colOffset >= info.colSpan) return null; return info.col + anchor.colOffset; }; const hide = () => { placedRef.current = null; placeBox(columnResizeRef.current, null); placeBox(rowResizeRef.current, null); if (!menuOpenRef.current) placeBox(columnHandleRef.current, null); paintIndicator(hoverIndicatorRef, null); }; const show = (target: TableEdgeTarget): TableControlsPlaced | null => { const table = tableRef.current; const wrapper = wrapperRef.current; const info = table && wrapper && target.cell.isConnected ? cellInfo(target.cell) : null; if (!table || !wrapper || !info) { hide(); return null; } const rtl = isRtlTable(table); const widths = getRenderedWidths(); const origin = wrapper.getBoundingClientRect(); const rect = target.cell.getBoundingClientRect(); const tableRect = table.getBoundingClientRect(); const previousCol = target.colAtStart && info.col > 0; const previousRow = target.rowAtStart && info.row > 0; const startX = rtl ? rect.right : rect.left; const endX = rtl ? rect.left : rect.right; const gripCol = target.gripCol ?? info.col; const gripRow = target.gripRow ?? info.row; const gripMiddle = columnOffset(gripCol, widths) + (widths[gripCol] ?? 0) / 2; const placed: TableControlsPlaced = { colIndex: previousCol ? info.col - 1 : info.col + info.colSpan - 1, columnX: (previousCol ? startX : endX) - origin.left, gripCol, gripRow, rowIndex: previousRow ? info.row - 1 : info.row + info.rowSpan - 1, }; placedRef.current = placed; placeBox(columnResizeRef.current, { height: rect.height + TABLE_RESIZE_EDGE, left: placed.columnX, top: rect.top - origin.top - TABLE_RESIZE_EDGE / 2, }); placeBox(rowResizeRef.current, { left: rect.left - origin.left, top: (previousRow ? rect.top : rect.bottom) - origin.top, width: rect.width, }); placeBox( columnHandleRef.current, resizingRef.current ? null : { left: (rtl ? tableRect.right - gripMiddle : tableRect.left + gripMiddle) - origin.left, } ); return placed; }; const selectedTarget = (): TableEdgeTarget | null => { const node = selectedCellKey ? editor.read.nodes.get(selectedCellKey)?.[0] : null; const dom = node ? editor.api.dom.resolveDOMNode(node) : null; const cell = dom ? ownedCell(dom) : null; return cell && cell === dom ? { cell, colAtStart: false, gripCol: null, gripRow: null, rowAtStart: false, } : null; }; const refresh = () => { if (columnDragRef.current) return; if (!columnsResizable) paintIndicator(hoverIndicatorRef, null); if (heldRef.current && !resizingRef.current) { hide(); return; } const target = activeRef.current ?? selectedTarget(); if (target) show(target); else hide(); }; const isLatched = () => resizingRef.current || !!columnDragRef.current || focusWithinRef.current || menuOpenRef.current; const edgeTarget = ( cell: HTMLTableCellElement, { clientX, clientY }: { clientX: number; clientY: number } ): TableEdgeTarget => { const rect = cell.getBoundingClientRect(); const table = tableRef.current; const startX = table && isRtlTable(table) ? rect.right : rect.left; return { cell, colAtStart: Math.abs(clientX - startX) <= TABLE_RESIZE_EDGE, gripCol: columnAt(clientX), gripRow: cellInfo(cell)?.row ?? null, rowAtStart: Math.abs(clientY - rect.top) <= TABLE_RESIZE_EDGE, }; }; const armHeldRelease = () => { if (clearHeldRef.current) return; const ownerWindow = wrapperRef.current?.ownerDocument.defaultView; if (!ownerWindow) return; const release = () => { clearHeldRef.current?.(); clearHeldRef.current = null; heldRef.current = false; refresh(); }; ownerWindow.addEventListener('pointerup', release, { once: true }); ownerWindow.addEventListener('pointercancel', release, { once: true }); clearHeldRef.current = () => { ownerWindow.removeEventListener('pointerup', release); ownerWindow.removeEventListener('pointercancel', release); }; }; const touchEdgeHit = ( target: Element | null, clientX: number, clientY: number ) => { if (!isOwnTarget(target) || overlayRef.current?.contains(target)) { return null; } const cell = ownedCell(target); if (!cell) return null; const info = cellInfo(cell); const rect = cell.getBoundingClientRect(); const table = tableRef.current; const rtl = Boolean(table && isRtlTable(table)); const startX = rtl ? rect.right : rect.left; const endX = rtl ? rect.left : rect.right; const colAtStart = Math.abs(clientX - startX) <= TABLE_TOUCH_RESIZE_EDGE; const rowAtStart = Math.abs(clientY - rect.top) <= TABLE_TOUCH_RESIZE_EDGE; const nearColumn = columnsResizable && ((colAtStart && (info?.col ?? 0) > 0) || Math.abs(clientX - endX) <= TABLE_TOUCH_RESIZE_EDGE); const nearRow = rowsResizable && ((rowAtStart && (info?.row ?? 0) > 0) || Math.abs(clientY - rect.bottom) <= TABLE_TOUCH_RESIZE_EDGE); return nearColumn || nearRow ? { edge: { cell, colAtStart, gripCol: columnAt(clientX), gripRow: info?.row ?? null, rowAtStart, }, nearColumn, nearRow, } : null; }; const onTouchStart = React.useEffectEvent((event: TouchEvent) => { if ( event.defaultPrevented || !event.cancelable || event.touches.length !== 1 ) { return; } const touch = event.touches[0]; if ( touchEdgeHit(event.target as Element | null, touch.clientX, touch.clientY) ) { // native-override: single-finger touch on a resizable cell border blocks browser scroll and text selection so pointer resize can drag event.preventDefault(); } }); React.useEffect(() => { const wrapper = wrapperRef.current; if (!wrapper || (!columnsResizable && !rowsResizable)) return undefined; const handleTouchStart = (event: TouchEvent) => onTouchStart(event); wrapper.addEventListener('touchstart', handleTouchStart, { passive: false, }); return () => { wrapper.removeEventListener('touchstart', handleTouchStart); }; }, [columnsResizable, rowsResizable, wrapperRef]); const beginResize = useTableResize({ containerRef: wrapperRef, element, tableRef, onResize: (resize) => { if (resize.rowIndex === undefined) { const first = resize.columns[0]; const startWidths = resizeStartWidthsRef.current ?? baseColSizes; paintLogicalIndicator( deferColumnResize ? dragIndicatorRef : hoverIndicatorRef, tableRef.current, controlColumnWidth + sumWidths(startWidths, first.colIndex) + first.width ); } onResize(resize); }, onResizeEnd: () => { resizingRef.current = false; resizeStartWidthsRef.current = null; paintIndicator(dragIndicatorRef, null); paintIndicator(hoverIndicatorRef, null); onResizeEnd(); setResizeEndVersion((version) => version + 1); refresh(); }, }); const startResize = ( event: React.PointerEvent, handle: TableResizeHandle ) => { if (!beginResize(event, handle)) return; resizingRef.current = true; heldRef.current = false; placeBox(columnHandleRef.current, null); paintIndicator(hoverIndicatorRef, null); if (handle.rowIndex === undefined) { const startWidths = getRenderedWidths(); resizeStartWidthsRef.current = startWidths; paintLogicalIndicator( deferColumnResize ? dragIndicatorRef : hoverIndicatorRef, tableRef.current, controlColumnWidth + sumWidths(startWidths, handle.colIndex + 1) ); } callbacksRef.current.onResizeStart?.(handle); }; const stepResize = (target: TableResizeTarget, delta: number) => { const isRow = 'rowIndex' in target && target.rowIndex !== undefined; if (!tableNodeKey || !(isRow ? rowsResizable : columnsResizable)) return; const table = editor.read.nodes.get(tableNodeKey, { type: TablePlugin, })?.[0]; if (!table) return; const tablePlugin = editor.plugin(TablePlugin); let resolvedTarget = target; if (!isRow) { const measured = resolveMeasuredTableColumnWidths({ columnCount: tablePlugin.api.columnWidths(table).length, defaultTableWidth: tablePlugin.store.get().defaultTableWidth, domTable: tableRef.current, storedWidths: table.columnWidths, }); if (measured) { resolvedTarget = { colIndex: target.colIndex, widths: measured }; } } const resize = tablePlugin.api.createResize(table, resolvedTarget); tablePlugin.update.resize({ at: tableNodeKey, ...resize(delta), }); }; const isCellEmpty = React.useCallback( (cell: { children: readonly unknown[] }) => { const paragraphType = editor.plugin(BaseParagraphPlugin).schema.type; return ( cell.children.length === 1 && ElementApi.isElement(cell.children[0]) && cell.children[0].type === paragraphType && cell.children[0].children.every( (leaf) => TextApi.isText(leaf) && leaf.text === '' ) ); }, [editor] ); const countCroppableTrailing = (axis: 'column' | 'row'): number => { if (!tableNodeKey) return 0; const tableNode = editor.read.nodes.get(tableNodeKey, { type: TablePlugin, })?.[0]; if (!tableNode) return 0; const grid = compileTableGrid(tableNode); let count = 0; if (axis === 'row') { for (let row = grid.height - 1; row >= 1; row--) { if (callbacksRef.current.isAxisLocked?.('row', row)) break; const slots = grid.slots[row] ?? []; const canCrop = slots.length > 0 && slots.every( (anchor) => anchor !== null && anchor.row === row && anchor.rowSpan === 1 && isCellEmpty(anchor.cell) ); if (!canCrop) break; count += 1; if (suggesting) break; } return count; } for (let col = grid.width - 1; col >= 1; col--) { if (callbacksRef.current.isAxisLocked?.('column', col)) break; const slots = grid.slots.map((rowSlots) => rowSlots[col]); const canCrop = slots.length > 0 && slots.every( (anchor) => anchor !== null && anchor !== undefined && anchor.col === col && anchor.colSpan === 1 && isCellEmpty(anchor.cell) ); if (!canCrop) break; count += 1; if (suggesting) break; } return count; }; const extendAxis = React.useCallback( (axis: 'column' | 'row', delta = 1): boolean => { if ( !tableNodeKey || !Number.isSafeInteger(delta) || delta === 0 || readOnly || editor.read.view.isReadOnly() || authoredPreview || gridLocked ) { return false; } const beforeTable = editor.read.nodes.get(tableNodeKey, { type: TablePlugin, })?.[0]; if (!beforeTable) return false; editor.update((tx) => { const tableApi = tx.plugin(TablePlugin); if (delta > 0) { const addCount = suggesting ? 1 : delta; for (let step = 0; step < addCount; step++) { const tableNode = tx.nodes.get(tableNodeKey, { type: TablePlugin, })?.[0]; if (!tableNode) break; const grid = compileTableGrid(tableNode); let didInsert = false; if (axis === 'row') { const lastRow = grid.height - 1; if (lastRow < 0) break; const anchor = grid.anchors.find( (candidate) => candidate.row + candidate.rowSpan - 1 === lastRow ); if (!anchor) break; didInsert = tableApi.insertRow({ at: anchor.cell }); } else { const lastCol = grid.width - 1; if (lastCol < 0) break; const anchor = grid.anchors.find( (candidate) => candidate.col + candidate.colSpan - 1 === lastCol ); if (!anchor) break; didInsert = tableApi.insertColumn({ at: anchor.cell }); } if (!didInsert) break; } return; } const cropCount = suggesting ? 1 : Math.abs(delta); for (let step = 0; step < cropCount; step++) { const tableNode = tx.nodes.get(tableNodeKey, { type: TablePlugin, })?.[0]; if (!tableNode) break; const grid = compileTableGrid(tableNode); let didRemove = false; if (axis === 'row') { if (grid.height <= 1) break; const lastRow = grid.height - 1; if (callbacksRef.current.isAxisLocked?.('row', lastRow)) break; const slots = grid.slots[lastRow] ?? []; const canCrop = slots.length > 0 && slots.every( (anchor) => anchor !== null && anchor.row === lastRow && anchor.rowSpan === 1 && isCellEmpty(anchor.cell) ); if (!canCrop) break; const firstAnchor = slots[0]; if (!firstAnchor) break; didRemove = tableApi.removeRow({ at: firstAnchor.cell }); } else { if (grid.width <= 1) break; const lastCol = grid.width - 1; if (callbacksRef.current.isAxisLocked?.('column', lastCol)) break; const slots = grid.slots.map((rowSlots) => rowSlots[lastCol]); const canCrop = slots.length > 0 && slots.every( (anchor) => anchor !== null && anchor !== undefined && anchor.col === lastCol && anchor.colSpan === 1 && isCellEmpty(anchor.cell) ); if (!canCrop) break; const firstAnchor = slots[0]; if (!firstAnchor) break; didRemove = tableApi.removeColumn({ at: firstAnchor.cell }); } if (!didRemove) break; } }); const afterTable = editor.read.nodes.get(tableNodeKey, { type: TablePlugin, })?.[0]; return Boolean(afterTable && afterTable !== beforeTable); }, [ authoredPreview, editor, gridLocked, isCellEmpty, readOnly, suggesting, tableNodeKey, ] ); const track = (event: React.PointerEvent) => { if ( resizingRef.current || columnDragRef.current || focusWithinRef.current || menuOpenRef.current ) { return; } const target = event.target as Element; if (!isOwnTarget(target)) { pointerInsideRef.current = false; paintIndicator(hoverIndicatorRef, null); if (!isLatched()) { activeRef.current = null; refresh(); } return; } pointerInsideRef.current = true; if (event.buttons !== 0) { heldRef.current = true; activeRef.current = null; hide(); armHeldRelease(); return; } heldRef.current = false; if ( overlayRef.current?.contains(target) || target.closest('[data-table-extend-bar]') ) { paintIndicator( hoverIndicatorRef, columnsResizable && target === columnResizeRef.current && placedRef.current ? placedRef.current.columnX : null ); return; } const cell = ownedCell(target); if (!cell) { paintIndicator(hoverIndicatorRef, null); if (isLatched()) return; activeRef.current = null; refresh(); return; } activeRef.current = edgeTarget(cell, event); const placed = show(activeRef.current); const origin = wrapperRef.current?.getBoundingClientRect(); const onColumnEdge = columnsResizable && placed && origin && Math.abs(event.clientX - origin.left - placed.columnX) <= TABLE_RESIZE_EDGE / 2; paintIndicator( hoverIndicatorRef, onColumnEdge && placed ? placed.columnX : null ); }; const dragColumn = (event: React.PointerEvent) => { const drag = columnDragRef.current; if (drag?.pointerId !== event.pointerId) return; const from = resolveAxisIndex('column', drag.fromAnchor, drag.from); if (from === null) { columnDragRef.current = null; paintIndicator(dragIndicatorRef, null); refresh(); return; } const fromChanged = from !== drag.from; drag.from = from; if (!drag.dragging) { if (Math.abs(event.clientX - drag.startX) < 4) return; drag.dragging = true; drag.locked = Boolean( callbacksRef.current.isAxisLocked?.('column', from) ); placeBox(columnResizeRef.current, null); placeBox(rowResizeRef.current, null); paintIndicator(hoverIndicatorRef, null); } else if (fromChanged) { drag.locked = Boolean( callbacksRef.current.isAxisLocked?.('column', from) ); } const to = columnAt(event.clientX); if (to === null || (!fromChanged && to === drag.to)) return; drag.to = to; drag.admitted = !drag.locked && to !== from && editor.plugin(TablePlugin).read.canMoveColumn({ at: element, from, to }); paintLogicalIndicator( dragIndicatorRef, tableRef.current, drag.admitted ? columnOffset(to > from ? to + 1 : to) : null ); }; const endColumnDrag = ( event: React.PointerEvent, commit: boolean ) => { const drag = columnDragRef.current; if (drag?.pointerId !== event.pointerId) return; columnDragRef.current = null; if (!drag.dragging) return; if (commit) { suppressClickRef.current = true; if (suppressClickTimerRef.current !== null) { clearTimeout(suppressClickTimerRef.current); } suppressClickTimerRef.current = setTimeout(() => { suppressClickTimerRef.current = null; suppressClickRef.current = false; }, 0); } paintIndicator(dragIndicatorRef, null); if (commit && drag.admitted) { const from = resolveAxisIndex('column', drag.fromAnchor, drag.from); const to = columnAt(event.clientX) ?? drag.to; if ( from !== null && from !== to && !callbacksRef.current.isAxisLocked?.('column', from) && editor.plugin(TablePlugin).read.canMoveColumn({ at: element, from, to }) ) { editor.plugin(TablePlugin).update.moveColumn({ at: element, from, to }); } } if ( event.currentTarget.ownerDocument.activeElement === event.currentTarget ) { event.currentTarget.blur(); } refresh(); }; const finishExtendDrag = ( event: React.PointerEvent, commit: boolean ) => { const drag = extendDragRef.current; if (!drag) { setExtendPreview(null); return; } if (drag.pointerId !== event.pointerId) return; extendDragRef.current = null; setExtendPreview(null); if (!drag.dragging) return; if (commit) { suppressExtendClickRef.current = true; if (suppressExtendClickTimerRef.current !== null) { clearTimeout(suppressExtendClickTimerRef.current); } suppressExtendClickTimerRef.current = setTimeout(() => { suppressExtendClickTimerRef.current = null; suppressExtendClickRef.current = false; }, 0); if (drag.delta !== 0) { extendAxis(drag.axis, drag.delta); } } }; const getExtendBarProps = ( axis: 'column' | 'row' ): React.ButtonHTMLAttributes & { 'data-table-extend-bar': 'column' | 'row'; } => ({ 'data-table-extend-bar': axis, disabled: readOnly || authoredPreview || gridLocked, type: 'button', onClick: (event) => { if (event.detail > 0 && suppressExtendClickRef.current) { suppressExtendClickRef.current = false; return; } suppressExtendClickRef.current = false; extendAxis(axis, 1); }, onLostPointerCapture: (event) => finishExtendDrag(event, false), onPointerCancel: (event) => finishExtendDrag(event, false), onPointerDown: (event) => { if ( readOnly || authoredPreview || gridLocked || event.button !== 0 || !event.isPrimary ) { return; } const table = tableRef.current; const rtl = Boolean(axis === 'column' && table && isRtlTable(table)); suppressExtendClickRef.current = false; setExtendPreview(null); event.currentTarget.setPointerCapture?.(event.pointerId); extendDragRef.current = { axis, delta: 0, dragging: false, pointerId: event.pointerId, rtl, startPos: axis === 'row' ? event.clientY : event.clientX, }; }, onPointerMove: (event) => { const drag = extendDragRef.current; if (drag?.pointerId !== event.pointerId || drag.axis !== axis) return; const currentPos = axis === 'row' ? event.clientY : event.clientX; const rawDelta = drag.rtl ? drag.startPos - currentPos : currentPos - drag.startPos; if (!drag.dragging) { if (Math.abs(rawDelta) < TABLE_EXTEND_DRAG_THRESHOLD) return; drag.dragging = true; } const step = axis === 'row' ? TABLE_EXTEND_ROW_STEP : TABLE_EXTEND_COLUMN_STEP; const rawSteps = Math.round(rawDelta / step); const nextDelta = rawSteps < 0 ? Math.max(rawSteps, -countCroppableTrailing(axis)) : suggesting ? Math.min(rawSteps, 1) : rawSteps; if (nextDelta !== drag.delta) { drag.delta = nextDelta; setExtendPreview({ axis, delta: nextDelta }); } }, onPointerUp: (event) => finishExtendDrag(event, true), }); const onLayoutChange = React.useEffectEvent(refresh); React.useLayoutEffect(() => { onLayoutChange(); }, [ baseColSizes, columnsResizable, element, menuOpen, resizeEndVersion, rowsResizable, selectedCellKey, ]); const setOverlayNode = React.useCallback((node: HTMLDivElement | null) => { overlayRef.current = node; }, []); const setColumnResizeNode = React.useCallback( (node: HTMLDivElement | null) => { columnResizeRef.current = node; }, [] ); const setRowResizeNode = React.useCallback((node: HTMLDivElement | null) => { rowResizeRef.current = node; }, []); const setColumnHandleNode = React.useCallback( (node: HTMLDivElement | null) => { columnHandleRef.current = node; }, [] ); const setDragIndicatorNode = React.useCallback( (node: HTMLDivElement | null) => { dragIndicatorRef.current = node; }, [] ); const setHoverIndicatorNode = React.useCallback( (node: HTMLDivElement | null) => { hoverIndicatorRef.current = node; }, [] ); return { authoredPreview, columnCount, columnHandleContainerProps: { ref: setColumnHandleNode, }, columnHandleProps: { onClick: (event) => { if (event.detail > 0 && suppressClickRef.current) { suppressClickRef.current = false; return; } suppressClickRef.current = false; const table = tableRef.current; const colIndex = placedRef.current?.gripCol; if (!table || colIndex === undefined) return; callbacksRef.current.onColumnHandleClick?.({ anchor: getAxisAnchor('column', colIndex), cellPaths: getColumnCellPaths(colIndex), colIndex, deleteTarget: getColumnDeleteTarget(colIndex), insertAfter: getColumnInsertTarget(colIndex, false), insertBefore: getColumnInsertTarget(colIndex, true), rtl: isRtlTable(table), setMenuOpen, }); }, onLostPointerCapture: (event) => endColumnDrag(event, false), onPointerCancel: (event) => endColumnDrag(event, false), onPointerDown: (event) => { const from = placedRef.current?.gripCol; suppressClickRef.current = false; if ( event.button !== 0 || !event.isPrimary || from === undefined || readOnly || authoredPreview || gridLocked ) { return; } event.currentTarget.setPointerCapture?.(event.pointerId); columnDragRef.current = { admitted: false, dragging: false, from, fromAnchor: getAxisAnchor('column', from), locked: false, pointerId: event.pointerId, startX: event.clientX, to: from, }; }, onPointerMove: dragColumn, onPointerUp: (event) => endColumnDrag(event, true), }, columnResizeProps: { 'data-table-resize-handle': 'column-end', ref: setColumnResizeNode, role: 'separator', tabIndex: 0, onKeyDown: (event) => { const table = tableRef.current; const colIndex = placedRef.current?.colIndex; if ( event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || !columnsResizable || (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') || !table || colIndex === undefined ) { return; } // native-override: focused column resize separator owns plain ArrowLeft and ArrowRight stepping so the container does not scroll event.preventDefault(); event.stopPropagation(); const widen = (event.key === 'ArrowRight') !== isRtlTable(table); stepResize( { colIndex }, widen ? TABLE_RESIZE_STEP : -TABLE_RESIZE_STEP ); }, onPointerDown: (event) => { const colIndex = placedRef.current?.colIndex; if (columnsResizable && colIndex !== undefined) { startResize(event, { colIndex }); } }, }, columnsResizable, dragIndicatorProps: { ref: setDragIndicatorNode, }, extendAxis, extendPreview: readOnly || authoredPreview || gridLocked ? null : extendPreview, getAxisAnchor, getColumnCellPaths, getColumnDeleteTarget, getColumnInsertTarget, getExtendBarProps, getPlaced: () => placedRef.current, gridLocked, hasMultiRowSelection, hoverIndicatorProps: { ref: setHoverIndicatorNode, }, overlayProps: { ref: setOverlayNode, onBlur: (event) => { if (!event.currentTarget.contains(event.relatedTarget)) { focusWithinRef.current = false; if (!pointerInsideRef.current) activeRef.current = null; refresh(); } }, onFocus: () => { focusWithinRef.current = true; }, }, refresh, resolveAxisIndex, rowCount, rowResizeProps: { 'data-table-resize-handle': 'row-end', ref: setRowResizeNode, role: 'separator', tabIndex: 0, onKeyDown: (event) => { const table = tableRef.current; const rowIndex = placedRef.current?.rowIndex; if ( event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || !rowsResizable || (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') || !table || rowIndex === undefined ) { return; } const height = getContentTableRows(table)[rowIndex]?.getBoundingClientRect().height; if (!height) return; // native-override: focused row resize separator owns plain ArrowUp and ArrowDown stepping so the container does not scroll event.preventDefault(); event.stopPropagation(); stepResize( { height, rowIndex }, event.key === 'ArrowDown' ? TABLE_RESIZE_STEP : -TABLE_RESIZE_STEP ); }, onPointerDown: (event) => { const rowIndex = placedRef.current?.rowIndex; if (rowsResizable && rowIndex !== undefined) { startResize(event, { rowIndex }); } }, }, rowsResizable, setMenuOpen, suggesting, wrapperProps: { 'data-table-wrapper': 'true', onPointerDownCapture: (event) => { const target = event.target as Element; if (!isOwnTarget(target)) return; if ( overlayRef.current?.contains(target) || target.closest('[data-table-extend-bar]') ) { return; } const touchHit = event.pointerType === 'mouse' ? null : touchEdgeHit(target, event.clientX, event.clientY); if (touchHit) { activeRef.current = touchHit.edge; const placed = show(touchHit.edge); if (placed && touchHit.nearColumn) { startResize(event, { colIndex: placed.colIndex }); return; } if (placed && touchHit.nearRow) { startResize(event, { rowIndex: placed.rowIndex }); return; } } heldRef.current = true; activeRef.current = null; hide(); armHeldRelease(); }, onPointerLeave: () => { pointerInsideRef.current = false; if (resizingRef.current || columnDragRef.current) return; paintIndicator(hoverIndicatorRef, null); if (isLatched()) return; activeRef.current = null; refresh(); }, onPointerMove: track, onPointerUp: (event) => { if (!heldRef.current) return; heldRef.current = false; track(event); }, }, }; };