@livetemplate/client 0.8.26 → 0.8.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/dom/link-interceptor.d.ts +1 -0
- package/dist/dom/link-interceptor.d.ts.map +1 -1
- package/dist/dom/link-interceptor.js +47 -23
- package/dist/dom/link-interceptor.js.map +1 -1
- package/dist/livetemplate-client.browser.js +3 -3
- package/dist/livetemplate-client.browser.js.map +3 -3
- package/dist/tests/navigate.test.js +17 -9
- package/dist/tests/navigate.test.js.map +1 -1
- package/package.json +1 -1
|
@@ -24,6 +24,7 @@ export declare class LinkInterceptor {
|
|
|
24
24
|
private readonly logger;
|
|
25
25
|
private popstateListener;
|
|
26
26
|
private abortController;
|
|
27
|
+
private currentHref;
|
|
27
28
|
constructor(context: LinkInterceptorContext, logger: Logger);
|
|
28
29
|
/**
|
|
29
30
|
* Remove the click listener registered by setup() for a specific
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"link-interceptor.d.ts","sourceRoot":"","sources":["../../dom/link-interceptor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAE9C,MAAM,WAAW,sBAAsB;IACrC,iBAAiB,IAAI,OAAO,GAAG,IAAI,CAAC;IACpC,wBAAwB,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IAO7C,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC;IAKpC,eAAe,IAAI,OAAO,CAAC;CAC5B;AAED;;;;;;;;;;;;;GAaG;AACH,qBAAa,eAAe;
|
|
1
|
+
{"version":3,"file":"link-interceptor.d.ts","sourceRoot":"","sources":["../../dom/link-interceptor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAE9C,MAAM,WAAW,sBAAsB;IACrC,iBAAiB,IAAI,OAAO,GAAG,IAAI,CAAC;IACpC,wBAAwB,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IAO7C,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC;IAKpC,eAAe,IAAI,OAAO,CAAC;CAC5B;AAED;;;;;;;;;;;;;GAaG;AACH,qBAAa,eAAe;IAaxB,OAAO,CAAC,QAAQ,CAAC,OAAO;IACxB,OAAO,CAAC,QAAQ,CAAC,MAAM;IAbzB,OAAO,CAAC,gBAAgB,CAA6B;IACrD,OAAO,CAAC,eAAe,CAAgC;IAQvD,OAAO,CAAC,WAAW,CAAgC;gBAGhC,OAAO,EAAE,sBAAsB,EAC/B,MAAM,EAAE,MAAM;IAGjC;;;;;;;;OAQG;IACH,kBAAkB,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI;IAmBlD,KAAK,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI;IA6C7B,OAAO,CAAC,UAAU;YAwBJ,QAAQ;CA6FvB"}
|
|
@@ -21,6 +21,14 @@ class LinkInterceptor {
|
|
|
21
21
|
this.logger = logger;
|
|
22
22
|
this.popstateListener = null;
|
|
23
23
|
this.abortController = null;
|
|
24
|
+
// Tracks the URL that was last successfully navigated to (or the initial
|
|
25
|
+
// page URL). Updated after each in-band __navigate__ push and after each
|
|
26
|
+
// fetch-based navigation. The popstate handler uses this to compare the
|
|
27
|
+
// target URL against the URL we were actually at *before* the browser
|
|
28
|
+
// changed window.location, because by the time popstate fires, the browser
|
|
29
|
+
// has already moved window.location to the target — making a naive
|
|
30
|
+
// window.location comparison always look like a same-URL no-op.
|
|
31
|
+
this.currentHref = window.location.href;
|
|
24
32
|
}
|
|
25
33
|
/**
|
|
26
34
|
* Remove the click listener registered by setup() for a specific
|
|
@@ -50,6 +58,11 @@ class LinkInterceptor {
|
|
|
50
58
|
}
|
|
51
59
|
}
|
|
52
60
|
setup(wrapper) {
|
|
61
|
+
// Refresh currentHref so the popstate handler compares against the URL
|
|
62
|
+
// that is actually showing when this setup runs, not a stale value from
|
|
63
|
+
// a previous navigation or from construction time (which may predate the
|
|
64
|
+
// first history.replaceState in tests and cross-handler nav re-setups).
|
|
65
|
+
this.currentHref = window.location.href;
|
|
53
66
|
const wrapperId = wrapper.getAttribute("data-lvt-id");
|
|
54
67
|
const listenerKey = `__lvt_link_intercept_${wrapperId}`;
|
|
55
68
|
const existing = document[listenerKey];
|
|
@@ -73,7 +86,13 @@ class LinkInterceptor {
|
|
|
73
86
|
// Handle back/forward navigation
|
|
74
87
|
if (!this.popstateListener) {
|
|
75
88
|
this.popstateListener = () => {
|
|
76
|
-
|
|
89
|
+
// Capture the URL we were at *before* the browser moved to the new
|
|
90
|
+
// history entry. This lets navigate() compare pathname+search against
|
|
91
|
+
// the previous URL rather than window.location (which already reflects
|
|
92
|
+
// the target after popstate fires).
|
|
93
|
+
const prevHref = this.currentHref;
|
|
94
|
+
this.currentHref = window.location.href;
|
|
95
|
+
this.navigate(window.location.href, false, prevHref);
|
|
77
96
|
};
|
|
78
97
|
window.addEventListener("popstate", this.popstateListener);
|
|
79
98
|
}
|
|
@@ -100,19 +119,25 @@ class LinkInterceptor {
|
|
|
100
119
|
return true;
|
|
101
120
|
return false;
|
|
102
121
|
}
|
|
103
|
-
|
|
122
|
+
// prevHref is the URL the client was at *before* this navigation.
|
|
123
|
+
// For link clicks (pushState=true) it defaults to window.location.href,
|
|
124
|
+
// which is correct because pushState hasn't run yet. For popstate
|
|
125
|
+
// (pushState=false) the popstate listener supplies the saved currentHref
|
|
126
|
+
// so the same-pathname comparison reflects the real previous entry, not
|
|
127
|
+
// window.location (which the browser already updated to the target).
|
|
128
|
+
async navigate(href, pushState = true, prevHref = window.location.href) {
|
|
104
129
|
const targetURL = new URL(href, window.location.origin);
|
|
105
|
-
const
|
|
106
|
-
|
|
130
|
+
const refURL = new URL(prevHref, window.location.origin);
|
|
131
|
+
const samePath = targetURL.origin === refURL.origin &&
|
|
132
|
+
targetURL.pathname === refURL.pathname;
|
|
107
133
|
if (samePath) {
|
|
108
|
-
const sameSearch = targetURL.search ===
|
|
134
|
+
const sameSearch = targetURL.search === refURL.search;
|
|
109
135
|
if (sameSearch) {
|
|
110
136
|
// Hash-only change or exact same URL — the browser handles scroll
|
|
111
|
-
// to the anchor; no server round-trip is needed. This
|
|
112
|
-
//
|
|
113
|
-
//
|
|
114
|
-
//
|
|
115
|
-
// and bypasses shouldSkip).
|
|
137
|
+
// to the anchor; no server round-trip is needed. This also correctly
|
|
138
|
+
// handles popstate for hash-only back/forward because the popstate
|
|
139
|
+
// listener passes prevHref (the previous entry), so refURL reflects
|
|
140
|
+
// where we came from rather than the already-updated window.location.
|
|
116
141
|
//
|
|
117
142
|
// Still abort any in-flight cross-path fetch: if a fetch was in
|
|
118
143
|
// progress when the user clicked a hash anchor, we don't want it
|
|
@@ -121,13 +146,13 @@ class LinkInterceptor {
|
|
|
121
146
|
this.abortController = null;
|
|
122
147
|
return;
|
|
123
148
|
}
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
149
|
+
// __navigate__ fast path: same pathname, different search, WS mode.
|
|
150
|
+
// Only for explicit forward navigation (pushState=true / link clicks).
|
|
151
|
+
// For popstate (pushState=false) the search difference is real (it
|
|
152
|
+
// compares against the previous entry via prevHref), but back/forward
|
|
153
|
+
// must restore prior page state via a full fetch, not a WS message
|
|
154
|
+
// that only forwards query data to Mount.
|
|
155
|
+
if (pushState && this.context.canSendNavigate()) {
|
|
131
156
|
// Abort any in-flight fetch even on the fast path: a user could
|
|
132
157
|
// click a cross-path link (starting a fetch) and quickly click a
|
|
133
158
|
// same-pathname link. Without aborting, the earlier fetch can
|
|
@@ -143,16 +168,14 @@ class LinkInterceptor {
|
|
|
143
168
|
// the normal fetch so the navigation isn't silently dropped.
|
|
144
169
|
const sent = this.context.sendNavigate(href);
|
|
145
170
|
if (sent) {
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
}
|
|
171
|
+
window.history.pushState(null, "", href);
|
|
172
|
+
this.currentHref = href;
|
|
149
173
|
return;
|
|
150
174
|
}
|
|
151
175
|
// sendNavigate returned false — fall through to fetch as recovery.
|
|
152
176
|
}
|
|
153
|
-
// HTTP mode, WS not OPEN,
|
|
154
|
-
// fall through to normal fetch. pushState is handled downstream
|
|
155
|
-
// the fetch path (after the response resolves).
|
|
177
|
+
// HTTP mode, WS not OPEN, sendNavigate returned false, or popstate:
|
|
178
|
+
// fall through to normal fetch. pushState is handled downstream.
|
|
156
179
|
}
|
|
157
180
|
// Cancel any in-flight navigation fetch
|
|
158
181
|
this.abortController?.abort();
|
|
@@ -174,6 +197,7 @@ class LinkInterceptor {
|
|
|
174
197
|
if (pushState) {
|
|
175
198
|
window.history.pushState(null, "", href);
|
|
176
199
|
}
|
|
200
|
+
this.currentHref = href;
|
|
177
201
|
this.context.handleNavigationResponse(html);
|
|
178
202
|
}
|
|
179
203
|
catch (e) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"link-interceptor.js","sourceRoot":"","sources":["../../dom/link-interceptor.ts"],"names":[],"mappings":";;;AAmBA;;;;;;;;;;;;;GAaG;AACH,MAAa,eAAe;
|
|
1
|
+
{"version":3,"file":"link-interceptor.js","sourceRoot":"","sources":["../../dom/link-interceptor.ts"],"names":[],"mappings":";;;AAmBA;;;;;;;;;;;;;GAaG;AACH,MAAa,eAAe;IAY1B,YACmB,OAA+B,EAC/B,MAAc;QADd,YAAO,GAAP,OAAO,CAAwB;QAC/B,WAAM,GAAN,MAAM,CAAQ;QAbzB,qBAAgB,GAAwB,IAAI,CAAC;QAC7C,oBAAe,GAA2B,IAAI,CAAC;QACvD,yEAAyE;QACzE,yEAAyE;QACzE,wEAAwE;QACxE,sEAAsE;QACtE,2EAA2E;QAC3E,mEAAmE;QACnE,gEAAgE;QACxD,gBAAW,GAAW,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC;IAKhD,CAAC;IAEJ;;;;;;;;OAQG;IACH,kBAAkB,CAAC,SAAwB;QACzC,qEAAqE;QACrE,oEAAoE;QACpE,2DAA2D;QAC3D,IAAI,CAAC,eAAe,EAAE,KAAK,EAAE,CAAC;QAC9B,IAAI,CAAC,eAAe,GAAG,IAAI,CAAC;QAE5B,IAAI,CAAC,SAAS;YAAE,OAAO;QACvB,MAAM,WAAW,GAAG,wBAAwB,SAAS,EAAE,CAAC;QACxD,MAAM,QAAQ,GAAI,QAAgB,CAAC,WAAW,CAAC,CAAC;QAChD,IAAI,QAAQ,EAAE,CAAC;YACb,qDAAqD;YACrD,yDAAyD;YACzD,uBAAuB;YACvB,QAAQ,CAAC,mBAAmB,CAAC,OAAO,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAC;YACvD,OAAQ,QAAgB,CAAC,WAAW,CAAC,CAAC;QACxC,CAAC;IACH,CAAC;IAED,KAAK,CAAC,OAAgB;QACpB,uEAAuE;QACvE,wEAAwE;QACxE,yEAAyE;QACzE,wEAAwE;QACxE,IAAI,CAAC,WAAW,GAAG,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC;QAExC,MAAM,SAAS,GAAG,OAAO,CAAC,YAAY,CAAC,aAAa,CAAC,CAAC;QACtD,MAAM,WAAW,GAAG,wBAAwB,SAAS,EAAE,CAAC;QACxD,MAAM,QAAQ,GAAI,QAAgB,CAAC,WAAW,CAAC,CAAC;QAChD,IAAI,QAAQ,EAAE,CAAC;YACb,QAAQ,CAAC,mBAAmB,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;QAClD,CAAC;QAED,MAAM,QAAQ,GAAG,CAAC,CAAQ,EAAE,EAAE;YAC5B,MAAM,MAAM,GAAI,CAAC,CAAC,MAAkB,EAAE,OAAO,CAAC,SAAS,CAA6B,CAAC;YACrF,IAAI,CAAC,MAAM;gBAAE,OAAO;YAEpB,MAAM,cAAc,GAAG,IAAI,CAAC,OAAO,CAAC,iBAAiB,EAAE,CAAC;YACxD,IAAI,CAAC,cAAc,IAAI,CAAC,cAAc,CAAC,QAAQ,CAAC,MAAM,CAAC;gBAAE,OAAO;YAEhE,IAAI,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC;gBAAE,OAAO;YAEpC,CAAC,CAAC,cAAc,EAAE,CAAC;YACnB,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QAC7B,CAAC,CAAC;QAEF,QAAQ,CAAC,gBAAgB,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;QAC5C,QAAgB,CAAC,WAAW,CAAC,GAAG,QAAQ,CAAC;QAE1C,iCAAiC;QACjC,IAAI,CAAC,IAAI,CAAC,gBAAgB,EAAE,CAAC;YAC3B,IAAI,CAAC,gBAAgB,GAAG,GAAG,EAAE;gBAC3B,mEAAmE;gBACnE,sEAAsE;gBACtE,uEAAuE;gBACvE,oCAAoC;gBACpC,MAAM,QAAQ,GAAG,IAAI,CAAC,WAAW,CAAC;gBAClC,IAAI,CAAC,WAAW,GAAG,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC;gBACxC,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,KAAK,EAAE,QAAQ,CAAC,CAAC;YACvD,CAAC,CAAC;YACF,MAAM,CAAC,gBAAgB,CAAC,UAAU,EAAE,IAAI,CAAC,gBAAgB,CAAC,CAAC;QAC7D,CAAC;IACH,CAAC;IAEO,UAAU,CAAC,IAAuB;QACxC,iBAAiB;QACjB,IAAI,IAAI,CAAC,MAAM,KAAK,MAAM,CAAC,QAAQ,CAAC,MAAM;YAAE,OAAO,IAAI,CAAC;QACxD,mCAAmC;QACnC,IAAI,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,MAAM,KAAK,OAAO;YAAE,OAAO,IAAI,CAAC;QACxD,iBAAiB;QACjB,IAAI,IAAI,CAAC,YAAY,CAAC,UAAU,CAAC;YAAE,OAAO,IAAI,CAAC;QAC/C,0CAA0C;QAC1C,IAAI,IAAI,CAAC,YAAY,CAAC,sBAAsB,CAAC;YAAE,OAAO,IAAI,CAAC;QAC3D,mCAAmC;QACnC,IAAI,IAAI,CAAC,QAAQ,KAAK,MAAM,CAAC,QAAQ,CAAC,QAAQ,IAAI,IAAI,CAAC,IAAI;YAAE,OAAO,IAAI,CAAC;QACzE,wBAAwB;QACxB,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC;QAC/B,IAAI,QAAQ,KAAK,OAAO,IAAI,QAAQ,KAAK,QAAQ;YAAE,OAAO,IAAI,CAAC;QAE/D,OAAO,KAAK,CAAC;IACf,CAAC;IAED,kEAAkE;IAClE,wEAAwE;IACxE,kEAAkE;IAClE,yEAAyE;IACzE,wEAAwE;IACxE,qEAAqE;IAC7D,KAAK,CAAC,QAAQ,CACpB,IAAY,EACZ,YAAqB,IAAI,EACzB,WAAmB,MAAM,CAAC,QAAQ,CAAC,IAAI;QAEvC,MAAM,SAAS,GAAG,IAAI,GAAG,CAAC,IAAI,EAAE,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;QACxD,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,QAAQ,EAAE,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;QACzD,MAAM,QAAQ,GACZ,SAAS,CAAC,MAAM,KAAK,MAAM,CAAC,MAAM;YAClC,SAAS,CAAC,QAAQ,KAAK,MAAM,CAAC,QAAQ,CAAC;QAEzC,IAAI,QAAQ,EAAE,CAAC;YACb,MAAM,UAAU,GAAG,SAAS,CAAC,MAAM,KAAK,MAAM,CAAC,MAAM,CAAC;YACtD,IAAI,UAAU,EAAE,CAAC;gBACf,kEAAkE;gBAClE,qEAAqE;gBACrE,mEAAmE;gBACnE,oEAAoE;gBACpE,sEAAsE;gBACtE,EAAE;gBACF,gEAAgE;gBAChE,iEAAiE;gBACjE,6DAA6D;gBAC7D,IAAI,CAAC,eAAe,EAAE,KAAK,EAAE,CAAC;gBAC9B,IAAI,CAAC,eAAe,GAAG,IAAI,CAAC;gBAC5B,OAAO;YACT,CAAC;YAED,oEAAoE;YACpE,uEAAuE;YACvE,mEAAmE;YACnE,sEAAsE;YACtE,mEAAmE;YACnE,0CAA0C;YAC1C,IAAI,SAAS,IAAI,IAAI,CAAC,OAAO,CAAC,eAAe,EAAE,EAAE,CAAC;gBAChD,gEAAgE;gBAChE,iEAAiE;gBACjE,8DAA8D;gBAC9D,mEAAmE;gBACnE,+BAA+B;gBAC/B,IAAI,CAAC,eAAe,EAAE,KAAK,EAAE,CAAC;gBAC9B,IAAI,CAAC,eAAe,GAAG,IAAI,CAAC;gBAC5B,iEAAiE;gBACjE,6DAA6D;gBAC7D,4CAA4C;gBAC5C,iEAAiE;gBACjE,iEAAiE;gBACjE,6DAA6D;gBAC7D,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;gBAC7C,IAAI,IAAI,EAAE,CAAC;oBACT,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,IAAI,EAAE,EAAE,EAAE,IAAI,CAAC,CAAC;oBACzC,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC;oBACxB,OAAO;gBACT,CAAC;gBACD,mEAAmE;YACrE,CAAC;YACD,oEAAoE;YACpE,iEAAiE;QACnE,CAAC;QAED,wCAAwC;QACxC,IAAI,CAAC,eAAe,EAAE,KAAK,EAAE,CAAC;QAC9B,IAAI,CAAC,eAAe,GAAG,IAAI,eAAe,EAAE,CAAC;QAE7C,IAAI,CAAC;YACH,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,IAAI,EAAE;gBACjC,WAAW,EAAE,SAAS;gBACtB,OAAO,EAAE,EAAE,MAAM,EAAE,WAAW,EAAE;gBAChC,MAAM,EAAE,IAAI,CAAC,eAAe,CAAC,MAAM;aACpC,CAAC,CAAC;YAEH,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;gBACjB,MAAM,CAAC,QAAQ,CAAC,IAAI,GAAG,IAAI,CAAC;gBAC5B,OAAO;YACT,CAAC;YAED,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;YAEnC,4DAA4D;YAC5D,0DAA0D;YAC1D,6DAA6D;YAC7D,IAAI,SAAS,EAAE,CAAC;gBACd,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,IAAI,EAAE,EAAE,EAAE,IAAI,CAAC,CAAC;YAC3C,CAAC;YAED,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC;YACxB,IAAI,CAAC,OAAO,CAAC,wBAAwB,CAAC,IAAI,CAAC,CAAC;QAC9C,CAAC;QAAC,OAAO,CAAU,EAAE,CAAC;YACpB,iEAAiE;YACjE,IAAI,CAAC,YAAY,YAAY,IAAI,CAAC,CAAC,IAAI,KAAK,YAAY;gBAAE,OAAO;YACjE,MAAM,CAAC,QAAQ,CAAC,IAAI,GAAG,IAAI,CAAC;QAC9B,CAAC;IACH,CAAC;CACF;AA/MD,0CA+MC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var LiveTemplateClient=(()=>{var ye=Object.defineProperty;var at=Object.getOwnPropertyDescriptor;var lt=Object.getOwnPropertyNames;var ct=Object.prototype.hasOwnProperty;var dt=(o,e)=>{for(var t in e)ye(o,t,{get:e[t],enumerable:!0})},ut=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of lt(e))!ct.call(o,r)&&r!==t&&ye(o,r,{get:()=>e[r],enumerable:!(n=at(e,r))||n.enumerable});return o};var pt=o=>ut(ye({},"__esModule",{value:!0}),o);var Bt={};dt(Bt,{LiveTemplateClient:()=>me,compareHTML:()=>ot,loadAndApplyUpdate:()=>st,setupReactiveAttributeListeners:()=>ie});var _e=11;function gt(o,e){var t=e.attributes,n,r,i,a,s;if(!(e.nodeType===_e||o.nodeType===_e)){for(var l=t.length-1;l>=0;l--)n=t[l],r=n.name,i=n.namespaceURI,a=n.value,i?(r=n.localName||r,s=o.getAttributeNS(i,r),s!==a&&(n.prefix==="xmlns"&&(r=n.name),o.setAttributeNS(i,r,a))):(s=o.getAttribute(r),s!==a&&o.setAttribute(r,a));for(var c=o.attributes,d=c.length-1;d>=0;d--)n=c[d],r=n.name,i=n.namespaceURI,i?(r=n.localName||r,e.hasAttributeNS(i,r)||o.removeAttributeNS(i,r)):e.hasAttribute(r)||o.removeAttribute(r)}}var J,ft="http://www.w3.org/1999/xhtml",I=typeof document=="undefined"?void 0:document,ht=!!I&&"content"in I.createElement("template"),mt=!!I&&I.createRange&&"createContextualFragment"in I.createRange();function vt(o){var e=I.createElement("template");return e.innerHTML=o,e.content.childNodes[0]}function yt(o){J||(J=I.createRange(),J.selectNode(I.body));var e=J.createContextualFragment(o);return e.childNodes[0]}function bt(o){var e=I.createElement("body");return e.innerHTML=o,e.childNodes[0]}function Et(o){return o=o.trim(),ht?vt(o):mt?yt(o):bt(o)}function Q(o,e){var t=o.nodeName,n=e.nodeName,r,i;return t===n?!0:(r=t.charCodeAt(0),i=n.charCodeAt(0),r<=90&&i>=97?t===n.toUpperCase():i<=90&&r>=97?n===t.toUpperCase():!1)}function wt(o,e){return!e||e===ft?I.createElement(o):I.createElementNS(e,o)}function St(o,e){for(var t=o.firstChild;t;){var n=t.nextSibling;e.appendChild(t),t=n}return e}function be(o,e,t){o[t]!==e[t]&&(o[t]=e[t],o[t]?o.setAttribute(t,""):o.removeAttribute(t))}var Fe={OPTION:function(o,e){var t=o.parentNode;if(t){var n=t.nodeName.toUpperCase();n==="OPTGROUP"&&(t=t.parentNode,n=t&&t.nodeName.toUpperCase()),n==="SELECT"&&!t.hasAttribute("multiple")&&(o.hasAttribute("selected")&&!e.selected&&(o.setAttribute("selected","selected"),o.removeAttribute("selected")),t.selectedIndex=-1)}be(o,e,"selected")},INPUT:function(o,e){be(o,e,"checked"),be(o,e,"disabled"),o.value!==e.value&&(o.value=e.value),e.hasAttribute("value")||o.removeAttribute("value")},TEXTAREA:function(o,e){var t=e.value;o.value!==t&&(o.value=t);var n=o.firstChild;if(n){var r=n.nodeValue;if(r==t||!t&&r==o.placeholder)return;n.nodeValue=t}},SELECT:function(o,e){if(!e.hasAttribute("multiple")){for(var t=-1,n=0,r=o.firstChild,i,a;r;)if(a=r.nodeName&&r.nodeName.toUpperCase(),a==="OPTGROUP")i=r,r=i.firstChild,r||(r=i.nextSibling,i=null);else{if(a==="OPTION"){if(r.hasAttribute("selected")){t=n;break}n++}r=r.nextSibling,!r&&i&&(r=i.nextSibling,i=null)}o.selectedIndex=t}}},V=1,Ie=11,Re=3,Ne=8;function W(){}function Tt(o){if(o)return o.getAttribute&&o.getAttribute("id")||o.id}function At(o){return function(t,n,r){if(r||(r={}),typeof n=="string")if(t.nodeName==="#document"||t.nodeName==="HTML"||t.nodeName==="BODY"){var i=n;n=I.createElement("html"),n.innerHTML=i}else n=Et(n);else n.nodeType===Ie&&(n=n.firstElementChild);var a=r.getNodeKey||Tt,s=r.onBeforeNodeAdded||W,l=r.onNodeAdded||W,c=r.onBeforeElUpdated||W,d=r.onElUpdated||W,p=r.onBeforeNodeDiscarded||W,u=r.onNodeDiscarded||W,f=r.onBeforeElChildrenUpdated||W,v=r.skipFromChildren||W,C=r.addChild||function(h,m){return h.appendChild(m)},w=r.childrenOnly===!0,y=Object.create(null),_=[];function g(h){_.push(h)}function x(h,m){if(h.nodeType===V)for(var M=h.firstChild;M;){var E=void 0;m&&(E=a(M))?g(E):(u(M),M.firstChild&&x(M,m)),M=M.nextSibling}}function k(h,m,M){p(h)!==!1&&(m&&m.removeChild(h),u(h),x(h,M))}function N(h){if(h.nodeType===V||h.nodeType===Ie)for(var m=h.firstChild;m;){var M=a(m);M&&(y[M]=m),N(m),m=m.nextSibling}}N(t);function G(h){l(h);for(var m=h.firstChild;m;){var M=m.nextSibling,E=a(m);if(E){var S=y[E];S&&Q(m,S)?(m.parentNode.replaceChild(S,m),F(S,m)):G(m)}else G(m);m=M}}function L(h,m,M){for(;m;){var E=m.nextSibling;(M=a(m))?g(M):k(m,h,!0),m=E}}function F(h,m,M){var E=a(m);if(E&&delete y[E],!M){var S=c(h,m);if(S===!1||(S instanceof HTMLElement&&(h=S,N(h)),o(h,m),d(h),f(h,m)===!1))return}h.nodeName!=="TEXTAREA"?A(h,m):Fe.TEXTAREA(h,m)}function A(h,m){var M=v(h,m),E=m.firstChild,S=h.firstChild,B,O,K,X,U;e:for(;E;){for(X=E.nextSibling,B=a(E);!M&&S;){if(K=S.nextSibling,E.isSameNode&&E.isSameNode(S)){E=X,S=K;continue e}O=a(S);var Y=S.nodeType,$=void 0;if(Y===E.nodeType&&(Y===V?(B?B!==O&&((U=y[B])?K===U?$=!1:(h.insertBefore(U,S),O?g(O):k(S,h,!0),S=U,O=a(S)):$=!1):O&&($=!1),$=$!==!1&&Q(S,E),$&&F(S,E)):(Y===Re||Y==Ne)&&($=!0,S.nodeValue!==E.nodeValue&&(S.nodeValue=E.nodeValue))),$){E=X,S=K;continue e}O?g(O):k(S,h,!0),S=K}if(B&&(U=y[B])&&Q(U,E))M||C(h,U),F(U,E);else{var ve=s(E);ve!==!1&&(ve&&(E=ve),E.actualize&&(E=E.actualize(h.ownerDocument||I)),C(h,E),G(E))}E=X,S=K}L(h,S,O);var Ce=Fe[h.nodeName];Ce&&Ce(h,m)}var b=t,T=b.nodeType,H=n.nodeType;if(!w){if(T===V)H===V?Q(t,n)||(u(t),b=St(t,wt(n.nodeName,n.namespaceURI))):b=n;else if(T===Re||T===Ne){if(H===T)return b.nodeValue!==n.nodeValue&&(b.nodeValue=n.nodeValue),b;b=n}}if(b===n)u(t);else{if(n.isSameNode&&n.isSameNode(b))return;if(F(b,n,w),_)for(var R=0,D=_.length;R<D;R++){var P=y[_[R]];P&&k(P,P.parentNode,!1)}}return!w&&b!==t&&t.parentNode&&(b.actualize&&(b=b.actualize(t.ownerDocument||I)),t.parentNode.replaceChild(b,t)),b}}var Lt=At(gt),Oe=Lt;var Ee=["text","textarea","number","email","password","search","tel","url","date","time","datetime-local","color","range"];var Z=class{constructor(e){this.logger=e;this.wrapperElement=null;this.focusableElements=[];this.lastFocusedElement=null;this.lastFocusedSelectionStart=null;this.lastFocusedSelectionEnd=null}attach(e){this.wrapperElement=e,e&&(this.updateFocusableElements(),this.setupFocusTracking())}reset(){this.wrapperElement=null,this.focusableElements=[],this.lastFocusedElement=null,this.lastFocusedSelectionStart=null,this.lastFocusedSelectionEnd=null}updateFocusableElements(){if(!this.wrapperElement)return;let n=`${Ee.map(r=>r==="textarea"?"textarea:not([disabled])":`input[type="${r}"]:not([disabled])`).join(", ")}, select:not([disabled]), button:not([disabled]), [contenteditable="true"], [tabindex]:not([tabindex="-1"])`;this.focusableElements=Array.from(this.wrapperElement.querySelectorAll(n))}setupFocusTracking(){if(!this.wrapperElement)return;let e=this.wrapperElement.getAttribute("data-lvt-id"),t=`__lvt_focus_tracker_${e}`,n=`__lvt_blur_tracker_${e}`,r=a=>{var l;let s=a.target;!s||!((l=this.wrapperElement)!=null&&l.contains(s))||(this.isTextualInput(s)||s instanceof HTMLSelectElement)&&(this.lastFocusedElement=s,this.logger.debug("[Focus] Tracked focus on:",s.tagName,s.id||s.getAttribute("name")),this.isTextualInput(s)&&(this.lastFocusedSelectionStart=s.selectionStart,this.lastFocusedSelectionEnd=s.selectionEnd))},i=a=>{var l;let s=a.target;!s||!((l=this.wrapperElement)!=null&&l.contains(s))||this.isTextualInput(s)&&s===this.lastFocusedElement&&(this.lastFocusedSelectionStart=s.selectionStart,this.lastFocusedSelectionEnd=s.selectionEnd,this.logger.debug("[Focus] Saved cursor on blur:",this.lastFocusedSelectionStart,"-",this.lastFocusedSelectionEnd))};document[t]&&document.removeEventListener("focus",document[t],!0),document[n]&&document.removeEventListener("blur",document[n],!0),document[t]=r,document[n]=i,document.addEventListener("focus",r,!0),document.addEventListener("blur",i,!0),this.logger.debug("[Focus] Focus tracking set up")}restoreFocusedElement(){var a,s,l;if(this.logger.debug("[Focus] restoreFocusedElement - lastFocusedElement:",(a=this.lastFocusedElement)==null?void 0:a.tagName,((s=this.lastFocusedElement)==null?void 0:s.id)||((l=this.lastFocusedElement)==null?void 0:l.getAttribute("name"))),!this.lastFocusedElement||!this.wrapperElement){this.logger.debug("[Focus] No element to restore");return}let e=this.getElementSelector(this.lastFocusedElement);if(this.logger.debug("[Focus] Selector for last focused:",e),!e){this.logger.debug("[Focus] Could not generate selector");return}let t=null;if(e.startsWith("data-focus-index-")){this.updateFocusableElements();let c=parseInt(e.replace("data-focus-index-",""),10);t=this.focusableElements[c]||null,this.logger.debug("[Focus] Found by index:",c,t==null?void 0:t.tagName)}else t=this.wrapperElement.querySelector(e),this.logger.debug("[Focus] Found by selector:",e,t==null?void 0:t.tagName);if(!t){this.logger.debug("[Focus] Element not found in updated DOM");return}let n=t.matches(":focus");if(this.logger.debug("[Focus] Already focused:",n),n){this.logger.debug("[Focus] Element retained focus \u2014 skipping restoration");return}let r=this.lastFocusedSelectionStart,i=this.lastFocusedSelectionEnd;t.focus(),this.logger.debug("[Focus] Restored focus"),this.isTextualInput(t)&&r!==null&&i!==null&&(t.setSelectionRange(r,i),this.logger.debug("[Focus] Restored cursor:",r,"-",i))}isTextualInput(e){return e instanceof HTMLTextAreaElement?!0:e instanceof HTMLInputElement?Ee.indexOf(e.type)>=0:!1}shouldSkipUpdate(e){return e!==document.activeElement||e.hasAttribute("data-lvt-force-update")?!1:!!(this.isTextualInput(e)||e instanceof HTMLSelectElement)}getLastFocusedElement(){return this.lastFocusedElement}getElementSelector(e){if(e.id)return`#${e.id}`;if(e.name)return`[name="${e.name}"]`;if(e.getAttribute("data-key"))return`[data-key="${e.getAttribute("data-key")}"]`;let t=this.focusableElements.indexOf(e);return t>=0?`data-focus-index-${t}`:null}};var He=["pending","success","error","done"],we=new Set(He),ee=new Set(["click-away"]),Se={reset:"reset",addclass:"addClass",removeclass:"removeClass",toggleclass:"toggleClass",setattr:"setAttr",toggleattr:"toggleAttr"};function Mt(o,e){let n=o.toLowerCase().match(/^lvt-el:(\w+):on:(.+)$/);if(n){let r=n[1],i=Se[r];if(!i)return null;let a=n[2];if(ee.has(a)||!we.has(a)&&!a.includes(":"))return null;let s=a.split(":"),l=s[s.length-1];if(!we.has(l))return null;let c=l,d=s.length>1?s.slice(0,-1).join(":"):void 0;return{action:i,lifecycle:c,actionName:d||void 0,param:e||void 0}}return null}function te(o){let e=o.getAttribute("data-lvt-target");return e?e.startsWith("#")?document.getElementById(e.slice(1))||o:e.startsWith("closest:")&&o.closest(e.slice(8))||o:o}function ne(o,e,t){switch(e){case"reset":o instanceof HTMLFormElement&&o.reset();break;case"addClass":if(t){let n=t.split(/\s+/).filter(Boolean);o.classList.add(...n)}break;case"removeClass":if(t){let n=t.split(/\s+/).filter(Boolean);o.classList.remove(...n)}break;case"toggleClass":t&&t.split(/\s+/).filter(Boolean).forEach(r=>o.classList.toggle(r));break;case"setAttr":if(t){let n=t.indexOf(":");if(n>0){let r=t.substring(0,n),i=t.substring(n+1);o.setAttribute(r,i)}}break;case"toggleAttr":t&&o.toggleAttribute(t);break}}function kt(o,e,t){return o.lifecycle!==e?!1:o.actionName?o.actionName===t:!0}function xt(o,e){let t=Object.keys(Se),n=[],r=e?e.replace(/([^\w-])/g,"\\$1"):void 0;for(let s of t)n.push(`[lvt-el\\:${s}\\:on\\:${o}]`),r&&n.push(`[lvt-el\\:${s}\\:on\\:${r}\\:${o}]`);let i=n.join(", "),a;try{a=document.querySelectorAll(i)}catch(s){let l=t.map(c=>`[lvt-el\\:${c}\\:on\\:${o}]`);try{a=document.querySelectorAll(l.join(", "))}catch(c){return}}a.forEach(s=>{Array.from(s.attributes).forEach(l=>{if(!l.name.startsWith("lvt-el:")||!l.name.includes(":on:"))return;let c=Mt(l.name,l.value);c&&kt(c,o,e)&&ne(te(s),c.action,c.param)})})}function re(o,e){for(let t of o.attributes){let n=t.name.match(/^lvt-el:(\w+):on:([a-z-]+)$/i);if(!n||n[2].toLowerCase()!==e)continue;let r=n[1].toLowerCase(),i=Se[r];i&&ne(te(o),i,t.value)}}function De(o){return!we.has(o)&&!ee.has(o)}function ie(){He.forEach(o=>{document.addEventListener(`lvt:${o}`,e=>{var r;let n=(r=e.detail)==null?void 0:r.action;xt(o,n)},!0)})}var We=new Set(["pending","success","error","done"]),Ue=new WeakSet;function Pe(o){let e=o.match(/^lvt-fx:\w+:on:(.+)$/i);if(!e)return{trigger:null};let t=e[1].split(":");return t.length===1?{trigger:t[0].toLowerCase()}:{trigger:t[t.length-1].toLowerCase(),actionName:t.slice(0,-1).join(":")}}function Be(o,e){let t=e||o,n="__lvtFxDirectListeners",r=(t[n]||[]).filter(a=>a.el.isConnected),i=a=>{var s;for(let l of a.attributes){if(!l.name.startsWith("lvt-fx:"))continue;let c=Pe(l.name);if(!c.trigger||We.has(c.trigger)||ee.has(c.trigger))continue;let d=`__lvt_fx_${l.name}`;if(a[d])continue;let p=(s=l.name.match(/^lvt-fx:(\w+)/i))==null?void 0:s[1];if(!p)continue;let u=l.name,f=()=>{if(!a.hasAttribute(u))return;let v=a.getAttribute(u)||"";j(a,p,v)};a.addEventListener(c.trigger,f),a[d]=f,r.push({el:a,event:c.trigger,handler:f,guardKey:d})}};i(o),o.querySelectorAll("*").forEach(i),t[n]=r}function Ke(o){let e="__lvtFxDirectListeners",t=o[e];t&&(t.forEach(({el:n,event:r,handler:i,guardKey:a})=>{n.removeEventListener(r,i),delete n[a]}),delete o[e])}function Ct(o,e,t){let n=r=>{var i;for(let a of r.attributes){if(!a.name.startsWith("lvt-fx:"))continue;let s=Pe(a.name);if(!s.trigger||!We.has(s.trigger)||s.trigger!==e||s.actionName&&s.actionName!==t)continue;let l=(i=a.name.match(/^lvt-fx:(\w+)/i))==null?void 0:i[1];l&&j(r,l,a.value)}};n(o),o.querySelectorAll("*").forEach(n)}function j(o,e,t){let n=getComputedStyle(o);switch(e){case"highlight":{if(o.__lvtHighlighting)break;o.__lvtHighlighting=!0;let r=parseInt(n.getPropertyValue("--lvt-highlight-duration").trim()||"500",10),i=n.getPropertyValue("--lvt-highlight-color").trim()||"#ffc107",a=o.style.backgroundColor,s=o.style.transition;o.style.transition=`background-color ${r}ms ease-out`,o.style.backgroundColor=i,setTimeout(()=>{if(!o.isConnected){o.style.backgroundColor=a,o.style.transition=s,o.__lvtHighlighting=!1;return}o.style.backgroundColor=a,setTimeout(()=>{o.isConnected&&(o.style.transition=s),o.__lvtHighlighting=!1},r)},50);break}case"animate":{if(Ue.has(o))break;Ue.add(o);let r=parseInt(n.getPropertyValue("--lvt-animate-duration").trim()||"500",10),i=t||"fade",a="";switch(i){case"fade":a=`lvt-fade-in ${r}ms ease-out`;break;case"slide":a=`lvt-slide-in ${r}ms ease-out`;break;case"scale":a=`lvt-scale-in ${r}ms ease-out`;break;default:console.warn(`Unknown lvt-fx:animate mode: ${i}`)}if(!a)break;o.style.animation=a,o.addEventListener("animationend",()=>{o.style.removeProperty("animation"),o.style.length===0&&o.removeAttribute("style")},{once:!0});break}case"scroll":{let r=n.getPropertyValue("--lvt-scroll-behavior").trim(),i=_t.has(r)?r:"auto",a=parseInt(n.getPropertyValue("--lvt-scroll-threshold").trim()||"100",10),s=t||"bottom";switch(s){case"bottom":o.scrollTo({top:o.scrollHeight,behavior:i});break;case"bottom-sticky":{o.scrollHeight-o.scrollTop-o.clientHeight<=a&&o.scrollTo({top:o.scrollHeight,behavior:i});break}case"top":o.scrollTo({top:0,behavior:i});break;case"preserve":break;default:console.warn(`Unknown lvt-fx:scroll mode: ${s}`)}break}default:console.warn(`Unknown lvt-fx effect: ${e}`)}}function Ve(o){let e="__lvtFxLifecycleSetup";if(o[e])return;o[e]=!0;let t=[];["pending","success","error","done"].forEach(r=>{let i=a=>{var c;let l=(c=a.detail)==null?void 0:c.action;Ct(o,r,l)};document.addEventListener(`lvt:${r}`,i,!0),t.push({event:`lvt:${r}`,handler:i})}),o.__lvtFxLifecycleListeners=t}function je(o){let e=o.__lvtFxLifecycleListeners;e&&(e.forEach(({event:t,handler:n})=>{document.removeEventListener(t,n,!0)}),delete o.__lvtFxLifecycleListeners),delete o.__lvtFxLifecycleSetup}var _t=new Set(["auto","smooth","instant"]);function qe(o){o.querySelectorAll("[lvt-fx\\:scroll]").forEach(e=>{let t=e.getAttribute("lvt-fx:scroll");t&&j(e,"scroll",t)})}function ze(o){o.querySelectorAll("[lvt-fx\\:highlight]").forEach(e=>{let t=e.getAttribute("lvt-fx:highlight");t&&j(e,"highlight",t)})}function Ge(o){o.querySelectorAll("[lvt-fx\\:animate]").forEach(e=>{let t=e.getAttribute("lvt-fx:animate");t&&j(e,"animate",t)}),Ft()}function Ft(){if(!document.getElementById("lvt-animate-styles")){let o=document.createElement("style");o.id="lvt-animate-styles",o.textContent=`
|
|
1
|
+
"use strict";var LiveTemplateClient=(()=>{var ye=Object.defineProperty;var at=Object.getOwnPropertyDescriptor;var lt=Object.getOwnPropertyNames;var ct=Object.prototype.hasOwnProperty;var dt=(o,e)=>{for(var t in e)ye(o,t,{get:e[t],enumerable:!0})},ut=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of lt(e))!ct.call(o,r)&&r!==t&&ye(o,r,{get:()=>e[r],enumerable:!(n=at(e,r))||n.enumerable});return o};var pt=o=>ut(ye({},"__esModule",{value:!0}),o);var Bt={};dt(Bt,{LiveTemplateClient:()=>me,compareHTML:()=>ot,loadAndApplyUpdate:()=>st,setupReactiveAttributeListeners:()=>ie});var _e=11;function gt(o,e){var t=e.attributes,n,r,i,a,s;if(!(e.nodeType===_e||o.nodeType===_e)){for(var l=t.length-1;l>=0;l--)n=t[l],r=n.name,i=n.namespaceURI,a=n.value,i?(r=n.localName||r,s=o.getAttributeNS(i,r),s!==a&&(n.prefix==="xmlns"&&(r=n.name),o.setAttributeNS(i,r,a))):(s=o.getAttribute(r),s!==a&&o.setAttribute(r,a));for(var c=o.attributes,d=c.length-1;d>=0;d--)n=c[d],r=n.name,i=n.namespaceURI,i?(r=n.localName||r,e.hasAttributeNS(i,r)||o.removeAttributeNS(i,r)):e.hasAttribute(r)||o.removeAttribute(r)}}var J,ft="http://www.w3.org/1999/xhtml",H=typeof document=="undefined"?void 0:document,ht=!!H&&"content"in H.createElement("template"),mt=!!H&&H.createRange&&"createContextualFragment"in H.createRange();function vt(o){var e=H.createElement("template");return e.innerHTML=o,e.content.childNodes[0]}function yt(o){J||(J=H.createRange(),J.selectNode(H.body));var e=J.createContextualFragment(o);return e.childNodes[0]}function bt(o){var e=H.createElement("body");return e.innerHTML=o,e.childNodes[0]}function Et(o){return o=o.trim(),ht?vt(o):mt?yt(o):bt(o)}function Q(o,e){var t=o.nodeName,n=e.nodeName,r,i;return t===n?!0:(r=t.charCodeAt(0),i=n.charCodeAt(0),r<=90&&i>=97?t===n.toUpperCase():i<=90&&r>=97?n===t.toUpperCase():!1)}function wt(o,e){return!e||e===ft?H.createElement(o):H.createElementNS(e,o)}function St(o,e){for(var t=o.firstChild;t;){var n=t.nextSibling;e.appendChild(t),t=n}return e}function be(o,e,t){o[t]!==e[t]&&(o[t]=e[t],o[t]?o.setAttribute(t,""):o.removeAttribute(t))}var Fe={OPTION:function(o,e){var t=o.parentNode;if(t){var n=t.nodeName.toUpperCase();n==="OPTGROUP"&&(t=t.parentNode,n=t&&t.nodeName.toUpperCase()),n==="SELECT"&&!t.hasAttribute("multiple")&&(o.hasAttribute("selected")&&!e.selected&&(o.setAttribute("selected","selected"),o.removeAttribute("selected")),t.selectedIndex=-1)}be(o,e,"selected")},INPUT:function(o,e){be(o,e,"checked"),be(o,e,"disabled"),o.value!==e.value&&(o.value=e.value),e.hasAttribute("value")||o.removeAttribute("value")},TEXTAREA:function(o,e){var t=e.value;o.value!==t&&(o.value=t);var n=o.firstChild;if(n){var r=n.nodeValue;if(r==t||!t&&r==o.placeholder)return;n.nodeValue=t}},SELECT:function(o,e){if(!e.hasAttribute("multiple")){for(var t=-1,n=0,r=o.firstChild,i,a;r;)if(a=r.nodeName&&r.nodeName.toUpperCase(),a==="OPTGROUP")i=r,r=i.firstChild,r||(r=i.nextSibling,i=null);else{if(a==="OPTION"){if(r.hasAttribute("selected")){t=n;break}n++}r=r.nextSibling,!r&&i&&(r=i.nextSibling,i=null)}o.selectedIndex=t}}},V=1,He=11,Re=3,Ie=8;function W(){}function Tt(o){if(o)return o.getAttribute&&o.getAttribute("id")||o.id}function At(o){return function(t,n,r){if(r||(r={}),typeof n=="string")if(t.nodeName==="#document"||t.nodeName==="HTML"||t.nodeName==="BODY"){var i=n;n=H.createElement("html"),n.innerHTML=i}else n=Et(n);else n.nodeType===He&&(n=n.firstElementChild);var a=r.getNodeKey||Tt,s=r.onBeforeNodeAdded||W,l=r.onNodeAdded||W,c=r.onBeforeElUpdated||W,d=r.onElUpdated||W,p=r.onBeforeNodeDiscarded||W,u=r.onNodeDiscarded||W,f=r.onBeforeElChildrenUpdated||W,v=r.skipFromChildren||W,C=r.addChild||function(h,m){return h.appendChild(m)},w=r.childrenOnly===!0,y=Object.create(null),_=[];function g(h){_.push(h)}function x(h,m){if(h.nodeType===V)for(var M=h.firstChild;M;){var E=void 0;m&&(E=a(M))?g(E):(u(M),M.firstChild&&x(M,m)),M=M.nextSibling}}function k(h,m,M){p(h)!==!1&&(m&&m.removeChild(h),u(h),x(h,M))}function I(h){if(h.nodeType===V||h.nodeType===He)for(var m=h.firstChild;m;){var M=a(m);M&&(y[M]=m),I(m),m=m.nextSibling}}I(t);function G(h){l(h);for(var m=h.firstChild;m;){var M=m.nextSibling,E=a(m);if(E){var S=y[E];S&&Q(m,S)?(m.parentNode.replaceChild(S,m),F(S,m)):G(m)}else G(m);m=M}}function L(h,m,M){for(;m;){var E=m.nextSibling;(M=a(m))?g(M):k(m,h,!0),m=E}}function F(h,m,M){var E=a(m);if(E&&delete y[E],!M){var S=c(h,m);if(S===!1||(S instanceof HTMLElement&&(h=S,I(h)),o(h,m),d(h),f(h,m)===!1))return}h.nodeName!=="TEXTAREA"?A(h,m):Fe.TEXTAREA(h,m)}function A(h,m){var M=v(h,m),E=m.firstChild,S=h.firstChild,B,N,K,X,U;e:for(;E;){for(X=E.nextSibling,B=a(E);!M&&S;){if(K=S.nextSibling,E.isSameNode&&E.isSameNode(S)){E=X,S=K;continue e}N=a(S);var Y=S.nodeType,$=void 0;if(Y===E.nodeType&&(Y===V?(B?B!==N&&((U=y[B])?K===U?$=!1:(h.insertBefore(U,S),N?g(N):k(S,h,!0),S=U,N=a(S)):$=!1):N&&($=!1),$=$!==!1&&Q(S,E),$&&F(S,E)):(Y===Re||Y==Ie)&&($=!0,S.nodeValue!==E.nodeValue&&(S.nodeValue=E.nodeValue))),$){E=X,S=K;continue e}N?g(N):k(S,h,!0),S=K}if(B&&(U=y[B])&&Q(U,E))M||C(h,U),F(U,E);else{var ve=s(E);ve!==!1&&(ve&&(E=ve),E.actualize&&(E=E.actualize(h.ownerDocument||H)),C(h,E),G(E))}E=X,S=K}L(h,S,N);var Ce=Fe[h.nodeName];Ce&&Ce(h,m)}var b=t,T=b.nodeType,O=n.nodeType;if(!w){if(T===V)O===V?Q(t,n)||(u(t),b=St(t,wt(n.nodeName,n.namespaceURI))):b=n;else if(T===Re||T===Ie){if(O===T)return b.nodeValue!==n.nodeValue&&(b.nodeValue=n.nodeValue),b;b=n}}if(b===n)u(t);else{if(n.isSameNode&&n.isSameNode(b))return;if(F(b,n,w),_)for(var R=0,D=_.length;R<D;R++){var P=y[_[R]];P&&k(P,P.parentNode,!1)}}return!w&&b!==t&&t.parentNode&&(b.actualize&&(b=b.actualize(t.ownerDocument||H)),t.parentNode.replaceChild(b,t)),b}}var Lt=At(gt),Ne=Lt;var Ee=["text","textarea","number","email","password","search","tel","url","date","time","datetime-local","color","range"];var Z=class{constructor(e){this.logger=e;this.wrapperElement=null;this.focusableElements=[];this.lastFocusedElement=null;this.lastFocusedSelectionStart=null;this.lastFocusedSelectionEnd=null}attach(e){this.wrapperElement=e,e&&(this.updateFocusableElements(),this.setupFocusTracking())}reset(){this.wrapperElement=null,this.focusableElements=[],this.lastFocusedElement=null,this.lastFocusedSelectionStart=null,this.lastFocusedSelectionEnd=null}updateFocusableElements(){if(!this.wrapperElement)return;let n=`${Ee.map(r=>r==="textarea"?"textarea:not([disabled])":`input[type="${r}"]:not([disabled])`).join(", ")}, select:not([disabled]), button:not([disabled]), [contenteditable="true"], [tabindex]:not([tabindex="-1"])`;this.focusableElements=Array.from(this.wrapperElement.querySelectorAll(n))}setupFocusTracking(){if(!this.wrapperElement)return;let e=this.wrapperElement.getAttribute("data-lvt-id"),t=`__lvt_focus_tracker_${e}`,n=`__lvt_blur_tracker_${e}`,r=a=>{var l;let s=a.target;!s||!((l=this.wrapperElement)!=null&&l.contains(s))||(this.isTextualInput(s)||s instanceof HTMLSelectElement)&&(this.lastFocusedElement=s,this.logger.debug("[Focus] Tracked focus on:",s.tagName,s.id||s.getAttribute("name")),this.isTextualInput(s)&&(this.lastFocusedSelectionStart=s.selectionStart,this.lastFocusedSelectionEnd=s.selectionEnd))},i=a=>{var l;let s=a.target;!s||!((l=this.wrapperElement)!=null&&l.contains(s))||this.isTextualInput(s)&&s===this.lastFocusedElement&&(this.lastFocusedSelectionStart=s.selectionStart,this.lastFocusedSelectionEnd=s.selectionEnd,this.logger.debug("[Focus] Saved cursor on blur:",this.lastFocusedSelectionStart,"-",this.lastFocusedSelectionEnd))};document[t]&&document.removeEventListener("focus",document[t],!0),document[n]&&document.removeEventListener("blur",document[n],!0),document[t]=r,document[n]=i,document.addEventListener("focus",r,!0),document.addEventListener("blur",i,!0),this.logger.debug("[Focus] Focus tracking set up")}restoreFocusedElement(){var a,s,l;if(this.logger.debug("[Focus] restoreFocusedElement - lastFocusedElement:",(a=this.lastFocusedElement)==null?void 0:a.tagName,((s=this.lastFocusedElement)==null?void 0:s.id)||((l=this.lastFocusedElement)==null?void 0:l.getAttribute("name"))),!this.lastFocusedElement||!this.wrapperElement){this.logger.debug("[Focus] No element to restore");return}let e=this.getElementSelector(this.lastFocusedElement);if(this.logger.debug("[Focus] Selector for last focused:",e),!e){this.logger.debug("[Focus] Could not generate selector");return}let t=null;if(e.startsWith("data-focus-index-")){this.updateFocusableElements();let c=parseInt(e.replace("data-focus-index-",""),10);t=this.focusableElements[c]||null,this.logger.debug("[Focus] Found by index:",c,t==null?void 0:t.tagName)}else t=this.wrapperElement.querySelector(e),this.logger.debug("[Focus] Found by selector:",e,t==null?void 0:t.tagName);if(!t){this.logger.debug("[Focus] Element not found in updated DOM");return}let n=t.matches(":focus");if(this.logger.debug("[Focus] Already focused:",n),n){this.logger.debug("[Focus] Element retained focus \u2014 skipping restoration");return}let r=this.lastFocusedSelectionStart,i=this.lastFocusedSelectionEnd;t.focus(),this.logger.debug("[Focus] Restored focus"),this.isTextualInput(t)&&r!==null&&i!==null&&(t.setSelectionRange(r,i),this.logger.debug("[Focus] Restored cursor:",r,"-",i))}isTextualInput(e){return e instanceof HTMLTextAreaElement?!0:e instanceof HTMLInputElement?Ee.indexOf(e.type)>=0:!1}shouldSkipUpdate(e){return e!==document.activeElement||e.hasAttribute("data-lvt-force-update")?!1:!!(this.isTextualInput(e)||e instanceof HTMLSelectElement)}getLastFocusedElement(){return this.lastFocusedElement}getElementSelector(e){if(e.id)return`#${e.id}`;if(e.name)return`[name="${e.name}"]`;if(e.getAttribute("data-key"))return`[data-key="${e.getAttribute("data-key")}"]`;let t=this.focusableElements.indexOf(e);return t>=0?`data-focus-index-${t}`:null}};var Oe=["pending","success","error","done"],we=new Set(Oe),ee=new Set(["click-away"]),Se={reset:"reset",addclass:"addClass",removeclass:"removeClass",toggleclass:"toggleClass",setattr:"setAttr",toggleattr:"toggleAttr"};function Mt(o,e){let n=o.toLowerCase().match(/^lvt-el:(\w+):on:(.+)$/);if(n){let r=n[1],i=Se[r];if(!i)return null;let a=n[2];if(ee.has(a)||!we.has(a)&&!a.includes(":"))return null;let s=a.split(":"),l=s[s.length-1];if(!we.has(l))return null;let c=l,d=s.length>1?s.slice(0,-1).join(":"):void 0;return{action:i,lifecycle:c,actionName:d||void 0,param:e||void 0}}return null}function te(o){let e=o.getAttribute("data-lvt-target");return e?e.startsWith("#")?document.getElementById(e.slice(1))||o:e.startsWith("closest:")&&o.closest(e.slice(8))||o:o}function ne(o,e,t){switch(e){case"reset":o instanceof HTMLFormElement&&o.reset();break;case"addClass":if(t){let n=t.split(/\s+/).filter(Boolean);o.classList.add(...n)}break;case"removeClass":if(t){let n=t.split(/\s+/).filter(Boolean);o.classList.remove(...n)}break;case"toggleClass":t&&t.split(/\s+/).filter(Boolean).forEach(r=>o.classList.toggle(r));break;case"setAttr":if(t){let n=t.indexOf(":");if(n>0){let r=t.substring(0,n),i=t.substring(n+1);o.setAttribute(r,i)}}break;case"toggleAttr":t&&o.toggleAttribute(t);break}}function kt(o,e,t){return o.lifecycle!==e?!1:o.actionName?o.actionName===t:!0}function xt(o,e){let t=Object.keys(Se),n=[],r=e?e.replace(/([^\w-])/g,"\\$1"):void 0;for(let s of t)n.push(`[lvt-el\\:${s}\\:on\\:${o}]`),r&&n.push(`[lvt-el\\:${s}\\:on\\:${r}\\:${o}]`);let i=n.join(", "),a;try{a=document.querySelectorAll(i)}catch(s){let l=t.map(c=>`[lvt-el\\:${c}\\:on\\:${o}]`);try{a=document.querySelectorAll(l.join(", "))}catch(c){return}}a.forEach(s=>{Array.from(s.attributes).forEach(l=>{if(!l.name.startsWith("lvt-el:")||!l.name.includes(":on:"))return;let c=Mt(l.name,l.value);c&&kt(c,o,e)&&ne(te(s),c.action,c.param)})})}function re(o,e){for(let t of o.attributes){let n=t.name.match(/^lvt-el:(\w+):on:([a-z-]+)$/i);if(!n||n[2].toLowerCase()!==e)continue;let r=n[1].toLowerCase(),i=Se[r];i&&ne(te(o),i,t.value)}}function De(o){return!we.has(o)&&!ee.has(o)}function ie(){Oe.forEach(o=>{document.addEventListener(`lvt:${o}`,e=>{var r;let n=(r=e.detail)==null?void 0:r.action;xt(o,n)},!0)})}var We=new Set(["pending","success","error","done"]),Ue=new WeakSet;function Pe(o){let e=o.match(/^lvt-fx:\w+:on:(.+)$/i);if(!e)return{trigger:null};let t=e[1].split(":");return t.length===1?{trigger:t[0].toLowerCase()}:{trigger:t[t.length-1].toLowerCase(),actionName:t.slice(0,-1).join(":")}}function Be(o,e){let t=e||o,n="__lvtFxDirectListeners",r=(t[n]||[]).filter(a=>a.el.isConnected),i=a=>{var s;for(let l of a.attributes){if(!l.name.startsWith("lvt-fx:"))continue;let c=Pe(l.name);if(!c.trigger||We.has(c.trigger)||ee.has(c.trigger))continue;let d=`__lvt_fx_${l.name}`;if(a[d])continue;let p=(s=l.name.match(/^lvt-fx:(\w+)/i))==null?void 0:s[1];if(!p)continue;let u=l.name,f=()=>{if(!a.hasAttribute(u))return;let v=a.getAttribute(u)||"";j(a,p,v)};a.addEventListener(c.trigger,f),a[d]=f,r.push({el:a,event:c.trigger,handler:f,guardKey:d})}};i(o),o.querySelectorAll("*").forEach(i),t[n]=r}function Ke(o){let e="__lvtFxDirectListeners",t=o[e];t&&(t.forEach(({el:n,event:r,handler:i,guardKey:a})=>{n.removeEventListener(r,i),delete n[a]}),delete o[e])}function Ct(o,e,t){let n=r=>{var i;for(let a of r.attributes){if(!a.name.startsWith("lvt-fx:"))continue;let s=Pe(a.name);if(!s.trigger||!We.has(s.trigger)||s.trigger!==e||s.actionName&&s.actionName!==t)continue;let l=(i=a.name.match(/^lvt-fx:(\w+)/i))==null?void 0:i[1];l&&j(r,l,a.value)}};n(o),o.querySelectorAll("*").forEach(n)}function j(o,e,t){let n=getComputedStyle(o);switch(e){case"highlight":{if(o.__lvtHighlighting)break;o.__lvtHighlighting=!0;let r=parseInt(n.getPropertyValue("--lvt-highlight-duration").trim()||"500",10),i=n.getPropertyValue("--lvt-highlight-color").trim()||"#ffc107",a=o.style.backgroundColor,s=o.style.transition;o.style.transition=`background-color ${r}ms ease-out`,o.style.backgroundColor=i,setTimeout(()=>{if(!o.isConnected){o.style.backgroundColor=a,o.style.transition=s,o.__lvtHighlighting=!1;return}o.style.backgroundColor=a,setTimeout(()=>{o.isConnected&&(o.style.transition=s),o.__lvtHighlighting=!1},r)},50);break}case"animate":{if(Ue.has(o))break;Ue.add(o);let r=parseInt(n.getPropertyValue("--lvt-animate-duration").trim()||"500",10),i=t||"fade",a="";switch(i){case"fade":a=`lvt-fade-in ${r}ms ease-out`;break;case"slide":a=`lvt-slide-in ${r}ms ease-out`;break;case"scale":a=`lvt-scale-in ${r}ms ease-out`;break;default:console.warn(`Unknown lvt-fx:animate mode: ${i}`)}if(!a)break;o.style.animation=a,o.addEventListener("animationend",()=>{o.style.removeProperty("animation"),o.style.length===0&&o.removeAttribute("style")},{once:!0});break}case"scroll":{let r=n.getPropertyValue("--lvt-scroll-behavior").trim(),i=_t.has(r)?r:"auto",a=parseInt(n.getPropertyValue("--lvt-scroll-threshold").trim()||"100",10),s=t||"bottom";switch(s){case"bottom":o.scrollTo({top:o.scrollHeight,behavior:i});break;case"bottom-sticky":{o.scrollHeight-o.scrollTop-o.clientHeight<=a&&o.scrollTo({top:o.scrollHeight,behavior:i});break}case"top":o.scrollTo({top:0,behavior:i});break;case"preserve":break;default:console.warn(`Unknown lvt-fx:scroll mode: ${s}`)}break}default:console.warn(`Unknown lvt-fx effect: ${e}`)}}function Ve(o){let e="__lvtFxLifecycleSetup";if(o[e])return;o[e]=!0;let t=[];["pending","success","error","done"].forEach(r=>{let i=a=>{var c;let l=(c=a.detail)==null?void 0:c.action;Ct(o,r,l)};document.addEventListener(`lvt:${r}`,i,!0),t.push({event:`lvt:${r}`,handler:i})}),o.__lvtFxLifecycleListeners=t}function je(o){let e=o.__lvtFxLifecycleListeners;e&&(e.forEach(({event:t,handler:n})=>{document.removeEventListener(t,n,!0)}),delete o.__lvtFxLifecycleListeners),delete o.__lvtFxLifecycleSetup}var _t=new Set(["auto","smooth","instant"]);function qe(o){o.querySelectorAll("[lvt-fx\\:scroll]").forEach(e=>{let t=e.getAttribute("lvt-fx:scroll");t&&j(e,"scroll",t)})}function ze(o){o.querySelectorAll("[lvt-fx\\:highlight]").forEach(e=>{let t=e.getAttribute("lvt-fx:highlight");t&&j(e,"highlight",t)})}function Ge(o){o.querySelectorAll("[lvt-fx\\:animate]").forEach(e=>{let t=e.getAttribute("lvt-fx:animate");t&&j(e,"animate",t)}),Ft()}function Ft(){if(!document.getElementById("lvt-animate-styles")){let o=document.createElement("style");o.id="lvt-animate-styles",o.textContent=`
|
|
2
2
|
@keyframes lvt-fade-in {
|
|
3
3
|
from { opacity: 0; }
|
|
4
4
|
to { opacity: 1; }
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
from { opacity: 0; transform: scale(0.95); }
|
|
12
12
|
to { opacity: 1; transform: scale(1); }
|
|
13
13
|
}
|
|
14
|
-
`,document.head.appendChild(o)}}var $e="__lvtPendingProcessed";function Xe(o){o.querySelectorAll("[data-toast-trigger]").forEach(e=>{let t=e.getAttribute("data-pending");if(!t||e[$e]===t)return;e[$e]=t;let n;try{n=JSON.parse(t)}catch(a){return}if(!Array.isArray(n)||!n.length)return;let r=e.getAttribute("data-position")||"top-right",i=It(r);n.forEach(a=>{let s=Nt(a);i.appendChild(s),typeof a.dismissMS=="number"&&a.dismissMS>0&&setTimeout(()=>s.remove(),a.dismissMS)})})}function Ye(){let o="__lvt_toast_click_outside",e=document[o];e&&document.removeEventListener("click",e);let t=n=>{let r=document.querySelector("[data-lvt-toast-stack]");!r||r.contains(n.target)||r.querySelectorAll("[data-lvt-toast-item]").forEach(i=>i.remove())};document[o]=t,document.addEventListener("click",t)}function It(o){let e=document.querySelector("[data-lvt-toast-stack]");return e||(e=document.createElement("div"),e.setAttribute("data-lvt-toast-stack",""),e.setAttribute("aria-live","polite"),Rt(e,o),document.body.appendChild(e)),e}function Rt(o,e){let t=o.style;switch(e){case"top-left":t.top="1rem",t.left="1rem";break;case"top-center":t.top="1rem",t.left="50%",t.transform="translateX(-50%)";break;case"bottom-right":t.bottom="1rem",t.right="1rem";break;case"bottom-left":t.bottom="1rem",t.left="1rem";break;case"bottom-center":t.bottom="1rem",t.left="50%",t.transform="translateX(-50%)";break;default:t.top="1rem",t.right="1rem";break}}function Nt(o){let e=document.createElement("div");e.setAttribute("role","alert"),e.setAttribute("data-lvt-toast-item",o.id),o.type&&e.setAttribute("data-type",o.type);let t=document.createElement("div");if(t.setAttribute("data-lvt-toast-content",""),o.title){let n=document.createElement("strong");n.textContent=o.title,t.appendChild(n)}if(o.body){let n=document.createElement("p");n.textContent=o.body,t.appendChild(n)}if(e.appendChild(t),o.dismissible){let n=document.createElement("button");n.type="button",n.setAttribute("aria-label","Dismiss"),n.textContent="\xD7",n.addEventListener("click",()=>e.remove()),e.appendChild(n)}return e}function q(o,e){let t=null;return function(...r){let i=this;t!==null&&clearTimeout(t),t=window.setTimeout(()=>{o.apply(i,r)},e)}}function Te(o,e){let t=!1;return function(...r){let i=this;t||(o.apply(i,r),t=!0,setTimeout(()=>{t=!1},e))}}function Ae(o,e){let t=o.replace(/:/g,"\\:");if(e===void 0)return`[${t}]`;let n=e.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`[${t}="${n}"]`}var Qe={reset:"reset",addclass:"addClass",removeclass:"removeClass",toggleclass:"toggleClass",setattr:"setAttr",toggleattr:"toggleAttr"},Ot=Object.keys(Qe),Ht=new Set(["mouseenter","mouseleave","focus","blur"]),Je=["click","submit","change","input","search","keydown","keyup","focus","blur","mouseenter","mouseleave"],se=class{constructor(e,t){this.context=e;this.logger=t}teardownForWrapper(e){if(e)for(let t of Je){let n=`__lvt_delegated_${t}_${e}`,r=document[n];r&&(document.removeEventListener(t,r,!1),delete document[n])}}extractButtonData(e,t){e.value&&(t.value=this.context.parseValue(e.value)),Array.from(e.attributes).forEach(n=>{if(n.name.startsWith("data-")&&n.name!=="data-key"){let r=n.name.slice(5);t[r]=this.context.parseValue(n.value)}})}setupEventDelegation(){let e=this.context.getWrapperElement();if(!e)return;let t=Je,n=e.getAttribute("data-lvt-id"),r=this.context.getRateLimitedHandlers();t.forEach(i=>{let a=`__lvt_delegated_${i}_${n}`,s=document[a];s&&document.removeEventListener(i,s,!1);let l=c=>{var C;let d=this.context.getWrapperElement();if(!d)return;let p=c.target;if(this.logger.debug("Event listener triggered:",i,c.target),!p)return;let u=p,f=!1;for(;u;){if(u===d){f=!0;break}u=u.parentElement}if(!f)return;let v=`lvt-on:${i}`;for(u=p;u&&u!==d.parentElement;){let w=u.getAttribute(v),y=u,_=!1;if(!w&&i==="submit"&&u instanceof HTMLFormElement){let g=u.getAttribute("lvt-persist");g&&(w=`persist:${g}`,y=u)}if(!w&&i==="click"){let g=u instanceof HTMLButtonElement?u:null;g&&g.name&&!g.disabled&&g.type!=="reset"&&g.form===null&&!g.hasAttribute("commandfor")&&(w=g.name,y=g,_=!0)}if(!w&&i==="submit"&&u instanceof HTMLFormElement&&!u.hasAttribute("lvt-form:no-intercept")){let g=u.getAttribute("lvt-form:action"),x=c.submitter;g?w=g:x instanceof HTMLButtonElement&&x.name?w=x.name:u.getAttribute("name")?w=u.getAttribute("name"):w="submit",y=u,x&&(u.__lvtSubmitter=x);let k=u.closest("dialog");k&&((C=u.getAttribute("method"))==null?void 0:C.toLowerCase())==="dialog"&&(u.__lvtCloseDialog=k)}if(w!=null&&y){if(i==="submit"&&c.preventDefault(),(i==="keydown"||i==="keyup")&&y.hasAttribute("lvt-key")){let L=y.getAttribute("lvt-key");if(L&&c.key!==L){u=u.parentElement;continue}}let g=y,x=()=>{this.logger.debug("handleAction called",{action:w,eventType:i,targetElement:g});let L={action:w,data:{}};if(g instanceof HTMLFormElement){this.logger.debug("Processing form element");let A=new FormData(g),b=Array.from(g.querySelectorAll('input[type="checkbox"][name]')),T=new Set(b.map(h=>h.name));T.forEach(h=>{L.data[h]=!1});let H=new Set(Array.from(g.querySelectorAll('input[type="password"][name]')).map(h=>h.name)),R=g.__lvtSubmitter,D=R==null?void 0:R.name;A.forEach((h,m)=>{h instanceof File||D&&m===D||(T.has(m)?(L.data[m]=!0,this.logger.debug("Converted checkbox",m,"to true")):H.has(m)?L.data[m]=h:L.data[m]=this.context.parseValue(h))});let P=g.__lvtSubmitter;P&&(this.extractButtonData(P,L.data),delete g.__lvtSubmitter),this.logger.debug("Form data collected:",L.data)}else if(i==="change"||i==="input"||i==="search"){if(g instanceof HTMLInputElement){let A=g.name||"value";L.data[A]=this.context.parseValue(g.value)}else if(g instanceof HTMLSelectElement){let A=g.name||"value";L.data[A]=this.context.parseValue(g.value)}else if(g instanceof HTMLTextAreaElement){let A=g.name||"value";L.data[A]=this.context.parseValue(g.value)}}_&&this.extractButtonData(y,L.data),!(g instanceof HTMLFormElement)&&!_&&Array.from(y.attributes).forEach(A=>{if(A.name.startsWith("data-")&&A.name!=="data-key"&&A.name!=="data-lvt-id"){let b=A.name.slice(5);L.data[b]=this.context.parseValue(A.value)}});let F=null;if(i==="submit"&&g instanceof HTMLFormElement){let A=g.querySelectorAll('input[type="file"]:not([lvt-upload])');if(Array.from(A).some(T=>T.files&&T.files.length>0)){let T=c.submitter;F=new FormData(g),T!=null&&T.name&&F.set(T.name,T.value),F.set("lvt-action",w)}}if(i==="submit"&&g instanceof HTMLFormElement){let b=c.submitter,T=null;b&&b.hasAttribute("lvt-form:disable-with")&&(T=b.textContent,b.disabled=!0,b.textContent=b.getAttribute("lvt-form:disable-with"),this.logger.debug("Disabled submit button")),this.context.setActiveSubmission(g,b||null,T),g.querySelectorAll('input[type="file"][lvt-upload]').forEach(R=>{let D=R.getAttribute("lvt-upload");D&&(this.logger.debug("Triggering pending uploads for:",D),this.context.triggerPendingUploads(D))}),g.dispatchEvent(new CustomEvent("lvt:pending",{detail:L})),this.logger.debug("Emitted lvt:pending event")}if(this.logger.debug("About to send message:",L),this.logger.debug("WebSocket state:",this.context.getWebSocketReadyState()),F!==null){this.logger.debug("Tier 1 file upload detected, using HTTP fetch"),this.context.sendHTTPMultipart(g,w,F);return}if(this.context.send(L),this.logger.debug("send() called"),g instanceof HTMLFormElement){let A=g.__lvtCloseDialog;A&&(A.close(),delete g.__lvtCloseDialog)}},k=y.getAttribute("lvt-mod:throttle"),N=y.getAttribute("lvt-mod:debounce");if((k||N)&&i!=="search"){r.has(y)||r.set(y,new Map);let L=r.get(y),F=`${i}:${w}`,A=`__lvt_callback_${F}`,b=y;b[A]||(b[A]={current:x}),b[A].current=x;let T=L.get(F);if(!T){let H=()=>b[A].current();if(k){let R=parseInt(k,10);T=Te(H,R)}else if(N){let R=parseInt(N,10);T=q(H,R)}T&&L.set(F,T)}T&&T()}else x();return}u=u.parentElement}};document[a]=l,document.addEventListener(i,l,!1),this.logger.debug("Registered event listener:",i,"with key:",a)})}setupWindowEventDelegation(){let e=this.context.getWrapperElement();if(!e)return;let t=["keydown","keyup","scroll","resize","focus","blur"],n=e.getAttribute("data-lvt-id"),r=this.context.getRateLimitedHandlers();t.forEach(i=>{let a=`__lvt_window_${i}_${n}`,s=window[a];s&&window.removeEventListener(i,s);let l=c=>{let d=this.context.getWrapperElement();if(!d)return;let p=`lvt-on:window:${i}`;d.querySelectorAll(Ae(p)).forEach(f=>{let v=f.getAttribute(p);if(!v)return;if((i==="keydown"||i==="keyup")&&f.hasAttribute("lvt-key")){let g=f.getAttribute("lvt-key");if(g&&c.key!==g)return}let C={action:v,data:{}};Array.from(f.attributes).forEach(g=>{if(g.name.startsWith("data-")&&g.name!=="data-key"&&g.name!=="data-lvt-id"){let x=g.name.slice(5);C.data[x]=this.context.parseValue(g.value)}});let w=f.getAttribute("lvt-mod:throttle"),y=f.getAttribute("lvt-mod:debounce"),_=()=>this.context.send(C);if(w||y){r.has(f)||r.set(f,new Map);let g=r.get(f),x=`window-${i}:${v}`,k=g.get(x);if(!k){if(w){let N=parseInt(w,10);k=Te(_,N)}else if(y){let N=parseInt(y,10);k=q(_,N)}k&&g.set(x,k)}k&&k()}else _()})};window[a]=l,window.addEventListener(i,l)})}setupClickAwayDelegation(){let e=this.context.getWrapperElement();if(!e)return;let n=`__lvt_click_away_${e.getAttribute("data-lvt-id")}`,r=document[n];r&&document.removeEventListener("click",r);let i=a=>{let s=this.context.getWrapperElement();if(!s)return;let l=a.target,c=Ot.map(p=>Ae(`lvt-el:${p}:on:click-away`)).join(", ");s.querySelectorAll(c).forEach(p=>{p.contains(l)||Array.from(p.attributes).forEach(u=>{if(!u.name.includes(":on:click-away"))return;let f=u.name.match(/^lvt-el:(\w+):on:click-away$/);if(!f)return;let v=Qe[f[1].toLowerCase()];v&&ne(te(p),v,u.value)})})};document[n]=i,document.addEventListener("click",i)}setupDOMEventTriggerDelegation(e){let t=this.context.getWrapperElement();if(!t)return;let n=t.getAttribute("data-lvt-id");if(!n)return;let r=`__lvt_el_delegated_${n}`,i=t[r]||new Set,a=`__lvt_el_listeners_${n}`,s=(t[a]||[]).filter(d=>d.el.isConnected),l=e||t,c=d=>{let p=new Set;for(let u of d.attributes){if(!u.name.startsWith("lvt-el:"))continue;let f=u.name.match(/^lvt-el:\w+:on:([a-z-]+)$/i);if(!f)continue;let v=f[1].toLowerCase();De(v)&&p.add(v)}for(let u of p)if(Ht.has(u)){let f=`__lvt_el_${u}`;if(d[f])continue;let v=()=>re(d,u);d.addEventListener(u,v),d[f]=v,s.push({el:d,event:u,handler:v,guardKey:f})}else if(!i.has(u)){let f=u.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),v=new RegExp(`^lvt-el:\\w+:on:${f}$`,"i"),C=w=>{let y=w.target;for(;y&&y!==t;){let _=!1;for(let g of y.attributes)if(v.test(g.name)){_=!0;break}if(_){re(y,u);return}y=y.parentElement}y===t&&re(t,u)};t.addEventListener(u,C),i.add(u),s.push({el:t,event:u,handler:C})}};c(l),l.querySelectorAll("*").forEach(c),t[a]=s,t[r]=i}teardownDOMEventTriggerDelegation(){let e=this.context.getWrapperElement();if(!e)return;let t=e.getAttribute("data-lvt-id");if(!t)return;let n=`__lvt_el_listeners_${t}`,r=e[n];r&&(r.forEach(({el:a,event:s,handler:l,guardKey:c})=>{a.removeEventListener(s,l),c&&delete a[c]}),delete e[n]);let i=`__lvt_el_delegated_${t}`;delete e[i]}setupFocusTrapDelegation(){let e=this.context.getWrapperElement();if(!e)return;let n=`__lvt_focus_trap_${e.getAttribute("data-lvt-id")}`,r=document[n];r&&document.removeEventListener("keydown",r);let i=s=>{let l=["a[href]:not([disabled])","button:not([disabled])","textarea:not([disabled])",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])",'[tabindex]:not([tabindex="-1"]):not([disabled])','[contenteditable="true"]'].join(", ");return Array.from(s.querySelectorAll(l)).filter(c=>{let d=c,p=window.getComputedStyle(d),u=p.display!=="none",f=p.visibility!=="hidden",v=d.offsetParent!==null||p.position==="fixed"||p.position==="absolute"||typeof process!="undefined"&&!1;return u&&f&&v})},a=s=>{if(s.key!=="Tab")return;let l=this.context.getWrapperElement();if(!l)return;let c=l.querySelectorAll("[lvt-focus-trap]"),d=null;if(c.forEach(v=>{v.contains(document.activeElement)&&(!d||v.contains(d))&&(d=v)}),d||c.forEach(v=>{let C=v,w=window.getComputedStyle(C);w.display!=="none"&&w.visibility!=="hidden"&&(d=v)}),!d)return;let p=i(d);if(p.length===0)return;let u=p[0],f=p[p.length-1];s.shiftKey?document.activeElement===u&&(s.preventDefault(),f.focus()):document.activeElement===f&&(s.preventDefault(),u.focus())};document[n]=a,document.addEventListener("keydown",a),this.logger.debug("Focus trap delegation set up")}setupAutofocusDelegation(){let e=this.context.getWrapperElement();if(!e)return;let n=`__lvt_autofocus_observer_${e.getAttribute("data-lvt-id")}`,r=e[n];r&&r.disconnect();let i=()=>{let s=this.context.getWrapperElement();if(!s)return;s.querySelectorAll("[lvt-autofocus]").forEach(c=>{let d=c,p=window.getComputedStyle(d),u=p.display!=="none",f=p.visibility!=="hidden",v=d.offsetParent!==null||p.position==="fixed"||p.position==="absolute"||d.tagName==="BODY"||typeof process!="undefined"&&!1,C=u&&f&&v,w=d.getAttribute("data-lvt-autofocused")==="true";C&&!w?(d.setAttribute("data-lvt-autofocused","true"),requestAnimationFrame(()=>{d.focus(),this.logger.debug("Autofocused element:",d.tagName,d.id||d.getAttribute("name"))})):!C&&w&&d.removeAttribute("data-lvt-autofocused")})};i();let a=new MutationObserver(s=>{let l=!1;s.forEach(c=>{c.type==="childList"&&c.addedNodes.length>0&&c.addedNodes.forEach(d=>{d instanceof Element&&(d.hasAttribute("lvt-autofocus")||d.querySelector("[lvt-autofocus]"))&&(l=!0)}),c.type==="attributes"&&(c.target.hasAttribute("lvt-autofocus")||c.attributeName==="hidden"||c.attributeName==="style"||c.attributeName==="class")&&(l=!0)}),l&&i()});a.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["hidden","style","class","lvt-autofocus"]}),e[n]=a,this.logger.debug("Autofocus delegation set up")}};var oe=class{constructor(e,t){this.context=e;this.logger=t;this.popstateListener=null;this.abortController=null}teardownForWrapper(e){var r;if((r=this.abortController)==null||r.abort(),this.abortController=null,!e)return;let t=`__lvt_link_intercept_${e}`,n=document[t];n&&(document.removeEventListener("click",n,!1),delete document[t])}setup(e){let n=`__lvt_link_intercept_${e.getAttribute("data-lvt-id")}`,r=document[n];r&&document.removeEventListener("click",r);let i=a=>{var c;let s=(c=a.target)==null?void 0:c.closest("a[href]");if(!s)return;let l=this.context.getWrapperElement();!l||!l.contains(s)||this.shouldSkip(s)||(a.preventDefault(),this.navigate(s.href))};document.addEventListener("click",i),document[n]=i,this.popstateListener||(this.popstateListener=()=>{this.navigate(window.location.href,!1)},window.addEventListener("popstate",this.popstateListener))}shouldSkip(e){if(e.origin!==window.location.origin||e.target&&e.target!=="_self"||e.hasAttribute("download")||e.hasAttribute("lvt-nav:no-intercept")||e.pathname===window.location.pathname&&e.hash)return!0;let t=e.protocol;return t!=="http:"&&t!=="https:"}async navigate(e,t=!0){var i,a,s;let n=new URL(e,window.location.origin);if(n.origin===window.location.origin&&n.pathname===window.location.pathname){if(n.search===window.location.search){(i=this.abortController)==null||i.abort(),this.abortController=null;return}if(this.context.canSendNavigate()&&((a=this.abortController)==null||a.abort(),this.abortController=null,this.context.sendNavigate(e))){t&&window.history.pushState(null,"",e);return}}(s=this.abortController)==null||s.abort(),this.abortController=new AbortController;try{let l=await fetch(e,{credentials:"include",headers:{Accept:"text/html"},signal:this.abortController.signal});if(!l.ok){window.location.href=e;return}let c=await l.text();t&&window.history.pushState(null,"",e),this.context.handleNavigationResponse(c)}catch(l){if(l instanceof DOMException&&l.name==="AbortError")return;window.location.href=e}}};var z=class z{constructor(e,t){this.context=e;this.logger=t;this.infiniteScrollObserver=null;this.mutationObserver=null;this.observedSentinel=null;this.updatedListener=null;this.updatedListenerWrapper=null;this.loadMorePending=!1;this.loadMoreTimeoutId=null}setupInfiniteScrollObserver(){let e=this.context.getWrapperElement();if(!e)return;this.ensureUpdatedListener(e);let t=document.getElementById("scroll-sentinel");if(!t){this.infiniteScrollObserver&&(this.infiniteScrollObserver.disconnect(),this.infiniteScrollObserver=null,this.observedSentinel=null),this.releaseLoadMore();return}this.infiniteScrollObserver&&this.observedSentinel===t||(this.infiniteScrollObserver&&this.infiniteScrollObserver.disconnect(),this.infiniteScrollObserver=new IntersectionObserver(n=>{if(n[0].isIntersecting){if(this.loadMorePending){this.logger.debug("Sentinel visible but load_more already pending, skipping");return}this.loadMorePending=!0,this.armLoadMoreTimeout(),this.logger.debug("Sentinel visible, sending load_more action"),this.context.send({action:"load_more"})}},{rootMargin:"200px"}),this.infiniteScrollObserver.observe(t),this.observedSentinel=t,this.logger.debug("Observer set up successfully"))}ensureUpdatedListener(e){this.updatedListener&&this.updatedListenerWrapper===e||(this.updatedListener&&this.updatedListenerWrapper&&this.updatedListenerWrapper.removeEventListener("lvt:updated",this.updatedListener),this.updatedListener=t=>{let n=t.detail;(n==null?void 0:n.action)==="load_more"&&(this.releaseLoadMore(),this.observedSentinel=null,this.setupInfiniteScrollObserver())},e.addEventListener("lvt:updated",this.updatedListener),this.updatedListenerWrapper=e)}armLoadMoreTimeout(){this.clearLoadMoreTimeout(),this.loadMoreTimeoutId=window.setTimeout(()=>{this.logger.warn(`load_more response not received within ${z.LOAD_MORE_TIMEOUT_MS}ms; releasing throttle`),this.loadMoreTimeoutId=null,this.loadMorePending=!1,this.observedSentinel=null,this.setupInfiniteScrollObserver()},z.LOAD_MORE_TIMEOUT_MS)}releaseLoadMore(){this.loadMorePending=!1,this.clearLoadMoreTimeout()}clearLoadMoreTimeout(){this.loadMoreTimeoutId!==null&&(clearTimeout(this.loadMoreTimeoutId),this.loadMoreTimeoutId=null)}setupInfiniteScrollMutationObserver(){let e=this.context.getWrapperElement();e&&(this.mutationObserver&&this.mutationObserver.disconnect(),this.mutationObserver=new MutationObserver(()=>{this.setupInfiniteScrollObserver()}),this.mutationObserver.observe(e,{childList:!0,subtree:!0}),this.logger.debug("MutationObserver set up successfully"))}teardown(){this.infiniteScrollObserver&&(this.infiniteScrollObserver.disconnect(),this.infiniteScrollObserver=null),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null),this.updatedListener&&this.updatedListenerWrapper&&this.updatedListenerWrapper.removeEventListener("lvt:updated",this.updatedListener),this.updatedListener=null,this.updatedListenerWrapper=null,this.observedSentinel=null,this.releaseLoadMore()}};z.LOAD_MORE_TIMEOUT_MS=3e4;var ae=z;var le=class{constructor(){this.bar=null}show(){if(this.bar)return;let e=document.createElement("div");if(e.style.cssText=`
|
|
14
|
+
`,document.head.appendChild(o)}}var $e="__lvtPendingProcessed";function Xe(o){o.querySelectorAll("[data-toast-trigger]").forEach(e=>{let t=e.getAttribute("data-pending");if(!t||e[$e]===t)return;e[$e]=t;let n;try{n=JSON.parse(t)}catch(a){return}if(!Array.isArray(n)||!n.length)return;let r=e.getAttribute("data-position")||"top-right",i=Ht(r);n.forEach(a=>{let s=It(a);i.appendChild(s),typeof a.dismissMS=="number"&&a.dismissMS>0&&setTimeout(()=>s.remove(),a.dismissMS)})})}function Ye(){let o="__lvt_toast_click_outside",e=document[o];e&&document.removeEventListener("click",e);let t=n=>{let r=document.querySelector("[data-lvt-toast-stack]");!r||r.contains(n.target)||r.querySelectorAll("[data-lvt-toast-item]").forEach(i=>i.remove())};document[o]=t,document.addEventListener("click",t)}function Ht(o){let e=document.querySelector("[data-lvt-toast-stack]");return e||(e=document.createElement("div"),e.setAttribute("data-lvt-toast-stack",""),e.setAttribute("aria-live","polite"),Rt(e,o),document.body.appendChild(e)),e}function Rt(o,e){let t=o.style;switch(e){case"top-left":t.top="1rem",t.left="1rem";break;case"top-center":t.top="1rem",t.left="50%",t.transform="translateX(-50%)";break;case"bottom-right":t.bottom="1rem",t.right="1rem";break;case"bottom-left":t.bottom="1rem",t.left="1rem";break;case"bottom-center":t.bottom="1rem",t.left="50%",t.transform="translateX(-50%)";break;default:t.top="1rem",t.right="1rem";break}}function It(o){let e=document.createElement("div");e.setAttribute("role","alert"),e.setAttribute("data-lvt-toast-item",o.id),o.type&&e.setAttribute("data-type",o.type);let t=document.createElement("div");if(t.setAttribute("data-lvt-toast-content",""),o.title){let n=document.createElement("strong");n.textContent=o.title,t.appendChild(n)}if(o.body){let n=document.createElement("p");n.textContent=o.body,t.appendChild(n)}if(e.appendChild(t),o.dismissible){let n=document.createElement("button");n.type="button",n.setAttribute("aria-label","Dismiss"),n.textContent="\xD7",n.addEventListener("click",()=>e.remove()),e.appendChild(n)}return e}function q(o,e){let t=null;return function(...r){let i=this;t!==null&&clearTimeout(t),t=window.setTimeout(()=>{o.apply(i,r)},e)}}function Te(o,e){let t=!1;return function(...r){let i=this;t||(o.apply(i,r),t=!0,setTimeout(()=>{t=!1},e))}}function Ae(o,e){let t=o.replace(/:/g,"\\:");if(e===void 0)return`[${t}]`;let n=e.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`[${t}="${n}"]`}var Qe={reset:"reset",addclass:"addClass",removeclass:"removeClass",toggleclass:"toggleClass",setattr:"setAttr",toggleattr:"toggleAttr"},Nt=Object.keys(Qe),Ot=new Set(["mouseenter","mouseleave","focus","blur"]),Je=["click","submit","change","input","search","keydown","keyup","focus","blur","mouseenter","mouseleave"],se=class{constructor(e,t){this.context=e;this.logger=t}teardownForWrapper(e){if(e)for(let t of Je){let n=`__lvt_delegated_${t}_${e}`,r=document[n];r&&(document.removeEventListener(t,r,!1),delete document[n])}}extractButtonData(e,t){e.value&&(t.value=this.context.parseValue(e.value)),Array.from(e.attributes).forEach(n=>{if(n.name.startsWith("data-")&&n.name!=="data-key"){let r=n.name.slice(5);t[r]=this.context.parseValue(n.value)}})}setupEventDelegation(){let e=this.context.getWrapperElement();if(!e)return;let t=Je,n=e.getAttribute("data-lvt-id"),r=this.context.getRateLimitedHandlers();t.forEach(i=>{let a=`__lvt_delegated_${i}_${n}`,s=document[a];s&&document.removeEventListener(i,s,!1);let l=c=>{var C;let d=this.context.getWrapperElement();if(!d)return;let p=c.target;if(this.logger.debug("Event listener triggered:",i,c.target),!p)return;let u=p,f=!1;for(;u;){if(u===d){f=!0;break}u=u.parentElement}if(!f)return;let v=`lvt-on:${i}`;for(u=p;u&&u!==d.parentElement;){let w=u.getAttribute(v),y=u,_=!1;if(!w&&i==="submit"&&u instanceof HTMLFormElement){let g=u.getAttribute("lvt-persist");g&&(w=`persist:${g}`,y=u)}if(!w&&i==="click"){let g=u instanceof HTMLButtonElement?u:null;g&&g.name&&!g.disabled&&g.type!=="reset"&&g.form===null&&!g.hasAttribute("commandfor")&&(w=g.name,y=g,_=!0)}if(!w&&i==="submit"&&u instanceof HTMLFormElement&&!u.hasAttribute("lvt-form:no-intercept")){let g=u.getAttribute("lvt-form:action"),x=c.submitter;g?w=g:x instanceof HTMLButtonElement&&x.name?w=x.name:u.getAttribute("name")?w=u.getAttribute("name"):w="submit",y=u,x&&(u.__lvtSubmitter=x);let k=u.closest("dialog");k&&((C=u.getAttribute("method"))==null?void 0:C.toLowerCase())==="dialog"&&(u.__lvtCloseDialog=k)}if(w!=null&&y){if(i==="submit"&&c.preventDefault(),(i==="keydown"||i==="keyup")&&y.hasAttribute("lvt-key")){let L=y.getAttribute("lvt-key");if(L&&c.key!==L){u=u.parentElement;continue}}let g=y,x=()=>{this.logger.debug("handleAction called",{action:w,eventType:i,targetElement:g});let L={action:w,data:{}};if(g instanceof HTMLFormElement){this.logger.debug("Processing form element");let A=new FormData(g),b=Array.from(g.querySelectorAll('input[type="checkbox"][name]')),T=new Set(b.map(h=>h.name));T.forEach(h=>{L.data[h]=!1});let O=new Set(Array.from(g.querySelectorAll('input[type="password"][name]')).map(h=>h.name)),R=g.__lvtSubmitter,D=R==null?void 0:R.name;A.forEach((h,m)=>{h instanceof File||D&&m===D||(T.has(m)?(L.data[m]=!0,this.logger.debug("Converted checkbox",m,"to true")):O.has(m)?L.data[m]=h:L.data[m]=this.context.parseValue(h))});let P=g.__lvtSubmitter;P&&(this.extractButtonData(P,L.data),delete g.__lvtSubmitter),this.logger.debug("Form data collected:",L.data)}else if(i==="change"||i==="input"||i==="search"){if(g instanceof HTMLInputElement){let A=g.name||"value";L.data[A]=this.context.parseValue(g.value)}else if(g instanceof HTMLSelectElement){let A=g.name||"value";L.data[A]=this.context.parseValue(g.value)}else if(g instanceof HTMLTextAreaElement){let A=g.name||"value";L.data[A]=this.context.parseValue(g.value)}}_&&this.extractButtonData(y,L.data),!(g instanceof HTMLFormElement)&&!_&&Array.from(y.attributes).forEach(A=>{if(A.name.startsWith("data-")&&A.name!=="data-key"&&A.name!=="data-lvt-id"){let b=A.name.slice(5);L.data[b]=this.context.parseValue(A.value)}});let F=null;if(i==="submit"&&g instanceof HTMLFormElement){let A=g.querySelectorAll('input[type="file"]:not([lvt-upload])');if(Array.from(A).some(T=>T.files&&T.files.length>0)){let T=c.submitter;F=new FormData(g),T!=null&&T.name&&F.set(T.name,T.value),F.set("lvt-action",w)}}if(i==="submit"&&g instanceof HTMLFormElement){let b=c.submitter,T=null;b&&b.hasAttribute("lvt-form:disable-with")&&(T=b.textContent,b.disabled=!0,b.textContent=b.getAttribute("lvt-form:disable-with"),this.logger.debug("Disabled submit button")),this.context.setActiveSubmission(g,b||null,T),g.querySelectorAll('input[type="file"][lvt-upload]').forEach(R=>{let D=R.getAttribute("lvt-upload");D&&(this.logger.debug("Triggering pending uploads for:",D),this.context.triggerPendingUploads(D))}),g.dispatchEvent(new CustomEvent("lvt:pending",{detail:L})),this.logger.debug("Emitted lvt:pending event")}if(this.logger.debug("About to send message:",L),this.logger.debug("WebSocket state:",this.context.getWebSocketReadyState()),F!==null){this.logger.debug("Tier 1 file upload detected, using HTTP fetch"),this.context.sendHTTPMultipart(g,w,F);return}if(this.context.send(L),this.logger.debug("send() called"),g instanceof HTMLFormElement){let A=g.__lvtCloseDialog;A&&(A.close(),delete g.__lvtCloseDialog)}},k=y.getAttribute("lvt-mod:throttle"),I=y.getAttribute("lvt-mod:debounce");if((k||I)&&i!=="search"){r.has(y)||r.set(y,new Map);let L=r.get(y),F=`${i}:${w}`,A=`__lvt_callback_${F}`,b=y;b[A]||(b[A]={current:x}),b[A].current=x;let T=L.get(F);if(!T){let O=()=>b[A].current();if(k){let R=parseInt(k,10);T=Te(O,R)}else if(I){let R=parseInt(I,10);T=q(O,R)}T&&L.set(F,T)}T&&T()}else x();return}u=u.parentElement}};document[a]=l,document.addEventListener(i,l,!1),this.logger.debug("Registered event listener:",i,"with key:",a)})}setupWindowEventDelegation(){let e=this.context.getWrapperElement();if(!e)return;let t=["keydown","keyup","scroll","resize","focus","blur"],n=e.getAttribute("data-lvt-id"),r=this.context.getRateLimitedHandlers();t.forEach(i=>{let a=`__lvt_window_${i}_${n}`,s=window[a];s&&window.removeEventListener(i,s);let l=c=>{let d=this.context.getWrapperElement();if(!d)return;let p=`lvt-on:window:${i}`;d.querySelectorAll(Ae(p)).forEach(f=>{let v=f.getAttribute(p);if(!v)return;if((i==="keydown"||i==="keyup")&&f.hasAttribute("lvt-key")){let g=f.getAttribute("lvt-key");if(g&&c.key!==g)return}let C={action:v,data:{}};Array.from(f.attributes).forEach(g=>{if(g.name.startsWith("data-")&&g.name!=="data-key"&&g.name!=="data-lvt-id"){let x=g.name.slice(5);C.data[x]=this.context.parseValue(g.value)}});let w=f.getAttribute("lvt-mod:throttle"),y=f.getAttribute("lvt-mod:debounce"),_=()=>this.context.send(C);if(w||y){r.has(f)||r.set(f,new Map);let g=r.get(f),x=`window-${i}:${v}`,k=g.get(x);if(!k){if(w){let I=parseInt(w,10);k=Te(_,I)}else if(y){let I=parseInt(y,10);k=q(_,I)}k&&g.set(x,k)}k&&k()}else _()})};window[a]=l,window.addEventListener(i,l)})}setupClickAwayDelegation(){let e=this.context.getWrapperElement();if(!e)return;let n=`__lvt_click_away_${e.getAttribute("data-lvt-id")}`,r=document[n];r&&document.removeEventListener("click",r);let i=a=>{let s=this.context.getWrapperElement();if(!s)return;let l=a.target,c=Nt.map(p=>Ae(`lvt-el:${p}:on:click-away`)).join(", ");s.querySelectorAll(c).forEach(p=>{p.contains(l)||Array.from(p.attributes).forEach(u=>{if(!u.name.includes(":on:click-away"))return;let f=u.name.match(/^lvt-el:(\w+):on:click-away$/);if(!f)return;let v=Qe[f[1].toLowerCase()];v&&ne(te(p),v,u.value)})})};document[n]=i,document.addEventListener("click",i)}setupDOMEventTriggerDelegation(e){let t=this.context.getWrapperElement();if(!t)return;let n=t.getAttribute("data-lvt-id");if(!n)return;let r=`__lvt_el_delegated_${n}`,i=t[r]||new Set,a=`__lvt_el_listeners_${n}`,s=(t[a]||[]).filter(d=>d.el.isConnected),l=e||t,c=d=>{let p=new Set;for(let u of d.attributes){if(!u.name.startsWith("lvt-el:"))continue;let f=u.name.match(/^lvt-el:\w+:on:([a-z-]+)$/i);if(!f)continue;let v=f[1].toLowerCase();De(v)&&p.add(v)}for(let u of p)if(Ot.has(u)){let f=`__lvt_el_${u}`;if(d[f])continue;let v=()=>re(d,u);d.addEventListener(u,v),d[f]=v,s.push({el:d,event:u,handler:v,guardKey:f})}else if(!i.has(u)){let f=u.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),v=new RegExp(`^lvt-el:\\w+:on:${f}$`,"i"),C=w=>{let y=w.target;for(;y&&y!==t;){let _=!1;for(let g of y.attributes)if(v.test(g.name)){_=!0;break}if(_){re(y,u);return}y=y.parentElement}y===t&&re(t,u)};t.addEventListener(u,C),i.add(u),s.push({el:t,event:u,handler:C})}};c(l),l.querySelectorAll("*").forEach(c),t[a]=s,t[r]=i}teardownDOMEventTriggerDelegation(){let e=this.context.getWrapperElement();if(!e)return;let t=e.getAttribute("data-lvt-id");if(!t)return;let n=`__lvt_el_listeners_${t}`,r=e[n];r&&(r.forEach(({el:a,event:s,handler:l,guardKey:c})=>{a.removeEventListener(s,l),c&&delete a[c]}),delete e[n]);let i=`__lvt_el_delegated_${t}`;delete e[i]}setupFocusTrapDelegation(){let e=this.context.getWrapperElement();if(!e)return;let n=`__lvt_focus_trap_${e.getAttribute("data-lvt-id")}`,r=document[n];r&&document.removeEventListener("keydown",r);let i=s=>{let l=["a[href]:not([disabled])","button:not([disabled])","textarea:not([disabled])",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])",'[tabindex]:not([tabindex="-1"]):not([disabled])','[contenteditable="true"]'].join(", ");return Array.from(s.querySelectorAll(l)).filter(c=>{let d=c,p=window.getComputedStyle(d),u=p.display!=="none",f=p.visibility!=="hidden",v=d.offsetParent!==null||p.position==="fixed"||p.position==="absolute"||typeof process!="undefined"&&!1;return u&&f&&v})},a=s=>{if(s.key!=="Tab")return;let l=this.context.getWrapperElement();if(!l)return;let c=l.querySelectorAll("[lvt-focus-trap]"),d=null;if(c.forEach(v=>{v.contains(document.activeElement)&&(!d||v.contains(d))&&(d=v)}),d||c.forEach(v=>{let C=v,w=window.getComputedStyle(C);w.display!=="none"&&w.visibility!=="hidden"&&(d=v)}),!d)return;let p=i(d);if(p.length===0)return;let u=p[0],f=p[p.length-1];s.shiftKey?document.activeElement===u&&(s.preventDefault(),f.focus()):document.activeElement===f&&(s.preventDefault(),u.focus())};document[n]=a,document.addEventListener("keydown",a),this.logger.debug("Focus trap delegation set up")}setupAutofocusDelegation(){let e=this.context.getWrapperElement();if(!e)return;let n=`__lvt_autofocus_observer_${e.getAttribute("data-lvt-id")}`,r=e[n];r&&r.disconnect();let i=()=>{let s=this.context.getWrapperElement();if(!s)return;s.querySelectorAll("[lvt-autofocus]").forEach(c=>{let d=c,p=window.getComputedStyle(d),u=p.display!=="none",f=p.visibility!=="hidden",v=d.offsetParent!==null||p.position==="fixed"||p.position==="absolute"||d.tagName==="BODY"||typeof process!="undefined"&&!1,C=u&&f&&v,w=d.getAttribute("data-lvt-autofocused")==="true";C&&!w?(d.setAttribute("data-lvt-autofocused","true"),requestAnimationFrame(()=>{d.focus(),this.logger.debug("Autofocused element:",d.tagName,d.id||d.getAttribute("name"))})):!C&&w&&d.removeAttribute("data-lvt-autofocused")})};i();let a=new MutationObserver(s=>{let l=!1;s.forEach(c=>{c.type==="childList"&&c.addedNodes.length>0&&c.addedNodes.forEach(d=>{d instanceof Element&&(d.hasAttribute("lvt-autofocus")||d.querySelector("[lvt-autofocus]"))&&(l=!0)}),c.type==="attributes"&&(c.target.hasAttribute("lvt-autofocus")||c.attributeName==="hidden"||c.attributeName==="style"||c.attributeName==="class")&&(l=!0)}),l&&i()});a.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["hidden","style","class","lvt-autofocus"]}),e[n]=a,this.logger.debug("Autofocus delegation set up")}};var oe=class{constructor(e,t){this.context=e;this.logger=t;this.popstateListener=null;this.abortController=null;this.currentHref=window.location.href}teardownForWrapper(e){var r;if((r=this.abortController)==null||r.abort(),this.abortController=null,!e)return;let t=`__lvt_link_intercept_${e}`,n=document[t];n&&(document.removeEventListener("click",n,!1),delete document[t])}setup(e){this.currentHref=window.location.href;let n=`__lvt_link_intercept_${e.getAttribute("data-lvt-id")}`,r=document[n];r&&document.removeEventListener("click",r);let i=a=>{var c;let s=(c=a.target)==null?void 0:c.closest("a[href]");if(!s)return;let l=this.context.getWrapperElement();!l||!l.contains(s)||this.shouldSkip(s)||(a.preventDefault(),this.navigate(s.href))};document.addEventListener("click",i),document[n]=i,this.popstateListener||(this.popstateListener=()=>{let a=this.currentHref;this.currentHref=window.location.href,this.navigate(window.location.href,!1,a)},window.addEventListener("popstate",this.popstateListener))}shouldSkip(e){if(e.origin!==window.location.origin||e.target&&e.target!=="_self"||e.hasAttribute("download")||e.hasAttribute("lvt-nav:no-intercept")||e.pathname===window.location.pathname&&e.hash)return!0;let t=e.protocol;return t!=="http:"&&t!=="https:"}async navigate(e,t=!0,n=window.location.href){var s,l,c;let r=new URL(e,window.location.origin),i=new URL(n,window.location.origin);if(r.origin===i.origin&&r.pathname===i.pathname){if(r.search===i.search){(s=this.abortController)==null||s.abort(),this.abortController=null;return}if(t&&this.context.canSendNavigate()&&((l=this.abortController)==null||l.abort(),this.abortController=null,this.context.sendNavigate(e))){window.history.pushState(null,"",e),this.currentHref=e;return}}(c=this.abortController)==null||c.abort(),this.abortController=new AbortController;try{let d=await fetch(e,{credentials:"include",headers:{Accept:"text/html"},signal:this.abortController.signal});if(!d.ok){window.location.href=e;return}let p=await d.text();t&&window.history.pushState(null,"",e),this.currentHref=e,this.context.handleNavigationResponse(p)}catch(d){if(d instanceof DOMException&&d.name==="AbortError")return;window.location.href=e}}};var z=class z{constructor(e,t){this.context=e;this.logger=t;this.infiniteScrollObserver=null;this.mutationObserver=null;this.observedSentinel=null;this.updatedListener=null;this.updatedListenerWrapper=null;this.loadMorePending=!1;this.loadMoreTimeoutId=null}setupInfiniteScrollObserver(){let e=this.context.getWrapperElement();if(!e)return;this.ensureUpdatedListener(e);let t=document.getElementById("scroll-sentinel");if(!t){this.infiniteScrollObserver&&(this.infiniteScrollObserver.disconnect(),this.infiniteScrollObserver=null,this.observedSentinel=null),this.releaseLoadMore();return}this.infiniteScrollObserver&&this.observedSentinel===t||(this.infiniteScrollObserver&&this.infiniteScrollObserver.disconnect(),this.infiniteScrollObserver=new IntersectionObserver(n=>{if(n[0].isIntersecting){if(this.loadMorePending){this.logger.debug("Sentinel visible but load_more already pending, skipping");return}this.loadMorePending=!0,this.armLoadMoreTimeout(),this.logger.debug("Sentinel visible, sending load_more action"),this.context.send({action:"load_more"})}},{rootMargin:"200px"}),this.infiniteScrollObserver.observe(t),this.observedSentinel=t,this.logger.debug("Observer set up successfully"))}ensureUpdatedListener(e){this.updatedListener&&this.updatedListenerWrapper===e||(this.updatedListener&&this.updatedListenerWrapper&&this.updatedListenerWrapper.removeEventListener("lvt:updated",this.updatedListener),this.updatedListener=t=>{let n=t.detail;(n==null?void 0:n.action)==="load_more"&&(this.releaseLoadMore(),this.observedSentinel=null,this.setupInfiniteScrollObserver())},e.addEventListener("lvt:updated",this.updatedListener),this.updatedListenerWrapper=e)}armLoadMoreTimeout(){this.clearLoadMoreTimeout(),this.loadMoreTimeoutId=window.setTimeout(()=>{this.logger.warn(`load_more response not received within ${z.LOAD_MORE_TIMEOUT_MS}ms; releasing throttle`),this.loadMoreTimeoutId=null,this.loadMorePending=!1,this.observedSentinel=null,this.setupInfiniteScrollObserver()},z.LOAD_MORE_TIMEOUT_MS)}releaseLoadMore(){this.loadMorePending=!1,this.clearLoadMoreTimeout()}clearLoadMoreTimeout(){this.loadMoreTimeoutId!==null&&(clearTimeout(this.loadMoreTimeoutId),this.loadMoreTimeoutId=null)}setupInfiniteScrollMutationObserver(){let e=this.context.getWrapperElement();e&&(this.mutationObserver&&this.mutationObserver.disconnect(),this.mutationObserver=new MutationObserver(()=>{this.setupInfiniteScrollObserver()}),this.mutationObserver.observe(e,{childList:!0,subtree:!0}),this.logger.debug("MutationObserver set up successfully"))}teardown(){this.infiniteScrollObserver&&(this.infiniteScrollObserver.disconnect(),this.infiniteScrollObserver=null),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null),this.updatedListener&&this.updatedListenerWrapper&&this.updatedListenerWrapper.removeEventListener("lvt:updated",this.updatedListener),this.updatedListener=null,this.updatedListenerWrapper=null,this.observedSentinel=null,this.releaseLoadMore()}};z.LOAD_MORE_TIMEOUT_MS=3e4;var ae=z;var le=class{constructor(){this.bar=null}show(){if(this.bar)return;let e=document.createElement("div");if(e.style.cssText=`
|
|
15
15
|
position: fixed;
|
|
16
16
|
top: 0;
|
|
17
17
|
left: 0;
|
|
@@ -28,5 +28,5 @@
|
|
|
28
28
|
}
|
|
29
29
|
`,document.head.appendChild(t)}document.body.insertBefore(e,document.body.firstChild),this.bar=e}hide(){this.bar&&(this.bar.parentNode&&this.bar.parentNode.removeChild(this.bar),this.bar=null)}};var ce=class{disable(e){if(!e)return;e.querySelectorAll("form").forEach(n=>{n.querySelectorAll("input, textarea, select, button").forEach(i=>{i.disabled=!0})})}enable(e){if(!e)return;e.querySelectorAll("form").forEach(n=>{n.querySelectorAll("input, textarea, select, button").forEach(i=>{i.disabled=!1})})}};var Ze=!1;function Dt(o){let e=o.target;if(!e||!(e instanceof Element))return;let t=e.closest("button[commandfor]");if(!t||t.disabled)return;let n=t.getAttribute("commandfor");if(!n)return;let r=t.getAttribute("command"),i=document.getElementById(n);!i||!(i instanceof HTMLDialogElement)||(r==="show-modal"&&!i.open?i.showModal():r==="close"&&i.open&&i.close())}function et(){"commandForElement"in HTMLButtonElement.prototype||Ze||(Ze=!0,document.addEventListener("click",Dt))}function tt(o){return typeof structuredClone=="function"?structuredClone(o):JSON.parse(JSON.stringify(o))}function Ut(o){return o!=null&&typeof o=="object"&&Array.isArray(o.d)&&Array.isArray(o.s)}function Le(o,e=0){if(e>50||o==null||typeof o!="object"||Array.isArray(o))return!1;if(Ut(o))return!0;for(let n of Object.keys(o))if(/^\d+$/.test(n)){let r=o[n];if(r!=null&&typeof r=="object"&&!Array.isArray(r)&&Le(r,e+1))return!0}return!1}function $t(o,e){if(!e.s||!Array.isArray(e.s))return!1;if(Le(o)&&!Le(e))return!0;for(let t of Object.keys(o))if(/^\d+$/.test(t)&&!(t in e))return!0;return!1}var de=class{constructor(e){this.logger=e;this.treeState={};this.rangeState={};this.rangeIdKeys={}}applyUpdate(e){let t=!1;for(let[r,i]of Object.entries(e))if(Array.isArray(i)&&i.length>0&&Array.isArray(i[0])&&typeof i[0][0]=="string"){let s=this.treeState[r];s&&typeof s=="object"&&!Array.isArray(s)&&Array.isArray(s.d)&&Array.isArray(s.s)?(this.treeState[r]=tt(s),this.applyDifferentialOpsToRange(this.treeState[r],i,r)):this.treeState[r]=i,t=!0}else{let s=this.treeState[r],l=typeof i=="object"&&i!==null&&!Array.isArray(i)?this.deepMergeTreeNodes(s,i,r):i;JSON.stringify(s)!==JSON.stringify(l)&&(this.treeState[r]=l,t=!0)}return{html:this.reconstructFromTree(this.treeState,""),changed:t}}reset(){this.treeState={},this.rangeState={},this.rangeIdKeys={}}getTreeState(){return{...this.treeState}}getStaticStructure(){return this.treeState.s||null}deepMergeTreeNodes(e,t,n=""){var i;if(typeof t!="object"||t===null||Array.isArray(t)||typeof e!="object"||e===null||Array.isArray(e))return t;if($t(e,t))return this.logger.debug(`[deepMerge] Structure transition at path ${n}, replacing instead of merging`),t;let r={...e};for(let[a,s]of Object.entries(t)){let l=n?`${n}.${a}`:a,c=Array.isArray(s)&&s.length>0&&Array.isArray(s[0])&&typeof s[0][0]=="string",d=r[a]&&typeof r[a]=="object"&&!Array.isArray(r[a])&&Array.isArray(r[a].d)&&Array.isArray(r[a].s);c&&d?(r[a]=tt(r[a]),this.logger.debug(`[deepMerge] Applying diff ops at path ${l}`,{ops:s,rangeItems:(i=r[a].d)==null?void 0:i.length}),this.applyDifferentialOpsToRange(r[a],s,l)):typeof s=="object"&&s!==null&&!Array.isArray(s)&&typeof r[a]=="object"&&r[a]!==null&&!Array.isArray(r[a])?r[a]=this.deepMergeTreeNodes(r[a],s,l):r[a]=s}return r}applyDifferentialOpsToRange(e,t,n){if(!e||typeof e!="object"||!Array.isArray(e.d)||!Array.isArray(e.s)){this.logger.error(`[applyDiffOpsToRange] Invalid rangeStructure at path ${n}`,{rangeStructure:e});return}let r=e.d;this.rangeState[n]||(this.rangeState[n]={items:r,statics:e.s,staticsMap:e.sm}),e.m&&typeof e.m=="object"&&typeof e.m.idKey=="string"&&(this.rangeIdKeys[n]=e.m.idKey),this.logger.debug(`[applyDiffOpsToRange] path=${n}, idKey=${this.rangeIdKeys[n]}, items=${r.length}, ops=${t.length}`);for(let i of t){if(!Array.isArray(i)||i.length<2)continue;switch(i[0]){case"r":{let s=i[1],l=this.findItemIndexByKey(r,s,e.s,n);this.logger.debug(`[applyDiffOpsToRange] Remove: key=${s}, index=${l}, total=${r.length}`),l>=0?(r.splice(l,1),this.logger.debug(`[applyDiffOpsToRange] After removal: ${r.length} items`)):this.logger.debug(`[applyDiffOpsToRange] Remove failed: key ${s} not found`);break}case"u":{let s=this.findItemIndexByKey(r,i[1],e.s,n),l=i[2];s>=0&&l&&(r[s]=this.mergeRangeItem(r[s],l,n));break}case"a":{let s=Array.isArray(i[1])?i[1]:[i[1]];i[2]&&(e.s=i[2]),r.push(...s),i[3]&&typeof i[3]=="object"&&i[3].idKey&&(this.rangeIdKeys[n]=i[3].idKey);break}case"p":{let s=Array.isArray(i[1])?i[1]:[i[1]];i[2]&&(e.s=i[2]),r.unshift(...s);break}case"i":{let s=this.findItemIndexByKey(r,i[1],e.s,n);if(s>=0){let l=Array.isArray(i[2])?i[2]:[i[2]];r.splice(s+1,0,...l)}break}case"o":{let s=i[1],l=[],c=new Map;for(let d of r){let p=this.getItemKey(d,e.s,n);p&&c.set(p,d)}for(let d of s){let p=c.get(d);p&&l.push(p)}r.length=0,r.push(...l);break}default:break}}this.rangeState[n]={items:r,statics:e.s,staticsMap:e.sm}}reconstructFromTree(e,t){if(e.s&&Array.isArray(e.s)){let n="";for(let r=0;r<e.s.length;r++){let i=e.s[r];if(n+=i,r<e.s.length-1){let a=r.toString();if(e[a]!==void 0){let s=t?`${t}.${a}`:a;n+=this.renderValue(e[a],a,s)}}}return n=n.replace(/<root>/g,"").replace(/<\/root>/g,""),n}return this.renderValue(e,"",t)}renderValue(e,t,n){if(e==null||typeof e=="string"&&e.startsWith("{{")&&e.endsWith("}}"))return"";if(typeof e=="object"&&!Array.isArray(e)){if(e.d&&Array.isArray(e.d)&&e.s&&Array.isArray(e.s)){let a=n||t||"";return a&&(this.rangeState[a]={items:e.d,statics:e.s,staticsMap:e.sm},e.m&&typeof e.m=="object"&&typeof e.m.idKey=="string"&&(this.rangeIdKeys[a]=e.m.idKey)),this.renderRangeStructure(e,t,n)}if("s"in e&&Array.isArray(e.s))return this.reconstructFromTree(e,n||"");let r=Object.keys(e),i=r.filter(a=>/^\d+$/.test(a)).sort((a,s)=>parseInt(a)-parseInt(s));if(i.length>0&&i.length===r.length)return i.map(a=>{let s=n?`${n}.${a}`:a;return this.renderValue(e[a],a,s)}).join("")}return Array.isArray(e)?e.length>0&&Array.isArray(e[0])&&typeof e[0][0]=="string"?this.applyDifferentialOperations(e,n):e.map((r,i)=>{let a=i.toString(),s=n?`${n}.${a}`:a;return typeof r=="object"&&r&&r.s?this.reconstructFromTree(r,s):this.renderValue(r,a,s)}).join(""):typeof e=="object"?(this.logger.debug("Skipping plain object value (not a tree node) - this is normal for state-only data"),""):String(e)}renderRangeStructure(e,t,n){let{d:r,s:i,sm:a}=e;if(!r||!Array.isArray(r))return"";if(r.length===0){if(e.else){let l="else",c=n?`${n}.else`:"else";return this.renderValue(e.else,l,c)}return""}let s=a&&typeof a=="object";return i&&Array.isArray(i)?r.map((l,c)=>{let d=i;s&&l._sk&&a[l._sk]&&(d=a[l._sk]);let p="";for(let u=0;u<d.length;u++)if(p+=d[u],u<d.length-1){let f=u.toString();if(l[f]!==void 0){let v=n?`${n}.${c}.${f}`:`${c}.${f}`;p+=this.renderValue(l[f],f,v)}}return p}).join(""):r.map((l,c)=>{let d=c.toString(),p=n?`${n}.${d}`:d;return this.renderValue(l,d,p)}).join("")}applyDifferentialOperations(e,t){if(!t||!this.rangeState[t])return"";let n=this.rangeState[t],r=[...n.items],i=n.statics;for(let s of e){if(!Array.isArray(s)||s.length<2)continue;switch(s[0]){case"r":{let c=this.findItemIndexByKey(r,s[1],i,t);c>=0&&r.splice(c,1);break}case"u":{let c=this.findItemIndexByKey(r,s[1],i,t),d=s[2];c>=0&&d&&(r[c]=this.mergeRangeItem(r[c],d,t||""));break}case"a":{this.addItemsToRange(r,s[1],s[2],n,!1),s[3]&&typeof s[3]=="object"&&s[3].idKey&&(this.rangeIdKeys[t||""]=s[3].idKey);break}case"p":{this.addItemsToRange(r,s[1],s[2],n,!0);break}case"i":{let c=this.findItemIndexByKey(r,s[1],i,t);if(c>=0){let d=Array.isArray(s[2])?s[2]:[s[2]];r.splice(c+1,0,...d)}break}case"o":{let c=s[1],d=[],p=new Map;for(let u of r){let f=this.getItemKey(u,i,t);f&&p.set(f,u)}for(let u of c){let f=p.get(u);f&&d.push(f)}r.length=0,r.push(...d);break}default:break}}this.rangeState[t]={items:r,statics:n.statics,staticsMap:n.staticsMap},this.treeState[t]={d:r,s:n.statics,sm:n.staticsMap};let a=this.getCurrentRangeStructure(t);return a&&a.s?this.renderItemsWithStatics(r,a.s,a.sm,t):r.map(s=>this.renderValue(s)).join("")}getCurrentRangeStructure(e){if(this.rangeState[e])return{d:this.rangeState[e].items,s:this.rangeState[e].statics,sm:this.rangeState[e].staticsMap};let t=this.treeState[e];return t&&typeof t=="object"&&t.s?t:null}renderItemsWithStatics(e,t,n,r){let i=e.map((a,s)=>{let l=t;n&&typeof n=="object"&&a._sk&&n[a._sk]&&(l=n[a._sk]);let c="";for(let d=0;d<l.length;d++)if(c+=l[d],d<l.length-1){let p=d.toString();if(a[p]!==void 0){let u=r?`${r}.${s}.${p}`:`${s}.${p}`;c+=this.renderValue(a[p],p,u)}}return c}).join("");return this.logger.isDebugEnabled()&&(this.logger.debug("[renderItemsWithStatics] statics:",t),this.logger.debug("[renderItemsWithStatics] items count:",e.length),this.logger.debug("[renderItemsWithStatics] result snippet:",i.substring(0,200))),i}addItemsToRange(e,t,n,r,i){if(n&&(r.statics=n),!t)return;let a=Array.isArray(t)?t:[t];i?e.unshift(...a):e.push(...a)}getItemKey(e,t,n){if(e._k&&typeof e._k=="string")return e._k;if(!n||!this.rangeIdKeys[n])return null;let r=this.rangeIdKeys[n];return e[r]||null}findItemIndexByKey(e,t,n,r){return e.findIndex(i=>this.getItemKey(i,n,r)===t)}mergeRangeItem(e,t,n){return this.deepMergeTreeNodes(e,t,`${n}.item`)}};var ue=class{constructor(){this.activeForm=null;this.activeButton=null;this.originalButtonText=null}setActiveSubmission(e,t,n){if(this.activeForm=e,this.activeButton=t,this.originalButtonText=n,e){e.setAttribute("aria-busy","true");let r=e.querySelector("fieldset");r&&(r.disabled=!0)}}handleResponse(e){this.activeForm&&this.activeForm.dispatchEvent(new CustomEvent("lvt:done",{detail:e})),e.success?this.handleSuccess(e):this.handleError(e),this.restoreFormState()}reset(){this.restoreFormState()}handleSuccess(e){if(!this.activeForm)return;this.activeForm.dispatchEvent(new CustomEvent("lvt:success",{detail:e}));let t=this.activeForm.closest("dialog");t&&t.open&&t.close(),this.activeForm.hasAttribute("lvt-form:preserve")||this.activeForm.reset()}handleError(e){this.activeForm&&this.activeForm.dispatchEvent(new CustomEvent("lvt:error",{detail:e}))}restoreFormState(){if(this.activeForm){this.activeForm.removeAttribute("aria-busy");let e=this.activeForm.querySelector("fieldset");e&&(e.disabled=!1)}this.activeButton&&this.originalButtonText!==null&&(this.activeButton.disabled=!1,this.activeButton.textContent=this.originalButtonText),this.activeForm=null,this.activeButton=null,this.originalButtonText=null}};var pe=class{constructor(e,t){this.context=e;this.logger=t;this.boundFields=new Map;this.enabled=!1;this.wiredElements=new Set;this.elementCleanups=new Map}setCapabilities(e){this.enabled=e.includes("change"),this.logger.debug("Capabilities received, change auto-wiring:",this.enabled?"enabled":"disabled")}analyzeStatics(e){let t=this.boundFields.size;this.walkTree(e),this.boundFields.size>t&&this.logger.debug(`Detected ${this.boundFields.size} bound field(s):`,Array.from(this.boundFields.keys()))}wireElements(){if(!this.enabled)return;let e=this.context.getWrapperElement();if(!e)return;for(let n of this.elementCleanups.keys())n.isConnected||(this.elementCleanups.get(n)(),this.elementCleanups.delete(n),this.wiredElements.delete(n));for(let[n,r]of this.boundFields){let i=this.escapeCSSSelector(n),a=e.querySelectorAll(`[name="${i}"]`);for(let s of a){if(this.wiredElements.has(s)||s.hasAttribute("lvt-input")||s.hasAttribute("lvt-change"))continue;let l=s.closest("form");l&&(l.hasAttribute("lvt-change")||l.hasAttribute("lvt-form:no-intercept"))||s instanceof HTMLInputElement&&(s.type==="hidden"||s.type==="submit"||s.type==="button")||s instanceof HTMLButtonElement||(this.attachListener(s,n,r),this.wiredElements.add(s))}}let t=e.querySelectorAll("select[name]");for(let n of t){if(this.wiredElements.has(n)||n.hasAttribute("lvt-input")||n.hasAttribute("lvt-change"))continue;let r=n.closest("form");if(r&&(r.hasAttribute("lvt-change")||r.hasAttribute("lvt-form:no-intercept")))continue;let i=n.getAttribute("name");i&&(this.attachListener(n,i,"value"),this.wiredElements.add(n))}}teardown(){for(let e of this.elementCleanups.values())e();this.elementCleanups.clear(),this.wiredElements.clear(),this.boundFields.clear(),this.enabled=!1}getBoundFields(){return this.boundFields}isEnabled(){return this.enabled}walkTree(e){if(!(!e||typeof e!="object"||Array.isArray(e))){e.s&&Array.isArray(e.s)&&this.analyzeStaticsArray(e.s);for(let t of Object.keys(e))if(/^\d+$/.test(t)){let n=e[t];n&&typeof n=="object"&&!Array.isArray(n)&&this.walkTree(n)}if(e.d&&Array.isArray(e.d))for(let t of e.d)t&&typeof t=="object"&&!Array.isArray(t)&&this.walkTree(t)}}analyzeStaticsArray(e){for(let t=0;t<e.length-1;t++){let n=e[t],r=e[t+1],i=this.detectBinding(n,r);i&&!this.boundFields.has(i.fieldName)&&this.boundFields.set(i.fieldName,i.bindingType)}}detectBinding(e,t){let n=this.detectValueBinding(e);return n?{fieldName:n,bindingType:"value"}:(n=this.detectTextareaBinding(e,t),n?{fieldName:n,bindingType:"content"}:(n=this.detectAttributeBinding(e,t),n?{fieldName:n,bindingType:"attribute"}:null))}escapeCSSSelector(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}extractUnclosedTag(e){let t=e.lastIndexOf("<"),n=e.lastIndexOf(">");return t===-1||t<=n?null:e.substring(t)}extractNameFromTag(e){let t=e.match(/\sname="([^"]+)"/);return t?t[1]:null}detectValueBinding(e){if(!e.endsWith('value="'))return null;let t=this.extractUnclosedTag(e);return t?this.extractNameFromTag(t):null}detectTextareaBinding(e,t){if(!t.startsWith("</textarea"))return null;let n=e.match(/<textarea[^>]*\sname="([^"]+)"[^>]*>$/);return n?n[1]:null}detectAttributeBinding(e,t){if(!e.endsWith(" ")||!/^[a-zA-Z>/\s]/.test(t))return null;let n=this.extractUnclosedTag(e);if(!n||!/^<input\s/i.test(n))return null;let r=n.match(/\stype="([^"]+)"/i);if(!r)return null;let i=r[1].toLowerCase();return i!=="checkbox"&&i!=="radio"?null:this.extractNameFromTag(n)}attachListener(e,t,n){let r=e.getAttribute("lvt-debounce"),i=r?parseInt(r,10):NaN,a=Number.isNaN(i)||i<0?300:i,l=q(()=>{if(!this.enabled)return;let d=n==="attribute"&&e.type==="checkbox"?e.checked:e.value;this.context.send({action:"change",data:{[t]:d}})},a),c=n==="attribute"||e instanceof HTMLSelectElement?"change":"input";e.addEventListener(c,l),this.elementCleanups.set(e,()=>{e.removeEventListener(c,l)}),this.logger.debug(`Auto-wired ${c} listener on [name="${t}"] (debounce: ${a}ms)`)}};var Me=class{constructor(e){this.options=e;this.socket=null;this.reconnectTimer=null;this.manuallyClosed=!1;this.reconnectAttempts=0}connect(){this.manuallyClosed=!1,this.clearReconnectTimer(),this.socket=new WebSocket(this.options.url);let e=this.socket;e.onopen=()=>{var t,n;this.reconnectAttempts=0,(n=(t=this.options).onOpen)==null||n.call(t,e)},e.onmessage=t=>{var n,r;(r=(n=this.options).onMessage)==null||r.call(n,t)},e.onclose=t=>{var n,r;(r=(n=this.options).onClose)==null||r.call(n,t),!this.manuallyClosed&&this.options.autoReconnect&&this.scheduleReconnect()},e.onerror=t=>{var n,r;(r=(n=this.options).onError)==null||r.call(n,t)}}send(e){this.socket&&this.socket.readyState===1&&this.socket.send(e)}disconnect(){this.manuallyClosed=!0,this.clearReconnectTimer(),this.socket&&(this.socket.close(),this.socket=null)}getSocket(){return this.socket}scheduleReconnect(){var s,l,c,d,p;this.clearReconnectTimer();let e=(s=this.options.maxReconnectAttempts)!=null?s:10;if(e>0&&this.reconnectAttempts>=e){(c=(l=this.options).onReconnectFailed)==null||c.call(l);return}this.reconnectAttempts++;let t=(d=this.options.reconnectDelay)!=null?d:1e3,n=(p=this.options.maxReconnectDelay)!=null?p:16e3,r=t*Math.pow(2,this.reconnectAttempts-1),i=Math.random()*1e3,a=Math.min(r+i,n);this.reconnectTimer=window.setTimeout(()=>{var u,f;(f=(u=this.options).onReconnectAttempt)==null||f.call(u,this.reconnectAttempts,a),this.connect()},a)}clearReconnectTimer(){this.reconnectTimer!==null&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}},ge=class{constructor(e){this.config=e;this.transport=null;this.liveUrlOverride=null}setLiveUrl(e){this.liveUrlOverride=e}async connect(){var d;let e=this.getLiveUrl();if(!await Pt(e,this.config.logger))return{usingWebSocket:!1,initialState:await nt(e,this.config.logger)};let n,r,i=new Promise((p,u)=>{n=p,r=u}),a=!1,s=!1,l=null,c=p=>{a||(a=!0,l!==null&&(clearTimeout(l),l=null),p?r(p):n({usingWebSocket:!0}))};l=setTimeout(()=>{c(new Error("WebSocket open timed out after 10s"))},1e4),this.transport=new Me({url:this.getWebSocketUrl(),autoReconnect:this.config.options.autoReconnect,reconnectDelay:this.config.options.reconnectDelay,maxReconnectDelay:16e3,maxReconnectAttempts:10,onOpen:()=>{s=!0,this.config.onConnected(),c()},onMessage:p=>{try{let u=JSON.parse(p.data);this.config.onMessage(u,p)}catch(u){this.config.logger.error("Failed to parse WebSocket message:",u)}},onClose:()=>{s?this.config.onDisconnected():c(new Error("WebSocket closed before it opened"))},onReconnectAttempt:(p,u)=>{var f,v;(v=(f=this.config).onReconnectAttempt)==null||v.call(f,p,u)},onReconnectFailed:()=>{var p,u;(u=(p=this.config).onReconnectFailed)==null||u.call(p)},onError:p=>{var u,f;(f=(u=this.config).onError)==null||f.call(u,p),c(new Error("WebSocket errored before it opened"))}}),this.transport.connect();try{return await i}catch(p){return this.config.logger.warn("WebSocket open failed, falling back to HTTP",p),(d=this.transport)==null||d.disconnect(),this.transport=null,{usingWebSocket:!1,initialState:await nt(e,this.config.logger)}}}disconnect(){var e;(e=this.transport)==null||e.disconnect(),this.transport=null}send(e){var t;(t=this.transport)==null||t.send(e)}getReadyState(){var e,t;return(t=(e=this.transport)==null?void 0:e.getSocket())==null?void 0:t.readyState}getSocket(){var e,t;return(t=(e=this.transport)==null?void 0:e.getSocket())!=null?t:null}getWebSocketUrl(){let e=this.liveUrlOverride||this.config.options.liveUrl||"/live",t=this.config.options.wsUrl;return t||`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}${e}`}getLiveUrl(){return this.liveUrlOverride||this.config.options.liveUrl||window.location.pathname+window.location.search}};async function Pt(o,e){try{let n=(await fetch(o,{method:"HEAD"})).headers.get("X-LiveTemplate-WebSocket");return n?n==="enabled":!0}catch(t){return e==null||e.warn("Failed to check WebSocket availability:",t),!0}}async function nt(o,e){try{let t=await fetch(o,{method:"GET",credentials:"include",headers:{Accept:"application/json"}});if(!t.ok)throw new Error(`Failed to fetch initial state: ${t.status}`);return await t.json()}catch(t){return e==null||e.warn("Failed to fetch initial state:",t),null}}var fe=class{async upload(e,t,n){let{file:r}=e;e.abortController=new AbortController;try{let i=new XMLHttpRequest;i.upload.addEventListener("progress",s=>{s.lengthComputable&&(e.bytesUploaded=s.loaded,e.progress=Math.round(s.loaded/s.total*100),n&&n(e))}),e.abortController.signal.addEventListener("abort",()=>{i.abort()});let a=new Promise((s,l)=>{i.addEventListener("load",()=>{i.status>=200&&i.status<300?(e.done=!0,e.progress=100,s()):l(new Error(`S3 upload failed with status ${i.status}: ${i.statusText}`))}),i.addEventListener("error",()=>{l(new Error("S3 upload failed: Network error"))}),i.addEventListener("abort",()=>{l(new Error("S3 upload cancelled"))})});if(i.open("PUT",t.url),t.headers)for(let[s,l]of Object.entries(t.headers))i.setRequestHeader(s,l);i.send(r),await a}catch(i){throw e.error=i instanceof Error?i.message:String(i),i}}};var he=class{constructor(e,t={}){this.sendMessage=e;this.entries=new Map;this.pendingFiles=new Map;this.autoUploadConfig=new Map;this.uploaders=new Map;this.inputHandlers=new WeakMap;this.chunkSize=t.chunkSize||256*1024,this.onProgress=t.onProgress,this.onComplete=t.onComplete,this.onError=t.onError,this.uploaders.set("s3",new fe)}initializeFileInputs(e){e.querySelectorAll('input[type="file"][lvt-upload]').forEach(n=>{let r=n.getAttribute("lvt-upload");if(!r)return;let i=this.inputHandlers.get(n);i&&n.removeEventListener("change",i);let a=s=>{let l=s.target.files;!l||l.length===0||this.startUpload(r,Array.from(l))};n.addEventListener("change",a),this.inputHandlers.set(n,a)})}async startUpload(e,t){this.pendingFiles.set(e,t);let n=t.map(i=>({name:i.name,type:i.type||"application/octet-stream",size:i.size})),r={action:"upload_start",upload_name:e,files:n};this.sendMessage(r)}async handleUploadStartResponse(e){let{upload_name:t,entries:n}=e;n.length>0&&this.autoUploadConfig.set(t,n[0].auto_upload);let r=this.pendingFiles.get(t);if(!r){console.error(`No pending files found for upload: ${t}`);return}this.pendingFiles.delete(t);let i=new Map;for(let s of r)i.set(s.name,s);let a=[];for(let s of n){let l=i.get(s.client_name);if(!l){console.warn(`No file found for entry ${s.entry_id} (client_name: ${s.client_name})`);continue}let c={id:s.entry_id,file:l,uploadName:t,progress:0,bytesUploaded:0,valid:s.valid,done:!1,error:s.error,external:s.external};if(this.entries.set(c.id,c),a.push(c),!s.valid){this.onError&&s.error&&this.onError(c,s.error);continue}s.auto_upload&&(s.external?this.uploadExternal(c,s.external):this.uploadChunked(c))}}async uploadExternal(e,t){try{let n=this.uploaders.get(t.uploader);if(!n)throw new Error(`Unknown uploader: ${t.uploader}`);await n.upload(e,t,this.onProgress);let r={action:"upload_complete",upload_name:e.uploadName,entry_ids:[e.id]};this.sendMessage(r),this.onComplete&&this.onComplete(e.uploadName,[e]),this.clearFileInput(e.uploadName),this.cleanupEntries(e.uploadName)}catch(n){let r=n instanceof Error?n.message:String(n);e.error=r,this.onError&&this.onError(e,r),this.cleanupEntries(e.uploadName)}}async uploadChunked(e){let{file:t,id:n}=e,r=0;e.abortController=new AbortController;try{for(;r<t.size;){if(e.abortController.signal.aborted)throw new Error("Upload cancelled");let a=Math.min(r+this.chunkSize,t.size),s=t.slice(r,a),l=await this.fileToBase64(s),c={action:"upload_chunk",entry_id:n,chunk_base64:l,offset:r,total:t.size};this.sendMessage(c),r=a,e.bytesUploaded=r,e.progress=Math.round(r/t.size*100),this.onProgress&&this.onProgress(e)}e.done=!0;let i={action:"upload_complete",upload_name:e.uploadName,entry_ids:[n]};this.sendMessage(i),this.onComplete&&this.onComplete(e.uploadName,[e]),this.clearFileInput(e.uploadName),this.cleanupEntries(e.uploadName)}catch(i){let a=i instanceof Error?i.message:String(i);e.error=a,this.onError&&this.onError(e,a),this.cleanupEntries(e.uploadName)}}handleProgressMessage(e){let t=this.entries.get(e.entry_id);t&&(t.progress=e.progress,t.bytesUploaded=e.bytes_recv,this.onProgress&&this.onProgress(t))}cancelUpload(e){let t=this.entries.get(e);t&&(t.abortController&&t.abortController.abort(),this.sendMessage({action:"cancel_upload",entry_id:e}),this.entries.delete(e))}getEntries(e){let t=[];for(let n of this.entries.values())n.uploadName===e&&t.push(n);return t}triggerPendingUploads(e){let t=[];for(let n of this.entries.values())n.uploadName===e&&n.progress===0&&!n.done&&!n.error&&t.push(n);for(let n of t)n.external?this.uploadExternal(n,n.external):this.uploadChunked(n)}registerUploader(e,t){this.uploaders.set(e,t)}clearFileInput(e){document.querySelectorAll(`input[type="file"][lvt-upload="${e}"]`).forEach(n=>{n.value=""})}cleanupEntries(e,t=5e3){setTimeout(()=>{let n=[];for(let[r,i]of this.entries)e&&i.uploadName!==e||(i.done||i.error)&&n.push(r);for(let r of n)this.entries.delete(r)},t)}fileToBase64(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let a=r.result.split(",")[1];t(a)},r.onerror=n,r.readAsDataURL(e)})}};var rt={silent:0,error:1,warn:2,info:3,debug:4},it="LiveTemplate",ke=class o{constructor(e,t=[],n=console){this.state=e;this.scope=t;this.sink=n}setLevel(e){this.state.level=e}getLevel(){return this.state.level}child(e){return new o(this.state,[...this.scope,e],this.sink)}isDebugEnabled(){return this.shouldLog("debug")}error(...e){this.log("error","error",e)}warn(...e){this.log("warn","warn",e)}info(...e){this.log("info","info",e)}debug(...e){this.log("debug","debug",e)}log(e,t,n){if(!this.shouldLog(e))return;(this.sink[t]||console[t]||console.log).apply(this.sink,[this.formatPrefix(),...n])}shouldLog(e){return rt[e]<=rt[this.state.level]}formatPrefix(){return this.scope.length===0?`[${it}]`:`[${it}:${this.scope.join(":")}]`}};function xe(o={}){var n,r;let e={level:(n=o.level)!=null?n:"info"},t=Array.isArray(o.scope)?o.scope:o.scope?[o.scope]:[];return new ke(e,t,(r=o.sink)!=null?r:console)}async function st(o,e){try{let t=globalThis==null?void 0:globalThis.require;if(typeof t=="function"){let i=t("fs"),a=JSON.parse(i.readFileSync(e,"utf8"));return o.applyUpdate(a)}let r=await(await fetch(e)).json();return o.applyUpdate(r)}catch(t){throw new Error(`Failed to load update from ${e}: ${t}`)}}function ot(o,e){let t=[],n=c=>c.replace(/\s+/g," ").replace(/>\s+</g,"><").trim(),r=n(o),i=n(e);if(r===i)return{match:!0,differences:[]};let a=r.split(`
|
|
30
30
|
`),s=i.split(`
|
|
31
|
-
`),l=Math.max(a.length,s.length);for(let c=0;c<l;c++){let d=a[c]||"",p=s[c]||"";d!==p&&(t.push(`Line ${c+1}:`),t.push(` Expected: ${d}`),t.push(` Actual: ${p}`))}return{match:!1,differences:t}}var me=class o{constructor(e={}){this.lvtId=null;this.ws=null;this.wrapperElement=null;this.useHTTP=!1;this.sessionCookie=null;this.rateLimitedHandlers=new WeakMap;this.isInitialized=!1;this.messageCount=0;this.navigationEpoch=0;this.liveUrlOverride=null;let{logger:t,logLevel:n,debug:r,...i}=e,a=n!=null?n:r?"debug":"info",s=t!=null?t:xe({level:a});t?n?t.setLevel(n):r&&t.setLevel("debug"):s.setLevel(a),this.logger=s.child("Client"),this.options={autoReconnect:!1,reconnectDelay:1e3,liveUrl:window.location.pathname+window.location.search,...i},this.treeRenderer=new de(this.logger.child("TreeRenderer")),this.focusManager=new Z(this.logger.child("FocusManager")),this.formLifecycleManager=new ue,this.loadingIndicator=new le,this.formDisabler=new ce,this.uploadHandler=new he(l=>this.send(l),{chunkSize:256*1024,onProgress:l=>{this.wrapperElement&&this.wrapperElement.dispatchEvent(new CustomEvent("lvt:upload:progress",{detail:{entry:l}}))},onComplete:(l,c)=>{this.logger.info(`Upload complete: ${l}`,c),this.wrapperElement&&this.wrapperElement.dispatchEvent(new CustomEvent("lvt:upload:complete",{detail:{uploadName:l,entries:c}}))},onError:(l,c)=>{this.logger.error(`Upload error for ${l.id}:`,c),this.wrapperElement&&this.wrapperElement.dispatchEvent(new CustomEvent("lvt:upload:error",{detail:{entry:l,error:c}}))}}),this.eventDelegator=new se({getWrapperElement:()=>this.wrapperElement,getRateLimitedHandlers:()=>this.rateLimitedHandlers,parseValue:l=>this.parseValue(l),send:l=>this.send(l),sendHTTPMultipart:(l,c,d)=>this.sendHTTPMultipart(l,c,d),setActiveSubmission:(l,c,d)=>this.formLifecycleManager.setActiveSubmission(l,c,d),getWebSocketReadyState:()=>this.webSocketManager.getReadyState(),triggerPendingUploads:l=>this.uploadHandler.triggerPendingUploads(l)},this.logger.child("EventDelegator")),this.linkInterceptor=new oe({getWrapperElement:()=>this.wrapperElement,handleNavigationResponse:l=>this.handleNavigationResponse(l),sendNavigate:l=>this.sendNavigate(l),canSendNavigate:()=>!this.useHTTP&&this.webSocketManager.getReadyState()===1},this.logger.child("LinkInterceptor")),this.observerManager=new ae({getWrapperElement:()=>this.wrapperElement,send:l=>this.send(l)},this.logger.child("ObserverManager")),this.changeAutoWirer=new pe({getWrapperElement:()=>this.wrapperElement,send:l=>this.send(l)},this.logger.child("ChangeAutoWirer")),this.webSocketManager=new ge({options:this.options,logger:this.logger.child("Transport"),onConnected:()=>{var l,c,d;this.ws=this.webSocketManager.getSocket(),this.logger.info("WebSocket connected"),this.clearFlashQueryParams(),(c=(l=this.options).onConnect)==null||c.call(l),(d=this.wrapperElement)==null||d.dispatchEvent(new Event("lvt:connected"))},onDisconnected:()=>{var l,c,d;this.ws=null,this.logger.info("WebSocket disconnected"),(c=(l=this.options).onDisconnect)==null||c.call(l),(d=this.wrapperElement)==null||d.dispatchEvent(new Event("lvt:disconnected"))},onMessage:(l,c)=>{this.handleWebSocketPayload(l,c)},onReconnectAttempt:()=>{this.logger.info("Attempting to reconnect...")},onError:l=>{var c,d;this.logger.error("WebSocket error:",l),(d=(c=this.options).onError)==null||d.call(c,l)}})}static autoInit(){let e=xe({scope:"Client:autoInit"}),t=()=>{let n=document.querySelector("[data-lvt-id]");if(n){let r=new o;r.wrapperElement=n,n.getAttribute("data-lvt-loading")==="true"&&(r.loadingIndicator.show(),r.formDisabler.disable(r.wrapperElement)),r.connect().catch(a=>{e.error("Auto-initialization connect failed:",a)}),window.liveTemplateClient=r}};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",t):t()}handleWebSocketPayload(e,t){var r,i,a;let n=e;if(n.type==="upload_progress"){this.uploadHandler.handleProgressMessage(n);return}if(n.upload_name&&n.entries){let s=n;try{this.handleUploadStartResponse(s)}catch(l){this.logger.error("Error handling upload start response:",l)}return}if(n.upload_name&&n.hasOwnProperty("success")){n.success?this.logger.info(`Upload complete: ${n.upload_name}`):this.logger.error(`Upload failed: ${n.upload_name}`,n.error);return}this.isInitialized||(this.loadingIndicator.hide(),this.formDisabler.enable(this.wrapperElement),this.wrapperElement&&this.wrapperElement.hasAttribute("data-lvt-loading")&&this.wrapperElement.removeAttribute("data-lvt-loading"),this.isInitialized=!0),this.wrapperElement&&((r=e.meta)!=null&&r.capabilities&&this.changeAutoWirer.setCapabilities(e.meta.capabilities),this.changeAutoWirer.analyzeStatics(e.tree),this.updateDOM(this.wrapperElement,e.tree,e.meta),this.messageCount++,this.wrapperElement.dispatchEvent(new CustomEvent("lvt:updated",{detail:{messageCount:this.messageCount,action:(i=e.meta)==null?void 0:i.action,success:(a=e.meta)==null?void 0:a.success}})))}async connect(e="[data-lvt-id]"){var n,r;if(this.wrapperElement=document.querySelector(e),!this.wrapperElement)throw new Error(`LiveTemplate wrapper not found with selector: ${e}`);this.webSocketManager.disconnect();let t=await this.webSocketManager.connect();this.useHTTP=!t.usingWebSocket,this.useHTTP&&(this.ws=null,this.logger.info("WebSocket not available, using HTTP mode"),(r=(n=this.options).onConnect)==null||r.call(n),t.initialState&&this.wrapperElement&&this.handleWebSocketPayload(t.initialState)),this.eventDelegator.setupEventDelegation(),this.eventDelegator.setupWindowEventDelegation(),this.eventDelegator.setupClickAwayDelegation(),this.eventDelegator.setupDOMEventTriggerDelegation(),Ye(),this.eventDelegator.setupFocusTrapDelegation(),this.eventDelegator.setupAutofocusDelegation(),this.linkInterceptor.setup(this.wrapperElement),ie(),et(),Ve(this.wrapperElement),this.focusManager.attach(this.wrapperElement),this.observerManager.setupInfiniteScrollObserver(),this.observerManager.setupInfiniteScrollMutationObserver()}disconnect(){this.webSocketManager.disconnect(),this.ws=null,this.useHTTP=!1,this.eventDelegator.teardownDOMEventTriggerDelegation(),this.wrapperElement&&(Ke(this.wrapperElement),je(this.wrapperElement)),this.resetSessionState()}resetSessionState(){this.treeRenderer.reset(),this.focusManager.reset(),this.observerManager.teardown(),this.changeAutoWirer.teardown(),this.formLifecycleManager.reset(),this.loadingIndicator.hide(),this.formDisabler.enable(this.wrapperElement),this.lvtId=null,this.isInitialized=!1}clearFlashQueryParams(){let e=new URL(window.location.href),t=["error","success"],n=!1;for(let r of t)e.searchParams.has(r)&&(e.searchParams.delete(r),n=!0);n&&(this.logger.debug("Clearing flash query params from URL"),window.history.replaceState(null,"",e.toString()))}isReady(){let e=this.wrapperElement;return!e||e.hasAttribute("data-lvt-loading")?!1:this.useHTTP?!0:this.webSocketManager.getReadyState()===1}send(e){let t=this.webSocketManager.getReadyState();this.logger.isDebugEnabled()&&this.logger.debug("send() invoked",{message:e,useHTTP:this.useHTTP,hasWebSocket:t!==void 0,readyState:t}),this.useHTTP?(this.logger.debug("Using HTTP mode for send"),this.sendHTTP(e)):t===1?(this.logger.debug("Sending via WebSocket"),this.webSocketManager.send(JSON.stringify(e))):t!==void 0?(this.logger.warn(`WebSocket not ready (state: ${t}), using HTTP fallback`),this.sendHTTP(e)):this.logger.error("No transport available")}getLiveUrl(){return this.liveUrlOverride||this.options.liveUrl||"/live"}sendNavigate(e){let t=new URL(e,window.location.origin),n={},r=new Set;t.searchParams.forEach((a,s)=>{r.has(s)&&this.logger.warn("sendNavigate: duplicate query param key \u2014 last value wins; server may receive incomplete data",{key:s,href:e}),r.add(s),n[s]=a});let i=t.pathname+t.search;if(this.webSocketManager.getReadyState()!==1){let a=this.webSocketManager.getReadyState();return a===3?this.logger.error("sendNavigate: WebSocket is CLOSED and autoReconnect may be disabled; navigate message dropped. Reload or re-enable autoReconnect.",{href:e}):this.options.autoReconnect?this.logger.warn("sendNavigate: WS not open; browser URL is ahead of server state until reconnect",{href:e,readyState:a}):this.logger.error("sendNavigate: WS not open and autoReconnect is disabled; navigate may be permanently lost",{href:e,readyState:a}),!1}return this.liveUrlOverride=i,this.webSocketManager.setLiveUrl(i),this.logger.debug("sendNavigate",{href:e,data:n}),this.send({action:"__navigate__",data:n}),!0}async sendHTTP(e){try{let t=this.getLiveUrl(),n=await fetch(t,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)});if(!n.ok)throw new Error(`HTTP request failed: ${n.status}`);let r=await n.json();this.wrapperElement&&this.updateDOM(this.wrapperElement,r.tree,r.meta)}catch(t){this.logger.error("Failed to send HTTP request:",t)}}sendHTTPMultipart(e,t,n){this.doSendHTTPMultipart(e,t,n)}async doSendHTTPMultipart(e,t,n){try{let r=this.getLiveUrl(),i=await fetch(r,{method:"POST",credentials:"include",headers:{Accept:"application/json"},body:n});if(!i.ok)throw new Error(`HTTP multipart request failed: ${i.status}`);let a=await i.json();this.wrapperElement&&this.updateDOM(this.wrapperElement,a.tree,a.meta)}catch(r){this.logger.error("Failed to send HTTP multipart request:",r)}}handleNavigationResponse(e){var l;if(!this.wrapperElement)return;let n=new DOMParser().parseFromString(e,"text/html"),r=this.wrapperElement.getAttribute("data-lvt-id"),i=(l=n.querySelector("title"))==null?void 0:l.textContent;i&&(document.title=i);let a=n.querySelector("[data-lvt-id]");if(a){let c=a.getAttribute("data-lvt-id");if(!c){this.logger.warn("Cross-handler navigation: new wrapper has empty data-lvt-id"),window.location.reload();return}this.linkInterceptor.teardownForWrapper(r),this.eventDelegator.teardownForWrapper(r);let d=++this.navigationEpoch;this.disconnect(),this.wrapperElement.setAttribute("data-lvt-id",c),this.wrapperElement.replaceChildren(...Array.from(a.childNodes).map(u=>u.cloneNode(!0))),this.eventDelegator.setupEventDelegation(),this.linkInterceptor.setup(this.wrapperElement),window.scrollTo(0,0);let p=window.location.pathname+window.location.search;if(this.liveUrlOverride=p,this.webSocketManager.setLiveUrl(p),!this.useHTTP){let f=`[data-lvt-id="${c.replace(/[\\"]/g,"\\$&")}"]`;this.connect(f).catch(v=>{d===this.navigationEpoch&&(this.logger.error("Cross-handler reconnect failed:",v),window.location.reload())})}return}this.linkInterceptor.teardownForWrapper(r),this.eventDelegator.teardownForWrapper(r),this.disconnect();let s=n.querySelector("body");s&&this.wrapperElement.replaceChildren(...Array.from(s.childNodes).map(c=>c.cloneNode(!0))),this.eventDelegator.setupEventDelegation(),this.linkInterceptor.setup(this.wrapperElement)}parseValue(e){let t=e.trim(),n=parseFloat(t);if(!isNaN(n)){if(Number.isInteger(n)&&Math.abs(n)>Number.MAX_SAFE_INTEGER)return t;if(t===n.toString())return n}return e==="true"?!0:e==="false"?!1:e}applyUpdate(e){return this.treeRenderer.applyUpdate(e)}applyUpdateToHTML(e,t){let n=this.applyUpdate(t);if(!this.lvtId){let c=e.match(/data-lvt-id="([^"]+)"/);c&&(this.lvtId=c[1])}let r=n.html;if(!e.match(/<body>([\s\S]*?)<\/body>/))return e;let l=`<div data-lvt-id="${this.lvtId||"lvt-unknown"}">`+r+"</div>";return e.replace(/<body>[\s\S]*?<\/body>/,`<body>${l}</body>`)}updateDOM(e,t,n){let r=this.applyUpdate(t),i=s=>!s||typeof s!="object"?!1:s.s&&Array.isArray(s.s)?!0:Object.values(s).some(l=>i(l));if(!r.changed&&!i(t))return;let a=document.createElement(e.tagName);if(this.logger.isDebugEnabled()&&(this.logger.debug("[updateDOM] element.tagName:",e.tagName),this.logger.debug("[updateDOM] result.html (first 500 chars):",r.html.substring(0,500)),this.logger.debug("[updateDOM] Has <table> tag:",r.html.includes("<table>")),this.logger.debug("[updateDOM] Has <tbody> tag:",r.html.includes("<tbody>")),this.logger.debug("[updateDOM] Has <tr> tag:",r.html.includes("<tr"))),/<script[\s>]/i.test(r.html)){let s=e.tagName.toLowerCase(),l=s==="body"||s==="html"?"div":s,d=new DOMParser().parseFromString(`<${l}>${r.html}</${l}>`,"text/html"),p=d.body.firstElementChild;p?a.replaceChildren(...Array.from(p.childNodes)):(this.logger.warn("[updateDOM] DOMParser: no wrapper root element; using doc.body children"),a.replaceChildren(...Array.from(d.body.childNodes)))}else a.innerHTML=r.html;this.logger.isDebugEnabled()&&(this.logger.debug("[updateDOM] tempWrapper.innerHTML (first 500 chars):",a.innerHTML.substring(0,500)),this.logger.debug("[updateDOM] tempWrapper has <table>:",a.innerHTML.includes("<table>")),this.logger.debug("[updateDOM] tempWrapper has <tbody>:",a.innerHTML.includes("<tbody>")),this.logger.debug("[updateDOM] tempWrapper has <tr>:",a.innerHTML.includes("<tr"))),Oe(e,a,{childrenOnly:!0,getNodeKey:s=>{if(s.nodeType===1)return s.getAttribute("data-key")||s.getAttribute("data-lvt-key")||void 0},onBeforeElUpdated:(s,l)=>{if(l.nodeType===Node.ELEMENT_NODE&&l.hasAttribute("lvt-preserve"))return!1;if(l.nodeType===Node.ELEMENT_NODE&&l.hasAttribute("lvt-preserve-attrs")&&s.nodeType===Node.ELEMENT_NODE){let c=s.attributes,d=l;for(let p=0;p<c.length;p++){let u=c[p];u.name==="lvt-preserve"||u.name==="lvt-preserve-attrs"||d.hasAttributeNS(u.namespaceURI,u.localName)||d.setAttributeNS(u.namespaceURI,u.name,u.value)}}return this.focusManager.shouldSkipUpdate(s)||s.isEqualNode(l)?!1:(this.executeLifecycleHook(s,"lvt-updated"),!0)},onElUpdated:s=>{var l;s instanceof HTMLTextAreaElement&&(s.value=(l=s.textContent)!=null?l:"")},onNodeAdded:s=>{var l;s instanceof HTMLTextAreaElement&&(s.value=(l=s.textContent)!=null?l:""),s.nodeType===Node.ELEMENT_NODE&&this.executeLifecycleHook(s,"lvt-mounted")},onBeforeNodeDiscarded:s=>(s.nodeType===Node.ELEMENT_NODE&&this.executeLifecycleHook(s,"lvt-destroyed"),!0)}),this.focusManager.restoreFocusedElement(),qe(e),ze(e),Ge(e),Be(e,this.wrapperElement||void 0),this.eventDelegator.setupDOMEventTriggerDelegation(e),Xe(e),this.uploadHandler.initializeFileInputs(e),this.changeAutoWirer.wireElements(),n&&this.formLifecycleManager.handleResponse(n)}handleUploadStartResponse(e){this.uploadHandler.handleUploadStartResponse(e)}executeLifecycleHook(e,t){let n=e.getAttribute(t);if(n)try{new Function("element",n).call(e,e)}catch(r){this.logger.error(`Error executing ${t} hook:`,r)}}reset(){this.resetSessionState()}getTreeState(){return this.treeRenderer.getTreeState()}getStaticStructure(){return this.treeRenderer.getStaticStructure()}};typeof window!="undefined"&&me.autoInit();return pt(Bt);})();
|
|
31
|
+
`),l=Math.max(a.length,s.length);for(let c=0;c<l;c++){let d=a[c]||"",p=s[c]||"";d!==p&&(t.push(`Line ${c+1}:`),t.push(` Expected: ${d}`),t.push(` Actual: ${p}`))}return{match:!1,differences:t}}var me=class o{constructor(e={}){this.lvtId=null;this.ws=null;this.wrapperElement=null;this.useHTTP=!1;this.sessionCookie=null;this.rateLimitedHandlers=new WeakMap;this.isInitialized=!1;this.messageCount=0;this.navigationEpoch=0;this.liveUrlOverride=null;let{logger:t,logLevel:n,debug:r,...i}=e,a=n!=null?n:r?"debug":"info",s=t!=null?t:xe({level:a});t?n?t.setLevel(n):r&&t.setLevel("debug"):s.setLevel(a),this.logger=s.child("Client"),this.options={autoReconnect:!1,reconnectDelay:1e3,liveUrl:window.location.pathname+window.location.search,...i},this.treeRenderer=new de(this.logger.child("TreeRenderer")),this.focusManager=new Z(this.logger.child("FocusManager")),this.formLifecycleManager=new ue,this.loadingIndicator=new le,this.formDisabler=new ce,this.uploadHandler=new he(l=>this.send(l),{chunkSize:256*1024,onProgress:l=>{this.wrapperElement&&this.wrapperElement.dispatchEvent(new CustomEvent("lvt:upload:progress",{detail:{entry:l}}))},onComplete:(l,c)=>{this.logger.info(`Upload complete: ${l}`,c),this.wrapperElement&&this.wrapperElement.dispatchEvent(new CustomEvent("lvt:upload:complete",{detail:{uploadName:l,entries:c}}))},onError:(l,c)=>{this.logger.error(`Upload error for ${l.id}:`,c),this.wrapperElement&&this.wrapperElement.dispatchEvent(new CustomEvent("lvt:upload:error",{detail:{entry:l,error:c}}))}}),this.eventDelegator=new se({getWrapperElement:()=>this.wrapperElement,getRateLimitedHandlers:()=>this.rateLimitedHandlers,parseValue:l=>this.parseValue(l),send:l=>this.send(l),sendHTTPMultipart:(l,c,d)=>this.sendHTTPMultipart(l,c,d),setActiveSubmission:(l,c,d)=>this.formLifecycleManager.setActiveSubmission(l,c,d),getWebSocketReadyState:()=>this.webSocketManager.getReadyState(),triggerPendingUploads:l=>this.uploadHandler.triggerPendingUploads(l)},this.logger.child("EventDelegator")),this.linkInterceptor=new oe({getWrapperElement:()=>this.wrapperElement,handleNavigationResponse:l=>this.handleNavigationResponse(l),sendNavigate:l=>this.sendNavigate(l),canSendNavigate:()=>!this.useHTTP&&this.webSocketManager.getReadyState()===1},this.logger.child("LinkInterceptor")),this.observerManager=new ae({getWrapperElement:()=>this.wrapperElement,send:l=>this.send(l)},this.logger.child("ObserverManager")),this.changeAutoWirer=new pe({getWrapperElement:()=>this.wrapperElement,send:l=>this.send(l)},this.logger.child("ChangeAutoWirer")),this.webSocketManager=new ge({options:this.options,logger:this.logger.child("Transport"),onConnected:()=>{var l,c,d;this.ws=this.webSocketManager.getSocket(),this.logger.info("WebSocket connected"),this.clearFlashQueryParams(),(c=(l=this.options).onConnect)==null||c.call(l),(d=this.wrapperElement)==null||d.dispatchEvent(new Event("lvt:connected"))},onDisconnected:()=>{var l,c,d;this.ws=null,this.logger.info("WebSocket disconnected"),(c=(l=this.options).onDisconnect)==null||c.call(l),(d=this.wrapperElement)==null||d.dispatchEvent(new Event("lvt:disconnected"))},onMessage:(l,c)=>{this.handleWebSocketPayload(l,c)},onReconnectAttempt:()=>{this.logger.info("Attempting to reconnect...")},onError:l=>{var c,d;this.logger.error("WebSocket error:",l),(d=(c=this.options).onError)==null||d.call(c,l)}})}static autoInit(){let e=xe({scope:"Client:autoInit"}),t=()=>{let n=document.querySelector("[data-lvt-id]");if(n){let r=new o;r.wrapperElement=n,n.getAttribute("data-lvt-loading")==="true"&&(r.loadingIndicator.show(),r.formDisabler.disable(r.wrapperElement)),r.connect().catch(a=>{e.error("Auto-initialization connect failed:",a)}),window.liveTemplateClient=r}};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",t):t()}handleWebSocketPayload(e,t){var r,i,a;let n=e;if(n.type==="upload_progress"){this.uploadHandler.handleProgressMessage(n);return}if(n.upload_name&&n.entries){let s=n;try{this.handleUploadStartResponse(s)}catch(l){this.logger.error("Error handling upload start response:",l)}return}if(n.upload_name&&n.hasOwnProperty("success")){n.success?this.logger.info(`Upload complete: ${n.upload_name}`):this.logger.error(`Upload failed: ${n.upload_name}`,n.error);return}this.isInitialized||(this.loadingIndicator.hide(),this.formDisabler.enable(this.wrapperElement),this.wrapperElement&&this.wrapperElement.hasAttribute("data-lvt-loading")&&this.wrapperElement.removeAttribute("data-lvt-loading"),this.isInitialized=!0),this.wrapperElement&&((r=e.meta)!=null&&r.capabilities&&this.changeAutoWirer.setCapabilities(e.meta.capabilities),this.changeAutoWirer.analyzeStatics(e.tree),this.updateDOM(this.wrapperElement,e.tree,e.meta),this.messageCount++,this.wrapperElement.dispatchEvent(new CustomEvent("lvt:updated",{detail:{messageCount:this.messageCount,action:(i=e.meta)==null?void 0:i.action,success:(a=e.meta)==null?void 0:a.success}})))}async connect(e="[data-lvt-id]"){var n,r;if(this.wrapperElement=document.querySelector(e),!this.wrapperElement)throw new Error(`LiveTemplate wrapper not found with selector: ${e}`);this.webSocketManager.disconnect();let t=await this.webSocketManager.connect();this.useHTTP=!t.usingWebSocket,this.useHTTP&&(this.ws=null,this.logger.info("WebSocket not available, using HTTP mode"),(r=(n=this.options).onConnect)==null||r.call(n),t.initialState&&this.wrapperElement&&this.handleWebSocketPayload(t.initialState)),this.eventDelegator.setupEventDelegation(),this.eventDelegator.setupWindowEventDelegation(),this.eventDelegator.setupClickAwayDelegation(),this.eventDelegator.setupDOMEventTriggerDelegation(),Ye(),this.eventDelegator.setupFocusTrapDelegation(),this.eventDelegator.setupAutofocusDelegation(),this.linkInterceptor.setup(this.wrapperElement),ie(),et(),Ve(this.wrapperElement),this.focusManager.attach(this.wrapperElement),this.observerManager.setupInfiniteScrollObserver(),this.observerManager.setupInfiniteScrollMutationObserver()}disconnect(){this.webSocketManager.disconnect(),this.ws=null,this.useHTTP=!1,this.eventDelegator.teardownDOMEventTriggerDelegation(),this.wrapperElement&&(Ke(this.wrapperElement),je(this.wrapperElement)),this.resetSessionState()}resetSessionState(){this.treeRenderer.reset(),this.focusManager.reset(),this.observerManager.teardown(),this.changeAutoWirer.teardown(),this.formLifecycleManager.reset(),this.loadingIndicator.hide(),this.formDisabler.enable(this.wrapperElement),this.lvtId=null,this.isInitialized=!1}clearFlashQueryParams(){let e=new URL(window.location.href),t=["error","success"],n=!1;for(let r of t)e.searchParams.has(r)&&(e.searchParams.delete(r),n=!0);n&&(this.logger.debug("Clearing flash query params from URL"),window.history.replaceState(null,"",e.toString()))}isReady(){let e=this.wrapperElement;return!e||e.hasAttribute("data-lvt-loading")?!1:this.useHTTP?!0:this.webSocketManager.getReadyState()===1}send(e){let t=this.webSocketManager.getReadyState();this.logger.isDebugEnabled()&&this.logger.debug("send() invoked",{message:e,useHTTP:this.useHTTP,hasWebSocket:t!==void 0,readyState:t}),this.useHTTP?(this.logger.debug("Using HTTP mode for send"),this.sendHTTP(e)):t===1?(this.logger.debug("Sending via WebSocket"),this.webSocketManager.send(JSON.stringify(e))):t!==void 0?(this.logger.warn(`WebSocket not ready (state: ${t}), using HTTP fallback`),this.sendHTTP(e)):this.logger.error("No transport available")}getLiveUrl(){return this.liveUrlOverride||this.options.liveUrl||"/live"}sendNavigate(e){let t=new URL(e,window.location.origin),n={},r=new Set;t.searchParams.forEach((a,s)=>{r.has(s)&&this.logger.warn("sendNavigate: duplicate query param key \u2014 last value wins; server may receive incomplete data",{key:s,href:e}),r.add(s),n[s]=a});let i=t.pathname+t.search;if(this.webSocketManager.getReadyState()!==1){let a=this.webSocketManager.getReadyState();return a===3?this.logger.error("sendNavigate: WebSocket is CLOSED and autoReconnect may be disabled; navigate message dropped. Reload or re-enable autoReconnect.",{href:e}):this.options.autoReconnect?this.logger.warn("sendNavigate: WS not open; browser URL is ahead of server state until reconnect",{href:e,readyState:a}):this.logger.error("sendNavigate: WS not open and autoReconnect is disabled; navigate may be permanently lost",{href:e,readyState:a}),!1}return this.liveUrlOverride=i,this.webSocketManager.setLiveUrl(i),this.logger.debug("sendNavigate",{href:e,data:n}),this.send({action:"__navigate__",data:n}),!0}async sendHTTP(e){try{let t=this.getLiveUrl(),n=await fetch(t,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)});if(!n.ok)throw new Error(`HTTP request failed: ${n.status}`);let r=await n.json();this.wrapperElement&&this.updateDOM(this.wrapperElement,r.tree,r.meta)}catch(t){this.logger.error("Failed to send HTTP request:",t)}}sendHTTPMultipart(e,t,n){this.doSendHTTPMultipart(e,t,n)}async doSendHTTPMultipart(e,t,n){try{let r=this.getLiveUrl(),i=await fetch(r,{method:"POST",credentials:"include",headers:{Accept:"application/json"},body:n});if(!i.ok)throw new Error(`HTTP multipart request failed: ${i.status}`);let a=await i.json();this.wrapperElement&&this.updateDOM(this.wrapperElement,a.tree,a.meta)}catch(r){this.logger.error("Failed to send HTTP multipart request:",r)}}handleNavigationResponse(e){var l;if(!this.wrapperElement)return;let n=new DOMParser().parseFromString(e,"text/html"),r=this.wrapperElement.getAttribute("data-lvt-id"),i=(l=n.querySelector("title"))==null?void 0:l.textContent;i&&(document.title=i);let a=n.querySelector("[data-lvt-id]");if(a){let c=a.getAttribute("data-lvt-id");if(!c){this.logger.warn("Cross-handler navigation: new wrapper has empty data-lvt-id"),window.location.reload();return}this.linkInterceptor.teardownForWrapper(r),this.eventDelegator.teardownForWrapper(r);let d=++this.navigationEpoch;this.disconnect(),this.wrapperElement.setAttribute("data-lvt-id",c),this.wrapperElement.replaceChildren(...Array.from(a.childNodes).map(u=>u.cloneNode(!0))),this.eventDelegator.setupEventDelegation(),this.linkInterceptor.setup(this.wrapperElement),window.scrollTo(0,0);let p=window.location.pathname+window.location.search;if(this.liveUrlOverride=p,this.webSocketManager.setLiveUrl(p),!this.useHTTP){let f=`[data-lvt-id="${c.replace(/[\\"]/g,"\\$&")}"]`;this.connect(f).catch(v=>{d===this.navigationEpoch&&(this.logger.error("Cross-handler reconnect failed:",v),window.location.reload())})}return}this.linkInterceptor.teardownForWrapper(r),this.eventDelegator.teardownForWrapper(r),this.disconnect();let s=n.querySelector("body");s&&this.wrapperElement.replaceChildren(...Array.from(s.childNodes).map(c=>c.cloneNode(!0))),this.eventDelegator.setupEventDelegation(),this.linkInterceptor.setup(this.wrapperElement)}parseValue(e){let t=e.trim(),n=parseFloat(t);if(!isNaN(n)){if(Number.isInteger(n)&&Math.abs(n)>Number.MAX_SAFE_INTEGER)return t;if(t===n.toString())return n}return e==="true"?!0:e==="false"?!1:e}applyUpdate(e){return this.treeRenderer.applyUpdate(e)}applyUpdateToHTML(e,t){let n=this.applyUpdate(t);if(!this.lvtId){let c=e.match(/data-lvt-id="([^"]+)"/);c&&(this.lvtId=c[1])}let r=n.html;if(!e.match(/<body>([\s\S]*?)<\/body>/))return e;let l=`<div data-lvt-id="${this.lvtId||"lvt-unknown"}">`+r+"</div>";return e.replace(/<body>[\s\S]*?<\/body>/,`<body>${l}</body>`)}updateDOM(e,t,n){let r=this.applyUpdate(t),i=s=>!s||typeof s!="object"?!1:s.s&&Array.isArray(s.s)?!0:Object.values(s).some(l=>i(l));if(!r.changed&&!i(t))return;let a=document.createElement(e.tagName);if(this.logger.isDebugEnabled()&&(this.logger.debug("[updateDOM] element.tagName:",e.tagName),this.logger.debug("[updateDOM] result.html (first 500 chars):",r.html.substring(0,500)),this.logger.debug("[updateDOM] Has <table> tag:",r.html.includes("<table>")),this.logger.debug("[updateDOM] Has <tbody> tag:",r.html.includes("<tbody>")),this.logger.debug("[updateDOM] Has <tr> tag:",r.html.includes("<tr"))),/<script[\s>]/i.test(r.html)){let s=e.tagName.toLowerCase(),l=s==="body"||s==="html"?"div":s,d=new DOMParser().parseFromString(`<${l}>${r.html}</${l}>`,"text/html"),p=d.body.firstElementChild;p?a.replaceChildren(...Array.from(p.childNodes)):(this.logger.warn("[updateDOM] DOMParser: no wrapper root element; using doc.body children"),a.replaceChildren(...Array.from(d.body.childNodes)))}else a.innerHTML=r.html;this.logger.isDebugEnabled()&&(this.logger.debug("[updateDOM] tempWrapper.innerHTML (first 500 chars):",a.innerHTML.substring(0,500)),this.logger.debug("[updateDOM] tempWrapper has <table>:",a.innerHTML.includes("<table>")),this.logger.debug("[updateDOM] tempWrapper has <tbody>:",a.innerHTML.includes("<tbody>")),this.logger.debug("[updateDOM] tempWrapper has <tr>:",a.innerHTML.includes("<tr"))),Ne(e,a,{childrenOnly:!0,getNodeKey:s=>{if(s.nodeType===1)return s.getAttribute("data-key")||s.getAttribute("data-lvt-key")||void 0},onBeforeElUpdated:(s,l)=>{if(l.nodeType===Node.ELEMENT_NODE&&l.hasAttribute("lvt-preserve"))return!1;if(l.nodeType===Node.ELEMENT_NODE&&l.hasAttribute("lvt-preserve-attrs")&&s.nodeType===Node.ELEMENT_NODE){let c=s.attributes,d=l;for(let p=0;p<c.length;p++){let u=c[p];u.name==="lvt-preserve"||u.name==="lvt-preserve-attrs"||d.hasAttributeNS(u.namespaceURI,u.localName)||d.setAttributeNS(u.namespaceURI,u.name,u.value)}}return this.focusManager.shouldSkipUpdate(s)||s.isEqualNode(l)?!1:(this.executeLifecycleHook(s,"lvt-updated"),!0)},onElUpdated:s=>{var l;s instanceof HTMLTextAreaElement&&(s.value=(l=s.textContent)!=null?l:"")},onNodeAdded:s=>{var l;s instanceof HTMLTextAreaElement&&(s.value=(l=s.textContent)!=null?l:""),s.nodeType===Node.ELEMENT_NODE&&this.executeLifecycleHook(s,"lvt-mounted")},onBeforeNodeDiscarded:s=>(s.nodeType===Node.ELEMENT_NODE&&this.executeLifecycleHook(s,"lvt-destroyed"),!0)}),this.focusManager.restoreFocusedElement(),qe(e),ze(e),Ge(e),Be(e,this.wrapperElement||void 0),this.eventDelegator.setupDOMEventTriggerDelegation(e),Xe(e),this.uploadHandler.initializeFileInputs(e),this.changeAutoWirer.wireElements(),n&&this.formLifecycleManager.handleResponse(n)}handleUploadStartResponse(e){this.uploadHandler.handleUploadStartResponse(e)}executeLifecycleHook(e,t){let n=e.getAttribute(t);if(n)try{new Function("element",n).call(e,e)}catch(r){this.logger.error(`Error executing ${t} hook:`,r)}}reset(){this.resetSessionState()}getTreeState(){return this.treeRenderer.getTreeState()}getStaticStructure(){return this.treeRenderer.getStaticStructure()}};typeof window!="undefined"&&me.autoInit();return pt(Bt);})();
|
|
32
32
|
//# sourceMappingURL=livetemplate-client.browser.js.map
|