diff --git a/.changeset/35688-cell-editor-layer.md b/.changeset/35688-cell-editor-layer.md new file mode 100644 index 00000000000..f1eca1a2fe0 --- /dev/null +++ b/.changeset/35688-cell-editor-layer.md @@ -0,0 +1,15 @@ +--- +'@object-ui/components': patch +'@object-ui/plugin-grid': patch +--- + +feat(grid): the inline cell editor floats over its cell, so the row keeps its height; a selected cell that is cut off shows its whole value + +Clause-②: no +Metadata-protocol: none + +In `data-table` (and so in every grid `ObjectGrid` draws): + +- **The editor draws on a layer over the cell** instead of inside it. The layer's top-left corner sits on the cell's, it is at least as wide as the column and grows wider or taller where the editor needs it (an address form, a record picker, a multi-line text), and neither the row's height nor any column's width changes. Near the bottom of the window it opens upward, near the right edge it shifts left, and its height is capped at the space left, scrolling inside. A cell partly hidden behind a frozen column, a right-pinned column or the sticky header is scrolled clear first; scrolling the cell out of sight commits the edit, as a click outside does. The layer stays inside the cell's DOM, so click-outside, Escape, Enter / Tab and focus behave as before. Tab inside the layer goes where it went before: the select-first grid commits and moves, other grids let the browser move focus. +- **`ObjectGrid` sizes the layer per field type**: an address or location starts 22rem wide, a multi-line text, markdown, code or JSON 20rem, a lookup, master-detail or user 18rem, a multi-select, tags or checkboxes 16rem, a date, date-time, phone, URL, email or currency 14rem, anything else 10rem; never narrower than its cell. +- **On the select-first grid** (the list page), a selected cell whose value the column cuts off shows it in full on a layer over the cell, wrapped and scrolling past a few lines. Escape, an arrow key or a click elsewhere closes it; Enter or a double-click turns it into the editor in the same place and at least the same size. Enter on a checkbox cell flips it, as Space and a second click already did, instead of opening an editor. diff --git a/content/docs/frontend/plugins/plugin-grid.mdx b/content/docs/frontend/plugins/plugin-grid.mdx index 058c36f2fa8..26a95d8bc1d 100644 --- a/content/docs/frontend/plugins/plugin-grid.mdx +++ b/content/docs/frontend/plugins/plugin-grid.mdx @@ -367,6 +367,13 @@ through the host's data source (`dataSource.update`) with no callback to wire. editor. There is no `editable` key on `ListColumn`. - **Visual feedback**: editable cells show a hover state, and the input is focused and selected when editing begins +- **The editor floats over its cell** (objectstack#35688): it opens on a layer + anchored to the cell's top-left corner, at least as wide as the column and + wider where its field type needs it (an address form, a record picker), so + the row keeps its height and no other column moves. Near the bottom of the + window the layer opens upward, near the right edge it shifts left, and a + cell half hidden behind a frozen column or the header is scrolled into view + first. Scrolling the cell out of sight commits the edit. To own persistence in a React host, supply `onCellChange` as a **component prop** — it is not a schema key. @@ -383,6 +390,11 @@ object and the view does not declare `userActions.editInline: false`, and - **A click selects** a cell (a ring around it); it neither edits nor opens the record. A link a cell draws (the name, a lookup, a phone or an email) keeps its own click. On a touch screen a tap opens the record. +- **A cut-off value shows in full** when its cell is selected: a long text, a + multi-line text or a list of tags that the column truncates opens on a + layer over the cell, wrapped, scrolling inside past a few lines. Escape, an + arrow key or a click elsewhere closes it; Enter or a double-click turns it + into the editor in the same place and at the same size. - **Editing** starts on a double-click, Enter or F2 (the value kept, caret at its end), or by typing, which replaces the value; an input method's composition is kept whole. Backspace or Delete opens an empty editor and @@ -393,7 +405,7 @@ object and the view does not declare `userActions.editInline: false`, and elsewhere commits. - **Selected cell keys:** the arrows and Tab move the selection; Space is typed like any other key and opens the editor (a checkbox cell flips instead, as - does a second click on it); Ctrl/Cmd+C copies; Ctrl/Cmd+V converts the text + do Enter and a second click on it); Ctrl/Cmd+C copies; Ctrl/Cmd+V converts the text to the field's type and commits it; Escape clears the selection. The record opens from the name link, or a tap on a touch screen. - **A cell that opens no editor says why** on the cell: the field is read-only, diff --git a/ui/packages/components/src/__tests__/data-table-cell-overlay-35688.test.tsx b/ui/packages/components/src/__tests__/data-table-cell-overlay-35688.test.tsx new file mode 100644 index 00000000000..dadcd275fcc --- /dev/null +++ b/ui/packages/components/src/__tests__/data-table-cell-overlay-35688.test.tsx @@ -0,0 +1,193 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * `data-table`'s cell layer (objectstack#35688): the editor, and the full + * content of a cut-off selected cell, draw on a layer over the cell instead of + * inside it, so the row keeps its height. Layout itself (row height 32, the + * flip at the viewport's edge, painting above frozen columns) is a browser + * reading on the PR; jsdom has no layout, so these pin the structure and the + * gestures. + * + * 1. The editor sits in a fixed-position layer inside its cell, the cell is + * raised above the sticky cells, and nothing is drawn in the cell's flow. + * An injected (host) editor goes on the same layer. + * 2. A selected cell whose content is cut off shows it in full on a layer; + * one that fits shows none. + * 3. Enter on that preview opens the editor in its place, at least the + * preview's size; Esc there does not bring the preview back. + * 4. Esc on the preview closes it and keeps the cell selected; an arrow key + * moves the selection and the preview with it. + * 5. Enter on a two-state cell flips it and opens no layer. + * 6. Scrolling the open editor's cell out of the table's box commits it. + */ +import React from 'react'; +import { describe, it, expect, afterEach, beforeEach, vi } from 'vitest'; +import { render, fireEvent, cleanup, act } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import { ComponentRegistry } from '@object-ui/core'; +// Registers `data-table` at module scope, not in a hook (objectui#3010). +import '../renderers'; +// `react-page` reaches a dynamic `import('@object-ui/react-runtime')`: pay its load +// at collection, never inside a case's clocked window (`check:test-source-alias`). +import '@object-ui/react-runtime'; +import { GridCellSelectionProvider } from '../context/gridCellSelection'; + +const LONG = 'A long note that runs well past the width of its column'; + +const ROWS = [ + { id: '1', name: 'Alpha', note: LONG, done: false }, + { id: '2', name: 'Beta', note: 'Short', done: true }, +]; + +// jsdom draws nothing: a text longer than ten characters reads as cut off. +const proto = HTMLElement.prototype; +const saved = { + scrollWidth: Object.getOwnPropertyDescriptor(proto, 'scrollWidth'), + clientWidth: Object.getOwnPropertyDescriptor(proto, 'clientWidth'), +}; +beforeEach(() => { + Object.defineProperty(proto, 'scrollWidth', { configurable: true, get() { return (this.textContent ?? '').length * 10; } }); + Object.defineProperty(proto, 'clientWidth', { configurable: true, get() { return 100; } }); +}); +afterEach(() => { + cleanup(); + for (const [k, d] of Object.entries(saved)) { + if (d) Object.defineProperty(proto, k, d); + else delete (proto as unknown as Record)[k]; + } +}); + +function renderTable(extra: Record = {}) { + const DataTable = ComponentRegistry.get('data-table')!; + const onCellChange = vi.fn(); + const schema = { + type: 'data-table', + columns: [ + { header: 'Name', accessorKey: 'name' }, + { header: 'Note', accessorKey: 'note' }, + { header: 'Done', accessorKey: 'done', type: 'boolean' }, + ], + data: ROWS, + editable: true, + singleClickEdit: true, + searchable: false, + pagination: false, + onCellChange, + ...extra, + }; + const utils = render( + + + , + ); + const cell = (row: number, col: number) => + utils.container.querySelectorAll('tbody tr')[row].querySelectorAll('td[data-grid-cell]')[col] as HTMLElement; + const catcher = () => utils.container.querySelector('[data-slot="cell-type-catcher"]')!; + const editorLayer = () => utils.container.querySelector('[data-slot="cell-editor-overlay"]'); + const previewLayer = () => utils.container.querySelector('[data-slot="cell-preview-overlay"]'); + return { ...utils, cell, catcher, editorLayer, previewLayer, onCellChange }; +} + +describe('data-table — the editor and a cut-off cell draw on a layer over the cell (objectstack#35688)', () => { + it('1. the editor sits in a fixed-position layer inside its cell, and the cell is raised', () => { + const t = renderTable(); + fireEvent.click(t.cell(0, 0)); + fireEvent.keyDown(t.catcher(), { key: 'Enter' }); + const layer = t.editorLayer(); + expect(layer).not.toBeNull(); + // Inside the cell's DOM, so the grid's own `contains` reads hold. + expect(t.cell(0, 0).contains(layer)).toBe(true); + expect(layer!.querySelector('input')).toHaveValue('Alpha'); + // Out of the cell's flow: Radix places the layer's wrapper `fixed`. + expect(layer!.closest('[data-radix-popper-content-wrapper]')!.style.position).toBe('fixed'); + expect(t.cell(0, 0).className).toMatch(/\bz-30\b/); + expect(t.cell(1, 0).className).not.toMatch(/\bz-30\b/); + }); + + it('1b. a host-injected editor goes on the same layer', () => { + const t = renderTable({ + renderCellEditor: ({ value, stage }: { value: unknown; stage: (v: unknown) => void }) => ( + stage(e.target.value)} /> + ), + }); + fireEvent.click(t.cell(0, 0)); + fireEvent.keyDown(t.catcher(), { key: 'Enter' }); + expect(t.editorLayer()!.querySelector('[data-testid="host-editor"]')).not.toBeNull(); + }); + + it('2. a selected cell that is cut off shows its whole content on a layer; one that fits shows none', () => { + const t = renderTable(); + fireEvent.click(t.cell(0, 1)); + expect(t.previewLayer()).toHaveTextContent(LONG); + expect(t.cell(0, 1).contains(t.previewLayer())).toBe(true); + // Its height cap keeps the space-available cap (one class, not two that merge away). + expect(t.previewLayer()!.className).toContain('max-h-[min(16rem,var(--radix-popper-available-height))]'); + expect(t.previewLayer()!.className).not.toMatch(/(^|\s)max-h-64(\s|$)/); + fireEvent.click(t.cell(0, 0)); + expect(t.previewLayer()).toBeNull(); + }); + + it('3. Enter on the preview opens the editor in its place, at least its size; Esc does not bring it back', () => { + const t = renderTable(); + fireEvent.click(t.cell(0, 1)); + const preview = t.previewLayer()!; + vi.spyOn(preview, 'getBoundingClientRect').mockReturnValue({ width: 300, height: 72, top: 0, left: 0, right: 300, bottom: 72, x: 0, y: 0, toJSON: () => ({}) } as DOMRect); + fireEvent.keyDown(t.catcher(), { key: 'Enter' }); + expect(t.previewLayer()).toBeNull(); + const layer = t.editorLayer()!; + expect(layer.querySelector('input')).toHaveValue(LONG); + expect(layer.style.getPropertyValue('--cell-overlay-min-w')).toBe('300px'); + expect(layer.style.getPropertyValue('--cell-overlay-min-h')).toBe('72px'); + // The utility that reads the seed survives the per-type floor, which rides an inner box. + expect(layer.className).toContain('min-w-[max(var(--radix-popper-anchor-width),var(--cell-overlay-min-w,0px))]'); + expect(layer.className).not.toMatch(/(^|\s)min-w-40(\s|$)/); + expect(layer.querySelector('.min-w-40')).not.toBeNull(); + fireEvent.keyDown(layer.querySelector('input')!, { key: 'Escape' }); + expect(t.editorLayer()).toBeNull(); + expect(t.previewLayer()).toBeNull(); + expect(t.cell(0, 1)).toHaveAttribute('data-selected-cell'); + }); + + it('4. Esc closes the preview and keeps the selection; an arrow key moves on', () => { + const t = renderTable(); + fireEvent.click(t.cell(0, 1)); + fireEvent.keyDown(t.catcher(), { key: 'Escape' }); + expect(t.previewLayer()).toBeNull(); + expect(t.cell(0, 1)).toHaveAttribute('data-selected-cell'); + fireEvent.click(t.cell(1, 1)); + expect(t.previewLayer()).toBeNull(); + fireEvent.keyDown(t.catcher(), { key: 'ArrowUp' }); + expect(t.cell(0, 1)).toHaveAttribute('data-selected-cell'); + expect(t.previewLayer()).toHaveTextContent(LONG); + }); + + it('5. Enter on a two-state cell flips it and opens no layer', () => { + const t = renderTable(); + fireEvent.click(t.cell(0, 2)); + fireEvent.keyDown(t.catcher(), { key: 'Enter' }); + expect(t.editorLayer()).toBeNull(); + expect(t.onCellChange).toHaveBeenCalledWith(0, 'done', true, expect.anything()); + }); + + it('6. scrolling the open editor\'s cell out of the table\'s box commits it', () => { + const t = renderTable(); + fireEvent.click(t.cell(0, 0)); + fireEvent.keyDown(t.catcher(), { key: 'Enter' }); + fireEvent.change(t.editorLayer()!.querySelector('input')!, { target: { value: 'Alpha 2' } }); + // The table's scroll box, and a cell scrolled past its left edge. + const box = t.cell(0, 0).closest('table')!.parentElement!; + box.style.overflowX = 'auto'; + vi.spyOn(box, 'getBoundingClientRect').mockReturnValue({ left: 0, top: 0, right: 100, bottom: 100, width: 100, height: 100, x: 0, y: 0, toJSON: () => ({}) } as DOMRect); + Object.defineProperty(box, 'clientHeight', { configurable: true, value: 100 }); + vi.spyOn(t.cell(0, 0), 'getBoundingClientRect').mockReturnValue({ left: -200, top: 40, right: -50, bottom: 72, width: 150, height: 32, x: -200, y: 40, toJSON: () => ({}) } as DOMRect); + act(() => { box.dispatchEvent(new Event('scroll')); }); + expect(t.editorLayer()).toBeNull(); + expect(t.onCellChange).toHaveBeenCalledWith(0, 'name', 'Alpha 2', expect.anything()); + }); +}); diff --git a/ui/packages/components/src/renderers/complex/data-table.tsx b/ui/packages/components/src/renderers/complex/data-table.tsx index 19b0f7649e4..cfc79a5366f 100644 --- a/ui/packages/components/src/renderers/complex/data-table.tsx +++ b/ui/packages/components/src/renderers/complex/data-table.tsx @@ -19,6 +19,8 @@ import { caretToEnd, defaultTyping, defaultValueFromText, firstEditorControl, is import { useHorizontalOverflow, HOVER_SCROLLBAR_CLASSES } from '../../custom/use-horizontal-overflow'; import { ActiveListRow, listRecordIdOf } from '../../custom/record-list-face'; import { describeIgnoredBind, describeNonArrayData } from './dataTableBindDiagnostic'; +import { CellOverlay } from './dataTableCellOverlay'; +import { CELL_OVERLAY_HOST_CLASS, isCellContentTruncated, type CellOverlaySize } from './dataTableCellOverlayDom'; import { ComponentRegistry, compareSortValues, csvBlob, evalRowPredicate, formatDate, hasDeclaredPredicate, isActionSwitchedOff, formatDateTime, fromDateTimeInputValue, getSortValue, isEmptyValue, isImpossibleStoredDay, toDateInputValue, toDateTimeInputValue } from '@object-ui/core'; import type { DataTableSchema, TableColumn, TableSortItem, TableColumnType } from '@object-ui/types'; import type { SortDirection } from '@objectstack/spec/shared'; @@ -96,6 +98,14 @@ import { // emit seam (`normalizeTableColumnType`), so an undeclared spelling can no // longer reach this set. Typed as `TableColumnType` so re-adding one is a tsc // error rather than a silent re-opening of the undeclared dialect. +/** + * objectstack#35688 — how wide a built-in editor's layer starts (a host's + * injected editor sizes its own). Never narrower than the cell. + */ +function builtInEditorWidthClass(type: TableColumnType | undefined): string { + return type === 'date' || type === 'datetime' ? 'min-w-56' : 'min-w-40'; +} + const NUMERIC_EDIT_TYPES = new Set(['number', 'currency', 'percent']); /** @@ -3537,6 +3547,22 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { : null; const setSelectedCell = (pos: { rowIndex: number; colIndex: number } | null) => setSelectedCellKey(pos ? { rowKey: pendingRowKeyOf(paginatedData[pos.rowIndex]), columnKey: columns[pos.colIndex].accessorKey } : null); + // objectstack#35688 — a selected cell whose content is cut off shows it in + // full on a layer over the cell. Measured after the selection draws. + // It opens when the selection lands on such a cell, not when an edit there + // ends; Esc, a click elsewhere or an arrow key closes it. + const [previewKey, setPreviewKey] = useState(null); + const selectedPosKey = selectedPos ? `${selectedPos.rowIndex}:${selectedPos.colIndex}` : null; + const previewSeenKeyRef = useRef(null); + useLayoutEffect(() => { + const landed = selectedPosKey !== previewSeenKeyRef.current; + previewSeenKeyRef.current = selectedPosKey; + if (!selectedPosKey || editingCell || !landed) { setPreviewKey(null); return; } + const display = tableRef.current?.querySelector('[data-selected-cell] [data-slot="cell-display"]'); + setPreviewKey(isCellContentTruncated(display ?? null) ? selectedPosKey : null); + }, [selectedPosKey, editingCell]); + // The preview's size, taken as the editor replaces it, so the layer does not jump. + const [editorSeedSize, setEditorSeedSize] = useState(null); const focusSelectionRef = useRef(false); useEffect(() => { if (!focusSelectionRef.current || editingCell) return; @@ -3589,6 +3615,11 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { return; } setCellNotice(null); + const preview = previewKey === `${rowIndex}:${colIndex}` + ? tableRef.current?.querySelector('[data-slot="cell-preview-overlay"]') + : null; + const rect = preview?.getBoundingClientRect(); + setEditorSeedSize(rect ? { width: rect.width, height: rect.height } : null); setSelectedCell({ rowIndex, colIndex }); startEdit(row, col.accessorKey, seed); }; @@ -3671,7 +3702,11 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { if (e.key === 'Escape') { const rowKey = pendingRowKeyOf(row); if (cellNotice) setCellNotice(null); - else if (autosaves && pendingChanges.get(rowKey)?.changes && col.accessorKey in pendingChanges.get(rowKey)!.changes && !runningSavesRef.current.has(rowKey)) { + else if (previewKey !== null) { + // objectstack#35688 — the full-content preview closes; the cell stays selected. + e.preventDefault(); + setPreviewKey(null); + } else if (autosaves && pendingChanges.get(rowKey)?.changes && col.accessorKey in pendingChanges.get(rowKey)!.changes && !runningSavesRef.current.has(rowKey)) { // objectstack#35685 — a kept (refused) edit: Esc drops it. e.preventDefault(); discardCellChange(rowKey, col.accessorKey); @@ -3708,7 +3743,9 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { } if ((e.key === 'Enter' || e.key === 'F2') && bare && !e.shiftKey) { e.preventDefault(); - attemptEdit(rowIndex, colIndex); + // objectstack#35688 — a two-state cell flips in place; it opens no layer. + if (togglesCell(row, col)) toggleCell(rowIndex, colIndex); + else attemptEdit(rowIndex, colIndex); } else if (e.key === ' ' && bare && togglesCell(row, col)) { // A two-state cell flips; on any other cell Space is typed like any key // and opens the editor (the catcher reads it). @@ -4849,6 +4886,11 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { const isFrozen = frozenColumns > 0 && colIndex < frozenColumns; // objectstack#35684 — the selected cell of the select-first model. const isSelectedCell = selectFirst && selectedPos?.rowIndex === rowIndex && selectedPos.colIndex === colIndex; + const showsPreview = isSelectedCell && !isEditing && previewKey === `${rowIndex}:${colIndex}`; + // What the cell draws; the preview layer draws the same, unclipped. + const drawCell = (): React.ReactNode => (typeof col.cell === 'function' + ? col.cell(cellValue, row) + : (cellValue != null && typeof cellValue === 'object' ? String(cellValue) : formatCellValue(cellValue) as any)); const frozenOffset = isFrozen ? measuredStickyLefts?.[leadingCellCount + colIndex] ?? columns.slice(0, colIndex).reduce((sum, c, i) => { @@ -4880,6 +4922,10 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { cellError !== undefined && "ring-2 ring-inset ring-destructive", isFrozen && ['sticky z-10 bg-background', STICKY_ROW_TINT], isFrozen && colIndex === frozenColumns - 1 && scrolledX && FROZEN_EDGE_SHADOW, + // objectstack#35688 — the cell under an open layer paints above + // the sticky header and the frozen columns. + (isEditing || showsPreview) && !isFrozen && 'relative', + (isEditing || showsPreview) && CELL_OVERLAY_HOST_CLASS, )} style={{ width: columnWidth, @@ -5036,7 +5082,15 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { ); })()} {isEditing ? ( - (() => { + { flushInjectedEditor(); saveEditRef.current(true); }} + > + {/* The per-type floor rides an inner box: on the layer's own + class it would replace the layer's cell-width floor. */} +
{(() => { // Type-aware inline editor. `col.type` is forwarded // from a producer's column inference, folded onto the // DECLARED vocabulary at that producer's emit seam @@ -5250,7 +5304,8 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { className="h-8 px-2 py-1" /> ); - })() + })()}
+
) : (
{ // The cell half of the drawn-size read the // auto width is estimated from (objectui#11682). data-auto-width-key={autoWidthKey(col)} + data-slot="cell-display" > - {typeof col.cell === 'function' - ? col.cell(cellValue, row) - : (cellValue != null && typeof cellValue === 'object' ? String(cellValue) : formatCellValue(cellValue) as any)} + {drawCell()}
)} + {showsPreview && ( + // objectstack#35688 — the whole content of a cut-off cell, in place. + setPreviewKey(null)}> + {drawCell()} + + )} ); })} diff --git a/ui/packages/components/src/renderers/complex/dataTableCellOverlay.tsx b/ui/packages/components/src/renderers/complex/dataTableCellOverlay.tsx new file mode 100644 index 00000000000..2dd5396017b --- /dev/null +++ b/ui/packages/components/src/renderers/complex/dataTableCellOverlay.tsx @@ -0,0 +1,176 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +import * as React from 'react'; +import * as PopoverPrimitive from '@radix-ui/react-popover'; +import { cn } from '../../lib/utils'; +import { caretToEnd, firstEditorControl } from './dataTableCellSelection'; +import { isCellHidden, revealCell, type CellOverlaySize } from './dataTableCellOverlayDom'; + + +/** + * A layer drawn over one grid cell, top-left on the cell's own corner, at least + * as wide as the cell, free to grow wider and taller (objectstack#35688). + * + * Invariants: + * - The table's layout never moves: the layer is `position: fixed` (Radix + * Popper), so neither the row height nor any column width changes. + * - The layer stays in the cell's DOM subtree (no portal). Every `contains` + * read the grid makes — click-outside, focus, keydown routing — keeps seeing + * the editor as inside its cell. + * - Near the viewport's bottom it flips so its bottom edge sits on the cell's + * bottom edge; near the right edge it shifts left. Its height is capped at + * the space available and scrolls inside. + * - On open, the cell is scrolled clear of the frozen columns, the right-pinned + * columns and the sticky header; once a scroll hides the cell behind them or + * out of the table's box, `onHidden` runs (the grid commits or collapses). + * - The host cell is raised above the sticky header and frozen columns while + * the layer is open (`CELL_OVERLAY_HOST_CLASS`), because a fixed descendant + * still paints inside its nearest stacking context. + */ +export function CellOverlay({ + children, + className, + kind, + minSize, + onHidden, +}: { + children: React.ReactNode; + className?: string; + /** `preview` = the read-only full content of a selected cell; `editor` = the editor. */ + kind: 'preview' | 'editor'; + minSize?: CellOverlaySize | null; + onHidden?: () => void; +}) { + const markerRef = React.useRef(null); + const contentRef = React.useRef(null); + const [cell, setCell] = React.useState(null); + const [cellHeight, setCellHeight] = React.useState(0); + const onHiddenRef = React.useRef(onHidden); + React.useLayoutEffect(() => { + onHiddenRef.current = onHidden; + }); + + React.useLayoutEffect(() => { + const td = markerRef.current?.closest('td,[role="gridcell"]') ?? null; + if (td) { + revealCell(td); + setCellHeight(td.getBoundingClientRect().height); + } + setCell(td); + }, []); + + // A scroll that hides the cell closes its layer. + React.useEffect(() => { + if (!cell || typeof document === 'undefined') return undefined; + let fired = false; + const onScroll = () => { + if (fired || !isCellHidden(cell)) return; + fired = true; + onHiddenRef.current?.(); + }; + document.addEventListener('scroll', onScroll, { capture: true, passive: true }); + return () => document.removeEventListener('scroll', onScroll, { capture: true }); + }, [cell]); + + // The editor takes the caret once the layer is placed: Radix keeps an + // unplaced layer hidden, and a hidden control refuses focus. + React.useEffect(() => { + if (kind !== 'editor' || !cell) return undefined; + let frame = 0; + let frames = 0; + const place = () => { + const host = contentRef.current; + if (host?.contains(document.activeElement)) return; + const control = host ? firstEditorControl(host) : null; + if (control) { + control.focus({ preventScroll: true }); + caretToEnd(control); + if (host?.contains(document.activeElement)) return; + } + if (++frames < 30) frame = requestAnimationFrame(place); + }; + place(); + return () => cancelAnimationFrame(frame); + }, [kind, cell]); + + const virtualRef = React.useMemo( + () => ({ current: { getBoundingClientRect: () => (cell ?? markerRef.current!).getBoundingClientRect() } }), + [cell], + ); + + // Seeded sizes travel as custom properties the static utilities below read. + const seeded = minSize + ? ({ '--cell-overlay-min-w': `${Math.round(minSize.width)}px`, '--cell-overlay-min-h': `${Math.round(minSize.height)}px` } as React.CSSProperties) + : undefined; + + return ( + <> +