flexui-runtime 0.0.0-stage → 2.0.0-alpha.2

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/README.md CHANGED
@@ -1,3 +1,71 @@
1
- # Temporary Holding Version
1
+ # @flexui/runtime
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Optional zero-dependency browser runtime for [FlexUI](https://github.com/Ahaduzzamankhan/flexui) components. The CSS works without it; this package adds keyboard behaviour, focus management, ARIA state and DOM events on top of native `<dialog>` and the popover API.
4
+
5
+ ```bash
6
+ npm install @flexui/runtime
7
+ ```
8
+
9
+ ```ts
10
+ import { init } from "@flexui/runtime";
11
+
12
+ const dispose = init();
13
+ ```
14
+
15
+ ## Features
16
+
17
+ - Dialogs and drawers: backdrop dismissal, Escape, scroll locking, focus trap and focus restoration.
18
+ - Dropdown menus: arrow/Home/End navigation, roving focus, outside dismissal.
19
+ - Popovers: native popover API with viewport-aware positioning and a fallback.
20
+ - Tabs: roving tabindex, automatic activation, horizontal/vertical orientation.
21
+ - Toasts: polite live region, four-toast cap, pause on hover/focus, sticky option.
22
+ - Command palette: Ctrl/Cmd+K, multi-term filtering, active descendant, events.
23
+ - Theme switching: light/dark/system, `localStorage`, `prefers-color-scheme`.
24
+ - Focus helpers: `focusable`, `focusFirst`, `trapFocus`.
25
+
26
+ ## Markup contracts
27
+
28
+ | Feature | Markup |
29
+ | --- | --- |
30
+ | Dialog | `<dialog class="fui-dialog" data-fui-dialog>` with `data-fui-open="#id"` / `data-fui-close` |
31
+ | Drawer | `<dialog class="fui-drawer" data-fui-drawer data-fui-side="right">` |
32
+ | Dropdown | `data-fui-dropdown="#menu"` + `role="menu"` items |
33
+ | Popover | `data-fui-popover="#panel"` + `popover` panel |
34
+ | Tabs | `data-fui-tabs` + `role="tablist"` / `tab` / `tabpanel` |
35
+ | Toast | `toast({ title, description, variant, duration })` |
36
+ | Command palette | `data-fui-command` + input/list/item attributes |
37
+ | Theme | `data-fui-theme-set="light\|dark\|system"` or `data-fui-theme-toggle` |
38
+
39
+ `init(root?)` returns a cleanup function and is safe to call once per page. Every feature is also exported from its own entry point:
40
+
41
+ ```ts
42
+ import { initDialogs } from "@flexui/runtime/dialog";
43
+ import { toast } from "@flexui/runtime/toast";
44
+ import { setTheme } from "@flexui/runtime/theme";
45
+ ```
46
+
47
+ ## Events
48
+
49
+ All events bubble and are cancelable.
50
+
51
+ | Event | Detail |
52
+ | --- | --- |
53
+ | `fui:open` / `fui:close` | `{ dialog, reason }` or `{ menu, trigger }` |
54
+ | `fui:select` | `{ item, menu, trigger }` |
55
+ | `fui:tabchange` | `{ tabs, tab, panel, index }` |
56
+ | `fui:popoveropen` / `fui:popoverclose` | `{ trigger, panel }` |
57
+ | `fui:toast` / `fui:toastdismiss` | `{ toast, variant }` |
58
+ | `fui:command` | `{ value, label, item, palette }` |
59
+ | `fui:themechange` | `{ mode, resolved }` |
60
+
61
+ ## Docs
62
+
63
+ The full guide lives in [docs/runtime.md](https://github.com/Ahaduzzamankhan/flexui/blob/main/docs/runtime.md).
64
+
65
+ ## Build
66
+
67
+ ```bash
68
+ bun run build:runtime
69
+ ```
70
+
71
+ Output is ESM plus declarations in `dist/`. MIT licensed.
package/dist/auto.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Zero-config entry point.
3
+ *
4
+ * Importing this module (for example `<script type="module" src=".../auto.js">`)
5
+ * initialises the runtime once the document has been parsed, and exposes the
6
+ * handle on `window.flexui` so inline scripts can drive it.
7
+ */
8
+ import { init, type InitOptions } from "./index.js";
9
+ import type { Cleanup } from "./types.js";
10
+ /** Initialises the runtime once; repeated calls return the same cleanup. */
11
+ export declare function start(options?: InitOptions): Cleanup;
12
+ /** Tears the runtime down and forgets the handle. */
13
+ export declare function stop(): void;
14
+ export { init };
15
+ export type { InitOptions };
package/dist/auto.js ADDED
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Zero-config entry point.
3
+ *
4
+ * Importing this module (for example `<script type="module" src=".../auto.js">`)
5
+ * initialises the runtime once the document has been parsed, and exposes the
6
+ * handle on `window.flexui` so inline scripts can drive it.
7
+ */
8
+ import { init } from "./index.js";
9
+ let dispose = null;
10
+ /** Initialises the runtime once; repeated calls return the same cleanup. */
11
+ export function start(options = {}) {
12
+ if (dispose) {
13
+ return dispose;
14
+ }
15
+ dispose = init(document, options);
16
+ return dispose;
17
+ }
18
+ /** Tears the runtime down and forgets the handle. */
19
+ export function stop() {
20
+ dispose?.();
21
+ dispose = null;
22
+ }
23
+ if (typeof window !== "undefined" && typeof document !== "undefined") {
24
+ const boot = () => {
25
+ start();
26
+ };
27
+ if (document.readyState === "loading") {
28
+ document.addEventListener("DOMContentLoaded", boot, { once: true });
29
+ }
30
+ else {
31
+ boot();
32
+ }
33
+ window.flexui = {
34
+ start,
35
+ stop,
36
+ init,
37
+ };
38
+ }
39
+ export { init };
@@ -0,0 +1,38 @@
1
+ import { type Cleanup } from "./types.js";
2
+ export interface CommandPaletteOptions {
3
+ /** Close the palette after a command is chosen. Defaults to true. */
4
+ closeOnSelect?: boolean;
5
+ }
6
+ /**
7
+ * Keyboard-first command palette over existing listbox markup.
8
+ *
9
+ * Item attributes: data-fui-command-item, data-value and optional
10
+ * data-keywords. Selection dispatches a bubbling fui:command event.
11
+ */
12
+ export declare class CommandPalette {
13
+ readonly element: HTMLElement;
14
+ private readonly input;
15
+ private readonly list;
16
+ private readonly empty;
17
+ private readonly dialog;
18
+ private readonly options;
19
+ private readonly disposer;
20
+ private entries;
21
+ private filtered;
22
+ private activeIndex;
23
+ constructor(element: HTMLElement, options?: CommandPaletteOptions);
24
+ get isOpen(): boolean;
25
+ /** Re-reads items from the DOM. Call after adding or removing commands. */
26
+ refresh(): void;
27
+ open(): void;
28
+ close(): void;
29
+ toggle(): void;
30
+ dispose(): void;
31
+ private reset;
32
+ private filter;
33
+ private setActive;
34
+ private handleKeydown;
35
+ private select;
36
+ }
37
+ /** Binds [data-fui-command] palettes, Ctrl/Cmd+K and command openers. */
38
+ export declare function initCommandPalettes(root?: ParentNode): Cleanup;
@@ -0,0 +1,270 @@
1
+ import { bindDialog, getDialog } from "./dialog.js";
2
+ import { closestFromEvent, createDisposer, emit, getElement, on, qsa, uid, } from "./types.js";
3
+ const controllers = new WeakMap();
4
+ const ITEM_SELECTOR = "[data-fui-command-item], [role='option']";
5
+ /**
6
+ * Keyboard-first command palette over existing listbox markup.
7
+ *
8
+ * Item attributes: data-fui-command-item, data-value and optional
9
+ * data-keywords. Selection dispatches a bubbling fui:command event.
10
+ */
11
+ export class CommandPalette {
12
+ element;
13
+ input;
14
+ list;
15
+ empty;
16
+ dialog;
17
+ options;
18
+ disposer;
19
+ entries = [];
20
+ filtered = [];
21
+ activeIndex = -1;
22
+ constructor(element, options = {}) {
23
+ this.element = element;
24
+ this.options = options;
25
+ this.disposer = createDisposer();
26
+ const input = element.querySelector("[data-fui-command-input], input[role='combobox'], input");
27
+ const list = element.querySelector("[data-fui-command-list], [role='listbox']");
28
+ if (!input || !list) {
29
+ throw new Error("@flexui/runtime: command palette needs an input and a list");
30
+ }
31
+ this.input = input;
32
+ this.list = list;
33
+ this.empty = element.querySelector("[data-fui-command-empty]");
34
+ this.dialog = element instanceof HTMLDialogElement ? (getDialog(element) ?? bindDialog(element)) : null;
35
+ if (!input.id) {
36
+ input.id = uid("fui-command-input");
37
+ }
38
+ if (!list.id) {
39
+ list.id = uid("fui-command-list");
40
+ }
41
+ input.setAttribute("role", "combobox");
42
+ input.setAttribute("aria-controls", list.id);
43
+ input.setAttribute("aria-expanded", "true");
44
+ input.setAttribute("aria-autocomplete", "list");
45
+ input.setAttribute("autocomplete", "off");
46
+ input.spellcheck = false;
47
+ list.setAttribute("role", "listbox");
48
+ if (!this.dialog) {
49
+ element.hidden = true;
50
+ }
51
+ this.disposer.add(on(input, "input", () => {
52
+ this.filter(input.value);
53
+ }));
54
+ this.disposer.add(on(input, "keydown", (event) => {
55
+ this.handleKeydown(event);
56
+ }));
57
+ this.disposer.add(on(list, "click", (event) => {
58
+ const mouse = event;
59
+ const item = closestFromEvent(mouse, ITEM_SELECTOR);
60
+ if (!item || !list.contains(item)) {
61
+ return;
62
+ }
63
+ mouse.preventDefault();
64
+ const index = this.filtered.findIndex((entry) => entry.element === item);
65
+ this.select(index);
66
+ }));
67
+ this.disposer.add(on(list, "pointermove", (event) => {
68
+ const item = closestFromEvent(event, ITEM_SELECTOR);
69
+ if (!item) {
70
+ return;
71
+ }
72
+ const index = this.filtered.findIndex((entry) => entry.element === item);
73
+ if (index >= 0 && index !== this.activeIndex) {
74
+ this.setActive(index, false);
75
+ }
76
+ }));
77
+ this.disposer.add(on(element, "close", () => {
78
+ this.reset();
79
+ }));
80
+ this.refresh();
81
+ }
82
+ get isOpen() {
83
+ return this.dialog ? this.dialog.isOpen : !this.element.hidden;
84
+ }
85
+ /** Re-reads items from the DOM. Call after adding or removing commands. */
86
+ refresh() {
87
+ this.entries = qsa(this.list, ITEM_SELECTOR).map((element) => {
88
+ if (!element.id) {
89
+ element.id = uid("fui-command-item");
90
+ }
91
+ element.setAttribute("role", "option");
92
+ element.tabIndex = -1;
93
+ const label = (element.getAttribute("data-label") ?? element.textContent ?? "").trim();
94
+ const keywords = element.getAttribute("data-keywords") ?? "";
95
+ const value = element.getAttribute("data-value") ?? label;
96
+ return {
97
+ element,
98
+ label,
99
+ value,
100
+ search: `${label} ${keywords} ${value}`.toLowerCase(),
101
+ };
102
+ });
103
+ this.filter(this.input.value);
104
+ }
105
+ open() {
106
+ if (this.dialog) {
107
+ this.dialog.open();
108
+ }
109
+ else {
110
+ this.element.hidden = false;
111
+ this.element.dataset["fuiState"] = "open";
112
+ }
113
+ this.filter(this.input.value);
114
+ this.input.focus({ preventScroll: true });
115
+ this.input.select();
116
+ emit(this.element, "fui:commandopen", { palette: this });
117
+ }
118
+ close() {
119
+ if (this.dialog) {
120
+ this.dialog.close("command");
121
+ }
122
+ else {
123
+ this.element.hidden = true;
124
+ delete this.element.dataset["fuiState"];
125
+ }
126
+ emit(this.element, "fui:commandclose", { palette: this });
127
+ }
128
+ toggle() {
129
+ if (this.isOpen) {
130
+ this.close();
131
+ }
132
+ else {
133
+ this.open();
134
+ }
135
+ }
136
+ dispose() {
137
+ if (this.dialog?.isOpen) {
138
+ this.dialog.close("dispose");
139
+ }
140
+ this.disposer.dispose();
141
+ controllers.delete(this.element);
142
+ }
143
+ reset() {
144
+ this.input.value = "";
145
+ this.filter("");
146
+ }
147
+ filter(query) {
148
+ const terms = query.toLowerCase().trim().split(/\s+/).filter(Boolean);
149
+ this.filtered = this.entries.filter((entry) => terms.every((term) => entry.search.includes(term)));
150
+ const visible = new Set(this.filtered.map((entry) => entry.element));
151
+ for (const entry of this.entries) {
152
+ entry.element.hidden = !visible.has(entry.element);
153
+ entry.element.setAttribute("aria-selected", "false");
154
+ }
155
+ if (this.empty) {
156
+ this.empty.hidden = this.filtered.length > 0;
157
+ }
158
+ this.setActive(this.filtered.length > 0 ? 0 : -1, false);
159
+ }
160
+ setActive(index, scroll) {
161
+ const previous = this.filtered[this.activeIndex];
162
+ previous?.element.setAttribute("aria-selected", "false");
163
+ this.activeIndex = index;
164
+ const entry = this.filtered[index];
165
+ if (!entry) {
166
+ this.input.removeAttribute("aria-activedescendant");
167
+ return;
168
+ }
169
+ entry.element.setAttribute("aria-selected", "true");
170
+ this.input.setAttribute("aria-activedescendant", entry.element.id);
171
+ if (scroll) {
172
+ entry.element.scrollIntoView({ block: "nearest" });
173
+ }
174
+ }
175
+ handleKeydown(event) {
176
+ switch (event.key) {
177
+ case "ArrowDown":
178
+ event.preventDefault();
179
+ if (this.filtered.length > 0) {
180
+ this.setActive((this.activeIndex + 1) % this.filtered.length, true);
181
+ }
182
+ break;
183
+ case "ArrowUp":
184
+ event.preventDefault();
185
+ if (this.filtered.length > 0) {
186
+ this.setActive(this.activeIndex <= 0 ? this.filtered.length - 1 : this.activeIndex - 1, true);
187
+ }
188
+ break;
189
+ case "Home":
190
+ event.preventDefault();
191
+ this.setActive(0, true);
192
+ break;
193
+ case "End":
194
+ event.preventDefault();
195
+ this.setActive(this.filtered.length - 1, true);
196
+ break;
197
+ case "Enter":
198
+ event.preventDefault();
199
+ this.select(this.activeIndex);
200
+ break;
201
+ case "Escape":
202
+ event.preventDefault();
203
+ this.close();
204
+ break;
205
+ default:
206
+ break;
207
+ }
208
+ }
209
+ select(index) {
210
+ const entry = this.filtered[index];
211
+ if (!entry) {
212
+ return;
213
+ }
214
+ if (this.options.closeOnSelect !== false) {
215
+ this.close();
216
+ }
217
+ emit(entry.element, "fui:command", {
218
+ value: entry.value,
219
+ label: entry.label,
220
+ item: entry.element,
221
+ palette: this,
222
+ });
223
+ }
224
+ }
225
+ /** Binds [data-fui-command] palettes, Ctrl/Cmd+K and command openers. */
226
+ export function initCommandPalettes(root = document) {
227
+ if (typeof document === "undefined") {
228
+ return () => undefined;
229
+ }
230
+ const disposer = createDisposer();
231
+ const palettes = [];
232
+ for (const element of qsa(root, "[data-fui-command]")) {
233
+ if (controllers.has(element)) {
234
+ continue;
235
+ }
236
+ try {
237
+ const controller = new CommandPalette(element);
238
+ controllers.set(element, controller);
239
+ disposer.add(() => controller.dispose());
240
+ palettes.push(controller);
241
+ }
242
+ catch {
243
+ // Misconfigured palettes are ignored rather than breaking the page.
244
+ }
245
+ }
246
+ if (palettes.length === 0) {
247
+ return () => disposer.dispose();
248
+ }
249
+ disposer.add(on(document, "keydown", (event) => {
250
+ const keyboard = event;
251
+ if ((keyboard.metaKey || keyboard.ctrlKey) &&
252
+ !keyboard.altKey &&
253
+ keyboard.key.toLowerCase() === "k") {
254
+ keyboard.preventDefault();
255
+ palettes[0]?.toggle();
256
+ }
257
+ }));
258
+ disposer.add(on(document, "click", (event) => {
259
+ const opener = closestFromEvent(event, "[data-fui-command-open]");
260
+ if (!opener) {
261
+ return;
262
+ }
263
+ event.preventDefault();
264
+ const value = opener.getAttribute("data-fui-command-open");
265
+ const target = getElement(value);
266
+ const palette = target ? controllers.get(target) : palettes[0];
267
+ palette?.open();
268
+ }));
269
+ return () => disposer.dispose();
270
+ }
@@ -0,0 +1,44 @@
1
+ import { type Cleanup } from "./types.js";
2
+ export interface DialogOptions {
3
+ /** Close when the backdrop is clicked. Defaults to true. */
4
+ closeOnBackdrop?: boolean;
5
+ /** Return focus to the opener when the dialog closes. Defaults to true. */
6
+ restoreFocus?: boolean;
7
+ onOpen?: (dialog: HTMLDialogElement) => void;
8
+ onClose?: (dialog: HTMLDialogElement, reason: string) => void;
9
+ }
10
+ /**
11
+ * Accessible controller for a native <dialog>.
12
+ *
13
+ * showModal() supplies the top layer and inert background. This class adds
14
+ * backdrop dismissal, scroll locking, focus restoration and DOM events.
15
+ */
16
+ export declare class Dialog {
17
+ readonly element: HTMLDialogElement;
18
+ private readonly options;
19
+ private readonly disposer;
20
+ private lastFocus;
21
+ private openState;
22
+ private pendingReason;
23
+ private releaseTrap;
24
+ constructor(element: HTMLDialogElement, options?: DialogOptions);
25
+ get isOpen(): boolean;
26
+ open(): void;
27
+ close(reason?: string): void;
28
+ dispose(): void;
29
+ private adoptOpen;
30
+ private markOpen;
31
+ private handleClosed;
32
+ private handleClick;
33
+ }
34
+ /** Returns an existing controller, if one was bound. */
35
+ export declare function getDialog(element: HTMLDialogElement): Dialog | undefined;
36
+ /** Creates or reuses the controller for a dialog element. */
37
+ export declare function bindDialog(element: HTMLDialogElement, options?: DialogOptions): Dialog;
38
+ /**
39
+ * Delegated open/close listeners for data-fui-open and data-fui-close.
40
+ * This is exported so custom overlays can share the same trigger protocol.
41
+ */
42
+ export declare function bindOverlayTriggers(): Cleanup;
43
+ /** Binds every dialog/drawer under root and the shared trigger delegation. */
44
+ export declare function initDialogs(root?: ParentNode): Cleanup;