import { jsxDEV, Fragment } from "react/jsx-dev-runtime";
import { Component, useEntity, QueryLanguage, useMutationState, Field } from "@contember/react-binding";
import { FieldContainer, EditorCanvas } from "@contember/ui";
import { useMemo, useState, useCallback } from "react";
import { Transforms, Element, Editor, Node } from "slate";
import { Slate, Editable } from "slate-react";
import { useAccessorErrors } from "@contember/react-binding-ui";
import { RichEditor } from "../RichEditor.js";
import { useRichTextFieldNodes } from "./useRichTextFieldNodes.js";
import { createEditor } from "../editorFactory/createEditor.js";
import { HoveringToolbars } from "../toolbars/HoveringToolbars.js";
import { paragraphElementType } from "../plugins/element/paragraphs/ParagraphElement.js";
const RichTextField = Component(
  (props) => {
    const entity = useEntity();
    const environment = entity.environment;
    const getParent = entity.getAccessor;
    const desugaredField = useMemo(
      () => QueryLanguage.desugarRelativeSingleField(props, environment),
      [environment, props]
    );
    const fieldAccessor = useMemo(() => entity.getRelativeSingleField(desugaredField), [entity, desugaredField]);
    const [contemberFieldElementCache] = useState(() => /* @__PURE__ */ new WeakMap());
    const isMutating = useMutationState();
    const [editor] = useState(() => {
      const editor2 = createEditor({
        plugins: props.plugins ?? [
          "code",
          "strikeThrough",
          "highlight",
          "underline",
          "italic",
          "bold",
          "scrollTarget",
          "anchor",
          "paragraph"
        ],
        augmentEditor: props.augmentEditor,
        augmentEditorBuiltins: props.augmentEditorBuiltins,
        defaultElementType: paragraphElementType,
        addEditorBuiltins: (editor3) => editor3
      });
      const { normalizeNode } = editor2;
      Object.assign(editor2, {
        insertBreak: () => {
          Transforms.insertText(editor2, "\n");
        },
        normalizeNode: (nodeEntry) => {
          const [node, path] = nodeEntry;
          if (path.length === 0 && Element.isAncestor(node)) {
            if (node.children.length > 1) {
              return Editor.withoutNormalizing(editor2, () => {
                const targetPath = [0, editor2.children[0].children.length];
                Transforms.moveNodes(editor2, {
                  at: [1],
                  to: targetPath
                });
                Transforms.unwrapNodes(editor2, { at: targetPath });
              });
            }
            if (Element.isElement(node.children[0]) && !editor2.isDefaultElement(node.children[0])) {
              return Editor.withoutNormalizing(editor2, () => {
                Transforms.wrapNodes(editor2, editor2.createDefaultElement([{ text: "" }]), {
                  at: path
                });
                Transforms.unwrapNodes(editor2, { at: [0, 0] });
              });
            }
          }
          if (Editor.isBlock(editor2, node) && path.length > 1) {
            return Transforms.unwrapNodes(editor2, { at: path });
          }
          normalizeNode(nodeEntry);
        }
      });
      return editor2;
    });
    const valueNodes = useRichTextFieldNodes({
      editor,
      fieldAccessor,
      contemberFieldElementCache
    });
    const serialize = editor.serializeNodes;
    const onChange = useCallback(
      (value) => {
        getParent().batchUpdates((getAccessor) => {
          const fieldAccessor2 = getAccessor().getRelativeSingleField(desugaredField);
          if (Node.string({ type: "dummy", children: value }) === "" && fieldAccessor2.valueOnServer === null) {
            fieldAccessor2.updateValue(null);
            return;
          }
          if (Element.isElement(value[0])) {
            fieldAccessor2.updateValue(serialize(value[0].children));
            contemberFieldElementCache.set(getAccessor().getRelativeSingleField(desugaredField), value);
          }
        });
      },
      [getParent, contemberFieldElementCache, desugaredField, serialize]
    );
    return /* @__PURE__ */ jsxDEV(
      FieldContainer,
      {
        label: props.label,
        size: props.size,
        labelDescription: props.labelDescription,
        labelPosition: props.labelPosition,
        description: props.description,
        useLabelElement: props.useLabelElement,
        errors: useAccessorErrors(fieldAccessor.errors?.errors),
        children: /* @__PURE__ */ jsxDEV(Slate, { editor, value: valueNodes, onChange, children: /* @__PURE__ */ jsxDEV(
          EditorCanvas,
          {
            underlyingComponent: Editable,
            distinction: props.distinction,
            componentProps: {
              readOnly: isMutating,
              renderElement: editor.renderElement,
              renderLeaf: editor.renderLeaf,
              onKeyDown: editor.onKeyDown,
              onFocusCapture: editor.onFocus,
              onBlurCapture: editor.onBlur,
              onDOMBeforeInput: editor.onDOMBeforeInput,
              placeholder: props.placeholder
            },
            children: /* @__PURE__ */ jsxDEV(
              HoveringToolbars,
              {
                blockButtons: props.blockButtons,
                inlineButtons: props.inlineButtons ?? defaultInlineButtons
              },
              void 0,
              false,
              {
                fileName: "/__w/interface/interface/packages/admin/src/components/bindingFacade/richText/RichTextField/RichTextField.tsx",
                lineNumber: 159,
                columnNumber: 7
              },
              void 0
            )
          },
          void 0,
          false,
          {
            fileName: "/__w/interface/interface/packages/admin/src/components/bindingFacade/richText/RichTextField/RichTextField.tsx",
            lineNumber: 145,
            columnNumber: 6
          },
          void 0
        ) }, void 0, false, {
          fileName: "/__w/interface/interface/packages/admin/src/components/bindingFacade/richText/RichTextField/RichTextField.tsx",
          lineNumber: 144,
          columnNumber: 5
        }, void 0)
      },
      void 0,
      false,
      {
        fileName: "/__w/interface/interface/packages/admin/src/components/bindingFacade/richText/RichTextField/RichTextField.tsx",
        lineNumber: 135,
        columnNumber: 4
      },
      void 0
    );
  },
  (props) => /* @__PURE__ */ jsxDEV(Fragment, { children: [
    /* @__PURE__ */ jsxDEV(Field, { defaultValue: props.defaultValue, field: props.field, isNonbearing: props.isNonbearing }, void 0, false, {
      fileName: "/__w/interface/interface/packages/admin/src/components/bindingFacade/richText/RichTextField/RichTextField.tsx",
      lineNumber: 170,
      columnNumber: 4
    }, void 0),
    props.label,
    props.labelDescription,
    props.description
  ] }, void 0, true, {
    fileName: "/__w/interface/interface/packages/admin/src/components/bindingFacade/richText/RichTextField/RichTextField.tsx",
    lineNumber: 169,
    columnNumber: 3
  }, void 0),
  "RichTextField"
);
const RB = RichEditor.buttons;
const defaultInlineButtons = [
  [RB.bold, RB.italic, RB.underline, RB.anchor],
  [RB.strikeThrough, RB.code]
];
export {
  RichTextField
};
//# sourceMappingURL=RichTextField.js.map
