flexdesk 0.17.18 → 0.18.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.
Files changed (118) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/README.md +1 -0
  3. package/css/flexdesk.css +7544 -5916
  4. package/css/reset.css +1 -1
  5. package/css/tokens.css +23 -1
  6. package/dist/charts.js +10 -6
  7. package/dist/charts.js.map +1 -1
  8. package/dist/chunk-5W4EEKSK.js +778 -0
  9. package/dist/chunk-5W4EEKSK.js.map +7 -0
  10. package/dist/chunk-DNJ3N4T4.js +82 -0
  11. package/dist/chunk-DNJ3N4T4.js.map +7 -0
  12. package/dist/{chunk-REJ5HLIM.js → chunk-HYJYYEPK.js} +2 -2
  13. package/dist/{chunk-7U4IB65H.js → chunk-LLBJ2SJH.js} +5 -3
  14. package/dist/{chunk-7U4IB65H.js.map → chunk-LLBJ2SJH.js.map} +1 -1
  15. package/dist/{chunk-7OL6F2AM.js → chunk-P74F6I6P.js} +6 -4
  16. package/dist/{chunk-7OL6F2AM.js.map → chunk-P74F6I6P.js.map} +1 -1
  17. package/dist/chunk-PAI2ZUWV.js +260 -0
  18. package/dist/chunk-PAI2ZUWV.js.map +7 -0
  19. package/dist/chunk-Q7BALEPX.js +527 -0
  20. package/dist/chunk-Q7BALEPX.js.map +7 -0
  21. package/dist/chunk-QXAOTGCC.js +40 -0
  22. package/dist/chunk-QXAOTGCC.js.map +7 -0
  23. package/dist/{chunk-XJNADRGR.js → chunk-RKVYIXDC.js} +664 -91
  24. package/dist/chunk-RKVYIXDC.js.map +7 -0
  25. package/dist/{chunk-2Z2ENHR3.js → chunk-U5GKJUOC.js} +3 -3
  26. package/dist/{chunk-2Z2ENHR3.js.map → chunk-U5GKJUOC.js.map} +1 -1
  27. package/dist/chunk-UKP22RUG.js +219 -0
  28. package/dist/chunk-UKP22RUG.js.map +7 -0
  29. package/dist/chunk-VLOAI3HS.js +43 -0
  30. package/dist/chunk-VLOAI3HS.js.map +7 -0
  31. package/dist/{chunk-WUFLGETN.js → chunk-WVFGV5FT.js} +2 -39
  32. package/dist/{chunk-WUFLGETN.js.map → chunk-WVFGV5FT.js.map} +3 -3
  33. package/dist/{chunk-PGZ4EHSE.js → chunk-ZL3VKINP.js} +41 -390
  34. package/dist/chunk-ZL3VKINP.js.map +7 -0
  35. package/dist/editor.js +3 -2
  36. package/dist/editor.js.map +1 -1
  37. package/dist/flexdesk.css +7544 -5916
  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 +23 -1
  46. package/dist/widgets.js +3967 -1188
  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/chat-shell.md +198 -0
  53. package/docs/components/conversation.md +10 -0
  54. package/docs/components/filter-builder.md +246 -0
  55. package/docs/components/forms-and-dialogs.md +22 -0
  56. package/docs/components/git.md +355 -0
  57. package/docs/components/input-fields.md +167 -2
  58. package/docs/components/keymap.md +8 -0
  59. package/docs/components/menus.md +82 -2
  60. package/docs/components/panels-and-desktops.md +16 -5
  61. package/docs/components/shell.md +104 -1
  62. package/docs/components/workspace-picker.md +149 -0
  63. package/docs/concepts/building-and-packaging.md +2 -2
  64. package/docs/concepts/packages-and-entry-points.md +14 -13
  65. package/docs/concepts/state-guard.md +3 -3
  66. package/docs/quickstart.md +1 -1
  67. package/git.js +13 -0
  68. package/package.json +6 -1
  69. package/src/flow/kit/dom.js +28 -119
  70. package/src/flow/kit/step_picker.js +1 -1
  71. package/src/flow/kit/value_picker.js +1 -1
  72. package/src/flow/outline/menu.js +1 -1
  73. package/src/git/diff_viewer.js +212 -0
  74. package/src/git/diff_window.js +51 -0
  75. package/src/git/git_graph.js +401 -0
  76. package/src/git/git_ops.js +61 -0
  77. package/src/git/git_panel.js +755 -0
  78. package/src/git/index.js +9 -0
  79. package/src/git/line_diff.js +202 -0
  80. package/src/tiles/tile_base.js +5 -4
  81. package/src/tiling/desktops.js +10 -8
  82. package/src/tiling/keymap.js +6 -5
  83. package/src/tiling/kind_taxonomy.js +15 -2
  84. package/src/tiling/shell.js +124 -17
  85. package/src/tiling/tile_renderer.js +2 -3
  86. package/src/ui/components/action_dropdown.js +4 -78
  87. package/src/ui/components/anchored_layer.js +255 -0
  88. package/src/ui/components/chat_shell.js +920 -0
  89. package/src/ui/components/chat_state_machine.js +223 -0
  90. package/src/ui/components/choice_controls.js +45 -2
  91. package/src/ui/components/color_field.js +3 -2
  92. package/src/ui/components/color_list_field.js +3 -2
  93. package/src/ui/components/combobox.js +422 -0
  94. package/src/ui/components/conversation_view.js +17 -2
  95. package/src/ui/components/data_table.js +2 -2
  96. package/src/ui/components/filter_builder.js +766 -0
  97. package/src/ui/components/filter_model.js +614 -0
  98. package/src/ui/components/managed_window.js +24 -47
  99. package/src/ui/components/modal.js +79 -109
  100. package/src/ui/components/option_list.js +160 -0
  101. package/src/ui/components/popover.js +94 -0
  102. package/src/ui/components/recent_items.js +169 -0
  103. package/src/ui/components/select.js +322 -0
  104. package/src/ui/components/tag_input.js +77 -8
  105. package/src/ui/components/workspace_picker.js +1155 -0
  106. package/src/ui/utils/fire_event.js +17 -0
  107. package/src/ui/utils/focusable.js +25 -0
  108. package/src/ui/utils/modal_host.js +27 -0
  109. package/widgets.js +12 -2
  110. package/css/base.css +0 -10547
  111. package/css/overrides.css +0 -2596
  112. package/dist/chunk-7JI7HHSY.js +0 -107
  113. package/dist/chunk-7JI7HHSY.js.map +0 -7
  114. package/dist/chunk-MIW7D6WC.js +0 -526
  115. package/dist/chunk-MIW7D6WC.js.map +0 -7
  116. package/dist/chunk-PGZ4EHSE.js.map +0 -7
  117. package/dist/chunk-XJNADRGR.js.map +0 -7
  118. /package/dist/{chunk-REJ5HLIM.js.map → chunk-HYJYYEPK.js.map} +0 -0
@@ -0,0 +1,94 @@
1
+ /**
2
+ * A POPOVER — a panel of rich content hung off the element that opened it. (0.18.0)
3
+ *
4
+ * `role="dialog"`, on an anchored layer (`anchored_layer.js`, which says how it is
5
+ * placed and what closes it). Focus moves into it on open and comes back to the
6
+ * anchor on close. Opening one from the anchor that holds an open one closes it,
7
+ * a toggle; opening one anywhere else closes the open one, unless that one owns
8
+ * the new anchor (`anchored_layer.js`).
9
+ *
10
+ * TAB STAYS INSIDE, cycling the panel's controls, as a modal's and a `CategoryPicker`'s
11
+ * do. The panel is mounted at the end of the page, so past its edge lies whatever comes
12
+ * next in the document, which is not the anchor's neighbour and, over a modal, is behind
13
+ * it. Escape is the way out.
14
+ */
15
+ import { openAnchoredLayer } from './anchored_layer.js';
16
+ import { collectFocusable } from '../utils/focusable.js';
17
+
18
+ /** The open popovers, to find the one an anchor holds. */
19
+ const OPEN = new Set();
20
+
21
+ /** What a call answers when nothing opened. */
22
+ const nothingOpened = (toggled) => ({ el: null, close() {}, closed: Promise.resolve(), reposition() {}, toggled });
23
+
24
+ /** Tab at the panel's edge goes round to the other edge. */
25
+ function keepTabInside(el) {
26
+ el.addEventListener('keydown', (ev) => {
27
+ if (ev.key !== 'Tab' || ev.defaultPrevented) return;
28
+ const controls = collectFocusable(el);
29
+ if (!controls.length) { ev.preventDefault(); return; }
30
+ const first = controls[0];
31
+ const last = controls[controls.length - 1];
32
+ const active = el.ownerDocument.activeElement;
33
+ if (ev.shiftKey ? (active === first || active === el) : active === last) {
34
+ ev.preventDefault();
35
+ (ev.shiftKey ? last : first).focus();
36
+ }
37
+ });
38
+ }
39
+
40
+ /**
41
+ * @param {object} o
42
+ * @param {HTMLElement} o.anchor What opened it; focus returns here.
43
+ * @param {HTMLElement} o.content The popover's body.
44
+ * @param {string} [o.label] Its accessible name.
45
+ * @param {string} [o.className] Extra classes on the panel.
46
+ * @param {HTMLElement} [o.focus] What takes focus on open; else the panel.
47
+ * @param {'start'|'end'} [o.align] Which anchor edge it lines up with first.
48
+ * @param {string} [o.inside] A selector for floating things of your own that
49
+ * are not "outside" it.
50
+ * @param {(reason: string) => void} [o.onClose] After it is gone.
51
+ * @returns {{el: HTMLElement|null, close: (reason?: string) => void, closed: Promise<void>,
52
+ * reposition: () => void, toggled: boolean}}
53
+ * `el` is null when nothing opened, and `onClose` is not called for it: `toggled`
54
+ * is true when the call only CLOSED the popover its anchor held, false when
55
+ * the anchor has left the document.
56
+ */
57
+ export function openPopover({ anchor, content, label = '', className = '', focus = null, align = 'start',
58
+ inside = null, onClose = null }) {
59
+ for (const open of OPEN) {
60
+ if (anchor && open.anchor === anchor) {
61
+ open.close('toggle');
62
+ return nothingOpened(true);
63
+ }
64
+ }
65
+
66
+ const el = document.createElement('div');
67
+ el.className = `twm-popover${className ? ` ${className}` : ''}`;
68
+ el.setAttribute('role', 'dialog');
69
+ if (label) el.setAttribute('aria-label', label);
70
+ el.tabIndex = -1;
71
+ el.appendChild(content);
72
+ keepTabInside(el);
73
+
74
+ let settle;
75
+ const closed = new Promise((resolve) => { settle = resolve; });
76
+ const layer = openAnchoredLayer({
77
+ anchor, el, align, gap: 4, inside,
78
+ onClose(reason) {
79
+ OPEN.delete(handle);
80
+ anchor?.classList?.remove('twm-is-open');
81
+ anchor?.setAttribute?.('aria-expanded', 'false');
82
+ onClose?.(reason);
83
+ settle();
84
+ },
85
+ });
86
+ if (!layer) return nothingOpened(false);
87
+ const handle = { el, anchor, closed, toggled: false, close: layer.close, reposition: layer.place };
88
+ OPEN.add(handle);
89
+ anchor?.classList?.add('twm-is-open');
90
+ if (anchor && !anchor.hasAttribute?.('aria-haspopup')) anchor.setAttribute?.('aria-haspopup', 'dialog');
91
+ anchor?.setAttribute?.('aria-expanded', 'true');
92
+ (focus || el).focus?.({ preventScroll: true });
93
+ return handle;
94
+ }
@@ -0,0 +1,169 @@
1
+ /**
2
+ * recent_items.js — a most-recent-first list kept through the Host's `state`
3
+ * capability, so it survives a restart.
4
+ *
5
+ * const recent = createRecentItems({ host, key: 'recent-workspaces' });
6
+ * await recent.load();
7
+ * recent.add({ id: 'w1', name: 'North' });
8
+ * recent.list(); // [{ id: 'w1', name: 'North', openedAt: 1730... }]
9
+ *
10
+ * An entry is any plain object; `identity` says which two are the same one, and
11
+ * `add` stamps `openedAt`. `capacity` is per `groupOf(entry)` when that is
12
+ * given, so one busy kind of entry never pushes another kind out.
13
+ *
14
+ * ══ A READ THAT FAILS IS NOT AN EMPTY LIST ═════════════════════════════════
15
+ *
16
+ * A `host.state.read` that rejects says nothing about what is stored, so until
17
+ * a read succeeds the stored list is never written: writing would replace
18
+ * entries nobody has seen. Changes made in the meantime show in `list()` at
19
+ * once, are kept, are replayed onto the stored list when it is read, and each
20
+ * of them asks for the read again. A read that answers something other than an
21
+ * array is a read: the store is empty.
22
+ *
23
+ * Writes run one at a time and the last one carries the latest list, because a
24
+ * host may answer them out of order and the older list must not win.
25
+ *
26
+ * A host with no `state` capability keeps the list in memory for this session.
27
+ */
28
+
29
+ /**
30
+ * @param {object} options
31
+ * @param {object} options.host - The Host; its `state` keeps the list
32
+ * @param {string} options.key - The state key the list is stored under
33
+ * @param {(entry: object) => string} [options.identity] - Which entries are the same one
34
+ * @param {(entry: unknown) => boolean} [options.isValid] - Stored entries that fail this
35
+ * are dropped on read, as is one that makes it, `identity` or `groupOf` throw, so
36
+ * `identity` may assume an entry's shape.
37
+ * @param {number} [options.capacity=10] - The most entries kept, per group
38
+ * @param {(entry: object) => string} [options.groupOf] - Groups the capacity counts within
39
+ * @param {() => void} [options.onChange] - After every change, and after a read that
40
+ * replayed changes
41
+ * @param {object} [options.logger] - Its `warn` hears a failed read or write
42
+ */
43
+ export function createRecentItems({
44
+ host,
45
+ key,
46
+ identity = (entry) => entry.id,
47
+ isValid = (entry) => !!entry && typeof entry === 'object' && !!identity(entry),
48
+ capacity = 10,
49
+ groupOf = () => '',
50
+ onChange = null,
51
+ logger = null,
52
+ }) {
53
+ const state = host?.state ?? null;
54
+ let entries = [];
55
+ let loaded = !state;
56
+ /** The changes made while the stored list is unread, oldest first: list => list. */
57
+ let pending = [];
58
+ let reading = null;
59
+ let writing = false;
60
+ let writeAgain = false;
61
+
62
+ const capped = (list) => {
63
+ const counts = new Map();
64
+ return list.filter((entry) => {
65
+ const group = groupOf(entry);
66
+ const count = (counts.get(group) ?? 0) + 1;
67
+ counts.set(group, count);
68
+ return count <= capacity;
69
+ });
70
+ };
71
+
72
+ const without = (list, entry) => {
73
+ const id = identity(entry);
74
+ return list.filter((other) => identity(other) !== id);
75
+ };
76
+
77
+ async function write() {
78
+ if (!state) return;
79
+ if (writing) {
80
+ writeAgain = true;
81
+ return;
82
+ }
83
+ writing = true;
84
+ do {
85
+ writeAgain = false;
86
+ try {
87
+ await state.write(key, entries);
88
+ } catch (err) {
89
+ logger?.warn?.(`Could not save the recent list "${key}"`, err);
90
+ }
91
+ } while (writeAgain);
92
+ writing = false;
93
+ }
94
+
95
+ /** A stored entry the list can hold: everything it goes through accepts it. */
96
+ const usable = (entry) => {
97
+ try {
98
+ if (!isValid(entry)) return false;
99
+ identity(entry);
100
+ groupOf(entry);
101
+ return true;
102
+ } catch (err) {
103
+ logger?.warn?.(`Dropped an unreadable entry of the recent list "${key}"`, err);
104
+ return false;
105
+ }
106
+ };
107
+
108
+ async function read() {
109
+ let stored;
110
+ try {
111
+ const saved = await state.read(key);
112
+ stored = Array.isArray(saved) ? capped(saved.filter(usable)) : [];
113
+ } catch (err) {
114
+ logger?.warn?.(`Could not read the recent list "${key}"; the stored list is left unchanged until it can be read`, err);
115
+ return false;
116
+ }
117
+ const replay = pending;
118
+ pending = [];
119
+ loaded = true;
120
+ entries = replay.reduce((list, apply) => apply(list), stored);
121
+ if (replay.length > 0) {
122
+ onChange?.();
123
+ void write();
124
+ }
125
+ return true;
126
+ }
127
+
128
+ /**
129
+ * Read the stored list. Call it once at startup, before anything lists; a
130
+ * change made while the list is unread calls it again. Once a read has
131
+ * succeeded it does not read again.
132
+ * @returns {Promise<boolean>} Whether the stored list has been read
133
+ */
134
+ function load() {
135
+ if (!state) return Promise.resolve(false);
136
+ if (loaded) return Promise.resolve(true);
137
+ reading ??= read().finally(() => { reading = null; });
138
+ return reading;
139
+ }
140
+
141
+ function change(apply) {
142
+ entries = apply(entries);
143
+ onChange?.();
144
+ if (loaded) {
145
+ void write();
146
+ return;
147
+ }
148
+ pending.push(apply);
149
+ void load();
150
+ }
151
+
152
+ return Object.freeze({
153
+ load,
154
+ /** @returns {ReadonlyArray<object>} Most recent first */
155
+ list: () => Object.freeze(entries.map((entry) => Object.freeze({ ...entry }))),
156
+ /** Put an entry at the top, dropping the older one with its identity. */
157
+ add(entry) {
158
+ const stamped = { ...entry, openedAt: Date.now() };
159
+ change((list) => capped([stamped, ...without(list, stamped)]));
160
+ },
161
+ /** Drop the entry with this one's identity. */
162
+ remove(entry) {
163
+ change((list) => without(list, entry));
164
+ },
165
+ clear() {
166
+ change(() => []);
167
+ },
168
+ });
169
+ }
@@ -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
+ }