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.csp.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
  */
@@ -11170,6 +11170,79 @@
11170
11170
  return scopeVersionMap.get(target);
11171
11171
  }
11172
11172
 
11173
+ /** Keep the longest already-ordered run of rows connected; move only the rest. */
11174
+ function placeKeyedRows(placeholder, rows) {
11175
+ const parent = placeholder.parentNode;
11176
+ if (!parent || rows.length === 0)
11177
+ return;
11178
+ const managed = new Set(rows);
11179
+ const positions = new Map();
11180
+ let boundary = placeholder.nextSibling;
11181
+ while (boundary && managed.has(boundary)) {
11182
+ positions.set(boundary, positions.size);
11183
+ boundary = boundary.nextSibling;
11184
+ }
11185
+ const active = placeholder.ownerDocument.activeElement;
11186
+ const ownsFocus = !!active && rows.some((row) => row === active || row.contains(active));
11187
+ const selection = ownsFocus && (active instanceof HTMLInputElement || active instanceof HTMLTextAreaElement)
11188
+ ? { start: active.selectionStart, end: active.selectionEnd, direction: active.selectionDirection }
11189
+ : null;
11190
+ if (positions.size !== rows.length) {
11191
+ // Leaving transition nodes, foreign siblings or externally detached rows:
11192
+ // preserve the established contiguous-after-placeholder placement contract.
11193
+ let previous = placeholder;
11194
+ for (const row of rows) {
11195
+ if (row !== previous.nextSibling)
11196
+ parent.insertBefore(row, previous.nextSibling);
11197
+ previous = row;
11198
+ }
11199
+ }
11200
+ else {
11201
+ const order = rows.map((row) => positions.get(row));
11202
+ let sorted = true;
11203
+ for (let i = 1; i < order.length; i++)
11204
+ if (order[i] < order[i - 1]) {
11205
+ sorted = false;
11206
+ break;
11207
+ }
11208
+ if (sorted)
11209
+ return;
11210
+ // Patience sorting: indices of a longest increasing subsequence, O(n log n).
11211
+ const tails = [], predecessors = new Array(order.length).fill(-1);
11212
+ for (let i = 0; i < order.length; i++) {
11213
+ let low = 0, high = tails.length;
11214
+ while (low < high) {
11215
+ const middle = (low + high) >>> 1;
11216
+ if (order[tails[middle]] < order[i])
11217
+ low = middle + 1;
11218
+ else
11219
+ high = middle;
11220
+ }
11221
+ if (low > 0)
11222
+ predecessors[i] = tails[low - 1];
11223
+ tails[low] = i;
11224
+ }
11225
+ const retained = new Set();
11226
+ for (let i = tails[tails.length - 1]; i >= 0; i = predecessors[i])
11227
+ retained.add(i);
11228
+ for (let i = rows.length - 1; i >= 0; i--) {
11229
+ const row = rows[i];
11230
+ if (!retained.has(i) && row.nextSibling !== boundary)
11231
+ parent.insertBefore(row, boundary);
11232
+ boundary = row;
11233
+ }
11234
+ }
11235
+ // insertBefore can blur a moved input. Restore only a surviving owned focus,
11236
+ // and never steal focus assigned to another control by application callbacks.
11237
+ const document = placeholder.ownerDocument;
11238
+ if (ownsFocus && active.isConnected && document.activeElement === document.body) {
11239
+ active.focus({ preventScroll: true });
11240
+ if (selection?.start != null && selection.end != null) {
11241
+ active.setSelectionRange(selection.start, selection.end, selection.direction || undefined);
11242
+ }
11243
+ }
11244
+ }
11245
+
11173
11246
  /**
11174
11247
  * Structural Directives (*if, *for)
11175
11248
  * Single-pass parser for conditional and list rendering with transitions
@@ -11350,6 +11423,7 @@
11350
11423
  });
11351
11424
  // Add/reorder items immediately (parallel with remove animations)
11352
11425
  let lastPlacedNode = placeholder;
11426
+ const rows = [];
11353
11427
  orderedKeys.forEach((key) => {
11354
11428
  const newItemData = newItemsMap.get(key);
11355
11429
  const { index } = newItemData;
@@ -11401,13 +11475,10 @@
11401
11475
  });
11402
11476
  }
11403
11477
  }
11404
- // Place each managed row directly after the previous row. This does not
11405
- // depend on formatting whitespace or unrelated sibling nodes.
11406
- if (itemElement !== lastPlacedNode.nextSibling) {
11407
- placeholder.parentNode?.insertBefore(itemElement, lastPlacedNode.nextSibling);
11408
- }
11478
+ rows.push(itemElement);
11409
11479
  lastPlacedNode = itemElement;
11410
11480
  });
11481
+ placeKeyedRows(placeholder, rows);
11411
11482
  }
11412
11483
  /**
11413
11484
  * Process *for without keys (simple re-render)
@@ -12285,6 +12356,21 @@
12285
12356
  * Registry of all scopes
12286
12357
  */
12287
12358
  const scopeRegistry = new Map();
12359
+ const warnedReveals = new WeakSet();
12360
+ function diagnoseUnscopedReveals(root) {
12361
+ if (!DEBUG())
12362
+ return;
12363
+ const elements = [...root.querySelectorAll('[g-reveal]')];
12364
+ if (root instanceof Element && root.hasAttribute('g-reveal'))
12365
+ elements.unshift(root);
12366
+ for (const element of elements) {
12367
+ if (warnedReveals.has(element) || isInIgnoredTree(element)
12368
+ || element.closest('[g-scope]') || getScopeFromElement(element))
12369
+ continue;
12370
+ warnedReveals.add(element);
12371
+ console.warn('[Gyos] g-reveal has no owning scope. Add g-scope to its container; global reveal CSS may otherwise hide this content.', element);
12372
+ }
12373
+ }
12288
12374
  /**
12289
12375
  * Register a scope
12290
12376
  */
@@ -12332,6 +12418,7 @@
12332
12418
  allElements.sort((a, b) => getDepth(b) - getDepth(a));
12333
12419
  // Filter out elements inside structural directives - they will be mounted by structural processor
12334
12420
  allElements.forEach(el => !hasStructuralParent(el) && mount(el));
12421
+ diagnoseUnscopedReveals(document.body);
12335
12422
  }
12336
12423
  function mountTree(el) {
12337
12424
  if (isInIgnoredTree(el) || !document.body.contains(el))
@@ -12342,6 +12429,7 @@
12342
12429
  // Child scopes own their subtree before an existing parent scope parses the insertion.
12343
12430
  candidates.sort((a, b) => getDepth(b) - getDepth(a));
12344
12431
  candidates.forEach(element => !hasStructuralParent(element) && mount(element));
12432
+ diagnoseUnscopedReveals(el);
12345
12433
  if (getMountedScope(el))
12346
12434
  return;
12347
12435
  const ownerScope = getScopeFromElement(el);
@@ -12360,7 +12448,7 @@
12360
12448
  return;
12361
12449
  // Check if element removed but still has g-scope (possible in some edge cases)
12362
12450
  getAllMountedScopes().forEach((_, mountedEl) => {
12363
- if (!document.body.contains(mountedEl)) {
12451
+ if (!mountedEl.isConnected) {
12364
12452
  disposeEffects(mountedEl);
12365
12453
  }
12366
12454
  });
@@ -13672,7 +13760,8 @@
13672
13760
  el.dataset.gyosPersistId = key;
13673
13761
  return key;
13674
13762
  }
13675
- // Hidden parking lot keeps persisted nodes alive (e.g. audio keeps playing)
13763
+ // Keep the parking host outside body: body itself may be the swap target.
13764
+ // A disconnected parking host makes browsers pause otherwise persisted media.
13676
13765
  const persistParking = typeof document !== 'undefined'
13677
13766
  ? (() => {
13678
13767
  const park = document.createElement('div');
@@ -13681,12 +13770,7 @@
13681
13770
  park.style.top = '-99999px';
13682
13771
  park.style.width = '0';
13683
13772
  park.style.height = '0';
13684
- if (document.readyState === 'loading') {
13685
- document.addEventListener('DOMContentLoaded', () => document.body.appendChild(park));
13686
- }
13687
- else {
13688
- document.body.appendChild(park);
13689
- }
13773
+ document.documentElement.appendChild(park);
13690
13774
  return park;
13691
13775
  })()
13692
13776
  : null;
@@ -13697,8 +13781,8 @@
13697
13781
  return elements;
13698
13782
  }
13699
13783
  function ensureParkingIsConnected() {
13700
- if (persistParking && document.body && !persistParking.isConnected) {
13701
- document.body.appendChild(persistParking);
13784
+ if (persistParking && persistParking.parentElement !== document.documentElement) {
13785
+ document.documentElement.appendChild(persistParking);
13702
13786
  }
13703
13787
  }
13704
13788
  function detachPersist(root = document) {
@@ -13716,12 +13800,18 @@
13716
13800
  });
13717
13801
  }
13718
13802
  function mergePersistIntoLive(root) {
13803
+ // Return the host to the current body before scope mounting/cleanup inspects it.
13804
+ if (persistParking && persistParking.parentElement !== document.body) {
13805
+ document.body.appendChild(persistParking);
13806
+ }
13719
13807
  if (!persistEntries.size)
13720
13808
  return;
13721
13809
  // If placeholders lack ids but we only have one persist entry, assign its key for convenience
13722
13810
  if (persistEntries.size === 1) {
13723
13811
  const loneKey = Array.from(persistEntries.keys())[0];
13724
13812
  elementsIn(root).forEach(el => {
13813
+ if (persistParking?.contains(el))
13814
+ return;
13725
13815
  if (!getPersistKey(el, false)) {
13726
13816
  el.dataset.gyosPersistId = loneKey;
13727
13817
  }
@@ -13729,6 +13819,8 @@
13729
13819
  }
13730
13820
  // Element placeholders
13731
13821
  elementsIn(root).forEach(placeholder => {
13822
+ if (persistParking?.contains(placeholder))
13823
+ return;
13732
13824
  const key = getPersistKey(placeholder, false);
13733
13825
  if (!key)
13734
13826
  return;
@@ -13746,6 +13838,8 @@
13746
13838
  const toReplace = [];
13747
13839
  while (walker.nextNode()) {
13748
13840
  const comment = walker.currentNode;
13841
+ if (persistParking?.contains(comment))
13842
+ continue;
13749
13843
  const match = comment.data.match(/g-persist[:=]\s*([A-Za-z0-9_\-:.]+)/);
13750
13844
  if (match) {
13751
13845
  toReplace.push({ node: comment, key: match[1] });
@@ -14403,6 +14497,36 @@
14403
14497
  * Implements attribute-driven routing, snapshot caching, and persistent islands.
14404
14498
  */
14405
14499
  const submittingForms = new WeakSet();
14500
+ async function visit(url, options, fresh) {
14501
+ const destination = new URL(url, document.baseURI);
14502
+ if (!['http:', 'https:'].includes(destination.protocol) || destination.origin !== location.origin || destination.username || destination.password) {
14503
+ throw new TypeError('Gyos.navigate requires a same-origin HTTP(S) URL without credentials.');
14504
+ }
14505
+ if (options.target !== undefined && !(document.querySelector(options.target) instanceof HTMLElement)) {
14506
+ throw new TypeError('Gyos.navigate target does not exist.');
14507
+ }
14508
+ if (!document.querySelector('[g-boost]')) {
14509
+ throw new TypeError('Gyos.navigate requires a g-boost layout.');
14510
+ }
14511
+ startRouter();
14512
+ let result;
14513
+ await navigateRequest({
14514
+ url: destination.href, method: 'GET',
14515
+ changeState: options.history !== 'none', replace: options.history === 'replace',
14516
+ targetSelector: options.target, strictTarget: options.target !== undefined, swapMode: options.swap,
14517
+ currentHead: options.currentHead, scroll: options.scroll, signal: options.signal, fresh,
14518
+ onEnd: context => { result = context; }
14519
+ });
14520
+ return result;
14521
+ }
14522
+ /** Navigate through the boost pipeline. Resolves after navigation-end hooks. */
14523
+ function navigate(url, options = {}) {
14524
+ return visit(url, options, false);
14525
+ }
14526
+ /** Fetch the current URL again, preserving history and scroll by default. */
14527
+ function refresh(options = {}) {
14528
+ return visit(location.href, { history: 'none', scroll: false, ...options }, true);
14529
+ }
14406
14530
  const snapshots = new Map();
14407
14531
  const preloadCache = new Map();
14408
14532
  const preloadControllers = new Map();
@@ -14789,12 +14913,27 @@
14789
14913
  }
14790
14914
  console.error(`[GyosRouter] ${method} navigation could not be boosted; the request will not be replayed.`);
14791
14915
  }
14792
- async function navigate(opts) {
14916
+ async function navigateRequest(opts) {
14917
+ const finishUnstarted = () => {
14918
+ opts.onEnd?.({ from: currentUrl, url: opts.url, method: opts.method,
14919
+ trigger: opts.trigger || null, target: null, form: null, popstate: false,
14920
+ signal: opts.signal, status: null, committed: false, fallback: false, outcome: 'aborted' });
14921
+ };
14922
+ if (opts.signal?.aborted) {
14923
+ finishUnstarted();
14924
+ return;
14925
+ }
14793
14926
  while (activeNavigation) {
14794
14927
  const previous = activeNavigation;
14795
14928
  if (previous.committing) {
14796
14929
  log('[GyosRouter] Waiting for previous DOM commit');
14797
- await previous.done;
14930
+ try {
14931
+ await (opts.signal ? waitForNavigation(previous.done, opts.signal) : previous.done);
14932
+ }
14933
+ catch {
14934
+ finishUnstarted();
14935
+ return;
14936
+ }
14798
14937
  continue;
14799
14938
  }
14800
14939
  log('[GyosRouter] Cancelling previous navigation');
@@ -14813,6 +14952,10 @@
14813
14952
  resolveDone
14814
14953
  };
14815
14954
  activeNavigation = transaction;
14955
+ const abort = () => cancelNavigation(transaction);
14956
+ opts.signal?.addEventListener('abort', abort, { once: true });
14957
+ if (opts.signal?.aborted)
14958
+ abort();
14816
14959
  const currentBaseUrl = document.baseURI;
14817
14960
  rememberResourceUrls(document, currentBaseUrl);
14818
14961
  const context = {
@@ -14836,6 +14979,7 @@
14836
14979
  }
14837
14980
  };
14838
14981
  try {
14982
+ assertActiveNavigation(transaction);
14839
14983
  if (formEvent)
14840
14984
  document.dispatchEvent(new CustomEvent('gyos:form-start', { detail: { ...formEvent } }));
14841
14985
  runNavigationHooks(beforeNavigate, opts.url, context);
@@ -14848,6 +14992,10 @@
14848
14992
  saveScrollPosition();
14849
14993
  // Pick target element to swap
14850
14994
  let target = resolveTarget(opts.trigger, opts.targetSelector, opts.targetOutletIndex);
14995
+ if (opts.strictTarget && (!opts.targetSelector || !target?.matches(opts.targetSelector))) {
14996
+ context.outcome = 'invalid-response';
14997
+ return; // A queued explicit target disappeared; never broaden the swap.
14998
+ }
14851
14999
  context.target = target;
14852
15000
  if (!target) {
14853
15001
  if (isActiveNavigation(transaction))
@@ -14892,7 +15040,12 @@
14892
15040
  else {
14893
15041
  // Check preload cache if GET
14894
15042
  const preloadKey = canonicalUrl(finalUrl, true);
14895
- if (opts.method.toUpperCase() === 'GET' && preloadCache.has(preloadKey)) {
15043
+ if (opts.fresh) {
15044
+ preloadControllers.get(preloadKey)?.abort();
15045
+ preloadControllers.delete(preloadKey);
15046
+ preloadCache.delete(preloadKey);
15047
+ }
15048
+ if (!opts.fresh && opts.method.toUpperCase() === 'GET' && preloadCache.has(preloadKey)) {
14896
15049
  log('[GyosRouter] using preload cache for', finalUrl);
14897
15050
  try {
14898
15051
  response = await waitForNavigation(preloadCache.get(preloadKey), transaction.controller.signal);
@@ -15100,7 +15253,10 @@
15100
15253
  finalizeCommit();
15101
15254
  }
15102
15255
  // Handle scroll after mount scopes
15103
- if (changesState) {
15256
+ if (opts.scroll === false) {
15257
+ // Explicit refresh/navigation policy keeps the current viewport.
15258
+ }
15259
+ else if (changesState) {
15104
15260
  handleScroll(targetUrl, opts.trigger);
15105
15261
  }
15106
15262
  else if (opts.popstate) {
@@ -15165,6 +15321,7 @@
15165
15321
  activeNavigation = null;
15166
15322
  progressBar?.complete();
15167
15323
  }
15324
+ opts.signal?.removeEventListener('abort', abort);
15168
15325
  transaction.resolveDone();
15169
15326
  if (formEvent)
15170
15327
  submittingForms.delete(formEvent.form);
@@ -15175,6 +15332,7 @@
15175
15332
  detail: { ...formEvent, url, status, outcome, committed, fallback }
15176
15333
  }));
15177
15334
  }
15335
+ opts.onEnd?.({ ...context });
15178
15336
  }
15179
15337
  }
15180
15338
  function shouldBoost(el) {
@@ -15205,7 +15363,7 @@
15205
15363
  const scope = getScopeFromElement(element);
15206
15364
  const jsonData = evaluateExpression(decodeURIComponent(element.getAttribute(paramsAttr) || ''), scope, false);
15207
15365
  // The default changeState is false, as this is commonly used for: load more, infinite scroll, etc.
15208
- navigate({
15366
+ navigateRequest({
15209
15367
  url: parsedUrl.toString(), method, trigger: element, jsonData, changeState: false
15210
15368
  });
15211
15369
  }
@@ -15254,7 +15412,7 @@
15254
15412
  return;
15255
15413
  event.preventDefault();
15256
15414
  // The default changeState is true, as this is commonly used for: navigation, etc.
15257
- navigate({ url: url.toString(), method: 'GET', trigger: link, changeState: true });
15415
+ navigateRequest({ url: url.toString(), method: 'GET', trigger: link, changeState: true });
15258
15416
  }
15259
15417
  function onMouseOverCapture(event) {
15260
15418
  const target = event.target;
@@ -15310,7 +15468,7 @@
15310
15468
  return;
15311
15469
  const formData = new FormData(form, submitter);
15312
15470
  submittingForms.add(form);
15313
- void navigate({ url: url.toString(), method, trigger: form, form, formData, formEncoding, changeState: method === 'GET' });
15471
+ void navigateRequest({ url: url.toString(), method, trigger: form, form, formData, formEncoding, changeState: method === 'GET' });
15314
15472
  }
15315
15473
  function onPopState(event) {
15316
15474
  const url = window.location.href;
@@ -15328,14 +15486,14 @@
15328
15486
  }
15329
15487
  event.preventDefault();
15330
15488
  // The browser changes location before popstate fires. Stop any pending page
15331
- // script immediately, then let navigate() wait for its DOM finalizer.
15489
+ // script immediately, then let navigateRequest() wait for its DOM finalizer.
15332
15490
  if (activeNavigation?.committing)
15333
15491
  cancelNavigation(activeNavigation);
15334
15492
  // The browser has already moved to the destination history entry. Keep the
15335
15493
  // router's entry pointer aligned before any restored page script can navigate.
15336
15494
  currentHistoryEntryId = destinationEntryId;
15337
15495
  // No snapshot, do a normal navigation without changing history (changeState: false)
15338
- navigate({
15496
+ navigateRequest({
15339
15497
  url,
15340
15498
  method: 'GET',
15341
15499
  replace: true,
@@ -15417,10 +15575,12 @@
15417
15575
  onAfterNavigate,
15418
15576
  onBeforeSwap,
15419
15577
  onNavigationEnd,
15578
+ navigate,
15579
+ refresh,
15420
15580
  portalCreate,
15421
15581
  portalDestroy,
15422
15582
  setCspNonce,
15423
- version: '0.4.1'
15583
+ version: '0.5.1'
15424
15584
  };
15425
15585
 
15426
15586
  setExpressionRuntime(cspExpressionRuntime);
@@ -15451,6 +15611,7 @@
15451
15611
  exports.mountAll = mountAll;
15452
15612
  exports.mountTree = mountTree;
15453
15613
  exports.mountedScopes = getAllMountedScopes;
15614
+ exports.navigate = navigate;
15454
15615
  exports.nextTick = nextTick;
15455
15616
  exports.off = off;
15456
15617
  exports.on = on;
@@ -15464,6 +15625,7 @@
15464
15625
  exports.portalDestroy = portalDestroy;
15465
15626
  exports.provide = provide;
15466
15627
  exports.ready = ready;
15628
+ exports.refresh = refresh;
15467
15629
  exports.registerTransition = registerTransition;
15468
15630
  exports.removeStore = removeStore;
15469
15631
  exports.scope = scope;