"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _i18n = require("@wordpress/i18n");
var _components = require("@wordpress/components");
var _date = require("@wordpress/date");
var _coreData = require("@wordpress/core-data");
var _data = require("@wordpress/data");
var _blockEditor = require("@wordpress/block-editor");
var _keycodes = require("@wordpress/keycodes");
var _lockUnlock = require("../../../lock-unlock");
var _jsxRuntime = require("react/jsx-runtime");
/**
 * WordPress dependencies
 */

/**
 * Internal dependencies
 */

const DAY_IN_MILLISECONDS = 60 * 60 * 1000 * 24;
const {
  getGlobalStylesChanges
} = (0, _lockUnlock.unlock)(_blockEditor.privateApis);
function ChangesSummary({
  revision,
  previousRevision
}) {
  const changes = getGlobalStylesChanges(revision, previousRevision, {
    maxResults: 7
  });
  if (!changes.length) {
    return null;
  }
  return /*#__PURE__*/(0, _jsxRuntime.jsx)("ul", {
    "data-testid": "global-styles-revision-changes",
    className: "edit-site-global-styles-screen-revisions__changes",
    children: changes.map(change => /*#__PURE__*/(0, _jsxRuntime.jsx)("li", {
      children: change
    }, change))
  });
}

/**
 * Returns a button label for the revision.
 *
 * @param {string|number} id                    A revision object.
 * @param {string}        authorDisplayName     Author name.
 * @param {string}        formattedModifiedDate Revision modified date formatted.
 * @param {boolean}       areStylesEqual        Whether the revision matches the current editor styles.
 * @return {string} Translated label.
 */
function getRevisionLabel(id, authorDisplayName, formattedModifiedDate, areStylesEqual) {
  if ('parent' === id) {
    return (0, _i18n.__)('Reset the styles to the theme defaults');
  }
  if ('unsaved' === id) {
    return (0, _i18n.sprintf)(/* translators: %s: author display name */
    (0, _i18n.__)('Unsaved changes by %s'), authorDisplayName);
  }
  return areStylesEqual ? (0, _i18n.sprintf)(
  // translators: 1: author display name. 2: revision creation date.
  (0, _i18n.__)('Changes saved by %1$s on %2$s. This revision matches current editor styles.'), authorDisplayName, formattedModifiedDate) : (0, _i18n.sprintf)(
  // translators: 1: author display name. 2: revision creation date.
  (0, _i18n.__)('Changes saved by %1$s on %2$s'), authorDisplayName, formattedModifiedDate);
}

/**
 * Returns a rendered list of revisions buttons.
 *
 * @typedef {Object} props
 * @property {Array<Object>} userRevisions      A collection of user revisions.
 * @property {number}        selectedRevisionId The id of the currently-selected revision.
 * @property {Function}      onChange           Callback fired when a revision is selected.
 *
 * @param    {props}         Component          props.
 * @return {JSX.Element} The modal component.
 */
function RevisionsButtons({
  userRevisions,
  selectedRevisionId,
  onChange,
  canApplyRevision,
  onApplyRevision
}) {
  const {
    currentThemeName,
    currentUser
  } = (0, _data.useSelect)(select => {
    const {
      getCurrentTheme,
      getCurrentUser
    } = select(_coreData.store);
    const currentTheme = getCurrentTheme();
    return {
      currentThemeName: currentTheme?.name?.rendered || currentTheme?.stylesheet,
      currentUser: getCurrentUser()
    };
  }, []);
  const dateNowInMs = (0, _date.getDate)().getTime();
  const {
    datetimeAbbreviated
  } = (0, _date.getSettings)().formats;
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Composite, {
    orientation: "vertical",
    className: "edit-site-global-styles-screen-revisions__revisions-list",
    "aria-label": (0, _i18n.__)('Global styles revisions list'),
    role: "listbox",
    children: userRevisions.map((revision, index) => {
      const {
        id,
        author,
        modified
      } = revision;
      const isUnsaved = 'unsaved' === id;
      // Unsaved changes are created by the current user.
      const revisionAuthor = isUnsaved ? currentUser : author;
      const authorDisplayName = revisionAuthor?.name || (0, _i18n.__)('User');
      const authorAvatar = revisionAuthor?.avatar_urls?.['48'];
      const isFirstItem = index === 0;
      const isSelected = selectedRevisionId ? selectedRevisionId === id : isFirstItem;
      const areStylesEqual = !canApplyRevision && isSelected;
      const isReset = 'parent' === id;
      const modifiedDate = (0, _date.getDate)(modified);
      const displayDate = modified && dateNowInMs - modifiedDate.getTime() > DAY_IN_MILLISECONDS ? (0, _date.dateI18n)(datetimeAbbreviated, modifiedDate) : (0, _date.humanTimeDiff)(modified);
      const revisionLabel = getRevisionLabel(id, authorDisplayName, (0, _date.dateI18n)(datetimeAbbreviated, modifiedDate), areStylesEqual);
      return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.Composite.Item, {
        className: "edit-site-global-styles-screen-revisions__revision-item",
        "aria-current": isSelected,
        role: "option",
        onKeyDown: event => {
          const {
            keyCode
          } = event;
          if (keyCode === _keycodes.ENTER || keyCode === _keycodes.SPACE) {
            onChange(revision);
          }
        },
        onClick: event => {
          event.preventDefault();
          onChange(revision);
        },
        "aria-selected": isSelected,
        "aria-label": revisionLabel,
        render: /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {}),
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
          className: "edit-site-global-styles-screen-revisions__revision-item-wrapper",
          children: isReset ? /*#__PURE__*/(0, _jsxRuntime.jsxs)("span", {
            className: "edit-site-global-styles-screen-revisions__description",
            children: [(0, _i18n.__)('Default styles'), /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
              className: "edit-site-global-styles-screen-revisions__meta",
              children: currentThemeName
            })]
          }) : /*#__PURE__*/(0, _jsxRuntime.jsxs)("span", {
            className: "edit-site-global-styles-screen-revisions__description",
            children: [isUnsaved ? /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
              className: "edit-site-global-styles-screen-revisions__date",
              children: (0, _i18n.__)('(Unsaved)')
            }) : /*#__PURE__*/(0, _jsxRuntime.jsx)("time", {
              className: "edit-site-global-styles-screen-revisions__date",
              dateTime: modified,
              children: displayDate
            }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("span", {
              className: "edit-site-global-styles-screen-revisions__meta",
              children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("img", {
                alt: authorDisplayName,
                src: authorAvatar
              }), authorDisplayName]
            }), isSelected && /*#__PURE__*/(0, _jsxRuntime.jsx)(ChangesSummary, {
              revision: revision,
              previousRevision: index < userRevisions.length ? userRevisions[index + 1] : {}
            })]
          })
        }), isSelected && (areStylesEqual ? /*#__PURE__*/(0, _jsxRuntime.jsx)("p", {
          className: "edit-site-global-styles-screen-revisions__applied-text",
          children: (0, _i18n.__)('These styles are already applied to your site.')
        }) : /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Button, {
          size: "compact",
          variant: "primary",
          className: "edit-site-global-styles-screen-revisions__apply-button",
          onClick: onApplyRevision,
          "aria-label": (0, _i18n.__)('Apply the selected revision to your site.'),
          children: isReset ? (0, _i18n.__)('Reset to defaults') : (0, _i18n.__)('Apply')
        }))]
      }, id);
    })
  });
}
var _default = exports.default = RevisionsButtons;
//# sourceMappingURL=revisions-buttons.js.map