import isFirefox from '../utils/isFirefox';
import { addEventListener } from '../utils/component/event-handler';
var gEventRegistered = false;
var subscriberList = [];
var cancelEvent = null;
export function install(config) {
    if (!gEventRegistered) {
        if (isFirefox) {
            cancelEvent = addEventListener(document, 'click', onDocumentSelectionChange, {
                capture: true,
                passive: true,
            });
        }
        else {
            cancelEvent = addEventListener(document, 'selectionchange', onDocumentSelectionChange, { passive: true });
        }
    }
    var idx = findSubscriberIndex(config);
    if (idx === -1) {
        subscriberList.push(config);
    }
}
export function uninstall(config) {
    var idx = findSubscriberIndex(config);
    if (idx === -1) {
        return;
    }
    subscriberList.splice(idx, 1);
    if (subscriberList.length === 0) {
        cancelEvent();
    }
}
function onDocumentSelectionChange(evt) {
    var activeElement = document.activeElement;
    var matchedSubscriberIndex = findSubscriberIndex({
        node: activeElement,
    });
    if (matchedSubscriberIndex !== -1) {
        subscriberList[matchedSubscriberIndex].callback(evt);
    }
}
function findSubscriberIndex(config) {
    var keys = Object.keys(config);
    return subscriberList.findIndex(function (item) {
        return keys.every(function (k) { return item[k] === config[k]; });
    });
}
