/* wp:polyfill */
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = AddNewPattern;
var _components = require("@wordpress/components");
var _element = require("@wordpress/element");
var _i18n = require("@wordpress/i18n");
var _icons = require("@wordpress/icons");
var _data = require("@wordpress/data");
var _router = require("@wordpress/router");
var _patterns = require("@wordpress/patterns");
var _notices = require("@wordpress/notices");
var _coreData = require("@wordpress/core-data");
var _editor = require("@wordpress/editor");
var _lockUnlock = require("../../lock-unlock");
var _constants = require("../../utils/constants");
var _jsxRuntime = require("react/jsx-runtime");
/**
 * WordPress dependencies
 */

/**
 * Internal dependencies
 */

const {
  useHistory,
  useLocation
} = (0, _lockUnlock.unlock)(_router.privateApis);
const {
  CreatePatternModal,
  useAddPatternCategory
} = (0, _lockUnlock.unlock)(_patterns.privateApis);
const {
  CreateTemplatePartModal
} = (0, _lockUnlock.unlock)(_editor.privateApis);
function AddNewPattern() {
  const history = useHistory();
  const location = useLocation();
  const [showPatternModal, setShowPatternModal] = (0, _element.useState)(false);
  const [showTemplatePartModal, setShowTemplatePartModal] = (0, _element.useState)(false);
  // eslint-disable-next-line @wordpress/no-unused-vars-before-return
  const {
    createPatternFromFile
  } = (0, _lockUnlock.unlock)((0, _data.useDispatch)(_patterns.store));
  const {
    createSuccessNotice,
    createErrorNotice
  } = (0, _data.useDispatch)(_notices.store);
  const patternUploadInputRef = (0, _element.useRef)();
  const {
    isBlockBasedTheme,
    addNewPatternLabel,
    addNewTemplatePartLabel,
    canCreatePattern,
    canCreateTemplatePart
  } = (0, _data.useSelect)(select => {
    const {
      getCurrentTheme,
      getPostType,
      canUser
    } = select(_coreData.store);
    return {
      isBlockBasedTheme: getCurrentTheme()?.is_block_theme,
      addNewPatternLabel: getPostType(_constants.PATTERN_TYPES.user)?.labels?.add_new_item,
      addNewTemplatePartLabel: getPostType(_constants.TEMPLATE_PART_POST_TYPE)?.labels?.add_new_item,
      // Blocks refers to the wp_block post type, this checks the ability to create a post of that type.
      canCreatePattern: canUser('create', {
        kind: 'postType',
        name: _constants.PATTERN_TYPES.user
      }),
      canCreateTemplatePart: canUser('create', {
        kind: 'postType',
        name: _constants.TEMPLATE_PART_POST_TYPE
      })
    };
  }, []);
  function handleCreatePattern({
    pattern
  }) {
    setShowPatternModal(false);
    history.navigate(`/${_constants.PATTERN_TYPES.user}/${pattern.id}?canvas=edit`);
  }
  function handleCreateTemplatePart(templatePart) {
    setShowTemplatePartModal(false);
    history.navigate(`/${_constants.TEMPLATE_PART_POST_TYPE}/${templatePart.id}?canvas=edit`);
  }
  function handleError() {
    setShowPatternModal(false);
    setShowTemplatePartModal(false);
  }
  const controls = [];
  if (canCreatePattern) {
    controls.push({
      icon: _icons.symbol,
      onClick: () => setShowPatternModal(true),
      title: addNewPatternLabel
    });
  }
  if (isBlockBasedTheme && canCreateTemplatePart) {
    controls.push({
      icon: _icons.symbolFilled,
      onClick: () => setShowTemplatePartModal(true),
      title: addNewTemplatePartLabel
    });
  }
  if (canCreatePattern) {
    controls.push({
      icon: _icons.upload,
      onClick: () => {
        patternUploadInputRef.current.click();
      },
      title: (0, _i18n.__)('Import pattern from JSON')
    });
  }
  const {
    categoryMap,
    findOrCreateTerm
  } = useAddPatternCategory();
  if (controls.length === 0) {
    return null;
  }
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
    children: [addNewPatternLabel && /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.DropdownMenu, {
      controls: controls,
      icon: null,
      toggleProps: {
        variant: 'primary',
        showTooltip: false,
        __next40pxDefaultSize: true
      },
      text: addNewPatternLabel,
      label: addNewPatternLabel
    }), showPatternModal && /*#__PURE__*/(0, _jsxRuntime.jsx)(CreatePatternModal, {
      onClose: () => setShowPatternModal(false),
      onSuccess: handleCreatePattern,
      onError: handleError
    }), showTemplatePartModal && /*#__PURE__*/(0, _jsxRuntime.jsx)(CreateTemplatePartModal, {
      closeModal: () => setShowTemplatePartModal(false),
      blocks: [],
      onCreate: handleCreateTemplatePart,
      onError: handleError
    }), /*#__PURE__*/(0, _jsxRuntime.jsx)("input", {
      type: "file",
      accept: ".json",
      hidden: true,
      ref: patternUploadInputRef,
      onChange: async event => {
        const file = event.target.files?.[0];
        if (!file) {
          return;
        }
        try {
          let currentCategoryId;
          // When we're not handling template parts, we should
          // add or create the proper pattern category.
          if (location.query.postType !== _constants.TEMPLATE_PART_POST_TYPE) {
            /*
             * categoryMap.values() returns an iterator.
             * Iterator.prototype.find() is not yet widely supported.
             * Convert to array to use the Array.prototype.find method.
             */
            const currentCategory = Array.from(categoryMap.values()).find(term => term.name === location.query.categoryId);
            if (currentCategory) {
              currentCategoryId = currentCategory.id || (await findOrCreateTerm(currentCategory.label));
            }
          }
          const pattern = await createPatternFromFile(file, currentCategoryId ? [currentCategoryId] : undefined);

          // Navigate to the All patterns category for the newly created pattern
          // if we're not on that page already and if we're not in the `my-patterns`
          // category.
          if (!currentCategoryId && location.query.categoryId !== 'my-patterns') {
            history.navigate(`/pattern?categoryId=${_constants.PATTERN_DEFAULT_CATEGORY}`);
          }
          createSuccessNotice((0, _i18n.sprintf)(
          // translators: %s: The imported pattern's title.
          (0, _i18n.__)('Imported "%s" from JSON.'), pattern.title.raw), {
            type: 'snackbar',
            id: 'import-pattern-success'
          });
        } catch (err) {
          createErrorNotice(err.message, {
            type: 'snackbar',
            id: 'import-pattern-error'
          });
        } finally {
          event.target.value = '';
        }
      }
    })]
  });
}
//# sourceMappingURL=index.js.map