gyosjs 0.5.3 → 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 +412 -212
  12. package/dist/gyos.auto.esm.js.map +1 -1
  13. package/dist/gyos.auto.js +412 -212
  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 +428 -228
  17. package/dist/gyos.csp.auto.esm.js.map +1 -1
  18. package/dist/gyos.csp.auto.js +428 -228
  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 +428 -228
  22. package/dist/gyos.csp.esm.js.map +1 -1
  23. package/dist/gyos.csp.js +428 -228
  24. package/dist/gyos.csp.js.map +1 -1
  25. package/dist/gyos.csp.min.js +2 -2
  26. package/dist/gyos.esm.js +412 -212
  27. package/dist/gyos.esm.js.map +1 -1
  28. package/dist/gyos.js +412 -212
  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
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * GyosJS v0.5.3
2
+ * GyosJS v0.5.4
3
3
  * (c) 2026
4
4
  * @license MIT
5
5
  */
@@ -70,25 +70,30 @@ function clone(obj) {
70
70
  }
71
71
  const cloned = {};
72
72
  for (const key in obj) {
73
- if (obj.hasOwnProperty(key)) {
73
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
74
74
  cloned[key] = clone(obj[key]);
75
75
  }
76
76
  }
77
77
  return cloned;
78
78
  }
79
79
  function deepEqual(a, b) {
80
- if (a === b)
80
+ if (Object.is(a, b))
81
81
  return true;
82
82
  if (typeof a !== 'object' || typeof b !== 'object' || a == null || b == null) {
83
83
  return false;
84
84
  }
85
+ if (a instanceof Date || b instanceof Date) {
86
+ return a instanceof Date && b instanceof Date && Object.is(a.getTime(), b.getTime());
87
+ }
88
+ if (Array.isArray(a) !== Array.isArray(b))
89
+ return false;
85
90
  const keysA = Object.keys(a);
86
91
  const keysB = Object.keys(b);
87
92
  if (keysA.length !== keysB.length) {
88
93
  return false;
89
94
  }
90
95
  for (const key of keysA) {
91
- if (!deepEqual(a[key], b[key])) {
96
+ if (!Object.prototype.hasOwnProperty.call(b, key) || !deepEqual(a[key], b[key])) {
92
97
  return false;
93
98
  }
94
99
  }
@@ -624,8 +629,11 @@ function effect(fn) {
624
629
  execute.__dependencies = dependencies;
625
630
  execute.__versions = versions;
626
631
  try {
627
- const nextCleanup = fn();
628
- cleanup = typeof nextCleanup === 'function' ? nextCleanup : undefined;
632
+ // The previous cleanup can dispose this effect before the next run.
633
+ if (active) {
634
+ const nextCleanup = fn();
635
+ cleanup = typeof nextCleanup === 'function' ? nextCleanup : undefined;
636
+ }
629
637
  }
630
638
  catch (error) {
631
639
  console.error('[Effect] Error in effect:', error);
@@ -634,6 +642,25 @@ function effect(fn) {
634
642
  finally {
635
643
  initialized = true;
636
644
  currentEffect = prevEffect;
645
+ // stop() may have been called inside fn, before its cleanup was returned
646
+ // or before later reads registered more dependencies.
647
+ if (!active) {
648
+ dependencies.forEach(dependency => dependency.delete(execute));
649
+ dependencies.clear();
650
+ versions.clear();
651
+ effectQueue.delete(execute);
652
+ batchedEffects.delete(execute);
653
+ const finalCleanup = cleanup;
654
+ cleanup = undefined;
655
+ if (finalCleanup) {
656
+ try {
657
+ untrack(finalCleanup);
658
+ }
659
+ catch (error) {
660
+ console.error('[Effect] Error in final cleanup:', error);
661
+ }
662
+ }
663
+ }
637
664
  effectDepth--;
638
665
  runningEffects.delete(execute);
639
666
  // Flush queue when we're back to top level
@@ -658,8 +685,10 @@ function effect(fn) {
658
685
  dependencies.clear();
659
686
  versions.clear();
660
687
  if (cleanup) {
688
+ const finalCleanup = cleanup;
689
+ cleanup = undefined;
661
690
  try {
662
- untrack(cleanup);
691
+ untrack(finalCleanup);
663
692
  }
664
693
  catch (error) {
665
694
  console.error('[Effect] Error in final cleanup:', error);
@@ -1401,11 +1430,6 @@ function evaluateExpression(expr, scope, allowPipes = true) {
1401
1430
  * @returns Evaluated value
1402
1431
  */
1403
1432
  function evaluateSimpleExpression(expr, scope) {
1404
- // Handle string literals
1405
- if ((expr.startsWith("'") && expr.endsWith("'")) ||
1406
- (expr.startsWith('"') && expr.endsWith('"'))) {
1407
- return expr.slice(1, -1);
1408
- }
1409
1433
  // Handle numbers
1410
1434
  if (!isNaN(Number(expr))) {
1411
1435
  return Number(expr);
@@ -1452,6 +1476,8 @@ function unmountScope(el) {
1452
1476
  let instance = mountedScopes.get(el);
1453
1477
  if (!instance)
1454
1478
  return;
1479
+ // A hook may call cleanup again; each mount is disposed at most once.
1480
+ mountedScopes.delete(el);
1455
1481
  // Cleanup all effects
1456
1482
  if (instance.__gyos_effects__) {
1457
1483
  instance.__gyos_effects__.forEach((cleanup) => {
@@ -1466,7 +1492,12 @@ function unmountScope(el) {
1466
1492
  }
1467
1493
  // Call lifecycle hook
1468
1494
  if (instance.onUnmount) {
1469
- instance.onUnmount.call(instance);
1495
+ try {
1496
+ instance.onUnmount.call(instance);
1497
+ }
1498
+ catch (error) {
1499
+ console.error('[Component] Error in onUnmount:', error);
1500
+ }
1470
1501
  }
1471
1502
  // Clear reference on element
1472
1503
  el.__gyos_scope__ = null;
@@ -1503,6 +1534,9 @@ function currentQueue() {
1503
1534
  return effectQueueStack[effectQueueStack.length - 1];
1504
1535
  }
1505
1536
  function attachDispose(target, runner) {
1537
+ // An earlier queued content binding can replace this subtree during flush.
1538
+ if (!target.isConnected)
1539
+ return;
1506
1540
  const dispose = effect(runner);
1507
1541
  if (!target.__gyos_effects__) {
1508
1542
  target.__gyos_effects__ = [];
@@ -2422,6 +2456,125 @@ function applyLeaveTransition(element, scope, removeElement = true) {
2422
2456
  return transitionManager.leave(element, transitionConfig, removeElement);
2423
2457
  }
2424
2458
 
2459
+ /**
2460
+ * Portal/Teleport System - Render content in different DOM location
2461
+ * Useful for modals, tooltips, notifications that need to break out of parent containers
2462
+ *
2463
+ * @example
2464
+ * // Portal to body (for modals)
2465
+ * <div g-portal="body">
2466
+ * <div class="modal">Modal content</div>
2467
+ * </div>
2468
+ *
2469
+ * @example
2470
+ * // Portal to specific element
2471
+ * <div g-portal="#notifications">
2472
+ * <div class="toast">Toast message</div>
2473
+ * </div>
2474
+ */
2475
+ /**
2476
+ * Create a portal - Move element to target location
2477
+ *
2478
+ * @param sourceEl - Element to teleport
2479
+ * @param targetSelector - CSS selector for destination
2480
+ *
2481
+ * @example
2482
+ * portalCreate(modalEl, 'body');
2483
+ * portalCreate(tooltipEl, '#tooltip-container');
2484
+ */
2485
+ function portalCreate(sourceEl, targetSelector) {
2486
+ if (!sourceEl)
2487
+ return;
2488
+ const target = document.querySelector(targetSelector);
2489
+ if (!target) {
2490
+ console.warn(`[GyosJS] Portal target "${targetSelector}" not found`);
2491
+ return;
2492
+ }
2493
+ // Create placeholder comment to mark original position
2494
+ const placeholder = document.createComment('g-portal');
2495
+ sourceEl.parentNode?.insertBefore(placeholder, sourceEl);
2496
+ // Store original parent for restoration
2497
+ sourceEl.__portal_placeholder__ = placeholder;
2498
+ sourceEl.__portal_target__ = target;
2499
+ placeholder.__gyos_portal__ = sourceEl;
2500
+ // Move the entire element to target
2501
+ target.appendChild(sourceEl);
2502
+ DEBUG() && console.log('[Portal] Created - moved element to', targetSelector);
2503
+ }
2504
+ /**
2505
+ * Destroy a portal - Restore element to original position
2506
+ *
2507
+ * @param sourceEl - Element to restore
2508
+ *
2509
+ * @example
2510
+ * portalDestroy(modalEl); // Returns modal to original location
2511
+ */
2512
+ function portalDestroy(sourceEl) {
2513
+ if (!sourceEl)
2514
+ return;
2515
+ const placeholder = sourceEl.__portal_placeholder__;
2516
+ if (placeholder && placeholder.parentNode) {
2517
+ delete placeholder.__gyos_portal__;
2518
+ // Move element back to original position
2519
+ placeholder.parentNode.insertBefore(sourceEl, placeholder);
2520
+ placeholder.remove();
2521
+ delete sourceEl.__portal_placeholder__;
2522
+ delete sourceEl.__portal_target__;
2523
+ DEBUG() && console.log('[Portal] Destroyed - restored element to original position');
2524
+ }
2525
+ }
2526
+
2527
+ /**
2528
+ * Cleanup utilities for disposing effects and event listeners
2529
+ */
2530
+ /**
2531
+ * Dispose all effects attached to an element and its descendants
2532
+ * Handles both element effects (__gyos_effects__) and component lifecycle
2533
+ */
2534
+ function disposeEffects(element = document.body, removeElement = false) {
2535
+ if (!element)
2536
+ return;
2537
+ disposeNode(element);
2538
+ if (removeElement)
2539
+ element.remove();
2540
+ }
2541
+ function disposeNode(element, removeElement = false) {
2542
+ untrack(() => disposeNodeInternal(element, removeElement));
2543
+ }
2544
+ function disposeNodeInternal(element, removeElement = false) {
2545
+ const portal = element.__gyos_portal__;
2546
+ if (portal) {
2547
+ delete element.__gyos_portal__;
2548
+ disposeNode(portal, removeElement);
2549
+ }
2550
+ // Include structural comment anchors. Snapshot before hooks mutate the tree.
2551
+ const children = Array.from(element.childNodes);
2552
+ const effects = element.__gyos_effects__;
2553
+ // Release ownership before callbacks to make reentrant cleanup safe.
2554
+ element.__gyos_effects__ = null;
2555
+ // Unmount scope if element has one (calls onUnmount + cleans instance.__gyos_effects__)
2556
+ if (element.hasAttribute?.('g-scope') || element.__gyos_scope__) {
2557
+ unmountScope(element);
2558
+ }
2559
+ // Dispose effects on this element (template effects like g-show, :class, {text})
2560
+ if (effects) {
2561
+ effects.forEach((dispose) => {
2562
+ try {
2563
+ dispose();
2564
+ }
2565
+ catch (error) {
2566
+ console.error('[GyosJS] Error disposing effect:', error);
2567
+ }
2568
+ });
2569
+ }
2570
+ // Recursively dispose effects on all descendants
2571
+ children.forEach(child => disposeNode(child));
2572
+ // Restore a portal to its placeholder before removing the owning tree.
2573
+ portalDestroy(element);
2574
+ if (removeElement)
2575
+ element.parentNode?.removeChild(element);
2576
+ }
2577
+
2425
2578
  /**
2426
2579
  * Directive Processing
2427
2580
  * Handles built-in directives (g-show, g-html, g-text) and custom directives
@@ -2483,6 +2636,7 @@ function processDirectives(element, scope, root) {
2483
2636
  const expr = element.getAttribute('g-html');
2484
2637
  queueReactiveEffect(element, () => {
2485
2638
  const value = evaluateExpression(expr, scope);
2639
+ Array.from(element.childNodes).forEach(child => disposeNode(child));
2486
2640
  element.innerHTML = value;
2487
2641
  });
2488
2642
  }
@@ -2491,6 +2645,7 @@ function processDirectives(element, scope, root) {
2491
2645
  const expr = element.getAttribute('g-text');
2492
2646
  queueReactiveEffect(element, () => {
2493
2647
  const value = evaluateExpression(expr, scope);
2648
+ Array.from(element.childNodes).forEach(child => disposeNode(child));
2494
2649
  element.textContent = value;
2495
2650
  });
2496
2651
  }
@@ -2568,7 +2723,7 @@ function processDirectives(element, scope, root) {
2568
2723
  * @param scope - Scope object for evaluation
2569
2724
  */
2570
2725
  function processDirectivesStatic(el, scope) {
2571
- const directives = Array.from(el.querySelectorAll('[g-show], [g-html], [g-text]'))
2726
+ const directives = [el, ...el.querySelectorAll('[g-show], [g-html], [g-text]')]
2572
2727
  .filter(element => !isInIgnoredTree(element));
2573
2728
  directives.forEach(elem => {
2574
2729
  const element = elem;
@@ -2645,7 +2800,9 @@ function readStyleValues(style) {
2645
2800
  return values;
2646
2801
  }
2647
2802
  function normalizeStyleProperty(property) {
2648
- if (property.startsWith('--') || property.includes('-'))
2803
+ if (property.startsWith('--'))
2804
+ return property;
2805
+ if (property.includes('-'))
2649
2806
  return property.toLowerCase();
2650
2807
  return property.replace(/[A-Z]/g, match => `-${match.toLowerCase()}`);
2651
2808
  }
@@ -2824,72 +2981,6 @@ function processBindingsStatic(root, scope) {
2824
2981
  }
2825
2982
  }
2826
2983
 
2827
- /**
2828
- * Portal/Teleport System - Render content in different DOM location
2829
- * Useful for modals, tooltips, notifications that need to break out of parent containers
2830
- *
2831
- * @example
2832
- * // Portal to body (for modals)
2833
- * <div g-portal="body">
2834
- * <div class="modal">Modal content</div>
2835
- * </div>
2836
- *
2837
- * @example
2838
- * // Portal to specific element
2839
- * <div g-portal="#notifications">
2840
- * <div class="toast">Toast message</div>
2841
- * </div>
2842
- */
2843
- /**
2844
- * Create a portal - Move element to target location
2845
- *
2846
- * @param sourceEl - Element to teleport
2847
- * @param targetSelector - CSS selector for destination
2848
- *
2849
- * @example
2850
- * portalCreate(modalEl, 'body');
2851
- * portalCreate(tooltipEl, '#tooltip-container');
2852
- */
2853
- function portalCreate(sourceEl, targetSelector) {
2854
- if (!sourceEl)
2855
- return;
2856
- const target = document.querySelector(targetSelector);
2857
- if (!target) {
2858
- console.warn(`[GyosJS] Portal target "${targetSelector}" not found`);
2859
- return;
2860
- }
2861
- // Create placeholder comment to mark original position
2862
- const placeholder = document.createComment('g-portal');
2863
- sourceEl.parentNode?.insertBefore(placeholder, sourceEl);
2864
- // Store original parent for restoration
2865
- sourceEl.__portal_placeholder__ = placeholder;
2866
- sourceEl.__portal_target__ = target;
2867
- // Move the entire element to target
2868
- target.appendChild(sourceEl);
2869
- DEBUG() && console.log('[Portal] Created - moved element to', targetSelector);
2870
- }
2871
- /**
2872
- * Destroy a portal - Restore element to original position
2873
- *
2874
- * @param sourceEl - Element to restore
2875
- *
2876
- * @example
2877
- * portalDestroy(modalEl); // Returns modal to original location
2878
- */
2879
- function portalDestroy(sourceEl) {
2880
- if (!sourceEl)
2881
- return;
2882
- const placeholder = sourceEl.__portal_placeholder__;
2883
- if (placeholder && placeholder.parentNode) {
2884
- // Move element back to original position
2885
- placeholder.parentNode.insertBefore(sourceEl, placeholder);
2886
- placeholder.remove();
2887
- delete sourceEl.__portal_placeholder__;
2888
- delete sourceEl.__portal_target__;
2889
- DEBUG() && console.log('[Portal] Destroyed - restored element to original position');
2890
- }
2891
- }
2892
-
2893
2984
  /**
2894
2985
  * Validator registry
2895
2986
  */
@@ -3075,7 +3166,7 @@ validator('maxLength', (value, length) => {
3075
3166
  * @example "min(18)"
3076
3167
  */
3077
3168
  validator('min', (value, min) => {
3078
- if (!value)
3169
+ if (value == null || value === '')
3079
3170
  return true;
3080
3171
  const minVal = parseFloat(min);
3081
3172
  return parseFloat(value) >= minVal || `Minimum value is ${minVal}`;
@@ -3086,7 +3177,7 @@ validator('min', (value, min) => {
3086
3177
  * @example "max(100)"
3087
3178
  */
3088
3179
  validator('max', (value, max) => {
3089
- if (!value)
3180
+ if (value == null || value === '')
3090
3181
  return true;
3091
3182
  const maxVal = parseFloat(max);
3092
3183
  return parseFloat(value) <= maxVal || `Maximum value is ${maxVal}`;
@@ -3107,9 +3198,9 @@ validator('number', (value) => {
3107
3198
  * @example "integer"
3108
3199
  */
3109
3200
  validator('integer', (value) => {
3110
- if (!value)
3201
+ if (value == null || value === '')
3111
3202
  return true;
3112
- return Number.isInteger(parseFloat(value)) || 'Must be an integer';
3203
+ return (String(value).trim() !== '' && Number.isInteger(Number(value))) || 'Must be an integer';
3113
3204
  });
3114
3205
  /**
3115
3206
  * Numeric - Must contain only digits
@@ -3222,7 +3313,7 @@ validator('date', (value) => {
3222
3313
  return 'Invalid date format (use YYYY-MM-DD)';
3223
3314
  }
3224
3315
  const date = new Date(value);
3225
- return !isNaN(date.getTime()) || 'Invalid date';
3316
+ return (!isNaN(date.getTime()) && date.toISOString().slice(0, 10) === value) || 'Invalid date';
3226
3317
  });
3227
3318
  /**
3228
3319
  * Before - Date must be before specified date
@@ -3302,7 +3393,7 @@ validator('notIn', (value, ...forbiddenValues) => {
3302
3393
  * @example "between(18,65)"
3303
3394
  */
3304
3395
  validator('between', (value, min, max) => {
3305
- if (!value)
3396
+ if (value == null || value === '')
3306
3397
  return true;
3307
3398
  const num = parseFloat(value);
3308
3399
  const minVal = parseFloat(min);
@@ -3556,8 +3647,16 @@ function processValidateDirective(el) {
3556
3647
  // Initialize error state - direct mutation
3557
3648
  state.errors.value[modelAttr] = null;
3558
3649
  state.touched.value[modelAttr] = false;
3559
- // Validation function
3560
- const validateField = async () => {
3650
+ let active = true;
3651
+ let generation = 0;
3652
+ let timeout;
3653
+ let latestValidation = Promise.resolve();
3654
+ // Each control publishes only its newest result. validateAll also waits for
3655
+ // a newer validation that superseded the request it originally started.
3656
+ const runValidation = async () => {
3657
+ if (!active)
3658
+ return;
3659
+ const request = ++generation;
3561
3660
  const value = getControlValue(el, form);
3562
3661
  // Get form context for validators that need it (like 'same')
3563
3662
  const formData = {};
@@ -3572,7 +3671,26 @@ function processValidateDirective(el) {
3572
3671
  }
3573
3672
  }
3574
3673
  });
3575
- const error = await validate(value, rules, { form: formData, field: modelAttr });
3674
+ let error;
3675
+ try {
3676
+ error = await validate(value, rules, { form: formData, field: modelAttr });
3677
+ }
3678
+ catch (cause) {
3679
+ console.error('[GyosJS] Field validation failed:', cause);
3680
+ error = 'Validation failed. Please try again.';
3681
+ }
3682
+ if (!active)
3683
+ return;
3684
+ if (request !== generation) {
3685
+ await latestValidation;
3686
+ return;
3687
+ }
3688
+ // Input may have changed while its debounce timer has not fired yet.
3689
+ // A submit must validate the current value before publishing approval.
3690
+ if (value !== getControlValue(el, form)) {
3691
+ await validateField();
3692
+ return;
3693
+ }
3576
3694
  // Update errors - only if changed
3577
3695
  const currentErrors = state.errors.value;
3578
3696
  if (currentErrors[modelAttr] !== error) {
@@ -3582,6 +3700,12 @@ function processValidateDirective(el) {
3582
3700
  updateFormState(state);
3583
3701
  }
3584
3702
  };
3703
+ const validateField = () => {
3704
+ clearTimeout(timeout);
3705
+ timeout = undefined;
3706
+ latestValidation = runValidation();
3707
+ return latestValidation;
3708
+ };
3585
3709
  // Register validator for validateAll
3586
3710
  if (!formValidators.has(form)) {
3587
3711
  formValidators.set(form, []);
@@ -3599,7 +3723,6 @@ function processValidateDirective(el) {
3599
3723
  };
3600
3724
  el.addEventListener('blur', blurListener);
3601
3725
  // Validate on input (with debounce)
3602
- let timeout;
3603
3726
  const inputListener = () => {
3604
3727
  clearTimeout(timeout);
3605
3728
  timeout = setTimeout(() => {
@@ -3611,6 +3734,24 @@ function processValidateDirective(el) {
3611
3734
  el.__gyos_effects__ = [];
3612
3735
  }
3613
3736
  el.__gyos_effects__.push(() => {
3737
+ active = false;
3738
+ generation++;
3739
+ delete el[validationFieldKey];
3740
+ const validators = formValidators.get(form);
3741
+ const index = validators?.indexOf(validateField) ?? -1;
3742
+ if (index !== -1)
3743
+ validators.splice(index, 1);
3744
+ const sharesField = Array.from(form.querySelectorAll('input, textarea, select'))
3745
+ .some(control => control[validationFieldKey] === modelAttr);
3746
+ if (!sharesField) {
3747
+ const errors = { ...state.errors.peek };
3748
+ delete errors[modelAttr];
3749
+ const touched = { ...state.touched.peek };
3750
+ delete touched[modelAttr];
3751
+ state.errors.value = errors;
3752
+ state.touched.value = touched;
3753
+ updateFormState(state);
3754
+ }
3614
3755
  el.removeEventListener('blur', blurListener);
3615
3756
  el.removeEventListener('input', inputListener);
3616
3757
  clearTimeout(timeout);
@@ -3683,7 +3824,9 @@ function processFormValidation(root, scope) {
3683
3824
  processFormDirective(root, scope);
3684
3825
  }
3685
3826
  // Then process g-validate
3686
- root.querySelectorAll('[g-validate]').forEach(el => {
3827
+ [root, ...root.querySelectorAll('[g-validate]')].forEach(el => {
3828
+ if (!el.hasAttribute('g-validate'))
3829
+ return;
3687
3830
  if (isInIgnoredTree(el))
3688
3831
  return;
3689
3832
  if (el instanceof HTMLElement) {
@@ -3691,7 +3834,9 @@ function processFormValidation(root, scope) {
3691
3834
  }
3692
3835
  });
3693
3836
  // Finally process g-errors
3694
- root.querySelectorAll('[g-errors]').forEach(el => {
3837
+ [root, ...root.querySelectorAll('[g-errors]')].forEach(el => {
3838
+ if (!el.hasAttribute('g-errors'))
3839
+ return;
3695
3840
  if (isInIgnoredTree(el))
3696
3841
  return;
3697
3842
  if (el instanceof HTMLElement) {
@@ -3722,12 +3867,13 @@ const RESERVED_MODIFIERS = new Set(['prevent', 'stop', 'once', 'capture', 'passi
3722
3867
  /**
3723
3868
  * Execute handler with modifiers (prevent, stop)
3724
3869
  */
3725
- function executeHandler(handler, scope, e, modifiers) {
3726
- // Handle prevent/stop modifiers
3870
+ function applyEventModifiers(e, modifiers) {
3727
3871
  if (modifiers.includes('prevent'))
3728
3872
  e.preventDefault();
3729
3873
  if (modifiers.includes('stop'))
3730
3874
  e.stopPropagation();
3875
+ }
3876
+ function executeHandler(handler, scope, e) {
3731
3877
  try {
3732
3878
  expressionRuntime().execute(handler, scope, e);
3733
3879
  }
@@ -3817,10 +3963,11 @@ function setupClickOutsideHandler(element, handler, modifiers, scope, attrName)
3817
3963
  if (target instanceof Element && target.closest('[g-ignore-outside-click]'))
3818
3964
  return;
3819
3965
  if (element !== target && !element.contains(target)) {
3966
+ applyEventModifiers(e, modifiers);
3820
3967
  const currentScope = getScopeFromElement(element) || scope;
3821
3968
  if (modifiers.includes('once'))
3822
3969
  cleanup();
3823
- executeHandler(handler, currentScope, e, modifiers);
3970
+ executeHandler(handler, currentScope, e);
3824
3971
  }
3825
3972
  };
3826
3973
  // Cleanup function
@@ -3897,13 +4044,14 @@ function processEvents(el, scope) {
3897
4044
  return; // Key doesn't match, skip
3898
4045
  }
3899
4046
  // Execute handler with optional debounce
4047
+ applyEventModifiers(e, modifiers);
3900
4048
  const execute = () => {
3901
4049
  if (modifiers.includes('once'))
3902
4050
  cleanup();
3903
4051
  // Batch in case handler mutates multiple signals
3904
4052
  batch(() => {
3905
4053
  const currentScope = getScopeFromElement(element) || scope;
3906
- executeHandler(handler, currentScope, e, modifiers);
4054
+ executeHandler(handler, currentScope, e);
3907
4055
  });
3908
4056
  };
3909
4057
  if (debounceMs > 0) {
@@ -4153,60 +4301,6 @@ function processModel(element, scope, root) {
4153
4301
  element.removeAttribute(modelAttr.name);
4154
4302
  }
4155
4303
 
4156
- /**
4157
- * Cleanup utilities for disposing effects and event listeners
4158
- */
4159
- /**
4160
- * Dispose all effects attached to an element and its descendants
4161
- * Handles both element effects (__gyos_effects__) and component lifecycle
4162
- */
4163
- function disposeEffects(element = document.body, removeElement = false) {
4164
- if (!element)
4165
- return;
4166
- // Unmount scope if element has one (calls onUnmount + cleans instance.__gyos_effects__)
4167
- if (element.hasAttribute?.('g-scope') || element.__gyos_scope__) {
4168
- unmountScope(element);
4169
- }
4170
- // Dispose effects on this element (template effects like g-show, :class, {text})
4171
- if (element.__gyos_effects__) {
4172
- const effects = element.__gyos_effects__;
4173
- effects.forEach((dispose) => {
4174
- try {
4175
- dispose();
4176
- }
4177
- catch (error) {
4178
- console.error('[GyosJS] Error disposing effect:', error);
4179
- }
4180
- });
4181
- element.__gyos_effects__ = null;
4182
- }
4183
- // Recursively dispose effects on all descendants
4184
- const descendants = element.querySelectorAll('*');
4185
- descendants.forEach((child) => {
4186
- // Unmount child scopes
4187
- if (child.hasAttribute?.('g-scope') || child.__gyos_scope__) {
4188
- unmountScope(child);
4189
- }
4190
- // Dispose child template effects
4191
- if (child.__gyos_effects__) {
4192
- const effects = child.__gyos_effects__;
4193
- effects.forEach((dispose) => {
4194
- try {
4195
- dispose();
4196
- }
4197
- catch (error) {
4198
- console.error('[GyosJS] Error disposing child effect:', error);
4199
- }
4200
- });
4201
- child.__gyos_effects__ = null;
4202
- }
4203
- });
4204
- // portal cleanup could be added here if needed
4205
- portalDestroy(element);
4206
- if (removeElement)
4207
- element.remove();
4208
- }
4209
-
4210
4304
  const storeCache = new WeakMap();
4211
4305
  const reactiveProxies = new WeakSet();
4212
4306
  const fieldSignals = new WeakMap();
@@ -4221,7 +4315,7 @@ function bumpScopeVersion(target) {
4221
4315
  if (visited.has(ver))
4222
4316
  return;
4223
4317
  visited.add(ver);
4224
- ver.value = ver.value + 1;
4318
+ ver.update(value => value + 1);
4225
4319
  const parents = versionParents.get(ver);
4226
4320
  if (parents) {
4227
4321
  parents.forEach(parentVer => bumpSignal(parentVer));
@@ -4259,7 +4353,7 @@ function getFieldSignal(target, key, initial) {
4259
4353
  }
4260
4354
  const STORE_MARKER = Symbol.for('gyos.store');
4261
4355
  function markStore(obj) {
4262
- if (obj.hasOwnProperty(STORE_MARKER))
4356
+ if (Object.prototype.hasOwnProperty.call(obj, STORE_MARKER))
4263
4357
  return obj;
4264
4358
  Reflect.defineProperty(obj, STORE_MARKER, {
4265
4359
  value: true,
@@ -4273,7 +4367,7 @@ function isStoreObject(val) {
4273
4367
  // markRaw: đánh dấu object để reactive() bỏ qua, không tạo proxy
4274
4368
  const RAW_MARKER = Symbol.for('gyos.raw');
4275
4369
  function markRaw(obj) {
4276
- if (obj.hasOwnProperty(RAW_MARKER))
4370
+ if (Object.prototype.hasOwnProperty.call(obj, RAW_MARKER))
4277
4371
  return obj;
4278
4372
  Reflect.defineProperty(obj, RAW_MARKER, {
4279
4373
  value: true,
@@ -4287,7 +4381,7 @@ function isRawObject(val) {
4287
4381
  // shallow: chỉ reactive "lớp ngoài", không reactive sâu bên trong
4288
4382
  const SHALLOW_MARKER = Symbol.for('gyos.shallow');
4289
4383
  function shallow(obj) {
4290
- if (obj.hasOwnProperty(SHALLOW_MARKER))
4384
+ if (Object.prototype.hasOwnProperty.call(obj, SHALLOW_MARKER))
4291
4385
  return obj;
4292
4386
  Reflect.defineProperty(obj, SHALLOW_MARKER, {
4293
4387
  value: true,
@@ -4321,6 +4415,25 @@ function linkParentVersion(child, parentVersion) {
4321
4415
  }
4322
4416
  versionParentsSet.add(parentVersion);
4323
4417
  }
4418
+ // Array [[DefineOwnProperty]] can change length or remove indices without
4419
+ // entering their individual Proxy traps. Keep already observed fields current.
4420
+ function syncArrayFields(target, previousLength) {
4421
+ if (previousLength === undefined)
4422
+ return;
4423
+ const array = target;
4424
+ if (array.length === previousLength)
4425
+ return;
4426
+ const signals = fieldSignals.get(target);
4427
+ signals?.get('length')?.update(() => array.length);
4428
+ if (array.length < previousLength) {
4429
+ signals?.forEach((sig, key) => {
4430
+ if (typeof key === 'string' && /^(0|[1-9]\d*)$/.test(key)
4431
+ && Number(key) >= array.length && Number(key) < previousLength) {
4432
+ sig.update(() => Reflect.get(target, key));
4433
+ }
4434
+ });
4435
+ }
4436
+ }
4324
4437
  function reactive(raw) {
4325
4438
  if (!raw || typeof raw !== "object" || isBuiltInObject(raw)) {
4326
4439
  return raw;
@@ -4358,6 +4471,8 @@ function reactive(raw) {
4358
4471
  return value;
4359
4472
  }
4360
4473
  if (isStoreObject(value)) {
4474
+ if (hasCurrentEffect())
4475
+ getFieldSignal(target, key, value).value;
4361
4476
  return value;
4362
4477
  }
4363
4478
  // Check if this is a getter property (computed property)
@@ -4434,10 +4549,6 @@ function reactive(raw) {
4434
4549
  }
4435
4550
  // capture old value BEFORE write to detect real changes
4436
4551
  const oldValue = target[key];
4437
- // VALUE LÀ STORE → set thẳng, KHÔNG tạo signal, KHÔNG trigger
4438
- if (isStoreObject(value)) {
4439
- return Reflect.set(target, key, value, receiver);
4440
- }
4441
4552
  const ok = Reflect.set(target, key, value, receiver);
4442
4553
  if (!ok)
4443
4554
  return false;
@@ -4479,7 +4590,9 @@ function reactive(raw) {
4479
4590
  const oldDesc = Object.getOwnPropertyDescriptor(target, key);
4480
4591
  const oldValue = oldDesc && "value" in oldDesc ? oldDesc.value : undefined;
4481
4592
  const newValue = "value" in descriptor ? descriptor.value : oldValue;
4593
+ const previousLength = Array.isArray(target) ? target.length : undefined;
4482
4594
  const ok = Reflect.defineProperty(target, key, descriptor);
4595
+ syncArrayFields(target, previousLength);
4483
4596
  if (!ok)
4484
4597
  return false;
4485
4598
  if ('value' in descriptor) {
@@ -4505,7 +4618,7 @@ function makeReactive(source) {
4505
4618
  // tạo 1 version signal cho root scope
4506
4619
  const version = ensureVersion(source);
4507
4620
  const proxy = reactive(source);
4508
- if (!proxy.hasOwnProperty(SCOPE_VERSION)) {
4621
+ if (!Object.prototype.hasOwnProperty.call(proxy, SCOPE_VERSION)) {
4509
4622
  Object.defineProperty(proxy, SCOPE_VERSION, {
4510
4623
  value: version,
4511
4624
  enumerable: false,
@@ -4627,6 +4740,20 @@ function getCachedTemplate(template) {
4627
4740
  function setRootScope(element, scope) {
4628
4741
  element.__gyos_scope__ = scope;
4629
4742
  }
4743
+ function inheritScope(child, parent) {
4744
+ attachParentScope(child, parent);
4745
+ for (const key in parent) {
4746
+ if (!(key in child)) {
4747
+ Object.defineProperty(child, key, {
4748
+ get: () => parent[key],
4749
+ set: value => { parent[key] = value; },
4750
+ enumerable: true,
4751
+ configurable: true,
4752
+ });
4753
+ }
4754
+ }
4755
+ return child;
4756
+ }
4630
4757
  /**
4631
4758
  * Create child scope for *for loops
4632
4759
  * Inherits parent scope properties via getters
@@ -4697,13 +4824,15 @@ function processForDirective(element, currentScope) {
4697
4824
  template.removeAttribute('g-key');
4698
4825
  const placeholder = document.createComment('*for');
4699
4826
  element.parentNode?.replaceChild(placeholder, element);
4827
+ const end = document.createComment('/*for');
4828
+ placeholder.parentNode?.insertBefore(end, placeholder.nextSibling);
4700
4829
  // Store previous items for key-based diffing
4701
4830
  // WARNING: Use primitive keys (id, string, number) to avoid memory leaks
4702
4831
  // Object keys will prevent garbage collection
4703
4832
  let prevItemsMap = new Map();
4704
4833
  let prevListRef = null;
4705
4834
  let prevVersionValue = undefined;
4706
- queueReactiveEffect(element, () => {
4835
+ queueReactiveEffect(placeholder, () => {
4707
4836
  // Parse: "item in items" or "item, index in items"
4708
4837
  const match = expr.match(/(.+?)\s+in\s+(.+)/);
4709
4838
  if (!match)
@@ -4730,7 +4859,7 @@ function processForDirective(element, currentScope) {
4730
4859
  }
4731
4860
  else {
4732
4861
  // Simple re-render (no diffing)
4733
- processForSimple(placeholder, template, list, itemVar, currentScope);
4862
+ processForSimple(placeholder, end, template, list, itemVar, currentScope);
4734
4863
  }
4735
4864
  });
4736
4865
  });
@@ -4837,16 +4966,19 @@ function processForWithKeys(placeholder, template, list, itemVar, keyExpr, curre
4837
4966
  /**
4838
4967
  * Process *for without keys (simple re-render)
4839
4968
  */
4840
- function processForSimple(placeholder, template, list, itemVar, currentScope) {
4969
+ function processForSimple(placeholder, end, template, list, itemVar, currentScope) {
4841
4970
  // Remove all existing items
4842
4971
  let next = placeholder.nextSibling;
4843
- while (next && next.nodeType !== Node.COMMENT_NODE) {
4972
+ while (next && next !== end) {
4844
4973
  const toRemove = next;
4845
4974
  next = next.nextSibling;
4846
4975
  if (toRemove instanceof Element) {
4847
4976
  unmountChildScopes(toRemove);
4848
4977
  disposeEffects(toRemove, true);
4849
4978
  }
4979
+ else {
4980
+ disposeNode(toRemove, true);
4981
+ }
4850
4982
  }
4851
4983
  // Render new items
4852
4984
  // Track last inserted node to maintain order
@@ -4939,7 +5071,7 @@ function processIfChain(element, currentScope) {
4939
5071
  element.parentNode?.replaceChild(placeholder, element);
4940
5072
  let currentElement = null;
4941
5073
  let currentIndex = -1;
4942
- queueReactiveEffect(element, () => {
5074
+ queueReactiveEffect(placeholder, () => {
4943
5075
  // Find first truthy condition
4944
5076
  let matchedIndex = -1;
4945
5077
  for (let i = 0; i < templates.length; i++) {
@@ -5065,14 +5197,13 @@ function processSwitchDirective(element, currentScope) {
5065
5197
  const switchValue = evaluateExpression(switchExpr, currentScope, false);
5066
5198
  // Find matching case
5067
5199
  let matchedIndex = -1;
5200
+ let defaultIndex = -1;
5068
5201
  for (let i = 0; i < templates.length; i++) {
5069
5202
  const { value } = templates[i];
5070
5203
  if (value === null) {
5071
- // *default matches (only if no other case matched)
5072
- if (matchedIndex === -1) {
5073
- matchedIndex = i;
5074
- }
5075
- break;
5204
+ if (defaultIndex === -1)
5205
+ defaultIndex = i;
5206
+ continue;
5076
5207
  }
5077
5208
  const caseValue = evaluateExpression(value, currentScope, false);
5078
5209
  if (switchValue === caseValue) {
@@ -5080,6 +5211,8 @@ function processSwitchDirective(element, currentScope) {
5080
5211
  break;
5081
5212
  }
5082
5213
  }
5214
+ if (matchedIndex === -1)
5215
+ matchedIndex = defaultIndex;
5083
5216
  // If same case, do nothing
5084
5217
  if (matchedIndex === currentIndex)
5085
5218
  return;
@@ -5198,6 +5331,7 @@ function processAwaitDirective(element, currentScope) {
5198
5331
  let requestVersion = 0;
5199
5332
  // Helper to render state
5200
5333
  const renderState = (state, data) => {
5334
+ currentState = state;
5201
5335
  // Remove old element
5202
5336
  if (currentElement) {
5203
5337
  const elemToRemove = currentElement;
@@ -5223,20 +5357,19 @@ function processAwaitDirective(element, currentScope) {
5223
5357
  else if (state === 'fulfilled' && thenTemplate) {
5224
5358
  template = thenTemplate.template;
5225
5359
  // Create child scope with data if varName provided
5226
- if (thenTemplate.varName && data !== undefined) {
5227
- scope = { ...currentScope, [thenTemplate.varName]: data };
5360
+ if (thenTemplate.varName) {
5361
+ scope = inheritScope({ [thenTemplate.varName]: data }, currentScope);
5228
5362
  }
5229
5363
  }
5230
5364
  else if (state === 'rejected' && catchTemplate) {
5231
5365
  template = catchTemplate.template;
5232
5366
  // Create child scope with error if varName provided
5233
- if (catchTemplate.varName && data !== undefined) {
5234
- scope = { ...currentScope, [catchTemplate.varName]: data };
5367
+ if (catchTemplate.varName) {
5368
+ scope = inheritScope({ [catchTemplate.varName]: data }, currentScope);
5235
5369
  }
5236
5370
  }
5237
5371
  if (template) {
5238
5372
  currentElement = getCachedTemplate(template);
5239
- currentState = state;
5240
5373
  setRootScope(currentElement, scope);
5241
5374
  // Apply transition initial state
5242
5375
  const elementsWithTransition = findElementsWithTransition(currentElement);
@@ -5264,8 +5397,6 @@ function processAwaitDirective(element, currentScope) {
5264
5397
  }
5265
5398
  }
5266
5399
  };
5267
- // Initial state: pending
5268
- renderState('pending');
5269
5400
  // Track promise expression
5270
5401
  queueReactiveEffect(element, () => {
5271
5402
  const promiseOrValue = evaluateExpression(awaitExpr, currentScope, false);
@@ -5289,6 +5420,8 @@ function processAwaitDirective(element, currentScope) {
5289
5420
  renderState('rejected', error);
5290
5421
  }
5291
5422
  });
5423
+ // Both reruns and disposal invalidate callbacks from this request.
5424
+ return () => { requestVersion++; };
5292
5425
  });
5293
5426
  }
5294
5427
 
@@ -5356,6 +5489,9 @@ function processStructuralDirectives(elements, scope) {
5356
5489
  structuralElements.sort((a, b) => a.depth - b.depth);
5357
5490
  // Process each structural directive
5358
5491
  structuralElements.forEach(({ element, type }) => {
5492
+ // Parent directives parse their clones, not the detached original tree.
5493
+ if (!root.contains(element) || elementBelongsToAnotherScope(element, scope))
5494
+ return;
5359
5495
  if (type === 'for') {
5360
5496
  processForDirective(element, scope);
5361
5497
  }
@@ -5391,6 +5527,10 @@ const elementBelongsToAnotherScope = (el, scope) => {
5391
5527
  function processParse(element, scope, fromStructural = false) {
5392
5528
  if (isInIgnoredTree(element))
5393
5529
  return;
5530
+ if (fromStructural && element.hasAttribute('g-scope') && mountFunction) {
5531
+ mountFunction(element);
5532
+ return;
5533
+ }
5394
5534
  beginEffectCollection();
5395
5535
  const allElements = [
5396
5536
  element,
@@ -5412,7 +5552,7 @@ function processParse(element, scope, fromStructural = false) {
5412
5552
  return;
5413
5553
  if (el.attributes.length === 0)
5414
5554
  return; // Skip if no attributes
5415
- if (elementBelongsToAnotherScope(el, scope) && !fromStructural) {
5555
+ if (elementBelongsToAnotherScope(el, scope)) {
5416
5556
  // (fromStructural allows processing newly created elements inside structurals)
5417
5557
  return; // Skip if inside mounted scope
5418
5558
  }
@@ -5420,8 +5560,9 @@ function processParse(element, scope, fromStructural = false) {
5420
5560
  if (el.hasAttribute('g-static')) {
5421
5561
  // Pre-process g-static elements (mark and render them before reactive processing)
5422
5562
  processStaticElements(el, scope);
5563
+ return;
5423
5564
  }
5424
- if (el.hasAttribute('g-form')) {
5565
+ if (el.hasAttribute('g-form') || el.hasAttribute('g-validate') || el.hasAttribute('g-errors')) {
5425
5566
  // Process form validation (g-form, g-validate, g-errors)
5426
5567
  processFormValidation(el, scope);
5427
5568
  }
@@ -5771,7 +5912,7 @@ function mountAll(root) {
5771
5912
  const allElements = [...elements, ...elementsNotScope].filter(el => !isInIgnoredTree(el));
5772
5913
  allElements.sort((a, b) => getDepth(b) - getDepth(a));
5773
5914
  // Filter out elements inside structural directives - they will be mounted by structural processor
5774
- allElements.forEach(el => !hasStructuralParent(el) && mount(el));
5915
+ allElements.forEach(el => !el.hasAttribute('*if') && !el.hasAttribute('*for') && !hasStructuralParent(el) && mount(el));
5775
5916
  diagnoseUnscopedReveals(document.body);
5776
5917
  }
5777
5918
  function mountTree(el) {
@@ -5782,7 +5923,7 @@ function mountTree(el) {
5782
5923
  .filter(element => element.hasAttribute('g-scope') || hasAutoScope(element));
5783
5924
  // Child scopes own their subtree before an existing parent scope parses the insertion.
5784
5925
  candidates.sort((a, b) => getDepth(b) - getDepth(a));
5785
- candidates.forEach(element => !hasStructuralParent(element) && mount(element));
5926
+ candidates.forEach(element => !element.hasAttribute('*if') && !element.hasAttribute('*for') && !hasStructuralParent(element) && mount(element));
5786
5927
  diagnoseUnscopedReveals(el);
5787
5928
  if (getMountedScope(el))
5788
5929
  return;
@@ -5811,9 +5952,17 @@ function mount(el) {
5811
5952
  /**
5812
5953
  * Parse inline scope definition from HTML attribute
5813
5954
  */
5955
+ function decodeMarkupExpression(value) {
5956
+ try {
5957
+ return decodeURIComponent(value);
5958
+ }
5959
+ catch {
5960
+ return value;
5961
+ } // Plain expressions may contain a literal % or modulo.
5962
+ }
5814
5963
  function parseInlineScope(scopeStr) {
5815
5964
  // If scopeStr is encode urld, decode it first
5816
- scopeStr = decodeURIComponent(scopeStr);
5965
+ scopeStr = decodeMarkupExpression(scopeStr);
5817
5966
  try {
5818
5967
  // Check if it's an inline object definition (starts with '{')
5819
5968
  const trimmed = scopeStr.trim();
@@ -5880,7 +6029,7 @@ function parseAutoScope(el) {
5880
6029
  // gm-method-name:args:arg2="expression"
5881
6030
  if (attr.name.match(/^gm-.+/)) {
5882
6031
  // If expr is encoded url, decode it first
5883
- const expr = decodeURIComponent(attr.value.trim());
6032
+ const expr = decodeMarkupExpression(attr.value.trim());
5884
6033
  if (forbidden.some(f => expr.includes(f))) {
5885
6034
  DEBUG() && console.log("[GyosJS] Scope mount error: Forbidden expression:", expr);
5886
6035
  }
@@ -5991,15 +6140,11 @@ function handleDefinition(el, scopeAttr) {
5991
6140
  * Mount a specific scope
5992
6141
  */
5993
6142
  function mountScope(el, scopeAttr) {
5994
- const definition = handleDefinition(el, scopeAttr);
5995
6143
  // Check if already mounted
5996
6144
  if (getMountedScope(el)) {
5997
6145
  return;
5998
6146
  }
5999
- // Check if element is static (no reactivity)
6000
- if (el.hasAttribute('g-static')) {
6001
- return;
6002
- }
6147
+ const definition = handleDefinition(el, scopeAttr);
6003
6148
  // Check hydration strategy
6004
6149
  const hydrationStrategy = getHydrationStrategy(el);
6005
6150
  if (hydrationStrategy) {
@@ -6064,13 +6209,21 @@ function mountScopeInternal(el, definition) {
6064
6209
  // Parse and bind template (portals will be processed inside *if)
6065
6210
  // Pass onMount callback to be called after parsing (or after hydration triggers)
6066
6211
  parseTemplate(el, instance, () => {
6212
+ // The hook may inspect or clean up its own mount. Register before calling
6213
+ // user code, and do not register again if the hook disposes the scope.
6214
+ registerMountedScope(el, instance);
6067
6215
  // Call lifecycle hook after template is parsed
6068
6216
  if (instance.onMount) {
6069
- Promise.resolve(instance.onMount.call(instance)).catch(console.error);
6217
+ try {
6218
+ Promise.resolve(instance.onMount.call(instance)).catch(console.error);
6219
+ }
6220
+ catch (error) {
6221
+ console.error('[Component] Error in onMount:', error);
6222
+ }
6070
6223
  }
6071
6224
  });
6072
- // Store instance
6073
- registerMountedScope(el, instance);
6225
+ if (getMountedScope(el) !== instance)
6226
+ return;
6074
6227
  // Cache instance if g-scope-persist is set (with interpolation support)
6075
6228
  getPersistKey$1(el, persistKey => {
6076
6229
  if (!scopeCached.has(persistKey)) {
@@ -6086,7 +6239,7 @@ function createContext(el, getInstance) {
6086
6239
  const events = new Map();
6087
6240
  // Find all refs within this scope only
6088
6241
  el.querySelectorAll('[g-ref]').forEach(refEl => {
6089
- if (isInIgnoredTree(refEl))
6242
+ if (isInIgnoredTree(refEl) || (refEl.closest('[g-scope]') || el) !== el)
6090
6243
  return;
6091
6244
  const refName = refEl.getAttribute('g-ref');
6092
6245
  if (refName && !hasUnsafePropertyPath(refName)) {
@@ -6136,13 +6289,16 @@ function createContext(el, getInstance) {
6136
6289
  }
6137
6290
  const { immediate = false, deep = false, debounce = 0 } = options;
6138
6291
  let timeoutId;
6292
+ let active = true;
6139
6293
  if (debounce > 0) {
6140
6294
  // Wrap handler with debounce
6141
6295
  const originalHandler = handler;
6142
6296
  handler = (...args) => {
6143
6297
  clearTimeout(timeoutId);
6144
6298
  timeoutId = setTimeout(() => {
6145
- originalHandler(...args);
6299
+ timeoutId = undefined;
6300
+ if (active)
6301
+ untrack(() => originalHandler.call(instance, ...args));
6146
6302
  }, debounce);
6147
6303
  };
6148
6304
  }
@@ -6171,28 +6327,34 @@ function createContext(el, getInstance) {
6171
6327
  initialized = true;
6172
6328
  // Call immediately if requested
6173
6329
  if (immediate) {
6174
- handler.call(instance, clonedValue, undefined);
6330
+ untrack(() => handler.call(instance, clonedValue, undefined));
6175
6331
  }
6176
6332
  return;
6177
6333
  }
6178
6334
  // Check if value actually changed
6179
6335
  const changed = deep
6180
6336
  ? !deepEqual(oldValue, clonedValue)
6181
- : oldValue !== clonedValue;
6337
+ : !Object.is(oldValue, clonedValue);
6182
6338
  if (changed) {
6183
- handler.call(instance, clonedValue, oldValue);
6339
+ untrack(() => handler.call(instance, clonedValue, oldValue));
6184
6340
  oldValue = deep && typeof clonedValue === 'object'
6185
6341
  ? clone(clonedValue)
6186
6342
  : clonedValue;
6187
6343
  }
6188
6344
  });
6345
+ const stopWatching = () => {
6346
+ active = false;
6347
+ clearTimeout(timeoutId);
6348
+ timeoutId = undefined;
6349
+ watchEffect();
6350
+ };
6189
6351
  // Store cleanup for unmount
6190
6352
  if (!instance.__gyos_effects__) {
6191
6353
  instance.__gyos_effects__ = [];
6192
6354
  }
6193
- instance.__gyos_effects__.push(watchEffect);
6355
+ instance.__gyos_effects__.push(stopWatching);
6194
6356
  // Return unwatch function
6195
- return watchEffect;
6357
+ return stopWatching;
6196
6358
  },
6197
6359
  $effect: (fn) => {
6198
6360
  // Shorthand for effect with auto cleanup on unmount
@@ -6400,8 +6562,8 @@ function off(event, handler) {
6400
6562
  */
6401
6563
  function once(event, handler) {
6402
6564
  const wrapper = (...args) => {
6403
- handler(...args);
6404
6565
  off(event, wrapper);
6566
+ handler(...args);
6405
6567
  };
6406
6568
  return on(event, wrapper);
6407
6569
  }
@@ -6439,23 +6601,34 @@ function useFetch(url) {
6439
6601
  const data = signal(null);
6440
6602
  const loading = signal(true);
6441
6603
  const error = signal(null);
6604
+ let generation = 0;
6605
+ let active = true;
6442
6606
  const fetchData = async () => {
6607
+ if (!active)
6608
+ return;
6609
+ const requestId = ++generation;
6443
6610
  loading.value = true;
6444
6611
  error.value = null;
6445
6612
  data.value = null;
6446
6613
  try {
6447
6614
  const request = typeof url === 'function' ? await url() : url;
6615
+ if (requestId !== generation)
6616
+ return;
6448
6617
  const response = typeof request === 'string' ? await fetch(request) : request;
6449
6618
  if (!response.ok) {
6450
6619
  throw new Error(`HTTP error! status: ${response.status}`);
6451
6620
  }
6452
- data.value = await response.json();
6621
+ const result = await response.json();
6622
+ if (requestId === generation)
6623
+ data.value = result;
6453
6624
  }
6454
6625
  catch (e) {
6455
- error.value = e;
6626
+ if (requestId === generation)
6627
+ error.value = e;
6456
6628
  }
6457
6629
  finally {
6458
- loading.value = false;
6630
+ if (requestId === generation)
6631
+ loading.value = false;
6459
6632
  }
6460
6633
  };
6461
6634
  return {
@@ -6463,7 +6636,8 @@ function useFetch(url) {
6463
6636
  loading,
6464
6637
  error,
6465
6638
  refetch: fetchData,
6466
- onMount: fetchData
6639
+ onMount: () => { active = true; return fetchData(); },
6640
+ onUnmount: () => { active = false; generation++; loading.value = false; }
6467
6641
  };
6468
6642
  }
6469
6643
  /**
@@ -6721,17 +6895,26 @@ function useAsync(asyncFn, immediate = true) {
6721
6895
  const data = signal(null);
6722
6896
  const loading = signal(false);
6723
6897
  const error = signal(null);
6898
+ let generation = 0;
6899
+ let active = true;
6724
6900
  const execute = async () => {
6901
+ if (!active)
6902
+ return;
6903
+ const requestId = ++generation;
6725
6904
  loading.value = true;
6726
6905
  error.value = null;
6727
6906
  try {
6728
- data.value = await asyncFn();
6907
+ const result = await asyncFn();
6908
+ if (requestId === generation)
6909
+ data.value = result;
6729
6910
  }
6730
6911
  catch (e) {
6731
- error.value = e;
6912
+ if (requestId === generation)
6913
+ error.value = e;
6732
6914
  }
6733
6915
  finally {
6734
- loading.value = false;
6916
+ if (requestId === generation)
6917
+ loading.value = false;
6735
6918
  }
6736
6919
  };
6737
6920
  return {
@@ -6740,9 +6923,10 @@ function useAsync(asyncFn, immediate = true) {
6740
6923
  error,
6741
6924
  execute,
6742
6925
  onMount: () => {
6743
- if (immediate)
6744
- execute();
6745
- }
6926
+ active = true;
6927
+ return immediate ? execute() : undefined;
6928
+ },
6929
+ onUnmount: () => { active = false; generation++; loading.value = false; }
6746
6930
  };
6747
6931
  }
6748
6932
 
@@ -7230,7 +7414,10 @@ function syncAttributes(target, source) {
7230
7414
  Array.from(source.attributes).forEach(attribute => {
7231
7415
  sourceAttributes.add(attribute.name);
7232
7416
  if (target.getAttribute(attribute.name) !== attribute.value) {
7233
- target.setAttribute(attribute.name, attribute.value);
7417
+ // HTML permits directive names such as @click and *if, while older
7418
+ // DOM implementations apply XML name validation in setAttribute.
7419
+ // Transfer the already-parsed Attr without validating its name again.
7420
+ target.setAttributeNodeNS(target.ownerDocument.importNode(attribute, true));
7234
7421
  }
7235
7422
  });
7236
7423
  Array.from(target.attributes).forEach(attribute => {
@@ -7514,7 +7701,14 @@ function handleScroll(url, trigger, savedScroll) {
7514
7701
  // Hash scrolling
7515
7702
  const hash = new URL(url).hash;
7516
7703
  if (hash) {
7517
- const el = document.querySelector(hash);
7704
+ // A URL fragment identifies an id, not a CSS selector. Numeric ids,
7705
+ // punctuation and percent-encoded Unicode must work without escaping.
7706
+ let id = hash.slice(1);
7707
+ try {
7708
+ id = decodeURIComponent(id);
7709
+ }
7710
+ catch { /* Keep malformed fragments literal. */ }
7711
+ const el = document.getElementById(id);
7518
7712
  if (el) {
7519
7713
  el.scrollIntoView({ behavior: 'smooth' });
7520
7714
  return;
@@ -8094,6 +8288,12 @@ function getHistoryFragment(entryId, neighbourId) {
8094
8288
  return fragment?.cloneNode(true);
8095
8289
  }
8096
8290
  function cloneHistoryTarget(target) {
8291
+ // Mounted templates have already consumed event/model attributes and text
8292
+ // expressions. A DOM clone cannot recreate their observers. Restore these
8293
+ // targets from response HTML (snapshot or fetch) instead of caching inert UI.
8294
+ if (getScopeFromElement(target) || Array.from(target.querySelectorAll('*'))
8295
+ .some(element => element.__gyos_scope__))
8296
+ return null;
8097
8297
  const clone = target.cloneNode(true);
8098
8298
  clone.querySelectorAll('.gyos-target-spinner').forEach(spinner => spinner.remove());
8099
8299
  return clone;
@@ -8951,7 +9151,7 @@ const Gyos = {
8951
9151
  portalCreate,
8952
9152
  portalDestroy,
8953
9153
  setCspNonce,
8954
- version: '0.5.3'
9154
+ version: '0.5.4'
8955
9155
  };
8956
9156
 
8957
9157
  // This file was generated. Do not modify manually!
@@ -15365,30 +15565,30 @@ function resolveReference(node, context, expression) {
15365
15565
  throw cspError('Invalid assignment target', expression, node);
15366
15566
  }
15367
15567
  function evaluateCall(node, context, expression) {
15368
- const args = node.arguments.map((argument) => {
15369
- if (argument.type === 'SpreadElement')
15370
- throw cspError('Spread arguments are not supported', expression, argument);
15371
- return evaluateNode(argument, context, expression);
15372
- });
15568
+ let receiver = context.scope;
15569
+ let callable;
15373
15570
  if (node.callee.type === 'MemberExpression') {
15374
15571
  const [object, property] = memberParts(node.callee, context, expression);
15375
15572
  if (object === optionalChainMiss)
15376
15573
  return optionalChainMiss;
15377
- const method = object[property];
15378
- if (method == null && node.optional)
15379
- return optionalChainMiss;
15380
- if (typeof method !== 'function')
15381
- throw cspError('Called value is not a function', expression, node.callee);
15382
- return method.apply(object, args);
15574
+ receiver = object;
15575
+ callable = object[property];
15576
+ }
15577
+ else {
15578
+ callable = evaluateNode(node.callee, context, expression);
15383
15579
  }
15384
- const callable = evaluateNode(node.callee, context, expression);
15385
15580
  if (callable === optionalChainMiss)
15386
15581
  return optionalChainMiss;
15387
15582
  if (callable == null && node.optional)
15388
15583
  return optionalChainMiss;
15584
+ const args = node.arguments.map((argument) => {
15585
+ if (argument.type === 'SpreadElement')
15586
+ throw cspError('Spread arguments are not supported', expression, argument);
15587
+ return evaluateNode(argument, context, expression);
15588
+ });
15389
15589
  if (typeof callable !== 'function')
15390
15590
  throw cspError('Called value is not a function', expression, node.callee);
15391
- return callable.apply(context.scope, args);
15591
+ return callable.apply(receiver, args);
15392
15592
  }
15393
15593
  function applyAssignment(operator, current, value, expression, node) {
15394
15594
  switch (operator) {
@@ -15511,10 +15711,10 @@ function evaluateNode(node, context, expression) {
15511
15711
  }
15512
15712
  case 'UpdateExpression': {
15513
15713
  const reference = resolveReference(node.argument, context, expression);
15514
- const current = reference.get();
15515
- const next = node.operator === '++' ? current + 1 : current - 1;
15714
+ let next = reference.get();
15715
+ const previous = node.operator === '++' ? next++ : next--;
15516
15716
  reference.set(next);
15517
- return node.prefix ? next : current;
15717
+ return node.prefix ? next : previous;
15518
15718
  }
15519
15719
  case 'SequenceExpression': {
15520
15720
  let value;