gyosjs 0.3.2 → 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.2
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
  }
@@ -6643,33 +6643,44 @@
6643
6643
  getCurrentProgress() {
6644
6644
  return this.currentProgress;
6645
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
+ }
6646
6657
  createBar() {
6647
6658
  if (typeof document === 'undefined')
6648
6659
  return;
6649
6660
  // Create progress bar element
6650
6661
  this.element = document.createElement('div');
6651
6662
  this.element.id = 'gyos-progress-bar';
6652
- this.element.style.cssText = `
6653
- position: fixed;
6654
- top: 0;
6655
- left: 0;
6656
- width: 0%;
6657
- height: 6px;
6658
- background: var(--gyos-progress-color, linear-gradient(90deg, #aab9ff, #77889f));
6659
- z-index: 999999;
6660
- transition: width 0.3s linear, opacity 0.3s linear;
6661
- opacity: 0;
6662
- pointer-events: none;
6663
- 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);
6664
6675
  `;
6665
6676
  // Insert into DOM when ready
6666
6677
  if (document.readyState === 'loading') {
6667
6678
  document.addEventListener('DOMContentLoaded', () => {
6668
- document.body.insertAdjacentElement('beforeend', this.element);
6669
- });
6679
+ this.reconnect();
6680
+ }, { once: true });
6670
6681
  }
6671
6682
  else {
6672
- document.body.insertAdjacentElement('beforeend', this.element);
6683
+ this.reconnect();
6673
6684
  }
6674
6685
  }
6675
6686
  start() {
@@ -6693,6 +6704,7 @@
6693
6704
  setProgress(percent) {
6694
6705
  if (!this.element || !this.progressBarEnabled)
6695
6706
  return;
6707
+ this.reconnect();
6696
6708
  // Clamp between 0-100
6697
6709
  percent = Math.min(100, Math.max(0, percent));
6698
6710
  this.currentProgress = percent;
@@ -6741,41 +6753,41 @@
6741
6753
  function createTargetSpinner() {
6742
6754
  const spinner = document.createElement('div');
6743
6755
  spinner.className = 'gyos-target-spinner';
6744
- spinner.innerHTML = `
6745
- <div class="gyos-spinner-content">
6746
- <svg class="gyos-spinner-icon" viewBox="0 0 50 50">
6747
- <circle cx="25" cy="25" r="20" fill="none" stroke="currentColor" stroke-width="4" stroke-dasharray="31.4 31.4" />
6748
- </svg>
6749
- </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>
6750
6762
  `;
6751
6763
  // Inject styles if not already present
6752
6764
  if (expressionRuntimeMode() === 'standard' && !document.getElementById('gyos-target-spinner-styles')) {
6753
6765
  const style = document.createElement('style');
6754
6766
  style.id = 'gyos-target-spinner-styles';
6755
- style.textContent = `
6756
- .gyos-target-spinner {
6757
- display: flex;
6758
- align-items: center;
6759
- justify-content: center;
6760
- padding: 20px;
6761
- min-height: 60px;
6762
- }
6763
- .gyos-spinner-content {
6764
- display: flex;
6765
- align-items: center;
6766
- gap: 10px;
6767
- color: var(--gyos-spinner-color, #667eea);
6768
- font-size: 14px;
6769
- }
6770
- .gyos-spinner-icon {
6771
- width: 24px;
6772
- height: 24px;
6773
- animation: gyos-spin 1s linear infinite;
6774
- }
6775
- @keyframes gyos-spin {
6776
- 0% { transform: rotate(0deg); }
6777
- 100% { transform: rotate(360deg); }
6778
- }
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
+ }
6779
6791
  `;
6780
6792
  document.head.appendChild(style);
6781
6793
  }
@@ -7135,8 +7147,8 @@
7135
7147
  }
7136
7148
  result = target;
7137
7149
  }
7138
- await options.beforeScripts?.();
7139
7150
  options.onCommitted?.(result, normalized === 'append' || normalized === 'prepend' ? incomingChildren : [result]);
7151
+ await options.beforeScripts?.();
7140
7152
  // Additive swaps must not re-run scripts that already existed in the target.
7141
7153
  if (normalized === 'append' || normalized === 'prepend') {
7142
7154
  await executeScriptsInNodes(incomingChildren, options.signal);
@@ -7376,6 +7388,21 @@
7376
7388
  window.scrollTo({ top: 0, behavior: 'smooth' });
7377
7389
  }
7378
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
+ }
7379
7406
  function isNonceMeta(el) {
7380
7407
  return el.tagName === 'META' && el.getAttribute('name')?.toLowerCase() === 'csp-nonce';
7381
7408
  }
@@ -7393,7 +7420,20 @@
7393
7420
  return;
7394
7421
  if (context.csp && isNonceMeta(el) && attr.name.toLowerCase() === 'content')
7395
7422
  return;
7396
- 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);
7397
7437
  });
7398
7438
  if (context.csp && usesCspNonce(el) && context.activeNonce) {
7399
7439
  attributes.set('nonce', context.activeNonce);
@@ -7460,19 +7500,21 @@
7460
7500
  console.warn('[GyosJS CSP] Skipped an inline MPA script because no active document nonce is configured.');
7461
7501
  }
7462
7502
  }
7463
- async function diffNodes(currentNodes, nextNodes, container = document.head, signal) {
7503
+ async function diffNodes(currentNodes, nextNodes, container = document.head, signal, currentBaseUrl = document.baseURI) {
7464
7504
  const csp = expressionRuntimeMode() === 'csp';
7465
7505
  const context = {
7466
7506
  csp,
7467
7507
  activeNonce: csp ? resolveCspNonce() : undefined
7468
7508
  };
7469
- const current = keyedNodes(currentNodes, context);
7509
+ const current = keyedNodes(currentNodes, { ...context, baseUrl: currentBaseUrl });
7470
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));
7471
7513
  const currentKeys = new Set(current.map(item => item.key));
7472
7514
  const nextKeys = new Set(next.map(item => item.key));
7473
7515
  // Remove nodes that are not in the new head
7474
7516
  current.forEach(({ key, node }) => {
7475
- if (!nextKeys.has(key)) {
7517
+ if (!nextKeys.has(key) && !persistentKey(node)) {
7476
7518
  node.remove();
7477
7519
  }
7478
7520
  });
@@ -7480,6 +7522,8 @@
7480
7522
  for (const { key, node } of next) {
7481
7523
  if (signal?.aborted)
7482
7524
  return;
7525
+ if (persistent.has(persistentKey(node)))
7526
+ continue;
7483
7527
  if (!currentKeys.has(key)) {
7484
7528
  if (!canInsertNode(node, context)) {
7485
7529
  warnSkippedNode(node);
@@ -7682,6 +7726,7 @@
7682
7726
  * MPA boost navigation inspired by Turbo Drive.
7683
7727
  * Implements attribute-driven routing, snapshot caching, and persistent islands.
7684
7728
  */
7729
+ const submittingForms = new WeakSet();
7685
7730
  const snapshots = new Map();
7686
7731
  const preloadCache = new Map();
7687
7732
  const preloadControllers = new Map();
@@ -7698,12 +7743,30 @@
7698
7743
  let progressBar = null;
7699
7744
  const beforeNavigate = [];
7700
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
+ }
7701
7758
  // Expose hooks to register before/after navigation callbacks
7702
7759
  function onBeforeNavigate(callback) {
7703
- beforeNavigate.push(callback);
7760
+ return registerNavigationHook(beforeNavigate, callback);
7704
7761
  }
7705
7762
  function onAfterNavigate(callback) {
7706
- 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));
7707
7770
  }
7708
7771
  function startRouter(options) {
7709
7772
  // If not has g-boost attribute, do not start router
@@ -7727,6 +7790,7 @@
7727
7790
  }
7728
7791
  // Cache scripts from initial page to prevent re-execution on first navigation back
7729
7792
  cacheInitialPageScripts();
7793
+ rememberResourceUrls(document, document.baseURI);
7730
7794
  routerStarted = true;
7731
7795
  log('[GyosRouter] started');
7732
7796
  }
@@ -7783,9 +7847,13 @@
7783
7847
  const outlet = findGlobalOutlet();
7784
7848
  return outlet instanceof HTMLElement ? outlet : null;
7785
7849
  }
7850
+ function isFullDocument(html) {
7851
+ return /^\s*(?:<!--[^]*?-->\s*)*(?:<!doctype\s+html\b|<html(?:\s|>))/i.test(html);
7852
+ }
7786
7853
  function saveSnapshot(url, html) {
7787
7854
  // create HTMLElement by html string to remove scripts and get clean snapshot
7788
7855
  const doc = parseNavigationDocument(html);
7856
+ doc.querySelectorAll('#gyos-progress-bar').forEach(node => node.remove());
7789
7857
  // Ignore hash for snapshot keys
7790
7858
  if (url.includes('#'))
7791
7859
  url = url.split('#')[0];
@@ -7794,7 +7862,7 @@
7794
7862
  if (s.hasAttribute('g-script-once'))
7795
7863
  s.textContent = '';
7796
7864
  });
7797
- snapshots.set(url, { html: doc.documentElement.outerHTML });
7865
+ snapshots.set(url, { html: doc.documentElement.outerHTML, fullDocument: isFullDocument(html) });
7798
7866
  log('[GyosRouter] snapshot saved for', url);
7799
7867
  }
7800
7868
  function getOutletIndex(root, target) {
@@ -7906,10 +7974,10 @@
7906
7974
  // update callback remains the navigation source of truth and is awaited below.
7907
7975
  void promise?.catch(() => undefined);
7908
7976
  }
7909
- function runNavigationHooks(callbacks, url) {
7910
- callbacks.forEach(callback => {
7977
+ function runNavigationHooks(callbacks, url, context) {
7978
+ [...callbacks].forEach(callback => {
7911
7979
  try {
7912
- callback(url);
7980
+ callback(url, { ...context });
7913
7981
  }
7914
7982
  catch (error) {
7915
7983
  console.error('[GyosRouter] navigation hook error', error);
@@ -7947,7 +8015,13 @@
7947
8015
  url = mergeFormDataIntoUrl(url, opts.formData);
7948
8016
  }
7949
8017
  else {
7950
- 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;
7951
8025
  }
7952
8026
  }
7953
8027
  else if (opts.jsonData) {
@@ -7990,25 +8064,26 @@
7990
8064
  preloadControllers.delete(cacheKey);
7991
8065
  });
7992
8066
  }
7993
- async function updateHead(fromDoc, signal) {
8067
+ async function updateHead(fromDoc, signal, currentBaseUrl) {
7994
8068
  const allowedSelector = 'meta, link, style:not(#gyos-transitions), script';
7995
8069
  const currentNodes = Array.from(document.head.querySelectorAll(allowedSelector));
7996
8070
  const nextNodes = Array.from(fromDoc.head.querySelectorAll(allowedSelector));
7997
- await diffNodes(currentNodes, nextNodes, document.head, signal);
8071
+ await diffNodes(currentNodes, nextNodes, document.head, signal, currentBaseUrl);
7998
8072
  }
7999
- async function scriptNotInOutletTarget(fromDoc, target, source, signal) {
8073
+ async function scriptNotInOutletTarget(fromDoc, target, source, signal, currentBaseUrl) {
8000
8074
  // scripts in current document and it not in target outlet
8001
8075
  const currentScripts = Array.from(document.scripts).filter(s => !target.contains(s) && !document.head.contains(s));
8002
8076
  // scripts in fromDoc and it not in source outlet
8003
8077
  const incomingScripts = Array.from(fromDoc.scripts).filter(s => !source.contains(s) && !fromDoc.head.contains(s));
8004
8078
  // Diff and update scripts not in outlet/target
8005
- await diffNodes(currentScripts, incomingScripts, document.body, signal);
8079
+ await diffNodes(currentScripts, incomingScripts, document.body, signal, currentBaseUrl);
8006
8080
  }
8007
8081
  function resolveIncomingScriptUrls(root, baseUrl) {
8008
- root.querySelectorAll('script[src]').forEach(script => {
8009
- 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);
8010
8085
  if (source)
8011
- script.src = new URL(source, baseUrl).href;
8086
+ node.setAttribute(attribute, new URL(source, baseUrl).href);
8012
8087
  });
8013
8088
  }
8014
8089
  function isNavigableHtmlResponse(response) {
@@ -8062,6 +8137,22 @@
8062
8137
  resolveDone
8063
8138
  };
8064
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
+ };
8065
8156
  const hasTargetSpinner = opts.trigger?.hasAttribute('g-router-spin');
8066
8157
  const setRand = () => {
8067
8158
  if (isActiveNavigation(transaction) && progressBar?.getCurrentProgress() < 70) {
@@ -8069,7 +8160,10 @@
8069
8160
  }
8070
8161
  };
8071
8162
  try {
8072
- 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);
8073
8167
  progressBar?.start();
8074
8168
  // popstate already points history at the destination entry. Keep the visible
8075
8169
  // page's position under currentUrl without overwriting that destination state.
@@ -8078,9 +8172,10 @@
8078
8172
  saveScrollPosition();
8079
8173
  // Pick target element to swap
8080
8174
  let target = resolveTarget(opts.trigger, opts.targetSelector, opts.targetOutletIndex);
8175
+ context.target = target;
8081
8176
  if (!target) {
8082
8177
  if (isActiveNavigation(transaction))
8083
- fallbackFromBoost(opts, opts.url, false);
8178
+ fallback(opts.url, false);
8084
8179
  return;
8085
8180
  }
8086
8181
  const swapMode = (opts.swapMode || opts.trigger?.getAttribute('g-swap') || 'inner').toLowerCase();
@@ -8105,6 +8200,7 @@
8105
8200
  if (hasTargetSpinner)
8106
8201
  transaction.spinner = showTargetSpinner(target, swapMode);
8107
8202
  const { finalUrl, init } = buildRequest(opts);
8203
+ context.url = finalUrl;
8108
8204
  // Add abort signal to request
8109
8205
  init.signal = transaction.controller.signal;
8110
8206
  let html;
@@ -8132,7 +8228,8 @@
8132
8228
  if (error.name === 'AbortError')
8133
8229
  throw error;
8134
8230
  assertActiveNavigation(transaction);
8135
- window.location.href = finalUrl;
8231
+ context.outcome = 'network-error';
8232
+ fallback(finalUrl, true);
8136
8233
  return;
8137
8234
  }
8138
8235
  preloadCache.delete(preloadKey); // consume cache
@@ -8157,28 +8254,46 @@
8157
8254
  log('[GyosRouter] Navigation cancelled');
8158
8255
  return;
8159
8256
  }
8257
+ context.outcome = 'network-error';
8160
8258
  if (isActiveNavigation(transaction))
8161
- fallbackFromBoost(opts, finalUrl, true);
8259
+ fallback(finalUrl, true);
8162
8260
  return;
8163
8261
  }
8164
8262
  }
8165
8263
  assertActiveNavigation(transaction);
8166
- // If response not ok, fallback to full navigation
8167
- 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');
8168
8273
  if (isActiveNavigation(transaction))
8169
- fallbackFromBoost(opts, finalUrl, true);
8274
+ fallback(finalUrl, true);
8170
8275
  return;
8171
8276
  }
8172
8277
  html = await response.text();
8173
8278
  assertActiveNavigation(transaction);
8174
- if (!opts.popstate && target.hasAttribute('g-snapshot')) {
8175
- saveSnapshot(canonicalUrl(response.url || finalUrl), html);
8176
- }
8177
8279
  }
8178
8280
  // Parse HTML
8179
8281
  const doc = html
8180
8282
  ? parseNavigationDocument(html)
8181
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 || ''));
8182
8297
  // Pick source fragment
8183
8298
  const src = opts.historyFragment || pickSourceFragment(doc, target, targetOutletIndex);
8184
8299
  stripInertFallbackContent(src);
@@ -8190,15 +8305,18 @@
8190
8305
  targetUrl += finalUrl.substring(finalUrl.indexOf('#'));
8191
8306
  }
8192
8307
  resolveIncomingScriptUrls(doc, targetUrl);
8308
+ context.url = targetUrl;
8193
8309
  if (opts.historyFragment)
8194
8310
  resolveIncomingScriptUrls(src, targetUrl);
8195
8311
  const triggerChangesState = opts.trigger?.hasAttribute('g-change-state') || false;
8196
8312
  const keepsCurrentState = opts.trigger?.hasAttribute('g-current-state') || false;
8197
8313
  const redirectedSubmission = opts.method.toUpperCase() !== 'GET' && response?.redirected === true;
8198
- const changesState = !keepsCurrentState && (opts.changeState === true || triggerChangesState || redirectedSubmission);
8314
+ const changesState = context.outcome !== 'http-error' && !keepsCurrentState && (opts.changeState === true || triggerChangesState || redirectedSubmission);
8199
8315
  const performUpdate = async () => {
8200
8316
  assertActiveNavigation(transaction);
8201
8317
  transaction.committing = true;
8318
+ runNavigationHooks(beforeSwap, targetUrl, context);
8319
+ assertActiveNavigation(transaction);
8202
8320
  // Update progress to rand 80 - 90% before swap
8203
8321
  progressBar?.setProgress(Math.random() * 10 + 80);
8204
8322
  const outgoingHistoryFragment = changesState && !opts.replace && !isFullOutletNavigation
@@ -8269,21 +8387,34 @@
8269
8387
  beforeScripts: async () => {
8270
8388
  if (!isFullOutletNavigation || currentHead)
8271
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
+ }
8272
8399
  const incomingTitle = doc.querySelector('title');
8273
8400
  if (incomingTitle) {
8274
8401
  document.title = incomingTitle.textContent || document.title;
8275
8402
  }
8276
- await updateHead(doc, transaction.controller.signal);
8403
+ await updateHead(doc, transaction.controller.signal, currentBaseUrl);
8277
8404
  assertActiveNavigation(transaction);
8278
8405
  },
8279
8406
  onCommitted: (committedTarget, roots) => {
8280
8407
  target = committedTarget;
8408
+ context.target = committedTarget;
8409
+ context.committed = true;
8410
+ progressBar?.reconnect();
8281
8411
  committedRoots = roots;
8282
8412
  }
8283
8413
  });
8414
+ context.committed = true;
8284
8415
  assertActiveNavigation(transaction);
8285
8416
  if (isFullOutletNavigation) {
8286
- await scriptNotInOutletTarget(doc, target, src, transaction.controller.signal);
8417
+ await scriptNotInOutletTarget(doc, target, src, transaction.controller.signal, currentBaseUrl);
8287
8418
  assertActiveNavigation(transaction);
8288
8419
  }
8289
8420
  }
@@ -8317,14 +8448,15 @@
8317
8448
  await performUpdate();
8318
8449
  }
8319
8450
  assertActiveNavigation(transaction);
8320
- if (removeTriggerAfterCommit && opts.trigger instanceof HTMLElement && opts.trigger.isConnected) {
8451
+ if (removeTriggerAfterCommit && context.outcome !== 'http-error' && opts.trigger instanceof HTMLElement && opts.trigger.isConnected) {
8321
8452
  disposeEffects(opts.trigger);
8322
8453
  opts.trigger.remove();
8323
8454
  }
8324
8455
  if (hasTargetSpinner)
8325
8456
  hideTargetSpinner(transaction.spinner);
8326
8457
  transaction.spinner = null;
8327
- runNavigationHooks(afterNavigate, targetUrl);
8458
+ context.outcome ?? (context.outcome = 'success');
8459
+ runNavigationHooks(afterNavigate, targetUrl, context);
8328
8460
  log('[GyosRouter] navigated to', targetUrl);
8329
8461
  currentUrl = changesState
8330
8462
  ? canonicalUrl(targetUrl, true)
@@ -8340,11 +8472,15 @@
8340
8472
  return;
8341
8473
  }
8342
8474
  if (isActiveNavigation(transaction)) {
8475
+ context.outcome ?? (context.outcome = 'error');
8343
8476
  console.error('[GyosRouter] navigation error', error);
8344
- fallbackFromBoost(opts, opts.url, true);
8477
+ fallback(opts.url, true);
8345
8478
  }
8346
8479
  }
8347
8480
  finally {
8481
+ if (transaction.controller.signal.aborted)
8482
+ context.outcome = 'aborted';
8483
+ context.outcome ?? (context.outcome = 'aborted');
8348
8484
  if (transaction.interval)
8349
8485
  clearInterval(transaction.interval);
8350
8486
  if (transaction.spinner)
@@ -8354,6 +8490,15 @@
8354
8490
  progressBar?.complete();
8355
8491
  }
8356
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
+ }
8357
8502
  }
8358
8503
  }
8359
8504
  function shouldBoost(el) {
@@ -8462,16 +8607,34 @@
8462
8607
  return;
8463
8608
  if (shouldDeferToFormValidation(form))
8464
8609
  return;
8465
- event.preventDefault();
8466
- const action = form.action || window.location.href;
8467
- const method = (form.method || 'GET').toUpperCase();
8468
- const url = new URL(action, window.location.href);
8469
- if (url.origin !== window.location.origin) {
8470
- 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 {
8471
8628
  return;
8472
8629
  }
8473
- const formData = new FormData(form);
8474
- 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' });
8475
8638
  }
8476
8639
  function onPopState(event) {
8477
8640
  const url = window.location.href;
@@ -8576,10 +8739,12 @@
8576
8739
  startRouter,
8577
8740
  onBeforeNavigate,
8578
8741
  onAfterNavigate,
8742
+ onBeforeSwap,
8743
+ onNavigationEnd,
8579
8744
  portalCreate,
8580
8745
  portalDestroy,
8581
8746
  setCspNonce,
8582
- version: '0.3.2'
8747
+ version: '0.4.0'
8583
8748
  };
8584
8749
 
8585
8750
  setExpressionRuntime(standardExpressionRuntime);
@@ -8615,6 +8780,8 @@
8615
8780
  exports.on = on;
8616
8781
  exports.onAfterNavigate = onAfterNavigate;
8617
8782
  exports.onBeforeNavigate = onBeforeNavigate;
8783
+ exports.onBeforeSwap = onBeforeSwap;
8784
+ exports.onNavigationEnd = onNavigationEnd;
8618
8785
  exports.once = once;
8619
8786
  exports.pipe = pipe;
8620
8787
  exports.portalCreate = portalCreate;