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