ZDDC/tests/tables.spec.js
ZDDC e6d9966593 refactor(tables): in-dir convention + unified table+form HTML bundle
Two intertwined refactors that share too many files to split cleanly.
Both are described separately below.

PART 1 — in-dir convention for table+form spec files

Old layout had the spec at the parent and rows in a child:

    archive/<party>/
      mdl.table.yaml         spec
      mdl.form.yaml          row-edit form
      mdl/                   rows-dir
        row-001.yaml ...

URLs were /<dir>/mdl.table.html and /<dir>/mdl.form.html. Copying
mdl/ elsewhere lost the spec and form because they lived next door.

New layout collapses everything into the rows-dir:

    archive/<party>/mdl/      self-contained
      table.yaml              spec
      form.yaml               row-edit form
      row-001.yaml ...        rows

URLs become /<dir>/mdl/table.html and /<dir>/mdl/form.html. The
"copying-the-folder-takes-everything" property the user asked for
falls out by construction; the row-edit URL /<dir>/<id>.yaml.html
keeps the same shape (spec is now in the same dir, not the
grandparent).

Server changes:

- internal/handler/tablehandler.go RecognizeTableRequest fires on
  /<dir>/table.html when <dir>/table.yaml exists. The .zddc.tables
  alias map is gone — pure presence-based discovery now matches
  the form system's existing convention. Default-MDL fallback at
  archive/<party>/mdl/ stays for the virgin-archive case (the
  rows-dir need not exist on disk; the URL renders fully virtually).

- internal/handler/formhandler.go RecognizeFormRequest fires on
  /<dir>/form.html and /<dir>/<id>.yaml.html with spec at
  <dir>/form.yaml. specEligible accepts on-disk files OR the
  default-MDL virtual path so an empty mdl/ dir still surfaces the
  add-row form.

- internal/handler/tablehandler.go IsDefaultMdlSpec moves to
  serving archive/<party>/mdl/{table,form}.yaml (5 segments after
  ZDDC_ROOT). New isAtArchivePartyMdlLevel predicate; new
  isAtArchivePartyMdlDir for directory-based recognition. New
  IsDefaultMdlSpecAbs accessor for callers that hold an abs path
  rather than a URL (formhandler).

- internal/handler/formhandler.go loadFormSpec(fsRoot, path) falls
  back to embedded default-MDL bytes when os.ReadFile returns
  NotExist AND the path matches the archive-party-mdl shape. Three
  call sites updated to pass cfg.Root.

- internal/handler/formhandler.go serveFormCreate writes
  submissions to filepath.Dir(req.SpecPath) — the spec, the form,
  and rows all live in one directory. The submissionsDir creation
  is idempotent (MkdirAll); cascade falls back one level for ACL
  evaluation when the dir hasn't been materialized yet.

- internal/handler/tablehandler.go tableRowsRedirect now points at
  /<dir>/table.html (was /<dir>.table.html) when the directory
  request maps to a recognized table.

- cmd/zddc-server/main.go dispatch synth flips from
  urlPath + ".table.html" to urlPath + "/table.html" for the
  no-trailing-slash → tables-app routing.

- internal/apps/availability.go DefaultAppAt comment clarified
  that the dir at archive/<party>/mdl/ IS the table (not a child).

Client changes:

- tables/js/context.js walkServer fetches <currentdir>/table.yaml
  directly — no .zddc walk for table declarations. Rows are every
  *.yaml in current dir EXCLUDING table.yaml and form.yaml. The
  .zddc fetch-for-aliases is gated on file:// (online mode 404s
  on .zddc reads via the dispatcher's reserve guard, so skipping
  the request avoids browser console noise).

- tables/js/main.js add-row button links to relative form.html
  (same dir).

- tables/js/render.js + filters.js: every column's autofilter is
  uniformly a text-contains input, even enum columns — keeps the
  filter row visually consistent and doesn't constrain users to
  the enum vocabulary.

PART 2 — unified table+form HTML bundle

The form-render and table-render code paths share field schemas,
the cell editor for excel-mode IS a form widget, and the form
system's POST-back / validation already exists. Combining the two
HTMLs eliminates duplicating jsyaml/jsonschema/theme/source-
detection/.zddc-parsing across two single-file tools.

- tables/template.html grows two top-level mode containers:
  #table-mode (toolbar + sortable table) and #form-mode (form +
  submit button). Both hidden at parse time; the dispatcher
  unhides one. The shared #form-context placeholder was added
  here so the server's existing injectFormContext target
  resolves.

- tables/js/mode.js (new) sets window.zddcMode synchronously
  based on URL pattern: /form.html or /<id>.yaml.html → form,
  /table.html → table, else inline-context fallback for
  file:// (whichever context blob is non-empty wins). Unhides
  the matching container at DOMContentLoaded.

- tables/js/main.js init() and form/js/main.js boot() each guard
  early when mode isn't theirs. Both apps live on different
  globals (window.tablesApp vs window.formApp) so module
  registration doesn't collide.

- form/js/main.js title write falls back from #form-title to
  #table-title (the unified bundle's shared header element)
  when the dedicated id isn't present.

- tables/build.sh concatenates form modules (widgets, render,
  object, array, errors, post, serialize, util) and form CSS.
  No new external deps. Bundle grows from ~95KB to ~120KB.

- internal/handler/formhandler.go drops the //go:embed form.html
  directive; serveFormRender now writes embeddedTablesHTML via
  a small formRenderHTML() accessor (var declared in
  tablehandler.go, same package). The embedded form.html file
  is removed.

- build script: cp form/dist/form.html → internal/handler/form.html
  step is gone (file no longer exists in the source tree). cp
  tables/dist/tables.html → internal/handler/tables.html now
  runs unconditionally rather than only on beta/stable cuts —
  the renderer is a fixed binary component and dev iteration
  needs the embedded copy refreshed every build. Channel-cascaded
  apps (internal/apps/embedded/) stay channel-gated as before.

- form/dist/form.html still builds for standalone offline-only
  use (downloadable from /releases/), but no longer goes into
  the binary.

Tests:

- internal/handler/tablehandler_test.go and formhandler_test.go
  rewritten for the in-dir layout. New test
  TestRecognizeFormRequest_DefaultMdlAtArchiveParty covers
  empty-form, create POST, re-edit row, and the negative cases
  (Working/, non-mdl name) where the fallback must NOT fire.

- internal/handler/directory_test.go updated for the new
  /<dir>/table.html redirect target.

- cmd/zddc-server/main_test.go TestDispatchSlashRouting Location
  expectation updated.

- tests/form-safety.spec.js loads tables/dist/tables.html
  (named form.html in the temp dir to trigger form-mode in the
  dispatcher) so it tests the same bytes the server returns.
  Title-element selector switches to #table-title.

- tests/tables.spec.js updates the status-filter test for the
  uniform text-input filter.

Docs:

- AGENTS.md form-data system rewrites the URL conventions and
  storage layout for in-dir; gains a Tables system section
  parallel to forms describing the self-contained-directory
  property; subfolder rules ("one table per folder by
  construction; subfolders allowed and silently ignored as rows
  — legitimate uses: nested sub-tables, per-row attachments,
  drafts, future history sidecars") so we don't re-derive this.

Not included (deferred):

- ACL gating on cell-level writes — not relevant until Phase 3.
- Editable cells UI — separate commit (Phase 1).

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

211 lines
8.9 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('click on editable row navigates to the row URL', async ({ page }) => {
await loadTableWithContext(page, {
columns: MDL_COLUMNS,
rows: ROWS,
});
await page.waitForSelector('#table-root tbody tr');
// Stub the navigate seam render.js consults before falling back
// to window.location.assign (which Chromium won't let us override
// directly via a plain property assignment).
await page.evaluate(() => {
window.__navTarget = null;
window.tablesApp.navigateTo = url => { window.__navTarget = url; };
});
await page.locator('#table-root tbody tr').first().click();
const target = await page.evaluate(() => window.__navTarget);
expect(target).toBeTruthy();
expect(target).toContain('.yaml.html');
});
test('non-editable rows do not navigate on click', async ({ page }) => {
const readOnlyRows = ROWS.map(r => ({ ...r, editable: false }));
await loadTableWithContext(page, {
columns: MDL_COLUMNS,
rows: readOnlyRows,
});
await page.waitForSelector('#table-root tbody tr');
await page.evaluate(() => {
window.__navTarget = null;
window.tablesApp.navigateTo = url => { window.__navTarget = url; };
});
await page.locator('#table-root tbody tr').first().click();
const target = await page.evaluate(() => window.__navTarget);
expect(target).toBeNull();
// Read-only rows should also lack the editable visual class.
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();
});
});