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
  */
@@ -4515,6 +4515,79 @@ function getScopeVersion(target) {
4515
4515
  return scopeVersionMap.get(target);
4516
4516
  }
4517
4517
 
4518
+ /** Keep the longest already-ordered run of rows connected; move only the rest. */
4519
+ function placeKeyedRows(placeholder, rows) {
4520
+ const parent = placeholder.parentNode;
4521
+ if (!parent || rows.length === 0)
4522
+ return;
4523
+ const managed = new Set(rows);
4524
+ const positions = new Map();
4525
+ let boundary = placeholder.nextSibling;
4526
+ while (boundary && managed.has(boundary)) {
4527
+ positions.set(boundary, positions.size);
4528
+ boundary = boundary.nextSibling;
4529
+ }
4530
+ const active = placeholder.ownerDocument.activeElement;
4531
+ const ownsFocus = !!active && rows.some((row) => row === active || row.contains(active));
4532
+ const selection = ownsFocus && (active instanceof HTMLInputElement || active instanceof HTMLTextAreaElement)
4533
+ ? { start: active.selectionStart, end: active.selectionEnd, direction: active.selectionDirection }
4534
+ : null;
4535
+ if (positions.size !== rows.length) {
4536
+ // Leaving transition nodes, foreign siblings or externally detached rows:
4537
+ // preserve the established contiguous-after-placeholder placement contract.
4538
+ let previous = placeholder;
4539
+ for (const row of rows) {
4540
+ if (row !== previous.nextSibling)
4541
+ parent.insertBefore(row, previous.nextSibling);
4542
+ previous = row;
4543
+ }
4544
+ }
4545
+ else {
4546
+ const order = rows.map((row) => positions.get(row));
4547
+ let sorted = true;
4548
+ for (let i = 1; i < order.length; i++)
4549
+ if (order[i] < order[i - 1]) {
4550
+ sorted = false;
4551
+ break;
4552
+ }
4553
+ if (sorted)
4554
+ return;
4555
+ // Patience sorting: indices of a longest increasing subsequence, O(n log n).
4556
+ const tails = [], predecessors = new Array(order.length).fill(-1);
4557
+ for (let i = 0; i < order.length; i++) {
4558
+ let low = 0, high = tails.length;
4559
+ while (low < high) {
4560
+ const middle = (low + high) >>> 1;
4561
+ if (order[tails[middle]] < order[i])
4562
+ low = middle + 1;
4563
+ else
4564
+ high = middle;
4565
+ }
4566
+ if (low > 0)
4567
+ predecessors[i] = tails[low - 1];
4568
+ tails[low] = i;
4569
+ }
4570
+ const retained = new Set();
4571
+ for (let i = tails[tails.length - 1]; i >= 0; i = predecessors[i])
4572
+ retained.add(i);
4573
+ for (let i = rows.length - 1; i >= 0; i--) {
4574
+ const row = rows[i];
4575
+ if (!retained.has(i) && row.nextSibling !== boundary)
4576
+ parent.insertBefore(row, boundary);
4577
+ boundary = row;
4578
+ }
4579
+ }
4580
+ // insertBefore can blur a moved input. Restore only a surviving owned focus,
4581
+ // and never steal focus assigned to another control by application callbacks.
4582
+ const document = placeholder.ownerDocument;
4583
+ if (ownsFocus && active.isConnected && document.activeElement === document.body) {
4584
+ active.focus({ preventScroll: true });
4585
+ if (selection?.start != null && selection.end != null) {
4586
+ active.setSelectionRange(selection.start, selection.end, selection.direction || undefined);
4587
+ }
4588
+ }
4589
+ }
4590
+
4518
4591
  /**
4519
4592
  * Structural Directives (*if, *for)
4520
4593
  * Single-pass parser for conditional and list rendering with transitions
@@ -4695,6 +4768,7 @@ function processForWithKeys(placeholder, template, list, itemVar, keyExpr, curre
4695
4768
  });
4696
4769
  // Add/reorder items immediately (parallel with remove animations)
4697
4770
  let lastPlacedNode = placeholder;
4771
+ const rows = [];
4698
4772
  orderedKeys.forEach((key) => {
4699
4773
  const newItemData = newItemsMap.get(key);
4700
4774
  const { index } = newItemData;
@@ -4746,13 +4820,10 @@ function processForWithKeys(placeholder, template, list, itemVar, keyExpr, curre
4746
4820
  });
4747
4821
  }
4748
4822
  }
4749
- // Place each managed row directly after the previous row. This does not
4750
- // depend on formatting whitespace or unrelated sibling nodes.
4751
- if (itemElement !== lastPlacedNode.nextSibling) {
4752
- placeholder.parentNode?.insertBefore(itemElement, lastPlacedNode.nextSibling);
4753
- }
4823
+ rows.push(itemElement);
4754
4824
  lastPlacedNode = itemElement;
4755
4825
  });
4826
+ placeKeyedRows(placeholder, rows);
4756
4827
  }
4757
4828
  /**
4758
4829
  * Process *for without keys (simple re-render)
@@ -5630,6 +5701,21 @@ setMountFunction(mount);
5630
5701
  * Registry of all scopes
5631
5702
  */
5632
5703
  const scopeRegistry = new Map();
5704
+ const warnedReveals = new WeakSet();
5705
+ function diagnoseUnscopedReveals(root) {
5706
+ if (!DEBUG())
5707
+ return;
5708
+ const elements = [...root.querySelectorAll('[g-reveal]')];
5709
+ if (root instanceof Element && root.hasAttribute('g-reveal'))
5710
+ elements.unshift(root);
5711
+ for (const element of elements) {
5712
+ if (warnedReveals.has(element) || isInIgnoredTree(element)
5713
+ || element.closest('[g-scope]') || getScopeFromElement(element))
5714
+ continue;
5715
+ warnedReveals.add(element);
5716
+ console.warn('[Gyos] g-reveal has no owning scope. Add g-scope to its container; global reveal CSS may otherwise hide this content.', element);
5717
+ }
5718
+ }
5633
5719
  /**
5634
5720
  * Register a scope
5635
5721
  */
@@ -5677,6 +5763,7 @@ function mountAll(root) {
5677
5763
  allElements.sort((a, b) => getDepth(b) - getDepth(a));
5678
5764
  // Filter out elements inside structural directives - they will be mounted by structural processor
5679
5765
  allElements.forEach(el => !hasStructuralParent(el) && mount(el));
5766
+ diagnoseUnscopedReveals(document.body);
5680
5767
  }
5681
5768
  function mountTree(el) {
5682
5769
  if (isInIgnoredTree(el) || !document.body.contains(el))
@@ -5687,6 +5774,7 @@ function mountTree(el) {
5687
5774
  // Child scopes own their subtree before an existing parent scope parses the insertion.
5688
5775
  candidates.sort((a, b) => getDepth(b) - getDepth(a));
5689
5776
  candidates.forEach(element => !hasStructuralParent(element) && mount(element));
5777
+ diagnoseUnscopedReveals(el);
5690
5778
  if (getMountedScope(el))
5691
5779
  return;
5692
5780
  const ownerScope = getScopeFromElement(el);
@@ -5705,7 +5793,7 @@ function mount(el) {
5705
5793
  return;
5706
5794
  // Check if element removed but still has g-scope (possible in some edge cases)
5707
5795
  getAllMountedScopes().forEach((_, mountedEl) => {
5708
- if (!document.body.contains(mountedEl)) {
5796
+ if (!mountedEl.isConnected) {
5709
5797
  disposeEffects(mountedEl);
5710
5798
  }
5711
5799
  });
@@ -7031,7 +7119,8 @@ function getPersistKey(el, generateIfMissing = false) {
7031
7119
  el.dataset.gyosPersistId = key;
7032
7120
  return key;
7033
7121
  }
7034
- // Hidden parking lot keeps persisted nodes alive (e.g. audio keeps playing)
7122
+ // Keep the parking host outside body: body itself may be the swap target.
7123
+ // A disconnected parking host makes browsers pause otherwise persisted media.
7035
7124
  const persistParking = typeof document !== 'undefined'
7036
7125
  ? (() => {
7037
7126
  const park = document.createElement('div');
@@ -7040,12 +7129,7 @@ const persistParking = typeof document !== 'undefined'
7040
7129
  park.style.top = '-99999px';
7041
7130
  park.style.width = '0';
7042
7131
  park.style.height = '0';
7043
- if (document.readyState === 'loading') {
7044
- document.addEventListener('DOMContentLoaded', () => document.body.appendChild(park));
7045
- }
7046
- else {
7047
- document.body.appendChild(park);
7048
- }
7132
+ document.documentElement.appendChild(park);
7049
7133
  return park;
7050
7134
  })()
7051
7135
  : null;
@@ -7056,8 +7140,8 @@ function elementsIn(root) {
7056
7140
  return elements;
7057
7141
  }
7058
7142
  function ensureParkingIsConnected() {
7059
- if (persistParking && document.body && !persistParking.isConnected) {
7060
- document.body.appendChild(persistParking);
7143
+ if (persistParking && persistParking.parentElement !== document.documentElement) {
7144
+ document.documentElement.appendChild(persistParking);
7061
7145
  }
7062
7146
  }
7063
7147
  function detachPersist(root = document) {
@@ -7075,12 +7159,18 @@ function detachPersist(root = document) {
7075
7159
  });
7076
7160
  }
7077
7161
  function mergePersistIntoLive(root) {
7162
+ // Return the host to the current body before scope mounting/cleanup inspects it.
7163
+ if (persistParking && persistParking.parentElement !== document.body) {
7164
+ document.body.appendChild(persistParking);
7165
+ }
7078
7166
  if (!persistEntries.size)
7079
7167
  return;
7080
7168
  // If placeholders lack ids but we only have one persist entry, assign its key for convenience
7081
7169
  if (persistEntries.size === 1) {
7082
7170
  const loneKey = Array.from(persistEntries.keys())[0];
7083
7171
  elementsIn(root).forEach(el => {
7172
+ if (persistParking?.contains(el))
7173
+ return;
7084
7174
  if (!getPersistKey(el, false)) {
7085
7175
  el.dataset.gyosPersistId = loneKey;
7086
7176
  }
@@ -7088,6 +7178,8 @@ function mergePersistIntoLive(root) {
7088
7178
  }
7089
7179
  // Element placeholders
7090
7180
  elementsIn(root).forEach(placeholder => {
7181
+ if (persistParking?.contains(placeholder))
7182
+ return;
7091
7183
  const key = getPersistKey(placeholder, false);
7092
7184
  if (!key)
7093
7185
  return;
@@ -7105,6 +7197,8 @@ function mergePersistIntoLive(root) {
7105
7197
  const toReplace = [];
7106
7198
  while (walker.nextNode()) {
7107
7199
  const comment = walker.currentNode;
7200
+ if (persistParking?.contains(comment))
7201
+ continue;
7108
7202
  const match = comment.data.match(/g-persist[:=]\s*([A-Za-z0-9_\-:.]+)/);
7109
7203
  if (match) {
7110
7204
  toReplace.push({ node: comment, key: match[1] });
@@ -7762,6 +7856,36 @@ function prepareNavigationHtml(html) {
7762
7856
  * Implements attribute-driven routing, snapshot caching, and persistent islands.
7763
7857
  */
7764
7858
  const submittingForms = new WeakSet();
7859
+ async function visit(url, options, fresh) {
7860
+ const destination = new URL(url, document.baseURI);
7861
+ if (!['http:', 'https:'].includes(destination.protocol) || destination.origin !== location.origin || destination.username || destination.password) {
7862
+ throw new TypeError('Gyos.navigate requires a same-origin HTTP(S) URL without credentials.');
7863
+ }
7864
+ if (options.target !== undefined && !(document.querySelector(options.target) instanceof HTMLElement)) {
7865
+ throw new TypeError('Gyos.navigate target does not exist.');
7866
+ }
7867
+ if (!document.querySelector('[g-boost]')) {
7868
+ throw new TypeError('Gyos.navigate requires a g-boost layout.');
7869
+ }
7870
+ startRouter();
7871
+ let result;
7872
+ await navigateRequest({
7873
+ url: destination.href, method: 'GET',
7874
+ changeState: options.history !== 'none', replace: options.history === 'replace',
7875
+ targetSelector: options.target, strictTarget: options.target !== undefined, swapMode: options.swap,
7876
+ currentHead: options.currentHead, scroll: options.scroll, signal: options.signal, fresh,
7877
+ onEnd: context => { result = context; }
7878
+ });
7879
+ return result;
7880
+ }
7881
+ /** Navigate through the boost pipeline. Resolves after navigation-end hooks. */
7882
+ function navigate(url, options = {}) {
7883
+ return visit(url, options, false);
7884
+ }
7885
+ /** Fetch the current URL again, preserving history and scroll by default. */
7886
+ function refresh(options = {}) {
7887
+ return visit(location.href, { history: 'none', scroll: false, ...options }, true);
7888
+ }
7765
7889
  const snapshots = new Map();
7766
7890
  const preloadCache = new Map();
7767
7891
  const preloadControllers = new Map();
@@ -8148,12 +8272,27 @@ function fallbackFromBoost(opts, url, requestSent) {
8148
8272
  }
8149
8273
  console.error(`[GyosRouter] ${method} navigation could not be boosted; the request will not be replayed.`);
8150
8274
  }
8151
- async function navigate(opts) {
8275
+ async function navigateRequest(opts) {
8276
+ const finishUnstarted = () => {
8277
+ opts.onEnd?.({ from: currentUrl, url: opts.url, method: opts.method,
8278
+ trigger: opts.trigger || null, target: null, form: null, popstate: false,
8279
+ signal: opts.signal, status: null, committed: false, fallback: false, outcome: 'aborted' });
8280
+ };
8281
+ if (opts.signal?.aborted) {
8282
+ finishUnstarted();
8283
+ return;
8284
+ }
8152
8285
  while (activeNavigation) {
8153
8286
  const previous = activeNavigation;
8154
8287
  if (previous.committing) {
8155
8288
  log('[GyosRouter] Waiting for previous DOM commit');
8156
- await previous.done;
8289
+ try {
8290
+ await (opts.signal ? waitForNavigation(previous.done, opts.signal) : previous.done);
8291
+ }
8292
+ catch {
8293
+ finishUnstarted();
8294
+ return;
8295
+ }
8157
8296
  continue;
8158
8297
  }
8159
8298
  log('[GyosRouter] Cancelling previous navigation');
@@ -8172,6 +8311,10 @@ async function navigate(opts) {
8172
8311
  resolveDone
8173
8312
  };
8174
8313
  activeNavigation = transaction;
8314
+ const abort = () => cancelNavigation(transaction);
8315
+ opts.signal?.addEventListener('abort', abort, { once: true });
8316
+ if (opts.signal?.aborted)
8317
+ abort();
8175
8318
  const currentBaseUrl = document.baseURI;
8176
8319
  rememberResourceUrls(document, currentBaseUrl);
8177
8320
  const context = {
@@ -8195,6 +8338,7 @@ async function navigate(opts) {
8195
8338
  }
8196
8339
  };
8197
8340
  try {
8341
+ assertActiveNavigation(transaction);
8198
8342
  if (formEvent)
8199
8343
  document.dispatchEvent(new CustomEvent('gyos:form-start', { detail: { ...formEvent } }));
8200
8344
  runNavigationHooks(beforeNavigate, opts.url, context);
@@ -8207,6 +8351,10 @@ async function navigate(opts) {
8207
8351
  saveScrollPosition();
8208
8352
  // Pick target element to swap
8209
8353
  let target = resolveTarget(opts.trigger, opts.targetSelector, opts.targetOutletIndex);
8354
+ if (opts.strictTarget && (!opts.targetSelector || !target?.matches(opts.targetSelector))) {
8355
+ context.outcome = 'invalid-response';
8356
+ return; // A queued explicit target disappeared; never broaden the swap.
8357
+ }
8210
8358
  context.target = target;
8211
8359
  if (!target) {
8212
8360
  if (isActiveNavigation(transaction))
@@ -8251,7 +8399,12 @@ async function navigate(opts) {
8251
8399
  else {
8252
8400
  // Check preload cache if GET
8253
8401
  const preloadKey = canonicalUrl(finalUrl, true);
8254
- if (opts.method.toUpperCase() === 'GET' && preloadCache.has(preloadKey)) {
8402
+ if (opts.fresh) {
8403
+ preloadControllers.get(preloadKey)?.abort();
8404
+ preloadControllers.delete(preloadKey);
8405
+ preloadCache.delete(preloadKey);
8406
+ }
8407
+ if (!opts.fresh && opts.method.toUpperCase() === 'GET' && preloadCache.has(preloadKey)) {
8255
8408
  log('[GyosRouter] using preload cache for', finalUrl);
8256
8409
  try {
8257
8410
  response = await waitForNavigation(preloadCache.get(preloadKey), transaction.controller.signal);
@@ -8459,7 +8612,10 @@ async function navigate(opts) {
8459
8612
  finalizeCommit();
8460
8613
  }
8461
8614
  // Handle scroll after mount scopes
8462
- if (changesState) {
8615
+ if (opts.scroll === false) {
8616
+ // Explicit refresh/navigation policy keeps the current viewport.
8617
+ }
8618
+ else if (changesState) {
8463
8619
  handleScroll(targetUrl, opts.trigger);
8464
8620
  }
8465
8621
  else if (opts.popstate) {
@@ -8524,6 +8680,7 @@ async function navigate(opts) {
8524
8680
  activeNavigation = null;
8525
8681
  progressBar?.complete();
8526
8682
  }
8683
+ opts.signal?.removeEventListener('abort', abort);
8527
8684
  transaction.resolveDone();
8528
8685
  if (formEvent)
8529
8686
  submittingForms.delete(formEvent.form);
@@ -8534,6 +8691,7 @@ async function navigate(opts) {
8534
8691
  detail: { ...formEvent, url, status, outcome, committed, fallback }
8535
8692
  }));
8536
8693
  }
8694
+ opts.onEnd?.({ ...context });
8537
8695
  }
8538
8696
  }
8539
8697
  function shouldBoost(el) {
@@ -8564,7 +8722,7 @@ function onClickRouter(element) {
8564
8722
  const scope = getScopeFromElement(element);
8565
8723
  const jsonData = evaluateExpression(decodeURIComponent(element.getAttribute(paramsAttr) || ''), scope, false);
8566
8724
  // The default changeState is false, as this is commonly used for: load more, infinite scroll, etc.
8567
- navigate({
8725
+ navigateRequest({
8568
8726
  url: parsedUrl.toString(), method, trigger: element, jsonData, changeState: false
8569
8727
  });
8570
8728
  }
@@ -8613,7 +8771,7 @@ function onClick(event) {
8613
8771
  return;
8614
8772
  event.preventDefault();
8615
8773
  // The default changeState is true, as this is commonly used for: navigation, etc.
8616
- navigate({ url: url.toString(), method: 'GET', trigger: link, changeState: true });
8774
+ navigateRequest({ url: url.toString(), method: 'GET', trigger: link, changeState: true });
8617
8775
  }
8618
8776
  function onMouseOverCapture(event) {
8619
8777
  const target = event.target;
@@ -8669,7 +8827,7 @@ function onSubmit(event) {
8669
8827
  return;
8670
8828
  const formData = new FormData(form, submitter);
8671
8829
  submittingForms.add(form);
8672
- void navigate({ url: url.toString(), method, trigger: form, form, formData, formEncoding, changeState: method === 'GET' });
8830
+ void navigateRequest({ url: url.toString(), method, trigger: form, form, formData, formEncoding, changeState: method === 'GET' });
8673
8831
  }
8674
8832
  function onPopState(event) {
8675
8833
  const url = window.location.href;
@@ -8687,14 +8845,14 @@ function onPopState(event) {
8687
8845
  }
8688
8846
  event.preventDefault();
8689
8847
  // The browser changes location before popstate fires. Stop any pending page
8690
- // script immediately, then let navigate() wait for its DOM finalizer.
8848
+ // script immediately, then let navigateRequest() wait for its DOM finalizer.
8691
8849
  if (activeNavigation?.committing)
8692
8850
  cancelNavigation(activeNavigation);
8693
8851
  // The browser has already moved to the destination history entry. Keep the
8694
8852
  // router's entry pointer aligned before any restored page script can navigate.
8695
8853
  currentHistoryEntryId = destinationEntryId;
8696
8854
  // No snapshot, do a normal navigation without changing history (changeState: false)
8697
- navigate({
8855
+ navigateRequest({
8698
8856
  url,
8699
8857
  method: 'GET',
8700
8858
  replace: true,
@@ -8776,10 +8934,12 @@ const Gyos = {
8776
8934
  onAfterNavigate,
8777
8935
  onBeforeSwap,
8778
8936
  onNavigationEnd,
8937
+ navigate,
8938
+ refresh,
8779
8939
  portalCreate,
8780
8940
  portalDestroy,
8781
8941
  setCspNonce,
8782
- version: '0.4.1'
8942
+ version: '0.5.1'
8783
8943
  };
8784
8944
 
8785
8945
  // This file was generated. Do not modify manually!