Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
- Decide whether it stages into the row buffer. Make staging opt-in, as `SheetEditableTextCell`'s `stage` is, since a commit can mean creating a row rather than updating one.
- Call the app's `onCommit` through `cell.submit(onCommit, value, labels.saveFailed)`, so a returned `{ error }`, or a throw, shows on the cell with the value kept.
- End an edit with nothing to save through `onCancel`, as `useInlineEdit` does, so an empty new row can remove itself.
- Open on a typed key or F2: pass the trigger's key presses to `editOnKey` (`src/ui/cells/edit-key.ts`), so the cell takes data entry like the others.
5. Export it from `src/ui/index.ts`, and document it in the package README.
6. Test it inside a `SheetCellProvider`. A cell rendered on its own exercises none of the status reporting.

Expand Down
34 changes: 34 additions & 0 deletions apps/playground-e2e/src/playground.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,25 @@ test.describe('keyboard', () => {

await expect(row.getByRole('button', { name: 'Grace' })).toBeFocused();
});

// Data entry: type into a cell, Tab, type into the next, as in a spreadsheet.
test('types straight into a cell, then Tab and the next', async ({
page,
}) => {
const row = dataRow(page, 'Inline editing', 2);
await row.getByRole('button', { name: 'Accessibility pass' }).focus();

await page.keyboard.type('Audit the docs');
await expect(row.getByRole('textbox')).toHaveValue('Audit the docs');
await page.keyboard.press('Tab');
await expect(row.getByRole('button', { name: 'Grace' })).toBeFocused();
await page.keyboard.type('Linus');
await expect(row.getByRole('textbox')).toHaveValue('Linus');
await page.keyboard.press('Tab');

await expect(row.getByRole('status')).toHaveText(['Saved', 'Saved']);
await expect(row).toContainText('Audit the docs');
});
});

test.describe('full screen', () => {
Expand Down Expand Up @@ -219,6 +238,21 @@ test.describe('full screen', () => {
});

test.describe('adding rows', () => {
test('puts the add button right below the rows', async ({ page }) => {
const region = demo(page, 'Adding rows');
const rows = region.getByRole('row');
// The last row is the add button's own; the one before it, the last task.
const lastTask = await rows.nth((await rows.count()) - 2).boundingBox();
const add = await region
.getByRole('button', { name: 'Add task' })
.boundingBox();

if (!lastTask || !add) throw new Error('Nothing to measure');
expect(
Math.abs(add.y - (lastTask.y + lastTask.height)),
).toBeLessThanOrEqual(1);
});

test('creates a task from the new row', async ({ page }) => {
const region = demo(page, 'Adding rows');
// Header, three tasks and the add-row footer.
Expand Down
15 changes: 8 additions & 7 deletions apps/playground/src/app/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -215,10 +215,11 @@ function App() {
title="Inline editing"
description={
<>
Click a title or owner to edit. A row&apos;s edits are batched
into one save after a 600 ms pause. Type <code>taken</code> as a
title to have it refused, or <code>offline</code> anywhere for a
network error.
Click a title or owner to edit, or focus one and type: Tab moves
on to the next. A row&apos;s edits are batched into one save
after a 600 ms pause. Type <code>taken</code> as a title to have
it refused, or <code>offline</code> anywhere for a network
error.
</>
}
>
Expand All @@ -229,9 +230,9 @@ function App() {
title="Adding rows"
description={
<>
The footer opens a new row at the bottom, where it stays even
when the list is sorted. Type a title and press Enter to create
the task, or leave it empty to discard it. Type{' '}
The add button opens a new row at the bottom, where it stays
even when the list is sorted. Type a title and press Enter to
create the task, or leave it empty to discard it. Type{' '}
<code>taken</code> to have the create refused, or{' '}
<code>offline</code> for a network error.
</>
Expand Down
2 changes: 1 addition & 1 deletion docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ Outside a `Sheet`, for example in a test, there's no context. The hooks then do

`useInlineEdit` runs the editor, and `useSheetCellEditing` connects it to the sheet. Both editable cells, `SheetEditableTextCell` and `SheetPrimaryCell` with `editable`, work like this:

1. **Opening.** Clicking the cell clears its status icon, which would cover the text, but keeps any refused value so a typo can be fixed. The input takes focus as it mounts.
1. **Opening.** A click, F2 or a typed character opens the editor. A typed character replaces the value, as in a spreadsheet; the others keep any refused value so a typo can be fixed. Opening clears the cell's status icon, which would cover the text. The input takes focus as it mounts, with the caret after the text.
2. **Closing:**
- Enter or blur commits. Tab moves focus on, and the blur commits.
- Escape cancels, dropping the cell's staged value, status and refused value.
Expand Down
2 changes: 2 additions & 0 deletions docs/decisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ When you make a choice that a future contributor would question, add it here.

## Editing and saving

- **Typing into a focused cell opens it, replacing the value.** That's how a spreadsheet takes data entry: type, press Tab, type again. The W3C's grid pattern also lists letters and F2 as ways into a cell's editor. Space still opens the editor with the value kept, since it's how a button is pressed. The cost is that one stray key and a click away saves a one-character value, because blur saves. Escape undoes it. Only the built-in cells do this; a cell built on `useInlineEdit` calls `beginEdit(draft)` itself.
- **Outcomes show on the cell:**
- A dot while unsaved, a spinner while saving, a tick once saved, or an error icon with a tooltip. A toast can't say which cell it's about.
- The cell itself isn't tinted, because in a grid with a few bad values, tinting turns it into a wall of red.
Expand Down Expand Up @@ -63,6 +64,7 @@ When you make a choice that a future contributor would question, add it here.
- **The filter panel is a native popover, placed with CSS anchor positioning.** The top layer keeps it from being clipped by the sheet's scroll container, and the browser closes it on a click outside and returns focus to its button, so there's no portal and no positioning code. Anchor positioning has been in every major browser since January 2026.
- **Filter controls mount only while the panel is open.** A checklist counts its column's values when it mounts, so a sheet with many filterable columns doesn't count them all on every render. Mounting on open also lets `autoFocus` move focus into the panel, which content that's always mounted couldn't do.
- **No virtualization yet.** Every row is rendered. The playground's 1,000-row demo shows how that performs. Virtualization is planned for a later release.
- **The add-row button follows the last row,** rather than being pinned to the bottom of the sheet, and sits in the row-number column, where the next row's number would be. It belongs with the rows it adds to, and on a short list a pinned footer left a gap above it. On a long list, you scroll to the end to reach it.
- **No empty gridlines below the last row.** When the rows don't fill the sheet, the space below them stays blank, since empty cells would look like rows that exist.

## Accessibility and languages
Expand Down
17 changes: 9 additions & 8 deletions packages/sheets/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ A spreadsheet-style data grid for React. It's built on [TanStack Table](https://

![A sheet with a saved edit, and a refused one showing its reason](https://raw.githubusercontent.com/codemancers/sheets/main/docs/images/sheet.png)

- **Spreadsheet layout:** row numbers, a sticky header, resizable columns, grouped headers, a sticky add-row footer, and loading and empty states.
- **Spreadsheet layout:** row numbers, a sticky header, resizable columns, grouped headers, an add-row button below the rows, and loading and empty states.
- **In-place editing:** click a cell, type, then Enter to save or Escape to cancel. Each cell shows its own status: unsaved, saving, saved or refused.
- **Saving per row:** edits to one row can be batched into a single request. If the server refuses a field, the error appears on that field's cell.
- **Validation** with any [Standard Schema](https://standardschema.dev) library (zod, Valibot, ArkType and others).
Expand Down Expand Up @@ -333,12 +333,12 @@ function PriorityCell({ value }: { value: number }) {
- `accepts`, which runs the schema and reports a failure on the cell
- `abandon` and `clearOnEditStart`
- `label`, the column's header, for naming your editor
- `useInlineEdit` handles text-style editors: Enter, Escape, saving on blur, IME input, and returning focus to the cell. It calls `onCancel` on Escape, and when an edit ends with nothing to save.
- `useInlineEdit` handles text-style editors: Enter, Escape, saving on blur, IME input, and returning focus to the cell. It calls `onCancel` on Escape, and when an edit ends with nothing to save. `beginEdit(draft)` opens the editor on `draft` instead of the value, which is how the built-in cells open on a typed key.
- Report outcomes through `cellStatus`, and `SheetCell` draws the icons.

## Layout and states

`<Sheet>` fills its parent (`h-full w-full`) and scrolls inside it. The header and the add-row footer stay pinned while the rows scroll. Give the parent a height:
`<Sheet>` fills its parent (`h-full w-full`) and scrolls inside it. The header stays pinned while the rows scroll, and the add-row button follows the last row, in the row-number column. Give the parent a height:

```tsx
// Fill the rest of a full-height page
Expand All @@ -356,7 +356,7 @@ Column widths come from `size` (TanStack's default is 150px). After the last col
| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `isLoading` | Shows placeholder rows inside the same frame and marks the rows busy for assistive tech. `loadingState` replaces the placeholders. |
| `emptyState` | Content for a row that spans the columns when there's no data. Defaults to the `empty` label. |
| `onAddRow` | Shows the sticky add-row footer. `addRowDisabled` disables its button. See [Adding rows](#adding-rows). |
| `onAddRow` | Shows the add-row button, right below the rows. `addRowDisabled` disables it. See [Adding rows](#adding-rows). |
| `highlightedRowId` | Highlights a row and scrolls it into view, and marks it `data-highlighted` for tests. Clear it after a moment to fade the highlight. |
| `openRowId` | Marks the row that is open in a drawer: highlighted, and announced as current. See [Opening rows in a drawer](#opening-rows-in-a-drawer). |
| `rowHeight`, `className` | The minimum row height, and extra classes for the scroll container. |
Expand All @@ -375,7 +375,7 @@ useEffect(() => {

## Adding rows

`onAddRow` shows the add-row footer. To create a record from a new row in the sheet, add a temporary row to `data`, and give its first cell an editor:
`onAddRow` shows the add-row button. To create a record from a new row in the sheet, add a temporary row to `data`, and give its first cell an editor:

```tsx
const NEW_ROW = 'new';
Expand Down Expand Up @@ -517,7 +517,7 @@ To follow your design system's CSS variables, such as shadcn's, use `@theme inli
| --------------------------------------------------------------------- | --------------------------------------------------------------------- |
| `sheet-bg`, `sheet-fg` | Background and text. Borders and hover tints are `fg` at low opacity. |
| `sheet-muted`, `sheet-faint` | Secondary text, and placeholders |
| `sheet-raised` | The add-row footer on hover, and the filter panel |
| `sheet-raised` | The add-row button's row on hover, and the filter panel |
| `sheet-skeleton` | Loading placeholders |
| `sheet-tooltip`, `sheet-tooltip-fg` | The error tooltip |
| `sheet-link`, `sheet-link-hover` | Links |
Expand Down Expand Up @@ -598,7 +598,8 @@ const { table } = useSheet({ columns, data, getRowId: (task) => task.id });
- **Keyboard:**
- Tab reaches the sort and filter buttons, resize handles, cells and row actions. Row actions appear on focus as well as hover.
- A filter button opens its filter with focus inside it. Escape, or Enter in a text filter, closes it and returns focus to the button.
- Enter or Space opens an editable cell. Enter saves, Escape cancels, and both return focus to the cell. Tab saves and moves on to the next cell.
- Enter or Space opens an editable cell with its value. In the built-in cells, F2 does too, and typing a character opens it with that character instead, replacing the value, as in a spreadsheet.
- Enter saves, Escape cancels, and both return focus to the cell. Tab saves and moves on to the next cell, so you can type, press Tab and type again.
- On a focused resize handle, the arrow keys resize the column (Shift for bigger steps), and a double-click resets it.
- **Screen readers:** editors are named after their column. Saving statuses are announced, and refused values are announced as alerts.
- **Testing:** the playground is scanned with axe in CI, and any violation fails the build.
Expand Down Expand Up @@ -629,7 +630,7 @@ Not yet supported: moving between cells with the arrow keys (`role="grid"`).
| `useSheet(options)` | `useReactTable` plus `cellStatus` and `rowChanges`. Returns `{ table, cellStatus, rowChanges }`, where `cellStatus` is the one you passed or the sheet's own. |
| `useCellStatus()` | Per-cell outcomes: `setCellSaved`, `rejectCellValue`, `rejectFieldErrors`, `clearCellStatus`, `abandonCellValueChange`, `setCellDirty`, `setCellSaving`, `statuses`, `rejectedCellValue`. |
| `useRowChanges(options)` | The per-row save buffer. Options: `onSubmitRow`, `cellStatus`, `flush`, `transportErrorMessage`. Returns `stageCellValue`, `discardCellValue`, `stagedCellValue`, `hasStagedChanges`, `flushAll`. |
| `useInlineEdit(options)` | Edit-in-place state for a text editor: `isEditing`, `beginEdit`, `commit`, `cancel`, `inputProps`, `triggerRef`. Calls `onCancel` on Escape, and when an edit ends unchanged. |
| `useInlineEdit(options)` | Edit-in-place state for a text editor: `isEditing`, `beginEdit(draft?)`, `commit`, `cancel`, `inputProps`, `triggerRef`. Calls `onCancel` on Escape, and when an edit ends unchanged. |
| `useRowDrawer(options?)` | Which row is open in a drawer or panel: `openRowId`, `open`, `close`, `toggle`, `isOpen`. Options: `openRowId` and `onOpenRowIdChange` to control it, or `defaultOpenRowId`. |
| `useSheetCellEditing(schema?)` | The editing context for a cell, for building your own (see above). |
| `textFilter`, `valuesFilter` | Filter functions for a column's `filterFn`: the text it contains, or one of a checklist of values. Either one gives the column's header a filter button. |
Expand Down
50 changes: 50 additions & 0 deletions packages/sheets/src/hooks/use-inline-edit.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { fireEvent, render, screen } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import { useInlineEdit } from './use-inline-edit.js';

/** A cell built on the hook, as an app's own editable cell would be. */
function Cell({ type }: { type: 'text' | 'number' }) {
const { isEditing, beginEdit, triggerRef, inputProps } = useInlineEdit({
value: '42',
});
if (isEditing)
return <input type={type} aria-label="Amount" {...inputProps} />;
return (
<button ref={triggerRef} type="button" onClick={() => beginEdit()}>
42
</button>
);
}

describe('useInlineEdit', () => {
it('opens with the caret after the text', () => {
render(<Cell type="text" />);

fireEvent.click(screen.getByRole('button', { name: '42' }));

const input = screen.getByRole<HTMLInputElement>('textbox');
expect(document.activeElement).toBe(input);
expect(input.selectionStart).toBe(2);
});

// A number input has no caret, and placing one throws. The throw happens in
// a focus handler, which reports it as an uncaught error rather than failing
// the render, so listen for that.
it('opens a number input without placing a caret', () => {
const errors: unknown[] = [];
const onError = (event: ErrorEvent) => {
errors.push(event.error);
event.preventDefault();
};
window.addEventListener('error', onError);
try {
render(<Cell type="number" />);
fireEvent.click(screen.getByRole('button', { name: '42' }));
} finally {
window.removeEventListener('error', onError);
}

expect(errors).toEqual([]);
expect(screen.getByRole('spinbutton', { name: 'Amount' })).toBeTruthy();
});
});
26 changes: 21 additions & 5 deletions packages/sheets/src/hooks/use-inline-edit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,19 @@ export function useInlineEdit<T extends string>({
}
}, [isEditing]);

const beginEdit = useCallback(() => {
committedRef.current = false;
setDraft(value);
setIsEditing(true);
}, [value]);
/**
* Opens the editor on the value, or on `draft` instead, such as the key typed
* into a focused cell. Anything else passed in, like the click event from
* `onClick={beginEdit}`, is ignored.
*/
const beginEdit = useCallback(
(draft?: T) => {
committedRef.current = false;
setDraft(typeof draft === 'string' ? draft : value);
setIsEditing(true);
},
[value],
);

const commit = useCallback(async () => {
if (committedRef.current) return;
Expand Down Expand Up @@ -128,6 +136,14 @@ export function useInlineEdit<T extends string>({
setDraft(e.target.value as T),
onKeyDown: handleKeyDown,
onBlur: handleBlur,
// The caret goes after the text, so typing carries on from a typed first
// key in every browser, rather than landing in front of it.
// Number, email and date inputs have no caret to place: setting one throws.
onFocus: (e: FocusEvent<HTMLInputElement>) => {
if (e.currentTarget.selectionStart === null) return;
const end = e.currentTarget.value.length;
e.currentTarget.setSelectionRange(end, end);
},
autoFocus: true,
},
};
Expand Down
Loading
Loading