"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = StartPageOptions;
exports.useStartPatterns = useStartPatterns;
var _components = require("@wordpress/components");
var _i18n = require("@wordpress/i18n");
var _element = require("@wordpress/element");
var _blockEditor = require("@wordpress/block-editor");
var _data = require("@wordpress/data");
var _coreData = require("@wordpress/core-data");
var _blocks = require("@wordpress/blocks");
var _preferences = require("@wordpress/preferences");
var _interface = require("@wordpress/interface");
var _store = require("../../store");
var _jsxRuntime = require("react/jsx-runtime");
/**
 * WordPress dependencies
 */

/**
 * Internal dependencies
 */

function useStartPatterns() {
  // A pattern is a start pattern if it includes 'core/post-content' in its blockTypes,
  // and it has no postTypes declared and the current post type is page or if
  // the current post type is part of the postTypes declared.
  const {
    blockPatternsWithPostContentBlockType,
    postType
  } = (0, _data.useSelect)(select => {
    const {
      getPatternsByBlockTypes,
      getBlocksByName
    } = select(_blockEditor.store);
    const {
      getCurrentPostType,
      getRenderingMode
    } = select(_store.store);
    const rootClientId = getRenderingMode() === 'post-only' ? '' : getBlocksByName('core/post-content')?.[0];
    return {
      blockPatternsWithPostContentBlockType: getPatternsByBlockTypes('core/post-content', rootClientId),
      postType: getCurrentPostType()
    };
  }, []);
  return (0, _element.useMemo)(() => {
    if (!blockPatternsWithPostContentBlockType?.length) {
      return [];
    }

    /*
     * Filter patterns without postTypes declared if the current postType is page
     * or patterns that declare the current postType in its post type array.
     */
    return blockPatternsWithPostContentBlockType.filter(pattern => {
      return postType === 'page' && !pattern.postTypes || Array.isArray(pattern.postTypes) && pattern.postTypes.includes(postType);
    });
  }, [postType, blockPatternsWithPostContentBlockType]);
}
function PatternSelection({
  blockPatterns,
  onChoosePattern
}) {
  const {
    editEntityRecord
  } = (0, _data.useDispatch)(_coreData.store);
  const {
    postType,
    postId
  } = (0, _data.useSelect)(select => {
    const {
      getCurrentPostType,
      getCurrentPostId
    } = select(_store.store);
    return {
      postType: getCurrentPostType(),
      postId: getCurrentPostId()
    };
  }, []);
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_blockEditor.__experimentalBlockPatternsList, {
    blockPatterns: blockPatterns,
    onClickPattern: (_pattern, blocks) => {
      editEntityRecord('postType', postType, postId, {
        blocks,
        content: ({
          blocks: blocksForSerialization = []
        }) => (0, _blocks.__unstableSerializeAndClean)(blocksForSerialization)
      });
      onChoosePattern();
    }
  });
}
function StartPageOptionsModal({
  onClose
}) {
  const [showStartPatterns, setShowStartPatterns] = (0, _element.useState)(true);
  const {
    set: setPreference
  } = (0, _data.useDispatch)(_preferences.store);
  const startPatterns = useStartPatterns();
  const hasStartPattern = startPatterns.length > 0;
  if (!hasStartPattern) {
    return null;
  }
  function handleClose() {
    onClose();
    setPreference('core', 'enableChoosePatternModal', showStartPatterns);
  }
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.Modal, {
    className: "editor-start-page-options__modal",
    title: (0, _i18n.__)('Choose a pattern'),
    isFullScreen: true,
    onRequestClose: handleClose,
    children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      className: "editor-start-page-options__modal-content",
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(PatternSelection, {
        blockPatterns: startPatterns,
        onChoosePattern: handleClose
      })
    }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Flex, {
      className: "editor-start-page-options__modal__actions",
      justify: "flex-end",
      expanded: false,
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.FlexItem, {
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.ToggleControl, {
          __nextHasNoMarginBottom: true,
          checked: showStartPatterns,
          label: (0, _i18n.__)('Show starter patterns'),
          help: (0, _i18n.__)('Shows starter patterns when creating a new page.'),
          onChange: newValue => {
            setShowStartPatterns(newValue);
          }
        })
      })
    })]
  });
}
function StartPageOptions() {
  const [isOpen, setIsOpen] = (0, _element.useState)(false);
  const {
    isEditedPostDirty,
    isEditedPostEmpty
  } = (0, _data.useSelect)(_store.store);
  const {
    isModalActive
  } = (0, _data.useSelect)(_interface.store);
  const {
    enabled,
    postId
  } = (0, _data.useSelect)(select => {
    const {
      getCurrentPostId,
      getCurrentPostType
    } = select(_store.store);
    const choosePatternModalEnabled = select(_preferences.store).get('core', 'enableChoosePatternModal');
    return {
      postId: getCurrentPostId(),
      enabled: choosePatternModalEnabled && 'page' === getCurrentPostType()
    };
  }, []);

  // Note: The `postId` ensures the effect re-runs when pages are switched without remounting the component.
  // Examples: changing pages in the List View, creating a new page via Command Palette.
  (0, _element.useEffect)(() => {
    const isFreshPage = !isEditedPostDirty() && isEditedPostEmpty();
    // Prevents immediately opening when features is enabled via preferences modal.
    const isPreferencesModalActive = isModalActive('editor/preferences');
    if (!enabled || !isFreshPage || isPreferencesModalActive) {
      return;
    }

    // Open the modal after the initial render for a new page.
    setIsOpen(true);
  }, [enabled, postId, isEditedPostDirty, isEditedPostEmpty, isModalActive]);
  if (!isOpen) {
    return null;
  }
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(StartPageOptionsModal, {
    onClose: () => setIsOpen(false)
  });
}
//# sourceMappingURL=index.js.map