"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _clsx = _interopRequireDefault(require("clsx"));
var _components = require("@wordpress/components");
var _htmlEntities = require("@wordpress/html-entities");
var _element = require("@wordpress/element");
var _data = require("@wordpress/data");
var _coreData = require("@wordpress/core-data");
var _compose = require("@wordpress/compose");
var _icons = require("@wordpress/icons");
var _i18n = require("@wordpress/i18n");
var _notices = require("@wordpress/notices");
var _router = require("@wordpress/router");
var _constants = require("../../utils/constants");
var _addCustomTemplateModalContent = _interopRequireDefault(require("./add-custom-template-modal-content"));
var _utils = require("./utils");
var _addCustomGenericTemplateModalContent = _interopRequireDefault(require("./add-custom-generic-template-modal-content"));
var _lockUnlock = require("../../lock-unlock");
var _jsxRuntime = require("react/jsx-runtime");
/**
 * External dependencies
 */

/**
 * WordPress dependencies
 */

/**
 * Internal dependencies
 */

/**
 * Internal dependencies
 */

const {
  useHistory
} = (0, _lockUnlock.unlock)(_router.privateApis);
const DEFAULT_TEMPLATE_SLUGS = ['front-page', 'home', 'single', 'page', 'index', 'archive', 'author', 'category', 'date', 'tag', 'search', '404'];
const TEMPLATE_ICONS = {
  'front-page': _icons.home,
  home: _icons.verse,
  single: _icons.pin,
  page: _icons.page,
  archive: _icons.archive,
  search: _icons.search,
  404: _icons.notFound,
  index: _icons.list,
  category: _icons.category,
  author: _icons.commentAuthorAvatar,
  taxonomy: _icons.blockMeta,
  date: _icons.calendar,
  tag: _icons.tag,
  attachment: _icons.media
};
function TemplateListItem({
  title,
  direction,
  className,
  description,
  icon,
  onClick,
  children
}) {
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Button, {
    __next40pxDefaultSize: true,
    className: className,
    onClick: onClick,
    label: description,
    showTooltip: !!description,
    children: /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.Flex, {
      as: "span",
      spacing: 2,
      align: "center",
      justify: "center",
      style: {
        width: '100%'
      },
      direction: direction,
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        className: "edit-site-add-new-template__template-icon",
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Icon, {
          icon: icon
        })
      }), /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.__experimentalVStack, {
        className: "edit-site-add-new-template__template-name",
        alignment: "center",
        spacing: 0,
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__experimentalText, {
          align: "center",
          weight: 500,
          lineHeight: 1.53846153846 // 20px
          ,
          children: title
        }), children]
      })]
    })
  });
}
const modalContentMap = {
  templatesList: 1,
  customTemplate: 2,
  customGenericTemplate: 3
};
function NewTemplateModal({
  onClose
}) {
  const [modalContent, setModalContent] = (0, _element.useState)(modalContentMap.templatesList);
  const [entityForSuggestions, setEntityForSuggestions] = (0, _element.useState)({});
  const [isSubmitting, setIsSubmitting] = (0, _element.useState)(false);
  const missingTemplates = useMissingTemplates(setEntityForSuggestions, () => setModalContent(modalContentMap.customTemplate));
  const history = useHistory();
  const {
    saveEntityRecord
  } = (0, _data.useDispatch)(_coreData.store);
  const {
    createErrorNotice,
    createSuccessNotice
  } = (0, _data.useDispatch)(_notices.store);
  const isMobile = (0, _compose.useViewportMatch)('medium', '<');
  const homeUrl = (0, _data.useSelect)(select => {
    // Site index.
    return select(_coreData.store).getEntityRecord('root', '__unstableBase')?.home;
  }, []);
  const TEMPLATE_SHORT_DESCRIPTIONS = {
    'front-page': homeUrl,
    date: (0, _i18n.sprintf)(
    // translators: %s: The homepage url.
    (0, _i18n.__)('E.g. %s'), homeUrl + '/' + new Date().getFullYear())
  };
  async function createTemplate(template, isWPSuggestion = true) {
    if (isSubmitting) {
      return;
    }
    setIsSubmitting(true);
    try {
      const {
        title,
        description,
        slug
      } = template;
      const newTemplate = await saveEntityRecord('postType', _constants.TEMPLATE_POST_TYPE, {
        description,
        // Slugs need to be strings, so this is for template `404`
        slug: slug.toString(),
        status: 'publish',
        title,
        // This adds a post meta field in template that is part of `is_custom` value calculation.
        is_wp_suggestion: isWPSuggestion
      }, {
        throwOnError: true
      });

      // Navigate to the created template editor.
      history.navigate(`/${_constants.TEMPLATE_POST_TYPE}/${newTemplate.id}?canvas=edit`);
      createSuccessNotice((0, _i18n.sprintf)(
      // translators: %s: Title of the created post or template, e.g: "Hello world".
      (0, _i18n.__)('"%s" successfully created.'), (0, _htmlEntities.decodeEntities)(newTemplate.title?.rendered || title)), {
        type: 'snackbar'
      });
    } catch (error) {
      const errorMessage = error.message && error.code !== 'unknown_error' ? error.message : (0, _i18n.__)('An error occurred while creating the template.');
      createErrorNotice(errorMessage, {
        type: 'snackbar'
      });
    } finally {
      setIsSubmitting(false);
    }
  }
  const onModalClose = () => {
    onClose();
    setModalContent(modalContentMap.templatesList);
  };
  let modalTitle = (0, _i18n.__)('Add template');
  if (modalContent === modalContentMap.customTemplate) {
    modalTitle = (0, _i18n.sprintf)(
    // translators: %s: Name of the post type e.g: "Post".
    (0, _i18n.__)('Add template: %s'), entityForSuggestions.labels.singular_name);
  } else if (modalContent === modalContentMap.customGenericTemplate) {
    modalTitle = (0, _i18n.__)('Create custom template');
  }
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.Modal, {
    title: modalTitle,
    className: (0, _clsx.default)('edit-site-add-new-template__modal', {
      'edit-site-add-new-template__modal_template_list': modalContent === modalContentMap.templatesList,
      'edit-site-custom-template-modal': modalContent === modalContentMap.customTemplate
    }),
    onRequestClose: onModalClose,
    overlayClassName: modalContent === modalContentMap.customGenericTemplate ? 'edit-site-custom-generic-template__modal' : undefined,
    children: [modalContent === modalContentMap.templatesList && /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.__experimentalGrid, {
      columns: isMobile ? 2 : 3,
      gap: 4,
      align: "flex-start",
      justify: "center",
      className: "edit-site-add-new-template__template-list__contents",
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Flex, {
        className: "edit-site-add-new-template__template-list__prompt",
        children: (0, _i18n.__)('Select what the new template should apply to:')
      }), missingTemplates.map(template => {
        const {
          title,
          slug,
          onClick
        } = template;
        return /*#__PURE__*/(0, _jsxRuntime.jsx)(TemplateListItem, {
          title: title,
          direction: "column",
          className: "edit-site-add-new-template__template-button",
          description: TEMPLATE_SHORT_DESCRIPTIONS[slug],
          icon: TEMPLATE_ICONS[slug] || _icons.layout,
          onClick: () => onClick ? onClick(template) : createTemplate(template)
        }, slug);
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)(TemplateListItem, {
        title: (0, _i18n.__)('Custom template'),
        direction: "row",
        className: "edit-site-add-new-template__custom-template-button",
        icon: _icons.edit,
        onClick: () => setModalContent(modalContentMap.customGenericTemplate),
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__experimentalText, {
          lineHeight: 1.53846153846 // 20px
          ,
          children: (0, _i18n.__)('A custom template can be manually applied to any post or page.')
        })
      })]
    }), modalContent === modalContentMap.customTemplate && /*#__PURE__*/(0, _jsxRuntime.jsx)(_addCustomTemplateModalContent.default, {
      onSelect: createTemplate,
      entityForSuggestions: entityForSuggestions
    }), modalContent === modalContentMap.customGenericTemplate && /*#__PURE__*/(0, _jsxRuntime.jsx)(_addCustomGenericTemplateModalContent.default, {
      onClose: onModalClose,
      createTemplate: createTemplate
    })]
  });
}
function NewTemplate() {
  const [showModal, setShowModal] = (0, _element.useState)(false);
  const {
    postType
  } = (0, _data.useSelect)(select => {
    const {
      getPostType
    } = select(_coreData.store);
    return {
      postType: getPostType(_constants.TEMPLATE_POST_TYPE)
    };
  }, []);
  if (!postType) {
    return null;
  }
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
    children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Button, {
      variant: "primary",
      onClick: () => setShowModal(true),
      label: postType.labels.add_new_item,
      __next40pxDefaultSize: true,
      children: postType.labels.add_new_item
    }), showModal && /*#__PURE__*/(0, _jsxRuntime.jsx)(NewTemplateModal, {
      onClose: () => setShowModal(false)
    })]
  });
}
function useMissingTemplates(setEntityForSuggestions, onClick) {
  const existingTemplates = (0, _utils.useExistingTemplates)();
  const defaultTemplateTypes = (0, _utils.useDefaultTemplateTypes)();
  const existingTemplateSlugs = (existingTemplates || []).map(({
    slug
  }) => slug);
  const missingDefaultTemplates = (defaultTemplateTypes || []).filter(template => DEFAULT_TEMPLATE_SLUGS.includes(template.slug) && !existingTemplateSlugs.includes(template.slug));
  const onClickMenuItem = _entityForSuggestions => {
    onClick?.();
    setEntityForSuggestions(_entityForSuggestions);
  };
  // We need to replace existing default template types with
  // the create specific template functionality. The original
  // info (title, description, etc.) is preserved in the
  // used hooks.
  const enhancedMissingDefaultTemplateTypes = [...missingDefaultTemplates];
  const {
    defaultTaxonomiesMenuItems,
    taxonomiesMenuItems
  } = (0, _utils.useTaxonomiesMenuItems)(onClickMenuItem);
  const {
    defaultPostTypesMenuItems,
    postTypesMenuItems
  } = (0, _utils.usePostTypeMenuItems)(onClickMenuItem);
  const authorMenuItem = (0, _utils.useAuthorMenuItem)(onClickMenuItem);
  [...defaultTaxonomiesMenuItems, ...defaultPostTypesMenuItems, authorMenuItem].forEach(menuItem => {
    if (!menuItem) {
      return;
    }
    const matchIndex = enhancedMissingDefaultTemplateTypes.findIndex(template => template.slug === menuItem.slug);
    // Some default template types might have been filtered above from
    // `missingDefaultTemplates` because they only check for the general
    // template. So here we either replace or append the item, augmented
    // with the check if it has available specific item to create a
    // template for.
    if (matchIndex > -1) {
      enhancedMissingDefaultTemplateTypes[matchIndex] = menuItem;
    } else {
      enhancedMissingDefaultTemplateTypes.push(menuItem);
    }
  });
  // Update the sort order to match the DEFAULT_TEMPLATE_SLUGS order.
  enhancedMissingDefaultTemplateTypes?.sort((template1, template2) => {
    return DEFAULT_TEMPLATE_SLUGS.indexOf(template1.slug) - DEFAULT_TEMPLATE_SLUGS.indexOf(template2.slug);
  });
  const missingTemplates = [...enhancedMissingDefaultTemplateTypes, ...(0, _utils.usePostTypeArchiveMenuItems)(), ...postTypesMenuItems, ...taxonomiesMenuItems];
  return missingTemplates;
}
var _default = exports.default = (0, _element.memo)(NewTemplate);
//# sourceMappingURL=index.js.map