import * as i0 from '@angular/core';
import { inject, PLATFORM_ID, ElementRef, Renderer2, output, input, signal, Directive } from '@angular/core';
import { isPlatformServer } from '@angular/common';

class ContentEditorContentEditableDirective {
    _platformId = inject(PLATFORM_ID);
    _elementRef = inject(ElementRef);
    _renderer = inject(Renderer2);
    contentChanged = output();
    pressedEnter = output();
    initialized = output();
    _observer;
    content = input('', { ...(ngDevMode ? { debugName: "content" } : /* istanbul ignore next */ {}), alias: 'ngsContentEditorContentEditable' });
    settings = input({}, ...(ngDevMode ? [{ debugName: "settings" }] : /* istanbul ignore next */ []));
    props = input([], ...(ngDevMode ? [{ debugName: "props" }] : /* istanbul ignore next */ []));
    _props = signal([], ...(ngDevMode ? [{ debugName: "_props" }] : /* istanbul ignore next */ []));
    propsChanged = output();
    _isAlreadyRendered = false;
    ngOnInit() {
        this._props.set(this.props() || []);
        (this.props() || []).forEach(prop => {
            this._renderer.setAttribute(this._elementRef.nativeElement, `data-props-${prop.name}`, prop.value);
        });
        this._renderer.setAttribute(this._elementRef.nativeElement, 'contenteditable', 'true');
        if (this._isAlreadyRendered) {
            return;
        }
        if (this.content()) {
            this._elementRef.nativeElement.innerHTML = this.content();
        }
        this._isAlreadyRendered = true;
        this.initialized.emit();
        let prevContent = this.getContent();
        if (isPlatformServer(this._platformId)) {
            return;
        }
        const config = { attributes: true, childList: true, subtree: true };
        const callback = (mutationList, observer) => {
            for (const mutation of mutationList) {
                if (mutation.type === 'attributes') {
                    if (mutation.attributeName.startsWith('data-props-')) {
                        const prevPropsHash = JSON.stringify(this._props());
                        const propName = mutation.attributeName.replace('data-props-', '');
                        const propValue = mutation.target.getAttribute(mutation.attributeName);
                        const propIndex = this._props().findIndex(p => p.name === propName);
                        if (propIndex >= 0) {
                            this._props.update((props) => {
                                props[propIndex].value = propValue;
                                return props;
                            });
                        }
                        else {
                            this._props.update((props) => {
                                props.push({
                                    name: propName,
                                    value: propValue,
                                });
                                return props;
                            });
                        }
                        const updatedPropsHash = JSON.stringify(this._props());
                        if (prevPropsHash !== updatedPropsHash) {
                            this.propsChanged.emit(this._props());
                        }
                    }
                }
                else {
                    const currentContent = this.getContent();
                    if (prevContent !== currentContent) {
                        prevContent = currentContent;
                        this._raiseUpdateEvent();
                    }
                }
            }
        };
        this._observer = new MutationObserver(callback);
        this._observer.observe(this._elementRef.nativeElement, config);
    }
    ngOnDestroy() {
        this._observer?.disconnect();
    }
    getContent() {
        let content = this._elementRef.nativeElement.innerHTML;
        content = content.replaceAll('<br>', '').replaceAll(/&nbsp;/g, ' ').trim();
        if (content.length === 0) {
            this._elementRef.nativeElement.innerHTML = '';
        }
        return content;
    }
    _handleBlur(event) {
    }
    _handleInput(event) {
        if (!this._isAlreadyRendered) {
            return;
        }
        this._raiseUpdateEvent();
    }
    _raiseUpdateEvent() {
        this.contentChanged.emit(this.getContent());
    }
    _handleKeyPress(event) {
        if (event.key === 'Enter') {
            this.pressedEnter.emit(event);
        }
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: ContentEditorContentEditableDirective, deps: [], target: i0.ɵɵFactoryTarget.Directive });
    static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.4", type: ContentEditorContentEditableDirective, isStandalone: true, selector: "[ngsContentEditorContentEditable]", inputs: { content: { classPropertyName: "content", publicName: "ngsContentEditorContentEditable", isSignal: true, isRequired: false, transformFunction: null }, settings: { classPropertyName: "settings", publicName: "settings", isSignal: true, isRequired: false, transformFunction: null }, props: { classPropertyName: "props", publicName: "props", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { contentChanged: "contentChanged", pressedEnter: "pressedEnter", initialized: "initialized", propsChanged: "propsChanged" }, host: { listeners: { "blur": "_handleBlur($event)", "input": "_handleInput($event)", "keypress": "_handleKeyPress($event)" }, properties: { "class.ngs-content-editor-content-editable": "true" } }, exportAs: ["ngsContentEditorContentEditable"], ngImport: i0 });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: ContentEditorContentEditableDirective, decorators: [{
            type: Directive,
            args: [{
                    selector: '[ngsContentEditorContentEditable]',
                    exportAs: 'ngsContentEditorContentEditable',
                    host: {
                        '[class.ngs-content-editor-content-editable]': 'true',
                        '(blur)': '_handleBlur($event)',
                        '(input)': '_handleInput($event)',
                        '(keypress)': '_handleKeyPress($event)',
                    }
                }]
        }], propDecorators: { contentChanged: [{ type: i0.Output, args: ["contentChanged"] }], pressedEnter: [{ type: i0.Output, args: ["pressedEnter"] }], initialized: [{ type: i0.Output, args: ["initialized"] }], content: [{ type: i0.Input, args: [{ isSignal: true, alias: "ngsContentEditorContentEditable", required: false }] }], settings: [{ type: i0.Input, args: [{ isSignal: true, alias: "settings", required: false }] }], props: [{ type: i0.Input, args: [{ isSignal: true, alias: "props", required: false }] }], propsChanged: [{ type: i0.Output, args: ["propsChanged"] }] } });

export { ContentEditorContentEditableDirective as C };
//# sourceMappingURL=ngstarter-ui-components-content-editor-content-editor-content-editable.directive-Bvfa2dqh.mjs.map
