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.esm.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
  */
@@ -4547,6 +4547,79 @@ function getScopeVersion(target) {
4547
4547
  return scopeVersionMap.get(target);
4548
4548
  }
4549
4549
 
4550
+ /** Keep the longest already-ordered run of rows connected; move only the rest. */
4551
+ function placeKeyedRows(placeholder, rows) {
4552
+ const parent = placeholder.parentNode;
4553
+ if (!parent || rows.length === 0)
4554
+ return;
4555
+ const managed = new Set(rows);
4556
+ const positions = new Map();
4557
+ let boundary = placeholder.nextSibling;
4558
+ while (boundary && managed.has(boundary)) {
4559
+ positions.set(boundary, positions.size);
4560
+ boundary = boundary.nextSibling;
4561
+ }
4562
+ const active = placeholder.ownerDocument.activeElement;
4563
+ const ownsFocus = !!active && rows.some((row) => row === active || row.contains(active));
4564
+ const selection = ownsFocus && (active instanceof HTMLInputElement || active instanceof HTMLTextAreaElement)
4565
+ ? { start: active.selectionStart, end: active.selectionEnd, direction: active.selectionDirection }
4566
+ : null;
4567
+ if (positions.size !== rows.length) {
4568
+ // Leaving transition nodes, foreign siblings or externally detached rows:
4569
+ // preserve the established contiguous-after-placeholder placement contract.
4570
+ let previous = placeholder;
4571
+ for (const row of rows) {
4572
+ if (row !== previous.nextSibling)
4573
+ parent.insertBefore(row, previous.nextSibling);
4574
+ previous = row;
4575
+ }
4576
+ }
4577
+ else {
4578
+ const order = rows.map((row) => positions.get(row));
4579
+ let sorted = true;
4580
+ for (let i = 1; i < order.length; i++)
4581
+ if (order[i] < order[i - 1]) {
4582
+ sorted = false;
4583
+ break;
4584
+ }
4585
+ if (sorted)
4586
+ return;
4587
+ // Patience sorting: indices of a longest increasing subsequence, O(n log n).
4588
+ const tails = [], predecessors = new Array(order.length).fill(-1);
4589
+ for (let i = 0; i < order.length; i++) {
4590
+ let low = 0, high = tails.length;
4591
+ while (low < high) {
4592
+ const middle = (low + high) >>> 1;
4593
+ if (order[tails[middle]] < order[i])
4594
+ low = middle + 1;
4595
+ else
4596
+ high = middle;
4597
+ }
4598
+ if (low > 0)
4599
+ predecessors[i] = tails[low - 1];
4600
+ tails[low] = i;
4601
+ }
4602
+ const retained = new Set();
4603
+ for (let i = tails[tails.length - 1]; i >= 0; i = predecessors[i])
4604
+ retained.add(i);
4605
+ for (let i = rows.length - 1; i >= 0; i--) {
4606
+ const row = rows[i];
4607
+ if (!retained.has(i) && row.nextSibling !== boundary)
4608
+ parent.insertBefore(row, boundary);
4609
+ boundary = row;
4610
+ }
4611
+ }
4612
+ // insertBefore can blur a moved input. Restore only a surviving owned focus,
4613
+ // and never steal focus assigned to another control by application callbacks.
4614
+ const document = placeholder.ownerDocument;
4615
+ if (ownsFocus && active.isConnected && document.activeElement === document.body) {
4616
+ active.focus({ preventScroll: true });
4617
+ if (selection?.start != null && selection.end != null) {
4618
+ active.setSelectionRange(selection.start, selection.end, selection.direction || undefined);
4619
+ }
4620
+ }
4621
+ }
4622
+
4550
4623
  /**
4551
4624
  * Structural Directives (*if, *for)
4552
4625
  * Single-pass parser for conditional and list rendering with transitions
@@ -4727,6 +4800,7 @@ function processForWithKeys(placeholder, template, list, itemVar, keyExpr, curre
4727
4800
  });
4728
4801
  // Add/reorder items immediately (parallel with remove animations)
4729
4802
  let lastPlacedNode = placeholder;
4803
+ const rows = [];
4730
4804
  orderedKeys.forEach((key) => {
4731
4805
  const newItemData = newItemsMap.get(key);
4732
4806
  const { index } = newItemData;
@@ -4778,13 +4852,10 @@ function processForWithKeys(placeholder, template, list, itemVar, keyExpr, curre
4778
4852
  });
4779
4853
  }
4780
4854
  }
4781
- // Place each managed row directly after the previous row. This does not
4782
- // depend on formatting whitespace or unrelated sibling nodes.
4783
- if (itemElement !== lastPlacedNode.nextSibling) {
4784
- placeholder.parentNode?.insertBefore(itemElement, lastPlacedNode.nextSibling);
4785
- }
4855
+ rows.push(itemElement);
4786
4856
  lastPlacedNode = itemElement;
4787
4857
  });
4858
+ placeKeyedRows(placeholder, rows);
4788
4859
  }
4789
4860
  /**
4790
4861
  * Process *for without keys (simple re-render)
@@ -5662,6 +5733,21 @@ setMountFunction(mount);
5662
5733
  * Registry of all scopes
5663
5734
  */
5664
5735
  const scopeRegistry = new Map();
5736
+ const warnedReveals = new WeakSet();
5737
+ function diagnoseUnscopedReveals(root) {
5738
+ if (!DEBUG())
5739
+ return;
5740
+ const elements = [...root.querySelectorAll('[g-reveal]')];
5741
+ if (root instanceof Element && root.hasAttribute('g-reveal'))
5742
+ elements.unshift(root);
5743
+ for (const element of elements) {
5744
+ if (warnedReveals.has(element) || isInIgnoredTree(element)
5745
+ || element.closest('[g-scope]') || getScopeFromElement(element))
5746
+ continue;
5747
+ warnedReveals.add(element);
5748
+ console.warn('[Gyos] g-reveal has no owning scope. Add g-scope to its container; global reveal CSS may otherwise hide this content.', element);
5749
+ }
5750
+ }
5665
5751
  /**
5666
5752
  * Register a scope
5667
5753
  */
@@ -5709,6 +5795,7 @@ function mountAll(root) {
5709
5795
  allElements.sort((a, b) => getDepth(b) - getDepth(a));
5710
5796
  // Filter out elements inside structural directives - they will be mounted by structural processor
5711
5797
  allElements.forEach(el => !hasStructuralParent(el) && mount(el));
5798
+ diagnoseUnscopedReveals(document.body);
5712
5799
  }
5713
5800
  function mountTree(el) {
5714
5801
  if (isInIgnoredTree(el) || !document.body.contains(el))
@@ -5719,6 +5806,7 @@ function mountTree(el) {
5719
5806
  // Child scopes own their subtree before an existing parent scope parses the insertion.
5720
5807
  candidates.sort((a, b) => getDepth(b) - getDepth(a));
5721
5808
  candidates.forEach(element => !hasStructuralParent(element) && mount(element));
5809
+ diagnoseUnscopedReveals(el);
5722
5810
  if (getMountedScope(el))
5723
5811
  return;
5724
5812
  const ownerScope = getScopeFromElement(el);
@@ -5737,7 +5825,7 @@ function mount(el) {
5737
5825
  return;
5738
5826
  // Check if element removed but still has g-scope (possible in some edge cases)
5739
5827
  getAllMountedScopes().forEach((_, mountedEl) => {
5740
- if (!document.body.contains(mountedEl)) {
5828
+ if (!mountedEl.isConnected) {
5741
5829
  disposeEffects(mountedEl);
5742
5830
  }
5743
5831
  });
@@ -7049,7 +7137,8 @@ function getPersistKey(el, generateIfMissing = false) {
7049
7137
  el.dataset.gyosPersistId = key;
7050
7138
  return key;
7051
7139
  }
7052
- // Hidden parking lot keeps persisted nodes alive (e.g. audio keeps playing)
7140
+ // Keep the parking host outside body: body itself may be the swap target.
7141
+ // A disconnected parking host makes browsers pause otherwise persisted media.
7053
7142
  const persistParking = typeof document !== 'undefined'
7054
7143
  ? (() => {
7055
7144
  const park = document.createElement('div');
@@ -7058,12 +7147,7 @@ const persistParking = typeof document !== 'undefined'
7058
7147
  park.style.top = '-99999px';
7059
7148
  park.style.width = '0';
7060
7149
  park.style.height = '0';
7061
- if (document.readyState === 'loading') {
7062
- document.addEventListener('DOMContentLoaded', () => document.body.appendChild(park));
7063
- }
7064
- else {
7065
- document.body.appendChild(park);
7066
- }
7150
+ document.documentElement.appendChild(park);
7067
7151
  return park;
7068
7152
  })()
7069
7153
  : null;
@@ -7074,8 +7158,8 @@ function elementsIn(root) {
7074
7158
  return elements;
7075
7159
  }
7076
7160
  function ensureParkingIsConnected() {
7077
- if (persistParking && document.body && !persistParking.isConnected) {
7078
- document.body.appendChild(persistParking);
7161
+ if (persistParking && persistParking.parentElement !== document.documentElement) {
7162
+ document.documentElement.appendChild(persistParking);
7079
7163
  }
7080
7164
  }
7081
7165
  function detachPersist(root = document) {
@@ -7093,12 +7177,18 @@ function detachPersist(root = document) {
7093
7177
  });
7094
7178
  }
7095
7179
  function mergePersistIntoLive(root) {
7180
+ // Return the host to the current body before scope mounting/cleanup inspects it.
7181
+ if (persistParking && persistParking.parentElement !== document.body) {
7182
+ document.body.appendChild(persistParking);
7183
+ }
7096
7184
  if (!persistEntries.size)
7097
7185
  return;
7098
7186
  // If placeholders lack ids but we only have one persist entry, assign its key for convenience
7099
7187
  if (persistEntries.size === 1) {
7100
7188
  const loneKey = Array.from(persistEntries.keys())[0];
7101
7189
  elementsIn(root).forEach(el => {
7190
+ if (persistParking?.contains(el))
7191
+ return;
7102
7192
  if (!getPersistKey(el, false)) {
7103
7193
  el.dataset.gyosPersistId = loneKey;
7104
7194
  }
@@ -7106,6 +7196,8 @@ function mergePersistIntoLive(root) {
7106
7196
  }
7107
7197
  // Element placeholders
7108
7198
  elementsIn(root).forEach(placeholder => {
7199
+ if (persistParking?.contains(placeholder))
7200
+ return;
7109
7201
  const key = getPersistKey(placeholder, false);
7110
7202
  if (!key)
7111
7203
  return;
@@ -7123,6 +7215,8 @@ function mergePersistIntoLive(root) {
7123
7215
  const toReplace = [];
7124
7216
  while (walker.nextNode()) {
7125
7217
  const comment = walker.currentNode;
7218
+ if (persistParking?.contains(comment))
7219
+ continue;
7126
7220
  const match = comment.data.match(/g-persist[:=]\s*([A-Za-z0-9_\-:.]+)/);
7127
7221
  if (match) {
7128
7222
  toReplace.push({ node: comment, key: match[1] });
@@ -7780,6 +7874,36 @@ function prepareNavigationHtml(html) {
7780
7874
  * Implements attribute-driven routing, snapshot caching, and persistent islands.
7781
7875
  */
7782
7876
  const submittingForms = new WeakSet();
7877
+ async function visit(url, options, fresh) {
7878
+ const destination = new URL(url, document.baseURI);
7879
+ if (!['http:', 'https:'].includes(destination.protocol) || destination.origin !== location.origin || destination.username || destination.password) {
7880
+ throw new TypeError('Gyos.navigate requires a same-origin HTTP(S) URL without credentials.');
7881
+ }
7882
+ if (options.target !== undefined && !(document.querySelector(options.target) instanceof HTMLElement)) {
7883
+ throw new TypeError('Gyos.navigate target does not exist.');
7884
+ }
7885
+ if (!document.querySelector('[g-boost]')) {
7886
+ throw new TypeError('Gyos.navigate requires a g-boost layout.');
7887
+ }
7888
+ startRouter();
7889
+ let result;
7890
+ await navigateRequest({
7891
+ url: destination.href, method: 'GET',
7892
+ changeState: options.history !== 'none', replace: options.history === 'replace',
7893
+ targetSelector: options.target, strictTarget: options.target !== undefined, swapMode: options.swap,
7894
+ currentHead: options.currentHead, scroll: options.scroll, signal: options.signal, fresh,
7895
+ onEnd: context => { result = context; }
7896
+ });
7897
+ return result;
7898
+ }
7899
+ /** Navigate through the boost pipeline. Resolves after navigation-end hooks. */
7900
+ function navigate(url, options = {}) {
7901
+ return visit(url, options, false);
7902
+ }
7903
+ /** Fetch the current URL again, preserving history and scroll by default. */
7904
+ function refresh(options = {}) {
7905
+ return visit(location.href, { history: 'none', scroll: false, ...options }, true);
7906
+ }
7783
7907
  const snapshots = new Map();
7784
7908
  const preloadCache = new Map();
7785
7909
  const preloadControllers = new Map();
@@ -8166,12 +8290,27 @@ function fallbackFromBoost(opts, url, requestSent) {
8166
8290
  }
8167
8291
  console.error(`[GyosRouter] ${method} navigation could not be boosted; the request will not be replayed.`);
8168
8292
  }
8169
- async function navigate(opts) {
8293
+ async function navigateRequest(opts) {
8294
+ const finishUnstarted = () => {
8295
+ opts.onEnd?.({ from: currentUrl, url: opts.url, method: opts.method,
8296
+ trigger: opts.trigger || null, target: null, form: null, popstate: false,
8297
+ signal: opts.signal, status: null, committed: false, fallback: false, outcome: 'aborted' });
8298
+ };
8299
+ if (opts.signal?.aborted) {
8300
+ finishUnstarted();
8301
+ return;
8302
+ }
8170
8303
  while (activeNavigation) {
8171
8304
  const previous = activeNavigation;
8172
8305
  if (previous.committing) {
8173
8306
  log('[GyosRouter] Waiting for previous DOM commit');
8174
- await previous.done;
8307
+ try {
8308
+ await (opts.signal ? waitForNavigation(previous.done, opts.signal) : previous.done);
8309
+ }
8310
+ catch {
8311
+ finishUnstarted();
8312
+ return;
8313
+ }
8175
8314
  continue;
8176
8315
  }
8177
8316
  log('[GyosRouter] Cancelling previous navigation');
@@ -8190,6 +8329,10 @@ async function navigate(opts) {
8190
8329
  resolveDone
8191
8330
  };
8192
8331
  activeNavigation = transaction;
8332
+ const abort = () => cancelNavigation(transaction);
8333
+ opts.signal?.addEventListener('abort', abort, { once: true });
8334
+ if (opts.signal?.aborted)
8335
+ abort();
8193
8336
  const currentBaseUrl = document.baseURI;
8194
8337
  rememberResourceUrls(document, currentBaseUrl);
8195
8338
  const context = {
@@ -8213,6 +8356,7 @@ async function navigate(opts) {
8213
8356
  }
8214
8357
  };
8215
8358
  try {
8359
+ assertActiveNavigation(transaction);
8216
8360
  if (formEvent)
8217
8361
  document.dispatchEvent(new CustomEvent('gyos:form-start', { detail: { ...formEvent } }));
8218
8362
  runNavigationHooks(beforeNavigate, opts.url, context);
@@ -8225,6 +8369,10 @@ async function navigate(opts) {
8225
8369
  saveScrollPosition();
8226
8370
  // Pick target element to swap
8227
8371
  let target = resolveTarget(opts.trigger, opts.targetSelector, opts.targetOutletIndex);
8372
+ if (opts.strictTarget && (!opts.targetSelector || !target?.matches(opts.targetSelector))) {
8373
+ context.outcome = 'invalid-response';
8374
+ return; // A queued explicit target disappeared; never broaden the swap.
8375
+ }
8228
8376
  context.target = target;
8229
8377
  if (!target) {
8230
8378
  if (isActiveNavigation(transaction))
@@ -8269,7 +8417,12 @@ async function navigate(opts) {
8269
8417
  else {
8270
8418
  // Check preload cache if GET
8271
8419
  const preloadKey = canonicalUrl(finalUrl, true);
8272
- if (opts.method.toUpperCase() === 'GET' && preloadCache.has(preloadKey)) {
8420
+ if (opts.fresh) {
8421
+ preloadControllers.get(preloadKey)?.abort();
8422
+ preloadControllers.delete(preloadKey);
8423
+ preloadCache.delete(preloadKey);
8424
+ }
8425
+ if (!opts.fresh && opts.method.toUpperCase() === 'GET' && preloadCache.has(preloadKey)) {
8273
8426
  log('[GyosRouter] using preload cache for', finalUrl);
8274
8427
  try {
8275
8428
  response = await waitForNavigation(preloadCache.get(preloadKey), transaction.controller.signal);
@@ -8477,7 +8630,10 @@ async function navigate(opts) {
8477
8630
  finalizeCommit();
8478
8631
  }
8479
8632
  // Handle scroll after mount scopes
8480
- if (changesState) {
8633
+ if (opts.scroll === false) {
8634
+ // Explicit refresh/navigation policy keeps the current viewport.
8635
+ }
8636
+ else if (changesState) {
8481
8637
  handleScroll(targetUrl, opts.trigger);
8482
8638
  }
8483
8639
  else if (opts.popstate) {
@@ -8542,6 +8698,7 @@ async function navigate(opts) {
8542
8698
  activeNavigation = null;
8543
8699
  progressBar?.complete();
8544
8700
  }
8701
+ opts.signal?.removeEventListener('abort', abort);
8545
8702
  transaction.resolveDone();
8546
8703
  if (formEvent)
8547
8704
  submittingForms.delete(formEvent.form);
@@ -8552,6 +8709,7 @@ async function navigate(opts) {
8552
8709
  detail: { ...formEvent, url, status, outcome, committed, fallback }
8553
8710
  }));
8554
8711
  }
8712
+ opts.onEnd?.({ ...context });
8555
8713
  }
8556
8714
  }
8557
8715
  function shouldBoost(el) {
@@ -8582,7 +8740,7 @@ function onClickRouter(element) {
8582
8740
  const scope = getScopeFromElement(element);
8583
8741
  const jsonData = evaluateExpression(decodeURIComponent(element.getAttribute(paramsAttr) || ''), scope, false);
8584
8742
  // The default changeState is false, as this is commonly used for: load more, infinite scroll, etc.
8585
- navigate({
8743
+ navigateRequest({
8586
8744
  url: parsedUrl.toString(), method, trigger: element, jsonData, changeState: false
8587
8745
  });
8588
8746
  }
@@ -8631,7 +8789,7 @@ function onClick(event) {
8631
8789
  return;
8632
8790
  event.preventDefault();
8633
8791
  // The default changeState is true, as this is commonly used for: navigation, etc.
8634
- navigate({ url: url.toString(), method: 'GET', trigger: link, changeState: true });
8792
+ navigateRequest({ url: url.toString(), method: 'GET', trigger: link, changeState: true });
8635
8793
  }
8636
8794
  function onMouseOverCapture(event) {
8637
8795
  const target = event.target;
@@ -8687,7 +8845,7 @@ function onSubmit(event) {
8687
8845
  return;
8688
8846
  const formData = new FormData(form, submitter);
8689
8847
  submittingForms.add(form);
8690
- void navigate({ url: url.toString(), method, trigger: form, form, formData, formEncoding, changeState: method === 'GET' });
8848
+ void navigateRequest({ url: url.toString(), method, trigger: form, form, formData, formEncoding, changeState: method === 'GET' });
8691
8849
  }
8692
8850
  function onPopState(event) {
8693
8851
  const url = window.location.href;
@@ -8705,14 +8863,14 @@ function onPopState(event) {
8705
8863
  }
8706
8864
  event.preventDefault();
8707
8865
  // The browser changes location before popstate fires. Stop any pending page
8708
- // script immediately, then let navigate() wait for its DOM finalizer.
8866
+ // script immediately, then let navigateRequest() wait for its DOM finalizer.
8709
8867
  if (activeNavigation?.committing)
8710
8868
  cancelNavigation(activeNavigation);
8711
8869
  // The browser has already moved to the destination history entry. Keep the
8712
8870
  // router's entry pointer aligned before any restored page script can navigate.
8713
8871
  currentHistoryEntryId = destinationEntryId;
8714
8872
  // No snapshot, do a normal navigation without changing history (changeState: false)
8715
- navigate({
8873
+ navigateRequest({
8716
8874
  url,
8717
8875
  method: 'GET',
8718
8876
  replace: true,
@@ -8794,13 +8952,15 @@ const Gyos = {
8794
8952
  onAfterNavigate,
8795
8953
  onBeforeSwap,
8796
8954
  onNavigationEnd,
8955
+ navigate,
8956
+ refresh,
8797
8957
  portalCreate,
8798
8958
  portalDestroy,
8799
8959
  setCspNonce,
8800
- version: '0.4.1'
8960
+ version: '0.5.1'
8801
8961
  };
8802
8962
 
8803
8963
  setExpressionRuntime(standardExpressionRuntime);
8804
8964
 
8805
- export { applyDirective, applyTransitionStyles, batch, disposeEffects as cleanup, clearAllEvents, computed, debounce, Gyos as default, directive, effect, emit, getEventListeners, getGlobalContainer, getStoreNames, getTransitionConfig, getValidator, getValidatorNames, hasStore, inject, isComputed, isSignal, markRaw, mount, mountAll, mountTree, getAllMountedScopes as mountedScopes, nextTick, off, on, onAfterNavigate, onBeforeNavigate, onBeforeSwap, onNavigationEnd, once, pipe, portalCreate, portalDestroy, provide, ready, registerTransition, removeStore, scope, setCspNonce, shallow, signal, startRouter, store, throttle, unref, untrack, useAsync, useCounter, useDebounce, useFetch, useInterval, useLocalStorage, useMediaQuery, useMouse, useThrottle, useTimeout, useToggle, useWindowSize, validate, validator };
8965
+ export { applyDirective, applyTransitionStyles, batch, disposeEffects as cleanup, clearAllEvents, computed, debounce, Gyos as default, directive, effect, emit, getEventListeners, getGlobalContainer, getStoreNames, getTransitionConfig, getValidator, getValidatorNames, hasStore, inject, isComputed, isSignal, markRaw, mount, mountAll, mountTree, getAllMountedScopes as mountedScopes, navigate, nextTick, off, on, onAfterNavigate, onBeforeNavigate, onBeforeSwap, onNavigationEnd, once, pipe, portalCreate, portalDestroy, provide, ready, refresh, registerTransition, removeStore, scope, setCspNonce, shallow, signal, startRouter, store, throttle, unref, untrack, useAsync, useCounter, useDebounce, useFetch, useInterval, useLocalStorage, useMediaQuery, useMouse, useThrottle, useTimeout, useToggle, useWindowSize, validate, validator };
8806
8966
  //# sourceMappingURL=gyos.esm.js.map