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.
package/README.md CHANGED
@@ -21,6 +21,8 @@ Tadabut wraps [DataTables](https://datatables.net) and adds what it doesn't give
21
21
  DataTables is great for showing data. Editing that data inside the table is a different story: you either buy the Editor extension or write a lot of code yourself. Tadabut is that code, written once.
22
22
 
23
23
  - Edit a row in place, then save or cancel. Saving can be async. If it fails, the row stays open with what the user typed, so nothing is lost.
24
+ - Add a row from your own button: it opens at the top of the table, with the same inputs and validation.
25
+ - Delete a row, with a question first, or your own popup.
24
26
  - Text, number, date, checkbox and select inputs, with validation.
25
27
  - Selects that depend on another field, like country and city. Old requests get cancelled when the user changes their mind.
26
28
  - Fully typed. The table knows what your rows look like, so a typo in a column name is a type error.
@@ -254,7 +256,7 @@ In React, keep `dataTables` outside your component or in a `useMemo`, like `colu
254
256
 
255
257
  ### Texts and translations
256
258
 
257
- Tadabut's own texts (the Edit, Save and Cancel buttons, "Loading…", and the error messages) are in English by default. French comes built in:
259
+ Tadabut's own texts (the Edit, Save, Cancel and Delete buttons, the delete question, "Loading…", and the error messages) are in English by default. French comes built in:
258
260
 
259
261
  ```ts
260
262
  import { Tadabut, fr } from 'tadabut';
@@ -273,8 +275,13 @@ texts: { edit: 'Bearbeiten', save: 'Speichern', cancel: 'Abbrechen' }
273
275
  | Key | English |
274
276
  | ------------------------ | ------------------------------- |
275
277
  | `edit`, `save`, `cancel` | Edit, Save, Cancel |
278
+ | `delete` | Delete |
279
+ | `deleteQuestion` | Delete this row? |
280
+ | `confirm`, `keep` | Yes, delete / No |
276
281
  | `loading` | Loading… |
277
282
  | `saveFailed` | Could not save. |
283
+ | `addFailed` | Could not add. |
284
+ | `deleteFailed` | Could not delete. |
278
285
  | `loadFailed` | Could not load the options. |
279
286
  | `required` | This field is required. |
280
287
  | `patternMismatch` | Wrong format. |
@@ -290,7 +297,7 @@ texts: {
290
297
  }
291
298
  ```
292
299
 
293
- `saveFailed` only shows when `onSave` throws something that isn't an `Error`. When it throws an `Error`, its own message is shown.
300
+ `saveFailed`, `addFailed` and `deleteFailed` only show when `onSave`, `onAdd` or `onDelete` throws something that isn't an `Error`. When it throws an `Error`, its own message is shown.
294
301
 
295
302
  DataTables' own texts (search, paging, "Showing 1 to 10") are set separately, with `dataTables.language`. See [DataTables settings](#datatables-settings).
296
303
 
@@ -300,24 +307,30 @@ In React, `texts={fr}` is fine. A new object on every render (like `texts={{ ...
300
307
 
301
308
  Tadabut doesn't ship any CSS. Everything it creates gets these classes, so you can style it however you want:
302
309
 
303
- | Class | Used on |
304
- | ------------------------ | ------------------------------------------------- |
305
- | `tdb-input` | every input |
306
- | `tdb-input-text` | text inputs |
307
- | `tdb-input-number` | number inputs |
308
- | `tdb-input-date` | date inputs |
309
- | `tdb-input-checkbox` | checkboxes |
310
- | `tdb-input-select` | selects |
311
- | `tdb-error` | a field's error message, under its input |
312
- | `tdb-save-error` | the line (`<tr>`) under a row that failed to save |
313
- | `tdb-save-error-message` | the message inside that line |
314
- | `tdb-row-editing` | a row while it's being edited |
315
- | `tdb-row-saving` | a row while it's being saved |
316
- | `tdb-actions` | the column with the buttons, header too |
317
- | `tdb-button` | every button |
318
- | `tdb-button-edit` | the Edit button |
319
- | `tdb-button-save` | the Save button |
320
- | `tdb-button-cancel` | the Cancel button |
310
+ | Class | Used on |
311
+ | ----------------------- | ----------------------------------------------------------- |
312
+ | `tdb-input` | every input |
313
+ | `tdb-input-text` | text inputs |
314
+ | `tdb-input-number` | number inputs |
315
+ | `tdb-input-date` | date inputs |
316
+ | `tdb-input-checkbox` | checkboxes |
317
+ | `tdb-input-select` | selects |
318
+ | `tdb-error` | a field's error message, under its input |
319
+ | `tdb-row-error` | the line (`<tr>`) under a row that failed to save or delete |
320
+ | `tdb-row-error-message` | the message inside that line |
321
+ | `tdb-row-editing` | a row while it's being edited, and the new row |
322
+ | `tdb-row-saving` | a row while it's being saved, added or deleted |
323
+ | `tdb-row-new` | the new row `add()` opens |
324
+ | `tdb-new-rows` | the `<tbody>` it lives in, above the others |
325
+ | `tdb-actions` | the column with the buttons, header too |
326
+ | `tdb-button` | every button |
327
+ | `tdb-button-edit` | the Edit button |
328
+ | `tdb-button-save` | the Save button |
329
+ | `tdb-button-cancel` | the Cancel button |
330
+ | `tdb-button-delete` | the Delete button |
331
+ | `tdb-delete-question` | the "Delete this row?" text |
332
+ | `tdb-button-confirm` | the "Yes, delete" button |
333
+ | `tdb-button-keep` | the "No" button |
321
334
 
322
335
  To use Bootstrap, Tailwind or anything else, add your own classes. They always go next to the `tdb-` ones, never instead of them. There are two places:
323
336
 
@@ -344,13 +357,16 @@ const table = new Tadabut(container, {
344
357
  });
345
358
  ```
346
359
 
347
- | `classNames` key | Added to |
348
- | ---------------- | --------------------------------- |
349
- | `table` | the `<table>` |
350
- | `button` | the Edit, Save and Cancel buttons |
351
- | `edit` | the Edit button only |
352
- | `save` | the Save button only |
353
- | `cancel` | the Cancel button only |
360
+ | `classNames` key | Added to |
361
+ | ---------------- | ----------------------------- |
362
+ | `table` | the `<table>` |
363
+ | `button` | every button |
364
+ | `edit` | the Edit button only |
365
+ | `save` | the Save button only |
366
+ | `cancel` | the Cancel button only |
367
+ | `delete` | the Delete button only |
368
+ | `confirm` | the "Yes, delete" button only |
369
+ | `keep` | the "No" button only |
354
370
 
355
371
  All of them are optional. Tadabut doesn't know any CSS framework: it adds the classes you give it, and nothing else. If you use Tailwind: it only keeps classes it finds in your own files. Classes in your column config count, so they work.
356
372
 
@@ -407,6 +423,9 @@ const table = new Tadabut(container, {
407
423
  edit: 'btn-outline-primary',
408
424
  save: 'btn-primary',
409
425
  cancel: 'btn-outline-secondary',
426
+ delete: 'btn-outline-danger',
427
+ confirm: 'btn-danger',
428
+ keep: 'btn-outline-secondary',
410
429
  },
411
430
  });
412
431
  ```
@@ -417,7 +436,7 @@ Error messages and the rows being edited need a few lines of your own CSS:
417
436
  /* Errors in Bootstrap's red. Use the message's class, not the row's:
418
437
  Bootstrap sets a color on every table cell. */
419
438
  .tdb-error,
420
- .tdb-save-error-message {
439
+ .tdb-row-error-message {
421
440
  color: var(--bs-form-invalid-color);
422
441
  font-size: 0.875em;
423
442
  }
@@ -431,6 +450,15 @@ Error messages and the rows being edited need a few lines of your own CSS:
431
450
  .tdb-row-saving {
432
451
  opacity: 0.5;
433
452
  }
453
+
454
+ /* Space between the buttons, and after "Delete this row?". */
455
+ .tdb-button + .tdb-button {
456
+ margin-left: 0.25rem;
457
+ }
458
+
459
+ .tdb-delete-question {
460
+ margin-right: 0.5rem;
461
+ }
434
462
  ```
435
463
 
436
464
  > [!TIP]
@@ -587,6 +615,7 @@ How it works:
587
615
  - A cleared field is `null`, and the functions below it still run. That's why the example checks `row.countryId === null`. Returning `[]` right away costs nothing.
588
616
  - If the user changes the country again before the cities come back, the old request is cancelled through `signal`. Pass it to `fetch` so the request really stops. Even if you don't, a late answer is thrown away.
589
617
  - Cancelling or saving the row, `setData` and `destroy` cancel every request still running.
618
+ - In a new row (see [Adding](#adding)), nothing is picked yet, so the functions first run with an empty parent. Another reason to return `[]` for `null`.
590
619
 
591
620
  If `options` throws, the select stays empty and "Could not load the options." shows under it. The row can't be saved while that message is there. Changing the field it depends on tries again, or the user can cancel the row.
592
621
 
@@ -646,6 +675,103 @@ The table's data only changes when saving works, so there's nothing to undo when
646
675
 
647
676
  `onSave` is optional. Without it, saving just updates the table.
648
677
 
678
+ ### Adding
679
+
680
+ Call `add()` from your own button. An empty row opens at the top of the table, with the same inputs, validation and Save/Cancel as an edited row. Save calls `onAdd`.
681
+
682
+ ```ts
683
+ async function createEmployee(row: Partial<Employee>): Promise<Employee> {
684
+ const res = await fetch('/api/employees', {
685
+ method: 'POST',
686
+ headers: { 'Content-Type': 'application/json' },
687
+ body: JSON.stringify(row),
688
+ });
689
+
690
+ if (!res.ok) throw new Error('Could not add the employee');
691
+
692
+ return res.json(); // the row with its new id
693
+ }
694
+
695
+ const table = new Tadabut(container, {
696
+ data: employees,
697
+ rowId: 'id',
698
+ columns,
699
+ onSave: saveEmployee,
700
+ onAdd: createEmployee,
701
+ });
702
+
703
+ addButton.addEventListener('click', () => table.add());
704
+ ```
705
+
706
+ What happens:
707
+
708
+ 1. `add()` opens the row at the top, with the cursor in the first input. Sorting, search and paging never move it: it lives in its own `<tbody>`, above the table's rows.
709
+ 2. Save, or <kbd>Enter</kbd>, validates the fields. Cancel, or <kbd>Escape</kbd>, throws the row away.
710
+ 3. `onAdd` gets the typed row. The row is locked while it runs.
711
+ 4. If `onAdd` works, the row joins the table, and the table shows the page it landed on. If the search box hides it, the table stays where it is.
712
+ 5. If `onAdd` throws, the row stays open with what the user typed, and your error message shows under it.
713
+
714
+ **What `onAdd` gets and returns:**
715
+
716
+ - It gets a `Partial` row, because the row isn't saved yet: the id, and columns without an editor, are only there if you gave them to `add()`. TypeScript makes you check them.
717
+ - Return the saved row, usually with the id the server made, or nothing to keep the row as typed.
718
+ - Either way, the row must have its `rowId`. If it doesn't, Tadabut throws `Tadabut: the added row has no "id". Return it from onAdd.` That's a mistake in your code, so it goes to the console, and the row stays open.
719
+ - Without `onAdd`, the row is added as typed. That's fine for a table that only lives in the page, as long as the id comes from an input or from `add({ id })`.
720
+
721
+ **Starting values:** `table.add({ country: 'MA', active: true })`. Inputs start with them, and columns without an editor show them as text. Those cells don't use the column's `render`.
722
+
723
+ **Rules:**
724
+
725
+ - One new row at a time. `add()` returns `false` if one is already open.
726
+ - In `'single'` mode, the new row counts as the open row: you can't add while a row is edited, and you can't edit while the new row is open. In `'multiple'` mode, both work together.
727
+ - `setData` and `destroy` throw the new row away, like any open row.
728
+
729
+ ### Deleting
730
+
731
+ Give the table an `onDelete`, and each row gets a Delete button next to Edit. It can be async, like `onSave`.
732
+
733
+ ```ts
734
+ async function deleteEmployee(row: Employee) {
735
+ const res = await fetch(`/api/employees/${row.id}`, { method: 'DELETE' });
736
+
737
+ if (!res.ok) throw new Error('Could not delete the employee');
738
+ }
739
+
740
+ const table = new Tadabut(container, {
741
+ data: employees,
742
+ rowId: 'id',
743
+ columns,
744
+ onSave: saveEmployee,
745
+ onDelete: deleteEmployee,
746
+ });
747
+ ```
748
+
749
+ What happens when you click Delete:
750
+
751
+ 1. The buttons are replaced by "Delete this row? [Yes, delete] [No]". The cursor goes to No, so pressing <kbd>Enter</kbd> by reflex doesn't delete anything.
752
+ 2. No puts Edit and Delete back.
753
+ 3. Yes calls `onDelete` with the row. The row is locked while it runs, and gets the `tdb-row-saving` class.
754
+ 4. If `onDelete` works, the row is removed. You stay on the same page.
755
+ 5. If `onDelete` throws, the row stays, and your error message shows under it.
756
+
757
+ A row that's being edited has Save and Cancel instead, so it can't be deleted halfway through an edit. `onDelete` needs a `rowId`, and Tadabut throws an error without one.
758
+
759
+ #### Your own question: `confirmDelete`
760
+
761
+ ```ts
762
+ confirmDelete: false, // delete right away, no question
763
+
764
+ confirmDelete: (row) => window.confirm(`Delete ${row.name}?`), // the browser's popup
765
+
766
+ // any modal, as long as it returns true to delete
767
+ confirmDelete: async (row) => {
768
+ const result = await Swal.fire({ title: `Delete ${row.name}?`, showCancelButton: true });
769
+ return result.isConfirmed;
770
+ },
771
+ ```
772
+
773
+ Leave it out for the question in the row. To only change its words, use `texts` (`deleteQuestion`, `confirm`, `keep`). To style it, use `classNames` (`delete`, `confirm`, `keep`).
774
+
649
775
  ### Editing options
650
776
 
651
777
  When at least one column has an `editor`, the table gets one more column at the end, with an Edit button in each row. While a row is being edited, its Edit button is replaced by Save and Cancel. The labels can be changed with `texts`.
@@ -667,7 +793,7 @@ const table = new Tadabut(container, {
667
793
 
668
794
  - `'single'` mode: one row at a time. You can't start a new edit while another row is open.
669
795
  - `'multiple'` mode: several rows can be open. Each one saves on its own, so `onSave` runs once per row.
670
- - `button: false`: no buttons column. Start edits from your own code. <kbd>Enter</kbd> and <kbd>Escape</kbd> still work.
796
+ - `button: false`: no Edit button. Start edits from your own code. <kbd>Enter</kbd> and <kbd>Escape</kbd> still work. With `onDelete`, the column stays, with only the Delete button.
671
797
 
672
798
  ### Controlling it from code
673
799
 
@@ -676,6 +802,12 @@ table.edit(5); // start editing the row with id 5
676
802
  await table.save(5); // validate and save it
677
803
  table.cancel(5); // cancel and restore its old values
678
804
  table.isEditing(5); // true while row 5 is open
805
+ await table.delete(5); // call onDelete, then remove the row
806
+
807
+ table.add({ country: 'MA' }); // open a new row at the top
808
+ await table.saveNew(); // validate it and call onAdd
809
+ table.cancelNew(); // throw the new row away
810
+ table.isAdding(); // true while the new row is open
679
811
 
680
812
  table.setData(newEmployees); // replace all rows, keeps sorting and search
681
813
  table.destroy(); // remove everything Tadabut created
@@ -687,7 +819,11 @@ table.destroy(); // remove everything Tadabut created
687
819
 
688
820
  `cancel` does nothing if the row isn't being edited, or while it's saving.
689
821
 
690
- `setData` and `destroy` cancel any row being edited first. Unsaved changes are lost.
822
+ `delete` never asks first: only the Delete button does. It returns a promise of `true` once the row is removed, `false` if it wasn't: the row doesn't exist, it's being edited, it's already being deleted, or `onDelete` failed. Without `onDelete`, it just removes the row.
823
+
824
+ `add` returns `true` if the new row opened, `false` if one is already open, no column has an editor, or a row is being edited in `'single'` mode. `saveNew` works like `save`, and throws if the saved row has no id. `cancelNew` does nothing while `onAdd` runs.
825
+
826
+ `setData` and `destroy` cancel any row being edited, and the new row, first. Unsaved changes are lost.
691
827
 
692
828
  <kbd>Enter</kbd> saves the row you're in. <kbd>Escape</kbd> cancels it. If something else already used the key, like Select2 picking an option with <kbd>Enter</kbd>, Tadabut leaves it alone.
693
829
 
@@ -733,8 +869,26 @@ async function saveEmployee(row: Employee): Promise<void> {
733
869
  if (!res.ok) throw new Error('Could not save the employee');
734
870
  }
735
871
 
872
+ async function createEmployee(row: Partial<Employee>): Promise<Employee> {
873
+ const res = await fetch('/api/employees', {
874
+ method: 'POST',
875
+ headers: { 'Content-Type': 'application/json' },
876
+ body: JSON.stringify(row),
877
+ });
878
+
879
+ if (!res.ok) throw new Error('Could not add the employee');
880
+
881
+ return res.json();
882
+ }
883
+
884
+ async function deleteEmployee(row: Employee): Promise<void> {
885
+ const res = await fetch(`/api/employees/${row.id}`, { method: 'DELETE' });
886
+
887
+ if (!res.ok) throw new Error('Could not delete the employee');
888
+ }
889
+
736
890
  export default function Employees() {
737
- const [employees] = useState<Employee[]>([
891
+ const [employees, setEmployees] = useState<Employee[]>([
738
892
  { id: 1, name: 'Amina', countryId: 1 },
739
893
  { id: 2, name: 'Paul', countryId: 2 },
740
894
  ]);
@@ -745,6 +899,9 @@ export default function Employees() {
745
899
  <button type="button" onClick={() => tableRef.current?.edit(1)}>
746
900
  Edit Amina
747
901
  </button>
902
+ <button type="button" onClick={() => tableRef.current?.add()}>
903
+ Add an employee
904
+ </button>
748
905
 
749
906
  <Tadabut
750
907
  ref={tableRef}
@@ -753,6 +910,15 @@ export default function Employees() {
753
910
  columns={columns}
754
911
  editing={{ mode: 'multiple' }}
755
912
  onSave={(row) => saveEmployee(row)}
913
+ onAdd={async (row) => {
914
+ const saved = await createEmployee(row);
915
+ setEmployees((current) => [...current, saved]);
916
+ return saved;
917
+ }}
918
+ onDelete={async (row) => {
919
+ await deleteEmployee(row);
920
+ setEmployees((current) => current.filter((e) => e.id !== row.id));
921
+ }}
756
922
  />
757
923
  </>
758
924
  );
@@ -760,9 +926,10 @@ export default function Employees() {
760
926
  ```
761
927
 
762
928
  - When `employees` changes, the table updates in place. It doesn't get rebuilt.
763
- - `onSave` can be a new function on every render. The table always calls the latest one.
929
+ - `onSave`, `onAdd`, `onDelete` and `confirmDelete` can be new functions on every render. The table always calls the latest ones.
930
+ - In `onAdd` and `onDelete`, update your state too, like above. Otherwise the next time `data` changes, the new row disappears, or the deleted one comes back.
764
931
  - `editing` can be a new object on every render too. The table is only rebuilt when `mode` or `button` really change. Changing `columns`, `rowId` or `editing` closes any row being edited.
765
- - The ref has `edit`, `save`, `cancel` and `isEditing`, the same as the core. Before the table is built, or after it's gone, `edit` and `save` give `false` and `cancel` does nothing.
932
+ - The ref has the same methods as the core: `edit`, `save`, `cancel`, `delete`, `isEditing`, `add`, `saveNew`, `cancelNew` and `isAdding`. Before the table is built, or after it's gone, they give `false` and `cancel` and `cancelNew` do nothing.
766
933
  - There is no `setData` on the ref. To change the rows, change `data`.
767
934
 
768
935
  ## Roadmap
@@ -783,10 +950,11 @@ Done:
783
950
  - [x] Pass DataTables settings through (paging, page sizes, default order, language, extensions like Buttons), and column `width`, `visible`, `orderable`, `searchable` and `className`
784
951
  - [x] Selects that also save their label in the row (`labelProp`), so the cell shows the new label after a save
785
952
  - [x] Translations for Tadabut's own texts (buttons and error messages), French built in
953
+ - [x] Deleting rows, with a question first that you can replace (`confirmDelete`)
954
+ - [x] Adding new rows, at the top of the table (`add()` and `onAdd`)
786
955
 
787
956
  Next, roughly in this order:
788
957
 
789
- - [ ] Adding new rows, and deleting rows, with a confirmation step
790
958
  - [ ] Checkboxes with your own values, like `'O'` and `'N'` instead of `true` and `false`
791
959
  - [ ] Money inputs, formatted while typing (`12 500.00`)
792
960
  - [ ] Dates as `dd/mm/yyyy`, in the input and when sorting
@@ -795,7 +963,7 @@ Next, roughly in this order:
795
963
  - [ ] More events: when editing starts, after saving, row click and double click
796
964
  - [ ] Detail rows that open under a row
797
965
  - [ ] Time and read-only inputs
798
- - [ ] Methods to read rows (`getData`, `getRow`), add and remove rows from code, and reach the DataTables API
966
+ - [ ] Methods to read rows (`getData`, `getRow`), put a row in directly without opening it, and reach the DataTables API
799
967
  - [ ] Keyboard navigation and theming
800
968
 
801
969
  Later: popup editing, changing many rows in one go, server-side mode, Vue and jQuery adapters.
@@ -106,10 +106,22 @@ type Texts = {
106
106
  readonly save: string;
107
107
  /** The Cancel button. */
108
108
  readonly cancel: string;
109
+ /** The Delete button. */
110
+ readonly delete: string;
111
+ /** Asked in the row before deleting it. */
112
+ readonly deleteQuestion: string;
113
+ /** The button that confirms a delete. */
114
+ readonly confirm: string;
115
+ /** The button that keeps the row instead. */
116
+ readonly keep: string;
117
+ /** Under a row when `onDelete` throws something that isn't an `Error`. */
118
+ readonly deleteFailed: string;
109
119
  /** Shown in a select while its options load. */
110
120
  readonly loading: string;
111
121
  /** Under a row when `onSave` throws something that isn't an `Error`. */
112
122
  readonly saveFailed: string;
123
+ /** Under a new row when `onAdd` throws something that isn’t an `Error`. */
124
+ readonly addFailed: string;
113
125
  /** Under a select whose options failed to load. */
114
126
  readonly loadFailed: string;
115
127
  /** An empty field with `required`. */
@@ -294,7 +306,8 @@ type EditingOptions = {
294
306
  readonly mode?: "single" | "multiple";
295
307
  /**
296
308
  * Adds an Edit/Save/Cancel column at the end. Defaults to `true`. Turn it
297
- * off if you open rows yourself with `edit()`.
309
+ * off if you open rows yourself with `edit()`. The Delete button still
310
+ * shows if `onDelete` is set.
298
311
  */
299
312
  readonly button?: boolean;
300
313
  };
@@ -310,12 +323,15 @@ type EditingOptions = {
310
323
  * edit: 'btn-outline-primary',
311
324
  * save: 'btn-primary',
312
325
  * cancel: 'btn-outline-secondary',
326
+ * delete: 'btn-outline-danger',
327
+ * confirm: 'btn-danger',
328
+ * keep: 'btn-outline-secondary',
313
329
  * }
314
330
  */
315
331
  type TableClassNames = {
316
332
  /** On the `<table>`. */
317
333
  readonly table?: string;
318
- /** All three buttons. */
334
+ /** Every button. */
319
335
  readonly button?: string;
320
336
  /** Edit button only. */
321
337
  readonly edit?: string;
@@ -323,6 +339,12 @@ type TableClassNames = {
323
339
  readonly save?: string;
324
340
  /** Cancel button only. */
325
341
  readonly cancel?: string;
342
+ /** Delete button only. */
343
+ readonly delete?: string;
344
+ /** The button that confirms a delete. */
345
+ readonly confirm?: string;
346
+ /** The button that keeps the row instead. */
347
+ readonly keep?: string;
326
348
  };
327
349
  /**
328
350
  * Any {@link https://datatables.net/reference/option/ | DataTables option},
@@ -366,6 +388,43 @@ type TadabutOptions<Row extends object> = {
366
388
  * save: the row stays open and the error message is shown under it.
367
389
  */
368
390
  readonly onSave?: (row: Row, context: SaveContext<Row>) => Row | void | Promise<Row | void>;
391
+ /**
392
+ * Called with a new row once it passes validation. May be async.
393
+ *
394
+ * Return the saved row, usually with its id from the server, or nothing
395
+ * to keep the row as typed. Either way it must have its `rowId` field, or
396
+ * Tadabut throws an error. Throw to reject the add: the row stays open and
397
+ * the error message is shown under it.
398
+ *
399
+ * The row is partial because it isn't saved yet: the id, and columns
400
+ * without an editor, are only there if you passed them to `add()`.
401
+ *
402
+ * @example
403
+ * onAdd: async (row) => {
404
+ * const res = await fetch('/api/employees', { method: 'POST', body: JSON.stringify(row) });
405
+ * return res.json();
406
+ * }
407
+ */
408
+ readonly onAdd?: (row: Partial<Row>) => Row | void | Promise<Row | void>;
409
+ /**
410
+ * Called when a row is deleted. May be async. Throw to stop the delete:
411
+ * the row stays and the error message is shown under it.
412
+ *
413
+ * The Delete button only shows when this is set.
414
+ */
415
+ readonly onDelete?: (row: Row) => void | Promise<void>;
416
+ /**
417
+ * What happens before a row is deleted with the Delete button. By default
418
+ * the row asks "Delete this row?" with two buttons. `false` deletes right
419
+ * away. A function replaces the question with yours: return `true` to
420
+ * delete. May be async, for a modal.
421
+ *
422
+ * `delete()` from code never asks.
423
+ *
424
+ * @example
425
+ * confirmDelete: (row) => window.confirm(`Delete ${row.name}?`)
426
+ */
427
+ readonly confirmDelete?: false | ((row: Row) => boolean | Promise<boolean>);
369
428
  };
370
429
  /**
371
430
  * A DataTables table with row editing.
@@ -399,16 +458,27 @@ declare class Tadabut<Row extends object> {
399
458
  private readonly texts;
400
459
  /** The user's save callback. */
401
460
  private readonly onSave;
402
- /** Whether the Edit/Save/Cancel column exists. */
461
+ /** The user's add callback. */
462
+ private readonly onAdd;
463
+ /** The user's delete callback. */
464
+ private readonly onDelete;
465
+ /** What the Delete button does before deleting. */
466
+ private readonly confirmDelete;
467
+ /** Whether the actions column exists. */
403
468
  private readonly hasActions;
404
469
  /** Whether any column has an editor. */
405
470
  private readonly hasEditor;
406
471
  /** Open rows, by row id. */
407
472
  private readonly sessions;
473
+ /** Rows waiting for `onDelete`, by row id. */
474
+ private readonly deleting;
475
+ /** The row `add()` opened, if any. */
476
+ private newRow;
408
477
  /**
409
478
  * Builds the table inside `container`, which should be empty.
410
479
  *
411
480
  * @throws If a column has an `editor` and there's no `rowId`.
481
+ * @throws If `onDelete` is set and there's no `rowId`.
412
482
  * @throws If a hidden column (`visible: false`) has an `editor`.
413
483
  * @throws If a select's `labelProp` is its own column.
414
484
  */
@@ -416,7 +486,8 @@ declare class Tadabut<Row extends object> {
416
486
  /**
417
487
  * Replaces all rows. Sorting, search and the page are kept.
418
488
  *
419
- * Open rows are closed first, and their unsaved changes are lost.
489
+ * Open rows, and the new row, are closed first, and their unsaved changes
490
+ * are lost.
420
491
  */
421
492
  setData(rows: readonly Row[]): void;
422
493
  /**
@@ -424,10 +495,40 @@ declare class Tadabut<Row extends object> {
424
495
  *
425
496
  * @param id The value of the row's `rowId` field.
426
497
  * @returns `false` if the row doesn't exist, is already open, another row
427
- * is open in `'single'` mode, nothing is editable, or the row is on a
428
- * page that hasn't been displayed yet.
498
+ * or the new row is open in `'single'` mode, nothing is editable, the row
499
+ * is being deleted, or it's on a page that hasn't been displayed yet.
429
500
  */
430
501
  edit(id: string | number): boolean;
502
+ /**
503
+ * Opens an empty row at the top of the table, for a new row. `defaults` are
504
+ * its starting values. The row is only added once Save works.
505
+ *
506
+ * @returns `false` if no column has an editor, a new row is already open,
507
+ * or a row is being edited in `'single'` mode.
508
+ *
509
+ * @example
510
+ * table.add({ country: 'MA' });
511
+ */
512
+ add(defaults?: Partial<Row>): boolean;
513
+ /** Whether a new row is open. */
514
+ isAdding(): boolean;
515
+ /**
516
+ * Closes the new row and throws it away. Does nothing if there's none, or
517
+ * while it's saving.
518
+ */
519
+ cancelNew(): void;
520
+ /**
521
+ * Validates the new row, then calls `onAdd`. On success the row joins the
522
+ * table, and the table shows the page it landed on.
523
+ *
524
+ * While `onAdd` runs the row is locked. If it throws, the row stays open
525
+ * and the error message is shown under it.
526
+ *
527
+ * @returns `true` once the row is added. `false` if there's no new row, a
528
+ * field is invalid, it's already saving, or `onAdd` threw.
529
+ * @throws If the saved row has no `rowId` value.
530
+ */
531
+ saveNew(): Promise<boolean>;
431
532
  /**
432
533
  * Closes a row and throws away its changes. Does nothing if the row isn't
433
534
  * open, or while it's saving.
@@ -445,34 +546,56 @@ declare class Tadabut<Row extends object> {
445
546
  * @returns `true` once the row is saved and closed.
446
547
  */
447
548
  save(id: string | number): Promise<boolean>;
549
+ /**
550
+ * Calls `onDelete`, then removes the row. Never asks first: only the
551
+ * Delete button does.
552
+ *
553
+ * While `onDelete` runs the row is locked. If it throws, the row stays and
554
+ * the error message is shown under it.
555
+ *
556
+ * @returns `true` once the row is removed. `false` if the row doesn't
557
+ * exist, is open for editing, is already being deleted, or `onDelete`
558
+ * threw.
559
+ */
560
+ delete(id: string | number): Promise<boolean>;
448
561
  /** Removes the table. Open rows are closed without saving. */
449
562
  destroy(): void;
450
563
  /** The row with this id, or `undefined`. */
451
564
  private findRow;
452
- /** Only for when the rows are about to go away: cells aren't restored. */
565
+ /**
566
+ * Closes every open row, the new one too. Only for when the rows are about
567
+ * to go away: cells aren't restored.
568
+ */
453
569
  private destroySessions;
454
570
  /** Also works after the session is gone, so a row can always be unlocked. */
455
571
  private setSaving;
572
+ /** Shows a save or delete error in a child row under the row. */
573
+ private showRowError;
574
+ /** Removes the save or delete error under a row, if any. */
575
+ private clearRowError;
576
+ /** The last cell of a row, the one with the buttons. */
577
+ private actionsCell;
456
578
  /**
457
- * Shows the error in a child row under the row. The message gets its own
458
- * class because Bootstrap colors every cell, which hides a color on the
459
- * `<tr>`. Set as text: it often comes from a server.
579
+ * What the Delete button does: asks inline, asks with the user's function,
580
+ * or deletes right away.
460
581
  */
461
- private showSaveError;
462
- /** Removes the error row under a row, if any. */
463
- private clearSaveError;
582
+ private askDelete;
583
+ /** Puts Edit and Delete back after No. */
584
+ private keepRow;
585
+ /** Whether an element is inside the new row, or its error. */
586
+ private isInNewRow;
464
587
  /**
465
- * `undefined` for rows DataTables doesn't know, like the save error row or
588
+ * `undefined` for rows DataTables doesn't know, like the error row or
466
589
  * a table inside a custom editor.
467
590
  */
468
591
  private rowIdOf;
469
592
  /**
470
- * Handles Edit, Save and Cancel. One listener on the table, because
471
- * DataTables keeps replacing rows. An arrow function, so `this` stays
472
- * bound and `destroy` can remove it.
593
+ * Handles the action buttons, the new row's too. One listener on the
594
+ * table, because DataTables keeps replacing rows. An arrow function, so
595
+ * `this` stays bound and `destroy` can remove it.
473
596
  */
474
597
  private readonly onClick;
475
- /** Enter saves, Escape cancels. */
598
+ /** Enter saves, Escape cancels, in edited rows and the new row. */
476
599
  private readonly onKeyDown;
477
600
  }
478
601
  /** English, the default. */
package/dist/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { C as EditorInstance, S as EditorContext, _ as Texts, a as EditingOptions, b as CustomEditor, c as TadabutOptions, d as EditorFor, f as TextEditor, g as SelectOptionsLoader, h as SelectOption, i as DataTablesSettings, l as Column, m as SelectEditor, n as en, o as SaveContext, p as OptionsContext, r as Tadabut, s as TableClassNames, t as fr, u as ValidationOptions, v as NumberEditor, x as CheckboxEditor, y as DateEditor } from "./index-DYUdG69c.js";
1
+ import { C as EditorInstance, S as EditorContext, _ as Texts, a as EditingOptions, b as CustomEditor, c as TadabutOptions, d as EditorFor, f as TextEditor, g as SelectOptionsLoader, h as SelectOption, i as DataTablesSettings, l as Column, m as SelectEditor, n as en, o as SaveContext, p as OptionsContext, r as Tadabut, s as TableClassNames, t as fr, u as ValidationOptions, v as NumberEditor, x as CheckboxEditor, y as DateEditor } from "./index-mZisu7MG.js";
2
2
  export { type CheckboxEditor, type Column, type CustomEditor, type DataTablesSettings, type DateEditor, type EditingOptions, type EditorContext, type EditorFor, type EditorInstance, type NumberEditor, type OptionsContext, type SaveContext, type SelectEditor, type SelectOption, type SelectOptionsLoader, type TableClassNames, Tadabut, type TadabutOptions, type TextEditor, type Texts, type ValidationOptions, en, fr };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- export { n as Tadabut, r as en, t as fr } from "./src-cI0CYV46.js";
1
+ export { n as Tadabut, r as en, t as fr } from "./src-DWwW61Yo.js";