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
@@ -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
  */
@@ -76,25 +76,30 @@
76
76
  }
77
77
  const cloned = {};
78
78
  for (const key in obj) {
79
- if (obj.hasOwnProperty(key)) {
79
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
80
80
  cloned[key] = clone(obj[key]);
81
81
  }
82
82
  }
83
83
  return cloned;
84
84
  }
85
85
  function deepEqual(a, b) {
86
- if (a === b)
86
+ if (Object.is(a, b))
87
87
  return true;
88
88
  if (typeof a !== 'object' || typeof b !== 'object' || a == null || b == null) {
89
89
  return false;
90
90
  }
91
+ if (a instanceof Date || b instanceof Date) {
92
+ return a instanceof Date && b instanceof Date && Object.is(a.getTime(), b.getTime());
93
+ }
94
+ if (Array.isArray(a) !== Array.isArray(b))
95
+ return false;
91
96
  const keysA = Object.keys(a);
92
97
  const keysB = Object.keys(b);
93
98
  if (keysA.length !== keysB.length) {
94
99
  return false;
95
100
  }
96
101
  for (const key of keysA) {
97
- if (!deepEqual(a[key], b[key])) {
102
+ if (!Object.prototype.hasOwnProperty.call(b, key) || !deepEqual(a[key], b[key])) {
98
103
  return false;
99
104
  }
100
105
  }
@@ -630,8 +635,11 @@
630
635
  execute.__dependencies = dependencies;
631
636
  execute.__versions = versions;
632
637
  try {
633
- const nextCleanup = fn();
634
- cleanup = typeof nextCleanup === 'function' ? nextCleanup : undefined;
638
+ // The previous cleanup can dispose this effect before the next run.
639
+ if (active) {
640
+ const nextCleanup = fn();
641
+ cleanup = typeof nextCleanup === 'function' ? nextCleanup : undefined;
642
+ }
635
643
  }
636
644
  catch (error) {
637
645
  console.error('[Effect] Error in effect:', error);
@@ -640,6 +648,25 @@
640
648
  finally {
641
649
  initialized = true;
642
650
  currentEffect = prevEffect;
651
+ // stop() may have been called inside fn, before its cleanup was returned
652
+ // or before later reads registered more dependencies.
653
+ if (!active) {
654
+ dependencies.forEach(dependency => dependency.delete(execute));
655
+ dependencies.clear();
656
+ versions.clear();
657
+ effectQueue.delete(execute);
658
+ batchedEffects.delete(execute);
659
+ const finalCleanup = cleanup;
660
+ cleanup = undefined;
661
+ if (finalCleanup) {
662
+ try {
663
+ untrack(finalCleanup);
664
+ }
665
+ catch (error) {
666
+ console.error('[Effect] Error in final cleanup:', error);
667
+ }
668
+ }
669
+ }
643
670
  effectDepth--;
644
671
  runningEffects.delete(execute);
645
672
  // Flush queue when we're back to top level
@@ -664,8 +691,10 @@
664
691
  dependencies.clear();
665
692
  versions.clear();
666
693
  if (cleanup) {
694
+ const finalCleanup = cleanup;
695
+ cleanup = undefined;
667
696
  try {
668
- untrack(cleanup);
697
+ untrack(finalCleanup);
669
698
  }
670
699
  catch (error) {
671
700
  console.error('[Effect] Error in final cleanup:', error);
@@ -1407,11 +1436,6 @@
1407
1436
  * @returns Evaluated value
1408
1437
  */
1409
1438
  function evaluateSimpleExpression(expr, scope) {
1410
- // Handle string literals
1411
- if ((expr.startsWith("'") && expr.endsWith("'")) ||
1412
- (expr.startsWith('"') && expr.endsWith('"'))) {
1413
- return expr.slice(1, -1);
1414
- }
1415
1439
  // Handle numbers
1416
1440
  if (!isNaN(Number(expr))) {
1417
1441
  return Number(expr);
@@ -1458,6 +1482,8 @@
1458
1482
  let instance = mountedScopes.get(el);
1459
1483
  if (!instance)
1460
1484
  return;
1485
+ // A hook may call cleanup again; each mount is disposed at most once.
1486
+ mountedScopes.delete(el);
1461
1487
  // Cleanup all effects
1462
1488
  if (instance.__gyos_effects__) {
1463
1489
  instance.__gyos_effects__.forEach((cleanup) => {
@@ -1472,7 +1498,12 @@
1472
1498
  }
1473
1499
  // Call lifecycle hook
1474
1500
  if (instance.onUnmount) {
1475
- instance.onUnmount.call(instance);
1501
+ try {
1502
+ instance.onUnmount.call(instance);
1503
+ }
1504
+ catch (error) {
1505
+ console.error('[Component] Error in onUnmount:', error);
1506
+ }
1476
1507
  }
1477
1508
  // Clear reference on element
1478
1509
  el.__gyos_scope__ = null;
@@ -1509,6 +1540,9 @@
1509
1540
  return effectQueueStack[effectQueueStack.length - 1];
1510
1541
  }
1511
1542
  function attachDispose(target, runner) {
1543
+ // An earlier queued content binding can replace this subtree during flush.
1544
+ if (!target.isConnected)
1545
+ return;
1512
1546
  const dispose = effect(runner);
1513
1547
  if (!target.__gyos_effects__) {
1514
1548
  target.__gyos_effects__ = [];
@@ -2428,6 +2462,125 @@
2428
2462
  return transitionManager.leave(element, transitionConfig, removeElement);
2429
2463
  }
2430
2464
 
2465
+ /**
2466
+ * Portal/Teleport System - Render content in different DOM location
2467
+ * Useful for modals, tooltips, notifications that need to break out of parent containers
2468
+ *
2469
+ * @example
2470
+ * // Portal to body (for modals)
2471
+ * <div g-portal="body">
2472
+ * <div class="modal">Modal content</div>
2473
+ * </div>
2474
+ *
2475
+ * @example
2476
+ * // Portal to specific element
2477
+ * <div g-portal="#notifications">
2478
+ * <div class="toast">Toast message</div>
2479
+ * </div>
2480
+ */
2481
+ /**
2482
+ * Create a portal - Move element to target location
2483
+ *
2484
+ * @param sourceEl - Element to teleport
2485
+ * @param targetSelector - CSS selector for destination
2486
+ *
2487
+ * @example
2488
+ * portalCreate(modalEl, 'body');
2489
+ * portalCreate(tooltipEl, '#tooltip-container');
2490
+ */
2491
+ function portalCreate(sourceEl, targetSelector) {
2492
+ if (!sourceEl)
2493
+ return;
2494
+ const target = document.querySelector(targetSelector);
2495
+ if (!target) {
2496
+ console.warn(`[GyosJS] Portal target "${targetSelector}" not found`);
2497
+ return;
2498
+ }
2499
+ // Create placeholder comment to mark original position
2500
+ const placeholder = document.createComment('g-portal');
2501
+ sourceEl.parentNode?.insertBefore(placeholder, sourceEl);
2502
+ // Store original parent for restoration
2503
+ sourceEl.__portal_placeholder__ = placeholder;
2504
+ sourceEl.__portal_target__ = target;
2505
+ placeholder.__gyos_portal__ = sourceEl;
2506
+ // Move the entire element to target
2507
+ target.appendChild(sourceEl);
2508
+ DEBUG() && console.log('[Portal] Created - moved element to', targetSelector);
2509
+ }
2510
+ /**
2511
+ * Destroy a portal - Restore element to original position
2512
+ *
2513
+ * @param sourceEl - Element to restore
2514
+ *
2515
+ * @example
2516
+ * portalDestroy(modalEl); // Returns modal to original location
2517
+ */
2518
+ function portalDestroy(sourceEl) {
2519
+ if (!sourceEl)
2520
+ return;
2521
+ const placeholder = sourceEl.__portal_placeholder__;
2522
+ if (placeholder && placeholder.parentNode) {
2523
+ delete placeholder.__gyos_portal__;
2524
+ // Move element back to original position
2525
+ placeholder.parentNode.insertBefore(sourceEl, placeholder);
2526
+ placeholder.remove();
2527
+ delete sourceEl.__portal_placeholder__;
2528
+ delete sourceEl.__portal_target__;
2529
+ DEBUG() && console.log('[Portal] Destroyed - restored element to original position');
2530
+ }
2531
+ }
2532
+
2533
+ /**
2534
+ * Cleanup utilities for disposing effects and event listeners
2535
+ */
2536
+ /**
2537
+ * Dispose all effects attached to an element and its descendants
2538
+ * Handles both element effects (__gyos_effects__) and component lifecycle
2539
+ */
2540
+ function disposeEffects(element = document.body, removeElement = false) {
2541
+ if (!element)
2542
+ return;
2543
+ disposeNode(element);
2544
+ if (removeElement)
2545
+ element.remove();
2546
+ }
2547
+ function disposeNode(element, removeElement = false) {
2548
+ untrack(() => disposeNodeInternal(element, removeElement));
2549
+ }
2550
+ function disposeNodeInternal(element, removeElement = false) {
2551
+ const portal = element.__gyos_portal__;
2552
+ if (portal) {
2553
+ delete element.__gyos_portal__;
2554
+ disposeNode(portal, removeElement);
2555
+ }
2556
+ // Include structural comment anchors. Snapshot before hooks mutate the tree.
2557
+ const children = Array.from(element.childNodes);
2558
+ const effects = element.__gyos_effects__;
2559
+ // Release ownership before callbacks to make reentrant cleanup safe.
2560
+ element.__gyos_effects__ = null;
2561
+ // Unmount scope if element has one (calls onUnmount + cleans instance.__gyos_effects__)
2562
+ if (element.hasAttribute?.('g-scope') || element.__gyos_scope__) {
2563
+ unmountScope(element);
2564
+ }
2565
+ // Dispose effects on this element (template effects like g-show, :class, {text})
2566
+ if (effects) {
2567
+ effects.forEach((dispose) => {
2568
+ try {
2569
+ dispose();
2570
+ }
2571
+ catch (error) {
2572
+ console.error('[GyosJS] Error disposing effect:', error);
2573
+ }
2574
+ });
2575
+ }
2576
+ // Recursively dispose effects on all descendants
2577
+ children.forEach(child => disposeNode(child));
2578
+ // Restore a portal to its placeholder before removing the owning tree.
2579
+ portalDestroy(element);
2580
+ if (removeElement)
2581
+ element.parentNode?.removeChild(element);
2582
+ }
2583
+
2431
2584
  /**
2432
2585
  * Directive Processing
2433
2586
  * Handles built-in directives (g-show, g-html, g-text) and custom directives
@@ -2489,6 +2642,7 @@
2489
2642
  const expr = element.getAttribute('g-html');
2490
2643
  queueReactiveEffect(element, () => {
2491
2644
  const value = evaluateExpression(expr, scope);
2645
+ Array.from(element.childNodes).forEach(child => disposeNode(child));
2492
2646
  element.innerHTML = value;
2493
2647
  });
2494
2648
  }
@@ -2497,6 +2651,7 @@
2497
2651
  const expr = element.getAttribute('g-text');
2498
2652
  queueReactiveEffect(element, () => {
2499
2653
  const value = evaluateExpression(expr, scope);
2654
+ Array.from(element.childNodes).forEach(child => disposeNode(child));
2500
2655
  element.textContent = value;
2501
2656
  });
2502
2657
  }
@@ -2574,7 +2729,7 @@
2574
2729
  * @param scope - Scope object for evaluation
2575
2730
  */
2576
2731
  function processDirectivesStatic(el, scope) {
2577
- const directives = Array.from(el.querySelectorAll('[g-show], [g-html], [g-text]'))
2732
+ const directives = [el, ...el.querySelectorAll('[g-show], [g-html], [g-text]')]
2578
2733
  .filter(element => !isInIgnoredTree(element));
2579
2734
  directives.forEach(elem => {
2580
2735
  const element = elem;
@@ -2651,7 +2806,9 @@
2651
2806
  return values;
2652
2807
  }
2653
2808
  function normalizeStyleProperty(property) {
2654
- if (property.startsWith('--') || property.includes('-'))
2809
+ if (property.startsWith('--'))
2810
+ return property;
2811
+ if (property.includes('-'))
2655
2812
  return property.toLowerCase();
2656
2813
  return property.replace(/[A-Z]/g, match => `-${match.toLowerCase()}`);
2657
2814
  }
@@ -2830,72 +2987,6 @@
2830
2987
  }
2831
2988
  }
2832
2989
 
2833
- /**
2834
- * Portal/Teleport System - Render content in different DOM location
2835
- * Useful for modals, tooltips, notifications that need to break out of parent containers
2836
- *
2837
- * @example
2838
- * // Portal to body (for modals)
2839
- * <div g-portal="body">
2840
- * <div class="modal">Modal content</div>
2841
- * </div>
2842
- *
2843
- * @example
2844
- * // Portal to specific element
2845
- * <div g-portal="#notifications">
2846
- * <div class="toast">Toast message</div>
2847
- * </div>
2848
- */
2849
- /**
2850
- * Create a portal - Move element to target location
2851
- *
2852
- * @param sourceEl - Element to teleport
2853
- * @param targetSelector - CSS selector for destination
2854
- *
2855
- * @example
2856
- * portalCreate(modalEl, 'body');
2857
- * portalCreate(tooltipEl, '#tooltip-container');
2858
- */
2859
- function portalCreate(sourceEl, targetSelector) {
2860
- if (!sourceEl)
2861
- return;
2862
- const target = document.querySelector(targetSelector);
2863
- if (!target) {
2864
- console.warn(`[GyosJS] Portal target "${targetSelector}" not found`);
2865
- return;
2866
- }
2867
- // Create placeholder comment to mark original position
2868
- const placeholder = document.createComment('g-portal');
2869
- sourceEl.parentNode?.insertBefore(placeholder, sourceEl);
2870
- // Store original parent for restoration
2871
- sourceEl.__portal_placeholder__ = placeholder;
2872
- sourceEl.__portal_target__ = target;
2873
- // Move the entire element to target
2874
- target.appendChild(sourceEl);
2875
- DEBUG() && console.log('[Portal] Created - moved element to', targetSelector);
2876
- }
2877
- /**
2878
- * Destroy a portal - Restore element to original position
2879
- *
2880
- * @param sourceEl - Element to restore
2881
- *
2882
- * @example
2883
- * portalDestroy(modalEl); // Returns modal to original location
2884
- */
2885
- function portalDestroy(sourceEl) {
2886
- if (!sourceEl)
2887
- return;
2888
- const placeholder = sourceEl.__portal_placeholder__;
2889
- if (placeholder && placeholder.parentNode) {
2890
- // Move element back to original position
2891
- placeholder.parentNode.insertBefore(sourceEl, placeholder);
2892
- placeholder.remove();
2893
- delete sourceEl.__portal_placeholder__;
2894
- delete sourceEl.__portal_target__;
2895
- DEBUG() && console.log('[Portal] Destroyed - restored element to original position');
2896
- }
2897
- }
2898
-
2899
2990
  /**
2900
2991
  * Validator registry
2901
2992
  */
@@ -3081,7 +3172,7 @@
3081
3172
  * @example "min(18)"
3082
3173
  */
3083
3174
  validator('min', (value, min) => {
3084
- if (!value)
3175
+ if (value == null || value === '')
3085
3176
  return true;
3086
3177
  const minVal = parseFloat(min);
3087
3178
  return parseFloat(value) >= minVal || `Minimum value is ${minVal}`;
@@ -3092,7 +3183,7 @@
3092
3183
  * @example "max(100)"
3093
3184
  */
3094
3185
  validator('max', (value, max) => {
3095
- if (!value)
3186
+ if (value == null || value === '')
3096
3187
  return true;
3097
3188
  const maxVal = parseFloat(max);
3098
3189
  return parseFloat(value) <= maxVal || `Maximum value is ${maxVal}`;
@@ -3113,9 +3204,9 @@
3113
3204
  * @example "integer"
3114
3205
  */
3115
3206
  validator('integer', (value) => {
3116
- if (!value)
3207
+ if (value == null || value === '')
3117
3208
  return true;
3118
- return Number.isInteger(parseFloat(value)) || 'Must be an integer';
3209
+ return (String(value).trim() !== '' && Number.isInteger(Number(value))) || 'Must be an integer';
3119
3210
  });
3120
3211
  /**
3121
3212
  * Numeric - Must contain only digits
@@ -3228,7 +3319,7 @@
3228
3319
  return 'Invalid date format (use YYYY-MM-DD)';
3229
3320
  }
3230
3321
  const date = new Date(value);
3231
- return !isNaN(date.getTime()) || 'Invalid date';
3322
+ return (!isNaN(date.getTime()) && date.toISOString().slice(0, 10) === value) || 'Invalid date';
3232
3323
  });
3233
3324
  /**
3234
3325
  * Before - Date must be before specified date
@@ -3308,7 +3399,7 @@
3308
3399
  * @example "between(18,65)"
3309
3400
  */
3310
3401
  validator('between', (value, min, max) => {
3311
- if (!value)
3402
+ if (value == null || value === '')
3312
3403
  return true;
3313
3404
  const num = parseFloat(value);
3314
3405
  const minVal = parseFloat(min);
@@ -3562,8 +3653,16 @@
3562
3653
  // Initialize error state - direct mutation
3563
3654
  state.errors.value[modelAttr] = null;
3564
3655
  state.touched.value[modelAttr] = false;
3565
- // Validation function
3566
- const validateField = async () => {
3656
+ let active = true;
3657
+ let generation = 0;
3658
+ let timeout;
3659
+ let latestValidation = Promise.resolve();
3660
+ // Each control publishes only its newest result. validateAll also waits for
3661
+ // a newer validation that superseded the request it originally started.
3662
+ const runValidation = async () => {
3663
+ if (!active)
3664
+ return;
3665
+ const request = ++generation;
3567
3666
  const value = getControlValue(el, form);
3568
3667
  // Get form context for validators that need it (like 'same')
3569
3668
  const formData = {};
@@ -3578,7 +3677,26 @@
3578
3677
  }
3579
3678
  }
3580
3679
  });
3581
- const error = await validate(value, rules, { form: formData, field: modelAttr });
3680
+ let error;
3681
+ try {
3682
+ error = await validate(value, rules, { form: formData, field: modelAttr });
3683
+ }
3684
+ catch (cause) {
3685
+ console.error('[GyosJS] Field validation failed:', cause);
3686
+ error = 'Validation failed. Please try again.';
3687
+ }
3688
+ if (!active)
3689
+ return;
3690
+ if (request !== generation) {
3691
+ await latestValidation;
3692
+ return;
3693
+ }
3694
+ // Input may have changed while its debounce timer has not fired yet.
3695
+ // A submit must validate the current value before publishing approval.
3696
+ if (value !== getControlValue(el, form)) {
3697
+ await validateField();
3698
+ return;
3699
+ }
3582
3700
  // Update errors - only if changed
3583
3701
  const currentErrors = state.errors.value;
3584
3702
  if (currentErrors[modelAttr] !== error) {
@@ -3588,6 +3706,12 @@
3588
3706
  updateFormState(state);
3589
3707
  }
3590
3708
  };
3709
+ const validateField = () => {
3710
+ clearTimeout(timeout);
3711
+ timeout = undefined;
3712
+ latestValidation = runValidation();
3713
+ return latestValidation;
3714
+ };
3591
3715
  // Register validator for validateAll
3592
3716
  if (!formValidators.has(form)) {
3593
3717
  formValidators.set(form, []);
@@ -3605,7 +3729,6 @@
3605
3729
  };
3606
3730
  el.addEventListener('blur', blurListener);
3607
3731
  // Validate on input (with debounce)
3608
- let timeout;
3609
3732
  const inputListener = () => {
3610
3733
  clearTimeout(timeout);
3611
3734
  timeout = setTimeout(() => {
@@ -3617,6 +3740,24 @@
3617
3740
  el.__gyos_effects__ = [];
3618
3741
  }
3619
3742
  el.__gyos_effects__.push(() => {
3743
+ active = false;
3744
+ generation++;
3745
+ delete el[validationFieldKey];
3746
+ const validators = formValidators.get(form);
3747
+ const index = validators?.indexOf(validateField) ?? -1;
3748
+ if (index !== -1)
3749
+ validators.splice(index, 1);
3750
+ const sharesField = Array.from(form.querySelectorAll('input, textarea, select'))
3751
+ .some(control => control[validationFieldKey] === modelAttr);
3752
+ if (!sharesField) {
3753
+ const errors = { ...state.errors.peek };
3754
+ delete errors[modelAttr];
3755
+ const touched = { ...state.touched.peek };
3756
+ delete touched[modelAttr];
3757
+ state.errors.value = errors;
3758
+ state.touched.value = touched;
3759
+ updateFormState(state);
3760
+ }
3620
3761
  el.removeEventListener('blur', blurListener);
3621
3762
  el.removeEventListener('input', inputListener);
3622
3763
  clearTimeout(timeout);
@@ -3689,7 +3830,9 @@
3689
3830
  processFormDirective(root, scope);
3690
3831
  }
3691
3832
  // Then process g-validate
3692
- root.querySelectorAll('[g-validate]').forEach(el => {
3833
+ [root, ...root.querySelectorAll('[g-validate]')].forEach(el => {
3834
+ if (!el.hasAttribute('g-validate'))
3835
+ return;
3693
3836
  if (isInIgnoredTree(el))
3694
3837
  return;
3695
3838
  if (el instanceof HTMLElement) {
@@ -3697,7 +3840,9 @@
3697
3840
  }
3698
3841
  });
3699
3842
  // Finally process g-errors
3700
- root.querySelectorAll('[g-errors]').forEach(el => {
3843
+ [root, ...root.querySelectorAll('[g-errors]')].forEach(el => {
3844
+ if (!el.hasAttribute('g-errors'))
3845
+ return;
3701
3846
  if (isInIgnoredTree(el))
3702
3847
  return;
3703
3848
  if (el instanceof HTMLElement) {
@@ -3728,12 +3873,13 @@
3728
3873
  /**
3729
3874
  * Execute handler with modifiers (prevent, stop)
3730
3875
  */
3731
- function executeHandler(handler, scope, e, modifiers) {
3732
- // Handle prevent/stop modifiers
3876
+ function applyEventModifiers(e, modifiers) {
3733
3877
  if (modifiers.includes('prevent'))
3734
3878
  e.preventDefault();
3735
3879
  if (modifiers.includes('stop'))
3736
3880
  e.stopPropagation();
3881
+ }
3882
+ function executeHandler(handler, scope, e) {
3737
3883
  try {
3738
3884
  expressionRuntime().execute(handler, scope, e);
3739
3885
  }
@@ -3823,10 +3969,11 @@
3823
3969
  if (target instanceof Element && target.closest('[g-ignore-outside-click]'))
3824
3970
  return;
3825
3971
  if (element !== target && !element.contains(target)) {
3972
+ applyEventModifiers(e, modifiers);
3826
3973
  const currentScope = getScopeFromElement(element) || scope;
3827
3974
  if (modifiers.includes('once'))
3828
3975
  cleanup();
3829
- executeHandler(handler, currentScope, e, modifiers);
3976
+ executeHandler(handler, currentScope, e);
3830
3977
  }
3831
3978
  };
3832
3979
  // Cleanup function
@@ -3903,13 +4050,14 @@
3903
4050
  return; // Key doesn't match, skip
3904
4051
  }
3905
4052
  // Execute handler with optional debounce
4053
+ applyEventModifiers(e, modifiers);
3906
4054
  const execute = () => {
3907
4055
  if (modifiers.includes('once'))
3908
4056
  cleanup();
3909
4057
  // Batch in case handler mutates multiple signals
3910
4058
  batch(() => {
3911
4059
  const currentScope = getScopeFromElement(element) || scope;
3912
- executeHandler(handler, currentScope, e, modifiers);
4060
+ executeHandler(handler, currentScope, e);
3913
4061
  });
3914
4062
  };
3915
4063
  if (debounceMs > 0) {
@@ -4159,60 +4307,6 @@
4159
4307
  element.removeAttribute(modelAttr.name);
4160
4308
  }
4161
4309
 
4162
- /**
4163
- * Cleanup utilities for disposing effects and event listeners
4164
- */
4165
- /**
4166
- * Dispose all effects attached to an element and its descendants
4167
- * Handles both element effects (__gyos_effects__) and component lifecycle
4168
- */
4169
- function disposeEffects(element = document.body, removeElement = false) {
4170
- if (!element)
4171
- return;
4172
- // Unmount scope if element has one (calls onUnmount + cleans instance.__gyos_effects__)
4173
- if (element.hasAttribute?.('g-scope') || element.__gyos_scope__) {
4174
- unmountScope(element);
4175
- }
4176
- // Dispose effects on this element (template effects like g-show, :class, {text})
4177
- if (element.__gyos_effects__) {
4178
- const effects = element.__gyos_effects__;
4179
- effects.forEach((dispose) => {
4180
- try {
4181
- dispose();
4182
- }
4183
- catch (error) {
4184
- console.error('[GyosJS] Error disposing effect:', error);
4185
- }
4186
- });
4187
- element.__gyos_effects__ = null;
4188
- }
4189
- // Recursively dispose effects on all descendants
4190
- const descendants = element.querySelectorAll('*');
4191
- descendants.forEach((child) => {
4192
- // Unmount child scopes
4193
- if (child.hasAttribute?.('g-scope') || child.__gyos_scope__) {
4194
- unmountScope(child);
4195
- }
4196
- // Dispose child template effects
4197
- if (child.__gyos_effects__) {
4198
- const effects = child.__gyos_effects__;
4199
- effects.forEach((dispose) => {
4200
- try {
4201
- dispose();
4202
- }
4203
- catch (error) {
4204
- console.error('[GyosJS] Error disposing child effect:', error);
4205
- }
4206
- });
4207
- child.__gyos_effects__ = null;
4208
- }
4209
- });
4210
- // portal cleanup could be added here if needed
4211
- portalDestroy(element);
4212
- if (removeElement)
4213
- element.remove();
4214
- }
4215
-
4216
4310
  const storeCache = new WeakMap();
4217
4311
  const reactiveProxies = new WeakSet();
4218
4312
  const fieldSignals = new WeakMap();
@@ -4227,7 +4321,7 @@
4227
4321
  if (visited.has(ver))
4228
4322
  return;
4229
4323
  visited.add(ver);
4230
- ver.value = ver.value + 1;
4324
+ ver.update(value => value + 1);
4231
4325
  const parents = versionParents.get(ver);
4232
4326
  if (parents) {
4233
4327
  parents.forEach(parentVer => bumpSignal(parentVer));
@@ -4265,7 +4359,7 @@
4265
4359
  }
4266
4360
  const STORE_MARKER = Symbol.for('gyos.store');
4267
4361
  function markStore(obj) {
4268
- if (obj.hasOwnProperty(STORE_MARKER))
4362
+ if (Object.prototype.hasOwnProperty.call(obj, STORE_MARKER))
4269
4363
  return obj;
4270
4364
  Reflect.defineProperty(obj, STORE_MARKER, {
4271
4365
  value: true,
@@ -4279,7 +4373,7 @@
4279
4373
  // markRaw: đánh dấu object để reactive() bỏ qua, không tạo proxy
4280
4374
  const RAW_MARKER = Symbol.for('gyos.raw');
4281
4375
  function markRaw(obj) {
4282
- if (obj.hasOwnProperty(RAW_MARKER))
4376
+ if (Object.prototype.hasOwnProperty.call(obj, RAW_MARKER))
4283
4377
  return obj;
4284
4378
  Reflect.defineProperty(obj, RAW_MARKER, {
4285
4379
  value: true,
@@ -4293,7 +4387,7 @@
4293
4387
  // shallow: chỉ reactive "lớp ngoài", không reactive sâu bên trong
4294
4388
  const SHALLOW_MARKER = Symbol.for('gyos.shallow');
4295
4389
  function shallow(obj) {
4296
- if (obj.hasOwnProperty(SHALLOW_MARKER))
4390
+ if (Object.prototype.hasOwnProperty.call(obj, SHALLOW_MARKER))
4297
4391
  return obj;
4298
4392
  Reflect.defineProperty(obj, SHALLOW_MARKER, {
4299
4393
  value: true,
@@ -4327,6 +4421,25 @@
4327
4421
  }
4328
4422
  versionParentsSet.add(parentVersion);
4329
4423
  }
4424
+ // Array [[DefineOwnProperty]] can change length or remove indices without
4425
+ // entering their individual Proxy traps. Keep already observed fields current.
4426
+ function syncArrayFields(target, previousLength) {
4427
+ if (previousLength === undefined)
4428
+ return;
4429
+ const array = target;
4430
+ if (array.length === previousLength)
4431
+ return;
4432
+ const signals = fieldSignals.get(target);
4433
+ signals?.get('length')?.update(() => array.length);
4434
+ if (array.length < previousLength) {
4435
+ signals?.forEach((sig, key) => {
4436
+ if (typeof key === 'string' && /^(0|[1-9]\d*)$/.test(key)
4437
+ && Number(key) >= array.length && Number(key) < previousLength) {
4438
+ sig.update(() => Reflect.get(target, key));
4439
+ }
4440
+ });
4441
+ }
4442
+ }
4330
4443
  function reactive(raw) {
4331
4444
  if (!raw || typeof raw !== "object" || isBuiltInObject(raw)) {
4332
4445
  return raw;
@@ -4364,6 +4477,8 @@
4364
4477
  return value;
4365
4478
  }
4366
4479
  if (isStoreObject(value)) {
4480
+ if (hasCurrentEffect())
4481
+ getFieldSignal(target, key, value).value;
4367
4482
  return value;
4368
4483
  }
4369
4484
  // Check if this is a getter property (computed property)
@@ -4440,10 +4555,6 @@
4440
4555
  }
4441
4556
  // capture old value BEFORE write to detect real changes
4442
4557
  const oldValue = target[key];
4443
- // VALUE LÀ STORE → set thẳng, KHÔNG tạo signal, KHÔNG trigger
4444
- if (isStoreObject(value)) {
4445
- return Reflect.set(target, key, value, receiver);
4446
- }
4447
4558
  const ok = Reflect.set(target, key, value, receiver);
4448
4559
  if (!ok)
4449
4560
  return false;
@@ -4485,7 +4596,9 @@
4485
4596
  const oldDesc = Object.getOwnPropertyDescriptor(target, key);
4486
4597
  const oldValue = oldDesc && "value" in oldDesc ? oldDesc.value : undefined;
4487
4598
  const newValue = "value" in descriptor ? descriptor.value : oldValue;
4599
+ const previousLength = Array.isArray(target) ? target.length : undefined;
4488
4600
  const ok = Reflect.defineProperty(target, key, descriptor);
4601
+ syncArrayFields(target, previousLength);
4489
4602
  if (!ok)
4490
4603
  return false;
4491
4604
  if ('value' in descriptor) {
@@ -4511,7 +4624,7 @@
4511
4624
  // tạo 1 version signal cho root scope
4512
4625
  const version = ensureVersion(source);
4513
4626
  const proxy = reactive(source);
4514
- if (!proxy.hasOwnProperty(SCOPE_VERSION)) {
4627
+ if (!Object.prototype.hasOwnProperty.call(proxy, SCOPE_VERSION)) {
4515
4628
  Object.defineProperty(proxy, SCOPE_VERSION, {
4516
4629
  value: version,
4517
4630
  enumerable: false,
@@ -4633,6 +4746,20 @@
4633
4746
  function setRootScope(element, scope) {
4634
4747
  element.__gyos_scope__ = scope;
4635
4748
  }
4749
+ function inheritScope(child, parent) {
4750
+ attachParentScope(child, parent);
4751
+ for (const key in parent) {
4752
+ if (!(key in child)) {
4753
+ Object.defineProperty(child, key, {
4754
+ get: () => parent[key],
4755
+ set: value => { parent[key] = value; },
4756
+ enumerable: true,
4757
+ configurable: true,
4758
+ });
4759
+ }
4760
+ }
4761
+ return child;
4762
+ }
4636
4763
  /**
4637
4764
  * Create child scope for *for loops
4638
4765
  * Inherits parent scope properties via getters
@@ -4703,13 +4830,15 @@
4703
4830
  template.removeAttribute('g-key');
4704
4831
  const placeholder = document.createComment('*for');
4705
4832
  element.parentNode?.replaceChild(placeholder, element);
4833
+ const end = document.createComment('/*for');
4834
+ placeholder.parentNode?.insertBefore(end, placeholder.nextSibling);
4706
4835
  // Store previous items for key-based diffing
4707
4836
  // WARNING: Use primitive keys (id, string, number) to avoid memory leaks
4708
4837
  // Object keys will prevent garbage collection
4709
4838
  let prevItemsMap = new Map();
4710
4839
  let prevListRef = null;
4711
4840
  let prevVersionValue = undefined;
4712
- queueReactiveEffect(element, () => {
4841
+ queueReactiveEffect(placeholder, () => {
4713
4842
  // Parse: "item in items" or "item, index in items"
4714
4843
  const match = expr.match(/(.+?)\s+in\s+(.+)/);
4715
4844
  if (!match)
@@ -4736,7 +4865,7 @@
4736
4865
  }
4737
4866
  else {
4738
4867
  // Simple re-render (no diffing)
4739
- processForSimple(placeholder, template, list, itemVar, currentScope);
4868
+ processForSimple(placeholder, end, template, list, itemVar, currentScope);
4740
4869
  }
4741
4870
  });
4742
4871
  });
@@ -4843,16 +4972,19 @@
4843
4972
  /**
4844
4973
  * Process *for without keys (simple re-render)
4845
4974
  */
4846
- function processForSimple(placeholder, template, list, itemVar, currentScope) {
4975
+ function processForSimple(placeholder, end, template, list, itemVar, currentScope) {
4847
4976
  // Remove all existing items
4848
4977
  let next = placeholder.nextSibling;
4849
- while (next && next.nodeType !== Node.COMMENT_NODE) {
4978
+ while (next && next !== end) {
4850
4979
  const toRemove = next;
4851
4980
  next = next.nextSibling;
4852
4981
  if (toRemove instanceof Element) {
4853
4982
  unmountChildScopes(toRemove);
4854
4983
  disposeEffects(toRemove, true);
4855
4984
  }
4985
+ else {
4986
+ disposeNode(toRemove, true);
4987
+ }
4856
4988
  }
4857
4989
  // Render new items
4858
4990
  // Track last inserted node to maintain order
@@ -4945,7 +5077,7 @@
4945
5077
  element.parentNode?.replaceChild(placeholder, element);
4946
5078
  let currentElement = null;
4947
5079
  let currentIndex = -1;
4948
- queueReactiveEffect(element, () => {
5080
+ queueReactiveEffect(placeholder, () => {
4949
5081
  // Find first truthy condition
4950
5082
  let matchedIndex = -1;
4951
5083
  for (let i = 0; i < templates.length; i++) {
@@ -5071,14 +5203,13 @@
5071
5203
  const switchValue = evaluateExpression(switchExpr, currentScope, false);
5072
5204
  // Find matching case
5073
5205
  let matchedIndex = -1;
5206
+ let defaultIndex = -1;
5074
5207
  for (let i = 0; i < templates.length; i++) {
5075
5208
  const { value } = templates[i];
5076
5209
  if (value === null) {
5077
- // *default matches (only if no other case matched)
5078
- if (matchedIndex === -1) {
5079
- matchedIndex = i;
5080
- }
5081
- break;
5210
+ if (defaultIndex === -1)
5211
+ defaultIndex = i;
5212
+ continue;
5082
5213
  }
5083
5214
  const caseValue = evaluateExpression(value, currentScope, false);
5084
5215
  if (switchValue === caseValue) {
@@ -5086,6 +5217,8 @@
5086
5217
  break;
5087
5218
  }
5088
5219
  }
5220
+ if (matchedIndex === -1)
5221
+ matchedIndex = defaultIndex;
5089
5222
  // If same case, do nothing
5090
5223
  if (matchedIndex === currentIndex)
5091
5224
  return;
@@ -5204,6 +5337,7 @@
5204
5337
  let requestVersion = 0;
5205
5338
  // Helper to render state
5206
5339
  const renderState = (state, data) => {
5340
+ currentState = state;
5207
5341
  // Remove old element
5208
5342
  if (currentElement) {
5209
5343
  const elemToRemove = currentElement;
@@ -5229,20 +5363,19 @@
5229
5363
  else if (state === 'fulfilled' && thenTemplate) {
5230
5364
  template = thenTemplate.template;
5231
5365
  // Create child scope with data if varName provided
5232
- if (thenTemplate.varName && data !== undefined) {
5233
- scope = { ...currentScope, [thenTemplate.varName]: data };
5366
+ if (thenTemplate.varName) {
5367
+ scope = inheritScope({ [thenTemplate.varName]: data }, currentScope);
5234
5368
  }
5235
5369
  }
5236
5370
  else if (state === 'rejected' && catchTemplate) {
5237
5371
  template = catchTemplate.template;
5238
5372
  // Create child scope with error if varName provided
5239
- if (catchTemplate.varName && data !== undefined) {
5240
- scope = { ...currentScope, [catchTemplate.varName]: data };
5373
+ if (catchTemplate.varName) {
5374
+ scope = inheritScope({ [catchTemplate.varName]: data }, currentScope);
5241
5375
  }
5242
5376
  }
5243
5377
  if (template) {
5244
5378
  currentElement = getCachedTemplate(template);
5245
- currentState = state;
5246
5379
  setRootScope(currentElement, scope);
5247
5380
  // Apply transition initial state
5248
5381
  const elementsWithTransition = findElementsWithTransition(currentElement);
@@ -5270,8 +5403,6 @@
5270
5403
  }
5271
5404
  }
5272
5405
  };
5273
- // Initial state: pending
5274
- renderState('pending');
5275
5406
  // Track promise expression
5276
5407
  queueReactiveEffect(element, () => {
5277
5408
  const promiseOrValue = evaluateExpression(awaitExpr, currentScope, false);
@@ -5295,6 +5426,8 @@
5295
5426
  renderState('rejected', error);
5296
5427
  }
5297
5428
  });
5429
+ // Both reruns and disposal invalidate callbacks from this request.
5430
+ return () => { requestVersion++; };
5298
5431
  });
5299
5432
  }
5300
5433
 
@@ -5362,6 +5495,9 @@
5362
5495
  structuralElements.sort((a, b) => a.depth - b.depth);
5363
5496
  // Process each structural directive
5364
5497
  structuralElements.forEach(({ element, type }) => {
5498
+ // Parent directives parse their clones, not the detached original tree.
5499
+ if (!root.contains(element) || elementBelongsToAnotherScope(element, scope))
5500
+ return;
5365
5501
  if (type === 'for') {
5366
5502
  processForDirective(element, scope);
5367
5503
  }
@@ -5397,6 +5533,10 @@
5397
5533
  function processParse(element, scope, fromStructural = false) {
5398
5534
  if (isInIgnoredTree(element))
5399
5535
  return;
5536
+ if (fromStructural && element.hasAttribute('g-scope') && mountFunction) {
5537
+ mountFunction(element);
5538
+ return;
5539
+ }
5400
5540
  beginEffectCollection();
5401
5541
  const allElements = [
5402
5542
  element,
@@ -5418,7 +5558,7 @@
5418
5558
  return;
5419
5559
  if (el.attributes.length === 0)
5420
5560
  return; // Skip if no attributes
5421
- if (elementBelongsToAnotherScope(el, scope) && !fromStructural) {
5561
+ if (elementBelongsToAnotherScope(el, scope)) {
5422
5562
  // (fromStructural allows processing newly created elements inside structurals)
5423
5563
  return; // Skip if inside mounted scope
5424
5564
  }
@@ -5426,8 +5566,9 @@
5426
5566
  if (el.hasAttribute('g-static')) {
5427
5567
  // Pre-process g-static elements (mark and render them before reactive processing)
5428
5568
  processStaticElements(el, scope);
5569
+ return;
5429
5570
  }
5430
- if (el.hasAttribute('g-form')) {
5571
+ if (el.hasAttribute('g-form') || el.hasAttribute('g-validate') || el.hasAttribute('g-errors')) {
5431
5572
  // Process form validation (g-form, g-validate, g-errors)
5432
5573
  processFormValidation(el, scope);
5433
5574
  }
@@ -5777,7 +5918,7 @@
5777
5918
  const allElements = [...elements, ...elementsNotScope].filter(el => !isInIgnoredTree(el));
5778
5919
  allElements.sort((a, b) => getDepth(b) - getDepth(a));
5779
5920
  // Filter out elements inside structural directives - they will be mounted by structural processor
5780
- allElements.forEach(el => !hasStructuralParent(el) && mount(el));
5921
+ allElements.forEach(el => !el.hasAttribute('*if') && !el.hasAttribute('*for') && !hasStructuralParent(el) && mount(el));
5781
5922
  diagnoseUnscopedReveals(document.body);
5782
5923
  }
5783
5924
  function mountTree(el) {
@@ -5788,7 +5929,7 @@
5788
5929
  .filter(element => element.hasAttribute('g-scope') || hasAutoScope(element));
5789
5930
  // Child scopes own their subtree before an existing parent scope parses the insertion.
5790
5931
  candidates.sort((a, b) => getDepth(b) - getDepth(a));
5791
- candidates.forEach(element => !hasStructuralParent(element) && mount(element));
5932
+ candidates.forEach(element => !element.hasAttribute('*if') && !element.hasAttribute('*for') && !hasStructuralParent(element) && mount(element));
5792
5933
  diagnoseUnscopedReveals(el);
5793
5934
  if (getMountedScope(el))
5794
5935
  return;
@@ -5817,9 +5958,17 @@
5817
5958
  /**
5818
5959
  * Parse inline scope definition from HTML attribute
5819
5960
  */
5961
+ function decodeMarkupExpression(value) {
5962
+ try {
5963
+ return decodeURIComponent(value);
5964
+ }
5965
+ catch {
5966
+ return value;
5967
+ } // Plain expressions may contain a literal % or modulo.
5968
+ }
5820
5969
  function parseInlineScope(scopeStr) {
5821
5970
  // If scopeStr is encode urld, decode it first
5822
- scopeStr = decodeURIComponent(scopeStr);
5971
+ scopeStr = decodeMarkupExpression(scopeStr);
5823
5972
  try {
5824
5973
  // Check if it's an inline object definition (starts with '{')
5825
5974
  const trimmed = scopeStr.trim();
@@ -5886,7 +6035,7 @@
5886
6035
  // gm-method-name:args:arg2="expression"
5887
6036
  if (attr.name.match(/^gm-.+/)) {
5888
6037
  // If expr is encoded url, decode it first
5889
- const expr = decodeURIComponent(attr.value.trim());
6038
+ const expr = decodeMarkupExpression(attr.value.trim());
5890
6039
  if (forbidden.some(f => expr.includes(f))) {
5891
6040
  DEBUG() && console.log("[GyosJS] Scope mount error: Forbidden expression:", expr);
5892
6041
  }
@@ -5997,15 +6146,11 @@
5997
6146
  * Mount a specific scope
5998
6147
  */
5999
6148
  function mountScope(el, scopeAttr) {
6000
- const definition = handleDefinition(el, scopeAttr);
6001
6149
  // Check if already mounted
6002
6150
  if (getMountedScope(el)) {
6003
6151
  return;
6004
6152
  }
6005
- // Check if element is static (no reactivity)
6006
- if (el.hasAttribute('g-static')) {
6007
- return;
6008
- }
6153
+ const definition = handleDefinition(el, scopeAttr);
6009
6154
  // Check hydration strategy
6010
6155
  const hydrationStrategy = getHydrationStrategy(el);
6011
6156
  if (hydrationStrategy) {
@@ -6028,8 +6173,9 @@
6028
6173
  if (typeof definition === 'object') {
6029
6174
  instance = makeReactive(definition);
6030
6175
  }
6031
- // Create component context (needs instance for $watch)
6032
- const context = createContext(el, instance);
6176
+ // Factories receive context before their reactive instance exists. Resolve it
6177
+ // when an observer is registered so captured context also works in onMount.
6178
+ const context = createContext(el, () => instance);
6033
6179
  // If function component, call it now with context
6034
6180
  if (typeof definition === 'function' && !instance) {
6035
6181
  const factoryResult = definition(context);
@@ -6069,13 +6215,21 @@
6069
6215
  // Parse and bind template (portals will be processed inside *if)
6070
6216
  // Pass onMount callback to be called after parsing (or after hydration triggers)
6071
6217
  parseTemplate(el, instance, () => {
6218
+ // The hook may inspect or clean up its own mount. Register before calling
6219
+ // user code, and do not register again if the hook disposes the scope.
6220
+ registerMountedScope(el, instance);
6072
6221
  // Call lifecycle hook after template is parsed
6073
6222
  if (instance.onMount) {
6074
- Promise.resolve(instance.onMount.call(instance)).catch(console.error);
6223
+ try {
6224
+ Promise.resolve(instance.onMount.call(instance)).catch(console.error);
6225
+ }
6226
+ catch (error) {
6227
+ console.error('[Component] Error in onMount:', error);
6228
+ }
6075
6229
  }
6076
6230
  });
6077
- // Store instance
6078
- registerMountedScope(el, instance);
6231
+ if (getMountedScope(el) !== instance)
6232
+ return;
6079
6233
  // Cache instance if g-scope-persist is set (with interpolation support)
6080
6234
  getPersistKey$1(el, persistKey => {
6081
6235
  if (!scopeCached.has(persistKey)) {
@@ -6086,12 +6240,12 @@
6086
6240
  /**
6087
6241
  * Create component context
6088
6242
  */
6089
- function createContext(el, instance) {
6243
+ function createContext(el, getInstance) {
6090
6244
  const refs = {};
6091
6245
  const events = new Map();
6092
6246
  // Find all refs within this scope only
6093
6247
  el.querySelectorAll('[g-ref]').forEach(refEl => {
6094
- if (isInIgnoredTree(refEl))
6248
+ if (isInIgnoredTree(refEl) || (refEl.closest('[g-scope]') || el) !== el)
6095
6249
  return;
6096
6250
  const refName = refEl.getAttribute('g-ref');
6097
6251
  if (refName && !hasUnsafePropertyPath(refName)) {
@@ -6134,19 +6288,23 @@
6134
6288
  },
6135
6289
  $watch: (key, handler, options = {}) => {
6136
6290
  // Watch a reactive property for changes (supports nested paths like 'xxx.count')
6291
+ const instance = getInstance();
6137
6292
  if (!instance) {
6138
6293
  DEBUG() && console.warn('[Component] $watch called before instance created');
6139
6294
  return () => { };
6140
6295
  }
6141
6296
  const { immediate = false, deep = false, debounce = 0 } = options;
6142
6297
  let timeoutId;
6298
+ let active = true;
6143
6299
  if (debounce > 0) {
6144
6300
  // Wrap handler with debounce
6145
6301
  const originalHandler = handler;
6146
6302
  handler = (...args) => {
6147
6303
  clearTimeout(timeoutId);
6148
6304
  timeoutId = setTimeout(() => {
6149
- originalHandler(...args);
6305
+ timeoutId = undefined;
6306
+ if (active)
6307
+ untrack(() => originalHandler.call(instance, ...args));
6150
6308
  }, debounce);
6151
6309
  };
6152
6310
  }
@@ -6175,31 +6333,38 @@
6175
6333
  initialized = true;
6176
6334
  // Call immediately if requested
6177
6335
  if (immediate) {
6178
- handler.call(instance, clonedValue, undefined);
6336
+ untrack(() => handler.call(instance, clonedValue, undefined));
6179
6337
  }
6180
6338
  return;
6181
6339
  }
6182
6340
  // Check if value actually changed
6183
6341
  const changed = deep
6184
6342
  ? !deepEqual(oldValue, clonedValue)
6185
- : oldValue !== clonedValue;
6343
+ : !Object.is(oldValue, clonedValue);
6186
6344
  if (changed) {
6187
- handler.call(instance, clonedValue, oldValue);
6345
+ untrack(() => handler.call(instance, clonedValue, oldValue));
6188
6346
  oldValue = deep && typeof clonedValue === 'object'
6189
6347
  ? clone(clonedValue)
6190
6348
  : clonedValue;
6191
6349
  }
6192
6350
  });
6351
+ const stopWatching = () => {
6352
+ active = false;
6353
+ clearTimeout(timeoutId);
6354
+ timeoutId = undefined;
6355
+ watchEffect();
6356
+ };
6193
6357
  // Store cleanup for unmount
6194
6358
  if (!instance.__gyos_effects__) {
6195
6359
  instance.__gyos_effects__ = [];
6196
6360
  }
6197
- instance.__gyos_effects__.push(watchEffect);
6361
+ instance.__gyos_effects__.push(stopWatching);
6198
6362
  // Return unwatch function
6199
- return watchEffect;
6363
+ return stopWatching;
6200
6364
  },
6201
6365
  $effect: (fn) => {
6202
6366
  // Shorthand for effect with auto cleanup on unmount
6367
+ const instance = getInstance();
6203
6368
  if (!instance) {
6204
6369
  DEBUG() && console.warn('[Component] $effect called before instance created');
6205
6370
  return () => { };
@@ -6403,8 +6568,8 @@
6403
6568
  */
6404
6569
  function once(event, handler) {
6405
6570
  const wrapper = (...args) => {
6406
- handler(...args);
6407
6571
  off(event, wrapper);
6572
+ handler(...args);
6408
6573
  };
6409
6574
  return on(event, wrapper);
6410
6575
  }
@@ -6442,23 +6607,34 @@
6442
6607
  const data = signal(null);
6443
6608
  const loading = signal(true);
6444
6609
  const error = signal(null);
6610
+ let generation = 0;
6611
+ let active = true;
6445
6612
  const fetchData = async () => {
6613
+ if (!active)
6614
+ return;
6615
+ const requestId = ++generation;
6446
6616
  loading.value = true;
6447
6617
  error.value = null;
6448
6618
  data.value = null;
6449
6619
  try {
6450
6620
  const request = typeof url === 'function' ? await url() : url;
6621
+ if (requestId !== generation)
6622
+ return;
6451
6623
  const response = typeof request === 'string' ? await fetch(request) : request;
6452
6624
  if (!response.ok) {
6453
6625
  throw new Error(`HTTP error! status: ${response.status}`);
6454
6626
  }
6455
- data.value = await response.json();
6627
+ const result = await response.json();
6628
+ if (requestId === generation)
6629
+ data.value = result;
6456
6630
  }
6457
6631
  catch (e) {
6458
- error.value = e;
6632
+ if (requestId === generation)
6633
+ error.value = e;
6459
6634
  }
6460
6635
  finally {
6461
- loading.value = false;
6636
+ if (requestId === generation)
6637
+ loading.value = false;
6462
6638
  }
6463
6639
  };
6464
6640
  return {
@@ -6466,7 +6642,8 @@
6466
6642
  loading,
6467
6643
  error,
6468
6644
  refetch: fetchData,
6469
- onMount: fetchData
6645
+ onMount: () => { active = true; return fetchData(); },
6646
+ onUnmount: () => { active = false; generation++; loading.value = false; }
6470
6647
  };
6471
6648
  }
6472
6649
  /**
@@ -6724,17 +6901,26 @@
6724
6901
  const data = signal(null);
6725
6902
  const loading = signal(false);
6726
6903
  const error = signal(null);
6904
+ let generation = 0;
6905
+ let active = true;
6727
6906
  const execute = async () => {
6907
+ if (!active)
6908
+ return;
6909
+ const requestId = ++generation;
6728
6910
  loading.value = true;
6729
6911
  error.value = null;
6730
6912
  try {
6731
- data.value = await asyncFn();
6913
+ const result = await asyncFn();
6914
+ if (requestId === generation)
6915
+ data.value = result;
6732
6916
  }
6733
6917
  catch (e) {
6734
- error.value = e;
6918
+ if (requestId === generation)
6919
+ error.value = e;
6735
6920
  }
6736
6921
  finally {
6737
- loading.value = false;
6922
+ if (requestId === generation)
6923
+ loading.value = false;
6738
6924
  }
6739
6925
  };
6740
6926
  return {
@@ -6743,9 +6929,10 @@
6743
6929
  error,
6744
6930
  execute,
6745
6931
  onMount: () => {
6746
- if (immediate)
6747
- execute();
6748
- }
6932
+ active = true;
6933
+ return immediate ? execute() : undefined;
6934
+ },
6935
+ onUnmount: () => { active = false; generation++; loading.value = false; }
6749
6936
  };
6750
6937
  }
6751
6938
 
@@ -7233,7 +7420,10 @@
7233
7420
  Array.from(source.attributes).forEach(attribute => {
7234
7421
  sourceAttributes.add(attribute.name);
7235
7422
  if (target.getAttribute(attribute.name) !== attribute.value) {
7236
- target.setAttribute(attribute.name, attribute.value);
7423
+ // HTML permits directive names such as @click and *if, while older
7424
+ // DOM implementations apply XML name validation in setAttribute.
7425
+ // Transfer the already-parsed Attr without validating its name again.
7426
+ target.setAttributeNodeNS(target.ownerDocument.importNode(attribute, true));
7237
7427
  }
7238
7428
  });
7239
7429
  Array.from(target.attributes).forEach(attribute => {
@@ -7517,7 +7707,14 @@
7517
7707
  // Hash scrolling
7518
7708
  const hash = new URL(url).hash;
7519
7709
  if (hash) {
7520
- const el = document.querySelector(hash);
7710
+ // A URL fragment identifies an id, not a CSS selector. Numeric ids,
7711
+ // punctuation and percent-encoded Unicode must work without escaping.
7712
+ let id = hash.slice(1);
7713
+ try {
7714
+ id = decodeURIComponent(id);
7715
+ }
7716
+ catch { /* Keep malformed fragments literal. */ }
7717
+ const el = document.getElementById(id);
7521
7718
  if (el) {
7522
7719
  el.scrollIntoView({ behavior: 'smooth' });
7523
7720
  return;
@@ -8097,6 +8294,12 @@
8097
8294
  return fragment?.cloneNode(true);
8098
8295
  }
8099
8296
  function cloneHistoryTarget(target) {
8297
+ // Mounted templates have already consumed event/model attributes and text
8298
+ // expressions. A DOM clone cannot recreate their observers. Restore these
8299
+ // targets from response HTML (snapshot or fetch) instead of caching inert UI.
8300
+ if (getScopeFromElement(target) || Array.from(target.querySelectorAll('*'))
8301
+ .some(element => element.__gyos_scope__))
8302
+ return null;
8100
8303
  const clone = target.cloneNode(true);
8101
8304
  clone.querySelectorAll('.gyos-target-spinner').forEach(spinner => spinner.remove());
8102
8305
  return clone;
@@ -8954,7 +9157,7 @@
8954
9157
  portalCreate,
8955
9158
  portalDestroy,
8956
9159
  setCspNonce,
8957
- version: '0.5.2'
9160
+ version: '0.5.4'
8958
9161
  };
8959
9162
 
8960
9163
  // This file was generated. Do not modify manually!
@@ -15368,30 +15571,30 @@
15368
15571
  throw cspError('Invalid assignment target', expression, node);
15369
15572
  }
15370
15573
  function evaluateCall(node, context, expression) {
15371
- const args = node.arguments.map((argument) => {
15372
- if (argument.type === 'SpreadElement')
15373
- throw cspError('Spread arguments are not supported', expression, argument);
15374
- return evaluateNode(argument, context, expression);
15375
- });
15574
+ let receiver = context.scope;
15575
+ let callable;
15376
15576
  if (node.callee.type === 'MemberExpression') {
15377
15577
  const [object, property] = memberParts(node.callee, context, expression);
15378
15578
  if (object === optionalChainMiss)
15379
15579
  return optionalChainMiss;
15380
- const method = object[property];
15381
- if (method == null && node.optional)
15382
- return optionalChainMiss;
15383
- if (typeof method !== 'function')
15384
- throw cspError('Called value is not a function', expression, node.callee);
15385
- return method.apply(object, args);
15580
+ receiver = object;
15581
+ callable = object[property];
15582
+ }
15583
+ else {
15584
+ callable = evaluateNode(node.callee, context, expression);
15386
15585
  }
15387
- const callable = evaluateNode(node.callee, context, expression);
15388
15586
  if (callable === optionalChainMiss)
15389
15587
  return optionalChainMiss;
15390
15588
  if (callable == null && node.optional)
15391
15589
  return optionalChainMiss;
15590
+ const args = node.arguments.map((argument) => {
15591
+ if (argument.type === 'SpreadElement')
15592
+ throw cspError('Spread arguments are not supported', expression, argument);
15593
+ return evaluateNode(argument, context, expression);
15594
+ });
15392
15595
  if (typeof callable !== 'function')
15393
15596
  throw cspError('Called value is not a function', expression, node.callee);
15394
- return callable.apply(context.scope, args);
15597
+ return callable.apply(receiver, args);
15395
15598
  }
15396
15599
  function applyAssignment(operator, current, value, expression, node) {
15397
15600
  switch (operator) {
@@ -15514,10 +15717,10 @@
15514
15717
  }
15515
15718
  case 'UpdateExpression': {
15516
15719
  const reference = resolveReference(node.argument, context, expression);
15517
- const current = reference.get();
15518
- const next = node.operator === '++' ? current + 1 : current - 1;
15720
+ let next = reference.get();
15721
+ const previous = node.operator === '++' ? next++ : next--;
15519
15722
  reference.set(next);
15520
- return node.prefix ? next : current;
15723
+ return node.prefix ? next : previous;
15521
15724
  }
15522
15725
  case 'SequenceExpression': {
15523
15726
  let value;