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.
package/dist/gyos.js CHANGED
@@ -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
  */
@@ -4553,6 +4553,79 @@
4553
4553
  return scopeVersionMap.get(target);
4554
4554
  }
4555
4555
 
4556
+ /** Keep the longest already-ordered run of rows connected; move only the rest. */
4557
+ function placeKeyedRows(placeholder, rows) {
4558
+ const parent = placeholder.parentNode;
4559
+ if (!parent || rows.length === 0)
4560
+ return;
4561
+ const managed = new Set(rows);
4562
+ const positions = new Map();
4563
+ let boundary = placeholder.nextSibling;
4564
+ while (boundary && managed.has(boundary)) {
4565
+ positions.set(boundary, positions.size);
4566
+ boundary = boundary.nextSibling;
4567
+ }
4568
+ const active = placeholder.ownerDocument.activeElement;
4569
+ const ownsFocus = !!active && rows.some((row) => row === active || row.contains(active));
4570
+ const selection = ownsFocus && (active instanceof HTMLInputElement || active instanceof HTMLTextAreaElement)
4571
+ ? { start: active.selectionStart, end: active.selectionEnd, direction: active.selectionDirection }
4572
+ : null;
4573
+ if (positions.size !== rows.length) {
4574
+ // Leaving transition nodes, foreign siblings or externally detached rows:
4575
+ // preserve the established contiguous-after-placeholder placement contract.
4576
+ let previous = placeholder;
4577
+ for (const row of rows) {
4578
+ if (row !== previous.nextSibling)
4579
+ parent.insertBefore(row, previous.nextSibling);
4580
+ previous = row;
4581
+ }
4582
+ }
4583
+ else {
4584
+ const order = rows.map((row) => positions.get(row));
4585
+ let sorted = true;
4586
+ for (let i = 1; i < order.length; i++)
4587
+ if (order[i] < order[i - 1]) {
4588
+ sorted = false;
4589
+ break;
4590
+ }
4591
+ if (sorted)
4592
+ return;
4593
+ // Patience sorting: indices of a longest increasing subsequence, O(n log n).
4594
+ const tails = [], predecessors = new Array(order.length).fill(-1);
4595
+ for (let i = 0; i < order.length; i++) {
4596
+ let low = 0, high = tails.length;
4597
+ while (low < high) {
4598
+ const middle = (low + high) >>> 1;
4599
+ if (order[tails[middle]] < order[i])
4600
+ low = middle + 1;
4601
+ else
4602
+ high = middle;
4603
+ }
4604
+ if (low > 0)
4605
+ predecessors[i] = tails[low - 1];
4606
+ tails[low] = i;
4607
+ }
4608
+ const retained = new Set();
4609
+ for (let i = tails[tails.length - 1]; i >= 0; i = predecessors[i])
4610
+ retained.add(i);
4611
+ for (let i = rows.length - 1; i >= 0; i--) {
4612
+ const row = rows[i];
4613
+ if (!retained.has(i) && row.nextSibling !== boundary)
4614
+ parent.insertBefore(row, boundary);
4615
+ boundary = row;
4616
+ }
4617
+ }
4618
+ // insertBefore can blur a moved input. Restore only a surviving owned focus,
4619
+ // and never steal focus assigned to another control by application callbacks.
4620
+ const document = placeholder.ownerDocument;
4621
+ if (ownsFocus && active.isConnected && document.activeElement === document.body) {
4622
+ active.focus({ preventScroll: true });
4623
+ if (selection?.start != null && selection.end != null) {
4624
+ active.setSelectionRange(selection.start, selection.end, selection.direction || undefined);
4625
+ }
4626
+ }
4627
+ }
4628
+
4556
4629
  /**
4557
4630
  * Structural Directives (*if, *for)
4558
4631
  * Single-pass parser for conditional and list rendering with transitions
@@ -4733,6 +4806,7 @@
4733
4806
  });
4734
4807
  // Add/reorder items immediately (parallel with remove animations)
4735
4808
  let lastPlacedNode = placeholder;
4809
+ const rows = [];
4736
4810
  orderedKeys.forEach((key) => {
4737
4811
  const newItemData = newItemsMap.get(key);
4738
4812
  const { index } = newItemData;
@@ -4784,13 +4858,10 @@
4784
4858
  });
4785
4859
  }
4786
4860
  }
4787
- // Place each managed row directly after the previous row. This does not
4788
- // depend on formatting whitespace or unrelated sibling nodes.
4789
- if (itemElement !== lastPlacedNode.nextSibling) {
4790
- placeholder.parentNode?.insertBefore(itemElement, lastPlacedNode.nextSibling);
4791
- }
4861
+ rows.push(itemElement);
4792
4862
  lastPlacedNode = itemElement;
4793
4863
  });
4864
+ placeKeyedRows(placeholder, rows);
4794
4865
  }
4795
4866
  /**
4796
4867
  * Process *for without keys (simple re-render)
@@ -5668,6 +5739,21 @@
5668
5739
  * Registry of all scopes
5669
5740
  */
5670
5741
  const scopeRegistry = new Map();
5742
+ const warnedReveals = new WeakSet();
5743
+ function diagnoseUnscopedReveals(root) {
5744
+ if (!DEBUG())
5745
+ return;
5746
+ const elements = [...root.querySelectorAll('[g-reveal]')];
5747
+ if (root instanceof Element && root.hasAttribute('g-reveal'))
5748
+ elements.unshift(root);
5749
+ for (const element of elements) {
5750
+ if (warnedReveals.has(element) || isInIgnoredTree(element)
5751
+ || element.closest('[g-scope]') || getScopeFromElement(element))
5752
+ continue;
5753
+ warnedReveals.add(element);
5754
+ console.warn('[Gyos] g-reveal has no owning scope. Add g-scope to its container; global reveal CSS may otherwise hide this content.', element);
5755
+ }
5756
+ }
5671
5757
  /**
5672
5758
  * Register a scope
5673
5759
  */
@@ -5715,6 +5801,7 @@
5715
5801
  allElements.sort((a, b) => getDepth(b) - getDepth(a));
5716
5802
  // Filter out elements inside structural directives - they will be mounted by structural processor
5717
5803
  allElements.forEach(el => !hasStructuralParent(el) && mount(el));
5804
+ diagnoseUnscopedReveals(document.body);
5718
5805
  }
5719
5806
  function mountTree(el) {
5720
5807
  if (isInIgnoredTree(el) || !document.body.contains(el))
@@ -5725,6 +5812,7 @@
5725
5812
  // Child scopes own their subtree before an existing parent scope parses the insertion.
5726
5813
  candidates.sort((a, b) => getDepth(b) - getDepth(a));
5727
5814
  candidates.forEach(element => !hasStructuralParent(element) && mount(element));
5815
+ diagnoseUnscopedReveals(el);
5728
5816
  if (getMountedScope(el))
5729
5817
  return;
5730
5818
  const ownerScope = getScopeFromElement(el);
@@ -5743,7 +5831,7 @@
5743
5831
  return;
5744
5832
  // Check if element removed but still has g-scope (possible in some edge cases)
5745
5833
  getAllMountedScopes().forEach((_, mountedEl) => {
5746
- if (!document.body.contains(mountedEl)) {
5834
+ if (!mountedEl.isConnected) {
5747
5835
  disposeEffects(mountedEl);
5748
5836
  }
5749
5837
  });
@@ -7055,7 +7143,8 @@
7055
7143
  el.dataset.gyosPersistId = key;
7056
7144
  return key;
7057
7145
  }
7058
- // Hidden parking lot keeps persisted nodes alive (e.g. audio keeps playing)
7146
+ // Keep the parking host outside body: body itself may be the swap target.
7147
+ // A disconnected parking host makes browsers pause otherwise persisted media.
7059
7148
  const persistParking = typeof document !== 'undefined'
7060
7149
  ? (() => {
7061
7150
  const park = document.createElement('div');
@@ -7064,12 +7153,7 @@
7064
7153
  park.style.top = '-99999px';
7065
7154
  park.style.width = '0';
7066
7155
  park.style.height = '0';
7067
- if (document.readyState === 'loading') {
7068
- document.addEventListener('DOMContentLoaded', () => document.body.appendChild(park));
7069
- }
7070
- else {
7071
- document.body.appendChild(park);
7072
- }
7156
+ document.documentElement.appendChild(park);
7073
7157
  return park;
7074
7158
  })()
7075
7159
  : null;
@@ -7080,8 +7164,8 @@
7080
7164
  return elements;
7081
7165
  }
7082
7166
  function ensureParkingIsConnected() {
7083
- if (persistParking && document.body && !persistParking.isConnected) {
7084
- document.body.appendChild(persistParking);
7167
+ if (persistParking && persistParking.parentElement !== document.documentElement) {
7168
+ document.documentElement.appendChild(persistParking);
7085
7169
  }
7086
7170
  }
7087
7171
  function detachPersist(root = document) {
@@ -7099,12 +7183,18 @@
7099
7183
  });
7100
7184
  }
7101
7185
  function mergePersistIntoLive(root) {
7186
+ // Return the host to the current body before scope mounting/cleanup inspects it.
7187
+ if (persistParking && persistParking.parentElement !== document.body) {
7188
+ document.body.appendChild(persistParking);
7189
+ }
7102
7190
  if (!persistEntries.size)
7103
7191
  return;
7104
7192
  // If placeholders lack ids but we only have one persist entry, assign its key for convenience
7105
7193
  if (persistEntries.size === 1) {
7106
7194
  const loneKey = Array.from(persistEntries.keys())[0];
7107
7195
  elementsIn(root).forEach(el => {
7196
+ if (persistParking?.contains(el))
7197
+ return;
7108
7198
  if (!getPersistKey(el, false)) {
7109
7199
  el.dataset.gyosPersistId = loneKey;
7110
7200
  }
@@ -7112,6 +7202,8 @@
7112
7202
  }
7113
7203
  // Element placeholders
7114
7204
  elementsIn(root).forEach(placeholder => {
7205
+ if (persistParking?.contains(placeholder))
7206
+ return;
7115
7207
  const key = getPersistKey(placeholder, false);
7116
7208
  if (!key)
7117
7209
  return;
@@ -7129,6 +7221,8 @@
7129
7221
  const toReplace = [];
7130
7222
  while (walker.nextNode()) {
7131
7223
  const comment = walker.currentNode;
7224
+ if (persistParking?.contains(comment))
7225
+ continue;
7132
7226
  const match = comment.data.match(/g-persist[:=]\s*([A-Za-z0-9_\-:.]+)/);
7133
7227
  if (match) {
7134
7228
  toReplace.push({ node: comment, key: match[1] });
@@ -7786,6 +7880,36 @@
7786
7880
  * Implements attribute-driven routing, snapshot caching, and persistent islands.
7787
7881
  */
7788
7882
  const submittingForms = new WeakSet();
7883
+ async function visit(url, options, fresh) {
7884
+ const destination = new URL(url, document.baseURI);
7885
+ if (!['http:', 'https:'].includes(destination.protocol) || destination.origin !== location.origin || destination.username || destination.password) {
7886
+ throw new TypeError('Gyos.navigate requires a same-origin HTTP(S) URL without credentials.');
7887
+ }
7888
+ if (options.target !== undefined && !(document.querySelector(options.target) instanceof HTMLElement)) {
7889
+ throw new TypeError('Gyos.navigate target does not exist.');
7890
+ }
7891
+ if (!document.querySelector('[g-boost]')) {
7892
+ throw new TypeError('Gyos.navigate requires a g-boost layout.');
7893
+ }
7894
+ startRouter();
7895
+ let result;
7896
+ await navigateRequest({
7897
+ url: destination.href, method: 'GET',
7898
+ changeState: options.history !== 'none', replace: options.history === 'replace',
7899
+ targetSelector: options.target, strictTarget: options.target !== undefined, swapMode: options.swap,
7900
+ currentHead: options.currentHead, scroll: options.scroll, signal: options.signal, fresh,
7901
+ onEnd: context => { result = context; }
7902
+ });
7903
+ return result;
7904
+ }
7905
+ /** Navigate through the boost pipeline. Resolves after navigation-end hooks. */
7906
+ function navigate(url, options = {}) {
7907
+ return visit(url, options, false);
7908
+ }
7909
+ /** Fetch the current URL again, preserving history and scroll by default. */
7910
+ function refresh(options = {}) {
7911
+ return visit(location.href, { history: 'none', scroll: false, ...options }, true);
7912
+ }
7789
7913
  const snapshots = new Map();
7790
7914
  const preloadCache = new Map();
7791
7915
  const preloadControllers = new Map();
@@ -8172,12 +8296,27 @@
8172
8296
  }
8173
8297
  console.error(`[GyosRouter] ${method} navigation could not be boosted; the request will not be replayed.`);
8174
8298
  }
8175
- async function navigate(opts) {
8299
+ async function navigateRequest(opts) {
8300
+ const finishUnstarted = () => {
8301
+ opts.onEnd?.({ from: currentUrl, url: opts.url, method: opts.method,
8302
+ trigger: opts.trigger || null, target: null, form: null, popstate: false,
8303
+ signal: opts.signal, status: null, committed: false, fallback: false, outcome: 'aborted' });
8304
+ };
8305
+ if (opts.signal?.aborted) {
8306
+ finishUnstarted();
8307
+ return;
8308
+ }
8176
8309
  while (activeNavigation) {
8177
8310
  const previous = activeNavigation;
8178
8311
  if (previous.committing) {
8179
8312
  log('[GyosRouter] Waiting for previous DOM commit');
8180
- await previous.done;
8313
+ try {
8314
+ await (opts.signal ? waitForNavigation(previous.done, opts.signal) : previous.done);
8315
+ }
8316
+ catch {
8317
+ finishUnstarted();
8318
+ return;
8319
+ }
8181
8320
  continue;
8182
8321
  }
8183
8322
  log('[GyosRouter] Cancelling previous navigation');
@@ -8196,6 +8335,10 @@
8196
8335
  resolveDone
8197
8336
  };
8198
8337
  activeNavigation = transaction;
8338
+ const abort = () => cancelNavigation(transaction);
8339
+ opts.signal?.addEventListener('abort', abort, { once: true });
8340
+ if (opts.signal?.aborted)
8341
+ abort();
8199
8342
  const currentBaseUrl = document.baseURI;
8200
8343
  rememberResourceUrls(document, currentBaseUrl);
8201
8344
  const context = {
@@ -8219,6 +8362,7 @@
8219
8362
  }
8220
8363
  };
8221
8364
  try {
8365
+ assertActiveNavigation(transaction);
8222
8366
  if (formEvent)
8223
8367
  document.dispatchEvent(new CustomEvent('gyos:form-start', { detail: { ...formEvent } }));
8224
8368
  runNavigationHooks(beforeNavigate, opts.url, context);
@@ -8231,6 +8375,10 @@
8231
8375
  saveScrollPosition();
8232
8376
  // Pick target element to swap
8233
8377
  let target = resolveTarget(opts.trigger, opts.targetSelector, opts.targetOutletIndex);
8378
+ if (opts.strictTarget && (!opts.targetSelector || !target?.matches(opts.targetSelector))) {
8379
+ context.outcome = 'invalid-response';
8380
+ return; // A queued explicit target disappeared; never broaden the swap.
8381
+ }
8234
8382
  context.target = target;
8235
8383
  if (!target) {
8236
8384
  if (isActiveNavigation(transaction))
@@ -8275,7 +8423,12 @@
8275
8423
  else {
8276
8424
  // Check preload cache if GET
8277
8425
  const preloadKey = canonicalUrl(finalUrl, true);
8278
- if (opts.method.toUpperCase() === 'GET' && preloadCache.has(preloadKey)) {
8426
+ if (opts.fresh) {
8427
+ preloadControllers.get(preloadKey)?.abort();
8428
+ preloadControllers.delete(preloadKey);
8429
+ preloadCache.delete(preloadKey);
8430
+ }
8431
+ if (!opts.fresh && opts.method.toUpperCase() === 'GET' && preloadCache.has(preloadKey)) {
8279
8432
  log('[GyosRouter] using preload cache for', finalUrl);
8280
8433
  try {
8281
8434
  response = await waitForNavigation(preloadCache.get(preloadKey), transaction.controller.signal);
@@ -8483,7 +8636,10 @@
8483
8636
  finalizeCommit();
8484
8637
  }
8485
8638
  // Handle scroll after mount scopes
8486
- if (changesState) {
8639
+ if (opts.scroll === false) {
8640
+ // Explicit refresh/navigation policy keeps the current viewport.
8641
+ }
8642
+ else if (changesState) {
8487
8643
  handleScroll(targetUrl, opts.trigger);
8488
8644
  }
8489
8645
  else if (opts.popstate) {
@@ -8548,6 +8704,7 @@
8548
8704
  activeNavigation = null;
8549
8705
  progressBar?.complete();
8550
8706
  }
8707
+ opts.signal?.removeEventListener('abort', abort);
8551
8708
  transaction.resolveDone();
8552
8709
  if (formEvent)
8553
8710
  submittingForms.delete(formEvent.form);
@@ -8558,6 +8715,7 @@
8558
8715
  detail: { ...formEvent, url, status, outcome, committed, fallback }
8559
8716
  }));
8560
8717
  }
8718
+ opts.onEnd?.({ ...context });
8561
8719
  }
8562
8720
  }
8563
8721
  function shouldBoost(el) {
@@ -8588,7 +8746,7 @@
8588
8746
  const scope = getScopeFromElement(element);
8589
8747
  const jsonData = evaluateExpression(decodeURIComponent(element.getAttribute(paramsAttr) || ''), scope, false);
8590
8748
  // The default changeState is false, as this is commonly used for: load more, infinite scroll, etc.
8591
- navigate({
8749
+ navigateRequest({
8592
8750
  url: parsedUrl.toString(), method, trigger: element, jsonData, changeState: false
8593
8751
  });
8594
8752
  }
@@ -8637,7 +8795,7 @@
8637
8795
  return;
8638
8796
  event.preventDefault();
8639
8797
  // The default changeState is true, as this is commonly used for: navigation, etc.
8640
- navigate({ url: url.toString(), method: 'GET', trigger: link, changeState: true });
8798
+ navigateRequest({ url: url.toString(), method: 'GET', trigger: link, changeState: true });
8641
8799
  }
8642
8800
  function onMouseOverCapture(event) {
8643
8801
  const target = event.target;
@@ -8693,7 +8851,7 @@
8693
8851
  return;
8694
8852
  const formData = new FormData(form, submitter);
8695
8853
  submittingForms.add(form);
8696
- void navigate({ url: url.toString(), method, trigger: form, form, formData, formEncoding, changeState: method === 'GET' });
8854
+ void navigateRequest({ url: url.toString(), method, trigger: form, form, formData, formEncoding, changeState: method === 'GET' });
8697
8855
  }
8698
8856
  function onPopState(event) {
8699
8857
  const url = window.location.href;
@@ -8711,14 +8869,14 @@
8711
8869
  }
8712
8870
  event.preventDefault();
8713
8871
  // The browser changes location before popstate fires. Stop any pending page
8714
- // script immediately, then let navigate() wait for its DOM finalizer.
8872
+ // script immediately, then let navigateRequest() wait for its DOM finalizer.
8715
8873
  if (activeNavigation?.committing)
8716
8874
  cancelNavigation(activeNavigation);
8717
8875
  // The browser has already moved to the destination history entry. Keep the
8718
8876
  // router's entry pointer aligned before any restored page script can navigate.
8719
8877
  currentHistoryEntryId = destinationEntryId;
8720
8878
  // No snapshot, do a normal navigation without changing history (changeState: false)
8721
- navigate({
8879
+ navigateRequest({
8722
8880
  url,
8723
8881
  method: 'GET',
8724
8882
  replace: true,
@@ -8800,10 +8958,12 @@
8800
8958
  onAfterNavigate,
8801
8959
  onBeforeSwap,
8802
8960
  onNavigationEnd,
8961
+ navigate,
8962
+ refresh,
8803
8963
  portalCreate,
8804
8964
  portalDestroy,
8805
8965
  setCspNonce,
8806
- version: '0.4.1'
8966
+ version: '0.5.1'
8807
8967
  };
8808
8968
 
8809
8969
  setExpressionRuntime(standardExpressionRuntime);
@@ -8834,6 +8994,7 @@
8834
8994
  exports.mountAll = mountAll;
8835
8995
  exports.mountTree = mountTree;
8836
8996
  exports.mountedScopes = getAllMountedScopes;
8997
+ exports.navigate = navigate;
8837
8998
  exports.nextTick = nextTick;
8838
8999
  exports.off = off;
8839
9000
  exports.on = on;
@@ -8847,6 +9008,7 @@
8847
9008
  exports.portalDestroy = portalDestroy;
8848
9009
  exports.provide = provide;
8849
9010
  exports.ready = ready;
9011
+ exports.refresh = refresh;
8850
9012
  exports.registerTransition = registerTransition;
8851
9013
  exports.removeStore = removeStore;
8852
9014
  exports.scope = scope;