"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = PageTemplates;
var _i18n = require("@wordpress/i18n");
var _element = require("@wordpress/element");
var _coreData = require("@wordpress/core-data");
var _dataviews = require("@wordpress/dataviews");
var _router = require("@wordpress/router");
var _editor = require("@wordpress/editor");
var _page = _interopRequireDefault(require("../page"));
var _addNewTemplate = _interopRequireDefault(require("../add-new-template"));
var _constants = require("../../utils/constants");
var _lockUnlock = require("../../lock-unlock");
var _dataviewsActions = require("../dataviews-actions");
var _fields = require("./fields");
var _jsxRuntime = require("react/jsx-runtime");
/**
 * WordPress dependencies
 */

/**
 * Internal dependencies
 */

const {
  usePostActions
} = (0, _lockUnlock.unlock)(_editor.privateApis);
const {
  useHistory,
  useLocation
} = (0, _lockUnlock.unlock)(_router.privateApis);
const {
  useEntityRecordsWithPermissions
} = (0, _lockUnlock.unlock)(_coreData.privateApis);
const EMPTY_ARRAY = [];
const defaultLayouts = {
  [_constants.LAYOUT_TABLE]: {
    fields: ['template', 'author'],
    layout: {
      primaryField: 'title',
      combinedFields: [{
        id: 'template',
        label: (0, _i18n.__)('Template'),
        children: ['title', 'description'],
        direction: 'vertical'
      }],
      styles: {
        template: {
          maxWidth: 400,
          minWidth: 320
        },
        preview: {
          width: '1%'
        },
        author: {
          width: '1%'
        }
      }
    }
  },
  [_constants.LAYOUT_GRID]: {
    fields: ['title', 'description', 'author'],
    layout: {
      mediaField: 'preview',
      primaryField: 'title',
      columnFields: ['description']
    }
  },
  [_constants.LAYOUT_LIST]: {
    fields: ['title', 'description', 'author'],
    layout: {
      primaryField: 'title',
      mediaField: 'preview'
    }
  }
};
const DEFAULT_VIEW = {
  type: _constants.LAYOUT_GRID,
  search: '',
  page: 1,
  perPage: 20,
  sort: {
    field: 'title',
    direction: 'asc'
  },
  fields: defaultLayouts[_constants.LAYOUT_GRID].fields,
  layout: defaultLayouts[_constants.LAYOUT_GRID].layout,
  filters: []
};
function PageTemplates() {
  const {
    params
  } = useLocation();
  const {
    activeView = 'all',
    layout,
    postId
  } = params;
  const [selection, setSelection] = (0, _element.useState)([postId]);
  const defaultView = (0, _element.useMemo)(() => {
    const usedType = layout !== null && layout !== void 0 ? layout : DEFAULT_VIEW.type;
    return {
      ...DEFAULT_VIEW,
      type: usedType,
      layout: defaultLayouts[usedType].layout,
      fields: defaultLayouts[usedType].fields,
      filters: activeView !== 'all' ? [{
        field: 'author',
        operator: 'isAny',
        value: [activeView]
      }] : []
    };
  }, [layout, activeView]);
  const [view, setView] = (0, _element.useState)(defaultView);
  (0, _element.useEffect)(() => {
    setView(currentView => ({
      ...currentView,
      filters: activeView !== 'all' ? [{
        field: 'author',
        operator: _constants.OPERATOR_IS_ANY,
        value: [activeView]
      }] : []
    }));
  }, [activeView]);
  const {
    records,
    isResolving: isLoadingData
  } = useEntityRecordsWithPermissions('postType', _constants.TEMPLATE_POST_TYPE, {
    per_page: -1
  });
  const history = useHistory();
  const onChangeSelection = (0, _element.useCallback)(items => {
    setSelection(items);
    if (view?.type === _constants.LAYOUT_LIST) {
      history.push({
        ...params,
        postId: items.length === 1 ? items[0] : undefined
      });
    }
  }, [history, params, view?.type]);
  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)(() => [_fields.previewField, _fields.titleField, _fields.descriptionField, {
    ..._fields.authorField,
    elements: authors
  }], [authors]);
  const {
    data,
    paginationInfo
  } = (0, _element.useMemo)(() => {
    return (0, _dataviews.filterSortAndPaginate)(records, view, fields);
  }, [records, view, fields]);
  const postTypeActions = usePostActions({
    postType: _constants.TEMPLATE_POST_TYPE,
    context: 'list'
  });
  const editAction = (0, _dataviewsActions.useEditPostAction)();
  const actions = (0, _element.useMemo)(() => [editAction, ...postTypeActions], [postTypeActions, editAction]);
  const onChangeView = (0, _element.useCallback)(newView => {
    if (newView.type !== view.type) {
      history.push({
        ...params,
        layout: newView.type
      });
    }
    setView(newView);
  }, [view.type, setView, history, params]);
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_page.default, {
    className: "edit-site-page-templates",
    title: (0, _i18n.__)('Templates'),
    actions: /*#__PURE__*/(0, _jsxRuntime.jsx)(_addNewTemplate.default, {}),
    children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_dataviews.DataViews, {
      paginationInfo: paginationInfo,
      fields: fields,
      actions: actions,
      data: data,
      isLoading: isLoadingData,
      view: view,
      onChangeView: onChangeView,
      onChangeSelection: onChangeSelection,
      selection: selection,
      defaultLayouts: defaultLayouts
    }, activeView)
  });
}
//# sourceMappingURL=index.js.map