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.
@@ -1,30 +1,18 @@
1
1
  import DataTable from "datatables.net";
2
2
  // src/editors/classes.ts
3
3
  /**
4
- * Turns class lists like `'btn btn-sm '` into single classes, like
5
- * `['btn', 'btn-sm']`.
6
- *
7
- * Internal. Each list can hold several classes separated by any spaces.
8
- * `undefined` lists and empty pieces are skipped, because
4
+ * `'btn btn-sm '` → `['btn', 'btn-sm']`. Empty pieces are dropped because
9
5
  * `classList.add('')` throws.
10
- *
11
- * @param lists The class lists, in order. `undefined` is allowed, so
12
- * optional options can be passed as they are.
13
6
  */
14
7
  function splitClasses(...lists) {
15
8
  return lists.flatMap((list) => list?.split(/\s+/).filter(Boolean) ?? []);
16
9
  }
17
- /**
18
- * Adds Tadabut's own classes and the user's `className` to an element.
19
- *
20
- * Internal. `className` can hold several classes separated by any spaces,
21
- * like `'border rounded'`.
22
- */
10
+ /** Adds Tadabut's own classes, then the user's. */
23
11
  function addClasses(element, ownClasses, className) {
24
12
  element.classList.add(...ownClasses, ...splitClasses(className));
25
13
  }
26
14
  // src/columns/escape.ts
27
- /** The characters that mean something in HTML, and what replaces them. */
15
+ /** Characters that mean something in HTML. */
28
16
  const entities = {
29
17
  "&": "&",
30
18
  "<": "&lt;",
@@ -32,26 +20,13 @@ const entities = {
32
20
  "\"": "&quot;",
33
21
  "'": "&#39;"
34
22
  };
35
- /**
36
- * Makes text safe to put in HTML: `<b>` shows as the text `<b>`, and can
37
- * never become a tag or run code.
38
- *
39
- * Internal: DataTables puts what a column's `render` returns into the cell
40
- * as HTML, so every label goes through this first.
41
- */
23
+ /** DataTables inserts rendered cells as HTML, so labels go through this. */
42
24
  function escapeHtml(text) {
43
25
  return text.replace(/[&<>"']/g, (char) => entities[char] ?? char);
44
26
  }
45
27
  // src/columns/to-datatables.ts
46
- /**
47
- * The last column, with the Edit button. When a row is being edited, its
48
- * cell holds Save and Cancel instead.
49
- *
50
- * DataTables wants the button as an HTML string. The user's classes go
51
- * inside that string, so they are escaped: a class like `x" onclick="…`
52
- * stays a (strange) class, and can't close the attribute and add code.
53
- */
54
- function actionsColumn(classNames) {
28
+ /** The Edit button column. Save and Cancel replace the button while a row is open. */
29
+ function actionsColumn(classNames, label) {
55
30
  return {
56
31
  title: "",
57
32
  data: null,
@@ -62,25 +37,24 @@ function actionsColumn(classNames) {
62
37
  "tdb-button",
63
38
  "tdb-button-edit",
64
39
  ...splitClasses(classNames.button, classNames.edit)
65
- ].join(" "))}" data-tdb-action="edit">Edit</button>`
40
+ ].join(" "))}" data-tdb-action="edit">${escapeHtml(label)}</button>`
66
41
  };
67
42
  }
68
43
  /**
69
- * Turns Tadabut columns into DataTables column settings.
70
- *
71
- * Internal: not exported from the package. It is the only place that knows
72
- * DataTables' column names, so a DataTables change only touches this file.
73
- *
74
- * @param columns The user's columns.
75
- * @param withActions Adds the actions column at the end. It must stay last:
76
- * the user's columns keep their positions, and Tadabut finds cells by
77
- * position.
78
- * @param classNames The user's classes. Only the Edit button uses them here.
44
+ * The actions column is always appended last, because the rest of Tadabut
45
+ * finds cells by the user's column index.
79
46
  */
80
- function toDataTables(columns, withActions, classNames) {
47
+ function toDataTables(columns, withActions, classNames, texts) {
81
48
  const converted = columns.map((column) => {
82
49
  const label = labelOf(column);
83
50
  return {
51
+ ...defined({
52
+ width: column.width,
53
+ visible: column.visible,
54
+ orderable: column.orderable,
55
+ searchable: column.searchable,
56
+ className: column.className
57
+ }),
84
58
  title: column.title,
85
59
  data: column.prop,
86
60
  render: (value, type, row) => {
@@ -92,40 +66,59 @@ function toDataTables(columns, withActions, classNames) {
92
66
  }
93
67
  };
94
68
  });
95
- return withActions ? [...converted, actionsColumn(classNames)] : converted;
69
+ return withActions ? [...converted, actionsColumn(classNames, texts.edit)] : converted;
96
70
  }
97
- /**
98
- * Picks how a column's value becomes text: its own `render`, else the label
99
- * of a fixed select list, else the value itself. Empty values give `''`.
100
- */
71
+ /** `render`, then `labelProp`, then a fixed list's label, then the value. */
101
72
  function labelOf(column) {
102
73
  const { render, editor } = column;
103
74
  if (render !== void 0) return render;
104
- if (editor?.type === "select" && typeof editor.options !== "function") {
105
- const options = editor.options;
106
- return (value) => options.find((option) => option.value === value)?.label ?? asText(value);
75
+ if (editor?.type === "select") {
76
+ const labelProp = editor.labelProp;
77
+ if (labelProp !== void 0) return (_value, row) => asText(row[labelProp]);
78
+ if (typeof editor.options !== "function") {
79
+ const options = editor.options;
80
+ return (value) => options.find((option) => option.value === value)?.label ?? asText(value);
81
+ }
107
82
  }
108
83
  return asText;
109
84
  }
110
- /** The value as text. `null` and `undefined` give an empty cell. */
85
+ /** `null` and `undefined` become an empty cell. */
111
86
  function asText(value) {
112
87
  return value === null || value === void 0 ? "" : String(value);
113
88
  }
89
+ /** Drops the keys whose value is `undefined`. */
90
+ function defined(values) {
91
+ const kept = Object.entries(values).filter(([, value]) => value !== void 0);
92
+ return Object.fromEntries(kept);
93
+ }
94
+ // src/texts/en.ts
95
+ /** English, the default. */
96
+ const en = {
97
+ edit: "Edit",
98
+ save: "Save",
99
+ cancel: "Cancel",
100
+ loading: "Loading…",
101
+ saveFailed: "Could not save.",
102
+ loadFailed: "Could not load the options.",
103
+ required: "This field is required.",
104
+ patternMismatch: "Wrong format.",
105
+ tooShort: (min) => `Must be at least ${min} characters.`,
106
+ tooLong: (max) => `Must be at most ${max} characters.`,
107
+ tooSmall: (min) => `Must be ${min} or more.`,
108
+ tooLarge: (max) => `Must be ${max} or less.`,
109
+ tooEarly: (min) => `Must be on or after ${min}.`,
110
+ tooLate: (max) => `Must be on or before ${max}.`
111
+ };
114
112
  // src/editors/checkbox.ts
115
113
  /**
116
- * Creates a live checkbox editor.
117
- *
118
- * Internal: Tadabut calls it when a row starts being edited.
119
- *
120
- * @param _config The editor config from the column. A checkbox has no
121
- * options of its own yet; the parameter keeps the same shape as the other
122
- * editors.
123
- * @param context The starting value, the classes and the change callback.
114
+ * Builds the checkbox. `_config` is unused for now, but keeps the same
115
+ * shape as the other editors.
124
116
  */
125
117
  function createCheckboxEditor(_config, context) {
126
118
  const input = document.createElement("input");
127
119
  input.type = "checkbox";
128
120
  addClasses(input, ["tdb-input", "tdb-input-checkbox"], context.className);
121
+ /** `null` shows as unchecked. */
129
122
  const setValue = (value) => {
130
123
  input.checked = value === true;
131
124
  };
@@ -140,21 +133,16 @@ function createCheckboxEditor(_config, context) {
140
133
  };
141
134
  }
142
135
  // src/editors/date.ts
143
- /**
144
- * Creates a live date editor.
145
- *
146
- * Internal: Tadabut calls it when a row starts being edited.
147
- *
148
- * @param config The editor config from the column.
149
- * @param context The starting value, the classes and the change callback.
150
- */
136
+ /** Builds the date input. */
151
137
  function createDateEditor(config, context) {
152
138
  const input = document.createElement("input");
153
139
  input.type = "date";
154
140
  addClasses(input, ["tdb-input", "tdb-input-date"], context.className);
155
141
  if (config.min !== void 0) input.min = config.min;
156
142
  if (config.max !== void 0) input.max = config.max;
143
+ /** Empty gives `null`. */
157
144
  const getValue = () => input.value === "" ? null : input.value;
145
+ /** `null` shows as empty. */
158
146
  const setValue = (value) => {
159
147
  input.value = value ?? "";
160
148
  };
@@ -169,14 +157,7 @@ function createDateEditor(config, context) {
169
157
  };
170
158
  }
171
159
  // src/editors/number.ts
172
- /**
173
- * Creates a live number editor.
174
- *
175
- * Internal: Tadabut calls it when a row starts being edited.
176
- *
177
- * @param config The editor config from the column.
178
- * @param context The starting value, the classes and the change callback.
179
- */
160
+ /** Builds the number input. */
180
161
  function createNumberEditor(config, context) {
181
162
  const input = document.createElement("input");
182
163
  input.type = "number";
@@ -184,7 +165,9 @@ function createNumberEditor(config, context) {
184
165
  if (config.min !== void 0) input.min = String(config.min);
185
166
  if (config.max !== void 0) input.max = String(config.max);
186
167
  if (config.step !== void 0) input.step = String(config.step);
168
+ /** Empty gives `null`, not `0`. */
187
169
  const getValue = () => input.value === "" ? null : input.valueAsNumber;
170
+ /** `null` shows as empty. */
188
171
  const setValue = (value) => {
189
172
  input.value = value === null ? "" : String(value);
190
173
  };
@@ -200,40 +183,25 @@ function createNumberEditor(config, context) {
200
183
  }
201
184
  // src/editors/select.ts
202
185
  /**
203
- * Creates a live select editor.
204
- *
205
- * Internal: Tadabut calls it when a row starts being edited.
206
- *
207
- * HTML `<option>` values are always strings, so the picked value is read
208
- * from the options list by position, which keeps its real type (`1`, not
209
- * `'1'`).
210
- *
211
- * With an `options` function, the select starts empty and Tadabut calls
212
- * `load`. Until the options arrive, the starting value is remembered:
213
- * `getValue` gives it, and it's picked once the options are shown.
214
- *
215
- * @param config The editor config from the column.
216
- * @param context The starting value, the classes and the change callback.
186
+ * `<option>` values are always strings, so the picked value is looked up by
187
+ * index to keep its real type. Until a loader's options arrive, the starting
188
+ * value is kept in `current`.
217
189
  */
218
- function createSelectEditor(config, context) {
190
+ function createSelectEditor(config, context, texts = en) {
219
191
  const select = document.createElement("select");
220
192
  addClasses(select, ["tdb-input", "tdb-input-select"], context.className);
221
- /** The options shown now. Empty until a function's options arrive. */
193
+ /** The options on screen. Empty while a loader runs. */
222
194
  let options = [];
223
- /**
224
- * The value, kept here and not only in the `<select>`: while options are
225
- * loading, the `<select>` has nothing to pick, but the value must not be
226
- * lost.
227
- */
195
+ /** The value, kept even while there are no options to pick it from. */
228
196
  let current = context.value;
229
- /** The load that's running, so a newer one (or destroy) can stop it. */
197
+ /** The running load, so a newer one or `destroy` can abort it. */
230
198
  let controller;
231
- /** Picks `current` in the `<select>`. If it's not in the list, it's `null`. */
199
+ /** Selects `current`. A value that isn't in the list becomes `null`. */
232
200
  const pickCurrent = () => {
233
201
  select.selectedIndex = options.findIndex((option) => option.value === current);
234
202
  if (select.selectedIndex === -1) current = null;
235
203
  };
236
- /** Replaces the `<option>`s with `list`, enables the select and picks `current`. */
204
+ /** Shows `list`, enables the select and picks `current`. */
237
205
  const fill = (list) => {
238
206
  options = list;
239
207
  select.replaceChildren(...list.map((option) => {
@@ -244,7 +212,7 @@ function createSelectEditor(config, context) {
244
212
  select.disabled = false;
245
213
  pickCurrent();
246
214
  };
247
- /** Shows one disabled, unpickable line, like "Loading…". */
215
+ /** Shows a single disabled line, like "Loading…". */
248
216
  const showOnly = (text) => {
249
217
  options = [];
250
218
  const element = document.createElement("option");
@@ -252,6 +220,7 @@ function createSelectEditor(config, context) {
252
220
  select.replaceChildren(element);
253
221
  select.disabled = true;
254
222
  };
223
+ /** Runs the `options` function and shows its result. */
255
224
  const load = async (row) => {
256
225
  if (typeof config.options !== "function") return "loaded";
257
226
  controller?.abort();
@@ -263,7 +232,7 @@ function createSelectEditor(config, context) {
263
232
  fill(result);
264
233
  return "loaded";
265
234
  }
266
- showOnly("Loading…");
235
+ showOnly(texts.loading);
267
236
  const list = await result;
268
237
  if (own.signal.aborted) return "cancelled";
269
238
  fill(list);
@@ -274,7 +243,11 @@ function createSelectEditor(config, context) {
274
243
  return "failed";
275
244
  }
276
245
  };
246
+ /** The value, even while options are loading. */
277
247
  const getValue = () => current;
248
+ /** `undefined` while options aren't loaded. */
249
+ const getLabel = () => current === null ? null : options.find((option) => option.value === current)?.label;
250
+ /** While loading, the value is only remembered. */
278
251
  const setValue = (value) => {
279
252
  current = value;
280
253
  if (!select.disabled) pickCurrent();
@@ -287,6 +260,7 @@ function createSelectEditor(config, context) {
287
260
  return {
288
261
  element: select,
289
262
  getValue,
263
+ getLabel,
290
264
  setValue,
291
265
  load,
292
266
  focus: () => select.focus(),
@@ -297,14 +271,7 @@ function createSelectEditor(config, context) {
297
271
  };
298
272
  }
299
273
  // src/editors/text.ts
300
- /**
301
- * Creates a live text editor.
302
- *
303
- * Internal: Tadabut calls it when a row starts being edited.
304
- *
305
- * @param options The editor config from the column.
306
- * @param context The starting value, the classes and the change callback.
307
- */
274
+ /** Builds the text input. `null` shows as empty. */
308
275
  function createTextEditor(config, context) {
309
276
  const input = document.createElement("input");
310
277
  input.type = "text";
@@ -326,21 +293,10 @@ function createTextEditor(config, context) {
326
293
  }
327
294
  // src/editors/create.ts
328
295
  /**
329
- * Creates the live editor that matches a column's editor config.
330
- *
331
- * Internal: Tadabut calls it for each editable cell when a row starts being
332
- * edited.
333
- *
334
- * The exact column type is not known here, so values are `unknown`.
335
- * That is safe: `Column<Row>` already checked that the config fits the
336
- * column, before the table was created.
337
- *
338
- * @param config The editor config from the column.
339
- * @param context The starting value and the change callback. Its
340
- * `className` is filled in from `config`, so every editor, built-in or
341
- * custom, gets the same full context.
296
+ * `Column<Row>` already checked that each config fits its column, so the
297
+ * casts below are safe.
342
298
  */
343
- function createEditor(config, context) {
299
+ function createEditor(config, context, texts = en) {
344
300
  const fullContext = {
345
301
  ...context,
346
302
  className: config.className
@@ -350,7 +306,7 @@ function createEditor(config, context) {
350
306
  case "number": return loosen(createNumberEditor(config, tighten(fullContext)));
351
307
  case "date": return loosen(createDateEditor(config, tighten(fullContext)));
352
308
  case "checkbox": return loosen(createCheckboxEditor(config, tighten(fullContext)));
353
- case "select": return createSelectEditor(config, fullContext);
309
+ case "select": return createSelectEditor(config, fullContext, texts);
354
310
  case "custom": return config.create(fullContext);
355
311
  default: throw new Error(`Unknown editor: ${JSON.stringify(config)}`);
356
312
  }
@@ -359,80 +315,47 @@ function createEditor(config, context) {
359
315
  function tighten(context) {
360
316
  return context;
361
317
  }
362
- /** Turns a typed editor back into the loose type `createEditor` returns. */
318
+ /** Turns a typed editor back into the loose type. */
363
319
  function loosen(editor) {
364
320
  return editor;
365
321
  }
366
322
  // src/validation/validate.ts
367
- /**
368
- * Error messages. Plain English for now. They will become an option when
369
- * translations are added.
370
- *
371
- * Internal: exported for the edit session, which shows `loadFailed`.
372
- */
373
- const messages = {
374
- required: "This field is required.",
375
- loadFailed: "Could not load the options.",
376
- tooShort: (min) => `Must be at least ${min} characters.`,
377
- tooLong: (max) => `Must be at most ${max} characters.`,
378
- patternMismatch: "Wrong format.",
379
- tooSmall: (min) => `Must be ${min} or more.`,
380
- tooLarge: (max) => `Must be ${max} or less.`,
381
- tooEarly: (min) => `Must be on or after ${min}.`,
382
- tooLate: (max) => `Must be on or before ${max}.`
383
- };
384
- /**
385
- * Checks a value against a column's rules.
386
- *
387
- * Internal: Tadabut calls it before saving a row.
388
- *
389
- * The checks run in this order, and the first error wins:
390
- * 1. Empty value (`null`, `undefined` or `''`): an error if `required`,
391
- * otherwise no error and nothing else is checked. An empty optional field
392
- * never fails a rule like `min`.
393
- * 2. The editor's own rules (`minLength`, `min`, and so on).
394
- * 3. The user's `validate`.
395
- *
396
- * @param config The editor config, with its validation rules.
397
- * @param value The value the editor gave.
398
- * @param row The row being edited.
399
- * @returns The error message, or `undefined` if the value is fine.
400
- */
401
- function validateValue(config, value, row) {
402
- if (value === null || value === void 0 || value === "") return config.required ? messages.required : void 0;
403
- return builtInError(config, value) ?? config.validate?.(value, row);
323
+ /** Returns the first error message, or `undefined`. */
324
+ function validateValue(config, value, row, texts = en) {
325
+ if (value === null || value === void 0 || value === "") return config.required ? texts.required : void 0;
326
+ return builtInError(config, value, texts) ?? config.validate?.(value, row);
404
327
  }
405
- /** Checks the rules that come with each built-in editor. */
406
- function builtInError(config, value) {
328
+ /** The rules each built-in editor brings. */
329
+ function builtInError(config, value, texts) {
407
330
  switch (config.type) {
408
- case "text": return typeof value === "string" ? textError(config, value) : void 0;
409
- case "number": return typeof value === "number" ? rangeError(config, value) : void 0;
410
- case "date": return typeof value === "string" ? dateError(config, value) : void 0;
331
+ case "text": return typeof value === "string" ? textError(config, value, texts) : void 0;
332
+ case "number": return typeof value === "number" ? rangeError(config, value, texts) : void 0;
333
+ case "date": return typeof value === "string" ? dateError(config, value, texts) : void 0;
411
334
  case "checkbox":
412
335
  case "select":
413
336
  case "custom": return;
414
337
  default: throw new Error(`Unknown editor: ${JSON.stringify(config)}`);
415
338
  }
416
339
  }
417
- function textError(config, value) {
418
- if (config.minLength !== void 0 && value.length < config.minLength) return messages.tooShort(config.minLength);
419
- if (config.maxLength !== void 0 && value.length > config.maxLength) return messages.tooLong(config.maxLength);
420
- if (config.pattern !== void 0 && !matchesWhole(config.pattern, value)) return messages.patternMismatch;
340
+ /** `minLength`, `maxLength` and `pattern`. */
341
+ function textError(config, value, texts) {
342
+ if (config.minLength !== void 0 && value.length < config.minLength) return texts.tooShort(config.minLength);
343
+ if (config.maxLength !== void 0 && value.length > config.maxLength) return texts.tooLong(config.maxLength);
344
+ if (config.pattern !== void 0 && !matchesWhole(config.pattern, value)) return texts.patternMismatch;
421
345
  }
422
- function rangeError(config, value) {
423
- if (config.min !== void 0 && value < config.min) return messages.tooSmall(config.min);
424
- if (config.max !== void 0 && value > config.max) return messages.tooLarge(config.max);
346
+ /** `min` and `max` for numbers. */
347
+ function rangeError(config, value, texts) {
348
+ if (config.min !== void 0 && value < config.min) return texts.tooSmall(config.min);
349
+ if (config.max !== void 0 && value > config.max) return texts.tooLarge(config.max);
425
350
  }
426
- function dateError(config, value) {
427
- if (config.min !== void 0 && value < config.min) return messages.tooEarly(config.min);
428
- if (config.max !== void 0 && value > config.max) return messages.tooLate(config.max);
351
+ /** `min` and `max` for dates. */
352
+ function dateError(config, value, texts) {
353
+ if (config.min !== void 0 && value < config.min) return texts.tooEarly(config.min);
354
+ if (config.max !== void 0 && value > config.max) return texts.tooLate(config.max);
429
355
  }
430
356
  /**
431
- * Checks that `pattern` matches the whole value, like the HTML `pattern`
432
- * attribute: same `v` flag, and an invalid pattern is ignored.
433
- *
434
- * The `(?:…)` keeps `^` and `$` around the whole pattern: without it,
435
- * `a|b` would become `^a|b$`, which means something else.
357
+ * Same rules as the HTML `pattern` attribute: whole value, `v` flag, and an
358
+ * invalid pattern is ignored. The group stops `a|b` from becoming `^a|b$`.
436
359
  */
437
360
  function matchesWhole(pattern, value) {
438
361
  let regex;
@@ -444,45 +367,31 @@ function matchesWhole(pattern, value) {
444
367
  return regex.test(value);
445
368
  }
446
369
  // src/editing/session.ts
447
- /** Counter for unique error element ids, like `tdb-error-3`. */
370
+ /** For unique error ids (`aria-describedby` needs one). */
448
371
  let errorCount = 0;
449
372
  /**
450
- * Everything about one row while it is being edited.
451
- *
452
- * Internal. It knows nothing about DataTables: `Tadabut` finds the cells and
453
- * passes them in, and puts the cells' text back after `destroy`.
454
- *
455
- * @typeParam Row - The shape of one row.
373
+ * One open row. Doesn't know about DataTables: `Tadabut` hands it the cells
374
+ * and restores them afterwards.
456
375
  */
457
376
  var EditSession = class {
458
- /** A copy of the row as it was when editing started. */
377
+ /** A copy of the row from before editing. `onSave` gets it as `previous`. */
459
378
  originalData;
460
- /** The edited fields, by row property. */
379
+ /** Open fields, by row field. */
461
380
  fields = /* @__PURE__ */ new Map();
462
- /** The error messages being shown, by row property. */
381
+ /** Error messages on screen, by row field. */
463
382
  errors = /* @__PURE__ */ new Map();
464
- /**
465
- * For each field, the selects that depend on it: when it changes, they
466
- * are cleared and their options load again.
467
- */
383
+ /** For each field, the selects that depend on it. */
468
384
  dependents = /* @__PURE__ */ new Map();
469
- /** The fields whose last options load failed. */
385
+ /** Selects whose last options load failed. */
470
386
  loadErrors = /* @__PURE__ */ new Set();
471
- /**
472
- * `true` while `onSave` runs. Set by `Tadabut`, which ignores a second
473
- * save, or a cancel, during that time.
474
- */
387
+ /** Set by `Tadabut` while `onSave` runs. */
475
388
  saving = false;
476
- /**
477
- * Replaces each cell's content with an editor showing the row's value,
478
- * then loads the options of every select whose `options` is a function.
479
- *
480
- * @param row The row to edit.
481
- * @param cells The editable columns and their cells. Columns without an
482
- * `editor` are skipped.
483
- */
484
- constructor(row, cells) {
389
+ /** Error messages and the "Loading…" text. */
390
+ texts;
391
+ /** Puts an editor in each cell and starts loading select options. */
392
+ constructor(row, cells, texts = en) {
485
393
  this.originalData = { ...row };
394
+ this.texts = texts;
486
395
  for (const { column, cell } of cells) {
487
396
  if (column.editor === void 0) continue;
488
397
  const config = column.editor;
@@ -494,7 +403,7 @@ var EditSession = class {
494
403
  const editor = createEditor(config, {
495
404
  value: this.originalData[column.prop],
496
405
  onChange: () => this.changed(column.prop)
497
- });
406
+ }, texts);
498
407
  cell.replaceChildren(editor.element);
499
408
  this.fields.set(column.prop, {
500
409
  editor,
@@ -504,69 +413,44 @@ var EditSession = class {
504
413
  for (const prop of this.fields.keys()) this.loadField(prop);
505
414
  }
506
415
  /**
507
- * Returns the row as the user has edited it so far: a copy of the
508
- * original, with each edited field replaced by its editor's value.
509
- * Fields that aren't edited are kept as they were.
510
- *
511
- * The result can hold `null` where `Row` says it can't, like an empty
512
- * number editor on an `age: number` column. Validate before using it.
416
+ * The row with the current editor values. It can hold `null` where `Row`
417
+ * doesn't allow it (an empty number input), so validate before trusting it.
513
418
  */
514
419
  getRow() {
515
420
  const row = { ...this.originalData };
516
- for (const [prop, { editor }] of this.fields) row[prop] = editor.getValue();
421
+ for (const [prop, { editor, config }] of this.fields) {
422
+ row[prop] = editor.getValue();
423
+ if (config.type === "select" && config.labelProp !== void 0) {
424
+ const label = editor.getLabel?.();
425
+ if (label !== void 0) row[config.labelProp] = label;
426
+ }
427
+ }
517
428
  return row;
518
429
  }
519
- /**
520
- * Checks every field against its rules.
521
- *
522
- * Each field is checked with the whole edited row, so a rule can compare
523
- * it with other new values.
524
- *
525
- * @returns The error message of each invalid field, by row property.
526
- * Empty when everything is valid.
527
- */
430
+ /** Every rule gets the whole edited row, so fields can be compared. */
528
431
  validate() {
529
432
  const row = this.getRow();
530
433
  const errors = /* @__PURE__ */ new Map();
531
434
  for (const [prop, { editor, config }] of this.fields) {
532
- const message = this.loadErrors.has(prop) ? messages.loadFailed : validateValue(config, editor.getValue(), row);
435
+ const message = this.loadErrors.has(prop) ? this.texts.loadFailed : validateValue(config, editor.getValue(), row, this.texts);
533
436
  if (message !== void 0) errors.set(prop, message);
534
437
  }
535
438
  return errors;
536
439
  }
537
- /**
538
- * Shows each error message under its field's editor.
539
- *
540
- * Errors already shown are removed first.
541
- *
542
- * @param errors The error message of each invalid field, by row property,
543
- * as returned by `validate`.
544
- */
440
+ /** Replaces whatever errors are currently shown. */
545
441
  showErrors(errors) {
546
442
  this.clearErrors();
547
443
  for (const [prop, message] of errors) this.showError(prop, message);
548
444
  }
549
- /**
550
- * Removes every error message, and the ARIA attributes that point at them.
551
- */
445
+ /** Removes every error message and its ARIA attributes. */
552
446
  clearErrors() {
553
447
  for (const prop of [...this.errors.keys()]) this.hideError(prop);
554
448
  }
555
- /**
556
- * Puts the cursor in a field's editor. Does nothing if the field isn't
557
- * being edited.
558
- *
559
- * @param prop The row property of the field.
560
- */
449
+ /** Moves the cursor to a field. */
561
450
  focus(prop) {
562
451
  this.fields.get(prop)?.editor.focus();
563
452
  }
564
- /**
565
- * Destroys every editor and error message. Safe to call more than once.
566
- *
567
- * The editable cells are left empty: the caller must put their content
568
- * back.
569
- */
453
+ /** Leaves the cells empty; the caller redraws them. Safe to call twice. */
570
454
  destroy() {
571
455
  this.clearErrors();
572
456
  for (const { editor } of this.fields.values()) editor.destroy();
@@ -574,13 +458,7 @@ var EditSession = class {
574
458
  this.dependents.clear();
575
459
  this.loadErrors.clear();
576
460
  }
577
- /**
578
- * Shows one error message under a field's editor, replacing the one that
579
- * was there.
580
- *
581
- * The editor's element gets `aria-invalid` and points at the message with
582
- * `aria-describedby`, so screen readers read the error with the field.
583
- */
461
+ /** Shows one message under a field, linked with `aria-describedby`. */
584
462
  showError(prop, message) {
585
463
  const field = this.fields.get(prop);
586
464
  if (field === void 0) return;
@@ -595,7 +473,7 @@ var EditSession = class {
595
473
  field.editor.element.setAttribute("aria-describedby", error.id);
596
474
  this.errors.set(prop, error);
597
475
  }
598
- /** Removes one field's error message and its ARIA attributes, if shown. */
476
+ /** Removes one field's message, if there is one. */
599
477
  hideError(prop) {
600
478
  const error = this.errors.get(prop);
601
479
  if (error === void 0) return;
@@ -605,13 +483,7 @@ var EditSession = class {
605
483
  element?.removeAttribute("aria-invalid");
606
484
  element?.removeAttribute("aria-describedby");
607
485
  }
608
- /**
609
- * Runs when the user changes a field: every select below it in the chain
610
- * is cleared, then loads its options again.
611
- *
612
- * Example, with Country → Region → City: changing the country clears the
613
- * region and the city, then both reload.
614
- */
486
+ /** Country changed: clear region and city, then reload both. */
615
487
  changed(prop) {
616
488
  const cleared = /* @__PURE__ */ new Set([prop]);
617
489
  this.clearBelow(prop, cleared);
@@ -619,12 +491,8 @@ var EditSession = class {
619
491
  for (const field of cleared) this.loadField(field);
620
492
  }
621
493
  /**
622
- * Clears the fields that depend on `prop`, then the ones that depend on
623
- * those, and so on. `setValue` never calls `onChange`, so the chain has to
624
- * be walked here.
625
- *
626
- * @param cleared The fields cleared so far. A field already in it is
627
- * skipped, so a loop (A depends on B, B depends on A) can't run forever.
494
+ * Walks the chain by hand, since `setValue` doesn't fire `onChange`.
495
+ * `cleared` also stops dependency loops.
628
496
  */
629
497
  clearBelow(prop, cleared) {
630
498
  for (const dependent of this.dependents.get(prop) ?? []) {
@@ -634,12 +502,7 @@ var EditSession = class {
634
502
  this.clearBelow(dependent, cleared);
635
503
  }
636
504
  }
637
- /**
638
- * Loads a field's options with the current row, and shows or hides
639
- * "Could not load the options." under it.
640
- *
641
- * Fields that aren't selects with an options function finish at once.
642
- */
505
+ /** Loads one select's options and shows or hides the load error. */
643
506
  async loadField(prop) {
644
507
  const field = this.fields.get(prop);
645
508
  if (field?.editor.load === void 0) return;
@@ -647,7 +510,7 @@ var EditSession = class {
647
510
  if (result === "cancelled") return;
648
511
  if (result === "failed") {
649
512
  this.loadErrors.add(prop);
650
- this.showError(prop, messages.loadFailed);
513
+ this.showError(prop, this.texts.loadFailed);
651
514
  return;
652
515
  }
653
516
  if (this.loadErrors.delete(prop)) this.hideError(prop);
@@ -655,10 +518,9 @@ var EditSession = class {
655
518
  };
656
519
  // src/table/tadabut.ts
657
520
  /**
658
- * A DataTables table, created and owned by Tadabut.
521
+ * A DataTables table with row editing.
659
522
  *
660
- * @typeParam Row - The shape of one row. Usually worked out from `data`,
661
- * so there is no need to write it.
523
+ * @typeParam Row - Usually inferred from `data`.
662
524
  *
663
525
  * @example
664
526
  * const table = new Tadabut(container, {
@@ -671,33 +533,42 @@ var EditSession = class {
671
533
  * });
672
534
  */
673
535
  var Tadabut = class {
536
+ /** The DataTables instance. */
674
537
  dataTable;
538
+ /** The `<table>` Tadabut created. */
675
539
  tableEl;
540
+ /** The field that identifies a row. */
676
541
  rowId;
542
+ /** The user's columns, without the actions column. */
677
543
  columns;
678
- /** The `editing` option, with its defaults filled in. */
544
+ /** `editing` with its defaults filled in. */
679
545
  editing;
680
- /** The user's extra classes. `{}` when there are none. */
546
+ /** The user's classes, or `{}`. */
681
547
  classNames;
548
+ /** The user's texts over English. */
549
+ texts;
550
+ /** The user's save callback. */
682
551
  onSave;
683
- /** Whether the table has the actions column, with the Edit buttons. */
552
+ /** Whether the Edit/Save/Cancel column exists. */
684
553
  hasActions;
685
- /** Whether at least one column has an editor. */
554
+ /** Whether any column has an editor. */
686
555
  hasEditor;
687
- /** The rows being edited, by row id. */
556
+ /** Open rows, by row id. */
688
557
  sessions = /* @__PURE__ */ new Map();
689
558
  /**
690
- * Creates a table inside `container`.
559
+ * Builds the table inside `container`, which should be empty.
691
560
  *
692
- * @param container An empty element. Tadabut adds the table to it, and
693
- * `destroy()` leaves it empty again.
694
- * @param options The data and columns to show.
695
- * @throws If a column has an `editor` but `rowId` is missing. Editing
696
- * needs `rowId` to find rows.
561
+ * @throws If a column has an `editor` and there's no `rowId`.
562
+ * @throws If a hidden column (`visible: false`) has an `editor`.
563
+ * @throws If a select's `labelProp` is its own column.
697
564
  */
698
565
  constructor(container, options) {
699
566
  this.hasEditor = options.columns.some((column) => column.editor !== void 0);
700
567
  if (this.hasEditor && options.rowId === void 0) throw new Error("Tadabut: rowId is required when a column has an editor.");
568
+ const hiddenEditable = options.columns.find((column) => column.editor !== void 0 && column.visible === false);
569
+ if (hiddenEditable !== void 0) throw new Error(`Tadabut: the "${hiddenEditable.prop}" column can't have both an editor and visible: false.`);
570
+ const selfLabeled = options.columns.find((column) => column.editor?.type === "select" && column.editor.labelProp === column.prop);
571
+ if (selfLabeled !== void 0) throw new Error(`Tadabut: the "${selfLabeled.prop}" column's labelProp can't be "${selfLabeled.prop}" itself.`);
701
572
  this.rowId = options.rowId;
702
573
  this.columns = options.columns;
703
574
  this.editing = {
@@ -707,41 +578,37 @@ var Tadabut = class {
707
578
  this.hasActions = this.hasEditor && this.editing.button;
708
579
  this.onSave = options.onSave;
709
580
  this.classNames = options.classNames ?? {};
581
+ this.texts = {
582
+ ...en,
583
+ ...options.texts
584
+ };
710
585
  this.tableEl = document.createElement("table");
711
586
  addClasses(this.tableEl, [], this.classNames.table);
712
587
  container.appendChild(this.tableEl);
713
588
  this.dataTable = new DataTable(this.tableEl, {
589
+ ...options.dataTables,
714
590
  data: [...options.data],
715
- columns: toDataTables(options.columns, this.hasActions, this.classNames)
591
+ columns: toDataTables(options.columns, this.hasActions, this.classNames, this.texts)
716
592
  });
717
593
  if (this.hasActions) this.tableEl.addEventListener("click", this.onClick);
718
594
  if (this.hasEditor) this.tableEl.addEventListener("keydown", this.onKeyDown);
719
595
  }
720
596
  /**
721
- * Replaces all rows without rebuilding the table.
597
+ * Replaces all rows. Sorting, search and the page are kept.
722
598
  *
723
- * Sorting, search and the current page are kept. If the current page no
724
- * longer exists (fewer rows than before), DataTables shows the last one.
725
- *
726
- * Any row being edited is cancelled first. Unsaved changes are lost.
727
- *
728
- * @param rows The new rows. The array is copied, never changed.
599
+ * Open rows are closed first, and their unsaved changes are lost.
729
600
  */
730
601
  setData(rows) {
731
602
  this.destroySessions();
732
603
  this.dataTable.clear().rows.add([...rows]).draw(false);
733
604
  }
734
605
  /**
735
- * Starts editing a row: its editable cells are replaced by editors showing
736
- * the row's values.
606
+ * Opens a row for editing.
737
607
  *
738
- * In `'single'` mode (the default), only one row can be open at a time.
739
- * In `'multiple'` mode, any number can.
740
- *
741
- * @param id The row's id: the value of its `rowId` field.
742
- * @returns `true` if editing started. `false` if the row doesn't exist,
743
- * it's already open, another row is open in `'single'` mode, no column
744
- * is editable, or the row is on a page that hasn't been shown yet.
608
+ * @param id The value of the row's `rowId` field.
609
+ * @returns `false` if the row doesn't exist, is already open, another row
610
+ * is open in `'single'` mode, nothing is editable, or the row is on a
611
+ * page that hasn't been displayed yet.
745
612
  */
746
613
  edit(id) {
747
614
  if (!this.hasEditor || this.sessions.has(id) || this.editing.mode === "single" && this.sessions.size > 0) return false;
@@ -758,16 +625,14 @@ var Tadabut = class {
758
625
  });
759
626
  }
760
627
  });
761
- this.sessions.set(id, new EditSession(row.data(), cells));
628
+ this.sessions.set(id, new EditSession(row.data(), cells, this.texts));
762
629
  row.node()?.classList.add("tdb-row-editing");
763
- if (this.hasActions) this.dataTable.cell(rowIndex, this.columns.length).node().replaceChildren(actionButton("save", "Save", splitClasses(this.classNames.button, this.classNames.save)), actionButton("cancel", "Cancel", splitClasses(this.classNames.button, this.classNames.cancel)));
630
+ if (this.hasActions) this.dataTable.cell(rowIndex, this.columns.length).node().replaceChildren(actionButton("save", this.texts.save, splitClasses(this.classNames.button, this.classNames.save)), actionButton("cancel", this.texts.cancel, splitClasses(this.classNames.button, this.classNames.cancel)));
764
631
  return true;
765
632
  }
766
633
  /**
767
- * Stops editing a row and puts its original values back. Unsaved changes
768
- * are lost. Does nothing if the row isn't being edited.
769
- *
770
- * @param id The row's id: the value of its `rowId` field.
634
+ * Closes a row and throws away its changes. Does nothing if the row isn't
635
+ * open, or while it's saving.
771
636
  */
772
637
  cancel(id) {
773
638
  const session = this.sessions.get(id);
@@ -779,33 +644,18 @@ var Tadabut = class {
779
644
  this.findRow(id)?.node()?.classList.remove("tdb-row-editing");
780
645
  this.findRow(id)?.invalidate("data").draw(false);
781
646
  }
782
- /**
783
- * Tells whether a row is being edited.
784
- *
785
- * @param id The row's id: the value of its `rowId` field.
786
- */
647
+ /** Whether a row is open for editing. */
787
648
  isEditing(id) {
788
649
  return this.sessions.has(id);
789
650
  }
790
651
  /**
791
- * Validates and saves the row being edited.
652
+ * Validates the open row, then calls `onSave`.
792
653
  *
793
- * 1. Every field is validated. If one fails, its error shows under its
794
- * input, the cursor goes to the first wrong field, and `onSave` isn't
795
- * called.
796
- * 2. The row is locked while `onSave` runs.
797
- * 3. If `onSave` works, the row closes and shows the new values: the row
798
- * `onSave` returned, or else the edited row.
799
- * 4. If `onSave` throws, the row stays open with what the user typed, and
800
- * the error's message shows under the row.
654
+ * Invalid fields show their errors and `onSave` isn't called. While
655
+ * `onSave` runs the row is locked. If it throws, the row stays open and
656
+ * the error message is shown under it. The table only changes on success.
801
657
  *
802
- * The table's data only changes when saving works.
803
- *
804
- * @param id The row's id: the value of its `rowId` field.
805
- * @returns `true` if the row was saved and closed. `false` if a field is
806
- * invalid, `onSave` failed, the row isn't being edited, it's already
807
- * saving, or editing was stopped (by `setData` or `destroy`) while
808
- * `onSave` was running.
658
+ * @returns `true` once the row is saved and closed.
809
659
  */
810
660
  async save(id) {
811
661
  const session = this.sessions.get(id);
@@ -828,7 +678,7 @@ var Tadabut = class {
828
678
  } catch (error) {
829
679
  if (this.sessions.get(id) !== session) return false;
830
680
  this.setSaving(id, false);
831
- this.showSaveError(id, error instanceof Error ? error.message : "Could not save.");
681
+ this.showSaveError(id, error instanceof Error ? error.message : this.texts.saveFailed);
832
682
  return false;
833
683
  }
834
684
  if (this.sessions.get(id) !== session) return false;
@@ -839,10 +689,7 @@ var Tadabut = class {
839
689
  this.setSaving(id, false);
840
690
  return true;
841
691
  }
842
- /**
843
- * Removes the table and everything Tadabut added to the container.
844
- * Any row being edited is cancelled first.
845
- */
692
+ /** Removes the table. Open rows are closed without saving. */
846
693
  destroy() {
847
694
  this.tableEl.removeEventListener("click", this.onClick);
848
695
  this.tableEl.removeEventListener("keydown", this.onKeyDown);
@@ -850,31 +697,19 @@ var Tadabut = class {
850
697
  this.dataTable.destroy();
851
698
  this.tableEl.remove();
852
699
  }
853
- /**
854
- * Finds a row by its id. `undefined` if there is no `rowId` option, or no
855
- * row with that id.
856
- */
700
+ /** The row with this id, or `undefined`. */
857
701
  findRow(id) {
858
702
  const rowId = this.rowId;
859
703
  if (rowId === void 0) return;
860
704
  const row = this.dataTable.row((_index, data) => data[rowId] === id);
861
705
  return row.any() ? row : void 0;
862
706
  }
863
- /**
864
- * Destroys every open editor, without putting the cells' content back.
865
- * Used right before the rows or the whole table go away.
866
- */
707
+ /** Only for when the rows are about to go away: cells aren't restored. */
867
708
  destroySessions() {
868
709
  for (const session of this.sessions.values()) session.destroy();
869
710
  this.sessions.clear();
870
711
  }
871
- /**
872
- * Locks or unlocks a row while it's being saved: sets the session's
873
- * `saving` flag, and `inert` and the `tdb-row-saving` class on the row.
874
- *
875
- * Works even when the session is already gone, so a row can always be
876
- * unlocked after saving.
877
- */
712
+ /** Also works after the session is gone, so a row can always be unlocked. */
878
713
  setSaving(id, saving) {
879
714
  const session = this.sessions.get(id);
880
715
  if (session !== void 0) session.saving = saving;
@@ -885,15 +720,9 @@ var Tadabut = class {
885
720
  }
886
721
  }
887
722
  /**
888
- * Shows a save error on its own line under the row. The line (a `<tr>`)
889
- * gets `tdb-save-error`, and the message inside it gets
890
- * `tdb-save-error-message`.
891
- *
892
- * The message needs its own class: frameworks like Bootstrap set a color
893
- * on every table cell, which hides a color set on the `<tr>`.
894
- *
895
- * The message is set as text, never as HTML: it often comes from a server,
896
- * and HTML in it could run code in the page.
723
+ * Shows the error in a child row under the row. The message gets its own
724
+ * class because Bootstrap colors every cell, which hides a color on the
725
+ * `<tr>`. Set as text: it often comes from a server.
897
726
  */
898
727
  showSaveError(id, message) {
899
728
  const error = document.createElement("div");
@@ -901,15 +730,13 @@ var Tadabut = class {
901
730
  error.textContent = message;
902
731
  this.findRow(id)?.child(error, "tdb-save-error").show();
903
732
  }
904
- /** Removes the save error under a row, if there is one. */
733
+ /** Removes the error row under a row, if any. */
905
734
  clearSaveError(id) {
906
735
  this.findRow(id)?.child.remove();
907
736
  }
908
737
  /**
909
- * Finds the id of the row an element is in.
910
- *
911
- * `undefined` if the element isn't in a row DataTables knows, like the
912
- * save error line under a row, or a table inside a custom editor.
738
+ * `undefined` for rows DataTables doesn't know, like the save error row or
739
+ * a table inside a custom editor.
913
740
  */
914
741
  rowIdOf(element) {
915
742
  const tr = element.closest("tr");
@@ -918,14 +745,9 @@ var Tadabut = class {
918
745
  return row.any() ? row.data()[this.rowId] : void 0;
919
746
  }
920
747
  /**
921
- * Handles clicks on the Edit, Save and Cancel buttons.
922
- *
923
- * One listener on the whole table, not one per button: DataTables adds and
924
- * removes rows all the time (paging, `setData`), and new buttons would need
925
- * new listeners.
926
- *
927
- * An arrow function, so `this` is still the Tadabut when the browser calls
928
- * it, and the same function can be removed in `destroy`.
748
+ * Handles Edit, Save and Cancel. One listener on the table, because
749
+ * DataTables keeps replacing rows. An arrow function, so `this` stays
750
+ * bound and `destroy` can remove it.
929
751
  */
930
752
  onClick = (event) => {
931
753
  if (!(event.target instanceof Element)) return;
@@ -942,11 +764,7 @@ var Tadabut = class {
942
764
  case "cancel": this.cancel(id);
943
765
  }
944
766
  };
945
- /**
946
- * Enter saves the row being edited, Escape cancels it.
947
- *
948
- * An arrow function, for the same reasons as `onClick`.
949
- */
767
+ /** Enter saves, Escape cancels. */
950
768
  onKeyDown = (event) => {
951
769
  if (event.defaultPrevented) return;
952
770
  if (!(event.target instanceof Element) || event.target.closest("button")) return;
@@ -963,14 +781,7 @@ var Tadabut = class {
963
781
  }
964
782
  };
965
783
  };
966
- /**
967
- * Makes one of the buttons in the actions column.
968
- *
969
- * Built with `createElement`, not an HTML string, so a label can never be
970
- * read as HTML, even once labels can be translated.
971
- *
972
- * @param extra The user's classes from `classNames`, already split.
973
- */
784
+ /** Builds a Save or Cancel button. */
974
785
  function actionButton(action, label, extra) {
975
786
  const button = document.createElement("button");
976
787
  button.type = "button";
@@ -979,4 +790,22 @@ function actionButton(action, label, extra) {
979
790
  button.textContent = label;
980
791
  return button;
981
792
  }
982
- export { Tadabut as t };
793
+ // src/texts/fr.ts
794
+ /** French. */
795
+ const fr = {
796
+ edit: "Modifier",
797
+ save: "Enregistrer",
798
+ cancel: "Annuler",
799
+ loading: "Chargement…",
800
+ saveFailed: "Impossible d'enregistrer.",
801
+ loadFailed: "Impossible de charger les options.",
802
+ required: "Ce champ est obligatoire.",
803
+ patternMismatch: "Format incorrect.",
804
+ tooShort: (min) => `Au moins ${min} caractères.`,
805
+ tooLong: (max) => `Au plus ${max} caractères.`,
806
+ tooSmall: (min) => `Doit être supérieur ou égal à ${min}.`,
807
+ tooLarge: (max) => `Doit être inférieur ou égal à ${max}.`,
808
+ tooEarly: (min) => `Doit être le ${min} ou après.`,
809
+ tooLate: (max) => `Doit être le ${max} ou avant.`
810
+ };
811
+ export { Tadabut as n, en as r, fr as t };