fix: table re-renders no longer lose cell focus

This commit is contained in:
Carlos Valente
2026-02-08 17:14:14 +01:00
committed by Carlos Valente
parent f9563fca5f
commit b6a01a52e2
6 changed files with 264 additions and 116 deletions
@@ -1,7 +1,14 @@
import { useCallback, useEffect, useMemo, useRef } from 'react';
import { TableVirtuoso, TableVirtuosoHandle } from 'react-virtuoso';
import { ComponentProps, memo, useCallback, useEffect, useMemo, useRef } from 'react';
import {
ContextProp,
ItemProps,
TableComponents,
TableProps,
TableVirtuoso,
TableVirtuosoHandle,
} from 'react-virtuoso';
import { useTableNav } from '@table-nav/react';
import { ColumnDef, getCoreRowModel, useReactTable } from '@tanstack/react-table';
import { ColumnDef, getCoreRowModel, Table, useReactTable } from '@tanstack/react-table';
import { isOntimeDelay, isOntimeGroup, isOntimeMilestone, OntimeEntry, TimeField } from 'ontime-types';
import EmptyPage from '../../../common/components/state/EmptyPage';
@@ -170,6 +177,28 @@ export default function CuesheetTable({ columns, cuesheetMode, tableRoot = 'cues
const allLeafColumns = table.getAllLeafColumns();
const { rows } = table.getRowModel();
const virtuosoContext = useMemo(
() => ({
columnSizeVars,
cursor,
listeners,
rows,
table,
}),
[columnSizeVars, cursor, listeners, rows, table],
);
const computeItemKey = useCallback((_: number, item: ExtendedEntry) => item.id, []);
const fixedHeaderContent = useCallback(() => {
return table.getHeaderGroups().map((headerGroup) => {
const HeaderComponent = table.getState().columnSizingInfo.isResizingColumn
? CuesheetHeader
: SortableCuesheetHeader;
// if the table is being resized, we render non-sortable headers to avoid performance issues
return <HeaderComponent key={headerGroup.id} cuesheetMode={cuesheetMode} headerGroup={headerGroup} />;
});
}, [cuesheetMode, table]);
const isLoading = !data || status === 'pending';
@@ -191,113 +220,146 @@ export default function CuesheetTable({ columns, cuesheetMode, tableRoot = 'cues
<TableVirtuoso
ref={virtuosoRef}
data={data}
context={virtuosoContext}
style={tableRoot === 'editor' ? { paddingLeft: '1rem' } : undefined}
computeItemKey={computeItemKey}
increaseViewportBy={{ top: 100, bottom: 200 }}
components={{
EmptyPlaceholder: () => <EmptyTableBody text='No data in rundown' />,
Table: ({ style: injectedStyles, ...virtuosoProps }) => {
return (
<table
className={style.cuesheet}
id='cuesheet'
style={{ ...injectedStyles, ...columnSizeVars }}
{...listeners}
{...virtuosoProps}
/>
);
},
TableRow: ({ item: _item, style: injectedStyles, ...virtuosoProps }) => {
// eslint-disable-next-line react/destructuring-assignment
const rowIndex = virtuosoProps['data-index'];
const row = rows[rowIndex];
const key = row.original.id;
const entry = row.original;
const hasCursor = entry.id === cursor;
if (isOntimeGroup(entry)) {
return (
<GroupRow
key={key}
groupId={entry.id}
colour={entry.colour}
rowId={row.id}
rowIndex={row.index}
table={table}
injectedStyles={injectedStyles}
hasCursor={hasCursor}
{...virtuosoProps}
/>
);
}
if (isOntimeDelay(entry)) {
return (
<DelayRow
key={key}
duration={entry.duration}
injectedStyles={injectedStyles}
hasCursor={hasCursor}
{...virtuosoProps}
/>
);
}
if (isOntimeMilestone(entry)) {
return (
<MilestoneRow
key={key}
entryId={entry.id}
isPast={entry.isPast}
parentBgColour={entry.groupColour}
parentId={entry.parent}
colour={entry.colour}
rowId={row.id}
rowIndex={rowIndex}
table={table}
injectedStyles={injectedStyles}
hasCursor={hasCursor}
{...virtuosoProps}
/>
);
}
return (
<EventRow
key={row.id}
id={entry.id}
eventIndex={entry.eventIndex}
colour={entry.colour}
isFirstAfterGroup={entry.isFirstAfterGroup}
isLoaded={entry.isLoaded}
isPast={entry.isPast}
groupColour={entry.groupColour}
flag={entry.flag}
skip={entry.skip}
parent={entry.parent}
rowId={row.id}
rowIndex={rowIndex}
table={table}
injectedStyles={injectedStyles}
hasCursor={hasCursor}
{...virtuosoProps}
/>
);
},
TableHead: (virtuosoProps) => <thead className={style.tableHeader} {...virtuosoProps} />,
}}
fixedHeaderContent={() => {
return table.getHeaderGroups().map((headerGroup) => {
const HeaderComponent = table.getState().columnSizingInfo.isResizingColumn
? CuesheetHeader
: SortableCuesheetHeader;
// if the table is being resized, we render non-sortable headers to avoid performance issues
return <HeaderComponent key={headerGroup.id} cuesheetMode={cuesheetMode} headerGroup={headerGroup} />;
});
}}
components={virtuosoComponents}
fixedHeaderContent={fixedHeaderContent}
/>
<TableMenu />
</>
);
}
interface CuesheetVirtuosoContext {
columnSizeVars: { [key: string]: number };
cursor: string | null;
listeners: ReturnType<typeof useTableNav>['listeners'];
rows: ReturnType<Table<ExtendedEntry>['getRowModel']>['rows'];
table: Table<ExtendedEntry>;
}
const EmptyPlaceholder = memo(function EmptyPlaceholder() {
return <EmptyTableBody text='No data in rundown' />;
});
const CuesheetTableElement = memo(function CuesheetTableElement({
style: injectedStyles,
context,
...virtuosoProps
}: TableProps & ContextProp<CuesheetVirtuosoContext>) {
return (
<table
className={style.cuesheet}
id='cuesheet'
style={{ ...injectedStyles, ...context.columnSizeVars }}
{...context.listeners}
{...virtuosoProps}
/>
);
});
const CuesheetTableHead = memo(function CuesheetTableHead({
context: _context,
className: _className,
...virtuosoProps
}: ComponentProps<'thead'> & ContextProp<CuesheetVirtuosoContext>) {
return <thead className={style.tableHeader} {...virtuosoProps} />;
});
const CuesheetTableRow = memo(function CuesheetTableRow({
item: _item,
style: injectedStyles,
context,
...virtuosoProps
}: ItemProps<ExtendedEntry> & ContextProp<CuesheetVirtuosoContext>) {
// eslint-disable-next-line react/destructuring-assignment
const rowIndex = virtuosoProps['data-index'];
const row = context.rows[rowIndex];
if (!row) {
return null;
}
const key = row.original.id;
const entry = row.original;
const hasCursor = entry.id === context.cursor;
if (isOntimeGroup(entry)) {
return (
<GroupRow
key={key}
groupId={entry.id}
colour={entry.colour}
rowId={row.id}
rowIndex={row.index}
table={context.table}
injectedStyles={injectedStyles}
hasCursor={hasCursor}
{...virtuosoProps}
/>
);
}
if (isOntimeDelay(entry)) {
return (
<DelayRow
key={key}
duration={entry.duration}
injectedStyles={injectedStyles}
hasCursor={hasCursor}
{...virtuosoProps}
/>
);
}
if (isOntimeMilestone(entry)) {
return (
<MilestoneRow
key={key}
entryId={entry.id}
isPast={entry.isPast}
parentBgColour={entry.groupColour}
parentId={entry.parent}
colour={entry.colour}
rowId={row.id}
rowIndex={rowIndex}
table={context.table}
injectedStyles={injectedStyles}
hasCursor={hasCursor}
{...virtuosoProps}
/>
);
}
return (
<EventRow
key={row.id}
id={entry.id}
eventIndex={entry.eventIndex}
colour={entry.colour}
isFirstAfterGroup={entry.isFirstAfterGroup}
isLoaded={entry.isLoaded}
isPast={entry.isPast}
groupColour={entry.groupColour}
flag={entry.flag}
skip={entry.skip}
parent={entry.parent}
rowId={row.id}
rowIndex={rowIndex}
table={context.table}
injectedStyles={injectedStyles}
hasCursor={hasCursor}
{...virtuosoProps}
/>
);
});
const virtuosoComponents: TableComponents<ExtendedEntry, CuesheetVirtuosoContext> = {
EmptyPlaceholder,
Table: CuesheetTableElement,
TableHead: CuesheetTableHead,
TableRow: CuesheetTableRow,
};
@@ -91,6 +91,7 @@ export default function EventRow({
}}
data-cursor={hasCursor}
data-testid='cuesheet-event'
data-entry-id={id}
{...virtuosoProps}
>
{cuesheetMode === AppMode.Edit && (
@@ -127,6 +128,8 @@ export default function EventRow({
}}
tabIndex={-1}
role='cell'
data-testid={`cuesheet-cell-${cell.column.id}`}
data-column-id={cell.column.id}
>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</td>
@@ -5,12 +5,14 @@ import useReactiveTextInput from '../../../../common/components/input/text-input
interface MultiLineCellProps {
initialValue: string;
fieldId?: string;
fieldLabel?: string;
handleUpdate: (newValue: string) => void;
}
export default memo(MultiLineCell);
function MultiLineCell({ initialValue, handleUpdate }: MultiLineCellProps) {
function MultiLineCell({ initialValue, fieldId, fieldLabel, handleUpdate }: MultiLineCellProps) {
const ref = useRef<HTMLTextAreaElement | null>(null);
const submitCallback = useCallback((newValue: string) => handleUpdate(newValue), [handleUpdate]);
@@ -30,6 +32,8 @@ function MultiLineCell({ initialValue, handleUpdate }: MultiLineCellProps) {
onBlur={onBlur}
onKeyDown={onKeyDown}
spellCheck={false}
data-testid={fieldId ? `cuesheet-editor-${fieldId}` : undefined}
aria-label={fieldLabel ? `${fieldLabel} editor` : undefined}
/>
);
}
@@ -5,13 +5,18 @@ import useReactiveTextInput from '../../../../common/components/input/text-input
interface SingleLineCellProps {
initialValue: string;
fieldId?: string;
fieldLabel?: string;
allowSubmitSameValue?: boolean;
handleUpdate: (newValue: string) => void;
handleCancelUpdate?: () => void;
}
const SingleLineCell = forwardRef(
({ initialValue, allowSubmitSameValue, handleUpdate, handleCancelUpdate }: SingleLineCellProps, inputRef) => {
(
{ initialValue, fieldId, fieldLabel, allowSubmitSameValue, handleUpdate, handleCancelUpdate }: SingleLineCellProps,
inputRef,
) => {
const ref = useRef<HTMLInputElement | null>(null);
const submitCallback = useCallback((newValue: string) => handleUpdate(newValue), [handleUpdate]);
@@ -47,6 +52,8 @@ const SingleLineCell = forwardRef(
onChange={onChange}
onBlur={onBlur}
onKeyDown={onKeyDown}
data-testid={fieldId ? `cuesheet-editor-${fieldId}` : undefined}
aria-label={fieldLabel ? `${fieldLabel} editor` : undefined}
/>
);
},
@@ -17,6 +17,10 @@ import MutedText from './MutedText';
import SingleLineCell from './SingleLineCell';
import TimeInput from './TimeInput';
function getColumnLabel(column: CellContext<ExtendedEntry, unknown>['column']): string {
return typeof column.columnDef.header === 'string' ? column.columnDef.header : column.id;
}
function MakeStart({ getValue, row, table, column }: CellContext<ExtendedEntry, unknown>) {
if (!table.options.meta) {
return null;
@@ -146,7 +150,14 @@ function MakeMultiLineField({ row, column, table }: CellContext<ExtendedEntry, u
return <GhostedText multiline>{initialValue}</GhostedText>;
}
return <MultiLineCell initialValue={initialValue as string} handleUpdate={update} />;
return (
<MultiLineCell
initialValue={initialValue as string}
fieldId={column.id}
fieldLabel={getColumnLabel(column)}
handleUpdate={update}
/>
);
}
function LazyImage({ row, column, table }: CellContext<ExtendedEntry, unknown>) {
@@ -186,7 +197,14 @@ function MakeSingleLineField({ row, column, table }: CellContext<ExtendedEntry,
return <GhostedText>{initialValue}</GhostedText>;
}
return <SingleLineCell initialValue={initialValue as string} handleUpdate={update} />;
return (
<SingleLineCell
initialValue={initialValue as string}
fieldId={column.id}
fieldLabel={getColumnLabel(column)}
handleUpdate={update}
/>
);
}
function MakeFlagField({ row }: CellContext<ExtendedEntry, unknown>) {
@@ -219,7 +237,14 @@ function MakeCustomField({ row, column, table }: CellContext<ExtendedEntry, unkn
return <GhostedText multiline>{initialValue}</GhostedText>;
}
return <MultiLineCell initialValue={initialValue} handleUpdate={update} />;
return (
<MultiLineCell
initialValue={initialValue}
fieldId={column.id}
fieldLabel={getColumnLabel(column)}
handleUpdate={update}
/>
);
}
/**
+53 -6
View File
@@ -1,10 +1,57 @@
import { expect, test } from '@playwright/test';
test('cuesheet displays events', async ({ page }) => {
// same elements in cuesheet
await page.goto('http://localhost:4001/cuesheet');
await expect(page.getByRole('row', { name: 'Lunch break' })).toBeVisible();
await expect(page.getByRole('row', { name: 'Afternoon break' })).toBeVisible();
await expect(page.locator('#cuesheet')).toBeVisible();
await page.goto('/cuesheet');
await expect(page.getByTestId('cuesheet')).toBeVisible();
await expect(page.getByTestId('cuesheet-event').first()).toBeVisible();
});
test('cuesheet datagrid keeps keyboard focus flow while editing text cells', async ({ page }) => {
await page.goto('/cuesheet');
const firstEvent = page.getByTestId('cuesheet-event').first();
await expect(firstEvent).toBeVisible();
const cueEditor = firstEvent.getByTestId('cuesheet-editor-cue');
const titleEditor = firstEvent.getByTestId('cuesheet-editor-title');
const noteEditor = firstEvent.getByTestId('cuesheet-editor-note');
/**
* 1. focus a cell in the datagrid single line text
* submitting the data returns the focus to the parent
*/
await titleEditor.click();
await expect(titleEditor).toBeFocused();
const updatedTitle = `focus-title-${Date.now()}`;
await titleEditor.fill(updatedTitle);
await titleEditor.press('Enter');
await expect(titleEditor).not.toBeFocused();
await expect(titleEditor).toHaveValue(updatedTitle);
/**
* 2. navigate and modify multiline text cell
* submitting works with ctrl/cmd + enter and the focus returns to the parent
*/
await page.keyboard.press('ArrowRight');
await page.keyboard.press('Enter');
await expect(noteEditor).toBeFocused();
const updatedNote = `focus-note-${Date.now()}`;
await noteEditor.fill(updatedNote);
await noteEditor.press('ControlOrMeta+Enter');
await expect(noteEditor).not.toBeFocused();
await expect(noteEditor).toHaveValue(updatedNote);
/**
* 2. navigate and modify single line text cell again
* pressing escape cancels the edit and the focus returns to the parent
*/
await page.keyboard.press('ArrowLeft');
await page.keyboard.press('Enter');
await expect(titleEditor).toBeFocused();
const cueBeforeCancel = await cueEditor.inputValue();
await cueEditor.click();
await cueEditor.fill(`${cueBeforeCancel} temporary`);
await cueEditor.press('Escape');
await expect(cueEditor).not.toBeFocused();
await expect(cueEditor).toHaveValue(cueBeforeCancel);
});