"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = QueryInspectorControls;
var _components = require("@wordpress/components");
var _data = require("@wordpress/data");
var _coreData = require("@wordpress/core-data");
var _i18n = require("@wordpress/i18n");
var _blockEditor = require("@wordpress/block-editor");
var _compose = require("@wordpress/compose");
var _element = require("@wordpress/element");
var _orderControl = _interopRequireDefault(require("./order-control"));
var _authorControl = _interopRequireDefault(require("./author-control"));
var _parentControl = _interopRequireDefault(require("./parent-control"));
var _taxonomyControls = require("./taxonomy-controls");
var _formatControls = _interopRequireDefault(require("./format-controls"));
var _stickyControl = _interopRequireDefault(require("./sticky-control"));
var _createNewPostLink = _interopRequireDefault(require("./create-new-post-link"));
var _perPageControl = _interopRequireDefault(require("./per-page-control"));
var _offsetControls = _interopRequireDefault(require("./offset-controls"));
var _pagesControl = _interopRequireDefault(require("./pages-control"));
var _lockUnlock = require("../../../lock-unlock");
var _utils = require("../../utils");
var _hooks = require("../../../utils/hooks");
var _jsxRuntime = require("react/jsx-runtime");
/**
 * WordPress dependencies
 */

/**
 * Internal dependencies
 */

const {
  BlockInfo
} = (0, _lockUnlock.unlock)(_blockEditor.privateApis);
function QueryInspectorControls(props) {
  const {
    attributes,
    setQuery,
    setDisplayLayout,
    isTemplate
  } = props;
  const {
    query,
    displayLayout
  } = attributes;
  const {
    order,
    orderBy,
    author: authorIds,
    pages,
    postType,
    perPage,
    offset,
    sticky,
    inherit,
    taxQuery,
    parents,
    format
  } = query;
  const allowedControls = (0, _utils.useAllowedControls)(attributes);
  const [showSticky, setShowSticky] = (0, _element.useState)(postType === 'post');
  const {
    postTypesTaxonomiesMap,
    postTypesSelectOptions,
    postTypeFormatSupportMap
  } = (0, _utils.usePostTypes)();
  const taxonomies = (0, _utils.useTaxonomies)(postType);
  const isPostTypeHierarchical = (0, _utils.useIsPostTypeHierarchical)(postType);
  (0, _element.useEffect)(() => {
    setShowSticky(postType === 'post');
  }, [postType]);
  const onPostTypeChange = newValue => {
    const updateQuery = {
      postType: newValue
    };
    // We need to dynamically update the `taxQuery` property,
    // by removing any not supported taxonomy from the query.
    const supportedTaxonomies = postTypesTaxonomiesMap[newValue];
    const updatedTaxQuery = Object.entries(taxQuery || {}).reduce((accumulator, [taxonomySlug, terms]) => {
      if (supportedTaxonomies.includes(taxonomySlug)) {
        accumulator[taxonomySlug] = terms;
      }
      return accumulator;
    }, {});
    updateQuery.taxQuery = !!Object.keys(updatedTaxQuery).length ? updatedTaxQuery : undefined;
    if (newValue !== 'post') {
      updateQuery.sticky = '';
    }
    // We need to reset `parents` because they are tied to each post type.
    updateQuery.parents = [];
    // Post types can register post format support with `add_post_type_support`.
    // But we need to reset the `format` property when switching to post types
    // that do not support post formats.
    const hasFormatSupport = postTypeFormatSupportMap[newValue];
    if (!hasFormatSupport) {
      updateQuery.format = [];
    }
    setQuery(updateQuery);
  };
  const [querySearch, setQuerySearch] = (0, _element.useState)(query.search);
  const onChangeDebounced = (0, _element.useCallback)((0, _compose.debounce)(() => {
    if (query.search !== querySearch) {
      setQuery({
        search: querySearch
      });
    }
  }, 250), [querySearch, query.search]);
  (0, _element.useEffect)(() => {
    onChangeDebounced();
    return onChangeDebounced.cancel;
  }, [querySearch, onChangeDebounced]);
  const showInheritControl = isTemplate && (0, _utils.isControlAllowed)(allowedControls, 'inherit');
  const showPostTypeControl = !inherit && (0, _utils.isControlAllowed)(allowedControls, 'postType') || !isTemplate;
  const postTypeControlLabel = (0, _i18n.__)('Post type');
  const postTypeControlHelp = (0, _i18n.__)('Select the type of content to display: posts, pages, or custom post types.');
  const showColumnsControl = false;
  const showOrderControl = !inherit && (0, _utils.isControlAllowed)(allowedControls, 'order') || !isTemplate;
  const showStickyControl = !inherit && showSticky && (0, _utils.isControlAllowed)(allowedControls, 'sticky') || showSticky && !isTemplate;
  const showSettingsPanel = showInheritControl || showPostTypeControl || showColumnsControl || showOrderControl || showStickyControl;
  const showTaxControl = !!taxonomies?.length && (0, _utils.isControlAllowed)(allowedControls, 'taxQuery');
  const showAuthorControl = (0, _utils.isControlAllowed)(allowedControls, 'author');
  const showSearchControl = (0, _utils.isControlAllowed)(allowedControls, 'search');
  const showParentControl = (0, _utils.isControlAllowed)(allowedControls, 'parents') && isPostTypeHierarchical;
  const postTypeHasFormatSupport = postTypeFormatSupportMap[postType];
  const showFormatControl = (0, _data.useSelect)(select => {
    // Check if the post type supports post formats and if the control is allowed.
    if (!postTypeHasFormatSupport || !(0, _utils.isControlAllowed)(allowedControls, 'format')) {
      return false;
    }
    const themeSupports = select(_coreData.store).getThemeSupports();

    // If there are no supported formats, getThemeSupports still includes the default 'standard' format,
    // and in this case the control should not be shown since the user has no other formats to choose from.
    return themeSupports.formats && themeSupports.formats.length > 0 && themeSupports.formats.some(type => type !== 'standard');
  }, [allowedControls, postTypeHasFormatSupport]);
  const showFiltersPanel = showTaxControl || showAuthorControl || showSearchControl || showParentControl || showFormatControl;
  const dropdownMenuProps = (0, _hooks.useToolsPanelDropdownMenuProps)();
  const showPostCountControl = (0, _utils.isControlAllowed)(allowedControls, 'postCount');
  const showOffSetControl = (0, _utils.isControlAllowed)(allowedControls, 'offset');
  const showPagesControl = (0, _utils.isControlAllowed)(allowedControls, 'pages');
  const showDisplayPanel = showPostCountControl || showOffSetControl || showPagesControl;
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
    children: [!!postType && /*#__PURE__*/(0, _jsxRuntime.jsx)(BlockInfo, {
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_createNewPostLink.default, {
        postType: postType
      })
    }), showSettingsPanel && /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.PanelBody, {
      title: (0, _i18n.__)('Settings'),
      children: [showInheritControl && /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.__experimentalToggleGroupControl, {
        __next40pxDefaultSize: true,
        __nextHasNoMarginBottom: true,
        label: (0, _i18n.__)('Query type'),
        isBlock: true,
        onChange: value => {
          setQuery({
            inherit: !!value
          });
        },
        help: inherit ? (0, _i18n.__)('Display a list of posts or custom post types based on the current template.') : (0, _i18n.__)('Display a list of posts or custom post types based on specific criteria.'),
        value: !!inherit,
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__experimentalToggleGroupControlOption, {
          value: true,
          label: (0, _i18n.__)('Default')
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__experimentalToggleGroupControlOption, {
          value: false,
          label: (0, _i18n.__)('Custom')
        })]
      }), showPostTypeControl && (postTypesSelectOptions.length > 2 ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.SelectControl, {
        __nextHasNoMarginBottom: true,
        __next40pxDefaultSize: true,
        options: postTypesSelectOptions,
        value: postType,
        label: postTypeControlLabel,
        onChange: onPostTypeChange,
        help: postTypeControlHelp
      }) : /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__experimentalToggleGroupControl, {
        __nextHasNoMarginBottom: true,
        __next40pxDefaultSize: true,
        isBlock: true,
        value: postType,
        label: postTypeControlLabel,
        onChange: onPostTypeChange,
        help: postTypeControlHelp,
        children: postTypesSelectOptions.map(option => /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__experimentalToggleGroupControlOption, {
          value: option.value,
          label: option.label
        }, option.value))
      })), showColumnsControl && /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_components.RangeControl, {
          __nextHasNoMarginBottom: true,
          __next40pxDefaultSize: true,
          label: (0, _i18n.__)('Columns'),
          value: displayLayout.columns,
          onChange: value => setDisplayLayout({
            columns: value
          }),
          min: 2,
          max: Math.max(6, displayLayout.columns)
        }), displayLayout.columns > 6 && /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Notice, {
          status: "warning",
          isDismissible: false,
          children: (0, _i18n.__)('This column count exceeds the recommended amount and may cause visual breakage.')
        })]
      }), showOrderControl && /*#__PURE__*/(0, _jsxRuntime.jsx)(_orderControl.default, {
        order,
        orderBy,
        onChange: setQuery
      }), showStickyControl && /*#__PURE__*/(0, _jsxRuntime.jsx)(_stickyControl.default, {
        value: sticky,
        onChange: value => setQuery({
          sticky: value
        })
      })]
    }), !inherit && showDisplayPanel && /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.__experimentalToolsPanel, {
      className: "block-library-query-toolspanel__display",
      label: (0, _i18n.__)('Display'),
      resetAll: () => {
        setQuery({
          offset: 0,
          pages: 0
        });
      },
      dropdownMenuProps: dropdownMenuProps,
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__experimentalToolsPanelItem, {
        label: (0, _i18n.__)('Items per page'),
        hasValue: () => perPage > 0,
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_perPageControl.default, {
          perPage: perPage,
          offset: offset,
          onChange: setQuery
        })
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__experimentalToolsPanelItem, {
        label: (0, _i18n.__)('Offset'),
        hasValue: () => offset > 0,
        onDeselect: () => setQuery({
          offset: 0
        }),
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_offsetControls.default, {
          offset: offset,
          onChange: setQuery
        })
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__experimentalToolsPanelItem, {
        label: (0, _i18n.__)('Max pages to show'),
        hasValue: () => pages > 0,
        onDeselect: () => setQuery({
          pages: 0
        }),
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_pagesControl.default, {
          pages: pages,
          onChange: setQuery
        })
      })]
    }), !inherit && showFiltersPanel && /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.__experimentalToolsPanel, {
      className: "block-library-query-toolspanel__filters" // unused but kept for backward compatibility
      ,
      label: (0, _i18n.__)('Filters'),
      resetAll: () => {
        setQuery({
          author: '',
          parents: [],
          search: '',
          taxQuery: null,
          format: []
        });
        setQuerySearch('');
      },
      dropdownMenuProps: dropdownMenuProps,
      children: [showTaxControl && /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__experimentalToolsPanelItem, {
        label: (0, _i18n.__)('Taxonomies'),
        hasValue: () => Object.values(taxQuery || {}).some(terms => !!terms.length),
        onDeselect: () => setQuery({
          taxQuery: null
        }),
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_taxonomyControls.TaxonomyControls, {
          onChange: setQuery,
          query: query
        })
      }), showAuthorControl && /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__experimentalToolsPanelItem, {
        hasValue: () => !!authorIds,
        label: (0, _i18n.__)('Authors'),
        onDeselect: () => setQuery({
          author: ''
        }),
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_authorControl.default, {
          value: authorIds,
          onChange: setQuery
        })
      }), showSearchControl && /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__experimentalToolsPanelItem, {
        hasValue: () => !!querySearch,
        label: (0, _i18n.__)('Keyword'),
        onDeselect: () => setQuerySearch(''),
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.TextControl, {
          __nextHasNoMarginBottom: true,
          __next40pxDefaultSize: true,
          label: (0, _i18n.__)('Keyword'),
          value: querySearch,
          onChange: setQuerySearch
        })
      }), showParentControl && /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__experimentalToolsPanelItem, {
        hasValue: () => !!parents?.length,
        label: (0, _i18n.__)('Parents'),
        onDeselect: () => setQuery({
          parents: []
        }),
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_parentControl.default, {
          parents: parents,
          postType: postType,
          onChange: setQuery
        })
      }), showFormatControl && /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__experimentalToolsPanelItem, {
        hasValue: () => !!format?.length,
        label: (0, _i18n.__)('Formats'),
        onDeselect: () => setQuery({
          format: []
        }),
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_formatControls.default, {
          onChange: setQuery,
          query: query
        })
      })]
    })]
  });
}
//# sourceMappingURL=index.js.map