"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _clsx = _interopRequireDefault(require("clsx"));
var _i18n = require("@wordpress/i18n");
var _htmlEntities = require("@wordpress/html-entities");
var _element = require("@wordpress/element");
var _date = require("@wordpress/date");
var _icons = require("@wordpress/icons");
var _components = require("@wordpress/components");
var _data = require("@wordpress/data");
var _coreData = require("@wordpress/core-data");
var _constants = require("../../utils/constants");
var _link = _interopRequireWildcard(require("../routes/link"));
var _media = _interopRequireDefault(require("../media"));
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; }
/**
 * External dependencies
 */

/**
 * WordPress dependencies
 */

/**
 * Internal dependencies
 */

// See https://github.com/WordPress/gutenberg/issues/55886
// We do not support custom statutes at the moment.
const STATUSES = [{
  value: 'draft',
  label: (0, _i18n.__)('Draft'),
  icon: _icons.drafts,
  description: (0, _i18n.__)('Not ready to publish.')
}, {
  value: 'future',
  label: (0, _i18n.__)('Scheduled'),
  icon: _icons.scheduled,
  description: (0, _i18n.__)('Publish automatically on a chosen date.')
}, {
  value: 'pending',
  label: (0, _i18n.__)('Pending Review'),
  icon: _icons.pending,
  description: (0, _i18n.__)('Waiting for review before publishing.')
}, {
  value: 'private',
  label: (0, _i18n.__)('Private'),
  icon: _icons.notAllowed,
  description: (0, _i18n.__)('Only visible to site admins and editors.')
}, {
  value: 'publish',
  label: (0, _i18n.__)('Published'),
  icon: _icons.published,
  description: (0, _i18n.__)('Visible to everyone.')
}, {
  value: 'trash',
  label: (0, _i18n.__)('Trash'),
  icon: _icons.trash
}];
const getFormattedDate = dateToDisplay => (0, _date.dateI18n)((0, _date.getSettings)().formats.datetimeAbbreviated, (0, _date.getDate)(dateToDisplay));
function FeaturedImage({
  item,
  viewType
}) {
  const isDisabled = item.status === 'trash';
  const {
    onClick
  } = (0, _link.useLink)({
    postId: item.id,
    postType: item.type,
    canvas: 'edit'
  });
  const hasMedia = !!item.featured_media;
  const size = viewType === _constants.LAYOUT_GRID ? ['large', 'full', 'medium', 'thumbnail'] : ['thumbnail', 'medium', 'large', 'full'];
  const media = hasMedia ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_media.default, {
    className: "edit-site-post-list__featured-image",
    id: item.featured_media,
    size: size
  }) : null;
  const renderButton = viewType !== _constants.LAYOUT_LIST && !isDisabled;
  return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
    className: `edit-site-post-list__featured-image-wrapper is-layout-${viewType}`,
    children: renderButton ? /*#__PURE__*/(0, _jsxRuntime.jsx)("button", {
      className: "edit-site-post-list__featured-image-button",
      type: "button",
      onClick: onClick,
      "aria-label": item.title?.rendered || (0, _i18n.__)('(no title)'),
      children: media
    }) : media
  });
}
function PostStatusField({
  item
}) {
  const status = STATUSES.find(({
    value
  }) => value === item.status);
  const label = status?.label || item.status;
  const icon = status?.icon;
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.__experimentalHStack, {
    alignment: "left",
    spacing: 0,
    children: [icon && /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      className: "edit-site-post-list__status-icon",
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Icon, {
        icon: icon
      })
    }), /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
      children: label
    })]
  });
}
function PostAuthorField({
  item
}) {
  const {
    text,
    imageUrl
  } = (0, _data.useSelect)(select => {
    const {
      getUser
    } = select(_coreData.store);
    const user = getUser(item.author);
    return {
      imageUrl: user?.avatar_urls?.[48],
      text: user?.name
    };
  }, [item]);
  const [isImageLoaded, setIsImageLoaded] = (0, _element.useState)(false);
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.__experimentalHStack, {
    alignment: "left",
    spacing: 0,
    children: [!!imageUrl && /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      className: (0, _clsx.default)('page-templates-author-field__avatar', {
        'is-loaded': isImageLoaded
      }),
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)("img", {
        onLoad: () => setIsImageLoaded(true),
        alt: (0, _i18n.__)('Author avatar'),
        src: imageUrl
      })
    }), !imageUrl && /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      className: "page-templates-author-field__icon",
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Icon, {
        icon: _icons.commentAuthorAvatar
      })
    }), /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
      className: "page-templates-author-field__name",
      children: text
    })]
  });
}
function usePostFields(viewType) {
  const {
    records: authors,
    isResolving: isLoadingAuthors
  } = (0, _coreData.useEntityRecords)('root', 'user', {
    per_page: -1
  });
  const {
    frontPageId,
    postsPageId
  } = (0, _data.useSelect)(select => {
    const {
      getEntityRecord
    } = select(_coreData.store);
    const siteSettings = getEntityRecord('root', 'site');
    return {
      frontPageId: siteSettings?.page_on_front,
      postsPageId: siteSettings?.page_for_posts
    };
  }, []);
  const fields = (0, _element.useMemo)(() => [{
    id: 'featured-image',
    label: (0, _i18n.__)('Featured Image'),
    getValue: ({
      item
    }) => item.featured_media,
    render: ({
      item
    }) => /*#__PURE__*/(0, _jsxRuntime.jsx)(FeaturedImage, {
      item: item,
      viewType: viewType
    }),
    enableSorting: false
  }, {
    label: (0, _i18n.__)('Title'),
    id: 'title',
    type: 'text',
    getValue: ({
      item
    }) => typeof item.title === 'string' ? item.title : item.title?.raw,
    render: ({
      item
    }) => {
      const addLink = [_constants.LAYOUT_TABLE, _constants.LAYOUT_GRID].includes(viewType) && item.status !== 'trash';
      const renderedTitle = typeof item.title === 'string' ? item.title : item.title?.rendered;
      const title = addLink ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_link.default, {
        params: {
          postId: item.id,
          postType: item.type,
          canvas: 'edit'
        },
        children: (0, _htmlEntities.decodeEntities)(renderedTitle) || (0, _i18n.__)('(no title)')
      }) : /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
        children: (0, _htmlEntities.decodeEntities)(renderedTitle) || (0, _i18n.__)('(no title)')
      });
      let suffix = '';
      if (item.id === frontPageId) {
        suffix = /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
          className: "edit-site-post-list__title-badge",
          children: (0, _i18n.__)('Homepage')
        });
      } else if (item.id === postsPageId) {
        suffix = /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
          className: "edit-site-post-list__title-badge",
          children: (0, _i18n.__)('Posts Page')
        });
      }
      return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.__experimentalHStack, {
        className: "edit-site-post-list__title",
        alignment: "center",
        justify: "flex-start",
        children: [title, suffix]
      });
    },
    enableHiding: false
  }, {
    label: (0, _i18n.__)('Author'),
    id: 'author',
    type: 'integer',
    elements: authors?.map(({
      id,
      name
    }) => ({
      value: id,
      label: name
    })) || [],
    render: PostAuthorField,
    sort: (a, b, direction) => {
      const nameA = a._embedded?.author?.[0]?.name || '';
      const nameB = b._embedded?.author?.[0]?.name || '';
      return direction === 'asc' ? nameA.localeCompare(nameB) : nameB.localeCompare(nameA);
    }
  }, {
    label: (0, _i18n.__)('Status'),
    id: 'status',
    type: 'text',
    elements: STATUSES,
    render: PostStatusField,
    Edit: 'radio',
    enableSorting: false,
    filterBy: {
      operators: [_constants.OPERATOR_IS_ANY]
    }
  }, {
    label: (0, _i18n.__)('Date'),
    id: 'date',
    type: 'datetime',
    render: ({
      item
    }) => {
      const isDraftOrPrivate = ['draft', 'private'].includes(item.status);
      if (isDraftOrPrivate) {
        return (0, _element.createInterpolateElement)((0, _i18n.sprintf)(/* translators: %s: page creation date */
        (0, _i18n.__)('<span>Modified: <time>%s</time></span>'), getFormattedDate(item.date)), {
          span: /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {}),
          time: /*#__PURE__*/(0, _jsxRuntime.jsx)("time", {})
        });
      }
      const isScheduled = item.status === 'future';
      if (isScheduled) {
        return (0, _element.createInterpolateElement)((0, _i18n.sprintf)(/* translators: %s: page creation date */
        (0, _i18n.__)('<span>Scheduled: <time>%s</time></span>'), getFormattedDate(item.date)), {
          span: /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {}),
          time: /*#__PURE__*/(0, _jsxRuntime.jsx)("time", {})
        });
      }
      const isPublished = item.status === 'publish';
      if (isPublished) {
        return (0, _element.createInterpolateElement)((0, _i18n.sprintf)(/* translators: %s: page creation time */
        (0, _i18n.__)('<span>Published: <time>%s</time></span>'), getFormattedDate(item.date)), {
          span: /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {}),
          time: /*#__PURE__*/(0, _jsxRuntime.jsx)("time", {})
        });
      }

      // Pending posts show the modified date if it's newer.
      const dateToDisplay = (0, _date.getDate)(item.modified) > (0, _date.getDate)(item.date) ? item.modified : item.date;
      const isPending = item.status === 'pending';
      if (isPending) {
        return (0, _element.createInterpolateElement)((0, _i18n.sprintf)(/* translators: %s: the newest of created or modified date for the page */
        (0, _i18n.__)('<span>Modified: <time>%s</time></span>'), getFormattedDate(dateToDisplay)), {
          span: /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {}),
          time: /*#__PURE__*/(0, _jsxRuntime.jsx)("time", {})
        });
      }

      // Unknow status.
      return /*#__PURE__*/(0, _jsxRuntime.jsx)("time", {
        children: getFormattedDate(item.date)
      });
    }
  }, {
    id: 'comment_status',
    label: (0, _i18n.__)('Discussion'),
    type: 'text',
    Edit: 'radio',
    enableSorting: false,
    filterBy: {
      operators: []
    },
    elements: [{
      value: 'open',
      label: (0, _i18n.__)('Open'),
      description: (0, _i18n.__)('Visitors can add new comments and replies.')
    }, {
      value: 'closed',
      label: (0, _i18n.__)('Closed'),
      description: (0, _i18n.__)('Visitors cannot add new comments or replies. Existing comments remain visible.')
    }]
  }], [authors, viewType, frontPageId, postsPageId]);
  return {
    isLoading: isLoadingAuthors,
    fields
  };
}
var _default = exports.default = usePostFields;
//# sourceMappingURL=index.js.map