import * as i0 from '@angular/core';
import { inject, ElementRef, DestroyRef, output, afterNextRender, Directive, PLATFORM_ID, Input, Renderer2, NgZone, input, booleanAttribute, HostBinding, ChangeDetectionStrategy, Component, ChangeDetectorRef, viewChild, signal } from '@angular/core';
import { DOCUMENT, isPlatformServer, isPlatformBrowser } from '@angular/common';
import { a as CONTENT_BUILDER, C as ContentBuilderStore, 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 SelectionArea from '@viselect/vanilla';
import { Icon } from '@ngstarter-ui/components/icon';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { fromEvent, Subject } from 'rxjs';
import { CdkMonitorFocus } from '@angular/cdk/a11y';
import { takeUntil } from 'rxjs/operators';
import { moveItemInArray } from '@angular/cdk/drag-drop';

class TableColumnsManagerDirective {
    _elementRef = inject(ElementRef);
    _destroyRef = inject(DestroyRef);
    _document = inject(DOCUMENT);
    _dragging = false;
    _elementPosition = 0;
    _cellWidth = 90;
    columnAdded = output();
    columnDeleted = output();
    columnManagingStart = output();
    columnManagingEnd = output();
    constructor() {
        afterNextRender(() => {
            this._initResize();
        });
    }
    onContextMenu(event) {
        event.preventDefault();
        event.stopPropagation();
    }
    _initResize() {
        fromEvent(this._elementRef.nativeElement, 'mousedown')
            .pipe(takeUntilDestroyed(this._destroyRef))
            .subscribe((event) => {
            this._dragging = true;
            const elementRect = this._elementRef.nativeElement.getBoundingClientRect();
            this._elementPosition = elementRect.x + elementRect.width / 2;
            this.columnManagingStart.emit();
        });
        fromEvent(this._document, 'mousemove')
            .pipe(takeUntilDestroyed(this._destroyRef))
            .subscribe((event) => {
            if (this._dragging) {
                const elementRect = this._elementRef.nativeElement.getBoundingClientRect();
                const elementRightPosition = elementRect.x + elementRect.width;
                const elementLeftPosition = elementRect.x;
                if (event.clientX > (this._elementPosition + this._cellWidth) && event.clientX > (elementRightPosition + this._cellWidth)) {
                    this._elementPosition = elementRightPosition + this._cellWidth;
                    this.columnAdded.emit();
                }
                else if (event.clientX < (this._elementPosition - this._cellWidth) && event.clientX < (elementLeftPosition - this._cellWidth)) {
                    this._elementPosition = elementLeftPosition - this._cellWidth;
                    this.columnDeleted.emit();
                }
            }
        });
        fromEvent(this._document, 'mouseup')
            .pipe(takeUntilDestroyed(this._destroyRef))
            .subscribe((event) => {
            if (this._dragging) {
                this._dragging = false;
                this.columnManagingEnd.emit();
            }
        });
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: TableColumnsManagerDirective, deps: [], target: i0.ɵɵFactoryTarget.Directive });
    static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "21.2.4", type: TableColumnsManagerDirective, isStandalone: true, selector: "[ngsTableColumnsManager]", outputs: { columnAdded: "columnAdded", columnDeleted: "columnDeleted", columnManagingStart: "columnManagingStart", columnManagingEnd: "columnManagingEnd" }, host: { listeners: { "contextmenu": "onContextMenu($event)" } }, ngImport: i0 });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: TableColumnsManagerDirective, decorators: [{
            type: Directive,
            args: [{
                    selector: '[ngsTableColumnsManager]',
                    host: {
                        '(contextmenu)': 'onContextMenu($event)',
                    }
                }]
        }], ctorParameters: () => [], propDecorators: { columnAdded: [{ type: i0.Output, args: ["columnAdded"] }], columnDeleted: [{ type: i0.Output, args: ["columnDeleted"] }], columnManagingStart: [{ type: i0.Output, args: ["columnManagingStart"] }], columnManagingEnd: [{ type: i0.Output, args: ["columnManagingEnd"] }] } });

class TableRowsManagerDirective {
    _elementRef = inject(ElementRef);
    _destroyRef = inject(DestroyRef);
    _document = inject(DOCUMENT);
    _dragging = false;
    _elementPosition = 0;
    _cellHeight = 24;
    rowManagingStart = output();
    rowManagingEnd = output();
    rowAdded = output();
    rowDeleted = output();
    constructor() {
        afterNextRender(() => {
            this._initResize();
        });
    }
    onContextMenu(event) {
        event.preventDefault();
        event.stopPropagation();
    }
    _initResize() {
        fromEvent(this._elementRef.nativeElement, 'mousedown')
            .pipe(takeUntilDestroyed(this._destroyRef))
            .subscribe((event) => {
            this._dragging = true;
            const elementRect = this._elementRef.nativeElement.getBoundingClientRect();
            this._elementPosition = elementRect.y + elementRect.height / 2;
            this.rowManagingStart.emit();
        });
        fromEvent(this._document, 'mousemove')
            .pipe(takeUntilDestroyed(this._destroyRef))
            .subscribe((event) => {
            if (this._dragging) {
                const elementRect = this._elementRef.nativeElement.getBoundingClientRect();
                const elementBottomPosition = elementRect.y + elementRect.height;
                const elementTopPosition = elementRect.y;
                if (event.clientY > (this._elementPosition + this._cellHeight) && event.clientY > (elementBottomPosition + this._cellHeight)) {
                    this._elementPosition = elementBottomPosition + this._cellHeight;
                    this.rowAdded.emit();
                }
                else if (event.clientY < (this._elementPosition - this._cellHeight) && event.clientY < (elementTopPosition - this._cellHeight)) {
                    this._elementPosition = elementTopPosition - this._cellHeight;
                    this.rowDeleted.emit();
                }
            }
        });
        fromEvent(this._document, 'mouseup')
            .pipe(takeUntilDestroyed(this._destroyRef))
            .subscribe((event) => {
            if (this._dragging) {
                this._dragging = false;
                this.rowManagingEnd.emit();
            }
        });
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: TableRowsManagerDirective, deps: [], target: i0.ɵɵFactoryTarget.Directive });
    static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "21.2.4", type: TableRowsManagerDirective, isStandalone: true, selector: "[ngsTableRowsManager]", outputs: { rowManagingStart: "rowManagingStart", rowManagingEnd: "rowManagingEnd", rowAdded: "rowAdded", rowDeleted: "rowDeleted" }, host: { listeners: { "contextmenu": "onContextMenu($event)" } }, ngImport: i0 });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: TableRowsManagerDirective, decorators: [{
            type: Directive,
            args: [{
                    selector: '[ngsTableRowsManager]',
                    host: {
                        '(contextmenu)': 'onContextMenu($event)',
                    }
                }]
        }], ctorParameters: () => [], propDecorators: { rowManagingStart: [{ type: i0.Output, args: ["rowManagingStart"] }], rowManagingEnd: [{ type: i0.Output, args: ["rowManagingEnd"] }], rowAdded: [{ type: i0.Output, args: ["rowAdded"] }], rowDeleted: [{ type: i0.Output, args: ["rowDeleted"] }] } });

const RESIZING_TABLE_CLASS = 'table-resizing';
const RESIZE_HANDLE_ACTIVE_CLASS = 'resize-handle--active';
class ResizableTableDirective {
    el;
    renderer;
    ngZone;
    _platformId = inject(PLATFORM_ID);
    minColumnWidth = 120;
    resizeHandleWidth = 5;
    mutationObserverDebounceTime = 20;
    columnWidthChange = output();
    columnWidthChangeStart = output();
    columnWidthChangeEnd = output();
    table;
    wrapper = null;
    resizeHandle = null;
    colgroup = null;
    colElements = [];
    isResizing = false;
    resizingColumnIndex = -1;
    resizingColElement = null;
    startX = 0;
    startWidth = 0;
    startEdgeXRelative = 0;
    activeHoverColumnIndex = -1;
    isHandleVisible = false;
    destroy$ = new Subject();
    hideHandleDebounced;
    syncColumnsDebounced; // Debounce для синхронизации колонок
    listeners = [];
    observer = null;
    constructor(el, renderer, ngZone) {
        this.el = el;
        this.renderer = renderer;
        this.ngZone = ngZone;
        this.table = this.el.nativeElement;
        this.hideHandleDebounced = this.debounce(() => this.hideResizeHandle(), 50);
        this.syncColumnsDebounced = this.debounce(() => {
            this.syncColumnsAndColgroup();
            this.ensureColWidths();
            if (this.isHandleVisible) {
                this.hideResizeHandle();
            }
        }, this.mutationObserverDebounceTime);
    }
    ngOnInit() {
    }
    ngAfterViewInit() {
        if (isPlatformServer(this._platformId)) {
            return;
        }
        this.checkTableLayout();
        this.createWrapperAndHandle();
        this.syncColumnsAndColgroup();
        if (!this.wrapper || !this.resizeHandle) {
            console.error('ResizableTableDirective: Wrapper or handle creation failed.');
            this.cleanupWrapperAndHandleOnError();
            return;
        }
        this.addWrapperListeners();
        this.setupGlobalResizeListeners();
        this.setupMutationObserver();
        this.ensureColWidths();
    }
    ngOnDestroy() {
        this.observer?.disconnect();
        this.destroy$.next();
        this.destroy$.complete();
        this.listeners.forEach(unlisten => unlisten());
        this.cleanupWrapperAndHandle();
    }
    checkTableLayout() {
        if (getComputedStyle(this.table).tableLayout !== 'fixed') {
            console.warn('ResizableTableDirective: table-layout: fixed is highly recommended.');
            this.renderer.setStyle(this.table, 'table-layout', 'fixed');
        }
    }
    syncColumnsAndColgroup() {
        let requiredColumnCount = 0;
        const firstDataRow = this.table.querySelector('tbody > tr:first-child');
        if (firstDataRow) {
            requiredColumnCount = firstDataRow.cells.length;
        }
        else {
            // Если tbody пуст, можно попробовать определить по thead, если он есть
            const firstHeadRow = this.table.querySelector('thead > tr:first-child');
            if (firstHeadRow) {
                requiredColumnCount = firstHeadRow.cells.length;
            }
            else {
                if (this.colgroup) {
                    this.colElements.forEach(col => this.renderer.removeChild(this.colgroup, col));
                }
                this.colElements = [];
                return;
            }
        }
        this.colgroup = this.table.querySelector('colgroup');
        const currentColElements = Array.from(this.colgroup.querySelectorAll('col'));
        const currentColCount = currentColElements.length;
        if (requiredColumnCount > currentColCount) {
            for (let i = currentColCount; i < requiredColumnCount; i++) {
                const col = this.renderer.createElement('col');
                this.renderer.appendChild(this.colgroup, col);
            }
        }
        else if (requiredColumnCount < currentColCount) {
            for (let i = currentColCount - 1; i >= requiredColumnCount; i--) {
                this.renderer.removeChild(this.colgroup, currentColElements[i]);
            }
        }
        this.colElements = Array.from(this.colgroup.querySelectorAll('col'));
    }
    ensureColWidths() {
        const referenceRow = this.table.querySelector('tbody > tr:first-child, thead > tr:first-child');
        if (!referenceRow || this.colElements.length !== referenceRow.cells.length) {
            return;
        }
        this.colElements.forEach((col, index) => {
            if (!col.style.width && referenceRow.cells[index]) {
                const cellWidth = referenceRow.cells[index].getBoundingClientRect().width;
                if (cellWidth > 0) {
                    this.renderer.setStyle(col, 'width', `${cellWidth}px`);
                }
            }
        });
    }
    setupMutationObserver() {
        const targetNode = this.table.querySelector('tbody') ?? this.table;
        const config = {
            childList: true,
            subtree: true
        };
        const callback = (mutationsList, observer) => {
            this.ngZone.runOutsideAngular(() => {
                this.syncColumnsDebounced();
            });
        };
        this.observer = new MutationObserver(callback);
        this.observer.observe(targetNode, config);
    }
    createWrapperAndHandle() {
        this.wrapper = this.renderer.createElement('div');
        this.renderer.addClass(this.wrapper, 'resizable-table-wrapper');
        this.resizeHandle = this.renderer.createElement('div');
        this.renderer.addClass(this.resizeHandle, 'resizable-table-handle');
        this.renderer.setStyle(this.resizeHandle, 'width', `${this.resizeHandleWidth}px`);
        const parent = this.renderer.parentNode(this.table);
        if (parent) {
            this.renderer.insertBefore(parent, this.wrapper, this.table);
            this.renderer.appendChild(this.wrapper, this.table);
            this.renderer.appendChild(this.wrapper, this.resizeHandle);
        }
        else {
            console.error('ResizableTableDirective: Table has no parent node.');
            this.wrapper = null;
            this.resizeHandle = null;
        }
    }
    cleanupWrapperAndHandle() {
        if (this.wrapper && this.wrapper.parentNode) {
            if (this.table.parentNode === this.wrapper) {
                this.renderer.insertBefore(this.wrapper.parentNode, this.table, this.wrapper);
            }
            this.renderer.removeChild(this.wrapper.parentNode, this.wrapper);
        }
        else if (this.resizeHandle && this.resizeHandle.parentNode) {
            this.renderer.removeChild(this.resizeHandle.parentNode, this.resizeHandle);
        }
        this.wrapper = null;
        this.resizeHandle = null;
    }
    cleanupWrapperAndHandleOnError() {
        if (this.wrapper && this.table.parentNode === this.wrapper) {
            const parent = this.wrapper.parentNode;
            if (parent) {
                this.renderer.insertBefore(parent, this.table, this.wrapper);
                this.renderer.removeChild(parent, this.wrapper);
            }
        }
        this.wrapper = null;
        this.resizeHandle = null;
    }
    addWrapperListeners() {
        if (!this.wrapper)
            return;
        this.ngZone.runOutsideAngular(() => {
            const mm = this.renderer.listen(this.wrapper, 'mousemove', (e) => this.handleMouseMoveWrapper(e));
            this.listeners.push(mm);
        });
        const md = this.renderer.listen(this.wrapper, 'mousedown', (e) => this.handleMouseDownWrapper(e));
        const ml = this.renderer.listen(this.wrapper, 'mouseleave', (e) => { if (!this.isResizing)
            this.hideResizeHandle(); });
        this.listeners.push(md, ml);
    }
    handleMouseMoveWrapper(event) {
        if (this.isResizing || !this.wrapper) {
            return;
        }
        const wrapperRect = this.wrapper.getBoundingClientRect();
        const mouseXRelative = event.clientX - wrapperRect.left;
        let targetColumnIndex = -1;
        let edgeXPosition = 0;
        const firstRow = this.table.querySelector('tbody > tr:first-child, thead > tr:first-child');
        if (!firstRow) {
            return;
        }
        if (this.colElements.length !== firstRow.cells.length) {
            return;
        }
        for (let i = 0; i < firstRow.cells.length; i++) {
            const cell = firstRow.cells[i];
            if (!cell) {
                continue;
            }
            const cellRect = cell.getBoundingClientRect();
            const cellEdgeX = cellRect.right - wrapperRect.left;
            if (Math.abs(mouseXRelative - cellEdgeX) <= this.resizeHandleWidth / 2) {
                if (this.colElements[i]) {
                    targetColumnIndex = i;
                    edgeXPosition = cellEdgeX;
                    break;
                }
            }
        }
        if (targetColumnIndex !== -1) {
            this.showResizeHandle(edgeXPosition);
            this.activeHoverColumnIndex = targetColumnIndex;
        }
        else {
            this.hideHandleDebounced();
        }
    }
    handleMouseDownWrapper(event) {
        if (this.activeHoverColumnIndex !== -1 && this.isHandleVisible && this.wrapper) {
            const targetCol = this.colElements[this.activeHoverColumnIndex];
            const firstRow = this.table.querySelector('tbody > tr:first-child, thead > tr:first-child');
            if (!targetCol || !firstRow || !firstRow.cells[this.activeHoverColumnIndex]) {
                return;
            }
            this.isResizing = true;
            this.resizingColumnIndex = this.activeHoverColumnIndex;
            this.resizingColElement = targetCol;
            this.startX = event.clientX;
            const colStyleWidth = this.resizingColElement.style.width;
            this.startWidth = colStyleWidth && colStyleWidth.endsWith('px')
                ? parseFloat(colStyleWidth)
                : this.resizingColElement.getBoundingClientRect().width;
            if (this.startWidth <= 0) {
                this.startWidth = firstRow.cells[this.resizingColumnIndex].getBoundingClientRect().width;
            }
            const wrapperRect = this.wrapper.getBoundingClientRect();
            const cellRect = firstRow.cells[this.resizingColumnIndex].getBoundingClientRect();
            this.startEdgeXRelative = cellRect.right - wrapperRect.left;
            this.renderer.addClass(this.table, RESIZING_TABLE_CLASS);
            event.preventDefault();
            this.columnWidthChangeStart.emit();
        }
    }
    showResizeHandle(edgeX) {
        if (!this.resizeHandle || !this.wrapper) {
            return;
        }
        const handleLeft = edgeX - (this.resizeHandleWidth / 2);
        this.renderer.setStyle(this.resizeHandle, 'left', `${handleLeft}px`);
        this.renderer.setStyle(this.resizeHandle, 'top', `${this.table.offsetTop}px`);
        this.renderer.setStyle(this.resizeHandle, 'height', `${this.table.offsetHeight}px`);
        this.renderer.addClass(this.resizeHandle, RESIZE_HANDLE_ACTIVE_CLASS);
        this.isHandleVisible = true;
    }
    hideResizeHandle() {
        if (this.resizeHandle && this.isHandleVisible) {
            this.renderer.removeClass(this.resizeHandle, RESIZE_HANDLE_ACTIVE_CLASS);
            this.isHandleVisible = false;
            this.activeHoverColumnIndex = -1;
        }
    }
    debounce(func, wait) {
        let timeout;
        return (...args) => {
            clearTimeout(timeout);
            timeout = setTimeout(() => func.apply(this, args), wait);
        };
    }
    setupGlobalResizeListeners() {
        this.ngZone.runOutsideAngular(() => {
            fromEvent(document, 'mousemove')
                .pipe(takeUntil(this.destroy$))
                .subscribe(event => {
                if (!this.isResizing || !this.resizingColElement || !this.wrapper || !this.resizeHandle)
                    return;
                if (!this.resizingColElement.parentElement) {
                    this.stopResizing();
                    return;
                }
                const deltaX = event.clientX - this.startX;
                const newWidth = this.startWidth + deltaX;
                const finalWidth = Math.max(newWidth, this.minColumnWidth);
                this.renderer.setStyle(this.resizingColElement, 'width', `${finalWidth}px`);
                const actualDeltaX = finalWidth - this.startWidth;
                const newEdgeXRelative = this.startEdgeXRelative + actualDeltaX;
                const handleLeft = newEdgeXRelative - (this.resizeHandleWidth / 2);
                this.renderer.setStyle(this.resizeHandle, 'left', `${handleLeft}px`);
                if (!this.isHandleVisible) {
                    this.renderer.addClass(this.resizeHandle, RESIZE_HANDLE_ACTIVE_CLASS);
                    this.isHandleVisible = true;
                }
                this.updateHandleHeight();
            });
            fromEvent(document, 'mouseup')
                .pipe(takeUntil(this.destroy$))
                .subscribe(() => {
                if (this.isResizing) {
                    this.ngZone.run(() => {
                        this.stopResizing();
                    });
                }
            });
        });
    }
    stopResizing() {
        this.columnWidthChange.emit({
            columnIndex: this.resizingColumnIndex,
            width: this.resizingColElement?.getBoundingClientRect().width
        });
        this.renderer.removeClass(this.table, RESIZING_TABLE_CLASS);
        this.hideResizeHandle();
        this.isResizing = false;
        this.resizingColumnIndex = -1;
        this.resizingColElement = null;
        this.columnWidthChangeEnd.emit();
    }
    updateHandleHeight() {
        if (this.resizeHandle && this.isHandleVisible && this.wrapper) {
            requestAnimationFrame(() => {
                if (this.isHandleVisible && this.resizeHandle && this.table) {
                    this.renderer.setStyle(this.resizeHandle, 'top', `${this.table.offsetTop}px`);
                    this.renderer.setStyle(this.resizeHandle, 'height', `${this.table.offsetHeight}px`);
                }
            });
        }
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: ResizableTableDirective, deps: [{ token: i0.ElementRef }, { token: i0.Renderer2 }, { token: i0.NgZone }], target: i0.ɵɵFactoryTarget.Directive });
    static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "21.2.4", type: ResizableTableDirective, isStandalone: true, selector: "table[ngsResizableTable]", inputs: { minColumnWidth: "minColumnWidth", resizeHandleWidth: "resizeHandleWidth", mutationObserverDebounceTime: "mutationObserverDebounceTime" }, outputs: { columnWidthChange: "columnWidthChange", columnWidthChangeStart: "columnWidthChangeStart", columnWidthChangeEnd: "columnWidthChangeEnd" }, ngImport: i0 });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: ResizableTableDirective, decorators: [{
            type: Directive,
            args: [{
                    selector: 'table[ngsResizableTable]'
                }]
        }], ctorParameters: () => [{ type: i0.ElementRef }, { type: i0.Renderer2 }, { type: i0.NgZone }], propDecorators: { minColumnWidth: [{
                type: Input
            }], resizeHandleWidth: [{
                type: Input
            }], mutationObserverDebounceTime: [{
                type: Input
            }], columnWidthChange: [{ type: i0.Output, args: ["columnWidthChange"] }], columnWidthChangeStart: [{ type: i0.Output, args: ["columnWidthChangeStart"] }], columnWidthChangeEnd: [{ type: i0.Output, args: ["columnWidthChangeEnd"] }] } });

const HIDE_DELAY_MS = 300;
class DraggableTableComponent {
    contentBuilder = inject(CONTENT_BUILDER);
    _platformId = inject(PLATFORM_ID);
    elRef = inject((ElementRef));
    renderer = inject(Renderer2);
    ngZone = inject(NgZone);
    destroyRef = inject(DestroyRef);
    table = null;
    suppressInteractions = false;
    columnHandler;
    rowHandler;
    dropIndicator;
    hoveredCell = null;
    hoveredColumnIndex = -1;
    hoveredRowIndex = -1;
    isDragging = false;
    dragMode = null;
    startX = 0;
    startY = 0;
    handlerStartY = 0;
    draggedElement = null;
    draggedElementSource = null;
    startElementIndex = -1;
    currentDropIndex = -1;
    hideTimeoutId = null;
    columnInfo = [];
    rowInfo = [];
    listeners = [];
    boundOnDrag;
    boundEndDrag;
    handlerSize = 18;
    handlerOffset = -9;
    indicatorThickness = 3;
    suppressResetTimeoutId = null;
    scrollContainerRef = null; // оставлено для обратной совместимости, не используется напрямую
    scrollSub = null;
    hostClass = true;
    disabled = input(false, { ...(ngDevMode ? { debugName: "disabled" } : /* istanbul ignore next */ {}), transform: booleanAttribute });
    columnMoved = output();
    rowMoved = output();
    moveStart = output();
    moveEnd = output();
    constructor() {
        this.boundOnDrag = this.onDrag.bind(this);
        this.boundEndDrag = this.endDrag.bind(this);
    }
    ngOnInit() {
        if (isPlatformServer(this._platformId)) {
            return;
        }
        this.createHandlers();
        this.createDropIndicator();
        this.prepareListeners();
    }
    ngAfterViewInit() {
        if (isPlatformServer(this._platformId)) {
            return;
        }
        this.table = this.elRef.nativeElement.querySelector('table');
        if (!this.table) {
            return;
        }
        if (getComputedStyle(this.table).position === 'static') {
            this.renderer.setStyle(this.table, 'position', 'relative');
        }
        this.renderer.appendChild(this.table, this.columnHandler);
        this.renderer.appendChild(this.table, this.rowHandler);
        this.renderer.appendChild(this.table, this.dropIndicator);
        this.attachListeners('element');
        this.bindScrollContainerListener();
    }
    ngOnDestroy() {
        if (isPlatformServer(this._platformId)) {
            return;
        }
        this.unbindScrollContainerListener();
        this.detachListeners('all');
        this.cancelHideTimer();
        if (this.suppressResetTimeoutId) {
            clearTimeout(this.suppressResetTimeoutId);
            this.suppressResetTimeoutId = null;
        }
        if (this.dropIndicator?.parentNode) {
            this.renderer.removeChild(this.dropIndicator.parentNode, this.dropIndicator);
        }
        if (this.columnHandler?.parentNode) {
            this.renderer.removeChild(this.columnHandler.parentNode, this.columnHandler);
        }
        if (this.rowHandler?.parentNode) {
            this.renderer.removeChild(this.rowHandler.parentNode, this.rowHandler);
        }
        if (this.table) {
            this.renderer.removeClass(this.table, 'dragging-column');
            this.renderer.removeClass(this.table, 'dragging-row');
            this.table.querySelectorAll('.dragging-source').forEach(el => this.renderer.removeClass(el, 'dragging-source'));
            this.table.querySelectorAll('.col-highlight').forEach(el => this.renderer.removeClass(el, 'col-highlight'));
        }
        document.body.style.cursor = '';
        this.columnInfo = [];
        this.rowInfo = [];
        this.currentDropIndex = -1;
        this.suppressInteractions = false;
    }
    prepareListeners() {
        this.listeners = [
            {
                name: 'tableMouseOver',
                type: 'element',
                target: () => this.table,
                event: 'mouseover',
                handler: this.onTableMouseOver.bind(this)
            },
            {
                name: 'tableMouseLeave',
                type: 'element',
                target: () => this.table,
                event: 'mouseleave',
                handler: this.onTableMouseLeave.bind(this)
            },
            {
                name: 'colHandlerMouseDown',
                type: 'element',
                target: () => this.columnHandler,
                event: 'mousedown',
                handler: (e) => this.onHandlerMouseDown(e, 'column')
            },
            {
                name: 'colHandlerMouseEnter',
                type: 'element',
                target: () => this.columnHandler,
                event: 'mouseenter',
                handler: this.onHandlerMouseEnter.bind(this)
            },
            {
                name: 'colHandlerMouseLeave',
                type: 'element',
                target: () => this.columnHandler,
                event: 'mouseleave',
                handler: this.onHandlerMouseLeave.bind(this)
            },
            {
                name: 'rowHandlerMouseDown',
                type: 'element',
                target: () => this.rowHandler,
                event: 'mousedown',
                handler: (e) => this.onHandlerMouseDown(e, 'row')
            },
            {
                name: 'rowHandlerMouseEnter',
                type: 'element',
                target: () => this.rowHandler,
                event: 'mouseenter',
                handler: this.onHandlerMouseEnter.bind(this)
            },
            {
                name: 'rowHandlerMouseLeave',
                type: 'element',
                target: () => this.rowHandler,
                event: 'mouseleave',
                handler: this.onHandlerMouseLeave.bind(this)
            },
            { name: 'docMouseMove', type: 'document', target: () => document, event: 'mousemove', handler: this.boundOnDrag },
            {
                name: 'docMouseUp', type: 'document', target: () => document, event: 'mouseup', handler: (e) => {
                    this.suppressInteractions = false;
                    this.boundEndDrag(e);
                }
            },
            {
                name: 'winBlur', type: 'document', target: () => window, event: 'blur', handler: () => {
                    this.suppressInteractions = false;
                }
            },
            {
                name: 'visibilityChange', type: 'document', target: () => document, event: 'visibilitychange', handler: () => {
                    if (document.visibilityState !== 'visible') {
                        this.suppressInteractions = false;
                    }
                }
            },
        ];
    }
    attachListeners(type = 'element') {
        this.ngZone.runOutsideAngular(() => {
            this.listeners.forEach(listener => {
                if (listener.type === 'document' && type !== 'document' && type !== 'all')
                    return;
                if (listener.type === 'element' && type === 'document')
                    return;
                if (listener.cleanup || !listener.target)
                    return;
                const targetElement = listener.target();
                if (!targetElement)
                    return;
                listener.cleanup = this.renderer.listen(targetElement, listener.event, listener.handler);
            });
        });
    }
    detachListeners(type = 'all') {
        this.listeners.forEach(listener => {
            if (listener.type === 'document' && type !== 'document' && type !== 'all')
                return;
            if (listener.type === 'element' && type === 'document')
                return;
            if (listener.cleanup) {
                listener.cleanup();
                listener.cleanup = undefined;
            }
        });
    }
    onTableMouseOver(event) {
        this.cancelHideTimer();
        this.ensureScrollContainerListener();
        if (!this.table || this.isDragging)
            return;
        if (this.suppressInteractions)
            return;
        const anyButtonDown = typeof event.buttons === 'number' ? event.buttons !== 0 : false;
        if (anyButtonDown)
            return;
        const target = event.target;
        const cell = target.closest('td, th');
        if (cell && this.table.contains(cell)) {
            const currentColumnIndex = cell.cellIndex;
            const currentRow = cell.closest('tr');
            const currentRowIndex = currentRow?.parentElement?.tagName === 'TBODY' ? Array.from(currentRow.parentElement.children).indexOf(currentRow) : -1;
            this.hoveredCell = cell;
            if (currentColumnIndex !== this.hoveredColumnIndex || this.columnHandler.style.visibility === 'hidden') {
                this.hoveredColumnIndex = currentColumnIndex;
                this.positionColumnHandler(cell);
                this.renderer.setStyle(this.columnHandler, 'visibility', 'visible');
            }
            if (currentRowIndex !== -1) {
                if (currentRowIndex !== this.hoveredRowIndex || this.rowHandler.style.visibility === 'hidden') {
                    this.hoveredRowIndex = currentRowIndex;
                    this.positionRowHandler(cell);
                    this.renderer.setStyle(this.rowHandler, 'visibility', 'visible');
                }
            }
            else if (this.hoveredRowIndex !== -1) {
                this.renderer.setStyle(this.rowHandler, 'visibility', 'hidden');
                this.hoveredRowIndex = -1;
            }
        }
    }
    onTableMouseLeave(event) {
        if (this.isDragging)
            return;
        if (this.suppressInteractions)
            return;
        const relatedTarget = event.relatedTarget;
        if (relatedTarget !== this.columnHandler && relatedTarget !== this.rowHandler) {
            this.scheduleHideHandlers();
        }
    }
    onHandlerMouseEnter() {
        this.cancelHideTimer();
    }
    onHandlerMouseLeave(event) {
        if (this.isDragging)
            return;
        if (this.suppressInteractions)
            return;
        const relatedTarget = event.relatedTarget;
        const isOverTable = relatedTarget && this.table && this.table.contains(relatedTarget);
        const isOverOtherHandler = (event.target === this.columnHandler && relatedTarget === this.rowHandler) || (event.target === this.rowHandler && relatedTarget === this.columnHandler);
        if (!isOverTable && !isOverOtherHandler) {
            this.scheduleHideHandlers();
        }
    }
    onHandlerMouseDown(event, mode) {
        const isPrimary = (event.button === 0) && ((event.buttons & 1) === 1);
        if (!isPrimary || event.ctrlKey) {
            this.suppressInteractions = true;
            event.preventDefault();
            event.stopPropagation();
            this.cancelHideTimer();
            if (this.suppressResetTimeoutId) {
                clearTimeout(this.suppressResetTimeoutId);
                this.suppressResetTimeoutId = null;
            }
            this.suppressResetTimeoutId = setTimeout(() => {
                this.suppressInteractions = false;
                this.suppressResetTimeoutId = null;
            }, 1200);
            return;
        }
        this.startDrag(event, mode);
    }
    createHandlers() {
        this.columnHandler = this.renderer.createElement('div');
        this.columnHandler.oncontextmenu = ((e) => {
            e.preventDefault();
            e.stopPropagation();
        });
        this.renderer.addClass(this.columnHandler, 'drag-handler');
        this.renderer.addClass(this.columnHandler, 'column-handler');
        this.renderer.setStyle(this.columnHandler, 'position', 'fixed');
        this.renderer.setStyle(this.columnHandler, 'visibility', 'hidden');
        this.renderer.setStyle(this.columnHandler, 'z-index', '1000');
        this.rowHandler = this.renderer.createElement('div');
        this.rowHandler.oncontextmenu = ((e) => {
            e.preventDefault();
            e.stopPropagation();
        });
        this.renderer.addClass(this.rowHandler, 'drag-handler');
        this.renderer.addClass(this.rowHandler, 'row-handler');
        this.renderer.setStyle(this.rowHandler, 'position', 'fixed');
        this.renderer.setStyle(this.rowHandler, 'visibility', 'hidden');
        this.renderer.setStyle(this.rowHandler, 'z-index', '1000');
    }
    createDropIndicator() {
        this.dropIndicator = this.renderer.createElement('div');
        this.renderer.addClass(this.dropIndicator, 'drop-indicator');
    }
    positionColumnHandler(cellOrIndex) {
        if (!this.table) {
            return;
        }
        let targetCell = null;
        if (typeof cellOrIndex === 'number') {
            targetCell = this.findFirstVisibleCellInColumn(cellOrIndex);
            if (!targetCell)
                return;
        }
        else {
            targetCell = cellOrIndex;
        }
        const tableRect = this.table.getBoundingClientRect();
        const cellRect = targetCell.getBoundingClientRect();
        const colHandlerLeft = cellRect.left + (cellRect.width / 2) - (this.handlerSize / 2);
        const colHandlerTop = tableRect.top - this.handlerSize - this.handlerOffset;
        this.renderer.setStyle(this.columnHandler, 'top', `${colHandlerTop}px`);
        this.renderer.setStyle(this.columnHandler, 'left', `${colHandlerLeft}px`);
    }
    positionRowHandler(cell) {
        if (!this.table || this.isDragging)
            return;
        const tableRect = this.table.getBoundingClientRect();
        const cellRect = cell.getBoundingClientRect();
        const rowHandlerTop = cellRect.top + (cellRect.height / 2) - (this.handlerSize / 2);
        const rowHandlerLeft = tableRect.left - this.handlerSize - this.handlerOffset;
        this.renderer.setStyle(this.rowHandler, 'top', `${rowHandlerTop}px`);
        this.renderer.setStyle(this.rowHandler, 'left', `${rowHandlerLeft}px`);
    }
    scheduleHideHandlers() {
        this.cancelHideTimer();
        this.hideTimeoutId = setTimeout(() => {
            this.hideHandlers();
            this.hideTimeoutId = null;
        }, HIDE_DELAY_MS);
    }
    cancelHideTimer() {
        if (this.hideTimeoutId) {
            clearTimeout(this.hideTimeoutId);
            this.hideTimeoutId = null;
        }
    }
    hideHandlers() {
        if (!this.isDragging) {
            this.renderer.setStyle(this.columnHandler, 'visibility', 'hidden');
            this.renderer.setStyle(this.rowHandler, 'visibility', 'hidden');
            this.renderer.setStyle(this.dropIndicator, 'visibility', 'hidden');
            this.hoveredCell = null;
            this.hoveredColumnIndex = -1;
            this.hoveredRowIndex = -1;
        }
    }
    startDrag(event, mode) {
        const isPrimary = (event.button === 0) && ((event.buttons & 1) === 1);
        if (!isPrimary || event.ctrlKey) {
            return;
        }
        this.cancelHideTimer();
        const sourceRow = mode === 'row' ? this.hoveredCell?.closest('tr') : null;
        if (!this.table || (mode === 'row' && this.hoveredRowIndex < 0) ||
            (mode === 'column' && this.hoveredColumnIndex < 0) ||
            (mode === 'row' && sourceRow?.parentElement?.tagName !== 'TBODY')) {
            return;
        }
        event.preventDefault();
        this.isDragging = true;
        this.dragMode = mode;
        this.startX = event.clientX;
        this.startY = event.clientY;
        this.currentDropIndex = -1;
        if (mode === 'column') {
            this.startElementIndex = this.hoveredColumnIndex;
            this.currentDropIndex = this.startElementIndex;
            this.draggedElement = this.columnHandler;
            this.draggedElementSource = null;
            this.renderer.addClass(this.table, 'dragging-column');
            this.styleColumnAsSource(this.startElementIndex, true);
            this.calculateColumnInfo();
            this.updateColumnHandlerPositionOnDrag(event.clientX);
            this.renderer.setStyle(this.columnHandler, 'visibility', 'visible');
            this.renderer.setStyle(this.rowHandler, 'visibility', 'hidden');
            this.renderer.setStyle(this.dropIndicator, 'visibility', 'hidden');
        }
        else {
            this.startElementIndex = this.hoveredRowIndex;
            this.currentDropIndex = this.startElementIndex;
            this.draggedElement = this.rowHandler;
            this.draggedElementSource = sourceRow;
            this.renderer.addClass(this.draggedElementSource, 'dragging-source');
            this.renderer.addClass(this.table, 'dragging-row');
            this.calculateRowInfo();
            this.handlerStartY = parseFloat(this.rowHandler.style.top || '0');
            this.updateRowHandlerPositionOnDrag(event.clientY);
            this.renderer.setStyle(this.rowHandler, 'visibility', 'visible');
            this.renderer.setStyle(this.columnHandler, 'visibility', 'hidden');
            this.renderer.setStyle(this.dropIndicator, 'visibility', 'hidden');
        }
        if (this.draggedElement) {
            this.renderer.addClass(this.draggedElement, 'dragging-active-handler');
        }
        this.attachListeners('document');
    }
    onDrag(event) {
        if (!this.isDragging || !this.draggedElement || !this.table)
            return;
        if ((event.buttons & 1) !== 1) {
            this.endDrag(event);
            return;
        }
        event.preventDefault();
        this.moveStart.emit();
        const currentX = event.clientX;
        const currentY = event.clientY;
        document.body.style.cursor = 'grabbing';
        if (this.dragMode === 'row') {
            this.updateRowHandlerPositionOnDrag(currentY);
            const currentHandlerCenterY = parseFloat(this.rowHandler.style.top || '0') + this.handlerSize / 2;
            const newVisualTargetIndex = this.getVisualTargetRowIndex(currentHandlerCenterY);
            if (newVisualTargetIndex !== -1) {
                this.updateDropIndicator(newVisualTargetIndex, 'row');
                this.currentDropIndex = newVisualTargetIndex;
            }
            else {
                this.renderer.setStyle(this.dropIndicator, 'visibility', 'hidden');
                this.currentDropIndex = -1;
            }
            this.clearDropHighlights();
        }
        else if (this.dragMode === 'column') {
            this.updateColumnHandlerPositionOnDrag(currentX);
            const currentHandlerCenterX = parseFloat(this.columnHandler.style.left || '0') + this.handlerSize / 2;
            const newVisualTargetIndex = this.getVisualTargetColumnIndex(currentHandlerCenterX);
            if (newVisualTargetIndex !== -1) {
                this.updateDropIndicator(newVisualTargetIndex, 'column');
                this.currentDropIndex = newVisualTargetIndex;
            }
            else {
                this.renderer.setStyle(this.dropIndicator, 'visibility', 'hidden');
                this.currentDropIndex = -1;
            }
            this.clearDropHighlights();
        }
    }
    getVisualTargetColumnIndex(currentHandlerCenterX) {
        if (this.startElementIndex < 0 || !this.columnInfo?.length)
            return -1;
        let potentialTargetIndex = this.startElementIndex;
        const currentGeometry = this.columnInfo;
        for (const targetColumn of currentGeometry) {
            if (targetColumn.index === this.startElementIndex)
                continue;
            const targetCenter = targetColumn.center;
            const threshold = targetColumn.width * 0.5;
            if (targetColumn.index > this.startElementIndex && currentHandlerCenterX > targetCenter - threshold) {
                potentialTargetIndex = Math.max(potentialTargetIndex, targetColumn.index);
            }
            else if (targetColumn.index < this.startElementIndex && currentHandlerCenterX < targetCenter + threshold) {
                potentialTargetIndex = (potentialTargetIndex === this.startElementIndex) ? targetColumn.index : Math.min(potentialTargetIndex, targetColumn.index);
            }
        }
        return potentialTargetIndex;
    }
    getVisualTargetRowIndex(currentHandlerCenterY) {
        if (this.startElementIndex < 0 || !this.table?.tBodies[0] || !this.rowInfo?.length)
            return -1;
        let potentialTargetIndex = this.startElementIndex;
        const currentGeometry = this.rowInfo;
        for (const targetRow of currentGeometry) {
            if (targetRow.index === this.startElementIndex)
                continue;
            const targetCenter = targetRow.center;
            const threshold = targetRow.height * 0.5;
            if (targetRow.index > this.startElementIndex && currentHandlerCenterY > targetCenter - threshold) {
                potentialTargetIndex = Math.max(potentialTargetIndex, targetRow.index);
            }
            else if (targetRow.index < this.startElementIndex && currentHandlerCenterY < targetCenter + threshold) {
                potentialTargetIndex = (potentialTargetIndex === this.startElementIndex) ? targetRow.index : Math.min(potentialTargetIndex, targetRow.index);
            }
        }
        return potentialTargetIndex;
    }
    updateColumnHandlerPositionOnDrag(currentX) {
        if (!this.table || !this.columnHandler)
            return;
        const handlerLeft = currentX - (this.handlerSize / 2);
        this.renderer.setStyle(this.columnHandler, 'left', `${handlerLeft}px`);
    }
    updateRowHandlerPositionOnDrag(currentY) {
        if (!this.table || !this.rowHandler)
            return;
        const deltaY = currentY - this.startY;
        const handlerTop = this.handlerStartY + deltaY;
        this.renderer.setStyle(this.rowHandler, 'top', `${handlerTop}px`);
    }
    endDrag(event) {
        if (!this.isDragging)
            return;
        this.detachListeners('document');
        event.preventDefault();
        this.renderer.setStyle(this.dropIndicator, 'visibility', 'hidden');
        if (!this.table) {
            this.cleanupDragState();
            return;
        }
        const finalTargetIndex = this.currentDropIndex;
        if (this.startElementIndex !== -1 && finalTargetIndex !== -1 && finalTargetIndex !== this.startElementIndex) {
            if (this.dragMode === 'column') {
                this.moveColumn(this.startElementIndex, finalTargetIndex);
                this.columnMoved.emit({
                    startElementIndex: this.startElementIndex,
                    finalTargetIndex
                });
            }
            else if (this.dragMode === 'row') {
                this.moveRow(this.startElementIndex, finalTargetIndex);
                this.rowMoved.emit({
                    startElementIndex: this.startElementIndex,
                    finalTargetIndex
                });
            }
        }
        this.cleanupDragState();
        this.moveEnd.emit();
        this.table
            .querySelectorAll('td.dragging-source, th.dragging-source')
            .forEach(cell => {
            this.renderer.removeClass(cell, 'dragging-source');
        });
    }
    cleanupDragState() {
        const draggedMode = this.dragMode;
        const startIndex = this.startElementIndex;
        const sourceElement = this.draggedElementSource;
        const activeHandler = this.draggedElement;
        this.renderer.setStyle(this.dropIndicator, 'visibility', 'hidden');
        this.isDragging = false;
        this.dragMode = null;
        this.startElementIndex = -1;
        this.draggedElement = null;
        this.draggedElementSource = null;
        this.columnInfo = [];
        this.rowInfo = [];
        this.currentDropIndex = -1;
        this.handlerStartY = 0;
        this.suppressInteractions = false;
        this.clearDropHighlights();
        if (this.table) {
            if (draggedMode === 'column') {
                this.renderer.removeClass(this.table, 'dragging-column');
                if (startIndex >= 0) {
                    this.styleColumnAsSource(startIndex, false);
                    this.highlightColumn(startIndex, false);
                }
                else {
                    this.table.querySelectorAll('td.dragging-source, th.dragging-source').forEach(cell => this.renderer.removeClass(cell, 'dragging-source'));
                    this.table.querySelectorAll('.col-highlight').forEach(cell => this.renderer.removeClass(cell, 'col-highlight'));
                }
            }
            else if (draggedMode === 'row') {
                this.renderer.removeClass(this.table, 'dragging-row');
                if (sourceElement)
                    this.renderer.removeClass(sourceElement, 'dragging-source');
            }
        }
        if (activeHandler) {
            this.renderer.removeClass(activeHandler, 'dragging-active-handler');
        }
        document.body.style.cursor = '';
        this.hideHandlers();
        this.cancelHideTimer();
    }
    moveRow(fromIndex, toIndex) {
        if (!this.table) {
            return;
        }
        const tbody = this.table.tBodies[0];
        if (!tbody) {
            return;
        }
        const visibleRows = Array.from(tbody.rows).filter(r => !r.classList.contains('dragging-source'));
        if (fromIndex < 0 || fromIndex >= visibleRows.length || toIndex < 0 || toIndex > visibleRows.length || fromIndex === toIndex) {
            const allRows = Array.from(tbody.rows);
            if (fromIndex < 0 || fromIndex >= allRows.length || toIndex < 0 || toIndex > allRows.length || fromIndex === toIndex) {
                return;
            }
        }
        const rowToMove = tbody.querySelector('tr.dragging-source');
        if (!rowToMove) {
            return;
        }
        const actualFromIndex = Array.from(tbody.rows).indexOf(rowToMove);
        const allRows = Array.from(tbody.rows);
        let referenceNode = null;
        let currentVisibleIndex = 0;
        let actualInsertIndex = -1;
        for (let i = 0; i < allRows.length; i++) {
            if (!allRows[i].classList.contains('dragging-source')) {
                if (currentVisibleIndex === toIndex) {
                    actualInsertIndex = i;
                    break;
                }
                currentVisibleIndex++;
            }
        }
        if (actualInsertIndex === -1 && toIndex === visibleRows.length) {
            actualInsertIndex = allRows.length;
        }
        if (actualInsertIndex !== -1) {
            if (actualFromIndex < actualInsertIndex) {
                referenceNode = allRows[actualInsertIndex] ?? null;
            }
            else {
                referenceNode = allRows[actualInsertIndex];
            }
        }
        else {
            return;
        }
        try {
            this.renderer.insertBefore(tbody, rowToMove, referenceNode);
        }
        catch (error) {
        }
        this.hoveredRowIndex = -1;
    }
    moveColumn(fromIndex, toIndex) {
        if (!this.table || fromIndex === toIndex || fromIndex < 0 || toIndex < 0) {
            return;
        }
        let moved = false;
        for (let i = 0; i < this.table.rows.length; i++) {
            const row = this.table.rows[i];
            const cells = Array.from(row.cells);
            if (fromIndex >= cells.length || toIndex > cells.length) {
                continue;
            }
            const cellToMove = cells[fromIndex];
            let referenceNode = null;
            if (fromIndex < toIndex) {
                referenceNode = cells[toIndex + 1] ?? null;
            }
            else {
                referenceNode = cells[toIndex];
            }
            if (cellToMove) {
                try {
                    this.renderer.insertBefore(row, cellToMove, referenceNode);
                    moved = true;
                }
                catch (error) {
                }
            }
        }
    }
    styleColumnAsSource(columnIndex, add) {
        if (!this.table || columnIndex < 0)
            return;
        for (let i = 0; i < this.table.rows.length; i++) {
            const row = this.table.rows[i];
            if (columnIndex < row.cells.length) {
                const cell = row.cells[columnIndex];
                if (cell) {
                    if (add) {
                        this.renderer.addClass(cell, 'dragging-source');
                    }
                    else {
                        this.renderer.removeClass(cell, 'dragging-source');
                    }
                }
            }
        }
    }
    calculateColumnInfo() {
        this.columnInfo = [];
        if (!this.table || this.table.rows.length === 0)
            return;
        const referenceRow = this.table.tHead?.rows[0] ?? this.table.rows[0];
        if (!referenceRow)
            return;
        for (let i = 0; i < referenceRow.cells.length; i++) {
            const cell = referenceRow.cells[i];
            const rect = cell.getBoundingClientRect();
            this.columnInfo.push({ index: i, left: rect.left, width: rect.width, center: rect.left + rect.width / 2 });
        }
    }
    calculateRowInfo() {
        this.rowInfo = [];
        if (!this.table || !this.table.tBodies[0])
            return;
        const tbody = this.table.tBodies[0];
        let visibleIndex = 0;
        for (let i = 0; i < tbody.rows.length; i++) {
            const row = tbody.rows[i];
            const rect = row.getBoundingClientRect();
            this.rowInfo.push({
                index: visibleIndex,
                element: row,
                top: rect.top,
                height: rect.height,
                center: rect.top + rect.height / 2
            });
            visibleIndex++;
        }
    }
    findFirstVisibleCellInColumn(columnIndex) {
        if (!this.table || columnIndex < 0)
            return null;
        for (let i = 0; i < this.table.rows.length; i++) {
            const row = this.table.rows[i];
            if (columnIndex < row.cells.length) {
                const c = row.cells[columnIndex];
                if (c && c.offsetParent !== null) {
                    return c;
                }
            }
        }
        return null;
    }
    updateDropIndicator(targetVisualIndex, mode) {
        if (!this.table || targetVisualIndex < 0 || this.startElementIndex < 0) {
            this.renderer.setStyle(this.dropIndicator, 'visibility', 'hidden');
            return;
        }
        const insertBeforeIndex = (targetVisualIndex <= this.startElementIndex) ? targetVisualIndex : targetVisualIndex + 1;
        if (insertBeforeIndex === this.startElementIndex || insertBeforeIndex === this.startElementIndex + 1) {
            this.renderer.setStyle(this.dropIndicator, 'visibility', 'hidden');
            return;
        }
        const tableRect = this.table.getBoundingClientRect();
        if (mode === 'column') {
            const referenceColumnInfo = this.columnInfo.find(c => c.index === insertBeforeIndex);
            let indicatorLeftTable = 0;
            if (referenceColumnInfo) {
                indicatorLeftTable = referenceColumnInfo.left - tableRect.left;
            }
            else {
                const lastColInfo = this.columnInfo[this.columnInfo.length - 1];
                indicatorLeftTable = lastColInfo ? (lastColInfo.left - tableRect.left + lastColInfo.width) : this.table.offsetWidth;
            }
            indicatorLeftTable -= Math.floor(this.indicatorThickness / 2);
            this.renderer.setStyle(this.dropIndicator, 'left', `${indicatorLeftTable}px`);
            this.renderer.setStyle(this.dropIndicator, 'top', `0px`);
            this.renderer.setStyle(this.dropIndicator, 'height', `${this.table.offsetHeight}px`);
            this.renderer.setStyle(this.dropIndicator, 'width', `${this.indicatorThickness}px`);
            this.renderer.removeStyle(this.dropIndicator, 'right');
            this.renderer.removeStyle(this.dropIndicator, 'bottom');
        }
        else {
            const referenceRowInfo = this.rowInfo.find(r => r.index === insertBeforeIndex);
            let indicatorTopTable = 0;
            if (referenceRowInfo) {
                indicatorTopTable = referenceRowInfo.top - tableRect.top;
            }
            else {
                const lastRowInfo = this.rowInfo[this.rowInfo.length - 1];
                indicatorTopTable = lastRowInfo
                    ? (lastRowInfo.top - tableRect.top + lastRowInfo.height)
                    : (this.table.tBodies[0]?.offsetHeight ?? this.table.offsetHeight);
            }
            indicatorTopTable -= Math.floor(this.indicatorThickness / 2);
            this.renderer.setStyle(this.dropIndicator, 'top', `${indicatorTopTable}px`);
            this.renderer.setStyle(this.dropIndicator, 'left', `0px`);
            this.renderer.setStyle(this.dropIndicator, 'width', `${this.table.offsetWidth}px`);
            this.renderer.setStyle(this.dropIndicator, 'height', `${this.indicatorThickness}px`);
            this.renderer.removeStyle(this.dropIndicator, 'bottom');
            this.renderer.removeStyle(this.dropIndicator, 'right');
        }
        this.renderer.setStyle(this.dropIndicator, 'visibility', 'visible');
    }
    highlightColumn(index, add) {
    }
    clearDropHighlights() {
    }
    getCurrentScrollContainer() {
        if (isPlatformServer(this._platformId)) {
            return null;
        }
        try {
            const container = this.contentBuilder?.getScrollContainer?.();
            return container || null;
        }
        catch {
            return null;
        }
    }
    bindScrollContainerListener() {
        if (isPlatformServer(this._platformId)) {
            return;
        }
        if (this.scrollSub) {
            return;
        }
        this.unbindScrollContainerListener();
        this.ngZone.runOutsideAngular(() => {
            const scroll$ = this.contentBuilder?.scrollContainerScrolled;
            if (!scroll$) {
                return;
            }
            this.scrollSub = scroll$
                .pipe(takeUntilDestroyed(this.destroyRef))
                .subscribe(() => this.onScrollContainerScrolled());
        });
    }
    unbindScrollContainerListener() {
        if (this.scrollSub) {
            try {
                this.scrollSub.unsubscribe();
            }
            catch { }
            this.scrollSub = null;
        }
        this.scrollContainerRef = null;
    }
    ensureScrollContainerListener() {
        if (isPlatformServer(this._platformId)) {
            return;
        }
        if (!this.scrollSub)
            this.bindScrollContainerListener();
    }
    onScrollContainerScrolled() {
        this.cancelHideTimer();
        this.hideHandlers();
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: DraggableTableComponent, deps: [], target: i0.ɵɵFactoryTarget.Component });
    static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.1.0", version: "21.2.4", type: DraggableTableComponent, isStandalone: true, selector: "ngs-draggable-table", inputs: { disabled: { classPropertyName: "disabled", publicName: "disabled", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { columnMoved: "columnMoved", rowMoved: "rowMoved", moveStart: "moveStart", moveEnd: "moveEnd" }, host: { properties: { "class.disabled": "disabled() || null", "class.draggable-table-host": "this.hostClass" } }, exportAs: ["ngsDraggableTable"], ngImport: i0, template: "<ng-content/>\n", styles: ["@charset \"UTF-8\";:host{display:block}:host ::ng-deep .drag-handler{position:fixed;width:18px;height:18px;background-color:#6496ffb3;border:1px solid var(--ngs-color-primary);border-radius:3px;cursor:grab;box-sizing:border-box;transition:background-color .2s ease,visibility .1s linear;z-index:1000;visibility:hidden}:host ::ng-deep .drag-handler:hover{background-color:var(--ngs-color-primary)}:host ::ng-deep .drag-handler.dragging-active-handler{cursor:grabbing!important;background-color:var(--ngs-color-primary)!important;border-color:var(--ngs-color-primary)!important;z-index:1001!important}:host ::ng-deep .drop-indicator{position:absolute;background-color:var(--ngs-color-primary);z-index:5;pointer-events:none;visibility:hidden}:host ::ng-deep tr.dragging-source,:host ::ng-deep td.dragging-source,:host ::ng-deep th.dragging-source{background:var(--ngs-color-surface-container-low)}:host ::ng-deep table.dragging-row td,:host ::ng-deep table.dragging-row th,:host ::ng-deep table.dragging-column td,:host ::ng-deep table.dragging-column th,:host ::ng-deep tr.dragging-source td,:host ::ng-deep tr.dragging-source th,:host ::ng-deep td.dragging-source,:host ::ng-deep th.dragging-source{pointer-events:none}:host.disabled ::ng-deep .drag-handler{visibility:hidden!important}\n"], changeDetection: i0.ChangeDetectionStrategy.OnPush });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: DraggableTableComponent, decorators: [{
            type: Component,
            args: [{ selector: 'ngs-draggable-table', exportAs: 'ngsDraggableTable', imports: [], changeDetection: ChangeDetectionStrategy.OnPush, host: {
                        '[class.disabled]': 'disabled() || null'
                    }, template: "<ng-content/>\n", styles: ["@charset \"UTF-8\";:host{display:block}:host ::ng-deep .drag-handler{position:fixed;width:18px;height:18px;background-color:#6496ffb3;border:1px solid var(--ngs-color-primary);border-radius:3px;cursor:grab;box-sizing:border-box;transition:background-color .2s ease,visibility .1s linear;z-index:1000;visibility:hidden}:host ::ng-deep .drag-handler:hover{background-color:var(--ngs-color-primary)}:host ::ng-deep .drag-handler.dragging-active-handler{cursor:grabbing!important;background-color:var(--ngs-color-primary)!important;border-color:var(--ngs-color-primary)!important;z-index:1001!important}:host ::ng-deep .drop-indicator{position:absolute;background-color:var(--ngs-color-primary);z-index:5;pointer-events:none;visibility:hidden}:host ::ng-deep tr.dragging-source,:host ::ng-deep td.dragging-source,:host ::ng-deep th.dragging-source{background:var(--ngs-color-surface-container-low)}:host ::ng-deep table.dragging-row td,:host ::ng-deep table.dragging-row th,:host ::ng-deep table.dragging-column td,:host ::ng-deep table.dragging-column th,:host ::ng-deep tr.dragging-source td,:host ::ng-deep tr.dragging-source th,:host ::ng-deep td.dragging-source,:host ::ng-deep th.dragging-source{pointer-events:none}:host.disabled ::ng-deep .drag-handler{visibility:hidden!important}\n"] }]
        }], ctorParameters: () => [], propDecorators: { hostClass: [{
                type: HostBinding,
                args: ['class.draggable-table-host']
            }], disabled: [{ type: i0.Input, args: [{ isSignal: true, alias: "disabled", required: false }] }], columnMoved: [{ type: i0.Output, args: ["columnMoved"] }], rowMoved: [{ type: i0.Output, args: ["rowMoved"] }], moveStart: [{ type: i0.Output, args: ["moveStart"] }], moveEnd: [{ type: i0.Output, args: ["moveEnd"] }] } });

class TableBlockComponent {
    _platformId = inject(PLATFORM_ID);
    _contentBuilder = inject(CONTENT_BUILDER);
    _store = inject(ContentBuilderStore);
    _cdr = inject(ChangeDetectorRef);
    _tableRef = viewChild.required('table');
    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 */ []));
    _content = signal([], ...(ngDevMode ? [{ debugName: "_content" }] : /* istanbul ignore next */ []));
    _columnManaging = signal(false, ...(ngDevMode ? [{ debugName: "_columnManaging" }] : /* istanbul ignore next */ []));
    _rowManaging = signal(false, ...(ngDevMode ? [{ debugName: "_rowManaging" }] : /* istanbul ignore next */ []));
    _tableManging = signal(false, ...(ngDevMode ? [{ debugName: "_tableManging" }] : /* istanbul ignore next */ []));
    _resizeManging = signal(false, ...(ngDevMode ? [{ debugName: "_resizeManging" }] : /* istanbul ignore next */ []));
    initialized = signal(false, ...(ngDevMode ? [{ debugName: "initialized" }] : /* istanbul ignore next */ []));
    ngOnInit() {
        this._content.set(this.content());
    }
    ngAfterViewInit() {
        if (isPlatformBrowser(this._platformId)) {
            const selection = new SelectionArea({
                selectables: ['.table td'],
                boundaries: ['.table'],
                features: {
                    touch: true,
                    range: true,
                    deselectOnBlur: true,
                    singleTap: {
                        allow: false,
                        intersect: 'native'
                    }
                }
            }).on('start', ({ store, event }) => {
                if (!event.ctrlKey && !event.metaKey) {
                    store.stored.forEach((el) => el.classList.remove('selected'));
                    selection.clearSelection();
                }
            })
                .on('move', ({ store: { changed: { added, removed } } }) => {
                if (this._tableManging() || this._columnManaging() || this._rowManaging()) {
                    return;
                }
                added.forEach(el => el.classList.add('selected'));
                removed.forEach(el => el.classList.remove('selected'));
            });
        }
        this.initialized.set(true);
    }
    focus() {
    }
    onTableFocusChange(type) {
        if (type === null) {
            this.clearCellsSelection();
        }
    }
    clearCellsSelection() {
        this._tableRef().nativeElement.querySelectorAll('td')
            .forEach((el) => el.classList.remove('selected'));
        this.update();
    }
    onColAdded() {
        this._content.update((content) => {
            content.forEach((row) => {
                row.push({
                    content: '',
                    props: [],
                    styles: {},
                    options: {
                        colspan: 1,
                        rowspan: 1
                    }
                });
            });
            return content;
        });
        this._cdr.markForCheck();
        this.update();
    }
    onColDeleted() {
        if (this._content().length > 0 && this._content()[0].length === 1) {
            return;
        }
        let isLastColEmpty = false;
        this._content().forEach((row) => {
            if (row[row.length - 1].content) {
                isLastColEmpty = true;
            }
        });
        if (isLastColEmpty) {
            return;
        }
        this._content.update((content) => {
            content.forEach((row) => {
                row.splice(row.length - 1, 1);
            });
            return content;
        });
        this._cdr.markForCheck();
        this.update();
    }
    onRowAdded() {
        this._content.update((content) => {
            const row = [];
            for (let i = 0; i < content[0].length; i++) {
                row.push({
                    content: '',
                    props: [],
                    styles: {},
                    options: {
                        colspan: 1,
                        rowspan: 1
                    }
                });
            }
            content.push(row);
            return content;
        });
        this._cdr.markForCheck();
        this.update();
    }
    onRowDeleted() {
        if (this._content().length === 1) {
            return;
        }
        let isLastRowEmpty = false;
        this._content()[this._content().length - 1].forEach((cell) => {
            if (cell.content) {
                isLastRowEmpty = true;
            }
        });
        if (isLastRowEmpty) {
            return;
        }
        this._content.update((content) => {
            content.splice(content.length - 1, 1);
            return content;
        });
        this._cdr.markForCheck();
        this.update();
    }
    onColumnManagingStart() {
        this._columnManaging.set(true);
    }
    onColumnManagingEnd() {
        this._columnManaging.set(false);
    }
    onRowManagingStart() {
        this._rowManaging.set(true);
    }
    onRowManagingEnd() {
        this._rowManaging.set(false);
    }
    onColumnWidthChange(event) {
        this._content.update((content) => {
            content.forEach(row => {
                row[event.columnIndex].options['width'] = event.width;
            });
            return content;
        });
        this.update();
    }
    onColumnMoved(event) {
        this._content.update((content) => {
            content.forEach(row => {
                moveItemInArray(row, event.startElementIndex, event.finalTargetIndex);
            });
            return content;
        });
        this._cdr.markForCheck();
        this.update();
    }
    onRowMoved(event) {
        this._content.update((content) => {
            moveItemInArray(content, event.startElementIndex, event.finalTargetIndex);
            return content;
        });
        this._cdr.markForCheck();
        this.update();
    }
    onMoveStart() {
        this._tableManging.set(true);
    }
    onMoveEnd() {
        this._tableManging.set(false);
    }
    onColumnWidthChangeStart() {
        this._tableManging.set(true);
        this._resizeManging.set(true);
    }
    onColumnWidthChangeEnd() {
        this._tableManging.set(false);
        this._resizeManging.set(false);
        this._cdr.markForCheck();
    }
    getData() {
        return {
            content: this._content(),
            settings: {
                ...this.settings(),
            }
        };
    }
    isEmpty() {
        return false;
    }
    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: TableBlockComponent, deps: [], target: i0.ɵɵFactoryTarget.Component });
    static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "21.2.4", type: TableBlockComponent, isStandalone: true, selector: "ngs-table-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.is-column-managing": "_columnManaging()", "class.is-row-managing": "_rowManaging()" } }, providers: [
            {
                provide: CONTENT_EDITOR_BLOCK,
                useExisting: TableBlockComponent,
                multi: true
            }
        ], viewQueries: [{ propertyName: "_tableRef", first: true, predicate: ["table"], descendants: true, isSignal: true }], ngImport: i0, template: "<div class=\"table-overflow\">\n  <div class=\"table-container\">\n    <ngs-draggable-table [disabled]=\"_resizeManging() || _columnManaging() || _rowManaging()\"\n                         (columnMoved)=\"onColumnMoved($event)\"\n                         (rowMoved)=\"onRowMoved($event)\"\n                         (moveStart)=\"onMoveStart()\"\n                         (moveEnd)=\"onMoveEnd()\">\n      <table #table class=\"table\"\n             ngsResizableTable\n             cdkMonitorSubtreeFocus\n             (cdkFocusChange)=\"onTableFocusChange($event)\"\n             (columnWidthChangeStart)=\"onColumnWidthChangeStart()\"\n             (columnWidthChangeEnd)=\"onColumnWidthChangeEnd()\"\n             (columnWidthChange)=\"onColumnWidthChange($event)\">\n        <colgroup>\n          @for (cell of _content()[0]; track $index) {\n            <col [style.width.px]=\"cell.options.width || null\">\n          }\n        </colgroup>\n        <tbody>\n          @for (row of _content(); track $index) {\n            <tr>\n              @for (cell of row; track $index) {\n                <td #cell\n                    [ngsContentEditorContentEditable]=\"cell.content\"\n                    [props]=\"cell.props\"\n                    (contentChanged)=\"cell.content = $event\"\n                    (blur)=\"clearCellsSelection()\"\n                    [rowSpan]=\"cell.options.rowspan\"\n                    [colSpan]=\"cell.options.colspan\"></td>\n              }\n            </tr>\n          }\n        </tbody>\n      </table>\n      <div class=\"resize-end\" ngsTableColumnsManager\n           (columnManagingStart)=\"onColumnManagingStart()\"\n           (columnManagingEnd)=\"onColumnManagingEnd()\"\n           (columnAdded)=\"onColAdded()\"\n           (columnDeleted)=\"onColDeleted()\">\n        <ngs-icon name=\"fluent:add-24-regular\" class=\"resize-icon\" />\n      </div>\n      <div class=\"resize-bottom\" ngsTableRowsManager\n           (rowManagingStart)=\"onRowManagingStart()\"\n           (rowManagingEnd)=\"onRowManagingEnd()\"\n           (rowAdded)=\"onRowAdded()\"\n           (rowDeleted)=\"onRowDeleted()\">\n        <ngs-icon name=\"fluent:add-24-regular\" class=\"resize-icon\" />\n      </div>\n    </ngs-draggable-table>\n  </div>\n</div>\n", styles: ["@charset \"UTF-8\";:host{display:block}:host.is-column-managing{cursor:col-resize;-webkit-user-select:none;user-select:none}:host.is-row-managing{cursor:row-resize;-webkit-user-select:none;user-select:none}:host .table-overflow{position:relative;padding-bottom:26px;overflow-y:hidden;overflow-x:auto;width:var(--ngs-content-builder-content-width)}:host .table-container{position:relative;width:max-content}:host table{width:auto!important;word-break:break-word;border-collapse:collapse;table-layout:fixed;border:1px solid var(--ngs-color-border);outline:none}:host table tr:not(:last-child){border-bottom:1px solid var(--ngs-color-border)}:host table td{min-width:120px;height:40px;padding:calc(var(--spacing, .25rem) * 2) calc(var(--spacing, .25rem) * 3);outline:none}:host table td:not(:last-child){border-right:1px solid var(--ngs-color-border)}:host table td.selected{background:var(--ngs-color-neutral-200)}:host .resize-end{position:absolute;width:calc(var(--spacing, .25rem) * 4);right:calc(calc(var(--spacing, .25rem) * 5) * -1);top:0;bottom:0;border-radius:calc(var(--spacing, .25rem) * 1);background:var(--ngs-color-surface-container);display:flex;align-items:center;justify-content:center}:host .resize-end:hover{cursor:col-resize;background:var(--ngs-color-surface-container-high)}:host .resize-bottom{position:absolute;height:calc(var(--spacing, .25rem) * 4);bottom:calc(calc(var(--spacing, .25rem) * 5) * -1);left:0;right:0;border-radius:calc(var(--spacing, .25rem) * 1);background:var(--ngs-color-surface-container);display:flex;align-items:center;justify-content:center}:host .resize-bottom:hover{cursor:row-resize;background:var(--ngs-color-surface-container-high)}:host .resize-icon{font-size:14px!important;height:14px!important;width:14px!important}:host.is-resizing{-webkit-user-select:none;user-select:none}:host table[ngsResizableTable] th.resizable-hover-handle:after,:host table[ngsResizableTable] td.resizable-hover-handle:after{opacity:1;visibility:visible}:host .table-resizing{cursor:col-resize!important;-webkit-user-select:none;user-select:none}:host .table-resizing+.resizable-table-handle{opacity:1;visibility:visible}:host .resizable-table-wrapper{position:relative}:host .resizable-table-handle{position:absolute;top:0;height:100%;background-color:var(--ngs-color-primary-400);cursor:col-resize;z-index:10;opacity:0;visibility:hidden;left:-9999px;transition:opacity .05s ease-in-out,visibility .05s ease-in-out}:host .resizable-table-handle.resize-handle--active{opacity:1;visibility:visible}\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: "component", type: Icon, selector: "ngs-icon", inputs: ["name"], exportAs: ["ngsIcon"] }, { kind: "directive", type: TableColumnsManagerDirective, selector: "[ngsTableColumnsManager]", outputs: ["columnAdded", "columnDeleted", "columnManagingStart", "columnManagingEnd"] }, { kind: "directive", type: TableRowsManagerDirective, selector: "[ngsTableRowsManager]", outputs: ["rowManagingStart", "rowManagingEnd", "rowAdded", "rowDeleted"] }, { kind: "directive", type: CdkMonitorFocus, selector: "[cdkMonitorElementFocus], [cdkMonitorSubtreeFocus]", outputs: ["cdkFocusChange"], exportAs: ["cdkMonitorFocus"] }, { kind: "directive", type: ResizableTableDirective, selector: "table[ngsResizableTable]", inputs: ["minColumnWidth", "resizeHandleWidth", "mutationObserverDebounceTime"], outputs: ["columnWidthChange", "columnWidthChangeStart", "columnWidthChangeEnd"] }, { kind: "component", type: DraggableTableComponent, selector: "ngs-draggable-table", inputs: ["disabled"], outputs: ["columnMoved", "rowMoved", "moveStart", "moveEnd"], exportAs: ["ngsDraggableTable"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.4", ngImport: i0, type: TableBlockComponent, decorators: [{
            type: Component,
            args: [{ selector: 'ngs-table-block', imports: [
                        ContentEditorContentEditableDirective,
                        Icon,
                        TableColumnsManagerDirective,
                        TableRowsManagerDirective,
                        CdkMonitorFocus,
                        ResizableTableDirective,
                        DraggableTableComponent
                    ], providers: [
                        {
                            provide: CONTENT_EDITOR_BLOCK,
                            useExisting: TableBlockComponent,
                            multi: true
                        }
                    ], changeDetection: ChangeDetectionStrategy.OnPush, host: {
                        '[class.is-column-managing]': '_columnManaging()',
                        '[class.is-row-managing]': '_rowManaging()',
                    }, template: "<div class=\"table-overflow\">\n  <div class=\"table-container\">\n    <ngs-draggable-table [disabled]=\"_resizeManging() || _columnManaging() || _rowManaging()\"\n                         (columnMoved)=\"onColumnMoved($event)\"\n                         (rowMoved)=\"onRowMoved($event)\"\n                         (moveStart)=\"onMoveStart()\"\n                         (moveEnd)=\"onMoveEnd()\">\n      <table #table class=\"table\"\n             ngsResizableTable\n             cdkMonitorSubtreeFocus\n             (cdkFocusChange)=\"onTableFocusChange($event)\"\n             (columnWidthChangeStart)=\"onColumnWidthChangeStart()\"\n             (columnWidthChangeEnd)=\"onColumnWidthChangeEnd()\"\n             (columnWidthChange)=\"onColumnWidthChange($event)\">\n        <colgroup>\n          @for (cell of _content()[0]; track $index) {\n            <col [style.width.px]=\"cell.options.width || null\">\n          }\n        </colgroup>\n        <tbody>\n          @for (row of _content(); track $index) {\n            <tr>\n              @for (cell of row; track $index) {\n                <td #cell\n                    [ngsContentEditorContentEditable]=\"cell.content\"\n                    [props]=\"cell.props\"\n                    (contentChanged)=\"cell.content = $event\"\n                    (blur)=\"clearCellsSelection()\"\n                    [rowSpan]=\"cell.options.rowspan\"\n                    [colSpan]=\"cell.options.colspan\"></td>\n              }\n            </tr>\n          }\n        </tbody>\n      </table>\n      <div class=\"resize-end\" ngsTableColumnsManager\n           (columnManagingStart)=\"onColumnManagingStart()\"\n           (columnManagingEnd)=\"onColumnManagingEnd()\"\n           (columnAdded)=\"onColAdded()\"\n           (columnDeleted)=\"onColDeleted()\">\n        <ngs-icon name=\"fluent:add-24-regular\" class=\"resize-icon\" />\n      </div>\n      <div class=\"resize-bottom\" ngsTableRowsManager\n           (rowManagingStart)=\"onRowManagingStart()\"\n           (rowManagingEnd)=\"onRowManagingEnd()\"\n           (rowAdded)=\"onRowAdded()\"\n           (rowDeleted)=\"onRowDeleted()\">\n        <ngs-icon name=\"fluent:add-24-regular\" class=\"resize-icon\" />\n      </div>\n    </ngs-draggable-table>\n  </div>\n</div>\n", styles: ["@charset \"UTF-8\";:host{display:block}:host.is-column-managing{cursor:col-resize;-webkit-user-select:none;user-select:none}:host.is-row-managing{cursor:row-resize;-webkit-user-select:none;user-select:none}:host .table-overflow{position:relative;padding-bottom:26px;overflow-y:hidden;overflow-x:auto;width:var(--ngs-content-builder-content-width)}:host .table-container{position:relative;width:max-content}:host table{width:auto!important;word-break:break-word;border-collapse:collapse;table-layout:fixed;border:1px solid var(--ngs-color-border);outline:none}:host table tr:not(:last-child){border-bottom:1px solid var(--ngs-color-border)}:host table td{min-width:120px;height:40px;padding:calc(var(--spacing, .25rem) * 2) calc(var(--spacing, .25rem) * 3);outline:none}:host table td:not(:last-child){border-right:1px solid var(--ngs-color-border)}:host table td.selected{background:var(--ngs-color-neutral-200)}:host .resize-end{position:absolute;width:calc(var(--spacing, .25rem) * 4);right:calc(calc(var(--spacing, .25rem) * 5) * -1);top:0;bottom:0;border-radius:calc(var(--spacing, .25rem) * 1);background:var(--ngs-color-surface-container);display:flex;align-items:center;justify-content:center}:host .resize-end:hover{cursor:col-resize;background:var(--ngs-color-surface-container-high)}:host .resize-bottom{position:absolute;height:calc(var(--spacing, .25rem) * 4);bottom:calc(calc(var(--spacing, .25rem) * 5) * -1);left:0;right:0;border-radius:calc(var(--spacing, .25rem) * 1);background:var(--ngs-color-surface-container);display:flex;align-items:center;justify-content:center}:host .resize-bottom:hover{cursor:row-resize;background:var(--ngs-color-surface-container-high)}:host .resize-icon{font-size:14px!important;height:14px!important;width:14px!important}:host.is-resizing{-webkit-user-select:none;user-select:none}:host table[ngsResizableTable] th.resizable-hover-handle:after,:host table[ngsResizableTable] td.resizable-hover-handle:after{opacity:1;visibility:visible}:host .table-resizing{cursor:col-resize!important;-webkit-user-select:none;user-select:none}:host .table-resizing+.resizable-table-handle{opacity:1;visibility:visible}:host .resizable-table-wrapper{position:relative}:host .resizable-table-handle{position:absolute;top:0;height:100%;background-color:var(--ngs-color-primary-400);cursor:col-resize;z-index:10;opacity:0;visibility:hidden;left:-9999px;transition:opacity .05s ease-in-out,visibility .05s ease-in-out}:host .resizable-table-handle.resize-handle--active{opacity:1;visibility:visible}\n/*! tailwindcss v4.2.2 | MIT License | https://tailwindcss.com */\n"] }]
        }], propDecorators: { _tableRef: [{ type: i0.ViewChild, args: ['table', { isSignal: true }] }], 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 { TableBlockComponent };
//# sourceMappingURL=ngstarter-ui-components-content-editor-table-block.component-bgBNjf4d.mjs.map
