All files / lib/compiler/parser/directives eventDelegation.js

100% Statements 53/53
80% Branches 8/10
100% Functions 2/2
100% Lines 53/53

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 54532x 532x 532x 532x 532x 532x 532x 532x 532x 532x 532x 532x 532x 532x 532x 532x 532x 532x 532x 532x 532x 532x 532x 532x 911x 911x 911x 911x 911x 7671x 3124x 3124x 3017x 560x 560x 560x 555x 555x 555x 560x 3017x 3124x 554x 554x 3124x 3124x 3124x 3124x 911x 911x 911x 911x 911x  
/**
 * @file eventDelegation.js
 * @description Folds common `@event` handlers into one `data-ax-event` attribute for delegation.
 */
import { parseHTML, serializeHTML } from '../htmlTree.js';
import { getCustomVoidTags } from '../projectConfig.js';
 
/**
 * The events the runtime delegates from the component root. Any other `@event`
 * attribute is left on its element and bound directly.
 * @type {string[]}
 */
const COMMON_EVENTS = ['click', 'input', 'change', 'keydown'];
 
/**
 * Translates common event handler attributes (@click, @input, etc.)
 * to a single data-ax-event JSON-encoded attribute for centralized delegation.
 * @param {string} template - The HTML template string.
 * @param {string} filePath - The component file path.
 * @param {object} [options] - Parser state the pass reads.
 * @param {string[]} [options.customVoidTags] - Void tags configured on the parser itself.
 * @returns {string} The transformed template string.
 */
export function processEventDelegation(template, filePath, { customVoidTags = [] } = {}) {
  if (!template) return template;
  const voidTags = [...(customVoidTags || []), ...getCustomVoidTags(filePath)];
  const nodes = parseHTML(template, voidTags);
 
  const transformNode = (node) => {
    if (node.type === 'element') {
      const eventMap = {};
      for (const [name, val] of Object.entries(node.attrs)) {
        if (name.startsWith('@')) {
          const fullEventName = name.substring(1);
          const baseEventName = fullEventName.split('.')[0];
          if (COMMON_EVENTS.includes(baseEventName)) {
            delete node.attrs[name];
            eventMap[fullEventName] = val;
          }
        }
      }
      if (Object.keys(eventMap).length > 0) {
        node.attrs['data-ax-event'] = JSON.stringify(eventMap);
      }
      if (node.children) {
        node.children.forEach(transformNode);
      }
    }
  };
 
  nodes.forEach(transformNode);
  return serializeHTML(nodes, voidTags);
}