import { j as e } from "../../../../../_virtual/jsx-runtime.js";
import { useEditor as W, EditorContent as _ } from "../../../../../node_modules/.pnpm/@tiptap_react@2.14.0_@tiptap_core@2.14.0_@tiptap_pm@2.14.0__@tiptap_pm@2.14.0_react-dom_ed8bf96066084acdc2699d834a628075/node_modules/@tiptap/react/dist/index.js";
import { Placeholder as Y } from "../../../../../node_modules/.pnpm/@tiptap_extension-placeholder@2.14.0_@tiptap_core@2.14.0_@tiptap_pm@2.14.0__@tiptap_pm@2.14.0/node_modules/@tiptap/extension-placeholder/dist/index.js";
import { RiBracesLine as Z, RiArrowDownSLine as N } from "../../../../../node_modules/.pnpm/react-icons@5.3.0_react@18.3.0-canary-3d9b20132-20240124/node_modules/react-icons/ri/index.js";
import { TextStyle as q } from "../../../../../node_modules/.pnpm/@tiptap_extension-text-style@2.14.0_@tiptap_core@2.14.0_@tiptap_pm@2.14.0_/node_modules/@tiptap/extension-text-style/dist/index.js";
import { StarterKit as ee } from "../../../../../node_modules/.pnpm/@tiptap_starter-kit@2.14.0/node_modules/@tiptap/starter-kit/dist/index.js";
import { TextAlign as te } from "../../../../../node_modules/.pnpm/@tiptap_extension-text-align@2.14.0_@tiptap_core@2.14.0_@tiptap_pm@2.14.0_/node_modules/@tiptap/extension-text-align/dist/index.js";
import { Heading as se } from "../../../../../node_modules/.pnpm/@tiptap_extension-heading@2.14.0_@tiptap_core@2.14.0_@tiptap_pm@2.14.0_/node_modules/@tiptap/extension-heading/dist/index.js";
import { forwardRef as ae, useState as m, useEffect as E, useImperativeHandle as re, startTransition as ne } from "react";
import "../../../../../node_modules/.pnpm/@formkit_auto-animate@0.8.2/node_modules/@formkit/auto-animate/index.js";
import { Root as oe, Item as v } from "../../../../../node_modules/.pnpm/@radix-ui_react-toggle-group@1.1.0_@types_react-dom@18.3.6_@types_react@18.3.3__@types__b10e33b51cd126cada778228afbcac05/node_modules/@radix-ui/react-toggle-group/dist/index.js";
import "../../../../../node_modules/.pnpm/react-hot-toast@2.5.2_react-dom@18.3.0-canary-3d9b20132-20240124_react@18.3.0-canary-3d_c02c1e17bf76c343fd22d1f22394ecf5/node_modules/react-hot-toast/dist/index.js";
import { Document as M } from "../../../../../node_modules/.pnpm/@tiptap_extension-document@2.14.0_@tiptap_core@2.14.0_@tiptap_pm@2.14.0_/node_modules/@tiptap/extension-document/dist/index.js";
import { MdFormatAlignLeft as ie, MdFormatAlignCenter as le, MdFormatAlignRight as ce, MdFormatAlignJustify as de, MdFormatBold as ue, MdOutlineFormatItalic as me, MdStrikethroughS as he } from "../../../../../node_modules/.pnpm/react-icons@5.3.0_react@18.3.0-canary-3d9b20132-20240124/node_modules/react-icons/md/index.js";
import { useEditor as pe, useSelectedBrickId as xe } from "../../../../../use-editor.js";
import { JSONSchemaView as fe } from "../../editor/components/json-form/SchemaView.js";
import { Mention as ge } from "../../../../../node_modules/.pnpm/@tiptap_extension-mention@2.14.0_@tiptap_core@2.14.0_@tiptap_pm@2.14.0__@tiptap_pm@2.14_61b779bbdaffa78f06bf6f82349b50b0/node_modules/@tiptap/extension-mention/dist/index.js";
import be from "./datasourceFieldSuggestions.js";
import { getJSONSchemaFieldsList as je } from "../utils/json-field-list.js";
import { Highlight as ke } from "../../../../../node_modules/.pnpm/@tiptap_extension-highlight@2.14.0_@tiptap_core@2.14.0_@tiptap_pm@2.14.0_/node_modules/@tiptap/extension-highlight/dist/index.js";
import { menuBarBtnCls as h, menuBarBtnCommonCls as p, menuBarBtnActiveCls as w } from "../styles/menubar-styles.js";
import { useTextEditorUpdateHandler as ye } from "../../editor/hooks/use-editable-text.js";
import { tx as o } from "../../../../style-system/dist/twind.js";
import { insertInEditor as Ce, getEditorNodeFromField as ve } from "../utils/editor-utils.js";
import { useLoopAlias as I, usePageQueries as T } from "../../../../../use-page-data.js";
import { Extension as we } from "../../../../../node_modules/.pnpm/@tiptap_core@2.14.0_@tiptap_pm@2.14.0/node_modules/@tiptap/core/dist/index.js";
import { Portal as Ne } from "../../../../../node_modules/.pnpm/@radix-ui_react-portal@1.1.1_@types_react-dom@18.3.6_@types_react@18.3.3__@types_react@_d91fd04d10d265136bf0d35a7b9375b2/node_modules/@radix-ui/react-portal/dist/index.js";
import { Root as Te, Trigger as Ae, Content as He } from "../../../../../node_modules/.pnpm/@radix-ui_themes@3.1.4_@types_react-dom@18.3.6_@types_react@18.3.3__@types_react@18.3.3_46b1dabc193c5ff5696ee783983c694e/node_modules/@radix-ui/themes/dist/esm/components/popover.js";
import { Root as Le, Text as Se } from "../../../../../node_modules/.pnpm/@radix-ui_themes@3.1.4_@types_react-dom@18.3.6_@types_react@18.3.3__@types_react@18.3.3_46b1dabc193c5ff5696ee783983c694e/node_modules/@radix-ui/themes/dist/esm/components/callout.js";
import { Root as Be, Trigger as Fe, Content as Ee, Label as Me, CheckboxItem as $e, Item as Ie } from "../../../../../node_modules/.pnpm/@radix-ui_themes@3.1.4_@types_react-dom@18.3.6_@types_react@18.3.3__@types_react@18.3.3_46b1dabc193c5ff5696ee783983c694e/node_modules/@radix-ui/themes/dist/esm/components/dropdown-menu.js";
const Re = se.extend({
  addAttributes() {
    return {
      ...this.parent?.(),
      heroSize: {
        default: "hero-size-1",
        parseHTML: (s) => s.getAttribute("class") || "",
        renderHTML: (s) => s.heroSize ? { class: s.heroSize } : {}
      }
    };
  }
}), ze = we.create({
  name: "OverrideEscape",
  addKeyboardShortcuts() {
    return {
      Escape: () => this.editor.commands.blur()
    };
  }
}), Pe = o("dynamic-field");
function $(s) {
  return s?.replace(/{{(\S+)}}/g, (t, a) => `<span data-type="mention" data-id="${a.trim()}" data-label="${a.trim()}" class="${Pe}">${a.trim()}</span>`) || "";
}
const Oe = ae(
  ({
    content: s,
    rawContent: t,
    className: a,
    brickId: n,
    inline: r,
    singleline: l,
    propPath: c,
    noTextAlign: x,
    noTextStrike: L,
    textSizeMode: f = "classic",
    placeholder: R,
    noMenuBar: z,
    dynamic: P = !1,
    onChange: O
  }, D) => {
    const X = ye(n, c, P, r === !0), b = pe(), j = xe(), J = T(), [S, Q] = m(null), [k, U] = m($(s)), [B, Ke] = m($(t)), [y, F] = m(!1), C = I(n), V = r ? X : O, G = J.filter((i) => i.alias === C || !C && i.queryInfo.limit === 1).flatMap((i) => je(i.datasource.schema, i.alias)), K = [
      ee.configure({
        document: l || f === "hero" ? !1 : void 0,
        dropcursor: {
          class: "drop-cursor",
          color: "#FF9900"
        },
        heading: f === "hero" ? !1 : {}
      }),
      q.configure({
        mergeNestedSpanStyles: !1
      }),
      Y.configure({
        placeholder: R ?? "Type your text..."
      }),
      ...f === "hero" ? [M.extend({ content: "heading*" })] : l ? [M.extend({ content: "paragraph" })] : [],
      ...f === "hero" ? [Re] : [],
      ...x ? [] : [
        te.configure({
          types: ["heading", "paragraph"]
        })
      ],
      ke.configure({ multicolor: !0 }),
      ge.configure({
        HTMLAttributes: {
          class: "dynamic-field"
        },
        suggestion: {
          ...be,
          items: ({ query: i }) => G.filter((u) => u.toLowerCase().includes(i.toLowerCase()))
        },
        renderHTML: ({ options: i, node: u }) => {
          const g = u.attrs.label ?? u.attrs.id;
          return [
            "span",
            {
              "data-type": "mention",
              class: o("dynamic-field"),
              "data-label": g,
              "data-id": g
            },
            `${i.suggestion.char}${g}`.replace(i.suggestion.char, "")
          ];
        },
        renderText: ({ options: i, node: u }) => `{{${u.attrs.label ?? u.attrs.id}}}`
      }),
      ze
    ], d = W(
      {
        extensions: K,
        content: k,
        onUpdate: V,
        onBlur: (i) => {
          if (i.event.relatedTarget && !i.event.relatedTarget.classList.contains("tiptap")) {
            console.debug("Editor blur triggered by editor buttons, ignoring", i.event.relatedTarget);
            return;
          }
          b.setIsEditingText(!1), ne(() => {
            U(i.editor.getHTML()), F(!1);
          });
        },
        onFocus: (i) => {
          console.log("Editor focused", i), b.setIsEditingText(n), b.setSelectedBrickId(n), F(!0), !z && setTimeout(() => {
            const u = document.querySelector(`#text-editor-menu-${n}`);
            u && Q(u);
          }, 0);
        },
        immediatelyRender: !0,
        editable: !0,
        editorProps: {
          attributes: {
            class: o(a, l && "singleline")
          }
        }
      },
      [n, j, C]
    );
    return E(() => {
      y ? d.commands.setContent(B, !1) : d.commands.setContent(k, !1);
    }, [y, k, B, d]), E(() => {
      n !== j && d.commands.blur();
    }, [j, n, d]), re(
      D,
      () => ({
        editor: d
      }),
      [d]
    ), /* @__PURE__ */ e.jsxs(e.Fragment, { children: [
      /* @__PURE__ */ e.jsx(_, { autoCorrect: "false", spellCheck: "false", editor: d, className: o("contents") }),
      (y || d.isFocused) && S && /* @__PURE__ */ e.jsx(Ne, { container: S, asChild: !0, children: /* @__PURE__ */ e.jsx(
        De,
        {
          brickId: n,
          editor: d,
          noTextAlign: x,
          noTextStrike: L,
          textSizeMode: f
        }
      ) })
    ] });
  }
);
Oe.displayName = "TextEditor";
const De = ({
  editor: s,
  textSizeMode: t,
  noTextAlign: a,
  noTextStrike: n,
  brickId: r
}) => {
  const l = T().length > 0;
  return /* @__PURE__ */ e.jsxs(e.Fragment, { children: [
    t === "classic" && /* @__PURE__ */ e.jsx(Ve, { editor: s }),
    t === "hero" && /* @__PURE__ */ e.jsx(Ge, { editor: s }),
    !a && /* @__PURE__ */ e.jsx(Xe, { editor: s }),
    /* @__PURE__ */ e.jsx(Ue, { editor: s, noTextStrike: n, textSizeMode: t }),
    l && /* @__PURE__ */ e.jsx(Qe, { editor: s, brickId: r, children: /* @__PURE__ */ e.jsx("button", { type: "button", className: o(h, p), children: /* @__PURE__ */ e.jsx(Z, { className: "w-5 h-5" }) }) })
  ] });
}, A = "h-4 w-4 opacity-60 -mr-2";
function Xe({ editor: s }) {
  const [t, a] = m(
    s.isActive("textAlign") ? s.getAttributes("textAlign").alignment : void 0
  ), n = {
    left: "Left",
    center: "Center",
    right: "Right",
    justify: "Justify"
  };
  return /* @__PURE__ */ e.jsx(
    H,
    {
      items: [
        ...Object.entries(n).map(([r, l]) => ({
          label: l,
          onClick: () => {
            const c = s.commands.setTextAlign(r);
            console.log("alignOk", r, c), a(r);
          },
          type: "checkbox",
          checked: t === r
        }))
      ],
      children: /* @__PURE__ */ e.jsxs("button", { type: "button", className: o(h, p), children: [
        !t || t === "left" ? /* @__PURE__ */ e.jsx(ie, { className: o("w-5 h-5") }) : t === "center" ? /* @__PURE__ */ e.jsx(le, { className: o("w-5 h-5") }) : t === "right" ? /* @__PURE__ */ e.jsx(ce, { className: o("w-5 h-5") }) : /* @__PURE__ */ e.jsx(de, { className: o("w-5 h-5") }),
        /* @__PURE__ */ e.jsx(N, { className: o(A) })
      ] })
    }
  );
}
function Je({ brickId: s, onlyAlias: t, onFieldSelect: a }) {
  const n = T();
  return n.length ? /* @__PURE__ */ e.jsxs("div", { className: "bg-white flex flex-col gap-3", children: [
    /* @__PURE__ */ e.jsx("h3", { className: "text-base font-medium", children: "Insert fields from your queries" }),
    /* @__PURE__ */ e.jsx(Le, { className: "-mx-4 !py-2 !px-3 !rounded-none", children: /* @__PURE__ */ e.jsx(Se, { size: "1", className: o("text-pretty"), children: "Click on a field to insert it into the text box. Fields are inserted as dynamic placeholders, which will be replaced with their actual values when the document is rendered." }) }),
    /* @__PURE__ */ e.jsx("div", { className: "flex flex-col gap-1 pb-2 max-h-[300px] overflow-y-auto scrollbar-thin", children: n.filter((r) => r.alias === t || !t && r.queryInfo.limit === 1).map((r) => /* @__PURE__ */ e.jsxs("div", { className: "flex flex-col gap-1", children: [
      /* @__PURE__ */ e.jsxs("h4", { className: "text-sm font-semibold", children: [
        r.alias,
        " - ",
        r.queryInfo?.label
      ] }),
      /* @__PURE__ */ e.jsx(
        fe,
        {
          prefix: r.alias,
          schema: r.datasource.schema,
          onFieldSelect: a
        },
        r.alias
      )
    ] }, r.alias)) })
  ] }) : /* @__PURE__ */ e.jsx("div", { className: "bg-white min-w-52 min-h-80 flex flex-col gap-4", children: "No database selected in the dynamic parent brick." });
}
function Qe({
  editor: s,
  brickId: t,
  children: a,
  onFieldClick: n
}) {
  const r = I(t), l = (c) => {
    if (n?.(c), !s)
      return;
    const x = ve(c);
    Ce(s, x);
  };
  return /* @__PURE__ */ e.jsxs(Te, { children: [
    /* @__PURE__ */ e.jsx(Ae, { children: a }),
    /* @__PURE__ */ e.jsx(He, { minWidth: "260px", side: "top", align: "start", size: "2", maxHeight: "70dvh", sideOffset: 10, children: /* @__PURE__ */ e.jsx(Je, { onFieldSelect: l, brickId: t, onlyAlias: r }) })
  ] });
}
function Ue({ editor: s, noTextStrike: t, textSizeMode: a }) {
  const n = s.isActive("bold"), r = s.isActive("italic"), l = s.isActive("strike");
  return /* @__PURE__ */ e.jsxs(
    oe,
    {
      className: o("flex !shadow-none divide-x divide-gray-200", !a && "!rounded-l-none"),
      type: "multiple",
      value: [
        n ? "bold" : void 0,
        r ? "italic" : void 0,
        l ? "strike" : void 0
      ].filter(Boolean),
      "aria-label": "Text style",
      children: [
        /* @__PURE__ */ e.jsx(
          v,
          {
            className: o(h, p, "!rounded-l-none", n && w),
            value: "bold",
            onClick: () => s.chain().focus().toggleBold().run(),
            children: /* @__PURE__ */ e.jsx(ue, { className: "w-5 h-5" })
          }
        ),
        /* @__PURE__ */ e.jsx(
          v,
          {
            className: o(h, p, r && w),
            value: "italic",
            onClick: () => s.chain().focus().toggleItalic().run(),
            children: /* @__PURE__ */ e.jsx(me, { className: "w-5 h-5" })
          }
        ),
        !t && /* @__PURE__ */ e.jsx(
          v,
          {
            className: o(h, p, "!rounded-none", l && w),
            value: "strike",
            onClick: () => s.chain().focus().toggleStrike().run(),
            children: /* @__PURE__ */ e.jsx(he, { className: "w-5 h-5" })
          }
        )
      ]
    }
  );
}
function Ve({ editor: s }) {
  const [t, a] = m(
    s.isActive("heading") ? s.getAttributes("heading").level?.toString() : s.isActive("code") ? "code" : "paragraph"
  );
  return /* @__PURE__ */ e.jsx(
    H,
    {
      items: [
        {
          label: "Title 1",
          onClick: () => {
            s.chain().focus().toggleHeading({ level: 1 }).run(), a("1");
          },
          type: "checkbox",
          checked: t === "1"
        },
        {
          label: "Title 2",
          onClick: () => {
            s.chain().focus().toggleHeading({ level: 2 }).run(), a("2");
          },
          type: "checkbox",
          checked: t === "2"
        },
        {
          label: "Title 3",
          onClick: () => {
            s.chain().focus().toggleHeading({ level: 3 }).run(), a("3");
          },
          type: "checkbox",
          checked: t === "3"
        },
        {
          label: "Title 4",
          onClick: () => {
            s.chain().focus().toggleHeading({ level: 4 }).run(), a("4");
          },
          type: "checkbox",
          checked: t === "4"
        },
        {
          label: "Title 5",
          onClick: () => {
            s.chain().focus().toggleHeading({ level: 5 }).run(), a("5");
          },
          type: "checkbox",
          checked: t === "5"
        },
        {
          type: "separator"
        },
        {
          label: "Paragraph",
          onClick: () => {
            s.chain().focus().setParagraph().run(), a("paragraph");
          },
          type: "checkbox",
          checked: t === "paragraph"
        },
        {
          type: "separator"
        },
        {
          label: "Code",
          onClick: () => {
            s.chain().focus().toggleCode().run(), a("code");
          },
          type: "checkbox",
          checked: t === "code"
        }
      ],
      children: /* @__PURE__ */ e.jsxs("button", { type: "button", className: o(h, p, "!px-3"), children: [
        /* @__PURE__ */ e.jsx("span", { className: "text-[0.85rem] font-medium", children: t === "code" ? "Code" : t === "paragraph" ? "Paragraph" : `Title ${t}` }),
        /* @__PURE__ */ e.jsx(N, { className: o(A) })
      ] })
    }
  );
}
function Ge({ editor: s }) {
  const [t, a] = m(s.getAttributes("heading").class?.toString() ?? "hero-size-1"), n = [1, 2, 3, 4, 5], r = ["M", "L", "XL", "2XL", "3XL"], l = {
    "hero-size-1": "M",
    "hero-size-2": "L",
    "hero-size-3": "XL",
    "hero-size-4": "2XL",
    "hero-size-5": "3XL"
  };
  return /* @__PURE__ */ e.jsx(
    H,
    {
      items: n.map((c, x) => ({
        label: `Hero ${r[x]}`,
        onClick: () => {
          s.isActive("heading", { level: 1 }) && s.chain().focus().updateAttributes("heading", { heroSize: `hero-size-${c}` }).run(), a(`hero-size-${c}`);
        },
        type: "checkbox",
        checked: t === `hero-size-${c}`
      })),
      children: /* @__PURE__ */ e.jsxs("button", { type: "button", className: o(h, p), children: [
        /* @__PURE__ */ e.jsxs("span", { className: "text-[0.94rem] font-medium capitalize", children: [
          "Hero ",
          l[t]
        ] }),
        /* @__PURE__ */ e.jsx(N, { className: o(A) })
      ] })
    }
  );
}
function H(s) {
  return /* @__PURE__ */ e.jsxs(Be, { modal: !1, children: [
    /* @__PURE__ */ e.jsx(Fe, { className: "focus:outline-none", id: s.id, children: s.children }),
    /* @__PURE__ */ e.jsx(Ee, { side: "bottom", children: s.items.map(
      (t, a) => t.type === "separator" ? /* @__PURE__ */ e.jsx("div", { className: "my-1.5 h-px bg-black/10" }, a) : t.type === "label" ? /* @__PURE__ */ e.jsx(Me, { children: t.label }, t.label) : t.type === "checkbox" ? /* @__PURE__ */ e.jsx($e, { checked: t.checked, children: /* @__PURE__ */ e.jsxs(
        "button",
        {
          onClick: t.onClick,
          type: "button",
          className: `group flex justify-start items-center text-nowrap rounded-[inherit]
                py-1.5 w-fulldark:text-white/90 text-left data-[focus]:bg-upstart-600 data-[focus]:text-white `,
          children: [
            /* @__PURE__ */ e.jsx("span", { className: "pr-3", children: t.label }),
            t.shortcut && /* @__PURE__ */ e.jsx(
              "kbd",
              {
                className: `ml-auto font-sans text-right text-[smaller] text-black/50 dark:text-dark-300
                    group-hover:text-white/90
                      group-data-[focus]:text-white/70 group-data-[active]:text-white/70`,
                children: t.shortcut
              }
            )
          ]
        }
      ) }, t.label) : /* @__PURE__ */ e.jsx(Ie, { children: /* @__PURE__ */ e.jsxs(
        "button",
        {
          onClick: t.onClick,
          type: "button",
          className: `group flex justify-start items-center text-nowrap rounded-[inherit]
                py-1.5 w-fulldark:text-white/90 text-left data-[focus]:bg-upstart-600 data-[focus]:text-white `,
          children: [
            /* @__PURE__ */ e.jsx("span", { className: "pr-3", children: t.label }),
            t.shortcut && /* @__PURE__ */ e.jsx(
              "kbd",
              {
                className: `ml-auto font-sans text-right text-[smaller] text-black/50 dark:text-dark-300
                    group-hover:text-white/90
                      group-data-[focus]:text-white/70 group-data-[active]:text-white/70`,
                children: t.shortcut
              }
            )
          ]
        }
      ) }, t.label)
    ) })
  ] });
}
export {
  Qe as DatasourceItemButton,
  Oe as default
};
//# sourceMappingURL=TextEditor.js.map
