All files / lib/core/events bindEvents.js

98.09% Statements 515/525
87.42% Branches 153/175
100% Functions 20/20
98.09% Lines 515/525

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526405x 405x 405x 405x 405x 405x 405x 405x 308x 308x 131x 131x 177x 177x 308x 280x 280x 4x 280x 276x 276x 276x 7x 2x 5x 2x 2x 7x 280x 278x 278x 175x 308x 405x 405x 405x 405x 405x 405x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 4429x 4429x 4429x 4429x 4429x 678x 678x 678x 678x 678x 678x 678x 678x 152x 152x 152x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 3128x 3128x 3128x 3128x 22x 22x 22x 22x 23x 23x 23x 23x 23x 23x 22x     22x 3128x 3128x 3124x 1634x 245x 245x 245x 245x 245x 245x 3124x 3124x 3128x 3128x 3128x 678x 678x 678x 678x 678x 678x 678x 678x 678x 1108x 1108x 4x 1108x 1104x 1104x 1108x 678x 678x 678x 678x 678x 678x 204x 197x 5x 197x 192x 192x 192x 204x 678x 678x 678x 678x 678x 678x 1104x 1104x 1104x 1104x 1104x 1104x 4564x 4425x 4425x 4564x 1104x 1104x 1104x 1104x 1104x 4354x 2819x 2819x 2819x 148x 148x 148x 148x 2819x 2819x 4354x 10x 10x 2809x 4326x 4354x 1733x 4354x 45x 45x 2764x 4354x 4354x 2762x 3250x 3250x 2762x 1104x 1104x 1104x 1104x 623x 623x 1104x 1104x 1104x 1104x 4425x 1925x 1925x 1925x 1925x 1689x 1689x 1925x 1925x 1925x 4425x 4425x 131x 131x 308x 301x 5x 5x 5x 5x 301x 301x 113x 113x 113x 111x 111x 111x 111x 111x 301x 301x 308x 131x 131x 177x 308x     308x 4425x 4425x 4425x 4425x 4001x 4001x 4425x 4425x 4425x 4425x 1104x 1104x 678x 678x 678x 678x 678x 192x 179x 716x 716x 716x 680x 680x 179x 179x 179x 192x 192x 179x 716x 716x 716x 680x 680x 179x 179x 179x 192x 678x 678x 678x 678x 678x 678x 4x 4x 9x 9x 5x 5x 9x     9x 9x 6x 5x 5x 6x 4x 4x 4x 4x 5x 4x 4x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 4x 4x 4x 4x 4x 4x 5x 5x 5x 4x 4x 4x 4x 4x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 5x 4x 4x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 99x 99x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 114x 114x 2x 1x 1x 2x 113x 113x 114x 4x 4x 2x 2x 2x 4x 2x 2x 2x 2x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 114x 6x 6x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 114x 13x     13x 13x 6x 6x 13x 99x 99x 99x 99x 114x 114x 114x 2x 114x 2x 2x 114x 2x 2x 99x 99x 99x 99x 114x 678x 678x 678x 678x 678x 197x 197x 992x 645x 635x 635x 992x     992x 992x 639x 795x 795x 639x 197x 197x 197x 197x 635x 2x 1x 1x 1x 1x 1x 2x 2x 2x 635x 635x 635x 1x 1x 1x 1x 1x 1x 1x 1x 1x 197x 197x 678x 678x 678x 678x 678x 193x 193x 193x 678x  
import { findScope } from '../renderer/bindingScope.js';
/**
 * Checks if a given DOM element belongs to the component defined by root.
 * Deals with nested component boundaries and transcluded slots.
 * @param {Element} element
 * @param {Element} root
 * @returns {boolean}
 */
function belongsToComponent(element, root) {
  if (element === root) {
    return !(root.hasAttribute && (root.hasAttribute('data-avenx-comp') || root.hasAttribute('data-avenx-comp-dynamic')));
  }
  let current = element;
  let isTranscluded = false;
  while (current && current !== root) {
    if (current.nodeType === 1) {
      if (current.nodeName === 'SLOT' && current.hasAttribute && current.hasAttribute('data-avenx-transcluded')) {
        isTranscluded = true;
      } else if (
        current.hasAttribute &&
        (current.hasAttribute('data-avenx-comp') || current.hasAttribute('data-avenx-comp-dynamic'))
      ) {
        if (isTranscluded) {
          isTranscluded = false;
        } else if (current !== element) {
          return false;
        }
      }
    }
    current = current.parentNode;
  }
  return !isTranscluded;
}
 
/**
 * Responsible for binding event listeners to DOM elements based on attributes.
 * Uses event delegation on the root element.
 */
export class EventBinder {
  /**
   * Stores bound events and handlers.
   * @type {WeakMap<Element, Map<string, {handler: Function, options: object}>>}
   * @private
   */
  #boundEvents = new WeakMap();
 
  /**
   * Builds addEventListener options from OR'd passive/capture flags.
   * @param {object} flags
   * @returns {object}
   * @private
   */
  #toListenerOptions(flags) {
    const options = {};
    if (flags && flags.passive) options.passive = true;
    if (flags && flags.capture) options.capture = true;
    return options;
  }
 
  /**
   * ORs `.passive` / `.capture` modifiers into an options flags object.
   * @param {{passive: boolean, capture: boolean}} flags
   * @param {string[]} modifiers
   * @private
   */
  #orListenerFlags(flags, modifiers) {
    if (modifiers.includes('passive')) flags.passive = true;
    if (modifiers.includes('capture')) flags.capture = true;
  }
 
  /**
   * Stores elements and executed modifier keys for once handlers.
   * @type {WeakMap<Element, Set<string>>}
   * @private
   */
  #onceExecuted = new WeakMap();
 
  /**
   * Reads all event handlers (including delegation metadata) from an element.
   * Supports both data-ax-event and traditional @event attributes.
   * @param {Element} el
   * @returns {Array<{fullName: string, value: string, attrName: string}>}
   * @private
   */
  #getEventHandlers(el) {
    const handlers = [];
    if (!el) return handlers;
 
    if (el.hasAttribute && el.hasAttribute('data-ax-event')) {
      const attrVal = el.getAttribute('data-ax-event');
      try {
        const parsed = JSON.parse(attrVal);
        for (const [key, val] of Object.entries(parsed)) {
          handlers.push({
            fullName: key,
            value: val,
            attrName: `data-ax-event:${key}`
          });
        }
      } catch {
        // Ignored
      }
    }
 
    if (el.attributes) {
      Array.from(el.attributes).forEach((attr) => {
        if (attr.name.startsWith('@')) {
          handlers.push({
            fullName: attr.name.substring(1),
            value: attr.value,
            attrName: attr.name
          });
        }
      });
    }
 
    return handlers;
  }
 
  /**
   * Binds event listeners to all elements under the root that have attributes starting with '@'.
   * Uses event delegation on Element roots, falls back to direct binding on DocumentFragments.
   * @param {Element|DocumentFragment} root - The root element to bind events on.
   * @param {object} dispatcher - The object responsible for executing the event handler.
   * @param {function(string, Event): void} dispatcher.execute - Method to execute the event.
   */
  bind(root, dispatcher) {
    if (!root) return;
    if (root.nodeType === 11) {
      this.#bindDirect(root, dispatcher);
    } else {
      this.#bindDelegated(root, dispatcher);
    }
  }
 
  /**
   * Removes all event listeners for the given root.
   * @param {Element|DocumentFragment} root
   */
  unbind(root) {
    if (!root) return;
    if (root.nodeType === 11) {
      this.#unbindDirect(root);
    } else {
      this.#unbindDelegated(root);
      this.#unbindDirect(root);
    }
  }
 
  /**
   * @param {Element} root
   * @param {object} dispatcher
   */
  #bindDelegated(root, dispatcher) {
    const COMMON_EVENTS = ['click', 'input', 'change', 'keydown'];
    const eventNames = new Set(COMMON_EVENTS);
    /** @type {Map<string, {passive: boolean, capture: boolean}>} */
    const eventFlags = new Map();
 
    const ensureFlags = (eventName) => {
      if (!eventFlags.has(eventName)) {
        eventFlags.set(eventName, { passive: false, capture: false });
      }
      return eventFlags.get(eventName);
    };
 
    COMMON_EVENTS.forEach((name) => ensureFlags(name));
 
    const traverse = (node) => {
      if (node.nodeType !== 1) return;
 
      const handlers = this.#getEventHandlers(node);
      handlers.forEach((h) => {
        const parts = h.fullName.split('.');
        const baseEventName = parts[0];
        eventNames.add(baseEventName);
        this.#orListenerFlags(ensureFlags(baseEventName), parts.slice(1));
      });
 
      if (node.nodeName === 'SLOT' && node.hasAttribute && node.hasAttribute('data-avenx-transcluded')) {
        return;
      }
      if (
        node !== root &&
        node.hasAttribute &&
        (node.hasAttribute('data-avenx-comp') || node.hasAttribute('data-avenx-comp-dynamic'))
      ) {
        return;
      }
 
      const children = node.childNodes || node.children;
      if (children) {
        for (let i = 0; i < children.length; i++) {
          traverse(children[i]);
        }
      }
    };
    traverse(root);
 
    if (!root.__avenxDelegatedListeners) {
      root.__avenxDelegatedListeners = new Map();
    }
    const delegatedMap = root.__avenxDelegatedListeners;
    const existing = this.#boundEvents.get(root) || new Map();
 
    eventNames.forEach((eventName) => {
      if (delegatedMap.has(eventName)) {
        const oldEntry = delegatedMap.get(eventName);
        const oldHandler = typeof oldEntry === 'function' ? oldEntry : oldEntry.handler;
        const oldOptions = typeof oldEntry === 'function' ? undefined : oldEntry.options;
        if (typeof root.removeEventListener === 'function') {
          root.removeEventListener(eventName, oldHandler, oldOptions);
        }
        delegatedMap.delete(eventName);
        existing.delete(eventName);
      }
 
      const handler = (event) => {
        let current = (event && event.target) || root;
        while (current) {
          if (belongsToComponent(current, root)) {
            if (current.hasAttribute && current.hasAttribute('data-ax-validate')) {
              if (dispatcher && typeof dispatcher.validate === 'function') {
                dispatcher.validate(current);
              }
            }
            const handlers = this.#getEventHandlers(current);
            handlers.forEach((h) => {
              const parts = h.fullName.split('.');
              const baseEventName = parts[0];
              if (baseEventName === eventName) {
                const modifiers = parts.slice(1);
                if (h.value) {
                  this.#executeWithModifiers(dispatcher, h.value, event, modifiers, current, h.attrName);
                }
              }
            });
          }
          if (current === root) {
            break;
          }
          current = current.parentNode;
          if (event.cancelBubble) {
            break;
          }
        }
      };
 
      const options = this.#toListenerOptions(eventFlags.get(eventName));
      if (typeof root.addEventListener === 'function') {
        root.addEventListener(eventName, handler, options);
      }
      const entry = { handler, options };
      delegatedMap.set(eventName, entry);
      existing.set(eventName, entry);
      this.#boundEvents.set(root, existing);
    });
  }
 
  /**
   * @param {Element} root
   */
  #unbindDelegated(root) {
    if (root.__avenxDelegatedListeners) {
      root.__avenxDelegatedListeners.forEach((entry, eventName) => {
        const handler = typeof entry === 'function' ? entry : entry.handler;
        const options = typeof entry === 'function' ? undefined : entry.options;
        if (typeof root.removeEventListener === 'function') {
          root.removeEventListener(eventName, handler, options);
        }
      });
      delete root.__avenxDelegatedListeners;
    }
    const existing = this.#boundEvents.get(root);
    if (existing) {
      existing.forEach((entry, eventName) => {
        const handler = typeof entry === 'function' ? entry : entry.handler;
        const options = typeof entry === 'function' ? undefined : entry.options;
        if (typeof root.removeEventListener === 'function') {
          root.removeEventListener(eventName, handler, options);
        }
      });
      this.#boundEvents.delete(root);
    }
  }
 
  /**
   * @param {Element|DocumentFragment} root
   * @param {object} dispatcher
   */
  #bindDirect(root, dispatcher) {
    const elements = [];
    const traverse = (node) => {
      if (node.nodeType !== 1 && node.nodeType !== 11) return;
      if (node.nodeType === 1) {
        elements.push(node);
      }
      if (node.nodeName === 'SLOT' && node.hasAttribute && node.hasAttribute('data-avenx-transcluded')) {
        return;
      }
      const children = node.childNodes || node.children;
      if (children) {
        for (let i = 0; i < children.length; i++) {
          traverse(children[i]);
        }
      }
    };
    traverse(root);
 
    elements.forEach((el) => {
      if (!el.__avenxDirectListeners) {
        el.__avenxDirectListeners = new Map();
      }
      const directMap = el.__avenxDirectListeners;
      const existing = this.#boundEvents.get(el) || new Map();
      const handlers = this.#getEventHandlers(el);
 
      // Remove any existing direct listeners on el before binding new ones
      directMap.forEach((oldEntry, baseEventName) => {
        const oldHandler = typeof oldEntry === 'function' ? oldEntry : oldEntry.handler;
        const oldOptions = typeof oldEntry === 'function' ? undefined : oldEntry.options;
        if (typeof el.removeEventListener === 'function') {
          el.removeEventListener(baseEventName, oldHandler, oldOptions);
        }
      });
      directMap.clear();
      existing.clear();
 
      /** @type {Map<string, {passive: boolean, capture: boolean}>} */
      const eventFlags = new Map();
      handlers.forEach((h) => {
        const parts = h.fullName.split('.');
        const baseEventName = parts[0];
        if (!eventFlags.has(baseEventName)) {
          eventFlags.set(baseEventName, { passive: false, capture: false });
        }
        this.#orListenerFlags(eventFlags.get(baseEventName), parts.slice(1));
      });
 
      handlers.forEach((h) => {
        const parts = h.fullName.split('.');
        const baseEventName = parts[0];
 
        if (!directMap.has(baseEventName)) {
          const handler = (event) => {
            const currentHandlers = this.#getEventHandlers(el);
            currentHandlers.forEach((ch) => {
              const cp = ch.fullName.split('.');
              const cbEventName = cp[0];
              if (cbEventName === baseEventName) {
                const mods = cp.slice(1);
                if (ch.value) {
                  this.#executeWithModifiers(dispatcher, ch.value, event, mods, el, ch.attrName);
                }
              }
            });
          };
          const options = this.#toListenerOptions(eventFlags.get(baseEventName));
          if (typeof el.addEventListener === 'function') {
            el.addEventListener(baseEventName, handler, options);
          }
          const entry = { handler, options };
          directMap.set(baseEventName, entry);
          existing.set(baseEventName, entry);
          this.#boundEvents.set(el, existing);
        }
      });
    });
  }
 
  /**
   * Resolves the scope an element's bindings belong to.
   *
   * A scoped slot was the first thing to need this; a `<@for>` row needs
   * exactly the same answer, so the walk lives in one module now and both stamp
   * through it.
   * @param {Element} el - The element a binding is attached to.
   * @returns {object|null} The nearest enclosing derived scope, or null.
   * @private
   */
  #getSlotScope(el) {
    return findScope(el);
  }
 
  /**
   * Executes the handler expression if modifiers permit, and applies modifier effects.
   * @param {object} dispatcher
   * @param {string} handlerExpression
   * @param {Event} event
   * @param {string[]} modifiers
   * @param {Element} el
   * @param {string} attrName
   * @private
   */
  #executeWithModifiers(dispatcher, handlerExpression, event, modifiers, el, attrName) {
    // 0. Check self modifier
    if (modifiers.includes('self')) {
      if (event && event.target && event.target !== el) {
        return;
      }
    }
 
    // 1. Check once modifier
    if (modifiers.includes('once')) {
      let executedSet = this.#onceExecuted.get(el);
      if (!executedSet) {
        executedSet = new Set();
        this.#onceExecuted.set(el, executedSet);
      }
      if (executedSet.has(attrName)) {
        return;
      }
      executedSet.add(attrName);
    }
 
    // 2. Check system key modifiers
    const SYSTEM_MODIFIER_MAP = {
      ctrl: 'ctrlKey',
      alt: 'altKey',
      shift: 'shiftKey',
      meta: 'metaKey',
      cmd: 'metaKey',
    };
 
    const systemModifiers = modifiers.filter(m => Object.prototype.hasOwnProperty.call(SYSTEM_MODIFIER_MAP, m));
    if (systemModifiers.some(mod => !event || event[SYSTEM_MODIFIER_MAP[mod]] !== true)) {
      return;
    }
 
    // 3. Check key modifiers for keyboard events
    const KEY_MODIFIER_MAP = {
      enter: 'Enter',
      esc: 'Escape',
      escape: 'Escape',
      space: ' ',
      tab: 'Tab',
      delete: 'Delete',
    };
 
    const keyModifiers = modifiers.filter(m => Object.prototype.hasOwnProperty.call(KEY_MODIFIER_MAP, m));
    if (keyModifiers.length > 0) {
      if (!event || typeof event.key !== 'string') {
        return;
      }
      const matches = keyModifiers.some(mod => event.key === KEY_MODIFIER_MAP[mod]);
      if (!matches) {
        return;
      }
    }
 
    // 4. Apply prevent & stop modifiers
    // Skip preventDefault when .passive is present — browsers ignore it on passive listeners
    if (
      modifiers.includes('prevent') &&
      !modifiers.includes('passive') &&
      event &&
      typeof event.preventDefault === 'function'
    ) {
      event.preventDefault();
    }
    if (modifiers.includes('stop') && event && typeof event.stopPropagation === 'function') {
      event.stopPropagation();
    }
 
    // 4. Execute handler
    const slotScope = this.#getSlotScope(el);
    dispatcher.execute(handlerExpression, event, slotScope);
  }
 
  /**
   * @param {Element|DocumentFragment} root
   */
  #unbindDirect(root) {
    const elements = [];
    const traverse = (node) => {
      if (node.nodeType !== 1 && node.nodeType !== 11) return;
      if (node.nodeType === 1) {
        elements.push(node);
      }
      if (node.nodeName === 'SLOT' && node.hasAttribute && node.hasAttribute('data-avenx-transcluded')) {
        return;
      }
      const children = node.childNodes || node.children;
      if (children) {
        for (let i = 0; i < children.length; i++) {
          traverse(children[i]);
        }
      }
    };
    traverse(root);
 
    elements.forEach((el) => {
      if (el.__avenxDirectListeners) {
        el.__avenxDirectListeners.forEach((entry, eventName) => {
          const handler = typeof entry === 'function' ? entry : entry.handler;
          const options = typeof entry === 'function' ? undefined : entry.options;
          if (typeof el.removeEventListener === 'function') {
            el.removeEventListener(eventName, handler, options);
          }
        });
        delete el.__avenxDirectListeners;
      }
 
      const existing = this.#boundEvents.get(el);
      if (existing) {
        existing.forEach((entry, eventName) => {
          const handler = typeof entry === 'function' ? entry : entry.handler;
          const options = typeof entry === 'function' ? undefined : entry.options;
          if (typeof el.removeEventListener === 'function') {
            el.removeEventListener(eventName, handler, options);
          }
        });
        this.#boundEvents.delete(el);
      }
    });
  }
 
  /**
   * Resets internal WeakMaps to release any remaining element-handler references.
   */
  teardown() {
    this.#boundEvents = new WeakMap();
    this.#onceExecuted = new WeakMap();
  }
}