import * as i0 from '@angular/core';
import { inject, PLATFORM_ID, ElementRef, input, output, Directive, signal, ChangeDetectionStrategy, Component } from '@angular/core';
import { C as ContentBuilderStore, a as CONTENT_BUILDER, b as CONTENT_EDITOR_BLOCK } from './ngstarter-ui-components-content-editor-ngstarter-ui-components-content-editor-DNLTNGYa.mjs';
import { C as ContentEditorContentEditableDirective } from './ngstarter-ui-components-content-editor-content-editor-content-editable.directive-Bvfa2dqh.mjs';
import { isPlatformServer, NgTemplateOutlet } from '@angular/common';
import { C as CursorController } from './ngstarter-ui-components-content-editor-cursor-controller-4Ak8VqGX.mjs';

class ContentObserverDirective {
    _platformId = inject(PLATFORM_ID);
    _elementRef = inject(ElementRef);
    _observer;
    detectAddedNode = input.required(...(ngDevMode ? [{ debugName: "detectAddedNode" }] : /* istanbul ignore next */ []));
    nodeAdded = output();
    ngOnInit() {
        if (isPlatformServer(this._platformId)) {
            return;
        }
        const config = { attributes: false, childList: true, subtree: false };
        const callback = (mutationList, observer) => {
            for (const mutation of mutationList) {
                if (mutation.type === 'childList') {
                    const addedNode = mutation.addedNodes[0];
                    if (addedNode && addedNode.tagName && addedNode.classList.contains(this.detectAddedNode())) {
                        this.nodeAdded.emit(addedNode);
                    }
                }
            }
        };
        this._observer = new MutationObserver(callback);
        this._observer.observe(this._elementRef.nativeElement, config);
    }
    ngOnDestroy() {
        this._observer?.disconnect();
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: ContentObserverDirective, deps: [], target: i0.ɵɵFactoryTarget.Directive });
    static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.4", type: ContentObserverDirective, isStandalone: true, selector: "[ngsContentObserver]", inputs: { detectAddedNode: { classPropertyName: "detectAddedNode", publicName: "detectAddedNode", isSignal: true, isRequired: true, transformFunction: null } }, outputs: { nodeAdded: "nodeAdded" }, ngImport: i0 });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: ContentObserverDirective, decorators: [{
            type: Directive,
            args: [{
                    selector: '[ngsContentObserver]'
                }]
        }], propDecorators: { detectAddedNode: [{ type: i0.Input, args: [{ isSignal: true, alias: "detectAddedNode", required: true }] }], nodeAdded: [{ type: i0.Output, args: ["nodeAdded"] }] } });

class ListBlockComponent {
    _store = inject(ContentBuilderStore);
    _contentBuilder = inject(CONTENT_BUILDER);
    id = input.required(...(ngDevMode ? [{ debugName: "id" }] : /* istanbul ignore next */ []));
    content = input.required(...(ngDevMode ? [{ debugName: "content" }] : /* istanbul ignore next */ []));
    settings = input.required(...(ngDevMode ? [{ debugName: "settings" }] : /* istanbul ignore next */ []));
    index = input.required(...(ngDevMode ? [{ debugName: "index" }] : /* istanbul ignore next */ []));
    _placeholder = signal('List item', ...(ngDevMode ? [{ debugName: "_placeholder" }] : /* istanbul ignore next */ []));
    _content = signal([
        {
            content: '',
            props: [],
            children: []
        }
    ], ...(ngDevMode ? [{ debugName: "_content" }] : /* istanbul ignore next */ []));
    _listStyle = signal('', ...(ngDevMode ? [{ debugName: "_listStyle" }] : /* istanbul ignore next */ []));
    initialized = signal(false, ...(ngDevMode ? [{ debugName: "initialized" }] : /* istanbul ignore next */ []));
    ngOnInit() {
        this._listStyle.set(this.settings().listStyle);
        if (this.content().length !== 0) {
            this._content.set(this.content());
        }
    }
    ngAfterViewInit() {
        this.initialized.set(true);
    }
    focus() {
    }
    onContentChanged(content, list, index) {
        if (!list[index]) {
            return;
        }
        list[index].content = content;
        this.update();
    }
    onPressedEnter(event, contentEditable, list, index, level, parentItem, parentList) {
        event.preventDefault();
        event.stopPropagation();
        if (level === 0) {
            const content = contentEditable.getContent();
            if (content) {
                list.splice(index + 1, 0, {
                    content: '',
                    props: [],
                    styles: {},
                    children: []
                });
            }
            else {
                list.splice(index, 1);
                if (list.length === 0) {
                    this._contentBuilder.deleteBlock(this.id());
                }
                this._contentBuilder.insertEmptyBlock(this.index());
            }
        }
        else {
            if (list[index] && !list[index].content) {
                list.splice(index, 1);
                const parentIndex = parentList.findIndex(item => item === parentItem);
                parentList.splice(parentIndex + 1, 0, {
                    content: '',
                    props: [],
                    children: []
                });
            }
            else {
                list.splice(index + 1, 0, {
                    content: '',
                    props: [],
                    styles: {},
                    children: []
                });
            }
        }
        this.update();
    }
    getId(level, index) {
        return 'item-level-' + (level + index + 2).toString();
    }
    getData() {
        return {
            content: this._content(),
            settings: {
                ...this.settings(),
            }
        };
    }
    isEmpty() {
        return this.getData().content.find((item) => item.content.trim().length > 0);
    }
    _onNodeAdded(node) {
        this._focusItem(node.querySelector('.list-item-content'));
    }
    _focusItem(element) {
        const cursorController = new CursorController(element);
        cursorController.setToEnd();
    }
    _onKeyDown(event, contentEditable, list, index, level, parentItem, parentList, listItem) {
        if (event.key === 'Backspace' && !contentEditable.getContent()) {
            const latestElementInParentList = listItem.closest('.list')?.parentNode;
            list.splice(index, 1);
            const prevElement = listItem.previousSibling;
            if (prevElement) {
                this._focusItem(prevElement.querySelector('.list-item-content'));
            }
            else {
                if (latestElementInParentList) {
                    this._focusItem(latestElementInParentList.querySelector('.list-item-content'));
                }
            }
        }
        else if (event.key === 'Tab') {
            event.preventDefault();
            event.stopPropagation();
            if (event.shiftKey && parentItem) {
                const cached = JSON.parse(JSON.stringify(list[index]));
                list.splice(index, 1);
                const parentIndex = parentList.findIndex(item => item === parentItem);
                parentList.splice(parentIndex + 1, 0, cached);
            }
            else {
                if (list[index - 1]) {
                    const cached = JSON.parse(JSON.stringify(list[index]));
                    list.splice(index, 1);
                    list[index - 1].children.push(cached);
                }
            }
        }
        if (level === 0 && list.length === 0) {
            this._contentBuilder.deleteBlock(this.id());
        }
        this.update();
    }
    onPropsChanged(props, item) {
        item.props = props;
        this.update();
    }
    update() {
        this._store.updateBlock(this.id(), { ...this.getData(), isEmpty: this.isEmpty() });
        this._contentBuilder.emitContentChangeEvent();
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: ListBlockComponent, deps: [], target: i0.ɵɵFactoryTarget.Component });
    static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "21.2.4", type: ListBlockComponent, isStandalone: true, selector: "ngs-list-block", inputs: { id: { classPropertyName: "id", publicName: "id", isSignal: true, isRequired: true, transformFunction: null }, content: { classPropertyName: "content", publicName: "content", isSignal: true, isRequired: true, transformFunction: null }, settings: { classPropertyName: "settings", publicName: "settings", isSignal: true, isRequired: true, transformFunction: null }, index: { classPropertyName: "index", publicName: "index", isSignal: true, isRequired: true, transformFunction: null } }, host: { properties: { "class.list-bullet": "_listStyle() === 'bullet'", "class.list-ordered": "_listStyle() === 'ordered'" } }, providers: [
            {
                provide: CONTENT_EDITOR_BLOCK,
                useExisting: ListBlockComponent,
                multi: true
            }
        ], exportAs: ["ngsListBlock"], ngImport: i0, template: "<ul class=\"list\"\n    ngsContentObserver\n    detectAddedNode=\"list-item\"\n    (nodeAdded)=\"_onNodeAdded($event)\">\n  <ng-container [ngTemplateOutlet]=\"listTpl\"\n                [ngTemplateOutletContext]=\"{ $implicit: _content(), level: 0, parentItem: null, parentList: [] }\"/>\n</ul>\n\n<ng-template #listTpl let-list let-level=\"level\" let-parentItem=\"parentItem\" let-parentList=\"parentList\">\n  @for (item of list; track $index; let index = $index) {\n    <li #listItem class=\"list-item\" [attr.id]=\"getId(level, index)\">\n      <div [ngsContentEditorContentEditable]=\"item.content\"\n           [props]=\"item.props\"\n           (propsChanged)=\"onPropsChanged($event, item)\"\n           #contentEditable=\"ngsContentEditorContentEditable\"\n           class=\"list-item-content\"\n           (contentChanged)=\"onContentChanged($event, list, index)\"\n           (pressedEnter)=\"onPressedEnter($event, contentEditable, list, index, level, parentItem, parentList)\"\n           (keydown)=\"_onKeyDown($event, contentEditable, list, index, level, parentItem, parentList, listItem)\"\n           [attr.data-empty-placeholder]=\"_placeholder()\"></div>\n      @if (item.children.length > 0) {\n        <ol class=\"list\"\n            ngsContentObserver\n            detectAddedNode=\"list-item\"\n            (nodeAdded)=\"_onNodeAdded($event)\">\n          <ng-container [ngTemplateOutlet]=\"listTpl\"\n                        [ngTemplateOutletContext]=\"{ $implicit: item.children, level: level + 1, parentItem: item, parentList: list }\"/>\n        </ol>\n      }\n    </li>\n  }\n</ng-template>\n", styles: [":host .list{display:flex;flex-direction:column;gap:calc(var(--spacing, .25rem) * 2);padding-inline-start:calc(var(--spacing, .25rem) * 4);--tw-outline-style: none;outline-style:none}:host .list .list{margin-top:calc(var(--spacing, .25rem) * 2);padding-inline-start:calc(var(--spacing, .25rem) * 4)}:host.list-ordered .list{list-style-type:decimal}:host.list-bullet .list{list-style-type:disc}:host .list-item-content{--tw-outline-style: none;outline-style:none}:host .list-item-content:empty:before{content:attr(data-empty-placeholder);color:var(--ngs-color-neutral-500)}\n/*! tailwindcss v4.2.2 | MIT License | https://tailwindcss.com */\n"], dependencies: [{ kind: "directive", type: ContentEditorContentEditableDirective, selector: "[ngsContentEditorContentEditable]", inputs: ["ngsContentEditorContentEditable", "settings", "props"], outputs: ["contentChanged", "pressedEnter", "initialized", "propsChanged"], exportAs: ["ngsContentEditorContentEditable"] }, { kind: "directive", type: NgTemplateOutlet, selector: "[ngTemplateOutlet]", inputs: ["ngTemplateOutletContext", "ngTemplateOutlet", "ngTemplateOutletInjector"] }, { kind: "directive", type: ContentObserverDirective, selector: "[ngsContentObserver]", inputs: ["detectAddedNode"], outputs: ["nodeAdded"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: ListBlockComponent, decorators: [{
            type: Component,
            args: [{ selector: 'ngs-list-block', exportAs: 'ngsListBlock', imports: [
                        ContentEditorContentEditableDirective,
                        NgTemplateOutlet,
                        ContentObserverDirective
                    ], providers: [
                        {
                            provide: CONTENT_EDITOR_BLOCK,
                            useExisting: ListBlockComponent,
                            multi: true
                        }
                    ], changeDetection: ChangeDetectionStrategy.OnPush, host: {
                        '[class.list-bullet]': "_listStyle() === 'bullet'",
                        '[class.list-ordered]': "_listStyle() === 'ordered'",
                    }, template: "<ul class=\"list\"\n    ngsContentObserver\n    detectAddedNode=\"list-item\"\n    (nodeAdded)=\"_onNodeAdded($event)\">\n  <ng-container [ngTemplateOutlet]=\"listTpl\"\n                [ngTemplateOutletContext]=\"{ $implicit: _content(), level: 0, parentItem: null, parentList: [] }\"/>\n</ul>\n\n<ng-template #listTpl let-list let-level=\"level\" let-parentItem=\"parentItem\" let-parentList=\"parentList\">\n  @for (item of list; track $index; let index = $index) {\n    <li #listItem class=\"list-item\" [attr.id]=\"getId(level, index)\">\n      <div [ngsContentEditorContentEditable]=\"item.content\"\n           [props]=\"item.props\"\n           (propsChanged)=\"onPropsChanged($event, item)\"\n           #contentEditable=\"ngsContentEditorContentEditable\"\n           class=\"list-item-content\"\n           (contentChanged)=\"onContentChanged($event, list, index)\"\n           (pressedEnter)=\"onPressedEnter($event, contentEditable, list, index, level, parentItem, parentList)\"\n           (keydown)=\"_onKeyDown($event, contentEditable, list, index, level, parentItem, parentList, listItem)\"\n           [attr.data-empty-placeholder]=\"_placeholder()\"></div>\n      @if (item.children.length > 0) {\n        <ol class=\"list\"\n            ngsContentObserver\n            detectAddedNode=\"list-item\"\n            (nodeAdded)=\"_onNodeAdded($event)\">\n          <ng-container [ngTemplateOutlet]=\"listTpl\"\n                        [ngTemplateOutletContext]=\"{ $implicit: item.children, level: level + 1, parentItem: item, parentList: list }\"/>\n        </ol>\n      }\n    </li>\n  }\n</ng-template>\n", styles: [":host .list{display:flex;flex-direction:column;gap:calc(var(--spacing, .25rem) * 2);padding-inline-start:calc(var(--spacing, .25rem) * 4);--tw-outline-style: none;outline-style:none}:host .list .list{margin-top:calc(var(--spacing, .25rem) * 2);padding-inline-start:calc(var(--spacing, .25rem) * 4)}:host.list-ordered .list{list-style-type:decimal}:host.list-bullet .list{list-style-type:disc}:host .list-item-content{--tw-outline-style: none;outline-style:none}:host .list-item-content:empty:before{content:attr(data-empty-placeholder);color:var(--ngs-color-neutral-500)}\n/*! tailwindcss v4.2.2 | MIT License | https://tailwindcss.com */\n"] }]
        }], propDecorators: { id: [{ type: i0.Input, args: [{ isSignal: true, alias: "id", required: true }] }], content: [{ type: i0.Input, args: [{ isSignal: true, alias: "content", required: true }] }], settings: [{ type: i0.Input, args: [{ isSignal: true, alias: "settings", required: true }] }], index: [{ type: i0.Input, args: [{ isSignal: true, alias: "index", required: true }] }] } });

export { ListBlockComponent };
//# sourceMappingURL=ngstarter-ui-components-content-editor-list-block.component-guhW_EyK.mjs.map
