"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = Tutorials;
exports.PermissionContext = exports.cmVariableContext = void 0;

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

var _react = _interopRequireWildcard(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _cloneDeep = _interopRequireDefault(require("lodash/cloneDeep"));

var ApiActions = _interopRequireWildcard(require("./apiActions"));

var _useReadmeApi2 = _interopRequireDefault(require("../../core/hooks/useReadmeApi"));

var _components = require("../../ui/components");

var _compositions = require("../../ui/compositions");

var _Body = _interopRequireDefault(require("../../ui/components/Modal/Body"));

var _Footer = _interopRequireDefault(require("../../ui/components/Modal/Footer"));

var _TutorialHero = _interopRequireDefault(require("./components/TutorialHero"));

var _stepDefaults = require("../../ui/compositions/Tutorials/Modal/constants/stepDefaults");

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

// Internal Variable Context
var cmVariableContext = typeof window !== 'undefined' ? require('@readme/syntax-highlighter/dist/index.js').cmVariableContext : /*#__PURE__*/_react["default"].createContext(); // Style

exports.cmVariableContext = cmVariableContext;
var classes = {};
/* istanbul ignore next */

if (typeof window !== 'undefined' || typeof _COMPILED_ === 'undefined') classes = {
  "slate": "#384248",
  "blue": "#118CFD",
  "green": "#12CA93",
  "red": "#E95F6A",
  "yellow": "#F7C543",
  "purple": "#8470BE",
  "graphite": "#4F5A66",
  "shale": "#939EAE",
  "chalk": "#c6cbd3",
  "ivory": "#F0F0F0",
  "lightGray": "#F8F8F8",
  "white": "#FFF",
  "Tutorial": "_1rQGm-Tutorial",
  "Tutorial-Wrapper": "_3Haqm-Tutorial-Wrapper",
  "TutorialGrid": "_1RK9j-TutorialGrid",
  "TutorialToolbar": "mIgtw-TutorialToolbar",
  "TutorialToolbar-Button": "_3BrhK-TutorialToolbar-Button",
  "TutorialToolbar-PopoverWrapper": "_1-3Vy-TutorialToolbar-PopoverWrapper",
  "TutorialToolbar-Popover": "w_eFv-TutorialToolbar-Popover",
  "TutorialToolbar-Button-Icon": "aIwUK-TutorialToolbar-Button-Icon",
  "TutorialToolbar-Button-Arrow": "_2_j-u-TutorialToolbar-Button-Arrow",
  "TutorialToolbar-Popover-Description": "Kigt4-TutorialToolbar-Popover-Description",
  "TutorialConfirmation": "_2vx5z-TutorialConfirmation",
  "TutorialConfirmation-Title": "bCl_V-TutorialConfirmation-Title",
  "TutorialConfirmation-Description": "fKFOn-TutorialConfirmation-Description"
};

var PermissionContext = /*#__PURE__*/_react["default"].createContext(false);

exports.PermissionContext = PermissionContext;

function Tutorials(props) {
  var baseUrl = props.baseUrl,
      modalTarget = props.modalTarget,
      confirmationTarget = props.confirmationTarget,
      slug = props.slug,
      referenceEnabled = props.referenceEnabled;

  var _useState = (0, _react.useState)({}),
      _useState2 = (0, _slicedToArray2["default"])(_useState, 2),
      hero = _useState2[0],
      setHero = _useState2[1];

  var _useState3 = (0, _react.useState)({}),
      _useState4 = (0, _slicedToArray2["default"])(_useState3, 2),
      onboarding = _useState4[0],
      setOnboarding = _useState4[1];

  var _useState5 = (0, _react.useState)([]),
      _useState6 = (0, _slicedToArray2["default"])(_useState5, 2),
      tutorials = _useState6[0],
      setTutorials = _useState6[1];

  var _useState7 = (0, _react.useState)(true),
      _useState8 = (0, _slicedToArray2["default"])(_useState7, 2),
      initialLoad = _useState8[0],
      setInitialLoad = _useState8[1];

  var _useState9 = (0, _react.useState)({
    open: false,
    action: 'View'
  }),
      _useState10 = (0, _slicedToArray2["default"])(_useState9, 2),
      modalMeta = _useState10[0],
      setModalMeta = _useState10[1];

  var _useState11 = (0, _react.useState)({}),
      _useState12 = (0, _slicedToArray2["default"])(_useState11, 2),
      confirmModalState = _useState12[0],
      setConfirmModal = _useState12[1];

  var _useState13 = (0, _react.useState)(false),
      _useState14 = (0, _slicedToArray2["default"])(_useState13, 2),
      moduleEnabled = _useState14[0],
      setModuleEnabled = _useState14[1];

  var _useState15 = (0, _react.useState)(),
      _useState16 = (0, _slicedToArray2["default"])(_useState15, 2),
      selectedTutorial = _useState16[0],
      setSelectedTutorial = _useState16[1];

  var _useState17 = (0, _react.useState)(props.isAdmin),
      _useState18 = (0, _slicedToArray2["default"])(_useState17, 1),
      isAdmin = _useState18[0];

  var modalRef = /*#__PURE__*/_react["default"].createRef();

  var _useReadmeApi = (0, _useReadmeApi2["default"])(baseUrl),
      response = _useReadmeApi.response,
      error = _useReadmeApi.error,
      setError = _useReadmeApi.setError,
      pendingRequest = _useReadmeApi.pendingRequest,
      initRequest = _useReadmeApi.initRequest;

  var getTutorials = function getTutorials() {
    return ApiActions.getTutorials(initRequest);
  };

  (0, _react.useEffect)(function () {
    getTutorials();
  }, []);
  (0, _react.useEffect)(function () {
    if (pendingRequest) getTutorials();
  }, [pendingRequest]);
  (0, _react.useEffect)(function () {
    if (Object.keys(response).length) setInitialLoad(false);
  }, [response]);
  (0, _react.useEffect)(function () {
    if (response.hero) setHero(response.hero);
  }, [response.hero]);
  (0, _react.useEffect)(function () {
    if (response.tutorialOnboarding) setOnboarding(response.tutorialOnboarding);
  }, [response.tutorialOnboarding]);
  (0, _react.useEffect)(function () {
    if (response.tutorials) setTutorials(response.tutorials);
  }, [response.tutorials]);
  (0, _react.useEffect)(function () {
    if ('moduleEnabled' in response) setModuleEnabled(response.moduleEnabled);
  }, [response.moduleEnabled]);
  (0, _react.useEffect)(function () {
    if (slug) {
      ApiActions.getTutorialBySlug(initRequest, {
        slug: slug
      });
      setTimeout(function () {
        return getTutorials();
      });
    }
  }, [slug]);
  (0, _react.useEffect)(function () {
    if (response.tutorial && !response.tutorialPublishToggled) {
      setSelectedTutorial(response.tutorial);
      setModalMeta({
        open: true,
        action: 'View'
      });
    }
  }, [response.tutorial]);

  var pushState = function pushState(pathSlug) {
    var urlRegexp = /https?:\/\//;

    if (!urlRegexp.test(baseUrl)) {
      var uri = pathSlug ? "".concat(baseUrl, "/tutorials/").concat(pathSlug) : "".concat(baseUrl, "/tutorials"); // eslint-disable-next-line no-restricted-globals

      history.pushState('', '', uri);
    }
  };

  var openTutorial = function openTutorial(action, tutorial) {
    setModalMeta({
      open: true,
      action: action
    }); // Allow us to differentiate based on two factors
    // What type of modal action is this? View|Create|Update
    // And is this the first time we're opening it?

    setSelectedTutorial(function (prevTutorial) {
      var prevId = prevTutorial && prevTutorial._id && prevTutorial._id.toString();

      var newId = tutorial && tutorial._id && tutorial._id.toString() || '';

      if (prevId !== newId && action === 'Create') {
        return _objectSpread({}, (0, _cloneDeep["default"])(_stepDefaults.DEFAULT_TUTORIAL));
      } else if (prevId !== newId) {
        pushState(tutorial.slug);
        return _objectSpread({}, tutorial);
      }

      pushState(tutorial.slug); // If we're opening the same modal, we don't want to overwrite any previous work

      return prevTutorial;
    });
  };

  var closeTutorialModal = function closeTutorialModal() {
    pushState();
    setModalMeta(function (prevMeta) {
      return _objectSpread(_objectSpread({}, prevMeta), {}, {
        open: false
      });
    });
  };

  var publishTutorial = function publishTutorial(event) {
    var published = event.published;
    modalRef.current.toggle(true);
    return setConfirmModal({
      title: "Are you sure you want to ".concat(published ? 'publish' : 'unpublish', " this tutorial?"),
      body: published ? 'This will make it viewable all users.' : 'It will no longer be viewable to users.',
      action: ApiActions.updateTutorial.bind(null, initRequest, event),
      buttonText: published ? 'Publish It!' : 'Unpublish Tutorial'
    });
  };

  var deleteTutorial = function deleteTutorial(event) {
    modalRef.current.toggle(true);
    return setConfirmModal({
      title: 'Are you sure you want to delete this tutorial?',
      body: "You cannot undo this action.",
      action: ApiActions.deleteTutorial.bind(null, initRequest, event),
      buttonText: "Delete Tutorial"
    });
  };

  var makeHero = function makeHero(event) {
    var _id = event._id,
        published = event.published;
    if (published) return ApiActions.makeHero(initRequest, {
      _id: _id
    });
    modalRef.current.toggle(true);
    return setConfirmModal({
      title: 'Are you sure you want to feature an unpublished tutorial?',
      body: 'Featuring an unpublished tutorial will publish it. Make sure it’s ready!',
      action: ApiActions.makeHero.bind(null, initRequest, {
        _id: _id
      }),
      buttonText: 'Feature It!'
    });
  };

  var defaultNav = function defaultNav(e) {
    e.preventDefault();
    if (window) window.open('https://docs.readme.com/tutorials/publish-all-docs-in-category', '_blank');
  };

  return /*#__PURE__*/_react["default"].createElement(PermissionContext.Provider, {
    value: isAdmin
  }, /*#__PURE__*/_react["default"].createElement(cmVariableContext.Provider, {
    value: props.variables
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: classes.Tutorial
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: classes['Tutorial-Wrapper']
  }, !initialLoad && !tutorials.length && /*#__PURE__*/_react["default"].createElement(_compositions.TutorialObstacle, {
    body: "Tutorials are task-driven guidance for your API. Try creating a new Tutorial for your users!",
    className: modalMeta.open && 'paused',
    heading: "Create a Tutorial to Get Started"
  }, /*#__PURE__*/_react["default"].createElement(_components.Button, {
    onClick: function onClick() {
      return openTutorial('Create');
    }
  }, "Create Tutorial"), /*#__PURE__*/_react["default"].createElement(_components.Button, {
    bem: {
      shale: true
    },
    onClick: defaultNav
  }, "Try Example")), tutorials.length > 0 && /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, hero && hero.title && /*#__PURE__*/_react["default"].createElement(_TutorialHero["default"], {
    hero: hero,
    openTutorial: openTutorial
  }), /*#__PURE__*/_react["default"].createElement("section", {
    className: classes.TutorialGrid
  }, tutorials.map(function (tutorial, idx) {
    return /*#__PURE__*/_react["default"].createElement(_compositions.TutorialCard, {
      key: "tut-".concat(idx),
      className: classes['TutorialGrid-Card'],
      deleteTutorial: deleteTutorial,
      makeHero: makeHero,
      numTutorials: tutorials.length,
      openTutorial: openTutorial,
      publish: publishTutorial,
      shiftOrder: function shiftOrder(e) {
        return ApiActions.shiftOrder(initRequest, e);
      },
      tutorial: tutorial
    });
  })))), isAdmin && /*#__PURE__*/_react["default"].createElement("div", {
    className: classes.TutorialToolbar
  }, /*#__PURE__*/_react["default"].createElement("button", {
    className: classes['TutorialToolbar-Button'],
    type: "Button"
  }, moduleEnabled ? /*#__PURE__*/_react["default"].createElement("i", {
    className: "icon icon-eye ".concat(classes['TutorialToolbar-Button-Icon'])
  }) : /*#__PURE__*/_react["default"].createElement("i", {
    className: "icon icon-eye-crossed ".concat(classes['TutorialToolbar-Button-Icon'])
  }), /*#__PURE__*/_react["default"].createElement("span", null, "Show Tutorials", /*#__PURE__*/_react["default"].createElement("i", {
    className: "fa fa-chevron-down ".concat(classes['TutorialToolbar-Button-Arrow'])
  })), /*#__PURE__*/_react["default"].createElement("div", {
    className: classes['TutorialToolbar-PopoverWrapper']
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: classes['TutorialToolbar-Popover']
  }, /*#__PURE__*/_react["default"].createElement(_components.Toggle, {
    checked: moduleEnabled,
    disabled: !tutorials.length,
    label: "Show Tutorials",
    onChange: function onChange() {
      return ApiActions.toggleModule(initRequest);
    },
    type: "toggle"
  }), /*#__PURE__*/_react["default"].createElement("div", {
    className: classes['TutorialToolbar-Popover-Description']
  }, "The Tutorial view won\u2019t be shown to users until you publish your first tutorial.")))), /*#__PURE__*/_react["default"].createElement("button", {
    className: classes['TutorialToolbar-Button'],
    onClick: function onClick() {
      return openTutorial('Create');
    },
    type: "Button"
  }, /*#__PURE__*/_react["default"].createElement("i", {
    className: "icon icon-tutorials-new ".concat(classes['TutorialToolbar-Button-Icon'])
  }), "Create Tutorial"))), isAdmin && error && /*#__PURE__*/_react["default"].createElement(_components.Notification, {
    color: 'red',
    dismissible: true,
    handleClick: function handleClick() {
      return setError(null);
    },
    position: 'top'
  }, /*#__PURE__*/_react["default"].createElement("p", null, error)), /*#__PURE__*/_react["default"].createElement(_compositions.TutorialModal, {
    action: modalMeta.action,
    baseUrl: baseUrl,
    closeTutorialModal: closeTutorialModal,
    confirmModal: modalRef,
    moduleEnabled: moduleEnabled,
    onboarding: onboarding,
    open: modalMeta.open,
    referenceEnabled: referenceEnabled,
    requestDataRefresh: function requestDataRefresh() {
      return getTutorials();
    },
    setConfirmModal: setConfirmModal,
    target: modalTarget,
    tutorial: selectedTutorial
  }), /*#__PURE__*/_react["default"].createElement(_components.Modal, {
    ref: modalRef,
    className: classes.TutorialConfirmation,
    size: "sm",
    target: confirmationTarget,
    verticalCenter: true
  }, /*#__PURE__*/_react["default"].createElement(_Body["default"], null, /*#__PURE__*/_react["default"].createElement(_components.Title, {
    className: classes['TutorialConfirmation-Title'],
    level: 4
  }, confirmModalState.title), /*#__PURE__*/_react["default"].createElement("p", {
    className: classes['TutorialConfirmation-Description']
  }, confirmModalState.body)), /*#__PURE__*/_react["default"].createElement(_Footer["default"], {
    justify: "center"
  }, /*#__PURE__*/_react["default"].createElement(_components.Button, {
    bem: {
      shale_text: true
    },
    onClick: function onClick() {
      setConfirmModal({});
      modalRef.current.toggle(false);
    }
  }, "Cancel"), /*#__PURE__*/_react["default"].createElement(_components.Button, {
    bem: confirmModalState.buttonText === 'Delete Tutorial' ? {
      red: true
    } : {
      blue: true
    },
    onClick: function onClick() {
      confirmModalState.action();
      modalRef.current.toggle(false);
    }
  }, confirmModalState.buttonText)))));
}

Tutorials.propTypes = {
  baseUrl: _propTypes["default"].string,
  confirmationTarget: _propTypes["default"].string,
  isAdmin: _propTypes["default"].bool.isRequired,
  modalTarget: _propTypes["default"].string,
  referenceEnabled: _propTypes["default"].bool,
  slug: _propTypes["default"].string,
  variables: _propTypes["default"].shape({
    defaults: _propTypes["default"].arrayOf(_propTypes["default"].any),
    user: _propTypes["default"].any
  })
};
Tutorials.defaultProps = {
  baseUrl: '',
  confirmationTarget: '#confirmation-root',
  isAdmin: false,
  modalTarget: '#modal-root',
  referenceEnabled: false,
  variables: {
    defaults: [],
    user: {}
  }
};