fablecut 1.18.0 → 1.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/select-menu.js ADDED
@@ -0,0 +1,295 @@
1
+ /* FableCut select menus — every <select> in the editor opens a list drawn in
2
+ the editor's theme instead of the browser's native popup (which ignores the
3
+ dark theme and differs per OS).
4
+
5
+ The <select> stays in the page and stays the source of truth: code that
6
+ builds options, reads .value or listens for input / change works unchanged,
7
+ including selects rebuilt with innerHTML (one set of listeners on window
8
+ serves them all). Opening one with the mouse does not focus it, so Space
9
+ still plays the timeline after a pick.
10
+
11
+ Keyboard: on a focused select, Space / Enter / ↑ / ↓ / Alt+↓ / F4 open the
12
+ list. In the list ↑ ↓ Home End PageUp PageDown move, typing jumps to the
13
+ next match, Enter / Space pick, Esc closes, Tab closes and moves on.
14
+ Optgroups show as headings; disabled and hidden options are respected.
15
+ <select multiple>, <select size="n"> and <select data-native> keep the
16
+ browser's own control.
17
+
18
+ Loaded by the editor as a plain script (global `FableCutSelect`, installed
19
+ on load) and required by the tests. */
20
+ (function (root, factory) {
21
+ const api = factory();
22
+ if (typeof module === "object" && module.exports) module.exports = api;
23
+ else {
24
+ root.FableCutSelect = api;
25
+ if (typeof document !== "undefined") api.install(root, document);
26
+ }
27
+ })(typeof self !== "undefined" ? self : this, function () {
28
+ "use strict";
29
+
30
+ const MAX_H = 340; // px, the list's tallest
31
+ const PAGE = 8; // items a PageUp / PageDown moves
32
+
33
+ /** Selects that get the themed list. */
34
+ /** True when `option` can still be picked from `sel`: the select is connected and enabled, and the
35
+ option still belongs to it and isn't disabled itself or by its group (code may have changed any of
36
+ these while the list was open). */
37
+ function canPick(sel, option) {
38
+ if (!sel || !option || !sel.isConnected || sel.disabled) return false;
39
+ if (!Array.prototype.includes.call(sel.options, option)) return false;
40
+ return !(option.disabled || (option.parentNode && option.parentNode.tagName === "OPTGROUP" && option.parentNode.disabled));
41
+ }
42
+
43
+ function isThemed(sel) {
44
+ if (!sel || sel.tagName !== "SELECT" || sel.multiple || sel.hasAttribute("data-native")) return false;
45
+ // the attribute as the CSS reads it (no size, or size="1"), so the box and the list always agree
46
+ const size = sel.getAttribute("size");
47
+ return size === null || size === "1";
48
+ }
49
+ /** An option's label as shown in the list (its label, else its text), whitespace collapsed. */
50
+ function optionText(o) {
51
+ return String(o.label || o.textContent || "").replace(/\s+/g, " ").trim();
52
+ }
53
+ /** The select's rows in order: { group } headings and { option } entries (hidden options dropped). */
54
+ function rows(sel) {
55
+ const out = [];
56
+ for (const child of sel.children) {
57
+ if (child.tagName === "OPTGROUP") {
58
+ if (child.hidden) continue;
59
+ out.push({ group: child.label || "", disabled: !!child.disabled });
60
+ for (const o of child.children)
61
+ if (o.tagName === "OPTION" && !o.hidden) out.push({ option: o, inGroup: true, disabled: !!(o.disabled || child.disabled) });
62
+ } else if (child.tagName === "OPTION" && !child.hidden) out.push({ option: child, inGroup: false, disabled: !!child.disabled });
63
+ }
64
+ return out;
65
+ }
66
+ /** Index of the next enabled item from `from` going `dir` (±1); `from` when there is none. */
67
+ function step(items, from, dir) {
68
+ for (let i = from + dir; i >= 0 && i < items.length; i += dir) if (!items[i].disabled) return i;
69
+ return from;
70
+ }
71
+ /** PageUp / PageDown: `n` items on in direction `dir`, landing on an enabled one
72
+ (the next one on, else the nearest one back); `from` when there is none. */
73
+ function pageStep(items, from, dir, n) {
74
+ const i = Math.max(0, Math.min(items.length - 1, from + dir * n));
75
+ if (!items[i] || !items[i].disabled) return i;
76
+ const on = step(items, i, dir);
77
+ if (on !== i) return on;
78
+ const back = step(items, i, -dir);
79
+ return back !== i ? back : from;
80
+ }
81
+ /** Type-to-find: the first enabled item from `start` (wrapping) whose text starts with `q`; -1 if none. */
82
+ function findMatch(items, start, q) {
83
+ q = q.toLowerCase();
84
+ const n = items.length;
85
+ for (let k = 0; k < n; k++) {
86
+ const i = (((start + k) % n) + n) % n;
87
+ if (!items[i].disabled && optionText(items[i].option).toLowerCase().startsWith(q)) return i;
88
+ }
89
+ return -1;
90
+ }
91
+ /** Where the list goes: under the select, or above it when there is more room there. */
92
+ function placement(rect, viewH, listH, pad = 6) {
93
+ const below = viewH - rect.bottom - pad, above = rect.top - pad;
94
+ const down = below >= Math.min(listH, 200) || below >= above;
95
+ const maxH = Math.min(MAX_H, Math.max(80, down ? below : above));
96
+ const h = Math.min(listH, maxH);
97
+ return { down, maxH, top: down ? rect.bottom + 2 : Math.max(pad, rect.top - 2 - h) };
98
+ }
99
+
100
+ /** Wire the themed lists to every <select> on the page through listeners on `win` (once). */
101
+ function install(win, doc) {
102
+ if (install.done) return;
103
+ install.done = true;
104
+ let open = null; // { sel, list, items, active, byKey }
105
+ let typed = "", typedAt = 0;
106
+ let lists = 0; // numbers the lists of selects with no id, so aria-controls always has a target
107
+
108
+ /** Build the list element for `sel`: group headings and one row per visible option. Returns { list, items }. */
109
+ function draw(sel) {
110
+ const list = doc.createElement("div");
111
+ list.className = "fc-select-list";
112
+ list.setAttribute("role", "listbox");
113
+ list.id = (sel.id || "fc-select-" + ++lists) + "-list";
114
+ const items = [];
115
+ for (const r of rows(sel)) {
116
+ const d = doc.createElement("div");
117
+ if (r.group !== undefined) {
118
+ d.className = "fc-select-group";
119
+ d.textContent = r.group;
120
+ } else {
121
+ const o = r.option;
122
+ d.className = "fc-select-opt" + (r.inGroup ? " in-group" : "") + (r.disabled ? " disabled" : "") + (o.selected ? " selected" : "");
123
+ d.setAttribute("role", "option");
124
+ d.setAttribute("aria-selected", String(o.selected));
125
+ if (r.disabled) d.setAttribute("aria-disabled", "true");
126
+ d.textContent = optionText(o) || "\u00a0";
127
+ // long names (two takes that differ only at the end) show whole on hover
128
+ d.title = o.title || optionText(o);
129
+ if (sel.dataset.k === "font" && o.value) d.style.fontFamily = `"${o.value}", system-ui, sans-serif`; // preview each font
130
+ d.dataset.i = items.length;
131
+ items.push({ el: d, option: o, disabled: r.disabled });
132
+ }
133
+ list.appendChild(d);
134
+ }
135
+ if (!items.length) {
136
+ const d = doc.createElement("div");
137
+ d.className = "fc-select-empty";
138
+ d.textContent = "No options";
139
+ list.appendChild(d);
140
+ }
141
+ return { list, items };
142
+ }
143
+ /** Size and position the open list beside its select, above it when there's more room there. */
144
+ function place() {
145
+ const { sel, list } = open;
146
+ const r = sel.getBoundingClientRect(), pad = 6;
147
+ list.style.minWidth = Math.max(r.width, 120) + "px";
148
+ list.style.maxWidth = Math.max(r.width, Math.min(480, win.innerWidth - pad * 2)) + "px";
149
+ const p = placement(r, win.innerHeight, list.scrollHeight, pad);
150
+ list.style.maxHeight = p.maxH + "px";
151
+ list.style.left = Math.max(pad, Math.min(r.left, win.innerWidth - list.offsetWidth - pad)) + "px";
152
+ list.style.top = p.top + "px";
153
+ list.classList.toggle("up", !p.down);
154
+ }
155
+ /** Highlight item `i` (clamped) as the keyboard's current row and point aria-activedescendant at it. */
156
+ function activate(i, scroll = true) {
157
+ if (!open || !open.items.length) return;
158
+ i = Math.max(0, Math.min(open.items.length - 1, i));
159
+ if (open.items[open.active]) open.items[open.active].el.classList.remove("active");
160
+ open.active = i;
161
+ const el = open.items[i].el;
162
+ el.classList.add("active");
163
+ if (el.id === "") el.id = open.list.id + "-" + i;
164
+ open.sel.setAttribute("aria-activedescendant", el.id);
165
+ if (scroll) el.scrollIntoView({ block: "nearest" });
166
+ }
167
+ /** Open the list for `sel` (a second open on the same select closes it). `byKey`: opened from the keyboard. */
168
+ function show(sel, byKey) {
169
+ const again = open && open.sel === sel;
170
+ close();
171
+ if (again || sel.disabled || !sel.isConnected) return;
172
+ const { list, items } = draw(sel);
173
+ doc.body.appendChild(list);
174
+ // the select taken out of the page (the Inspector rebuilt by an undo, say): the list goes with it
175
+ const gone = new MutationObserver(() => { if (open && !open.sel.isConnected) close(); });
176
+ gone.observe(doc.body, { childList: true, subtree: true });
177
+ open = { sel, list, items, active: -1, byKey, gone };
178
+ sel.classList.add("fc-open");
179
+ sel.setAttribute("aria-expanded", "true");
180
+ sel.setAttribute("aria-controls", list.id);
181
+ place();
182
+ const cur = items.findIndex((x) => x.option.selected);
183
+ activate(cur >= 0 ? cur : step(items, -1, 1));
184
+ list.addEventListener("mousemove", (e) => {
185
+ const d = e.target.closest(".fc-select-opt");
186
+ if (d && !d.classList.contains("disabled")) activate(+d.dataset.i, false);
187
+ });
188
+ list.addEventListener("click", (e) => {
189
+ const d = e.target.closest(".fc-select-opt");
190
+ if (d && !d.classList.contains("disabled")) pick(+d.dataset.i, true);
191
+ });
192
+ }
193
+ /** Close the open list, if any, and reset its select's open state. */
194
+ function close() {
195
+ if (!open) return;
196
+ const { sel, list, gone } = open;
197
+ open = null;
198
+ gone.disconnect();
199
+ typed = ""; typedAt = 0; // type-to-find starts afresh in the next list
200
+ list.remove();
201
+ sel.classList.remove("fc-open");
202
+ sel.setAttribute("aria-expanded", "false");
203
+ sel.removeAttribute("aria-activedescendant");
204
+ }
205
+ /** Choose item `i`: select its option, fire input + change when it changed, then close the list. */
206
+ function pick(i, byMouse) {
207
+ if (!open) return;
208
+ const { sel, items } = open;
209
+ const it = items[i];
210
+ close();
211
+ // re-checked now: code may have disabled, removed or rebuilt things while the list was open
212
+ if (!it || it.disabled || !canPick(sel, it.option)) return;
213
+ if (!it.option.selected) {
214
+ // a mouse pick never focused the select, as a native one would have: send its focus event, so
215
+ // code that acts on focus (the Inspector's undo step before an edit) still runs. Focus doesn't move.
216
+ if (doc.activeElement !== sel) sel.dispatchEvent(new FocusEvent("focus"));
217
+ it.option.selected = true;
218
+ sel.dispatchEvent(new Event("input", { bubbles: true }));
219
+ sel.dispatchEvent(new Event("change", { bubbles: true }));
220
+ }
221
+ // a keyboard pick keeps focus on the select (Space / ↓ reopen it). A mouse pick from a list the
222
+ // keyboard opened hands focus back, as every mouse pick does, so Space and Ctrl+Z reach the editor
223
+ if (byMouse && doc.activeElement === sel && win.FableCutFocus) win.FableCutFocus.release(sel);
224
+ }
225
+
226
+ // Mouse: open the list without focusing the select (and without the native popup).
227
+ win.addEventListener("mousedown", (e) => {
228
+ if (open && open.list.contains(e.target)) { e.preventDefault(); return; } // keep focus where it is while picking
229
+ const sel = e.target.closest && e.target.closest("select");
230
+ if (e.button !== 0 || !isThemed(sel)) { close(); return; }
231
+ e.preventDefault();
232
+ // preventDefault keeps focus where it was: a text field typed into
233
+ // before, or a button reached with Tab, would keep it, and take Space after the pick
234
+ const prev = doc.activeElement;
235
+ const typing = !!prev && (prev.tagName === "INPUT" || prev.tagName === "TEXTAREA" || prev.isContentEditable);
236
+ const control = !!prev && !!win.FableCutFocus && win.FableCutFocus.isClickControl(prev);
237
+ const inDialog = !!(sel.closest && sel.closest(".overlay, .ctx-menu, [role=dialog]"));
238
+ if ((typing || control) && prev !== sel && !inDialog) prev.blur();
239
+ show(sel, false);
240
+ }, true);
241
+ // A pick inside the list is not a click outside an open popover (those close on pointerdown).
242
+ win.addEventListener("pointerdown", (e) => {
243
+ if (open && open.list.contains(e.target)) e.stopPropagation();
244
+ }, true);
245
+ win.addEventListener("keydown", (e) => {
246
+ if (open && !open.sel.isConnected) close(); // its select is gone: the key isn't the list's
247
+ if (open) {
248
+ const k = e.key, items = open.items;
249
+ // one held key mustn't open the list and then pick from it: repeats of Enter / Space do nothing here
250
+ if (e.repeat && (k === "Enter" || k === " ")) { e.preventDefault(); e.stopImmediatePropagation(); return; }
251
+ let used = true;
252
+ if (k === "Escape") close(); // only the list: not the dialog behind it
253
+ else if (k === "Tab") { close(); used = false; }
254
+ else if (k === "ArrowDown") activate(step(items, open.active, 1));
255
+ else if (k === "ArrowUp") activate(step(items, open.active, -1));
256
+ else if (k === "Home") activate(step(items, -1, 1));
257
+ else if (k === "End") activate(step(items, items.length, -1));
258
+ else if (k === "PageDown") activate(pageStep(items, open.active, 1, PAGE));
259
+ else if (k === "PageUp") activate(pageStep(items, open.active, -1, PAGE));
260
+ else if (k === "Enter" || (k === " " && Date.now() - typedAt > 700)) pick(open.active);
261
+ else if (k.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey) {
262
+ const now = Date.now();
263
+ typed = now - typedAt > 700 ? k : typed + k;
264
+ typedAt = now;
265
+ const i = findMatch(items, typed.length > 1 ? open.active : open.active + 1, typed);
266
+ if (i >= 0) activate(i);
267
+ } else used = !(e.ctrlKey || e.metaKey); // browser chords pass; other keys stop here
268
+ if (used) { e.preventDefault(); e.stopImmediatePropagation(); }
269
+ return;
270
+ }
271
+ const sel = e.target;
272
+ if (!isThemed(sel) || sel.disabled || e.ctrlKey || e.metaKey) return;
273
+ // focus.js may have just let go of it (an arrow after a mouse-opened list closed): the key is the editor's
274
+ if (doc.activeElement !== sel) return;
275
+ const k = e.key;
276
+ // a select still focused from a mouse click (its list closed without a pick): Space plays (focus.js)
277
+ if (k === " " && win.FableCutFocus && win.FableCutFocus.spaceShouldPlay(sel)) return;
278
+ if (k === " " || k === "Enter" || k === "ArrowDown" || k === "ArrowUp" || k === "F4") {
279
+ e.preventDefault(); e.stopImmediatePropagation();
280
+ // the key held from the pick that just closed the list: don't open it again
281
+ if (e.repeat && (k === " " || k === "Enter")) return;
282
+ show(sel, true);
283
+ }
284
+ }, true);
285
+ const outside = (e) => { if (open && !open.list.contains(e.target)) close(); };
286
+ win.addEventListener("scroll", outside, true);
287
+ win.addEventListener("wheel", outside, { capture: true, passive: true });
288
+ win.addEventListener("resize", () => { if (open) open.sel.isConnected ? place() : close(); });
289
+ win.addEventListener("blur", close);
290
+ // focus moved somewhere else (code focusing a text field, say): the list mustn't keep the keys
291
+ doc.addEventListener("focusin", (e) => { if (open && e.target !== open.sel && !open.list.contains(e.target)) close(); }, true);
292
+ }
293
+
294
+ return { isThemed, canPick, optionText, rows, step, pageStep, findMatch, placement, install };
295
+ });