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.
@@ -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
  */
@@ -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
  }
@@ -5183,6 +5183,10 @@ function processStructuralDirectives(elements, scope) {
5183
5183
  const structuralElements = [];
5184
5184
  const root = elements[0];
5185
5185
  elements.forEach(el => {
5186
+ // Await branches are detached and parsed only after their alias scope exists.
5187
+ // Do not evaluate nested structural expressions during the parent scan.
5188
+ if (isAwaitBranchDescendant(el))
5189
+ return;
5186
5190
  const hasIf = el.hasAttribute('*if');
5187
5191
  const hasFor = el.hasAttribute('*for');
5188
5192
  const hasSwitch = el.hasAttribute('*switch');
@@ -5227,6 +5231,20 @@ function processStructuralDirectives(elements, scope) {
5227
5231
  }
5228
5232
  });
5229
5233
  }
5234
+ function isAwaitBranchDescendant(element) {
5235
+ let child = element;
5236
+ let parent = element.parentElement;
5237
+ while (parent && parent !== document.body) {
5238
+ if (parent.hasAttribute('*await') && (child.hasAttribute('*pending') ||
5239
+ child.hasAttribute('*then') ||
5240
+ child.hasAttribute('*catch'))) {
5241
+ return true;
5242
+ }
5243
+ child = parent;
5244
+ parent = parent.parentElement;
5245
+ }
5246
+ return false;
5247
+ }
5230
5248
  const elementBelongsToAnotherScope = (el, scope) => {
5231
5249
  const owner = getScopeFromElement(el);
5232
5250
  return Boolean(owner && owner !== scope);
@@ -6587,33 +6605,44 @@ class ProgressBar {
6587
6605
  getCurrentProgress() {
6588
6606
  return this.currentProgress;
6589
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
+ }
6590
6619
  createBar() {
6591
6620
  if (typeof document === 'undefined')
6592
6621
  return;
6593
6622
  // Create progress bar element
6594
6623
  this.element = document.createElement('div');
6595
6624
  this.element.id = 'gyos-progress-bar';
6596
- this.element.style.cssText = `
6597
- position: fixed;
6598
- top: 0;
6599
- left: 0;
6600
- width: 0%;
6601
- height: 6px;
6602
- background: var(--gyos-progress-color, linear-gradient(90deg, #aab9ff, #77889f));
6603
- z-index: 999999;
6604
- transition: width 0.3s linear, opacity 0.3s linear;
6605
- opacity: 0;
6606
- pointer-events: none;
6607
- 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);
6608
6637
  `;
6609
6638
  // Insert into DOM when ready
6610
6639
  if (document.readyState === 'loading') {
6611
6640
  document.addEventListener('DOMContentLoaded', () => {
6612
- document.body.insertAdjacentElement('beforeend', this.element);
6613
- });
6641
+ this.reconnect();
6642
+ }, { once: true });
6614
6643
  }
6615
6644
  else {
6616
- document.body.insertAdjacentElement('beforeend', this.element);
6645
+ this.reconnect();
6617
6646
  }
6618
6647
  }
6619
6648
  start() {
@@ -6637,6 +6666,7 @@ class ProgressBar {
6637
6666
  setProgress(percent) {
6638
6667
  if (!this.element || !this.progressBarEnabled)
6639
6668
  return;
6669
+ this.reconnect();
6640
6670
  // Clamp between 0-100
6641
6671
  percent = Math.min(100, Math.max(0, percent));
6642
6672
  this.currentProgress = percent;
@@ -6685,41 +6715,41 @@ class ProgressBar {
6685
6715
  function createTargetSpinner() {
6686
6716
  const spinner = document.createElement('div');
6687
6717
  spinner.className = 'gyos-target-spinner';
6688
- spinner.innerHTML = `
6689
- <div class="gyos-spinner-content">
6690
- <svg class="gyos-spinner-icon" viewBox="0 0 50 50">
6691
- <circle cx="25" cy="25" r="20" fill="none" stroke="currentColor" stroke-width="4" stroke-dasharray="31.4 31.4" />
6692
- </svg>
6693
- </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>
6694
6724
  `;
6695
6725
  // Inject styles if not already present
6696
6726
  if (expressionRuntimeMode() === 'standard' && !document.getElementById('gyos-target-spinner-styles')) {
6697
6727
  const style = document.createElement('style');
6698
6728
  style.id = 'gyos-target-spinner-styles';
6699
- style.textContent = `
6700
- .gyos-target-spinner {
6701
- display: flex;
6702
- align-items: center;
6703
- justify-content: center;
6704
- padding: 20px;
6705
- min-height: 60px;
6706
- }
6707
- .gyos-spinner-content {
6708
- display: flex;
6709
- align-items: center;
6710
- gap: 10px;
6711
- color: var(--gyos-spinner-color, #667eea);
6712
- font-size: 14px;
6713
- }
6714
- .gyos-spinner-icon {
6715
- width: 24px;
6716
- height: 24px;
6717
- animation: gyos-spin 1s linear infinite;
6718
- }
6719
- @keyframes gyos-spin {
6720
- 0% { transform: rotate(0deg); }
6721
- 100% { transform: rotate(360deg); }
6722
- }
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
+ }
6723
6753
  `;
6724
6754
  document.head.appendChild(style);
6725
6755
  }
@@ -7093,8 +7123,8 @@ async function performSwap(target, src, mode, options = {}) {
7093
7123
  }
7094
7124
  result = target;
7095
7125
  }
7096
- await options.beforeScripts?.();
7097
7126
  options.onCommitted?.(result, normalized === 'append' || normalized === 'prepend' ? incomingChildren : [result]);
7127
+ await options.beforeScripts?.();
7098
7128
  // Additive swaps must not re-run scripts that already existed in the target.
7099
7129
  if (normalized === 'append' || normalized === 'prepend') {
7100
7130
  await executeScriptsInNodes(incomingChildren, options.signal);
@@ -7334,6 +7364,21 @@ function handleScroll(url, trigger, savedScroll) {
7334
7364
  window.scrollTo({ top: 0, behavior: 'smooth' });
7335
7365
  }
7336
7366
 
7367
+ // A retained relative URL still identifies the resource loaded on its original
7368
+ // page, even after pushState changes document.baseURI.
7369
+ const resourceUrls = new WeakMap();
7370
+ function rememberResourceUrls(root, baseUrl) {
7371
+ root.querySelectorAll('script[src], link[href]').forEach(node => {
7372
+ const attribute = node.tagName === 'SCRIPT' ? 'src' : 'href';
7373
+ const source = node.getAttribute(attribute);
7374
+ if (resourceUrls.get(node)?.source === source)
7375
+ return;
7376
+ try {
7377
+ resourceUrls.set(node, { source, url: new URL(source, baseUrl).href });
7378
+ }
7379
+ catch { /* Invalid resource URLs retain their literal identity. */ }
7380
+ });
7381
+ }
7337
7382
  function isNonceMeta(el) {
7338
7383
  return el.tagName === 'META' && el.getAttribute('name')?.toLowerCase() === 'csp-nonce';
7339
7384
  }
@@ -7351,7 +7396,20 @@ function serializeAttributes(el, context) {
7351
7396
  return;
7352
7397
  if (context.csp && isNonceMeta(el) && attr.name.toLowerCase() === 'content')
7353
7398
  return;
7354
- attributes.set(attr.name, attr.value);
7399
+ let value = attr.value;
7400
+ if ((el.tagName === 'SCRIPT' && attr.name === 'src') || (el.tagName === 'LINK' && attr.name === 'href')) {
7401
+ const cached = resourceUrls.get(el);
7402
+ if (cached?.source === value)
7403
+ value = cached.url;
7404
+ else {
7405
+ try {
7406
+ value = new URL(value, context.baseUrl || el.baseURI).href;
7407
+ resourceUrls.set(el, { source: attr.value, url: value });
7408
+ }
7409
+ catch { /* Keep invalid URLs distinct. */ }
7410
+ }
7411
+ }
7412
+ attributes.set(attr.name, value);
7355
7413
  });
7356
7414
  if (context.csp && usesCspNonce(el) && context.activeNonce) {
7357
7415
  attributes.set('nonce', context.activeNonce);
@@ -7418,19 +7476,21 @@ function warnSkippedNode(node) {
7418
7476
  console.warn('[GyosJS CSP] Skipped an inline MPA script because no active document nonce is configured.');
7419
7477
  }
7420
7478
  }
7421
- async function diffNodes(currentNodes, nextNodes, container = document.head, signal) {
7479
+ async function diffNodes(currentNodes, nextNodes, container = document.head, signal, currentBaseUrl = document.baseURI) {
7422
7480
  const csp = expressionRuntimeMode() === 'csp';
7423
7481
  const context = {
7424
7482
  csp,
7425
7483
  activeNonce: csp ? resolveCspNonce() : undefined
7426
7484
  };
7427
- const current = keyedNodes(currentNodes, context);
7485
+ const current = keyedNodes(currentNodes, { ...context, baseUrl: currentBaseUrl });
7428
7486
  const next = keyedNodes(nextNodes, context);
7487
+ const persistentKey = (node) => container === document.head ? node.getAttribute('g-head-persist') : null;
7488
+ const persistent = new Set(currentNodes.map(persistentKey).filter(Boolean));
7429
7489
  const currentKeys = new Set(current.map(item => item.key));
7430
7490
  const nextKeys = new Set(next.map(item => item.key));
7431
7491
  // Remove nodes that are not in the new head
7432
7492
  current.forEach(({ key, node }) => {
7433
- if (!nextKeys.has(key)) {
7493
+ if (!nextKeys.has(key) && !persistentKey(node)) {
7434
7494
  node.remove();
7435
7495
  }
7436
7496
  });
@@ -7438,6 +7498,8 @@ async function diffNodes(currentNodes, nextNodes, container = document.head, sig
7438
7498
  for (const { key, node } of next) {
7439
7499
  if (signal?.aborted)
7440
7500
  return;
7501
+ if (persistent.has(persistentKey(node)))
7502
+ continue;
7441
7503
  if (!currentKeys.has(key)) {
7442
7504
  if (!canInsertNode(node, context)) {
7443
7505
  warnSkippedNode(node);
@@ -7640,6 +7702,7 @@ function prepareNavigationHtml(html) {
7640
7702
  * MPA boost navigation inspired by Turbo Drive.
7641
7703
  * Implements attribute-driven routing, snapshot caching, and persistent islands.
7642
7704
  */
7705
+ const submittingForms = new WeakSet();
7643
7706
  const snapshots = new Map();
7644
7707
  const preloadCache = new Map();
7645
7708
  const preloadControllers = new Map();
@@ -7656,12 +7719,30 @@ let activeNavigation = null;
7656
7719
  let progressBar = null;
7657
7720
  const beforeNavigate = [];
7658
7721
  const afterNavigate = [];
7722
+ const beforeSwap = [];
7723
+ const navigationEnd = [];
7724
+ function registerNavigationHook(hooks, callback) {
7725
+ // A wrapper gives each registration its own unsubscribe identity.
7726
+ const entry = (url, context) => callback(url, context);
7727
+ hooks.push(entry);
7728
+ return () => {
7729
+ const index = hooks.indexOf(entry);
7730
+ if (index !== -1)
7731
+ hooks.splice(index, 1);
7732
+ };
7733
+ }
7659
7734
  // Expose hooks to register before/after navigation callbacks
7660
7735
  function onBeforeNavigate(callback) {
7661
- beforeNavigate.push(callback);
7736
+ return registerNavigationHook(beforeNavigate, callback);
7662
7737
  }
7663
7738
  function onAfterNavigate(callback) {
7664
- afterNavigate.push(callback);
7739
+ return registerNavigationHook(afterNavigate, callback);
7740
+ }
7741
+ function onBeforeSwap(callback) {
7742
+ return registerNavigationHook(beforeSwap, callback);
7743
+ }
7744
+ function onNavigationEnd(callback) {
7745
+ return registerNavigationHook(navigationEnd, (_url, context) => callback(context));
7665
7746
  }
7666
7747
  function startRouter(options) {
7667
7748
  // If not has g-boost attribute, do not start router
@@ -7685,6 +7766,7 @@ function startRouter(options) {
7685
7766
  }
7686
7767
  // Cache scripts from initial page to prevent re-execution on first navigation back
7687
7768
  cacheInitialPageScripts();
7769
+ rememberResourceUrls(document, document.baseURI);
7688
7770
  routerStarted = true;
7689
7771
  log('[GyosRouter] started');
7690
7772
  }
@@ -7741,9 +7823,13 @@ function resolveTarget(trigger, targetSelector, targetOutletIndex) {
7741
7823
  const outlet = findGlobalOutlet();
7742
7824
  return outlet instanceof HTMLElement ? outlet : null;
7743
7825
  }
7826
+ function isFullDocument(html) {
7827
+ return /^\s*(?:<!--[^]*?-->\s*)*(?:<!doctype\s+html\b|<html(?:\s|>))/i.test(html);
7828
+ }
7744
7829
  function saveSnapshot(url, html) {
7745
7830
  // create HTMLElement by html string to remove scripts and get clean snapshot
7746
7831
  const doc = parseNavigationDocument(html);
7832
+ doc.querySelectorAll('#gyos-progress-bar').forEach(node => node.remove());
7747
7833
  // Ignore hash for snapshot keys
7748
7834
  if (url.includes('#'))
7749
7835
  url = url.split('#')[0];
@@ -7752,7 +7838,7 @@ function saveSnapshot(url, html) {
7752
7838
  if (s.hasAttribute('g-script-once'))
7753
7839
  s.textContent = '';
7754
7840
  });
7755
- snapshots.set(url, { html: doc.documentElement.outerHTML });
7841
+ snapshots.set(url, { html: doc.documentElement.outerHTML, fullDocument: isFullDocument(html) });
7756
7842
  log('[GyosRouter] snapshot saved for', url);
7757
7843
  }
7758
7844
  function getOutletIndex(root, target) {
@@ -7864,10 +7950,10 @@ function consumeViewTransitionRejection(promise) {
7864
7950
  // update callback remains the navigation source of truth and is awaited below.
7865
7951
  void promise?.catch(() => undefined);
7866
7952
  }
7867
- function runNavigationHooks(callbacks, url) {
7868
- callbacks.forEach(callback => {
7953
+ function runNavigationHooks(callbacks, url, context) {
7954
+ [...callbacks].forEach(callback => {
7869
7955
  try {
7870
- callback(url);
7956
+ callback(url, { ...context });
7871
7957
  }
7872
7958
  catch (error) {
7873
7959
  console.error('[GyosRouter] navigation hook error', error);
@@ -7905,7 +7991,13 @@ function buildRequest(opts) {
7905
7991
  url = mergeFormDataIntoUrl(url, opts.formData);
7906
7992
  }
7907
7993
  else {
7908
- init.body = opts.formData;
7994
+ if (opts.formEncoding === 'application/x-www-form-urlencoded') {
7995
+ const encoded = new URLSearchParams();
7996
+ opts.formData.forEach((value, name) => encoded.append(name, typeof value === 'string' ? value : value.name));
7997
+ init.body = encoded;
7998
+ }
7999
+ else
8000
+ init.body = opts.formData;
7909
8001
  }
7910
8002
  }
7911
8003
  else if (opts.jsonData) {
@@ -7948,25 +8040,26 @@ function preload(url) {
7948
8040
  preloadControllers.delete(cacheKey);
7949
8041
  });
7950
8042
  }
7951
- async function updateHead(fromDoc, signal) {
8043
+ async function updateHead(fromDoc, signal, currentBaseUrl) {
7952
8044
  const allowedSelector = 'meta, link, style:not(#gyos-transitions), script';
7953
8045
  const currentNodes = Array.from(document.head.querySelectorAll(allowedSelector));
7954
8046
  const nextNodes = Array.from(fromDoc.head.querySelectorAll(allowedSelector));
7955
- await diffNodes(currentNodes, nextNodes, document.head, signal);
8047
+ await diffNodes(currentNodes, nextNodes, document.head, signal, currentBaseUrl);
7956
8048
  }
7957
- async function scriptNotInOutletTarget(fromDoc, target, source, signal) {
8049
+ async function scriptNotInOutletTarget(fromDoc, target, source, signal, currentBaseUrl) {
7958
8050
  // scripts in current document and it not in target outlet
7959
8051
  const currentScripts = Array.from(document.scripts).filter(s => !target.contains(s) && !document.head.contains(s));
7960
8052
  // scripts in fromDoc and it not in source outlet
7961
8053
  const incomingScripts = Array.from(fromDoc.scripts).filter(s => !source.contains(s) && !fromDoc.head.contains(s));
7962
8054
  // Diff and update scripts not in outlet/target
7963
- await diffNodes(currentScripts, incomingScripts, document.body, signal);
8055
+ await diffNodes(currentScripts, incomingScripts, document.body, signal, currentBaseUrl);
7964
8056
  }
7965
8057
  function resolveIncomingScriptUrls(root, baseUrl) {
7966
- root.querySelectorAll('script[src]').forEach(script => {
7967
- const source = script.getAttribute('src');
8058
+ root.querySelectorAll('script[src], link[href]').forEach(node => {
8059
+ const attribute = node.tagName === 'SCRIPT' ? 'src' : 'href';
8060
+ const source = node.getAttribute(attribute);
7968
8061
  if (source)
7969
- script.src = new URL(source, baseUrl).href;
8062
+ node.setAttribute(attribute, new URL(source, baseUrl).href);
7970
8063
  });
7971
8064
  }
7972
8065
  function isNavigableHtmlResponse(response) {
@@ -8020,6 +8113,22 @@ async function navigate(opts) {
8020
8113
  resolveDone
8021
8114
  };
8022
8115
  activeNavigation = transaction;
8116
+ const currentBaseUrl = document.baseURI;
8117
+ rememberResourceUrls(document, currentBaseUrl);
8118
+ const context = {
8119
+ from: currentUrl, url: opts.url, method: opts.method.toUpperCase(),
8120
+ trigger: opts.trigger || null, target: null, form: opts.form || null,
8121
+ popstate: opts.popstate === true, signal: transaction.controller.signal,
8122
+ status: null, committed: false, fallback: false, outcome: null
8123
+ };
8124
+ const formEvent = opts.form
8125
+ ? { form: opts.form, url: opts.url, status: null, outcome: null, committed: false, fallback: false }
8126
+ : null;
8127
+ const fallback = (url, requestSent) => {
8128
+ context.fallback = context.method === 'GET' || (!requestSent && !!opts.form);
8129
+ context.outcome ?? (context.outcome = context.fallback ? 'fallback' : 'invalid-response');
8130
+ fallbackFromBoost(opts, url, requestSent);
8131
+ };
8023
8132
  const hasTargetSpinner = opts.trigger?.hasAttribute('g-router-spin');
8024
8133
  const setRand = () => {
8025
8134
  if (isActiveNavigation(transaction) && progressBar?.getCurrentProgress() < 70) {
@@ -8027,7 +8136,10 @@ async function navigate(opts) {
8027
8136
  }
8028
8137
  };
8029
8138
  try {
8030
- runNavigationHooks(beforeNavigate, opts.url);
8139
+ if (formEvent)
8140
+ document.dispatchEvent(new CustomEvent('gyos:form-start', { detail: { ...formEvent } }));
8141
+ runNavigationHooks(beforeNavigate, opts.url, context);
8142
+ assertActiveNavigation(transaction);
8031
8143
  progressBar?.start();
8032
8144
  // popstate already points history at the destination entry. Keep the visible
8033
8145
  // page's position under currentUrl without overwriting that destination state.
@@ -8036,9 +8148,10 @@ async function navigate(opts) {
8036
8148
  saveScrollPosition();
8037
8149
  // Pick target element to swap
8038
8150
  let target = resolveTarget(opts.trigger, opts.targetSelector, opts.targetOutletIndex);
8151
+ context.target = target;
8039
8152
  if (!target) {
8040
8153
  if (isActiveNavigation(transaction))
8041
- fallbackFromBoost(opts, opts.url, false);
8154
+ fallback(opts.url, false);
8042
8155
  return;
8043
8156
  }
8044
8157
  const swapMode = (opts.swapMode || opts.trigger?.getAttribute('g-swap') || 'inner').toLowerCase();
@@ -8063,6 +8176,7 @@ async function navigate(opts) {
8063
8176
  if (hasTargetSpinner)
8064
8177
  transaction.spinner = showTargetSpinner(target, swapMode);
8065
8178
  const { finalUrl, init } = buildRequest(opts);
8179
+ context.url = finalUrl;
8066
8180
  // Add abort signal to request
8067
8181
  init.signal = transaction.controller.signal;
8068
8182
  let html;
@@ -8090,7 +8204,8 @@ async function navigate(opts) {
8090
8204
  if (error.name === 'AbortError')
8091
8205
  throw error;
8092
8206
  assertActiveNavigation(transaction);
8093
- window.location.href = finalUrl;
8207
+ context.outcome = 'network-error';
8208
+ fallback(finalUrl, true);
8094
8209
  return;
8095
8210
  }
8096
8211
  preloadCache.delete(preloadKey); // consume cache
@@ -8115,28 +8230,46 @@ async function navigate(opts) {
8115
8230
  log('[GyosRouter] Navigation cancelled');
8116
8231
  return;
8117
8232
  }
8233
+ context.outcome = 'network-error';
8118
8234
  if (isActiveNavigation(transaction))
8119
- fallbackFromBoost(opts, finalUrl, true);
8235
+ fallback(finalUrl, true);
8120
8236
  return;
8121
8237
  }
8122
8238
  }
8123
8239
  assertActiveNavigation(transaction);
8124
- // If response not ok, fallback to full navigation
8125
- if (!response || !response.ok || !isNavigableHtmlResponse(response)) {
8240
+ context.status = response?.status ?? null;
8241
+ context.url = response?.url || finalUrl;
8242
+ const acceptedErrors = (opts.trigger?.getAttribute('g-boost-errors') || '').split(/[\s,]+/);
8243
+ const renderHttpError = !!response && response.status >= 400 && response.status <= 599
8244
+ && acceptedErrors.includes(String(response.status));
8245
+ if (response && !response.ok)
8246
+ context.outcome = 'http-error';
8247
+ if (!response || (!response.ok && !renderHttpError) || !isNavigableHtmlResponse(response)) {
8248
+ context.outcome ?? (context.outcome = 'invalid-response');
8126
8249
  if (isActiveNavigation(transaction))
8127
- fallbackFromBoost(opts, finalUrl, true);
8250
+ fallback(finalUrl, true);
8128
8251
  return;
8129
8252
  }
8130
8253
  html = await response.text();
8131
8254
  assertActiveNavigation(transaction);
8132
- if (!opts.popstate && target.hasAttribute('g-snapshot')) {
8133
- saveSnapshot(canonicalUrl(response.url || finalUrl), html);
8134
- }
8135
8255
  }
8136
8256
  // Parse HTML
8137
8257
  const doc = html
8138
8258
  ? parseNavigationDocument(html)
8139
8259
  : document.implementation.createHTMLDocument();
8260
+ // Detached parsing cannot tell whether the live CSP permits an incoming base.
8261
+ // Let native navigation enforce base-uri instead of authorizing its URLs ourselves.
8262
+ if (doc.querySelector('base[href]') || opts.historyFragment?.querySelector('base[href]')) {
8263
+ context.outcome = 'invalid-response';
8264
+ fallback(response?.url || finalUrl, true);
8265
+ return;
8266
+ }
8267
+ if (response?.ok && !opts.popstate && target.hasAttribute('g-snapshot')) {
8268
+ saveSnapshot(canonicalUrl(response.url || finalUrl), html);
8269
+ }
8270
+ const syncDocumentAttributes = isFullOutletNavigation && destructiveSwap && !currentHead
8271
+ && !opts.historyFragment && (opts.popstate && snapshots.has(urlWithoutHash)
8272
+ ? snapshots.get(urlWithoutHash).fullDocument : isFullDocument(html || ''));
8140
8273
  // Pick source fragment
8141
8274
  const src = opts.historyFragment || pickSourceFragment(doc, target, targetOutletIndex);
8142
8275
  stripInertFallbackContent(src);
@@ -8148,15 +8281,18 @@ async function navigate(opts) {
8148
8281
  targetUrl += finalUrl.substring(finalUrl.indexOf('#'));
8149
8282
  }
8150
8283
  resolveIncomingScriptUrls(doc, targetUrl);
8284
+ context.url = targetUrl;
8151
8285
  if (opts.historyFragment)
8152
8286
  resolveIncomingScriptUrls(src, targetUrl);
8153
8287
  const triggerChangesState = opts.trigger?.hasAttribute('g-change-state') || false;
8154
8288
  const keepsCurrentState = opts.trigger?.hasAttribute('g-current-state') || false;
8155
8289
  const redirectedSubmission = opts.method.toUpperCase() !== 'GET' && response?.redirected === true;
8156
- const changesState = !keepsCurrentState && (opts.changeState === true || triggerChangesState || redirectedSubmission);
8290
+ const changesState = context.outcome !== 'http-error' && !keepsCurrentState && (opts.changeState === true || triggerChangesState || redirectedSubmission);
8157
8291
  const performUpdate = async () => {
8158
8292
  assertActiveNavigation(transaction);
8159
8293
  transaction.committing = true;
8294
+ runNavigationHooks(beforeSwap, targetUrl, context);
8295
+ assertActiveNavigation(transaction);
8160
8296
  // Update progress to rand 80 - 90% before swap
8161
8297
  progressBar?.setProgress(Math.random() * 10 + 80);
8162
8298
  const outgoingHistoryFragment = changesState && !opts.replace && !isFullOutletNavigation
@@ -8227,21 +8363,34 @@ async function navigate(opts) {
8227
8363
  beforeScripts: async () => {
8228
8364
  if (!isFullOutletNavigation || currentHead)
8229
8365
  return;
8366
+ if (syncDocumentAttributes) {
8367
+ for (const name of ['lang', 'dir']) {
8368
+ const value = doc.documentElement.getAttribute(name);
8369
+ if (value === null)
8370
+ document.documentElement.removeAttribute(name);
8371
+ else
8372
+ document.documentElement.setAttribute(name, value);
8373
+ }
8374
+ }
8230
8375
  const incomingTitle = doc.querySelector('title');
8231
8376
  if (incomingTitle) {
8232
8377
  document.title = incomingTitle.textContent || document.title;
8233
8378
  }
8234
- await updateHead(doc, transaction.controller.signal);
8379
+ await updateHead(doc, transaction.controller.signal, currentBaseUrl);
8235
8380
  assertActiveNavigation(transaction);
8236
8381
  },
8237
8382
  onCommitted: (committedTarget, roots) => {
8238
8383
  target = committedTarget;
8384
+ context.target = committedTarget;
8385
+ context.committed = true;
8386
+ progressBar?.reconnect();
8239
8387
  committedRoots = roots;
8240
8388
  }
8241
8389
  });
8390
+ context.committed = true;
8242
8391
  assertActiveNavigation(transaction);
8243
8392
  if (isFullOutletNavigation) {
8244
- await scriptNotInOutletTarget(doc, target, src, transaction.controller.signal);
8393
+ await scriptNotInOutletTarget(doc, target, src, transaction.controller.signal, currentBaseUrl);
8245
8394
  assertActiveNavigation(transaction);
8246
8395
  }
8247
8396
  }
@@ -8275,14 +8424,15 @@ async function navigate(opts) {
8275
8424
  await performUpdate();
8276
8425
  }
8277
8426
  assertActiveNavigation(transaction);
8278
- if (removeTriggerAfterCommit && opts.trigger instanceof HTMLElement && opts.trigger.isConnected) {
8427
+ if (removeTriggerAfterCommit && context.outcome !== 'http-error' && opts.trigger instanceof HTMLElement && opts.trigger.isConnected) {
8279
8428
  disposeEffects(opts.trigger);
8280
8429
  opts.trigger.remove();
8281
8430
  }
8282
8431
  if (hasTargetSpinner)
8283
8432
  hideTargetSpinner(transaction.spinner);
8284
8433
  transaction.spinner = null;
8285
- runNavigationHooks(afterNavigate, targetUrl);
8434
+ context.outcome ?? (context.outcome = 'success');
8435
+ runNavigationHooks(afterNavigate, targetUrl, context);
8286
8436
  log('[GyosRouter] navigated to', targetUrl);
8287
8437
  currentUrl = changesState
8288
8438
  ? canonicalUrl(targetUrl, true)
@@ -8298,11 +8448,15 @@ async function navigate(opts) {
8298
8448
  return;
8299
8449
  }
8300
8450
  if (isActiveNavigation(transaction)) {
8451
+ context.outcome ?? (context.outcome = 'error');
8301
8452
  console.error('[GyosRouter] navigation error', error);
8302
- fallbackFromBoost(opts, opts.url, true);
8453
+ fallback(opts.url, true);
8303
8454
  }
8304
8455
  }
8305
8456
  finally {
8457
+ if (transaction.controller.signal.aborted)
8458
+ context.outcome = 'aborted';
8459
+ context.outcome ?? (context.outcome = 'aborted');
8306
8460
  if (transaction.interval)
8307
8461
  clearInterval(transaction.interval);
8308
8462
  if (transaction.spinner)
@@ -8312,6 +8466,15 @@ async function navigate(opts) {
8312
8466
  progressBar?.complete();
8313
8467
  }
8314
8468
  transaction.resolveDone();
8469
+ if (formEvent)
8470
+ submittingForms.delete(formEvent.form);
8471
+ runNavigationHooks(navigationEnd, context.url, context);
8472
+ if (formEvent) {
8473
+ const { url, status, outcome, committed, fallback } = context;
8474
+ document.dispatchEvent(new CustomEvent('gyos:form-end', {
8475
+ detail: { ...formEvent, url, status, outcome, committed, fallback }
8476
+ }));
8477
+ }
8315
8478
  }
8316
8479
  }
8317
8480
  function shouldBoost(el) {
@@ -8420,16 +8583,34 @@ function onSubmit(event) {
8420
8583
  return;
8421
8584
  if (shouldDeferToFormValidation(form))
8422
8585
  return;
8423
- event.preventDefault();
8424
- const action = form.action || window.location.href;
8425
- const method = (form.method || 'GET').toUpperCase();
8426
- const url = new URL(action, window.location.href);
8427
- if (url.origin !== window.location.origin) {
8428
- window.location.href = url.toString();
8586
+ const submitter = event.submitter;
8587
+ const override = (name) => submitter?.getAttribute(`form${name}`) ?? form.getAttribute(name);
8588
+ const target = override('target') ?? document.querySelector('base[target]')?.getAttribute('target');
8589
+ const declaredMethod = (override('method') || 'GET').toUpperCase();
8590
+ const method = ['GET', 'POST', 'DIALOG'].includes(declaredMethod) ? declaredMethod : 'GET';
8591
+ const formEncoding = override('enctype')?.toLowerCase();
8592
+ if ((target && target.toLowerCase() !== '_self') || method === 'DIALOG' || formEncoding === 'text/plain')
8593
+ return;
8594
+ if (!resolveTarget(form))
8595
+ return;
8596
+ // Image submitters carry click coordinates which SubmitEvent does not expose.
8597
+ if (submitter instanceof HTMLInputElement && submitter.type === 'image')
8598
+ return;
8599
+ let url;
8600
+ try {
8601
+ url = new URL(override('action') || window.location.href, document.baseURI);
8602
+ }
8603
+ catch {
8429
8604
  return;
8430
8605
  }
8431
- const formData = new FormData(form);
8432
- navigate({ url: url.toString(), method, trigger: form, form, formData, changeState: method === 'GET' });
8606
+ if (url.origin !== window.location.origin)
8607
+ return;
8608
+ event.preventDefault();
8609
+ if (submittingForms.has(form))
8610
+ return;
8611
+ const formData = new FormData(form, submitter);
8612
+ submittingForms.add(form);
8613
+ void navigate({ url: url.toString(), method, trigger: form, form, formData, formEncoding, changeState: method === 'GET' });
8433
8614
  }
8434
8615
  function onPopState(event) {
8435
8616
  const url = window.location.href;
@@ -8534,10 +8715,12 @@ const Gyos = {
8534
8715
  startRouter,
8535
8716
  onBeforeNavigate,
8536
8717
  onAfterNavigate,
8718
+ onBeforeSwap,
8719
+ onNavigationEnd,
8537
8720
  portalCreate,
8538
8721
  portalDestroy,
8539
8722
  setCspNonce,
8540
- version: '0.3.1'
8723
+ version: '0.4.0'
8541
8724
  };
8542
8725
 
8543
8726
  // This file was generated. Do not modify manually!