import { Chat as oe } from "@ai-sdk/react";
import { createExtension as ne, createStore as H, getNodeById as re, UnreachableCaseError as ie, mergeCSSClasses as ae } from "@blocknote/core";
import { ForkYDocExtension as L, ShowSelectionExtension as T, filterSuggestionItems as se, FormattingToolbarExtension as le } from "@blocknote/core/extensions";
import { suggestChanges as ce, revertSuggestions as j, applySuggestions as ue } from "@handlewithcare/prosemirror-suggest-changes";
import { Slice as R, Fragment as q } from "prosemirror-model";
import { Plugin as W, PluginKey as G } from "prosemirror-state";
import { fixTablesKey as me } from "prosemirror-tables";
import { DecorationSet as Z, Decoration as D } from "prosemirror-view";
import { defaultSelectionBuilder as de } from "y-prosemirror";
import { b as fe, s as ge, c as y, a as S } from "./client-B0lU3j7B.js";
import { C as gt, P as pt, S as ht, g as Ct, d as bt, f as vt, h as St, j as yt, m as wt, o as kt, n as It, k as _t, p as xt, i as Mt, e as Lt, l as Tt, t as Pt } from "./client-B0lU3j7B.js";
import { jsxs as pe, jsx as l } from "react/jsx-runtime";
import { useBlockNoteContext as he, useComponentsContext as P, useSuggestionMenuKeyboardHandler as Ce, useBlockNoteEditor as A, useExtension as _, useExtensionState as $, BlockPopover as be } from "@blocknote/react";
import v, { useState as Y, useCallback as I, useMemo as k, useEffect as J } from "react";
import { offset as ve, size as Se, autoUpdate as ye } from "@floating-ui/react";
const N = new G("blocknote-agent-cursor");
function we(e) {
  return new W({
    key: N,
    view: (t) => ({}),
    state: {
      init: () => ({
        selection: void 0
      }),
      apply: (t, r) => {
        const o = t.getMeta("aiAgent");
        return o ? {
          selection: o.selection
        } : {
          selection: void 0
        };
      }
    },
    props: {
      decorations: (t) => {
        const { doc: r } = t, { selection: o } = N.getState(t), i = [];
        if (!o)
          return Z.create(r, []);
        i.push(
          D.widget(o.head, () => ke(e), {
            key: "agent-cursor",
            side: 10
          })
        );
        const m = Math.min(o.anchor, o.head), f = Math.max(o.anchor, o.head);
        return i.push(
          D.inline(m, f, de(e), {
            inclusiveEnd: !0,
            inclusiveStart: !1
          })
        ), Z.create(r, i);
      }
    }
  });
}
const ke = (e) => {
  const t = document.createElement("span");
  t.classList.add("bn-collaboration-cursor__base"), t.setAttribute("data-active", "true");
  const r = document.createElement("span");
  r.setAttribute("contentedEditable", "false"), r.classList.add("bn-collaboration-cursor__caret"), r.setAttribute("style", `background-color: ${e.color}`);
  const o = document.createElement("span");
  return o.classList.add("bn-collaboration-cursor__label"), o.setAttribute("style", `background-color: ${e.color}`), o.insertBefore(document.createTextNode(e.name), null), r.insertBefore(o, null), t.insertBefore(document.createTextNode("⁠"), null), t.insertBefore(r, null), t.insertBefore(document.createTextNode("⁠"), null), t;
}, Ie = new G("blocknote-ai-plugin"), b = ne(
  ({
    editor: e,
    options: t
  }) => {
    const r = H(t ?? {}), o = H({
      aiMenuState: "closed"
    });
    let i, m = !1;
    const f = ce();
    return f.props.decorations = void 0, {
      key: "ai",
      options: r,
      store: o,
      mount({ signal: n }) {
        let a = !1;
        document.addEventListener(
          "scroll",
          () => {
            a && (m = !1), a = !0;
          },
          {
            capture: !0,
            signal: n
          }
        ), document.addEventListener(
          "scrollend",
          () => {
            a = !1;
          },
          {
            capture: !0,
            signal: n
          }
        );
      },
      prosemirrorPlugins: [
        new W({
          key: Ie,
          filterTransaction: (n) => {
            var s;
            const a = o.state.aiMenuState;
            return !(a !== "closed" && a.status === "ai-writing" && (s = n.getMeta(me)) != null && s.fixTables);
          }
        }),
        f,
        we(
          (t == null ? void 0 : t.agentCursor) || { name: "AI", color: "#8bc6ff" }
        )
      ],
      /**
       * Open the AI menu at a specific block
       */
      openAIMenuAtBlock(n) {
        var s, c;
        (s = e.getExtension(T)) == null || s.showSelection(!0), e.isEditable = !1, o.setState({
          aiMenuState: {
            blockId: n,
            status: "user-input"
          }
        });
        const a = (c = e.domElement) == null ? void 0 : c.querySelector(
          `[data-node-type="blockContainer"][data-id="${n}"]`
        );
        a == null || a.scrollIntoView({ block: "center" });
      },
      /**
       * Close the AI menu
       */
      closeAIMenu() {
        var n;
        o.setState({
          aiMenuState: "closed"
        }), i = void 0, (n = e.getExtension(T)) == null || n.showSelection(!1), e.isEditable = !0, e.focus();
      },
      /**
       * Accept the changes made by the LLM
       */
      acceptChanges() {
        var a;
        const n = e.prosemirrorState.doc;
        e.exec((s, c) => j(s, (g) => {
          c == null || c(g.setMeta("addToHistory", !1));
        })), e.exec((s, c) => {
          const g = s.tr;
          g.replace(
            0,
            g.doc.content.size,
            new R(q.from(n), 0, 0)
          );
          const p = s.apply(g);
          return ue(p, (d) => {
            c == null || c(
              g.replace(
                0,
                g.doc.content.size,
                new R(q.from(d.doc), 0, 0)
              )
            );
          });
        }), (a = e.getExtension(L)) == null || a.merge({ keepChanges: !0 }), this.closeAIMenu();
      },
      /**
       * Reject the changes made by the LLM
       */
      rejectChanges() {
        var n;
        e.exec((a, s) => j(a, (c) => {
          s == null || s(c.setMeta("addToHistory", !1));
        })), (n = e.getExtension(L)) == null || n.merge({ keepChanges: !1 }), this.closeAIMenu();
      },
      /**
       * Abort the current LLM request.
       *
       * This will stop the ongoing request and revert any changes made by the AI.
       * Only valid when there is an active AI request in progress.
       */
      async abort(n) {
        const { aiMenuState: a } = o.state;
        if (a === "closed" || !i || a.status !== "thinking" && a.status !== "ai-writing")
          return;
        const s = i.chat;
        i.abortController.abort(n), await s.stop();
      },
      /**
       * Retry the previous LLM call.
       *
       * Only valid if the current status is "error"
       */
      async retry() {
        const { aiMenuState: n } = o.state;
        if (n === "closed" || n.status !== "error" || !i)
          throw new Error(
            "retry() is only valid when a previous response failed"
          );
        return (i == null ? void 0 : i.chat.status) === "error" ? this.invokeAI({
          ...i.previousRequestOptions,
          userPrompt: "An error occured in the previous request. Please retry to accomplish the last user prompt."
        }) : this.invokeAI({
          ...i.previousRequestOptions,
          userPrompt: "An error occured while executing the previous tool call. Please retry to accomplish the last user prompt."
        });
      },
      /**
       * Update the status of a call to an LLM
       *
       * @warning This method should usually only be used for advanced use-cases
       * if you want to implement how an LLM call is executed. Usually, you should
       * use {@link executeLLMRequest} instead which will handle the status updates for you.
       */
      setAIResponseStatus(n) {
        var s;
        const a = o.state.aiMenuState;
        if (a !== "closed")
          if (n === "ai-writing" && ((s = e.getExtension(T)) == null || s.showSelection(!1)), typeof n == "object") {
            if (n.status !== "error")
              throw new ie(n.status);
            this.store.setState({
              aiMenuState: {
                status: n.status,
                error: n.error,
                blockId: a.blockId
              }
            });
          } else
            this.store.setState({
              aiMenuState: {
                status: n,
                blockId: a.blockId
              }
            });
      },
      /**
       * @deprecated Use {@link invokeAI} instead
       */
      async callLLM(n) {
        return this.invokeAI(n);
      },
      /**
       * Execute a call to an LLM and apply the result to the editor
       */
      async invokeAI(n) {
        var a, s, c, g;
        this.setAIResponseStatus("thinking"), (a = e.getExtension(L)) == null || a.fork();
        try {
          const p = new AbortController();
          i ? (i.previousRequestOptions = n, i.abortController = p) : i = {
            previousRequestOptions: n,
            chat: ((s = n.chatProvider) == null ? void 0 : s.call(n)) || ((g = (c = this.options.state).chatProvider) == null ? void 0 : g.call(c)) || new oe({
              sendAutomaticallyWhen: () => !1,
              transport: n.transport || this.options.state.transport
            }),
            abortController: p
          };
          const d = i.chat;
          n = {
            ...r.state,
            ...n
          };
          const u = await fe({
            editor: e,
            useSelection: n.useSelection,
            deleteEmptyCursorBlock: n.deleteEmptyCursorBlock,
            streamToolsProvider: n.streamToolsProvider ?? this.options.state.streamToolsProvider,
            documentStateBuilder: n.documentStateBuilder ?? this.options.state.documentStateBuilder,
            onBlockUpdated: (B) => {
              const O = o.state.aiMenuState, z = O === "closed" ? void 0 : O;
              if (!z || z.status !== "ai-writing")
                return;
              const V = re(
                B,
                e.prosemirrorState.doc
              );
              V && (o.setState({
                aiMenuState: {
                  blockId: B,
                  status: "ai-writing"
                }
              }), m && e.prosemirrorView.domAtPos(
                V.posBeforeNode + 1
              ).node.scrollIntoView({
                block: "center"
              }));
            },
            onStart: () => {
              m = !0, this.setAIResponseStatus("ai-writing"), u.emptyCursorBlockToDelete && u.editor.getBlock(u.emptyCursorBlockToDelete) && u.editor.removeBlocks([
                u.emptyCursorBlockToDelete
              ]);
            }
          }), C = await ge(
            d,
            u,
            {
              role: "user",
              parts: [
                {
                  type: "text",
                  text: n.userPrompt
                }
              ]
            },
            n.chatRequestOptions || this.options.state.chatRequestOptions,
            i.abortController.signal
          );
          C.ok && d.status !== "error" || p.signal.aborted ? this.setAIResponseStatus("user-reviewing") : (console.warn("Error calling LLM", {
            result: C,
            chatStatus: d.status,
            chatError: d.error
          }), this.setAIResponseStatus({
            status: "error",
            error: C.ok ? d.error : C.error
          }));
        } catch (p) {
          this.setAIResponseStatus({
            status: "error",
            error: p
          }), console.error(
            "Unexpected error calling LLM",
            p,
            i == null ? void 0 : i.chat.messages
          );
        }
      }
    };
  }
);
var Q = {
  color: void 0,
  size: void 0,
  className: void 0,
  style: void 0,
  attr: void 0
}, F = v.createContext && /* @__PURE__ */ v.createContext(Q), _e = ["attr", "size", "title"];
function xe(e, t) {
  if (e == null) return {};
  var r = Me(e, t), o, i;
  if (Object.getOwnPropertySymbols) {
    var m = Object.getOwnPropertySymbols(e);
    for (i = 0; i < m.length; i++)
      o = m[i], !(t.indexOf(o) >= 0) && Object.prototype.propertyIsEnumerable.call(e, o) && (r[o] = e[o]);
  }
  return r;
}
function Me(e, t) {
  if (e == null) return {};
  var r = {};
  for (var o in e)
    if (Object.prototype.hasOwnProperty.call(e, o)) {
      if (t.indexOf(o) >= 0) continue;
      r[o] = e[o];
    }
  return r;
}
function x() {
  return x = Object.assign ? Object.assign.bind() : function(e) {
    for (var t = 1; t < arguments.length; t++) {
      var r = arguments[t];
      for (var o in r)
        Object.prototype.hasOwnProperty.call(r, o) && (e[o] = r[o]);
    }
    return e;
  }, x.apply(this, arguments);
}
function U(e, t) {
  var r = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    t && (o = o.filter(function(i) {
      return Object.getOwnPropertyDescriptor(e, i).enumerable;
    })), r.push.apply(r, o);
  }
  return r;
}
function M(e) {
  for (var t = 1; t < arguments.length; t++) {
    var r = arguments[t] != null ? arguments[t] : {};
    t % 2 ? U(Object(r), !0).forEach(function(o) {
      Le(e, o, r[o]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(r)) : U(Object(r)).forEach(function(o) {
      Object.defineProperty(e, o, Object.getOwnPropertyDescriptor(r, o));
    });
  }
  return e;
}
function Le(e, t, r) {
  return t = Te(t), t in e ? Object.defineProperty(e, t, { value: r, enumerable: !0, configurable: !0, writable: !0 }) : e[t] = r, e;
}
function Te(e) {
  var t = Pe(e, "string");
  return typeof t == "symbol" ? t : t + "";
}
function Pe(e, t) {
  if (typeof e != "object" || !e) return e;
  var r = e[Symbol.toPrimitive];
  if (r !== void 0) {
    var o = r.call(e, t);
    if (typeof o != "object") return o;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (t === "string" ? String : Number)(e);
}
function X(e) {
  return e && e.map((t, r) => /* @__PURE__ */ v.createElement(t.tag, M({
    key: r
  }, t.attr), X(t.child)));
}
function h(e) {
  return (t) => /* @__PURE__ */ v.createElement(Ae, x({
    attr: M({}, e.attr)
  }, t), X(e.child));
}
function Ae(e) {
  var t = (r) => {
    var {
      attr: o,
      size: i,
      title: m
    } = e, f = xe(e, _e), n = i || r.size || "1em", a;
    return r.className && (a = r.className), e.className && (a = (a ? a + " " : "") + e.className), /* @__PURE__ */ v.createElement("svg", x({
      stroke: "currentColor",
      fill: "currentColor",
      strokeWidth: "0"
    }, r.attr, o, f, {
      className: a,
      style: M(M({
        color: e.color || r.color
      }, r.style), e.style),
      height: n,
      width: n,
      xmlns: "http://www.w3.org/2000/svg"
    }), m && /* @__PURE__ */ v.createElement("title", null, m), e.children);
  };
  return F !== void 0 ? /* @__PURE__ */ v.createElement(F.Consumer, null, (r) => t(r)) : t(Q);
}
function ee(e) {
  return h({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M8 7V11L2 6L8 1V5H13C17.4183 5 21 8.58172 21 13C21 17.4183 17.4183 21 13 21H4V19H13C16.3137 19 19 16.3137 19 13C19 9.68629 16.3137 7 13 7H8Z" }, child: [] }] })(e);
}
function K(e) {
  return h({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M17.8492 11.6983L17.1421 10.9912L7.24264 20.8907H3V16.648L14.3137 5.33432L19.9706 10.9912C20.3611 11.3817 20.3611 12.0149 19.9706 12.4054L12.8995 19.4765L11.4853 18.0622L17.8492 11.6983ZM15.7279 9.57696L14.3137 8.16274L5 17.4765V18.8907H6.41421L15.7279 9.57696ZM18.5563 2.50589L21.3848 5.33432C21.7753 5.72484 21.7753 6.35801 21.3848 6.74853L19.9706 8.16274L15.7279 3.9201L17.1421 2.50589C17.5327 2.11537 18.1658 2.11537 18.5563 2.50589Z" }, child: [] }] })(e);
}
function Ee(e) {
  return h({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M15.1986 9.94447C14.7649 9.5337 14.4859 8.98613 14.4085 8.39384L14.0056 5.31138L11.275 6.79724C10.7503 7.08274 10.1433 7.17888 9.55608 7.06948L6.49998 6.50015L7.06931 9.55625C7.17871 10.1435 7.08257 10.7505 6.79707 11.2751L5.31121 14.0057L8.39367 14.4086C8.98596 14.4861 9.53353 14.7651 9.94431 15.1987L12.0821 17.4557L13.4178 14.6486C13.6745 14.1092 14.109 13.6747 14.6484 13.418L17.4555 12.0823L15.1986 9.94447ZM15.2238 15.5079L13.0111 20.1581C12.8687 20.4573 12.5107 20.5844 12.2115 20.442C12.1448 20.4103 12.0845 20.3665 12.0337 20.3129L8.49229 16.5741C8.39749 16.474 8.27113 16.4096 8.13445 16.3918L3.02816 15.7243C2.69958 15.6814 2.46804 15.3802 2.51099 15.0516C2.52056 14.9784 2.54359 14.9075 2.5789 14.8426L5.04031 10.3192C5.1062 10.1981 5.12839 10.058 5.10314 9.92253L4.16 4.85991C4.09931 4.53414 4.3142 4.22086 4.63997 4.16017C4.7126 4.14664 4.78711 4.14664 4.85974 4.16017L9.92237 5.10331C10.0579 5.12855 10.198 5.10637 10.319 5.04048L14.8424 2.57907C15.1335 2.42068 15.4979 2.52825 15.6562 2.81931C15.6916 2.88421 15.7146 2.95507 15.7241 3.02833L16.3916 8.13462C16.4095 8.2713 16.4739 8.39766 16.5739 8.49245L20.3127 12.0338C20.5533 12.2617 20.5636 12.6415 20.3357 12.8821C20.2849 12.9357 20.2246 12.9795 20.1579 13.0112L15.5078 15.224C15.3833 15.2832 15.283 15.3835 15.2238 15.5079ZM16.0206 17.435L17.4348 16.0208L21.6775 20.2634L20.2633 21.6776L16.0206 17.435Z" }, child: [] }] })(e);
}
function Be(e) {
  return h({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M8.00008 6V9H5.00008V6H8.00008ZM3.00008 4V11H10.0001V4H3.00008ZM13.0001 4H21.0001V6H13.0001V4ZM13.0001 11H21.0001V13H13.0001V11ZM13.0001 18H21.0001V20H13.0001V18ZM10.7072 16.2071L9.29297 14.7929L6.00008 18.0858L4.20718 16.2929L2.79297 17.7071L6.00008 20.9142L10.7072 16.2071Z" }, child: [] }] })(e);
}
function Oe(e) {
  return h({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M15 18H16.5C17.8807 18 19 16.8807 19 15.5C19 14.1193 17.8807 13 16.5 13H3V11H16.5C18.9853 11 21 13.0147 21 15.5C21 17.9853 18.9853 20 16.5 20H15V22L11 19L15 16V18ZM3 4H21V6H3V4ZM9 18V20H3V18H9Z" }, child: [] }] })(e);
}
function ze(e) {
  return h({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M13 6V21H11V6H5V4H19V6H13Z" }, child: [] }] })(e);
}
function Ve(e) {
  return h({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M6.23509 6.45329C4.85101 7.89148 4 9.84636 4 12C4 16.4183 7.58172 20 12 20C13.0808 20 14.1116 19.7857 15.0521 19.3972C15.1671 18.6467 14.9148 17.9266 14.8116 17.6746C14.582 17.115 13.8241 16.1582 12.5589 14.8308C12.2212 14.4758 12.2429 14.2035 12.3636 13.3943L12.3775 13.3029C12.4595 12.7486 12.5971 12.4209 14.4622 12.1248C15.4097 11.9746 15.6589 12.3533 16.0043 12.8777C16.0425 12.9358 16.0807 12.9928 16.1198 13.0499C16.4479 13.5297 16.691 13.6394 17.0582 13.8064C17.2227 13.881 17.428 13.9751 17.7031 14.1314C18.3551 14.504 18.3551 14.9247 18.3551 15.8472V15.9518C18.3551 16.3434 18.3168 16.6872 18.2566 16.9859C19.3478 15.6185 20 13.8854 20 12C20 8.70089 18.003 5.8682 15.1519 4.64482C14.5987 5.01813 13.8398 5.54726 13.575 5.91C13.4396 6.09538 13.2482 7.04166 12.6257 7.11976C12.4626 7.14023 12.2438 7.12589 12.012 7.11097C11.3905 7.07058 10.5402 7.01606 10.268 7.75495C10.0952 8.2232 10.0648 9.49445 10.6239 10.1543C10.7134 10.2597 10.7307 10.4547 10.6699 10.6735C10.59 10.9608 10.4286 11.1356 10.3783 11.1717C10.2819 11.1163 10.0896 10.8931 9.95938 10.7412C9.64554 10.3765 9.25405 9.92233 8.74797 9.78176C8.56395 9.73083 8.36166 9.68867 8.16548 9.64736C7.6164 9.53227 6.99443 9.40134 6.84992 9.09302C6.74442 8.8672 6.74488 8.55621 6.74529 8.22764C6.74529 7.8112 6.74529 7.34029 6.54129 6.88256C6.46246 6.70541 6.35689 6.56446 6.23509 6.45329ZM12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22Z" }, child: [] }] })(e);
}
function He(e) {
  return h({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M9.9997 15.1709L19.1921 5.97852L20.6063 7.39273L9.9997 17.9993L3.63574 11.6354L5.04996 10.2212L9.9997 15.1709Z" }, child: [] }] })(e);
}
function je(e) {
  return h({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M9.9997 15.1709L19.1921 5.97852L20.6063 7.39273L9.9997 17.9993L3.63574 11.6354L5.04996 10.2212L9.9997 15.1709Z" }, child: [] }] })(e);
}
function Re(e) {
  return h({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M12 4C9.4095 4 7.10606 5.23053 5.64274 7.14274L8 9.5H2V3.5L4.21863 5.71863C6.05061 3.452 8.85558 2 12 2 17.5228 2 22 6.47715 22 12H20C20 7.58172 16.4183 4 12 4ZM4 12C4 16.4183 7.58172 20 12 20 14.5905 20 16.894 18.7695 18.3573 16.8573L16 14.5 22 14.5V20.5L19.7814 18.2814C17.9494 20.548 15.1444 22 12 22 6.47715 22 2 17.5228 2 12H4Z" }, child: [] }] })(e);
}
function E(e) {
  return h({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M17.0007 1.20825 18.3195 3.68108 20.7923 4.99992 18.3195 6.31876 17.0007 8.79159 15.6818 6.31876 13.209 4.99992 15.6818 3.68108 17.0007 1.20825ZM8.00065 4.33325 10.6673 9.33325 15.6673 11.9999 10.6673 14.6666 8.00065 19.6666 5.33398 14.6666.333984 11.9999 5.33398 9.33325 8.00065 4.33325ZM19.6673 16.3333 18.0007 13.2083 16.334 16.3333 13.209 17.9999 16.334 19.6666 18.0007 22.7916 19.6673 19.6666 22.7923 17.9999 19.6673 16.3333Z" }, child: [] }] })(e);
}
function te() {
  const e = he();
  return y(e.editor);
}
const qe = (e) => {
  const t = P(), { onManualPromptSubmit: r, promptText: o, onPromptTextChange: i } = e, [m, f] = Y(""), n = o || m, a = I(
    async (u) => {
      u.key === "Enter" && r(n);
    },
    [n, r]
  ), s = I(
    (u) => {
      const C = u.currentTarget.value;
      i && i(C), o === void 0 && f(C);
    },
    [i, f, o]
  ), c = k(() => se(e.items, n), [n, e.items]), { selectedIndex: g, setSelectedIndex: p, handler: d } = Ce(c, (u) => u.onItemClick()), w = I(
    (u) => {
      u.key === "Enter" ? c.length > 0 ? d(u) : a(u) : d(u);
    },
    [a, d, c.length]
  );
  return J(() => {
    p(0);
  }, [n, p]), /* @__PURE__ */ pe("div", { className: "bn-combobox", children: [
    /* @__PURE__ */ l(t.Generic.Form.Root, { children: /* @__PURE__ */ l(
      t.Generic.Form.TextInput,
      {
        className: "bn-combobox-input",
        name: "ai-prompt",
        variant: "large",
        icon: e.icon,
        value: n || "",
        autoFocus: !0,
        placeholder: e.placeholder,
        disabled: e.disabled,
        onKeyDown: w,
        onChange: s,
        autoComplete: "off",
        rightSection: e.rightSection
      },
      "input-" + e.disabled
    ) }),
    /* @__PURE__ */ l(
      t.SuggestionMenu.Root,
      {
        className: "bn-combobox-items",
        id: "ai-suggestion-menu",
        children: c.map((u, C) => /* @__PURE__ */ l(
          t.SuggestionMenu.Item,
          {
            className: ae(
              "bn-suggestion-menu-item",
              u.size === "small" ? "bn-suggestion-menu-item-small" : ""
            ),
            id: `bn-suggestion-menu-item-${C}`,
            isSelected: C === g,
            onClick: u.onItemClick,
            item: u
          },
          u.title
        ))
      }
    )
  ] });
};
function Ze(e) {
  const t = y(e), r = e.getExtension(b);
  return r ? [
    {
      key: "continue_writing",
      title: t.ai_default_commands.continue_writing.title,
      aliases: t.ai_default_commands.continue_writing.aliases,
      icon: /* @__PURE__ */ l(K, { size: 18 }),
      onItemClick: async () => {
        await r.invokeAI({
          userPrompt: "Continue writing at the current cursor position related to the previous text. Add multiple blocks if needed. If the document looks like a template / draft, follow the template. Be extensive if needed.",
          // By default, LLM will be able to add / update / delete blocks. For "continue writing", we only want to allow adding new blocks.
          streamToolsProvider: S.html.getStreamToolsProvider({
            defaultStreamTools: {
              add: !0,
              delete: !1,
              update: !1
            }
          })
        });
      },
      size: "small"
    },
    {
      key: "summarize",
      title: t.ai_default_commands.summarize.title,
      aliases: t.ai_default_commands.summarize.aliases,
      icon: /* @__PURE__ */ l(Oe, { size: 18 }),
      onItemClick: async () => {
        await r.invokeAI({
          userPrompt: "Summarize",
          // By default, LLM will be able to add / update / delete blocks. For "summarize", we only want to allow adding new blocks.
          streamToolsProvider: S.html.getStreamToolsProvider({
            defaultStreamTools: {
              add: !0,
              delete: !1,
              update: !1
            }
          })
        });
      },
      size: "small"
    },
    {
      key: "action_items",
      title: t.ai_default_commands.add_action_items.title,
      aliases: t.ai_default_commands.add_action_items.aliases,
      icon: /* @__PURE__ */ l(Be, { size: 18 }),
      onItemClick: async () => {
        await r.invokeAI({
          userPrompt: "Add action items",
          // By default, LLM will be able to add / update / delete blocks. For "summarize", we only want to allow adding new blocks.
          streamToolsProvider: S.html.getStreamToolsProvider({
            defaultStreamTools: {
              add: !0,
              delete: !1,
              update: !1
            }
          })
        });
      },
      size: "small"
    },
    {
      key: "write_anything",
      title: t.ai_default_commands.write_anything.title,
      aliases: t.ai_default_commands.write_anything.aliases,
      icon: /* @__PURE__ */ l(K, { size: 18 }),
      onItemClick: (o) => {
        o(t.ai_default_commands.write_anything.prompt_placeholder);
      },
      size: "small"
    }
  ] : [];
}
function De(e) {
  const t = y(e), r = e.getExtension(b);
  return r ? [
    {
      key: "improve_writing",
      title: t.ai_default_commands.improve_writing.title,
      aliases: t.ai_default_commands.improve_writing.aliases,
      icon: /* @__PURE__ */ l(ze, { size: 18 }),
      onItemClick: async () => {
        await r.invokeAI({
          useSelection: !0,
          userPrompt: "Improve writing",
          // By default, LLM will be able to add / update / delete blocks. For "summarize", we only want to allow adding new blocks.
          streamToolsProvider: S.html.getStreamToolsProvider({
            defaultStreamTools: {
              add: !1,
              delete: !1,
              update: !0
            }
          })
        });
      },
      size: "small"
    },
    {
      key: "fix_spelling",
      title: t.ai_default_commands.fix_spelling.title,
      aliases: t.ai_default_commands.fix_spelling.aliases,
      icon: /* @__PURE__ */ l(je, { size: 18 }),
      onItemClick: async () => {
        await r.invokeAI({
          useSelection: !0,
          userPrompt: "Fix spelling",
          // By default, LLM will be able to add / update / delete blocks. For "summarize", we only want to allow adding new blocks.
          streamToolsProvider: S.html.getStreamToolsProvider({
            defaultStreamTools: {
              add: !1,
              delete: !1,
              update: !0
            }
          })
        });
      },
      size: "small"
    },
    {
      key: "translate",
      title: t.ai_default_commands.translate.title,
      aliases: t.ai_default_commands.translate.aliases,
      icon: /* @__PURE__ */ l(Ve, { size: 18 }),
      onItemClick: (o) => {
        o(t.ai_default_commands.translate.prompt_placeholder);
      },
      size: "small"
    },
    {
      key: "simplify",
      title: t.ai_default_commands.simplify.title,
      aliases: t.ai_default_commands.simplify.aliases,
      icon: /* @__PURE__ */ l(Ee, { size: 18 }),
      onItemClick: async () => {
        await r.invokeAI({
          useSelection: !0,
          userPrompt: "Simplify",
          // By default, LLM will be able to add / update / delete blocks. For "summarize", we only want to allow adding new blocks.
          streamToolsProvider: S.html.getStreamToolsProvider({
            defaultStreamTools: {
              add: !1,
              delete: !1,
              update: !0
            }
          })
        });
      },
      size: "small"
    }
  ] : [];
}
function Ne(e) {
  const t = y(e), r = e.getExtension(b);
  return r ? [
    {
      key: "accept",
      title: t.ai_menu.actions.accept.title,
      aliases: t.ai_menu.actions.accept.aliases,
      icon: /* @__PURE__ */ l(He, { size: 18 }),
      onItemClick: () => {
        r.acceptChanges();
      },
      size: "small"
    },
    {
      key: "revert",
      title: t.ai_menu.actions.revert.title,
      aliases: t.ai_menu.actions.revert.aliases,
      icon: /* @__PURE__ */ l(ee, { size: 18 }),
      onItemClick: () => {
        r.rejectChanges();
      },
      size: "small"
    }
  ] : [];
}
function Fe(e) {
  const t = y(e), r = e.getExtension(b);
  return r ? [
    {
      key: "retry",
      title: t.ai_menu.actions.retry.title,
      aliases: t.ai_menu.actions.retry.aliases,
      icon: /* @__PURE__ */ l(Re, { size: 18 }),
      onItemClick: async () => {
        await r.retry();
      },
      size: "small"
    },
    {
      key: "cancel",
      title: t.ai_menu.actions.cancel.title,
      aliases: t.ai_menu.actions.cancel.aliases,
      icon: /* @__PURE__ */ l(ee, { size: 18 }),
      onItemClick: () => {
        r.rejectChanges();
      },
      size: "small"
    }
  ] : [];
}
function Ue(e, t) {
  return t === "user-input" ? e.getSelection() ? De(e) : Ze(e) : t === "user-reviewing" ? Ne(e) : t === "error" ? Fe(e) : [];
}
const Ke = (e) => {
  const t = A(), [r, o] = Y(""), i = te(), m = P(), f = _(b), n = $(b, {
    selector: (d) => d.aiMenuState !== "closed" ? d.aiMenuState.status : "closed"
  }), { items: a } = e, s = k(() => {
    let d = [];
    return a ? d = a(t, n) : d = Ue(t, n), d.map((w) => ({
      ...w,
      onItemClick: () => {
        w.onItemClick(o);
      }
    }));
  }, [a, n, t]), c = I(
    async (d) => {
      await f.invokeAI({
        userPrompt: d,
        useSelection: t.getSelection() !== void 0
      });
    },
    [f, t]
  );
  J(() => {
    (n === "ai-writing" || n === "user-reviewing" || n === "error") && o("");
  }, [n]);
  const g = k(() => n === "thinking" ? i.ai_menu.status.thinking : n === "ai-writing" ? i.ai_menu.status.editing : n === "error" ? i.ai_menu.status.error : i.ai_menu.input_placeholder, [n, i]), p = k(() => {
    if (n === "thinking" || n === "ai-writing")
      return /* @__PURE__ */ l(
        m.SuggestionMenu.Loader,
        {
          className: "bn-suggestion-menu-loader bn-combobox-right-section"
        }
      );
    if (n === "error")
      return /* @__PURE__ */ l("div", { className: "bn-combobox-right-section bn-combobox-error", children: /* @__PURE__ */ l(
        "svg",
        {
          xmlns: "http://www.w3.org/2000/svg",
          height: "1em",
          viewBox: "0 -960 960 960",
          width: "1em",
          fill: "currentColor",
          children: /* @__PURE__ */ l("path", { d: "M480-280q17 0 28.5-11.5T520-320q0-17-11.5-28.5T480-360q-17 0-28.5 11.5T440-320q0 17 11.5 28.5T480-280Zm0-160q17 0 28.5-11.5T520-480v-160q0-17-11.5-28.5T480-680q-17 0-28.5 11.5T440-640v160q0 17 11.5 28.5T480-440Zm0 360q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0-80q134 0 227-93t93-227q0-134-93-227t-227-93q-134 0-227 93t-93 227q0 134 93 227t227 93Zm0-320Z" })
        }
      ) });
  }, [m, n]);
  return /* @__PURE__ */ l(
    qe,
    {
      onManualPromptSubmit: e.onManualPromptSubmit || c,
      items: s,
      promptText: r,
      onPromptTextChange: o,
      placeholder: g,
      disabled: n === "thinking" || n === "ai-writing",
      icon: /* @__PURE__ */ l("div", { className: "bn-combobox-icon", children: /* @__PURE__ */ l(E, {}) }),
      rightSection: p
    }
  );
}, ct = (e) => {
  const t = A(), r = _(b), o = $(b, {
    editor: t,
    selector: (n) => n.aiMenuState
  }), i = o === "closed" ? void 0 : o.blockId, m = k(
    () => ({
      useFloatingOptions: {
        open: o !== "closed",
        placement: "bottom",
        middleware: [
          ve(10),
          // flip(),
          Se({
            apply({ rects: n, elements: a }) {
              Object.assign(a.floating.style, {
                width: `${n.reference.width}px`
              });
            }
          })
        ],
        onOpenChange: (n) => {
          n || o === "closed" || (o.status === "user-input" ? r.closeAIMenu() : (o.status === "user-reviewing" || o.status === "error") && r.rejectChanges());
        },
        whileElementsMounted(n, a, s) {
          return ye(n, a, s, {
            animationFrame: !0
          });
        }
      },
      useDismissProps: {
        enabled: o === "closed" || o.status === "user-input",
        // We should just be able to set `referencePress: true` instead of
        // using this listener, but this doesn't seem to trigger.
        // (probably because we don't assign the referenceProps to the reference element)
        outsidePress: (n) => {
          if (n.target instanceof Element) {
            const a = n.target.closest(".bn-block");
            a && a.getAttribute("data-id") === i && r.closeAIMenu();
          }
          return !0;
        }
      },
      elementProps: {
        style: {
          zIndex: 100
        }
      },
      ...e.floatingUIOptions
    }),
    [r, o, i, e.floatingUIOptions]
  ), f = e.aiMenu || Ke;
  return /* @__PURE__ */ l(be, { blockId: i, ...m, children: o !== "closed" && /* @__PURE__ */ l(f, {}) });
}, ut = () => {
  const e = te(), t = P(), r = A(), o = _(b), i = _(le), m = () => {
    const f = r.getSelection();
    if (!f)
      throw new Error("No selection");
    const n = f.blocks[f.blocks.length - 1].id;
    o.openAIMenuAtBlock(n), i.store.setState(!1);
  };
  return r.isEditable ? /* @__PURE__ */ l(
    t.Generic.Toolbar.Button,
    {
      className: "bn-button",
      label: e.formatting_toolbar.ai.tooltip,
      mainTooltip: e.formatting_toolbar.ai.tooltip,
      icon: /* @__PURE__ */ l(E, {}),
      onClick: m
    }
  ) : null;
}, We = {
  AI: E
};
function mt(e) {
  const t = e.getExtension(b);
  return t ? [
    {
      key: "ai",
      onItemClick: () => {
        const o = e.getTextCursorPosition();
        o.block.content && Array.isArray(o.block.content) && // isarray check not ideal
        o.block.content.length === 0 && o.prevBlock ? t.openAIMenuAtBlock(o.prevBlock.id) : t.openAIMenuAtBlock(o.block.id);
      },
      ...y(e).slash_menu.ai,
      icon: /* @__PURE__ */ l(We.AI, {})
    }
  ] : [];
}
export {
  b as AIExtension,
  Ke as AIMenu,
  ct as AIMenuController,
  ut as AIToolbarButton,
  gt as ClientSideTransport,
  pt as PROVIDER_OVERRIDES,
  qe as PromptSuggestionMenu,
  ht as StreamToolExecutor,
  Ct as _getApplySuggestionsTr,
  S as aiDocumentFormats,
  fe as buildAIRequest,
  bt as createStreamToolsArraySchema,
  vt as fetchViaProxy,
  y as getAIDictionary,
  mt as getAISlashMenuItems,
  Ue as getDefaultAIMenuItems,
  St as getProviderOverrides,
  yt as injectDocumentStateMessages,
  wt as makeDocumentStateBuilder,
  kt as objectAsToolCallInUIMessageStream,
  It as objectStreamToOperationsResult,
  _t as partialObjectStreamAsToolCallInUIMessageStream,
  xt as promptHelpers,
  ge as sendMessageWithAIRequest,
  Mt as setupToolCallStreaming,
  Lt as streamToolsToToolSet,
  Tt as toolDefinitionsToToolSet,
  Pt as toolSetToToolDefinitions,
  te as useAIDictionary
};
//# sourceMappingURL=blocknote-xl-ai.js.map
