stx-router 0.2.47 → 0.2.51

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/client.js ADDED
@@ -0,0 +1,768 @@
1
+ // @bun
2
+ // src/client.ts
3
+ function getRouterScript() {
4
+ return `
5
+ ;(function(){
6
+ 'use strict';
7
+ if(window.__stxRouter)return;
8
+
9
+ // \u2500\u2500 Configuration \u2500\u2500
10
+ var defaults={container:'main',loadingClass:'stx-navigating',viewTransitions:true,cache:true,scrollToTop:true,prefetch:true,progress:true,progressColor:'#78dce8',progressHeight:'2px',interceptAllLinks:false};
11
+ var o=Object.assign({},defaults,window.__stxRouterConfig||{},window.STX_ROUTER_OPTIONS||{});
12
+ var containerSel=o.container;
13
+ var debug=!!o.debug;
14
+ function log(){if(debug&&typeof console!=='undefined'&&console.log)console.log.apply(console,arguments)}
15
+
16
+ // \u2500\u2500 Progress bar (0\u2192100% at top of viewport) \u2500\u2500
17
+ // Native loading indicator baked into the router. Starts when navigation
18
+ // begins, trickles up to ~90% during fetch, snaps to 100% + fades on
19
+ // completion. Opt-out via window.__stxRouterConfig={progress:false}.
20
+ var progEl=null;
21
+ var progVal=0;
22
+ var progTimer=null;
23
+ function setProgress(v){
24
+ progVal=v<0?0:(v>100?100:v);
25
+ if(!progEl)return;
26
+ progEl.style.opacity=progVal>0?'1':'0';
27
+ progEl.style.transform='scaleX('+(progVal/100)+')';
28
+ }
29
+ function startProgress(){
30
+ if(!o.progress||!progEl)return;
31
+ if(progTimer){clearInterval(progTimer);progTimer=null}
32
+ setProgress(8);
33
+ progTimer=setInterval(function(){
34
+ if(progVal>=90)return;
35
+ // Asymptotic trickle \u2014 fast at first, slower near 90%
36
+ var inc=Math.max(0.4,(90-progVal)*0.08);
37
+ setProgress(progVal+inc);
38
+ },160);
39
+ }
40
+ function finishProgress(){
41
+ if(!o.progress||!progEl)return;
42
+ if(progTimer){clearInterval(progTimer);progTimer=null}
43
+ setProgress(100);
44
+ // Fade out, then reset. Delays chosen so the "full" state is briefly
45
+ // visible before the bar disappears.
46
+ setTimeout(function(){
47
+ if(!progEl)return;
48
+ progEl.style.opacity='0';
49
+ setTimeout(function(){progVal=0;if(progEl)progEl.style.transform='scaleX(0)'},260);
50
+ },180);
51
+ }
52
+
53
+ var cache={};
54
+ var prefetching={};
55
+ var isNavigating=false;
56
+
57
+ // Extract top-level CSS blocks (rules AND @media blocks with nested braces).
58
+ // The old regex ([^{}]+{[^{}]*}) silently dropped @media blocks because
59
+ // it couldn't handle nested braces \u2014 causing responsive classes (lg:, md:)
60
+ // to vanish after SPA navigation.
61
+ function extractCssBlocks(css){
62
+ var blocks=[];
63
+ var i=0;
64
+ var len=css.length;
65
+ while(i<len){
66
+ // Skip whitespace
67
+ while(i<len&&(css[i]===' '||css[i]==='\\n'||css[i]==='\\r'||css[i]==='\\t'))i++;
68
+ if(i>=len)break;
69
+ // Find the start of a block (first {)
70
+ var blockStart=i;
71
+ var bracePos=css.indexOf('{',i);
72
+ if(bracePos===-1)break;
73
+ // Walk forward tracking brace depth to find the matching close
74
+ var depth=0;
75
+ var j=bracePos;
76
+ while(j<len){
77
+ if(css[j]==='{')depth++;
78
+ else if(css[j]==='}'){depth--;if(depth===0){j++;break}}
79
+ j++;
80
+ }
81
+ if(depth!==0)break;
82
+ blocks.push(css.slice(blockStart,j).trim());
83
+ i=j;
84
+ }
85
+ return blocks;
86
+ }
87
+
88
+ function mergeCrosswindCSS(existing,incoming){
89
+ var blocks=extractCssBlocks(incoming);
90
+ var newBlocks=[];
91
+ for(var bi=0;bi<blocks.length;bi++){
92
+ if(existing.indexOf(blocks[bi])===-1)newBlocks.push(blocks[bi]);
93
+ }
94
+ if(newBlocks.length>0)return existing+'\\n'+newBlocks.join('\\n');
95
+ return null;
96
+ }
97
+
98
+ function getContainer(){
99
+ return document.querySelector(containerSel)||document.querySelector('[data-stx-content]')||document.querySelector('main');
100
+ }
101
+
102
+ // \u2500\u2500 Navigation \u2500\u2500
103
+ // Layout group detection \u2014 layouts in the same group share a <main> container.
104
+ // Only truly different layout groups trigger a full page reload.
105
+ var layoutCache={};
106
+ var layoutGroupCache={};
107
+ // Track executed script hashes to prevent redeclaration errors on navigation.
108
+ // Layout-level scripts (theme, nav setup) execute on initial page load and
109
+ // should NOT re-execute when navigating to another page with the same layout.
110
+ var executedScriptHashes={};
111
+ function hashScript(code){
112
+ var h=0;for(var i=0;i<code.length;i++){h=((h<<5)-h)+code.charCodeAt(i);h|=0}
113
+ return h;
114
+ }
115
+ // Record scripts from the initial page load
116
+ document.querySelectorAll('script').forEach(function(s){
117
+ var text=s.textContent||'';
118
+ if(text.trim()&&!s.hasAttribute('src'))executedScriptHashes[hashScript(text)]=1;
119
+ });
120
+ function cacheKey(url){
121
+ var u=new URL(url,location.origin);
122
+ return u.pathname+u.search;
123
+ }
124
+ function defaultLayoutGroup(layout){
125
+ if(!layout)return 'app';
126
+ var clean=String(layout).replace(/\\\\/g,'/');
127
+ var parts=clean.split('/').filter(Boolean);
128
+ var idx=parts.lastIndexOf('layouts');
129
+ var part=idx>=0?parts[idx+1]:parts[parts.length-1];
130
+ return part?part.replace(/\\.stx$/i,''):'app';
131
+ }
132
+ function getCurrentLayoutGroup(){
133
+ var meta=document.querySelector('meta[name="stx-layout-group"]');
134
+ if(meta&&meta.getAttribute('content'))return meta.getAttribute('content');
135
+ var layout=document.querySelector('meta[name="stx-layout"]');
136
+ return defaultLayoutGroup(layout?layout.getAttribute('content'):'');
137
+ }
138
+ function getDocLayoutGroup(doc,layout){
139
+ var meta=doc&&doc.querySelector?doc.querySelector('meta[name="stx-layout-group"]'):null;
140
+ return meta&&meta.getAttribute('content')?meta.getAttribute('content'):defaultLayoutGroup(layout||'');
141
+ }
142
+ function checkLayoutChange(newLayout,targetUrl,newGroup){
143
+ var currentLayout=document.querySelector('meta[name="stx-layout"]');
144
+ var curLayoutName=currentLayout?currentLayout.getAttribute('content'):'';
145
+ var curGroup=getCurrentLayoutGroup();
146
+ var nextGroup=newGroup||defaultLayoutGroup(newLayout);
147
+ log('[router] layout check: current='+curLayoutName+'('+curGroup+') new='+(newLayout||'')+'('+nextGroup+')');
148
+ // Different layout GROUP (e.g. app \u2192 auth): full reload
149
+ if(curGroup!==nextGroup){
150
+ log('[router] layout group change:',curGroup,'\u2192',nextGroup,'\u2014 full reload to:',targetUrl);
151
+ return true;
152
+ }
153
+ // Same group but different SPECIFIC layout (e.g. layouts/app \u2192 layouts/coach):
154
+ // full body swap so nav, sidebar, and other layout-level elements update
155
+ if(curLayoutName && newLayout && curLayoutName!==newLayout){
156
+ log('[router] layout name change:',curLayoutName,'\u2192',newLayout,'\u2014 full body swap');
157
+ return true;
158
+ }
159
+ return false;
160
+ }
161
+
162
+ function navigate(url,pushState,force){
163
+ log('[router] navigate() called:',url,'isNavigating:',isNavigating);
164
+ if(isNavigating)return;
165
+ var t=new URL(url,location.origin);
166
+
167
+ if(t.origin!==location.origin){location.href=url;return}
168
+
169
+ if(t.pathname===location.pathname&&t.hash){
170
+ if(pushState!==false)history.pushState({},'',t.href);
171
+ var el=document.querySelector(t.hash);
172
+ if(el)el.scrollIntoView({behavior:'smooth'});
173
+ return;
174
+ }
175
+
176
+ // Skip if user clicks a link to the page they're already on. We
177
+ // deliberately allow popstate (pushState===false) through because
178
+ // the browser has already updated location.href to the popped
179
+ // entry \u2014 without this allowance, hitting back would early-return
180
+ // and the visible page content would be left frozen on the
181
+ // forward-navigation page.
182
+ if(pushState!==false&&t.href===location.href&&!t.hash&&!force)return;
183
+
184
+ isNavigating=true;
185
+ document.body.classList.add(o.loadingClass);
186
+ startProgress();
187
+
188
+ var targetHref=t.href;
189
+ var targetPath=cacheKey(url);
190
+ var targetHash=t.hash;
191
+
192
+ function done(){isNavigating=false;document.body.classList.remove(o.loadingClass);finishProgress()}
193
+
194
+ if(o.cache&&cache[targetPath]&&!force){
195
+ if(checkLayoutChange(layoutCache[targetPath],url,layoutGroupCache[targetPath])){
196
+ // Layout changed \u2014 fetch full page and do full document swap
197
+ log('[router] cache hit but layout changed \u2014 fetching full page');
198
+ fetch(url,{headers:{'Accept':'text/html'}}).then(function(r){
199
+ if(!r.ok)throw new Error(r.status);
200
+ return r.text();
201
+ }).then(function(html){
202
+ log('[router] full page fetched from cache path, len:',html.length);
203
+ swap(html,targetPath,pushState,targetHash);
204
+ }).catch(function(err){
205
+ console.error('[router] full page fetch error:',err);
206
+ location.href=url;
207
+ }).finally(done);
208
+ return;
209
+ }
210
+ swap(cache[targetPath],targetPath,pushState,targetHash);
211
+ done();
212
+ }
213
+ else {
214
+ if(force&&cache[targetPath])delete cache[targetPath];
215
+ // First fetch as fragment (SPA mode)
216
+ fetch(url,{headers:{'X-STX-Router':'true','Accept':'text/html'}}).then(function(r){
217
+ if(!r.ok)throw new Error(r.status);
218
+ var isFragment=r.headers.get('X-STX-Fragment')==='true';
219
+ var newLayout=r.headers.get('X-STX-Layout')||'';
220
+ var newGroup=r.headers.get('X-STX-Layout-Group')||'';
221
+ // Layout change? Fetch the FULL page (no X-STX-Router header) and do full document swap
222
+ if(isFragment&&checkLayoutChange(newLayout,url,newGroup)){
223
+ log('[router] layout change \u2014 fetching full page for document swap');
224
+ return fetch(url,{headers:{'Accept':'text/html'}}).then(function(fullRes){
225
+ log('[router] full page fetched:',fullRes.status,'ok:',fullRes.ok);
226
+ if(!fullRes.ok)throw new Error(fullRes.status);
227
+ return fullRes.text().then(function(html){
228
+ log('[router] full page html length:',html.length);
229
+ return{html:html,isFragment:false,layout:newLayout,layoutGroup:newGroup};
230
+ });
231
+ });
232
+ }
233
+ return r.text().then(function(html){return{html:html,isFragment:isFragment,layout:newLayout,layoutGroup:newGroup}});
234
+ }).then(function(result){
235
+ if(!result)return;
236
+ if(result.isFragment)result.html='<!--stx-fragment-->'+result.html;
237
+ if(o.cache){cache[targetPath]=result.html;layoutCache[targetPath]=result.layout;layoutGroupCache[targetPath]=result.layoutGroup}
238
+ swap(result.html,targetPath,pushState,targetHash);
239
+ }).catch(function(err){
240
+ console.error('[router] fetch error:',err);
241
+ location.href=url;
242
+ }).finally(done);
243
+ }
244
+ }
245
+
246
+ function swap(html,url,pushState,hash){
247
+ var isFragment=html.indexOf('<!--stx-fragment-->')===0;
248
+ if(isFragment)html=html.slice('<!--stx-fragment-->'.length);
249
+ var currentContent=getContainer();
250
+ log('[router] swap: isFragment='+isFragment+' container='+!!currentContent+' tag='+(currentContent&&currentContent.tagName)+' selector='+containerSel+' htmlLen='+html.length);
251
+ if(!currentContent){log('[router] no container \u2014 falling back');location.href=url;return}
252
+
253
+ // Fragment mode: server returned just the page content (no document wrapper)
254
+ if(isFragment){
255
+ if(window.stx&&window.stx._cleanupContainer)window.stx._cleanupContainer(currentContent);
256
+ function doFragSwap(){
257
+ // Extract scripts from fragment before injecting HTML
258
+ var fragScripts=[];
259
+ var fragStyles=[];
260
+ var fragCrosswindCSS=null;
261
+ var cleanFrag=html.replace(new RegExp('<scr'+'ipt\\\\b[^>]*>([\\\\s\\\\S]*?)<\\\\/scr'+'ipt>','gi'),function(m,code){
262
+ if(code&&code.trim())fragScripts.push(code);
263
+ return '';
264
+ });
265
+ cleanFrag=cleanFrag.replace(new RegExp('<sty'+'le\\\\b([^>]*)>([\\\\s\\\\S]*?)<\\\\/sty'+'le>','gi'),function(m,attrs,css){
266
+ if(attrs.indexOf('data-crosswind')!==-1){
267
+ fragCrosswindCSS=css;
268
+ }else{
269
+ fragStyles.push({attrs:attrs,css:css});
270
+ }
271
+ return '';
272
+ });
273
+ // Remove old page styles (not crosswind \u2014 that gets merged)
274
+ document.querySelectorAll('style[data-stx-page]').forEach(function(s){s.remove()});
275
+ // Merge crosswind CSS from fragment into existing crosswind style
276
+ if(fragCrosswindCSS){
277
+ var curCrosswind=document.querySelector('head style[data-crosswind]');
278
+ if(curCrosswind){
279
+ var merged=mergeCrosswindCSS(curCrosswind.textContent||'',fragCrosswindCSS);
280
+ if(merged)curCrosswind.textContent=merged;
281
+ }else{
282
+ var cw=document.createElement('style');
283
+ cw.setAttribute('data-crosswind','generated');
284
+ cw.textContent=fragCrosswindCSS;
285
+ document.head.appendChild(cw);
286
+ }
287
+ }
288
+ // Add new page styles
289
+ fragStyles.forEach(function(s){
290
+ var el=document.createElement('style');
291
+ el.textContent=s.css;
292
+ el.setAttribute('data-stx-page','');
293
+ document.head.appendChild(el);
294
+ });
295
+ // Swap content
296
+ currentContent.innerHTML=cleanFrag;
297
+ // Remove old page scripts
298
+ document.querySelectorAll('script[data-stx-page]').forEach(function(s){s.remove()});
299
+ if(pushState!==false)history.pushState({},'',url+(hash||''));
300
+ updateNav(url);
301
+ updateActiveLinks();
302
+ if(o.scrollToTop&&!hash)window.scrollTo({top:0,behavior:'instant'});
303
+ else if(hash){var el=document.querySelector(hash);if(el)el.scrollIntoView({behavior:'smooth'})}
304
+ window.dispatchEvent(new CustomEvent('stx:navigate',{detail:{url:url}}));
305
+ // Execute page scripts FIRST \u2014 they define setup functions and set _latestSetup
306
+ log('[router] frag scripts:', fragScripts.length);
307
+ document.querySelectorAll('script[data-stx-page]').forEach(function(s){s.remove()});
308
+ fragScripts.forEach(function(code){
309
+ log('[router] exec script len:', code.length, 'has __stx_setup:', code.indexOf('__stx_setup')>-1);
310
+ // Skip scripts that were already executed (layout-level partials
311
+ // like theme.stx, stores.stx, nav.stx). Their top-level const/let
312
+ // declarations would throw "Identifier has already been declared"
313
+ // on re-execution. Setup functions (__stx_setup_) must always
314
+ // re-execute because each page has its own setup.
315
+ var h=hashScript(code);
316
+ var isSetup=code.indexOf('__stx_setup_')!==-1;
317
+ if(!isSetup&&executedScriptHashes[h]){
318
+ log('[router] skipping already-executed script (hash dedup)');
319
+ return;
320
+ }
321
+ executedScriptHashes[h]=1;
322
+ var ns=document.createElement('script');
323
+ // Wrap in block scope to prevent const/let collisions on re-navigation.
324
+ // Without this, navigating away and back throws "Identifier has already
325
+ // been declared" because the previous page's top-level const/let are
326
+ // still in the global scope.
327
+ var isAlreadyScoped=code.trimStart().charAt(0)==='('||code.trimStart().charAt(0)===';'||code.indexOf('window.stx.mount')>-1;
328
+ ns.textContent=isAlreadyScoped?code:'{'+code+'}';
329
+ ns.setAttribute('data-stx-page','');
330
+ document.body.appendChild(ns);
331
+ });
332
+ log('[router] scripts done. _latestSetup:', !!window.stx._latestSetup);
333
+ // THEN fire stx:load \u2014 now _latestSetup is set and processElement has the right scope
334
+ window.dispatchEvent(new Event('stx:load'));
335
+ }
336
+ if(o.viewTransitions&&document.startViewTransition){document.startViewTransition(doFragSwap)}
337
+ else{currentContent.style.transition='opacity 0.12s ease-out';currentContent.style.opacity='0';setTimeout(function(){doFragSwap();currentContent.style.opacity='1';setTimeout(function(){currentContent.style.transition=''},150)},120)}
338
+ return;
339
+ }
340
+
341
+ // Full document mode: parse with DOMParser and extract container content
342
+ var parser=new DOMParser();
343
+ var doc=parser.parseFromString(html,'text/html');
344
+ var newContent=doc.querySelector(containerSel)||doc.querySelector('[data-stx-content]')||doc.querySelector('main');
345
+ if(!newContent){location.href=url;return}
346
+
347
+ // Clean up existing signals/effects
348
+ if(window.stx&&window.stx._cleanupContainer){
349
+ window.stx._cleanupContainer(currentContent);
350
+ }
351
+
352
+ function doSwap(){
353
+ // \u2500\u2500 Swap <head> styles \u2500\u2500
354
+ // Inject new styles FIRST, then remove old to prevent unstyled flash
355
+ var keepIds={'stx-view-transitions':1,'stx-r-css':1};
356
+ var curStyles=document.querySelectorAll('head style');
357
+ var newStyles=doc.querySelectorAll('head style');
358
+
359
+ // Merge crosswind styles instead of replacing \u2014 persistent elements
360
+ // (nav, footer) outside <main> still need their utility classes
361
+ var curCrosswind=document.querySelector('head style[data-crosswind]');
362
+ var newCrosswind=null;
363
+ newStyles.forEach(function(s){if(s.getAttribute('data-crosswind'))newCrosswind=s});
364
+
365
+ if(curCrosswind&&newCrosswind){
366
+ var merged=mergeCrosswindCSS(curCrosswind.textContent||'',newCrosswind.textContent||'');
367
+ if(merged)curCrosswind.textContent=merged;
368
+ }
369
+
370
+ var incoming=[];
371
+ newStyles.forEach(function(s){
372
+ if(!keepIds[s.id]&&!s.getAttribute('data-crosswind')){
373
+ var ns=document.createElement('style');
374
+ ns.textContent=s.textContent;
375
+ ns.setAttribute('data-stx-incoming','');
376
+ document.head.appendChild(ns);
377
+ incoming.push(ns);
378
+ }
379
+ });
380
+
381
+ // If no existing crosswind but new page has one, add it
382
+ if(!curCrosswind&&newCrosswind){
383
+ var ns=document.createElement('style');
384
+ ns.textContent=newCrosswind.textContent;
385
+ ns.setAttribute('data-crosswind',newCrosswind.getAttribute('data-crosswind'));
386
+ document.head.appendChild(ns);
387
+ }
388
+
389
+ // Remove old styles (except persistent ones, crosswind, and incoming)
390
+ curStyles.forEach(function(s){
391
+ if(!keepIds[s.id]&&!s.hasAttribute('data-stx-incoming')&&!s.hasAttribute('data-crosswind'))s.remove();
392
+ });
393
+
394
+ incoming.forEach(function(s){s.removeAttribute('data-stx-incoming')});
395
+
396
+ // \u2500\u2500 Swap content \u2500\u2500
397
+ // For layout changes: swap the entire <body> to replace layout chrome (nav, footer, etc.)
398
+ // For same-layout: swap only the container (<main>)
399
+ var newBody=doc.querySelector('body');
400
+ var isLayoutChange=false;
401
+ if(newBody){
402
+ var newMeta=doc.querySelector('meta[name="stx-layout"]');
403
+ var curMeta=document.querySelector('meta[name="stx-layout"]');
404
+ var curLayout=curMeta?curMeta.getAttribute('content'):'';
405
+ var newLayout=newMeta?newMeta.getAttribute('content'):'';
406
+ var curGroup=getCurrentLayoutGroup();
407
+ var newGroup=getDocLayoutGroup(doc,newLayout);
408
+ isLayoutChange=curGroup!==newGroup||(curLayout&&newLayout&&curLayout!==newLayout);
409
+ }
410
+ if(isLayoutChange&&newBody){
411
+ log('[router] full body swap for layout change');
412
+ // Replace entire body content \u2014 layout chrome and all
413
+ var bodyHTML=newBody.innerHTML.replace(new RegExp('<scr'+'ipt\\\\b[^>]*>[\\\\s\\\\S]*?<\\\\/scr'+'ipt\\\\s*>','gi'),'');
414
+ document.body.innerHTML=bodyHTML;
415
+ // Copy body attributes (class, data-stx, etc.)
416
+ Array.from(newBody.attributes).forEach(function(attr){document.body.setAttribute(attr.name,attr.value)});
417
+ // Update layout meta tag
418
+ var oldMeta=document.querySelector('meta[name="stx-layout"]');
419
+ var freshMeta=doc.querySelector('meta[name="stx-layout"]');
420
+ if(oldMeta&&freshMeta)oldMeta.setAttribute('content',freshMeta.getAttribute('content')||'');
421
+ else if(freshMeta){var m=document.createElement('meta');m.name='stx-layout';m.content=freshMeta.getAttribute('content')||'';document.head.appendChild(m)}
422
+ var oldGroupMeta=document.querySelector('meta[name="stx-layout-group"]');
423
+ var freshGroupMeta=doc.querySelector('meta[name="stx-layout-group"]');
424
+ if(oldGroupMeta&&freshGroupMeta)oldGroupMeta.setAttribute('content',freshGroupMeta.getAttribute('content')||'');
425
+ else if(freshGroupMeta){var gm=document.createElement('meta');gm.name='stx-layout-group';gm.content=freshGroupMeta.getAttribute('content')||'';document.head.appendChild(gm)}
426
+ // Update container reference for script execution below
427
+ currentContent=document.querySelector(containerSel)||document.querySelector('main')||document.body;
428
+ } else {
429
+ // Same layout \u2014 swap only container content
430
+ var cleanHTML=newContent.innerHTML.replace(new RegExp('<scr'+'ipt\\\\b[^>]*>[\\\\s\\\\S]*?<\\\\/scr'+'ipt\\\\s*>','gi'),'');
431
+ currentContent.innerHTML=cleanHTML;
432
+ }
433
+
434
+ // \u2500\u2500 Load new external <head> scripts \u2500\u2500
435
+ var loadedSrcs={};
436
+ document.querySelectorAll('head script[src]').forEach(function(s){loadedSrcs[s.src]=1});
437
+ var extPromises=[];
438
+ doc.querySelectorAll('head script[src]').forEach(function(s){
439
+ var src=new URL(s.getAttribute('src'),location.origin).href;
440
+ if(loadedSrcs[src])return;
441
+ loadedSrcs[src]=1;
442
+ extPromises.push(new Promise(function(resolve,reject){
443
+ var ns=document.createElement('script');
444
+ ns.src=src;
445
+ ns.onload=resolve;
446
+ ns.onerror=reject;
447
+ document.head.appendChild(ns);
448
+ }));
449
+ });
450
+
451
+ // \u2500\u2500 Script re-execution \u2500\u2500
452
+ // Remove previously injected page scripts
453
+ document.querySelectorAll('script[data-stx-page]').forEach(function(s){s.remove()});
454
+
455
+ var scripts=[];
456
+ if(isLayoutChange){
457
+ // Layout change: collect ALL scripts from the new document body
458
+ // (layout scripts, component mounts, setup functions \u2014 everything)
459
+ var newBodyEl=doc.querySelector('body');
460
+ if(newBodyEl){
461
+ newBodyEl.querySelectorAll('script').forEach(function(s){
462
+ var text=s.textContent||'';
463
+ if(s.hasAttribute('src'))return;
464
+ if(!text.trim())return;
465
+ // Skip the signals runtime IIFE \u2014 it's already loaded
466
+ if(text.indexOf("'use strict';var cloakStyle")!==-1)return;
467
+ if(text.indexOf('__stxRouter')!==-1)return;
468
+ scripts.push(text);
469
+ });
470
+ }
471
+ // Also collect setup functions from <head>
472
+ doc.querySelectorAll('head script').forEach(function(s){
473
+ var text=s.textContent||'';
474
+ if(s.hasAttribute('src'))return;
475
+ if(!text.trim())return;
476
+ if(text.indexOf('__stx_setup_')!==-1)scripts.push(text);
477
+ });
478
+ } else {
479
+ // Same layout: collect scripts from the container
480
+ newContent.querySelectorAll('script').forEach(function(s){
481
+ var text=s.textContent||'';
482
+ if(s.hasAttribute('src'))return;
483
+ if(!text.trim())return;
484
+ scripts.push(text);
485
+ });
486
+ // Collect setup scripts from <head> AND <body> (outside container).
487
+ // SSG builds place the setup function in <body> before <main>, not
488
+ // in <head>. Without this, SPA navigation on static sites never
489
+ // runs the setup and reactive data stays empty.
490
+ var seenSetups={};
491
+ scripts.forEach(function(t){if(t.indexOf('__stx_setup_')!==-1)seenSetups[t.substring(0,80)]=1});
492
+ doc.querySelectorAll('script').forEach(function(s){
493
+ var text=s.textContent||'';
494
+ if(s.hasAttribute('src'))return;
495
+ if(!text.trim())return;
496
+ if(text.indexOf('__stx_setup_')===-1)return;
497
+ // Skip signals runtime and router (they contain __stx_setup references but aren't setup functions)
498
+ if(text.indexOf("'use strict';var cloakStyle")!==-1)return;
499
+ if(text.indexOf('__stxRouter')!==-1)return;
500
+ var key=text.substring(0,80);
501
+ if(seenSetups[key])return;
502
+ seenSetups[key]=1;
503
+ scripts.push(text);
504
+ });
505
+ }
506
+
507
+ // Push history state (before active link updates so location.pathname is current)
508
+ if(pushState!==false)history.pushState({},'',url+(hash||''));
509
+
510
+ // Update active nav links
511
+ updateNav(url);
512
+ updateActiveLinks();
513
+
514
+ // Scroll
515
+ if(o.scrollToTop&&!hash)window.scrollTo({top:0,behavior:'instant'});
516
+ else if(hash){var el=document.querySelector(hash);if(el)el.scrollIntoView({behavior:'smooth'})}
517
+
518
+ // Update title
519
+ var newTitle=doc.querySelector('title');
520
+ if(newTitle)document.title=newTitle.textContent;
521
+
522
+ // Update <html lang> from the destination doc so screen readers,
523
+ // CSS :lang() selectors, and any i18n picker that mirrors
524
+ // document.documentElement.lang stay accurate after SPA hops.
525
+ if(doc.documentElement&&doc.documentElement.lang){
526
+ document.documentElement.lang=doc.documentElement.lang;
527
+ }
528
+
529
+ window.dispatchEvent(new CustomEvent('stx:navigate',{detail:{url:url}}));
530
+
531
+ // Execute page scripts FIRST \u2014 they define setup functions and set _latestSetup
532
+ function execScripts(){
533
+ scripts.forEach(function(text){
534
+ // Skip scripts that were already executed (layout-level partials
535
+ // like theme.stx). Their top-level const/function declarations
536
+ // would throw "Identifier has already been declared" on re-execution.
537
+ // Exception: setup functions (__stx_setup_) must always re-execute
538
+ // because each page has its own setup, and import statements
539
+ // need special handling.
540
+ var h=hashScript(text);
541
+ var isSetup=text.indexOf('__stx_setup_')!==-1;
542
+ var hasImport=text.indexOf('import ')!==-1;
543
+ if(!isSetup&&executedScriptHashes[h])return;
544
+ executedScriptHashes[h]=1;
545
+ // Wrap scripts with import statements as modules (Bug 3 fix)
546
+ var ns=document.createElement('script');
547
+ if(hasImport){
548
+ ns.type='module';
549
+ }
550
+ // Wrap in block scope to prevent const/let collisions on re-navigation.
551
+ // Top-level const/let in <script> tags are global-scoped in browsers
552
+ // and throw "Identifier has already been declared" on re-execution.
553
+ var alreadyScoped=text.trimStart().charAt(0)==='('||text.trimStart().charAt(0)===';'||text.indexOf('window.stx.mount')>-1;
554
+ ns.textContent=alreadyScoped?text:'{'+text+'}';
555
+ ns.setAttribute('data-stx-page','');
556
+ document.body.appendChild(ns);
557
+ });
558
+ // THEN fire stx:load \u2014 now _latestSetup is set and processElement has the right scope
559
+ window.dispatchEvent(new Event('stx:load'));
560
+ }
561
+
562
+ if(extPromises.length>0){
563
+ Promise.all(extPromises).then(execScripts).catch(execScripts);
564
+ }
565
+ else {
566
+ execScripts();
567
+ }
568
+ }
569
+
570
+ if(o.viewTransitions&&document.startViewTransition){
571
+ document.startViewTransition(doSwap);
572
+ }
573
+ else {
574
+ // Fallback fade for browsers without View Transitions API
575
+ currentContent.style.transition='opacity 0.12s ease-out';
576
+ currentContent.style.opacity='0';
577
+ setTimeout(function(){
578
+ doSwap();
579
+ currentContent.style.opacity='1';
580
+ setTimeout(function(){currentContent.style.transition=''},150);
581
+ },120);
582
+ }
583
+ }
584
+
585
+ // \u2500\u2500 Link interception \u2500\u2500
586
+ function shouldIntercept(link){
587
+ if(!link)return false;
588
+ var href=link.getAttribute('href');
589
+ if(!href)return false;
590
+ if(href.startsWith('http')||href.startsWith('#')||href.startsWith('mailto:')||href.startsWith('tel:')||href.startsWith('javascript:'))return false;
591
+ if(link.target==='_blank')return false;
592
+ if(link.hasAttribute('data-stx-no-router')||link.hasAttribute('data-no-router')||link.hasAttribute('download'))return false;
593
+ if(href===location.pathname)return false;
594
+ if(!getContainer())return false;
595
+ return true;
596
+ }
597
+
598
+ // SPA click handling. By default only [data-stx-link] elements get
599
+ // SPA navigation; regular <a href> does native full page reload. Set
600
+ // interceptAllLinks:true (window.__stxRouterConfig or build-time
601
+ // config) to intercept any same-origin anchor \u2014 used by static-site
602
+ // mode where every page is part of the same SPA shell.
603
+ document.addEventListener('click',function(e){
604
+ if(e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;
605
+ if(!e.target||!e.target.closest)return;
606
+ var link=e.target.closest('[data-stx-link]');
607
+ if(!link&&o.interceptAllLinks){
608
+ var anchor=e.target.closest('a[href]');
609
+ if(anchor&&shouldIntercept(anchor))link=anchor;
610
+ }
611
+ if(!link){return}
612
+ var href=link.getAttribute('href');
613
+ log('[router] click intercepted:',href,'container:',!!getContainer(),'defaultPrevented:',e.defaultPrevented);
614
+ if(!href||href.startsWith('http')||href.startsWith('#')||href.startsWith('mailto:')||href.startsWith('tel:')){log('[router] skipped:',href);return}
615
+ if(link.target==='_blank'||link.hasAttribute('download'))return;
616
+ e.preventDefault();
617
+ e.stopPropagation();
618
+ log('[router] navigating to:',href);
619
+ navigate(href);
620
+ },true);
621
+
622
+ // \u2500\u2500 Back/forward \u2500\u2500
623
+ window.addEventListener('popstate',function(){
624
+ navigate(location.pathname+location.search+location.hash,false);
625
+ });
626
+
627
+ // \u2500\u2500 Prefetch on hover \u2500\u2500
628
+ if(o.prefetch){
629
+ document.addEventListener('mouseover',function(e){
630
+ if(!e.target||!e.target.closest)return;
631
+ var link=e.target.closest('[data-stx-link]');
632
+ if(!link)return;
633
+ var href=link.getAttribute('href');
634
+ var key=cacheKey(href);
635
+ if(cache[key]||prefetching[key])return;
636
+ prefetching[key]=true;
637
+ fetch(href,{headers:{'X-STX-Router':'true','Accept':'text/html'}}).then(function(r){
638
+ var isFrag=r.headers.get('X-STX-Fragment')==='true';
639
+ var pLayout=r.headers.get('X-STX-Layout')||'';
640
+ var pGroup=r.headers.get('X-STX-Layout-Group')||'';
641
+ return r.text().then(function(html){return{html:isFrag?'<!--stx-fragment-->'+html:html,layout:pLayout,layoutGroup:pGroup}});
642
+ }).then(function(result){
643
+ if(o.cache){cache[key]=result.html;layoutCache[key]=result.layout;layoutGroupCache[key]=result.layoutGroup}
644
+ }).catch(function(){}).finally(function(){delete prefetching[key]});
645
+ },true);
646
+ }
647
+
648
+ // \u2500\u2500 Active link management \u2500\u2500
649
+ function updateNav(url){
650
+ document.querySelectorAll('nav a[href], #mobileNav a[href], [data-stx-nav] a[href]').forEach(function(a){
651
+ var href=a.getAttribute('href');
652
+ if(!href||href.startsWith('#')||href.startsWith('http'))return;
653
+ var isActive=(href===url)||(href==='/'&&url==='/');
654
+ if(a.hasAttribute('data-stx-link')){
655
+ var ac=a.getAttribute('data-stx-active-class')||'active';
656
+ if(isActive)ac.split(' ').forEach(function(cls){if(cls)a.classList.add(cls)});else ac.split(' ').forEach(function(cls){if(cls)a.classList.remove(cls)});
657
+ }
658
+ });
659
+ }
660
+
661
+ function updateActiveLinks(){
662
+ // Update active classes on <stx-link> elements (and legacy data-stx-link)
663
+ var links=document.querySelectorAll('[data-stx-link]');
664
+ var cur=location.pathname;
665
+ links.forEach(function(link){
666
+ var href=link.getAttribute('to')||link.getAttribute('href')||'';
667
+ var ac=link.getAttribute('active-class')||link.getAttribute('data-stx-active-class')||'active';
668
+ var eac=link.getAttribute('exact-active-class')||link.getAttribute('data-stx-exact-active-class')||'exact-active';
669
+ ac.split(' ').forEach(function(cls){if(cls)link.classList.remove(cls)});
670
+ eac.split(' ').forEach(function(cls){if(cls)link.classList.remove(cls)});
671
+ var isExact=cur===href;
672
+ var isActive=href!=='/'?cur.startsWith(href):cur==='/';
673
+ if(isExact)eac.split(' ').forEach(function(cls){if(cls)link.classList.add(cls)});
674
+ if(isActive)ac.split(' ').forEach(function(cls){if(cls)link.classList.add(cls)});
675
+ });
676
+ }
677
+
678
+ // \u2500\u2500 Progress bar DOM + style \u2500\u2500
679
+ // Injects a fixed-position element at the top of the viewport plus the
680
+ // minimal CSS for its transform/opacity transitions. Kept idempotent so
681
+ // repeated init() calls (e.g. after full-body swaps) don't duplicate.
682
+ // Also ships the default View Transitions fade+slide CSS when
683
+ // viewTransitions is enabled and the browser supports it. Apps can
684
+ // override by defining more specific ::view-transition-* rules later in
685
+ // the cascade, or opt out entirely with viewTransitions:false.
686
+ function injectStyles(){
687
+ if(!document.getElementById('stx-r-css')){
688
+ var s=document.createElement('style');s.id='stx-r-css';
689
+ // Strip characters that could escape our CSS block and inject new
690
+ // declarations: ; { } ( ) " ' \\ < > plus whitespace control chars.
691
+ // This keeps the value safe to concat into a stylesheet even if a
692
+ // caller wires the config from an untrusted source.
693
+ var sanitize=function(v){return String(v).replace(/[;{}()"'\\\\<>\\n\\r\\t]/g,'')};
694
+ var pc=sanitize(o.progressColor);
695
+ var ph=sanitize(o.progressHeight);
696
+ var css='.stx-navigating{cursor:wait}.stx-navigating a,.stx-navigating button{pointer-events:none}#stx-router-progress{position:fixed;top:0;left:0;right:0;height:'+ph+';background:'+pc+';box-shadow:0 0 8px '+pc+',0 0 4px '+pc+';transform:scaleX(0);transform-origin:left;transition:transform .18s ease-out,opacity .26s ease;opacity:0;pointer-events:none;z-index:999999}';
697
+ if(o.viewTransitions&&'startViewTransition' in document){
698
+ var dur=(o.viewTransitionDuration||220)+'ms';
699
+ var ease=o.viewTransitionEasing||'cubic-bezier(0.16, 1, 0.3, 1)';
700
+ css+='::view-transition-old(root),::view-transition-new(root){animation-duration:'+dur+';animation-timing-function:'+ease+'}';
701
+ css+='::view-transition-old(root){animation-name:stx-r-fade-out}::view-transition-new(root){animation-name:stx-r-fade-in}';
702
+ css+='@keyframes stx-r-fade-out{from{opacity:1;transform:translateY(0)}to{opacity:0;transform:translateY(-4px)}}';
703
+ css+='@keyframes stx-r-fade-in{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:translateY(0)}}';
704
+ css+='@media (prefers-reduced-motion: reduce){::view-transition-old(root),::view-transition-new(root){animation-duration:0s;animation-name:none}}';
705
+ }
706
+ s.textContent=css;
707
+ document.head.appendChild(s);
708
+ }
709
+ if(o.progress&&!document.getElementById('stx-router-progress')){
710
+ var el=document.createElement('div');
711
+ el.id='stx-router-progress';
712
+ el.setAttribute('role','progressbar');
713
+ el.setAttribute('aria-hidden','true');
714
+ // Append to <html>, not <body>: when the router swaps the body
715
+ // (container:'body' for full-page static-site SPAs) the progress
716
+ // element gets wiped along with it. <html> stays put across
717
+ // swaps, so the bar survives multi-hop navigation.
718
+ document.documentElement.appendChild(el);
719
+ progEl=el;
720
+ } else if(o.progress){
721
+ progEl=document.getElementById('stx-router-progress');
722
+ }
723
+ }
724
+
725
+ function injectViewTransitionCSS(){
726
+ if(document.getElementById('stx-view-transitions'))return;
727
+ var s=document.createElement('style');s.id='stx-view-transitions';
728
+ s.textContent='::view-transition-group(root){animation:none}::view-transition-old(root){animation:none}::view-transition-new(root){animation:none}main,#app-content,[data-stx-content]{view-transition-name:stx-content}::view-transition-old(stx-content){animation:stx-fade-out .15s ease-out both}::view-transition-new(stx-content){animation:stx-fade-in .15s ease-in .1s both}@keyframes stx-fade-out{from{opacity:1}to{opacity:0}}@keyframes stx-fade-in{from{opacity:0}to{opacity:1}}::view-transition{background:transparent}::view-transition-group(stx-content){background:inherit;overflow:hidden}';
729
+ (document.head||document.documentElement).appendChild(s);
730
+ }
731
+
732
+ // \u2500\u2500 Public API \u2500\u2500
733
+ var router={
734
+ navigate:navigate,
735
+ navigateTo:navigate,
736
+ prefetch:function(url){
737
+ var key=cacheKey(url);
738
+ if(!cache[key]){
739
+ fetch(url,{headers:{'X-STX-Router':'true'}}).then(function(r){var isFrag=r.headers.get('X-STX-Fragment')==='true';var pLayout=r.headers.get('X-STX-Layout')||'';var pGroup=r.headers.get('X-STX-Layout-Group')||'';return r.text().then(function(html){return{html:isFrag?'<!--stx-fragment-->'+html:html,layout:pLayout,layoutGroup:pGroup}})}).then(function(result){cache[key]=result.html;layoutCache[key]=result.layout;layoutGroupCache[key]=result.layoutGroup}).catch(function(){});
740
+ }
741
+ },
742
+ clearCache:function(){for(var k in cache)delete cache[k];for(var lk in layoutCache)delete layoutCache[lk];for(var gk in layoutGroupCache)delete layoutGroupCache[gk]},
743
+ cache:cache,
744
+ swap:swap,
745
+ updateNav:updateNav
746
+ };
747
+
748
+ window.__stxRouter=router;
749
+ window.stxRouter=router;
750
+ if(window.stx)window.stx.router=router;
751
+
752
+ // \u2500\u2500 Initialize \u2500\u2500
753
+ function init(){
754
+ injectStyles();
755
+ injectViewTransitionCSS();
756
+ updateActiveLinks();
757
+ updateNav(location.pathname);
758
+ }
759
+
760
+ if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',init);else init();
761
+ })();
762
+ `;
763
+ }
764
+ export {
765
+ getRouterScript
766
+ };
767
+
768
+ //# debugId=A4C84E765CFC895664756E2164756E21