tadabut 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1189 @@
1
+ import DataTable from "datatables.net";
2
+ // src/editors/classes.ts
3
+ /**
4
+ * `'btn btn-sm '` → `['btn', 'btn-sm']`. Empty pieces are dropped because
5
+ * `classList.add('')` throws.
6
+ */
7
+ function splitClasses(...lists) {
8
+ return lists.flatMap((list) => list?.split(/\s+/).filter(Boolean) ?? []);
9
+ }
10
+ /** Adds Tadabut's own classes, then the user's. */
11
+ function addClasses(element, ownClasses, className) {
12
+ element.classList.add(...ownClasses, ...splitClasses(className));
13
+ }
14
+ // src/columns/escape.ts
15
+ /** Characters that mean something in HTML. */
16
+ const entities = {
17
+ "&": "&",
18
+ "<": "&lt;",
19
+ ">": "&gt;",
20
+ "\"": "&quot;",
21
+ "'": "&#39;"
22
+ };
23
+ /** DataTables inserts rendered cells as HTML, so labels go through this. */
24
+ function escapeHtml(text) {
25
+ return text.replace(/[&<>"']/g, (char) => entities[char] ?? char);
26
+ }
27
+ // src/table/elements.ts
28
+ /** The same list at runtime, to check what's read back from the page. */
29
+ const buttonActions = /* @__PURE__ */ new Set([
30
+ "edit",
31
+ "delete",
32
+ "save",
33
+ "cancel",
34
+ "confirm",
35
+ "keep"
36
+ ]);
37
+ /** Whether a `data-tdb-action` is one of ours. */
38
+ function isButtonAction(value) {
39
+ return value !== void 0 && buttonActions.has(value);
40
+ }
41
+ /** Edit or Delete as HTML, for DataTables' `defaultContent`, so everything in it is escaped. */
42
+ function buttonHtml(action, label, extra) {
43
+ return `<button type="button" class="${escapeHtml([
44
+ "tdb-button",
45
+ `tdb-button-${action}`,
46
+ ...extra
47
+ ].join(" "))}" data-tdb-action="${action}">${escapeHtml(label)}</button>`;
48
+ }
49
+ /** Builds a button that replaces Edit and Delete for a while. */
50
+ function actionButton(action, label, extra) {
51
+ const button = document.createElement("button");
52
+ button.type = "button";
53
+ button.classList.add("tdb-button", `tdb-button-${action}`, ...extra);
54
+ button.dataset.tdbAction = action;
55
+ button.textContent = label;
56
+ return button;
57
+ }
58
+ /** Save and Cancel, for an open row. */
59
+ function saveCancelButtons(texts, classNames) {
60
+ return [actionButton("save", texts.save, splitClasses(classNames.button, classNames.save)), actionButton("cancel", texts.cancel, splitClasses(classNames.button, classNames.cancel))];
61
+ }
62
+ /**
63
+ * "Delete this row? [Yes, delete] [No]". `keep` is returned on its own so it
64
+ * can get the focus.
65
+ */
66
+ function deleteQuestion(texts, classNames) {
67
+ const question = document.createElement("span");
68
+ question.className = "tdb-delete-question";
69
+ question.textContent = texts.deleteQuestion;
70
+ const confirm = actionButton("confirm", texts.confirm, splitClasses(classNames.button, classNames.confirm));
71
+ const keep = actionButton("keep", texts.keep, splitClasses(classNames.button, classNames.keep));
72
+ return {
73
+ parts: [
74
+ question,
75
+ confirm,
76
+ keep
77
+ ],
78
+ keep
79
+ };
80
+ }
81
+ /**
82
+ * The message of a save, delete or add error. It gets its own class because
83
+ * Bootstrap colors every cell, which hides a color on the row. Set as text:
84
+ * it often comes from a server.
85
+ */
86
+ function rowErrorMessage(message) {
87
+ const error = document.createElement("div");
88
+ error.className = "tdb-row-error-message";
89
+ error.textContent = message;
90
+ return error;
91
+ }
92
+ // src/columns/to-datatables.ts
93
+ /**
94
+ * The column with the Edit and Delete buttons. While a row is open, Save and
95
+ * Cancel replace them.
96
+ */
97
+ function actionsColumn(actions, classNames, texts) {
98
+ return {
99
+ title: "",
100
+ data: null,
101
+ className: "tdb-actions",
102
+ orderable: false,
103
+ searchable: false,
104
+ defaultContent: actions.map((action) => buttonHtml(action, texts[action], splitClasses(classNames.button, classNames[action]))).join("")
105
+ };
106
+ }
107
+ /**
108
+ * The actions column is always appended last, because the rest of Tadabut
109
+ * finds cells by the user's column index. No `actions` means no column.
110
+ */
111
+ function toDataTables(columns, actions, classNames, texts) {
112
+ const converted = columns.map((column) => {
113
+ const label = labelOf(column);
114
+ return {
115
+ ...defined({
116
+ width: column.width,
117
+ visible: column.visible,
118
+ orderable: column.orderable,
119
+ searchable: column.searchable,
120
+ className: column.className
121
+ }),
122
+ title: column.title,
123
+ data: column.prop,
124
+ render: (value, type, row) => {
125
+ switch (type) {
126
+ case "display": return escapeHtml(label(value, row));
127
+ case "filter": return label(value, row);
128
+ default: return value;
129
+ }
130
+ }
131
+ };
132
+ });
133
+ return actions.length > 0 ? [...converted, actionsColumn(actions, classNames, texts)] : converted;
134
+ }
135
+ /** `render`, then `labelProp`, then a fixed list's label, then the value. */
136
+ function labelOf(column) {
137
+ const { render, editor } = column;
138
+ if (render !== void 0) return render;
139
+ if (editor?.type === "select") {
140
+ const labelProp = editor.labelProp;
141
+ if (labelProp !== void 0) return (_value, row) => asText(row[labelProp]);
142
+ if (typeof editor.options !== "function") {
143
+ const options = editor.options;
144
+ return (value) => options.find((option) => option.value === value)?.label ?? asText(value);
145
+ }
146
+ }
147
+ return asText;
148
+ }
149
+ /** `null` and `undefined` become an empty cell. */
150
+ function asText(value) {
151
+ return value === null || value === void 0 ? "" : String(value);
152
+ }
153
+ /** Drops the keys whose value is `undefined`. */
154
+ function defined(values) {
155
+ const kept = Object.entries(values).filter(([, value]) => value !== void 0);
156
+ return Object.fromEntries(kept);
157
+ }
158
+ // src/texts/en.ts
159
+ /** English, the default. */
160
+ const en = {
161
+ edit: "Edit",
162
+ save: "Save",
163
+ cancel: "Cancel",
164
+ delete: "Delete",
165
+ deleteQuestion: "Delete this row?",
166
+ confirm: "Yes, delete",
167
+ keep: "No",
168
+ deleteFailed: "Could not delete.",
169
+ loading: "Loading…",
170
+ saveFailed: "Could not save.",
171
+ loadFailed: "Could not load the options.",
172
+ addFailed: "Could not add.",
173
+ required: "This field is required.",
174
+ patternMismatch: "Wrong format.",
175
+ tooShort: (min) => `Must be at least ${min} characters.`,
176
+ tooLong: (max) => `Must be at most ${max} characters.`,
177
+ tooSmall: (min) => `Must be ${min} or more.`,
178
+ tooLarge: (max) => `Must be ${max} or less.`,
179
+ tooEarly: (min) => `Must be on or after ${min}.`,
180
+ tooLate: (max) => `Must be on or before ${max}.`
181
+ };
182
+ // src/editors/checkbox.ts
183
+ /**
184
+ * Builds the checkbox. `_config` is unused for now, but keeps the same
185
+ * shape as the other editors.
186
+ */
187
+ function createCheckboxEditor(_config, context) {
188
+ const input = document.createElement("input");
189
+ input.type = "checkbox";
190
+ addClasses(input, ["tdb-input", "tdb-input-checkbox"], context.className);
191
+ /** `null` shows as unchecked. */
192
+ const setValue = (value) => {
193
+ input.checked = value === true;
194
+ };
195
+ setValue(context.value);
196
+ input.addEventListener("change", () => context.onChange(input.checked));
197
+ return {
198
+ element: input,
199
+ getValue: () => input.checked,
200
+ setValue,
201
+ focus: () => input.focus(),
202
+ destroy: () => input.remove()
203
+ };
204
+ }
205
+ // src/editors/date.ts
206
+ /** Builds the date input. */
207
+ function createDateEditor(config, context) {
208
+ const input = document.createElement("input");
209
+ input.type = "date";
210
+ addClasses(input, ["tdb-input", "tdb-input-date"], context.className);
211
+ if (config.min !== void 0) input.min = config.min;
212
+ if (config.max !== void 0) input.max = config.max;
213
+ /** Empty gives `null`. */
214
+ const getValue = () => input.value === "" ? null : input.value;
215
+ /** `null` shows as empty. */
216
+ const setValue = (value) => {
217
+ input.value = value ?? "";
218
+ };
219
+ setValue(context.value ?? null);
220
+ input.addEventListener("input", () => context.onChange(getValue()));
221
+ return {
222
+ element: input,
223
+ getValue,
224
+ setValue,
225
+ focus: () => input.focus(),
226
+ destroy: () => input.remove()
227
+ };
228
+ }
229
+ // src/editors/number.ts
230
+ /** Builds the number input. */
231
+ function createNumberEditor(config, context) {
232
+ const input = document.createElement("input");
233
+ input.type = "number";
234
+ addClasses(input, ["tdb-input", "tdb-input-number"], context.className);
235
+ if (config.min !== void 0) input.min = String(config.min);
236
+ if (config.max !== void 0) input.max = String(config.max);
237
+ if (config.step !== void 0) input.step = String(config.step);
238
+ /** Empty gives `null`, not `0`. */
239
+ const getValue = () => input.value === "" ? null : input.valueAsNumber;
240
+ /** `null` shows as empty. */
241
+ const setValue = (value) => {
242
+ input.value = value === null ? "" : String(value);
243
+ };
244
+ setValue(context.value ?? null);
245
+ input.addEventListener("input", () => context.onChange(getValue()));
246
+ return {
247
+ element: input,
248
+ getValue,
249
+ setValue,
250
+ focus: () => input.focus(),
251
+ destroy: () => input.remove()
252
+ };
253
+ }
254
+ // src/editors/select.ts
255
+ /**
256
+ * `<option>` values are always strings, so the picked value is looked up by
257
+ * index to keep its real type. Until a loader's options arrive, the starting
258
+ * value is kept in `current`.
259
+ */
260
+ function createSelectEditor(config, context, texts = en) {
261
+ const select = document.createElement("select");
262
+ addClasses(select, ["tdb-input", "tdb-input-select"], context.className);
263
+ /** The options on screen. Empty while a loader runs. */
264
+ let options = [];
265
+ /** The value, kept even while there are no options to pick it from. */
266
+ let current = context.value;
267
+ /** The running load, so a newer one or `destroy` can abort it. */
268
+ let controller;
269
+ /** Selects `current`. A value that isn't in the list becomes `null`. */
270
+ const pickCurrent = () => {
271
+ select.selectedIndex = options.findIndex((option) => option.value === current);
272
+ if (select.selectedIndex === -1) current = null;
273
+ };
274
+ /** Shows `list`, enables the select and picks `current`. */
275
+ const fill = (list) => {
276
+ options = list;
277
+ select.replaceChildren(...list.map((option) => {
278
+ const element = document.createElement("option");
279
+ element.textContent = option.label;
280
+ return element;
281
+ }));
282
+ select.disabled = false;
283
+ pickCurrent();
284
+ };
285
+ /** Shows a single disabled line, like "Loading…". */
286
+ const showOnly = (text) => {
287
+ options = [];
288
+ const element = document.createElement("option");
289
+ element.textContent = text;
290
+ select.replaceChildren(element);
291
+ select.disabled = true;
292
+ };
293
+ /** Runs the `options` function and shows its result. */
294
+ const load = async (row) => {
295
+ if (typeof config.options !== "function") return "loaded";
296
+ controller?.abort();
297
+ const own = new AbortController();
298
+ controller = own;
299
+ try {
300
+ const result = config.options(row, { signal: own.signal });
301
+ if (!(result instanceof Promise)) {
302
+ fill(result);
303
+ return "loaded";
304
+ }
305
+ showOnly(texts.loading);
306
+ const list = await result;
307
+ if (own.signal.aborted) return "cancelled";
308
+ fill(list);
309
+ return "loaded";
310
+ } catch {
311
+ if (own.signal.aborted) return "cancelled";
312
+ showOnly("");
313
+ return "failed";
314
+ }
315
+ };
316
+ /** The value, even while options are loading. */
317
+ const getValue = () => current;
318
+ /** `undefined` while options aren't loaded. */
319
+ const getLabel = () => current === null ? null : options.find((option) => option.value === current)?.label;
320
+ /** While loading, the value is only remembered. */
321
+ const setValue = (value) => {
322
+ current = value;
323
+ if (!select.disabled) pickCurrent();
324
+ };
325
+ if (typeof config.options !== "function") fill(config.options);
326
+ select.addEventListener("change", () => {
327
+ current = options[select.selectedIndex]?.value ?? null;
328
+ context.onChange(current);
329
+ });
330
+ return {
331
+ element: select,
332
+ getValue,
333
+ getLabel,
334
+ setValue,
335
+ load,
336
+ focus: () => select.focus(),
337
+ destroy: () => {
338
+ controller?.abort();
339
+ select.remove();
340
+ }
341
+ };
342
+ }
343
+ // src/editors/text.ts
344
+ /** Builds the text input. `null` shows as empty. */
345
+ function createTextEditor(config, context) {
346
+ const input = document.createElement("input");
347
+ input.type = "text";
348
+ addClasses(input, ["tdb-input", "tdb-input-text"], context.className);
349
+ if (config.minLength !== void 0) input.minLength = config.minLength;
350
+ if (config.maxLength !== void 0) input.maxLength = config.maxLength;
351
+ if (config.pattern !== void 0) input.pattern = config.pattern;
352
+ input.value = context.value ?? "";
353
+ input.addEventListener("input", () => context.onChange(input.value));
354
+ return {
355
+ element: input,
356
+ getValue: () => input.value,
357
+ setValue: (value) => {
358
+ input.value = value ?? "";
359
+ },
360
+ focus: () => input.focus(),
361
+ destroy: () => input.remove()
362
+ };
363
+ }
364
+ // src/editors/create.ts
365
+ /**
366
+ * `Column<Row>` already checked that each config fits its column, so the
367
+ * casts below are safe.
368
+ */
369
+ function createEditor(config, context, texts = en) {
370
+ const fullContext = {
371
+ ...context,
372
+ className: config.className
373
+ };
374
+ switch (config.type) {
375
+ case "text": return loosen(createTextEditor(config, tighten(fullContext)));
376
+ case "number": return loosen(createNumberEditor(config, tighten(fullContext)));
377
+ case "date": return loosen(createDateEditor(config, tighten(fullContext)));
378
+ case "checkbox": return loosen(createCheckboxEditor(config, tighten(fullContext)));
379
+ case "select": return createSelectEditor(config, fullContext, texts);
380
+ case "custom": return config.create(fullContext);
381
+ default: throw new Error(`Unknown editor: ${JSON.stringify(config)}`);
382
+ }
383
+ }
384
+ /** Gives a built-in editor the context type it expects. */
385
+ function tighten(context) {
386
+ return context;
387
+ }
388
+ /** Turns a typed editor back into the loose type. */
389
+ function loosen(editor) {
390
+ return editor;
391
+ }
392
+ // src/validation/validate.ts
393
+ /** Returns the first error message, or `undefined`. */
394
+ function validateValue(config, value, row, texts = en) {
395
+ if (value === null || value === void 0 || value === "") return config.required ? texts.required : void 0;
396
+ return builtInError(config, value, texts) ?? config.validate?.(value, row);
397
+ }
398
+ /** The rules each built-in editor brings. */
399
+ function builtInError(config, value, texts) {
400
+ switch (config.type) {
401
+ case "text": return typeof value === "string" ? textError(config, value, texts) : void 0;
402
+ case "number": return typeof value === "number" ? rangeError(config, value, texts) : void 0;
403
+ case "date": return typeof value === "string" ? dateError(config, value, texts) : void 0;
404
+ case "checkbox":
405
+ case "select":
406
+ case "custom": return;
407
+ default: throw new Error(`Unknown editor: ${JSON.stringify(config)}`);
408
+ }
409
+ }
410
+ /** `minLength`, `maxLength` and `pattern`. */
411
+ function textError(config, value, texts) {
412
+ if (config.minLength !== void 0 && value.length < config.minLength) return texts.tooShort(config.minLength);
413
+ if (config.maxLength !== void 0 && value.length > config.maxLength) return texts.tooLong(config.maxLength);
414
+ if (config.pattern !== void 0 && !matchesWhole(config.pattern, value)) return texts.patternMismatch;
415
+ }
416
+ /** `min` and `max` for numbers. */
417
+ function rangeError(config, value, texts) {
418
+ if (config.min !== void 0 && value < config.min) return texts.tooSmall(config.min);
419
+ if (config.max !== void 0 && value > config.max) return texts.tooLarge(config.max);
420
+ }
421
+ /** `min` and `max` for dates. */
422
+ function dateError(config, value, texts) {
423
+ if (config.min !== void 0 && value < config.min) return texts.tooEarly(config.min);
424
+ if (config.max !== void 0 && value > config.max) return texts.tooLate(config.max);
425
+ }
426
+ /**
427
+ * Same rules as the HTML `pattern` attribute: whole value, `v` flag, and an
428
+ * invalid pattern is ignored. The group stops `a|b` from becoming `^a|b$`.
429
+ */
430
+ function matchesWhole(pattern, value) {
431
+ let regex;
432
+ try {
433
+ regex = new RegExp(`^(?:${pattern})$`, "v");
434
+ } catch {
435
+ return true;
436
+ }
437
+ return regex.test(value);
438
+ }
439
+ // src/editing/session.ts
440
+ /** For unique error ids (`aria-describedby` needs one). */
441
+ let errorCount = 0;
442
+ /**
443
+ * One open row. Doesn't know about DataTables: `Tadabut` hands it the cells
444
+ * and restores them afterwards.
445
+ */
446
+ var EditSession = class {
447
+ /** A copy of the row from before editing. `onSave` gets it as `previous`. */
448
+ originalData;
449
+ /** Open fields, by row field. */
450
+ fields = /* @__PURE__ */ new Map();
451
+ /** Error messages on screen, by row field. */
452
+ errors = /* @__PURE__ */ new Map();
453
+ /** For each field, the selects that depend on it. */
454
+ dependents = /* @__PURE__ */ new Map();
455
+ /** Selects whose last options load failed. */
456
+ loadErrors = /* @__PURE__ */ new Set();
457
+ /** Set by `Tadabut` while `onSave` runs. */
458
+ saving = false;
459
+ /** Error messages and the "Loading…" text. */
460
+ texts;
461
+ /** Puts an editor in each cell and starts loading select options. */
462
+ constructor(row, cells, texts = en) {
463
+ this.originalData = { ...row };
464
+ this.texts = texts;
465
+ for (const { column, cell } of cells) {
466
+ if (column.editor === void 0) continue;
467
+ const config = column.editor;
468
+ if (config.type === "select" && config.dependsOn !== void 0) {
469
+ const list = this.dependents.get(config.dependsOn) ?? [];
470
+ list.push(column.prop);
471
+ this.dependents.set(config.dependsOn, list);
472
+ }
473
+ const editor = createEditor(config, {
474
+ value: this.originalData[column.prop],
475
+ onChange: () => this.changed(column.prop)
476
+ }, texts);
477
+ cell.replaceChildren(editor.element);
478
+ this.fields.set(column.prop, {
479
+ editor,
480
+ config
481
+ });
482
+ }
483
+ for (const prop of this.fields.keys()) this.loadField(prop);
484
+ }
485
+ /**
486
+ * The row with the current editor values. It can hold `null` where `Row`
487
+ * doesn't allow it (an empty number input), so validate before trusting it.
488
+ */
489
+ getRow() {
490
+ const row = { ...this.originalData };
491
+ for (const [prop, { editor, config }] of this.fields) {
492
+ row[prop] = editor.getValue();
493
+ if (config.type === "select" && config.labelProp !== void 0) {
494
+ const label = editor.getLabel?.();
495
+ if (label !== void 0) row[config.labelProp] = label;
496
+ }
497
+ }
498
+ return row;
499
+ }
500
+ /** Every rule gets the whole edited row, so fields can be compared. */
501
+ validate() {
502
+ const row = this.getRow();
503
+ const errors = /* @__PURE__ */ new Map();
504
+ for (const [prop, { editor, config }] of this.fields) {
505
+ const message = this.loadErrors.has(prop) ? this.texts.loadFailed : validateValue(config, editor.getValue(), row, this.texts);
506
+ if (message !== void 0) errors.set(prop, message);
507
+ }
508
+ return errors;
509
+ }
510
+ /** Replaces whatever errors are currently shown. */
511
+ showErrors(errors) {
512
+ this.clearErrors();
513
+ for (const [prop, message] of errors) this.showError(prop, message);
514
+ }
515
+ /** Removes every error message and its ARIA attributes. */
516
+ clearErrors() {
517
+ for (const prop of [...this.errors.keys()]) this.hideError(prop);
518
+ }
519
+ /** Moves the cursor to a field. */
520
+ focus(prop) {
521
+ this.fields.get(prop)?.editor.focus();
522
+ }
523
+ /** Leaves the cells empty; the caller redraws them. Safe to call twice. */
524
+ destroy() {
525
+ this.clearErrors();
526
+ for (const { editor } of this.fields.values()) editor.destroy();
527
+ this.fields.clear();
528
+ this.dependents.clear();
529
+ this.loadErrors.clear();
530
+ }
531
+ /** Shows one message under a field, linked with `aria-describedby`. */
532
+ showError(prop, message) {
533
+ const field = this.fields.get(prop);
534
+ if (field === void 0) return;
535
+ this.hideError(prop);
536
+ errorCount += 1;
537
+ const error = document.createElement("div");
538
+ error.id = `tdb-error-${errorCount}`;
539
+ error.className = "tdb-error";
540
+ error.textContent = message;
541
+ field.editor.element.after(error);
542
+ field.editor.element.setAttribute("aria-invalid", "true");
543
+ field.editor.element.setAttribute("aria-describedby", error.id);
544
+ this.errors.set(prop, error);
545
+ }
546
+ /** Removes one field's message, if there is one. */
547
+ hideError(prop) {
548
+ const error = this.errors.get(prop);
549
+ if (error === void 0) return;
550
+ error.remove();
551
+ this.errors.delete(prop);
552
+ const element = this.fields.get(prop)?.editor.element;
553
+ element?.removeAttribute("aria-invalid");
554
+ element?.removeAttribute("aria-describedby");
555
+ }
556
+ /** Country changed: clear region and city, then reload both. */
557
+ changed(prop) {
558
+ const cleared = /* @__PURE__ */ new Set([prop]);
559
+ this.clearBelow(prop, cleared);
560
+ cleared.delete(prop);
561
+ for (const field of cleared) this.loadField(field);
562
+ }
563
+ /**
564
+ * Walks the chain by hand, since `setValue` doesn't fire `onChange`.
565
+ * `cleared` also stops dependency loops.
566
+ */
567
+ clearBelow(prop, cleared) {
568
+ for (const dependent of this.dependents.get(prop) ?? []) {
569
+ if (cleared.has(dependent)) continue;
570
+ cleared.add(dependent);
571
+ this.fields.get(dependent)?.editor.setValue(null);
572
+ this.clearBelow(dependent, cleared);
573
+ }
574
+ }
575
+ /** Loads one select's options and shows or hides the load error. */
576
+ async loadField(prop) {
577
+ const field = this.fields.get(prop);
578
+ if (field?.editor.load === void 0) return;
579
+ const result = await field.editor.load(this.getRow());
580
+ if (result === "cancelled") return;
581
+ if (result === "failed") {
582
+ this.loadErrors.add(prop);
583
+ this.showError(prop, this.texts.loadFailed);
584
+ return;
585
+ }
586
+ if (this.loadErrors.delete(prop)) this.hideError(prop);
587
+ }
588
+ };
589
+ // src/table/check-options.ts
590
+ /**
591
+ * Throws on options that can't work together, before anything is built.
592
+ *
593
+ * @throws If a column has an `editor` and there's no `rowId`.
594
+ * @throws If `onDelete` is set and there's no `rowId`.
595
+ * @throws If a hidden column (`visible: false`) has an `editor`.
596
+ * @throws If a select's `labelProp` is its own column.
597
+ */
598
+ function checkOptions(options) {
599
+ if (options.rowId === void 0) {
600
+ if (options.columns.some((column) => column.editor !== void 0)) throw new Error("Tadabut: rowId is required when a column has an editor.");
601
+ if (options.onDelete !== void 0) throw new Error("Tadabut: rowId is required with onDelete.");
602
+ }
603
+ const hiddenEditable = options.columns.find((column) => column.editor !== void 0 && column.visible === false);
604
+ if (hiddenEditable !== void 0) throw new Error(`Tadabut: the "${hiddenEditable.prop}" column can't have both an editor and visible: false.`);
605
+ const selfLabeled = options.columns.find((column) => column.editor?.type === "select" && column.editor.labelProp === column.prop);
606
+ if (selfLabeled !== void 0) throw new Error(`Tadabut: the "${selfLabeled.prop}" column's labelProp can't be "${selfLabeled.prop}" itself.`);
607
+ }
608
+ // src/table/new-row.ts
609
+ /**
610
+ * The row `add()` opens. It lives in its own `<tbody>`, above DataTables'
611
+ * one, so sorting, search and paging never move it. DataTables doesn't know
612
+ * about it, so nothing here goes through DataTables.
613
+ */
614
+ var NewRow = class {
615
+ /** The `<tbody>` to put in the table. Removing it removes everything. */
616
+ body;
617
+ /** The row itself. */
618
+ tr;
619
+ /** Its inputs. */
620
+ session;
621
+ /** The first column with an editor, for the focus. */
622
+ firstProp;
623
+ /** Builds the row. Nothing is shown until `body` is put in the table. */
624
+ constructor(defaults, options) {
625
+ this.body = document.createElement("tbody");
626
+ this.body.classList.add("tdb-new-rows");
627
+ this.tr = document.createElement("tr");
628
+ this.tr.classList.add("tdb-row-new", "tdb-row-editing");
629
+ const cells = [];
630
+ options.columns.forEach((column, index) => {
631
+ if (!options.isVisible(index)) return;
632
+ const cell = document.createElement("td");
633
+ addClasses(cell, [], column.className);
634
+ if (column.editor !== void 0) cells.push({
635
+ column,
636
+ cell
637
+ });
638
+ else cell.textContent = String(defaults[column.prop] ?? "");
639
+ this.tr.append(cell);
640
+ });
641
+ if (options.withButtons) {
642
+ const actionsCell = document.createElement("td");
643
+ actionsCell.classList.add("tdb-actions");
644
+ actionsCell.replaceChildren(...saveCancelButtons(options.texts, options.classNames));
645
+ this.tr.append(actionsCell);
646
+ }
647
+ this.body.append(this.tr);
648
+ this.session = new EditSession(defaults, cells, options.texts);
649
+ this.firstProp = cells[0]?.column.prop;
650
+ }
651
+ /** Whether `onAdd` is running. */
652
+ get saving() {
653
+ return this.session.saving;
654
+ }
655
+ /** Whether an element is inside this row, or its error. */
656
+ contains(element) {
657
+ return this.body.contains(element);
658
+ }
659
+ /** Puts the cursor in the first input. Only works once `body` is in the page. */
660
+ focus() {
661
+ if (this.firstProp !== void 0) this.session.focus(this.firstProp);
662
+ }
663
+ /**
664
+ * Clears the old errors, then checks every field. Shows the new errors and
665
+ * puts the cursor on the first wrong field.
666
+ *
667
+ * @returns Whether every field is valid.
668
+ */
669
+ validate() {
670
+ this.session.clearErrors();
671
+ this.clearError();
672
+ const errors = this.session.validate();
673
+ const [firstInvalid] = errors.keys();
674
+ if (firstInvalid === void 0) return true;
675
+ this.session.showErrors(errors);
676
+ this.session.focus(firstInvalid);
677
+ return false;
678
+ }
679
+ /** The row with what was typed. Validate first. */
680
+ getRow() {
681
+ return this.session.getRow();
682
+ }
683
+ /** Locks or unlocks the row while `onAdd` runs. */
684
+ setSaving(saving) {
685
+ this.session.saving = saving;
686
+ this.tr.inert = saving;
687
+ this.tr.classList.toggle("tdb-row-saving", saving);
688
+ }
689
+ /**
690
+ * Shows the error in a line under the row, like DataTables' child rows
691
+ * (which only work under DataTables' own rows).
692
+ */
693
+ showError(message) {
694
+ this.clearError();
695
+ const cell = document.createElement("td");
696
+ cell.colSpan = this.tr.cells.length;
697
+ cell.append(rowErrorMessage(message));
698
+ const line = document.createElement("tr");
699
+ line.className = "tdb-row-error";
700
+ line.append(cell);
701
+ this.body.append(line);
702
+ }
703
+ /** Removes the error line, if any. */
704
+ clearError() {
705
+ this.body.querySelector("tr.tdb-row-error")?.remove();
706
+ }
707
+ /** Stops pending loads and takes the row out of the table. */
708
+ destroy() {
709
+ this.session.destroy();
710
+ this.body.remove();
711
+ }
712
+ };
713
+ // src/table/tadabut.ts
714
+ /**
715
+ * A DataTables table with row editing.
716
+ *
717
+ * @typeParam Row - Usually inferred from `data`.
718
+ *
719
+ * @example
720
+ * const table = new Tadabut(container, {
721
+ * data: [{ id: 1, name: 'Amina' }],
722
+ * rowId: 'id',
723
+ * columns: [
724
+ * { title: 'ID', prop: 'id' },
725
+ * { title: 'Name', prop: 'name' },
726
+ * ],
727
+ * });
728
+ */
729
+ var Tadabut = class {
730
+ /** The DataTables instance. */
731
+ dataTable;
732
+ /** The `<table>` Tadabut created. */
733
+ tableEl;
734
+ /** The field that identifies a row. */
735
+ rowId;
736
+ /** The user's columns, without the actions column. */
737
+ columns;
738
+ /** `editing` with its defaults filled in. */
739
+ editing;
740
+ /** The user's classes, or `{}`. */
741
+ classNames;
742
+ /** The user's texts over English. */
743
+ texts;
744
+ /** The user's save callback. */
745
+ onSave;
746
+ /** The user's add callback. */
747
+ onAdd;
748
+ /** The user's delete callback. */
749
+ onDelete;
750
+ /** What the Delete button does before deleting. */
751
+ confirmDelete;
752
+ /** Whether the actions column exists. */
753
+ hasActions;
754
+ /** Whether any column has an editor. */
755
+ hasEditor;
756
+ /** Open rows, by row id. */
757
+ sessions = /* @__PURE__ */ new Map();
758
+ /** Rows waiting for `onDelete`, by row id. */
759
+ deleting = /* @__PURE__ */ new Set();
760
+ /** The row `add()` opened, if any. */
761
+ newRow;
762
+ /**
763
+ * Builds the table inside `container`, which should be empty.
764
+ *
765
+ * @throws If a column has an `editor` and there's no `rowId`.
766
+ * @throws If `onDelete` is set and there's no `rowId`.
767
+ * @throws If a hidden column (`visible: false`) has an `editor`.
768
+ * @throws If a select's `labelProp` is its own column.
769
+ */
770
+ constructor(container, options) {
771
+ checkOptions(options);
772
+ this.hasEditor = options.columns.some((column) => column.editor !== void 0);
773
+ this.rowId = options.rowId;
774
+ this.columns = options.columns;
775
+ this.editing = {
776
+ mode: options.editing?.mode ?? "single",
777
+ button: options.editing?.button ?? true
778
+ };
779
+ const actions = [];
780
+ if (this.hasEditor && this.editing.button) actions.push("edit");
781
+ if (options.onDelete !== void 0) actions.push("delete");
782
+ this.hasActions = actions.length > 0;
783
+ this.onSave = options.onSave;
784
+ this.onAdd = options.onAdd;
785
+ this.onDelete = options.onDelete;
786
+ this.confirmDelete = options.confirmDelete;
787
+ this.classNames = options.classNames ?? {};
788
+ this.texts = {
789
+ ...en,
790
+ ...options.texts
791
+ };
792
+ this.tableEl = document.createElement("table");
793
+ addClasses(this.tableEl, [], this.classNames.table);
794
+ container.appendChild(this.tableEl);
795
+ this.dataTable = new DataTable(this.tableEl, {
796
+ ...options.dataTables,
797
+ data: [...options.data],
798
+ columns: toDataTables(options.columns, actions, this.classNames, this.texts)
799
+ });
800
+ if (this.hasActions) this.tableEl.addEventListener("click", this.onClick);
801
+ if (this.hasEditor) this.tableEl.addEventListener("keydown", this.onKeyDown);
802
+ }
803
+ /**
804
+ * Replaces all rows. Sorting, search and the page are kept.
805
+ *
806
+ * Open rows, and the new row, are closed first, and their unsaved changes
807
+ * are lost.
808
+ */
809
+ setData(rows) {
810
+ this.destroySessions();
811
+ this.deleting.clear();
812
+ this.dataTable.clear().rows.add([...rows]).draw(false);
813
+ }
814
+ /**
815
+ * Opens a row for editing.
816
+ *
817
+ * @param id The value of the row's `rowId` field.
818
+ * @returns `false` if the row doesn't exist, is already open, another row
819
+ * or the new row is open in `'single'` mode, nothing is editable, the row
820
+ * is being deleted, or it's on a page that hasn't been displayed yet.
821
+ */
822
+ edit(id) {
823
+ if (!this.hasEditor || this.sessions.has(id) || this.editing.mode === "single" && (this.sessions.size > 0 || this.newRow !== void 0) || this.deleting.has(id)) return false;
824
+ const row = this.findRow(id);
825
+ if (row === void 0 || row.node() === null) return false;
826
+ const rowIndex = row.index();
827
+ const cells = [];
828
+ this.columns.forEach((column, columnIndex) => {
829
+ if (column.editor !== void 0) {
830
+ const cell = this.dataTable.cell(rowIndex, columnIndex).node();
831
+ cells.push({
832
+ column,
833
+ cell
834
+ });
835
+ }
836
+ });
837
+ this.sessions.set(id, new EditSession(row.data(), cells, this.texts));
838
+ row.node()?.classList.add("tdb-row-editing");
839
+ if (this.hasActions) this.actionsCell(row).replaceChildren(...saveCancelButtons(this.texts, this.classNames));
840
+ return true;
841
+ }
842
+ /**
843
+ * Opens an empty row at the top of the table, for a new row. `defaults` are
844
+ * its starting values. The row is only added once Save works.
845
+ *
846
+ * @returns `false` if no column has an editor, a new row is already open,
847
+ * or a row is being edited in `'single'` mode.
848
+ *
849
+ * @example
850
+ * table.add({ country: 'MA' });
851
+ */
852
+ add(defaults = {}) {
853
+ if (!this.hasEditor || this.newRow !== void 0 || this.editing.mode === "single" && this.sessions.size > 0) return false;
854
+ const newRow = new NewRow(defaults, {
855
+ columns: this.columns,
856
+ isVisible: (index) => this.dataTable.column(index).visible(),
857
+ withButtons: this.hasActions,
858
+ texts: this.texts,
859
+ classNames: this.classNames
860
+ });
861
+ this.tableEl.insertBefore(newRow.body, this.dataTable.table().body());
862
+ newRow.focus();
863
+ this.newRow = newRow;
864
+ return true;
865
+ }
866
+ /** Whether a new row is open. */
867
+ isAdding() {
868
+ return this.newRow !== void 0;
869
+ }
870
+ /**
871
+ * Closes the new row and throws it away. Does nothing if there's none, or
872
+ * while it's saving.
873
+ */
874
+ cancelNew() {
875
+ const newRow = this.newRow;
876
+ if (newRow === void 0 || newRow.saving) return;
877
+ newRow.destroy();
878
+ this.newRow = void 0;
879
+ }
880
+ /**
881
+ * Validates the new row, then calls `onAdd`. On success the row joins the
882
+ * table, and the table shows the page it landed on.
883
+ *
884
+ * While `onAdd` runs the row is locked. If it throws, the row stays open
885
+ * and the error message is shown under it.
886
+ *
887
+ * @returns `true` once the row is added. `false` if there's no new row, a
888
+ * field is invalid, it's already saving, or `onAdd` threw.
889
+ * @throws If the saved row has no `rowId` value.
890
+ */
891
+ async saveNew() {
892
+ const newRow = this.newRow;
893
+ if (newRow === void 0 || newRow.saving) return false;
894
+ if (!newRow.validate()) return false;
895
+ const row = newRow.getRow();
896
+ newRow.setSaving(true);
897
+ let saved = row;
898
+ try {
899
+ const result = await this.onAdd?.(row);
900
+ if (result !== void 0) saved = result;
901
+ } catch (error) {
902
+ if (this.newRow !== newRow) return false;
903
+ newRow.setSaving(false);
904
+ newRow.showError(error instanceof Error ? error.message : this.texts.addFailed);
905
+ return false;
906
+ }
907
+ if (this.newRow !== newRow) return false;
908
+ const id = this.rowId === void 0 ? void 0 : saved[this.rowId];
909
+ if (typeof id !== "string" && typeof id !== "number") {
910
+ newRow.setSaving(false);
911
+ throw new Error(`Tadabut: the added row has no "${String(this.rowId)}". Return it from onAdd.`);
912
+ }
913
+ newRow.destroy();
914
+ this.newRow = void 0;
915
+ const added = this.dataTable.row.add({ ...saved });
916
+ this.dataTable.draw(false);
917
+ const position = this.dataTable.rows({
918
+ order: "applied",
919
+ search: "applied"
920
+ }).indexes().toArray().indexOf(added.index());
921
+ const length = this.dataTable.page.len();
922
+ if (position >= 0 && length > 0) this.dataTable.page(Math.floor(position / length)).draw(false);
923
+ return true;
924
+ }
925
+ /**
926
+ * Closes a row and throws away its changes. Does nothing if the row isn't
927
+ * open, or while it's saving.
928
+ */
929
+ cancel(id) {
930
+ const session = this.sessions.get(id);
931
+ if (session === void 0) return;
932
+ if (session.saving) return;
933
+ session.destroy();
934
+ this.sessions.delete(id);
935
+ this.clearRowError(id);
936
+ this.findRow(id)?.node()?.classList.remove("tdb-row-editing");
937
+ this.findRow(id)?.invalidate("data").draw(false);
938
+ }
939
+ /** Whether a row is open for editing. */
940
+ isEditing(id) {
941
+ return this.sessions.has(id);
942
+ }
943
+ /**
944
+ * Validates the open row, then calls `onSave`.
945
+ *
946
+ * Invalid fields show their errors and `onSave` isn't called. While
947
+ * `onSave` runs the row is locked. If it throws, the row stays open and
948
+ * the error message is shown under it. The table only changes on success.
949
+ *
950
+ * @returns `true` once the row is saved and closed.
951
+ */
952
+ async save(id) {
953
+ const session = this.sessions.get(id);
954
+ if (session === void 0 || session.saving) return false;
955
+ session.clearErrors();
956
+ this.clearRowError(id);
957
+ const errors = session.validate();
958
+ const [firstInvalid] = errors.keys();
959
+ if (firstInvalid !== void 0) {
960
+ session.showErrors(errors);
961
+ session.focus(firstInvalid);
962
+ return false;
963
+ }
964
+ const row = session.getRow();
965
+ this.setSaving(id, true);
966
+ let saved = row;
967
+ try {
968
+ const result = await this.onSave?.(row, { previous: session.originalData });
969
+ if (result !== void 0) saved = result;
970
+ } catch (error) {
971
+ if (this.sessions.get(id) !== session) return false;
972
+ this.setSaving(id, false);
973
+ this.showRowError(id, error instanceof Error ? error.message : this.texts.saveFailed);
974
+ return false;
975
+ }
976
+ if (this.sessions.get(id) !== session) return false;
977
+ session.destroy();
978
+ this.sessions.delete(id);
979
+ this.findRow(id)?.data({ ...saved }).draw(false);
980
+ this.findRow(id)?.node()?.classList.remove("tdb-row-editing");
981
+ this.setSaving(id, false);
982
+ return true;
983
+ }
984
+ /**
985
+ * Calls `onDelete`, then removes the row. Never asks first: only the
986
+ * Delete button does.
987
+ *
988
+ * While `onDelete` runs the row is locked. If it throws, the row stays and
989
+ * the error message is shown under it.
990
+ *
991
+ * @returns `true` once the row is removed. `false` if the row doesn't
992
+ * exist, is open for editing, is already being deleted, or `onDelete`
993
+ * threw.
994
+ */
995
+ async delete(id) {
996
+ const row = this.findRow(id);
997
+ if (row === void 0 || this.sessions.has(id) || this.deleting.has(id)) return false;
998
+ this.clearRowError(id);
999
+ this.deleting.add(id);
1000
+ this.setSaving(id, true);
1001
+ try {
1002
+ await this.onDelete?.(row.data());
1003
+ } catch (error) {
1004
+ if (!this.deleting.has(id)) return false;
1005
+ this.deleting.delete(id);
1006
+ this.setSaving(id, false);
1007
+ this.keepRow(id);
1008
+ this.showRowError(id, error instanceof Error ? error.message : this.texts.deleteFailed);
1009
+ return false;
1010
+ }
1011
+ if (!this.deleting.has(id)) return false;
1012
+ this.deleting.delete(id);
1013
+ this.findRow(id)?.remove().draw(false);
1014
+ return true;
1015
+ }
1016
+ /** Removes the table. Open rows are closed without saving. */
1017
+ destroy() {
1018
+ this.tableEl.removeEventListener("click", this.onClick);
1019
+ this.tableEl.removeEventListener("keydown", this.onKeyDown);
1020
+ this.destroySessions();
1021
+ this.deleting.clear();
1022
+ this.dataTable.destroy();
1023
+ this.tableEl.remove();
1024
+ }
1025
+ /** The row with this id, or `undefined`. */
1026
+ findRow(id) {
1027
+ const rowId = this.rowId;
1028
+ if (rowId === void 0) return;
1029
+ const row = this.dataTable.row((_index, data) => data[rowId] === id);
1030
+ return row.any() ? row : void 0;
1031
+ }
1032
+ /**
1033
+ * Closes every open row, the new one too. Only for when the rows are about
1034
+ * to go away: cells aren't restored.
1035
+ */
1036
+ destroySessions() {
1037
+ for (const session of this.sessions.values()) session.destroy();
1038
+ this.sessions.clear();
1039
+ this.newRow?.destroy();
1040
+ this.newRow = void 0;
1041
+ }
1042
+ /** Also works after the session is gone, so a row can always be unlocked. */
1043
+ setSaving(id, saving) {
1044
+ const session = this.sessions.get(id);
1045
+ if (session !== void 0) session.saving = saving;
1046
+ const tr = this.findRow(id)?.node();
1047
+ if (tr) {
1048
+ tr.inert = saving;
1049
+ tr.classList.toggle("tdb-row-saving", saving);
1050
+ }
1051
+ }
1052
+ /** Shows a save or delete error in a child row under the row. */
1053
+ showRowError(id, message) {
1054
+ this.findRow(id)?.child(rowErrorMessage(message), "tdb-row-error").show();
1055
+ }
1056
+ /** Removes the save or delete error under a row, if any. */
1057
+ clearRowError(id) {
1058
+ this.findRow(id)?.child.remove();
1059
+ }
1060
+ /** The last cell of a row, the one with the buttons. */
1061
+ actionsCell(row) {
1062
+ return this.dataTable.cell(row.index(), this.columns.length).node();
1063
+ }
1064
+ /**
1065
+ * What the Delete button does: asks inline, asks with the user's function,
1066
+ * or deletes right away.
1067
+ */
1068
+ async askDelete(id) {
1069
+ const row = this.findRow(id);
1070
+ if (row === void 0) return;
1071
+ if (this.confirmDelete === false) {
1072
+ await this.delete(id);
1073
+ return;
1074
+ }
1075
+ if (this.confirmDelete !== void 0) {
1076
+ if (await this.confirmDelete(row.data())) await this.delete(id);
1077
+ return;
1078
+ }
1079
+ const { parts, keep } = deleteQuestion(this.texts, this.classNames);
1080
+ this.actionsCell(row).replaceChildren(...parts);
1081
+ keep.focus();
1082
+ }
1083
+ /** Puts Edit and Delete back after No. */
1084
+ keepRow(id) {
1085
+ this.findRow(id)?.invalidate("data").draw(false);
1086
+ }
1087
+ /** Whether an element is inside the new row, or its error. */
1088
+ isInNewRow(element) {
1089
+ return this.newRow?.contains(element) ?? false;
1090
+ }
1091
+ /**
1092
+ * `undefined` for rows DataTables doesn't know, like the error row or
1093
+ * a table inside a custom editor.
1094
+ */
1095
+ rowIdOf(element) {
1096
+ const tr = element.closest("tr");
1097
+ if (tr === null || this.rowId === void 0) return;
1098
+ const row = this.dataTable.row(tr);
1099
+ return row.any() ? row.data()[this.rowId] : void 0;
1100
+ }
1101
+ /**
1102
+ * Handles the action buttons, the new row's too. One listener on the
1103
+ * table, because DataTables keeps replacing rows. An arrow function, so
1104
+ * `this` stays bound and `destroy` can remove it.
1105
+ */
1106
+ onClick = (event) => {
1107
+ if (!(event.target instanceof Element)) return;
1108
+ const button = event.target.closest("[data-tdb-action]");
1109
+ if (button === null) return;
1110
+ const action = button.dataset.tdbAction;
1111
+ if (!isButtonAction(action)) return;
1112
+ if (this.isInNewRow(button)) {
1113
+ if (action === "save") this.saveNew();
1114
+ else if (action === "cancel") this.cancelNew();
1115
+ return;
1116
+ }
1117
+ const id = this.rowIdOf(button);
1118
+ if (id === void 0) return;
1119
+ switch (action) {
1120
+ case "edit":
1121
+ this.edit(id);
1122
+ break;
1123
+ case "save":
1124
+ this.save(id);
1125
+ break;
1126
+ case "cancel":
1127
+ this.cancel(id);
1128
+ break;
1129
+ case "delete":
1130
+ this.askDelete(id);
1131
+ break;
1132
+ case "keep":
1133
+ this.keepRow(id);
1134
+ break;
1135
+ case "confirm": this.delete(id);
1136
+ }
1137
+ };
1138
+ /** Enter saves, Escape cancels, in edited rows and the new row. */
1139
+ onKeyDown = (event) => {
1140
+ if (event.defaultPrevented) return;
1141
+ if (!(event.target instanceof Element) || event.target.closest("button")) return;
1142
+ if (this.isInNewRow(event.target)) {
1143
+ if (event.key === "Enter") {
1144
+ event.preventDefault();
1145
+ this.saveNew();
1146
+ } else if (event.key === "Escape") {
1147
+ event.preventDefault();
1148
+ this.cancelNew();
1149
+ }
1150
+ return;
1151
+ }
1152
+ const id = this.rowIdOf(event.target);
1153
+ if (id === void 0 || !this.sessions.has(id)) return;
1154
+ switch (event.key) {
1155
+ case "Enter":
1156
+ event.preventDefault();
1157
+ this.save(id);
1158
+ break;
1159
+ case "Escape":
1160
+ event.preventDefault();
1161
+ this.cancel(id);
1162
+ }
1163
+ };
1164
+ };
1165
+ // src/texts/fr.ts
1166
+ /** French. */
1167
+ const fr = {
1168
+ edit: "Modifier",
1169
+ save: "Enregistrer",
1170
+ cancel: "Annuler",
1171
+ delete: "Supprimer",
1172
+ deleteQuestion: "Supprimer cette ligne\xA0?",
1173
+ confirm: "Oui, supprimer",
1174
+ keep: "Non",
1175
+ deleteFailed: "Impossible de supprimer.",
1176
+ loading: "Chargement…",
1177
+ saveFailed: "Impossible d'enregistrer.",
1178
+ addFailed: "Impossible d'ajouter.",
1179
+ loadFailed: "Impossible de charger les options.",
1180
+ required: "Ce champ est obligatoire.",
1181
+ patternMismatch: "Format incorrect.",
1182
+ tooShort: (min) => `Au moins ${min} caractères.`,
1183
+ tooLong: (max) => `Au plus ${max} caractères.`,
1184
+ tooSmall: (min) => `Doit être supérieur ou égal à ${min}.`,
1185
+ tooLarge: (max) => `Doit être inférieur ou égal à ${max}.`,
1186
+ tooEarly: (min) => `Doit être le ${min} ou après.`,
1187
+ tooLate: (max) => `Doit être le ${max} ou avant.`
1188
+ };
1189
+ export { Tadabut as n, en as r, fr as t };