import {
  TIPTAP_COLLAPSIBLE_ITEM_BODY_TYPE,
  TIPTAP_COLLAPSIBLE_ITEM_TITLE_TYPE,
  TIPTAP_COLLAPSIBLE_ITEM_TYPE,
  TIPTAP_COLLAPSIBLE_LIST_TYPE
} from "./../../ricos-content/index.js";
import { TextStyle_TextAlignment } from "./../../ricos-schema/legacy/wix/rich_content/v1/index.js";
import { findParentNodeClosestToPos } from "./../../tiptap/index.js";
import { Slice } from "./../../tiptap/pm/model.js";
import { Decoration, DecorationSet } from "./../../tiptap/pm/view.js";
import { createRicosNodeExtension } from "./../../plugin-commons/index.js";
import { collapsibleCopyPastePlugin, collapsibleStateManagerPlugin } from "../consts.js";
import { getAlignmentFromDirection } from "../utils.js";
import {
  CollapsibleList,
  CollapsibleListItem,
  CollapsibleListItemBody,
  CollapsibleListItemTitle
} from "./component.js";
import { defaultCollapsibleItem } from "./defaults.js";
import {
  findNodeById,
  getCollapsibleListByItemId,
  getCollapsibleListItems,
  updateCollapsibleListAttrs,
  updateCollapsibleListItemsAttrs,
  updateListItemAttributes
} from "./utils.js";
const tiptapExtensions = [
  createRicosNodeExtension({
    groups: ["custom-styles", "shortcuts-enabled", "node-container", "footer-disabled"],
    type: "react-node",
    reconfigure: (config, _extensions, _props, settings, services) => {
      return {
        ...config,
        addOptions: () => {
          return { services, ...settings };
        }
      };
    },
    Component: CollapsibleList,
    name: TIPTAP_COLLAPSIBLE_LIST_TYPE,
    createExtensionConfig({ Plugin }) {
      return {
        name: this.name,
        group: "block smartBlockCellContent layoutCellContent collapsibleListItemBodyContent",
        selectable: true,
        draggable: true,
        priority: 25,
        content: "COLLAPSIBLE_ITEM+",
        addAttributes() {
          return {
            containerData: null,
            isQapageData: null,
            direction: { default: this.options.services.context.languageDir.toUpperCase() },
            expandOnlyOne: { default: false },
            initialExpandedItems: { default: "FIRST" }
          };
        },
        addCommands() {
          return {
            addCollapsibleListItem: (position) => ({ commands }) => {
              return commands.insertContentAt(position - 1, defaultCollapsibleItem);
            },
            setCollapsibleListAttributes: (nodeId, attrs) => ({ state, view, commands }) => {
              updateCollapsibleListAttrs(commands, nodeId, attrs);
              updateCollapsibleListItemsAttrs(state, commands, nodeId, attrs);
              view.dispatch(state.tr);
              return true;
            },
            toggleCollapsibleItem: (nodeId) => ({ state, view, commands }) => {
              const collapsibleList = getCollapsibleListByItemId(state, nodeId);
              if (!collapsibleList) {
                return false;
              }
              const collapsibleListItem = findNodeById(state, nodeId)[0].node;
              const isListItemExpanded = collapsibleListItem.attrs.isExpanded;
              const items = getCollapsibleListItems(state, collapsibleList.attrs.id);
              if (collapsibleList.attrs.expandOnlyOne) {
                const expandedItems = items.filter(
                  (node) => node.attrs.isExpanded === true && node.attrs.id !== nodeId
                );
                if (expandedItems.length > 0 && !isListItemExpanded) {
                  expandedItems.forEach(
                    (i) => updateListItemAttributes(commands, i, { isExpanded: false })
                  );
                }
              }
              updateListItemAttributes(commands, collapsibleListItem, {
                isExpanded: !isListItemExpanded
              });
              view.dispatch(state.tr);
              return true;
            }
          };
        },
        addProseMirrorPlugins() {
          return [
            new Plugin({
              key: collapsibleStateManagerPlugin,
              props: {
                decorations: ({ doc }) => {
                  const decorations = [];
                  doc.descendants((node, pos) => {
                    const $pos = doc.resolve(pos);
                    const collapsibleListAncestorNode = findParentNodeClosestToPos(
                      $pos,
                      (node2) => node2.type?.name === TIPTAP_COLLAPSIBLE_LIST_TYPE
                    );
                    if (node.type?.name !== TIPTAP_COLLAPSIBLE_LIST_TYPE && !collapsibleListAncestorNode) {
                      return false;
                    }
                    if (collapsibleListAncestorNode) {
                      if (node?.attrs.textStyle?.textAlignment && node?.attrs.textStyle?.textAlignment !== TextStyle_TextAlignment.AUTO) {
                        return;
                      }
                      decorations.push(
                        Decoration.node(pos, pos + node.nodeSize, {
                          "data-text-align": getAlignmentFromDirection(
                            collapsibleListAncestorNode?.node.attrs.direction
                          )
                        })
                      );
                    }
                  });
                  return DecorationSet.create(doc, decorations);
                }
              }
            }),
            new Plugin({
              key: collapsibleCopyPastePlugin,
              props: {
                handlePaste: (view, event, slice) => {
                  if (slice.content.firstChild?.type.name !== TIPTAP_COLLAPSIBLE_LIST_TYPE) {
                    return false;
                  }
                  const { state } = view;
                  const { selection } = state;
                  const openStart = selection.$from.depth;
                  const adjustedSlice = new Slice(slice.content, openStart + 1, slice.openEnd);
                  const tr = state.tr;
                  tr.replaceRange(selection.from, selection.to, adjustedSlice);
                  view.dispatch(tr);
                  return true;
                }
              }
            })
          ];
        }
      };
    }
  }),
  createRicosNodeExtension({
    groups: ["custom-styles", "node-container"],
    type: "react-node",
    reconfigure: (config, _extensions, _props, settings) => ({
      ...config,
      addOptions: () => settings
    }),
    Component: CollapsibleListItem,
    name: TIPTAP_COLLAPSIBLE_ITEM_TYPE,
    createExtensionConfig() {
      return {
        name: this.name,
        group: TIPTAP_COLLAPSIBLE_ITEM_TYPE,
        draggable: true,
        content: "COLLAPSIBLE_ITEM_TITLE COLLAPSIBLE_ITEM_BODY",
        addAttributes: () => ({
          isExpanded: { default: true }
        })
      };
    }
  }),
  createRicosNodeExtension({
    groups: ["custom-styles", "node-container"],
    type: "react-node",
    reconfigure: (config, _extensions, _props, settings) => ({
      ...config,
      addOptions: () => settings
    }),
    Component: CollapsibleListItemTitle,
    name: TIPTAP_COLLAPSIBLE_ITEM_TITLE_TYPE,
    placeholder: {
      predicate: ({ doc, pos }) => {
        const parentNode = doc.resolve(pos).parent;
        return parentNode.childCount === 1 && parentNode.type.name === TIPTAP_COLLAPSIBLE_ITEM_TITLE_TYPE;
      },
      content: "CollapsibleList_ShownText_Placeholder",
      alwaysVisible: true
    },
    createExtensionConfig() {
      return {
        name: this.name,
        group: TIPTAP_COLLAPSIBLE_ITEM_TITLE_TYPE,
        isolating: true,
        content: "(PARAGRAPH|collapsibleListItemTitleContent)"
      };
    }
  }),
  createRicosNodeExtension({
    groups: ["custom-styles", "node-container"],
    type: "react-node",
    reconfigure: (config, _extensions, _props, settings) => ({
      ...config,
      addOptions: () => settings
    }),
    Component: CollapsibleListItemBody,
    name: TIPTAP_COLLAPSIBLE_ITEM_BODY_TYPE,
    placeholder: {
      predicate: ({ doc, pos }) => {
        const parentNode = doc.resolve(pos).parent;
        return parentNode.childCount === 1 && parentNode.type.name === TIPTAP_COLLAPSIBLE_ITEM_BODY_TYPE;
      },
      content: "CollapsibleList_CollapsedText_Placeholder",
      alwaysVisible: true
    },
    createExtensionConfig() {
      return {
        name: this.name,
        group: TIPTAP_COLLAPSIBLE_ITEM_BODY_TYPE,
        isolating: true,
        content: "(PARAGRAPH|collapsibleListItemBodyContent)+",
        addAttributes: () => ({
          isExpanded: null
        })
      };
    }
  })
];
export {
  tiptapExtensions
};
//# sourceMappingURL=tiptap.js.map
