import { jsx, jsxs, Fragment } from "react/jsx-runtime";
import { bk as useLoopAlias, am as RiBracesLine, m as useDraftHelpers } from "./use-page-data.BgY0vKG4.js";
import * as React from "react";
import { useRef, Suspense, lazy } from "react";
import { a as useControllableState, c as createContextScope, u as useComposedRefs, P as Primitive, b as composeEventHandlers, g as createSlot, y } from "./index.W70dzubm.js";
import { t, c as o$1, v as v$1 } from "./radius.prop.DrZ_kW2M.js";
import { h as hideOthers, R as ReactRemoveScroll, u as useFocusGuards, F as FocusScope, a } from "./icons.DU44nXm4.js";
import { n, e } from "./base-button.DUjH3il1.js";
import { c as createPopperScope, a as Root2$1, u as useId, A as Anchor, P as Presence, b as Portal$1, D as DismissableLayer, C as Content, d as Arrow, R } from "./theme.BUf-nmmj.js";
import { a as tx, c as css } from "./twind.DdSZmZu6.js";
import { b as useDebounceCallback } from "./index.Dcu_6uM0.js";
var POPOVER_NAME = "Popover";
var [createPopoverContext, createPopoverScope] = createContextScope(POPOVER_NAME, [
  createPopperScope
]);
var usePopperScope = createPopperScope();
var [PopoverProvider, usePopoverContext] = createPopoverContext(POPOVER_NAME);
var Popover = (props) => {
  const {
    __scopePopover,
    children,
    open: openProp,
    defaultOpen,
    onOpenChange,
    modal = false
  } = props;
  const popperScope = usePopperScope(__scopePopover);
  const triggerRef = React.useRef(null);
  const [hasCustomAnchor, setHasCustomAnchor] = React.useState(false);
  const [open, setOpen] = useControllableState({
    prop: openProp,
    defaultProp: defaultOpen ?? false,
    onChange: onOpenChange,
    caller: POPOVER_NAME
  });
  return /* @__PURE__ */ jsx(Root2$1, { ...popperScope, children: /* @__PURE__ */ jsx(
    PopoverProvider,
    {
      scope: __scopePopover,
      contentId: useId(),
      triggerRef,
      open,
      onOpenChange: setOpen,
      onOpenToggle: React.useCallback(() => setOpen((prevOpen) => !prevOpen), [setOpen]),
      hasCustomAnchor,
      onCustomAnchorAdd: React.useCallback(() => setHasCustomAnchor(true), []),
      onCustomAnchorRemove: React.useCallback(() => setHasCustomAnchor(false), []),
      modal,
      children
    }
  ) });
};
Popover.displayName = POPOVER_NAME;
var ANCHOR_NAME = "PopoverAnchor";
var PopoverAnchor = React.forwardRef(
  (props, forwardedRef) => {
    const { __scopePopover, ...anchorProps } = props;
    const context = usePopoverContext(ANCHOR_NAME, __scopePopover);
    const popperScope = usePopperScope(__scopePopover);
    const { onCustomAnchorAdd, onCustomAnchorRemove } = context;
    React.useEffect(() => {
      onCustomAnchorAdd();
      return () => onCustomAnchorRemove();
    }, [onCustomAnchorAdd, onCustomAnchorRemove]);
    return /* @__PURE__ */ jsx(Anchor, { ...popperScope, ...anchorProps, ref: forwardedRef });
  }
);
PopoverAnchor.displayName = ANCHOR_NAME;
var TRIGGER_NAME = "PopoverTrigger";
var PopoverTrigger = React.forwardRef(
  (props, forwardedRef) => {
    const { __scopePopover, ...triggerProps } = props;
    const context = usePopoverContext(TRIGGER_NAME, __scopePopover);
    const popperScope = usePopperScope(__scopePopover);
    const composedTriggerRef = useComposedRefs(forwardedRef, context.triggerRef);
    const trigger = /* @__PURE__ */ jsx(
      Primitive.button,
      {
        type: "button",
        "aria-haspopup": "dialog",
        "aria-expanded": context.open,
        "aria-controls": context.contentId,
        "data-state": getState(context.open),
        ...triggerProps,
        ref: composedTriggerRef,
        onClick: composeEventHandlers(props.onClick, context.onOpenToggle)
      }
    );
    return context.hasCustomAnchor ? trigger : /* @__PURE__ */ jsx(Anchor, { asChild: true, ...popperScope, children: trigger });
  }
);
PopoverTrigger.displayName = TRIGGER_NAME;
var PORTAL_NAME = "PopoverPortal";
var [PortalProvider, usePortalContext] = createPopoverContext(PORTAL_NAME, {
  forceMount: void 0
});
var PopoverPortal = (props) => {
  const { __scopePopover, forceMount, children, container } = props;
  const context = usePopoverContext(PORTAL_NAME, __scopePopover);
  return /* @__PURE__ */ jsx(PortalProvider, { scope: __scopePopover, forceMount, children: /* @__PURE__ */ jsx(Presence, { present: forceMount || context.open, children: /* @__PURE__ */ jsx(Portal$1, { asChild: true, container, children }) }) });
};
PopoverPortal.displayName = PORTAL_NAME;
var CONTENT_NAME = "PopoverContent";
var PopoverContent = React.forwardRef(
  (props, forwardedRef) => {
    const portalContext = usePortalContext(CONTENT_NAME, props.__scopePopover);
    const { forceMount = portalContext.forceMount, ...contentProps } = props;
    const context = usePopoverContext(CONTENT_NAME, props.__scopePopover);
    return /* @__PURE__ */ jsx(Presence, { present: forceMount || context.open, children: context.modal ? /* @__PURE__ */ jsx(PopoverContentModal, { ...contentProps, ref: forwardedRef }) : /* @__PURE__ */ jsx(PopoverContentNonModal, { ...contentProps, ref: forwardedRef }) });
  }
);
PopoverContent.displayName = CONTENT_NAME;
var Slot = createSlot("PopoverContent.RemoveScroll");
var PopoverContentModal = React.forwardRef(
  (props, forwardedRef) => {
    const context = usePopoverContext(CONTENT_NAME, props.__scopePopover);
    const contentRef = React.useRef(null);
    const composedRefs = useComposedRefs(forwardedRef, contentRef);
    const isRightClickOutsideRef = React.useRef(false);
    React.useEffect(() => {
      const content = contentRef.current;
      if (content) return hideOthers(content);
    }, []);
    return /* @__PURE__ */ jsx(ReactRemoveScroll, { as: Slot, allowPinchZoom: true, children: /* @__PURE__ */ jsx(
      PopoverContentImpl,
      {
        ...props,
        ref: composedRefs,
        trapFocus: context.open,
        disableOutsidePointerEvents: true,
        onCloseAutoFocus: composeEventHandlers(props.onCloseAutoFocus, (event) => {
          event.preventDefault();
          if (!isRightClickOutsideRef.current) context.triggerRef.current?.focus();
        }),
        onPointerDownOutside: composeEventHandlers(
          props.onPointerDownOutside,
          (event) => {
            const originalEvent = event.detail.originalEvent;
            const ctrlLeftClick = originalEvent.button === 0 && originalEvent.ctrlKey === true;
            const isRightClick = originalEvent.button === 2 || ctrlLeftClick;
            isRightClickOutsideRef.current = isRightClick;
          },
          { checkForDefaultPrevented: false }
        ),
        onFocusOutside: composeEventHandlers(
          props.onFocusOutside,
          (event) => event.preventDefault(),
          { checkForDefaultPrevented: false }
        )
      }
    ) });
  }
);
var PopoverContentNonModal = React.forwardRef(
  (props, forwardedRef) => {
    const context = usePopoverContext(CONTENT_NAME, props.__scopePopover);
    const hasInteractedOutsideRef = React.useRef(false);
    const hasPointerDownOutsideRef = React.useRef(false);
    return /* @__PURE__ */ jsx(
      PopoverContentImpl,
      {
        ...props,
        ref: forwardedRef,
        trapFocus: false,
        disableOutsidePointerEvents: false,
        onCloseAutoFocus: (event) => {
          props.onCloseAutoFocus?.(event);
          if (!event.defaultPrevented) {
            if (!hasInteractedOutsideRef.current) context.triggerRef.current?.focus();
            event.preventDefault();
          }
          hasInteractedOutsideRef.current = false;
          hasPointerDownOutsideRef.current = false;
        },
        onInteractOutside: (event) => {
          props.onInteractOutside?.(event);
          if (!event.defaultPrevented) {
            hasInteractedOutsideRef.current = true;
            if (event.detail.originalEvent.type === "pointerdown") {
              hasPointerDownOutsideRef.current = true;
            }
          }
          const target = event.target;
          const targetIsTrigger = context.triggerRef.current?.contains(target);
          if (targetIsTrigger) event.preventDefault();
          if (event.detail.originalEvent.type === "focusin" && hasPointerDownOutsideRef.current) {
            event.preventDefault();
          }
        }
      }
    );
  }
);
var PopoverContentImpl = React.forwardRef(
  (props, forwardedRef) => {
    const {
      __scopePopover,
      trapFocus,
      onOpenAutoFocus,
      onCloseAutoFocus,
      disableOutsidePointerEvents,
      onEscapeKeyDown,
      onPointerDownOutside,
      onFocusOutside,
      onInteractOutside,
      ...contentProps
    } = props;
    const context = usePopoverContext(CONTENT_NAME, __scopePopover);
    const popperScope = usePopperScope(__scopePopover);
    useFocusGuards();
    return /* @__PURE__ */ jsx(
      FocusScope,
      {
        asChild: true,
        loop: true,
        trapped: trapFocus,
        onMountAutoFocus: onOpenAutoFocus,
        onUnmountAutoFocus: onCloseAutoFocus,
        children: /* @__PURE__ */ jsx(
          DismissableLayer,
          {
            asChild: true,
            disableOutsidePointerEvents,
            onInteractOutside,
            onEscapeKeyDown,
            onPointerDownOutside,
            onFocusOutside,
            onDismiss: () => context.onOpenChange(false),
            children: /* @__PURE__ */ jsx(
              Content,
              {
                "data-state": getState(context.open),
                role: "dialog",
                id: context.contentId,
                ...popperScope,
                ...contentProps,
                ref: forwardedRef,
                style: {
                  ...contentProps.style,
                  // re-namespace exposed content custom properties
                  ...{
                    "--radix-popover-content-transform-origin": "var(--radix-popper-transform-origin)",
                    "--radix-popover-content-available-width": "var(--radix-popper-available-width)",
                    "--radix-popover-content-available-height": "var(--radix-popper-available-height)",
                    "--radix-popover-trigger-width": "var(--radix-popper-anchor-width)",
                    "--radix-popover-trigger-height": "var(--radix-popper-anchor-height)"
                  }
                }
              }
            )
          }
        )
      }
    );
  }
);
var CLOSE_NAME = "PopoverClose";
var PopoverClose = React.forwardRef(
  (props, forwardedRef) => {
    const { __scopePopover, ...closeProps } = props;
    const context = usePopoverContext(CLOSE_NAME, __scopePopover);
    return /* @__PURE__ */ jsx(
      Primitive.button,
      {
        type: "button",
        ...closeProps,
        ref: forwardedRef,
        onClick: composeEventHandlers(props.onClick, () => context.onOpenChange(false))
      }
    );
  }
);
PopoverClose.displayName = CLOSE_NAME;
var ARROW_NAME = "PopoverArrow";
var PopoverArrow = React.forwardRef(
  (props, forwardedRef) => {
    const { __scopePopover, ...arrowProps } = props;
    const popperScope = usePopperScope(__scopePopover);
    return /* @__PURE__ */ jsx(Arrow, { ...popperScope, ...arrowProps, ref: forwardedRef });
  }
);
PopoverArrow.displayName = ARROW_NAME;
function getState(open) {
  return open ? "open" : "closed";
}
var Root2 = Popover;
var Anchor2 = PopoverAnchor;
var Trigger = PopoverTrigger;
var Portal = PopoverPortal;
var Content2 = PopoverContent;
var Close = PopoverClose;
const o = React.forwardRef(({ className: e2, ...n$1 }, r2) => React.createElement(n, { ...n$1, ref: r2, className: y("rt-IconButton", e2) }));
o.displayName = "IconButton";
const p = ["1", "2", "3", "4"], r = { ...o$1, size: { type: "enum", className: "rt-r-size", values: p, default: "2", responsive: true }, width: t.width, minWidth: t.minWidth, maxWidth: { ...t.maxWidth, default: "480px" }, ...e };
const P = (e2) => React.createElement(Root2, { ...e2 });
P.displayName = "Popover.Root";
const s = React.forwardRef(({ children: e2, ...r2 }, t2) => React.createElement(Trigger, { ...r2, ref: t2, asChild: true }, a(e2)));
s.displayName = "Popover.Trigger";
const i = React.forwardRef((e2, r$1) => {
  const { className: t2, forceMount: a2, container: f, ...l } = v$1(e2, r);
  return React.createElement(Portal, { container: f, forceMount: a2 }, React.createElement(R, { asChild: true }, React.createElement(Content2, { align: "start", sideOffset: 8, collisionPadding: 10, ...l, ref: r$1, className: y("rt-PopperContent", "rt-PopoverContent", t2) })));
});
i.displayName = "Popover.Content";
const v = React.forwardRef(({ children: e2, ...r2 }, t2) => React.createElement(Close, { ...r2, ref: t2, asChild: true }, a(e2)));
v.displayName = "Popover.Close";
const m = React.forwardRef(({ children: e2, ...r2 }, t2) => React.createElement(Anchor2, { ...r2, ref: t2 }));
m.displayName = "Popover.Anchor";
function getEditorNodeFromField(field) {
  return [
    {
      type: "mention",
      attrs: { "data-id": field, label: field }
    },
    {
      type: "text",
      text: ` `
    }
  ];
}
function insertInEditor(editor, content) {
  console.log("Inserting content %s", content);
  editor.chain().insertContent(content, {
    parseOptions: {
      preserveWhitespace: "full"
    }
  }).run();
}
function DatasourceFieldPickerModal({
  brickId,
  onlyAlias,
  onFieldSelect
}) {
  return null;
}
function DatasourceItemButton({
  editor,
  brickId,
  children,
  onFieldClick
}) {
  const queryAlias = useLoopAlias(brickId);
  const onFieldSelect = (field) => {
    onFieldClick?.(field);
    if (!editor) {
      return;
    }
    const content = getEditorNodeFromField(field);
    insertInEditor(editor, content);
  };
  return /* @__PURE__ */ jsxs(P, { children: [
    /* @__PURE__ */ jsx(s, { children }),
    /* @__PURE__ */ jsx(i, { minWidth: "260px", side: "top", align: "start", size: "2", maxHeight: "70dvh", sideOffset: 10, children: /* @__PURE__ */ jsx(DatasourceFieldPickerModal, { onFieldSelect, brickId, onlyAlias: queryAlias }) })
  ] });
}
const TextEditor = lazy(() => import("./TextEditor.ya4V9RCa.js"));
function useTextEditorUpdateHandler(brickId, propPath, dynamic = false, enabled = true) {
  const helpers = useDraftHelpers();
  if (!enabled) {
    return;
  }
  return (e2) => {
    console.log("Updating text editor props", brickId, propPath);
    if (dynamic) {
      helpers.updateBrickProps(brickId, {
        [propPath]: e2.editor.getText()
      });
    } else {
      helpers.updateBrickProps(brickId, { [propPath]: e2.editor.getHTML() });
    }
  };
}
function useDynamicTextEditor({
  currentValue,
  brickId,
  schema,
  onChange,
  placeholder
}) {
  const textEditorRef = useRef(null);
  const onChangeDebounced = useDebounceCallback(onChange, 300);
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(
      "div",
      {
        className: tx(
          "rounded border border-gray-300 px-2 py-[4px] text-sm flex-grow max-w-[calc(100%-34px)] bg-white",
          css({
            "&:has([contenteditable='true']:focus)": {
              outline: "1px solid var(--violet-8)",
              borderColor: "var(--violet-8)"
            }
          })
        ),
        children: /* @__PURE__ */ jsx(Suspense, { fallback: null, children: /* @__PURE__ */ jsx(
          TextEditor,
          {
            content: currentValue,
            brickId,
            ref: textEditorRef,
            className: tx(
              css({ lineHeight: "1.5" }),
              schema["ui:multiline"] && `scrollbar-thin ${schema["ui:textarea-class"] ?? "min-h-24"}`
            ),
            placeholder: schema["ui:placeholder"] ?? placeholder,
            spellCheck: !!schema["ui:spellcheck"],
            singleline: true,
            noMenuBar: true,
            dynamic: true,
            onChange: (e2) => {
              onChangeDebounced(e2.editor.getText());
            }
          }
        ) })
      }
    ),
    /* @__PURE__ */ jsx(
      DatasourceItemButton,
      {
        brickId,
        onFieldClick: (field) => {
          if (textEditorRef.current?.editor) {
            insertInEditor(textEditorRef.current.editor, getEditorNodeFromField(field));
          }
        },
        children: /* @__PURE__ */ jsx(o, { variant: "surface", radius: "large", className: "!w-[31px] !h-[31px]", children: /* @__PURE__ */ jsx(RiBracesLine, { className: "w-4 h-4" }) })
      }
    )
  ] });
}
export {
  DatasourceItemButton as D,
  P,
  useTextEditorUpdateHandler as a,
  i,
  o,
  s,
  useDynamicTextEditor as u
};
//# sourceMappingURL=use-editable-text.CyXfLgKN.js.map
