@seip/bluebird-js 0.1.7 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/AGENTS.md +726 -620
  2. package/README.md +615 -607
  3. package/app/models/user.js +19 -0
  4. package/app/resources/html/home.html +137 -0
  5. package/app/resources/html/layouts/main.html +54 -0
  6. package/app/resources/html/notFound.html +14 -0
  7. package/app/resources/html/terms.html +46 -0
  8. package/app/resources/index.html +27 -0
  9. package/app/resources/layouts/AppLayout.jsx +89 -0
  10. package/app/resources/main.jsx +18 -0
  11. package/app/resources/pages/Dashboard.jsx +98 -0
  12. package/app/resources/pages/Home.jsx +140 -0
  13. package/app/resources/pages/Login.jsx +35 -0
  14. package/app/resources/pages/NotFound.jsx +16 -0
  15. package/app/resources/pages/Register.jsx +55 -0
  16. package/app/resources/routes.jsx +54 -0
  17. package/app/resources/spa.js +67 -0
  18. package/app/resources/styles.css +9 -0
  19. package/app/routes/api.js +85 -50
  20. package/app/routes/auth.js +209 -0
  21. package/app/routes/web.js +59 -47
  22. package/core/ai.js +30 -10
  23. package/core/app.d.ts +2 -18
  24. package/core/app.js +987 -801
  25. package/core/auth.d.ts +2 -13
  26. package/core/auth.js +444 -326
  27. package/core/cli/build.js +37 -0
  28. package/core/cli/dev.js +155 -0
  29. package/core/cli/doctor.js +37 -2
  30. package/core/cli/export.js +191 -0
  31. package/core/cli/init.js +91 -322
  32. package/core/cli/nginx.js +1 -1
  33. package/core/cli/templates.js +139 -0
  34. package/core/cli/view.js +98 -161
  35. package/core/config.js +44 -2
  36. package/core/csrf.js +156 -24
  37. package/core/database.js +1184 -1131
  38. package/core/debug.js +1 -1
  39. package/core/html.js +8 -1
  40. package/core/index.d.ts +126 -310
  41. package/core/paths.js +55 -0
  42. package/core/ratelimit.js +10 -1
  43. package/core/react/client/api.js +237 -0
  44. package/core/react/client/auth.js +236 -0
  45. package/core/react/client/components.js +1321 -0
  46. package/core/react/client/i18n.js +338 -0
  47. package/core/react/client/index.d.ts +249 -0
  48. package/core/react/client/index.js +49 -0
  49. package/core/react/client/router.js +26 -0
  50. package/core/react/client/theme.css +512 -0
  51. package/core/render-cache.js +250 -212
  52. package/core/render.d.ts +25 -21
  53. package/core/render.js +738 -736
  54. package/core/router.d.ts +2 -3
  55. package/core/router.js +171 -171
  56. package/core/seo.js +10 -0
  57. package/core/spa.js +599 -0
  58. package/core/view-loader.js +155 -613
  59. package/core/vite-plugin.d.ts +18 -0
  60. package/core/vite-plugin.js +162 -0
  61. package/core/vite.js +250 -145
  62. package/index.js +22 -18
  63. package/jsconfig.json +5 -3
  64. package/package.json +114 -92
  65. package/production.md +8 -3
  66. package/public/js/bluebird.js +1160 -0
  67. package/templates/_auth/app/database.js +19 -0
  68. package/templates/_auth/app/models/user.js +22 -0
  69. package/templates/_auth/app/routes/auth-router.js +304 -0
  70. package/templates/_base/app/resources/html/layouts/main.html +55 -0
  71. package/templates/_base/app/resources/html/notFound.html +14 -0
  72. package/templates/_base/app/resources/index.html +27 -0
  73. package/templates/_base/app/resources/styles.css +9 -0
  74. package/templates/api/app/models/note.js +18 -0
  75. package/templates/api/app/routes/api.js +82 -0
  76. package/templates/api/app/routes/auth.js +11 -0
  77. package/templates/api/index.js +19 -0
  78. package/templates/api/template.json +13 -0
  79. package/templates/auth/app/mail.js +11 -0
  80. package/templates/auth/app/models/password_reset.js +18 -0
  81. package/templates/auth/app/resources/html/home.html +21 -0
  82. package/templates/auth/app/resources/html/partials/nav.html +2 -0
  83. package/templates/auth/app/resources/layouts/AppLayout.jsx +60 -0
  84. package/templates/auth/app/resources/main.jsx +18 -0
  85. package/templates/auth/app/resources/pages/Dashboard.jsx +51 -0
  86. package/templates/auth/app/resources/pages/ForgotPassword.jsx +34 -0
  87. package/templates/auth/app/resources/pages/Login.jsx +36 -0
  88. package/templates/auth/app/resources/pages/NotFound.jsx +16 -0
  89. package/templates/auth/app/resources/pages/Profile.jsx +99 -0
  90. package/templates/auth/app/resources/pages/Register.jsx +50 -0
  91. package/templates/auth/app/resources/pages/ResetPassword.jsx +50 -0
  92. package/templates/auth/app/resources/routes.jsx +54 -0
  93. package/templates/auth/app/resources/spa.js +29 -0
  94. package/templates/auth/app/routes/api.js +17 -0
  95. package/templates/auth/app/routes/auth.js +13 -0
  96. package/templates/auth/app/routes/web.js +21 -0
  97. package/templates/auth/index.js +19 -0
  98. package/templates/auth/template.json +15 -0
  99. package/templates/blank/app/models/.gitkeep +0 -0
  100. package/templates/blank/app/resources/html/home.html +27 -0
  101. package/templates/blank/app/resources/html/partials/nav.html +1 -0
  102. package/templates/blank/app/resources/main.jsx +16 -0
  103. package/templates/blank/app/resources/pages/Home.jsx +42 -0
  104. package/templates/blank/app/resources/pages/NotFound.jsx +27 -0
  105. package/templates/blank/app/resources/routes.jsx +15 -0
  106. package/templates/blank/app/resources/spa.js +24 -0
  107. package/templates/blank/app/routes/api.js +11 -0
  108. package/templates/blank/app/routes/web.js +21 -0
  109. package/templates/blank/index.js +13 -0
  110. package/templates/blank/template.json +12 -0
  111. package/templates/blog/app/lib/blog.js +149 -0
  112. package/templates/blog/app/models/post.js +22 -0
  113. package/templates/blog/app/resources/html/home.html +28 -0
  114. package/templates/blog/app/resources/html/not-found.html +5 -0
  115. package/templates/blog/app/resources/html/partials/nav.html +2 -0
  116. package/templates/blog/app/resources/html/partials/post-card.html +9 -0
  117. package/templates/blog/app/resources/html/post.html +8 -0
  118. package/templates/blog/app/resources/layouts/AdminLayout.jsx +54 -0
  119. package/templates/blog/app/resources/main.jsx +18 -0
  120. package/templates/blog/app/resources/pages/Login.jsx +31 -0
  121. package/templates/blog/app/resources/pages/NotFound.jsx +16 -0
  122. package/templates/blog/app/resources/pages/PostEditor.jsx +51 -0
  123. package/templates/blog/app/resources/pages/Posts.jsx +83 -0
  124. package/templates/blog/app/resources/pages/Register.jsx +43 -0
  125. package/templates/blog/app/resources/routes.jsx +51 -0
  126. package/templates/blog/app/resources/spa.js +25 -0
  127. package/templates/blog/app/resources/styles.css +40 -0
  128. package/templates/blog/app/routes/api.js +77 -0
  129. package/templates/blog/app/routes/auth.js +10 -0
  130. package/templates/blog/app/routes/web.js +114 -0
  131. package/templates/blog/index.js +21 -0
  132. package/templates/blog/template.json +14 -0
  133. package/vite.config.js +11 -0
  134. package/app/views/components/Header.jsx +0 -42
  135. package/app/views/components/LiveCounter.jsx +0 -67
  136. package/app/views/layouts/main/view.jsx +0 -201
  137. package/app/views/legal/terms.html +0 -29
  138. package/app/views/pages/about.jsx +0 -98
  139. package/app/views/pages/dashboard.jsx +0 -278
  140. package/app/views/pages/index.jsx +0 -123
  141. package/app/views/pages/login.jsx +0 -141
  142. package/core/actions.d.ts +0 -4
  143. package/core/actions.js +0 -355
  144. package/core/jsx.d.ts +0 -38
  145. package/core/jsx.js +0 -1597
  146. package/core/vite.d.ts +0 -3
  147. package/public/js/bluebird-client.js +0 -3265
  148. package/public/js/tailwind.js +0 -8
@@ -1,3265 +0,0 @@
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 resolvedName =
384
- typeof actionName === "string"
385
- ? actionName
386
- : actionName?.__actionName || actionName?.name || String(actionName);
387
- const targetUrl = options.url || window.location.pathname;
388
- const csrfToken = Bluebird.getCsrfToken();
389
- const wantsPartial = Boolean(options.partial);
390
-
391
- const headers = {
392
- "Content-Type": "application/json",
393
- "X-Requested-With": "XMLHttpRequest",
394
- "X-Bluebird-Client-Router": "1",
395
- "X-Bluebird-Action": String(resolvedName),
396
- };
397
- if (csrfToken) {
398
- headers["X-CSRF-Token"] = csrfToken;
399
- }
400
- if (wantsPartial) {
401
- headers["X-Bluebird-Partial"] = "1";
402
- }
403
-
404
- const res = await fetch(targetUrl, {
405
- method: "POST",
406
- headers,
407
- body: JSON.stringify(payload || {}),
408
- credentials: "include",
409
- });
410
-
411
- const redirectHeader = res.headers.get("X-Bluebird-Redirect");
412
- if (redirectHeader) {
413
- await Bluebird.navigate(redirectHeader);
414
- return { redirect: redirectHeader };
415
- }
416
-
417
- const contentType = res.headers.get("content-type") || "";
418
- if (wantsPartial && contentType.includes("text/html")) {
419
- const html = await res.text();
420
- const selector =
421
- typeof options.partial === "string"
422
- ? options.partial
423
- : ".page-content, [data-bb-outlet]";
424
- const targetEl = document.querySelector(selector);
425
- if (targetEl) {
426
- const applySwap = () => {
427
- Bluebird.unmountNonPersistent(targetEl);
428
- targetEl.innerHTML = html;
429
- executeScripts(targetEl);
430
- Bluebird.hydrate(targetEl);
431
- };
432
- if (options.transition && document.startViewTransition) {
433
- await document.startViewTransition(applySwap).finished;
434
- } else {
435
- applySwap();
436
- }
437
- }
438
- return { ok: res.ok, html };
439
- }
440
-
441
- if (contentType.includes("application/json")) {
442
- const data = await res.json();
443
- return data;
444
- }
445
-
446
- return { ok: res.ok, status: res.status };
447
- },
448
- };
449
-
450
- /**
451
- * Swaps the current document DOM with the incoming parsed document.
452
- * Preserves [data-persist="true"] elements and synchronizes <head> meta tags.
453
- * @param {Document} nextDoc - Parsed incoming HTML document.
454
- * @param {string} url - Target URL.
455
- * @param {Object} options - Navigation options.
456
- */
457
- function swapDocument(nextDoc, url, options) {
458
- const currentPersistNodes = new Map();
459
- const currentPersistElements = document.querySelectorAll('[data-persist="true"]');
460
-
461
- currentPersistElements.forEach((el, index) => {
462
- const key = el.getAttribute("data-island") || el.getAttribute("data-bb-client") || el.id || `persist-${index}`;
463
- currentPersistNodes.set(key, el);
464
- });
465
-
466
- Bluebird.unmountNonPersistent();
467
-
468
- document.title = nextDoc.title || document.title;
469
-
470
- updateHeadTags(nextDoc);
471
-
472
- const nextPersistElements = nextDoc.querySelectorAll('[data-persist="true"]');
473
- nextPersistElements.forEach((nextEl, index) => {
474
- const key = nextEl.getAttribute("data-island") || nextEl.getAttribute("data-bb-client") || nextEl.id || `persist-${index}`;
475
- const activeEl = currentPersistNodes.get(key);
476
- if (activeEl && nextEl.parentNode) {
477
- nextEl.parentNode.replaceChild(activeEl, nextEl);
478
- currentPersistNodes.delete(key);
479
- }
480
- });
481
-
482
- const currentOutlet = document.querySelector("[data-bb-outlet]");
483
- const nextOutlet = nextDoc.querySelector("[data-bb-outlet]");
484
- const currentLayout = document.body.getAttribute("data-layout");
485
- const nextLayout = nextDoc.body.getAttribute("data-layout");
486
-
487
- const canSwapOutletOnly =
488
- currentOutlet &&
489
- nextOutlet &&
490
- currentLayout &&
491
- nextLayout &&
492
- currentLayout === nextLayout;
493
-
494
- if (canSwapOutletOnly) {
495
- currentOutlet.innerHTML = nextOutlet.innerHTML;
496
- executeScripts(currentOutlet);
497
- Bluebird.hydrate(currentOutlet);
498
- } else {
499
- document.body.innerHTML = nextDoc.body.innerHTML;
500
-
501
- for (const [key, activeEl] of currentPersistNodes.entries()) {
502
- const placeholder = document.querySelector(
503
- `[data-persist="true"][data-island="${key}"], [data-persist="true"][data-bb-client="${key}"], [data-persist="true"]#${key}`
504
- );
505
- if (placeholder && placeholder.parentNode && placeholder !== activeEl) {
506
- placeholder.parentNode.replaceChild(activeEl, placeholder);
507
- }
508
- }
509
-
510
- executeScripts(document.body);
511
- Bluebird.hydrate();
512
- drainMountQueue();
513
- }
514
-
515
- syncActiveNavLinks(url);
516
-
517
- if (options.replace) {
518
- window.history.replaceState({}, "", url);
519
- } else {
520
- window.history.pushState({}, "", url);
521
- }
522
-
523
- if (options.scroll !== false) {
524
- window.scrollTo(0, 0);
525
- }
526
-
527
- const pageLoadDetail = { url, initial: false };
528
- window.dispatchEvent(new CustomEvent("bluebird:navigate", { detail: { url } }));
529
- window.dispatchEvent(new CustomEvent("bluebird:page-load", { detail: pageLoadDetail }));
530
- document.dispatchEvent(new CustomEvent("bluebird:page-load", { detail: pageLoadDetail }));
531
- }
532
-
533
- /**
534
- * Synchronizes active state on navigation links across header and aside.
535
- * @param {string} targetUrl
536
- */
537
- function syncActiveNavLinks(targetUrl) {
538
- try {
539
- const parsed = new URL(targetUrl, window.location.origin);
540
- const targetPath = parsed.pathname;
541
- const navLinks = document.querySelectorAll("header a, aside a, nav a");
542
- for (const link of navLinks) {
543
- const href = link.getAttribute("href");
544
- if (!href || href.startsWith("http") || href.startsWith("#")) continue;
545
- const linkPath = new URL(href, window.location.origin).pathname;
546
- const isActive = linkPath === targetPath;
547
- if (isActive) {
548
- link.setAttribute("aria-current", "page");
549
- link.classList.add("bg-sky-500/15", "text-sky-400", "border", "border-sky-500/30", "font-semibold");
550
- link.classList.remove("text-slate-400");
551
- } else if (link.getAttribute("aria-current") === "page" || link.classList.contains("bg-sky-500/15")) {
552
- link.removeAttribute("aria-current");
553
- link.classList.remove("bg-sky-500/15", "text-sky-400", "border", "border-sky-500/30", "font-semibold");
554
- link.classList.add("text-slate-400");
555
- }
556
- }
557
- } catch (err) {}
558
- }
559
-
560
- /**
561
- * Re-evaluates script elements found in the newly injected container.
562
- * Wraps inline classic scripts in an isolated block/IIFE scope so top-level `const` / `let`
563
- * declarations never collide across repeated SPA navigations.
564
- * Skips persistent scripts and the Bluebird client runtime itself.
565
- * @param {HTMLElement} container
566
- */
567
- function executeScripts(container) {
568
- const scripts = Array.from(container.querySelectorAll("script"));
569
- for (const oldScript of scripts) {
570
- if (oldScript.getAttribute("data-persist") === "true") continue;
571
- const src = oldScript.getAttribute("src") || "";
572
- if (src.includes("bluebird-client.js")) continue;
573
-
574
- const newScript = document.createElement("script");
575
- for (const attr of Array.from(oldScript.attributes)) {
576
- newScript.setAttribute(attr.name, attr.value);
577
- }
578
-
579
- const rawType = (oldScript.getAttribute("type") || "").trim().toLowerCase();
580
- const isClassicInline =
581
- !src && (!rawType || rawType === "text/javascript" || rawType === "application/javascript");
582
- const code = oldScript.textContent || "";
583
-
584
- if (isClassicInline && code.trim().length > 0) {
585
- newScript.textContent = `{(() => {\n${code}\n})();}`;
586
- } else {
587
- newScript.textContent = code;
588
- }
589
-
590
- if (oldScript.parentNode) {
591
- oldScript.parentNode.replaceChild(newScript, oldScript);
592
- }
593
- }
594
- }
595
-
596
- /**
597
- * Synchronizes meta and link tags between current and incoming <head>.
598
- * @param {Document} nextDoc
599
- */
600
- function updateHeadTags(nextDoc) {
601
- const currentMeta = document.head.querySelectorAll("meta[name], meta[property]");
602
- currentMeta.forEach((el) => el.remove());
603
-
604
- const nextMeta = nextDoc.head.querySelectorAll("meta[name], meta[property]");
605
- nextMeta.forEach((el) => {
606
- document.head.appendChild(document.importNode(el, true));
607
- });
608
-
609
- const nextCanonical = nextDoc.head.querySelector("link[rel='canonical']");
610
- const currentCanonical = document.head.querySelector("link[rel='canonical']");
611
- if (nextCanonical) {
612
- if (currentCanonical) {
613
- currentCanonical.setAttribute("href", nextCanonical.getAttribute("href") || "");
614
- } else {
615
- document.head.appendChild(document.importNode(nextCanonical, true));
616
- }
617
- } else if (currentCanonical) {
618
- currentCanonical.remove();
619
- }
620
- }
621
-
622
- /**
623
- * Determines if a link element qualifies for SPA navigation.
624
- * @param {HTMLAnchorElement} anchor
625
- * @returns {boolean}
626
- */
627
- function isInternalLink(anchor) {
628
- if (!anchor || anchor.tagName !== "A") return false;
629
- if (anchor.target && anchor.target !== "_self") return false;
630
- if (anchor.hasAttribute("download")) return false;
631
- if (anchor.getAttribute("rel") === "external") return false;
632
- if (anchor.getAttribute("data-no-router") !== null) return false;
633
-
634
- const href = anchor.getAttribute("href");
635
- if (!href || href.startsWith("#") || href.startsWith("javascript:") || href.startsWith("mailto:") || href.startsWith("tel:")) {
636
- return false;
637
- }
638
-
639
- try {
640
- const url = new URL(anchor.href, window.location.href);
641
- return url.origin === window.location.origin;
642
- } catch {
643
- return false;
644
- }
645
- }
646
-
647
- /**
648
- * Determines if a link element qualifies for background prefetching on hover.
649
- * Excludes links marked with data-no-prefetch, data-prefetch="false", data-no-hover,
650
- * or paths typically used for session termination (such as /logout or /signout).
651
- * @param {HTMLAnchorElement} anchor
652
- * @returns {boolean}
653
- */
654
- function canPrefetch(anchor) {
655
- if (!isInternalLink(anchor)) return false;
656
- if (anchor.hasAttribute("data-no-prefetch")) return false;
657
- if (anchor.getAttribute("data-prefetch") === "false") return false;
658
- if (anchor.hasAttribute("data-no-hover")) return false;
659
- if (anchor.hasAttribute("data-partial-target")) return false;
660
-
661
- try {
662
- const url = new URL(anchor.href, window.location.href);
663
- const pathname = url.pathname.toLowerCase();
664
- if (
665
- pathname === "/logout" ||
666
- pathname.endsWith("/logout") ||
667
- pathname === "/signout" ||
668
- pathname.endsWith("/signout")
669
- ) {
670
- return false;
671
- }
672
- } catch {
673
- return false;
674
- }
675
-
676
- return true;
677
- }
678
-
679
- /**
680
- * Initializes click interception on document for client-side routing and partial swaps.
681
- */
682
- function initLinkInterception() {
683
- document.addEventListener("click", (e) => {
684
- if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {
685
- return;
686
- }
687
-
688
- const anchor = e.target.closest("a");
689
- if (!anchor || !isInternalLink(anchor)) return;
690
-
691
- const partialTarget = anchor.getAttribute("data-partial-target");
692
- if (partialTarget) {
693
- e.preventDefault();
694
- Bluebird.renderPartial(anchor.href, partialTarget, {
695
- transition: anchor.getAttribute("data-transition") === "true",
696
- pushUrl: anchor.getAttribute("data-push-url") === "true",
697
- });
698
- return;
699
- }
700
-
701
- const url = anchor.href;
702
- if (url === window.location.href) {
703
- e.preventDefault();
704
- return;
705
- }
706
-
707
- e.preventDefault();
708
- Bluebird.navigate(url);
709
- });
710
-
711
- document.addEventListener(
712
- "mouseover",
713
- (e) => {
714
- const anchor = e.target.closest("a");
715
- if (!anchor || !canPrefetch(anchor)) return;
716
- const url = anchor.href;
717
- if (!getPrefetchedHtml(url)) {
718
- fetch(url, { headers: { "X-Bluebird-Prefetch": "1" }, credentials: "include" })
719
- .then((r) => (r.ok ? r.text() : null))
720
- .then((html) => {
721
- if (html) setPrefetchedHtml(url, html);
722
- })
723
- .catch(() => {});
724
- }
725
- },
726
- { passive: true }
727
- );
728
-
729
- window.addEventListener("popstate", () => {
730
- Bluebird.navigate(window.location.href, { replace: true, scroll: false });
731
- });
732
- }
733
-
734
- /**
735
- * DOM query selector shortcut.
736
- * @param {string} selector
737
- * @param {HTMLElement|Document} [context=document]
738
- * @returns {HTMLElement|null}
739
- */
740
- const $ = (selector, context = document) => context.querySelector(selector);
741
-
742
- /**
743
- * DOM query selector all shortcut returning an Array.
744
- * @param {string} selector
745
- * @param {HTMLElement|Document} [context=document]
746
- * @returns {HTMLElement[]}
747
- */
748
- const $$ = (selector, context = document) => Array.from(context.querySelectorAll(selector));
749
-
750
- /**
751
- * Delegated DOM event listener helper.
752
- * Listens on document, matching selectors dynamically.
753
- * Works across View Transitions without manual re-binding!
754
- * @param {string} selector - CSS selector (e.g. '#btnInc', '.card-btn')
755
- * @param {string} type - Event type (e.g. 'click', 'input', 'submit')
756
- * @param {Function} handler - Callback receiving (event, matchedElement)
757
- * @returns {Function} Unsubscribe function.
758
- */
759
- function delegate(selector, type, handler) {
760
- const listener = (e) => {
761
- const match = e.target.closest(selector);
762
- if (match) handler(e, match);
763
- };
764
- document.addEventListener(type, listener);
765
- return () => document.removeEventListener(type, listener);
766
- }
767
-
768
- Bluebird.$ = $;
769
- Bluebird.$$ = $$;
770
- Bluebird.delegate = delegate;
771
- Bluebird.event = delegate;
772
-
773
- window.$ = window.$ || $;
774
- window.$$ = window.$$ || $$;
775
- window.on = window.on || delegate;
776
-
777
- const VOID_TAGS = new Set([
778
- "area", "base", "br", "col", "embed", "hr", "img", "input",
779
- "link", "meta", "param", "source", "track", "wbr"
780
- ]);
781
-
782
- const templateCache = new Map();
783
-
784
- const MODE_TEXT = 0;
785
- const MODE_WHITESPACE = 1;
786
- const MODE_TAGNAME = 2;
787
- const MODE_PROPNAME = 3;
788
- const MODE_PROPVAL = 4;
789
-
790
- /**
791
- * Compiles static template strings into structured parser tokens.
792
- * Cached by template string reference for optimal re-render performance.
793
- * @param {Array<string>} statics
794
- * @returns {Array<Array<any>>}
795
- */
796
- function compileHtmlTemplate(statics) {
797
- let mode = MODE_TEXT;
798
- let buffer = "";
799
- let quote = "";
800
- const tokens = [];
801
-
802
- const commit = () => {
803
- if (buffer) {
804
- if (mode === MODE_TEXT) {
805
- tokens.push([1, buffer]);
806
- } else if (mode === MODE_TAGNAME) {
807
- tokens.push([2, buffer]);
808
- } else if (mode === MODE_PROPNAME) {
809
- tokens.push([3, buffer]);
810
- } else if (mode === MODE_PROPVAL) {
811
- tokens.push([4, buffer]);
812
- }
813
- buffer = "";
814
- }
815
- };
816
-
817
- for (let i = 0; i < statics.length; i++) {
818
- if (i > 0) {
819
- commit();
820
- if (mode === MODE_TEXT) {
821
- tokens.push([5, i - 1]);
822
- } else if (mode === MODE_PROPVAL) {
823
- tokens.push([6, i - 1]);
824
- mode = MODE_WHITESPACE;
825
- } else if (mode === MODE_PROPNAME) {
826
- tokens.push([7, i - 1]);
827
- mode = MODE_WHITESPACE;
828
- } else if (mode === MODE_WHITESPACE) {
829
- tokens.push([7, i - 1]);
830
- }
831
- }
832
-
833
- const str = statics[i];
834
- for (let j = 0; j < str.length; j++) {
835
- const char = str[j];
836
-
837
- if (mode === MODE_TEXT) {
838
- if (char === "<") {
839
- commit();
840
- mode = MODE_TAGNAME;
841
- } else {
842
- buffer += char;
843
- }
844
- } else if (quote) {
845
- if (char === quote) {
846
- quote = "";
847
- commit();
848
- mode = MODE_WHITESPACE;
849
- } else {
850
- buffer += char;
851
- }
852
- } else if (char === '"' || char === "'") {
853
- quote = char;
854
- } else if (char === ">") {
855
- commit();
856
- tokens.push([8]);
857
- mode = MODE_TEXT;
858
- } else if (mode === MODE_TAGNAME) {
859
- if (char === "/" && buffer === "") {
860
- const closeEnd = str.indexOf(">", j);
861
- if (closeEnd !== -1) {
862
- tokens.push([9]);
863
- j = closeEnd;
864
- mode = MODE_TEXT;
865
- continue;
866
- }
867
- }
868
- if (char === " " || char === "\t" || char === "\n" || char === "\r") {
869
- commit();
870
- mode = MODE_WHITESPACE;
871
- } else if (char === "/" && str[j + 1] === ">") {
872
- commit();
873
- tokens.push([10]);
874
- j++;
875
- mode = MODE_TEXT;
876
- } else {
877
- buffer += char;
878
- }
879
- } else if (mode === MODE_WHITESPACE) {
880
- if (char === "/" && str[j + 1] === ">") {
881
- tokens.push([10]);
882
- j++;
883
- mode = MODE_TEXT;
884
- } else if (char === ">") {
885
- tokens.push([8]);
886
- mode = MODE_TEXT;
887
- } else if (char !== " " && char !== "\t" && char !== "\n" && char !== "\r") {
888
- buffer = char;
889
- mode = MODE_PROPNAME;
890
- }
891
- } else if (mode === MODE_PROPNAME) {
892
- if (char === "=") {
893
- commit();
894
- mode = MODE_PROPVAL;
895
- } else if (char === " " || char === "\t" || char === "\n" || char === "\r") {
896
- commit();
897
- mode = MODE_WHITESPACE;
898
- } else if (char === "/" && str[j + 1] === ">") {
899
- commit();
900
- tokens.push([10]);
901
- j++;
902
- mode = MODE_TEXT;
903
- } else if (char === ">") {
904
- commit();
905
- tokens.push([8]);
906
- mode = MODE_TEXT;
907
- } else {
908
- buffer += char;
909
- }
910
- } else if (mode === MODE_PROPVAL) {
911
- if (char === " " || char === "\t" || char === "\n" || char === "\r") {
912
- commit();
913
- mode = MODE_WHITESPACE;
914
- } else if (char === "/" && str[j + 1] === ">") {
915
- commit();
916
- tokens.push([10]);
917
- j++;
918
- mode = MODE_TEXT;
919
- } else if (char === ">") {
920
- commit();
921
- tokens.push([8]);
922
- mode = MODE_TEXT;
923
- } else {
924
- buffer += char;
925
- }
926
- }
927
- }
928
- }
929
-
930
- commit();
931
- return tokens;
932
- }
933
-
934
- /**
935
- * Evaluates compiled template tokens with dynamic fields into a Virtual DOM tree.
936
- * @param {Array<Array<any>>} tokens
937
- * @param {Array<any>} fields
938
- * @returns {Object|Array<any>}
939
- */
940
- function evaluateHtmlTemplate(tokens, fields) {
941
- const stack = [];
942
- let current = { tag: "root", props: {}, children: [] };
943
- let currentPropName = null;
944
-
945
- const pushChild = (child) => {
946
- if (child === null || child === undefined || typeof child === "boolean") return;
947
- if (typeof child === "string" && !child.trim() && current.children.length === 0 && stack.length === 0) {
948
- return;
949
- }
950
- if (Array.isArray(child)) {
951
- for (const c of child) pushChild(c);
952
- return;
953
- }
954
- current.children.push(child);
955
- };
956
-
957
- for (let i = 0; i < tokens.length; i++) {
958
- const t = tokens[i];
959
- const type = t[0];
960
-
961
- if (type === 1) {
962
- pushChild(t[1]);
963
- } else if (type === 2) {
964
- stack.push(current);
965
- current = { tag: t[1], props: {}, children: [] };
966
- } else if (type === 3) {
967
- current.props[t[1]] = true;
968
- currentPropName = t[1];
969
- } else if (type === 4) {
970
- if (currentPropName) {
971
- current.props[currentPropName] = t[1];
972
- currentPropName = null;
973
- }
974
- } else if (type === 5) {
975
- pushChild(fields[t[1]]);
976
- } else if (type === 6) {
977
- if (currentPropName) {
978
- current.props[currentPropName] = fields[t[1]];
979
- currentPropName = null;
980
- }
981
- } else if (type === 7) {
982
- const spread = fields[t[1]];
983
- if (spread && typeof spread === "object") {
984
- Object.assign(current.props, spread);
985
- }
986
- } else if (type === 8) {
987
- currentPropName = null;
988
- if (VOID_TAGS.has(current.tag.toLowerCase())) {
989
- const finished = current;
990
- current = stack.pop() || current;
991
- pushChild(finished);
992
- }
993
- } else if (type === 9) {
994
- const finished = current;
995
- current = stack.pop() || current;
996
- pushChild(finished);
997
- } else if (type === 10) {
998
- const finished = current;
999
- current = stack.pop() || current;
1000
- pushChild(finished);
1001
- }
1002
- }
1003
-
1004
- const rootChildren = current.children.filter((c) => typeof c !== "string" || c.trim());
1005
- return rootChildren.length === 1 ? rootChildren[0] : rootChildren;
1006
- }
1007
-
1008
- /**
1009
- * Tagged template helper for declarative HTML in client components.
1010
- * @param {TemplateStringsArray} statics
1011
- * @param {...any} fields
1012
- * @returns {Object|Array<any>}
1013
- */
1014
- function html(statics, ...fields) {
1015
- if (!statics || !statics.raw) {
1016
- return String(statics || "");
1017
- }
1018
- let tokens = templateCache.get(statics);
1019
- if (!tokens) {
1020
- tokens = compileHtmlTemplate(statics);
1021
- templateCache.set(statics, tokens);
1022
- }
1023
- return evaluateHtmlTemplate(tokens, fields);
1024
- }
1025
-
1026
- /**
1027
- * Fragment symbol/helper for JSX client components.
1028
- * @param {Object} props
1029
- * @returns {Array<any>}
1030
- */
1031
- function Fragment(props) {
1032
- return props?.children || [];
1033
- }
1034
-
1035
- /**
1036
- * Flatten and normalize JSX children arrays, filtering booleans and nullish values.
1037
- * @param {Array<any>} rawChildren
1038
- * @param {Array<any>} [target=[]]
1039
- * @returns {Array<any>}
1040
- */
1041
- function normalizeJsxChildren(rawChildren, target = []) {
1042
- for (let i = 0; i < rawChildren.length; i++) {
1043
- const child = rawChildren[i];
1044
- if (child === null || child === undefined || typeof child === "boolean") continue;
1045
- if (Array.isArray(child)) {
1046
- normalizeJsxChildren(child, target);
1047
- } else {
1048
- target.push(child);
1049
- }
1050
- }
1051
- return target;
1052
- }
1053
-
1054
- /**
1055
- * Hyperscript / JSX factory function for zero-build client JSX components.
1056
- * Compatible with Preact/React h(tag, props, ...children) signature and Bluebird VDOM.
1057
- * @param {string|Function} tag
1058
- * @param {Record<string, any>|null} props
1059
- * @param {...any} rawChildren
1060
- * @returns {Object|Array<any>}
1061
- */
1062
- function h(tag, props, ...rawChildren) {
1063
- const children = normalizeJsxChildren(rawChildren);
1064
- if (tag === Fragment || tag === "" || tag === "__bb_Fragment") {
1065
- return children;
1066
- }
1067
- if (typeof tag === "function") {
1068
- return tag(Object.assign({}, props || {}, { children }));
1069
- }
1070
- return {
1071
- tag: String(tag),
1072
- props: props || {},
1073
- children,
1074
- };
1075
- }
1076
-
1077
- /**
1078
- * Patches a virtual node into a target DOM parent element.
1079
- * @param {HTMLElement} parentDom
1080
- * @param {any} oldVNode
1081
- * @param {any} newVNode
1082
- * @param {number} index
1083
- */
1084
- function patch(parentDom, oldVNode, newVNode, index) {
1085
- const currentDom = parentDom.childNodes[index];
1086
-
1087
- if (newVNode === null || newVNode === undefined || typeof newVNode === "boolean") {
1088
- if (currentDom) {
1089
- parentDom.removeChild(currentDom);
1090
- }
1091
- return;
1092
- }
1093
-
1094
- if (typeof newVNode === "string" || typeof newVNode === "number") {
1095
- const textStr = String(newVNode);
1096
- if (currentDom && currentDom.nodeType === 3) {
1097
- if (currentDom.nodeValue !== textStr) {
1098
- currentDom.nodeValue = textStr;
1099
- }
1100
- } else {
1101
- const textNode = document.createTextNode(textStr);
1102
- if (currentDom) {
1103
- parentDom.replaceChild(textNode, currentDom);
1104
- } else {
1105
- parentDom.appendChild(textNode);
1106
- }
1107
- }
1108
- return;
1109
- }
1110
-
1111
- const tag = (newVNode.tag || newVNode.type || "").toUpperCase();
1112
- if (!tag) return;
1113
-
1114
- if (currentDom && currentDom.nodeType === 1 && currentDom.tagName === tag) {
1115
- patchProps(currentDom, oldVNode && typeof oldVNode === "object" ? oldVNode.props : {}, newVNode.props || {});
1116
- patchChildren(currentDom, oldVNode && typeof oldVNode === "object" ? oldVNode.children : [], newVNode.children || []);
1117
- } else {
1118
- const newEl = createDomNode(newVNode);
1119
- if (currentDom) {
1120
- parentDom.replaceChild(newEl, currentDom);
1121
- } else {
1122
- parentDom.appendChild(newEl);
1123
- }
1124
- }
1125
- }
1126
-
1127
- /**
1128
- * Creates a live DOM element from a Virtual DOM node.
1129
- * @param {any} vnode
1130
- * @returns {Node}
1131
- */
1132
- function createDomNode(vnode) {
1133
- if (typeof vnode === "string" || typeof vnode === "number") {
1134
- return document.createTextNode(String(vnode));
1135
- }
1136
- const tag = vnode.tag || vnode.type || "div";
1137
- const el = document.createElement(tag);
1138
- patchProps(el, {}, vnode.props || {});
1139
- const children = vnode.children || [];
1140
- for (let i = 0; i < children.length; i++) {
1141
- const c = children[i];
1142
- if (c === null || c === undefined || typeof c === "boolean") continue;
1143
- el.appendChild(createDomNode(c));
1144
- }
1145
- return el;
1146
- }
1147
-
1148
- /**
1149
- * Updates properties, attributes, and event listeners on a DOM node.
1150
- * @param {HTMLElement} dom
1151
- * @param {Record<string, any>} oldProps
1152
- * @param {Record<string, any>} newProps
1153
- */
1154
- function patchProps(dom, oldProps, newProps) {
1155
- oldProps = oldProps || {};
1156
- newProps = newProps || {};
1157
-
1158
- for (const key of Object.keys(oldProps)) {
1159
- if (!(key in newProps)) {
1160
- if (key.startsWith("on")) {
1161
- const evt = key.slice(2).toLowerCase();
1162
- if (dom._bb_events) delete dom._bb_events[evt];
1163
- } else if (key === "class" || key === "className") {
1164
- dom.className = "";
1165
- } else if (key === "style") {
1166
- dom.style.cssText = "";
1167
- } else {
1168
- dom.removeAttribute(key);
1169
- }
1170
- }
1171
- }
1172
-
1173
- for (const [key, val] of Object.entries(newProps)) {
1174
- if (val === undefined || val === null) {
1175
- if (key.startsWith("on")) {
1176
- const evt = key.slice(2).toLowerCase();
1177
- if (dom._bb_events) delete dom._bb_events[evt];
1178
- } else {
1179
- dom.removeAttribute(key);
1180
- }
1181
- continue;
1182
- }
1183
-
1184
- if (key.startsWith("on") && typeof val === "function") {
1185
- const evt = key.slice(2).toLowerCase();
1186
- dom._bb_events = dom._bb_events || {};
1187
- dom._bb_events[evt] = val;
1188
- if (!dom._bb_bound) dom._bb_bound = {};
1189
- if (!dom._bb_bound[evt]) {
1190
- dom._bb_bound[evt] = true;
1191
- dom.addEventListener(evt, (e) => {
1192
- if (dom._bb_events && dom._bb_events[evt]) {
1193
- dom._bb_events[evt](e);
1194
- }
1195
- });
1196
- }
1197
- continue;
1198
- }
1199
-
1200
- if (key === "class" || key === "className") {
1201
- if (dom.className !== val) dom.className = val || "";
1202
- continue;
1203
- }
1204
-
1205
- if (key === "style") {
1206
- if (typeof val === "object" && val !== null) {
1207
- Object.assign(dom.style, val);
1208
- } else if (dom.style.cssText !== val) {
1209
- dom.style.cssText = val || "";
1210
- }
1211
- continue;
1212
- }
1213
-
1214
- if (key === "value" && "value" in dom) {
1215
- if (dom.value !== String(val)) dom.value = val ?? "";
1216
- continue;
1217
- }
1218
-
1219
- if (key === "checked" && "checked" in dom) {
1220
- dom.checked = Boolean(val);
1221
- continue;
1222
- }
1223
-
1224
- if (typeof val === "boolean") {
1225
- if (val) dom.setAttribute(key, "");
1226
- else dom.removeAttribute(key);
1227
- continue;
1228
- }
1229
-
1230
- if (dom.getAttribute(key) !== String(val)) {
1231
- dom.setAttribute(key, String(val));
1232
- }
1233
- }
1234
- }
1235
-
1236
- /**
1237
- * Reconciles child nodes of a parent DOM element against an array of virtual child nodes.
1238
- * @param {HTMLElement} parentDom
1239
- * @param {Array<any>} oldChildren
1240
- * @param {Array<any>} newChildren
1241
- */
1242
- function patchChildren(parentDom, oldChildren, newChildren) {
1243
- oldChildren = oldChildren || [];
1244
- newChildren = newChildren || [];
1245
- const max = Math.max(oldChildren.length, newChildren.length);
1246
- let childIndex = 0;
1247
-
1248
- for (let i = 0; i < max; i++) {
1249
- const oldChild = oldChildren[i];
1250
- const newChild = newChildren[i];
1251
-
1252
- if (newChild === null || newChild === undefined || typeof newChild === "boolean") {
1253
- if (oldChild !== null && oldChild !== undefined && typeof oldChild !== "boolean") {
1254
- if (parentDom.childNodes[childIndex]) {
1255
- parentDom.removeChild(parentDom.childNodes[childIndex]);
1256
- }
1257
- }
1258
- continue;
1259
- }
1260
-
1261
- patch(parentDom, oldChild, newChild, childIndex);
1262
- childIndex++;
1263
- }
1264
-
1265
- while (parentDom.childNodes.length > childIndex) {
1266
- parentDom.removeChild(parentDom.lastChild);
1267
- }
1268
- }
1269
-
1270
- /**
1271
- * Updates root container nodes from a single virtual node or array of virtual nodes.
1272
- * @param {HTMLElement} container
1273
- * @param {any} oldVNode
1274
- * @param {any} newVNode
1275
- */
1276
- function patchRoot(container, oldVNode, newVNode) {
1277
- if (Array.isArray(newVNode)) {
1278
- const oldArr = Array.isArray(oldVNode) ? oldVNode : oldVNode ? [oldVNode] : [];
1279
- patchChildren(container, oldArr, newVNode);
1280
- } else {
1281
- patch(container, oldVNode, newVNode, 0);
1282
- while (container.childNodes.length > 1) {
1283
- container.removeChild(container.lastChild);
1284
- }
1285
- }
1286
- }
1287
-
1288
- let activeInstance = null;
1289
-
1290
- /**
1291
- * Declares a reactive state variable in a client component.
1292
- * Triggers scheduled reconciliation when updater is called with a new value.
1293
- * @param {any} [initial]
1294
- * @returns {[any, Function]}
1295
- */
1296
- function useState(initial) {
1297
- if (!activeInstance) {
1298
- const val = typeof initial === "function" ? initial() : initial;
1299
- return [val, () => {}];
1300
- }
1301
- const inst = activeInstance;
1302
- const idx = inst.hookIndex++;
1303
- if (inst.hooks.length <= idx) {
1304
- const val = typeof initial === "function" ? initial() : initial;
1305
- inst.hooks[idx] = val;
1306
- }
1307
- const setState = (nextVal) => {
1308
- const current = inst.hooks[idx];
1309
- const computed = typeof nextVal === "function" ? nextVal(current) : nextVal;
1310
- if (!Object.is(current, computed)) {
1311
- inst.hooks[idx] = computed;
1312
- scheduleComponentUpdate(inst);
1313
- }
1314
- };
1315
- return [inst.hooks[idx], setState];
1316
- }
1317
-
1318
- /**
1319
- * Runs side effects after DOM reconciliation and cleans up before next invocation or unmount.
1320
- * @param {Function} effectFn
1321
- * @param {Array<any>} [deps]
1322
- */
1323
- function useEffect(effectFn, deps) {
1324
- if (!activeInstance) return;
1325
- const inst = activeInstance;
1326
- const idx = inst.hookIndex++;
1327
- const prev = inst.hooks[idx];
1328
- const hasChanged = !prev || !deps || deps.some((d, i) => !Object.is(d, prev.deps[i]));
1329
- if (hasChanged) {
1330
- inst.effects.push({
1331
- idx,
1332
- effectFn,
1333
- deps,
1334
- prevCleanup: prev?.cleanup,
1335
- });
1336
- }
1337
- }
1338
-
1339
- /**
1340
- * Persists a mutable object reference across component re-renders without triggering updates.
1341
- * @param {any} [initial]
1342
- * @returns {{ current: any }}
1343
- */
1344
- function useRef(initial) {
1345
- if (!activeInstance) return { current: initial };
1346
- const inst = activeInstance;
1347
- const idx = inst.hookIndex++;
1348
- if (inst.hooks.length <= idx) {
1349
- inst.hooks[idx] = { current: initial };
1350
- }
1351
- return inst.hooks[idx];
1352
- }
1353
-
1354
- /**
1355
- * Caches a computed calculation across re-renders until dependency array values change.
1356
- * @param {Function} fn
1357
- * @param {Array<any>} [deps]
1358
- * @returns {any}
1359
- */
1360
- function useMemo(fn, deps) {
1361
- if (!activeInstance) return typeof fn === "function" ? fn() : fn;
1362
- const inst = activeInstance;
1363
- const idx = inst.hookIndex++;
1364
- const prev = inst.hooks[idx];
1365
- const hasChanged = !prev || !deps || deps.some((d, i) => !Object.is(d, prev.deps[i]));
1366
- if (hasChanged) {
1367
- const value = fn();
1368
- inst.hooks[idx] = { value, deps };
1369
- return value;
1370
- }
1371
- return prev.value;
1372
- }
1373
-
1374
- /**
1375
- * Returns a memoized callback function that only changes when its dependencies change.
1376
- * @param {Function} fn
1377
- * @param {Array<any>} [deps]
1378
- * @returns {Function}
1379
- */
1380
- function useCallback(fn, deps) {
1381
- return useMemo(() => fn, deps);
1382
- }
1383
-
1384
- /**
1385
- * Manages Server Action execution with reactive pending state, data, and error handling.
1386
- * Returns [execute, isPending, data, error, reset].
1387
- *
1388
- * @param {string|Function} actionName - Registered Server Action name or action handler function.
1389
- * @param {Object} [options={}] - Options (url, partial, onSuccess, onError, onSettled).
1390
- * @returns {[Function, boolean, any, any, Function]}
1391
- */
1392
- function useAction(actionName, options = {}) {
1393
- const [isPending, setIsPending] = useState(false);
1394
- const [data, setData] = useState(null);
1395
- const [error, setError] = useState(null);
1396
- const optionsRef = useRef(options);
1397
- optionsRef.current = options;
1398
-
1399
- const execute = useCallback(
1400
- async (payload = {}) => {
1401
- setIsPending(true);
1402
- setError(null);
1403
- try {
1404
- let res;
1405
- const resolvedName =
1406
- typeof actionName === "string"
1407
- ? actionName
1408
- : actionName?.__actionName || actionName?.name || null;
1409
-
1410
- if (resolvedName && Bluebird && typeof Bluebird.action === "function") {
1411
- res = await Bluebird.action(resolvedName, payload, optionsRef.current);
1412
- } else if (typeof actionName === "function") {
1413
- res = await actionName(payload, optionsRef.current);
1414
- } else if (Bluebird && typeof Bluebird.action === "function") {
1415
- res = await Bluebird.action(actionName, payload, optionsRef.current);
1416
- }
1417
- setData(res);
1418
- setIsPending(false);
1419
- if (typeof optionsRef.current?.onSuccess === "function") {
1420
- optionsRef.current.onSuccess(res);
1421
- }
1422
- return res;
1423
- } catch (err) {
1424
- setError(err);
1425
- setIsPending(false);
1426
- if (typeof optionsRef.current?.onError === "function") {
1427
- optionsRef.current.onError(err);
1428
- }
1429
- throw err;
1430
- } finally {
1431
- if (typeof optionsRef.current?.onSettled === "function") {
1432
- optionsRef.current.onSettled();
1433
- }
1434
- }
1435
- },
1436
- [actionName]
1437
- );
1438
-
1439
- const reset = useCallback(() => {
1440
- setIsPending(false);
1441
- setData(null);
1442
- setError(null);
1443
- }, []);
1444
-
1445
- return [execute, isPending, data, error, reset];
1446
- }
1447
-
1448
- /**
1449
- * React 19-compatible useActionState hook for Server Actions and form submissions.
1450
- *
1451
- * @param {string|Function} actionFn - Action name or async reducer (prevState, formDataOrPayload) => nextState.
1452
- * @param {any} initialState - Initial state value before any action executes.
1453
- * @returns {[any, Function, boolean]} [state, dispatch, isPending]
1454
- */
1455
- function useActionState(actionFn, initialState) {
1456
- const [state, setState] = useState(initialState);
1457
- const [isPending, setIsPending] = useState(false);
1458
-
1459
- const dispatch = useCallback(
1460
- async (payload) => {
1461
- setIsPending(true);
1462
- try {
1463
- let nextState;
1464
- const resolvedName =
1465
- typeof actionFn === "string"
1466
- ? actionFn
1467
- : actionFn?.__actionName || actionFn?.name || null;
1468
-
1469
- if (resolvedName && Bluebird && typeof Bluebird.action === "function") {
1470
- const res = await Bluebird.action(resolvedName, payload);
1471
- nextState = res?.data !== undefined ? res.data : res;
1472
- } else if (typeof actionFn === "function") {
1473
- nextState = await actionFn(state, payload);
1474
- }
1475
- setState(nextState);
1476
- return nextState;
1477
- } finally {
1478
- setIsPending(false);
1479
- }
1480
- },
1481
- [actionFn, state]
1482
- );
1483
-
1484
- return [state, dispatch, isPending];
1485
- }
1486
-
1487
- const activeComponentInstances = new Map();
1488
-
1489
- /**
1490
- * Schedules microtask reconciliation for a dirty component instance.
1491
- * @param {Object} inst
1492
- */
1493
- function scheduleComponentUpdate(inst) {
1494
- if (inst.scheduled) return;
1495
- inst.scheduled = true;
1496
- queueMicrotask(() => {
1497
- if (!inst.mounted) return;
1498
- renderComponentInstance(inst);
1499
- });
1500
- }
1501
-
1502
- /**
1503
- * Invokes component render function, applies DOM patches, and runs queued effects.
1504
- * @param {Object} inst
1505
- */
1506
- function renderComponentInstance(inst) {
1507
- inst.scheduled = false;
1508
- inst.hookIndex = 0;
1509
- activeInstance = inst;
1510
- window.useState = window.useState || useState;
1511
- window.useEffect = window.useEffect || useEffect;
1512
- window.useAction = window.useAction || useAction;
1513
- window.useActionState = window.useActionState || useActionState;
1514
- window.useRef = useRef;
1515
- window.useMemo = useMemo;
1516
- window.useCallback = useCallback;
1517
- window.h = window.h || h;
1518
- window.Fragment = window.Fragment || Fragment;
1519
- window.__bb_h = h;
1520
- window.__bb_Fragment = Fragment;
1521
-
1522
- let vnode;
1523
- try {
1524
- const clientCtx = {
1525
- el: inst.el,
1526
- root: inst.el,
1527
- Bluebird,
1528
- useState,
1529
- useEffect,
1530
- useAction,
1531
- useActionState,
1532
- useRef,
1533
- useMemo,
1534
- useCallback,
1535
- h,
1536
- Fragment,
1537
- __bb_h: h,
1538
- __bb_Fragment: Fragment,
1539
- html,
1540
- };
1541
- if (inst.fn.length >= 2) {
1542
- vnode = inst.fn(inst.el, inst.props, clientCtx);
1543
- } else {
1544
- vnode = inst.fn(Object.assign({}, inst.props, clientCtx));
1545
- }
1546
- } catch (err) {
1547
- console.error("[BLUEBIRD COMPONENT ERROR]:", err);
1548
- return;
1549
- } finally {
1550
- activeInstance = null;
1551
- }
1552
-
1553
- if (vnode === undefined) {
1554
- return;
1555
- }
1556
-
1557
- if (!inst.hasRenderedVNode) {
1558
- inst.hasRenderedVNode = true;
1559
- const mountScript = inst.el.querySelector('script[data-bb-client-mount="true"]');
1560
- if (mountScript) {
1561
- mountScript.remove();
1562
- }
1563
- inst.el.innerHTML = "";
1564
- }
1565
-
1566
- patchRoot(inst.el, inst.prevVNode, vnode);
1567
- inst.prevVNode = vnode;
1568
-
1569
- const effects = inst.effects;
1570
- inst.effects = [];
1571
- for (const eff of effects) {
1572
- if (typeof eff.prevCleanup === "function") {
1573
- try { eff.prevCleanup(); } catch (err) { console.error(err); }
1574
- }
1575
- try {
1576
- const cleanup = eff.effectFn();
1577
- inst.hooks[eff.idx] = {
1578
- deps: eff.deps,
1579
- cleanup: typeof cleanup === "function" ? cleanup : null,
1580
- };
1581
- } catch (err) {
1582
- console.error(err);
1583
- }
1584
- }
1585
- }
1586
-
1587
- /**
1588
- * Mounts a client component into a DOM element with reactive state and lifecycle management.
1589
- * @param {HTMLElement} el
1590
- * @param {Function} fn
1591
- * @param {Record<string, any>} [props={}]
1592
- */
1593
- function mountComponent(el, fn, props) {
1594
- if (!el || typeof fn !== "function") return;
1595
- let inst = activeComponentInstances.get(el);
1596
- if (!inst) {
1597
- inst = {
1598
- el,
1599
- fn,
1600
- props: props || {},
1601
- hooks: [],
1602
- hookIndex: 0,
1603
- effects: [],
1604
- prevVNode: null,
1605
- hasRenderedVNode: false,
1606
- scheduled: false,
1607
- mounted: true,
1608
- };
1609
- activeComponentInstances.set(el, inst);
1610
- mountedRoots.set(el, {
1611
- unmount: () => unmountComponentInstance(el),
1612
- persist: el.getAttribute("data-persist") === "true",
1613
- name: el.getAttribute("data-island") || fn.name || "ClientComponent",
1614
- });
1615
- } else {
1616
- inst.fn = fn;
1617
- inst.props = props || {};
1618
- }
1619
-
1620
- renderComponentInstance(inst);
1621
- }
1622
-
1623
- /**
1624
- * Cleans up hooks, effects, and active state for an unmounting component.
1625
- * @param {HTMLElement} el
1626
- */
1627
- function unmountComponentInstance(el) {
1628
- const inst = activeComponentInstances.get(el);
1629
- if (!inst) return;
1630
- inst.mounted = false;
1631
- for (const hook of inst.hooks) {
1632
- if (hook && typeof hook.cleanup === "function") {
1633
- try { hook.cleanup(); } catch (err) { console.error(err); }
1634
- }
1635
- }
1636
- activeComponentInstances.delete(el);
1637
- }
1638
-
1639
- /**
1640
- * Executes queued component mount requests initialized before runtime script completion.
1641
- */
1642
- function drainMountQueue() {
1643
- if (window.__BB_MOUNT_QUEUE__ && Array.isArray(window.__BB_MOUNT_QUEUE__)) {
1644
- const queue = window.__BB_MOUNT_QUEUE__.splice(0);
1645
- for (const task of queue) {
1646
- try { task(); } catch (err) { console.error(err); }
1647
- }
1648
- }
1649
- }
1650
-
1651
- Bluebird.h = h;
1652
- Bluebird.Fragment = Fragment;
1653
- Bluebird.__bb_h = h;
1654
- Bluebird.__bb_Fragment = Fragment;
1655
- Bluebird.html = html; // Se mantiene por retrocompatibilidad
1656
- Bluebird.mount = mountComponent;
1657
- Bluebird.mountComponent = mountComponent;
1658
- Bluebird.useState = useState;
1659
- Bluebird.useEffect = useEffect;
1660
- Bluebird.useRef = useRef;
1661
- Bluebird.useMemo = useMemo;
1662
- Bluebird.useCallback = useCallback;
1663
- Bluebird.useAction = useAction;
1664
- Bluebird.useActionState = useActionState;
1665
-
1666
- window.h = h;
1667
- window.Fragment = Fragment;
1668
- window.__bb_h = h;
1669
- window.__bb_Fragment = Fragment;
1670
- window.html = html;
1671
- window.useState = useState;
1672
- window.useEffect = useEffect;
1673
- window.useRef = useRef;
1674
- window.useMemo = useMemo;
1675
- window.useCallback = useCallback;
1676
- window.useAction = useAction;
1677
- window.useActionState = useActionState;
1678
-
1679
- window.Bluebird = Bluebird;
1680
- drainMountQueue();
1681
-
1682
- /**
1683
- * Initializes automatic page reload during development when the Node server restarts.
1684
- */
1685
- function initDevReload() {
1686
- if (typeof window === "undefined" || !window.EventSource) return;
1687
- const isLocalhost =
1688
- window.location.hostname === "localhost" ||
1689
- window.location.hostname === "127.0.0.1" ||
1690
- window.location.hostname === "::1";
1691
- if (!isLocalhost) return;
1692
-
1693
- let initialBootId = null;
1694
- let connectedOnce = false;
1695
- let failedAttempts = 0;
1696
- let es = null;
1697
-
1698
- function connect() {
1699
- try {
1700
- es = new EventSource("/_bb/dev-reload");
1701
-
1702
- es.onmessage = (event) => {
1703
- try {
1704
- const data = JSON.parse(event.data);
1705
- if (data.type === "connected" && data.bootId) {
1706
- connectedOnce = true;
1707
- failedAttempts = 0;
1708
- if (initialBootId === null) {
1709
- initialBootId = data.bootId;
1710
- } else if (initialBootId !== data.bootId) {
1711
- console.log("[Bluebird] Server restart detected, reloading page...");
1712
- window.location.reload();
1713
- }
1714
- }
1715
- } catch {}
1716
- };
1717
-
1718
- es.onerror = () => {
1719
- try { es.close(); } catch {}
1720
- if (!connectedOnce) {
1721
- failedAttempts++;
1722
- if (failedAttempts > 2) return;
1723
- setTimeout(connect, 1000);
1724
- return;
1725
- }
1726
- setTimeout(connect, 500);
1727
- };
1728
- } catch {}
1729
- }
1730
-
1731
- connect();
1732
- }
1733
-
1734
- /**
1735
- * Initializes client router, hydrates components, and emits initial page-load event.
1736
- */
1737
- function triggerInitialLoad() {
1738
- initLinkInterception();
1739
- Bluebird.hydrate();
1740
- drainMountQueue();
1741
- initDevReload();
1742
- const detail = { url: window.location.href, initial: true };
1743
- window.dispatchEvent(new CustomEvent("bluebird:page-load", { detail }));
1744
- document.dispatchEvent(new CustomEvent("bluebird:page-load", { detail }));
1745
- }
1746
-
1747
- if (document.readyState === "loading") {
1748
- document.addEventListener("DOMContentLoaded", triggerInitialLoad);
1749
- } else {
1750
- triggerInitialLoad();
1751
- }
1752
- })();
1753
- /**
1754
- * Bluebird Client UI & Interactive Runtime.
1755
- * Styled with Tailwind CSS v4 and designed for SPA navigation and desktop apps.
1756
- */
1757
-
1758
- /**
1759
- * Escapes HTML special characters in client-side strings.
1760
- * @param {any} str
1761
- * @returns {string}
1762
- */
1763
- function escapeClientHtml(str) {
1764
- if (str === null || str === undefined) return "";
1765
- return String(str)
1766
- .replace(/&/g, "&amp;")
1767
- .replace(/</g, "&lt;")
1768
- .replace(/>/g, "&gt;")
1769
- .replace(/"/g, "&quot;")
1770
- .replace(/'/g, "&#39;");
1771
- }
1772
-
1773
- let customCommandsList = null;
1774
- if (typeof window !== "undefined") {
1775
- window.Bluebird = window.Bluebird || {};
1776
- window.Bluebird.setCommands = function (items) {
1777
- customCommandsList = Array.isArray(items) ? items : null;
1778
- };
1779
- }
1780
-
1781
- /**
1782
- * Global component dispatcher for Bluebird interactive widgets.
1783
- * @param {string|Object} component
1784
- * @param {Object} [options]
1785
- */
1786
- function bluebird(component, options) {
1787
- if (typeof component === "object") {
1788
- options = component;
1789
- component = "snackbar";
1790
- }
1791
-
1792
- if (component === "snackbar") {
1793
- let snackbarEl = document.getElementById("snackbar");
1794
- if (!snackbarEl) {
1795
- snackbarEl = document.createElement("div");
1796
- snackbarEl.id = "snackbar";
1797
- document.body.appendChild(snackbarEl);
1798
- }
1799
-
1800
- const type = (options && options.type) || "info";
1801
- let colorClasses = "bg-slate-900 text-slate-100 border border-slate-700/80";
1802
- if (type === "success") {
1803
- colorClasses = "bg-emerald-950/95 text-emerald-100 border border-emerald-500/40";
1804
- } else if (type === "warning") {
1805
- colorClasses = "bg-amber-950/95 text-amber-100 border border-amber-500/40";
1806
- } else if (type === "error" || type === "danger") {
1807
- colorClasses = "bg-red-950/95 text-red-100 border border-red-500/40";
1808
- }
1809
-
1810
- const baseClasses =
1811
- "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";
1812
- snackbarEl.className = `${baseClasses} ${colorClasses} opacity-0 translate-y-4 pointer-events-none`;
1813
- snackbarEl.textContent = (options && options.message) || "";
1814
-
1815
- setTimeout(() => {
1816
- snackbarEl.classList.remove("opacity-0", "translate-y-4", "pointer-events-none");
1817
- snackbarEl.classList.add("opacity-100", "translate-y-0", "pointer-events-auto");
1818
- }, 10);
1819
-
1820
- const duration = (options && options.duration) || 3000;
1821
- if (snackbarEl.timeoutId) {
1822
- clearTimeout(snackbarEl.timeoutId);
1823
- }
1824
- snackbarEl.timeoutId = setTimeout(function () {
1825
- snackbarEl.classList.remove("opacity-100", "translate-y-0", "pointer-events-auto");
1826
- snackbarEl.classList.add("opacity-0", "translate-y-4", "pointer-events-none");
1827
- }, duration);
1828
- }
1829
-
1830
- if (component === "toast") {
1831
- const position = (options && options.position) || "bottom-right";
1832
- const posMap = {
1833
- "bottom-right": "fixed bottom-4 right-4 z-[100] flex flex-col gap-2.5 w-full max-w-sm pointer-events-none",
1834
- "bottom-left": "fixed bottom-4 left-4 z-[100] flex flex-col gap-2.5 w-full max-w-sm pointer-events-none",
1835
- "top-right": "fixed top-4 right-4 z-[100] flex flex-col gap-2.5 w-full max-w-sm pointer-events-none",
1836
- "top-left": "fixed top-4 left-4 z-[100] flex flex-col gap-2.5 w-full max-w-sm pointer-events-none",
1837
- "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",
1838
- "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",
1839
- };
1840
- const containerClass = posMap[position] || posMap["bottom-right"];
1841
- let container = document.querySelector(`.toast-container[data-position="${position}"]`);
1842
- if (!container) {
1843
- container = document.createElement("div");
1844
- container.className = `toast-container ${containerClass}`;
1845
- container.setAttribute("data-position", position);
1846
- document.body.appendChild(container);
1847
- }
1848
-
1849
- const toastEl = document.createElement("div");
1850
- const type = (options && options.type) || "info";
1851
- let variantClass = "bg-slate-900/95 border-slate-700/80 text-slate-100";
1852
- if (type === "success") {
1853
- variantClass = "bg-slate-900/95 border-emerald-500/40 text-slate-100";
1854
- } else if (type === "error" || type === "danger") {
1855
- variantClass = "bg-slate-900/95 border-red-500/40 text-slate-100";
1856
- } else if (type === "warning") {
1857
- variantClass = "bg-slate-900/95 border-amber-500/40 text-slate-100";
1858
- }
1859
-
1860
- 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}`;
1861
- const title = options && options.title
1862
- ? `<div class="toast-title font-semibold text-sm">${escapeClientHtml(options.title)}</div>`
1863
- : "";
1864
- const desc = options && options.description
1865
- ? `<div class="toast-description text-xs text-slate-300 mt-0.5 leading-relaxed">${escapeClientHtml(options.description)}</div>`
1866
- : "";
1867
-
1868
- toastEl.innerHTML = `
1869
- <div class="toast-content flex-1 min-w-0">
1870
- ${title}
1871
- ${desc}
1872
- </div>
1873
- <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>
1874
- `;
1875
-
1876
- const closeBtn = toastEl.querySelector(".toast-close");
1877
- closeBtn.addEventListener("click", () => dismissToast(toastEl));
1878
- container.appendChild(toastEl);
1879
-
1880
- const duration = (options && options.duration) !== undefined ? options.duration : 4000;
1881
- if (duration > 0) {
1882
- setTimeout(() => dismissToast(toastEl), duration);
1883
- }
1884
- }
1885
-
1886
- if (component === "tab") {
1887
- const targetId = options && options.id;
1888
- if (!targetId) return;
1889
- const targetContent = document.getElementById(targetId);
1890
- if (!targetContent) return;
1891
-
1892
- const tabsContainer = targetContent.closest(".tabs") || document.body;
1893
- const allTriggers = tabsContainer.querySelectorAll(".tab-trigger, [data-tab-target]");
1894
- const allContents = tabsContainer.querySelectorAll(".tab-content, [data-tab-content]");
1895
-
1896
- allContents.forEach((c) => {
1897
- c.classList.remove("active", "block");
1898
- c.classList.add("hidden");
1899
- });
1900
- allTriggers.forEach((t) => {
1901
- t.classList.remove("active", "border-sky-500", "text-sky-400");
1902
- t.setAttribute("aria-selected", "false");
1903
- });
1904
-
1905
- targetContent.classList.remove("hidden");
1906
- targetContent.classList.add("active", "block");
1907
-
1908
- const matchingTrigger = Array.from(allTriggers).find(
1909
- (t) =>
1910
- t.getAttribute("data-tab-target") === targetId ||
1911
- t.getAttribute("href") === `#${targetId}`
1912
- );
1913
- if (matchingTrigger) {
1914
- matchingTrigger.classList.add("active", "border-sky-500", "text-sky-400");
1915
- matchingTrigger.setAttribute("aria-selected", "true");
1916
- }
1917
- }
1918
-
1919
- if (component === "command") {
1920
- const action = (options && options.action) || "toggle";
1921
- let backdrop = document.querySelector(".command-backdrop");
1922
- if (!backdrop) {
1923
- backdrop = createCommandPaletteModal();
1924
- }
1925
- const isOpen = backdrop.classList.contains("open");
1926
- if (action === "open" || (action === "toggle" && !isOpen)) {
1927
- backdrop.classList.remove("hidden");
1928
- backdrop.classList.add("flex", "open");
1929
- const input = backdrop.querySelector(".command-input");
1930
- if (input) {
1931
- input.value = "";
1932
- setTimeout(() => input.focus(), 50);
1933
- }
1934
- } else if (action === "close" || (action === "toggle" && isOpen)) {
1935
- backdrop.classList.remove("flex", "open");
1936
- backdrop.classList.add("hidden");
1937
- }
1938
- }
1939
-
1940
- if (component === "popover") {
1941
- const id = options && (options.id || options.targetId);
1942
- const action = (options && options.action) || "toggle";
1943
- if (!id) return;
1944
- const popoverEl =
1945
- document.getElementById(id) || document.querySelector(`[data-popover-id="${id}"]`);
1946
- if (!popoverEl) return;
1947
- const isOpen = popoverEl.classList.contains("open");
1948
- const shouldOpen = action === "open" || (action === "toggle" && !isOpen);
1949
- popoverEl.classList.toggle("hidden", !shouldOpen);
1950
- popoverEl.classList.toggle("open", shouldOpen);
1951
- }
1952
-
1953
- if (component === "drawer") {
1954
- cleanupOrphanedBackdrops();
1955
- const id = options && options.id;
1956
- const action = (options && options.action) || "toggle";
1957
- if (!id) return;
1958
- const drawerEl = document.getElementById(id);
1959
- if (!drawerEl) return;
1960
-
1961
- let overlay = document.querySelector(`.drawer-backdrop[data-for="${id}"]`);
1962
- if (!overlay) {
1963
- overlay = document.createElement("div");
1964
- overlay.className =
1965
- "drawer-backdrop fixed inset-0 z-40 bg-slate-950/60 backdrop-blur-xs transition-opacity duration-300 opacity-0 pointer-events-none";
1966
- overlay.setAttribute("data-for", id);
1967
- document.body.appendChild(overlay);
1968
- overlay.addEventListener("click", () => {
1969
- bluebird("drawer", { id, action: "close" });
1970
- });
1971
- }
1972
-
1973
- const isOpen = drawerEl.classList.contains("open") || drawerEl.classList.contains("active");
1974
- if (action === "open" || (action === "toggle" && !isOpen)) {
1975
- drawerEl.classList.add("open");
1976
- drawerEl.classList.remove("-translate-x-full");
1977
- drawerEl.classList.add("translate-x-0");
1978
- overlay.classList.remove("opacity-0", "pointer-events-none");
1979
- overlay.classList.add("opacity-100", "pointer-events-auto", "open");
1980
- document.body.style.overflow = "hidden";
1981
- } else if (action === "close" || (action === "toggle" && isOpen)) {
1982
- drawerEl.classList.remove("open", "translate-x-0");
1983
- drawerEl.classList.add("-translate-x-full");
1984
- overlay.classList.remove("opacity-100", "pointer-events-auto", "open");
1985
- overlay.classList.add("opacity-0", "pointer-events-none");
1986
- document.body.style.overflow = "";
1987
- setTimeout(() => {
1988
- if (overlay && overlay.parentNode && !drawerEl.classList.contains("open")) {
1989
- overlay.remove();
1990
- }
1991
- }, 300);
1992
- }
1993
- }
1994
-
1995
- if (component === "carousel") {
1996
- const selector = (options && options.selector) || ".carousel";
1997
- const carousels = document.querySelectorAll(selector);
1998
- carousels.forEach((carousel) => initSingleCarousel(carousel, options));
1999
- }
2000
-
2001
- if (component === "datatable" || component === "table") {
2002
- const containerId = (options && (options.container || options.id)) || "datatable";
2003
- return new ResponsiveDataTable(containerId, options);
2004
- }
2005
- }
2006
-
2007
- /**
2008
- * Display a temporary snackbar message.
2009
- * @param {Object} options
2010
- */
2011
- function snackbar(options) {
2012
- bluebird("snackbar", options);
2013
- }
2014
-
2015
- /**
2016
- * Display a temporary toast notification.
2017
- * @param {Object} options
2018
- */
2019
- function toast(options) {
2020
- bluebird("toast", options);
2021
- }
2022
-
2023
- /**
2024
- * Dismisses a toast element with animation.
2025
- * @param {HTMLElement} toastEl
2026
- */
2027
- function dismissToast(toastEl) {
2028
- if (!toastEl || toastEl.isDismissing) return;
2029
- toastEl.isDismissing = true;
2030
- toastEl.style.opacity = "0";
2031
- toastEl.style.transform = "translateY(-10px) scale(0.95)";
2032
- setTimeout(() => {
2033
- if (toastEl.parentNode) {
2034
- toastEl.remove();
2035
- }
2036
- }, 200);
2037
- }
2038
-
2039
- /**
2040
- * Creates and injects the global command palette modal.
2041
- * @returns {HTMLElement}
2042
- */
2043
- function createCommandPaletteModal() {
2044
- const backdrop = document.createElement("div");
2045
- backdrop.className =
2046
- "command-backdrop fixed inset-0 z-[100] hidden items-start justify-center bg-slate-950/70 backdrop-blur-xs pt-[14vh] px-4";
2047
-
2048
- let itemsHtml = "";
2049
- if (customCommandsList && customCommandsList.length > 0) {
2050
- itemsHtml = customCommandsList
2051
- .map(
2052
- (item) => `
2053
- <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 || "")}">
2054
- <span>${escapeClientHtml(item.label || item.title || item.name)}</span>
2055
- <kbd class="text-[10px] px-1.5 py-0.5 rounded bg-slate-800 text-slate-400 border border-slate-700">↵</kbd>
2056
- </div>
2057
- `
2058
- )
2059
- .join("");
2060
- } else {
2061
- itemsHtml = `
2062
- <div class="command-group space-y-1">
2063
- <div class="command-group-title px-3 py-1 text-[11px] font-semibold uppercase tracking-wider text-slate-500">Navigation</div>
2064
- <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>
2065
- <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>
2066
- <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>
2067
- <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>
2068
- </div>
2069
- `;
2070
- }
2071
-
2072
- backdrop.innerHTML = `
2073
- <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">
2074
- <div class="command-input-wrapper flex items-center gap-3 px-4 py-3 border-b border-slate-800">
2075
- <span class="text-slate-400">🔍</span>
2076
- <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..." />
2077
- <kbd class="text-[10px] px-1.5 py-0.5 rounded bg-slate-800 text-slate-400 border border-slate-700">ESC</kbd>
2078
- </div>
2079
- <div class="command-list max-h-80 overflow-y-auto p-2 space-y-2">
2080
- ${itemsHtml}
2081
- </div>
2082
- </div>
2083
- `;
2084
-
2085
- document.body.appendChild(backdrop);
2086
- backdrop.addEventListener("click", (e) => {
2087
- if (e.target === backdrop) {
2088
- bluebird("command", { action: "close" });
2089
- }
2090
- });
2091
-
2092
- const input = backdrop.querySelector(".command-input");
2093
- input.addEventListener("input", (e) => {
2094
- const query = e.target.value.toLowerCase().trim();
2095
- const items = backdrop.querySelectorAll(".command-item");
2096
- items.forEach((item) => {
2097
- const text = item.textContent.toLowerCase();
2098
- item.style.display = text.includes(query) ? "flex" : "none";
2099
- });
2100
- });
2101
-
2102
- backdrop.addEventListener("click", (e) => {
2103
- const item = e.target.closest(".command-item");
2104
- if (item && item.getAttribute("data-navigate")) {
2105
- const dest = item.getAttribute("data-navigate");
2106
- if (dest.startsWith("/") && window.Bluebird && typeof window.Bluebird.navigate === "function") {
2107
- window.Bluebird.navigate(dest);
2108
- } else {
2109
- window.location.href = dest;
2110
- }
2111
- bluebird("command", { action: "close" });
2112
- }
2113
- });
2114
-
2115
- return backdrop;
2116
- }
2117
-
2118
- /**
2119
- * Removes backdrops whose associated elements are no longer in the DOM.
2120
- */
2121
- function cleanupOrphanedBackdrops() {
2122
- document.querySelectorAll(".drawer-backdrop[data-for]").forEach((backdrop) => {
2123
- const targetId = backdrop.getAttribute("data-for");
2124
- if (!document.getElementById(targetId)) {
2125
- backdrop.remove();
2126
- }
2127
- });
2128
- }
2129
-
2130
- /**
2131
- * Initializes responsive mobile drawer navigation menu.
2132
- */
2133
- function initMobileDrawer() {
2134
- const mainEl = document.querySelector("main");
2135
- const aside = mainEl ? mainEl.querySelector(":scope > aside") : null;
2136
- if (!aside) return;
2137
-
2138
- let overlay = document.querySelector(".bluebird-drawer-overlay");
2139
- if (!overlay) {
2140
- overlay = document.createElement("div");
2141
- overlay.className =
2142
- "bluebird-drawer-overlay fixed inset-0 z-40 bg-slate-950/60 backdrop-blur-xs hidden";
2143
- document.body.appendChild(overlay);
2144
- }
2145
-
2146
- let drawer = document.querySelector(".bluebird-drawer");
2147
- if (!drawer) {
2148
- drawer = document.createElement("div");
2149
- drawer.className =
2150
- "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";
2151
- document.body.appendChild(drawer);
2152
- }
2153
- drawer.innerHTML = aside.innerHTML;
2154
-
2155
- let toggle = document.querySelector(".bluebird-drawer-toggle");
2156
- if (!toggle) {
2157
- toggle = document.createElement("button");
2158
- toggle.className =
2159
- "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";
2160
- toggle.innerHTML = '<span class="text-lg leading-none">☰</span>';
2161
- toggle.setAttribute("aria-label", "Toggle navigation menu");
2162
- const header = document.querySelector("header");
2163
- if (header) {
2164
- const nav = header.querySelector("nav");
2165
- if (nav) {
2166
- nav.insertBefore(toggle, nav.firstChild);
2167
- } else {
2168
- header.prepend(toggle);
2169
- }
2170
- } else {
2171
- document.body.prepend(toggle);
2172
- }
2173
- }
2174
- }
2175
-
2176
- /**
2177
- * Initializes a single carousel container.
2178
- * @param {HTMLElement} carousel
2179
- * @param {Object} [opts]
2180
- */
2181
- function initSingleCarousel(carousel, opts = {}) {
2182
- if (carousel._bb_initialized) return;
2183
- carousel._bb_initialized = true;
2184
-
2185
- const track = carousel.querySelector(".carousel-track");
2186
- if (!track) return;
2187
- track.classList.add("flex", "overflow-x-auto", "snap-x", "snap-mandatory", "scroll-smooth", "gap-4");
2188
-
2189
- const items = Array.from(track.querySelectorAll(".carousel-item, .carousel-card"));
2190
- if (items.length === 0) return;
2191
-
2192
- const prevBtn = carousel.querySelector(".carousel-prev");
2193
- const nextBtn = carousel.querySelector(".carousel-next");
2194
- let indicatorsContainer = carousel.querySelector(".carousel-indicators");
2195
- let currentSlideIndex = 0;
2196
-
2197
- if (indicatorsContainer && indicatorsContainer.children.length === 0) {
2198
- items.forEach((_, idx) => {
2199
- const dot = document.createElement("button");
2200
- dot.className = `carousel-dot w-2.5 h-2.5 rounded-full transition-all ${
2201
- idx === 0 ? "bg-sky-400 w-5" : "bg-slate-600"
2202
- }`;
2203
- dot.setAttribute("aria-label", `Go to slide ${idx + 1}`);
2204
- dot.addEventListener("click", (e) => {
2205
- e.preventDefault();
2206
- scrollToSlide(idx);
2207
- });
2208
- indicatorsContainer.appendChild(dot);
2209
- });
2210
- }
2211
-
2212
- function scrollToSlide(index) {
2213
- if (index < 0) index = 0;
2214
- if (index >= items.length) index = items.length - 1;
2215
- currentSlideIndex = index;
2216
- const targetItem = items[index];
2217
- if (targetItem) {
2218
- track.scrollTo({
2219
- left: targetItem.offsetLeft - track.offsetLeft,
2220
- behavior: "smooth",
2221
- });
2222
- updateIndicators(index);
2223
- }
2224
- }
2225
-
2226
- function updateIndicators(activeIndex) {
2227
- if (!indicatorsContainer) return;
2228
- const dots = Array.from(indicatorsContainer.children);
2229
- dots.forEach((dot, idx) => {
2230
- if (idx === activeIndex) {
2231
- dot.className = "carousel-dot w-5 h-2.5 rounded-full transition-all bg-sky-400";
2232
- } else {
2233
- dot.className = "carousel-dot w-2.5 h-2.5 rounded-full transition-all bg-slate-600";
2234
- }
2235
- });
2236
- }
2237
-
2238
- let scrollTimeout;
2239
- track.addEventListener("scroll", () => {
2240
- clearTimeout(scrollTimeout);
2241
- scrollTimeout = setTimeout(() => {
2242
- const trackLeft = track.scrollLeft;
2243
- let closestIndex = 0;
2244
- let minDistance = Infinity;
2245
- items.forEach((item, idx) => {
2246
- const distance = Math.abs(item.offsetLeft - track.offsetLeft - trackLeft);
2247
- if (distance < minDistance) {
2248
- minDistance = distance;
2249
- closestIndex = idx;
2250
- }
2251
- });
2252
- currentSlideIndex = closestIndex;
2253
- updateIndicators(closestIndex);
2254
- }, 40);
2255
- });
2256
-
2257
- if (prevBtn) {
2258
- prevBtn.addEventListener("click", (e) => {
2259
- e.preventDefault();
2260
- e.stopPropagation();
2261
- scrollToSlide(currentSlideIndex - 1);
2262
- });
2263
- }
2264
- if (nextBtn) {
2265
- nextBtn.addEventListener("click", (e) => {
2266
- e.preventDefault();
2267
- e.stopPropagation();
2268
- scrollToSlide(currentSlideIndex + 1);
2269
- });
2270
- }
2271
-
2272
- let startX = 0;
2273
- let isDragging = false;
2274
- track.addEventListener(
2275
- "touchstart",
2276
- (e) => {
2277
- startX = e.touches[0].clientX;
2278
- isDragging = true;
2279
- },
2280
- { passive: true }
2281
- );
2282
-
2283
- track.addEventListener("touchend", (e) => {
2284
- if (!isDragging) return;
2285
- isDragging = false;
2286
- const endX = e.changedTouches[0].clientX;
2287
- const diffX = startX - endX;
2288
- if (Math.abs(diffX) > 35) {
2289
- if (diffX > 0) {
2290
- scrollToSlide(currentSlideIndex + 1);
2291
- } else {
2292
- scrollToSlide(currentSlideIndex - 1);
2293
- }
2294
- }
2295
- });
2296
-
2297
- track.addEventListener("mousedown", (e) => {
2298
- startX = e.clientX;
2299
- isDragging = true;
2300
- track.style.cursor = "grabbing";
2301
- });
2302
-
2303
- track.addEventListener("mouseleave", () => {
2304
- isDragging = false;
2305
- track.style.cursor = "grab";
2306
- });
2307
-
2308
- track.addEventListener("mouseup", (e) => {
2309
- if (!isDragging) return;
2310
- isDragging = false;
2311
- track.style.cursor = "grab";
2312
- const endX = e.clientX;
2313
- const diffX = startX - endX;
2314
- if (Math.abs(diffX) > 35) {
2315
- if (diffX > 0) {
2316
- scrollToSlide(currentSlideIndex + 1);
2317
- } else {
2318
- scrollToSlide(currentSlideIndex - 1);
2319
- }
2320
- }
2321
- });
2322
-
2323
- const isAutoplay =
2324
- (opts && opts.autoplay) || carousel.getAttribute("data-autoplay") === "true";
2325
- const intervalTime = parseInt(
2326
- (opts && opts.interval) || carousel.getAttribute("data-interval") || 3500,
2327
- 10
2328
- );
2329
-
2330
- if (isAutoplay) {
2331
- let autoInterval = setInterval(() => {
2332
- const nextIdx = (currentSlideIndex + 1) % items.length;
2333
- scrollToSlide(nextIdx);
2334
- }, intervalTime);
2335
- carousel.addEventListener("mouseenter", () => clearInterval(autoInterval));
2336
- carousel.addEventListener("mouseleave", () => {
2337
- autoInterval = setInterval(() => {
2338
- const nextIdx = (currentSlideIndex + 1) % items.length;
2339
- scrollToSlide(nextIdx);
2340
- }, intervalTime);
2341
- });
2342
- }
2343
- }
2344
-
2345
- (function setupDeclarativeListeners() {
2346
- if (window.__BLUEBIRD_UI_BOUND__) return;
2347
- window.__BLUEBIRD_UI_BOUND__ = true;
2348
-
2349
- document.addEventListener("click", (e) => {
2350
- const tabTrigger = e.target.closest("[data-tab-target], .tab-trigger");
2351
- if (tabTrigger) {
2352
- const targetId =
2353
- tabTrigger.getAttribute("data-tab-target") ||
2354
- (tabTrigger.getAttribute("href") || "").replace("#", "");
2355
- if (targetId) {
2356
- e.preventDefault();
2357
- bluebird("tab", { id: targetId });
2358
- }
2359
- }
2360
-
2361
- const popoverTrigger = e.target.closest("[data-popover-target]");
2362
- if (popoverTrigger) {
2363
- const popoverId = popoverTrigger.getAttribute("data-popover-target");
2364
- bluebird("popover", { id: popoverId, action: "toggle" });
2365
- }
2366
- if (!e.target.closest(".popover") && !e.target.closest("[data-popover-target]")) {
2367
- document.querySelectorAll(".popover.open").forEach((p) => {
2368
- p.classList.remove("open");
2369
- p.classList.add("hidden");
2370
- });
2371
- }
2372
-
2373
- const mobileToggle = e.target.closest(".bluebird-drawer-toggle");
2374
- if (mobileToggle) {
2375
- e.preventDefault();
2376
- e.stopPropagation();
2377
- initMobileDrawer();
2378
- const drawer = document.querySelector(".bluebird-drawer");
2379
- const overlay = document.querySelector(".bluebird-drawer-overlay");
2380
- if (drawer && overlay) {
2381
- const isOpen = drawer.classList.contains("open");
2382
- if (isOpen) {
2383
- drawer.classList.remove("open", "translate-x-0");
2384
- drawer.classList.add("-translate-x-full");
2385
- overlay.classList.add("hidden");
2386
- overlay.classList.remove("open");
2387
- document.body.style.overflow = "";
2388
- } else {
2389
- drawer.classList.remove("-translate-x-full");
2390
- drawer.classList.add("open", "translate-x-0");
2391
- overlay.classList.remove("hidden");
2392
- overlay.classList.add("open");
2393
- document.body.style.overflow = "hidden";
2394
- }
2395
- }
2396
- return;
2397
- }
2398
-
2399
- if (e.target.closest(".bluebird-drawer-overlay")) {
2400
- const drawer = document.querySelector(".bluebird-drawer");
2401
- const overlay = document.querySelector(".bluebird-drawer-overlay");
2402
- if (drawer) {
2403
- drawer.classList.remove("open", "translate-x-0");
2404
- drawer.classList.add("-translate-x-full");
2405
- }
2406
- if (overlay) {
2407
- overlay.classList.add("hidden");
2408
- overlay.classList.remove("open");
2409
- }
2410
- document.body.style.overflow = "";
2411
- return;
2412
- }
2413
-
2414
- if (e.target.closest(".bluebird-drawer a")) {
2415
- const drawer = document.querySelector(".bluebird-drawer");
2416
- const overlay = document.querySelector(".bluebird-drawer-overlay");
2417
- if (drawer) {
2418
- drawer.classList.remove("open", "translate-x-0");
2419
- drawer.classList.add("-translate-x-full");
2420
- }
2421
- if (overlay) {
2422
- overlay.classList.add("hidden");
2423
- overlay.classList.remove("open");
2424
- }
2425
- document.body.style.overflow = "";
2426
- }
2427
-
2428
- const drawerTrigger = e.target.closest("[data-drawer-target]");
2429
- if (drawerTrigger) {
2430
- const id = drawerTrigger.getAttribute("data-drawer-target");
2431
- bluebird("drawer", { id, action: "toggle" });
2432
- }
2433
-
2434
- const drawerClose = e.target.closest("[data-drawer-close]");
2435
- if (drawerClose) {
2436
- const drawerEl = drawerClose.closest(".drawer");
2437
- if (drawerEl && drawerEl.id) {
2438
- bluebird("drawer", { id: drawerEl.id, action: "close" });
2439
- }
2440
- }
2441
-
2442
- const copyTrigger = e.target.closest("[data-copy]");
2443
- if (copyTrigger) {
2444
- e.preventDefault();
2445
- const targetAttr = copyTrigger.getAttribute("data-copy");
2446
- let textToCopy = targetAttr;
2447
- if (targetAttr && (targetAttr.startsWith("#") || targetAttr.startsWith("."))) {
2448
- const targetEl = document.querySelector(targetAttr);
2449
- if (targetEl) {
2450
- textToCopy =
2451
- targetEl.value !== undefined
2452
- ? targetEl.value
2453
- : targetEl.innerText || targetEl.textContent;
2454
- }
2455
- }
2456
- if (textToCopy) {
2457
- navigator.clipboard.writeText(textToCopy.trim()).then(() => {
2458
- copyTrigger.classList.add("copied");
2459
- if (typeof bluebird === "function") {
2460
- bluebird("toast", {
2461
- title: "Copied to clipboard",
2462
- description:
2463
- textToCopy.length > 50 ? textToCopy.substring(0, 50) + "..." : textToCopy,
2464
- type: "success",
2465
- duration: 2500,
2466
- });
2467
- }
2468
- setTimeout(() => copyTrigger.classList.remove("copied"), 2000);
2469
- });
2470
- }
2471
- return;
2472
- }
2473
-
2474
- const confirmTrigger = e.target.closest("[data-confirm]");
2475
- if (confirmTrigger) {
2476
- const msg = confirmTrigger.getAttribute("data-confirm") || "Are you sure?";
2477
- if (!window.confirm(msg)) {
2478
- e.preventDefault();
2479
- e.stopImmediatePropagation();
2480
- return;
2481
- }
2482
- }
2483
-
2484
- const scrollTrigger = e.target.closest("[data-scroll-to]");
2485
- if (scrollTrigger) {
2486
- e.preventDefault();
2487
- const targetId = scrollTrigger.getAttribute("data-scroll-to");
2488
- const targetEl = document.querySelector(targetId);
2489
- if (targetEl) {
2490
- targetEl.scrollIntoView({ behavior: "smooth", block: "start" });
2491
- }
2492
- return;
2493
- }
2494
-
2495
- const passToggle = e.target.closest("[data-password-toggle]");
2496
- if (passToggle) {
2497
- e.preventDefault();
2498
- const targetSelector = passToggle.getAttribute("data-password-toggle");
2499
- const input = targetSelector
2500
- ? document.querySelector(targetSelector)
2501
- : passToggle.closest(".input-group, .form-input-group, div")?.querySelector("input") ||
2502
- passToggle.previousElementSibling;
2503
- if (input && (input.type === "password" || input.type === "text")) {
2504
- const isPassword = input.type === "password";
2505
- input.type = isPassword ? "text" : "password";
2506
- passToggle.classList.toggle("showing", isPassword);
2507
- passToggle.setAttribute("aria-pressed", isPassword ? "true" : "false");
2508
- }
2509
- return;
2510
- }
2511
-
2512
- const stepUp = e.target.closest("[data-step-up]");
2513
- if (stepUp) {
2514
- e.preventDefault();
2515
- const targetInput =
2516
- document.querySelector(stepUp.getAttribute("data-step-up")) ||
2517
- stepUp.closest(".stepper")?.querySelector('input[type="number"]');
2518
- if (targetInput && typeof targetInput.stepUp === "function") {
2519
- targetInput.stepUp();
2520
- targetInput.dispatchEvent(new Event("input", { bubbles: true }));
2521
- targetInput.dispatchEvent(new Event("change", { bubbles: true }));
2522
- }
2523
- return;
2524
- }
2525
-
2526
- const stepDown = e.target.closest("[data-step-down]");
2527
- if (stepDown) {
2528
- e.preventDefault();
2529
- const targetInput =
2530
- document.querySelector(stepDown.getAttribute("data-step-down")) ||
2531
- stepDown.closest(".stepper")?.querySelector('input[type="number"]');
2532
- if (targetInput && typeof targetInput.stepDown === "function") {
2533
- targetInput.stepDown();
2534
- targetInput.dispatchEvent(new Event("input", { bubbles: true }));
2535
- targetInput.dispatchEvent(new Event("change", { bubbles: true }));
2536
- }
2537
- return;
2538
- }
2539
-
2540
- const selectItem = e.target.closest("[data-select-value]");
2541
- if (selectItem) {
2542
- const val = selectItem.getAttribute("data-select-value");
2543
- const targetSelector =
2544
- selectItem.getAttribute("data-select-target") ||
2545
- selectItem.closest("[data-select-container]")?.getAttribute("data-select-target");
2546
- if (targetSelector) {
2547
- const targetEl = document.querySelector(targetSelector);
2548
- if (targetEl) {
2549
- if (targetEl.tagName === "INPUT" || targetEl.tagName === "SELECT") {
2550
- targetEl.value = val;
2551
- targetEl.dispatchEvent(new Event("input", { bubbles: true }));
2552
- targetEl.dispatchEvent(new Event("change", { bubbles: true }));
2553
- } else {
2554
- targetEl.textContent = selectItem.textContent.trim();
2555
- }
2556
- }
2557
- }
2558
- const parentDropdown = selectItem.closest(".dropdown-content, .popover-content");
2559
- if (parentDropdown) {
2560
- parentDropdown.classList.remove("open");
2561
- }
2562
- }
2563
-
2564
- const modalTrigger = e.target.closest("[data-toggle='modal'], [data-modal-target], [data-dialog-target]");
2565
- if (modalTrigger) {
2566
- e.preventDefault();
2567
- const targetSelector =
2568
- modalTrigger.getAttribute("data-modal-target") ||
2569
- modalTrigger.getAttribute("data-dialog-target") ||
2570
- modalTrigger.getAttribute("data-target") ||
2571
- modalTrigger.getAttribute("href");
2572
- if (targetSelector) {
2573
- const dialog = document.querySelector(targetSelector);
2574
- if (dialog && typeof dialog.showModal === "function") {
2575
- dialog.showModal();
2576
- }
2577
- }
2578
- return;
2579
- }
2580
-
2581
- const dismissTrigger = e.target.closest("[data-dismiss='modal'], [data-close-dialog], [data-close-modal]");
2582
- if (dismissTrigger) {
2583
- e.preventDefault();
2584
- const dialog =
2585
- dismissTrigger.closest("dialog") ||
2586
- document.querySelector(dismissTrigger.getAttribute("data-target") || "");
2587
- if (dialog && typeof dialog.close === "function") {
2588
- dialog.close();
2589
- }
2590
- return;
2591
- }
2592
-
2593
- const themeTrigger = e.target.closest('[data-toggle="theme"]');
2594
- if (themeTrigger) {
2595
- e.preventDefault();
2596
- const html = document.documentElement;
2597
- const current = html.getAttribute("data-theme") || (html.classList.contains("dark") ? "dark" : "light");
2598
- const next = current === "dark" ? "light" : "dark";
2599
- html.setAttribute("data-theme", next);
2600
- html.classList.toggle("dark", next === "dark");
2601
- try {
2602
- localStorage.setItem("bluebird-theme", next);
2603
- } catch (err) {}
2604
- return;
2605
- }
2606
-
2607
- const toastTrigger = e.target.closest("[data-toast]");
2608
- if (toastTrigger) {
2609
- e.preventDefault();
2610
- const desc = toastTrigger.getAttribute("data-toast") || "";
2611
- const title = toastTrigger.getAttribute("data-toast-title") || "";
2612
- const type = toastTrigger.getAttribute("data-toast-type") || "info";
2613
- if (typeof bluebird === "function") {
2614
- bluebird("toast", { title, description: desc, type });
2615
- }
2616
- return;
2617
- }
2618
-
2619
- const snackbarTrigger = e.target.closest("[data-snackbar]");
2620
- if (snackbarTrigger) {
2621
- e.preventDefault();
2622
- const message = snackbarTrigger.getAttribute("data-snackbar") || "";
2623
- const type = snackbarTrigger.getAttribute("data-snackbar-type") || "info";
2624
- if (typeof bluebird === "function") {
2625
- bluebird("snackbar", { message, type });
2626
- }
2627
- return;
2628
- }
2629
-
2630
- const actionBtn = e.target.closest("button[data-action], a[data-action]");
2631
- if (actionBtn) {
2632
- e.preventDefault();
2633
- const actionName = actionBtn.getAttribute("data-action");
2634
- if (actionName && window.Bluebird && typeof window.Bluebird.action === "function") {
2635
- let payload = {};
2636
- const rawArgs = actionBtn.getAttribute("data-args") || actionBtn.getAttribute("data-payload");
2637
- if (rawArgs) {
2638
- try {
2639
- payload = JSON.parse(rawArgs);
2640
- } catch {}
2641
- }
2642
- const partialTarget = actionBtn.getAttribute("data-partial");
2643
- actionBtn.disabled = true;
2644
- actionBtn.setAttribute("aria-busy", "true");
2645
- actionBtn.classList.add("is-pending");
2646
- window.Bluebird.action(actionName, payload, {
2647
- url: actionBtn.getAttribute("data-url") || undefined,
2648
- partial: partialTarget === "true" ? true : partialTarget || false,
2649
- }).finally(() => {
2650
- actionBtn.disabled = false;
2651
- actionBtn.removeAttribute("aria-busy");
2652
- actionBtn.classList.remove("is-pending");
2653
- });
2654
- }
2655
- return;
2656
- }
2657
-
2658
- if (!e.target.closest(".dropdown") && !e.target.closest(".popover")) {
2659
- document.querySelectorAll(".dropdown-content.open, .popover-content.open").forEach((el) => {
2660
- el.classList.remove("open");
2661
- });
2662
- }
2663
- });
2664
-
2665
- document.addEventListener("input", (e) => {
2666
- const filterInput = e.target.closest("[data-filter-target]");
2667
- if (filterInput) {
2668
- const targetSelector = filterInput.getAttribute("data-filter-target");
2669
- const targetContainer = document.querySelector(targetSelector);
2670
- if (targetContainer) {
2671
- const query = filterInput.value.toLowerCase().trim();
2672
- const items = targetContainer.querySelectorAll("[data-filter-item], li, tr, .card, .dropdown-item, .item");
2673
- let visibleCount = 0;
2674
- items.forEach((item) => {
2675
- const text = item.textContent.toLowerCase();
2676
- const matches = text.includes(query);
2677
- item.style.display = matches ? "" : "none";
2678
- if (matches) visibleCount++;
2679
- });
2680
- const emptyMsg = targetContainer.querySelector(".no-filter-results");
2681
- if (emptyMsg) {
2682
- emptyMsg.style.display = visibleCount === 0 ? "block" : "none";
2683
- }
2684
- }
2685
- }
2686
-
2687
- if (e.target.matches("textarea[data-auto-resize]")) {
2688
- const textarea = e.target;
2689
- textarea.style.height = "auto";
2690
- textarea.style.height = textarea.scrollHeight + 2 + "px";
2691
- }
2692
- });
2693
-
2694
- document.addEventListener("submit", async (e) => {
2695
- const actionForm = e.target.closest("form[data-action]");
2696
- if (actionForm && window.Bluebird && typeof window.Bluebird.action === "function") {
2697
- e.preventDefault();
2698
- const actionName = actionForm.getAttribute("data-action");
2699
- const submitButtons = actionForm.querySelectorAll('button[type="submit"], input[type="submit"]');
2700
- submitButtons.forEach((btn) => {
2701
- btn.disabled = true;
2702
- btn.setAttribute("aria-busy", "true");
2703
- });
2704
- actionForm.classList.add("is-pending");
2705
- const formData = new FormData(actionForm);
2706
- const payload = {};
2707
- formData.forEach((val, key) => {
2708
- payload[key] = val;
2709
- });
2710
- const partialAttr = actionForm.getAttribute("data-partial");
2711
- try {
2712
- const res = await window.Bluebird.action(actionName, payload, {
2713
- url: actionForm.getAttribute("action") || window.location.pathname,
2714
- partial: partialAttr === "true" ? true : partialAttr || false,
2715
- });
2716
- if (res && (res.message || res.data?.message) && typeof bluebird === "function") {
2717
- bluebird("toast", {
2718
- title: res.status === "error" ? "Error" : "Success",
2719
- description: res.message || res.data?.message,
2720
- type: res.status === "error" ? "error" : "success",
2721
- });
2722
- }
2723
- } finally {
2724
- submitButtons.forEach((btn) => {
2725
- btn.disabled = false;
2726
- btn.removeAttribute("aria-busy");
2727
- });
2728
- actionForm.classList.remove("is-pending");
2729
- }
2730
- return;
2731
- }
2732
-
2733
- const form = e.target.closest("form[data-bb-form]");
2734
- if (!form) return;
2735
- e.preventDefault();
2736
- const action = form.getAttribute("action") || window.location.pathname;
2737
- const method = (form.getAttribute("method") || "POST").toUpperCase();
2738
- const formData = new FormData(form);
2739
-
2740
- const csrfEl =
2741
- document.getElementById("csrf") ||
2742
- document.querySelector('input[name="_csrf"]') ||
2743
- document.querySelector('meta[name="csrf-token"]');
2744
- const csrfToken = csrfEl ? csrfEl.value || csrfEl.getAttribute("content") : null;
2745
- if (csrfToken && !formData.has("_csrf")) {
2746
- formData.append("_csrf", csrfToken);
2747
- }
2748
-
2749
- try {
2750
- const headers = { "X-Requested-With": "XMLHttpRequest" };
2751
- if (csrfToken) headers["X-CSRF-Token"] = csrfToken;
2752
-
2753
- const res = await fetch(action, {
2754
- method,
2755
- body: formData,
2756
- headers,
2757
- credentials: "include",
2758
- });
2759
-
2760
- const redirectHeader = res.headers.get("X-Bluebird-Redirect");
2761
- if (redirectHeader) {
2762
- if (window.Bluebird && typeof window.Bluebird.navigate === "function") {
2763
- window.Bluebird.navigate(redirectHeader);
2764
- } else {
2765
- window.location.href = redirectHeader;
2766
- }
2767
- return;
2768
- }
2769
-
2770
- if (res.redirected) {
2771
- if (window.Bluebird && typeof window.Bluebird.navigate === "function") {
2772
- window.Bluebird.navigate(res.url);
2773
- } else {
2774
- window.location.href = res.url;
2775
- }
2776
- return;
2777
- }
2778
-
2779
- const contentType = res.headers.get("content-type") || "";
2780
- if (contentType.includes("application/json")) {
2781
- const json = await res.json();
2782
- if (json.message || json.msg || json.error) {
2783
- const type = res.ok ? "success" : "error";
2784
- if (typeof bluebird === "function") {
2785
- bluebird("toast", {
2786
- title: res.ok ? "Success" : "Error",
2787
- description: json.message || json.msg || json.error,
2788
- type,
2789
- });
2790
- }
2791
- }
2792
- }
2793
- } catch (err) {
2794
- if (typeof bluebird === "function") {
2795
- bluebird("toast", {
2796
- title: "Request Failed",
2797
- description: err.message,
2798
- type: "error",
2799
- });
2800
- }
2801
- }
2802
- });
2803
-
2804
- document.addEventListener("keydown", (e) => {
2805
- if ((e.ctrlKey || e.metaKey) && e.key === "k") {
2806
- e.preventDefault();
2807
- if (typeof bluebird === "function") {
2808
- bluebird("command", { action: "toggle" });
2809
- }
2810
- } else if (e.key === "Escape") {
2811
- const openCommand = document.querySelector(".command-backdrop.open");
2812
- if (openCommand && typeof bluebird === "function") {
2813
- bluebird("command", { action: "close" });
2814
- }
2815
- }
2816
- });
2817
- })();
2818
-
2819
- (function () {
2820
- function init() {
2821
- cleanupOrphanedBackdrops();
2822
- initMobileDrawer();
2823
- document.querySelectorAll(".carousel").forEach((c) => initSingleCarousel(c));
2824
- document.querySelectorAll("textarea[data-auto-resize]").forEach((t) => {
2825
- t.style.height = "auto";
2826
- t.style.height = t.scrollHeight + 2 + "px";
2827
- });
2828
- try {
2829
- const savedTheme = localStorage.getItem("bluebird-theme");
2830
- if (savedTheme) {
2831
- document.documentElement.setAttribute("data-theme", savedTheme);
2832
- document.documentElement.classList.toggle("dark", savedTheme === "dark");
2833
- }
2834
- } catch (e) {}
2835
- }
2836
-
2837
- if (document.readyState === "loading") {
2838
- document.addEventListener("DOMContentLoaded", () => setTimeout(init, 50));
2839
- } else {
2840
- setTimeout(init, 50);
2841
- }
2842
-
2843
- if (!window.__BLUEBIRD_INIT_BOUND__) {
2844
- window.__BLUEBIRD_INIT_BOUND__ = true;
2845
- window.addEventListener("bluebird:page-load", () => setTimeout(init, 20));
2846
- window.addEventListener("bluebird:partial-load", () => setTimeout(init, 20));
2847
- }
2848
- })();
2849
-
2850
- /**
2851
- * Standard fetch wrapper supporting automatic CSRF injection and JSON parsing.
2852
- * @param {string} url
2853
- * @param {string} method
2854
- * @param {Object|boolean} body
2855
- * @param {FormData|boolean} bodyForm
2856
- * @param {Object} headers
2857
- * @returns {Promise<any>}
2858
- */
2859
- async function Http(
2860
- url = "/",
2861
- method = "GET",
2862
- body = false,
2863
- bodyForm = false,
2864
- headers = {}
2865
- ) {
2866
- const csrfEl =
2867
- document.getElementById("csrf") ||
2868
- document.querySelector('input[name="_csrf"]') ||
2869
- document.querySelector('meta[name="csrf-token"]');
2870
- const csrfToken = csrfEl ? csrfEl.value || csrfEl.getAttribute("content") : null;
2871
- const mergedHeaders = { ...headers };
2872
- if (csrfToken) {
2873
- mergedHeaders["X-CSRF-Token"] = csrfToken;
2874
- }
2875
- const upperMethod = String(method || "GET").toUpperCase();
2876
- const options = { method: upperMethod, headers: mergedHeaders, credentials: "include" };
2877
- if (body) {
2878
- const payload = csrfToken ? { ...body, _csrf: csrfToken, csrf: csrfToken } : body;
2879
- options["body"] = JSON.stringify(payload);
2880
- if (!mergedHeaders["Content-Type"]) {
2881
- mergedHeaders["Content-Type"] = "application/json";
2882
- }
2883
- }
2884
- if (bodyForm) {
2885
- if (csrfToken && bodyForm instanceof FormData) {
2886
- if (!bodyForm.has("_csrf")) bodyForm.append("_csrf", csrfToken);
2887
- }
2888
- options["body"] = bodyForm;
2889
- }
2890
- if (upperMethod !== "GET" && window.Bluebird && typeof window.Bluebird.clearPrefetch === "function") {
2891
- window.Bluebird.clearPrefetch();
2892
- }
2893
- const response = await fetch(url, options);
2894
- if (!response.ok) {
2895
- let errorData;
2896
- try {
2897
- errorData = await response.json();
2898
- } catch {
2899
- errorData = { message: `HTTP Error ${response.status}: ${response.statusText}` };
2900
- }
2901
- throw new Error(errorData.message || errorData.msg || errorData.mensaje || "Fetch request failed");
2902
- }
2903
- return await response.json();
2904
- }
2905
-
2906
- /**
2907
- * Retrieves a query parameter from window.location.search.
2908
- * @param {string} name
2909
- * @returns {string|null}
2910
- */
2911
- function getUrlParameter(name) {
2912
- return new URLSearchParams(window.location.search).get(name);
2913
- }
2914
-
2915
- /**
2916
- * Checks whether the document matches the specified language.
2917
- * @param {string} l
2918
- * @returns {boolean}
2919
- */
2920
- function lang(l = "es") {
2921
- const docLang = document.documentElement.lang || "es";
2922
- return docLang === l || docLang.startsWith(l);
2923
- }
2924
-
2925
- /**
2926
- * High-performance responsive data table with search, pagination, and mobile card view.
2927
- */
2928
- class ResponsiveDataTable {
2929
- constructor(containerId, options = {}) {
2930
- this.container =
2931
- typeof containerId === "string" ? document.getElementById(containerId) : containerId;
2932
- if (!this.container) return;
2933
- this.defaults = {
2934
- data: [],
2935
- columns: [],
2936
- rowsPerPage: 10,
2937
- search: true,
2938
- pagination: true,
2939
- headerTitles: {},
2940
- summaryFields: ["id"],
2941
- edit: false,
2942
- delete: false,
2943
- breakpoint: 768,
2944
- };
2945
- this.options = { ...this.defaults, ...options };
2946
- if (options.pageSize !== undefined) this.options.rowsPerPage = options.pageSize;
2947
- if (options.searchable !== undefined) this.options.search = options.searchable;
2948
- if (options.onEdit !== undefined) this.options.edit = options.onEdit;
2949
- if (options.onDelete !== undefined) this.options.delete = options.onDelete;
2950
- this.currentPage = 1;
2951
- this.filteredData = [...this.options.data];
2952
- this.isMobile = window.innerWidth < this.options.breakpoint;
2953
- this.init();
2954
- if (this.container._bb_resize_handler) {
2955
- window.removeEventListener("resize", this.container._bb_resize_handler);
2956
- }
2957
- this._onResize = () => this.handleResize();
2958
- this.container._bb_resize_handler = this._onResize;
2959
- window.addEventListener("resize", this._onResize);
2960
- }
2961
-
2962
- init() {
2963
- this.renderContainer();
2964
- this.updateTable();
2965
- if (this.options.search) this.setupSearch();
2966
- }
2967
-
2968
- handleResize() {
2969
- const wasMobile = this.isMobile;
2970
- this.isMobile = window.innerWidth < this.options.breakpoint;
2971
- if (wasMobile !== this.isMobile) this.updateTable();
2972
- }
2973
-
2974
- renderContainer() {
2975
- this.container.innerHTML = `
2976
- <section class="w-full">
2977
- ${
2978
- this.options.search
2979
- ? `<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>`
2980
- : ""
2981
- }
2982
- <div class="overflow-x-auto rounded-xl border border-slate-800">
2983
- <table class="datatable-table w-full text-sm text-left border-collapse hidden"></table>
2984
- <div class="datatable-mobile p-3 space-y-3"></div>
2985
- </div>
2986
- ${this.options.pagination ? `<nav class="datatable-pagination mt-4 flex items-center justify-center gap-1.5" aria-label="Pagination"></nav>` : ""}
2987
- </section>`;
2988
- }
2989
-
2990
- renderTable() {
2991
- const table = this.container.querySelector(".datatable-table");
2992
- const mobileView = this.container.querySelector(".datatable-mobile");
2993
- if (!table || !mobileView) return;
2994
- if (this.isMobile) {
2995
- table.classList.add("hidden");
2996
- mobileView.classList.remove("hidden");
2997
- this.renderMobileView();
2998
- } else {
2999
- table.classList.remove("hidden");
3000
- mobileView.classList.add("hidden");
3001
- this.renderDesktopTable();
3002
- }
3003
- }
3004
-
3005
- renderDesktopTable() {
3006
- const table = this.container.querySelector(".datatable-table");
3007
- table.innerHTML = `
3008
- <thead>
3009
- <tr class="datatable-header border-b border-slate-800 bg-slate-900/70 text-xs font-semibold uppercase tracking-wider text-slate-400"></tr>
3010
- </thead>
3011
- <tbody class="datatable-body divide-y divide-slate-800/70"></tbody>`;
3012
- const headerRow = table.querySelector("thead tr");
3013
- this.options.columns.forEach((column) => {
3014
- const th = document.createElement("th");
3015
- th.scope = "col";
3016
- th.className = "px-4 py-3";
3017
- th.textContent =
3018
- this.options.headerTitles[column.key] || column.title || column.label || column.key;
3019
- headerRow.appendChild(th);
3020
- });
3021
- if (this.options.edit || this.options.delete) {
3022
- const th = document.createElement("th");
3023
- th.scope = "col";
3024
- th.className = "px-4 py-3";
3025
- th.textContent = lang() ? "Acciones" : "Actions";
3026
- headerRow.appendChild(th);
3027
- }
3028
- const startIndex = (this.currentPage - 1) * this.options.rowsPerPage;
3029
- const endIndex = startIndex + this.options.rowsPerPage;
3030
- const paginatedData = this.filteredData.slice(startIndex, endIndex);
3031
- const tbody = table.querySelector("tbody");
3032
- paginatedData.forEach((item) => {
3033
- const row = document.createElement("tr");
3034
- row.className = "hover:bg-slate-800/40 transition-colors";
3035
- this.options.columns.forEach((column) => {
3036
- const td = document.createElement("td");
3037
- td.className = "px-4 py-3 text-slate-200";
3038
- const value = item[column.key];
3039
- if (
3040
- value &&
3041
- typeof value === "string" &&
3042
- /<[a-z][\s\S]*>/i.test(value)
3043
- ) {
3044
- td.innerHTML = value;
3045
- } else {
3046
- td.textContent = value !== undefined && value !== null ? value : "-";
3047
- }
3048
- row.appendChild(td);
3049
- });
3050
- if (this.options.edit || this.options.delete) {
3051
- const td = document.createElement("td");
3052
- td.className = "px-4 py-3 text-slate-200";
3053
- const actionsDiv = document.createElement("div");
3054
- actionsDiv.className = "flex items-center gap-2";
3055
- if (this.options.edit) {
3056
- const btn = document.createElement("button");
3057
- btn.className =
3058
- "px-2.5 py-1 text-xs font-medium rounded-md border border-slate-700 text-slate-200 hover:bg-slate-800 transition-colors";
3059
- btn.textContent = lang() ? "Editar" : "Edit";
3060
- btn.onclick = (e) => this.handleAction("edit", e, item);
3061
- actionsDiv.appendChild(btn);
3062
- }
3063
- if (this.options.delete) {
3064
- const btn = document.createElement("button");
3065
- btn.className =
3066
- "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";
3067
- btn.textContent = lang() ? "Eliminar" : "Delete";
3068
- btn.onclick = (e) => this.handleAction("delete", e, item);
3069
- actionsDiv.appendChild(btn);
3070
- }
3071
- td.appendChild(actionsDiv);
3072
- row.appendChild(td);
3073
- }
3074
- tbody.appendChild(row);
3075
- });
3076
- }
3077
-
3078
- renderMobileView() {
3079
- const mobileView = this.container.querySelector(".datatable-mobile");
3080
- mobileView.innerHTML = "";
3081
- const startIndex = (this.currentPage - 1) * this.options.rowsPerPage;
3082
- const endIndex = startIndex + this.options.rowsPerPage;
3083
- const paginatedData = this.filteredData.slice(startIndex, endIndex);
3084
- paginatedData.forEach((item) => {
3085
- const card = document.createElement("article");
3086
- card.className = "rounded-xl border border-slate-800 bg-slate-900/60 p-4 mb-3 shadow-xs";
3087
- const summary = document.createElement("h3");
3088
- summary.className =
3089
- "flex items-center justify-between font-semibold text-slate-100 mb-3 pb-2 border-b border-slate-800";
3090
- this.options.summaryFields.forEach((fieldKey) => {
3091
- const value = item[fieldKey];
3092
- summary.innerHTML += `<span>${escapeClientHtml(value !== undefined && value !== null ? value : "-")}</span>`;
3093
- });
3094
- card.appendChild(summary);
3095
- const details = document.createElement("dl");
3096
- details.className = "grid grid-cols-1 gap-2 mb-3 text-sm";
3097
- this.options.columns.forEach((column) => {
3098
- if (this.options.summaryFields.includes(column.key)) return;
3099
- const dt = document.createElement("dt");
3100
- dt.className = "text-xs font-semibold uppercase tracking-wider text-slate-400";
3101
- dt.textContent =
3102
- this.options.headerTitles[column.key] || column.title || column.label || column.key;
3103
- const dd = document.createElement("dd");
3104
- dd.className = "text-slate-200 mb-1";
3105
- const cellValue = item[column.key];
3106
- if (
3107
- cellValue &&
3108
- typeof cellValue === "string" &&
3109
- /<[a-z][\s\S]*>/i.test(cellValue)
3110
- ) {
3111
- dd.innerHTML = cellValue;
3112
- } else {
3113
- dd.textContent = cellValue !== undefined && cellValue !== null ? cellValue : "-";
3114
- }
3115
- details.appendChild(dt);
3116
- details.appendChild(dd);
3117
- });
3118
- card.appendChild(details);
3119
- if (this.options.edit || this.options.delete) {
3120
- const actions = document.createElement("div");
3121
- actions.className = "flex items-center gap-2 justify-end pt-2 border-t border-slate-800/60";
3122
- if (this.options.edit) {
3123
- const btn = document.createElement("button");
3124
- btn.className =
3125
- "px-2.5 py-1 text-xs font-medium rounded-md border border-slate-700 text-slate-200 hover:bg-slate-800 transition-colors";
3126
- btn.textContent = lang() ? "Editar" : "Edit";
3127
- btn.onclick = (e) => this.handleAction("edit", e, item);
3128
- actions.appendChild(btn);
3129
- }
3130
- if (this.options.delete) {
3131
- const btn = document.createElement("button");
3132
- btn.className =
3133
- "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";
3134
- btn.textContent = lang() ? "Eliminar" : "Delete";
3135
- btn.onclick = (e) => this.handleAction("delete", e, item);
3136
- actions.appendChild(btn);
3137
- }
3138
- card.appendChild(actions);
3139
- }
3140
- mobileView.appendChild(card);
3141
- });
3142
- }
3143
-
3144
- renderPagination() {
3145
- const pagination = this.container.querySelector(".datatable-pagination");
3146
- if (!pagination || !this.options.pagination) return;
3147
- pagination.innerHTML = "";
3148
- const pageCount = Math.ceil(this.filteredData.length / this.options.rowsPerPage);
3149
- if (pageCount <= 1) return;
3150
- const baseClass =
3151
- "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";
3152
- const activeClass =
3153
- "px-3 py-1.5 text-xs font-semibold rounded-lg bg-sky-500 text-slate-950 border border-sky-400";
3154
- const prevButton = document.createElement("button");
3155
- prevButton.textContent = "«";
3156
- prevButton.className = baseClass;
3157
- prevButton.disabled = this.currentPage === 1;
3158
- prevButton.onclick = () => this.changePage(this.currentPage - 1);
3159
- pagination.appendChild(prevButton);
3160
- const maxVisible = 5;
3161
- let start = Math.max(1, this.currentPage - Math.floor(maxVisible / 2));
3162
- let end = start + maxVisible - 1;
3163
- if (end > pageCount) {
3164
- end = pageCount;
3165
- start = Math.max(1, end - maxVisible + 1);
3166
- }
3167
- if (start > 1) {
3168
- const firstButton = document.createElement("button");
3169
- firstButton.className = baseClass;
3170
- firstButton.textContent = "1";
3171
- firstButton.onclick = () => this.changePage(1);
3172
- pagination.appendChild(firstButton);
3173
- if (start > 2) pagination.appendChild(this.createEllipsis());
3174
- }
3175
- for (let i = start; i <= end; i++) {
3176
- const button = document.createElement("button");
3177
- button.className = i === this.currentPage ? activeClass : baseClass;
3178
- button.textContent = i;
3179
- button.onclick = () => this.changePage(i);
3180
- pagination.appendChild(button);
3181
- }
3182
- if (end < pageCount) {
3183
- if (end < pageCount - 1) pagination.appendChild(this.createEllipsis());
3184
- const lastButton = document.createElement("button");
3185
- lastButton.className = baseClass;
3186
- lastButton.textContent = pageCount;
3187
- lastButton.onclick = () => this.changePage(pageCount);
3188
- pagination.appendChild(lastButton);
3189
- }
3190
- const nextButton = document.createElement("button");
3191
- nextButton.className = baseClass;
3192
- nextButton.textContent = "»";
3193
- nextButton.disabled = this.currentPage === pageCount;
3194
- nextButton.onclick = () => this.changePage(this.currentPage + 1);
3195
- pagination.appendChild(nextButton);
3196
- }
3197
-
3198
- createEllipsis() {
3199
- const span = document.createElement("span");
3200
- span.className = "px-2 text-xs text-slate-500";
3201
- span.textContent = "...";
3202
- return span;
3203
- }
3204
-
3205
- changePage(page) {
3206
- this.currentPage = page;
3207
- this.updateTable();
3208
- }
3209
-
3210
- handleAction(type, event, item) {
3211
- if (!this.options[type]) return;
3212
- const callback =
3213
- typeof this.options[type] === "function"
3214
- ? this.options[type]
3215
- : window[this.options[type]];
3216
- if (typeof callback === "function") callback(event, item.id || item);
3217
- }
3218
-
3219
- setupSearch() {
3220
- const searchInput = this.container.querySelector(".datatable-search-input");
3221
- if (!searchInput) return;
3222
- searchInput.addEventListener("input", (e) => {
3223
- const term = e.target.value.toLowerCase().trim();
3224
- this.filteredData = this.options.data.filter((item) =>
3225
- this.options.columns.some((column) =>
3226
- String(item[column.key] || "")
3227
- .toLowerCase()
3228
- .includes(term)
3229
- )
3230
- );
3231
- this.currentPage = 1;
3232
- this.updateTable();
3233
- });
3234
- }
3235
-
3236
- updateTable() {
3237
- this.renderTable();
3238
- if (this.options.pagination) this.renderPagination();
3239
- }
3240
-
3241
- updateData(newData) {
3242
- this.options.data = newData;
3243
- this.filteredData = [...newData];
3244
- this.currentPage = 1;
3245
- this.updateTable();
3246
- }
3247
-
3248
- updateColumns(newColumns) {
3249
- this.options.columns = newColumns;
3250
- this.updateTable();
3251
- }
3252
- }
3253
-
3254
- if (typeof window !== "undefined") {
3255
- window.ResponsiveDataTable = ResponsiveDataTable;
3256
- window.Http = Http;
3257
- window.getUrlParameter = getUrlParameter;
3258
- window.snackbar = snackbar;
3259
- window.toast = toast;
3260
- window.bluebird = bluebird;
3261
- window.dismissToast = dismissToast;
3262
- window.initMobileDrawer = initMobileDrawer;
3263
- window.initSingleCarousel = initSingleCarousel;
3264
- window.lang = lang;
3265
- }