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.
package/dist/gyos.js CHANGED
@@ -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
  */
@@ -2234,59 +2234,59 @@
2234
2234
  return;
2235
2235
  const style = document.createElement('style');
2236
2236
  style.id = styleId;
2237
- style.textContent = `
2238
- /* Opacity utilities */
2237
+ style.textContent = `
2238
+ /* Opacity utilities */
2239
2239
  .gyos-t-opacity-0 { opacity: 0; }
2240
2240
  .gyos-t-opacity-100 { opacity: 1; }
2241
-
2242
- /* Transform - Translate Y */
2241
+
2242
+ /* Transform - Translate Y */
2243
2243
  .gyos-t-translate-y-0 { transform: translateY(0); }
2244
2244
  .gyos-t-translate-y--100 { transform: translateY(-100%); }
2245
2245
  .gyos-t-translate-y-100 { transform: translateY(100%); }
2246
-
2247
- /* Transform - Translate X */
2246
+
2247
+ /* Transform - Translate X */
2248
2248
  .gyos-t-translate-x-0 { transform: translateX(0); }
2249
2249
  .gyos-t-translate-x--100 { transform: translateX(-100%); }
2250
2250
  .gyos-t-translate-x-100 { transform: translateX(100%); }
2251
-
2252
- /* Transform - Scale */
2251
+
2252
+ /* Transform - Scale */
2253
2253
  .gyos-t-scale-0 { transform: scale(0); }
2254
2254
  .gyos-t-scale-50 { transform: scale(0.5); }
2255
2255
  .gyos-t-scale-100 { transform: scale(1); }
2256
-
2257
- /* Animation Keyframes */
2258
- @keyframes gyos-fade-in {
2259
- from { opacity: 0; }
2260
- to { opacity: 1; }
2261
- }
2262
-
2263
- @keyframes gyos-fade-out {
2264
- from { opacity: 1; }
2265
- to { opacity: 0; }
2266
- }
2267
-
2268
- @keyframes gyos-slide-down {
2269
- from { transform: translateY(-100%); opacity: 0; }
2270
- to { transform: translateY(0); opacity: 1; }
2271
- }
2272
-
2273
- @keyframes gyos-slide-up {
2274
- from { transform: translateY(100%); opacity: 0; }
2275
- to { transform: translateY(0); opacity: 1; }
2276
- }
2277
-
2278
- @keyframes gyos-scale-in {
2279
- from { transform: scale(0); opacity: 0; }
2280
- to { transform: scale(1); opacity: 1; }
2281
- }
2282
-
2283
- @keyframes gyos-scale-out {
2284
- from { transform: scale(1); opacity: 1; }
2285
- to { transform: scale(0); opacity: 0; }
2286
- }
2287
-
2288
- [g-cloak] {
2289
- display: none !important;
2256
+
2257
+ /* Animation Keyframes */
2258
+ @keyframes gyos-fade-in {
2259
+ from { opacity: 0; }
2260
+ to { opacity: 1; }
2261
+ }
2262
+
2263
+ @keyframes gyos-fade-out {
2264
+ from { opacity: 1; }
2265
+ to { opacity: 0; }
2266
+ }
2267
+
2268
+ @keyframes gyos-slide-down {
2269
+ from { transform: translateY(-100%); opacity: 0; }
2270
+ to { transform: translateY(0); opacity: 1; }
2271
+ }
2272
+
2273
+ @keyframes gyos-slide-up {
2274
+ from { transform: translateY(100%); opacity: 0; }
2275
+ to { transform: translateY(0); opacity: 1; }
2276
+ }
2277
+
2278
+ @keyframes gyos-scale-in {
2279
+ from { transform: scale(0); opacity: 0; }
2280
+ to { transform: scale(1); opacity: 1; }
2281
+ }
2282
+
2283
+ @keyframes gyos-scale-out {
2284
+ from { transform: scale(1); opacity: 1; }
2285
+ to { transform: scale(0); opacity: 0; }
2286
+ }
2287
+
2288
+ [g-cloak] {
2289
+ display: none !important;
2290
2290
  }`;
2291
2291
  document.head.appendChild(style);
2292
2292
  }
@@ -5221,6 +5221,10 @@
5221
5221
  const structuralElements = [];
5222
5222
  const root = elements[0];
5223
5223
  elements.forEach(el => {
5224
+ // Await branches are detached and parsed only after their alias scope exists.
5225
+ // Do not evaluate nested structural expressions during the parent scan.
5226
+ if (isAwaitBranchDescendant(el))
5227
+ return;
5224
5228
  const hasIf = el.hasAttribute('*if');
5225
5229
  const hasFor = el.hasAttribute('*for');
5226
5230
  const hasSwitch = el.hasAttribute('*switch');
@@ -5265,6 +5269,20 @@
5265
5269
  }
5266
5270
  });
5267
5271
  }
5272
+ function isAwaitBranchDescendant(element) {
5273
+ let child = element;
5274
+ let parent = element.parentElement;
5275
+ while (parent && parent !== document.body) {
5276
+ if (parent.hasAttribute('*await') && (child.hasAttribute('*pending') ||
5277
+ child.hasAttribute('*then') ||
5278
+ child.hasAttribute('*catch'))) {
5279
+ return true;
5280
+ }
5281
+ child = parent;
5282
+ parent = parent.parentElement;
5283
+ }
5284
+ return false;
5285
+ }
5268
5286
  const elementBelongsToAnotherScope = (el, scope) => {
5269
5287
  const owner = getScopeFromElement(el);
5270
5288
  return Boolean(owner && owner !== scope);
@@ -6625,33 +6643,44 @@
6625
6643
  getCurrentProgress() {
6626
6644
  return this.currentProgress;
6627
6645
  }
6646
+ reconnect() {
6647
+ if (!this.element || !this.progressBarEnabled || !document.body)
6648
+ return;
6649
+ // Snapshots may contain a clone of the runtime bar. Keep this instance.
6650
+ document.querySelectorAll('#gyos-progress-bar').forEach(node => {
6651
+ if (node !== this.element)
6652
+ node.remove();
6653
+ });
6654
+ if (!this.element.isConnected)
6655
+ document.body.appendChild(this.element);
6656
+ }
6628
6657
  createBar() {
6629
6658
  if (typeof document === 'undefined')
6630
6659
  return;
6631
6660
  // Create progress bar element
6632
6661
  this.element = document.createElement('div');
6633
6662
  this.element.id = 'gyos-progress-bar';
6634
- this.element.style.cssText = `
6635
- position: fixed;
6636
- top: 0;
6637
- left: 0;
6638
- width: 0%;
6639
- height: 6px;
6640
- background: var(--gyos-progress-color, linear-gradient(90deg, #aab9ff, #77889f));
6641
- z-index: 999999;
6642
- transition: width 0.3s linear, opacity 0.3s linear;
6643
- opacity: 0;
6644
- pointer-events: none;
6645
- box-shadow: 0 0 10px rgba(102, 126, 234, 0.5);
6663
+ this.element.style.cssText = `
6664
+ position: fixed;
6665
+ top: 0;
6666
+ left: 0;
6667
+ width: 0%;
6668
+ height: 6px;
6669
+ background: var(--gyos-progress-color, linear-gradient(90deg, #aab9ff, #77889f));
6670
+ z-index: 999999;
6671
+ transition: width 0.3s linear, opacity 0.3s linear;
6672
+ opacity: 0;
6673
+ pointer-events: none;
6674
+ box-shadow: 0 0 10px rgba(102, 126, 234, 0.5);
6646
6675
  `;
6647
6676
  // Insert into DOM when ready
6648
6677
  if (document.readyState === 'loading') {
6649
6678
  document.addEventListener('DOMContentLoaded', () => {
6650
- document.body.insertAdjacentElement('beforeend', this.element);
6651
- });
6679
+ this.reconnect();
6680
+ }, { once: true });
6652
6681
  }
6653
6682
  else {
6654
- document.body.insertAdjacentElement('beforeend', this.element);
6683
+ this.reconnect();
6655
6684
  }
6656
6685
  }
6657
6686
  start() {
@@ -6675,6 +6704,7 @@
6675
6704
  setProgress(percent) {
6676
6705
  if (!this.element || !this.progressBarEnabled)
6677
6706
  return;
6707
+ this.reconnect();
6678
6708
  // Clamp between 0-100
6679
6709
  percent = Math.min(100, Math.max(0, percent));
6680
6710
  this.currentProgress = percent;
@@ -6723,41 +6753,41 @@
6723
6753
  function createTargetSpinner() {
6724
6754
  const spinner = document.createElement('div');
6725
6755
  spinner.className = 'gyos-target-spinner';
6726
- spinner.innerHTML = `
6727
- <div class="gyos-spinner-content">
6728
- <svg class="gyos-spinner-icon" viewBox="0 0 50 50">
6729
- <circle cx="25" cy="25" r="20" fill="none" stroke="currentColor" stroke-width="4" stroke-dasharray="31.4 31.4" />
6730
- </svg>
6731
- </div>
6756
+ spinner.innerHTML = `
6757
+ <div class="gyos-spinner-content">
6758
+ <svg class="gyos-spinner-icon" viewBox="0 0 50 50">
6759
+ <circle cx="25" cy="25" r="20" fill="none" stroke="currentColor" stroke-width="4" stroke-dasharray="31.4 31.4" />
6760
+ </svg>
6761
+ </div>
6732
6762
  `;
6733
6763
  // Inject styles if not already present
6734
6764
  if (expressionRuntimeMode() === 'standard' && !document.getElementById('gyos-target-spinner-styles')) {
6735
6765
  const style = document.createElement('style');
6736
6766
  style.id = 'gyos-target-spinner-styles';
6737
- style.textContent = `
6738
- .gyos-target-spinner {
6739
- display: flex;
6740
- align-items: center;
6741
- justify-content: center;
6742
- padding: 20px;
6743
- min-height: 60px;
6744
- }
6745
- .gyos-spinner-content {
6746
- display: flex;
6747
- align-items: center;
6748
- gap: 10px;
6749
- color: var(--gyos-spinner-color, #667eea);
6750
- font-size: 14px;
6751
- }
6752
- .gyos-spinner-icon {
6753
- width: 24px;
6754
- height: 24px;
6755
- animation: gyos-spin 1s linear infinite;
6756
- }
6757
- @keyframes gyos-spin {
6758
- 0% { transform: rotate(0deg); }
6759
- 100% { transform: rotate(360deg); }
6760
- }
6767
+ style.textContent = `
6768
+ .gyos-target-spinner {
6769
+ display: flex;
6770
+ align-items: center;
6771
+ justify-content: center;
6772
+ padding: 20px;
6773
+ min-height: 60px;
6774
+ }
6775
+ .gyos-spinner-content {
6776
+ display: flex;
6777
+ align-items: center;
6778
+ gap: 10px;
6779
+ color: var(--gyos-spinner-color, #667eea);
6780
+ font-size: 14px;
6781
+ }
6782
+ .gyos-spinner-icon {
6783
+ width: 24px;
6784
+ height: 24px;
6785
+ animation: gyos-spin 1s linear infinite;
6786
+ }
6787
+ @keyframes gyos-spin {
6788
+ 0% { transform: rotate(0deg); }
6789
+ 100% { transform: rotate(360deg); }
6790
+ }
6761
6791
  `;
6762
6792
  document.head.appendChild(style);
6763
6793
  }
@@ -7117,8 +7147,8 @@
7117
7147
  }
7118
7148
  result = target;
7119
7149
  }
7120
- await options.beforeScripts?.();
7121
7150
  options.onCommitted?.(result, normalized === 'append' || normalized === 'prepend' ? incomingChildren : [result]);
7151
+ await options.beforeScripts?.();
7122
7152
  // Additive swaps must not re-run scripts that already existed in the target.
7123
7153
  if (normalized === 'append' || normalized === 'prepend') {
7124
7154
  await executeScriptsInNodes(incomingChildren, options.signal);
@@ -7358,6 +7388,21 @@
7358
7388
  window.scrollTo({ top: 0, behavior: 'smooth' });
7359
7389
  }
7360
7390
 
7391
+ // A retained relative URL still identifies the resource loaded on its original
7392
+ // page, even after pushState changes document.baseURI.
7393
+ const resourceUrls = new WeakMap();
7394
+ function rememberResourceUrls(root, baseUrl) {
7395
+ root.querySelectorAll('script[src], link[href]').forEach(node => {
7396
+ const attribute = node.tagName === 'SCRIPT' ? 'src' : 'href';
7397
+ const source = node.getAttribute(attribute);
7398
+ if (resourceUrls.get(node)?.source === source)
7399
+ return;
7400
+ try {
7401
+ resourceUrls.set(node, { source, url: new URL(source, baseUrl).href });
7402
+ }
7403
+ catch { /* Invalid resource URLs retain their literal identity. */ }
7404
+ });
7405
+ }
7361
7406
  function isNonceMeta(el) {
7362
7407
  return el.tagName === 'META' && el.getAttribute('name')?.toLowerCase() === 'csp-nonce';
7363
7408
  }
@@ -7375,7 +7420,20 @@
7375
7420
  return;
7376
7421
  if (context.csp && isNonceMeta(el) && attr.name.toLowerCase() === 'content')
7377
7422
  return;
7378
- attributes.set(attr.name, attr.value);
7423
+ let value = attr.value;
7424
+ if ((el.tagName === 'SCRIPT' && attr.name === 'src') || (el.tagName === 'LINK' && attr.name === 'href')) {
7425
+ const cached = resourceUrls.get(el);
7426
+ if (cached?.source === value)
7427
+ value = cached.url;
7428
+ else {
7429
+ try {
7430
+ value = new URL(value, context.baseUrl || el.baseURI).href;
7431
+ resourceUrls.set(el, { source: attr.value, url: value });
7432
+ }
7433
+ catch { /* Keep invalid URLs distinct. */ }
7434
+ }
7435
+ }
7436
+ attributes.set(attr.name, value);
7379
7437
  });
7380
7438
  if (context.csp && usesCspNonce(el) && context.activeNonce) {
7381
7439
  attributes.set('nonce', context.activeNonce);
@@ -7442,19 +7500,21 @@
7442
7500
  console.warn('[GyosJS CSP] Skipped an inline MPA script because no active document nonce is configured.');
7443
7501
  }
7444
7502
  }
7445
- async function diffNodes(currentNodes, nextNodes, container = document.head, signal) {
7503
+ async function diffNodes(currentNodes, nextNodes, container = document.head, signal, currentBaseUrl = document.baseURI) {
7446
7504
  const csp = expressionRuntimeMode() === 'csp';
7447
7505
  const context = {
7448
7506
  csp,
7449
7507
  activeNonce: csp ? resolveCspNonce() : undefined
7450
7508
  };
7451
- const current = keyedNodes(currentNodes, context);
7509
+ const current = keyedNodes(currentNodes, { ...context, baseUrl: currentBaseUrl });
7452
7510
  const next = keyedNodes(nextNodes, context);
7511
+ const persistentKey = (node) => container === document.head ? node.getAttribute('g-head-persist') : null;
7512
+ const persistent = new Set(currentNodes.map(persistentKey).filter(Boolean));
7453
7513
  const currentKeys = new Set(current.map(item => item.key));
7454
7514
  const nextKeys = new Set(next.map(item => item.key));
7455
7515
  // Remove nodes that are not in the new head
7456
7516
  current.forEach(({ key, node }) => {
7457
- if (!nextKeys.has(key)) {
7517
+ if (!nextKeys.has(key) && !persistentKey(node)) {
7458
7518
  node.remove();
7459
7519
  }
7460
7520
  });
@@ -7462,6 +7522,8 @@
7462
7522
  for (const { key, node } of next) {
7463
7523
  if (signal?.aborted)
7464
7524
  return;
7525
+ if (persistent.has(persistentKey(node)))
7526
+ continue;
7465
7527
  if (!currentKeys.has(key)) {
7466
7528
  if (!canInsertNode(node, context)) {
7467
7529
  warnSkippedNode(node);
@@ -7664,6 +7726,7 @@
7664
7726
  * MPA boost navigation inspired by Turbo Drive.
7665
7727
  * Implements attribute-driven routing, snapshot caching, and persistent islands.
7666
7728
  */
7729
+ const submittingForms = new WeakSet();
7667
7730
  const snapshots = new Map();
7668
7731
  const preloadCache = new Map();
7669
7732
  const preloadControllers = new Map();
@@ -7680,12 +7743,30 @@
7680
7743
  let progressBar = null;
7681
7744
  const beforeNavigate = [];
7682
7745
  const afterNavigate = [];
7746
+ const beforeSwap = [];
7747
+ const navigationEnd = [];
7748
+ function registerNavigationHook(hooks, callback) {
7749
+ // A wrapper gives each registration its own unsubscribe identity.
7750
+ const entry = (url, context) => callback(url, context);
7751
+ hooks.push(entry);
7752
+ return () => {
7753
+ const index = hooks.indexOf(entry);
7754
+ if (index !== -1)
7755
+ hooks.splice(index, 1);
7756
+ };
7757
+ }
7683
7758
  // Expose hooks to register before/after navigation callbacks
7684
7759
  function onBeforeNavigate(callback) {
7685
- beforeNavigate.push(callback);
7760
+ return registerNavigationHook(beforeNavigate, callback);
7686
7761
  }
7687
7762
  function onAfterNavigate(callback) {
7688
- afterNavigate.push(callback);
7763
+ return registerNavigationHook(afterNavigate, callback);
7764
+ }
7765
+ function onBeforeSwap(callback) {
7766
+ return registerNavigationHook(beforeSwap, callback);
7767
+ }
7768
+ function onNavigationEnd(callback) {
7769
+ return registerNavigationHook(navigationEnd, (_url, context) => callback(context));
7689
7770
  }
7690
7771
  function startRouter(options) {
7691
7772
  // If not has g-boost attribute, do not start router
@@ -7709,6 +7790,7 @@
7709
7790
  }
7710
7791
  // Cache scripts from initial page to prevent re-execution on first navigation back
7711
7792
  cacheInitialPageScripts();
7793
+ rememberResourceUrls(document, document.baseURI);
7712
7794
  routerStarted = true;
7713
7795
  log('[GyosRouter] started');
7714
7796
  }
@@ -7765,9 +7847,13 @@
7765
7847
  const outlet = findGlobalOutlet();
7766
7848
  return outlet instanceof HTMLElement ? outlet : null;
7767
7849
  }
7850
+ function isFullDocument(html) {
7851
+ return /^\s*(?:<!--[^]*?-->\s*)*(?:<!doctype\s+html\b|<html(?:\s|>))/i.test(html);
7852
+ }
7768
7853
  function saveSnapshot(url, html) {
7769
7854
  // create HTMLElement by html string to remove scripts and get clean snapshot
7770
7855
  const doc = parseNavigationDocument(html);
7856
+ doc.querySelectorAll('#gyos-progress-bar').forEach(node => node.remove());
7771
7857
  // Ignore hash for snapshot keys
7772
7858
  if (url.includes('#'))
7773
7859
  url = url.split('#')[0];
@@ -7776,7 +7862,7 @@
7776
7862
  if (s.hasAttribute('g-script-once'))
7777
7863
  s.textContent = '';
7778
7864
  });
7779
- snapshots.set(url, { html: doc.documentElement.outerHTML });
7865
+ snapshots.set(url, { html: doc.documentElement.outerHTML, fullDocument: isFullDocument(html) });
7780
7866
  log('[GyosRouter] snapshot saved for', url);
7781
7867
  }
7782
7868
  function getOutletIndex(root, target) {
@@ -7888,10 +7974,10 @@
7888
7974
  // update callback remains the navigation source of truth and is awaited below.
7889
7975
  void promise?.catch(() => undefined);
7890
7976
  }
7891
- function runNavigationHooks(callbacks, url) {
7892
- callbacks.forEach(callback => {
7977
+ function runNavigationHooks(callbacks, url, context) {
7978
+ [...callbacks].forEach(callback => {
7893
7979
  try {
7894
- callback(url);
7980
+ callback(url, { ...context });
7895
7981
  }
7896
7982
  catch (error) {
7897
7983
  console.error('[GyosRouter] navigation hook error', error);
@@ -7929,7 +8015,13 @@
7929
8015
  url = mergeFormDataIntoUrl(url, opts.formData);
7930
8016
  }
7931
8017
  else {
7932
- init.body = opts.formData;
8018
+ if (opts.formEncoding === 'application/x-www-form-urlencoded') {
8019
+ const encoded = new URLSearchParams();
8020
+ opts.formData.forEach((value, name) => encoded.append(name, typeof value === 'string' ? value : value.name));
8021
+ init.body = encoded;
8022
+ }
8023
+ else
8024
+ init.body = opts.formData;
7933
8025
  }
7934
8026
  }
7935
8027
  else if (opts.jsonData) {
@@ -7972,25 +8064,26 @@
7972
8064
  preloadControllers.delete(cacheKey);
7973
8065
  });
7974
8066
  }
7975
- async function updateHead(fromDoc, signal) {
8067
+ async function updateHead(fromDoc, signal, currentBaseUrl) {
7976
8068
  const allowedSelector = 'meta, link, style:not(#gyos-transitions), script';
7977
8069
  const currentNodes = Array.from(document.head.querySelectorAll(allowedSelector));
7978
8070
  const nextNodes = Array.from(fromDoc.head.querySelectorAll(allowedSelector));
7979
- await diffNodes(currentNodes, nextNodes, document.head, signal);
8071
+ await diffNodes(currentNodes, nextNodes, document.head, signal, currentBaseUrl);
7980
8072
  }
7981
- async function scriptNotInOutletTarget(fromDoc, target, source, signal) {
8073
+ async function scriptNotInOutletTarget(fromDoc, target, source, signal, currentBaseUrl) {
7982
8074
  // scripts in current document and it not in target outlet
7983
8075
  const currentScripts = Array.from(document.scripts).filter(s => !target.contains(s) && !document.head.contains(s));
7984
8076
  // scripts in fromDoc and it not in source outlet
7985
8077
  const incomingScripts = Array.from(fromDoc.scripts).filter(s => !source.contains(s) && !fromDoc.head.contains(s));
7986
8078
  // Diff and update scripts not in outlet/target
7987
- await diffNodes(currentScripts, incomingScripts, document.body, signal);
8079
+ await diffNodes(currentScripts, incomingScripts, document.body, signal, currentBaseUrl);
7988
8080
  }
7989
8081
  function resolveIncomingScriptUrls(root, baseUrl) {
7990
- root.querySelectorAll('script[src]').forEach(script => {
7991
- const source = script.getAttribute('src');
8082
+ root.querySelectorAll('script[src], link[href]').forEach(node => {
8083
+ const attribute = node.tagName === 'SCRIPT' ? 'src' : 'href';
8084
+ const source = node.getAttribute(attribute);
7992
8085
  if (source)
7993
- script.src = new URL(source, baseUrl).href;
8086
+ node.setAttribute(attribute, new URL(source, baseUrl).href);
7994
8087
  });
7995
8088
  }
7996
8089
  function isNavigableHtmlResponse(response) {
@@ -8044,6 +8137,22 @@
8044
8137
  resolveDone
8045
8138
  };
8046
8139
  activeNavigation = transaction;
8140
+ const currentBaseUrl = document.baseURI;
8141
+ rememberResourceUrls(document, currentBaseUrl);
8142
+ const context = {
8143
+ from: currentUrl, url: opts.url, method: opts.method.toUpperCase(),
8144
+ trigger: opts.trigger || null, target: null, form: opts.form || null,
8145
+ popstate: opts.popstate === true, signal: transaction.controller.signal,
8146
+ status: null, committed: false, fallback: false, outcome: null
8147
+ };
8148
+ const formEvent = opts.form
8149
+ ? { form: opts.form, url: opts.url, status: null, outcome: null, committed: false, fallback: false }
8150
+ : null;
8151
+ const fallback = (url, requestSent) => {
8152
+ context.fallback = context.method === 'GET' || (!requestSent && !!opts.form);
8153
+ context.outcome ?? (context.outcome = context.fallback ? 'fallback' : 'invalid-response');
8154
+ fallbackFromBoost(opts, url, requestSent);
8155
+ };
8047
8156
  const hasTargetSpinner = opts.trigger?.hasAttribute('g-router-spin');
8048
8157
  const setRand = () => {
8049
8158
  if (isActiveNavigation(transaction) && progressBar?.getCurrentProgress() < 70) {
@@ -8051,7 +8160,10 @@
8051
8160
  }
8052
8161
  };
8053
8162
  try {
8054
- runNavigationHooks(beforeNavigate, opts.url);
8163
+ if (formEvent)
8164
+ document.dispatchEvent(new CustomEvent('gyos:form-start', { detail: { ...formEvent } }));
8165
+ runNavigationHooks(beforeNavigate, opts.url, context);
8166
+ assertActiveNavigation(transaction);
8055
8167
  progressBar?.start();
8056
8168
  // popstate already points history at the destination entry. Keep the visible
8057
8169
  // page's position under currentUrl without overwriting that destination state.
@@ -8060,9 +8172,10 @@
8060
8172
  saveScrollPosition();
8061
8173
  // Pick target element to swap
8062
8174
  let target = resolveTarget(opts.trigger, opts.targetSelector, opts.targetOutletIndex);
8175
+ context.target = target;
8063
8176
  if (!target) {
8064
8177
  if (isActiveNavigation(transaction))
8065
- fallbackFromBoost(opts, opts.url, false);
8178
+ fallback(opts.url, false);
8066
8179
  return;
8067
8180
  }
8068
8181
  const swapMode = (opts.swapMode || opts.trigger?.getAttribute('g-swap') || 'inner').toLowerCase();
@@ -8087,6 +8200,7 @@
8087
8200
  if (hasTargetSpinner)
8088
8201
  transaction.spinner = showTargetSpinner(target, swapMode);
8089
8202
  const { finalUrl, init } = buildRequest(opts);
8203
+ context.url = finalUrl;
8090
8204
  // Add abort signal to request
8091
8205
  init.signal = transaction.controller.signal;
8092
8206
  let html;
@@ -8114,7 +8228,8 @@
8114
8228
  if (error.name === 'AbortError')
8115
8229
  throw error;
8116
8230
  assertActiveNavigation(transaction);
8117
- window.location.href = finalUrl;
8231
+ context.outcome = 'network-error';
8232
+ fallback(finalUrl, true);
8118
8233
  return;
8119
8234
  }
8120
8235
  preloadCache.delete(preloadKey); // consume cache
@@ -8139,28 +8254,46 @@
8139
8254
  log('[GyosRouter] Navigation cancelled');
8140
8255
  return;
8141
8256
  }
8257
+ context.outcome = 'network-error';
8142
8258
  if (isActiveNavigation(transaction))
8143
- fallbackFromBoost(opts, finalUrl, true);
8259
+ fallback(finalUrl, true);
8144
8260
  return;
8145
8261
  }
8146
8262
  }
8147
8263
  assertActiveNavigation(transaction);
8148
- // If response not ok, fallback to full navigation
8149
- if (!response || !response.ok || !isNavigableHtmlResponse(response)) {
8264
+ context.status = response?.status ?? null;
8265
+ context.url = response?.url || finalUrl;
8266
+ const acceptedErrors = (opts.trigger?.getAttribute('g-boost-errors') || '').split(/[\s,]+/);
8267
+ const renderHttpError = !!response && response.status >= 400 && response.status <= 599
8268
+ && acceptedErrors.includes(String(response.status));
8269
+ if (response && !response.ok)
8270
+ context.outcome = 'http-error';
8271
+ if (!response || (!response.ok && !renderHttpError) || !isNavigableHtmlResponse(response)) {
8272
+ context.outcome ?? (context.outcome = 'invalid-response');
8150
8273
  if (isActiveNavigation(transaction))
8151
- fallbackFromBoost(opts, finalUrl, true);
8274
+ fallback(finalUrl, true);
8152
8275
  return;
8153
8276
  }
8154
8277
  html = await response.text();
8155
8278
  assertActiveNavigation(transaction);
8156
- if (!opts.popstate && target.hasAttribute('g-snapshot')) {
8157
- saveSnapshot(canonicalUrl(response.url || finalUrl), html);
8158
- }
8159
8279
  }
8160
8280
  // Parse HTML
8161
8281
  const doc = html
8162
8282
  ? parseNavigationDocument(html)
8163
8283
  : document.implementation.createHTMLDocument();
8284
+ // Detached parsing cannot tell whether the live CSP permits an incoming base.
8285
+ // Let native navigation enforce base-uri instead of authorizing its URLs ourselves.
8286
+ if (doc.querySelector('base[href]') || opts.historyFragment?.querySelector('base[href]')) {
8287
+ context.outcome = 'invalid-response';
8288
+ fallback(response?.url || finalUrl, true);
8289
+ return;
8290
+ }
8291
+ if (response?.ok && !opts.popstate && target.hasAttribute('g-snapshot')) {
8292
+ saveSnapshot(canonicalUrl(response.url || finalUrl), html);
8293
+ }
8294
+ const syncDocumentAttributes = isFullOutletNavigation && destructiveSwap && !currentHead
8295
+ && !opts.historyFragment && (opts.popstate && snapshots.has(urlWithoutHash)
8296
+ ? snapshots.get(urlWithoutHash).fullDocument : isFullDocument(html || ''));
8164
8297
  // Pick source fragment
8165
8298
  const src = opts.historyFragment || pickSourceFragment(doc, target, targetOutletIndex);
8166
8299
  stripInertFallbackContent(src);
@@ -8172,15 +8305,18 @@
8172
8305
  targetUrl += finalUrl.substring(finalUrl.indexOf('#'));
8173
8306
  }
8174
8307
  resolveIncomingScriptUrls(doc, targetUrl);
8308
+ context.url = targetUrl;
8175
8309
  if (opts.historyFragment)
8176
8310
  resolveIncomingScriptUrls(src, targetUrl);
8177
8311
  const triggerChangesState = opts.trigger?.hasAttribute('g-change-state') || false;
8178
8312
  const keepsCurrentState = opts.trigger?.hasAttribute('g-current-state') || false;
8179
8313
  const redirectedSubmission = opts.method.toUpperCase() !== 'GET' && response?.redirected === true;
8180
- const changesState = !keepsCurrentState && (opts.changeState === true || triggerChangesState || redirectedSubmission);
8314
+ const changesState = context.outcome !== 'http-error' && !keepsCurrentState && (opts.changeState === true || triggerChangesState || redirectedSubmission);
8181
8315
  const performUpdate = async () => {
8182
8316
  assertActiveNavigation(transaction);
8183
8317
  transaction.committing = true;
8318
+ runNavigationHooks(beforeSwap, targetUrl, context);
8319
+ assertActiveNavigation(transaction);
8184
8320
  // Update progress to rand 80 - 90% before swap
8185
8321
  progressBar?.setProgress(Math.random() * 10 + 80);
8186
8322
  const outgoingHistoryFragment = changesState && !opts.replace && !isFullOutletNavigation
@@ -8251,21 +8387,34 @@
8251
8387
  beforeScripts: async () => {
8252
8388
  if (!isFullOutletNavigation || currentHead)
8253
8389
  return;
8390
+ if (syncDocumentAttributes) {
8391
+ for (const name of ['lang', 'dir']) {
8392
+ const value = doc.documentElement.getAttribute(name);
8393
+ if (value === null)
8394
+ document.documentElement.removeAttribute(name);
8395
+ else
8396
+ document.documentElement.setAttribute(name, value);
8397
+ }
8398
+ }
8254
8399
  const incomingTitle = doc.querySelector('title');
8255
8400
  if (incomingTitle) {
8256
8401
  document.title = incomingTitle.textContent || document.title;
8257
8402
  }
8258
- await updateHead(doc, transaction.controller.signal);
8403
+ await updateHead(doc, transaction.controller.signal, currentBaseUrl);
8259
8404
  assertActiveNavigation(transaction);
8260
8405
  },
8261
8406
  onCommitted: (committedTarget, roots) => {
8262
8407
  target = committedTarget;
8408
+ context.target = committedTarget;
8409
+ context.committed = true;
8410
+ progressBar?.reconnect();
8263
8411
  committedRoots = roots;
8264
8412
  }
8265
8413
  });
8414
+ context.committed = true;
8266
8415
  assertActiveNavigation(transaction);
8267
8416
  if (isFullOutletNavigation) {
8268
- await scriptNotInOutletTarget(doc, target, src, transaction.controller.signal);
8417
+ await scriptNotInOutletTarget(doc, target, src, transaction.controller.signal, currentBaseUrl);
8269
8418
  assertActiveNavigation(transaction);
8270
8419
  }
8271
8420
  }
@@ -8299,14 +8448,15 @@
8299
8448
  await performUpdate();
8300
8449
  }
8301
8450
  assertActiveNavigation(transaction);
8302
- if (removeTriggerAfterCommit && opts.trigger instanceof HTMLElement && opts.trigger.isConnected) {
8451
+ if (removeTriggerAfterCommit && context.outcome !== 'http-error' && opts.trigger instanceof HTMLElement && opts.trigger.isConnected) {
8303
8452
  disposeEffects(opts.trigger);
8304
8453
  opts.trigger.remove();
8305
8454
  }
8306
8455
  if (hasTargetSpinner)
8307
8456
  hideTargetSpinner(transaction.spinner);
8308
8457
  transaction.spinner = null;
8309
- runNavigationHooks(afterNavigate, targetUrl);
8458
+ context.outcome ?? (context.outcome = 'success');
8459
+ runNavigationHooks(afterNavigate, targetUrl, context);
8310
8460
  log('[GyosRouter] navigated to', targetUrl);
8311
8461
  currentUrl = changesState
8312
8462
  ? canonicalUrl(targetUrl, true)
@@ -8322,11 +8472,15 @@
8322
8472
  return;
8323
8473
  }
8324
8474
  if (isActiveNavigation(transaction)) {
8475
+ context.outcome ?? (context.outcome = 'error');
8325
8476
  console.error('[GyosRouter] navigation error', error);
8326
- fallbackFromBoost(opts, opts.url, true);
8477
+ fallback(opts.url, true);
8327
8478
  }
8328
8479
  }
8329
8480
  finally {
8481
+ if (transaction.controller.signal.aborted)
8482
+ context.outcome = 'aborted';
8483
+ context.outcome ?? (context.outcome = 'aborted');
8330
8484
  if (transaction.interval)
8331
8485
  clearInterval(transaction.interval);
8332
8486
  if (transaction.spinner)
@@ -8336,6 +8490,15 @@
8336
8490
  progressBar?.complete();
8337
8491
  }
8338
8492
  transaction.resolveDone();
8493
+ if (formEvent)
8494
+ submittingForms.delete(formEvent.form);
8495
+ runNavigationHooks(navigationEnd, context.url, context);
8496
+ if (formEvent) {
8497
+ const { url, status, outcome, committed, fallback } = context;
8498
+ document.dispatchEvent(new CustomEvent('gyos:form-end', {
8499
+ detail: { ...formEvent, url, status, outcome, committed, fallback }
8500
+ }));
8501
+ }
8339
8502
  }
8340
8503
  }
8341
8504
  function shouldBoost(el) {
@@ -8444,16 +8607,34 @@
8444
8607
  return;
8445
8608
  if (shouldDeferToFormValidation(form))
8446
8609
  return;
8447
- event.preventDefault();
8448
- const action = form.action || window.location.href;
8449
- const method = (form.method || 'GET').toUpperCase();
8450
- const url = new URL(action, window.location.href);
8451
- if (url.origin !== window.location.origin) {
8452
- window.location.href = url.toString();
8610
+ const submitter = event.submitter;
8611
+ const override = (name) => submitter?.getAttribute(`form${name}`) ?? form.getAttribute(name);
8612
+ const target = override('target') ?? document.querySelector('base[target]')?.getAttribute('target');
8613
+ const declaredMethod = (override('method') || 'GET').toUpperCase();
8614
+ const method = ['GET', 'POST', 'DIALOG'].includes(declaredMethod) ? declaredMethod : 'GET';
8615
+ const formEncoding = override('enctype')?.toLowerCase();
8616
+ if ((target && target.toLowerCase() !== '_self') || method === 'DIALOG' || formEncoding === 'text/plain')
8617
+ return;
8618
+ if (!resolveTarget(form))
8619
+ return;
8620
+ // Image submitters carry click coordinates which SubmitEvent does not expose.
8621
+ if (submitter instanceof HTMLInputElement && submitter.type === 'image')
8622
+ return;
8623
+ let url;
8624
+ try {
8625
+ url = new URL(override('action') || window.location.href, document.baseURI);
8626
+ }
8627
+ catch {
8453
8628
  return;
8454
8629
  }
8455
- const formData = new FormData(form);
8456
- navigate({ url: url.toString(), method, trigger: form, form, formData, changeState: method === 'GET' });
8630
+ if (url.origin !== window.location.origin)
8631
+ return;
8632
+ event.preventDefault();
8633
+ if (submittingForms.has(form))
8634
+ return;
8635
+ const formData = new FormData(form, submitter);
8636
+ submittingForms.add(form);
8637
+ void navigate({ url: url.toString(), method, trigger: form, form, formData, formEncoding, changeState: method === 'GET' });
8457
8638
  }
8458
8639
  function onPopState(event) {
8459
8640
  const url = window.location.href;
@@ -8558,10 +8739,12 @@
8558
8739
  startRouter,
8559
8740
  onBeforeNavigate,
8560
8741
  onAfterNavigate,
8742
+ onBeforeSwap,
8743
+ onNavigationEnd,
8561
8744
  portalCreate,
8562
8745
  portalDestroy,
8563
8746
  setCspNonce,
8564
- version: '0.3.1'
8747
+ version: '0.4.0'
8565
8748
  };
8566
8749
 
8567
8750
  setExpressionRuntime(standardExpressionRuntime);
@@ -8597,6 +8780,8 @@
8597
8780
  exports.on = on;
8598
8781
  exports.onAfterNavigate = onAfterNavigate;
8599
8782
  exports.onBeforeNavigate = onBeforeNavigate;
8783
+ exports.onBeforeSwap = onBeforeSwap;
8784
+ exports.onNavigationEnd = onNavigationEnd;
8600
8785
  exports.once = once;
8601
8786
  exports.pipe = pipe;
8602
8787
  exports.portalCreate = portalCreate;