flexdesk 0.17.18 → 0.18.1

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.
Files changed (126) hide show
  1. package/CHANGELOG.md +91 -0
  2. package/README.md +1 -0
  3. package/css/flexdesk.css +7547 -5891
  4. package/css/reset.css +1 -1
  5. package/css/tokens.css +30 -1
  6. package/dist/charts.js +83 -13
  7. package/dist/charts.js.map +2 -2
  8. package/dist/chunk-3BLIVOFD.js +778 -0
  9. package/dist/chunk-3BLIVOFD.js.map +7 -0
  10. package/dist/{chunk-7OL6F2AM.js → chunk-4X4SY3CP.js} +7 -5
  11. package/dist/chunk-4X4SY3CP.js.map +7 -0
  12. package/dist/chunk-DNJ3N4T4.js +82 -0
  13. package/dist/chunk-DNJ3N4T4.js.map +7 -0
  14. package/dist/{chunk-PGZ4EHSE.js → chunk-HL3IIHU3.js} +501 -359
  15. package/dist/chunk-HL3IIHU3.js.map +7 -0
  16. package/dist/{chunk-REJ5HLIM.js → chunk-HYJYYEPK.js} +2 -2
  17. package/dist/{chunk-7U4IB65H.js → chunk-LLBJ2SJH.js} +5 -3
  18. package/dist/{chunk-7U4IB65H.js.map → chunk-LLBJ2SJH.js.map} +1 -1
  19. package/dist/{chunk-XJNADRGR.js → chunk-NFZJ6P42.js} +188 -96
  20. package/dist/chunk-NFZJ6P42.js.map +7 -0
  21. package/dist/chunk-PAI2ZUWV.js +260 -0
  22. package/dist/chunk-PAI2ZUWV.js.map +7 -0
  23. package/dist/chunk-Q7BALEPX.js +527 -0
  24. package/dist/chunk-Q7BALEPX.js.map +7 -0
  25. package/dist/{chunk-2Z2ENHR3.js → chunk-QRBOIUU3.js} +7 -8
  26. package/dist/chunk-QRBOIUU3.js.map +7 -0
  27. package/dist/chunk-QXAOTGCC.js +40 -0
  28. package/dist/chunk-QXAOTGCC.js.map +7 -0
  29. package/dist/chunk-UKP22RUG.js +219 -0
  30. package/dist/chunk-UKP22RUG.js.map +7 -0
  31. package/dist/chunk-VLOAI3HS.js +43 -0
  32. package/dist/chunk-VLOAI3HS.js.map +7 -0
  33. package/dist/{chunk-WUFLGETN.js → chunk-WVFGV5FT.js} +2 -39
  34. package/dist/{chunk-WUFLGETN.js.map → chunk-WVFGV5FT.js.map} +3 -3
  35. package/dist/editor.js +3 -2
  36. package/dist/editor.js.map +1 -1
  37. package/dist/flexdesk.css +7547 -5891
  38. package/dist/flow.js +29 -97
  39. package/dist/flow.js.map +3 -3
  40. package/dist/git.js +1356 -0
  41. package/dist/git.js.map +7 -0
  42. package/dist/reset.css +1 -1
  43. package/dist/tiles.js +20 -15
  44. package/dist/tiles.js.map +2 -2
  45. package/dist/tokens.css +30 -1
  46. package/dist/widgets.js +4146 -1199
  47. package/dist/widgets.js.map +4 -4
  48. package/dist/wm.js +120 -32
  49. package/dist/wm.js.map +2 -2
  50. package/docs/README.md +9 -4
  51. package/docs/best-practices.md +2 -2
  52. package/docs/components/charts.md +40 -0
  53. package/docs/components/chat-shell.md +204 -0
  54. package/docs/components/conversation.md +10 -0
  55. package/docs/components/filter-builder.md +292 -0
  56. package/docs/components/forms-and-dialogs.md +30 -0
  57. package/docs/components/git.md +355 -0
  58. package/docs/components/input-fields.md +191 -2
  59. package/docs/components/keymap.md +8 -0
  60. package/docs/components/menus.md +86 -2
  61. package/docs/components/panels-and-desktops.md +16 -5
  62. package/docs/components/shell.md +108 -1
  63. package/docs/components/workspace-picker.md +193 -0
  64. package/docs/concepts/building-and-packaging.md +2 -2
  65. package/docs/concepts/packages-and-entry-points.md +14 -13
  66. package/docs/concepts/state-guard.md +3 -3
  67. package/docs/quickstart.md +1 -1
  68. package/git.js +13 -0
  69. package/package.json +6 -1
  70. package/src/charts/plot_config_editor.js +92 -6
  71. package/src/charts/plot_grid.js +6 -1
  72. package/src/flow/kit/dom.js +28 -119
  73. package/src/flow/kit/step_picker.js +1 -1
  74. package/src/flow/kit/value_picker.js +1 -1
  75. package/src/flow/outline/menu.js +1 -1
  76. package/src/git/diff_viewer.js +212 -0
  77. package/src/git/diff_window.js +51 -0
  78. package/src/git/git_graph.js +401 -0
  79. package/src/git/git_ops.js +61 -0
  80. package/src/git/git_panel.js +755 -0
  81. package/src/git/index.js +9 -0
  82. package/src/git/line_diff.js +202 -0
  83. package/src/tiles/tile_base.js +5 -4
  84. package/src/tiling/desktops.js +10 -8
  85. package/src/tiling/keymap.js +6 -5
  86. package/src/tiling/kind_taxonomy.js +15 -2
  87. package/src/tiling/shell.js +124 -17
  88. package/src/tiling/tile_renderer.js +2 -3
  89. package/src/ui/components/action_dropdown.js +4 -78
  90. package/src/ui/components/anchored_layer.js +255 -0
  91. package/src/ui/components/chat_shell.js +926 -0
  92. package/src/ui/components/chat_state_machine.js +223 -0
  93. package/src/ui/components/choice_controls.js +45 -2
  94. package/src/ui/components/color_field.js +3 -2
  95. package/src/ui/components/color_list_field.js +3 -2
  96. package/src/ui/components/combobox.js +422 -0
  97. package/src/ui/components/context_menu.js +8 -2
  98. package/src/ui/components/conversation_view.js +17 -2
  99. package/src/ui/components/data_table.js +2 -2
  100. package/src/ui/components/filter_builder.js +791 -0
  101. package/src/ui/components/filter_model.js +682 -0
  102. package/src/ui/components/inline_renamer.js +10 -5
  103. package/src/ui/components/managed_window.js +24 -47
  104. package/src/ui/components/modal.js +104 -117
  105. package/src/ui/components/option_list.js +160 -0
  106. package/src/ui/components/popover.js +94 -0
  107. package/src/ui/components/recent_items.js +169 -0
  108. package/src/ui/components/select.js +322 -0
  109. package/src/ui/components/tag_input.js +77 -8
  110. package/src/ui/components/workspace_picker.js +1253 -0
  111. package/src/ui/utils/fire_event.js +17 -0
  112. package/src/ui/utils/focusable.js +25 -0
  113. package/src/ui/utils/modal_host.js +27 -0
  114. package/src/ui/utils/tooltip_service.js +81 -14
  115. package/widgets.js +12 -2
  116. package/css/base.css +0 -10547
  117. package/css/overrides.css +0 -2596
  118. package/dist/chunk-2Z2ENHR3.js.map +0 -7
  119. package/dist/chunk-7JI7HHSY.js +0 -107
  120. package/dist/chunk-7JI7HHSY.js.map +0 -7
  121. package/dist/chunk-7OL6F2AM.js.map +0 -7
  122. package/dist/chunk-MIW7D6WC.js +0 -526
  123. package/dist/chunk-MIW7D6WC.js.map +0 -7
  124. package/dist/chunk-PGZ4EHSE.js.map +0 -7
  125. package/dist/chunk-XJNADRGR.js.map +0 -7
  126. /package/dist/{chunk-REJ5HLIM.js.map → chunk-HYJYYEPK.js.map} +0 -0
@@ -0,0 +1,322 @@
1
+ /**
2
+ * createSelect — A SELECT DRAWN IN THE DOM. (0.18.0)
3
+ *
4
+ * A native `<select>` styles down to its closed box: the list is the operating
5
+ * system's, so it cannot show a glyph or a second line, ignores the tokens and
6
+ * opens at the system's type size. `selectBox` (`choice_controls.js`) is the
7
+ * native one, for a list with nothing to say in a tight strip. This one is for
8
+ * the rest: a trigger showing the current value, over a list whose rows have a
9
+ * glyph, a second line and a hint, under group headings, with a search box and,
10
+ * with `allowNew`, a way to type a value nobody listed.
11
+ *
12
+ * THE VALUE IS NEVER SILENTLY CHANGED. A value in none of the options, or naming a
13
+ * disabled one, stays the value and is shown (a disabled option under its label,
14
+ * any other through `notFound`): a list that arrives late or has moved on must not
15
+ * turn it into something else on the next save. Only `null`, `undefined` and `''`
16
+ * with no option of their own read as "nothing chosen", showing `placeholder`.
17
+ *
18
+ * Values keep their type, as in `choice_controls.js`; `loose` lets a stored `'2'`
19
+ * name option `2`.
20
+ *
21
+ * Focus stays on the trigger unless there is a search box, which then holds it.
22
+ * Either way the arrow keys move the highlight, named by `aria-activedescendant`,
23
+ * and Tab closes the list and goes on from the trigger.
24
+ */
25
+ import { openAnchoredLayer } from './anchored_layer.js';
26
+ import { fireEvent } from '../utils/fire_event.js';
27
+ import { choiceSections, filterSections, findChoice, flatChoices, shownValue } from './choice_controls.js';
28
+ import { createOptionList } from './option_list.js';
29
+
30
+ /** More options than this and a select draws a search box unless told otherwise. */
31
+ const SEARCH_ABOVE = 7;
32
+ /** Printable keys within this many ms are one word for the type-ahead. */
33
+ const TYPEAHEAD_MS = 500;
34
+
35
+ function node(tag, className, text) {
36
+ const n = document.createElement(tag);
37
+ if (className) n.className = className;
38
+ if (text !== undefined) n.textContent = String(text);
39
+ return n;
40
+ }
41
+
42
+ function glyphNode(className, text = '') {
43
+ const n = node('span', `material-symbols-outlined ${className}`.trim(), text);
44
+ n.setAttribute('aria-hidden', 'true');
45
+ return n;
46
+ }
47
+
48
+ const isEmptyValue = (v) => v === null || v === undefined || v === '';
49
+
50
+ /**
51
+ * @param {object} config
52
+ * @param {Array|(() => Array)} [config.options] Bare values, `{ value, label?, icon?,
53
+ * description?, hint?, keywords?, disabled?, reason? }`, or `{ group, options }`.
54
+ * A function is read each time the list opens and the trigger is painted, for a
55
+ * list that grows while the page lives.
56
+ * @param {*} [config.value]
57
+ * @param {(value: *, option: object|null) => void} [config.onChange] After the reader
58
+ * chooses a different value. `option` is the entry as you gave it, `null` for a
59
+ * new value (`allowNew`). Not called for `value =` or `setOptions`.
60
+ * @param {string} [config.className] Extra classes on the trigger.
61
+ * @param {string} [config.panelClassName] Extra classes on the list's panel.
62
+ * @param {string} [config.placeholder] Shown while nothing is chosen.
63
+ * @param {string} [config.title] The trigger's tooltip; else it says the value.
64
+ * @param {string} [config.ariaLabel] When no `<label>` names the control.
65
+ * @param {boolean} [config.disabled]
66
+ * @param {boolean} [config.showIcon=true] Draw the chosen option's glyph on the trigger too.
67
+ * @param {boolean|{placeholder?: string}} [config.search] The search box. By default it
68
+ * is there with `allowNew` or more than seven options.
69
+ * @param {boolean} [config.allowNew] A value in no option may be typed into the
70
+ * search box; it is offered as its own row at the end of the list.
71
+ * @param {(typed: string) => string} [config.newLabel] That row's words.
72
+ * @param {(value: string) => string} [config.notFound] How an unlisted value reads on the trigger.
73
+ * @param {(typed: string) => string} [config.emptyText] What a list with no rows says.
74
+ * @param {boolean} [config.loose] A stored value names an option of the same text.
75
+ * @param {string} [config.name] A hidden input of this name carries the value
76
+ * as text, for a surrounding form; it fires a bubbling `change` when the reader chooses.
77
+ * @param {HTMLInputElement} [config.carrier] That hidden input, yours, for a field something
78
+ * finds by more than a name (`[data-f]`, an id). Instead of `name`; its attributes are left as they are.
79
+ * @param {'start'|'end'} [config.align]
80
+ * @returns {{el: HTMLElement, input: HTMLInputElement|null, value: *, isOpen: boolean,
81
+ * setOptions: Function, setPlaceholder: Function, setDisabled: Function,
82
+ * open: Function, close: Function, focus: Function, destroy: Function}}
83
+ * `el` is the control to put in your layout: the trigger, or a wrapper round it
84
+ * and the hidden input when there is a `name` or a `carrier`.
85
+ */
86
+ export function createSelect({
87
+ options = [], value = null, onChange = null, className = '', panelClassName = '', placeholder = 'Choose…',
88
+ title = '', ariaLabel = '', disabled = false, showIcon = true, search = undefined, allowNew = false,
89
+ newLabel = (typed) => `Use “${typed}”`, notFound = (v) => v,
90
+ emptyText = (typed) => (typed ? `Nothing matches “${typed}”.` : 'Nothing to choose from.'),
91
+ loose = false, name = null, carrier = null, align = 'start',
92
+ } = {}) {
93
+ let source = options;
94
+ let current = value;
95
+ let emptyLabel = placeholder;
96
+ let layer = null;
97
+ let typedKeys = '';
98
+ let typedTimer = null;
99
+
100
+ const given = () => (typeof source === 'function' ? source() : source) || [];
101
+
102
+ const trigger = node('button', `twm-select${className ? ` ${className}` : ''}`);
103
+ trigger.type = 'button';
104
+ trigger.setAttribute('role', 'combobox');
105
+ trigger.setAttribute('aria-haspopup', 'listbox');
106
+ trigger.setAttribute('aria-expanded', 'false');
107
+ if (ariaLabel) trigger.setAttribute('aria-label', ariaLabel);
108
+ const icon = glyphNode('twm-select__icon');
109
+ const label = node('span', 'twm-select__label');
110
+ trigger.append(icon, label, glyphNode('twm-select__caret', 'expand_more'));
111
+
112
+ let root = trigger;
113
+ let hidden = carrier;
114
+ if (name && !hidden) {
115
+ hidden = node('input');
116
+ hidden.type = 'hidden';
117
+ hidden.name = name;
118
+ }
119
+ if (hidden) {
120
+ root = node('div', 'twm-select-field');
121
+ root.append(trigger, hidden);
122
+ }
123
+
124
+ // Whichever holds focus names the active row.
125
+ let focusHolder = trigger;
126
+ const list = createOptionList({
127
+ onPick: (option) => choose(option),
128
+ onActive: (id) => {
129
+ if (id) focusHolder.setAttribute('aria-activedescendant', id);
130
+ else focusHolder.removeAttribute('aria-activedescendant');
131
+ },
132
+ });
133
+ trigger.setAttribute('aria-controls', list.id);
134
+
135
+ const panel = node('div', `twm-option-panel${panelClassName ? ` ${panelClassName}` : ''}`);
136
+ const searchRow = node('div', 'twm-option-panel__search');
137
+ searchRow.appendChild(glyphNode('', 'search'));
138
+ const searchInput = node('input', 'twm-option-panel__search-input');
139
+ searchInput.type = 'text';
140
+ searchInput.autocomplete = 'off';
141
+ searchInput.spellcheck = false;
142
+ searchInput.setAttribute('role', 'combobox');
143
+ searchInput.setAttribute('aria-expanded', 'true');
144
+ searchInput.setAttribute('aria-autocomplete', 'list');
145
+ searchInput.setAttribute('aria-controls', list.id);
146
+ searchRow.appendChild(searchInput);
147
+ panel.append(searchRow, list.el);
148
+
149
+ const hasSearch = () => (search === undefined
150
+ ? allowNew || flatChoices(given()).length > SEARCH_ABOVE
151
+ : !!search);
152
+
153
+ function paint() {
154
+ const flat = flatChoices(given());
155
+ const chosen = findChoice(flat, current, loose);
156
+ const none = !chosen && isEmptyValue(current);
157
+ label.textContent = chosen ? chosen.label : none ? emptyLabel : notFound(shownValue(current));
158
+ trigger.classList.toggle('twm-select--empty', none);
159
+ trigger.title = title || label.textContent;
160
+ const glyph = showIcon ? (chosen?.icon || '') : '';
161
+ icon.textContent = glyph;
162
+ icon.hidden = !glyph;
163
+ if (hidden) hidden.value = isEmptyValue(current) ? '' : shownValue(current);
164
+ }
165
+
166
+ /** The rows for what is typed, a new-value row after them when it is offered. */
167
+ function draw(typed) {
168
+ const text = typed.trim();
169
+ const all = choiceSections(given());
170
+ const flat = all.flatMap((s) => s.items);
171
+ const taken = (o) => [o.value, o.label].some((v) => shownValue(v).toLowerCase() === text.toLowerCase());
172
+ const shown = filterSections(all, text);
173
+ if (allowNew && text !== '' && !flat.some(taken)) {
174
+ shown.push({ heading: null, items: [{ value: text, label: newLabel(text), icon: 'add', description: null,
175
+ hint: null, disabled: false, reason: null, keywords: null,
176
+ source: null }] });
177
+ }
178
+ const chosen = findChoice(flat, current, loose);
179
+ if (shown.length) {
180
+ list.setRows(shown, { mark: text, isCurrent: (o) => o === chosen });
181
+ // On the current value when it is showing, else on the first row that may be chosen.
182
+ const at = list.options().indexOf(chosen);
183
+ if (at >= 0 && !chosen.disabled) list.setActive(at);
184
+ else list.moveToEnd(1);
185
+ } else {
186
+ list.setMessage(emptyText(text));
187
+ }
188
+ layer?.place();
189
+ }
190
+
191
+ function choose(option) {
192
+ const changed = !(option.value === current || (loose && String(option.value) === String(current)));
193
+ current = option.value;
194
+ paint();
195
+ layer?.close('pick');
196
+ if (!changed) return;
197
+ if (hidden) fireEvent(hidden, 'change', { bubbles: true });
198
+ onChange?.(current, option.source);
199
+ }
200
+
201
+ function open() {
202
+ if (layer || trigger.disabled) return;
203
+ const searching = hasSearch();
204
+ searchRow.hidden = !searching;
205
+ focusHolder = searching ? searchInput : trigger;
206
+ if (searching) {
207
+ const word = (typeof search === 'object' && search?.placeholder)
208
+ || (allowNew ? 'Search, or type a new one…' : 'Search…');
209
+ searchInput.placeholder = word;
210
+ searchInput.setAttribute('aria-label', word);
211
+ searchInput.value = '';
212
+ }
213
+ panel.style.width = '';
214
+ layer = openAnchoredLayer({
215
+ anchor: trigger, el: panel, align, gap: 4, matchWidth: true,
216
+ onClose() {
217
+ layer = null;
218
+ trigger.classList.remove('twm-is-open');
219
+ trigger.setAttribute('aria-expanded', 'false');
220
+ focusHolder.removeAttribute('aria-activedescendant');
221
+ },
222
+ });
223
+ if (!layer) return; // the trigger is not on the page
224
+ trigger.classList.add('twm-is-open');
225
+ trigger.setAttribute('aria-expanded', 'true');
226
+ // Once it is on the page: the current value has to scroll into view.
227
+ draw('');
228
+ if (searching) {
229
+ // PINNED, or the panel narrows and widens under the pointer as each
230
+ // keystroke hides or shows the longest name in it.
231
+ const width = Math.round(panel.getBoundingClientRect().width);
232
+ if (width > 0) panel.style.width = `${width}px`;
233
+ searchInput.focus({ preventScroll: true });
234
+ }
235
+ }
236
+
237
+ const close = () => layer?.close('closed');
238
+
239
+ /** Printable keys on a trigger with no search box walk to the label they begin. */
240
+ function typeAhead(ch) {
241
+ clearTimeout(typedTimer);
242
+ typedTimer = setTimeout(() => { typedKeys = ''; }, TYPEAHEAD_MS);
243
+ typedKeys += ch.toLowerCase();
244
+ const at = list.options().findIndex((o) => !o.disabled && o.label.toLowerCase().startsWith(typedKeys));
245
+ if (at >= 0) list.setActive(at);
246
+ }
247
+
248
+ function onKey(ev) {
249
+ if (ev.isComposing) return;
250
+ const inSearch = ev.target === searchInput;
251
+ if (!layer) {
252
+ if (ev.key === 'ArrowDown' || ev.key === 'ArrowUp' || ev.key === 'Enter' || ev.key === ' ') {
253
+ ev.preventDefault();
254
+ open();
255
+ }
256
+ return;
257
+ }
258
+ if (ev.key === 'Tab') {
259
+ // Not taken: focus goes back to the trigger, and the Tab goes on from there.
260
+ layer.close('tab');
261
+ return;
262
+ }
263
+ if (ev.key === 'ArrowDown') list.move(1);
264
+ else if (ev.key === 'ArrowUp') list.move(-1);
265
+ else if (ev.key === 'Home' && !inSearch) list.moveToEnd(1);
266
+ else if (ev.key === 'End' && !inSearch) list.moveToEnd(-1);
267
+ else if (ev.key === 'Enter' || (ev.key === ' ' && !inSearch)) {
268
+ const option = list.activeOption();
269
+ if (option) choose(option);
270
+ else if (!inSearch) close();
271
+ } else if (!inSearch && ev.key.length === 1 && !ev.ctrlKey && !ev.metaKey && !ev.altKey) {
272
+ typeAhead(ev.key);
273
+ } else {
274
+ return;
275
+ }
276
+ ev.preventDefault();
277
+ ev.stopPropagation();
278
+ }
279
+
280
+ trigger.addEventListener('click', () => { if (layer) close(); else open(); });
281
+ trigger.addEventListener('keydown', onKey);
282
+ // Some browsers click a button on Space's keyup whatever its keydown did.
283
+ trigger.addEventListener('keyup', (ev) => { if (ev.key === ' ') ev.preventDefault(); });
284
+ searchInput.addEventListener('keydown', onKey);
285
+ searchInput.addEventListener('input', () => draw(searchInput.value));
286
+
287
+ function setDisabled(off) {
288
+ trigger.disabled = !!off;
289
+ if (off) close();
290
+ }
291
+
292
+ paint();
293
+ setDisabled(disabled);
294
+
295
+ return {
296
+ el: root,
297
+ /** The hidden input carrying the value, when there is one. */
298
+ input: hidden,
299
+ get value() { return current; },
300
+ set value(next) { current = next; paint(); },
301
+ get isOpen() { return !!layer; },
302
+ /** Replace the list. Pass `nextValue` to change the value as well; left out, it stays. */
303
+ setOptions(nextOptions, nextValue) {
304
+ source = nextOptions;
305
+ if (arguments.length > 1) current = nextValue;
306
+ paint();
307
+ if (layer) draw(searchInput.value);
308
+ },
309
+ /** The text shown while nothing is chosen: "Loading…", the failure, "Choose…". */
310
+ setPlaceholder(text) { emptyLabel = text; paint(); },
311
+ setDisabled,
312
+ open,
313
+ close,
314
+ focus() { trigger.focus(); },
315
+ /** Closes the list and takes the control off the page. */
316
+ destroy() {
317
+ clearTimeout(typedTimer);
318
+ close();
319
+ root.remove();
320
+ },
321
+ };
322
+ }
@@ -28,12 +28,20 @@
28
28
  * tags.getValue(); // ['baseline']
29
29
  * tags.setValue(['a', 'b']);
30
30
  * tags.dispose();
31
+ *
32
+ * `suggestions` (0.18.0) offers known tags under the box, on `attachInputOptions`:
33
+ * the arrow keys walk the rows, and Enter or a comma takes the active one; with none
34
+ * active they commit what was typed. Whatever the list's source, a row is in the one
35
+ * spelling, says a tag once and is not a tag already in the list. An array is filtered
36
+ * and ordered here, the earliest match first and then alphabetically; a function
37
+ * answers for itself and keeps its own order, and may be async.
38
+ * `normalise` (0.18.0) keeps one spelling of a tag: `Path Finding` and `path-finding`
39
+ * cannot both exist, whichever way one arrives. It is handed the trimmed text.
31
40
  */
41
+ import { attachInputOptions } from './combobox.js';
42
+ import { shownValue } from './choice_controls.js';
32
43
 
33
- /** The list as strings, the empty ones left out. */
34
- const normalise = (list) => (Array.isArray(list) ? list : [])
35
- .map((v) => (v == null ? '' : String(v).trim()))
36
- .filter((v) => v !== '');
44
+ const optionValue = (o) => (o !== null && typeof o === 'object' ? o.value : o);
37
45
 
38
46
  /**
39
47
  * @typedef {Object} TagInputOptions
@@ -45,6 +53,9 @@ const normalise = (list) => (Array.isArray(list) ? list : [])
45
53
  * @property {string} [label] - The text box's accessible name.
46
54
  * @property {(tag: string) => string} [removeLabel] - A remove button's `aria-label`.
47
55
  * @property {string} [className] - Extra classes on the root.
56
+ * @property {Array|((query: string, ctx: {signal: AbortSignal}) => Array|Promise<Array>)} [suggestions] -
57
+ * Known tags: strings or `{ value, label?, description?, icon?, hint? }`.
58
+ * @property {(text: string) => string} [normalise] - The one spelling of a tag.
48
59
  */
49
60
 
50
61
  /**
@@ -59,8 +70,16 @@ export function createTagInput(host, options = {}) {
59
70
  const allowDuplicates = !!options.allowDuplicates;
60
71
  const removeLabel = typeof options.removeLabel === 'function'
61
72
  ? options.removeLabel : (tag) => `Remove ${tag}`;
73
+ const spell = typeof options.normalise === 'function'
74
+ ? (text) => String(options.normalise(text.trim()) ?? '').trim() : (text) => text.trim();
75
+
76
+ /** The list as spelled, the empty ones left out, and a repeat unless it is allowed. */
77
+ const cleaned = (list) => {
78
+ const out = (Array.isArray(list) ? list : []).map((v) => (v == null ? '' : spell(String(v)))).filter((v) => v !== '');
79
+ return allowDuplicates ? out : [...new Set(out)];
80
+ };
62
81
 
63
- let tags = normalise(options.value);
82
+ let tags = cleaned(options.value);
64
83
  let disposed = false;
65
84
 
66
85
  const root = document.createElement('div');
@@ -134,7 +153,7 @@ export function createTagInput(host, options = {}) {
134
153
  if (disposed || readOnly) return false;
135
154
  const next = [...tags];
136
155
  for (const piece of String(text).split(',')) {
137
- const tag = piece.trim();
156
+ const tag = spell(piece);
138
157
  if (tag === '') continue;
139
158
  if (!allowDuplicates && next.includes(tag)) continue;
140
159
  next.push(tag);
@@ -150,17 +169,66 @@ export function createTagInput(host, options = {}) {
150
169
  return true;
151
170
  };
152
171
 
172
+ /** Known tags as rows: in the one spelling, each once, less those already in the list. */
173
+ const offered = (list) => {
174
+ const seen = new Set();
175
+ const rows = [];
176
+ for (const o of list || []) {
177
+ const tag = spell(shownValue(optionValue(o)));
178
+ if (tag === '' || seen.has(tag) || (!allowDuplicates && tags.includes(tag))) continue;
179
+ seen.add(tag);
180
+ rows.push(o !== null && typeof o === 'object' ? { ...o, value: tag } : tag);
181
+ }
182
+ return rows;
183
+ };
184
+ // What is typed is the query however the list opened: an arrow key or a click
185
+ // reopening it must not offer rows that have nothing to do with the text in the box.
186
+ /** An array of known tags: those holding what is typed, the earliest match first, then alphabetically. */
187
+ const rankedFor = () => {
188
+ const needle = spell(input.value).toLowerCase();
189
+ const word = (o) => shownValue(optionValue(o));
190
+ const at = (o) => word(o).toLowerCase().indexOf(needle);
191
+ return offered(options.suggestions).filter((o) => at(o) >= 0)
192
+ .sort((x, y) => at(x) - at(y) || word(x).localeCompare(word(y)));
193
+ };
194
+ /** A function's answer, whenever it comes. */
195
+ const askedFor = (_query, ctx) => {
196
+ const answer = options.suggestions(input.value, ctx);
197
+ return typeof answer?.then === 'function' ? answer.then(offered) : offered(answer);
198
+ };
199
+ const asking = typeof options.suggestions === 'function';
200
+
201
+ // Before the box's own keydown listener: a row taken by Enter is not also a commit.
202
+ const menu = input && options.suggestions
203
+ ? attachInputOptions(input, {
204
+ options: asking ? askedFor : rankedFor,
205
+ anchor: root,
206
+ normalise: spell,
207
+ openOnFocus: true,
208
+ passEnter: true,
209
+ debounce: asking ? undefined : 0,
210
+ onPick(option) {
211
+ input.value = '';
212
+ commitText(shownValue(option.value));
213
+ input.focus();
214
+ },
215
+ })
216
+ : null;
217
+
153
218
  const commitInput = () => {
154
219
  if (!input) return;
155
220
  const text = input.value;
156
221
  input.value = '';
222
+ menu?.close();
157
223
  commitText(text);
158
224
  };
159
225
 
160
226
  if (input) {
161
227
  input.addEventListener('keydown', (ev) => {
162
228
  if (ev.isComposing) return;
163
- if (ev.key === 'Enter' || ev.key === ',') {
229
+ if (ev.key === ',' && menu?.takeActive()) {
230
+ ev.preventDefault();
231
+ } else if (ev.key === 'Enter' || ev.key === ',') {
164
232
  ev.preventDefault();
165
233
  commitInput();
166
234
  } else if (ev.key === 'Backspace' && input.value === '' && tags.length) {
@@ -202,13 +270,14 @@ export function createTagInput(host, options = {}) {
202
270
  /** Replaces the list. Does not call `onChange`. */
203
271
  setValue(list) {
204
272
  if (disposed) return;
205
- tags = normalise(list);
273
+ tags = cleaned(list);
206
274
  paint();
207
275
  },
208
276
  focus() { input?.focus(); },
209
277
  dispose() {
210
278
  if (disposed) return;
211
279
  disposed = true;
280
+ menu?.destroy();
212
281
  root.remove();
213
282
  },
214
283
  };