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.auto.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
  */
@@ -4521,6 +4521,79 @@
4521
4521
  return scopeVersionMap.get(target);
4522
4522
  }
4523
4523
 
4524
+ /** Keep the longest already-ordered run of rows connected; move only the rest. */
4525
+ function placeKeyedRows(placeholder, rows) {
4526
+ const parent = placeholder.parentNode;
4527
+ if (!parent || rows.length === 0)
4528
+ return;
4529
+ const managed = new Set(rows);
4530
+ const positions = new Map();
4531
+ let boundary = placeholder.nextSibling;
4532
+ while (boundary && managed.has(boundary)) {
4533
+ positions.set(boundary, positions.size);
4534
+ boundary = boundary.nextSibling;
4535
+ }
4536
+ const active = placeholder.ownerDocument.activeElement;
4537
+ const ownsFocus = !!active && rows.some((row) => row === active || row.contains(active));
4538
+ const selection = ownsFocus && (active instanceof HTMLInputElement || active instanceof HTMLTextAreaElement)
4539
+ ? { start: active.selectionStart, end: active.selectionEnd, direction: active.selectionDirection }
4540
+ : null;
4541
+ if (positions.size !== rows.length) {
4542
+ // Leaving transition nodes, foreign siblings or externally detached rows:
4543
+ // preserve the established contiguous-after-placeholder placement contract.
4544
+ let previous = placeholder;
4545
+ for (const row of rows) {
4546
+ if (row !== previous.nextSibling)
4547
+ parent.insertBefore(row, previous.nextSibling);
4548
+ previous = row;
4549
+ }
4550
+ }
4551
+ else {
4552
+ const order = rows.map((row) => positions.get(row));
4553
+ let sorted = true;
4554
+ for (let i = 1; i < order.length; i++)
4555
+ if (order[i] < order[i - 1]) {
4556
+ sorted = false;
4557
+ break;
4558
+ }
4559
+ if (sorted)
4560
+ return;
4561
+ // Patience sorting: indices of a longest increasing subsequence, O(n log n).
4562
+ const tails = [], predecessors = new Array(order.length).fill(-1);
4563
+ for (let i = 0; i < order.length; i++) {
4564
+ let low = 0, high = tails.length;
4565
+ while (low < high) {
4566
+ const middle = (low + high) >>> 1;
4567
+ if (order[tails[middle]] < order[i])
4568
+ low = middle + 1;
4569
+ else
4570
+ high = middle;
4571
+ }
4572
+ if (low > 0)
4573
+ predecessors[i] = tails[low - 1];
4574
+ tails[low] = i;
4575
+ }
4576
+ const retained = new Set();
4577
+ for (let i = tails[tails.length - 1]; i >= 0; i = predecessors[i])
4578
+ retained.add(i);
4579
+ for (let i = rows.length - 1; i >= 0; i--) {
4580
+ const row = rows[i];
4581
+ if (!retained.has(i) && row.nextSibling !== boundary)
4582
+ parent.insertBefore(row, boundary);
4583
+ boundary = row;
4584
+ }
4585
+ }
4586
+ // insertBefore can blur a moved input. Restore only a surviving owned focus,
4587
+ // and never steal focus assigned to another control by application callbacks.
4588
+ const document = placeholder.ownerDocument;
4589
+ if (ownsFocus && active.isConnected && document.activeElement === document.body) {
4590
+ active.focus({ preventScroll: true });
4591
+ if (selection?.start != null && selection.end != null) {
4592
+ active.setSelectionRange(selection.start, selection.end, selection.direction || undefined);
4593
+ }
4594
+ }
4595
+ }
4596
+
4524
4597
  /**
4525
4598
  * Structural Directives (*if, *for)
4526
4599
  * Single-pass parser for conditional and list rendering with transitions
@@ -4701,6 +4774,7 @@
4701
4774
  });
4702
4775
  // Add/reorder items immediately (parallel with remove animations)
4703
4776
  let lastPlacedNode = placeholder;
4777
+ const rows = [];
4704
4778
  orderedKeys.forEach((key) => {
4705
4779
  const newItemData = newItemsMap.get(key);
4706
4780
  const { index } = newItemData;
@@ -4752,13 +4826,10 @@
4752
4826
  });
4753
4827
  }
4754
4828
  }
4755
- // Place each managed row directly after the previous row. This does not
4756
- // depend on formatting whitespace or unrelated sibling nodes.
4757
- if (itemElement !== lastPlacedNode.nextSibling) {
4758
- placeholder.parentNode?.insertBefore(itemElement, lastPlacedNode.nextSibling);
4759
- }
4829
+ rows.push(itemElement);
4760
4830
  lastPlacedNode = itemElement;
4761
4831
  });
4832
+ placeKeyedRows(placeholder, rows);
4762
4833
  }
4763
4834
  /**
4764
4835
  * Process *for without keys (simple re-render)
@@ -5636,6 +5707,21 @@
5636
5707
  * Registry of all scopes
5637
5708
  */
5638
5709
  const scopeRegistry = new Map();
5710
+ const warnedReveals = new WeakSet();
5711
+ function diagnoseUnscopedReveals(root) {
5712
+ if (!DEBUG())
5713
+ return;
5714
+ const elements = [...root.querySelectorAll('[g-reveal]')];
5715
+ if (root instanceof Element && root.hasAttribute('g-reveal'))
5716
+ elements.unshift(root);
5717
+ for (const element of elements) {
5718
+ if (warnedReveals.has(element) || isInIgnoredTree(element)
5719
+ || element.closest('[g-scope]') || getScopeFromElement(element))
5720
+ continue;
5721
+ warnedReveals.add(element);
5722
+ console.warn('[Gyos] g-reveal has no owning scope. Add g-scope to its container; global reveal CSS may otherwise hide this content.', element);
5723
+ }
5724
+ }
5639
5725
  /**
5640
5726
  * Register a scope
5641
5727
  */
@@ -5683,6 +5769,7 @@
5683
5769
  allElements.sort((a, b) => getDepth(b) - getDepth(a));
5684
5770
  // Filter out elements inside structural directives - they will be mounted by structural processor
5685
5771
  allElements.forEach(el => !hasStructuralParent(el) && mount(el));
5772
+ diagnoseUnscopedReveals(document.body);
5686
5773
  }
5687
5774
  function mountTree(el) {
5688
5775
  if (isInIgnoredTree(el) || !document.body.contains(el))
@@ -5693,6 +5780,7 @@
5693
5780
  // Child scopes own their subtree before an existing parent scope parses the insertion.
5694
5781
  candidates.sort((a, b) => getDepth(b) - getDepth(a));
5695
5782
  candidates.forEach(element => !hasStructuralParent(element) && mount(element));
5783
+ diagnoseUnscopedReveals(el);
5696
5784
  if (getMountedScope(el))
5697
5785
  return;
5698
5786
  const ownerScope = getScopeFromElement(el);
@@ -5711,7 +5799,7 @@
5711
5799
  return;
5712
5800
  // Check if element removed but still has g-scope (possible in some edge cases)
5713
5801
  getAllMountedScopes().forEach((_, mountedEl) => {
5714
- if (!document.body.contains(mountedEl)) {
5802
+ if (!mountedEl.isConnected) {
5715
5803
  disposeEffects(mountedEl);
5716
5804
  }
5717
5805
  });
@@ -7023,7 +7111,8 @@
7023
7111
  el.dataset.gyosPersistId = key;
7024
7112
  return key;
7025
7113
  }
7026
- // Hidden parking lot keeps persisted nodes alive (e.g. audio keeps playing)
7114
+ // Keep the parking host outside body: body itself may be the swap target.
7115
+ // A disconnected parking host makes browsers pause otherwise persisted media.
7027
7116
  const persistParking = typeof document !== 'undefined'
7028
7117
  ? (() => {
7029
7118
  const park = document.createElement('div');
@@ -7032,12 +7121,7 @@
7032
7121
  park.style.top = '-99999px';
7033
7122
  park.style.width = '0';
7034
7123
  park.style.height = '0';
7035
- if (document.readyState === 'loading') {
7036
- document.addEventListener('DOMContentLoaded', () => document.body.appendChild(park));
7037
- }
7038
- else {
7039
- document.body.appendChild(park);
7040
- }
7124
+ document.documentElement.appendChild(park);
7041
7125
  return park;
7042
7126
  })()
7043
7127
  : null;
@@ -7048,8 +7132,8 @@
7048
7132
  return elements;
7049
7133
  }
7050
7134
  function ensureParkingIsConnected() {
7051
- if (persistParking && document.body && !persistParking.isConnected) {
7052
- document.body.appendChild(persistParking);
7135
+ if (persistParking && persistParking.parentElement !== document.documentElement) {
7136
+ document.documentElement.appendChild(persistParking);
7053
7137
  }
7054
7138
  }
7055
7139
  function detachPersist(root = document) {
@@ -7067,12 +7151,18 @@
7067
7151
  });
7068
7152
  }
7069
7153
  function mergePersistIntoLive(root) {
7154
+ // Return the host to the current body before scope mounting/cleanup inspects it.
7155
+ if (persistParking && persistParking.parentElement !== document.body) {
7156
+ document.body.appendChild(persistParking);
7157
+ }
7070
7158
  if (!persistEntries.size)
7071
7159
  return;
7072
7160
  // If placeholders lack ids but we only have one persist entry, assign its key for convenience
7073
7161
  if (persistEntries.size === 1) {
7074
7162
  const loneKey = Array.from(persistEntries.keys())[0];
7075
7163
  elementsIn(root).forEach(el => {
7164
+ if (persistParking?.contains(el))
7165
+ return;
7076
7166
  if (!getPersistKey(el, false)) {
7077
7167
  el.dataset.gyosPersistId = loneKey;
7078
7168
  }
@@ -7080,6 +7170,8 @@
7080
7170
  }
7081
7171
  // Element placeholders
7082
7172
  elementsIn(root).forEach(placeholder => {
7173
+ if (persistParking?.contains(placeholder))
7174
+ return;
7083
7175
  const key = getPersistKey(placeholder, false);
7084
7176
  if (!key)
7085
7177
  return;
@@ -7097,6 +7189,8 @@
7097
7189
  const toReplace = [];
7098
7190
  while (walker.nextNode()) {
7099
7191
  const comment = walker.currentNode;
7192
+ if (persistParking?.contains(comment))
7193
+ continue;
7100
7194
  const match = comment.data.match(/g-persist[:=]\s*([A-Za-z0-9_\-:.]+)/);
7101
7195
  if (match) {
7102
7196
  toReplace.push({ node: comment, key: match[1] });
@@ -7754,6 +7848,36 @@
7754
7848
  * Implements attribute-driven routing, snapshot caching, and persistent islands.
7755
7849
  */
7756
7850
  const submittingForms = new WeakSet();
7851
+ async function visit(url, options, fresh) {
7852
+ const destination = new URL(url, document.baseURI);
7853
+ if (!['http:', 'https:'].includes(destination.protocol) || destination.origin !== location.origin || destination.username || destination.password) {
7854
+ throw new TypeError('Gyos.navigate requires a same-origin HTTP(S) URL without credentials.');
7855
+ }
7856
+ if (options.target !== undefined && !(document.querySelector(options.target) instanceof HTMLElement)) {
7857
+ throw new TypeError('Gyos.navigate target does not exist.');
7858
+ }
7859
+ if (!document.querySelector('[g-boost]')) {
7860
+ throw new TypeError('Gyos.navigate requires a g-boost layout.');
7861
+ }
7862
+ startRouter();
7863
+ let result;
7864
+ await navigateRequest({
7865
+ url: destination.href, method: 'GET',
7866
+ changeState: options.history !== 'none', replace: options.history === 'replace',
7867
+ targetSelector: options.target, strictTarget: options.target !== undefined, swapMode: options.swap,
7868
+ currentHead: options.currentHead, scroll: options.scroll, signal: options.signal, fresh,
7869
+ onEnd: context => { result = context; }
7870
+ });
7871
+ return result;
7872
+ }
7873
+ /** Navigate through the boost pipeline. Resolves after navigation-end hooks. */
7874
+ function navigate(url, options = {}) {
7875
+ return visit(url, options, false);
7876
+ }
7877
+ /** Fetch the current URL again, preserving history and scroll by default. */
7878
+ function refresh(options = {}) {
7879
+ return visit(location.href, { history: 'none', scroll: false, ...options }, true);
7880
+ }
7757
7881
  const snapshots = new Map();
7758
7882
  const preloadCache = new Map();
7759
7883
  const preloadControllers = new Map();
@@ -8140,12 +8264,27 @@
8140
8264
  }
8141
8265
  console.error(`[GyosRouter] ${method} navigation could not be boosted; the request will not be replayed.`);
8142
8266
  }
8143
- async function navigate(opts) {
8267
+ async function navigateRequest(opts) {
8268
+ const finishUnstarted = () => {
8269
+ opts.onEnd?.({ from: currentUrl, url: opts.url, method: opts.method,
8270
+ trigger: opts.trigger || null, target: null, form: null, popstate: false,
8271
+ signal: opts.signal, status: null, committed: false, fallback: false, outcome: 'aborted' });
8272
+ };
8273
+ if (opts.signal?.aborted) {
8274
+ finishUnstarted();
8275
+ return;
8276
+ }
8144
8277
  while (activeNavigation) {
8145
8278
  const previous = activeNavigation;
8146
8279
  if (previous.committing) {
8147
8280
  log('[GyosRouter] Waiting for previous DOM commit');
8148
- await previous.done;
8281
+ try {
8282
+ await (opts.signal ? waitForNavigation(previous.done, opts.signal) : previous.done);
8283
+ }
8284
+ catch {
8285
+ finishUnstarted();
8286
+ return;
8287
+ }
8149
8288
  continue;
8150
8289
  }
8151
8290
  log('[GyosRouter] Cancelling previous navigation');
@@ -8164,6 +8303,10 @@
8164
8303
  resolveDone
8165
8304
  };
8166
8305
  activeNavigation = transaction;
8306
+ const abort = () => cancelNavigation(transaction);
8307
+ opts.signal?.addEventListener('abort', abort, { once: true });
8308
+ if (opts.signal?.aborted)
8309
+ abort();
8167
8310
  const currentBaseUrl = document.baseURI;
8168
8311
  rememberResourceUrls(document, currentBaseUrl);
8169
8312
  const context = {
@@ -8187,6 +8330,7 @@
8187
8330
  }
8188
8331
  };
8189
8332
  try {
8333
+ assertActiveNavigation(transaction);
8190
8334
  if (formEvent)
8191
8335
  document.dispatchEvent(new CustomEvent('gyos:form-start', { detail: { ...formEvent } }));
8192
8336
  runNavigationHooks(beforeNavigate, opts.url, context);
@@ -8199,6 +8343,10 @@
8199
8343
  saveScrollPosition();
8200
8344
  // Pick target element to swap
8201
8345
  let target = resolveTarget(opts.trigger, opts.targetSelector, opts.targetOutletIndex);
8346
+ if (opts.strictTarget && (!opts.targetSelector || !target?.matches(opts.targetSelector))) {
8347
+ context.outcome = 'invalid-response';
8348
+ return; // A queued explicit target disappeared; never broaden the swap.
8349
+ }
8202
8350
  context.target = target;
8203
8351
  if (!target) {
8204
8352
  if (isActiveNavigation(transaction))
@@ -8243,7 +8391,12 @@
8243
8391
  else {
8244
8392
  // Check preload cache if GET
8245
8393
  const preloadKey = canonicalUrl(finalUrl, true);
8246
- if (opts.method.toUpperCase() === 'GET' && preloadCache.has(preloadKey)) {
8394
+ if (opts.fresh) {
8395
+ preloadControllers.get(preloadKey)?.abort();
8396
+ preloadControllers.delete(preloadKey);
8397
+ preloadCache.delete(preloadKey);
8398
+ }
8399
+ if (!opts.fresh && opts.method.toUpperCase() === 'GET' && preloadCache.has(preloadKey)) {
8247
8400
  log('[GyosRouter] using preload cache for', finalUrl);
8248
8401
  try {
8249
8402
  response = await waitForNavigation(preloadCache.get(preloadKey), transaction.controller.signal);
@@ -8451,7 +8604,10 @@
8451
8604
  finalizeCommit();
8452
8605
  }
8453
8606
  // Handle scroll after mount scopes
8454
- if (changesState) {
8607
+ if (opts.scroll === false) {
8608
+ // Explicit refresh/navigation policy keeps the current viewport.
8609
+ }
8610
+ else if (changesState) {
8455
8611
  handleScroll(targetUrl, opts.trigger);
8456
8612
  }
8457
8613
  else if (opts.popstate) {
@@ -8516,6 +8672,7 @@
8516
8672
  activeNavigation = null;
8517
8673
  progressBar?.complete();
8518
8674
  }
8675
+ opts.signal?.removeEventListener('abort', abort);
8519
8676
  transaction.resolveDone();
8520
8677
  if (formEvent)
8521
8678
  submittingForms.delete(formEvent.form);
@@ -8526,6 +8683,7 @@
8526
8683
  detail: { ...formEvent, url, status, outcome, committed, fallback }
8527
8684
  }));
8528
8685
  }
8686
+ opts.onEnd?.({ ...context });
8529
8687
  }
8530
8688
  }
8531
8689
  function shouldBoost(el) {
@@ -8556,7 +8714,7 @@
8556
8714
  const scope = getScopeFromElement(element);
8557
8715
  const jsonData = evaluateExpression(decodeURIComponent(element.getAttribute(paramsAttr) || ''), scope, false);
8558
8716
  // The default changeState is false, as this is commonly used for: load more, infinite scroll, etc.
8559
- navigate({
8717
+ navigateRequest({
8560
8718
  url: parsedUrl.toString(), method, trigger: element, jsonData, changeState: false
8561
8719
  });
8562
8720
  }
@@ -8605,7 +8763,7 @@
8605
8763
  return;
8606
8764
  event.preventDefault();
8607
8765
  // The default changeState is true, as this is commonly used for: navigation, etc.
8608
- navigate({ url: url.toString(), method: 'GET', trigger: link, changeState: true });
8766
+ navigateRequest({ url: url.toString(), method: 'GET', trigger: link, changeState: true });
8609
8767
  }
8610
8768
  function onMouseOverCapture(event) {
8611
8769
  const target = event.target;
@@ -8661,7 +8819,7 @@
8661
8819
  return;
8662
8820
  const formData = new FormData(form, submitter);
8663
8821
  submittingForms.add(form);
8664
- void navigate({ url: url.toString(), method, trigger: form, form, formData, formEncoding, changeState: method === 'GET' });
8822
+ void navigateRequest({ url: url.toString(), method, trigger: form, form, formData, formEncoding, changeState: method === 'GET' });
8665
8823
  }
8666
8824
  function onPopState(event) {
8667
8825
  const url = window.location.href;
@@ -8679,14 +8837,14 @@
8679
8837
  }
8680
8838
  event.preventDefault();
8681
8839
  // The browser changes location before popstate fires. Stop any pending page
8682
- // script immediately, then let navigate() wait for its DOM finalizer.
8840
+ // script immediately, then let navigateRequest() wait for its DOM finalizer.
8683
8841
  if (activeNavigation?.committing)
8684
8842
  cancelNavigation(activeNavigation);
8685
8843
  // The browser has already moved to the destination history entry. Keep the
8686
8844
  // router's entry pointer aligned before any restored page script can navigate.
8687
8845
  currentHistoryEntryId = destinationEntryId;
8688
8846
  // No snapshot, do a normal navigation without changing history (changeState: false)
8689
- navigate({
8847
+ navigateRequest({
8690
8848
  url,
8691
8849
  method: 'GET',
8692
8850
  replace: true,
@@ -8768,10 +8926,12 @@
8768
8926
  onAfterNavigate,
8769
8927
  onBeforeSwap,
8770
8928
  onNavigationEnd,
8929
+ navigate,
8930
+ refresh,
8771
8931
  portalCreate,
8772
8932
  portalDestroy,
8773
8933
  setCspNonce,
8774
- version: '0.4.1'
8934
+ version: '0.5.1'
8775
8935
  };
8776
8936
 
8777
8937
  const standardExpressionRuntime = {