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.
@@ -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
  */
@@ -2196,59 +2196,59 @@ function applyTransitionStyles() {
2196
2196
  return;
2197
2197
  const style = document.createElement('style');
2198
2198
  style.id = styleId;
2199
- style.textContent = `
2200
- /* Opacity utilities */
2199
+ style.textContent = `
2200
+ /* Opacity utilities */
2201
2201
  .gyos-t-opacity-0 { opacity: 0; }
2202
2202
  .gyos-t-opacity-100 { opacity: 1; }
2203
-
2204
- /* Transform - Translate Y */
2203
+
2204
+ /* Transform - Translate Y */
2205
2205
  .gyos-t-translate-y-0 { transform: translateY(0); }
2206
2206
  .gyos-t-translate-y--100 { transform: translateY(-100%); }
2207
2207
  .gyos-t-translate-y-100 { transform: translateY(100%); }
2208
-
2209
- /* Transform - Translate X */
2208
+
2209
+ /* Transform - Translate X */
2210
2210
  .gyos-t-translate-x-0 { transform: translateX(0); }
2211
2211
  .gyos-t-translate-x--100 { transform: translateX(-100%); }
2212
2212
  .gyos-t-translate-x-100 { transform: translateX(100%); }
2213
-
2214
- /* Transform - Scale */
2213
+
2214
+ /* Transform - Scale */
2215
2215
  .gyos-t-scale-0 { transform: scale(0); }
2216
2216
  .gyos-t-scale-50 { transform: scale(0.5); }
2217
2217
  .gyos-t-scale-100 { transform: scale(1); }
2218
-
2219
- /* Animation Keyframes */
2220
- @keyframes gyos-fade-in {
2221
- from { opacity: 0; }
2222
- to { opacity: 1; }
2223
- }
2224
-
2225
- @keyframes gyos-fade-out {
2226
- from { opacity: 1; }
2227
- to { opacity: 0; }
2228
- }
2229
-
2230
- @keyframes gyos-slide-down {
2231
- from { transform: translateY(-100%); opacity: 0; }
2232
- to { transform: translateY(0); opacity: 1; }
2233
- }
2234
-
2235
- @keyframes gyos-slide-up {
2236
- from { transform: translateY(100%); opacity: 0; }
2237
- to { transform: translateY(0); opacity: 1; }
2238
- }
2239
-
2240
- @keyframes gyos-scale-in {
2241
- from { transform: scale(0); opacity: 0; }
2242
- to { transform: scale(1); opacity: 1; }
2243
- }
2244
-
2245
- @keyframes gyos-scale-out {
2246
- from { transform: scale(1); opacity: 1; }
2247
- to { transform: scale(0); opacity: 0; }
2248
- }
2249
-
2250
- [g-cloak] {
2251
- display: none !important;
2218
+
2219
+ /* Animation Keyframes */
2220
+ @keyframes gyos-fade-in {
2221
+ from { opacity: 0; }
2222
+ to { opacity: 1; }
2223
+ }
2224
+
2225
+ @keyframes gyos-fade-out {
2226
+ from { opacity: 1; }
2227
+ to { opacity: 0; }
2228
+ }
2229
+
2230
+ @keyframes gyos-slide-down {
2231
+ from { transform: translateY(-100%); opacity: 0; }
2232
+ to { transform: translateY(0); opacity: 1; }
2233
+ }
2234
+
2235
+ @keyframes gyos-slide-up {
2236
+ from { transform: translateY(100%); opacity: 0; }
2237
+ to { transform: translateY(0); opacity: 1; }
2238
+ }
2239
+
2240
+ @keyframes gyos-scale-in {
2241
+ from { transform: scale(0); opacity: 0; }
2242
+ to { transform: scale(1); opacity: 1; }
2243
+ }
2244
+
2245
+ @keyframes gyos-scale-out {
2246
+ from { transform: scale(1); opacity: 1; }
2247
+ to { transform: scale(0); opacity: 0; }
2248
+ }
2249
+
2250
+ [g-cloak] {
2251
+ display: none !important;
2252
2252
  }`;
2253
2253
  document.head.appendChild(style);
2254
2254
  }
@@ -6605,33 +6605,44 @@ class ProgressBar {
6605
6605
  getCurrentProgress() {
6606
6606
  return this.currentProgress;
6607
6607
  }
6608
+ reconnect() {
6609
+ if (!this.element || !this.progressBarEnabled || !document.body)
6610
+ return;
6611
+ // Snapshots may contain a clone of the runtime bar. Keep this instance.
6612
+ document.querySelectorAll('#gyos-progress-bar').forEach(node => {
6613
+ if (node !== this.element)
6614
+ node.remove();
6615
+ });
6616
+ if (!this.element.isConnected)
6617
+ document.body.appendChild(this.element);
6618
+ }
6608
6619
  createBar() {
6609
6620
  if (typeof document === 'undefined')
6610
6621
  return;
6611
6622
  // Create progress bar element
6612
6623
  this.element = document.createElement('div');
6613
6624
  this.element.id = 'gyos-progress-bar';
6614
- this.element.style.cssText = `
6615
- position: fixed;
6616
- top: 0;
6617
- left: 0;
6618
- width: 0%;
6619
- height: 6px;
6620
- background: var(--gyos-progress-color, linear-gradient(90deg, #aab9ff, #77889f));
6621
- z-index: 999999;
6622
- transition: width 0.3s linear, opacity 0.3s linear;
6623
- opacity: 0;
6624
- pointer-events: none;
6625
- box-shadow: 0 0 10px rgba(102, 126, 234, 0.5);
6625
+ this.element.style.cssText = `
6626
+ position: fixed;
6627
+ top: 0;
6628
+ left: 0;
6629
+ width: 0%;
6630
+ height: 6px;
6631
+ background: var(--gyos-progress-color, linear-gradient(90deg, #aab9ff, #77889f));
6632
+ z-index: 999999;
6633
+ transition: width 0.3s linear, opacity 0.3s linear;
6634
+ opacity: 0;
6635
+ pointer-events: none;
6636
+ box-shadow: 0 0 10px rgba(102, 126, 234, 0.5);
6626
6637
  `;
6627
6638
  // Insert into DOM when ready
6628
6639
  if (document.readyState === 'loading') {
6629
6640
  document.addEventListener('DOMContentLoaded', () => {
6630
- document.body.insertAdjacentElement('beforeend', this.element);
6631
- });
6641
+ this.reconnect();
6642
+ }, { once: true });
6632
6643
  }
6633
6644
  else {
6634
- document.body.insertAdjacentElement('beforeend', this.element);
6645
+ this.reconnect();
6635
6646
  }
6636
6647
  }
6637
6648
  start() {
@@ -6655,6 +6666,7 @@ class ProgressBar {
6655
6666
  setProgress(percent) {
6656
6667
  if (!this.element || !this.progressBarEnabled)
6657
6668
  return;
6669
+ this.reconnect();
6658
6670
  // Clamp between 0-100
6659
6671
  percent = Math.min(100, Math.max(0, percent));
6660
6672
  this.currentProgress = percent;
@@ -6703,41 +6715,41 @@ class ProgressBar {
6703
6715
  function createTargetSpinner() {
6704
6716
  const spinner = document.createElement('div');
6705
6717
  spinner.className = 'gyos-target-spinner';
6706
- spinner.innerHTML = `
6707
- <div class="gyos-spinner-content">
6708
- <svg class="gyos-spinner-icon" viewBox="0 0 50 50">
6709
- <circle cx="25" cy="25" r="20" fill="none" stroke="currentColor" stroke-width="4" stroke-dasharray="31.4 31.4" />
6710
- </svg>
6711
- </div>
6718
+ spinner.innerHTML = `
6719
+ <div class="gyos-spinner-content">
6720
+ <svg class="gyos-spinner-icon" viewBox="0 0 50 50">
6721
+ <circle cx="25" cy="25" r="20" fill="none" stroke="currentColor" stroke-width="4" stroke-dasharray="31.4 31.4" />
6722
+ </svg>
6723
+ </div>
6712
6724
  `;
6713
6725
  // Inject styles if not already present
6714
6726
  if (expressionRuntimeMode() === 'standard' && !document.getElementById('gyos-target-spinner-styles')) {
6715
6727
  const style = document.createElement('style');
6716
6728
  style.id = 'gyos-target-spinner-styles';
6717
- style.textContent = `
6718
- .gyos-target-spinner {
6719
- display: flex;
6720
- align-items: center;
6721
- justify-content: center;
6722
- padding: 20px;
6723
- min-height: 60px;
6724
- }
6725
- .gyos-spinner-content {
6726
- display: flex;
6727
- align-items: center;
6728
- gap: 10px;
6729
- color: var(--gyos-spinner-color, #667eea);
6730
- font-size: 14px;
6731
- }
6732
- .gyos-spinner-icon {
6733
- width: 24px;
6734
- height: 24px;
6735
- animation: gyos-spin 1s linear infinite;
6736
- }
6737
- @keyframes gyos-spin {
6738
- 0% { transform: rotate(0deg); }
6739
- 100% { transform: rotate(360deg); }
6740
- }
6729
+ style.textContent = `
6730
+ .gyos-target-spinner {
6731
+ display: flex;
6732
+ align-items: center;
6733
+ justify-content: center;
6734
+ padding: 20px;
6735
+ min-height: 60px;
6736
+ }
6737
+ .gyos-spinner-content {
6738
+ display: flex;
6739
+ align-items: center;
6740
+ gap: 10px;
6741
+ color: var(--gyos-spinner-color, #667eea);
6742
+ font-size: 14px;
6743
+ }
6744
+ .gyos-spinner-icon {
6745
+ width: 24px;
6746
+ height: 24px;
6747
+ animation: gyos-spin 1s linear infinite;
6748
+ }
6749
+ @keyframes gyos-spin {
6750
+ 0% { transform: rotate(0deg); }
6751
+ 100% { transform: rotate(360deg); }
6752
+ }
6741
6753
  `;
6742
6754
  document.head.appendChild(style);
6743
6755
  }
@@ -7097,8 +7109,8 @@ async function performSwap(target, src, mode, options = {}) {
7097
7109
  }
7098
7110
  result = target;
7099
7111
  }
7100
- await options.beforeScripts?.();
7101
7112
  options.onCommitted?.(result, normalized === 'append' || normalized === 'prepend' ? incomingChildren : [result]);
7113
+ await options.beforeScripts?.();
7102
7114
  // Additive swaps must not re-run scripts that already existed in the target.
7103
7115
  if (normalized === 'append' || normalized === 'prepend') {
7104
7116
  await executeScriptsInNodes(incomingChildren, options.signal);
@@ -7338,6 +7350,21 @@ function handleScroll(url, trigger, savedScroll) {
7338
7350
  window.scrollTo({ top: 0, behavior: 'smooth' });
7339
7351
  }
7340
7352
 
7353
+ // A retained relative URL still identifies the resource loaded on its original
7354
+ // page, even after pushState changes document.baseURI.
7355
+ const resourceUrls = new WeakMap();
7356
+ function rememberResourceUrls(root, baseUrl) {
7357
+ root.querySelectorAll('script[src], link[href]').forEach(node => {
7358
+ const attribute = node.tagName === 'SCRIPT' ? 'src' : 'href';
7359
+ const source = node.getAttribute(attribute);
7360
+ if (resourceUrls.get(node)?.source === source)
7361
+ return;
7362
+ try {
7363
+ resourceUrls.set(node, { source, url: new URL(source, baseUrl).href });
7364
+ }
7365
+ catch { /* Invalid resource URLs retain their literal identity. */ }
7366
+ });
7367
+ }
7341
7368
  function isNonceMeta(el) {
7342
7369
  return el.tagName === 'META' && el.getAttribute('name')?.toLowerCase() === 'csp-nonce';
7343
7370
  }
@@ -7355,7 +7382,20 @@ function serializeAttributes(el, context) {
7355
7382
  return;
7356
7383
  if (context.csp && isNonceMeta(el) && attr.name.toLowerCase() === 'content')
7357
7384
  return;
7358
- attributes.set(attr.name, attr.value);
7385
+ let value = attr.value;
7386
+ if ((el.tagName === 'SCRIPT' && attr.name === 'src') || (el.tagName === 'LINK' && attr.name === 'href')) {
7387
+ const cached = resourceUrls.get(el);
7388
+ if (cached?.source === value)
7389
+ value = cached.url;
7390
+ else {
7391
+ try {
7392
+ value = new URL(value, context.baseUrl || el.baseURI).href;
7393
+ resourceUrls.set(el, { source: attr.value, url: value });
7394
+ }
7395
+ catch { /* Keep invalid URLs distinct. */ }
7396
+ }
7397
+ }
7398
+ attributes.set(attr.name, value);
7359
7399
  });
7360
7400
  if (context.csp && usesCspNonce(el) && context.activeNonce) {
7361
7401
  attributes.set('nonce', context.activeNonce);
@@ -7422,19 +7462,21 @@ function warnSkippedNode(node) {
7422
7462
  console.warn('[GyosJS CSP] Skipped an inline MPA script because no active document nonce is configured.');
7423
7463
  }
7424
7464
  }
7425
- async function diffNodes(currentNodes, nextNodes, container = document.head, signal) {
7465
+ async function diffNodes(currentNodes, nextNodes, container = document.head, signal, currentBaseUrl = document.baseURI) {
7426
7466
  const csp = expressionRuntimeMode() === 'csp';
7427
7467
  const context = {
7428
7468
  csp,
7429
7469
  activeNonce: csp ? resolveCspNonce() : undefined
7430
7470
  };
7431
- const current = keyedNodes(currentNodes, context);
7471
+ const current = keyedNodes(currentNodes, { ...context, baseUrl: currentBaseUrl });
7432
7472
  const next = keyedNodes(nextNodes, context);
7473
+ const persistentKey = (node) => container === document.head ? node.getAttribute('g-head-persist') : null;
7474
+ const persistent = new Set(currentNodes.map(persistentKey).filter(Boolean));
7433
7475
  const currentKeys = new Set(current.map(item => item.key));
7434
7476
  const nextKeys = new Set(next.map(item => item.key));
7435
7477
  // Remove nodes that are not in the new head
7436
7478
  current.forEach(({ key, node }) => {
7437
- if (!nextKeys.has(key)) {
7479
+ if (!nextKeys.has(key) && !persistentKey(node)) {
7438
7480
  node.remove();
7439
7481
  }
7440
7482
  });
@@ -7442,6 +7484,8 @@ async function diffNodes(currentNodes, nextNodes, container = document.head, sig
7442
7484
  for (const { key, node } of next) {
7443
7485
  if (signal?.aborted)
7444
7486
  return;
7487
+ if (persistent.has(persistentKey(node)))
7488
+ continue;
7445
7489
  if (!currentKeys.has(key)) {
7446
7490
  if (!canInsertNode(node, context)) {
7447
7491
  warnSkippedNode(node);
@@ -7644,6 +7688,7 @@ function prepareNavigationHtml(html) {
7644
7688
  * MPA boost navigation inspired by Turbo Drive.
7645
7689
  * Implements attribute-driven routing, snapshot caching, and persistent islands.
7646
7690
  */
7691
+ const submittingForms = new WeakSet();
7647
7692
  const snapshots = new Map();
7648
7693
  const preloadCache = new Map();
7649
7694
  const preloadControllers = new Map();
@@ -7660,12 +7705,30 @@ let activeNavigation = null;
7660
7705
  let progressBar = null;
7661
7706
  const beforeNavigate = [];
7662
7707
  const afterNavigate = [];
7708
+ const beforeSwap = [];
7709
+ const navigationEnd = [];
7710
+ function registerNavigationHook(hooks, callback) {
7711
+ // A wrapper gives each registration its own unsubscribe identity.
7712
+ const entry = (url, context) => callback(url, context);
7713
+ hooks.push(entry);
7714
+ return () => {
7715
+ const index = hooks.indexOf(entry);
7716
+ if (index !== -1)
7717
+ hooks.splice(index, 1);
7718
+ };
7719
+ }
7663
7720
  // Expose hooks to register before/after navigation callbacks
7664
7721
  function onBeforeNavigate(callback) {
7665
- beforeNavigate.push(callback);
7722
+ return registerNavigationHook(beforeNavigate, callback);
7666
7723
  }
7667
7724
  function onAfterNavigate(callback) {
7668
- afterNavigate.push(callback);
7725
+ return registerNavigationHook(afterNavigate, callback);
7726
+ }
7727
+ function onBeforeSwap(callback) {
7728
+ return registerNavigationHook(beforeSwap, callback);
7729
+ }
7730
+ function onNavigationEnd(callback) {
7731
+ return registerNavigationHook(navigationEnd, (_url, context) => callback(context));
7669
7732
  }
7670
7733
  function startRouter(options) {
7671
7734
  // If not has g-boost attribute, do not start router
@@ -7689,6 +7752,7 @@ function startRouter(options) {
7689
7752
  }
7690
7753
  // Cache scripts from initial page to prevent re-execution on first navigation back
7691
7754
  cacheInitialPageScripts();
7755
+ rememberResourceUrls(document, document.baseURI);
7692
7756
  routerStarted = true;
7693
7757
  log('[GyosRouter] started');
7694
7758
  }
@@ -7745,9 +7809,13 @@ function resolveTarget(trigger, targetSelector, targetOutletIndex) {
7745
7809
  const outlet = findGlobalOutlet();
7746
7810
  return outlet instanceof HTMLElement ? outlet : null;
7747
7811
  }
7812
+ function isFullDocument(html) {
7813
+ return /^\s*(?:<!--[^]*?-->\s*)*(?:<!doctype\s+html\b|<html(?:\s|>))/i.test(html);
7814
+ }
7748
7815
  function saveSnapshot(url, html) {
7749
7816
  // create HTMLElement by html string to remove scripts and get clean snapshot
7750
7817
  const doc = parseNavigationDocument(html);
7818
+ doc.querySelectorAll('#gyos-progress-bar').forEach(node => node.remove());
7751
7819
  // Ignore hash for snapshot keys
7752
7820
  if (url.includes('#'))
7753
7821
  url = url.split('#')[0];
@@ -7756,7 +7824,7 @@ function saveSnapshot(url, html) {
7756
7824
  if (s.hasAttribute('g-script-once'))
7757
7825
  s.textContent = '';
7758
7826
  });
7759
- snapshots.set(url, { html: doc.documentElement.outerHTML });
7827
+ snapshots.set(url, { html: doc.documentElement.outerHTML, fullDocument: isFullDocument(html) });
7760
7828
  log('[GyosRouter] snapshot saved for', url);
7761
7829
  }
7762
7830
  function getOutletIndex(root, target) {
@@ -7868,10 +7936,10 @@ function consumeViewTransitionRejection(promise) {
7868
7936
  // update callback remains the navigation source of truth and is awaited below.
7869
7937
  void promise?.catch(() => undefined);
7870
7938
  }
7871
- function runNavigationHooks(callbacks, url) {
7872
- callbacks.forEach(callback => {
7939
+ function runNavigationHooks(callbacks, url, context) {
7940
+ [...callbacks].forEach(callback => {
7873
7941
  try {
7874
- callback(url);
7942
+ callback(url, { ...context });
7875
7943
  }
7876
7944
  catch (error) {
7877
7945
  console.error('[GyosRouter] navigation hook error', error);
@@ -7909,7 +7977,13 @@ function buildRequest(opts) {
7909
7977
  url = mergeFormDataIntoUrl(url, opts.formData);
7910
7978
  }
7911
7979
  else {
7912
- init.body = opts.formData;
7980
+ if (opts.formEncoding === 'application/x-www-form-urlencoded') {
7981
+ const encoded = new URLSearchParams();
7982
+ opts.formData.forEach((value, name) => encoded.append(name, typeof value === 'string' ? value : value.name));
7983
+ init.body = encoded;
7984
+ }
7985
+ else
7986
+ init.body = opts.formData;
7913
7987
  }
7914
7988
  }
7915
7989
  else if (opts.jsonData) {
@@ -7952,25 +8026,26 @@ function preload(url) {
7952
8026
  preloadControllers.delete(cacheKey);
7953
8027
  });
7954
8028
  }
7955
- async function updateHead(fromDoc, signal) {
8029
+ async function updateHead(fromDoc, signal, currentBaseUrl) {
7956
8030
  const allowedSelector = 'meta, link, style:not(#gyos-transitions), script';
7957
8031
  const currentNodes = Array.from(document.head.querySelectorAll(allowedSelector));
7958
8032
  const nextNodes = Array.from(fromDoc.head.querySelectorAll(allowedSelector));
7959
- await diffNodes(currentNodes, nextNodes, document.head, signal);
8033
+ await diffNodes(currentNodes, nextNodes, document.head, signal, currentBaseUrl);
7960
8034
  }
7961
- async function scriptNotInOutletTarget(fromDoc, target, source, signal) {
8035
+ async function scriptNotInOutletTarget(fromDoc, target, source, signal, currentBaseUrl) {
7962
8036
  // scripts in current document and it not in target outlet
7963
8037
  const currentScripts = Array.from(document.scripts).filter(s => !target.contains(s) && !document.head.contains(s));
7964
8038
  // scripts in fromDoc and it not in source outlet
7965
8039
  const incomingScripts = Array.from(fromDoc.scripts).filter(s => !source.contains(s) && !fromDoc.head.contains(s));
7966
8040
  // Diff and update scripts not in outlet/target
7967
- await diffNodes(currentScripts, incomingScripts, document.body, signal);
8041
+ await diffNodes(currentScripts, incomingScripts, document.body, signal, currentBaseUrl);
7968
8042
  }
7969
8043
  function resolveIncomingScriptUrls(root, baseUrl) {
7970
- root.querySelectorAll('script[src]').forEach(script => {
7971
- const source = script.getAttribute('src');
8044
+ root.querySelectorAll('script[src], link[href]').forEach(node => {
8045
+ const attribute = node.tagName === 'SCRIPT' ? 'src' : 'href';
8046
+ const source = node.getAttribute(attribute);
7972
8047
  if (source)
7973
- script.src = new URL(source, baseUrl).href;
8048
+ node.setAttribute(attribute, new URL(source, baseUrl).href);
7974
8049
  });
7975
8050
  }
7976
8051
  function isNavigableHtmlResponse(response) {
@@ -8024,6 +8099,22 @@ async function navigate(opts) {
8024
8099
  resolveDone
8025
8100
  };
8026
8101
  activeNavigation = transaction;
8102
+ const currentBaseUrl = document.baseURI;
8103
+ rememberResourceUrls(document, currentBaseUrl);
8104
+ const context = {
8105
+ from: currentUrl, url: opts.url, method: opts.method.toUpperCase(),
8106
+ trigger: opts.trigger || null, target: null, form: opts.form || null,
8107
+ popstate: opts.popstate === true, signal: transaction.controller.signal,
8108
+ status: null, committed: false, fallback: false, outcome: null
8109
+ };
8110
+ const formEvent = opts.form
8111
+ ? { form: opts.form, url: opts.url, status: null, outcome: null, committed: false, fallback: false }
8112
+ : null;
8113
+ const fallback = (url, requestSent) => {
8114
+ context.fallback = context.method === 'GET' || (!requestSent && !!opts.form);
8115
+ context.outcome ?? (context.outcome = context.fallback ? 'fallback' : 'invalid-response');
8116
+ fallbackFromBoost(opts, url, requestSent);
8117
+ };
8027
8118
  const hasTargetSpinner = opts.trigger?.hasAttribute('g-router-spin');
8028
8119
  const setRand = () => {
8029
8120
  if (isActiveNavigation(transaction) && progressBar?.getCurrentProgress() < 70) {
@@ -8031,7 +8122,10 @@ async function navigate(opts) {
8031
8122
  }
8032
8123
  };
8033
8124
  try {
8034
- runNavigationHooks(beforeNavigate, opts.url);
8125
+ if (formEvent)
8126
+ document.dispatchEvent(new CustomEvent('gyos:form-start', { detail: { ...formEvent } }));
8127
+ runNavigationHooks(beforeNavigate, opts.url, context);
8128
+ assertActiveNavigation(transaction);
8035
8129
  progressBar?.start();
8036
8130
  // popstate already points history at the destination entry. Keep the visible
8037
8131
  // page's position under currentUrl without overwriting that destination state.
@@ -8040,9 +8134,10 @@ async function navigate(opts) {
8040
8134
  saveScrollPosition();
8041
8135
  // Pick target element to swap
8042
8136
  let target = resolveTarget(opts.trigger, opts.targetSelector, opts.targetOutletIndex);
8137
+ context.target = target;
8043
8138
  if (!target) {
8044
8139
  if (isActiveNavigation(transaction))
8045
- fallbackFromBoost(opts, opts.url, false);
8140
+ fallback(opts.url, false);
8046
8141
  return;
8047
8142
  }
8048
8143
  const swapMode = (opts.swapMode || opts.trigger?.getAttribute('g-swap') || 'inner').toLowerCase();
@@ -8067,6 +8162,7 @@ async function navigate(opts) {
8067
8162
  if (hasTargetSpinner)
8068
8163
  transaction.spinner = showTargetSpinner(target, swapMode);
8069
8164
  const { finalUrl, init } = buildRequest(opts);
8165
+ context.url = finalUrl;
8070
8166
  // Add abort signal to request
8071
8167
  init.signal = transaction.controller.signal;
8072
8168
  let html;
@@ -8094,7 +8190,8 @@ async function navigate(opts) {
8094
8190
  if (error.name === 'AbortError')
8095
8191
  throw error;
8096
8192
  assertActiveNavigation(transaction);
8097
- window.location.href = finalUrl;
8193
+ context.outcome = 'network-error';
8194
+ fallback(finalUrl, true);
8098
8195
  return;
8099
8196
  }
8100
8197
  preloadCache.delete(preloadKey); // consume cache
@@ -8119,28 +8216,46 @@ async function navigate(opts) {
8119
8216
  log('[GyosRouter] Navigation cancelled');
8120
8217
  return;
8121
8218
  }
8219
+ context.outcome = 'network-error';
8122
8220
  if (isActiveNavigation(transaction))
8123
- fallbackFromBoost(opts, finalUrl, true);
8221
+ fallback(finalUrl, true);
8124
8222
  return;
8125
8223
  }
8126
8224
  }
8127
8225
  assertActiveNavigation(transaction);
8128
- // If response not ok, fallback to full navigation
8129
- if (!response || !response.ok || !isNavigableHtmlResponse(response)) {
8226
+ context.status = response?.status ?? null;
8227
+ context.url = response?.url || finalUrl;
8228
+ const acceptedErrors = (opts.trigger?.getAttribute('g-boost-errors') || '').split(/[\s,]+/);
8229
+ const renderHttpError = !!response && response.status >= 400 && response.status <= 599
8230
+ && acceptedErrors.includes(String(response.status));
8231
+ if (response && !response.ok)
8232
+ context.outcome = 'http-error';
8233
+ if (!response || (!response.ok && !renderHttpError) || !isNavigableHtmlResponse(response)) {
8234
+ context.outcome ?? (context.outcome = 'invalid-response');
8130
8235
  if (isActiveNavigation(transaction))
8131
- fallbackFromBoost(opts, finalUrl, true);
8236
+ fallback(finalUrl, true);
8132
8237
  return;
8133
8238
  }
8134
8239
  html = await response.text();
8135
8240
  assertActiveNavigation(transaction);
8136
- if (!opts.popstate && target.hasAttribute('g-snapshot')) {
8137
- saveSnapshot(canonicalUrl(response.url || finalUrl), html);
8138
- }
8139
8241
  }
8140
8242
  // Parse HTML
8141
8243
  const doc = html
8142
8244
  ? parseNavigationDocument(html)
8143
8245
  : document.implementation.createHTMLDocument();
8246
+ // Detached parsing cannot tell whether the live CSP permits an incoming base.
8247
+ // Let native navigation enforce base-uri instead of authorizing its URLs ourselves.
8248
+ if (doc.querySelector('base[href]') || opts.historyFragment?.querySelector('base[href]')) {
8249
+ context.outcome = 'invalid-response';
8250
+ fallback(response?.url || finalUrl, true);
8251
+ return;
8252
+ }
8253
+ if (response?.ok && !opts.popstate && target.hasAttribute('g-snapshot')) {
8254
+ saveSnapshot(canonicalUrl(response.url || finalUrl), html);
8255
+ }
8256
+ const syncDocumentAttributes = isFullOutletNavigation && destructiveSwap && !currentHead
8257
+ && !opts.historyFragment && (opts.popstate && snapshots.has(urlWithoutHash)
8258
+ ? snapshots.get(urlWithoutHash).fullDocument : isFullDocument(html || ''));
8144
8259
  // Pick source fragment
8145
8260
  const src = opts.historyFragment || pickSourceFragment(doc, target, targetOutletIndex);
8146
8261
  stripInertFallbackContent(src);
@@ -8152,15 +8267,18 @@ async function navigate(opts) {
8152
8267
  targetUrl += finalUrl.substring(finalUrl.indexOf('#'));
8153
8268
  }
8154
8269
  resolveIncomingScriptUrls(doc, targetUrl);
8270
+ context.url = targetUrl;
8155
8271
  if (opts.historyFragment)
8156
8272
  resolveIncomingScriptUrls(src, targetUrl);
8157
8273
  const triggerChangesState = opts.trigger?.hasAttribute('g-change-state') || false;
8158
8274
  const keepsCurrentState = opts.trigger?.hasAttribute('g-current-state') || false;
8159
8275
  const redirectedSubmission = opts.method.toUpperCase() !== 'GET' && response?.redirected === true;
8160
- const changesState = !keepsCurrentState && (opts.changeState === true || triggerChangesState || redirectedSubmission);
8276
+ const changesState = context.outcome !== 'http-error' && !keepsCurrentState && (opts.changeState === true || triggerChangesState || redirectedSubmission);
8161
8277
  const performUpdate = async () => {
8162
8278
  assertActiveNavigation(transaction);
8163
8279
  transaction.committing = true;
8280
+ runNavigationHooks(beforeSwap, targetUrl, context);
8281
+ assertActiveNavigation(transaction);
8164
8282
  // Update progress to rand 80 - 90% before swap
8165
8283
  progressBar?.setProgress(Math.random() * 10 + 80);
8166
8284
  const outgoingHistoryFragment = changesState && !opts.replace && !isFullOutletNavigation
@@ -8231,21 +8349,34 @@ async function navigate(opts) {
8231
8349
  beforeScripts: async () => {
8232
8350
  if (!isFullOutletNavigation || currentHead)
8233
8351
  return;
8352
+ if (syncDocumentAttributes) {
8353
+ for (const name of ['lang', 'dir']) {
8354
+ const value = doc.documentElement.getAttribute(name);
8355
+ if (value === null)
8356
+ document.documentElement.removeAttribute(name);
8357
+ else
8358
+ document.documentElement.setAttribute(name, value);
8359
+ }
8360
+ }
8234
8361
  const incomingTitle = doc.querySelector('title');
8235
8362
  if (incomingTitle) {
8236
8363
  document.title = incomingTitle.textContent || document.title;
8237
8364
  }
8238
- await updateHead(doc, transaction.controller.signal);
8365
+ await updateHead(doc, transaction.controller.signal, currentBaseUrl);
8239
8366
  assertActiveNavigation(transaction);
8240
8367
  },
8241
8368
  onCommitted: (committedTarget, roots) => {
8242
8369
  target = committedTarget;
8370
+ context.target = committedTarget;
8371
+ context.committed = true;
8372
+ progressBar?.reconnect();
8243
8373
  committedRoots = roots;
8244
8374
  }
8245
8375
  });
8376
+ context.committed = true;
8246
8377
  assertActiveNavigation(transaction);
8247
8378
  if (isFullOutletNavigation) {
8248
- await scriptNotInOutletTarget(doc, target, src, transaction.controller.signal);
8379
+ await scriptNotInOutletTarget(doc, target, src, transaction.controller.signal, currentBaseUrl);
8249
8380
  assertActiveNavigation(transaction);
8250
8381
  }
8251
8382
  }
@@ -8279,14 +8410,15 @@ async function navigate(opts) {
8279
8410
  await performUpdate();
8280
8411
  }
8281
8412
  assertActiveNavigation(transaction);
8282
- if (removeTriggerAfterCommit && opts.trigger instanceof HTMLElement && opts.trigger.isConnected) {
8413
+ if (removeTriggerAfterCommit && context.outcome !== 'http-error' && opts.trigger instanceof HTMLElement && opts.trigger.isConnected) {
8283
8414
  disposeEffects(opts.trigger);
8284
8415
  opts.trigger.remove();
8285
8416
  }
8286
8417
  if (hasTargetSpinner)
8287
8418
  hideTargetSpinner(transaction.spinner);
8288
8419
  transaction.spinner = null;
8289
- runNavigationHooks(afterNavigate, targetUrl);
8420
+ context.outcome ?? (context.outcome = 'success');
8421
+ runNavigationHooks(afterNavigate, targetUrl, context);
8290
8422
  log('[GyosRouter] navigated to', targetUrl);
8291
8423
  currentUrl = changesState
8292
8424
  ? canonicalUrl(targetUrl, true)
@@ -8302,11 +8434,15 @@ async function navigate(opts) {
8302
8434
  return;
8303
8435
  }
8304
8436
  if (isActiveNavigation(transaction)) {
8437
+ context.outcome ?? (context.outcome = 'error');
8305
8438
  console.error('[GyosRouter] navigation error', error);
8306
- fallbackFromBoost(opts, opts.url, true);
8439
+ fallback(opts.url, true);
8307
8440
  }
8308
8441
  }
8309
8442
  finally {
8443
+ if (transaction.controller.signal.aborted)
8444
+ context.outcome = 'aborted';
8445
+ context.outcome ?? (context.outcome = 'aborted');
8310
8446
  if (transaction.interval)
8311
8447
  clearInterval(transaction.interval);
8312
8448
  if (transaction.spinner)
@@ -8316,6 +8452,15 @@ async function navigate(opts) {
8316
8452
  progressBar?.complete();
8317
8453
  }
8318
8454
  transaction.resolveDone();
8455
+ if (formEvent)
8456
+ submittingForms.delete(formEvent.form);
8457
+ runNavigationHooks(navigationEnd, context.url, context);
8458
+ if (formEvent) {
8459
+ const { url, status, outcome, committed, fallback } = context;
8460
+ document.dispatchEvent(new CustomEvent('gyos:form-end', {
8461
+ detail: { ...formEvent, url, status, outcome, committed, fallback }
8462
+ }));
8463
+ }
8319
8464
  }
8320
8465
  }
8321
8466
  function shouldBoost(el) {
@@ -8424,16 +8569,34 @@ function onSubmit(event) {
8424
8569
  return;
8425
8570
  if (shouldDeferToFormValidation(form))
8426
8571
  return;
8427
- event.preventDefault();
8428
- const action = form.action || window.location.href;
8429
- const method = (form.method || 'GET').toUpperCase();
8430
- const url = new URL(action, window.location.href);
8431
- if (url.origin !== window.location.origin) {
8432
- window.location.href = url.toString();
8572
+ const submitter = event.submitter;
8573
+ const override = (name) => submitter?.getAttribute(`form${name}`) ?? form.getAttribute(name);
8574
+ const target = override('target') ?? document.querySelector('base[target]')?.getAttribute('target');
8575
+ const declaredMethod = (override('method') || 'GET').toUpperCase();
8576
+ const method = ['GET', 'POST', 'DIALOG'].includes(declaredMethod) ? declaredMethod : 'GET';
8577
+ const formEncoding = override('enctype')?.toLowerCase();
8578
+ if ((target && target.toLowerCase() !== '_self') || method === 'DIALOG' || formEncoding === 'text/plain')
8579
+ return;
8580
+ if (!resolveTarget(form))
8581
+ return;
8582
+ // Image submitters carry click coordinates which SubmitEvent does not expose.
8583
+ if (submitter instanceof HTMLInputElement && submitter.type === 'image')
8584
+ return;
8585
+ let url;
8586
+ try {
8587
+ url = new URL(override('action') || window.location.href, document.baseURI);
8588
+ }
8589
+ catch {
8433
8590
  return;
8434
8591
  }
8435
- const formData = new FormData(form);
8436
- navigate({ url: url.toString(), method, trigger: form, form, formData, changeState: method === 'GET' });
8592
+ if (url.origin !== window.location.origin)
8593
+ return;
8594
+ event.preventDefault();
8595
+ if (submittingForms.has(form))
8596
+ return;
8597
+ const formData = new FormData(form, submitter);
8598
+ submittingForms.add(form);
8599
+ void navigate({ url: url.toString(), method, trigger: form, form, formData, formEncoding, changeState: method === 'GET' });
8437
8600
  }
8438
8601
  function onPopState(event) {
8439
8602
  const url = window.location.href;
@@ -8538,10 +8701,12 @@ const Gyos = {
8538
8701
  startRouter,
8539
8702
  onBeforeNavigate,
8540
8703
  onAfterNavigate,
8704
+ onBeforeSwap,
8705
+ onNavigationEnd,
8541
8706
  portalCreate,
8542
8707
  portalDestroy,
8543
8708
  setCspNonce,
8544
- version: '0.3.2'
8709
+ version: '0.4.0'
8545
8710
  };
8546
8711
 
8547
8712
  const standardExpressionRuntime = {