"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = BlockRenameControl;
var _components = require("@wordpress/components");
var _data = require("@wordpress/data");
var _i18n = require("@wordpress/i18n");
var _element = require("@wordpress/element");
var _store = require("../../store");
var _ = require("..");
var _isEmptyString = _interopRequireDefault(require("./is-empty-string"));
var _modal = _interopRequireDefault(require("./modal"));
var _jsxRuntime = require("react/jsx-runtime");
/**
 * WordPress dependencies
 */

/**
 * Internal dependencies
 */

function BlockRenameControl({
  clientId
}) {
  const [renamingBlock, setRenamingBlock] = (0, _element.useState)(false);
  const {
    metadata
  } = (0, _data.useSelect)(select => {
    const {
      getBlockAttributes
    } = select(_store.store);
    const _metadata = getBlockAttributes(clientId)?.metadata;
    return {
      metadata: _metadata
    };
  }, [clientId]);
  const {
    updateBlockAttributes
  } = (0, _data.useDispatch)(_store.store);
  const customName = metadata?.name;
  const hasPatternOverrides = !!customName && !!metadata?.bindings && Object.values(metadata.bindings).some(binding => binding.source === 'core/pattern-overrides');
  function onChange(newName) {
    updateBlockAttributes([clientId], {
      metadata: {
        ...metadata,
        name: newName
      }
    });
  }
  const blockInformation = (0, _.useBlockDisplayInformation)(clientId);
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
    children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_components.MenuItem, {
      onClick: () => {
        setRenamingBlock(true);
      },
      "aria-expanded": renamingBlock,
      "aria-haspopup": "dialog",
      children: (0, _i18n.__)('Rename')
    }), renamingBlock && /*#__PURE__*/(0, _jsxRuntime.jsx)(_modal.default, {
      blockName: customName || '',
      originalBlockName: blockInformation?.title,
      hasOverridesWarning: hasPatternOverrides,
      onClose: () => setRenamingBlock(false),
      onSave: newName => {
        // If the new value is the block's original name (e.g. `Group`)
        // or it is an empty string then assume the intent is to reset
        // the value. Therefore reset the metadata.
        if (newName === blockInformation?.title || (0, _isEmptyString.default)(newName)) {
          newName = undefined;
        }
        onChange(newName);
      }
    })]
  });
}
//# sourceMappingURL=rename-control.js.map