"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = DataviewsPatterns;
var _i18n = require("@wordpress/i18n");
var _element = require("@wordpress/element");
var _blockEditor = require("@wordpress/block-editor");
var _dataviews = require("@wordpress/dataviews");
var _compose = require("@wordpress/compose");
var _coreData = require("@wordpress/core-data");
var _editor = require("@wordpress/editor");
var _router = require("@wordpress/router");
var _page = _interopRequireDefault(require("../page"));
var _constants = require("../../utils/constants");
var _usePatternSettings = _interopRequireDefault(require("./use-pattern-settings"));
var _lockUnlock = require("../../lock-unlock");
var _usePatterns = _interopRequireWildcard(require("./use-patterns"));
var _header = _interopRequireDefault(require("./header"));
var _dataviewsActions = require("../dataviews-actions");
var _fields2 = require("./fields");
var _jsxRuntime = require("react/jsx-runtime");
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
/**
 * WordPress dependencies
 */

/**
 * Internal dependencies
 */

const {
  ExperimentalBlockEditorProvider
} = (0, _lockUnlock.unlock)(_blockEditor.privateApis);
const {
  usePostActions,
  patternTitleField
} = (0, _lockUnlock.unlock)(_editor.privateApis);
const {
  useLocation,
  useHistory
} = (0, _lockUnlock.unlock)(_router.privateApis);
const EMPTY_ARRAY = [];
const defaultLayouts = {
  [_constants.LAYOUT_TABLE]: {
    layout: {
      styles: {
        author: {
          width: '1%'
        }
      }
    }
  },
  [_constants.LAYOUT_GRID]: {
    layout: {
      badgeFields: ['sync-status']
    }
  }
};
const DEFAULT_VIEW = {
  type: _constants.LAYOUT_GRID,
  search: '',
  page: 1,
  perPage: 20,
  titleField: 'title',
  mediaField: 'preview',
  fields: ['sync-status'],
  filters: [],
  ...defaultLayouts[_constants.LAYOUT_GRID]
};
function DataviewsPatterns() {
  const {
    query: {
      postType = 'wp_block',
      categoryId: categoryIdFromURL
    }
  } = useLocation();
  const history = useHistory();
  const categoryId = categoryIdFromURL || _constants.PATTERN_DEFAULT_CATEGORY;
  const [view, setView] = (0, _element.useState)(DEFAULT_VIEW);
  const previousCategoryId = (0, _compose.usePrevious)(categoryId);
  const previousPostType = (0, _compose.usePrevious)(postType);
  const viewSyncStatus = view.filters?.find(({
    field
  }) => field === 'sync-status')?.value;
  const {
    patterns,
    isResolving
  } = (0, _usePatterns.default)(postType, categoryId, {
    search: view.search,
    syncStatus: viewSyncStatus
  });
  const {
    records
  } = (0, _coreData.useEntityRecords)('postType', _constants.TEMPLATE_PART_POST_TYPE, {
    per_page: -1
  });
  const authors = (0, _element.useMemo)(() => {
    if (!records) {
      return EMPTY_ARRAY;
    }
    const authorsSet = new Set();
    records.forEach(template => {
      authorsSet.add(template.author_text);
    });
    return Array.from(authorsSet).map(author => ({
      value: author,
      label: author
    }));
  }, [records]);
  const fields = (0, _element.useMemo)(() => {
    const _fields = [_fields2.previewField, patternTitleField];
    if (postType === _constants.PATTERN_TYPES.user) {
      _fields.push(_fields2.patternStatusField);
    } else if (postType === _constants.TEMPLATE_PART_POST_TYPE) {
      _fields.push({
        ..._fields2.templatePartAuthorField,
        elements: authors
      });
    }
    return _fields;
  }, [postType, authors]);

  // Reset the page number when the category changes.
  (0, _element.useEffect)(() => {
    if (previousCategoryId !== categoryId || previousPostType !== postType) {
      setView(prevView => ({
        ...prevView,
        page: 1
      }));
    }
  }, [categoryId, previousCategoryId, previousPostType, postType]);
  const {
    data,
    paginationInfo
  } = (0, _element.useMemo)(() => {
    // Search is managed server-side as well as filters for patterns.
    // However, the author filter in template parts is done client-side.
    const viewWithoutFilters = {
      ...view
    };
    delete viewWithoutFilters.search;
    if (postType !== _constants.TEMPLATE_PART_POST_TYPE) {
      viewWithoutFilters.filters = [];
    }
    return (0, _dataviews.filterSortAndPaginate)(patterns, viewWithoutFilters, fields);
  }, [patterns, view, fields, postType]);
  const dataWithPermissions = (0, _usePatterns.useAugmentPatternsWithPermissions)(data);
  const templatePartActions = usePostActions({
    postType: _constants.TEMPLATE_PART_POST_TYPE,
    context: 'list'
  });
  const patternActions = usePostActions({
    postType: _constants.PATTERN_TYPES.user,
    context: 'list'
  });
  const editAction = (0, _dataviewsActions.useEditPostAction)();
  const actions = (0, _element.useMemo)(() => {
    if (postType === _constants.TEMPLATE_PART_POST_TYPE) {
      return [editAction, ...templatePartActions].filter(Boolean);
    }
    return [editAction, ...patternActions].filter(Boolean);
  }, [editAction, postType, templatePartActions, patternActions]);
  const id = (0, _element.useId)();
  const settings = (0, _usePatternSettings.default)();
  // Wrap everything in a block editor provider.
  // This ensures 'styles' that are needed for the previews are synced
  // from the site editor store to the block editor store.
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(ExperimentalBlockEditorProvider, {
    settings: settings,
    children: /*#__PURE__*/(0, _jsxRuntime.jsxs)(_page.default, {
      title: (0, _i18n.__)('Patterns content'),
      className: "edit-site-page-patterns-dataviews",
      hideTitleFromUI: true,
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_header.default, {
        categoryId: categoryId,
        type: postType,
        titleId: `${id}-title`,
        descriptionId: `${id}-description`
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_dataviews.DataViews, {
        paginationInfo: paginationInfo,
        fields: fields,
        actions: actions,
        data: dataWithPermissions || EMPTY_ARRAY,
        getItemId: item => {
          var _item$name;
          return (_item$name = item.name) !== null && _item$name !== void 0 ? _item$name : item.id;
        },
        isLoading: isResolving,
        isItemClickable: item => item.type !== _constants.PATTERN_TYPES.theme,
        onClickItem: item => {
          history.navigate(`/${item.type}/${[_constants.PATTERN_TYPES.user, _constants.TEMPLATE_PART_POST_TYPE].includes(item.type) ? item.id : item.name}?canvas=edit`);
        },
        view: view,
        onChangeView: setView,
        defaultLayouts: defaultLayouts
      }, categoryId + postType)]
    })
  });
}
//# sourceMappingURL=index.js.map