tadabut 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -24,27 +24,91 @@ const entities = {
24
24
  function escapeHtml(text) {
25
25
  return text.replace(/[&<>"']/g, (char) => entities[char] ?? char);
26
26
  }
27
+ // src/table/elements.ts
28
+ /** The same list at runtime, to check what's read back from the page. */
29
+ const buttonActions = /* @__PURE__ */ new Set([
30
+ "edit",
31
+ "delete",
32
+ "save",
33
+ "cancel",
34
+ "confirm",
35
+ "keep"
36
+ ]);
37
+ /** Whether a `data-tdb-action` is one of ours. */
38
+ function isButtonAction(value) {
39
+ return value !== void 0 && buttonActions.has(value);
40
+ }
41
+ /** Edit or Delete as HTML, for DataTables' `defaultContent`, so everything in it is escaped. */
42
+ function buttonHtml(action, label, extra) {
43
+ return `<button type="button" class="${escapeHtml([
44
+ "tdb-button",
45
+ `tdb-button-${action}`,
46
+ ...extra
47
+ ].join(" "))}" data-tdb-action="${action}">${escapeHtml(label)}</button>`;
48
+ }
49
+ /** Builds a button that replaces Edit and Delete for a while. */
50
+ function actionButton(action, label, extra) {
51
+ const button = document.createElement("button");
52
+ button.type = "button";
53
+ button.classList.add("tdb-button", `tdb-button-${action}`, ...extra);
54
+ button.dataset.tdbAction = action;
55
+ button.textContent = label;
56
+ return button;
57
+ }
58
+ /** Save and Cancel, for an open row. */
59
+ function saveCancelButtons(texts, classNames) {
60
+ return [actionButton("save", texts.save, splitClasses(classNames.button, classNames.save)), actionButton("cancel", texts.cancel, splitClasses(classNames.button, classNames.cancel))];
61
+ }
62
+ /**
63
+ * "Delete this row? [Yes, delete] [No]". `keep` is returned on its own so it
64
+ * can get the focus.
65
+ */
66
+ function deleteQuestion(texts, classNames) {
67
+ const question = document.createElement("span");
68
+ question.className = "tdb-delete-question";
69
+ question.textContent = texts.deleteQuestion;
70
+ const confirm = actionButton("confirm", texts.confirm, splitClasses(classNames.button, classNames.confirm));
71
+ const keep = actionButton("keep", texts.keep, splitClasses(classNames.button, classNames.keep));
72
+ return {
73
+ parts: [
74
+ question,
75
+ confirm,
76
+ keep
77
+ ],
78
+ keep
79
+ };
80
+ }
81
+ /**
82
+ * The message of a save, delete or add error. It gets its own class because
83
+ * Bootstrap colors every cell, which hides a color on the row. Set as text:
84
+ * it often comes from a server.
85
+ */
86
+ function rowErrorMessage(message) {
87
+ const error = document.createElement("div");
88
+ error.className = "tdb-row-error-message";
89
+ error.textContent = message;
90
+ return error;
91
+ }
27
92
  // src/columns/to-datatables.ts
28
- /** The Edit button column. Save and Cancel replace the button while a row is open. */
29
- function actionsColumn(classNames, label) {
93
+ /**
94
+ * The column with the Edit and Delete buttons. While a row is open, Save and
95
+ * Cancel replace them.
96
+ */
97
+ function actionsColumn(actions, classNames, texts) {
30
98
  return {
31
99
  title: "",
32
100
  data: null,
33
101
  className: "tdb-actions",
34
102
  orderable: false,
35
103
  searchable: false,
36
- defaultContent: `<button type="button" class="${escapeHtml([
37
- "tdb-button",
38
- "tdb-button-edit",
39
- ...splitClasses(classNames.button, classNames.edit)
40
- ].join(" "))}" data-tdb-action="edit">${escapeHtml(label)}</button>`
104
+ defaultContent: actions.map((action) => buttonHtml(action, texts[action], splitClasses(classNames.button, classNames[action]))).join("")
41
105
  };
42
106
  }
43
107
  /**
44
108
  * The actions column is always appended last, because the rest of Tadabut
45
- * finds cells by the user's column index.
109
+ * finds cells by the user's column index. No `actions` means no column.
46
110
  */
47
- function toDataTables(columns, withActions, classNames, texts) {
111
+ function toDataTables(columns, actions, classNames, texts) {
48
112
  const converted = columns.map((column) => {
49
113
  const label = labelOf(column);
50
114
  return {
@@ -66,7 +130,7 @@ function toDataTables(columns, withActions, classNames, texts) {
66
130
  }
67
131
  };
68
132
  });
69
- return withActions ? [...converted, actionsColumn(classNames, texts.edit)] : converted;
133
+ return actions.length > 0 ? [...converted, actionsColumn(actions, classNames, texts)] : converted;
70
134
  }
71
135
  /** `render`, then `labelProp`, then a fixed list's label, then the value. */
72
136
  function labelOf(column) {
@@ -97,9 +161,15 @@ const en = {
97
161
  edit: "Edit",
98
162
  save: "Save",
99
163
  cancel: "Cancel",
164
+ delete: "Delete",
165
+ deleteQuestion: "Delete this row?",
166
+ confirm: "Yes, delete",
167
+ keep: "No",
168
+ deleteFailed: "Could not delete.",
100
169
  loading: "Loading…",
101
170
  saveFailed: "Could not save.",
102
171
  loadFailed: "Could not load the options.",
172
+ addFailed: "Could not add.",
103
173
  required: "This field is required.",
104
174
  patternMismatch: "Wrong format.",
105
175
  tooShort: (min) => `Must be at least ${min} characters.`,
@@ -516,6 +586,130 @@ var EditSession = class {
516
586
  if (this.loadErrors.delete(prop)) this.hideError(prop);
517
587
  }
518
588
  };
589
+ // src/table/check-options.ts
590
+ /**
591
+ * Throws on options that can't work together, before anything is built.
592
+ *
593
+ * @throws If a column has an `editor` and there's no `rowId`.
594
+ * @throws If `onDelete` is set and there's no `rowId`.
595
+ * @throws If a hidden column (`visible: false`) has an `editor`.
596
+ * @throws If a select's `labelProp` is its own column.
597
+ */
598
+ function checkOptions(options) {
599
+ if (options.rowId === void 0) {
600
+ if (options.columns.some((column) => column.editor !== void 0)) throw new Error("Tadabut: rowId is required when a column has an editor.");
601
+ if (options.onDelete !== void 0) throw new Error("Tadabut: rowId is required with onDelete.");
602
+ }
603
+ const hiddenEditable = options.columns.find((column) => column.editor !== void 0 && column.visible === false);
604
+ if (hiddenEditable !== void 0) throw new Error(`Tadabut: the "${hiddenEditable.prop}" column can't have both an editor and visible: false.`);
605
+ const selfLabeled = options.columns.find((column) => column.editor?.type === "select" && column.editor.labelProp === column.prop);
606
+ if (selfLabeled !== void 0) throw new Error(`Tadabut: the "${selfLabeled.prop}" column's labelProp can't be "${selfLabeled.prop}" itself.`);
607
+ }
608
+ // src/table/new-row.ts
609
+ /**
610
+ * The row `add()` opens. It lives in its own `<tbody>`, above DataTables'
611
+ * one, so sorting, search and paging never move it. DataTables doesn't know
612
+ * about it, so nothing here goes through DataTables.
613
+ */
614
+ var NewRow = class {
615
+ /** The `<tbody>` to put in the table. Removing it removes everything. */
616
+ body;
617
+ /** The row itself. */
618
+ tr;
619
+ /** Its inputs. */
620
+ session;
621
+ /** The first column with an editor, for the focus. */
622
+ firstProp;
623
+ /** Builds the row. Nothing is shown until `body` is put in the table. */
624
+ constructor(defaults, options) {
625
+ this.body = document.createElement("tbody");
626
+ this.body.classList.add("tdb-new-rows");
627
+ this.tr = document.createElement("tr");
628
+ this.tr.classList.add("tdb-row-new", "tdb-row-editing");
629
+ const cells = [];
630
+ options.columns.forEach((column, index) => {
631
+ if (!options.isVisible(index)) return;
632
+ const cell = document.createElement("td");
633
+ addClasses(cell, [], column.className);
634
+ if (column.editor !== void 0) cells.push({
635
+ column,
636
+ cell
637
+ });
638
+ else cell.textContent = String(defaults[column.prop] ?? "");
639
+ this.tr.append(cell);
640
+ });
641
+ if (options.withButtons) {
642
+ const actionsCell = document.createElement("td");
643
+ actionsCell.classList.add("tdb-actions");
644
+ actionsCell.replaceChildren(...saveCancelButtons(options.texts, options.classNames));
645
+ this.tr.append(actionsCell);
646
+ }
647
+ this.body.append(this.tr);
648
+ this.session = new EditSession(defaults, cells, options.texts);
649
+ this.firstProp = cells[0]?.column.prop;
650
+ }
651
+ /** Whether `onAdd` is running. */
652
+ get saving() {
653
+ return this.session.saving;
654
+ }
655
+ /** Whether an element is inside this row, or its error. */
656
+ contains(element) {
657
+ return this.body.contains(element);
658
+ }
659
+ /** Puts the cursor in the first input. Only works once `body` is in the page. */
660
+ focus() {
661
+ if (this.firstProp !== void 0) this.session.focus(this.firstProp);
662
+ }
663
+ /**
664
+ * Clears the old errors, then checks every field. Shows the new errors and
665
+ * puts the cursor on the first wrong field.
666
+ *
667
+ * @returns Whether every field is valid.
668
+ */
669
+ validate() {
670
+ this.session.clearErrors();
671
+ this.clearError();
672
+ const errors = this.session.validate();
673
+ const [firstInvalid] = errors.keys();
674
+ if (firstInvalid === void 0) return true;
675
+ this.session.showErrors(errors);
676
+ this.session.focus(firstInvalid);
677
+ return false;
678
+ }
679
+ /** The row with what was typed. Validate first. */
680
+ getRow() {
681
+ return this.session.getRow();
682
+ }
683
+ /** Locks or unlocks the row while `onAdd` runs. */
684
+ setSaving(saving) {
685
+ this.session.saving = saving;
686
+ this.tr.inert = saving;
687
+ this.tr.classList.toggle("tdb-row-saving", saving);
688
+ }
689
+ /**
690
+ * Shows the error in a line under the row, like DataTables' child rows
691
+ * (which only work under DataTables' own rows).
692
+ */
693
+ showError(message) {
694
+ this.clearError();
695
+ const cell = document.createElement("td");
696
+ cell.colSpan = this.tr.cells.length;
697
+ cell.append(rowErrorMessage(message));
698
+ const line = document.createElement("tr");
699
+ line.className = "tdb-row-error";
700
+ line.append(cell);
701
+ this.body.append(line);
702
+ }
703
+ /** Removes the error line, if any. */
704
+ clearError() {
705
+ this.body.querySelector("tr.tdb-row-error")?.remove();
706
+ }
707
+ /** Stops pending loads and takes the row out of the table. */
708
+ destroy() {
709
+ this.session.destroy();
710
+ this.body.remove();
711
+ }
712
+ };
519
713
  // src/table/tadabut.ts
520
714
  /**
521
715
  * A DataTables table with row editing.
@@ -549,34 +743,47 @@ var Tadabut = class {
549
743
  texts;
550
744
  /** The user's save callback. */
551
745
  onSave;
552
- /** Whether the Edit/Save/Cancel column exists. */
746
+ /** The user's add callback. */
747
+ onAdd;
748
+ /** The user's delete callback. */
749
+ onDelete;
750
+ /** What the Delete button does before deleting. */
751
+ confirmDelete;
752
+ /** Whether the actions column exists. */
553
753
  hasActions;
554
754
  /** Whether any column has an editor. */
555
755
  hasEditor;
556
756
  /** Open rows, by row id. */
557
757
  sessions = /* @__PURE__ */ new Map();
758
+ /** Rows waiting for `onDelete`, by row id. */
759
+ deleting = /* @__PURE__ */ new Set();
760
+ /** The row `add()` opened, if any. */
761
+ newRow;
558
762
  /**
559
763
  * Builds the table inside `container`, which should be empty.
560
764
  *
561
765
  * @throws If a column has an `editor` and there's no `rowId`.
766
+ * @throws If `onDelete` is set and there's no `rowId`.
562
767
  * @throws If a hidden column (`visible: false`) has an `editor`.
563
768
  * @throws If a select's `labelProp` is its own column.
564
769
  */
565
770
  constructor(container, options) {
771
+ checkOptions(options);
566
772
  this.hasEditor = options.columns.some((column) => column.editor !== void 0);
567
- if (this.hasEditor && options.rowId === void 0) throw new Error("Tadabut: rowId is required when a column has an editor.");
568
- const hiddenEditable = options.columns.find((column) => column.editor !== void 0 && column.visible === false);
569
- if (hiddenEditable !== void 0) throw new Error(`Tadabut: the "${hiddenEditable.prop}" column can't have both an editor and visible: false.`);
570
- const selfLabeled = options.columns.find((column) => column.editor?.type === "select" && column.editor.labelProp === column.prop);
571
- if (selfLabeled !== void 0) throw new Error(`Tadabut: the "${selfLabeled.prop}" column's labelProp can't be "${selfLabeled.prop}" itself.`);
572
773
  this.rowId = options.rowId;
573
774
  this.columns = options.columns;
574
775
  this.editing = {
575
776
  mode: options.editing?.mode ?? "single",
576
777
  button: options.editing?.button ?? true
577
778
  };
578
- this.hasActions = this.hasEditor && this.editing.button;
779
+ const actions = [];
780
+ if (this.hasEditor && this.editing.button) actions.push("edit");
781
+ if (options.onDelete !== void 0) actions.push("delete");
782
+ this.hasActions = actions.length > 0;
579
783
  this.onSave = options.onSave;
784
+ this.onAdd = options.onAdd;
785
+ this.onDelete = options.onDelete;
786
+ this.confirmDelete = options.confirmDelete;
580
787
  this.classNames = options.classNames ?? {};
581
788
  this.texts = {
582
789
  ...en,
@@ -588,7 +795,7 @@ var Tadabut = class {
588
795
  this.dataTable = new DataTable(this.tableEl, {
589
796
  ...options.dataTables,
590
797
  data: [...options.data],
591
- columns: toDataTables(options.columns, this.hasActions, this.classNames, this.texts)
798
+ columns: toDataTables(options.columns, actions, this.classNames, this.texts)
592
799
  });
593
800
  if (this.hasActions) this.tableEl.addEventListener("click", this.onClick);
594
801
  if (this.hasEditor) this.tableEl.addEventListener("keydown", this.onKeyDown);
@@ -596,10 +803,12 @@ var Tadabut = class {
596
803
  /**
597
804
  * Replaces all rows. Sorting, search and the page are kept.
598
805
  *
599
- * Open rows are closed first, and their unsaved changes are lost.
806
+ * Open rows, and the new row, are closed first, and their unsaved changes
807
+ * are lost.
600
808
  */
601
809
  setData(rows) {
602
810
  this.destroySessions();
811
+ this.deleting.clear();
603
812
  this.dataTable.clear().rows.add([...rows]).draw(false);
604
813
  }
605
814
  /**
@@ -607,11 +816,11 @@ var Tadabut = class {
607
816
  *
608
817
  * @param id The value of the row's `rowId` field.
609
818
  * @returns `false` if the row doesn't exist, is already open, another row
610
- * is open in `'single'` mode, nothing is editable, or the row is on a
611
- * page that hasn't been displayed yet.
819
+ * or the new row is open in `'single'` mode, nothing is editable, the row
820
+ * is being deleted, or it's on a page that hasn't been displayed yet.
612
821
  */
613
822
  edit(id) {
614
- if (!this.hasEditor || this.sessions.has(id) || this.editing.mode === "single" && this.sessions.size > 0) return false;
823
+ if (!this.hasEditor || this.sessions.has(id) || this.editing.mode === "single" && (this.sessions.size > 0 || this.newRow !== void 0) || this.deleting.has(id)) return false;
615
824
  const row = this.findRow(id);
616
825
  if (row === void 0 || row.node() === null) return false;
617
826
  const rowIndex = row.index();
@@ -627,7 +836,90 @@ var Tadabut = class {
627
836
  });
628
837
  this.sessions.set(id, new EditSession(row.data(), cells, this.texts));
629
838
  row.node()?.classList.add("tdb-row-editing");
630
- if (this.hasActions) this.dataTable.cell(rowIndex, this.columns.length).node().replaceChildren(actionButton("save", this.texts.save, splitClasses(this.classNames.button, this.classNames.save)), actionButton("cancel", this.texts.cancel, splitClasses(this.classNames.button, this.classNames.cancel)));
839
+ if (this.hasActions) this.actionsCell(row).replaceChildren(...saveCancelButtons(this.texts, this.classNames));
840
+ return true;
841
+ }
842
+ /**
843
+ * Opens an empty row at the top of the table, for a new row. `defaults` are
844
+ * its starting values. The row is only added once Save works.
845
+ *
846
+ * @returns `false` if no column has an editor, a new row is already open,
847
+ * or a row is being edited in `'single'` mode.
848
+ *
849
+ * @example
850
+ * table.add({ country: 'MA' });
851
+ */
852
+ add(defaults = {}) {
853
+ if (!this.hasEditor || this.newRow !== void 0 || this.editing.mode === "single" && this.sessions.size > 0) return false;
854
+ const newRow = new NewRow(defaults, {
855
+ columns: this.columns,
856
+ isVisible: (index) => this.dataTable.column(index).visible(),
857
+ withButtons: this.hasActions,
858
+ texts: this.texts,
859
+ classNames: this.classNames
860
+ });
861
+ this.tableEl.insertBefore(newRow.body, this.dataTable.table().body());
862
+ newRow.focus();
863
+ this.newRow = newRow;
864
+ return true;
865
+ }
866
+ /** Whether a new row is open. */
867
+ isAdding() {
868
+ return this.newRow !== void 0;
869
+ }
870
+ /**
871
+ * Closes the new row and throws it away. Does nothing if there's none, or
872
+ * while it's saving.
873
+ */
874
+ cancelNew() {
875
+ const newRow = this.newRow;
876
+ if (newRow === void 0 || newRow.saving) return;
877
+ newRow.destroy();
878
+ this.newRow = void 0;
879
+ }
880
+ /**
881
+ * Validates the new row, then calls `onAdd`. On success the row joins the
882
+ * table, and the table shows the page it landed on.
883
+ *
884
+ * While `onAdd` runs the row is locked. If it throws, the row stays open
885
+ * and the error message is shown under it.
886
+ *
887
+ * @returns `true` once the row is added. `false` if there's no new row, a
888
+ * field is invalid, it's already saving, or `onAdd` threw.
889
+ * @throws If the saved row has no `rowId` value.
890
+ */
891
+ async saveNew() {
892
+ const newRow = this.newRow;
893
+ if (newRow === void 0 || newRow.saving) return false;
894
+ if (!newRow.validate()) return false;
895
+ const row = newRow.getRow();
896
+ newRow.setSaving(true);
897
+ let saved = row;
898
+ try {
899
+ const result = await this.onAdd?.(row);
900
+ if (result !== void 0) saved = result;
901
+ } catch (error) {
902
+ if (this.newRow !== newRow) return false;
903
+ newRow.setSaving(false);
904
+ newRow.showError(error instanceof Error ? error.message : this.texts.addFailed);
905
+ return false;
906
+ }
907
+ if (this.newRow !== newRow) return false;
908
+ const id = this.rowId === void 0 ? void 0 : saved[this.rowId];
909
+ if (typeof id !== "string" && typeof id !== "number") {
910
+ newRow.setSaving(false);
911
+ throw new Error(`Tadabut: the added row has no "${String(this.rowId)}". Return it from onAdd.`);
912
+ }
913
+ newRow.destroy();
914
+ this.newRow = void 0;
915
+ const added = this.dataTable.row.add({ ...saved });
916
+ this.dataTable.draw(false);
917
+ const position = this.dataTable.rows({
918
+ order: "applied",
919
+ search: "applied"
920
+ }).indexes().toArray().indexOf(added.index());
921
+ const length = this.dataTable.page.len();
922
+ if (position >= 0 && length > 0) this.dataTable.page(Math.floor(position / length)).draw(false);
631
923
  return true;
632
924
  }
633
925
  /**
@@ -640,7 +932,7 @@ var Tadabut = class {
640
932
  if (session.saving) return;
641
933
  session.destroy();
642
934
  this.sessions.delete(id);
643
- this.clearSaveError(id);
935
+ this.clearRowError(id);
644
936
  this.findRow(id)?.node()?.classList.remove("tdb-row-editing");
645
937
  this.findRow(id)?.invalidate("data").draw(false);
646
938
  }
@@ -661,7 +953,7 @@ var Tadabut = class {
661
953
  const session = this.sessions.get(id);
662
954
  if (session === void 0 || session.saving) return false;
663
955
  session.clearErrors();
664
- this.clearSaveError(id);
956
+ this.clearRowError(id);
665
957
  const errors = session.validate();
666
958
  const [firstInvalid] = errors.keys();
667
959
  if (firstInvalid !== void 0) {
@@ -678,7 +970,7 @@ var Tadabut = class {
678
970
  } catch (error) {
679
971
  if (this.sessions.get(id) !== session) return false;
680
972
  this.setSaving(id, false);
681
- this.showSaveError(id, error instanceof Error ? error.message : this.texts.saveFailed);
973
+ this.showRowError(id, error instanceof Error ? error.message : this.texts.saveFailed);
682
974
  return false;
683
975
  }
684
976
  if (this.sessions.get(id) !== session) return false;
@@ -689,11 +981,44 @@ var Tadabut = class {
689
981
  this.setSaving(id, false);
690
982
  return true;
691
983
  }
984
+ /**
985
+ * Calls `onDelete`, then removes the row. Never asks first: only the
986
+ * Delete button does.
987
+ *
988
+ * While `onDelete` runs the row is locked. If it throws, the row stays and
989
+ * the error message is shown under it.
990
+ *
991
+ * @returns `true` once the row is removed. `false` if the row doesn't
992
+ * exist, is open for editing, is already being deleted, or `onDelete`
993
+ * threw.
994
+ */
995
+ async delete(id) {
996
+ const row = this.findRow(id);
997
+ if (row === void 0 || this.sessions.has(id) || this.deleting.has(id)) return false;
998
+ this.clearRowError(id);
999
+ this.deleting.add(id);
1000
+ this.setSaving(id, true);
1001
+ try {
1002
+ await this.onDelete?.(row.data());
1003
+ } catch (error) {
1004
+ if (!this.deleting.has(id)) return false;
1005
+ this.deleting.delete(id);
1006
+ this.setSaving(id, false);
1007
+ this.keepRow(id);
1008
+ this.showRowError(id, error instanceof Error ? error.message : this.texts.deleteFailed);
1009
+ return false;
1010
+ }
1011
+ if (!this.deleting.has(id)) return false;
1012
+ this.deleting.delete(id);
1013
+ this.findRow(id)?.remove().draw(false);
1014
+ return true;
1015
+ }
692
1016
  /** Removes the table. Open rows are closed without saving. */
693
1017
  destroy() {
694
1018
  this.tableEl.removeEventListener("click", this.onClick);
695
1019
  this.tableEl.removeEventListener("keydown", this.onKeyDown);
696
1020
  this.destroySessions();
1021
+ this.deleting.clear();
697
1022
  this.dataTable.destroy();
698
1023
  this.tableEl.remove();
699
1024
  }
@@ -704,10 +1029,15 @@ var Tadabut = class {
704
1029
  const row = this.dataTable.row((_index, data) => data[rowId] === id);
705
1030
  return row.any() ? row : void 0;
706
1031
  }
707
- /** Only for when the rows are about to go away: cells aren't restored. */
1032
+ /**
1033
+ * Closes every open row, the new one too. Only for when the rows are about
1034
+ * to go away: cells aren't restored.
1035
+ */
708
1036
  destroySessions() {
709
1037
  for (const session of this.sessions.values()) session.destroy();
710
1038
  this.sessions.clear();
1039
+ this.newRow?.destroy();
1040
+ this.newRow = void 0;
711
1041
  }
712
1042
  /** Also works after the session is gone, so a row can always be unlocked. */
713
1043
  setSaving(id, saving) {
@@ -719,23 +1049,47 @@ var Tadabut = class {
719
1049
  tr.classList.toggle("tdb-row-saving", saving);
720
1050
  }
721
1051
  }
1052
+ /** Shows a save or delete error in a child row under the row. */
1053
+ showRowError(id, message) {
1054
+ this.findRow(id)?.child(rowErrorMessage(message), "tdb-row-error").show();
1055
+ }
1056
+ /** Removes the save or delete error under a row, if any. */
1057
+ clearRowError(id) {
1058
+ this.findRow(id)?.child.remove();
1059
+ }
1060
+ /** The last cell of a row, the one with the buttons. */
1061
+ actionsCell(row) {
1062
+ return this.dataTable.cell(row.index(), this.columns.length).node();
1063
+ }
722
1064
  /**
723
- * Shows the error in a child row under the row. The message gets its own
724
- * class because Bootstrap colors every cell, which hides a color on the
725
- * `<tr>`. Set as text: it often comes from a server.
1065
+ * What the Delete button does: asks inline, asks with the user's function,
1066
+ * or deletes right away.
726
1067
  */
727
- showSaveError(id, message) {
728
- const error = document.createElement("div");
729
- error.className = "tdb-save-error-message";
730
- error.textContent = message;
731
- this.findRow(id)?.child(error, "tdb-save-error").show();
1068
+ async askDelete(id) {
1069
+ const row = this.findRow(id);
1070
+ if (row === void 0) return;
1071
+ if (this.confirmDelete === false) {
1072
+ await this.delete(id);
1073
+ return;
1074
+ }
1075
+ if (this.confirmDelete !== void 0) {
1076
+ if (await this.confirmDelete(row.data())) await this.delete(id);
1077
+ return;
1078
+ }
1079
+ const { parts, keep } = deleteQuestion(this.texts, this.classNames);
1080
+ this.actionsCell(row).replaceChildren(...parts);
1081
+ keep.focus();
732
1082
  }
733
- /** Removes the error row under a row, if any. */
734
- clearSaveError(id) {
735
- this.findRow(id)?.child.remove();
1083
+ /** Puts Edit and Delete back after No. */
1084
+ keepRow(id) {
1085
+ this.findRow(id)?.invalidate("data").draw(false);
1086
+ }
1087
+ /** Whether an element is inside the new row, or its error. */
1088
+ isInNewRow(element) {
1089
+ return this.newRow?.contains(element) ?? false;
736
1090
  }
737
1091
  /**
738
- * `undefined` for rows DataTables doesn't know, like the save error row or
1092
+ * `undefined` for rows DataTables doesn't know, like the error row or
739
1093
  * a table inside a custom editor.
740
1094
  */
741
1095
  rowIdOf(element) {
@@ -745,29 +1099,56 @@ var Tadabut = class {
745
1099
  return row.any() ? row.data()[this.rowId] : void 0;
746
1100
  }
747
1101
  /**
748
- * Handles Edit, Save and Cancel. One listener on the table, because
749
- * DataTables keeps replacing rows. An arrow function, so `this` stays
750
- * bound and `destroy` can remove it.
1102
+ * Handles the action buttons, the new row's too. One listener on the
1103
+ * table, because DataTables keeps replacing rows. An arrow function, so
1104
+ * `this` stays bound and `destroy` can remove it.
751
1105
  */
752
1106
  onClick = (event) => {
753
1107
  if (!(event.target instanceof Element)) return;
754
1108
  const button = event.target.closest("[data-tdb-action]");
755
- const id = button ? this.rowIdOf(button) : void 0;
756
- if (!button || id === void 0) return;
757
- switch (button.dataset.tdbAction) {
1109
+ if (button === null) return;
1110
+ const action = button.dataset.tdbAction;
1111
+ if (!isButtonAction(action)) return;
1112
+ if (this.isInNewRow(button)) {
1113
+ if (action === "save") this.saveNew();
1114
+ else if (action === "cancel") this.cancelNew();
1115
+ return;
1116
+ }
1117
+ const id = this.rowIdOf(button);
1118
+ if (id === void 0) return;
1119
+ switch (action) {
758
1120
  case "edit":
759
1121
  this.edit(id);
760
1122
  break;
761
1123
  case "save":
762
1124
  this.save(id);
763
1125
  break;
764
- case "cancel": this.cancel(id);
1126
+ case "cancel":
1127
+ this.cancel(id);
1128
+ break;
1129
+ case "delete":
1130
+ this.askDelete(id);
1131
+ break;
1132
+ case "keep":
1133
+ this.keepRow(id);
1134
+ break;
1135
+ case "confirm": this.delete(id);
765
1136
  }
766
1137
  };
767
- /** Enter saves, Escape cancels. */
1138
+ /** Enter saves, Escape cancels, in edited rows and the new row. */
768
1139
  onKeyDown = (event) => {
769
1140
  if (event.defaultPrevented) return;
770
1141
  if (!(event.target instanceof Element) || event.target.closest("button")) return;
1142
+ if (this.isInNewRow(event.target)) {
1143
+ if (event.key === "Enter") {
1144
+ event.preventDefault();
1145
+ this.saveNew();
1146
+ } else if (event.key === "Escape") {
1147
+ event.preventDefault();
1148
+ this.cancelNew();
1149
+ }
1150
+ return;
1151
+ }
771
1152
  const id = this.rowIdOf(event.target);
772
1153
  if (id === void 0 || !this.sessions.has(id)) return;
773
1154
  switch (event.key) {
@@ -781,23 +1162,20 @@ var Tadabut = class {
781
1162
  }
782
1163
  };
783
1164
  };
784
- /** Builds a Save or Cancel button. */
785
- function actionButton(action, label, extra) {
786
- const button = document.createElement("button");
787
- button.type = "button";
788
- button.classList.add("tdb-button", `tdb-button-${action}`, ...extra);
789
- button.dataset.tdbAction = action;
790
- button.textContent = label;
791
- return button;
792
- }
793
1165
  // src/texts/fr.ts
794
1166
  /** French. */
795
1167
  const fr = {
796
1168
  edit: "Modifier",
797
1169
  save: "Enregistrer",
798
1170
  cancel: "Annuler",
1171
+ delete: "Supprimer",
1172
+ deleteQuestion: "Supprimer cette ligne\xA0?",
1173
+ confirm: "Oui, supprimer",
1174
+ keep: "Non",
1175
+ deleteFailed: "Impossible de supprimer.",
799
1176
  loading: "Chargement…",
800
1177
  saveFailed: "Impossible d'enregistrer.",
1178
+ addFailed: "Impossible d'ajouter.",
801
1179
  loadFailed: "Impossible de charger les options.",
802
1180
  required: "Ce champ est obligatoire.",
803
1181
  patternMismatch: "Format incorrect.",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tadabut",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Typed wrapper for DataTables with row editing, rich inputs and chained selects.",
5
5
  "keywords": [
6
6
  "datatables",
@@ -51,7 +51,7 @@
51
51
  "publint": "^0.3.25",
52
52
  "react": "^19.3.1",
53
53
  "react-dom": "^19.3.1",
54
- "tsdown": "^0.23.4",
54
+ "tsdown": "^0.23.5",
55
55
  "typescript": "^7.0.2",
56
56
  "vite": "^8.3.5",
57
57
  "vitest": "^5.1.0"