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
  */
@@ -2202,59 +2202,59 @@
2202
2202
  return;
2203
2203
  const style = document.createElement('style');
2204
2204
  style.id = styleId;
2205
- style.textContent = `
2206
- /* Opacity utilities */
2205
+ style.textContent = `
2206
+ /* Opacity utilities */
2207
2207
  .gyos-t-opacity-0 { opacity: 0; }
2208
2208
  .gyos-t-opacity-100 { opacity: 1; }
2209
-
2210
- /* Transform - Translate Y */
2209
+
2210
+ /* Transform - Translate Y */
2211
2211
  .gyos-t-translate-y-0 { transform: translateY(0); }
2212
2212
  .gyos-t-translate-y--100 { transform: translateY(-100%); }
2213
2213
  .gyos-t-translate-y-100 { transform: translateY(100%); }
2214
-
2215
- /* Transform - Translate X */
2214
+
2215
+ /* Transform - Translate X */
2216
2216
  .gyos-t-translate-x-0 { transform: translateX(0); }
2217
2217
  .gyos-t-translate-x--100 { transform: translateX(-100%); }
2218
2218
  .gyos-t-translate-x-100 { transform: translateX(100%); }
2219
-
2220
- /* Transform - Scale */
2219
+
2220
+ /* Transform - Scale */
2221
2221
  .gyos-t-scale-0 { transform: scale(0); }
2222
2222
  .gyos-t-scale-50 { transform: scale(0.5); }
2223
2223
  .gyos-t-scale-100 { transform: scale(1); }
2224
-
2225
- /* Animation Keyframes */
2226
- @keyframes gyos-fade-in {
2227
- from { opacity: 0; }
2228
- to { opacity: 1; }
2229
- }
2230
-
2231
- @keyframes gyos-fade-out {
2232
- from { opacity: 1; }
2233
- to { opacity: 0; }
2234
- }
2235
-
2236
- @keyframes gyos-slide-down {
2237
- from { transform: translateY(-100%); opacity: 0; }
2238
- to { transform: translateY(0); opacity: 1; }
2239
- }
2240
-
2241
- @keyframes gyos-slide-up {
2242
- from { transform: translateY(100%); opacity: 0; }
2243
- to { transform: translateY(0); opacity: 1; }
2244
- }
2245
-
2246
- @keyframes gyos-scale-in {
2247
- from { transform: scale(0); opacity: 0; }
2248
- to { transform: scale(1); opacity: 1; }
2249
- }
2250
-
2251
- @keyframes gyos-scale-out {
2252
- from { transform: scale(1); opacity: 1; }
2253
- to { transform: scale(0); opacity: 0; }
2254
- }
2255
-
2256
- [g-cloak] {
2257
- display: none !important;
2224
+
2225
+ /* Animation Keyframes */
2226
+ @keyframes gyos-fade-in {
2227
+ from { opacity: 0; }
2228
+ to { opacity: 1; }
2229
+ }
2230
+
2231
+ @keyframes gyos-fade-out {
2232
+ from { opacity: 1; }
2233
+ to { opacity: 0; }
2234
+ }
2235
+
2236
+ @keyframes gyos-slide-down {
2237
+ from { transform: translateY(-100%); opacity: 0; }
2238
+ to { transform: translateY(0); opacity: 1; }
2239
+ }
2240
+
2241
+ @keyframes gyos-slide-up {
2242
+ from { transform: translateY(100%); opacity: 0; }
2243
+ to { transform: translateY(0); opacity: 1; }
2244
+ }
2245
+
2246
+ @keyframes gyos-scale-in {
2247
+ from { transform: scale(0); opacity: 0; }
2248
+ to { transform: scale(1); opacity: 1; }
2249
+ }
2250
+
2251
+ @keyframes gyos-scale-out {
2252
+ from { transform: scale(1); opacity: 1; }
2253
+ to { transform: scale(0); opacity: 0; }
2254
+ }
2255
+
2256
+ [g-cloak] {
2257
+ display: none !important;
2258
2258
  }`;
2259
2259
  document.head.appendChild(style);
2260
2260
  }
@@ -5189,6 +5189,10 @@
5189
5189
  const structuralElements = [];
5190
5190
  const root = elements[0];
5191
5191
  elements.forEach(el => {
5192
+ // Await branches are detached and parsed only after their alias scope exists.
5193
+ // Do not evaluate nested structural expressions during the parent scan.
5194
+ if (isAwaitBranchDescendant(el))
5195
+ return;
5192
5196
  const hasIf = el.hasAttribute('*if');
5193
5197
  const hasFor = el.hasAttribute('*for');
5194
5198
  const hasSwitch = el.hasAttribute('*switch');
@@ -5233,6 +5237,20 @@
5233
5237
  }
5234
5238
  });
5235
5239
  }
5240
+ function isAwaitBranchDescendant(element) {
5241
+ let child = element;
5242
+ let parent = element.parentElement;
5243
+ while (parent && parent !== document.body) {
5244
+ if (parent.hasAttribute('*await') && (child.hasAttribute('*pending') ||
5245
+ child.hasAttribute('*then') ||
5246
+ child.hasAttribute('*catch'))) {
5247
+ return true;
5248
+ }
5249
+ child = parent;
5250
+ parent = parent.parentElement;
5251
+ }
5252
+ return false;
5253
+ }
5236
5254
  const elementBelongsToAnotherScope = (el, scope) => {
5237
5255
  const owner = getScopeFromElement(el);
5238
5256
  return Boolean(owner && owner !== scope);
@@ -6593,33 +6611,44 @@
6593
6611
  getCurrentProgress() {
6594
6612
  return this.currentProgress;
6595
6613
  }
6614
+ reconnect() {
6615
+ if (!this.element || !this.progressBarEnabled || !document.body)
6616
+ return;
6617
+ // Snapshots may contain a clone of the runtime bar. Keep this instance.
6618
+ document.querySelectorAll('#gyos-progress-bar').forEach(node => {
6619
+ if (node !== this.element)
6620
+ node.remove();
6621
+ });
6622
+ if (!this.element.isConnected)
6623
+ document.body.appendChild(this.element);
6624
+ }
6596
6625
  createBar() {
6597
6626
  if (typeof document === 'undefined')
6598
6627
  return;
6599
6628
  // Create progress bar element
6600
6629
  this.element = document.createElement('div');
6601
6630
  this.element.id = 'gyos-progress-bar';
6602
- this.element.style.cssText = `
6603
- position: fixed;
6604
- top: 0;
6605
- left: 0;
6606
- width: 0%;
6607
- height: 6px;
6608
- background: var(--gyos-progress-color, linear-gradient(90deg, #aab9ff, #77889f));
6609
- z-index: 999999;
6610
- transition: width 0.3s linear, opacity 0.3s linear;
6611
- opacity: 0;
6612
- pointer-events: none;
6613
- box-shadow: 0 0 10px rgba(102, 126, 234, 0.5);
6631
+ this.element.style.cssText = `
6632
+ position: fixed;
6633
+ top: 0;
6634
+ left: 0;
6635
+ width: 0%;
6636
+ height: 6px;
6637
+ background: var(--gyos-progress-color, linear-gradient(90deg, #aab9ff, #77889f));
6638
+ z-index: 999999;
6639
+ transition: width 0.3s linear, opacity 0.3s linear;
6640
+ opacity: 0;
6641
+ pointer-events: none;
6642
+ box-shadow: 0 0 10px rgba(102, 126, 234, 0.5);
6614
6643
  `;
6615
6644
  // Insert into DOM when ready
6616
6645
  if (document.readyState === 'loading') {
6617
6646
  document.addEventListener('DOMContentLoaded', () => {
6618
- document.body.insertAdjacentElement('beforeend', this.element);
6619
- });
6647
+ this.reconnect();
6648
+ }, { once: true });
6620
6649
  }
6621
6650
  else {
6622
- document.body.insertAdjacentElement('beforeend', this.element);
6651
+ this.reconnect();
6623
6652
  }
6624
6653
  }
6625
6654
  start() {
@@ -6643,6 +6672,7 @@
6643
6672
  setProgress(percent) {
6644
6673
  if (!this.element || !this.progressBarEnabled)
6645
6674
  return;
6675
+ this.reconnect();
6646
6676
  // Clamp between 0-100
6647
6677
  percent = Math.min(100, Math.max(0, percent));
6648
6678
  this.currentProgress = percent;
@@ -6691,41 +6721,41 @@
6691
6721
  function createTargetSpinner() {
6692
6722
  const spinner = document.createElement('div');
6693
6723
  spinner.className = 'gyos-target-spinner';
6694
- spinner.innerHTML = `
6695
- <div class="gyos-spinner-content">
6696
- <svg class="gyos-spinner-icon" viewBox="0 0 50 50">
6697
- <circle cx="25" cy="25" r="20" fill="none" stroke="currentColor" stroke-width="4" stroke-dasharray="31.4 31.4" />
6698
- </svg>
6699
- </div>
6724
+ spinner.innerHTML = `
6725
+ <div class="gyos-spinner-content">
6726
+ <svg class="gyos-spinner-icon" viewBox="0 0 50 50">
6727
+ <circle cx="25" cy="25" r="20" fill="none" stroke="currentColor" stroke-width="4" stroke-dasharray="31.4 31.4" />
6728
+ </svg>
6729
+ </div>
6700
6730
  `;
6701
6731
  // Inject styles if not already present
6702
6732
  if (expressionRuntimeMode() === 'standard' && !document.getElementById('gyos-target-spinner-styles')) {
6703
6733
  const style = document.createElement('style');
6704
6734
  style.id = 'gyos-target-spinner-styles';
6705
- style.textContent = `
6706
- .gyos-target-spinner {
6707
- display: flex;
6708
- align-items: center;
6709
- justify-content: center;
6710
- padding: 20px;
6711
- min-height: 60px;
6712
- }
6713
- .gyos-spinner-content {
6714
- display: flex;
6715
- align-items: center;
6716
- gap: 10px;
6717
- color: var(--gyos-spinner-color, #667eea);
6718
- font-size: 14px;
6719
- }
6720
- .gyos-spinner-icon {
6721
- width: 24px;
6722
- height: 24px;
6723
- animation: gyos-spin 1s linear infinite;
6724
- }
6725
- @keyframes gyos-spin {
6726
- 0% { transform: rotate(0deg); }
6727
- 100% { transform: rotate(360deg); }
6728
- }
6735
+ style.textContent = `
6736
+ .gyos-target-spinner {
6737
+ display: flex;
6738
+ align-items: center;
6739
+ justify-content: center;
6740
+ padding: 20px;
6741
+ min-height: 60px;
6742
+ }
6743
+ .gyos-spinner-content {
6744
+ display: flex;
6745
+ align-items: center;
6746
+ gap: 10px;
6747
+ color: var(--gyos-spinner-color, #667eea);
6748
+ font-size: 14px;
6749
+ }
6750
+ .gyos-spinner-icon {
6751
+ width: 24px;
6752
+ height: 24px;
6753
+ animation: gyos-spin 1s linear infinite;
6754
+ }
6755
+ @keyframes gyos-spin {
6756
+ 0% { transform: rotate(0deg); }
6757
+ 100% { transform: rotate(360deg); }
6758
+ }
6729
6759
  `;
6730
6760
  document.head.appendChild(style);
6731
6761
  }
@@ -7099,8 +7129,8 @@
7099
7129
  }
7100
7130
  result = target;
7101
7131
  }
7102
- await options.beforeScripts?.();
7103
7132
  options.onCommitted?.(result, normalized === 'append' || normalized === 'prepend' ? incomingChildren : [result]);
7133
+ await options.beforeScripts?.();
7104
7134
  // Additive swaps must not re-run scripts that already existed in the target.
7105
7135
  if (normalized === 'append' || normalized === 'prepend') {
7106
7136
  await executeScriptsInNodes(incomingChildren, options.signal);
@@ -7340,6 +7370,21 @@
7340
7370
  window.scrollTo({ top: 0, behavior: 'smooth' });
7341
7371
  }
7342
7372
 
7373
+ // A retained relative URL still identifies the resource loaded on its original
7374
+ // page, even after pushState changes document.baseURI.
7375
+ const resourceUrls = new WeakMap();
7376
+ function rememberResourceUrls(root, baseUrl) {
7377
+ root.querySelectorAll('script[src], link[href]').forEach(node => {
7378
+ const attribute = node.tagName === 'SCRIPT' ? 'src' : 'href';
7379
+ const source = node.getAttribute(attribute);
7380
+ if (resourceUrls.get(node)?.source === source)
7381
+ return;
7382
+ try {
7383
+ resourceUrls.set(node, { source, url: new URL(source, baseUrl).href });
7384
+ }
7385
+ catch { /* Invalid resource URLs retain their literal identity. */ }
7386
+ });
7387
+ }
7343
7388
  function isNonceMeta(el) {
7344
7389
  return el.tagName === 'META' && el.getAttribute('name')?.toLowerCase() === 'csp-nonce';
7345
7390
  }
@@ -7357,7 +7402,20 @@
7357
7402
  return;
7358
7403
  if (context.csp && isNonceMeta(el) && attr.name.toLowerCase() === 'content')
7359
7404
  return;
7360
- attributes.set(attr.name, attr.value);
7405
+ let value = attr.value;
7406
+ if ((el.tagName === 'SCRIPT' && attr.name === 'src') || (el.tagName === 'LINK' && attr.name === 'href')) {
7407
+ const cached = resourceUrls.get(el);
7408
+ if (cached?.source === value)
7409
+ value = cached.url;
7410
+ else {
7411
+ try {
7412
+ value = new URL(value, context.baseUrl || el.baseURI).href;
7413
+ resourceUrls.set(el, { source: attr.value, url: value });
7414
+ }
7415
+ catch { /* Keep invalid URLs distinct. */ }
7416
+ }
7417
+ }
7418
+ attributes.set(attr.name, value);
7361
7419
  });
7362
7420
  if (context.csp && usesCspNonce(el) && context.activeNonce) {
7363
7421
  attributes.set('nonce', context.activeNonce);
@@ -7424,19 +7482,21 @@
7424
7482
  console.warn('[GyosJS CSP] Skipped an inline MPA script because no active document nonce is configured.');
7425
7483
  }
7426
7484
  }
7427
- async function diffNodes(currentNodes, nextNodes, container = document.head, signal) {
7485
+ async function diffNodes(currentNodes, nextNodes, container = document.head, signal, currentBaseUrl = document.baseURI) {
7428
7486
  const csp = expressionRuntimeMode() === 'csp';
7429
7487
  const context = {
7430
7488
  csp,
7431
7489
  activeNonce: csp ? resolveCspNonce() : undefined
7432
7490
  };
7433
- const current = keyedNodes(currentNodes, context);
7491
+ const current = keyedNodes(currentNodes, { ...context, baseUrl: currentBaseUrl });
7434
7492
  const next = keyedNodes(nextNodes, context);
7493
+ const persistentKey = (node) => container === document.head ? node.getAttribute('g-head-persist') : null;
7494
+ const persistent = new Set(currentNodes.map(persistentKey).filter(Boolean));
7435
7495
  const currentKeys = new Set(current.map(item => item.key));
7436
7496
  const nextKeys = new Set(next.map(item => item.key));
7437
7497
  // Remove nodes that are not in the new head
7438
7498
  current.forEach(({ key, node }) => {
7439
- if (!nextKeys.has(key)) {
7499
+ if (!nextKeys.has(key) && !persistentKey(node)) {
7440
7500
  node.remove();
7441
7501
  }
7442
7502
  });
@@ -7444,6 +7504,8 @@
7444
7504
  for (const { key, node } of next) {
7445
7505
  if (signal?.aborted)
7446
7506
  return;
7507
+ if (persistent.has(persistentKey(node)))
7508
+ continue;
7447
7509
  if (!currentKeys.has(key)) {
7448
7510
  if (!canInsertNode(node, context)) {
7449
7511
  warnSkippedNode(node);
@@ -7646,6 +7708,7 @@
7646
7708
  * MPA boost navigation inspired by Turbo Drive.
7647
7709
  * Implements attribute-driven routing, snapshot caching, and persistent islands.
7648
7710
  */
7711
+ const submittingForms = new WeakSet();
7649
7712
  const snapshots = new Map();
7650
7713
  const preloadCache = new Map();
7651
7714
  const preloadControllers = new Map();
@@ -7662,12 +7725,30 @@
7662
7725
  let progressBar = null;
7663
7726
  const beforeNavigate = [];
7664
7727
  const afterNavigate = [];
7728
+ const beforeSwap = [];
7729
+ const navigationEnd = [];
7730
+ function registerNavigationHook(hooks, callback) {
7731
+ // A wrapper gives each registration its own unsubscribe identity.
7732
+ const entry = (url, context) => callback(url, context);
7733
+ hooks.push(entry);
7734
+ return () => {
7735
+ const index = hooks.indexOf(entry);
7736
+ if (index !== -1)
7737
+ hooks.splice(index, 1);
7738
+ };
7739
+ }
7665
7740
  // Expose hooks to register before/after navigation callbacks
7666
7741
  function onBeforeNavigate(callback) {
7667
- beforeNavigate.push(callback);
7742
+ return registerNavigationHook(beforeNavigate, callback);
7668
7743
  }
7669
7744
  function onAfterNavigate(callback) {
7670
- afterNavigate.push(callback);
7745
+ return registerNavigationHook(afterNavigate, callback);
7746
+ }
7747
+ function onBeforeSwap(callback) {
7748
+ return registerNavigationHook(beforeSwap, callback);
7749
+ }
7750
+ function onNavigationEnd(callback) {
7751
+ return registerNavigationHook(navigationEnd, (_url, context) => callback(context));
7671
7752
  }
7672
7753
  function startRouter(options) {
7673
7754
  // If not has g-boost attribute, do not start router
@@ -7691,6 +7772,7 @@
7691
7772
  }
7692
7773
  // Cache scripts from initial page to prevent re-execution on first navigation back
7693
7774
  cacheInitialPageScripts();
7775
+ rememberResourceUrls(document, document.baseURI);
7694
7776
  routerStarted = true;
7695
7777
  log('[GyosRouter] started');
7696
7778
  }
@@ -7747,9 +7829,13 @@
7747
7829
  const outlet = findGlobalOutlet();
7748
7830
  return outlet instanceof HTMLElement ? outlet : null;
7749
7831
  }
7832
+ function isFullDocument(html) {
7833
+ return /^\s*(?:<!--[^]*?-->\s*)*(?:<!doctype\s+html\b|<html(?:\s|>))/i.test(html);
7834
+ }
7750
7835
  function saveSnapshot(url, html) {
7751
7836
  // create HTMLElement by html string to remove scripts and get clean snapshot
7752
7837
  const doc = parseNavigationDocument(html);
7838
+ doc.querySelectorAll('#gyos-progress-bar').forEach(node => node.remove());
7753
7839
  // Ignore hash for snapshot keys
7754
7840
  if (url.includes('#'))
7755
7841
  url = url.split('#')[0];
@@ -7758,7 +7844,7 @@
7758
7844
  if (s.hasAttribute('g-script-once'))
7759
7845
  s.textContent = '';
7760
7846
  });
7761
- snapshots.set(url, { html: doc.documentElement.outerHTML });
7847
+ snapshots.set(url, { html: doc.documentElement.outerHTML, fullDocument: isFullDocument(html) });
7762
7848
  log('[GyosRouter] snapshot saved for', url);
7763
7849
  }
7764
7850
  function getOutletIndex(root, target) {
@@ -7870,10 +7956,10 @@
7870
7956
  // update callback remains the navigation source of truth and is awaited below.
7871
7957
  void promise?.catch(() => undefined);
7872
7958
  }
7873
- function runNavigationHooks(callbacks, url) {
7874
- callbacks.forEach(callback => {
7959
+ function runNavigationHooks(callbacks, url, context) {
7960
+ [...callbacks].forEach(callback => {
7875
7961
  try {
7876
- callback(url);
7962
+ callback(url, { ...context });
7877
7963
  }
7878
7964
  catch (error) {
7879
7965
  console.error('[GyosRouter] navigation hook error', error);
@@ -7911,7 +7997,13 @@
7911
7997
  url = mergeFormDataIntoUrl(url, opts.formData);
7912
7998
  }
7913
7999
  else {
7914
- init.body = opts.formData;
8000
+ if (opts.formEncoding === 'application/x-www-form-urlencoded') {
8001
+ const encoded = new URLSearchParams();
8002
+ opts.formData.forEach((value, name) => encoded.append(name, typeof value === 'string' ? value : value.name));
8003
+ init.body = encoded;
8004
+ }
8005
+ else
8006
+ init.body = opts.formData;
7915
8007
  }
7916
8008
  }
7917
8009
  else if (opts.jsonData) {
@@ -7954,25 +8046,26 @@
7954
8046
  preloadControllers.delete(cacheKey);
7955
8047
  });
7956
8048
  }
7957
- async function updateHead(fromDoc, signal) {
8049
+ async function updateHead(fromDoc, signal, currentBaseUrl) {
7958
8050
  const allowedSelector = 'meta, link, style:not(#gyos-transitions), script';
7959
8051
  const currentNodes = Array.from(document.head.querySelectorAll(allowedSelector));
7960
8052
  const nextNodes = Array.from(fromDoc.head.querySelectorAll(allowedSelector));
7961
- await diffNodes(currentNodes, nextNodes, document.head, signal);
8053
+ await diffNodes(currentNodes, nextNodes, document.head, signal, currentBaseUrl);
7962
8054
  }
7963
- async function scriptNotInOutletTarget(fromDoc, target, source, signal) {
8055
+ async function scriptNotInOutletTarget(fromDoc, target, source, signal, currentBaseUrl) {
7964
8056
  // scripts in current document and it not in target outlet
7965
8057
  const currentScripts = Array.from(document.scripts).filter(s => !target.contains(s) && !document.head.contains(s));
7966
8058
  // scripts in fromDoc and it not in source outlet
7967
8059
  const incomingScripts = Array.from(fromDoc.scripts).filter(s => !source.contains(s) && !fromDoc.head.contains(s));
7968
8060
  // Diff and update scripts not in outlet/target
7969
- await diffNodes(currentScripts, incomingScripts, document.body, signal);
8061
+ await diffNodes(currentScripts, incomingScripts, document.body, signal, currentBaseUrl);
7970
8062
  }
7971
8063
  function resolveIncomingScriptUrls(root, baseUrl) {
7972
- root.querySelectorAll('script[src]').forEach(script => {
7973
- const source = script.getAttribute('src');
8064
+ root.querySelectorAll('script[src], link[href]').forEach(node => {
8065
+ const attribute = node.tagName === 'SCRIPT' ? 'src' : 'href';
8066
+ const source = node.getAttribute(attribute);
7974
8067
  if (source)
7975
- script.src = new URL(source, baseUrl).href;
8068
+ node.setAttribute(attribute, new URL(source, baseUrl).href);
7976
8069
  });
7977
8070
  }
7978
8071
  function isNavigableHtmlResponse(response) {
@@ -8026,6 +8119,22 @@
8026
8119
  resolveDone
8027
8120
  };
8028
8121
  activeNavigation = transaction;
8122
+ const currentBaseUrl = document.baseURI;
8123
+ rememberResourceUrls(document, currentBaseUrl);
8124
+ const context = {
8125
+ from: currentUrl, url: opts.url, method: opts.method.toUpperCase(),
8126
+ trigger: opts.trigger || null, target: null, form: opts.form || null,
8127
+ popstate: opts.popstate === true, signal: transaction.controller.signal,
8128
+ status: null, committed: false, fallback: false, outcome: null
8129
+ };
8130
+ const formEvent = opts.form
8131
+ ? { form: opts.form, url: opts.url, status: null, outcome: null, committed: false, fallback: false }
8132
+ : null;
8133
+ const fallback = (url, requestSent) => {
8134
+ context.fallback = context.method === 'GET' || (!requestSent && !!opts.form);
8135
+ context.outcome ?? (context.outcome = context.fallback ? 'fallback' : 'invalid-response');
8136
+ fallbackFromBoost(opts, url, requestSent);
8137
+ };
8029
8138
  const hasTargetSpinner = opts.trigger?.hasAttribute('g-router-spin');
8030
8139
  const setRand = () => {
8031
8140
  if (isActiveNavigation(transaction) && progressBar?.getCurrentProgress() < 70) {
@@ -8033,7 +8142,10 @@
8033
8142
  }
8034
8143
  };
8035
8144
  try {
8036
- runNavigationHooks(beforeNavigate, opts.url);
8145
+ if (formEvent)
8146
+ document.dispatchEvent(new CustomEvent('gyos:form-start', { detail: { ...formEvent } }));
8147
+ runNavigationHooks(beforeNavigate, opts.url, context);
8148
+ assertActiveNavigation(transaction);
8037
8149
  progressBar?.start();
8038
8150
  // popstate already points history at the destination entry. Keep the visible
8039
8151
  // page's position under currentUrl without overwriting that destination state.
@@ -8042,9 +8154,10 @@
8042
8154
  saveScrollPosition();
8043
8155
  // Pick target element to swap
8044
8156
  let target = resolveTarget(opts.trigger, opts.targetSelector, opts.targetOutletIndex);
8157
+ context.target = target;
8045
8158
  if (!target) {
8046
8159
  if (isActiveNavigation(transaction))
8047
- fallbackFromBoost(opts, opts.url, false);
8160
+ fallback(opts.url, false);
8048
8161
  return;
8049
8162
  }
8050
8163
  const swapMode = (opts.swapMode || opts.trigger?.getAttribute('g-swap') || 'inner').toLowerCase();
@@ -8069,6 +8182,7 @@
8069
8182
  if (hasTargetSpinner)
8070
8183
  transaction.spinner = showTargetSpinner(target, swapMode);
8071
8184
  const { finalUrl, init } = buildRequest(opts);
8185
+ context.url = finalUrl;
8072
8186
  // Add abort signal to request
8073
8187
  init.signal = transaction.controller.signal;
8074
8188
  let html;
@@ -8096,7 +8210,8 @@
8096
8210
  if (error.name === 'AbortError')
8097
8211
  throw error;
8098
8212
  assertActiveNavigation(transaction);
8099
- window.location.href = finalUrl;
8213
+ context.outcome = 'network-error';
8214
+ fallback(finalUrl, true);
8100
8215
  return;
8101
8216
  }
8102
8217
  preloadCache.delete(preloadKey); // consume cache
@@ -8121,28 +8236,46 @@
8121
8236
  log('[GyosRouter] Navigation cancelled');
8122
8237
  return;
8123
8238
  }
8239
+ context.outcome = 'network-error';
8124
8240
  if (isActiveNavigation(transaction))
8125
- fallbackFromBoost(opts, finalUrl, true);
8241
+ fallback(finalUrl, true);
8126
8242
  return;
8127
8243
  }
8128
8244
  }
8129
8245
  assertActiveNavigation(transaction);
8130
- // If response not ok, fallback to full navigation
8131
- if (!response || !response.ok || !isNavigableHtmlResponse(response)) {
8246
+ context.status = response?.status ?? null;
8247
+ context.url = response?.url || finalUrl;
8248
+ const acceptedErrors = (opts.trigger?.getAttribute('g-boost-errors') || '').split(/[\s,]+/);
8249
+ const renderHttpError = !!response && response.status >= 400 && response.status <= 599
8250
+ && acceptedErrors.includes(String(response.status));
8251
+ if (response && !response.ok)
8252
+ context.outcome = 'http-error';
8253
+ if (!response || (!response.ok && !renderHttpError) || !isNavigableHtmlResponse(response)) {
8254
+ context.outcome ?? (context.outcome = 'invalid-response');
8132
8255
  if (isActiveNavigation(transaction))
8133
- fallbackFromBoost(opts, finalUrl, true);
8256
+ fallback(finalUrl, true);
8134
8257
  return;
8135
8258
  }
8136
8259
  html = await response.text();
8137
8260
  assertActiveNavigation(transaction);
8138
- if (!opts.popstate && target.hasAttribute('g-snapshot')) {
8139
- saveSnapshot(canonicalUrl(response.url || finalUrl), html);
8140
- }
8141
8261
  }
8142
8262
  // Parse HTML
8143
8263
  const doc = html
8144
8264
  ? parseNavigationDocument(html)
8145
8265
  : document.implementation.createHTMLDocument();
8266
+ // Detached parsing cannot tell whether the live CSP permits an incoming base.
8267
+ // Let native navigation enforce base-uri instead of authorizing its URLs ourselves.
8268
+ if (doc.querySelector('base[href]') || opts.historyFragment?.querySelector('base[href]')) {
8269
+ context.outcome = 'invalid-response';
8270
+ fallback(response?.url || finalUrl, true);
8271
+ return;
8272
+ }
8273
+ if (response?.ok && !opts.popstate && target.hasAttribute('g-snapshot')) {
8274
+ saveSnapshot(canonicalUrl(response.url || finalUrl), html);
8275
+ }
8276
+ const syncDocumentAttributes = isFullOutletNavigation && destructiveSwap && !currentHead
8277
+ && !opts.historyFragment && (opts.popstate && snapshots.has(urlWithoutHash)
8278
+ ? snapshots.get(urlWithoutHash).fullDocument : isFullDocument(html || ''));
8146
8279
  // Pick source fragment
8147
8280
  const src = opts.historyFragment || pickSourceFragment(doc, target, targetOutletIndex);
8148
8281
  stripInertFallbackContent(src);
@@ -8154,15 +8287,18 @@
8154
8287
  targetUrl += finalUrl.substring(finalUrl.indexOf('#'));
8155
8288
  }
8156
8289
  resolveIncomingScriptUrls(doc, targetUrl);
8290
+ context.url = targetUrl;
8157
8291
  if (opts.historyFragment)
8158
8292
  resolveIncomingScriptUrls(src, targetUrl);
8159
8293
  const triggerChangesState = opts.trigger?.hasAttribute('g-change-state') || false;
8160
8294
  const keepsCurrentState = opts.trigger?.hasAttribute('g-current-state') || false;
8161
8295
  const redirectedSubmission = opts.method.toUpperCase() !== 'GET' && response?.redirected === true;
8162
- const changesState = !keepsCurrentState && (opts.changeState === true || triggerChangesState || redirectedSubmission);
8296
+ const changesState = context.outcome !== 'http-error' && !keepsCurrentState && (opts.changeState === true || triggerChangesState || redirectedSubmission);
8163
8297
  const performUpdate = async () => {
8164
8298
  assertActiveNavigation(transaction);
8165
8299
  transaction.committing = true;
8300
+ runNavigationHooks(beforeSwap, targetUrl, context);
8301
+ assertActiveNavigation(transaction);
8166
8302
  // Update progress to rand 80 - 90% before swap
8167
8303
  progressBar?.setProgress(Math.random() * 10 + 80);
8168
8304
  const outgoingHistoryFragment = changesState && !opts.replace && !isFullOutletNavigation
@@ -8233,21 +8369,34 @@
8233
8369
  beforeScripts: async () => {
8234
8370
  if (!isFullOutletNavigation || currentHead)
8235
8371
  return;
8372
+ if (syncDocumentAttributes) {
8373
+ for (const name of ['lang', 'dir']) {
8374
+ const value = doc.documentElement.getAttribute(name);
8375
+ if (value === null)
8376
+ document.documentElement.removeAttribute(name);
8377
+ else
8378
+ document.documentElement.setAttribute(name, value);
8379
+ }
8380
+ }
8236
8381
  const incomingTitle = doc.querySelector('title');
8237
8382
  if (incomingTitle) {
8238
8383
  document.title = incomingTitle.textContent || document.title;
8239
8384
  }
8240
- await updateHead(doc, transaction.controller.signal);
8385
+ await updateHead(doc, transaction.controller.signal, currentBaseUrl);
8241
8386
  assertActiveNavigation(transaction);
8242
8387
  },
8243
8388
  onCommitted: (committedTarget, roots) => {
8244
8389
  target = committedTarget;
8390
+ context.target = committedTarget;
8391
+ context.committed = true;
8392
+ progressBar?.reconnect();
8245
8393
  committedRoots = roots;
8246
8394
  }
8247
8395
  });
8396
+ context.committed = true;
8248
8397
  assertActiveNavigation(transaction);
8249
8398
  if (isFullOutletNavigation) {
8250
- await scriptNotInOutletTarget(doc, target, src, transaction.controller.signal);
8399
+ await scriptNotInOutletTarget(doc, target, src, transaction.controller.signal, currentBaseUrl);
8251
8400
  assertActiveNavigation(transaction);
8252
8401
  }
8253
8402
  }
@@ -8281,14 +8430,15 @@
8281
8430
  await performUpdate();
8282
8431
  }
8283
8432
  assertActiveNavigation(transaction);
8284
- if (removeTriggerAfterCommit && opts.trigger instanceof HTMLElement && opts.trigger.isConnected) {
8433
+ if (removeTriggerAfterCommit && context.outcome !== 'http-error' && opts.trigger instanceof HTMLElement && opts.trigger.isConnected) {
8285
8434
  disposeEffects(opts.trigger);
8286
8435
  opts.trigger.remove();
8287
8436
  }
8288
8437
  if (hasTargetSpinner)
8289
8438
  hideTargetSpinner(transaction.spinner);
8290
8439
  transaction.spinner = null;
8291
- runNavigationHooks(afterNavigate, targetUrl);
8440
+ context.outcome ?? (context.outcome = 'success');
8441
+ runNavigationHooks(afterNavigate, targetUrl, context);
8292
8442
  log('[GyosRouter] navigated to', targetUrl);
8293
8443
  currentUrl = changesState
8294
8444
  ? canonicalUrl(targetUrl, true)
@@ -8304,11 +8454,15 @@
8304
8454
  return;
8305
8455
  }
8306
8456
  if (isActiveNavigation(transaction)) {
8457
+ context.outcome ?? (context.outcome = 'error');
8307
8458
  console.error('[GyosRouter] navigation error', error);
8308
- fallbackFromBoost(opts, opts.url, true);
8459
+ fallback(opts.url, true);
8309
8460
  }
8310
8461
  }
8311
8462
  finally {
8463
+ if (transaction.controller.signal.aborted)
8464
+ context.outcome = 'aborted';
8465
+ context.outcome ?? (context.outcome = 'aborted');
8312
8466
  if (transaction.interval)
8313
8467
  clearInterval(transaction.interval);
8314
8468
  if (transaction.spinner)
@@ -8318,6 +8472,15 @@
8318
8472
  progressBar?.complete();
8319
8473
  }
8320
8474
  transaction.resolveDone();
8475
+ if (formEvent)
8476
+ submittingForms.delete(formEvent.form);
8477
+ runNavigationHooks(navigationEnd, context.url, context);
8478
+ if (formEvent) {
8479
+ const { url, status, outcome, committed, fallback } = context;
8480
+ document.dispatchEvent(new CustomEvent('gyos:form-end', {
8481
+ detail: { ...formEvent, url, status, outcome, committed, fallback }
8482
+ }));
8483
+ }
8321
8484
  }
8322
8485
  }
8323
8486
  function shouldBoost(el) {
@@ -8426,16 +8589,34 @@
8426
8589
  return;
8427
8590
  if (shouldDeferToFormValidation(form))
8428
8591
  return;
8429
- event.preventDefault();
8430
- const action = form.action || window.location.href;
8431
- const method = (form.method || 'GET').toUpperCase();
8432
- const url = new URL(action, window.location.href);
8433
- if (url.origin !== window.location.origin) {
8434
- window.location.href = url.toString();
8592
+ const submitter = event.submitter;
8593
+ const override = (name) => submitter?.getAttribute(`form${name}`) ?? form.getAttribute(name);
8594
+ const target = override('target') ?? document.querySelector('base[target]')?.getAttribute('target');
8595
+ const declaredMethod = (override('method') || 'GET').toUpperCase();
8596
+ const method = ['GET', 'POST', 'DIALOG'].includes(declaredMethod) ? declaredMethod : 'GET';
8597
+ const formEncoding = override('enctype')?.toLowerCase();
8598
+ if ((target && target.toLowerCase() !== '_self') || method === 'DIALOG' || formEncoding === 'text/plain')
8599
+ return;
8600
+ if (!resolveTarget(form))
8601
+ return;
8602
+ // Image submitters carry click coordinates which SubmitEvent does not expose.
8603
+ if (submitter instanceof HTMLInputElement && submitter.type === 'image')
8604
+ return;
8605
+ let url;
8606
+ try {
8607
+ url = new URL(override('action') || window.location.href, document.baseURI);
8608
+ }
8609
+ catch {
8435
8610
  return;
8436
8611
  }
8437
- const formData = new FormData(form);
8438
- navigate({ url: url.toString(), method, trigger: form, form, formData, changeState: method === 'GET' });
8612
+ if (url.origin !== window.location.origin)
8613
+ return;
8614
+ event.preventDefault();
8615
+ if (submittingForms.has(form))
8616
+ return;
8617
+ const formData = new FormData(form, submitter);
8618
+ submittingForms.add(form);
8619
+ void navigate({ url: url.toString(), method, trigger: form, form, formData, formEncoding, changeState: method === 'GET' });
8439
8620
  }
8440
8621
  function onPopState(event) {
8441
8622
  const url = window.location.href;
@@ -8540,10 +8721,12 @@
8540
8721
  startRouter,
8541
8722
  onBeforeNavigate,
8542
8723
  onAfterNavigate,
8724
+ onBeforeSwap,
8725
+ onNavigationEnd,
8543
8726
  portalCreate,
8544
8727
  portalDestroy,
8545
8728
  setCspNonce,
8546
- version: '0.3.1'
8729
+ version: '0.4.0'
8547
8730
  };
8548
8731
 
8549
8732
  // This file was generated. Do not modify manually!