gyosjs 0.1.1 → 0.2.0

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.1.1
2
+ * GyosJS v0.2.0
3
3
  * (c) 2026
4
4
  * @license MIT
5
5
  */
@@ -1492,6 +1492,29 @@ function flushEffectCollection() {
1492
1492
  * Text Node Processing
1493
1493
  * Handles template string interpolation in text nodes
1494
1494
  */
1495
+ const rawTextContainers = new Set([
1496
+ 'SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'TITLE', 'XMP', 'IFRAME', 'NOEMBED', 'NOFRAMES'
1497
+ ]);
1498
+ function shouldSkipTextNode(node, root, scope) {
1499
+ let parent = node.parentElement;
1500
+ while (parent) {
1501
+ if (isInIgnoredTree(parent) || rawTextContainers.has(parent.tagName))
1502
+ return true;
1503
+ if (parent.hasAttribute('*if') || parent.hasAttribute('*for'))
1504
+ return true;
1505
+ if (parent.__gyos_static__ && (scope !== undefined || parent !== root))
1506
+ return true;
1507
+ if (parent === root)
1508
+ break;
1509
+ parent = parent.parentElement;
1510
+ }
1511
+ if (scope !== undefined && node.parentElement) {
1512
+ const owner = getScopeFromElement(node.parentElement);
1513
+ if (owner && owner !== scope)
1514
+ return true;
1515
+ }
1516
+ return false;
1517
+ }
1495
1518
  /**
1496
1519
  * Process text nodes with {expression} interpolation
1497
1520
  *
@@ -1507,20 +1530,7 @@ function processTextNodes(el, scope) {
1507
1530
  const nodesToProcess = [];
1508
1531
  let node;
1509
1532
  while ((node = walker.nextNode())) {
1510
- if (node.parentElement && isInIgnoredTree(node.parentElement))
1511
- continue;
1512
- // Skip if parent has structural directive or is static or is script/style
1513
- let parent = node.parentElement;
1514
- let shouldSkip = false;
1515
- while (parent && parent !== el) {
1516
- if (parent.hasAttribute('*if') || parent.hasAttribute('*for') || parent.__gyos_static__
1517
- || parent.tagName === 'SCRIPT' || parent.tagName === 'STYLE') {
1518
- shouldSkip = true;
1519
- break;
1520
- }
1521
- parent = parent.parentElement;
1522
- }
1523
- if (shouldSkip)
1533
+ if (shouldSkipTextNode(node, el, scope))
1524
1534
  continue;
1525
1535
  const text = node.textContent || '';
1526
1536
  if (text.includes('{') && text.includes('}')) {
@@ -1552,7 +1562,7 @@ function processTextNodesStatic(el, scope) {
1552
1562
  const nodesToProcess = [];
1553
1563
  let node;
1554
1564
  while ((node = walker.nextNode())) {
1555
- if (node.parentElement && isInIgnoredTree(node.parentElement))
1565
+ if (shouldSkipTextNode(node, el))
1556
1566
  continue;
1557
1567
  const text = node.textContent || '';
1558
1568
  if (text.includes('{') && text.includes('}')) {
@@ -1744,2093 +1754,2047 @@ directive('markdown', {
1744
1754
  });
1745
1755
 
1746
1756
  /**
1747
- * Directive Processing
1748
- * Handles built-in directives (g-show, g-html, g-text) and custom directives
1749
- */
1750
- /**
1751
- * Process built-in and custom directives
1752
- *
1753
- * Built-in directives:
1754
- * - g-show: Toggle element visibility
1755
- * - g-html: Set innerHTML reactively
1756
- * - g-text: Set textContent reactively
1757
+ * Transitions System - Smooth animations for enter/leave
1757
1758
  *
1758
- * Custom directives: Registered via Gyos.directive()
1759
+ * Provides built-in transitions and custom transition support for elements.
1760
+ * Works with conditional rendering (*if, *for) to animate element appearance.
1759
1761
  *
1760
- * @param el - Root element to process
1761
- * @param scope - Scope object for evaluation
1762
+ * @example Basic usage
1763
+ * ```html
1764
+ * <div *if="show" g-transition="fade">Content</div>
1765
+ * <div *if="show" g-transition.500="slide-down">Slower slide</div>
1766
+ * ```
1762
1767
  */
1763
- function processDirectives(element, scope, root) {
1764
- if (isInIgnoredTree(element))
1765
- return;
1766
- // Skip if inside g-static parent
1767
- if (isInStaticParent(element, root))
1768
- return;
1769
- // Built-in directives: g-show
1770
- if (element.hasAttribute('g-show')) {
1771
- const expr = element.getAttribute('g-show');
1772
- queueReactiveEffect(element, () => {
1773
- const value = evaluateExpression(expr, scope);
1774
- element.style.display = value ? '' : 'none';
1775
- });
1776
- }
1777
- // g-html: Set innerHTML
1778
- if (element.hasAttribute('g-html')) {
1779
- const expr = element.getAttribute('g-html');
1780
- queueReactiveEffect(element, () => {
1781
- const value = evaluateExpression(expr, scope);
1782
- element.innerHTML = value;
1783
- });
1784
- }
1785
- // g-text: Set textContent
1786
- if (element.hasAttribute('g-text')) {
1787
- const expr = element.getAttribute('g-text');
1788
- queueReactiveEffect(element, () => {
1789
- const value = evaluateExpression(expr, scope);
1790
- element.textContent = value;
1791
- });
1792
- }
1793
- // Process custom directives (g-focus, g-tooltip, g-clickoutside, etc.)
1794
- Array.from(element.attributes).forEach(attr => {
1795
- // Skip built-in and framework directives
1796
- if (attr.name.startsWith('g-') &&
1797
- !['g-scope', 'g-show', 'g-html', 'g-text', 'g-model', 'g-static', 'g-portal', 'g-transition', 'g-hydrate', 'g-provide'].includes(attr.name)) {
1798
- const directiveName = attr.name.slice(2).replace(/:.+$/, ''); // Remove 'g-' prefix and any arguments
1799
- const directive = getDirective(directiveName);
1800
- const args = attr.name.split(':');
1801
- let arg = undefined;
1802
- if (args.length > 1)
1803
- arg = args.slice(1); // Get arguments as array
1804
- if (directive) {
1805
- // g-on needs the handler itself. The general evaluator intentionally
1806
- // invokes bare functions to support function-style computed values.
1807
- const value = directiveName === 'on' && typeof scope[attr.value] === 'function'
1808
- ? scope[attr.value]
1809
- : evaluateExpression(attr.value, scope, false);
1810
- if (value === undefined)
1811
- return; // Skip if value is undefined
1812
- let oldValue = directive.mounted ? value : undefined;
1813
- let initialized = !directive.mounted;
1814
- // Call mounted hook
1815
- if (directive.mounted) {
1816
- directive.mounted(element, {
1817
- value, arg,
1818
- oldValue: undefined,
1819
- }, scope);
1820
- }
1821
- if (directive.unmounted) {
1822
- let active = true;
1823
- const cleanup = () => {
1824
- if (!active)
1825
- return;
1826
- active = false;
1827
- directive.unmounted(element);
1828
- };
1829
- if (!element.__gyos_effects__) {
1830
- element.__gyos_effects__ = [];
1831
- }
1832
- element.__gyos_effects__.push(cleanup);
1833
- }
1834
- // Setup reactive update if has updated hook
1835
- if (directive.updated) {
1836
- queueReactiveEffect(element, () => {
1837
- const newValue = evaluateExpression(attr.value, scope, false);
1838
- if (!initialized) {
1839
- initialized = true;
1840
- oldValue = newValue;
1841
- return;
1842
- }
1843
- if (Object.is(oldValue, newValue))
1844
- return;
1845
- directive.updated(element, {
1846
- value: newValue,
1847
- oldValue,
1848
- arg,
1849
- }, scope);
1850
- oldValue = newValue;
1851
- });
1852
- }
1853
- }
1854
- }
1855
- });
1856
- }
1857
1768
  /**
1858
- * Process static directives (no reactivity)
1769
+ * Built-in transitions
1859
1770
  *
1860
- * @param el - Root element to process
1861
- * @param scope - Scope object for evaluation
1862
- */
1863
- function processDirectivesStatic(el, scope) {
1864
- const directives = Array.from(el.querySelectorAll('[g-show], [g-html], [g-text]'))
1865
- .filter(element => !isInIgnoredTree(element));
1866
- directives.forEach(elem => {
1867
- const element = elem;
1868
- // g-show
1869
- if (element.hasAttribute('g-show')) {
1870
- const expr = element.getAttribute('g-show');
1871
- const value = evaluateExpression(expr, scope);
1872
- element.style.display = value ? '' : 'none';
1873
- }
1874
- // g-html
1875
- if (element.hasAttribute('g-html')) {
1876
- const expr = element.getAttribute('g-html');
1877
- const value = evaluateExpression(expr, scope);
1878
- element.innerHTML = value;
1879
- }
1880
- // g-text
1881
- if (element.hasAttribute('g-text')) {
1882
- const expr = element.getAttribute('g-text');
1883
- const value = evaluateExpression(expr, scope);
1884
- element.textContent = value;
1885
- }
1886
- });
1887
- }
1888
-
1889
- /**
1890
- * Attribute Bindings
1891
- * Handles :attribute directives (:class, :style, :disabled, :href, etc.)
1771
+ * Available: fade, slide-down, slide-up, slide-left, slide-right, scale, zoom
1892
1772
  */
1773
+ const builtInTransitions = {
1774
+ fade: {
1775
+ enterFrom: 'gyos-t-opacity-0',
1776
+ enterTo: 'gyos-t-opacity-100',
1777
+ leaveFrom: 'gyos-t-opacity-100',
1778
+ leaveTo: 'gyos-t-opacity-0',
1779
+ duration: 250
1780
+ },
1781
+ 'slide-down': {
1782
+ enterFrom: 'gyos-t-translate-y--100 gyos-t-opacity-0',
1783
+ enterTo: 'gyos-t-translate-y-0 gyos-t-opacity-100',
1784
+ leaveFrom: 'gyos-t-translate-y-0 gyos-t-opacity-100',
1785
+ leaveTo: 'gyos-t-translate-y-100 gyos-t-opacity-0',
1786
+ duration: 250
1787
+ },
1788
+ 'slide-up': {
1789
+ enterFrom: 'gyos-t-translate-y-100 gyos-t-opacity-0',
1790
+ enterTo: 'gyos-t-translate-y-0 gyos-t-opacity-100',
1791
+ leaveFrom: 'gyos-t-translate-y-0 gyos-t-opacity-100',
1792
+ leaveTo: 'gyos-t-translate-y--100 gyos-t-opacity-0',
1793
+ duration: 250
1794
+ },
1795
+ 'slide-left': {
1796
+ enterFrom: 'gyos-t-translate-x-100 gyos-t-opacity-0',
1797
+ enterTo: 'gyos-t-translate-x-0 gyos-t-opacity-100',
1798
+ leaveFrom: 'gyos-t-translate-x-0 gyos-t-opacity-100',
1799
+ leaveTo: 'gyos-t-translate-x--100 gyos-t-opacity-0',
1800
+ duration: 250
1801
+ },
1802
+ 'slide-right': {
1803
+ enterFrom: 'gyos-t-translate-x--100 gyos-t-opacity-0',
1804
+ enterTo: 'gyos-t-translate-x-0 gyos-t-opacity-100',
1805
+ leaveFrom: 'gyos-t-translate-x-0 gyos-t-opacity-100',
1806
+ leaveTo: 'gyos-t-translate-x-100 gyos-t-opacity-0',
1807
+ duration: 250
1808
+ },
1809
+ scale: {
1810
+ enterFrom: 'gyos-t-scale-50 gyos-t-opacity-0',
1811
+ enterTo: 'gyos-t-scale-100 gyos-t-opacity-100',
1812
+ leaveFrom: 'gyos-t-scale-100 gyos-t-opacity-100',
1813
+ leaveTo: 'gyos-t-scale-50 gyos-t-opacity-0',
1814
+ duration: 250
1815
+ },
1816
+ zoom: {
1817
+ enterFrom: 'gyos-t-scale-0 gyos-t-opacity-0',
1818
+ enterTo: 'gyos-t-scale-100 gyos-t-opacity-100',
1819
+ leaveFrom: 'gyos-t-scale-100 gyos-t-opacity-100',
1820
+ leaveTo: 'gyos-t-scale-0 gyos-t-opacity-0',
1821
+ duration: 250
1822
+ }
1823
+ };
1893
1824
  /**
1894
- * Handle :class binding
1895
- * Supports string or object syntax
1825
+ * Register a custom transition
1896
1826
  *
1897
- * @param el - Element to update
1898
- * @param value - Class value (string or object)
1827
+ * @param name - Transition name
1828
+ * @param config - Transition configuration
1899
1829
  *
1900
1830
  * @example
1901
- * :class="'active'" → set className
1902
- * :class="{ active: isActive }" → toggle classes
1831
+ * ```javascript
1832
+ * Gyos.registerTransition('bounce-in', {
1833
+ * enter: 'bounce-in 500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)',
1834
+ * leave: 'bounce-out 250ms ease-in',
1835
+ * duration: 500
1836
+ * });
1837
+ * ```
1903
1838
  */
1904
- function handleClassBinding(el, value) {
1905
- DEBUG() && console.log('[ClassBinding] Element:', el.tagName, 'Value:', value, 'Current classes:', el.className);
1906
- if (typeof value === 'string') {
1907
- el.className = value;
1908
- }
1909
- else if (typeof value === 'object') {
1910
- Object.entries(value).forEach(([className, condition]) => {
1911
- DEBUG() && console.log(`[ClassBinding] ${className}: ${condition ? 'ADD' : 'REMOVE'}`);
1912
- if (condition) {
1913
- el.classList.add(className);
1839
+ function registerTransition(name, config) {
1840
+ builtInTransitions[name] = config;
1841
+ }
1842
+ /**
1843
+ * Transition manager - Handles enter/leave animations
1844
+ */
1845
+ class TransitionManager {
1846
+ constructor() {
1847
+ this.active = new WeakMap();
1848
+ }
1849
+ cancel(el) {
1850
+ this.active.get(el)?.cancel();
1851
+ }
1852
+ enter(el, config, interruptLeave = false) {
1853
+ if (!el.isConnected)
1854
+ return Promise.resolve(false);
1855
+ if (this.active.get(el)?.phase === 'leave' && !interruptLeave)
1856
+ return Promise.resolve(false);
1857
+ return this.run(el, config, 'enter', false);
1858
+ }
1859
+ leave(el, config, removeElement = true) {
1860
+ return this.run(el, config, 'leave', removeElement);
1861
+ }
1862
+ run(el, config, phase, removeElement) {
1863
+ this.cancel(el);
1864
+ const fromClasses = phase === 'enter' ? config.enterFrom : config.leaveFrom;
1865
+ const toClasses = phase === 'enter' ? config.enterTo : config.leaveTo;
1866
+ const animation = phase === 'enter' ? config.enter : config.leave;
1867
+ const beforeHook = phase === 'enter' ? config.onBeforeEnter : config.onBeforeLeave;
1868
+ const afterHook = phase === 'enter' ? config.onAfterEnter : config.onAfterLeave;
1869
+ const reduceMotion = typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
1870
+ const duration = reduceMotion ? 0 : (config.duration ?? 250);
1871
+ const originalTransition = el.style.transition;
1872
+ const originalAnimation = el.style.animation;
1873
+ return new Promise(resolve => {
1874
+ let settled = false;
1875
+ let timer;
1876
+ const cleanup = () => {
1877
+ if (fromClasses)
1878
+ this.removeClasses(el, fromClasses);
1879
+ if (toClasses)
1880
+ this.removeClasses(el, toClasses);
1881
+ el.style.transition = originalTransition;
1882
+ el.style.animation = originalAnimation;
1883
+ el.removeEventListener('transitionend', onEnd);
1884
+ el.removeEventListener('animationend', onEnd);
1885
+ if (timer !== undefined)
1886
+ clearTimeout(timer);
1887
+ this.active.delete(el);
1888
+ };
1889
+ const finish = (cancelled) => {
1890
+ if (settled)
1891
+ return;
1892
+ settled = true;
1893
+ cleanup();
1894
+ if (!cancelled) {
1895
+ afterHook?.(el);
1896
+ if (phase === 'leave' && removeElement)
1897
+ el.remove();
1898
+ }
1899
+ resolve(!cancelled);
1900
+ };
1901
+ const onEnd = (event) => {
1902
+ if (event.target === el)
1903
+ finish(false);
1904
+ };
1905
+ this.active.set(el, { phase, cancel: () => finish(true) });
1906
+ try {
1907
+ beforeHook?.(el);
1908
+ if (fromClasses)
1909
+ this.applyClasses(el, fromClasses);
1910
+ el.offsetHeight;
1911
+ el.style.transition = `all ${duration}ms ${phase === 'enter' ? 'ease-out' : 'ease-in'}`;
1912
+ if (fromClasses)
1913
+ this.removeClasses(el, fromClasses);
1914
+ if (toClasses)
1915
+ this.applyClasses(el, toClasses);
1916
+ if (animation)
1917
+ el.style.animation = animation;
1918
+ if (duration === 0) {
1919
+ queueMicrotask(() => finish(false));
1920
+ }
1921
+ else {
1922
+ el.addEventListener('transitionend', onEnd);
1923
+ el.addEventListener('animationend', onEnd);
1924
+ timer = setTimeout(() => finish(false), duration + 50);
1925
+ }
1914
1926
  }
1915
- else {
1916
- el.classList.remove(className);
1927
+ catch (error) {
1928
+ console.error(`[GyosJS] Transition ${phase} error:`, error);
1929
+ finish(false);
1917
1930
  }
1918
1931
  });
1919
1932
  }
1920
- }
1921
- /**
1922
- * Handle :style binding
1923
- * Supports string or object syntax
1924
- *
1925
- * @param el - Element to update
1926
- * @param value - Style value (string or object)
1927
- *
1928
- * @example
1929
- * :style="'color: red'" → set style attribute
1930
- * :style="{ color: 'red', fontSize }" → set individual styles
1931
- */
1932
- function handleStyleBinding(el, value) {
1933
- if (typeof value === 'string') {
1934
- el.setAttribute('style', value);
1933
+ /**
1934
+ * Apply CSS classes
1935
+ */
1936
+ applyClasses(el, classes) {
1937
+ classes.split(' ').forEach(cls => {
1938
+ if (cls)
1939
+ el.classList.add(cls);
1940
+ });
1935
1941
  }
1936
- else if (typeof value === 'object') {
1937
- Object.entries(value).forEach(([prop, val]) => {
1938
- el.style[prop] = val;
1942
+ /**
1943
+ * Remove CSS classes
1944
+ */
1945
+ removeClasses(el, classes) {
1946
+ classes.split(' ').forEach(cls => {
1947
+ if (cls)
1948
+ el.classList.remove(cls);
1939
1949
  });
1940
1950
  }
1941
- }
1942
- const allowsAttrs = [
1943
- 'class',
1944
- 'style',
1945
- 'disabled',
1946
- 'readonly',
1947
- 'checked',
1948
- 'selected',
1949
- 'value',
1950
- 'src',
1951
- 'href',
1952
- 'alt',
1953
- 'title'
1954
- ];
1955
- const removeAttrs = ['disabled', 'readonly', 'checked', 'selected'];
1956
- const activeUrlElements = new Set(['BASE', 'EMBED', 'IFRAME', 'LINK', 'OBJECT', 'SCRIPT']);
1957
- function isSafeBoundUrl(element, attrName, value) {
1958
- if (attrName !== 'href' && attrName !== 'src')
1959
- return true;
1960
- if (value === null || value === undefined)
1961
- return true;
1962
- if (activeUrlElements.has(element.tagName))
1963
- return false;
1964
- const normalized = String(value).trim().replace(/[\u0000-\u0020]+/g, '').toLowerCase();
1965
- if (normalized.startsWith('javascript:') || normalized.startsWith('vbscript:'))
1966
- return false;
1967
- if (!normalized.startsWith('data:'))
1968
- return true;
1969
- return attrName === 'src'
1970
- && element instanceof HTMLImageElement
1971
- && /^data:image\/(?:png|gif|jpe?g|webp|avif);base64,/i.test(normalized);
1972
- }
1973
- function applyAttributeBinding(element, attrName, value) {
1974
- if (!isSafeBoundUrl(element, attrName, value)) {
1975
- element.removeAttribute(attrName);
1976
- DEBUG() && console.warn(`[GyosJS] Blocked unsafe :${attrName} URL`);
1977
- return;
1978
- }
1979
- if (removeAttrs.includes(attrName) && !value) {
1980
- element.removeAttribute(attrName);
1951
+ /**
1952
+ * Get transition config by name or return custom config
1953
+ *
1954
+ * @param name - Transition name or custom config object
1955
+ * @returns Transition configuration
1956
+ */
1957
+ getConfig(name) {
1958
+ if (typeof name === 'object') {
1959
+ return name;
1960
+ }
1961
+ return builtInTransitions[name] || builtInTransitions.fade;
1981
1962
  }
1982
- else {
1983
- element.setAttribute(attrName, String(value ?? ''));
1963
+ /**
1964
+ * Get all available transition names
1965
+ *
1966
+ * @returns Array of transition names
1967
+ */
1968
+ getAvailableTransitions() {
1969
+ return Object.keys(builtInTransitions);
1984
1970
  }
1985
1971
  }
1972
+ // Singleton instance
1973
+ const transitionManager = new TransitionManager();
1986
1974
  /**
1987
- * Process attribute bindings (:class, :style, :disabled, etc.)
1975
+ * Get transition config from element attribute
1988
1976
  *
1989
- * @param el - Root element to process
1990
- * @param scope - Scope object for evaluation
1977
+ * Supports:
1978
+ * - `g-transition="fade"` - Built-in transition
1979
+ * - `g-transition.500="fade"` - Custom duration (500ms)
1980
+ *
1981
+ * @param source - Registered transition name or element containing a transition attribute
1982
+ * @returns Transition configuration or null
1991
1983
  *
1992
1984
  * @example
1993
- * <div :class="{ active: isActive }"></div>
1994
- * <div :style="{ color: textColor }"></div>
1995
- * <button :disabled="isLoading">Submit</button>
1996
- * <a :href="link">Link</a>
1985
+ * ```html
1986
+ * <div g-transition="fade">Default 250ms fade</div>
1987
+ * <div g-transition.500="slide-down">500ms slide</div>
1988
+ * ```
1997
1989
  */
1998
- function processBindings(element, scope, root) {
1999
- if (isInIgnoredTree(element))
2000
- return;
2001
- // Check el itself first
2002
- if (!element.matches(allowsAttrs.map(a => `[\\:${a}]`).join(', ')))
2003
- return;
2004
- // Skip if element has structural directive (already processed) or in g-static parent
2005
- if (element.hasAttribute('*if') || element.hasAttribute('*for') || isInStaticParent(element, root)) {
2006
- return;
1990
+ function getTransitionConfig(source) {
1991
+ if (typeof source === 'string') {
1992
+ return builtInTransitions[source] || null;
2007
1993
  }
2008
- const attrs = element.attributes;
2009
- for (let i = 0; i < attrs.length; i++) {
2010
- const attr = attrs[i];
2011
- if (attr.name.startsWith(':')) {
2012
- const attrName = attr.name.substring(1);
2013
- const expr = attr.value;
2014
- queueReactiveEffect(element, () => {
2015
- // Always get fresh scope from element
2016
- let scopeEl = element;
2017
- DEBUG() && console.log('[Binding] Element:', element.tagName, 'Attribute:', attrName, 'Expression:', expr);
2018
- const currentScope = getScopeFromElement(scopeEl) || scope;
2019
- const value = evaluateExpression(expr, currentScope);
2020
- if (attrName === 'class') {
2021
- handleClassBinding(element, value);
2022
- }
2023
- else if (attrName === 'style') {
2024
- handleStyleBinding(element, value);
2025
- }
2026
- else {
2027
- applyAttributeBinding(element, attrName, value);
2028
- }
2029
- });
2030
- }
1994
+ const transitionAttr = Array.from(source.attributes).find(attribute => attribute.name === 'g-transition' || attribute.name.startsWith('g-transition.'));
1995
+ if (!transitionAttr)
1996
+ return null;
1997
+ const attr = transitionAttr.value;
1998
+ try {
1999
+ // Try to parse as JSON for custom config
2000
+ const customConfig = JSON.parse(attr);
2001
+ return customConfig;
2031
2002
  }
2032
- }
2033
- /**
2034
- * Process static bindings (no reactivity)
2035
- *
2036
- * @param el - Root element to process
2037
- * @param scope - Scope object for evaluation
2038
- */
2039
- function processBindingsStatic(el, scope) {
2040
- const allElements = [el, ...Array.from(el.querySelectorAll(allowsAttrs.map(a => `[\\:${a}]`).join(', ')))];
2041
- allElements.forEach(element => {
2042
- if (isInIgnoredTree(element))
2043
- return;
2044
- const attrs = element.attributes;
2045
- for (let i = 0; i < attrs.length; i++) {
2046
- const attr = attrs[i];
2047
- if (attr.name.startsWith(':')) {
2048
- const attrName = attr.name.substring(1);
2049
- const expr = attr.value;
2050
- const value = evaluateExpression(expr, scope);
2051
- if (attrName === 'class') {
2052
- handleClassBinding(element, value);
2053
- }
2054
- else if (attrName === 'style') {
2055
- handleStyleBinding(element, value);
2056
- }
2057
- else {
2058
- applyAttributeBinding(element, attrName, value);
2059
- }
2003
+ catch {
2004
+ // Use built-in transition by name
2005
+ const config = builtInTransitions[attr];
2006
+ if (!config) {
2007
+ console.warn(`[GyosJS] Unknown transition: "${attr}". Using "fade" as fallback.`);
2008
+ return builtInTransitions.fade;
2009
+ }
2010
+ // Check for duration modifier (e.g., g-transition.500="fade")
2011
+ if (transitionAttr.name.startsWith('g-transition.')) {
2012
+ const durationMatch = transitionAttr.name.match(/g-transition\.(\d+)/);
2013
+ if (durationMatch) {
2014
+ return {
2015
+ ...config,
2016
+ duration: parseInt(durationMatch[1], 10)
2017
+ };
2060
2018
  }
2061
2019
  }
2062
- });
2020
+ return config;
2021
+ }
2063
2022
  }
2064
-
2065
- /**
2066
- * Portal/Teleport System - Render content in different DOM location
2067
- * Useful for modals, tooltips, notifications that need to break out of parent containers
2068
- *
2069
- * @example
2070
- * // Portal to body (for modals)
2071
- * <div g-portal="body">
2072
- * <div class="modal">Modal content</div>
2073
- * </div>
2074
- *
2075
- * @example
2076
- * // Portal to specific element
2077
- * <div g-portal="#notifications">
2078
- * <div class="toast">Toast message</div>
2079
- * </div>
2080
- */
2081
2023
  /**
2082
- * Create a portal - Move element to target location
2024
+ * Apply built-in transition utility styles to document
2083
2025
  *
2084
- * @param sourceEl - Element to teleport
2085
- * @param targetSelector - CSS selector for destination
2026
+ * Called automatically on component mount. Adds CSS classes and keyframes
2027
+ * used by built-in transitions (opacity, transform, scale, etc.)
2086
2028
  *
2087
2029
  * @example
2088
- * portalCreate(modalEl, 'body');
2089
- * portalCreate(tooltipEl, '#tooltip-container');
2030
+ * ```javascript
2031
+ * // Usually called automatically, but can be called manually:
2032
+ * Gyos.applyTransitionStyles();
2033
+ * ```
2090
2034
  */
2091
- function portalCreate(sourceEl, targetSelector) {
2092
- if (!sourceEl)
2035
+ function applyTransitionStyles() {
2036
+ if (typeof document === 'undefined')
2093
2037
  return;
2094
- const target = document.querySelector(targetSelector);
2095
- if (!target) {
2096
- console.warn(`[GyosJS] Portal target "${targetSelector}" not found`);
2038
+ const styleId = 'gyos-transitions';
2039
+ if (document.getElementById(styleId))
2097
2040
  return;
2098
- }
2099
- // Create placeholder comment to mark original position
2100
- const placeholder = document.createComment('g-portal');
2101
- sourceEl.parentNode?.insertBefore(placeholder, sourceEl);
2102
- // Store original parent for restoration
2103
- sourceEl.__portal_placeholder__ = placeholder;
2104
- sourceEl.__portal_target__ = target;
2105
- // Move the entire element to target
2106
- target.appendChild(sourceEl);
2107
- DEBUG() && console.log('[Portal] Created - moved element to', targetSelector);
2041
+ const style = document.createElement('style');
2042
+ style.id = styleId;
2043
+ style.textContent = `
2044
+ /* Opacity utilities */
2045
+ .gyos-t-opacity-0 { opacity: 0; }
2046
+ .gyos-t-opacity-100 { opacity: 1; }
2047
+
2048
+ /* Transform - Translate Y */
2049
+ .gyos-t-translate-y-0 { transform: translateY(0); }
2050
+ .gyos-t-translate-y--100 { transform: translateY(-100%); }
2051
+ .gyos-t-translate-y-100 { transform: translateY(100%); }
2052
+
2053
+ /* Transform - Translate X */
2054
+ .gyos-t-translate-x-0 { transform: translateX(0); }
2055
+ .gyos-t-translate-x--100 { transform: translateX(-100%); }
2056
+ .gyos-t-translate-x-100 { transform: translateX(100%); }
2057
+
2058
+ /* Transform - Scale */
2059
+ .gyos-t-scale-0 { transform: scale(0); }
2060
+ .gyos-t-scale-50 { transform: scale(0.5); }
2061
+ .gyos-t-scale-100 { transform: scale(1); }
2062
+
2063
+ /* Animation Keyframes */
2064
+ @keyframes gyos-fade-in {
2065
+ from { opacity: 0; }
2066
+ to { opacity: 1; }
2067
+ }
2068
+
2069
+ @keyframes gyos-fade-out {
2070
+ from { opacity: 1; }
2071
+ to { opacity: 0; }
2072
+ }
2073
+
2074
+ @keyframes gyos-slide-down {
2075
+ from { transform: translateY(-100%); opacity: 0; }
2076
+ to { transform: translateY(0); opacity: 1; }
2077
+ }
2078
+
2079
+ @keyframes gyos-slide-up {
2080
+ from { transform: translateY(100%); opacity: 0; }
2081
+ to { transform: translateY(0); opacity: 1; }
2082
+ }
2083
+
2084
+ @keyframes gyos-scale-in {
2085
+ from { transform: scale(0); opacity: 0; }
2086
+ to { transform: scale(1); opacity: 1; }
2087
+ }
2088
+
2089
+ @keyframes gyos-scale-out {
2090
+ from { transform: scale(1); opacity: 1; }
2091
+ to { transform: scale(0); opacity: 0; }
2092
+ }
2093
+
2094
+ [g-cloak] {
2095
+ display: none !important;
2096
+ }`;
2097
+ document.head.appendChild(style);
2108
2098
  }
2099
+
2109
2100
  /**
2110
- * Destroy a portal - Restore element to original position
2111
- *
2112
- * @param sourceEl - Element to restore
2101
+ * Transition Helper Utilities
2102
+ * Shared utilities for handling transitions in structural directives
2103
+ */
2104
+ /**
2105
+ * Parse transition name from attribute value
2106
+ * Handles:
2107
+ * 1. Literal string: "fade" or "slide-down"
2108
+ * 2. Expression with {}: "{transition}"
2109
+ * 3. Expression without {}: "transition" (evaluate as variable)
2113
2110
  *
2114
- * @example
2115
- * portalDestroy(modalEl); // Returns modal to original location
2111
+ * @param attrValue - The g-transition attribute value
2112
+ * @param scope - Current scope for expression evaluation
2113
+ * @returns The transition name (string)
2116
2114
  */
2117
- function portalDestroy(sourceEl) {
2118
- if (!sourceEl)
2119
- return;
2120
- const placeholder = sourceEl.__portal_placeholder__;
2121
- if (placeholder && placeholder.parentNode) {
2122
- // Move element back to original position
2123
- placeholder.parentNode.insertBefore(sourceEl, placeholder);
2124
- placeholder.remove();
2125
- delete sourceEl.__portal_placeholder__;
2126
- delete sourceEl.__portal_target__;
2127
- DEBUG() && console.log('[Portal] Destroyed - restored element to original position');
2115
+ function parseTransitionName(attrValue, scope) {
2116
+ if (attrValue.includes('{') && attrValue.includes('}')) {
2117
+ // Extract expression from {} and evaluate it
2118
+ const match = attrValue.match(/\{([^}]+)\}/);
2119
+ if (match) {
2120
+ return evaluateExpression(match[1].trim(), scope);
2121
+ }
2122
+ }
2123
+ // Try to evaluate as expression first (variable name)
2124
+ // If it fails or returns undefined, use as literal string
2125
+ try {
2126
+ const evaluated = evaluateExpression(attrValue, scope);
2127
+ if (evaluated !== undefined && evaluated !== null) {
2128
+ return evaluated;
2129
+ }
2130
+ }
2131
+ catch (e) {
2132
+ // If evaluation fails, use value as literal string (built-in transition name)
2128
2133
  }
2134
+ return attrValue;
2129
2135
  }
2130
-
2131
- /**
2132
- * Validator registry
2133
- */
2134
- const validators = new Map();
2135
2136
  /**
2136
- * Register a custom validator
2137
+ * Parse transition config from element's g-transition attribute
2138
+ * Extracts transition name and custom duration modifier
2137
2139
  *
2138
- * @param name - Validator name
2139
- * @param fn - Validator function (return true for valid, string for error message)
2140
- *
2141
- * @example
2142
- * ```javascript
2143
- * Gyos.validator('even', (value) => {
2144
- * return value % 2 === 0 || 'Must be an even number';
2145
- * });
2146
- * ```
2147
- */
2148
- function validator(name, fn) {
2149
- validators.set(name, fn);
2150
- }
2151
- /**
2152
- * Get registered validator by name
2153
- *
2154
- * @param name - Validator name
2155
- * @returns Validator function or undefined
2140
+ * @param element - Element with g-transition attribute
2141
+ * @param scope - Current scope for expression evaluation
2142
+ * @returns { name: string, duration?: number } or null if no transition
2156
2143
  */
2157
- function getValidator(name) {
2158
- return validators.get(name);
2144
+ function parseTransitionConfig(element, scope) {
2145
+ const attrs = Array.from(element.attributes);
2146
+ const transitionAttr = attrs.find(attr => attr.name.startsWith('g-transition'));
2147
+ if (!transitionAttr)
2148
+ return null;
2149
+ // Parse modifiers from attribute name: g-transition.500
2150
+ const attrParts = transitionAttr.name.split('.');
2151
+ const modifiers = attrParts.slice(1); // ['500'] or []
2152
+ const customDuration = modifiers.find(m => /^\d+$/.test(m));
2153
+ const transitionName = parseTransitionName(transitionAttr.value, scope);
2154
+ return {
2155
+ name: transitionName,
2156
+ duration: customDuration ? parseInt(customDuration) : undefined
2157
+ };
2159
2158
  }
2160
2159
  /**
2161
- * Get all registered validator names
2162
- *
2163
- * @returns Array of validator names
2160
+ * Find all elements with g-transition attribute
2161
+ * Searches root element and all descendants
2164
2162
  *
2165
- * @example
2166
- * ```javascript
2167
- * console.log('Available validators:', Gyos.getValidatorNames());
2168
- * // ['required', 'email', 'minLength', ...]
2169
- * ```
2163
+ * @param root - Root element to search from
2164
+ * @returns Array of elements with g-transition
2170
2165
  */
2171
- function getValidatorNames() {
2172
- return Array.from(validators.keys());
2166
+ function findElementsWithTransition(root) {
2167
+ if (isInIgnoredTree(root))
2168
+ return [];
2169
+ const elements = [];
2170
+ // Check root element
2171
+ if (Array.from(root.attributes).some(attr => attr.name.startsWith('g-transition'))) {
2172
+ elements.push(root);
2173
+ }
2174
+ // Check all descendants
2175
+ const allDescendants = walkerDOM(root, el => !isInIgnoredTree(el), NodeFilter.FILTER_REJECT).filter(el => Array.from(el.attributes).some(attr => attr.name.startsWith('g-transition')));
2176
+ elements.push(...allDescendants);
2177
+ return elements;
2173
2178
  }
2174
2179
  /**
2175
- * Validate a value against validation rules
2176
- *
2177
- * Supports custom error messages in two ways:
2178
- * 1. Inline: "required:Custom message|email:Invalid email"
2179
- * 2. Via context: { messages: { required: "Custom message" } }
2180
- *
2181
- * @param value - Value to validate
2182
- * @param rules - Validation rules (pipe-separated: "required|email|minLength(5)")
2183
- * @param context - Optional context with form data and custom messages
2184
- * @returns Error message or null if valid
2185
- *
2186
- * @example Basic validation
2187
- * ```javascript
2188
- * const error = await Gyos.validate('test@', 'required|email');
2189
- * // Returns: "Invalid email address"
2190
- * ```
2191
- *
2192
- * @example Inline custom messages
2193
- * ```javascript
2194
- * const error = await Gyos.validate('', 'required:This field is mandatory|email:Enter valid email');
2195
- * // Returns: "This field is mandatory"
2196
- * ```
2197
- *
2198
- * @example Custom messages via context
2199
- * ```javascript
2200
- * const error = await Gyos.validate('abc', 'required|minLength(5)', {
2201
- * messages: {
2202
- * required: 'Please fill this field',
2203
- * minLength: 'Too short! Need at least 5 characters'
2204
- * }
2205
- * });
2206
- * // Returns: "Too short! Need at least 5 characters"
2207
- * ```
2180
+ * Apply enter transition to an element
2181
+ * Handles transition config parsing and application
2208
2182
  *
2209
- * @example With form context
2210
- * ```javascript
2211
- * const error = await Gyos.validate(confirmPw, 'required|same(password)', {
2212
- * form: { password: 'MyPass123' },
2213
- * messages: { same: 'Passwords do not match' }
2214
- * });
2215
- * ```
2183
+ * @param element - Element to apply transition to
2184
+ * @param scope - Current scope for expression evaluation
2185
+ * @returns Promise that resolves when transition completes
2216
2186
  */
2217
- async function validate(value, rules, context) {
2218
- const ruleParts = rules.split('|');
2219
- for (const rule of ruleParts) {
2220
- // Parse rule: "required:Custom message" or "required" or "minLength(5):Custom message"
2221
- const colonIndex = rule.lastIndexOf(':');
2222
- let rulePart = rule;
2223
- let customMessage;
2224
- // Check if there's a custom message after colon (but not inside parentheses)
2225
- if (colonIndex > 0) {
2226
- const beforeColon = rule.substring(0, colonIndex);
2227
- // Only treat as custom message if colon is not inside function args
2228
- const openParen = beforeColon.indexOf('(');
2229
- const closeParen = beforeColon.lastIndexOf(')');
2230
- if (openParen === -1 || (closeParen > openParen && closeParen === beforeColon.length - 1)) {
2231
- // Colon is after closing paren or no parens at all
2232
- rulePart = beforeColon;
2233
- customMessage = rule.substring(colonIndex + 1).trim();
2234
- }
2235
- }
2236
- const match = rulePart.match(/^(\w+)(?:\((.*?)\))?$/);
2237
- if (!match)
2238
- continue;
2239
- const [, ruleName, argsStr] = match;
2240
- const args = argsStr ? argsStr.split(',').map(a => a.trim().replace(/['"]/g, '')) : [];
2241
- const validatorFn = validators.get(ruleName);
2242
- if (!validatorFn) {
2243
- console.warn(`[GyosJS] Validator "${ruleName}" not found`);
2244
- continue;
2245
- }
2246
- // Pass context as last argument for validators that need it
2247
- const result = await validatorFn(value, ...args, context);
2248
- if (result !== true) {
2249
- // Priority: inline message > context messages > default validator message
2250
- if (customMessage) {
2251
- return customMessage;
2252
- }
2253
- else if (context?.messages?.[ruleName]) {
2254
- return context.messages[ruleName];
2255
- }
2256
- else {
2257
- return typeof result === 'string' ? result : `Validation failed for ${ruleName}`;
2258
- }
2259
- }
2187
+ function applyEnterTransition(element, scope, interruptLeave = false) {
2188
+ const config = parseTransitionConfig(element, scope);
2189
+ if (!config)
2190
+ return Promise.resolve(true);
2191
+ DEBUG() && console.log('[Transition] Enter with:', config.name, config.duration ? `(${config.duration}ms)` : '', 'on', element.tagName, element.className);
2192
+ const transitionConfig = { ...transitionManager.getConfig(config.name) };
2193
+ if (config.duration) {
2194
+ transitionConfig.duration = config.duration;
2260
2195
  }
2261
- return null;
2196
+ return transitionManager.enter(element, transitionConfig, interruptLeave);
2262
2197
  }
2263
- // ============================================================================
2264
- // Built-in Validators
2265
- // ============================================================================
2266
2198
  /**
2267
- * Required - Field must not be empty
2199
+ * Apply leave transition to an element
2200
+ * Handles transition config parsing and application
2268
2201
  *
2269
- * @example "required"
2202
+ * @param element - Element to apply transition to
2203
+ * @param scope - Current scope for expression evaluation
2204
+ * @returns Promise that resolves when transition completes
2270
2205
  */
2271
- validator('required', (value) => {
2272
- if (value == null || value === '' || (Array.isArray(value) && value.length === 0)) {
2273
- return 'This field is required';
2206
+ function applyLeaveTransition(element, scope, removeElement = true) {
2207
+ const config = parseTransitionConfig(element, scope);
2208
+ if (!config)
2209
+ return Promise.resolve(true);
2210
+ DEBUG() && console.log('[Transition] Leave with:', config.name, config.duration ? `(${config.duration}ms)` : '', 'on', element.tagName, element.className);
2211
+ const transitionConfig = { ...transitionManager.getConfig(config.name) };
2212
+ if (config.duration) {
2213
+ transitionConfig.duration = config.duration;
2274
2214
  }
2275
- return true;
2276
- });
2277
- /**
2278
- * Email - Valid email format
2279
- *
2280
- * @example "email"
2281
- */
2282
- validator('email', (value) => {
2283
- if (!value)
2284
- return true;
2285
- const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
2286
- return emailRegex.test(value) || 'Invalid email address';
2287
- });
2288
- /**
2289
- * Min length - Minimum string/array length
2290
- *
2291
- * @example "minLength(5)"
2292
- */
2293
- validator('minLength', (value, length) => {
2294
- if (!value)
2295
- return true;
2296
- const minLen = parseInt(length);
2297
- return value.length >= minLen || `Minimum length is ${minLen}`;
2298
- });
2299
- /**
2300
- * Max length - Maximum string/array length
2301
- *
2302
- * @example "maxLength(100)"
2303
- */
2304
- validator('maxLength', (value, length) => {
2305
- if (!value)
2306
- return true;
2307
- const maxLen = parseInt(length);
2308
- return value.length <= maxLen || `Maximum length is ${maxLen}`;
2309
- });
2215
+ return transitionManager.leave(element, transitionConfig, removeElement);
2216
+ }
2217
+
2310
2218
  /**
2311
- * Min - Minimum numeric value
2312
- *
2313
- * @example "min(18)"
2219
+ * Directive Processing
2220
+ * Handles built-in directives (g-show, g-html, g-text) and custom directives
2314
2221
  */
2315
- validator('min', (value, min) => {
2316
- if (!value)
2317
- return true;
2318
- const minVal = parseFloat(min);
2319
- return parseFloat(value) >= minVal || `Minimum value is ${minVal}`;
2320
- });
2321
2222
  /**
2322
- * Max - Maximum numeric value
2223
+ * Process built-in and custom directives
2323
2224
  *
2324
- * @example "max(100)"
2325
- */
2326
- validator('max', (value, max) => {
2327
- if (!value)
2328
- return true;
2329
- const maxVal = parseFloat(max);
2330
- return parseFloat(value) <= maxVal || `Maximum value is ${maxVal}`;
2331
- });
2332
- /**
2333
- * Number - Must be a valid number
2225
+ * Built-in directives:
2226
+ * - g-show: Toggle element visibility
2227
+ * - g-html: Set innerHTML reactively
2228
+ * - g-text: Set textContent reactively
2334
2229
  *
2335
- * @example "number"
2336
- */
2337
- validator('number', (value) => {
2338
- if (!value)
2339
- return true;
2340
- return !isNaN(parseFloat(value)) && isFinite(value) || 'Must be a number';
2341
- });
2342
- /**
2343
- * Integer - Must be a valid integer
2230
+ * Custom directives: Registered via Gyos.directive()
2344
2231
  *
2345
- * @example "integer"
2232
+ * @param el - Root element to process
2233
+ * @param scope - Scope object for evaluation
2346
2234
  */
2347
- validator('integer', (value) => {
2348
- if (!value)
2349
- return true;
2350
- return Number.isInteger(parseFloat(value)) || 'Must be an integer';
2351
- });
2352
- /**
2353
- * Numeric - Must contain only digits
2354
- *
2355
- * @example "numeric"
2356
- */
2357
- validator('numeric', (value) => {
2358
- if (!value)
2359
- return true;
2360
- return /^\d+$/.test(value) || 'Must contain only digits';
2361
- });
2362
- /**
2363
- * Alpha - Must contain only letters
2364
- *
2365
- * @example "alpha"
2366
- */
2367
- validator('alpha', (value) => {
2368
- if (!value)
2369
- return true;
2370
- return /^[a-zA-Z]+$/.test(value) || 'Must contain only letters';
2371
- });
2372
- /**
2373
- * Alphanumeric - Must contain only letters and numbers
2374
- *
2375
- * @example "alphanumeric"
2376
- */
2377
- validator('alphanumeric', (value) => {
2378
- if (!value)
2379
- return true;
2380
- return /^[a-zA-Z0-9]+$/.test(value) || 'Must contain only letters and numbers';
2381
- });
2382
- /**
2383
- * Pattern - Must match regex pattern
2384
- *
2385
- * @example "pattern(^[A-Z]{3}$)"
2386
- */
2387
- validator('pattern', (value, pattern) => {
2388
- if (!value)
2389
- return true;
2390
- const regex = new RegExp(pattern);
2391
- return regex.test(value) || 'Invalid format';
2392
- });
2393
- /**
2394
- * Same - Must match another field value
2395
- *
2396
- * @example "same(password)" - Useful for password confirmation
2397
- */
2398
- validator('same', (value, fieldName, context) => {
2399
- if (!value)
2400
- return true;
2401
- if (!context?.form) {
2402
- console.warn('[GyosJS] "same" validator requires form context');
2403
- return true;
2404
- }
2405
- const otherValue = context.form[fieldName];
2406
- return value === otherValue || `Must match ${fieldName}`;
2407
- });
2408
- /**
2409
- * Different - Must not match another field value
2410
- *
2411
- * @example "different(oldPassword)"
2412
- */
2413
- validator('different', (value, fieldName, context) => {
2414
- if (!value)
2415
- return true;
2416
- if (!context?.form) {
2417
- console.warn('[GyosJS] "different" validator requires form context');
2418
- return true;
2235
+ function processDirectives(element, scope, root) {
2236
+ if (isInIgnoredTree(element))
2237
+ return;
2238
+ // Skip if inside g-static parent
2239
+ if (isInStaticParent(element, root))
2240
+ return;
2241
+ // Built-in directives: g-show
2242
+ if (element.hasAttribute('g-show')) {
2243
+ const expr = element.getAttribute('g-show');
2244
+ const originalDisplay = element.style.display === 'none' ? '' : element.style.display;
2245
+ let initialized = false;
2246
+ let runId = 0;
2247
+ queueReactiveEffect(element, () => {
2248
+ const value = evaluateExpression(expr, scope);
2249
+ const visible = Boolean(value);
2250
+ const currentRun = ++runId;
2251
+ transitionManager.cancel(element);
2252
+ if (!initialized) {
2253
+ initialized = true;
2254
+ element.style.display = visible ? originalDisplay : 'none';
2255
+ return () => transitionManager.cancel(element);
2256
+ }
2257
+ if (!parseTransitionConfig(element, scope)) {
2258
+ element.style.display = visible ? originalDisplay : 'none';
2259
+ return () => transitionManager.cancel(element);
2260
+ }
2261
+ if (visible) {
2262
+ element.style.display = originalDisplay;
2263
+ void applyEnterTransition(element, scope, true);
2264
+ }
2265
+ else if (element.style.display !== 'none') {
2266
+ void applyLeaveTransition(element, scope, false).then(completed => {
2267
+ if (completed !== false && currentRun === runId)
2268
+ element.style.display = 'none';
2269
+ });
2270
+ }
2271
+ return () => transitionManager.cancel(element);
2272
+ });
2419
2273
  }
2420
- const otherValue = context.form[fieldName];
2421
- return value !== otherValue || `Must be different from ${fieldName}`;
2422
- });
2423
- /**
2424
- * URL - Valid URL format
2425
- *
2426
- * @example "url"
2427
- */
2428
- validator('url', (value) => {
2429
- if (!value)
2430
- return true;
2431
- try {
2432
- new URL(value);
2433
- return true;
2274
+ // g-html: Set innerHTML
2275
+ if (element.hasAttribute('g-html')) {
2276
+ const expr = element.getAttribute('g-html');
2277
+ queueReactiveEffect(element, () => {
2278
+ const value = evaluateExpression(expr, scope);
2279
+ element.innerHTML = value;
2280
+ });
2434
2281
  }
2435
- catch {
2436
- return 'Invalid URL';
2282
+ // g-text: Set textContent
2283
+ if (element.hasAttribute('g-text')) {
2284
+ const expr = element.getAttribute('g-text');
2285
+ queueReactiveEffect(element, () => {
2286
+ const value = evaluateExpression(expr, scope);
2287
+ element.textContent = value;
2288
+ });
2437
2289
  }
2438
- });
2290
+ // Process custom directives (g-focus, g-tooltip, g-clickoutside, etc.)
2291
+ Array.from(element.attributes).forEach(attr => {
2292
+ // Skip built-in and framework directives
2293
+ if (attr.name.startsWith('g-') &&
2294
+ !['g-scope', 'g-show', 'g-html', 'g-text', 'g-model', 'g-static', 'g-portal', 'g-transition', 'g-hydrate', 'g-provide'].includes(attr.name)) {
2295
+ const directiveName = attr.name.slice(2).replace(/:.+$/, ''); // Remove 'g-' prefix and any arguments
2296
+ const directive = getDirective(directiveName);
2297
+ const args = attr.name.split(':');
2298
+ let arg = undefined;
2299
+ if (args.length > 1)
2300
+ arg = args.slice(1); // Get arguments as array
2301
+ if (directive) {
2302
+ // g-on needs the handler itself. The general evaluator intentionally
2303
+ // 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
2309
+ let oldValue = directive.mounted ? value : undefined;
2310
+ let initialized = !directive.mounted;
2311
+ // Call mounted hook
2312
+ if (directive.mounted) {
2313
+ directive.mounted(element, {
2314
+ value, arg,
2315
+ oldValue: undefined,
2316
+ }, scope);
2317
+ }
2318
+ if (directive.unmounted) {
2319
+ let active = true;
2320
+ const cleanup = () => {
2321
+ if (!active)
2322
+ return;
2323
+ active = false;
2324
+ directive.unmounted(element);
2325
+ };
2326
+ if (!element.__gyos_effects__) {
2327
+ element.__gyos_effects__ = [];
2328
+ }
2329
+ element.__gyos_effects__.push(cleanup);
2330
+ }
2331
+ // Setup reactive update if has updated hook
2332
+ if (directive.updated) {
2333
+ queueReactiveEffect(element, () => {
2334
+ const newValue = evaluateExpression(attr.value, scope, false);
2335
+ if (!initialized) {
2336
+ initialized = true;
2337
+ oldValue = newValue;
2338
+ return;
2339
+ }
2340
+ if (Object.is(oldValue, newValue))
2341
+ return;
2342
+ directive.updated(element, {
2343
+ value: newValue,
2344
+ oldValue,
2345
+ arg,
2346
+ }, scope);
2347
+ oldValue = newValue;
2348
+ });
2349
+ }
2350
+ }
2351
+ }
2352
+ });
2353
+ }
2439
2354
  /**
2440
- * Phone - Valid Vietnamese phone format (0xxxxxxxxx)
2355
+ * Process static directives (no reactivity)
2441
2356
  *
2442
- * @example "phone"
2357
+ * @param el - Root element to process
2358
+ * @param scope - Scope object for evaluation
2443
2359
  */
2444
- validator('phone', (value) => {
2445
- if (!value)
2446
- return true;
2447
- const phoneRegex = /^0\d{9}$/;
2448
- return phoneRegex.test(value) || 'Invalid phone number (format: 0xxxxxxxxx)';
2449
- });
2360
+ function processDirectivesStatic(el, scope) {
2361
+ const directives = Array.from(el.querySelectorAll('[g-show], [g-html], [g-text]'))
2362
+ .filter(element => !isInIgnoredTree(element));
2363
+ directives.forEach(elem => {
2364
+ const element = elem;
2365
+ // g-show
2366
+ if (element.hasAttribute('g-show')) {
2367
+ const expr = element.getAttribute('g-show');
2368
+ const value = evaluateExpression(expr, scope);
2369
+ element.style.display = value ? '' : 'none';
2370
+ }
2371
+ // g-html
2372
+ if (element.hasAttribute('g-html')) {
2373
+ const expr = element.getAttribute('g-html');
2374
+ const value = evaluateExpression(expr, scope);
2375
+ element.innerHTML = value;
2376
+ }
2377
+ // g-text
2378
+ if (element.hasAttribute('g-text')) {
2379
+ const expr = element.getAttribute('g-text');
2380
+ const value = evaluateExpression(expr, scope);
2381
+ element.textContent = value;
2382
+ }
2383
+ });
2384
+ }
2385
+
2450
2386
  /**
2451
- * Date - Valid date format (YYYY-MM-DD)
2452
- *
2453
- * @example "date"
2387
+ * Reactive attribute bindings (:class, :style, :aria-*, :data-*, and custom attributes).
2454
2388
  */
2455
- validator('date', (value) => {
2456
- if (!value)
2457
- return true;
2458
- const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
2459
- if (!dateRegex.test(value)) {
2460
- return 'Invalid date format (use YYYY-MM-DD)';
2389
+ function handleClassBinding(el, value) {
2390
+ if (typeof value === 'string') {
2391
+ el.className = value;
2461
2392
  }
2462
- const date = new Date(value);
2463
- return !isNaN(date.getTime()) || 'Invalid date';
2464
- });
2465
- /**
2466
- * Before - Date must be before specified date
2467
- *
2468
- * @example "before(2025-12-31)"
2469
- */
2470
- validator('before', (value, targetDate) => {
2471
- if (!value)
2472
- return true;
2473
- const date = new Date(value);
2474
- const target = new Date(targetDate);
2475
- return date < target || `Must be before ${targetDate}`;
2476
- });
2477
- /**
2478
- * After - Date must be after specified date
2479
- *
2480
- * @example "after(2025-01-01)"
2481
- */
2482
- validator('after', (value, targetDate) => {
2483
- if (!value)
2484
- return true;
2485
- const date = new Date(value);
2486
- const target = new Date(targetDate);
2487
- return date > target || `Must be after ${targetDate}`;
2488
- });
2489
- /**
2490
- * Password - Strong password (uppercase, lowercase, number, min 8 chars)
2491
- *
2492
- * @example "password"
2493
- */
2494
- validator('password', (value) => {
2495
- if (!value)
2496
- return true;
2497
- if (value.length < 8) {
2498
- return 'Password must be at least 8 characters';
2393
+ else if (value && typeof value === 'object') {
2394
+ Object.entries(value).forEach(([className, condition]) => {
2395
+ el.classList.toggle(className, Boolean(condition));
2396
+ });
2499
2397
  }
2500
- const hasUpper = /[A-Z]/.test(value);
2501
- const hasLower = /[a-z]/.test(value);
2502
- const hasNumber = /[0-9]/.test(value);
2503
- if (!hasUpper) {
2504
- return 'Password must contain at least one uppercase letter';
2398
+ }
2399
+ function handleStyleBinding(el, value) {
2400
+ if (typeof value === 'string') {
2401
+ el.setAttribute('style', value);
2505
2402
  }
2506
- if (!hasLower) {
2507
- return 'Password must contain at least one lowercase letter';
2403
+ else if (value && typeof value === 'object') {
2404
+ Object.entries(value).forEach(([property, propertyValue]) => {
2405
+ el.style[property] = propertyValue ?? '';
2406
+ });
2508
2407
  }
2509
- if (!hasNumber) {
2510
- return 'Password must contain at least one number';
2408
+ else if (value == null || value === false) {
2409
+ el.removeAttribute('style');
2410
+ }
2411
+ }
2412
+ const booleanAttributes = new Set([
2413
+ 'allowfullscreen', 'async', 'autofocus', 'autoplay', 'checked', 'controls',
2414
+ 'defer', 'disabled', 'formnovalidate', 'hidden', 'inert', 'ismap', 'itemscope',
2415
+ 'loop', 'multiple', 'muted', 'nomodule', 'novalidate', 'open', 'playsinline',
2416
+ 'readonly', 'required', 'reversed', 'selected'
2417
+ ]);
2418
+ const booleanPropertyNames = {
2419
+ allowfullscreen: 'allowFullscreen',
2420
+ formnovalidate: 'formNoValidate',
2421
+ ismap: 'isMap',
2422
+ itemscope: 'itemScope',
2423
+ nomodule: 'noModule',
2424
+ novalidate: 'noValidate',
2425
+ playsinline: 'playsInline',
2426
+ readonly: 'readOnly'
2427
+ };
2428
+ const urlAttributes = new Set(['action', 'background', 'cite', 'formaction', 'href', 'poster', 'src', 'xlink:href']);
2429
+ const activeUrlElements = new Set(['BASE', 'EMBED', 'IFRAME', 'LINK', 'OBJECT', 'SCRIPT']);
2430
+ function isAllowedBindingName(attrName) {
2431
+ const normalized = attrName.toLowerCase();
2432
+ if (!normalized || normalized.startsWith('@') || normalized.startsWith(':') || normalized.startsWith('*'))
2433
+ return false;
2434
+ if (/^on/i.test(normalized) || normalized === 'srcdoc' || normalized === 'xmlns')
2435
+ return false;
2436
+ return !normalized.startsWith('g-') && !normalized.startsWith('gd-') && !normalized.startsWith('gm-');
2437
+ }
2438
+ function isSafeBoundUrl(element, attrName, value) {
2439
+ if (!urlAttributes.has(attrName)) {
2440
+ return !(attrName === 'data' && element.tagName === 'OBJECT');
2511
2441
  }
2512
- return true;
2513
- });
2514
- /**
2515
- * In - Value must be in allowed list
2516
- *
2517
- * @example "in(red,green,blue)"
2518
- */
2519
- validator('in', (value, ...allowedValues) => {
2520
- if (!value)
2521
- return true;
2522
- // Remove context if it's the last argument
2523
- const values = allowedValues.filter(v => typeof v === 'string' || typeof v === 'number');
2524
- return values.includes(value) || `Must be one of: ${values.join(', ')}`;
2525
- });
2526
- /**
2527
- * NotIn - Value must not be in forbidden list
2528
- *
2529
- * @example "notIn(admin,root,system)"
2530
- */
2531
- validator('notIn', (value, ...forbiddenValues) => {
2532
- if (!value)
2442
+ if (value === null || value === undefined || value === false)
2533
2443
  return true;
2534
- const values = forbiddenValues.filter(v => typeof v === 'string' || typeof v === 'number');
2535
- return !values.includes(value) || `Cannot be: ${values.join(', ')}`;
2536
- });
2537
- /**
2538
- * Between - Numeric value must be between min and max
2539
- *
2540
- * @example "between(18,65)"
2541
- */
2542
- validator('between', (value, min, max) => {
2543
- if (!value)
2444
+ if (activeUrlElements.has(element.tagName))
2445
+ return false;
2446
+ const normalized = String(value).trim().replace(/[\u0000-\u0020]+/g, '').toLowerCase();
2447
+ if (normalized.startsWith('javascript:') || normalized.startsWith('vbscript:'))
2448
+ return false;
2449
+ if (!normalized.startsWith('data:'))
2544
2450
  return true;
2545
- const num = parseFloat(value);
2546
- const minVal = parseFloat(min);
2547
- const maxVal = parseFloat(max);
2548
- return (num >= minVal && num <= maxVal) || `Must be between ${minVal} and ${maxVal}`;
2549
- });
2550
-
2551
- /**
2552
- * Form Validation Directives
2553
- * Provides g-form, g-validate, and g-errors directives for reactive form validation
2554
- */
2555
- const formStates = new WeakMap();
2556
- const formValidators = new WeakMap();
2557
- const validationFieldKey = Symbol('gyos.validation-field');
2558
- function getFieldName(el) {
2559
- const storedName = el[validationFieldKey];
2560
- if (storedName)
2561
- return storedName;
2562
- const modelAttr = Array.from(el.attributes).find(attr => attr.name === 'g-model' || attr.name.startsWith('g-model.'));
2563
- return modelAttr?.value || el.getAttribute('name') || el.id;
2451
+ return attrName === 'src'
2452
+ && element instanceof HTMLImageElement
2453
+ && /^data:image\/(?:png|gif|jpe?g|webp|avif);base64,/i.test(normalized);
2564
2454
  }
2565
- /**
2566
- * Get or create form validation state
2567
- */
2568
- function getFormState(form) {
2569
- if (!formStates.has(form)) {
2570
- // Create reactive state using signals
2571
- formStates.set(form, {
2572
- errors: signal({}),
2573
- touched: signal({}),
2574
- $invalid: signal(false),
2575
- $valid: signal(true),
2576
- $dirty: signal(false), // dirty when any field touched
2577
- $pristine: signal(true) // pristine when no fields touched
2578
- });
2455
+ function syncBooleanProperty(element, attrName, value) {
2456
+ const propertyName = booleanPropertyNames[attrName] || attrName;
2457
+ if (propertyName in element) {
2458
+ try {
2459
+ element[propertyName] = value;
2460
+ }
2461
+ catch {
2462
+ // Some reflected DOM properties are read-only in older engines.
2463
+ }
2579
2464
  }
2580
- return formStates.get(form);
2581
2465
  }
2582
- /**
2583
- * Update form computed properties
2584
- * Only updates when values actually change
2585
- */
2586
- function updateFormState(state) {
2587
- const errors = state.errors.value;
2588
- const touched = state.touched.value;
2589
- const hasErrors = Object.values(errors).some(error => error !== null);
2590
- const anyTouched = Object.values(touched).some(t => t);
2591
- // Only update if changed
2592
- if (state.$invalid.value !== hasErrors) {
2593
- state.$invalid.value = hasErrors;
2594
- state.$valid.value = !hasErrors;
2466
+ function applyAttributeBinding(element, rawAttrName, value) {
2467
+ const attrName = rawAttrName.toLowerCase();
2468
+ if (!isAllowedBindingName(attrName)) {
2469
+ element.removeAttribute(attrName);
2470
+ DEBUG() && console.warn(`[GyosJS] Blocked unsafe :${attrName} binding`);
2471
+ return;
2595
2472
  }
2596
- if (state.$dirty.value !== anyTouched) {
2597
- state.$dirty.value = anyTouched;
2598
- state.$pristine.value = !anyTouched;
2473
+ if (!isSafeBoundUrl(element, attrName, value)) {
2474
+ element.removeAttribute(attrName);
2475
+ DEBUG() && console.warn(`[GyosJS] Blocked unsafe :${attrName} URL`);
2476
+ return;
2599
2477
  }
2600
- }
2601
- /**
2602
- * Process g-form directive
2603
- * Binds form validation state to scope
2604
- *
2605
- * @example
2606
- * <form g-form="formData">
2607
- * <button :disabled="formData.$invalid">Submit</button>
2608
- * </form>
2609
- */
2610
- function processFormDirective(form, scope) {
2611
- const formName = form.getAttribute('g-form');
2612
- if (!formName || hasUnsafePropertyPath(formName))
2478
+ if (booleanAttributes.has(attrName)) {
2479
+ const enabled = Boolean(value);
2480
+ element.toggleAttribute(attrName, enabled);
2481
+ syncBooleanProperty(element, attrName, enabled);
2613
2482
  return;
2614
- form.removeAttribute('g-form');
2615
- const state = getFormState(form);
2616
- // Create validateAll function
2617
- const validateAll = async () => {
2618
- const validators = formValidators.get(form) || [];
2619
- const touchedObj = { ...state.touched.value };
2620
- Object.keys(touchedObj).forEach(fieldName => {
2621
- touchedObj[fieldName] = true;
2622
- });
2623
- // Trigger signal update once
2624
- state.touched.value = { ...touchedObj };
2625
- // Run all validators in parallel
2626
- await Promise.all(validators.map(validator => validator()));
2627
- updateFormState(state);
2628
- return !state.$invalid.value;
2629
- };
2630
- state.validateAll = validateAll;
2631
- // Directly assign signals to scope properties
2632
- // Scope will wrap these in signals automatically during component mounting
2633
- const formStateObj = {
2634
- errors: state.errors,
2635
- touched: state.touched,
2636
- $invalid: state.$invalid,
2637
- $valid: state.$valid,
2638
- $dirty: state.$dirty,
2639
- $pristine: state.$pristine,
2640
- validateAll: validateAll
2641
- };
2642
- if (!(formName in scope)) {
2643
- scope[formName] = formStateObj;
2644
2483
  }
2645
- else {
2646
- // Merge signals into existing object
2647
- Object.assign(scope[formName], formStateObj);
2484
+ if (value === null || value === undefined || (value === false && !attrName.startsWith('aria-') && !attrName.startsWith('data-'))) {
2485
+ element.removeAttribute(attrName);
2486
+ return;
2648
2487
  }
2649
- // Prevent default form submission and validate first
2650
- const submitListener = async (e) => {
2651
- e.preventDefault();
2652
- const isValid = await validateAll();
2653
- if (!isValid)
2654
- return;
2655
- const submitMethod = form.getAttribute('g-submit');
2656
- // If not defined, submit the form normally
2657
- if (!submitMethod) {
2658
- form.submit();
2659
- return;
2660
- }
2661
- // Trigger custom submit handler if exists
2662
- const submitHandler = scope[submitMethod];
2663
- if (typeof submitHandler === 'function') {
2664
- submitHandler.call(scope);
2488
+ const stringValue = String(value);
2489
+ if (attrName === 'value' && 'value' in element) {
2490
+ element.value = stringValue;
2491
+ }
2492
+ element.setAttribute(attrName, stringValue);
2493
+ }
2494
+ function boundAttributes(element) {
2495
+ return Array.from(element.attributes).filter(attribute => attribute.name.startsWith(':'));
2496
+ }
2497
+ function processBindings(element, scope, root) {
2498
+ if (isInIgnoredTree(element) || isInStaticParent(element, root))
2499
+ return;
2500
+ if (element.hasAttribute('*if') || element.hasAttribute('*for'))
2501
+ return;
2502
+ for (const attribute of boundAttributes(element)) {
2503
+ const attrName = attribute.name.slice(1);
2504
+ const expression = attribute.value;
2505
+ queueReactiveEffect(element, () => {
2506
+ const currentScope = getScopeFromElement(element) || scope;
2507
+ const value = evaluateExpression(expression, currentScope);
2508
+ if (attrName === 'class')
2509
+ handleClassBinding(element, value);
2510
+ else if (attrName === 'style')
2511
+ handleStyleBinding(element, value);
2512
+ else
2513
+ applyAttributeBinding(element, attrName, value);
2514
+ });
2515
+ }
2516
+ }
2517
+ function processBindingsStatic(root, scope) {
2518
+ const elements = [root, ...walkerDOM(root, element => !isInIgnoredTree(element), NodeFilter.FILTER_REJECT)];
2519
+ for (const element of elements) {
2520
+ if (isInIgnoredTree(element))
2521
+ continue;
2522
+ for (const attribute of boundAttributes(element)) {
2523
+ const attrName = attribute.name.slice(1);
2524
+ const value = evaluateExpression(attribute.value, scope);
2525
+ if (attrName === 'class')
2526
+ handleClassBinding(element, value);
2527
+ else if (attrName === 'style')
2528
+ handleStyleBinding(element, value);
2529
+ else
2530
+ applyAttributeBinding(element, attrName, value);
2665
2531
  }
2666
- };
2667
- form.addEventListener('submit', submitListener);
2668
- if (!form.__gyos_effects__) {
2669
- form.__gyos_effects__ = [];
2670
2532
  }
2671
- form.__gyos_effects__.push(() => {
2672
- form.removeEventListener('submit', submitListener);
2673
- formStates.delete(form);
2674
- formValidators.delete(form);
2675
- });
2676
2533
  }
2534
+
2677
2535
  /**
2678
- * Process g-validate directive on input elements
2679
- * Validates input value against rules and updates form state
2536
+ * Portal/Teleport System - Render content in different DOM location
2537
+ * Useful for modals, tooltips, notifications that need to break out of parent containers
2680
2538
  *
2681
2539
  * @example
2682
- * <input g-model="email" g-validate="required|email">
2683
- * <input g-model="password" g-validate="required|minLength(8)|password">
2540
+ * // Portal to body (for modals)
2541
+ * <div g-portal="body">
2542
+ * <div class="modal">Modal content</div>
2543
+ * </div>
2544
+ *
2545
+ * @example
2546
+ * // Portal to specific element
2547
+ * <div g-portal="#notifications">
2548
+ * <div class="toast">Toast message</div>
2549
+ * </div>
2684
2550
  */
2685
- function processValidateDirective(el) {
2686
- if (!(el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement || el instanceof HTMLSelectElement)) {
2687
- return;
2688
- }
2689
- const rules = el.getAttribute('g-validate');
2690
- if (!rules)
2691
- return;
2692
- el.removeAttribute('g-validate');
2693
- // Get field name from g-model attribute
2694
- const modelAttr = getFieldName(el);
2695
- if (!modelAttr)
2551
+ /**
2552
+ * Create a portal - Move element to target location
2553
+ *
2554
+ * @param sourceEl - Element to teleport
2555
+ * @param targetSelector - CSS selector for destination
2556
+ *
2557
+ * @example
2558
+ * portalCreate(modalEl, 'body');
2559
+ * portalCreate(tooltipEl, '#tooltip-container');
2560
+ */
2561
+ function portalCreate(sourceEl, targetSelector) {
2562
+ if (!sourceEl)
2696
2563
  return;
2697
- el[validationFieldKey] = modelAttr;
2698
- // Find parent form
2699
- const form = el.closest('form');
2700
- if (!form)
2564
+ const target = document.querySelector(targetSelector);
2565
+ if (!target) {
2566
+ console.warn(`[GyosJS] Portal target "${targetSelector}" not found`);
2701
2567
  return;
2702
- const state = getFormState(form);
2703
- // Initialize error state - direct mutation
2704
- state.errors.value[modelAttr] = null;
2705
- state.touched.value[modelAttr] = false;
2706
- // Validation function
2707
- const validateField = async () => {
2708
- const value = el.value;
2709
- // Get form context for validators that need it (like 'same')
2710
- const formData = {};
2711
- const formInputs = form.querySelectorAll('input, textarea, select');
2712
- formInputs.forEach(input => {
2713
- if (isInIgnoredTree(input))
2714
- return;
2715
- if (input instanceof HTMLInputElement || input instanceof HTMLTextAreaElement || input instanceof HTMLSelectElement) {
2716
- const fieldName = getFieldName(input);
2717
- if (fieldName) {
2718
- formData[fieldName] = input.value;
2719
- }
2720
- }
2721
- });
2722
- const error = await validate(value, rules, { form: formData, field: modelAttr });
2723
- // Update errors - only if changed
2724
- const currentErrors = state.errors.value;
2725
- if (currentErrors[modelAttr] !== error) {
2726
- currentErrors[modelAttr] = error;
2727
- // Trigger reactivity by reassigning
2728
- state.errors.value = { ...currentErrors };
2729
- updateFormState(state);
2730
- }
2731
- };
2732
- // Register validator for validateAll
2733
- if (!formValidators.has(form)) {
2734
- formValidators.set(form, []);
2735
2568
  }
2736
- formValidators.get(form).push(validateField);
2737
- // Mark as touched on blur
2738
- const blurListener = () => {
2739
- const touchedObj = state.touched.value;
2740
- if (!touchedObj[modelAttr]) {
2741
- touchedObj[modelAttr] = true;
2742
- state.touched.value = { ...touchedObj };
2743
- updateFormState(state);
2744
- }
2745
- validateField();
2746
- };
2747
- el.addEventListener('blur', blurListener);
2748
- // Validate on input (with debounce)
2749
- let timeout;
2750
- const inputListener = () => {
2751
- clearTimeout(timeout);
2752
- timeout = setTimeout(() => {
2753
- validateField();
2754
- }, 300);
2755
- };
2756
- el.addEventListener('input', inputListener);
2757
- if (!el.__gyos_effects__) {
2758
- el.__gyos_effects__ = [];
2569
+ // Create placeholder comment to mark original position
2570
+ const placeholder = document.createComment('g-portal');
2571
+ sourceEl.parentNode?.insertBefore(placeholder, sourceEl);
2572
+ // Store original parent for restoration
2573
+ sourceEl.__portal_placeholder__ = placeholder;
2574
+ sourceEl.__portal_target__ = target;
2575
+ // Move the entire element to target
2576
+ target.appendChild(sourceEl);
2577
+ DEBUG() && console.log('[Portal] Created - moved element to', targetSelector);
2578
+ }
2579
+ /**
2580
+ * Destroy a portal - Restore element to original position
2581
+ *
2582
+ * @param sourceEl - Element to restore
2583
+ *
2584
+ * @example
2585
+ * portalDestroy(modalEl); // Returns modal to original location
2586
+ */
2587
+ function portalDestroy(sourceEl) {
2588
+ if (!sourceEl)
2589
+ return;
2590
+ const placeholder = sourceEl.__portal_placeholder__;
2591
+ if (placeholder && placeholder.parentNode) {
2592
+ // Move element back to original position
2593
+ placeholder.parentNode.insertBefore(sourceEl, placeholder);
2594
+ placeholder.remove();
2595
+ delete sourceEl.__portal_placeholder__;
2596
+ delete sourceEl.__portal_target__;
2597
+ DEBUG() && console.log('[Portal] Destroyed - restored element to original position');
2759
2598
  }
2760
- el.__gyos_effects__.push(() => {
2761
- el.removeEventListener('blur', blurListener);
2762
- el.removeEventListener('input', inputListener);
2763
- clearTimeout(timeout);
2764
- });
2765
2599
  }
2600
+
2766
2601
  /**
2767
- * Process g-errors directive
2768
- * Displays validation errors for a specific field or all fields
2602
+ * Validator registry
2603
+ */
2604
+ const validators = new Map();
2605
+ /**
2606
+ * Register a custom validator
2607
+ *
2608
+ * @param name - Validator name
2609
+ * @param fn - Validator function (return true for valid, string for error message)
2769
2610
  *
2770
2611
  * @example
2771
- * <!-- Show errors for specific field -->
2772
- * <span g-errors="email" class="error"></span>
2612
+ * ```javascript
2613
+ * Gyos.validator('even', (value) => {
2614
+ * return value % 2 === 0 || 'Must be an even number';
2615
+ * });
2616
+ * ```
2617
+ */
2618
+ function validator(name, fn) {
2619
+ validators.set(name, fn);
2620
+ }
2621
+ /**
2622
+ * Get registered validator by name
2773
2623
  *
2774
- * <!-- Show all form errors -->
2775
- * <div g-errors class="error-summary"></div>
2624
+ * @param name - Validator name
2625
+ * @returns Validator function or undefined
2776
2626
  */
2777
- function processErrorsDirective(el) {
2778
- const fieldName = el.getAttribute('g-errors');
2779
- el.removeAttribute('g-errors');
2780
- // Find parent form
2781
- const form = el.closest('form');
2782
- if (!form)
2783
- return;
2784
- const state = getFormState(form);
2785
- if (fieldName === '' || fieldName === null) {
2786
- // Show all errors
2787
- const dispose = effect(() => {
2788
- const errors = state.errors.value;
2789
- const errorEntries = Object.entries(errors).filter(([_, error]) => error !== null);
2790
- el.replaceChildren(...errorEntries.map(([field, error]) => {
2791
- const row = document.createElement('div');
2792
- const label = document.createElement('strong');
2793
- label.textContent = `${field}:`;
2794
- row.append(label, document.createTextNode(` ${String(error)}`));
2795
- return row;
2796
- }));
2797
- el.style.display = errorEntries.length ? '' : 'none';
2798
- });
2799
- if (!el.__gyos_effects__) {
2800
- el.__gyos_effects__ = [];
2627
+ function getValidator(name) {
2628
+ return validators.get(name);
2629
+ }
2630
+ /**
2631
+ * Get all registered validator names
2632
+ *
2633
+ * @returns Array of validator names
2634
+ *
2635
+ * @example
2636
+ * ```javascript
2637
+ * console.log('Available validators:', Gyos.getValidatorNames());
2638
+ * // ['required', 'email', 'minLength', ...]
2639
+ * ```
2640
+ */
2641
+ function getValidatorNames() {
2642
+ return Array.from(validators.keys());
2643
+ }
2644
+ /**
2645
+ * Validate a value against validation rules
2646
+ *
2647
+ * Supports custom error messages in two ways:
2648
+ * 1. Inline: "required:Custom message|email:Invalid email"
2649
+ * 2. Via context: { messages: { required: "Custom message" } }
2650
+ *
2651
+ * @param value - Value to validate
2652
+ * @param rules - Validation rules (pipe-separated: "required|email|minLength(5)")
2653
+ * @param context - Optional context with form data and custom messages
2654
+ * @returns Error message or null if valid
2655
+ *
2656
+ * @example Basic validation
2657
+ * ```javascript
2658
+ * const error = await Gyos.validate('test@', 'required|email');
2659
+ * // Returns: "Invalid email address"
2660
+ * ```
2661
+ *
2662
+ * @example Inline custom messages
2663
+ * ```javascript
2664
+ * const error = await Gyos.validate('', 'required:This field is mandatory|email:Enter valid email');
2665
+ * // Returns: "This field is mandatory"
2666
+ * ```
2667
+ *
2668
+ * @example Custom messages via context
2669
+ * ```javascript
2670
+ * const error = await Gyos.validate('abc', 'required|minLength(5)', {
2671
+ * messages: {
2672
+ * required: 'Please fill this field',
2673
+ * minLength: 'Too short! Need at least 5 characters'
2674
+ * }
2675
+ * });
2676
+ * // Returns: "Too short! Need at least 5 characters"
2677
+ * ```
2678
+ *
2679
+ * @example With form context
2680
+ * ```javascript
2681
+ * const error = await Gyos.validate(confirmPw, 'required|same(password)', {
2682
+ * form: { password: 'MyPass123' },
2683
+ * messages: { same: 'Passwords do not match' }
2684
+ * });
2685
+ * ```
2686
+ */
2687
+ async function validate(value, rules, context) {
2688
+ const ruleParts = rules.split('|');
2689
+ for (const rule of ruleParts) {
2690
+ // Parse rule: "required:Custom message" or "required" or "minLength(5):Custom message"
2691
+ const colonIndex = rule.lastIndexOf(':');
2692
+ let rulePart = rule;
2693
+ let customMessage;
2694
+ // Check if there's a custom message after colon (but not inside parentheses)
2695
+ if (colonIndex > 0) {
2696
+ const beforeColon = rule.substring(0, colonIndex);
2697
+ // Only treat as custom message if colon is not inside function args
2698
+ const openParen = beforeColon.indexOf('(');
2699
+ const closeParen = beforeColon.lastIndexOf(')');
2700
+ if (openParen === -1 || (closeParen > openParen && closeParen === beforeColon.length - 1)) {
2701
+ // Colon is after closing paren or no parens at all
2702
+ rulePart = beforeColon;
2703
+ customMessage = rule.substring(colonIndex + 1).trim();
2704
+ }
2801
2705
  }
2802
- el.__gyos_effects__.push(dispose);
2803
- }
2804
- else {
2805
- // Show specific field error (removed isTouched check as requested)
2806
- const dispose = effect(() => {
2807
- const errors = state.errors.value;
2808
- const error = errors[fieldName];
2809
- if (error) {
2810
- el.textContent = error;
2811
- el.style.display = '';
2706
+ const match = rulePart.match(/^(\w+)(?:\((.*?)\))?$/);
2707
+ if (!match)
2708
+ continue;
2709
+ const [, ruleName, argsStr] = match;
2710
+ const args = argsStr ? argsStr.split(',').map(a => a.trim().replace(/['"]/g, '')) : [];
2711
+ const validatorFn = validators.get(ruleName);
2712
+ if (!validatorFn) {
2713
+ console.warn(`[GyosJS] Validator "${ruleName}" not found`);
2714
+ continue;
2715
+ }
2716
+ // Pass context as last argument for validators that need it
2717
+ const result = await validatorFn(value, ...args, context);
2718
+ if (result !== true) {
2719
+ // Priority: inline message > context messages > default validator message
2720
+ if (customMessage) {
2721
+ return customMessage;
2722
+ }
2723
+ else if (context?.messages?.[ruleName]) {
2724
+ return context.messages[ruleName];
2812
2725
  }
2813
2726
  else {
2814
- el.textContent = '';
2815
- el.style.display = 'none';
2727
+ return typeof result === 'string' ? result : `Validation failed for ${ruleName}`;
2816
2728
  }
2817
- });
2818
- if (!el.__gyos_effects__) {
2819
- el.__gyos_effects__ = [];
2820
2729
  }
2821
- el.__gyos_effects__.push(dispose);
2822
2730
  }
2731
+ return null;
2823
2732
  }
2733
+ // ============================================================================
2734
+ // Built-in Validators
2735
+ // ============================================================================
2824
2736
  /**
2825
- * Process all form validation directives in an element tree
2737
+ * Required - Field must not be empty
2738
+ *
2739
+ * @example "required"
2826
2740
  */
2827
- function processFormValidation(root, scope) {
2828
- // Process g-form first
2829
- if (root instanceof HTMLFormElement && root.hasAttribute('g-form')) {
2830
- processFormDirective(root, scope);
2741
+ validator('required', (value) => {
2742
+ if (value == null || value === '' || (Array.isArray(value) && value.length === 0)) {
2743
+ return 'This field is required';
2831
2744
  }
2832
- // Then process g-validate
2833
- root.querySelectorAll('[g-validate]').forEach(el => {
2834
- if (isInIgnoredTree(el))
2835
- return;
2836
- if (el instanceof HTMLElement) {
2837
- processValidateDirective(el);
2838
- }
2839
- });
2840
- // Finally process g-errors
2841
- root.querySelectorAll('[g-errors]').forEach(el => {
2842
- if (isInIgnoredTree(el))
2843
- return;
2844
- if (el instanceof HTMLElement) {
2845
- processErrorsDirective(el);
2846
- }
2847
- });
2848
- }
2849
-
2745
+ return true;
2746
+ });
2850
2747
  /**
2851
- * Event Processing
2852
- * Handles @event directives with modifiers (prevent, stop, debounce, key modifiers, etc.)
2748
+ * Email - Valid email format
2749
+ *
2750
+ * @example "email"
2853
2751
  */
2854
- // Reusable key modifier map for performance
2855
- const KEY_MODIFIER_MAP = {
2856
- 'enter': 'enter',
2857
- 'esc': 'escape',
2858
- 'escape': 'escape',
2859
- 'space': ' ',
2860
- 'up': 'arrowup',
2861
- 'down': 'arrowdown',
2862
- 'left': 'arrowleft',
2863
- 'right': 'arrowright',
2864
- 'delete': 'delete',
2865
- 'tab': 'tab',
2866
- };
2867
- // Reserved modifiers that aren't key names
2868
- const RESERVED_MODIFIERS = new Set(['prevent', 'stop', 'once', 'capture', 'passive', 'debounce', 'outside', 'global']);
2752
+ validator('email', (value) => {
2753
+ if (!value)
2754
+ return true;
2755
+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
2756
+ return emailRegex.test(value) || 'Invalid email address';
2757
+ });
2869
2758
  /**
2870
- * Execute handler with modifiers (prevent, stop)
2759
+ * Min length - Minimum string/array length
2760
+ *
2761
+ * @example "minLength(5)"
2871
2762
  */
2872
- function executeHandler(handler, scope, e, modifiers) {
2873
- // Handle prevent/stop modifiers
2874
- if (modifiers.includes('prevent'))
2875
- e.preventDefault();
2876
- if (modifiers.includes('stop'))
2877
- e.stopPropagation();
2878
- try {
2879
- const isMethodCall = handler.includes('(');
2880
- if (isMethodCall) {
2881
- // Method call with args: "doSomething()" or "method(arg1, arg2)"
2882
- const fn = new Function('$event', `with(this) { ${handler} }`);
2883
- fn.call(scope, e);
2884
- }
2885
- else {
2886
- // Check if it's a method name or expression
2887
- const method = scope[handler];
2888
- if (typeof method === 'function') {
2889
- method.call(scope, e);
2890
- }
2891
- else {
2892
- // Expression like "count++", "count = 0"
2893
- const fn = new Function('$event', `with(this) { ${handler} }`);
2894
- fn.call(scope, e);
2895
- }
2896
- }
2897
- }
2898
- catch (err) {
2899
- console.error('[GyosJS] Error in event handler:', err);
2900
- }
2901
- }
2763
+ validator('minLength', (value, length) => {
2764
+ if (!value)
2765
+ return true;
2766
+ const minLen = parseInt(length);
2767
+ return value.length >= minLen || `Minimum length is ${minLen}`;
2768
+ });
2769
+ /**
2770
+ * Max length - Maximum string/array length
2771
+ *
2772
+ * @example "maxLength(100)"
2773
+ */
2774
+ validator('maxLength', (value, length) => {
2775
+ if (!value)
2776
+ return true;
2777
+ const maxLen = parseInt(length);
2778
+ return value.length <= maxLen || `Maximum length is ${maxLen}`;
2779
+ });
2780
+ /**
2781
+ * Min - Minimum numeric value
2782
+ *
2783
+ * @example "min(18)"
2784
+ */
2785
+ validator('min', (value, min) => {
2786
+ if (!value)
2787
+ return true;
2788
+ const minVal = parseFloat(min);
2789
+ return parseFloat(value) >= minVal || `Minimum value is ${minVal}`;
2790
+ });
2791
+ /**
2792
+ * Max - Maximum numeric value
2793
+ *
2794
+ * @example "max(100)"
2795
+ */
2796
+ validator('max', (value, max) => {
2797
+ if (!value)
2798
+ return true;
2799
+ const maxVal = parseFloat(max);
2800
+ return parseFloat(value) <= maxVal || `Maximum value is ${maxVal}`;
2801
+ });
2802
+ /**
2803
+ * Number - Must be a valid number
2804
+ *
2805
+ * @example "number"
2806
+ */
2807
+ validator('number', (value) => {
2808
+ if (!value)
2809
+ return true;
2810
+ return !isNaN(parseFloat(value)) && isFinite(value) || 'Must be a number';
2811
+ });
2812
+ /**
2813
+ * Integer - Must be a valid integer
2814
+ *
2815
+ * @example "integer"
2816
+ */
2817
+ validator('integer', (value) => {
2818
+ if (!value)
2819
+ return true;
2820
+ return Number.isInteger(parseFloat(value)) || 'Must be an integer';
2821
+ });
2822
+ /**
2823
+ * Numeric - Must contain only digits
2824
+ *
2825
+ * @example "numeric"
2826
+ */
2827
+ validator('numeric', (value) => {
2828
+ if (!value)
2829
+ return true;
2830
+ return /^\d+$/.test(value) || 'Must contain only digits';
2831
+ });
2832
+ /**
2833
+ * Alpha - Must contain only letters
2834
+ *
2835
+ * @example "alpha"
2836
+ */
2837
+ validator('alpha', (value) => {
2838
+ if (!value)
2839
+ return true;
2840
+ return /^[a-zA-Z]+$/.test(value) || 'Must contain only letters';
2841
+ });
2842
+ /**
2843
+ * Alphanumeric - Must contain only letters and numbers
2844
+ *
2845
+ * @example "alphanumeric"
2846
+ */
2847
+ validator('alphanumeric', (value) => {
2848
+ if (!value)
2849
+ return true;
2850
+ return /^[a-zA-Z0-9]+$/.test(value) || 'Must contain only letters and numbers';
2851
+ });
2852
+ /**
2853
+ * Pattern - Must match regex pattern
2854
+ *
2855
+ * @example "pattern(^[A-Z]{3}$)"
2856
+ */
2857
+ validator('pattern', (value, pattern) => {
2858
+ if (!value)
2859
+ return true;
2860
+ const regex = new RegExp(pattern);
2861
+ return regex.test(value) || 'Invalid format';
2862
+ });
2902
2863
  /**
2903
- * Check if keyboard event matches key modifiers
2864
+ * Same - Must match another field value
2865
+ *
2866
+ * @example "same(password)" - Useful for password confirmation
2904
2867
  */
2905
- function matchesKeyModifiers(e, modifiers) {
2906
- // Fast path: no key modifiers
2907
- let hasKeyModifiers = false;
2908
- for (const mod of modifiers) {
2909
- if (!RESERVED_MODIFIERS.has(mod) && !/^\d+$/.test(mod)) {
2910
- hasKeyModifiers = true;
2911
- break;
2912
- }
2913
- }
2914
- if (!hasKeyModifiers)
2868
+ validator('same', (value, fieldName, context) => {
2869
+ if (!value)
2915
2870
  return true;
2916
- const key = e.key.toLowerCase();
2917
- // Check against key modifier map
2918
- for (const mod of modifiers) {
2919
- if (RESERVED_MODIFIERS.has(mod) || /^\d+$/.test(mod))
2920
- continue;
2921
- const mappedKey = KEY_MODIFIER_MAP[mod];
2922
- if (mappedKey) {
2923
- if (key === mappedKey)
2924
- return true;
2925
- }
2926
- else if (key === mod.toLowerCase()) {
2927
- return true;
2928
- }
2929
- }
2930
- // Special case: delete can match backspace
2931
- if (key === 'backspace' && modifiers.includes('delete'))
2871
+ if (!context?.form) {
2872
+ console.warn('[GyosJS] "same" validator requires form context');
2932
2873
  return true;
2933
- return false;
2934
- }
2874
+ }
2875
+ const otherValue = context.form[fieldName];
2876
+ return value === otherValue || `Must match ${fieldName}`;
2877
+ });
2935
2878
  /**
2936
- * Get debounce delay from modifiers
2879
+ * Different - Must not match another field value
2880
+ *
2881
+ * @example "different(oldPassword)"
2937
2882
  */
2938
- function getDebounceDelay(modifiers) {
2939
- const debounceIndex = modifiers.findIndex(m => m === 'debounce' || /^\d+$/.test(m));
2940
- if (debounceIndex === -1)
2941
- return 0;
2942
- if (modifiers[debounceIndex] === 'debounce') {
2943
- const nextMod = modifiers[debounceIndex + 1];
2944
- return nextMod && /^\d+$/.test(nextMod) ? parseInt(nextMod) : 300;
2883
+ validator('different', (value, fieldName, context) => {
2884
+ if (!value)
2885
+ return true;
2886
+ if (!context?.form) {
2887
+ console.warn('[GyosJS] "different" validator requires form context');
2888
+ return true;
2945
2889
  }
2946
- return 0;
2947
- }
2890
+ const otherValue = context.form[fieldName];
2891
+ return value !== otherValue || `Must be different from ${fieldName}`;
2892
+ });
2948
2893
  /**
2949
- * Process event handlers (@click, @input, @keyup.enter, etc.)
2950
- *
2951
- * Supports modifiers:
2952
- * - prevent: preventDefault()
2953
- * - stop: stopPropagation()
2954
- * - once: addEventListener with once option
2955
- * - debounce.300: Debounce with custom delay
2956
- * - Key modifiers: enter, esc, space, up, down, left, right, delete, tab
2894
+ * URL - Valid URL format
2957
2895
  *
2958
- * @param el - Root element to process
2959
- * @param scope - Scope object for evaluation
2896
+ * @example "url"
2897
+ */
2898
+ validator('url', (value) => {
2899
+ if (!value)
2900
+ return true;
2901
+ try {
2902
+ new URL(value);
2903
+ return true;
2904
+ }
2905
+ catch {
2906
+ return 'Invalid URL';
2907
+ }
2908
+ });
2909
+ /**
2910
+ * Phone - Valid Vietnamese phone format (0xxxxxxxxx)
2960
2911
  *
2961
- * @example
2962
- * <button @click="handleClick">Click</button>
2963
- * <button @click.prevent="submit">Submit</button>
2964
- * <input @input.debounce.500="search">
2965
- * <input @keyup.enter="submit">
2912
+ * @example "phone"
2966
2913
  */
2914
+ validator('phone', (value) => {
2915
+ if (!value)
2916
+ return true;
2917
+ const phoneRegex = /^0\d{9}$/;
2918
+ return phoneRegex.test(value) || 'Invalid phone number (format: 0xxxxxxxxx)';
2919
+ });
2967
2920
  /**
2968
- * Setup click outside handler with cleanup
2921
+ * Date - Valid date format (YYYY-MM-DD)
2922
+ *
2923
+ * @example "date"
2969
2924
  */
2970
- function setupClickOutsideHandler(element, handler, modifiers, scope, attrName) {
2971
- let active = true;
2972
- let timeoutId;
2973
- const clickOutsideHandler = (e) => {
2974
- // e.stopPropagation(); // Optional: prevent other click handlers
2975
- const target = e.target;
2976
- // Check if click is outside element AND element is still in DOM
2977
- if (!document.body.contains(element) ||
2978
- (target instanceof Element && target.hasAttribute('g-ignore-outside-click'))) {
2979
- // Element removed, cleanup
2980
- cleanup();
2981
- return;
2982
- }
2983
- if (element !== target && !element.contains(target)) {
2984
- const currentScope = getScopeFromElement(element) || scope;
2985
- if (modifiers.includes('once'))
2986
- cleanup();
2987
- executeHandler(handler, currentScope, e, modifiers);
2988
- }
2989
- };
2990
- // Cleanup function
2991
- const cleanup = () => {
2992
- if (!active)
2993
- return;
2994
- active = false;
2995
- if (timeoutId !== undefined) {
2996
- clearTimeout(timeoutId);
2997
- timeoutId = undefined;
2998
- }
2999
- document.removeEventListener('click', clickOutsideHandler, true);
3000
- observer.disconnect();
3001
- };
3002
- // MutationObserver to detect when element is removed from DOM
3003
- const observer = new MutationObserver((mutations) => {
3004
- for (const mutation of mutations) {
3005
- mutation.removedNodes.forEach((node) => {
3006
- const removedWithElement = node === element ||
3007
- (node instanceof Element && node.contains(element));
3008
- if (removedWithElement && !document.body.contains(element)) {
3009
- cleanup();
3010
- }
3011
- });
3012
- }
3013
- });
3014
- // Observe document.body for any removal (including *if removing element)
3015
- observer.observe(document.body, { childList: true, subtree: true });
3016
- // Store cleanup in __gyos_effects__
3017
- if (!element.__gyos_effects__) {
3018
- element.__gyos_effects__ = [];
2925
+ validator('date', (value) => {
2926
+ if (!value)
2927
+ return true;
2928
+ const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
2929
+ if (!dateRegex.test(value)) {
2930
+ return 'Invalid date format (use YYYY-MM-DD)';
3019
2931
  }
3020
- element.__gyos_effects__.push(cleanup);
3021
- // Use setTimeout to avoid triggering on the same click that opens the element
3022
- timeoutId = window.setTimeout(() => {
3023
- if (active)
3024
- document.addEventListener('click', clickOutsideHandler, true);
3025
- }, 0);
3026
- element.removeAttribute(attrName);
3027
- }
3028
- function processEvents(el, scope) {
3029
- // TreeWalker is more efficient than querySelectorAll for large DOMs
3030
- const elementsToProcess = walkerDOM(el, element => !isInIgnoredTree(element) && !element.hasAttribute('g-static'), NodeFilter.FILTER_REJECT);
3031
- elementsToProcess.unshift(el); // Include root element
3032
- elementsToProcess.forEach(element => {
3033
- // Skip if inside g-static parent (double check)
3034
- if (isInStaticParent(element, el))
3035
- return;
3036
- const attrs = Array.from(element.attributes);
3037
- attrs.forEach(attr => {
3038
- if (attr.name.startsWith('@')) {
3039
- // Parse event name and modifiers once
3040
- const parts = attr.name.substring(1).split('.');
3041
- const eventName = parts[0];
3042
- const modifiers = parts.slice(1);
3043
- const handler = attr.value;
3044
- // Handle @click.outside modifier
3045
- if (modifiers.includes('outside')) {
3046
- setupClickOutsideHandler(element, handler, modifiers, scope, attr.name);
3047
- return; // Skip normal event binding
3048
- }
3049
- // Setup event handler with debounce support
3050
- const debounceMs = getDebounceDelay(modifiers);
3051
- const isKeyEvent = eventName === 'keyup' || eventName === 'keydown' || eventName === 'keypress';
3052
- // Create dedicated debounce context per element-event pair
3053
- const debounceContext = { timeoutId: 0 };
3054
- let cleanup = () => { };
3055
- const eventHandler = (e) => {
3056
- // Check key modifiers for keyboard events
3057
- if (isKeyEvent && !matchesKeyModifiers(e, modifiers)) {
3058
- return; // Key doesn't match, skip
3059
- }
3060
- // Execute handler with optional debounce
3061
- const execute = () => {
3062
- if (modifiers.includes('once'))
3063
- cleanup();
3064
- // Batch in case handler mutates multiple signals
3065
- batch(() => {
3066
- const currentScope = getScopeFromElement(element) || scope;
3067
- executeHandler(handler, currentScope, e, modifiers);
3068
- });
3069
- };
3070
- if (debounceMs > 0) {
3071
- clearTimeout(debounceContext.timeoutId);
3072
- debounceContext.timeoutId = window.setTimeout(execute, debounceMs);
3073
- }
3074
- else {
3075
- execute();
3076
- }
3077
- };
3078
- // Bind event and store cleanup
3079
- const options = {};
3080
- let targetElement = element;
3081
- if (modifiers.includes('capture'))
3082
- options.capture = true;
3083
- if (modifiers.includes('passive'))
3084
- options.passive = true;
3085
- if (modifiers.includes('global'))
3086
- targetElement = document.documentElement;
3087
- targetElement.addEventListener(eventName, eventHandler, options);
3088
- cleanup = () => {
3089
- targetElement.removeEventListener(eventName, eventHandler, !!options.capture);
3090
- if (debounceContext.timeoutId) {
3091
- clearTimeout(debounceContext.timeoutId);
3092
- }
3093
- };
3094
- if (!element.__gyos_effects__) {
3095
- element.__gyos_effects__ = [];
3096
- }
3097
- element.__gyos_effects__.push(cleanup);
3098
- // Remove attribute
3099
- element.removeAttribute(attr.name);
3100
- }
3101
- });
3102
- });
3103
- }
2932
+ const date = new Date(value);
2933
+ return !isNaN(date.getTime()) || 'Invalid date';
2934
+ });
2935
+ /**
2936
+ * Before - Date must be before specified date
2937
+ *
2938
+ * @example "before(2025-12-31)"
2939
+ */
2940
+ validator('before', (value, targetDate) => {
2941
+ if (!value)
2942
+ return true;
2943
+ const date = new Date(value);
2944
+ const target = new Date(targetDate);
2945
+ return date < target || `Must be before ${targetDate}`;
2946
+ });
2947
+ /**
2948
+ * After - Date must be after specified date
2949
+ *
2950
+ * @example "after(2025-01-01)"
2951
+ */
2952
+ validator('after', (value, targetDate) => {
2953
+ if (!value)
2954
+ return true;
2955
+ const date = new Date(value);
2956
+ const target = new Date(targetDate);
2957
+ return date > target || `Must be after ${targetDate}`;
2958
+ });
2959
+ /**
2960
+ * Password - Strong password (uppercase, lowercase, number, min 8 chars)
2961
+ *
2962
+ * @example "password"
2963
+ */
2964
+ validator('password', (value) => {
2965
+ if (!value)
2966
+ return true;
2967
+ if (value.length < 8) {
2968
+ return 'Password must be at least 8 characters';
2969
+ }
2970
+ const hasUpper = /[A-Z]/.test(value);
2971
+ const hasLower = /[a-z]/.test(value);
2972
+ const hasNumber = /[0-9]/.test(value);
2973
+ if (!hasUpper) {
2974
+ return 'Password must contain at least one uppercase letter';
2975
+ }
2976
+ if (!hasLower) {
2977
+ return 'Password must contain at least one lowercase letter';
2978
+ }
2979
+ if (!hasNumber) {
2980
+ return 'Password must contain at least one number';
2981
+ }
2982
+ return true;
2983
+ });
2984
+ /**
2985
+ * In - Value must be in allowed list
2986
+ *
2987
+ * @example "in(red,green,blue)"
2988
+ */
2989
+ validator('in', (value, ...allowedValues) => {
2990
+ if (!value)
2991
+ return true;
2992
+ // Remove context if it's the last argument
2993
+ const values = allowedValues.filter(v => typeof v === 'string' || typeof v === 'number');
2994
+ return values.includes(value) || `Must be one of: ${values.join(', ')}`;
2995
+ });
2996
+ /**
2997
+ * NotIn - Value must not be in forbidden list
2998
+ *
2999
+ * @example "notIn(admin,root,system)"
3000
+ */
3001
+ validator('notIn', (value, ...forbiddenValues) => {
3002
+ if (!value)
3003
+ return true;
3004
+ const values = forbiddenValues.filter(v => typeof v === 'string' || typeof v === 'number');
3005
+ return !values.includes(value) || `Cannot be: ${values.join(', ')}`;
3006
+ });
3007
+ /**
3008
+ * Between - Numeric value must be between min and max
3009
+ *
3010
+ * @example "between(18,65)"
3011
+ */
3012
+ validator('between', (value, min, max) => {
3013
+ if (!value)
3014
+ return true;
3015
+ const num = parseFloat(value);
3016
+ const minVal = parseFloat(min);
3017
+ const maxVal = parseFloat(max);
3018
+ return (num >= minVal && num <= maxVal) || `Must be between ${minVal} and ${maxVal}`;
3019
+ });
3104
3020
 
3105
3021
  /**
3106
- * Two-Way Binding (g-model)
3107
- * Handles form input binding with optional modifiers (debounce, number, trim, etc.)
3022
+ * Form Validation Directives
3023
+ * Provides g-form, g-validate, and g-errors directives for reactive form validation
3108
3024
  */
3025
+ const formStates = new WeakMap();
3026
+ const formValidators = new WeakMap();
3027
+ const validationFieldKey = Symbol('gyos.validation-field');
3028
+ function getFieldName(el) {
3029
+ const storedName = el[validationFieldKey];
3030
+ if (storedName)
3031
+ return storedName;
3032
+ const modelAttr = Array.from(el.attributes).find(attr => attr.name === 'g-model' || attr.name.startsWith('g-model.'));
3033
+ return modelAttr?.value || el.getAttribute('name') || el.id;
3034
+ }
3109
3035
  /**
3110
- * Parse path kiểu:
3111
- * - "user.name"
3112
- * - "list[0].title"
3113
- * - "a.b[10].c[2].d"
3036
+ * Get or create form validation state
3114
3037
  */
3115
- function parsePath(path) {
3116
- const tokens = [];
3117
- const re = /[^.[\]]+|\[(\d+)\]/g;
3118
- let match;
3119
- while ((match = re.exec(path))) {
3120
- if (match[1] !== undefined) {
3121
- // là index trong []
3122
- tokens.push(Number(match[1]));
3123
- }
3124
- else {
3125
- // là tên key bình thường
3126
- tokens.push(match[0]);
3127
- }
3038
+ function getFormState(form) {
3039
+ if (!formStates.has(form)) {
3040
+ // Create reactive state using signals
3041
+ formStates.set(form, {
3042
+ errors: signal({}),
3043
+ touched: signal({}),
3044
+ $invalid: signal(false),
3045
+ $valid: signal(true),
3046
+ $dirty: signal(false), // dirty when any field touched
3047
+ $pristine: signal(true) // pristine when no fields touched
3048
+ });
3128
3049
  }
3129
- return tokens;
3050
+ return formStates.get(form);
3130
3051
  }
3131
3052
  /**
3132
- * Set property on scope (supports nested paths, signals, and array indexes)
3133
- *
3134
- * @param scope - Scope object (hoặc signal bọc object)
3135
- * @param path - Property path (e.g., "user.name", "items[3].title")
3136
- * @param value - Value to set
3053
+ * Update form computed properties
3054
+ * Only updates when values actually change
3137
3055
  */
3138
- function setProperty(scope, path, value) {
3139
- if (hasUnsafePropertyPath(path))
3140
- return;
3141
- const parts = parsePath(path);
3142
- if (parts.length === 0)
3143
- return;
3144
- let obj = scope;
3145
- // nếu scope là signal thì unwrap
3146
- if (isSignal(obj)) {
3147
- obj = obj.value;
3056
+ function updateFormState(state) {
3057
+ const errors = state.errors.value;
3058
+ const touched = state.touched.value;
3059
+ const hasErrors = Object.values(errors).some(error => error !== null);
3060
+ const anyTouched = Object.values(touched).some(t => t);
3061
+ // Only update if changed
3062
+ if (state.$invalid.value !== hasErrors) {
3063
+ state.$invalid.value = hasErrors;
3064
+ state.$valid.value = !hasErrors;
3148
3065
  }
3149
- // đi tới thằng cha của key cuối
3150
- for (let i = 0; i < parts.length - 1; i++) {
3151
- const key = parts[i];
3152
- let next = obj[key];
3153
- // nếu là signal ở giữa thì unwrap
3154
- if (isSignal(next)) {
3155
- next = next.value;
3156
- }
3157
- obj = next;
3066
+ if (state.$dirty.value !== anyTouched) {
3067
+ state.$dirty.value = anyTouched;
3068
+ state.$pristine.value = !anyTouched;
3158
3069
  }
3159
- const lastKey = parts[parts.length - 1];
3160
- const current = obj[lastKey];
3161
- if (isSignal(current)) {
3162
- current.value = value;
3070
+ }
3071
+ /**
3072
+ * Process g-form directive
3073
+ * Binds form validation state to scope
3074
+ *
3075
+ * @example
3076
+ * <form g-form="formData">
3077
+ * <button :disabled="formData.$invalid">Submit</button>
3078
+ * </form>
3079
+ */
3080
+ function processFormDirective(form, scope) {
3081
+ const formName = form.getAttribute('g-form');
3082
+ if (!formName || hasUnsafePropertyPath(formName))
3083
+ return;
3084
+ form.removeAttribute('g-form');
3085
+ const state = getFormState(form);
3086
+ // Create validateAll function
3087
+ const validateAll = async () => {
3088
+ const validators = formValidators.get(form) || [];
3089
+ const touchedObj = { ...state.touched.value };
3090
+ Object.keys(touchedObj).forEach(fieldName => {
3091
+ touchedObj[fieldName] = true;
3092
+ });
3093
+ // Trigger signal update once
3094
+ state.touched.value = { ...touchedObj };
3095
+ // Run all validators in parallel
3096
+ await Promise.all(validators.map(validator => validator()));
3097
+ updateFormState(state);
3098
+ return !state.$invalid.value;
3099
+ };
3100
+ state.validateAll = validateAll;
3101
+ // Directly assign signals to scope properties
3102
+ // Scope will wrap these in signals automatically during component mounting
3103
+ const formStateObj = {
3104
+ errors: state.errors,
3105
+ touched: state.touched,
3106
+ $invalid: state.$invalid,
3107
+ $valid: state.$valid,
3108
+ $dirty: state.$dirty,
3109
+ $pristine: state.$pristine,
3110
+ validateAll: validateAll
3111
+ };
3112
+ if (!(formName in scope)) {
3113
+ scope[formName] = formStateObj;
3163
3114
  }
3164
3115
  else {
3165
- obj[lastKey] = value;
3116
+ // Merge signals into existing object
3117
+ Object.assign(scope[formName], formStateObj);
3118
+ }
3119
+ // Prevent default form submission and validate first
3120
+ const submitListener = async (e) => {
3121
+ e.preventDefault();
3122
+ const isValid = await validateAll();
3123
+ if (!isValid)
3124
+ return;
3125
+ const submitMethod = form.getAttribute('g-submit');
3126
+ // If not defined, submit the form normally
3127
+ if (!submitMethod) {
3128
+ form.submit();
3129
+ return;
3130
+ }
3131
+ // Trigger custom submit handler if exists
3132
+ const submitHandler = scope[submitMethod];
3133
+ if (typeof submitHandler === 'function') {
3134
+ submitHandler.call(scope);
3135
+ }
3136
+ };
3137
+ form.addEventListener('submit', submitListener);
3138
+ if (!form.__gyos_effects__) {
3139
+ form.__gyos_effects__ = [];
3166
3140
  }
3141
+ form.__gyos_effects__.push(() => {
3142
+ form.removeEventListener('submit', submitListener);
3143
+ formStates.delete(form);
3144
+ formValidators.delete(form);
3145
+ });
3167
3146
  }
3168
3147
  /**
3169
- * Process g-model directive for two-way data binding
3170
- *
3171
- * Supports modifiers:
3172
- * - debounce.300: Debounce input with custom delay
3173
- * - number: Convert value to number
3174
- * - trim: Trim whitespace
3175
- *
3176
- * @param el - Root element to process
3177
- * @param scope - Scope object for evaluation
3148
+ * Process g-validate directive on input elements
3149
+ * Validates input value against rules and updates form state
3178
3150
  *
3179
3151
  * @example
3180
- * <input g-model="name">
3181
- * <input g-model.debounce.500="search">
3182
- * <input g-model.number="age">
3183
- * <input type="checkbox" g-model="accepted">
3152
+ * <input g-model="email" g-validate="required|email">
3153
+ * <input g-model="password" g-validate="required|minLength(8)|password">
3184
3154
  */
3185
- function processModel(element, scope, root) {
3186
- if (isInIgnoredTree(element))
3155
+ function processValidateDirective(el) {
3156
+ if (!(el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement || el instanceof HTMLSelectElement)) {
3187
3157
  return;
3188
- // Skip if inside g-static parent
3189
- if (isInStaticParent(element, root))
3158
+ }
3159
+ const rules = el.getAttribute('g-validate');
3160
+ if (!rules)
3190
3161
  return;
3191
- const attrs = Array.from(element.attributes);
3192
- // Find g-model attribute (with or without modifiers)
3193
- const modelAttr = attrs.find(attr => attr.name.startsWith('g-model'));
3162
+ el.removeAttribute('g-validate');
3163
+ // Get field name from g-model attribute
3164
+ const modelAttr = getFieldName(el);
3194
3165
  if (!modelAttr)
3195
3166
  return;
3196
- const inputElement = element;
3197
- // Parse attribute name for modifiers: g-model.debounce.500
3198
- const attrParts = modelAttr.name.split('.');
3199
- const modifiers = attrParts.slice(1); // ['debounce', '500']
3200
- const expr = modelAttr.value; // The actual expression like "searchQuery"
3201
- // Check for debounce modifier
3202
- const hasDebounce = modifiers.includes('debounce');
3203
- let debounceMs = 300; // default
3204
- if (hasDebounce) {
3205
- // Find numeric modifier after 'debounce'
3206
- const numericModifier = modifiers.find(m => /^\d+$/.test(m));
3207
- if (numericModifier) {
3208
- debounceMs = parseInt(numericModifier);
3167
+ el[validationFieldKey] = modelAttr;
3168
+ // Find parent form
3169
+ const form = el.closest('form');
3170
+ if (!form)
3171
+ return;
3172
+ const state = getFormState(form);
3173
+ // Initialize error state - direct mutation
3174
+ state.errors.value[modelAttr] = null;
3175
+ state.touched.value[modelAttr] = false;
3176
+ // Validation function
3177
+ const validateField = async () => {
3178
+ const value = el.value;
3179
+ // Get form context for validators that need it (like 'same')
3180
+ const formData = {};
3181
+ const formInputs = form.querySelectorAll('input, textarea, select');
3182
+ formInputs.forEach(input => {
3183
+ if (isInIgnoredTree(input))
3184
+ return;
3185
+ if (input instanceof HTMLInputElement || input instanceof HTMLTextAreaElement || input instanceof HTMLSelectElement) {
3186
+ const fieldName = getFieldName(input);
3187
+ if (fieldName) {
3188
+ formData[fieldName] = input.value;
3189
+ }
3190
+ }
3191
+ });
3192
+ const error = await validate(value, rules, { form: formData, field: modelAttr });
3193
+ // Update errors - only if changed
3194
+ const currentErrors = state.errors.value;
3195
+ if (currentErrors[modelAttr] !== error) {
3196
+ currentErrors[modelAttr] = error;
3197
+ // Trigger reactivity by reassigning
3198
+ state.errors.value = { ...currentErrors };
3199
+ updateFormState(state);
3209
3200
  }
3201
+ };
3202
+ // Register validator for validateAll
3203
+ if (!formValidators.has(form)) {
3204
+ formValidators.set(form, []);
3210
3205
  }
3211
- DEBUG() && console.log('[g-model] Expression:', expr, 'Modifiers:', modifiers, 'Debounce:', debounceMs);
3212
- // Get current scope from element
3213
- const currentScope = getScopeFromElement(element) || scope;
3214
- // Set initial value (no pipes in v-model)
3215
- const initialValue = evaluateExpression(expr, currentScope, false);
3216
- if (inputElement.type === 'checkbox') {
3217
- inputElement.checked = !!initialValue;
3218
- }
3219
- else {
3220
- inputElement.value = unref(initialValue);
3221
- }
3222
- // Debounce helper
3223
- let timeoutId;
3224
- const debouncedUpdate = (value) => {
3225
- if (modifiers.includes('number'))
3226
- value = Number(value);
3227
- if (modifiers.includes('trim') && typeof value === 'string')
3228
- value = value.trim();
3229
- if (hasDebounce) {
3230
- clearTimeout(timeoutId);
3231
- timeoutId = setTimeout(() => {
3232
- setProperty(currentScope, expr, value);
3233
- }, debounceMs);
3234
- }
3235
- else {
3236
- setProperty(currentScope, expr, value);
3206
+ formValidators.get(form).push(validateField);
3207
+ // Mark as touched on blur
3208
+ const blurListener = () => {
3209
+ const touchedObj = state.touched.value;
3210
+ if (!touchedObj[modelAttr]) {
3211
+ touchedObj[modelAttr] = true;
3212
+ state.touched.value = { ...touchedObj };
3213
+ updateFormState(state);
3237
3214
  }
3215
+ validateField();
3238
3216
  };
3239
- const eventInput = (e) => {
3240
- const target = e.target;
3241
- const value = target.type === 'checkbox' ? target.checked : target.value;
3242
- debouncedUpdate(value);
3243
- };
3244
- // Listen to input events
3245
- inputElement.addEventListener('input', eventInput);
3246
- const cleanupInput = () => {
3247
- inputElement.removeEventListener('input', eventInput);
3248
- if (timeoutId) {
3249
- clearTimeout(timeoutId);
3250
- timeoutId = undefined;
3251
- }
3217
+ el.addEventListener('blur', blurListener);
3218
+ // Validate on input (with debounce)
3219
+ let timeout;
3220
+ const inputListener = () => {
3221
+ clearTimeout(timeout);
3222
+ timeout = setTimeout(() => {
3223
+ validateField();
3224
+ }, 300);
3252
3225
  };
3253
- // Update view when model changes
3254
- queueReactiveEffect(element, () => {
3255
- // No pipes in v-model reactive updates
3256
- const newValue = evaluateExpression(expr, currentScope, false);
3257
- if (inputElement.type === 'checkbox') {
3258
- inputElement.checked = !!newValue;
3259
- }
3260
- else if (inputElement.value !== newValue) {
3261
- inputElement.value = unref(newValue);
3262
- }
3263
- });
3264
- // Store cleanup function
3265
- if (!element.__gyos_effects__) {
3266
- element.__gyos_effects__ = [];
3226
+ el.addEventListener('input', inputListener);
3227
+ if (!el.__gyos_effects__) {
3228
+ el.__gyos_effects__ = [];
3267
3229
  }
3268
- element.__gyos_effects__.push(cleanupInput);
3269
- // Remove the attribute after processing
3270
- element.removeAttribute(modelAttr.name);
3230
+ el.__gyos_effects__.push(() => {
3231
+ el.removeEventListener('blur', blurListener);
3232
+ el.removeEventListener('input', inputListener);
3233
+ clearTimeout(timeout);
3234
+ });
3271
3235
  }
3272
-
3273
3236
  /**
3274
- * Cleanup utilities for disposing effects and event listeners
3275
- */
3276
- /**
3277
- * Dispose all effects attached to an element and its descendants
3278
- * Handles both element effects (__gyos_effects__) and component lifecycle
3237
+ * Process g-errors directive
3238
+ * Displays validation errors for a specific field or all fields
3239
+ *
3240
+ * @example
3241
+ * <!-- Show errors for specific field -->
3242
+ * <span g-errors="email" class="error"></span>
3243
+ *
3244
+ * <!-- Show all form errors -->
3245
+ * <div g-errors class="error-summary"></div>
3279
3246
  */
3280
- function disposeEffects(element = document.body, removeElement = false) {
3281
- if (!element)
3247
+ function processErrorsDirective(el) {
3248
+ const fieldName = el.getAttribute('g-errors');
3249
+ el.removeAttribute('g-errors');
3250
+ // Find parent form
3251
+ const form = el.closest('form');
3252
+ if (!form)
3282
3253
  return;
3283
- // Unmount scope if element has one (calls onUnmount + cleans instance.__gyos_effects__)
3284
- if (element.hasAttribute?.('g-scope') || element.__gyos_scope__) {
3285
- unmountScope(element);
3254
+ const state = getFormState(form);
3255
+ if (fieldName === '' || fieldName === null) {
3256
+ // Show all errors
3257
+ const dispose = effect(() => {
3258
+ const errors = state.errors.value;
3259
+ const errorEntries = Object.entries(errors).filter(([_, error]) => error !== null);
3260
+ el.replaceChildren(...errorEntries.map(([field, error]) => {
3261
+ const row = document.createElement('div');
3262
+ const label = document.createElement('strong');
3263
+ label.textContent = `${field}:`;
3264
+ row.append(label, document.createTextNode(` ${String(error)}`));
3265
+ return row;
3266
+ }));
3267
+ el.style.display = errorEntries.length ? '' : 'none';
3268
+ });
3269
+ if (!el.__gyos_effects__) {
3270
+ el.__gyos_effects__ = [];
3271
+ }
3272
+ el.__gyos_effects__.push(dispose);
3286
3273
  }
3287
- // Dispose effects on this element (template effects like g-show, :class, {text})
3288
- if (element.__gyos_effects__) {
3289
- const effects = element.__gyos_effects__;
3290
- effects.forEach((dispose) => {
3291
- try {
3292
- dispose();
3274
+ else {
3275
+ // Show specific field error (removed isTouched check as requested)
3276
+ const dispose = effect(() => {
3277
+ const errors = state.errors.value;
3278
+ const error = errors[fieldName];
3279
+ if (error) {
3280
+ el.textContent = error;
3281
+ el.style.display = '';
3293
3282
  }
3294
- catch (error) {
3295
- console.error('[GyosJS] Error disposing effect:', error);
3283
+ else {
3284
+ el.textContent = '';
3285
+ el.style.display = 'none';
3296
3286
  }
3297
3287
  });
3298
- element.__gyos_effects__ = null;
3288
+ if (!el.__gyos_effects__) {
3289
+ el.__gyos_effects__ = [];
3290
+ }
3291
+ el.__gyos_effects__.push(dispose);
3299
3292
  }
3300
- // Recursively dispose effects on all descendants
3301
- const descendants = element.querySelectorAll('*');
3302
- descendants.forEach((child) => {
3303
- // Unmount child scopes
3304
- if (child.hasAttribute?.('g-scope') || child.__gyos_scope__) {
3305
- unmountScope(child);
3293
+ }
3294
+ /**
3295
+ * Process all form validation directives in an element tree
3296
+ */
3297
+ function processFormValidation(root, scope) {
3298
+ // Process g-form first
3299
+ if (root instanceof HTMLFormElement && root.hasAttribute('g-form')) {
3300
+ processFormDirective(root, scope);
3301
+ }
3302
+ // Then process g-validate
3303
+ root.querySelectorAll('[g-validate]').forEach(el => {
3304
+ if (isInIgnoredTree(el))
3305
+ return;
3306
+ if (el instanceof HTMLElement) {
3307
+ processValidateDirective(el);
3306
3308
  }
3307
- // Dispose child template effects
3308
- if (child.__gyos_effects__) {
3309
- const effects = child.__gyos_effects__;
3310
- effects.forEach((dispose) => {
3311
- try {
3312
- dispose();
3313
- }
3314
- catch (error) {
3315
- console.error('[GyosJS] Error disposing child effect:', error);
3316
- }
3317
- });
3318
- child.__gyos_effects__ = null;
3309
+ });
3310
+ // Finally process g-errors
3311
+ root.querySelectorAll('[g-errors]').forEach(el => {
3312
+ if (isInIgnoredTree(el))
3313
+ return;
3314
+ if (el instanceof HTMLElement) {
3315
+ processErrorsDirective(el);
3319
3316
  }
3320
3317
  });
3321
- // portal cleanup could be added here if needed
3322
- portalDestroy(element);
3323
- if (removeElement)
3324
- element.remove();
3325
3318
  }
3326
3319
 
3327
3320
  /**
3328
- * Transitions System - Smooth animations for enter/leave
3329
- *
3330
- * Provides built-in transitions and custom transition support for elements.
3331
- * Works with conditional rendering (*if, *for) to animate element appearance.
3332
- *
3333
- * @example Basic usage
3334
- * ```html
3335
- * <div *if="show" g-transition="fade">Content</div>
3336
- * <div *if="show" g-transition.500="slide-down">Slower slide</div>
3337
- * ```
3338
- */
3339
- /**
3340
- * Built-in transitions
3341
- *
3342
- * Available: fade, slide-down, slide-up, slide-left, slide-right, scale, zoom
3321
+ * Event Processing
3322
+ * Handles @event directives with modifiers (prevent, stop, debounce, key modifiers, etc.)
3343
3323
  */
3344
- const builtInTransitions = {
3345
- fade: {
3346
- enterFrom: 'opacity-0',
3347
- enterTo: 'opacity-100',
3348
- leaveFrom: 'opacity-100',
3349
- leaveTo: 'opacity-0',
3350
- duration: 250
3351
- },
3352
- 'slide-down': {
3353
- enterFrom: 'translate-y--100 opacity-0',
3354
- enterTo: 'translate-y-0 opacity-100',
3355
- leaveFrom: 'translate-y-0 opacity-100',
3356
- leaveTo: 'translate-y-100 opacity-0',
3357
- duration: 250
3358
- },
3359
- 'slide-up': {
3360
- enterFrom: 'translate-y-100 opacity-0',
3361
- enterTo: 'translate-y-0 opacity-100',
3362
- leaveFrom: 'translate-y-0 opacity-100',
3363
- leaveTo: 'translate-y--100 opacity-0',
3364
- duration: 250
3365
- },
3366
- 'slide-left': {
3367
- enterFrom: 'translate-x-100 opacity-0',
3368
- enterTo: 'translate-x-0 opacity-100',
3369
- leaveFrom: 'translate-x-0 opacity-100',
3370
- leaveTo: 'translate-x--100 opacity-0',
3371
- duration: 250
3372
- },
3373
- 'slide-right': {
3374
- enterFrom: 'translate-x--100 opacity-0',
3375
- enterTo: 'translate-x-0 opacity-100',
3376
- leaveFrom: 'translate-x-0 opacity-100',
3377
- leaveTo: 'translate-x-100 opacity-0',
3378
- duration: 250
3379
- },
3380
- scale: {
3381
- enterFrom: 'scale-50 opacity-0',
3382
- enterTo: 'scale-100 opacity-100',
3383
- leaveFrom: 'scale-100 opacity-100',
3384
- leaveTo: 'scale-50 opacity-0',
3385
- duration: 250
3386
- },
3387
- zoom: {
3388
- enterFrom: 'scale-0 opacity-0',
3389
- enterTo: 'scale-100 opacity-100',
3390
- leaveFrom: 'scale-100 opacity-100',
3391
- leaveTo: 'scale-0 opacity-0',
3392
- duration: 250
3393
- }
3324
+ // Reusable key modifier map for performance
3325
+ const KEY_MODIFIER_MAP = {
3326
+ 'enter': 'enter',
3327
+ 'esc': 'escape',
3328
+ 'escape': 'escape',
3329
+ 'space': ' ',
3330
+ 'up': 'arrowup',
3331
+ 'down': 'arrowdown',
3332
+ 'left': 'arrowleft',
3333
+ 'right': 'arrowright',
3334
+ 'delete': 'delete',
3335
+ 'tab': 'tab',
3394
3336
  };
3337
+ // Reserved modifiers that aren't key names
3338
+ const RESERVED_MODIFIERS = new Set(['prevent', 'stop', 'once', 'capture', 'passive', 'debounce', 'outside', 'global']);
3395
3339
  /**
3396
- * Register a custom transition
3397
- *
3398
- * @param name - Transition name
3399
- * @param config - Transition configuration
3400
- *
3401
- * @example
3402
- * ```javascript
3403
- * Gyos.registerTransition('bounce-in', {
3404
- * enter: 'bounce-in 500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)',
3405
- * leave: 'bounce-out 250ms ease-in',
3406
- * duration: 500
3407
- * });
3408
- * ```
3409
- */
3410
- function registerTransition(name, config) {
3411
- builtInTransitions[name] = config;
3412
- }
3413
- /**
3414
- * Transition manager - Handles enter/leave animations
3340
+ * Execute handler with modifiers (prevent, stop)
3415
3341
  */
3416
- class TransitionManager {
3417
- constructor() {
3418
- this.leavingElements = new WeakSet();
3419
- }
3420
- /**
3421
- * Enter transition - Animates element appearing
3422
- *
3423
- * @param el - Element to animate
3424
- * @param config - Transition configuration
3425
- */
3426
- async enter(el, config) {
3427
- if (!el.isConnected || this.leavingElements.has(el))
3428
- return;
3429
- try {
3430
- const duration = config.duration || 250;
3431
- // Call before hook
3432
- if (config.onBeforeEnter) {
3433
- config.onBeforeEnter(el);
3434
- }
3435
- // Apply enter-from state
3436
- if (config.enterFrom) {
3437
- this.applyClasses(el, config.enterFrom);
3438
- }
3439
- // Force reflow to ensure classes are applied
3440
- el.offsetHeight;
3441
- // Add transition
3442
- el.style.transition = `all ${duration}ms ease-out`;
3443
- // Apply enter-to state
3444
- if (config.enterFrom) {
3445
- this.removeClasses(el, config.enterFrom);
3446
- }
3447
- if (config.enterTo) {
3448
- this.applyClasses(el, config.enterTo);
3449
- }
3450
- // Or use animation
3451
- if (config.enter) {
3452
- el.style.animation = config.enter;
3453
- }
3454
- // Wait for transition to complete
3455
- await this.waitForTransition(el, duration);
3456
- if (!el.isConnected || this.leavingElements.has(el))
3457
- return;
3458
- // Cleanup
3459
- el.style.transition = '';
3460
- el.style.animation = '';
3461
- if (config.enterTo) {
3462
- this.removeClasses(el, config.enterTo);
3342
+ function executeHandler(handler, scope, e, modifiers) {
3343
+ // Handle prevent/stop modifiers
3344
+ if (modifiers.includes('prevent'))
3345
+ e.preventDefault();
3346
+ if (modifiers.includes('stop'))
3347
+ e.stopPropagation();
3348
+ try {
3349
+ const isMethodCall = handler.includes('(');
3350
+ if (isMethodCall) {
3351
+ // Method call with args: "doSomething()" or "method(arg1, arg2)"
3352
+ const fn = new Function('$event', `with(this) { ${handler} }`);
3353
+ fn.call(scope, e);
3354
+ }
3355
+ else {
3356
+ // Check if it's a method name or expression
3357
+ const method = scope[handler];
3358
+ if (typeof method === 'function') {
3359
+ method.call(scope, e);
3463
3360
  }
3464
- // Call after hook
3465
- if (config.onAfterEnter) {
3466
- config.onAfterEnter(el);
3361
+ else {
3362
+ // Expression like "count++", "count = 0"
3363
+ const fn = new Function('$event', `with(this) { ${handler} }`);
3364
+ fn.call(scope, e);
3467
3365
  }
3468
3366
  }
3469
- catch (error) {
3470
- console.error('[GyosJS] Transition enter error:', error);
3471
- }
3472
- }
3473
- /**
3474
- * Leave transition - Animates element disappearing
3475
- *
3476
- * @param el - Element to animate
3477
- * @param config - Transition configuration
3478
- */
3479
- async leave(el, config) {
3480
- this.leavingElements.add(el);
3481
- try {
3482
- const duration = config.duration || 250;
3483
- // Call before hook
3484
- if (config.onBeforeLeave) {
3485
- config.onBeforeLeave(el);
3486
- }
3487
- // Apply leave-from state
3488
- if (config.leaveFrom) {
3489
- this.applyClasses(el, config.leaveFrom);
3490
- }
3491
- // Force reflow
3492
- el.offsetHeight;
3493
- // Add transition
3494
- el.style.transition = `all ${duration}ms ease-in`;
3495
- // Apply leave-to state
3496
- if (config.leaveFrom) {
3497
- this.removeClasses(el, config.leaveFrom);
3498
- }
3499
- if (config.leaveTo) {
3500
- this.applyClasses(el, config.leaveTo);
3501
- }
3502
- // Or use animation
3503
- if (config.leave) {
3504
- el.style.animation = config.leave;
3505
- }
3506
- // Wait for transition to complete
3507
- await this.waitForTransition(el, duration);
3508
- // Call after hook
3509
- if (config.onAfterLeave) {
3510
- config.onAfterLeave(el);
3511
- }
3512
- // Remove element
3513
- el.remove();
3514
- }
3515
- catch (error) {
3516
- console.error('[GyosJS] Transition leave error:', error);
3517
- // Still remove element on error
3518
- el.remove();
3519
- }
3520
- finally {
3521
- this.leavingElements.delete(el);
3522
- }
3523
- }
3524
- /**
3525
- * Apply CSS classes
3526
- */
3527
- applyClasses(el, classes) {
3528
- classes.split(' ').forEach(cls => {
3529
- if (cls)
3530
- el.classList.add(cls);
3531
- });
3532
- }
3533
- /**
3534
- * Remove CSS classes
3535
- */
3536
- removeClasses(el, classes) {
3537
- classes.split(' ').forEach(cls => {
3538
- if (cls)
3539
- el.classList.remove(cls);
3540
- });
3541
- }
3542
- /**
3543
- * Wait for transition to complete
3544
- */
3545
- waitForTransition(el, duration) {
3546
- return new Promise(resolve => {
3547
- let settled = false;
3548
- let timeoutId;
3549
- const finish = () => {
3550
- if (settled)
3551
- return;
3552
- settled = true;
3553
- el.removeEventListener('transitionend', handler);
3554
- el.removeEventListener('animationend', handler);
3555
- if (timeoutId !== undefined)
3556
- clearTimeout(timeoutId);
3557
- resolve();
3558
- };
3559
- const handler = (event) => {
3560
- if (event.target === el)
3561
- finish();
3562
- };
3563
- el.addEventListener('transitionend', handler);
3564
- el.addEventListener('animationend', handler);
3565
- // Fallback timeout
3566
- timeoutId = setTimeout(finish, duration + 50);
3567
- });
3568
- }
3569
- /**
3570
- * Get transition config by name or return custom config
3571
- *
3572
- * @param name - Transition name or custom config object
3573
- * @returns Transition configuration
3574
- */
3575
- getConfig(name) {
3576
- if (typeof name === 'object') {
3577
- return name;
3578
- }
3579
- return builtInTransitions[name] || builtInTransitions.fade;
3580
3367
  }
3581
- /**
3582
- * Get all available transition names
3583
- *
3584
- * @returns Array of transition names
3585
- */
3586
- getAvailableTransitions() {
3587
- return Object.keys(builtInTransitions);
3368
+ catch (err) {
3369
+ console.error('[GyosJS] Error in event handler:', err);
3588
3370
  }
3589
3371
  }
3590
- // Singleton instance
3591
- const transitionManager = new TransitionManager();
3592
3372
  /**
3593
- * Get transition config from element attribute
3594
- *
3595
- * Supports:
3596
- * - `g-transition="fade"` - Built-in transition
3597
- * - `g-transition.500="fade"` - Custom duration (500ms)
3598
- *
3599
- * @param source - Registered transition name or element containing a transition attribute
3600
- * @returns Transition configuration or null
3601
- *
3602
- * @example
3603
- * ```html
3604
- * <div g-transition="fade">Default 250ms fade</div>
3605
- * <div g-transition.500="slide-down">500ms slide</div>
3606
- * ```
3373
+ * Check if keyboard event matches key modifiers
3607
3374
  */
3608
- function getTransitionConfig(source) {
3609
- if (typeof source === 'string') {
3610
- return builtInTransitions[source] || null;
3611
- }
3612
- const transitionAttr = Array.from(source.attributes).find(attribute => attribute.name === 'g-transition' || attribute.name.startsWith('g-transition.'));
3613
- if (!transitionAttr)
3614
- return null;
3615
- const attr = transitionAttr.value;
3616
- try {
3617
- // Try to parse as JSON for custom config
3618
- const customConfig = JSON.parse(attr);
3619
- return customConfig;
3375
+ function matchesKeyModifiers(e, modifiers) {
3376
+ // Fast path: no key modifiers
3377
+ let hasKeyModifiers = false;
3378
+ for (const mod of modifiers) {
3379
+ if (!RESERVED_MODIFIERS.has(mod) && !/^\d+$/.test(mod)) {
3380
+ hasKeyModifiers = true;
3381
+ break;
3382
+ }
3620
3383
  }
3621
- catch {
3622
- // Use built-in transition by name
3623
- const config = builtInTransitions[attr];
3624
- if (!config) {
3625
- console.warn(`[GyosJS] Unknown transition: "${attr}". Using "fade" as fallback.`);
3626
- return builtInTransitions.fade;
3384
+ if (!hasKeyModifiers)
3385
+ return true;
3386
+ const key = e.key.toLowerCase();
3387
+ // Check against key modifier map
3388
+ for (const mod of modifiers) {
3389
+ if (RESERVED_MODIFIERS.has(mod) || /^\d+$/.test(mod))
3390
+ continue;
3391
+ const mappedKey = KEY_MODIFIER_MAP[mod];
3392
+ if (mappedKey) {
3393
+ if (key === mappedKey)
3394
+ return true;
3627
3395
  }
3628
- // Check for duration modifier (e.g., g-transition.500="fade")
3629
- if (transitionAttr.name.startsWith('g-transition.')) {
3630
- const durationMatch = transitionAttr.name.match(/g-transition\.(\d+)/);
3631
- if (durationMatch) {
3632
- return {
3633
- ...config,
3634
- duration: parseInt(durationMatch[1], 10)
3635
- };
3636
- }
3396
+ else if (key === mod.toLowerCase()) {
3397
+ return true;
3637
3398
  }
3638
- return config;
3639
3399
  }
3400
+ // Special case: delete can match backspace
3401
+ if (key === 'backspace' && modifiers.includes('delete'))
3402
+ return true;
3403
+ return false;
3404
+ }
3405
+ /**
3406
+ * Get debounce delay from modifiers
3407
+ */
3408
+ function getDebounceDelay(modifiers) {
3409
+ const debounceIndex = modifiers.findIndex(m => m === 'debounce' || /^\d+$/.test(m));
3410
+ if (debounceIndex === -1)
3411
+ return 0;
3412
+ if (modifiers[debounceIndex] === 'debounce') {
3413
+ const nextMod = modifiers[debounceIndex + 1];
3414
+ return nextMod && /^\d+$/.test(nextMod) ? parseInt(nextMod) : 300;
3415
+ }
3416
+ return 0;
3640
3417
  }
3641
3418
  /**
3642
- * Apply built-in transition utility styles to document
3419
+ * Process event handlers (@click, @input, @keyup.enter, etc.)
3643
3420
  *
3644
- * Called automatically on component mount. Adds CSS classes and keyframes
3645
- * used by built-in transitions (opacity, transform, scale, etc.)
3421
+ * Supports modifiers:
3422
+ * - prevent: preventDefault()
3423
+ * - stop: stopPropagation()
3424
+ * - once: addEventListener with once option
3425
+ * - debounce.300: Debounce with custom delay
3426
+ * - Key modifiers: enter, esc, space, up, down, left, right, delete, tab
3427
+ *
3428
+ * @param el - Root element to process
3429
+ * @param scope - Scope object for evaluation
3646
3430
  *
3647
3431
  * @example
3648
- * ```javascript
3649
- * // Usually called automatically, but can be called manually:
3650
- * Gyos.applyTransitionStyles();
3651
- * ```
3432
+ * <button @click="handleClick">Click</button>
3433
+ * <button @click.prevent="submit">Submit</button>
3434
+ * <input @input.debounce.500="search">
3435
+ * <input @keyup.enter="submit">
3652
3436
  */
3653
- function applyTransitionStyles() {
3654
- if (typeof document === 'undefined')
3655
- return;
3656
- const styleId = 'gyos-transitions';
3657
- if (document.getElementById(styleId))
3658
- return;
3659
- const style = document.createElement('style');
3660
- style.id = styleId;
3661
- style.textContent = `
3662
- /* Opacity utilities */
3663
- .opacity-0 { opacity: 0; }
3664
- .opacity-100 { opacity: 1; }
3665
-
3666
- /* Transform - Translate Y */
3667
- .translate-y-0 { transform: translateY(0); }
3668
- .translate-y--100 { transform: translateY(-100%); }
3669
- .translate-y-100 { transform: translateY(100%); }
3670
-
3671
- /* Transform - Translate X */
3672
- .translate-x-0 { transform: translateX(0); }
3673
- .translate-x--100 { transform: translateX(-100%); }
3674
- .translate-x-100 { transform: translateX(100%); }
3675
-
3676
- /* Transform - Scale */
3677
- .scale-0 { transform: scale(0); }
3678
- .scale-50 { transform: scale(0.5); }
3679
- .scale-100 { transform: scale(1); }
3680
-
3681
- /* Animation Keyframes */
3682
- @keyframes gyos-fade-in {
3683
- from { opacity: 0; }
3684
- to { opacity: 1; }
3685
- }
3686
-
3687
- @keyframes gyos-fade-out {
3688
- from { opacity: 1; }
3689
- to { opacity: 0; }
3690
- }
3691
-
3692
- @keyframes gyos-slide-down {
3693
- from { transform: translateY(-100%); opacity: 0; }
3694
- to { transform: translateY(0); opacity: 1; }
3695
- }
3696
-
3697
- @keyframes gyos-slide-up {
3698
- from { transform: translateY(100%); opacity: 0; }
3699
- to { transform: translateY(0); opacity: 1; }
3700
- }
3701
-
3702
- @keyframes gyos-scale-in {
3703
- from { transform: scale(0); opacity: 0; }
3704
- to { transform: scale(1); opacity: 1; }
3705
- }
3706
-
3707
- @keyframes gyos-scale-out {
3708
- from { transform: scale(1); opacity: 1; }
3709
- to { transform: scale(0); opacity: 0; }
3710
- }
3711
-
3712
- [g-cloak] {
3713
- display: none !important;
3714
- }`;
3715
- document.head.appendChild(style);
3437
+ /**
3438
+ * Setup click outside handler with cleanup
3439
+ */
3440
+ function setupClickOutsideHandler(element, handler, modifiers, scope, attrName) {
3441
+ let active = true;
3442
+ let timeoutId;
3443
+ const clickOutsideHandler = (e) => {
3444
+ // e.stopPropagation(); // Optional: prevent other click handlers
3445
+ const target = e.target;
3446
+ // Check if click is outside element AND element is still in DOM
3447
+ if (!document.body.contains(element) ||
3448
+ (target instanceof Element && target.hasAttribute('g-ignore-outside-click'))) {
3449
+ // Element removed, cleanup
3450
+ cleanup();
3451
+ return;
3452
+ }
3453
+ if (element !== target && !element.contains(target)) {
3454
+ const currentScope = getScopeFromElement(element) || scope;
3455
+ if (modifiers.includes('once'))
3456
+ cleanup();
3457
+ executeHandler(handler, currentScope, e, modifiers);
3458
+ }
3459
+ };
3460
+ // Cleanup function
3461
+ const cleanup = () => {
3462
+ if (!active)
3463
+ return;
3464
+ active = false;
3465
+ if (timeoutId !== undefined) {
3466
+ clearTimeout(timeoutId);
3467
+ timeoutId = undefined;
3468
+ }
3469
+ document.removeEventListener('click', clickOutsideHandler, true);
3470
+ observer.disconnect();
3471
+ };
3472
+ // MutationObserver to detect when element is removed from DOM
3473
+ const observer = new MutationObserver((mutations) => {
3474
+ for (const mutation of mutations) {
3475
+ mutation.removedNodes.forEach((node) => {
3476
+ const removedWithElement = node === element ||
3477
+ (node instanceof Element && node.contains(element));
3478
+ if (removedWithElement && !document.body.contains(element)) {
3479
+ cleanup();
3480
+ }
3481
+ });
3482
+ }
3483
+ });
3484
+ // Observe document.body for any removal (including *if removing element)
3485
+ observer.observe(document.body, { childList: true, subtree: true });
3486
+ // Store cleanup in __gyos_effects__
3487
+ if (!element.__gyos_effects__) {
3488
+ element.__gyos_effects__ = [];
3489
+ }
3490
+ element.__gyos_effects__.push(cleanup);
3491
+ // Use setTimeout to avoid triggering on the same click that opens the element
3492
+ timeoutId = window.setTimeout(() => {
3493
+ if (active)
3494
+ document.addEventListener('click', clickOutsideHandler, true);
3495
+ }, 0);
3496
+ element.removeAttribute(attrName);
3497
+ }
3498
+ function processEvents(el, scope) {
3499
+ // TreeWalker is more efficient than querySelectorAll for large DOMs
3500
+ const elementsToProcess = walkerDOM(el, element => !isInIgnoredTree(element) && !element.hasAttribute('g-static'), NodeFilter.FILTER_REJECT);
3501
+ elementsToProcess.unshift(el); // Include root element
3502
+ elementsToProcess.forEach(element => {
3503
+ // Skip if inside g-static parent (double check)
3504
+ if (isInStaticParent(element, el))
3505
+ return;
3506
+ const ownerScope = getScopeFromElement(element);
3507
+ if (ownerScope && ownerScope !== scope)
3508
+ return;
3509
+ const attrs = Array.from(element.attributes);
3510
+ attrs.forEach(attr => {
3511
+ if (attr.name.startsWith('@')) {
3512
+ // Parse event name and modifiers once
3513
+ const parts = attr.name.substring(1).split('.');
3514
+ const eventName = parts[0];
3515
+ const modifiers = parts.slice(1);
3516
+ const handler = attr.value;
3517
+ // Handle @click.outside modifier
3518
+ if (modifiers.includes('outside')) {
3519
+ setupClickOutsideHandler(element, handler, modifiers, scope, attr.name);
3520
+ return; // Skip normal event binding
3521
+ }
3522
+ // Setup event handler with debounce support
3523
+ const debounceMs = getDebounceDelay(modifiers);
3524
+ const isKeyEvent = eventName === 'keyup' || eventName === 'keydown' || eventName === 'keypress';
3525
+ // Create dedicated debounce context per element-event pair
3526
+ const debounceContext = { timeoutId: 0 };
3527
+ let cleanup = () => { };
3528
+ const eventHandler = (e) => {
3529
+ // Check key modifiers for keyboard events
3530
+ if (isKeyEvent && !matchesKeyModifiers(e, modifiers)) {
3531
+ return; // Key doesn't match, skip
3532
+ }
3533
+ // Execute handler with optional debounce
3534
+ const execute = () => {
3535
+ if (modifiers.includes('once'))
3536
+ cleanup();
3537
+ // Batch in case handler mutates multiple signals
3538
+ batch(() => {
3539
+ const currentScope = getScopeFromElement(element) || scope;
3540
+ executeHandler(handler, currentScope, e, modifiers);
3541
+ });
3542
+ };
3543
+ if (debounceMs > 0) {
3544
+ clearTimeout(debounceContext.timeoutId);
3545
+ debounceContext.timeoutId = window.setTimeout(execute, debounceMs);
3546
+ }
3547
+ else {
3548
+ execute();
3549
+ }
3550
+ };
3551
+ // Bind event and store cleanup
3552
+ const options = {};
3553
+ let targetElement = element;
3554
+ if (modifiers.includes('capture'))
3555
+ options.capture = true;
3556
+ if (modifiers.includes('passive'))
3557
+ options.passive = true;
3558
+ if (modifiers.includes('global'))
3559
+ targetElement = document.documentElement;
3560
+ targetElement.addEventListener(eventName, eventHandler, options);
3561
+ cleanup = () => {
3562
+ targetElement.removeEventListener(eventName, eventHandler, !!options.capture);
3563
+ if (debounceContext.timeoutId) {
3564
+ clearTimeout(debounceContext.timeoutId);
3565
+ }
3566
+ };
3567
+ if (!element.__gyos_effects__) {
3568
+ element.__gyos_effects__ = [];
3569
+ }
3570
+ element.__gyos_effects__.push(cleanup);
3571
+ // Remove attribute
3572
+ element.removeAttribute(attr.name);
3573
+ }
3574
+ });
3575
+ });
3716
3576
  }
3717
3577
 
3718
3578
  /**
3719
- * Transition Helper Utilities
3720
- * Shared utilities for handling transitions in structural directives
3579
+ * Two-Way Binding (g-model)
3580
+ * Handles form input binding with optional modifiers (debounce, number, trim, etc.)
3721
3581
  */
3722
3582
  /**
3723
- * Parse transition name from attribute value
3724
- * Handles:
3725
- * 1. Literal string: "fade" or "slide-down"
3726
- * 2. Expression with {}: "{transition}"
3727
- * 3. Expression without {}: "transition" (evaluate as variable)
3728
- *
3729
- * @param attrValue - The g-transition attribute value
3730
- * @param scope - Current scope for expression evaluation
3731
- * @returns The transition name (string)
3583
+ * Parse path kiểu:
3584
+ * - "user.name"
3585
+ * - "list[0].title"
3586
+ * - "a.b[10].c[2].d"
3732
3587
  */
3733
- function parseTransitionName(attrValue, scope) {
3734
- if (attrValue.includes('{') && attrValue.includes('}')) {
3735
- // Extract expression from {} and evaluate it
3736
- const match = attrValue.match(/\{([^}]+)\}/);
3737
- if (match) {
3738
- return evaluateExpression(match[1].trim(), scope);
3588
+ function parsePath(path) {
3589
+ const tokens = [];
3590
+ const re = /[^.[\]]+|\[(\d+)\]/g;
3591
+ let match;
3592
+ while ((match = re.exec(path))) {
3593
+ if (match[1] !== undefined) {
3594
+ // là index trong []
3595
+ tokens.push(Number(match[1]));
3596
+ }
3597
+ else {
3598
+ // là tên key bình thường
3599
+ tokens.push(match[0]);
3739
3600
  }
3740
3601
  }
3741
- // Try to evaluate as expression first (variable name)
3742
- // If it fails or returns undefined, use as literal string
3743
- try {
3744
- const evaluated = evaluateExpression(attrValue, scope);
3745
- if (evaluated !== undefined && evaluated !== null) {
3746
- return evaluated;
3602
+ return tokens;
3603
+ }
3604
+ /**
3605
+ * Set property on scope (supports nested paths, signals, and array indexes)
3606
+ *
3607
+ * @param scope - Scope object (hoặc signal bọc object)
3608
+ * @param path - Property path (e.g., "user.name", "items[3].title")
3609
+ * @param value - Value to set
3610
+ */
3611
+ function setProperty(scope, path, value) {
3612
+ if (hasUnsafePropertyPath(path))
3613
+ return;
3614
+ const parts = parsePath(path);
3615
+ if (parts.length === 0)
3616
+ return;
3617
+ let obj = scope;
3618
+ // nếu scope là signal thì unwrap
3619
+ if (isSignal(obj)) {
3620
+ obj = obj.value;
3621
+ }
3622
+ // đi tới thằng cha của key cuối
3623
+ for (let i = 0; i < parts.length - 1; i++) {
3624
+ const key = parts[i];
3625
+ let next = obj[key];
3626
+ // nếu là signal ở giữa thì unwrap
3627
+ if (isSignal(next)) {
3628
+ next = next.value;
3747
3629
  }
3630
+ obj = next;
3748
3631
  }
3749
- catch (e) {
3750
- // If evaluation fails, use value as literal string (built-in transition name)
3632
+ const lastKey = parts[parts.length - 1];
3633
+ const current = obj[lastKey];
3634
+ if (isSignal(current)) {
3635
+ current.value = value;
3636
+ }
3637
+ else {
3638
+ obj[lastKey] = value;
3751
3639
  }
3752
- return attrValue;
3753
3640
  }
3754
3641
  /**
3755
- * Parse transition config from element's g-transition attribute
3756
- * Extracts transition name and custom duration modifier
3642
+ * Process g-model directive for two-way data binding
3757
3643
  *
3758
- * @param element - Element with g-transition attribute
3759
- * @param scope - Current scope for expression evaluation
3760
- * @returns { name: string, duration?: number } or null if no transition
3644
+ * Supports modifiers:
3645
+ * - debounce.300: Debounce input with custom delay
3646
+ * - number: Convert value to number
3647
+ * - trim: Trim whitespace
3648
+ *
3649
+ * @param el - Root element to process
3650
+ * @param scope - Scope object for evaluation
3651
+ *
3652
+ * @example
3653
+ * <input g-model="name">
3654
+ * <input g-model.debounce.500="search">
3655
+ * <input g-model.number="age">
3656
+ * <input type="checkbox" g-model="accepted">
3761
3657
  */
3762
- function parseTransitionConfig(element, scope) {
3658
+ function processModel(element, scope, root) {
3659
+ if (isInIgnoredTree(element))
3660
+ return;
3661
+ // Skip if inside g-static parent
3662
+ if (isInStaticParent(element, root))
3663
+ return;
3763
3664
  const attrs = Array.from(element.attributes);
3764
- const transitionAttr = attrs.find(attr => attr.name.startsWith('g-transition'));
3765
- if (!transitionAttr)
3766
- return null;
3767
- // Parse modifiers from attribute name: g-transition.500
3768
- const attrParts = transitionAttr.name.split('.');
3769
- const modifiers = attrParts.slice(1); // ['500'] or []
3770
- const customDuration = modifiers.find(m => /^\d+$/.test(m));
3771
- const transitionName = parseTransitionName(transitionAttr.value, scope);
3772
- return {
3773
- name: transitionName,
3774
- duration: customDuration ? parseInt(customDuration) : undefined
3665
+ // Find g-model attribute (with or without modifiers)
3666
+ const modelAttr = attrs.find(attr => attr.name.startsWith('g-model'));
3667
+ if (!modelAttr)
3668
+ return;
3669
+ const inputElement = element;
3670
+ // Parse attribute name for modifiers: g-model.debounce.500
3671
+ const attrParts = modelAttr.name.split('.');
3672
+ const modifiers = attrParts.slice(1); // ['debounce', '500']
3673
+ const expr = modelAttr.value; // The actual expression like "searchQuery"
3674
+ // Check for debounce modifier
3675
+ const hasDebounce = modifiers.includes('debounce');
3676
+ let debounceMs = 300; // default
3677
+ if (hasDebounce) {
3678
+ // Find numeric modifier after 'debounce'
3679
+ const numericModifier = modifiers.find(m => /^\d+$/.test(m));
3680
+ if (numericModifier) {
3681
+ debounceMs = parseInt(numericModifier);
3682
+ }
3683
+ }
3684
+ DEBUG() && console.log('[g-model] Expression:', expr, 'Modifiers:', modifiers, 'Debounce:', debounceMs);
3685
+ // Get current scope from element
3686
+ const currentScope = getScopeFromElement(element) || scope;
3687
+ // Set initial value (no pipes in v-model)
3688
+ const initialValue = evaluateExpression(expr, currentScope, false);
3689
+ if (inputElement.type === 'checkbox') {
3690
+ inputElement.checked = !!initialValue;
3691
+ }
3692
+ else {
3693
+ inputElement.value = unref(initialValue);
3694
+ }
3695
+ // Debounce helper
3696
+ let timeoutId;
3697
+ const debouncedUpdate = (value) => {
3698
+ if (modifiers.includes('number'))
3699
+ value = Number(value);
3700
+ if (modifiers.includes('trim') && typeof value === 'string')
3701
+ value = value.trim();
3702
+ if (hasDebounce) {
3703
+ clearTimeout(timeoutId);
3704
+ timeoutId = setTimeout(() => {
3705
+ setProperty(currentScope, expr, value);
3706
+ }, debounceMs);
3707
+ }
3708
+ else {
3709
+ setProperty(currentScope, expr, value);
3710
+ }
3775
3711
  };
3776
- }
3777
- /**
3778
- * Find all elements with g-transition attribute
3779
- * Searches root element and all descendants
3780
- *
3781
- * @param root - Root element to search from
3782
- * @returns Array of elements with g-transition
3783
- */
3784
- function findElementsWithTransition(root) {
3785
- if (isInIgnoredTree(root))
3786
- return [];
3787
- const elements = [];
3788
- // Check root element
3789
- if (Array.from(root.attributes).some(attr => attr.name.startsWith('g-transition'))) {
3790
- elements.push(root);
3712
+ const eventInput = (e) => {
3713
+ const target = e.target;
3714
+ const value = target.type === 'checkbox' ? target.checked : target.value;
3715
+ debouncedUpdate(value);
3716
+ };
3717
+ // Listen to input events
3718
+ inputElement.addEventListener('input', eventInput);
3719
+ const cleanupInput = () => {
3720
+ inputElement.removeEventListener('input', eventInput);
3721
+ if (timeoutId) {
3722
+ clearTimeout(timeoutId);
3723
+ timeoutId = undefined;
3724
+ }
3725
+ };
3726
+ // Update view when model changes
3727
+ queueReactiveEffect(element, () => {
3728
+ // No pipes in v-model reactive updates
3729
+ const newValue = evaluateExpression(expr, currentScope, false);
3730
+ if (inputElement.type === 'checkbox') {
3731
+ inputElement.checked = !!newValue;
3732
+ }
3733
+ else if (inputElement.value !== newValue) {
3734
+ inputElement.value = unref(newValue);
3735
+ }
3736
+ });
3737
+ // Store cleanup function
3738
+ if (!element.__gyos_effects__) {
3739
+ element.__gyos_effects__ = [];
3791
3740
  }
3792
- // Check all descendants
3793
- const allDescendants = walkerDOM(root, el => !isInIgnoredTree(el), NodeFilter.FILTER_REJECT).filter(el => Array.from(el.attributes).some(attr => attr.name.startsWith('g-transition')));
3794
- elements.push(...allDescendants);
3795
- return elements;
3741
+ element.__gyos_effects__.push(cleanupInput);
3742
+ // Remove the attribute after processing
3743
+ element.removeAttribute(modelAttr.name);
3796
3744
  }
3745
+
3797
3746
  /**
3798
- * Apply enter transition to an element
3799
- * Handles transition config parsing and application
3800
- *
3801
- * @param element - Element to apply transition to
3802
- * @param scope - Current scope for expression evaluation
3803
- * @returns Promise that resolves when transition completes
3747
+ * Cleanup utilities for disposing effects and event listeners
3804
3748
  */
3805
- function applyEnterTransition(element, scope) {
3806
- const config = parseTransitionConfig(element, scope);
3807
- if (!config)
3808
- return Promise.resolve();
3809
- DEBUG() && console.log('[Transition] Enter with:', config.name, config.duration ? `(${config.duration}ms)` : '', 'on', element.tagName, element.className);
3810
- const transitionConfig = { ...transitionManager.getConfig(config.name) };
3811
- if (config.duration) {
3812
- transitionConfig.duration = config.duration;
3813
- }
3814
- return transitionManager.enter(element, transitionConfig);
3815
- }
3816
3749
  /**
3817
- * Apply leave transition to an element
3818
- * Handles transition config parsing and application
3819
- *
3820
- * @param element - Element to apply transition to
3821
- * @param scope - Current scope for expression evaluation
3822
- * @returns Promise that resolves when transition completes
3750
+ * Dispose all effects attached to an element and its descendants
3751
+ * Handles both element effects (__gyos_effects__) and component lifecycle
3823
3752
  */
3824
- function applyLeaveTransition(element, scope) {
3825
- const config = parseTransitionConfig(element, scope);
3826
- if (!config)
3827
- return Promise.resolve();
3828
- DEBUG() && console.log('[Transition] Leave with:', config.name, config.duration ? `(${config.duration}ms)` : '', 'on', element.tagName, element.className);
3829
- const transitionConfig = { ...transitionManager.getConfig(config.name) };
3830
- if (config.duration) {
3831
- transitionConfig.duration = config.duration;
3753
+ function disposeEffects(element = document.body, removeElement = false) {
3754
+ if (!element)
3755
+ return;
3756
+ // Unmount scope if element has one (calls onUnmount + cleans instance.__gyos_effects__)
3757
+ if (element.hasAttribute?.('g-scope') || element.__gyos_scope__) {
3758
+ unmountScope(element);
3759
+ }
3760
+ // Dispose effects on this element (template effects like g-show, :class, {text})
3761
+ if (element.__gyos_effects__) {
3762
+ const effects = element.__gyos_effects__;
3763
+ effects.forEach((dispose) => {
3764
+ try {
3765
+ dispose();
3766
+ }
3767
+ catch (error) {
3768
+ console.error('[GyosJS] Error disposing effect:', error);
3769
+ }
3770
+ });
3771
+ element.__gyos_effects__ = null;
3832
3772
  }
3833
- return transitionManager.leave(element, transitionConfig);
3773
+ // Recursively dispose effects on all descendants
3774
+ const descendants = element.querySelectorAll('*');
3775
+ descendants.forEach((child) => {
3776
+ // Unmount child scopes
3777
+ if (child.hasAttribute?.('g-scope') || child.__gyos_scope__) {
3778
+ unmountScope(child);
3779
+ }
3780
+ // Dispose child template effects
3781
+ if (child.__gyos_effects__) {
3782
+ const effects = child.__gyos_effects__;
3783
+ effects.forEach((dispose) => {
3784
+ try {
3785
+ dispose();
3786
+ }
3787
+ catch (error) {
3788
+ console.error('[GyosJS] Error disposing child effect:', error);
3789
+ }
3790
+ });
3791
+ child.__gyos_effects__ = null;
3792
+ }
3793
+ });
3794
+ // portal cleanup could be added here if needed
3795
+ portalDestroy(element);
3796
+ if (removeElement)
3797
+ element.remove();
3834
3798
  }
3835
3799
 
3836
3800
  const storeCache = new WeakMap();
@@ -4900,9 +4864,9 @@ function processStructuralDirectives(elements, scope) {
4900
4864
  }
4901
4865
  });
4902
4866
  }
4903
- const elementInScope = (el) => {
4904
- const mountedScopes = Array.from(getAllMountedScopes());
4905
- return mountedScopes.some(([mountedEl, _]) => mountedEl.contains(el) && mountedEl !== el);
4867
+ const elementBelongsToAnotherScope = (el, scope) => {
4868
+ const owner = getScopeFromElement(el);
4869
+ return Boolean(owner && owner !== scope);
4906
4870
  };
4907
4871
  function processParse(element, scope, fromStructural = false) {
4908
4872
  if (isInIgnoredTree(element))
@@ -4928,7 +4892,7 @@ function processParse(element, scope, fromStructural = false) {
4928
4892
  return;
4929
4893
  if (el.attributes.length === 0)
4930
4894
  return; // Skip if no attributes
4931
- if (elementInScope(el) && !fromStructural) {
4895
+ if (elementBelongsToAnotherScope(el, scope) && !fromStructural) {
4932
4896
  // (fromStructural allows processing newly created elements inside structurals)
4933
4897
  return; // Skip if inside mounted scope
4934
4898
  }
@@ -5250,7 +5214,12 @@ function getDepth(el) {
5250
5214
  /**
5251
5215
  * Mount all scopes in the document
5252
5216
  */
5253
- function mountAll() {
5217
+ function mountAll(root) {
5218
+ if (root) {
5219
+ const roots = root instanceof HTMLElement ? [root] : Array.from(root);
5220
+ roots.forEach(element => mountTree(element));
5221
+ return;
5222
+ }
5254
5223
  const elements = document.querySelectorAll('[g-scope]');
5255
5224
  const elementsNotScope = walkerDOM(document.body, el => {
5256
5225
  if (el.hasAttribute('g-scope'))
@@ -5270,21 +5239,19 @@ function mountAll() {
5270
5239
  allElements.forEach(el => !hasStructuralParent(el) && mount(el));
5271
5240
  }
5272
5241
  function mountTree(el) {
5273
- if (isInIgnoredTree(el))
5242
+ if (isInIgnoredTree(el) || !document.body.contains(el))
5274
5243
  return;
5275
- const walker = document.createTreeWalker(el, NodeFilter.SHOW_ELEMENT, {
5276
- acceptNode(node) {
5277
- return node.hasAttribute('g-ignore')
5278
- ? NodeFilter.FILTER_REJECT
5279
- : NodeFilter.FILTER_ACCEPT;
5280
- }
5281
- });
5282
- let node = walker.currentNode;
5283
- while (node = walker.nextNode()) {
5284
- if (node instanceof HTMLElement && node.hasAttribute('g-scope')) {
5285
- mount(node);
5286
- }
5287
- }
5244
+ const hasAutoScope = (element) => Array.from(element.attributes).some(attribute => attribute.name.startsWith('gd-') || attribute.name.startsWith('gm-'));
5245
+ const candidates = [el, ...walkerDOM(el, element => !isInIgnoredTree(element), NodeFilter.FILTER_REJECT)]
5246
+ .filter(element => element.hasAttribute('g-scope') || hasAutoScope(element));
5247
+ // Child scopes own their subtree before an existing parent scope parses the insertion.
5248
+ candidates.sort((a, b) => getDepth(b) - getDepth(a));
5249
+ candidates.forEach(element => !hasStructuralParent(element) && mount(element));
5250
+ if (getMountedScope(el))
5251
+ return;
5252
+ const ownerScope = getScopeFromElement(el);
5253
+ if (ownerScope)
5254
+ processParse(el, ownerScope);
5288
5255
  }
5289
5256
  /**
5290
5257
  * Mount a element with g-scope attribute
@@ -5444,6 +5411,19 @@ function handleDefinition(el, scopeAttr) {
5444
5411
  if (!definition)
5445
5412
  definition = scopeRegistry.get(scopeAttr) || {};
5446
5413
  const autoDef = parseAutoScope(el);
5414
+ if (typeof definition === 'function') {
5415
+ const factory = definition;
5416
+ return context => {
5417
+ const instance = factory(context);
5418
+ if (!instance || typeof instance !== 'object')
5419
+ return instance;
5420
+ Object.keys(autoDef).forEach(key => {
5421
+ instance[key] = autoDef[key];
5422
+ });
5423
+ autoBindModelProp(el, instance);
5424
+ return instance;
5425
+ };
5426
+ }
5447
5427
  Object.keys(autoDef).forEach(key => {
5448
5428
  definition[key] = autoDef[key];
5449
5429
  });
@@ -5490,7 +5470,10 @@ function mountScopeInternal(el, definition) {
5490
5470
  const context = createContext(el, instance);
5491
5471
  // If function component, call it now with context
5492
5472
  if (typeof definition === 'function' && !instance) {
5493
- instance = definition(context);
5473
+ const factoryResult = definition(context);
5474
+ instance = factoryResult && typeof factoryResult === 'object'
5475
+ ? makeReactive(factoryResult)
5476
+ : factoryResult;
5494
5477
  }
5495
5478
  if (!instance || typeof instance !== 'object') {
5496
5479
  DEBUG() && console.error('[GyosJS] Invalid scope definition for element:', el);
@@ -6695,6 +6678,7 @@ async function performSwap(target, src, mode, options = {}) {
6695
6678
  result = target;
6696
6679
  }
6697
6680
  await options.beforeScripts?.();
6681
+ options.onCommitted?.(result, normalized === 'append' || normalized === 'prepend' ? incomingChildren : [result]);
6698
6682
  // Additive swaps must not re-run scripts that already existed in the target.
6699
6683
  if (normalized === 'append' || normalized === 'prepend') {
6700
6684
  await executeScriptsInNodes(incomingChildren, options.signal);
@@ -7395,6 +7379,8 @@ async function navigate(opts) {
7395
7379
  return;
7396
7380
  }
7397
7381
  const swapMode = (opts.swapMode || opts.trigger?.getAttribute('g-swap') || 'inner').toLowerCase();
7382
+ const removeTriggerAfterCommit = opts.trigger instanceof HTMLElement
7383
+ && opts.trigger.hasAttribute('g-router-remove');
7398
7384
  const destructiveSwap = !['append', 'prepend'].includes(swapMode);
7399
7385
  const isFullOutletNavigation = target === findGlobalOutlet();
7400
7386
  const targetOutletIndex = getOutletIndex(document, target);
@@ -7513,16 +7499,18 @@ async function navigate(opts) {
7513
7499
  ? cloneHistoryTarget(target)
7514
7500
  : null;
7515
7501
  let historyEdge = null;
7502
+ let committedRoots = [];
7516
7503
  let finalized = false;
7517
7504
  const finalizeCommit = () => {
7518
7505
  if (finalized)
7519
7506
  return;
7520
7507
  finalized = true;
7508
+ const mountRoots = committedRoots.filter((root) => root instanceof HTMLElement && root.isConnected);
7521
7509
  mergePersistIntoLive(target);
7522
7510
  if (historyEdge) {
7523
7511
  setHistoryFragment(historyEdge.nextEntryId, historyEdge.currentEntryId, target);
7524
7512
  }
7525
- mountAll();
7513
+ mountAll(mountRoots.length > 0 ? mountRoots : undefined);
7526
7514
  };
7527
7515
  if (destructiveSwap) {
7528
7516
  detachPersist(target);
@@ -7581,6 +7569,10 @@ async function navigate(opts) {
7581
7569
  }
7582
7570
  await updateHead(doc, transaction.controller.signal);
7583
7571
  assertActiveNavigation(transaction);
7572
+ },
7573
+ onCommitted: (committedTarget, roots) => {
7574
+ target = committedTarget;
7575
+ committedRoots = roots;
7584
7576
  }
7585
7577
  });
7586
7578
  assertActiveNavigation(transaction);
@@ -7619,6 +7611,10 @@ async function navigate(opts) {
7619
7611
  await performUpdate();
7620
7612
  }
7621
7613
  assertActiveNavigation(transaction);
7614
+ if (removeTriggerAfterCommit && opts.trigger instanceof HTMLElement && opts.trigger.isConnected) {
7615
+ disposeEffects(opts.trigger);
7616
+ opts.trigger.remove();
7617
+ }
7622
7618
  if (hasTargetSpinner)
7623
7619
  hideTargetSpinner(transaction.spinner);
7624
7620
  transaction.spinner = null;
@@ -7872,7 +7868,7 @@ const Gyos = {
7872
7868
  onAfterNavigate,
7873
7869
  portalCreate,
7874
7870
  portalDestroy,
7875
- version: '0.1.1'
7871
+ version: '0.2.0'
7876
7872
  };
7877
7873
 
7878
7874
  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 };