tadabut 0.2.0 → 0.3.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tadabut",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Typed wrapper for DataTables with row editing, rich inputs and chained selects.",
5
5
  "keywords": [
6
6
  "datatables",
@@ -20,7 +20,7 @@
20
20
  "type": "git",
21
21
  "url": "git+https://github.com/ayem1412/tadabut.git"
22
22
  },
23
- "homepage": "https://github.com/ayem1412/tadabut#readme",
23
+ "homepage": "https://ayem1412.github.io/tadabut/",
24
24
  "bugs": "https://github.com/ayem1412/tadabut/issues",
25
25
  "license": "MIT",
26
26
  "type": "module",
@@ -54,7 +54,7 @@
54
54
  "tsdown": "^0.23.4",
55
55
  "typescript": "^7.0.2",
56
56
  "vite": "^8.3.5",
57
- "vitest": "^5.0.5"
57
+ "vitest": "^5.1.0"
58
58
  },
59
59
  "devEngines": {
60
60
  "packageManager": {
@@ -69,6 +69,7 @@
69
69
  "./package.json": "./package.json"
70
70
  },
71
71
  "scripts": {
72
+ "docs": "pnpm dlx --package typedoc@0.28.20 --package typescript@6.0.x typedoc",
72
73
  "dev": "vite",
73
74
  "build": "tsdown",
74
75
  "test": "vitest",
@@ -1,603 +0,0 @@
1
- /**
2
- * Options shared by every editor.
3
- *
4
- * Internal: users never write this type. Its fields show up on each editor.
5
- */
6
- type BaseEditor = {
7
- /**
8
- * Extra CSS classes added to the input, next to Tadabut's own `tdb-…`
9
- * classes. Use it for Tailwind or Bootstrap classes, like `'form-control'`.
10
- */
11
- readonly className?: string;
12
- };
13
- /**
14
- * What an editor receives when Tadabut creates it, at the start of a row edit.
15
- *
16
- * Custom editors get the same context as the built-in ones.
17
- *
18
- * @typeParam Value - The column's value type.
19
- */
20
- type EditorContext<Value> = {
21
- /** The value from the row when editing starts. */
22
- readonly value: Value;
23
- /**
24
- * Extra CSS classes from the editor config, if any. Add them to the
25
- * element, next to your own classes.
26
- */
27
- readonly className?: string;
28
- /**
29
- * Call this every time the user changes the value, with the new value.
30
- * Tadabut keeps track of the previous one.
31
- */
32
- readonly onChange: (value: Value) => void;
33
- };
34
- /**
35
- * A live editor: the input shown in a cell while a row is being edited.
36
- *
37
- * Every editor, built-in or custom, returns one of these. Tadabut puts
38
- * `element` in the cell, reads the value with `getValue` when saving, and
39
- * calls `destroy` when editing ends.
40
- *
41
- * @typeParam Value - The column's value type.
42
- */
43
- type EditorInstance<Value> = {
44
- /** The root element. Tadabut adds it to the cell. */
45
- readonly element: HTMLElement;
46
- /** Returns the value the user has entered so far. */
47
- readonly getValue: () => Value;
48
- /** Shows a new value, without calling `onChange`. */
49
- readonly setValue: (value: Value) => void;
50
- /** Puts the cursor in the editor. */
51
- readonly focus: () => void;
52
- /**
53
- * Removes the element and cleans up anything the editor created, like
54
- * listeners or third-party widgets. Called once, when editing ends.
55
- */
56
- readonly destroy: () => void;
57
- };
58
- /**
59
- * A checkbox, for `boolean` columns. Checked means `true`.
60
- *
61
- * A `null` value shows as unchecked. The checkbox always gives back `true`
62
- * or `false`, never `null`.
63
- *
64
- * @example
65
- * { type: 'checkbox' }
66
- */
67
- type CheckboxEditor = BaseEditor & {
68
- readonly type: "checkbox";
69
- };
70
- /**
71
- * An editor you build yourself, like a Select2 dropdown or a date picker
72
- * library. Works on any column, including object columns that have no
73
- * built-in editor.
74
- *
75
- * Tadabut calls `create` each time a row starts being edited. It gets the
76
- * starting value (which can be `null` on a nullable column), the
77
- * `className` from this config, and an `onChange` to call when the user
78
- * changes the value.
79
- *
80
- * @typeParam Value - The column's value type, including `null` if the
81
- * column can hold it.
82
- *
83
- * @example
84
- * {
85
- * type: 'custom',
86
- * create: (context) => {
87
- * const input = document.createElement('input');
88
- * input.value = context.value ?? '';
89
- * input.addEventListener('input', () => context.onChange(input.value));
90
- * return {
91
- * element: input,
92
- * getValue: () => input.value,
93
- * setValue: (value) => { input.value = value ?? ''; },
94
- * focus: () => input.focus(),
95
- * destroy: () => input.remove(),
96
- * };
97
- * },
98
- * }
99
- */
100
- type CustomEditor<Value> = BaseEditor & {
101
- readonly type: "custom";
102
- /** Builds the live editor. Called once per row edit. */
103
- readonly create: (context: EditorContext<Value>) => EditorInstance<Value>;
104
- };
105
- /**
106
- * A date picker, for `string` columns holding dates as `'YYYY-MM-DD'`.
107
- *
108
- * The options match the HTML `<input type="date">` attributes of the same
109
- * name. An empty input gives `null`.
110
- *
111
- * The column must hold exactly `'YYYY-MM-DD'`. Any other format, like
112
- * `'2024-01-05T00:00:00'`, shows as an empty input, and saving would turn it
113
- * into `null`. Convert dates to `'YYYY-MM-DD'` before giving them to the
114
- * table.
115
- *
116
- * @example
117
- * { type: 'date', min: '2020-01-01', max: '2030-12-31' }
118
- */
119
- type DateEditor = BaseEditor & {
120
- readonly type: "date";
121
- /** Earliest date allowed, as `'YYYY-MM-DD'`. */
122
- readonly min?: string;
123
- /** Latest date allowed, as `'YYYY-MM-DD'`. */
124
- readonly max?: string;
125
- };
126
- /**
127
- * A number input, for `number` columns.
128
- *
129
- * An empty input gives `null`, not `0`.
130
- *
131
- * The options match the HTML `<input type="number">` attributes of the same
132
- * name.
133
- *
134
- * @example
135
- * { type: 'number', min: 18, max: 65, step: 1 }
136
- */
137
- type NumberEditor = BaseEditor & {
138
- readonly type: "number";
139
- /** Smallest value allowed. */
140
- readonly min?: number;
141
- /** Largest value allowed. */
142
- readonly max?: number;
143
- /**
144
- * Allowed gap between values, counted from `min` (or 0).
145
- * `1` allows only whole numbers, `0.01` allows cents, and `'any'` allows
146
- * any decimal. Default: `1`.
147
- */
148
- readonly step?: number | "any";
149
- };
150
- /**
151
- * One choice in a select.
152
- *
153
- * @typeParam Value - The column's value type.
154
- */
155
- type SelectOption<Value> = {
156
- /** Text shown to the user. */
157
- readonly label: string;
158
- /** Value saved in the row when this choice is picked. */
159
- readonly value: Value;
160
- };
161
- /**
162
- * What a select's `options` function gets next to the row.
163
- */
164
- type OptionsContext = {
165
- /**
166
- * Aborted when the options aren't needed anymore: the field it depends on
167
- * changed again, or the row was closed. Pass it to `fetch` so old requests
168
- * stop.
169
- */
170
- readonly signal: AbortSignal;
171
- };
172
- /**
173
- * A select's options as a function of the row. It can return the list right
174
- * away, or a promise of it.
175
- *
176
- * @typeParam Value - The column's value type.
177
- * @typeParam Row - The shape of one row.
178
- */
179
- type SelectOptionsLoader<Value, Row> = (row: Row, context: OptionsContext) => readonly SelectOption<Value>[] | Promise<readonly SelectOption<Value>[]>;
180
- /**
181
- * A dropdown list. Works for `string`, `number` and `boolean` columns.
182
- *
183
- * Option values must have the same type as the column: a `number` column
184
- * needs `value: 1`, not `value: '1'`.
185
- *
186
- * When the row's value matches no option (or is `null`), nothing is picked
187
- * and the editor gives `null`.
188
- *
189
- * `options` is either a fixed list, or a function of the row. Only a
190
- * function can have `dependsOn`: when that field changes, this select is
191
- * cleared and its options load again.
192
- *
193
- * @typeParam Value - The column's value type.
194
- * @typeParam Row - The shape of one row.
195
- *
196
- * @example
197
- * // A fixed list
198
- * { type: 'select', options: [{ value: 1, label: 'Morocco' }] }
199
- *
200
- * // Options that depend on another field
201
- * {
202
- * type: 'select',
203
- * dependsOn: 'countryId',
204
- * options: (row, { signal }) => fetchCities(row.countryId, signal),
205
- * }
206
- */
207
- type SelectEditor<Value, Row> = BaseEditor & {
208
- readonly type: "select";
209
- } & ({
210
- /** The choices, in the order they are shown. */
211
- readonly options: readonly SelectOption<Value>[];
212
- /** Only allowed when `options` is a function. */
213
- readonly dependsOn?: never;
214
- } | {
215
- /** Gives the choices for the row being edited. */
216
- readonly options: SelectOptionsLoader<Value, Row>;
217
- /**
218
- * Another field of the row. When it changes, this select is cleared
219
- * and `options` runs again.
220
- */
221
- readonly dependsOn?: keyof Row & string;
222
- });
223
- /**
224
- * A one-line text input, for `string` columns.
225
- *
226
- * The options match the HTML `<input>` attributes of the same name.
227
- *
228
- * @example
229
- * { type: 'text', minLength: 2, maxLength: 50 }
230
- */
231
- type TextEditor = BaseEditor & {
232
- readonly type: "text";
233
- /** Fewest characters allowed. */
234
- readonly minLength?: number;
235
- /** Most characters allowed. The input stops accepting more. */
236
- readonly maxLength?: number;
237
- /**
238
- * A regular expression the whole value must match, written as a string,
239
- * like `'[A-Z]{2}[0-9]{4}'`. No `/…/` slashes and no `^` or `$`:
240
- * the browser always checks the full value.
241
- */
242
- readonly pattern?: string;
243
- };
244
- /**
245
- * The editors that fit a column, based on the type of value it holds.
246
- *
247
- * | Column value | Built-in editors | Custom editor |
248
- * | ------------- | ------------------ | ------------- |
249
- * | `string` | text, date, select | yes |
250
- * | `number` | number, select | yes |
251
- * | `boolean` | checkbox, select | yes |
252
- * | anything else | none | yes |
253
- *
254
- * For built-in editors, `null` and `undefined` are ignored, so a
255
- * `string | null` column gets the same editors as a `string` column.
256
- * A custom editor keeps the full type, `null` included, because it receives
257
- * the row's value as it is.
258
- *
259
- * @typeParam Value - The column's value type.
260
- * @typeParam Row - The shape of one row. Only selects use it, for `options`
261
- * functions and `dependsOn`.
262
- */
263
- type EditorFor<Value, Row> = EditorForValue<NonNullable<Value>, Row> | CustomEditor<Value>;
264
- 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;
265
- /**
266
- * Validation options. They go on any editor, built-in or custom.
267
- *
268
- * Checks run in this order, and the first error wins:
269
- * 1. Empty value (`null`, `undefined` or `''`): an error if `required`,
270
- * otherwise no error and nothing else is checked.
271
- * 2. The editor's own rules, like `min` or `maxLength`.
272
- * 3. `validate`.
273
- *
274
- * @typeParam Row - The shape of one row.
275
- * @typeParam Value - The column's value type.
276
- *
277
- * @example
278
- * {
279
- * type: 'number',
280
- * required: true,
281
- * min: 18,
282
- * validate: (value, row) =>
283
- * row.active && value !== null && value > 65
284
- * ? 'Active employees must be 65 or younger'
285
- * : undefined,
286
- * }
287
- */
288
- type ValidationOptions<Row, Value> = {
289
- /**
290
- * The value can't be empty. Has no effect on a checkbox, which is never
291
- * empty.
292
- */
293
- readonly required?: boolean;
294
- /**
295
- * Your own check. Return an error message, or `undefined` if the value is
296
- * fine. Runs last, only on values that passed the other rules.
297
- *
298
- * `value` can be `null`, because editors give `null` when empty, even on
299
- * columns that can't hold `null`.
300
- */
301
- readonly validate?: (value: Value | null, row: Row) => string | undefined;
302
- };
303
- /**
304
- * One column of a Tadabut table.
305
- *
306
- * `prop` picks the row property to show, and `editor` (optional) must fit
307
- * that property's type: a `number` property can't have a text editor.
308
- * A column without an `editor` is read-only.
309
- *
310
- * @typeParam Row - The shape of one row.
311
- *
312
- * @example
313
- * const columns: Column<Employee>[] = [
314
- * { title: 'ID', prop: 'id' },
315
- * {
316
- * title: 'Age',
317
- * prop: 'age',
318
- * editor: { type: 'number', required: true, min: 18 },
319
- * },
320
- * ];
321
- */
322
- type Column<Row extends object> = { readonly [Key in keyof Row & string]: ColumnFor<Row, Key>; }[keyof Row & string];
323
- /** The column for one row property. `Column` is the union of these. */
324
- type ColumnFor<Row extends object, Key extends keyof Row & string> = {
325
- /** Text shown in the column header. */
326
- readonly title: string;
327
- /** Name of the row property shown in this column. */
328
- readonly prop: Key;
329
- /**
330
- * How the value is edited, and its validation rules. Leave it out for a
331
- * read-only column.
332
- */
333
- readonly editor?: EditorFor<Row[Key], Row> & ValidationOptions<Row, Row[Key]>;
334
- /**
335
- * The text shown in the cell, when the row isn't being edited.
336
- *
337
- * Without it, a select with a fixed list shows its option's label, and
338
- * any other column shows its value as text.
339
- *
340
- * The result is shown as plain text, never as HTML. Searching uses it,
341
- * sorting still uses the raw value.
342
- *
343
- * @example
344
- * render: (value, row) => row.cityName
345
- * render: (value) => `${value} MAD`
346
- */
347
- readonly render?: (value: Row[Key], row: Row) => string;
348
- };
349
- /**
350
- * Extra information `onSave` gets next to the edited row.
351
- *
352
- * @typeParam Row - The shape of one row.
353
- */
354
- type SaveContext<Row extends object> = {
355
- /** The row as it was when editing started. */
356
- readonly previous: Row;
357
- };
358
- /**
359
- * How rows are edited.
360
- */
361
- type EditingOptions = {
362
- /**
363
- * How many rows can be edited at once.
364
- *
365
- * - `'single'` (default): one row. `edit` returns `false` while another
366
- * row is open.
367
- * - `'multiple'`: any number of rows. Each one is saved or cancelled on
368
- * its own.
369
- */
370
- readonly mode?: "single" | "multiple";
371
- /**
372
- * Adds a column at the end with Edit, Save and Cancel buttons.
373
- * Default `true`. Turn it off to start editing from your own code with
374
- * `edit`, `save` and `cancel`.
375
- */
376
- readonly button?: boolean;
377
- };
378
- /**
379
- * Your own CSS classes for the table and its buttons, like Bootstrap's or
380
- * Tailwind's.
381
- *
382
- * They are added next to the `tdb-` classes, never instead of them, so CSS
383
- * that targets `tdb-` classes keeps working.
384
- *
385
- * @example
386
- * // Bootstrap 5
387
- * {
388
- * table: 'table table-striped table-hover',
389
- * button: 'btn btn-sm',
390
- * edit: 'btn-outline-primary',
391
- * save: 'btn-primary',
392
- * cancel: 'btn-outline-secondary',
393
- * }
394
- */
395
- type TableClassNames = {
396
- /** Added to the `<table>`. */
397
- readonly table?: string;
398
- /** Added to the Edit, Save and Cancel buttons. */
399
- readonly button?: string;
400
- /** Added to the Edit button only. */
401
- readonly edit?: string;
402
- /** Added to the Save button only. */
403
- readonly save?: string;
404
- /** Added to the Cancel button only. */
405
- readonly cancel?: string;
406
- };
407
- /**
408
- * Options for creating a Tadabut table.
409
- *
410
- * @typeParam Row - The shape of one row. Usually worked out from `data`.
411
- */
412
- type TadabutOptions<Row extends object> = {
413
- /** The rows to show. One object per row. */
414
- readonly data: readonly Row[];
415
- /** The columns to show, in order. */
416
- readonly columns: readonly Column<Row>[];
417
- /**
418
- * Name of the row property that identifies each row, like `'id'`.
419
- * Its values must be unique strings or numbers.
420
- *
421
- * Required when a column has an `editor`: editing uses it to find rows.
422
- */
423
- readonly rowId?: keyof Row & string;
424
- /** How rows are edited. Only used when a column has an `editor`. */
425
- readonly editing?: EditingOptions;
426
- /** Your CSS classes for the table and the buttons, like Bootstrap's. */
427
- readonly classNames?: TableClassNames;
428
- /**
429
- * Called when a row is saved, after every field passed validation.
430
- * It can be async.
431
- *
432
- * - Return nothing to keep the edited row, or return a row to use that
433
- * one instead (for fields the server fills in, like `updatedAt`).
434
- * - Throw to say saving failed. The row stays open with what the user
435
- * typed, and the error's message shows under it.
436
- *
437
- * Without `onSave`, saving just updates the table.
438
- */
439
- readonly onSave?: (row: Row, context: SaveContext<Row>) => Row | void | Promise<Row | void>;
440
- };
441
- /**
442
- * A DataTables table, created and owned by Tadabut.
443
- *
444
- * @typeParam Row - The shape of one row. Usually worked out from `data`,
445
- * so there is no need to write it.
446
- *
447
- * @example
448
- * const table = new Tadabut(container, {
449
- * data: [{ id: 1, name: 'Amina' }],
450
- * rowId: 'id',
451
- * columns: [
452
- * { title: 'ID', prop: 'id' },
453
- * { title: 'Name', prop: 'name' },
454
- * ],
455
- * });
456
- */
457
- declare class Tadabut<Row extends object> {
458
- private readonly dataTable;
459
- private readonly tableEl;
460
- private readonly rowId;
461
- private readonly columns;
462
- /** The `editing` option, with its defaults filled in. */
463
- private readonly editing;
464
- /** The user's extra classes. `{}` when there are none. */
465
- private readonly classNames;
466
- private readonly onSave;
467
- /** Whether the table has the actions column, with the Edit buttons. */
468
- private readonly hasActions;
469
- /** Whether at least one column has an editor. */
470
- private readonly hasEditor;
471
- /** The rows being edited, by row id. */
472
- private readonly sessions;
473
- /**
474
- * Creates a table inside `container`.
475
- *
476
- * @param container An empty element. Tadabut adds the table to it, and
477
- * `destroy()` leaves it empty again.
478
- * @param options The data and columns to show.
479
- * @throws If a column has an `editor` but `rowId` is missing. Editing
480
- * needs `rowId` to find rows.
481
- */
482
- constructor(container: HTMLElement, options: TadabutOptions<Row>);
483
- /**
484
- * Replaces all rows without rebuilding the table.
485
- *
486
- * Sorting, search and the current page are kept. If the current page no
487
- * longer exists (fewer rows than before), DataTables shows the last one.
488
- *
489
- * Any row being edited is cancelled first. Unsaved changes are lost.
490
- *
491
- * @param rows The new rows. The array is copied, never changed.
492
- */
493
- setData(rows: readonly Row[]): void;
494
- /**
495
- * Starts editing a row: its editable cells are replaced by editors showing
496
- * the row's values.
497
- *
498
- * In `'single'` mode (the default), only one row can be open at a time.
499
- * In `'multiple'` mode, any number can.
500
- *
501
- * @param id The row's id: the value of its `rowId` field.
502
- * @returns `true` if editing started. `false` if the row doesn't exist,
503
- * it's already open, another row is open in `'single'` mode, no column
504
- * is editable, or the row is on a page that hasn't been shown yet.
505
- */
506
- edit(id: string | number): boolean;
507
- /**
508
- * Stops editing a row and puts its original values back. Unsaved changes
509
- * are lost. Does nothing if the row isn't being edited.
510
- *
511
- * @param id The row's id: the value of its `rowId` field.
512
- */
513
- cancel(id: string | number): void;
514
- /**
515
- * Tells whether a row is being edited.
516
- *
517
- * @param id The row's id: the value of its `rowId` field.
518
- */
519
- isEditing(id: string | number): boolean;
520
- /**
521
- * Validates and saves the row being edited.
522
- *
523
- * 1. Every field is validated. If one fails, its error shows under its
524
- * input, the cursor goes to the first wrong field, and `onSave` isn't
525
- * called.
526
- * 2. The row is locked while `onSave` runs.
527
- * 3. If `onSave` works, the row closes and shows the new values: the row
528
- * `onSave` returned, or else the edited row.
529
- * 4. If `onSave` throws, the row stays open with what the user typed, and
530
- * the error's message shows under the row.
531
- *
532
- * The table's data only changes when saving works.
533
- *
534
- * @param id The row's id: the value of its `rowId` field.
535
- * @returns `true` if the row was saved and closed. `false` if a field is
536
- * invalid, `onSave` failed, the row isn't being edited, it's already
537
- * saving, or editing was stopped (by `setData` or `destroy`) while
538
- * `onSave` was running.
539
- */
540
- save(id: string | number): Promise<boolean>;
541
- /**
542
- * Removes the table and everything Tadabut added to the container.
543
- * Any row being edited is cancelled first.
544
- */
545
- destroy(): void;
546
- /**
547
- * Finds a row by its id. `undefined` if there is no `rowId` option, or no
548
- * row with that id.
549
- */
550
- private findRow;
551
- /**
552
- * Destroys every open editor, without putting the cells' content back.
553
- * Used right before the rows or the whole table go away.
554
- */
555
- private destroySessions;
556
- /**
557
- * Locks or unlocks a row while it's being saved: sets the session's
558
- * `saving` flag, and `inert` and the `tdb-row-saving` class on the row.
559
- *
560
- * Works even when the session is already gone, so a row can always be
561
- * unlocked after saving.
562
- */
563
- private setSaving;
564
- /**
565
- * Shows a save error on its own line under the row. The line (a `<tr>`)
566
- * gets `tdb-save-error`, and the message inside it gets
567
- * `tdb-save-error-message`.
568
- *
569
- * The message needs its own class: frameworks like Bootstrap set a color
570
- * on every table cell, which hides a color set on the `<tr>`.
571
- *
572
- * The message is set as text, never as HTML: it often comes from a server,
573
- * and HTML in it could run code in the page.
574
- */
575
- private showSaveError;
576
- /** Removes the save error under a row, if there is one. */
577
- private clearSaveError;
578
- /**
579
- * Finds the id of the row an element is in.
580
- *
581
- * `undefined` if the element isn't in a row DataTables knows, like the
582
- * save error line under a row, or a table inside a custom editor.
583
- */
584
- private rowIdOf;
585
- /**
586
- * Handles clicks on the Edit, Save and Cancel buttons.
587
- *
588
- * One listener on the whole table, not one per button: DataTables adds and
589
- * removes rows all the time (paging, `setData`), and new buttons would need
590
- * new listeners.
591
- *
592
- * An arrow function, so `this` is still the Tadabut when the browser calls
593
- * it, and the same function can be removed in `destroy`.
594
- */
595
- private readonly onClick;
596
- /**
597
- * Enter saves the row being edited, Escape cancels it.
598
- *
599
- * An arrow function, for the same reasons as `onClick`.
600
- */
601
- private readonly onKeyDown;
602
- }
603
- export { CheckboxEditor as _, TadabutOptions as a, EditorFor as c, SelectEditor as d, SelectOption as f, CustomEditor as g, DateEditor as h, TableClassNames as i, TextEditor as l, NumberEditor as m, EditingOptions as n, Column as o, SelectOptionsLoader as p, SaveContext as r, ValidationOptions as s, Tadabut as t, OptionsContext as u, EditorContext as v, EditorInstance as y };