tadabut 0.6.0 → 0.7.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.
@@ -1,8 +1,13 @@
1
- import { Config } from "datatables.net";
1
+ import { Api, Config } from "datatables.net";
2
2
  /** Options every editor has. */
3
3
  type BaseEditor = {
4
4
  /** Extra classes for the input, like `'form-control'`. */
5
5
  readonly className?: string;
6
+ /**
7
+ * Shows the value in a locked input. The field is never checked, and saving
8
+ * keeps the value as it was. Defaults to `false`.
9
+ */
10
+ readonly readOnly?: boolean;
6
11
  };
7
12
  /** What a custom editor's `create` receives. */
8
13
  type EditorContext<Value> = {
@@ -10,6 +15,8 @@ type EditorContext<Value> = {
10
15
  readonly value: Value;
11
16
  /** The `className` from the editor config. Put it on your element. */
12
17
  readonly className?: string;
18
+ /** Whether the field is locked. With `true`, disable your input. */
19
+ readonly readOnly?: boolean;
13
20
  /** Call it when the user changes the value. */
14
21
  readonly onChange: (value: Value) => void;
15
22
  };
@@ -75,7 +82,10 @@ type CheckboxEditor<Value = boolean> = BaseEditor & {
75
82
  type CustomEditor<Value> = BaseEditor & {
76
83
  /** Picks this editor. */
77
84
  readonly type: "custom";
78
- /** Builds your editor. Runs every time a row opens. */
85
+ /**
86
+ * Builds your editor. Runs every time a row opens. With `readOnly`,
87
+ * `context.readOnly` is `true`: disable your input.
88
+ */
79
89
  readonly create: (context: EditorContext<Value>) => EditorInstance<Value>;
80
90
  };
81
91
  /** The separators a date format can use. */
@@ -129,6 +139,35 @@ type DateEditor = BaseEditor & {
129
139
  /** How the cell shows it. Defaults to `format`. */
130
140
  readonly display?: DateFormat;
131
141
  };
142
+ /**
143
+ * For `string` columns holding a date and a time: the date in `format`, then
144
+ * the time, like `'05/01/2024 14:30'`. With the default ISO format, a `T`
145
+ * goes between them: `'2024-01-05T14:30'`.
146
+ *
147
+ * When reading, a `T` or a space both work, a date alone counts as midnight,
148
+ * and what comes after the seconds (`.000Z`) is ignored: the time is shown as
149
+ * written, not converted. Anything else shows as empty and saves as `null`.
150
+ *
151
+ * @example
152
+ * { type: 'datetime', format: 'dd/mm/yyyy', min: '01/01/2020 08:00' }
153
+ */
154
+ type DateTimeEditor = BaseEditor & {
155
+ /** Picks this editor. */
156
+ readonly type: "datetime";
157
+ /**
158
+ * How the date part is written in your rows. Defaults to `'yyyy-mm-dd'`.
159
+ * The time always follows, as `hh:mm`.
160
+ */
161
+ readonly format?: DateFormat;
162
+ /** How the cell shows the date part. Defaults to `format`. */
163
+ readonly display?: DateFormat;
164
+ /** Earliest date and time, written like the data: `'01/01/2020 08:00'`. */
165
+ readonly min?: string;
166
+ /** Latest date and time, written like the data. */
167
+ readonly max?: string;
168
+ /** Shows and saves the seconds. Defaults to `false`. */
169
+ readonly seconds?: boolean;
170
+ };
132
171
  /** How a money input and its cells look. */
133
172
  type MoneyFormat = {
134
173
  /** Digits after the point. */
@@ -223,6 +262,14 @@ type Texts = {
223
262
  readonly required: string;
224
263
  /** A text that doesn't match `pattern`. */
225
264
  readonly patternMismatch: string;
265
+ /** The label of the ▸ button, for screen readers. */
266
+ readonly showDetail: string;
267
+ /** Its label while the detail is open. */
268
+ readonly hideDetail: string;
269
+ /** Shown while an async `detail` loads. */
270
+ readonly detailLoading: string;
271
+ /** Shown when `detail` throws something that isn't an `Error`. */
272
+ readonly detailFailed: string;
226
273
  /** A text shorter than `minLength`. */
227
274
  readonly tooShort: (min: number) => string;
228
275
  /** A text longer than `maxLength`. */
@@ -231,10 +278,14 @@ type Texts = {
231
278
  readonly tooSmall: (min: number) => string;
232
279
  /** A number above `max`. */
233
280
  readonly tooLarge: (max: number) => string;
234
- /** A date before `min`, given as `'YYYY-MM-DD'`. */
281
+ /** A date before `min`, given as the column shows dates (its `display`). */
235
282
  readonly tooEarly: (min: string) => string;
236
- /** A date after `max`, given as `'YYYY-MM-DD'`. */
283
+ /** A date after `max`, given as the column shows dates (its `display`). */
237
284
  readonly tooLate: (max: string) => string;
285
+ /** A time before `min`, like `'08:00'`. */
286
+ readonly timeTooEarly: (min: string) => string;
287
+ /** A time after `max`, like `'18:00'`. */
288
+ readonly timeTooLate: (max: string) => string;
238
289
  };
239
290
  /** One choice in a select. */
240
291
  type SelectOption<Value> = {
@@ -308,21 +359,38 @@ type TextEditor = BaseEditor & {
308
359
  /** Must match the whole value, like `'[A-Z]{2}[0-9]{4}'`. No slashes, no `^`/`$`. */
309
360
  readonly pattern?: string;
310
361
  };
362
+ /**
363
+ * For `string` columns holding a time, like `'14:30'`. Anything that isn't a
364
+ * time shows as empty and saves as `null`. Empty gives `null`.
365
+ *
366
+ * @example
367
+ * { type: 'time', min: '08:00', max: '18:00' }
368
+ */
369
+ type TimeEditor = BaseEditor & {
370
+ /** Picks this editor. */
371
+ readonly type: "time";
372
+ /** Earliest time, like `'08:00'`. */
373
+ readonly min?: string;
374
+ /** Latest time, like `'18:00'`. */
375
+ readonly max?: string;
376
+ /** Shows and saves the seconds: `'14:30:00'` instead of `'14:30'`. Defaults to `false`. */
377
+ readonly seconds?: boolean;
378
+ };
311
379
  /**
312
380
  * Which editors a column can have, from its value type:
313
381
  *
314
- * | Column value | Built-in editors |
315
- * | ------------- | --------------------------------------------- |
316
- * | `string` | text, date, select, checkbox with `values` |
317
- * | `number` | number, money, select, checkbox with `values` |
318
- * | `boolean` | checkbox, select |
382
+ * | Column value | Built-in editors |
383
+ * | ------------- | ------------------------------------------------------------- |
384
+ * | `string` | text, date, time, datetime, select, checkbox with `values` |
385
+ * | `number` | number, money, select, checkbox with `values` |
386
+ * | `boolean` | checkbox, select |
319
387
  *
320
388
  * `custom` works on anything. Nullable columns get the same editors as
321
389
  * non-nullable ones.
322
390
  */
323
391
  type EditorFor<Value, Row> = EditorForValue<NonNullable<Value>, Row> | CustomEditor<Value>;
324
392
  /** The built-in editors for a non-null value type. */
325
- 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;
393
+ type EditorForValue<Value, Row> = [Value] extends [string] ? TextEditor | DateEditor | TimeEditor | DateTimeEditor | SelectEditor<Value, Row> | CheckboxEditor<Value> : [Value] extends [number] ? NumberEditor | MoneyEditor | SelectEditor<Value, Row> | CheckboxEditor<Value> : [Value] extends [boolean] ? CheckboxEditor | SelectEditor<Value, Row> : never;
326
394
  /**
327
395
  * Works on every editor. An empty value fails `required` and skips every
328
396
  * other check. Otherwise the editor's own rules (`min`, `maxLength`…) run,
@@ -411,6 +479,38 @@ type ColumnFor<Row extends object, Key extends keyof Row & string> = {
411
479
  /** Classes for the cells (header too), not for the input. */
412
480
  readonly className?: string;
413
481
  };
482
+ /**
483
+ * Reads a date in `format`, then a time after a `T` or a space, and gives
484
+ * `'yyyy-mm-ddThh:mm:ss'`. No time means midnight. A time zone is ignored,
485
+ * not converted. `null` if the date or the time isn't real.
486
+ *
487
+ * @example
488
+ * parseDateTime('05/01/2024 14:30', 'dd/mm/yyyy'); // '2024-01-05T14:30:00'
489
+ */
490
+ declare function parseDateTime(value: string, format: DateFormat): string | null;
491
+ /**
492
+ * Writes a date-time `parseDateTime` returned. `separator` goes between the
493
+ * date and the time.
494
+ *
495
+ * @example
496
+ * formatDateTime('2024-01-05T14:30:00', 'dd/mm/yyyy', false, ' '); // '05/01/2024 14:30'
497
+ */
498
+ declare function formatDateTime(value: string, format: DateFormat, seconds: boolean, separator: string): string;
499
+ /**
500
+ * Reads `'h:mm'`, `'hh:mm'` or `'hh:mm:ss'`, and gives `'hh:mm:ss'`. Anything
501
+ * after is ignored, like `'.000Z'`. `null` if it isn't a real time.
502
+ *
503
+ * @example
504
+ * parseTime('9:05'); // '09:05:00'
505
+ */
506
+ declare function parseTime(value: string): string | null;
507
+ /**
508
+ * Writes a time `parseTime` returned, with or without the seconds.
509
+ *
510
+ * @example
511
+ * formatTime('09:05:00', false); // '09:05'
512
+ */
513
+ declare function formatTime(time: string, seconds: boolean): string;
414
514
  /**
415
515
  * Which rows something counts: every row matching the search (on every
416
516
  * page), every row, or the rows on the page shown.
@@ -477,6 +577,8 @@ type TableClassNames = {
477
577
  readonly keep?: string;
478
578
  /** The selection checkboxes, header included. */
479
579
  readonly select?: string;
580
+ /** The button that opens and closes a detail. */
581
+ readonly detail?: string;
480
582
  };
481
583
  /**
482
584
  * Any {@link https://datatables.net/reference/option/ | DataTables option},
@@ -496,6 +598,13 @@ type SelectionOptions = {
496
598
  */
497
599
  readonly checkAll?: RowScope;
498
600
  };
601
+ /** What `detail` returns: an element, or text. Text is shown as it is, never as HTML. */
602
+ type DetailContent = Node | string;
603
+ /** The second argument of `detail`. */
604
+ type DetailContext = {
605
+ /** Aborted when the detail closes before it finished loading. Pass it to `fetch`. */
606
+ readonly signal: AbortSignal;
607
+ };
499
608
  /** Options for `new Tadabut()`. */
500
609
  type TadabutOptions<Row extends object> = {
501
610
  /** The rows. The array is copied, never changed. */
@@ -541,6 +650,23 @@ type TadabutOptions<Row extends object> = {
541
650
  * click or from code.
542
651
  */
543
652
  readonly onSelect?: (rows: readonly Row[]) => void;
653
+ /**
654
+ * Adds a ▸ button at the start of each row. It opens a line under the row
655
+ * with what this returns. May be async: "Loading…" shows while it waits,
656
+ * and the error message if it throws. It runs again after the row is
657
+ * saved. Needs `rowId`.
658
+ *
659
+ * @example
660
+ * detail: async (row, { signal }) => {
661
+ * const res = await fetch(`/api/orders/${row.id}/lines`, { signal });
662
+ * const box = document.createElement('ul');
663
+ * for (const line of await res.json()) {
664
+ * box.append(Object.assign(document.createElement('li'), { textContent: line.label }));
665
+ * }
666
+ * return box;
667
+ * }
668
+ */
669
+ readonly detail?: (row: Row, context: DetailContext) => DetailContent | Promise<DetailContent>;
544
670
  /**
545
671
  * Called with the edited row once it passes validation. May be async.
546
672
  *
@@ -670,7 +796,7 @@ declare class Tadabut<Row extends object> {
670
796
  private readonly hasTotals;
671
797
  /** Which rows the totals count, with its default filled in. */
672
798
  private readonly totalRows;
673
- /** How many columns Tadabut adds before yours: 1 with `selection`. */
799
+ /** How many columns Tadabut adds before yours: the checkboxes and the ▸ button. */
674
800
  private readonly offset;
675
801
  /** The ticked rows. Only with `selection`. */
676
802
  private readonly selection?;
@@ -686,25 +812,105 @@ declare class Tadabut<Row extends object> {
686
812
  private readonly onRowClick;
687
813
  /** The user's row double click callback. */
688
814
  private readonly onRowDoubleClick;
815
+ /** The lines under each row: details and errors. */
816
+ private readonly rowLines;
817
+ /** The last options each select loaded, by field. */
818
+ private readonly loadedOptions;
689
819
  /**
690
820
  * Builds the table inside `container`, which should be empty.
691
821
  *
692
822
  * @throws If a column has an `editor` and there's no `rowId`.
693
823
  * @throws If `onDelete` is set and there's no `rowId`.
694
824
  * @throws If `selection` is on and there's no `rowId`.
825
+ * @throws If `detail` is set and there's no `rowId`.
695
826
  * @throws If a hidden column (`visible: false`) has an `editor`.
696
827
  * @throws If a select's `labelProp` is its own column.
697
828
  * @throws If a money editor's `separator` and `point` are the same.
698
829
  * @throws If a date editor's `min` or `max` isn't a real date in its `format`.
830
+ * @throws If a time editor's `min` or `max` isn't a real time.
831
+ * @throws If a datetime editor's `min` or `max` isn't a real date and time in its `format`.
699
832
  */
700
833
  constructor(container: HTMLElement, options: TadabutOptions<Row>);
701
834
  /**
702
835
  * Replaces all rows. Sorting, search and the page are kept.
703
836
  *
704
837
  * Open rows, and the new row, are closed first, and their unsaved changes
705
- * are lost.
838
+ * are lost. Open details close too.
706
839
  */
707
840
  setData(rows: readonly Row[]): void;
841
+ /**
842
+ * Every row, in the order shown. `scope` works like `totalRows`: `'all'`
843
+ * (default), `'searched'` or `'page'`. They're copies, so changing them
844
+ * changes nothing: use `updateRow` for that.
845
+ *
846
+ * @example
847
+ * table.getData('searched'); // the rows that match the search
848
+ */
849
+ getData(scope?: RowScope): Row[];
850
+ /**
851
+ * The row with this id, as a copy, or `undefined`. It's the saved row:
852
+ * while a row is edited, what's typed isn't in it until Save.
853
+ */
854
+ getRow(id: string | number): Row | undefined;
855
+ /**
856
+ * The DataTables API, for anything Tadabut doesn't do itself.
857
+ *
858
+ * Careful: rows added or removed through it skip Tadabut, so the
859
+ * selection, details and open rows won't know. Use `insertRow`,
860
+ * `updateRow`, `removeRow` and `setData` for that.
861
+ *
862
+ * @example
863
+ * table.getApi().order([2, 'desc']).draw();
864
+ */
865
+ getApi(): Api<Row>;
866
+ /**
867
+ * Puts one row or many in the table, without `onAdd` or the new-row form,
868
+ * and `onAdded` doesn't fire. They go where the sorting puts them, and the
869
+ * table stays on the page it's on. Either every row goes in, or none.
870
+ *
871
+ * @throws If there's no `rowId`, a row has no `rowId` value, or its id is
872
+ * already in the table (or twice in `rows`).
873
+ *
874
+ * @example
875
+ * table.insertRow(rowFromServer);
876
+ */
877
+ insertRow(rows: Row | readonly Row[]): void;
878
+ /**
879
+ * Replaces the row with the same id, without `onSave`, and `onSaved` doesn't
880
+ * fire. An open detail reloads.
881
+ *
882
+ * @returns `false` if no row has this id, or it's being edited or deleted.
883
+ *
884
+ * @example
885
+ * table.updateRow({ ...table.getRow(1), name: 'Nadia' });
886
+ */
887
+ updateRow(row: Row): boolean;
888
+ /**
889
+ * Takes a row out of the table, without `onDelete` and without asking, and
890
+ * `onDeleted` doesn't fire. Its detail closes, and it leaves the selection.
891
+ *
892
+ * @returns `false` if no row has this id, or it's being edited or deleted.
893
+ */
894
+ removeRow(id: string | number): boolean;
895
+ /**
896
+ * The footer's totals, by field: numbers for built-in totals (not
897
+ * formatted, rounded like the footer), or your function's text. They count
898
+ * the same rows as the footer. If two columns show the same field with a
899
+ * total each, the last one wins.
900
+ *
901
+ * @example
902
+ * table.getTotals().salary; // 176651.5
903
+ */
904
+ getTotals(): Partial<Record<keyof Row & string, number | string>>;
905
+ /**
906
+ * A select's options. With a fixed list, that list. With an `options`
907
+ * function, the list it last loaded in an open row, or `undefined` before
908
+ * any row was opened. `undefined` for a column that isn't a select.
909
+ *
910
+ * @example
911
+ * table.getOptions('countryId'); // [{ value: 1, label: 'Morocco' }, …]
912
+ */
913
+ getOptions<Key extends keyof Row & string>(prop: Key): readonly SelectOption<NonNullable<Row[Key]>>[] | undefined;
708
914
  /**
709
915
  * Opens a row for editing.
710
916
  *
@@ -747,6 +953,21 @@ declare class Tadabut<Row extends object> {
747
953
  deselect(ids: readonly (string | number)[]): void;
748
954
  /** Unselects every row. Does nothing without `selection`. */
749
955
  clearSelection(): void;
956
+ /**
957
+ * Opens a row's detail under it. "Loading…" shows until `detail` returns.
958
+ * Does nothing without `detail`, if it's open already, or if the row
959
+ * isn't in the table.
960
+ *
961
+ * @example
962
+ * onRowClick: (row) => table.toggleDetail(row.id)
963
+ */
964
+ openDetail(id: string | number): void;
965
+ /** Closes a row's detail, and stops its load if it's still running. Does nothing without `detail`. */
966
+ closeDetail(id: string | number): void;
967
+ /** Opens a closed detail, closes an open one, like the ▸ button. Does nothing without `detail`. */
968
+ toggleDetail(id: string | number): void;
969
+ /** Whether a row's detail is open, or loading. Always `false` without `detail`. */
970
+ isDetailOpen(id: string | number): boolean;
750
971
  /**
751
972
  * Closes the new row and throws it away. Does nothing if there's none, or
752
973
  * while it's saving.
@@ -804,10 +1025,6 @@ declare class Tadabut<Row extends object> {
804
1025
  private destroySessions;
805
1026
  /** Also works after the session is gone, so a row can always be unlocked. */
806
1027
  private setSaving;
807
- /** Shows a save or delete error in a child row under the row. */
808
- private showRowError;
809
- /** Removes the save or delete error under a row, if any. */
810
- private clearRowError;
811
1028
  /** The last cell of a row, the one with the buttons. */
812
1029
  private actionsCell;
813
1030
  /**
@@ -820,8 +1037,9 @@ declare class Tadabut<Row extends object> {
820
1037
  /** Whether an element is inside the new row, or its error. */
821
1038
  private isInNewRow;
822
1039
  /**
823
- * `undefined` for rows DataTables doesn't know, like the error row or
824
- * a table inside a custom editor.
1040
+ * `undefined` for rows DataTables doesn't know, like a table inside a custom
1041
+ * editor, and for the lines under a row (detail and error), which DataTables
1042
+ * maps back to their row.
825
1043
  */
826
1044
  private rowIdOf;
827
1045
  /**
@@ -837,12 +1055,14 @@ declare class Tadabut<Row extends object> {
837
1055
  * delete and `setData` all redraw.
838
1056
  */
839
1057
  private readonly updateTotals;
1058
+ /** Keeps the options a select loaded, for `getOptions`. An arrow function, so it can be passed as is. */
1059
+ private readonly rememberOptions;
840
1060
  /** Your column's index as DataTables counts it. */
841
1061
  private dtIndex;
842
1062
  /**
843
1063
  * The row a click landed on, or `undefined` if it doesn't count: buttons,
844
- * inputs, links, the checkbox and buttons cells, the new row, a row being
845
- * edited, the header, the footer and error lines.
1064
+ * inputs, links, the checkbox, ▸ and buttons cells, the new row, a row
1065
+ * being edited, the header, the footer, and the lines under a row.
846
1066
  */
847
1067
  private clickedRow;
848
1068
  /**
@@ -855,4 +1075,4 @@ declare class Tadabut<Row extends object> {
855
1075
  declare const en: Texts;
856
1076
  /** French. */
857
1077
  declare const fr: Texts;
858
- export { parseDate as A, MoneyFormat as C, DateFormat as D, DateEditor as E, CheckboxEditor as M, EditorContext as N, defaultDateFormat as O, EditorInstance as P, MoneyEditor as S, formatMoney as T, SelectEditor as _, EditingOptions as a, Texts as b, TableClassNames as c, Column as d, TotalFunction as f, OptionsContext as g, TextEditor as h, DataTablesSettings as i, CustomEditor as j, formatDate as k, TadabutOptions as l, EditorFor as m, en as n, SaveContext as o, ValidationOptions as p, Tadabut as r, SelectionOptions as s, fr as t, RowScope as u, SelectOption as v, defaultMoneyFormat as w, NumberEditor as x, SelectOptionsLoader as y };
1078
+ export { MoneyFormat as A, CheckboxEditor as B, OptionsContext as C, Texts as D, SelectOptionsLoader as E, DateFormat as F, EditorInstance as H, defaultDateFormat as I, formatDate as L, formatMoney as M, DateTimeEditor as N, NumberEditor as O, DateEditor as P, parseDate as R, TextEditor as S, SelectOption as T, EditorContext as V, Column as _, DetailContent as a, EditorFor as b, SaveContext as c, TadabutOptions as d, RowScope as f, parseDateTime as g, formatDateTime as h, DataTablesSettings as i, defaultMoneyFormat as j, MoneyEditor as k, SelectionOptions as l, parseTime as m, en as n, DetailContext as o, formatTime as p, Tadabut as r, EditingOptions as s, fr as t, TableClassNames as u, TotalFunction as v, SelectEditor as w, TimeEditor as x, ValidationOptions as y, CustomEditor as z };
package/dist/index.d.ts CHANGED
@@ -4,5 +4,5 @@
4
4
  * @packageDocumentation
5
5
  * @module tadabut
6
6
  */
7
- import { A as parseDate, C as MoneyFormat, D as DateFormat, E as DateEditor, M as CheckboxEditor, N as EditorContext, O as defaultDateFormat, P as EditorInstance, S as MoneyEditor, T as formatMoney, _ as SelectEditor, a as EditingOptions, b as Texts, c as TableClassNames, d as Column, f as TotalFunction, g as OptionsContext, h as TextEditor, i as DataTablesSettings, j as CustomEditor, k as formatDate, l as TadabutOptions, m as EditorFor, n as en, o as SaveContext, p as ValidationOptions, r as Tadabut, s as SelectionOptions, t as fr, u as RowScope, v as SelectOption, w as defaultMoneyFormat, x as NumberEditor, y as SelectOptionsLoader } from "./index-C_77p8Jv.js";
8
- export { type CheckboxEditor, type Column, type CustomEditor, type DataTablesSettings, type DateEditor, type DateFormat, type EditingOptions, type EditorContext, type EditorFor, type EditorInstance, type MoneyEditor, type MoneyFormat, type NumberEditor, type OptionsContext, type RowScope, type SaveContext, type SelectEditor, type SelectOption, type SelectOptionsLoader, type SelectionOptions, type TableClassNames, Tadabut, type TadabutOptions, type TextEditor, type Texts, type TotalFunction, type ValidationOptions, defaultDateFormat, defaultMoneyFormat, en, formatDate, formatMoney, fr, parseDate };
7
+ import { A as MoneyFormat, B as CheckboxEditor, C as OptionsContext, D as Texts, E as SelectOptionsLoader, F as DateFormat, H as EditorInstance, I as defaultDateFormat, L as formatDate, M as formatMoney, N as DateTimeEditor, O as NumberEditor, P as DateEditor, R as parseDate, S as TextEditor, T as SelectOption, V as EditorContext, _ as Column, a as DetailContent, b as EditorFor, c as SaveContext, d as TadabutOptions, f as RowScope, g as parseDateTime, h as formatDateTime, i as DataTablesSettings, j as defaultMoneyFormat, k as MoneyEditor, l as SelectionOptions, m as parseTime, n as en, o as DetailContext, p as formatTime, r as Tadabut, s as EditingOptions, t as fr, u as TableClassNames, v as TotalFunction, w as SelectEditor, x as TimeEditor, y as ValidationOptions, z as CustomEditor } from "./index-Cm0OsNb6.js";
8
+ export { type CheckboxEditor, type Column, type CustomEditor, type DataTablesSettings, type DateEditor, type DateFormat, type DateTimeEditor, type DetailContent, type DetailContext, type EditingOptions, type EditorContext, type EditorFor, type EditorInstance, type MoneyEditor, type MoneyFormat, type NumberEditor, type OptionsContext, type RowScope, type SaveContext, type SelectEditor, type SelectOption, type SelectOptionsLoader, type SelectionOptions, type TableClassNames, Tadabut, type TadabutOptions, type TextEditor, type Texts, type TimeEditor, type TotalFunction, type ValidationOptions, defaultDateFormat, defaultMoneyFormat, en, formatDate, formatDateTime, formatMoney, formatTime, fr, parseDate, parseDateTime, parseTime };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- export { n as Tadabut, o as defaultDateFormat, i as defaultMoneyFormat, r as en, s as formatDate, a as formatMoney, t as fr, c as parseDate } from "./src-BxdYoViF.js";
1
+ export { n as Tadabut, u as defaultDateFormat, i as defaultMoneyFormat, r as en, d as formatDate, o as formatDateTime, a as formatMoney, c as formatTime, t as fr, f as parseDate, s as parseDateTime, l as parseTime } from "./src-D6zL6H0B.js";
package/dist/react.d.ts CHANGED
@@ -11,25 +11,46 @@
11
11
  * <Tadabut data={employees} columns={columns} rowId='id' />
12
12
  * ```
13
13
  */
14
- import { l as TadabutOptions, r as Tadabut$1 } from "./index-C_77p8Jv.js";
15
- import { ReactElement, Ref } from "react";
16
- /** What the `ref` gets. No `setData`: change the `data` prop instead. */
17
- export type TadabutHandle<Row extends object> = Pick<Tadabut$1<Row>, "edit" | "save" | "cancel" | "delete" | "isEditing" | "add" | "isAdding" | "saveNew" | "cancelNew" | "getSelected" | "isSelected" | "select" | "deselect" | "clearSelection">;
18
- /** The core options, plus `ref`. */
19
- export type TadabutProps<Row extends object> = TadabutOptions<Row> & {
14
+ import { d as TadabutOptions, o as DetailContext, r as Tadabut$1 } from "./index-Cm0OsNb6.js";
15
+ import { Api } from "datatables.net";
16
+ import { ReactElement, ReactNode, Ref } from "react";
17
+ /**
18
+ * What the `ref` gets. No `setData`: change the `data` prop instead. Before
19
+ * the table is built, `getApi` gives `undefined`.
20
+ */
21
+ export type TadabutHandle<Row extends object> = Pick<Tadabut$1<Row>, "edit" | "save" | "cancel" | "delete" | "isEditing" | "add" | "isAdding" | "saveNew" | "cancelNew" | "getSelected" | "isSelected" | "select" | "deselect" | "clearSelection" | "openDetail" | "closeDetail" | "toggleDetail" | "isDetailOpen" | "getData" | "getRow" | "insertRow" | "updateRow" | "removeRow" | "getTotals" | "getOptions"> & {
22
+ /** The DataTables API, or `undefined` before the table is built. */
23
+ readonly getApi: () => Api<Row> | undefined;
24
+ };
25
+ /** The core options, with `detail` returning JSX, plus `ref`. */
26
+ export type TadabutProps<Row extends object> = Omit<TadabutOptions<Row>, "detail"> & {
27
+ /**
28
+ * Adds a ▸ button at the start of each row. It opens a line under the row
29
+ * with what this returns: any JSX, so hooks, state and your components
30
+ * work inside. May be async: "Loading…" shows while it waits, and the
31
+ * error message if it throws. It runs again after the row is saved. Needs
32
+ * `rowId`.
33
+ *
34
+ * @example
35
+ * detail={(row) => <OrderLines orderId={row.id} />}
36
+ */
37
+ readonly detail?: (row: Row, context: DetailContext) => ReactNode | Promise<ReactNode>;
20
38
  /**
21
39
  * Gives you the same methods as the core table: `edit`, `save`, `cancel`,
22
40
  * `delete`, `add`, `saveNew`, `cancelNew`, `isEditing`, `isAdding`,
23
- * `getSelected`, `isSelected`, `select`, `deselect` and `clearSelection`.
41
+ * `getSelected`, `isSelected`, `select`, `deselect`, `clearSelection`,
42
+ * `openDetail`, `closeDetail`, `toggleDetail`, `isDetailOpen`, `getData`,
43
+ * `getRow`, `getApi`, `insertRow`, `updateRow`, `removeRow`, `getTotals`
44
+ * and `getOptions`.
24
45
  */
25
46
  readonly ref?: Ref<TadabutHandle<Row>>;
26
47
  };
27
48
  /**
28
49
  * New `data` updates the table in place. Changing `columns`, `rowId`,
29
50
  * `dataTables`, `texts`, `totalRows` or `selection` rebuilds it (and closes
30
- * open rows, and clears the selection), so keep the objects stable with a
31
- * constant or `useMemo`. `editing`, `selection`, `classNames` and every `on…`
32
- * callback (and `confirmDelete`) can be inline: they're compared by value or
33
- * read through a ref.
51
+ * open rows and details, and clears the selection), so keep the objects
52
+ * stable with a constant or `useMemo`. `editing`, `selection`, `classNames`,
53
+ * `detail` and every `on…` callback (and `confirmDelete`) can be inline:
54
+ * they're compared by value or read through a ref.
34
55
  */
35
- export declare function Tadabut<Row extends object>({ data, columns, rowId, editing, classNames, dataTables, texts, totalRows, selection, onSelect, onSave, onAdd, onDelete, confirmDelete, onEditStart, onSaved, onAdded, onDeleted, onRowClick, onRowDoubleClick, ref }: TadabutProps<Row>): ReactElement;
56
+ export declare function Tadabut<Row extends object>({ data, columns, rowId, editing, classNames, dataTables, texts, totalRows, selection, onSelect, onSave, onAdd, onDelete, confirmDelete, onEditStart, onSaved, onAdded, onDeleted, onRowClick, onRowDoubleClick, detail, ref }: TadabutProps<Row>): ReactElement;
package/dist/react.js CHANGED
@@ -1,29 +1,17 @@
1
- import { n as Tadabut$1 } from "./src-BxdYoViF.js";
2
- import { useEffect, useImperativeHandle, useRef } from "react";
3
- import { jsx } from "react/jsx-runtime";
1
+ import { n as Tadabut$1 } from "./src-D6zL6H0B.js";
2
+ import { useEffect, useImperativeHandle, useRef, useState } from "react";
3
+ import { createPortal } from "react-dom";
4
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
4
5
  // src/react/index.tsx
5
6
  /**
6
- * The React component.
7
- *
8
- * @packageDocumentation
9
- * @module tadabut/react
10
- *
11
- * @example
12
- * ```tsx
13
- * import { Tadabut } from 'tadabut/react';
14
- *
15
- * <Tadabut data={employees} columns={columns} rowId='id' />
16
- * ```
17
- */
18
- /**
19
7
  * New `data` updates the table in place. Changing `columns`, `rowId`,
20
8
  * `dataTables`, `texts`, `totalRows` or `selection` rebuilds it (and closes
21
- * open rows, and clears the selection), so keep the objects stable with a
22
- * constant or `useMemo`. `editing`, `selection`, `classNames` and every `on…`
23
- * callback (and `confirmDelete`) can be inline: they're compared by value or
24
- * read through a ref.
9
+ * open rows and details, and clears the selection), so keep the objects
10
+ * stable with a constant or `useMemo`. `editing`, `selection`, `classNames`,
11
+ * `detail` and every `on…` callback (and `confirmDelete`) can be inline:
12
+ * they're compared by value or read through a ref.
25
13
  */
26
- function Tadabut({ data, columns, rowId, editing, classNames, dataTables, texts, totalRows, selection, onSelect, onSave, onAdd, onDelete, confirmDelete, onEditStart, onSaved, onAdded, onDeleted, onRowClick, onRowDoubleClick, ref }) {
14
+ function Tadabut({ data, columns, rowId, editing, classNames, dataTables, texts, totalRows, selection, onSelect, onSave, onAdd, onDelete, confirmDelete, onEditStart, onSaved, onAdded, onDeleted, onRowClick, onRowDoubleClick, detail, ref }) {
27
15
  /** The `<div>` the core builds the table in. */
28
16
  const containerRef = useRef(null);
29
17
  /** The core table. `null` before the first build and after unmount. */
@@ -52,6 +40,12 @@ function Tadabut({ data, columns, rowId, editing, classNames, dataTables, texts,
52
40
  const onRowClickRef = useRef(onRowClick);
53
41
  /** The latest `onRowDoubleClick`, so a new one doesn't rebuild the table. */
54
42
  const onRowDoubleClickRef = useRef(onRowDoubleClick);
43
+ /** The latest `detail`, so a new one doesn't rebuild the table. */
44
+ const detailRef = useRef(detail);
45
+ /** The next key for an open detail. Never reused, so a reload gets a fresh one. */
46
+ const nextKeyRef = useRef(0);
47
+ /** The open details React draws into, by key. */
48
+ const [details, setDetails] = useState(() => /* @__PURE__ */ new Map());
55
49
  const mode = editing?.mode;
56
50
  const button = editing?.button;
57
51
  const doubleClick = editing?.doubleClick;
@@ -68,6 +62,7 @@ function Tadabut({ data, columns, rowId, editing, classNames, dataTables, texts,
68
62
  const checkAll = typeof selection === "object" ? selection.checkAll : void 0;
69
63
  const hasDelete = onDelete !== void 0;
70
64
  const confirmWith = confirmDelete === false ? "never" : confirmDelete === void 0 ? "inline" : "function";
65
+ const hasDetail = detail !== void 0;
71
66
  useEffect(() => {
72
67
  const container = containerRef.current;
73
68
  if (!container) return;
@@ -111,7 +106,23 @@ function Tadabut({ data, columns, rowId, editing, classNames, dataTables, texts,
111
106
  onAdded: (row) => onAddedRef.current?.(row),
112
107
  onDeleted: (row) => onDeletedRef.current?.(row),
113
108
  onRowClick: (row, event) => onRowClickRef.current?.(row, event),
114
- onRowDoubleClick: (row, event) => onRowDoubleClickRef.current?.(row, event)
109
+ onRowDoubleClick: (row, event) => onRowDoubleClickRef.current?.(row, event),
110
+ detail: hasDetail ? async (row, context) => {
111
+ const content = await detailRef.current?.(row, context);
112
+ if (context.signal.aborted) return "";
113
+ const key = nextKeyRef.current++;
114
+ const element = document.createElement("div");
115
+ setDetails((previous) => new Map(previous).set(key, {
116
+ element,
117
+ content
118
+ }));
119
+ context.signal.addEventListener("abort", () => setDetails((previous) => {
120
+ const next = new Map(previous);
121
+ next.delete(key);
122
+ return next;
123
+ }), { once: true });
124
+ return element;
125
+ } : void 0
115
126
  });
116
127
  tableRef.current = table;
117
128
  return () => {
@@ -139,7 +150,8 @@ function Tadabut({ data, columns, rowId, editing, classNames, dataTables, texts,
139
150
  selectionOn,
140
151
  checkAll,
141
152
  hasDelete,
142
- confirmWith
153
+ confirmWith,
154
+ hasDetail
143
155
  ]);
144
156
  useEffect(() => {
145
157
  dataRef.current = data;
@@ -157,6 +169,7 @@ function Tadabut({ data, columns, rowId, editing, classNames, dataTables, texts,
157
169
  onDeletedRef.current = onDeleted;
158
170
  onRowClickRef.current = onRowClick;
159
171
  onRowDoubleClickRef.current = onRowDoubleClick;
172
+ detailRef.current = detail;
160
173
  });
161
174
  useImperativeHandle(ref, () => ({
162
175
  edit: (id) => tableRef.current?.edit(id) ?? false,
@@ -172,8 +185,20 @@ function Tadabut({ data, columns, rowId, editing, classNames, dataTables, texts,
172
185
  isSelected: (id) => tableRef.current?.isSelected(id) ?? false,
173
186
  select: (ids) => tableRef.current?.select(ids),
174
187
  deselect: (ids) => tableRef.current?.deselect(ids),
175
- clearSelection: () => tableRef.current?.clearSelection()
188
+ clearSelection: () => tableRef.current?.clearSelection(),
189
+ openDetail: (id) => tableRef.current?.openDetail(id),
190
+ closeDetail: (id) => tableRef.current?.closeDetail(id),
191
+ toggleDetail: (id) => tableRef.current?.toggleDetail(id),
192
+ isDetailOpen: (id) => tableRef.current?.isDetailOpen(id) ?? false,
193
+ getData: (scope) => tableRef.current?.getData(scope) ?? [],
194
+ getRow: (id) => tableRef.current?.getRow(id),
195
+ getApi: () => tableRef.current?.getApi(),
196
+ insertRow: (rows) => tableRef.current?.insertRow(rows),
197
+ updateRow: (row) => tableRef.current?.updateRow(row) ?? false,
198
+ removeRow: (id) => tableRef.current?.removeRow(id) ?? false,
199
+ getTotals: () => tableRef.current?.getTotals() ?? {},
200
+ getOptions: (prop) => tableRef.current?.getOptions(prop)
176
201
  }), []);
177
- return /* @__PURE__ */ jsx("div", { ref: containerRef });
202
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("div", { ref: containerRef }), [...details].map(([key, { element, content }]) => createPortal(content, element, key))] });
178
203
  }
179
204
  export { Tadabut };