Cell edits now actually persist. Row-level batch save fires on
row-blur (selection moves to a different row); the request is one
PUT with the full merged row (server-side data + client drafts)
and If-Match: <etag> for optimistic concurrency. Conflict and
validation responses are surfaced inline; drafts are NEVER silently
discarded — when the server says no, the user's typing stays put
until they explicitly reload or replay.
Architecture (per the research synthesis from earlier in this
sequence):
- ETag tracking: context.js readRows captures the per-row ETag
from HttpFileHandle's response header on the initial GET.
Stashed at row.etag alongside row.data and row.yamlUrl. Phase 3
reads it; later phases (undo replay) inherit it.
- Row-blur trigger: editor.js setSelected calls a new
notifySelectionChanged() hook after selection lands. save.js's
onSelectionChanged tracks _previousSelectedRowId; when it
changes AND the previous row had drafts, fires saveRow(prevId).
Fire-and-forget — don't block the user's flow on the network.
- save.saveRow flow:
1. mergeRow(row.data, drafts) → full updated row.
2. js-yaml dump → wire body.
3. PUT row.yamlUrl, body, headers={Content-Type, If-Match}.
4. Branch on response status:
- 200/201 → success: clear drafts + invalid marks, capture
new ETag from response, replace row.data with merged.
- 202 → outbox queued (downstream client offline):
clear drafts (the outbox owns them now), mark row queued.
- 412 → stale: drafts STAY; mark row stale; show
status-bar prompt with [Use mine] / [Reload] buttons.
- 422 → server validation failed; body has
{errors: [{path, message}]}; mark each cell invalid via
a red-corner CSS marker + title-attribute tooltip.
- other → mark errored; drafts stay.
- Conflict resolution UX:
- "Use mine" replays the user's drafts onto fresh server
state. Re-GETs the row to learn the new ETag + new server
data, replaces row.data with the fresh server values, then
re-PUTs the merge of fresh + drafts. This is client-side
field-level last-writer-wins: fields the user did NOT
touch get the server's new values automatically; only
fields the user changed override server state. No JSON
Patch endpoint required — pure client logic on top of the
existing whole-row PUT path.
- "Reload" drops drafts entirely, re-GETs the row, repaints.
- Validation error display: per-cell red-corner triangle
(Excel-style) plus title-attribute tooltip on hover. Marker
keyed off data-col-idx + the column's field; survives until
the next edit on that cell or the next paint() cycle.
- beforeunload safety net: any rows with drafts at unload time
get one fire-and-forget save attempt. Modern browsers limit
what beforeunload can do; a follow-up could add fetch's
keepalive flag for a more reliable last-shot.
UI surfaces:
- Per-row state classes drive a left-border swatch in the first
cell:
--dirty subtle blue (uncommitted changes)
--saving muted grey (PUT in flight)
--queued warm yellow (outbox accepted)
--invalid orange (server 422)
--stale warning amber (server 412 — also tints row bg)
--errored red (other failure — also tints row bg)
These re-apply across re-paints via save.markAllDirtyRows()
called from main.js's paint() hook (innerHTML='' wipes them).
- #table-status doubles as the conflict prompt host. When a row
goes stale, the bar shows
"This row was changed by someone else. [Use mine] [Reload] [×]"
and the row-id it's bound to is stored on data-row-id so a
successful reload of that row dismisses the prompt.
Outbox (downstream client) interaction:
The cache layer's PUT-replay queue intercepts saves transparently.
On local network failure the cache returns 202 with
X-ZDDC-Cache: queued; we treat 202 as "succeeded for now" —
drafts clear (the outbox owns them and will replay), but the
row stays marked --queued so the user knows the write hasn't
reached upstream yet. When the cache replays and gets a
real 200/201/412/etc., the row state will reflect that on next
read (next paint cycle / page refresh).
Tests (4 new Phase 3 specs, total 31 in tests/tables.spec.js):
- row-blur fires PUT with merged drafts + If-Match. Edit a
cell in row 0, Enter (commits + moves to row 1). Verifies
PUT went out with the right URL, the merged YAML body
contains the new value AND the unchanged fields, and the
If-Match header carries the original ETag.
- 412 conflict marks row stale + shows status prompt. Verifies
the row gains the stale class, the status bar appears with
both [Use mine] and [Reload] buttons, AND the draft is
preserved (never silently dropped on conflict).
- 422 validation errors mark cells invalid. Verifies multiple
field errors → multiple red-corner cells.
- Reload button drops drafts and refreshes. Verifies the bar
hides and drafts clear after a successful reload GET.
Setup: a small page.route helper intercepts http://test.local/*
PUTs and GETs, lets each test queue the next response via
window.__nextResponse, and captures requests at
window.__capturedRequests for inspection. Test fixtures use
absolute http URLs in row.yamlUrl so the route catches them.
Bundle size: 127 KB → 134 KB.
Files:
- tables/js/save.js (new) — saveRow, useMine, reload, status
prompt, row-state markers, beforeunload flush.
- tables/js/editor.js — notifySelectionChanged hook.
- tables/js/context.js — etag + yamlUrl on each row.
- tables/js/main.js — paint() re-applies dirty markers via
save.markAllDirtyRows; exposes app.repaint for save callbacks.
- tables/build.sh — save.js in concat list.
- tables/css/table.css — row-state classes + invalid-cell corner
+ status-bar prompt styling.
- zddc/internal/handler/tables.html — regenerated bundle.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
146 lines
5.9 KiB
JavaScript
146 lines
5.9 KiB
JavaScript
(function (app) {
|
|
'use strict';
|
|
|
|
async function init() {
|
|
// Both apps (table + form) ship in the same bundle. Skip if
|
|
// mode dispatcher said this isn't our mode — form-mode requests
|
|
// are handled by formApp.
|
|
if (window.zddcMode === 'form') {
|
|
return;
|
|
}
|
|
const ctx = await app.modules.context.load();
|
|
app.context = ctx;
|
|
|
|
const titleEl = document.getElementById('table-title');
|
|
if (ctx.title && titleEl) {
|
|
titleEl.textContent = ctx.title;
|
|
document.title = 'ZDDC — ' + ctx.title;
|
|
}
|
|
|
|
const descEl = document.getElementById('table-description');
|
|
if (descEl && ctx.description) {
|
|
descEl.textContent = ctx.description;
|
|
descEl.hidden = false;
|
|
}
|
|
|
|
const tableEl = document.getElementById('table-root');
|
|
const theadEl = tableEl.querySelector('thead');
|
|
const tbodyEl = tableEl.querySelector('tbody');
|
|
const emptyEl = document.getElementById('table-empty');
|
|
const countEl = document.getElementById('table-rowcount');
|
|
const clearBtn = document.getElementById('table-clear-filters');
|
|
const addRowBtn = document.getElementById('table-add-row');
|
|
|
|
// Add-row button: link to <name>.form.html, the form-system's
|
|
// empty-form URL for this table's row schema. POST creates a
|
|
// new submission and the server redirects to the row's edit
|
|
// URL. Hidden when we can't derive a table name from the
|
|
// pathname (e.g. inline-context test harness opening tables.html
|
|
// directly without a *.table.html URL).
|
|
if (addRowBtn) {
|
|
// Page is at <dir>/table.html; the row-creation form is at
|
|
// <dir>/form.html — same directory, just swap the basename.
|
|
if (/\/table\.html$/.test(location.pathname || '')) {
|
|
addRowBtn.href = 'form.html';
|
|
addRowBtn.hidden = false;
|
|
}
|
|
}
|
|
|
|
const columns = Array.isArray(ctx.columns) ? ctx.columns : [];
|
|
const allRows = Array.isArray(ctx.rows) ? ctx.rows : [];
|
|
|
|
const state = app.state;
|
|
state.rows = allRows;
|
|
state.sort = app.modules.sort.defaultsFromContext(ctx);
|
|
state.filter = {};
|
|
|
|
// Seed default filters from context.defaults.filter (per-column).
|
|
if (ctx.defaults && ctx.defaults.filter && typeof ctx.defaults.filter === 'object') {
|
|
for (let i = 0; i < columns.length; i++) {
|
|
const col = columns[i];
|
|
const seeded = ctx.defaults.filter[col.field];
|
|
if (seeded == null) {
|
|
continue;
|
|
}
|
|
// Filter UI is uniformly text-contains. If the spec
|
|
// seeds an array (legacy enum-style), coerce to a
|
|
// comma-joined contains string — partial match on any
|
|
// listed value still narrows the table sensibly.
|
|
const seedStr = Array.isArray(seeded) ? seeded.join(',') : String(seeded);
|
|
state.filter[col.field] = { kind: 'contains', value: seedStr };
|
|
}
|
|
}
|
|
|
|
function anyFilterActive() {
|
|
const filters = app.modules.filters;
|
|
const keys = Object.keys(state.filter);
|
|
for (let i = 0; i < keys.length; i++) {
|
|
if (!filters.isEmpty(state.filter[keys[i]])) {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
function paint() {
|
|
const filtered = app.modules.filters.apply(state.rows, columns, state.filter, app.modules.util.resolveField);
|
|
const sorted = app.modules.sort.apply(filtered, state.sort, columns, app.modules.util);
|
|
app.modules.render.header(theadEl, columns, state.sort, state.filter, onHeaderClick, onFilterChange);
|
|
app.modules.render.body(tbodyEl, sorted, columns);
|
|
app.modules.render.rowCount(countEl, sorted.length, state.rows.length);
|
|
if (emptyEl) {
|
|
emptyEl.hidden = sorted.length > 0 || state.rows.length === 0;
|
|
}
|
|
if (clearBtn) {
|
|
clearBtn.hidden = !anyFilterActive();
|
|
}
|
|
// Restore the editor's selection across re-paints so a sort
|
|
// or filter change doesn't dump the user out of the cell
|
|
// they were on. Selected coords clamp to the new bounds in
|
|
// setSelected; if the row vanished (filter excluded it),
|
|
// we land on the last valid cell instead of clearing.
|
|
const editor = app.modules.editor;
|
|
if (editor) {
|
|
editor.attachToTable();
|
|
if (state.selected) {
|
|
editor.setSelected(state.selected.row, state.selected.col, { noFocus: true });
|
|
}
|
|
}
|
|
// Re-apply Phase-3 dirty-row markers — tbody.innerHTML='' in
|
|
// renderBody wiped them.
|
|
const save = app.modules.save;
|
|
if (save && typeof save.markAllDirtyRows === 'function') {
|
|
save.markAllDirtyRows();
|
|
}
|
|
}
|
|
|
|
// Public re-paint entry point so other modules (save.useMine /
|
|
// save.reload) can request a refresh after they mutate row state.
|
|
app.repaint = paint;
|
|
|
|
function onHeaderClick(field, shiftKey) {
|
|
state.sort = app.modules.sort.cycle(state.sort, field, shiftKey);
|
|
paint();
|
|
}
|
|
|
|
function onFilterChange(field, value) {
|
|
state.filter[field] = value;
|
|
paint();
|
|
}
|
|
|
|
if (clearBtn) {
|
|
clearBtn.addEventListener('click', function () {
|
|
state.filter = {};
|
|
paint();
|
|
});
|
|
}
|
|
|
|
paint();
|
|
}
|
|
|
|
if (document.readyState === 'loading') {
|
|
document.addEventListener('DOMContentLoaded', init);
|
|
} else {
|
|
init();
|
|
}
|
|
})(window.tablesApp);
|