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.auto.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
  */
@@ -2202,59 +2202,59 @@
2202
2202
  return;
2203
2203
  const style = document.createElement('style');
2204
2204
  style.id = styleId;
2205
- style.textContent = `
2206
- /* Opacity utilities */
2205
+ style.textContent = `
2206
+ /* Opacity utilities */
2207
2207
  .gyos-t-opacity-0 { opacity: 0; }
2208
2208
  .gyos-t-opacity-100 { opacity: 1; }
2209
-
2210
- /* Transform - Translate Y */
2209
+
2210
+ /* Transform - Translate Y */
2211
2211
  .gyos-t-translate-y-0 { transform: translateY(0); }
2212
2212
  .gyos-t-translate-y--100 { transform: translateY(-100%); }
2213
2213
  .gyos-t-translate-y-100 { transform: translateY(100%); }
2214
-
2215
- /* Transform - Translate X */
2214
+
2215
+ /* Transform - Translate X */
2216
2216
  .gyos-t-translate-x-0 { transform: translateX(0); }
2217
2217
  .gyos-t-translate-x--100 { transform: translateX(-100%); }
2218
2218
  .gyos-t-translate-x-100 { transform: translateX(100%); }
2219
-
2220
- /* Transform - Scale */
2219
+
2220
+ /* Transform - Scale */
2221
2221
  .gyos-t-scale-0 { transform: scale(0); }
2222
2222
  .gyos-t-scale-50 { transform: scale(0.5); }
2223
2223
  .gyos-t-scale-100 { transform: scale(1); }
2224
-
2225
- /* Animation Keyframes */
2226
- @keyframes gyos-fade-in {
2227
- from { opacity: 0; }
2228
- to { opacity: 1; }
2229
- }
2230
-
2231
- @keyframes gyos-fade-out {
2232
- from { opacity: 1; }
2233
- to { opacity: 0; }
2234
- }
2235
-
2236
- @keyframes gyos-slide-down {
2237
- from { transform: translateY(-100%); opacity: 0; }
2238
- to { transform: translateY(0); opacity: 1; }
2239
- }
2240
-
2241
- @keyframes gyos-slide-up {
2242
- from { transform: translateY(100%); opacity: 0; }
2243
- to { transform: translateY(0); opacity: 1; }
2244
- }
2245
-
2246
- @keyframes gyos-scale-in {
2247
- from { transform: scale(0); opacity: 0; }
2248
- to { transform: scale(1); opacity: 1; }
2249
- }
2250
-
2251
- @keyframes gyos-scale-out {
2252
- from { transform: scale(1); opacity: 1; }
2253
- to { transform: scale(0); opacity: 0; }
2254
- }
2255
-
2256
- [g-cloak] {
2257
- display: none !important;
2224
+
2225
+ /* Animation Keyframes */
2226
+ @keyframes gyos-fade-in {
2227
+ from { opacity: 0; }
2228
+ to { opacity: 1; }
2229
+ }
2230
+
2231
+ @keyframes gyos-fade-out {
2232
+ from { opacity: 1; }
2233
+ to { opacity: 0; }
2234
+ }
2235
+
2236
+ @keyframes gyos-slide-down {
2237
+ from { transform: translateY(-100%); opacity: 0; }
2238
+ to { transform: translateY(0); opacity: 1; }
2239
+ }
2240
+
2241
+ @keyframes gyos-slide-up {
2242
+ from { transform: translateY(100%); opacity: 0; }
2243
+ to { transform: translateY(0); opacity: 1; }
2244
+ }
2245
+
2246
+ @keyframes gyos-scale-in {
2247
+ from { transform: scale(0); opacity: 0; }
2248
+ to { transform: scale(1); opacity: 1; }
2249
+ }
2250
+
2251
+ @keyframes gyos-scale-out {
2252
+ from { transform: scale(1); opacity: 1; }
2253
+ to { transform: scale(0); opacity: 0; }
2254
+ }
2255
+
2256
+ [g-cloak] {
2257
+ display: none !important;
2258
2258
  }`;
2259
2259
  document.head.appendChild(style);
2260
2260
  }
@@ -6611,33 +6611,44 @@
6611
6611
  getCurrentProgress() {
6612
6612
  return this.currentProgress;
6613
6613
  }
6614
+ reconnect() {
6615
+ if (!this.element || !this.progressBarEnabled || !document.body)
6616
+ return;
6617
+ // Snapshots may contain a clone of the runtime bar. Keep this instance.
6618
+ document.querySelectorAll('#gyos-progress-bar').forEach(node => {
6619
+ if (node !== this.element)
6620
+ node.remove();
6621
+ });
6622
+ if (!this.element.isConnected)
6623
+ document.body.appendChild(this.element);
6624
+ }
6614
6625
  createBar() {
6615
6626
  if (typeof document === 'undefined')
6616
6627
  return;
6617
6628
  // Create progress bar element
6618
6629
  this.element = document.createElement('div');
6619
6630
  this.element.id = 'gyos-progress-bar';
6620
- this.element.style.cssText = `
6621
- position: fixed;
6622
- top: 0;
6623
- left: 0;
6624
- width: 0%;
6625
- height: 6px;
6626
- background: var(--gyos-progress-color, linear-gradient(90deg, #aab9ff, #77889f));
6627
- z-index: 999999;
6628
- transition: width 0.3s linear, opacity 0.3s linear;
6629
- opacity: 0;
6630
- pointer-events: none;
6631
- box-shadow: 0 0 10px rgba(102, 126, 234, 0.5);
6631
+ this.element.style.cssText = `
6632
+ position: fixed;
6633
+ top: 0;
6634
+ left: 0;
6635
+ width: 0%;
6636
+ height: 6px;
6637
+ background: var(--gyos-progress-color, linear-gradient(90deg, #aab9ff, #77889f));
6638
+ z-index: 999999;
6639
+ transition: width 0.3s linear, opacity 0.3s linear;
6640
+ opacity: 0;
6641
+ pointer-events: none;
6642
+ box-shadow: 0 0 10px rgba(102, 126, 234, 0.5);
6632
6643
  `;
6633
6644
  // Insert into DOM when ready
6634
6645
  if (document.readyState === 'loading') {
6635
6646
  document.addEventListener('DOMContentLoaded', () => {
6636
- document.body.insertAdjacentElement('beforeend', this.element);
6637
- });
6647
+ this.reconnect();
6648
+ }, { once: true });
6638
6649
  }
6639
6650
  else {
6640
- document.body.insertAdjacentElement('beforeend', this.element);
6651
+ this.reconnect();
6641
6652
  }
6642
6653
  }
6643
6654
  start() {
@@ -6661,6 +6672,7 @@
6661
6672
  setProgress(percent) {
6662
6673
  if (!this.element || !this.progressBarEnabled)
6663
6674
  return;
6675
+ this.reconnect();
6664
6676
  // Clamp between 0-100
6665
6677
  percent = Math.min(100, Math.max(0, percent));
6666
6678
  this.currentProgress = percent;
@@ -6709,41 +6721,41 @@
6709
6721
  function createTargetSpinner() {
6710
6722
  const spinner = document.createElement('div');
6711
6723
  spinner.className = 'gyos-target-spinner';
6712
- spinner.innerHTML = `
6713
- <div class="gyos-spinner-content">
6714
- <svg class="gyos-spinner-icon" viewBox="0 0 50 50">
6715
- <circle cx="25" cy="25" r="20" fill="none" stroke="currentColor" stroke-width="4" stroke-dasharray="31.4 31.4" />
6716
- </svg>
6717
- </div>
6724
+ spinner.innerHTML = `
6725
+ <div class="gyos-spinner-content">
6726
+ <svg class="gyos-spinner-icon" viewBox="0 0 50 50">
6727
+ <circle cx="25" cy="25" r="20" fill="none" stroke="currentColor" stroke-width="4" stroke-dasharray="31.4 31.4" />
6728
+ </svg>
6729
+ </div>
6718
6730
  `;
6719
6731
  // Inject styles if not already present
6720
6732
  if (expressionRuntimeMode() === 'standard' && !document.getElementById('gyos-target-spinner-styles')) {
6721
6733
  const style = document.createElement('style');
6722
6734
  style.id = 'gyos-target-spinner-styles';
6723
- style.textContent = `
6724
- .gyos-target-spinner {
6725
- display: flex;
6726
- align-items: center;
6727
- justify-content: center;
6728
- padding: 20px;
6729
- min-height: 60px;
6730
- }
6731
- .gyos-spinner-content {
6732
- display: flex;
6733
- align-items: center;
6734
- gap: 10px;
6735
- color: var(--gyos-spinner-color, #667eea);
6736
- font-size: 14px;
6737
- }
6738
- .gyos-spinner-icon {
6739
- width: 24px;
6740
- height: 24px;
6741
- animation: gyos-spin 1s linear infinite;
6742
- }
6743
- @keyframes gyos-spin {
6744
- 0% { transform: rotate(0deg); }
6745
- 100% { transform: rotate(360deg); }
6746
- }
6735
+ style.textContent = `
6736
+ .gyos-target-spinner {
6737
+ display: flex;
6738
+ align-items: center;
6739
+ justify-content: center;
6740
+ padding: 20px;
6741
+ min-height: 60px;
6742
+ }
6743
+ .gyos-spinner-content {
6744
+ display: flex;
6745
+ align-items: center;
6746
+ gap: 10px;
6747
+ color: var(--gyos-spinner-color, #667eea);
6748
+ font-size: 14px;
6749
+ }
6750
+ .gyos-spinner-icon {
6751
+ width: 24px;
6752
+ height: 24px;
6753
+ animation: gyos-spin 1s linear infinite;
6754
+ }
6755
+ @keyframes gyos-spin {
6756
+ 0% { transform: rotate(0deg); }
6757
+ 100% { transform: rotate(360deg); }
6758
+ }
6747
6759
  `;
6748
6760
  document.head.appendChild(style);
6749
6761
  }
@@ -7103,8 +7115,8 @@
7103
7115
  }
7104
7116
  result = target;
7105
7117
  }
7106
- await options.beforeScripts?.();
7107
7118
  options.onCommitted?.(result, normalized === 'append' || normalized === 'prepend' ? incomingChildren : [result]);
7119
+ await options.beforeScripts?.();
7108
7120
  // Additive swaps must not re-run scripts that already existed in the target.
7109
7121
  if (normalized === 'append' || normalized === 'prepend') {
7110
7122
  await executeScriptsInNodes(incomingChildren, options.signal);
@@ -7344,6 +7356,21 @@
7344
7356
  window.scrollTo({ top: 0, behavior: 'smooth' });
7345
7357
  }
7346
7358
 
7359
+ // A retained relative URL still identifies the resource loaded on its original
7360
+ // page, even after pushState changes document.baseURI.
7361
+ const resourceUrls = new WeakMap();
7362
+ function rememberResourceUrls(root, baseUrl) {
7363
+ root.querySelectorAll('script[src], link[href]').forEach(node => {
7364
+ const attribute = node.tagName === 'SCRIPT' ? 'src' : 'href';
7365
+ const source = node.getAttribute(attribute);
7366
+ if (resourceUrls.get(node)?.source === source)
7367
+ return;
7368
+ try {
7369
+ resourceUrls.set(node, { source, url: new URL(source, baseUrl).href });
7370
+ }
7371
+ catch { /* Invalid resource URLs retain their literal identity. */ }
7372
+ });
7373
+ }
7347
7374
  function isNonceMeta(el) {
7348
7375
  return el.tagName === 'META' && el.getAttribute('name')?.toLowerCase() === 'csp-nonce';
7349
7376
  }
@@ -7361,7 +7388,20 @@
7361
7388
  return;
7362
7389
  if (context.csp && isNonceMeta(el) && attr.name.toLowerCase() === 'content')
7363
7390
  return;
7364
- attributes.set(attr.name, attr.value);
7391
+ let value = attr.value;
7392
+ if ((el.tagName === 'SCRIPT' && attr.name === 'src') || (el.tagName === 'LINK' && attr.name === 'href')) {
7393
+ const cached = resourceUrls.get(el);
7394
+ if (cached?.source === value)
7395
+ value = cached.url;
7396
+ else {
7397
+ try {
7398
+ value = new URL(value, context.baseUrl || el.baseURI).href;
7399
+ resourceUrls.set(el, { source: attr.value, url: value });
7400
+ }
7401
+ catch { /* Keep invalid URLs distinct. */ }
7402
+ }
7403
+ }
7404
+ attributes.set(attr.name, value);
7365
7405
  });
7366
7406
  if (context.csp && usesCspNonce(el) && context.activeNonce) {
7367
7407
  attributes.set('nonce', context.activeNonce);
@@ -7428,19 +7468,21 @@
7428
7468
  console.warn('[GyosJS CSP] Skipped an inline MPA script because no active document nonce is configured.');
7429
7469
  }
7430
7470
  }
7431
- async function diffNodes(currentNodes, nextNodes, container = document.head, signal) {
7471
+ async function diffNodes(currentNodes, nextNodes, container = document.head, signal, currentBaseUrl = document.baseURI) {
7432
7472
  const csp = expressionRuntimeMode() === 'csp';
7433
7473
  const context = {
7434
7474
  csp,
7435
7475
  activeNonce: csp ? resolveCspNonce() : undefined
7436
7476
  };
7437
- const current = keyedNodes(currentNodes, context);
7477
+ const current = keyedNodes(currentNodes, { ...context, baseUrl: currentBaseUrl });
7438
7478
  const next = keyedNodes(nextNodes, context);
7479
+ const persistentKey = (node) => container === document.head ? node.getAttribute('g-head-persist') : null;
7480
+ const persistent = new Set(currentNodes.map(persistentKey).filter(Boolean));
7439
7481
  const currentKeys = new Set(current.map(item => item.key));
7440
7482
  const nextKeys = new Set(next.map(item => item.key));
7441
7483
  // Remove nodes that are not in the new head
7442
7484
  current.forEach(({ key, node }) => {
7443
- if (!nextKeys.has(key)) {
7485
+ if (!nextKeys.has(key) && !persistentKey(node)) {
7444
7486
  node.remove();
7445
7487
  }
7446
7488
  });
@@ -7448,6 +7490,8 @@
7448
7490
  for (const { key, node } of next) {
7449
7491
  if (signal?.aborted)
7450
7492
  return;
7493
+ if (persistent.has(persistentKey(node)))
7494
+ continue;
7451
7495
  if (!currentKeys.has(key)) {
7452
7496
  if (!canInsertNode(node, context)) {
7453
7497
  warnSkippedNode(node);
@@ -7650,6 +7694,7 @@
7650
7694
  * MPA boost navigation inspired by Turbo Drive.
7651
7695
  * Implements attribute-driven routing, snapshot caching, and persistent islands.
7652
7696
  */
7697
+ const submittingForms = new WeakSet();
7653
7698
  const snapshots = new Map();
7654
7699
  const preloadCache = new Map();
7655
7700
  const preloadControllers = new Map();
@@ -7666,12 +7711,30 @@
7666
7711
  let progressBar = null;
7667
7712
  const beforeNavigate = [];
7668
7713
  const afterNavigate = [];
7714
+ const beforeSwap = [];
7715
+ const navigationEnd = [];
7716
+ function registerNavigationHook(hooks, callback) {
7717
+ // A wrapper gives each registration its own unsubscribe identity.
7718
+ const entry = (url, context) => callback(url, context);
7719
+ hooks.push(entry);
7720
+ return () => {
7721
+ const index = hooks.indexOf(entry);
7722
+ if (index !== -1)
7723
+ hooks.splice(index, 1);
7724
+ };
7725
+ }
7669
7726
  // Expose hooks to register before/after navigation callbacks
7670
7727
  function onBeforeNavigate(callback) {
7671
- beforeNavigate.push(callback);
7728
+ return registerNavigationHook(beforeNavigate, callback);
7672
7729
  }
7673
7730
  function onAfterNavigate(callback) {
7674
- afterNavigate.push(callback);
7731
+ return registerNavigationHook(afterNavigate, callback);
7732
+ }
7733
+ function onBeforeSwap(callback) {
7734
+ return registerNavigationHook(beforeSwap, callback);
7735
+ }
7736
+ function onNavigationEnd(callback) {
7737
+ return registerNavigationHook(navigationEnd, (_url, context) => callback(context));
7675
7738
  }
7676
7739
  function startRouter(options) {
7677
7740
  // If not has g-boost attribute, do not start router
@@ -7695,6 +7758,7 @@
7695
7758
  }
7696
7759
  // Cache scripts from initial page to prevent re-execution on first navigation back
7697
7760
  cacheInitialPageScripts();
7761
+ rememberResourceUrls(document, document.baseURI);
7698
7762
  routerStarted = true;
7699
7763
  log('[GyosRouter] started');
7700
7764
  }
@@ -7751,9 +7815,13 @@
7751
7815
  const outlet = findGlobalOutlet();
7752
7816
  return outlet instanceof HTMLElement ? outlet : null;
7753
7817
  }
7818
+ function isFullDocument(html) {
7819
+ return /^\s*(?:<!--[^]*?-->\s*)*(?:<!doctype\s+html\b|<html(?:\s|>))/i.test(html);
7820
+ }
7754
7821
  function saveSnapshot(url, html) {
7755
7822
  // create HTMLElement by html string to remove scripts and get clean snapshot
7756
7823
  const doc = parseNavigationDocument(html);
7824
+ doc.querySelectorAll('#gyos-progress-bar').forEach(node => node.remove());
7757
7825
  // Ignore hash for snapshot keys
7758
7826
  if (url.includes('#'))
7759
7827
  url = url.split('#')[0];
@@ -7762,7 +7830,7 @@
7762
7830
  if (s.hasAttribute('g-script-once'))
7763
7831
  s.textContent = '';
7764
7832
  });
7765
- snapshots.set(url, { html: doc.documentElement.outerHTML });
7833
+ snapshots.set(url, { html: doc.documentElement.outerHTML, fullDocument: isFullDocument(html) });
7766
7834
  log('[GyosRouter] snapshot saved for', url);
7767
7835
  }
7768
7836
  function getOutletIndex(root, target) {
@@ -7874,10 +7942,10 @@
7874
7942
  // update callback remains the navigation source of truth and is awaited below.
7875
7943
  void promise?.catch(() => undefined);
7876
7944
  }
7877
- function runNavigationHooks(callbacks, url) {
7878
- callbacks.forEach(callback => {
7945
+ function runNavigationHooks(callbacks, url, context) {
7946
+ [...callbacks].forEach(callback => {
7879
7947
  try {
7880
- callback(url);
7948
+ callback(url, { ...context });
7881
7949
  }
7882
7950
  catch (error) {
7883
7951
  console.error('[GyosRouter] navigation hook error', error);
@@ -7915,7 +7983,13 @@
7915
7983
  url = mergeFormDataIntoUrl(url, opts.formData);
7916
7984
  }
7917
7985
  else {
7918
- init.body = opts.formData;
7986
+ if (opts.formEncoding === 'application/x-www-form-urlencoded') {
7987
+ const encoded = new URLSearchParams();
7988
+ opts.formData.forEach((value, name) => encoded.append(name, typeof value === 'string' ? value : value.name));
7989
+ init.body = encoded;
7990
+ }
7991
+ else
7992
+ init.body = opts.formData;
7919
7993
  }
7920
7994
  }
7921
7995
  else if (opts.jsonData) {
@@ -7958,25 +8032,26 @@
7958
8032
  preloadControllers.delete(cacheKey);
7959
8033
  });
7960
8034
  }
7961
- async function updateHead(fromDoc, signal) {
8035
+ async function updateHead(fromDoc, signal, currentBaseUrl) {
7962
8036
  const allowedSelector = 'meta, link, style:not(#gyos-transitions), script';
7963
8037
  const currentNodes = Array.from(document.head.querySelectorAll(allowedSelector));
7964
8038
  const nextNodes = Array.from(fromDoc.head.querySelectorAll(allowedSelector));
7965
- await diffNodes(currentNodes, nextNodes, document.head, signal);
8039
+ await diffNodes(currentNodes, nextNodes, document.head, signal, currentBaseUrl);
7966
8040
  }
7967
- async function scriptNotInOutletTarget(fromDoc, target, source, signal) {
8041
+ async function scriptNotInOutletTarget(fromDoc, target, source, signal, currentBaseUrl) {
7968
8042
  // scripts in current document and it not in target outlet
7969
8043
  const currentScripts = Array.from(document.scripts).filter(s => !target.contains(s) && !document.head.contains(s));
7970
8044
  // scripts in fromDoc and it not in source outlet
7971
8045
  const incomingScripts = Array.from(fromDoc.scripts).filter(s => !source.contains(s) && !fromDoc.head.contains(s));
7972
8046
  // Diff and update scripts not in outlet/target
7973
- await diffNodes(currentScripts, incomingScripts, document.body, signal);
8047
+ await diffNodes(currentScripts, incomingScripts, document.body, signal, currentBaseUrl);
7974
8048
  }
7975
8049
  function resolveIncomingScriptUrls(root, baseUrl) {
7976
- root.querySelectorAll('script[src]').forEach(script => {
7977
- const source = script.getAttribute('src');
8050
+ root.querySelectorAll('script[src], link[href]').forEach(node => {
8051
+ const attribute = node.tagName === 'SCRIPT' ? 'src' : 'href';
8052
+ const source = node.getAttribute(attribute);
7978
8053
  if (source)
7979
- script.src = new URL(source, baseUrl).href;
8054
+ node.setAttribute(attribute, new URL(source, baseUrl).href);
7980
8055
  });
7981
8056
  }
7982
8057
  function isNavigableHtmlResponse(response) {
@@ -8030,6 +8105,22 @@
8030
8105
  resolveDone
8031
8106
  };
8032
8107
  activeNavigation = transaction;
8108
+ const currentBaseUrl = document.baseURI;
8109
+ rememberResourceUrls(document, currentBaseUrl);
8110
+ const context = {
8111
+ from: currentUrl, url: opts.url, method: opts.method.toUpperCase(),
8112
+ trigger: opts.trigger || null, target: null, form: opts.form || null,
8113
+ popstate: opts.popstate === true, signal: transaction.controller.signal,
8114
+ status: null, committed: false, fallback: false, outcome: null
8115
+ };
8116
+ const formEvent = opts.form
8117
+ ? { form: opts.form, url: opts.url, status: null, outcome: null, committed: false, fallback: false }
8118
+ : null;
8119
+ const fallback = (url, requestSent) => {
8120
+ context.fallback = context.method === 'GET' || (!requestSent && !!opts.form);
8121
+ context.outcome ?? (context.outcome = context.fallback ? 'fallback' : 'invalid-response');
8122
+ fallbackFromBoost(opts, url, requestSent);
8123
+ };
8033
8124
  const hasTargetSpinner = opts.trigger?.hasAttribute('g-router-spin');
8034
8125
  const setRand = () => {
8035
8126
  if (isActiveNavigation(transaction) && progressBar?.getCurrentProgress() < 70) {
@@ -8037,7 +8128,10 @@
8037
8128
  }
8038
8129
  };
8039
8130
  try {
8040
- runNavigationHooks(beforeNavigate, opts.url);
8131
+ if (formEvent)
8132
+ document.dispatchEvent(new CustomEvent('gyos:form-start', { detail: { ...formEvent } }));
8133
+ runNavigationHooks(beforeNavigate, opts.url, context);
8134
+ assertActiveNavigation(transaction);
8041
8135
  progressBar?.start();
8042
8136
  // popstate already points history at the destination entry. Keep the visible
8043
8137
  // page's position under currentUrl without overwriting that destination state.
@@ -8046,9 +8140,10 @@
8046
8140
  saveScrollPosition();
8047
8141
  // Pick target element to swap
8048
8142
  let target = resolveTarget(opts.trigger, opts.targetSelector, opts.targetOutletIndex);
8143
+ context.target = target;
8049
8144
  if (!target) {
8050
8145
  if (isActiveNavigation(transaction))
8051
- fallbackFromBoost(opts, opts.url, false);
8146
+ fallback(opts.url, false);
8052
8147
  return;
8053
8148
  }
8054
8149
  const swapMode = (opts.swapMode || opts.trigger?.getAttribute('g-swap') || 'inner').toLowerCase();
@@ -8073,6 +8168,7 @@
8073
8168
  if (hasTargetSpinner)
8074
8169
  transaction.spinner = showTargetSpinner(target, swapMode);
8075
8170
  const { finalUrl, init } = buildRequest(opts);
8171
+ context.url = finalUrl;
8076
8172
  // Add abort signal to request
8077
8173
  init.signal = transaction.controller.signal;
8078
8174
  let html;
@@ -8100,7 +8196,8 @@
8100
8196
  if (error.name === 'AbortError')
8101
8197
  throw error;
8102
8198
  assertActiveNavigation(transaction);
8103
- window.location.href = finalUrl;
8199
+ context.outcome = 'network-error';
8200
+ fallback(finalUrl, true);
8104
8201
  return;
8105
8202
  }
8106
8203
  preloadCache.delete(preloadKey); // consume cache
@@ -8125,28 +8222,46 @@
8125
8222
  log('[GyosRouter] Navigation cancelled');
8126
8223
  return;
8127
8224
  }
8225
+ context.outcome = 'network-error';
8128
8226
  if (isActiveNavigation(transaction))
8129
- fallbackFromBoost(opts, finalUrl, true);
8227
+ fallback(finalUrl, true);
8130
8228
  return;
8131
8229
  }
8132
8230
  }
8133
8231
  assertActiveNavigation(transaction);
8134
- // If response not ok, fallback to full navigation
8135
- if (!response || !response.ok || !isNavigableHtmlResponse(response)) {
8232
+ context.status = response?.status ?? null;
8233
+ context.url = response?.url || finalUrl;
8234
+ const acceptedErrors = (opts.trigger?.getAttribute('g-boost-errors') || '').split(/[\s,]+/);
8235
+ const renderHttpError = !!response && response.status >= 400 && response.status <= 599
8236
+ && acceptedErrors.includes(String(response.status));
8237
+ if (response && !response.ok)
8238
+ context.outcome = 'http-error';
8239
+ if (!response || (!response.ok && !renderHttpError) || !isNavigableHtmlResponse(response)) {
8240
+ context.outcome ?? (context.outcome = 'invalid-response');
8136
8241
  if (isActiveNavigation(transaction))
8137
- fallbackFromBoost(opts, finalUrl, true);
8242
+ fallback(finalUrl, true);
8138
8243
  return;
8139
8244
  }
8140
8245
  html = await response.text();
8141
8246
  assertActiveNavigation(transaction);
8142
- if (!opts.popstate && target.hasAttribute('g-snapshot')) {
8143
- saveSnapshot(canonicalUrl(response.url || finalUrl), html);
8144
- }
8145
8247
  }
8146
8248
  // Parse HTML
8147
8249
  const doc = html
8148
8250
  ? parseNavigationDocument(html)
8149
8251
  : document.implementation.createHTMLDocument();
8252
+ // Detached parsing cannot tell whether the live CSP permits an incoming base.
8253
+ // Let native navigation enforce base-uri instead of authorizing its URLs ourselves.
8254
+ if (doc.querySelector('base[href]') || opts.historyFragment?.querySelector('base[href]')) {
8255
+ context.outcome = 'invalid-response';
8256
+ fallback(response?.url || finalUrl, true);
8257
+ return;
8258
+ }
8259
+ if (response?.ok && !opts.popstate && target.hasAttribute('g-snapshot')) {
8260
+ saveSnapshot(canonicalUrl(response.url || finalUrl), html);
8261
+ }
8262
+ const syncDocumentAttributes = isFullOutletNavigation && destructiveSwap && !currentHead
8263
+ && !opts.historyFragment && (opts.popstate && snapshots.has(urlWithoutHash)
8264
+ ? snapshots.get(urlWithoutHash).fullDocument : isFullDocument(html || ''));
8150
8265
  // Pick source fragment
8151
8266
  const src = opts.historyFragment || pickSourceFragment(doc, target, targetOutletIndex);
8152
8267
  stripInertFallbackContent(src);
@@ -8158,15 +8273,18 @@
8158
8273
  targetUrl += finalUrl.substring(finalUrl.indexOf('#'));
8159
8274
  }
8160
8275
  resolveIncomingScriptUrls(doc, targetUrl);
8276
+ context.url = targetUrl;
8161
8277
  if (opts.historyFragment)
8162
8278
  resolveIncomingScriptUrls(src, targetUrl);
8163
8279
  const triggerChangesState = opts.trigger?.hasAttribute('g-change-state') || false;
8164
8280
  const keepsCurrentState = opts.trigger?.hasAttribute('g-current-state') || false;
8165
8281
  const redirectedSubmission = opts.method.toUpperCase() !== 'GET' && response?.redirected === true;
8166
- const changesState = !keepsCurrentState && (opts.changeState === true || triggerChangesState || redirectedSubmission);
8282
+ const changesState = context.outcome !== 'http-error' && !keepsCurrentState && (opts.changeState === true || triggerChangesState || redirectedSubmission);
8167
8283
  const performUpdate = async () => {
8168
8284
  assertActiveNavigation(transaction);
8169
8285
  transaction.committing = true;
8286
+ runNavigationHooks(beforeSwap, targetUrl, context);
8287
+ assertActiveNavigation(transaction);
8170
8288
  // Update progress to rand 80 - 90% before swap
8171
8289
  progressBar?.setProgress(Math.random() * 10 + 80);
8172
8290
  const outgoingHistoryFragment = changesState && !opts.replace && !isFullOutletNavigation
@@ -8237,21 +8355,34 @@
8237
8355
  beforeScripts: async () => {
8238
8356
  if (!isFullOutletNavigation || currentHead)
8239
8357
  return;
8358
+ if (syncDocumentAttributes) {
8359
+ for (const name of ['lang', 'dir']) {
8360
+ const value = doc.documentElement.getAttribute(name);
8361
+ if (value === null)
8362
+ document.documentElement.removeAttribute(name);
8363
+ else
8364
+ document.documentElement.setAttribute(name, value);
8365
+ }
8366
+ }
8240
8367
  const incomingTitle = doc.querySelector('title');
8241
8368
  if (incomingTitle) {
8242
8369
  document.title = incomingTitle.textContent || document.title;
8243
8370
  }
8244
- await updateHead(doc, transaction.controller.signal);
8371
+ await updateHead(doc, transaction.controller.signal, currentBaseUrl);
8245
8372
  assertActiveNavigation(transaction);
8246
8373
  },
8247
8374
  onCommitted: (committedTarget, roots) => {
8248
8375
  target = committedTarget;
8376
+ context.target = committedTarget;
8377
+ context.committed = true;
8378
+ progressBar?.reconnect();
8249
8379
  committedRoots = roots;
8250
8380
  }
8251
8381
  });
8382
+ context.committed = true;
8252
8383
  assertActiveNavigation(transaction);
8253
8384
  if (isFullOutletNavigation) {
8254
- await scriptNotInOutletTarget(doc, target, src, transaction.controller.signal);
8385
+ await scriptNotInOutletTarget(doc, target, src, transaction.controller.signal, currentBaseUrl);
8255
8386
  assertActiveNavigation(transaction);
8256
8387
  }
8257
8388
  }
@@ -8285,14 +8416,15 @@
8285
8416
  await performUpdate();
8286
8417
  }
8287
8418
  assertActiveNavigation(transaction);
8288
- if (removeTriggerAfterCommit && opts.trigger instanceof HTMLElement && opts.trigger.isConnected) {
8419
+ if (removeTriggerAfterCommit && context.outcome !== 'http-error' && opts.trigger instanceof HTMLElement && opts.trigger.isConnected) {
8289
8420
  disposeEffects(opts.trigger);
8290
8421
  opts.trigger.remove();
8291
8422
  }
8292
8423
  if (hasTargetSpinner)
8293
8424
  hideTargetSpinner(transaction.spinner);
8294
8425
  transaction.spinner = null;
8295
- runNavigationHooks(afterNavigate, targetUrl);
8426
+ context.outcome ?? (context.outcome = 'success');
8427
+ runNavigationHooks(afterNavigate, targetUrl, context);
8296
8428
  log('[GyosRouter] navigated to', targetUrl);
8297
8429
  currentUrl = changesState
8298
8430
  ? canonicalUrl(targetUrl, true)
@@ -8308,11 +8440,15 @@
8308
8440
  return;
8309
8441
  }
8310
8442
  if (isActiveNavigation(transaction)) {
8443
+ context.outcome ?? (context.outcome = 'error');
8311
8444
  console.error('[GyosRouter] navigation error', error);
8312
- fallbackFromBoost(opts, opts.url, true);
8445
+ fallback(opts.url, true);
8313
8446
  }
8314
8447
  }
8315
8448
  finally {
8449
+ if (transaction.controller.signal.aborted)
8450
+ context.outcome = 'aborted';
8451
+ context.outcome ?? (context.outcome = 'aborted');
8316
8452
  if (transaction.interval)
8317
8453
  clearInterval(transaction.interval);
8318
8454
  if (transaction.spinner)
@@ -8322,6 +8458,15 @@
8322
8458
  progressBar?.complete();
8323
8459
  }
8324
8460
  transaction.resolveDone();
8461
+ if (formEvent)
8462
+ submittingForms.delete(formEvent.form);
8463
+ runNavigationHooks(navigationEnd, context.url, context);
8464
+ if (formEvent) {
8465
+ const { url, status, outcome, committed, fallback } = context;
8466
+ document.dispatchEvent(new CustomEvent('gyos:form-end', {
8467
+ detail: { ...formEvent, url, status, outcome, committed, fallback }
8468
+ }));
8469
+ }
8325
8470
  }
8326
8471
  }
8327
8472
  function shouldBoost(el) {
@@ -8430,16 +8575,34 @@
8430
8575
  return;
8431
8576
  if (shouldDeferToFormValidation(form))
8432
8577
  return;
8433
- event.preventDefault();
8434
- const action = form.action || window.location.href;
8435
- const method = (form.method || 'GET').toUpperCase();
8436
- const url = new URL(action, window.location.href);
8437
- if (url.origin !== window.location.origin) {
8438
- window.location.href = url.toString();
8578
+ const submitter = event.submitter;
8579
+ const override = (name) => submitter?.getAttribute(`form${name}`) ?? form.getAttribute(name);
8580
+ const target = override('target') ?? document.querySelector('base[target]')?.getAttribute('target');
8581
+ const declaredMethod = (override('method') || 'GET').toUpperCase();
8582
+ const method = ['GET', 'POST', 'DIALOG'].includes(declaredMethod) ? declaredMethod : 'GET';
8583
+ const formEncoding = override('enctype')?.toLowerCase();
8584
+ if ((target && target.toLowerCase() !== '_self') || method === 'DIALOG' || formEncoding === 'text/plain')
8585
+ return;
8586
+ if (!resolveTarget(form))
8587
+ return;
8588
+ // Image submitters carry click coordinates which SubmitEvent does not expose.
8589
+ if (submitter instanceof HTMLInputElement && submitter.type === 'image')
8590
+ return;
8591
+ let url;
8592
+ try {
8593
+ url = new URL(override('action') || window.location.href, document.baseURI);
8594
+ }
8595
+ catch {
8439
8596
  return;
8440
8597
  }
8441
- const formData = new FormData(form);
8442
- navigate({ url: url.toString(), method, trigger: form, form, formData, changeState: method === 'GET' });
8598
+ if (url.origin !== window.location.origin)
8599
+ return;
8600
+ event.preventDefault();
8601
+ if (submittingForms.has(form))
8602
+ return;
8603
+ const formData = new FormData(form, submitter);
8604
+ submittingForms.add(form);
8605
+ void navigate({ url: url.toString(), method, trigger: form, form, formData, formEncoding, changeState: method === 'GET' });
8443
8606
  }
8444
8607
  function onPopState(event) {
8445
8608
  const url = window.location.href;
@@ -8544,10 +8707,12 @@
8544
8707
  startRouter,
8545
8708
  onBeforeNavigate,
8546
8709
  onAfterNavigate,
8710
+ onBeforeSwap,
8711
+ onNavigationEnd,
8547
8712
  portalCreate,
8548
8713
  portalDestroy,
8549
8714
  setCspNonce,
8550
- version: '0.3.2'
8715
+ version: '0.4.0'
8551
8716
  };
8552
8717
 
8553
8718
  const standardExpressionRuntime = {