gyosjs 0.2.2 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/gyos.esm.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * GyosJS v0.2.2
2
+ * GyosJS v0.2.3
3
3
  * (c) 2026
4
4
  * @license MIT
5
5
  */
@@ -1578,6 +1578,162 @@ function processTextNodesStatic(el, scope) {
1578
1578
  });
1579
1579
  }
1580
1580
 
1581
+ const DEFAULT_OPTIONS = {
1582
+ classNames: ['is-revealed'],
1583
+ rootMargin: '0px',
1584
+ threshold: 0.1
1585
+ };
1586
+ const pools = new Map();
1587
+ const mountedRecords = new WeakMap();
1588
+ function clampThreshold(value) {
1589
+ const number = Number(value);
1590
+ if (!Number.isFinite(number))
1591
+ return DEFAULT_OPTIONS.threshold;
1592
+ return Math.min(1, Math.max(0, number));
1593
+ }
1594
+ function normalizeThreshold(value) {
1595
+ if (!Array.isArray(value))
1596
+ return clampThreshold(value);
1597
+ const values = Array.from(new Set(value.map(clampThreshold))).sort((a, b) => a - b);
1598
+ return values.length ? values : DEFAULT_OPTIONS.threshold;
1599
+ }
1600
+ function normalizeOptions(binding) {
1601
+ const value = binding.value && typeof binding.value === 'object' && !Array.isArray(binding.value)
1602
+ ? binding.value
1603
+ : {};
1604
+ const args = new Set(binding.arg || []);
1605
+ const classNames = typeof value.className === 'string'
1606
+ ? value.className.split(/\s+/).filter(Boolean)
1607
+ : DEFAULT_OPTIONS.classNames;
1608
+ return {
1609
+ classNames,
1610
+ once: typeof value.once === 'boolean' ? value.once : !args.has('repeat'),
1611
+ rootMargin: typeof value.rootMargin === 'string' ? value.rootMargin : DEFAULT_OPTIONS.rootMargin,
1612
+ target: value.target === 'parent' || args.has('parent') ? 'parent' : 'self',
1613
+ threshold: normalizeThreshold(value.threshold ?? DEFAULT_OPTIONS.threshold)
1614
+ };
1615
+ }
1616
+ function poolKey(options) {
1617
+ return JSON.stringify([options.rootMargin, options.threshold]);
1618
+ }
1619
+ function setRevealed(record, revealed) {
1620
+ const { element, options } = record;
1621
+ if (revealed) {
1622
+ element.setAttribute('data-gyos-revealed', '');
1623
+ for (const className of options.classNames)
1624
+ element.classList.add(className);
1625
+ }
1626
+ else {
1627
+ element.removeAttribute('data-gyos-revealed');
1628
+ for (const className of options.classNames)
1629
+ element.classList.remove(className);
1630
+ }
1631
+ }
1632
+ function removeRecord(record) {
1633
+ if (mountedRecords.get(record.element) !== record)
1634
+ return;
1635
+ mountedRecords.delete(record.element);
1636
+ const records = record.pool.records.get(record.observedTarget);
1637
+ if (records) {
1638
+ records.delete(record);
1639
+ if (records.size === 0) {
1640
+ record.pool.records.delete(record.observedTarget);
1641
+ record.pool.observer.unobserve(record.observedTarget);
1642
+ }
1643
+ }
1644
+ if (record.pool.records.size === 0) {
1645
+ record.pool.observer.disconnect();
1646
+ pools.delete(record.pool.key);
1647
+ }
1648
+ }
1649
+ function createPool(options) {
1650
+ const key = poolKey(options);
1651
+ const existing = pools.get(key);
1652
+ if (existing)
1653
+ return existing;
1654
+ let pool;
1655
+ try {
1656
+ const records = new Map();
1657
+ const observer = new IntersectionObserver(entries => {
1658
+ for (const entry of entries) {
1659
+ const current = Array.from(records.get(entry.target) || []);
1660
+ for (const record of current) {
1661
+ if (entry.isIntersecting) {
1662
+ setRevealed(record, true);
1663
+ if (record.options.once)
1664
+ removeRecord(record);
1665
+ }
1666
+ else if (!record.options.once) {
1667
+ setRevealed(record, false);
1668
+ }
1669
+ }
1670
+ }
1671
+ }, { rootMargin: options.rootMargin, threshold: options.threshold });
1672
+ pool = { key, observer, records };
1673
+ }
1674
+ catch {
1675
+ return null;
1676
+ }
1677
+ pools.set(key, pool);
1678
+ return pool;
1679
+ }
1680
+ function prefersReducedMotion() {
1681
+ return typeof window.matchMedia === 'function'
1682
+ && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
1683
+ }
1684
+ function mountReveal(element, binding) {
1685
+ unmountReveal(element);
1686
+ document.documentElement.classList.add('gyos-reveal-ready');
1687
+ const options = normalizeOptions(binding);
1688
+ if (options.once && element.hasAttribute('data-gyos-revealed')) {
1689
+ for (const className of options.classNames)
1690
+ element.classList.add(className);
1691
+ return;
1692
+ }
1693
+ if (prefersReducedMotion() || typeof window.IntersectionObserver !== 'function') {
1694
+ const fallback = { element, options };
1695
+ setRevealed(fallback, true);
1696
+ return;
1697
+ }
1698
+ const pool = createPool(options);
1699
+ if (!pool) {
1700
+ const fallback = { element, options };
1701
+ setRevealed(fallback, true);
1702
+ return;
1703
+ }
1704
+ const observedTarget = options.target === 'parent' ? element.parentElement || element : element;
1705
+ const record = { element, observedTarget, options, pool };
1706
+ let records = pool.records.get(observedTarget);
1707
+ if (!records) {
1708
+ records = new Set();
1709
+ pool.records.set(observedTarget, records);
1710
+ pool.observer.observe(observedTarget);
1711
+ }
1712
+ records.add(record);
1713
+ mountedRecords.set(element, record);
1714
+ }
1715
+ function unmountReveal(element) {
1716
+ const record = mountedRecords.get(element);
1717
+ if (!record)
1718
+ return;
1719
+ removeRecord(record);
1720
+ if (!record.options.once)
1721
+ setRevealed(record, false);
1722
+ }
1723
+ const revealDirective = {
1724
+ mounted: mountReveal,
1725
+ updated(element, binding) {
1726
+ const previous = normalizeOptions({ ...binding, value: binding.oldValue });
1727
+ const next = normalizeOptions(binding);
1728
+ for (const className of previous.classNames) {
1729
+ if (!next.classNames.includes(className))
1730
+ element.classList.remove(className);
1731
+ }
1732
+ mountReveal(element, binding);
1733
+ },
1734
+ unmounted: unmountReveal
1735
+ };
1736
+
1581
1737
  const directives = new Map();
1582
1738
  /**
1583
1739
  * Register a custom directive
@@ -1752,6 +1908,7 @@ directive('markdown', {
1752
1908
  el.innerHTML = html;
1753
1909
  },
1754
1910
  });
1911
+ directive('reveal', revealDirective);
1755
1912
 
1756
1913
  /**
1757
1914
  * Transitions System - Smooth animations for enter/leave
@@ -2301,11 +2458,14 @@ function processDirectives(element, scope, root) {
2301
2458
  if (directive) {
2302
2459
  // g-on needs the handler itself. The general evaluator intentionally
2303
2460
  // invokes bare functions to support function-style computed values.
2304
- const value = directiveName === 'on' && typeof scope[attr.value] === 'function'
2305
- ? scope[attr.value]
2306
- : evaluateExpression(attr.value, scope, false);
2307
- if (value === undefined)
2308
- return; // Skip if value is undefined
2461
+ const evaluateValue = () => {
2462
+ if (attr.value.trim() === '')
2463
+ return undefined;
2464
+ return directiveName === 'on' && typeof scope[attr.value] === 'function'
2465
+ ? scope[attr.value]
2466
+ : evaluateExpression(attr.value, scope, false);
2467
+ };
2468
+ const value = evaluateValue();
2309
2469
  let oldValue = directive.mounted ? value : undefined;
2310
2470
  let initialized = !directive.mounted;
2311
2471
  // Call mounted hook
@@ -2331,7 +2491,7 @@ function processDirectives(element, scope, root) {
2331
2491
  // Setup reactive update if has updated hook
2332
2492
  if (directive.updated) {
2333
2493
  queueReactiveEffect(element, () => {
2334
- const newValue = evaluateExpression(attr.value, scope, false);
2494
+ const newValue = evaluateValue();
2335
2495
  if (!initialized) {
2336
2496
  initialized = true;
2337
2497
  oldValue = newValue;
@@ -2386,28 +2546,108 @@ function processDirectivesStatic(el, scope) {
2386
2546
  /**
2387
2547
  * Reactive attribute bindings (:class, :style, :aria-*, :data-*, and custom attributes).
2388
2548
  */
2389
- function handleClassBinding(el, value) {
2549
+ function createClassBindingState(el) {
2550
+ return {
2551
+ staticClasses: new Set(el.classList),
2552
+ dynamicClasses: new Set()
2553
+ };
2554
+ }
2555
+ function classNamesFromBinding(value) {
2390
2556
  if (typeof value === 'string') {
2391
- el.className = value;
2557
+ return new Set(value.split(/\s+/).filter(Boolean));
2392
2558
  }
2393
- else if (value && typeof value === 'object') {
2394
- Object.entries(value).forEach(([className, condition]) => {
2395
- el.classList.toggle(className, Boolean(condition));
2559
+ if (value && typeof value === 'object') {
2560
+ return new Set(Object.entries(value)
2561
+ .filter(([, condition]) => Boolean(condition))
2562
+ .flatMap(([className]) => className.split(/\s+/).filter(Boolean)));
2563
+ }
2564
+ return new Set();
2565
+ }
2566
+ function handleClassBinding(el, value, state) {
2567
+ const nextClasses = classNamesFromBinding(value);
2568
+ if (value && typeof value === 'object') {
2569
+ for (const [className, condition] of Object.entries(value)) {
2570
+ if (!condition) {
2571
+ for (const token of className.split(/\s+/).filter(Boolean))
2572
+ el.classList.remove(token);
2573
+ }
2574
+ }
2575
+ }
2576
+ for (const className of state.dynamicClasses) {
2577
+ if (!nextClasses.has(className) && !state.staticClasses.has(className)) {
2578
+ el.classList.remove(className);
2579
+ }
2580
+ }
2581
+ for (const className of nextClasses) {
2582
+ el.classList.add(className);
2583
+ }
2584
+ state.dynamicClasses = nextClasses;
2585
+ }
2586
+ function readStyleValues(style) {
2587
+ const values = new Map();
2588
+ for (let index = 0; index < style.length; index++) {
2589
+ const property = style.item(index);
2590
+ values.set(property, {
2591
+ priority: style.getPropertyPriority(property),
2592
+ value: style.getPropertyValue(property)
2396
2593
  });
2397
2594
  }
2595
+ return values;
2596
+ }
2597
+ function normalizeStyleProperty(property) {
2598
+ if (property.startsWith('--') || property.includes('-'))
2599
+ return property.toLowerCase();
2600
+ return property.replace(/[A-Z]/g, match => `-${match.toLowerCase()}`);
2398
2601
  }
2399
- function handleStyleBinding(el, value) {
2602
+ function styleValuesFromBinding(value) {
2603
+ const scratch = document.createElement('div').style;
2604
+ const mentioned = new Set();
2400
2605
  if (typeof value === 'string') {
2401
- el.setAttribute('style', value);
2606
+ scratch.cssText = value;
2607
+ for (const property of readStyleValues(scratch).keys())
2608
+ mentioned.add(property);
2402
2609
  }
2403
2610
  else if (value && typeof value === 'object') {
2404
- Object.entries(value).forEach(([property, propertyValue]) => {
2405
- el.style[property] = propertyValue ?? '';
2406
- });
2611
+ for (const [property, propertyValue] of Object.entries(value)) {
2612
+ const normalized = normalizeStyleProperty(property);
2613
+ mentioned.add(normalized);
2614
+ if (propertyValue == null || propertyValue === false)
2615
+ continue;
2616
+ if (property.startsWith('--'))
2617
+ scratch.setProperty(property, String(propertyValue));
2618
+ else
2619
+ scratch[property] = propertyValue;
2620
+ }
2407
2621
  }
2408
- else if (value == null || value === false) {
2409
- el.removeAttribute('style');
2622
+ return { mentioned, values: readStyleValues(scratch) };
2623
+ }
2624
+ function createStyleBindingState(el) {
2625
+ return {
2626
+ staticStyles: readStyleValues(el.style),
2627
+ dynamicProperties: new Set()
2628
+ };
2629
+ }
2630
+ function restoreStaticStyle(el, property, state) {
2631
+ const original = state.staticStyles.get(property);
2632
+ if (original)
2633
+ el.style.setProperty(property, original.value, original.priority);
2634
+ else
2635
+ el.style.removeProperty(property);
2636
+ }
2637
+ function handleStyleBinding(el, value, state) {
2638
+ const next = styleValuesFromBinding(value);
2639
+ for (const property of state.dynamicProperties) {
2640
+ if (!next.mentioned.has(property))
2641
+ restoreStaticStyle(el, property, state);
2642
+ }
2643
+ for (const property of next.mentioned) {
2644
+ const styleValue = next.values.get(property);
2645
+ if (styleValue)
2646
+ el.style.setProperty(property, styleValue.value, styleValue.priority);
2647
+ else
2648
+ el.style.removeProperty(property);
2410
2649
  }
2650
+ state.dynamicProperties = next.mentioned;
2411
2651
  }
2412
2652
  const booleanAttributes = new Set([
2413
2653
  'allowfullscreen', 'async', 'autofocus', 'autoplay', 'checked', 'controls',
@@ -2502,13 +2742,15 @@ function processBindings(element, scope, root) {
2502
2742
  for (const attribute of boundAttributes(element)) {
2503
2743
  const attrName = attribute.name.slice(1);
2504
2744
  const expression = attribute.value;
2745
+ const classState = attrName === 'class' ? createClassBindingState(element) : undefined;
2746
+ const styleState = attrName === 'style' ? createStyleBindingState(element) : undefined;
2505
2747
  queueReactiveEffect(element, () => {
2506
2748
  const currentScope = getScopeFromElement(element) || scope;
2507
2749
  const value = evaluateExpression(expression, currentScope);
2508
2750
  if (attrName === 'class')
2509
- handleClassBinding(element, value);
2751
+ handleClassBinding(element, value, classState);
2510
2752
  else if (attrName === 'style')
2511
- handleStyleBinding(element, value);
2753
+ handleStyleBinding(element, value, styleState);
2512
2754
  else
2513
2755
  applyAttributeBinding(element, attrName, value);
2514
2756
  });
@@ -2523,9 +2765,9 @@ function processBindingsStatic(root, scope) {
2523
2765
  const attrName = attribute.name.slice(1);
2524
2766
  const value = evaluateExpression(attribute.value, scope);
2525
2767
  if (attrName === 'class')
2526
- handleClassBinding(element, value);
2768
+ handleClassBinding(element, value, createClassBindingState(element));
2527
2769
  else if (attrName === 'style')
2528
- handleStyleBinding(element, value);
2770
+ handleStyleBinding(element, value, createStyleBindingState(element));
2529
2771
  else
2530
2772
  applyAttributeBinding(element, attrName, value);
2531
2773
  }
@@ -3536,12 +3778,12 @@ function setupClickOutsideHandler(element, handler, modifiers, scope, attrName)
3536
3778
  // e.stopPropagation(); // Optional: prevent other click handlers
3537
3779
  const target = e.target;
3538
3780
  // Check if click is outside element AND element is still in DOM
3539
- if (!document.body.contains(element) ||
3540
- (target instanceof Element && target.hasAttribute('g-ignore-outside-click'))) {
3541
- // Element removed, cleanup
3781
+ if (!document.body.contains(element)) {
3542
3782
  cleanup();
3543
3783
  return;
3544
3784
  }
3785
+ if (target instanceof Element && target.closest('[g-ignore-outside-click]'))
3786
+ return;
3545
3787
  if (element !== target && !element.contains(target)) {
3546
3788
  const currentScope = getScopeFromElement(element) || scope;
3547
3789
  if (modifiers.includes('once'))
@@ -3667,6 +3909,39 @@ function processEvents(el, scope) {
3667
3909
  });
3668
3910
  }
3669
3911
 
3912
+ const PARENT_SCOPE = Symbol('gyos.parent-scope');
3913
+ function attachParentScope(childScope, parentScope) {
3914
+ Object.defineProperty(childScope, PARENT_SCOPE, {
3915
+ value: parentScope,
3916
+ configurable: false,
3917
+ enumerable: false,
3918
+ writable: false
3919
+ });
3920
+ }
3921
+ function parentOf(scope) {
3922
+ return scope?.[PARENT_SCOPE];
3923
+ }
3924
+ function ensureModelPropertyOwner(scope, property) {
3925
+ if (!parentOf(scope) || property in scope)
3926
+ return;
3927
+ let owner = scope;
3928
+ let parent = parentOf(owner);
3929
+ while (parent) {
3930
+ owner = parent;
3931
+ parent = parentOf(owner);
3932
+ }
3933
+ if (!(property in owner))
3934
+ owner[property] = undefined;
3935
+ Object.defineProperty(scope, property, {
3936
+ get: () => owner[property],
3937
+ set: value => {
3938
+ owner[property] = value;
3939
+ },
3940
+ configurable: true,
3941
+ enumerable: true
3942
+ });
3943
+ }
3944
+
3670
3945
  /**
3671
3946
  * Two-Way Binding (g-model)
3672
3947
  * Handles form input binding with optional modifiers (debounce, number, trim, etc.)
@@ -3776,6 +4051,9 @@ function processModel(element, scope, root) {
3776
4051
  DEBUG() && console.log('[g-model] Expression:', expr, 'Modifiers:', modifiers, 'Debounce:', debounceMs);
3777
4052
  // Get current scope from element
3778
4053
  const currentScope = getScopeFromElement(element) || scope;
4054
+ const modelParts = parsePath(expr);
4055
+ if (typeof modelParts[0] === 'string')
4056
+ ensureModelPropertyOwner(currentScope, modelParts[0]);
3779
4057
  // Set initial value (no pipes in v-model)
3780
4058
  const initialValue = evaluateExpression(expr, currentScope, false);
3781
4059
  if (inputElement.type === 'checkbox') {
@@ -4032,8 +4310,15 @@ function reactive(raw) {
4032
4310
  proxy = new Proxy(raw, {
4033
4311
  get(target, key, receiver) {
4034
4312
  const value = Reflect.get(target, key, receiver);
4035
- // Không tạo signal cho property không phải own (vd forEach, map, filter...)
4313
+ // Missing own fields can become reactive later; prototype APIs stay untouched.
4036
4314
  if (!Object.prototype.hasOwnProperty.call(target, key)) {
4315
+ if (typeof key !== 'symbol' && !isReservedKey(key) && !(key in target)) {
4316
+ const existingSig = fieldSignals.get(target)?.get(key);
4317
+ if (hasCurrentEffect())
4318
+ return (existingSig || getFieldSignal(target, key, undefined)).value;
4319
+ if (existingSig)
4320
+ return existingSig.peek;
4321
+ }
4037
4322
  return value;
4038
4323
  }
4039
4324
  // symbol / key internal bỏ qua reactive
@@ -4124,6 +4409,7 @@ function reactive(raw) {
4124
4409
  return true;
4125
4410
  },
4126
4411
  ownKeys(target) {
4412
+ ensureVersion(target).value;
4127
4413
  return Reflect.ownKeys(target).filter(key => !isReservedKey(key));
4128
4414
  },
4129
4415
  getOwnPropertyDescriptor(target, key) {
@@ -4234,6 +4520,7 @@ function setRootScope(element, scope) {
4234
4520
  */
4235
4521
  function createChildScope(parentScope, itemVar, list, index) {
4236
4522
  const childScope = {};
4523
+ attachParentScope(childScope, parentScope);
4237
4524
  const state = signal({ list, index });
4238
4525
  Object.defineProperty(childScope, FOR_SCOPE_STATE, { value: state });
4239
4526
  // handle itemVar include index (e.g., "item, idx in items")
@@ -4272,6 +4559,9 @@ function createChildScope(parentScope, itemVar, list, index) {
4272
4559
  if (!(key in childScope)) {
4273
4560
  Object.defineProperty(childScope, key, {
4274
4561
  get: () => parentScope[key],
4562
+ set: (value) => {
4563
+ parentScope[key] = value;
4564
+ },
4275
4565
  enumerable: true,
4276
4566
  configurable: true,
4277
4567
  });
@@ -8003,7 +8293,7 @@ const Gyos = {
8003
8293
  onAfterNavigate,
8004
8294
  portalCreate,
8005
8295
  portalDestroy,
8006
- version: '0.2.2'
8296
+ version: '0.2.3'
8007
8297
  };
8008
8298
 
8009
8299
  export { applyDirective, applyTransitionStyles, batch, disposeEffects as cleanup, clearAllEvents, computed, debounce, Gyos as default, directive, effect, emit, getEventListeners, getGlobalContainer, getStoreNames, getTransitionConfig, getValidator, getValidatorNames, hasStore, inject, isComputed, isSignal, markRaw, mount, mountAll, mountTree, getAllMountedScopes as mountedScopes, nextTick, off, on, onAfterNavigate, onBeforeNavigate, once, pipe, portalCreate, portalDestroy, provide, ready, registerTransition, removeStore, scope, shallow, signal, startRouter, store, throttle, unref, untrack, useAsync, useCounter, useDebounce, useFetch, useInterval, useLocalStorage, useMediaQuery, useMouse, useThrottle, useTimeout, useToggle, useWindowSize, validate, validator };