/**
 * DevExtreme (esm/__internal/ui/html_editor/modules/m_tableContextMenu.js)
 * Version: 23.2.9 (build 24294-0112)
 * Build date: Sun Oct 20 2024
 *
 * Copyright (c) 2012 - 2024 Developer Express Inc. ALL RIGHTS RESERVED
 * Read about DevExtreme licensing here: https://js.devexpress.com/Licensing/
 */
import $ from "../../../../core/renderer";
import {
    extend
} from "../../../../core/utils/extend";
import {
    camelize,
    titleize
} from "../../../../core/utils/inflector";
import {
    each
} from "../../../../core/utils/iterator";
import {
    isObject,
    isString
} from "../../../../core/utils/type";
import eventsEngine from "../../../../events/core/events_engine";
import {
    addNamespace
} from "../../../../events/utils/index";
import localizationMessage from "../../../../localization/message";
import ContextMenu from "../../../../ui/context_menu";
import Quill from "devextreme-quill";
import {
    getTableFormats
} from "../utils/m_table_helper";
import {
    getDefaultClickHandler,
    getFormatHandlers,
    ICON_MAP
} from "../utils/m_toolbar_helper";
import BaseModule from "./m_base";
var MODULE_NAMESPACE = "dxHtmlEditorTableContextMenu";
var CONTEXT_MENU_EVENT = addNamespace("dxcontextmenu", MODULE_NAMESPACE);
var TableContextMenuModule = BaseModule;
var localize = name => localizationMessage.format("dxHtmlEditor-".concat(camelize(name)));
if (Quill) {
    TableContextMenuModule = class extends BaseModule {
        constructor(quill, options) {
            super(quill, options);
            this.enabled = !!options.enabled;
            this._quillContainer = this.editorInstance._getQuillContainer();
            this.addCleanCallback(this.prepareCleanCallback());
            this._formatHandlers = getFormatHandlers(this);
            this._tableFormats = getTableFormats(quill);
            if (this.enabled) {
                this._enableContextMenu(options.items)
            }
        }
        _enableContextMenu(items) {
            var _a;
            null === (_a = this._contextMenu) || void 0 === _a ? void 0 : _a.dispose();
            this._contextMenu = this._createContextMenu(items);
            this._attachEvents()
        }
        _attachEvents() {
            eventsEngine.on(this.editorInstance._getContent(), CONTEXT_MENU_EVENT, this._prepareContextMenuHandler())
        }
        _detachEvents() {
            eventsEngine.off(this.editorInstance._getContent(), CONTEXT_MENU_EVENT)
        }
        _createContextMenu(items) {
            var $container = $("<div>").appendTo(this.editorInstance.$element());
            var menuConfig = this._getMenuConfig(items);
            return this.editorInstance._createComponent($container, ContextMenu, menuConfig)
        }
        showPropertiesForm() {
            var type = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : "cell";
            var $element = $(this._targetElement).closest("cell" === type ? "th, td" : "table");
            this._contextMenu.hide();
            this._formatHandlers["".concat(type, "Properties")]($element);
            this._targetElement = null
        }
        _isAcceptableItem(widget, acceptableWidgetName) {
            return !widget || widget === acceptableWidgetName
        }
        _handleObjectItem(item) {
            if (item.name && this._isAcceptableItem(item.widget, "dxButton")) {
                var defaultButtonItemConfig = this._prepareMenuItemConfig(item.name);
                var buttonItemConfig = extend(true, defaultButtonItemConfig, item);
                return buttonItemConfig
            }
            if (item.items) {
                item.items = this._prepareMenuItems(item.items);
                return item
            }
            return item
        }
        _prepareMenuItemConfig(name) {
            var _a, _b;
            var iconName = null !== (_a = ICON_MAP[name]) && void 0 !== _a ? _a : name;
            var buttonText = titleize(name);
            return {
                text: localize(buttonText),
                icon: iconName.toLowerCase(),
                onClick: null !== (_b = this._formatHandlers[name]) && void 0 !== _b ? _b : getDefaultClickHandler(this, name)
            }
        }
        _prepareMenuItems(items) {
            var resultItems = [];
            each(items, (_, item) => {
                var newItem;
                if (isObject(item)) {
                    newItem = this._handleObjectItem(item)
                } else if (isString(item)) {
                    newItem = this._prepareMenuItemConfig(item)
                }
                if (newItem) {
                    resultItems.push(newItem)
                }
            });
            return resultItems
        }
        _getMenuConfig(items) {
            var defaultItems = [{
                text: localize("insert"),
                items: ["insertHeaderRow", "insertRowAbove", "insertRowBelow", extend(this._prepareMenuItemConfig("insertColumnLeft"), {
                    beginGroup: true
                }), "insertColumnRight"]
            }, {
                text: localize("delete"),
                items: ["deleteColumn", "deleteRow", "deleteTable"]
            }, extend(this._prepareMenuItemConfig("cellProperties"), {
                onClick: () => {
                    this.showPropertiesForm("cell")
                }
            }), extend(this._prepareMenuItemConfig("tableProperties"), {
                onClick: () => {
                    this.showPropertiesForm("table")
                }
            })];
            var customItems = this._prepareMenuItems((null === items || void 0 === items ? void 0 : items.length) ? items : defaultItems);
            return {
                target: this._quillContainer,
                showEvent: null,
                hideOnParentScroll: false,
                items: customItems
            }
        }
        _prepareContextMenuHandler() {
            return event => {
                if (this._isTableTarget(event.target)) {
                    this._targetElement = event.target;
                    this._setContextMenuPosition(event);
                    this._contextMenu.show();
                    event.preventDefault()
                }
            }
        }
        _setContextMenuPosition(event) {
            var startPosition = this._quillContainer.get(0).getBoundingClientRect();
            this._contextMenu.option({
                position: {
                    my: "left top",
                    at: "left top",
                    collision: "fit fit",
                    offset: {
                        x: event.clientX - startPosition.left,
                        y: event.clientY - startPosition.top
                    }
                }
            })
        }
        _isTableTarget(targetElement) {
            return !!$(targetElement).closest(".dx-htmleditor-content td, .dx-htmleditor-content th").length
        }
        clean() {
            this._detachEvents()
        }
        option(option, value) {
            var _a;
            if ("tableContextMenu" === option) {
                this.handleOptionChangeValue(value);
                return
            }
            if ("enabled" === option) {
                this.enabled = value;
                value ? this._enableContextMenu() : this.clean()
            } else if ("items" === option) {
                null === (_a = this._contextMenu) || void 0 === _a ? void 0 : _a.dispose();
                this._contextMenu = this._createContextMenu(value)
            }
        }
        prepareCleanCallback() {
            return () => {
                this.clean()
            }
        }
    }
}
export default TableContextMenuModule;
