ZDDC/tests/tables.spec.js
ZDDC 08ce8a1266 feat(tables): editable cells phase 1 — selection + keyboard nav
First step toward the Excel-like editable-table the user asked for.
Architecture decisions in this phase came from a focused research
pass over Notion / Airtable / AG Grid / Handsontable / Glide / W3C
ARIA APG; the design notes are in this commit's predecessor as a
research synthesis. Five phases planned; this is phase 1 of 5 and
ships the cell-selection + keyboard-navigation + per-cell editor
mount-on-demand foundation. Edits in this phase live in a client-
side draft buffer only; row-level save + ETag conflict UX is
phase 3.

Scope:

- ARIA grid pattern verbatim (W3C WAI-ARIA APG): role=grid on the
  table, role=row on rows, role=gridcell on cells, roving
  tabindex (only one cell carries tabindex=0; arrows move it).
  This makes the grid one tab stop in the page tab order — the
  documented spreadsheet UX, and also the basis for screen-reader
  correctness.

- Click selects a cell. Arrow keys move selection. Tab and
  Shift-Tab move with row-wrap. Home / End jump within row;
  Ctrl/Cmd+Home / End jump to grid corners. Enter, F2, double-
  click, or any printable character all enter edit mode. In edit
  mode: Enter commits and moves down (Excel convention), Tab
  commits and moves right (with row-wrap), Escape cancels and
  restores the prior value, blur commits.

- Mount-on-demand cell editor: one <input> at a time is
  instantiated inside the selected cell. Survives 1000-row tables
  without the focus-ring churn an always-editable design would
  hit, and lets Phase 2 swap the input for schema-driven widgets
  (number / date / select / etc.) without restructuring.

- Draft buffer at app.state.drafts keyed by row id (the row's
  re-edit URL — stable across sort and filter). When a cell
  commits with a value different from row.data, the draft entry
  is set; render reads from the draft via effectiveCellValue() so
  the visible cell content reflects unsaved edits. No-op edits
  (commit returns the original value) clear any pending draft.

- Selection survives re-paints. Sort / filter / spec changes
  trigger a re-render; the editor's setSelected at end of paint()
  clamps to new bounds and rebinds tabindex. The user's cell
  doesn't disappear when they sort the column they're editing.

- Numeric coercion fast-path: cells whose column declares
  format=number/integer coerce the input string to Number on
  commit. Phase 2 will generalize this to schema-driven coercion
  for date, boolean, enum, etc.

UX consequence — single-click semantics change:

The pre-existing row-click-navigates-to-form-edit behavior is
gone. Single click now selects a cell (spreadsheet-native). The
"open this row in the form editor" affordance moves to phase 2
(an explicit "Edit…" button or an icon column). The row-click-
navigation tests in tests/tables.spec.js are replaced with seven
new tests covering the editor lifecycle.

What this phase does NOT do (and which phases own it):

- Phase 2: schema-driven editor widgets (right input type per
  column). Server-side validation 422 → red-corner marks. Complex
  types (object, generic array, oneOf) get an "Edit…" button that
  opens the side-panel form-render mode the unified bundle
  already ships.

- Phase 3: row-level save on row-blur via PUT + If-Match. Stale-
  row badge with "Use mine" / "Reload" on 412. Outbox carries the
  offline path transparently via the existing source.js layer.

- Phase 4: copy/paste from Excel/Sheets via TSV parser, spill-
  from-anchor or fill-all into a selection range.

- Phase 5: undo (linear command stack, Ctrl+Z, session-local) and
  multi-cell ops (range select, bulk delete, Ctrl+D / Ctrl+R fill).

Tests (tests/tables.spec.js, all 15 pass):

- clicking a cell selects it (replaces the old row-click-navigates
  test; verifies single-click does NOT navigate)
- arrow keys move cell selection
- Tab and Shift-Tab traverse cells with row-wrap
- Enter enters edit mode; Enter commits and moves down (verifies
  draft is applied to visible cell + selection moves)
- Escape cancels edit, restoring prior value (verifies no-op on
  draft buffer)
- typing a printable char enters edit and replaces the value
- double-click also enters edit mode
- non-editable rows still get the readonly class (cosmetic guard
  for an existing convention; phase 3 will gate write submission)

Files:

- tables/js/editor.js (new) — selection + keyboard handling +
  edit-mode lifecycle + draft buffer.
- tables/js/app.js — state.selected / state.editing / state.drafts
  fields.
- tables/js/render.js — ARIA roles + editor.attachToCell wiring;
  cells render via editor.effectiveCellValue so drafts show.
- tables/js/main.js — paint()-end editor.attachToTable +
  setSelected restore.
- tables/css/table.css — selected-cell focus ring (outline,
  doesn't shift surrounding cells); cell-input bare-inside-cell
  styling.
- tables/build.sh — editor.js in the concat list.
- zddc/internal/handler/tables.html — regenerated bundle.

Bundle size: 117 KB → 124 KB (+7 KB for editor.js + ARIA + draft
machinery). Well within the budget the library survey identified
(Tabulator would have been +100 KB; SlickGrid +34 KB; custom is
+7 KB and we keep the no-third-party-deps invariant).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 09:16:39 -05:00

343 lines
15 KiB
JavaScript

import { test, expect } from '@playwright/test';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
const HTML_PATH = path.resolve('tables/dist/tables.html');
const HTML_RAW = fs.readFileSync(HTML_PATH, 'utf8');
const MDL_COLUMNS = [
{ field: 'id', title: 'ID', width: '6em' },
{ field: 'title', title: 'Deliverable' },
{ field: 'party', title: 'Party', enum: ['Acme', 'Beta', 'Gamma'] },
{ field: 'dueDate', title: 'Due', format: 'date' },
{ field: 'status', title: 'Status', enum: ['pending', 'submitted', 'accepted'] },
];
function makeRow(id, title, party, dueDate, status, editable = true) {
return {
url: `/Working/MDL/${id}.yaml.html`,
data: { id, title, party, dueDate, status },
editable,
};
}
const ROWS = [
makeRow('D-001', 'Site survey report', 'Acme', '2026-05-12', 'pending'),
makeRow('D-002', 'Foundation drawings A', 'Beta', '2026-05-20', 'submitted'),
makeRow('D-003', 'Procurement schedule', 'Acme', '2026-05-08', 'accepted'),
makeRow('D-004', 'Safety plan', 'Gamma', '2026-05-15', 'pending'),
makeRow('D-005', 'Geotechnical report', 'Beta', '2026-05-30', 'submitted'),
];
// Inject a complete table context into the page. Same pattern as
// form-safety.spec.js: write a patched copy of tables.html to a temp
// file and navigate via file://.
async function loadTableWithContext(page, context) {
const ctxJson = JSON.stringify(context).replace(/<\//g, '<\\/');
const replacement = `<script id="table-context" type="application/json">${ctxJson}</script>`;
const patched = HTML_RAW.replace(
/<script id="table-context" type="application\/json">[\s\S]*?<\/script>/,
replacement,
);
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'tables-spec-'));
const tmpPath = path.join(tmpDir, 'tables.html');
fs.writeFileSync(tmpPath, patched);
await page.goto(`file://${tmpPath}`, { waitUntil: 'load' });
}
test.describe('tables/ — directory-of-YAML table view', () => {
test('renders header with column titles and rows from context', async ({ page }) => {
page.on('pageerror', e => console.log('[pageerror]', e.message));
await loadTableWithContext(page, {
title: 'Master Deliverables List',
columns: MDL_COLUMNS,
rows: ROWS,
});
await page.waitForFunction(
() => document.querySelector('#table-root tbody').children.length > 0,
null,
{ timeout: 5000 },
);
// Header cells.
const headers = page.locator('.zddc-table__title-row .zddc-table__th');
await expect(headers).toHaveCount(MDL_COLUMNS.length);
await expect(headers.nth(0)).toContainText('ID');
await expect(headers.nth(1)).toContainText('Deliverable');
// Title in the page header.
await expect(page.locator('#table-title')).toContainText('Master Deliverables List');
// Row count.
await expect(page.locator('#table-root tbody tr')).toHaveCount(ROWS.length);
await expect(page.locator('#table-rowcount')).toContainText(`${ROWS.length} rows`);
});
test('default sort puts dueDate ascending when configured', async ({ page }) => {
await loadTableWithContext(page, {
columns: MDL_COLUMNS,
rows: ROWS,
defaults: { sort: [{ field: 'dueDate', dir: 'asc' }] },
});
await page.waitForSelector('#table-root tbody tr');
const ids = await page.locator('#table-root tbody tr td:first-child').allTextContents();
// Sorted ascending by dueDate: D-003 (5/8), D-001 (5/12), D-004 (5/15), D-002 (5/20), D-005 (5/30).
expect(ids).toEqual(['D-003', 'D-001', 'D-004', 'D-002', 'D-005']);
});
test('clicking a column header sorts by that column and toggles direction', async ({ page }) => {
await loadTableWithContext(page, {
columns: MDL_COLUMNS,
rows: ROWS,
});
await page.waitForSelector('#table-root tbody tr');
// Click the ID header → sort ascending.
await page.locator('.zddc-table__th[data-field="id"]').click();
let ids = await page.locator('#table-root tbody tr td:first-child').allTextContents();
expect(ids).toEqual(['D-001', 'D-002', 'D-003', 'D-004', 'D-005']);
// Click again → descending.
await page.locator('.zddc-table__th[data-field="id"]').click();
ids = await page.locator('#table-root tbody tr td:first-child').allTextContents();
expect(ids).toEqual(['D-005', 'D-004', 'D-003', 'D-002', 'D-001']);
});
test('free-text filter narrows visible rows', async ({ page }) => {
await loadTableWithContext(page, {
columns: MDL_COLUMNS,
rows: ROWS,
});
await page.waitForSelector('#table-root tbody tr');
// Type "report" in the title column's filter — should match the
// two rows whose title contains "report" (Site survey report,
// Geotechnical report).
const titleFilter = page.locator('.zddc-table__th[data-field="title"]')
.locator('..')
.locator('xpath=following-sibling::tr[1]')
.locator('input[type="text"]')
.nth(0);
// Simpler selector: nth filter input under the filter row.
const filterInputs = page.locator('.zddc-table__filter-row input[type="text"]');
await filterInputs.nth(1).fill('report'); // index 1 = title column
await expect(page.locator('#table-root tbody tr')).toHaveCount(2);
});
test('text filter on an enum column does substring match', async ({ page }) => {
// Filter row is uniformly text-contains across all columns —
// even for columns declared with `enum:` in the spec. Enum
// metadata still informs validation/sort but not filter UI.
await loadTableWithContext(page, {
columns: MDL_COLUMNS,
rows: ROWS,
});
await page.waitForSelector('#table-root tbody tr');
const filterInputs = page.locator('.zddc-table__filter-row input[type="text"]');
// Spec columns: 0=id, 1=title, 2=party, 3=dueDate, 4=status.
const statusInput = filterInputs.nth(4);
await statusInput.fill('pending');
await expect(page.locator('#table-root tbody tr')).toHaveCount(2);
});
test('clicking a cell selects it (Phase 1 — replaces row-click navigation)', async ({ page }) => {
// Single click → cell selection. Row navigation moves to a
// dedicated affordance in Phase 2 (open-in-form button) so the
// primary click action can be the spreadsheet-native one.
await loadTableWithContext(page, {
columns: MDL_COLUMNS,
rows: ROWS,
});
await page.waitForSelector('#table-root tbody tr');
// Stub navigate seam — verifies single-click does NOT navigate.
await page.evaluate(() => {
window.__navTarget = null;
window.tablesApp.navigateTo = url => { window.__navTarget = url; };
});
// Click a specific cell.
const firstCell = page.locator('#table-root tbody tr').first().locator('[role="gridcell"]').first();
await firstCell.click();
await expect(firstCell).toHaveClass(/zddc-table__cell--selected/);
await expect(firstCell).toHaveAttribute('tabindex', '0');
await expect(page.evaluate(() => window.__navTarget)).resolves.toBeNull();
});
test('arrow keys move cell selection (ARIA grid)', async ({ page }) => {
await loadTableWithContext(page, {
columns: MDL_COLUMNS,
rows: ROWS,
});
await page.waitForSelector('#table-root tbody tr');
// Click to seed selection at (0,0), then arrow around.
const r0c0 = page.locator('#table-root tbody tr').nth(0).locator('[role="gridcell"]').nth(0);
await r0c0.click();
await expect(r0c0).toHaveClass(/zddc-table__cell--selected/);
await page.keyboard.press('ArrowDown');
const r1c0 = page.locator('#table-root tbody tr').nth(1).locator('[role="gridcell"]').nth(0);
await expect(r1c0).toHaveClass(/zddc-table__cell--selected/);
await page.keyboard.press('ArrowRight');
const r1c1 = page.locator('#table-root tbody tr').nth(1).locator('[role="gridcell"]').nth(1);
await expect(r1c1).toHaveClass(/zddc-table__cell--selected/);
await page.keyboard.press('ArrowUp');
const r0c1 = page.locator('#table-root tbody tr').nth(0).locator('[role="gridcell"]').nth(1);
await expect(r0c1).toHaveClass(/zddc-table__cell--selected/);
await page.keyboard.press('ArrowLeft');
await expect(r0c0).toHaveClass(/zddc-table__cell--selected/);
});
test('Tab and Shift-Tab traverse cells with row-wrap', async ({ page }) => {
await loadTableWithContext(page, {
columns: MDL_COLUMNS,
rows: ROWS,
});
await page.waitForSelector('#table-root tbody tr');
const numCols = MDL_COLUMNS.length;
// Start at last column of row 0.
const r0Last = page.locator('#table-root tbody tr').nth(0).locator('[role="gridcell"]').nth(numCols - 1);
await r0Last.click();
await expect(r0Last).toHaveClass(/zddc-table__cell--selected/);
// Tab → first cell of row 1 (wrap).
await page.keyboard.press('Tab');
const r1First = page.locator('#table-root tbody tr').nth(1).locator('[role="gridcell"]').nth(0);
await expect(r1First).toHaveClass(/zddc-table__cell--selected/);
// Shift+Tab → back to last cell of row 0.
await page.keyboard.press('Shift+Tab');
await expect(r0Last).toHaveClass(/zddc-table__cell--selected/);
});
test('Enter enters edit mode; Enter commits and moves down', async ({ page }) => {
await loadTableWithContext(page, {
columns: MDL_COLUMNS,
rows: ROWS,
});
await page.waitForSelector('#table-root tbody tr');
// Edit the title cell (column index 1) of row 0.
const titleCell = page.locator('#table-root tbody tr').nth(0).locator('[role="gridcell"]').nth(1);
await titleCell.click();
await page.keyboard.press('Enter');
// Editor input mounted inside the cell.
const input = titleCell.locator('input.zddc-table__cell-input');
await expect(input).toBeVisible();
await expect(input).toBeFocused();
// Type new value, press Enter to commit + move down.
await page.keyboard.press('Control+a');
await page.keyboard.type('New title via cell editor');
await page.keyboard.press('Enter');
// Cell shows new value, input gone.
await expect(titleCell).toContainText('New title via cell editor');
await expect(titleCell.locator('input')).toHaveCount(0);
// Selection moved down one row, same column.
const r1Title = page.locator('#table-root tbody tr').nth(1).locator('[role="gridcell"]').nth(1);
await expect(r1Title).toHaveClass(/zddc-table__cell--selected/);
});
test('Escape cancels edit, restoring prior value', async ({ page }) => {
await loadTableWithContext(page, {
columns: MDL_COLUMNS,
rows: ROWS,
});
await page.waitForSelector('#table-root tbody tr');
const titleCell = page.locator('#table-root tbody tr').nth(0).locator('[role="gridcell"]').nth(1);
const originalText = await titleCell.textContent();
await titleCell.click();
await page.keyboard.press('Enter');
await page.keyboard.press('Control+a');
await page.keyboard.type('Should not stick');
await page.keyboard.press('Escape');
// Value restored to original; no draft entry.
await expect(titleCell).toHaveText(originalText.trim());
const draftCount = await page.evaluate(() =>
Object.keys(window.tablesApp.state.drafts).length);
expect(draftCount).toBe(0);
});
test('typing a printable char enters edit and replaces value', async ({ page }) => {
await loadTableWithContext(page, {
columns: MDL_COLUMNS,
rows: ROWS,
});
await page.waitForSelector('#table-root tbody tr');
const titleCell = page.locator('#table-root tbody tr').nth(0).locator('[role="gridcell"]').nth(1);
await titleCell.click();
// Press a printable character — should enter edit mode with
// that char as the new value.
await page.keyboard.press('X');
const input = titleCell.locator('input.zddc-table__cell-input');
await expect(input).toBeVisible();
await expect(input).toHaveValue('X');
});
test('double-click also enters edit mode', async ({ page }) => {
await loadTableWithContext(page, {
columns: MDL_COLUMNS,
rows: ROWS,
});
await page.waitForSelector('#table-root tbody tr');
const titleCell = page.locator('#table-root tbody tr').nth(0).locator('[role="gridcell"]').nth(1);
await titleCell.dblclick();
await expect(titleCell.locator('input.zddc-table__cell-input')).toBeVisible();
});
test('non-editable rows still get the readonly class', async ({ page }) => {
// Cosmetic guard for an existing convention: rows where the
// server says editable=false get a visual treatment. Cell
// selection still works in Phase 1; Phase 3 will gate writes
// on the editable flag at save time.
const readOnlyRows = ROWS.map(r => ({ ...r, editable: false }));
await loadTableWithContext(page, {
columns: MDL_COLUMNS,
rows: readOnlyRows,
});
await page.waitForSelector('#table-root tbody tr');
await expect(page.locator('#table-root tbody tr.zddc-table__row--editable')).toHaveCount(0);
await expect(page.locator('#table-root tbody tr.zddc-table__row--readonly')).toHaveCount(ROWS.length);
});
test('default filters seed the visible row count from defaults.filter', async ({ page }) => {
await loadTableWithContext(page, {
columns: MDL_COLUMNS,
rows: ROWS,
defaults: { filter: { status: ['pending'] } },
});
await page.waitForSelector('#table-root tbody tr');
await expect(page.locator('#table-root tbody tr')).toHaveCount(2);
});
test('empty rows list shows the empty-state notice', async ({ page }) => {
await loadTableWithContext(page, {
columns: MDL_COLUMNS,
rows: [],
});
// Wait briefly for init.
await page.waitForTimeout(50);
await expect(page.locator('#table-root tbody tr')).toHaveCount(0);
await expect(page.locator('#table-empty')).toBeHidden();
});
});