tadabut 0.3.0 → 0.5.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 +336 -52
- package/dist/{index-DYUdG69c.d.ts → index-KmSXRJlI.d.ts} +252 -29
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/react.d.ts +10 -6
- package/dist/react.js +46 -7
- package/dist/src-CBK3xu9-.js +1413 -0
- package/package.json +3 -3
- package/dist/src-cI0CYV46.js +0 -811
package/README.md
CHANGED
|
@@ -21,7 +21,9 @@ 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
|
-
-
|
|
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.
|
|
26
|
+
- Text, number, money, 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.
|
|
27
29
|
- No jQuery. It's built on DataTables 3, which doesn't need it anymore.
|
|
@@ -49,9 +51,20 @@ The core has no framework in it. Each framework gets a small adapter on top.
|
|
|
49
51
|
Install Tadabut with DataTables. `datatables.net-dt` is DataTables with its default look:
|
|
50
52
|
|
|
51
53
|
```sh
|
|
52
|
-
|
|
53
|
-
# or
|
|
54
|
+
# npm
|
|
54
55
|
npm install tadabut datatables.net-dt
|
|
56
|
+
|
|
57
|
+
# pnpm
|
|
58
|
+
pnpm add tadabut datatables.net-dt
|
|
59
|
+
|
|
60
|
+
# Yarn
|
|
61
|
+
yarn add tadabut datatables.net-dt
|
|
62
|
+
|
|
63
|
+
# Bun
|
|
64
|
+
bun add tadabut datatables.net-dt
|
|
65
|
+
|
|
66
|
+
# Deno
|
|
67
|
+
deno add npm:tadabut npm:datatables.net-dt
|
|
55
68
|
```
|
|
56
69
|
|
|
57
70
|
For the React adapter, you also need React 19, which your app most likely has already.
|
|
@@ -152,29 +165,77 @@ const columns: Column<Employee>[] = [
|
|
|
152
165
|
|
|
153
166
|
A select's values must have the same type as the column. `countryId` is a number, so `value: '1'` is a type error.
|
|
154
167
|
|
|
155
|
-
| Type | Value
|
|
156
|
-
| ---------- |
|
|
157
|
-
| `text` | `string`
|
|
158
|
-
| `number` | `number`
|
|
159
|
-
| `
|
|
160
|
-
| `
|
|
161
|
-
| `
|
|
168
|
+
| Type | Value | When empty | Options |
|
|
169
|
+
| ---------- | ---------------------- | ----------- | ---------------------------------------------- |
|
|
170
|
+
| `text` | `string` | `''` | `minLength`, `maxLength`, `pattern` |
|
|
171
|
+
| `number` | `number` | `null` | `min`, `max`, `step` |
|
|
172
|
+
| `money` | `number` | `null` | `min`, `max`, `decimals`, `separator`, `point` |
|
|
173
|
+
| `date` | `string` | `null` | `min`, `max` |
|
|
174
|
+
| `checkbox` | `boolean`, or `values` | never empty | `values` |
|
|
175
|
+
| `select` | same as the column | `null` | `options`, `dependsOn`, `labelProp` |
|
|
162
176
|
|
|
163
177
|
Every editor also takes `className`, for your own CSS classes.
|
|
164
178
|
|
|
165
179
|
A few things to know:
|
|
166
180
|
|
|
167
181
|
- An empty number or date gives `null`, not `0` or `NaN`. A select with nothing picked gives `null` too.
|
|
168
|
-
- A checkbox is
|
|
182
|
+
- A checkbox shows `null` as unchecked, but keeps it: an untouched `null` is still `null` after saving. It only becomes `true` or `false` once the user clicks it.
|
|
169
183
|
- A `string | null` column gets the same editors as a `string` column. `null` shows as an empty input.
|
|
170
184
|
- Date columns must hold `'YYYY-MM-DD'`. Something like `'2024-01-05T00:00:00'` shows as empty, and saving turns it into `null`. Convert your dates first.
|
|
171
185
|
|
|
186
|
+
#### Checkboxes with your own values
|
|
187
|
+
|
|
188
|
+
Many databases store yes/no as `'O'`/`'N'`, `'Y'`/`'N'` or `1`/`0`. Give the checkbox the two values to use:
|
|
189
|
+
|
|
190
|
+
```ts
|
|
191
|
+
type Employee = { id: number; active: 'O' | 'N' | null };
|
|
192
|
+
|
|
193
|
+
const columns: Column<Employee>[] = [
|
|
194
|
+
{
|
|
195
|
+
prop: 'active',
|
|
196
|
+
title: 'Active',
|
|
197
|
+
className: 'dt-center', // centers the cell and the checkbox
|
|
198
|
+
editor: { type: 'checkbox', values: { checked: 'O', unchecked: 'N' } },
|
|
199
|
+
render: (value) => (value === 'O' ? 'Yes' : value === 'N' ? 'No' : ''),
|
|
200
|
+
},
|
|
201
|
+
];
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
- The box is ticked only for the exact `checked` value. `'o'` isn't `'O'`, and `'1'` isn't `1`.
|
|
205
|
+
- Clicking writes `checked` or `unchecked`. A value that's neither, like `null` or an old `'X'`, shows unchecked and is kept as it is until the user clicks.
|
|
206
|
+
- `values` is required on `string` and `number` columns, and not allowed on `boolean` ones. Its values must fit the column, so `checked: 'Y'` on an `'O' | 'N'` column is a type error.
|
|
207
|
+
- The cell shows the raw value (`O`), like any column. Use `render` for "Yes"/"No", a ✓, or anything else.
|
|
208
|
+
|
|
209
|
+
#### Money
|
|
210
|
+
|
|
211
|
+
`money` is for `number` columns that hold amounts. It shows `12 500.00`, while typing and in the cells, but the row keeps a plain number (`12500`).
|
|
212
|
+
|
|
213
|
+
```ts
|
|
214
|
+
{ prop: 'salary', title: 'Salary', className: 'dt-right', editor: { type: 'money', min: 0 } }
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
- While typing, the thousands are grouped as you go, and the cursor stays where you're typing. The decimals are filled in when you leave the field: `12500` becomes `12 500.00`.
|
|
218
|
+
- Both `.` and `,` work as the decimal point. Letters are ignored, and a decimal too many is refused.
|
|
219
|
+
- The saved number is rounded to `decimals`, so `12.345` saves as `12.35`, never `12.345000001`.
|
|
220
|
+
- Empty gives `null`. `min`, `max` and `required` work like on `number`.
|
|
221
|
+
- The format is yours: `decimals` (default `2`), `separator` (default a space) and `point` (default `.`). For `12.500,00`, use `{ separator: '.', point: ',' }`. The separator and the point can't be the same: Tadabut throws an error if they are.
|
|
222
|
+
- The cells use the same format, without `render`. A `render` you write still wins, for a currency like `12 500.00 MAD`.
|
|
223
|
+
|
|
224
|
+
`formatMoney` and `defaultMoneyFormat` are exported, to show the same format in other places:
|
|
225
|
+
|
|
226
|
+
```ts
|
|
227
|
+
import { defaultMoneyFormat, formatMoney } from 'tadabut';
|
|
228
|
+
|
|
229
|
+
{ prop: 'bonus', title: 'Bonus', render: (value) => formatMoney(value, defaultMoneyFormat) }
|
|
230
|
+
```
|
|
231
|
+
|
|
172
232
|
### What cells show
|
|
173
233
|
|
|
174
|
-
When a row isn't being edited, a cell shows its value as text.
|
|
234
|
+
When a row isn't being edited, a cell shows its value as text. These change that:
|
|
175
235
|
|
|
176
236
|
- A select with a fixed list shows the option's label. A `countryId` of `1` shows "Morocco", with nothing to write.
|
|
177
237
|
- A select with `labelProp` shows that field of the row, like `cityName`. See [Chained selects](#chained-selects).
|
|
238
|
+
- A `money` editor shows its format, like `12 500.00`.
|
|
178
239
|
- `render` sets the text yourself, on any column:
|
|
179
240
|
|
|
180
241
|
```ts
|
|
@@ -183,12 +244,59 @@ When a row isn't being edited, a cell shows its value as text. Three things chan
|
|
|
183
244
|
|
|
184
245
|
A few things to know:
|
|
185
246
|
|
|
186
|
-
- The order is: `render`, then `labelProp`, then the fixed list's label, then the value itself.
|
|
247
|
+
- The order is: `render`, then the money format, then `labelProp`, then the fixed list's label, then the value itself.
|
|
187
248
|
- What `render` returns is shown as plain text, never as HTML. `<b>` shows as `<b>`, so text from a server can't break the page or run code.
|
|
188
|
-
- Searching uses the text. Sorting uses the raw value, so `200 MAD` comes before `1000 MAD`. A city column sorts by id, not by name.
|
|
249
|
+
- Searching uses both the text and the raw value, so `12500` finds `12 500.00`, and a country's id finds "Morocco". Sorting uses the raw value, so `200 MAD` comes before `1000 MAD`. A city column sorts by id, not by name.
|
|
189
250
|
- An empty value (`null` or `undefined`) shows an empty cell. On a nullable column, `render` gets `null` too.
|
|
190
251
|
- Editors always get the raw value. After saving or cancelling, the text is worked out again.
|
|
191
252
|
|
|
253
|
+
### Totals
|
|
254
|
+
|
|
255
|
+
Give a column a `total`, and the table gets a footer line with it:
|
|
256
|
+
|
|
257
|
+
```ts
|
|
258
|
+
const columns: Column<Employee>[] = [
|
|
259
|
+
{ prop: 'name', title: 'Name' },
|
|
260
|
+
{ prop: 'age', title: 'Age', render: (value) => `${value} years`, total: 'avg' },
|
|
261
|
+
{ prop: 'salary', title: 'Salary', editor: { type: 'money' }, total: 'sum' },
|
|
262
|
+
];
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
| Name | Age | Salary |
|
|
266
|
+
| ----- | ---------- | ---------- |
|
|
267
|
+
| … | … | … |
|
|
268
|
+
| Total | 32.5 years | 176 651.50 |
|
|
269
|
+
|
|
270
|
+
| `total` | Shows | Columns |
|
|
271
|
+
| ---------- | ------------------- | ------- |
|
|
272
|
+
| `'sum'` | everything added up | numbers |
|
|
273
|
+
| `'avg'` | the average | numbers |
|
|
274
|
+
| `'min'` | the smallest | numbers |
|
|
275
|
+
| `'max'` | the biggest | numbers |
|
|
276
|
+
| `'count'` | how many rows | any |
|
|
277
|
+
| a function | what it returns | any |
|
|
278
|
+
|
|
279
|
+
- The total looks like the cells: a `money` column shows `176 651.50`, and a `render` is used too (`32.5 years`). Numbers are rounded to 2 decimals. `count` is always a plain number.
|
|
280
|
+
- `render` gets the total and an empty object as its row, since a total isn't a row. A `render` that reads other fields of the row should use the function form instead.
|
|
281
|
+
- Empty values (`null`) are skipped. With no values, a sum is `0` and the others show nothing.
|
|
282
|
+
- A function gets the counted rows and returns the text, shown as text, not HTML:
|
|
283
|
+
|
|
284
|
+
```ts
|
|
285
|
+
{ prop: 'active', title: 'Active', total: (rows) => `${rows.filter((row) => row.active).length} active` }
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
- `Total` goes in the first cell, unless that column has a total of its own. Change it with `texts: { total: 'Somme' }`.
|
|
289
|
+
- The totals update by themselves after a search, a page change, a save, an add, a delete or `setData`.
|
|
290
|
+
- TypeScript only allows `sum`, `avg`, `min` and `max` on number columns.
|
|
291
|
+
|
|
292
|
+
**Which rows count,** with `totalRows`:
|
|
293
|
+
|
|
294
|
+
| `totalRows` | Counts |
|
|
295
|
+
| ---------------------- | ------------------------------------------------ |
|
|
296
|
+
| `'searched'` (default) | every row that matches the search, on every page |
|
|
297
|
+
| `'all'` | every row, whatever the search |
|
|
298
|
+
| `'page'` | only the rows on the page shown |
|
|
299
|
+
|
|
192
300
|
### Column options
|
|
193
301
|
|
|
194
302
|
A few more column settings, passed to DataTables:
|
|
@@ -254,7 +362,7 @@ In React, keep `dataTables` outside your component or in a `useMemo`, like `colu
|
|
|
254
362
|
|
|
255
363
|
### Texts and translations
|
|
256
364
|
|
|
257
|
-
Tadabut's own texts (the Edit, Save and
|
|
365
|
+
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
366
|
|
|
259
367
|
```ts
|
|
260
368
|
import { Tadabut, fr } from 'tadabut';
|
|
@@ -273,8 +381,14 @@ texts: { edit: 'Bearbeiten', save: 'Speichern', cancel: 'Abbrechen' }
|
|
|
273
381
|
| Key | English |
|
|
274
382
|
| ------------------------ | ------------------------------- |
|
|
275
383
|
| `edit`, `save`, `cancel` | Edit, Save, Cancel |
|
|
384
|
+
| `delete` | Delete |
|
|
385
|
+
| `deleteQuestion` | Delete this row? |
|
|
386
|
+
| `confirm`, `keep` | Yes, delete / No |
|
|
276
387
|
| `loading` | Loading… |
|
|
277
388
|
| `saveFailed` | Could not save. |
|
|
389
|
+
| `addFailed` | Could not add. |
|
|
390
|
+
| `deleteFailed` | Could not delete. |
|
|
391
|
+
| `total` | Total |
|
|
278
392
|
| `loadFailed` | Could not load the options. |
|
|
279
393
|
| `required` | This field is required. |
|
|
280
394
|
| `patternMismatch` | Wrong format. |
|
|
@@ -290,7 +404,7 @@ texts: {
|
|
|
290
404
|
}
|
|
291
405
|
```
|
|
292
406
|
|
|
293
|
-
`saveFailed` only
|
|
407
|
+
`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
408
|
|
|
295
409
|
DataTables' own texts (search, paging, "Showing 1 to 10") are set separately, with `dataTables.language`. See [DataTables settings](#datatables-settings).
|
|
296
410
|
|
|
@@ -300,24 +414,32 @@ In React, `texts={fr}` is fine. A new object on every render (like `texts={{ ...
|
|
|
300
414
|
|
|
301
415
|
Tadabut doesn't ship any CSS. Everything it creates gets these classes, so you can style it however you want:
|
|
302
416
|
|
|
303
|
-
| Class
|
|
304
|
-
|
|
|
305
|
-
| `tdb-input`
|
|
306
|
-
| `tdb-input-text`
|
|
307
|
-
| `tdb-input-number`
|
|
308
|
-
| `tdb-input-
|
|
309
|
-
| `tdb-input-
|
|
310
|
-
| `tdb-input-
|
|
311
|
-
| `tdb-
|
|
312
|
-
| `tdb-
|
|
313
|
-
| `tdb-
|
|
314
|
-
| `tdb-row-
|
|
315
|
-
| `tdb-row-
|
|
316
|
-
| `tdb-
|
|
317
|
-
| `tdb-
|
|
318
|
-
| `tdb-
|
|
319
|
-
| `tdb-
|
|
320
|
-
| `tdb-
|
|
417
|
+
| Class | Used on |
|
|
418
|
+
| ----------------------- | ----------------------------------------------------------- |
|
|
419
|
+
| `tdb-input` | every input |
|
|
420
|
+
| `tdb-input-text` | text inputs |
|
|
421
|
+
| `tdb-input-number` | number inputs |
|
|
422
|
+
| `tdb-input-money` | money inputs |
|
|
423
|
+
| `tdb-input-date` | date inputs |
|
|
424
|
+
| `tdb-input-checkbox` | checkboxes |
|
|
425
|
+
| `tdb-input-select` | selects |
|
|
426
|
+
| `tdb-error` | a field's error message, under its input |
|
|
427
|
+
| `tdb-row-error` | the line (`<tr>`) under a row that failed to save or delete |
|
|
428
|
+
| `tdb-row-error-message` | the message inside that line |
|
|
429
|
+
| `tdb-row-editing` | a row while it's being edited, and the new row |
|
|
430
|
+
| `tdb-row-saving` | a row while it's being saved, added or deleted |
|
|
431
|
+
| `tdb-row-new` | the new row `add()` opens |
|
|
432
|
+
| `tdb-totals` | the footer with the totals |
|
|
433
|
+
| `tdb-new-rows` | the `<tbody>` it lives in, above the others |
|
|
434
|
+
| `tdb-actions` | the column with the buttons, header too |
|
|
435
|
+
| `tdb-button` | every button |
|
|
436
|
+
| `tdb-button-edit` | the Edit button |
|
|
437
|
+
| `tdb-button-save` | the Save button |
|
|
438
|
+
| `tdb-button-cancel` | the Cancel button |
|
|
439
|
+
| `tdb-button-delete` | the Delete button |
|
|
440
|
+
| `tdb-delete-question` | the "Delete this row?" text |
|
|
441
|
+
| `tdb-button-confirm` | the "Yes, delete" button |
|
|
442
|
+
| `tdb-button-keep` | the "No" button |
|
|
321
443
|
|
|
322
444
|
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
445
|
|
|
@@ -344,13 +466,16 @@ const table = new Tadabut(container, {
|
|
|
344
466
|
});
|
|
345
467
|
```
|
|
346
468
|
|
|
347
|
-
| `classNames` key | Added to
|
|
348
|
-
| ---------------- |
|
|
349
|
-
| `table` | the `<table>`
|
|
350
|
-
| `button` |
|
|
351
|
-
| `edit` | the Edit button only
|
|
352
|
-
| `save` | the Save button only
|
|
353
|
-
| `cancel` | the Cancel button only
|
|
469
|
+
| `classNames` key | Added to |
|
|
470
|
+
| ---------------- | ----------------------------- |
|
|
471
|
+
| `table` | the `<table>` |
|
|
472
|
+
| `button` | every button |
|
|
473
|
+
| `edit` | the Edit button only |
|
|
474
|
+
| `save` | the Save button only |
|
|
475
|
+
| `cancel` | the Cancel button only |
|
|
476
|
+
| `delete` | the Delete button only |
|
|
477
|
+
| `confirm` | the "Yes, delete" button only |
|
|
478
|
+
| `keep` | the "No" button only |
|
|
354
479
|
|
|
355
480
|
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
481
|
|
|
@@ -407,6 +532,9 @@ const table = new Tadabut(container, {
|
|
|
407
532
|
edit: 'btn-outline-primary',
|
|
408
533
|
save: 'btn-primary',
|
|
409
534
|
cancel: 'btn-outline-secondary',
|
|
535
|
+
delete: 'btn-outline-danger',
|
|
536
|
+
confirm: 'btn-danger',
|
|
537
|
+
keep: 'btn-outline-secondary',
|
|
410
538
|
},
|
|
411
539
|
});
|
|
412
540
|
```
|
|
@@ -417,7 +545,7 @@ Error messages and the rows being edited need a few lines of your own CSS:
|
|
|
417
545
|
/* Errors in Bootstrap's red. Use the message's class, not the row's:
|
|
418
546
|
Bootstrap sets a color on every table cell. */
|
|
419
547
|
.tdb-error,
|
|
420
|
-
.tdb-
|
|
548
|
+
.tdb-row-error-message {
|
|
421
549
|
color: var(--bs-form-invalid-color);
|
|
422
550
|
font-size: 0.875em;
|
|
423
551
|
}
|
|
@@ -428,9 +556,23 @@ Error messages and the rows being edited need a few lines of your own CSS:
|
|
|
428
556
|
vertical-align: top;
|
|
429
557
|
}
|
|
430
558
|
|
|
559
|
+
/* A checkbox is smaller than the inputs: move it down to their middle. */
|
|
560
|
+
.table > tbody > tr.tdb-row-editing .tdb-input-checkbox {
|
|
561
|
+
margin-top: 0.5rem;
|
|
562
|
+
}
|
|
563
|
+
|
|
431
564
|
.tdb-row-saving {
|
|
432
565
|
opacity: 0.5;
|
|
433
566
|
}
|
|
567
|
+
|
|
568
|
+
/* Space between the buttons, and after "Delete this row?". */
|
|
569
|
+
.tdb-button + .tdb-button {
|
|
570
|
+
margin-left: 0.25rem;
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
.tdb-delete-question {
|
|
574
|
+
margin-right: 0.5rem;
|
|
575
|
+
}
|
|
434
576
|
```
|
|
435
577
|
|
|
436
578
|
> [!TIP]
|
|
@@ -527,6 +669,7 @@ Built-in rules:
|
|
|
527
669
|
| -------- | ----------------------------------- |
|
|
528
670
|
| text | `minLength`, `maxLength`, `pattern` |
|
|
529
671
|
| number | `min`, `max` |
|
|
672
|
+
| money | `min`, `max` |
|
|
530
673
|
| date | `min`, `max` |
|
|
531
674
|
| checkbox | none |
|
|
532
675
|
| select | none |
|
|
@@ -587,6 +730,7 @@ How it works:
|
|
|
587
730
|
- 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
731
|
- 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
732
|
- Cancelling or saving the row, `setData` and `destroy` cancel every request still running.
|
|
733
|
+
- 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
734
|
|
|
591
735
|
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
736
|
|
|
@@ -646,6 +790,103 @@ The table's data only changes when saving works, so there's nothing to undo when
|
|
|
646
790
|
|
|
647
791
|
`onSave` is optional. Without it, saving just updates the table.
|
|
648
792
|
|
|
793
|
+
### Adding
|
|
794
|
+
|
|
795
|
+
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`.
|
|
796
|
+
|
|
797
|
+
```ts
|
|
798
|
+
async function createEmployee(row: Partial<Employee>): Promise<Employee> {
|
|
799
|
+
const res = await fetch('/api/employees', {
|
|
800
|
+
method: 'POST',
|
|
801
|
+
headers: { 'Content-Type': 'application/json' },
|
|
802
|
+
body: JSON.stringify(row),
|
|
803
|
+
});
|
|
804
|
+
|
|
805
|
+
if (!res.ok) throw new Error('Could not add the employee');
|
|
806
|
+
|
|
807
|
+
return res.json(); // the row with its new id
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
const table = new Tadabut(container, {
|
|
811
|
+
data: employees,
|
|
812
|
+
rowId: 'id',
|
|
813
|
+
columns,
|
|
814
|
+
onSave: saveEmployee,
|
|
815
|
+
onAdd: createEmployee,
|
|
816
|
+
});
|
|
817
|
+
|
|
818
|
+
addButton.addEventListener('click', () => table.add());
|
|
819
|
+
```
|
|
820
|
+
|
|
821
|
+
What happens:
|
|
822
|
+
|
|
823
|
+
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.
|
|
824
|
+
2. Save, or <kbd>Enter</kbd>, validates the fields. Cancel, or <kbd>Escape</kbd>, throws the row away.
|
|
825
|
+
3. `onAdd` gets the typed row. The row is locked while it runs.
|
|
826
|
+
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.
|
|
827
|
+
5. If `onAdd` throws, the row stays open with what the user typed, and your error message shows under it.
|
|
828
|
+
|
|
829
|
+
**What `onAdd` gets and returns:**
|
|
830
|
+
|
|
831
|
+
- 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.
|
|
832
|
+
- Return the saved row, usually with the id the server made, or nothing to keep the row as typed.
|
|
833
|
+
- 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.
|
|
834
|
+
- 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 })`.
|
|
835
|
+
|
|
836
|
+
**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`.
|
|
837
|
+
|
|
838
|
+
**Rules:**
|
|
839
|
+
|
|
840
|
+
- One new row at a time. `add()` returns `false` if one is already open.
|
|
841
|
+
- 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.
|
|
842
|
+
- `setData` and `destroy` throw the new row away, like any open row.
|
|
843
|
+
|
|
844
|
+
### Deleting
|
|
845
|
+
|
|
846
|
+
Give the table an `onDelete`, and each row gets a Delete button next to Edit. It can be async, like `onSave`.
|
|
847
|
+
|
|
848
|
+
```ts
|
|
849
|
+
async function deleteEmployee(row: Employee) {
|
|
850
|
+
const res = await fetch(`/api/employees/${row.id}`, { method: 'DELETE' });
|
|
851
|
+
|
|
852
|
+
if (!res.ok) throw new Error('Could not delete the employee');
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
const table = new Tadabut(container, {
|
|
856
|
+
data: employees,
|
|
857
|
+
rowId: 'id',
|
|
858
|
+
columns,
|
|
859
|
+
onSave: saveEmployee,
|
|
860
|
+
onDelete: deleteEmployee,
|
|
861
|
+
});
|
|
862
|
+
```
|
|
863
|
+
|
|
864
|
+
What happens when you click Delete:
|
|
865
|
+
|
|
866
|
+
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.
|
|
867
|
+
2. No puts Edit and Delete back.
|
|
868
|
+
3. Yes calls `onDelete` with the row. The row is locked while it runs, and gets the `tdb-row-saving` class.
|
|
869
|
+
4. If `onDelete` works, the row is removed. You stay on the same page.
|
|
870
|
+
5. If `onDelete` throws, the row stays, and your error message shows under it.
|
|
871
|
+
|
|
872
|
+
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.
|
|
873
|
+
|
|
874
|
+
#### Your own question: `confirmDelete`
|
|
875
|
+
|
|
876
|
+
```ts
|
|
877
|
+
confirmDelete: false, // delete right away, no question
|
|
878
|
+
|
|
879
|
+
confirmDelete: (row) => window.confirm(`Delete ${row.name}?`), // the browser's popup
|
|
880
|
+
|
|
881
|
+
// any modal, as long as it returns true to delete
|
|
882
|
+
confirmDelete: async (row) => {
|
|
883
|
+
const result = await Swal.fire({ title: `Delete ${row.name}?`, showCancelButton: true });
|
|
884
|
+
return result.isConfirmed;
|
|
885
|
+
},
|
|
886
|
+
```
|
|
887
|
+
|
|
888
|
+
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`).
|
|
889
|
+
|
|
649
890
|
### Editing options
|
|
650
891
|
|
|
651
892
|
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 +908,7 @@ const table = new Tadabut(container, {
|
|
|
667
908
|
|
|
668
909
|
- `'single'` mode: one row at a time. You can't start a new edit while another row is open.
|
|
669
910
|
- `'multiple'` mode: several rows can be open. Each one saves on its own, so `onSave` runs once per row.
|
|
670
|
-
- `button: false`: no
|
|
911
|
+
- `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
912
|
|
|
672
913
|
### Controlling it from code
|
|
673
914
|
|
|
@@ -676,6 +917,12 @@ table.edit(5); // start editing the row with id 5
|
|
|
676
917
|
await table.save(5); // validate and save it
|
|
677
918
|
table.cancel(5); // cancel and restore its old values
|
|
678
919
|
table.isEditing(5); // true while row 5 is open
|
|
920
|
+
await table.delete(5); // call onDelete, then remove the row
|
|
921
|
+
|
|
922
|
+
table.add({ country: 'MA' }); // open a new row at the top
|
|
923
|
+
await table.saveNew(); // validate it and call onAdd
|
|
924
|
+
table.cancelNew(); // throw the new row away
|
|
925
|
+
table.isAdding(); // true while the new row is open
|
|
679
926
|
|
|
680
927
|
table.setData(newEmployees); // replace all rows, keeps sorting and search
|
|
681
928
|
table.destroy(); // remove everything Tadabut created
|
|
@@ -687,7 +934,11 @@ table.destroy(); // remove everything Tadabut created
|
|
|
687
934
|
|
|
688
935
|
`cancel` does nothing if the row isn't being edited, or while it's saving.
|
|
689
936
|
|
|
690
|
-
`
|
|
937
|
+
`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.
|
|
938
|
+
|
|
939
|
+
`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.
|
|
940
|
+
|
|
941
|
+
`setData` and `destroy` cancel any row being edited, and the new row, first. Unsaved changes are lost.
|
|
691
942
|
|
|
692
943
|
<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
944
|
|
|
@@ -733,8 +984,26 @@ async function saveEmployee(row: Employee): Promise<void> {
|
|
|
733
984
|
if (!res.ok) throw new Error('Could not save the employee');
|
|
734
985
|
}
|
|
735
986
|
|
|
987
|
+
async function createEmployee(row: Partial<Employee>): Promise<Employee> {
|
|
988
|
+
const res = await fetch('/api/employees', {
|
|
989
|
+
method: 'POST',
|
|
990
|
+
headers: { 'Content-Type': 'application/json' },
|
|
991
|
+
body: JSON.stringify(row),
|
|
992
|
+
});
|
|
993
|
+
|
|
994
|
+
if (!res.ok) throw new Error('Could not add the employee');
|
|
995
|
+
|
|
996
|
+
return res.json();
|
|
997
|
+
}
|
|
998
|
+
|
|
999
|
+
async function deleteEmployee(row: Employee): Promise<void> {
|
|
1000
|
+
const res = await fetch(`/api/employees/${row.id}`, { method: 'DELETE' });
|
|
1001
|
+
|
|
1002
|
+
if (!res.ok) throw new Error('Could not delete the employee');
|
|
1003
|
+
}
|
|
1004
|
+
|
|
736
1005
|
export default function Employees() {
|
|
737
|
-
const [employees] = useState<Employee[]>([
|
|
1006
|
+
const [employees, setEmployees] = useState<Employee[]>([
|
|
738
1007
|
{ id: 1, name: 'Amina', countryId: 1 },
|
|
739
1008
|
{ id: 2, name: 'Paul', countryId: 2 },
|
|
740
1009
|
]);
|
|
@@ -745,6 +1014,9 @@ export default function Employees() {
|
|
|
745
1014
|
<button type="button" onClick={() => tableRef.current?.edit(1)}>
|
|
746
1015
|
Edit Amina
|
|
747
1016
|
</button>
|
|
1017
|
+
<button type="button" onClick={() => tableRef.current?.add()}>
|
|
1018
|
+
Add an employee
|
|
1019
|
+
</button>
|
|
748
1020
|
|
|
749
1021
|
<Tadabut
|
|
750
1022
|
ref={tableRef}
|
|
@@ -753,6 +1025,15 @@ export default function Employees() {
|
|
|
753
1025
|
columns={columns}
|
|
754
1026
|
editing={{ mode: 'multiple' }}
|
|
755
1027
|
onSave={(row) => saveEmployee(row)}
|
|
1028
|
+
onAdd={async (row) => {
|
|
1029
|
+
const saved = await createEmployee(row);
|
|
1030
|
+
setEmployees((current) => [...current, saved]);
|
|
1031
|
+
return saved;
|
|
1032
|
+
}}
|
|
1033
|
+
onDelete={async (row) => {
|
|
1034
|
+
await deleteEmployee(row);
|
|
1035
|
+
setEmployees((current) => current.filter((e) => e.id !== row.id));
|
|
1036
|
+
}}
|
|
756
1037
|
/>
|
|
757
1038
|
</>
|
|
758
1039
|
);
|
|
@@ -760,9 +1041,11 @@ export default function Employees() {
|
|
|
760
1041
|
```
|
|
761
1042
|
|
|
762
1043
|
- When `employees` changes, the table updates in place. It doesn't get rebuilt.
|
|
763
|
-
- `onSave` can be
|
|
1044
|
+
- `onSave`, `onAdd`, `onDelete` and `confirmDelete` can be new functions on every render. The table always calls the latest ones.
|
|
1045
|
+
- 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.
|
|
1046
|
+
- `totalRows` is a plain string, so writing it inline is fine. Changing it rebuilds the table, to count other rows.
|
|
764
1047
|
- `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`
|
|
1048
|
+
- 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
1049
|
- There is no `setData` on the ref. To change the rows, change `data`.
|
|
767
1050
|
|
|
768
1051
|
## Roadmap
|
|
@@ -783,19 +1066,20 @@ Done:
|
|
|
783
1066
|
- [x] Pass DataTables settings through (paging, page sizes, default order, language, extensions like Buttons), and column `width`, `visible`, `orderable`, `searchable` and `className`
|
|
784
1067
|
- [x] Selects that also save their label in the row (`labelProp`), so the cell shows the new label after a save
|
|
785
1068
|
- [x] Translations for Tadabut's own texts (buttons and error messages), French built in
|
|
1069
|
+
- [x] Deleting rows, with a question first that you can replace (`confirmDelete`)
|
|
1070
|
+
- [x] Adding new rows, at the top of the table (`add()` and `onAdd`)
|
|
1071
|
+
- [x] Checkboxes with your own values, like `'O'` and `'N'` instead of `true` and `false`
|
|
1072
|
+
- [x] Money inputs, formatted while typing (`12 500.00`)
|
|
1073
|
+
- [x] Totals in the footer: sum, average, min, max, count or your own
|
|
786
1074
|
|
|
787
1075
|
Next, roughly in this order:
|
|
788
1076
|
|
|
789
|
-
- [ ] Adding new rows, and deleting rows, with a confirmation step
|
|
790
|
-
- [ ] Checkboxes with your own values, like `'O'` and `'N'` instead of `true` and `false`
|
|
791
|
-
- [ ] Money inputs, formatted while typing (`12 500.00`)
|
|
792
1077
|
- [ ] Dates as `dd/mm/yyyy`, in the input and when sorting
|
|
793
|
-
- [ ] Totals in the footer
|
|
794
1078
|
- [ ] A checkbox column to select rows, with "check all"
|
|
795
1079
|
- [ ] More events: when editing starts, after saving, row click and double click
|
|
796
1080
|
- [ ] Detail rows that open under a row
|
|
797
1081
|
- [ ] Time and read-only inputs
|
|
798
|
-
- [ ] Methods to read rows (`getData`, `getRow`),
|
|
1082
|
+
- [ ] Methods to read rows (`getData`, `getRow`), put a row in directly without opening it, and reach the DataTables API
|
|
799
1083
|
- [ ] Keyboard navigation and theming
|
|
800
1084
|
|
|
801
1085
|
Later: popup editing, changing many rows in one go, server-side mode, Vue and jQuery adapters.
|