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
  */
@@ -11164,6 +11164,79 @@ function getScopeVersion(target) {
11164
11164
  return scopeVersionMap.get(target);
11165
11165
  }
11166
11166
 
11167
+ /** Keep the longest already-ordered run of rows connected; move only the rest. */
11168
+ function placeKeyedRows(placeholder, rows) {
11169
+ const parent = placeholder.parentNode;
11170
+ if (!parent || rows.length === 0)
11171
+ return;
11172
+ const managed = new Set(rows);
11173
+ const positions = new Map();
11174
+ let boundary = placeholder.nextSibling;
11175
+ while (boundary && managed.has(boundary)) {
11176
+ positions.set(boundary, positions.size);
11177
+ boundary = boundary.nextSibling;
11178
+ }
11179
+ const active = placeholder.ownerDocument.activeElement;
11180
+ const ownsFocus = !!active && rows.some((row) => row === active || row.contains(active));
11181
+ const selection = ownsFocus && (active instanceof HTMLInputElement || active instanceof HTMLTextAreaElement)
11182
+ ? { start: active.selectionStart, end: active.selectionEnd, direction: active.selectionDirection }
11183
+ : null;
11184
+ if (positions.size !== rows.length) {
11185
+ // Leaving transition nodes, foreign siblings or externally detached rows:
11186
+ // preserve the established contiguous-after-placeholder placement contract.
11187
+ let previous = placeholder;
11188
+ for (const row of rows) {
11189
+ if (row !== previous.nextSibling)
11190
+ parent.insertBefore(row, previous.nextSibling);
11191
+ previous = row;
11192
+ }
11193
+ }
11194
+ else {
11195
+ const order = rows.map((row) => positions.get(row));
11196
+ let sorted = true;
11197
+ for (let i = 1; i < order.length; i++)
11198
+ if (order[i] < order[i - 1]) {
11199
+ sorted = false;
11200
+ break;
11201
+ }
11202
+ if (sorted)
11203
+ return;
11204
+ // Patience sorting: indices of a longest increasing subsequence, O(n log n).
11205
+ const tails = [], predecessors = new Array(order.length).fill(-1);
11206
+ for (let i = 0; i < order.length; i++) {
11207
+ let low = 0, high = tails.length;
11208
+ while (low < high) {
11209
+ const middle = (low + high) >>> 1;
11210
+ if (order[tails[middle]] < order[i])
11211
+ low = middle + 1;
11212
+ else
11213
+ high = middle;
11214
+ }
11215
+ if (low > 0)
11216
+ predecessors[i] = tails[low - 1];
11217
+ tails[low] = i;
11218
+ }
11219
+ const retained = new Set();
11220
+ for (let i = tails[tails.length - 1]; i >= 0; i = predecessors[i])
11221
+ retained.add(i);
11222
+ for (let i = rows.length - 1; i >= 0; i--) {
11223
+ const row = rows[i];
11224
+ if (!retained.has(i) && row.nextSibling !== boundary)
11225
+ parent.insertBefore(row, boundary);
11226
+ boundary = row;
11227
+ }
11228
+ }
11229
+ // insertBefore can blur a moved input. Restore only a surviving owned focus,
11230
+ // and never steal focus assigned to another control by application callbacks.
11231
+ const document = placeholder.ownerDocument;
11232
+ if (ownsFocus && active.isConnected && document.activeElement === document.body) {
11233
+ active.focus({ preventScroll: true });
11234
+ if (selection?.start != null && selection.end != null) {
11235
+ active.setSelectionRange(selection.start, selection.end, selection.direction || undefined);
11236
+ }
11237
+ }
11238
+ }
11239
+
11167
11240
  /**
11168
11241
  * Structural Directives (*if, *for)
11169
11242
  * Single-pass parser for conditional and list rendering with transitions
@@ -11344,6 +11417,7 @@ function processForWithKeys(placeholder, template, list, itemVar, keyExpr, curre
11344
11417
  });
11345
11418
  // Add/reorder items immediately (parallel with remove animations)
11346
11419
  let lastPlacedNode = placeholder;
11420
+ const rows = [];
11347
11421
  orderedKeys.forEach((key) => {
11348
11422
  const newItemData = newItemsMap.get(key);
11349
11423
  const { index } = newItemData;
@@ -11395,13 +11469,10 @@ function processForWithKeys(placeholder, template, list, itemVar, keyExpr, curre
11395
11469
  });
11396
11470
  }
11397
11471
  }
11398
- // Place each managed row directly after the previous row. This does not
11399
- // depend on formatting whitespace or unrelated sibling nodes.
11400
- if (itemElement !== lastPlacedNode.nextSibling) {
11401
- placeholder.parentNode?.insertBefore(itemElement, lastPlacedNode.nextSibling);
11402
- }
11472
+ rows.push(itemElement);
11403
11473
  lastPlacedNode = itemElement;
11404
11474
  });
11475
+ placeKeyedRows(placeholder, rows);
11405
11476
  }
11406
11477
  /**
11407
11478
  * Process *for without keys (simple re-render)
@@ -12279,6 +12350,21 @@ setMountFunction(mount);
12279
12350
  * Registry of all scopes
12280
12351
  */
12281
12352
  const scopeRegistry = new Map();
12353
+ const warnedReveals = new WeakSet();
12354
+ function diagnoseUnscopedReveals(root) {
12355
+ if (!DEBUG())
12356
+ return;
12357
+ const elements = [...root.querySelectorAll('[g-reveal]')];
12358
+ if (root instanceof Element && root.hasAttribute('g-reveal'))
12359
+ elements.unshift(root);
12360
+ for (const element of elements) {
12361
+ if (warnedReveals.has(element) || isInIgnoredTree(element)
12362
+ || element.closest('[g-scope]') || getScopeFromElement(element))
12363
+ continue;
12364
+ warnedReveals.add(element);
12365
+ console.warn('[Gyos] g-reveal has no owning scope. Add g-scope to its container; global reveal CSS may otherwise hide this content.', element);
12366
+ }
12367
+ }
12282
12368
  /**
12283
12369
  * Register a scope
12284
12370
  */
@@ -12326,6 +12412,7 @@ function mountAll(root) {
12326
12412
  allElements.sort((a, b) => getDepth(b) - getDepth(a));
12327
12413
  // Filter out elements inside structural directives - they will be mounted by structural processor
12328
12414
  allElements.forEach(el => !hasStructuralParent(el) && mount(el));
12415
+ diagnoseUnscopedReveals(document.body);
12329
12416
  }
12330
12417
  function mountTree(el) {
12331
12418
  if (isInIgnoredTree(el) || !document.body.contains(el))
@@ -12336,6 +12423,7 @@ function mountTree(el) {
12336
12423
  // Child scopes own their subtree before an existing parent scope parses the insertion.
12337
12424
  candidates.sort((a, b) => getDepth(b) - getDepth(a));
12338
12425
  candidates.forEach(element => !hasStructuralParent(element) && mount(element));
12426
+ diagnoseUnscopedReveals(el);
12339
12427
  if (getMountedScope(el))
12340
12428
  return;
12341
12429
  const ownerScope = getScopeFromElement(el);
@@ -12354,7 +12442,7 @@ function mount(el) {
12354
12442
  return;
12355
12443
  // Check if element removed but still has g-scope (possible in some edge cases)
12356
12444
  getAllMountedScopes().forEach((_, mountedEl) => {
12357
- if (!document.body.contains(mountedEl)) {
12445
+ if (!mountedEl.isConnected) {
12358
12446
  disposeEffects(mountedEl);
12359
12447
  }
12360
12448
  });
@@ -13666,7 +13754,8 @@ function getPersistKey(el, generateIfMissing = false) {
13666
13754
  el.dataset.gyosPersistId = key;
13667
13755
  return key;
13668
13756
  }
13669
- // Hidden parking lot keeps persisted nodes alive (e.g. audio keeps playing)
13757
+ // Keep the parking host outside body: body itself may be the swap target.
13758
+ // A disconnected parking host makes browsers pause otherwise persisted media.
13670
13759
  const persistParking = typeof document !== 'undefined'
13671
13760
  ? (() => {
13672
13761
  const park = document.createElement('div');
@@ -13675,12 +13764,7 @@ const persistParking = typeof document !== 'undefined'
13675
13764
  park.style.top = '-99999px';
13676
13765
  park.style.width = '0';
13677
13766
  park.style.height = '0';
13678
- if (document.readyState === 'loading') {
13679
- document.addEventListener('DOMContentLoaded', () => document.body.appendChild(park));
13680
- }
13681
- else {
13682
- document.body.appendChild(park);
13683
- }
13767
+ document.documentElement.appendChild(park);
13684
13768
  return park;
13685
13769
  })()
13686
13770
  : null;
@@ -13691,8 +13775,8 @@ function elementsIn(root) {
13691
13775
  return elements;
13692
13776
  }
13693
13777
  function ensureParkingIsConnected() {
13694
- if (persistParking && document.body && !persistParking.isConnected) {
13695
- document.body.appendChild(persistParking);
13778
+ if (persistParking && persistParking.parentElement !== document.documentElement) {
13779
+ document.documentElement.appendChild(persistParking);
13696
13780
  }
13697
13781
  }
13698
13782
  function detachPersist(root = document) {
@@ -13710,12 +13794,18 @@ function detachPersist(root = document) {
13710
13794
  });
13711
13795
  }
13712
13796
  function mergePersistIntoLive(root) {
13797
+ // Return the host to the current body before scope mounting/cleanup inspects it.
13798
+ if (persistParking && persistParking.parentElement !== document.body) {
13799
+ document.body.appendChild(persistParking);
13800
+ }
13713
13801
  if (!persistEntries.size)
13714
13802
  return;
13715
13803
  // If placeholders lack ids but we only have one persist entry, assign its key for convenience
13716
13804
  if (persistEntries.size === 1) {
13717
13805
  const loneKey = Array.from(persistEntries.keys())[0];
13718
13806
  elementsIn(root).forEach(el => {
13807
+ if (persistParking?.contains(el))
13808
+ return;
13719
13809
  if (!getPersistKey(el, false)) {
13720
13810
  el.dataset.gyosPersistId = loneKey;
13721
13811
  }
@@ -13723,6 +13813,8 @@ function mergePersistIntoLive(root) {
13723
13813
  }
13724
13814
  // Element placeholders
13725
13815
  elementsIn(root).forEach(placeholder => {
13816
+ if (persistParking?.contains(placeholder))
13817
+ return;
13726
13818
  const key = getPersistKey(placeholder, false);
13727
13819
  if (!key)
13728
13820
  return;
@@ -13740,6 +13832,8 @@ function mergePersistIntoLive(root) {
13740
13832
  const toReplace = [];
13741
13833
  while (walker.nextNode()) {
13742
13834
  const comment = walker.currentNode;
13835
+ if (persistParking?.contains(comment))
13836
+ continue;
13743
13837
  const match = comment.data.match(/g-persist[:=]\s*([A-Za-z0-9_\-:.]+)/);
13744
13838
  if (match) {
13745
13839
  toReplace.push({ node: comment, key: match[1] });
@@ -14397,6 +14491,36 @@ function prepareNavigationHtml(html) {
14397
14491
  * Implements attribute-driven routing, snapshot caching, and persistent islands.
14398
14492
  */
14399
14493
  const submittingForms = new WeakSet();
14494
+ async function visit(url, options, fresh) {
14495
+ const destination = new URL(url, document.baseURI);
14496
+ if (!['http:', 'https:'].includes(destination.protocol) || destination.origin !== location.origin || destination.username || destination.password) {
14497
+ throw new TypeError('Gyos.navigate requires a same-origin HTTP(S) URL without credentials.');
14498
+ }
14499
+ if (options.target !== undefined && !(document.querySelector(options.target) instanceof HTMLElement)) {
14500
+ throw new TypeError('Gyos.navigate target does not exist.');
14501
+ }
14502
+ if (!document.querySelector('[g-boost]')) {
14503
+ throw new TypeError('Gyos.navigate requires a g-boost layout.');
14504
+ }
14505
+ startRouter();
14506
+ let result;
14507
+ await navigateRequest({
14508
+ url: destination.href, method: 'GET',
14509
+ changeState: options.history !== 'none', replace: options.history === 'replace',
14510
+ targetSelector: options.target, strictTarget: options.target !== undefined, swapMode: options.swap,
14511
+ currentHead: options.currentHead, scroll: options.scroll, signal: options.signal, fresh,
14512
+ onEnd: context => { result = context; }
14513
+ });
14514
+ return result;
14515
+ }
14516
+ /** Navigate through the boost pipeline. Resolves after navigation-end hooks. */
14517
+ function navigate(url, options = {}) {
14518
+ return visit(url, options, false);
14519
+ }
14520
+ /** Fetch the current URL again, preserving history and scroll by default. */
14521
+ function refresh(options = {}) {
14522
+ return visit(location.href, { history: 'none', scroll: false, ...options }, true);
14523
+ }
14400
14524
  const snapshots = new Map();
14401
14525
  const preloadCache = new Map();
14402
14526
  const preloadControllers = new Map();
@@ -14783,12 +14907,27 @@ function fallbackFromBoost(opts, url, requestSent) {
14783
14907
  }
14784
14908
  console.error(`[GyosRouter] ${method} navigation could not be boosted; the request will not be replayed.`);
14785
14909
  }
14786
- async function navigate(opts) {
14910
+ async function navigateRequest(opts) {
14911
+ const finishUnstarted = () => {
14912
+ opts.onEnd?.({ from: currentUrl, url: opts.url, method: opts.method,
14913
+ trigger: opts.trigger || null, target: null, form: null, popstate: false,
14914
+ signal: opts.signal, status: null, committed: false, fallback: false, outcome: 'aborted' });
14915
+ };
14916
+ if (opts.signal?.aborted) {
14917
+ finishUnstarted();
14918
+ return;
14919
+ }
14787
14920
  while (activeNavigation) {
14788
14921
  const previous = activeNavigation;
14789
14922
  if (previous.committing) {
14790
14923
  log('[GyosRouter] Waiting for previous DOM commit');
14791
- await previous.done;
14924
+ try {
14925
+ await (opts.signal ? waitForNavigation(previous.done, opts.signal) : previous.done);
14926
+ }
14927
+ catch {
14928
+ finishUnstarted();
14929
+ return;
14930
+ }
14792
14931
  continue;
14793
14932
  }
14794
14933
  log('[GyosRouter] Cancelling previous navigation');
@@ -14807,6 +14946,10 @@ async function navigate(opts) {
14807
14946
  resolveDone
14808
14947
  };
14809
14948
  activeNavigation = transaction;
14949
+ const abort = () => cancelNavigation(transaction);
14950
+ opts.signal?.addEventListener('abort', abort, { once: true });
14951
+ if (opts.signal?.aborted)
14952
+ abort();
14810
14953
  const currentBaseUrl = document.baseURI;
14811
14954
  rememberResourceUrls(document, currentBaseUrl);
14812
14955
  const context = {
@@ -14830,6 +14973,7 @@ async function navigate(opts) {
14830
14973
  }
14831
14974
  };
14832
14975
  try {
14976
+ assertActiveNavigation(transaction);
14833
14977
  if (formEvent)
14834
14978
  document.dispatchEvent(new CustomEvent('gyos:form-start', { detail: { ...formEvent } }));
14835
14979
  runNavigationHooks(beforeNavigate, opts.url, context);
@@ -14842,6 +14986,10 @@ async function navigate(opts) {
14842
14986
  saveScrollPosition();
14843
14987
  // Pick target element to swap
14844
14988
  let target = resolveTarget(opts.trigger, opts.targetSelector, opts.targetOutletIndex);
14989
+ if (opts.strictTarget && (!opts.targetSelector || !target?.matches(opts.targetSelector))) {
14990
+ context.outcome = 'invalid-response';
14991
+ return; // A queued explicit target disappeared; never broaden the swap.
14992
+ }
14845
14993
  context.target = target;
14846
14994
  if (!target) {
14847
14995
  if (isActiveNavigation(transaction))
@@ -14886,7 +15034,12 @@ async function navigate(opts) {
14886
15034
  else {
14887
15035
  // Check preload cache if GET
14888
15036
  const preloadKey = canonicalUrl(finalUrl, true);
14889
- if (opts.method.toUpperCase() === 'GET' && preloadCache.has(preloadKey)) {
15037
+ if (opts.fresh) {
15038
+ preloadControllers.get(preloadKey)?.abort();
15039
+ preloadControllers.delete(preloadKey);
15040
+ preloadCache.delete(preloadKey);
15041
+ }
15042
+ if (!opts.fresh && opts.method.toUpperCase() === 'GET' && preloadCache.has(preloadKey)) {
14890
15043
  log('[GyosRouter] using preload cache for', finalUrl);
14891
15044
  try {
14892
15045
  response = await waitForNavigation(preloadCache.get(preloadKey), transaction.controller.signal);
@@ -15094,7 +15247,10 @@ async function navigate(opts) {
15094
15247
  finalizeCommit();
15095
15248
  }
15096
15249
  // Handle scroll after mount scopes
15097
- if (changesState) {
15250
+ if (opts.scroll === false) {
15251
+ // Explicit refresh/navigation policy keeps the current viewport.
15252
+ }
15253
+ else if (changesState) {
15098
15254
  handleScroll(targetUrl, opts.trigger);
15099
15255
  }
15100
15256
  else if (opts.popstate) {
@@ -15159,6 +15315,7 @@ async function navigate(opts) {
15159
15315
  activeNavigation = null;
15160
15316
  progressBar?.complete();
15161
15317
  }
15318
+ opts.signal?.removeEventListener('abort', abort);
15162
15319
  transaction.resolveDone();
15163
15320
  if (formEvent)
15164
15321
  submittingForms.delete(formEvent.form);
@@ -15169,6 +15326,7 @@ async function navigate(opts) {
15169
15326
  detail: { ...formEvent, url, status, outcome, committed, fallback }
15170
15327
  }));
15171
15328
  }
15329
+ opts.onEnd?.({ ...context });
15172
15330
  }
15173
15331
  }
15174
15332
  function shouldBoost(el) {
@@ -15199,7 +15357,7 @@ function onClickRouter(element) {
15199
15357
  const scope = getScopeFromElement(element);
15200
15358
  const jsonData = evaluateExpression(decodeURIComponent(element.getAttribute(paramsAttr) || ''), scope, false);
15201
15359
  // The default changeState is false, as this is commonly used for: load more, infinite scroll, etc.
15202
- navigate({
15360
+ navigateRequest({
15203
15361
  url: parsedUrl.toString(), method, trigger: element, jsonData, changeState: false
15204
15362
  });
15205
15363
  }
@@ -15248,7 +15406,7 @@ function onClick(event) {
15248
15406
  return;
15249
15407
  event.preventDefault();
15250
15408
  // The default changeState is true, as this is commonly used for: navigation, etc.
15251
- navigate({ url: url.toString(), method: 'GET', trigger: link, changeState: true });
15409
+ navigateRequest({ url: url.toString(), method: 'GET', trigger: link, changeState: true });
15252
15410
  }
15253
15411
  function onMouseOverCapture(event) {
15254
15412
  const target = event.target;
@@ -15304,7 +15462,7 @@ function onSubmit(event) {
15304
15462
  return;
15305
15463
  const formData = new FormData(form, submitter);
15306
15464
  submittingForms.add(form);
15307
- void navigate({ url: url.toString(), method, trigger: form, form, formData, formEncoding, changeState: method === 'GET' });
15465
+ void navigateRequest({ url: url.toString(), method, trigger: form, form, formData, formEncoding, changeState: method === 'GET' });
15308
15466
  }
15309
15467
  function onPopState(event) {
15310
15468
  const url = window.location.href;
@@ -15322,14 +15480,14 @@ function onPopState(event) {
15322
15480
  }
15323
15481
  event.preventDefault();
15324
15482
  // The browser changes location before popstate fires. Stop any pending page
15325
- // script immediately, then let navigate() wait for its DOM finalizer.
15483
+ // script immediately, then let navigateRequest() wait for its DOM finalizer.
15326
15484
  if (activeNavigation?.committing)
15327
15485
  cancelNavigation(activeNavigation);
15328
15486
  // The browser has already moved to the destination history entry. Keep the
15329
15487
  // router's entry pointer aligned before any restored page script can navigate.
15330
15488
  currentHistoryEntryId = destinationEntryId;
15331
15489
  // No snapshot, do a normal navigation without changing history (changeState: false)
15332
- navigate({
15490
+ navigateRequest({
15333
15491
  url,
15334
15492
  method: 'GET',
15335
15493
  replace: true,
@@ -15411,13 +15569,15 @@ const Gyos = {
15411
15569
  onAfterNavigate,
15412
15570
  onBeforeSwap,
15413
15571
  onNavigationEnd,
15572
+ navigate,
15573
+ refresh,
15414
15574
  portalCreate,
15415
15575
  portalDestroy,
15416
15576
  setCspNonce,
15417
- version: '0.4.1'
15577
+ version: '0.5.1'
15418
15578
  };
15419
15579
 
15420
15580
  setExpressionRuntime(cspExpressionRuntime);
15421
15581
 
15422
- 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 };
15582
+ 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 };
15423
15583
  //# sourceMappingURL=gyos.csp.esm.js.map