Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(editor): adjustable table row heights (#5947)
Wolf Mermelstein5dde7d7ff0a1
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsxindex 2a090f7eb5..03a651e4e5 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx@@ -813,8 +813,12 @@ const TableRow: TypedRenderableElement<TableRowNode> = {node.__type === 'tablerow',render: (props) => {const isFirstRow = props.node.getIndexWithinParent() === 0;+ const height = props.node.getHeight();return (- <tr class={cn(props.theme.tableRow, isFirstRow && 'font-bold')}>+ <tr+ class={cn(props.theme.tableRow, isFirstRow && 'font-bold')}+ style={height ? { height: `${height}px` } : undefined}+ >{props.children}</tr>);diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableCellResizer.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableCellResizer.tsxindex b16aebbb9c..032b529460 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableCellResizer.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableCellResizer.tsx@@ -1,26 +1,33 @@/**- * @file Column resize handles for tables. On pointer devices an invisible- * strip along the hovered cell's right edge shows a line on hover and drags- * that column border. Touch has no handle at all: a horizontal swipe that- * starts near a column border resizes it. The first touchmove decides the- * gesture — mostly-vertical movement is left to the browser as a scroll,- * and a still finger disarms before the long-press cell selection fires.- * The new width applies live while dragging, with the pointer captured so- * the drag survives leaving the editor; Escape/pointercancel restores the- * pre-drag width.+ * @file Column and row resize handles for tables. On pointer devices an+ * invisible strip along the hovered cell's right edge resizes that column,+ * and one along the bottom edge resizes that row. Touch has no row handle+ * (vertical movement stays a scroll) and no column handle either: a+ * horizontal swipe that starts near a column border resizes it. The first+ * touchmove decides the gesture — mostly-vertical movement is left to the+ * browser as a scroll, and a still finger disarms before the long-press+ * cell selection fires. The new size applies live while dragging, with the+ * pointer captured so the drag survives leaving the editor; Escape /+ * pointercancel restores the pre-drag width or height.*/import { mdStore } from '@block-md/signal/markdownBlockData';import { ScopedPortal } from '@core/component/ScopedPortal';import { isTouchDevice } from '@core/mobile/isTouchDevice';-import { getDOMCellFromTarget } from '@lexical/table';+import { $isTableCellNode, getDOMCellFromTarget } from '@lexical/table';import { calculateZoomLevel } from '@lexical/utils';+import { $getNearestNodeFromDOMNode } from 'lexical';import { createMemo, createSignal, onCleanup, Show } from 'solid-js';import { registerEditorWidthObserver } from '../../plugins/shared/utils';import {$applyResizeDrag,+ $applyRowResizeDrag,$captureResizeDrag,+ $captureRowResizeDrag,$revertResizeDrag,- type ResizeEdge,+ $revertRowResizeDrag,+ type ResizeEdge as ColumnResizeEdge,+ type ResizeDragSnapshot,+ type RowResizeDragSnapshot,} from '../../plugins/tables/tableCellResize';import { createLayoutTick } from './createLayoutTick';@@ -32,6 +39,12 @@ const TOUCH_EDGE_PX = 12;// before tableTouchSelection's 400ms long-press fires.const TOUCH_ARM_TIMEOUT_MS = 350;+type ResizeEdge = ColumnResizeEdge | 'bottom';++function isColumnEdge(edge: ResizeEdge): edge is ColumnResizeEdge {+ return edge === 'left' || edge === 'right';+}+// Set while dragging; names the border of the active cell being dragged.// Module scope: at most one drag runs across all editors, and the other// floating table controls (insert/delete buttons) hide themselves on it —@@ -44,21 +57,35 @@ export function TableCellResizer() {const editor = () => mdData.editor;// Cell whose border carries the handle: the hovered cell on pointer- // devices, the touched cell during a touch drag.+ // devices, the touched cell during a touch drag. `activeCellKey` is set+ // for the duration of a drag so we can re-resolve the element after+ // Lexical recreates a row's DOM when height changes.const [activeCellElem, setActiveCellElem] = createSignal<HTMLElement>();+ const [activeCellKey, setActiveCellKey] = createSignal<string>();const { layoutTick, bumpLayout } = createLayoutTick();+ // Kept across a row-height drag so the handle stays mounted while Lexical+ // recreates the <tr> (updateDOM returns true when height changes).+ let lastCellRect: DOMRect | undefined;const startResize = (cellElem: HTMLElement,edge: ResizeEdge,- down: { pointerId: number; clientX: number; pointerType: string },+ down: {+ pointerId: number;+ clientX: number;+ clientY: number;+ pointerType: string;+ },captureTarget: HTMLElement) => {const currentEditor = editor();if (!currentEditor) return;const zoom = calculateZoomLevel(cellElem);+ const isRow = edge === 'bottom';const drag = currentEditor.read(() =>- $captureResizeDrag(currentEditor, cellElem, edge, zoom)+ isRow+ ? $captureRowResizeDrag(currentEditor, cellElem, zoom)+ : $captureResizeDrag(currentEditor, cellElem, edge, zoom));if (!drag) return;@@ -70,10 +97,18 @@ export function TableCellResizer() {return;}setActiveCellElem(cellElem);+ setActiveCellKey(+ currentEditor.read(() => {+ const node = $getNearestNodeFromDOMNode(cellElem);+ return $isTableCellNode(node) ? node.getKey() : undefined;+ })+ );setDragEdge(edge);const previousCursor = document.body.style.cursor;- if (!isTouch) document.body.style.cursor = 'col-resize';+ if (!isTouch) {+ document.body.style.cursor = isRow ? 'row-resize' : 'col-resize';+ }let frame = 0;let delta = 0;@@ -87,13 +122,21 @@ export function TableCellResizer() {? ['skip-scroll-into-view', 'history-merge']: ['skip-scroll-into-view'];pushedHistory = true;- currentEditor.update(() => $applyResizeDrag(drag, delta), { tag });+ currentEditor.update(+ () => {+ if (isRow) $applyRowResizeDrag(drag as RowResizeDragSnapshot, delta);+ else $applyResizeDrag(drag as ResizeDragSnapshot, delta);+ },+ { tag }+ );};const onPointerMove = (move: PointerEvent) => {if (move.pointerId !== down.pointerId) return;move.preventDefault();- delta = (move.clientX - down.clientX) / zoom;+ delta = isRow+ ? (move.clientY - down.clientY) / zoom+ : (move.clientX - down.clientX) / zoom;if (!frame) frame = requestAnimationFrame(applyDelta);};@@ -111,9 +154,15 @@ export function TableCellResizer() {};const cancelDrag = () => {if (pushedHistory) {- currentEditor.update(() => $revertResizeDrag(drag), {- tag: ['skip-scroll-into-view', 'history-merge'],- });+ currentEditor.update(+ () => {+ if (isRow) $revertRowResizeDrag(drag as RowResizeDragSnapshot);+ else $revertResizeDrag(drag as ResizeDragSnapshot);+ },+ {+ tag: ['skip-scroll-into-view', 'history-merge'],+ }+ );}cleanup();};@@ -138,6 +187,7 @@ export function TableCellResizer() {document.removeEventListener('keydown', onKeyDown);document.body.style.cursor = previousCursor;setDragEdge(undefined);+ setActiveCellKey(undefined);if (isTouch) setActiveCellElem(undefined);};@@ -171,7 +221,7 @@ export function TableCellResizer() {down.target instanceof Node ? getDOMCellFromTarget(down.target) : null;if (!cell) return;const rect = cell.elem.getBoundingClientRect();- const edge: ResizeEdge | undefined =+ const edge: ColumnResizeEdge | undefined =Math.abs(down.clientX - rect.right) <= TOUCH_EDGE_PX? 'right': Math.abs(down.clientX - rect.left) <= TOUCH_EDGE_PX@@ -201,7 +251,7 @@ export function TableCellResizer() {startResize(cell.elem,edge,- { pointerId, clientX: startX, pointerType },+ { pointerId, clientX: startX, clientY: startY, pointerType },cell.elem);};@@ -246,12 +296,20 @@ export function TableCellResizer() {const cellRect = createMemo(() => {layoutTick();- const elem = activeCellElem();- if (!elem?.isConnected) return;- return elem.getBoundingClientRect();+ const currentEditor = editor();+ const key = activeCellKey();+ const elem =+ (key && currentEditor?.getElementByKey(key)) || activeCellElem();+ if (elem?.isConnected) {+ lastCellRect = elem.getBoundingClientRect();+ return lastCellRect;+ }+ if (dragEdge()) return lastCellRect;+ lastCellRect = undefined;+ return undefined;});- const onStripPointerDown = (down: PointerEvent) => {+ const onColumnStripPointerDown = (down: PointerEvent) => {if (down.pointerType === 'mouse' && down.button !== 0) return;const cellElem = activeCellElem();const strip = down.currentTarget;@@ -261,16 +319,43 @@ export function TableCellResizer() {startResize(cellElem, 'right', down, strip);};+ const onRowStripPointerDown = (down: PointerEvent) => {+ if (down.pointerType === 'mouse' && down.button !== 0) return;+ const cellElem = activeCellElem();+ const strip = down.currentTarget;+ if (!cellElem || !(strip instanceof HTMLElement)) return;+ down.preventDefault();+ down.stopPropagation();+ startResize(cellElem, 'bottom', down, strip);+ };+// The strip doubles as the drag indicator on touch, pinned to whichever// border is being dragged.const stripX = (rect: DOMRect) =>dragEdge() === 'left' ? rect.left : rect.right;+ const showColumnStrip = () => {+ const edge = dragEdge();+ if (isTouchDevice()) return edge === 'left' || edge === 'right';+ return !edge || isColumnEdge(edge);+ };++ const showRowStrip = () => {+ if (isTouchDevice()) return false;+ const edge = dragEdge();+ return !edge || edge === 'bottom';+ };++ const rowStripWidth = (rect: DOMRect) =>+ dragEdge() === 'bottom'+ ? rect.width+ : Math.max(0, rect.width - HIT_ZONE_PX);+return (<Show when={cellRect()}>{(rect) => (<ScopedPortal scope="split">- <Show when={!isTouchDevice() || dragEdge()}>+ <Show when={showColumnStrip()}><divclass="group fixed z-20 flex cursor-col-resize touch-none justify-center"style={{@@ -279,7 +364,7 @@ export function TableCellResizer() {width: `${HIT_ZONE_PX}px`,height: `${rect().height}px`,}}- onPointerDown={onStripPointerDown}+ onPointerDown={onColumnStripPointerDown}><divclass="h-full w-[3px] bg-accent transition-opacity"@@ -290,6 +375,26 @@ export function TableCellResizer() {/></div></Show>+ <Show when={showRowStrip()}>+ <div+ class="group fixed z-20 flex cursor-row-resize touch-none items-center"+ style={{+ left: `${rect().left}px`,+ top: `${rect().bottom - HIT_ZONE_PX / 2}px`,+ width: `${rowStripWidth(rect())}px`,+ height: `${HIT_ZONE_PX}px`,+ }}+ onPointerDown={onRowStripPointerDown}+ >+ <div+ class="h-[3px] w-full bg-accent transition-opacity"+ classList={{+ 'opacity-100': dragEdge() === 'bottom',+ 'opacity-0 group-hover:opacity-70': dragEdge() !== 'bottom',+ }}+ />+ </div>+ </Show></ScopedPortal>)}</Show>diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableCellResize.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableCellResize.test.tsindex 9054547cf5..3361e86193 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableCellResize.test.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableCellResize.test.ts@@ -2,15 +2,20 @@ import {$createTableCellNode,$createTableNode,$createTableRowNode,+ $isTableRowNode,TableCellHeaderStates,} from '@lexical/table';import { $getRoot, type LexicalEditor } from 'lexical';import { afterEach, describe, expect, it } from 'vitest';import {$applyResizeDrag,+ $applyRowResizeDrag,$captureResizeDrag,+ $captureRowResizeDrag,$revertResizeDrag,+ $revertRowResizeDrag,MIN_COLUMN_WIDTH,+ MIN_ROW_HEIGHT,} from './tableCellResize';import {$getCell,@@ -36,15 +41,15 @@ function getCellElement(}// jsdom lays nothing out, so rendered sizes are stubbed per element.-function stubRect(elem: HTMLElement, width: number) {+function stubRect(elem: HTMLElement, width: number, height = 0) {elem.getBoundingClientRect = () =>({width,- height: 0,+ height,top: 0,left: 0,right: width,- bottom: 0,+ bottom: height,x: 0,y: 0,toJSON: () => ({}),@@ -55,6 +60,25 @@ function getColWidths(editor: LexicalEditor): readonly number[] | undefined {return editor.read(() => $getTable().getColWidths());}+function getRowElement(editor: LexicalEditor, row: number): HTMLElement {+ const rowKey = editor.read(() => {+ const rowNode = $getTable().getChildren().filter($isTableRowNode)[row];+ return rowNode.getKey();+ });+ const elem = editor.getElementByKey(rowKey);+ if (!elem) throw new Error('no row element');+ return elem;+}++function getRowHeights(editor: LexicalEditor): (number | undefined)[] {+ return editor.read(() =>+ $getTable()+ .getChildren()+ .filter($isTableRowNode)+ .map((row) => row.getHeight())+ );+}+describe('table column resize drag', () => {afterEach(() => {document.body.innerHTML = '';@@ -200,3 +224,120 @@ describe('table column resize drag', () => {expect(getColWidths(editor)).toBeUndefined();});});++describe('table row resize drag', () => {+ afterEach(() => {+ document.body.innerHTML = '';+ });++ it('writes height only on the dragged row, leaving siblings unset', async () => {+ const editor = createTestEditor();+ await buildTable(editor, coordGrid(2, 2));+ stubRect(getRowElement(editor, 0), 0, 40);+ stubRect(getRowElement(editor, 1), 0, 40);++ const drag = editor.read(() =>+ $captureRowResizeDrag(editor, getCellElement(editor, 0, 0), 1)+ );+ expect(drag).toMatchObject({+ baseHeight: 40,+ revertHeight: undefined,+ });++ editor.update(() => $applyRowResizeDrag(drag!, 24));+ expect(getRowHeights(editor)).toEqual([64, undefined]);++ // Each frame applies against the drag-start snapshot, not the last frame.+ editor.update(() => $applyRowResizeDrag(drag!, 10));+ expect(getRowHeights(editor)).toEqual([50, undefined]);+ });++ it('clamps the row to the minimum height', async () => {+ const editor = createTestEditor();+ await buildTable(editor, coordGrid(1, 1));+ stubRect(getRowElement(editor, 0), 0, 80);++ const drag = editor.read(() =>+ $captureRowResizeDrag(editor, getCellElement(editor, 0, 0), 1)+ );+ editor.update(() => $applyRowResizeDrag(drag!, -1000));+ expect(getRowHeights(editor)).toEqual([MIN_ROW_HEIGHT]);+ });++ it('resizes the last spanned row of a merged cell', async () => {+ const editor = createTestEditor();+ await new Promise<void>((resolve) => {+ editor.update(+ () => {+ const table = $createTableNode();+ const mergedRow = $createTableRowNode();+ const merged = $createTableCellNode(TableCellHeaderStates.NO_STATUS);+ merged.setRowSpan(2);+ mergedRow.append(+ merged,+ $createTableCellNode(TableCellHeaderStates.NO_STATUS)+ );+ const continuation = $createTableRowNode();+ continuation.append(+ $createTableCellNode(TableCellHeaderStates.NO_STATUS)+ );+ table.append(mergedRow, continuation);+ $getRoot().clear().append(table);+ },+ { onUpdate: () => resolve() }+ );+ });+ stubRect(getRowElement(editor, 0), 0, 40);+ stubRect(getRowElement(editor, 1), 0, 50);++ const drag = editor.read(() =>+ $captureRowResizeDrag(editor, getCellElement(editor, 0, 0), 1)+ );+ expect(drag).toMatchObject({+ baseHeight: 50,+ revertHeight: undefined,+ });++ editor.update(() => $applyRowResizeDrag(drag!, 20));+ expect(getRowHeights(editor)).toEqual([undefined, 70]);+ });++ it('reverts a cancelled drag to the pre-drag height', async () => {+ const editor = createTestEditor();+ await buildTable(editor, coordGrid(1, 1));+ await new Promise<void>((resolve) => {+ editor.update(+ () => {+ const [row] = $getTable().getChildren().filter($isTableRowNode);+ row.setHeight(48);+ },+ { onUpdate: () => resolve() }+ );+ });+ stubRect(getRowElement(editor, 0), 0, 48);++ const drag = editor.read(() =>+ $captureRowResizeDrag(editor, getCellElement(editor, 0, 0), 1)+ );+ editor.update(() => $applyRowResizeDrag(drag!, 30));+ expect(getRowHeights(editor)).toEqual([78]);++ editor.update(() => $revertRowResizeDrag(drag!));+ expect(getRowHeights(editor)).toEqual([48]);+ });++ it('reverts to unset height when the row had none', async () => {+ const editor = createTestEditor();+ await buildTable(editor, coordGrid(2, 1));+ stubRect(getRowElement(editor, 0), 0, 40);++ const drag = editor.read(() =>+ $captureRowResizeDrag(editor, getCellElement(editor, 0, 0), 1)+ );+ editor.update(() => $applyRowResizeDrag(drag!, 25));+ expect(getRowHeights(editor)).toEqual([65, undefined]);++ editor.update(() => $revertRowResizeDrag(drag!));+ expect(getRowHeights(editor)).toEqual([undefined, undefined]);+ });+});diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableCellResize.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableCellResize.tsindex 241236f815..5234f6e29e 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableCellResize.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableCellResize.ts@@ -1,14 +1,18 @@/**- * @file Column resize logic for tables, driven by the TableCellResizer- * component. A drag captures a snapshot up front (which column, the rendered- * widths, and the stored widths to restore on cancel), then applies its+ * @file Column and row resize logic for tables, driven by the TableCellResizer+ * component. A drag captures a snapshot up front (which column/row, the+ * rendered size, and the stored size to restore on cancel), then applies its* running delta against that snapshot on every frame.+ *+ * Row height is optional: unset rows stay content-sized and serialize without+ * a `height` attribute. Dragging a row writes height only on that row.*/import {$computeTableMapSkipCellCheck,$getTableNodeFromLexicalNodeOrThrow,$isTableCellNode,$isTableNode,+ $isTableRowNode,} from '@lexical/table';import {$getNearestNodeFromDOMNode,@@ -17,6 +21,7 @@ import {} from 'lexical';export const MIN_COLUMN_WIDTH = 120;+export const MIN_ROW_HEIGHT = 33;// Which vertical edge of the cell is being dragged. Both name a column// border: 'right' resizes the cell's own (last spanned) column, 'left' the@@ -100,3 +105,61 @@ export function $revertResizeDrag(drag: ResizeDragSnapshot): void {if (!$isTableNode(tableNode) || !tableNode.isAttached()) return;tableNode.setColWidths(drag.revertWidths);}++export type RowResizeDragSnapshot = {+ rowKey: string;+ // Rendered row height at drag start; the drag applies its delta to this+ // so the grabbed edge stays under the pointer even when the stored height+ // is unset (content-sized) or disagrees with layout.+ baseHeight: number;+ revertHeight: number | undefined;+};++export function $captureRowResizeDrag(+ editor: LexicalEditor,+ cellElem: HTMLElement,+ zoom: number+): RowResizeDragSnapshot | undefined {+ const cellNode = $getNearestNodeFromDOMNode(cellElem);+ if (!$isTableCellNode(cellNode)) return;+ const tableNode = $getTableNodeFromLexicalNodeOrThrow(cellNode);++ const [tableMap] = $computeTableMapSkipCellCheck(tableNode, null, null);+ const position = tableMap.flat().find((value) => value.cell === cellNode);+ if (!position) return;+ // A merged cell's bottom edge belongs to the last row it spans.+ const rowIndex = position.startRow + cellNode.getRowSpan() - 1;+ const rows = tableNode.getChildren().filter($isTableRowNode);+ const rowNode = rows[rowIndex];+ if (!rowNode) return;++ const revertHeight = rowNode.getHeight();+ const rect = editor+ .getElementByKey(rowNode.getKey())+ ?.getBoundingClientRect();+ const baseHeight =+ rect && rect.height > 0+ ? rect.height / zoom+ : (revertHeight ?? MIN_ROW_HEIGHT);++ return {+ rowKey: rowNode.getKey(),+ baseHeight,+ revertHeight,+ };+}++export function $applyRowResizeDrag(+ drag: RowResizeDragSnapshot,+ delta: number+): void {+ const rowNode = $getNodeByKey(drag.rowKey);+ if (!$isTableRowNode(rowNode) || !rowNode.isAttached()) return;+ rowNode.setHeight(Math.max(MIN_ROW_HEIGHT, drag.baseHeight + delta));+}++export function $revertRowResizeDrag(drag: RowResizeDragSnapshot): void {+ const rowNode = $getNodeByKey(drag.rowKey);+ if (!$isTableRowNode(rowNode) || !rowNode.isAttached()) return;+ rowNode.setHeight(drag.revertHeight);+}diff --git a/packages/lexical-core/tests/tables.test.ts b/packages/lexical-core/tests/tables.test.tsindex 81c6fbeab4..c52ba29622 100644--- a/packages/lexical-core/tests/tables.test.ts+++ b/packages/lexical-core/tests/tables.test.ts@@ -146,6 +146,32 @@ describe('m-table internal transformer', () => {});});+ it('serializes height only on rows that have one', async () => {+ const editor = createTestEditor();++ await buildEditorState(editor, () => {+ const table = $createTableNode();+ const autoRow = $createTableRowNode();+ autoRow.append($createCell('a'));+ const tallRow = $createTableRowNode();+ tallRow.setHeight(48);+ tallRow.append($createCell('b'));+ table.append(autoRow, tallRow);+ $getRoot().append(table);+ });++ expect(exportMarkdown(editor)).toBe(+ '<m-table><m-table-row><m-table-cell>a</m-table-cell></m-table-row><m-table-row height="48"><m-table-cell>b</m-table-cell></m-table-row></m-table>'+ );++ await importMarkdown(editor, exportMarkdown(editor));+ editor.getEditorState().read(() => {+ const rows = $getFirstTable().getChildren().filter($isTableRowNode);+ expect((rows[0] as TableRowNode).getHeight()).toBeUndefined();+ expect((rows[1] as TableRowNode).getHeight()).toBe(48);+ });+ });+it('serializes plain tables without attributes, identical to the legacy format', async () => {const editor = createTestEditor();