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