tablo-ui 0.2.0

Beautiful Topcoat UI primitives for Tablo — owned library over topcoat-ui-registry.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
// Unit test for the confirmed-mutation wiring in `mutation-submit.js`.
//
// There is no JS test runner in this workspace — the assets are plain browser
// scripts loaded through `asset!` — so this runs on Node's built-in runner and
// reaches the functions through the guarded `module.exports` at the bottom of
// the script:
//
//     node --test crates/tablo-ui/assets/mutation-submit.test.js
//
// What it protects: which region a mutation response hands over (the rendered
// table inside the streamed swap envelope, never the loading skeleton the
// response also carries), which toast surfaces mount, which keys a write
// removed from the bulk selection, which submits this script answers at all —
// a form the page cannot serve must keep the browser's own submit — and what
// it does with a response the server answered itself: the fetched page is
// shown in place, and the mutation is not posted again.
//
// The DOM half of the script (the shard re-render, `DOMParser`) has no
// stand-in here; it is verified against a running panel instead. The fetch
// stand-in below covers the failure branch, which is where the re-send lived.

const test = require('node:test');
const assert = require('node:assert/strict');

const SCRIPT = require.resolve('./mutation-submit.js');
const {
  deletedKey,
  pruneWire,
  removedKeys,
  submitTarget,
  swapTargets,
  tableRootFor,
} = require(SCRIPT);

const { listenerDocument } = require('./test-dom');

// --- the record a row-delete action names -----------------------------------

test('a row-delete action names its record key', () => {
  assert.equal(
    deletedKey('/admin/users/01a0cf6a-7885-75e6-8230-74b677786c1f/delete'),
    '01a0cf6a-7885-75e6-8230-74b677786c1f',
  );
});

test('a percent-encoded key is decoded to the wire spelling', () => {
  // The wire and the action carry the same record key: the checkbox value is
  // the raw PK, the URL segment is the encoded one. Pruning compares raw keys,
  // so the action's segment has to come back decoded.
  assert.equal(deletedKey('/admin/users/a%20b%2Fc/delete'), 'a b/c');
});

test('a URL that is not a row-delete action names no record', () => {
  // The bulk-delete route and anything else must not prune a key.
  assert.equal(deletedKey('/admin/users/bulk-delete'), null);
  assert.equal(deletedKey('/admin/users'), null);
  assert.equal(deletedKey(''), null);
});

// --- where a submit posts ----------------------------------------------------

// An element stand-in answering `getAttribute` from a map.
const withAttributes = (attrs) => ({
  getAttribute: (name) => (name in attrs ? attrs[name] : null),
});

test('a submit posts to the form action by default', () => {
  const form = withAttributes({ action: '/admin/posts/bulk-delete' });
  assert.equal(submitTarget(form, null), '/admin/posts/bulk-delete');
  assert.equal(submitTarget(form, withAttributes({})), '/admin/posts/bulk-delete');
});

test("a bulk action button posts to its own formaction", () => {
  // The custom bulk actions share the bulk form, so its selection rides
  // along, and each names its route on the button.
  const form = withAttributes({ action: '/admin/posts/bulk-delete' });
  const button = withAttributes({ formaction: '/admin/posts/-/actions/publish' });
  assert.equal(submitTarget(form, button), '/admin/posts/-/actions/publish');
});

// --- the keys a write removed -----------------------------------------------

// A form stand-in carrying the fields the decision reads.
const formWith = (fields) => ({
  querySelector: (selector) => {
    const name = /name="([^"]+)"/.exec(selector);
    return name && name[1] in fields ? fields[name[1]] : null;
  },
});

test('a bulk form removes the batch it carried', () => {
  // The transport is the form's `ids` field: exactly the keys the handler
  // deletes, so the wire empties after the batch lands.
  const form = formWith({ ids: { value: ',a,b,' } });
  assert.deepEqual(removedKeys(form, '/admin/users/bulk-delete'), ['a', 'b']);
});

test('a bulk custom action removes nothing from the selection', () => {
  // It shares the bulk form, so it carries the same `ids`, but its rows stay.
  const form = formWith({ ids: { value: ',a,b,' } });
  assert.deepEqual(removedKeys(form, '/admin/users/-/actions/publish'), []);
});

test('a row form removes the one record its action names', () => {
  const form = formWith({});
  assert.deepEqual(removedKeys(form, '/admin/users/ada/delete'), ['ada']);
});

test('a form naming neither removes nothing', () => {
  // Pruning nothing keeps a selection the write did not touch; guessing here
  // would clear a selection the reader still holds.
  assert.deepEqual(removedKeys(formWith({}), '/admin/users/bulk-delete'), []);
});

// --- which table a form belongs to ------------------------------------------

// A node stand-in whose `closest` answers the selectors a case gives it.
const closestOf = (answers) => ({
  closest: (selector) => answers[selector] || null,
});

test('a form inside a table belongs to that table', () => {
  const own = closestOf({});
  const form = closestOf({ '[data-table-root]': own });
  assert.equal(tableRootFor(form, '/admin/users/ada/delete'), own);
});

test('a row confirm outside every table finds its table through its control', () => {
  // The row dialog is page-owned and sits outside the region, so the form has
  // no table ancestor: the control that opened it (carrying the same POST
  // target) is what names the table.
  const root = closestOf({});
  const trigger = {
    getAttribute: (name) =>
      name === 'data-row-delete-action' ? '/admin/users/ada/delete' : null,
    closest: (selector) => (selector === '[data-table-root]' ? root : null),
  };
  global.document = { querySelectorAll: () => [trigger] };
  try {
    const form = closestOf({});
    assert.equal(tableRootFor(form, '/admin/users/ada/delete'), root);
  } finally {
    delete global.document;
  }
});

test('a form whose control is gone belongs to no table', () => {
  // A stale action (the row was re-rendered away) must not fall back to the
  // document: the client then leaves the page alone instead of touching the
  // wrong table.
  global.document = { querySelectorAll: () => [] };
  try {
    assert.equal(tableRootFor(closestOf({}), '/admin/users/ada/delete'), null);
  } finally {
    delete global.document;
  }
});

// --- the selection wire -----------------------------------------------------

test('pruning drops the removed keys and keeps the rest', () => {
  assert.equal(pruneWire(',a,b,c,', ['b']), ',a,c,');
  assert.equal(pruneWire(',a,b,', ['a', 'b']), '');
  assert.equal(pruneWire('', ['a']), '');
  // Exactness comes from the wire's delimiters: `,ab,` never matches `b`.
  assert.equal(pruneWire(',ab,', ['b']), ',ab,');
});

test('pruning keeps keys selected on another page', () => {
  // The wire carries selections the page does not render (bulk.js keeps them
  // across pages); a delete must not drop those.
  assert.equal(pruneWire(',page2,page3,', ['page2']), ',page3,');
});

// --- what the response hands over -------------------------------------------

// A node stand-in: `querySelector` answers only the selectors the case uses.
const nodeOf = (selectors) => ({
  querySelector: (selector) => selectors[selector] || null,
});

// A node holding a rendered region. Two selectors reach it: the envelope is
// identified by carrying the region at all, and the region itself is taken
// with the busy placeholder excluded.
const regionNode = (table) =>
  nodeOf({
    '[data-boundary="table"]': table,
    '[data-boundary="table"]:not([aria-busy])': table,
  });

// A document stand-in holding the pieces `swapTargets` reads.
const docOf = ({ templates = [], toasts = [], region = null } = {}) => ({
  querySelectorAll: (selector) => {
    if (selector === 'template[data-topcoat-swap]') return templates;
    if (selector === '[data-sonner-toaster] > [data-sonner-toast]') return toasts;
    return [];
  },
  querySelector: (selector) =>
    selector === '[data-boundary="table"]:not([aria-busy])' ? region : null,
});

test('the streamed envelope wins over the skeleton the response also carries', () => {
  // A streamed list response renders the skeleton inside the region and ships
  // the table in a `<template data-topcoat-swap>` at the end of the body. The
  // skeleton is the same `[data-boundary="table"]`, so taking the document's
  // own region would replace a table with a loading placeholder.
  const table = nodeOf({});
  const skeleton = nodeOf({});
  const targets = swapTargets(
    docOf({
      templates: [{ content: nodeOf({}) }, { content: regionNode(table) }],
      region: skeleton,
    }),
  );
  assert.equal(targets.table, table);
});

test('a response with no envelope hands over its own rendered region', () => {
  const table = nodeOf({});
  const targets = swapTargets(docOf({ region: table }));
  assert.equal(targets.table, table);
});

test('a response offering no rendered region hands over nothing', () => {
  // The client then navigates instead of replacing the table with a skeleton.
  assert.equal(swapTargets(docOf({})).table, null);
});

test('a named region takes the response region of its own name', () => {
  // A record page renders one table per relation: a delete in the second
  // must not swap in the first.
  const own = nodeOf({});
  const doc = {
    querySelectorAll: () => [],
    querySelector: (selector) =>
      selector === '[data-boundary="table"][data-table="/admin/tags"]:not([aria-busy])'
        ? own
        : null,
  };
  assert.equal(swapTargets(doc, '/admin/tags').table, own);
  assert.equal(swapTargets(doc, '/admin/comments').table, null);
});

test('every toast surface the response carries is handed over', () => {
  const toasts = [nodeOf({}), nodeOf({})];
  assert.deepEqual(swapTargets(docOf({ toasts })).toasts, toasts);
});

// --- which submits this script answers --------------------------------------

// `install()` reads `document` and `window` from the global scope and every
// listener is document-delegated, so the stand-ins have to be in place before
// the script is required and stay there while its listeners run. `written`
// records the page `showResponse` replaces the document with.
function standInDocument() {
  return listenerDocument({
    written: [],
    // The wiring reads the page before it posts: the row a delete came from
    // and the dialog it was confirmed in.
    querySelectorAll: () => [],
    querySelector: () => null,
    // `showResponse` renders the fetched answer into the document.
    open() {},
    write(html) {
      this.written.push(html);
    },
    close() {},
  });
}

// A form stand-in: the marker answers the listener's `closest`, the action is
// what the case gives it, and `dialog` is the confirm dialog the row form
// lives in. `new FormData(form)` cannot serialize this, which is the point —
// the post is never reached, only the decision is under test.
const submitForm = ({
  marked = true,
  action = '/admin/users/ada/delete',
  dialog = null,
} = {}) => {
  const form = {
    getAttribute: (name) => (name === 'action' ? action : null),
    matches: () => marked,
    closest: (selector) => {
      if (selector === 'dialog') return dialog;
      return marked && selector === 'form[data-mutation-submit]' ? form : null;
    },
    querySelector: (selector) => (selector === 'dialog' ? dialog : null),
  };
  return form;
};

// Load a fresh copy of the script against the stand-ins, run the case, and
// drop them: a fresh copy re-runs `install()`, so each case gets its own
// listener set. An async case keeps the globals until it settles, because
// `send` reads them after the fetch resolves.
function withGlobals(run) {
  const document = standInDocument();
  const calls = { reloaded: 0, assigned: [] };
  global.document = document;
  global.window = {
    location: {
      reload: () => calls.reloaded++,
      assign: (url) => calls.assigned.push(url),
      href: 'http://localhost/admin/users',
    },
    history: { state: null, replaceState() {} },
    setTimeout: () => 0,
    clearTimeout() {},
  };
  delete require.cache[SCRIPT];
  const drop = () => {
    delete global.document;
    delete global.window;
  };
  let result;
  try {
    require(SCRIPT);
    result = run({ document, calls });
  } catch (error) {
    drop();
    throw error;
  }
  if (result && typeof result.then === 'function') {
    return result.finally(drop);
  }
  drop();
  return result;
}

// A submit event as the browser hands it to the listener.
function submitEvent(form) {
  return {
    prevented: false,
    target: form,
    submitter: null,
    preventDefault() {
      this.prevented = true;
    },
  };
}

test('a marked form with a target is answered in place', () => {
  withGlobals(({ document }) => {
    const form = submitForm();
    const event = submitEvent(form);
    document.listeners('submit').forEach((handler) => handler(event));
    assert.equal(event.prevented, true, 'the navigation must not happen');
  });
});

test('a form the page cannot serve keeps the browser submit', () => {
  // The row dialog is retargeted from the control that opens it, so an
  // actionless form is markup the page cannot post: swallowing it would leave
  // the row with no delete at all.
  withGlobals(({ document }) => {
    const form = submitForm({ action: null });
    const event = submitEvent(form);
    document.listeners('submit').forEach((handler) => handler(event));
    assert.equal(event.prevented, false, 'the browser posts it');
  });
});

test('a form without the marker is left alone', () => {
  // Every other form on the page — create, edit, login, the no-JS search —
  // is not this script's business.
  withGlobals(({ document }) => {
    const form = submitForm({ marked: false });
    const event = submitEvent(form);
    document.listeners('submit').forEach((handler) => handler(event));
    assert.equal(event.prevented, false, 'the browser posts it');
  });
});

// -- a response the server answered itself ------------------------

// A form stand-in that records a browser submit, so "the delete is not sent
// again" is an observation rather than a reading of the listener.
function recordableForm(options) {
  const form = submitForm(options);
  form.submits = 0;
  form.submit = () => {
    form.submits += 1;
  };
  return form;
}

// `send` reads `FormData` and `fetch` from the global scope. The fetch answers
// with a response that never redirected: the server answered the POST itself.
async function withServerAnswer(answer, run) {
  return withGlobals(async (context) => {
    const realFormData = global.FormData;
    const realFetch = global.fetch;
    global.FormData = class {
      constructor(form) {
        this.form = form;
      }
    };
    global.fetch = async () => answer;
    try {
      return await run(context);
    } finally {
      global.FormData = realFormData;
      global.fetch = realFetch;
    }
  });
}

test('a server-answered failure is shown, not posted again', async () => {
  // The server can commit the write and then fail — a panic in `after_commit`
  // answers 500 — so the response does not mean "nothing happened". The page
  // the no-JS POST would have rendered is shown in place, and the delete is
  // never sent a second time.
  await withServerAnswer(
    {
      redirected: false,
      ok: false,
      status: 500,
      text: async () => '<!doctype html><p>the write failed</p>',
    },
    async ({ document }) => {
      const form = recordableForm();
      const event = submitEvent(form);
      document.listeners('submit').forEach((handler) => handler(event));
      await new Promise((resolve) => setImmediate(resolve));
      assert.equal(form.submits, 0, 'the committed delete must not be re-sent');
      assert.deepEqual(
        document.written,
        ['<!doctype html><p>the write failed</p>'],
        'the server answer is shown where the browser would have shown it',
      );
    },
  );
});

test('a refused submit shows the response without repeating the request', async () => {
  // A 4xx is the server refusing the write, but the client still does not know
  // the record is untouched, so it applies the same rule: show, never re-send.
  await withServerAnswer(
    {
      redirected: false,
      ok: false,
      status: 403,
      text: async () => '<!doctype html><p>not allowed</p>',
    },
    async ({ document }) => {
      const form = recordableForm();
      const event = submitEvent(form);
      document.listeners('submit').forEach((handler) => handler(event));
      await new Promise((resolve) => setImmediate(resolve));
      assert.equal(form.submits, 0, 'the refused delete is not posted again');
      assert.deepEqual(document.written, ['<!doctype html><p>not allowed</p>']);
    },
  );
});

test('the confirm dialog is held while the mutation is in flight', async () => {
  // `dialog.js` refuses to dismiss a dialog carrying this marker, so the write
  // owns it until its response is in hand.
  await withServerAnswer(
    {
      redirected: false,
      ok: false,
      status: 500,
      text: async () => '<!doctype html><p>the write failed</p>',
    },
    async ({ document }) => {
      const dialog = { dataset: {} };
      const form = recordableForm({ dialog });
      const event = submitEvent(form);
      document.listeners('submit').forEach((handler) => handler(event));
      assert.equal(
        dialog.dataset.dialogBusy,
        'true',
        'the dialog belongs to the write while it is outstanding',
      );
      await new Promise((resolve) => setImmediate(resolve));
      assert.equal(
        dialog.dataset.dialogBusy,
        undefined,
        'the response hands the dialog back',
      );
    },
  );
});