@seip/bluebird-js 0.1.4 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,775 +1,775 @@
1
- /**
2
- * Bluebird Client Runtime.
3
- * Provides client-side SPA routing with View Transitions,
4
- * persistent element state, selective React Islands hydration,
5
- * and a lightweight global event bus.
6
- */
7
- (() => {
8
- if (typeof window === "undefined" || window.Bluebird) return;
9
-
10
- /**
11
- * Global Island component registry.
12
- * Components register themselves here via `window.__BLUEBIRD_ISLANDS__[name] = Component`.
13
- * @type {Record<string, any>}
14
- */
15
- window.__BLUEBIRD_ISLANDS__ = window.__BLUEBIRD_ISLANDS__ || {};
16
-
17
- /**
18
- * Global Island root mounter/renderer function supplied by the React bundle.
19
- * @type {Function|null}
20
- */
21
- window.__BLUEBIRD_MOUNT__ = window.__BLUEBIRD_MOUNT__ || null;
22
-
23
- /**
24
- * Map of mounted roots to DOM container elements.
25
- * @type {Map<HTMLElement, {unmount: Function, persist: boolean, name: string}>}
26
- */
27
- const mountedRoots = new Map();
28
-
29
- /**
30
- * Map of prefetched HTML entries by URL with TTL expiration.
31
- * @type {Map<string, {html: string, expiry: number}>}
32
- */
33
- const prefetchCache = new Map();
34
- const PREFETCH_TTL_MS = 30000;
35
- const PREFETCH_MAX_ENTRIES = 50;
36
-
37
- /**
38
- * Retrieves a valid prefetched HTML string from cache if not expired.
39
- * @param {string} url
40
- * @returns {string|null}
41
- */
42
- function getPrefetchedHtml(url) {
43
- const entry = prefetchCache.get(url);
44
- if (!entry) return null;
45
- if (entry.expiry <= Date.now()) {
46
- prefetchCache.delete(url);
47
- return null;
48
- }
49
- return entry.html;
50
- }
51
-
52
- /**
53
- * Stores a prefetched HTML string with TTL and LRU cap.
54
- * @param {string} url
55
- * @param {string} html
56
- */
57
- function setPrefetchedHtml(url, html) {
58
- if (prefetchCache.size >= PREFETCH_MAX_ENTRIES) {
59
- const oldestKey = prefetchCache.keys().next().value;
60
- if (oldestKey !== undefined) prefetchCache.delete(oldestKey);
61
- }
62
- prefetchCache.set(url, { html, expiry: Date.now() + PREFETCH_TTL_MS });
63
- }
64
-
65
- /**
66
- * Event listeners storage for the Bluebird Event Bus.
67
- * @type {Map<string, Set<Function>>}
68
- */
69
- const eventListeners = new Map();
70
-
71
- /**
72
- * In-memory key-value reactive store.
73
- * @type {Map<string, any>}
74
- */
75
- const storeState = new Map();
76
-
77
- /**
78
- * Reactive store change listeners.
79
- * @type {Map<string, Set<Function>>}
80
- */
81
- const storeListeners = new Map();
82
-
83
- /**
84
- * Bluebird global API object.
85
- */
86
- const Bluebird = {
87
- /**
88
- * Emits an event through the client event bus.
89
- * @param {string} event - Event identifier.
90
- * @param {any} [data] - Event payload.
91
- */
92
- emit(event, data) {
93
- const callbacks = eventListeners.get(event);
94
- if (callbacks) {
95
- for (const cb of callbacks) {
96
- try {
97
- cb(data);
98
- } catch (err) {
99
- console.error(`[BLUEBIRD EVENT ERROR] Error in listener for "${event}":`, err);
100
- }
101
- }
102
- }
103
- },
104
-
105
- /**
106
- * Subscribes to an event on the client event bus.
107
- * @param {string} event - Event identifier.
108
- * @param {Function} callback - Event listener callback.
109
- * @returns {Function} Unsubscribe function.
110
- */
111
- on(event, callback) {
112
- if (!eventListeners.has(event)) {
113
- eventListeners.set(event, new Set());
114
- }
115
- eventListeners.get(event).add(callback);
116
- return () => eventListeners.get(event)?.delete(callback);
117
- },
118
-
119
- /**
120
- * Unsubscribes a callback from the client event bus.
121
- * @param {string} event - Event identifier.
122
- * @param {Function} callback - Registered callback.
123
- */
124
- off(event, callback) {
125
- eventListeners.get(event)?.delete(callback);
126
- },
127
-
128
- /**
129
- * Gets or sets a reactive store value.
130
- * @param {string} key - Store key.
131
- * @param {any} [value] - Optional new value.
132
- * @returns {any} Current store value.
133
- */
134
- store(key, value) {
135
- if (arguments.length > 1) {
136
- storeState.set(key, value);
137
- const listeners = storeListeners.get(key);
138
- if (listeners) {
139
- for (const cb of listeners) {
140
- try {
141
- cb(value);
142
- } catch (err) {
143
- console.error(`[BLUEBIRD STORE ERROR] Error in listener for "${key}":`, err);
144
- }
145
- }
146
- }
147
- }
148
- return storeState.get(key);
149
- },
150
-
151
- /**
152
- * Subscribes to reactive store changes.
153
- * @param {string} key - Store key.
154
- * @param {Function} callback - Change handler receiving new value.
155
- * @returns {Function} Unsubscribe function.
156
- */
157
- subscribe(key, callback) {
158
- if (!storeListeners.has(key)) {
159
- storeListeners.set(key, new Set());
160
- }
161
- storeListeners.get(key).add(callback);
162
- return () => storeListeners.get(key)?.delete(callback);
163
- },
164
-
165
- /**
166
- * Clears the internal link prefetch cache.
167
- */
168
- clearPrefetch() {
169
- prefetchCache.clear();
170
- },
171
-
172
- /**
173
- * Registers a callback executed both on initial page load and after every SPA transition.
174
- * Replaces DOMContentLoaded for Vanilla JavaScript components, sliders, and event listeners.
175
- * @param {Function} callback - Function receiving { url, initial }.
176
- * @returns {Function} Unsubscribe function.
177
- */
178
- onPageLoad(callback) {
179
- if (typeof callback !== "function") return () => {};
180
- const handler = (e) => callback(e.detail || { url: window.location.href, initial: false });
181
- window.addEventListener("bluebird:page-load", handler);
182
- if (document.readyState !== "loading") {
183
- try {
184
- callback({ url: window.location.href, initial: true });
185
- } catch (err) {
186
- console.error("[BLUEBIRD ON_PAGE_LOAD ERROR]:", err);
187
- }
188
- }
189
- return () => window.removeEventListener("bluebird:page-load", handler);
190
- },
191
-
192
- /**
193
- * Hydrates and mounts all [data-island] elements inside a container.
194
- * @param {HTMLElement|Document} [container=document] - Target root DOM container.
195
- */
196
- hydrate(container = document) {
197
-
198
- const islands = container.querySelectorAll("[data-island]");
199
- for (const el of islands) {
200
- if (el.__bluebird_mounted__) continue;
201
-
202
- const name = el.getAttribute("data-island");
203
- const isPersist = el.getAttribute("data-persist") === "true";
204
- let props = {};
205
-
206
- try {
207
- const rawProps = el.getAttribute("data-props");
208
- if (rawProps) props = JSON.parse(rawProps);
209
- } catch (err) {
210
- console.warn(`[BLUEBIRD ISLAND] Failed to parse props for island "${name}":`, err);
211
- }
212
-
213
- const component = window.__BLUEBIRD_ISLANDS__[name];
214
- if (component && typeof window.__BLUEBIRD_MOUNT__ === "function") {
215
- try {
216
- const isHydrateMode = el.getAttribute("data-hydrate") === "true";
217
- const unmountFn = window.__BLUEBIRD_MOUNT__(el, component, props, isHydrateMode);
218
- el.__bluebird_mounted__ = true;
219
- mountedRoots.set(el, {
220
- unmount: unmountFn,
221
- persist: isPersist,
222
- name,
223
- });
224
- } catch (err) {
225
- console.error(`[BLUEBIRD ISLAND] Error mounting island "${name}":`, err);
226
- }
227
- }
228
- }
229
- },
230
-
231
- /**
232
- * Cleanly unmounts non-persistent mounted islands inside a specific container (or entire document).
233
- * @param {HTMLElement|Document} [container=document]
234
- */
235
- unmountNonPersistent(container = document) {
236
- for (const [el, item] of mountedRoots.entries()) {
237
- if (item.persist) continue;
238
- if (container !== document && !container.contains(el)) continue;
239
- try {
240
- if (typeof item.unmount === "function") {
241
- item.unmount();
242
- }
243
- } catch {}
244
- el.__bluebird_mounted__ = false;
245
- mountedRoots.delete(el);
246
- }
247
- },
248
-
249
- /**
250
- * Fetches an HTML partial from the server and swaps it into a target DOM selector.
251
- * Automatically handles authentication redirects by falling back to full SPA navigation.
252
- * @param {string} url - Endpoint returning a rendered partial or view.
253
- * @param {string|HTMLElement} target - CSS selector or DOM element to update.
254
- * @param {Object} [options={}] - Swap options.
255
- * @param {boolean} [options.transition=false] - Wrap swap in View Transition.
256
- * @param {boolean} [options.pushUrl=false] - Push URL to browser history.
257
- * @returns {Promise<boolean>}
258
- */
259
- async renderPartial(url, target, options = {}) {
260
- const targetEl = typeof target === "string" ? document.querySelector(target) : target;
261
- if (!targetEl) return false;
262
-
263
- try {
264
- const res = await fetch(url, {
265
- headers: {
266
- "X-Bluebird-Client-Router": "1",
267
- "X-Bluebird-Partial": "1",
268
- },
269
- credentials: "include",
270
- });
271
-
272
- if (!res.ok) return false;
273
-
274
- if (res.redirected && res.url && res.headers.get("X-Bluebird-Partial") !== "1") {
275
- await Bluebird.navigate(res.url);
276
- return true;
277
- }
278
-
279
- const html = await res.text();
280
- const applyPartial = () => {
281
- Bluebird.unmountNonPersistent(targetEl);
282
- targetEl.innerHTML = html;
283
- executeScripts(targetEl);
284
- Bluebird.hydrate(targetEl);
285
- if (options.pushUrl) {
286
- window.history.pushState({}, "", url);
287
- }
288
- window.dispatchEvent(
289
- new CustomEvent("bluebird:partial-load", { detail: { url, target: targetEl } })
290
- );
291
- };
292
-
293
- if (options.transition && document.startViewTransition) {
294
- await document.startViewTransition(applyPartial).finished;
295
- } else {
296
- applyPartial();
297
- }
298
- return true;
299
- } catch {
300
- return false;
301
- }
302
- },
303
-
304
- /**
305
- * Performs client-side navigation to a target URL.
306
- * @param {string} url - Target URL path.
307
- * @param {Object} [options={}] - Navigation options.
308
- * @param {boolean} [options.replace=false] - Use history.replaceState instead of pushState.
309
- * @param {boolean} [options.scroll=true] - Scroll to top on navigation.
310
- */
311
- async navigate(url, options = {}) {
312
- try {
313
- let html = getPrefetchedHtml(url);
314
- let targetUrl = url;
315
- if (!html) {
316
- const res = await fetch(url, {
317
- headers: { "X-Bluebird-Client-Router": "1" },
318
- credentials: "include",
319
- });
320
- if (!res.ok) {
321
- window.location.href = url;
322
- return;
323
- }
324
- if (res.redirected && res.url) {
325
- try {
326
- const parsed = new URL(res.url);
327
- targetUrl = parsed.pathname + parsed.search;
328
- } catch {}
329
- }
330
- html = await res.text();
331
- } else {
332
- prefetchCache.delete(url);
333
- }
334
-
335
- const parser = new DOMParser();
336
- const nextDoc = parser.parseFromString(html, "text/html");
337
-
338
- if (document.startViewTransition) {
339
- await document.startViewTransition(() => {
340
- swapDocument(nextDoc, targetUrl, options);
341
- }).finished;
342
- } else {
343
- swapDocument(nextDoc, targetUrl, options);
344
- }
345
- } catch {
346
- window.location.href = url;
347
- }
348
- },
349
-
350
- /**
351
- * Reads the active CSRF token from the `_csrf` cookie, hidden input, or meta tag.
352
- * @returns {string}
353
- */
354
- getCsrfToken() {
355
- const match = document.cookie.match(/(?:^|;\s*)_csrf=([^;]*)/);
356
- if (match && match[1]) {
357
- try {
358
- return decodeURIComponent(match[1]);
359
- } catch {
360
- return match[1];
361
- }
362
- }
363
- const csrfEl =
364
- document.getElementById("csrf") ||
365
- document.querySelector('input[name="_csrf"]') ||
366
- document.querySelector('meta[name="csrf-token"]');
367
- return csrfEl ? csrfEl.value || csrfEl.getAttribute("content") || "" : "";
368
- },
369
-
370
- /**
371
- * Invokes a Server Action exported by the current (or target) view module (`export const actions = { ... }`).
372
- * Automatically attaches the signed CSRF token, enforces JSON payload serialization,
373
- * and optionally swaps the returned partial HTML into the page outlet or target selector.
374
- *
375
- * @param {string} actionName - Name of the exported server action.
376
- * @param {Object} [payload={}] - Data payload sent to the server action.
377
- * @param {Object} [options={}] - Execution options.
378
- * @param {string} [options.url] - Target route URL (defaults to `window.location.pathname`).
379
- * @param {boolean|string} [options.partial=false] - If true or a CSS selector, requests a partial re-render and updates the DOM.
380
- * @returns {Promise<any>}
381
- */
382
- async action(actionName, payload = {}, options = {}) {
383
- const targetUrl = options.url || window.location.pathname;
384
- const csrfToken = Bluebird.getCsrfToken();
385
- const wantsPartial = Boolean(options.partial);
386
-
387
- const headers = {
388
- "Content-Type": "application/json",
389
- "X-Requested-With": "XMLHttpRequest",
390
- "X-Bluebird-Client-Router": "1",
391
- "X-Bluebird-Action": String(actionName),
392
- };
393
- if (csrfToken) {
394
- headers["X-CSRF-Token"] = csrfToken;
395
- }
396
- if (wantsPartial) {
397
- headers["X-Bluebird-Partial"] = "1";
398
- }
399
-
400
- const res = await fetch(targetUrl, {
401
- method: "POST",
402
- headers,
403
- body: JSON.stringify(payload || {}),
404
- credentials: "include",
405
- });
406
-
407
- const redirectHeader = res.headers.get("X-Bluebird-Redirect");
408
- if (redirectHeader) {
409
- await Bluebird.navigate(redirectHeader);
410
- return { redirect: redirectHeader };
411
- }
412
-
413
- const contentType = res.headers.get("content-type") || "";
414
- if (wantsPartial && contentType.includes("text/html")) {
415
- const html = await res.text();
416
- const selector =
417
- typeof options.partial === "string"
418
- ? options.partial
419
- : ".page-content, [data-bb-outlet]";
420
- const targetEl = document.querySelector(selector);
421
- if (targetEl) {
422
- const applySwap = () => {
423
- Bluebird.unmountNonPersistent(targetEl);
424
- targetEl.innerHTML = html;
425
- executeScripts(targetEl);
426
- Bluebird.hydrate(targetEl);
427
- };
428
- if (options.transition && document.startViewTransition) {
429
- await document.startViewTransition(applySwap).finished;
430
- } else {
431
- applySwap();
432
- }
433
- }
434
- return { ok: res.ok, html };
435
- }
436
-
437
- if (contentType.includes("application/json")) {
438
- const data = await res.json();
439
- return data;
440
- }
441
-
442
- return { ok: res.ok, status: res.status };
443
- },
444
- };
445
-
446
- /**
447
- * Swaps the current document DOM with the incoming parsed document.
448
- * Preserves [data-persist="true"] elements and synchronizes <head> meta tags.
449
- * @param {Document} nextDoc - Parsed incoming HTML document.
450
- * @param {string} url - Target URL.
451
- * @param {Object} options - Navigation options.
452
- */
453
- function swapDocument(nextDoc, url, options) {
454
- const currentPersistNodes = new Map();
455
- const currentPersistElements = document.querySelectorAll('[data-persist="true"]');
456
-
457
- currentPersistElements.forEach((el, index) => {
458
- const key = el.getAttribute("data-island") || el.getAttribute("data-bb-client") || el.id || `persist-${index}`;
459
- currentPersistNodes.set(key, el);
460
- });
461
-
462
- Bluebird.unmountNonPersistent();
463
-
464
- document.title = nextDoc.title || document.title;
465
-
466
- updateHeadTags(nextDoc);
467
-
468
- const nextPersistElements = nextDoc.querySelectorAll('[data-persist="true"]');
469
- nextPersistElements.forEach((nextEl, index) => {
470
- const key = nextEl.getAttribute("data-island") || nextEl.getAttribute("data-bb-client") || nextEl.id || `persist-${index}`;
471
- const activeEl = currentPersistNodes.get(key);
472
- if (activeEl && nextEl.parentNode) {
473
- nextEl.parentNode.replaceChild(activeEl, nextEl);
474
- currentPersistNodes.delete(key);
475
- }
476
- });
477
-
478
- const currentOutlet = document.querySelector("[data-bb-outlet]");
479
- const nextOutlet = nextDoc.querySelector("[data-bb-outlet]");
480
- const currentLayout = document.body.getAttribute("data-layout");
481
- const nextLayout = nextDoc.body.getAttribute("data-layout");
482
-
483
- const canSwapOutletOnly =
484
- currentOutlet &&
485
- nextOutlet &&
486
- currentLayout &&
487
- nextLayout &&
488
- currentLayout === nextLayout;
489
-
490
- if (canSwapOutletOnly) {
491
- currentOutlet.innerHTML = nextOutlet.innerHTML;
492
- executeScripts(currentOutlet);
493
- Bluebird.hydrate(currentOutlet);
494
- } else {
495
- document.body.innerHTML = nextDoc.body.innerHTML;
496
-
497
- for (const [key, activeEl] of currentPersistNodes.entries()) {
498
- const placeholder = document.querySelector(
499
- `[data-persist="true"][data-island="${key}"], [data-persist="true"][data-bb-client="${key}"], [data-persist="true"]#${key}`
500
- );
501
- if (placeholder && placeholder.parentNode && placeholder !== activeEl) {
502
- placeholder.parentNode.replaceChild(activeEl, placeholder);
503
- }
504
- }
505
-
506
- executeScripts(document.body);
1
+ /**
2
+ * Bluebird Client Runtime.
3
+ * Provides client-side SPA routing with View Transitions,
4
+ * persistent element state, selective React Islands hydration,
5
+ * and a lightweight global event bus.
6
+ */
7
+ (() => {
8
+ if (typeof window === "undefined" || window.Bluebird) return;
9
+
10
+ /**
11
+ * Global Island component registry.
12
+ * Components register themselves here via `window.__BLUEBIRD_ISLANDS__[name] = Component`.
13
+ * @type {Record<string, any>}
14
+ */
15
+ window.__BLUEBIRD_ISLANDS__ = window.__BLUEBIRD_ISLANDS__ || {};
16
+
17
+ /**
18
+ * Global Island root mounter/renderer function supplied by the React bundle.
19
+ * @type {Function|null}
20
+ */
21
+ window.__BLUEBIRD_MOUNT__ = window.__BLUEBIRD_MOUNT__ || null;
22
+
23
+ /**
24
+ * Map of mounted roots to DOM container elements.
25
+ * @type {Map<HTMLElement, {unmount: Function, persist: boolean, name: string}>}
26
+ */
27
+ const mountedRoots = new Map();
28
+
29
+ /**
30
+ * Map of prefetched HTML entries by URL with TTL expiration.
31
+ * @type {Map<string, {html: string, expiry: number}>}
32
+ */
33
+ const prefetchCache = new Map();
34
+ const PREFETCH_TTL_MS = 30000;
35
+ const PREFETCH_MAX_ENTRIES = 50;
36
+
37
+ /**
38
+ * Retrieves a valid prefetched HTML string from cache if not expired.
39
+ * @param {string} url
40
+ * @returns {string|null}
41
+ */
42
+ function getPrefetchedHtml(url) {
43
+ const entry = prefetchCache.get(url);
44
+ if (!entry) return null;
45
+ if (entry.expiry <= Date.now()) {
46
+ prefetchCache.delete(url);
47
+ return null;
48
+ }
49
+ return entry.html;
50
+ }
51
+
52
+ /**
53
+ * Stores a prefetched HTML string with TTL and LRU cap.
54
+ * @param {string} url
55
+ * @param {string} html
56
+ */
57
+ function setPrefetchedHtml(url, html) {
58
+ if (prefetchCache.size >= PREFETCH_MAX_ENTRIES) {
59
+ const oldestKey = prefetchCache.keys().next().value;
60
+ if (oldestKey !== undefined) prefetchCache.delete(oldestKey);
61
+ }
62
+ prefetchCache.set(url, { html, expiry: Date.now() + PREFETCH_TTL_MS });
63
+ }
64
+
65
+ /**
66
+ * Event listeners storage for the Bluebird Event Bus.
67
+ * @type {Map<string, Set<Function>>}
68
+ */
69
+ const eventListeners = new Map();
70
+
71
+ /**
72
+ * In-memory key-value reactive store.
73
+ * @type {Map<string, any>}
74
+ */
75
+ const storeState = new Map();
76
+
77
+ /**
78
+ * Reactive store change listeners.
79
+ * @type {Map<string, Set<Function>>}
80
+ */
81
+ const storeListeners = new Map();
82
+
83
+ /**
84
+ * Bluebird global API object.
85
+ */
86
+ const Bluebird = {
87
+ /**
88
+ * Emits an event through the client event bus.
89
+ * @param {string} event - Event identifier.
90
+ * @param {any} [data] - Event payload.
91
+ */
92
+ emit(event, data) {
93
+ const callbacks = eventListeners.get(event);
94
+ if (callbacks) {
95
+ for (const cb of callbacks) {
96
+ try {
97
+ cb(data);
98
+ } catch (err) {
99
+ console.error(`[BLUEBIRD EVENT ERROR] Error in listener for "${event}":`, err);
100
+ }
101
+ }
102
+ }
103
+ },
104
+
105
+ /**
106
+ * Subscribes to an event on the client event bus.
107
+ * @param {string} event - Event identifier.
108
+ * @param {Function} callback - Event listener callback.
109
+ * @returns {Function} Unsubscribe function.
110
+ */
111
+ on(event, callback) {
112
+ if (!eventListeners.has(event)) {
113
+ eventListeners.set(event, new Set());
114
+ }
115
+ eventListeners.get(event).add(callback);
116
+ return () => eventListeners.get(event)?.delete(callback);
117
+ },
118
+
119
+ /**
120
+ * Unsubscribes a callback from the client event bus.
121
+ * @param {string} event - Event identifier.
122
+ * @param {Function} callback - Registered callback.
123
+ */
124
+ off(event, callback) {
125
+ eventListeners.get(event)?.delete(callback);
126
+ },
127
+
128
+ /**
129
+ * Gets or sets a reactive store value.
130
+ * @param {string} key - Store key.
131
+ * @param {any} [value] - Optional new value.
132
+ * @returns {any} Current store value.
133
+ */
134
+ store(key, value) {
135
+ if (arguments.length > 1) {
136
+ storeState.set(key, value);
137
+ const listeners = storeListeners.get(key);
138
+ if (listeners) {
139
+ for (const cb of listeners) {
140
+ try {
141
+ cb(value);
142
+ } catch (err) {
143
+ console.error(`[BLUEBIRD STORE ERROR] Error in listener for "${key}":`, err);
144
+ }
145
+ }
146
+ }
147
+ }
148
+ return storeState.get(key);
149
+ },
150
+
151
+ /**
152
+ * Subscribes to reactive store changes.
153
+ * @param {string} key - Store key.
154
+ * @param {Function} callback - Change handler receiving new value.
155
+ * @returns {Function} Unsubscribe function.
156
+ */
157
+ subscribe(key, callback) {
158
+ if (!storeListeners.has(key)) {
159
+ storeListeners.set(key, new Set());
160
+ }
161
+ storeListeners.get(key).add(callback);
162
+ return () => storeListeners.get(key)?.delete(callback);
163
+ },
164
+
165
+ /**
166
+ * Clears the internal link prefetch cache.
167
+ */
168
+ clearPrefetch() {
169
+ prefetchCache.clear();
170
+ },
171
+
172
+ /**
173
+ * Registers a callback executed both on initial page load and after every SPA transition.
174
+ * Replaces DOMContentLoaded for Vanilla JavaScript components, sliders, and event listeners.
175
+ * @param {Function} callback - Function receiving { url, initial }.
176
+ * @returns {Function} Unsubscribe function.
177
+ */
178
+ onPageLoad(callback) {
179
+ if (typeof callback !== "function") return () => {};
180
+ const handler = (e) => callback(e.detail || { url: window.location.href, initial: false });
181
+ window.addEventListener("bluebird:page-load", handler);
182
+ if (document.readyState !== "loading") {
183
+ try {
184
+ callback({ url: window.location.href, initial: true });
185
+ } catch (err) {
186
+ console.error("[BLUEBIRD ON_PAGE_LOAD ERROR]:", err);
187
+ }
188
+ }
189
+ return () => window.removeEventListener("bluebird:page-load", handler);
190
+ },
191
+
192
+ /**
193
+ * Hydrates and mounts all [data-island] elements inside a container.
194
+ * @param {HTMLElement|Document} [container=document] - Target root DOM container.
195
+ */
196
+ hydrate(container = document) {
197
+
198
+ const islands = container.querySelectorAll("[data-island]");
199
+ for (const el of islands) {
200
+ if (el.__bluebird_mounted__) continue;
201
+
202
+ const name = el.getAttribute("data-island");
203
+ const isPersist = el.getAttribute("data-persist") === "true";
204
+ let props = {};
205
+
206
+ try {
207
+ const rawProps = el.getAttribute("data-props");
208
+ if (rawProps) props = JSON.parse(rawProps);
209
+ } catch (err) {
210
+ console.warn(`[BLUEBIRD ISLAND] Failed to parse props for island "${name}":`, err);
211
+ }
212
+
213
+ const component = window.__BLUEBIRD_ISLANDS__[name];
214
+ if (component && typeof window.__BLUEBIRD_MOUNT__ === "function") {
215
+ try {
216
+ const isHydrateMode = el.getAttribute("data-hydrate") === "true";
217
+ const unmountFn = window.__BLUEBIRD_MOUNT__(el, component, props, isHydrateMode);
218
+ el.__bluebird_mounted__ = true;
219
+ mountedRoots.set(el, {
220
+ unmount: unmountFn,
221
+ persist: isPersist,
222
+ name,
223
+ });
224
+ } catch (err) {
225
+ console.error(`[BLUEBIRD ISLAND] Error mounting island "${name}":`, err);
226
+ }
227
+ }
228
+ }
229
+ },
230
+
231
+ /**
232
+ * Cleanly unmounts non-persistent mounted islands inside a specific container (or entire document).
233
+ * @param {HTMLElement|Document} [container=document]
234
+ */
235
+ unmountNonPersistent(container = document) {
236
+ for (const [el, item] of mountedRoots.entries()) {
237
+ if (item.persist) continue;
238
+ if (container !== document && !container.contains(el)) continue;
239
+ try {
240
+ if (typeof item.unmount === "function") {
241
+ item.unmount();
242
+ }
243
+ } catch {}
244
+ el.__bluebird_mounted__ = false;
245
+ mountedRoots.delete(el);
246
+ }
247
+ },
248
+
249
+ /**
250
+ * Fetches an HTML partial from the server and swaps it into a target DOM selector.
251
+ * Automatically handles authentication redirects by falling back to full SPA navigation.
252
+ * @param {string} url - Endpoint returning a rendered partial or view.
253
+ * @param {string|HTMLElement} target - CSS selector or DOM element to update.
254
+ * @param {Object} [options={}] - Swap options.
255
+ * @param {boolean} [options.transition=false] - Wrap swap in View Transition.
256
+ * @param {boolean} [options.pushUrl=false] - Push URL to browser history.
257
+ * @returns {Promise<boolean>}
258
+ */
259
+ async renderPartial(url, target, options = {}) {
260
+ const targetEl = typeof target === "string" ? document.querySelector(target) : target;
261
+ if (!targetEl) return false;
262
+
263
+ try {
264
+ const res = await fetch(url, {
265
+ headers: {
266
+ "X-Bluebird-Client-Router": "1",
267
+ "X-Bluebird-Partial": "1",
268
+ },
269
+ credentials: "include",
270
+ });
271
+
272
+ if (!res.ok) return false;
273
+
274
+ if (res.redirected && res.url && res.headers.get("X-Bluebird-Partial") !== "1") {
275
+ await Bluebird.navigate(res.url);
276
+ return true;
277
+ }
278
+
279
+ const html = await res.text();
280
+ const applyPartial = () => {
281
+ Bluebird.unmountNonPersistent(targetEl);
282
+ targetEl.innerHTML = html;
283
+ executeScripts(targetEl);
284
+ Bluebird.hydrate(targetEl);
285
+ if (options.pushUrl) {
286
+ window.history.pushState({}, "", url);
287
+ }
288
+ window.dispatchEvent(
289
+ new CustomEvent("bluebird:partial-load", { detail: { url, target: targetEl } })
290
+ );
291
+ };
292
+
293
+ if (options.transition && document.startViewTransition) {
294
+ await document.startViewTransition(applyPartial).finished;
295
+ } else {
296
+ applyPartial();
297
+ }
298
+ return true;
299
+ } catch {
300
+ return false;
301
+ }
302
+ },
303
+
304
+ /**
305
+ * Performs client-side navigation to a target URL.
306
+ * @param {string} url - Target URL path.
307
+ * @param {Object} [options={}] - Navigation options.
308
+ * @param {boolean} [options.replace=false] - Use history.replaceState instead of pushState.
309
+ * @param {boolean} [options.scroll=true] - Scroll to top on navigation.
310
+ */
311
+ async navigate(url, options = {}) {
312
+ try {
313
+ let html = getPrefetchedHtml(url);
314
+ let targetUrl = url;
315
+ if (!html) {
316
+ const res = await fetch(url, {
317
+ headers: { "X-Bluebird-Client-Router": "1" },
318
+ credentials: "include",
319
+ });
320
+ if (!res.ok) {
321
+ window.location.href = url;
322
+ return;
323
+ }
324
+ if (res.redirected && res.url) {
325
+ try {
326
+ const parsed = new URL(res.url);
327
+ targetUrl = parsed.pathname + parsed.search;
328
+ } catch {}
329
+ }
330
+ html = await res.text();
331
+ } else {
332
+ prefetchCache.delete(url);
333
+ }
334
+
335
+ const parser = new DOMParser();
336
+ const nextDoc = parser.parseFromString(html, "text/html");
337
+
338
+ if (document.startViewTransition) {
339
+ await document.startViewTransition(() => {
340
+ swapDocument(nextDoc, targetUrl, options);
341
+ }).finished;
342
+ } else {
343
+ swapDocument(nextDoc, targetUrl, options);
344
+ }
345
+ } catch {
346
+ window.location.href = url;
347
+ }
348
+ },
349
+
350
+ /**
351
+ * Reads the active CSRF token from the `_csrf` cookie, hidden input, or meta tag.
352
+ * @returns {string}
353
+ */
354
+ getCsrfToken() {
355
+ const match = document.cookie.match(/(?:^|;\s*)_csrf=([^;]*)/);
356
+ if (match && match[1]) {
357
+ try {
358
+ return decodeURIComponent(match[1]);
359
+ } catch {
360
+ return match[1];
361
+ }
362
+ }
363
+ const csrfEl =
364
+ document.getElementById("csrf") ||
365
+ document.querySelector('input[name="_csrf"]') ||
366
+ document.querySelector('meta[name="csrf-token"]');
367
+ return csrfEl ? csrfEl.value || csrfEl.getAttribute("content") || "" : "";
368
+ },
369
+
370
+ /**
371
+ * Invokes a Server Action exported by the current (or target) view module (`export const actions = { ... }`).
372
+ * Automatically attaches the signed CSRF token, enforces JSON payload serialization,
373
+ * and optionally swaps the returned partial HTML into the page outlet or target selector.
374
+ *
375
+ * @param {string} actionName - Name of the exported server action.
376
+ * @param {Object} [payload={}] - Data payload sent to the server action.
377
+ * @param {Object} [options={}] - Execution options.
378
+ * @param {string} [options.url] - Target route URL (defaults to `window.location.pathname`).
379
+ * @param {boolean|string} [options.partial=false] - If true or a CSS selector, requests a partial re-render and updates the DOM.
380
+ * @returns {Promise<any>}
381
+ */
382
+ async action(actionName, payload = {}, options = {}) {
383
+ const targetUrl = options.url || window.location.pathname;
384
+ const csrfToken = Bluebird.getCsrfToken();
385
+ const wantsPartial = Boolean(options.partial);
386
+
387
+ const headers = {
388
+ "Content-Type": "application/json",
389
+ "X-Requested-With": "XMLHttpRequest",
390
+ "X-Bluebird-Client-Router": "1",
391
+ "X-Bluebird-Action": String(actionName),
392
+ };
393
+ if (csrfToken) {
394
+ headers["X-CSRF-Token"] = csrfToken;
395
+ }
396
+ if (wantsPartial) {
397
+ headers["X-Bluebird-Partial"] = "1";
398
+ }
399
+
400
+ const res = await fetch(targetUrl, {
401
+ method: "POST",
402
+ headers,
403
+ body: JSON.stringify(payload || {}),
404
+ credentials: "include",
405
+ });
406
+
407
+ const redirectHeader = res.headers.get("X-Bluebird-Redirect");
408
+ if (redirectHeader) {
409
+ await Bluebird.navigate(redirectHeader);
410
+ return { redirect: redirectHeader };
411
+ }
412
+
413
+ const contentType = res.headers.get("content-type") || "";
414
+ if (wantsPartial && contentType.includes("text/html")) {
415
+ const html = await res.text();
416
+ const selector =
417
+ typeof options.partial === "string"
418
+ ? options.partial
419
+ : ".page-content, [data-bb-outlet]";
420
+ const targetEl = document.querySelector(selector);
421
+ if (targetEl) {
422
+ const applySwap = () => {
423
+ Bluebird.unmountNonPersistent(targetEl);
424
+ targetEl.innerHTML = html;
425
+ executeScripts(targetEl);
426
+ Bluebird.hydrate(targetEl);
427
+ };
428
+ if (options.transition && document.startViewTransition) {
429
+ await document.startViewTransition(applySwap).finished;
430
+ } else {
431
+ applySwap();
432
+ }
433
+ }
434
+ return { ok: res.ok, html };
435
+ }
436
+
437
+ if (contentType.includes("application/json")) {
438
+ const data = await res.json();
439
+ return data;
440
+ }
441
+
442
+ return { ok: res.ok, status: res.status };
443
+ },
444
+ };
445
+
446
+ /**
447
+ * Swaps the current document DOM with the incoming parsed document.
448
+ * Preserves [data-persist="true"] elements and synchronizes <head> meta tags.
449
+ * @param {Document} nextDoc - Parsed incoming HTML document.
450
+ * @param {string} url - Target URL.
451
+ * @param {Object} options - Navigation options.
452
+ */
453
+ function swapDocument(nextDoc, url, options) {
454
+ const currentPersistNodes = new Map();
455
+ const currentPersistElements = document.querySelectorAll('[data-persist="true"]');
456
+
457
+ currentPersistElements.forEach((el, index) => {
458
+ const key = el.getAttribute("data-island") || el.getAttribute("data-bb-client") || el.id || `persist-${index}`;
459
+ currentPersistNodes.set(key, el);
460
+ });
461
+
462
+ Bluebird.unmountNonPersistent();
463
+
464
+ document.title = nextDoc.title || document.title;
465
+
466
+ updateHeadTags(nextDoc);
467
+
468
+ const nextPersistElements = nextDoc.querySelectorAll('[data-persist="true"]');
469
+ nextPersistElements.forEach((nextEl, index) => {
470
+ const key = nextEl.getAttribute("data-island") || nextEl.getAttribute("data-bb-client") || nextEl.id || `persist-${index}`;
471
+ const activeEl = currentPersistNodes.get(key);
472
+ if (activeEl && nextEl.parentNode) {
473
+ nextEl.parentNode.replaceChild(activeEl, nextEl);
474
+ currentPersistNodes.delete(key);
475
+ }
476
+ });
477
+
478
+ const currentOutlet = document.querySelector("[data-bb-outlet]");
479
+ const nextOutlet = nextDoc.querySelector("[data-bb-outlet]");
480
+ const currentLayout = document.body.getAttribute("data-layout");
481
+ const nextLayout = nextDoc.body.getAttribute("data-layout");
482
+
483
+ const canSwapOutletOnly =
484
+ currentOutlet &&
485
+ nextOutlet &&
486
+ currentLayout &&
487
+ nextLayout &&
488
+ currentLayout === nextLayout;
489
+
490
+ if (canSwapOutletOnly) {
491
+ currentOutlet.innerHTML = nextOutlet.innerHTML;
492
+ executeScripts(currentOutlet);
493
+ Bluebird.hydrate(currentOutlet);
494
+ } else {
495
+ document.body.innerHTML = nextDoc.body.innerHTML;
496
+
497
+ for (const [key, activeEl] of currentPersistNodes.entries()) {
498
+ const placeholder = document.querySelector(
499
+ `[data-persist="true"][data-island="${key}"], [data-persist="true"][data-bb-client="${key}"], [data-persist="true"]#${key}`
500
+ );
501
+ if (placeholder && placeholder.parentNode && placeholder !== activeEl) {
502
+ placeholder.parentNode.replaceChild(activeEl, placeholder);
503
+ }
504
+ }
505
+
506
+ executeScripts(document.body);
507
507
  Bluebird.hydrate();
508
- drainMountQueue();
509
- }
510
-
511
- syncActiveNavLinks(url);
512
-
513
- if (options.replace) {
514
- window.history.replaceState({}, "", url);
515
- } else {
516
- window.history.pushState({}, "", url);
517
- }
518
-
519
- if (options.scroll !== false) {
520
- window.scrollTo(0, 0);
521
- }
522
-
523
- const pageLoadDetail = { url, initial: false };
524
- window.dispatchEvent(new CustomEvent("bluebird:navigate", { detail: { url } }));
525
- window.dispatchEvent(new CustomEvent("bluebird:page-load", { detail: pageLoadDetail }));
526
- document.dispatchEvent(new CustomEvent("bluebird:page-load", { detail: pageLoadDetail }));
527
- }
528
-
529
- /**
530
- * Synchronizes active state on navigation links across header and aside.
531
- * @param {string} targetUrl
532
- */
533
- function syncActiveNavLinks(targetUrl) {
534
- try {
535
- const parsed = new URL(targetUrl, window.location.origin);
536
- const targetPath = parsed.pathname;
537
- const navLinks = document.querySelectorAll("header a, aside a, nav a");
538
- for (const link of navLinks) {
539
- const href = link.getAttribute("href");
540
- if (!href || href.startsWith("http") || href.startsWith("#")) continue;
541
- const linkPath = new URL(href, window.location.origin).pathname;
542
- const isActive = linkPath === targetPath;
543
- if (isActive) {
544
- link.setAttribute("aria-current", "page");
545
- link.classList.add("bg-sky-500/15", "text-sky-400", "border", "border-sky-500/30", "font-semibold");
546
- link.classList.remove("text-slate-400");
547
- } else if (link.getAttribute("aria-current") === "page" || link.classList.contains("bg-sky-500/15")) {
548
- link.removeAttribute("aria-current");
549
- link.classList.remove("bg-sky-500/15", "text-sky-400", "border", "border-sky-500/30", "font-semibold");
550
- link.classList.add("text-slate-400");
551
- }
552
- }
553
- } catch (err) {}
554
- }
555
-
556
- /**
557
- * Re-evaluates script elements found in the newly injected container.
558
- * Wraps inline classic scripts in an isolated block/IIFE scope so top-level `const` / `let`
559
- * declarations never collide across repeated SPA navigations.
560
- * Skips persistent scripts and the Bluebird client runtime itself.
561
- * @param {HTMLElement} container
562
- */
563
- function executeScripts(container) {
564
- const scripts = Array.from(container.querySelectorAll("script"));
565
- for (const oldScript of scripts) {
566
- if (oldScript.getAttribute("data-persist") === "true") continue;
567
- const src = oldScript.getAttribute("src") || "";
568
- if (src.includes("bluebird-client.js")) continue;
569
-
570
- const newScript = document.createElement("script");
571
- for (const attr of Array.from(oldScript.attributes)) {
572
- newScript.setAttribute(attr.name, attr.value);
573
- }
574
-
575
- const rawType = (oldScript.getAttribute("type") || "").trim().toLowerCase();
576
- const isClassicInline =
577
- !src && (!rawType || rawType === "text/javascript" || rawType === "application/javascript");
578
- const code = oldScript.textContent || "";
579
-
580
- if (isClassicInline && code.trim().length > 0) {
581
- newScript.textContent = `{(() => {\n${code}\n})();}`;
582
- } else {
583
- newScript.textContent = code;
584
- }
585
-
586
- if (oldScript.parentNode) {
587
- oldScript.parentNode.replaceChild(newScript, oldScript);
588
- }
589
- }
590
- }
591
-
592
- /**
593
- * Synchronizes meta and link tags between current and incoming <head>.
594
- * @param {Document} nextDoc
595
- */
596
- function updateHeadTags(nextDoc) {
597
- const currentMeta = document.head.querySelectorAll("meta[name], meta[property]");
598
- currentMeta.forEach((el) => el.remove());
599
-
600
- const nextMeta = nextDoc.head.querySelectorAll("meta[name], meta[property]");
601
- nextMeta.forEach((el) => {
602
- document.head.appendChild(document.importNode(el, true));
603
- });
604
-
605
- const nextCanonical = nextDoc.head.querySelector("link[rel='canonical']");
606
- const currentCanonical = document.head.querySelector("link[rel='canonical']");
607
- if (nextCanonical) {
608
- if (currentCanonical) {
609
- currentCanonical.setAttribute("href", nextCanonical.getAttribute("href") || "");
610
- } else {
611
- document.head.appendChild(document.importNode(nextCanonical, true));
612
- }
613
- } else if (currentCanonical) {
614
- currentCanonical.remove();
615
- }
616
- }
617
-
618
- /**
619
- * Determines if a link element qualifies for SPA navigation.
620
- * @param {HTMLAnchorElement} anchor
621
- * @returns {boolean}
622
- */
623
- function isInternalLink(anchor) {
624
- if (!anchor || anchor.tagName !== "A") return false;
625
- if (anchor.target && anchor.target !== "_self") return false;
626
- if (anchor.hasAttribute("download")) return false;
627
- if (anchor.getAttribute("rel") === "external") return false;
628
- if (anchor.getAttribute("data-no-router") !== null) return false;
629
-
630
- const href = anchor.getAttribute("href");
631
- if (!href || href.startsWith("#") || href.startsWith("javascript:") || href.startsWith("mailto:") || href.startsWith("tel:")) {
632
- return false;
633
- }
634
-
635
- try {
636
- const url = new URL(anchor.href, window.location.href);
637
- return url.origin === window.location.origin;
638
- } catch {
639
- return false;
640
- }
641
- }
642
-
643
- /**
644
- * Determines if a link element qualifies for background prefetching on hover.
645
- * Excludes links marked with data-no-prefetch, data-prefetch="false", data-no-hover,
646
- * or paths typically used for session termination (such as /logout or /signout).
647
- * @param {HTMLAnchorElement} anchor
648
- * @returns {boolean}
649
- */
650
- function canPrefetch(anchor) {
651
- if (!isInternalLink(anchor)) return false;
652
- if (anchor.hasAttribute("data-no-prefetch")) return false;
653
- if (anchor.getAttribute("data-prefetch") === "false") return false;
654
- if (anchor.hasAttribute("data-no-hover")) return false;
655
- if (anchor.hasAttribute("data-partial-target")) return false;
656
-
657
- try {
658
- const url = new URL(anchor.href, window.location.href);
659
- const pathname = url.pathname.toLowerCase();
660
- if (
661
- pathname === "/logout" ||
662
- pathname.endsWith("/logout") ||
663
- pathname === "/signout" ||
664
- pathname.endsWith("/signout")
665
- ) {
666
- return false;
667
- }
668
- } catch {
669
- return false;
670
- }
671
-
672
- return true;
673
- }
674
-
675
- /**
676
- * Initializes click interception on document for client-side routing and partial swaps.
677
- */
678
- function initLinkInterception() {
679
- document.addEventListener("click", (e) => {
680
- if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {
681
- return;
682
- }
683
-
684
- const anchor = e.target.closest("a");
685
- if (!anchor || !isInternalLink(anchor)) return;
686
-
687
- const partialTarget = anchor.getAttribute("data-partial-target");
688
- if (partialTarget) {
689
- e.preventDefault();
690
- Bluebird.renderPartial(anchor.href, partialTarget, {
691
- transition: anchor.getAttribute("data-transition") === "true",
692
- pushUrl: anchor.getAttribute("data-push-url") === "true",
693
- });
694
- return;
695
- }
696
-
697
- const url = anchor.href;
698
- if (url === window.location.href) {
699
- e.preventDefault();
700
- return;
701
- }
702
-
703
- e.preventDefault();
704
- Bluebird.navigate(url);
705
- });
706
-
707
- document.addEventListener(
708
- "mouseover",
709
- (e) => {
710
- const anchor = e.target.closest("a");
711
- if (!anchor || !canPrefetch(anchor)) return;
712
- const url = anchor.href;
713
- if (!getPrefetchedHtml(url)) {
714
- fetch(url, { headers: { "X-Bluebird-Prefetch": "1" }, credentials: "include" })
715
- .then((r) => (r.ok ? r.text() : null))
716
- .then((html) => {
717
- if (html) setPrefetchedHtml(url, html);
718
- })
719
- .catch(() => {});
720
- }
721
- },
722
- { passive: true }
723
- );
724
-
725
- window.addEventListener("popstate", () => {
726
- Bluebird.navigate(window.location.href, { replace: true, scroll: false });
727
- });
728
- }
729
-
730
- /**
731
- * DOM query selector shortcut.
732
- * @param {string} selector
733
- * @param {HTMLElement|Document} [context=document]
734
- * @returns {HTMLElement|null}
735
- */
736
- const $ = (selector, context = document) => context.querySelector(selector);
737
-
738
- /**
739
- * DOM query selector all shortcut returning an Array.
740
- * @param {string} selector
741
- * @param {HTMLElement|Document} [context=document]
742
- * @returns {HTMLElement[]}
743
- */
744
- const $$ = (selector, context = document) => Array.from(context.querySelectorAll(selector));
745
-
746
- /**
747
- * Delegated DOM event listener helper.
748
- * Listens on document, matching selectors dynamically.
749
- * Works across View Transitions without manual re-binding!
750
- * @param {string} selector - CSS selector (e.g. '#btnInc', '.card-btn')
751
- * @param {string} type - Event type (e.g. 'click', 'input', 'submit')
752
- * @param {Function} handler - Callback receiving (event, matchedElement)
753
- * @returns {Function} Unsubscribe function.
754
- */
755
- function delegate(selector, type, handler) {
756
- const listener = (e) => {
757
- const match = e.target.closest(selector);
758
- if (match) handler(e, match);
759
- };
760
- document.addEventListener(type, listener);
761
- return () => document.removeEventListener(type, listener);
762
- }
763
-
764
- Bluebird.$ = $;
765
- Bluebird.$$ = $$;
766
- Bluebird.delegate = delegate;
767
- Bluebird.event = delegate;
768
-
769
- window.$ = window.$ || $;
770
- window.$$ = window.$$ || $$;
771
- window.on = window.on || delegate;
772
-
508
+ drainMountQueue();
509
+ }
510
+
511
+ syncActiveNavLinks(url);
512
+
513
+ if (options.replace) {
514
+ window.history.replaceState({}, "", url);
515
+ } else {
516
+ window.history.pushState({}, "", url);
517
+ }
518
+
519
+ if (options.scroll !== false) {
520
+ window.scrollTo(0, 0);
521
+ }
522
+
523
+ const pageLoadDetail = { url, initial: false };
524
+ window.dispatchEvent(new CustomEvent("bluebird:navigate", { detail: { url } }));
525
+ window.dispatchEvent(new CustomEvent("bluebird:page-load", { detail: pageLoadDetail }));
526
+ document.dispatchEvent(new CustomEvent("bluebird:page-load", { detail: pageLoadDetail }));
527
+ }
528
+
529
+ /**
530
+ * Synchronizes active state on navigation links across header and aside.
531
+ * @param {string} targetUrl
532
+ */
533
+ function syncActiveNavLinks(targetUrl) {
534
+ try {
535
+ const parsed = new URL(targetUrl, window.location.origin);
536
+ const targetPath = parsed.pathname;
537
+ const navLinks = document.querySelectorAll("header a, aside a, nav a");
538
+ for (const link of navLinks) {
539
+ const href = link.getAttribute("href");
540
+ if (!href || href.startsWith("http") || href.startsWith("#")) continue;
541
+ const linkPath = new URL(href, window.location.origin).pathname;
542
+ const isActive = linkPath === targetPath;
543
+ if (isActive) {
544
+ link.setAttribute("aria-current", "page");
545
+ link.classList.add("bg-sky-500/15", "text-sky-400", "border", "border-sky-500/30", "font-semibold");
546
+ link.classList.remove("text-slate-400");
547
+ } else if (link.getAttribute("aria-current") === "page" || link.classList.contains("bg-sky-500/15")) {
548
+ link.removeAttribute("aria-current");
549
+ link.classList.remove("bg-sky-500/15", "text-sky-400", "border", "border-sky-500/30", "font-semibold");
550
+ link.classList.add("text-slate-400");
551
+ }
552
+ }
553
+ } catch (err) {}
554
+ }
555
+
556
+ /**
557
+ * Re-evaluates script elements found in the newly injected container.
558
+ * Wraps inline classic scripts in an isolated block/IIFE scope so top-level `const` / `let`
559
+ * declarations never collide across repeated SPA navigations.
560
+ * Skips persistent scripts and the Bluebird client runtime itself.
561
+ * @param {HTMLElement} container
562
+ */
563
+ function executeScripts(container) {
564
+ const scripts = Array.from(container.querySelectorAll("script"));
565
+ for (const oldScript of scripts) {
566
+ if (oldScript.getAttribute("data-persist") === "true") continue;
567
+ const src = oldScript.getAttribute("src") || "";
568
+ if (src.includes("bluebird-client.js")) continue;
569
+
570
+ const newScript = document.createElement("script");
571
+ for (const attr of Array.from(oldScript.attributes)) {
572
+ newScript.setAttribute(attr.name, attr.value);
573
+ }
574
+
575
+ const rawType = (oldScript.getAttribute("type") || "").trim().toLowerCase();
576
+ const isClassicInline =
577
+ !src && (!rawType || rawType === "text/javascript" || rawType === "application/javascript");
578
+ const code = oldScript.textContent || "";
579
+
580
+ if (isClassicInline && code.trim().length > 0) {
581
+ newScript.textContent = `{(() => {\n${code}\n})();}`;
582
+ } else {
583
+ newScript.textContent = code;
584
+ }
585
+
586
+ if (oldScript.parentNode) {
587
+ oldScript.parentNode.replaceChild(newScript, oldScript);
588
+ }
589
+ }
590
+ }
591
+
592
+ /**
593
+ * Synchronizes meta and link tags between current and incoming <head>.
594
+ * @param {Document} nextDoc
595
+ */
596
+ function updateHeadTags(nextDoc) {
597
+ const currentMeta = document.head.querySelectorAll("meta[name], meta[property]");
598
+ currentMeta.forEach((el) => el.remove());
599
+
600
+ const nextMeta = nextDoc.head.querySelectorAll("meta[name], meta[property]");
601
+ nextMeta.forEach((el) => {
602
+ document.head.appendChild(document.importNode(el, true));
603
+ });
604
+
605
+ const nextCanonical = nextDoc.head.querySelector("link[rel='canonical']");
606
+ const currentCanonical = document.head.querySelector("link[rel='canonical']");
607
+ if (nextCanonical) {
608
+ if (currentCanonical) {
609
+ currentCanonical.setAttribute("href", nextCanonical.getAttribute("href") || "");
610
+ } else {
611
+ document.head.appendChild(document.importNode(nextCanonical, true));
612
+ }
613
+ } else if (currentCanonical) {
614
+ currentCanonical.remove();
615
+ }
616
+ }
617
+
618
+ /**
619
+ * Determines if a link element qualifies for SPA navigation.
620
+ * @param {HTMLAnchorElement} anchor
621
+ * @returns {boolean}
622
+ */
623
+ function isInternalLink(anchor) {
624
+ if (!anchor || anchor.tagName !== "A") return false;
625
+ if (anchor.target && anchor.target !== "_self") return false;
626
+ if (anchor.hasAttribute("download")) return false;
627
+ if (anchor.getAttribute("rel") === "external") return false;
628
+ if (anchor.getAttribute("data-no-router") !== null) return false;
629
+
630
+ const href = anchor.getAttribute("href");
631
+ if (!href || href.startsWith("#") || href.startsWith("javascript:") || href.startsWith("mailto:") || href.startsWith("tel:")) {
632
+ return false;
633
+ }
634
+
635
+ try {
636
+ const url = new URL(anchor.href, window.location.href);
637
+ return url.origin === window.location.origin;
638
+ } catch {
639
+ return false;
640
+ }
641
+ }
642
+
643
+ /**
644
+ * Determines if a link element qualifies for background prefetching on hover.
645
+ * Excludes links marked with data-no-prefetch, data-prefetch="false", data-no-hover,
646
+ * or paths typically used for session termination (such as /logout or /signout).
647
+ * @param {HTMLAnchorElement} anchor
648
+ * @returns {boolean}
649
+ */
650
+ function canPrefetch(anchor) {
651
+ if (!isInternalLink(anchor)) return false;
652
+ if (anchor.hasAttribute("data-no-prefetch")) return false;
653
+ if (anchor.getAttribute("data-prefetch") === "false") return false;
654
+ if (anchor.hasAttribute("data-no-hover")) return false;
655
+ if (anchor.hasAttribute("data-partial-target")) return false;
656
+
657
+ try {
658
+ const url = new URL(anchor.href, window.location.href);
659
+ const pathname = url.pathname.toLowerCase();
660
+ if (
661
+ pathname === "/logout" ||
662
+ pathname.endsWith("/logout") ||
663
+ pathname === "/signout" ||
664
+ pathname.endsWith("/signout")
665
+ ) {
666
+ return false;
667
+ }
668
+ } catch {
669
+ return false;
670
+ }
671
+
672
+ return true;
673
+ }
674
+
675
+ /**
676
+ * Initializes click interception on document for client-side routing and partial swaps.
677
+ */
678
+ function initLinkInterception() {
679
+ document.addEventListener("click", (e) => {
680
+ if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {
681
+ return;
682
+ }
683
+
684
+ const anchor = e.target.closest("a");
685
+ if (!anchor || !isInternalLink(anchor)) return;
686
+
687
+ const partialTarget = anchor.getAttribute("data-partial-target");
688
+ if (partialTarget) {
689
+ e.preventDefault();
690
+ Bluebird.renderPartial(anchor.href, partialTarget, {
691
+ transition: anchor.getAttribute("data-transition") === "true",
692
+ pushUrl: anchor.getAttribute("data-push-url") === "true",
693
+ });
694
+ return;
695
+ }
696
+
697
+ const url = anchor.href;
698
+ if (url === window.location.href) {
699
+ e.preventDefault();
700
+ return;
701
+ }
702
+
703
+ e.preventDefault();
704
+ Bluebird.navigate(url);
705
+ });
706
+
707
+ document.addEventListener(
708
+ "mouseover",
709
+ (e) => {
710
+ const anchor = e.target.closest("a");
711
+ if (!anchor || !canPrefetch(anchor)) return;
712
+ const url = anchor.href;
713
+ if (!getPrefetchedHtml(url)) {
714
+ fetch(url, { headers: { "X-Bluebird-Prefetch": "1" }, credentials: "include" })
715
+ .then((r) => (r.ok ? r.text() : null))
716
+ .then((html) => {
717
+ if (html) setPrefetchedHtml(url, html);
718
+ })
719
+ .catch(() => {});
720
+ }
721
+ },
722
+ { passive: true }
723
+ );
724
+
725
+ window.addEventListener("popstate", () => {
726
+ Bluebird.navigate(window.location.href, { replace: true, scroll: false });
727
+ });
728
+ }
729
+
730
+ /**
731
+ * DOM query selector shortcut.
732
+ * @param {string} selector
733
+ * @param {HTMLElement|Document} [context=document]
734
+ * @returns {HTMLElement|null}
735
+ */
736
+ const $ = (selector, context = document) => context.querySelector(selector);
737
+
738
+ /**
739
+ * DOM query selector all shortcut returning an Array.
740
+ * @param {string} selector
741
+ * @param {HTMLElement|Document} [context=document]
742
+ * @returns {HTMLElement[]}
743
+ */
744
+ const $$ = (selector, context = document) => Array.from(context.querySelectorAll(selector));
745
+
746
+ /**
747
+ * Delegated DOM event listener helper.
748
+ * Listens on document, matching selectors dynamically.
749
+ * Works across View Transitions without manual re-binding!
750
+ * @param {string} selector - CSS selector (e.g. '#btnInc', '.card-btn')
751
+ * @param {string} type - Event type (e.g. 'click', 'input', 'submit')
752
+ * @param {Function} handler - Callback receiving (event, matchedElement)
753
+ * @returns {Function} Unsubscribe function.
754
+ */
755
+ function delegate(selector, type, handler) {
756
+ const listener = (e) => {
757
+ const match = e.target.closest(selector);
758
+ if (match) handler(e, match);
759
+ };
760
+ document.addEventListener(type, listener);
761
+ return () => document.removeEventListener(type, listener);
762
+ }
763
+
764
+ Bluebird.$ = $;
765
+ Bluebird.$$ = $$;
766
+ Bluebird.delegate = delegate;
767
+ Bluebird.event = delegate;
768
+
769
+ window.$ = window.$ || $;
770
+ window.$$ = window.$$ || $$;
771
+ window.on = window.on || delegate;
772
+
773
773
  const VOID_TAGS = new Set([
774
774
  "area", "base", "br", "col", "embed", "hr", "img", "input",
775
775
  "link", "meta", "param", "source", "track", "wbr"
@@ -1326,6 +1326,97 @@
1326
1326
  return useMemo(() => fn, deps);
1327
1327
  }
1328
1328
 
1329
+ /**
1330
+ * Manages Server Action execution with reactive pending state, data, and error handling.
1331
+ * Returns [execute, isPending, data, error, reset].
1332
+ *
1333
+ * @param {string|Function} actionName - Registered Server Action name or action handler function.
1334
+ * @param {Object} [options={}] - Options (url, partial, onSuccess, onError, onSettled).
1335
+ * @returns {[Function, boolean, any, any, Function]}
1336
+ */
1337
+ function useAction(actionName, options = {}) {
1338
+ const [isPending, setIsPending] = useState(false);
1339
+ const [data, setData] = useState(null);
1340
+ const [error, setError] = useState(null);
1341
+ const optionsRef = useRef(options);
1342
+ optionsRef.current = options;
1343
+
1344
+ const execute = useCallback(
1345
+ async (payload = {}) => {
1346
+ setIsPending(true);
1347
+ setError(null);
1348
+ try {
1349
+ let res;
1350
+ if (typeof actionName === "function") {
1351
+ res = await actionName(payload, optionsRef.current);
1352
+ } else if (Bluebird && typeof Bluebird.action === "function") {
1353
+ res = await Bluebird.action(actionName, payload, optionsRef.current);
1354
+ }
1355
+ setData(res);
1356
+ setIsPending(false);
1357
+ if (typeof optionsRef.current?.onSuccess === "function") {
1358
+ optionsRef.current.onSuccess(res);
1359
+ }
1360
+ return res;
1361
+ } catch (err) {
1362
+ setError(err);
1363
+ setIsPending(false);
1364
+ if (typeof optionsRef.current?.onError === "function") {
1365
+ optionsRef.current.onError(err);
1366
+ }
1367
+ throw err;
1368
+ } finally {
1369
+ if (typeof optionsRef.current?.onSettled === "function") {
1370
+ optionsRef.current.onSettled();
1371
+ }
1372
+ }
1373
+ },
1374
+ [actionName]
1375
+ );
1376
+
1377
+ const reset = useCallback(() => {
1378
+ setIsPending(false);
1379
+ setData(null);
1380
+ setError(null);
1381
+ }, []);
1382
+
1383
+ return [execute, isPending, data, error, reset];
1384
+ }
1385
+
1386
+ /**
1387
+ * React 19-compatible useActionState hook for Server Actions and form submissions.
1388
+ *
1389
+ * @param {string|Function} actionFn - Action name or async reducer (prevState, formDataOrPayload) => nextState.
1390
+ * @param {any} initialState - Initial state value before any action executes.
1391
+ * @returns {[any, Function, boolean]} [state, dispatch, isPending]
1392
+ */
1393
+ function useActionState(actionFn, initialState) {
1394
+ const [state, setState] = useState(initialState);
1395
+ const [isPending, setIsPending] = useState(false);
1396
+
1397
+ const dispatch = useCallback(
1398
+ async (payload) => {
1399
+ setIsPending(true);
1400
+ try {
1401
+ let nextState;
1402
+ if (typeof actionFn === "function") {
1403
+ nextState = await actionFn(state, payload);
1404
+ } else if (typeof actionFn === "string" && Bluebird && typeof Bluebird.action === "function") {
1405
+ const res = await Bluebird.action(actionFn, payload);
1406
+ nextState = res?.data !== undefined ? res.data : res;
1407
+ }
1408
+ setState(nextState);
1409
+ return nextState;
1410
+ } finally {
1411
+ setIsPending(false);
1412
+ }
1413
+ },
1414
+ [actionFn, state]
1415
+ );
1416
+
1417
+ return [state, dispatch, isPending];
1418
+ }
1419
+
1329
1420
  const activeComponentInstances = new Map();
1330
1421
 
1331
1422
  /**
@@ -1469,6 +1560,8 @@
1469
1560
  Bluebird.useRef = useRef;
1470
1561
  Bluebird.useMemo = useMemo;
1471
1562
  Bluebird.useCallback = useCallback;
1563
+ Bluebird.useAction = useAction;
1564
+ Bluebird.useActionState = useActionState;
1472
1565
 
1473
1566
  window.html = window.html || html;
1474
1567
  window.useState = window.useState || useState;
@@ -1476,1570 +1569,1593 @@
1476
1569
  window.useRef = window.useRef || useRef;
1477
1570
  window.useMemo = window.useMemo || useMemo;
1478
1571
  window.useCallback = window.useCallback || useCallback;
1572
+ window.useAction = window.useAction || useAction;
1573
+ window.useActionState = window.useActionState || useActionState;
1479
1574
 
1480
1575
  window.Bluebird = Bluebird;
1481
- drainMountQueue();
1482
-
1483
- /**
1484
- * Initializes automatic page reload during development when the Node server restarts.
1485
- */
1486
- function initDevReload() {
1487
- if (typeof window === "undefined" || !window.EventSource) return;
1488
- const isLocalhost =
1489
- window.location.hostname === "localhost" ||
1490
- window.location.hostname === "127.0.0.1" ||
1491
- window.location.hostname === "::1";
1492
- if (!isLocalhost) return;
1493
-
1494
- let initialBootId = null;
1495
- let connectedOnce = false;
1496
- let failedAttempts = 0;
1497
- let es = null;
1498
-
1499
- function connect() {
1500
- try {
1501
- es = new EventSource("/_bb/dev-reload");
1502
-
1503
- es.onmessage = (event) => {
1504
- try {
1505
- const data = JSON.parse(event.data);
1506
- if (data.type === "connected" && data.bootId) {
1507
- connectedOnce = true;
1508
- failedAttempts = 0;
1509
- if (initialBootId === null) {
1510
- initialBootId = data.bootId;
1511
- } else if (initialBootId !== data.bootId) {
1512
- console.log("[Bluebird] Server restart detected, reloading page...");
1513
- window.location.reload();
1514
- }
1515
- }
1516
- } catch {}
1517
- };
1518
-
1519
- es.onerror = () => {
1520
- try { es.close(); } catch {}
1521
- if (!connectedOnce) {
1522
- failedAttempts++;
1523
- if (failedAttempts > 2) return;
1524
- setTimeout(connect, 1000);
1525
- return;
1526
- }
1527
- setTimeout(connect, 500);
1528
- };
1529
- } catch {}
1530
- }
1531
-
1532
- connect();
1533
- }
1534
-
1535
- /**
1536
- * Initializes client router, hydrates components, and emits initial page-load event.
1537
- */
1538
- function triggerInitialLoad() {
1539
- initLinkInterception();
1576
+ drainMountQueue();
1577
+
1578
+ /**
1579
+ * Initializes automatic page reload during development when the Node server restarts.
1580
+ */
1581
+ function initDevReload() {
1582
+ if (typeof window === "undefined" || !window.EventSource) return;
1583
+ const isLocalhost =
1584
+ window.location.hostname === "localhost" ||
1585
+ window.location.hostname === "127.0.0.1" ||
1586
+ window.location.hostname === "::1";
1587
+ if (!isLocalhost) return;
1588
+
1589
+ let initialBootId = null;
1590
+ let connectedOnce = false;
1591
+ let failedAttempts = 0;
1592
+ let es = null;
1593
+
1594
+ function connect() {
1595
+ try {
1596
+ es = new EventSource("/_bb/dev-reload");
1597
+
1598
+ es.onmessage = (event) => {
1599
+ try {
1600
+ const data = JSON.parse(event.data);
1601
+ if (data.type === "connected" && data.bootId) {
1602
+ connectedOnce = true;
1603
+ failedAttempts = 0;
1604
+ if (initialBootId === null) {
1605
+ initialBootId = data.bootId;
1606
+ } else if (initialBootId !== data.bootId) {
1607
+ console.log("[Bluebird] Server restart detected, reloading page...");
1608
+ window.location.reload();
1609
+ }
1610
+ }
1611
+ } catch {}
1612
+ };
1613
+
1614
+ es.onerror = () => {
1615
+ try { es.close(); } catch {}
1616
+ if (!connectedOnce) {
1617
+ failedAttempts++;
1618
+ if (failedAttempts > 2) return;
1619
+ setTimeout(connect, 1000);
1620
+ return;
1621
+ }
1622
+ setTimeout(connect, 500);
1623
+ };
1624
+ } catch {}
1625
+ }
1626
+
1627
+ connect();
1628
+ }
1629
+
1630
+ /**
1631
+ * Initializes client router, hydrates components, and emits initial page-load event.
1632
+ */
1633
+ function triggerInitialLoad() {
1634
+ initLinkInterception();
1540
1635
  Bluebird.hydrate();
1541
- drainMountQueue();
1542
- initDevReload();
1543
- const detail = { url: window.location.href, initial: true };
1544
- window.dispatchEvent(new CustomEvent("bluebird:page-load", { detail }));
1545
- document.dispatchEvent(new CustomEvent("bluebird:page-load", { detail }));
1546
- }
1547
-
1548
- if (document.readyState === "loading") {
1549
- document.addEventListener("DOMContentLoaded", triggerInitialLoad);
1550
- } else {
1551
- triggerInitialLoad();
1552
- }
1553
- })();
1554
- /**
1555
- * Bluebird Client UI & Interactive Runtime.
1556
- * Styled with Tailwind CSS v4 and designed for SPA navigation and desktop apps.
1557
- */
1558
-
1559
- /**
1560
- * Escapes HTML special characters in client-side strings.
1561
- * @param {any} str
1562
- * @returns {string}
1563
- */
1564
- function escapeClientHtml(str) {
1565
- if (str === null || str === undefined) return "";
1566
- return String(str)
1567
- .replace(/&/g, "&amp;")
1568
- .replace(/</g, "&lt;")
1569
- .replace(/>/g, "&gt;")
1570
- .replace(/"/g, "&quot;")
1571
- .replace(/'/g, "&#39;");
1572
- }
1573
-
1574
- let customCommandsList = null;
1575
- if (typeof window !== "undefined") {
1576
- window.Bluebird = window.Bluebird || {};
1577
- window.Bluebird.setCommands = function (items) {
1578
- customCommandsList = Array.isArray(items) ? items : null;
1579
- };
1580
- }
1581
-
1582
- /**
1583
- * Global component dispatcher for Bluebird interactive widgets.
1584
- * @param {string|Object} component
1585
- * @param {Object} [options]
1586
- */
1587
- function bluebird(component, options) {
1588
- if (typeof component === "object") {
1589
- options = component;
1590
- component = "snackbar";
1591
- }
1592
-
1593
- if (component === "snackbar") {
1594
- let snackbarEl = document.getElementById("snackbar");
1595
- if (!snackbarEl) {
1596
- snackbarEl = document.createElement("div");
1597
- snackbarEl.id = "snackbar";
1598
- document.body.appendChild(snackbarEl);
1599
- }
1600
-
1601
- const type = (options && options.type) || "info";
1602
- let colorClasses = "bg-slate-900 text-slate-100 border border-slate-700/80";
1603
- if (type === "success") {
1604
- colorClasses = "bg-emerald-950/95 text-emerald-100 border border-emerald-500/40";
1605
- } else if (type === "warning") {
1606
- colorClasses = "bg-amber-950/95 text-amber-100 border border-amber-500/40";
1607
- } else if (type === "error" || type === "danger") {
1608
- colorClasses = "bg-red-950/95 text-red-100 border border-red-500/40";
1609
- }
1610
-
1611
- const baseClasses =
1612
- "fixed bottom-5 left-1/2 -translate-x-1/2 z-[100] flex items-center gap-3 px-5 py-3 rounded-xl shadow-2xl text-sm font-medium transition-all duration-300";
1613
- snackbarEl.className = `${baseClasses} ${colorClasses} opacity-0 translate-y-4 pointer-events-none`;
1614
- snackbarEl.textContent = (options && options.message) || "";
1615
-
1616
- setTimeout(() => {
1617
- snackbarEl.classList.remove("opacity-0", "translate-y-4", "pointer-events-none");
1618
- snackbarEl.classList.add("opacity-100", "translate-y-0", "pointer-events-auto");
1619
- }, 10);
1620
-
1621
- const duration = (options && options.duration) || 3000;
1622
- if (snackbarEl.timeoutId) {
1623
- clearTimeout(snackbarEl.timeoutId);
1624
- }
1625
- snackbarEl.timeoutId = setTimeout(function () {
1626
- snackbarEl.classList.remove("opacity-100", "translate-y-0", "pointer-events-auto");
1627
- snackbarEl.classList.add("opacity-0", "translate-y-4", "pointer-events-none");
1628
- }, duration);
1629
- }
1630
-
1631
- if (component === "toast") {
1632
- const position = (options && options.position) || "bottom-right";
1633
- const posMap = {
1634
- "bottom-right": "fixed bottom-4 right-4 z-[100] flex flex-col gap-2.5 w-full max-w-sm pointer-events-none",
1635
- "bottom-left": "fixed bottom-4 left-4 z-[100] flex flex-col gap-2.5 w-full max-w-sm pointer-events-none",
1636
- "top-right": "fixed top-4 right-4 z-[100] flex flex-col gap-2.5 w-full max-w-sm pointer-events-none",
1637
- "top-left": "fixed top-4 left-4 z-[100] flex flex-col gap-2.5 w-full max-w-sm pointer-events-none",
1638
- "top-center": "fixed top-4 left-1/2 -translate-x-1/2 z-[100] flex flex-col gap-2.5 w-full max-w-sm pointer-events-none",
1639
- "bottom-center": "fixed bottom-4 left-1/2 -translate-x-1/2 z-[100] flex flex-col gap-2.5 w-full max-w-sm pointer-events-none",
1640
- };
1641
- const containerClass = posMap[position] || posMap["bottom-right"];
1642
- let container = document.querySelector(`.toast-container[data-position="${position}"]`);
1643
- if (!container) {
1644
- container = document.createElement("div");
1645
- container.className = `toast-container ${containerClass}`;
1646
- container.setAttribute("data-position", position);
1647
- document.body.appendChild(container);
1648
- }
1649
-
1650
- const toastEl = document.createElement("div");
1651
- const type = (options && options.type) || "info";
1652
- let variantClass = "bg-slate-900/95 border-slate-700/80 text-slate-100";
1653
- if (type === "success") {
1654
- variantClass = "bg-slate-900/95 border-emerald-500/40 text-slate-100";
1655
- } else if (type === "error" || type === "danger") {
1656
- variantClass = "bg-slate-900/95 border-red-500/40 text-slate-100";
1657
- } else if (type === "warning") {
1658
- variantClass = "bg-slate-900/95 border-amber-500/40 text-slate-100";
1659
- }
1660
-
1661
- toastEl.className = `toast pointer-events-auto flex items-start justify-between gap-3 p-4 rounded-xl border shadow-xl backdrop-blur-md transition-all duration-200 ${variantClass}`;
1662
- const title = options && options.title
1663
- ? `<div class="toast-title font-semibold text-sm">${escapeClientHtml(options.title)}</div>`
1664
- : "";
1665
- const desc = options && options.description
1666
- ? `<div class="toast-description text-xs text-slate-300 mt-0.5 leading-relaxed">${escapeClientHtml(options.description)}</div>`
1667
- : "";
1668
-
1669
- toastEl.innerHTML = `
1670
- <div class="toast-content flex-1 min-w-0">
1671
- ${title}
1672
- ${desc}
1673
- </div>
1674
- <button class="toast-close shrink-0 rounded-lg p-1 text-slate-400 hover:text-white hover:bg-slate-800 transition-colors leading-none" aria-label="Dismiss">&times;</button>
1675
- `;
1676
-
1677
- const closeBtn = toastEl.querySelector(".toast-close");
1678
- closeBtn.addEventListener("click", () => dismissToast(toastEl));
1679
- container.appendChild(toastEl);
1680
-
1681
- const duration = (options && options.duration) !== undefined ? options.duration : 4000;
1682
- if (duration > 0) {
1683
- setTimeout(() => dismissToast(toastEl), duration);
1684
- }
1685
- }
1686
-
1687
- if (component === "tab") {
1688
- const targetId = options && options.id;
1689
- if (!targetId) return;
1690
- const targetContent = document.getElementById(targetId);
1691
- if (!targetContent) return;
1692
-
1693
- const tabsContainer = targetContent.closest(".tabs") || document.body;
1694
- const allTriggers = tabsContainer.querySelectorAll(".tab-trigger, [data-tab-target]");
1695
- const allContents = tabsContainer.querySelectorAll(".tab-content, [data-tab-content]");
1696
-
1697
- allContents.forEach((c) => {
1698
- c.classList.remove("active", "block");
1699
- c.classList.add("hidden");
1700
- });
1701
- allTriggers.forEach((t) => {
1702
- t.classList.remove("active", "border-sky-500", "text-sky-400");
1703
- t.setAttribute("aria-selected", "false");
1704
- });
1705
-
1706
- targetContent.classList.remove("hidden");
1707
- targetContent.classList.add("active", "block");
1708
-
1709
- const matchingTrigger = Array.from(allTriggers).find(
1710
- (t) =>
1711
- t.getAttribute("data-tab-target") === targetId ||
1712
- t.getAttribute("href") === `#${targetId}`
1713
- );
1714
- if (matchingTrigger) {
1715
- matchingTrigger.classList.add("active", "border-sky-500", "text-sky-400");
1716
- matchingTrigger.setAttribute("aria-selected", "true");
1717
- }
1718
- }
1719
-
1720
- if (component === "command") {
1721
- const action = (options && options.action) || "toggle";
1722
- let backdrop = document.querySelector(".command-backdrop");
1723
- if (!backdrop) {
1724
- backdrop = createCommandPaletteModal();
1725
- }
1726
- const isOpen = backdrop.classList.contains("open");
1727
- if (action === "open" || (action === "toggle" && !isOpen)) {
1728
- backdrop.classList.remove("hidden");
1729
- backdrop.classList.add("flex", "open");
1730
- const input = backdrop.querySelector(".command-input");
1731
- if (input) {
1732
- input.value = "";
1733
- setTimeout(() => input.focus(), 50);
1734
- }
1735
- } else if (action === "close" || (action === "toggle" && isOpen)) {
1736
- backdrop.classList.remove("flex", "open");
1737
- backdrop.classList.add("hidden");
1738
- }
1739
- }
1740
-
1741
- if (component === "popover") {
1742
- const id = options && (options.id || options.targetId);
1743
- const action = (options && options.action) || "toggle";
1744
- if (!id) return;
1745
- const popoverEl =
1746
- document.getElementById(id) || document.querySelector(`[data-popover-id="${id}"]`);
1747
- if (!popoverEl) return;
1748
- const isOpen = popoverEl.classList.contains("open");
1749
- const shouldOpen = action === "open" || (action === "toggle" && !isOpen);
1750
- popoverEl.classList.toggle("hidden", !shouldOpen);
1751
- popoverEl.classList.toggle("open", shouldOpen);
1752
- }
1753
-
1754
- if (component === "drawer") {
1755
- cleanupOrphanedBackdrops();
1756
- const id = options && options.id;
1757
- const action = (options && options.action) || "toggle";
1758
- if (!id) return;
1759
- const drawerEl = document.getElementById(id);
1760
- if (!drawerEl) return;
1761
-
1762
- let overlay = document.querySelector(`.drawer-backdrop[data-for="${id}"]`);
1763
- if (!overlay) {
1764
- overlay = document.createElement("div");
1765
- overlay.className =
1766
- "drawer-backdrop fixed inset-0 z-40 bg-slate-950/60 backdrop-blur-xs transition-opacity duration-300 opacity-0 pointer-events-none";
1767
- overlay.setAttribute("data-for", id);
1768
- document.body.appendChild(overlay);
1769
- overlay.addEventListener("click", () => {
1770
- bluebird("drawer", { id, action: "close" });
1771
- });
1772
- }
1773
-
1774
- const isOpen = drawerEl.classList.contains("open") || drawerEl.classList.contains("active");
1775
- if (action === "open" || (action === "toggle" && !isOpen)) {
1776
- drawerEl.classList.add("open");
1777
- drawerEl.classList.remove("-translate-x-full");
1778
- drawerEl.classList.add("translate-x-0");
1779
- overlay.classList.remove("opacity-0", "pointer-events-none");
1780
- overlay.classList.add("opacity-100", "pointer-events-auto", "open");
1781
- document.body.style.overflow = "hidden";
1782
- } else if (action === "close" || (action === "toggle" && isOpen)) {
1783
- drawerEl.classList.remove("open", "translate-x-0");
1784
- drawerEl.classList.add("-translate-x-full");
1785
- overlay.classList.remove("opacity-100", "pointer-events-auto", "open");
1786
- overlay.classList.add("opacity-0", "pointer-events-none");
1787
- document.body.style.overflow = "";
1788
- setTimeout(() => {
1789
- if (overlay && overlay.parentNode && !drawerEl.classList.contains("open")) {
1790
- overlay.remove();
1791
- }
1792
- }, 300);
1793
- }
1794
- }
1795
-
1796
- if (component === "carousel") {
1797
- const selector = (options && options.selector) || ".carousel";
1798
- const carousels = document.querySelectorAll(selector);
1799
- carousels.forEach((carousel) => initSingleCarousel(carousel, options));
1800
- }
1801
-
1802
- if (component === "datatable" || component === "table") {
1803
- const containerId = (options && (options.container || options.id)) || "datatable";
1804
- return new ResponsiveDataTable(containerId, options);
1805
- }
1806
- }
1807
-
1808
- /**
1809
- * Display a temporary snackbar message.
1810
- * @param {Object} options
1811
- */
1812
- function snackbar(options) {
1813
- bluebird("snackbar", options);
1814
- }
1815
-
1816
- /**
1817
- * Display a temporary toast notification.
1818
- * @param {Object} options
1819
- */
1820
- function toast(options) {
1821
- bluebird("toast", options);
1822
- }
1823
-
1824
- /**
1825
- * Dismisses a toast element with animation.
1826
- * @param {HTMLElement} toastEl
1827
- */
1828
- function dismissToast(toastEl) {
1829
- if (!toastEl || toastEl.isDismissing) return;
1830
- toastEl.isDismissing = true;
1831
- toastEl.style.opacity = "0";
1832
- toastEl.style.transform = "translateY(-10px) scale(0.95)";
1833
- setTimeout(() => {
1834
- if (toastEl.parentNode) {
1835
- toastEl.remove();
1836
- }
1837
- }, 200);
1838
- }
1839
-
1840
- /**
1841
- * Creates and injects the global command palette modal.
1842
- * @returns {HTMLElement}
1843
- */
1844
- function createCommandPaletteModal() {
1845
- const backdrop = document.createElement("div");
1846
- backdrop.className =
1847
- "command-backdrop fixed inset-0 z-[100] hidden items-start justify-center bg-slate-950/70 backdrop-blur-xs pt-[14vh] px-4";
1848
-
1849
- let itemsHtml = "";
1850
- if (customCommandsList && customCommandsList.length > 0) {
1851
- itemsHtml = customCommandsList
1852
- .map(
1853
- (item) => `
1854
- <div class="command-item flex items-center justify-between px-3 py-2 rounded-lg text-sm text-slate-300 hover:bg-sky-500/15 hover:text-sky-400 cursor-pointer transition-colors" data-navigate="${escapeClientHtml(item.url || item.href || "")}">
1855
- <span>${escapeClientHtml(item.label || item.title || item.name)}</span>
1856
- <kbd class="text-[10px] px-1.5 py-0.5 rounded bg-slate-800 text-slate-400 border border-slate-700">↵</kbd>
1857
- </div>
1858
- `
1859
- )
1860
- .join("");
1861
- } else {
1862
- itemsHtml = `
1863
- <div class="command-group space-y-1">
1864
- <div class="command-group-title px-3 py-1 text-[11px] font-semibold uppercase tracking-wider text-slate-500">Navigation</div>
1865
- <div class="command-item flex items-center justify-between px-3 py-2 rounded-lg text-sm text-slate-300 hover:bg-sky-500/15 hover:text-sky-400 cursor-pointer transition-colors" data-navigate="/"><span>Home</span><kbd class="text-[10px] px-1.5 py-0.5 rounded bg-slate-800 text-slate-400 border border-slate-700">↵</kbd></div>
1866
- <div class="command-item flex items-center justify-between px-3 py-2 rounded-lg text-sm text-slate-300 hover:bg-sky-500/15 hover:text-sky-400 cursor-pointer transition-colors" data-navigate="/about"><span>About Us</span><kbd class="text-[10px] px-1.5 py-0.5 rounded bg-slate-800 text-slate-400 border border-slate-700">↵</kbd></div>
1867
- <div class="command-item flex items-center justify-between px-3 py-2 rounded-lg text-sm text-slate-300 hover:bg-sky-500/15 hover:text-sky-400 cursor-pointer transition-colors" data-navigate="/login"><span>Login</span><kbd class="text-[10px] px-1.5 py-0.5 rounded bg-slate-800 text-slate-400 border border-slate-700">↵</kbd></div>
1868
- <div class="command-item flex items-center justify-between px-3 py-2 rounded-lg text-sm text-slate-300 hover:bg-sky-500/15 hover:text-sky-400 cursor-pointer transition-colors" data-navigate="/dashboard"><span>Dashboard</span><kbd class="text-[10px] px-1.5 py-0.5 rounded bg-slate-800 text-slate-400 border border-slate-700">↵</kbd></div>
1869
- </div>
1870
- `;
1871
- }
1872
-
1873
- backdrop.innerHTML = `
1874
- <div class="command-dialog w-full max-w-lg rounded-2xl border border-slate-800 bg-slate-900 text-slate-100 shadow-2xl overflow-hidden">
1875
- <div class="command-input-wrapper flex items-center gap-3 px-4 py-3 border-b border-slate-800">
1876
- <span class="text-slate-400">🔍</span>
1877
- <input type="text" class="command-input w-full bg-transparent text-sm text-slate-100 placeholder-slate-500 focus:outline-none" placeholder="Type a command or search..." />
1878
- <kbd class="text-[10px] px-1.5 py-0.5 rounded bg-slate-800 text-slate-400 border border-slate-700">ESC</kbd>
1879
- </div>
1880
- <div class="command-list max-h-80 overflow-y-auto p-2 space-y-2">
1881
- ${itemsHtml}
1882
- </div>
1883
- </div>
1884
- `;
1885
-
1886
- document.body.appendChild(backdrop);
1887
- backdrop.addEventListener("click", (e) => {
1888
- if (e.target === backdrop) {
1889
- bluebird("command", { action: "close" });
1890
- }
1891
- });
1892
-
1893
- const input = backdrop.querySelector(".command-input");
1894
- input.addEventListener("input", (e) => {
1895
- const query = e.target.value.toLowerCase().trim();
1896
- const items = backdrop.querySelectorAll(".command-item");
1897
- items.forEach((item) => {
1898
- const text = item.textContent.toLowerCase();
1899
- item.style.display = text.includes(query) ? "flex" : "none";
1900
- });
1901
- });
1902
-
1903
- backdrop.addEventListener("click", (e) => {
1904
- const item = e.target.closest(".command-item");
1905
- if (item && item.getAttribute("data-navigate")) {
1906
- const dest = item.getAttribute("data-navigate");
1907
- if (dest.startsWith("/") && window.Bluebird && typeof window.Bluebird.navigate === "function") {
1908
- window.Bluebird.navigate(dest);
1909
- } else {
1910
- window.location.href = dest;
1911
- }
1912
- bluebird("command", { action: "close" });
1913
- }
1914
- });
1915
-
1916
- return backdrop;
1917
- }
1918
-
1919
- /**
1920
- * Removes backdrops whose associated elements are no longer in the DOM.
1921
- */
1922
- function cleanupOrphanedBackdrops() {
1923
- document.querySelectorAll(".drawer-backdrop[data-for]").forEach((backdrop) => {
1924
- const targetId = backdrop.getAttribute("data-for");
1925
- if (!document.getElementById(targetId)) {
1926
- backdrop.remove();
1927
- }
1928
- });
1929
- }
1930
-
1931
- /**
1932
- * Initializes responsive mobile drawer navigation menu.
1933
- */
1934
- function initMobileDrawer() {
1935
- const mainEl = document.querySelector("main");
1936
- const aside = mainEl ? mainEl.querySelector(":scope > aside") : null;
1937
- if (!aside) return;
1938
-
1939
- let overlay = document.querySelector(".bluebird-drawer-overlay");
1940
- if (!overlay) {
1941
- overlay = document.createElement("div");
1942
- overlay.className =
1943
- "bluebird-drawer-overlay fixed inset-0 z-40 bg-slate-950/60 backdrop-blur-xs hidden";
1944
- document.body.appendChild(overlay);
1945
- }
1946
-
1947
- let drawer = document.querySelector(".bluebird-drawer");
1948
- if (!drawer) {
1949
- drawer = document.createElement("div");
1950
- drawer.className =
1951
- "bluebird-drawer fixed top-0 left-0 z-50 h-full w-72 max-w-[80vw] bg-slate-900 border-r border-slate-800 p-5 overflow-y-auto transition-transform duration-300 -translate-x-full flex flex-col gap-2";
1952
- document.body.appendChild(drawer);
1953
- }
1954
- drawer.innerHTML = aside.innerHTML;
1955
-
1956
- let toggle = document.querySelector(".bluebird-drawer-toggle");
1957
- if (!toggle) {
1958
- toggle = document.createElement("button");
1959
- toggle.className =
1960
- "bluebird-drawer-toggle md:hidden inline-flex items-center justify-center p-2 rounded-lg text-slate-300 hover:text-white hover:bg-slate-800 transition-colors mr-2";
1961
- toggle.innerHTML = '<span class="text-lg leading-none">☰</span>';
1962
- toggle.setAttribute("aria-label", "Toggle navigation menu");
1963
- const header = document.querySelector("header");
1964
- if (header) {
1965
- const nav = header.querySelector("nav");
1966
- if (nav) {
1967
- nav.insertBefore(toggle, nav.firstChild);
1968
- } else {
1969
- header.prepend(toggle);
1970
- }
1971
- } else {
1972
- document.body.prepend(toggle);
1973
- }
1974
- }
1975
- }
1976
-
1977
- /**
1978
- * Initializes a single carousel container.
1979
- * @param {HTMLElement} carousel
1980
- * @param {Object} [opts]
1981
- */
1982
- function initSingleCarousel(carousel, opts = {}) {
1983
- if (carousel._bb_initialized) return;
1984
- carousel._bb_initialized = true;
1985
-
1986
- const track = carousel.querySelector(".carousel-track");
1987
- if (!track) return;
1988
- track.classList.add("flex", "overflow-x-auto", "snap-x", "snap-mandatory", "scroll-smooth", "gap-4");
1989
-
1990
- const items = Array.from(track.querySelectorAll(".carousel-item, .carousel-card"));
1991
- if (items.length === 0) return;
1992
-
1993
- const prevBtn = carousel.querySelector(".carousel-prev");
1994
- const nextBtn = carousel.querySelector(".carousel-next");
1995
- let indicatorsContainer = carousel.querySelector(".carousel-indicators");
1996
- let currentSlideIndex = 0;
1997
-
1998
- if (indicatorsContainer && indicatorsContainer.children.length === 0) {
1999
- items.forEach((_, idx) => {
2000
- const dot = document.createElement("button");
2001
- dot.className = `carousel-dot w-2.5 h-2.5 rounded-full transition-all ${
2002
- idx === 0 ? "bg-sky-400 w-5" : "bg-slate-600"
2003
- }`;
2004
- dot.setAttribute("aria-label", `Go to slide ${idx + 1}`);
2005
- dot.addEventListener("click", (e) => {
2006
- e.preventDefault();
2007
- scrollToSlide(idx);
2008
- });
2009
- indicatorsContainer.appendChild(dot);
2010
- });
2011
- }
2012
-
2013
- function scrollToSlide(index) {
2014
- if (index < 0) index = 0;
2015
- if (index >= items.length) index = items.length - 1;
2016
- currentSlideIndex = index;
2017
- const targetItem = items[index];
2018
- if (targetItem) {
2019
- track.scrollTo({
2020
- left: targetItem.offsetLeft - track.offsetLeft,
2021
- behavior: "smooth",
2022
- });
2023
- updateIndicators(index);
2024
- }
2025
- }
2026
-
2027
- function updateIndicators(activeIndex) {
2028
- if (!indicatorsContainer) return;
2029
- const dots = Array.from(indicatorsContainer.children);
2030
- dots.forEach((dot, idx) => {
2031
- if (idx === activeIndex) {
2032
- dot.className = "carousel-dot w-5 h-2.5 rounded-full transition-all bg-sky-400";
2033
- } else {
2034
- dot.className = "carousel-dot w-2.5 h-2.5 rounded-full transition-all bg-slate-600";
2035
- }
2036
- });
2037
- }
2038
-
2039
- let scrollTimeout;
2040
- track.addEventListener("scroll", () => {
2041
- clearTimeout(scrollTimeout);
2042
- scrollTimeout = setTimeout(() => {
2043
- const trackLeft = track.scrollLeft;
2044
- let closestIndex = 0;
2045
- let minDistance = Infinity;
2046
- items.forEach((item, idx) => {
2047
- const distance = Math.abs(item.offsetLeft - track.offsetLeft - trackLeft);
2048
- if (distance < minDistance) {
2049
- minDistance = distance;
2050
- closestIndex = idx;
2051
- }
2052
- });
2053
- currentSlideIndex = closestIndex;
2054
- updateIndicators(closestIndex);
2055
- }, 40);
2056
- });
2057
-
2058
- if (prevBtn) {
2059
- prevBtn.addEventListener("click", (e) => {
2060
- e.preventDefault();
2061
- e.stopPropagation();
2062
- scrollToSlide(currentSlideIndex - 1);
2063
- });
2064
- }
2065
- if (nextBtn) {
2066
- nextBtn.addEventListener("click", (e) => {
2067
- e.preventDefault();
2068
- e.stopPropagation();
2069
- scrollToSlide(currentSlideIndex + 1);
2070
- });
2071
- }
2072
-
2073
- let startX = 0;
2074
- let isDragging = false;
2075
- track.addEventListener(
2076
- "touchstart",
2077
- (e) => {
2078
- startX = e.touches[0].clientX;
2079
- isDragging = true;
2080
- },
2081
- { passive: true }
2082
- );
2083
-
2084
- track.addEventListener("touchend", (e) => {
2085
- if (!isDragging) return;
2086
- isDragging = false;
2087
- const endX = e.changedTouches[0].clientX;
2088
- const diffX = startX - endX;
2089
- if (Math.abs(diffX) > 35) {
2090
- if (diffX > 0) {
2091
- scrollToSlide(currentSlideIndex + 1);
2092
- } else {
2093
- scrollToSlide(currentSlideIndex - 1);
2094
- }
2095
- }
2096
- });
2097
-
2098
- track.addEventListener("mousedown", (e) => {
2099
- startX = e.clientX;
2100
- isDragging = true;
2101
- track.style.cursor = "grabbing";
2102
- });
2103
-
2104
- track.addEventListener("mouseleave", () => {
2105
- isDragging = false;
2106
- track.style.cursor = "grab";
2107
- });
2108
-
2109
- track.addEventListener("mouseup", (e) => {
2110
- if (!isDragging) return;
2111
- isDragging = false;
2112
- track.style.cursor = "grab";
2113
- const endX = e.clientX;
2114
- const diffX = startX - endX;
2115
- if (Math.abs(diffX) > 35) {
2116
- if (diffX > 0) {
2117
- scrollToSlide(currentSlideIndex + 1);
2118
- } else {
2119
- scrollToSlide(currentSlideIndex - 1);
2120
- }
2121
- }
2122
- });
2123
-
2124
- const isAutoplay =
2125
- (opts && opts.autoplay) || carousel.getAttribute("data-autoplay") === "true";
2126
- const intervalTime = parseInt(
2127
- (opts && opts.interval) || carousel.getAttribute("data-interval") || 3500,
2128
- 10
2129
- );
2130
-
2131
- if (isAutoplay) {
2132
- let autoInterval = setInterval(() => {
2133
- const nextIdx = (currentSlideIndex + 1) % items.length;
2134
- scrollToSlide(nextIdx);
2135
- }, intervalTime);
2136
- carousel.addEventListener("mouseenter", () => clearInterval(autoInterval));
2137
- carousel.addEventListener("mouseleave", () => {
2138
- autoInterval = setInterval(() => {
2139
- const nextIdx = (currentSlideIndex + 1) % items.length;
2140
- scrollToSlide(nextIdx);
2141
- }, intervalTime);
2142
- });
2143
- }
2144
- }
2145
-
2146
- (function setupDeclarativeListeners() {
2147
- if (window.__BLUEBIRD_UI_BOUND__) return;
2148
- window.__BLUEBIRD_UI_BOUND__ = true;
2149
-
2150
- document.addEventListener("click", (e) => {
2151
- const tabTrigger = e.target.closest("[data-tab-target], .tab-trigger");
2152
- if (tabTrigger) {
2153
- const targetId =
2154
- tabTrigger.getAttribute("data-tab-target") ||
2155
- (tabTrigger.getAttribute("href") || "").replace("#", "");
2156
- if (targetId) {
2157
- e.preventDefault();
2158
- bluebird("tab", { id: targetId });
2159
- }
2160
- }
2161
-
2162
- const popoverTrigger = e.target.closest("[data-popover-target]");
2163
- if (popoverTrigger) {
2164
- const popoverId = popoverTrigger.getAttribute("data-popover-target");
2165
- bluebird("popover", { id: popoverId, action: "toggle" });
2166
- }
2167
- if (!e.target.closest(".popover") && !e.target.closest("[data-popover-target]")) {
2168
- document.querySelectorAll(".popover.open").forEach((p) => {
2169
- p.classList.remove("open");
2170
- p.classList.add("hidden");
2171
- });
2172
- }
2173
-
2174
- const mobileToggle = e.target.closest(".bluebird-drawer-toggle");
2175
- if (mobileToggle) {
2176
- e.preventDefault();
2177
- e.stopPropagation();
2178
- initMobileDrawer();
2179
- const drawer = document.querySelector(".bluebird-drawer");
2180
- const overlay = document.querySelector(".bluebird-drawer-overlay");
2181
- if (drawer && overlay) {
2182
- const isOpen = drawer.classList.contains("open");
2183
- if (isOpen) {
2184
- drawer.classList.remove("open", "translate-x-0");
2185
- drawer.classList.add("-translate-x-full");
2186
- overlay.classList.add("hidden");
2187
- overlay.classList.remove("open");
2188
- document.body.style.overflow = "";
2189
- } else {
2190
- drawer.classList.remove("-translate-x-full");
2191
- drawer.classList.add("open", "translate-x-0");
2192
- overlay.classList.remove("hidden");
2193
- overlay.classList.add("open");
2194
- document.body.style.overflow = "hidden";
2195
- }
2196
- }
2197
- return;
2198
- }
2199
-
2200
- if (e.target.closest(".bluebird-drawer-overlay")) {
2201
- const drawer = document.querySelector(".bluebird-drawer");
2202
- const overlay = document.querySelector(".bluebird-drawer-overlay");
2203
- if (drawer) {
2204
- drawer.classList.remove("open", "translate-x-0");
2205
- drawer.classList.add("-translate-x-full");
2206
- }
2207
- if (overlay) {
2208
- overlay.classList.add("hidden");
2209
- overlay.classList.remove("open");
2210
- }
2211
- document.body.style.overflow = "";
2212
- return;
2213
- }
2214
-
2215
- if (e.target.closest(".bluebird-drawer a")) {
2216
- const drawer = document.querySelector(".bluebird-drawer");
2217
- const overlay = document.querySelector(".bluebird-drawer-overlay");
2218
- if (drawer) {
2219
- drawer.classList.remove("open", "translate-x-0");
2220
- drawer.classList.add("-translate-x-full");
2221
- }
2222
- if (overlay) {
2223
- overlay.classList.add("hidden");
2224
- overlay.classList.remove("open");
2225
- }
2226
- document.body.style.overflow = "";
2227
- }
2228
-
2229
- const drawerTrigger = e.target.closest("[data-drawer-target]");
2230
- if (drawerTrigger) {
2231
- const id = drawerTrigger.getAttribute("data-drawer-target");
2232
- bluebird("drawer", { id, action: "toggle" });
2233
- }
2234
-
2235
- const drawerClose = e.target.closest("[data-drawer-close]");
2236
- if (drawerClose) {
2237
- const drawerEl = drawerClose.closest(".drawer");
2238
- if (drawerEl && drawerEl.id) {
2239
- bluebird("drawer", { id: drawerEl.id, action: "close" });
2240
- }
2241
- }
2242
-
2243
- const copyTrigger = e.target.closest("[data-copy]");
2244
- if (copyTrigger) {
2245
- e.preventDefault();
2246
- const targetAttr = copyTrigger.getAttribute("data-copy");
2247
- let textToCopy = targetAttr;
2248
- if (targetAttr && (targetAttr.startsWith("#") || targetAttr.startsWith("."))) {
2249
- const targetEl = document.querySelector(targetAttr);
2250
- if (targetEl) {
2251
- textToCopy =
2252
- targetEl.value !== undefined
2253
- ? targetEl.value
2254
- : targetEl.innerText || targetEl.textContent;
2255
- }
2256
- }
2257
- if (textToCopy) {
2258
- navigator.clipboard.writeText(textToCopy.trim()).then(() => {
2259
- copyTrigger.classList.add("copied");
2260
- if (typeof bluebird === "function") {
2261
- bluebird("toast", {
2262
- title: "Copied to clipboard",
2263
- description:
2264
- textToCopy.length > 50 ? textToCopy.substring(0, 50) + "..." : textToCopy,
2265
- type: "success",
2266
- duration: 2500,
2267
- });
2268
- }
2269
- setTimeout(() => copyTrigger.classList.remove("copied"), 2000);
2270
- });
2271
- }
2272
- return;
2273
- }
2274
-
2275
- const confirmTrigger = e.target.closest("[data-confirm]");
2276
- if (confirmTrigger) {
2277
- const msg = confirmTrigger.getAttribute("data-confirm") || "Are you sure?";
2278
- if (!window.confirm(msg)) {
2279
- e.preventDefault();
2280
- e.stopImmediatePropagation();
2281
- return;
2282
- }
2283
- }
2284
-
2285
- const scrollTrigger = e.target.closest("[data-scroll-to]");
2286
- if (scrollTrigger) {
2287
- e.preventDefault();
2288
- const targetId = scrollTrigger.getAttribute("data-scroll-to");
2289
- const targetEl = document.querySelector(targetId);
2290
- if (targetEl) {
2291
- targetEl.scrollIntoView({ behavior: "smooth", block: "start" });
2292
- }
2293
- return;
2294
- }
2295
-
2296
- const passToggle = e.target.closest("[data-password-toggle]");
2297
- if (passToggle) {
2298
- e.preventDefault();
2299
- const targetSelector = passToggle.getAttribute("data-password-toggle");
2300
- const input = targetSelector
2301
- ? document.querySelector(targetSelector)
2302
- : passToggle.closest(".input-group, .form-input-group, div")?.querySelector("input") ||
2303
- passToggle.previousElementSibling;
2304
- if (input && (input.type === "password" || input.type === "text")) {
2305
- const isPassword = input.type === "password";
2306
- input.type = isPassword ? "text" : "password";
2307
- passToggle.classList.toggle("showing", isPassword);
2308
- passToggle.setAttribute("aria-pressed", isPassword ? "true" : "false");
2309
- }
2310
- return;
2311
- }
2312
-
2313
- const stepUp = e.target.closest("[data-step-up]");
2314
- if (stepUp) {
2315
- e.preventDefault();
2316
- const targetInput =
2317
- document.querySelector(stepUp.getAttribute("data-step-up")) ||
2318
- stepUp.closest(".stepper")?.querySelector('input[type="number"]');
2319
- if (targetInput && typeof targetInput.stepUp === "function") {
2320
- targetInput.stepUp();
2321
- targetInput.dispatchEvent(new Event("input", { bubbles: true }));
2322
- targetInput.dispatchEvent(new Event("change", { bubbles: true }));
2323
- }
2324
- return;
2325
- }
2326
-
2327
- const stepDown = e.target.closest("[data-step-down]");
2328
- if (stepDown) {
2329
- e.preventDefault();
2330
- const targetInput =
2331
- document.querySelector(stepDown.getAttribute("data-step-down")) ||
2332
- stepDown.closest(".stepper")?.querySelector('input[type="number"]');
2333
- if (targetInput && typeof targetInput.stepDown === "function") {
2334
- targetInput.stepDown();
2335
- targetInput.dispatchEvent(new Event("input", { bubbles: true }));
2336
- targetInput.dispatchEvent(new Event("change", { bubbles: true }));
2337
- }
2338
- return;
2339
- }
2340
-
2341
- const selectItem = e.target.closest("[data-select-value]");
2342
- if (selectItem) {
2343
- const val = selectItem.getAttribute("data-select-value");
2344
- const targetSelector =
2345
- selectItem.getAttribute("data-select-target") ||
2346
- selectItem.closest("[data-select-container]")?.getAttribute("data-select-target");
2347
- if (targetSelector) {
2348
- const targetEl = document.querySelector(targetSelector);
2349
- if (targetEl) {
2350
- if (targetEl.tagName === "INPUT" || targetEl.tagName === "SELECT") {
2351
- targetEl.value = val;
2352
- targetEl.dispatchEvent(new Event("input", { bubbles: true }));
2353
- targetEl.dispatchEvent(new Event("change", { bubbles: true }));
2354
- } else {
2355
- targetEl.textContent = selectItem.textContent.trim();
2356
- }
2357
- }
2358
- }
2359
- const parentDropdown = selectItem.closest(".dropdown-content, .popover-content");
2360
- if (parentDropdown) {
2361
- parentDropdown.classList.remove("open");
2362
- }
2363
- }
2364
-
2365
- const modalTrigger = e.target.closest("[data-toggle='modal'], [data-modal-target], [data-dialog-target]");
2366
- if (modalTrigger) {
2367
- e.preventDefault();
2368
- const targetSelector =
2369
- modalTrigger.getAttribute("data-modal-target") ||
2370
- modalTrigger.getAttribute("data-dialog-target") ||
2371
- modalTrigger.getAttribute("data-target") ||
2372
- modalTrigger.getAttribute("href");
2373
- if (targetSelector) {
2374
- const dialog = document.querySelector(targetSelector);
2375
- if (dialog && typeof dialog.showModal === "function") {
2376
- dialog.showModal();
2377
- }
2378
- }
2379
- return;
2380
- }
2381
-
2382
- const dismissTrigger = e.target.closest("[data-dismiss='modal'], [data-close-dialog], [data-close-modal]");
2383
- if (dismissTrigger) {
2384
- e.preventDefault();
2385
- const dialog =
2386
- dismissTrigger.closest("dialog") ||
2387
- document.querySelector(dismissTrigger.getAttribute("data-target") || "");
2388
- if (dialog && typeof dialog.close === "function") {
2389
- dialog.close();
2390
- }
2391
- return;
2392
- }
2393
-
2394
- const themeTrigger = e.target.closest('[data-toggle="theme"]');
2395
- if (themeTrigger) {
2396
- e.preventDefault();
2397
- const html = document.documentElement;
2398
- const current = html.getAttribute("data-theme") || (html.classList.contains("dark") ? "dark" : "light");
2399
- const next = current === "dark" ? "light" : "dark";
2400
- html.setAttribute("data-theme", next);
2401
- html.classList.toggle("dark", next === "dark");
2402
- try {
2403
- localStorage.setItem("bluebird-theme", next);
2404
- } catch (err) {}
2405
- return;
2406
- }
2407
-
2408
- const toastTrigger = e.target.closest("[data-toast]");
2409
- if (toastTrigger) {
2410
- e.preventDefault();
2411
- const desc = toastTrigger.getAttribute("data-toast") || "";
2412
- const title = toastTrigger.getAttribute("data-toast-title") || "";
2413
- const type = toastTrigger.getAttribute("data-toast-type") || "info";
2414
- if (typeof bluebird === "function") {
2415
- bluebird("toast", { title, description: desc, type });
2416
- }
2417
- return;
2418
- }
2419
-
2420
- const snackbarTrigger = e.target.closest("[data-snackbar]");
2421
- if (snackbarTrigger) {
2422
- e.preventDefault();
2423
- const message = snackbarTrigger.getAttribute("data-snackbar") || "";
2424
- const type = snackbarTrigger.getAttribute("data-snackbar-type") || "info";
2425
- if (typeof bluebird === "function") {
2426
- bluebird("snackbar", { message, type });
2427
- }
2428
- return;
2429
- }
2430
-
2431
- const actionBtn = e.target.closest("button[data-action], a[data-action]");
2432
- if (actionBtn) {
2433
- e.preventDefault();
2434
- const actionName = actionBtn.getAttribute("data-action");
2435
- if (actionName && window.Bluebird && typeof window.Bluebird.action === "function") {
2436
- let payload = {};
2437
- const rawArgs = actionBtn.getAttribute("data-args") || actionBtn.getAttribute("data-payload");
2438
- if (rawArgs) {
2439
- try {
2440
- payload = JSON.parse(rawArgs);
2441
- } catch {}
2442
- }
2443
- const partialTarget = actionBtn.getAttribute("data-partial");
2444
- window.Bluebird.action(actionName, payload, {
2445
- url: actionBtn.getAttribute("data-url") || undefined,
2446
- partial: partialTarget === "true" ? true : partialTarget || false,
2447
- });
2448
- }
2449
- return;
2450
- }
2451
-
2452
- if (!e.target.closest(".dropdown") && !e.target.closest(".popover")) {
2453
- document.querySelectorAll(".dropdown-content.open, .popover-content.open").forEach((el) => {
2454
- el.classList.remove("open");
2455
- });
2456
- }
2457
- });
2458
-
2459
- document.addEventListener("input", (e) => {
2460
- const filterInput = e.target.closest("[data-filter-target]");
2461
- if (filterInput) {
2462
- const targetSelector = filterInput.getAttribute("data-filter-target");
2463
- const targetContainer = document.querySelector(targetSelector);
2464
- if (targetContainer) {
2465
- const query = filterInput.value.toLowerCase().trim();
2466
- const items = targetContainer.querySelectorAll("[data-filter-item], li, tr, .card, .dropdown-item, .item");
2467
- let visibleCount = 0;
2468
- items.forEach((item) => {
2469
- const text = item.textContent.toLowerCase();
2470
- const matches = text.includes(query);
2471
- item.style.display = matches ? "" : "none";
2472
- if (matches) visibleCount++;
2473
- });
2474
- const emptyMsg = targetContainer.querySelector(".no-filter-results");
2475
- if (emptyMsg) {
2476
- emptyMsg.style.display = visibleCount === 0 ? "block" : "none";
2477
- }
2478
- }
2479
- }
2480
-
2481
- if (e.target.matches("textarea[data-auto-resize]")) {
2482
- const textarea = e.target;
2483
- textarea.style.height = "auto";
2484
- textarea.style.height = textarea.scrollHeight + 2 + "px";
2485
- }
2486
- });
2487
-
2488
- document.addEventListener("submit", async (e) => {
2489
- const actionForm = e.target.closest("form[data-action]");
2490
- if (actionForm && window.Bluebird && typeof window.Bluebird.action === "function") {
2491
- e.preventDefault();
2492
- const actionName = actionForm.getAttribute("data-action");
2493
- const formData = new FormData(actionForm);
2494
- const payload = {};
2495
- formData.forEach((val, key) => {
2496
- payload[key] = val;
2497
- });
2498
- const partialAttr = actionForm.getAttribute("data-partial");
2499
- const res = await window.Bluebird.action(actionName, payload, {
2500
- url: actionForm.getAttribute("action") || window.location.pathname,
2501
- partial: partialAttr === "true" ? true : partialAttr || false,
2502
- });
2503
- if (res && (res.message || res.data?.message) && typeof bluebird === "function") {
2504
- bluebird("toast", {
2505
- title: res.status === "error" ? "Error" : "Success",
2506
- description: res.message || res.data?.message,
2507
- type: res.status === "error" ? "error" : "success",
2508
- });
2509
- }
2510
- return;
2511
- }
2512
-
2513
- const form = e.target.closest("form[data-bb-form]");
2514
- if (!form) return;
2515
- e.preventDefault();
2516
- const action = form.getAttribute("action") || window.location.pathname;
2517
- const method = (form.getAttribute("method") || "POST").toUpperCase();
2518
- const formData = new FormData(form);
2519
-
2520
- const csrfEl =
2521
- document.getElementById("csrf") ||
2522
- document.querySelector('input[name="_csrf"]') ||
2523
- document.querySelector('meta[name="csrf-token"]');
2524
- const csrfToken = csrfEl ? csrfEl.value || csrfEl.getAttribute("content") : null;
2525
- if (csrfToken && !formData.has("_csrf")) {
2526
- formData.append("_csrf", csrfToken);
2527
- }
2528
-
2529
- try {
2530
- const headers = { "X-Requested-With": "XMLHttpRequest" };
2531
- if (csrfToken) headers["X-CSRF-Token"] = csrfToken;
2532
-
2533
- const res = await fetch(action, {
2534
- method,
2535
- body: formData,
2536
- headers,
2537
- credentials: "include",
2538
- });
2539
-
2540
- const redirectHeader = res.headers.get("X-Bluebird-Redirect");
2541
- if (redirectHeader) {
2542
- if (window.Bluebird && typeof window.Bluebird.navigate === "function") {
2543
- window.Bluebird.navigate(redirectHeader);
2544
- } else {
2545
- window.location.href = redirectHeader;
2546
- }
2547
- return;
2548
- }
2549
-
2550
- if (res.redirected) {
2551
- if (window.Bluebird && typeof window.Bluebird.navigate === "function") {
2552
- window.Bluebird.navigate(res.url);
2553
- } else {
2554
- window.location.href = res.url;
2555
- }
2556
- return;
2557
- }
2558
-
2559
- const contentType = res.headers.get("content-type") || "";
2560
- if (contentType.includes("application/json")) {
2561
- const json = await res.json();
2562
- if (json.message || json.msg || json.error) {
2563
- const type = res.ok ? "success" : "error";
2564
- if (typeof bluebird === "function") {
2565
- bluebird("toast", {
2566
- title: res.ok ? "Success" : "Error",
2567
- description: json.message || json.msg || json.error,
2568
- type,
2569
- });
2570
- }
2571
- }
2572
- }
2573
- } catch (err) {
2574
- if (typeof bluebird === "function") {
2575
- bluebird("toast", {
2576
- title: "Request Failed",
2577
- description: err.message,
2578
- type: "error",
2579
- });
2580
- }
2581
- }
2582
- });
2583
-
2584
- document.addEventListener("keydown", (e) => {
2585
- if ((e.ctrlKey || e.metaKey) && e.key === "k") {
2586
- e.preventDefault();
2587
- if (typeof bluebird === "function") {
2588
- bluebird("command", { action: "toggle" });
2589
- }
2590
- } else if (e.key === "Escape") {
2591
- const openCommand = document.querySelector(".command-backdrop.open");
2592
- if (openCommand && typeof bluebird === "function") {
2593
- bluebird("command", { action: "close" });
2594
- }
2595
- }
2596
- });
2597
- })();
2598
-
2599
- (function () {
2600
- function init() {
2601
- cleanupOrphanedBackdrops();
2602
- initMobileDrawer();
2603
- document.querySelectorAll(".carousel").forEach((c) => initSingleCarousel(c));
2604
- document.querySelectorAll("textarea[data-auto-resize]").forEach((t) => {
2605
- t.style.height = "auto";
2606
- t.style.height = t.scrollHeight + 2 + "px";
2607
- });
2608
- try {
2609
- const savedTheme = localStorage.getItem("bluebird-theme");
2610
- if (savedTheme) {
2611
- document.documentElement.setAttribute("data-theme", savedTheme);
2612
- document.documentElement.classList.toggle("dark", savedTheme === "dark");
2613
- }
2614
- } catch (e) {}
2615
- }
2616
-
2617
- if (document.readyState === "loading") {
2618
- document.addEventListener("DOMContentLoaded", () => setTimeout(init, 50));
2619
- } else {
2620
- setTimeout(init, 50);
2621
- }
2622
-
2623
- if (!window.__BLUEBIRD_INIT_BOUND__) {
2624
- window.__BLUEBIRD_INIT_BOUND__ = true;
2625
- window.addEventListener("bluebird:page-load", () => setTimeout(init, 20));
2626
- window.addEventListener("bluebird:partial-load", () => setTimeout(init, 20));
2627
- }
2628
- })();
2629
-
2630
- /**
2631
- * Standard fetch wrapper supporting automatic CSRF injection and JSON parsing.
2632
- * @param {string} url
2633
- * @param {string} method
2634
- * @param {Object|boolean} body
2635
- * @param {FormData|boolean} bodyForm
2636
- * @param {Object} headers
2637
- * @returns {Promise<any>}
2638
- */
2639
- async function Http(
2640
- url = "/",
2641
- method = "GET",
2642
- body = false,
2643
- bodyForm = false,
2644
- headers = {}
2645
- ) {
2646
- const csrfEl =
2647
- document.getElementById("csrf") ||
2648
- document.querySelector('input[name="_csrf"]') ||
2649
- document.querySelector('meta[name="csrf-token"]');
2650
- const csrfToken = csrfEl ? csrfEl.value || csrfEl.getAttribute("content") : null;
2651
- const mergedHeaders = { ...headers };
2652
- if (csrfToken) {
2653
- mergedHeaders["X-CSRF-Token"] = csrfToken;
2654
- }
2655
- const upperMethod = String(method || "GET").toUpperCase();
2656
- const options = { method: upperMethod, headers: mergedHeaders, credentials: "include" };
2657
- if (body) {
2658
- const payload = csrfToken ? { ...body, _csrf: csrfToken, csrf: csrfToken } : body;
2659
- options["body"] = JSON.stringify(payload);
2660
- if (!mergedHeaders["Content-Type"]) {
2661
- mergedHeaders["Content-Type"] = "application/json";
2662
- }
2663
- }
2664
- if (bodyForm) {
2665
- if (csrfToken && bodyForm instanceof FormData) {
2666
- if (!bodyForm.has("_csrf")) bodyForm.append("_csrf", csrfToken);
2667
- }
2668
- options["body"] = bodyForm;
2669
- }
2670
- if (upperMethod !== "GET" && window.Bluebird && typeof window.Bluebird.clearPrefetch === "function") {
2671
- window.Bluebird.clearPrefetch();
2672
- }
2673
- const response = await fetch(url, options);
2674
- if (!response.ok) {
2675
- let errorData;
2676
- try {
2677
- errorData = await response.json();
2678
- } catch {
2679
- errorData = { message: `HTTP Error ${response.status}: ${response.statusText}` };
2680
- }
2681
- throw new Error(errorData.message || errorData.msg || errorData.mensaje || "Fetch request failed");
2682
- }
2683
- return await response.json();
2684
- }
2685
-
2686
- /**
2687
- * Retrieves a query parameter from window.location.search.
2688
- * @param {string} name
2689
- * @returns {string|null}
2690
- */
2691
- function getUrlParameter(name) {
2692
- return new URLSearchParams(window.location.search).get(name);
2693
- }
2694
-
2695
- /**
2696
- * Checks whether the document matches the specified language.
2697
- * @param {string} l
2698
- * @returns {boolean}
2699
- */
2700
- function lang(l = "es") {
2701
- const docLang = document.documentElement.lang || "es";
2702
- return docLang === l || docLang.startsWith(l);
2703
- }
2704
-
2705
- /**
2706
- * High-performance responsive data table with search, pagination, and mobile card view.
2707
- */
2708
- class ResponsiveDataTable {
2709
- constructor(containerId, options = {}) {
2710
- this.container =
2711
- typeof containerId === "string" ? document.getElementById(containerId) : containerId;
2712
- if (!this.container) return;
2713
- this.defaults = {
2714
- data: [],
2715
- columns: [],
2716
- rowsPerPage: 10,
2717
- search: true,
2718
- pagination: true,
2719
- headerTitles: {},
2720
- summaryFields: ["id"],
2721
- edit: false,
2722
- delete: false,
2723
- breakpoint: 768,
2724
- };
2725
- this.options = { ...this.defaults, ...options };
2726
- if (options.pageSize !== undefined) this.options.rowsPerPage = options.pageSize;
2727
- if (options.searchable !== undefined) this.options.search = options.searchable;
2728
- if (options.onEdit !== undefined) this.options.edit = options.onEdit;
2729
- if (options.onDelete !== undefined) this.options.delete = options.onDelete;
2730
- this.currentPage = 1;
2731
- this.filteredData = [...this.options.data];
2732
- this.isMobile = window.innerWidth < this.options.breakpoint;
2733
- this.init();
2734
- if (this.container._bb_resize_handler) {
2735
- window.removeEventListener("resize", this.container._bb_resize_handler);
2736
- }
2737
- this._onResize = () => this.handleResize();
2738
- this.container._bb_resize_handler = this._onResize;
2739
- window.addEventListener("resize", this._onResize);
2740
- }
2741
-
2742
- init() {
2743
- this.renderContainer();
2744
- this.updateTable();
2745
- if (this.options.search) this.setupSearch();
2746
- }
2747
-
2748
- handleResize() {
2749
- const wasMobile = this.isMobile;
2750
- this.isMobile = window.innerWidth < this.options.breakpoint;
2751
- if (wasMobile !== this.isMobile) this.updateTable();
2752
- }
2753
-
2754
- renderContainer() {
2755
- this.container.innerHTML = `
2756
- <section class="w-full">
2757
- ${
2758
- this.options.search
2759
- ? `<div class="mb-4 flex items-center justify-between"><input type="search" class="datatable-search-input w-full sm:w-72 rounded-lg border border-slate-700 bg-slate-900/90 px-3.5 py-2 text-sm text-slate-100 placeholder-slate-400 focus:border-sky-500 focus:outline-none focus:ring-2 focus:ring-sky-500/20" placeholder="${lang() ? "Buscar..." : "Search..."}" aria-label="Search"/></div>`
2760
- : ""
2761
- }
2762
- <div class="overflow-x-auto rounded-xl border border-slate-800">
2763
- <table class="datatable-table w-full text-sm text-left border-collapse hidden"></table>
2764
- <div class="datatable-mobile p-3 space-y-3"></div>
2765
- </div>
2766
- ${this.options.pagination ? `<nav class="datatable-pagination mt-4 flex items-center justify-center gap-1.5" aria-label="Pagination"></nav>` : ""}
2767
- </section>`;
2768
- }
2769
-
2770
- renderTable() {
2771
- const table = this.container.querySelector(".datatable-table");
2772
- const mobileView = this.container.querySelector(".datatable-mobile");
2773
- if (!table || !mobileView) return;
2774
- if (this.isMobile) {
2775
- table.classList.add("hidden");
2776
- mobileView.classList.remove("hidden");
2777
- this.renderMobileView();
2778
- } else {
2779
- table.classList.remove("hidden");
2780
- mobileView.classList.add("hidden");
2781
- this.renderDesktopTable();
2782
- }
2783
- }
2784
-
2785
- renderDesktopTable() {
2786
- const table = this.container.querySelector(".datatable-table");
2787
- table.innerHTML = `
2788
- <thead>
2789
- <tr class="datatable-header border-b border-slate-800 bg-slate-900/70 text-xs font-semibold uppercase tracking-wider text-slate-400"></tr>
2790
- </thead>
2791
- <tbody class="datatable-body divide-y divide-slate-800/70"></tbody>`;
2792
- const headerRow = table.querySelector("thead tr");
2793
- this.options.columns.forEach((column) => {
2794
- const th = document.createElement("th");
2795
- th.scope = "col";
2796
- th.className = "px-4 py-3";
2797
- th.textContent =
2798
- this.options.headerTitles[column.key] || column.title || column.label || column.key;
2799
- headerRow.appendChild(th);
2800
- });
2801
- if (this.options.edit || this.options.delete) {
2802
- const th = document.createElement("th");
2803
- th.scope = "col";
2804
- th.className = "px-4 py-3";
2805
- th.textContent = lang() ? "Acciones" : "Actions";
2806
- headerRow.appendChild(th);
2807
- }
2808
- const startIndex = (this.currentPage - 1) * this.options.rowsPerPage;
2809
- const endIndex = startIndex + this.options.rowsPerPage;
2810
- const paginatedData = this.filteredData.slice(startIndex, endIndex);
2811
- const tbody = table.querySelector("tbody");
2812
- paginatedData.forEach((item) => {
2813
- const row = document.createElement("tr");
2814
- row.className = "hover:bg-slate-800/40 transition-colors";
2815
- this.options.columns.forEach((column) => {
2816
- const td = document.createElement("td");
2817
- td.className = "px-4 py-3 text-slate-200";
2818
- const value = item[column.key];
2819
- if (
2820
- value &&
2821
- typeof value === "string" &&
2822
- /<[a-z][\s\S]*>/i.test(value)
2823
- ) {
2824
- td.innerHTML = value;
2825
- } else {
2826
- td.textContent = value !== undefined && value !== null ? value : "-";
2827
- }
2828
- row.appendChild(td);
2829
- });
2830
- if (this.options.edit || this.options.delete) {
2831
- const td = document.createElement("td");
2832
- td.className = "px-4 py-3 text-slate-200";
2833
- const actionsDiv = document.createElement("div");
2834
- actionsDiv.className = "flex items-center gap-2";
2835
- if (this.options.edit) {
2836
- const btn = document.createElement("button");
2837
- btn.className =
2838
- "px-2.5 py-1 text-xs font-medium rounded-md border border-slate-700 text-slate-200 hover:bg-slate-800 transition-colors";
2839
- btn.textContent = lang() ? "Editar" : "Edit";
2840
- btn.onclick = (e) => this.handleAction("edit", e, item);
2841
- actionsDiv.appendChild(btn);
2842
- }
2843
- if (this.options.delete) {
2844
- const btn = document.createElement("button");
2845
- btn.className =
2846
- "px-2.5 py-1 text-xs font-medium rounded-md bg-red-500/15 text-red-400 border border-red-500/30 hover:bg-red-500/25 transition-colors";
2847
- btn.textContent = lang() ? "Eliminar" : "Delete";
2848
- btn.onclick = (e) => this.handleAction("delete", e, item);
2849
- actionsDiv.appendChild(btn);
2850
- }
2851
- td.appendChild(actionsDiv);
2852
- row.appendChild(td);
2853
- }
2854
- tbody.appendChild(row);
2855
- });
2856
- }
2857
-
2858
- renderMobileView() {
2859
- const mobileView = this.container.querySelector(".datatable-mobile");
2860
- mobileView.innerHTML = "";
2861
- const startIndex = (this.currentPage - 1) * this.options.rowsPerPage;
2862
- const endIndex = startIndex + this.options.rowsPerPage;
2863
- const paginatedData = this.filteredData.slice(startIndex, endIndex);
2864
- paginatedData.forEach((item) => {
2865
- const card = document.createElement("article");
2866
- card.className = "rounded-xl border border-slate-800 bg-slate-900/60 p-4 mb-3 shadow-xs";
2867
- const summary = document.createElement("h3");
2868
- summary.className =
2869
- "flex items-center justify-between font-semibold text-slate-100 mb-3 pb-2 border-b border-slate-800";
2870
- this.options.summaryFields.forEach((fieldKey) => {
2871
- const value = item[fieldKey];
2872
- summary.innerHTML += `<span>${escapeClientHtml(value !== undefined && value !== null ? value : "-")}</span>`;
2873
- });
2874
- card.appendChild(summary);
2875
- const details = document.createElement("dl");
2876
- details.className = "grid grid-cols-1 gap-2 mb-3 text-sm";
2877
- this.options.columns.forEach((column) => {
2878
- if (this.options.summaryFields.includes(column.key)) return;
2879
- const dt = document.createElement("dt");
2880
- dt.className = "text-xs font-semibold uppercase tracking-wider text-slate-400";
2881
- dt.textContent =
2882
- this.options.headerTitles[column.key] || column.title || column.label || column.key;
2883
- const dd = document.createElement("dd");
2884
- dd.className = "text-slate-200 mb-1";
2885
- const cellValue = item[column.key];
2886
- if (
2887
- cellValue &&
2888
- typeof cellValue === "string" &&
2889
- /<[a-z][\s\S]*>/i.test(cellValue)
2890
- ) {
2891
- dd.innerHTML = cellValue;
2892
- } else {
2893
- dd.textContent = cellValue !== undefined && cellValue !== null ? cellValue : "-";
2894
- }
2895
- details.appendChild(dt);
2896
- details.appendChild(dd);
2897
- });
2898
- card.appendChild(details);
2899
- if (this.options.edit || this.options.delete) {
2900
- const actions = document.createElement("div");
2901
- actions.className = "flex items-center gap-2 justify-end pt-2 border-t border-slate-800/60";
2902
- if (this.options.edit) {
2903
- const btn = document.createElement("button");
2904
- btn.className =
2905
- "px-2.5 py-1 text-xs font-medium rounded-md border border-slate-700 text-slate-200 hover:bg-slate-800 transition-colors";
2906
- btn.textContent = lang() ? "Editar" : "Edit";
2907
- btn.onclick = (e) => this.handleAction("edit", e, item);
2908
- actions.appendChild(btn);
2909
- }
2910
- if (this.options.delete) {
2911
- const btn = document.createElement("button");
2912
- btn.className =
2913
- "px-2.5 py-1 text-xs font-medium rounded-md bg-red-500/15 text-red-400 border border-red-500/30 hover:bg-red-500/25 transition-colors";
2914
- btn.textContent = lang() ? "Eliminar" : "Delete";
2915
- btn.onclick = (e) => this.handleAction("delete", e, item);
2916
- actions.appendChild(btn);
2917
- }
2918
- card.appendChild(actions);
2919
- }
2920
- mobileView.appendChild(card);
2921
- });
2922
- }
2923
-
2924
- renderPagination() {
2925
- const pagination = this.container.querySelector(".datatable-pagination");
2926
- if (!pagination || !this.options.pagination) return;
2927
- pagination.innerHTML = "";
2928
- const pageCount = Math.ceil(this.filteredData.length / this.options.rowsPerPage);
2929
- if (pageCount <= 1) return;
2930
- const baseClass =
2931
- "px-3 py-1.5 text-xs font-medium rounded-lg border border-slate-800 bg-slate-900 text-slate-300 hover:bg-slate-800 disabled:opacity-40 disabled:pointer-events-none transition-colors";
2932
- const activeClass =
2933
- "px-3 py-1.5 text-xs font-semibold rounded-lg bg-sky-500 text-slate-950 border border-sky-400";
2934
- const prevButton = document.createElement("button");
2935
- prevButton.textContent = "«";
2936
- prevButton.className = baseClass;
2937
- prevButton.disabled = this.currentPage === 1;
2938
- prevButton.onclick = () => this.changePage(this.currentPage - 1);
2939
- pagination.appendChild(prevButton);
2940
- const maxVisible = 5;
2941
- let start = Math.max(1, this.currentPage - Math.floor(maxVisible / 2));
2942
- let end = start + maxVisible - 1;
2943
- if (end > pageCount) {
2944
- end = pageCount;
2945
- start = Math.max(1, end - maxVisible + 1);
2946
- }
2947
- if (start > 1) {
2948
- const firstButton = document.createElement("button");
2949
- firstButton.className = baseClass;
2950
- firstButton.textContent = "1";
2951
- firstButton.onclick = () => this.changePage(1);
2952
- pagination.appendChild(firstButton);
2953
- if (start > 2) pagination.appendChild(this.createEllipsis());
2954
- }
2955
- for (let i = start; i <= end; i++) {
2956
- const button = document.createElement("button");
2957
- button.className = i === this.currentPage ? activeClass : baseClass;
2958
- button.textContent = i;
2959
- button.onclick = () => this.changePage(i);
2960
- pagination.appendChild(button);
2961
- }
2962
- if (end < pageCount) {
2963
- if (end < pageCount - 1) pagination.appendChild(this.createEllipsis());
2964
- const lastButton = document.createElement("button");
2965
- lastButton.className = baseClass;
2966
- lastButton.textContent = pageCount;
2967
- lastButton.onclick = () => this.changePage(pageCount);
2968
- pagination.appendChild(lastButton);
2969
- }
2970
- const nextButton = document.createElement("button");
2971
- nextButton.className = baseClass;
2972
- nextButton.textContent = "»";
2973
- nextButton.disabled = this.currentPage === pageCount;
2974
- nextButton.onclick = () => this.changePage(this.currentPage + 1);
2975
- pagination.appendChild(nextButton);
2976
- }
2977
-
2978
- createEllipsis() {
2979
- const span = document.createElement("span");
2980
- span.className = "px-2 text-xs text-slate-500";
2981
- span.textContent = "...";
2982
- return span;
2983
- }
2984
-
2985
- changePage(page) {
2986
- this.currentPage = page;
2987
- this.updateTable();
2988
- }
2989
-
2990
- handleAction(type, event, item) {
2991
- if (!this.options[type]) return;
2992
- const callback =
2993
- typeof this.options[type] === "function"
2994
- ? this.options[type]
2995
- : window[this.options[type]];
2996
- if (typeof callback === "function") callback(event, item.id || item);
2997
- }
2998
-
2999
- setupSearch() {
3000
- const searchInput = this.container.querySelector(".datatable-search-input");
3001
- if (!searchInput) return;
3002
- searchInput.addEventListener("input", (e) => {
3003
- const term = e.target.value.toLowerCase().trim();
3004
- this.filteredData = this.options.data.filter((item) =>
3005
- this.options.columns.some((column) =>
3006
- String(item[column.key] || "")
3007
- .toLowerCase()
3008
- .includes(term)
3009
- )
3010
- );
3011
- this.currentPage = 1;
3012
- this.updateTable();
3013
- });
3014
- }
3015
-
3016
- updateTable() {
3017
- this.renderTable();
3018
- if (this.options.pagination) this.renderPagination();
3019
- }
3020
-
3021
- updateData(newData) {
3022
- this.options.data = newData;
3023
- this.filteredData = [...newData];
3024
- this.currentPage = 1;
3025
- this.updateTable();
3026
- }
3027
-
3028
- updateColumns(newColumns) {
3029
- this.options.columns = newColumns;
3030
- this.updateTable();
3031
- }
3032
- }
3033
-
3034
- if (typeof window !== "undefined") {
3035
- window.ResponsiveDataTable = ResponsiveDataTable;
3036
- window.Http = Http;
3037
- window.getUrlParameter = getUrlParameter;
3038
- window.snackbar = snackbar;
3039
- window.toast = toast;
3040
- window.bluebird = bluebird;
3041
- window.dismissToast = dismissToast;
3042
- window.initMobileDrawer = initMobileDrawer;
3043
- window.initSingleCarousel = initSingleCarousel;
3044
- window.lang = lang;
1636
+ drainMountQueue();
1637
+ initDevReload();
1638
+ const detail = { url: window.location.href, initial: true };
1639
+ window.dispatchEvent(new CustomEvent("bluebird:page-load", { detail }));
1640
+ document.dispatchEvent(new CustomEvent("bluebird:page-load", { detail }));
1641
+ }
1642
+
1643
+ if (document.readyState === "loading") {
1644
+ document.addEventListener("DOMContentLoaded", triggerInitialLoad);
1645
+ } else {
1646
+ triggerInitialLoad();
1647
+ }
1648
+ })();
1649
+ /**
1650
+ * Bluebird Client UI & Interactive Runtime.
1651
+ * Styled with Tailwind CSS v4 and designed for SPA navigation and desktop apps.
1652
+ */
1653
+
1654
+ /**
1655
+ * Escapes HTML special characters in client-side strings.
1656
+ * @param {any} str
1657
+ * @returns {string}
1658
+ */
1659
+ function escapeClientHtml(str) {
1660
+ if (str === null || str === undefined) return "";
1661
+ return String(str)
1662
+ .replace(/&/g, "&amp;")
1663
+ .replace(/</g, "&lt;")
1664
+ .replace(/>/g, "&gt;")
1665
+ .replace(/"/g, "&quot;")
1666
+ .replace(/'/g, "&#39;");
1667
+ }
1668
+
1669
+ let customCommandsList = null;
1670
+ if (typeof window !== "undefined") {
1671
+ window.Bluebird = window.Bluebird || {};
1672
+ window.Bluebird.setCommands = function (items) {
1673
+ customCommandsList = Array.isArray(items) ? items : null;
1674
+ };
1675
+ }
1676
+
1677
+ /**
1678
+ * Global component dispatcher for Bluebird interactive widgets.
1679
+ * @param {string|Object} component
1680
+ * @param {Object} [options]
1681
+ */
1682
+ function bluebird(component, options) {
1683
+ if (typeof component === "object") {
1684
+ options = component;
1685
+ component = "snackbar";
1686
+ }
1687
+
1688
+ if (component === "snackbar") {
1689
+ let snackbarEl = document.getElementById("snackbar");
1690
+ if (!snackbarEl) {
1691
+ snackbarEl = document.createElement("div");
1692
+ snackbarEl.id = "snackbar";
1693
+ document.body.appendChild(snackbarEl);
1694
+ }
1695
+
1696
+ const type = (options && options.type) || "info";
1697
+ let colorClasses = "bg-slate-900 text-slate-100 border border-slate-700/80";
1698
+ if (type === "success") {
1699
+ colorClasses = "bg-emerald-950/95 text-emerald-100 border border-emerald-500/40";
1700
+ } else if (type === "warning") {
1701
+ colorClasses = "bg-amber-950/95 text-amber-100 border border-amber-500/40";
1702
+ } else if (type === "error" || type === "danger") {
1703
+ colorClasses = "bg-red-950/95 text-red-100 border border-red-500/40";
1704
+ }
1705
+
1706
+ const baseClasses =
1707
+ "fixed bottom-5 left-1/2 -translate-x-1/2 z-[100] flex items-center gap-3 px-5 py-3 rounded-xl shadow-2xl text-sm font-medium transition-all duration-300";
1708
+ snackbarEl.className = `${baseClasses} ${colorClasses} opacity-0 translate-y-4 pointer-events-none`;
1709
+ snackbarEl.textContent = (options && options.message) || "";
1710
+
1711
+ setTimeout(() => {
1712
+ snackbarEl.classList.remove("opacity-0", "translate-y-4", "pointer-events-none");
1713
+ snackbarEl.classList.add("opacity-100", "translate-y-0", "pointer-events-auto");
1714
+ }, 10);
1715
+
1716
+ const duration = (options && options.duration) || 3000;
1717
+ if (snackbarEl.timeoutId) {
1718
+ clearTimeout(snackbarEl.timeoutId);
1719
+ }
1720
+ snackbarEl.timeoutId = setTimeout(function () {
1721
+ snackbarEl.classList.remove("opacity-100", "translate-y-0", "pointer-events-auto");
1722
+ snackbarEl.classList.add("opacity-0", "translate-y-4", "pointer-events-none");
1723
+ }, duration);
1724
+ }
1725
+
1726
+ if (component === "toast") {
1727
+ const position = (options && options.position) || "bottom-right";
1728
+ const posMap = {
1729
+ "bottom-right": "fixed bottom-4 right-4 z-[100] flex flex-col gap-2.5 w-full max-w-sm pointer-events-none",
1730
+ "bottom-left": "fixed bottom-4 left-4 z-[100] flex flex-col gap-2.5 w-full max-w-sm pointer-events-none",
1731
+ "top-right": "fixed top-4 right-4 z-[100] flex flex-col gap-2.5 w-full max-w-sm pointer-events-none",
1732
+ "top-left": "fixed top-4 left-4 z-[100] flex flex-col gap-2.5 w-full max-w-sm pointer-events-none",
1733
+ "top-center": "fixed top-4 left-1/2 -translate-x-1/2 z-[100] flex flex-col gap-2.5 w-full max-w-sm pointer-events-none",
1734
+ "bottom-center": "fixed bottom-4 left-1/2 -translate-x-1/2 z-[100] flex flex-col gap-2.5 w-full max-w-sm pointer-events-none",
1735
+ };
1736
+ const containerClass = posMap[position] || posMap["bottom-right"];
1737
+ let container = document.querySelector(`.toast-container[data-position="${position}"]`);
1738
+ if (!container) {
1739
+ container = document.createElement("div");
1740
+ container.className = `toast-container ${containerClass}`;
1741
+ container.setAttribute("data-position", position);
1742
+ document.body.appendChild(container);
1743
+ }
1744
+
1745
+ const toastEl = document.createElement("div");
1746
+ const type = (options && options.type) || "info";
1747
+ let variantClass = "bg-slate-900/95 border-slate-700/80 text-slate-100";
1748
+ if (type === "success") {
1749
+ variantClass = "bg-slate-900/95 border-emerald-500/40 text-slate-100";
1750
+ } else if (type === "error" || type === "danger") {
1751
+ variantClass = "bg-slate-900/95 border-red-500/40 text-slate-100";
1752
+ } else if (type === "warning") {
1753
+ variantClass = "bg-slate-900/95 border-amber-500/40 text-slate-100";
1754
+ }
1755
+
1756
+ toastEl.className = `toast pointer-events-auto flex items-start justify-between gap-3 p-4 rounded-xl border shadow-xl backdrop-blur-md transition-all duration-200 ${variantClass}`;
1757
+ const title = options && options.title
1758
+ ? `<div class="toast-title font-semibold text-sm">${escapeClientHtml(options.title)}</div>`
1759
+ : "";
1760
+ const desc = options && options.description
1761
+ ? `<div class="toast-description text-xs text-slate-300 mt-0.5 leading-relaxed">${escapeClientHtml(options.description)}</div>`
1762
+ : "";
1763
+
1764
+ toastEl.innerHTML = `
1765
+ <div class="toast-content flex-1 min-w-0">
1766
+ ${title}
1767
+ ${desc}
1768
+ </div>
1769
+ <button class="toast-close shrink-0 rounded-lg p-1 text-slate-400 hover:text-white hover:bg-slate-800 transition-colors leading-none" aria-label="Dismiss">&times;</button>
1770
+ `;
1771
+
1772
+ const closeBtn = toastEl.querySelector(".toast-close");
1773
+ closeBtn.addEventListener("click", () => dismissToast(toastEl));
1774
+ container.appendChild(toastEl);
1775
+
1776
+ const duration = (options && options.duration) !== undefined ? options.duration : 4000;
1777
+ if (duration > 0) {
1778
+ setTimeout(() => dismissToast(toastEl), duration);
1779
+ }
1780
+ }
1781
+
1782
+ if (component === "tab") {
1783
+ const targetId = options && options.id;
1784
+ if (!targetId) return;
1785
+ const targetContent = document.getElementById(targetId);
1786
+ if (!targetContent) return;
1787
+
1788
+ const tabsContainer = targetContent.closest(".tabs") || document.body;
1789
+ const allTriggers = tabsContainer.querySelectorAll(".tab-trigger, [data-tab-target]");
1790
+ const allContents = tabsContainer.querySelectorAll(".tab-content, [data-tab-content]");
1791
+
1792
+ allContents.forEach((c) => {
1793
+ c.classList.remove("active", "block");
1794
+ c.classList.add("hidden");
1795
+ });
1796
+ allTriggers.forEach((t) => {
1797
+ t.classList.remove("active", "border-sky-500", "text-sky-400");
1798
+ t.setAttribute("aria-selected", "false");
1799
+ });
1800
+
1801
+ targetContent.classList.remove("hidden");
1802
+ targetContent.classList.add("active", "block");
1803
+
1804
+ const matchingTrigger = Array.from(allTriggers).find(
1805
+ (t) =>
1806
+ t.getAttribute("data-tab-target") === targetId ||
1807
+ t.getAttribute("href") === `#${targetId}`
1808
+ );
1809
+ if (matchingTrigger) {
1810
+ matchingTrigger.classList.add("active", "border-sky-500", "text-sky-400");
1811
+ matchingTrigger.setAttribute("aria-selected", "true");
1812
+ }
1813
+ }
1814
+
1815
+ if (component === "command") {
1816
+ const action = (options && options.action) || "toggle";
1817
+ let backdrop = document.querySelector(".command-backdrop");
1818
+ if (!backdrop) {
1819
+ backdrop = createCommandPaletteModal();
1820
+ }
1821
+ const isOpen = backdrop.classList.contains("open");
1822
+ if (action === "open" || (action === "toggle" && !isOpen)) {
1823
+ backdrop.classList.remove("hidden");
1824
+ backdrop.classList.add("flex", "open");
1825
+ const input = backdrop.querySelector(".command-input");
1826
+ if (input) {
1827
+ input.value = "";
1828
+ setTimeout(() => input.focus(), 50);
1829
+ }
1830
+ } else if (action === "close" || (action === "toggle" && isOpen)) {
1831
+ backdrop.classList.remove("flex", "open");
1832
+ backdrop.classList.add("hidden");
1833
+ }
1834
+ }
1835
+
1836
+ if (component === "popover") {
1837
+ const id = options && (options.id || options.targetId);
1838
+ const action = (options && options.action) || "toggle";
1839
+ if (!id) return;
1840
+ const popoverEl =
1841
+ document.getElementById(id) || document.querySelector(`[data-popover-id="${id}"]`);
1842
+ if (!popoverEl) return;
1843
+ const isOpen = popoverEl.classList.contains("open");
1844
+ const shouldOpen = action === "open" || (action === "toggle" && !isOpen);
1845
+ popoverEl.classList.toggle("hidden", !shouldOpen);
1846
+ popoverEl.classList.toggle("open", shouldOpen);
1847
+ }
1848
+
1849
+ if (component === "drawer") {
1850
+ cleanupOrphanedBackdrops();
1851
+ const id = options && options.id;
1852
+ const action = (options && options.action) || "toggle";
1853
+ if (!id) return;
1854
+ const drawerEl = document.getElementById(id);
1855
+ if (!drawerEl) return;
1856
+
1857
+ let overlay = document.querySelector(`.drawer-backdrop[data-for="${id}"]`);
1858
+ if (!overlay) {
1859
+ overlay = document.createElement("div");
1860
+ overlay.className =
1861
+ "drawer-backdrop fixed inset-0 z-40 bg-slate-950/60 backdrop-blur-xs transition-opacity duration-300 opacity-0 pointer-events-none";
1862
+ overlay.setAttribute("data-for", id);
1863
+ document.body.appendChild(overlay);
1864
+ overlay.addEventListener("click", () => {
1865
+ bluebird("drawer", { id, action: "close" });
1866
+ });
1867
+ }
1868
+
1869
+ const isOpen = drawerEl.classList.contains("open") || drawerEl.classList.contains("active");
1870
+ if (action === "open" || (action === "toggle" && !isOpen)) {
1871
+ drawerEl.classList.add("open");
1872
+ drawerEl.classList.remove("-translate-x-full");
1873
+ drawerEl.classList.add("translate-x-0");
1874
+ overlay.classList.remove("opacity-0", "pointer-events-none");
1875
+ overlay.classList.add("opacity-100", "pointer-events-auto", "open");
1876
+ document.body.style.overflow = "hidden";
1877
+ } else if (action === "close" || (action === "toggle" && isOpen)) {
1878
+ drawerEl.classList.remove("open", "translate-x-0");
1879
+ drawerEl.classList.add("-translate-x-full");
1880
+ overlay.classList.remove("opacity-100", "pointer-events-auto", "open");
1881
+ overlay.classList.add("opacity-0", "pointer-events-none");
1882
+ document.body.style.overflow = "";
1883
+ setTimeout(() => {
1884
+ if (overlay && overlay.parentNode && !drawerEl.classList.contains("open")) {
1885
+ overlay.remove();
1886
+ }
1887
+ }, 300);
1888
+ }
1889
+ }
1890
+
1891
+ if (component === "carousel") {
1892
+ const selector = (options && options.selector) || ".carousel";
1893
+ const carousels = document.querySelectorAll(selector);
1894
+ carousels.forEach((carousel) => initSingleCarousel(carousel, options));
1895
+ }
1896
+
1897
+ if (component === "datatable" || component === "table") {
1898
+ const containerId = (options && (options.container || options.id)) || "datatable";
1899
+ return new ResponsiveDataTable(containerId, options);
1900
+ }
1901
+ }
1902
+
1903
+ /**
1904
+ * Display a temporary snackbar message.
1905
+ * @param {Object} options
1906
+ */
1907
+ function snackbar(options) {
1908
+ bluebird("snackbar", options);
1909
+ }
1910
+
1911
+ /**
1912
+ * Display a temporary toast notification.
1913
+ * @param {Object} options
1914
+ */
1915
+ function toast(options) {
1916
+ bluebird("toast", options);
1917
+ }
1918
+
1919
+ /**
1920
+ * Dismisses a toast element with animation.
1921
+ * @param {HTMLElement} toastEl
1922
+ */
1923
+ function dismissToast(toastEl) {
1924
+ if (!toastEl || toastEl.isDismissing) return;
1925
+ toastEl.isDismissing = true;
1926
+ toastEl.style.opacity = "0";
1927
+ toastEl.style.transform = "translateY(-10px) scale(0.95)";
1928
+ setTimeout(() => {
1929
+ if (toastEl.parentNode) {
1930
+ toastEl.remove();
1931
+ }
1932
+ }, 200);
1933
+ }
1934
+
1935
+ /**
1936
+ * Creates and injects the global command palette modal.
1937
+ * @returns {HTMLElement}
1938
+ */
1939
+ function createCommandPaletteModal() {
1940
+ const backdrop = document.createElement("div");
1941
+ backdrop.className =
1942
+ "command-backdrop fixed inset-0 z-[100] hidden items-start justify-center bg-slate-950/70 backdrop-blur-xs pt-[14vh] px-4";
1943
+
1944
+ let itemsHtml = "";
1945
+ if (customCommandsList && customCommandsList.length > 0) {
1946
+ itemsHtml = customCommandsList
1947
+ .map(
1948
+ (item) => `
1949
+ <div class="command-item flex items-center justify-between px-3 py-2 rounded-lg text-sm text-slate-300 hover:bg-sky-500/15 hover:text-sky-400 cursor-pointer transition-colors" data-navigate="${escapeClientHtml(item.url || item.href || "")}">
1950
+ <span>${escapeClientHtml(item.label || item.title || item.name)}</span>
1951
+ <kbd class="text-[10px] px-1.5 py-0.5 rounded bg-slate-800 text-slate-400 border border-slate-700">↵</kbd>
1952
+ </div>
1953
+ `
1954
+ )
1955
+ .join("");
1956
+ } else {
1957
+ itemsHtml = `
1958
+ <div class="command-group space-y-1">
1959
+ <div class="command-group-title px-3 py-1 text-[11px] font-semibold uppercase tracking-wider text-slate-500">Navigation</div>
1960
+ <div class="command-item flex items-center justify-between px-3 py-2 rounded-lg text-sm text-slate-300 hover:bg-sky-500/15 hover:text-sky-400 cursor-pointer transition-colors" data-navigate="/"><span>Home</span><kbd class="text-[10px] px-1.5 py-0.5 rounded bg-slate-800 text-slate-400 border border-slate-700">↵</kbd></div>
1961
+ <div class="command-item flex items-center justify-between px-3 py-2 rounded-lg text-sm text-slate-300 hover:bg-sky-500/15 hover:text-sky-400 cursor-pointer transition-colors" data-navigate="/about"><span>About Us</span><kbd class="text-[10px] px-1.5 py-0.5 rounded bg-slate-800 text-slate-400 border border-slate-700">↵</kbd></div>
1962
+ <div class="command-item flex items-center justify-between px-3 py-2 rounded-lg text-sm text-slate-300 hover:bg-sky-500/15 hover:text-sky-400 cursor-pointer transition-colors" data-navigate="/login"><span>Login</span><kbd class="text-[10px] px-1.5 py-0.5 rounded bg-slate-800 text-slate-400 border border-slate-700">↵</kbd></div>
1963
+ <div class="command-item flex items-center justify-between px-3 py-2 rounded-lg text-sm text-slate-300 hover:bg-sky-500/15 hover:text-sky-400 cursor-pointer transition-colors" data-navigate="/dashboard"><span>Dashboard</span><kbd class="text-[10px] px-1.5 py-0.5 rounded bg-slate-800 text-slate-400 border border-slate-700">↵</kbd></div>
1964
+ </div>
1965
+ `;
1966
+ }
1967
+
1968
+ backdrop.innerHTML = `
1969
+ <div class="command-dialog w-full max-w-lg rounded-2xl border border-slate-800 bg-slate-900 text-slate-100 shadow-2xl overflow-hidden">
1970
+ <div class="command-input-wrapper flex items-center gap-3 px-4 py-3 border-b border-slate-800">
1971
+ <span class="text-slate-400">🔍</span>
1972
+ <input type="text" class="command-input w-full bg-transparent text-sm text-slate-100 placeholder-slate-500 focus:outline-none" placeholder="Type a command or search..." />
1973
+ <kbd class="text-[10px] px-1.5 py-0.5 rounded bg-slate-800 text-slate-400 border border-slate-700">ESC</kbd>
1974
+ </div>
1975
+ <div class="command-list max-h-80 overflow-y-auto p-2 space-y-2">
1976
+ ${itemsHtml}
1977
+ </div>
1978
+ </div>
1979
+ `;
1980
+
1981
+ document.body.appendChild(backdrop);
1982
+ backdrop.addEventListener("click", (e) => {
1983
+ if (e.target === backdrop) {
1984
+ bluebird("command", { action: "close" });
1985
+ }
1986
+ });
1987
+
1988
+ const input = backdrop.querySelector(".command-input");
1989
+ input.addEventListener("input", (e) => {
1990
+ const query = e.target.value.toLowerCase().trim();
1991
+ const items = backdrop.querySelectorAll(".command-item");
1992
+ items.forEach((item) => {
1993
+ const text = item.textContent.toLowerCase();
1994
+ item.style.display = text.includes(query) ? "flex" : "none";
1995
+ });
1996
+ });
1997
+
1998
+ backdrop.addEventListener("click", (e) => {
1999
+ const item = e.target.closest(".command-item");
2000
+ if (item && item.getAttribute("data-navigate")) {
2001
+ const dest = item.getAttribute("data-navigate");
2002
+ if (dest.startsWith("/") && window.Bluebird && typeof window.Bluebird.navigate === "function") {
2003
+ window.Bluebird.navigate(dest);
2004
+ } else {
2005
+ window.location.href = dest;
2006
+ }
2007
+ bluebird("command", { action: "close" });
2008
+ }
2009
+ });
2010
+
2011
+ return backdrop;
2012
+ }
2013
+
2014
+ /**
2015
+ * Removes backdrops whose associated elements are no longer in the DOM.
2016
+ */
2017
+ function cleanupOrphanedBackdrops() {
2018
+ document.querySelectorAll(".drawer-backdrop[data-for]").forEach((backdrop) => {
2019
+ const targetId = backdrop.getAttribute("data-for");
2020
+ if (!document.getElementById(targetId)) {
2021
+ backdrop.remove();
2022
+ }
2023
+ });
2024
+ }
2025
+
2026
+ /**
2027
+ * Initializes responsive mobile drawer navigation menu.
2028
+ */
2029
+ function initMobileDrawer() {
2030
+ const mainEl = document.querySelector("main");
2031
+ const aside = mainEl ? mainEl.querySelector(":scope > aside") : null;
2032
+ if (!aside) return;
2033
+
2034
+ let overlay = document.querySelector(".bluebird-drawer-overlay");
2035
+ if (!overlay) {
2036
+ overlay = document.createElement("div");
2037
+ overlay.className =
2038
+ "bluebird-drawer-overlay fixed inset-0 z-40 bg-slate-950/60 backdrop-blur-xs hidden";
2039
+ document.body.appendChild(overlay);
2040
+ }
2041
+
2042
+ let drawer = document.querySelector(".bluebird-drawer");
2043
+ if (!drawer) {
2044
+ drawer = document.createElement("div");
2045
+ drawer.className =
2046
+ "bluebird-drawer fixed top-0 left-0 z-50 h-full w-72 max-w-[80vw] bg-slate-900 border-r border-slate-800 p-5 overflow-y-auto transition-transform duration-300 -translate-x-full flex flex-col gap-2";
2047
+ document.body.appendChild(drawer);
2048
+ }
2049
+ drawer.innerHTML = aside.innerHTML;
2050
+
2051
+ let toggle = document.querySelector(".bluebird-drawer-toggle");
2052
+ if (!toggle) {
2053
+ toggle = document.createElement("button");
2054
+ toggle.className =
2055
+ "bluebird-drawer-toggle md:hidden inline-flex items-center justify-center p-2 rounded-lg text-slate-300 hover:text-white hover:bg-slate-800 transition-colors mr-2";
2056
+ toggle.innerHTML = '<span class="text-lg leading-none">☰</span>';
2057
+ toggle.setAttribute("aria-label", "Toggle navigation menu");
2058
+ const header = document.querySelector("header");
2059
+ if (header) {
2060
+ const nav = header.querySelector("nav");
2061
+ if (nav) {
2062
+ nav.insertBefore(toggle, nav.firstChild);
2063
+ } else {
2064
+ header.prepend(toggle);
2065
+ }
2066
+ } else {
2067
+ document.body.prepend(toggle);
2068
+ }
2069
+ }
2070
+ }
2071
+
2072
+ /**
2073
+ * Initializes a single carousel container.
2074
+ * @param {HTMLElement} carousel
2075
+ * @param {Object} [opts]
2076
+ */
2077
+ function initSingleCarousel(carousel, opts = {}) {
2078
+ if (carousel._bb_initialized) return;
2079
+ carousel._bb_initialized = true;
2080
+
2081
+ const track = carousel.querySelector(".carousel-track");
2082
+ if (!track) return;
2083
+ track.classList.add("flex", "overflow-x-auto", "snap-x", "snap-mandatory", "scroll-smooth", "gap-4");
2084
+
2085
+ const items = Array.from(track.querySelectorAll(".carousel-item, .carousel-card"));
2086
+ if (items.length === 0) return;
2087
+
2088
+ const prevBtn = carousel.querySelector(".carousel-prev");
2089
+ const nextBtn = carousel.querySelector(".carousel-next");
2090
+ let indicatorsContainer = carousel.querySelector(".carousel-indicators");
2091
+ let currentSlideIndex = 0;
2092
+
2093
+ if (indicatorsContainer && indicatorsContainer.children.length === 0) {
2094
+ items.forEach((_, idx) => {
2095
+ const dot = document.createElement("button");
2096
+ dot.className = `carousel-dot w-2.5 h-2.5 rounded-full transition-all ${
2097
+ idx === 0 ? "bg-sky-400 w-5" : "bg-slate-600"
2098
+ }`;
2099
+ dot.setAttribute("aria-label", `Go to slide ${idx + 1}`);
2100
+ dot.addEventListener("click", (e) => {
2101
+ e.preventDefault();
2102
+ scrollToSlide(idx);
2103
+ });
2104
+ indicatorsContainer.appendChild(dot);
2105
+ });
2106
+ }
2107
+
2108
+ function scrollToSlide(index) {
2109
+ if (index < 0) index = 0;
2110
+ if (index >= items.length) index = items.length - 1;
2111
+ currentSlideIndex = index;
2112
+ const targetItem = items[index];
2113
+ if (targetItem) {
2114
+ track.scrollTo({
2115
+ left: targetItem.offsetLeft - track.offsetLeft,
2116
+ behavior: "smooth",
2117
+ });
2118
+ updateIndicators(index);
2119
+ }
2120
+ }
2121
+
2122
+ function updateIndicators(activeIndex) {
2123
+ if (!indicatorsContainer) return;
2124
+ const dots = Array.from(indicatorsContainer.children);
2125
+ dots.forEach((dot, idx) => {
2126
+ if (idx === activeIndex) {
2127
+ dot.className = "carousel-dot w-5 h-2.5 rounded-full transition-all bg-sky-400";
2128
+ } else {
2129
+ dot.className = "carousel-dot w-2.5 h-2.5 rounded-full transition-all bg-slate-600";
2130
+ }
2131
+ });
2132
+ }
2133
+
2134
+ let scrollTimeout;
2135
+ track.addEventListener("scroll", () => {
2136
+ clearTimeout(scrollTimeout);
2137
+ scrollTimeout = setTimeout(() => {
2138
+ const trackLeft = track.scrollLeft;
2139
+ let closestIndex = 0;
2140
+ let minDistance = Infinity;
2141
+ items.forEach((item, idx) => {
2142
+ const distance = Math.abs(item.offsetLeft - track.offsetLeft - trackLeft);
2143
+ if (distance < minDistance) {
2144
+ minDistance = distance;
2145
+ closestIndex = idx;
2146
+ }
2147
+ });
2148
+ currentSlideIndex = closestIndex;
2149
+ updateIndicators(closestIndex);
2150
+ }, 40);
2151
+ });
2152
+
2153
+ if (prevBtn) {
2154
+ prevBtn.addEventListener("click", (e) => {
2155
+ e.preventDefault();
2156
+ e.stopPropagation();
2157
+ scrollToSlide(currentSlideIndex - 1);
2158
+ });
2159
+ }
2160
+ if (nextBtn) {
2161
+ nextBtn.addEventListener("click", (e) => {
2162
+ e.preventDefault();
2163
+ e.stopPropagation();
2164
+ scrollToSlide(currentSlideIndex + 1);
2165
+ });
2166
+ }
2167
+
2168
+ let startX = 0;
2169
+ let isDragging = false;
2170
+ track.addEventListener(
2171
+ "touchstart",
2172
+ (e) => {
2173
+ startX = e.touches[0].clientX;
2174
+ isDragging = true;
2175
+ },
2176
+ { passive: true }
2177
+ );
2178
+
2179
+ track.addEventListener("touchend", (e) => {
2180
+ if (!isDragging) return;
2181
+ isDragging = false;
2182
+ const endX = e.changedTouches[0].clientX;
2183
+ const diffX = startX - endX;
2184
+ if (Math.abs(diffX) > 35) {
2185
+ if (diffX > 0) {
2186
+ scrollToSlide(currentSlideIndex + 1);
2187
+ } else {
2188
+ scrollToSlide(currentSlideIndex - 1);
2189
+ }
2190
+ }
2191
+ });
2192
+
2193
+ track.addEventListener("mousedown", (e) => {
2194
+ startX = e.clientX;
2195
+ isDragging = true;
2196
+ track.style.cursor = "grabbing";
2197
+ });
2198
+
2199
+ track.addEventListener("mouseleave", () => {
2200
+ isDragging = false;
2201
+ track.style.cursor = "grab";
2202
+ });
2203
+
2204
+ track.addEventListener("mouseup", (e) => {
2205
+ if (!isDragging) return;
2206
+ isDragging = false;
2207
+ track.style.cursor = "grab";
2208
+ const endX = e.clientX;
2209
+ const diffX = startX - endX;
2210
+ if (Math.abs(diffX) > 35) {
2211
+ if (diffX > 0) {
2212
+ scrollToSlide(currentSlideIndex + 1);
2213
+ } else {
2214
+ scrollToSlide(currentSlideIndex - 1);
2215
+ }
2216
+ }
2217
+ });
2218
+
2219
+ const isAutoplay =
2220
+ (opts && opts.autoplay) || carousel.getAttribute("data-autoplay") === "true";
2221
+ const intervalTime = parseInt(
2222
+ (opts && opts.interval) || carousel.getAttribute("data-interval") || 3500,
2223
+ 10
2224
+ );
2225
+
2226
+ if (isAutoplay) {
2227
+ let autoInterval = setInterval(() => {
2228
+ const nextIdx = (currentSlideIndex + 1) % items.length;
2229
+ scrollToSlide(nextIdx);
2230
+ }, intervalTime);
2231
+ carousel.addEventListener("mouseenter", () => clearInterval(autoInterval));
2232
+ carousel.addEventListener("mouseleave", () => {
2233
+ autoInterval = setInterval(() => {
2234
+ const nextIdx = (currentSlideIndex + 1) % items.length;
2235
+ scrollToSlide(nextIdx);
2236
+ }, intervalTime);
2237
+ });
2238
+ }
2239
+ }
2240
+
2241
+ (function setupDeclarativeListeners() {
2242
+ if (window.__BLUEBIRD_UI_BOUND__) return;
2243
+ window.__BLUEBIRD_UI_BOUND__ = true;
2244
+
2245
+ document.addEventListener("click", (e) => {
2246
+ const tabTrigger = e.target.closest("[data-tab-target], .tab-trigger");
2247
+ if (tabTrigger) {
2248
+ const targetId =
2249
+ tabTrigger.getAttribute("data-tab-target") ||
2250
+ (tabTrigger.getAttribute("href") || "").replace("#", "");
2251
+ if (targetId) {
2252
+ e.preventDefault();
2253
+ bluebird("tab", { id: targetId });
2254
+ }
2255
+ }
2256
+
2257
+ const popoverTrigger = e.target.closest("[data-popover-target]");
2258
+ if (popoverTrigger) {
2259
+ const popoverId = popoverTrigger.getAttribute("data-popover-target");
2260
+ bluebird("popover", { id: popoverId, action: "toggle" });
2261
+ }
2262
+ if (!e.target.closest(".popover") && !e.target.closest("[data-popover-target]")) {
2263
+ document.querySelectorAll(".popover.open").forEach((p) => {
2264
+ p.classList.remove("open");
2265
+ p.classList.add("hidden");
2266
+ });
2267
+ }
2268
+
2269
+ const mobileToggle = e.target.closest(".bluebird-drawer-toggle");
2270
+ if (mobileToggle) {
2271
+ e.preventDefault();
2272
+ e.stopPropagation();
2273
+ initMobileDrawer();
2274
+ const drawer = document.querySelector(".bluebird-drawer");
2275
+ const overlay = document.querySelector(".bluebird-drawer-overlay");
2276
+ if (drawer && overlay) {
2277
+ const isOpen = drawer.classList.contains("open");
2278
+ if (isOpen) {
2279
+ drawer.classList.remove("open", "translate-x-0");
2280
+ drawer.classList.add("-translate-x-full");
2281
+ overlay.classList.add("hidden");
2282
+ overlay.classList.remove("open");
2283
+ document.body.style.overflow = "";
2284
+ } else {
2285
+ drawer.classList.remove("-translate-x-full");
2286
+ drawer.classList.add("open", "translate-x-0");
2287
+ overlay.classList.remove("hidden");
2288
+ overlay.classList.add("open");
2289
+ document.body.style.overflow = "hidden";
2290
+ }
2291
+ }
2292
+ return;
2293
+ }
2294
+
2295
+ if (e.target.closest(".bluebird-drawer-overlay")) {
2296
+ const drawer = document.querySelector(".bluebird-drawer");
2297
+ const overlay = document.querySelector(".bluebird-drawer-overlay");
2298
+ if (drawer) {
2299
+ drawer.classList.remove("open", "translate-x-0");
2300
+ drawer.classList.add("-translate-x-full");
2301
+ }
2302
+ if (overlay) {
2303
+ overlay.classList.add("hidden");
2304
+ overlay.classList.remove("open");
2305
+ }
2306
+ document.body.style.overflow = "";
2307
+ return;
2308
+ }
2309
+
2310
+ if (e.target.closest(".bluebird-drawer a")) {
2311
+ const drawer = document.querySelector(".bluebird-drawer");
2312
+ const overlay = document.querySelector(".bluebird-drawer-overlay");
2313
+ if (drawer) {
2314
+ drawer.classList.remove("open", "translate-x-0");
2315
+ drawer.classList.add("-translate-x-full");
2316
+ }
2317
+ if (overlay) {
2318
+ overlay.classList.add("hidden");
2319
+ overlay.classList.remove("open");
2320
+ }
2321
+ document.body.style.overflow = "";
2322
+ }
2323
+
2324
+ const drawerTrigger = e.target.closest("[data-drawer-target]");
2325
+ if (drawerTrigger) {
2326
+ const id = drawerTrigger.getAttribute("data-drawer-target");
2327
+ bluebird("drawer", { id, action: "toggle" });
2328
+ }
2329
+
2330
+ const drawerClose = e.target.closest("[data-drawer-close]");
2331
+ if (drawerClose) {
2332
+ const drawerEl = drawerClose.closest(".drawer");
2333
+ if (drawerEl && drawerEl.id) {
2334
+ bluebird("drawer", { id: drawerEl.id, action: "close" });
2335
+ }
2336
+ }
2337
+
2338
+ const copyTrigger = e.target.closest("[data-copy]");
2339
+ if (copyTrigger) {
2340
+ e.preventDefault();
2341
+ const targetAttr = copyTrigger.getAttribute("data-copy");
2342
+ let textToCopy = targetAttr;
2343
+ if (targetAttr && (targetAttr.startsWith("#") || targetAttr.startsWith("."))) {
2344
+ const targetEl = document.querySelector(targetAttr);
2345
+ if (targetEl) {
2346
+ textToCopy =
2347
+ targetEl.value !== undefined
2348
+ ? targetEl.value
2349
+ : targetEl.innerText || targetEl.textContent;
2350
+ }
2351
+ }
2352
+ if (textToCopy) {
2353
+ navigator.clipboard.writeText(textToCopy.trim()).then(() => {
2354
+ copyTrigger.classList.add("copied");
2355
+ if (typeof bluebird === "function") {
2356
+ bluebird("toast", {
2357
+ title: "Copied to clipboard",
2358
+ description:
2359
+ textToCopy.length > 50 ? textToCopy.substring(0, 50) + "..." : textToCopy,
2360
+ type: "success",
2361
+ duration: 2500,
2362
+ });
2363
+ }
2364
+ setTimeout(() => copyTrigger.classList.remove("copied"), 2000);
2365
+ });
2366
+ }
2367
+ return;
2368
+ }
2369
+
2370
+ const confirmTrigger = e.target.closest("[data-confirm]");
2371
+ if (confirmTrigger) {
2372
+ const msg = confirmTrigger.getAttribute("data-confirm") || "Are you sure?";
2373
+ if (!window.confirm(msg)) {
2374
+ e.preventDefault();
2375
+ e.stopImmediatePropagation();
2376
+ return;
2377
+ }
2378
+ }
2379
+
2380
+ const scrollTrigger = e.target.closest("[data-scroll-to]");
2381
+ if (scrollTrigger) {
2382
+ e.preventDefault();
2383
+ const targetId = scrollTrigger.getAttribute("data-scroll-to");
2384
+ const targetEl = document.querySelector(targetId);
2385
+ if (targetEl) {
2386
+ targetEl.scrollIntoView({ behavior: "smooth", block: "start" });
2387
+ }
2388
+ return;
2389
+ }
2390
+
2391
+ const passToggle = e.target.closest("[data-password-toggle]");
2392
+ if (passToggle) {
2393
+ e.preventDefault();
2394
+ const targetSelector = passToggle.getAttribute("data-password-toggle");
2395
+ const input = targetSelector
2396
+ ? document.querySelector(targetSelector)
2397
+ : passToggle.closest(".input-group, .form-input-group, div")?.querySelector("input") ||
2398
+ passToggle.previousElementSibling;
2399
+ if (input && (input.type === "password" || input.type === "text")) {
2400
+ const isPassword = input.type === "password";
2401
+ input.type = isPassword ? "text" : "password";
2402
+ passToggle.classList.toggle("showing", isPassword);
2403
+ passToggle.setAttribute("aria-pressed", isPassword ? "true" : "false");
2404
+ }
2405
+ return;
2406
+ }
2407
+
2408
+ const stepUp = e.target.closest("[data-step-up]");
2409
+ if (stepUp) {
2410
+ e.preventDefault();
2411
+ const targetInput =
2412
+ document.querySelector(stepUp.getAttribute("data-step-up")) ||
2413
+ stepUp.closest(".stepper")?.querySelector('input[type="number"]');
2414
+ if (targetInput && typeof targetInput.stepUp === "function") {
2415
+ targetInput.stepUp();
2416
+ targetInput.dispatchEvent(new Event("input", { bubbles: true }));
2417
+ targetInput.dispatchEvent(new Event("change", { bubbles: true }));
2418
+ }
2419
+ return;
2420
+ }
2421
+
2422
+ const stepDown = e.target.closest("[data-step-down]");
2423
+ if (stepDown) {
2424
+ e.preventDefault();
2425
+ const targetInput =
2426
+ document.querySelector(stepDown.getAttribute("data-step-down")) ||
2427
+ stepDown.closest(".stepper")?.querySelector('input[type="number"]');
2428
+ if (targetInput && typeof targetInput.stepDown === "function") {
2429
+ targetInput.stepDown();
2430
+ targetInput.dispatchEvent(new Event("input", { bubbles: true }));
2431
+ targetInput.dispatchEvent(new Event("change", { bubbles: true }));
2432
+ }
2433
+ return;
2434
+ }
2435
+
2436
+ const selectItem = e.target.closest("[data-select-value]");
2437
+ if (selectItem) {
2438
+ const val = selectItem.getAttribute("data-select-value");
2439
+ const targetSelector =
2440
+ selectItem.getAttribute("data-select-target") ||
2441
+ selectItem.closest("[data-select-container]")?.getAttribute("data-select-target");
2442
+ if (targetSelector) {
2443
+ const targetEl = document.querySelector(targetSelector);
2444
+ if (targetEl) {
2445
+ if (targetEl.tagName === "INPUT" || targetEl.tagName === "SELECT") {
2446
+ targetEl.value = val;
2447
+ targetEl.dispatchEvent(new Event("input", { bubbles: true }));
2448
+ targetEl.dispatchEvent(new Event("change", { bubbles: true }));
2449
+ } else {
2450
+ targetEl.textContent = selectItem.textContent.trim();
2451
+ }
2452
+ }
2453
+ }
2454
+ const parentDropdown = selectItem.closest(".dropdown-content, .popover-content");
2455
+ if (parentDropdown) {
2456
+ parentDropdown.classList.remove("open");
2457
+ }
2458
+ }
2459
+
2460
+ const modalTrigger = e.target.closest("[data-toggle='modal'], [data-modal-target], [data-dialog-target]");
2461
+ if (modalTrigger) {
2462
+ e.preventDefault();
2463
+ const targetSelector =
2464
+ modalTrigger.getAttribute("data-modal-target") ||
2465
+ modalTrigger.getAttribute("data-dialog-target") ||
2466
+ modalTrigger.getAttribute("data-target") ||
2467
+ modalTrigger.getAttribute("href");
2468
+ if (targetSelector) {
2469
+ const dialog = document.querySelector(targetSelector);
2470
+ if (dialog && typeof dialog.showModal === "function") {
2471
+ dialog.showModal();
2472
+ }
2473
+ }
2474
+ return;
2475
+ }
2476
+
2477
+ const dismissTrigger = e.target.closest("[data-dismiss='modal'], [data-close-dialog], [data-close-modal]");
2478
+ if (dismissTrigger) {
2479
+ e.preventDefault();
2480
+ const dialog =
2481
+ dismissTrigger.closest("dialog") ||
2482
+ document.querySelector(dismissTrigger.getAttribute("data-target") || "");
2483
+ if (dialog && typeof dialog.close === "function") {
2484
+ dialog.close();
2485
+ }
2486
+ return;
2487
+ }
2488
+
2489
+ const themeTrigger = e.target.closest('[data-toggle="theme"]');
2490
+ if (themeTrigger) {
2491
+ e.preventDefault();
2492
+ const html = document.documentElement;
2493
+ const current = html.getAttribute("data-theme") || (html.classList.contains("dark") ? "dark" : "light");
2494
+ const next = current === "dark" ? "light" : "dark";
2495
+ html.setAttribute("data-theme", next);
2496
+ html.classList.toggle("dark", next === "dark");
2497
+ try {
2498
+ localStorage.setItem("bluebird-theme", next);
2499
+ } catch (err) {}
2500
+ return;
2501
+ }
2502
+
2503
+ const toastTrigger = e.target.closest("[data-toast]");
2504
+ if (toastTrigger) {
2505
+ e.preventDefault();
2506
+ const desc = toastTrigger.getAttribute("data-toast") || "";
2507
+ const title = toastTrigger.getAttribute("data-toast-title") || "";
2508
+ const type = toastTrigger.getAttribute("data-toast-type") || "info";
2509
+ if (typeof bluebird === "function") {
2510
+ bluebird("toast", { title, description: desc, type });
2511
+ }
2512
+ return;
2513
+ }
2514
+
2515
+ const snackbarTrigger = e.target.closest("[data-snackbar]");
2516
+ if (snackbarTrigger) {
2517
+ e.preventDefault();
2518
+ const message = snackbarTrigger.getAttribute("data-snackbar") || "";
2519
+ const type = snackbarTrigger.getAttribute("data-snackbar-type") || "info";
2520
+ if (typeof bluebird === "function") {
2521
+ bluebird("snackbar", { message, type });
2522
+ }
2523
+ return;
2524
+ }
2525
+
2526
+ const actionBtn = e.target.closest("button[data-action], a[data-action]");
2527
+ if (actionBtn) {
2528
+ e.preventDefault();
2529
+ const actionName = actionBtn.getAttribute("data-action");
2530
+ if (actionName && window.Bluebird && typeof window.Bluebird.action === "function") {
2531
+ let payload = {};
2532
+ const rawArgs = actionBtn.getAttribute("data-args") || actionBtn.getAttribute("data-payload");
2533
+ if (rawArgs) {
2534
+ try {
2535
+ payload = JSON.parse(rawArgs);
2536
+ } catch {}
2537
+ }
2538
+ const partialTarget = actionBtn.getAttribute("data-partial");
2539
+ actionBtn.disabled = true;
2540
+ actionBtn.setAttribute("aria-busy", "true");
2541
+ actionBtn.classList.add("is-pending");
2542
+ window.Bluebird.action(actionName, payload, {
2543
+ url: actionBtn.getAttribute("data-url") || undefined,
2544
+ partial: partialTarget === "true" ? true : partialTarget || false,
2545
+ }).finally(() => {
2546
+ actionBtn.disabled = false;
2547
+ actionBtn.removeAttribute("aria-busy");
2548
+ actionBtn.classList.remove("is-pending");
2549
+ });
2550
+ }
2551
+ return;
2552
+ }
2553
+
2554
+ if (!e.target.closest(".dropdown") && !e.target.closest(".popover")) {
2555
+ document.querySelectorAll(".dropdown-content.open, .popover-content.open").forEach((el) => {
2556
+ el.classList.remove("open");
2557
+ });
2558
+ }
2559
+ });
2560
+
2561
+ document.addEventListener("input", (e) => {
2562
+ const filterInput = e.target.closest("[data-filter-target]");
2563
+ if (filterInput) {
2564
+ const targetSelector = filterInput.getAttribute("data-filter-target");
2565
+ const targetContainer = document.querySelector(targetSelector);
2566
+ if (targetContainer) {
2567
+ const query = filterInput.value.toLowerCase().trim();
2568
+ const items = targetContainer.querySelectorAll("[data-filter-item], li, tr, .card, .dropdown-item, .item");
2569
+ let visibleCount = 0;
2570
+ items.forEach((item) => {
2571
+ const text = item.textContent.toLowerCase();
2572
+ const matches = text.includes(query);
2573
+ item.style.display = matches ? "" : "none";
2574
+ if (matches) visibleCount++;
2575
+ });
2576
+ const emptyMsg = targetContainer.querySelector(".no-filter-results");
2577
+ if (emptyMsg) {
2578
+ emptyMsg.style.display = visibleCount === 0 ? "block" : "none";
2579
+ }
2580
+ }
2581
+ }
2582
+
2583
+ if (e.target.matches("textarea[data-auto-resize]")) {
2584
+ const textarea = e.target;
2585
+ textarea.style.height = "auto";
2586
+ textarea.style.height = textarea.scrollHeight + 2 + "px";
2587
+ }
2588
+ });
2589
+
2590
+ document.addEventListener("submit", async (e) => {
2591
+ const actionForm = e.target.closest("form[data-action]");
2592
+ if (actionForm && window.Bluebird && typeof window.Bluebird.action === "function") {
2593
+ e.preventDefault();
2594
+ const actionName = actionForm.getAttribute("data-action");
2595
+ const submitButtons = actionForm.querySelectorAll('button[type="submit"], input[type="submit"]');
2596
+ submitButtons.forEach((btn) => {
2597
+ btn.disabled = true;
2598
+ btn.setAttribute("aria-busy", "true");
2599
+ });
2600
+ actionForm.classList.add("is-pending");
2601
+ const formData = new FormData(actionForm);
2602
+ const payload = {};
2603
+ formData.forEach((val, key) => {
2604
+ payload[key] = val;
2605
+ });
2606
+ const partialAttr = actionForm.getAttribute("data-partial");
2607
+ try {
2608
+ const res = await window.Bluebird.action(actionName, payload, {
2609
+ url: actionForm.getAttribute("action") || window.location.pathname,
2610
+ partial: partialAttr === "true" ? true : partialAttr || false,
2611
+ });
2612
+ if (res && (res.message || res.data?.message) && typeof bluebird === "function") {
2613
+ bluebird("toast", {
2614
+ title: res.status === "error" ? "Error" : "Success",
2615
+ description: res.message || res.data?.message,
2616
+ type: res.status === "error" ? "error" : "success",
2617
+ });
2618
+ }
2619
+ } finally {
2620
+ submitButtons.forEach((btn) => {
2621
+ btn.disabled = false;
2622
+ btn.removeAttribute("aria-busy");
2623
+ });
2624
+ actionForm.classList.remove("is-pending");
2625
+ }
2626
+ return;
2627
+ }
2628
+
2629
+ const form = e.target.closest("form[data-bb-form]");
2630
+ if (!form) return;
2631
+ e.preventDefault();
2632
+ const action = form.getAttribute("action") || window.location.pathname;
2633
+ const method = (form.getAttribute("method") || "POST").toUpperCase();
2634
+ const formData = new FormData(form);
2635
+
2636
+ const csrfEl =
2637
+ document.getElementById("csrf") ||
2638
+ document.querySelector('input[name="_csrf"]') ||
2639
+ document.querySelector('meta[name="csrf-token"]');
2640
+ const csrfToken = csrfEl ? csrfEl.value || csrfEl.getAttribute("content") : null;
2641
+ if (csrfToken && !formData.has("_csrf")) {
2642
+ formData.append("_csrf", csrfToken);
2643
+ }
2644
+
2645
+ try {
2646
+ const headers = { "X-Requested-With": "XMLHttpRequest" };
2647
+ if (csrfToken) headers["X-CSRF-Token"] = csrfToken;
2648
+
2649
+ const res = await fetch(action, {
2650
+ method,
2651
+ body: formData,
2652
+ headers,
2653
+ credentials: "include",
2654
+ });
2655
+
2656
+ const redirectHeader = res.headers.get("X-Bluebird-Redirect");
2657
+ if (redirectHeader) {
2658
+ if (window.Bluebird && typeof window.Bluebird.navigate === "function") {
2659
+ window.Bluebird.navigate(redirectHeader);
2660
+ } else {
2661
+ window.location.href = redirectHeader;
2662
+ }
2663
+ return;
2664
+ }
2665
+
2666
+ if (res.redirected) {
2667
+ if (window.Bluebird && typeof window.Bluebird.navigate === "function") {
2668
+ window.Bluebird.navigate(res.url);
2669
+ } else {
2670
+ window.location.href = res.url;
2671
+ }
2672
+ return;
2673
+ }
2674
+
2675
+ const contentType = res.headers.get("content-type") || "";
2676
+ if (contentType.includes("application/json")) {
2677
+ const json = await res.json();
2678
+ if (json.message || json.msg || json.error) {
2679
+ const type = res.ok ? "success" : "error";
2680
+ if (typeof bluebird === "function") {
2681
+ bluebird("toast", {
2682
+ title: res.ok ? "Success" : "Error",
2683
+ description: json.message || json.msg || json.error,
2684
+ type,
2685
+ });
2686
+ }
2687
+ }
2688
+ }
2689
+ } catch (err) {
2690
+ if (typeof bluebird === "function") {
2691
+ bluebird("toast", {
2692
+ title: "Request Failed",
2693
+ description: err.message,
2694
+ type: "error",
2695
+ });
2696
+ }
2697
+ }
2698
+ });
2699
+
2700
+ document.addEventListener("keydown", (e) => {
2701
+ if ((e.ctrlKey || e.metaKey) && e.key === "k") {
2702
+ e.preventDefault();
2703
+ if (typeof bluebird === "function") {
2704
+ bluebird("command", { action: "toggle" });
2705
+ }
2706
+ } else if (e.key === "Escape") {
2707
+ const openCommand = document.querySelector(".command-backdrop.open");
2708
+ if (openCommand && typeof bluebird === "function") {
2709
+ bluebird("command", { action: "close" });
2710
+ }
2711
+ }
2712
+ });
2713
+ })();
2714
+
2715
+ (function () {
2716
+ function init() {
2717
+ cleanupOrphanedBackdrops();
2718
+ initMobileDrawer();
2719
+ document.querySelectorAll(".carousel").forEach((c) => initSingleCarousel(c));
2720
+ document.querySelectorAll("textarea[data-auto-resize]").forEach((t) => {
2721
+ t.style.height = "auto";
2722
+ t.style.height = t.scrollHeight + 2 + "px";
2723
+ });
2724
+ try {
2725
+ const savedTheme = localStorage.getItem("bluebird-theme");
2726
+ if (savedTheme) {
2727
+ document.documentElement.setAttribute("data-theme", savedTheme);
2728
+ document.documentElement.classList.toggle("dark", savedTheme === "dark");
2729
+ }
2730
+ } catch (e) {}
2731
+ }
2732
+
2733
+ if (document.readyState === "loading") {
2734
+ document.addEventListener("DOMContentLoaded", () => setTimeout(init, 50));
2735
+ } else {
2736
+ setTimeout(init, 50);
2737
+ }
2738
+
2739
+ if (!window.__BLUEBIRD_INIT_BOUND__) {
2740
+ window.__BLUEBIRD_INIT_BOUND__ = true;
2741
+ window.addEventListener("bluebird:page-load", () => setTimeout(init, 20));
2742
+ window.addEventListener("bluebird:partial-load", () => setTimeout(init, 20));
2743
+ }
2744
+ })();
2745
+
2746
+ /**
2747
+ * Standard fetch wrapper supporting automatic CSRF injection and JSON parsing.
2748
+ * @param {string} url
2749
+ * @param {string} method
2750
+ * @param {Object|boolean} body
2751
+ * @param {FormData|boolean} bodyForm
2752
+ * @param {Object} headers
2753
+ * @returns {Promise<any>}
2754
+ */
2755
+ async function Http(
2756
+ url = "/",
2757
+ method = "GET",
2758
+ body = false,
2759
+ bodyForm = false,
2760
+ headers = {}
2761
+ ) {
2762
+ const csrfEl =
2763
+ document.getElementById("csrf") ||
2764
+ document.querySelector('input[name="_csrf"]') ||
2765
+ document.querySelector('meta[name="csrf-token"]');
2766
+ const csrfToken = csrfEl ? csrfEl.value || csrfEl.getAttribute("content") : null;
2767
+ const mergedHeaders = { ...headers };
2768
+ if (csrfToken) {
2769
+ mergedHeaders["X-CSRF-Token"] = csrfToken;
2770
+ }
2771
+ const upperMethod = String(method || "GET").toUpperCase();
2772
+ const options = { method: upperMethod, headers: mergedHeaders, credentials: "include" };
2773
+ if (body) {
2774
+ const payload = csrfToken ? { ...body, _csrf: csrfToken, csrf: csrfToken } : body;
2775
+ options["body"] = JSON.stringify(payload);
2776
+ if (!mergedHeaders["Content-Type"]) {
2777
+ mergedHeaders["Content-Type"] = "application/json";
2778
+ }
2779
+ }
2780
+ if (bodyForm) {
2781
+ if (csrfToken && bodyForm instanceof FormData) {
2782
+ if (!bodyForm.has("_csrf")) bodyForm.append("_csrf", csrfToken);
2783
+ }
2784
+ options["body"] = bodyForm;
2785
+ }
2786
+ if (upperMethod !== "GET" && window.Bluebird && typeof window.Bluebird.clearPrefetch === "function") {
2787
+ window.Bluebird.clearPrefetch();
2788
+ }
2789
+ const response = await fetch(url, options);
2790
+ if (!response.ok) {
2791
+ let errorData;
2792
+ try {
2793
+ errorData = await response.json();
2794
+ } catch {
2795
+ errorData = { message: `HTTP Error ${response.status}: ${response.statusText}` };
2796
+ }
2797
+ throw new Error(errorData.message || errorData.msg || errorData.mensaje || "Fetch request failed");
2798
+ }
2799
+ return await response.json();
2800
+ }
2801
+
2802
+ /**
2803
+ * Retrieves a query parameter from window.location.search.
2804
+ * @param {string} name
2805
+ * @returns {string|null}
2806
+ */
2807
+ function getUrlParameter(name) {
2808
+ return new URLSearchParams(window.location.search).get(name);
2809
+ }
2810
+
2811
+ /**
2812
+ * Checks whether the document matches the specified language.
2813
+ * @param {string} l
2814
+ * @returns {boolean}
2815
+ */
2816
+ function lang(l = "es") {
2817
+ const docLang = document.documentElement.lang || "es";
2818
+ return docLang === l || docLang.startsWith(l);
2819
+ }
2820
+
2821
+ /**
2822
+ * High-performance responsive data table with search, pagination, and mobile card view.
2823
+ */
2824
+ class ResponsiveDataTable {
2825
+ constructor(containerId, options = {}) {
2826
+ this.container =
2827
+ typeof containerId === "string" ? document.getElementById(containerId) : containerId;
2828
+ if (!this.container) return;
2829
+ this.defaults = {
2830
+ data: [],
2831
+ columns: [],
2832
+ rowsPerPage: 10,
2833
+ search: true,
2834
+ pagination: true,
2835
+ headerTitles: {},
2836
+ summaryFields: ["id"],
2837
+ edit: false,
2838
+ delete: false,
2839
+ breakpoint: 768,
2840
+ };
2841
+ this.options = { ...this.defaults, ...options };
2842
+ if (options.pageSize !== undefined) this.options.rowsPerPage = options.pageSize;
2843
+ if (options.searchable !== undefined) this.options.search = options.searchable;
2844
+ if (options.onEdit !== undefined) this.options.edit = options.onEdit;
2845
+ if (options.onDelete !== undefined) this.options.delete = options.onDelete;
2846
+ this.currentPage = 1;
2847
+ this.filteredData = [...this.options.data];
2848
+ this.isMobile = window.innerWidth < this.options.breakpoint;
2849
+ this.init();
2850
+ if (this.container._bb_resize_handler) {
2851
+ window.removeEventListener("resize", this.container._bb_resize_handler);
2852
+ }
2853
+ this._onResize = () => this.handleResize();
2854
+ this.container._bb_resize_handler = this._onResize;
2855
+ window.addEventListener("resize", this._onResize);
2856
+ }
2857
+
2858
+ init() {
2859
+ this.renderContainer();
2860
+ this.updateTable();
2861
+ if (this.options.search) this.setupSearch();
2862
+ }
2863
+
2864
+ handleResize() {
2865
+ const wasMobile = this.isMobile;
2866
+ this.isMobile = window.innerWidth < this.options.breakpoint;
2867
+ if (wasMobile !== this.isMobile) this.updateTable();
2868
+ }
2869
+
2870
+ renderContainer() {
2871
+ this.container.innerHTML = `
2872
+ <section class="w-full">
2873
+ ${
2874
+ this.options.search
2875
+ ? `<div class="mb-4 flex items-center justify-between"><input type="search" class="datatable-search-input w-full sm:w-72 rounded-lg border border-slate-700 bg-slate-900/90 px-3.5 py-2 text-sm text-slate-100 placeholder-slate-400 focus:border-sky-500 focus:outline-none focus:ring-2 focus:ring-sky-500/20" placeholder="${lang() ? "Buscar..." : "Search..."}" aria-label="Search"/></div>`
2876
+ : ""
2877
+ }
2878
+ <div class="overflow-x-auto rounded-xl border border-slate-800">
2879
+ <table class="datatable-table w-full text-sm text-left border-collapse hidden"></table>
2880
+ <div class="datatable-mobile p-3 space-y-3"></div>
2881
+ </div>
2882
+ ${this.options.pagination ? `<nav class="datatable-pagination mt-4 flex items-center justify-center gap-1.5" aria-label="Pagination"></nav>` : ""}
2883
+ </section>`;
2884
+ }
2885
+
2886
+ renderTable() {
2887
+ const table = this.container.querySelector(".datatable-table");
2888
+ const mobileView = this.container.querySelector(".datatable-mobile");
2889
+ if (!table || !mobileView) return;
2890
+ if (this.isMobile) {
2891
+ table.classList.add("hidden");
2892
+ mobileView.classList.remove("hidden");
2893
+ this.renderMobileView();
2894
+ } else {
2895
+ table.classList.remove("hidden");
2896
+ mobileView.classList.add("hidden");
2897
+ this.renderDesktopTable();
2898
+ }
2899
+ }
2900
+
2901
+ renderDesktopTable() {
2902
+ const table = this.container.querySelector(".datatable-table");
2903
+ table.innerHTML = `
2904
+ <thead>
2905
+ <tr class="datatable-header border-b border-slate-800 bg-slate-900/70 text-xs font-semibold uppercase tracking-wider text-slate-400"></tr>
2906
+ </thead>
2907
+ <tbody class="datatable-body divide-y divide-slate-800/70"></tbody>`;
2908
+ const headerRow = table.querySelector("thead tr");
2909
+ this.options.columns.forEach((column) => {
2910
+ const th = document.createElement("th");
2911
+ th.scope = "col";
2912
+ th.className = "px-4 py-3";
2913
+ th.textContent =
2914
+ this.options.headerTitles[column.key] || column.title || column.label || column.key;
2915
+ headerRow.appendChild(th);
2916
+ });
2917
+ if (this.options.edit || this.options.delete) {
2918
+ const th = document.createElement("th");
2919
+ th.scope = "col";
2920
+ th.className = "px-4 py-3";
2921
+ th.textContent = lang() ? "Acciones" : "Actions";
2922
+ headerRow.appendChild(th);
2923
+ }
2924
+ const startIndex = (this.currentPage - 1) * this.options.rowsPerPage;
2925
+ const endIndex = startIndex + this.options.rowsPerPage;
2926
+ const paginatedData = this.filteredData.slice(startIndex, endIndex);
2927
+ const tbody = table.querySelector("tbody");
2928
+ paginatedData.forEach((item) => {
2929
+ const row = document.createElement("tr");
2930
+ row.className = "hover:bg-slate-800/40 transition-colors";
2931
+ this.options.columns.forEach((column) => {
2932
+ const td = document.createElement("td");
2933
+ td.className = "px-4 py-3 text-slate-200";
2934
+ const value = item[column.key];
2935
+ if (
2936
+ value &&
2937
+ typeof value === "string" &&
2938
+ /<[a-z][\s\S]*>/i.test(value)
2939
+ ) {
2940
+ td.innerHTML = value;
2941
+ } else {
2942
+ td.textContent = value !== undefined && value !== null ? value : "-";
2943
+ }
2944
+ row.appendChild(td);
2945
+ });
2946
+ if (this.options.edit || this.options.delete) {
2947
+ const td = document.createElement("td");
2948
+ td.className = "px-4 py-3 text-slate-200";
2949
+ const actionsDiv = document.createElement("div");
2950
+ actionsDiv.className = "flex items-center gap-2";
2951
+ if (this.options.edit) {
2952
+ const btn = document.createElement("button");
2953
+ btn.className =
2954
+ "px-2.5 py-1 text-xs font-medium rounded-md border border-slate-700 text-slate-200 hover:bg-slate-800 transition-colors";
2955
+ btn.textContent = lang() ? "Editar" : "Edit";
2956
+ btn.onclick = (e) => this.handleAction("edit", e, item);
2957
+ actionsDiv.appendChild(btn);
2958
+ }
2959
+ if (this.options.delete) {
2960
+ const btn = document.createElement("button");
2961
+ btn.className =
2962
+ "px-2.5 py-1 text-xs font-medium rounded-md bg-red-500/15 text-red-400 border border-red-500/30 hover:bg-red-500/25 transition-colors";
2963
+ btn.textContent = lang() ? "Eliminar" : "Delete";
2964
+ btn.onclick = (e) => this.handleAction("delete", e, item);
2965
+ actionsDiv.appendChild(btn);
2966
+ }
2967
+ td.appendChild(actionsDiv);
2968
+ row.appendChild(td);
2969
+ }
2970
+ tbody.appendChild(row);
2971
+ });
2972
+ }
2973
+
2974
+ renderMobileView() {
2975
+ const mobileView = this.container.querySelector(".datatable-mobile");
2976
+ mobileView.innerHTML = "";
2977
+ const startIndex = (this.currentPage - 1) * this.options.rowsPerPage;
2978
+ const endIndex = startIndex + this.options.rowsPerPage;
2979
+ const paginatedData = this.filteredData.slice(startIndex, endIndex);
2980
+ paginatedData.forEach((item) => {
2981
+ const card = document.createElement("article");
2982
+ card.className = "rounded-xl border border-slate-800 bg-slate-900/60 p-4 mb-3 shadow-xs";
2983
+ const summary = document.createElement("h3");
2984
+ summary.className =
2985
+ "flex items-center justify-between font-semibold text-slate-100 mb-3 pb-2 border-b border-slate-800";
2986
+ this.options.summaryFields.forEach((fieldKey) => {
2987
+ const value = item[fieldKey];
2988
+ summary.innerHTML += `<span>${escapeClientHtml(value !== undefined && value !== null ? value : "-")}</span>`;
2989
+ });
2990
+ card.appendChild(summary);
2991
+ const details = document.createElement("dl");
2992
+ details.className = "grid grid-cols-1 gap-2 mb-3 text-sm";
2993
+ this.options.columns.forEach((column) => {
2994
+ if (this.options.summaryFields.includes(column.key)) return;
2995
+ const dt = document.createElement("dt");
2996
+ dt.className = "text-xs font-semibold uppercase tracking-wider text-slate-400";
2997
+ dt.textContent =
2998
+ this.options.headerTitles[column.key] || column.title || column.label || column.key;
2999
+ const dd = document.createElement("dd");
3000
+ dd.className = "text-slate-200 mb-1";
3001
+ const cellValue = item[column.key];
3002
+ if (
3003
+ cellValue &&
3004
+ typeof cellValue === "string" &&
3005
+ /<[a-z][\s\S]*>/i.test(cellValue)
3006
+ ) {
3007
+ dd.innerHTML = cellValue;
3008
+ } else {
3009
+ dd.textContent = cellValue !== undefined && cellValue !== null ? cellValue : "-";
3010
+ }
3011
+ details.appendChild(dt);
3012
+ details.appendChild(dd);
3013
+ });
3014
+ card.appendChild(details);
3015
+ if (this.options.edit || this.options.delete) {
3016
+ const actions = document.createElement("div");
3017
+ actions.className = "flex items-center gap-2 justify-end pt-2 border-t border-slate-800/60";
3018
+ if (this.options.edit) {
3019
+ const btn = document.createElement("button");
3020
+ btn.className =
3021
+ "px-2.5 py-1 text-xs font-medium rounded-md border border-slate-700 text-slate-200 hover:bg-slate-800 transition-colors";
3022
+ btn.textContent = lang() ? "Editar" : "Edit";
3023
+ btn.onclick = (e) => this.handleAction("edit", e, item);
3024
+ actions.appendChild(btn);
3025
+ }
3026
+ if (this.options.delete) {
3027
+ const btn = document.createElement("button");
3028
+ btn.className =
3029
+ "px-2.5 py-1 text-xs font-medium rounded-md bg-red-500/15 text-red-400 border border-red-500/30 hover:bg-red-500/25 transition-colors";
3030
+ btn.textContent = lang() ? "Eliminar" : "Delete";
3031
+ btn.onclick = (e) => this.handleAction("delete", e, item);
3032
+ actions.appendChild(btn);
3033
+ }
3034
+ card.appendChild(actions);
3035
+ }
3036
+ mobileView.appendChild(card);
3037
+ });
3038
+ }
3039
+
3040
+ renderPagination() {
3041
+ const pagination = this.container.querySelector(".datatable-pagination");
3042
+ if (!pagination || !this.options.pagination) return;
3043
+ pagination.innerHTML = "";
3044
+ const pageCount = Math.ceil(this.filteredData.length / this.options.rowsPerPage);
3045
+ if (pageCount <= 1) return;
3046
+ const baseClass =
3047
+ "px-3 py-1.5 text-xs font-medium rounded-lg border border-slate-800 bg-slate-900 text-slate-300 hover:bg-slate-800 disabled:opacity-40 disabled:pointer-events-none transition-colors";
3048
+ const activeClass =
3049
+ "px-3 py-1.5 text-xs font-semibold rounded-lg bg-sky-500 text-slate-950 border border-sky-400";
3050
+ const prevButton = document.createElement("button");
3051
+ prevButton.textContent = "«";
3052
+ prevButton.className = baseClass;
3053
+ prevButton.disabled = this.currentPage === 1;
3054
+ prevButton.onclick = () => this.changePage(this.currentPage - 1);
3055
+ pagination.appendChild(prevButton);
3056
+ const maxVisible = 5;
3057
+ let start = Math.max(1, this.currentPage - Math.floor(maxVisible / 2));
3058
+ let end = start + maxVisible - 1;
3059
+ if (end > pageCount) {
3060
+ end = pageCount;
3061
+ start = Math.max(1, end - maxVisible + 1);
3062
+ }
3063
+ if (start > 1) {
3064
+ const firstButton = document.createElement("button");
3065
+ firstButton.className = baseClass;
3066
+ firstButton.textContent = "1";
3067
+ firstButton.onclick = () => this.changePage(1);
3068
+ pagination.appendChild(firstButton);
3069
+ if (start > 2) pagination.appendChild(this.createEllipsis());
3070
+ }
3071
+ for (let i = start; i <= end; i++) {
3072
+ const button = document.createElement("button");
3073
+ button.className = i === this.currentPage ? activeClass : baseClass;
3074
+ button.textContent = i;
3075
+ button.onclick = () => this.changePage(i);
3076
+ pagination.appendChild(button);
3077
+ }
3078
+ if (end < pageCount) {
3079
+ if (end < pageCount - 1) pagination.appendChild(this.createEllipsis());
3080
+ const lastButton = document.createElement("button");
3081
+ lastButton.className = baseClass;
3082
+ lastButton.textContent = pageCount;
3083
+ lastButton.onclick = () => this.changePage(pageCount);
3084
+ pagination.appendChild(lastButton);
3085
+ }
3086
+ const nextButton = document.createElement("button");
3087
+ nextButton.className = baseClass;
3088
+ nextButton.textContent = "»";
3089
+ nextButton.disabled = this.currentPage === pageCount;
3090
+ nextButton.onclick = () => this.changePage(this.currentPage + 1);
3091
+ pagination.appendChild(nextButton);
3092
+ }
3093
+
3094
+ createEllipsis() {
3095
+ const span = document.createElement("span");
3096
+ span.className = "px-2 text-xs text-slate-500";
3097
+ span.textContent = "...";
3098
+ return span;
3099
+ }
3100
+
3101
+ changePage(page) {
3102
+ this.currentPage = page;
3103
+ this.updateTable();
3104
+ }
3105
+
3106
+ handleAction(type, event, item) {
3107
+ if (!this.options[type]) return;
3108
+ const callback =
3109
+ typeof this.options[type] === "function"
3110
+ ? this.options[type]
3111
+ : window[this.options[type]];
3112
+ if (typeof callback === "function") callback(event, item.id || item);
3113
+ }
3114
+
3115
+ setupSearch() {
3116
+ const searchInput = this.container.querySelector(".datatable-search-input");
3117
+ if (!searchInput) return;
3118
+ searchInput.addEventListener("input", (e) => {
3119
+ const term = e.target.value.toLowerCase().trim();
3120
+ this.filteredData = this.options.data.filter((item) =>
3121
+ this.options.columns.some((column) =>
3122
+ String(item[column.key] || "")
3123
+ .toLowerCase()
3124
+ .includes(term)
3125
+ )
3126
+ );
3127
+ this.currentPage = 1;
3128
+ this.updateTable();
3129
+ });
3130
+ }
3131
+
3132
+ updateTable() {
3133
+ this.renderTable();
3134
+ if (this.options.pagination) this.renderPagination();
3135
+ }
3136
+
3137
+ updateData(newData) {
3138
+ this.options.data = newData;
3139
+ this.filteredData = [...newData];
3140
+ this.currentPage = 1;
3141
+ this.updateTable();
3142
+ }
3143
+
3144
+ updateColumns(newColumns) {
3145
+ this.options.columns = newColumns;
3146
+ this.updateTable();
3147
+ }
3148
+ }
3149
+
3150
+ if (typeof window !== "undefined") {
3151
+ window.ResponsiveDataTable = ResponsiveDataTable;
3152
+ window.Http = Http;
3153
+ window.getUrlParameter = getUrlParameter;
3154
+ window.snackbar = snackbar;
3155
+ window.toast = toast;
3156
+ window.bluebird = bluebird;
3157
+ window.dismissToast = dismissToast;
3158
+ window.initMobileDrawer = initMobileDrawer;
3159
+ window.initSingleCarousel = initSingleCarousel;
3160
+ window.lang = lang;
3045
3161
  }