gyosjs 0.5.2 → 0.5.4

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.
Files changed (43) hide show
  1. package/README.md +1 -1
  2. package/dist/core/composables.d.ts +3 -1
  3. package/dist/core/composables.d.ts.map +1 -1
  4. package/dist/core/portal.d.ts.map +1 -1
  5. package/dist/core/reactive.d.ts.map +1 -1
  6. package/dist/core/router/router.d.ts.map +1 -1
  7. package/dist/core/router/scroll.d.ts.map +1 -1
  8. package/dist/core/router/swap.d.ts.map +1 -1
  9. package/dist/core/scope-registry.d.ts.map +1 -1
  10. package/dist/form/form-validation.d.ts.map +1 -1
  11. package/dist/gyos.auto.esm.js +418 -215
  12. package/dist/gyos.auto.esm.js.map +1 -1
  13. package/dist/gyos.auto.js +418 -215
  14. package/dist/gyos.auto.js.map +1 -1
  15. package/dist/gyos.auto.min.js +2 -2
  16. package/dist/gyos.csp.auto.esm.js +434 -231
  17. package/dist/gyos.csp.auto.esm.js.map +1 -1
  18. package/dist/gyos.csp.auto.js +434 -231
  19. package/dist/gyos.csp.auto.js.map +1 -1
  20. package/dist/gyos.csp.auto.min.js +2 -2
  21. package/dist/gyos.csp.esm.js +434 -231
  22. package/dist/gyos.csp.esm.js.map +1 -1
  23. package/dist/gyos.csp.js +434 -231
  24. package/dist/gyos.csp.js.map +1 -1
  25. package/dist/gyos.csp.min.js +2 -2
  26. package/dist/gyos.esm.js +418 -215
  27. package/dist/gyos.esm.js.map +1 -1
  28. package/dist/gyos.js +418 -215
  29. package/dist/gyos.js.map +1 -1
  30. package/dist/gyos.min.js +2 -2
  31. package/dist/reactivity/signal.d.ts.map +1 -1
  32. package/dist/runtime/csp-evaluator.d.ts.map +1 -1
  33. package/dist/template/bindings.d.ts.map +1 -1
  34. package/dist/template/cleanup.d.ts +1 -0
  35. package/dist/template/cleanup.d.ts.map +1 -1
  36. package/dist/template/directives.d.ts.map +1 -1
  37. package/dist/template/effect-queue.d.ts +1 -1
  38. package/dist/template/effect-queue.d.ts.map +1 -1
  39. package/dist/template/events.d.ts.map +1 -1
  40. package/dist/template/process.d.ts.map +1 -1
  41. package/dist/template/structurals/structural.d.ts.map +1 -1
  42. package/dist/utils/helpers.d.ts.map +1 -1
  43. package/package.json +1 -1
package/dist/gyos.esm.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * GyosJS v0.5.2
2
+ * GyosJS v0.5.4
3
3
  * (c) 2026
4
4
  * @license MIT
5
5
  */
@@ -116,25 +116,30 @@ function clone(obj) {
116
116
  }
117
117
  const cloned = {};
118
118
  for (const key in obj) {
119
- if (obj.hasOwnProperty(key)) {
119
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
120
120
  cloned[key] = clone(obj[key]);
121
121
  }
122
122
  }
123
123
  return cloned;
124
124
  }
125
125
  function deepEqual(a, b) {
126
- if (a === b)
126
+ if (Object.is(a, b))
127
127
  return true;
128
128
  if (typeof a !== 'object' || typeof b !== 'object' || a == null || b == null) {
129
129
  return false;
130
130
  }
131
+ if (a instanceof Date || b instanceof Date) {
132
+ return a instanceof Date && b instanceof Date && Object.is(a.getTime(), b.getTime());
133
+ }
134
+ if (Array.isArray(a) !== Array.isArray(b))
135
+ return false;
131
136
  const keysA = Object.keys(a);
132
137
  const keysB = Object.keys(b);
133
138
  if (keysA.length !== keysB.length) {
134
139
  return false;
135
140
  }
136
141
  for (const key of keysA) {
137
- if (!deepEqual(a[key], b[key])) {
142
+ if (!Object.prototype.hasOwnProperty.call(b, key) || !deepEqual(a[key], b[key])) {
138
143
  return false;
139
144
  }
140
145
  }
@@ -670,8 +675,11 @@ function effect(fn) {
670
675
  execute.__dependencies = dependencies;
671
676
  execute.__versions = versions;
672
677
  try {
673
- const nextCleanup = fn();
674
- cleanup = typeof nextCleanup === 'function' ? nextCleanup : undefined;
678
+ // The previous cleanup can dispose this effect before the next run.
679
+ if (active) {
680
+ const nextCleanup = fn();
681
+ cleanup = typeof nextCleanup === 'function' ? nextCleanup : undefined;
682
+ }
675
683
  }
676
684
  catch (error) {
677
685
  console.error('[Effect] Error in effect:', error);
@@ -680,6 +688,25 @@ function effect(fn) {
680
688
  finally {
681
689
  initialized = true;
682
690
  currentEffect = prevEffect;
691
+ // stop() may have been called inside fn, before its cleanup was returned
692
+ // or before later reads registered more dependencies.
693
+ if (!active) {
694
+ dependencies.forEach(dependency => dependency.delete(execute));
695
+ dependencies.clear();
696
+ versions.clear();
697
+ effectQueue.delete(execute);
698
+ batchedEffects.delete(execute);
699
+ const finalCleanup = cleanup;
700
+ cleanup = undefined;
701
+ if (finalCleanup) {
702
+ try {
703
+ untrack(finalCleanup);
704
+ }
705
+ catch (error) {
706
+ console.error('[Effect] Error in final cleanup:', error);
707
+ }
708
+ }
709
+ }
683
710
  effectDepth--;
684
711
  runningEffects.delete(execute);
685
712
  // Flush queue when we're back to top level
@@ -704,8 +731,10 @@ function effect(fn) {
704
731
  dependencies.clear();
705
732
  versions.clear();
706
733
  if (cleanup) {
734
+ const finalCleanup = cleanup;
735
+ cleanup = undefined;
707
736
  try {
708
- untrack(cleanup);
737
+ untrack(finalCleanup);
709
738
  }
710
739
  catch (error) {
711
740
  console.error('[Effect] Error in final cleanup:', error);
@@ -1433,11 +1462,6 @@ function evaluateExpression(expr, scope, allowPipes = true) {
1433
1462
  * @returns Evaluated value
1434
1463
  */
1435
1464
  function evaluateSimpleExpression(expr, scope) {
1436
- // Handle string literals
1437
- if ((expr.startsWith("'") && expr.endsWith("'")) ||
1438
- (expr.startsWith('"') && expr.endsWith('"'))) {
1439
- return expr.slice(1, -1);
1440
- }
1441
1465
  // Handle numbers
1442
1466
  if (!isNaN(Number(expr))) {
1443
1467
  return Number(expr);
@@ -1484,6 +1508,8 @@ function unmountScope(el) {
1484
1508
  let instance = mountedScopes.get(el);
1485
1509
  if (!instance)
1486
1510
  return;
1511
+ // A hook may call cleanup again; each mount is disposed at most once.
1512
+ mountedScopes.delete(el);
1487
1513
  // Cleanup all effects
1488
1514
  if (instance.__gyos_effects__) {
1489
1515
  instance.__gyos_effects__.forEach((cleanup) => {
@@ -1498,7 +1524,12 @@ function unmountScope(el) {
1498
1524
  }
1499
1525
  // Call lifecycle hook
1500
1526
  if (instance.onUnmount) {
1501
- instance.onUnmount.call(instance);
1527
+ try {
1528
+ instance.onUnmount.call(instance);
1529
+ }
1530
+ catch (error) {
1531
+ console.error('[Component] Error in onUnmount:', error);
1532
+ }
1502
1533
  }
1503
1534
  // Clear reference on element
1504
1535
  el.__gyos_scope__ = null;
@@ -1535,6 +1566,9 @@ function currentQueue() {
1535
1566
  return effectQueueStack[effectQueueStack.length - 1];
1536
1567
  }
1537
1568
  function attachDispose(target, runner) {
1569
+ // An earlier queued content binding can replace this subtree during flush.
1570
+ if (!target.isConnected)
1571
+ return;
1538
1572
  const dispose = effect(runner);
1539
1573
  if (!target.__gyos_effects__) {
1540
1574
  target.__gyos_effects__ = [];
@@ -2454,6 +2488,125 @@ function applyLeaveTransition(element, scope, removeElement = true) {
2454
2488
  return transitionManager.leave(element, transitionConfig, removeElement);
2455
2489
  }
2456
2490
 
2491
+ /**
2492
+ * Portal/Teleport System - Render content in different DOM location
2493
+ * Useful for modals, tooltips, notifications that need to break out of parent containers
2494
+ *
2495
+ * @example
2496
+ * // Portal to body (for modals)
2497
+ * <div g-portal="body">
2498
+ * <div class="modal">Modal content</div>
2499
+ * </div>
2500
+ *
2501
+ * @example
2502
+ * // Portal to specific element
2503
+ * <div g-portal="#notifications">
2504
+ * <div class="toast">Toast message</div>
2505
+ * </div>
2506
+ */
2507
+ /**
2508
+ * Create a portal - Move element to target location
2509
+ *
2510
+ * @param sourceEl - Element to teleport
2511
+ * @param targetSelector - CSS selector for destination
2512
+ *
2513
+ * @example
2514
+ * portalCreate(modalEl, 'body');
2515
+ * portalCreate(tooltipEl, '#tooltip-container');
2516
+ */
2517
+ function portalCreate(sourceEl, targetSelector) {
2518
+ if (!sourceEl)
2519
+ return;
2520
+ const target = document.querySelector(targetSelector);
2521
+ if (!target) {
2522
+ console.warn(`[GyosJS] Portal target "${targetSelector}" not found`);
2523
+ return;
2524
+ }
2525
+ // Create placeholder comment to mark original position
2526
+ const placeholder = document.createComment('g-portal');
2527
+ sourceEl.parentNode?.insertBefore(placeholder, sourceEl);
2528
+ // Store original parent for restoration
2529
+ sourceEl.__portal_placeholder__ = placeholder;
2530
+ sourceEl.__portal_target__ = target;
2531
+ placeholder.__gyos_portal__ = sourceEl;
2532
+ // Move the entire element to target
2533
+ target.appendChild(sourceEl);
2534
+ DEBUG() && console.log('[Portal] Created - moved element to', targetSelector);
2535
+ }
2536
+ /**
2537
+ * Destroy a portal - Restore element to original position
2538
+ *
2539
+ * @param sourceEl - Element to restore
2540
+ *
2541
+ * @example
2542
+ * portalDestroy(modalEl); // Returns modal to original location
2543
+ */
2544
+ function portalDestroy(sourceEl) {
2545
+ if (!sourceEl)
2546
+ return;
2547
+ const placeholder = sourceEl.__portal_placeholder__;
2548
+ if (placeholder && placeholder.parentNode) {
2549
+ delete placeholder.__gyos_portal__;
2550
+ // Move element back to original position
2551
+ placeholder.parentNode.insertBefore(sourceEl, placeholder);
2552
+ placeholder.remove();
2553
+ delete sourceEl.__portal_placeholder__;
2554
+ delete sourceEl.__portal_target__;
2555
+ DEBUG() && console.log('[Portal] Destroyed - restored element to original position');
2556
+ }
2557
+ }
2558
+
2559
+ /**
2560
+ * Cleanup utilities for disposing effects and event listeners
2561
+ */
2562
+ /**
2563
+ * Dispose all effects attached to an element and its descendants
2564
+ * Handles both element effects (__gyos_effects__) and component lifecycle
2565
+ */
2566
+ function disposeEffects(element = document.body, removeElement = false) {
2567
+ if (!element)
2568
+ return;
2569
+ disposeNode(element);
2570
+ if (removeElement)
2571
+ element.remove();
2572
+ }
2573
+ function disposeNode(element, removeElement = false) {
2574
+ untrack(() => disposeNodeInternal(element, removeElement));
2575
+ }
2576
+ function disposeNodeInternal(element, removeElement = false) {
2577
+ const portal = element.__gyos_portal__;
2578
+ if (portal) {
2579
+ delete element.__gyos_portal__;
2580
+ disposeNode(portal, removeElement);
2581
+ }
2582
+ // Include structural comment anchors. Snapshot before hooks mutate the tree.
2583
+ const children = Array.from(element.childNodes);
2584
+ const effects = element.__gyos_effects__;
2585
+ // Release ownership before callbacks to make reentrant cleanup safe.
2586
+ element.__gyos_effects__ = null;
2587
+ // Unmount scope if element has one (calls onUnmount + cleans instance.__gyos_effects__)
2588
+ if (element.hasAttribute?.('g-scope') || element.__gyos_scope__) {
2589
+ unmountScope(element);
2590
+ }
2591
+ // Dispose effects on this element (template effects like g-show, :class, {text})
2592
+ if (effects) {
2593
+ effects.forEach((dispose) => {
2594
+ try {
2595
+ dispose();
2596
+ }
2597
+ catch (error) {
2598
+ console.error('[GyosJS] Error disposing effect:', error);
2599
+ }
2600
+ });
2601
+ }
2602
+ // Recursively dispose effects on all descendants
2603
+ children.forEach(child => disposeNode(child));
2604
+ // Restore a portal to its placeholder before removing the owning tree.
2605
+ portalDestroy(element);
2606
+ if (removeElement)
2607
+ element.parentNode?.removeChild(element);
2608
+ }
2609
+
2457
2610
  /**
2458
2611
  * Directive Processing
2459
2612
  * Handles built-in directives (g-show, g-html, g-text) and custom directives
@@ -2515,6 +2668,7 @@ function processDirectives(element, scope, root) {
2515
2668
  const expr = element.getAttribute('g-html');
2516
2669
  queueReactiveEffect(element, () => {
2517
2670
  const value = evaluateExpression(expr, scope);
2671
+ Array.from(element.childNodes).forEach(child => disposeNode(child));
2518
2672
  element.innerHTML = value;
2519
2673
  });
2520
2674
  }
@@ -2523,6 +2677,7 @@ function processDirectives(element, scope, root) {
2523
2677
  const expr = element.getAttribute('g-text');
2524
2678
  queueReactiveEffect(element, () => {
2525
2679
  const value = evaluateExpression(expr, scope);
2680
+ Array.from(element.childNodes).forEach(child => disposeNode(child));
2526
2681
  element.textContent = value;
2527
2682
  });
2528
2683
  }
@@ -2600,7 +2755,7 @@ function processDirectives(element, scope, root) {
2600
2755
  * @param scope - Scope object for evaluation
2601
2756
  */
2602
2757
  function processDirectivesStatic(el, scope) {
2603
- const directives = Array.from(el.querySelectorAll('[g-show], [g-html], [g-text]'))
2758
+ const directives = [el, ...el.querySelectorAll('[g-show], [g-html], [g-text]')]
2604
2759
  .filter(element => !isInIgnoredTree(element));
2605
2760
  directives.forEach(elem => {
2606
2761
  const element = elem;
@@ -2677,7 +2832,9 @@ function readStyleValues(style) {
2677
2832
  return values;
2678
2833
  }
2679
2834
  function normalizeStyleProperty(property) {
2680
- if (property.startsWith('--') || property.includes('-'))
2835
+ if (property.startsWith('--'))
2836
+ return property;
2837
+ if (property.includes('-'))
2681
2838
  return property.toLowerCase();
2682
2839
  return property.replace(/[A-Z]/g, match => `-${match.toLowerCase()}`);
2683
2840
  }
@@ -2856,72 +3013,6 @@ function processBindingsStatic(root, scope) {
2856
3013
  }
2857
3014
  }
2858
3015
 
2859
- /**
2860
- * Portal/Teleport System - Render content in different DOM location
2861
- * Useful for modals, tooltips, notifications that need to break out of parent containers
2862
- *
2863
- * @example
2864
- * // Portal to body (for modals)
2865
- * <div g-portal="body">
2866
- * <div class="modal">Modal content</div>
2867
- * </div>
2868
- *
2869
- * @example
2870
- * // Portal to specific element
2871
- * <div g-portal="#notifications">
2872
- * <div class="toast">Toast message</div>
2873
- * </div>
2874
- */
2875
- /**
2876
- * Create a portal - Move element to target location
2877
- *
2878
- * @param sourceEl - Element to teleport
2879
- * @param targetSelector - CSS selector for destination
2880
- *
2881
- * @example
2882
- * portalCreate(modalEl, 'body');
2883
- * portalCreate(tooltipEl, '#tooltip-container');
2884
- */
2885
- function portalCreate(sourceEl, targetSelector) {
2886
- if (!sourceEl)
2887
- return;
2888
- const target = document.querySelector(targetSelector);
2889
- if (!target) {
2890
- console.warn(`[GyosJS] Portal target "${targetSelector}" not found`);
2891
- return;
2892
- }
2893
- // Create placeholder comment to mark original position
2894
- const placeholder = document.createComment('g-portal');
2895
- sourceEl.parentNode?.insertBefore(placeholder, sourceEl);
2896
- // Store original parent for restoration
2897
- sourceEl.__portal_placeholder__ = placeholder;
2898
- sourceEl.__portal_target__ = target;
2899
- // Move the entire element to target
2900
- target.appendChild(sourceEl);
2901
- DEBUG() && console.log('[Portal] Created - moved element to', targetSelector);
2902
- }
2903
- /**
2904
- * Destroy a portal - Restore element to original position
2905
- *
2906
- * @param sourceEl - Element to restore
2907
- *
2908
- * @example
2909
- * portalDestroy(modalEl); // Returns modal to original location
2910
- */
2911
- function portalDestroy(sourceEl) {
2912
- if (!sourceEl)
2913
- return;
2914
- const placeholder = sourceEl.__portal_placeholder__;
2915
- if (placeholder && placeholder.parentNode) {
2916
- // Move element back to original position
2917
- placeholder.parentNode.insertBefore(sourceEl, placeholder);
2918
- placeholder.remove();
2919
- delete sourceEl.__portal_placeholder__;
2920
- delete sourceEl.__portal_target__;
2921
- DEBUG() && console.log('[Portal] Destroyed - restored element to original position');
2922
- }
2923
- }
2924
-
2925
3016
  /**
2926
3017
  * Validator registry
2927
3018
  */
@@ -3107,7 +3198,7 @@ validator('maxLength', (value, length) => {
3107
3198
  * @example "min(18)"
3108
3199
  */
3109
3200
  validator('min', (value, min) => {
3110
- if (!value)
3201
+ if (value == null || value === '')
3111
3202
  return true;
3112
3203
  const minVal = parseFloat(min);
3113
3204
  return parseFloat(value) >= minVal || `Minimum value is ${minVal}`;
@@ -3118,7 +3209,7 @@ validator('min', (value, min) => {
3118
3209
  * @example "max(100)"
3119
3210
  */
3120
3211
  validator('max', (value, max) => {
3121
- if (!value)
3212
+ if (value == null || value === '')
3122
3213
  return true;
3123
3214
  const maxVal = parseFloat(max);
3124
3215
  return parseFloat(value) <= maxVal || `Maximum value is ${maxVal}`;
@@ -3139,9 +3230,9 @@ validator('number', (value) => {
3139
3230
  * @example "integer"
3140
3231
  */
3141
3232
  validator('integer', (value) => {
3142
- if (!value)
3233
+ if (value == null || value === '')
3143
3234
  return true;
3144
- return Number.isInteger(parseFloat(value)) || 'Must be an integer';
3235
+ return (String(value).trim() !== '' && Number.isInteger(Number(value))) || 'Must be an integer';
3145
3236
  });
3146
3237
  /**
3147
3238
  * Numeric - Must contain only digits
@@ -3254,7 +3345,7 @@ validator('date', (value) => {
3254
3345
  return 'Invalid date format (use YYYY-MM-DD)';
3255
3346
  }
3256
3347
  const date = new Date(value);
3257
- return !isNaN(date.getTime()) || 'Invalid date';
3348
+ return (!isNaN(date.getTime()) && date.toISOString().slice(0, 10) === value) || 'Invalid date';
3258
3349
  });
3259
3350
  /**
3260
3351
  * Before - Date must be before specified date
@@ -3334,7 +3425,7 @@ validator('notIn', (value, ...forbiddenValues) => {
3334
3425
  * @example "between(18,65)"
3335
3426
  */
3336
3427
  validator('between', (value, min, max) => {
3337
- if (!value)
3428
+ if (value == null || value === '')
3338
3429
  return true;
3339
3430
  const num = parseFloat(value);
3340
3431
  const minVal = parseFloat(min);
@@ -3588,8 +3679,16 @@ function processValidateDirective(el) {
3588
3679
  // Initialize error state - direct mutation
3589
3680
  state.errors.value[modelAttr] = null;
3590
3681
  state.touched.value[modelAttr] = false;
3591
- // Validation function
3592
- const validateField = async () => {
3682
+ let active = true;
3683
+ let generation = 0;
3684
+ let timeout;
3685
+ let latestValidation = Promise.resolve();
3686
+ // Each control publishes only its newest result. validateAll also waits for
3687
+ // a newer validation that superseded the request it originally started.
3688
+ const runValidation = async () => {
3689
+ if (!active)
3690
+ return;
3691
+ const request = ++generation;
3593
3692
  const value = getControlValue(el, form);
3594
3693
  // Get form context for validators that need it (like 'same')
3595
3694
  const formData = {};
@@ -3604,7 +3703,26 @@ function processValidateDirective(el) {
3604
3703
  }
3605
3704
  }
3606
3705
  });
3607
- const error = await validate(value, rules, { form: formData, field: modelAttr });
3706
+ let error;
3707
+ try {
3708
+ error = await validate(value, rules, { form: formData, field: modelAttr });
3709
+ }
3710
+ catch (cause) {
3711
+ console.error('[GyosJS] Field validation failed:', cause);
3712
+ error = 'Validation failed. Please try again.';
3713
+ }
3714
+ if (!active)
3715
+ return;
3716
+ if (request !== generation) {
3717
+ await latestValidation;
3718
+ return;
3719
+ }
3720
+ // Input may have changed while its debounce timer has not fired yet.
3721
+ // A submit must validate the current value before publishing approval.
3722
+ if (value !== getControlValue(el, form)) {
3723
+ await validateField();
3724
+ return;
3725
+ }
3608
3726
  // Update errors - only if changed
3609
3727
  const currentErrors = state.errors.value;
3610
3728
  if (currentErrors[modelAttr] !== error) {
@@ -3614,6 +3732,12 @@ function processValidateDirective(el) {
3614
3732
  updateFormState(state);
3615
3733
  }
3616
3734
  };
3735
+ const validateField = () => {
3736
+ clearTimeout(timeout);
3737
+ timeout = undefined;
3738
+ latestValidation = runValidation();
3739
+ return latestValidation;
3740
+ };
3617
3741
  // Register validator for validateAll
3618
3742
  if (!formValidators.has(form)) {
3619
3743
  formValidators.set(form, []);
@@ -3631,7 +3755,6 @@ function processValidateDirective(el) {
3631
3755
  };
3632
3756
  el.addEventListener('blur', blurListener);
3633
3757
  // Validate on input (with debounce)
3634
- let timeout;
3635
3758
  const inputListener = () => {
3636
3759
  clearTimeout(timeout);
3637
3760
  timeout = setTimeout(() => {
@@ -3643,6 +3766,24 @@ function processValidateDirective(el) {
3643
3766
  el.__gyos_effects__ = [];
3644
3767
  }
3645
3768
  el.__gyos_effects__.push(() => {
3769
+ active = false;
3770
+ generation++;
3771
+ delete el[validationFieldKey];
3772
+ const validators = formValidators.get(form);
3773
+ const index = validators?.indexOf(validateField) ?? -1;
3774
+ if (index !== -1)
3775
+ validators.splice(index, 1);
3776
+ const sharesField = Array.from(form.querySelectorAll('input, textarea, select'))
3777
+ .some(control => control[validationFieldKey] === modelAttr);
3778
+ if (!sharesField) {
3779
+ const errors = { ...state.errors.peek };
3780
+ delete errors[modelAttr];
3781
+ const touched = { ...state.touched.peek };
3782
+ delete touched[modelAttr];
3783
+ state.errors.value = errors;
3784
+ state.touched.value = touched;
3785
+ updateFormState(state);
3786
+ }
3646
3787
  el.removeEventListener('blur', blurListener);
3647
3788
  el.removeEventListener('input', inputListener);
3648
3789
  clearTimeout(timeout);
@@ -3715,7 +3856,9 @@ function processFormValidation(root, scope) {
3715
3856
  processFormDirective(root, scope);
3716
3857
  }
3717
3858
  // Then process g-validate
3718
- root.querySelectorAll('[g-validate]').forEach(el => {
3859
+ [root, ...root.querySelectorAll('[g-validate]')].forEach(el => {
3860
+ if (!el.hasAttribute('g-validate'))
3861
+ return;
3719
3862
  if (isInIgnoredTree(el))
3720
3863
  return;
3721
3864
  if (el instanceof HTMLElement) {
@@ -3723,7 +3866,9 @@ function processFormValidation(root, scope) {
3723
3866
  }
3724
3867
  });
3725
3868
  // Finally process g-errors
3726
- root.querySelectorAll('[g-errors]').forEach(el => {
3869
+ [root, ...root.querySelectorAll('[g-errors]')].forEach(el => {
3870
+ if (!el.hasAttribute('g-errors'))
3871
+ return;
3727
3872
  if (isInIgnoredTree(el))
3728
3873
  return;
3729
3874
  if (el instanceof HTMLElement) {
@@ -3754,12 +3899,13 @@ const RESERVED_MODIFIERS = new Set(['prevent', 'stop', 'once', 'capture', 'passi
3754
3899
  /**
3755
3900
  * Execute handler with modifiers (prevent, stop)
3756
3901
  */
3757
- function executeHandler(handler, scope, e, modifiers) {
3758
- // Handle prevent/stop modifiers
3902
+ function applyEventModifiers(e, modifiers) {
3759
3903
  if (modifiers.includes('prevent'))
3760
3904
  e.preventDefault();
3761
3905
  if (modifiers.includes('stop'))
3762
3906
  e.stopPropagation();
3907
+ }
3908
+ function executeHandler(handler, scope, e) {
3763
3909
  try {
3764
3910
  expressionRuntime().execute(handler, scope, e);
3765
3911
  }
@@ -3849,10 +3995,11 @@ function setupClickOutsideHandler(element, handler, modifiers, scope, attrName)
3849
3995
  if (target instanceof Element && target.closest('[g-ignore-outside-click]'))
3850
3996
  return;
3851
3997
  if (element !== target && !element.contains(target)) {
3998
+ applyEventModifiers(e, modifiers);
3852
3999
  const currentScope = getScopeFromElement(element) || scope;
3853
4000
  if (modifiers.includes('once'))
3854
4001
  cleanup();
3855
- executeHandler(handler, currentScope, e, modifiers);
4002
+ executeHandler(handler, currentScope, e);
3856
4003
  }
3857
4004
  };
3858
4005
  // Cleanup function
@@ -3929,13 +4076,14 @@ function processEvents(el, scope) {
3929
4076
  return; // Key doesn't match, skip
3930
4077
  }
3931
4078
  // Execute handler with optional debounce
4079
+ applyEventModifiers(e, modifiers);
3932
4080
  const execute = () => {
3933
4081
  if (modifiers.includes('once'))
3934
4082
  cleanup();
3935
4083
  // Batch in case handler mutates multiple signals
3936
4084
  batch(() => {
3937
4085
  const currentScope = getScopeFromElement(element) || scope;
3938
- executeHandler(handler, currentScope, e, modifiers);
4086
+ executeHandler(handler, currentScope, e);
3939
4087
  });
3940
4088
  };
3941
4089
  if (debounceMs > 0) {
@@ -4185,60 +4333,6 @@ function processModel(element, scope, root) {
4185
4333
  element.removeAttribute(modelAttr.name);
4186
4334
  }
4187
4335
 
4188
- /**
4189
- * Cleanup utilities for disposing effects and event listeners
4190
- */
4191
- /**
4192
- * Dispose all effects attached to an element and its descendants
4193
- * Handles both element effects (__gyos_effects__) and component lifecycle
4194
- */
4195
- function disposeEffects(element = document.body, removeElement = false) {
4196
- if (!element)
4197
- return;
4198
- // Unmount scope if element has one (calls onUnmount + cleans instance.__gyos_effects__)
4199
- if (element.hasAttribute?.('g-scope') || element.__gyos_scope__) {
4200
- unmountScope(element);
4201
- }
4202
- // Dispose effects on this element (template effects like g-show, :class, {text})
4203
- if (element.__gyos_effects__) {
4204
- const effects = element.__gyos_effects__;
4205
- effects.forEach((dispose) => {
4206
- try {
4207
- dispose();
4208
- }
4209
- catch (error) {
4210
- console.error('[GyosJS] Error disposing effect:', error);
4211
- }
4212
- });
4213
- element.__gyos_effects__ = null;
4214
- }
4215
- // Recursively dispose effects on all descendants
4216
- const descendants = element.querySelectorAll('*');
4217
- descendants.forEach((child) => {
4218
- // Unmount child scopes
4219
- if (child.hasAttribute?.('g-scope') || child.__gyos_scope__) {
4220
- unmountScope(child);
4221
- }
4222
- // Dispose child template effects
4223
- if (child.__gyos_effects__) {
4224
- const effects = child.__gyos_effects__;
4225
- effects.forEach((dispose) => {
4226
- try {
4227
- dispose();
4228
- }
4229
- catch (error) {
4230
- console.error('[GyosJS] Error disposing child effect:', error);
4231
- }
4232
- });
4233
- child.__gyos_effects__ = null;
4234
- }
4235
- });
4236
- // portal cleanup could be added here if needed
4237
- portalDestroy(element);
4238
- if (removeElement)
4239
- element.remove();
4240
- }
4241
-
4242
4336
  const storeCache = new WeakMap();
4243
4337
  const reactiveProxies = new WeakSet();
4244
4338
  const fieldSignals = new WeakMap();
@@ -4253,7 +4347,7 @@ function bumpScopeVersion(target) {
4253
4347
  if (visited.has(ver))
4254
4348
  return;
4255
4349
  visited.add(ver);
4256
- ver.value = ver.value + 1;
4350
+ ver.update(value => value + 1);
4257
4351
  const parents = versionParents.get(ver);
4258
4352
  if (parents) {
4259
4353
  parents.forEach(parentVer => bumpSignal(parentVer));
@@ -4291,7 +4385,7 @@ function getFieldSignal(target, key, initial) {
4291
4385
  }
4292
4386
  const STORE_MARKER = Symbol.for('gyos.store');
4293
4387
  function markStore(obj) {
4294
- if (obj.hasOwnProperty(STORE_MARKER))
4388
+ if (Object.prototype.hasOwnProperty.call(obj, STORE_MARKER))
4295
4389
  return obj;
4296
4390
  Reflect.defineProperty(obj, STORE_MARKER, {
4297
4391
  value: true,
@@ -4305,7 +4399,7 @@ function isStoreObject(val) {
4305
4399
  // markRaw: đánh dấu object để reactive() bỏ qua, không tạo proxy
4306
4400
  const RAW_MARKER = Symbol.for('gyos.raw');
4307
4401
  function markRaw(obj) {
4308
- if (obj.hasOwnProperty(RAW_MARKER))
4402
+ if (Object.prototype.hasOwnProperty.call(obj, RAW_MARKER))
4309
4403
  return obj;
4310
4404
  Reflect.defineProperty(obj, RAW_MARKER, {
4311
4405
  value: true,
@@ -4319,7 +4413,7 @@ function isRawObject(val) {
4319
4413
  // shallow: chỉ reactive "lớp ngoài", không reactive sâu bên trong
4320
4414
  const SHALLOW_MARKER = Symbol.for('gyos.shallow');
4321
4415
  function shallow(obj) {
4322
- if (obj.hasOwnProperty(SHALLOW_MARKER))
4416
+ if (Object.prototype.hasOwnProperty.call(obj, SHALLOW_MARKER))
4323
4417
  return obj;
4324
4418
  Reflect.defineProperty(obj, SHALLOW_MARKER, {
4325
4419
  value: true,
@@ -4353,6 +4447,25 @@ function linkParentVersion(child, parentVersion) {
4353
4447
  }
4354
4448
  versionParentsSet.add(parentVersion);
4355
4449
  }
4450
+ // Array [[DefineOwnProperty]] can change length or remove indices without
4451
+ // entering their individual Proxy traps. Keep already observed fields current.
4452
+ function syncArrayFields(target, previousLength) {
4453
+ if (previousLength === undefined)
4454
+ return;
4455
+ const array = target;
4456
+ if (array.length === previousLength)
4457
+ return;
4458
+ const signals = fieldSignals.get(target);
4459
+ signals?.get('length')?.update(() => array.length);
4460
+ if (array.length < previousLength) {
4461
+ signals?.forEach((sig, key) => {
4462
+ if (typeof key === 'string' && /^(0|[1-9]\d*)$/.test(key)
4463
+ && Number(key) >= array.length && Number(key) < previousLength) {
4464
+ sig.update(() => Reflect.get(target, key));
4465
+ }
4466
+ });
4467
+ }
4468
+ }
4356
4469
  function reactive(raw) {
4357
4470
  if (!raw || typeof raw !== "object" || isBuiltInObject(raw)) {
4358
4471
  return raw;
@@ -4390,6 +4503,8 @@ function reactive(raw) {
4390
4503
  return value;
4391
4504
  }
4392
4505
  if (isStoreObject(value)) {
4506
+ if (hasCurrentEffect())
4507
+ getFieldSignal(target, key, value).value;
4393
4508
  return value;
4394
4509
  }
4395
4510
  // Check if this is a getter property (computed property)
@@ -4466,10 +4581,6 @@ function reactive(raw) {
4466
4581
  }
4467
4582
  // capture old value BEFORE write to detect real changes
4468
4583
  const oldValue = target[key];
4469
- // VALUE LÀ STORE → set thẳng, KHÔNG tạo signal, KHÔNG trigger
4470
- if (isStoreObject(value)) {
4471
- return Reflect.set(target, key, value, receiver);
4472
- }
4473
4584
  const ok = Reflect.set(target, key, value, receiver);
4474
4585
  if (!ok)
4475
4586
  return false;
@@ -4511,7 +4622,9 @@ function reactive(raw) {
4511
4622
  const oldDesc = Object.getOwnPropertyDescriptor(target, key);
4512
4623
  const oldValue = oldDesc && "value" in oldDesc ? oldDesc.value : undefined;
4513
4624
  const newValue = "value" in descriptor ? descriptor.value : oldValue;
4625
+ const previousLength = Array.isArray(target) ? target.length : undefined;
4514
4626
  const ok = Reflect.defineProperty(target, key, descriptor);
4627
+ syncArrayFields(target, previousLength);
4515
4628
  if (!ok)
4516
4629
  return false;
4517
4630
  if ('value' in descriptor) {
@@ -4537,7 +4650,7 @@ function makeReactive(source) {
4537
4650
  // tạo 1 version signal cho root scope
4538
4651
  const version = ensureVersion(source);
4539
4652
  const proxy = reactive(source);
4540
- if (!proxy.hasOwnProperty(SCOPE_VERSION)) {
4653
+ if (!Object.prototype.hasOwnProperty.call(proxy, SCOPE_VERSION)) {
4541
4654
  Object.defineProperty(proxy, SCOPE_VERSION, {
4542
4655
  value: version,
4543
4656
  enumerable: false,
@@ -4659,6 +4772,20 @@ function getCachedTemplate(template) {
4659
4772
  function setRootScope(element, scope) {
4660
4773
  element.__gyos_scope__ = scope;
4661
4774
  }
4775
+ function inheritScope(child, parent) {
4776
+ attachParentScope(child, parent);
4777
+ for (const key in parent) {
4778
+ if (!(key in child)) {
4779
+ Object.defineProperty(child, key, {
4780
+ get: () => parent[key],
4781
+ set: value => { parent[key] = value; },
4782
+ enumerable: true,
4783
+ configurable: true,
4784
+ });
4785
+ }
4786
+ }
4787
+ return child;
4788
+ }
4662
4789
  /**
4663
4790
  * Create child scope for *for loops
4664
4791
  * Inherits parent scope properties via getters
@@ -4729,13 +4856,15 @@ function processForDirective(element, currentScope) {
4729
4856
  template.removeAttribute('g-key');
4730
4857
  const placeholder = document.createComment('*for');
4731
4858
  element.parentNode?.replaceChild(placeholder, element);
4859
+ const end = document.createComment('/*for');
4860
+ placeholder.parentNode?.insertBefore(end, placeholder.nextSibling);
4732
4861
  // Store previous items for key-based diffing
4733
4862
  // WARNING: Use primitive keys (id, string, number) to avoid memory leaks
4734
4863
  // Object keys will prevent garbage collection
4735
4864
  let prevItemsMap = new Map();
4736
4865
  let prevListRef = null;
4737
4866
  let prevVersionValue = undefined;
4738
- queueReactiveEffect(element, () => {
4867
+ queueReactiveEffect(placeholder, () => {
4739
4868
  // Parse: "item in items" or "item, index in items"
4740
4869
  const match = expr.match(/(.+?)\s+in\s+(.+)/);
4741
4870
  if (!match)
@@ -4762,7 +4891,7 @@ function processForDirective(element, currentScope) {
4762
4891
  }
4763
4892
  else {
4764
4893
  // Simple re-render (no diffing)
4765
- processForSimple(placeholder, template, list, itemVar, currentScope);
4894
+ processForSimple(placeholder, end, template, list, itemVar, currentScope);
4766
4895
  }
4767
4896
  });
4768
4897
  });
@@ -4869,16 +4998,19 @@ function processForWithKeys(placeholder, template, list, itemVar, keyExpr, curre
4869
4998
  /**
4870
4999
  * Process *for without keys (simple re-render)
4871
5000
  */
4872
- function processForSimple(placeholder, template, list, itemVar, currentScope) {
5001
+ function processForSimple(placeholder, end, template, list, itemVar, currentScope) {
4873
5002
  // Remove all existing items
4874
5003
  let next = placeholder.nextSibling;
4875
- while (next && next.nodeType !== Node.COMMENT_NODE) {
5004
+ while (next && next !== end) {
4876
5005
  const toRemove = next;
4877
5006
  next = next.nextSibling;
4878
5007
  if (toRemove instanceof Element) {
4879
5008
  unmountChildScopes(toRemove);
4880
5009
  disposeEffects(toRemove, true);
4881
5010
  }
5011
+ else {
5012
+ disposeNode(toRemove, true);
5013
+ }
4882
5014
  }
4883
5015
  // Render new items
4884
5016
  // Track last inserted node to maintain order
@@ -4971,7 +5103,7 @@ function processIfChain(element, currentScope) {
4971
5103
  element.parentNode?.replaceChild(placeholder, element);
4972
5104
  let currentElement = null;
4973
5105
  let currentIndex = -1;
4974
- queueReactiveEffect(element, () => {
5106
+ queueReactiveEffect(placeholder, () => {
4975
5107
  // Find first truthy condition
4976
5108
  let matchedIndex = -1;
4977
5109
  for (let i = 0; i < templates.length; i++) {
@@ -5097,14 +5229,13 @@ function processSwitchDirective(element, currentScope) {
5097
5229
  const switchValue = evaluateExpression(switchExpr, currentScope, false);
5098
5230
  // Find matching case
5099
5231
  let matchedIndex = -1;
5232
+ let defaultIndex = -1;
5100
5233
  for (let i = 0; i < templates.length; i++) {
5101
5234
  const { value } = templates[i];
5102
5235
  if (value === null) {
5103
- // *default matches (only if no other case matched)
5104
- if (matchedIndex === -1) {
5105
- matchedIndex = i;
5106
- }
5107
- break;
5236
+ if (defaultIndex === -1)
5237
+ defaultIndex = i;
5238
+ continue;
5108
5239
  }
5109
5240
  const caseValue = evaluateExpression(value, currentScope, false);
5110
5241
  if (switchValue === caseValue) {
@@ -5112,6 +5243,8 @@ function processSwitchDirective(element, currentScope) {
5112
5243
  break;
5113
5244
  }
5114
5245
  }
5246
+ if (matchedIndex === -1)
5247
+ matchedIndex = defaultIndex;
5115
5248
  // If same case, do nothing
5116
5249
  if (matchedIndex === currentIndex)
5117
5250
  return;
@@ -5230,6 +5363,7 @@ function processAwaitDirective(element, currentScope) {
5230
5363
  let requestVersion = 0;
5231
5364
  // Helper to render state
5232
5365
  const renderState = (state, data) => {
5366
+ currentState = state;
5233
5367
  // Remove old element
5234
5368
  if (currentElement) {
5235
5369
  const elemToRemove = currentElement;
@@ -5255,20 +5389,19 @@ function processAwaitDirective(element, currentScope) {
5255
5389
  else if (state === 'fulfilled' && thenTemplate) {
5256
5390
  template = thenTemplate.template;
5257
5391
  // Create child scope with data if varName provided
5258
- if (thenTemplate.varName && data !== undefined) {
5259
- scope = { ...currentScope, [thenTemplate.varName]: data };
5392
+ if (thenTemplate.varName) {
5393
+ scope = inheritScope({ [thenTemplate.varName]: data }, currentScope);
5260
5394
  }
5261
5395
  }
5262
5396
  else if (state === 'rejected' && catchTemplate) {
5263
5397
  template = catchTemplate.template;
5264
5398
  // Create child scope with error if varName provided
5265
- if (catchTemplate.varName && data !== undefined) {
5266
- scope = { ...currentScope, [catchTemplate.varName]: data };
5399
+ if (catchTemplate.varName) {
5400
+ scope = inheritScope({ [catchTemplate.varName]: data }, currentScope);
5267
5401
  }
5268
5402
  }
5269
5403
  if (template) {
5270
5404
  currentElement = getCachedTemplate(template);
5271
- currentState = state;
5272
5405
  setRootScope(currentElement, scope);
5273
5406
  // Apply transition initial state
5274
5407
  const elementsWithTransition = findElementsWithTransition(currentElement);
@@ -5296,8 +5429,6 @@ function processAwaitDirective(element, currentScope) {
5296
5429
  }
5297
5430
  }
5298
5431
  };
5299
- // Initial state: pending
5300
- renderState('pending');
5301
5432
  // Track promise expression
5302
5433
  queueReactiveEffect(element, () => {
5303
5434
  const promiseOrValue = evaluateExpression(awaitExpr, currentScope, false);
@@ -5321,6 +5452,8 @@ function processAwaitDirective(element, currentScope) {
5321
5452
  renderState('rejected', error);
5322
5453
  }
5323
5454
  });
5455
+ // Both reruns and disposal invalidate callbacks from this request.
5456
+ return () => { requestVersion++; };
5324
5457
  });
5325
5458
  }
5326
5459
 
@@ -5388,6 +5521,9 @@ function processStructuralDirectives(elements, scope) {
5388
5521
  structuralElements.sort((a, b) => a.depth - b.depth);
5389
5522
  // Process each structural directive
5390
5523
  structuralElements.forEach(({ element, type }) => {
5524
+ // Parent directives parse their clones, not the detached original tree.
5525
+ if (!root.contains(element) || elementBelongsToAnotherScope(element, scope))
5526
+ return;
5391
5527
  if (type === 'for') {
5392
5528
  processForDirective(element, scope);
5393
5529
  }
@@ -5423,6 +5559,10 @@ const elementBelongsToAnotherScope = (el, scope) => {
5423
5559
  function processParse(element, scope, fromStructural = false) {
5424
5560
  if (isInIgnoredTree(element))
5425
5561
  return;
5562
+ if (fromStructural && element.hasAttribute('g-scope') && mountFunction) {
5563
+ mountFunction(element);
5564
+ return;
5565
+ }
5426
5566
  beginEffectCollection();
5427
5567
  const allElements = [
5428
5568
  element,
@@ -5444,7 +5584,7 @@ function processParse(element, scope, fromStructural = false) {
5444
5584
  return;
5445
5585
  if (el.attributes.length === 0)
5446
5586
  return; // Skip if no attributes
5447
- if (elementBelongsToAnotherScope(el, scope) && !fromStructural) {
5587
+ if (elementBelongsToAnotherScope(el, scope)) {
5448
5588
  // (fromStructural allows processing newly created elements inside structurals)
5449
5589
  return; // Skip if inside mounted scope
5450
5590
  }
@@ -5452,8 +5592,9 @@ function processParse(element, scope, fromStructural = false) {
5452
5592
  if (el.hasAttribute('g-static')) {
5453
5593
  // Pre-process g-static elements (mark and render them before reactive processing)
5454
5594
  processStaticElements(el, scope);
5595
+ return;
5455
5596
  }
5456
- if (el.hasAttribute('g-form')) {
5597
+ if (el.hasAttribute('g-form') || el.hasAttribute('g-validate') || el.hasAttribute('g-errors')) {
5457
5598
  // Process form validation (g-form, g-validate, g-errors)
5458
5599
  processFormValidation(el, scope);
5459
5600
  }
@@ -5803,7 +5944,7 @@ function mountAll(root) {
5803
5944
  const allElements = [...elements, ...elementsNotScope].filter(el => !isInIgnoredTree(el));
5804
5945
  allElements.sort((a, b) => getDepth(b) - getDepth(a));
5805
5946
  // Filter out elements inside structural directives - they will be mounted by structural processor
5806
- allElements.forEach(el => !hasStructuralParent(el) && mount(el));
5947
+ allElements.forEach(el => !el.hasAttribute('*if') && !el.hasAttribute('*for') && !hasStructuralParent(el) && mount(el));
5807
5948
  diagnoseUnscopedReveals(document.body);
5808
5949
  }
5809
5950
  function mountTree(el) {
@@ -5814,7 +5955,7 @@ function mountTree(el) {
5814
5955
  .filter(element => element.hasAttribute('g-scope') || hasAutoScope(element));
5815
5956
  // Child scopes own their subtree before an existing parent scope parses the insertion.
5816
5957
  candidates.sort((a, b) => getDepth(b) - getDepth(a));
5817
- candidates.forEach(element => !hasStructuralParent(element) && mount(element));
5958
+ candidates.forEach(element => !element.hasAttribute('*if') && !element.hasAttribute('*for') && !hasStructuralParent(element) && mount(element));
5818
5959
  diagnoseUnscopedReveals(el);
5819
5960
  if (getMountedScope(el))
5820
5961
  return;
@@ -5843,9 +5984,17 @@ function mount(el) {
5843
5984
  /**
5844
5985
  * Parse inline scope definition from HTML attribute
5845
5986
  */
5987
+ function decodeMarkupExpression(value) {
5988
+ try {
5989
+ return decodeURIComponent(value);
5990
+ }
5991
+ catch {
5992
+ return value;
5993
+ } // Plain expressions may contain a literal % or modulo.
5994
+ }
5846
5995
  function parseInlineScope(scopeStr) {
5847
5996
  // If scopeStr is encode urld, decode it first
5848
- scopeStr = decodeURIComponent(scopeStr);
5997
+ scopeStr = decodeMarkupExpression(scopeStr);
5849
5998
  try {
5850
5999
  // Check if it's an inline object definition (starts with '{')
5851
6000
  const trimmed = scopeStr.trim();
@@ -5912,7 +6061,7 @@ function parseAutoScope(el) {
5912
6061
  // gm-method-name:args:arg2="expression"
5913
6062
  if (attr.name.match(/^gm-.+/)) {
5914
6063
  // If expr is encoded url, decode it first
5915
- const expr = decodeURIComponent(attr.value.trim());
6064
+ const expr = decodeMarkupExpression(attr.value.trim());
5916
6065
  if (forbidden.some(f => expr.includes(f))) {
5917
6066
  DEBUG() && console.log("[GyosJS] Scope mount error: Forbidden expression:", expr);
5918
6067
  }
@@ -6023,15 +6172,11 @@ function handleDefinition(el, scopeAttr) {
6023
6172
  * Mount a specific scope
6024
6173
  */
6025
6174
  function mountScope(el, scopeAttr) {
6026
- const definition = handleDefinition(el, scopeAttr);
6027
6175
  // Check if already mounted
6028
6176
  if (getMountedScope(el)) {
6029
6177
  return;
6030
6178
  }
6031
- // Check if element is static (no reactivity)
6032
- if (el.hasAttribute('g-static')) {
6033
- return;
6034
- }
6179
+ const definition = handleDefinition(el, scopeAttr);
6035
6180
  // Check hydration strategy
6036
6181
  const hydrationStrategy = getHydrationStrategy(el);
6037
6182
  if (hydrationStrategy) {
@@ -6054,8 +6199,9 @@ function mountScopeInternal(el, definition) {
6054
6199
  if (typeof definition === 'object') {
6055
6200
  instance = makeReactive(definition);
6056
6201
  }
6057
- // Create component context (needs instance for $watch)
6058
- const context = createContext(el, instance);
6202
+ // Factories receive context before their reactive instance exists. Resolve it
6203
+ // when an observer is registered so captured context also works in onMount.
6204
+ const context = createContext(el, () => instance);
6059
6205
  // If function component, call it now with context
6060
6206
  if (typeof definition === 'function' && !instance) {
6061
6207
  const factoryResult = definition(context);
@@ -6095,13 +6241,21 @@ function mountScopeInternal(el, definition) {
6095
6241
  // Parse and bind template (portals will be processed inside *if)
6096
6242
  // Pass onMount callback to be called after parsing (or after hydration triggers)
6097
6243
  parseTemplate(el, instance, () => {
6244
+ // The hook may inspect or clean up its own mount. Register before calling
6245
+ // user code, and do not register again if the hook disposes the scope.
6246
+ registerMountedScope(el, instance);
6098
6247
  // Call lifecycle hook after template is parsed
6099
6248
  if (instance.onMount) {
6100
- Promise.resolve(instance.onMount.call(instance)).catch(console.error);
6249
+ try {
6250
+ Promise.resolve(instance.onMount.call(instance)).catch(console.error);
6251
+ }
6252
+ catch (error) {
6253
+ console.error('[Component] Error in onMount:', error);
6254
+ }
6101
6255
  }
6102
6256
  });
6103
- // Store instance
6104
- registerMountedScope(el, instance);
6257
+ if (getMountedScope(el) !== instance)
6258
+ return;
6105
6259
  // Cache instance if g-scope-persist is set (with interpolation support)
6106
6260
  getPersistKey$1(el, persistKey => {
6107
6261
  if (!scopeCached.has(persistKey)) {
@@ -6112,12 +6266,12 @@ function mountScopeInternal(el, definition) {
6112
6266
  /**
6113
6267
  * Create component context
6114
6268
  */
6115
- function createContext(el, instance) {
6269
+ function createContext(el, getInstance) {
6116
6270
  const refs = {};
6117
6271
  const events = new Map();
6118
6272
  // Find all refs within this scope only
6119
6273
  el.querySelectorAll('[g-ref]').forEach(refEl => {
6120
- if (isInIgnoredTree(refEl))
6274
+ if (isInIgnoredTree(refEl) || (refEl.closest('[g-scope]') || el) !== el)
6121
6275
  return;
6122
6276
  const refName = refEl.getAttribute('g-ref');
6123
6277
  if (refName && !hasUnsafePropertyPath(refName)) {
@@ -6160,19 +6314,23 @@ function createContext(el, instance) {
6160
6314
  },
6161
6315
  $watch: (key, handler, options = {}) => {
6162
6316
  // Watch a reactive property for changes (supports nested paths like 'xxx.count')
6317
+ const instance = getInstance();
6163
6318
  if (!instance) {
6164
6319
  DEBUG() && console.warn('[Component] $watch called before instance created');
6165
6320
  return () => { };
6166
6321
  }
6167
6322
  const { immediate = false, deep = false, debounce = 0 } = options;
6168
6323
  let timeoutId;
6324
+ let active = true;
6169
6325
  if (debounce > 0) {
6170
6326
  // Wrap handler with debounce
6171
6327
  const originalHandler = handler;
6172
6328
  handler = (...args) => {
6173
6329
  clearTimeout(timeoutId);
6174
6330
  timeoutId = setTimeout(() => {
6175
- originalHandler(...args);
6331
+ timeoutId = undefined;
6332
+ if (active)
6333
+ untrack(() => originalHandler.call(instance, ...args));
6176
6334
  }, debounce);
6177
6335
  };
6178
6336
  }
@@ -6201,31 +6359,38 @@ function createContext(el, instance) {
6201
6359
  initialized = true;
6202
6360
  // Call immediately if requested
6203
6361
  if (immediate) {
6204
- handler.call(instance, clonedValue, undefined);
6362
+ untrack(() => handler.call(instance, clonedValue, undefined));
6205
6363
  }
6206
6364
  return;
6207
6365
  }
6208
6366
  // Check if value actually changed
6209
6367
  const changed = deep
6210
6368
  ? !deepEqual(oldValue, clonedValue)
6211
- : oldValue !== clonedValue;
6369
+ : !Object.is(oldValue, clonedValue);
6212
6370
  if (changed) {
6213
- handler.call(instance, clonedValue, oldValue);
6371
+ untrack(() => handler.call(instance, clonedValue, oldValue));
6214
6372
  oldValue = deep && typeof clonedValue === 'object'
6215
6373
  ? clone(clonedValue)
6216
6374
  : clonedValue;
6217
6375
  }
6218
6376
  });
6377
+ const stopWatching = () => {
6378
+ active = false;
6379
+ clearTimeout(timeoutId);
6380
+ timeoutId = undefined;
6381
+ watchEffect();
6382
+ };
6219
6383
  // Store cleanup for unmount
6220
6384
  if (!instance.__gyos_effects__) {
6221
6385
  instance.__gyos_effects__ = [];
6222
6386
  }
6223
- instance.__gyos_effects__.push(watchEffect);
6387
+ instance.__gyos_effects__.push(stopWatching);
6224
6388
  // Return unwatch function
6225
- return watchEffect;
6389
+ return stopWatching;
6226
6390
  },
6227
6391
  $effect: (fn) => {
6228
6392
  // Shorthand for effect with auto cleanup on unmount
6393
+ const instance = getInstance();
6229
6394
  if (!instance) {
6230
6395
  DEBUG() && console.warn('[Component] $effect called before instance created');
6231
6396
  return () => { };
@@ -6429,8 +6594,8 @@ function off(event, handler) {
6429
6594
  */
6430
6595
  function once(event, handler) {
6431
6596
  const wrapper = (...args) => {
6432
- handler(...args);
6433
6597
  off(event, wrapper);
6598
+ handler(...args);
6434
6599
  };
6435
6600
  return on(event, wrapper);
6436
6601
  }
@@ -6468,23 +6633,34 @@ function useFetch(url) {
6468
6633
  const data = signal(null);
6469
6634
  const loading = signal(true);
6470
6635
  const error = signal(null);
6636
+ let generation = 0;
6637
+ let active = true;
6471
6638
  const fetchData = async () => {
6639
+ if (!active)
6640
+ return;
6641
+ const requestId = ++generation;
6472
6642
  loading.value = true;
6473
6643
  error.value = null;
6474
6644
  data.value = null;
6475
6645
  try {
6476
6646
  const request = typeof url === 'function' ? await url() : url;
6647
+ if (requestId !== generation)
6648
+ return;
6477
6649
  const response = typeof request === 'string' ? await fetch(request) : request;
6478
6650
  if (!response.ok) {
6479
6651
  throw new Error(`HTTP error! status: ${response.status}`);
6480
6652
  }
6481
- data.value = await response.json();
6653
+ const result = await response.json();
6654
+ if (requestId === generation)
6655
+ data.value = result;
6482
6656
  }
6483
6657
  catch (e) {
6484
- error.value = e;
6658
+ if (requestId === generation)
6659
+ error.value = e;
6485
6660
  }
6486
6661
  finally {
6487
- loading.value = false;
6662
+ if (requestId === generation)
6663
+ loading.value = false;
6488
6664
  }
6489
6665
  };
6490
6666
  return {
@@ -6492,7 +6668,8 @@ function useFetch(url) {
6492
6668
  loading,
6493
6669
  error,
6494
6670
  refetch: fetchData,
6495
- onMount: fetchData
6671
+ onMount: () => { active = true; return fetchData(); },
6672
+ onUnmount: () => { active = false; generation++; loading.value = false; }
6496
6673
  };
6497
6674
  }
6498
6675
  /**
@@ -6750,17 +6927,26 @@ function useAsync(asyncFn, immediate = true) {
6750
6927
  const data = signal(null);
6751
6928
  const loading = signal(false);
6752
6929
  const error = signal(null);
6930
+ let generation = 0;
6931
+ let active = true;
6753
6932
  const execute = async () => {
6933
+ if (!active)
6934
+ return;
6935
+ const requestId = ++generation;
6754
6936
  loading.value = true;
6755
6937
  error.value = null;
6756
6938
  try {
6757
- data.value = await asyncFn();
6939
+ const result = await asyncFn();
6940
+ if (requestId === generation)
6941
+ data.value = result;
6758
6942
  }
6759
6943
  catch (e) {
6760
- error.value = e;
6944
+ if (requestId === generation)
6945
+ error.value = e;
6761
6946
  }
6762
6947
  finally {
6763
- loading.value = false;
6948
+ if (requestId === generation)
6949
+ loading.value = false;
6764
6950
  }
6765
6951
  };
6766
6952
  return {
@@ -6769,9 +6955,10 @@ function useAsync(asyncFn, immediate = true) {
6769
6955
  error,
6770
6956
  execute,
6771
6957
  onMount: () => {
6772
- if (immediate)
6773
- execute();
6774
- }
6958
+ active = true;
6959
+ return immediate ? execute() : undefined;
6960
+ },
6961
+ onUnmount: () => { active = false; generation++; loading.value = false; }
6775
6962
  };
6776
6963
  }
6777
6964
 
@@ -7245,7 +7432,10 @@ function syncAttributes(target, source) {
7245
7432
  Array.from(source.attributes).forEach(attribute => {
7246
7433
  sourceAttributes.add(attribute.name);
7247
7434
  if (target.getAttribute(attribute.name) !== attribute.value) {
7248
- target.setAttribute(attribute.name, attribute.value);
7435
+ // HTML permits directive names such as @click and *if, while older
7436
+ // DOM implementations apply XML name validation in setAttribute.
7437
+ // Transfer the already-parsed Attr without validating its name again.
7438
+ target.setAttributeNodeNS(target.ownerDocument.importNode(attribute, true));
7249
7439
  }
7250
7440
  });
7251
7441
  Array.from(target.attributes).forEach(attribute => {
@@ -7529,7 +7719,14 @@ function handleScroll(url, trigger, savedScroll) {
7529
7719
  // Hash scrolling
7530
7720
  const hash = new URL(url).hash;
7531
7721
  if (hash) {
7532
- const el = document.querySelector(hash);
7722
+ // A URL fragment identifies an id, not a CSS selector. Numeric ids,
7723
+ // punctuation and percent-encoded Unicode must work without escaping.
7724
+ let id = hash.slice(1);
7725
+ try {
7726
+ id = decodeURIComponent(id);
7727
+ }
7728
+ catch { /* Keep malformed fragments literal. */ }
7729
+ const el = document.getElementById(id);
7533
7730
  if (el) {
7534
7731
  el.scrollIntoView({ behavior: 'smooth' });
7535
7732
  return;
@@ -8109,6 +8306,12 @@ function getHistoryFragment(entryId, neighbourId) {
8109
8306
  return fragment?.cloneNode(true);
8110
8307
  }
8111
8308
  function cloneHistoryTarget(target) {
8309
+ // Mounted templates have already consumed event/model attributes and text
8310
+ // expressions. A DOM clone cannot recreate their observers. Restore these
8311
+ // targets from response HTML (snapshot or fetch) instead of caching inert UI.
8312
+ if (getScopeFromElement(target) || Array.from(target.querySelectorAll('*'))
8313
+ .some(element => element.__gyos_scope__))
8314
+ return null;
8112
8315
  const clone = target.cloneNode(true);
8113
8316
  clone.querySelectorAll('.gyos-target-spinner').forEach(spinner => spinner.remove());
8114
8317
  return clone;
@@ -8966,7 +9169,7 @@ const Gyos = {
8966
9169
  portalCreate,
8967
9170
  portalDestroy,
8968
9171
  setCspNonce,
8969
- version: '0.5.2'
9172
+ version: '0.5.4'
8970
9173
  };
8971
9174
 
8972
9175
  setExpressionRuntime(standardExpressionRuntime);