/**
 * Copyright IBM Corp. 2026
 *
 * This source code is licensed under the Apache-2.0 license found in the
 * LICENSE file in the root directory of this source tree.
 */

import on from "./on.js";
//#region src/globals/mixins/host-listener.ts
/**
* Copyright IBM Corp. 2019, 2023
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* The format for the event name used by `@HostListener` decorator.
*/
const EVENT_NAME_FORMAT = /^((document|window|parentRoot|shadowRoot):)?([\w-]+)$/;
/**
* @param Base The base class.
* @returns A mix-in that sets up and cleans up event listeners defined by `@HostListener` decorator.
*/
const HostListenerMixin = (Base) => {
	/**
	* A mix-in class that sets up and cleans up event listeners defined by `@HostListener` decorator.
	*/
	class HostListenerMixinImpl extends Base {
		constructor(..._args) {
			super(..._args);
			this._handles = /* @__PURE__ */ new Set();
		}
		connectedCallback() {
			super.connectedCallback();
			const hostListeners = this.constructor._hostListeners;
			Object.keys(hostListeners).forEach((listenerName) => {
				Object.keys(hostListeners[listenerName]).forEach((type) => {
					const tokens = EVENT_NAME_FORMAT.exec(type);
					if (!tokens) throw new Error(`Could not parse the event name: ${listenerName}`);
					const [, , targetName, unprefixedType] = tokens;
					const target = {
						document: this.ownerDocument,
						window: this.ownerDocument.defaultView,
						parentRoot: this.getRootNode(),
						shadowRoot: this.shadowRoot
					}[targetName] || this;
					const { options } = hostListeners[listenerName][type];
					this._handles.add(on(target, this.constructor[unprefixedType] ?? unprefixedType, this[listenerName], options));
				});
			});
		}
		disconnectedCallback() {
			this._handles.forEach((handle) => {
				handle.release();
				this._handles.delete(handle);
			});
			super.disconnectedCallback();
		}
		static {
			this._hostListeners = {};
		}
	}
	return HostListenerMixinImpl;
};
//#endregion
export { HostListenerMixin as default };

//# sourceMappingURL=host-listener.js.map