@seip/bluebird-js 0.1.1 → 0.1.4

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 (49) hide show
  1. package/.vscode/extensions.json +7 -0
  2. package/.vscode/settings.json +10 -0
  3. package/AGENTS.md +124 -64
  4. package/README.md +236 -103
  5. package/app/routes/web.js +47 -55
  6. package/app/views/about.jsx +98 -0
  7. package/app/views/components/Header.jsx +42 -0
  8. package/app/views/components/LiveCounter.jsx +67 -0
  9. package/app/views/dashboard.jsx +300 -0
  10. package/app/views/index.jsx +123 -0
  11. package/app/views/layouts/main/view.jsx +201 -0
  12. package/app/views/legal/terms.html +29 -19
  13. package/app/views/login.jsx +141 -0
  14. package/core/actions.d.ts +4 -0
  15. package/core/actions.js +329 -0
  16. package/core/app.js +129 -22
  17. package/core/auth.js +1 -1
  18. package/core/cli/doctor.js +3 -4
  19. package/core/cli/init.js +153 -6
  20. package/core/cli/migrate.js +418 -145
  21. package/core/cli/view.js +76 -11
  22. package/core/config.js +35 -5
  23. package/core/csrf.js +1 -1
  24. package/core/database.js +52 -17
  25. package/core/debug.js +1 -1
  26. package/core/html.d.ts +54 -42
  27. package/core/html.js +473 -217
  28. package/core/index.d.ts +187 -85
  29. package/core/jsx.d.ts +38 -0
  30. package/core/jsx.js +1180 -0
  31. package/core/model.js +282 -61
  32. package/core/queue.js +7 -4
  33. package/core/render-cache.js +212 -212
  34. package/core/render.d.ts +20 -2
  35. package/core/render.js +320 -43
  36. package/core/upload.js +7 -1
  37. package/core/validate.js +1 -1
  38. package/core/view-loader.js +341 -19
  39. package/core/vite.js +1 -1
  40. package/package.json +9 -3
  41. package/public/js/bluebird-client.js +2313 -1049
  42. package/public/js/tailwind.js +8 -0
  43. package/app/views/about.js +0 -63
  44. package/app/views/dashboard.js +0 -147
  45. package/app/views/index.js +0 -80
  46. package/app/views/layouts/main/view.js +0 -81
  47. package/app/views/login.js +0 -80
  48. package/public/css/bluebird.min.css +0 -2
  49. package/public/js/bluebird.min.js +0 -1073
@@ -213,7 +213,8 @@
213
213
  const component = window.__BLUEBIRD_ISLANDS__[name];
214
214
  if (component && typeof window.__BLUEBIRD_MOUNT__ === "function") {
215
215
  try {
216
- const unmountFn = window.__BLUEBIRD_MOUNT__(el, component, props);
216
+ const isHydrateMode = el.getAttribute("data-hydrate") === "true";
217
+ const unmountFn = window.__BLUEBIRD_MOUNT__(el, component, props, isHydrateMode);
217
218
  el.__bluebird_mounted__ = true;
218
219
  mountedRoots.set(el, {
219
220
  unmount: unmountFn,
@@ -345,6 +346,101 @@
345
346
  window.location.href = url;
346
347
  }
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
+ },
348
444
  };
349
445
 
350
446
  /**
@@ -408,9 +504,12 @@
408
504
  }
409
505
 
410
506
  executeScripts(document.body);
411
- Bluebird.hydrate();
507
+ Bluebird.hydrate();
508
+ drainMountQueue();
412
509
  }
413
510
 
511
+ syncActiveNavLinks(url);
512
+
414
513
  if (options.replace) {
415
514
  window.history.replaceState({}, "", url);
416
515
  } else {
@@ -421,16 +520,43 @@
421
520
  window.scrollTo(0, 0);
422
521
  }
423
522
 
424
- Bluebird.hydrate();
425
-
426
523
  const pageLoadDetail = { url, initial: false };
427
524
  window.dispatchEvent(new CustomEvent("bluebird:navigate", { detail: { url } }));
428
525
  window.dispatchEvent(new CustomEvent("bluebird:page-load", { detail: pageLoadDetail }));
429
526
  document.dispatchEvent(new CustomEvent("bluebird:page-load", { detail: pageLoadDetail }));
430
527
  }
431
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
+
432
556
  /**
433
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.
434
560
  * Skips persistent scripts and the Bluebird client runtime itself.
435
561
  * @param {HTMLElement} container
436
562
  */
@@ -445,7 +571,18 @@
445
571
  for (const attr of Array.from(oldScript.attributes)) {
446
572
  newScript.setAttribute(attr.name, attr.value);
447
573
  }
448
- newScript.textContent = oldScript.textContent;
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
+
449
586
  if (oldScript.parentNode) {
450
587
  oldScript.parentNode.replaceChild(newScript, oldScript);
451
588
  }
@@ -633,7 +770,715 @@
633
770
  window.$$ = window.$$ || $$;
634
771
  window.on = window.on || delegate;
635
772
 
636
- window.Bluebird = Bluebird;
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
+ const activeComponentInstances = new Map();
1330
+
1331
+ /**
1332
+ * Schedules microtask reconciliation for a dirty component instance.
1333
+ * @param {Object} inst
1334
+ */
1335
+ function scheduleComponentUpdate(inst) {
1336
+ if (inst.scheduled) return;
1337
+ inst.scheduled = true;
1338
+ queueMicrotask(() => {
1339
+ if (!inst.mounted) return;
1340
+ renderComponentInstance(inst);
1341
+ });
1342
+ }
1343
+
1344
+ /**
1345
+ * Invokes component render function, applies DOM patches, and runs queued effects.
1346
+ * @param {Object} inst
1347
+ */
1348
+ function renderComponentInstance(inst) {
1349
+ inst.scheduled = false;
1350
+ inst.hookIndex = 0;
1351
+ activeInstance = inst;
1352
+ let vnode;
1353
+ try {
1354
+ if (inst.fn.length >= 2) {
1355
+ vnode = inst.fn(inst.el, inst.props);
1356
+ } else {
1357
+ vnode = inst.fn(Object.assign({}, inst.props, { el: inst.el, root: inst.el, Bluebird }));
1358
+ }
1359
+ } catch (err) {
1360
+ console.error("[BLUEBIRD COMPONENT ERROR]:", err);
1361
+ return;
1362
+ } finally {
1363
+ activeInstance = null;
1364
+ }
1365
+
1366
+ if (vnode === undefined) {
1367
+ return;
1368
+ }
1369
+
1370
+ if (!inst.hasRenderedVNode) {
1371
+ inst.hasRenderedVNode = true;
1372
+ const mountScript = inst.el.querySelector('script[data-bb-client-mount="true"]');
1373
+ if (mountScript) {
1374
+ mountScript.remove();
1375
+ }
1376
+ inst.el.innerHTML = "";
1377
+ }
1378
+
1379
+ patchRoot(inst.el, inst.prevVNode, vnode);
1380
+ inst.prevVNode = vnode;
1381
+
1382
+ const effects = inst.effects;
1383
+ inst.effects = [];
1384
+ for (const eff of effects) {
1385
+ if (typeof eff.prevCleanup === "function") {
1386
+ try { eff.prevCleanup(); } catch (err) { console.error(err); }
1387
+ }
1388
+ try {
1389
+ const cleanup = eff.effectFn();
1390
+ inst.hooks[eff.idx] = {
1391
+ deps: eff.deps,
1392
+ cleanup: typeof cleanup === "function" ? cleanup : null,
1393
+ };
1394
+ } catch (err) {
1395
+ console.error(err);
1396
+ }
1397
+ }
1398
+ }
1399
+
1400
+ /**
1401
+ * Mounts a client component into a DOM element with reactive state and lifecycle management.
1402
+ * @param {HTMLElement} el
1403
+ * @param {Function} fn
1404
+ * @param {Record<string, any>} [props={}]
1405
+ */
1406
+ function mountComponent(el, fn, props) {
1407
+ if (!el || typeof fn !== "function") return;
1408
+ let inst = activeComponentInstances.get(el);
1409
+ if (!inst) {
1410
+ inst = {
1411
+ el,
1412
+ fn,
1413
+ props: props || {},
1414
+ hooks: [],
1415
+ hookIndex: 0,
1416
+ effects: [],
1417
+ prevVNode: null,
1418
+ hasRenderedVNode: false,
1419
+ scheduled: false,
1420
+ mounted: true,
1421
+ };
1422
+ activeComponentInstances.set(el, inst);
1423
+ mountedRoots.set(el, {
1424
+ unmount: () => unmountComponentInstance(el),
1425
+ persist: el.getAttribute("data-persist") === "true",
1426
+ name: el.getAttribute("data-island") || fn.name || "ClientComponent",
1427
+ });
1428
+ } else {
1429
+ inst.fn = fn;
1430
+ inst.props = props || {};
1431
+ }
1432
+
1433
+ renderComponentInstance(inst);
1434
+ }
1435
+
1436
+ /**
1437
+ * Cleans up hooks, effects, and active state for an unmounting component.
1438
+ * @param {HTMLElement} el
1439
+ */
1440
+ function unmountComponentInstance(el) {
1441
+ const inst = activeComponentInstances.get(el);
1442
+ if (!inst) return;
1443
+ inst.mounted = false;
1444
+ for (const hook of inst.hooks) {
1445
+ if (hook && typeof hook.cleanup === "function") {
1446
+ try { hook.cleanup(); } catch (err) { console.error(err); }
1447
+ }
1448
+ }
1449
+ activeComponentInstances.delete(el);
1450
+ }
1451
+
1452
+ /**
1453
+ * Executes queued component mount requests initialized before runtime script completion.
1454
+ */
1455
+ function drainMountQueue() {
1456
+ if (window.__BB_MOUNT_QUEUE__ && Array.isArray(window.__BB_MOUNT_QUEUE__)) {
1457
+ const queue = window.__BB_MOUNT_QUEUE__.splice(0);
1458
+ for (const task of queue) {
1459
+ try { task(); } catch (err) { console.error(err); }
1460
+ }
1461
+ }
1462
+ }
1463
+
1464
+ Bluebird.html = html;
1465
+ Bluebird.mount = mountComponent;
1466
+ Bluebird.mountComponent = mountComponent;
1467
+ Bluebird.useState = useState;
1468
+ Bluebird.useEffect = useEffect;
1469
+ Bluebird.useRef = useRef;
1470
+ Bluebird.useMemo = useMemo;
1471
+ Bluebird.useCallback = useCallback;
1472
+
1473
+ window.html = window.html || html;
1474
+ window.useState = window.useState || useState;
1475
+ window.useEffect = window.useEffect || useEffect;
1476
+ window.useRef = window.useRef || useRef;
1477
+ window.useMemo = window.useMemo || useMemo;
1478
+ window.useCallback = window.useCallback || useCallback;
1479
+
1480
+ window.Bluebird = Bluebird;
1481
+ drainMountQueue();
637
1482
 
638
1483
  /**
639
1484
  * Initializes automatic page reload during development when the Node server restarts.
@@ -692,7 +1537,8 @@
692
1537
  */
693
1538
  function triggerInitialLoad() {
694
1539
  initLinkInterception();
695
- Bluebird.hydrate();
1540
+ Bluebird.hydrate();
1541
+ drainMountQueue();
696
1542
  initDevReload();
697
1543
  const detail = { url: window.location.href, initial: true };
698
1544
  window.dispatchEvent(new CustomEvent("bluebird:page-load", { detail }));
@@ -705,1077 +1551,1495 @@
705
1551
  triggerInitialLoad();
706
1552
  }
707
1553
  })();
708
- /* Blue Bird JS v0.2.2 | MIT License | @seip/blue-bird-css */
709
- function bluebird(component, options) {
710
- if (typeof component === 'object') {
711
- options = component;
712
- component = 'snackbar';
713
- }
714
- if (component === 'snackbar') {
715
- let snackbarEl = document.getElementById('snackbar');
716
- if (!snackbarEl) {
717
- snackbarEl = document.createElement('div');
718
- snackbarEl.id = 'snackbar';
719
- document.body.appendChild(snackbarEl);
720
- }
721
- snackbarEl.className = 'show';
722
- if (options && options.type) {
723
- snackbarEl.classList.add(options.type);
724
- } else {
725
- snackbarEl.classList.add('info');
726
- }
727
- snackbarEl.textContent = (options && options.message) || '';
728
- setTimeout(() => {
729
- snackbarEl.classList.add('show');
730
- }, 10);
731
- const duration = (options && options.duration) || 3000;
732
- if (snackbarEl.timeoutId) {
733
- clearTimeout(snackbarEl.timeoutId);
734
- }
735
- snackbarEl.timeoutId = setTimeout(function () {
736
- snackbarEl.className = '';
737
- }, duration);
738
- }
739
- if (component === 'toast') {
740
- const position = (options && options.position) || 'bottom-right';
741
- let container = document.querySelector(`.toast-container.${position}`);
742
- if (!container) {
743
- container = document.createElement('div');
744
- container.className = `toast-container ${position}`;
745
- document.body.appendChild(container);
746
- }
747
- const toastEl = document.createElement('div');
748
- const typeClass = (options && options.type) ? `toast-${options.type}` : 'toast-info';
749
- toastEl.className = `toast ${typeClass}`;
750
- const title = (options && options.title) ? `<div class="toast-title">${options.title}</div>` : '';
751
- const desc = (options && options.description) ? `<div class="toast-description">${options.description}</div>` : '';
752
- toastEl.innerHTML = `
753
- <div class="toast-content">
754
- ${title}
755
- ${desc}
756
- </div>
757
- <button class="toast-close" aria-label="Dismiss">&times;</button>
758
- `;
759
- const closeBtn = toastEl.querySelector('.toast-close');
760
- closeBtn.addEventListener('click', () => dismissToast(toastEl));
761
- container.appendChild(toastEl);
762
- const duration = (options && options.duration) !== undefined ? options.duration : 4000;
763
- if (duration > 0) {
764
- setTimeout(() => dismissToast(toastEl), duration);
765
- }
766
- }
767
- if (component === 'tab') {
768
- const targetId = options && options.id;
769
- if (!targetId) return;
770
- const targetContent = document.getElementById(targetId);
771
- if (!targetContent) return;
772
- const tabsContainer = targetContent.closest('.tabs');
773
- if (!tabsContainer) return;
774
- const allTriggers = tabsContainer.querySelectorAll('.tab-trigger');
775
- const allContents = tabsContainer.querySelectorAll('.tab-content');
776
- allContents.forEach(c => c.classList.remove('active'));
777
- allTriggers.forEach(t => t.classList.remove('active'));
778
- targetContent.classList.add('active');
779
- const matchingTrigger = Array.from(allTriggers).find(t =>
780
- t.getAttribute('data-tab-target') === targetId || t.getAttribute('href') === `#${targetId}`
781
- );
782
- if (matchingTrigger) {
783
- matchingTrigger.classList.add('active');
784
- }
785
- }
786
- if (component === 'command') {
787
- const action = (options && options.action) || 'toggle';
788
- let backdrop = document.querySelector('.command-backdrop');
789
- if (!backdrop) {
790
- backdrop = createCommandPaletteModal();
791
- }
792
- const isOpen = backdrop.classList.contains('open');
793
- if (action === 'open' || (action === 'toggle' && !isOpen)) {
794
- backdrop.classList.add('open');
795
- const input = backdrop.querySelector('.command-input');
796
- if (input) {
797
- input.value = '';
798
- setTimeout(() => input.focus(), 50);
799
- }
800
- } else if (action === 'close' || (action === 'toggle' && isOpen)) {
801
- backdrop.classList.remove('open');
802
- }
803
- }
804
- if (component === 'popover') {
805
- const id = options && options.id;
806
- const action = (options && options.action) || 'toggle';
807
- if (!id) return;
808
- const popoverEl = document.getElementById(id) || document.querySelector(`[data-popover-id="${id}"]`);
809
- if (!popoverEl) return;
810
- const isOpen = popoverEl.classList.contains('open');
811
- if (action === 'open' || (action === 'toggle' && !isOpen)) {
812
- popoverEl.classList.add('open');
813
- } else {
814
- popoverEl.classList.remove('open');
815
- }
816
- }
817
- if (component === 'drawer') {
818
- cleanupOrphanedBackdrops();
819
- const id = options && options.id;
820
- const action = (options && options.action) || 'toggle';
821
- if (!id) return;
822
- const drawerEl = document.getElementById(id);
823
- if (!drawerEl) return;
824
- let overlay = document.querySelector(`.drawer-backdrop[data-for="${id}"]`);
825
- if (!overlay) {
826
- overlay = document.createElement('div');
827
- overlay.className = 'drawer-backdrop';
828
- overlay.setAttribute('data-for', id);
829
- document.body.appendChild(overlay);
830
- overlay.addEventListener('click', () => {
831
- bluebird('drawer', { id, action: 'close' });
832
- });
833
- }
834
- const isOpen = drawerEl.classList.contains('open') || drawerEl.classList.contains('active');
835
- if (action === 'open' || (action === 'toggle' && !isOpen)) {
836
- drawerEl.classList.add('open');
837
- overlay.classList.add('open');
838
- document.body.style.overflow = 'hidden';
839
- } else if (action === 'close' || (action === 'toggle' && isOpen)) {
840
- drawerEl.classList.remove('open');
841
- overlay.classList.remove('open');
842
- document.body.style.overflow = '';
843
- setTimeout(() => {
844
- if (overlay && overlay.parentNode && !drawerEl.classList.contains('open')) {
845
- overlay.remove();
846
- }
847
- }, 300);
848
- }
849
- }
850
- if (component === 'carousel') {
851
- const selector = (options && options.selector) || '.carousel';
852
- const carousels = document.querySelectorAll(selector);
853
- carousels.forEach(carousel => initSingleCarousel(carousel, options));
1554
+ /**
1555
+ * Bluebird Client UI & Interactive Runtime.
1556
+ * Styled with Tailwind CSS v4 and designed for SPA navigation and desktop apps.
1557
+ */
1558
+
1559
+ /**
1560
+ * Escapes HTML special characters in client-side strings.
1561
+ * @param {any} str
1562
+ * @returns {string}
1563
+ */
1564
+ function escapeClientHtml(str) {
1565
+ if (str === null || str === undefined) return "";
1566
+ return String(str)
1567
+ .replace(/&/g, "&amp;")
1568
+ .replace(/</g, "&lt;")
1569
+ .replace(/>/g, "&gt;")
1570
+ .replace(/"/g, "&quot;")
1571
+ .replace(/'/g, "&#39;");
854
1572
  }
855
- if (component === 'datatable' || component === 'table') {
856
- const containerId = (options && (options.container || options.id)) || 'datatable';
857
- return new ResponsiveDataTable(containerId, options);
1573
+
1574
+ let customCommandsList = null;
1575
+ if (typeof window !== "undefined") {
1576
+ window.Bluebird = window.Bluebird || {};
1577
+ window.Bluebird.setCommands = function (items) {
1578
+ customCommandsList = Array.isArray(items) ? items : null;
1579
+ };
858
1580
  }
1581
+
1582
+ /**
1583
+ * Global component dispatcher for Bluebird interactive widgets.
1584
+ * @param {string|Object} component
1585
+ * @param {Object} [options]
1586
+ */
1587
+ function bluebird(component, options) {
1588
+ if (typeof component === "object") {
1589
+ options = component;
1590
+ component = "snackbar";
1591
+ }
1592
+
1593
+ if (component === "snackbar") {
1594
+ let snackbarEl = document.getElementById("snackbar");
1595
+ if (!snackbarEl) {
1596
+ snackbarEl = document.createElement("div");
1597
+ snackbarEl.id = "snackbar";
1598
+ document.body.appendChild(snackbarEl);
1599
+ }
1600
+
1601
+ const type = (options && options.type) || "info";
1602
+ let colorClasses = "bg-slate-900 text-slate-100 border border-slate-700/80";
1603
+ if (type === "success") {
1604
+ colorClasses = "bg-emerald-950/95 text-emerald-100 border border-emerald-500/40";
1605
+ } else if (type === "warning") {
1606
+ colorClasses = "bg-amber-950/95 text-amber-100 border border-amber-500/40";
1607
+ } else if (type === "error" || type === "danger") {
1608
+ colorClasses = "bg-red-950/95 text-red-100 border border-red-500/40";
1609
+ }
1610
+
1611
+ const baseClasses =
1612
+ "fixed bottom-5 left-1/2 -translate-x-1/2 z-[100] flex items-center gap-3 px-5 py-3 rounded-xl shadow-2xl text-sm font-medium transition-all duration-300";
1613
+ snackbarEl.className = `${baseClasses} ${colorClasses} opacity-0 translate-y-4 pointer-events-none`;
1614
+ snackbarEl.textContent = (options && options.message) || "";
1615
+
1616
+ setTimeout(() => {
1617
+ snackbarEl.classList.remove("opacity-0", "translate-y-4", "pointer-events-none");
1618
+ snackbarEl.classList.add("opacity-100", "translate-y-0", "pointer-events-auto");
1619
+ }, 10);
1620
+
1621
+ const duration = (options && options.duration) || 3000;
1622
+ if (snackbarEl.timeoutId) {
1623
+ clearTimeout(snackbarEl.timeoutId);
1624
+ }
1625
+ snackbarEl.timeoutId = setTimeout(function () {
1626
+ snackbarEl.classList.remove("opacity-100", "translate-y-0", "pointer-events-auto");
1627
+ snackbarEl.classList.add("opacity-0", "translate-y-4", "pointer-events-none");
1628
+ }, duration);
1629
+ }
1630
+
1631
+ if (component === "toast") {
1632
+ const position = (options && options.position) || "bottom-right";
1633
+ const posMap = {
1634
+ "bottom-right": "fixed bottom-4 right-4 z-[100] flex flex-col gap-2.5 w-full max-w-sm pointer-events-none",
1635
+ "bottom-left": "fixed bottom-4 left-4 z-[100] flex flex-col gap-2.5 w-full max-w-sm pointer-events-none",
1636
+ "top-right": "fixed top-4 right-4 z-[100] flex flex-col gap-2.5 w-full max-w-sm pointer-events-none",
1637
+ "top-left": "fixed top-4 left-4 z-[100] flex flex-col gap-2.5 w-full max-w-sm pointer-events-none",
1638
+ "top-center": "fixed top-4 left-1/2 -translate-x-1/2 z-[100] flex flex-col gap-2.5 w-full max-w-sm pointer-events-none",
1639
+ "bottom-center": "fixed bottom-4 left-1/2 -translate-x-1/2 z-[100] flex flex-col gap-2.5 w-full max-w-sm pointer-events-none",
1640
+ };
1641
+ const containerClass = posMap[position] || posMap["bottom-right"];
1642
+ let container = document.querySelector(`.toast-container[data-position="${position}"]`);
1643
+ if (!container) {
1644
+ container = document.createElement("div");
1645
+ container.className = `toast-container ${containerClass}`;
1646
+ container.setAttribute("data-position", position);
1647
+ document.body.appendChild(container);
1648
+ }
1649
+
1650
+ const toastEl = document.createElement("div");
1651
+ const type = (options && options.type) || "info";
1652
+ let variantClass = "bg-slate-900/95 border-slate-700/80 text-slate-100";
1653
+ if (type === "success") {
1654
+ variantClass = "bg-slate-900/95 border-emerald-500/40 text-slate-100";
1655
+ } else if (type === "error" || type === "danger") {
1656
+ variantClass = "bg-slate-900/95 border-red-500/40 text-slate-100";
1657
+ } else if (type === "warning") {
1658
+ variantClass = "bg-slate-900/95 border-amber-500/40 text-slate-100";
1659
+ }
1660
+
1661
+ toastEl.className = `toast pointer-events-auto flex items-start justify-between gap-3 p-4 rounded-xl border shadow-xl backdrop-blur-md transition-all duration-200 ${variantClass}`;
1662
+ const title = options && options.title
1663
+ ? `<div class="toast-title font-semibold text-sm">${escapeClientHtml(options.title)}</div>`
1664
+ : "";
1665
+ const desc = options && options.description
1666
+ ? `<div class="toast-description text-xs text-slate-300 mt-0.5 leading-relaxed">${escapeClientHtml(options.description)}</div>`
1667
+ : "";
1668
+
1669
+ toastEl.innerHTML = `
1670
+ <div class="toast-content flex-1 min-w-0">
1671
+ ${title}
1672
+ ${desc}
1673
+ </div>
1674
+ <button class="toast-close shrink-0 rounded-lg p-1 text-slate-400 hover:text-white hover:bg-slate-800 transition-colors leading-none" aria-label="Dismiss">&times;</button>
1675
+ `;
1676
+
1677
+ const closeBtn = toastEl.querySelector(".toast-close");
1678
+ closeBtn.addEventListener("click", () => dismissToast(toastEl));
1679
+ container.appendChild(toastEl);
1680
+
1681
+ const duration = (options && options.duration) !== undefined ? options.duration : 4000;
1682
+ if (duration > 0) {
1683
+ setTimeout(() => dismissToast(toastEl), duration);
1684
+ }
1685
+ }
1686
+
1687
+ if (component === "tab") {
1688
+ const targetId = options && options.id;
1689
+ if (!targetId) return;
1690
+ const targetContent = document.getElementById(targetId);
1691
+ if (!targetContent) return;
1692
+
1693
+ const tabsContainer = targetContent.closest(".tabs") || document.body;
1694
+ const allTriggers = tabsContainer.querySelectorAll(".tab-trigger, [data-tab-target]");
1695
+ const allContents = tabsContainer.querySelectorAll(".tab-content, [data-tab-content]");
1696
+
1697
+ allContents.forEach((c) => {
1698
+ c.classList.remove("active", "block");
1699
+ c.classList.add("hidden");
1700
+ });
1701
+ allTriggers.forEach((t) => {
1702
+ t.classList.remove("active", "border-sky-500", "text-sky-400");
1703
+ t.setAttribute("aria-selected", "false");
1704
+ });
1705
+
1706
+ targetContent.classList.remove("hidden");
1707
+ targetContent.classList.add("active", "block");
1708
+
1709
+ const matchingTrigger = Array.from(allTriggers).find(
1710
+ (t) =>
1711
+ t.getAttribute("data-tab-target") === targetId ||
1712
+ t.getAttribute("href") === `#${targetId}`
1713
+ );
1714
+ if (matchingTrigger) {
1715
+ matchingTrigger.classList.add("active", "border-sky-500", "text-sky-400");
1716
+ matchingTrigger.setAttribute("aria-selected", "true");
1717
+ }
1718
+ }
1719
+
1720
+ if (component === "command") {
1721
+ const action = (options && options.action) || "toggle";
1722
+ let backdrop = document.querySelector(".command-backdrop");
1723
+ if (!backdrop) {
1724
+ backdrop = createCommandPaletteModal();
1725
+ }
1726
+ const isOpen = backdrop.classList.contains("open");
1727
+ if (action === "open" || (action === "toggle" && !isOpen)) {
1728
+ backdrop.classList.remove("hidden");
1729
+ backdrop.classList.add("flex", "open");
1730
+ const input = backdrop.querySelector(".command-input");
1731
+ if (input) {
1732
+ input.value = "";
1733
+ setTimeout(() => input.focus(), 50);
1734
+ }
1735
+ } else if (action === "close" || (action === "toggle" && isOpen)) {
1736
+ backdrop.classList.remove("flex", "open");
1737
+ backdrop.classList.add("hidden");
1738
+ }
1739
+ }
1740
+
1741
+ if (component === "popover") {
1742
+ const id = options && (options.id || options.targetId);
1743
+ const action = (options && options.action) || "toggle";
1744
+ if (!id) return;
1745
+ const popoverEl =
1746
+ document.getElementById(id) || document.querySelector(`[data-popover-id="${id}"]`);
1747
+ if (!popoverEl) return;
1748
+ const isOpen = popoverEl.classList.contains("open");
1749
+ const shouldOpen = action === "open" || (action === "toggle" && !isOpen);
1750
+ popoverEl.classList.toggle("hidden", !shouldOpen);
1751
+ popoverEl.classList.toggle("open", shouldOpen);
1752
+ }
1753
+
1754
+ if (component === "drawer") {
1755
+ cleanupOrphanedBackdrops();
1756
+ const id = options && options.id;
1757
+ const action = (options && options.action) || "toggle";
1758
+ if (!id) return;
1759
+ const drawerEl = document.getElementById(id);
1760
+ if (!drawerEl) return;
1761
+
1762
+ let overlay = document.querySelector(`.drawer-backdrop[data-for="${id}"]`);
1763
+ if (!overlay) {
1764
+ overlay = document.createElement("div");
1765
+ overlay.className =
1766
+ "drawer-backdrop fixed inset-0 z-40 bg-slate-950/60 backdrop-blur-xs transition-opacity duration-300 opacity-0 pointer-events-none";
1767
+ overlay.setAttribute("data-for", id);
1768
+ document.body.appendChild(overlay);
1769
+ overlay.addEventListener("click", () => {
1770
+ bluebird("drawer", { id, action: "close" });
1771
+ });
1772
+ }
1773
+
1774
+ const isOpen = drawerEl.classList.contains("open") || drawerEl.classList.contains("active");
1775
+ if (action === "open" || (action === "toggle" && !isOpen)) {
1776
+ drawerEl.classList.add("open");
1777
+ drawerEl.classList.remove("-translate-x-full");
1778
+ drawerEl.classList.add("translate-x-0");
1779
+ overlay.classList.remove("opacity-0", "pointer-events-none");
1780
+ overlay.classList.add("opacity-100", "pointer-events-auto", "open");
1781
+ document.body.style.overflow = "hidden";
1782
+ } else if (action === "close" || (action === "toggle" && isOpen)) {
1783
+ drawerEl.classList.remove("open", "translate-x-0");
1784
+ drawerEl.classList.add("-translate-x-full");
1785
+ overlay.classList.remove("opacity-100", "pointer-events-auto", "open");
1786
+ overlay.classList.add("opacity-0", "pointer-events-none");
1787
+ document.body.style.overflow = "";
1788
+ setTimeout(() => {
1789
+ if (overlay && overlay.parentNode && !drawerEl.classList.contains("open")) {
1790
+ overlay.remove();
1791
+ }
1792
+ }, 300);
1793
+ }
1794
+ }
1795
+
1796
+ if (component === "carousel") {
1797
+ const selector = (options && options.selector) || ".carousel";
1798
+ const carousels = document.querySelectorAll(selector);
1799
+ carousels.forEach((carousel) => initSingleCarousel(carousel, options));
1800
+ }
1801
+
1802
+ if (component === "datatable" || component === "table") {
1803
+ const containerId = (options && (options.container || options.id)) || "datatable";
1804
+ return new ResponsiveDataTable(containerId, options);
1805
+ }
859
1806
  }
1807
+
1808
+ /**
1809
+ * Display a temporary snackbar message.
1810
+ * @param {Object} options
1811
+ */
860
1812
  function snackbar(options) {
861
- bluebird('snackbar', options);
1813
+ bluebird("snackbar", options);
862
1814
  }
1815
+
1816
+ /**
1817
+ * Display a temporary toast notification.
1818
+ * @param {Object} options
1819
+ */
863
1820
  function toast(options) {
864
- bluebird('toast', options);
1821
+ bluebird("toast", options);
865
1822
  }
1823
+
1824
+ /**
1825
+ * Dismisses a toast element with animation.
1826
+ * @param {HTMLElement} toastEl
1827
+ */
866
1828
  function dismissToast(toastEl) {
867
- if (!toastEl || toastEl.isDismissing) return;
868
- toastEl.isDismissing = true;
869
- toastEl.style.opacity = '0';
870
- toastEl.style.transform = 'translateY(-10px) scale(0.95)';
871
- setTimeout(() => {
872
- if (toastEl.parentNode) {
873
- toastEl.remove();
874
- }
875
- }, 200);
1829
+ if (!toastEl || toastEl.isDismissing) return;
1830
+ toastEl.isDismissing = true;
1831
+ toastEl.style.opacity = "0";
1832
+ toastEl.style.transform = "translateY(-10px) scale(0.95)";
1833
+ setTimeout(() => {
1834
+ if (toastEl.parentNode) {
1835
+ toastEl.remove();
1836
+ }
1837
+ }, 200);
876
1838
  }
1839
+
1840
+ /**
1841
+ * Creates and injects the global command palette modal.
1842
+ * @returns {HTMLElement}
1843
+ */
877
1844
  function createCommandPaletteModal() {
878
- const backdrop = document.createElement('div');
879
- backdrop.className = 'command-backdrop';
880
- backdrop.innerHTML = `
881
- <div class="command-dialog">
882
- <div class="command-input-wrapper">
883
- <span>🔍</span>
884
- <input type="text" class="command-input" placeholder="Type a command or search documentation..." />
885
- <kbd>ESC</kbd>
886
- </div>
887
- <div class="command-list">
888
- <div class="command-group">
889
- <div class="command-group-title">Navigation</div>
890
- <div class="command-item" data-navigate="#/"><span>Documentation Home</span><kbd>↵</kbd></div>
891
- <div class="command-item" data-navigate="#/buttons"><span>Buttons & Badges</span><kbd>↵</kbd></div>
892
- <div class="command-item" data-navigate="#/forms"><span>Forms & Inputs</span><kbd>↵</kbd></div>
893
- </div>
894
- <div class="command-group">
895
- <div class="command-group-title">Components</div>
896
- <div class="command-item" data-navigate="#/carousel"><span>Touch Carousel</span><kbd>↵</kbd></div>
897
- <div class="command-item" data-navigate="#/aside-drawer"><span>Aside & Drawers</span><kbd>↵</kbd></div>
898
- <div class="command-item" data-navigate="#/animations"><span>CSS Animations</span><kbd>↵</kbd></div>
899
- </div>
900
- </div>
901
- </div>
902
- `;
903
- document.body.appendChild(backdrop);
904
- backdrop.addEventListener('click', (e) => {
905
- if (e.target === backdrop) {
906
- bluebird('command', { action: 'close' });
907
- }
908
- });
909
- const input = backdrop.querySelector('.command-input');
910
- input.addEventListener('input', (e) => {
911
- const query = e.target.value.toLowerCase().trim();
912
- const items = backdrop.querySelectorAll('.command-item');
913
- items.forEach(item => {
914
- const text = item.textContent.toLowerCase();
915
- item.style.display = text.includes(query) ? 'flex' : 'none';
916
- });
917
- });
918
- backdrop.addEventListener('click', (e) => {
919
- const item = e.target.closest('.command-item');
920
- if (item && item.getAttribute('data-navigate')) {
921
- window.location.hash = item.getAttribute('data-navigate');
922
- bluebird('command', { action: 'close' });
923
- }
924
- });
925
- return backdrop;
1845
+ const backdrop = document.createElement("div");
1846
+ backdrop.className =
1847
+ "command-backdrop fixed inset-0 z-[100] hidden items-start justify-center bg-slate-950/70 backdrop-blur-xs pt-[14vh] px-4";
1848
+
1849
+ let itemsHtml = "";
1850
+ if (customCommandsList && customCommandsList.length > 0) {
1851
+ itemsHtml = customCommandsList
1852
+ .map(
1853
+ (item) => `
1854
+ <div class="command-item flex items-center justify-between px-3 py-2 rounded-lg text-sm text-slate-300 hover:bg-sky-500/15 hover:text-sky-400 cursor-pointer transition-colors" data-navigate="${escapeClientHtml(item.url || item.href || "")}">
1855
+ <span>${escapeClientHtml(item.label || item.title || item.name)}</span>
1856
+ <kbd class="text-[10px] px-1.5 py-0.5 rounded bg-slate-800 text-slate-400 border border-slate-700">↵</kbd>
1857
+ </div>
1858
+ `
1859
+ )
1860
+ .join("");
1861
+ } else {
1862
+ itemsHtml = `
1863
+ <div class="command-group space-y-1">
1864
+ <div class="command-group-title px-3 py-1 text-[11px] font-semibold uppercase tracking-wider text-slate-500">Navigation</div>
1865
+ <div class="command-item flex items-center justify-between px-3 py-2 rounded-lg text-sm text-slate-300 hover:bg-sky-500/15 hover:text-sky-400 cursor-pointer transition-colors" data-navigate="/"><span>Home</span><kbd class="text-[10px] px-1.5 py-0.5 rounded bg-slate-800 text-slate-400 border border-slate-700">↵</kbd></div>
1866
+ <div class="command-item flex items-center justify-between px-3 py-2 rounded-lg text-sm text-slate-300 hover:bg-sky-500/15 hover:text-sky-400 cursor-pointer transition-colors" data-navigate="/about"><span>About Us</span><kbd class="text-[10px] px-1.5 py-0.5 rounded bg-slate-800 text-slate-400 border border-slate-700">↵</kbd></div>
1867
+ <div class="command-item flex items-center justify-between px-3 py-2 rounded-lg text-sm text-slate-300 hover:bg-sky-500/15 hover:text-sky-400 cursor-pointer transition-colors" data-navigate="/login"><span>Login</span><kbd class="text-[10px] px-1.5 py-0.5 rounded bg-slate-800 text-slate-400 border border-slate-700">↵</kbd></div>
1868
+ <div class="command-item flex items-center justify-between px-3 py-2 rounded-lg text-sm text-slate-300 hover:bg-sky-500/15 hover:text-sky-400 cursor-pointer transition-colors" data-navigate="/dashboard"><span>Dashboard</span><kbd class="text-[10px] px-1.5 py-0.5 rounded bg-slate-800 text-slate-400 border border-slate-700">↵</kbd></div>
1869
+ </div>
1870
+ `;
1871
+ }
1872
+
1873
+ backdrop.innerHTML = `
1874
+ <div class="command-dialog w-full max-w-lg rounded-2xl border border-slate-800 bg-slate-900 text-slate-100 shadow-2xl overflow-hidden">
1875
+ <div class="command-input-wrapper flex items-center gap-3 px-4 py-3 border-b border-slate-800">
1876
+ <span class="text-slate-400">🔍</span>
1877
+ <input type="text" class="command-input w-full bg-transparent text-sm text-slate-100 placeholder-slate-500 focus:outline-none" placeholder="Type a command or search..." />
1878
+ <kbd class="text-[10px] px-1.5 py-0.5 rounded bg-slate-800 text-slate-400 border border-slate-700">ESC</kbd>
1879
+ </div>
1880
+ <div class="command-list max-h-80 overflow-y-auto p-2 space-y-2">
1881
+ ${itemsHtml}
1882
+ </div>
1883
+ </div>
1884
+ `;
1885
+
1886
+ document.body.appendChild(backdrop);
1887
+ backdrop.addEventListener("click", (e) => {
1888
+ if (e.target === backdrop) {
1889
+ bluebird("command", { action: "close" });
1890
+ }
1891
+ });
1892
+
1893
+ const input = backdrop.querySelector(".command-input");
1894
+ input.addEventListener("input", (e) => {
1895
+ const query = e.target.value.toLowerCase().trim();
1896
+ const items = backdrop.querySelectorAll(".command-item");
1897
+ items.forEach((item) => {
1898
+ const text = item.textContent.toLowerCase();
1899
+ item.style.display = text.includes(query) ? "flex" : "none";
1900
+ });
1901
+ });
1902
+
1903
+ backdrop.addEventListener("click", (e) => {
1904
+ const item = e.target.closest(".command-item");
1905
+ if (item && item.getAttribute("data-navigate")) {
1906
+ const dest = item.getAttribute("data-navigate");
1907
+ if (dest.startsWith("/") && window.Bluebird && typeof window.Bluebird.navigate === "function") {
1908
+ window.Bluebird.navigate(dest);
1909
+ } else {
1910
+ window.location.href = dest;
1911
+ }
1912
+ bluebird("command", { action: "close" });
1913
+ }
1914
+ });
1915
+
1916
+ return backdrop;
926
1917
  }
1918
+
1919
+ /**
1920
+ * Removes backdrops whose associated elements are no longer in the DOM.
1921
+ */
927
1922
  function cleanupOrphanedBackdrops() {
928
- document.querySelectorAll('.drawer-backdrop[data-for]').forEach(backdrop => {
929
- const targetId = backdrop.getAttribute('data-for');
930
- if (!document.getElementById(targetId)) {
931
- backdrop.remove();
932
- }
933
- });
1923
+ document.querySelectorAll(".drawer-backdrop[data-for]").forEach((backdrop) => {
1924
+ const targetId = backdrop.getAttribute("data-for");
1925
+ if (!document.getElementById(targetId)) {
1926
+ backdrop.remove();
1927
+ }
1928
+ });
934
1929
  }
1930
+
1931
+ /**
1932
+ * Initializes responsive mobile drawer navigation menu.
1933
+ */
935
1934
  function initMobileDrawer() {
936
- const mainEl = document.querySelector('main');
937
- const aside = mainEl ? mainEl.querySelector(':scope > aside') : null;
938
- if (!aside) return;
939
- let overlay = document.querySelector('.bluebird-drawer-overlay');
940
- if (!overlay) {
941
- overlay = document.createElement('div');
942
- overlay.className = 'bluebird-drawer-overlay';
943
- document.body.appendChild(overlay);
944
- }
945
- let drawer = document.querySelector('.bluebird-drawer');
946
- if (!drawer) {
947
- drawer = document.createElement('div');
948
- drawer.className = 'bluebird-drawer';
949
- document.body.appendChild(drawer);
950
- }
951
- drawer.innerHTML = aside.innerHTML;
952
- let toggle = document.querySelector('.bluebird-drawer-toggle');
953
- if (!toggle) {
954
- toggle = document.createElement('button');
955
- toggle.className = 'bluebird-drawer-toggle';
956
- toggle.innerHTML = '☰';
957
- toggle.setAttribute('aria-label', 'Toggle navigation menu');
958
- const header = document.querySelector('header');
959
- if (header) {
960
- const nav = header.querySelector('nav');
961
- if (nav) {
962
- nav.insertBefore(toggle, nav.firstChild);
963
- } else {
964
- header.prepend(toggle);
965
- }
966
- } else {
967
- document.body.prepend(toggle);
968
- }
969
- }
970
- }
971
- if (!window.__BLUEBIRD_UI_BOUND__) {
972
- window.addEventListener('click', function (e) {
973
- const tabTrigger = e.target.closest('[data-tab-target], .tab-trigger');
974
- if (tabTrigger) {
975
- const targetId = tabTrigger.getAttribute('data-tab-target') || (tabTrigger.getAttribute('href') || '').replace('#', '');
976
- if (targetId) {
977
- e.preventDefault();
978
- bluebird('tab', { id: targetId });
979
- }
980
- }
981
- const popoverTrigger = e.target.closest('[data-popover-target]');
982
- if (popoverTrigger) {
983
- const popoverId = popoverTrigger.getAttribute('data-popover-target');
984
- bluebird('popover', { id: popoverId, action: 'toggle' });
985
- }
986
- if (!e.target.closest('.popover') && !e.target.closest('[data-popover-target]')) {
987
- document.querySelectorAll('.popover.open').forEach(p => p.classList.remove('open'));
988
- }
989
- const mobileToggle = e.target.closest('.bluebird-drawer-toggle');
990
- if (mobileToggle) {
991
- e.preventDefault();
992
- e.stopPropagation();
993
- initMobileDrawer();
994
- const drawer = document.querySelector('.bluebird-drawer');
995
- const overlay = document.querySelector('.bluebird-drawer-overlay');
996
- if (drawer && overlay) {
997
- const isOpen = drawer.classList.contains('open');
998
- if (isOpen) {
999
- drawer.classList.remove('open');
1000
- overlay.classList.remove('open');
1001
- document.body.style.overflow = '';
1002
- } else {
1003
- drawer.classList.add('open');
1004
- overlay.classList.add('open');
1005
- document.body.style.overflow = 'hidden';
1006
- }
1007
- }
1008
- return;
1009
- }
1010
- if (e.target.closest('.bluebird-drawer-overlay')) {
1011
- const drawer = document.querySelector('.bluebird-drawer');
1012
- const overlay = document.querySelector('.bluebird-drawer-overlay');
1013
- if (drawer) drawer.classList.remove('open');
1014
- if (overlay) overlay.classList.remove('open');
1015
- document.body.style.overflow = '';
1016
- return;
1017
- }
1018
- if (e.target.closest('.bluebird-drawer a')) {
1019
- const drawer = document.querySelector('.bluebird-drawer');
1020
- const overlay = document.querySelector('.bluebird-drawer-overlay');
1021
- if (drawer) drawer.classList.remove('open');
1022
- if (overlay) overlay.classList.remove('open');
1023
- document.body.style.overflow = '';
1024
- }
1025
- const btn = e.target.closest("button, a[role='button']");
1026
- if (btn && !btn.classList.contains('fab') && !btn.classList.contains('carousel-nav') && !btn.classList.contains('bluebird-drawer-toggle')) {
1027
- const rect = btn.getBoundingClientRect();
1028
- const size = Math.max(rect.width, rect.height);
1029
- const x = e.clientX - rect.left - size / 2;
1030
- const y = e.clientY - rect.top - size / 2;
1031
- const ripple = document.createElement('span');
1032
- ripple.className = 'ripple';
1033
- ripple.style.width = ripple.style.height = size + 'px';
1034
- ripple.style.left = x + 'px';
1035
- ripple.style.top = y + 'px';
1036
- btn.appendChild(ripple);
1037
- ripple.addEventListener('animationend', () => ripple.remove());
1038
- }
1039
- const drawerTrigger = e.target.closest('[data-drawer-target]');
1040
- if (drawerTrigger) {
1041
- const id = drawerTrigger.getAttribute('data-drawer-target');
1042
- bluebird('drawer', { id, action: 'toggle' });
1043
- }
1044
- const drawerClose = e.target.closest('[data-drawer-close]');
1045
- if (drawerClose) {
1046
- const drawerEl = drawerClose.closest('.drawer');
1047
- if (drawerEl && drawerEl.id) {
1048
- bluebird('drawer', { id: drawerEl.id, action: 'close' });
1049
- }
1050
- }
1051
- });
1935
+ const mainEl = document.querySelector("main");
1936
+ const aside = mainEl ? mainEl.querySelector(":scope > aside") : null;
1937
+ if (!aside) return;
1938
+
1939
+ let overlay = document.querySelector(".bluebird-drawer-overlay");
1940
+ if (!overlay) {
1941
+ overlay = document.createElement("div");
1942
+ overlay.className =
1943
+ "bluebird-drawer-overlay fixed inset-0 z-40 bg-slate-950/60 backdrop-blur-xs hidden";
1944
+ document.body.appendChild(overlay);
1945
+ }
1946
+
1947
+ let drawer = document.querySelector(".bluebird-drawer");
1948
+ if (!drawer) {
1949
+ drawer = document.createElement("div");
1950
+ drawer.className =
1951
+ "bluebird-drawer fixed top-0 left-0 z-50 h-full w-72 max-w-[80vw] bg-slate-900 border-r border-slate-800 p-5 overflow-y-auto transition-transform duration-300 -translate-x-full flex flex-col gap-2";
1952
+ document.body.appendChild(drawer);
1953
+ }
1954
+ drawer.innerHTML = aside.innerHTML;
1955
+
1956
+ let toggle = document.querySelector(".bluebird-drawer-toggle");
1957
+ if (!toggle) {
1958
+ toggle = document.createElement("button");
1959
+ toggle.className =
1960
+ "bluebird-drawer-toggle md:hidden inline-flex items-center justify-center p-2 rounded-lg text-slate-300 hover:text-white hover:bg-slate-800 transition-colors mr-2";
1961
+ toggle.innerHTML = '<span class="text-lg leading-none">☰</span>';
1962
+ toggle.setAttribute("aria-label", "Toggle navigation menu");
1963
+ const header = document.querySelector("header");
1964
+ if (header) {
1965
+ const nav = header.querySelector("nav");
1966
+ if (nav) {
1967
+ nav.insertBefore(toggle, nav.firstChild);
1968
+ } else {
1969
+ header.prepend(toggle);
1970
+ }
1971
+ } else {
1972
+ document.body.prepend(toggle);
1973
+ }
1974
+ }
1052
1975
  }
1976
+
1977
+ /**
1978
+ * Initializes a single carousel container.
1979
+ * @param {HTMLElement} carousel
1980
+ * @param {Object} [opts]
1981
+ */
1053
1982
  function initSingleCarousel(carousel, opts = {}) {
1054
- if (carousel._bb_initialized) return;
1055
- carousel._bb_initialized = true;
1056
- const track = carousel.querySelector('.carousel-track');
1057
- if (!track) return;
1058
- const items = Array.from(track.querySelectorAll('.carousel-item, .carousel-card'));
1059
- if (items.length === 0) return;
1060
- const prevBtn = carousel.querySelector('.carousel-prev');
1061
- const nextBtn = carousel.querySelector('.carousel-next');
1062
- let indicatorsContainer = carousel.querySelector('.carousel-indicators');
1063
- let currentSlideIndex = 0;
1064
- if (indicatorsContainer && indicatorsContainer.children.length === 0) {
1065
- items.forEach((_, idx) => {
1066
- const dot = document.createElement('button');
1067
- dot.className = `carousel-dot ${idx === 0 ? 'active' : ''}`;
1068
- dot.setAttribute('aria-label', `Go to slide ${idx + 1}`);
1069
- dot.addEventListener('click', (e) => {
1070
- e.preventDefault();
1071
- scrollToSlide(idx);
1072
- });
1073
- indicatorsContainer.appendChild(dot);
1074
- });
1075
- }
1076
- function scrollToSlide(index) {
1077
- if (index < 0) index = 0;
1078
- if (index >= items.length) index = items.length - 1;
1079
- currentSlideIndex = index;
1080
- const targetItem = items[index];
1081
- if (targetItem) {
1082
- track.scrollTo({
1083
- left: targetItem.offsetLeft - track.offsetLeft,
1084
- behavior: 'smooth'
1085
- });
1086
- updateIndicators(index);
1087
- }
1088
- }
1089
- function updateIndicators(activeIndex) {
1090
- if (!indicatorsContainer) return;
1091
- const dots = Array.from(indicatorsContainer.children);
1092
- dots.forEach((dot, idx) => {
1093
- dot.classList.toggle('active', idx === activeIndex);
1094
- });
1095
- }
1096
- let scrollTimeout;
1097
- track.addEventListener('scroll', () => {
1098
- clearTimeout(scrollTimeout);
1099
- scrollTimeout = setTimeout(() => {
1100
- const trackLeft = track.scrollLeft;
1101
- let closestIndex = 0;
1102
- let minDistance = Infinity;
1103
- items.forEach((item, idx) => {
1104
- const distance = Math.abs(item.offsetLeft - track.offsetLeft - trackLeft);
1105
- if (distance < minDistance) {
1106
- minDistance = distance;
1107
- closestIndex = idx;
1108
- }
1109
- });
1110
- currentSlideIndex = closestIndex;
1111
- updateIndicators(closestIndex);
1112
- }, 40);
1113
- });
1114
- if (prevBtn) {
1115
- prevBtn.addEventListener('click', (e) => {
1116
- e.preventDefault();
1117
- e.stopPropagation();
1118
- scrollToSlide(currentSlideIndex - 1);
1119
- });
1120
- }
1121
- if (nextBtn) {
1122
- nextBtn.addEventListener('click', (e) => {
1123
- e.preventDefault();
1124
- e.stopPropagation();
1125
- scrollToSlide(currentSlideIndex + 1);
1126
- });
1127
- }
1128
- let startX = 0;
1129
- let isDragging = false;
1130
- track.addEventListener('touchstart', (e) => {
1131
- startX = e.touches[0].clientX;
1132
- isDragging = true;
1133
- }, { passive: true });
1134
- track.addEventListener('touchend', (e) => {
1135
- if (!isDragging) return;
1136
- isDragging = false;
1137
- const endX = e.changedTouches[0].clientX;
1138
- const diffX = startX - endX;
1139
- if (Math.abs(diffX) > 35) {
1140
- if (diffX > 0) {
1141
- scrollToSlide(currentSlideIndex + 1);
1142
- } else {
1143
- scrollToSlide(currentSlideIndex - 1);
1144
- }
1145
- }
1146
- });
1147
- track.addEventListener('mousedown', (e) => {
1148
- startX = e.clientX;
1149
- isDragging = true;
1150
- track.style.cursor = 'grabbing';
1151
- });
1152
- track.addEventListener('mouseleave', () => {
1153
- isDragging = false;
1154
- track.style.cursor = 'grab';
1155
- });
1156
- track.addEventListener('mouseup', (e) => {
1157
- if (!isDragging) return;
1158
- isDragging = false;
1159
- track.style.cursor = 'grab';
1160
- const endX = e.clientX;
1161
- const diffX = startX - endX;
1162
- if (Math.abs(diffX) > 35) {
1163
- if (diffX > 0) {
1164
- scrollToSlide(currentSlideIndex + 1);
1165
- } else {
1166
- scrollToSlide(currentSlideIndex - 1);
1167
- }
1168
- }
1169
- });
1170
- const isAutoplay = (opts && opts.autoplay) || carousel.getAttribute('data-autoplay') === 'true';
1171
- const intervalTime = parseInt((opts && opts.interval) || carousel.getAttribute('data-interval') || 3500, 10);
1172
- if (isAutoplay) {
1173
- let autoInterval = setInterval(() => {
1174
- const nextIdx = (currentSlideIndex + 1) % items.length;
1175
- scrollToSlide(nextIdx);
1176
- }, intervalTime);
1177
- carousel.addEventListener('mouseenter', () => clearInterval(autoInterval));
1178
- carousel.addEventListener('mouseleave', () => {
1179
- autoInterval = setInterval(() => {
1180
- const nextIdx = (currentSlideIndex + 1) % items.length;
1181
- scrollToSlide(nextIdx);
1182
- }, intervalTime);
1183
- });
1184
- }
1983
+ if (carousel._bb_initialized) return;
1984
+ carousel._bb_initialized = true;
1985
+
1986
+ const track = carousel.querySelector(".carousel-track");
1987
+ if (!track) return;
1988
+ track.classList.add("flex", "overflow-x-auto", "snap-x", "snap-mandatory", "scroll-smooth", "gap-4");
1989
+
1990
+ const items = Array.from(track.querySelectorAll(".carousel-item, .carousel-card"));
1991
+ if (items.length === 0) return;
1992
+
1993
+ const prevBtn = carousel.querySelector(".carousel-prev");
1994
+ const nextBtn = carousel.querySelector(".carousel-next");
1995
+ let indicatorsContainer = carousel.querySelector(".carousel-indicators");
1996
+ let currentSlideIndex = 0;
1997
+
1998
+ if (indicatorsContainer && indicatorsContainer.children.length === 0) {
1999
+ items.forEach((_, idx) => {
2000
+ const dot = document.createElement("button");
2001
+ dot.className = `carousel-dot w-2.5 h-2.5 rounded-full transition-all ${
2002
+ idx === 0 ? "bg-sky-400 w-5" : "bg-slate-600"
2003
+ }`;
2004
+ dot.setAttribute("aria-label", `Go to slide ${idx + 1}`);
2005
+ dot.addEventListener("click", (e) => {
2006
+ e.preventDefault();
2007
+ scrollToSlide(idx);
2008
+ });
2009
+ indicatorsContainer.appendChild(dot);
2010
+ });
2011
+ }
2012
+
2013
+ function scrollToSlide(index) {
2014
+ if (index < 0) index = 0;
2015
+ if (index >= items.length) index = items.length - 1;
2016
+ currentSlideIndex = index;
2017
+ const targetItem = items[index];
2018
+ if (targetItem) {
2019
+ track.scrollTo({
2020
+ left: targetItem.offsetLeft - track.offsetLeft,
2021
+ behavior: "smooth",
2022
+ });
2023
+ updateIndicators(index);
2024
+ }
2025
+ }
2026
+
2027
+ function updateIndicators(activeIndex) {
2028
+ if (!indicatorsContainer) return;
2029
+ const dots = Array.from(indicatorsContainer.children);
2030
+ dots.forEach((dot, idx) => {
2031
+ if (idx === activeIndex) {
2032
+ dot.className = "carousel-dot w-5 h-2.5 rounded-full transition-all bg-sky-400";
2033
+ } else {
2034
+ dot.className = "carousel-dot w-2.5 h-2.5 rounded-full transition-all bg-slate-600";
2035
+ }
2036
+ });
2037
+ }
2038
+
2039
+ let scrollTimeout;
2040
+ track.addEventListener("scroll", () => {
2041
+ clearTimeout(scrollTimeout);
2042
+ scrollTimeout = setTimeout(() => {
2043
+ const trackLeft = track.scrollLeft;
2044
+ let closestIndex = 0;
2045
+ let minDistance = Infinity;
2046
+ items.forEach((item, idx) => {
2047
+ const distance = Math.abs(item.offsetLeft - track.offsetLeft - trackLeft);
2048
+ if (distance < minDistance) {
2049
+ minDistance = distance;
2050
+ closestIndex = idx;
2051
+ }
2052
+ });
2053
+ currentSlideIndex = closestIndex;
2054
+ updateIndicators(closestIndex);
2055
+ }, 40);
2056
+ });
2057
+
2058
+ if (prevBtn) {
2059
+ prevBtn.addEventListener("click", (e) => {
2060
+ e.preventDefault();
2061
+ e.stopPropagation();
2062
+ scrollToSlide(currentSlideIndex - 1);
2063
+ });
2064
+ }
2065
+ if (nextBtn) {
2066
+ nextBtn.addEventListener("click", (e) => {
2067
+ e.preventDefault();
2068
+ e.stopPropagation();
2069
+ scrollToSlide(currentSlideIndex + 1);
2070
+ });
2071
+ }
2072
+
2073
+ let startX = 0;
2074
+ let isDragging = false;
2075
+ track.addEventListener(
2076
+ "touchstart",
2077
+ (e) => {
2078
+ startX = e.touches[0].clientX;
2079
+ isDragging = true;
2080
+ },
2081
+ { passive: true }
2082
+ );
2083
+
2084
+ track.addEventListener("touchend", (e) => {
2085
+ if (!isDragging) return;
2086
+ isDragging = false;
2087
+ const endX = e.changedTouches[0].clientX;
2088
+ const diffX = startX - endX;
2089
+ if (Math.abs(diffX) > 35) {
2090
+ if (diffX > 0) {
2091
+ scrollToSlide(currentSlideIndex + 1);
2092
+ } else {
2093
+ scrollToSlide(currentSlideIndex - 1);
2094
+ }
2095
+ }
2096
+ });
2097
+
2098
+ track.addEventListener("mousedown", (e) => {
2099
+ startX = e.clientX;
2100
+ isDragging = true;
2101
+ track.style.cursor = "grabbing";
2102
+ });
2103
+
2104
+ track.addEventListener("mouseleave", () => {
2105
+ isDragging = false;
2106
+ track.style.cursor = "grab";
2107
+ });
2108
+
2109
+ track.addEventListener("mouseup", (e) => {
2110
+ if (!isDragging) return;
2111
+ isDragging = false;
2112
+ track.style.cursor = "grab";
2113
+ const endX = e.clientX;
2114
+ const diffX = startX - endX;
2115
+ if (Math.abs(diffX) > 35) {
2116
+ if (diffX > 0) {
2117
+ scrollToSlide(currentSlideIndex + 1);
2118
+ } else {
2119
+ scrollToSlide(currentSlideIndex - 1);
2120
+ }
2121
+ }
2122
+ });
2123
+
2124
+ const isAutoplay =
2125
+ (opts && opts.autoplay) || carousel.getAttribute("data-autoplay") === "true";
2126
+ const intervalTime = parseInt(
2127
+ (opts && opts.interval) || carousel.getAttribute("data-interval") || 3500,
2128
+ 10
2129
+ );
2130
+
2131
+ if (isAutoplay) {
2132
+ let autoInterval = setInterval(() => {
2133
+ const nextIdx = (currentSlideIndex + 1) % items.length;
2134
+ scrollToSlide(nextIdx);
2135
+ }, intervalTime);
2136
+ carousel.addEventListener("mouseenter", () => clearInterval(autoInterval));
2137
+ carousel.addEventListener("mouseleave", () => {
2138
+ autoInterval = setInterval(() => {
2139
+ const nextIdx = (currentSlideIndex + 1) % items.length;
2140
+ scrollToSlide(nextIdx);
2141
+ }, intervalTime);
2142
+ });
2143
+ }
1185
2144
  }
2145
+
1186
2146
  (function setupDeclarativeListeners() {
1187
- if (window.__BLUEBIRD_UI_BOUND__) return;
1188
- window.__BLUEBIRD_UI_BOUND__ = true;
1189
- document.addEventListener('click', (e) => {
1190
- const copyTrigger = e.target.closest('[data-copy]');
1191
- if (copyTrigger) {
1192
- e.preventDefault();
1193
- const targetAttr = copyTrigger.getAttribute('data-copy');
1194
- let textToCopy = targetAttr;
1195
- if (targetAttr && (targetAttr.startsWith('#') || targetAttr.startsWith('.'))) {
1196
- const targetEl = document.querySelector(targetAttr);
1197
- if (targetEl) {
1198
- textToCopy = targetEl.value !== undefined ? targetEl.value : (targetEl.innerText || targetEl.textContent);
1199
- }
1200
- }
1201
- if (textToCopy) {
1202
- navigator.clipboard.writeText(textToCopy.trim()).then(() => {
1203
- copyTrigger.classList.add('copied');
1204
- if (typeof bluebird === 'function') {
1205
- bluebird('toast', {
1206
- title: 'Copied to clipboard',
1207
- description: textToCopy.length > 50 ? textToCopy.substring(0, 50) + '...' : textToCopy,
1208
- type: 'success',
1209
- duration: 2500
1210
- });
1211
- }
1212
- setTimeout(() => copyTrigger.classList.remove('copied'), 2000);
1213
- });
1214
- }
1215
- return;
1216
- }
1217
- const confirmTrigger = e.target.closest('[data-confirm]');
1218
- if (confirmTrigger) {
1219
- const msg = confirmTrigger.getAttribute('data-confirm') || 'Are you sure?';
1220
- if (!window.confirm(msg)) {
1221
- e.preventDefault();
1222
- e.stopImmediatePropagation();
1223
- return;
1224
- }
1225
- }
1226
- const scrollTrigger = e.target.closest('[data-scroll-to]');
1227
- if (scrollTrigger) {
1228
- e.preventDefault();
1229
- const targetId = scrollTrigger.getAttribute('data-scroll-to');
1230
- const targetEl = document.querySelector(targetId);
1231
- if (targetEl) {
1232
- targetEl.scrollIntoView({ behavior: 'smooth', block: 'start' });
1233
- }
1234
- return;
1235
- }
1236
- const passToggle = e.target.closest('[data-password-toggle]');
1237
- if (passToggle) {
1238
- e.preventDefault();
1239
- const targetSelector = passToggle.getAttribute('data-password-toggle');
1240
- const input = targetSelector
1241
- ? document.querySelector(targetSelector)
1242
- : (passToggle.closest('.input-group, .form-input-group, div')?.querySelector('input') || passToggle.previousElementSibling);
1243
- if (input && (input.type === 'password' || input.type === 'text')) {
1244
- const isPassword = input.type === 'password';
1245
- input.type = isPassword ? 'text' : 'password';
1246
- passToggle.classList.toggle('showing', isPassword);
1247
- passToggle.setAttribute('aria-pressed', isPassword ? 'true' : 'false');
1248
- }
1249
- return;
1250
- }
1251
- const stepUp = e.target.closest('[data-step-up]');
1252
- if (stepUp) {
1253
- e.preventDefault();
1254
- const targetInput = document.querySelector(stepUp.getAttribute('data-step-up')) ||
1255
- stepUp.closest('.stepper')?.querySelector('input[type="number"]');
1256
- if (targetInput && typeof targetInput.stepUp === 'function') {
1257
- targetInput.stepUp();
1258
- targetInput.dispatchEvent(new Event('input', { bubbles: true }));
1259
- targetInput.dispatchEvent(new Event('change', { bubbles: true }));
1260
- }
1261
- return;
1262
- }
1263
- const stepDown = e.target.closest('[data-step-down]');
1264
- if (stepDown) {
1265
- e.preventDefault();
1266
- const targetInput = document.querySelector(stepDown.getAttribute('data-step-down')) ||
1267
- stepDown.closest('.stepper')?.querySelector('input[type="number"]');
1268
- if (targetInput && typeof targetInput.stepDown === 'function') {
1269
- targetInput.stepDown();
1270
- targetInput.dispatchEvent(new Event('input', { bubbles: true }));
1271
- targetInput.dispatchEvent(new Event('change', { bubbles: true }));
1272
- }
1273
- return;
1274
- }
1275
- const selectItem = e.target.closest('[data-select-value]');
1276
- if (selectItem) {
1277
- const val = selectItem.getAttribute('data-select-value');
1278
- const targetSelector = selectItem.getAttribute('data-select-target') ||
1279
- selectItem.closest('[data-select-container]')?.getAttribute('data-select-target');
1280
- if (targetSelector) {
1281
- const targetEl = document.querySelector(targetSelector);
1282
- if (targetEl) {
1283
- if (targetEl.tagName === 'INPUT' || targetEl.tagName === 'SELECT') {
1284
- targetEl.value = val;
1285
- targetEl.dispatchEvent(new Event('input', { bubbles: true }));
1286
- targetEl.dispatchEvent(new Event('change', { bubbles: true }));
1287
- } else {
1288
- targetEl.textContent = selectItem.textContent.trim();
1289
- }
1290
- }
1291
- }
1292
- const parentDropdown = selectItem.closest('.dropdown-content, .popover-content');
1293
- if (parentDropdown) {
1294
- parentDropdown.classList.remove('open');
1295
- }
1296
- }
1297
- const modalTrigger = e.target.closest('[data-toggle="modal"], [data-modal-target], [data-dialog-target]');
1298
- if (modalTrigger) {
1299
- e.preventDefault();
1300
- const targetSelector = modalTrigger.getAttribute('data-modal-target') ||
1301
- modalTrigger.getAttribute('data-dialog-target') ||
1302
- modalTrigger.getAttribute('data-target') ||
1303
- modalTrigger.getAttribute('href');
1304
- if (targetSelector) {
1305
- const dialog = document.querySelector(targetSelector);
1306
- if (dialog && typeof dialog.showModal === 'function') {
1307
- dialog.showModal();
1308
- }
1309
- }
1310
- return;
1311
- }
1312
- const dismissTrigger = e.target.closest('[data-dismiss="modal"], [data-close-dialog], [data-close-modal]');
1313
- if (dismissTrigger) {
1314
- e.preventDefault();
1315
- const dialog = dismissTrigger.closest('dialog') ||
1316
- document.querySelector(dismissTrigger.getAttribute('data-target') || '');
1317
- if (dialog && typeof dialog.close === 'function') {
1318
- dialog.close();
1319
- }
1320
- return;
1321
- }
1322
- const themeTrigger = e.target.closest('[data-toggle="theme"]');
1323
- if (themeTrigger) {
1324
- e.preventDefault();
1325
- const html = document.documentElement;
1326
- const current = html.getAttribute('data-theme') || 'light';
1327
- const next = current === 'dark' ? 'light' : 'dark';
1328
- html.setAttribute('data-theme', next);
1329
- try {
1330
- localStorage.setItem('bluebird-theme', next);
1331
- } catch (err) { }
1332
- return;
1333
- }
1334
- const toastTrigger = e.target.closest('[data-toast]');
1335
- if (toastTrigger) {
1336
- e.preventDefault();
1337
- const desc = toastTrigger.getAttribute('data-toast') || '';
1338
- const title = toastTrigger.getAttribute('data-toast-title') || '';
1339
- const type = toastTrigger.getAttribute('data-toast-type') || 'info';
1340
- if (typeof bluebird === 'function') {
1341
- bluebird('toast', { title, description: desc, type });
1342
- }
1343
- return;
1344
- }
1345
- const snackbarTrigger = e.target.closest('[data-snackbar]');
1346
- if (snackbarTrigger) {
1347
- e.preventDefault();
1348
- const message = snackbarTrigger.getAttribute('data-snackbar') || '';
1349
- const type = snackbarTrigger.getAttribute('data-snackbar-type') || 'info';
1350
- if (typeof bluebird === 'function') {
1351
- bluebird('snackbar', { message, type });
1352
- }
1353
- return;
1354
- }
1355
- if (!e.target.closest('.dropdown') && !e.target.closest('.popover')) {
1356
- document.querySelectorAll('.dropdown-content.open, .popover-content.open').forEach(el => {
1357
- el.classList.remove('open');
1358
- });
1359
- }
1360
- });
1361
- document.addEventListener('input', (e) => {
1362
- const filterInput = e.target.closest('[data-filter-target]');
1363
- if (filterInput) {
1364
- const targetSelector = filterInput.getAttribute('data-filter-target');
1365
- const targetContainer = document.querySelector(targetSelector);
1366
- if (targetContainer) {
1367
- const query = filterInput.value.toLowerCase().trim();
1368
- const items = targetContainer.querySelectorAll('[data-filter-item], li, tr, .card, .dropdown-item, .item');
1369
- let visibleCount = 0;
1370
- items.forEach(item => {
1371
- const text = item.textContent.toLowerCase();
1372
- const matches = text.includes(query);
1373
- item.style.display = matches ? '' : 'none';
1374
- if (matches) visibleCount++;
1375
- });
1376
- const emptyMsg = targetContainer.querySelector('.no-filter-results');
1377
- if (emptyMsg) {
1378
- emptyMsg.style.display = visibleCount === 0 ? 'block' : 'none';
1379
- }
1380
- }
1381
- }
1382
- if (e.target.matches('textarea[data-auto-resize]')) {
1383
- const textarea = e.target;
1384
- textarea.style.height = 'auto';
1385
- textarea.style.height = (textarea.scrollHeight + 2) + 'px';
1386
- }
1387
- });
1388
- document.addEventListener('keydown', (e) => {
1389
- if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
1390
- e.preventDefault();
1391
- if (typeof bluebird === 'function') {
1392
- bluebird('command', { action: 'toggle' });
1393
- }
1394
- } else if (e.key === 'Escape') {
1395
- const openCommand = document.querySelector('.command-backdrop.open');
1396
- if (openCommand && typeof bluebird === 'function') {
1397
- bluebird('command', { action: 'close' });
1398
- }
1399
- }
1400
- });
2147
+ if (window.__BLUEBIRD_UI_BOUND__) return;
2148
+ window.__BLUEBIRD_UI_BOUND__ = true;
2149
+
2150
+ document.addEventListener("click", (e) => {
2151
+ const tabTrigger = e.target.closest("[data-tab-target], .tab-trigger");
2152
+ if (tabTrigger) {
2153
+ const targetId =
2154
+ tabTrigger.getAttribute("data-tab-target") ||
2155
+ (tabTrigger.getAttribute("href") || "").replace("#", "");
2156
+ if (targetId) {
2157
+ e.preventDefault();
2158
+ bluebird("tab", { id: targetId });
2159
+ }
2160
+ }
2161
+
2162
+ const popoverTrigger = e.target.closest("[data-popover-target]");
2163
+ if (popoverTrigger) {
2164
+ const popoverId = popoverTrigger.getAttribute("data-popover-target");
2165
+ bluebird("popover", { id: popoverId, action: "toggle" });
2166
+ }
2167
+ if (!e.target.closest(".popover") && !e.target.closest("[data-popover-target]")) {
2168
+ document.querySelectorAll(".popover.open").forEach((p) => {
2169
+ p.classList.remove("open");
2170
+ p.classList.add("hidden");
2171
+ });
2172
+ }
2173
+
2174
+ const mobileToggle = e.target.closest(".bluebird-drawer-toggle");
2175
+ if (mobileToggle) {
2176
+ e.preventDefault();
2177
+ e.stopPropagation();
2178
+ initMobileDrawer();
2179
+ const drawer = document.querySelector(".bluebird-drawer");
2180
+ const overlay = document.querySelector(".bluebird-drawer-overlay");
2181
+ if (drawer && overlay) {
2182
+ const isOpen = drawer.classList.contains("open");
2183
+ if (isOpen) {
2184
+ drawer.classList.remove("open", "translate-x-0");
2185
+ drawer.classList.add("-translate-x-full");
2186
+ overlay.classList.add("hidden");
2187
+ overlay.classList.remove("open");
2188
+ document.body.style.overflow = "";
2189
+ } else {
2190
+ drawer.classList.remove("-translate-x-full");
2191
+ drawer.classList.add("open", "translate-x-0");
2192
+ overlay.classList.remove("hidden");
2193
+ overlay.classList.add("open");
2194
+ document.body.style.overflow = "hidden";
2195
+ }
2196
+ }
2197
+ return;
2198
+ }
2199
+
2200
+ if (e.target.closest(".bluebird-drawer-overlay")) {
2201
+ const drawer = document.querySelector(".bluebird-drawer");
2202
+ const overlay = document.querySelector(".bluebird-drawer-overlay");
2203
+ if (drawer) {
2204
+ drawer.classList.remove("open", "translate-x-0");
2205
+ drawer.classList.add("-translate-x-full");
2206
+ }
2207
+ if (overlay) {
2208
+ overlay.classList.add("hidden");
2209
+ overlay.classList.remove("open");
2210
+ }
2211
+ document.body.style.overflow = "";
2212
+ return;
2213
+ }
2214
+
2215
+ if (e.target.closest(".bluebird-drawer a")) {
2216
+ const drawer = document.querySelector(".bluebird-drawer");
2217
+ const overlay = document.querySelector(".bluebird-drawer-overlay");
2218
+ if (drawer) {
2219
+ drawer.classList.remove("open", "translate-x-0");
2220
+ drawer.classList.add("-translate-x-full");
2221
+ }
2222
+ if (overlay) {
2223
+ overlay.classList.add("hidden");
2224
+ overlay.classList.remove("open");
2225
+ }
2226
+ document.body.style.overflow = "";
2227
+ }
2228
+
2229
+ const drawerTrigger = e.target.closest("[data-drawer-target]");
2230
+ if (drawerTrigger) {
2231
+ const id = drawerTrigger.getAttribute("data-drawer-target");
2232
+ bluebird("drawer", { id, action: "toggle" });
2233
+ }
2234
+
2235
+ const drawerClose = e.target.closest("[data-drawer-close]");
2236
+ if (drawerClose) {
2237
+ const drawerEl = drawerClose.closest(".drawer");
2238
+ if (drawerEl && drawerEl.id) {
2239
+ bluebird("drawer", { id: drawerEl.id, action: "close" });
2240
+ }
2241
+ }
2242
+
2243
+ const copyTrigger = e.target.closest("[data-copy]");
2244
+ if (copyTrigger) {
2245
+ e.preventDefault();
2246
+ const targetAttr = copyTrigger.getAttribute("data-copy");
2247
+ let textToCopy = targetAttr;
2248
+ if (targetAttr && (targetAttr.startsWith("#") || targetAttr.startsWith("."))) {
2249
+ const targetEl = document.querySelector(targetAttr);
2250
+ if (targetEl) {
2251
+ textToCopy =
2252
+ targetEl.value !== undefined
2253
+ ? targetEl.value
2254
+ : targetEl.innerText || targetEl.textContent;
2255
+ }
2256
+ }
2257
+ if (textToCopy) {
2258
+ navigator.clipboard.writeText(textToCopy.trim()).then(() => {
2259
+ copyTrigger.classList.add("copied");
2260
+ if (typeof bluebird === "function") {
2261
+ bluebird("toast", {
2262
+ title: "Copied to clipboard",
2263
+ description:
2264
+ textToCopy.length > 50 ? textToCopy.substring(0, 50) + "..." : textToCopy,
2265
+ type: "success",
2266
+ duration: 2500,
2267
+ });
2268
+ }
2269
+ setTimeout(() => copyTrigger.classList.remove("copied"), 2000);
2270
+ });
2271
+ }
2272
+ return;
2273
+ }
2274
+
2275
+ const confirmTrigger = e.target.closest("[data-confirm]");
2276
+ if (confirmTrigger) {
2277
+ const msg = confirmTrigger.getAttribute("data-confirm") || "Are you sure?";
2278
+ if (!window.confirm(msg)) {
2279
+ e.preventDefault();
2280
+ e.stopImmediatePropagation();
2281
+ return;
2282
+ }
2283
+ }
2284
+
2285
+ const scrollTrigger = e.target.closest("[data-scroll-to]");
2286
+ if (scrollTrigger) {
2287
+ e.preventDefault();
2288
+ const targetId = scrollTrigger.getAttribute("data-scroll-to");
2289
+ const targetEl = document.querySelector(targetId);
2290
+ if (targetEl) {
2291
+ targetEl.scrollIntoView({ behavior: "smooth", block: "start" });
2292
+ }
2293
+ return;
2294
+ }
2295
+
2296
+ const passToggle = e.target.closest("[data-password-toggle]");
2297
+ if (passToggle) {
2298
+ e.preventDefault();
2299
+ const targetSelector = passToggle.getAttribute("data-password-toggle");
2300
+ const input = targetSelector
2301
+ ? document.querySelector(targetSelector)
2302
+ : passToggle.closest(".input-group, .form-input-group, div")?.querySelector("input") ||
2303
+ passToggle.previousElementSibling;
2304
+ if (input && (input.type === "password" || input.type === "text")) {
2305
+ const isPassword = input.type === "password";
2306
+ input.type = isPassword ? "text" : "password";
2307
+ passToggle.classList.toggle("showing", isPassword);
2308
+ passToggle.setAttribute("aria-pressed", isPassword ? "true" : "false");
2309
+ }
2310
+ return;
2311
+ }
2312
+
2313
+ const stepUp = e.target.closest("[data-step-up]");
2314
+ if (stepUp) {
2315
+ e.preventDefault();
2316
+ const targetInput =
2317
+ document.querySelector(stepUp.getAttribute("data-step-up")) ||
2318
+ stepUp.closest(".stepper")?.querySelector('input[type="number"]');
2319
+ if (targetInput && typeof targetInput.stepUp === "function") {
2320
+ targetInput.stepUp();
2321
+ targetInput.dispatchEvent(new Event("input", { bubbles: true }));
2322
+ targetInput.dispatchEvent(new Event("change", { bubbles: true }));
2323
+ }
2324
+ return;
2325
+ }
2326
+
2327
+ const stepDown = e.target.closest("[data-step-down]");
2328
+ if (stepDown) {
2329
+ e.preventDefault();
2330
+ const targetInput =
2331
+ document.querySelector(stepDown.getAttribute("data-step-down")) ||
2332
+ stepDown.closest(".stepper")?.querySelector('input[type="number"]');
2333
+ if (targetInput && typeof targetInput.stepDown === "function") {
2334
+ targetInput.stepDown();
2335
+ targetInput.dispatchEvent(new Event("input", { bubbles: true }));
2336
+ targetInput.dispatchEvent(new Event("change", { bubbles: true }));
2337
+ }
2338
+ return;
2339
+ }
2340
+
2341
+ const selectItem = e.target.closest("[data-select-value]");
2342
+ if (selectItem) {
2343
+ const val = selectItem.getAttribute("data-select-value");
2344
+ const targetSelector =
2345
+ selectItem.getAttribute("data-select-target") ||
2346
+ selectItem.closest("[data-select-container]")?.getAttribute("data-select-target");
2347
+ if (targetSelector) {
2348
+ const targetEl = document.querySelector(targetSelector);
2349
+ if (targetEl) {
2350
+ if (targetEl.tagName === "INPUT" || targetEl.tagName === "SELECT") {
2351
+ targetEl.value = val;
2352
+ targetEl.dispatchEvent(new Event("input", { bubbles: true }));
2353
+ targetEl.dispatchEvent(new Event("change", { bubbles: true }));
2354
+ } else {
2355
+ targetEl.textContent = selectItem.textContent.trim();
2356
+ }
2357
+ }
2358
+ }
2359
+ const parentDropdown = selectItem.closest(".dropdown-content, .popover-content");
2360
+ if (parentDropdown) {
2361
+ parentDropdown.classList.remove("open");
2362
+ }
2363
+ }
2364
+
2365
+ const modalTrigger = e.target.closest("[data-toggle='modal'], [data-modal-target], [data-dialog-target]");
2366
+ if (modalTrigger) {
2367
+ e.preventDefault();
2368
+ const targetSelector =
2369
+ modalTrigger.getAttribute("data-modal-target") ||
2370
+ modalTrigger.getAttribute("data-dialog-target") ||
2371
+ modalTrigger.getAttribute("data-target") ||
2372
+ modalTrigger.getAttribute("href");
2373
+ if (targetSelector) {
2374
+ const dialog = document.querySelector(targetSelector);
2375
+ if (dialog && typeof dialog.showModal === "function") {
2376
+ dialog.showModal();
2377
+ }
2378
+ }
2379
+ return;
2380
+ }
2381
+
2382
+ const dismissTrigger = e.target.closest("[data-dismiss='modal'], [data-close-dialog], [data-close-modal]");
2383
+ if (dismissTrigger) {
2384
+ e.preventDefault();
2385
+ const dialog =
2386
+ dismissTrigger.closest("dialog") ||
2387
+ document.querySelector(dismissTrigger.getAttribute("data-target") || "");
2388
+ if (dialog && typeof dialog.close === "function") {
2389
+ dialog.close();
2390
+ }
2391
+ return;
2392
+ }
2393
+
2394
+ const themeTrigger = e.target.closest('[data-toggle="theme"]');
2395
+ if (themeTrigger) {
2396
+ e.preventDefault();
2397
+ const html = document.documentElement;
2398
+ const current = html.getAttribute("data-theme") || (html.classList.contains("dark") ? "dark" : "light");
2399
+ const next = current === "dark" ? "light" : "dark";
2400
+ html.setAttribute("data-theme", next);
2401
+ html.classList.toggle("dark", next === "dark");
2402
+ try {
2403
+ localStorage.setItem("bluebird-theme", next);
2404
+ } catch (err) {}
2405
+ return;
2406
+ }
2407
+
2408
+ const toastTrigger = e.target.closest("[data-toast]");
2409
+ if (toastTrigger) {
2410
+ e.preventDefault();
2411
+ const desc = toastTrigger.getAttribute("data-toast") || "";
2412
+ const title = toastTrigger.getAttribute("data-toast-title") || "";
2413
+ const type = toastTrigger.getAttribute("data-toast-type") || "info";
2414
+ if (typeof bluebird === "function") {
2415
+ bluebird("toast", { title, description: desc, type });
2416
+ }
2417
+ return;
2418
+ }
2419
+
2420
+ const snackbarTrigger = e.target.closest("[data-snackbar]");
2421
+ if (snackbarTrigger) {
2422
+ e.preventDefault();
2423
+ const message = snackbarTrigger.getAttribute("data-snackbar") || "";
2424
+ const type = snackbarTrigger.getAttribute("data-snackbar-type") || "info";
2425
+ if (typeof bluebird === "function") {
2426
+ bluebird("snackbar", { message, type });
2427
+ }
2428
+ return;
2429
+ }
2430
+
2431
+ const actionBtn = e.target.closest("button[data-action], a[data-action]");
2432
+ if (actionBtn) {
2433
+ e.preventDefault();
2434
+ const actionName = actionBtn.getAttribute("data-action");
2435
+ if (actionName && window.Bluebird && typeof window.Bluebird.action === "function") {
2436
+ let payload = {};
2437
+ const rawArgs = actionBtn.getAttribute("data-args") || actionBtn.getAttribute("data-payload");
2438
+ if (rawArgs) {
2439
+ try {
2440
+ payload = JSON.parse(rawArgs);
2441
+ } catch {}
2442
+ }
2443
+ const partialTarget = actionBtn.getAttribute("data-partial");
2444
+ window.Bluebird.action(actionName, payload, {
2445
+ url: actionBtn.getAttribute("data-url") || undefined,
2446
+ partial: partialTarget === "true" ? true : partialTarget || false,
2447
+ });
2448
+ }
2449
+ return;
2450
+ }
2451
+
2452
+ if (!e.target.closest(".dropdown") && !e.target.closest(".popover")) {
2453
+ document.querySelectorAll(".dropdown-content.open, .popover-content.open").forEach((el) => {
2454
+ el.classList.remove("open");
2455
+ });
2456
+ }
2457
+ });
2458
+
2459
+ document.addEventListener("input", (e) => {
2460
+ const filterInput = e.target.closest("[data-filter-target]");
2461
+ if (filterInput) {
2462
+ const targetSelector = filterInput.getAttribute("data-filter-target");
2463
+ const targetContainer = document.querySelector(targetSelector);
2464
+ if (targetContainer) {
2465
+ const query = filterInput.value.toLowerCase().trim();
2466
+ const items = targetContainer.querySelectorAll("[data-filter-item], li, tr, .card, .dropdown-item, .item");
2467
+ let visibleCount = 0;
2468
+ items.forEach((item) => {
2469
+ const text = item.textContent.toLowerCase();
2470
+ const matches = text.includes(query);
2471
+ item.style.display = matches ? "" : "none";
2472
+ if (matches) visibleCount++;
2473
+ });
2474
+ const emptyMsg = targetContainer.querySelector(".no-filter-results");
2475
+ if (emptyMsg) {
2476
+ emptyMsg.style.display = visibleCount === 0 ? "block" : "none";
2477
+ }
2478
+ }
2479
+ }
2480
+
2481
+ if (e.target.matches("textarea[data-auto-resize]")) {
2482
+ const textarea = e.target;
2483
+ textarea.style.height = "auto";
2484
+ textarea.style.height = textarea.scrollHeight + 2 + "px";
2485
+ }
2486
+ });
2487
+
2488
+ document.addEventListener("submit", async (e) => {
2489
+ const actionForm = e.target.closest("form[data-action]");
2490
+ if (actionForm && window.Bluebird && typeof window.Bluebird.action === "function") {
2491
+ e.preventDefault();
2492
+ const actionName = actionForm.getAttribute("data-action");
2493
+ const formData = new FormData(actionForm);
2494
+ const payload = {};
2495
+ formData.forEach((val, key) => {
2496
+ payload[key] = val;
2497
+ });
2498
+ const partialAttr = actionForm.getAttribute("data-partial");
2499
+ const res = await window.Bluebird.action(actionName, payload, {
2500
+ url: actionForm.getAttribute("action") || window.location.pathname,
2501
+ partial: partialAttr === "true" ? true : partialAttr || false,
2502
+ });
2503
+ if (res && (res.message || res.data?.message) && typeof bluebird === "function") {
2504
+ bluebird("toast", {
2505
+ title: res.status === "error" ? "Error" : "Success",
2506
+ description: res.message || res.data?.message,
2507
+ type: res.status === "error" ? "error" : "success",
2508
+ });
2509
+ }
2510
+ return;
2511
+ }
2512
+
2513
+ const form = e.target.closest("form[data-bb-form]");
2514
+ if (!form) return;
2515
+ e.preventDefault();
2516
+ const action = form.getAttribute("action") || window.location.pathname;
2517
+ const method = (form.getAttribute("method") || "POST").toUpperCase();
2518
+ const formData = new FormData(form);
2519
+
2520
+ const csrfEl =
2521
+ document.getElementById("csrf") ||
2522
+ document.querySelector('input[name="_csrf"]') ||
2523
+ document.querySelector('meta[name="csrf-token"]');
2524
+ const csrfToken = csrfEl ? csrfEl.value || csrfEl.getAttribute("content") : null;
2525
+ if (csrfToken && !formData.has("_csrf")) {
2526
+ formData.append("_csrf", csrfToken);
2527
+ }
2528
+
2529
+ try {
2530
+ const headers = { "X-Requested-With": "XMLHttpRequest" };
2531
+ if (csrfToken) headers["X-CSRF-Token"] = csrfToken;
2532
+
2533
+ const res = await fetch(action, {
2534
+ method,
2535
+ body: formData,
2536
+ headers,
2537
+ credentials: "include",
2538
+ });
2539
+
2540
+ const redirectHeader = res.headers.get("X-Bluebird-Redirect");
2541
+ if (redirectHeader) {
2542
+ if (window.Bluebird && typeof window.Bluebird.navigate === "function") {
2543
+ window.Bluebird.navigate(redirectHeader);
2544
+ } else {
2545
+ window.location.href = redirectHeader;
2546
+ }
2547
+ return;
2548
+ }
2549
+
2550
+ if (res.redirected) {
2551
+ if (window.Bluebird && typeof window.Bluebird.navigate === "function") {
2552
+ window.Bluebird.navigate(res.url);
2553
+ } else {
2554
+ window.location.href = res.url;
2555
+ }
2556
+ return;
2557
+ }
2558
+
2559
+ const contentType = res.headers.get("content-type") || "";
2560
+ if (contentType.includes("application/json")) {
2561
+ const json = await res.json();
2562
+ if (json.message || json.msg || json.error) {
2563
+ const type = res.ok ? "success" : "error";
2564
+ if (typeof bluebird === "function") {
2565
+ bluebird("toast", {
2566
+ title: res.ok ? "Success" : "Error",
2567
+ description: json.message || json.msg || json.error,
2568
+ type,
2569
+ });
2570
+ }
2571
+ }
2572
+ }
2573
+ } catch (err) {
2574
+ if (typeof bluebird === "function") {
2575
+ bluebird("toast", {
2576
+ title: "Request Failed",
2577
+ description: err.message,
2578
+ type: "error",
2579
+ });
2580
+ }
2581
+ }
2582
+ });
2583
+
2584
+ document.addEventListener("keydown", (e) => {
2585
+ if ((e.ctrlKey || e.metaKey) && e.key === "k") {
2586
+ e.preventDefault();
2587
+ if (typeof bluebird === "function") {
2588
+ bluebird("command", { action: "toggle" });
2589
+ }
2590
+ } else if (e.key === "Escape") {
2591
+ const openCommand = document.querySelector(".command-backdrop.open");
2592
+ if (openCommand && typeof bluebird === "function") {
2593
+ bluebird("command", { action: "close" });
2594
+ }
2595
+ }
2596
+ });
1401
2597
  })();
2598
+
1402
2599
  (function () {
1403
- function init() {
1404
- cleanupOrphanedBackdrops();
1405
- initMobileDrawer();
1406
- document.querySelectorAll('.carousel').forEach(c => initSingleCarousel(c));
1407
- document.querySelectorAll('textarea[data-auto-resize]').forEach(t => {
1408
- t.style.height = 'auto';
1409
- t.style.height = (t.scrollHeight + 2) + 'px';
1410
- });
1411
- try {
1412
- const savedTheme = localStorage.getItem('bluebird-theme');
1413
- if (savedTheme) {
1414
- document.documentElement.setAttribute('data-theme', savedTheme);
1415
- }
1416
- } catch (e) { }
1417
- }
1418
- if (document.readyState === 'loading') {
1419
- document.addEventListener('DOMContentLoaded', () => setTimeout(init, 50));
1420
- } else {
1421
- setTimeout(init, 50);
1422
- }
1423
- if (!window.__BLUEBIRD_INIT_BOUND__) {
1424
- window.__BLUEBIRD_INIT_BOUND__ = true;
1425
- window.addEventListener('bluebird:page-load', () => setTimeout(init, 20));
1426
- window.addEventListener('bluebird:partial-load', () => setTimeout(init, 20));
1427
- }
2600
+ function init() {
2601
+ cleanupOrphanedBackdrops();
2602
+ initMobileDrawer();
2603
+ document.querySelectorAll(".carousel").forEach((c) => initSingleCarousel(c));
2604
+ document.querySelectorAll("textarea[data-auto-resize]").forEach((t) => {
2605
+ t.style.height = "auto";
2606
+ t.style.height = t.scrollHeight + 2 + "px";
2607
+ });
2608
+ try {
2609
+ const savedTheme = localStorage.getItem("bluebird-theme");
2610
+ if (savedTheme) {
2611
+ document.documentElement.setAttribute("data-theme", savedTheme);
2612
+ document.documentElement.classList.toggle("dark", savedTheme === "dark");
2613
+ }
2614
+ } catch (e) {}
2615
+ }
2616
+
2617
+ if (document.readyState === "loading") {
2618
+ document.addEventListener("DOMContentLoaded", () => setTimeout(init, 50));
2619
+ } else {
2620
+ setTimeout(init, 50);
2621
+ }
2622
+
2623
+ if (!window.__BLUEBIRD_INIT_BOUND__) {
2624
+ window.__BLUEBIRD_INIT_BOUND__ = true;
2625
+ window.addEventListener("bluebird:page-load", () => setTimeout(init, 20));
2626
+ window.addEventListener("bluebird:partial-load", () => setTimeout(init, 20));
2627
+ }
1428
2628
  })();
2629
+
2630
+ /**
2631
+ * Standard fetch wrapper supporting automatic CSRF injection and JSON parsing.
2632
+ * @param {string} url
2633
+ * @param {string} method
2634
+ * @param {Object|boolean} body
2635
+ * @param {FormData|boolean} bodyForm
2636
+ * @param {Object} headers
2637
+ * @returns {Promise<any>}
2638
+ */
1429
2639
  async function Http(
1430
- url = "/",
1431
- method = "GET",
1432
- body = false,
1433
- bodyForm = false,
1434
- headers = {},
2640
+ url = "/",
2641
+ method = "GET",
2642
+ body = false,
2643
+ bodyForm = false,
2644
+ headers = {}
1435
2645
  ) {
1436
- const csrfEl = document.getElementById("csrf") || document.querySelector('input[name="_csrf"]') || document.querySelector('meta[name="csrf-token"]');
1437
- const csrfToken = csrfEl ? (csrfEl.value || csrfEl.getAttribute("content")) : null;
1438
- const mergedHeaders = { ...headers };
1439
- if (csrfToken) {
1440
- mergedHeaders["X-CSRF-Token"] = csrfToken;
1441
- }
1442
- const upperMethod = String(method || "GET").toUpperCase();
1443
- const options = { method: upperMethod, headers: mergedHeaders, credentials: "include" };
1444
- if (body) {
1445
- const payload = csrfToken ? { ...body, _csrf: csrfToken, csrf: csrfToken } : body;
1446
- options["body"] = JSON.stringify(payload);
1447
- if (!mergedHeaders["Content-Type"]) {
1448
- mergedHeaders["Content-Type"] = "application/json";
1449
- }
1450
- }
1451
- if (bodyForm) {
1452
- if (csrfToken && bodyForm instanceof FormData) {
1453
- if (!bodyForm.has("_csrf")) bodyForm.append("_csrf", csrfToken);
1454
- }
1455
- options["body"] = bodyForm;
1456
- }
1457
- if (upperMethod !== "GET" && window.Bluebird && typeof window.Bluebird.clearPrefetch === "function") {
1458
- window.Bluebird.clearPrefetch();
1459
- }
1460
- const response = await fetch(url, options);
1461
- if (!response.ok) {
1462
- let errorData;
1463
- try {
1464
- errorData = await response.json();
1465
- } catch {
1466
- errorData = { message: `HTTP Error ${response.status}: ${response.statusText}` };
1467
- }
1468
- throw new Error(errorData.message || errorData.msg || errorData.mensaje || "Fetch request failed");
1469
- }
1470
- return await response.json();
2646
+ const csrfEl =
2647
+ document.getElementById("csrf") ||
2648
+ document.querySelector('input[name="_csrf"]') ||
2649
+ document.querySelector('meta[name="csrf-token"]');
2650
+ const csrfToken = csrfEl ? csrfEl.value || csrfEl.getAttribute("content") : null;
2651
+ const mergedHeaders = { ...headers };
2652
+ if (csrfToken) {
2653
+ mergedHeaders["X-CSRF-Token"] = csrfToken;
2654
+ }
2655
+ const upperMethod = String(method || "GET").toUpperCase();
2656
+ const options = { method: upperMethod, headers: mergedHeaders, credentials: "include" };
2657
+ if (body) {
2658
+ const payload = csrfToken ? { ...body, _csrf: csrfToken, csrf: csrfToken } : body;
2659
+ options["body"] = JSON.stringify(payload);
2660
+ if (!mergedHeaders["Content-Type"]) {
2661
+ mergedHeaders["Content-Type"] = "application/json";
2662
+ }
2663
+ }
2664
+ if (bodyForm) {
2665
+ if (csrfToken && bodyForm instanceof FormData) {
2666
+ if (!bodyForm.has("_csrf")) bodyForm.append("_csrf", csrfToken);
2667
+ }
2668
+ options["body"] = bodyForm;
2669
+ }
2670
+ if (upperMethod !== "GET" && window.Bluebird && typeof window.Bluebird.clearPrefetch === "function") {
2671
+ window.Bluebird.clearPrefetch();
2672
+ }
2673
+ const response = await fetch(url, options);
2674
+ if (!response.ok) {
2675
+ let errorData;
2676
+ try {
2677
+ errorData = await response.json();
2678
+ } catch {
2679
+ errorData = { message: `HTTP Error ${response.status}: ${response.statusText}` };
2680
+ }
2681
+ throw new Error(errorData.message || errorData.msg || errorData.mensaje || "Fetch request failed");
2682
+ }
2683
+ return await response.json();
1471
2684
  }
2685
+
2686
+ /**
2687
+ * Retrieves a query parameter from window.location.search.
2688
+ * @param {string} name
2689
+ * @returns {string|null}
2690
+ */
1472
2691
  function getUrlParameter(name) {
1473
- return new URLSearchParams(window.location.search).get(name);
2692
+ return new URLSearchParams(window.location.search).get(name);
1474
2693
  }
2694
+
2695
+ /**
2696
+ * Checks whether the document matches the specified language.
2697
+ * @param {string} l
2698
+ * @returns {boolean}
2699
+ */
1475
2700
  function lang(l = "es") {
1476
- const docLang = document.documentElement.lang || "es";
1477
- return docLang === l || docLang.startsWith(l);
2701
+ const docLang = document.documentElement.lang || "es";
2702
+ return docLang === l || docLang.startsWith(l);
1478
2703
  }
2704
+
2705
+ /**
2706
+ * High-performance responsive data table with search, pagination, and mobile card view.
2707
+ */
1479
2708
  class ResponsiveDataTable {
1480
- constructor(containerId, options = {}) {
1481
- this.container = typeof containerId === "string" ? document.getElementById(containerId) : containerId;
1482
- if (!this.container) return;
1483
- this.defaults = {
1484
- data: [],
1485
- columns: [],
1486
- rowsPerPage: 10,
1487
- search: true,
1488
- pagination: true,
1489
- headerTitles: {},
1490
- summaryFields: ["id"],
1491
- edit: false,
1492
- delete: false,
1493
- breakpoint: 768,
1494
- };
1495
- this.options = { ...this.defaults, ...options };
1496
- this.currentPage = 1;
1497
- this.filteredData = [...this.options.data];
1498
- this.isMobile = window.innerWidth < this.options.breakpoint;
1499
- this.init();
1500
- window.addEventListener("resize", () => this.handleResize());
1501
- }
1502
- init() {
1503
- this.renderContainer();
1504
- this.updateTable();
1505
- if (this.options.search) this.setupSearch();
1506
- }
1507
- handleResize() {
1508
- const wasMobile = this.isMobile;
1509
- this.isMobile = window.innerWidth < this.options.breakpoint;
1510
- if (wasMobile !== this.isMobile) this.updateTable();
1511
- }
1512
- renderContainer() {
1513
- this.container.innerHTML = `
1514
- <section class="w-full">
1515
- ${this.options.search
1516
- ? `<div class="mb-4 flex items-center justify-between"><input type="search" class="datatable-search-input outline" placeholder="${lang() ? "Buscar..." : "Search..."}" aria-label="Search"/></div>`
1517
- : ""
1518
- }
1519
- <div class="overflow-x-auto">
1520
- <table class="datatable-table hidden"></table>
1521
- <div class="datatable-mobile"></div>
1522
- </div>
1523
- ${this.options.pagination ? `<nav class="datatable-pagination mt-4 flex items-center justify-center gap-1" aria-label="Pagination"></nav>` : ""}
1524
- </section>`;
1525
- }
1526
- renderTable() {
1527
- const table = this.container.querySelector(".datatable-table");
1528
- const mobileView = this.container.querySelector(".datatable-mobile");
1529
- if (!table || !mobileView) return;
1530
- if (this.isMobile) {
1531
- table.classList.add("hidden");
1532
- mobileView.classList.remove("hidden");
1533
- this.renderMobileView();
1534
- } else {
1535
- table.classList.remove("hidden");
1536
- mobileView.classList.add("hidden");
1537
- this.renderDesktopTable();
1538
- }
1539
- }
1540
- renderDesktopTable() {
1541
- const table = this.container.querySelector(".datatable-table");
1542
- table.innerHTML = `
1543
- <thead>
1544
- <tr class="datatable-header"></tr>
1545
- </thead>
1546
- <tbody class="datatable-body"></tbody>`;
1547
- const headerRow = table.querySelector("thead tr");
1548
- this.options.columns.forEach((column) => {
1549
- const th = document.createElement("th");
1550
- th.scope = "col";
1551
- th.textContent =
1552
- this.options.headerTitles[column.key] || column.title || column.key;
1553
- headerRow.appendChild(th);
1554
- });
1555
- if (this.options.edit || this.options.delete) {
1556
- const th = document.createElement("th");
1557
- th.scope = "col";
1558
- th.textContent = lang() ? "Acciones" : "Actions";
1559
- headerRow.appendChild(th);
1560
- }
1561
- const startIndex = (this.currentPage - 1) * this.options.rowsPerPage;
1562
- const endIndex = startIndex + this.options.rowsPerPage;
1563
- const paginatedData = this.filteredData.slice(startIndex, endIndex);
1564
- const tbody = table.querySelector("tbody");
1565
- paginatedData.forEach((item) => {
1566
- const row = document.createElement("tr");
1567
- this.options.columns.forEach((column) => {
1568
- const td = document.createElement("td");
1569
- const value = item[column.key];
1570
- if (
1571
- value &&
1572
- typeof value === "string" &&
1573
- /<[a-z][\s\S]*>/i.test(value)
1574
- ) {
1575
- td.innerHTML = value;
1576
- } else {
1577
- td.textContent = value !== undefined && value !== null ? value : "-";
1578
- }
1579
- row.appendChild(td);
1580
- });
1581
- if (this.options.edit || this.options.delete) {
1582
- const td = document.createElement("td");
1583
- const actionsDiv = document.createElement("div");
1584
- actionsDiv.className = "flex items-center gap-2";
1585
- if (this.options.edit) {
1586
- const btn = document.createElement("button");
1587
- btn.className = "outline";
1588
- btn.textContent = lang() ? "Editar" : "Edit";
1589
- btn.onclick = (e) => this.handleAction("edit", e, item);
1590
- actionsDiv.appendChild(btn);
1591
- }
1592
- if (this.options.delete) {
1593
- const btn = document.createElement("button");
1594
- btn.className = "destructive";
1595
- btn.textContent = lang() ? "Eliminar" : "Delete";
1596
- btn.onclick = (e) => this.handleAction("delete", e, item);
1597
- actionsDiv.appendChild(btn);
1598
- }
1599
- td.appendChild(actionsDiv);
1600
- row.appendChild(td);
1601
- }
1602
- tbody.appendChild(row);
1603
- });
1604
- }
1605
- renderMobileView() {
1606
- const mobileView = this.container.querySelector(".datatable-mobile");
1607
- mobileView.innerHTML = "";
1608
- const startIndex = (this.currentPage - 1) * this.options.rowsPerPage;
1609
- const endIndex = startIndex + this.options.rowsPerPage;
1610
- const paginatedData = this.filteredData.slice(startIndex, endIndex);
1611
- paginatedData.forEach((item) => {
1612
- const card = document.createElement("article");
1613
- card.className = "card mb-4";
1614
- const summary = document.createElement("h3");
1615
- summary.className =
1616
- "flex items-center justify-between font-bold mb-2 pb-2";
1617
- this.options.summaryFields.forEach((fieldKey) => {
1618
- const value = item[fieldKey];
1619
- summary.innerHTML += `<span>${value !== undefined && value !== null ? value : "-"}</span>`;
1620
- });
1621
- card.appendChild(summary);
1622
- const details = document.createElement("dl");
1623
- details.className =
1624
- "grid cols-1 gap-2 mb-2 pb-2";
1625
- this.options.columns.forEach((column) => {
1626
- if (this.options.summaryFields.includes(column.key)) return;
1627
- const dt = document.createElement("dt");
1628
- dt.className =
1629
- "font-bold text-muted";
1630
- dt.textContent =
1631
- this.options.headerTitles[column.key] || column.title || column.key;
1632
- const dd = document.createElement("dd");
1633
- dd.className =
1634
- "text-left";
1635
- const cellValue = item[column.key];
1636
- if (
1637
- cellValue &&
1638
- typeof cellValue === "string" &&
1639
- /<[a-z][\s\S]*>/i.test(cellValue)
1640
- ) {
1641
- dd.innerHTML = cellValue;
1642
- } else {
1643
- dd.textContent = cellValue !== undefined && cellValue !== null ? cellValue : "-";
1644
- }
1645
- details.appendChild(dt);
1646
- details.appendChild(dd);
1647
- });
1648
- card.appendChild(details);
1649
- if (this.options.edit || this.options.delete) {
1650
- const actions = document.createElement("div");
1651
- actions.className = "flex items-center gap-2 justify-end";
1652
- if (this.options.edit) {
1653
- const btn = document.createElement("button");
1654
- btn.className = "outline";
1655
- btn.textContent = lang() ? "Editar" : "Edit";
1656
- btn.onclick = (e) => this.handleAction("edit", e, item);
1657
- actions.appendChild(btn);
1658
- }
1659
- if (this.options.delete) {
1660
- const btn = document.createElement("button");
1661
- btn.className = "destructive";
1662
- btn.textContent = lang() ? "Eliminar" : "Delete";
1663
- btn.onclick = (e) => this.handleAction("delete", e, item);
1664
- actions.appendChild(btn);
1665
- }
1666
- card.appendChild(actions);
1667
- }
1668
- mobileView.appendChild(card);
1669
- });
1670
- }
1671
- renderPagination() {
1672
- const pagination = this.container.querySelector(".datatable-pagination");
1673
- if (!pagination || !this.options.pagination) return;
1674
- pagination.innerHTML = "";
1675
- const pageCount = Math.ceil(
1676
- this.filteredData.length / this.options.rowsPerPage,
1677
- );
1678
- if (pageCount <= 1) return;
1679
- const baseClass = "px-3 py-2 outline";
1680
- const activeClass = "px-3 py-2";
1681
- const prevButton = document.createElement("button");
1682
- prevButton.textContent = "«";
1683
- prevButton.className = baseClass;
1684
- prevButton.disabled = this.currentPage === 1;
1685
- prevButton.onclick = () => this.changePage(this.currentPage - 1);
1686
- pagination.appendChild(prevButton);
1687
- const maxVisible = 5;
1688
- let start = Math.max(1, this.currentPage - Math.floor(maxVisible / 2));
1689
- let end = start + maxVisible - 1;
1690
- if (end > pageCount) {
1691
- end = pageCount;
1692
- start = Math.max(1, end - maxVisible + 1);
1693
- }
1694
- if (start > 1) {
1695
- const firstButton = document.createElement("button");
1696
- firstButton.className = baseClass;
1697
- firstButton.textContent = "1";
1698
- firstButton.onclick = () => this.changePage(1);
1699
- pagination.appendChild(firstButton);
1700
- if (start > 2) pagination.appendChild(this.createEllipsis());
1701
- }
1702
- for (let i = start; i <= end; i++) {
1703
- const button = document.createElement("button");
1704
- button.className =
1705
- i === this.currentPage ? activeClass : baseClass;
1706
- button.textContent = i;
1707
- button.onclick = () => this.changePage(i);
1708
- pagination.appendChild(button);
1709
- }
1710
- if (end < pageCount) {
1711
- if (end < pageCount - 1) pagination.appendChild(this.createEllipsis());
1712
- const lastButton = document.createElement("button");
1713
- lastButton.className = baseClass;
1714
- lastButton.textContent = pageCount;
1715
- lastButton.onclick = () => this.changePage(pageCount);
1716
- pagination.appendChild(lastButton);
1717
- }
1718
- const nextButton = document.createElement("button");
1719
- nextButton.className = baseClass;
1720
- nextButton.textContent = "»";
1721
- nextButton.disabled = this.currentPage === pageCount;
1722
- nextButton.onclick = () => this.changePage(this.currentPage + 1);
1723
- pagination.appendChild(nextButton);
1724
- }
1725
- createEllipsis() {
1726
- const span = document.createElement("span");
1727
- span.className = "px-2 text-muted";
1728
- span.textContent = "...";
1729
- return span;
1730
- }
1731
- changePage(page) {
1732
- this.currentPage = page;
1733
- this.updateTable();
1734
- }
1735
- handleAction(type, event, item) {
1736
- if (!this.options[type]) return;
1737
- const callback =
1738
- typeof this.options[type] === "function"
1739
- ? this.options[type]
1740
- : window[this.options[type]];
1741
- if (typeof callback === "function") callback(event, item.id || item);
1742
- }
1743
- setupSearch() {
1744
- const searchInput = this.container.querySelector(".datatable-search-input");
1745
- if (!searchInput) return;
1746
- searchInput.addEventListener("input", (e) => {
1747
- const term = e.target.value.toLowerCase().trim();
1748
- this.filteredData = this.options.data.filter((item) =>
1749
- this.options.columns.some((column) =>
1750
- String(item[column.key] || "")
1751
- .toLowerCase()
1752
- .includes(term),
1753
- ),
1754
- );
1755
- this.currentPage = 1;
1756
- this.updateTable();
1757
- });
1758
- }
1759
- updateTable() {
1760
- this.renderTable();
1761
- if (this.options.pagination) this.renderPagination();
1762
- }
1763
- updateData(newData) {
1764
- this.options.data = newData;
1765
- this.filteredData = [...newData];
1766
- this.currentPage = 1;
1767
- this.updateTable();
1768
- }
1769
- updateColumns(newColumns) {
1770
- this.options.columns = newColumns;
1771
- this.updateTable();
1772
- }
2709
+ constructor(containerId, options = {}) {
2710
+ this.container =
2711
+ typeof containerId === "string" ? document.getElementById(containerId) : containerId;
2712
+ if (!this.container) return;
2713
+ this.defaults = {
2714
+ data: [],
2715
+ columns: [],
2716
+ rowsPerPage: 10,
2717
+ search: true,
2718
+ pagination: true,
2719
+ headerTitles: {},
2720
+ summaryFields: ["id"],
2721
+ edit: false,
2722
+ delete: false,
2723
+ breakpoint: 768,
2724
+ };
2725
+ this.options = { ...this.defaults, ...options };
2726
+ if (options.pageSize !== undefined) this.options.rowsPerPage = options.pageSize;
2727
+ if (options.searchable !== undefined) this.options.search = options.searchable;
2728
+ if (options.onEdit !== undefined) this.options.edit = options.onEdit;
2729
+ if (options.onDelete !== undefined) this.options.delete = options.onDelete;
2730
+ this.currentPage = 1;
2731
+ this.filteredData = [...this.options.data];
2732
+ this.isMobile = window.innerWidth < this.options.breakpoint;
2733
+ this.init();
2734
+ if (this.container._bb_resize_handler) {
2735
+ window.removeEventListener("resize", this.container._bb_resize_handler);
2736
+ }
2737
+ this._onResize = () => this.handleResize();
2738
+ this.container._bb_resize_handler = this._onResize;
2739
+ window.addEventListener("resize", this._onResize);
2740
+ }
2741
+
2742
+ init() {
2743
+ this.renderContainer();
2744
+ this.updateTable();
2745
+ if (this.options.search) this.setupSearch();
2746
+ }
2747
+
2748
+ handleResize() {
2749
+ const wasMobile = this.isMobile;
2750
+ this.isMobile = window.innerWidth < this.options.breakpoint;
2751
+ if (wasMobile !== this.isMobile) this.updateTable();
2752
+ }
2753
+
2754
+ renderContainer() {
2755
+ this.container.innerHTML = `
2756
+ <section class="w-full">
2757
+ ${
2758
+ this.options.search
2759
+ ? `<div class="mb-4 flex items-center justify-between"><input type="search" class="datatable-search-input w-full sm:w-72 rounded-lg border border-slate-700 bg-slate-900/90 px-3.5 py-2 text-sm text-slate-100 placeholder-slate-400 focus:border-sky-500 focus:outline-none focus:ring-2 focus:ring-sky-500/20" placeholder="${lang() ? "Buscar..." : "Search..."}" aria-label="Search"/></div>`
2760
+ : ""
2761
+ }
2762
+ <div class="overflow-x-auto rounded-xl border border-slate-800">
2763
+ <table class="datatable-table w-full text-sm text-left border-collapse hidden"></table>
2764
+ <div class="datatable-mobile p-3 space-y-3"></div>
2765
+ </div>
2766
+ ${this.options.pagination ? `<nav class="datatable-pagination mt-4 flex items-center justify-center gap-1.5" aria-label="Pagination"></nav>` : ""}
2767
+ </section>`;
2768
+ }
2769
+
2770
+ renderTable() {
2771
+ const table = this.container.querySelector(".datatable-table");
2772
+ const mobileView = this.container.querySelector(".datatable-mobile");
2773
+ if (!table || !mobileView) return;
2774
+ if (this.isMobile) {
2775
+ table.classList.add("hidden");
2776
+ mobileView.classList.remove("hidden");
2777
+ this.renderMobileView();
2778
+ } else {
2779
+ table.classList.remove("hidden");
2780
+ mobileView.classList.add("hidden");
2781
+ this.renderDesktopTable();
2782
+ }
2783
+ }
2784
+
2785
+ renderDesktopTable() {
2786
+ const table = this.container.querySelector(".datatable-table");
2787
+ table.innerHTML = `
2788
+ <thead>
2789
+ <tr class="datatable-header border-b border-slate-800 bg-slate-900/70 text-xs font-semibold uppercase tracking-wider text-slate-400"></tr>
2790
+ </thead>
2791
+ <tbody class="datatable-body divide-y divide-slate-800/70"></tbody>`;
2792
+ const headerRow = table.querySelector("thead tr");
2793
+ this.options.columns.forEach((column) => {
2794
+ const th = document.createElement("th");
2795
+ th.scope = "col";
2796
+ th.className = "px-4 py-3";
2797
+ th.textContent =
2798
+ this.options.headerTitles[column.key] || column.title || column.label || column.key;
2799
+ headerRow.appendChild(th);
2800
+ });
2801
+ if (this.options.edit || this.options.delete) {
2802
+ const th = document.createElement("th");
2803
+ th.scope = "col";
2804
+ th.className = "px-4 py-3";
2805
+ th.textContent = lang() ? "Acciones" : "Actions";
2806
+ headerRow.appendChild(th);
2807
+ }
2808
+ const startIndex = (this.currentPage - 1) * this.options.rowsPerPage;
2809
+ const endIndex = startIndex + this.options.rowsPerPage;
2810
+ const paginatedData = this.filteredData.slice(startIndex, endIndex);
2811
+ const tbody = table.querySelector("tbody");
2812
+ paginatedData.forEach((item) => {
2813
+ const row = document.createElement("tr");
2814
+ row.className = "hover:bg-slate-800/40 transition-colors";
2815
+ this.options.columns.forEach((column) => {
2816
+ const td = document.createElement("td");
2817
+ td.className = "px-4 py-3 text-slate-200";
2818
+ const value = item[column.key];
2819
+ if (
2820
+ value &&
2821
+ typeof value === "string" &&
2822
+ /<[a-z][\s\S]*>/i.test(value)
2823
+ ) {
2824
+ td.innerHTML = value;
2825
+ } else {
2826
+ td.textContent = value !== undefined && value !== null ? value : "-";
2827
+ }
2828
+ row.appendChild(td);
2829
+ });
2830
+ if (this.options.edit || this.options.delete) {
2831
+ const td = document.createElement("td");
2832
+ td.className = "px-4 py-3 text-slate-200";
2833
+ const actionsDiv = document.createElement("div");
2834
+ actionsDiv.className = "flex items-center gap-2";
2835
+ if (this.options.edit) {
2836
+ const btn = document.createElement("button");
2837
+ btn.className =
2838
+ "px-2.5 py-1 text-xs font-medium rounded-md border border-slate-700 text-slate-200 hover:bg-slate-800 transition-colors";
2839
+ btn.textContent = lang() ? "Editar" : "Edit";
2840
+ btn.onclick = (e) => this.handleAction("edit", e, item);
2841
+ actionsDiv.appendChild(btn);
2842
+ }
2843
+ if (this.options.delete) {
2844
+ const btn = document.createElement("button");
2845
+ btn.className =
2846
+ "px-2.5 py-1 text-xs font-medium rounded-md bg-red-500/15 text-red-400 border border-red-500/30 hover:bg-red-500/25 transition-colors";
2847
+ btn.textContent = lang() ? "Eliminar" : "Delete";
2848
+ btn.onclick = (e) => this.handleAction("delete", e, item);
2849
+ actionsDiv.appendChild(btn);
2850
+ }
2851
+ td.appendChild(actionsDiv);
2852
+ row.appendChild(td);
2853
+ }
2854
+ tbody.appendChild(row);
2855
+ });
2856
+ }
2857
+
2858
+ renderMobileView() {
2859
+ const mobileView = this.container.querySelector(".datatable-mobile");
2860
+ mobileView.innerHTML = "";
2861
+ const startIndex = (this.currentPage - 1) * this.options.rowsPerPage;
2862
+ const endIndex = startIndex + this.options.rowsPerPage;
2863
+ const paginatedData = this.filteredData.slice(startIndex, endIndex);
2864
+ paginatedData.forEach((item) => {
2865
+ const card = document.createElement("article");
2866
+ card.className = "rounded-xl border border-slate-800 bg-slate-900/60 p-4 mb-3 shadow-xs";
2867
+ const summary = document.createElement("h3");
2868
+ summary.className =
2869
+ "flex items-center justify-between font-semibold text-slate-100 mb-3 pb-2 border-b border-slate-800";
2870
+ this.options.summaryFields.forEach((fieldKey) => {
2871
+ const value = item[fieldKey];
2872
+ summary.innerHTML += `<span>${escapeClientHtml(value !== undefined && value !== null ? value : "-")}</span>`;
2873
+ });
2874
+ card.appendChild(summary);
2875
+ const details = document.createElement("dl");
2876
+ details.className = "grid grid-cols-1 gap-2 mb-3 text-sm";
2877
+ this.options.columns.forEach((column) => {
2878
+ if (this.options.summaryFields.includes(column.key)) return;
2879
+ const dt = document.createElement("dt");
2880
+ dt.className = "text-xs font-semibold uppercase tracking-wider text-slate-400";
2881
+ dt.textContent =
2882
+ this.options.headerTitles[column.key] || column.title || column.label || column.key;
2883
+ const dd = document.createElement("dd");
2884
+ dd.className = "text-slate-200 mb-1";
2885
+ const cellValue = item[column.key];
2886
+ if (
2887
+ cellValue &&
2888
+ typeof cellValue === "string" &&
2889
+ /<[a-z][\s\S]*>/i.test(cellValue)
2890
+ ) {
2891
+ dd.innerHTML = cellValue;
2892
+ } else {
2893
+ dd.textContent = cellValue !== undefined && cellValue !== null ? cellValue : "-";
2894
+ }
2895
+ details.appendChild(dt);
2896
+ details.appendChild(dd);
2897
+ });
2898
+ card.appendChild(details);
2899
+ if (this.options.edit || this.options.delete) {
2900
+ const actions = document.createElement("div");
2901
+ actions.className = "flex items-center gap-2 justify-end pt-2 border-t border-slate-800/60";
2902
+ if (this.options.edit) {
2903
+ const btn = document.createElement("button");
2904
+ btn.className =
2905
+ "px-2.5 py-1 text-xs font-medium rounded-md border border-slate-700 text-slate-200 hover:bg-slate-800 transition-colors";
2906
+ btn.textContent = lang() ? "Editar" : "Edit";
2907
+ btn.onclick = (e) => this.handleAction("edit", e, item);
2908
+ actions.appendChild(btn);
2909
+ }
2910
+ if (this.options.delete) {
2911
+ const btn = document.createElement("button");
2912
+ btn.className =
2913
+ "px-2.5 py-1 text-xs font-medium rounded-md bg-red-500/15 text-red-400 border border-red-500/30 hover:bg-red-500/25 transition-colors";
2914
+ btn.textContent = lang() ? "Eliminar" : "Delete";
2915
+ btn.onclick = (e) => this.handleAction("delete", e, item);
2916
+ actions.appendChild(btn);
2917
+ }
2918
+ card.appendChild(actions);
2919
+ }
2920
+ mobileView.appendChild(card);
2921
+ });
2922
+ }
2923
+
2924
+ renderPagination() {
2925
+ const pagination = this.container.querySelector(".datatable-pagination");
2926
+ if (!pagination || !this.options.pagination) return;
2927
+ pagination.innerHTML = "";
2928
+ const pageCount = Math.ceil(this.filteredData.length / this.options.rowsPerPage);
2929
+ if (pageCount <= 1) return;
2930
+ const baseClass =
2931
+ "px-3 py-1.5 text-xs font-medium rounded-lg border border-slate-800 bg-slate-900 text-slate-300 hover:bg-slate-800 disabled:opacity-40 disabled:pointer-events-none transition-colors";
2932
+ const activeClass =
2933
+ "px-3 py-1.5 text-xs font-semibold rounded-lg bg-sky-500 text-slate-950 border border-sky-400";
2934
+ const prevButton = document.createElement("button");
2935
+ prevButton.textContent = "«";
2936
+ prevButton.className = baseClass;
2937
+ prevButton.disabled = this.currentPage === 1;
2938
+ prevButton.onclick = () => this.changePage(this.currentPage - 1);
2939
+ pagination.appendChild(prevButton);
2940
+ const maxVisible = 5;
2941
+ let start = Math.max(1, this.currentPage - Math.floor(maxVisible / 2));
2942
+ let end = start + maxVisible - 1;
2943
+ if (end > pageCount) {
2944
+ end = pageCount;
2945
+ start = Math.max(1, end - maxVisible + 1);
2946
+ }
2947
+ if (start > 1) {
2948
+ const firstButton = document.createElement("button");
2949
+ firstButton.className = baseClass;
2950
+ firstButton.textContent = "1";
2951
+ firstButton.onclick = () => this.changePage(1);
2952
+ pagination.appendChild(firstButton);
2953
+ if (start > 2) pagination.appendChild(this.createEllipsis());
2954
+ }
2955
+ for (let i = start; i <= end; i++) {
2956
+ const button = document.createElement("button");
2957
+ button.className = i === this.currentPage ? activeClass : baseClass;
2958
+ button.textContent = i;
2959
+ button.onclick = () => this.changePage(i);
2960
+ pagination.appendChild(button);
2961
+ }
2962
+ if (end < pageCount) {
2963
+ if (end < pageCount - 1) pagination.appendChild(this.createEllipsis());
2964
+ const lastButton = document.createElement("button");
2965
+ lastButton.className = baseClass;
2966
+ lastButton.textContent = pageCount;
2967
+ lastButton.onclick = () => this.changePage(pageCount);
2968
+ pagination.appendChild(lastButton);
2969
+ }
2970
+ const nextButton = document.createElement("button");
2971
+ nextButton.className = baseClass;
2972
+ nextButton.textContent = "»";
2973
+ nextButton.disabled = this.currentPage === pageCount;
2974
+ nextButton.onclick = () => this.changePage(this.currentPage + 1);
2975
+ pagination.appendChild(nextButton);
2976
+ }
2977
+
2978
+ createEllipsis() {
2979
+ const span = document.createElement("span");
2980
+ span.className = "px-2 text-xs text-slate-500";
2981
+ span.textContent = "...";
2982
+ return span;
2983
+ }
2984
+
2985
+ changePage(page) {
2986
+ this.currentPage = page;
2987
+ this.updateTable();
2988
+ }
2989
+
2990
+ handleAction(type, event, item) {
2991
+ if (!this.options[type]) return;
2992
+ const callback =
2993
+ typeof this.options[type] === "function"
2994
+ ? this.options[type]
2995
+ : window[this.options[type]];
2996
+ if (typeof callback === "function") callback(event, item.id || item);
2997
+ }
2998
+
2999
+ setupSearch() {
3000
+ const searchInput = this.container.querySelector(".datatable-search-input");
3001
+ if (!searchInput) return;
3002
+ searchInput.addEventListener("input", (e) => {
3003
+ const term = e.target.value.toLowerCase().trim();
3004
+ this.filteredData = this.options.data.filter((item) =>
3005
+ this.options.columns.some((column) =>
3006
+ String(item[column.key] || "")
3007
+ .toLowerCase()
3008
+ .includes(term)
3009
+ )
3010
+ );
3011
+ this.currentPage = 1;
3012
+ this.updateTable();
3013
+ });
3014
+ }
3015
+
3016
+ updateTable() {
3017
+ this.renderTable();
3018
+ if (this.options.pagination) this.renderPagination();
3019
+ }
3020
+
3021
+ updateData(newData) {
3022
+ this.options.data = newData;
3023
+ this.filteredData = [...newData];
3024
+ this.currentPage = 1;
3025
+ this.updateTable();
3026
+ }
3027
+
3028
+ updateColumns(newColumns) {
3029
+ this.options.columns = newColumns;
3030
+ this.updateTable();
3031
+ }
1773
3032
  }
3033
+
1774
3034
  if (typeof window !== "undefined") {
1775
- window.ResponsiveDataTable = ResponsiveDataTable;
1776
- window.Http = Http;
1777
- window.getUrlParameter = getUrlParameter;
1778
- window.snackbar = snackbar;
1779
- window.toast = toast;
1780
- window.bluebird = bluebird; window.dismissToast = dismissToast; window.initMobileDrawer = initMobileDrawer; window.initSingleCarousel = initSingleCarousel; window.lang = lang;
3035
+ window.ResponsiveDataTable = ResponsiveDataTable;
3036
+ window.Http = Http;
3037
+ window.getUrlParameter = getUrlParameter;
3038
+ window.snackbar = snackbar;
3039
+ window.toast = toast;
3040
+ window.bluebird = bluebird;
3041
+ window.dismissToast = dismissToast;
3042
+ window.initMobileDrawer = initMobileDrawer;
3043
+ window.initSingleCarousel = initSingleCarousel;
3044
+ window.lang = lang;
1781
3045
  }