// packages/block-editor/src/hooks/block-bindings.js
import fastDeepEqual from "fast-deep-equal/es6";
import { __ } from "@wordpress/i18n";
import {
  getBlockBindingsSource,
  getBlockType,
  store as blockStore
} from "@wordpress/blocks";
import {
  __experimentalItemGroup as ItemGroup,
  __experimentalItem as Item,
  __experimentalText as Text,
  __experimentalToolsPanel as ToolsPanel,
  __experimentalToolsPanelItem as ToolsPanelItem,
  __experimentalVStack as VStack,
  privateApis as componentsPrivateApis
} from "@wordpress/components";
import { useSelect } from "@wordpress/data";
import { useContext } from "@wordpress/element";
import { useViewportMatch } from "@wordpress/compose";
import { useBlockBindingsUtils } from "../utils/block-bindings";
import { unlock } from "../lock-unlock";
import InspectorControls from "../components/inspector-controls";
import BlockContext from "../components/block-context";
import { useBlockEditContext } from "../components/block-edit";
import { store as blockEditorStore } from "../store";
import { jsx, jsxs } from "react/jsx-runtime";
var { Menu } = unlock(componentsPrivateApis);
var getAttributeType = (blockName, attribute) => {
  const _attributeType = getBlockType(blockName).attributes?.[attribute]?.type;
  return _attributeType === "rich-text" ? "string" : _attributeType;
};
var useToolsPanelDropdownMenuProps = () => {
  const isMobile = useViewportMatch("medium", "<");
  return !isMobile ? {
    popoverProps: {
      placement: "left-start",
      // For non-mobile, inner sidebar width (248px) - button width (24px) - border (1px) + padding (16px) + spacing (20px)
      offset: 259
    }
  } : {};
};
function BlockBindingsPanelMenuContent({ attribute, binding, sources }) {
  const { clientId } = useBlockEditContext();
  const { updateBlockBindings } = useBlockBindingsUtils();
  const isMobile = useViewportMatch("medium", "<");
  const blockContext = useContext(BlockContext);
  const { attributeType, select } = useSelect(
    (_select) => {
      const { name: blockName } = _select(blockEditorStore).getBlock(clientId);
      return {
        attributeType: getAttributeType(blockName, attribute),
        select: _select
      };
    },
    [clientId, attribute]
  );
  return /* @__PURE__ */ jsx(Menu, { placement: isMobile ? "bottom-start" : "left-start", children: Object.entries(sources).map(([sourceKey, data]) => {
    const sourceDataItems = data.filter(
      (item) => item.type === attributeType
    );
    const noItemsAvailable = !sourceDataItems || sourceDataItems.length === 0;
    if (noItemsAvailable) {
      return null;
    }
    const source = getBlockBindingsSource(sourceKey);
    return /* @__PURE__ */ jsxs(
      Menu,
      {
        placement: isMobile ? "bottom-start" : "left-start",
        children: [
          /* @__PURE__ */ jsx(Menu.SubmenuTriggerItem, { children: /* @__PURE__ */ jsx(Menu.ItemLabel, { children: source.label }) }),
          /* @__PURE__ */ jsx(Menu.Popover, { gutter: 8, children: /* @__PURE__ */ jsx(Menu.Group, { children: sourceDataItems.map((item) => {
            const itemBindings = {
              source: sourceKey,
              args: item.args || {
                key: item.key
              }
            };
            let values = {};
            try {
              values = source.getValues({
                select,
                context: blockContext,
                bindings: {
                  [attribute]: itemBindings
                }
              });
            } catch (e) {
            }
            return /* @__PURE__ */ jsxs(
              Menu.CheckboxItem,
              {
                onChange: () => {
                  const isCurrentlySelected = fastDeepEqual(
                    binding?.args,
                    item.args
                  ) ?? // Deprecate key dependency in 7.0.
                  item.key === binding?.args?.key;
                  if (isCurrentlySelected) {
                    updateBlockBindings({
                      [attribute]: void 0
                    });
                  } else {
                    updateBlockBindings({
                      [attribute]: itemBindings
                    });
                  }
                },
                name: attribute + "-binding",
                value: values[attribute],
                checked: fastDeepEqual(
                  binding?.args,
                  item.args
                ) ?? // Deprecate key dependency in 7.0.
                item.key === binding?.args?.key,
                children: [
                  /* @__PURE__ */ jsx(Menu.ItemLabel, { children: item.label }),
                  /* @__PURE__ */ jsx(Menu.ItemHelpText, { children: values[attribute] })
                ]
              },
              sourceKey + JSON.stringify(
                item.args
              ) || item.key
            );
          }) }) })
        ]
      },
      sourceKey
    );
  }) });
}
function BlockBindingsAttribute({ attribute, binding, sources, blockName }) {
  const { source: sourceName, args } = binding || {};
  const data = sources?.[sourceName];
  const source = getBlockBindingsSource(sourceName);
  let displayText;
  let isValid = true;
  const isNotBound = binding === void 0;
  if (isNotBound) {
    const attributeType = getAttributeType(blockName, attribute);
    const hasCompatibleSources = Object.values(sources).some(
      (items) => items.some((item) => item.type === attributeType)
    );
    if (!hasCompatibleSources) {
      displayText = __("No sources available");
    } else {
      displayText = __("Not connected");
    }
    isValid = true;
  } else if (!source) {
    isValid = false;
    displayText = __("Source not registered");
  } else {
    displayText = data?.find((item) => fastDeepEqual(item.args, args))?.label || source?.label || sourceName;
  }
  return /* @__PURE__ */ jsxs(VStack, { className: "block-editor-bindings__item", spacing: 0, children: [
    /* @__PURE__ */ jsx(Text, { truncate: true, children: attribute }),
    /* @__PURE__ */ jsx(
      Text,
      {
        truncate: true,
        variant: isValid ? "muted" : void 0,
        isDestructive: !isValid,
        children: displayText
      }
    )
  ] });
}
function ReadOnlyBlockBindingsPanelItem({
  attribute,
  binding,
  sources,
  blockName
}) {
  const isMobile = useViewportMatch("medium", "<");
  return /* @__PURE__ */ jsx(ToolsPanelItem, { hasValue: () => !!binding, label: attribute, children: /* @__PURE__ */ jsx(Menu, { placement: isMobile ? "bottom-start" : "left-start", children: /* @__PURE__ */ jsx(Menu.TriggerButton, { render: /* @__PURE__ */ jsx(Item, {}), disabled: true, children: /* @__PURE__ */ jsx(
    BlockBindingsAttribute,
    {
      attribute,
      binding,
      sources,
      blockName
    }
  ) }) }) });
}
function EditableBlockBindingsPanelItem({
  attribute,
  binding,
  sources,
  blockName
}) {
  const { updateBlockBindings } = useBlockBindingsUtils();
  const isMobile = useViewportMatch("medium", "<");
  return /* @__PURE__ */ jsx(
    ToolsPanelItem,
    {
      hasValue: () => !!binding,
      label: attribute,
      onDeselect: () => {
        updateBlockBindings({
          [attribute]: void 0
        });
      },
      children: /* @__PURE__ */ jsxs(Menu, { placement: isMobile ? "bottom-start" : "left-start", children: [
        /* @__PURE__ */ jsx(Menu.TriggerButton, { render: /* @__PURE__ */ jsx(Item, {}), children: /* @__PURE__ */ jsx(
          BlockBindingsAttribute,
          {
            attribute,
            binding,
            sources,
            blockName
          }
        ) }),
        /* @__PURE__ */ jsx(Menu.Popover, { gutter: isMobile ? 8 : 36, children: /* @__PURE__ */ jsx(
          BlockBindingsPanelMenuContent,
          {
            attribute,
            binding,
            sources
          }
        ) })
      ] })
    }
  );
}
var BlockBindingsPanel = ({ name: blockName, metadata }) => {
  const blockContext = useContext(BlockContext);
  const { removeAllBlockBindings } = useBlockBindingsUtils();
  const dropdownMenuProps = useToolsPanelDropdownMenuProps();
  const { canUpdateBlockBindings, bindableAttributes } = useSelect(
    (select) => {
      const { __experimentalBlockBindingsSupportedAttributes } = select(blockEditorStore).getSettings();
      return {
        canUpdateBlockBindings: select(blockEditorStore).getSettings().canUpdateBlockBindings,
        bindableAttributes: __experimentalBlockBindingsSupportedAttributes?.[blockName]
      };
    },
    [blockName]
  );
  const sources = useSelect(
    (select) => {
      const { getAllBlockBindingsSources } = unlock(
        select(blockStore)
      );
      const data = {};
      Object.entries(getAllBlockBindingsSources()).forEach(
        ([sourceName, source]) => {
          if (!source.getFieldsList) {
            return;
          }
          const context = {};
          if (source.usesContext?.length) {
            for (const key of source.usesContext) {
              context[key] = blockContext[key];
            }
          }
          const items = source.getFieldsList({
            select,
            context
          });
          if (items?.length) {
            data[sourceName] = items;
          }
        }
      );
      return data;
    },
    [blockContext]
  );
  if (!bindableAttributes || bindableAttributes.length === 0) {
    return null;
  }
  const { bindings } = metadata || {};
  const hasCompatibleData = Object.keys(sources).length > 0;
  const readOnly = !canUpdateBlockBindings || !hasCompatibleData;
  if (bindings === void 0 && !hasCompatibleData) {
    return null;
  }
  return /* @__PURE__ */ jsx(InspectorControls, { group: "bindings", children: /* @__PURE__ */ jsxs(
    ToolsPanel,
    {
      label: __("Attributes"),
      resetAll: () => {
        removeAllBlockBindings();
      },
      dropdownMenuProps,
      className: "block-editor-bindings__panel",
      children: [
        /* @__PURE__ */ jsx(ItemGroup, { isBordered: true, isSeparated: true, children: bindableAttributes.map((attribute) => {
          const binding = bindings?.[attribute];
          const attributeType = getAttributeType(
            blockName,
            attribute
          );
          const hasCompatibleDataForAttribute = Object.values(
            sources
          ).some(
            (data) => data.some((item) => item.type === attributeType)
          );
          const isAttributeReadOnly = readOnly || !hasCompatibleDataForAttribute;
          return isAttributeReadOnly ? /* @__PURE__ */ jsx(
            ReadOnlyBlockBindingsPanelItem,
            {
              attribute,
              binding,
              sources,
              blockName
            },
            attribute
          ) : /* @__PURE__ */ jsx(
            EditableBlockBindingsPanelItem,
            {
              attribute,
              binding,
              sources,
              blockName
            },
            attribute
          );
        }) }),
        /* @__PURE__ */ jsx(Text, { as: "div", variant: "muted", children: /* @__PURE__ */ jsx("p", { children: __(
          "Attributes connected to custom fields or other dynamic data."
        ) }) })
      ]
    }
  ) });
};
var block_bindings_default = {
  edit: BlockBindingsPanel,
  attributeKeys: ["metadata"],
  hasSupport(name) {
    return ![
      "core/post-date",
      "core/navigation-link",
      "core/navigation-submenu"
    ].includes(name);
  }
};
export {
  BlockBindingsPanel,
  block_bindings_default as default
};
//# sourceMappingURL=block-bindings.js.map
