tadabut 0.5.0 → 0.7.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,113 @@
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/time-format.ts
54
+ /**
55
+ * Reads `'h:mm'`, `'hh:mm'` or `'hh:mm:ss'`, and gives `'hh:mm:ss'`. Anything
56
+ * after is ignored, like `'.000Z'`. `null` if it isn't a real time.
57
+ *
58
+ * @example
59
+ * parseTime('9:05'); // '09:05:00'
60
+ */
61
+ function parseTime(value) {
62
+ const match = value.trim().match(/^(\d{1,2}):(\d{2})(?::(\d{2}))?/);
63
+ if (match === null) return null;
64
+ const [, hh = "", mm = "", ss = "00"] = match;
65
+ if (Number(hh) > 23 || Number(mm) > 59 || Number(ss) > 59) return null;
66
+ return `${hh.padStart(2, "0")}:${mm}:${ss}`;
67
+ }
68
+ /**
69
+ * Writes a time `parseTime` returned, with or without the seconds.
70
+ *
71
+ * @example
72
+ * formatTime('09:05:00', false); // '09:05'
73
+ */
74
+ function formatTime(time, seconds) {
75
+ return seconds ? time : time.slice(0, 5);
76
+ }
77
+ // src/editors/datetime-format.ts
78
+ /**
79
+ * Reads a date in `format`, then a time after a `T` or a space, and gives
80
+ * `'yyyy-mm-ddThh:mm:ss'`. No time means midnight. A time zone is ignored,
81
+ * not converted. `null` if the date or the time isn't real.
82
+ *
83
+ * @example
84
+ * parseDateTime('05/01/2024 14:30', 'dd/mm/yyyy'); // '2024-01-05T14:30:00'
85
+ */
86
+ function parseDateTime(value, format) {
87
+ const text = value.trim();
88
+ const at = text.search(/[T ]/);
89
+ const date = parseDate(at === -1 ? text : text.slice(0, at), format);
90
+ const time = parseTime(at === -1 ? "00:00" : text.slice(at + 1));
91
+ return date === null || time === null ? null : `${date}T${time}`;
92
+ }
93
+ /**
94
+ * Writes a date-time `parseDateTime` returned. `separator` goes between the
95
+ * date and the time.
96
+ *
97
+ * @example
98
+ * formatDateTime('2024-01-05T14:30:00', 'dd/mm/yyyy', false, ' '); // '05/01/2024 14:30'
99
+ */
100
+ function formatDateTime(value, format, seconds, separator) {
101
+ const [date = "", time = ""] = value.split("T");
102
+ return `${formatDate(date, format)}${separator}${formatTime(time, seconds)}`;
103
+ }
104
+ /**
105
+ * What goes between the date and the time in the rows: `T` for ISO, as
106
+ * servers send it, a space otherwise.
107
+ */
108
+ function dataSeparator(format) {
109
+ return format === "yyyy-mm-dd" ? "T" : " ";
110
+ }
2
111
  // src/editors/money-format.ts
3
112
  /** `12 500.00`. */
4
113
  const defaultMoneyFormat = {
@@ -113,6 +222,7 @@ function createMoneyEditor(config, context) {
113
222
  input.type = "text";
114
223
  input.inputMode = "decimal";
115
224
  input.autocomplete = "off";
225
+ input.disabled = context.readOnly ?? false;
116
226
  addClasses(input, ["tdb-input", "tdb-input-money"], context.className);
117
227
  /** Read from the text every time, so there's no copy to get out of sync. */
118
228
  const getValue = () => parseMoney(input.value, format);
@@ -162,7 +272,8 @@ const buttonActions = /* @__PURE__ */ new Set([
162
272
  "save",
163
273
  "cancel",
164
274
  "confirm",
165
- "keep"
275
+ "keep",
276
+ "detail"
166
277
  ]);
167
278
  /** Whether a `data-tdb-action` is one of ours. */
168
279
  function isButtonAction(value) {
@@ -219,6 +330,22 @@ function rowErrorMessage(message) {
219
330
  error.textContent = message;
220
331
  return error;
221
332
  }
333
+ /** The header's "check all" checkbox, as HTML for the column title. */
334
+ function selectAllHtml(texts, classNames) {
335
+ return checkboxHtml("tdb-select-all", texts.selectAll, classNames);
336
+ }
337
+ /** A row's checkbox, as HTML for `defaultContent`. */
338
+ function selectRowHtml(texts, classNames) {
339
+ return checkboxHtml("tdb-select-row", texts.selectRow, classNames);
340
+ }
341
+ /** A selection checkbox as HTML, so the classes and the label are escaped. */
342
+ function checkboxHtml(kind, label, classNames) {
343
+ return `<input type="checkbox" class="${escapeHtml([kind, ...splitClasses(classNames.select)].join(" "))}" aria-label="${escapeHtml(label)}">`;
344
+ }
345
+ /** The ▸ button that opens a row's detail, as HTML for `defaultContent`. Starts closed. */
346
+ function detailToggleHtml(texts, classNames) {
347
+ return `<button type="button" class="${escapeHtml(["tdb-detail-toggle", ...splitClasses(classNames.detail)].join(" "))}" data-tdb-action="detail" aria-expanded="false" aria-label="${escapeHtml(texts.showDetail)}">▸</button>`;
348
+ }
222
349
  // src/columns/to-datatables.ts
223
350
  /**
224
351
  * The column with the Edit and Delete buttons. While a row is open, Save and
@@ -235,12 +362,39 @@ function actionsColumn(actions, classNames, texts) {
235
362
  };
236
363
  }
237
364
  /**
238
- * The actions column is always appended last, because the rest of Tadabut
239
- * finds cells by the user's column index. No `actions` means no column.
365
+ * The checkbox column. The checkboxes are the same HTML on every row; which
366
+ * ones are ticked is set after each draw.
367
+ */
368
+ function selectColumn(classNames, texts) {
369
+ return {
370
+ title: selectAllHtml(texts, classNames),
371
+ data: null,
372
+ className: "tdb-select",
373
+ orderable: false,
374
+ searchable: false,
375
+ defaultContent: selectRowHtml(texts, classNames)
376
+ };
377
+ }
378
+ /** The column with the ▸ button. Which ones are open is set after each draw. */
379
+ function detailColumn(classNames, texts) {
380
+ return {
381
+ title: "",
382
+ data: null,
383
+ className: "tdb-detail",
384
+ orderable: false,
385
+ searchable: false,
386
+ defaultContent: detailToggleHtml(texts, classNames)
387
+ };
388
+ }
389
+ /**
390
+ * The checkbox column goes first with `selection`, then the ▸ column with
391
+ * `detail`, and the actions column last. Tadabut shifts your column indexes
392
+ * to match. No `actions` means no actions column.
240
393
  */
241
- function toDataTables(columns, actions, classNames, texts) {
394
+ function toDataTables(columns, actions, classNames, texts, leading) {
242
395
  const converted = columns.map((column) => {
243
396
  const label = labelOf(column);
397
+ const sortValue = sortValueOf(column);
244
398
  return {
245
399
  ...defined({
246
400
  width: column.width,
@@ -256,27 +410,67 @@ function toDataTables(columns, actions, classNames, texts) {
256
410
  switch (type) {
257
411
  case "display": return escapeHtml(label(value, row));
258
412
  case "filter": return `${label(value, row)} ${asText(value)}`;
259
- default: return value;
413
+ default: return sortValue(value);
260
414
  }
261
415
  }
262
416
  };
263
417
  });
264
- return actions.length > 0 ? [...converted, actionsColumn(actions, classNames, texts)] : converted;
418
+ const first = [...leading.selection ? [selectColumn(classNames, texts)] : [], ...leading.detail ? [detailColumn(classNames, texts)] : []];
419
+ const last = actions.length > 0 ? [actionsColumn(actions, classNames, texts)] : [];
420
+ return [
421
+ ...first,
422
+ ...converted,
423
+ ...last
424
+ ];
265
425
  }
266
- /** `render`, then a money format, then `labelProp`, then a fixed list's label, then the value. */
426
+ /**
427
+ * `render`, then a money, date or time format, then `labelProp`, then a fixed
428
+ * list's label, then the value. A date or time that isn't valid shows as it
429
+ * is.
430
+ */
267
431
  function labelOf(column) {
268
432
  const { render, editor } = column;
269
433
  if (render !== void 0) return render;
270
- if (editor?.type === "money") {
271
- const format = moneyFormat(editor);
272
- return (value) => typeof value === "number" ? formatMoney(value, format) : asText(value);
273
- }
274
- if (editor?.type === "select") {
275
- const labelProp = editor.labelProp;
276
- if (labelProp !== void 0) return (_value, row) => asText(row[labelProp]);
277
- if (typeof editor.options !== "function") {
278
- const options = editor.options;
279
- return (value) => options.find((option) => option.value === value)?.label ?? asText(value);
434
+ switch (editor?.type) {
435
+ case "money": {
436
+ const format = moneyFormat(editor);
437
+ return (value) => typeof value === "number" ? formatMoney(value, format) : asText(value);
438
+ }
439
+ case "date": {
440
+ const format = editor.format ?? "yyyy-mm-dd";
441
+ const display = editor.display ?? format;
442
+ return (value) => {
443
+ if (typeof value !== "string") return asText(value);
444
+ const iso = parseDate(value, format);
445
+ if (iso === null) return asText(value);
446
+ return formatDate(iso, display);
447
+ };
448
+ }
449
+ case "time": {
450
+ const seconds = editor.seconds ?? false;
451
+ return (value) => {
452
+ if (typeof value !== "string") return asText(value);
453
+ const time = parseTime(value);
454
+ return time === null ? asText(value) : formatTime(time, seconds);
455
+ };
456
+ }
457
+ case "datetime": {
458
+ const format = editor.format ?? "yyyy-mm-dd";
459
+ const display = editor.display ?? format;
460
+ const seconds = editor.seconds ?? false;
461
+ return (value) => {
462
+ if (typeof value !== "string") return asText(value);
463
+ const dateTime = parseDateTime(value, format);
464
+ return dateTime === null ? asText(value) : formatDateTime(dateTime, display, seconds, " ");
465
+ };
466
+ }
467
+ case "select": {
468
+ const labelProp = editor.labelProp;
469
+ if (labelProp !== void 0) return (_value, row) => asText(row[labelProp]);
470
+ if (typeof editor.options !== "function") {
471
+ const options = editor.options;
472
+ return (value) => options.find((option) => option.value === value)?.label ?? asText(value);
473
+ }
280
474
  }
281
475
  }
282
476
  return asText;
@@ -290,6 +484,25 @@ function defined(values) {
290
484
  const kept = Object.entries(values).filter(([, value]) => value !== void 0);
291
485
  return Object.fromEntries(kept);
292
486
  }
487
+ /**
488
+ * What DataTables sorts by. Dates become `'yyyy-mm-dd'`, so `'05/01/2024'`
489
+ * sorts as January, times `'hh:mm:ss'`, and both `'yyyy-mm-ddThh:mm:ss'`.
490
+ * Invalid and empty ones give `''`, which sorts first. Anything else stays as
491
+ * it is: numbers stay numbers.
492
+ */
493
+ function sortValueOf(column) {
494
+ const editor = column.editor;
495
+ if (editor?.type === "date") {
496
+ const format = editor.format ?? "yyyy-mm-dd";
497
+ return (value) => typeof value === "string" ? parseDate(value, format) ?? "" : "";
498
+ }
499
+ if (editor?.type === "time") return (value) => typeof value === "string" ? parseTime(value) ?? "" : "";
500
+ if (editor?.type === "datetime") {
501
+ const format = editor.format ?? "yyyy-mm-dd";
502
+ return (value) => typeof value === "string" ? parseDateTime(value, format) ?? "" : "";
503
+ }
504
+ return (value) => value;
505
+ }
293
506
  // src/texts/en.ts
294
507
  /** English, the default. */
295
508
  const en = {
@@ -302,6 +515,12 @@ const en = {
302
515
  keep: "No",
303
516
  deleteFailed: "Could not delete.",
304
517
  total: "Total",
518
+ selectRow: "Select row",
519
+ selectAll: "Select all",
520
+ showDetail: "Show details",
521
+ hideDetail: "Hide details",
522
+ detailLoading: "Loading…",
523
+ detailFailed: "Couldn't load the details.",
305
524
  loading: "Loading…",
306
525
  saveFailed: "Could not save.",
307
526
  addFailed: "Could not add.",
@@ -313,7 +532,9 @@ const en = {
313
532
  tooSmall: (min) => `Must be ${min} or more.`,
314
533
  tooLarge: (max) => `Must be ${max} or less.`,
315
534
  tooEarly: (min) => `Must be on or after ${min}.`,
316
- tooLate: (max) => `Must be on or before ${max}.`
535
+ tooLate: (max) => `Must be on or before ${max}.`,
536
+ timeTooEarly: (min) => `Must be at or after ${min}.`,
537
+ timeTooLate: (max) => `Must be at or before ${max}.`
317
538
  };
318
539
  // src/editors/checkbox.ts
319
540
  /** Builds the checkbox. It keeps the row's value as it is until the user clicks it. */
@@ -325,6 +546,7 @@ function createCheckboxEditor(config, context) {
325
546
  let current = context.value;
326
547
  const input = document.createElement("input");
327
548
  input.type = "checkbox";
549
+ input.disabled = context.readOnly ?? false;
328
550
  addClasses(input, ["tdb-input", "tdb-input-checkbox"], context.className);
329
551
  /**
330
552
  * Only the `checked` value ticks the box. Anything else, `null` included,
@@ -348,18 +570,61 @@ function createCheckboxEditor(config, context) {
348
570
  };
349
571
  }
350
572
  // src/editors/date.ts
351
- /** Builds the date input. */
573
+ /**
574
+ * Builds the date input. The input itself always works in `'yyyy-mm-dd'`,
575
+ * whatever the computer's language, so values are converted going in and out.
576
+ */
352
577
  function createDateEditor(config, context) {
578
+ const format = config.format ?? "yyyy-mm-dd";
353
579
  const input = document.createElement("input");
354
580
  input.type = "date";
581
+ input.disabled = context.readOnly ?? false;
355
582
  addClasses(input, ["tdb-input", "tdb-input-date"], context.className);
356
- if (config.min !== void 0) input.min = config.min;
357
- if (config.max !== void 0) input.max = config.max;
358
- /** Empty gives `null`. */
359
- const getValue = () => input.value === "" ? null : input.value;
360
- /** `null` shows as empty. */
583
+ if (config.min !== void 0) input.min = parseDate(config.min, format) ?? "";
584
+ if (config.max !== void 0) input.max = parseDate(config.max, format) ?? "";
585
+ /** Empty gives `null`. Otherwise the date in `format`. */
586
+ const getValue = () => input.value === "" ? null : formatDate(input.value, format);
587
+ /** `null`, or a value that isn't a date in `format`, shows as empty. */
361
588
  const setValue = (value) => {
362
- input.value = value ?? "";
589
+ input.value = value === null ? "" : parseDate(value, format) ?? "";
590
+ };
591
+ setValue(context.value ?? null);
592
+ input.addEventListener("input", () => context.onChange(getValue()));
593
+ return {
594
+ element: input,
595
+ getValue,
596
+ setValue,
597
+ focus: () => input.focus(),
598
+ destroy: () => input.remove()
599
+ };
600
+ }
601
+ // src/editors/datetime.ts
602
+ /**
603
+ * Builds the date-and-time input. The input itself always works in
604
+ * `'yyyy-mm-ddThh:mm'`, so values are converted going in and out.
605
+ */
606
+ function createDateTimeEditor(config, context) {
607
+ const format = config.format ?? "yyyy-mm-dd";
608
+ const seconds = config.seconds ?? false;
609
+ const separator = dataSeparator(format);
610
+ const input = document.createElement("input");
611
+ input.type = "datetime-local";
612
+ input.disabled = context.readOnly ?? false;
613
+ addClasses(input, ["tdb-input", "tdb-input-datetime"], context.className);
614
+ if (seconds) input.step = "1";
615
+ /** What the input wants: `'yyyy-mm-ddThh:mm'`, with `:ss` when seconds show. */
616
+ const forInput = (value) => seconds ? value : value.slice(0, 16);
617
+ if (config.min !== void 0) input.min = forInput(parseDateTime(config.min, format) ?? "");
618
+ if (config.max !== void 0) input.max = forInput(parseDateTime(config.max, format) ?? "");
619
+ /** Empty gives `null`. Otherwise written like the data. */
620
+ const getValue = () => {
621
+ const value = input.value === "" ? null : parseDateTime(input.value, defaultDateFormat);
622
+ return value === null ? null : formatDateTime(value, format, seconds, separator);
623
+ };
624
+ /** `null`, or a value that isn't a date and time in `format`, shows as empty. */
625
+ const setValue = (value) => {
626
+ const inside = value === null ? null : parseDateTime(value, format);
627
+ input.value = inside === null ? "" : forInput(inside);
363
628
  };
364
629
  setValue(context.value ?? null);
365
630
  input.addEventListener("input", () => context.onChange(getValue()));
@@ -376,6 +641,7 @@ function createDateEditor(config, context) {
376
641
  function createNumberEditor(config, context) {
377
642
  const input = document.createElement("input");
378
643
  input.type = "number";
644
+ input.disabled = context.readOnly ?? false;
379
645
  addClasses(input, ["tdb-input", "tdb-input-number"], context.className);
380
646
  if (config.min !== void 0) input.min = String(config.min);
381
647
  if (config.max !== void 0) input.max = String(config.max);
@@ -404,6 +670,8 @@ function createNumberEditor(config, context) {
404
670
  */
405
671
  function createSelectEditor(config, context, texts = en) {
406
672
  const select = document.createElement("select");
673
+ const readOnly = context.readOnly ?? false;
674
+ select.disabled = readOnly;
407
675
  addClasses(select, ["tdb-input", "tdb-input-select"], context.className);
408
676
  /** The options on screen. Empty while a loader runs. */
409
677
  let options = [];
@@ -411,12 +679,14 @@ function createSelectEditor(config, context, texts = en) {
411
679
  let current = context.value;
412
680
  /** The running load, so a newer one or `destroy` can abort it. */
413
681
  let controller;
682
+ /** Whether "Loading…" or an empty line shows instead of the options. */
683
+ let waiting = false;
414
684
  /** Selects `current`. A value that isn't in the list becomes `null`. */
415
685
  const pickCurrent = () => {
416
686
  select.selectedIndex = options.findIndex((option) => option.value === current);
417
687
  if (select.selectedIndex === -1) current = null;
418
688
  };
419
- /** Shows `list`, enables the select and picks `current`. */
689
+ /** Shows `list`, unlocks the select unless it's read-only, and picks `current`. */
420
690
  const fill = (list) => {
421
691
  options = list;
422
692
  select.replaceChildren(...list.map((option) => {
@@ -424,7 +694,8 @@ function createSelectEditor(config, context, texts = en) {
424
694
  element.textContent = option.label;
425
695
  return element;
426
696
  }));
427
- select.disabled = false;
697
+ waiting = false;
698
+ select.disabled = readOnly;
428
699
  pickCurrent();
429
700
  };
430
701
  /** Shows a single disabled line, like "Loading…". */
@@ -433,6 +704,7 @@ function createSelectEditor(config, context, texts = en) {
433
704
  const element = document.createElement("option");
434
705
  element.textContent = text;
435
706
  select.replaceChildren(element);
707
+ waiting = true;
436
708
  select.disabled = true;
437
709
  };
438
710
  /** Runs the `options` function and shows its result. */
@@ -465,7 +737,7 @@ function createSelectEditor(config, context, texts = en) {
465
737
  /** While loading, the value is only remembered. */
466
738
  const setValue = (value) => {
467
739
  current = value;
468
- if (!select.disabled) pickCurrent();
740
+ if (!waiting) pickCurrent();
469
741
  };
470
742
  if (typeof config.options !== "function") fill(config.options);
471
743
  select.addEventListener("change", () => {
@@ -476,6 +748,7 @@ function createSelectEditor(config, context, texts = en) {
476
748
  element: select,
477
749
  getValue,
478
750
  getLabel,
751
+ getOptions: () => options,
479
752
  setValue,
480
753
  load,
481
754
  focus: () => select.focus(),
@@ -490,6 +763,7 @@ function createSelectEditor(config, context, texts = en) {
490
763
  function createTextEditor(config, context) {
491
764
  const input = document.createElement("input");
492
765
  input.type = "text";
766
+ input.disabled = context.readOnly ?? false;
493
767
  addClasses(input, ["tdb-input", "tdb-input-text"], context.className);
494
768
  if (config.minLength !== void 0) input.minLength = config.minLength;
495
769
  if (config.maxLength !== void 0) input.maxLength = config.maxLength;
@@ -506,6 +780,37 @@ function createTextEditor(config, context) {
506
780
  destroy: () => input.remove()
507
781
  };
508
782
  }
783
+ // src/editors/time.ts
784
+ /** Builds the time input. */
785
+ function createTimeEditor(config, context) {
786
+ const seconds = config.seconds ?? false;
787
+ const input = document.createElement("input");
788
+ input.type = "time";
789
+ input.disabled = context.readOnly ?? false;
790
+ addClasses(input, ["tdb-input", "tdb-input-time"], context.className);
791
+ if (seconds) input.step = "1";
792
+ if (config.min !== void 0) input.min = formatTime(parseTime(config.min) ?? "", seconds);
793
+ if (config.max !== void 0) input.max = formatTime(parseTime(config.max) ?? "", seconds);
794
+ /**
795
+ * Empty gives `null`. Read through `parseTime`, since some browsers drop
796
+ * `:00` seconds.
797
+ */
798
+ const getValue = () => input.value === "" ? null : formatTime(parseTime(input.value) ?? "", seconds);
799
+ /** `null`, or a value that isn't a time, shows as empty. */
800
+ const setValue = (value) => {
801
+ const time = value === null ? null : parseTime(value);
802
+ input.value = time === null ? "" : formatTime(time, seconds);
803
+ };
804
+ setValue(context.value ?? null);
805
+ input.addEventListener("input", () => context.onChange(getValue()));
806
+ return {
807
+ element: input,
808
+ getValue,
809
+ setValue,
810
+ focus: () => input.focus(),
811
+ destroy: () => input.remove()
812
+ };
813
+ }
509
814
  // src/editors/create.ts
510
815
  /**
511
816
  * `Column<Row>` already checked that each config fits its column, so the
@@ -514,7 +819,8 @@ function createTextEditor(config, context) {
514
819
  function createEditor(config, context, texts = en) {
515
820
  const fullContext = {
516
821
  ...context,
517
- className: config.className
822
+ className: config.className,
823
+ readOnly: config.readOnly
518
824
  };
519
825
  switch (config.type) {
520
826
  case "text": return loosen(createTextEditor(config, tighten(fullContext)));
@@ -524,6 +830,8 @@ function createEditor(config, context, texts = en) {
524
830
  case "select": return createSelectEditor(config, fullContext, texts);
525
831
  case "custom": return config.create(fullContext);
526
832
  case "money": return loosen(createMoneyEditor(config, tighten(fullContext)));
833
+ case "time": return loosen(createTimeEditor(config, tighten(fullContext)));
834
+ case "datetime": return loosen(createDateTimeEditor(config, tighten(fullContext)));
527
835
  default: throw new Error(`Unknown editor: ${JSON.stringify(config)}`);
528
836
  }
529
837
  }
@@ -548,6 +856,8 @@ function builtInError(config, value, texts) {
548
856
  case "number":
549
857
  case "money": return typeof value === "number" ? rangeError(config, value, texts) : void 0;
550
858
  case "date": return typeof value === "string" ? dateError(config, value, texts) : void 0;
859
+ case "time": return typeof value === "string" ? timeError(config, value, texts) : void 0;
860
+ case "datetime": return typeof value === "string" ? dateTimeError(config, value, texts) : void 0;
551
861
  case "checkbox":
552
862
  case "select":
553
863
  case "custom": return;
@@ -565,10 +875,48 @@ function rangeError(config, value, texts) {
565
875
  if (config.min !== void 0 && value < config.min) return texts.tooSmall(config.min);
566
876
  if (config.max !== void 0 && value > config.max) return texts.tooLarge(config.max);
567
877
  }
568
- /** `min` and `max` for dates. */
878
+ /**
879
+ * `min` and `max` for dates. Compared as `'yyyy-mm-dd'`, since `'15/03/1999'`
880
+ * comes after `'01/01/2000'` as text. The message shows the limit as the
881
+ * cells show dates.
882
+ */
569
883
  function dateError(config, value, texts) {
570
- if (config.min !== void 0 && value < config.min) return texts.tooEarly(config.min);
571
- if (config.max !== void 0 && value > config.max) return texts.tooLate(config.max);
884
+ const format = config.format ?? "yyyy-mm-dd";
885
+ const display = config.display ?? format;
886
+ const date = parseDate(value, format);
887
+ if (date === null) return;
888
+ const min = config.min === void 0 ? null : parseDate(config.min, format);
889
+ const max = config.max === void 0 ? null : parseDate(config.max, format);
890
+ if (min !== null && date < min) return texts.tooEarly(formatDate(min, display));
891
+ if (max !== null && date > max) return texts.tooLate(formatDate(max, display));
892
+ }
893
+ /**
894
+ * `min` and `max` for times. Compared as `'hh:mm:ss'`, since `'9:05'` comes
895
+ * after `'14:30'` as text.
896
+ */
897
+ function timeError(config, value, texts) {
898
+ const seconds = config.seconds ?? false;
899
+ const time = parseTime(value);
900
+ if (time === null) return;
901
+ const min = config.min === void 0 ? null : parseTime(config.min);
902
+ const max = config.max === void 0 ? null : parseTime(config.max);
903
+ if (min !== null && time < min) return texts.timeTooEarly(formatTime(min, seconds));
904
+ if (max !== null && time > max) return texts.timeTooLate(formatTime(max, seconds));
905
+ }
906
+ /**
907
+ * `min` and `max` for dates with a time. Compared as `'yyyy-mm-ddThh:mm:ss'`.
908
+ * The message shows the limit as the cells show it.
909
+ */
910
+ function dateTimeError(config, value, texts) {
911
+ const format = config.format ?? "yyyy-mm-dd";
912
+ const display = config.display ?? format;
913
+ const seconds = config.seconds ?? false;
914
+ const dateTime = parseDateTime(value, format);
915
+ if (dateTime === null) return;
916
+ const min = config.min === void 0 ? null : parseDateTime(config.min, format);
917
+ const max = config.max === void 0 ? null : parseDateTime(config.max, format);
918
+ if (min !== null && dateTime < min) return texts.tooEarly(formatDateTime(min, display, seconds, " "));
919
+ if (max !== null && dateTime > max) return texts.tooLate(formatDateTime(max, display, seconds, " "));
572
920
  }
573
921
  /**
574
922
  * Same rules as the HTML `pattern` attribute: whole value, `v` flag, and an
@@ -605,10 +953,13 @@ var EditSession = class {
605
953
  saving = false;
606
954
  /** Error messages and the "Loading…" text. */
607
955
  texts;
956
+ /** Told each time a select's options load, so the table can remember them. */
957
+ onOptions;
608
958
  /** Puts an editor in each cell and starts loading select options. */
609
- constructor(row, cells, texts = en) {
959
+ constructor(row, cells, texts = en, onOptions) {
610
960
  this.originalData = { ...row };
611
961
  this.texts = texts;
962
+ this.onOptions = onOptions;
612
963
  for (const { column, cell } of cells) {
613
964
  if (column.editor === void 0) continue;
614
965
  const config = column.editor;
@@ -636,6 +987,7 @@ var EditSession = class {
636
987
  getRow() {
637
988
  const row = { ...this.originalData };
638
989
  for (const [prop, { editor, config }] of this.fields) {
990
+ if (config.readOnly) continue;
639
991
  row[prop] = editor.getValue();
640
992
  if (config.type === "select" && config.labelProp !== void 0) {
641
993
  const label = editor.getLabel?.();
@@ -649,6 +1001,7 @@ var EditSession = class {
649
1001
  const row = this.getRow();
650
1002
  const errors = /* @__PURE__ */ new Map();
651
1003
  for (const [prop, { editor, config }] of this.fields) {
1004
+ if (config.readOnly) continue;
652
1005
  const message = this.loadErrors.has(prop) ? this.texts.loadFailed : validateValue(config, editor.getValue(), row, this.texts);
653
1006
  if (message !== void 0) errors.set(prop, message);
654
1007
  }
@@ -731,6 +1084,7 @@ var EditSession = class {
731
1084
  return;
732
1085
  }
733
1086
  if (this.loadErrors.delete(prop)) this.hideError(prop);
1087
+ this.onOptions?.(prop, field.editor.getOptions?.() ?? []);
734
1088
  }
735
1089
  };
736
1090
  // src/table/check-options.ts
@@ -739,14 +1093,21 @@ var EditSession = class {
739
1093
  *
740
1094
  * @throws If a column has an `editor` and there's no `rowId`.
741
1095
  * @throws If `onDelete` is set and there's no `rowId`.
1096
+ * @throws If `selection` is on and there's no `rowId`.
1097
+ * @throws If `detail` is set and there's no `rowId`.
742
1098
  * @throws If a hidden column (`visible: false`) has an `editor`.
743
1099
  * @throws If a select's `labelProp` is its own column.
744
1100
  * @throws If a money editor's `separator` and `point` are the same.
1101
+ * @throws If a date editor's `min` or `max` isn't a real date in its `format`.
1102
+ * @throws If a time editor's `min` or `max` isn't a real time.
1103
+ * @throws If a datetime editor's `min` or `max` isn't a real date and time in its `format`.
745
1104
  */
746
1105
  function checkOptions(options) {
747
1106
  if (options.rowId === void 0) {
748
1107
  if (options.columns.some((column) => column.editor !== void 0)) throw new Error("Tadabut: rowId is required when a column has an editor.");
749
1108
  if (options.onDelete !== void 0) throw new Error("Tadabut: rowId is required with onDelete.");
1109
+ if (options.selection) throw new Error("Tadabut: rowId is required with selection.");
1110
+ if (options.detail !== void 0) throw new Error("Tadabut: rowId is required with detail.");
750
1111
  }
751
1112
  const hiddenEditable = options.columns.find((column) => column.editor !== void 0 && column.visible === false);
752
1113
  if (hiddenEditable !== void 0) throw new Error(`Tadabut: the "${hiddenEditable.prop}" column can't have both an editor and visible: false.`);
@@ -757,6 +1118,20 @@ function checkOptions(options) {
757
1118
  const { separator, point } = moneyFormat(column.editor);
758
1119
  if (separator === point) throw new Error(`Tadabut: the "${column.prop}" column's money separator and point can't both be "${point}".`);
759
1120
  }
1121
+ for (const column of options.columns) {
1122
+ if (column.editor?.type !== "date") continue;
1123
+ const format = column.editor.format ?? "yyyy-mm-dd";
1124
+ 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}.`);
1125
+ }
1126
+ for (const column of options.columns) {
1127
+ if (column.editor?.type !== "time") continue;
1128
+ for (const limit of [column.editor.min, column.editor.max]) if (limit !== void 0 && parseTime(limit) === null) throw new Error(`Tadabut: the "${column.prop}" column's time "${limit}" isn't a real time.`);
1129
+ }
1130
+ for (const column of options.columns) {
1131
+ if (column.editor?.type !== "datetime") continue;
1132
+ const format = column.editor.format ?? "yyyy-mm-dd";
1133
+ for (const limit of [column.editor.min, column.editor.max]) if (limit !== void 0 && parseDateTime(limit, format) === null) throw new Error(`Tadabut: the "${column.prop}" column's date and time "${limit}" isn't real, or isn't written as ${format} hh:mm.`);
1134
+ }
760
1135
  }
761
1136
  // src/table/new-row.ts
762
1137
  /**
@@ -771,7 +1146,7 @@ var NewRow = class {
771
1146
  tr;
772
1147
  /** Its inputs. */
773
1148
  session;
774
- /** The first column with an editor, for the focus. */
1149
+ /** The first field that isn't read-only, for the focus. A locked input can't take it. */
775
1150
  firstProp;
776
1151
  /** Builds the row. Nothing is shown until `body` is put in the table. */
777
1152
  constructor(defaults, options) {
@@ -779,6 +1154,7 @@ var NewRow = class {
779
1154
  this.body.classList.add("tdb-new-rows");
780
1155
  this.tr = document.createElement("tr");
781
1156
  this.tr.classList.add("tdb-row-new", "tdb-row-editing");
1157
+ for (let index = 0; index < options.leadingCells; index++) this.tr.append(document.createElement("td"));
782
1158
  const cells = [];
783
1159
  options.columns.forEach((column, index) => {
784
1160
  if (!options.isVisible(index)) return;
@@ -800,8 +1176,8 @@ var NewRow = class {
800
1176
  this.body.append(this.tr);
801
1177
  const start = { ...defaults };
802
1178
  for (const { column } of cells) start[column.prop] ??= null;
803
- this.session = new EditSession(start, cells, options.texts);
804
- this.firstProp = cells[0]?.column.prop;
1179
+ this.session = new EditSession(start, cells, options.texts, options.onOptions);
1180
+ this.firstProp = cells.find(({ column }) => !column.editor?.readOnly)?.column.prop;
805
1181
  }
806
1182
  /** Whether `onAdd` is running. */
807
1183
  get saving() {
@@ -865,6 +1241,160 @@ var NewRow = class {
865
1241
  this.body.remove();
866
1242
  }
867
1243
  };
1244
+ // src/table/row-lines.ts
1245
+ /**
1246
+ * The lines under each row: its detail and its error. DataTables only allows
1247
+ * one set of lines per row, so both live here and are put back together each
1248
+ * time one changes.
1249
+ */
1250
+ var RowLines = class {
1251
+ /** The open details, by row id. */
1252
+ details = /* @__PURE__ */ new Map();
1253
+ /** The error lines, by row id. */
1254
+ errors = /* @__PURE__ */ new Map();
1255
+ /** What the lines need from the table. */
1256
+ parts;
1257
+ /** Nothing is shown until a detail opens or an error comes. */
1258
+ constructor(parts) {
1259
+ this.parts = parts;
1260
+ }
1261
+ /** Whether a row's detail is open. */
1262
+ isOpen(id) {
1263
+ return this.details.has(id);
1264
+ }
1265
+ /**
1266
+ * Opens a row's detail. "Loading…" shows until `detail` returns. Does
1267
+ * nothing without `detail`, if it's open already, or if the row isn't in
1268
+ * the table.
1269
+ */
1270
+ open(id) {
1271
+ const detail = this.parts.detail;
1272
+ const row = this.findRow(id);
1273
+ if (detail === void 0 || row === void 0 || this.isOpen(id)) return;
1274
+ const cell = document.createElement("div");
1275
+ cell.textContent = this.parts.texts.detailLoading;
1276
+ const controller = new AbortController();
1277
+ this.details.set(id, {
1278
+ line: this.line("tdb-row-detail", cell),
1279
+ controller
1280
+ });
1281
+ this.render(id);
1282
+ this.load(detail, row.data(), cell, controller);
1283
+ }
1284
+ /** Closes a row's detail, and stops its load if it's still running. */
1285
+ close(id) {
1286
+ const open = this.details.get(id);
1287
+ if (open === void 0) return;
1288
+ open.controller.abort();
1289
+ this.details.delete(id);
1290
+ this.render(id);
1291
+ }
1292
+ /** Opens a closed detail, closes an open one. */
1293
+ toggle(id) {
1294
+ if (this.isOpen(id)) this.close(id);
1295
+ else this.open(id);
1296
+ }
1297
+ /** Runs an open detail's `detail` again, after a save. Leaves a closed one closed. */
1298
+ reload(id) {
1299
+ if (this.isOpen(id)) {
1300
+ this.close(id);
1301
+ this.open(id);
1302
+ }
1303
+ }
1304
+ /** Shows an error under a row, under its detail if open. Replaces the previous one. */
1305
+ showError(id, message) {
1306
+ this.errors.set(id, this.line("tdb-row-error", rowErrorMessage(message)));
1307
+ this.render(id);
1308
+ }
1309
+ /** Removes a row's error, if any. */
1310
+ clearError(id) {
1311
+ if (this.errors.delete(id)) this.render(id);
1312
+ }
1313
+ /**
1314
+ * Sets the ▸ buttons and the `tdb-detail-open` class on the rows shown.
1315
+ * Runs after each draw, since redrawing a row brings back a closed ▸.
1316
+ */
1317
+ sync() {
1318
+ const rowId = this.parts.rowId;
1319
+ if (rowId === void 0) return;
1320
+ const { texts } = this.parts;
1321
+ const rows = this.parts.dataTable.rows({ page: "current" });
1322
+ const data = rows.data().toArray();
1323
+ rows.nodes().toArray().forEach((tr, index) => {
1324
+ const row = data[index];
1325
+ if (row === void 0) return;
1326
+ const open = this.details.has(row[rowId]);
1327
+ tr.classList.toggle("tdb-detail-open", open);
1328
+ const button = tr.querySelector(".tdb-detail-toggle");
1329
+ if (button !== null) {
1330
+ button.setAttribute("aria-expanded", String(open));
1331
+ button.setAttribute("aria-label", open ? texts.hideDetail : texts.showDetail);
1332
+ button.textContent = open ? "▾" : "▸";
1333
+ }
1334
+ });
1335
+ }
1336
+ /**
1337
+ * Forgets the details and errors of rows that left the table, after
1338
+ * `setData` or a delete. Their lines left with them.
1339
+ */
1340
+ prune() {
1341
+ const rowId = this.parts.rowId;
1342
+ if (rowId === void 0) return;
1343
+ const existing = new Set(this.parts.dataTable.rows().data().toArray().map((row) => row[rowId]));
1344
+ for (const [id, open] of this.details) if (!existing.has(id)) {
1345
+ open.controller.abort();
1346
+ this.details.delete(id);
1347
+ }
1348
+ for (const id of this.errors.keys()) if (!existing.has(id)) this.errors.delete(id);
1349
+ }
1350
+ /** Stops every load still running, and forgets everything. */
1351
+ destroy() {
1352
+ for (const open of this.details.values()) open.controller.abort();
1353
+ this.details.clear();
1354
+ this.errors.clear();
1355
+ }
1356
+ /** The row with this id, or `undefined`. */
1357
+ findRow(id) {
1358
+ const rowId = this.parts.rowId;
1359
+ if (rowId === void 0) return;
1360
+ const row = this.parts.dataTable.row((_index, data) => data[rowId] === id);
1361
+ return row.any() ? row : void 0;
1362
+ }
1363
+ /** Waits for `detail`, then puts what it gave, or its error, in the line. */
1364
+ async load(detail, row, cell, controller) {
1365
+ try {
1366
+ const content = await detail(row, { signal: controller.signal });
1367
+ if (controller.signal.aborted) return;
1368
+ if (typeof content === "string") cell.textContent = content;
1369
+ else cell.replaceChildren(content);
1370
+ } catch (error) {
1371
+ if (controller.signal.aborted) return;
1372
+ cell.replaceChildren(rowErrorMessage(error instanceof Error ? error.message : this.parts.texts.detailFailed));
1373
+ }
1374
+ }
1375
+ /** A line under a row: one cell as wide as the table. */
1376
+ line(className, content) {
1377
+ const tr = document.createElement("tr");
1378
+ tr.className = className;
1379
+ const td = document.createElement("td");
1380
+ td.colSpan = this.parts.dataTable.columns(":visible").count();
1381
+ td.append(content);
1382
+ tr.append(td);
1383
+ return tr;
1384
+ }
1385
+ /**
1386
+ * Puts the row's lines back under it: its detail, then its error. With
1387
+ * neither, the lines are removed.
1388
+ */
1389
+ render(id) {
1390
+ const row = this.findRow(id);
1391
+ if (row === void 0) return;
1392
+ const lines = [this.details.get(id)?.line, this.errors.get(id)].filter((line) => line !== void 0);
1393
+ if (lines.length === 0) row.child.remove();
1394
+ else row.child(lines).show();
1395
+ this.sync();
1396
+ }
1397
+ };
868
1398
  // src/table/totals.ts
869
1399
  /**
870
1400
  * An empty footer, one cell per column. It must be in the table before
@@ -878,25 +1408,41 @@ function footerFor(cellCount) {
878
1408
  tfoot.append(tr);
879
1409
  return tfoot;
880
1410
  }
881
- /** The DataTables filter for each `totalRows`. */
882
- function rowsFor(totalRows) {
883
- switch (totalRows) {
1411
+ /** The DataTables filter for each `RowScope`. */
1412
+ function rowsFor(scope) {
1413
+ switch (scope) {
884
1414
  case "searched": return { search: "applied" };
885
1415
  case "all": return { search: "none" };
886
1416
  case "page": return { page: "current" };
887
1417
  }
888
1418
  }
889
- /** The text under a column: `count` and functions as they are, numbers formatted like the cells. */
890
- function totalText(column, rows) {
891
- const { prop, total, render, editor } = column;
892
- if (total === void 0) return "";
1419
+ /**
1420
+ * The total of a column, before it's written: a number for built-in totals,
1421
+ * rounded like the footer, or your function's text. `undefined` when there's
1422
+ * nothing to show.
1423
+ */
1424
+ function totalValue(column, rows) {
1425
+ const { prop, total, editor } = column;
1426
+ if (total === void 0) return;
893
1427
  if (typeof total === "function") return total(rows);
894
- if (total === "count") return String(rows.length);
1428
+ if (total === "count") return rows.length;
895
1429
  const result = compute(total, rows.map((row) => row[prop]).filter((value) => typeof value === "number" && !Number.isNaN(value)));
896
- if (result === void 0) return "";
897
- if (editor?.type === "money" && render === void 0) return formatMoney(result, moneyFormat(editor));
898
- const rounded = Math.round(result * 100) / 100;
899
- return render === void 0 ? String(rounded) : render(rounded, {});
1430
+ if (result === void 0) return;
1431
+ return roundTo(result, editor?.type === "money" ? moneyFormat(editor).decimals : 2);
1432
+ }
1433
+ /** The text under a column: `count` and functions as they are, numbers formatted like the cells. */
1434
+ function totalText(column, rows) {
1435
+ const { total, render, editor } = column;
1436
+ const value = totalValue(column, rows);
1437
+ if (value === void 0) return "";
1438
+ if (typeof value === "string" || total === "count") return String(value);
1439
+ if (editor?.type === "money" && render === void 0) return formatMoney(value, moneyFormat(editor));
1440
+ return render === void 0 ? String(value) : render(value, {});
1441
+ }
1442
+ /** Rounds to this many decimals. */
1443
+ function roundTo(value, decimals) {
1444
+ const factor = 10 ** decimals;
1445
+ return Math.round(value * factor) / factor;
900
1446
  }
901
1447
  /** `undefined` when there's nothing to average, or no smallest or biggest. */
902
1448
  function compute(total, values) {
@@ -909,6 +1455,132 @@ function compute(total, values) {
909
1455
  case "max": return Math.max(...values);
910
1456
  }
911
1457
  }
1458
+ // src/table/selection.ts
1459
+ /**
1460
+ * Which rows are ticked. The ids are the truth; the checkboxes on the page
1461
+ * are redrawn from them after every draw, since DataTables rebuilds rows.
1462
+ */
1463
+ var Selection = class {
1464
+ /** The selected row ids. */
1465
+ ids = /* @__PURE__ */ new Set();
1466
+ /** What the selection needs from the table. */
1467
+ parts;
1468
+ /** Starts listening to the checkboxes. Nothing is ticked yet. */
1469
+ constructor(parts) {
1470
+ this.parts = parts;
1471
+ this.parts.dataTable.table().node().addEventListener("change", this.onChange);
1472
+ }
1473
+ /**
1474
+ * Ticks the checkboxes on the page to match the selection, and sets the
1475
+ * header's checkbox to all, none or some.
1476
+ */
1477
+ sync() {
1478
+ const rows = this.parts.dataTable.rows({ page: "current" });
1479
+ const data = rows.data().toArray();
1480
+ rows.nodes().toArray().forEach((node, index) => {
1481
+ const row = data[index];
1482
+ if (row === void 0) return;
1483
+ const selected = this.ids.has(this.idFor(row));
1484
+ node.classList.toggle("tdb-row-selected", selected);
1485
+ const checkbox = node.querySelector(".tdb-select-row");
1486
+ if (checkbox !== null) checkbox.checked = selected;
1487
+ });
1488
+ const all = this.parts.dataTable.table().header().querySelector(".tdb-select-all");
1489
+ if (all === null) return;
1490
+ const scope = this.scopeIds();
1491
+ const count = scope.filter((id) => this.ids.has(id)).length;
1492
+ all.checked = count > 0 && count === scope.length;
1493
+ all.indeterminate = count > 0 && count < scope.length;
1494
+ }
1495
+ /**
1496
+ * The selected rows, in the order they were added to the table. Rows the
1497
+ * search hides, or on other pages, are in it too.
1498
+ */
1499
+ selected() {
1500
+ return this.parts.dataTable.rows().data().toArray().filter((row) => this.ids.has(this.idFor(row)));
1501
+ }
1502
+ /** Whether the row with this id is selected. */
1503
+ has(id) {
1504
+ return this.ids.has(id);
1505
+ }
1506
+ /**
1507
+ * Selects or unselects rows. Ids of rows that aren't in the table are
1508
+ * skipped. `onSelect` is only called if something changed.
1509
+ */
1510
+ set(ids, selected) {
1511
+ const before = this.ids.size;
1512
+ if (selected) {
1513
+ const existing = this.allIds();
1514
+ for (const id of ids) if (existing.has(id)) this.ids.add(id);
1515
+ } else for (const id of ids) this.ids.delete(id);
1516
+ if (this.ids.size !== before) {
1517
+ this.sync();
1518
+ this.changed();
1519
+ }
1520
+ }
1521
+ /** Unselects every row. */
1522
+ clear() {
1523
+ if (this.ids.size === 0) return;
1524
+ this.ids.clear();
1525
+ this.sync();
1526
+ this.changed();
1527
+ }
1528
+ /** Forgets the ids of rows that left the table, after `setData` or a delete. */
1529
+ prune() {
1530
+ const existing = this.allIds();
1531
+ const before = this.ids.size;
1532
+ for (const id of this.ids) if (!existing.has(id)) this.ids.delete(id);
1533
+ if (this.ids.size !== before) {
1534
+ this.sync();
1535
+ this.changed();
1536
+ }
1537
+ }
1538
+ /** Stops listening to the checkboxes. */
1539
+ destroy() {
1540
+ this.parts.dataTable.table().node().removeEventListener("change", this.onChange);
1541
+ }
1542
+ /** Tells the user the selection changed. */
1543
+ changed() {
1544
+ this.parts.onSelect?.(this.selected());
1545
+ }
1546
+ /** The id of a row. */
1547
+ idFor(row) {
1548
+ return row[this.parts.rowId];
1549
+ }
1550
+ /** The ids of every row in the table. */
1551
+ allIds() {
1552
+ return new Set(this.parts.dataTable.rows().data().toArray().map((row) => this.idFor(row)));
1553
+ }
1554
+ /** The id of the row an element is in, or `undefined` outside DataTables' rows. */
1555
+ idOf(element) {
1556
+ const tr = element.closest("tr");
1557
+ if (tr === null) return;
1558
+ const row = this.parts.dataTable.row(tr);
1559
+ return row.any() ? this.idFor(row.data()) : void 0;
1560
+ }
1561
+ /** The ids of the rows in `scope`. */
1562
+ scopeIds() {
1563
+ return this.parts.dataTable.rows(rowsFor(this.parts.scope)).data().toArray().map((row) => this.idFor(row));
1564
+ }
1565
+ /**
1566
+ * A row's checkbox or the header's was clicked. An arrow function, so
1567
+ * `destroy` can remove it.
1568
+ */
1569
+ onChange = (event) => {
1570
+ const target = event.target;
1571
+ if (!(target instanceof HTMLInputElement)) return;
1572
+ if (target.classList.contains("tdb-select-row")) {
1573
+ const id = this.idOf(target);
1574
+ if (id === void 0) return;
1575
+ if (target.checked) this.ids.add(id);
1576
+ else this.ids.delete(id);
1577
+ } else if (target.classList.contains("tdb-select-all")) for (const id of this.scopeIds()) if (target.checked) this.ids.add(id);
1578
+ else this.ids.delete(id);
1579
+ else return;
1580
+ this.sync();
1581
+ this.changed();
1582
+ };
1583
+ };
912
1584
  // src/table/tadabut.ts
913
1585
  /**
914
1586
  * A DataTables table with row editing.
@@ -962,14 +1634,39 @@ var Tadabut = class {
962
1634
  hasTotals;
963
1635
  /** Which rows the totals count, with its default filled in. */
964
1636
  totalRows;
1637
+ /** How many columns Tadabut adds before yours: the checkboxes and the ▸ button. */
1638
+ offset;
1639
+ /** The ticked rows. Only with `selection`. */
1640
+ selection;
1641
+ /** Asked before a row opens. */
1642
+ onEditStart;
1643
+ /** The user's after-save callback. */
1644
+ onSaved;
1645
+ /** The user's after-add callback. */
1646
+ onAdded;
1647
+ /** The user's after-delete callback. */
1648
+ onDeleted;
1649
+ /** The user's row click callback. */
1650
+ onRowClick;
1651
+ /** The user's row double click callback. */
1652
+ onRowDoubleClick;
1653
+ /** The lines under each row: details and errors. */
1654
+ rowLines;
1655
+ /** The last options each select loaded, by field. */
1656
+ loadedOptions = /* @__PURE__ */ new Map();
965
1657
  /**
966
1658
  * Builds the table inside `container`, which should be empty.
967
1659
  *
968
1660
  * @throws If a column has an `editor` and there's no `rowId`.
969
1661
  * @throws If `onDelete` is set and there's no `rowId`.
1662
+ * @throws If `selection` is on and there's no `rowId`.
1663
+ * @throws If `detail` is set and there's no `rowId`.
970
1664
  * @throws If a hidden column (`visible: false`) has an `editor`.
971
1665
  * @throws If a select's `labelProp` is its own column.
972
1666
  * @throws If a money editor's `separator` and `point` are the same.
1667
+ * @throws If a date editor's `min` or `max` isn't a real date in its `format`.
1668
+ * @throws If a time editor's `min` or `max` isn't a real time.
1669
+ * @throws If a datetime editor's `min` or `max` isn't a real date and time in its `format`.
973
1670
  */
974
1671
  constructor(container, options) {
975
1672
  checkOptions(options);
@@ -978,7 +1675,8 @@ var Tadabut = class {
978
1675
  this.columns = options.columns;
979
1676
  this.editing = {
980
1677
  mode: options.editing?.mode ?? "single",
981
- button: options.editing?.button ?? true
1678
+ button: options.editing?.button ?? true,
1679
+ doubleClick: options.editing?.doubleClick ?? false
982
1680
  };
983
1681
  const actions = [];
984
1682
  if (this.hasEditor && this.editing.button) actions.push("edit");
@@ -987,6 +1685,12 @@ var Tadabut = class {
987
1685
  this.onSave = options.onSave;
988
1686
  this.onAdd = options.onAdd;
989
1687
  this.onDelete = options.onDelete;
1688
+ this.onEditStart = options.onEditStart;
1689
+ this.onSaved = options.onSaved;
1690
+ this.onAdded = options.onAdded;
1691
+ this.onDeleted = options.onDeleted;
1692
+ this.onRowClick = options.onRowClick;
1693
+ this.onRowDoubleClick = options.onRowDoubleClick;
990
1694
  this.confirmDelete = options.confirmDelete;
991
1695
  this.classNames = options.classNames ?? {};
992
1696
  this.texts = {
@@ -995,32 +1699,177 @@ var Tadabut = class {
995
1699
  };
996
1700
  this.hasTotals = options.columns.some((column) => column.total !== void 0);
997
1701
  this.totalRows = options.totalRows ?? "searched";
1702
+ this.offset = (options.selection ? 1 : 0) + (options.detail !== void 0 ? 1 : 0);
998
1703
  this.tableEl = document.createElement("table");
999
1704
  addClasses(this.tableEl, [], this.classNames.table);
1000
1705
  container.appendChild(this.tableEl);
1001
- if (this.hasTotals) this.tableEl.append(footerFor(this.columns.length + (this.hasActions ? 1 : 0)));
1706
+ if (this.hasTotals) this.tableEl.append(footerFor(this.offset + this.columns.length + (this.hasActions ? 1 : 0)));
1002
1707
  this.dataTable = new DataTable(this.tableEl, {
1003
1708
  ...options.dataTables,
1709
+ ...this.offset > 0 && { order: shiftOrder(options.dataTables?.order, this.offset) },
1004
1710
  data: [...options.data],
1005
- columns: toDataTables(options.columns, actions, this.classNames, this.texts)
1711
+ columns: toDataTables(options.columns, actions, this.classNames, this.texts, {
1712
+ selection: Boolean(options.selection),
1713
+ detail: options.detail !== void 0
1714
+ })
1715
+ });
1716
+ this.rowLines = new RowLines({
1717
+ dataTable: this.dataTable,
1718
+ rowId: this.rowId,
1719
+ detail: options.detail,
1720
+ texts: this.texts
1006
1721
  });
1722
+ if (options.detail !== void 0) this.dataTable.on("draw", () => this.rowLines.sync());
1723
+ if (options.selection) {
1724
+ this.selection = new Selection({
1725
+ dataTable: this.dataTable,
1726
+ rowId: this.rowId,
1727
+ scope: typeof options.selection === "object" ? options.selection.checkAll ?? "searched" : "searched",
1728
+ onSelect: options.onSelect
1729
+ });
1730
+ this.dataTable.on("draw", () => this.selection?.sync());
1731
+ this.selection.sync();
1732
+ }
1007
1733
  if (this.hasTotals) {
1008
1734
  this.dataTable.on("draw", this.updateTotals);
1009
1735
  this.updateTotals();
1010
1736
  }
1011
- if (this.hasActions) this.tableEl.addEventListener("click", this.onClick);
1737
+ if (this.hasActions || options.detail !== void 0) this.tableEl.addEventListener("click", this.onClick);
1012
1738
  if (this.hasEditor) this.tableEl.addEventListener("keydown", this.onKeyDown);
1739
+ this.tableEl.addEventListener("click", this.onRowEvent);
1740
+ this.tableEl.addEventListener("dblclick", this.onRowEvent);
1013
1741
  }
1014
1742
  /**
1015
1743
  * Replaces all rows. Sorting, search and the page are kept.
1016
1744
  *
1017
1745
  * Open rows, and the new row, are closed first, and their unsaved changes
1018
- * are lost.
1746
+ * are lost. Open details close too.
1019
1747
  */
1020
1748
  setData(rows) {
1021
1749
  this.destroySessions();
1022
1750
  this.deleting.clear();
1751
+ this.rowLines.destroy();
1023
1752
  this.dataTable.clear().rows.add([...rows]).draw(false);
1753
+ this.selection?.prune();
1754
+ }
1755
+ /**
1756
+ * Every row, in the order shown. `scope` works like `totalRows`: `'all'`
1757
+ * (default), `'searched'` or `'page'`. They're copies, so changing them
1758
+ * changes nothing: use `updateRow` for that.
1759
+ *
1760
+ * @example
1761
+ * table.getData('searched'); // the rows that match the search
1762
+ */
1763
+ getData(scope = "all") {
1764
+ return this.dataTable.rows(rowsFor(scope)).data().toArray().map((row) => ({ ...row }));
1765
+ }
1766
+ /**
1767
+ * The row with this id, as a copy, or `undefined`. It's the saved row:
1768
+ * while a row is edited, what's typed isn't in it until Save.
1769
+ */
1770
+ getRow(id) {
1771
+ const row = this.findRow(id);
1772
+ return row === void 0 ? void 0 : { ...row.data() };
1773
+ }
1774
+ /**
1775
+ * The DataTables API, for anything Tadabut doesn't do itself.
1776
+ *
1777
+ * Careful: rows added or removed through it skip Tadabut, so the
1778
+ * selection, details and open rows won't know. Use `insertRow`,
1779
+ * `updateRow`, `removeRow` and `setData` for that.
1780
+ *
1781
+ * @example
1782
+ * table.getApi().order([2, 'desc']).draw();
1783
+ */
1784
+ getApi() {
1785
+ return this.dataTable;
1786
+ }
1787
+ /**
1788
+ * Puts one row or many in the table, without `onAdd` or the new-row form,
1789
+ * and `onAdded` doesn't fire. They go where the sorting puts them, and the
1790
+ * table stays on the page it's on. Either every row goes in, or none.
1791
+ *
1792
+ * @throws If there's no `rowId`, a row has no `rowId` value, or its id is
1793
+ * already in the table (or twice in `rows`).
1794
+ *
1795
+ * @example
1796
+ * table.insertRow(rowFromServer);
1797
+ */
1798
+ insertRow(rows) {
1799
+ const rowId = this.rowId;
1800
+ if (rowId === void 0) throw new Error("Tadabut: rowId is required with insertRow.");
1801
+ const list = Array.isArray(rows) ? rows : [rows];
1802
+ const seen = /* @__PURE__ */ new Set();
1803
+ for (const row of list) {
1804
+ const id = row[rowId];
1805
+ if (typeof id !== "string" && typeof id !== "number") throw new Error(`Tadabut: a row given to insertRow has no "${rowId}".`);
1806
+ if (seen.has(id) || this.findRow(id) !== void 0) throw new Error(`Tadabut: insertRow got the id ${id}, which is already in the table.`);
1807
+ seen.add(id);
1808
+ }
1809
+ this.dataTable.rows.add(list.map((row) => ({ ...row }))).draw(false);
1810
+ }
1811
+ /**
1812
+ * Replaces the row with the same id, without `onSave`, and `onSaved` doesn't
1813
+ * fire. An open detail reloads.
1814
+ *
1815
+ * @returns `false` if no row has this id, or it's being edited or deleted.
1816
+ *
1817
+ * @example
1818
+ * table.updateRow({ ...table.getRow(1), name: 'Nadia' });
1819
+ */
1820
+ updateRow(row) {
1821
+ if (this.rowId === void 0) return false;
1822
+ const id = row[this.rowId];
1823
+ const found = this.findRow(id);
1824
+ if (found === void 0 || this.sessions.has(id) || this.deleting.has(id)) return false;
1825
+ found.data({ ...row }).draw(false);
1826
+ this.rowLines.reload(id);
1827
+ return true;
1828
+ }
1829
+ /**
1830
+ * Takes a row out of the table, without `onDelete` and without asking, and
1831
+ * `onDeleted` doesn't fire. Its detail closes, and it leaves the selection.
1832
+ *
1833
+ * @returns `false` if no row has this id, or it's being edited or deleted.
1834
+ */
1835
+ removeRow(id) {
1836
+ const found = this.findRow(id);
1837
+ if (found === void 0 || this.sessions.has(id) || this.deleting.has(id)) return false;
1838
+ found.remove().draw(false);
1839
+ this.rowLines.prune();
1840
+ this.selection?.prune();
1841
+ return true;
1842
+ }
1843
+ /**
1844
+ * The footer's totals, by field: numbers for built-in totals (not
1845
+ * formatted, rounded like the footer), or your function's text. They count
1846
+ * the same rows as the footer. If two columns show the same field with a
1847
+ * total each, the last one wins.
1848
+ *
1849
+ * @example
1850
+ * table.getTotals().salary; // 176651.5
1851
+ */
1852
+ getTotals() {
1853
+ const rows = this.dataTable.rows(rowsFor(this.totalRows)).data().toArray();
1854
+ const totals = {};
1855
+ for (const column of this.columns) {
1856
+ const value = totalValue(column, rows);
1857
+ if (value !== void 0) totals[column.prop] = value;
1858
+ }
1859
+ return totals;
1860
+ }
1861
+ /**
1862
+ * A select's options. With a fixed list, that list. With an `options`
1863
+ * function, the list it last loaded in an open row, or `undefined` before
1864
+ * any row was opened. `undefined` for a column that isn't a select.
1865
+ *
1866
+ * @example
1867
+ * table.getOptions('countryId'); // [{ value: 1, label: 'Morocco' }, …]
1868
+ */
1869
+ getOptions(prop) {
1870
+ const editor = this.columns.find((column) => column.prop === prop)?.editor;
1871
+ if (editor?.type !== "select") return;
1872
+ return typeof editor.options === "function" ? this.loadedOptions.get(prop) : editor.options;
1024
1873
  }
1025
1874
  /**
1026
1875
  * Opens a row for editing.
@@ -1028,24 +1877,26 @@ var Tadabut = class {
1028
1877
  * @param id The value of the row's `rowId` field.
1029
1878
  * @returns `false` if the row doesn't exist, is already open, another row
1030
1879
  * or the new row is open in `'single'` mode, nothing is editable, the row
1031
- * is being deleted, or it's on a page that hasn't been displayed yet.
1880
+ * is being deleted, it's on a page that hasn't been displayed yet, or
1881
+ * `onEditStart` returned `false`.
1032
1882
  */
1033
1883
  edit(id) {
1034
1884
  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;
1035
1885
  const row = this.findRow(id);
1036
1886
  if (row === void 0 || row.node() === null) return false;
1887
+ if (this.onEditStart?.(row.data()) === false) return false;
1037
1888
  const rowIndex = row.index();
1038
1889
  const cells = [];
1039
1890
  this.columns.forEach((column, columnIndex) => {
1040
1891
  if (column.editor !== void 0) {
1041
- const cell = this.dataTable.cell(rowIndex, columnIndex).node();
1892
+ const cell = this.dataTable.cell(rowIndex, this.dtIndex(columnIndex)).node();
1042
1893
  cells.push({
1043
1894
  column,
1044
1895
  cell
1045
1896
  });
1046
1897
  }
1047
1898
  });
1048
- this.sessions.set(id, new EditSession(row.data(), cells, this.texts));
1899
+ this.sessions.set(id, new EditSession(row.data(), cells, this.texts, this.rememberOptions));
1049
1900
  row.node()?.classList.add("tdb-row-editing");
1050
1901
  if (this.hasActions) this.actionsCell(row).replaceChildren(...saveCancelButtons(this.texts, this.classNames));
1051
1902
  return true;
@@ -1064,10 +1915,12 @@ var Tadabut = class {
1064
1915
  if (!this.hasEditor || this.newRow !== void 0 || this.editing.mode === "single" && this.sessions.size > 0) return false;
1065
1916
  const newRow = new NewRow(defaults, {
1066
1917
  columns: this.columns,
1067
- isVisible: (index) => this.dataTable.column(index).visible(),
1918
+ isVisible: (index) => this.dataTable.column(this.dtIndex(index)).visible(),
1068
1919
  withButtons: this.hasActions,
1069
1920
  texts: this.texts,
1070
- classNames: this.classNames
1921
+ classNames: this.classNames,
1922
+ leadingCells: this.offset,
1923
+ onOptions: this.rememberOptions
1071
1924
  });
1072
1925
  this.tableEl.insertBefore(newRow.body, this.dataTable.table().body());
1073
1926
  newRow.focus();
@@ -1079,6 +1932,58 @@ var Tadabut = class {
1079
1932
  return this.newRow !== void 0;
1080
1933
  }
1081
1934
  /**
1935
+ * The selected rows, in the order they were added. Rows the search hides,
1936
+ * or on other pages, are in it too. Always `[]` without `selection`.
1937
+ */
1938
+ getSelected() {
1939
+ return this.selection?.selected() ?? [];
1940
+ }
1941
+ /** Whether a row is selected. Always `false` without `selection`. */
1942
+ isSelected(id) {
1943
+ return this.selection?.has(id) ?? false;
1944
+ }
1945
+ /**
1946
+ * Selects rows by id. Ids not in the table are skipped. Does nothing
1947
+ * without `selection`.
1948
+ *
1949
+ * @example
1950
+ * table.select([1, 2]);
1951
+ */
1952
+ select(ids) {
1953
+ this.selection?.set(ids, true);
1954
+ }
1955
+ /** Unselects rows by id. Does nothing without `selection`. */
1956
+ deselect(ids) {
1957
+ this.selection?.set(ids, false);
1958
+ }
1959
+ /** Unselects every row. Does nothing without `selection`. */
1960
+ clearSelection() {
1961
+ this.selection?.clear();
1962
+ }
1963
+ /**
1964
+ * Opens a row's detail under it. "Loading…" shows until `detail` returns.
1965
+ * Does nothing without `detail`, if it's open already, or if the row
1966
+ * isn't in the table.
1967
+ *
1968
+ * @example
1969
+ * onRowClick: (row) => table.toggleDetail(row.id)
1970
+ */
1971
+ openDetail(id) {
1972
+ this.rowLines.open(id);
1973
+ }
1974
+ /** Closes a row's detail, and stops its load if it's still running. Does nothing without `detail`. */
1975
+ closeDetail(id) {
1976
+ this.rowLines.close(id);
1977
+ }
1978
+ /** Opens a closed detail, closes an open one, like the ▸ button. Does nothing without `detail`. */
1979
+ toggleDetail(id) {
1980
+ this.rowLines.toggle(id);
1981
+ }
1982
+ /** Whether a row's detail is open, or loading. Always `false` without `detail`. */
1983
+ isDetailOpen(id) {
1984
+ return this.rowLines.isOpen(id);
1985
+ }
1986
+ /**
1082
1987
  * Closes the new row and throws it away. Does nothing if there's none, or
1083
1988
  * while it's saving.
1084
1989
  */
@@ -1131,6 +2036,7 @@ var Tadabut = class {
1131
2036
  }).indexes().toArray().indexOf(added.index());
1132
2037
  const length = this.dataTable.page.len();
1133
2038
  if (position >= 0 && length > 0) this.dataTable.page(Math.floor(position / length)).draw(false);
2039
+ this.onAdded?.(added.data());
1134
2040
  return true;
1135
2041
  }
1136
2042
  /**
@@ -1143,7 +2049,7 @@ var Tadabut = class {
1143
2049
  if (session.saving) return;
1144
2050
  session.destroy();
1145
2051
  this.sessions.delete(id);
1146
- this.clearRowError(id);
2052
+ this.rowLines.clearError(id);
1147
2053
  this.findRow(id)?.node()?.classList.remove("tdb-row-editing");
1148
2054
  this.findRow(id)?.invalidate("data").draw(false);
1149
2055
  }
@@ -1164,7 +2070,7 @@ var Tadabut = class {
1164
2070
  const session = this.sessions.get(id);
1165
2071
  if (session === void 0 || session.saving) return false;
1166
2072
  session.clearErrors();
1167
- this.clearRowError(id);
2073
+ this.rowLines.clearError(id);
1168
2074
  const errors = session.validate();
1169
2075
  const [firstInvalid] = errors.keys();
1170
2076
  if (firstInvalid !== void 0) {
@@ -1181,7 +2087,7 @@ var Tadabut = class {
1181
2087
  } catch (error) {
1182
2088
  if (this.sessions.get(id) !== session) return false;
1183
2089
  this.setSaving(id, false);
1184
- this.showRowError(id, error instanceof Error ? error.message : this.texts.saveFailed);
2090
+ this.rowLines.showError(id, error instanceof Error ? error.message : this.texts.saveFailed);
1185
2091
  return false;
1186
2092
  }
1187
2093
  if (this.sessions.get(id) !== session) return false;
@@ -1190,6 +2096,8 @@ var Tadabut = class {
1190
2096
  this.findRow(id)?.data({ ...saved }).draw(false);
1191
2097
  this.findRow(id)?.node()?.classList.remove("tdb-row-editing");
1192
2098
  this.setSaving(id, false);
2099
+ this.rowLines.reload(id);
2100
+ this.onSaved?.(saved, { previous: session.originalData });
1193
2101
  return true;
1194
2102
  }
1195
2103
  /**
@@ -1206,30 +2114,38 @@ var Tadabut = class {
1206
2114
  async delete(id) {
1207
2115
  const row = this.findRow(id);
1208
2116
  if (row === void 0 || this.sessions.has(id) || this.deleting.has(id)) return false;
1209
- this.clearRowError(id);
2117
+ const data = row.data();
2118
+ this.rowLines.clearError(id);
1210
2119
  this.deleting.add(id);
1211
2120
  this.setSaving(id, true);
1212
2121
  try {
1213
- await this.onDelete?.(row.data());
2122
+ await this.onDelete?.(data);
1214
2123
  } catch (error) {
1215
2124
  if (!this.deleting.has(id)) return false;
1216
2125
  this.deleting.delete(id);
1217
2126
  this.setSaving(id, false);
1218
2127
  this.keepRow(id);
1219
- this.showRowError(id, error instanceof Error ? error.message : this.texts.deleteFailed);
2128
+ this.rowLines.showError(id, error instanceof Error ? error.message : this.texts.deleteFailed);
1220
2129
  return false;
1221
2130
  }
1222
2131
  if (!this.deleting.has(id)) return false;
1223
2132
  this.deleting.delete(id);
1224
2133
  this.findRow(id)?.remove().draw(false);
2134
+ this.rowLines.prune();
2135
+ this.selection?.prune();
2136
+ this.onDeleted?.(data);
1225
2137
  return true;
1226
2138
  }
1227
2139
  /** Removes the table. Open rows are closed without saving. */
1228
2140
  destroy() {
1229
2141
  this.tableEl.removeEventListener("click", this.onClick);
1230
2142
  this.tableEl.removeEventListener("keydown", this.onKeyDown);
2143
+ this.tableEl.removeEventListener("click", this.onRowEvent);
2144
+ this.tableEl.removeEventListener("dblclick", this.onRowEvent);
1231
2145
  this.destroySessions();
1232
2146
  this.deleting.clear();
2147
+ this.selection?.destroy();
2148
+ this.rowLines.destroy();
1233
2149
  this.dataTable.destroy();
1234
2150
  this.tableEl.remove();
1235
2151
  }
@@ -1260,17 +2176,9 @@ var Tadabut = class {
1260
2176
  tr.classList.toggle("tdb-row-saving", saving);
1261
2177
  }
1262
2178
  }
1263
- /** Shows a save or delete error in a child row under the row. */
1264
- showRowError(id, message) {
1265
- this.findRow(id)?.child(rowErrorMessage(message), "tdb-row-error").show();
1266
- }
1267
- /** Removes the save or delete error under a row, if any. */
1268
- clearRowError(id) {
1269
- this.findRow(id)?.child.remove();
1270
- }
1271
2179
  /** The last cell of a row, the one with the buttons. */
1272
2180
  actionsCell(row) {
1273
- return this.dataTable.cell(row.index(), this.columns.length).node();
2181
+ return this.dataTable.cell(row.index(), this.dtIndex(this.columns.length)).node();
1274
2182
  }
1275
2183
  /**
1276
2184
  * What the Delete button does: asks inline, asks with the user's function,
@@ -1300,14 +2208,15 @@ var Tadabut = class {
1300
2208
  return this.newRow?.contains(element) ?? false;
1301
2209
  }
1302
2210
  /**
1303
- * `undefined` for rows DataTables doesn't know, like the error row or
1304
- * a table inside a custom editor.
2211
+ * `undefined` for rows DataTables doesn't know, like a table inside a custom
2212
+ * editor, and for the lines under a row (detail and error), which DataTables
2213
+ * maps back to their row.
1305
2214
  */
1306
2215
  rowIdOf(element) {
1307
2216
  const tr = element.closest("tr");
1308
2217
  if (tr === null || this.rowId === void 0) return;
1309
2218
  const row = this.dataTable.row(tr);
1310
- return row.any() ? row.data()[this.rowId] : void 0;
2219
+ return row.any() && row.node() === tr ? row.data()[this.rowId] : void 0;
1311
2220
  }
1312
2221
  /**
1313
2222
  * Handles the action buttons, the new row's too. One listener on the
@@ -1343,7 +2252,10 @@ var Tadabut = class {
1343
2252
  case "keep":
1344
2253
  this.keepRow(id);
1345
2254
  break;
1346
- case "confirm": this.delete(id);
2255
+ case "confirm":
2256
+ this.delete(id);
2257
+ break;
2258
+ case "detail": this.toggleDetail(id);
1347
2259
  }
1348
2260
  };
1349
2261
  /** Enter saves, Escape cancels, in edited rows and the new row. */
@@ -1379,12 +2291,61 @@ var Tadabut = class {
1379
2291
  updateTotals = () => {
1380
2292
  const rows = this.dataTable.rows(rowsFor(this.totalRows)).data().toArray();
1381
2293
  this.columns.forEach((column, index) => {
1382
- const cell = this.dataTable.column(index).footer();
2294
+ const cell = this.dataTable.column(this.dtIndex(index)).footer();
1383
2295
  if (column.total !== void 0) cell.textContent = totalText(column, rows);
1384
2296
  else if (index === 0) cell.textContent = this.texts.total;
1385
2297
  });
1386
2298
  };
2299
+ /** Keeps the options a select loaded, for `getOptions`. An arrow function, so it can be passed as is. */
2300
+ rememberOptions = (prop, options) => {
2301
+ this.loadedOptions.set(prop, options);
2302
+ };
2303
+ /** Your column's index as DataTables counts it. */
2304
+ dtIndex(index) {
2305
+ return index + this.offset;
2306
+ }
2307
+ /**
2308
+ * The row a click landed on, or `undefined` if it doesn't count: buttons,
2309
+ * inputs, links, the checkbox, ▸ and buttons cells, the new row, a row
2310
+ * being edited, the header, the footer, and the lines under a row.
2311
+ */
2312
+ clickedRow(event) {
2313
+ const target = event.target;
2314
+ if (!(target instanceof Element)) return;
2315
+ if (target.closest("button, input, select, textarea, label, a") !== null) return;
2316
+ if (target.closest("td.tdb-select, td.tdb-detail, td.tdb-actions") !== null) return;
2317
+ if (this.isInNewRow(target)) return;
2318
+ const tr = target.closest("tr");
2319
+ if (tr === null || tr.classList.contains("tdb-row-editing")) return;
2320
+ const row = this.dataTable.row(tr);
2321
+ return row.any() && row.node() === tr ? row : void 0;
2322
+ }
2323
+ /**
2324
+ * Row clicks and double clicks. A double click also opens the row with
2325
+ * `editing.doubleClick`. An arrow function, so `destroy` can remove it.
2326
+ */
2327
+ onRowEvent = (event) => {
2328
+ const row = this.clickedRow(event);
2329
+ if (row === void 0) return;
2330
+ if (event.type === "click") {
2331
+ this.onRowClick?.(row.data(), event);
2332
+ return;
2333
+ }
2334
+ if (this.editing.doubleClick && this.rowId !== void 0) this.edit(row.data()[this.rowId]);
2335
+ this.onRowDoubleClick?.(row.data(), event);
2336
+ };
1387
2337
  };
2338
+ /**
2339
+ * DataTables counts the checkbox column too, so `[[1, 'asc']]` from you means
2340
+ * its column 2. Moves each `[index, direction]` along; the default sorts by
2341
+ * your first column, as without selection. Other shapes of `order` are rare
2342
+ * and left as they are.
2343
+ */
2344
+ function shiftOrder(order, offset) {
2345
+ if (order === void 0) return [[offset, "asc"]];
2346
+ if (!Array.isArray(order)) return order;
2347
+ return order.map((entry) => Array.isArray(entry) && typeof entry[0] === "number" ? [entry[0] + offset, entry[1]] : entry);
2348
+ }
1388
2349
  // src/texts/fr.ts
1389
2350
  /** French. */
1390
2351
  const fr = {
@@ -1397,6 +2358,12 @@ const fr = {
1397
2358
  keep: "Non",
1398
2359
  deleteFailed: "Impossible de supprimer.",
1399
2360
  total: "Total",
2361
+ selectRow: "Sélectionner la ligne",
2362
+ selectAll: "Tout sélectionner",
2363
+ showDetail: "Afficher les détails",
2364
+ hideDetail: "Masquer les détails",
2365
+ detailLoading: "Chargement…",
2366
+ detailFailed: "Impossible de charger les détails.",
1400
2367
  loading: "Chargement…",
1401
2368
  saveFailed: "Impossible d'enregistrer.",
1402
2369
  addFailed: "Impossible d'ajouter.",
@@ -1408,6 +2375,8 @@ const fr = {
1408
2375
  tooSmall: (min) => `Doit être supérieur ou égal à ${min}.`,
1409
2376
  tooLarge: (max) => `Doit être inférieur ou égal à ${max}.`,
1410
2377
  tooEarly: (min) => `Doit être le ${min} ou après.`,
1411
- tooLate: (max) => `Doit être le ${max} ou avant.`
2378
+ tooLate: (max) => `Doit être le ${max} ou avant.`,
2379
+ timeTooEarly: (min) => `Doit être à ${min} ou après.`,
2380
+ timeTooLate: (max) => `Doit être à ${max} ou avant.`
1412
2381
  };
1413
- export { formatMoney as a, defaultMoneyFormat as i, Tadabut as n, en as r, fr as t };
2382
+ export { formatMoney as a, formatTime as c, formatDate as d, parseDate as f, defaultMoneyFormat as i, parseTime as l, Tadabut as n, formatDateTime as o, en as r, parseDateTime as s, fr as t, defaultDateFormat as u };