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.
@@ -26,11 +26,30 @@ type EditorInstance<Value> = {
26
26
  /** Remove the element and tear down any widget you created. */
27
27
  readonly destroy: () => void;
28
28
  };
29
- /** For `boolean` columns. `null` shows unchecked; it never returns `null`. */
30
- type CheckboxEditor = BaseEditor & {
29
+ /** What a checkbox writes, for columns that don't hold `true`/`false`. */
30
+ type CheckboxValues<Value> = {
31
+ /** Written when the box is ticked. */
32
+ readonly checked: Value;
33
+ /** Written when it isn't. */
34
+ readonly unchecked: Value;
35
+ };
36
+ /**
37
+ * For `boolean` columns, or `string` and `number` columns with `values`. A
38
+ * value that's neither stays as it is until the box is clicked.
39
+ */
40
+ type CheckboxEditor<Value = boolean> = BaseEditor & {
31
41
  /** Picks this editor. */
32
42
  readonly type: "checkbox";
33
- };
43
+ } & (0 extends 1 & Value ? {
44
+ /** The column is `any`, so `values` can't be checked. */
45
+ readonly values?: CheckboxValues<Value>;
46
+ } : [Value] extends [boolean] ? {
47
+ /** Only for columns that aren't `true`/`false`. */
48
+ readonly values?: never;
49
+ } : {
50
+ /** What to write instead of `true` and `false`, like `{ checked: 'O', unchecked: 'N' }`. */
51
+ readonly values: CheckboxValues<Value>;
52
+ });
34
53
  /**
35
54
  * Bring your own editor (Select2, a date picker library…). Works on any
36
55
  * column, objects included. `create` runs every time a row is opened; call
@@ -75,6 +94,41 @@ type DateEditor = BaseEditor & {
75
94
  /** Latest date, as `'YYYY-MM-DD'`. */
76
95
  readonly max?: string;
77
96
  };
97
+ /** How a money input and its cells look. */
98
+ type MoneyFormat = {
99
+ /** Digits after the point. */
100
+ readonly decimals: number;
101
+ /** Between groups of thousands. */
102
+ readonly separator: string;
103
+ /** The decimal point that's shown. */
104
+ readonly point: string;
105
+ };
106
+ /** `12 500.00`. */
107
+ declare const defaultMoneyFormat: MoneyFormat;
108
+ /** `12500` → `'12 500.00'`, `null` → `''`. */
109
+ declare function formatMoney(value: number | null, format: MoneyFormat): string;
110
+ /**
111
+ * For `number` columns that hold money. Shows `12 500.00` while typing and in
112
+ * the cells. The row keeps a plain number.
113
+ *
114
+ * @example
115
+ * { type: 'money', min: 0 }
116
+ * { type: 'money', separator: '.', point: ',' } // 12.500,00
117
+ */
118
+ type MoneyEditor = BaseEditor & {
119
+ /** Picks this editor. */
120
+ readonly type: "money";
121
+ /** Smallest value allowed. */
122
+ readonly min?: number;
123
+ /** Largest value allowed. */
124
+ readonly max?: number;
125
+ /** Digits after the point. Defaults to `2`. */
126
+ readonly decimals?: number;
127
+ /** Between thousands. Defaults to a space. */
128
+ readonly separator?: string;
129
+ /** The decimal point shown. Defaults to `'.'`. Typing `.` or `,` both work. */
130
+ readonly point?: string;
131
+ };
78
132
  /**
79
133
  * For `number` columns. Empty gives `null`, not `0`. The options work like
80
134
  * the HTML attributes.
@@ -106,10 +160,24 @@ type Texts = {
106
160
  readonly save: string;
107
161
  /** The Cancel button. */
108
162
  readonly cancel: string;
163
+ /** The Delete button. */
164
+ readonly delete: string;
165
+ /** Asked in the row before deleting it. */
166
+ readonly deleteQuestion: string;
167
+ /** The button that confirms a delete. */
168
+ readonly confirm: string;
169
+ /** The button that keeps the row instead. */
170
+ readonly keep: string;
171
+ /** Under a row when `onDelete` throws something that isn't an `Error`. */
172
+ readonly deleteFailed: string;
173
+ /** In the footer's first cell, when that column has no total of its own. */
174
+ readonly total: string;
109
175
  /** Shown in a select while its options load. */
110
176
  readonly loading: string;
111
177
  /** Under a row when `onSave` throws something that isn't an `Error`. */
112
178
  readonly saveFailed: string;
179
+ /** Under a new row when `onAdd` throws something that isn't an `Error`. */
180
+ readonly addFailed: string;
113
181
  /** Under a select whose options failed to load. */
114
182
  readonly loadFailed: string;
115
183
  /** An empty field with `required`. */
@@ -204,18 +272,18 @@ type TextEditor = BaseEditor & {
204
272
  /**
205
273
  * Which editors a column can have, from its value type:
206
274
  *
207
- * | Column value | Built-in editors |
208
- * | ------------- | ------------------ |
209
- * | `string` | text, date, select |
210
- * | `number` | number, select |
211
- * | `boolean` | checkbox, select |
275
+ * | Column value | Built-in editors |
276
+ * | ------------- | --------------------------------------------- |
277
+ * | `string` | text, date, select, checkbox with `values` |
278
+ * | `number` | number, money, select, checkbox with `values` |
279
+ * | `boolean` | checkbox, select |
212
280
  *
213
281
  * `custom` works on anything. Nullable columns get the same editors as
214
282
  * non-nullable ones.
215
283
  */
216
284
  type EditorFor<Value, Row> = EditorForValue<NonNullable<Value>, Row> | CustomEditor<Value>;
217
285
  /** The built-in editors for a non-null value type. */
218
- type EditorForValue<Value, Row> = [Value] extends [string] ? TextEditor | DateEditor | SelectEditor<Value, Row> : [Value] extends [number] ? NumberEditor | SelectEditor<Value, Row> : [Value] extends [boolean] ? CheckboxEditor | SelectEditor<Value, Row> : never;
286
+ type EditorForValue<Value, Row> = [Value] extends [string] ? TextEditor | DateEditor | SelectEditor<Value, Row> | CheckboxEditor<Value> : [Value] extends [number] ? NumberEditor | MoneyEditor | SelectEditor<Value, Row> | CheckboxEditor<Value> : [Value] extends [boolean] ? CheckboxEditor | SelectEditor<Value, Row> : never;
219
287
  /**
220
288
  * Works on every editor. An empty value fails `required` and skips every
221
289
  * other check. Otherwise the editor's own rules (`min`, `maxLength`…) run,
@@ -242,6 +310,23 @@ type ValidationOptions<Row, Value> = {
242
310
  */
243
311
  readonly validate?: (value: Value | null, row: Row) => string | undefined;
244
312
  };
313
+ /** The totals that need numbers. `null` and empty cells are skipped. */
314
+ type NumberTotal = "sum" | "avg" | "min" | "max";
315
+ /**
316
+ * Gets the counted rows and returns the text to show. It's shown as text,
317
+ * not HTML.
318
+ *
319
+ * @example
320
+ * total: (rows) => `${rows.filter((row) => row.active).length} active`
321
+ */
322
+ type TotalFunction<Row extends object> = (rows: readonly Row[]) => string;
323
+ /**
324
+ * What a column's `total` can be: `sum`, `avg`, `min` and `max` only on
325
+ * number columns. `count` and a function work everywhere.
326
+ */
327
+ type TotalFor<Value, Row extends object> = [NonNullable<Value>] extends [number] ? NumberTotal | "count" | TotalFunction<Row> : "count" | TotalFunction<Row>;
328
+ /** Which rows the totals count. */
329
+ type TotalRows = "searched" | "all" | "page";
245
330
  /**
246
331
  * A table column. The `editor` has to fit the type of `prop`, so a number
247
332
  * field can't get a text input. Columns without an editor are read-only.
@@ -263,12 +348,21 @@ type ColumnFor<Row extends object, Key extends keyof Row & string> = {
263
348
  readonly editor?: EditorFor<Row[Key], Row> & ValidationOptions<Row, Row[Key]>;
264
349
  /**
265
350
  * The cell's text when the row isn't open. It's shown as text, not HTML.
266
- * Search uses it; sorting still uses the raw value.
351
+ * Search uses it and the raw value; sorting uses the raw value. Totals go
352
+ * through it too.
267
353
  *
268
354
  * @example
269
355
  * render: (value) => `${value} MAD`
270
356
  */
271
357
  readonly render?: (value: Row[Key], row: Row) => string;
358
+ /**
359
+ * Adds a footer line with this column's total. It's formatted like the
360
+ * cells: a money column shows `12 500.00`, and a `render` is used too.
361
+ *
362
+ * @example
363
+ * total: 'sum'
364
+ */
365
+ readonly total?: TotalFor<Row[Key], Row>;
272
366
  /** Like `'60px'` or `'20%'`. */
273
367
  readonly width?: string;
274
368
  /** Hidden columns still keep their value in the row, but can't be edited. */
@@ -294,7 +388,8 @@ type EditingOptions = {
294
388
  readonly mode?: "single" | "multiple";
295
389
  /**
296
390
  * Adds an Edit/Save/Cancel column at the end. Defaults to `true`. Turn it
297
- * off if you open rows yourself with `edit()`.
391
+ * off if you open rows yourself with `edit()`. The Delete button still
392
+ * shows if `onDelete` is set.
298
393
  */
299
394
  readonly button?: boolean;
300
395
  };
@@ -310,12 +405,15 @@ type EditingOptions = {
310
405
  * edit: 'btn-outline-primary',
311
406
  * save: 'btn-primary',
312
407
  * cancel: 'btn-outline-secondary',
408
+ * delete: 'btn-outline-danger',
409
+ * confirm: 'btn-danger',
410
+ * keep: 'btn-outline-secondary',
313
411
  * }
314
412
  */
315
413
  type TableClassNames = {
316
414
  /** On the `<table>`. */
317
415
  readonly table?: string;
318
- /** All three buttons. */
416
+ /** Every button. */
319
417
  readonly button?: string;
320
418
  /** Edit button only. */
321
419
  readonly edit?: string;
@@ -323,6 +421,12 @@ type TableClassNames = {
323
421
  readonly save?: string;
324
422
  /** Cancel button only. */
325
423
  readonly cancel?: string;
424
+ /** Delete button only. */
425
+ readonly delete?: string;
426
+ /** The button that confirms a delete. */
427
+ readonly confirm?: string;
428
+ /** The button that keeps the row instead. */
429
+ readonly keep?: string;
326
430
  };
327
431
  /**
328
432
  * Any {@link https://datatables.net/reference/option/ | DataTables option},
@@ -358,6 +462,14 @@ type TadabutOptions<Row extends object> = {
358
462
  * texts: { ...fr, save: 'Valider' }
359
463
  */
360
464
  readonly texts?: Partial<Texts>;
465
+ /**
466
+ * Which rows the totals count: `'searched'` (default) is every row that
467
+ * matches the search, on every page. `'all'` ignores the search. `'page'`
468
+ * is only the rows shown.
469
+ *
470
+ * Does nothing unless a column has `total`.
471
+ */
472
+ readonly totalRows?: TotalRows;
361
473
  /**
362
474
  * Called with the edited row once it passes validation. May be async.
363
475
  *
@@ -366,6 +478,43 @@ type TadabutOptions<Row extends object> = {
366
478
  * save: the row stays open and the error message is shown under it.
367
479
  */
368
480
  readonly onSave?: (row: Row, context: SaveContext<Row>) => Row | void | Promise<Row | void>;
481
+ /**
482
+ * Called with a new row once it passes validation. May be async.
483
+ *
484
+ * Return the saved row, usually with its id from the server, or nothing
485
+ * to keep the row as typed. Either way it must have its `rowId` field, or
486
+ * Tadabut throws an error. Throw to reject the add: the row stays open and
487
+ * the error message is shown under it.
488
+ *
489
+ * The row is partial because it isn't saved yet: the id, and columns
490
+ * without an editor, are only there if you passed them to `add()`.
491
+ *
492
+ * @example
493
+ * onAdd: async (row) => {
494
+ * const res = await fetch('/api/employees', { method: 'POST', body: JSON.stringify(row) });
495
+ * return res.json();
496
+ * }
497
+ */
498
+ readonly onAdd?: (row: Partial<Row>) => Row | void | Promise<Row | void>;
499
+ /**
500
+ * Called when a row is deleted. May be async. Throw to stop the delete:
501
+ * the row stays and the error message is shown under it.
502
+ *
503
+ * The Delete button only shows when this is set.
504
+ */
505
+ readonly onDelete?: (row: Row) => void | Promise<void>;
506
+ /**
507
+ * What happens before a row is deleted with the Delete button. By default
508
+ * the row asks "Delete this row?" with two buttons. `false` deletes right
509
+ * away. A function replaces the question with yours: return `true` to
510
+ * delete. May be async, for a modal.
511
+ *
512
+ * `delete()` from code never asks.
513
+ *
514
+ * @example
515
+ * confirmDelete: (row) => window.confirm(`Delete ${row.name}?`)
516
+ */
517
+ readonly confirmDelete?: false | ((row: Row) => boolean | Promise<boolean>);
369
518
  };
370
519
  /**
371
520
  * A DataTables table with row editing.
@@ -399,24 +548,41 @@ declare class Tadabut<Row extends object> {
399
548
  private readonly texts;
400
549
  /** The user's save callback. */
401
550
  private readonly onSave;
402
- /** Whether the Edit/Save/Cancel column exists. */
551
+ /** The user's add callback. */
552
+ private readonly onAdd;
553
+ /** The user's delete callback. */
554
+ private readonly onDelete;
555
+ /** What the Delete button does before deleting. */
556
+ private readonly confirmDelete;
557
+ /** Whether the actions column exists. */
403
558
  private readonly hasActions;
404
559
  /** Whether any column has an editor. */
405
560
  private readonly hasEditor;
406
561
  /** Open rows, by row id. */
407
562
  private readonly sessions;
563
+ /** Rows waiting for `onDelete`, by row id. */
564
+ private readonly deleting;
565
+ /** The row `add()` opened, if any. */
566
+ private newRow;
567
+ /** Whether any column has a `total`, so the table has a footer. */
568
+ private readonly hasTotals;
569
+ /** Which rows the totals count, with its default filled in. */
570
+ private readonly totalRows;
408
571
  /**
409
572
  * Builds the table inside `container`, which should be empty.
410
573
  *
411
574
  * @throws If a column has an `editor` and there's no `rowId`.
575
+ * @throws If `onDelete` is set and there's no `rowId`.
412
576
  * @throws If a hidden column (`visible: false`) has an `editor`.
413
577
  * @throws If a select's `labelProp` is its own column.
578
+ * @throws If a money editor's `separator` and `point` are the same.
414
579
  */
415
580
  constructor(container: HTMLElement, options: TadabutOptions<Row>);
416
581
  /**
417
582
  * Replaces all rows. Sorting, search and the page are kept.
418
583
  *
419
- * Open rows are closed first, and their unsaved changes are lost.
584
+ * Open rows, and the new row, are closed first, and their unsaved changes
585
+ * are lost.
420
586
  */
421
587
  setData(rows: readonly Row[]): void;
422
588
  /**
@@ -424,10 +590,40 @@ declare class Tadabut<Row extends object> {
424
590
  *
425
591
  * @param id The value of the row's `rowId` field.
426
592
  * @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.
593
+ * or the new row is open in `'single'` mode, nothing is editable, the row
594
+ * is being deleted, or it's on a page that hasn't been displayed yet.
429
595
  */
430
596
  edit(id: string | number): boolean;
597
+ /**
598
+ * Opens an empty row at the top of the table, for a new row. `defaults` are
599
+ * its starting values. The row is only added once Save works.
600
+ *
601
+ * @returns `false` if no column has an editor, a new row is already open,
602
+ * or a row is being edited in `'single'` mode.
603
+ *
604
+ * @example
605
+ * table.add({ country: 'MA' });
606
+ */
607
+ add(defaults?: Partial<Row>): boolean;
608
+ /** Whether a new row is open. */
609
+ isAdding(): boolean;
610
+ /**
611
+ * Closes the new row and throws it away. Does nothing if there's none, or
612
+ * while it's saving.
613
+ */
614
+ cancelNew(): void;
615
+ /**
616
+ * Validates the new row, then calls `onAdd`. On success the row joins the
617
+ * table, and the table shows the page it landed on.
618
+ *
619
+ * While `onAdd` runs the row is locked. If it throws, the row stays open
620
+ * and the error message is shown under it.
621
+ *
622
+ * @returns `true` once the row is added. `false` if there's no new row, a
623
+ * field is invalid, it's already saving, or `onAdd` threw.
624
+ * @throws If the saved row has no `rowId` value.
625
+ */
626
+ saveNew(): Promise<boolean>;
431
627
  /**
432
628
  * Closes a row and throws away its changes. Does nothing if the row isn't
433
629
  * open, or while it's saving.
@@ -445,38 +641,65 @@ declare class Tadabut<Row extends object> {
445
641
  * @returns `true` once the row is saved and closed.
446
642
  */
447
643
  save(id: string | number): Promise<boolean>;
644
+ /**
645
+ * Calls `onDelete`, then removes the row. Never asks first: only the
646
+ * Delete button does.
647
+ *
648
+ * While `onDelete` runs the row is locked. If it throws, the row stays and
649
+ * the error message is shown under it.
650
+ *
651
+ * @returns `true` once the row is removed. `false` if the row doesn't
652
+ * exist, is open for editing, is already being deleted, or `onDelete`
653
+ * threw.
654
+ */
655
+ delete(id: string | number): Promise<boolean>;
448
656
  /** Removes the table. Open rows are closed without saving. */
449
657
  destroy(): void;
450
658
  /** The row with this id, or `undefined`. */
451
659
  private findRow;
452
- /** Only for when the rows are about to go away: cells aren't restored. */
660
+ /**
661
+ * Closes every open row, the new one too. Only for when the rows are about
662
+ * to go away: cells aren't restored.
663
+ */
453
664
  private destroySessions;
454
665
  /** Also works after the session is gone, so a row can always be unlocked. */
455
666
  private setSaving;
667
+ /** Shows a save or delete error in a child row under the row. */
668
+ private showRowError;
669
+ /** Removes the save or delete error under a row, if any. */
670
+ private clearRowError;
671
+ /** The last cell of a row, the one with the buttons. */
672
+ private actionsCell;
456
673
  /**
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.
674
+ * What the Delete button does: asks inline, asks with the user's function,
675
+ * or deletes right away.
460
676
  */
461
- private showSaveError;
462
- /** Removes the error row under a row, if any. */
463
- private clearSaveError;
677
+ private askDelete;
678
+ /** Puts Edit and Delete back after No. */
679
+ private keepRow;
680
+ /** Whether an element is inside the new row, or its error. */
681
+ private isInNewRow;
464
682
  /**
465
- * `undefined` for rows DataTables doesn't know, like the save error row or
683
+ * `undefined` for rows DataTables doesn't know, like the error row or
466
684
  * a table inside a custom editor.
467
685
  */
468
686
  private rowIdOf;
469
687
  /**
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.
688
+ * Handles the action buttons, the new row's too. One listener on the
689
+ * table, because DataTables keeps replacing rows. An arrow function, so
690
+ * `this` stays bound and `destroy` can remove it.
473
691
  */
474
692
  private readonly onClick;
475
- /** Enter saves, Escape cancels. */
693
+ /** Enter saves, Escape cancels, in edited rows and the new row. */
476
694
  private readonly onKeyDown;
695
+ /**
696
+ * Writes every total. Runs after each redraw: search, paging, save, add,
697
+ * delete and `setData` all redraw.
698
+ */
699
+ private readonly updateTotals;
477
700
  }
478
701
  /** English, the default. */
479
702
  declare const en: Texts;
480
703
  /** French. */
481
704
  declare const fr: Texts;
482
- export { EditorInstance as C, EditorContext as S, Texts as _, EditingOptions as a, CustomEditor as b, TadabutOptions as c, EditorFor as d, TextEditor as f, SelectOptionsLoader as g, SelectOption as h, DataTablesSettings as i, Column as l, SelectEditor as m, en as n, SaveContext as o, OptionsContext as p, Tadabut as r, TableClassNames as s, fr as t, ValidationOptions as u, NumberEditor as v, CheckboxEditor as x, DateEditor as y };
705
+ export { defaultMoneyFormat as C, CheckboxEditor as D, CustomEditor as E, EditorContext as O, MoneyFormat as S, DateEditor as T, SelectOption as _, EditingOptions as a, NumberEditor as b, TadabutOptions as c, TotalRows as d, ValidationOptions as f, SelectEditor as g, OptionsContext as h, DataTablesSettings as i, EditorInstance as k, Column as l, TextEditor as m, en as n, SaveContext as o, EditorFor as p, Tadabut as r, TableClassNames as s, fr as t, TotalFunction as u, SelectOptionsLoader as v, formatMoney as w, MoneyEditor as x, Texts as y };
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";
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 };
1
+ import { C as defaultMoneyFormat, D as CheckboxEditor, E as CustomEditor, O as EditorContext, S as MoneyFormat, T as DateEditor, _ as SelectOption, a as EditingOptions, b as NumberEditor, c as TadabutOptions, d as TotalRows, f as ValidationOptions, g as SelectEditor, h as OptionsContext, i as DataTablesSettings, k as EditorInstance, l as Column, m as TextEditor, n as en, o as SaveContext, p as EditorFor, r as Tadabut, s as TableClassNames, t as fr, u as TotalFunction, v as SelectOptionsLoader, w as formatMoney, x as MoneyEditor, y as Texts } from "./index-KmSXRJlI.js";
2
+ export { type CheckboxEditor, type Column, type CustomEditor, type DataTablesSettings, type DateEditor, type EditingOptions, type EditorContext, type EditorFor, type EditorInstance, type MoneyEditor, type MoneyFormat, type NumberEditor, type OptionsContext, type SaveContext, type SelectEditor, type SelectOption, type SelectOptionsLoader, type TableClassNames, Tadabut, type TadabutOptions, type TextEditor, type Texts, type TotalFunction, type TotalRows, type ValidationOptions, defaultMoneyFormat, en, formatMoney, 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, i as defaultMoneyFormat, r as en, a as formatMoney, t as fr } from "./src-CBK3xu9-.js";
package/dist/react.d.ts CHANGED
@@ -1,16 +1,20 @@
1
- import { c as TadabutOptions, r as Tadabut$1 } from "./index-DYUdG69c.js";
1
+ import { c as TadabutOptions, r as Tadabut$1 } from "./index-KmSXRJlI.js";
2
2
  import { ReactElement, Ref } from "react";
3
3
  /** What the `ref` gets. No `setData`: change the `data` prop instead. */
4
- export type TadabutHandle<Row extends object> = Pick<Tadabut$1<Row>, "edit" | "save" | "cancel" | "isEditing">;
4
+ export type TadabutHandle<Row extends object> = Pick<Tadabut$1<Row>, "edit" | "save" | "cancel" | "delete" | "isEditing" | "add" | "isAdding" | "saveNew" | "cancelNew">;
5
5
  /** The core options, plus `ref`. */
6
6
  export type TadabutProps<Row extends object> = TadabutOptions<Row> & {
7
- /** Gives you `edit`, `save`, `cancel` and `isEditing`. */
7
+ /**
8
+ * Gives you the same methods as the core table: `edit`, `save`, `cancel`,
9
+ * `delete`, `add`, `saveNew`, `cancelNew`, `isEditing` and `isAdding`.
10
+ */
8
11
  readonly ref?: Ref<TadabutHandle<Row>>;
9
12
  };
10
13
  /**
11
14
  * New `data` updates the table in place. Changing `columns`, `rowId`,
12
- * `dataTables` or `texts` rebuilds it (and closes open rows), so keep those
13
- * stable with a constant or `useMemo`. `editing`, `classNames` and `onSave` can be
15
+ * `dataTables`, `texts` or `totalRows` rebuilds it (and closes open rows), so
16
+ * keep the objects stable with a constant or `useMemo`. `editing`,
17
+ * `classNames`, `onSave`, `onAdd`, `onDelete` and `confirmDelete` can be
14
18
  * inline: they're compared by value or read through a ref.
15
19
  */
16
- export declare function Tadabut<Row extends object>({ data, columns, rowId, editing, classNames, dataTables, texts, onSave, ref }: TadabutProps<Row>): ReactElement;
20
+ export declare function Tadabut<Row extends object>({ data, columns, rowId, editing, classNames, dataTables, texts, totalRows, onSave, onAdd, onDelete, confirmDelete, ref }: TadabutProps<Row>): ReactElement;
package/dist/react.js CHANGED
@@ -1,4 +1,4 @@
1
- import { n as Tadabut$1 } from "./src-cI0CYV46.js";
1
+ import { n as Tadabut$1 } from "./src-CBK3xu9-.js";
2
2
  import { useEffect, useImperativeHandle, useRef } from "react";
3
3
  import { jsx } from "react/jsx-runtime";
4
4
  // src/react/index.tsx
@@ -17,11 +17,12 @@ import { jsx } from "react/jsx-runtime";
17
17
  */
18
18
  /**
19
19
  * New `data` updates the table in place. Changing `columns`, `rowId`,
20
- * `dataTables` or `texts` rebuilds it (and closes open rows), so keep those
21
- * stable with a constant or `useMemo`. `editing`, `classNames` and `onSave` can be
20
+ * `dataTables`, `texts` or `totalRows` rebuilds it (and closes open rows), so
21
+ * keep the objects stable with a constant or `useMemo`. `editing`,
22
+ * `classNames`, `onSave`, `onAdd`, `onDelete` and `confirmDelete` can be
22
23
  * inline: they're compared by value or read through a ref.
23
24
  */
24
- function Tadabut({ data, columns, rowId, editing, classNames, dataTables, texts, onSave, ref }) {
25
+ function Tadabut({ data, columns, rowId, editing, classNames, dataTables, texts, totalRows, onSave, onAdd, onDelete, confirmDelete, ref }) {
25
26
  /** The `<div>` the core builds the table in. */
26
27
  const containerRef = useRef(null);
27
28
  /** The core table. `null` before the first build and after unmount. */
@@ -30,6 +31,12 @@ function Tadabut({ data, columns, rowId, editing, classNames, dataTables, texts,
30
31
  const dataRef = useRef(data);
31
32
  /** The latest `onSave`, so a new one doesn't rebuild the table. */
32
33
  const onSaveRef = useRef(onSave);
34
+ /** The latest `onAdd`, so a new one doesn't rebuild the table. */
35
+ const onAddRef = useRef(onAdd);
36
+ /** The latest `onDelete`, so a new one doesn't rebuild the table. */
37
+ const onDeleteRef = useRef(onDelete);
38
+ /** The latest `confirmDelete`, so a new one doesn't rebuild the table. */
39
+ const confirmDeleteRef = useRef(confirmDelete);
33
40
  const mode = editing?.mode;
34
41
  const button = editing?.button;
35
42
  const tableClass = classNames?.table;
@@ -37,9 +44,20 @@ function Tadabut({ data, columns, rowId, editing, classNames, dataTables, texts,
37
44
  const editClass = classNames?.edit;
38
45
  const saveClass = classNames?.save;
39
46
  const cancelClass = classNames?.cancel;
47
+ const deleteClass = classNames?.delete;
48
+ const confirmClass = classNames?.confirm;
49
+ const keepClass = classNames?.keep;
50
+ const hasDelete = onDelete !== void 0;
51
+ const confirmWith = confirmDelete === false ? "never" : confirmDelete === void 0 ? "inline" : "function";
40
52
  useEffect(() => {
41
53
  const container = containerRef.current;
42
54
  if (!container) return;
55
+ let confirm;
56
+ if (confirmWith === "never") confirm = false;
57
+ else if (confirmWith === "function") confirm = (row) => {
58
+ const ask = confirmDeleteRef.current;
59
+ return typeof ask === "function" ? ask(row) : true;
60
+ };
43
61
  const table = new Tadabut$1(container, {
44
62
  data: dataRef.current,
45
63
  columns,
@@ -50,14 +68,21 @@ function Tadabut({ data, columns, rowId, editing, classNames, dataTables, texts,
50
68
  },
51
69
  dataTables,
52
70
  texts,
71
+ totalRows,
53
72
  classNames: {
54
73
  table: tableClass,
55
74
  button: buttonClass,
56
75
  edit: editClass,
57
76
  save: saveClass,
58
- cancel: cancelClass
77
+ cancel: cancelClass,
78
+ delete: deleteClass,
79
+ confirm: confirmClass,
80
+ keep: keepClass
59
81
  },
60
- onSave: (row, context) => onSaveRef.current?.(row, context)
82
+ onSave: (row, context) => onSaveRef.current?.(row, context),
83
+ onAdd: (row) => onAddRef.current?.(row),
84
+ onDelete: hasDelete ? (row) => onDeleteRef.current?.(row) : void 0,
85
+ confirmDelete: confirm
61
86
  });
62
87
  tableRef.current = table;
63
88
  return () => {
@@ -69,13 +94,19 @@ function Tadabut({ data, columns, rowId, editing, classNames, dataTables, texts,
69
94
  rowId,
70
95
  dataTables,
71
96
  texts,
97
+ totalRows,
72
98
  mode,
73
99
  button,
74
100
  tableClass,
75
101
  buttonClass,
76
102
  editClass,
77
103
  saveClass,
78
- cancelClass
104
+ cancelClass,
105
+ deleteClass,
106
+ confirmClass,
107
+ keepClass,
108
+ hasDelete,
109
+ confirmWith
79
110
  ]);
80
111
  useEffect(() => {
81
112
  dataRef.current = data;
@@ -83,11 +114,19 @@ function Tadabut({ data, columns, rowId, editing, classNames, dataTables, texts,
83
114
  }, [data]);
84
115
  useEffect(() => {
85
116
  onSaveRef.current = onSave;
117
+ onAddRef.current = onAdd;
118
+ onDeleteRef.current = onDelete;
119
+ confirmDeleteRef.current = confirmDelete;
86
120
  });
87
121
  useImperativeHandle(ref, () => ({
88
122
  edit: (id) => tableRef.current?.edit(id) ?? false,
89
123
  save: (id) => tableRef.current?.save(id) ?? Promise.resolve(false),
90
124
  cancel: (id) => tableRef.current?.cancel(id),
125
+ delete: (id) => tableRef.current?.delete(id) ?? Promise.resolve(false),
126
+ add: (defaults) => tableRef.current?.add(defaults) ?? false,
127
+ isAdding: () => tableRef.current?.isAdding() ?? false,
128
+ saveNew: () => tableRef.current?.saveNew() ?? Promise.resolve(false),
129
+ cancelNew: () => tableRef.current?.cancelNew(),
91
130
  isEditing: (id) => tableRef.current?.isEditing(id) ?? false
92
131
  }), []);
93
132
  return /* @__PURE__ */ jsx("div", { ref: containerRef });