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.esm.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
  */
@@ -2228,59 +2228,59 @@ function applyTransitionStyles() {
2228
2228
  return;
2229
2229
  const style = document.createElement('style');
2230
2230
  style.id = styleId;
2231
- style.textContent = `
2232
- /* Opacity utilities */
2231
+ style.textContent = `
2232
+ /* Opacity utilities */
2233
2233
  .gyos-t-opacity-0 { opacity: 0; }
2234
2234
  .gyos-t-opacity-100 { opacity: 1; }
2235
-
2236
- /* Transform - Translate Y */
2235
+
2236
+ /* Transform - Translate Y */
2237
2237
  .gyos-t-translate-y-0 { transform: translateY(0); }
2238
2238
  .gyos-t-translate-y--100 { transform: translateY(-100%); }
2239
2239
  .gyos-t-translate-y-100 { transform: translateY(100%); }
2240
-
2241
- /* Transform - Translate X */
2240
+
2241
+ /* Transform - Translate X */
2242
2242
  .gyos-t-translate-x-0 { transform: translateX(0); }
2243
2243
  .gyos-t-translate-x--100 { transform: translateX(-100%); }
2244
2244
  .gyos-t-translate-x-100 { transform: translateX(100%); }
2245
-
2246
- /* Transform - Scale */
2245
+
2246
+ /* Transform - Scale */
2247
2247
  .gyos-t-scale-0 { transform: scale(0); }
2248
2248
  .gyos-t-scale-50 { transform: scale(0.5); }
2249
2249
  .gyos-t-scale-100 { transform: scale(1); }
2250
-
2251
- /* Animation Keyframes */
2252
- @keyframes gyos-fade-in {
2253
- from { opacity: 0; }
2254
- to { opacity: 1; }
2255
- }
2256
-
2257
- @keyframes gyos-fade-out {
2258
- from { opacity: 1; }
2259
- to { opacity: 0; }
2260
- }
2261
-
2262
- @keyframes gyos-slide-down {
2263
- from { transform: translateY(-100%); opacity: 0; }
2264
- to { transform: translateY(0); opacity: 1; }
2265
- }
2266
-
2267
- @keyframes gyos-slide-up {
2268
- from { transform: translateY(100%); opacity: 0; }
2269
- to { transform: translateY(0); opacity: 1; }
2270
- }
2271
-
2272
- @keyframes gyos-scale-in {
2273
- from { transform: scale(0); opacity: 0; }
2274
- to { transform: scale(1); opacity: 1; }
2275
- }
2276
-
2277
- @keyframes gyos-scale-out {
2278
- from { transform: scale(1); opacity: 1; }
2279
- to { transform: scale(0); opacity: 0; }
2280
- }
2281
-
2282
- [g-cloak] {
2283
- display: none !important;
2250
+
2251
+ /* Animation Keyframes */
2252
+ @keyframes gyos-fade-in {
2253
+ from { opacity: 0; }
2254
+ to { opacity: 1; }
2255
+ }
2256
+
2257
+ @keyframes gyos-fade-out {
2258
+ from { opacity: 1; }
2259
+ to { opacity: 0; }
2260
+ }
2261
+
2262
+ @keyframes gyos-slide-down {
2263
+ from { transform: translateY(-100%); opacity: 0; }
2264
+ to { transform: translateY(0); opacity: 1; }
2265
+ }
2266
+
2267
+ @keyframes gyos-slide-up {
2268
+ from { transform: translateY(100%); opacity: 0; }
2269
+ to { transform: translateY(0); opacity: 1; }
2270
+ }
2271
+
2272
+ @keyframes gyos-scale-in {
2273
+ from { transform: scale(0); opacity: 0; }
2274
+ to { transform: scale(1); opacity: 1; }
2275
+ }
2276
+
2277
+ @keyframes gyos-scale-out {
2278
+ from { transform: scale(1); opacity: 1; }
2279
+ to { transform: scale(0); opacity: 0; }
2280
+ }
2281
+
2282
+ [g-cloak] {
2283
+ display: none !important;
2284
2284
  }`;
2285
2285
  document.head.appendChild(style);
2286
2286
  }
@@ -6637,33 +6637,44 @@ class ProgressBar {
6637
6637
  getCurrentProgress() {
6638
6638
  return this.currentProgress;
6639
6639
  }
6640
+ reconnect() {
6641
+ if (!this.element || !this.progressBarEnabled || !document.body)
6642
+ return;
6643
+ // Snapshots may contain a clone of the runtime bar. Keep this instance.
6644
+ document.querySelectorAll('#gyos-progress-bar').forEach(node => {
6645
+ if (node !== this.element)
6646
+ node.remove();
6647
+ });
6648
+ if (!this.element.isConnected)
6649
+ document.body.appendChild(this.element);
6650
+ }
6640
6651
  createBar() {
6641
6652
  if (typeof document === 'undefined')
6642
6653
  return;
6643
6654
  // Create progress bar element
6644
6655
  this.element = document.createElement('div');
6645
6656
  this.element.id = 'gyos-progress-bar';
6646
- this.element.style.cssText = `
6647
- position: fixed;
6648
- top: 0;
6649
- left: 0;
6650
- width: 0%;
6651
- height: 6px;
6652
- background: var(--gyos-progress-color, linear-gradient(90deg, #aab9ff, #77889f));
6653
- z-index: 999999;
6654
- transition: width 0.3s linear, opacity 0.3s linear;
6655
- opacity: 0;
6656
- pointer-events: none;
6657
- box-shadow: 0 0 10px rgba(102, 126, 234, 0.5);
6657
+ this.element.style.cssText = `
6658
+ position: fixed;
6659
+ top: 0;
6660
+ left: 0;
6661
+ width: 0%;
6662
+ height: 6px;
6663
+ background: var(--gyos-progress-color, linear-gradient(90deg, #aab9ff, #77889f));
6664
+ z-index: 999999;
6665
+ transition: width 0.3s linear, opacity 0.3s linear;
6666
+ opacity: 0;
6667
+ pointer-events: none;
6668
+ box-shadow: 0 0 10px rgba(102, 126, 234, 0.5);
6658
6669
  `;
6659
6670
  // Insert into DOM when ready
6660
6671
  if (document.readyState === 'loading') {
6661
6672
  document.addEventListener('DOMContentLoaded', () => {
6662
- document.body.insertAdjacentElement('beforeend', this.element);
6663
- });
6673
+ this.reconnect();
6674
+ }, { once: true });
6664
6675
  }
6665
6676
  else {
6666
- document.body.insertAdjacentElement('beforeend', this.element);
6677
+ this.reconnect();
6667
6678
  }
6668
6679
  }
6669
6680
  start() {
@@ -6687,6 +6698,7 @@ class ProgressBar {
6687
6698
  setProgress(percent) {
6688
6699
  if (!this.element || !this.progressBarEnabled)
6689
6700
  return;
6701
+ this.reconnect();
6690
6702
  // Clamp between 0-100
6691
6703
  percent = Math.min(100, Math.max(0, percent));
6692
6704
  this.currentProgress = percent;
@@ -6735,41 +6747,41 @@ class ProgressBar {
6735
6747
  function createTargetSpinner() {
6736
6748
  const spinner = document.createElement('div');
6737
6749
  spinner.className = 'gyos-target-spinner';
6738
- spinner.innerHTML = `
6739
- <div class="gyos-spinner-content">
6740
- <svg class="gyos-spinner-icon" viewBox="0 0 50 50">
6741
- <circle cx="25" cy="25" r="20" fill="none" stroke="currentColor" stroke-width="4" stroke-dasharray="31.4 31.4" />
6742
- </svg>
6743
- </div>
6750
+ spinner.innerHTML = `
6751
+ <div class="gyos-spinner-content">
6752
+ <svg class="gyos-spinner-icon" viewBox="0 0 50 50">
6753
+ <circle cx="25" cy="25" r="20" fill="none" stroke="currentColor" stroke-width="4" stroke-dasharray="31.4 31.4" />
6754
+ </svg>
6755
+ </div>
6744
6756
  `;
6745
6757
  // Inject styles if not already present
6746
6758
  if (expressionRuntimeMode() === 'standard' && !document.getElementById('gyos-target-spinner-styles')) {
6747
6759
  const style = document.createElement('style');
6748
6760
  style.id = 'gyos-target-spinner-styles';
6749
- style.textContent = `
6750
- .gyos-target-spinner {
6751
- display: flex;
6752
- align-items: center;
6753
- justify-content: center;
6754
- padding: 20px;
6755
- min-height: 60px;
6756
- }
6757
- .gyos-spinner-content {
6758
- display: flex;
6759
- align-items: center;
6760
- gap: 10px;
6761
- color: var(--gyos-spinner-color, #667eea);
6762
- font-size: 14px;
6763
- }
6764
- .gyos-spinner-icon {
6765
- width: 24px;
6766
- height: 24px;
6767
- animation: gyos-spin 1s linear infinite;
6768
- }
6769
- @keyframes gyos-spin {
6770
- 0% { transform: rotate(0deg); }
6771
- 100% { transform: rotate(360deg); }
6772
- }
6761
+ style.textContent = `
6762
+ .gyos-target-spinner {
6763
+ display: flex;
6764
+ align-items: center;
6765
+ justify-content: center;
6766
+ padding: 20px;
6767
+ min-height: 60px;
6768
+ }
6769
+ .gyos-spinner-content {
6770
+ display: flex;
6771
+ align-items: center;
6772
+ gap: 10px;
6773
+ color: var(--gyos-spinner-color, #667eea);
6774
+ font-size: 14px;
6775
+ }
6776
+ .gyos-spinner-icon {
6777
+ width: 24px;
6778
+ height: 24px;
6779
+ animation: gyos-spin 1s linear infinite;
6780
+ }
6781
+ @keyframes gyos-spin {
6782
+ 0% { transform: rotate(0deg); }
6783
+ 100% { transform: rotate(360deg); }
6784
+ }
6773
6785
  `;
6774
6786
  document.head.appendChild(style);
6775
6787
  }
@@ -7129,8 +7141,8 @@ async function performSwap(target, src, mode, options = {}) {
7129
7141
  }
7130
7142
  result = target;
7131
7143
  }
7132
- await options.beforeScripts?.();
7133
7144
  options.onCommitted?.(result, normalized === 'append' || normalized === 'prepend' ? incomingChildren : [result]);
7145
+ await options.beforeScripts?.();
7134
7146
  // Additive swaps must not re-run scripts that already existed in the target.
7135
7147
  if (normalized === 'append' || normalized === 'prepend') {
7136
7148
  await executeScriptsInNodes(incomingChildren, options.signal);
@@ -7370,6 +7382,21 @@ function handleScroll(url, trigger, savedScroll) {
7370
7382
  window.scrollTo({ top: 0, behavior: 'smooth' });
7371
7383
  }
7372
7384
 
7385
+ // A retained relative URL still identifies the resource loaded on its original
7386
+ // page, even after pushState changes document.baseURI.
7387
+ const resourceUrls = new WeakMap();
7388
+ function rememberResourceUrls(root, baseUrl) {
7389
+ root.querySelectorAll('script[src], link[href]').forEach(node => {
7390
+ const attribute = node.tagName === 'SCRIPT' ? 'src' : 'href';
7391
+ const source = node.getAttribute(attribute);
7392
+ if (resourceUrls.get(node)?.source === source)
7393
+ return;
7394
+ try {
7395
+ resourceUrls.set(node, { source, url: new URL(source, baseUrl).href });
7396
+ }
7397
+ catch { /* Invalid resource URLs retain their literal identity. */ }
7398
+ });
7399
+ }
7373
7400
  function isNonceMeta(el) {
7374
7401
  return el.tagName === 'META' && el.getAttribute('name')?.toLowerCase() === 'csp-nonce';
7375
7402
  }
@@ -7387,7 +7414,20 @@ function serializeAttributes(el, context) {
7387
7414
  return;
7388
7415
  if (context.csp && isNonceMeta(el) && attr.name.toLowerCase() === 'content')
7389
7416
  return;
7390
- attributes.set(attr.name, attr.value);
7417
+ let value = attr.value;
7418
+ if ((el.tagName === 'SCRIPT' && attr.name === 'src') || (el.tagName === 'LINK' && attr.name === 'href')) {
7419
+ const cached = resourceUrls.get(el);
7420
+ if (cached?.source === value)
7421
+ value = cached.url;
7422
+ else {
7423
+ try {
7424
+ value = new URL(value, context.baseUrl || el.baseURI).href;
7425
+ resourceUrls.set(el, { source: attr.value, url: value });
7426
+ }
7427
+ catch { /* Keep invalid URLs distinct. */ }
7428
+ }
7429
+ }
7430
+ attributes.set(attr.name, value);
7391
7431
  });
7392
7432
  if (context.csp && usesCspNonce(el) && context.activeNonce) {
7393
7433
  attributes.set('nonce', context.activeNonce);
@@ -7454,19 +7494,21 @@ function warnSkippedNode(node) {
7454
7494
  console.warn('[GyosJS CSP] Skipped an inline MPA script because no active document nonce is configured.');
7455
7495
  }
7456
7496
  }
7457
- async function diffNodes(currentNodes, nextNodes, container = document.head, signal) {
7497
+ async function diffNodes(currentNodes, nextNodes, container = document.head, signal, currentBaseUrl = document.baseURI) {
7458
7498
  const csp = expressionRuntimeMode() === 'csp';
7459
7499
  const context = {
7460
7500
  csp,
7461
7501
  activeNonce: csp ? resolveCspNonce() : undefined
7462
7502
  };
7463
- const current = keyedNodes(currentNodes, context);
7503
+ const current = keyedNodes(currentNodes, { ...context, baseUrl: currentBaseUrl });
7464
7504
  const next = keyedNodes(nextNodes, context);
7505
+ const persistentKey = (node) => container === document.head ? node.getAttribute('g-head-persist') : null;
7506
+ const persistent = new Set(currentNodes.map(persistentKey).filter(Boolean));
7465
7507
  const currentKeys = new Set(current.map(item => item.key));
7466
7508
  const nextKeys = new Set(next.map(item => item.key));
7467
7509
  // Remove nodes that are not in the new head
7468
7510
  current.forEach(({ key, node }) => {
7469
- if (!nextKeys.has(key)) {
7511
+ if (!nextKeys.has(key) && !persistentKey(node)) {
7470
7512
  node.remove();
7471
7513
  }
7472
7514
  });
@@ -7474,6 +7516,8 @@ async function diffNodes(currentNodes, nextNodes, container = document.head, sig
7474
7516
  for (const { key, node } of next) {
7475
7517
  if (signal?.aborted)
7476
7518
  return;
7519
+ if (persistent.has(persistentKey(node)))
7520
+ continue;
7477
7521
  if (!currentKeys.has(key)) {
7478
7522
  if (!canInsertNode(node, context)) {
7479
7523
  warnSkippedNode(node);
@@ -7676,6 +7720,7 @@ function prepareNavigationHtml(html) {
7676
7720
  * MPA boost navigation inspired by Turbo Drive.
7677
7721
  * Implements attribute-driven routing, snapshot caching, and persistent islands.
7678
7722
  */
7723
+ const submittingForms = new WeakSet();
7679
7724
  const snapshots = new Map();
7680
7725
  const preloadCache = new Map();
7681
7726
  const preloadControllers = new Map();
@@ -7692,12 +7737,30 @@ let activeNavigation = null;
7692
7737
  let progressBar = null;
7693
7738
  const beforeNavigate = [];
7694
7739
  const afterNavigate = [];
7740
+ const beforeSwap = [];
7741
+ const navigationEnd = [];
7742
+ function registerNavigationHook(hooks, callback) {
7743
+ // A wrapper gives each registration its own unsubscribe identity.
7744
+ const entry = (url, context) => callback(url, context);
7745
+ hooks.push(entry);
7746
+ return () => {
7747
+ const index = hooks.indexOf(entry);
7748
+ if (index !== -1)
7749
+ hooks.splice(index, 1);
7750
+ };
7751
+ }
7695
7752
  // Expose hooks to register before/after navigation callbacks
7696
7753
  function onBeforeNavigate(callback) {
7697
- beforeNavigate.push(callback);
7754
+ return registerNavigationHook(beforeNavigate, callback);
7698
7755
  }
7699
7756
  function onAfterNavigate(callback) {
7700
- afterNavigate.push(callback);
7757
+ return registerNavigationHook(afterNavigate, callback);
7758
+ }
7759
+ function onBeforeSwap(callback) {
7760
+ return registerNavigationHook(beforeSwap, callback);
7761
+ }
7762
+ function onNavigationEnd(callback) {
7763
+ return registerNavigationHook(navigationEnd, (_url, context) => callback(context));
7701
7764
  }
7702
7765
  function startRouter(options) {
7703
7766
  // If not has g-boost attribute, do not start router
@@ -7721,6 +7784,7 @@ function startRouter(options) {
7721
7784
  }
7722
7785
  // Cache scripts from initial page to prevent re-execution on first navigation back
7723
7786
  cacheInitialPageScripts();
7787
+ rememberResourceUrls(document, document.baseURI);
7724
7788
  routerStarted = true;
7725
7789
  log('[GyosRouter] started');
7726
7790
  }
@@ -7777,9 +7841,13 @@ function resolveTarget(trigger, targetSelector, targetOutletIndex) {
7777
7841
  const outlet = findGlobalOutlet();
7778
7842
  return outlet instanceof HTMLElement ? outlet : null;
7779
7843
  }
7844
+ function isFullDocument(html) {
7845
+ return /^\s*(?:<!--[^]*?-->\s*)*(?:<!doctype\s+html\b|<html(?:\s|>))/i.test(html);
7846
+ }
7780
7847
  function saveSnapshot(url, html) {
7781
7848
  // create HTMLElement by html string to remove scripts and get clean snapshot
7782
7849
  const doc = parseNavigationDocument(html);
7850
+ doc.querySelectorAll('#gyos-progress-bar').forEach(node => node.remove());
7783
7851
  // Ignore hash for snapshot keys
7784
7852
  if (url.includes('#'))
7785
7853
  url = url.split('#')[0];
@@ -7788,7 +7856,7 @@ function saveSnapshot(url, html) {
7788
7856
  if (s.hasAttribute('g-script-once'))
7789
7857
  s.textContent = '';
7790
7858
  });
7791
- snapshots.set(url, { html: doc.documentElement.outerHTML });
7859
+ snapshots.set(url, { html: doc.documentElement.outerHTML, fullDocument: isFullDocument(html) });
7792
7860
  log('[GyosRouter] snapshot saved for', url);
7793
7861
  }
7794
7862
  function getOutletIndex(root, target) {
@@ -7900,10 +7968,10 @@ function consumeViewTransitionRejection(promise) {
7900
7968
  // update callback remains the navigation source of truth and is awaited below.
7901
7969
  void promise?.catch(() => undefined);
7902
7970
  }
7903
- function runNavigationHooks(callbacks, url) {
7904
- callbacks.forEach(callback => {
7971
+ function runNavigationHooks(callbacks, url, context) {
7972
+ [...callbacks].forEach(callback => {
7905
7973
  try {
7906
- callback(url);
7974
+ callback(url, { ...context });
7907
7975
  }
7908
7976
  catch (error) {
7909
7977
  console.error('[GyosRouter] navigation hook error', error);
@@ -7941,7 +8009,13 @@ function buildRequest(opts) {
7941
8009
  url = mergeFormDataIntoUrl(url, opts.formData);
7942
8010
  }
7943
8011
  else {
7944
- init.body = opts.formData;
8012
+ if (opts.formEncoding === 'application/x-www-form-urlencoded') {
8013
+ const encoded = new URLSearchParams();
8014
+ opts.formData.forEach((value, name) => encoded.append(name, typeof value === 'string' ? value : value.name));
8015
+ init.body = encoded;
8016
+ }
8017
+ else
8018
+ init.body = opts.formData;
7945
8019
  }
7946
8020
  }
7947
8021
  else if (opts.jsonData) {
@@ -7984,25 +8058,26 @@ function preload(url) {
7984
8058
  preloadControllers.delete(cacheKey);
7985
8059
  });
7986
8060
  }
7987
- async function updateHead(fromDoc, signal) {
8061
+ async function updateHead(fromDoc, signal, currentBaseUrl) {
7988
8062
  const allowedSelector = 'meta, link, style:not(#gyos-transitions), script';
7989
8063
  const currentNodes = Array.from(document.head.querySelectorAll(allowedSelector));
7990
8064
  const nextNodes = Array.from(fromDoc.head.querySelectorAll(allowedSelector));
7991
- await diffNodes(currentNodes, nextNodes, document.head, signal);
8065
+ await diffNodes(currentNodes, nextNodes, document.head, signal, currentBaseUrl);
7992
8066
  }
7993
- async function scriptNotInOutletTarget(fromDoc, target, source, signal) {
8067
+ async function scriptNotInOutletTarget(fromDoc, target, source, signal, currentBaseUrl) {
7994
8068
  // scripts in current document and it not in target outlet
7995
8069
  const currentScripts = Array.from(document.scripts).filter(s => !target.contains(s) && !document.head.contains(s));
7996
8070
  // scripts in fromDoc and it not in source outlet
7997
8071
  const incomingScripts = Array.from(fromDoc.scripts).filter(s => !source.contains(s) && !fromDoc.head.contains(s));
7998
8072
  // Diff and update scripts not in outlet/target
7999
- await diffNodes(currentScripts, incomingScripts, document.body, signal);
8073
+ await diffNodes(currentScripts, incomingScripts, document.body, signal, currentBaseUrl);
8000
8074
  }
8001
8075
  function resolveIncomingScriptUrls(root, baseUrl) {
8002
- root.querySelectorAll('script[src]').forEach(script => {
8003
- const source = script.getAttribute('src');
8076
+ root.querySelectorAll('script[src], link[href]').forEach(node => {
8077
+ const attribute = node.tagName === 'SCRIPT' ? 'src' : 'href';
8078
+ const source = node.getAttribute(attribute);
8004
8079
  if (source)
8005
- script.src = new URL(source, baseUrl).href;
8080
+ node.setAttribute(attribute, new URL(source, baseUrl).href);
8006
8081
  });
8007
8082
  }
8008
8083
  function isNavigableHtmlResponse(response) {
@@ -8056,6 +8131,22 @@ async function navigate(opts) {
8056
8131
  resolveDone
8057
8132
  };
8058
8133
  activeNavigation = transaction;
8134
+ const currentBaseUrl = document.baseURI;
8135
+ rememberResourceUrls(document, currentBaseUrl);
8136
+ const context = {
8137
+ from: currentUrl, url: opts.url, method: opts.method.toUpperCase(),
8138
+ trigger: opts.trigger || null, target: null, form: opts.form || null,
8139
+ popstate: opts.popstate === true, signal: transaction.controller.signal,
8140
+ status: null, committed: false, fallback: false, outcome: null
8141
+ };
8142
+ const formEvent = opts.form
8143
+ ? { form: opts.form, url: opts.url, status: null, outcome: null, committed: false, fallback: false }
8144
+ : null;
8145
+ const fallback = (url, requestSent) => {
8146
+ context.fallback = context.method === 'GET' || (!requestSent && !!opts.form);
8147
+ context.outcome ?? (context.outcome = context.fallback ? 'fallback' : 'invalid-response');
8148
+ fallbackFromBoost(opts, url, requestSent);
8149
+ };
8059
8150
  const hasTargetSpinner = opts.trigger?.hasAttribute('g-router-spin');
8060
8151
  const setRand = () => {
8061
8152
  if (isActiveNavigation(transaction) && progressBar?.getCurrentProgress() < 70) {
@@ -8063,7 +8154,10 @@ async function navigate(opts) {
8063
8154
  }
8064
8155
  };
8065
8156
  try {
8066
- runNavigationHooks(beforeNavigate, opts.url);
8157
+ if (formEvent)
8158
+ document.dispatchEvent(new CustomEvent('gyos:form-start', { detail: { ...formEvent } }));
8159
+ runNavigationHooks(beforeNavigate, opts.url, context);
8160
+ assertActiveNavigation(transaction);
8067
8161
  progressBar?.start();
8068
8162
  // popstate already points history at the destination entry. Keep the visible
8069
8163
  // page's position under currentUrl without overwriting that destination state.
@@ -8072,9 +8166,10 @@ async function navigate(opts) {
8072
8166
  saveScrollPosition();
8073
8167
  // Pick target element to swap
8074
8168
  let target = resolveTarget(opts.trigger, opts.targetSelector, opts.targetOutletIndex);
8169
+ context.target = target;
8075
8170
  if (!target) {
8076
8171
  if (isActiveNavigation(transaction))
8077
- fallbackFromBoost(opts, opts.url, false);
8172
+ fallback(opts.url, false);
8078
8173
  return;
8079
8174
  }
8080
8175
  const swapMode = (opts.swapMode || opts.trigger?.getAttribute('g-swap') || 'inner').toLowerCase();
@@ -8099,6 +8194,7 @@ async function navigate(opts) {
8099
8194
  if (hasTargetSpinner)
8100
8195
  transaction.spinner = showTargetSpinner(target, swapMode);
8101
8196
  const { finalUrl, init } = buildRequest(opts);
8197
+ context.url = finalUrl;
8102
8198
  // Add abort signal to request
8103
8199
  init.signal = transaction.controller.signal;
8104
8200
  let html;
@@ -8126,7 +8222,8 @@ async function navigate(opts) {
8126
8222
  if (error.name === 'AbortError')
8127
8223
  throw error;
8128
8224
  assertActiveNavigation(transaction);
8129
- window.location.href = finalUrl;
8225
+ context.outcome = 'network-error';
8226
+ fallback(finalUrl, true);
8130
8227
  return;
8131
8228
  }
8132
8229
  preloadCache.delete(preloadKey); // consume cache
@@ -8151,28 +8248,46 @@ async function navigate(opts) {
8151
8248
  log('[GyosRouter] Navigation cancelled');
8152
8249
  return;
8153
8250
  }
8251
+ context.outcome = 'network-error';
8154
8252
  if (isActiveNavigation(transaction))
8155
- fallbackFromBoost(opts, finalUrl, true);
8253
+ fallback(finalUrl, true);
8156
8254
  return;
8157
8255
  }
8158
8256
  }
8159
8257
  assertActiveNavigation(transaction);
8160
- // If response not ok, fallback to full navigation
8161
- if (!response || !response.ok || !isNavigableHtmlResponse(response)) {
8258
+ context.status = response?.status ?? null;
8259
+ context.url = response?.url || finalUrl;
8260
+ const acceptedErrors = (opts.trigger?.getAttribute('g-boost-errors') || '').split(/[\s,]+/);
8261
+ const renderHttpError = !!response && response.status >= 400 && response.status <= 599
8262
+ && acceptedErrors.includes(String(response.status));
8263
+ if (response && !response.ok)
8264
+ context.outcome = 'http-error';
8265
+ if (!response || (!response.ok && !renderHttpError) || !isNavigableHtmlResponse(response)) {
8266
+ context.outcome ?? (context.outcome = 'invalid-response');
8162
8267
  if (isActiveNavigation(transaction))
8163
- fallbackFromBoost(opts, finalUrl, true);
8268
+ fallback(finalUrl, true);
8164
8269
  return;
8165
8270
  }
8166
8271
  html = await response.text();
8167
8272
  assertActiveNavigation(transaction);
8168
- if (!opts.popstate && target.hasAttribute('g-snapshot')) {
8169
- saveSnapshot(canonicalUrl(response.url || finalUrl), html);
8170
- }
8171
8273
  }
8172
8274
  // Parse HTML
8173
8275
  const doc = html
8174
8276
  ? parseNavigationDocument(html)
8175
8277
  : document.implementation.createHTMLDocument();
8278
+ // Detached parsing cannot tell whether the live CSP permits an incoming base.
8279
+ // Let native navigation enforce base-uri instead of authorizing its URLs ourselves.
8280
+ if (doc.querySelector('base[href]') || opts.historyFragment?.querySelector('base[href]')) {
8281
+ context.outcome = 'invalid-response';
8282
+ fallback(response?.url || finalUrl, true);
8283
+ return;
8284
+ }
8285
+ if (response?.ok && !opts.popstate && target.hasAttribute('g-snapshot')) {
8286
+ saveSnapshot(canonicalUrl(response.url || finalUrl), html);
8287
+ }
8288
+ const syncDocumentAttributes = isFullOutletNavigation && destructiveSwap && !currentHead
8289
+ && !opts.historyFragment && (opts.popstate && snapshots.has(urlWithoutHash)
8290
+ ? snapshots.get(urlWithoutHash).fullDocument : isFullDocument(html || ''));
8176
8291
  // Pick source fragment
8177
8292
  const src = opts.historyFragment || pickSourceFragment(doc, target, targetOutletIndex);
8178
8293
  stripInertFallbackContent(src);
@@ -8184,15 +8299,18 @@ async function navigate(opts) {
8184
8299
  targetUrl += finalUrl.substring(finalUrl.indexOf('#'));
8185
8300
  }
8186
8301
  resolveIncomingScriptUrls(doc, targetUrl);
8302
+ context.url = targetUrl;
8187
8303
  if (opts.historyFragment)
8188
8304
  resolveIncomingScriptUrls(src, targetUrl);
8189
8305
  const triggerChangesState = opts.trigger?.hasAttribute('g-change-state') || false;
8190
8306
  const keepsCurrentState = opts.trigger?.hasAttribute('g-current-state') || false;
8191
8307
  const redirectedSubmission = opts.method.toUpperCase() !== 'GET' && response?.redirected === true;
8192
- const changesState = !keepsCurrentState && (opts.changeState === true || triggerChangesState || redirectedSubmission);
8308
+ const changesState = context.outcome !== 'http-error' && !keepsCurrentState && (opts.changeState === true || triggerChangesState || redirectedSubmission);
8193
8309
  const performUpdate = async () => {
8194
8310
  assertActiveNavigation(transaction);
8195
8311
  transaction.committing = true;
8312
+ runNavigationHooks(beforeSwap, targetUrl, context);
8313
+ assertActiveNavigation(transaction);
8196
8314
  // Update progress to rand 80 - 90% before swap
8197
8315
  progressBar?.setProgress(Math.random() * 10 + 80);
8198
8316
  const outgoingHistoryFragment = changesState && !opts.replace && !isFullOutletNavigation
@@ -8263,21 +8381,34 @@ async function navigate(opts) {
8263
8381
  beforeScripts: async () => {
8264
8382
  if (!isFullOutletNavigation || currentHead)
8265
8383
  return;
8384
+ if (syncDocumentAttributes) {
8385
+ for (const name of ['lang', 'dir']) {
8386
+ const value = doc.documentElement.getAttribute(name);
8387
+ if (value === null)
8388
+ document.documentElement.removeAttribute(name);
8389
+ else
8390
+ document.documentElement.setAttribute(name, value);
8391
+ }
8392
+ }
8266
8393
  const incomingTitle = doc.querySelector('title');
8267
8394
  if (incomingTitle) {
8268
8395
  document.title = incomingTitle.textContent || document.title;
8269
8396
  }
8270
- await updateHead(doc, transaction.controller.signal);
8397
+ await updateHead(doc, transaction.controller.signal, currentBaseUrl);
8271
8398
  assertActiveNavigation(transaction);
8272
8399
  },
8273
8400
  onCommitted: (committedTarget, roots) => {
8274
8401
  target = committedTarget;
8402
+ context.target = committedTarget;
8403
+ context.committed = true;
8404
+ progressBar?.reconnect();
8275
8405
  committedRoots = roots;
8276
8406
  }
8277
8407
  });
8408
+ context.committed = true;
8278
8409
  assertActiveNavigation(transaction);
8279
8410
  if (isFullOutletNavigation) {
8280
- await scriptNotInOutletTarget(doc, target, src, transaction.controller.signal);
8411
+ await scriptNotInOutletTarget(doc, target, src, transaction.controller.signal, currentBaseUrl);
8281
8412
  assertActiveNavigation(transaction);
8282
8413
  }
8283
8414
  }
@@ -8311,14 +8442,15 @@ async function navigate(opts) {
8311
8442
  await performUpdate();
8312
8443
  }
8313
8444
  assertActiveNavigation(transaction);
8314
- if (removeTriggerAfterCommit && opts.trigger instanceof HTMLElement && opts.trigger.isConnected) {
8445
+ if (removeTriggerAfterCommit && context.outcome !== 'http-error' && opts.trigger instanceof HTMLElement && opts.trigger.isConnected) {
8315
8446
  disposeEffects(opts.trigger);
8316
8447
  opts.trigger.remove();
8317
8448
  }
8318
8449
  if (hasTargetSpinner)
8319
8450
  hideTargetSpinner(transaction.spinner);
8320
8451
  transaction.spinner = null;
8321
- runNavigationHooks(afterNavigate, targetUrl);
8452
+ context.outcome ?? (context.outcome = 'success');
8453
+ runNavigationHooks(afterNavigate, targetUrl, context);
8322
8454
  log('[GyosRouter] navigated to', targetUrl);
8323
8455
  currentUrl = changesState
8324
8456
  ? canonicalUrl(targetUrl, true)
@@ -8334,11 +8466,15 @@ async function navigate(opts) {
8334
8466
  return;
8335
8467
  }
8336
8468
  if (isActiveNavigation(transaction)) {
8469
+ context.outcome ?? (context.outcome = 'error');
8337
8470
  console.error('[GyosRouter] navigation error', error);
8338
- fallbackFromBoost(opts, opts.url, true);
8471
+ fallback(opts.url, true);
8339
8472
  }
8340
8473
  }
8341
8474
  finally {
8475
+ if (transaction.controller.signal.aborted)
8476
+ context.outcome = 'aborted';
8477
+ context.outcome ?? (context.outcome = 'aborted');
8342
8478
  if (transaction.interval)
8343
8479
  clearInterval(transaction.interval);
8344
8480
  if (transaction.spinner)
@@ -8348,6 +8484,15 @@ async function navigate(opts) {
8348
8484
  progressBar?.complete();
8349
8485
  }
8350
8486
  transaction.resolveDone();
8487
+ if (formEvent)
8488
+ submittingForms.delete(formEvent.form);
8489
+ runNavigationHooks(navigationEnd, context.url, context);
8490
+ if (formEvent) {
8491
+ const { url, status, outcome, committed, fallback } = context;
8492
+ document.dispatchEvent(new CustomEvent('gyos:form-end', {
8493
+ detail: { ...formEvent, url, status, outcome, committed, fallback }
8494
+ }));
8495
+ }
8351
8496
  }
8352
8497
  }
8353
8498
  function shouldBoost(el) {
@@ -8456,16 +8601,34 @@ function onSubmit(event) {
8456
8601
  return;
8457
8602
  if (shouldDeferToFormValidation(form))
8458
8603
  return;
8459
- event.preventDefault();
8460
- const action = form.action || window.location.href;
8461
- const method = (form.method || 'GET').toUpperCase();
8462
- const url = new URL(action, window.location.href);
8463
- if (url.origin !== window.location.origin) {
8464
- window.location.href = url.toString();
8604
+ const submitter = event.submitter;
8605
+ const override = (name) => submitter?.getAttribute(`form${name}`) ?? form.getAttribute(name);
8606
+ const target = override('target') ?? document.querySelector('base[target]')?.getAttribute('target');
8607
+ const declaredMethod = (override('method') || 'GET').toUpperCase();
8608
+ const method = ['GET', 'POST', 'DIALOG'].includes(declaredMethod) ? declaredMethod : 'GET';
8609
+ const formEncoding = override('enctype')?.toLowerCase();
8610
+ if ((target && target.toLowerCase() !== '_self') || method === 'DIALOG' || formEncoding === 'text/plain')
8611
+ return;
8612
+ if (!resolveTarget(form))
8613
+ return;
8614
+ // Image submitters carry click coordinates which SubmitEvent does not expose.
8615
+ if (submitter instanceof HTMLInputElement && submitter.type === 'image')
8616
+ return;
8617
+ let url;
8618
+ try {
8619
+ url = new URL(override('action') || window.location.href, document.baseURI);
8620
+ }
8621
+ catch {
8465
8622
  return;
8466
8623
  }
8467
- const formData = new FormData(form);
8468
- navigate({ url: url.toString(), method, trigger: form, form, formData, changeState: method === 'GET' });
8624
+ if (url.origin !== window.location.origin)
8625
+ return;
8626
+ event.preventDefault();
8627
+ if (submittingForms.has(form))
8628
+ return;
8629
+ const formData = new FormData(form, submitter);
8630
+ submittingForms.add(form);
8631
+ void navigate({ url: url.toString(), method, trigger: form, form, formData, formEncoding, changeState: method === 'GET' });
8469
8632
  }
8470
8633
  function onPopState(event) {
8471
8634
  const url = window.location.href;
@@ -8570,13 +8733,15 @@ const Gyos = {
8570
8733
  startRouter,
8571
8734
  onBeforeNavigate,
8572
8735
  onAfterNavigate,
8736
+ onBeforeSwap,
8737
+ onNavigationEnd,
8573
8738
  portalCreate,
8574
8739
  portalDestroy,
8575
8740
  setCspNonce,
8576
- version: '0.3.2'
8741
+ version: '0.4.0'
8577
8742
  };
8578
8743
 
8579
8744
  setExpressionRuntime(standardExpressionRuntime);
8580
8745
 
8581
- export { applyDirective, applyTransitionStyles, batch, disposeEffects as cleanup, clearAllEvents, computed, debounce, Gyos as default, directive, effect, emit, getEventListeners, getGlobalContainer, getStoreNames, getTransitionConfig, getValidator, getValidatorNames, hasStore, inject, isComputed, isSignal, markRaw, mount, mountAll, mountTree, getAllMountedScopes as mountedScopes, nextTick, off, on, onAfterNavigate, onBeforeNavigate, once, pipe, portalCreate, portalDestroy, provide, ready, registerTransition, removeStore, scope, setCspNonce, shallow, signal, startRouter, store, throttle, unref, untrack, useAsync, useCounter, useDebounce, useFetch, useInterval, useLocalStorage, useMediaQuery, useMouse, useThrottle, useTimeout, useToggle, useWindowSize, validate, validator };
8746
+ export { applyDirective, applyTransitionStyles, batch, disposeEffects as cleanup, clearAllEvents, computed, debounce, Gyos as default, directive, effect, emit, getEventListeners, getGlobalContainer, getStoreNames, getTransitionConfig, getValidator, getValidatorNames, hasStore, inject, isComputed, isSignal, markRaw, mount, mountAll, mountTree, getAllMountedScopes as mountedScopes, nextTick, off, on, onAfterNavigate, onBeforeNavigate, onBeforeSwap, onNavigationEnd, once, pipe, portalCreate, portalDestroy, provide, ready, registerTransition, removeStore, scope, setCspNonce, shallow, signal, startRouter, store, throttle, unref, untrack, useAsync, useCounter, useDebounce, useFetch, useInterval, useLocalStorage, useMediaQuery, useMouse, useThrottle, useTimeout, useToggle, useWindowSize, validate, validator };
8582
8747
  //# sourceMappingURL=gyos.esm.js.map