gyosjs 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/gyos.esm.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * GyosJS v0.3.1
2
+ * GyosJS v0.4.0
3
3
  * (c) 2026
4
4
  * @license MIT
5
5
  */
@@ -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
  }
@@ -5215,6 +5215,10 @@ function processStructuralDirectives(elements, scope) {
5215
5215
  const structuralElements = [];
5216
5216
  const root = elements[0];
5217
5217
  elements.forEach(el => {
5218
+ // Await branches are detached and parsed only after their alias scope exists.
5219
+ // Do not evaluate nested structural expressions during the parent scan.
5220
+ if (isAwaitBranchDescendant(el))
5221
+ return;
5218
5222
  const hasIf = el.hasAttribute('*if');
5219
5223
  const hasFor = el.hasAttribute('*for');
5220
5224
  const hasSwitch = el.hasAttribute('*switch');
@@ -5259,6 +5263,20 @@ function processStructuralDirectives(elements, scope) {
5259
5263
  }
5260
5264
  });
5261
5265
  }
5266
+ function isAwaitBranchDescendant(element) {
5267
+ let child = element;
5268
+ let parent = element.parentElement;
5269
+ while (parent && parent !== document.body) {
5270
+ if (parent.hasAttribute('*await') && (child.hasAttribute('*pending') ||
5271
+ child.hasAttribute('*then') ||
5272
+ child.hasAttribute('*catch'))) {
5273
+ return true;
5274
+ }
5275
+ child = parent;
5276
+ parent = parent.parentElement;
5277
+ }
5278
+ return false;
5279
+ }
5262
5280
  const elementBelongsToAnotherScope = (el, scope) => {
5263
5281
  const owner = getScopeFromElement(el);
5264
5282
  return Boolean(owner && owner !== scope);
@@ -6619,33 +6637,44 @@ class ProgressBar {
6619
6637
  getCurrentProgress() {
6620
6638
  return this.currentProgress;
6621
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
+ }
6622
6651
  createBar() {
6623
6652
  if (typeof document === 'undefined')
6624
6653
  return;
6625
6654
  // Create progress bar element
6626
6655
  this.element = document.createElement('div');
6627
6656
  this.element.id = 'gyos-progress-bar';
6628
- this.element.style.cssText = `
6629
- position: fixed;
6630
- top: 0;
6631
- left: 0;
6632
- width: 0%;
6633
- height: 6px;
6634
- background: var(--gyos-progress-color, linear-gradient(90deg, #aab9ff, #77889f));
6635
- z-index: 999999;
6636
- transition: width 0.3s linear, opacity 0.3s linear;
6637
- opacity: 0;
6638
- pointer-events: none;
6639
- 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);
6640
6669
  `;
6641
6670
  // Insert into DOM when ready
6642
6671
  if (document.readyState === 'loading') {
6643
6672
  document.addEventListener('DOMContentLoaded', () => {
6644
- document.body.insertAdjacentElement('beforeend', this.element);
6645
- });
6673
+ this.reconnect();
6674
+ }, { once: true });
6646
6675
  }
6647
6676
  else {
6648
- document.body.insertAdjacentElement('beforeend', this.element);
6677
+ this.reconnect();
6649
6678
  }
6650
6679
  }
6651
6680
  start() {
@@ -6669,6 +6698,7 @@ class ProgressBar {
6669
6698
  setProgress(percent) {
6670
6699
  if (!this.element || !this.progressBarEnabled)
6671
6700
  return;
6701
+ this.reconnect();
6672
6702
  // Clamp between 0-100
6673
6703
  percent = Math.min(100, Math.max(0, percent));
6674
6704
  this.currentProgress = percent;
@@ -6717,41 +6747,41 @@ class ProgressBar {
6717
6747
  function createTargetSpinner() {
6718
6748
  const spinner = document.createElement('div');
6719
6749
  spinner.className = 'gyos-target-spinner';
6720
- spinner.innerHTML = `
6721
- <div class="gyos-spinner-content">
6722
- <svg class="gyos-spinner-icon" viewBox="0 0 50 50">
6723
- <circle cx="25" cy="25" r="20" fill="none" stroke="currentColor" stroke-width="4" stroke-dasharray="31.4 31.4" />
6724
- </svg>
6725
- </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>
6726
6756
  `;
6727
6757
  // Inject styles if not already present
6728
6758
  if (expressionRuntimeMode() === 'standard' && !document.getElementById('gyos-target-spinner-styles')) {
6729
6759
  const style = document.createElement('style');
6730
6760
  style.id = 'gyos-target-spinner-styles';
6731
- style.textContent = `
6732
- .gyos-target-spinner {
6733
- display: flex;
6734
- align-items: center;
6735
- justify-content: center;
6736
- padding: 20px;
6737
- min-height: 60px;
6738
- }
6739
- .gyos-spinner-content {
6740
- display: flex;
6741
- align-items: center;
6742
- gap: 10px;
6743
- color: var(--gyos-spinner-color, #667eea);
6744
- font-size: 14px;
6745
- }
6746
- .gyos-spinner-icon {
6747
- width: 24px;
6748
- height: 24px;
6749
- animation: gyos-spin 1s linear infinite;
6750
- }
6751
- @keyframes gyos-spin {
6752
- 0% { transform: rotate(0deg); }
6753
- 100% { transform: rotate(360deg); }
6754
- }
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
+ }
6755
6785
  `;
6756
6786
  document.head.appendChild(style);
6757
6787
  }
@@ -7111,8 +7141,8 @@ async function performSwap(target, src, mode, options = {}) {
7111
7141
  }
7112
7142
  result = target;
7113
7143
  }
7114
- await options.beforeScripts?.();
7115
7144
  options.onCommitted?.(result, normalized === 'append' || normalized === 'prepend' ? incomingChildren : [result]);
7145
+ await options.beforeScripts?.();
7116
7146
  // Additive swaps must not re-run scripts that already existed in the target.
7117
7147
  if (normalized === 'append' || normalized === 'prepend') {
7118
7148
  await executeScriptsInNodes(incomingChildren, options.signal);
@@ -7352,6 +7382,21 @@ function handleScroll(url, trigger, savedScroll) {
7352
7382
  window.scrollTo({ top: 0, behavior: 'smooth' });
7353
7383
  }
7354
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
+ }
7355
7400
  function isNonceMeta(el) {
7356
7401
  return el.tagName === 'META' && el.getAttribute('name')?.toLowerCase() === 'csp-nonce';
7357
7402
  }
@@ -7369,7 +7414,20 @@ function serializeAttributes(el, context) {
7369
7414
  return;
7370
7415
  if (context.csp && isNonceMeta(el) && attr.name.toLowerCase() === 'content')
7371
7416
  return;
7372
- 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);
7373
7431
  });
7374
7432
  if (context.csp && usesCspNonce(el) && context.activeNonce) {
7375
7433
  attributes.set('nonce', context.activeNonce);
@@ -7436,19 +7494,21 @@ function warnSkippedNode(node) {
7436
7494
  console.warn('[GyosJS CSP] Skipped an inline MPA script because no active document nonce is configured.');
7437
7495
  }
7438
7496
  }
7439
- async function diffNodes(currentNodes, nextNodes, container = document.head, signal) {
7497
+ async function diffNodes(currentNodes, nextNodes, container = document.head, signal, currentBaseUrl = document.baseURI) {
7440
7498
  const csp = expressionRuntimeMode() === 'csp';
7441
7499
  const context = {
7442
7500
  csp,
7443
7501
  activeNonce: csp ? resolveCspNonce() : undefined
7444
7502
  };
7445
- const current = keyedNodes(currentNodes, context);
7503
+ const current = keyedNodes(currentNodes, { ...context, baseUrl: currentBaseUrl });
7446
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));
7447
7507
  const currentKeys = new Set(current.map(item => item.key));
7448
7508
  const nextKeys = new Set(next.map(item => item.key));
7449
7509
  // Remove nodes that are not in the new head
7450
7510
  current.forEach(({ key, node }) => {
7451
- if (!nextKeys.has(key)) {
7511
+ if (!nextKeys.has(key) && !persistentKey(node)) {
7452
7512
  node.remove();
7453
7513
  }
7454
7514
  });
@@ -7456,6 +7516,8 @@ async function diffNodes(currentNodes, nextNodes, container = document.head, sig
7456
7516
  for (const { key, node } of next) {
7457
7517
  if (signal?.aborted)
7458
7518
  return;
7519
+ if (persistent.has(persistentKey(node)))
7520
+ continue;
7459
7521
  if (!currentKeys.has(key)) {
7460
7522
  if (!canInsertNode(node, context)) {
7461
7523
  warnSkippedNode(node);
@@ -7658,6 +7720,7 @@ function prepareNavigationHtml(html) {
7658
7720
  * MPA boost navigation inspired by Turbo Drive.
7659
7721
  * Implements attribute-driven routing, snapshot caching, and persistent islands.
7660
7722
  */
7723
+ const submittingForms = new WeakSet();
7661
7724
  const snapshots = new Map();
7662
7725
  const preloadCache = new Map();
7663
7726
  const preloadControllers = new Map();
@@ -7674,12 +7737,30 @@ let activeNavigation = null;
7674
7737
  let progressBar = null;
7675
7738
  const beforeNavigate = [];
7676
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
+ }
7677
7752
  // Expose hooks to register before/after navigation callbacks
7678
7753
  function onBeforeNavigate(callback) {
7679
- beforeNavigate.push(callback);
7754
+ return registerNavigationHook(beforeNavigate, callback);
7680
7755
  }
7681
7756
  function onAfterNavigate(callback) {
7682
- 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));
7683
7764
  }
7684
7765
  function startRouter(options) {
7685
7766
  // If not has g-boost attribute, do not start router
@@ -7703,6 +7784,7 @@ function startRouter(options) {
7703
7784
  }
7704
7785
  // Cache scripts from initial page to prevent re-execution on first navigation back
7705
7786
  cacheInitialPageScripts();
7787
+ rememberResourceUrls(document, document.baseURI);
7706
7788
  routerStarted = true;
7707
7789
  log('[GyosRouter] started');
7708
7790
  }
@@ -7759,9 +7841,13 @@ function resolveTarget(trigger, targetSelector, targetOutletIndex) {
7759
7841
  const outlet = findGlobalOutlet();
7760
7842
  return outlet instanceof HTMLElement ? outlet : null;
7761
7843
  }
7844
+ function isFullDocument(html) {
7845
+ return /^\s*(?:<!--[^]*?-->\s*)*(?:<!doctype\s+html\b|<html(?:\s|>))/i.test(html);
7846
+ }
7762
7847
  function saveSnapshot(url, html) {
7763
7848
  // create HTMLElement by html string to remove scripts and get clean snapshot
7764
7849
  const doc = parseNavigationDocument(html);
7850
+ doc.querySelectorAll('#gyos-progress-bar').forEach(node => node.remove());
7765
7851
  // Ignore hash for snapshot keys
7766
7852
  if (url.includes('#'))
7767
7853
  url = url.split('#')[0];
@@ -7770,7 +7856,7 @@ function saveSnapshot(url, html) {
7770
7856
  if (s.hasAttribute('g-script-once'))
7771
7857
  s.textContent = '';
7772
7858
  });
7773
- snapshots.set(url, { html: doc.documentElement.outerHTML });
7859
+ snapshots.set(url, { html: doc.documentElement.outerHTML, fullDocument: isFullDocument(html) });
7774
7860
  log('[GyosRouter] snapshot saved for', url);
7775
7861
  }
7776
7862
  function getOutletIndex(root, target) {
@@ -7882,10 +7968,10 @@ function consumeViewTransitionRejection(promise) {
7882
7968
  // update callback remains the navigation source of truth and is awaited below.
7883
7969
  void promise?.catch(() => undefined);
7884
7970
  }
7885
- function runNavigationHooks(callbacks, url) {
7886
- callbacks.forEach(callback => {
7971
+ function runNavigationHooks(callbacks, url, context) {
7972
+ [...callbacks].forEach(callback => {
7887
7973
  try {
7888
- callback(url);
7974
+ callback(url, { ...context });
7889
7975
  }
7890
7976
  catch (error) {
7891
7977
  console.error('[GyosRouter] navigation hook error', error);
@@ -7923,7 +8009,13 @@ function buildRequest(opts) {
7923
8009
  url = mergeFormDataIntoUrl(url, opts.formData);
7924
8010
  }
7925
8011
  else {
7926
- 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;
7927
8019
  }
7928
8020
  }
7929
8021
  else if (opts.jsonData) {
@@ -7966,25 +8058,26 @@ function preload(url) {
7966
8058
  preloadControllers.delete(cacheKey);
7967
8059
  });
7968
8060
  }
7969
- async function updateHead(fromDoc, signal) {
8061
+ async function updateHead(fromDoc, signal, currentBaseUrl) {
7970
8062
  const allowedSelector = 'meta, link, style:not(#gyos-transitions), script';
7971
8063
  const currentNodes = Array.from(document.head.querySelectorAll(allowedSelector));
7972
8064
  const nextNodes = Array.from(fromDoc.head.querySelectorAll(allowedSelector));
7973
- await diffNodes(currentNodes, nextNodes, document.head, signal);
8065
+ await diffNodes(currentNodes, nextNodes, document.head, signal, currentBaseUrl);
7974
8066
  }
7975
- async function scriptNotInOutletTarget(fromDoc, target, source, signal) {
8067
+ async function scriptNotInOutletTarget(fromDoc, target, source, signal, currentBaseUrl) {
7976
8068
  // scripts in current document and it not in target outlet
7977
8069
  const currentScripts = Array.from(document.scripts).filter(s => !target.contains(s) && !document.head.contains(s));
7978
8070
  // scripts in fromDoc and it not in source outlet
7979
8071
  const incomingScripts = Array.from(fromDoc.scripts).filter(s => !source.contains(s) && !fromDoc.head.contains(s));
7980
8072
  // Diff and update scripts not in outlet/target
7981
- await diffNodes(currentScripts, incomingScripts, document.body, signal);
8073
+ await diffNodes(currentScripts, incomingScripts, document.body, signal, currentBaseUrl);
7982
8074
  }
7983
8075
  function resolveIncomingScriptUrls(root, baseUrl) {
7984
- root.querySelectorAll('script[src]').forEach(script => {
7985
- 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);
7986
8079
  if (source)
7987
- script.src = new URL(source, baseUrl).href;
8080
+ node.setAttribute(attribute, new URL(source, baseUrl).href);
7988
8081
  });
7989
8082
  }
7990
8083
  function isNavigableHtmlResponse(response) {
@@ -8038,6 +8131,22 @@ async function navigate(opts) {
8038
8131
  resolveDone
8039
8132
  };
8040
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
+ };
8041
8150
  const hasTargetSpinner = opts.trigger?.hasAttribute('g-router-spin');
8042
8151
  const setRand = () => {
8043
8152
  if (isActiveNavigation(transaction) && progressBar?.getCurrentProgress() < 70) {
@@ -8045,7 +8154,10 @@ async function navigate(opts) {
8045
8154
  }
8046
8155
  };
8047
8156
  try {
8048
- 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);
8049
8161
  progressBar?.start();
8050
8162
  // popstate already points history at the destination entry. Keep the visible
8051
8163
  // page's position under currentUrl without overwriting that destination state.
@@ -8054,9 +8166,10 @@ async function navigate(opts) {
8054
8166
  saveScrollPosition();
8055
8167
  // Pick target element to swap
8056
8168
  let target = resolveTarget(opts.trigger, opts.targetSelector, opts.targetOutletIndex);
8169
+ context.target = target;
8057
8170
  if (!target) {
8058
8171
  if (isActiveNavigation(transaction))
8059
- fallbackFromBoost(opts, opts.url, false);
8172
+ fallback(opts.url, false);
8060
8173
  return;
8061
8174
  }
8062
8175
  const swapMode = (opts.swapMode || opts.trigger?.getAttribute('g-swap') || 'inner').toLowerCase();
@@ -8081,6 +8194,7 @@ async function navigate(opts) {
8081
8194
  if (hasTargetSpinner)
8082
8195
  transaction.spinner = showTargetSpinner(target, swapMode);
8083
8196
  const { finalUrl, init } = buildRequest(opts);
8197
+ context.url = finalUrl;
8084
8198
  // Add abort signal to request
8085
8199
  init.signal = transaction.controller.signal;
8086
8200
  let html;
@@ -8108,7 +8222,8 @@ async function navigate(opts) {
8108
8222
  if (error.name === 'AbortError')
8109
8223
  throw error;
8110
8224
  assertActiveNavigation(transaction);
8111
- window.location.href = finalUrl;
8225
+ context.outcome = 'network-error';
8226
+ fallback(finalUrl, true);
8112
8227
  return;
8113
8228
  }
8114
8229
  preloadCache.delete(preloadKey); // consume cache
@@ -8133,28 +8248,46 @@ async function navigate(opts) {
8133
8248
  log('[GyosRouter] Navigation cancelled');
8134
8249
  return;
8135
8250
  }
8251
+ context.outcome = 'network-error';
8136
8252
  if (isActiveNavigation(transaction))
8137
- fallbackFromBoost(opts, finalUrl, true);
8253
+ fallback(finalUrl, true);
8138
8254
  return;
8139
8255
  }
8140
8256
  }
8141
8257
  assertActiveNavigation(transaction);
8142
- // If response not ok, fallback to full navigation
8143
- 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');
8144
8267
  if (isActiveNavigation(transaction))
8145
- fallbackFromBoost(opts, finalUrl, true);
8268
+ fallback(finalUrl, true);
8146
8269
  return;
8147
8270
  }
8148
8271
  html = await response.text();
8149
8272
  assertActiveNavigation(transaction);
8150
- if (!opts.popstate && target.hasAttribute('g-snapshot')) {
8151
- saveSnapshot(canonicalUrl(response.url || finalUrl), html);
8152
- }
8153
8273
  }
8154
8274
  // Parse HTML
8155
8275
  const doc = html
8156
8276
  ? parseNavigationDocument(html)
8157
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 || ''));
8158
8291
  // Pick source fragment
8159
8292
  const src = opts.historyFragment || pickSourceFragment(doc, target, targetOutletIndex);
8160
8293
  stripInertFallbackContent(src);
@@ -8166,15 +8299,18 @@ async function navigate(opts) {
8166
8299
  targetUrl += finalUrl.substring(finalUrl.indexOf('#'));
8167
8300
  }
8168
8301
  resolveIncomingScriptUrls(doc, targetUrl);
8302
+ context.url = targetUrl;
8169
8303
  if (opts.historyFragment)
8170
8304
  resolveIncomingScriptUrls(src, targetUrl);
8171
8305
  const triggerChangesState = opts.trigger?.hasAttribute('g-change-state') || false;
8172
8306
  const keepsCurrentState = opts.trigger?.hasAttribute('g-current-state') || false;
8173
8307
  const redirectedSubmission = opts.method.toUpperCase() !== 'GET' && response?.redirected === true;
8174
- const changesState = !keepsCurrentState && (opts.changeState === true || triggerChangesState || redirectedSubmission);
8308
+ const changesState = context.outcome !== 'http-error' && !keepsCurrentState && (opts.changeState === true || triggerChangesState || redirectedSubmission);
8175
8309
  const performUpdate = async () => {
8176
8310
  assertActiveNavigation(transaction);
8177
8311
  transaction.committing = true;
8312
+ runNavigationHooks(beforeSwap, targetUrl, context);
8313
+ assertActiveNavigation(transaction);
8178
8314
  // Update progress to rand 80 - 90% before swap
8179
8315
  progressBar?.setProgress(Math.random() * 10 + 80);
8180
8316
  const outgoingHistoryFragment = changesState && !opts.replace && !isFullOutletNavigation
@@ -8245,21 +8381,34 @@ async function navigate(opts) {
8245
8381
  beforeScripts: async () => {
8246
8382
  if (!isFullOutletNavigation || currentHead)
8247
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
+ }
8248
8393
  const incomingTitle = doc.querySelector('title');
8249
8394
  if (incomingTitle) {
8250
8395
  document.title = incomingTitle.textContent || document.title;
8251
8396
  }
8252
- await updateHead(doc, transaction.controller.signal);
8397
+ await updateHead(doc, transaction.controller.signal, currentBaseUrl);
8253
8398
  assertActiveNavigation(transaction);
8254
8399
  },
8255
8400
  onCommitted: (committedTarget, roots) => {
8256
8401
  target = committedTarget;
8402
+ context.target = committedTarget;
8403
+ context.committed = true;
8404
+ progressBar?.reconnect();
8257
8405
  committedRoots = roots;
8258
8406
  }
8259
8407
  });
8408
+ context.committed = true;
8260
8409
  assertActiveNavigation(transaction);
8261
8410
  if (isFullOutletNavigation) {
8262
- await scriptNotInOutletTarget(doc, target, src, transaction.controller.signal);
8411
+ await scriptNotInOutletTarget(doc, target, src, transaction.controller.signal, currentBaseUrl);
8263
8412
  assertActiveNavigation(transaction);
8264
8413
  }
8265
8414
  }
@@ -8293,14 +8442,15 @@ async function navigate(opts) {
8293
8442
  await performUpdate();
8294
8443
  }
8295
8444
  assertActiveNavigation(transaction);
8296
- if (removeTriggerAfterCommit && opts.trigger instanceof HTMLElement && opts.trigger.isConnected) {
8445
+ if (removeTriggerAfterCommit && context.outcome !== 'http-error' && opts.trigger instanceof HTMLElement && opts.trigger.isConnected) {
8297
8446
  disposeEffects(opts.trigger);
8298
8447
  opts.trigger.remove();
8299
8448
  }
8300
8449
  if (hasTargetSpinner)
8301
8450
  hideTargetSpinner(transaction.spinner);
8302
8451
  transaction.spinner = null;
8303
- runNavigationHooks(afterNavigate, targetUrl);
8452
+ context.outcome ?? (context.outcome = 'success');
8453
+ runNavigationHooks(afterNavigate, targetUrl, context);
8304
8454
  log('[GyosRouter] navigated to', targetUrl);
8305
8455
  currentUrl = changesState
8306
8456
  ? canonicalUrl(targetUrl, true)
@@ -8316,11 +8466,15 @@ async function navigate(opts) {
8316
8466
  return;
8317
8467
  }
8318
8468
  if (isActiveNavigation(transaction)) {
8469
+ context.outcome ?? (context.outcome = 'error');
8319
8470
  console.error('[GyosRouter] navigation error', error);
8320
- fallbackFromBoost(opts, opts.url, true);
8471
+ fallback(opts.url, true);
8321
8472
  }
8322
8473
  }
8323
8474
  finally {
8475
+ if (transaction.controller.signal.aborted)
8476
+ context.outcome = 'aborted';
8477
+ context.outcome ?? (context.outcome = 'aborted');
8324
8478
  if (transaction.interval)
8325
8479
  clearInterval(transaction.interval);
8326
8480
  if (transaction.spinner)
@@ -8330,6 +8484,15 @@ async function navigate(opts) {
8330
8484
  progressBar?.complete();
8331
8485
  }
8332
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
+ }
8333
8496
  }
8334
8497
  }
8335
8498
  function shouldBoost(el) {
@@ -8438,16 +8601,34 @@ function onSubmit(event) {
8438
8601
  return;
8439
8602
  if (shouldDeferToFormValidation(form))
8440
8603
  return;
8441
- event.preventDefault();
8442
- const action = form.action || window.location.href;
8443
- const method = (form.method || 'GET').toUpperCase();
8444
- const url = new URL(action, window.location.href);
8445
- if (url.origin !== window.location.origin) {
8446
- 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 {
8447
8622
  return;
8448
8623
  }
8449
- const formData = new FormData(form);
8450
- 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' });
8451
8632
  }
8452
8633
  function onPopState(event) {
8453
8634
  const url = window.location.href;
@@ -8552,13 +8733,15 @@ const Gyos = {
8552
8733
  startRouter,
8553
8734
  onBeforeNavigate,
8554
8735
  onAfterNavigate,
8736
+ onBeforeSwap,
8737
+ onNavigationEnd,
8555
8738
  portalCreate,
8556
8739
  portalDestroy,
8557
8740
  setCspNonce,
8558
- version: '0.3.1'
8741
+ version: '0.4.0'
8559
8742
  };
8560
8743
 
8561
8744
  setExpressionRuntime(standardExpressionRuntime);
8562
8745
 
8563
- 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 };
8564
8747
  //# sourceMappingURL=gyos.esm.js.map