"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.ErrorBoundary = void 0;
var _base = _interopRequireDefault(require("@emotion/styled/base"));
var _truncate2 = _interopRequireDefault(require("lodash/truncate"));
var _react = _interopRequireDefault(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _reactPolyglot = require("react-polyglot");
var _yaml = _interopRequireDefault(require("yaml"));
var _copyTextToClipboard = _interopRequireDefault(require("copy-text-to-clipboard"));
var _decapCmsLibUtil = require("decap-cms-lib-util");
var _decapCmsUiDefault = require("decap-cms-ui-default");
var _cleanStack = _interopRequireDefault(require("clean-stack"));
var _react2 = require("@emotion/react");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
const ISSUE_URL = 'https://github.com/decaporg/decap-cms/issues/new?';
function getIssueTemplate({
  version,
  provider,
  browser,
  config
}) {
  return `
**Describe the bug**

**To Reproduce**

**Expected behavior**

**Screenshots**

**Applicable Versions:**
 - Decap CMS version: \`${version}\`
 - Git provider: \`${provider}\`
 - Browser version: \`${browser}\`

**CMS configuration**
\`\`\`
${config}
\`\`\`

**Additional context**
`;
}
function buildIssueTemplate({
  config
}) {
  let version = '';
  if (typeof DECAP_CMS_VERSION === 'string') {
    version = `decap-cms@${DECAP_CMS_VERSION}`;
  } else if (typeof "3.3.2" === 'string') {
    version = `decap-cms-app@${"3.3.2"}`;
  }
  const template = getIssueTemplate({
    version,
    provider: config.backend.name,
    browser: navigator.userAgent,
    config: _yaml.default.stringify(config)
  });
  return template;
}
function buildIssueUrl({
  title,
  config
}) {
  try {
    const body = buildIssueTemplate({
      config
    });
    const params = new URLSearchParams();
    params.append('title', (0, _truncate2.default)(title, {
      length: 100
    }));
    params.append('body', (0, _truncate2.default)(body, {
      length: 4000,
      omission: '\n...'
    }));
    params.append('labels', 'type: bug');
    return `${ISSUE_URL}${params.toString()}`;
  } catch (e) {
    console.log(e);
    return `${ISSUE_URL}template=bug_report.md`;
  }
}
const ErrorBoundaryContainer = /*#__PURE__*/(0, _base.default)("div", {
  target: "emw4gx72",
  label: "ErrorBoundaryContainer"
})("padding:40px;h1{font-size:28px;color:", _decapCmsUiDefault.colors.text, ";}h2{font-size:20px;}strong{color:", _decapCmsUiDefault.colors.textLead, ";font-weight:500;}hr{width:200px;margin:30px 0;border:0;height:1px;background-color:", _decapCmsUiDefault.colors.text, ";}a{color:", _decapCmsUiDefault.colors.active, ";}" + (process.env.NODE_ENV === "production" ? "" : "/*# sourceMappingURL=data:application/json;charset=utf-8;base64,[encoded data, 7116 characters] */"));
const PrivacyWarning = /*#__PURE__*/(0, _base.default)("span", {
  target: "emw4gx71",
  label: "PrivacyWarning"
})("color:", _decapCmsUiDefault.colors.text, ";" + (process.env.NODE_ENV === "production" ? "" : "/*# sourceMappingURL=data:application/json;charset=utf-8;base64,[encoded data, 7116 characters] */"));
const CopyButton = /*#__PURE__*/(0, _base.default)("button", {
  target: "emw4gx70",
  label: "CopyButton"
})(_decapCmsUiDefault.buttons.button, ";", _decapCmsUiDefault.buttons.default, ";", _decapCmsUiDefault.buttons.gray, ";display:block;margin:12px 0;" + (process.env.NODE_ENV === "production" ? "" : "/*# sourceMappingURL=data:application/json;charset=utf-8;base64,[encoded data, 7116 characters] */"));
function RecoveredEntry({
  entry,
  t
}) {
  console.log(entry);
  return (0, _react2.jsx)(_react.default.Fragment, null, (0, _react2.jsx)("hr", null), (0, _react2.jsx)("h2", null, t('ui.errorBoundary.recoveredEntry.heading')), (0, _react2.jsx)("strong", null, t('ui.errorBoundary.recoveredEntry.warning')), (0, _react2.jsx)(CopyButton, {
    onClick: () => (0, _copyTextToClipboard.default)(entry)
  }, t('ui.errorBoundary.recoveredEntry.copyButtonLabel')), (0, _react2.jsx)("pre", null, (0, _react2.jsx)("code", null, entry)));
}
class ErrorBoundary extends _react.default.Component {
  constructor(...args) {
    super(...args);
    _defineProperty(this, "state", {
      hasError: false,
      errorMessage: '',
      errorTitle: '',
      backup: ''
    });
  }
  static getDerivedStateFromError(error) {
    console.error(error);
    return {
      hasError: true,
      errorMessage: (0, _cleanStack.default)(error.stack, {
        basePath: window.location.origin || ''
      }),
      errorTitle: error.toString()
    };
  }
  shouldComponentUpdate(nextProps, nextState) {
    if (this.props.showBackup) {
      return this.state.errorMessage !== nextState.errorMessage || this.state.backup !== nextState.backup;
    }
    return true;
  }
  async componentDidUpdate() {
    if (this.props.showBackup) {
      const backup = await _decapCmsLibUtil.localForage.getItem('backup');
      backup && console.log(backup);
      this.setState({
        backup
      });
    }
  }
  render() {
    const {
      hasError,
      errorMessage,
      backup,
      errorTitle
    } = this.state;
    const {
      showBackup,
      t
    } = this.props;
    if (!hasError) {
      return this.props.children;
    }
    return (0, _react2.jsx)(ErrorBoundaryContainer, null, (0, _react2.jsx)("h1", null, t('ui.errorBoundary.title')), (0, _react2.jsx)("p", null, (0, _react2.jsx)("span", null, t('ui.errorBoundary.details')), (0, _react2.jsx)("a", {
      href: buildIssueUrl({
        title: errorTitle,
        config: this.props.config
      }),
      target: "_blank",
      rel: "noopener noreferrer",
      "data-testid": "issue-url"
    }, t('ui.errorBoundary.reportIt'))), (0, _react2.jsx)("p", null, t('ui.errorBoundary.privacyWarning').split('\n').map((item, index) => (0, _react2.jsx)(_react.default.Fragment, null, (0, _react2.jsx)(PrivacyWarning, {
      key: index
    }, item), (0, _react2.jsx)("br", null)))), (0, _react2.jsx)("hr", null), (0, _react2.jsx)("h2", null, t('ui.errorBoundary.detailsHeading')), (0, _react2.jsx)("p", null, errorMessage), backup && showBackup && (0, _react2.jsx)(RecoveredEntry, {
      entry: backup,
      t: t
    }));
  }
}
exports.ErrorBoundary = ErrorBoundary;
_defineProperty(ErrorBoundary, "propTypes", {
  children: _propTypes.default.node,
  t: _propTypes.default.func.isRequired,
  config: _propTypes.default.object.isRequired
});
var _default = exports.default = (0, _reactPolyglot.translate)()(ErrorBoundary);