gyosjs 0.4.1 → 0.5.1

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.4.1
2
+ * GyosJS v0.5.1
3
3
  * (c) 2026
4
4
  * @license MIT
5
5
  */
@@ -4521,6 +4521,79 @@
4521
4521
  return scopeVersionMap.get(target);
4522
4522
  }
4523
4523
 
4524
+ /** Keep the longest already-ordered run of rows connected; move only the rest. */
4525
+ function placeKeyedRows(placeholder, rows) {
4526
+ const parent = placeholder.parentNode;
4527
+ if (!parent || rows.length === 0)
4528
+ return;
4529
+ const managed = new Set(rows);
4530
+ const positions = new Map();
4531
+ let boundary = placeholder.nextSibling;
4532
+ while (boundary && managed.has(boundary)) {
4533
+ positions.set(boundary, positions.size);
4534
+ boundary = boundary.nextSibling;
4535
+ }
4536
+ const active = placeholder.ownerDocument.activeElement;
4537
+ const ownsFocus = !!active && rows.some((row) => row === active || row.contains(active));
4538
+ const selection = ownsFocus && (active instanceof HTMLInputElement || active instanceof HTMLTextAreaElement)
4539
+ ? { start: active.selectionStart, end: active.selectionEnd, direction: active.selectionDirection }
4540
+ : null;
4541
+ if (positions.size !== rows.length) {
4542
+ // Leaving transition nodes, foreign siblings or externally detached rows:
4543
+ // preserve the established contiguous-after-placeholder placement contract.
4544
+ let previous = placeholder;
4545
+ for (const row of rows) {
4546
+ if (row !== previous.nextSibling)
4547
+ parent.insertBefore(row, previous.nextSibling);
4548
+ previous = row;
4549
+ }
4550
+ }
4551
+ else {
4552
+ const order = rows.map((row) => positions.get(row));
4553
+ let sorted = true;
4554
+ for (let i = 1; i < order.length; i++)
4555
+ if (order[i] < order[i - 1]) {
4556
+ sorted = false;
4557
+ break;
4558
+ }
4559
+ if (sorted)
4560
+ return;
4561
+ // Patience sorting: indices of a longest increasing subsequence, O(n log n).
4562
+ const tails = [], predecessors = new Array(order.length).fill(-1);
4563
+ for (let i = 0; i < order.length; i++) {
4564
+ let low = 0, high = tails.length;
4565
+ while (low < high) {
4566
+ const middle = (low + high) >>> 1;
4567
+ if (order[tails[middle]] < order[i])
4568
+ low = middle + 1;
4569
+ else
4570
+ high = middle;
4571
+ }
4572
+ if (low > 0)
4573
+ predecessors[i] = tails[low - 1];
4574
+ tails[low] = i;
4575
+ }
4576
+ const retained = new Set();
4577
+ for (let i = tails[tails.length - 1]; i >= 0; i = predecessors[i])
4578
+ retained.add(i);
4579
+ for (let i = rows.length - 1; i >= 0; i--) {
4580
+ const row = rows[i];
4581
+ if (!retained.has(i) && row.nextSibling !== boundary)
4582
+ parent.insertBefore(row, boundary);
4583
+ boundary = row;
4584
+ }
4585
+ }
4586
+ // insertBefore can blur a moved input. Restore only a surviving owned focus,
4587
+ // and never steal focus assigned to another control by application callbacks.
4588
+ const document = placeholder.ownerDocument;
4589
+ if (ownsFocus && active.isConnected && document.activeElement === document.body) {
4590
+ active.focus({ preventScroll: true });
4591
+ if (selection?.start != null && selection.end != null) {
4592
+ active.setSelectionRange(selection.start, selection.end, selection.direction || undefined);
4593
+ }
4594
+ }
4595
+ }
4596
+
4524
4597
  /**
4525
4598
  * Structural Directives (*if, *for)
4526
4599
  * Single-pass parser for conditional and list rendering with transitions
@@ -4701,6 +4774,7 @@
4701
4774
  });
4702
4775
  // Add/reorder items immediately (parallel with remove animations)
4703
4776
  let lastPlacedNode = placeholder;
4777
+ const rows = [];
4704
4778
  orderedKeys.forEach((key) => {
4705
4779
  const newItemData = newItemsMap.get(key);
4706
4780
  const { index } = newItemData;
@@ -4752,13 +4826,10 @@
4752
4826
  });
4753
4827
  }
4754
4828
  }
4755
- // Place each managed row directly after the previous row. This does not
4756
- // depend on formatting whitespace or unrelated sibling nodes.
4757
- if (itemElement !== lastPlacedNode.nextSibling) {
4758
- placeholder.parentNode?.insertBefore(itemElement, lastPlacedNode.nextSibling);
4759
- }
4829
+ rows.push(itemElement);
4760
4830
  lastPlacedNode = itemElement;
4761
4831
  });
4832
+ placeKeyedRows(placeholder, rows);
4762
4833
  }
4763
4834
  /**
4764
4835
  * Process *for without keys (simple re-render)
@@ -5636,6 +5707,21 @@
5636
5707
  * Registry of all scopes
5637
5708
  */
5638
5709
  const scopeRegistry = new Map();
5710
+ const warnedReveals = new WeakSet();
5711
+ function diagnoseUnscopedReveals(root) {
5712
+ if (!DEBUG())
5713
+ return;
5714
+ const elements = [...root.querySelectorAll('[g-reveal]')];
5715
+ if (root instanceof Element && root.hasAttribute('g-reveal'))
5716
+ elements.unshift(root);
5717
+ for (const element of elements) {
5718
+ if (warnedReveals.has(element) || isInIgnoredTree(element)
5719
+ || element.closest('[g-scope]') || getScopeFromElement(element))
5720
+ continue;
5721
+ warnedReveals.add(element);
5722
+ console.warn('[Gyos] g-reveal has no owning scope. Add g-scope to its container; global reveal CSS may otherwise hide this content.', element);
5723
+ }
5724
+ }
5639
5725
  /**
5640
5726
  * Register a scope
5641
5727
  */
@@ -5683,6 +5769,7 @@
5683
5769
  allElements.sort((a, b) => getDepth(b) - getDepth(a));
5684
5770
  // Filter out elements inside structural directives - they will be mounted by structural processor
5685
5771
  allElements.forEach(el => !hasStructuralParent(el) && mount(el));
5772
+ diagnoseUnscopedReveals(document.body);
5686
5773
  }
5687
5774
  function mountTree(el) {
5688
5775
  if (isInIgnoredTree(el) || !document.body.contains(el))
@@ -5693,6 +5780,7 @@
5693
5780
  // Child scopes own their subtree before an existing parent scope parses the insertion.
5694
5781
  candidates.sort((a, b) => getDepth(b) - getDepth(a));
5695
5782
  candidates.forEach(element => !hasStructuralParent(element) && mount(element));
5783
+ diagnoseUnscopedReveals(el);
5696
5784
  if (getMountedScope(el))
5697
5785
  return;
5698
5786
  const ownerScope = getScopeFromElement(el);
@@ -5711,7 +5799,7 @@
5711
5799
  return;
5712
5800
  // Check if element removed but still has g-scope (possible in some edge cases)
5713
5801
  getAllMountedScopes().forEach((_, mountedEl) => {
5714
- if (!document.body.contains(mountedEl)) {
5802
+ if (!mountedEl.isConnected) {
5715
5803
  disposeEffects(mountedEl);
5716
5804
  }
5717
5805
  });
@@ -7037,7 +7125,8 @@
7037
7125
  el.dataset.gyosPersistId = key;
7038
7126
  return key;
7039
7127
  }
7040
- // Hidden parking lot keeps persisted nodes alive (e.g. audio keeps playing)
7128
+ // Keep the parking host outside body: body itself may be the swap target.
7129
+ // A disconnected parking host makes browsers pause otherwise persisted media.
7041
7130
  const persistParking = typeof document !== 'undefined'
7042
7131
  ? (() => {
7043
7132
  const park = document.createElement('div');
@@ -7046,12 +7135,7 @@
7046
7135
  park.style.top = '-99999px';
7047
7136
  park.style.width = '0';
7048
7137
  park.style.height = '0';
7049
- if (document.readyState === 'loading') {
7050
- document.addEventListener('DOMContentLoaded', () => document.body.appendChild(park));
7051
- }
7052
- else {
7053
- document.body.appendChild(park);
7054
- }
7138
+ document.documentElement.appendChild(park);
7055
7139
  return park;
7056
7140
  })()
7057
7141
  : null;
@@ -7062,8 +7146,8 @@
7062
7146
  return elements;
7063
7147
  }
7064
7148
  function ensureParkingIsConnected() {
7065
- if (persistParking && document.body && !persistParking.isConnected) {
7066
- document.body.appendChild(persistParking);
7149
+ if (persistParking && persistParking.parentElement !== document.documentElement) {
7150
+ document.documentElement.appendChild(persistParking);
7067
7151
  }
7068
7152
  }
7069
7153
  function detachPersist(root = document) {
@@ -7081,12 +7165,18 @@
7081
7165
  });
7082
7166
  }
7083
7167
  function mergePersistIntoLive(root) {
7168
+ // Return the host to the current body before scope mounting/cleanup inspects it.
7169
+ if (persistParking && persistParking.parentElement !== document.body) {
7170
+ document.body.appendChild(persistParking);
7171
+ }
7084
7172
  if (!persistEntries.size)
7085
7173
  return;
7086
7174
  // If placeholders lack ids but we only have one persist entry, assign its key for convenience
7087
7175
  if (persistEntries.size === 1) {
7088
7176
  const loneKey = Array.from(persistEntries.keys())[0];
7089
7177
  elementsIn(root).forEach(el => {
7178
+ if (persistParking?.contains(el))
7179
+ return;
7090
7180
  if (!getPersistKey(el, false)) {
7091
7181
  el.dataset.gyosPersistId = loneKey;
7092
7182
  }
@@ -7094,6 +7184,8 @@
7094
7184
  }
7095
7185
  // Element placeholders
7096
7186
  elementsIn(root).forEach(placeholder => {
7187
+ if (persistParking?.contains(placeholder))
7188
+ return;
7097
7189
  const key = getPersistKey(placeholder, false);
7098
7190
  if (!key)
7099
7191
  return;
@@ -7111,6 +7203,8 @@
7111
7203
  const toReplace = [];
7112
7204
  while (walker.nextNode()) {
7113
7205
  const comment = walker.currentNode;
7206
+ if (persistParking?.contains(comment))
7207
+ continue;
7114
7208
  const match = comment.data.match(/g-persist[:=]\s*([A-Za-z0-9_\-:.]+)/);
7115
7209
  if (match) {
7116
7210
  toReplace.push({ node: comment, key: match[1] });
@@ -7768,6 +7862,36 @@
7768
7862
  * Implements attribute-driven routing, snapshot caching, and persistent islands.
7769
7863
  */
7770
7864
  const submittingForms = new WeakSet();
7865
+ async function visit(url, options, fresh) {
7866
+ const destination = new URL(url, document.baseURI);
7867
+ if (!['http:', 'https:'].includes(destination.protocol) || destination.origin !== location.origin || destination.username || destination.password) {
7868
+ throw new TypeError('Gyos.navigate requires a same-origin HTTP(S) URL without credentials.');
7869
+ }
7870
+ if (options.target !== undefined && !(document.querySelector(options.target) instanceof HTMLElement)) {
7871
+ throw new TypeError('Gyos.navigate target does not exist.');
7872
+ }
7873
+ if (!document.querySelector('[g-boost]')) {
7874
+ throw new TypeError('Gyos.navigate requires a g-boost layout.');
7875
+ }
7876
+ startRouter();
7877
+ let result;
7878
+ await navigateRequest({
7879
+ url: destination.href, method: 'GET',
7880
+ changeState: options.history !== 'none', replace: options.history === 'replace',
7881
+ targetSelector: options.target, strictTarget: options.target !== undefined, swapMode: options.swap,
7882
+ currentHead: options.currentHead, scroll: options.scroll, signal: options.signal, fresh,
7883
+ onEnd: context => { result = context; }
7884
+ });
7885
+ return result;
7886
+ }
7887
+ /** Navigate through the boost pipeline. Resolves after navigation-end hooks. */
7888
+ function navigate(url, options = {}) {
7889
+ return visit(url, options, false);
7890
+ }
7891
+ /** Fetch the current URL again, preserving history and scroll by default. */
7892
+ function refresh(options = {}) {
7893
+ return visit(location.href, { history: 'none', scroll: false, ...options }, true);
7894
+ }
7771
7895
  const snapshots = new Map();
7772
7896
  const preloadCache = new Map();
7773
7897
  const preloadControllers = new Map();
@@ -8154,12 +8278,27 @@
8154
8278
  }
8155
8279
  console.error(`[GyosRouter] ${method} navigation could not be boosted; the request will not be replayed.`);
8156
8280
  }
8157
- async function navigate(opts) {
8281
+ async function navigateRequest(opts) {
8282
+ const finishUnstarted = () => {
8283
+ opts.onEnd?.({ from: currentUrl, url: opts.url, method: opts.method,
8284
+ trigger: opts.trigger || null, target: null, form: null, popstate: false,
8285
+ signal: opts.signal, status: null, committed: false, fallback: false, outcome: 'aborted' });
8286
+ };
8287
+ if (opts.signal?.aborted) {
8288
+ finishUnstarted();
8289
+ return;
8290
+ }
8158
8291
  while (activeNavigation) {
8159
8292
  const previous = activeNavigation;
8160
8293
  if (previous.committing) {
8161
8294
  log('[GyosRouter] Waiting for previous DOM commit');
8162
- await previous.done;
8295
+ try {
8296
+ await (opts.signal ? waitForNavigation(previous.done, opts.signal) : previous.done);
8297
+ }
8298
+ catch {
8299
+ finishUnstarted();
8300
+ return;
8301
+ }
8163
8302
  continue;
8164
8303
  }
8165
8304
  log('[GyosRouter] Cancelling previous navigation');
@@ -8178,6 +8317,10 @@
8178
8317
  resolveDone
8179
8318
  };
8180
8319
  activeNavigation = transaction;
8320
+ const abort = () => cancelNavigation(transaction);
8321
+ opts.signal?.addEventListener('abort', abort, { once: true });
8322
+ if (opts.signal?.aborted)
8323
+ abort();
8181
8324
  const currentBaseUrl = document.baseURI;
8182
8325
  rememberResourceUrls(document, currentBaseUrl);
8183
8326
  const context = {
@@ -8201,6 +8344,7 @@
8201
8344
  }
8202
8345
  };
8203
8346
  try {
8347
+ assertActiveNavigation(transaction);
8204
8348
  if (formEvent)
8205
8349
  document.dispatchEvent(new CustomEvent('gyos:form-start', { detail: { ...formEvent } }));
8206
8350
  runNavigationHooks(beforeNavigate, opts.url, context);
@@ -8213,6 +8357,10 @@
8213
8357
  saveScrollPosition();
8214
8358
  // Pick target element to swap
8215
8359
  let target = resolveTarget(opts.trigger, opts.targetSelector, opts.targetOutletIndex);
8360
+ if (opts.strictTarget && (!opts.targetSelector || !target?.matches(opts.targetSelector))) {
8361
+ context.outcome = 'invalid-response';
8362
+ return; // A queued explicit target disappeared; never broaden the swap.
8363
+ }
8216
8364
  context.target = target;
8217
8365
  if (!target) {
8218
8366
  if (isActiveNavigation(transaction))
@@ -8257,7 +8405,12 @@
8257
8405
  else {
8258
8406
  // Check preload cache if GET
8259
8407
  const preloadKey = canonicalUrl(finalUrl, true);
8260
- if (opts.method.toUpperCase() === 'GET' && preloadCache.has(preloadKey)) {
8408
+ if (opts.fresh) {
8409
+ preloadControllers.get(preloadKey)?.abort();
8410
+ preloadControllers.delete(preloadKey);
8411
+ preloadCache.delete(preloadKey);
8412
+ }
8413
+ if (!opts.fresh && opts.method.toUpperCase() === 'GET' && preloadCache.has(preloadKey)) {
8261
8414
  log('[GyosRouter] using preload cache for', finalUrl);
8262
8415
  try {
8263
8416
  response = await waitForNavigation(preloadCache.get(preloadKey), transaction.controller.signal);
@@ -8465,7 +8618,10 @@
8465
8618
  finalizeCommit();
8466
8619
  }
8467
8620
  // Handle scroll after mount scopes
8468
- if (changesState) {
8621
+ if (opts.scroll === false) {
8622
+ // Explicit refresh/navigation policy keeps the current viewport.
8623
+ }
8624
+ else if (changesState) {
8469
8625
  handleScroll(targetUrl, opts.trigger);
8470
8626
  }
8471
8627
  else if (opts.popstate) {
@@ -8530,6 +8686,7 @@
8530
8686
  activeNavigation = null;
8531
8687
  progressBar?.complete();
8532
8688
  }
8689
+ opts.signal?.removeEventListener('abort', abort);
8533
8690
  transaction.resolveDone();
8534
8691
  if (formEvent)
8535
8692
  submittingForms.delete(formEvent.form);
@@ -8540,6 +8697,7 @@
8540
8697
  detail: { ...formEvent, url, status, outcome, committed, fallback }
8541
8698
  }));
8542
8699
  }
8700
+ opts.onEnd?.({ ...context });
8543
8701
  }
8544
8702
  }
8545
8703
  function shouldBoost(el) {
@@ -8570,7 +8728,7 @@
8570
8728
  const scope = getScopeFromElement(element);
8571
8729
  const jsonData = evaluateExpression(decodeURIComponent(element.getAttribute(paramsAttr) || ''), scope, false);
8572
8730
  // The default changeState is false, as this is commonly used for: load more, infinite scroll, etc.
8573
- navigate({
8731
+ navigateRequest({
8574
8732
  url: parsedUrl.toString(), method, trigger: element, jsonData, changeState: false
8575
8733
  });
8576
8734
  }
@@ -8619,7 +8777,7 @@
8619
8777
  return;
8620
8778
  event.preventDefault();
8621
8779
  // The default changeState is true, as this is commonly used for: navigation, etc.
8622
- navigate({ url: url.toString(), method: 'GET', trigger: link, changeState: true });
8780
+ navigateRequest({ url: url.toString(), method: 'GET', trigger: link, changeState: true });
8623
8781
  }
8624
8782
  function onMouseOverCapture(event) {
8625
8783
  const target = event.target;
@@ -8675,7 +8833,7 @@
8675
8833
  return;
8676
8834
  const formData = new FormData(form, submitter);
8677
8835
  submittingForms.add(form);
8678
- void navigate({ url: url.toString(), method, trigger: form, form, formData, formEncoding, changeState: method === 'GET' });
8836
+ void navigateRequest({ url: url.toString(), method, trigger: form, form, formData, formEncoding, changeState: method === 'GET' });
8679
8837
  }
8680
8838
  function onPopState(event) {
8681
8839
  const url = window.location.href;
@@ -8693,14 +8851,14 @@
8693
8851
  }
8694
8852
  event.preventDefault();
8695
8853
  // The browser changes location before popstate fires. Stop any pending page
8696
- // script immediately, then let navigate() wait for its DOM finalizer.
8854
+ // script immediately, then let navigateRequest() wait for its DOM finalizer.
8697
8855
  if (activeNavigation?.committing)
8698
8856
  cancelNavigation(activeNavigation);
8699
8857
  // The browser has already moved to the destination history entry. Keep the
8700
8858
  // router's entry pointer aligned before any restored page script can navigate.
8701
8859
  currentHistoryEntryId = destinationEntryId;
8702
8860
  // No snapshot, do a normal navigation without changing history (changeState: false)
8703
- navigate({
8861
+ navigateRequest({
8704
8862
  url,
8705
8863
  method: 'GET',
8706
8864
  replace: true,
@@ -8782,10 +8940,12 @@
8782
8940
  onAfterNavigate,
8783
8941
  onBeforeSwap,
8784
8942
  onNavigationEnd,
8943
+ navigate,
8944
+ refresh,
8785
8945
  portalCreate,
8786
8946
  portalDestroy,
8787
8947
  setCspNonce,
8788
- version: '0.4.1'
8948
+ version: '0.5.1'
8789
8949
  };
8790
8950
 
8791
8951
  // This file was generated. Do not modify manually!