import classNames from "classnames";
import { Node_Type } from "./../../ricos-schema/legacy/wix/rich_content/v1/index.js";
import { CHECKBOX_LIST_STYLE_ATTRIBUTE_VALUE } from "./../../_shared/list-checkbox/checkbox-list-style.js";
import { findParentNodeClosestToPos, mergeAttributes } from "./../../tiptap/index.js";
import { Plugin, PluginKey } from "./../../tiptap/pm/state.js";
import { Decoration, DecorationSet } from "./../../tiptap/pm/view.js";
import { createRicosNodeExtension } from "./../../plugin-commons/index.js";
import { findNodeById } from "./../../tiptap-editor/helpers/index.js";
import {
  createIndentationStylingDecorationPlugin,
  createListItemSizingDecorationPlugin,
  createListStylePositionDecorationPlugin
} from "../decoration-plugins/index.js";
import styles from "../statics/styles-scss.js";
import {
  createCheckboxStateNormalizingTransactionPlugin,
  createHandleTextWrapPlugin,
  createMergingSiblingListNodesTransactionPlugin,
  createOffsetNormalizingTransactionPlugin
} from "../transaction-plugins/index.js";
import { findParentList } from "./commands/commons.js";
import { indentList } from "./commands/indent-list.js";
import { outdentList } from "./commands/outdent-list.js";
import { toggleLists } from "./commands/toggle-lists.js";
const checkboxListDecorationPluginKey = new PluginKey("checkbox-list-decoration");
const createCheckboxDecorationSet = (doc, editor) => {
  const decorations = [];
  doc.descendants((node, pos) => {
    if (node.type.name !== Node_Type.LIST_ITEM) {
      return;
    }
    const $pos = doc.resolve(pos);
    const parentList = findParentList($pos);
    if (!parentList || parentList.node.type.name !== Node_Type.CHECKBOX_LIST) {
      return;
    }
    decorations.push(
      Decoration.node(pos, pos + node.nodeSize, {
        "data-list-style": CHECKBOX_LIST_STYLE_ATTRIBUTE_VALUE,
        role: "checkbox",
        "aria-checked": node.attrs.checked ? "true" : "false"
      })
    );
    decorations.push(
      Decoration.widget(
        pos + 1,
        () => {
          const checkbox = document.createElement("span");
          checkbox.className = styles.checkboxInput;
          checkbox.setAttribute("aria-hidden", "true");
          checkbox.setAttribute("aria-checked", node.attrs.checked ? "true" : "false");
          checkbox.tabIndex = -1;
          checkbox.setAttribute("contenteditable", "false");
          checkbox.addEventListener("mousedown", (event) => {
            event.preventDefault();
          });
          checkbox.addEventListener("click", (event) => {
            event.preventDefault();
            event.stopPropagation();
            editor.chain().focus().toggleCheckboxListItem(node.attrs.id).run();
          });
          return checkbox;
        },
        {
          side: -1,
          key: `checkbox-${node.attrs.id}-${node.attrs.checked ? "checked" : "unchecked"}`
        }
      )
    );
  });
  return DecorationSet.create(doc, decorations);
};
const createCheckboxListDecorationPlugin = (editor) => new Plugin({
  key: checkboxListDecorationPluginKey,
  state: {
    init: (_config, state) => createCheckboxDecorationSet(state.doc, editor),
    apply: (tr, decorationSet, _oldState, newState) => tr.docChanged ? createCheckboxDecorationSet(newState.doc, editor) : decorationSet
  },
  props: {
    decorations: (state) => checkboxListDecorationPluginKey.getState(state) ?? DecorationSet.empty
  }
});
const listItem = createRicosNodeExtension({
  groups: ["shortcuts-enabled"],
  type: "html-node",
  name: Node_Type.LIST_ITEM,
  reconfigure: (config, _extensions, _props, settings, services) => {
    return {
      ...config,
      addOptions() {
        return {
          services,
          HTMLAttributes: {
            class: styles.listItem,
            dir: "auto"
          },
          ...settings
        };
      }
    };
  },
  createExtensionConfig() {
    return {
      name: this.name,
      priority: 101,
      content: "(PARAGRAPH|listItemFirstChildContent) listItemSecondChildContent*",
      defining: true,
      parseHTML() {
        return [
          {
            tag: "li"
          }
        ];
      },
      addAttributes() {
        return {
          checked: {
            default: null,
            keepOnSplit: false,
            parseHTML: (element) => {
              const checked = element.getAttribute("aria-checked");
              if (checked === "true") {
                return true;
              }
              if (checked === "false") {
                return false;
              }
              return null;
            },
            // Render the `<li>` as the semantic checkbox so the state round-trips
            // with Google Docs (and is valid ARIA) in both the live editor and the
            // copied clipboard HTML.
            renderHTML: (attributes) => attributes.checked === null || attributes.checked === void 0 ? {} : { role: "checkbox", "aria-checked": attributes.checked ? "true" : "false" }
          }
        };
      },
      renderHTML({ HTMLAttributes }) {
        const allAttributes = mergeAttributes(this.options.HTMLAttributes, HTMLAttributes);
        const attrs = {
          ...allAttributes,
          class: classNames(allAttributes.class),
          dir: "auto"
        };
        return ["li", attrs, 0];
      },
      addCommands() {
        return {
          toggleLists,
          indentList,
          outdentList,
          toggleCheckboxListItem: (id) => ({ tr, dispatch }) => {
            const listItemNodeWithPos = findNodeById(tr, id)[0];
            if (!listItemNodeWithPos) {
              console.error("Failed to find checkbox list item");
              return false;
            }
            const nextChecked = !listItemNodeWithPos.node.attrs.checked;
            tr.setNodeMarkup(listItemNodeWithPos.pos, void 0, {
              ...listItemNodeWithPos.node.attrs,
              id,
              checked: nextChecked
            });
            dispatch?.(tr);
            return true;
          }
        };
      },
      addKeyboardShortcuts() {
        const newLine = () => {
          const currListItem = findParentNodeClosestToPos(
            this.editor.state.selection.$from,
            (node) => node.type.name === Node_Type.LIST_ITEM
          );
          if (currListItem && currListItem.node.content.childCount >= 2 && this.editor.state.selection.$from.nodeBefore === null) {
            return false;
          }
          return this.editor.commands.splitListItem(this.name);
        };
        const tiptapKeyboardShortcuts = {
          Enter: newLine
        };
        const newLineShortcuts = [];
        this.options.services.shortcuts.shortcuts.forEach((shortcut) => {
          if (shortcut.shortcut.name === "NewLine") {
            newLineShortcuts.push(shortcut);
          }
        });
        newLineShortcuts.forEach((newLineShortcut) => {
          const modifier = newLineShortcut.keys.macOs.modifiers[0];
          const key = newLineShortcut.keys.macOs.key;
          const shortcutKey = modifier ? `${modifier}-${key}` : key;
          tiptapKeyboardShortcuts[shortcutKey] = newLine;
        });
        return {
          ...tiptapKeyboardShortcuts
        };
      },
      addProseMirrorPlugins() {
        return [
          createIndentationStylingDecorationPlugin(),
          createListItemSizingDecorationPlugin(),
          createListStylePositionDecorationPlugin(),
          createCheckboxListDecorationPlugin(this.editor),
          createCheckboxStateNormalizingTransactionPlugin(),
          createMergingSiblingListNodesTransactionPlugin(),
          createOffsetNormalizingTransactionPlugin(),
          createHandleTextWrapPlugin()
        ];
      }
    };
  }
});
export {
  listItem
};
//# sourceMappingURL=extension.js.map
