@stacksjs/stx 0.2.405 → 0.2.407

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (212) hide show
  1. package/dist/app-service-worker.d.ts +120 -0
  2. package/dist/chunk-00g9x6w2.js +2 -0
  3. package/dist/chunk-02g67164.js +2 -0
  4. package/dist/chunk-04tgatyy.js +2 -0
  5. package/dist/{chunk-et9knn3s.js → chunk-0a315nbf.js} +3 -3
  6. package/dist/{chunk-zwb8wv5p.js → chunk-0akydm2d.js} +1 -1
  7. package/dist/{chunk-tfy07tmv.js → chunk-0btmm4m2.js} +1 -1
  8. package/dist/{chunk-g0w8dyat.js → chunk-0c2h69k2.js} +1 -1
  9. package/dist/{chunk-aa4ss5pb.js → chunk-0pkk226n.js} +1 -1
  10. package/dist/{chunk-6de3hczw.js → chunk-0we9nw1d.js} +1 -1
  11. package/dist/chunk-178n9c40.js +2 -0
  12. package/dist/{chunk-2r399td7.js → chunk-1fs9jvpb.js} +1 -1
  13. package/dist/chunk-1hc58sh2.js +2 -0
  14. package/dist/chunk-1q4jrkhw.js +2 -0
  15. package/dist/chunk-1qembpzh.js +2 -0
  16. package/dist/chunk-1qq26zt0.js +2 -0
  17. package/dist/{chunk-7q06md6v.js → chunk-1te8k8gp.js} +1 -1
  18. package/dist/{chunk-jw6s8rkk.js → chunk-1ws3xcea.js} +2 -2
  19. package/dist/{chunk-z9a0ft6h.js → chunk-213jwgpx.js} +1 -1
  20. package/dist/{chunk-c7n0gsxa.js → chunk-26r88x1t.js} +2 -2
  21. package/dist/{chunk-k4x5we49.js → chunk-27fgag95.js} +2 -2
  22. package/dist/chunk-2c6t60vw.js +2 -0
  23. package/dist/{chunk-x7qyx7vn.js → chunk-2fw05hs2.js} +1 -1
  24. package/dist/{chunk-0seyntda.js → chunk-38wvkv3s.js} +1 -1
  25. package/dist/chunk-3w6z6tw9.js +2 -0
  26. package/dist/chunk-3za7m29m.js +2 -0
  27. package/dist/{chunk-ypw4egcv.js → chunk-4m7ajama.js} +1 -1
  28. package/dist/{chunk-1309n807.js → chunk-4zcbj36p.js} +2 -2
  29. package/dist/{chunk-yh9apppb.js → chunk-50pszj17.js} +1 -1
  30. package/dist/{chunk-59pakqdv.js → chunk-563shnkz.js} +2 -2
  31. package/dist/{chunk-zcrb5hgk.js → chunk-5r4s9s38.js} +2 -2
  32. package/dist/chunk-603x5gb2.js +2 -0
  33. package/dist/{chunk-afwbqeb2.js → chunk-6jrczd12.js} +2 -2
  34. package/dist/{chunk-abs56gdt.js → chunk-6kd5jjwc.js} +1 -1
  35. package/dist/{chunk-ewxbx67c.js → chunk-6kdrncsx.js} +1 -1
  36. package/dist/{chunk-pkspqh0m.js → chunk-72rwcbp6.js} +1 -1
  37. package/dist/{chunk-4m4n1sfc.js → chunk-76w34xne.js} +1 -1
  38. package/dist/chunk-7ypm243n.js +2 -0
  39. package/dist/{chunk-kdabbmbf.js → chunk-8036mdat.js} +2 -2
  40. package/dist/{chunk-46zx4pt8.js → chunk-82pd4b5w.js} +1 -1
  41. package/dist/chunk-8ds7rrdc.js +2 -0
  42. package/dist/chunk-8w2mqdnv.js +2 -0
  43. package/dist/chunk-8x05b790.js +2 -0
  44. package/dist/{chunk-pqhpcxsd.js → chunk-90b2vt2n.js} +1 -1
  45. package/dist/{chunk-g6c4f67z.js → chunk-920779jx.js} +2 -2
  46. package/dist/chunk-934eeghd.js +2 -0
  47. package/dist/{chunk-245ft0zp.js → chunk-9e8t0twa.js} +1 -1
  48. package/dist/{chunk-wpsx5avz.js → chunk-9fqp72ze.js} +1 -1
  49. package/dist/chunk-9wze2290.js +2 -0
  50. package/dist/{chunk-dj658wyq.js → chunk-9xew0kgf.js} +1 -1
  51. package/dist/{chunk-ca57sg6v.js → chunk-akwd34xt.js} +2 -2
  52. package/dist/{chunk-rqr735w8.js → chunk-anydpa34.js} +1 -1
  53. package/dist/{chunk-ffdxdgep.js → chunk-aq1xq0r4.js} +2 -2
  54. package/dist/{chunk-2xr974bj.js → chunk-avaywwsc.js} +2 -2
  55. package/dist/{chunk-36rnwhn2.js → chunk-bbt3tp6f.js} +1 -1
  56. package/dist/{chunk-n4197kjq.js → chunk-bjar18jd.js} +1 -1
  57. package/dist/{chunk-twg0y6ga.js → chunk-bjcsc6wx.js} +1 -1
  58. package/dist/{chunk-akzmq0jr.js → chunk-bn1edb1y.js} +2 -2
  59. package/dist/{chunk-503wfstj.js → chunk-btd7ds3x.js} +1 -1
  60. package/dist/{chunk-8mm86z5w.js → chunk-bwsxym3d.js} +1 -1
  61. package/dist/{chunk-c1f1vtjt.js → chunk-cj3adc77.js} +1 -1
  62. package/dist/{chunk-w9b94q64.js → chunk-cqchpe34.js} +396 -165
  63. package/dist/chunk-ct1jwd4r.js +2 -0
  64. package/dist/{chunk-c8kfqw8x.js → chunk-ej16bgrr.js} +2 -2
  65. package/dist/{chunk-s68jqmva.js → chunk-esq1k7fj.js} +2 -2
  66. package/dist/{chunk-fnabq4w1.js → chunk-f6s7d1jq.js} +2 -2
  67. package/dist/{chunk-bds4s9d8.js → chunk-fcnrgxck.js} +1 -1
  68. package/dist/chunk-fphs5g19.js +2 -0
  69. package/dist/{chunk-stdkw5st.js → chunk-fpwzacpm.js} +1 -1
  70. package/dist/chunk-gbmeh7jg.js +3 -0
  71. package/dist/{chunk-81zw5vw5.js → chunk-gc06g35w.js} +1 -1
  72. package/dist/{chunk-a389vxsn.js → chunk-gcvj5zdy.js} +3 -3
  73. package/dist/{chunk-yt9mq4m7.js → chunk-gengvwb7.js} +3 -3
  74. package/dist/{chunk-78rd6wxv.js → chunk-gjrgr367.js} +2 -2
  75. package/dist/{chunk-h8ej17sj.js → chunk-gna6dc48.js} +169 -169
  76. package/dist/{chunk-pyyccs6a.js → chunk-gvbf1mhs.js} +1 -1
  77. package/dist/chunk-h1r17awz.js +2 -0
  78. package/dist/chunk-ha46rg9g.js +2 -0
  79. package/dist/chunk-hcvjstmr.js +2 -0
  80. package/dist/{chunk-a01sf1sc.js → chunk-hdysywd8.js} +1 -1
  81. package/dist/{chunk-55g4qm7m.js → chunk-hx998w7n.js} +1 -1
  82. package/dist/chunk-j3r97xs5.js +2 -0
  83. package/dist/chunk-j5qeaprt.js +2 -0
  84. package/dist/chunk-jxvmf02k.js +2 -0
  85. package/dist/{chunk-8t3h7fsk.js → chunk-k80sn8d1.js} +1 -1
  86. package/dist/chunk-kajym1cx.js +2 -0
  87. package/dist/{chunk-6efr4j9h.js → chunk-kbwhs5df.js} +2 -2
  88. package/dist/{chunk-4n6ekt06.js → chunk-kmsyvaex.js} +1 -1
  89. package/dist/{chunk-4tsjysng.js → chunk-kvmx7dnb.js} +1 -1
  90. package/dist/{chunk-y8hp05y6.js → chunk-m072c38p.js} +2 -2
  91. package/dist/{chunk-jpnja3jy.js → chunk-mgrckqww.js} +1 -1
  92. package/dist/{chunk-971yqxa2.js → chunk-mq5ewmz6.js} +1 -1
  93. package/dist/{chunk-sptvg80e.js → chunk-mrahwn5v.js} +1 -1
  94. package/dist/{chunk-vyq86x5c.js → chunk-n2swas11.js} +1 -1
  95. package/dist/{chunk-rwwt24e3.js → chunk-n9cqrw9j.js} +1 -1
  96. package/dist/{chunk-3sea73fx.js → chunk-naw4jt7j.js} +1 -1
  97. package/dist/{chunk-1n2ng8nx.js → chunk-ny67c03k.js} +1 -1
  98. package/dist/chunk-p0m4ty6g.js +2 -0
  99. package/dist/chunk-p32x2apf.js +2 -0
  100. package/dist/{chunk-8bg1qmhg.js → chunk-p4zrvt5f.js} +1 -1
  101. package/dist/{chunk-0tnsyynz.js → chunk-p5wp0ce6.js} +2 -2
  102. package/dist/{chunk-mywrb5fy.js → chunk-pcxp4r9n.js} +1 -1
  103. package/dist/{chunk-5fwgczvh.js → chunk-pdfjy3at.js} +2 -2
  104. package/dist/chunk-pjrn29gg.js +2 -0
  105. package/dist/chunk-q738pwv6.js +2 -0
  106. package/dist/{chunk-w6n5c479.js → chunk-qmmp5kb5.js} +1 -1
  107. package/dist/{chunk-015p3jq5.js → chunk-qn5srnj3.js} +1 -1
  108. package/dist/{chunk-1vrk5y92.js → chunk-qvnbnsv9.js} +1 -1
  109. package/dist/{chunk-z8zmp74b.js → chunk-rt3cx932.js} +1025 -58
  110. package/dist/{chunk-7ba7x6jt.js → chunk-rz9f3zqz.js} +2 -2
  111. package/dist/{chunk-dxjtszaa.js → chunk-s8jd13nb.js} +1 -1
  112. package/dist/{chunk-qem2tw9r.js → chunk-s9za1vvd.js} +1 -1
  113. package/dist/{chunk-r909bddf.js → chunk-spxsw4mp.js} +1 -1
  114. package/dist/chunk-ssn5k77d.js +2 -0
  115. package/dist/chunk-sy9pfe3h.js +2 -0
  116. package/dist/{chunk-0nhpymyy.js → chunk-t1htzg9e.js} +1 -1
  117. package/dist/{chunk-rkzfwgr8.js → chunk-t1tdjjht.js} +1 -1
  118. package/dist/{chunk-1x6c4ys1.js → chunk-t5ja7qkn.js} +131 -34
  119. package/dist/{chunk-rx0cntdm.js → chunk-td08rnk3.js} +2 -2
  120. package/dist/chunk-tgadbsd4.js +2 -0
  121. package/dist/{chunk-xakdgn9h.js → chunk-tgrpp58r.js} +1 -1
  122. package/dist/{chunk-pgeh4g3a.js → chunk-tkyrk66a.js} +1 -1
  123. package/dist/chunk-tpcmn119.js +2 -0
  124. package/dist/{chunk-0n054h7w.js → chunk-v3nwkveg.js} +1 -1
  125. package/dist/{chunk-83tefmh1.js → chunk-vsbmc9kt.js} +1 -1
  126. package/dist/{chunk-qcpnfw0k.js → chunk-vx86cf4r.js} +1 -1
  127. package/dist/{chunk-n9cgqg0x.js → chunk-w6hqh4z5.js} +2 -2
  128. package/dist/{chunk-nqpd84vs.js → chunk-w9n12yzf.js} +3 -3
  129. package/dist/chunk-wkanrfb3.js +2 -0
  130. package/dist/chunk-wvegegmb.js +2 -0
  131. package/dist/{chunk-seqmzr8k.js → chunk-xq1acw1r.js} +1 -1
  132. package/dist/{chunk-vtjegbgy.js → chunk-xsng1mtq.js} +1 -1
  133. package/dist/chunk-xv9bhvye.js +12 -0
  134. package/dist/{chunk-a8ypw36d.js → chunk-z52f4zcy.js} +2 -2
  135. package/dist/{chunk-vtmhh3dp.js → chunk-z5rwnnk1.js} +2 -2
  136. package/dist/{chunk-m8bdy2wt.js → chunk-zcz9rs6p.js} +1 -1
  137. package/dist/{chunk-1phxzej9.js → chunk-zpcnbdhn.js} +2 -2
  138. package/dist/{chunk-wxkn47vk.js → chunk-zq4ssxj9.js} +1 -1
  139. package/dist/cli.js +14 -14
  140. package/dist/composables/index.d.ts +10 -1
  141. package/dist/composables/index.js +6 -1
  142. package/dist/composables/use-cached-query.d.ts +18 -0
  143. package/dist/composables/use-cached-query.js +27 -0
  144. package/dist/composables/use-offline.d.ts +18 -0
  145. package/dist/composables/use-offline.js +17 -0
  146. package/dist/composables/use-outbox.d.ts +19 -27
  147. package/dist/composables/use-outbox.js +100 -16
  148. package/dist/composables/use-query.d.ts +2 -0
  149. package/dist/composables/use-storage.d.ts +7 -3
  150. package/dist/composables/use-storage.js +22 -13
  151. package/dist/craft-entry.js +1 -1
  152. package/dist/craft.js +1 -1
  153. package/dist/database.js +1 -1
  154. package/dist/index.d.ts +10 -0
  155. package/dist/index.js +5 -0
  156. package/dist/offline/app-service-worker.d.ts +61 -13
  157. package/dist/offline/app-service-worker.js +398 -58
  158. package/dist/offline/kept-store.d.ts +67 -0
  159. package/dist/offline/kept-store.js +252 -0
  160. package/dist/offline/query-cache.d.ts +137 -0
  161. package/dist/offline/query-cache.js +260 -0
  162. package/dist/pwa.js +2 -2
  163. package/dist/runtime-globals.js +3 -0
  164. package/dist/signal-processing.js +5 -0
  165. package/dist/signals.js +123 -24
  166. package/dist/ssg.js +2 -2
  167. package/dist/stx-module.d.ts +3 -0
  168. package/dist/stx.d.ts +48 -1
  169. package/dist/unresolved-identifiers.js +2 -0
  170. package/dist/visual-testing.js +1 -1
  171. package/package.json +5 -5
  172. package/stx-module.d.ts +3 -0
  173. package/stx.d.ts +48 -1
  174. package/dist/chunk-0ek2mj5x.js +0 -2
  175. package/dist/chunk-241cvbas.js +0 -2
  176. package/dist/chunk-2ryg907a.js +0 -2
  177. package/dist/chunk-4k471790.js +0 -2
  178. package/dist/chunk-4md4tj27.js +0 -3
  179. package/dist/chunk-65yty69p.js +0 -2
  180. package/dist/chunk-68gspceh.js +0 -2
  181. package/dist/chunk-ad7q7zff.js +0 -2
  182. package/dist/chunk-anwxcm8j.js +0 -2
  183. package/dist/chunk-cvtxk36x.js +0 -2
  184. package/dist/chunk-dgd8jyaz.js +0 -2
  185. package/dist/chunk-emx4ey5d.js +0 -2
  186. package/dist/chunk-fg48tp2x.js +0 -2
  187. package/dist/chunk-fwvbmmb3.js +0 -2
  188. package/dist/chunk-gg3hm3kq.js +0 -2
  189. package/dist/chunk-hs9g1dpr.js +0 -2
  190. package/dist/chunk-jndc710n.js +0 -2
  191. package/dist/chunk-jqm6tbtb.js +0 -2
  192. package/dist/chunk-jrzw9782.js +0 -2
  193. package/dist/chunk-k66qphdp.js +0 -2
  194. package/dist/chunk-n1yz08j4.js +0 -2
  195. package/dist/chunk-nsese4as.js +0 -2
  196. package/dist/chunk-pmy5k4kn.js +0 -12
  197. package/dist/chunk-pvzbsjcw.js +0 -2
  198. package/dist/chunk-qdc3yj82.js +0 -2
  199. package/dist/chunk-rjkgqegg.js +0 -2
  200. package/dist/chunk-rrkjjyqb.js +0 -2
  201. package/dist/chunk-rstz7e7c.js +0 -2
  202. package/dist/chunk-sgmqfphy.js +0 -2
  203. package/dist/chunk-sw89c1b7.js +0 -2
  204. package/dist/chunk-vfjccz8p.js +0 -2
  205. package/dist/chunk-w9v7fstr.js +0 -2
  206. package/dist/chunk-wj66sab5.js +0 -2
  207. package/dist/chunk-wqgyb4zb.js +0 -2
  208. package/dist/chunk-wz7ca99x.js +0 -2
  209. package/dist/chunk-xw23twxw.js +0 -2
  210. package/dist/chunk-y3cz15x3.js +0 -2
  211. package/dist/chunk-ybm9ac7z.js +0 -2
  212. package/dist/chunk-yf0v44v8.js +0 -2
@@ -1,14 +1,14 @@
1
1
  // @bun
2
- import{$w as v$,ax as G}from"./chunk-x7qyx7vn.js";function y($){return $.split(/[\\/]/).filter(Boolean).slice(0,-1).some((O)=>F.includes(O))}function A($){return y($.replace(/^\//,""))}var F;var C=G(()=>{F=["components","layouts","partials","emails"]});import W from"fs";import E from"path";function H($,U){let O=$.filter((K)=>!A(K.pattern)),I=["// Auto-generated by STX - do not edit"];if(O.length===0)I.push("// No page routes found \u2014 route paths stay typed as string.","export {}","");else{I.push("declare module '@stacksjs/stx' {"," interface KnownRoutes {");for(let K of O){let V=[];for(let X of K.params){let Y=K.pattern.includes(`:${X}?`)?"?":"";V.push(`${X}${Y}: string`)}let J=V.join("; ");I.push(` '${K.pattern}': { ${J} }`)}I.push(" }","}","","export {}","")}let B=I.join(`
2
+ import{gx as v$,hx as G}from"./chunk-2fw05hs2.js";function y($){return $.split(/[\\/]/).filter(Boolean).slice(0,-1).some((O)=>F.includes(O))}function A($){return y($.replace(/^\//,""))}var F;var C=G(()=>{F=["components","layouts","partials","emails"]});import W from"fs";import E from"path";function H($,U){let O=$.filter((K)=>!A(K.pattern)),I=["// Auto-generated by STX - do not edit"];if(O.length===0)I.push("// No page routes found \u2014 route paths stay typed as string.","export {}","");else{I.push("declare module '@stacksjs/stx' {"," interface KnownRoutes {");for(let K of O){let V=[];for(let X of K.params){let Y=K.pattern.includes(`:${X}?`)?"?":"";V.push(`${X}${Y}: string`)}let J=V.join("; ");I.push(` '${K.pattern}': { ${J} }`)}I.push(" }","}","","export {}","")}let B=I.join(`
3
3
  `),L=E.join(U,"route-types.d.ts");try{if(W.existsSync(L)&&W.readFileSync(L,"utf8")===B)return;W.mkdirSync(U,{recursive:!0}),W.writeFileSync(L,B)}catch{}}function q($,U,O){let I=process.cwd(),B=E.relative(I,O),L=$.filter((V)=>!A(V.pattern)),K=["// Auto-generated by stx \u2014 do not edit",`// Source: ${B||"pages"}/`,"","export const routes = ["];for(let V of L){let J=E.relative(I,V.filePath).replace(/\\/g,"/"),X=JSON.stringify(V.params),Y=V.layout?`, layout: '${E.relative(I,V.layout).replace(/\\/g,"/")}'`:"";K.push(` { pattern: '${V.pattern}', filePath: '${J}', isDynamic: ${V.isDynamic}, params: ${X}${Y} },`)}K.push("] as const",""),K.push("export type RouteName = typeof routes[number]['pattern']",""),W.mkdirSync(U,{recursive:!0}),W.writeFileSync(E.join(U,"routes.ts"),K.join(`
4
- `))}var f=G(()=>{C()});import i from"path";function N($,U){let I=i.relative(U,$).replace(/\.(stx|md)$/,"");if(I=I.split(i.sep).join("/"),I==="index")return"/";if(I.endsWith("/index"))I=I.slice(0,-6);return I=I.replace(/\[\[([^\]]+)\]\]/g,":$1?"),I=I.replace(/\[([^\]]+)\]/g,":$1"),I=I.replace(/:\.\.\.([^/]+)/g,":$1*"),`/${I}`}function j($){let U=[],O="",I=0;while(I<$.length){let B=$.slice(I),L=/^\/:([^/?*]+)\?/.exec(B);if(L){U.push(L[1]),O+="(?:/([^/]+))?",I+=L[0].length;continue}let K=/^:([^/?*]+)\*/.exec(B);if(K){U.push(K[1]),O+="(.+)",I+=K[0].length;continue}let V=/^:([^/?*]+)/.exec(B);if(V){U.push(V[1]),O+="([^/]+)",I+=V[0].length;continue}O+=$[I].replace(/[.+^${}()|[\]\\*?]/g,"\\$&"),I+=1}return{regex:new RegExp(`^${O}$`),params:U}}function o($,U){let O=$===""?"/":$;for(let I of U){let B=O.match(I.regex);if(B){let L={};return I.params.forEach((K,V)=>{L[K]=B[V+1]}),{route:I,params:L}}}return null}function r($){let U=$.replace(/\[\[([^\]]+)\]\]/g,":$1?").replace(/\[([^\]]+)\]/g,":$1").replace(/:\.\.\.([^/]+)/g,":$1*");return j(U)}var g=()=>{};import b$ from"fs";import d from"path";function R($,U){let O=[],I=d.dirname($);while(I.startsWith(U)||I===U){let B=d.join(I,"_layout.stx");if(b$.existsSync(B))O.unshift(B);if(I===U)break;I=d.dirname(I)}return O}var m=()=>{};import S from"fs";import Q from"path";function t($,U){let O=[];if(!S.existsSync($))return O;let I=S.readdirSync($,{withFileTypes:!0});for(let B of I){let L=Q.join($,B.name);if(B.isDirectory()){if(B.name.startsWith("."))continue;if(F.includes(B.name))continue;O.push(...t(L,U))}else if(B.isFile()){let K=Q.extname(B.name);if(U.includes(K)){if(B.name.startsWith("_")&&B.name!=="_layout.stx")continue;if(B.name==="_layout.stx")continue;O.push(L)}}}return O}class b{routes;pagesDir;pagesDirs;config;constructor($,U={}){this.config=U;let O=U.pagesDirs&&U.pagesDirs.length>0?U.pagesDirs:[U.pagesDir||"pages"];this.pagesDirs=O.map((J)=>Q.resolve($,J)),this.pagesDir=this.pagesDirs[0];let I=U.extensions||[".stx"],B=(J)=>{let X=Q.resolve($,J);try{return S.realpathSync(X)}catch{return X}},L=(U.exclude??[]).filter((J)=>typeof J==="string"&&J.trim()!=="").map(B),K=(J)=>{if(L.length===0)return!1;let X=B(J);return L.some((Y)=>X===Y||X.startsWith(`${Y}${Q.sep}`))},V=new Set;this.routes=[];for(let J of this.pagesDirs){let X=t(J,I).filter((Z)=>!K(Z)),Y=new Map;for(let Z of X){let _=N(Z,J),z=U.pagesDirs?_.replace(/:[\w]+/g,":param"):_;if(U.pagesDirs&&Y.has(z))throw Error(`Conflicting layer pages for ${_}: ${Y.get(z)} and ${Z}`);if(Y.set(z,Z),V.has(z))continue;V.add(z);let{regex:S$,params:s}=j(_),D=U.layouts!==!1?R(Z,J):[];this.routes.push({pattern:_,regex:S$,params:s,filePath:Z,isDynamic:s.length>0,layout:D.length>0?D[D.length-1]:void 0})}}if(this.routes.sort((J,X)=>{if(!J.isDynamic&&X.isDynamic)return-1;if(J.isDynamic&&!X.isDynamic)return 1;let Y=J.pattern.split("/").length,Z=X.pattern.split("/").length;if(Y!==Z)return Z-Y;return J.pattern.localeCompare(X.pattern)}),U.emit!==!1){let J=Q.resolve($,U.stateDir||process.env.STX_DIR?.trim()||".stx");H(this.routes,J),q(this.routes,J,this.pagesDir)}}match($){let U=$===""?"/":$;for(let O of this.routes){let I=U.match(O.regex);if(I){let B={};return O.params.forEach((L,K)=>{B[L]=I[K+1]}),{route:O,params:B}}}return null}resolve($,U){let O=this.routes.find((B)=>B.pattern===$||B.filePath.includes($));if(!O)return"#not-found";let I=O.pattern;if(U)for(let[B,L]of Object.entries(U))I=I.replace(`:${B}`,encodeURIComponent(L));return I}addRoute($){this.routes.push($),this.routes.sort((U,O)=>{if(!U.isDynamic&&O.isDynamic)return-1;if(U.isDynamic&&!O.isDynamic)return 1;return U.pattern.localeCompare(O.pattern)})}getLayout($){return $.layout??null}}function a($,U){return new b($,U)}function e($,U){let O=[`${U}.stx`,"error.stx"];for(let I of O){let B=Q.join($,I);if(S.existsSync(B))return B}return null}function $$($,U){return $.map((O)=>{let I=Q.relative(U,O.filePath),B=O.isDynamic?" (dynamic)":"";return`${O.pattern} \u2192 ${I}${B}`})}var U$=G(()=>{f();g();m();C()});function I$($){x=$.replace(/\/$/,"")}function O$($,U,O={}){M[$]={path:U,name:$,params:O}}function B$($){for(let[U,O]of Object.entries($))if(typeof O==="string")M[U]={path:O,name:U};else M[U]={...O,name:U}}function J$($,U={},O=!1){let I=M[$];if(!I)return console.warn(`Route [${$}] not defined.`),"#undefined-route";let B={...I.params,...U},L=I.path;L=L.replace(/:(\w+)/g,(V,J)=>{let X=B[J];if(X===void 0)return console.warn(`Missing parameter [${J}] for route [${$}].`),`:${J}`;return delete B[J],encodeURIComponent(String(X))});let K=Object.entries(B);if(K.length>0){let V=K.map(([J,X])=>`${encodeURIComponent(J)}=${encodeURIComponent(String(X))}`).join("&");L+=(L.includes("?")?"&":"?")+V}return O&&x?`${x}${L}`:L}function K$(){for(let $ of Object.keys(M))delete M[$];x=""}var M,x="";var L$=G(()=>{M={}});import V$ from"fs";import X$ from"path";function Y$($,U={}){return{type:"redirect",path:$,options:{replace:U.replace??!1,external:U.external??!1,redirectCode:U.redirectCode??302}}}function Z$($){return{type:"abort",error:typeof $==="string"?{statusCode:500,message:$}:$}}function G$($,U={}){return{handler:$,mode:U.mode??"universal"}}function h($){let U={};if(!$)return U;let O=$.split(";");for(let I of O){let[B,...L]=I.split("=");if(B){let K=B.trim(),V=L.join("=").trim();if(K)U[K]=decodeURIComponent(V)}}return U}function k($,U,O={}){let I=`${encodeURIComponent($)}=${encodeURIComponent(U)}`;if(O.expires){let B=typeof O.expires==="number"?new Date(Date.now()+O.expires*1000):O.expires;I+=`; Expires=${B.toUTCString()}`}if(O.path)I+=`; Path=${O.path}`;if(O.domain)I+=`; Domain=${O.domain}`;if(O.secure)I+="; Secure";if(O.httpOnly)I+="; HttpOnly";if(O.sameSite)I+=`; SameSite=${O.sameSite}`;return I}function c($,U){let O=$.headers.get("cookie")||"",I=h(O);return{get(B){return I[B]},set(B,L,K={}){I[B]=L,U.append("Set-Cookie",k(B,L,K))},delete(B){delete I[B],U.append("Set-Cookie",k(B,"",{expires:new Date(0),path:"/"}))},getAll(){return{...I}}}}function l(){return{get($){if(typeof document>"u")return;return h(document.cookie)[$]},set($,U,O={}){if(typeof document>"u")return;document.cookie=k($,U,O)},delete($){if(typeof document>"u")return;document.cookie=k($,"",{expires:new Date(0),path:"/"})},getAll(){if(typeof document>"u")return{};return h(document.cookie)}}}function u(){let $=typeof window<"u"&&typeof window.localStorage<"u";return{get(U){if(!$)return null;try{return window.localStorage.getItem(U)}catch{return null}},set(U,O){if(!$)return;try{window.localStorage.setItem(U,O)}catch{}},remove(U){if(!$)return;try{window.localStorage.removeItem(U)}catch{}},isAvailable(){return $}}}function v($,U){T.set($,U)}function p($){return T.get($)}function Q$($){return T.has($)}function W$(){T.clear()}function M$(){return Array.from(T.keys())}async function _$($,U="middleware"){let O=X$.resolve($,U);if(!V$.existsSync(O))return;let I=V$.readdirSync(O);for(let B of I){if(!B.endsWith(".ts")&&!B.endsWith(".js"))continue;if(B.includes(".test.")||B.includes(".spec."))continue;let L=B.replace(/\.(ts|js)$/,""),K=X$.join(O,B);try{let J=(await import(K)).default;if(J&&typeof J.handler==="function")v(L,J);else if(typeof J==="function")v(L,{handler:J,mode:"universal"})}catch(V){console.warn(`Failed to load middleware '${L}' from ${K}:`,V)}}}function x$($){let U={};if(!$)return U;let O=new URLSearchParams($);for(let[I,B]of O)U[I]=B;return U}function z$($,U,O,I=""){return{path:$,params:U,query:x$(I),fullPath:I?`${$}?${I}`:$,meta:O}}function F$($,U,O,I){let B=I?.isServer??typeof window>"u",L=!B,K=new Headers;return{to:$,from:U,isClient:L,isServer:B,cookies:B&&O?c(O,K):l(),storage:u(),state:{},request:O,responseHeaders:K}}async function A$($,U){let O=Array.isArray($)?$:[$],I=U.isServer;for(let B of O){let L=p(B);if(!L)return console.error(`Route middleware '${B}' is not registered \u2014 failing the guard closed.`),{passed:!1,abort:{type:"abort",error:{statusCode:500,message:`Route middleware '${B}' is not registered`}},state:U.state,responseHeaders:U.responseHeaders};if(L.mode==="server"&&!I)continue;try{let K=await L.handler(U);if(K){if(K.type==="redirect")return{passed:!1,redirect:K,state:U.state,responseHeaders:U.responseHeaders};if(K.type==="abort")return{passed:!1,abort:K,state:U.state,responseHeaders:U.responseHeaders}}}catch(K){return console.error(`Error in middleware '${B}':`,K),{passed:!1,abort:{type:"abort",error:{statusCode:500,message:K instanceof Error?K.message:"Middleware error"}},state:U.state,responseHeaders:U.responseHeaders}}}return{passed:!0,state:U.state,responseHeaders:U.responseHeaders}}var T;var E$=G(()=>{T=new Map});function n($){let O=$.replace(/\\/g,"/").split("/").filter(Boolean),I=O.lastIndexOf("layouts"),B=I>=0?O[I+1]:O.at(-1);if(!B)return"app";return B.replace(/\.stx$/i,"")||"app"}function j$($){let U=$.match(/<meta\b[^>]*name=["']stx-layout["'][^>]*content=["']([^"']+)["'][^>]*>/i),O=$.match(/<meta\b[^>]*name=["']stx-layout-group["'][^>]*content=["']([^"']+)["'][^>]*>/i),I=$.match(/<!--\s*stx-layout:\s*([^ ]+)\s*-->/i),B=U?.[1]||I?.[1]||"";return{layout:B,group:O?.[1]||n(B)}}var T$=()=>{};function k$($){let U=[],O="log(",I=0;while(I<$.length){let B=$.indexOf("log(",I);if(B===-1){U.push($.slice(I));break}let L=B>0?$[B-1]:" ",K=/\bfunction\s+$/.test($.slice(Math.max(0,B-16),B));if(/[\w$.]/.test(L)||K){U.push($.slice(I,B+4)),I=B+4;continue}U.push($.slice(I,B));let V=1,J=B+4;while(J<$.length&&V>0){let X=$[J];if(X==='"'||X==="'"||X==="`"){let Y=X;J++;while(J<$.length&&$[J]!==Y){if($[J]==="\\")J++;J++}J++;continue}if(X==="(")V++;else if(X===")")V--;J++}U.push("0"),I=J}return U.join("")}function C$($){try{return new Bun.Transpiler({loader:"js",minifyWhitespace:!0}).transformSync($).replace(/\}(var |let |const |function )/g,"};$1").trim()}catch{return $}}function H$(){return`
4
+ `))}var f=G(()=>{C()});import i from"path";function N($,U){let I=i.relative(U,$).replace(/\.(stx|md)$/,"");if(I=I.split(i.sep).join("/"),I==="index")return"/";if(I.endsWith("/index"))I=I.slice(0,-6);return I=I.replace(/\[\[([^\]]+)\]\]/g,":$1?"),I=I.replace(/\[([^\]]+)\]/g,":$1"),I=I.replace(/:\.\.\.([^/]+)/g,":$1*"),`/${I}`}function j($){let U=[],O="",I=0;while(I<$.length){let B=$.slice(I),L=/^\/:([^/?*]+)\?/.exec(B);if(L){U.push(L[1]),O+="(?:/([^/]+))?",I+=L[0].length;continue}let K=/^:([^/?*]+)\*/.exec(B);if(K){U.push(K[1]),O+="(.+)",I+=K[0].length;continue}let V=/^:([^/?*]+)/.exec(B);if(V){U.push(V[1]),O+="([^/]+)",I+=V[0].length;continue}O+=$[I].replace(/[.+^${}()|[\]\\*?]/g,"\\$&"),I+=1}return{regex:new RegExp(`^${O}$`),params:U}}function o($,U){let O=$===""?"/":$;for(let I of U){let B=O.match(I.regex);if(B){let L={};return I.params.forEach((K,V)=>{L[K]=B[V+1]}),{route:I,params:L}}}return null}function r($){let U=$.replace(/\[\[([^\]]+)\]\]/g,":$1?").replace(/\[([^\]]+)\]/g,":$1").replace(/:\.\.\.([^/]+)/g,":$1*");return j(U)}var g=()=>{};import b$ from"fs";import d from"path";function R($,U){let O=[],I=d.dirname($);while(I.startsWith(U)||I===U){let B=d.join(I,"_layout.stx");if(b$.existsSync(B))O.unshift(B);if(I===U)break;I=d.dirname(I)}return O}var m=()=>{};import S from"fs";import Q from"path";function t($,U){let O=[];if(!S.existsSync($))return O;let I=S.readdirSync($,{withFileTypes:!0});for(let B of I){let L=Q.join($,B.name);if(B.isDirectory()){if(B.name.startsWith("."))continue;if(F.includes(B.name))continue;O.push(...t(L,U))}else if(B.isFile()){let K=Q.extname(B.name);if(U.includes(K)){if(B.name.startsWith("_")&&B.name!=="_layout.stx")continue;if(B.name==="_layout.stx")continue;O.push(L)}}}return O}class b{routes;pagesDir;pagesDirs;config;constructor($,U={}){this.config=U;let O=U.pagesDirs&&U.pagesDirs.length>0?U.pagesDirs:[U.pagesDir||"pages"];this.pagesDirs=O.map((J)=>Q.resolve($,J)),this.pagesDir=this.pagesDirs[0];let I=U.extensions||[".stx"],B=(J)=>{let X=Q.resolve($,J);try{return S.realpathSync(X)}catch{return X}},L=(U.exclude??[]).filter((J)=>typeof J==="string"&&J.trim()!=="").map(B),K=(J)=>{if(L.length===0)return!1;let X=B(J);return L.some((Y)=>X===Y||X.startsWith(`${Y}${Q.sep}`))},V=new Set;this.routes=[];for(let J of this.pagesDirs){let X=t(J,I).filter((Z)=>!K(Z)),Y=new Map;for(let Z of X){let _=N(Z,J),z=U.pagesDirs?_.replace(/:[\w]+/g,":param"):_;if(U.pagesDirs&&Y.has(z))throw Error(`Conflicting layer pages for ${_}: ${Y.get(z)} and ${Z}`);if(Y.set(z,Z),V.has(z))continue;V.add(z);let{regex:S$,params:s}=j(_),D=U.layouts!==!1?R(Z,J):[];this.routes.push({pattern:_,regex:S$,params:s,filePath:Z,isDynamic:s.length>0,layout:D.length>0?D[D.length-1]:void 0})}}if(this.routes.sort((J,X)=>{if(!J.isDynamic&&X.isDynamic)return-1;if(J.isDynamic&&!X.isDynamic)return 1;let Y=J.pattern.split("/").length,Z=X.pattern.split("/").length;if(Y!==Z)return Z-Y;return J.pattern.localeCompare(X.pattern)}),U.emit!==!1){let J=Q.resolve($,U.stateDir||process.env.STX_DIR?.trim()||".stx");H(this.routes,J),q(this.routes,J,this.pagesDir)}}match($){let U=$===""?"/":$;for(let O of this.routes){let I=U.match(O.regex);if(I){let B={};return O.params.forEach((L,K)=>{B[L]=I[K+1]}),{route:O,params:B}}}return null}resolve($,U){let O=this.routes.find((B)=>B.pattern===$||B.filePath.includes($));if(!O)return"#not-found";let I=O.pattern;if(U)for(let[B,L]of Object.entries(U))I=I.replace(`:${B}`,encodeURIComponent(L));return I}addRoute($){this.routes.push($),this.routes.sort((U,O)=>{if(!U.isDynamic&&O.isDynamic)return-1;if(U.isDynamic&&!O.isDynamic)return 1;return U.pattern.localeCompare(O.pattern)})}getLayout($){return $.layout??null}}function a($,U){return new b($,U)}function e($,U){let O=[`${U}.stx`,"error.stx"];for(let I of O){let B=Q.join($,I);if(S.existsSync(B))return B}return null}function $$($,U){return $.map((O)=>{let I=Q.relative(U,O.filePath),B=O.isDynamic?" (dynamic)":"";return`${O.pattern} \u2192 ${I}${B}`})}var U$=G(()=>{f();g();m();C()});function I$($){x=$.replace(/\/$/,"")}function O$($,U,O={}){M[$]={path:U,name:$,params:O}}function B$($){for(let[U,O]of Object.entries($))if(typeof O==="string")M[U]={path:O,name:U};else M[U]={...O,name:U}}function J$($,U={},O=!1){let I=M[$];if(!I)return console.warn(`Route [${$}] not defined.`),"#undefined-route";let B={...I.params,...U},L=I.path;L=L.replace(/:(\w+)/g,(V,J)=>{let X=B[J];if(X===void 0)return console.warn(`Missing parameter [${J}] for route [${$}].`),`:${J}`;return delete B[J],encodeURIComponent(String(X))});let K=Object.entries(B);if(K.length>0){let V=K.map(([J,X])=>`${encodeURIComponent(J)}=${encodeURIComponent(String(X))}`).join("&");L+=(L.includes("?")?"&":"?")+V}return O&&x?`${x}${L}`:L}function K$(){for(let $ of Object.keys(M))delete M[$];x=""}var M,x="";var L$=G(()=>{M={}});import V$ from"fs";import X$ from"path";function Y$($,U={}){return{type:"redirect",path:$,options:{replace:U.replace??!1,external:U.external??!1,redirectCode:U.redirectCode??302}}}function Z$($){return{type:"abort",error:typeof $==="string"?{statusCode:500,message:$}:$}}function G$($,U={}){return{handler:$,mode:U.mode??"universal"}}function h($){let U={};if(!$)return U;let O=$.split(";");for(let I of O){let[B,...L]=I.split("=");if(B){let K=B.trim(),V=L.join("=").trim();if(K)U[K]=decodeURIComponent(V)}}return U}function k($,U,O={}){let I=`${encodeURIComponent($)}=${encodeURIComponent(U)}`;if(O.expires){let B=typeof O.expires==="number"?new Date(Date.now()+O.expires*1000):O.expires;I+=`; Expires=${B.toUTCString()}`}if(O.path)I+=`; Path=${O.path}`;if(O.domain)I+=`; Domain=${O.domain}`;if(O.secure)I+="; Secure";if(O.httpOnly)I+="; HttpOnly";if(O.sameSite)I+=`; SameSite=${O.sameSite}`;return I}function c($,U){let O=$.headers.get("cookie")||"",I=h(O);return{get(B){return I[B]},set(B,L,K={}){I[B]=L,U.append("Set-Cookie",k(B,L,K))},delete(B){delete I[B],U.append("Set-Cookie",k(B,"",{expires:new Date(0),path:"/"}))},getAll(){return{...I}}}}function u(){return{get($){if(typeof document>"u")return;return h(document.cookie)[$]},set($,U,O={}){if(typeof document>"u")return;document.cookie=k($,U,O)},delete($){if(typeof document>"u")return;document.cookie=k($,"",{expires:new Date(0),path:"/"})},getAll(){if(typeof document>"u")return{};return h(document.cookie)}}}function l(){let $=typeof window<"u"&&typeof window.localStorage<"u";return{get(U){if(!$)return null;try{return window.localStorage.getItem(U)}catch{return null}},set(U,O){if(!$)return;try{window.localStorage.setItem(U,O)}catch{}},remove(U){if(!$)return;try{window.localStorage.removeItem(U)}catch{}},isAvailable(){return $}}}function v($,U){T.set($,U)}function p($){return T.get($)}function Q$($){return T.has($)}function W$(){T.clear()}function M$(){return Array.from(T.keys())}async function _$($,U="middleware"){let O=X$.resolve($,U);if(!V$.existsSync(O))return;let I=V$.readdirSync(O);for(let B of I){if(!B.endsWith(".ts")&&!B.endsWith(".js"))continue;if(B.includes(".test.")||B.includes(".spec."))continue;let L=B.replace(/\.(ts|js)$/,""),K=X$.join(O,B);try{let J=(await import(K)).default;if(J&&typeof J.handler==="function")v(L,J);else if(typeof J==="function")v(L,{handler:J,mode:"universal"})}catch(V){console.warn(`Failed to load middleware '${L}' from ${K}:`,V)}}}function x$($){let U={};if(!$)return U;let O=new URLSearchParams($);for(let[I,B]of O)U[I]=B;return U}function z$($,U,O,I=""){return{path:$,params:U,query:x$(I),fullPath:I?`${$}?${I}`:$,meta:O}}function F$($,U,O,I){let B=I?.isServer??typeof window>"u",L=!B,K=new Headers;return{to:$,from:U,isClient:L,isServer:B,cookies:B&&O?c(O,K):u(),storage:l(),state:{},request:O,responseHeaders:K}}async function A$($,U){let O=Array.isArray($)?$:[$],I=U.isServer;for(let B of O){let L=p(B);if(!L)return console.error(`Route middleware '${B}' is not registered \u2014 failing the guard closed.`),{passed:!1,abort:{type:"abort",error:{statusCode:500,message:`Route middleware '${B}' is not registered`}},state:U.state,responseHeaders:U.responseHeaders};if(L.mode==="server"&&!I)continue;try{let K=await L.handler(U);if(K){if(K.type==="redirect")return{passed:!1,redirect:K,state:U.state,responseHeaders:U.responseHeaders};if(K.type==="abort")return{passed:!1,abort:K,state:U.state,responseHeaders:U.responseHeaders}}}catch(K){return console.error(`Error in middleware '${B}':`,K),{passed:!1,abort:{type:"abort",error:{statusCode:500,message:K instanceof Error?K.message:"Middleware error"}},state:U.state,responseHeaders:U.responseHeaders}}}return{passed:!0,state:U.state,responseHeaders:U.responseHeaders}}var T;var E$=G(()=>{T=new Map});function n($){let O=$.replace(/\\/g,"/").split("/").filter(Boolean),I=O.lastIndexOf("layouts"),B=I>=0?O[I+1]:O.at(-1);if(!B)return"app";return B.replace(/\.stx$/i,"")||"app"}function j$($){let U=$.match(/<meta\b[^>]*name=["']stx-layout["'][^>]*content=["']([^"']+)["'][^>]*>/i),O=$.match(/<meta\b[^>]*name=["']stx-layout-group["'][^>]*content=["']([^"']+)["'][^>]*>/i),I=$.match(/<!--\s*stx-layout:\s*([^ ]+)\s*-->/i),B=U?.[1]||I?.[1]||"";return{layout:B,group:O?.[1]||n(B)}}var T$=()=>{};function k$($){let U=[],O="log(",I=0;while(I<$.length){let B=$.indexOf("log(",I);if(B===-1){U.push($.slice(I));break}let L=B>0?$[B-1]:" ",K=/\bfunction\s+$/.test($.slice(Math.max(0,B-16),B));if(/[\w$.]/.test(L)||K){U.push($.slice(I,B+4)),I=B+4;continue}U.push($.slice(I,B));let V=1,J=B+4;while(J<$.length&&V>0){let X=$[J];if(X==='"'||X==="'"||X==="`"){let Y=X;J++;while(J<$.length&&$[J]!==Y){if($[J]==="\\")J++;J++}J++;continue}if(X==="(")V++;else if(X===")")V--;J++}U.push("0"),I=J}return U.join("")}function C$($,U=!1){try{return new Bun.Transpiler(U?{loader:"js",minify:{whitespace:!0,identifiers:!0}}:{loader:"js",minifyWhitespace:!0}).transformSync($).replace(/\}(var |let |const |function )/g,"};$1").trim()}catch{return $}}function H$(){return`
5
5
  ;(function(){
6
6
  'use strict';
7
7
  var ROUTER_REV=7;
8
8
  if(window.__stxRouter&&window.__stxRouter.__rev===ROUTER_REV)return;
9
9
 
10
10
  // \u2500\u2500 Configuration \u2500\u2500
11
- var defaults={container:'main',loadingClass:'stx-navigating',viewTransitions:true,cache:true,scrollToTop:true,prefetch:true,progress:true,progressColor:'#78dce8',progressHeight:'2px',interceptAllLinks:false,prefetchCacheMax:50,routeFocus:true,announceRoute:true,interceptForms:false,cssLoadTimeout:1500,scrollRestoration:true};
11
+ var defaults={container:'main',loadingClass:'stx-navigating',viewTransitions:true,cache:true,scrollToTop:true,prefetch:true,progress:true,progressColor:'#78dce8',progressHeight:'2px',interceptAllLinks:false,prefetchCacheMax:50,routeFocus:true,announceRoute:true,interceptForms:false,cssLoadTimeout:1500,scrollRestoration:true,screens:'auto',screenLimit:8,navDuration:350,swipeBack:true,swipeEdge:20,prefetchVisible:true,prefetchVisibleMax:12,revalidate:true,revalidateAfter:3000};
12
12
  var o=Object.assign({},defaults,window.__stxRouterConfig||{},window.STX_ROUTER_OPTIONS||{});
13
13
  var containerSel=o.container;
14
14
  var debug=!!o.debug;
@@ -44,6 +44,12 @@ import{$w as v$,ax as G}from"./chunk-x7qyx7vn.js";function y($){return $.split(/
44
44
  // (which carries a scroll token too): going back from a pushed entry stays
45
45
  // in the app, from the first it leaves it (or, in a phone app, does nothing).
46
46
  var PUSHED_MARK='__stxPushed';
47
+ // How far above the entry the app opened with this one sits, and which tab
48
+ // it belongs to. A tab switch rewinds to depth 0 before it writes the next
49
+ // tab's entries, which is what keeps Back from ever crossing tabs.
50
+ var DEPTH='__stxDepth';
51
+ var TAB='__stxTab';
52
+ var histDepth=(history.state&&history.state[DEPTH])|0;
47
53
  var scrollSeq=0;
48
54
  var pendingScroll=null;
49
55
  var restoreScroll=!!o.scrollRestoration;
@@ -58,11 +64,44 @@ import{$w as v$,ax as G}from"./chunk-x7qyx7vn.js";function y($){return $.split(/
58
64
  return parts.length===2?[parseFloat(parts[0])||0,parseFloat(parts[1])||0]:null;
59
65
  }catch(e){return null}
60
66
  }
67
+ // Inner scrollers, marked data-stx-scroll: a screen whose list scrolls
68
+ // inside its own box rather than the window lost its place on Back exactly
69
+ // the way the window used to. Keyed by the attribute's value, or by order
70
+ // for an unnamed one.
71
+ function scrollerKey(el,i){return el.getAttribute('data-stx-scroll')||('#'+i)}
72
+ function innerScroll(root){
73
+ var m=null;
74
+ if(root&&root.querySelectorAll)root.querySelectorAll('[data-stx-scroll]').forEach(function(el,i){
75
+ if(el.scrollTop||el.scrollLeft){m=m||{};m[scrollerKey(el,i)]=[el.scrollLeft||0,el.scrollTop||0]}
76
+ });
77
+ return m;
78
+ }
79
+ function applyInner(root,m){
80
+ if(!m||!root||!root.querySelectorAll)return;
81
+ root.querySelectorAll('[data-stx-scroll]').forEach(function(el,i){
82
+ var at=m[scrollerKey(el,i)];
83
+ if(at){el.scrollLeft=at[0];el.scrollTop=at[1]}
84
+ });
85
+ }
61
86
  // Called while the outgoing entry is still the current one, so the position
62
87
  // read here belongs to the token being written.
63
88
  function rememberScroll(){
89
+ if(active&&active.el&&!active.el.hasAttribute(HIDDEN))saveScroll(active);
64
90
  if(!restoreScroll)return;
65
- try{window.sessionStorage.setItem(SCROLL_STORE+scrollToken,(window.pageXOffset||window.scrollX||0)+','+(window.pageYOffset||window.scrollY||0))}catch(e){}
91
+ try{
92
+ window.sessionStorage.setItem(SCROLL_STORE+scrollToken,(window.pageXOffset||window.scrollX||0)+','+(window.pageYOffset||window.scrollY||0));
93
+ // Taken as the swap began when there is one: by the time the history
94
+ // is written the outgoing page's scrollers have been replaced.
95
+ var inner=innerSnap!==undefined?innerSnap:innerScroll(activeRoot());
96
+ innerSnap=undefined;
97
+ if(inner)window.sessionStorage.setItem(SCROLL_STORE+scrollToken+':i',JSON.stringify(inner));
98
+ else window.sessionStorage.removeItem(SCROLL_STORE+scrollToken+':i');
99
+ }catch(e){}
100
+ }
101
+ var pendingInner=null;
102
+ var innerSnap;
103
+ function readInner(token){
104
+ try{return JSON.parse(window.sessionStorage.getItem(SCROLL_STORE+token+':i')||'null')}catch(e){return null}
66
105
  }
67
106
  // One place decides where a swap leaves the viewport, so the fragment path
68
107
  // and the whole-document path cannot drift apart.
@@ -71,10 +110,16 @@ import{$w as v$,ax as G}from"./chunk-x7qyx7vn.js";function y($){return $.split(/
71
110
  var at=pendingScroll;
72
111
  pendingScroll=null;
73
112
  window.scrollTo({left:at[0],top:at[1],behavior:'instant'});
113
+ // Again once the page has bound: a scroller's content is often drawn
114
+ // by a :for that has not run yet, and a box with nothing in it cannot
115
+ // be scrolled anywhere.
116
+ var inner=pendingInner;pendingInner=null;
117
+ if(inner){applyInner(activeRoot(),inner);setTimeout(function(){applyInner(activeRoot(),inner)},60)}
74
118
  return;
75
119
  }
120
+ pendingInner=null;
76
121
  if(o.scrollToTop&&!hash){window.scrollTo({top:0,behavior:'instant'});return}
77
- if(hash){var el=qs(hash);if(el)el.scrollIntoView({behavior:'smooth'})}
122
+ if(hash){var el=findIn(hash);if(el)el.scrollIntoView({behavior:'smooth'})}
78
123
  }
79
124
  // Keeps whatever another script put in the entry; only adds the token.
80
125
  function stampScrollToken(){
@@ -82,6 +127,7 @@ import{$w as v$,ax as G}from"./chunk-x7qyx7vn.js";function y($){return $.split(/
82
127
  var current=history.state;
83
128
  if(current&&typeof current==='object')for(var key in current)state[key]=current[key];
84
129
  state[SCROLL_TOKEN]=scrollToken;
130
+ state[DEPTH]=histDepth;
85
131
  try{history.replaceState(state,'',location.href)}catch(e){}
86
132
  }
87
133
  if(restoreScroll){
@@ -135,9 +181,24 @@ import{$w as v$,ax as G}from"./chunk-x7qyx7vn.js";function y($){return $.split(/
135
181
  function isBuildSkew(incoming){
136
182
  return !!(loadedBuild&&incoming&&incoming!==loadedBuild);
137
183
  }
138
- function reloadForSkew(url,incoming){
139
- log('[router] build skew: page is',loadedBuild,'server is',incoming,'\u2014 full navigation');
140
- location.href=url;
184
+ // A navigation the user asked for loads its destination as a document: no
185
+ // fragment of the newer build can be hydrated by this runtime, and a tap is
186
+ // the one moment a page load is expected anyway. Anything else that notices
187
+ // the newer build (a background revalidation, the offline worker) must not
188
+ // reload a screen the user is in the middle of using, so the reload waits
189
+ // until the page is hidden, and a cold start picks the build up regardless.
190
+ var skewDeferred=false;
191
+ function reloadForSkew(url,incoming,background){
192
+ log('[router] build skew: page is',loadedBuild,'server is',incoming,background?'\u2014 reload when hidden':'\u2014 full navigation');
193
+ if(!background){location.href=url;return}
194
+ if(skewDeferred)return;
195
+ skewDeferred=true;
196
+ var reloadHidden=function(){
197
+ if(document.visibilityState!=='hidden')return;
198
+ document.removeEventListener('visibilitychange',reloadHidden);
199
+ location.reload();
200
+ };
201
+ document.addEventListener('visibilitychange',reloadHidden);
141
202
  }
142
203
  // A link marked data-stx-transition="none" swaps without the cross-fade. A
143
204
  // tab bar is the case: iOS switches tabs instantly, and the fade read as a
@@ -284,6 +345,9 @@ import{$w as v$,ax as G}from"./chunk-x7qyx7vn.js";function y($){return $.split(/
284
345
  }
285
346
 
286
347
  var cache={};
348
+ // When each entry was fetched, so a cache hit knows whether it is worth
349
+ // checking behind the swap (revalidate).
350
+ var cacheAt={};
287
351
  var prefetching={};
288
352
  var awaitingKey='';
289
353
  var isNavigating=false;
@@ -305,6 +369,7 @@ import{$w as v$,ax as G}from"./chunk-x7qyx7vn.js";function y($){return $.split(/
305
369
  layoutGroupCache[key]=group;
306
370
  titleCache[key]=title||'';
307
371
  attrsCache[key]=cattrs||'';
372
+ cacheAt[key]=Date.now();
308
373
  while(cacheOrder.length>o.prefetchCacheMax){
309
374
  var oldest=cacheOrder.shift();
310
375
  delete cache[oldest];
@@ -312,6 +377,7 @@ import{$w as v$,ax as G}from"./chunk-x7qyx7vn.js";function y($){return $.split(/
312
377
  delete layoutGroupCache[oldest];
313
378
  delete titleCache[oldest];
314
379
  delete attrsCache[oldest];
380
+ delete cacheAt[oldest];
315
381
  }
316
382
  }
317
383
  // Read a prefetch response into the shape setCache stores, or null when this
@@ -415,6 +481,7 @@ import{$w as v$,ax as G}from"./chunk-x7qyx7vn.js";function y($){return $.split(/
415
481
  delete layoutGroupCache[key];
416
482
  delete titleCache[key];
417
483
  delete attrsCache[key];
484
+ delete cacheAt[key];
418
485
  }
419
486
 
420
487
  // Extract top-level CSS blocks (rules AND @media blocks with nested braces).
@@ -824,10 +891,17 @@ import{$w as v$,ax as G}from"./chunk-x7qyx7vn.js";function y($){return $.split(/
824
891
  // pushes, and the string 'replace' replaces. Threading a fourth argument
825
892
  // through swap() to each of the three history sites would have been the
826
893
  // alternative (#1807).
894
+ //
895
+ // 'tab' is a tab's first screen: it takes the place of the entry the app
896
+ // opened with (selectTab has rewound to it), under a token of its own so
897
+ // the tab it replaced keeps its positions.
898
+ var scrollSaved=false;
827
899
  function writeHistory(mode,href){
828
900
  // The position belongs to the entry being left, and scrollToken still
829
- // names it here.
830
- rememberScroll();
901
+ // names it here -- unless the screen swap already saved it, before the
902
+ // outgoing screen was lifted out of the page and the window clamped.
903
+ if(!scrollSaved)rememberScroll();
904
+ scrollSaved=false;
831
905
  if(mode==='replace'){
832
906
  // A replaced entry is still the one it replaces: pushed by the app or
833
907
  // the one the app opened with.
@@ -837,22 +911,43 @@ import{$w as v$,ax as G}from"./chunk-x7qyx7vn.js";function y($){return $.split(/
837
911
  return;
838
912
  }
839
913
  scrollToken=newScrollToken();
914
+ if(mode==='tab'){histDepth=0;history.replaceState(tokenState(),'',href);return}
915
+ histDepth++;
840
916
  var pushed=tokenState();
841
917
  pushed[PUSHED_MARK]=true;
842
918
  history.pushState(pushed,'',href);
843
919
  }
844
- function tokenState(){var state={};state[SCROLL_TOKEN]=scrollToken;return state}
920
+ function tokenState(){var state={};state[SCROLL_TOKEN]=scrollToken;state[DEPTH]=histDepth;if(curTab)state[TAB]=curTab;return state}
845
921
 
846
922
  // Second arg accepts the legacy pushState boolean OR an options object
847
923
  // { replace, instant }. Callers inside this file still pass the boolean.
848
924
  // instant is what data-stx-transition="none" is to a link: no cross-fade.
925
+ //
926
+ // The newest navigation wins. One already on its way when another starts
927
+ // (a second tap, Back while a page is still loading) is aborted and its
928
+ // answer ignored: it used to be the other way round, the later one was
929
+ // dropped, and a Back during a load left the address bar on the popped
930
+ // entry while the screen went on to show the page being left.
931
+ var navSeq=0;
932
+ var navAbort=null;
933
+ // What the next swap needs to know about where it is going: set by the
934
+ // caller right before navigate() (popstate, a tab switch) and carried to
935
+ // swap() through pendingCtx, the same way pendingContainerAttrs is.
936
+ var navCtxNext=null;
937
+ var pendingCtx=null;
938
+ function routerFetch(url,headers){
939
+ var init={headers:headers};
940
+ if(navAbort)init.signal=navAbort.signal;
941
+ return fetch(url,init);
942
+ }
849
943
  function navigate(url,pushState,force){
944
+ var ctx=navCtxNext||{};
945
+ navCtxNext=null;
850
946
  if(pushState&&typeof pushState==='object'){if(pushState.instant)instantNext=true;pushState=pushState.replace?'replace':true}
851
947
  // Lang-picker passes force=true with an already-localized path (/en/...).
852
948
  // Re-localizing would map it back to the *current* locale and no-op.
853
949
  if(!force) url=withCurrentLocale(url);
854
950
  log('[router] navigate() called:',url,'isNavigating:',isNavigating);
855
- if(isNavigating)return Promise.resolve(false);
856
951
  // Resolve against the current document URL, matching native <a> semantics.
857
952
  // With location.origin as the base, any relative href ('?status=resolved',
858
953
  // '#anchor', './sibling') resolved to the SITE ROOT \u2014 so filter tabs,
@@ -862,9 +957,9 @@ import{$w as v$,ax as G}from"./chunk-x7qyx7vn.js";function y($){return $.split(/
862
957
 
863
958
  if(t.origin!==location.origin){location.href=url;return Promise.resolve(false)}
864
959
 
865
- if(t.pathname===location.pathname&&t.hash){
960
+ if(t.pathname===location.pathname&&t.hash&&pushState!=='tab'){
866
961
  if(pushState!==false)writeHistory(pushState,t.href);
867
- var el=qs(t.hash);
962
+ var el=findIn(t.hash);
868
963
  if(el)el.scrollIntoView({behavior:'smooth'});
869
964
  return Promise.resolve(true);
870
965
  }
@@ -875,7 +970,7 @@ import{$w as v$,ax as G}from"./chunk-x7qyx7vn.js";function y($){return $.split(/
875
970
  // entry \u2014 without this allowance, hitting back would early-return
876
971
  // and the visible page content would be left frozen on the
877
972
  // forward-navigation page.
878
- if(pushState!==false&&t.href===location.href&&!t.hash&&!force)return Promise.resolve(false);
973
+ if(pushState!==false&&pushState!=='tab'&&t.href===location.href&&!t.hash&&!force)return Promise.resolve(false);
879
974
 
880
975
  // Its prefetch is on the way: wait for that answer rather than asking the
881
976
  // server a second time. A later tap elsewhere wins.
@@ -885,11 +980,17 @@ import{$w as v$,ax as G}from"./chunk-x7qyx7vn.js";function y($){return $.split(/
885
980
  return prefetching[awaitedKey].then(function(){
886
981
  if(awaitingKey!==awaitedKey)return false;
887
982
  awaitingKey='';
983
+ navCtxNext=ctx;
888
984
  return navigate(url,pushState,force);
889
985
  });
890
986
  }
891
987
  awaitingKey='';
892
988
 
989
+ if(navAbort){try{navAbort.abort()}catch(e){}}
990
+ navAbort=typeof AbortController==='function'?new AbortController():null;
991
+ var id=++navSeq;
992
+ ctx.id=id;
993
+ if(!ctx.direction)ctx.direction=pushState==='replace'?'replace':pushState==='tab'?'tab':pushState===false?'pop':'push';
893
994
  isNavigating=true;
894
995
  instantNav=instantNext;
895
996
  instantNext=false;
@@ -900,7 +1001,22 @@ import{$w as v$,ax as G}from"./chunk-x7qyx7vn.js";function y($){return $.split(/
900
1001
  var targetPath=cacheKey(url);
901
1002
  var targetHash=t.hash;
902
1003
 
903
- function done(){isNavigating=false;document.body.classList.remove(o.loadingClass);finishProgress()}
1004
+ function done(){
1005
+ if(id!==navSeq)return;
1006
+ isNavigating=false;navAbort=null;
1007
+ document.body.classList.remove(o.loadingClass);finishProgress();
1008
+ settleDirection();
1009
+ }
1010
+ function stale(){return id!==navSeq}
1011
+ // A failed fetch keeps the app: the destination shows a way to try again
1012
+ // in place of its content, where a document load used to be the answer
1013
+ // to everything -- offline that load is the offline page, or nothing.
1014
+ function failed(err){
1015
+ if(stale()||(err&&err.name==='AbortError'))return false;
1016
+ console.error('[router] fetch error:',err);
1017
+ return showNavError(url,err,pushState,targetHash,ctx);
1018
+ }
1019
+ function swapWith(html,key){pendingCtx=ctx;return swap(html,key,pushState,targetHash)}
904
1020
 
905
1021
  if(o.cache&&cache[targetPath]&&!force){
906
1022
  // Cache hit \u2192 promote in LRU order so this entry survives eviction
@@ -909,22 +1025,24 @@ import{$w as v$,ax as G}from"./chunk-x7qyx7vn.js";function y($){return $.split(/
909
1025
  if(checkLayoutChange(layoutCache[targetPath],url,layoutGroupCache[targetPath])){
910
1026
  // Layout changed \u2014 fetch full page and do full document swap
911
1027
  log('[router] cache hit but layout changed \u2014 fetching full page');
912
- return fetch(url,{headers:{'Accept':'text/html'}}).then(function(r){
913
- if(!r.ok)throw new Error(r.status);
1028
+ return routerFetch(url,{'Accept':'text/html'}).then(function(r){
1029
+ if(!r.ok)throw httpError(r.status);
914
1030
  return r.text();
915
1031
  }).then(function(html){
1032
+ if(stale())return false;
916
1033
  log('[router] full page fetched from cache path, len:',html.length);
917
1034
  pendingLayoutDecl={layout:layoutCache[targetPath]||'',group:layoutGroupCache[targetPath]||''};
918
- return swap(html,targetPath,pushState,targetHash);
919
- }).catch(function(err){
920
- console.error('[router] full page fetch error:',err);
921
- location.href=url;
922
- }).finally(done);
1035
+ return swapWith(html,targetPath);
1036
+ }).catch(failed).finally(done);
923
1037
  }
924
1038
  pendingContainerAttrs=attrsCache[targetPath]||'';
925
1039
  pendingLayoutDecl=null;
926
- return Promise.resolve(swap(cache[targetPath],targetPath,pushState,targetHash)).then(function(){
1040
+ return Promise.resolve(swapWith(cache[targetPath],targetPath)).then(function(swapped){
1041
+ if(swapped===false)return false;
927
1042
  applyTitle(titleCache[targetPath]);
1043
+ // Shown from the cache at once; asked again behind it, so a page that
1044
+ // changed since says so (stx:updated) instead of staying stale.
1045
+ revalidate(targetPath,url);
928
1046
  return true;
929
1047
  }).finally(done);
930
1048
  }
@@ -934,8 +1052,9 @@ else {
934
1052
  // the page content. Custom app-shell containers need full documents so
935
1053
  // the router does not inject a <main> fragment into the wrong element.
936
1054
  var wantsFragment=shouldUseFragmentResponse();
937
- return fetch(url,{headers:wantsFragment?{'X-STX-Router':'true','Accept':'text/html'}:{'Accept':'text/html'}}).then(function(r){
938
- if(!r.ok)throw new Error(r.status);
1055
+ return routerFetch(url,wantsFragment?{'X-STX-Router':'true','Accept':'text/html'}:{'Accept':'text/html'}).then(function(r){
1056
+ if(stale())return null;
1057
+ if(!r.ok)throw httpError(r.status);
939
1058
  // A route guard answered with a redirect and fetch followed it
940
1059
  // transparently, so r.ok is the DESTINATION's 200 and this markup
941
1060
  // belongs to r.url \u2014 not to the path that was requested. Without
@@ -966,9 +1085,9 @@ else {
966
1085
  // Layout change? Fetch the FULL page (no X-STX-Router header) and do full document swap
967
1086
  if(isFragment&&checkLayoutChange(newLayout,url,newGroup)){
968
1087
  log('[router] layout change \u2014 fetching full page for document swap');
969
- return fetch(url,{headers:{'Accept':'text/html'}}).then(function(fullRes){
1088
+ return routerFetch(url,{'Accept':'text/html'}).then(function(fullRes){
970
1089
  log('[router] full page fetched:',fullRes.status,'ok:',fullRes.ok);
971
- if(!fullRes.ok)throw new Error(fullRes.status);
1090
+ if(!fullRes.ok)throw httpError(fullRes.status);
972
1091
  return fullRes.text().then(function(html){
973
1092
  log('[router] full page html length:',html.length);
974
1093
  return{html:html,isFragment:false,layout:newLayout,layoutGroup:newGroup,title:newTitle};
@@ -977,23 +1096,51 @@ else {
977
1096
  }
978
1097
  return r.text().then(function(html){return{html:html,isFragment:isFragment,layout:newLayout,layoutGroup:newGroup,title:newTitle,containerAttrs:newCAttrs,runtime:newRuntime}});
979
1098
  }).then(function(result){
980
- if(!result)return;
1099
+ if(!result||stale())return false;
981
1100
  if(result.isFragment)result.html=fragmentMarker(result.runtime)+result.html;
982
1101
  if(o.cache)setCache(targetPath,result.html,result.layout,result.layoutGroup,result.title,result.containerAttrs);
983
1102
  pendingContainerAttrs=result.isFragment?(result.containerAttrs||''):'';
984
1103
  pendingLayoutDecl=result.isFragment?null:{layout:result.layout||'',group:result.layoutGroup||''};
985
- return Promise.resolve(swap(result.html,targetPath,pushState,targetHash)).then(function(){
1104
+ return Promise.resolve(swapWith(result.html,targetPath)).then(function(swapped){
1105
+ if(swapped===false)return false;
986
1106
  // Fragment swaps carry no <head>; apply the title from the header.
987
1107
  // Full-document swaps already set document.title from the <title> tag.
988
1108
  if(result.isFragment)applyTitle(result.title);
989
1109
  return true;
990
1110
  });
991
- }).catch(function(err){
992
- console.error('[router] fetch error:',err);
993
- location.href=url;
994
- }).finally(done);
1111
+ }).catch(failed).finally(done);
995
1112
  }
996
1113
  }
1114
+ function httpError(status){var err=new Error(String(status));err.status=status;return err}
1115
+
1116
+ // \u2500\u2500 A screen that could not be loaded \u2500\u2500
1117
+ // Shown in the routed container (in a screen of its own when screens are
1118
+ // retained, so Back returns to the one before it), with the address bar at
1119
+ // the destination, so "Try again" and coming back online both retry it in
1120
+ // place. A page that wants to draw its own cancels stx:navigate-error.
1121
+ function escAttr(v){return String(v).replace(/&/g,'&amp;').replace(/"/g,'&quot;').replace(/</g,'&lt;')}
1122
+ function showNavError(url,err,pushState,hash,ctx){
1123
+ var status=err&&err.status||0;
1124
+ var offline=!status&&navigator.onLine===false;
1125
+ var ev=new CustomEvent('stx:navigate-error',{cancelable:true,detail:{url:url,status:status,offline:offline,error:err}});
1126
+ window.dispatchEvent(ev);
1127
+ if(ev.defaultPrevented)return false;
1128
+ var title=offline?'You are offline':'This page could not be loaded';
1129
+ var text=offline?'It will load as soon as you are back online.':status?'Something went wrong on the way. Try again in a moment.':'Check your connection and try again.';
1130
+ var html='<!--stx-fragment rt=0--><div class="stx-retry" role="alert" data-stx-retry="'+escAttr(url)+'"><p class="stx-retry-title">'+title+'</p><p class="stx-retry-text">'+text+'</p><button type="button" class="stx-retry-button" data-stx-retry-button>Try again</button></div>';
1131
+ pendingContainerAttrs='';
1132
+ pendingLayoutDecl=null;
1133
+ pendingCtx=ctx;
1134
+ return Promise.resolve(swap(html,cacheKey(url),pushState,hash)).then(function(){return false});
1135
+ }
1136
+ function retryShown(){var root=activeRoot();var el=root&&root.querySelector?root.querySelector('[data-stx-retry]'):null;return el?el.getAttribute('data-stx-retry'):''}
1137
+ document.addEventListener('click',function(e){
1138
+ var b=e.target&&e.target.closest?e.target.closest('[data-stx-retry-button]'):null;
1139
+ if(!b)return;
1140
+ var holder=b.closest('[data-stx-retry]');
1141
+ if(holder)navigate(holder.getAttribute('data-stx-retry'),'replace',true);
1142
+ });
1143
+ window.addEventListener('online',function(){var u=retryShown();if(u)navigate(u,'replace',true)});
997
1144
 
998
1145
  // A full document is only safe to partial-swap into the stx shell if it is
999
1146
  // itself stx-rendered. Pages served by another engine mounted on the same
@@ -1039,7 +1186,7 @@ else {
1039
1186
 
1040
1187
  function announceRoute(){
1041
1188
  if(o.announceRoute===false)return;
1042
- var c=getContainer();
1189
+ var c=activeRoot();
1043
1190
  var h=c&&c.querySelector?c.querySelector('h1'):null;
1044
1191
  // The heading names the destination better than the title, which often
1045
1192
  // carries a site-name suffix. Falls back to the title, then gives up
@@ -1189,7 +1336,12 @@ else {
1189
1336
  var declaredRuntime=fragMark&&fragMark[1]?fragMark[1]:'';
1190
1337
  if(isFragment)html=html.slice(fragMark[0].length);
1191
1338
  if(!isFragment&&!isStxDocument(html)){log('[router] non-stx document \u2014 full navigation to:',url);location.href=url;return Promise.resolve(false)}
1339
+ var ctx=pendingCtx||{direction:pushState==='replace'?'replace':pushState==='tab'?'tab':pushState===false?'pop':'push'};
1340
+ pendingCtx=null;
1192
1341
  var currentContent=getContainer();
1342
+ // The routed container. currentContent is where the page is written: the
1343
+ // container itself, or with screens retained, the new screen inside it.
1344
+ var host=currentContent;
1193
1345
  log('[router] swap: isFragment='+isFragment+' container='+!!currentContent+' tag='+(currentContent&&currentContent.tagName)+' selector='+containerSel+' htmlLen='+html.length);
1194
1346
  if(!currentContent){log('[router] no container \u2014 falling back');location.href=url;return Promise.resolve(false)}
1195
1347
 
@@ -1306,14 +1458,16 @@ else {
1306
1458
  // Swap content \u2014 apply the destination container's own attributes first
1307
1459
  // so the incoming markup lands in a correctly-laid-out container instead
1308
1460
  // of flashing (or sticking) unstyled.
1309
- applyContainerAttrs(currentContent,pendingContainerAttrs);
1461
+ if(scr)scr.cattrs=pendingContainerAttrs;
1462
+ applyContainerAttrs(host,pendingContainerAttrs);
1310
1463
  currentContent.innerHTML=cleanFrag;
1311
1464
  // Remove old page scripts
1312
1465
  qsa('script[data-stx-page]').forEach(function(s){s.remove()});
1313
1466
  if(pushState!==false)writeHistory(pushState,url+(hash||''));
1467
+ if(scr)screenCommit(scr,url+(hash||''));
1314
1468
  refreshCurrentLinks();
1315
1469
  applyScroll(hash);
1316
- window.dispatchEvent(new CustomEvent('stx:navigate',{detail:{url:url}}));
1470
+ window.dispatchEvent(new CustomEvent('stx:navigate',{detail:{url:url,direction:ctx.direction}}));
1317
1471
  // Before page scripts run, so a page that focuses its own control on
1318
1472
  // mount still wins \u2014 its script executes after this.
1319
1473
  focusAfterNavigation(hash);
@@ -1418,17 +1572,28 @@ else {
1418
1572
  if(fragPending.length)Promise.all(fragPending).then(runFragScripts).catch(runFragScripts);
1419
1573
  else runFragScripts();
1420
1574
  }
1575
+ // With screens retained, the outgoing page is kept (or disposed once it
1576
+ // has animated away) by screenBegin rather than cleaned up here.
1577
+ var scr=null;
1578
+ var useScreens=screensOn();
1421
1579
  function startFragSwap(){
1422
- if(window.stx&&window.stx._cleanupContainer)window.stx._cleanupContainer(currentContent);
1580
+ if(ctx.id&&ctx.id!==navSeq)return Promise.resolve(false);
1581
+ if(pushState!==false)innerSnap=innerScroll(activeRoot());
1582
+ if(useScreens)settleAnimation();
1583
+ else if(window.stx&&window.stx._cleanupContainer)window.stx._cleanupContainer(currentContent);
1423
1584
  return new Promise(function(resolve,reject){
1424
1585
  function completeFragSwap(){
1425
1586
  try{
1587
+ setDirection(ctx.direction);
1588
+ if(useScreens){scr=screenBegin(host,ctx,html,pushState!==false);currentContent=scr.el}
1426
1589
  doFragSwap();
1590
+ if(scr)screenEnd(scr);
1427
1591
  resolve(true);
1428
1592
  }catch(err){reject(err)}
1429
1593
  }
1430
1594
  if(instantNav&&swapRunsInOneTask(html,url)){runInOneTask(completeFragSwap)}
1431
1595
  else if(instantNav&&runInstantSwap(completeFragSwap)){}
1596
+ else if(useScreens){completeFragSwap()}
1432
1597
  else if(runViewTransition(completeFragSwap)){}
1433
1598
  else if(instantNav){completeFragSwap()}
1434
1599
  else{currentContent.style.transition='opacity 0.12s ease-out';currentContent.style.opacity='0';setTimeout(function(){completeFragSwap();currentContent.style.opacity='1';setTimeout(function(){currentContent.style.transition=''},150)},120)}
@@ -1480,7 +1645,7 @@ else {
1480
1645
  function doSwap(){
1481
1646
  // \u2500\u2500 Swap <head> styles \u2500\u2500
1482
1647
  // Inject new styles FIRST, then remove old to prevent unstyled flash
1483
- var keepIds={'stx-view-transitions':1,'stx-r-css':1};
1648
+ var keepIds={'stx-r-css':1};
1484
1649
  var curStyles=qsa('head style');
1485
1650
  var newStyles=doc.querySelectorAll('head style');
1486
1651
 
@@ -1814,7 +1979,7 @@ else {
1814
1979
  else curRoot.removeAttribute('data-stx-html-attrs');
1815
1980
  }
1816
1981
 
1817
- window.dispatchEvent(new CustomEvent('stx:navigate',{detail:{url:url}}));
1982
+ window.dispatchEvent(new CustomEvent('stx:navigate',{detail:{url:url,direction:ctx.direction}}));
1818
1983
 
1819
1984
  // Execute page scripts FIRST \u2014 they define setup functions and set _latestSetup
1820
1985
  function execScripts(){
@@ -1868,6 +2033,13 @@ else {
1868
2033
  }
1869
2034
 
1870
2035
  function startSwap(){
2036
+ if(ctx.id&&ctx.id!==navSeq)return Promise.resolve(false);
2037
+ if(pushState!==false)innerSnap=innerScroll(activeRoot());
2038
+ setDirection(ctx.direction);
2039
+ // A whole document is written into the container as it is, so retained
2040
+ // screens go first: they would otherwise outlive the page they belong to.
2041
+ collapseScreens();
2042
+ currentContent=getContainer();
1871
2043
  // Clean up existing signals/effects
1872
2044
  if(window.stx&&window.stx._cleanupContainer){
1873
2045
  window.stx._cleanupContainer(currentContent);
@@ -1903,6 +2075,748 @@ else {
1903
2075
  return afterCss(docCssReady,url,startSwap);
1904
2076
  }
1905
2077
 
2078
+ // \u2500\u2500 Screens \u2500\u2500
2079
+ // A phone app keeps the screens it has shown. Going back finds the list
2080
+ // exactly where it was left, and switching tabs finds the other tab as it
2081
+ // was: the same DOM, its scroll, its signals still live. Re-rendering each
2082
+ // of them from the server on every visit is what made an stx app read as a
2083
+ // web page in a shell.
2084
+ //
2085
+ // So with screens on, each page is written into a screen of its own,
2086
+ // <div data-stx-screen>, inside the routed container. Leaving one by a push
2087
+ // or a tab switch hides it instead of disposing it; Back and the tab bar
2088
+ // show it again without running anything. Each tab owns a stack of them,
2089
+ // mirrored by the history entries above the one the app opened with.
2090
+ //
2091
+ // The runtime binds whichever element carries data-stx-content before it
2092
+ // falls back to the router's container, so the screen being shown wears
2093
+ // that marker and a navigation binds the new screen alone, leaving the
2094
+ // retained ones as they are. A container that is itself [data-stx-content]
2095
+ // (the app-shell mode) keeps the old behaviour, as does a page without the
2096
+ // signals runtime, which has nothing to retain.
2097
+ //
2098
+ // On when the page has tab links (data-stx-nav="tab"), or always with
2099
+ // screens:true; never with screens:false.
2100
+ var SCREEN='data-stx-screen';
2101
+ var HIDDEN='data-stx-screen-hidden';
2102
+ var TAB_SEL='[data-stx-nav="tab"],[data-native-tab]';
2103
+ var tabs={};
2104
+ var curTab='';
2105
+ var active=null;
2106
+ var shownSeq=0;
2107
+ var screensLive=false;
2108
+ function screensOn(){
2109
+ if(screensLive)return true;
2110
+ if(o.screens===false||o.screens==='false'||!shouldUseFragmentResponse())return false;
2111
+ var stx=window.stx;
2112
+ if(!stx||typeof stx._cleanupContainer!=='function')return false;
2113
+ var host=getContainer();
2114
+ if(!host||(host.closest&&host.closest('[data-stx-content]')))return false;
2115
+ return o.screens===true||!!qs(TAB_SEL);
2116
+ }
2117
+ // Where the current page lives: its screen, or the container.
2118
+ function activeRoot(){return active&&active.el&&active.el.isConnected?active.el:getContainer()}
2119
+ // A selector looked up in the page on screen first: a retained screen
2120
+ // carries the same ids as the page that rendered it.
2121
+ function findIn(sel){
2122
+ var root=activeRoot(),el=null;
2123
+ try{el=root&&root.querySelector?root.querySelector(sel):null;if(!el)el=qs(sel)}catch(e){}
2124
+ return el;
2125
+ }
2126
+ function stackOf(id){return tabs[id]||(tabs[id]=[])}
2127
+ function newEntry(url,token,depth){return{url:url,key:cacheKey(url),token:token,depth:depth,tab:curTab,el:null,sx:0,sy:0,inner:null,destroys:[],cattrs:'',shown:0}}
2128
+ function tabId(href){return cacheKey(withCurrentLocale(href))}
2129
+ function tabLinks(){return qsa(TAB_SEL)}
2130
+ // The tab the page on screen belongs to: the one the tab bar has current,
2131
+ // which the sticky nav keeps lit for a screen opened from it.
2132
+ function currentTabId(){
2133
+ var links=tabLinks(),best='',i;
2134
+ for(i=0;i<links.length;i++)if(links[i].hasAttribute('data-stx-nav-current'))return tabId(links[i].getAttribute('href')||'');
2135
+ for(i=0;i<links.length;i++){
2136
+ var st=linkState(links[i].getAttribute('href')||'',links[i].getAttribute('data-stx-active-match'));
2137
+ if(st&&(st.exact||st.matched))return tabId(links[i].getAttribute('href')||'');
2138
+ if(st&&st.active&&!best)best=tabId(links[i].getAttribute('href')||'');
2139
+ }
2140
+ return best;
2141
+ }
2142
+ // Which tab link the bar shows as current. Set by hand on a switch: the
2143
+ // sticky nav would otherwise keep the old tab lit over the other tab's
2144
+ // pushed screen, since neither tab's own URL is on screen.
2145
+ function markTab(id){
2146
+ tabLinks().forEach(function(a){
2147
+ if(tabId(a.getAttribute('href')||'')===id)a.setAttribute('data-stx-nav-current','');
2148
+ else a.removeAttribute('data-stx-nav-current');
2149
+ });
2150
+ }
2151
+ function hostAttrString(host){
2152
+ var out=[];
2153
+ if(host&&host.getAttributeNames)host.getAttributeNames().forEach(function(n){
2154
+ if(n==='data-stx-cattrs'||n==='data-stx-route-focus'||n==='data-stx-animating'||(n==='tabindex'&&host.hasAttribute('data-stx-route-focus')))return;
2155
+ out.push(n+'="'+escAttr(host.getAttribute(n))+'"');
2156
+ });
2157
+ return encodeURIComponent(out.join(' '));
2158
+ }
2159
+ // The page the app opened with becomes the first screen the first time a
2160
+ // screen is needed. Moved, not re-rendered: its bindings stay on its nodes.
2161
+ function adoptInitial(host){
2162
+ if(active&&active.el&&active.el.isConnected)return;
2163
+ screensLive=true;
2164
+ var el=ce('div');
2165
+ el.setAttribute(SCREEN,'');
2166
+ while(host.firstChild)el.appendChild(host.firstChild);
2167
+ host.appendChild(el);
2168
+ if(host.__stx_disposers){el.__stx_disposers=host.__stx_disposers;host.__stx_disposers=null}
2169
+ if(!curTab)curTab=currentTabId();
2170
+ active=newEntry(location.pathname+location.search+location.hash,scrollToken,histDepth);
2171
+ active.el=el;
2172
+ active.cattrs=hostAttrString(host);
2173
+ active.shown=++shownSeq;
2174
+ stackOf(curTab)[histDepth]=active;
2175
+ markActive(el);
2176
+ }
2177
+ function markActive(el){
2178
+ var host=getContainer();
2179
+ if(host)Array.prototype.forEach.call(host.querySelectorAll('['+SCREEN+'][data-stx-content]'),function(other){if(other!==el)other.removeAttribute('data-stx-content')});
2180
+ el.setAttribute('data-stx-content','');
2181
+ el.removeAttribute(HIDDEN);
2182
+ }
2183
+ function saveScroll(e){
2184
+ e.sx=window.pageXOffset||window.scrollX||0;
2185
+ e.sy=window.pageYOffset||window.scrollY||0;
2186
+ e.inner=innerScroll(e.el);
2187
+ }
2188
+ // Everything that is global to the page on screen, kept with it while it is
2189
+ // hidden: its page-level onDestroy callbacks (the runtime runs whatever is
2190
+ // queued on the next stx:load, which would tear a retained page down), its
2191
+ // setup, its server data and its route params.
2192
+ function saveEntry(e){
2193
+ var stx=window.stx||{};
2194
+ e.title=document.title;
2195
+ e.setup=stx._latestSetup;
2196
+ e.data=window.__STX_DATA__;
2197
+ e.config=window.__STX_RUNTIME_CONFIG__;
2198
+ e.params=stx._rp||window.__stx_rp||{};
2199
+ if(stx._destroyCallbacks)e.destroys=e.destroys.concat(stx._destroyCallbacks.splice(0));
2200
+ }
2201
+ function restoreEntry(e){
2202
+ var stx=window.stx||{};
2203
+ if(e.title)document.title=e.title;
2204
+ if(e.setup)stx._latestSetup=e.setup;
2205
+ window.__STX_DATA__=e.data||{};
2206
+ window.__STX_RUNTIME_CONFIG__=e.config||{};
2207
+ if(stx._destroyCallbacks&&e.destroys.length)Array.prototype.push.apply(stx._destroyCallbacks,e.destroys);
2208
+ e.destroys=[];
2209
+ applyContainerAttrs(getContainer(),e.cattrs);
2210
+ }
2211
+ // A new page must not share the outgoing page's scope object, or its setup
2212
+ // merges into the one the retained screen's bindings read. Cleaning an
2213
+ // empty element resets that scope and nothing else.
2214
+ function resetScope(){
2215
+ var stx=window.stx;
2216
+ if(!stx||!stx._cleanupContainer)return;
2217
+ var keep=stx._mountCallbacks?stx._mountCallbacks.splice(0):[];
2218
+ stx._cleanupContainer(ce('div'));
2219
+ if(stx._mountCallbacks)Array.prototype.push.apply(stx._mountCallbacks,keep);
2220
+ }
2221
+ function hideScreen(e){
2222
+ if(!e||!e.el)return;
2223
+ unfreeze(e.el);
2224
+ e.el.setAttribute(HIDDEN,'');
2225
+ e.el.removeAttribute('data-stx-content');
2226
+ }
2227
+ // Disposal runs the same paths a navigation always has: the runtime's
2228
+ // container cleanup (effects, scopes, element hooks) and the page-level
2229
+ // onDestroy callbacks that were put aside when the screen was hidden.
2230
+ // Pending mount callbacks belong to whatever is arriving, so they survive.
2231
+ function disposeEntry(e){
2232
+ if(!e||!e.el)return;
2233
+ var el=e.el,stx=window.stx;
2234
+ e.el=null;
2235
+ if(e===active)saveEntry(e);
2236
+ if(stx&&stx._cleanupContainer){
2237
+ var keep=stx._mountCallbacks?stx._mountCallbacks.splice(0):[];
2238
+ try{stx._cleanupContainer(el)}catch(err){console.error('[router] screen cleanup failed:',err)}
2239
+ if(stx._mountCallbacks)Array.prototype.push.apply(stx._mountCallbacks,keep);
2240
+ }
2241
+ var fns=e.destroys;e.destroys=[];
2242
+ fns.forEach(function(fn){try{fn()}catch(err){console.warn('[stx] destroy callback error:',err)}});
2243
+ if(el.parentNode)el.parentNode.removeChild(el);
2244
+ }
2245
+ function eachEntry(fn){for(var id in tabs)tabs[id].forEach(function(e){if(e)fn(e,id)})}
2246
+ // Keep at most screenLimit screens alive, the least recently shown going
2247
+ // first. An evicted screen stays in its stack as an address: Back to it
2248
+ // loads it again.
2249
+ function enforceLimit(){
2250
+ var live=[];
2251
+ eachEntry(function(e){if(e.el&&e!==active&&!e.leaving)live.push(e)});
2252
+ live.sort(function(a,b){return a.shown-b.shown});
2253
+ while(live.length+1>Math.max(1,o.screenLimit|0))disposeEntry(live.shift());
2254
+ }
2255
+ // Everything back to the plain container: before a whole-document swap and
2256
+ // when the screens are given up.
2257
+ // The screen on screen is left in place: the swap cleans the container,
2258
+ // and it with it, as it always has.
2259
+ function collapseScreens(){
2260
+ if(!screensLive)return;
2261
+ settleAnimation();
2262
+ eachEntry(function(e){if(e!==active)disposeEntry(e)});
2263
+ tabs={};active=null;screensLive=false;
2264
+ }
2265
+ // Component scopes are keyed by ids the server derives from the page, so a
2266
+ // second visit to the same page, pushed over a retained first one, brings
2267
+ // the same ids. The retained copies are renamed out of the way, registry
2268
+ // entry and all, so each instance keeps its own and disposing one cannot
2269
+ // reach the other.
2270
+ var retagSeq=0;
2271
+ function retagCollisions(html){
2272
+ var ids={},any=false;
2273
+ html.replace(/data-stx-scope="([^"]+)"/g,function(m,id){ids[id]=1;any=true;return m});
2274
+ if(!any)return;
2275
+ var scopes=window.stx&&window.stx._scopes;
2276
+ eachEntry(function(e){
2277
+ if(!e.el)return;
2278
+ Array.prototype.forEach.call(e.el.querySelectorAll('[data-stx-scope]'),function(node){
2279
+ var id=node.getAttribute('data-stx-scope');
2280
+ if(!ids[id])return;
2281
+ var next=id+'-r'+(++retagSeq);
2282
+ node.setAttribute('data-stx-scope',next);
2283
+ if(scopes&&scopes[id]&&(!scopes[id].__el||scopes[id].__el===node)){scopes[next]=scopes[id];delete scopes[id]}
2284
+ });
2285
+ });
2286
+ }
2287
+
2288
+ // The swap's half: before the page is written, the outgoing screen is put
2289
+ // aside (lifted out of the page for a slide, or hidden), and a new screen
2290
+ // is made for the page to go into, first in the container so that a lookup
2291
+ // by id finds the page on screen before any retained copy of it.
2292
+ function screenBegin(host,ctx,html,writes){
2293
+ adoptInitial(host);
2294
+ var from=active;
2295
+ retagCollisions(html);
2296
+ if(from&&from.el){
2297
+ // A popstate saved the outgoing position already, under the token it
2298
+ // has since replaced; saving again here would file it under the wrong one.
2299
+ if(writes){rememberScroll();scrollSaved=true}
2300
+ saveEntry(from);
2301
+ }
2302
+ resetScope();
2303
+ var el=ce('div');
2304
+ el.setAttribute(SCREEN,'');
2305
+ var anim=!!(from&&from.el&&canAnimate(ctx.direction));
2306
+ if(anim)freeze(from.el);
2307
+ else if(from&&from.el)hideScreen(from);
2308
+ host.insertBefore(el,host.firstChild);
2309
+ markActive(el);
2310
+ return{el:el,from:from,ctx:ctx,anim:anim,cattrs:''};
2311
+ }
2312
+ // After the history write, so the entry knows its token and depth.
2313
+ function screenCommit(scr,href){
2314
+ var e=scr.ctx.entry||newEntry(href,scrollToken,histDepth);
2315
+ e.url=href;e.key=cacheKey(href);e.token=scrollToken;e.depth=histDepth;e.tab=curTab;
2316
+ e.el=scr.el;e.cattrs=scr.cattrs;e.shown=++shownSeq;e.destroys=[];
2317
+ var stack=stackOf(curTab);
2318
+ // A push drops whatever was forward of it; a pop or a replacement takes
2319
+ // the place of what was at its depth. The outgoing screen is left to the
2320
+ // transition, which disposes it once it is off screen.
2321
+ for(var i=e.depth;i<stack.length;i++){var x=stack[i];if(x&&x!==e&&x!==scr.from)disposeEntry(x)}
2322
+ stack.length=e.depth;
2323
+ stack[e.depth]=e;
2324
+ active=e;
2325
+ scrollSaved=false;
2326
+ }
2327
+ function screenEnd(scr){
2328
+ var from=scr.from,dir=scr.ctx.direction;
2329
+ if(!from||!from.el){finishScreen();return}
2330
+ // Retained: left by a push, or by a tab switch. Popped or replaced: gone.
2331
+ var keep=dir==='push'||dir==='tab';
2332
+ var stack=tabs[from.tab];
2333
+ if(keep&&!(stack&&stack[from.depth]===from))keep=false;
2334
+ from.leaving=true;
2335
+ var after=function(){
2336
+ from.leaving=false;
2337
+ if(keep&&from.el)hideScreen(from);
2338
+ else disposeEntry(from);
2339
+ finishScreen();
2340
+ };
2341
+ if(scr.anim)animateScreens(from.el,scr.el,dir,after);
2342
+ else after();
2343
+ }
2344
+ function finishScreen(){
2345
+ enforceLimit();
2346
+ observeLinks();
2347
+ }
2348
+
2349
+ // Show a screen that is already here: Back to one below in the stack, or a
2350
+ // tab's top screen. Nothing is fetched and no page script runs; the page is
2351
+ // told it is on screen again (stx:screen-shown) so it can refresh whatever
2352
+ // may have gone stale while it was hidden.
2353
+ function showRetained(to,dir,opts){
2354
+ opts=opts||{};
2355
+ settleAnimation();
2356
+ var from=active,host=getContainer();
2357
+ if(navAbort){try{navAbort.abort()}catch(e){}navAbort=null}
2358
+ navSeq++;
2359
+ isNavigating=false;
2360
+ document.body.classList.remove(o.loadingClass);
2361
+ if(from&&from.el){if(!opts.settled)saveScroll(from);saveEntry(from)}
2362
+ setDirection(dir);
2363
+ var anim=!opts.settled&&from&&from.el&&from!==to&&canAnimate(dir,true);
2364
+ if(anim)freeze(from.el);
2365
+ else if(from&&from.el&&from!==to&&!opts.settled)hideScreen(from);
2366
+ unfreeze(to.el);
2367
+ markActive(to.el);
2368
+ active=to;
2369
+ to.shown=++shownSeq;
2370
+ restoreEntry(to);
2371
+ pendingScroll=null;pendingInner=null;
2372
+ window.scrollTo({left:to.sx,top:to.sy,behavior:'instant'});
2373
+ applyInner(to.el,to.inner);
2374
+ if(opts.settled&&from&&from!==to&&from.el)hideScreen(from);
2375
+ refreshCurrentLinks();
2376
+ window.dispatchEvent(new CustomEvent('stx:navigate',{detail:{url:to.url,direction:dir,retained:true,params:to.params||{}}}));
2377
+ focusAfterNavigation('');
2378
+ setTimeout(announceRoute,0);
2379
+ window.dispatchEvent(new CustomEvent('stx:screen-shown',{detail:{url:to.url,direction:dir}}));
2380
+ revalidate(to.key,to.url);
2381
+ var keep=dir==='push'||dir==='tab';
2382
+ var after=function(){
2383
+ if(from&&from!==to){
2384
+ if(dir==='pop'){
2385
+ // Everything above the screen shown is gone from the stack.
2386
+ var stack=tabs[to.tab]||[];
2387
+ for(var i=to.depth+1;i<stack.length;i++)if(stack[i]&&stack[i]!==from)disposeEntry(stack[i]);
2388
+ stack.length=to.depth+1;
2389
+ }
2390
+ if(keep&&from.el)hideScreen(from);
2391
+ else if(!keep)disposeEntry(from);
2392
+ }
2393
+ finishScreen();
2394
+ settleDirection();
2395
+ };
2396
+ if(anim){from.leaving=true;animateScreens(from.el,to.el,dir,function(){from.leaving=false;after()})}
2397
+ else after();
2398
+ return true;
2399
+ }
2400
+
2401
+ // \u2500\u2500 Direction and motion \u2500\u2500
2402
+ // data-nav-direction on <html> says what kind of move is under way --
2403
+ // push, pop, tab or replace -- for as long as it is, so CSS (and a page's
2404
+ // own transitions) can tell a step forward from a step back.
2405
+ var animEnd=null;
2406
+ function setDirection(d){if(d)document.documentElement.setAttribute('data-nav-direction',d)}
2407
+ function settleDirection(){
2408
+ if(isNavigating||animEnd)return;
2409
+ document.documentElement.removeAttribute('data-nav-direction');
2410
+ }
2411
+ function reducedMotion(){
2412
+ try{return !!(window.matchMedia&&window.matchMedia('(prefers-reduced-motion: reduce)').matches)}catch(e){return false}
2413
+ }
2414
+ // instantNav belongs to a navigation that fetched; a screen shown from
2415
+ // the stack (Back) is not one, and must not inherit the last tab tap's.
2416
+ function canAnimate(dir,shown){
2417
+ return (dir==='push'||dir==='pop')&&(shown||!instantNav)&&o.navDuration>0&&typeof window.getComputedStyle==='function';
2418
+ }
2419
+ // The first background behind the container that is not transparent: the
2420
+ // screens are transparent, and two of them sliding over each other need
2421
+ // the page's colour to hide the one underneath.
2422
+ function screenBackground(host){
2423
+ for(var n=host;n&&n.nodeType===1;n=n.parentNode){
2424
+ var c='';
2425
+ try{c=getComputedStyle(n).backgroundColor}catch(e){}
2426
+ if(c&&c!=='transparent'&&c!=='rgba(0, 0, 0, 0)')return c;
2427
+ }
2428
+ return '';
2429
+ }
2430
+ // Lifted out of the flow and pinned where it is on screen, as a box the
2431
+ // height of the viewport scrolled to the same place: the page can scroll
2432
+ // to wherever the next screen wants, the outgoing one does not move, and a
2433
+ // sticky header inside it stays stuck.
2434
+ function freeze(el,top){
2435
+ var r=el.getBoundingClientRect();
2436
+ var vh=window.innerHeight||document.documentElement.clientHeight||0;
2437
+ var at=top===undefined?r.top:top;
2438
+ var y=Math.max(at,0);
2439
+ var s=el.style;
2440
+ s.position='fixed';s.top=y+'px';s.left=r.left+'px';s.width=r.width+'px';s.height=Math.max(vh-y,0)+'px';s.overflow='hidden';s.margin='0';
2441
+ el.scrollTop=y-at;
2442
+ }
2443
+ function unfreeze(el){
2444
+ if(!el)return;
2445
+ var s=el.style;
2446
+ ['position','top','left','width','height','overflow','margin','transform','transition','zIndex','backgroundColor','pointerEvents'].forEach(function(k){s[k]=''});
2447
+ el.removeAttribute('data-stx-screen-enter');
2448
+ el.removeAttribute('data-stx-screen-leave');
2449
+ el.scrollTop=0;
2450
+ }
2451
+ function parseDuration(v){
2452
+ v=String(v||'').split(',')[0].trim();
2453
+ var n=parseFloat(v);
2454
+ if(!(n>=0))return -1;
2455
+ return v.indexOf('ms')>0?n:n*1000;
2456
+ }
2457
+ function dimLayer(host){
2458
+ var r=host.getBoundingClientRect();
2459
+ var dim=ce('div');
2460
+ dim.setAttribute('data-stx-screen-dim','');
2461
+ dim.style.left=r.left+'px';
2462
+ dim.style.width=r.width+'px';
2463
+ return dim;
2464
+ }
2465
+ // Two real screens, animated by the shipped CSS: the one arriving and the
2466
+ // one leaving, and a dim between them over the one underneath.
2467
+ function animateScreens(fromEl,toEl,dir,done){
2468
+ var host=getContainer();
2469
+ var bg=screenBackground(host);
2470
+ var dim=dimLayer(host);
2471
+ host.setAttribute('data-stx-animating','');
2472
+ fromEl.style.backgroundColor=bg;toEl.style.backgroundColor=bg;
2473
+ fromEl.style.pointerEvents='none';
2474
+ fromEl.setAttribute('data-stx-screen-leave','');
2475
+ toEl.setAttribute('data-stx-screen-enter','');
2476
+ host.appendChild(dim);
2477
+ var ms=-1;
2478
+ try{ms=parseDuration(getComputedStyle(toEl).animationDuration)}catch(e){}
2479
+ if(!(ms>0))ms=o.navDuration;
2480
+ var timer=setTimeout(end,ms+120);
2481
+ function onEnd(e){if(e.target===toEl)end()}
2482
+ toEl.addEventListener('animationend',onEnd);
2483
+ function end(){
2484
+ if(animEnd!==end)return;
2485
+ animEnd=null;
2486
+ clearTimeout(timer);
2487
+ toEl.removeEventListener('animationend',onEnd);
2488
+ if(dim.parentNode)dim.parentNode.removeChild(dim);
2489
+ host.removeAttribute('data-stx-animating');
2490
+ toEl.removeAttribute('data-stx-screen-enter');
2491
+ toEl.style.backgroundColor='';
2492
+ done();
2493
+ settleDirection();
2494
+ }
2495
+ animEnd=end;
2496
+ }
2497
+ // A navigation that starts while a slide is still running finishes the
2498
+ // slide first, rather than lifting a screen that is halfway across.
2499
+ function settleAnimation(){if(animEnd)animEnd()}
2500
+
2501
+ // \u2500\u2500 Tabs \u2500\u2500
2502
+ // Back never crosses tabs: the history above the entry the app opened with
2503
+ // is always the current tab's stack. A switch rewinds to that entry, writes
2504
+ // the target tab's stack in its place, and shows its top screen exactly as
2505
+ // it was left.
2506
+ var rewinding=null;
2507
+ function rewind(){
2508
+ if(histDepth<=0)return Promise.resolve();
2509
+ return new Promise(function(resolve){
2510
+ var n=histDepth;
2511
+ var timer=setTimeout(finish,700);
2512
+ function finish(){
2513
+ clearTimeout(timer);
2514
+ if(rewinding===finish)rewinding=null;
2515
+ histDepth=(history.state&&history.state[DEPTH])|0;
2516
+ var token=history.state&&history.state[SCROLL_TOKEN];
2517
+ if(token)scrollToken=token;
2518
+ resolve();
2519
+ }
2520
+ rewinding=finish;
2521
+ history.go(-n);
2522
+ });
2523
+ }
2524
+ function entryState(e,pushed){
2525
+ var st={};
2526
+ st[SCROLL_TOKEN]=e.token;st[DEPTH]=e.depth;st[TAB]=e.tab;
2527
+ if(pushed)st[PUSHED_MARK]=true;
2528
+ return st;
2529
+ }
2530
+ function selectTab(href){
2531
+ if(!href)return Promise.resolve(false);
2532
+ var id=tabId(href);
2533
+ var on=screensOn();
2534
+ if(on&&!screensLive)adoptInitial(getContainer());
2535
+ if(!curTab)curTab=on&&active?active.tab:currentTabId();
2536
+ if(id===curTab)return reselectTab(href);
2537
+ if(active&&active.el){rememberScroll();saveScroll(active)}
2538
+ settleAnimation();
2539
+ if(navAbort){try{navAbort.abort()}catch(e){}navAbort=null}
2540
+ var seq=++navSeq;
2541
+ return rewind().then(function(){
2542
+ if(seq!==navSeq)return false;
2543
+ curTab=id;
2544
+ markTab(id);
2545
+ var stack=on?(tabs[id]||[]).filter(Boolean):[];
2546
+ if(!stack.length){
2547
+ if(on)tabs[id]=[];
2548
+ navCtxNext={direction:'tab'};
2549
+ instantNext=true;
2550
+ return navigate(href,'tab');
2551
+ }
2552
+ // Rewritten in order, so Back walks this tab's own stack.
2553
+ stack.forEach(function(e,i){
2554
+ e.depth=i;e.tab=id;
2555
+ if(i===0)history.replaceState(entryState(e,false),'',e.url);
2556
+ else history.pushState(entryState(e,true),'',e.url);
2557
+ });
2558
+ tabs[id]=stack;
2559
+ var top=stack[stack.length-1];
2560
+ histDepth=top.depth;
2561
+ scrollToken=top.token;
2562
+ if(top.el)return showRetained(top,'tab');
2563
+ // Its top screen was let go: load it into the same entry.
2564
+ pendingScroll=[top.sx,top.sy];
2565
+ navCtxNext={direction:'tab',entry:top};
2566
+ instantNext=true;
2567
+ return navigate(top.url,false);
2568
+ });
2569
+ }
2570
+ // The tab that is already current, selected again: back to the top of its
2571
+ // screen, and when it is there already, back to the tab's first screen.
2572
+ // stx:tabreselect says which, and a page that cancels it keeps its own.
2573
+ function reselectTab(href){
2574
+ var root=activeRoot();
2575
+ var y=window.pageYOffset||window.scrollY||0;
2576
+ var inner=innerScroll(root);
2577
+ var atRoot=active?active.depth===0&&active.key===tabId(href):cacheKey(location.href)===tabId(href);
2578
+ var action=(y>0||inner)?'top':atRoot?'none':'root';
2579
+ var ev=new CustomEvent('stx:tabreselect',{cancelable:true,detail:{href:href,action:action}});
2580
+ window.dispatchEvent(ev);
2581
+ if(ev.defaultPrevented||action==='none')return Promise.resolve(false);
2582
+ if(action==='top'){
2583
+ window.scrollTo({top:0,left:0,behavior:reducedMotion()?'instant':'smooth'});
2584
+ if(root&&root.querySelectorAll)root.querySelectorAll('[data-stx-scroll]').forEach(function(el){if(el.scrollTo)el.scrollTo({top:0,left:0,behavior:'smooth'});else el.scrollTop=0});
2585
+ return Promise.resolve(true);
2586
+ }
2587
+ var stack=tabs[curTab]||[];
2588
+ var first=stack.filter(Boolean)[0];
2589
+ if(first&&first.el&&first.key===tabId(href)&&histDepth>0){
2590
+ var target=first;
2591
+ return new Promise(function(resolve){
2592
+ history.go(target.depth-histDepth);
2593
+ setTimeout(function(){resolve(true)},0);
2594
+ });
2595
+ }
2596
+ // The tab's first screen is not here (opened on a deep link, or let
2597
+ // go): load the tab's own page in its place.
2598
+ return rewind().then(function(){
2599
+ navCtxNext={direction:'pop'};
2600
+ return navigate(href,'tab');
2601
+ });
2602
+ }
2603
+
2604
+ // \u2500\u2500 Swipe back \u2500\u2500
2605
+ // A pan from the left edge drags the screen on top away and shows the
2606
+ // retained one underneath, the way iOS does: the one underneath moves from
2607
+ // -30% and brightens as the top one goes. Released past half way, or
2608
+ // flicked, it completes as a Back (history.back(), shown without a second
2609
+ // animation); otherwise it springs back. Only where there is a screen to
2610
+ // go back to in this tab, never from inside data-stx-no-swipe, and never
2611
+ // over something that pans sideways on its own (touch-action none, pan-x,
2612
+ // pan-y, or a horizontal scroller that is not at its start).
2613
+ var swipe=null;
2614
+ var swipeSettled=null;
2615
+ function swipePrev(){
2616
+ if(o.swipeBack===false||!screensLive||!active||!active.el||isNavigating||animEnd)return null;
2617
+ var prev=(tabs[curTab]||[])[active.depth-1];
2618
+ return prev&&prev.el?prev:null;
2619
+ }
2620
+ function swipeBlocked(target){
2621
+ var host=getContainer();
2622
+ for(var n=target;n&&n.nodeType===1&&n!==host;n=n.parentNode){
2623
+ if(n.hasAttribute('data-stx-no-swipe'))return true;
2624
+ var cs=null;
2625
+ try{cs=getComputedStyle(n)}catch(e){}
2626
+ if(!cs)continue;
2627
+ var ta=String(cs.touchAction||'').split(' ');
2628
+ var has=function(v){return ta.indexOf(v)!==-1};
2629
+ if(has('none')||(has('pan-x')||has('pan-left')||has('pan-right'))!==(has('pan-y')||has('pan-up')||has('pan-down')))return true;
2630
+ var ox=String(cs.overflowX||'');
2631
+ if((ox==='auto'||ox==='scroll')&&n.scrollWidth>n.clientWidth&&n.scrollLeft>0)return true;
2632
+ }
2633
+ return false;
2634
+ }
2635
+ function now(){return window.performance&&performance.now?performance.now():Date.now()}
2636
+ function touchOf(e){return (e.touches&&e.touches[0])||(e.changedTouches&&e.changedTouches[0])||null}
2637
+ function swipeStart(e){
2638
+ if(swipe||!e.touches||e.touches.length!==1)return;
2639
+ var t=e.touches[0];
2640
+ if(t.clientX>o.swipeEdge)return;
2641
+ var prev=swipePrev();
2642
+ if(!prev||swipeBlocked(e.target))return;
2643
+ swipe={prev:prev,x0:t.clientX,y0:t.clientY,x:t.clientX,t:now(),v:0,on:false};
2644
+ }
2645
+ function swipeBegin(){
2646
+ var cur=active,prev=swipe.prev,host=getContainer();
2647
+ var w=host.getBoundingClientRect().width||window.innerWidth||1;
2648
+ saveScroll(cur);
2649
+ var docTop=cur.el.getBoundingClientRect().top+(window.pageYOffset||window.scrollY||0);
2650
+ swipe.w=w;
2651
+ swipe.cur=cur;
2652
+ swipe.bg=screenBackground(host);
2653
+ swipe.dim=dimLayer(host);
2654
+ swipe.dim.setAttribute('data-stx-drag','');
2655
+ // Shown before it is measured: a hidden screen has no box to pin.
2656
+ prev.el.removeAttribute(HIDDEN);
2657
+ freeze(prev.el,docTop-prev.sy);
2658
+ applyInner(prev.el,prev.inner);
2659
+ prev.el.style.zIndex='1';
2660
+ prev.el.style.backgroundColor=swipe.bg;
2661
+ cur.el.style.position='relative';
2662
+ cur.el.style.zIndex='3';
2663
+ cur.el.style.backgroundColor=swipe.bg;
2664
+ host.setAttribute('data-stx-animating','');
2665
+ host.appendChild(swipe.dim);
2666
+ setDirection('pop');
2667
+ swipe.on=true;
2668
+ }
2669
+ function swipeDraw(dx){
2670
+ var p=Math.min(Math.max(dx/swipe.w,0),1);
2671
+ swipe.p=p;
2672
+ swipe.cur.el.style.transform='translateX('+(p*swipe.w)+'px)';
2673
+ swipe.prev.el.style.transform='translateX('+(-0.3*swipe.w*(1-p))+'px)';
2674
+ swipe.dim.style.opacity=String(1-p);
2675
+ }
2676
+ function swipeMove(e){
2677
+ if(!swipe)return;
2678
+ var t=touchOf(e);
2679
+ if(!t)return;
2680
+ var dx=t.clientX-swipe.x0,dy=t.clientY-swipe.y0;
2681
+ if(!swipe.on){
2682
+ if(Math.abs(dx)<8&&Math.abs(dy)<8)return;
2683
+ // Vertical first, or leftwards: a scroll, not a Back.
2684
+ if(dx<=0||Math.abs(dy)>=Math.abs(dx)){swipe=null;return}
2685
+ swipeBegin();
2686
+ }
2687
+ if(e.cancelable)e.preventDefault();
2688
+ var n=now(),dt=n-swipe.t;
2689
+ if(dt>0)swipe.v=swipe.v*0.2+((t.clientX-swipe.x)/dt)*0.8;
2690
+ swipe.x=t.clientX;swipe.t=n;
2691
+ swipeDraw(dx);
2692
+ }
2693
+ function swipeEnd(e){
2694
+ if(!swipe)return;
2695
+ var s=swipe;
2696
+ swipe=null;
2697
+ if(!s.on)return;
2698
+ // A finger held still before lifting has no speed left.
2699
+ if(now()-s.t>80)s.v=0;
2700
+ var commit=e.type!=='touchcancel'&&(s.p>0.5||s.v>0.5);
2701
+ var remaining=commit?(1-s.p)*s.w:s.p*s.w;
2702
+ var ms=Math.round(Math.min(o.navDuration,Math.max(120,remaining/Math.max(Math.abs(s.v),0.6))));
2703
+ var ease='cubic-bezier(0.2, 0.9, 0.3, 1)';
2704
+ [s.cur.el,s.prev.el].forEach(function(el){el.style.transition='transform '+ms+'ms '+ease});
2705
+ s.dim.style.transition='opacity '+ms+'ms '+ease;
2706
+ s.cur.el.style.transform=commit?'translateX('+s.w+'px)':'translateX(0px)';
2707
+ s.prev.el.style.transform=commit?'translateX(0px)':'translateX('+(-0.3*s.w)+'px)';
2708
+ s.dim.style.opacity=commit?'0':'1';
2709
+ var finished=false;
2710
+ var finish=function(){
2711
+ if(finished)return;
2712
+ finished=true;
2713
+ animEnd=null;
2714
+ if(s.dim.parentNode)s.dim.parentNode.removeChild(s.dim);
2715
+ getContainer().removeAttribute('data-stx-animating');
2716
+ if(commit){
2717
+ // Already where Back would put it: the popstate that follows shows
2718
+ // the screen underneath as it is, with no second animation.
2719
+ s.cur.el.style.visibility='hidden';
2720
+ swipeSettled=s.prev;
2721
+ history.back();
2722
+ }
2723
+ else{
2724
+ hideScreen(s.prev);
2725
+ s.cur.el.style.transform='';s.cur.el.style.transition='';s.cur.el.style.position='';s.cur.el.style.zIndex='';s.cur.el.style.backgroundColor='';
2726
+ settleDirection();
2727
+ }
2728
+ };
2729
+ animEnd=finish;
2730
+ setTimeout(finish,ms+40);
2731
+ }
2732
+ document.addEventListener('touchstart',swipeStart,{capture:true,passive:true});
2733
+ document.addEventListener('touchmove',swipeMove,{capture:true,passive:false});
2734
+ document.addEventListener('touchend',swipeEnd,{capture:true,passive:true});
2735
+ document.addEventListener('touchcancel',swipeEnd,{capture:true,passive:true});
2736
+ // The system is short of memory: let go of every hidden screen except the
2737
+ // one a swipe back would show.
2738
+ window.addEventListener('craftMemoryWarning',function(){
2739
+ var keep=active?(tabs[curTab]||[])[active.depth-1]:null;
2740
+ eachEntry(function(e){if(e!==active&&e!==keep&&!e.leaving)disposeEntry(e)});
2741
+ });
2742
+
2743
+ // \u2500\u2500 Revalidation and updates \u2500\u2500
2744
+ // A page served from the router's cache, or a screen shown again, is asked
2745
+ // for once more behind the swap. If it changed, the cache takes the new copy
2746
+ // and stx:updated says so, so the page can refresh what it shows; the
2747
+ // screen is never swapped out from under the user.
2748
+ function revalidate(key,url){
2749
+ if(!o.revalidate||!o.cache||!key||prefetching[key])return;
2750
+ if(Date.now()-(cacheAt[key]||0)<o.revalidateAfter)return;
2751
+ var wantsFragment=shouldUseFragmentResponse();
2752
+ var before=cache[key];
2753
+ prefetching[key]=fetch(url,{headers:wantsFragment?{'X-STX-Router':'true','Accept':'text/html'}:{'Accept':'text/html'}}).then(function(r){
2754
+ var incoming=r.headers.get('X-STX-Build')||'';
2755
+ if(isBuildSkew(incoming)){reloadForSkew(url,incoming,true);return null}
2756
+ return readPrefetchResponse(r,wantsFragment);
2757
+ }).then(function(result){
2758
+ if(!result)return;
2759
+ if(o.cache)setCache(key,result.html,result.layout,result.layoutGroup,result.title,result.containerAttrs);
2760
+ if(before!==undefined&&before!==result.html&&cacheKey(location.href)===key)emitUpdated(url,'page');
2761
+ }).catch(function(){}).finally(function(){delete prefetching[key]});
2762
+ }
2763
+ // The offline worker answered from its cache and found something newer
2764
+ // behind it. It posts { type: 'stx:updated', url, kind }, which its own
2765
+ // register script turns into a window event; the router does that only
2766
+ // where that script is not on the page, so the event is heard once. Either
2767
+ // way a page the router has cached is dropped, so the next visit gets the
2768
+ // new one.
2769
+ var ownUpdate=false;
2770
+ function emitUpdated(url,kind){
2771
+ ownUpdate=true;
2772
+ try{window.dispatchEvent(new CustomEvent('stx:updated',{detail:{url:url,kind:kind||'page'}}))}finally{ownUpdate=false}
2773
+ }
2774
+ window.addEventListener('stx:updated',function(e){
2775
+ var d=e&&e.detail;
2776
+ if(ownUpdate||!d||!d.url||d.kind==='api')return;
2777
+ try{evictCache(cacheKey(d.url))}catch(err){}
2778
+ });
2779
+ try{
2780
+ var sw=navigator.serviceWorker;
2781
+ if(sw&&sw.addEventListener)sw.addEventListener('message',function(e){
2782
+ var d=e&&e.data;
2783
+ if(!d||d.type!=='stx:updated'||window.stxOffline)return;
2784
+ window.dispatchEvent(new CustomEvent('stx:updated',{detail:{url:d.url,kind:d.kind||'page'}}));
2785
+ });
2786
+ }catch(e){}
2787
+
2788
+ // \u2500\u2500 Prefetch on sight \u2500\u2500
2789
+ // Links are fetched as they scroll into view, a few per screen, so most
2790
+ // taps find their page already here. Not on a connection that asked to
2791
+ // save data, and not for a link marked data-stx-prefetch="false" or
2792
+ // "hover" (hover and touch still prefetch everything).
2793
+ var sightObserver=null;
2794
+ var sightCount=0;
2795
+ function observeLinks(){
2796
+ if(!o.prefetch||!o.cache||o.prefetchVisible===false||typeof IntersectionObserver!=='function')return;
2797
+ var c=navigator.connection;
2798
+ if(c&&(c.saveData||/2g/.test(c.effectiveType||'')))return;
2799
+ if(!sightObserver)sightObserver=new IntersectionObserver(function(entries){
2800
+ entries.forEach(function(en){
2801
+ if(!en.isIntersecting)return;
2802
+ sightObserver.unobserve(en.target);
2803
+ if(sightCount>=o.prefetchVisibleMax)return;
2804
+ sightCount++;
2805
+ prefetchLink(en.target);
2806
+ });
2807
+ });
2808
+ sightCount=0;
2809
+ var root=activeRoot()||document.body;
2810
+ if(!root||!root.querySelectorAll)return;
2811
+ root.querySelectorAll('[data-stx-link][href]').forEach(function(a){
2812
+ if(a.__stxSeen)return;
2813
+ var p=a.getAttribute('data-stx-prefetch');
2814
+ if(p==='false'||p==='hover'||p==='none')return;
2815
+ a.__stxSeen=1;
2816
+ sightObserver.observe(a);
2817
+ });
2818
+ }
2819
+
1906
2820
  // \u2500\u2500 Link interception \u2500\u2500
1907
2821
  // Links the router must never touch, however it found them. This is the
1908
2822
  // opt-out set, and it is deliberately separate from shouldIntercept's
@@ -2005,6 +2919,8 @@ else {
2005
2919
  e.preventDefault();
2006
2920
  e.stopPropagation();
2007
2921
  log('[router] navigating to:',href);
2922
+ // A tab: its own stack, never a back entry (selectTab).
2923
+ if(link.getAttribute('data-stx-nav')==='tab'||link.hasAttribute('data-native-tab')){selectTab(href);return}
2008
2924
  instantNext=link.getAttribute('data-stx-transition')==='none';
2009
2925
  navigate(withCurrentLocale(href));
2010
2926
  });
@@ -2146,16 +3062,33 @@ else {
2146
3062
 
2147
3063
  // \u2500\u2500 Back/forward \u2500\u2500
2148
3064
  window.addEventListener('popstate',function(){
3065
+ // A tab switch rewinding to the first entry: not a navigation of its own.
3066
+ if(rewinding){rewinding();return}
3067
+ var settled=swipeSettled;
3068
+ swipeSettled=null;
2149
3069
  // Nothing has scrolled yet (restoration is manual), so the viewport still
2150
3070
  // shows the entry being left: save it under its own token before adopting
2151
3071
  // the popped entry's, and hand the swap the position to land on.
2152
- rememberScroll();
3072
+ if(!settled)rememberScroll();
3073
+ var st=history.state;
3074
+ // An entry the router did not write (a page's own pushState) keeps the
3075
+ // depth it was written at; a lower one is a step back.
3076
+ var depth=st&&typeof st[DEPTH]==='number'?st[DEPTH]:histDepth;
3077
+ var dir=depth<histDepth?'pop':depth>histDepth?'push':'replace';
3078
+ histDepth=depth;
3079
+ var popped=st&&st[SCROLL_TOKEN];
3080
+ scrollToken=popped||newScrollToken();
2153
3081
  if(restoreScroll){
2154
- var popped=history.state&&history.state[SCROLL_TOKEN];
2155
- scrollToken=popped||newScrollToken();
2156
3082
  if(!popped)stampScrollToken();
2157
3083
  pendingScroll=readScroll(scrollToken);
3084
+ pendingInner=readInner(scrollToken);
3085
+ }
3086
+ if(screensLive){
3087
+ if(st&&st[TAB]!==undefined&&st[TAB]!==curTab&&tabs[st[TAB]]){curTab=st[TAB];markTab(curTab)}
3088
+ var target=(tabs[curTab]||[])[depth];
3089
+ if(target&&target.el&&target.token===scrollToken&&target!==active){showRetained(target,dir==='replace'?'pop':dir,{settled:settled===target});return}
2158
3090
  }
3091
+ navCtxNext={direction:dir};
2159
3092
  navigate(location.pathname+location.search+location.hash,false);
2160
3093
  });
2161
3094
 
@@ -2199,7 +3132,13 @@ else {
2199
3132
  setCache(key,result.html,result.layout,result.layoutGroup,result.title,result.containerAttrs);
2200
3133
  if(eager)keepPage(key,result);
2201
3134
  }
2202
- if(result)loadModuleRegistries(result.html,href);
3135
+ if(result){
3136
+ loadModuleRegistries(result.html,href);
3137
+ // Its stylesheet too, so the tap never waits on cssLoadTimeout for a
3138
+ // sheet it could have had all along. Added unapplied (media=print),
3139
+ // as a navigation adds it; the swap makes it live.
3140
+ if(result.html.indexOf('<!--stx-fragment')===0)preloadGeneratedCss(fragmentCssHrefs(result.html),location.href);
3141
+ }
2203
3142
  }).catch(function(){}).finally(function(){delete prefetching[key]});
2204
3143
  }
2205
3144
 
@@ -2295,6 +3234,7 @@ else {
2295
3234
  document.addEventListener('mouseover',onIntent,true);
2296
3235
  document.addEventListener('touchstart',onIntent,{capture:true,passive:true});
2297
3236
  window.addEventListener('stx:load',prefetchEager);
3237
+ window.addEventListener('stx:load',function(){setTimeout(observeLinks,0)});
2298
3238
  }
2299
3239
 
2300
3240
  // \u2500\u2500 Active link management \u2500\u2500
@@ -2361,7 +3301,7 @@ else {
2361
3301
  // updateActiveLinks has already rewritten the classes by now.
2362
3302
  function updateNav(){
2363
3303
  var done=new Set();
2364
- qsa('nav, #mobileNav, [data-stx-nav]').forEach(function(nav){
3304
+ qsa('nav, #mobileNav, [data-stx-nav]:not(a)').forEach(function(nav){
2365
3305
  var states=[];
2366
3306
  Array.prototype.forEach.call(nav.querySelectorAll('a[href]'),function(a){
2367
3307
  if(done.has(a)||!a.hasAttribute('data-stx-link'))return;
@@ -2457,16 +3397,40 @@ else {
2457
3397
  // The container the router focuses after a navigation is not a
2458
3398
  // control, so it draws no focus ring: Safari drew one around the whole
2459
3399
  // page, a blue line along its bottom edge on every screen.
2460
- var css='[data-stx-route-focus]:focus{outline:none}.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}html.stx-instant::view-transition-group(*),html.stx-instant::view-transition-old(*),html.stx-instant::view-transition-new(*){animation:none!important}';
3400
+ // Links stay live while a page loads: a tap on another one is the newest
3401
+ // navigation and wins (navigate), where pointer-events:none used to
3402
+ // swallow it.
3403
+ var css='[data-stx-route-focus]:focus{outline:none}.stx-navigating{cursor:progress}#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}html.stx-instant::view-transition-group(*),html.stx-instant::view-transition-old(*),html.stx-instant::view-transition-new(*){animation:none!important}';
3404
+ // One View Transitions block. There used to be two, and the second
3405
+ // (injected after this one) silently overrode the first: the page stays
3406
+ // put and only the routed content fades, which is what this now says
3407
+ // once. The retained screen inside it is not named, so the container
3408
+ // and the screen never carry the same name.
2461
3409
  if(o.viewTransitions&&'startViewTransition' in document){
2462
3410
  var dur=(o.viewTransitionDuration||220)+'ms';
2463
3411
  var ease=o.viewTransitionEasing||'cubic-bezier(0.16, 1, 0.3, 1)';
2464
- css+='::view-transition-old(root),::view-transition-new(root){animation-duration:'+dur+';animation-timing-function:'+ease+'}';
2465
- css+='::view-transition-old(root){animation-name:stx-r-fade-out}::view-transition-new(root){animation-name:stx-r-fade-in}';
3412
+ css+='::view-transition-old(root),::view-transition-new(root){animation:none}::view-transition{background:transparent}';
3413
+ css+='main,#app-content,[data-stx-content]:not([data-stx-screen]){view-transition-name:stx-content}::view-transition-group(stx-content){overflow:hidden}';
3414
+ css+='::view-transition-old(stx-content){animation:stx-r-fade-out '+dur+' '+ease+' both}::view-transition-new(stx-content){animation:stx-r-fade-in '+dur+' '+ease+' both}';
2466
3415
  css+='@keyframes stx-r-fade-out{from{opacity:1;transform:translateY(0)}to{opacity:0;transform:translateY(-4px)}}';
2467
3416
  css+='@keyframes stx-r-fade-in{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:translateY(0)}}';
2468
- css+='@media (prefers-reduced-motion: reduce){::view-transition-old(root),::view-transition-new(root){animation-duration:0s;animation-name:none}}';
3417
+ css+='@media (prefers-reduced-motion: reduce){::view-transition-old(stx-content),::view-transition-new(stx-content){animation-duration:0s;animation-name:none}}';
2469
3418
  }
3419
+ // Screens: a hidden one takes no room, and a screen lays its page out
3420
+ // the way the container would have. Push and pop are iOS's: the new
3421
+ // screen slides in from the right edge while the one under it moves a
3422
+ // third of the way left and dims, over --stx-nav-duration on a spring
3423
+ // (linear() where the browser has it). Reduced motion cross-fades.
3424
+ css+='[data-stx-screen]{display:inherit;flex-direction:inherit;flex-wrap:inherit;gap:inherit;align-items:inherit;justify-content:inherit;grid-template-columns:inherit;grid-template-rows:inherit;grid-column:1/-1;flex:1 1 auto;align-self:stretch;min-width:0}['+HIDDEN+']{display:none!important}';
3425
+ css+=':root{--stx-nav-duration:'+(o.navDuration|0)+'ms;--stx-nav-ease:cubic-bezier(0.32,0.72,0,1)}@supports (animation-timing-function:linear(0,1)){:root{--stx-nav-ease:linear(0,.079,.236,.403,.551,.671,.764,.833,.883,.919,.944,.962,.974,.983,.988,.992,.995,.997,.998,.999,1)}}';
3426
+ css+='[data-stx-animating]{overflow-x:clip}[data-stx-screen-enter],[data-stx-screen-leave]{position:relative;will-change:transform;animation-duration:var(--stx-nav-duration);animation-timing-function:var(--stx-nav-ease);animation-fill-mode:both}';
3427
+ css+='html[data-nav-direction=push] [data-stx-screen-enter]{animation-name:stx-nav-in;z-index:3;box-shadow:0 0 24px rgb(0 0 0 / .12)}html[data-nav-direction=push] [data-stx-screen-leave]{animation-name:stx-nav-out;z-index:1}';
3428
+ css+='html[data-nav-direction=pop] [data-stx-screen-enter]{animation-name:stx-nav-back-in;z-index:1}html[data-nav-direction=pop] [data-stx-screen-leave]{animation-name:stx-nav-back-out;z-index:3;box-shadow:0 0 24px rgb(0 0 0 / .12)}';
3429
+ css+='[data-stx-screen-dim]{position:fixed;top:0;bottom:0;z-index:2;background:rgb(0 0 0 / .1);pointer-events:none;animation:stx-nav-dim var(--stx-nav-duration) var(--stx-nav-ease) both}html[data-nav-direction=pop] [data-stx-screen-dim]{animation-direction:reverse}[data-stx-screen-dim][data-stx-drag]{animation:none}';
3430
+ css+='@keyframes stx-nav-in{from{transform:translateX(100%)}to{transform:none}}@keyframes stx-nav-out{from{transform:none}to{transform:translateX(-30%)}}@keyframes stx-nav-back-in{from{transform:translateX(-30%)}to{transform:none}}@keyframes stx-nav-back-out{from{transform:none}to{transform:translateX(100%)}}@keyframes stx-nav-dim{from{opacity:0}to{opacity:1}}@keyframes stx-nav-fade-in{from{opacity:0}}@keyframes stx-nav-fade-out{to{opacity:0}}';
3431
+ css+='@media (prefers-reduced-motion: reduce){html[data-nav-direction] [data-stx-screen-enter]{animation-name:stx-nav-fade-in;animation-duration:200ms;box-shadow:none}html[data-nav-direction] [data-stx-screen-leave]{animation-name:stx-nav-fade-out;animation-duration:200ms;box-shadow:none}[data-stx-screen-dim]{display:none}}';
3432
+ // The screen a failed load leaves behind (showNavError).
3433
+ css+='.stx-retry{display:flex;flex-direction:column;align-items:center;gap:.5rem;padding:4rem 1.5rem;text-align:center}.stx-retry-title{margin:0;font-weight:600;font-size:1.0625rem}.stx-retry-text{margin:0;opacity:.7;max-width:20rem}.stx-retry-button{margin-top:.75rem;padding:.5rem 1.25rem;border:0;border-radius:999px;background:var(--native-accent,#2563eb);color:#fff;font:inherit;font-weight:600}';
2470
3434
  s.textContent=css;
2471
3435
  dhead().appendChild(s);
2472
3436
  }
@@ -2486,12 +3450,6 @@ else {
2486
3450
  }
2487
3451
  }
2488
3452
 
2489
- function injectViewTransitionCSS(){
2490
- if(document.getElementById('stx-view-transitions'))return;
2491
- var s=ce('style');s.id='stx-view-transitions';
2492
- 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}';
2493
- (document.head||document.documentElement).appendChild(s);
2494
- }
2495
3453
 
2496
3454
  // \u2500\u2500 Public API \u2500\u2500
2497
3455
  var router={
@@ -2526,6 +3484,12 @@ else {
2526
3484
  evictCache(cacheKey(url||(location.pathname+location.search)));
2527
3485
  },
2528
3486
  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];cacheOrder.length=0},
3487
+ // Switch to the tab whose link points at href, as a tap on it would:
3488
+ // its retained screens and its own back stack (selectTab).
3489
+ selectTab:selectTab,
3490
+ back:function(){return history.back()},
3491
+ // The screens kept alive, for a page or a test that wants to look.
3492
+ screens:function(){var out=[];eachEntry(function(e,id){out.push({url:e.url,tab:id,depth:e.depth,live:!!e.el,active:e===active})});return out},
2529
3493
  cache:cache,
2530
3494
  swap:swap,
2531
3495
  updateNav:updateNav
@@ -2539,13 +3503,16 @@ else {
2539
3503
  // \u2500\u2500 Initialize \u2500\u2500
2540
3504
  function init(){
2541
3505
  injectStyles();
2542
- injectViewTransitionCSS();
2543
3506
  refreshCurrentLinks();
3507
+ // The first screen, from the start, so the page never changes shape on
3508
+ // its first navigation.
3509
+ if(screensOn()){var host=getContainer();if(host)adoptInitial(host)}
2544
3510
  restoreKeptPages();
2545
3511
  prefetchEager();
3512
+ observeLinks();
2546
3513
  }
2547
3514
 
2548
3515
  if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',init);else init();
2549
3516
  })();
2550
- `}function q$(){if(w)return w;return w=C$(k$(H$())),w}function N$(){if(P)return P;return P=C$(H$()),P}var w,P;var R$=()=>{};var w$={};v$(w$,{setAppUrl:()=>I$,runMiddleware:()=>A$,route:()=>J$,resolveLayoutChain:()=>R,resetRoutes:()=>K$,registerMiddleware:()=>v,patternToRegex:()=>j,navigateTo:()=>Y$,matchRoute:()=>o,loadMiddlewareFromDirectory:()=>_$,isNonPageRoutePattern:()=>A,isNonPageRoutePath:()=>y,hasMiddleware:()=>Q$,getRouterScriptDev:()=>N$,getRouterScript:()=>q$,getMiddlewareNames:()=>M$,getMiddleware:()=>p,generateRouteTypes:()=>H,generateRouteManifest:()=>q,formatRoutes:()=>$$,findErrorPage:()=>e,filePathToPattern:()=>N,extractLayoutMetadata:()=>j$,deriveLayoutGroup:()=>n,defineRoutes:()=>B$,defineRoute:()=>O$,defineMiddleware:()=>G$,createStorageManager:()=>u,createServerCookieManager:()=>c,createRouter:()=>a,createRouteLocation:()=>z$,createMiddlewareContext:()=>F$,createClientCookieManager:()=>l,clearMiddleware:()=>W$,bracketPathToRegex:()=>r,abortNavigation:()=>Z$,Router:()=>b,NON_PAGE_DIRS:()=>F});var P$=G(()=>{U$();g();L$();E$();m();T$();f();C();R$()});
2551
- export{F as bw,y as cw,A as dw,H as ew,q as fw,N as gw,j as hw,o as iw,r as jw,R as kw,b as lw,a as mw,e as nw,$$ as ow,I$ as pw,O$ as qw,B$ as rw,J$ as sw,K$ as tw,Y$ as uw,Z$ as vw,G$ as ww,c as xw,l as yw,u as zw,v as Aw,p as Bw,Q$ as Cw,W$ as Dw,M$ as Ew,_$ as Fw,z$ as Gw,F$ as Hw,A$ as Iw,n as Jw,j$ as Kw,T$ as Lw,q$ as Mw,N$ as Nw,w$ as Ow,P$ as Pw};
3517
+ `}function q$(){if(w)return w;return w=C$(k$(H$()),!0),w}function N$(){if(P)return P;return P=C$(H$()),P}var w,P;var R$=()=>{};var w$={};v$(w$,{setAppUrl:()=>I$,runMiddleware:()=>A$,route:()=>J$,resolveLayoutChain:()=>R,resetRoutes:()=>K$,registerMiddleware:()=>v,patternToRegex:()=>j,navigateTo:()=>Y$,matchRoute:()=>o,loadMiddlewareFromDirectory:()=>_$,isNonPageRoutePattern:()=>A,isNonPageRoutePath:()=>y,hasMiddleware:()=>Q$,getRouterScriptDev:()=>N$,getRouterScript:()=>q$,getMiddlewareNames:()=>M$,getMiddleware:()=>p,generateRouteTypes:()=>H,generateRouteManifest:()=>q,formatRoutes:()=>$$,findErrorPage:()=>e,filePathToPattern:()=>N,extractLayoutMetadata:()=>j$,deriveLayoutGroup:()=>n,defineRoutes:()=>B$,defineRoute:()=>O$,defineMiddleware:()=>G$,createStorageManager:()=>l,createServerCookieManager:()=>c,createRouter:()=>a,createRouteLocation:()=>z$,createMiddlewareContext:()=>F$,createClientCookieManager:()=>u,clearMiddleware:()=>W$,bracketPathToRegex:()=>r,abortNavigation:()=>Z$,Router:()=>b,NON_PAGE_DIRS:()=>F});var P$=G(()=>{U$();g();L$();E$();m();T$();f();C();R$()});
3518
+ export{F as iw,y as jw,A as kw,H as lw,q as mw,N as nw,j as ow,o as pw,r as qw,R as rw,b as sw,a as tw,e as uw,$$ as vw,I$ as ww,O$ as xw,B$ as yw,J$ as zw,K$ as Aw,Y$ as Bw,Z$ as Cw,G$ as Dw,c as Ew,u as Fw,l as Gw,v as Hw,p as Iw,Q$ as Jw,W$ as Kw,M$ as Lw,_$ as Mw,z$ as Nw,F$ as Ow,A$ as Pw,n as Qw,j$ as Rw,T$ as Sw,q$ as Tw,N$ as Uw,w$ as Vw,P$ as Ww};