"use strict";

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

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = withSteps;

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

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

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

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

var _Button = _interopRequireDefault(require("@material-ui/core/Button"));

var _Step = _interopRequireDefault(require("@material-ui/core/Step"));

var _StepButton = _interopRequireDefault(require("@material-ui/core/StepButton"));

var _StepContent = _interopRequireDefault(require("@material-ui/core/StepContent"));

var _Stepper = _interopRequireDefault(require("@material-ui/core/Stepper"));

var _styles = require("@material-ui/core/styles");

var _Typography = _interopRequireDefault(require("@material-ui/core/Typography"));

var _lodash = require("lodash");

var _react = require("react");

var _reactIntl = require("react-intl");

var _stepTitle = require("./configToSchemas/types/stepTitle");

var _Check = _interopRequireDefault(require("@material-ui/icons/Check"));

var _jsxRuntime = require("react/jsx-runtime");

var _excluded = ["onSubmit", "onChange", "onError", "formData", "steps", "fillProps"];
var useStyles = (0, _styles.makeStyles)(function (theme) {
  return {
    button: {
      marginRight: theme.spacing(1)
    },
    buttonContainer: {
      '& > *': {
        marginRight: theme.spacing(1),
        marginTop: theme.spacing(1),
        '@media print': {
          display: 'none'
        }
      }
    },
    labelContainer: {
      textAlign: 'start'
    },
    stepIconActive: {
      color: '#0077C7',
      fill: 'currentColor',
      width: '1em',
      height: '1em',
      display: 'inline-block',
      fontSize: '1.5rem',
      transition: 'fill 200ms cubic-bezier(0.4, 0, 0.2, 1) 0ms',
      flexShrink: '0',
      userSelect: 'none'
    },
    stepIcon: {
      color: 'rgba(0, 0, 0, 0.38)',
      fill: 'currentColor',
      width: '1em',
      height: '1em',
      display: 'inline-block',
      fontSize: '1.5rem',
      transition: 'fill 200ms cubic-bezier(0.4, 0, 0.2, 1) 0ms',
      flexShrink: '0',
      userSelect: 'none'
    }
  };
});

function withSteps(Form) {
  var WithSteps = /*#__PURE__*/(0, _react.forwardRef)(function (_ref, ref) {
    var _ref2;

    var onSubmit = _ref.onSubmit,
        _onChange = _ref.onChange,
        _onError = _ref.onError,
        formData = _ref.formData,
        steps = _ref.steps,
        fillProps = _ref.fillProps,
        otherProps = (0, _objectWithoutProperties2["default"])(_ref, _excluded);
    var intl = (0, _reactIntl.useIntl)();

    var _useState = (0, _react.useState)(otherProps.dataIsDraft && otherProps.activeStep ? otherProps.activeStep : 0),
        _useState2 = (0, _slicedToArray2["default"])(_useState, 2),
        activeStep = _useState2[0],
        setActiveStep = _useState2[1];

    var _useState3 = (0, _react.useState)(activeStep),
        _useState4 = (0, _slicedToArray2["default"])(_useState3, 2),
        maxJump = _useState4[0],
        setMaxJump = _useState4[1];

    var _useState5 = (0, _react.useState)(false),
        _useState6 = (0, _slicedToArray2["default"])(_useState5, 2),
        noValidate = _useState6[0],
        setNoValidate = _useState6[1];

    var _useState7 = (0, _react.useState)(false),
        _useState8 = (0, _slicedToArray2["default"])(_useState7, 2),
        liveValidate = _useState8[0],
        setLiveValidate = _useState8[1];

    var classes = useStyles();
    var formRef = (0, _react.useRef)();
    (_ref2 = ref) !== null && _ref2 !== void 0 ? _ref2 : ref = formRef;
    var formWrapperRef = (0, _react.useRef)();
    var jumpRef = (0, _react.useRef)(null);

    function handleStepChange() {
      var _jumpRef$current;

      var nextStep = (_jumpRef$current = jumpRef.current) !== null && _jumpRef$current !== void 0 ? _jumpRef$current : activeStep + 1;

      if (nextStep < steps.length) {
        setMaxJump(function (prev) {
          return Math.max(prev, nextStep);
        });
        setActiveStep(nextStep);
        setTimeout(function () {
          var _steps$nextStep$uiOp, _steps$nextStep$uiOp$, _formWrapperRef$curre, _formWrapperRef$curre2;

          var stepId = 'formula-step-' + ((_steps$nextStep$uiOp = steps[nextStep]['ui:options']) === null || _steps$nextStep$uiOp === void 0 ? void 0 : (_steps$nextStep$uiOp$ = _steps$nextStep$uiOp.element) === null || _steps$nextStep$uiOp$ === void 0 ? void 0 : _steps$nextStep$uiOp$.key);
          var selection = (_formWrapperRef$curre = formWrapperRef.current) === null || _formWrapperRef$curre === void 0 ? void 0 : _formWrapperRef$curre.querySelector('#' + stepId);
          selection.scrollIntoView(true);
          var focusableElements = 'a:not([disabled]), button:not([disabled]), input:not([disabled]), [tabindex]:not([disabled]):not([tabindex="-1"])';
          var allFocusableElements = (_formWrapperRef$curre2 = formWrapperRef.current) === null || _formWrapperRef$curre2 === void 0 ? void 0 : _formWrapperRef$curre2.querySelectorAll(focusableElements);
          var focusableFormElements = Array.prototype.slice.call(allFocusableElements).filter(function (element) {
            return !element.id.startsWith('formula-step');
          });
          focusableFormElements[0].focus();
        }, 0); // Prevent submit

        return false;
      } // Submit


      return true;
    }

    var handleSubmit = function handleSubmit() {
      setNoValidate(false);
    };

    var isLastStep = activeStep === steps.length - 1;
    var elements = otherProps.uiSchema['ui:order'];
    var currentStepElements = [];
    var beforeMaxJumpElements = [];
    var current = -1;

    var _iterator = (0, _createForOfIteratorHelper2["default"])(elements),
        _step;

    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var _otherProps$uiSchema$;

        var element = _step.value;
        var uiField = (_otherProps$uiSchema$ = otherProps.uiSchema[element]) === null || _otherProps$uiSchema$ === void 0 ? void 0 : _otherProps$uiSchema$['ui:field'];

        if (uiField === _stepTitle.StepTitle) {
          current++;

          if (current > maxJump) {
            break;
          } else {
            continue;
          }
        }

        if (current === -1 && activeStep === 0 || current === activeStep) {
          currentStepElements.push(element);
        }

        beforeMaxJumpElements.push(element);
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }

    var createHandleJump = function createHandleJump(step) {
      return function handleJump(event) {
        // If backward button pressed
        step < activeStep ? setNoValidate(true) : setNoValidate(false);
        setLiveValidate(false);
        jumpRef.current = step;
        ref.current.submit(event); // Wait for the submit event to trigger.

        setTimeout(function () {
          // If form has validation errors, jump does not happen and we must clean
          // current value.
          jumpRef.current = null;
        });
      };
    };

    var StepIcon = function StepIcon(_ref3) {
      var pageNumber = _ref3.pageNumber,
          active = _ref3.active,
          completed = _ref3.completed;
      return /*#__PURE__*/(0, _jsxRuntime.jsxs)("svg", {
        "aria-label": completed ? intl.formatMessage({
          id: "eQag3L",
          defaultMessage: [{
            "type": 0,
            "value": "Ikoni, sivu "
          }, {
            "type": 1,
            "value": "page"
          }, {
            "type": 0,
            "value": ": täytetty"
          }]
        }, {
          page: pageNumber
        }) : active ? intl.formatMessage({
          id: "00WiO4",
          defaultMessage: [{
            "type": 0,
            "value": "Ikoni, sivu "
          }, {
            "type": 1,
            "value": "page"
          }, {
            "type": 0,
            "value": ": aktiivinen"
          }]
        }, {
          page: pageNumber
        }) : intl.formatMessage({
          id: "BM+uIV",
          defaultMessage: [{
            "type": 0,
            "value": "Ikoni, sivu "
          }, {
            "type": 1,
            "value": "page"
          }, {
            "type": 0,
            "value": ": täyttämätön"
          }]
        }, {
          page: pageNumber
        }),
        className: active ? classes.stepIconActive : classes.stepIcon,
        focusable: false,
        viewBox: "0 0 24 24",
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("circle", {
          cx: 12,
          cy: 12,
          r: 12,
          "aria-hidden": true
        }), completed ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_Check["default"], {
          style: {
            color: 'white'
          },
          "aria-hidden": true
        }) : /*#__PURE__*/(0, _jsxRuntime.jsx)("text", {
          className: "MuiStepIcon-text",
          x: 12,
          y: 16,
          textAnchor: "middle",
          "aria-hidden": true,
          children: pageNumber
        })]
      });
    };

    return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
      ref: formWrapperRef,
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_Typography["default"], {
        component: "h2",
        variant: "h5",
        gutterBottom: true,
        children: otherProps.schema.title
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_Stepper["default"], {
        activeStep: activeStep,
        orientation: "vertical",
        nonLinear: true,
        children: steps.map(function (_ref4) {
          var title = _ref4['ui:title'],
              options = _ref4['ui:options'];
          return {
            title: title,
            options: options
          };
        }).map(function (_ref5, index) {
          var _options$element, _otherProps$schema$re;

          var title = _ref5.title,
              options = _ref5.options;
          var active = index <= maxJump;
          var current = index === activeStep;
          return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_Step["default"], {
            children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_StepButton["default"], {
              id: "formula-step-".concat(options === null || options === void 0 ? void 0 : (_options$element = options.element) === null || _options$element === void 0 ? void 0 : _options$element.key),
              completed: index < activeStep,
              disabled: current || !active,
              active: active,
              onClick: createHandleJump(index),
              className: classes.labelContainer,
              icon: /*#__PURE__*/(0, _jsxRuntime.jsx)(StepIcon, {
                pageNumber: index + 1,
                active: active,
                completed: index < activeStep
              }),
              "aria-expanded": current,
              "aria-disabled": current,
              children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Typography["default"], {
                variant: "subtitle2",
                component: "h3",
                children: title
              })
            }), current && /*#__PURE__*/(0, _jsxRuntime.jsx)(_StepContent["default"], {
              children: /*#__PURE__*/(0, _jsxRuntime.jsx)(Form, (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, otherProps), {}, {
                fillProps: fillProps,
                onSubmit: isLastStep ? onSubmit : undefined,
                onPreSubmit: handleStepChange,
                ref: ref,
                isLastStep: isLastStep,
                formData: formData,
                onChange: function onChange() {
                  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                    args[_key] = arguments[_key];
                  }

                  _onChange === null || _onChange === void 0 ? void 0 : _onChange.apply(void 0, args);
                  setMaxJump(activeStep);
                },
                onError: function onError() {
                  setLiveValidate(true);

                  for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
                    args[_key2] = arguments[_key2];
                  }

                  _onError === null || _onError === void 0 ? void 0 : _onError.apply(void 0, args);
                },
                liveValidate: liveValidate,
                noValidate: noValidate,
                schema: (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, otherProps.schema), {}, {
                  properties: (0, _lodash.pick)(otherProps.schema.properties, isLastStep ? beforeMaxJumpElements : currentStepElements),
                  title: undefined,
                  required: (_otherProps$schema$re = otherProps.schema.required) === null || _otherProps$schema$re === void 0 ? void 0 : _otherProps$schema$re.filter(function (key) {
                    return currentStepElements.includes(key);
                  })
                }),
                uiSchema: (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, (0, _lodash.mapValues)(otherProps.schema.properties, function (value, key) {
                  return currentStepElements.includes(key) ? otherProps.uiSchema[key] : {
                    'ui:widget': 'hidden'
                  };
                })), (0, _lodash.mapValues)(otherProps.uiSchema, function (value, key) {
                  return elements.includes(key) && !currentStepElements.includes(key) ? {
                    'ui:widget': 'hidden'
                  } : value;
                })),
                children: /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
                  className: classes.buttonContainer,
                  children: [(fillProps === null || fillProps === void 0 ? void 0 : fillProps.actions) && fillProps.actions, isLastStep ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_Button["default"], {
                    type: "submit",
                    onClick: handleSubmit,
                    variant: "contained",
                    color: "primary",
                    children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactIntl.FormattedMessage, {
                      id: "6jFMKd",
                      defaultMessage: [{
                        "type": 0,
                        "value": "Lähetä"
                      }]
                    })
                  }) : /*#__PURE__*/(0, _jsxRuntime.jsx)(_Button["default"], {
                    onClick: createHandleJump(activeStep + 1),
                    variant: "contained",
                    color: "primary",
                    children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactIntl.FormattedMessage, {
                      id: "KwX5/f",
                      defaultMessage: [{
                        "type": 0,
                        "value": "Eteenpäin"
                      }]
                    })
                  }), activeStep !== 0 && /*#__PURE__*/(0, _jsxRuntime.jsx)(_Button["default"], {
                    onClick: createHandleJump(activeStep - 1),
                    children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactIntl.FormattedMessage, {
                      id: "DeSNU6",
                      defaultMessage: [{
                        "type": 0,
                        "value": "Takaisin"
                      }]
                    })
                  }), otherProps.draftButton]
                })
              }))
            })]
          }, title);
        })
      })]
    });
  });
  return /*#__PURE__*/(0, _react.forwardRef)(function (props, ref) {
    var _props$uiSchema$uiOr, _props$fillProps;

    var uiOrder = (_props$uiSchema$uiOr = props.uiSchema['ui:order']) !== null && _props$uiSchema$uiOr !== void 0 ? _props$uiSchema$uiOr : [];
    var steps = Object.entries(props.uiSchema).sort(function (_ref6, _ref7) {
      var _ref8 = (0, _slicedToArray2["default"])(_ref6, 1),
          a = _ref8[0];

      var _ref9 = (0, _slicedToArray2["default"])(_ref7, 1),
          b = _ref9[0];

      return uiOrder.indexOf(a) - uiOrder.indexOf(b);
    }).map(function (_ref10) {
      var _ref11 = (0, _slicedToArray2["default"])(_ref10, 2),
          value = _ref11[1];

      return value;
    }).filter(Boolean).filter(function (_ref12) {
      var uiField = _ref12['ui:field'];
      return uiField === _stepTitle.StepTitle;
    });
    var steppedProps = (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, props), {}, {
      // In form step schema & uiSchema is incomplete.
      // This is to access the original/full schema & uiSchema.
      __withStepped_original_props__: props
    });
    return !(props === null || props === void 0 ? void 0 : (_props$fillProps = props.fillProps) === null || _props$fillProps === void 0 ? void 0 : _props$fillProps.disableSteps) && steps.length ? /*#__PURE__*/(0, _jsxRuntime.jsx)(WithSteps, (0, _objectSpread2["default"])((0, _objectSpread2["default"])({
      ref: ref
    }, steppedProps), {}, {
      steps: steps
    })) : /*#__PURE__*/(0, _jsxRuntime.jsx)(Form, (0, _objectSpread2["default"])({
      ref: ref
    }, steppedProps));
  });
}
//# sourceMappingURL=withSteps.cjs.map