import { Node_Type } from "./../ricos-schema/legacy/wix/rich_content/v1/index.js";
import { TextSelection } from "./../tiptap/pm/state.js";
import {
  createRicosNodeExtension,
  withBreakoutContainer
} from "./../plugin-commons/index.js";
import { ROOT } from "./data-hooks.js";
import styles from "./statics/styles/code-block-scss.js";
const backtickInputRegex = /^```(?<language>[a-z]*)?[\s\n]$/;
const tildeInputRegex = /^~~~(?<language>[a-z]*)?[\s\n]$/;
const tiptapExtensions = [
  createRicosNodeExtension({
    groups: ["shortcuts-enabled"],
    type: "html-node",
    name: Node_Type.CODE_BLOCK,
    reconfigure: (config, _extensions, _props, settings, services) => ({
      ...config,
      addOptions() {
        return {
          services,
          languageClassPrefix: "language-",
          HTMLAttributes: {
            class: styles.code
          },
          ...settings
        };
      }
    }),
    createExtensionConfig({ Plugin, PluginKey, textblockTypeInputRule, mergeAttributes }) {
      return {
        name: this.name,
        content: "(text|specialCharacter)*",
        group: "block smartBlockCellContent layoutCellContent collapsibleListItemTitleContent collapsibleListItemBodyContent tableCellContent",
        code: true,
        defining: true,
        priority: 101,
        addAttributes() {
          return {
            textStyle: null,
            language: {
              default: null,
              renderHTML: (attributes) => {
                if (!attributes.language) {
                  return null;
                }
                return {
                  class: this.options.languageClassPrefix + attributes.language
                };
              }
            }
          };
        },
        parseHTML() {
          return [
            {
              tag: "pre",
              preserveWhitespace: "full"
            }
          ];
        },
        renderHTML({ HTMLAttributes }) {
          const allAttributes = mergeAttributes(this.options.HTMLAttributes, HTMLAttributes, {
            "data-hook": ROOT,
            dir: "auto"
          });
          return withBreakoutContainer(["pre", allAttributes, 0], { class: styles.codeParent });
        },
        addCommands() {
          return {
            setCodeBlock: (attributes) => ({ commands }) => {
              return commands.updateTextNode(this.name, attributes);
            },
            toggleCodeBlock: (attributes) => ({ commands }) => {
              return commands.toggleTextNode(this.name, Node_Type.PARAGRAPH, attributes);
            }
          };
        },
        addKeyboardShortcuts() {
          const newLine = ({ editor }) => {
            const { state } = editor;
            const { selection } = state;
            const { $from, empty } = selection;
            if (!empty || $from.parent.type !== this.type) {
              return false;
            }
            const isAtEnd = $from.parentOffset === $from.parent.nodeSize - 2;
            const endsWithDoubleNewline = $from.parent.textContent.endsWith("\n\n");
            if (!isAtEnd || !endsWithDoubleNewline) {
              return false;
            }
            return editor.chain().command(({ tr }) => {
              tr.delete($from.pos - 2, $from.pos);
              return true;
            }).exitCode().run();
          };
          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 {
            // 'Mod-Alt-c': () => this.editor.commands.toggleCodeBlock(),
            // remove code block when at start of document or code block is empty
            Backspace: () => {
              const { empty, $anchor } = this.editor.state.selection;
              const isAtStart = $anchor.pos === 1;
              if (!empty || $anchor.parent.type.name !== this.name) {
                return false;
              }
              if (isAtStart || !$anchor.parent.textContent.length) {
                return this.editor.commands.normalizeNodes();
              }
              return false;
            },
            ...tiptapKeyboardShortcuts
          };
        },
        addInputRules() {
          return [
            textblockTypeInputRule({
              find: backtickInputRegex,
              type: this.type,
              getAttributes: ({ groups }) => groups
            }),
            textblockTypeInputRule({
              find: tildeInputRegex,
              type: this.type,
              getAttributes: ({ groups }) => groups
            })
          ];
        },
        addProseMirrorPlugins() {
          return [
            // this plugin creates a code block for pasted content from VS Code
            // we can also detect the copied code language
            new Plugin({
              key: new PluginKey("codeBlockVSCodeHandler"),
              props: {
                handlePaste: (view, event) => {
                  if (!event.clipboardData) {
                    return false;
                  }
                  if (this.editor.isActive(this.type.name)) {
                    return false;
                  }
                  const text = event.clipboardData.getData("text/plain");
                  const vscode = event.clipboardData.getData("vscode-editor-data");
                  const vscodeData = vscode ? JSON.parse(vscode) : void 0;
                  const language = vscodeData?.mode;
                  if (!text || !language) {
                    return false;
                  }
                  const { tr } = view.state;
                  tr.replaceSelectionWith(this.type.create({ language }));
                  tr.setSelection(
                    TextSelection.near(tr.doc.resolve(Math.max(0, tr.selection.from - 2)))
                  );
                  tr.insertText(text.replace(/\r\n?/g, "\n"));
                  tr.setMeta("paste", true);
                  view.dispatch(tr);
                  return true;
                }
              }
            })
          ];
        }
      };
    }
  })
];
export {
  tiptapExtensions
};
//# sourceMappingURL=tiptap.js.map
