All files / roosterjs-content-model-core/lib/coreApi/attachDomEvent attachDomEvent.ts

100% Statements 19/19
100% Branches 6/6
100% Functions 6/6
100% Lines 14/14

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 421x                     1x 490x 1760x 1760x 1760x 49x 48x     49x 2x                     1760x   1760x 1322x       1322x    
import { getObjectKeys } from 'roosterjs-content-model-dom';
import type { AttachDomEvent, PluginEvent } from 'roosterjs-content-model-types';
 
/**
 * @internal
 * Attach a DOM event to the editor content DIV
 * @param core The EditorCore object
 * @param eventName The DOM event name
 * @param pluginEventType Optional event type. When specified, editor will trigger a plugin event with this name when the DOM event is triggered
 * @param beforeDispatch Optional callback function to be invoked when the DOM event is triggered before trigger plugin event
 */
export const attachDomEvent: AttachDomEvent = (core, eventMap) => {
    const disposers = getObjectKeys(eventMap || {}).map(key => {
        const { pluginEventType, beforeDispatch } = eventMap[key];
        const eventName = key as keyof HTMLElementEventMap;
        const onEvent = (event: HTMLElementEventMap[typeof eventName]) => {
            if (beforeDispatch) {
                beforeDispatch(event);
            }
 
            if (pluginEventType != null) {
                core.api.triggerEvent(
                    core,
                    <PluginEvent>{
                        eventType: pluginEventType,
                        rawEvent: event,
                    },
                    false /*broadcast*/
                );
            }
        };
 
        core.logicalRoot.addEventListener(eventName, onEvent);
 
        return () => {
            core.logicalRoot.removeEventListener(eventName, onEvent);
        };
    });
 
    return () => disposers.forEach(disposers => disposers());
};