tadabut 0.4.0 → 0.6.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.
@@ -1,4 +1,138 @@
1
1
  import DataTable from "datatables.net";
2
+ // src/editors/date-format.ts
3
+ /** ISO, what `<input type="date">` and most servers use. */
4
+ const defaultDateFormat = "yyyy-mm-dd";
5
+ /**
6
+ * Reads a date written in `format`, and gives it as `'yyyy-mm-dd'`. A time
7
+ * after it is dropped. `null` if it isn't a real date, like `31/02/2024`.
8
+ *
9
+ * @example
10
+ * parseDate('05/01/2024', 'dd/mm/yyyy'); // '2024-01-05'
11
+ */
12
+ function parseDate(value, format) {
13
+ const { separator, order } = partsOf(format);
14
+ const [date = ""] = value.trim().split(/[T ]/);
15
+ const pieces = date.split(separator);
16
+ if (pieces.length !== 3) return null;
17
+ const yyyy = pieces[order.indexOf("yyyy")] ?? "";
18
+ const mm = pieces[order.indexOf("mm")] ?? "";
19
+ const dd = pieces[order.indexOf("dd")] ?? "";
20
+ if (!/^\d{4}$/.test(yyyy) || !/^\d{1,2}$/.test(mm) || !/^\d{1,2}$/.test(dd)) return null;
21
+ const year = Number(yyyy);
22
+ const month = Number(mm);
23
+ const day = Number(dd);
24
+ const check = new Date(Date.UTC(year, month - 1, day));
25
+ if (check.getUTCFullYear() !== year || check.getUTCMonth() !== month - 1 || check.getUTCDate() !== day) return null;
26
+ return `${yyyy}-${mm.padStart(2, "0")}-${dd.padStart(2, "0")}`;
27
+ }
28
+ /**
29
+ * Writes a `'yyyy-mm-dd'` date in `format`. Only give it dates `parseDate`
30
+ * returned: it checks nothing.
31
+ *
32
+ * @example
33
+ * formatDate('2024-01-05', 'dd.mm.yyyy'); // '05.01.2024'
34
+ */
35
+ function formatDate(iso, format) {
36
+ const [yyyy = "", mm = "", dd = ""] = iso.split("-");
37
+ const { separator, order } = partsOf(format);
38
+ const pieces = {
39
+ yyyy,
40
+ mm,
41
+ dd
42
+ };
43
+ return order.map((part) => pieces[part]).join(separator);
44
+ }
45
+ /** The separator and the order of the parts. */
46
+ function partsOf(format) {
47
+ const separator = format.match(/[^a-z]/)?.[0] ?? "-";
48
+ return {
49
+ separator,
50
+ order: format.split(separator)
51
+ };
52
+ }
53
+ // src/editors/money-format.ts
54
+ /** `12 500.00`. */
55
+ const defaultMoneyFormat = {
56
+ decimals: 2,
57
+ separator: " ",
58
+ point: "."
59
+ };
60
+ /** `12500` → `'12 500.00'`, `null` → `''`. */
61
+ function formatMoney(value, format) {
62
+ if (value === null) return "";
63
+ const fixed = value.toFixed(format.decimals);
64
+ const sign = fixed.startsWith("-") ? "-" : "";
65
+ const [whole = "", decimals = ""] = fixed.slice(sign.length).split(".");
66
+ const grouped = sign + groupThousands(whole, format.separator);
67
+ return format.decimals > 0 ? grouped + format.point + decimals : grouped;
68
+ }
69
+ /** `'12 500,5'` → `12500.5`, rounded to `decimals`. Empty or not a number → `null`. */
70
+ function parseMoney(text, format) {
71
+ let cleaned = text.replaceAll(format.separator, "").replace(/\s/g, "");
72
+ for (const mark of decimalMarks(format)) cleaned = cleaned.replaceAll(mark, ".");
73
+ if (cleaned === "") return null;
74
+ const value = Number(cleaned);
75
+ if (Number.isNaN(value)) return null;
76
+ const factor = 10 ** format.decimals;
77
+ return Math.round((value + Number.EPSILON) * factor) / factor;
78
+ }
79
+ /**
80
+ * Cleans and regroups what's being typed, without filling in the decimals.
81
+ * `'12500,5'` → `'12 500.5'`, `'12 500.'` stays, `'12.345'` → `'12.34'`.
82
+ */
83
+ function formatTyping(text, format) {
84
+ const trimmed = text.trim();
85
+ const sign = trimmed.startsWith("-") ? "-" : "";
86
+ const marks = decimalMarks(format);
87
+ const markAt = [...trimmed].findIndex((char) => marks.includes(char));
88
+ const hasMark = markAt !== -1;
89
+ const before = hasMark ? trimmed.slice(0, markAt) : trimmed;
90
+ const after = hasMark ? trimmed.slice(markAt + 1) : "";
91
+ let whole = before.replace(/\D/g, "").replace(/^0+(?=\d)/, "");
92
+ const decimals = after.replace(/\D/g, "").slice(0, format.decimals);
93
+ const hasPoint = hasMark && format.decimals > 0;
94
+ if (whole === "" && hasPoint) whole = "0";
95
+ const grouped = sign + groupThousands(whole, format.separator);
96
+ return hasPoint ? grouped + format.point + decimals : grouped;
97
+ }
98
+ /**
99
+ * Counts the characters before `end` that survive formatting: digits,
100
+ * decimal marks and the minus. Formatting adds and removes separators, which
101
+ * would move the cursor. Counting only what stays, before and after, puts it
102
+ * back in the same place.
103
+ */
104
+ function countKept(text, end, format) {
105
+ return [...text.slice(0, end)].filter((char) => isKept(char, format)).length;
106
+ }
107
+ /** The position right after the `kept`-th kept character. See `countKept`. */
108
+ function caretAt(formatted, kept, format) {
109
+ if (kept <= 0) return 0;
110
+ let seen = 0;
111
+ for (const [index, char] of [...formatted].entries()) {
112
+ if (isKept(char, format)) seen += 1;
113
+ if (seen === kept) return index + 1;
114
+ }
115
+ return formatted.length;
116
+ }
117
+ /** A digit, a decimal mark or the minus. */
118
+ function isKept(char, format) {
119
+ return /\d/.test(char) || char === "-" || decimalMarks(format).includes(char);
120
+ }
121
+ /**
122
+ * The keys accepted as a decimal point: the shown one, `.` and `,`, except
123
+ * the separator. With `separator: '.'`, only `,` is a point.
124
+ */
125
+ function decimalMarks(format) {
126
+ return [.../* @__PURE__ */ new Set([
127
+ format.point,
128
+ ".",
129
+ ","
130
+ ])].filter((mark) => mark !== format.separator);
131
+ }
132
+ /** `'12500'` → `'12 500'`. */
133
+ function groupThousands(digits, separator) {
134
+ return digits.replace(/\B(?=(\d{3})+(?!\d))/g, separator);
135
+ }
2
136
  // src/editors/classes.ts
3
137
  /**
4
138
  * `'btn btn-sm '` → `['btn', 'btn-sm']`. Empty pieces are dropped because
@@ -11,6 +145,53 @@ function splitClasses(...lists) {
11
145
  function addClasses(element, ownClasses, className) {
12
146
  element.classList.add(...ownClasses, ...splitClasses(className));
13
147
  }
148
+ // src/editors/money.ts
149
+ /** The config's format, with the defaults filled in. */
150
+ function moneyFormat(config) {
151
+ return {
152
+ decimals: config.decimals ?? defaultMoneyFormat.decimals,
153
+ separator: config.separator ?? defaultMoneyFormat.separator,
154
+ point: config.point ?? defaultMoneyFormat.point
155
+ };
156
+ }
157
+ /**
158
+ * Builds the money input. It regroups while typing, keeps the cursor in place,
159
+ * and fills in the decimals on blur.
160
+ */
161
+ function createMoneyEditor(config, context) {
162
+ const format = moneyFormat(config);
163
+ const input = document.createElement("input");
164
+ input.type = "text";
165
+ input.inputMode = "decimal";
166
+ input.autocomplete = "off";
167
+ addClasses(input, ["tdb-input", "tdb-input-money"], context.className);
168
+ /** Read from the text every time, so there's no copy to get out of sync. */
169
+ const getValue = () => parseMoney(input.value, format);
170
+ /** Shows the value fully formatted, decimals included. */
171
+ const setValue = (value) => {
172
+ input.value = formatMoney(value, format);
173
+ };
174
+ setValue(context.value);
175
+ input.addEventListener("input", () => {
176
+ const caret = input.selectionStart ?? input.value.length;
177
+ const kept = countKept(input.value, caret, format);
178
+ const next = formatTyping(input.value, format);
179
+ if (next !== input.value) {
180
+ input.value = next;
181
+ const position = caretAt(next, kept, format);
182
+ input.setSelectionRange(position, position);
183
+ }
184
+ context.onChange(getValue());
185
+ });
186
+ input.addEventListener("blur", () => setValue(getValue()));
187
+ return {
188
+ element: input,
189
+ getValue,
190
+ setValue,
191
+ focus: () => input.focus(),
192
+ destroy: () => input.remove()
193
+ };
194
+ }
14
195
  // src/columns/escape.ts
15
196
  /** Characters that mean something in HTML. */
16
197
  const entities = {
@@ -89,6 +270,18 @@ function rowErrorMessage(message) {
89
270
  error.textContent = message;
90
271
  return error;
91
272
  }
273
+ /** The header's "check all" checkbox, as HTML for the column title. */
274
+ function selectAllHtml(texts, classNames) {
275
+ return checkboxHtml("tdb-select-all", texts.selectAll, classNames);
276
+ }
277
+ /** A row's checkbox, as HTML for `defaultContent`. */
278
+ function selectRowHtml(texts, classNames) {
279
+ return checkboxHtml("tdb-select-row", texts.selectRow, classNames);
280
+ }
281
+ /** A selection checkbox as HTML, so the classes and the label are escaped. */
282
+ function checkboxHtml(kind, label, classNames) {
283
+ return `<input type="checkbox" class="${escapeHtml([kind, ...splitClasses(classNames.select)].join(" "))}" aria-label="${escapeHtml(label)}">`;
284
+ }
92
285
  // src/columns/to-datatables.ts
93
286
  /**
94
287
  * The column with the Edit and Delete buttons. While a row is open, Save and
@@ -105,12 +298,28 @@ function actionsColumn(actions, classNames, texts) {
105
298
  };
106
299
  }
107
300
  /**
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.
301
+ * The checkbox column. The checkboxes are the same HTML on every row; which
302
+ * ones are ticked is set after each draw.
110
303
  */
111
- function toDataTables(columns, actions, classNames, texts) {
304
+ function selectColumn(classNames, texts) {
305
+ return {
306
+ title: selectAllHtml(texts, classNames),
307
+ data: null,
308
+ className: "tdb-select",
309
+ orderable: false,
310
+ searchable: false,
311
+ defaultContent: selectRowHtml(texts, classNames)
312
+ };
313
+ }
314
+ /**
315
+ * The checkbox column goes first with `selection`, and the actions column
316
+ * last. Tadabut shifts your column indexes to match. No `actions` means no
317
+ * actions column.
318
+ */
319
+ function toDataTables(columns, actions, classNames, texts, selection) {
112
320
  const converted = columns.map((column) => {
113
321
  const label = labelOf(column);
322
+ const sortValue = sortValueOf(column);
114
323
  return {
115
324
  ...defined({
116
325
  width: column.width,
@@ -121,27 +330,53 @@ function toDataTables(columns, actions, classNames, texts) {
121
330
  }),
122
331
  title: column.title,
123
332
  data: column.prop,
333
+ defaultContent: "",
124
334
  render: (value, type, row) => {
125
335
  switch (type) {
126
336
  case "display": return escapeHtml(label(value, row));
127
- case "filter": return label(value, row);
128
- default: return value;
337
+ case "filter": return `${label(value, row)} ${asText(value)}`;
338
+ default: return sortValue(value);
129
339
  }
130
340
  }
131
341
  };
132
342
  });
133
- return actions.length > 0 ? [...converted, actionsColumn(actions, classNames, texts)] : converted;
343
+ const first = selection ? [selectColumn(classNames, texts)] : [];
344
+ const last = actions.length > 0 ? [actionsColumn(actions, classNames, texts)] : [];
345
+ return [
346
+ ...first,
347
+ ...converted,
348
+ ...last
349
+ ];
134
350
  }
135
- /** `render`, then `labelProp`, then a fixed list's label, then the value. */
351
+ /**
352
+ * `render`, then a money or date format, then `labelProp`, then a fixed
353
+ * list's label, then the value. A date that isn't valid shows as it is.
354
+ */
136
355
  function labelOf(column) {
137
356
  const { render, editor } = column;
138
357
  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);
358
+ switch (editor?.type) {
359
+ case "money": {
360
+ const format = moneyFormat(editor);
361
+ return (value) => typeof value === "number" ? formatMoney(value, format) : asText(value);
362
+ }
363
+ case "date": {
364
+ const format = editor.format ?? "yyyy-mm-dd";
365
+ const display = editor.display ?? format;
366
+ return (value) => {
367
+ if (typeof value !== "string") return asText(value);
368
+ const iso = parseDate(value, format);
369
+ if (iso === null) return asText(value);
370
+ return formatDate(iso, display);
371
+ };
372
+ }
373
+ case "select": {
374
+ const labelProp = editor.labelProp;
375
+ if (labelProp !== void 0) return (_value, row) => asText(row[labelProp]);
376
+ if (typeof editor.options !== "function") {
377
+ const options = editor.options;
378
+ return (value) => options.find((option) => option.value === value)?.label ?? asText(value);
379
+ }
145
380
  }
146
381
  }
147
382
  return asText;
@@ -155,6 +390,19 @@ function defined(values) {
155
390
  const kept = Object.entries(values).filter(([, value]) => value !== void 0);
156
391
  return Object.fromEntries(kept);
157
392
  }
393
+ /**
394
+ * What DataTables sorts by. Dates become `'yyyy-mm-dd'`, so `'05/01/2024'`
395
+ * sorts as January; invalid and empty dates give `''`, which sorts first.
396
+ * Anything else stays as it is: numbers stay numbers.
397
+ */
398
+ function sortValueOf(column) {
399
+ const editor = column.editor;
400
+ if (editor?.type === "date") {
401
+ const format = editor.format ?? "yyyy-mm-dd";
402
+ return (value) => typeof value === "string" ? parseDate(value, format) ?? "" : "";
403
+ }
404
+ return (value) => value;
405
+ }
158
406
  // src/texts/en.ts
159
407
  /** English, the default. */
160
408
  const en = {
@@ -166,12 +414,15 @@ const en = {
166
414
  confirm: "Yes, delete",
167
415
  keep: "No",
168
416
  deleteFailed: "Could not delete.",
417
+ total: "Total",
169
418
  loading: "Loading…",
170
419
  saveFailed: "Could not save.",
171
- loadFailed: "Could not load the options.",
172
420
  addFailed: "Could not add.",
421
+ loadFailed: "Could not load the options.",
173
422
  required: "This field is required.",
174
423
  patternMismatch: "Wrong format.",
424
+ selectRow: "Select row",
425
+ selectAll: "Select all",
175
426
  tooShort: (min) => `Must be at least ${min} characters.`,
176
427
  tooLong: (max) => `Must be at most ${max} characters.`,
177
428
  tooSmall: (min) => `Must be ${min} or more.`,
@@ -180,41 +431,54 @@ const en = {
180
431
  tooLate: (max) => `Must be on or before ${max}.`
181
432
  };
182
433
  // 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) {
434
+ /** Builds the checkbox. It keeps the row's value as it is until the user clicks it. */
435
+ function createCheckboxEditor(config, context) {
436
+ const { checked, unchecked } = config.values ?? {
437
+ checked: true,
438
+ unchecked: false
439
+ };
440
+ let current = context.value;
188
441
  const input = document.createElement("input");
189
442
  input.type = "checkbox";
190
443
  addClasses(input, ["tdb-input", "tdb-input-checkbox"], context.className);
191
- /** `null` shows as unchecked. */
444
+ /**
445
+ * Only the `checked` value ticks the box. Anything else, `null` included,
446
+ * shows unchecked but is kept.
447
+ */
192
448
  const setValue = (value) => {
193
- input.checked = value === true;
449
+ current = value;
450
+ input.checked = value === checked;
194
451
  };
195
452
  setValue(context.value);
196
- input.addEventListener("change", () => context.onChange(input.checked));
453
+ input.addEventListener("change", () => {
454
+ current = input.checked ? checked : unchecked;
455
+ context.onChange(current);
456
+ });
197
457
  return {
198
458
  element: input,
199
- getValue: () => input.checked,
459
+ getValue: () => current,
200
460
  setValue,
201
461
  focus: () => input.focus(),
202
462
  destroy: () => input.remove()
203
463
  };
204
464
  }
205
465
  // src/editors/date.ts
206
- /** Builds the date input. */
466
+ /**
467
+ * Builds the date input. The input itself always works in `'yyyy-mm-dd'`,
468
+ * whatever the computer's language, so values are converted going in and out.
469
+ */
207
470
  function createDateEditor(config, context) {
471
+ const format = config.format ?? "yyyy-mm-dd";
208
472
  const input = document.createElement("input");
209
473
  input.type = "date";
210
474
  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. */
475
+ if (config.min !== void 0) input.min = parseDate(config.min, format) ?? "";
476
+ if (config.max !== void 0) input.max = parseDate(config.max, format) ?? "";
477
+ /** Empty gives `null`. Otherwise the date in `format`. */
478
+ const getValue = () => input.value === "" ? null : formatDate(input.value, format);
479
+ /** `null`, or a value that isn't a date in `format`, shows as empty. */
216
480
  const setValue = (value) => {
217
- input.value = value ?? "";
481
+ input.value = value === null ? "" : parseDate(value, format) ?? "";
218
482
  };
219
483
  setValue(context.value ?? null);
220
484
  input.addEventListener("input", () => context.onChange(getValue()));
@@ -375,9 +639,10 @@ function createEditor(config, context, texts = en) {
375
639
  case "text": return loosen(createTextEditor(config, tighten(fullContext)));
376
640
  case "number": return loosen(createNumberEditor(config, tighten(fullContext)));
377
641
  case "date": return loosen(createDateEditor(config, tighten(fullContext)));
378
- case "checkbox": return loosen(createCheckboxEditor(config, tighten(fullContext)));
642
+ case "checkbox": return createCheckboxEditor(config, fullContext);
379
643
  case "select": return createSelectEditor(config, fullContext, texts);
380
644
  case "custom": return config.create(fullContext);
645
+ case "money": return loosen(createMoneyEditor(config, tighten(fullContext)));
381
646
  default: throw new Error(`Unknown editor: ${JSON.stringify(config)}`);
382
647
  }
383
648
  }
@@ -399,7 +664,8 @@ function validateValue(config, value, row, texts = en) {
399
664
  function builtInError(config, value, texts) {
400
665
  switch (config.type) {
401
666
  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;
667
+ case "number":
668
+ case "money": return typeof value === "number" ? rangeError(config, value, texts) : void 0;
403
669
  case "date": return typeof value === "string" ? dateError(config, value, texts) : void 0;
404
670
  case "checkbox":
405
671
  case "select":
@@ -592,18 +858,32 @@ var EditSession = class {
592
858
  *
593
859
  * @throws If a column has an `editor` and there's no `rowId`.
594
860
  * @throws If `onDelete` is set and there's no `rowId`.
861
+ * @throws If `selection` is on and there's no `rowId`.
595
862
  * @throws If a hidden column (`visible: false`) has an `editor`.
596
863
  * @throws If a select's `labelProp` is its own column.
864
+ * @throws If a money editor's `separator` and `point` are the same.
865
+ * @throws If a date editor's `min` or `max` isn't a real date in its `format`.
597
866
  */
598
867
  function checkOptions(options) {
599
868
  if (options.rowId === void 0) {
600
869
  if (options.columns.some((column) => column.editor !== void 0)) throw new Error("Tadabut: rowId is required when a column has an editor.");
601
870
  if (options.onDelete !== void 0) throw new Error("Tadabut: rowId is required with onDelete.");
871
+ if (options.selection) throw new Error("Tadabut: rowId is required with selection.");
602
872
  }
603
873
  const hiddenEditable = options.columns.find((column) => column.editor !== void 0 && column.visible === false);
604
874
  if (hiddenEditable !== void 0) throw new Error(`Tadabut: the "${hiddenEditable.prop}" column can't have both an editor and visible: false.`);
605
875
  const selfLabeled = options.columns.find((column) => column.editor?.type === "select" && column.editor.labelProp === column.prop);
606
876
  if (selfLabeled !== void 0) throw new Error(`Tadabut: the "${selfLabeled.prop}" column's labelProp can't be "${selfLabeled.prop}" itself.`);
877
+ for (const column of options.columns) {
878
+ if (column.editor?.type !== "money") continue;
879
+ const { separator, point } = moneyFormat(column.editor);
880
+ if (separator === point) throw new Error(`Tadabut: the "${column.prop}" column's money separator and point can't both be "${point}".`);
881
+ }
882
+ for (const column of options.columns) {
883
+ if (column.editor?.type !== "date") continue;
884
+ const format = column.editor.format ?? "yyyy-mm-dd";
885
+ for (const limit of [column.editor.min, column.editor.max]) if (limit !== void 0 && parseDate(limit, format) === null) throw new Error(`Tadabut: the "${column.prop}" column's date "${limit}" isn't a real date written as ${format}.`);
886
+ }
607
887
  }
608
888
  // src/table/new-row.ts
609
889
  /**
@@ -626,6 +906,7 @@ var NewRow = class {
626
906
  this.body.classList.add("tdb-new-rows");
627
907
  this.tr = document.createElement("tr");
628
908
  this.tr.classList.add("tdb-row-new", "tdb-row-editing");
909
+ for (let index = 0; index < options.leadingCells; index++) this.tr.append(document.createElement("td"));
629
910
  const cells = [];
630
911
  options.columns.forEach((column, index) => {
631
912
  if (!options.isVisible(index)) return;
@@ -645,7 +926,9 @@ var NewRow = class {
645
926
  this.tr.append(actionsCell);
646
927
  }
647
928
  this.body.append(this.tr);
648
- this.session = new EditSession(defaults, cells, options.texts);
929
+ const start = { ...defaults };
930
+ for (const { column } of cells) start[column.prop] ??= null;
931
+ this.session = new EditSession(start, cells, options.texts);
649
932
  this.firstProp = cells[0]?.column.prop;
650
933
  }
651
934
  /** Whether `onAdd` is running. */
@@ -710,6 +993,176 @@ var NewRow = class {
710
993
  this.body.remove();
711
994
  }
712
995
  };
996
+ // src/table/totals.ts
997
+ /**
998
+ * An empty footer, one cell per column. It must be in the table before
999
+ * DataTables starts, or DataTables won't manage it.
1000
+ */
1001
+ function footerFor(cellCount) {
1002
+ const tfoot = document.createElement("tfoot");
1003
+ tfoot.classList.add("tdb-totals");
1004
+ const tr = document.createElement("tr");
1005
+ for (let index = 0; index < cellCount; index++) tr.append(document.createElement("th"));
1006
+ tfoot.append(tr);
1007
+ return tfoot;
1008
+ }
1009
+ /** The DataTables filter for each `RowScope`. */
1010
+ function rowsFor(scope) {
1011
+ switch (scope) {
1012
+ case "searched": return { search: "applied" };
1013
+ case "all": return { search: "none" };
1014
+ case "page": return { page: "current" };
1015
+ }
1016
+ }
1017
+ /** The text under a column: `count` and functions as they are, numbers formatted like the cells. */
1018
+ function totalText(column, rows) {
1019
+ const { prop, total, render, editor } = column;
1020
+ if (total === void 0) return "";
1021
+ if (typeof total === "function") return total(rows);
1022
+ if (total === "count") return String(rows.length);
1023
+ const result = compute(total, rows.map((row) => row[prop]).filter((value) => typeof value === "number" && !Number.isNaN(value)));
1024
+ if (result === void 0) return "";
1025
+ if (editor?.type === "money" && render === void 0) return formatMoney(result, moneyFormat(editor));
1026
+ const rounded = Math.round(result * 100) / 100;
1027
+ return render === void 0 ? String(rounded) : render(rounded, {});
1028
+ }
1029
+ /** `undefined` when there's nothing to average, or no smallest or biggest. */
1030
+ function compute(total, values) {
1031
+ const sum = values.reduce((a, b) => a + b, 0);
1032
+ if (total === "sum") return sum;
1033
+ if (values.length === 0) return;
1034
+ switch (total) {
1035
+ case "avg": return sum / values.length;
1036
+ case "min": return Math.min(...values);
1037
+ case "max": return Math.max(...values);
1038
+ }
1039
+ }
1040
+ // src/table/selection.ts
1041
+ /**
1042
+ * Which rows are ticked. The ids are the truth; the checkboxes on the page
1043
+ * are redrawn from them after every draw, since DataTables rebuilds rows.
1044
+ */
1045
+ var Selection = class {
1046
+ /** The selected row ids. */
1047
+ ids = /* @__PURE__ */ new Set();
1048
+ /** What the selection needs from the table. */
1049
+ parts;
1050
+ /** Starts listening to the checkboxes. Nothing is ticked yet. */
1051
+ constructor(parts) {
1052
+ this.parts = parts;
1053
+ this.parts.dataTable.table().node().addEventListener("change", this.onChange);
1054
+ }
1055
+ /**
1056
+ * Ticks the checkboxes on the page to match the selection, and sets the
1057
+ * header's checkbox to all, none or some.
1058
+ */
1059
+ sync() {
1060
+ const rows = this.parts.dataTable.rows({ page: "current" });
1061
+ const data = rows.data().toArray();
1062
+ rows.nodes().toArray().forEach((node, index) => {
1063
+ const row = data[index];
1064
+ if (row === void 0) return;
1065
+ const selected = this.ids.has(this.idFor(row));
1066
+ node.classList.toggle("tdb-row-selected", selected);
1067
+ const checkbox = node.querySelector(".tdb-select-row");
1068
+ if (checkbox !== null) checkbox.checked = selected;
1069
+ });
1070
+ const all = this.parts.dataTable.table().header().querySelector(".tdb-select-all");
1071
+ if (all === null) return;
1072
+ const scope = this.scopeIds();
1073
+ const count = scope.filter((id) => this.ids.has(id)).length;
1074
+ all.checked = count > 0 && count === scope.length;
1075
+ all.indeterminate = count > 0 && count < scope.length;
1076
+ }
1077
+ /**
1078
+ * The selected rows, in the order they were added to the table. Rows the
1079
+ * search hides, or on other pages, are in it too.
1080
+ */
1081
+ selected() {
1082
+ return this.parts.dataTable.rows().data().toArray().filter((row) => this.ids.has(this.idFor(row)));
1083
+ }
1084
+ /** Whether the row with this id is selected. */
1085
+ has(id) {
1086
+ return this.ids.has(id);
1087
+ }
1088
+ /**
1089
+ * Selects or unselects rows. Ids of rows that aren't in the table are
1090
+ * skipped. `onSelect` is only called if something changed.
1091
+ */
1092
+ set(ids, selected) {
1093
+ const before = this.ids.size;
1094
+ if (selected) {
1095
+ const existing = this.allIds();
1096
+ for (const id of ids) if (existing.has(id)) this.ids.add(id);
1097
+ } else for (const id of ids) this.ids.delete(id);
1098
+ if (this.ids.size !== before) {
1099
+ this.sync();
1100
+ this.changed();
1101
+ }
1102
+ }
1103
+ /** Unselects every row. */
1104
+ clear() {
1105
+ if (this.ids.size === 0) return;
1106
+ this.ids.clear();
1107
+ this.sync();
1108
+ this.changed();
1109
+ }
1110
+ /** Forgets the ids of rows that left the table, after `setData` or a delete. */
1111
+ prune() {
1112
+ const existing = this.allIds();
1113
+ const before = this.ids.size;
1114
+ for (const id of this.ids) if (!existing.has(id)) this.ids.delete(id);
1115
+ if (this.ids.size !== before) {
1116
+ this.sync();
1117
+ this.changed();
1118
+ }
1119
+ }
1120
+ /** Stops listening to the checkboxes. */
1121
+ destroy() {
1122
+ this.parts.dataTable.table().node().removeEventListener("change", this.onChange);
1123
+ }
1124
+ /** Tells the user the selection changed. */
1125
+ changed() {
1126
+ this.parts.onSelect?.(this.selected());
1127
+ }
1128
+ /** The id of a row. */
1129
+ idFor(row) {
1130
+ return row[this.parts.rowId];
1131
+ }
1132
+ /** The ids of every row in the table. */
1133
+ allIds() {
1134
+ return new Set(this.parts.dataTable.rows().data().toArray().map((row) => this.idFor(row)));
1135
+ }
1136
+ /** The id of the row an element is in, or `undefined` outside DataTables' rows. */
1137
+ idOf(element) {
1138
+ const tr = element.closest("tr");
1139
+ if (tr === null) return;
1140
+ const row = this.parts.dataTable.row(tr);
1141
+ return row.any() ? this.idFor(row.data()) : void 0;
1142
+ }
1143
+ /** The ids of the rows in `scope`. */
1144
+ scopeIds() {
1145
+ return this.parts.dataTable.rows(rowsFor(this.parts.scope)).data().toArray().map((row) => this.idFor(row));
1146
+ }
1147
+ /**
1148
+ * A row's checkbox or the header's was clicked. An arrow function, so
1149
+ * `destroy` can remove it.
1150
+ */
1151
+ onChange = (event) => {
1152
+ const target = event.target;
1153
+ if (!(target instanceof HTMLInputElement)) return;
1154
+ if (target.classList.contains("tdb-select-row")) {
1155
+ const id = this.idOf(target);
1156
+ if (id === void 0) return;
1157
+ if (target.checked) this.ids.add(id);
1158
+ else this.ids.delete(id);
1159
+ } else if (target.classList.contains("tdb-select-all")) for (const id of this.scopeIds()) if (target.checked) this.ids.add(id);
1160
+ else this.ids.delete(id);
1161
+ else return;
1162
+ this.sync();
1163
+ this.changed();
1164
+ };
1165
+ };
713
1166
  // src/table/tadabut.ts
714
1167
  /**
715
1168
  * A DataTables table with row editing.
@@ -759,13 +1212,36 @@ var Tadabut = class {
759
1212
  deleting = /* @__PURE__ */ new Set();
760
1213
  /** The row `add()` opened, if any. */
761
1214
  newRow;
1215
+ /** Whether any column has a `total`, so the table has a footer. */
1216
+ hasTotals;
1217
+ /** Which rows the totals count, with its default filled in. */
1218
+ totalRows;
1219
+ /** How many columns Tadabut adds before yours: 1 with `selection`. */
1220
+ offset;
1221
+ /** The ticked rows. Only with `selection`. */
1222
+ selection;
1223
+ /** Asked before a row opens. */
1224
+ onEditStart;
1225
+ /** The user's after-save callback. */
1226
+ onSaved;
1227
+ /** The user's after-add callback. */
1228
+ onAdded;
1229
+ /** The user's after-delete callback. */
1230
+ onDeleted;
1231
+ /** The user's row click callback. */
1232
+ onRowClick;
1233
+ /** The user's row double click callback. */
1234
+ onRowDoubleClick;
762
1235
  /**
763
1236
  * Builds the table inside `container`, which should be empty.
764
1237
  *
765
1238
  * @throws If a column has an `editor` and there's no `rowId`.
766
1239
  * @throws If `onDelete` is set and there's no `rowId`.
1240
+ * @throws If `selection` is on and there's no `rowId`.
767
1241
  * @throws If a hidden column (`visible: false`) has an `editor`.
768
1242
  * @throws If a select's `labelProp` is its own column.
1243
+ * @throws If a money editor's `separator` and `point` are the same.
1244
+ * @throws If a date editor's `min` or `max` isn't a real date in its `format`.
769
1245
  */
770
1246
  constructor(container, options) {
771
1247
  checkOptions(options);
@@ -774,7 +1250,8 @@ var Tadabut = class {
774
1250
  this.columns = options.columns;
775
1251
  this.editing = {
776
1252
  mode: options.editing?.mode ?? "single",
777
- button: options.editing?.button ?? true
1253
+ button: options.editing?.button ?? true,
1254
+ doubleClick: options.editing?.doubleClick ?? false
778
1255
  };
779
1256
  const actions = [];
780
1257
  if (this.hasEditor && this.editing.button) actions.push("edit");
@@ -783,22 +1260,49 @@ var Tadabut = class {
783
1260
  this.onSave = options.onSave;
784
1261
  this.onAdd = options.onAdd;
785
1262
  this.onDelete = options.onDelete;
1263
+ this.onEditStart = options.onEditStart;
1264
+ this.onSaved = options.onSaved;
1265
+ this.onAdded = options.onAdded;
1266
+ this.onDeleted = options.onDeleted;
1267
+ this.onRowClick = options.onRowClick;
1268
+ this.onRowDoubleClick = options.onRowDoubleClick;
786
1269
  this.confirmDelete = options.confirmDelete;
787
1270
  this.classNames = options.classNames ?? {};
788
1271
  this.texts = {
789
1272
  ...en,
790
1273
  ...options.texts
791
1274
  };
1275
+ this.hasTotals = options.columns.some((column) => column.total !== void 0);
1276
+ this.totalRows = options.totalRows ?? "searched";
1277
+ this.offset = options.selection ? 1 : 0;
792
1278
  this.tableEl = document.createElement("table");
793
1279
  addClasses(this.tableEl, [], this.classNames.table);
794
1280
  container.appendChild(this.tableEl);
1281
+ if (this.hasTotals) this.tableEl.append(footerFor(this.offset + this.columns.length + (this.hasActions ? 1 : 0)));
795
1282
  this.dataTable = new DataTable(this.tableEl, {
796
1283
  ...options.dataTables,
1284
+ ...this.offset > 0 && { order: shiftOrder(options.dataTables?.order, this.offset) },
797
1285
  data: [...options.data],
798
- columns: toDataTables(options.columns, actions, this.classNames, this.texts)
1286
+ columns: toDataTables(options.columns, actions, this.classNames, this.texts, this.offset > 0)
799
1287
  });
1288
+ if (this.offset > 0) {
1289
+ this.selection = new Selection({
1290
+ dataTable: this.dataTable,
1291
+ rowId: this.rowId,
1292
+ scope: typeof options.selection === "object" ? options.selection.checkAll ?? "searched" : "searched",
1293
+ onSelect: options.onSelect
1294
+ });
1295
+ this.dataTable.on("draw", () => this.selection?.sync());
1296
+ this.selection.sync();
1297
+ }
1298
+ if (this.hasTotals) {
1299
+ this.dataTable.on("draw", this.updateTotals);
1300
+ this.updateTotals();
1301
+ }
800
1302
  if (this.hasActions) this.tableEl.addEventListener("click", this.onClick);
801
1303
  if (this.hasEditor) this.tableEl.addEventListener("keydown", this.onKeyDown);
1304
+ this.tableEl.addEventListener("click", this.onRowEvent);
1305
+ this.tableEl.addEventListener("dblclick", this.onRowEvent);
802
1306
  }
803
1307
  /**
804
1308
  * Replaces all rows. Sorting, search and the page are kept.
@@ -810,6 +1314,7 @@ var Tadabut = class {
810
1314
  this.destroySessions();
811
1315
  this.deleting.clear();
812
1316
  this.dataTable.clear().rows.add([...rows]).draw(false);
1317
+ this.selection?.prune();
813
1318
  }
814
1319
  /**
815
1320
  * Opens a row for editing.
@@ -817,17 +1322,19 @@ var Tadabut = class {
817
1322
  * @param id The value of the row's `rowId` field.
818
1323
  * @returns `false` if the row doesn't exist, is already open, another row
819
1324
  * 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.
1325
+ * is being deleted, it's on a page that hasn't been displayed yet, or
1326
+ * `onEditStart` returned `false`.
821
1327
  */
822
1328
  edit(id) {
823
1329
  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
1330
  const row = this.findRow(id);
825
1331
  if (row === void 0 || row.node() === null) return false;
1332
+ if (this.onEditStart?.(row.data()) === false) return false;
826
1333
  const rowIndex = row.index();
827
1334
  const cells = [];
828
1335
  this.columns.forEach((column, columnIndex) => {
829
1336
  if (column.editor !== void 0) {
830
- const cell = this.dataTable.cell(rowIndex, columnIndex).node();
1337
+ const cell = this.dataTable.cell(rowIndex, this.dtIndex(columnIndex)).node();
831
1338
  cells.push({
832
1339
  column,
833
1340
  cell
@@ -853,10 +1360,11 @@ var Tadabut = class {
853
1360
  if (!this.hasEditor || this.newRow !== void 0 || this.editing.mode === "single" && this.sessions.size > 0) return false;
854
1361
  const newRow = new NewRow(defaults, {
855
1362
  columns: this.columns,
856
- isVisible: (index) => this.dataTable.column(index).visible(),
1363
+ isVisible: (index) => this.dataTable.column(this.dtIndex(index)).visible(),
857
1364
  withButtons: this.hasActions,
858
1365
  texts: this.texts,
859
- classNames: this.classNames
1366
+ classNames: this.classNames,
1367
+ leadingCells: this.offset
860
1368
  });
861
1369
  this.tableEl.insertBefore(newRow.body, this.dataTable.table().body());
862
1370
  newRow.focus();
@@ -868,6 +1376,35 @@ var Tadabut = class {
868
1376
  return this.newRow !== void 0;
869
1377
  }
870
1378
  /**
1379
+ * The selected rows, in the order they were added. Rows the search hides,
1380
+ * or on other pages, are in it too. Always `[]` without `selection`.
1381
+ */
1382
+ getSelected() {
1383
+ return this.selection?.selected() ?? [];
1384
+ }
1385
+ /** Whether a row is selected. Always `false` without `selection`. */
1386
+ isSelected(id) {
1387
+ return this.selection?.has(id) ?? false;
1388
+ }
1389
+ /**
1390
+ * Selects rows by id. Ids not in the table are skipped. Does nothing
1391
+ * without `selection`.
1392
+ *
1393
+ * @example
1394
+ * table.select([1, 2]);
1395
+ */
1396
+ select(ids) {
1397
+ this.selection?.set(ids, true);
1398
+ }
1399
+ /** Unselects rows by id. Does nothing without `selection`. */
1400
+ deselect(ids) {
1401
+ this.selection?.set(ids, false);
1402
+ }
1403
+ /** Unselects every row. Does nothing without `selection`. */
1404
+ clearSelection() {
1405
+ this.selection?.clear();
1406
+ }
1407
+ /**
871
1408
  * Closes the new row and throws it away. Does nothing if there's none, or
872
1409
  * while it's saving.
873
1410
  */
@@ -920,6 +1457,7 @@ var Tadabut = class {
920
1457
  }).indexes().toArray().indexOf(added.index());
921
1458
  const length = this.dataTable.page.len();
922
1459
  if (position >= 0 && length > 0) this.dataTable.page(Math.floor(position / length)).draw(false);
1460
+ this.onAdded?.(added.data());
923
1461
  return true;
924
1462
  }
925
1463
  /**
@@ -979,6 +1517,7 @@ var Tadabut = class {
979
1517
  this.findRow(id)?.data({ ...saved }).draw(false);
980
1518
  this.findRow(id)?.node()?.classList.remove("tdb-row-editing");
981
1519
  this.setSaving(id, false);
1520
+ this.onSaved?.(saved, { previous: session.originalData });
982
1521
  return true;
983
1522
  }
984
1523
  /**
@@ -995,11 +1534,12 @@ var Tadabut = class {
995
1534
  async delete(id) {
996
1535
  const row = this.findRow(id);
997
1536
  if (row === void 0 || this.sessions.has(id) || this.deleting.has(id)) return false;
1537
+ const data = row.data();
998
1538
  this.clearRowError(id);
999
1539
  this.deleting.add(id);
1000
1540
  this.setSaving(id, true);
1001
1541
  try {
1002
- await this.onDelete?.(row.data());
1542
+ await this.onDelete?.(data);
1003
1543
  } catch (error) {
1004
1544
  if (!this.deleting.has(id)) return false;
1005
1545
  this.deleting.delete(id);
@@ -1011,14 +1551,19 @@ var Tadabut = class {
1011
1551
  if (!this.deleting.has(id)) return false;
1012
1552
  this.deleting.delete(id);
1013
1553
  this.findRow(id)?.remove().draw(false);
1554
+ this.selection?.prune();
1555
+ this.onDeleted?.(data);
1014
1556
  return true;
1015
1557
  }
1016
1558
  /** Removes the table. Open rows are closed without saving. */
1017
1559
  destroy() {
1018
1560
  this.tableEl.removeEventListener("click", this.onClick);
1019
1561
  this.tableEl.removeEventListener("keydown", this.onKeyDown);
1562
+ this.tableEl.removeEventListener("click", this.onRowEvent);
1563
+ this.tableEl.removeEventListener("dblclick", this.onRowEvent);
1020
1564
  this.destroySessions();
1021
1565
  this.deleting.clear();
1566
+ this.selection?.destroy();
1022
1567
  this.dataTable.destroy();
1023
1568
  this.tableEl.remove();
1024
1569
  }
@@ -1059,7 +1604,7 @@ var Tadabut = class {
1059
1604
  }
1060
1605
  /** The last cell of a row, the one with the buttons. */
1061
1606
  actionsCell(row) {
1062
- return this.dataTable.cell(row.index(), this.columns.length).node();
1607
+ return this.dataTable.cell(row.index(), this.dtIndex(this.columns.length)).node();
1063
1608
  }
1064
1609
  /**
1065
1610
  * What the Delete button does: asks inline, asks with the user's function,
@@ -1161,7 +1706,64 @@ var Tadabut = class {
1161
1706
  this.cancel(id);
1162
1707
  }
1163
1708
  };
1709
+ /**
1710
+ * Writes every total. Runs after each redraw: search, paging, save, add,
1711
+ * delete and `setData` all redraw.
1712
+ */
1713
+ updateTotals = () => {
1714
+ const rows = this.dataTable.rows(rowsFor(this.totalRows)).data().toArray();
1715
+ this.columns.forEach((column, index) => {
1716
+ const cell = this.dataTable.column(this.dtIndex(index)).footer();
1717
+ if (column.total !== void 0) cell.textContent = totalText(column, rows);
1718
+ else if (index === 0) cell.textContent = this.texts.total;
1719
+ });
1720
+ };
1721
+ /** Your column's index as DataTables counts it. */
1722
+ dtIndex(index) {
1723
+ return index + this.offset;
1724
+ }
1725
+ /**
1726
+ * The row a click landed on, or `undefined` if it doesn't count: buttons,
1727
+ * inputs, links, the checkbox and buttons cells, the new row, a row being
1728
+ * edited, the header, the footer and error lines.
1729
+ */
1730
+ clickedRow(event) {
1731
+ const target = event.target;
1732
+ if (!(target instanceof Element)) return;
1733
+ if (target.closest("button, input, select, textarea, label, a") !== null) return;
1734
+ if (target.closest("td.tdb-select, td.tdb-actions") !== null) return;
1735
+ if (this.isInNewRow(target)) return;
1736
+ const tr = target.closest("tr");
1737
+ if (tr === null || tr.classList.contains("tdb-row-editing")) return;
1738
+ const row = this.dataTable.row(tr);
1739
+ return row.any() && row.node() === tr ? row : void 0;
1740
+ }
1741
+ /**
1742
+ * Row clicks and double clicks. A double click also opens the row with
1743
+ * `editing.doubleClick`. An arrow function, so `destroy` can remove it.
1744
+ */
1745
+ onRowEvent = (event) => {
1746
+ const row = this.clickedRow(event);
1747
+ if (row === void 0) return;
1748
+ if (event.type === "click") {
1749
+ this.onRowClick?.(row.data(), event);
1750
+ return;
1751
+ }
1752
+ if (this.editing.doubleClick && this.rowId !== void 0) this.edit(row.data()[this.rowId]);
1753
+ this.onRowDoubleClick?.(row.data(), event);
1754
+ };
1164
1755
  };
1756
+ /**
1757
+ * DataTables counts the checkbox column too, so `[[1, 'asc']]` from you means
1758
+ * its column 2. Moves each `[index, direction]` along; the default sorts by
1759
+ * your first column, as without selection. Other shapes of `order` are rare
1760
+ * and left as they are.
1761
+ */
1762
+ function shiftOrder(order, offset) {
1763
+ if (order === void 0) return [[offset, "asc"]];
1764
+ if (!Array.isArray(order)) return order;
1765
+ return order.map((entry) => Array.isArray(entry) && typeof entry[0] === "number" ? [entry[0] + offset, entry[1]] : entry);
1766
+ }
1165
1767
  // src/texts/fr.ts
1166
1768
  /** French. */
1167
1769
  const fr = {
@@ -1173,12 +1775,15 @@ const fr = {
1173
1775
  confirm: "Oui, supprimer",
1174
1776
  keep: "Non",
1175
1777
  deleteFailed: "Impossible de supprimer.",
1778
+ total: "Total",
1176
1779
  loading: "Chargement…",
1177
1780
  saveFailed: "Impossible d'enregistrer.",
1178
1781
  addFailed: "Impossible d'ajouter.",
1179
1782
  loadFailed: "Impossible de charger les options.",
1180
1783
  required: "Ce champ est obligatoire.",
1181
1784
  patternMismatch: "Format incorrect.",
1785
+ selectRow: "Sélectionner la ligne",
1786
+ selectAll: "Tout sélectionner",
1182
1787
  tooShort: (min) => `Au moins ${min} caractères.`,
1183
1788
  tooLong: (max) => `Au plus ${max} caractères.`,
1184
1789
  tooSmall: (min) => `Doit être supérieur ou égal à ${min}.`,
@@ -1186,4 +1791,4 @@ const fr = {
1186
1791
  tooEarly: (min) => `Doit être le ${min} ou après.`,
1187
1792
  tooLate: (max) => `Doit être le ${max} ou avant.`
1188
1793
  };
1189
- export { Tadabut as n, en as r, fr as t };
1794
+ export { formatMoney as a, parseDate as c, defaultMoneyFormat as i, Tadabut as n, defaultDateFormat as o, en as r, formatDate as s, fr as t };