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