gyosjs 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * GyosJS v0.3.1
2
+ * GyosJS v0.4.0
3
3
  * (c) 2026
4
4
  * @license MIT
5
5
  */
@@ -2196,59 +2196,59 @@ function applyTransitionStyles() {
2196
2196
  return;
2197
2197
  const style = document.createElement('style');
2198
2198
  style.id = styleId;
2199
- style.textContent = `
2200
- /* Opacity utilities */
2199
+ style.textContent = `
2200
+ /* Opacity utilities */
2201
2201
  .gyos-t-opacity-0 { opacity: 0; }
2202
2202
  .gyos-t-opacity-100 { opacity: 1; }
2203
-
2204
- /* Transform - Translate Y */
2203
+
2204
+ /* Transform - Translate Y */
2205
2205
  .gyos-t-translate-y-0 { transform: translateY(0); }
2206
2206
  .gyos-t-translate-y--100 { transform: translateY(-100%); }
2207
2207
  .gyos-t-translate-y-100 { transform: translateY(100%); }
2208
-
2209
- /* Transform - Translate X */
2208
+
2209
+ /* Transform - Translate X */
2210
2210
  .gyos-t-translate-x-0 { transform: translateX(0); }
2211
2211
  .gyos-t-translate-x--100 { transform: translateX(-100%); }
2212
2212
  .gyos-t-translate-x-100 { transform: translateX(100%); }
2213
-
2214
- /* Transform - Scale */
2213
+
2214
+ /* Transform - Scale */
2215
2215
  .gyos-t-scale-0 { transform: scale(0); }
2216
2216
  .gyos-t-scale-50 { transform: scale(0.5); }
2217
2217
  .gyos-t-scale-100 { transform: scale(1); }
2218
-
2219
- /* Animation Keyframes */
2220
- @keyframes gyos-fade-in {
2221
- from { opacity: 0; }
2222
- to { opacity: 1; }
2223
- }
2224
-
2225
- @keyframes gyos-fade-out {
2226
- from { opacity: 1; }
2227
- to { opacity: 0; }
2228
- }
2229
-
2230
- @keyframes gyos-slide-down {
2231
- from { transform: translateY(-100%); opacity: 0; }
2232
- to { transform: translateY(0); opacity: 1; }
2233
- }
2234
-
2235
- @keyframes gyos-slide-up {
2236
- from { transform: translateY(100%); opacity: 0; }
2237
- to { transform: translateY(0); opacity: 1; }
2238
- }
2239
-
2240
- @keyframes gyos-scale-in {
2241
- from { transform: scale(0); opacity: 0; }
2242
- to { transform: scale(1); opacity: 1; }
2243
- }
2244
-
2245
- @keyframes gyos-scale-out {
2246
- from { transform: scale(1); opacity: 1; }
2247
- to { transform: scale(0); opacity: 0; }
2248
- }
2249
-
2250
- [g-cloak] {
2251
- display: none !important;
2218
+
2219
+ /* Animation Keyframes */
2220
+ @keyframes gyos-fade-in {
2221
+ from { opacity: 0; }
2222
+ to { opacity: 1; }
2223
+ }
2224
+
2225
+ @keyframes gyos-fade-out {
2226
+ from { opacity: 1; }
2227
+ to { opacity: 0; }
2228
+ }
2229
+
2230
+ @keyframes gyos-slide-down {
2231
+ from { transform: translateY(-100%); opacity: 0; }
2232
+ to { transform: translateY(0); opacity: 1; }
2233
+ }
2234
+
2235
+ @keyframes gyos-slide-up {
2236
+ from { transform: translateY(100%); opacity: 0; }
2237
+ to { transform: translateY(0); opacity: 1; }
2238
+ }
2239
+
2240
+ @keyframes gyos-scale-in {
2241
+ from { transform: scale(0); opacity: 0; }
2242
+ to { transform: scale(1); opacity: 1; }
2243
+ }
2244
+
2245
+ @keyframes gyos-scale-out {
2246
+ from { transform: scale(1); opacity: 1; }
2247
+ to { transform: scale(0); opacity: 0; }
2248
+ }
2249
+
2250
+ [g-cloak] {
2251
+ display: none !important;
2252
2252
  }`;
2253
2253
  document.head.appendChild(style);
2254
2254
  }
@@ -5183,6 +5183,10 @@ function processStructuralDirectives(elements, scope) {
5183
5183
  const structuralElements = [];
5184
5184
  const root = elements[0];
5185
5185
  elements.forEach(el => {
5186
+ // Await branches are detached and parsed only after their alias scope exists.
5187
+ // Do not evaluate nested structural expressions during the parent scan.
5188
+ if (isAwaitBranchDescendant(el))
5189
+ return;
5186
5190
  const hasIf = el.hasAttribute('*if');
5187
5191
  const hasFor = el.hasAttribute('*for');
5188
5192
  const hasSwitch = el.hasAttribute('*switch');
@@ -5227,6 +5231,20 @@ function processStructuralDirectives(elements, scope) {
5227
5231
  }
5228
5232
  });
5229
5233
  }
5234
+ function isAwaitBranchDescendant(element) {
5235
+ let child = element;
5236
+ let parent = element.parentElement;
5237
+ while (parent && parent !== document.body) {
5238
+ if (parent.hasAttribute('*await') && (child.hasAttribute('*pending') ||
5239
+ child.hasAttribute('*then') ||
5240
+ child.hasAttribute('*catch'))) {
5241
+ return true;
5242
+ }
5243
+ child = parent;
5244
+ parent = parent.parentElement;
5245
+ }
5246
+ return false;
5247
+ }
5230
5248
  const elementBelongsToAnotherScope = (el, scope) => {
5231
5249
  const owner = getScopeFromElement(el);
5232
5250
  return Boolean(owner && owner !== scope);
@@ -6587,33 +6605,44 @@ class ProgressBar {
6587
6605
  getCurrentProgress() {
6588
6606
  return this.currentProgress;
6589
6607
  }
6608
+ reconnect() {
6609
+ if (!this.element || !this.progressBarEnabled || !document.body)
6610
+ return;
6611
+ // Snapshots may contain a clone of the runtime bar. Keep this instance.
6612
+ document.querySelectorAll('#gyos-progress-bar').forEach(node => {
6613
+ if (node !== this.element)
6614
+ node.remove();
6615
+ });
6616
+ if (!this.element.isConnected)
6617
+ document.body.appendChild(this.element);
6618
+ }
6590
6619
  createBar() {
6591
6620
  if (typeof document === 'undefined')
6592
6621
  return;
6593
6622
  // Create progress bar element
6594
6623
  this.element = document.createElement('div');
6595
6624
  this.element.id = 'gyos-progress-bar';
6596
- this.element.style.cssText = `
6597
- position: fixed;
6598
- top: 0;
6599
- left: 0;
6600
- width: 0%;
6601
- height: 6px;
6602
- background: var(--gyos-progress-color, linear-gradient(90deg, #aab9ff, #77889f));
6603
- z-index: 999999;
6604
- transition: width 0.3s linear, opacity 0.3s linear;
6605
- opacity: 0;
6606
- pointer-events: none;
6607
- box-shadow: 0 0 10px rgba(102, 126, 234, 0.5);
6625
+ this.element.style.cssText = `
6626
+ position: fixed;
6627
+ top: 0;
6628
+ left: 0;
6629
+ width: 0%;
6630
+ height: 6px;
6631
+ background: var(--gyos-progress-color, linear-gradient(90deg, #aab9ff, #77889f));
6632
+ z-index: 999999;
6633
+ transition: width 0.3s linear, opacity 0.3s linear;
6634
+ opacity: 0;
6635
+ pointer-events: none;
6636
+ box-shadow: 0 0 10px rgba(102, 126, 234, 0.5);
6608
6637
  `;
6609
6638
  // Insert into DOM when ready
6610
6639
  if (document.readyState === 'loading') {
6611
6640
  document.addEventListener('DOMContentLoaded', () => {
6612
- document.body.insertAdjacentElement('beforeend', this.element);
6613
- });
6641
+ this.reconnect();
6642
+ }, { once: true });
6614
6643
  }
6615
6644
  else {
6616
- document.body.insertAdjacentElement('beforeend', this.element);
6645
+ this.reconnect();
6617
6646
  }
6618
6647
  }
6619
6648
  start() {
@@ -6637,6 +6666,7 @@ class ProgressBar {
6637
6666
  setProgress(percent) {
6638
6667
  if (!this.element || !this.progressBarEnabled)
6639
6668
  return;
6669
+ this.reconnect();
6640
6670
  // Clamp between 0-100
6641
6671
  percent = Math.min(100, Math.max(0, percent));
6642
6672
  this.currentProgress = percent;
@@ -6685,41 +6715,41 @@ class ProgressBar {
6685
6715
  function createTargetSpinner() {
6686
6716
  const spinner = document.createElement('div');
6687
6717
  spinner.className = 'gyos-target-spinner';
6688
- spinner.innerHTML = `
6689
- <div class="gyos-spinner-content">
6690
- <svg class="gyos-spinner-icon" viewBox="0 0 50 50">
6691
- <circle cx="25" cy="25" r="20" fill="none" stroke="currentColor" stroke-width="4" stroke-dasharray="31.4 31.4" />
6692
- </svg>
6693
- </div>
6718
+ spinner.innerHTML = `
6719
+ <div class="gyos-spinner-content">
6720
+ <svg class="gyos-spinner-icon" viewBox="0 0 50 50">
6721
+ <circle cx="25" cy="25" r="20" fill="none" stroke="currentColor" stroke-width="4" stroke-dasharray="31.4 31.4" />
6722
+ </svg>
6723
+ </div>
6694
6724
  `;
6695
6725
  // Inject styles if not already present
6696
6726
  if (expressionRuntimeMode() === 'standard' && !document.getElementById('gyos-target-spinner-styles')) {
6697
6727
  const style = document.createElement('style');
6698
6728
  style.id = 'gyos-target-spinner-styles';
6699
- style.textContent = `
6700
- .gyos-target-spinner {
6701
- display: flex;
6702
- align-items: center;
6703
- justify-content: center;
6704
- padding: 20px;
6705
- min-height: 60px;
6706
- }
6707
- .gyos-spinner-content {
6708
- display: flex;
6709
- align-items: center;
6710
- gap: 10px;
6711
- color: var(--gyos-spinner-color, #667eea);
6712
- font-size: 14px;
6713
- }
6714
- .gyos-spinner-icon {
6715
- width: 24px;
6716
- height: 24px;
6717
- animation: gyos-spin 1s linear infinite;
6718
- }
6719
- @keyframes gyos-spin {
6720
- 0% { transform: rotate(0deg); }
6721
- 100% { transform: rotate(360deg); }
6722
- }
6729
+ style.textContent = `
6730
+ .gyos-target-spinner {
6731
+ display: flex;
6732
+ align-items: center;
6733
+ justify-content: center;
6734
+ padding: 20px;
6735
+ min-height: 60px;
6736
+ }
6737
+ .gyos-spinner-content {
6738
+ display: flex;
6739
+ align-items: center;
6740
+ gap: 10px;
6741
+ color: var(--gyos-spinner-color, #667eea);
6742
+ font-size: 14px;
6743
+ }
6744
+ .gyos-spinner-icon {
6745
+ width: 24px;
6746
+ height: 24px;
6747
+ animation: gyos-spin 1s linear infinite;
6748
+ }
6749
+ @keyframes gyos-spin {
6750
+ 0% { transform: rotate(0deg); }
6751
+ 100% { transform: rotate(360deg); }
6752
+ }
6723
6753
  `;
6724
6754
  document.head.appendChild(style);
6725
6755
  }
@@ -7079,8 +7109,8 @@ async function performSwap(target, src, mode, options = {}) {
7079
7109
  }
7080
7110
  result = target;
7081
7111
  }
7082
- await options.beforeScripts?.();
7083
7112
  options.onCommitted?.(result, normalized === 'append' || normalized === 'prepend' ? incomingChildren : [result]);
7113
+ await options.beforeScripts?.();
7084
7114
  // Additive swaps must not re-run scripts that already existed in the target.
7085
7115
  if (normalized === 'append' || normalized === 'prepend') {
7086
7116
  await executeScriptsInNodes(incomingChildren, options.signal);
@@ -7320,6 +7350,21 @@ function handleScroll(url, trigger, savedScroll) {
7320
7350
  window.scrollTo({ top: 0, behavior: 'smooth' });
7321
7351
  }
7322
7352
 
7353
+ // A retained relative URL still identifies the resource loaded on its original
7354
+ // page, even after pushState changes document.baseURI.
7355
+ const resourceUrls = new WeakMap();
7356
+ function rememberResourceUrls(root, baseUrl) {
7357
+ root.querySelectorAll('script[src], link[href]').forEach(node => {
7358
+ const attribute = node.tagName === 'SCRIPT' ? 'src' : 'href';
7359
+ const source = node.getAttribute(attribute);
7360
+ if (resourceUrls.get(node)?.source === source)
7361
+ return;
7362
+ try {
7363
+ resourceUrls.set(node, { source, url: new URL(source, baseUrl).href });
7364
+ }
7365
+ catch { /* Invalid resource URLs retain their literal identity. */ }
7366
+ });
7367
+ }
7323
7368
  function isNonceMeta(el) {
7324
7369
  return el.tagName === 'META' && el.getAttribute('name')?.toLowerCase() === 'csp-nonce';
7325
7370
  }
@@ -7337,7 +7382,20 @@ function serializeAttributes(el, context) {
7337
7382
  return;
7338
7383
  if (context.csp && isNonceMeta(el) && attr.name.toLowerCase() === 'content')
7339
7384
  return;
7340
- attributes.set(attr.name, attr.value);
7385
+ let value = attr.value;
7386
+ if ((el.tagName === 'SCRIPT' && attr.name === 'src') || (el.tagName === 'LINK' && attr.name === 'href')) {
7387
+ const cached = resourceUrls.get(el);
7388
+ if (cached?.source === value)
7389
+ value = cached.url;
7390
+ else {
7391
+ try {
7392
+ value = new URL(value, context.baseUrl || el.baseURI).href;
7393
+ resourceUrls.set(el, { source: attr.value, url: value });
7394
+ }
7395
+ catch { /* Keep invalid URLs distinct. */ }
7396
+ }
7397
+ }
7398
+ attributes.set(attr.name, value);
7341
7399
  });
7342
7400
  if (context.csp && usesCspNonce(el) && context.activeNonce) {
7343
7401
  attributes.set('nonce', context.activeNonce);
@@ -7404,19 +7462,21 @@ function warnSkippedNode(node) {
7404
7462
  console.warn('[GyosJS CSP] Skipped an inline MPA script because no active document nonce is configured.');
7405
7463
  }
7406
7464
  }
7407
- async function diffNodes(currentNodes, nextNodes, container = document.head, signal) {
7465
+ async function diffNodes(currentNodes, nextNodes, container = document.head, signal, currentBaseUrl = document.baseURI) {
7408
7466
  const csp = expressionRuntimeMode() === 'csp';
7409
7467
  const context = {
7410
7468
  csp,
7411
7469
  activeNonce: csp ? resolveCspNonce() : undefined
7412
7470
  };
7413
- const current = keyedNodes(currentNodes, context);
7471
+ const current = keyedNodes(currentNodes, { ...context, baseUrl: currentBaseUrl });
7414
7472
  const next = keyedNodes(nextNodes, context);
7473
+ const persistentKey = (node) => container === document.head ? node.getAttribute('g-head-persist') : null;
7474
+ const persistent = new Set(currentNodes.map(persistentKey).filter(Boolean));
7415
7475
  const currentKeys = new Set(current.map(item => item.key));
7416
7476
  const nextKeys = new Set(next.map(item => item.key));
7417
7477
  // Remove nodes that are not in the new head
7418
7478
  current.forEach(({ key, node }) => {
7419
- if (!nextKeys.has(key)) {
7479
+ if (!nextKeys.has(key) && !persistentKey(node)) {
7420
7480
  node.remove();
7421
7481
  }
7422
7482
  });
@@ -7424,6 +7484,8 @@ async function diffNodes(currentNodes, nextNodes, container = document.head, sig
7424
7484
  for (const { key, node } of next) {
7425
7485
  if (signal?.aborted)
7426
7486
  return;
7487
+ if (persistent.has(persistentKey(node)))
7488
+ continue;
7427
7489
  if (!currentKeys.has(key)) {
7428
7490
  if (!canInsertNode(node, context)) {
7429
7491
  warnSkippedNode(node);
@@ -7626,6 +7688,7 @@ function prepareNavigationHtml(html) {
7626
7688
  * MPA boost navigation inspired by Turbo Drive.
7627
7689
  * Implements attribute-driven routing, snapshot caching, and persistent islands.
7628
7690
  */
7691
+ const submittingForms = new WeakSet();
7629
7692
  const snapshots = new Map();
7630
7693
  const preloadCache = new Map();
7631
7694
  const preloadControllers = new Map();
@@ -7642,12 +7705,30 @@ let activeNavigation = null;
7642
7705
  let progressBar = null;
7643
7706
  const beforeNavigate = [];
7644
7707
  const afterNavigate = [];
7708
+ const beforeSwap = [];
7709
+ const navigationEnd = [];
7710
+ function registerNavigationHook(hooks, callback) {
7711
+ // A wrapper gives each registration its own unsubscribe identity.
7712
+ const entry = (url, context) => callback(url, context);
7713
+ hooks.push(entry);
7714
+ return () => {
7715
+ const index = hooks.indexOf(entry);
7716
+ if (index !== -1)
7717
+ hooks.splice(index, 1);
7718
+ };
7719
+ }
7645
7720
  // Expose hooks to register before/after navigation callbacks
7646
7721
  function onBeforeNavigate(callback) {
7647
- beforeNavigate.push(callback);
7722
+ return registerNavigationHook(beforeNavigate, callback);
7648
7723
  }
7649
7724
  function onAfterNavigate(callback) {
7650
- afterNavigate.push(callback);
7725
+ return registerNavigationHook(afterNavigate, callback);
7726
+ }
7727
+ function onBeforeSwap(callback) {
7728
+ return registerNavigationHook(beforeSwap, callback);
7729
+ }
7730
+ function onNavigationEnd(callback) {
7731
+ return registerNavigationHook(navigationEnd, (_url, context) => callback(context));
7651
7732
  }
7652
7733
  function startRouter(options) {
7653
7734
  // If not has g-boost attribute, do not start router
@@ -7671,6 +7752,7 @@ function startRouter(options) {
7671
7752
  }
7672
7753
  // Cache scripts from initial page to prevent re-execution on first navigation back
7673
7754
  cacheInitialPageScripts();
7755
+ rememberResourceUrls(document, document.baseURI);
7674
7756
  routerStarted = true;
7675
7757
  log('[GyosRouter] started');
7676
7758
  }
@@ -7727,9 +7809,13 @@ function resolveTarget(trigger, targetSelector, targetOutletIndex) {
7727
7809
  const outlet = findGlobalOutlet();
7728
7810
  return outlet instanceof HTMLElement ? outlet : null;
7729
7811
  }
7812
+ function isFullDocument(html) {
7813
+ return /^\s*(?:<!--[^]*?-->\s*)*(?:<!doctype\s+html\b|<html(?:\s|>))/i.test(html);
7814
+ }
7730
7815
  function saveSnapshot(url, html) {
7731
7816
  // create HTMLElement by html string to remove scripts and get clean snapshot
7732
7817
  const doc = parseNavigationDocument(html);
7818
+ doc.querySelectorAll('#gyos-progress-bar').forEach(node => node.remove());
7733
7819
  // Ignore hash for snapshot keys
7734
7820
  if (url.includes('#'))
7735
7821
  url = url.split('#')[0];
@@ -7738,7 +7824,7 @@ function saveSnapshot(url, html) {
7738
7824
  if (s.hasAttribute('g-script-once'))
7739
7825
  s.textContent = '';
7740
7826
  });
7741
- snapshots.set(url, { html: doc.documentElement.outerHTML });
7827
+ snapshots.set(url, { html: doc.documentElement.outerHTML, fullDocument: isFullDocument(html) });
7742
7828
  log('[GyosRouter] snapshot saved for', url);
7743
7829
  }
7744
7830
  function getOutletIndex(root, target) {
@@ -7850,10 +7936,10 @@ function consumeViewTransitionRejection(promise) {
7850
7936
  // update callback remains the navigation source of truth and is awaited below.
7851
7937
  void promise?.catch(() => undefined);
7852
7938
  }
7853
- function runNavigationHooks(callbacks, url) {
7854
- callbacks.forEach(callback => {
7939
+ function runNavigationHooks(callbacks, url, context) {
7940
+ [...callbacks].forEach(callback => {
7855
7941
  try {
7856
- callback(url);
7942
+ callback(url, { ...context });
7857
7943
  }
7858
7944
  catch (error) {
7859
7945
  console.error('[GyosRouter] navigation hook error', error);
@@ -7891,7 +7977,13 @@ function buildRequest(opts) {
7891
7977
  url = mergeFormDataIntoUrl(url, opts.formData);
7892
7978
  }
7893
7979
  else {
7894
- init.body = opts.formData;
7980
+ if (opts.formEncoding === 'application/x-www-form-urlencoded') {
7981
+ const encoded = new URLSearchParams();
7982
+ opts.formData.forEach((value, name) => encoded.append(name, typeof value === 'string' ? value : value.name));
7983
+ init.body = encoded;
7984
+ }
7985
+ else
7986
+ init.body = opts.formData;
7895
7987
  }
7896
7988
  }
7897
7989
  else if (opts.jsonData) {
@@ -7934,25 +8026,26 @@ function preload(url) {
7934
8026
  preloadControllers.delete(cacheKey);
7935
8027
  });
7936
8028
  }
7937
- async function updateHead(fromDoc, signal) {
8029
+ async function updateHead(fromDoc, signal, currentBaseUrl) {
7938
8030
  const allowedSelector = 'meta, link, style:not(#gyos-transitions), script';
7939
8031
  const currentNodes = Array.from(document.head.querySelectorAll(allowedSelector));
7940
8032
  const nextNodes = Array.from(fromDoc.head.querySelectorAll(allowedSelector));
7941
- await diffNodes(currentNodes, nextNodes, document.head, signal);
8033
+ await diffNodes(currentNodes, nextNodes, document.head, signal, currentBaseUrl);
7942
8034
  }
7943
- async function scriptNotInOutletTarget(fromDoc, target, source, signal) {
8035
+ async function scriptNotInOutletTarget(fromDoc, target, source, signal, currentBaseUrl) {
7944
8036
  // scripts in current document and it not in target outlet
7945
8037
  const currentScripts = Array.from(document.scripts).filter(s => !target.contains(s) && !document.head.contains(s));
7946
8038
  // scripts in fromDoc and it not in source outlet
7947
8039
  const incomingScripts = Array.from(fromDoc.scripts).filter(s => !source.contains(s) && !fromDoc.head.contains(s));
7948
8040
  // Diff and update scripts not in outlet/target
7949
- await diffNodes(currentScripts, incomingScripts, document.body, signal);
8041
+ await diffNodes(currentScripts, incomingScripts, document.body, signal, currentBaseUrl);
7950
8042
  }
7951
8043
  function resolveIncomingScriptUrls(root, baseUrl) {
7952
- root.querySelectorAll('script[src]').forEach(script => {
7953
- const source = script.getAttribute('src');
8044
+ root.querySelectorAll('script[src], link[href]').forEach(node => {
8045
+ const attribute = node.tagName === 'SCRIPT' ? 'src' : 'href';
8046
+ const source = node.getAttribute(attribute);
7954
8047
  if (source)
7955
- script.src = new URL(source, baseUrl).href;
8048
+ node.setAttribute(attribute, new URL(source, baseUrl).href);
7956
8049
  });
7957
8050
  }
7958
8051
  function isNavigableHtmlResponse(response) {
@@ -8006,6 +8099,22 @@ async function navigate(opts) {
8006
8099
  resolveDone
8007
8100
  };
8008
8101
  activeNavigation = transaction;
8102
+ const currentBaseUrl = document.baseURI;
8103
+ rememberResourceUrls(document, currentBaseUrl);
8104
+ const context = {
8105
+ from: currentUrl, url: opts.url, method: opts.method.toUpperCase(),
8106
+ trigger: opts.trigger || null, target: null, form: opts.form || null,
8107
+ popstate: opts.popstate === true, signal: transaction.controller.signal,
8108
+ status: null, committed: false, fallback: false, outcome: null
8109
+ };
8110
+ const formEvent = opts.form
8111
+ ? { form: opts.form, url: opts.url, status: null, outcome: null, committed: false, fallback: false }
8112
+ : null;
8113
+ const fallback = (url, requestSent) => {
8114
+ context.fallback = context.method === 'GET' || (!requestSent && !!opts.form);
8115
+ context.outcome ?? (context.outcome = context.fallback ? 'fallback' : 'invalid-response');
8116
+ fallbackFromBoost(opts, url, requestSent);
8117
+ };
8009
8118
  const hasTargetSpinner = opts.trigger?.hasAttribute('g-router-spin');
8010
8119
  const setRand = () => {
8011
8120
  if (isActiveNavigation(transaction) && progressBar?.getCurrentProgress() < 70) {
@@ -8013,7 +8122,10 @@ async function navigate(opts) {
8013
8122
  }
8014
8123
  };
8015
8124
  try {
8016
- runNavigationHooks(beforeNavigate, opts.url);
8125
+ if (formEvent)
8126
+ document.dispatchEvent(new CustomEvent('gyos:form-start', { detail: { ...formEvent } }));
8127
+ runNavigationHooks(beforeNavigate, opts.url, context);
8128
+ assertActiveNavigation(transaction);
8017
8129
  progressBar?.start();
8018
8130
  // popstate already points history at the destination entry. Keep the visible
8019
8131
  // page's position under currentUrl without overwriting that destination state.
@@ -8022,9 +8134,10 @@ async function navigate(opts) {
8022
8134
  saveScrollPosition();
8023
8135
  // Pick target element to swap
8024
8136
  let target = resolveTarget(opts.trigger, opts.targetSelector, opts.targetOutletIndex);
8137
+ context.target = target;
8025
8138
  if (!target) {
8026
8139
  if (isActiveNavigation(transaction))
8027
- fallbackFromBoost(opts, opts.url, false);
8140
+ fallback(opts.url, false);
8028
8141
  return;
8029
8142
  }
8030
8143
  const swapMode = (opts.swapMode || opts.trigger?.getAttribute('g-swap') || 'inner').toLowerCase();
@@ -8049,6 +8162,7 @@ async function navigate(opts) {
8049
8162
  if (hasTargetSpinner)
8050
8163
  transaction.spinner = showTargetSpinner(target, swapMode);
8051
8164
  const { finalUrl, init } = buildRequest(opts);
8165
+ context.url = finalUrl;
8052
8166
  // Add abort signal to request
8053
8167
  init.signal = transaction.controller.signal;
8054
8168
  let html;
@@ -8076,7 +8190,8 @@ async function navigate(opts) {
8076
8190
  if (error.name === 'AbortError')
8077
8191
  throw error;
8078
8192
  assertActiveNavigation(transaction);
8079
- window.location.href = finalUrl;
8193
+ context.outcome = 'network-error';
8194
+ fallback(finalUrl, true);
8080
8195
  return;
8081
8196
  }
8082
8197
  preloadCache.delete(preloadKey); // consume cache
@@ -8101,28 +8216,46 @@ async function navigate(opts) {
8101
8216
  log('[GyosRouter] Navigation cancelled');
8102
8217
  return;
8103
8218
  }
8219
+ context.outcome = 'network-error';
8104
8220
  if (isActiveNavigation(transaction))
8105
- fallbackFromBoost(opts, finalUrl, true);
8221
+ fallback(finalUrl, true);
8106
8222
  return;
8107
8223
  }
8108
8224
  }
8109
8225
  assertActiveNavigation(transaction);
8110
- // If response not ok, fallback to full navigation
8111
- if (!response || !response.ok || !isNavigableHtmlResponse(response)) {
8226
+ context.status = response?.status ?? null;
8227
+ context.url = response?.url || finalUrl;
8228
+ const acceptedErrors = (opts.trigger?.getAttribute('g-boost-errors') || '').split(/[\s,]+/);
8229
+ const renderHttpError = !!response && response.status >= 400 && response.status <= 599
8230
+ && acceptedErrors.includes(String(response.status));
8231
+ if (response && !response.ok)
8232
+ context.outcome = 'http-error';
8233
+ if (!response || (!response.ok && !renderHttpError) || !isNavigableHtmlResponse(response)) {
8234
+ context.outcome ?? (context.outcome = 'invalid-response');
8112
8235
  if (isActiveNavigation(transaction))
8113
- fallbackFromBoost(opts, finalUrl, true);
8236
+ fallback(finalUrl, true);
8114
8237
  return;
8115
8238
  }
8116
8239
  html = await response.text();
8117
8240
  assertActiveNavigation(transaction);
8118
- if (!opts.popstate && target.hasAttribute('g-snapshot')) {
8119
- saveSnapshot(canonicalUrl(response.url || finalUrl), html);
8120
- }
8121
8241
  }
8122
8242
  // Parse HTML
8123
8243
  const doc = html
8124
8244
  ? parseNavigationDocument(html)
8125
8245
  : document.implementation.createHTMLDocument();
8246
+ // Detached parsing cannot tell whether the live CSP permits an incoming base.
8247
+ // Let native navigation enforce base-uri instead of authorizing its URLs ourselves.
8248
+ if (doc.querySelector('base[href]') || opts.historyFragment?.querySelector('base[href]')) {
8249
+ context.outcome = 'invalid-response';
8250
+ fallback(response?.url || finalUrl, true);
8251
+ return;
8252
+ }
8253
+ if (response?.ok && !opts.popstate && target.hasAttribute('g-snapshot')) {
8254
+ saveSnapshot(canonicalUrl(response.url || finalUrl), html);
8255
+ }
8256
+ const syncDocumentAttributes = isFullOutletNavigation && destructiveSwap && !currentHead
8257
+ && !opts.historyFragment && (opts.popstate && snapshots.has(urlWithoutHash)
8258
+ ? snapshots.get(urlWithoutHash).fullDocument : isFullDocument(html || ''));
8126
8259
  // Pick source fragment
8127
8260
  const src = opts.historyFragment || pickSourceFragment(doc, target, targetOutletIndex);
8128
8261
  stripInertFallbackContent(src);
@@ -8134,15 +8267,18 @@ async function navigate(opts) {
8134
8267
  targetUrl += finalUrl.substring(finalUrl.indexOf('#'));
8135
8268
  }
8136
8269
  resolveIncomingScriptUrls(doc, targetUrl);
8270
+ context.url = targetUrl;
8137
8271
  if (opts.historyFragment)
8138
8272
  resolveIncomingScriptUrls(src, targetUrl);
8139
8273
  const triggerChangesState = opts.trigger?.hasAttribute('g-change-state') || false;
8140
8274
  const keepsCurrentState = opts.trigger?.hasAttribute('g-current-state') || false;
8141
8275
  const redirectedSubmission = opts.method.toUpperCase() !== 'GET' && response?.redirected === true;
8142
- const changesState = !keepsCurrentState && (opts.changeState === true || triggerChangesState || redirectedSubmission);
8276
+ const changesState = context.outcome !== 'http-error' && !keepsCurrentState && (opts.changeState === true || triggerChangesState || redirectedSubmission);
8143
8277
  const performUpdate = async () => {
8144
8278
  assertActiveNavigation(transaction);
8145
8279
  transaction.committing = true;
8280
+ runNavigationHooks(beforeSwap, targetUrl, context);
8281
+ assertActiveNavigation(transaction);
8146
8282
  // Update progress to rand 80 - 90% before swap
8147
8283
  progressBar?.setProgress(Math.random() * 10 + 80);
8148
8284
  const outgoingHistoryFragment = changesState && !opts.replace && !isFullOutletNavigation
@@ -8213,21 +8349,34 @@ async function navigate(opts) {
8213
8349
  beforeScripts: async () => {
8214
8350
  if (!isFullOutletNavigation || currentHead)
8215
8351
  return;
8352
+ if (syncDocumentAttributes) {
8353
+ for (const name of ['lang', 'dir']) {
8354
+ const value = doc.documentElement.getAttribute(name);
8355
+ if (value === null)
8356
+ document.documentElement.removeAttribute(name);
8357
+ else
8358
+ document.documentElement.setAttribute(name, value);
8359
+ }
8360
+ }
8216
8361
  const incomingTitle = doc.querySelector('title');
8217
8362
  if (incomingTitle) {
8218
8363
  document.title = incomingTitle.textContent || document.title;
8219
8364
  }
8220
- await updateHead(doc, transaction.controller.signal);
8365
+ await updateHead(doc, transaction.controller.signal, currentBaseUrl);
8221
8366
  assertActiveNavigation(transaction);
8222
8367
  },
8223
8368
  onCommitted: (committedTarget, roots) => {
8224
8369
  target = committedTarget;
8370
+ context.target = committedTarget;
8371
+ context.committed = true;
8372
+ progressBar?.reconnect();
8225
8373
  committedRoots = roots;
8226
8374
  }
8227
8375
  });
8376
+ context.committed = true;
8228
8377
  assertActiveNavigation(transaction);
8229
8378
  if (isFullOutletNavigation) {
8230
- await scriptNotInOutletTarget(doc, target, src, transaction.controller.signal);
8379
+ await scriptNotInOutletTarget(doc, target, src, transaction.controller.signal, currentBaseUrl);
8231
8380
  assertActiveNavigation(transaction);
8232
8381
  }
8233
8382
  }
@@ -8261,14 +8410,15 @@ async function navigate(opts) {
8261
8410
  await performUpdate();
8262
8411
  }
8263
8412
  assertActiveNavigation(transaction);
8264
- if (removeTriggerAfterCommit && opts.trigger instanceof HTMLElement && opts.trigger.isConnected) {
8413
+ if (removeTriggerAfterCommit && context.outcome !== 'http-error' && opts.trigger instanceof HTMLElement && opts.trigger.isConnected) {
8265
8414
  disposeEffects(opts.trigger);
8266
8415
  opts.trigger.remove();
8267
8416
  }
8268
8417
  if (hasTargetSpinner)
8269
8418
  hideTargetSpinner(transaction.spinner);
8270
8419
  transaction.spinner = null;
8271
- runNavigationHooks(afterNavigate, targetUrl);
8420
+ context.outcome ?? (context.outcome = 'success');
8421
+ runNavigationHooks(afterNavigate, targetUrl, context);
8272
8422
  log('[GyosRouter] navigated to', targetUrl);
8273
8423
  currentUrl = changesState
8274
8424
  ? canonicalUrl(targetUrl, true)
@@ -8284,11 +8434,15 @@ async function navigate(opts) {
8284
8434
  return;
8285
8435
  }
8286
8436
  if (isActiveNavigation(transaction)) {
8437
+ context.outcome ?? (context.outcome = 'error');
8287
8438
  console.error('[GyosRouter] navigation error', error);
8288
- fallbackFromBoost(opts, opts.url, true);
8439
+ fallback(opts.url, true);
8289
8440
  }
8290
8441
  }
8291
8442
  finally {
8443
+ if (transaction.controller.signal.aborted)
8444
+ context.outcome = 'aborted';
8445
+ context.outcome ?? (context.outcome = 'aborted');
8292
8446
  if (transaction.interval)
8293
8447
  clearInterval(transaction.interval);
8294
8448
  if (transaction.spinner)
@@ -8298,6 +8452,15 @@ async function navigate(opts) {
8298
8452
  progressBar?.complete();
8299
8453
  }
8300
8454
  transaction.resolveDone();
8455
+ if (formEvent)
8456
+ submittingForms.delete(formEvent.form);
8457
+ runNavigationHooks(navigationEnd, context.url, context);
8458
+ if (formEvent) {
8459
+ const { url, status, outcome, committed, fallback } = context;
8460
+ document.dispatchEvent(new CustomEvent('gyos:form-end', {
8461
+ detail: { ...formEvent, url, status, outcome, committed, fallback }
8462
+ }));
8463
+ }
8301
8464
  }
8302
8465
  }
8303
8466
  function shouldBoost(el) {
@@ -8406,16 +8569,34 @@ function onSubmit(event) {
8406
8569
  return;
8407
8570
  if (shouldDeferToFormValidation(form))
8408
8571
  return;
8409
- event.preventDefault();
8410
- const action = form.action || window.location.href;
8411
- const method = (form.method || 'GET').toUpperCase();
8412
- const url = new URL(action, window.location.href);
8413
- if (url.origin !== window.location.origin) {
8414
- window.location.href = url.toString();
8572
+ const submitter = event.submitter;
8573
+ const override = (name) => submitter?.getAttribute(`form${name}`) ?? form.getAttribute(name);
8574
+ const target = override('target') ?? document.querySelector('base[target]')?.getAttribute('target');
8575
+ const declaredMethod = (override('method') || 'GET').toUpperCase();
8576
+ const method = ['GET', 'POST', 'DIALOG'].includes(declaredMethod) ? declaredMethod : 'GET';
8577
+ const formEncoding = override('enctype')?.toLowerCase();
8578
+ if ((target && target.toLowerCase() !== '_self') || method === 'DIALOG' || formEncoding === 'text/plain')
8579
+ return;
8580
+ if (!resolveTarget(form))
8581
+ return;
8582
+ // Image submitters carry click coordinates which SubmitEvent does not expose.
8583
+ if (submitter instanceof HTMLInputElement && submitter.type === 'image')
8584
+ return;
8585
+ let url;
8586
+ try {
8587
+ url = new URL(override('action') || window.location.href, document.baseURI);
8588
+ }
8589
+ catch {
8415
8590
  return;
8416
8591
  }
8417
- const formData = new FormData(form);
8418
- navigate({ url: url.toString(), method, trigger: form, form, formData, changeState: method === 'GET' });
8592
+ if (url.origin !== window.location.origin)
8593
+ return;
8594
+ event.preventDefault();
8595
+ if (submittingForms.has(form))
8596
+ return;
8597
+ const formData = new FormData(form, submitter);
8598
+ submittingForms.add(form);
8599
+ void navigate({ url: url.toString(), method, trigger: form, form, formData, formEncoding, changeState: method === 'GET' });
8419
8600
  }
8420
8601
  function onPopState(event) {
8421
8602
  const url = window.location.href;
@@ -8520,10 +8701,12 @@ const Gyos = {
8520
8701
  startRouter,
8521
8702
  onBeforeNavigate,
8522
8703
  onAfterNavigate,
8704
+ onBeforeSwap,
8705
+ onNavigationEnd,
8523
8706
  portalCreate,
8524
8707
  portalDestroy,
8525
8708
  setCspNonce,
8526
- version: '0.3.1'
8709
+ version: '0.4.0'
8527
8710
  };
8528
8711
 
8529
8712
  const standardExpressionRuntime = {