tadabut 0.4.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 CHANGED
@@ -23,7 +23,7 @@ DataTables is great for showing data. Editing that data inside the table is a di
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
25
  - Delete a row, with a question first, or your own popup.
26
- - Text, number, date, checkbox and select inputs, with validation.
26
+ - Text, number, money, date, checkbox and select inputs, with validation.
27
27
  - Selects that depend on another field, like country and city. Old requests get cancelled when the user changes their mind.
28
28
  - Fully typed. The table knows what your rows look like, so a typo in a column name is a type error.
29
29
  - No jQuery. It's built on DataTables 3, which doesn't need it anymore.
@@ -51,9 +51,20 @@ The core has no framework in it. Each framework gets a small adapter on top.
51
51
  Install Tadabut with DataTables. `datatables.net-dt` is DataTables with its default look:
52
52
 
53
53
  ```sh
54
- pnpm add tadabut datatables.net-dt
55
- # or
54
+ # npm
56
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
57
68
  ```
58
69
 
59
70
  For the React adapter, you also need React 19, which your app most likely has already.
@@ -154,29 +165,77 @@ const columns: Column<Employee>[] = [
154
165
 
155
166
  A select's values must have the same type as the column. `countryId` is a number, so `value: '1'` is a type error.
156
167
 
157
- | Type | Value | When empty | Options |
158
- | ---------- | ------------------ | ----------- | ----------------------------------- |
159
- | `text` | `string` | `''` | `minLength`, `maxLength`, `pattern` |
160
- | `number` | `number` | `null` | `min`, `max`, `step` |
161
- | `date` | `string` | `null` | `min`, `max` |
162
- | `checkbox` | `boolean` | never empty | none |
163
- | `select` | same as the column | `null` | `options`, `dependsOn`, `labelProp` |
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` |
164
176
 
165
177
  Every editor also takes `className`, for your own CSS classes.
166
178
 
167
179
  A few things to know:
168
180
 
169
181
  - An empty number or date gives `null`, not `0` or `NaN`. A select with nothing picked gives `null` too.
170
- - A checkbox is always `true` or `false`. A `null` value shows as unchecked.
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.
171
183
  - A `string | null` column gets the same editors as a `string` column. `null` shows as an empty input.
172
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.
173
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
+
174
232
  ### What cells show
175
233
 
176
- When a row isn't being edited, a cell shows its value as text. Three things change that:
234
+ When a row isn't being edited, a cell shows its value as text. These change that:
177
235
 
178
236
  - A select with a fixed list shows the option's label. A `countryId` of `1` shows "Morocco", with nothing to write.
179
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`.
180
239
  - `render` sets the text yourself, on any column:
181
240
 
182
241
  ```ts
@@ -185,12 +244,59 @@ When a row isn't being edited, a cell shows its value as text. Three things chan
185
244
 
186
245
  A few things to know:
187
246
 
188
- - 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.
189
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.
190
- - 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.
191
250
  - An empty value (`null` or `undefined`) shows an empty cell. On a nullable column, `render` gets `null` too.
192
251
  - Editors always get the raw value. After saving or cancelling, the text is worked out again.
193
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
+
194
300
  ### Column options
195
301
 
196
302
  A few more column settings, passed to DataTables:
@@ -282,6 +388,7 @@ texts: { edit: 'Bearbeiten', save: 'Speichern', cancel: 'Abbrechen' }
282
388
  | `saveFailed` | Could not save. |
283
389
  | `addFailed` | Could not add. |
284
390
  | `deleteFailed` | Could not delete. |
391
+ | `total` | Total |
285
392
  | `loadFailed` | Could not load the options. |
286
393
  | `required` | This field is required. |
287
394
  | `patternMismatch` | Wrong format. |
@@ -312,6 +419,7 @@ Tadabut doesn't ship any CSS. Everything it creates gets these classes, so you c
312
419
  | `tdb-input` | every input |
313
420
  | `tdb-input-text` | text inputs |
314
421
  | `tdb-input-number` | number inputs |
422
+ | `tdb-input-money` | money inputs |
315
423
  | `tdb-input-date` | date inputs |
316
424
  | `tdb-input-checkbox` | checkboxes |
317
425
  | `tdb-input-select` | selects |
@@ -321,6 +429,7 @@ Tadabut doesn't ship any CSS. Everything it creates gets these classes, so you c
321
429
  | `tdb-row-editing` | a row while it's being edited, and the new row |
322
430
  | `tdb-row-saving` | a row while it's being saved, added or deleted |
323
431
  | `tdb-row-new` | the new row `add()` opens |
432
+ | `tdb-totals` | the footer with the totals |
324
433
  | `tdb-new-rows` | the `<tbody>` it lives in, above the others |
325
434
  | `tdb-actions` | the column with the buttons, header too |
326
435
  | `tdb-button` | every button |
@@ -447,6 +556,11 @@ Error messages and the rows being edited need a few lines of your own CSS:
447
556
  vertical-align: top;
448
557
  }
449
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
+
450
564
  .tdb-row-saving {
451
565
  opacity: 0.5;
452
566
  }
@@ -555,6 +669,7 @@ Built-in rules:
555
669
  | -------- | ----------------------------------- |
556
670
  | text | `minLength`, `maxLength`, `pattern` |
557
671
  | number | `min`, `max` |
672
+ | money | `min`, `max` |
558
673
  | date | `min`, `max` |
559
674
  | checkbox | none |
560
675
  | select | none |
@@ -928,6 +1043,7 @@ export default function Employees() {
928
1043
  - When `employees` changes, the table updates in place. It doesn't get rebuilt.
929
1044
  - `onSave`, `onAdd`, `onDelete` and `confirmDelete` can be new functions on every render. The table always calls the latest ones.
930
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.
931
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.
932
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.
933
1049
  - There is no `setData` on the ref. To change the rows, change `data`.
@@ -952,13 +1068,13 @@ Done:
952
1068
  - [x] Translations for Tadabut's own texts (buttons and error messages), French built in
953
1069
  - [x] Deleting rows, with a question first that you can replace (`confirmDelete`)
954
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
955
1074
 
956
1075
  Next, roughly in this order:
957
1076
 
958
- - [ ] Checkboxes with your own values, like `'O'` and `'N'` instead of `true` and `false`
959
- - [ ] Money inputs, formatted while typing (`12 500.00`)
960
1077
  - [ ] Dates as `dd/mm/yyyy`, in the input and when sorting
961
- - [ ] Totals in the footer
962
1078
  - [ ] A checkbox column to select rows, with "check all"
963
1079
  - [ ] More events: when editing starts, after saving, row click and double click
964
1080
  - [ ] Detail rows that open under a row
@@ -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.
@@ -116,11 +170,13 @@ type Texts = {
116
170
  readonly keep: string;
117
171
  /** Under a row when `onDelete` throws something that isn't an `Error`. */
118
172
  readonly deleteFailed: string;
173
+ /** In the footer's first cell, when that column has no total of its own. */
174
+ readonly total: string;
119
175
  /** Shown in a select while its options load. */
120
176
  readonly loading: string;
121
177
  /** Under a row when `onSave` throws something that isn't an `Error`. */
122
178
  readonly saveFailed: string;
123
- /** Under a new row when `onAdd` throws something that isn’t an `Error`. */
179
+ /** Under a new row when `onAdd` throws something that isn't an `Error`. */
124
180
  readonly addFailed: string;
125
181
  /** Under a select whose options failed to load. */
126
182
  readonly loadFailed: string;
@@ -216,18 +272,18 @@ type TextEditor = BaseEditor & {
216
272
  /**
217
273
  * Which editors a column can have, from its value type:
218
274
  *
219
- * | Column value | Built-in editors |
220
- * | ------------- | ------------------ |
221
- * | `string` | text, date, select |
222
- * | `number` | number, select |
223
- * | `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 |
224
280
  *
225
281
  * `custom` works on anything. Nullable columns get the same editors as
226
282
  * non-nullable ones.
227
283
  */
228
284
  type EditorFor<Value, Row> = EditorForValue<NonNullable<Value>, Row> | CustomEditor<Value>;
229
285
  /** The built-in editors for a non-null value type. */
230
- 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;
231
287
  /**
232
288
  * Works on every editor. An empty value fails `required` and skips every
233
289
  * other check. Otherwise the editor's own rules (`min`, `maxLength`…) run,
@@ -254,6 +310,23 @@ type ValidationOptions<Row, Value> = {
254
310
  */
255
311
  readonly validate?: (value: Value | null, row: Row) => string | undefined;
256
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";
257
330
  /**
258
331
  * A table column. The `editor` has to fit the type of `prop`, so a number
259
332
  * field can't get a text input. Columns without an editor are read-only.
@@ -275,12 +348,21 @@ type ColumnFor<Row extends object, Key extends keyof Row & string> = {
275
348
  readonly editor?: EditorFor<Row[Key], Row> & ValidationOptions<Row, Row[Key]>;
276
349
  /**
277
350
  * The cell's text when the row isn't open. It's shown as text, not HTML.
278
- * 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.
279
353
  *
280
354
  * @example
281
355
  * render: (value) => `${value} MAD`
282
356
  */
283
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>;
284
366
  /** Like `'60px'` or `'20%'`. */
285
367
  readonly width?: string;
286
368
  /** Hidden columns still keep their value in the row, but can't be edited. */
@@ -380,6 +462,14 @@ type TadabutOptions<Row extends object> = {
380
462
  * texts: { ...fr, save: 'Valider' }
381
463
  */
382
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;
383
473
  /**
384
474
  * Called with the edited row once it passes validation. May be async.
385
475
  *
@@ -474,6 +564,10 @@ declare class Tadabut<Row extends object> {
474
564
  private readonly deleting;
475
565
  /** The row `add()` opened, if any. */
476
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;
477
571
  /**
478
572
  * Builds the table inside `container`, which should be empty.
479
573
  *
@@ -481,6 +575,7 @@ declare class Tadabut<Row extends object> {
481
575
  * @throws If `onDelete` is set and there's no `rowId`.
482
576
  * @throws If a hidden column (`visible: false`) has an `editor`.
483
577
  * @throws If a select's `labelProp` is its own column.
578
+ * @throws If a money editor's `separator` and `point` are the same.
484
579
  */
485
580
  constructor(container: HTMLElement, options: TadabutOptions<Row>);
486
581
  /**
@@ -597,9 +692,14 @@ declare class Tadabut<Row extends object> {
597
692
  private readonly onClick;
598
693
  /** Enter saves, Escape cancels, in edited rows and the new row. */
599
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;
600
700
  }
601
701
  /** English, the default. */
602
702
  declare const en: Texts;
603
703
  /** French. */
604
704
  declare const fr: Texts;
605
- 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-mZisu7MG.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-DWwW61Yo.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,4 +1,4 @@
1
- import { c as TadabutOptions, r as Tadabut$1 } from "./index-mZisu7MG.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
4
  export type TadabutHandle<Row extends object> = Pick<Tadabut$1<Row>, "edit" | "save" | "cancel" | "delete" | "isEditing" | "add" | "isAdding" | "saveNew" | "cancelNew">;
@@ -12,9 +12,9 @@ export type TadabutProps<Row extends object> = TadabutOptions<Row> & {
12
12
  };
13
13
  /**
14
14
  * New `data` updates the table in place. Changing `columns`, `rowId`,
15
- * `dataTables` or `texts` rebuilds it (and closes open rows), so keep those
16
- * stable with a constant or `useMemo`. `editing`, `classNames`, `onSave`,
17
- * `onAdd`, `onDelete` and `confirmDelete` can be inline: they're compared by value or
18
- * read through a ref.
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
18
+ * inline: they're compared by value or read through a ref.
19
19
  */
20
- export declare function Tadabut<Row extends object>({ data, columns, rowId, editing, classNames, dataTables, texts, onSave, onAdd, onDelete, confirmDelete, 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-DWwW61Yo.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,12 +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`, `onSave`,
22
- * `onAdd`, `onDelete` and `confirmDelete` can be inline: they're compared by value or
23
- * read through a ref.
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
23
+ * inline: they're compared by value or read through a ref.
24
24
  */
25
- function Tadabut({ data, columns, rowId, editing, classNames, dataTables, texts, onSave, onAdd, onDelete, confirmDelete, ref }) {
25
+ function Tadabut({ data, columns, rowId, editing, classNames, dataTables, texts, totalRows, onSave, onAdd, onDelete, confirmDelete, ref }) {
26
26
  /** The `<div>` the core builds the table in. */
27
27
  const containerRef = useRef(null);
28
28
  /** The core table. `null` before the first build and after unmount. */
@@ -68,6 +68,7 @@ function Tadabut({ data, columns, rowId, editing, classNames, dataTables, texts,
68
68
  },
69
69
  dataTables,
70
70
  texts,
71
+ totalRows,
71
72
  classNames: {
72
73
  table: tableClass,
73
74
  button: buttonClass,
@@ -93,6 +94,7 @@ function Tadabut({ data, columns, rowId, editing, classNames, dataTables, texts,
93
94
  rowId,
94
95
  dataTables,
95
96
  texts,
97
+ totalRows,
96
98
  mode,
97
99
  button,
98
100
  tableClass,
@@ -1,4 +1,87 @@
1
1
  import DataTable from "datatables.net";
2
+ // src/editors/money-format.ts
3
+ /** `12 500.00`. */
4
+ const defaultMoneyFormat = {
5
+ decimals: 2,
6
+ separator: " ",
7
+ point: "."
8
+ };
9
+ /** `12500` → `'12 500.00'`, `null` → `''`. */
10
+ function formatMoney(value, format) {
11
+ if (value === null) return "";
12
+ const fixed = value.toFixed(format.decimals);
13
+ const sign = fixed.startsWith("-") ? "-" : "";
14
+ const [whole = "", decimals = ""] = fixed.slice(sign.length).split(".");
15
+ const grouped = sign + groupThousands(whole, format.separator);
16
+ return format.decimals > 0 ? grouped + format.point + decimals : grouped;
17
+ }
18
+ /** `'12 500,5'` → `12500.5`, rounded to `decimals`. Empty or not a number → `null`. */
19
+ function parseMoney(text, format) {
20
+ let cleaned = text.replaceAll(format.separator, "").replace(/\s/g, "");
21
+ for (const mark of decimalMarks(format)) cleaned = cleaned.replaceAll(mark, ".");
22
+ if (cleaned === "") return null;
23
+ const value = Number(cleaned);
24
+ if (Number.isNaN(value)) return null;
25
+ const factor = 10 ** format.decimals;
26
+ return Math.round((value + Number.EPSILON) * factor) / factor;
27
+ }
28
+ /**
29
+ * Cleans and regroups what's being typed, without filling in the decimals.
30
+ * `'12500,5'` → `'12 500.5'`, `'12 500.'` stays, `'12.345'` → `'12.34'`.
31
+ */
32
+ function formatTyping(text, format) {
33
+ const trimmed = text.trim();
34
+ const sign = trimmed.startsWith("-") ? "-" : "";
35
+ const marks = decimalMarks(format);
36
+ const markAt = [...trimmed].findIndex((char) => marks.includes(char));
37
+ const hasMark = markAt !== -1;
38
+ const before = hasMark ? trimmed.slice(0, markAt) : trimmed;
39
+ const after = hasMark ? trimmed.slice(markAt + 1) : "";
40
+ let whole = before.replace(/\D/g, "").replace(/^0+(?=\d)/, "");
41
+ const decimals = after.replace(/\D/g, "").slice(0, format.decimals);
42
+ const hasPoint = hasMark && format.decimals > 0;
43
+ if (whole === "" && hasPoint) whole = "0";
44
+ const grouped = sign + groupThousands(whole, format.separator);
45
+ return hasPoint ? grouped + format.point + decimals : grouped;
46
+ }
47
+ /**
48
+ * Counts the characters before `end` that survive formatting: digits,
49
+ * decimal marks and the minus. Formatting adds and removes separators, which
50
+ * would move the cursor. Counting only what stays, before and after, puts it
51
+ * back in the same place.
52
+ */
53
+ function countKept(text, end, format) {
54
+ return [...text.slice(0, end)].filter((char) => isKept(char, format)).length;
55
+ }
56
+ /** The position right after the `kept`-th kept character. See `countKept`. */
57
+ function caretAt(formatted, kept, format) {
58
+ if (kept <= 0) return 0;
59
+ let seen = 0;
60
+ for (const [index, char] of [...formatted].entries()) {
61
+ if (isKept(char, format)) seen += 1;
62
+ if (seen === kept) return index + 1;
63
+ }
64
+ return formatted.length;
65
+ }
66
+ /** A digit, a decimal mark or the minus. */
67
+ function isKept(char, format) {
68
+ return /\d/.test(char) || char === "-" || decimalMarks(format).includes(char);
69
+ }
70
+ /**
71
+ * The keys accepted as a decimal point: the shown one, `.` and `,`, except
72
+ * the separator. With `separator: '.'`, only `,` is a point.
73
+ */
74
+ function decimalMarks(format) {
75
+ return [.../* @__PURE__ */ new Set([
76
+ format.point,
77
+ ".",
78
+ ","
79
+ ])].filter((mark) => mark !== format.separator);
80
+ }
81
+ /** `'12500'` → `'12 500'`. */
82
+ function groupThousands(digits, separator) {
83
+ return digits.replace(/\B(?=(\d{3})+(?!\d))/g, separator);
84
+ }
2
85
  // src/editors/classes.ts
3
86
  /**
4
87
  * `'btn btn-sm '` → `['btn', 'btn-sm']`. Empty pieces are dropped because
@@ -11,6 +94,53 @@ function splitClasses(...lists) {
11
94
  function addClasses(element, ownClasses, className) {
12
95
  element.classList.add(...ownClasses, ...splitClasses(className));
13
96
  }
97
+ // src/editors/money.ts
98
+ /** The config's format, with the defaults filled in. */
99
+ function moneyFormat(config) {
100
+ return {
101
+ decimals: config.decimals ?? defaultMoneyFormat.decimals,
102
+ separator: config.separator ?? defaultMoneyFormat.separator,
103
+ point: config.point ?? defaultMoneyFormat.point
104
+ };
105
+ }
106
+ /**
107
+ * Builds the money input. It regroups while typing, keeps the cursor in place,
108
+ * and fills in the decimals on blur.
109
+ */
110
+ function createMoneyEditor(config, context) {
111
+ const format = moneyFormat(config);
112
+ const input = document.createElement("input");
113
+ input.type = "text";
114
+ input.inputMode = "decimal";
115
+ input.autocomplete = "off";
116
+ addClasses(input, ["tdb-input", "tdb-input-money"], context.className);
117
+ /** Read from the text every time, so there's no copy to get out of sync. */
118
+ const getValue = () => parseMoney(input.value, format);
119
+ /** Shows the value fully formatted, decimals included. */
120
+ const setValue = (value) => {
121
+ input.value = formatMoney(value, format);
122
+ };
123
+ setValue(context.value);
124
+ input.addEventListener("input", () => {
125
+ const caret = input.selectionStart ?? input.value.length;
126
+ const kept = countKept(input.value, caret, format);
127
+ const next = formatTyping(input.value, format);
128
+ if (next !== input.value) {
129
+ input.value = next;
130
+ const position = caretAt(next, kept, format);
131
+ input.setSelectionRange(position, position);
132
+ }
133
+ context.onChange(getValue());
134
+ });
135
+ input.addEventListener("blur", () => setValue(getValue()));
136
+ return {
137
+ element: input,
138
+ getValue,
139
+ setValue,
140
+ focus: () => input.focus(),
141
+ destroy: () => input.remove()
142
+ };
143
+ }
14
144
  // src/columns/escape.ts
15
145
  /** Characters that mean something in HTML. */
16
146
  const entities = {
@@ -121,10 +251,11 @@ function toDataTables(columns, actions, classNames, texts) {
121
251
  }),
122
252
  title: column.title,
123
253
  data: column.prop,
254
+ defaultContent: "",
124
255
  render: (value, type, row) => {
125
256
  switch (type) {
126
257
  case "display": return escapeHtml(label(value, row));
127
- case "filter": return label(value, row);
258
+ case "filter": return `${label(value, row)} ${asText(value)}`;
128
259
  default: return value;
129
260
  }
130
261
  }
@@ -132,10 +263,14 @@ function toDataTables(columns, actions, classNames, texts) {
132
263
  });
133
264
  return actions.length > 0 ? [...converted, actionsColumn(actions, classNames, texts)] : converted;
134
265
  }
135
- /** `render`, then `labelProp`, then a fixed list's label, then the value. */
266
+ /** `render`, then a money format, then `labelProp`, then a fixed list's label, then the value. */
136
267
  function labelOf(column) {
137
268
  const { render, editor } = column;
138
269
  if (render !== void 0) return render;
270
+ if (editor?.type === "money") {
271
+ const format = moneyFormat(editor);
272
+ return (value) => typeof value === "number" ? formatMoney(value, format) : asText(value);
273
+ }
139
274
  if (editor?.type === "select") {
140
275
  const labelProp = editor.labelProp;
141
276
  if (labelProp !== void 0) return (_value, row) => asText(row[labelProp]);
@@ -166,10 +301,11 @@ const en = {
166
301
  confirm: "Yes, delete",
167
302
  keep: "No",
168
303
  deleteFailed: "Could not delete.",
304
+ total: "Total",
169
305
  loading: "Loading…",
170
306
  saveFailed: "Could not save.",
171
- loadFailed: "Could not load the options.",
172
307
  addFailed: "Could not add.",
308
+ loadFailed: "Could not load the options.",
173
309
  required: "This field is required.",
174
310
  patternMismatch: "Wrong format.",
175
311
  tooShort: (min) => `Must be at least ${min} characters.`,
@@ -180,23 +316,32 @@ const en = {
180
316
  tooLate: (max) => `Must be on or before ${max}.`
181
317
  };
182
318
  // src/editors/checkbox.ts
183
- /**
184
- * Builds the checkbox. `_config` is unused for now, but keeps the same
185
- * shape as the other editors.
186
- */
187
- function createCheckboxEditor(_config, context) {
319
+ /** Builds the checkbox. It keeps the row's value as it is until the user clicks it. */
320
+ function createCheckboxEditor(config, context) {
321
+ const { checked, unchecked } = config.values ?? {
322
+ checked: true,
323
+ unchecked: false
324
+ };
325
+ let current = context.value;
188
326
  const input = document.createElement("input");
189
327
  input.type = "checkbox";
190
328
  addClasses(input, ["tdb-input", "tdb-input-checkbox"], context.className);
191
- /** `null` shows as unchecked. */
329
+ /**
330
+ * Only the `checked` value ticks the box. Anything else, `null` included,
331
+ * shows unchecked but is kept.
332
+ */
192
333
  const setValue = (value) => {
193
- input.checked = value === true;
334
+ current = value;
335
+ input.checked = value === checked;
194
336
  };
195
337
  setValue(context.value);
196
- input.addEventListener("change", () => context.onChange(input.checked));
338
+ input.addEventListener("change", () => {
339
+ current = input.checked ? checked : unchecked;
340
+ context.onChange(current);
341
+ });
197
342
  return {
198
343
  element: input,
199
- getValue: () => input.checked,
344
+ getValue: () => current,
200
345
  setValue,
201
346
  focus: () => input.focus(),
202
347
  destroy: () => input.remove()
@@ -375,9 +520,10 @@ function createEditor(config, context, texts = en) {
375
520
  case "text": return loosen(createTextEditor(config, tighten(fullContext)));
376
521
  case "number": return loosen(createNumberEditor(config, tighten(fullContext)));
377
522
  case "date": return loosen(createDateEditor(config, tighten(fullContext)));
378
- case "checkbox": return loosen(createCheckboxEditor(config, tighten(fullContext)));
523
+ case "checkbox": return createCheckboxEditor(config, fullContext);
379
524
  case "select": return createSelectEditor(config, fullContext, texts);
380
525
  case "custom": return config.create(fullContext);
526
+ case "money": return loosen(createMoneyEditor(config, tighten(fullContext)));
381
527
  default: throw new Error(`Unknown editor: ${JSON.stringify(config)}`);
382
528
  }
383
529
  }
@@ -399,7 +545,8 @@ function validateValue(config, value, row, texts = en) {
399
545
  function builtInError(config, value, texts) {
400
546
  switch (config.type) {
401
547
  case "text": return typeof value === "string" ? textError(config, value, texts) : void 0;
402
- case "number": return typeof value === "number" ? rangeError(config, value, texts) : void 0;
548
+ case "number":
549
+ case "money": return typeof value === "number" ? rangeError(config, value, texts) : void 0;
403
550
  case "date": return typeof value === "string" ? dateError(config, value, texts) : void 0;
404
551
  case "checkbox":
405
552
  case "select":
@@ -594,6 +741,7 @@ var EditSession = class {
594
741
  * @throws If `onDelete` is set and there's no `rowId`.
595
742
  * @throws If a hidden column (`visible: false`) has an `editor`.
596
743
  * @throws If a select's `labelProp` is its own column.
744
+ * @throws If a money editor's `separator` and `point` are the same.
597
745
  */
598
746
  function checkOptions(options) {
599
747
  if (options.rowId === void 0) {
@@ -604,6 +752,11 @@ function checkOptions(options) {
604
752
  if (hiddenEditable !== void 0) throw new Error(`Tadabut: the "${hiddenEditable.prop}" column can't have both an editor and visible: false.`);
605
753
  const selfLabeled = options.columns.find((column) => column.editor?.type === "select" && column.editor.labelProp === column.prop);
606
754
  if (selfLabeled !== void 0) throw new Error(`Tadabut: the "${selfLabeled.prop}" column's labelProp can't be "${selfLabeled.prop}" itself.`);
755
+ for (const column of options.columns) {
756
+ if (column.editor?.type !== "money") continue;
757
+ const { separator, point } = moneyFormat(column.editor);
758
+ if (separator === point) throw new Error(`Tadabut: the "${column.prop}" column's money separator and point can't both be "${point}".`);
759
+ }
607
760
  }
608
761
  // src/table/new-row.ts
609
762
  /**
@@ -645,7 +798,9 @@ var NewRow = class {
645
798
  this.tr.append(actionsCell);
646
799
  }
647
800
  this.body.append(this.tr);
648
- this.session = new EditSession(defaults, cells, options.texts);
801
+ const start = { ...defaults };
802
+ for (const { column } of cells) start[column.prop] ??= null;
803
+ this.session = new EditSession(start, cells, options.texts);
649
804
  this.firstProp = cells[0]?.column.prop;
650
805
  }
651
806
  /** Whether `onAdd` is running. */
@@ -710,6 +865,50 @@ var NewRow = class {
710
865
  this.body.remove();
711
866
  }
712
867
  };
868
+ // src/table/totals.ts
869
+ /**
870
+ * An empty footer, one cell per column. It must be in the table before
871
+ * DataTables starts, or DataTables won't manage it.
872
+ */
873
+ function footerFor(cellCount) {
874
+ const tfoot = document.createElement("tfoot");
875
+ tfoot.classList.add("tdb-totals");
876
+ const tr = document.createElement("tr");
877
+ for (let index = 0; index < cellCount; index++) tr.append(document.createElement("th"));
878
+ tfoot.append(tr);
879
+ return tfoot;
880
+ }
881
+ /** The DataTables filter for each `totalRows`. */
882
+ function rowsFor(totalRows) {
883
+ switch (totalRows) {
884
+ case "searched": return { search: "applied" };
885
+ case "all": return { search: "none" };
886
+ case "page": return { page: "current" };
887
+ }
888
+ }
889
+ /** The text under a column: `count` and functions as they are, numbers formatted like the cells. */
890
+ function totalText(column, rows) {
891
+ const { prop, total, render, editor } = column;
892
+ if (total === void 0) return "";
893
+ if (typeof total === "function") return total(rows);
894
+ if (total === "count") return String(rows.length);
895
+ const result = compute(total, rows.map((row) => row[prop]).filter((value) => typeof value === "number" && !Number.isNaN(value)));
896
+ if (result === void 0) return "";
897
+ if (editor?.type === "money" && render === void 0) return formatMoney(result, moneyFormat(editor));
898
+ const rounded = Math.round(result * 100) / 100;
899
+ return render === void 0 ? String(rounded) : render(rounded, {});
900
+ }
901
+ /** `undefined` when there's nothing to average, or no smallest or biggest. */
902
+ function compute(total, values) {
903
+ const sum = values.reduce((a, b) => a + b, 0);
904
+ if (total === "sum") return sum;
905
+ if (values.length === 0) return;
906
+ switch (total) {
907
+ case "avg": return sum / values.length;
908
+ case "min": return Math.min(...values);
909
+ case "max": return Math.max(...values);
910
+ }
911
+ }
713
912
  // src/table/tadabut.ts
714
913
  /**
715
914
  * A DataTables table with row editing.
@@ -759,6 +958,10 @@ var Tadabut = class {
759
958
  deleting = /* @__PURE__ */ new Set();
760
959
  /** The row `add()` opened, if any. */
761
960
  newRow;
961
+ /** Whether any column has a `total`, so the table has a footer. */
962
+ hasTotals;
963
+ /** Which rows the totals count, with its default filled in. */
964
+ totalRows;
762
965
  /**
763
966
  * Builds the table inside `container`, which should be empty.
764
967
  *
@@ -766,6 +969,7 @@ var Tadabut = class {
766
969
  * @throws If `onDelete` is set and there's no `rowId`.
767
970
  * @throws If a hidden column (`visible: false`) has an `editor`.
768
971
  * @throws If a select's `labelProp` is its own column.
972
+ * @throws If a money editor's `separator` and `point` are the same.
769
973
  */
770
974
  constructor(container, options) {
771
975
  checkOptions(options);
@@ -789,14 +993,21 @@ var Tadabut = class {
789
993
  ...en,
790
994
  ...options.texts
791
995
  };
996
+ this.hasTotals = options.columns.some((column) => column.total !== void 0);
997
+ this.totalRows = options.totalRows ?? "searched";
792
998
  this.tableEl = document.createElement("table");
793
999
  addClasses(this.tableEl, [], this.classNames.table);
794
1000
  container.appendChild(this.tableEl);
1001
+ if (this.hasTotals) this.tableEl.append(footerFor(this.columns.length + (this.hasActions ? 1 : 0)));
795
1002
  this.dataTable = new DataTable(this.tableEl, {
796
1003
  ...options.dataTables,
797
1004
  data: [...options.data],
798
1005
  columns: toDataTables(options.columns, actions, this.classNames, this.texts)
799
1006
  });
1007
+ if (this.hasTotals) {
1008
+ this.dataTable.on("draw", this.updateTotals);
1009
+ this.updateTotals();
1010
+ }
800
1011
  if (this.hasActions) this.tableEl.addEventListener("click", this.onClick);
801
1012
  if (this.hasEditor) this.tableEl.addEventListener("keydown", this.onKeyDown);
802
1013
  }
@@ -1161,6 +1372,18 @@ var Tadabut = class {
1161
1372
  this.cancel(id);
1162
1373
  }
1163
1374
  };
1375
+ /**
1376
+ * Writes every total. Runs after each redraw: search, paging, save, add,
1377
+ * delete and `setData` all redraw.
1378
+ */
1379
+ updateTotals = () => {
1380
+ const rows = this.dataTable.rows(rowsFor(this.totalRows)).data().toArray();
1381
+ this.columns.forEach((column, index) => {
1382
+ const cell = this.dataTable.column(index).footer();
1383
+ if (column.total !== void 0) cell.textContent = totalText(column, rows);
1384
+ else if (index === 0) cell.textContent = this.texts.total;
1385
+ });
1386
+ };
1164
1387
  };
1165
1388
  // src/texts/fr.ts
1166
1389
  /** French. */
@@ -1173,6 +1396,7 @@ const fr = {
1173
1396
  confirm: "Oui, supprimer",
1174
1397
  keep: "Non",
1175
1398
  deleteFailed: "Impossible de supprimer.",
1399
+ total: "Total",
1176
1400
  loading: "Chargement…",
1177
1401
  saveFailed: "Impossible d'enregistrer.",
1178
1402
  addFailed: "Impossible d'ajouter.",
@@ -1186,4 +1410,4 @@ const fr = {
1186
1410
  tooEarly: (min) => `Doit être le ${min} ou après.`,
1187
1411
  tooLate: (max) => `Doit être le ${max} ou avant.`
1188
1412
  };
1189
- export { Tadabut as n, en as r, fr as t };
1413
+ export { formatMoney as a, defaultMoneyFormat as i, Tadabut as n, en as r, fr as t };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tadabut",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Typed wrapper for DataTables with row editing, rich inputs and chained selects.",
5
5
  "keywords": [
6
6
  "datatables",
@@ -53,7 +53,7 @@
53
53
  "react-dom": "^19.3.1",
54
54
  "tsdown": "^0.23.5",
55
55
  "typescript": "^7.0.2",
56
- "vite": "^8.3.5",
56
+ "vite": "^8.3.6",
57
57
  "vitest": "^5.1.0"
58
58
  },
59
59
  "devEngines": {