// #region Imports
import { DomServiceLocator } from '../../../../Dom/Dom';
import { ControllerBase } from '../../../Controllers/Abstracts/ControllerBase';
import { SlotController } from '../../../Controllers/SlotController';
import { PortalElement } from './PortalElement';
/**
 * A controller that observes content projected into a slot in the host,
 * removes the DOM nodes from the host, and transfers them into a render target
 * inside a portal component.
 *
 * @public
 */
export class ProjectionController extends ControllerBase {
    // #region Fields
    _slotController;
    _slotName;
    _targetSelector;
    _observer;
    // #endregion
    // #region Ctor
    constructor(host, options) {
        super(host);
        this._slotController = new SlotController(host);
        this._slotName = options.slotName ?? '';
        this._targetSelector = options.targetSelector;
        this._observer = new MutationObserver(() => this.projectContent());
    }
    // #endregion
    // #region Methods
    /**
     * @public
     * @override
     */
    hostFirstUpdated() {
        super.hostFirstUpdated();
        this.projectContent();
        this._observer.observe(this.host, {
            childList: true,
            subtree: true
        });
    }
    /**
     * @public
     * @override
     */
    hostDisconnected() {
        this._observer.disconnect();
        super.hostDisconnected();
    }
    /**
     * @private
     */
    projectContent() {
        const elements = this._slotController.getAssignedElements(this._slotName);
        // Remove from host DOM to prevent double rendering
        elements.forEach((n) => {
            if (n.parentNode) {
                n.parentNode.removeChild(n);
            }
        });
        if (this.host.shadowRoot) {
            const portal = DomServiceLocator.current.findDescendant(this.host.shadowRoot, PortalElement.is, { strict: true });
            const target = DomServiceLocator.current.findDescendant(portal, this._targetSelector, { strict: true });
            target.replaceChildren(...elements);
        }
        else {
            console.warn('[ProjectionController] Host does not have a shadow root. Projection will not work.');
        }
    }
}
//# sourceMappingURL=ProjectionController.js.map