"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 _url = require("@wordpress/url");
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 _compose = require("@wordpress/compose");
var _jsxRuntime = require("react/jsx-runtime");
/**
 * WordPress dependencies
 */

/**
 * Internal dependencies
 */

const {
  usePostActions,
  templateTitleField
} = (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]: {
    showMedia: false,
    layout: {
      styles: {
        author: {
          width: '1%'
        }
      }
    }
  },
  [_constants.LAYOUT_GRID]: {
    showMedia: true
  },
  [_constants.LAYOUT_LIST]: {
    showMedia: false
  }
};
const DEFAULT_VIEW = {
  type: _constants.LAYOUT_GRID,
  search: '',
  page: 1,
  perPage: 20,
  sort: {
    field: 'title',
    direction: 'asc'
  },
  titleField: 'title',
  descriptionField: 'description',
  mediaField: 'preview',
  fields: ['author'],
  filters: [],
  ...defaultLayouts[_constants.LAYOUT_GRID]
};
function PageTemplates() {
  const {
    path,
    query
  } = useLocation();
  const {
    activeView = 'all',
    layout,
    postId
  } = query;
  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,
      filters: activeView !== 'all' ? [{
        field: 'author',
        operator: 'isAny',
        value: [activeView]
      }] : [],
      ...defaultLayouts[usedType]
    };
  }, [layout, activeView]);
  const [view, setView] = (0, _element.useState)(defaultView);

  // Sync the layout from the URL to the view state.
  (0, _element.useEffect)(() => {
    setView(currentView => ({
      ...currentView,
      type: layout !== null && layout !== void 0 ? layout : DEFAULT_VIEW.type
    }));
  }, [setView, layout]);

  // Sync the active view from the URL to the view state.
  (0, _element.useEffect)(() => {
    setView(currentView => ({
      ...currentView,
      filters: activeView !== 'all' ? [{
        field: 'author',
        operator: _constants.OPERATOR_IS_ANY,
        value: [activeView]
      }] : []
    }));
  }, [setView, 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.navigate((0, _url.addQueryArgs)(path, {
        postId: items.length === 1 ? items[0] : undefined
      }));
    }
  }, [history, path, 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, templateTitleField, _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, _compose.useEvent)(newView => {
    setView(newView);
    if (newView.type !== layout) {
      history.navigate((0, _url.addQueryArgs)(path, {
        layout: newView.type
      }));
    }
  });
  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,
      isItemClickable: () => true,
      onClickItem: ({
        id
      }) => {
        history.navigate(`/wp_template/${id}?canvas=edit`);
      },
      selection: selection,
      defaultLayouts: defaultLayouts
    }, activeView)
  });
}
//# sourceMappingURL=index.js.map