UNPKG

bma-react-invenio-deposit

Version:
10,211 lines 364 kB
Object.defineProperty(exports, '__esModule', { value: true });

var axios = require('axios');
var _isEmpty = require('lodash/isEmpty');
var _set = require('lodash/set');
var React = require('react');
var reactRedux = require('react-redux');
var reactI18next = require('react-i18next');
var reactInvenioForms = require('react-invenio-forms');
var _indexOf = require('lodash/indexOf');
var _cloneDeep = require('lodash/cloneDeep');
var _defaults = require('lodash/defaults');
var _isArray = require('lodash/isArray');
var _isBoolean = require('lodash/isBoolean');
var _isNull = require('lodash/isNull');
var _isNumber = require('lodash/isNumber');
var _isObject = require('lodash/isObject');
var _mapValues = require('lodash/mapValues');
var _pick = require('lodash/pick');
var _pickBy = require('lodash/pickBy');
var _get = require('lodash/get');
require('lodash/isEqual');
var redux = require('redux');
var thunk = require('redux-thunk');
var i18n = require('i18next');
var LanguageDetector = require('i18next-browser-languagedetector');
var _join = require('lodash/join');
var formik = require('formik');
var semanticUiReact = require('semantic-ui-react');
var luxon = require('luxon');
var reactDndHtml5Backend = require('react-dnd-html5-backend');
var reactDnd = require('react-dnd');
var Yup = require('yup');
var _find = require('lodash/find');
var _map = require('lodash/map');
var _unickBy = require('lodash/unionBy');
var Dropzone = require('react-dropzone');
var _debounce = require('lodash/debounce');
var reactSearchkit = require('react-searchkit');
var reactOverridable = require('react-overridable');
var _truncate = require('lodash/truncate');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

function _interopNamespace(e) {
	if (e && e.__esModule) return e;
	var n = Object.create(null);
	if (e) {
		Object.keys(e).forEach(function (k) {
			if (k !== 'default') {
				var d = Object.getOwnPropertyDescriptor(e, k);
				Object.defineProperty(n, k, d.get ? d : {
					enumerable: true,
					get: function () {
						return e[k];
					}
				});
			}
		});
	}
	n['default'] = e;
	return Object.freeze(n);
}

var axios__default = /*#__PURE__*/_interopDefaultLegacy(axios);
var _isEmpty__default = /*#__PURE__*/_interopDefaultLegacy(_isEmpty);
var _set__default = /*#__PURE__*/_interopDefaultLegacy(_set);
var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
var _indexOf__default = /*#__PURE__*/_interopDefaultLegacy(_indexOf);
var _cloneDeep__default = /*#__PURE__*/_interopDefaultLegacy(_cloneDeep);
var _defaults__default = /*#__PURE__*/_interopDefaultLegacy(_defaults);
var _isArray__default = /*#__PURE__*/_interopDefaultLegacy(_isArray);
var _isBoolean__default = /*#__PURE__*/_interopDefaultLegacy(_isBoolean);
var _isNull__default = /*#__PURE__*/_interopDefaultLegacy(_isNull);
var _isNumber__default = /*#__PURE__*/_interopDefaultLegacy(_isNumber);
var _isObject__default = /*#__PURE__*/_interopDefaultLegacy(_isObject);
var _mapValues__default = /*#__PURE__*/_interopDefaultLegacy(_mapValues);
var _pick__default = /*#__PURE__*/_interopDefaultLegacy(_pick);
var _pickBy__default = /*#__PURE__*/_interopDefaultLegacy(_pickBy);
var _get__default = /*#__PURE__*/_interopDefaultLegacy(_get);
var thunk__default = /*#__PURE__*/_interopDefaultLegacy(thunk);
var i18n__default = /*#__PURE__*/_interopDefaultLegacy(i18n);
var LanguageDetector__default = /*#__PURE__*/_interopDefaultLegacy(LanguageDetector);
var _join__default = /*#__PURE__*/_interopDefaultLegacy(_join);
var Yup__namespace = /*#__PURE__*/_interopNamespace(Yup);
var _find__default = /*#__PURE__*/_interopDefaultLegacy(_find);
var _map__default = /*#__PURE__*/_interopDefaultLegacy(_map);
var _unickBy__default = /*#__PURE__*/_interopDefaultLegacy(_unickBy);
var Dropzone__default = /*#__PURE__*/_interopDefaultLegacy(Dropzone);
var _debounce__default = /*#__PURE__*/_interopDefaultLegacy(_debounce);
var _truncate__default = /*#__PURE__*/_interopDefaultLegacy(_truncate);

function createCommonjsModule(fn, module) {
	return module = { exports: {} }, fn(module, module.exports), module.exports;
}

var runtime_1 = createCommonjsModule(function (module) {
/**
 * Copyright (c) 2014-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

var runtime = (function (exports) {

  var Op = Object.prototype;
  var hasOwn = Op.hasOwnProperty;
  var undefined$1; // More compressible than void 0.
  var $Symbol = typeof Symbol === "function" ? Symbol : {};
  var iteratorSymbol = $Symbol.iterator || "@@iterator";
  var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
  var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";

  function define(obj, key, value) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
    return obj[key];
  }
  try {
    // IE 8 has a broken Object.defineProperty that only works on DOM objects.
    define({}, "");
  } catch (err) {
    define = function(obj, key, value) {
      return obj[key] = value;
    };
  }

  function wrap(innerFn, outerFn, self, tryLocsList) {
    // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
    var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
    var generator = Object.create(protoGenerator.prototype);
    var context = new Context(tryLocsList || []);

    // The ._invoke method unifies the implementations of the .next,
    // .throw, and .return methods.
    generator._invoke = makeInvokeMethod(innerFn, self, context);

    return generator;
  }
  exports.wrap = wrap;

  // Try/catch helper to minimize deoptimizations. Returns a completion
  // record like context.tryEntries[i].completion. This interface could
  // have been (and was previously) designed to take a closure to be
  // invoked without arguments, but in all the cases we care about we
  // already have an existing method we want to call, so there's no need
  // to create a new function object. We can even get away with assuming
  // the method takes exactly one argument, since that happens to be true
  // in every case, so we don't have to touch the arguments object. The
  // only additional allocation required is the completion record, which
  // has a stable shape and so hopefully should be cheap to allocate.
  function tryCatch(fn, obj, arg) {
    try {
      return { type: "normal", arg: fn.call(obj, arg) };
    } catch (err) {
      return { type: "throw", arg: err };
    }
  }

  var GenStateSuspendedStart = "suspendedStart";
  var GenStateSuspendedYield = "suspendedYield";
  var GenStateExecuting = "executing";
  var GenStateCompleted = "completed";

  // Returning this object from the innerFn has the same effect as
  // breaking out of the dispatch switch statement.
  var ContinueSentinel = {};

  // Dummy constructor functions that we use as the .constructor and
  // .constructor.prototype properties for functions that return Generator
  // objects. For full spec compliance, you may wish to configure your
  // minifier not to mangle the names of these two functions.
  function Generator() {}
  function GeneratorFunction() {}
  function GeneratorFunctionPrototype() {}

  // This is a polyfill for %IteratorPrototype% for environments that
  // don't natively support it.
  var IteratorPrototype = {};
  IteratorPrototype[iteratorSymbol] = function () {
    return this;
  };

  var getProto = Object.getPrototypeOf;
  var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
  if (NativeIteratorPrototype &&
      NativeIteratorPrototype !== Op &&
      hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
    // This environment has a native %IteratorPrototype%; use it instead
    // of the polyfill.
    IteratorPrototype = NativeIteratorPrototype;
  }

  var Gp = GeneratorFunctionPrototype.prototype =
    Generator.prototype = Object.create(IteratorPrototype);
  GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
  GeneratorFunctionPrototype.constructor = GeneratorFunction;
  GeneratorFunction.displayName = define(
    GeneratorFunctionPrototype,
    toStringTagSymbol,
    "GeneratorFunction"
  );

  // Helper for defining the .next, .throw, and .return methods of the
  // Iterator interface in terms of a single ._invoke method.
  function defineIteratorMethods(prototype) {
    ["next", "throw", "return"].forEach(function(method) {
      define(prototype, method, function(arg) {
        return this._invoke(method, arg);
      });
    });
  }

  exports.isGeneratorFunction = function(genFun) {
    var ctor = typeof genFun === "function" && genFun.constructor;
    return ctor
      ? ctor === GeneratorFunction ||
        // For the native GeneratorFunction constructor, the best we can
        // do is to check its .name property.
        (ctor.displayName || ctor.name) === "GeneratorFunction"
      : false;
  };

  exports.mark = function(genFun) {
    if (Object.setPrototypeOf) {
      Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
    } else {
      genFun.__proto__ = GeneratorFunctionPrototype;
      define(genFun, toStringTagSymbol, "GeneratorFunction");
    }
    genFun.prototype = Object.create(Gp);
    return genFun;
  };

  // Within the body of any async function, `await x` is transformed to
  // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
  // `hasOwn.call(value, "__await")` to determine if the yielded value is
  // meant to be awaited.
  exports.awrap = function(arg) {
    return { __await: arg };
  };

  function AsyncIterator(generator, PromiseImpl) {
    function invoke(method, arg, resolve, reject) {
      var record = tryCatch(generator[method], generator, arg);
      if (record.type === "throw") {
        reject(record.arg);
      } else {
        var result = record.arg;
        var value = result.value;
        if (value &&
            typeof value === "object" &&
            hasOwn.call(value, "__await")) {
          return PromiseImpl.resolve(value.__await).then(function(value) {
            invoke("next", value, resolve, reject);
          }, function(err) {
            invoke("throw", err, resolve, reject);
          });
        }

        return PromiseImpl.resolve(value).then(function(unwrapped) {
          // When a yielded Promise is resolved, its final value becomes
          // the .value of the Promise<{value,done}> result for the
          // current iteration.
          result.value = unwrapped;
          resolve(result);
        }, function(error) {
          // If a rejected Promise was yielded, throw the rejection back
          // into the async generator function so it can be handled there.
          return invoke("throw", error, resolve, reject);
        });
      }
    }

    var previousPromise;

    function enqueue(method, arg) {
      function callInvokeWithMethodAndArg() {
        return new PromiseImpl(function(resolve, reject) {
          invoke(method, arg, resolve, reject);
        });
      }

      return previousPromise =
        // If enqueue has been called before, then we want to wait until
        // all previous Promises have been resolved before calling invoke,
        // so that results are always delivered in the correct order. If
        // enqueue has not been called before, then it is important to
        // call invoke immediately, without waiting on a callback to fire,
        // so that the async generator function has the opportunity to do
        // any necessary setup in a predictable way. This predictability
        // is why the Promise constructor synchronously invokes its
        // executor callback, and why async functions synchronously
        // execute code before the first await. Since we implement simple
        // async functions in terms of async generators, it is especially
        // important to get this right, even though it requires care.
        previousPromise ? previousPromise.then(
          callInvokeWithMethodAndArg,
          // Avoid propagating failures to Promises returned by later
          // invocations of the iterator.
          callInvokeWithMethodAndArg
        ) : callInvokeWithMethodAndArg();
    }

    // Define the unified helper method that is used to implement .next,
    // .throw, and .return (see defineIteratorMethods).
    this._invoke = enqueue;
  }

  defineIteratorMethods(AsyncIterator.prototype);
  AsyncIterator.prototype[asyncIteratorSymbol] = function () {
    return this;
  };
  exports.AsyncIterator = AsyncIterator;

  // Note that simple async functions are implemented on top of
  // AsyncIterator objects; they just return a Promise for the value of
  // the final result produced by the iterator.
  exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {
    if (PromiseImpl === void 0) PromiseImpl = Promise;

    var iter = new AsyncIterator(
      wrap(innerFn, outerFn, self, tryLocsList),
      PromiseImpl
    );

    return exports.isGeneratorFunction(outerFn)
      ? iter // If outerFn is a generator, return the full iterator.
      : iter.next().then(function(result) {
          return result.done ? result.value : iter.next();
        });
  };

  function makeInvokeMethod(innerFn, self, context) {
    var state = GenStateSuspendedStart;

    return function invoke(method, arg) {
      if (state === GenStateExecuting) {
        throw new Error("Generator is already running");
      }

      if (state === GenStateCompleted) {
        if (method === "throw") {
          throw arg;
        }

        // Be forgiving, per 25.3.3.3.3 of the spec:
        // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
        return doneResult();
      }

      context.method = method;
      context.arg = arg;

      while (true) {
        var delegate = context.delegate;
        if (delegate) {
          var delegateResult = maybeInvokeDelegate(delegate, context);
          if (delegateResult) {
            if (delegateResult === ContinueSentinel) continue;
            return delegateResult;
          }
        }

        if (context.method === "next") {
          // Setting context._sent for legacy support of Babel's
          // function.sent implementation.
          context.sent = context._sent = context.arg;

        } else if (context.method === "throw") {
          if (state === GenStateSuspendedStart) {
            state = GenStateCompleted;
            throw context.arg;
          }

          context.dispatchException(context.arg);

        } else if (context.method === "return") {
          context.abrupt("return", context.arg);
        }

        state = GenStateExecuting;

        var record = tryCatch(innerFn, self, context);
        if (record.type === "normal") {
          // If an exception is thrown from innerFn, we leave state ===
          // GenStateExecuting and loop back for another invocation.
          state = context.done
            ? GenStateCompleted
            : GenStateSuspendedYield;

          if (record.arg === ContinueSentinel) {
            continue;
          }

          return {
            value: record.arg,
            done: context.done
          };

        } else if (record.type === "throw") {
          state = GenStateCompleted;
          // Dispatch the exception by looping back around to the
          // context.dispatchException(context.arg) call above.
          context.method = "throw";
          context.arg = record.arg;
        }
      }
    };
  }

  // Call delegate.iterator[context.method](context.arg) and handle the
  // result, either by returning a { value, done } result from the
  // delegate iterator, or by modifying context.method and context.arg,
  // setting context.delegate to null, and returning the ContinueSentinel.
  function maybeInvokeDelegate(delegate, context) {
    var method = delegate.iterator[context.method];
    if (method === undefined$1) {
      // A .throw or .return when the delegate iterator has no .throw
      // method always terminates the yield* loop.
      context.delegate = null;

      if (context.method === "throw") {
        // Note: ["return"] must be used for ES3 parsing compatibility.
        if (delegate.iterator["return"]) {
          // If the delegate iterator has a return method, give it a
          // chance to clean up.
          context.method = "return";
          context.arg = undefined$1;
          maybeInvokeDelegate(delegate, context);

          if (context.method === "throw") {
            // If maybeInvokeDelegate(context) changed context.method from
            // "return" to "throw", let that override the TypeError below.
            return ContinueSentinel;
          }
        }

        context.method = "throw";
        context.arg = new TypeError(
          "The iterator does not provide a 'throw' method");
      }

      return ContinueSentinel;
    }

    var record = tryCatch(method, delegate.iterator, context.arg);

    if (record.type === "throw") {
      context.method = "throw";
      context.arg = record.arg;
      context.delegate = null;
      return ContinueSentinel;
    }

    var info = record.arg;

    if (! info) {
      context.method = "throw";
      context.arg = new TypeError("iterator result is not an object");
      context.delegate = null;
      return ContinueSentinel;
    }

    if (info.done) {
      // Assign the result of the finished delegate to the temporary
      // variable specified by delegate.resultName (see delegateYield).
      context[delegate.resultName] = info.value;

      // Resume execution at the desired location (see delegateYield).
      context.next = delegate.nextLoc;

      // If context.method was "throw" but the delegate handled the
      // exception, let the outer generator proceed normally. If
      // context.method was "next", forget context.arg since it has been
      // "consumed" by the delegate iterator. If context.method was
      // "return", allow the original .return call to continue in the
      // outer generator.
      if (context.method !== "return") {
        context.method = "next";
        context.arg = undefined$1;
      }

    } else {
      // Re-yield the result returned by the delegate method.
      return info;
    }

    // The delegate iterator is finished, so forget it and continue with
    // the outer generator.
    context.delegate = null;
    return ContinueSentinel;
  }

  // Define Generator.prototype.{next,throw,return} in terms of the
  // unified ._invoke helper method.
  defineIteratorMethods(Gp);

  define(Gp, toStringTagSymbol, "Generator");

  // A Generator should always return itself as the iterator object when the
  // @@iterator function is called on it. Some browsers' implementations of the
  // iterator prototype chain incorrectly implement this, causing the Generator
  // object to not be returned from this call. This ensures that doesn't happen.
  // See https://github.com/facebook/regenerator/issues/274 for more details.
  Gp[iteratorSymbol] = function() {
    return this;
  };

  Gp.toString = function() {
    return "[object Generator]";
  };

  function pushTryEntry(locs) {
    var entry = { tryLoc: locs[0] };

    if (1 in locs) {
      entry.catchLoc = locs[1];
    }

    if (2 in locs) {
      entry.finallyLoc = locs[2];
      entry.afterLoc = locs[3];
    }

    this.tryEntries.push(entry);
  }

  function resetTryEntry(entry) {
    var record = entry.completion || {};
    record.type = "normal";
    delete record.arg;
    entry.completion = record;
  }

  function Context(tryLocsList) {
    // The root entry object (effectively a try statement without a catch
    // or a finally block) gives us a place to store values thrown from
    // locations where there is no enclosing try statement.
    this.tryEntries = [{ tryLoc: "root" }];
    tryLocsList.forEach(pushTryEntry, this);
    this.reset(true);
  }

  exports.keys = function(object) {
    var keys = [];
    for (var key in object) {
      keys.push(key);
    }
    keys.reverse();

    // Rather than returning an object with a next method, we keep
    // things simple and return the next function itself.
    return function next() {
      while (keys.length) {
        var key = keys.pop();
        if (key in object) {
          next.value = key;
          next.done = false;
          return next;
        }
      }

      // To avoid creating an additional object, we just hang the .value
      // and .done properties off the next function object itself. This
      // also ensures that the minifier will not anonymize the function.
      next.done = true;
      return next;
    };
  };

  function values(iterable) {
    if (iterable) {
      var iteratorMethod = iterable[iteratorSymbol];
      if (iteratorMethod) {
        return iteratorMethod.call(iterable);
      }

      if (typeof iterable.next === "function") {
        return iterable;
      }

      if (!isNaN(iterable.length)) {
        var i = -1, next = function next() {
          while (++i < iterable.length) {
            if (hasOwn.call(iterable, i)) {
              next.value = iterable[i];
              next.done = false;
              return next;
            }
          }

          next.value = undefined$1;
          next.done = true;

          return next;
        };

        return next.next = next;
      }
    }

    // Return an iterator with no values.
    return { next: doneResult };
  }
  exports.values = values;

  function doneResult() {
    return { value: undefined$1, done: true };
  }

  Context.prototype = {
    constructor: Context,

    reset: function(skipTempReset) {
      this.prev = 0;
      this.next = 0;
      // Resetting context._sent for legacy support of Babel's
      // function.sent implementation.
      this.sent = this._sent = undefined$1;
      this.done = false;
      this.delegate = null;

      this.method = "next";
      this.arg = undefined$1;

      this.tryEntries.forEach(resetTryEntry);

      if (!skipTempReset) {
        for (var name in this) {
          // Not sure about the optimal order of these conditions:
          if (name.charAt(0) === "t" &&
              hasOwn.call(this, name) &&
              !isNaN(+name.slice(1))) {
            this[name] = undefined$1;
          }
        }
      }
    },

    stop: function() {
      this.done = true;

      var rootEntry = this.tryEntries[0];
      var rootRecord = rootEntry.completion;
      if (rootRecord.type === "throw") {
        throw rootRecord.arg;
      }

      return this.rval;
    },

    dispatchException: function(exception) {
      if (this.done) {
        throw exception;
      }

      var context = this;
      function handle(loc, caught) {
        record.type = "throw";
        record.arg = exception;
        context.next = loc;

        if (caught) {
          // If the dispatched exception was caught by a catch block,
          // then let that catch block handle the exception normally.
          context.method = "next";
          context.arg = undefined$1;
        }

        return !! caught;
      }

      for (var i = this.tryEntries.length - 1; i >= 0; --i) {
        var entry = this.tryEntries[i];
        var record = entry.completion;

        if (entry.tryLoc === "root") {
          // Exception thrown outside of any try block that could handle
          // it, so set the completion value of the entire function to
          // throw the exception.
          return handle("end");
        }

        if (entry.tryLoc <= this.prev) {
          var hasCatch = hasOwn.call(entry, "catchLoc");
          var hasFinally = hasOwn.call(entry, "finallyLoc");

          if (hasCatch && hasFinally) {
            if (this.prev < entry.catchLoc) {
              return handle(entry.catchLoc, true);
            } else if (this.prev < entry.finallyLoc) {
              return handle(entry.finallyLoc);
            }

          } else if (hasCatch) {
            if (this.prev < entry.catchLoc) {
              return handle(entry.catchLoc, true);
            }

          } else if (hasFinally) {
            if (this.prev < entry.finallyLoc) {
              return handle(entry.finallyLoc);
            }

          } else {
            throw new Error("try statement without catch or finally");
          }
        }
      }
    },

    abrupt: function(type, arg) {
      for (var i = this.tryEntries.length - 1; i >= 0; --i) {
        var entry = this.tryEntries[i];
        if (entry.tryLoc <= this.prev &&
            hasOwn.call(entry, "finallyLoc") &&
            this.prev < entry.finallyLoc) {
          var finallyEntry = entry;
          break;
        }
      }

      if (finallyEntry &&
          (type === "break" ||
           type === "continue") &&
          finallyEntry.tryLoc <= arg &&
          arg <= finallyEntry.finallyLoc) {
        // Ignore the finally entry if control is not jumping to a
        // location outside the try/catch block.
        finallyEntry = null;
      }

      var record = finallyEntry ? finallyEntry.completion : {};
      record.type = type;
      record.arg = arg;

      if (finallyEntry) {
        this.method = "next";
        this.next = finallyEntry.finallyLoc;
        return ContinueSentinel;
      }

      return this.complete(record);
    },

    complete: function(record, afterLoc) {
      if (record.type === "throw") {
        throw record.arg;
      }

      if (record.type === "break" ||
          record.type === "continue") {
        this.next = record.arg;
      } else if (record.type === "return") {
        this.rval = this.arg = record.arg;
        this.method = "return";
        this.next = "end";
      } else if (record.type === "normal" && afterLoc) {
        this.next = afterLoc;
      }

      return ContinueSentinel;
    },

    finish: function(finallyLoc) {
      for (var i = this.tryEntries.length - 1; i >= 0; --i) {
        var entry = this.tryEntries[i];
        if (entry.finallyLoc === finallyLoc) {
          this.complete(entry.completion, entry.afterLoc);
          resetTryEntry(entry);
          return ContinueSentinel;
        }
      }
    },

    "catch": function(tryLoc) {
      for (var i = this.tryEntries.length - 1; i >= 0; --i) {
        var entry = this.tryEntries[i];
        if (entry.tryLoc === tryLoc) {
          var record = entry.completion;
          if (record.type === "throw") {
            var thrown = record.arg;
            resetTryEntry(entry);
          }
          return thrown;
        }
      }

      // The context.catch method must only be called with a location
      // argument that corresponds to a known catch block.
      throw new Error("illegal catch attempt");
    },

    delegateYield: function(iterable, resultName, nextLoc) {
      this.delegate = {
        iterator: values(iterable),
        resultName: resultName,
        nextLoc: nextLoc
      };

      if (this.method === "next") {
        // Deliberately forget the last sent value so that we don't
        // accidentally pass it on to the delegate.
        this.arg = undefined$1;
      }

      return ContinueSentinel;
    }
  };

  // Regardless of whether this script is executing as a CommonJS module
  // or not, return the runtime object so that we can declare the variable
  // regeneratorRuntime in the outer scope, which allows this module to be
  // injected easily by `bin/regenerator --include-runtime script.js`.
  return exports;

}(
  // If this script is executing as a CommonJS module, use module.exports
  // as the regeneratorRuntime namespace. Otherwise create a new empty
  // object. Either way, the resulting object will be used to initialize
  // the regeneratorRuntime variable at the top of this file.
  module.exports 
));

try {
  regeneratorRuntime = runtime;
} catch (accidentalStrictMode) {
  // This module should not be running in strict mode, so the above
  // assignment should always work unless something is misconfigured. Just
  // in case runtime.js accidentally runs in strict mode, we can escape
  // strict mode using a global Function call. This could conceivably fail
  // if a Content Security Policy forbids using Function, but in that case
  // the proper solution is to fix the accidental strict mode problem. If
  // you've misconfigured your bundler to force strict mode and applied a
  // CSP to forbid Function, and you're not willing to fix either of those
  // problems, please detail your unique predicament in a GitHub issue.
  Function("r", "regeneratorRuntime = r")(runtime);
}
});

var regenerator = runtime_1;

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
  try {
    var info = gen[key](arg);
    var value = info.value;
  } catch (error) {
    reject(error);
    return;
  }

  if (info.done) {
    resolve(value);
  } else {
    Promise.resolve(value).then(_next, _throw);
  }
}

function _asyncToGenerator(fn) {
  return function () {
    var self = this,
        args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);

      function _next(value) {
        asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }

      function _throw(err) {
        asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }

      _next(undefined);
    });
  };
}

function _defineProperties(target, props) {
  for (var i = 0; i < props.length; i++) {
    var descriptor = props[i];
    descriptor.enumerable = descriptor.enumerable || false;
    descriptor.configurable = true;
    if ("value" in descriptor) descriptor.writable = true;
    Object.defineProperty(target, descriptor.key, descriptor);
  }
}

function _createClass(Constructor, protoProps, staticProps) {
  if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  if (staticProps) _defineProperties(Constructor, staticProps);
  return Constructor;
}

function _classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}

var CancelToken = axios__default['default'].CancelToken;
var apiConfig$1 = {
  withCredentials: true,
  xsrfCookieName: 'csrftoken',
  xsrfHeaderName: 'X-CSRFToken'
};
var axiosWithconfig$1 = axios__default['default'].create(apiConfig$1);
/**
 * API client response.
 *
 * It's a wrapper/sieve around Axios to contain Axios coupling here. It maps
 * good and bad responses to a unified interface.
 *
 */

var DepositApiClientResponse = function DepositApiClientResponse(data, errors, code) {
  _classCallCheck(this, DepositApiClientResponse);

  this.data = data;
  this.errors = errors;
  this.code = code;
};
/**
 * API Client for deposits.
 *
 * It mostly uses the API links passed to it from responses.
 *
 */

var DepositApiClient = /*#__PURE__*/function () {
  function DepositApiClient(createUrl) {
    _classCallCheck(this, DepositApiClient);

    this.createUrl = createUrl;
  }

  _createClass(DepositApiClient, [{
    key: "createResponse",
    value: function () {
      var _createResponse = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(axios_call) {
        var response;
        return regenerator.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _context.prev = 0;
                _context.next = 3;
                return axios_call();

              case 3:
                response = _context.sent;
                return _context.abrupt("return", new DepositApiClientResponse(response.data, // exclude errors?
                response.data.errors, response.status));

              case 7:
                _context.prev = 7;
                _context.t0 = _context["catch"](0);
                return _context.abrupt("return", new DepositApiClientResponse(_context.t0.response.data, _context.t0.response.data.errors, _context.t0.response.status));

              case 10:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, null, [[0, 7]]);
      }));

      function createResponse(_x) {
        return _createResponse.apply(this, arguments);
      }

      return createResponse;
    }()
    /**
     * Calls the API to create a new draft.
     *
     * @param {object} draft - Serialized draft
     */

  }, {
    key: "create",
    value: function () {
      var _create = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2(draft) {
        var _this = this;

        return regenerator.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                return _context2.abrupt("return", this.createResponse(function () {
                  return axiosWithconfig$1.post(_this.createUrl, draft, {
                    headers: {
                      'Content-Type': 'application/json',
                      Accept: 'application/vnd.inveniordm.v1+json'
                    }
                  });
                }));

              case 1:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2, this);
      }));

      function create(_x2) {
        return _create.apply(this, arguments);
      }

      return create;
    }()
    /**
     * Calls the API to save a pre-existing draft.
     *
     * @param {object} draft - Serialized draft
     */

  }, {
    key: "save",
    value: function () {
      var _save = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee3(draft) {
        return regenerator.wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                return _context3.abrupt("return", this.createResponse(function () {
                  return axiosWithconfig$1.put(draft.links.self, draft, {
                    headers: {
                      'Content-Type': 'application/json',
                      Accept: 'application/vnd.inveniordm.v1+json'
                    }
                  });
                }));

              case 1:
              case "end":
                return _context3.stop();
            }
          }
        }, _callee3, this);
      }));

      function save(_x3) {
        return _save.apply(this, arguments);
      }

      return save;
    }()
    /**
     * Publishes the draft by calling its publish link.
     *
     * @param {object} draft - the payload from create()
     */

  }, {
    key: "publish",
    value: function () {
      var _publish = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee4(draft) {
        return regenerator.wrap(function _callee4$(_context4) {
          while (1) {
            switch (_context4.prev = _context4.next) {
              case 0:
                return _context4.abrupt("return", this.createResponse(function () {
                  return axiosWithconfig$1.post(draft.links.publish, {}, {
                    headers: {
                      'Content-Type': 'application/json'
                    }
                  });
                }));

              case 1:
              case "end":
                return _context4.stop();
            }
          }
        }, _callee4, this);
      }));

      function publish(_x4) {
        return _publish.apply(this, arguments);
      }

      return publish;
    }()
    /**
     * Deletes the draft by calling DELETE on its self link.
     *
     * @param {object} draft - the payload from create()/save()
     */

  }, {
    key: "delete",
    value: function () {
      var _delete2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee5(draft) {
        return regenerator.wrap(function _callee5$(_context5) {
          while (1) {
            switch (_context5.prev = _context5.next) {
              case 0:
                return _context5.abrupt("return", this.createResponse(function () {
                  return axiosWithconfig$1.delete(draft.links.self, {}, {
                    headers: {
                      'Content-Type': 'application/json'
                    }
                  });
                }));

              case 1:
              case "end":
                return _context5.stop();
            }
          }
        }, _callee5, this);
      }));

      function _delete(_x5) {
        return _delete2.apply(this, arguments);
      }

      return _delete;
    }() // TODO: Might consider extracting these out to a FilesApiClient.js

  }, {
    key: "initializeFileUpload",
    value: function initializeFileUpload(initializeUploadUrl, filename) {
      var payload = [{
        key: filename
      }];
      return axiosWithconfig$1.post(initializeUploadUrl, payload, {
        headers: {
          'content-type': 'application/json'
        }
      });
    }
  }, {
    key: "uploadFile",
    value: function uploadFile(uploadUrl, file, onUploadProgress, cancel) {
      var formData = new FormData();
      formData.append('file', file);
      return axiosWithconfig$1.put(uploadUrl, file, {
        headers: {
          'content-type': 'application/octet-stream'
        },
        onUploadProgress: onUploadProgress,
        cancelToken: new CancelToken(cancel)
      });
    }
  }, {
    key: "finalizeFileUpload",
    value: function finalizeFileUpload(finalizeUploadUrl) {
      return axiosWithconfig$1.post(finalizeUploadUrl, {}, {
        headers: {
          'content-type': 'application/json'
        }
      });
    }
  }, {
    key: "deleteFile",
    value: function deleteFile(deleteUrl) {
      return axiosWithconfig$1.delete(deleteUrl);
    }
  }, {
    key: "importParentRecordFiles",
    value: function importParentRecordFiles(importFilesUrl) {
      return axiosWithconfig$1.post(importFilesUrl, {}, {
        headers: {
          'content-type': 'application/json'
        }
      });
    }
    /**
     * Calls the API to reserve a PID.
     *
     */

  }, {
    key: "reservePID",
    value: function () {
      var _reservePID = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee6(links, pidType) {
        return regenerator.wrap(function _callee6$(_context6) {
          while (1) {
            switch (_context6.prev = _context6.next) {
              case 0:
                return _context6.abrupt("return", this.createResponse(function () {
                  var link = "".concat(links.self, "/pids/").concat(pidType); // PIDS-FIXME: should be uncommented when links for pids are released in backend
                  // const link = _get(links, `self_${pidType}`, '');
                  // if (link === '') {
                  //   throw Error(`Cannot get the link to discard the PID for ${pidType}`);
                  // }

                  // PIDS-FIXME: should be uncommented when links for pids are released in backend
                  // const link = _get(links, `self_${pidType}`, '');
                  // if (link === '') {
                  //   throw Error(`Cannot get the link to discard the PID for ${pidType}`);
                  // }
                  return axiosWithconfig$1.post(link, {}, {
                    headers: {
                      'Content-Type': 'application/json'
                    }
                  });
                }));

              case 1:
              case "end":
                return _context6.stop();
            }
          }
        }, _callee6, this);
      }));

      function reservePID(_x6, _x7) {
        return _reservePID.apply(this, arguments);
      }

      return reservePID;
    }()
    /**
     * Calls the API to discard a previously reserved PID.
     *
     */

  }, {
    key: "discardPID",
    value: function () {
      var _discardPID = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee7(links, pidType) {
        return regenerator.wrap(function _callee7$(_context7) {
          while (1) {
            switch (_context7.prev = _context7.next) {
              case 0:
                return _context7.abrupt("return", this.createResponse(function () {
                  var link = "".concat(links.self, "/pids/").concat(pidType); // PIDS-FIXME: should be uncommented when links for pids are released in backend
                  // const link = _get(links, `self_${pidType}`, '');
                  // if (link === '') {
                  //   throw Error(`Cannot get the link to discard the PID for ${pidType}`);
                  // }

                  // PIDS-FIXME: should be uncommented when links for pids are released in backend
                  // const link = _get(links, `self_${pidType}`, '');
                  // if (link === '') {
                  //   throw Error(`Cannot get the link to discard the PID for ${pidType}`);
                  // }
                  return axiosWithconfig$1.delete(link, {}, {
                    headers: {
                      'Content-Type': 'application/json'
                    }
                  });
                }));

              case 1:
              case "end":
                return _context7.stop();
            }
          }
        }, _callee7, this);
      }));

      function discardPID(_x8, _x9) {
        return _discardPID.apply(this, arguments);
      }

      return discardPID;
    }()
  }]);

  return DepositApiClient;
}();

function _arrayLikeToArray(arr, len) {
  if (len == null || len > arr.length) len = arr.length;

  for (var i = 0, arr2 = new Array(len); i < len; i++) {
    arr2[i] = arr[i];
  }

  return arr2;
}

function _unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return _arrayLikeToArray(o, minLen);
  var n = Object.prototype.toString.call(o).slice(8, -1);
  if (n === "Object" && o.constructor) n = o.constructor.name;
  if (n === "Map" || n === "Set") return Array.from(n);
  if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}

function _createForOfIteratorHelper(o) {
  if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
    if (Array.isArray(o) || (o = _unsupportedIterableToArray(o))) {
      var i = 0;

      var F = function F() {};

      return {
        s: F,
        n: function n() {
          if (i >= o.length) return {
            done: true
          };
          return {
            done: false,
            value: o[i++]
          };
        },
        e: function e(_e) {
          throw _e;
        },
        f: F
      };
    }

    throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  }

  var it,
      normalCompletion = true,
      didErr = false,
      err;
  return {
    s: function s() {
      it = o[Symbol.iterator]();
    },
    n: function n() {
      var step = it.next();
      normalCompletion = step.done;
      return step;
    },
    e: function e(_e2) {
      didErr = true;
      err = _e2;
    },
    f: function f() {
      try {
        if (!normalCompletion && it["return"] != null) it["return"]();
      } finally {
        if (didErr) throw err;
      }
    }
  };
}

// This file is part of React-Invenio-Deposit
// Copyright (C) 2020 CERN.
// Copyright (C) 2020 Northwestern University.
//
// React-Invenio-Deposit is free software; you can redistribute it and/or modify it
// under the terms of the MIT License; see LICENSE file for more details.
var FILE_UPLOAD_IN_PROGRESS = 'FILE_UPLOAD_IN_PROGRESS';
var FILE_UPLOAD_START = 'FILE_UPLOAD_START';
var FILE_UPLOAD_FINISHED = 'FILE_UPLOAD_FINISHED';
var FILE_UPLOAD_FAILED = 'FILE_UPLOAD_FAILED';
var FILE_IMPORT_STARTED = 'FILE_IMPORT_STARTED';
var FILE_IMPORT_SUCCESS = 'FILE_IMPORT_SUCCESS';
var FILE_IMPORT_FAILED = 'FILE_IMPORT_FAILED';
var FILE_DELETED_SUCCESS = 'FILE_DELETED_SUCCESS';
var FILE_DELETE_FAILED = 'FILE_DELETE_FAILED';
var FILE_UPLOAD_SET_CANCEL_FUNCTION = 'FILE_UPLOAD_SET_CANCEL_FUNCTION';
var FILE_UPLOAD_CANCELLED = 'FILE_UPLOAD_CANCELLED';
var FILE_UPLOAD_INITIATE = 'FILE_UPLOAD_INITIATE'; // Actions

var ACTION_CREATE_SUCCEEDED = 'ACTION_CREATE_SUCCEEDED';
var ACTION_DELETE_FAILED = 'ACTION_DELETE_FAILED';
var ACTION_PUBLISH_SUCCEEDED = 'ACTION_PUBLISH_SUCCEEDED';
var ACTION_PUBLISH_FAILED = 'ACTION_PUBLISH_FAILED';
var ACTION_SAVE_SUCCEEDED = 'ACTION_SAVE_SUCCEEDED';
var ACTION_SAVE_PARTIALLY_SUCCEEDED = 'ACTION_SAVE_PARTIALLY_SUCCEEDED';
var ACTION_SAVE_FAILED = 'ACTION_SAVE_FAILED'; // Form States

var FORM_ACTION_EVENT_EMITTED = 'FORM_ACTION_EVENT_EMITTED';
var FORM_DELETE_FAILED = 'FORM_DELETE_FAILED';
var FORM_SAVING = 'FORM_SAVING';
var FORM_SAVE_SUCCEEDED = 'FORM_SAVE_SUCCEEDED';
var FORM_SAVE_PARTIALLY_SUCCEEDED = 'FORM_SAVE_PARTIALLY_SUCCEEDED';
var FORM_SAVE_FAILED = 'FORM_SAVE_FAILED';
var FORM_PUBLISHING = 'FORM_PUBLISHING';
var FORM_PUBLISH_FAILED = 'FORM_PUBLISH_FAILED';
var FORM_PUBLISH_SUCCEEDED = 'FORM_PUBLISH_SUCCEEDED'; // PIDs reserve

var RESERVE_PID_STARTED = 'RESERVE_PID_STARTED';
var RESERVE_PID_SUCCESS = 'RESERVE_PID_SUCCESS';
var RESERVE_PID_FAILED = 'RESERVE_PID_FAILED'; // PIDs discard

var DISCARD_PID_STARTED = 'DISCARD_PID_STARTED';
var DISCARD_PID_SUCCESS = 'DISCARD_PID_SUCCESS';
var DISCARD_PID_FAILED = 'DISCARD_PID_FAILED';

var DepositController = /*#__PURE__*/function () {
  function DepositController(apiClient, fileUploader) {
    var _this = this;

    _classCallCheck(this, DepositController);

    this.reservePID = /*#__PURE__*/function () {
      var _ref2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(draft, pidType, _ref) {
        var formik, store, recordSerializer, response, data, errors;
        return regenerator.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                formik = _ref.formik, store = _ref.store;
                recordSerializer = store.config.recordSerializer;
                _context.next = 4;
                return _this.apiClient.reservePID(draft, pidType);

              case 4:
                response = _context.sent;
                data = recordSerializer.deserialize(response.data || {});
                errors = recordSerializer.deserializeErrors(response.errors || []);

                if (200 <= response.code && response.code < 300 && _isEmpty__default['default'](errors)) {
                  store.dispatch({
                    type: RESERVE_PID_SUCCESS,
                    payload: {
                      data: data
                    }
                  });
                } else {
                  store.dispatch({
                    type: RESERVE_PID_FAILED,
                    payload: {
                      data: data,
                      errors: errors
                    }
                  });
                  formik.setErrors(errors);
                }

              case 8:
              case "end":
                return _context.stop();
            }
          }
        }, _callee);
      }));

      return function (_x, _x2, _x3) {
        return _ref2.apply(this, arguments);
      };
    }();

    this.discardPID = /*#__PURE__*/function () {
      var _ref4 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2(draft, pidType, _ref3) {
        var formik, store, recordSerializer, response, data, errors;
        return regenerator.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                formik = _ref3.formik, store = _ref3.store;
                recordSerializer = store.config.recordSerializer;
                _context2.next = 4;
                return _this.apiClient.discardPID(draft, pidType);

              case 4:
                response = _context2.sent;
                data = recordSerializer.deserialize(response.data || {});
                errors = recordSerializer.deserializeErrors(response.errors || []);

                if (200 <= response.code && response.code < 300 && _isEmpty__default['default'](errors)) {
                  store.dispatch({
                    type: DISCARD_PID_SUCCESS,
                    payload: {
                      data: data
                    }
                  });
                } else {
                  store.dispatch({
                    type: DISCARD_PID_FAILED,
                    payload: {
                      data: data,
                      errors: errors
                    }
                  });
                  formik.setErrors(errors);
                }

              case 8:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2);
      }));

      return function (_x4, _x5, _x6) {
        return _ref4.apply(this, arguments);
      };
    }();

    this.apiClient = apiClient;
    this.fileUploader = fileUploader;
  }

  _createClass(DepositController, [{
    key: "draftAlreadyCreated",
    value: function draftAlreadyCreated(record) {
      return record.id ? true : false;
    }
    /**
     * Creates the current draft (backend) and changes URL to match its edit URL.
     *
     * @param {object} draft - current draft
     * @param {object} store - redux store
     */

  }, {
    key: "createDraft",
    value: function () {
      var _createDraft = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee3(draft, _ref5) {
        var store, recordSerializer, payload, response, draftURL;
        return regenerator.wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                store = _ref5.store;
                recordSerializer = store.config.recordSerializer;
                payload = recordSerializer.serialize(draft);
                _context3.next = 5;
                return this.apiClient.create(payload);

              case 5:
                response = _context3.sent;
                // TODO: Deal with case when create fails using formik.setErrors(errors);
                store.dispatch({
                  type: ACTION_CREATE_SUCCEEDED,
                  payload: {
                    data: recordSerializer.deserialize(response.data)
                  }
                });
                draftURL = response.data.links.self_html;
                window.history.replaceState(undefined, '', draftURL);
                return _context3.abrupt("return", response);

              case 10:
              case "end":
                return _context3.stop();
            }
          }
        }, _callee3, this);
      }));

      function createDraft(_x7, _x8) {
        return _createDraft.apply(this, arguments);
      }

      return createDraft;
    }()
    /**
     * Saves the current draft (backend) and changes URL to match its edit URL.
     *
     * @param {object} draft - current draft
     * @param {object} formik - the Formik object
     * @param {object} store - redux store
     */

  }, {
    key: "saveDraft",
    value: function () {
      var _saveDraft = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee4(draft, _ref6) {
        var formik, store, recordSerializer, response, payload, data, errors;
        return regenerator.wrap(function _callee4$(_context4) {
          while (1) {
            switch (_context4.prev = _context4.next) {
              case 0:
                formik = _ref6.formik, store = _ref6.store;
                recordSerializer = store.config.recordSerializer; // Set defaultPreview for files

                draft = _set__default['default'](draft, 'defaultFilePreview', store.getState().deposit.defaultFilePreview);
                response = {};

                if (this.draftAlreadyCreated(draft)) {
                  _context4.next = 10;
                  break;
                }

                _context4.next = 7;
                return this.createDraft(draft, {
                  store: store
                });

              case 7:
                response = _context4.sent;
                _context4.next = 14;
                break;

              case 10:
                payload = recordSerializer.serialize(draft);
                _context4.next = 13;
                return this.apiClient.save(payload);

              case 13:
                response = _context4.sent;

              case 14:
                data = recordSerializer.deserialize(response.data || {});
                errors = recordSerializer.deserializeErrors(response.errors || []); // response 100% successful

                if (200 <= response.code && response.code < 300 && _isEmpty__default['default'](errors)) {
                  store.dispatch({
                    type: ACTION_SAVE_SUCCEEDED,
                    payload: {
                      data: data
                    }
                  });
                } // response partially successful
                else if (200 <= response.code && response.code < 300) {
                    store.dispatch({
                      type: ACTION_SAVE_PARTIALLY_SUCCEEDED,
                      payload: {
                        data: data,
                        errors: errors
                      }
                    });
                    formik.setErrors(errors);
                  } // response exceptionally bad
                  else {
                      store.dispatch({
                        type: ACTION_SAVE_FAILED,
                        payload: {
                          errors: errors
                        }
                      });
                      formik.setErrors(errors);
                    }

                formik.setSubmitting(false);

              case 18:
              case "end":
                return _context4.stop();
            }
          }
        }, _callee4, this);
      }));

      function saveDraft(_x9, _x10) {
        return _saveDraft.apply(this, arguments);
      }

      return saveDraft;
    }()
    /**
     * Publishes the current draft (backend) and redirects to its view URL.
     *
     * @param {object} draft - current draft
     * @param {object} formik - the Formik object
     * @param {object} store - redux store
     */

  }, {
    key: "publishDraft",
    value: function () {
      var _publishDraft = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee5(draft, _ref7) {
        var formik, store, recordSerializer, response, payload, data, errors, recordURL;
        return regenerator.wrap(function _callee5$(_context5) {
          while (1) {
            switch (_context5.prev = _context5.next) {
              case 0:
                formik = _ref7.formik, store = _ref7.store;
                recordSerializer = store.config.recordSerializer;
                response = {};

                if (this.draftAlreadyCreated(draft)) {
                  _context5.next = 7;
                  break;
                }

                _context5.next = 6;
                return this.createDraft(draft, {
                  store: store
                });

              case 6:
                response = _context5.sent;

              case 7:
                payload = recordSerializer.serialize(draft);
                _context5.next = 10;
                return this.apiClient.publish(payload);

              case 10:
                response = _context5.sent;
                data = recordSerializer.deserialize(response.data || {});
                errors = recordSerializer.deserializeErrors(response.errors || []); // response 100% successful

                if (200 <= response.code && response.code < 300 && _isEmpty__default['default'](errors)) {
                  store.dispatch({
                    type: ACTION_PUBLISH_SUCCEEDED,
                    payload: {
                      data: data
                    }
                  });
                  recordURL = response.data.links.self_html;
                  window.location.replace(recordURL);
                } // "succeed or not, there is no partial"
                else {
                    store.dispatch({
                      type: ACTION_PUBLISH_FAILED,
                      payload: {
                        data: data,
                        errors: errors
                      }
                    });
                    formik.setErrors(errors);
                  }

                formik.setSubmitting(false);

              case 15:
              case "end":
                return _context5.stop();
            }
          }
        }, _callee5, this);
      }));

      function publishDraft(_x11, _x12) {
        return _publishDraft.apply(this, arguments);
      }

      return publishDraft;
    }()
    /**
     * Deletes the current draft and redirects to uploads page.
     *
     * The current draft may not have been saved yet. We only delete the draft
     * if it has been saved.
     *
     * @param {object} draft - current draft
     */

  }, {
    key: "deleteDraft",
    value: function () {
      var _deleteDraft = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee6(draft, _ref8) {
        var store, response, uploadsURL;
        return regenerator.wrap(function _callee6$(_context6) {
          while (1) {
            switch (_context6.prev = _context6.next) {
              case 0:
                store = _ref8.store;

                if (!draft.id) {
                  _context6.next = 8;
                  break;
                }

                _context6.next = 4;
                return this.apiClient.delete(draft);

              case 4:
                response = _context6.sent;

                if (200 <= response.code && response.code < 300) {
                  _context6.next = 8;
                  break;
                }

                store.dispatch({
                  type: ACTION_DELETE_FAILED,
                  payload: {}
                });
                return _context6.abrupt("return");

              case 8:
                uploadsURL = '/uploads';
                window.location.replace(uploadsURL);

              case 10:
              case "end":
                return _context6.stop();
            }
          }
        }, _callee6, this);
      }));

      function deleteDraft(_x13, _x14) {
        return _deleteDraft.apply(this, arguments);
      }

      return deleteDraft;
    }()
    /**
     * Uploads the draft's files.
     *
     * The current draft may not have been saved yet. We create it if not.
     *
     * @param {object} draft - current draft
     * @param {object} files - files to upload
     * @param {object} store - redux store
     */

  }, {
    key: "uploadDraftFiles",
    value: function () {
      var _uploadDraftFiles = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee7(draft, files, _ref9) {
        var store, response, recordSerializer, payload, _iterator, _step, file, uploadFileUrl;

        return regenerator.wrap(function _callee7$(_context7) {
          while (1) {
            switch (_context7.prev = _context7.next) {
              case 0:
                store = _ref9.store;

                if (this.draftAlreadyCreated(draft)) {
                  _context7.next = 8;
                  break;
                }

                _context7.next = 4;
                return this.createDraft(draft, {
                  store: store
                });

              case 4:
                response = _context7.sent;
                draft = response.data;
                _context7.next = 12;
                break;

              case 8:
                // We have to save draft before we upload files, because files might have
                // been disabled and we need to re-enable them first. We do it
                // "stealthily" (not using saveDraft) so as to provide a nice UX.
                recordSerializer = store.config.recordSerializer;
                payload = recordSerializer.serialize(draft);
                _context7.next = 12;
                return this.apiClient.save(payload);

              case 12:
                _iterator = _createForOfIteratorHelper(files);

                try {
                  for (_iterator.s(); !(_step = _iterator.n()).done;) {
                    file = _step.value;
                    uploadFileUrl = draft.links.files;
                    this.fileUploader.upload(uploadFileUrl, file, {
                      store: store
                    });
                  }
                } catch (err) {
                  _iterator.e(err);
                } finally {
                  _iterator.f();
                }

              case 14:
              case "end":
                return _context7.stop();
            }
          }
        }, _callee7, this);
      }));

      function uploadDraftFiles(_x15, _x16, _x17) {
        return _uploadDraftFiles.apply(this, arguments);
      }

      return uploadDraftFiles;
    }()
    /**
     * Delete an uploaded file.
     *
     * @param {object} file - file to delete
     * @param {object} store - redux store
     */

  }, {
    key: "deleteDraftFile",
    value: function () {
      var _deleteDraftFile = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee8(file, _ref10) {
        var store, deleteFileUrl;
        return regenerator.wrap(function _callee8$(_context8) {
          while (1) {
            switch (_context8.prev = _context8.next) {
              case 0:
                store = _ref10.store;
                deleteFileUrl = file.links.self;
                _context8.next = 4;
                return this.fileUploader.deleteUpload(deleteFileUrl, file, {
                  store: store
                });

              case 4:
              case "end":
                return _context8.stop();
            }
          }
        }, _callee8, this);
      }));

      function deleteDraftFile(_x18, _x19) {
        return _deleteDraftFile.apply(this, arguments);
      }

      return deleteDraftFile;
    }()
    /**
     * Imports parent record files into the draft
     *
     * Should only be used with already saved draft
     *
     * @param {object} draft - current draft
     * @param {object} store - redux store
     */

  }, {
    key: "importParentRecordFiles",
    value: function () {
      var _importParentRecordFiles = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee9(draft, _ref11) {
        var store, importFilesUrl;
        return regenerator.wrap(function _callee9$(_context9) {
          while (1) {
            switch (_context9.prev = _context9.next) {
              case 0:
                store = _ref11.store;

                if (draft.id) {
                  _context9.next = 3;
                  break;
                }

                return _context9.abrupt("return");

              case 3:
                importFilesUrl = draft.links.self + '/actions/files-import';
                _context9.next = 6;
                return this.fileUploader.importParentRecordFiles(importFilesUrl, {
                  store: store
                });

              case 6:
              case "end":
                return _context9.stop();
            }
          }
        }, _callee9, this);
      }));

      function importParentRecordFiles(_x20, _x21) {
        return _importParentRecordFiles.apply(this, arguments);
      }

      return importParentRecordFiles;
    }()
    /**
     * Reserve a PID
     */

  }]);

  return DepositController;
}();

function _setPrototypeOf(o, p) {
  _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };

  return _setPrototypeOf(o, p);
}

function _inherits(subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function");
  }

  subClass.prototype = Object.create(superClass && superClass.prototype, {
    constructor: {
      value: subClass,
      writable: true,
      configurable: true
    }
  });
  if (superClass) _setPrototypeOf(subClass, superClass);
}

function _getPrototypeOf(o) {
  _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return _getPrototypeOf(o);
}

function _isNativeReflectConstruct() {
  if (typeof Reflect === "undefined" || !Reflect.construct) return false;
  if (Reflect.construct.sham) return false;
  if (typeof Proxy === "function") return true;

  try {
    Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
    return true;
  } catch (e) {
    return false;
  }
}

function _typeof(obj) {
  "@babel/helpers - typeof";

  if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
    _typeof = function _typeof(obj) {
      return typeof obj;
    };
  } else {
    _typeof = function _typeof(obj) {
      return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
    };
  }

  return _typeof(obj);
}

function _assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }

  return self;
}

function _possibleConstructorReturn(self, call) {
  if (call && (_typeof(call) === "object" || typeof call === "function")) {
    return call;
  }

  return _assertThisInitialized(self);
}

function _createSuper(Derived) {
  return function () {
    var Super = _getPrototypeOf(Derived),
        result;

    if (_isNativeReflectConstruct()) {
      var NewTarget = _getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }

    return _possibleConstructorReturn(this, result);
  };
}

function _objectWithoutPropertiesLoose(source, excluded) {
  if (source == null) return {};
  var target = {};
  var sourceKeys = Object.keys(source);
  var key, i;

  for (i = 0; i < sourceKeys.length; i++) {
    key = sourceKeys[i];
    if (excluded.indexOf(key) >= 0) continue;
    target[key] = source[key];
  }

  return target;
}

function _objectWithoutProperties(source, excluded) {
  if (source == null) return {};
  var target = _objectWithoutPropertiesLoose(source, excluded);
  var key, i;

  if (Object.getOwnPropertySymbols) {
    var sourceSymbolKeys = Object.getOwnPropertySymbols(source);

    for (i = 0; i < sourceSymbolKeys.length; i++) {
      key = sourceSymbolKeys[i];
      if (excluded.indexOf(key) >= 0) continue;
      if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
      target[key] = source[key];
    }
  }

  return target;
}

function _defineProperty(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }

  return obj;
}

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 _objectSpread2(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) {
        _defineProperty(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;
}

var publish$4 = function publish(record, formik) {
  return function (dispatch, getState, config) {
    var controller = config.controller;
    return controller.publishDraft(record, {
      formik: formik,
      store: {
        dispatch: dispatch,
        getState: getState,
        config: config
      }
    });
  };
};
var save = function save(record, formik) {
  return function (dispatch, getState, config) {
    var controller = config.controller;
    return controller.saveDraft(record, {
      formik: formik,
      store: {
        dispatch: dispatch,
        getState: getState,
        config: config
      }
    });
  };
};
var submitAction = function submitAction(action, event, formik) {
  return function (dispatch, getState, config) {
    dispatch({
      type: FORM_ACTION_EVENT_EMITTED,
      payload: action
    });
    formik.handleSubmit(event); // eventually calls submitFormData below
  };
};
var submitFormData = function submitFormData(record, formik) {
  return function (dispatch, getState, config) {
    var formState = getState().deposit.formState;

    switch (formState) {
      case FORM_SAVING:
        return dispatch(save(record, formik));

      case FORM_PUBLISHING:
        return dispatch(publish$4(record, formik));

      default:
        console.log("onSubmit triggered with unknown action ".concat(formState));
    }
  };
};
/**
 * Returns the function that controls draft deletion.
 *
 * This function is different from the save/publish above because this thunk
 * is independent of form submission.
 *
 * @param {object} event - click event
 * @param {object} formik - formik object
 */

var discard = function discard(event, formik) {
  return function (dispatch, getState, extra) {
    var controller = extra.controller;
    var record = getState().deposit.record;
    return controller.deleteDraft(record, {
      formik: formik,
      store: {
        dispatch: dispatch,
        getState: getState,
        extra: extra
      }
    });
  };
};
/**
 * Reserve the PID after having saved the current draft
 * @param {string} pidType - the PID type to reserve the PID for
 * @param {object} formik- formik object
 */

var reservePID = function reservePID(pidType, formik) {
  return /*#__PURE__*/function () {
    var _ref = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(dispatch, getState, config) {
      var controller, draft, links;
      return regenerator.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              controller = config.controller;
              dispatch({
                type: RESERVE_PID_STARTED
              }); // PIDS-FIXME: this is not the latest version of the form values,
              // it will replace the form values with what was in the record

              draft = getState().deposit.record;
              _context.next = 5;
              return dispatch(save(draft, formik));

            case 5:
              links = getState().deposit.record.links;
              return _context.abrupt("return", controller.reservePID(links, pidType, {
                formik: formik,
                store: {
                  dispatch: dispatch,
                  getState: getState,
                  config: config
                }
              }));

            case 7:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }));

    return function (_x, _x2, _x3) {
      return _ref.apply(this, arguments);
    };
  }();
};
/**
 * Discard a previously reserved PID
 * @param {string} pidType - the PID type to discard the PID for
 */

var discardPID = function discardPID(pidType, formik) {
  return /*#__PURE__*/function () {
    var _ref2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2(dispatch, getState, config) {
      var controller, draft, links;
      return regenerator.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              controller = config.controller;
              dispatch({
                type: DISCARD_PID_STARTED
              }); // PIDS-FIXME: this is not the latest version of the form values,
              // it will replace the form values with what was in the record

              draft = getState().deposit.record;
              _context2.next = 5;
              return dispatch(save(draft, formik));

            case 5:
              links = getState().deposit.record.links;
              return _context2.abrupt("return", controller.discardPID(links, pidType, {
                formik: formik,
                store: {
                  dispatch: dispatch,
                  getState: getState,
                  config: config
                }
              }));

            case 7:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2);
    }));

    return function (_x4, _x5, _x6) {
      return _ref2.apply(this, arguments);
    };
  }();
};

// This file is part of React-Invenio-Deposit
// Copyright (C) 2020-2021 CERN.
// Copyright (C) 2020-2021 Northwestern University.
//
// React-Invenio-Deposit is free software; you can redistribute it and/or modify it
// under the terms of the MIT License; see LICENSE file for more details.
var uploadDraftFiles = function uploadDraftFiles(draft, files) {
  return function (dispatch, getState, config) {
    var controller = config.controller;
    return controller.uploadDraftFiles(draft, files, {
      store: {
        dispatch: dispatch,
        getState: getState,
        config: config
      }
    });
  };
};
var importParentRecordFiles = function importParentRecordFiles() {
  return function (dispatch, getState, config) {
    var controller = config.controller;
    var draft = getState().deposit.record;
    return controller.importParentRecordFiles(draft, {
      store: {
        dispatch: dispatch,
        getState: getState,
        config: config
      }
    });
  };
};
var deleteDraftFile = function deleteDraftFile(file) {
  return function (dispatch, getState, config) {
    var controller = config.controller;
    return controller.deleteDraftFile(file, {
      store: {
        dispatch: dispatch,
        getState: getState,
        config: config
      }
    });
  };
};

var _excluded$9 = ["isFileUploadInProgress"];

var DepositBootstrapComponent = /*#__PURE__*/function (_Component) {
  _inherits(DepositBootstrapComponent, _Component);

  var _super = _createSuper(DepositBootstrapComponent);

  function DepositBootstrapComponent() {
    _classCallCheck(this, DepositBootstrapComponent);

    return _super.apply(this, arguments);
  }

  _createClass(DepositBootstrapComponent, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var _this = this;

      window.addEventListener('beforeunload', function (e) {
        if (_this.props.fileUploadOngoing) {
          e.returnValue = '';
          return '';
        }
      });
      window.addEventListener('unload', /*#__PURE__*/function () {
        var _ref = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(e) {
          return regenerator.wrap(function _callee$(_context) {
            while (1) {
              switch (_context.prev = _context.next) {
                case 0:
                case "end":
                  return _context.stop();
              }
            }
          }, _callee);
        }));

        return function (_x) {
          return _ref.apply(this, arguments);
        };
      }());
    }
  }, {
    key: "render",
    value: function render() {
      return /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.BaseForm, {
        onSubmit: this.props.submitFormData,
        formik: _objectSpread2({
          enableReinitialize: true,
          // Needed for files
          initialValues: this.props.record
        }, this.props.errors && {
          initialErrors: this.props.errors
        })
      }, this.props.children);
    }
  }]);

  return DepositBootstrapComponent;
}(React.Component);

var mapStateToProps$9 = function mapStateToProps(state) {
  var _state$files = state.files,
      isFileUploadInProgress = _state$files.isFileUploadInProgress,
      files = _objectWithoutProperties(_state$files, _excluded$9);

  return {
    record: state.deposit.record,
    errors: state.deposit.errors,
    formState: state.deposit.formState,
    fileUploadOngoing: isFileUploadInProgress,
    files: files
  };
};

var mapDispatchToProps$6 = function mapDispatchToProps(dispatch) {
  return {
    submitFormData: function submitFormData$1(values, formik) {
      return dispatch(submitFormData(values, formik));
    }
  };
};

var DepositBootstrap = reactRedux.connect(mapStateToProps$9, mapDispatchToProps$6)(DepositBootstrapComponent);

function _toPrimitive(input, hint) {
  if (_typeof(input) !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];

  if (prim !== undefined) {
    var res = prim.call(input, hint || "default");
    if (_typeof(res) !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }

  return (hint === "string" ? String : Number)(input);
}

function _toPropertyKey(arg) {
  var key = _toPrimitive(arg, "string");
  return _typeof(key) === "symbol" ? key : String(key);
}

var UploadState = {
  initial: 'initial',
  // no file or the initial file selected
  uploading: 'uploading',
  // currently uploading a file from the UI
  error: 'error',
  // upload failed
  finished: 'finished',
  // upload finished (uploaded file is the field's current file)
  pending: 'pending' // files retrieved from the backend are in pending state

};
var initialState$1 = {};
var fileReducer = (function () {
  var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState$1;
  var action = arguments.length > 1 ? arguments[1] : undefined;
  var newState;

  switch (action.type) {
    case FILE_UPLOAD_INITIATE:
      return _objectSpread2(_objectSpread2({}, state), {}, {
        entries: _objectSpread2(_objectSpread2({}, state.entries), {}, _defineProperty({}, action.payload.filename, {
          progress: 0,
          name: action.payload.filename,
          size: action.payload.size,
          status: UploadState.initial,
          checksum: null,
          links: null,
          cancel: null
        }))
      });

    case FILE_UPLOAD_START:
      return _objectSpread2(_objectSpread2({}, state), {}, {
        entries: _objectSpread2(_objectSpread2({}, state.entries), {}, _defineProperty({}, action.payload.filename, {
          progress: 0,
          name: action.payload.filename,
          size: action.payload.size,
          status: UploadState.uploading,
          checksum: null,
          links: null,
          cancel: null
        })),
        isFileUploadInProgress: true
      });

    case FILE_UPLOAD_IN_PROGRESS:
      return _objectSpread2(_objectSpread2({}, state), {}, {
        entries: _objectSpread2(_objectSpread2({}, state.entries), {}, _defineProperty({}, action.payload.filename, _objectSpread2(_objectSpread2({}, state.entries[action.payload.filename]), {}, {
          progress: action.payload.percent,
          status: UploadState.uploading
        })))
      });

    case FILE_UPLOAD_FINISHED:
      newState = _objectSpread2(_objectSpread2({}, state), {}, {
        entries: _objectSpread2(_objectSpread2({}, state.entries), {}, _defineProperty({}, action.payload.filename, _objectSpread2(_objectSpread2({}, state.entries[action.payload.filename]), {}, {
          status: UploadState.finished,
          size: action.payload.size,
          progress: 100,
          checksum: action.payload.checksum,
          links: action.payload.links,
          cancel: null
        })))
      });
      return _objectSpread2(_objectSpread2({}, newState), {}, {
        isFileUploadInProgress: Object.values(newState.entries).some(function (value) {
          return value.status === UploadState.uploading;
        })
      });

    case FILE_UPLOAD_FAILED:
      newState = _objectSpread2(_objectSpread2({}, state), {}, {
        entries: _objectSpread2(_objectSpread2({}, state.entries), {}, _defineProperty({}, action.payload.filename, _objectSpread2(_objectSpread2({}, state.entries[action.payload.filename]), {}, {
          status: UploadState.error,
          cancel: null
        })))
      });
      return _objectSpread2(_objectSpread2({}, newState), {}, {
        isFileUploadInProgress: Object.values(newState.entries).some(function (value) {
          return value.status === UploadState.uploading;
        })
      });

    case FILE_UPLOAD_SET_CANCEL_FUNCTION:
      return _objectSpread2(_objectSpread2({}, state), {}, {
        entries: _objectSpread2(_objectSpread2({}, state.entries), {}, _defineProperty({}, action.payload.filename, _objectSpread2(_objectSpread2({}, state.entries[action.payload.filename]), {}, {
          cancel: action.payload.cancel
        })))
      });

    case FILE_UPLOAD_CANCELLED:
      var _state$entries = state.entries,
          _action$payload$filen = action.payload.filename;
          _state$entries[_action$payload$filen];
          var afterCancellationEntriesState = _objectWithoutProperties(_state$entries, [_action$payload$filen].map(_toPropertyKey));

      return _objectSpread2(_objectSpread2({}, state), {}, {
        entries: _objectSpread2({}, afterCancellationEntriesState),
        isFileUploadInProgress: Object.values(afterCancellationEntriesState).some(function (value) {
          return value.status === UploadState.uploading;
        })
      });

    case FILE_DELETED_SUCCESS:
      var _state$entries2 = state.entries,
          _action$payload$filen2 = action.payload.filename;
          _state$entries2[_action$payload$filen2];
          var afterDeletionEntriesState = _objectWithoutProperties(_state$entries2, [_action$payload$filen2].map(_toPropertyKey));

      return _objectSpread2(_objectSpread2({}, state), {}, {
        entries: _objectSpread2({}, afterDeletionEntriesState),
        isFileUploadInProgress: Object.values(afterDeletionEntriesState).some(function (value) {
          return value.status === UploadState.uploading;
        })
      });

    case FILE_DELETE_FAILED:
      // TODO: handle
      return state;

    case FILE_IMPORT_STARTED:
      return _objectSpread2(_objectSpread2({}, state), {}, {
        isFileImportInProgress: true
      });

    case FILE_IMPORT_SUCCESS:
      return _objectSpread2(_objectSpread2({}, state), {}, {
        entries: _objectSpread2({}, action.payload.files),
        isFileImportInProgress: false
      });

    case FILE_IMPORT_FAILED:
      return _objectSpread2(_objectSpread2({}, state), {}, {
        isFileImportInProgress: false
      });

    default:
      return state;
  }
});

var DepositFileUploader = /*#__PURE__*/function () {
  function DepositFileUploader(apiClient) {
    var _this = this;

    var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
        fileUploadConcurrency = _ref.fileUploadConcurrency;

    _classCallCheck(this, DepositFileUploader);

    this._uploadNext = function () {
      var nextUpload;

      if (_this.pending.length > 0) {
        nextUpload = _this._removeFromPending();
      }

      if (nextUpload) {
        _this.upload(nextUpload.initializeUploadUrl, nextUpload.file, {
          store: nextUpload.store
        });
      } else if (!_this.currentUploads.length) {
        _this._flushQueues();
      }
    };

    this.initializeUpload = /*#__PURE__*/function () {
      var _ref3 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(initializeUploadUrl, file, _ref2) {
        var store, resp, initializedFile;
        return regenerator.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                store = _ref2.store;
                _context.prev = 1;

                _this._addToCurrentUploads(file);

                _context.next = 5;
                return _this.apiClient.initializeFileUpload(initializeUploadUrl, file.name);

              case 5:
                resp = _context.sent;
                initializedFile = resp.data.entries.filter(function (entry) {
                  return entry.key === file.name;
                })[0]; // this should throw an error if not found

                store.dispatch({
                  type: FILE_UPLOAD_INITIATE,
                  payload: {
                    filename: initializedFile.key
                  }
                });
                return _context.abrupt("return", initializedFile);

              case 11:
                _context.prev = 11;
                _context.t0 = _context["catch"](1);
                console.error(_context.t0);

              case 14:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, null, [[1, 11]]);
      }));

      return function (_x, _x2, _x3) {
        return _ref3.apply(this, arguments);
      };
    }();

    this.startUpload = /*#__PURE__*/function () {
      var _ref5 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2(uploadUrl, file, _ref4) {
        var store;
        return regenerator.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                store = _ref4.store;
                store.dispatch({
                  type: FILE_UPLOAD_START,
                  payload: {
                    filename: file.name
                  }
                });
                _context2.prev = 2;
                _context2.next = 5;
                return _this.apiClient.uploadFile(uploadUrl, file, function (e) {
                  store.dispatch({
                    type: FILE_UPLOAD_IN_PROGRESS,
                    payload: {
                      filename: file.name,
                      percent: Math.floor(e.loaded / e.total * 100)
                    }
                  });
                }, function (c) {
                  // A cancel function for aborting the upload request
                  store.dispatch({
                    type: FILE_UPLOAD_SET_CANCEL_FUNCTION,
                    payload: {
                      filename: file.name,
                      cancel: c
                    }
                  });
                });

              case 5:
                _context2.next = 14;
                break;

              case 7:
                _context2.prev = 7;
                _context2.t0 = _context2["catch"](2);

                if (!axios__default['default'].isCancel(_context2.t0)) {
                  _context2.next = 13;
                  break;
                }

                throw new Error(FILE_UPLOAD_CANCELLED);

              case 13:
                throw new Error(FILE_UPLOAD_FAILED);

              case 14:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2, null, [[2, 7]]);
      }));

      return function (_x4, _x5, _x6) {
        return _ref5.apply(this, arguments);
      };
    }();

    this.finalizeUpload = /*#__PURE__*/function () {
      var _ref7 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee3(finalizeUploadUrl, file, _ref6) {
        var store, resp;
        return regenerator.wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                store = _ref6.store;
                _context3.prev = 1;

                // Regardless of what is the status of the finalize step we start
                // the next upload in the queue
                _this._removeFromCurrentUploads(file);

                _this._uploadNext();

                _context3.next = 6;
                return _this.apiClient.finalizeFileUpload(finalizeUploadUrl);

              case 6:
                resp = _context3.sent;
                store.dispatch({
                  type: FILE_UPLOAD_FINISHED,
                  payload: {
                    filename: resp.data.key,
                    size: resp.data.size,
                    checksum: resp.data.checksum,
                    links: resp.data.links
                  }
                });
                _context3.next = 13;
                break;

              case 10:
                _context3.prev = 10;
                _context3.t0 = _context3["catch"](1);
                throw new Error(FILE_UPLOAD_FAILED);

              case 13:
              case "end":
                return _context3.stop();
            }
          }
        }, _callee3, null, [[1, 10]]);
      }));

      return function (_x7, _x8, _x9) {
        return _ref7.apply(this, arguments);
      };
    }();

    this.upload = /*#__PURE__*/function () {
      var _ref9 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee4(initializeUploadUrl, file, _ref8) {
        var store, initializedFileMetadata, startUploadUrl, finalizeFileUrl, deleteFileUrl, isUploadCancelledOrFailed;
        return regenerator.wrap(function _callee4$(_context4) {
          while (1) {
            switch (_context4.prev = _context4.next) {
              case 0:
                store = _ref8.store;

                if (!(_this.currentUploads.length < _this.maxConcurrentUploads)) {
                  _context4.next = 23;
                  break;
                }

                _context4.next = 4;
                return _this.initializeUpload(initializeUploadUrl, file, {
                  store: store
                });

              case 4:
                initializedFileMetadata = _context4.sent;
                startUploadUrl = initializedFileMetadata.links.content; // FIXME: rename to links.complete

                finalizeFileUrl = initializedFileMetadata.links.commit;
                deleteFileUrl = initializedFileMetadata.links.self;
                _context4.prev = 8;
                _context4.next = 11;
                return _this.startUpload(startUploadUrl, file, {
                  store: store
                });

              case 11:
                _this.finalizeUpload(finalizeFileUrl, file, {
                  store: store
                });

                _context4.next = 21;
                break;

              case 14:
                _context4.prev = 14;
                _context4.t0 = _context4["catch"](8);
                // TODO: should handle `FILE_UPLOAD_FAILED` from intermediate requests
                isUploadCancelledOrFailed = [FILE_UPLOAD_CANCELLED, FILE_UPLOAD_FAILED].some(function (msg) {
                  return _context4.t0.message === msg;
                });

                if (!isUploadCancelledOrFailed) {
                  _context4.next = 21;
                  break;
                }

                _context4.next = 20;
                return _this.deleteUpload(deleteFileUrl, file, {
                  store: store
                });

              case 20:
                store.dispatch({
                  type: _context4.t0.message,
                  payload: {
                    filename: file.name
                  }
                });

              case 21:
                _context4.next = 24;
                break;

              case 23:
                _this._addToPending({
                  initializeUploadUrl: initializeUploadUrl,
                  file: file,
                  store: store
                });

              case 24:
              case "end":
                return _context4.stop();
            }
          }
        }, _callee4, null, [[8, 14]]);
      }));

      return function (_x10, _x11, _x12) {
        return _ref9.apply(this, arguments);
      };
    }();

    this.deleteUpload = /*#__PURE__*/function () {
      var _ref11 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee5(fileDeletionUrl, file, _ref10) {
        var store;
        return regenerator.wrap(function _callee5$(_context5) {
          while (1) {
            switch (_context5.prev = _context5.next) {
              case 0:
                store = _ref10.store;
                _context5.prev = 1;
                _context5.next = 4;
                return _this.apiClient.deleteFile(fileDeletionUrl);

              case 4:
                store.dispatch({
                  type: FILE_DELETED_SUCCESS,
                  payload: {
                    filename: file.name
                  }
                });
                _context5.next = 10;
                break;

              case 7:
                _context5.prev = 7;
                _context5.t0 = _context5["catch"](1);
                store.dispatch({
                  type: FILE_DELETE_FAILED
                });

              case 10:
              case "end":
                return _context5.stop();
            }
          }
        }, _callee5, null, [[1, 7]]);
      }));

      return function (_x13, _x14, _x15) {
        return _ref11.apply(this, arguments);
      };
    }();

    this.importParentRecordFiles = /*#__PURE__*/function () {
      var _ref13 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee6(importFilesUrl, _ref12) {
        var store, response, files;
        return regenerator.wrap(function _callee6$(_context6) {
          while (1) {
            switch (_context6.prev = _context6.next) {
              case 0:
                store = _ref12.store;
                store.dispatch({
                  type: FILE_IMPORT_STARTED
                });
                _context6.prev = 2;
                _context6.next = 5;
                return _this.apiClient.importParentRecordFiles(importFilesUrl);

              case 5:
                response = _context6.sent;
                files = response.data.entries.reduce(function (acc, file) {
                  return _objectSpread2(_objectSpread2({}, acc), {}, _defineProperty({}, file.key, {
                    status: UploadState.finished,
                    size: file.size,
                    name: file.key,
                    progress: 100,
                    checksum: file.checksum,
                    links: file.links
                  }));
                }, {});
                store.dispatch({
                  type: FILE_IMPORT_SUCCESS,
                  payload: {
                    files: files
                  }
                });
                _context6.next = 13;
                break;

              case 10:
                _context6.prev = 10;
                _context6.t0 = _context6["catch"](2);
                //TODO: show notification on failure
                store.dispatch({
                  type: FILE_IMPORT_FAILED
                });

              case 13:
              case "end":
                return _context6.stop();
            }
          }
        }, _callee6, null, [[2, 10]]);
      }));

      return function (_x16, _x17) {
        return _ref13.apply(this, arguments);
      };
    }();

    this.apiClient = apiClient;
    this.currentUploads = [];
    this.pending = [];
    this.maxConcurrentUploads = fileUploadConcurrency || 3;
  }

  _createClass(DepositFileUploader, [{
    key: "_addToCurrentUploads",
    value: function _addToCurrentUploads(file) {
      return this.currentUploads.push(file);
    }
  }, {
    key: "_removeFromCurrentUploads",
    value: function _removeFromCurrentUploads(file) {
      this.currentUploads.splice(_indexOf__default['default'](this.currentUploads, file), 1);
    }
  }, {
    key: "_addToPending",
    value: function _addToPending(file) {
      this.pending.push(file);
    }
  }, {
    key: "_removeFromPending",
    value: function _removeFromPending() {
      return this.pending.shift();
    }
  }, {
    key: "_flushQueues",
    value: function _flushQueues() {
      this.currentUploads = [];
      this.pending = [];
    }
  }]);

  return DepositFileUploader;
}();

var Field = /*#__PURE__*/function () {
  function Field(_ref) {
    var fieldpath = _ref.fieldpath,
        _ref$deserializedDefa = _ref.deserializedDefault,
        deserializedDefault = _ref$deserializedDefa === void 0 ? null : _ref$deserializedDefa,
        _ref$serializedDefaul = _ref.serializedDefault,
        serializedDefault = _ref$serializedDefaul === void 0 ? null : _ref$serializedDefaul;

    _classCallCheck(this, Field);

    this.fieldpath = fieldpath;
    this.deserializedDefault = deserializedDefault;
    this.serializedDefault = serializedDefault;
  }

  _createClass(Field, [{
    key: "deserialize",
    value: function deserialize(record) {
      var fieldValue = _get__default['default'](record, this.fieldpath, this.deserializedDefault);

      if (fieldValue !== null) {
        return _set__default['default'](_cloneDeep__default['default'](record), this.fieldpath, fieldValue);
      }

      return record;
    }
  }, {
    key: "serialize",
    value: function serialize(record) {
      var fieldValue = _get__default['default'](record, this.fieldpath, this.serializedDefault);

      if (fieldValue !== null) {
        return _set__default['default'](_cloneDeep__default['default'](record), this.fieldpath, fieldValue);
      }

      return record;
    }
  }]);

  return Field;
}();

var SchemaField = /*#__PURE__*/function (_Field) {
  _inherits(SchemaField, _Field);

  var _super = _createSuper(SchemaField);

  /**
   * IMPORTANT: This component is so far only thought for list, since
   * the use case of a single object with schema has not rose yet.
   */
  function SchemaField(_ref) {
    var _this;

    var fieldpath = _ref.fieldpath,
        schema = _ref.schema,
        _ref$deserializedDefa = _ref.deserializedDefault,
        deserializedDefault = _ref$deserializedDefa === void 0 ? [] : _ref$deserializedDefa,
        _ref$serializedDefaul = _ref.serializedDefault,
        serializedDefault = _ref$serializedDefaul === void 0 ? [] : _ref$serializedDefaul;

    _classCallCheck(this, SchemaField);

    _this = _super.call(this, {
      fieldpath: fieldpath,
      deserializedDefault: deserializedDefault,
      serializedDefault: serializedDefault
    });
    _this.schema = schema;
    _this.schemaKeys = Object.keys(_this.schema);
    return _this;
  }

  _createClass(SchemaField, [{
    key: "deserialize",
    value:
    /**
     * Deserialize backend field into format compatible with frontend using
     * the given schema. 
     * @method
     * @param {object} element - potentially empty object
     * @returns {object} frontend compatible element object
     */
    function deserialize(elements) {
      var _this2 = this;

      var fieldValues = _get__default['default'](elements, this.fieldpath, this.deserializedDefault);

      var deserializedElements = fieldValues.map(function (value) {
        var deserializedElement = _pick__default['default'](value, _this2.schemaKeys);

        _this2.schemaKeys.forEach(function (key) {
          deserializedElement = _this2.schema[key].deserialize(deserializedElement);
        });

        return deserializedElement;
      });
      return _set__default['default'](_cloneDeep__default['default'](elements), this.fieldpath, deserializedElements);
    }
    /**
     * Serialize element to send to the backend.
     * @method
     * @param {object} element - in frontend format
     * @returns {object} element - in API format
     *
     */

  }, {
    key: "serialize",
    value: function serialize(elements) {
      var _this3 = this;

      var fieldValues = _get__default['default'](elements, this.fieldpath, this.serializedDefault);

      var serializedElements = fieldValues.map(function (value) {
        var serializedElement = _pick__default['default'](value, _this3.schemaKeys);

        _this3.schemaKeys.forEach(function (key) {
          serializedElement = _this3.schema[key].serialize(serializedElement);
        });

        return serializedElement;
      });

      if (serializedElements !== null) {
        return _set__default['default'](_cloneDeep__default['default'](elements), this.fieldpath, serializedElements);
      }

      return elements;
    }
  }]);

  return SchemaField;
}(Field);

var VocabularyField = /*#__PURE__*/function (_Field) {
  _inherits(VocabularyField, _Field);

  var _super = _createSuper(VocabularyField);

  function VocabularyField(_ref) {
    var _this;

    var fieldpath = _ref.fieldpath,
        _ref$deserializedDefa = _ref.deserializedDefault,
        deserializedDefault = _ref$deserializedDefa === void 0 ? null : _ref$deserializedDefa,
        _ref$serializedDefaul = _ref.serializedDefault,
        serializedDefault = _ref$serializedDefaul === void 0 ? null : _ref$serializedDefaul,
        _ref$labelField = _ref.labelField,
        labelField = _ref$labelField === void 0 ? 'name' : _ref$labelField;

    _classCallCheck(this, VocabularyField);

    _this = _super.call(this, {
      fieldpath: fieldpath,
      deserializedDefault: deserializedDefault,
      serializedDefault: serializedDefault
    });
    _this.labelField = labelField;
    return _this;
  }

  _createClass(VocabularyField, [{
    key: "deserialize",
    value: function deserialize(record) {
      var fieldValue = _get__default['default'](record, this.fieldpath, this.deserializedDefault);

      var _deserialize = function _deserialize(value) {
        return value.id;
      };

      var deserializedValue = null;

      if (fieldValue !== null) {
        deserializedValue = Array.isArray(fieldValue) ? fieldValue.map(_deserialize) : _deserialize(fieldValue);
      }

      return _set__default['default'](_cloneDeep__default['default'](record), this.fieldpath, deserializedValue || fieldValue);
    }
  }, {
    key: "serialize",
    value: function serialize(record) {
      var _this2 = this;

      var fieldValue = _get__default['default'](record, this.fieldpath, this.serializedDefault);

      var serializedValue = null;

      if (fieldValue !== null) {
        serializedValue = Array.isArray(fieldValue) ? fieldValue.map(function (value) {
          if (typeof value === 'string') {
            return {
              id: value
            };
          } else {
            return _objectSpread2(_objectSpread2({}, value.id ? {
              id: value.id
            } : {}), {}, _defineProperty({}, _this2.labelField, value[_this2.labelField]));
          }
        }) : {
          id: fieldValue
        }; // fieldValue is a string
      }

      return _set__default['default'](_cloneDeep__default['default'](record), this.fieldpath, serializedValue || fieldValue);
    }
  }]);

  return VocabularyField;
}(Field);
var AllowAdditionsVocabularyField = /*#__PURE__*/function (_VocabularyField) {
  _inherits(AllowAdditionsVocabularyField, _VocabularyField);

  var _super2 = _createSuper(AllowAdditionsVocabularyField);

  function AllowAdditionsVocabularyField() {
    _classCallCheck(this, AllowAdditionsVocabularyField);

    return _super2.apply(this, arguments);
  }

  _createClass(AllowAdditionsVocabularyField, [{
    key: "deserialize",
    value: function deserialize(record) {
      var _this3 = this;

      var fieldValue = _get__default['default'](record, this.fieldpath, this.deserializedDefault); // We deserialize the values in the format
      // {id: 'vocab_id', <labelField>: 'vacab_name'} for controlled values
      // and {<labelField>: 'vocab_name'} for user added entries


      var _deserialize = function _deserialize(value) {
        return _objectSpread2(_objectSpread2({}, value.id ? {
          id: value.id
        } : {}), {}, _defineProperty({}, _this3.labelField, value[_this3.labelField]));
      };

      var deserializedValue = null;

      if (fieldValue !== null) {
        deserializedValue = Array.isArray(fieldValue) ? fieldValue.map(_deserialize) : _deserialize(fieldValue);
      }

      return _set__default['default'](_cloneDeep__default['default'](record), this.fieldpath, deserializedValue || fieldValue);
    }
  }]);

  return AllowAdditionsVocabularyField;
}(VocabularyField);
/**
 * Serialize and deserialize rights field that can contain vocabulary values
 * and free text but sharing structure with the vocabulary values
 */

var RightsVocabularyField = /*#__PURE__*/function (_VocabularyField2) {
  _inherits(RightsVocabularyField, _VocabularyField2);

  var _super3 = _createSuper(RightsVocabularyField);

  function RightsVocabularyField(_ref2) {
    var _this4;

    var fieldpath = _ref2.fieldpath,
        _ref2$deserializedDef = _ref2.deserializedDefault,
        deserializedDefault = _ref2$deserializedDef === void 0 ? null : _ref2$deserializedDef,
        _ref2$serializedDefau = _ref2.serializedDefault,
        serializedDefault = _ref2$serializedDefau === void 0 ? null : _ref2$serializedDefau,
        _ref2$localeFields = _ref2.localeFields,
        localeFields = _ref2$localeFields === void 0 ? [] : _ref2$localeFields;

    _classCallCheck(this, RightsVocabularyField);

    _this4 = _super3.call(this, {
      fieldpath: fieldpath,
      deserializedDefault: deserializedDefault,
      serializedDefault: serializedDefault
    });
    _this4.localeFields = localeFields;
    return _this4;
  }
  /**
   * Deserializes the values in the format:
   * {id: 'vocab_id'} for controlled vocabs and
   * {<field_name>: 'field_name', <field_descripton>: 'field_descripton', ...}
   * for user added entries
   *
   * @param {Object} record - Record to deserialize
   * @param {String} defaultLocale - The default locale
   * @returns
   */


  _createClass(RightsVocabularyField, [{
    key: "deserialize",
    value: function deserialize(record, defaultLocale) {
      var _this5 = this;

      var fieldValue = _get__default['default'](record, this.fieldpath, this.deserializedDefault);

      var _deserialize = function _deserialize(value) {
        if ('id' in value) {
          if (typeof value.title === 'string') {
            // Needed in case we pass a default value
            return value;
          }

          return {
            id: value.id
          };
        } else {
          var _deserializedValue = _cloneDeep__default['default'](value);

          _this5.localeFields.forEach(function (field) {
            if (value[field]) {
              _deserializedValue[field] = value[field][defaultLocale];
            }
          });

          return _deserializedValue;
        }
      };

      var deserializedValue = null;

      if (fieldValue !== null) {
        deserializedValue = Array.isArray(fieldValue) ? fieldValue.map(_deserialize) : _deserialize(fieldValue);
      }

      return _set__default['default'](_cloneDeep__default['default'](record), this.fieldpath, deserializedValue || fieldValue);
    }
    /**
     * Serializes the values in the format:
     * {id: 'vocab_id'} for controlled vocabs and
     * {
     *    <field_name>:
     *      { '<default_locale>: 'field_name'},
     *    <field_descripton>:
     *      { <default_locale>: 'field_descripton'}
     * }
     * for user added entries
     * @param {object} record - Record to serialize
     * @param {string} defaultLocale - The default locale
     * @returns
     */

  }, {
    key: "serialize",
    value: function serialize(record, defaultLocale) {
      var _this6 = this;

      var fieldValue = _get__default['default'](record, this.fieldpath, this.serializedDefault);

      var serializedValue = null;

      var _serialize = function _serialize(value) {
        var clonedValue = _cloneDeep__default['default'](value);

        if ('id' in value) {
          return {
            id: value.id
          };
        } else {
          _this6.localeFields.forEach(function (field) {
            if (field in value) {
              clonedValue[field] = _defineProperty({}, defaultLocale, value[field]);
            }
          });
        }

        return clonedValue;
      };

      if (fieldValue !== null) {
        serializedValue = Array.isArray(fieldValue) ? fieldValue.map(_serialize) : _serialize(fieldValue);
      }

      return _set__default['default'](_cloneDeep__default['default'](record), this.fieldpath, serializedValue || fieldValue);
    }
  }]);

  return RightsVocabularyField;
}(VocabularyField);

// This file is part of React-Invenio-Deposit
// Copyright (C) 2020 CERN.
// Copyright (C) 2020 Northwestern University.
//
// React-Invenio-Deposit is free software; you can redistribute it and/or modify it
// under the terms of the MIT License; see LICENSE file for more details.
// TODO: Move to rely on DepositRecordSerializer with the deserializedDefault
//       values to generate the empty values. Then delete this file.
var emptyIdentifier = {
  scheme: '',
  identifier: ''
};
var emptyAdditionalTitle = {
  lang: '',
  title: '',
  type: 'alternative-title'
};
var emptyAdditionalDescription = {
  lang: '',
  description: '',
  type: ''
};
var emptyRelatedWork = {
  scheme: '',
  identifier: '',
  resource_type: '',
  relation_type: ''
};
var emptyDate = {
  date: '',
  description: '',
  type: ''
};
var emptyFunding = {
  funder: {
    name: '',
    identifier: '',
    scheme: ''
  },
  award: {
    title: '',
    number: '',
    identifier: '',
    scheme: ''
  }
};

var DepositRecordSerializer = /*#__PURE__*/function () {
  function DepositRecordSerializer(defaultLocale) {
    _classCallCheck(this, DepositRecordSerializer);

    this.depositRecordSchema = {
      files: new Field({
        fieldpath: 'files'
      }),
      links: new Field({
        fieldpath: 'links'
      }),
      pids: new Field({
        fieldpath: 'pids',
        deserializedDefault: {},
        serializedDefault: {}
      }),
      title: new Field({
        fieldpath: 'metadata.title',
        deserializedDefault: ''
      }),
      additional_titles: new SchemaField({
        fieldpath: 'metadata.additional_titles',
        schema: {
          title: new Field({
            fieldpath: 'title'
          }),
          type: new VocabularyField({
            fieldpath: 'type',
            deserializedDefault: '',
            serializedDefault: ''
          }),
          lang: new VocabularyField({
            fieldpath: 'lang',
            deserializedDefault: '',
            serializedDefault: ''
          })
        }
      }),
      additional_descriptions: new SchemaField({
        fieldpath: 'metadata.additional_descriptions',
        schema: {
          description: new Field({
            fieldpath: 'description'
          }),
          type: new VocabularyField({
            fieldpath: 'type',
            deserializedDefault: '',
            serializedDefault: ''
          }),
          lang: new VocabularyField({
            fieldpath: 'lang',
            deserializedDefault: '',
            serializedDefault: ''
          })
        }
      }),
      creators: new SchemaField({
        fieldpath: 'metadata.creators',
        schema: {
          person_or_org: new Field({
            fieldpath: 'person_or_org'
          }),
          role: new VocabularyField({
            fieldpath: 'role',
            deserializedDefault: '',
            serializedDefault: ''
          }),
          affiliations: new AllowAdditionsVocabularyField({
            fieldpath: 'affiliations',
            deserializedDefault: [],
            serializedDefault: [],
            labelField: 'name'
          })
        }
      }),
      contributors: new SchemaField({
        fieldpath: 'metadata.contributors',
        schema: {
          person_or_org: new Field({
            fieldpath: 'person_or_org'
          }),
          role: new VocabularyField({
            fieldpath: 'role',
            deserializedDefault: '',
            serializedDefault: ''
          }),
          affiliations: new AllowAdditionsVocabularyField({
            fieldpath: 'affiliations',
            deserializedDefault: [],
            serializedDefault: [],
            labelField: 'name'
          })
        }
      }),
      resource_type: new VocabularyField({
        fieldpath: 'metadata.resource_type',
        deserializedDefault: '',
        serializedDefault: ''
      }),
      access: new Field({
        fieldpath: 'access',
        deserializedDefault: {
          record: 'public',
          files: 'public'
        }
      }),
      publication_date: new Field({
        fieldpath: 'metadata.publication_date',
        deserializedDefault: ''
      }),
      dates: new SchemaField({
        fieldpath: 'metadata.dates',
        schema: {
          date: new Field({
            fieldpath: 'date'
          }),
          type: new VocabularyField({
            fieldpath: 'type',
            deserializedDefault: '',
            serializedDefault: ''
          }),
          description: new Field({
            fieldpath: 'description'
          })
        },
        deserializedDefault: [emptyDate]
      }),
      languages: new VocabularyField({
        fieldpath: 'metadata.languages',
        deserializedDefault: [],
        serializedDefault: []
      }),
      identifiers: new Field({
        fieldpath: 'metadata.identifiers',
        deserializedDefault: [emptyIdentifier]
      }),
      related_identifiers: new SchemaField({
        fieldpath: 'metadata.related_identifiers',
        schema: {
          scheme: new Field({
            fieldpath: 'scheme'
          }),
          identifier: new Field({
            fieldpath: 'identifier'
          }),
          relation_type: new VocabularyField({
            fieldpath: 'relation_type',
            deserializedDefault: '',
            serializedDefault: ''
          }),
          resource_type: new VocabularyField({
            fieldpath: 'resource_type',
            deserializedDefault: '',
            serializedDefault: ''
          })
        },
        deserializedDefault: [emptyRelatedWork]
      }),
      subjects: new AllowAdditionsVocabularyField({
        fieldpath: 'metadata.subjects',
        deserializedDefault: [],
        serializedDefault: [],
        labelField: 'subject'
      }),
      funding: new Field({
        fieldpath: 'metadata.funding',
        deserializedDefault: [emptyFunding]
      }),
      version: new Field({
        fieldpath: 'metadata.version',
        deserializedDefault: ''
      }),
      rights: new RightsVocabularyField({
        fieldpath: 'metadata.rights',
        deserializedDefault: [],
        serializedDefault: [],
        localeFields: ['title', 'description']
      })
    };
    this.defaultLocale = defaultLocale;
  }

  _createClass(DepositRecordSerializer, [{
    key: "removeEmptyValues",
    value:
    /**
     * Remove empty fields from record
     * @method
     * @param {object} obj - potentially empty object
     * @returns {object} record - without empty fields
     */
    function removeEmptyValues(obj) {
      var _this = this;

      if (_isArray__default['default'](obj)) {
        var mappedValues = obj.map(function (value) {
          return _this.removeEmptyValues(value);
        });
        var filterValues = mappedValues.filter(function (value) {
          if (_isBoolean__default['default'](value) || _isNumber__default['default'](value)) {
            return value;
          }

          return !_isEmpty__default['default'](value);
        });
        return filterValues;
      } else if (_isObject__default['default'](obj)) {
        var _mappedValues = _mapValues__default['default'](obj, function (value) {
          return _this.removeEmptyValues(value);
        });

        var pickedValues = _pickBy__default['default'](_mappedValues, function (value) {
          if (_isArray__default['default'](value) || _isObject__default['default'](value)) {
            return !_isEmpty__default['default'](value);
          }

          return !_isNull__default['default'](value);
        });

        return pickedValues;
      }

      return _isNumber__default['default'](obj) || _isBoolean__default['default'](obj) || obj ? obj : null;
    }
    /**
     * Deserialize backend record into format compatible with frontend.
     * @method
     * @param {object} record - potentially empty object
     * @returns {object} frontend compatible record object
     */

  }, {
    key: "deserialize",
    value: function deserialize(record) {
      // NOTE: cloning nows allows us to manipulate the copy with impunity
      //       without affecting the original
      record = _cloneDeep__default['default'](record); // Remove empty null values from record. This happens when we create a new
      // draft and the backend produces an empty record filled in with null
      // values, array of null values etc.
      // TODO: Backend should not attempt to provide empty values. It should just
      //       return existing record in case of edit or {} in case of new.

      var deserializedRecord = this.removeEmptyValues(record);
      deserializedRecord = _pick__default['default'](deserializedRecord, ['access', 'metadata', 'id', 'links', 'files', 'is_published', 'versions', 'pids', 'ui']);

      for (var key in this.depositRecordSchema) {
        deserializedRecord = this.depositRecordSchema[key].deserialize(deserializedRecord, this.defaultLocale);
      }

      return deserializedRecord;
    }
    /**
     * Deserialize backend record errors into format compatible with frontend.
     * @method
     * @param {array} errors - array of error objects
     * @returns {object} - object representing errors
     */

  }, {
    key: "deserializeErrors",
    value: function deserializeErrors(errors) {
      var deserializedErrors = {}; // TODO - WARNING: This doesn't convert backend error paths to frontend
      //                 error paths. Doing so is non-trivial
      //                 (re-using deserialize has some caveats)
      //                 Form/Error UX is tackled in next sprint and this is good
      //                 enough for now.

      var _iterator = _createForOfIteratorHelper(errors),
          _step;

      try {
        for (_iterator.s(); !(_step = _iterator.n()).done;) {
          var e = _step.value;

          _set__default['default'](deserializedErrors, e.field, e.messages.join(' '));
        }
      } catch (err) {
        _iterator.e(err);
      } finally {
        _iterator.f();
      }

      return deserializedErrors;
    }
    /**
     * Serialize record to send to the backend.
     * @method
     * @param {object} record - in frontend format
     * @returns {object} record - in API format
     *
     */

  }, {
    key: "serialize",
    value: function serialize(record) {
      // NOTE: cloning nows allows us to manipulate the copy with impunity without
      //       affecting the original
      record = _cloneDeep__default['default'](record);
      var serializedRecord = this.removeEmptyValues(record);
      serializedRecord = _pick__default['default'](serializedRecord, ['access', 'metadata', 'id', 'links', 'defaultFilePreview', 'files', 'pids']);

      for (var key in this.depositRecordSchema) {
        serializedRecord = this.depositRecordSchema[key].serialize(serializedRecord, this.defaultLocale);
      } // Remove empty values again because serialization may add some back


      serializedRecord = this.removeEmptyValues(serializedRecord); // Finally add back 'metadata' if absent
      // We need to do this for backend validation, unless we mark metadata as
      // required in the backend or find another alternative.

      _defaults__default['default'](serializedRecord, {
        metadata: {}
      });

      return serializedRecord;
    }
  }]);

  return DepositRecordSerializer;
}();

var depositReducer = (function () {
  var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var action = arguments.length > 1 ? arguments[1] : undefined;

  switch (action.type) {
    case ACTION_CREATE_SUCCEEDED:
      return _objectSpread2(_objectSpread2({}, state), {}, {
        record: _objectSpread2(_objectSpread2({}, state.record), action.payload.data),
        formState: null
      });

    case ACTION_DELETE_FAILED:
      return _objectSpread2(_objectSpread2({}, state), {}, {
        formState: FORM_DELETE_FAILED
      });

    case FORM_ACTION_EVENT_EMITTED:
      return _objectSpread2(_objectSpread2({}, state), {}, {
        formState: action.payload
      });

    case ACTION_SAVE_SUCCEEDED:
      return _objectSpread2(_objectSpread2({}, state), {}, {
        record: _objectSpread2(_objectSpread2({}, state.record), action.payload.data),
        errors: {},
        formState: FORM_SAVE_SUCCEEDED
      });

    case ACTION_SAVE_PARTIALLY_SUCCEEDED:
      return _objectSpread2(_objectSpread2({}, state), {}, {
        record: _objectSpread2(_objectSpread2({}, state.record), action.payload.data),
        errors: _objectSpread2({}, action.payload.errors),
        formState: FORM_SAVE_PARTIALLY_SUCCEEDED
      });

    case ACTION_SAVE_FAILED:
      return _objectSpread2(_objectSpread2({}, state), {}, {
        errors: _objectSpread2({}, action.payload.errors),
        formState: FORM_SAVE_FAILED
      });

    case ACTION_PUBLISH_SUCCEEDED:
      return _objectSpread2(_objectSpread2({}, state), {}, {
        record: _objectSpread2(_objectSpread2({}, state.record), action.payload.data),
        formState: FORM_PUBLISH_SUCCEEDED
      });

    case ACTION_PUBLISH_FAILED:
      return _objectSpread2(_objectSpread2({}, state), {}, {
        errors: _objectSpread2({}, action.payload.errors),
        formState: FORM_PUBLISH_FAILED
      });

    case RESERVE_PID_STARTED:
    case DISCARD_PID_STARTED:
      return _objectSpread2(_objectSpread2({}, state), {}, {
        reservePIDsLoading: true
      });

    case RESERVE_PID_SUCCESS:
    case DISCARD_PID_SUCCESS:
      return _objectSpread2(_objectSpread2({}, state), {}, {
        record: _objectSpread2(_objectSpread2({}, state.record), action.payload.data),
        errors: {},
        reservePIDsLoading: false
      });

    case RESERVE_PID_FAILED:
    case DISCARD_PID_FAILED:
      return _objectSpread2(_objectSpread2({}, state), {}, {
        errors: _objectSpread2({}, action.payload.errors),
        reservePIDsLoading: false
      });

    default:
      return state;
  }
});

// This file is part of React-Invenio-Deposit
var rootReducer = redux.combineReducers({
  deposit: depositReducer,
  files: fileReducer
});

// This file is part of React-Invenio-Deposit
// Copyright (C) 2020 CERN.
// Copyright (C) 2020 Northwestern University.
//
// React-Invenio-Deposit is free software; you can redistribute it and/or modify it
// under the terms of the MIT License; see LICENSE file for more details.
var INITIAL_STORE_STATE = {
  formState: null
};

var _excluded$8 = ["record", "files", "config", "permissions"];

var preloadFiles = function preloadFiles(files) {
  var _files = _cloneDeep__default['default'](files);

  return {
    defaultFilePreview: files.default_preview || null,
    links: files.links || {},
    entries: _get__default['default'](_files, 'entries', []).map(function (file) {
      var hasSize;

      if (file.size) {
        hasSize = true;
      }

      var fileState = {
        name: file.key,
        size: file.size || 0,
        checksum: file.checksum || '',
        links: file.links || {}
      }; // TODO: fix this as the lack of size is not always an error e.g upload ongoing in another tab

      return hasSize ? _objectSpread2({
        status: UploadState.finished,
        progress: 100
      }, fileState) : _objectSpread2({
        status: UploadState.pending
      }, fileState);
    }).reduce(function (acc, current) {
      acc[current.name] = _objectSpread2({}, current);
      return acc;
    }, {})
  };
};

function configureStore(appConfig) {
  var record = appConfig.record,
      files = appConfig.files,
      config = appConfig.config,
      permissions = appConfig.permissions,
      extra = _objectWithoutProperties(appConfig, _excluded$8);

  var initialDepositState = _objectSpread2({
    record: record,
    config: config,
    permissions: permissions
  }, INITIAL_STORE_STATE);

  var preloadedState = {
    deposit: initialDepositState,
    files: preloadFiles(files || {})
  };
  var composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || redux.compose;
  return redux.createStore(rootReducer, preloadedState, composeEnhancers(redux.applyMiddleware(thunk__default['default'].withExtraArgument(extra))));
}

var Title$3 = "";
var Added$3 = "";
var Person$3 = "";
var Organization$3 = "";
var Name$3 = "";
var Role$3 = "";
var Cancel$3 = "";
var Save$3 = "";
var Affiliations$3 = "";
var Description$3 = "";
var Type$3 = "";
var Language$3 = "";
var Licenses$3 = "";
var Remove$3 = "";
var Link$3 = "";
var All$3 = "";
var Data$3 = "";
var Software$3 = "";
var Recommended$3 = "";
var Subjects$3 = "";
var Languages$3 = "";
var Dates$3 = "";
var Version$3 = "";
var Publisher$3 = "";
var Identifier$3 = "";
var Scheme$3 = "";
var Relation$3 = "";
var Preview$3 = "";
var publish$3 = "";
var Options$3 = "";
var Reason$3 = "";
var Filename$3 = "";
var Size$3 = "";
var Progress$3 = "";
var Pending$3 = "";
var or$3 = "";
var Public$3 = "";
var Restricted$4 = "";
var Edit$3 = "";
var Award$3 = "";
var Awards$3 = "";
var Files$3 = "";
var Creators$3 = "";
var Contributors$3 = "";
var TRANSLATE_EL = {
	"New version": "Νέα εκδοχή",
	"New upload": "Νέα μεταφόρτωση",
	"Storage available": "Διαθέσιμη χωρητικότητα",
	"Add identifier": "Προσθήκη identifier",
	"Edit upload": "Τροποποίηση μεταφόρτωσης",
	"Add titles": "",
	"Uploading the selected files would result in": "",
	"but the limit is": "",
	"You can import files from the previous version.": "",
	"File addition, removal or modification are not allowed after you have published your upload.": "",
	"You must create a new version to add, modify or delete files.": "",
	"Drag and drop file(s)": "",
	"Upload files": "",
	"Import files": "",
	"Metadata-only record": "",
	"{{length}} out of {{maxfiles}} files": "",
	"out of": "",
	"In case your upload was already published elsewhere, please use the date of the first publication. Format: YYYY-MM-DD, YYYY-MM, or YYYY. For intervals use DATE/DATE, e.g. 1939/1945.": "",
	"Publication date": "",
	"YYYY-MM-DD or YYYY-MM-DD/YYYY-MM-DD for intervals. MM and DD are optional.": "",
	"Resource type": "",
	Title: Title$3,
	"Add creator": "",
	"Name identifiers": "",
	"e.g. ORCID, ISNI or GND.": "",
	"Type the value of an identifier...": "",
	"Save and add another": "",
	"Family name is a required field.": "",
	"Name is a required field.": "",
	"Role is a required field.": "",
	Added: Added$3,
	Person: Person$3,
	Organization: Organization$3,
	"Family name": "",
	"Given name(s)": "",
	"Given name": "",
	Name: Name$3,
	"Organization name": "",
	Role: Role$3,
	"Select role": "",
	Cancel: Cancel$3,
	Save: Save$3,
	"Search or create affiliation'": "",
	Affiliations: Affiliations$3,
	"Search for affiliations..": "",
	Description: Description$3,
	"Additional Description": "",
	Type: Type$3,
	Language: Language$3,
	"Select language": "",
	"Add description": "",
	"Add standard": "",
	"Add custom": "",
	Licenses: Licenses$3,
	Remove: Remove$3,
	"Read more": "",
	"Title is a required field.": "",
	"Link must be a valid URL": "",
	"License title": "",
	Link: Link$3,
	"License link": "",
	All: All$3,
	Data: Data$3,
	Software: Software$3,
	"Add license": "",
	"Change license": "",
	Recommended: Recommended$3,
	"Search or create subjects..": "",
	Subjects: Subjects$3,
	"Search for a subject by name": "",
	"Search for languages...": "",
	Languages: Languages$3,
	"Search for a language by name (e.g \"eng\", \"fr\" or \"Polish\")": "",
	"Add date": "",
	"Format: DATE or DATE/DATE where DATE is YYYY or YYYY-MM or YYYY-MM-DD.": "",
	"Date": "",
	Dates: Dates$3,
	"YYYY-MM-DD or YYYY-MM-DD/YYYY-MM-DD": "",
	Version: Version$3,
	"The publisher is used to formulate the citation, so consider the prominence of the role.": "",
	Publisher: Publisher$3,
	"Enter publisher name": "",
	Identifier: Identifier$3,
	Scheme: Scheme$3,
	"Identifier(s)": "",
	"Specify identifiers of related works. Supported identifiers include DOI, Handle, ARK, PURL, ISSN, ISBN, PubMed ID, PubMed Central ID, ADS Bibliographic Code, arXiv, Life Science Identifiers (LSID), EAN-13, ISTC, URNs, and URLs.": "",
	"Add related work": "",
	Relation: Relation$3,
	"Select relation...": "",
	"Related works": "",
	"Save draft": "",
	Preview: Preview$3,
	"Are you sure you want to {{action}} this record?": "",
	publish: publish$3,
	"Are you sure you want to discard the changes to this draft?": "",
	"Are you sure you want to delete this new version?": "",
	"Are you sure you want to delete this draft?": "",
	"discard version": "",
	"delete": "",
	"discard changes": "",
	Options: Options$3,
	"The full record is restricted.": "",
	"The record and files are publicly accessible.": "",
	"Full record": "",
	"Files only": "",
	"Apply an embargo": "",
	"Embargo reason": "",
	"Optionally, describe the reason for the embargo.": "",
	"Embargo was lifted on {{fmtDate}}.": "",
	Reason: Reason$3,
	Filename: Filename$3,
	Size: Size$3,
	Progress: Progress$3,
	"This is the file fingerprint (MD5 checksum), which can be used to verify the file integrity.": "",
	Pending: Pending$3,
	or: or$3,
	"This is a Metadata only record": "",
	Public: Public$3,
	Restricted: Restricted$4,
	"Public with restricted files": "",
	"Suggest from": "",
	"The record and files can <1>only</1> be accessed by<3>users specified</3> in the permissions.": "",
	"The record is publicly accessible. The files can <1>only</1> be accessed by <3>users specified</3> in the permissions.": "",
	"Record or files protection must be <1>restricted</1> to apply an embargo.": "",
	"Mostly relevant for software and dataset uploads. A semantic version string is preferred see<1> semver.org</1>, but any version string is accepted.": "",
	"The record has no files.": "",
	"Embargoed (full record)": "",
	"Embargoed (files-only)": "",
	"Embargo until": "",
	"Alternate identifiers": "",
	"YYYY-MM-DD": "",
	Edit: Edit$3,
	"Add award": "",
	"Funding Organization": "",
	"Funding organization...": "",
	Award: Award$3,
	"Award number/acronym/name ...": "",
	Awards: Awards$3,
	Files: Files$3,
	Creators: Creators$3,
	Contributors: Contributors$3,
	"Record successfully saved.": "",
	"Record saved with validation errors:": "",
	"There was an internal error (and the record was not saved).": "",
	"There was an internal error (and the record was not deleted).": "",
	"The record is publicly accessible.": "",
	"The record can <1>only</1> be accessed by <3>users specified</3> in the permissions.": "",
	"You don't have permissions to create a new version.": "",
	"Additional titles": "",
	"Additional descriptions": "",
	"On <bold>{{ date }}</bold> the record and the files will automatically be made publicly accessible. Until then, the record and the files can <bold>only</bold> be accessed by <bold>users specified</bold> in the permissions.": "",
	"The record is publicly accessible. On <bold>{{ date }}</bold> the files will automatically be made publicly accessible. Until then, the files can <bold>only</bold> be accessed by <bold>users specified</bold> in the permissions.": "",
	"On <bold>{{ date }}</bold> the record will automatically be made publicly accessible. Until then, the record can <bold>only</bold> be accessed by <bold>users specified</bold> in the permissions.": ""
};

var Public$2 = "Public";
var Restricted$3 = "Restricted";
var Reason$2 = "Reason";
var Options$2 = "Options";
var Type$2 = "Type";
var Language$2 = "Language";
var Affiliations$2 = "Affiliations";
var Edit$2 = "Edit";
var Remove$2 = "Remove";
var Added$2 = "Added";
var Person$2 = "Person";
var Organization$2 = "Organization";
var Name$2 = "Name";
var Role$2 = "Role";
var Cancel$2 = "Cancel";
var Save$2 = "Save";
var Description$2 = "Description";
var Dates$2 = "Dates";
var Preview$2 = "Preview";
var Filename$2 = "Filename";
var Size$2 = "Size";
var Progress$2 = "Progress";
var Pending$2 = "Pending";
var or$2 = "or";
var Files$2 = "Files";
var Title$2 = "Title";
var Creators$2 = "Creators";
var Contributors$2 = "Contributors";
var Licenses$2 = "Licenses";
var Languages$2 = "Languages";
var Version$2 = "Version";
var Publisher$2 = "Publisher";
var Award$2 = "Award";
var Awards$2 = "Awards";
var Identifier$2 = "Identifier";
var Scheme$2 = "Scheme";
var Recommended$2 = "Recommended";
var All$2 = "All";
var Data$2 = "Data";
var Software$2 = "Software";
var Link$2 = "Link";
var publish$2 = "publish";
var Relation$2 = "Relation";
var Subjects$2 = "Subjects";
var Yes$1 = "Yes";
var No$1 = "No";
var TRANSLATE_EN = {
	"Embargo until": "Embargo until",
	"YYYY-MM-DD": "YYYY-MM-DD",
	"The full record is restricted.": "The full record is restricted.",
	"Embargoed (full record)": "Embargoed (full record)",
	"On <bold>{{ date }}</bold> the record and the files will automatically be made publicly accessible. Until then, the record and the files can <bold>only</bold> be accessed by <bold>users specified</bold> in the permissions.": "On <bold>{{ date }}</bold> the record and the files will automatically be made publicly accessible. Until then, the record and the files can <bold>only</bold> be accessed by <bold>users specified</bold> in the permissions.",
	"Embargoed (files-only)": "Embargoed (files-only)",
	"The record is publicly accessible. On <bold>{{ date }}</bold> the files will automatically be made publicly accessible. Until then, the files can <bold>only</bold> be accessed by <bold>users specified</bold> in the permissions.": "The record is publicly accessible. On <bold>{{ date }}</bold> the files will automatically be made publicly accessible. Until then, the files can <bold>only</bold> be accessed by <bold>users specified</bold> in the permissions.",
	"The record has no files.": "The record has no files.",
	"On <bold>{{ date }}</bold> the record will automatically be made publicly accessible. Until then, the record can <bold>only</bold> be accessed by <bold>users specified</bold> in the permissions.": "On <bold>{{ date }}</bold> the record will automatically be made publicly accessible. Until then, the record can <bold>only</bold> be accessed by <bold>users specified</bold> in the permissions.",
	Public: Public$2,
	Restricted: Restricted$3,
	"The record and files are publicly accessible.": "The record and files are publicly accessible.",
	"The record is publicly accessible.": "The record is publicly accessible.",
	"The record and files can <1>only</1> be accessed by<3>users specified</3> in the permissions.": "The record and files can <1>only</1> be accessed by<3>users specified</3> in the permissions.",
	"Public with restricted files": "Public with restricted files",
	"The record is publicly accessible. The files can <1>only</1> be accessed by <3>users specified</3> in the permissions.": "The record is publicly accessible. The files can <1>only</1> be accessed by <3>users specified</3> in the permissions.",
	"The record can <1>only</1> be accessed by <3>users specified</3> in the permissions.": "The record can <1>only</1> be accessed by <3>users specified</3> in the permissions.",
	"Full record": "Full record",
	"Files only": "Files only",
	"Apply an embargo": "Apply an embargo",
	"Embargo reason": "Embargo reason",
	"Optionally, describe the reason for the embargo.": "Optionally, describe the reason for the embargo.",
	"Embargo was lifted on {{fmtDate}}.": "Embargo was lifted on {{fmtDate}}.",
	Reason: Reason$2,
	"Record or files protection must be <1>restricted</1> to apply an embargo.": "Record or files protection must be <1>restricted</1> to apply an embargo.",
	Options: Options$2,
	"Add description": "Add description",
	"Additional Description": "Additional Description",
	Type: Type$2,
	Language: Language$2,
	"Select language": "Select language",
	"Add titles": "Add titles",
	"Search or create affiliation'": "Search or create affiliation'",
	Affiliations: Affiliations$2,
	"Search for affiliations..": "Search for affiliations..",
	"Add creator": "Add creator",
	Edit: Edit$2,
	Remove: Remove$2,
	"Name identifiers": "Name identifiers",
	"e.g. ORCID, ISNI or GND.": "e.g. ORCID, ISNI or GND.",
	"Type the value of an identifier...": "Type the value of an identifier...",
	"Save and add another": "Save and add another",
	"Family name is a required field.": "Family name is a required field.",
	"Name is a required field.": "Name is a required field.",
	"Role is a required field.": "Role is a required field.",
	Added: Added$2,
	Person: Person$2,
	Organization: Organization$2,
	"Family name": "Family name",
	"Given name(s)": "Given name(s)",
	"Given name": "Given name",
	Name: Name$2,
	"Organization name": "Organization name",
	Role: Role$2,
	"Select role": "Select role",
	Cancel: Cancel$2,
	Save: Save$2,
	"Add date": "Add date",
	"Format: DATE or DATE/DATE where DATE is YYYY or YYYY-MM or YYYY-MM-DD.": "Format: DATE or DATE/DATE where DATE is YYYY or YYYY-MM or YYYY-MM-DD.",
	"Date": "Date",
	Description: Description$2,
	Dates: Dates$2,
	"YYYY-MM-DD or YYYY-MM-DD/YYYY-MM-DD": "YYYY-MM-DD or YYYY-MM-DD/YYYY-MM-DD",
	"discard changes": "discard changes",
	"discard version": "discard version",
	"delete": "delete",
	"Are you sure you want to discard the changes to this draft?": "Are you sure you want to discard the changes to this draft?",
	"Are you sure you want to delete this new version?": "Are you sure you want to delete this new version?",
	"Are you sure you want to delete this draft?": "Are you sure you want to delete this draft?",
	"New version": "New version",
	"New upload": "New upload",
	"Edit upload": "Edit upload",
	"Uploading the selected files would result in": "Uploading the selected files would result in",
	"but the limit is": "but the limit is",
	"You can import files from the previous version.": "You can import files from the previous version.",
	"File addition, removal or modification are not allowed after you have published your upload.": "File addition, removal or modification are not allowed after you have published your upload.",
	"You must create a new version to add, modify or delete files.": "You must create a new version to add, modify or delete files.",
	"Drag and drop file(s)": "Drag and drop file(s)",
	"Upload files": "Upload files",
	"Import files": "Import files",
	Preview: Preview$2,
	Filename: Filename$2,
	Size: Size$2,
	Progress: Progress$2,
	"This is the file fingerprint (MD5 checksum), which can be used to verify the file integrity.": "This is the file fingerprint (MD5 checksum), which can be used to verify the file integrity.",
	Pending: Pending$2,
	or: or$2,
	"This is a Metadata only record": "This is a Metadata only record",
	"Metadata-only record": "Metadata-only record",
	"Storage available": "Storage available",
	"{{length}} out of {{maxfiles}} files": "{{length}} out of {{maxfiles}} files",
	"out of": "out of",
	Files: Files$2,
	"Resource type": "Resource type",
	Title: Title$2,
	"Additional titles": "Additional titles",
	"Publication date": "Publication date",
	Creators: Creators$2,
	Contributors: Contributors$2,
	"Additional descriptions": "Additional descriptions",
	Licenses: Licenses$2,
	Languages: Languages$2,
	Version: Version$2,
	Publisher: Publisher$2,
	"Related works": "Related works",
	"Alternate identifiers": "Alternate identifiers",
	"Record successfully saved.": "Record successfully saved.",
	"Record saved with validation errors:": "Record saved with validation errors:",
	"There was an internal error (and the record was not saved).": "There was an internal error (and the record was not saved).",
	"There was an internal error (and the record was not deleted).": "There was an internal error (and the record was not deleted).",
	"Add award": "Add award",
	"Funding Organization": "Funding Organization",
	"Funding organization...": "Funding organization...",
	Award: Award$2,
	"Award number/acronym/name ...": "Award number/acronym/name ...",
	Awards: Awards$2,
	"Add identifier": "Add identifier",
	Identifier: Identifier$2,
	Scheme: Scheme$2,
	"Identifier(s)": "Identifier(s)",
	"Search for languages...": "Search for languages...",
	"Search for a language by name (e.g \"eng\", \"fr\" or \"Polish\")": "Search for a language by name (e.g \"eng\", \"fr\" or \"Polish\")",
	"Add standard": "Add standard",
	"Add custom": "Add custom",
	"Read more": "Read more",
	"Title is a required field.": "Title is a required field.",
	"Link must be a valid URL": "Link must be a valid URL",
	Recommended: Recommended$2,
	All: All$2,
	Data: Data$2,
	Software: Software$2,
	"License title": "License title",
	Link: Link$2,
	"License link": "License link",
	"Add license": "Add license",
	"Change license": "Change license",
	"You don't have permissions to create a new version.": "You don't have permissions to create a new version.",
	"In case your upload was already published elsewhere, please use the date of the first publication. Format: YYYY-MM-DD, YYYY-MM, or YYYY. For intervals use DATE/DATE, e.g. 1939/1945.": "In case your upload was already published elsewhere, please use the date of the first publication. Format: YYYY-MM-DD, YYYY-MM, or YYYY. For intervals use DATE/DATE, e.g. 1939/1945.",
	"YYYY-MM-DD or YYYY-MM-DD/YYYY-MM-DD for intervals. MM and DD are optional.": "YYYY-MM-DD or YYYY-MM-DD/YYYY-MM-DD for intervals. MM and DD are optional.",
	publish: publish$2,
	"Are you sure you want to {{action}} this record?": "Are you sure you want to {{action}} this record?",
	"The publisher is used to formulate the citation, so consider the prominence of the role.": "The publisher is used to formulate the citation, so consider the prominence of the role.",
	"Enter publisher name": "Enter publisher name",
	"Specify identifiers of related works. Supported identifiers include DOI, Handle, ARK, PURL, ISSN, ISBN, PubMed ID, PubMed Central ID, ADS Bibliographic Code, arXiv, Life Science Identifiers (LSID), EAN-13, ISTC, URNs, and URLs.": "Specify identifiers of related works. Supported identifiers include DOI, Handle, ARK, PURL, ISSN, ISBN, PubMed ID, PubMed Central ID, ADS Bibliographic Code, arXiv, Life Science Identifiers (LSID), EAN-13, ISTC, URNs, and URLs.",
	"Add related work": "Add related work",
	Relation: Relation$2,
	"Select relation...": "Select relation...",
	"Save draft": "Save draft",
	"Suggest from": "Suggest from",
	"Search or create subjects..": "Search or create subjects..",
	Subjects: Subjects$2,
	"Search for a subject by name": "Search for a subject by name",
	"Mostly relevant for software and dataset uploads. A semantic version string is preferred see<1> semver.org</1>, but any version string is accepted.": "Mostly relevant for software and dataset uploads. A semantic version string is preferred see<1> semver.org</1>, but any version string is accepted.",
	"Do you already have a {{pidLabel}} for this upload?": "Do you already have a {{pidLabel}} for this upload?",
	Yes: Yes$1,
	No: No$1
};

var Public$1 = "Öffentlich";
var Restricted$2 = "Eingeschränkt";
var Reason$1 = "Grund";
var Options$1 = "Optionen";
var Type$1 = "Typ";
var Language$1 = "Sprache";
var Affiliations$1 = "Zugehörigkeiten";
var Edit$1 = "Editieren";
var Remove$1 = "Löschen";
var Added$1 = "Hinzugefügt";
var Person$1 = "Person";
var Organization$1 = "Organisation";
var Name$1 = "Name";
var Role$1 = "Rolle";
var Cancel$1 = "Abbrechen";
var Save$1 = "Speichern";
var Description$1 = "Beschreibung";
var Dates$1 = "Daten";
var Preview$1 = "Vorschau";
var Filename$1 = "Dateiname";
var Size$1 = "Größe";
var Progress$1 = "Fortschritt";
var Pending$1 = "Ausstehend";
var or$1 = "oder";
var Files$1 = "Dateien";
var Title$1 = "Titel";
var Creators$1 = "Erstellerinnen";
var Contributors$1 = "Mitwirkende";
var Licenses$1 = "Lizenzen";
var Languages$1 = "Sprachen";
var Version$1 = "Version";
var Publisher$1 = "Herausgeber";
var Award$1 = "Auszeichnung";
var Awards$1 = "Auszeichnungen";
var Identifier$1 = "Bezeichner";
var Scheme$1 = "Schema";
var Recommended$1 = "Empfohlen";
var All$1 = "Alle";
var Data$1 = "Daten";
var Software$1 = "Software";
var Link$1 = "Link";
var publish$1 = "veröffentlichen";
var Relation$1 = "Relation";
var Subjects$1 = "Themen";
var Yes = "Ja";
var No = "Nein";
var TRANSLATE_DE = {
	"Embargo until": "Embargo bis",
	"YYYY-MM-DD": "JJJJ-MM-TT",
	"The full record is restricted.": "Der vollständige Eintrag ist eingeschränkt.",
	"Embargoed (full record)": "Embargoed (vollständiger Datensatz)",
	"On <bold>{{ date }}</bold> the record and the files will automatically be made publicly accessible. Until then, the record and the files can <bold>only</bold> be accessed by <bold>users specified</bold> in the permissions.": "Am <bold>{{ date }}</bold> werden der Datensatz und die Dateien automatisch öffentlich zugänglich gemacht. Bis dahin können <bold>nur</bold> die in den Berechtigungen <bold>angegebenen Benutzer</bold> auf den Datensatz und die Dateien zugreifen.",
	"Embargoed (files-only)": "Embargoed (nur für Dateien)",
	"The record is publicly accessible. On <bold>{{ date }}</bold> the files will automatically be made publicly accessible. Until then, the files can <bold>only</bold> be accessed by <bold>users specified</bold> in the permissions.": "Der Datensatz ist öffentlich zugänglich. Am <bold>{{ date }}</bold> werden die Dateien automatisch öffentlich zugänglich gemacht. Bis dahin können die Dateien <bold>nur</bold> von den in den <bold>Berechtigungen angegebenen Benutzern</bold> aufgerufen werden.",
	"The record has no files.": "Der Eintrag hat keine Dateien.",
	"On <bold>{{ date }}</bold> the record will automatically be made publicly accessible. Until then, the record can <bold>only</bold> be accessed by <bold>users specified</bold> in the permissions.": "Am <bold>{{ date }}</bold>the record will automatically be made publicly accessible. Until then, the record can <bold>nur</bold>von den in den Berechtigungen <bold>angegebenen Benutzern</bold> aufgerufen werden.",
	Public: Public$1,
	Restricted: Restricted$2,
	"The record and files are publicly accessible.": "Der Eintrag und die Dateien sind öffentlich zugänglich.",
	"The record is publicly accessible.": "Der Eintrag ist öffentlich zugänglich.",
	"The record and files can <1>only</1> be accessed by<3>users specified</3> in the permissions.": "Auf den Eintrag und die Dateien können <1>nur</1> die in den Berechtigungen <3>angegebenen Benutzer</3> zugreifen.",
	"Public with restricted files": "Öffentlich mit eingeschränkten Dateien",
	"The record is publicly accessible. The files can <1>only</1> be accessed by <3>users specified</3> in the permissions.": "Der Eintrag ist öffentlich zugänglich. Auf die Dateien können <1>nur</1> die in den Berechtigungen <3>angegebenen Benutzer</3> zugreifen.",
	"The record can <1>only</1> be accessed by <3>users specified</3> in the permissions.": "Auf den Eintrag können <1>nur</1>die in den Berechtigungen <3>angegebenen Benutzer</3> zugreifen.",
	"Full record": "Vollständiger Eintrag",
	"Files only": "Nur Dateien",
	"Apply an embargo": "Embargo verhängen",
	"Embargo reason": "Embargo Grund",
	"Optionally, describe the reason for the embargo.": "Beschreiben Sie optional den Grund für das Embargo.",
	"Embargo was lifted on {{fmtDate}}.": "Das Embargo wurde am {{fmtDate}} aufgehoben.",
	Reason: Reason$1,
	"Record or files protection must be <1>restricted</1> to apply an embargo.": "Der Schutz von Einträgen oder Dateien muss <1>eingeschränkt</1> werden, um ein Embargo anzuwenden.",
	Options: Options$1,
	"Add description": "Beschreibung hinzufügen",
	"Additional Description": "Zusätzliche Beschreibung",
	Type: Type$1,
	Language: Language$1,
	"Select language": "Wählen Sie eine Sprache",
	"Add titles": "Titel hinzufügen",
	"Search or create affiliation'": "Zugehörigkeit suchen oder erstellen'",
	Affiliations: Affiliations$1,
	"Search for affiliations..": "Suche nach Zugehörigkeiten..",
	"Add creator": "Ersteller hinzufügen",
	Edit: Edit$1,
	Remove: Remove$1,
	"Name identifiers": "Kennungen benennen",
	"e.g. ORCID, ISNI or GND.": "z.B. ORCID, ISNI oder GND.",
	"Type the value of an identifier...": "Geben Sie den Wert einer Kennung ein...",
	"Save and add another": "Speichern und ein weiteres hinzufügen",
	"Family name is a required field.": "Der Familienname ist ein Pflichtfeld.",
	"Name is a required field.": "Name ist ein Pflichtfeld.",
	"Role is a required field.": "Rolle ist ein Pflichtfeld.",
	Added: Added$1,
	Person: Person$1,
	Organization: Organization$1,
	"Family name": "Familienname",
	"Given name(s)": "Vorname(n)",
	"Given name": "Vorname",
	Name: Name$1,
	"Organization name": "Name der Organisation",
	Role: Role$1,
	"Select role": "Wählen Sie eine Rolle",
	Cancel: Cancel$1,
	Save: Save$1,
	"Add date": "Datum hinzufügen",
	"Format: DATE or DATE/DATE where DATE is YYYY or YYYY-MM or YYYY-MM-DD.": "Format: DATUM oder DATUM/DATUM, wobei DATUM JJJJ oder JJJJ-MM oder JJJJ-MM-TT ist.",
	"Date": "Datum",
	Description: Description$1,
	Dates: Dates$1,
	"YYYY-MM-DD or YYYY-MM-DD/YYYY-MM-DD": "JJJJ-MM-TT oder JJJJ-MM-TT/ JJJJ-MM-TT",
	"discard changes": "Änderungen verwerfen",
	"discard version": "verworfene Version",
	"delete": "löschen",
	"Are you sure you want to discard the changes to this draft?": "Sind Sie sicher, dass Sie die Änderungen an diesem Entwurf verwerfen wollen?",
	"Are you sure you want to delete this new version?": "Sind Sie sicher, dass Sie diese neue Version löschen wollen?",
	"Are you sure you want to delete this draft?": "Sind Sie sicher, dass Sie diesen Entwurf löschen möchten?",
	"New version": "Neue Version",
	"New upload": "Neuer Eintrag",
	"Edit upload": "Upload bearbeiten",
	"Uploading the selected files would result in": "Das Hochladen der ausgewählten Dateien würde dazu führen, dass",
	"but the limit is": "aber die Grenze ist",
	"You can import files from the previous version.": "Sie können Dateien aus der Vorgängerversion importieren.",
	"File addition, removal or modification are not allowed after you have published your upload.": "Das Hinzufügen, Entfernen oder Ändern von Dateien ist nicht erlaubt, nachdem Sie Ihren Upload veröffentlicht haben.",
	"You must create a new version to add, modify or delete files.": "Sie müssen eine neue Version erstellen, um Dateien hinzuzufügen, zu ändern oder zu löschen.",
	"Drag and drop file(s)": "Ziehen und Ablegen von Datei(en)",
	"Upload files": "Dateien hochladen",
	"Import files": "Dateien importieren",
	Preview: Preview$1,
	Filename: Filename$1,
	Size: Size$1,
	Progress: Progress$1,
	"This is the file fingerprint (MD5 checksum), which can be used to verify the file integrity.": "Dies ist der Datei-Fingerabdruck (MD5-Prüfsumme), der zur Überprüfung der Dateiintegrität verwendet werden kann.",
	Pending: Pending$1,
	or: or$1,
	"This is a Metadata only record": "Dies ist ein reiner Metadateneintrag.",
	"Metadata-only record": "Nur-Metadaten Eintrag",
	"Storage available": "Verfügbarer Speicherplatz",
	"{{length}} out of {{maxfiles}} files": "{{length}} aus {{maxfiles}} Dateien",
	"out of": "aus",
	Files: Files$1,
	"Resource type": "Art der Ressource",
	Title: Title$1,
	"Additional titles": "Zusätzliche Titel",
	"Publication date": "Veröffentlichungsdatum",
	Creators: Creators$1,
	Contributors: Contributors$1,
	"Additional descriptions": "Zusätzliche Beschreibungen",
	Licenses: Licenses$1,
	Languages: Languages$1,
	Version: Version$1,
	Publisher: Publisher$1,
	"Related works": "Verwandte Werke",
	"Alternate identifiers": "Alternative Kennungen",
	"Record successfully saved.": "Eintrag erfolgreich gespeichert.",
	"Record saved with validation errors:": "Eintrag mit Überprüfungsfehlern gespeichert:",
	"There was an internal error (and the record was not saved).": "Es lag ein interner Fehler vor (und der Eintrag wurde nicht gespeichert).",
	"There was an internal error (and the record was not deleted).": "Es lag ein interner Fehler vor (und der Eintrag wurde nicht gelöscht).",
	"Add award": "Auszeichnung hinzufügen",
	"Funding Organization": "Organisation der Finanzierung",
	"Funding organization...": "Organisation der Finanzierung...",
	Award: Award$1,
	"Award number/acronym/name ...": "Vergabe-Nummer/Akronym/Name ...",
	Awards: Awards$1,
	"Add identifier": "Kennung hinzufügen",
	Identifier: Identifier$1,
	Scheme: Scheme$1,
	"Identifier(s)": "Bezeichner(n)",
	"Search for languages...": "Suche nach Sprachen...",
	"Search for a language by name (e.g \"eng\", \"fr\" or \"Polish\")": "Suche nach einer Sprache anhand des Namens (z. B. \"eng\", \"fr\" oder \"polnisch\")",
	"Add standard": "Standard hinzufügen",
	"Add custom": "Benutzerdefiniertes hinzufügen",
	"Read more": "Mehr lesen",
	"Title is a required field.": "Titel ist ein Pflichtfeld.",
	"Link must be a valid URL": "Link muss eine gültige URL sein",
	Recommended: Recommended$1,
	All: All$1,
	Data: Data$1,
	Software: Software$1,
	"License title": "Lizenztitel",
	Link: Link$1,
	"License link": "Lizenzlink",
	"Add license": "Lizenz hinzufügen",
	"Change license": "Lizenz ändern",
	"You don't have permissions to create a new version.": "Sie haben nicht die Berechtigung, eine neue Version zu erstellen.",
	"In case your upload was already published elsewhere, please use the date of the first publication. Format: YYYY-MM-DD, YYYY-MM, or YYYY. For intervals use DATE/DATE, e.g. 1939/1945.": "Falls Ihr Upload bereits an anderer Stelle veröffentlicht wurde, verwenden Sie bitte das Datum der Erstveröffentlichung. Format: JJJJ-MM-TT, JJJJ-MM, oder JJJJ. Für Intervalle verwenden Sie DATE/DATE, z. B. 1939/1945.",
	"YYYY-MM-DD or YYYY-MM-DD/YYYY-MM-DD for intervals. MM and DD are optional.": "JJJJ-MM-TT oder JJJJ-MM-TT/ JJJJ-MM-TT für Intervalle. MM und TT sind optional.",
	publish: publish$1,
	"Are you sure you want to {{action}} this record?": "Sind Sie sicher, dass Sie diesen Eintrag {{action}} wollen?",
	"The publisher is used to formulate the citation, so consider the prominence of the role.": "Der Herausgeber wird zur Formulierung des Zitats verwendet, beachten Sie also die Bedeutsamkeit der Rolle.",
	"Enter publisher name": "Herausgebername eingeben",
	"Specify identifiers of related works. Supported identifiers include DOI, Handle, ARK, PURL, ISSN, ISBN, PubMed ID, PubMed Central ID, ADS Bibliographic Code, arXiv, Life Science Identifiers (LSID), EAN-13, ISTC, URNs, and URLs.": "Geben Sie Bezeichner von verwandten Werken an. Unterstützte Bezeichner sind DOI, Handle, ARK, PURL, ISSN, ISBN, PubMed ID, PubMed Central ID, ADS Bibliographic Code, arXiv, Life Science Identifiers (LSID), EAN-13, ISTC, URNs und URLs.",
	"Add related work": "Verwandte Arbeiten hinzufügen",
	Relation: Relation$1,
	"Select relation...": "Relation auswählen...",
	"Save draft": "Entwurf speichern",
	"Suggest from": "Vorschlagen von",
	"Search or create subjects..": "Themen suchen oder erstellen...",
	Subjects: Subjects$1,
	"Search for a subject by name": "Suche nach einem Thema anhand des Namens",
	"Mostly relevant for software and dataset uploads. A semantic version string is preferred see<1> semver.org</1>, but any version string is accepted.": "Hauptsächlich relevant für Software- und Datensatz-Uploads. Ein semantischer Versionsstring wird bevorzugt, siehe <1>semver.org</1>, aber jeder Versionsstring wird akzeptiert.",
	"Do you already have a {{pidLabel}} for this upload?": "Haben Sie bereits einen {{pidLabel}} für diesen Eintrag?",
	Yes: Yes,
	No: No
};

var Public = "";
var Restricted$1 = "";
var Reason = "";
var Options = "";
var Type = "";
var Language = "";
var Affiliations = "";
var Added = "";
var Person = "";
var Organization = "";
var Name = "";
var Role = "";
var Cancel = "";
var Save = "";
var Description = "";
var Dates = "";
var Preview = "";
var Filename = "";
var Size = "";
var Progress = "";
var Pending = "";
var or = "";
var Identifier = "";
var Scheme = "";
var Languages = "";
var Licenses = "";
var Remove = "";
var Recommended = "";
var All = "";
var Data = "";
var Software = "";
var Title = "";
var Link = "";
var publish = "";
var Publisher = "";
var Relation = "";
var Subjects = "";
var Version = "";
var Edit = "";
var Award = "";
var Awards = "";
var Files = "";
var Creators = "";
var Contributors = "";
var TRANSLATE_TR = {
	"New version": "",
	"New upload": "",
	"Edit upload": "",
	"Storage available": "",
	"The full record is restricted.": "",
	Public: Public,
	Restricted: Restricted$1,
	"The record and files are publicly accessible.": "",
	"Public with restricted files": "",
	"Full record": "",
	"Files only": "",
	"Apply an embargo": "",
	"Embargo reason": "",
	"Optionally, describe the reason for the embargo.": "",
	"Embargo was lifted on {{fmtDate}}.": "",
	Reason: Reason,
	Options: Options,
	"Add description": "",
	"Additional Description": "",
	Type: Type,
	Language: Language,
	"Select language": "",
	"Add titles": "",
	"Search or create affiliation'": "",
	Affiliations: Affiliations,
	"Search for affiliations..": "",
	"Add creator": "",
	"Name identifiers": "",
	"e.g. ORCID, ISNI or GND.": "",
	"Type the value of an identifier...": "",
	"Save and add another": "",
	"Family name is a required field.": "",
	"Name is a required field.": "",
	"Role is a required field.": "",
	Added: Added,
	Person: Person,
	Organization: Organization,
	"Family name": "",
	"Given name(s)": "",
	"Given name": "",
	Name: Name,
	"Organization name": "",
	Role: Role,
	"Select role": "",
	Cancel: Cancel,
	Save: Save,
	"Add date": "",
	"Format: DATE or DATE/DATE where DATE is YYYY or YYYY-MM or YYYY-MM-DD.": "",
	"Date": "",
	Description: Description,
	Dates: Dates,
	"YYYY-MM-DD or YYYY-MM-DD/YYYY-MM-DD": "",
	"Are you sure you want to discard the changes to this draft?": "",
	"Are you sure you want to delete this new version?": "",
	"Are you sure you want to delete this draft?": "",
	"discard version": "",
	"delete": "",
	"discard changes": "",
	"Uploading the selected files would result in": "",
	"but the limit is": "",
	"You can import files from the previous version.": "",
	"File addition, removal or modification are not allowed after you have published your upload.": "",
	"You must create a new version to add, modify or delete files.": "",
	"Drag and drop file(s)": "",
	"Upload files": "",
	"Import files": "",
	Preview: Preview,
	Filename: Filename,
	Size: Size,
	Progress: Progress,
	"This is the file fingerprint (MD5 checksum), which can be used to verify the file integrity.": "",
	Pending: Pending,
	or: or,
	"This is a Metadata only record": "",
	"Metadata-only record": "",
	"{{length}} out of {{maxfiles}} files": "",
	"out of": "",
	"Add identifier": "",
	Identifier: Identifier,
	Scheme: Scheme,
	"Identifier(s)": "",
	"Search for languages...": "",
	Languages: Languages,
	"Search for a language by name (e.g \"eng\", \"fr\" or \"Polish\")": "",
	"Add standard": "",
	"Add custom": "",
	Licenses: Licenses,
	Remove: Remove,
	"Read more": "",
	"Title is a required field.": "",
	"Link must be a valid URL": "",
	Recommended: Recommended,
	All: All,
	Data: Data,
	Software: Software,
	Title: Title,
	"License title": "",
	Link: Link,
	"License link": "",
	"Add license": "",
	"Change license": "",
	"In case your upload was already published elsewhere, please use the date of the first publication. Format: YYYY-MM-DD, YYYY-MM, or YYYY. For intervals use DATE/DATE, e.g. 1939/1945.": "",
	"Publication date": "",
	"YYYY-MM-DD or YYYY-MM-DD/YYYY-MM-DD for intervals. MM and DD are optional.": "",
	publish: publish,
	"Are you sure you want to {{action}} this record?": "",
	"The publisher is used to formulate the citation, so consider the prominence of the role.": "",
	Publisher: Publisher,
	"Enter publisher name": "",
	"Specify identifiers of related works. Supported identifiers include DOI, Handle, ARK, PURL, ISSN, ISBN, PubMed ID, PubMed Central ID, ADS Bibliographic Code, arXiv, Life Science Identifiers (LSID), EAN-13, ISTC, URNs, and URLs.": "",
	"Add related work": "",
	Relation: Relation,
	"Select relation...": "",
	"Related works": "",
	"Resource type": "",
	"Save draft": "",
	"Suggest from": "",
	"Search or create subjects..": "",
	Subjects: Subjects,
	"Search for a subject by name": "",
	Version: Version,
	"The record and files can <1>only</1> be accessed by<3>users specified</3> in the permissions.": "",
	"The record is publicly accessible. The files can <1>only</1> be accessed by <3>users specified</3> in the permissions.": "",
	"Record or files protection must be <1>restricted</1> to apply an embargo.": "",
	"The record has no files.": "",
	"Embargoed (full record)": "",
	"Embargoed (files-only)": "",
	"Embargo until": "",
	"Alternate identifiers": "",
	"YYYY-MM-DD": "",
	Edit: Edit,
	"Add award": "",
	"Funding Organization": "",
	"Funding organization...": "",
	Award: Award,
	"Award number/acronym/name ...": "",
	Awards: Awards,
	Files: Files,
	Creators: Creators,
	Contributors: Contributors,
	"Record successfully saved.": "",
	"Record saved with validation errors:": "",
	"There was an internal error (and the record was not saved).": "",
	"There was an internal error (and the record was not deleted).": "",
	"The record is publicly accessible.": "",
	"The record can <1>only</1> be accessed by <3>users specified</3> in the permissions.": "",
	"You don't have permissions to create a new version.": "",
	"Additional titles": "",
	"Additional descriptions": "",
	"On <bold>{{ date }}</bold> the record and the files will automatically be made publicly accessible. Until then, the record and the files can <bold>only</bold> be accessed by <bold>users specified</bold> in the permissions.": "",
	"The record is publicly accessible. On <bold>{{ date }}</bold> the files will automatically be made publicly accessible. Until then, the files can <bold>only</bold> be accessed by <bold>users specified</bold> in the permissions.": "",
	"On <bold>{{ date }}</bold> the record will automatically be made publicly accessible. Until then, the record can <bold>only</bold> be accessed by <bold>users specified</bold> in the permissions.": ""
};

var translations = {
  el: {
    translation: TRANSLATE_EL
  },
  en: {
    translation: TRANSLATE_EN
  },
  de: {
    translation: TRANSLATE_DE
  },
  tr: {
    translation: TRANSLATE_TR
  }
};

// This file is part of React-Invenio-Deposit
var options = {
  fallbackLng: 'en',
  // fallback keys
  returnEmptyString: false,
  debug: process.env.NODE_ENV === 'development',
  resources: translations,
  keySeparator: false,
  nsSeparator: false,
  // specify language detection order
  detection: {
    order: ['htmlTag'],
    // cache user language off
    caches: []
  },
  react: {
    // Set empty - to allow html tags convert to trans tags
    // HTML TAG | Trans TAG
    //  <span>  | <1>
    transKeepBasicHtmlNodesFor: []
  }
}; // i18next instance creation
// https://www.i18next.com/overview/api#instance-creation
// this is required in order to keep the resources seperate
// if there is going to be another package
// which requires translation this is the way to create a new instance.
//
// We can use this particular instance for this particular package
// to mark strings for translation.

var i18next = i18n__default['default'].createInstance();
i18next.use(LanguageDetector__default['default']).init(options); // Bind Trans component to i18next instance

var Trans = function Trans(props) {
  return /*#__PURE__*/React__default['default'].createElement(reactI18next.Trans, Object.assign({
    i18n: i18next
  }, props));
};

var DepositFormApp = /*#__PURE__*/function (_Component) {
  _inherits(DepositFormApp, _Component);

  var _super = _createSuper(DepositFormApp);

  function DepositFormApp(props) {
    var _this;

    _classCallCheck(this, DepositFormApp);

    _this = _super.call(this);
    var apiClient = props.apiClient ? props.apiClient : new DepositApiClient(props.config.createUrl);
    var fileUploader = props.fileUploader ? props.fileUploader : new DepositFileUploader(apiClient, props.config);
    var controller = props.controller ? props.controller : new DepositController(apiClient, fileUploader);
    var recordSerializer = props.recordSerializer ? props.recordSerializer : new DepositRecordSerializer(props.config.default_locale);
    var appConfig = {
      config: props.config,
      record: recordSerializer.deserialize(props.record),
      files: props.files,
      controller: controller,
      apiClient: apiClient,
      fileUploader: fileUploader,
      permissions: props.permissions,
      recordSerializer: recordSerializer
    };
    _this.store = configureStore(appConfig);
    return _this;
  }

  _createClass(DepositFormApp, [{
    key: "render",
    value: function render() {
      return /*#__PURE__*/React__default['default'].createElement(reactRedux.Provider, {
        store: this.store
      }, /*#__PURE__*/React__default['default'].createElement(reactI18next.I18nextProvider, {
        i18n: i18next
      }, /*#__PURE__*/React__default['default'].createElement(DepositBootstrap, null, this.props.children)));
    }
  }]);

  return DepositFormApp;
}(React.Component);

function _arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}

function _iterableToArray(iter) {
  if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
}

function _nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}

function _toConsumableArray(arr) {
  return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
}

var DepositErrorHandler = /*#__PURE__*/function () {
  function DepositErrorHandler() {
    _classCallCheck(this, DepositErrorHandler);
  }

  _createClass(DepositErrorHandler, [{
    key: "extractErrors",
    value: function extractErrors(error, record) {
      var backendErrors = _get__default['default'](error, 'response.data.errors', []);

      var backendErrorMessage = _get__default['default'](error, 'response.data.message', '');

      var frontendErrors = {
        message: backendErrorMessage
      };

      var _iterator = _createForOfIteratorHelper(backendErrors),
          _step;

      try {
        for (_iterator.s(); !(_step = _iterator.n()).done;) {
          var fieldError = _step.value;

          var errorPath = _join__default['default']([].concat(_toConsumableArray(fieldError.parents), [fieldError.field]), '.');

          frontendErrors[errorPath] = fieldError.message;
        }
      } catch (err) {
        _iterator.e(err);
      } finally {
        _iterator.f();
      }

      return frontendErrors;
    }
  }]);

  return DepositErrorHandler;
}();

var _excluded$7 = ["dispatch"];
function connect(Component) {
  var WrappedComponent = function WrappedComponent(_ref) {
    _ref.dispatch;
        var props = _objectWithoutProperties(_ref, _excluded$7);

    return /*#__PURE__*/React__default['default'].createElement(Component, props);
  };

  var mapStateToProps = function mapStateToProps(state) {
    return {
      deposit: state.deposit
    };
  };

  return reactRedux.connect(mapStateToProps, null)(WrappedComponent);
}

// This file is part of React-Invenio-Deposit
// Copyright (C) 2020 CERN.
// Copyright (C) 2020 Northwestern University.
//
// React-Invenio-Deposit is free software; you can redistribute it and/or modify it
// under the terms of the MIT License; see LICENSE file for more details.
var getInputFromDOM = function getInputFromDOM(elementName) {
  var element = document.getElementsByName(elementName);

  if (element.length > 0 && element[0].hasAttribute('value')) {
    return JSON.parse(element[0].value);
  }

  return null;
};

// This file is part of React-Invenio-Deposit
// Copyright (C) 2020-2021 CERN.
// Copyright (C) 2020-2021 Northwestern University.
//
// React-Invenio-Deposit is free software; you can redistribute it and/or modify it
// under the terms of the MIT License; see LICENSE file for more details.
var EmbargoState = /*#__PURE__*/function () {
  function EmbargoState() {
    _classCallCheck(this, EmbargoState);
  }

  _createClass(EmbargoState, null, [{
    key: "isEnabled",
    value: function isEnabled(access) {
      return access.record === 'restricted' || access.files === 'restricted';
    }
  }, {
    key: "from",
    value: function from(access) {
      if (access.embargo && access.embargo.active) {
        return EmbargoState.APPLIED;
      } else if (EmbargoState.isEnabled(access)) {
        return EmbargoState.ENABLED;
      } else {
        return EmbargoState.DISABLED;
      }
    }
  }]);

  return EmbargoState;
}();
EmbargoState.DISABLED = 'disabled';
EmbargoState.ENABLED = 'enabled';
EmbargoState.APPLIED = 'applied';
var Embargo = /*#__PURE__*/function () {
  function Embargo(_ref) {
    var state = _ref.state,
        date = _ref.date,
        reason = _ref.reason;

    _classCallCheck(this, Embargo);

    this.state = state || EmbargoState.DISABLED;
    this.date = date || '';
    this.reason = reason || '';
  }

  _createClass(Embargo, [{
    key: "is",
    value: function is(state) {
      return this.state === state;
    }
  }]);

  return Embargo;
}();

var ProtectionButtonsComponent = /*#__PURE__*/function (_Component) {
  _inherits(ProtectionButtonsComponent, _Component);

  var _super = _createSuper(ProtectionButtonsComponent);

  function ProtectionButtonsComponent() {
    _classCallCheck(this, ProtectionButtonsComponent);

    return _super.apply(this, arguments);
  }

  _createClass(ProtectionButtonsComponent, [{
    key: "getButtonProps",
    value:
    /**
     * Returns the props for a protection button.
     * @param active is button active
     * @param activeColor button color when active
     */
    function getButtonProps(active, activeColor) {
      var props = {
        active: active
      };

      if (active) {
        props['color'] = activeColor;
      }

      return props;
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props = this.props,
          fieldPath = _this$props.fieldPath,
          formik = _this$props.formik,
          active = _this$props.active;
      return /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Button.Group, {
        widths: '2'
      }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Button, Object.assign({}, this.getButtonProps(active, 'green'), {
        onClick: function onClick(event, data) {
          formik.form.setFieldValue(fieldPath, 'public'); // NOTE: We reset values, so if embargo filled and click Public,
          //       user needs to fill embargo again. Otherwise lots of
          //       bookkeeping.

          formik.form.setFieldValue('access.embargo', {
            active: false
          });
        },
        compact: true,
        attached: true
      }), i18next.t('Public')), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Button, Object.assign({}, this.getButtonProps(!active, 'red'), {
        onClick: function onClick(event, data) {
          return formik.form.setFieldValue(fieldPath, 'restricted');
        },
        compact: true,
        attached: true
      }), i18next.t('Restricted')));
    }
  }]);

  return ProtectionButtonsComponent;
}(React.Component);

var ProtectionButtons = /*#__PURE__*/function (_Component2) {
  _inherits(ProtectionButtons, _Component2);

  var _super2 = _createSuper(ProtectionButtons);

  function ProtectionButtons() {
    _classCallCheck(this, ProtectionButtons);

    return _super2.apply(this, arguments);
  }

  _createClass(ProtectionButtons, [{
    key: "render",
    value: function render() {
      var _this = this;

      var fieldPath = this.props.fieldPath;
      return /*#__PURE__*/React__default['default'].createElement(formik.FastField, {
        name: fieldPath,
        component: function component(formikProps) {
          return /*#__PURE__*/React__default['default'].createElement(ProtectionButtonsComponent, Object.assign({
            formik: formikProps
          }, _this.props));
        }
      });
    }
  }]);

  return ProtectionButtons;
}(React.Component);

var EmbargoCheckboxComponent = /*#__PURE__*/function (_Component) {
  _inherits(EmbargoCheckboxComponent, _Component);

  var _super = _createSuper(EmbargoCheckboxComponent);

  function EmbargoCheckboxComponent() {
    _classCallCheck(this, EmbargoCheckboxComponent);

    return _super.apply(this, arguments);
  }

  _createClass(EmbargoCheckboxComponent, [{
    key: "render",
    value: function render() {
      var _this$props = this.props,
          fieldPath = _this$props.fieldPath,
          formik = _this$props.formik,
          embargo = _this$props.embargo;
      return /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Checkbox, {
        id: fieldPath,
        disabled: embargo.is(EmbargoState.DISABLED),
        checked: embargo.is(EmbargoState.APPLIED),
        onChange: function onChange(event, data) {
          if (formik.field.value) {
            // NOTE: We reset values, so if embargo filled and user unchecks,
            //       user needs to fill embargo again. Otherwise lots of
            //       bookkeeping.
            formik.form.setFieldValue("access.embargo", {
              active: false
            });
          } else {
            formik.form.setFieldValue(fieldPath, true);
          }
        }
      });
    }
  }]);

  return EmbargoCheckboxComponent;
}(React.Component);

var EmbargoCheckboxField = /*#__PURE__*/function (_Component2) {
  _inherits(EmbargoCheckboxField, _Component2);

  var _super2 = _createSuper(EmbargoCheckboxField);

  function EmbargoCheckboxField() {
    _classCallCheck(this, EmbargoCheckboxField);

    return _super2.apply(this, arguments);
  }

  _createClass(EmbargoCheckboxField, [{
    key: "render",
    value: function render() {
      var _this = this;

      // NOTE: See the optimization pattern on AccessRightField for more details.
      //       This makes FastField only render when the things
      //       (access.embargo.active and embargo) it cares about change as it
      //       should be.
      var change = this.props.embargo.is(EmbargoState.DISABLED) ? {} : {
        change: true
      };
      return /*#__PURE__*/React__default['default'].createElement(formik.FastField, Object.assign({
        name: this.props.fieldPath,
        component: function component(formikProps) {
          return /*#__PURE__*/React__default['default'].createElement(EmbargoCheckboxComponent, Object.assign({
            formik: formikProps
          }, _this.props));
        }
      }, change));
    }
  }]);

  return EmbargoCheckboxField;
}(React.Component);

// This file is part of React-Invenio-Deposit
function EmbargoDateField(_ref) {
  var fieldPath = _ref.fieldPath,
      label = _ref.label,
      labelIcon = _ref.labelIcon,
      placeholder = _ref.placeholder,
      required = _ref.required;
  return /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.TextField, {
    fieldPath: fieldPath,
    label: /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.FieldLabel, {
      htmlFor: fieldPath,
      icon: labelIcon,
      label: label
    }),
    placeholder: placeholder,
    required: required
  });
}
EmbargoDateField.defaultProps = {
  fieldPath: 'access.embargo.until',
  label: i18next.t('Embargo until'),
  labelIcon: 'calendar',
  placeholder: i18next.t('YYYY-MM-DD')
};

// This file is part of React-Invenio-Deposit
function MetadataSection(_ref) {
  var isPublic = _ref.isPublic;
  return /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, /*#__PURE__*/React__default['default'].createElement("p", null, i18next.t('Full record')), /*#__PURE__*/React__default['default'].createElement(ProtectionButtons, {
    active: isPublic,
    fieldPath: "access.record"
  }));
}
function filesButtons(filesPublic) {
  return /*#__PURE__*/React__default['default'].createElement(ProtectionButtons, {
    active: filesPublic,
    fieldPath: "access.files"
  });
}
function filesSection(filesStyle, filesContent) {
  return /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, /*#__PURE__*/React__default['default'].createElement("p", {
    style: filesStyle
  }, i18next.t('Files only')), filesContent);
}
function MessageSection(_ref2) {
  var intent = _ref2.intent,
      icon = _ref2.icon,
      title = _ref2.title,
      text = _ref2.text;
  return /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Message, Object.assign({
    visible: true
  }, intent), /*#__PURE__*/React__default['default'].createElement("strong", null, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Icon, {
    name: icon
  }), " ", title), /*#__PURE__*/React__default['default'].createElement("p", {
    style: {
      marginTop: '0.25em'
    }
  }, text));
}
function embargoSection(initialAccessValues, embargo) {
  var _initialAccessValues$, _initialAccessValues$2, _initialAccessValues$3, _initialAccessValues$4;

  var fmtDate = ((_initialAccessValues$ = initialAccessValues.embargo) === null || _initialAccessValues$ === void 0 ? void 0 : _initialAccessValues$.until) ? luxon.DateTime.fromISO((_initialAccessValues$2 = initialAccessValues.embargo) === null || _initialAccessValues$2 === void 0 ? void 0 : _initialAccessValues$2.until).toLocaleString(luxon.DateTime.DATE_FULL) // e.g. June 21, 2021
  : '???';
  var embargoWasLifted = !((_initialAccessValues$3 = initialAccessValues.embargo) === null || _initialAccessValues$3 === void 0 ? void 0 : _initialAccessValues$3.active) && !_isEmpty__default['default']((_initialAccessValues$4 = initialAccessValues.embargo) === null || _initialAccessValues$4 === void 0 ? void 0 : _initialAccessValues$4.until);
  return /*#__PURE__*/React__default['default'].createElement(semanticUiReact.List, null, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.List.Item, null, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.List.Icon, null, /*#__PURE__*/React__default['default'].createElement(EmbargoCheckboxField, {
    fieldPath: "access.embargo.active",
    embargo: embargo
  })), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.List.Content, null, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.List.Header, null, /*#__PURE__*/React__default['default'].createElement("label", {
    className: embargo.is(EmbargoState.DISABLED) ? 'disabled' : '',
    htmlFor: 'access.embargo.active'
  }, i18next.t('Apply an embargo'), " ", /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Icon, {
    name: "clock outline"
  }))), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.List.Description, {
    className: 'disabled'
  }, /*#__PURE__*/React__default['default'].createElement(Trans, null, "Record or files protection must be ", /*#__PURE__*/React__default['default'].createElement("b", null, "restricted"), " to apply an embargo.")), embargo.is(EmbargoState.APPLIED) && /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Divider, {
    hidden: true
  }), /*#__PURE__*/React__default['default'].createElement(EmbargoDateField, {
    fieldPath: "access.embargo.until",
    required: true
  }), /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.TextAreaField, {
    label: i18next.t('Embargo reason'),
    fieldPath: 'access.embargo.reason',
    placeholder: i18next.t('Optionally, describe the reason for the embargo.'),
    optimized: true
  })), embargoWasLifted && /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Divider, {
    hidden: true
  }), /*#__PURE__*/React__default['default'].createElement("p", null, i18next.t("Embargo was lifted on {{fmtDate}}.", {
    fmtDate: fmtDate
  })), initialAccessValues.embargo.reason && /*#__PURE__*/React__default['default'].createElement("p", null, /*#__PURE__*/React__default['default'].createElement("b", null, i18next.t('Reason')), ":", ' ', initialAccessValues.embargo.reason, ".")))));
}

var Embargoed = /*#__PURE__*/function () {
  function Embargoed(embargo) {
    _classCallCheck(this, Embargoed);

    this.embargo = embargo;
  }

  _createClass(Embargoed, [{
    key: "renderMetadataSection",
    value: function renderMetadataSection() {
      return /*#__PURE__*/React__default['default'].createElement(MetadataSection, {
        isPublic: false
      });
    }
  }, {
    key: "renderFilesSection",
    value: function renderFilesSection() {
      // Same as Restricted
      var filesStyle = {
        opacity: '0.5',
        cursor: 'default !important'
      };
      var filesContent = /*#__PURE__*/React__default['default'].createElement("p", {
        style: _objectSpread2(_objectSpread2({}, filesStyle), {}, {
          textAlign: 'center'
        })
      }, /*#__PURE__*/React__default['default'].createElement("em", null, i18next.t('The full record is restricted.')));
      return filesSection(filesStyle, filesContent);
    }
  }, {
    key: "renderMessageSection",
    value: function renderMessageSection() {
      var fmtDate = this.embargo.date ? luxon.DateTime.fromISO(this.embargo.date).toLocaleString(luxon.DateTime.DATE_FULL) // e.g. June 21, 2021
      : '???';
      var text = /*#__PURE__*/React__default['default'].createElement(Trans, {
        defaults: "On <bold>{{ date }}</bold> the record and the files will automatically be made publicly accessible. Until then, the record and the files can <bold>only</bold> be accessed by <bold>users specified</bold> in the permissions.",
        values: {
          date: fmtDate
        },
        components: {
          bold: /*#__PURE__*/React__default['default'].createElement("b", null)
        }
      });
      return /*#__PURE__*/React__default['default'].createElement(MessageSection, {
        intent: {
          warning: true
        },
        icon: "lock",
        title: i18next.t('Embargoed (full record)'),
        text: text
      });
    }
  }, {
    key: "renderEmbargoSection",
    value: function renderEmbargoSection(initialAccessValues) {
      return embargoSection(initialAccessValues, this.embargo);
    }
  }]);

  return Embargoed;
}();

var EmbargoedFiles = /*#__PURE__*/function () {
  function EmbargoedFiles(embargo) {
    _classCallCheck(this, EmbargoedFiles);

    this.embargo = embargo;
  }

  _createClass(EmbargoedFiles, [{
    key: "renderMetadataSection",
    value: function renderMetadataSection() {
      return /*#__PURE__*/React__default['default'].createElement(MetadataSection, {
        isPublic: true
      });
    }
  }, {
    key: "renderFilesSection",
    value: function renderFilesSection() {
      var filesStyle = {};
      var filesContent = filesButtons(false);
      return filesSection(filesStyle, filesContent);
    }
  }, {
    key: "renderMessageSection",
    value: function renderMessageSection() {
      var fmtDate = this.embargo.date ? luxon.DateTime.fromISO(this.embargo.date).toLocaleString(luxon.DateTime.DATE_FULL) // e.g. June 21, 2021
      : '???';
      var text = /*#__PURE__*/React__default['default'].createElement(Trans, {
        defaults: "The record is publicly accessible. On <bold>{{ date }}</bold> the files will automatically be made publicly accessible. Until then, the files can <bold>only</bold> be accessed by <bold>users specified</bold> in the permissions.",
        values: {
          date: fmtDate
        },
        components: {
          bold: /*#__PURE__*/React__default['default'].createElement("b", null)
        }
      });
      return /*#__PURE__*/React__default['default'].createElement(MessageSection, {
        intent: {
          warning: true
        },
        icon: "lock",
        title: i18next.t('Embargoed (files-only)'),
        text: text
      });
    }
  }, {
    key: "renderEmbargoSection",
    value: function renderEmbargoSection(initialAccessValues) {
      return embargoSection(initialAccessValues, this.embargo);
    }
  }]);

  return EmbargoedFiles;
}();

var EmbargoedMetadataOnly = /*#__PURE__*/function () {
  function EmbargoedMetadataOnly(embargo) {
    _classCallCheck(this, EmbargoedMetadataOnly);

    this.embargo = embargo;
  }

  _createClass(EmbargoedMetadataOnly, [{
    key: "renderMetadataSection",
    value: function renderMetadataSection() {
      return /*#__PURE__*/React__default['default'].createElement(MetadataSection, {
        isPublic: false
      });
    }
  }, {
    key: "renderFilesSection",
    value: function renderFilesSection() {
      var filesStyle = {
        opacity: '0.5',
        cursor: 'default !important'
      };
      var filesContent = /*#__PURE__*/React__default['default'].createElement("p", {
        style: _objectSpread2(_objectSpread2({}, filesStyle), {}, {
          textAlign: 'center'
        })
      }, /*#__PURE__*/React__default['default'].createElement("em", null, i18next.t('The record has no files.')));
      return filesSection(filesStyle, filesContent);
    }
  }, {
    key: "renderMessageSection",
    value: function renderMessageSection() {
      var fmtDate = this.embargo.date ? luxon.DateTime.fromISO(this.embargo.date).toLocaleString(luxon.DateTime.DATE_FULL) // e.g. June 21, 2021
      : '???';
      var text = /*#__PURE__*/React__default['default'].createElement(Trans, {
        defaults: "On <bold>{{ date }}</bold> the record will automatically be made publicly accessible. Until then, the record can <bold>only</bold> be accessed by <bold>users specified</bold> in the permissions.",
        values: {
          date: fmtDate
        },
        components: {
          bold: /*#__PURE__*/React__default['default'].createElement("b", null)
        }
      });
      return /*#__PURE__*/React__default['default'].createElement(MessageSection, {
        intent: {
          warning: true
        },
        icon: "lock",
        title: i18next.t('Embargoed (full record)'),
        text: text
      });
    }
  }, {
    key: "renderEmbargoSection",
    value: function renderEmbargoSection(initialAccessValues) {
      return embargoSection(initialAccessValues, this.embargo);
    }
  }]);

  return EmbargoedMetadataOnly;
}();

var PublicFiles = /*#__PURE__*/function () {
  function PublicFiles(embargo) {
    _classCallCheck(this, PublicFiles);

    this.embargo = embargo;
  }

  _createClass(PublicFiles, [{
    key: "renderMetadataSection",
    value: function renderMetadataSection() {
      return /*#__PURE__*/React__default['default'].createElement(MetadataSection, {
        isPublic: true
      });
    }
  }, {
    key: "renderFilesSection",
    value: function renderFilesSection() {
      var filesStyle = {};
      var filesContent = filesButtons(true);
      return filesSection(filesStyle, filesContent);
    }
  }, {
    key: "renderMessageSection",
    value: function renderMessageSection() {
      var text = i18next.t('The record and files are publicly accessible.');
      return /*#__PURE__*/React__default['default'].createElement(MessageSection, {
        intent: {
          positive: true
        },
        icon: "lock open",
        title: i18next.t('Public'),
        text: text
      });
    }
  }, {
    key: "renderEmbargoSection",
    value: function renderEmbargoSection(initialAccessValues) {
      return embargoSection(initialAccessValues, this.embargo);
    }
  }]);

  return PublicFiles;
}();

var PublicMetadataOnly = /*#__PURE__*/function () {
  function PublicMetadataOnly(embargo) {
    _classCallCheck(this, PublicMetadataOnly);

    this.embargo = embargo;
  }

  _createClass(PublicMetadataOnly, [{
    key: "renderMetadataSection",
    value: function renderMetadataSection() {
      return /*#__PURE__*/React__default['default'].createElement(MetadataSection, {
        isPublic: true
      });
    }
  }, {
    key: "renderFilesSection",
    value: function renderFilesSection() {
      var filesStyle = {
        opacity: "0.5",
        cursor: "default !important"
      };
      var filesContent = /*#__PURE__*/React__default['default'].createElement("p", {
        style: _objectSpread2(_objectSpread2({}, filesStyle), {}, {
          textAlign: "center"
        })
      }, /*#__PURE__*/React__default['default'].createElement("em", null, i18next.t('The record has no files.')));
      return filesSection(filesStyle, filesContent);
    }
  }, {
    key: "renderMessageSection",
    value: function renderMessageSection() {
      var text = i18next.t('The record is publicly accessible.');
      return /*#__PURE__*/React__default['default'].createElement(MessageSection, {
        intent: {
          positive: true
        },
        icon: "lock open",
        title: i18next.t('Public'),
        text: text
      });
    }
  }, {
    key: "renderEmbargoSection",
    value: function renderEmbargoSection(initialAccessValues) {
      return embargoSection(initialAccessValues, this.embargo);
    }
  }]);

  return PublicMetadataOnly;
}();

var Restricted = /*#__PURE__*/function () {
  function Restricted(embargo) {
    _classCallCheck(this, Restricted);

    this.embargo = embargo;
  }

  _createClass(Restricted, [{
    key: "renderMetadataSection",
    value: function renderMetadataSection() {
      // Same as embargoed
      return /*#__PURE__*/React__default['default'].createElement(MetadataSection, {
        isPublic: false
      });
    }
  }, {
    key: "renderFilesSection",
    value: function renderFilesSection() {
      // Same as embargoed
      var filesStyle = {
        opacity: '0.5',
        cursor: 'default !important'
      };
      var filesContent = /*#__PURE__*/React__default['default'].createElement("p", {
        style: _objectSpread2(_objectSpread2({}, filesStyle), {}, {
          textAlign: 'center'
        })
      }, /*#__PURE__*/React__default['default'].createElement("em", null, i18next.t('The full record is restricted.')));
      return filesSection(filesStyle, filesContent);
    }
  }, {
    key: "renderMessageSection",
    value: function renderMessageSection() {
      var text = /*#__PURE__*/React__default['default'].createElement(Trans, null, "The record and files can ", /*#__PURE__*/React__default['default'].createElement("b", null, "only"), " be accessed by", /*#__PURE__*/React__default['default'].createElement("b", null, "users specified"), " in the permissions.");
      return /*#__PURE__*/React__default['default'].createElement(MessageSection, {
        intent: {
          negative: true
        },
        icon: "lock",
        title: i18next.t('Restricted'),
        text: text
      });
    }
  }, {
    key: "renderEmbargoSection",
    value: function renderEmbargoSection(initialAccessValues) {
      // Same as Embargoed, same as Public
      return embargoSection(initialAccessValues, this.embargo);
    }
  }]);

  return Restricted;
}();

var RestrictedFiles = /*#__PURE__*/function () {
  function RestrictedFiles(embargo) {
    _classCallCheck(this, RestrictedFiles);

    this.embargo = embargo;
  }

  _createClass(RestrictedFiles, [{
    key: "renderMetadataSection",
    value: function renderMetadataSection() {
      // Same as Public
      return /*#__PURE__*/React__default['default'].createElement(MetadataSection, {
        isPublic: true
      });
    }
  }, {
    key: "renderFilesSection",
    value: function renderFilesSection() {
      // Same as EmbargoedFiles
      var filesStyle = {};
      var filesContent = filesButtons(false);
      return filesSection(filesStyle, filesContent);
    }
  }, {
    key: "renderMessageSection",
    value: function renderMessageSection() {
      var text = /*#__PURE__*/React__default['default'].createElement(Trans, null, "The record is publicly accessible. The files can ", /*#__PURE__*/React__default['default'].createElement("b", null, "only"), " be accessed by ", /*#__PURE__*/React__default['default'].createElement("b", null, "users specified"), " in the permissions.");
      return /*#__PURE__*/React__default['default'].createElement(MessageSection, {
        intent: {
          warning: true
        },
        icon: "lock",
        title: i18next.t('Public with restricted files'),
        text: text
      });
    }
  }, {
    key: "renderEmbargoSection",
    value: function renderEmbargoSection(initialAccessValues) {
      return embargoSection(initialAccessValues, this.embargo);
    }
  }]);

  return RestrictedFiles;
}();

var RestrictedMetadataOnly = /*#__PURE__*/function () {
  function RestrictedMetadataOnly(embargo) {
    _classCallCheck(this, RestrictedMetadataOnly);

    this.embargo = embargo;
  }

  _createClass(RestrictedMetadataOnly, [{
    key: "renderMetadataSection",
    value: function renderMetadataSection() {
      // Same as embargoed
      return /*#__PURE__*/React__default['default'].createElement(MetadataSection, {
        isPublic: false
      });
    }
  }, {
    key: "renderFilesSection",
    value: function renderFilesSection() {
      // Same as embargoed
      var filesStyle = {
        opacity: '0.5',
        cursor: 'default !important'
      };
      var filesContent = /*#__PURE__*/React__default['default'].createElement("p", {
        style: _objectSpread2(_objectSpread2({}, filesStyle), {}, {
          textAlign: 'center'
        })
      }, /*#__PURE__*/React__default['default'].createElement("em", null, i18next.t('The record has no files.')));
      return filesSection(filesStyle, filesContent);
    }
  }, {
    key: "renderMessageSection",
    value: function renderMessageSection() {
      var text = /*#__PURE__*/React__default['default'].createElement(Trans, null, "The record can ", /*#__PURE__*/React__default['default'].createElement("b", null, "only"), " be accessed by ", /*#__PURE__*/React__default['default'].createElement("b", null, "users specified"), " in the permissions.");
      return /*#__PURE__*/React__default['default'].createElement(MessageSection, {
        intent: {
          negative: true
        },
        icon: "lock",
        title: i18next.t('Restricted'),
        text: text
      });
    }
  }, {
    key: "renderEmbargoSection",
    value: function renderEmbargoSection(initialAccessValues) {
      // Same as Embargoed, same as Public
      return embargoSection(initialAccessValues, this.embargo);
    }
  }]);

  return RestrictedMetadataOnly;
}();

var Protection = /*#__PURE__*/function () {
  function Protection() {
    _classCallCheck(this, Protection);
  }

  _createClass(Protection, null, [{
    key: "create",
    value: function create(access, isMetadataOnly) {
      var embargo = new Embargo({
        state: EmbargoState.from(access),
        date: access.embargo ? access.embargo.until : '',
        reason: access.embargo ? access.embargo.reason : ''
      });

      if (access.record === 'public') {
        if (isMetadataOnly) {
          return new PublicMetadataOnly(embargo);
        } else if (access.files === 'public') {
          return new PublicFiles(embargo);
        } else if (embargo.is(EmbargoState.APPLIED)) {
          return new EmbargoedFiles(embargo);
        } else {
          return new RestrictedFiles(embargo); // technically no embargo
        }
      } else {
        if (isMetadataOnly) {
          if (embargo.is(EmbargoState.APPLIED)) {
            return new EmbargoedMetadataOnly(embargo);
          } else {
            return new RestrictedMetadataOnly(embargo); // technically no embargo
          }
        } else if (embargo.is(EmbargoState.APPLIED)) {
          return new Embargoed(embargo);
        } else {
          return new Restricted(embargo); // technically no embargo
        }
      }
    }
  }]);

  return Protection;
}();

var AccessRightFieldComponent = /*#__PURE__*/function (_Component) {
  _inherits(AccessRightFieldComponent, _Component);

  var _super = _createSuper(AccessRightFieldComponent);

  function AccessRightFieldComponent() {
    _classCallCheck(this, AccessRightFieldComponent);

    return _super.apply(this, arguments);
  }

  _createClass(AccessRightFieldComponent, [{
    key: "render",
    value:
    /** Top-level Access Right Component */
    function render() {
      var _this$props = this.props,
          fieldPath = _this$props.fieldPath,
          formik = _this$props.formik,
          isMetadataOnly = _this$props.isMetadataOnly,
          label = _this$props.label,
          labelIcon = _this$props.labelIcon;
      var protection = Protection.create(formik.field.value, isMetadataOnly);
      return /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Card, {
        className: "access-right"
      }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Card.Content, null, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Form.Field, {
        required: true
      }, /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.FieldLabel, {
        htmlFor: fieldPath,
        icon: labelIcon,
        label: label
      }), protection.renderMetadataSection(), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Divider, {
        hidden: true
      }), protection.renderFilesSection(), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Divider, {
        hidden: true
      }), protection.renderMessageSection(), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Divider, {
        hidden: true
      }), /*#__PURE__*/React__default['default'].createElement("p", null, /*#__PURE__*/React__default['default'].createElement("b", null, i18next.t('Options'))), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Divider, null), protection.renderEmbargoSection(formik.form.initialValues.access))));
    }
  }]);

  return AccessRightFieldComponent;
}(React.Component);

var FormikAccessRightField = /*#__PURE__*/function (_Component2) {
  _inherits(FormikAccessRightField, _Component2);

  var _super2 = _createSuper(FormikAccessRightField);

  function FormikAccessRightField() {
    _classCallCheck(this, FormikAccessRightField);

    return _super2.apply(this, arguments);
  }

  _createClass(FormikAccessRightField, [{
    key: "render",
    value: function render() {
      var _this = this;

      // NOTE: This is a "cute" optimization.
      //       In general, FastField only re-renders if
      //       * formik slice associated with this.props.fieldPath changes
      //         (i.e. `access` changes)
      //       * props are ADDED or REMOVED to FastField
      // So we add/remove a prop to FastField based on the presence of files.
      // This way, FastField only renders when the things (access and isMetadataOnly)
      // it cares about change, as it should be.
      var change = this.props.isMetadataOnly ? {
        change: true
      } : {};
      return /*#__PURE__*/React__default['default'].createElement(formik.FastField, Object.assign({
        name: this.props.fieldPath,
        component: function component(formikProps) {
          return /*#__PURE__*/React__default['default'].createElement(AccessRightFieldComponent, Object.assign({
            formik: formikProps
          }, _this.props));
        }
      }, change));
    }
  }]);

  return FormikAccessRightField;
}(React.Component);

FormikAccessRightField.defaultProps = {
  fieldPath: 'access'
};

var mapStateToProps$8 = function mapStateToProps(state) {
  return {
    isMetadataOnly: !state.deposit.record.files.enabled
  };
};

var AccessRightField = reactRedux.connect(mapStateToProps$8, null)(FormikAccessRightField);

var _excluded$6 = ["fieldPath", "label", "labelIcon", "required", "multiple", "placeholder", "clearable", "initialOptions"];
var LanguagesField = /*#__PURE__*/function (_Component) {
  _inherits(LanguagesField, _Component);

  var _super = _createSuper(LanguagesField);

  function LanguagesField() {
    _classCallCheck(this, LanguagesField);

    return _super.apply(this, arguments);
  }

  _createClass(LanguagesField, [{
    key: "render",
    value: function render() {
      var _this$props = this.props,
          fieldPath = _this$props.fieldPath,
          label = _this$props.label,
          labelIcon = _this$props.labelIcon,
          required = _this$props.required,
          multiple = _this$props.multiple,
          placeholder = _this$props.placeholder,
          clearable = _this$props.clearable,
          initialOptions = _this$props.initialOptions,
          uiProps = _objectWithoutProperties(_this$props, _excluded$6);

      var serializeSuggestions = this.props.serializeSuggestions || null;
      return /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.RemoteSelectField, Object.assign({
        fieldPath: fieldPath,
        suggestionAPIUrl: "/api/vocabularies/languages",
        suggestionAPIHeaders: {
          Accept: 'application/vnd.inveniordm.v1+json'
        },
        placeholder: placeholder,
        required: required,
        clearable: clearable,
        multiple: multiple,
        initialSuggestions: initialOptions,
        label: /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.FieldLabel, {
          htmlFor: fieldPath,
          icon: labelIcon,
          label: label
        }),
        noQueryMessage: i18next.t('Search for languages...')
      }, serializeSuggestions && {
        serializeSuggestions: serializeSuggestions
      }, uiProps));
    }
  }]);

  return LanguagesField;
}(React.Component);
LanguagesField.defaultProps = {
  fieldPath: 'metadata.languages',
  label: i18next.t('Languages'),
  labelIcon: 'globe',
  multiple: true,
  clearable: true,
  placeholder: i18next.t('Search for a language by name (e.g "eng", "fr" or "Polish")')
};

var AdditionalTitlesField = /*#__PURE__*/function (_Component) {
  _inherits(AdditionalTitlesField, _Component);

  var _super = _createSuper(AdditionalTitlesField);

  function AdditionalTitlesField() {
    _classCallCheck(this, AdditionalTitlesField);

    return _super.apply(this, arguments);
  }

  _createClass(AdditionalTitlesField, [{
    key: "render",
    value: function render() {
      var _this$props = this.props,
          fieldPath = _this$props.fieldPath,
          options = _this$props.options,
          recordUI = _this$props.recordUI;
      return /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.ArrayField, {
        addButtonLabel: i18next.t('Add titles'),
        defaultNewValue: emptyAdditionalTitle,
        fieldPath: fieldPath
      }, function (_ref) {
        var _recordUI$additional_;

        _ref.array;
            var arrayHelpers = _ref.arrayHelpers,
            indexPath = _ref.indexPath,
            key = _ref.key;
        return /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.GroupField, {
          fieldPath: fieldPath,
          optimized: true
        }, /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.TextField, {
          fieldPath: "".concat(key, ".title"),
          label: 'Additional title',
          required: true,
          width: 5
        }), /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.SelectField, {
          fieldPath: "".concat(key, ".type"),
          label: 'Type',
          optimized: true,
          options: options.type,
          required: true,
          width: 5
        }), /*#__PURE__*/React__default['default'].createElement(LanguagesField, {
          serializeSuggestions: function serializeSuggestions(suggestions) {
            return suggestions.map(function (item) {
              return {
                text: item.title_l10n,
                value: item.id,
                key: item.id
              };
            });
          },
          initialOptions: (recordUI === null || recordUI === void 0 ? void 0 : recordUI.additional_titles) && ((_recordUI$additional_ = recordUI.additional_titles[indexPath]) === null || _recordUI$additional_ === void 0 ? void 0 : _recordUI$additional_.lang) ? [recordUI.additional_titles[indexPath].lang] : [],
          fieldPath: "".concat(key, ".lang"),
          label: 'Language',
          multiple: false,
          placeholder: 'Select language',
          labelIcon: null,
          clearable: true,
          selectOnBlur: false,
          width: 5
        }), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Form.Field, {
          width: 1
        }, /*#__PURE__*/React__default['default'].createElement("label", null, "\xA0"), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Button, {
          icon: true,
          onClick: function onClick() {
            return arrayHelpers.remove(indexPath);
          }
        }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Icon, {
          name: "close"
        }))));
      });
    }
  }]);

  return AdditionalTitlesField;
}(React.Component);
AdditionalTitlesField.defaultProps = {
  fieldPath: 'metadata.additional_titles'
};

/**Affiliation input component */

var AffiliationsField = /*#__PURE__*/function (_Component) {
  _inherits(AffiliationsField, _Component);

  var _super = _createSuper(AffiliationsField);

  function AffiliationsField() {
    var _this;

    _classCallCheck(this, AffiliationsField);

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

    _this = _super.call.apply(_super, [this].concat(args));

    _this.serializeAffiliations = function (affiliations) {
      return affiliations.map(function (affiliation) {
        return _objectSpread2(_objectSpread2({
          text: affiliation.acronym ? "".concat(affiliation.name, " (").concat(affiliation.acronym, ")") : affiliation.name,
          value: affiliation.name,
          key: affiliation.name
        }, affiliation.id ? {
          id: affiliation.id
        } : {}), {}, {
          name: affiliation.name
        });
      });
    };

    return _this;
  }

  _createClass(AffiliationsField, [{
    key: "render",
    value: function render() {
      var _this2 = this;

      var fieldPath = this.props.fieldPath;
      return /*#__PURE__*/React__default['default'].createElement(formik.Field, {
        name: this.props.fieldPath
      }, function (_ref) {
        var values = _ref.form.values;
        return /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.RemoteSelectField, {
          fieldPath: fieldPath,
          suggestionAPIUrl: "/api/affiliations",
          suggestionAPIHeaders: {
            Accept: 'application/json'
          },
          initialSuggestions: formik.getIn(values, fieldPath, []),
          serializeSuggestions: _this2.serializeAffiliations,
          placeholder: i18next.t("Search or create affiliation'"),
          label: /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.FieldLabel, {
            htmlFor: "".concat(fieldPath, ".name"),
            label: i18next.t('Affiliations')
          }),
          noQueryMessage: i18next.t('Search for affiliations..'),
          allowAdditions: true,
          clearable: true,
          multiple: true,
          onValueChange: function onValueChange(_ref2, selectedSuggestions) {
            var formikProps = _ref2.formikProps;
            formikProps.form.setFieldValue(fieldPath, // save the suggestion objects so we can extract information
            // about which value added by the user
            selectedSuggestions);
          },
          value: formik.getIn(values, fieldPath, []).map(function (val) {
            return val.name;
          })
        });
      });
    }
  }]);

  return AffiliationsField;
}(React.Component);

var ComingSoonField = /*#__PURE__*/function (_Component) {
  _inherits(ComingSoonField, _Component);

  var _super = _createSuper(ComingSoonField);

  function ComingSoonField() {
    _classCallCheck(this, ComingSoonField);

    return _super.apply(this, arguments);
  }

  _createClass(ComingSoonField, [{
    key: "render",
    value: function render() {
      var _this$props = this.props,
          fieldPath = _this$props.fieldPath,
          label = _this$props.label,
          labelIcon = _this$props.labelIcon;
      return /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Form.Field, {
        id: fieldPath,
        name: fieldPath
      }, /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.FieldLabel, {
        htmlFor: fieldPath,
        icon: labelIcon,
        label: label
      }), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Segment, {
        size: "massive",
        tertiary: true,
        textAlign: "center"
      }, "Coming soon"));
    }
  }]);

  return ComingSoonField;
}(React.Component);

var CreatibutorsIdentifiers = /*#__PURE__*/function (_Component) {
  _inherits(CreatibutorsIdentifiers, _Component);

  var _super = _createSuper(CreatibutorsIdentifiers);

  function CreatibutorsIdentifiers(props) {
    var _this;

    _classCallCheck(this, CreatibutorsIdentifiers);

    _this = _super.call(this, props);

    _this.handleIdentifierAddition = function (e, _ref) {
      var value = _ref.value;

      _this.setState(function (prevState) {
        return {
          selectedOptions: _unickBy__default['default']([{
            text: value,
            value: value,
            key: value
          }].concat(_toConsumableArray(prevState.selectedOptions)), 'value')
        };
      });
    };

    _this.valuesToOptions = function (options) {
      return options.map(function (option) {
        return {
          text: option,
          value: option,
          key: option
        };
      });
    };

    _this.handleChange = function (_ref2) {
      var data = _ref2.data,
          formikProps = _ref2.formikProps;

      _this.setState({
        selectedOptions: _this.valuesToOptions(data.value)
      });

      formikProps.form.setFieldValue(_this.props.fieldPath, data.value);
    };

    _this.state = {
      selectedOptions: props.initialOptions
    };
    return _this;
  }

  _createClass(CreatibutorsIdentifiers, [{
    key: "render",
    value: function render() {
      return /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.SelectField, {
        fieldPath: this.props.fieldPath,
        label: this.props.label,
        options: this.state.selectedOptions,
        placeholder: this.props.placeholder,
        noResultsMessage: i18next.t('Type the value of an identifier...'),
        search: true,
        multiple: true,
        selection: true,
        allowAdditions: true,
        onChange: this.handleChange // `icon` is set to `null` in order to hide the dropdown default icon
        ,
        icon: null,
        onAddItem: this.handleIdentifierAddition,
        optimized: true
      });
    }
  }]);

  return CreatibutorsIdentifiers;
}(React.Component);
CreatibutorsIdentifiers.defaultProps = {
  fieldPath: 'person_or_org.identifiers',
  label: i18next.t('Name identifiers'),
  placeholder: i18next.t('e.g. ORCID, ISNI or GND.')
};

// This file is part of React-Invenio-Deposit
// Copyright (C) 2021 CERN.
// Copyright (C) 2021 Northwestern University.
//
// React-Invenio-Deposit is free software; you can redistribute it and/or modify it
// under the terms of the MIT License; see LICENSE file for more details.
var CREATIBUTOR_TYPE = {
  PERSON: 'personal',
  ORGANIZATION: 'organizational'
};

var ModalActions$1 = {
  ADD: 'add',
  EDIT: 'edit'
};
var CreatibutorsModal = /*#__PURE__*/function (_Component) {
  _inherits(CreatibutorsModal, _Component);

  var _super = _createSuper(CreatibutorsModal);

  function CreatibutorsModal(props) {
    var _this;

    _classCallCheck(this, CreatibutorsModal);

    _this = _super.call(this, props);
    _this.CreatorSchema = Yup__namespace.object({
      person_or_org: Yup__namespace.object({
        type: Yup__namespace.string(),
        family_name: Yup__namespace.string().when('type', function (type, schema) {
          if (type === CREATIBUTOR_TYPE.PERSON && _this.isCreator()) {
            return schema.required(i18next.t('Family name is a required field.'));
          }
        }),
        name: Yup__namespace.string().when('type', function (type, schema) {
          if (type === CREATIBUTOR_TYPE.ORGANIZATION && _this.isCreator()) {
            return schema.required(i18next.t('Name is a required field.'));
          }
        })
      }),
      role: Yup__namespace.string().when('_', function (_, schema) {
        if (!_this.isCreator()) {
          return schema.required(i18next.t('Role is a required field.'));
        }
      })
    });

    _this.focusInput = function () {
      return _this.inputRef.current.focus();
    };

    _this.openModal = function () {
      _this.setState({
        open: true,
        action: null
      }, function () {
        _this.focusInput();
      });
    };

    _this.closeModal = function () {
      _this.setState({
        open: false,
        action: null
      });
    };

    _this.changeContent = function () {
      _this.setState({
        saveAndContinueLabel: i18next.t('Added')
      }); // change in 2 sec


      setTimeout(function () {
        _this.setState({
          saveAndContinueLabel: i18next.t('Save and add another')
        });
      }, 2000);
    };

    _this.displayActionLabel = function () {
      return _this.props.action === ModalActions$1.ADD ? _this.props.addLabel : _this.props.editLabel;
    };

    _this.serializeCreatibutor = function (submittedCreatibutor) {
      var findField = function findField(arrayField, key, value) {
        var knownField = _find__default['default'](arrayField, _defineProperty({}, key, value));

        return knownField ? knownField : _defineProperty({}, key, value);
      };

      var identifiersFieldPath = 'person_or_org.identifiers';
      var affiliationsFieldPath = 'affiliations'; // The modal is saving only identifiers values, thus
      // identifiers with existing scheme are trimmed
      // Here we merge back the known scheme for the submitted identifiers

      var initialIdentifiers = _get__default['default'](_this.props.initialCreatibutor, identifiersFieldPath, []);

      var submittedIdentifiers = _get__default['default'](submittedCreatibutor, identifiersFieldPath, []);

      var identifiers = submittedIdentifiers.map(function (identifier) {
        return findField(initialIdentifiers, 'identifier', identifier);
      });

      var submittedAffiliations = _get__default['default'](submittedCreatibutor, affiliationsFieldPath, []);

      return _objectSpread2(_objectSpread2({}, submittedCreatibutor), {}, {
        person_or_org: _objectSpread2(_objectSpread2({}, submittedCreatibutor.person_or_org), {}, {
          identifiers: identifiers
        }),
        affiliations: submittedAffiliations
      });
    };

    _this.deserializeCreatibutor = function (initialCreatibutor) {
      var identifiersFieldPath = 'person_or_org.identifiers';
      return {
        // default type to personal
        person_or_org: _objectSpread2(_objectSpread2({
          type: CREATIBUTOR_TYPE.PERSON
        }, initialCreatibutor.person_or_org), {}, {
          identifiers: _map__default['default'](_get__default['default'](initialCreatibutor, identifiersFieldPath, []), 'identifier')
        }),
        affiliations: _get__default['default'](initialCreatibutor, 'affiliations', []),
        role: _get__default['default'](initialCreatibutor, 'role', '')
      };
    };

    _this.isCreator = function () {
      return _this.props.schema === 'creators';
    };

    _this.onSubmit = function (values, formikBag) {
      _this.props.onCreatibutorChange(_this.serializeCreatibutor(values));

      formikBag.setSubmitting(false);
      formikBag.resetForm();

      switch (_this.state.action) {
        case 'saveAndContinue':
          // Needed to close and open the modal to reset the internal
          // state of the cmp inside the modal
          _this.closeModal();

          _this.openModal();

          _this.changeContent();

          break;

        case 'saveAndClose':
          _this.closeModal();

          break;
      }
    };

    _this.state = {
      open: false,
      saveAndContinueLabel: i18next.t('Save and add another'),
      action: null
    };
    _this.inputRef = React.createRef();
    return _this;
  }

  _createClass(CreatibutorsModal, [{
    key: "render",
    value: function render() {
      var _this2 = this;

      var initialCreatibutor = this.props.initialCreatibutor;

      var ActionLabel = function ActionLabel() {
        return _this2.displayActionLabel();
      };

      return /*#__PURE__*/React__default['default'].createElement(formik.Formik, {
        initialValues: this.deserializeCreatibutor(initialCreatibutor),
        onSubmit: this.onSubmit,
        enableReinitialize: true,
        validationSchema: this.CreatorSchema,
        validateOnChange: false,
        validateOnBlur: false
      }, function (_ref2) {
        var values = _ref2.values;
            _ref2.setFieldValue;
            var resetForm = _ref2.resetForm;
        var personOrOrgPath = "person_or_org";
        var typeFieldPath = "".concat(personOrOrgPath, ".type");
        var familyNameFieldPath = "".concat(personOrOrgPath, ".family_name");
        var givenNameFieldPath = "".concat(personOrOrgPath, ".given_name");
        var nameFieldPath = "".concat(personOrOrgPath, ".name");
        var identifiersFieldPath = "".concat(personOrOrgPath, ".identifiers");
        var affiliationsFieldPath = 'affiliations';
        var roleFieldPath = 'role';
        return /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Modal, {
          onOpen: function onOpen() {
            return _this2.openModal();
          },
          open: _this2.state.open,
          trigger: _this2.props.trigger,
          onClose: function onClose() {
            _this2.closeModal();

            resetForm();
          },
          closeIcon: true
        }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Modal.Header, {
          as: "h6",
          className: "deposit-modal-header"
        }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Grid, null, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Grid.Column, {
          floated: "left",
          width: 4
        }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Header, {
          as: "h2"
        }, /*#__PURE__*/React__default['default'].createElement(ActionLabel, null))))), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Modal.Content, null, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Form, null, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Form.Group, null, /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.RadioField, {
          fieldPath: typeFieldPath,
          label: i18next.t('Person'),
          checked: _get__default['default'](values, typeFieldPath) === CREATIBUTOR_TYPE.PERSON,
          value: CREATIBUTOR_TYPE.PERSON,
          onChange: function onChange(_ref3) {
            _ref3.event;
                _ref3.data;
                var formikProps = _ref3.formikProps;
            formikProps.form.setFieldValue(typeFieldPath, CREATIBUTOR_TYPE.PERSON);

            _this2.focusInput();
          },
          optimized: true
        }), /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.RadioField, {
          fieldPath: typeFieldPath,
          label: i18next.t('Organization'),
          checked: _get__default['default'](values, typeFieldPath) === CREATIBUTOR_TYPE.ORGANIZATION,
          value: CREATIBUTOR_TYPE.ORGANIZATION,
          onChange: function onChange(_ref4) {
            _ref4.event;
                _ref4.data;
                var formikProps = _ref4.formikProps;
            formikProps.form.setFieldValue(typeFieldPath, CREATIBUTOR_TYPE.ORGANIZATION);

            _this2.focusInput();
          },
          optimized: true
        })), _get__default['default'](values, typeFieldPath, '') === CREATIBUTOR_TYPE.PERSON ? /*#__PURE__*/React__default['default'].createElement("div", null, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Form.Group, {
          widths: "equal"
        }, /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.TextField, {
          label: i18next.t('Family name'),
          placeholder: i18next.t('Family name'),
          fieldPath: familyNameFieldPath,
          required: _this2.isCreator() // forward ref to Input component because Form.Input
          // doesn't handle it
          ,
          input: {
            ref: _this2.inputRef
          }
        }), /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.TextField, {
          label: i18next.t('Given name(s)'),
          placeholder: i18next.t('Given name'),
          fieldPath: givenNameFieldPath
        })), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Form.Group, {
          widths: "equal"
        }, /*#__PURE__*/React__default['default'].createElement(CreatibutorsIdentifiers, {
          initialOptions: _map__default['default'](_get__default['default'](values, identifiersFieldPath, []), function (identifier) {
            return {
              text: identifier,
              value: identifier,
              key: identifier
            };
          }),
          fieldPath: identifiersFieldPath
        }))) : /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.TextField, {
          label: i18next.t('Name'),
          placeholder: i18next.t('Organization name'),
          fieldPath: nameFieldPath,
          required: _this2.isCreator() // forward ref to Input component because Form.Input
          // doesn't handle it
          ,
          input: {
            ref: _this2.inputRef
          }
        }), /*#__PURE__*/React__default['default'].createElement(CreatibutorsIdentifiers, {
          initialOptions: _map__default['default'](_get__default['default'](values, identifiersFieldPath, []), function (identifier) {
            return {
              text: identifier,
              value: identifier,
              key: identifier
            };
          }),
          fieldPath: identifiersFieldPath,
          placeholder: i18next.t('e.g. ROR, ISNI or GND.')
        })), /*#__PURE__*/React__default['default'].createElement(AffiliationsField, {
          fieldPath: affiliationsFieldPath
        }), /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.SelectField, Object.assign({
          fieldPath: roleFieldPath,
          label: i18next.t('Role'),
          options: _this2.props.roleOptions,
          placeholder: i18next.t('Select role')
        }, _this2.isCreator() && {
          clearable: true
        }, {
          required: !_this2.isCreator(),
          optimized: true
        })))), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Modal.Actions, null, /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.ActionButton, {
          name: "cancel",
          onClick: function onClick(values, formikBag) {
            formikBag.resetForm();

            _this2.closeModal();
          },
          icon: "remove",
          content: i18next.t('Cancel'),
          floated: "left"
        }), _this2.props.action === ModalActions$1.ADD && /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.ActionButton, {
          name: "submit",
          onClick: function onClick(event, formik) {
            _this2.setState({
              action: 'saveAndContinue'
            }, function () {
              formik.handleSubmit();

              _this2.focusInput();
            });
          },
          primary: true,
          icon: "checkmark",
          content: _this2.state.saveAndContinueLabel
        }), /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.ActionButton, {
          name: "submit",
          onClick: function onClick(event, formik) {
            _this2.setState({
              action: 'saveAndClose'
            }, function () {
              return formik.handleSubmit();
            });
          },
          primary: true,
          icon: "checkmark",
          content: i18next.t('Save')
        })));
      });
    }
  }]);

  return CreatibutorsModal;
}(React.Component);
CreatibutorsModal.defaultProps = {
  roleOptions: [],
  initialCreatibutor: {}
};

function _arrayWithHoles(arr) {
  if (Array.isArray(arr)) return arr;
}

function _iterableToArrayLimit(arr, i) {
  if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return;
  var _arr = [];
  var _n = true;
  var _d = false;
  var _e = undefined;

  try {
    for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
      _arr.push(_s.value);

      if (i && _arr.length === i) break;
    }
  } catch (err) {
    _d = true;
    _e = err;
  } finally {
    try {
      if (!_n && _i["return"] != null) _i["return"]();
    } finally {
      if (_d) throw _e;
    }
  }

  return _arr;
}

function _nonIterableRest() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}

function _slicedToArray(arr, i) {
  return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
}

var CreatibutorsFieldItem = function CreatibutorsFieldItem(_ref) {
  var compKey = _ref.compKey,
      identifiersError = _ref.identifiersError,
      index = _ref.index,
      replaceCreatibutor = _ref.replaceCreatibutor,
      removeCreatibutor = _ref.removeCreatibutor,
      moveCreatibutor = _ref.moveCreatibutor,
      addLabel = _ref.addLabel,
      editLabel = _ref.editLabel,
      initialCreatibutor = _ref.initialCreatibutor,
      displayName = _ref.displayName,
      roleOptions = _ref.roleOptions,
      schema = _ref.schema;
  var dropRef = React__default['default'].useRef(null);

  var _useDrag = reactDnd.useDrag({
    item: {
      index: index,
      type: 'creatibutor'
    }
  }),
      _useDrag2 = _slicedToArray(_useDrag, 3);
      _useDrag2[0];
      var drag = _useDrag2[1],
      preview = _useDrag2[2];

  var _useDrop = reactDnd.useDrop({
    accept: 'creatibutor',
    hover: function hover(item, monitor) {
      if (!dropRef.current) {
        return;
      }

      var dragIndex = item.index;
      var hoverIndex = index; // Don't replace items with themselves

      // Don't replace items with themselves
      if (dragIndex === hoverIndex) {
        return;
      }

      if (monitor.isOver({
        shallow: true
      })) {
        moveCreatibutor(dragIndex, hoverIndex);
        item.index = hoverIndex;
      }
    },
    collect: function collect(monitor) {
      return {
        hidden: monitor.isOver({
          shallow: true
        })
      };
    }
  }),
      _useDrop2 = _slicedToArray(_useDrop, 2),
      hidden = _useDrop2[0].hidden,
      drop = _useDrop2[1];

  var renderRole = function renderRole(role, roleOptions) {
    if (role) {
      var _roleOptions$find$tex, _roleOptions$find;

      var friendlyRole = (_roleOptions$find$tex = (_roleOptions$find = roleOptions.find(function (_ref2) {
        var value = _ref2.value;
        return value === role;
      })) === null || _roleOptions$find === void 0 ? void 0 : _roleOptions$find.text) !== null && _roleOptions$find$tex !== void 0 ? _roleOptions$find$tex : role;
      return /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Label, {
        size: "tiny"
      }, friendlyRole);
    }
  };

  var firstError = identifiersError && identifiersError.find(function (elem) {
    return ![undefined, null].includes(elem);
  }); // Initialize the ref explicitely

  drop(dropRef);
  return /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Ref, {
    innerRef: dropRef,
    key: compKey
  }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.List.Item, {
    key: compKey,
    className: hidden ? 'deposit-drag-listitem hidden' : 'deposit-drag-listitem'
  }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.List.Content, {
    floated: "right"
  }, /*#__PURE__*/React__default['default'].createElement(CreatibutorsModal, {
    addLabel: addLabel,
    editLabel: editLabel,
    onCreatibutorChange: function onCreatibutorChange(selectedCreatibutor) {
      replaceCreatibutor(index, selectedCreatibutor);
    },
    initialCreatibutor: initialCreatibutor,
    roleOptions: roleOptions,
    schema: schema,
    action: "edit",
    trigger: /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Button, {
      size: "mini",
      primary: true,
      type: "button"
    }, i18next.t('Edit'))
  }), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Button, {
    size: "mini",
    type: "button",
    onClick: function onClick() {
      return removeCreatibutor(index);
    }
  }, i18next.t('Remove'))), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Ref, {
    innerRef: drag
  }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.List.Icon, {
    name: "bars",
    className: "drag-anchor"
  })), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Ref, {
    innerRef: preview
  }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.List.Content, null, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.List.Description, null, _get__default['default'](initialCreatibutor, 'person_or_org.identifiers', []).some(function (identifier) {
    return identifier.scheme === 'orcid';
  }) && /*#__PURE__*/React__default['default'].createElement("img", {
    className: "inline-orcid",
    src: "/static/images/orcid.svg"
  }), displayName, " ", renderRole(initialCreatibutor === null || initialCreatibutor === void 0 ? void 0 : initialCreatibutor.role, roleOptions)), firstError && /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Label, {
    pointing: "left",
    prompt: true
  }, firstError.scheme ? firstError.scheme : 'Invalid identifiers')))));
};

// This file is part of React-Invenio-Deposit
// Copyright (C) 2021 CERN.
// Copyright (C) 2021 Northwestern University.
//
// React-Invenio-Deposit is free software; you can redistribute it and/or modify it
// under the terms of the MIT License; see LICENSE file for more details.
function toCapitalCase(str) {
  return str[0].toUpperCase() + str.slice(1);
}
/**
 * Traverse the leaves (non-Object, non-Array values) of obj and execute func
 * on each.
 *
 * @param {object} obj - generic Object
 * @param {function} func - (leaf) => ... (identity by default)
 *
 */

function leafTraverse(obj) {
  var func = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (l) {
    return l;
  };

  if (typeof obj === "object") {
    // Objects and Arrays
    for (var key in obj) {
      leafTraverse(obj[key], func);
    }
  } else {
    func(obj);
  }
}
/**
 * Sort a list of string values (options).
 * @param {list} options
 * @returns
 */

function sortOptions(options) {
  return options.sort(function (o1, o2) {
    return o1.text.localeCompare(o2.text);
  });
}

var displayCreatibutorName = function displayCreatibutorName(_ref) {
  var familyName = _ref.familyName,
      givenName = _ref.givenName,
      affiliationName = _ref.affiliationName;
  var displayName = familyName;

  if (givenName) {
    displayName += ", ".concat(givenName);
  }

  if (affiliationName) {
    displayName += " (".concat(affiliationName, ")");
  }

  return displayName;
};

var CreatibutorsFieldForm = /*#__PURE__*/function (_Component) {
  _inherits(CreatibutorsFieldForm, _Component);

  var _super = _createSuper(CreatibutorsFieldForm);

  function CreatibutorsFieldForm() {
    _classCallCheck(this, CreatibutorsFieldForm);

    return _super.apply(this, arguments);
  }

  _createClass(CreatibutorsFieldForm, [{
    key: "render",
    value: function render() {
      var _this = this;

      var _this$props = this.props,
          _this$props$form = _this$props.form,
          values = _this$props$form.values,
          errors = _this$props$form.errors,
          initialErrors = _this$props$form.initialErrors,
          initialValues = _this$props$form.initialValues,
          formikArrayRemove = _this$props.remove,
          formikArrayReplace = _this$props.replace,
          formikArrayMove = _this$props.move,
          formikArrayPush = _this$props.push,
          fieldPath = _this$props.name,
          label = _this$props.label,
          labelIcon = _this$props.labelIcon,
          roleOptions = _this$props.roleOptions,
          schema = _this$props.schema;
      var formikValues = formik.getIn(values, fieldPath, []);
      var formikInitialValues = formik.getIn(initialValues, fieldPath, []);
      var error = formik.getIn(errors, fieldPath, null);
      var initialError = formik.getIn(initialErrors, fieldPath, null);
      var creatibutorsError = error || formikValues === formikInitialValues && initialError;
      return /*#__PURE__*/React__default['default'].createElement(reactDnd.DndProvider, {
        backend: reactDndHtml5Backend.HTML5Backend
      }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Form.Field, {
        required: schema === 'creators',
        className: creatibutorsError && 'error'
      }, /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.FieldLabel, {
        htmlFor: fieldPath,
        icon: labelIcon,
        label: label
      }), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.List, null, formik.getIn(values, fieldPath, []).map(function (value, index, array) {
        var _creatibutorsError$in, _creatibutorsError$in2;

        var key = "".concat(fieldPath, ".").concat(index);
        var personOrOrgPath = 'person_or_org';
        var typeFieldPath = "".concat(personOrOrgPath, ".type");
        var familyNameFieldPath = "".concat(personOrOrgPath, ".family_name");
        var givenNameFieldPath = "".concat(personOrOrgPath, ".given_name");
        var nameFieldPath = "".concat(personOrOrgPath, ".name");
        var affiliationsFieldPath = 'affiliations';
        var identifiersError = creatibutorsError && ((_creatibutorsError$in = creatibutorsError[index]) === null || _creatibutorsError$in === void 0 ? void 0 : (_creatibutorsError$in2 = _creatibutorsError$in.person_or_org) === null || _creatibutorsError$in2 === void 0 ? void 0 : _creatibutorsError$in2.identifiers); // Default to person type

        var isPerson = _get__default['default'](value, typeFieldPath, CREATIBUTOR_TYPE.PERSON) === CREATIBUTOR_TYPE.PERSON;
        var displayName = isPerson ? displayCreatibutorName({
          familyName: _get__default['default'](value, familyNameFieldPath, 'No family name'),
          givenName: _get__default['default'](value, givenNameFieldPath, 'No given name'),
          affiliationName: _get__default['default'](value, "".concat(affiliationsFieldPath, "[0].name"))
        }) : displayCreatibutorName({
          familyName: _get__default['default'](value, nameFieldPath, 'No organization name'),
          affiliationName: _get__default['default'](value, "".concat(affiliationsFieldPath, "[0].name"))
        });
        return /*#__PURE__*/React__default['default'].createElement(CreatibutorsFieldItem, {
          key: key,
          identifiersError: identifiersError,
          displayName: displayName,
          index: index,
          roleOptions: roleOptions,
          schema: schema,
          compKey: key,
          initialCreatibutor: value,
          removeCreatibutor: formikArrayRemove,
          replaceCreatibutor: formikArrayReplace,
          moveCreatibutor: formikArrayMove,
          addLabel: _this.props.modal.addLabel,
          editLabel: _this.props.modal.editLabel
        });
      }), /*#__PURE__*/React__default['default'].createElement(CreatibutorsModal, {
        onCreatibutorChange: function onCreatibutorChange(selectedCreatibutor) {
          formikArrayPush(selectedCreatibutor);
        },
        action: "add",
        addLabel: this.props.modal.addLabel,
        editLabel: this.props.modal.editLabel,
        roleOptions: sortOptions(roleOptions),
        schema: schema,
        trigger: /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Button, {
          type: "button"
        }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Icon, {
          name: "add"
        }), this.props.addButtonLabel)
      }), creatibutorsError && typeof creatibutorsError == 'string' && /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Label, {
        pointing: "left",
        prompt: true
      }, creatibutorsError))));
    }
  }]);

  return CreatibutorsFieldForm;
}(React.Component);

var CreatibutorsField = /*#__PURE__*/function (_Component2) {
  _inherits(CreatibutorsField, _Component2);

  var _super2 = _createSuper(CreatibutorsField);

  function CreatibutorsField() {
    _classCallCheck(this, CreatibutorsField);

    return _super2.apply(this, arguments);
  }

  _createClass(CreatibutorsField, [{
    key: "render",
    value: function render() {
      var _this2 = this;

      return /*#__PURE__*/React__default['default'].createElement(formik.FieldArray, {
        name: this.props.fieldPath,
        component: function component(formikProps) {
          return /*#__PURE__*/React__default['default'].createElement(CreatibutorsFieldForm, Object.assign({}, formikProps, _this2.props));
        }
      });
    }
  }]);

  return CreatibutorsField;
}(React.Component);
CreatibutorsField.defaultProps = {
  modal: {
    addLabel: 'Add creator',
    editLabel: 'Edit creator'
  },
  addButtonLabel: i18next.t('Add creator')
};

var DatesField = /*#__PURE__*/function (_Component) {
  _inherits(DatesField, _Component);

  var _super = _createSuper(DatesField);

  function DatesField() {
    _classCallCheck(this, DatesField);

    return _super.apply(this, arguments);
  }

  _createClass(DatesField, [{
    key: "render",
    value:
    /** Top-level Dates Component */
    function render() {
      var _this$props = this.props,
          fieldPath = _this$props.fieldPath,
          options = _this$props.options,
          label = _this$props.label,
          labelIcon = _this$props.labelIcon,
          placeholderDate = _this$props.placeholderDate,
          required = _this$props.required;
      return /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.ArrayField, {
        addButtonLabel: i18next.t('Add date') // TODO: Pass by prop
        ,
        defaultNewValue: emptyDate,
        fieldPath: fieldPath,
        helpText: i18next.t('Format: DATE or DATE/DATE where DATE is YYYY or YYYY-MM or YYYY-MM-DD.'),
        label: label,
        labelIcon: labelIcon,
        required: required
      }, function (_ref) {
        _ref.array;
            var arrayHelpers = _ref.arrayHelpers,
            indexPath = _ref.indexPath,
            key = _ref.key;
            _ref.form;
        return /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.GroupField, {
          fieldPath: fieldPath,
          optimized: true
        }, /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.TextField, {
          fieldPath: "".concat(key, ".date"),
          label: i18next.t('Date'),
          placeholder: placeholderDate,
          required: true,
          width: 5
        }), /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.SelectField, {
          fieldPath: "".concat(key, ".type"),
          label: i18next.t('Type'),
          options: sortOptions(options.type),
          required: true,
          width: 5,
          optimized: true
        }), /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.TextField, {
          fieldPath: "".concat(key, ".description"),
          label: i18next.t('Description'),
          width: 5
        }), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Form.Field, {
          width: 1
        }, /*#__PURE__*/React__default['default'].createElement("label", null, "\xA0"), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Button, {
          icon: true,
          onClick: function onClick() {
            return arrayHelpers.remove(indexPath);
          },
          type: "button"
        }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Icon, {
          name: "close"
        }))));
      });
    }
  }]);

  return DatesField;
}(React.Component);
DatesField.defaultProps = {
  fieldPath: 'metadata.dates',
  label: i18next.t('Dates'),
  labelIcon: 'calendar',
  placeholderDate: i18next.t('YYYY-MM-DD or YYYY-MM-DD/YYYY-MM-DD')
};

var _excluded$5 = ["isSaved", "isPublished", "deleteClick", "isVersion"];

var DISCARD_CHANGES = i18next.t('discard changes');
var DISCARD_VERSION = i18next.t('discard version');
var DELETE = i18next.t('delete'); // action messages

var DISCARD_CHANGES_MSG = i18next.t('Are you sure you want to discard the changes to this draft?');
var DISCARD_VERSION_MSG = i18next.t('Are you sure you want to delete this new version?');
var DISCARD_DELETE_MSG = i18next.t('Are you sure you want to delete this draft?');

var DialogText = function DialogText(_ref) {
  var action = _ref.action;
  var text = '';

  switch (action) {
    case DISCARD_CHANGES:
      text = DISCARD_CHANGES_MSG;
      break;

    case DISCARD_VERSION:
      text = DISCARD_VERSION_MSG;
      break;

    case DELETE:
      text = DISCARD_DELETE_MSG;
      break;
  }

  return text;
};

var DeleteButtonComponent = /*#__PURE__*/function (_Component) {
  _inherits(DeleteButtonComponent, _Component);

  var _super = _createSuper(DeleteButtonComponent);

  function DeleteButtonComponent() {
    var _this;

    _classCallCheck(this, DeleteButtonComponent);

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

    _this = _super.call.apply(_super, [this].concat(args));
    _this.state = {
      modalOpen: false,
      isDeleting: false
    };

    _this.handleOpen = function () {
      return _this.setState({
        modalOpen: true
      });
    };

    _this.handleClose = function () {
      return _this.setState({
        modalOpen: false
      });
    };

    _this.isDisabled = function (formik) {
      var isDeleting = _this.state.isDeleting;
      return !_this.props.isSaved || formik.isSubmitting || isDeleting;
    };

    return _this;
  }

  _createClass(DeleteButtonComponent, [{
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$props = this.props;
          _this$props.isSaved;
          var isPublished = _this$props.isPublished,
          deleteClick = _this$props.deleteClick;
          _this$props.isVersion;
          var uiProps = _objectWithoutProperties(_this$props, _excluded$5);

      var isDeleting = this.state.isDeleting;

      var handleDelete = function handleDelete(event, formik) {
        _this2.setState({
          isDeleting: true
        });

        deleteClick(event, formik).then(function () {
          _this2.setState({
            isDeleting: false
          });
        });

        _this2.handleClose();
      };

      var action = '';

      if (!this.props.isPublished) {
        action = this.props.isVersion ? DISCARD_VERSION : DELETE;
      } else {
        action = DISCARD_CHANGES;
      }

      var color = {
        color: isPublished ? 'yellow' : 'red'
      };
      var capitalizedAction = toCapitalCase(action);
      return /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.ActionButton, Object.assign({
        isDisabled: this.isDisabled,
        name: "delete",
        onClick: this.handleOpen
      }, color, {
        icon: true,
        labelPosition: "left"
      }, uiProps), function (formik) {
        return /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, formik.isSubmitting && isDeleting ? /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Icon, {
          size: "large",
          loading: true,
          name: "spinner"
        }) : /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Icon, {
          name: "trash alternate outline"
        }), capitalizedAction);
      }), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Modal, {
        open: this.state.modalOpen,
        onClose: this.handleClose,
        size: "tiny"
      }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Modal.Content, null, /*#__PURE__*/React__default['default'].createElement("h3", null, /*#__PURE__*/React__default['default'].createElement(DialogText, {
        action: action
      }))), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Modal.Actions, null, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Button, {
        onClick: this.handleClose,
        floated: "left"
      }, "Cancel"), /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.ActionButton, Object.assign({}, color, {
        name: "delete",
        onClick: handleDelete,
        content: capitalizedAction
      })))));
    }
  }]);

  return DeleteButtonComponent;
}(React.Component);

var mapStateToProps$7 = function mapStateToProps(state) {
  var _state$deposit$record;

  return {
    isSaved: Boolean(state.deposit.record.id),
    isPublished: state.deposit.record.is_published,
    isVersion: ((_state$deposit$record = state.deposit.record.versions) === null || _state$deposit$record === void 0 ? void 0 : _state$deposit$record.index) > 1
  };
};

var mapDispatchToProps$5 = function mapDispatchToProps(dispatch) {
  return {
    deleteClick: function deleteClick(event, formik) {
      return dispatch(discard(event, formik));
    }
  };
};

var DeleteButton = reactRedux.connect(mapStateToProps$7, mapDispatchToProps$5)(DeleteButtonComponent);

var DepositFormTitleComponent = /*#__PURE__*/function (_Component) {
  _inherits(DepositFormTitleComponent, _Component);

  var _super = _createSuper(DepositFormTitleComponent);

  function DepositFormTitleComponent() {
    _classCallCheck(this, DepositFormTitleComponent);

    return _super.apply(this, arguments);
  }

  _createClass(DepositFormTitleComponent, [{
    key: "render",
    value: function render() {
      var content = '';

      if (!this.props.isPublished) {
        content = this.props.isVersion ? i18next.t('New version') : i18next.t('New upload');
      } else {
        content = i18next.t('Edit upload');
      }

      return /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Header, {
        as: "h1",
        icon: "upload",
        content: content
      });
    }
  }]);

  return DepositFormTitleComponent;
}(React.Component);

var mapStateToProps$6 = function mapStateToProps(state) {
  var _state$deposit$record;

  return {
    isPublished: state.deposit.record.is_published,
    isVersion: ((_state$deposit$record = state.deposit.record.versions) === null || _state$deposit$record === void 0 ? void 0 : _state$deposit$record.index) > 1
  };
};

var DepositFormTitle = reactRedux.connect(mapStateToProps$6, null)(DepositFormTitleComponent);

var AdditionalDescriptionsField = /*#__PURE__*/function (_Component) {
  _inherits(AdditionalDescriptionsField, _Component);

  var _super = _createSuper(AdditionalDescriptionsField);

  function AdditionalDescriptionsField() {
    _classCallCheck(this, AdditionalDescriptionsField);

    return _super.apply(this, arguments);
  }

  _createClass(AdditionalDescriptionsField, [{
    key: "render",
    value: function render() {
      var _this$props = this.props,
          fieldPath = _this$props.fieldPath,
          options = _this$props.options,
          recordUI = _this$props.recordUI;
      return /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.ArrayField, {
        addButtonLabel: i18next.t('Add description'),
        defaultNewValue: emptyAdditionalDescription,
        fieldPath: fieldPath,
        className: "additional-descriptions"
      }, function (_ref) {
        var _recordUI$additional_;

        _ref.array;
            var arrayHelpers = _ref.arrayHelpers,
            indexPath = _ref.indexPath,
            key = _ref.key;
        return /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Grid, {
          relaxed: true
        }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Grid.Row, null, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Grid.Column, {
          width: 12
        }, /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.RichInputField, {
          fieldPath: "".concat(key, ".description"),
          label: i18next.t('Additional Description'),
          optimized: true,
          required: true
        })), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Grid.Column, {
          width: 4
        }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Form.Field, null, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Button, {
          floated: "right",
          icon: true,
          onClick: function onClick() {
            return arrayHelpers.remove(indexPath);
          }
        }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Icon, {
          name: "close"
        }))), /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.SelectField, {
          fieldPath: "".concat(key, ".type"),
          label: i18next.t('Type'),
          options: sortOptions(options.type),
          required: true,
          optimized: true
        }), /*#__PURE__*/React__default['default'].createElement(LanguagesField, {
          serializeSuggestions: function serializeSuggestions(suggestions) {
            return suggestions.map(function (item) {
              return {
                text: item.title_l10n,
                value: item.id,
                key: item.id
              };
            });
          },
          initialOptions: (recordUI === null || recordUI === void 0 ? void 0 : recordUI.additional_descriptions) && ((_recordUI$additional_ = recordUI.additional_descriptions[indexPath]) === null || _recordUI$additional_ === void 0 ? void 0 : _recordUI$additional_.lang) ? [recordUI.additional_descriptions[indexPath].lang] : [],
          fieldPath: "".concat(key, ".lang"),
          label: i18next.t('Language'),
          multiple: false,
          placeholder: i18next.t('Select language'),
          labelIcon: null,
          clearable: true,
          selectOnBlur: false
        })))));
      });
    }
  }]);

  return AdditionalDescriptionsField;
}(React.Component);
AdditionalDescriptionsField.defaultProps = {
  fieldPath: 'metadata.additional_descriptions',
  recordUI: {}
};

var DescriptionsField = /*#__PURE__*/function (_Component) {
  _inherits(DescriptionsField, _Component);

  var _super = _createSuper(DescriptionsField);

  function DescriptionsField() {
    _classCallCheck(this, DescriptionsField);

    return _super.apply(this, arguments);
  }

  _createClass(DescriptionsField, [{
    key: "render",
    value: function render() {
      var _this$props = this.props,
          fieldPath = _this$props.fieldPath,
          label = _this$props.label,
          labelIcon = _this$props.labelIcon,
          options = _this$props.options,
          editorConfig = _this$props.editorConfig,
          recordUI = _this$props.recordUI;
      return /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.RichInputField, {
        fieldPath: fieldPath,
        editorConfig: editorConfig,
        label: /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.FieldLabel, {
          htmlFor: fieldPath,
          icon: labelIcon,
          label: label
        }),
        optimized: true
      }), /*#__PURE__*/React__default['default'].createElement(AdditionalDescriptionsField, {
        recordUI: recordUI,
        options: options
      }));
    }
  }]);

  return DescriptionsField;
}(React.Component);
DescriptionsField.defaultProps = {
  fieldPath: 'metadata.description',
  label: i18next.t('Description'),
  labelIcon: 'pencil',
  editorConfig: {},
  recordUI: {}
};

var apiConfig = {
  withCredentials: true,
  xsrfCookieName: 'csrftoken',
  xsrfHeaderName: 'X-CSRFToken'
};
var axiosWithconfig = axios__default['default'].create(apiConfig);
var NewVersionButton = function NewVersionButton(props) {
  var _useState = React.useState(false),
      _useState2 = _slicedToArray(_useState, 2),
      loading = _useState2[0],
      setLoading = _useState2[1];

  var handleError = props.onError;

  var handleClick = function handleClick() {
    setLoading(true);
    axiosWithconfig.post(props.record.links.versions).then(function (response) {
      window.location = response.data.links.self_html;
    }).catch(function (error) {
      setLoading(false);
      handleError(error.response.data.message);
    });
  };

  return /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Popup, {
    content: i18next.t("You don't have permissions to create a new version."),
    disabled: !props.disabled,
    trigger: /*#__PURE__*/React__default['default'].createElement("div", {
      style: _objectSpread2({
        display: 'inline-block'
      }, props.style)
    }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Button, {
      disabled: props.disabled,
      type: "button",
      color: "green",
      size: "mini",
      onClick: handleClick,
      loading: loading
    }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Icon, {
      name: "tag"
    }), i18next.t('New version')))
  });
};

// This file is part of React-Invenio-Deposit
function humanReadableBytes(bytes) {
  if (_isNumber__default['default'](bytes)) {
    var kiloBytes = 1000;
    var megaBytes = 1000 * kiloBytes;
    var gigaBytes = 1000 * megaBytes;

    if (bytes < kiloBytes) {
      return /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, bytes, " bytes");
    } else if (bytes < megaBytes) {
      return /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, (bytes / kiloBytes).toFixed(2), " Kb");
    } else if (bytes < gigaBytes) {
      return /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, (bytes / megaBytes).toFixed(2), " Mb");
    } else {
      return /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, (bytes / gigaBytes).toFixed(2), " Gb");
    }
  }

  return '';
}

var FileTableHeader = function FileTableHeader(_ref) {
  var isDraftRecord = _ref.isDraftRecord;
  return /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Table.Header, null, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Table.Row, {
    className: "file-table-row"
  }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Table.HeaderCell, {
    className: "file-table-header-cell"
  }, i18next.t('Preview'), ' ', /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Popup, {
    content: "Set the default preview",
    trigger: /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Icon, {
      fitted: true,
      name: "help circle",
      size: "small"
    })
  })), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Table.HeaderCell, {
    className: "file-table-header-cell"
  }, i18next.t('Filename')), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Table.HeaderCell, {
    className: "file-table-header-cell"
  }, i18next.t('Size')), isDraftRecord && /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Table.HeaderCell, {
    textAlign: "center",
    className: "file-table-header-cell"
  }, i18next.t('Progress')), isDraftRecord && /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Table.HeaderCell, {
    className: "file-table-header-cell"
  })));
};

var FileTableRow = function FileTableRow(_ref2) {
  var _file$upload, _file$upload2;

  var isDraftRecord = _ref2.isDraftRecord,
      file = _ref2.file,
      deleteFileFromRecord = _ref2.deleteFileFromRecord,
      defaultPreview = _ref2.defaultPreview,
      setDefaultPreview = _ref2.setDefaultPreview;
  var isDefaultPreview = defaultPreview === file.name;

  var handleDelete = function handleDelete(file) {
    deleteFileFromRecord(file).then(function () {
      if (isDefaultPreview) {
        setDefaultPreview('');
      }
    });
  };

  return /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Table.Row, {
    key: file.name,
    className: "file-table-row"
  }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Table.Cell, {
    className: "file-table-cell",
    width: 2
  }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Checkbox, {
    checked: isDefaultPreview,
    onChange: function onChange() {
      return setDefaultPreview(isDefaultPreview ? '' : file.name);
    }
  })), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Table.Cell, {
    className: "file-table-cell",
    width: 10
  }, file.upload.pending ? file.name : /*#__PURE__*/React__default['default'].createElement("a", {
    href: _get__default['default'](file, 'links.content', ''),
    target: "_blank",
    rel: "noopener noreferrer"
  }, file.name), /*#__PURE__*/React__default['default'].createElement("br", null), file.checksum && /*#__PURE__*/React__default['default'].createElement("div", {
    className: "ui text-muted"
  }, /*#__PURE__*/React__default['default'].createElement("span", {
    style: {
      fontSize: '10px'
    }
  }, file.checksum), ' ', /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Popup, {
    content: i18next.t('This is the file fingerprint (MD5 checksum), which can be used to verify the file integrity.'),
    trigger: /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Icon, {
      fitted: true,
      name: "help circle",
      size: "small"
    }),
    position: "top center"
  }))), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Table.Cell, {
    className: "file-table-cell",
    width: 2
  }, file.size ? humanReadableBytes(file.size) : ''), isDraftRecord && /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Table.Cell, {
    className: "file-table-cell file-upload-pending",
    width: 2
  }, !((_file$upload = file.upload) === null || _file$upload === void 0 ? void 0 : _file$upload.pending) && /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Progress, {
    className: "file-upload-progress",
    percent: file.upload.progress,
    error: file.upload.failed,
    size: "medium",
    color: "blue",
    progress: true,
    autoSuccess: true,
    active: !file.upload.initial,
    disabled: file.upload.initial
  }), ((_file$upload2 = file.upload) === null || _file$upload2 === void 0 ? void 0 : _file$upload2.pending) && /*#__PURE__*/React__default['default'].createElement("span", null, i18next.t('Pending'))), isDraftRecord && /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Table.Cell, {
    textAlign: "right",
    width: 2,
    className: "file-table-cell"
  }, file.upload && !(file.upload.ongoing || file.upload.initial) && /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Icon, {
    link: true,
    className: "action",
    name: "trash alternate outline",
    color: "blue",
    onClick: function onClick() {
      return handleDelete(file);
    }
  }), file.upload && file.upload.ongoing && /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Button, {
    compact: true,
    type: "button",
    negative: true,
    size: "tiny",
    onClick: function onClick() {
      return file.upload.cancel();
    }
  }, i18next.t('Cancel'))));
};

var FileUploadBox = function FileUploadBox(_ref3) {
  var isDraftRecord = _ref3.isDraftRecord,
      filesList = _ref3.filesList,
      dragText = _ref3.dragText,
      uploadButtonIcon = _ref3.uploadButtonIcon,
      uploadButtonText = _ref3.uploadButtonText,
      openFileDialog = _ref3.openFileDialog;
  return isDraftRecord && /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Segment, {
    basic: true,
    padded: "very",
    className: filesList.length ? 'file-upload-area' : 'file-upload-area no-files'
  }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Grid, {
    columns: 3,
    textAlign: "center"
  }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Grid.Row, {
    verticalAlign: "middle"
  }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Grid.Column, {
    width: "7"
  }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Header, {
    size: "small"
  }, dragText)), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Grid.Column, {
    width: "2"
  }, "- ", i18next.t('or'), " -"), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Grid.Column, {
    width: "7"
  }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Button, {
    type: "button",
    primary: true,
    icon: uploadButtonIcon,
    content: uploadButtonText,
    onClick: function onClick() {
      return openFileDialog();
    },
    disabled: openFileDialog === null
  })))));
};

var FilesListTable = function FilesListTable(_ref4) {
  var isDraftRecord = _ref4.isDraftRecord,
      filesList = _ref4.filesList,
      deleteFileFromRecord = _ref4.deleteFileFromRecord;

  var _useFormikContext = formik.useFormikContext(),
      setFieldValue = _useFormikContext.setFieldValue,
      formikDraft = _useFormikContext.values;

  var defaultPreview = _get__default['default'](formikDraft, 'files.default_preview', '');

  return /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Table, null, /*#__PURE__*/React__default['default'].createElement(FileTableHeader, {
    isDraftRecord: isDraftRecord
  }), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Table.Body, null, filesList.map(function (file) {
    return /*#__PURE__*/React__default['default'].createElement(FileTableRow, {
      key: file.name,
      isDraftRecord: isDraftRecord,
      file: file,
      deleteFileFromRecord: deleteFileFromRecord,
      defaultPreview: defaultPreview,
      setDefaultPreview: function setDefaultPreview(filename) {
        return setFieldValue('files.default_preview', filename);
      }
    });
  })));
};

var FileUploaderArea = /*#__PURE__*/function (_Component) {
  _inherits(FileUploaderArea, _Component);

  var _super = _createSuper(FileUploaderArea);

  function FileUploaderArea() {
    _classCallCheck(this, FileUploaderArea);

    return _super.apply(this, arguments);
  }

  _createClass(FileUploaderArea, [{
    key: "render",
    value: function render() {
      var _this = this;

      var _this$props = this.props,
          filesEnabled = _this$props.filesEnabled,
          dropzoneParams = _this$props.dropzoneParams,
          filesList = _this$props.filesList;
      return filesEnabled ? /*#__PURE__*/React__default['default'].createElement(Dropzone__default['default'], dropzoneParams, function (_ref5) {
        var getRootProps = _ref5.getRootProps,
            getInputProps = _ref5.getInputProps,
            openFileDialog = _ref5.open;
        return /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Grid.Column, {
          width: 16
        }, /*#__PURE__*/React__default['default'].createElement("span", getRootProps(), /*#__PURE__*/React__default['default'].createElement("input", getInputProps()), filesList.length !== 0 && /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Grid.Column, {
          verticalAlign: "middle"
        }, /*#__PURE__*/React__default['default'].createElement(FilesListTable, _this.props)), /*#__PURE__*/React__default['default'].createElement(FileUploadBox, Object.assign({}, _this.props, {
          openFileDialog: openFileDialog
        }))));
      }) : /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Grid.Column, {
        width: 16
      }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Segment, {
        basic: true,
        padded: "very",
        className: "file-upload-area no-files"
      }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Grid, {
        textAlign: "center"
      }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Grid.Row, {
        verticalAlign: "middle"
      }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Grid.Column, null, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Header, {
        size: "medium"
      }, i18next.t('This is a Metadata only record')))))));
    }
  }]);

  return FileUploaderArea;
}(React.Component);

// This file is part of React-Invenio-Deposit
//       the `useFormikContext` hook.

var FileUploaderToolbar = function FileUploaderToolbar(_ref) {
  var config = _ref.config,
      filesList = _ref.filesList,
      filesSize = _ref.filesSize,
      filesEnabled = _ref.filesEnabled,
      quota = _ref.quota;

  var _useFormikContext = formik.useFormikContext(),
      setFieldValue = _useFormikContext.setFieldValue;

  return /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Grid.Column, {
    verticalAlign: "middle",
    floated: "left",
    width: 6
  }, config.canHaveMetadataOnlyRecords && /*#__PURE__*/React__default['default'].createElement(semanticUiReact.List, {
    horizontal: true
  }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.List.Item, null, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Checkbox, {
    label: i18next.t('Metadata-only record'),
    onChange: function onChange() {
      return setFieldValue('files.enabled', !filesEnabled);
    },
    disabled: filesList.length > 0,
    checked: !filesEnabled
  })), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.List.Item, {
    style: {
      marginLeft: '5px'
    }
  }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Popup, {
    trigger: /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Icon, {
      name: "question circle outline",
      color: "grey"
    }),
    content: "Disable files for this record",
    position: "top center"
  })))), filesEnabled && /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Grid.Column, {
    width: 10
  }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.List, {
    horizontal: true,
    floated: "right"
  }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.List.Item, null, i18next.t('Storage available')), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.List.Item, null, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Label, filesList.length === quota.maxFiles ? {
    color: 'blue'
  } : {}, i18next.t("{{length}} out of {{maxfiles}} files", {
    length: filesList.length,
    maxfiles: quota.maxFiles
  }))), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.List.Item, null, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Label, humanReadableBytes(filesSize) === humanReadableBytes(quota.maxStorage) ? {
    color: 'blue'
  } : {}, humanReadableBytes(filesSize), " ", i18next.t('out of'), ' ', humanReadableBytes(quota.maxStorage))))));
};

var _excluded$4 = ["config", "files", "isDraftRecord", "hasParentRecord", "quota", "permissions", "record", "uploadFilesToDraft", "importRecordFilesToDraft", "importButtonIcon", "importButtonText", "isFileImportInProgress"];
//       the `useFormikContext` hook.

var FileUploaderComponent = function FileUploaderComponent(_ref) {
  var config = _ref.config,
      files = _ref.files,
      isDraftRecord = _ref.isDraftRecord,
      hasParentRecord = _ref.hasParentRecord,
      quota = _ref.quota,
      permissions = _ref.permissions,
      record = _ref.record,
      uploadFilesToDraft = _ref.uploadFilesToDraft,
      importRecordFilesToDraft = _ref.importRecordFilesToDraft,
      importButtonIcon = _ref.importButtonIcon,
      importButtonText = _ref.importButtonText,
      isFileImportInProgress = _ref.isFileImportInProgress,
      uiProps = _objectWithoutProperties(_ref, _excluded$4);

  // We extract the working copy of the draft stored as `values` in formik
  var _useFormikContext = formik.useFormikContext(),
      formikDraft = _useFormikContext.values;

  var filesEnabled = _get__default['default'](formikDraft, 'files.enabled', false);

  var _useState = React.useState(),
      _useState2 = _slicedToArray(_useState, 2),
      warningMsg = _useState2[0],
      setWarningMsg = _useState2[1];

  var filesList = Object.values(files).map(function (fileState) {
    return {
      name: fileState.name,
      size: fileState.size,
      checksum: fileState.checksum,
      links: fileState.links,
      upload: {
        initial: fileState.status === UploadState.initial,
        failed: fileState.status === UploadState.error,
        ongoing: fileState.status === UploadState.uploading,
        finished: fileState.status === UploadState.finished,
        pending: fileState.status === UploadState.pending,
        progress: fileState.progress,
        cancel: fileState.cancel
      }
    };
  });
  var filesSize = filesList.reduce(function (totalSize, file) {
    return totalSize += file.size;
  }, 0);
  var dropzoneParams = {
    preventDropOnDocument: true,
    onDropAccepted: function onDropAccepted(acceptedFiles) {
      var maxFileNumberReached = filesList.length + acceptedFiles.length > quota.maxFiles;
      var acceptedFilesSize = acceptedFiles.reduce(function (totalSize, file) {
        return totalSize += file.size;
      }, 0);
      var maxFileStorageReached = filesSize + acceptedFilesSize > quota.maxStorage;

      if (maxFileNumberReached) {
        setWarningMsg( /*#__PURE__*/React__default['default'].createElement("div", {
          className: "content"
        }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Message, {
          warning: true,
          icon: "warning circle",
          header: "Could not upload files.",
          content: "Uploading the selected files would result in ".concat(filesList.length + acceptedFiles.length, " files (max.").concat(quota.maxFiles, ")")
        })));
      } else if (maxFileStorageReached) {
        setWarningMsg( /*#__PURE__*/React__default['default'].createElement("div", {
          className: "content"
        }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Message, {
          warning: true,
          icon: "warning circle",
          header: "Could not upload file(s).",
          content: /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, i18next.t('Uploading the selected files would result in'), ' ', humanReadableBytes(filesSize + acceptedFilesSize), i18next.t('but the limit is'), humanReadableBytes(quota.maxStorage), ".")
        })));
      } else {
        uploadFilesToDraft(formikDraft, acceptedFiles);
      }
    },
    multiple: true,
    noClick: true,
    noKeyboard: true,
    disabled: false
  };
  var filesLeft = filesList.length < quota.maxFiles;

  if (!filesLeft) {
    dropzoneParams['disabled'] = true;
  }

  var displayImportBtn = filesEnabled && isDraftRecord && hasParentRecord && !filesList.length;
  return /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Grid, {
    style: {
      marginBottom: '20px'
    }
  }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Grid.Row, null, isDraftRecord && /*#__PURE__*/React__default['default'].createElement(FileUploaderToolbar, Object.assign({}, uiProps, {
    config: config,
    filesEnabled: filesEnabled,
    filesList: filesList,
    filesSize: filesSize,
    isDraftRecord: isDraftRecord,
    quota: quota
  }))), displayImportBtn && /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Grid.Row, {
    className: "file-import-note-row"
  }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Grid.Column, {
    width: 16
  }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Message, {
    visible: true,
    info: true
  }, /*#__PURE__*/React__default['default'].createElement("div", {
    style: {
      display: 'inline-block',
      float: 'right'
    }
  }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Button, {
    type: "button",
    size: "mini",
    primary: true,
    icon: importButtonIcon,
    content: importButtonText,
    onClick: function onClick() {
      return importRecordFilesToDraft();
    },
    disabled: isFileImportInProgress,
    loading: isFileImportInProgress
  })), /*#__PURE__*/React__default['default'].createElement("p", {
    style: {
      marginTop: '5px',
      display: 'inline-block'
    }
  }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Icon, {
    name: "info circle"
  }), i18next.t('You can import files from the previous version.'))))), filesEnabled && /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Grid.Row, {
    className: "file-upload-area-row"
  }, /*#__PURE__*/React__default['default'].createElement(FileUploaderArea, Object.assign({}, uiProps, {
    filesList: filesList,
    dropzoneParams: dropzoneParams,
    isDraftRecord: isDraftRecord,
    filesEnabled: filesEnabled
  }))), isDraftRecord ? /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Grid.Row, {
    className: "file-upload-note-row"
  }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Grid.Column, {
    width: 16
  }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Message, {
    visible: true,
    warning: true
  }, /*#__PURE__*/React__default['default'].createElement("p", null, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Icon, {
    name: "warning sign"
  }), i18next.t('File addition, removal or modification are not allowed after you have published your upload.'))))) : /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Grid.Row, {
    className: "file-upload-note-row"
  }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Grid.Column, {
    width: 16
  }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Message, {
    info: true
  }, /*#__PURE__*/React__default['default'].createElement(NewVersionButton, {
    record: record,
    onError: function onError() {},
    className: "",
    disabled: !permissions.can_new_version,
    style: {
      float: 'right'
    }
  }), /*#__PURE__*/React__default['default'].createElement("p", {
    style: {
      marginTop: '5px',
      display: 'inline-block'
    }
  }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Icon, {
    name: "info circle",
    size: "large"
  }), i18next.t('You must create a new version to add, modify or delete files.')))))), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Modal, {
    open: !!warningMsg,
    header: "Warning!",
    content: warningMsg,
    onClose: function onClose() {
      return setWarningMsg();
    },
    closeIcon: true
  }));
};
FileUploaderComponent.defaultProps = {
  dragText: i18next.t('Drag and drop file(s)'),
  isDraftRecord: true,
  hasParentRecord: false,
  quota: {
    maxFiles: 5,
    maxStorage: Math.pow(10, 10)
  },
  uploadButtonIcon: 'upload',
  uploadButtonText: i18next.t('Upload files'),
  importButtonIcon: 'sync',
  importButtonText: i18next.t('Import files')
};

// This file is part of React-Invenio-Deposit

var mapStateToProps$5 = function mapStateToProps(state) {
  var _state$deposit$record, _state$deposit$record2, _state$deposit$record3, _state$deposit$record4;

  var _state$files = state.files,
      links = _state$files.links,
      entries = _state$files.entries;
  return {
    files: entries,
    links: links,
    record: state.deposit.record,
    config: state.deposit.config,
    permissions: state.deposit.permissions,
    isFileImportInProgress: state.files.isFileImportInProgress,
    hasParentRecord: Boolean(((_state$deposit$record = state.deposit.record) === null || _state$deposit$record === void 0 ? void 0 : (_state$deposit$record2 = _state$deposit$record.versions) === null || _state$deposit$record2 === void 0 ? void 0 : _state$deposit$record2.index) && ((_state$deposit$record3 = state.deposit.record) === null || _state$deposit$record3 === void 0 ? void 0 : (_state$deposit$record4 = _state$deposit$record3.versions) === null || _state$deposit$record4 === void 0 ? void 0 : _state$deposit$record4.index) > 1)
  };
};

var mapDispatchToProps$4 = function mapDispatchToProps(dispatch) {
  return {
    uploadFilesToDraft: function uploadFilesToDraft(draft, files) {
      return dispatch(uploadDraftFiles(draft, files));
    },
    importRecordFilesToDraft: function importRecordFilesToDraft() {
      return dispatch(importParentRecordFiles());
    },
    deleteFileFromRecord: function deleteFileFromRecord(file) {
      return dispatch(deleteDraftFile(file));
    }
  };
};

var FileUploader = reactRedux.connect(mapStateToProps$5, mapDispatchToProps$4)(FileUploaderComponent);

var defaultLabels = {
  'files.enabled': i18next.t('Files'),
  'metadata.resource_type': i18next.t('Resource type'),
  'metadata.title': i18next.t('Title'),
  'metadata.additional_titles': i18next.t('Additional titles'),
  'metadata.publication_date': i18next.t('Publication date'),
  'metadata.creators': i18next.t('Creators'),
  'metadata.contributors': i18next.t('Contributors'),
  'metadata.description': i18next.t('Description'),
  'metadata.additional_descriptions': i18next.t('Additional descriptions'),
  'metadata.rights': i18next.t('Licenses'),
  'metadata.languages': i18next.t('Languages'),
  'metadata.dates': i18next.t('Dates'),
  'metadata.version': i18next.t('Version'),
  'metadata.publisher': i18next.t('Publisher'),
  'metadata.related_identifiers': i18next.t('Related works'),
  'metadata.identifiers': i18next.t('Alternate identifiers'),
  'access.embargo.until': i18next.t('Embargo until')
};

var DisconnectedFormFeedback = /*#__PURE__*/function (_Component) {
  _inherits(DisconnectedFormFeedback, _Component);

  var _super = _createSuper(DisconnectedFormFeedback);

  function DisconnectedFormFeedback(props) {
    var _this;

    _classCallCheck(this, DisconnectedFormFeedback);

    _this = _super.call(this, props);
    _this.labels = _objectSpread2(_objectSpread2({}, defaultLabels), props.labels);
    return _this;
  }
  /**
   * Render error messages inline (if 1) or as list (if multiple).
   *
   * @param {Array<String>} messages
   * @returns String or React node
   */


  _createClass(DisconnectedFormFeedback, [{
    key: "renderErrorMessages",
    value: function renderErrorMessages(messages) {
      var uniqueMessages = _toConsumableArray(new Set(messages));

      if (uniqueMessages.length === 1) {
        return messages[0];
      } else {
        return /*#__PURE__*/React__default['default'].createElement("ul", null, uniqueMessages.map(function (m, i) {
          return /*#__PURE__*/React__default['default'].createElement("li", {
            key: i
          }, m);
        }));
      }
    }
    /**
     * Return array of error messages from errorValue object.
     *
     * The error message(s) might be deeply nested in the errorValue e.g.
     *
     * errorValue = [
     *   {
     *     title: "Missing value"
     *   }
     * ];
     *
     * @param {object} errorValue
     * @returns array of Strings (error messages)
     */

  }, {
    key: "toErrorMessages",
    value: function toErrorMessages(errorValue) {
      var messages = [];

      var store = function store(l) {
        messages.push(l);
      };

      leafTraverse(errorValue, store);
      return messages;
    }
    /**
     * Return object with human readbable labels as keys and error messages as
     * values given an errors object.
     *
     * @param {object} errors
     * @returns object
     */

  }, {
    key: "toLabelledErrorMessages",
    value: function toLabelledErrorMessages(errors) {
      var _errors$access,
          _this2 = this;

      // Step 0 - Create object with collapsed 1st and 2nd level keys
      //          e.g., {metadata: {creators: ,,,}} => {"metadata.creators": ...}
      // For now, only for metadata, files and access.embargo
      var metadata = errors.metadata || {};
      var step0_metadata = Object.entries(metadata).map(function (_ref) {
        var _ref2 = _slicedToArray(_ref, 2),
            key = _ref2[0],
            value = _ref2[1];

        return ['metadata.' + key, value];
      });
      var files = errors.files || {};
      var step0_files = Object.entries(files).map(function (_ref3) {
        var _ref4 = _slicedToArray(_ref3, 2),
            key = _ref4[0],
            value = _ref4[1];

        return ['files.' + key, value];
      });
      var access = ((_errors$access = errors.access) === null || _errors$access === void 0 ? void 0 : _errors$access.embargo) || {};
      var step0_access = Object.entries(access).map(function (_ref5) {
        var _ref6 = _slicedToArray(_ref5, 2),
            key = _ref6[0],
            value = _ref6[1];

        return ['access.embargo.' + key, value];
      });
      var step0 = Object.fromEntries(step0_metadata.concat(step0_files).concat(step0_access)); // Step 1 - Transform each error value into array of error messages

      var step1 = Object.fromEntries(Object.entries(step0).map(function (_ref7) {
        var _ref8 = _slicedToArray(_ref7, 2),
            key = _ref8[0],
            value = _ref8[1];

        return [key, _this2.toErrorMessages(value)];
      })); // Step 2 - Group error messages by label
      // (different error keys can map to same label e.g. title and
      // additional_titles)

      var labelledErrorMessages = {};

      for (var key in step1) {
        var label = this.labels[key] || 'Unknown field';
        var messages = labelledErrorMessages[label] || [];
        labelledErrorMessages[label] = messages.concat(step1[key]);
      }

      return labelledErrorMessages;
    }
  }, {
    key: "render",
    value: function render() {
      var _this3 = this;

      var visibleStates = [FORM_SAVE_SUCCEEDED, FORM_SAVE_PARTIALLY_SUCCEEDED, FORM_SAVE_FAILED, FORM_PUBLISH_FAILED, FORM_DELETE_FAILED];
      var formState = this.props.formState;
      var errors = this.props.errors || {};
      var feedback;
      var message = null;

      switch (formState) {
        case FORM_SAVE_SUCCEEDED:
          feedback = 'positive';
          message = i18next.t('Record successfully saved.');
          break;

        case FORM_SAVE_PARTIALLY_SUCCEEDED:
          feedback = 'warning';
          message = i18next.t('Record saved with validation errors:');
          break;

        case FORM_SAVE_FAILED:
        case FORM_PUBLISH_FAILED:
          feedback = 'negative'; // TODO: use the backend error message

          message = i18next.t('There was an internal error (and the record was not saved).');
          break;

        case FORM_DELETE_FAILED:
          feedback = 'negative';
          message = i18next.t('There was an internal error (and the record was not deleted).');
      }

      var labelledMessages = this.toLabelledErrorMessages(errors);
      var listErrors = Object.entries(labelledMessages).map(function (_ref9) {
        var _ref10 = _slicedToArray(_ref9, 2),
            label = _ref10[0],
            messages = _ref10[1];

        return /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Message.Item, {
          key: label
        }, /*#__PURE__*/React__default['default'].createElement("b", null, label), ": ", _this3.renderErrorMessages(messages));
      });
      return visibleStates.includes(formState) ? /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Message, {
        visible: true,
        positive: feedback === 'positive',
        warning: feedback === 'warning',
        negative: feedback === 'negative',
        className: "flashed top-attached"
      }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Grid, {
        container: true
      }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Grid.Column, {
        width: 15,
        textAlign: "left"
      }, /*#__PURE__*/React__default['default'].createElement("strong", null, message), listErrors.length > 0 && /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Message.List, null, listErrors)))) : null;
    }
  }]);

  return DisconnectedFormFeedback;
}(React.Component);

var mapStateToProps$4 = function mapStateToProps(state) {
  return {
    formState: state.deposit.formState,
    errors: state.deposit.errors
  };
};

var FormFeedback = reactRedux.connect(mapStateToProps$4, null)(DisconnectedFormFeedback);

var FundingField = /*#__PURE__*/function (_Component) {
  _inherits(FundingField, _Component);

  var _super = _createSuper(FundingField);

  function FundingField() {
    var _this;

    _classCallCheck(this, FundingField);

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

    _this = _super.call.apply(_super, [this].concat(args));

    _this.groupErrors = function (errors) {
      for (var field in errors) {
        if (field.startsWith(_this.props.fieldPath)) {
          return {
            content: _get__default['default'](errors, _this.props.fieldPath)
          };
        }
      }

      return null;
    };

    _this.renderField = function (_ref) {
      _ref.field;
          _ref.form;
      var _this$props = _this.props,
          fieldPath = _this$props.fieldPath,
          label = _this$props.label,
          labelIcon = _this$props.labelIcon,
          options = _this$props.options,
          required = _this$props.required;
      var selectFieldFunderOptions = options.funder.map(function (f) {
        return Object({
          text: f.name,
          value: "".concat(f.scheme, " ").concat(f.identifier)
        });
      });
      return /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.ArrayField, {
        addButtonLabel: i18next.t('Add award') // TODO: Pass by prop
        ,
        defaultNewValue: emptyFunding,
        fieldPath: fieldPath,
        label: label,
        labelIcon: labelIcon,
        required: required
      }, function (_ref2) {
        _ref2.array;
            var arrayHelpers = _ref2.arrayHelpers,
            indexPath = _ref2.indexPath,
            key = _ref2.key,
            form = _ref2.form;
        return /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.GroupField, {
          widths: "equal",
          optimized: true
        }, /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.SelectField, {
          error: _this.groupErrors(form.errors),
          fieldPath: "".concat(key, ".funder"),
          label: /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.FieldLabel, {
            htmlFor: "".concat(key, ".funder"),
            label: i18next.t('Funding Organization')
          }),
          options: selectFieldFunderOptions,
          onChange: function onChange(event, selectedOption) {
            var funderFieldPath = "".concat(key, ".funder");
            var awardFieldPath = "".concat(key, ".award");

            var _selectedOption$value = selectedOption.value.split(" "),
                _selectedOption$value2 = _slicedToArray(_selectedOption$value, 2),
                scheme = _selectedOption$value2[0],
                identifier = _selectedOption$value2[1];

            var funderValue = options.funder.find(function (f) {
              return f.scheme === scheme && f.identifier === identifier;
            });
            form.setFieldValue(funderFieldPath, funderValue);
            form.setFieldValue(awardFieldPath, emptyFunding.award);
          },
          value: function () {
            var funder = _get__default['default'](form.values, "".concat(key, ".funder"));

            return funder ? "".concat(funder.scheme, " ").concat(funder.identifier) : '';
          }(),
          placeholder: i18next.t('Funding organization...'),
          required: true,
          optimized: true
        }), /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.SelectField, {
          error: _this.groupErrors(form.errors),
          fieldPath: "".concat(key, ".award"),
          label: /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.FieldLabel, {
            htmlFor: "".concat(key, ".award"),
            label: i18next.t('Award')
          }),
          options: options.award.filter(function (a) {
            var funder = _get__default['default'](form.values, "".concat(key, ".funder"));

            return funder.scheme === a.parentScheme && funder.identifier === a.parentIdentifier;
          }).map(function (a) {
            return Object({
              text: a.title,
              value: "".concat(a.scheme, " ").concat(a.identifier)
            });
          }),
          onChange: function onChange(event, selectedOption) {
            var awardFieldPath = "".concat(key, ".award");

            var _selectedOption$value3 = selectedOption.value.split(" "),
                _selectedOption$value4 = _slicedToArray(_selectedOption$value3, 2),
                scheme = _selectedOption$value4[0],
                identifier = _selectedOption$value4[1];

            var award = options.award.find(function (a) {
              return a.scheme === scheme && a.identifier === identifier;
            }); // Get rid of parentScheme + parentIdentifier

            award = _pick__default['default'](award, ["identifier", "number", "scheme", "title"]);
            form.setFieldValue(awardFieldPath, award);
          },
          value: function () {
            var award = _get__default['default'](form.values, "".concat(key, ".award"));

            return award ? "".concat(award.scheme, " ").concat(award.identifier) : '';
          }(),
          placeholder: i18next.t('Award number/acronym/name ...'),
          required: true,
          optimized: true
        }), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Form.Field, null, /*#__PURE__*/React__default['default'].createElement("label", null, "\xA0"), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Button, {
          icon: true,
          onClick: function onClick() {
            return arrayHelpers.remove(indexPath);
          }
        }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Icon, {
          name: "close",
          size: "large"
        }))));
      });
    };

    return _this;
  }

  _createClass(FundingField, [{
    key: "render",
    value: function render() {
      return /*#__PURE__*/React__default['default'].createElement(formik.Field, {
        name: this.props.fieldPath,
        component: this.renderField
      });
    }
  }]);

  return FundingField;
}(React.Component);
FundingField.defaultProps = {
  fieldPath: 'metadata.funding',
  label: i18next.t('Awards'),
  labelIcon: 'money bill alternate outline'
};

/** Identifiers array component */

var IdentifiersField = /*#__PURE__*/function (_Component) {
  _inherits(IdentifiersField, _Component);

  var _super = _createSuper(IdentifiersField);

  function IdentifiersField() {
    _classCallCheck(this, IdentifiersField);

    return _super.apply(this, arguments);
  }

  _createClass(IdentifiersField, [{
    key: "render",
    value: function render() {
      var _this$props = this.props,
          fieldPath = _this$props.fieldPath,
          label = _this$props.label,
          labelIcon = _this$props.labelIcon,
          required = _this$props.required,
          schemeOptions = _this$props.schemeOptions;
      return /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.ArrayField, {
        addButtonLabel: i18next.t('Add identifier'),
        defaultNewValue: emptyIdentifier,
        fieldPath: fieldPath,
        label: /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.FieldLabel, {
          htmlFor: fieldPath,
          icon: labelIcon,
          label: label
        }),
        required: required
      }, function (_ref) {
        _ref.array;
            var arrayHelpers = _ref.arrayHelpers,
            indexPath = _ref.indexPath,
            key = _ref.key;
        return /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.GroupField, {
          optimized: true
        }, /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.TextField, {
          fieldPath: "".concat(key, ".identifier"),
          label: i18next.t('Identifier'),
          required: true,
          width: 11
        }), schemeOptions && /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.SelectField, {
          fieldPath: "".concat(key, ".scheme"),
          label: i18next.t('Scheme'),
          options: schemeOptions,
          optimized: true,
          required: true,
          width: 5
        }), !schemeOptions && /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.TextField, {
          fieldPath: "".concat(key, ".scheme"),
          label: i18next.t('Scheme'),
          required: true,
          width: 5
        }), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Form.Field, null, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Form.Field, null, /*#__PURE__*/React__default['default'].createElement("label", null, "\xA0"), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Button, {
          icon: "close",
          onClick: function onClick() {
            return arrayHelpers.remove(indexPath);
          }
        }))));
      }));
    }
  }]);

  return IdentifiersField;
}(React.Component);
IdentifiersField.defaultProps = {
  fieldPath: 'metadata.identifiers',
  label: i18next.t('Identifier(s)'),
  labelIcon: 'barcode'
};

var PROVIDER_EXTERNAL = 'unmanaged';
var UPDATE_PID_DEBOUNCE_MS = 200;
/**
 * Button component to reserve a PID.
 */

var ReservePIDBtn = /*#__PURE__*/function (_Component) {
  _inherits(ReservePIDBtn, _Component);

  var _super = _createSuper(ReservePIDBtn);

  function ReservePIDBtn() {
    _classCallCheck(this, ReservePIDBtn);

    return _super.apply(this, arguments);
  }

  _createClass(ReservePIDBtn, [{
    key: "render",
    value: function render() {
      var _this$props = this.props,
          disabled = _this$props.disabled,
          handleReservePID = _this$props.handleReservePID,
          label = _this$props.label,
          loading = _this$props.loading;
      return /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Form.Button, {
        color: "green",
        size: "mini",
        loading: loading,
        disabled: disabled || loading,
        onClick: handleReservePID,
        content: label
      });
    }
  }]);

  return ReservePIDBtn;
}(React.Component);

ReservePIDBtn.defaultProps = {
  disabled: false,
  loading: false
};
/**
 * Button component to unreserve a PID.
 */

var UnreservePIDBtn = /*#__PURE__*/function (_Component2) {
  _inherits(UnreservePIDBtn, _Component2);

  var _super2 = _createSuper(UnreservePIDBtn);

  function UnreservePIDBtn() {
    _classCallCheck(this, UnreservePIDBtn);

    return _super2.apply(this, arguments);
  }

  _createClass(UnreservePIDBtn, [{
    key: "render",
    value: function render() {
      var _this$props2 = this.props,
          disabled = _this$props2.disabled,
          handleDiscardPID = _this$props2.handleDiscardPID,
          label = _this$props2.label,
          loading = _this$props2.loading;
      return /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Popup, {
        content: label,
        trigger: /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Form.Button, {
          disabled: disabled || loading,
          loading: loading,
          icon: "close",
          onClick: handleDiscardPID,
          size: "mini"
        })
      });
    }
  }]);

  return UnreservePIDBtn;
}(React.Component);

UnreservePIDBtn.defaultProps = {
  disabled: false,
  loading: false
};
/**
 * Manage radio buttons choices between managed
 * and unmanaged PID.
 */

var ManagedUnmanagedSwitch = /*#__PURE__*/function (_Component3) {
  _inherits(ManagedUnmanagedSwitch, _Component3);

  var _super3 = _createSuper(ManagedUnmanagedSwitch);

  function ManagedUnmanagedSwitch() {
    var _this;

    _classCallCheck(this, ManagedUnmanagedSwitch);

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

    _this = _super3.call.apply(_super3, [this].concat(args));

    _this.handleChange = function (e, _ref) {
      var value = _ref.value;
      var onManagedUnmanagedChange = _this.props.onManagedUnmanagedChange;
      var isManagedSelected = value === 'managed' ? true : false;
      onManagedUnmanagedChange(isManagedSelected);
    };

    return _this;
  }

  _createClass(ManagedUnmanagedSwitch, [{
    key: "render",
    value: function render() {
      var _this$props3 = this.props,
          disabled = _this$props3.disabled,
          isManagedSelected = _this$props3.isManagedSelected,
          pidLabel = _this$props3.pidLabel;
      return /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Form.Group, {
        inline: true
      }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Form.Field, null, i18next.t('Do you already have a {{pidLabel}} for this upload?', {
        pidLabel: pidLabel
      })), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Form.Field, {
        width: 2
      }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Radio, {
        label: i18next.t('Yes'),
        name: "radioGroup",
        value: "unmanaged",
        disabled: disabled,
        checked: !isManagedSelected,
        onChange: this.handleChange
      })), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Form.Field, {
        width: 2
      }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Radio, {
        label: i18next.t('No'),
        name: "radioGroup",
        value: "managed",
        disabled: disabled,
        checked: isManagedSelected,
        onChange: this.handleChange
      })));
    }
  }]);

  return ManagedUnmanagedSwitch;
}(React.Component);

ManagedUnmanagedSwitch.defaultProps = {
  disabled: false
};
/**
 * Render identifier field and reserve/unreserve
 * button components for managed PID.
 */

var ManagedIdentifierComponent = /*#__PURE__*/function (_Component4) {
  _inherits(ManagedIdentifierComponent, _Component4);

  var _super4 = _createSuper(ManagedIdentifierComponent);

  function ManagedIdentifierComponent() {
    var _this2;

    _classCallCheck(this, ManagedIdentifierComponent);

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

    _this2 = _super4.call.apply(_super4, [this].concat(args));

    _this2.handleReservePID = function () {
      var _this2$props = _this2.props,
          actionReservePID = _this2$props.actionReservePID,
          form = _this2$props.form,
          pidType = _this2$props.pidType;
      actionReservePID(pidType, form);
    };

    _this2.handleDiscardPID = function () {
      var _this2$props2 = _this2.props,
          actionDiscardPID = _this2$props2.actionDiscardPID,
          form = _this2$props2.form,
          pidType = _this2$props2.pidType;
      actionDiscardPID(pidType, form);
    };

    return _this2;
  }

  _createClass(ManagedIdentifierComponent, [{
    key: "render",
    value: function render() {
      var _this$props4 = this.props,
          btnLabelDiscardPID = _this$props4.btnLabelDiscardPID,
          btnLabelGetPID = _this$props4.btnLabelGetPID,
          disabled = _this$props4.disabled,
          helpText = _this$props4.helpText,
          identifier = _this$props4.identifier,
          pidPlaceholder = _this$props4.pidPlaceholder,
          reservePIDsLoading = _this$props4.reservePIDsLoading;
      var hasIdentifier = identifier !== '';
      var ReserveBtn = /*#__PURE__*/React__default['default'].createElement(ReservePIDBtn, {
        disabled: disabled || hasIdentifier,
        label: btnLabelGetPID,
        loading: reservePIDsLoading,
        handleReservePID: this.handleReservePID
      });
      var UnreserveBtn = /*#__PURE__*/React__default['default'].createElement(UnreservePIDBtn, {
        disabled: disabled,
        label: btnLabelDiscardPID,
        handleDiscardPID: this.handleDiscardPID,
        loading: reservePIDsLoading,
        pidType: this.props.pidType
      });
      return /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Form.Group, {
        inline: true
      }, hasIdentifier ? /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Form.Field, null, /*#__PURE__*/React__default['default'].createElement("label", null, identifier)) : /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Form.Field, {
        width: 4
      }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Form.Input, {
        disabled: true,
        value: "",
        placeholder: pidPlaceholder,
        width: 16
      })), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Form.Field, null, identifier ? UnreserveBtn : ReserveBtn)), helpText && /*#__PURE__*/React__default['default'].createElement("label", {
        className: "helptext"
      }, helpText));
    }
  }]);

  return ManagedIdentifierComponent;
}(React.Component);

ManagedIdentifierComponent.defaultProps = {
  disabled: false,
  helpText: null,
  reservePIDsLoading: false
};

var mapStateToProps$3 = function mapStateToProps(state) {
  return {
    reservePIDsLoading: state.deposit.reservePIDsLoading
  };
};

var mapDispatchToProps$3 = function mapDispatchToProps(dispatch) {
  return {
    actionReservePID: function actionReservePID(pidType, formik) {
      return dispatch(reservePID(pidType, formik));
    },
    actionDiscardPID: function actionDiscardPID(pidType, formik) {
      return dispatch(discardPID(pidType, formik));
    }
  };
};

var ManagedIdentifierCmp = reactRedux.connect(mapStateToProps$3, mapDispatchToProps$3)(ManagedIdentifierComponent);
/**
 * Render identifier field to allow user to input
 * the unmanaged PID.
 */

var UnmanagedIdentifierCmp = /*#__PURE__*/function (_Component5) {
  _inherits(UnmanagedIdentifierCmp, _Component5);

  var _super5 = _createSuper(UnmanagedIdentifierCmp);

  function UnmanagedIdentifierCmp(props) {
    var _this3;

    _classCallCheck(this, UnmanagedIdentifierCmp);

    _this3 = _super5.call(this, props);

    _this3.onChange = function (value) {
      var onIdentifierChanged = _this3.props.onIdentifierChanged;

      _this3.setState({
        localIdentifier: value
      }, function () {
        return onIdentifierChanged(value);
      });
    };

    var identifier = props.identifier;
    _this3.state = {
      localIdentifier: identifier
    };
    return _this3;
  }

  _createClass(UnmanagedIdentifierCmp, [{
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps) {
      // called after the form field is updated and therefore re-rendered.
      if (this.props.identifier !== prevProps.identifier) {
        this.setState({
          localIdentifier: this.props.identifier
        });
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this4 = this;

      var localIdentifier = this.state.localIdentifier;
      var _this$props5 = this.props,
          helpText = _this$props5.helpText,
          pidPlaceholder = _this$props5.pidPlaceholder;
      return /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Form.Field, {
        width: 8
      }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Form.Input, {
        onChange: function onChange(e, _ref2) {
          var value = _ref2.value;
          return _this4.onChange(value);
        },
        value: localIdentifier,
        placeholder: pidPlaceholder,
        width: 16
      })), helpText && /*#__PURE__*/React__default['default'].createElement("label", {
        className: "helptext"
      }, helpText));
    }
  }]);

  return UnmanagedIdentifierCmp;
}(React.Component);

UnmanagedIdentifierCmp.defaultProps = {
  helpText: null
};
/**
 * Render managed or unamanged PID fields and update
 * Formik form on input changed.
 * The field value has the following format:
 * { 'doi': { identifier: '<value>', provider: '<value>', client: '<value>' } }
 */

var CustomPIDField = /*#__PURE__*/function (_Component6) {
  _inherits(CustomPIDField, _Component6);

  var _super6 = _createSuper(CustomPIDField);

  function CustomPIDField(props) {
    var _this5;

    _classCallCheck(this, CustomPIDField);

    _this5 = _super6.call(this, props);

    _this5.onExternalIdentifierChanged = function (identifier) {
      var _this5$props = _this5.props,
          form = _this5$props.form,
          fieldPath = _this5$props.fieldPath;
      var pid = {
        identifier: identifier,
        provider: PROVIDER_EXTERNAL
      };
      _this5.debounced && _this5.debounced.cancel();
      _this5.debounced = _debounce__default['default'](function () {
        form.setFieldValue(fieldPath, pid);
      }, UPDATE_PID_DEBOUNCE_MS);

      _this5.debounced();
    };

    var _this5$props2 = _this5.props,
        canBeManaged = _this5$props2.canBeManaged,
        canBeUnmanaged = _this5$props2.canBeUnmanaged;
    _this5.canBeManagedAndUnmanaged = canBeManaged && canBeUnmanaged;
    _this5.state = {
      isManagedSelected: undefined
    };
    return _this5;
  }

  _createClass(CustomPIDField, [{
    key: "render",
    value: function render() {
      var _this6 = this;

      var isManagedSelected = this.state.isManagedSelected;
      var _this$props6 = this.props,
          btnLabelDiscardPID = _this$props6.btnLabelDiscardPID,
          btnLabelGetPID = _this$props6.btnLabelGetPID,
          canBeManaged = _this$props6.canBeManaged,
          canBeUnmanaged = _this$props6.canBeUnmanaged,
          form = _this$props6.form,
          fieldPath = _this$props6.fieldPath,
          isEditingPublishedRecord = _this$props6.isEditingPublishedRecord,
          managedHelpText = _this$props6.managedHelpText,
          pidLabel = _this$props6.pidLabel,
          pidIcon = _this$props6.pidIcon,
          pidPlaceholder = _this$props6.pidPlaceholder,
          required = _this$props6.required,
          unmanagedHelpText = _this$props6.unmanagedHelpText,
          pidType = _this$props6.pidType,
          field = _this$props6.field;
      var value = field.value || {};
      var currentIdentifier = value.identifier || '';
      var currentProvider = value.provider || '';
      var managedIdentifier = '',
          unmanagedIdentifier = '';

      if (currentIdentifier !== '') {
        var isProviderExternal = currentProvider === PROVIDER_EXTERNAL;
        managedIdentifier = !isProviderExternal ? currentIdentifier : '';
        unmanagedIdentifier = isProviderExternal ? currentIdentifier : '';
      }

      var hasManagedIdentifier = managedIdentifier !== '';

      var _isManagedSelected = isManagedSelected === undefined ? hasManagedIdentifier : isManagedSelected;

      return /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Form.Field, {
        required: required
      }, /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.FieldLabel, {
        htmlFor: fieldPath,
        icon: pidIcon,
        label: pidLabel
      })), this.canBeManagedAndUnmanaged && /*#__PURE__*/React__default['default'].createElement(ManagedUnmanagedSwitch, {
        disabled: isEditingPublishedRecord || hasManagedIdentifier,
        isManagedSelected: _isManagedSelected,
        onManagedUnmanagedChange: function onManagedUnmanagedChange(userSelectedManaged) {
          _this6.setState({
            isManagedSelected: userSelectedManaged
          });
        },
        pidLabel: pidLabel
      }), canBeManaged && _isManagedSelected && /*#__PURE__*/React__default['default'].createElement(ManagedIdentifierCmp, {
        disabled: isEditingPublishedRecord,
        btnLabelDiscardPID: btnLabelDiscardPID,
        btnLabelGetPID: btnLabelGetPID,
        form: form,
        identifier: managedIdentifier,
        helpText: managedHelpText,
        pidPlaceholder: pidPlaceholder,
        pidType: pidType,
        pidLabel: pidLabel
      }), canBeUnmanaged && !_isManagedSelected && /*#__PURE__*/React__default['default'].createElement(UnmanagedIdentifierCmp, {
        identifier: unmanagedIdentifier,
        onIdentifierChanged: function onIdentifierChanged(identifier) {
          _this6.onExternalIdentifierChanged(identifier);
        },
        pidPlaceholder: pidPlaceholder,
        helpText: unmanagedHelpText
      }));
    }
  }]);

  return CustomPIDField;
}(React.Component);

CustomPIDField.defaultProps = {
  managedHelpText: null,
  unmanagedHelpText: null
};
/**
 * Render the PIDField using a custom Formik component
 */

var PIDField = /*#__PURE__*/function (_Component7) {
  _inherits(PIDField, _Component7);

  var _super7 = _createSuper(PIDField);

  function PIDField(props) {
    var _this7;

    _classCallCheck(this, PIDField);

    _this7 = _super7.call(this, props);

    _this7.validatePropValues = function () {
      var _this7$props = _this7.props,
          canBeManaged = _this7$props.canBeManaged,
          canBeUnmanaged = _this7$props.canBeUnmanaged,
          fieldPath = _this7$props.fieldPath;

      if (!canBeManaged && !canBeUnmanaged) {
        throw Error("".concat(fieldPath, " must be managed, unmanaged or both."));
      }
    };

    _this7.validatePropValues();

    _this7.state = {
      isManagedSelected: false
    };
    return _this7;
  }

  _createClass(PIDField, [{
    key: "render",
    value: function render() {
      var fieldPath = this.props.fieldPath;
      return /*#__PURE__*/React__default['default'].createElement(formik.FastField, Object.assign({
        name: fieldPath,
        component: CustomPIDField
      }, this.props));
    }
  }]);

  return PIDField;
}(React.Component);
PIDField.defaultProps = {
  btnLabelDiscardPID: 'Discard',
  btnLabelGetPID: 'Reserve',
  canBeManaged: true,
  canBeUnmanaged: true,
  managedHelpText: null,
  pidIcon: 'barcode',
  pidPlaceholder: '',
  required: false,
  unmanagedHelpText: null
};

// This file is part of React-Invenio-Deposit
var LicenseFilter = function LicenseFilter(_ref) {
  var updateQueryFilters = _ref.updateQueryFilters,
      userSelectionFilters = _ref.userSelectionFilters,
      filterValue = _ref.filterValue,
      label = _ref.label,
      title = _ref.title;

  var _isChecked = function _isChecked(userSelectionFilters) {
    var isFilterActive = userSelectionFilters.filter(function (filter) {
      return filter[1] === filterValue[1];
    }).length > 0;
    return isFilterActive;
  };

  var onToggleClicked = function onToggleClicked() {
    updateQueryFilters(userSelectionFilters.concat([filterValue]));
  };

  var isChecked = _isChecked(userSelectionFilters);

  return isChecked ? /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Menu.Item, {
    name: label,
    active: true,
    className: "license-menu-item-active",
    onClick: onToggleClicked
  }, title) : /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Menu.Item, {
    name: label,
    onClick: onToggleClicked
  }, title);
};

// This file is part of React-Invenio-Deposit
var LicenseResults = reactSearchkit.withState(function (_ref) {
  var results = _ref.currentResultsState,
      serializeLicenses = _ref.serializeLicenses;
  var serializeLicenseResult = serializeLicenses ? serializeLicenses : function (result) {
    return {
      title: result.title_l10n,
      description: result.description_l10n,
      id: result.id
    };
  };
  return /*#__PURE__*/React__default['default'].createElement(formik.FastField, {
    name: "selectedLicense"
  }, function (_ref2) {
    var _ref2$form = _ref2.form,
        values = _ref2$form.values,
        setFieldValue = _ref2$form.setFieldValue;
    return /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Item.Group, null, results.data.hits.map(function (result) {
      var title = result['title_l10n'];
      var description = result['description_l10n'];
      return /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Item, {
        key: title,
        onClick: function onClick() {
          return setFieldValue('selectedLicense', serializeLicenseResult(result));
        },
        className: "license-item"
      }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Image, {
        ui: false,
        className: "license-radiobox",
        centered: true
      }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Radio, {
        checked: _get__default['default'](values, 'selectedLicense.title') === title,
        onChange: function onChange() {
          return setFieldValue('selectedLicense', serializeLicenseResult(result));
        }
      })), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Item.Content, {
        className: "license-item-content"
      }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Header, {
        size: "small"
      }, title), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Item.Description, {
        className: "license-item-description"
      }, description)));
    }));
  });
});

var overriddenComponents = {
  'SearchFilters.ToggleComponent': LicenseFilter
};
var ModalTypes = {
  STANDARD: 'standard',
  CUSTOM: 'custom'
};
var ModalActions = {
  ADD: 'add',
  EDIT: 'edit'
};
var LicenseSchema = Yup__namespace.object().shape({
  selectedLicense: Yup__namespace.object().shape({
    title: Yup__namespace.string().required(i18next.t('Title is a required field.')),
    link: Yup__namespace.string().url(i18next.t('Link must be a valid URL'))
  })
});
var LicenseModal = /*#__PURE__*/function (_Component) {
  _inherits(LicenseModal, _Component);

  var _super = _createSuper(LicenseModal);

  function LicenseModal() {
    var _this;

    _classCallCheck(this, LicenseModal);

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

    _this = _super.call.apply(_super, [this].concat(args));
    _this.state = {
      open: false
    };

    _this.openModal = function () {
      _this.setState({
        open: true
      });
    };

    _this.closeModal = function () {
      _this.setState({
        open: false
      });
    };

    _this.onSubmit = function (values, formikBag) {
      _this.props.onLicenseChange(values.selectedLicense);

      formikBag.setSubmitting(false);
      formikBag.resetForm();

      _this.closeModal();
    };

    return _this;
  }

  _createClass(LicenseModal, [{
    key: "render",
    value: function render() {
      var _this2 = this;

      var initialLicense = this.props.initialLicense || {
        title: '',
        description: '',
        id: null,
        link: ''
      };
      var searchApi = new reactSearchkit.InvenioSearchApi(this.props.searchConfig.searchApi);
      return /*#__PURE__*/React__default['default'].createElement(formik.Formik, {
        initialValues: {
          selectedLicense: initialLicense
        },
        onSubmit: this.onSubmit,
        validationSchema: LicenseSchema,
        validateOnChange: false,
        validateOnBlur: false
      }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Modal, {
        onOpen: function onOpen() {
          return _this2.openModal();
        },
        open: this.state.open,
        trigger: this.props.trigger,
        onClose: this.closeModal,
        closeIcon: true
      }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Modal.Header, {
        as: "h6",
        className: "deposit-modal-header"
      }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Grid, null, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Grid.Column, {
        floated: "left"
      }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Header, {
        as: "h2"
      }, this.props.action === ModalActions.ADD ? "Add ".concat(this.props.mode, " license") : "Change ".concat(this.props.mode, " license"))))), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Modal.Content, {
        scrolling: true
      }, this.props.mode === ModalTypes.STANDARD && /*#__PURE__*/React__default['default'].createElement(reactOverridable.OverridableContext.Provider, {
        value: overriddenComponents
      }, /*#__PURE__*/React__default['default'].createElement(reactSearchkit.ReactSearchKit, {
        searchApi: searchApi,
        appName: 'licenses',
        urlHandlerApi: {
          enabled: false
        },
        initialQueryState: this.props.searchConfig.initialQueryState
      }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Grid, null, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Grid.Row, null, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Grid.Column, {
        width: 8,
        floated: "left",
        verticalAlign: "middle"
      }, /*#__PURE__*/React__default['default'].createElement(reactSearchkit.SearchBar, {
        placeholder: i18next.t('Search'),
        autofocus: true,
        actionProps: {
          icon: 'search',
          content: null,
          className: 'search'
        }
      })), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Grid.Column, {
        width: 8,
        textAlign: "right",
        floated: "right"
      }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Menu, {
        compact: true
      }, /*#__PURE__*/React__default['default'].createElement(reactSearchkit.Toggle, {
        title: i18next.t('Recommended'),
        label: "recommended",
        filterValue: ['tags', 'recommended']
      }), /*#__PURE__*/React__default['default'].createElement(reactSearchkit.Toggle, {
        title: i18next.t('All'),
        label: "all",
        filterValue: ['tags', 'all']
      }), /*#__PURE__*/React__default['default'].createElement(reactSearchkit.Toggle, {
        title: i18next.t('Data'),
        label: "data",
        filterValue: ['tags', 'data']
      }), /*#__PURE__*/React__default['default'].createElement(reactSearchkit.Toggle, {
        title: i18next.t('Software'),
        label: "software",
        filterValue: ['tags', 'software']
      })))), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Grid.Row, {
        verticalAlign: "middle"
      }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Grid.Column, null, /*#__PURE__*/React__default['default'].createElement(reactSearchkit.ResultsLoader, null, /*#__PURE__*/React__default['default'].createElement(reactSearchkit.EmptyResults, null), /*#__PURE__*/React__default['default'].createElement(reactSearchkit.Error, null), /*#__PURE__*/React__default['default'].createElement(LicenseResults, this.props.serializeLicenses && {
        serializeLicenses: this.props.serializeLicenses
      }))))))), this.props.mode === ModalTypes.CUSTOM && /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Form, null, /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.TextField, {
        label: i18next.t('Title'),
        placeholder: i18next.t('License title'),
        fieldPath: "selectedLicense.title",
        required: true
      }), /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.TextAreaField, {
        fieldPath: 'selectedLicense.description',
        label: i18next.t('Description')
      }), /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.TextField, {
        label: i18next.t('Link'),
        placeholder: i18next.t('License link'),
        fieldPath: "selectedLicense.link"
      }))), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Modal.Actions, null, /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.ActionButton, {
        name: "cancel",
        onClick: function onClick(values, formikBag) {
          formikBag.resetForm();

          _this2.closeModal();
        },
        icon: "remove",
        content: i18next.t('Cancel'),
        floated: "left"
      }), /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.ActionButton, {
        name: "submit",
        onClick: function onClick(event, formik) {
          return formik.handleSubmit(event);
        },
        primary: true,
        icon: "checkmark",
        content: this.props.action === ModalActions.ADD ? i18next.t('Add license') : i18next.t('Change license')
      }))));
    }
  }]);

  return LicenseModal;
}(React.Component);

var LicenseFieldItem = function LicenseFieldItem(_ref) {
  var compKey = _ref.compKey,
      index = _ref.index,
      initialLicense = _ref.initialLicense,
      licenseDescription = _ref.licenseDescription,
      licenseTitle = _ref.licenseTitle,
      licenseType = _ref.licenseType,
      moveLicense = _ref.moveLicense,
      replaceLicense = _ref.replaceLicense,
      replaceUILicense = _ref.replaceUILicense,
      removeLicense = _ref.removeLicense,
      removeUILicense = _ref.removeUILicense,
      searchConfig = _ref.searchConfig,
      serializeLicenses = _ref.serializeLicenses,
      link = _ref.link;
  var dropRef = React__default['default'].useRef(null);

  var _useDrag = reactDnd.useDrag({
    item: {
      index: index,
      type: 'license'
    }
  }),
      _useDrag2 = _slicedToArray(_useDrag, 3);
      _useDrag2[0];
      var drag = _useDrag2[1],
      preview = _useDrag2[2];

  var _useDrop = reactDnd.useDrop({
    accept: 'license',
    hover: function hover(item, monitor) {
      if (!dropRef.current) {
        return;
      }

      var dragIndex = item.index;
      var hoverIndex = index; // Don't replace items with themselves

      // Don't replace items with themselves
      if (dragIndex === hoverIndex) {
        return;
      }

      if (monitor.isOver({
        shallow: true
      })) {
        moveLicense(dragIndex, hoverIndex);
        item.index = hoverIndex;
      }
    },
    collect: function collect(monitor) {
      return {
        hidden: monitor.isOver({
          shallow: true
        })
      };
    }
  }),
      _useDrop2 = _slicedToArray(_useDrop, 2),
      hidden = _useDrop2[0].hidden,
      drop = _useDrop2[1]; // Initialize the ref explicitely


  drop(dropRef);
  return /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Ref, {
    innerRef: dropRef,
    key: compKey
  }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.List.Item, {
    key: compKey,
    className: hidden ? 'deposit-drag-listitem hidden' : 'deposit-drag-listitem'
  }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.List.Content, {
    floated: "right"
  }, /*#__PURE__*/React__default['default'].createElement(LicenseModal, {
    searchConfig: searchConfig,
    onLicenseChange: function onLicenseChange(selectedLicense) {
      replaceUILicense(index, selectedLicense);
      replaceLicense(index, selectedLicense);
    },
    mode: licenseType,
    initialLicense: initialLicense,
    action: "edit",
    trigger: /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Button, {
      size: "mini",
      primary: true,
      type: "button"
    }, i18next.t('Edit')),
    serializeLicenses: serializeLicenses
  }), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Button, {
    size: "mini",
    type: "button",
    onClick: function onClick() {
      removeUILicense(index);
      removeLicense(index);
    }
  }, i18next.t('Remove'))), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Ref, {
    innerRef: drag
  }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.List.Icon, {
    name: "bars",
    className: "drag-anchor"
  })), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Ref, {
    innerRef: preview
  }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.List.Content, null, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.List.Header, null, licenseTitle), licenseDescription && /*#__PURE__*/React__default['default'].createElement(semanticUiReact.List.Description, null, _truncate__default['default'](licenseDescription, {
    length: 300
  })), link && /*#__PURE__*/React__default['default'].createElement("span", null, /*#__PURE__*/React__default['default'].createElement("a", {
    href: link,
    target: "_blank",
    rel: "noopener noreferrer"
  }, licenseDescription && /*#__PURE__*/React__default['default'].createElement("span", null, "\xA0"), i18next.t('Read more')))))));
};

var LicenseFieldForm = /*#__PURE__*/function (_Component) {
  _inherits(LicenseFieldForm, _Component);

  var _super = _createSuper(LicenseFieldForm);

  function LicenseFieldForm() {
    var _this;

    _classCallCheck(this, LicenseFieldForm);

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

    _this = _super.call.apply(_super, [this].concat(args));

    _this.setOpen = function (open) {
      return _this.setState({
        open: open
      });
    };

    return _this;
  }

  _createClass(LicenseFieldForm, [{
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$props = this.props,
          label = _this$props.label,
          labelIcon = _this$props.labelIcon,
          fieldPath = _this$props.fieldPath,
          uiFieldPath = _this$props.uiFieldPath,
          _this$props$form = _this$props.form,
          values = _this$props$form.values;
          _this$props$form.errors;
          var formikArrayMove = _this$props.move,
          formikArrayPush = _this$props.push,
          formikArrayRemove = _this$props.remove,
          formikArrayReplace = _this$props.replace,
          required = _this$props.required;
      /**
       * Removes license from UI object
       * @param {number} index
       */

      var removeUILicense = function removeUILicense(index) {
        var uiValues = formik.getIn(values, "".concat(uiFieldPath), '');
        uiValues.splice(index, 1);
      };
      /**
       * Replaces license in UI object
       * @param {number} index
       * @param {Object} selectedLicense
       */


      var replaceUILicense = function replaceUILicense(index, selectedLicense) {
        var uiValues = formik.getIn(values, "".concat(uiFieldPath), '');

        var UIserialize = function UIserialize(selectedLicense) {
          return {
            id: selectedLicense.id,
            description_l10n: selectedLicense.description,
            title_l10n: selectedLicense.title,
            link: selectedLicense.link
          };
        };

        uiValues.splice(index, 1, UIserialize(selectedLicense));
      };

      return /*#__PURE__*/React__default['default'].createElement(reactDnd.DndProvider, {
        backend: reactDndHtml5Backend.HTML5Backend
      }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Form.Field, {
        required: required
      }, /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.FieldLabel, {
        htmlFor: fieldPath,
        icon: labelIcon,
        label: label
      }), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.List, null, formik.getIn(values, fieldPath, []).map(function (value, index, array) {
        var arrayPath = fieldPath;
        var indexPath = index;
        var key = "".concat(arrayPath, ".").concat(indexPath);
        var uiKey = "".concat(uiFieldPath, ".").concat(indexPath);
        var licenseType = value.id ? 'standard' : 'custom';
        var description = formik.getIn(values, "".concat(uiKey, ".description_l10n"), formik.getIn(values, "".concat(key, ".description")));
        var link = value.id ? formik.getIn(values, "".concat(uiKey, ".props.url"), formik.getIn(values, "".concat(key, ".props.url"), '')) : formik.getIn(values, "".concat(uiKey, ".link"), formik.getIn(values, "".concat(key, ".link"), ''));
        var title = formik.getIn(values, "".concat(uiKey, ".title_l10n"), formik.getIn(values, "".concat(key, ".title"), ''));
        return /*#__PURE__*/React__default['default'].createElement(LicenseFieldItem, {
          key: key,
          index: index,
          licenseType: licenseType,
          compKey: key,
          initialLicense: licenseType === 'custom' ? value : null,
          licenseDescription: description,
          licenseTitle: title,
          moveLicense: formikArrayMove,
          replaceLicense: formikArrayReplace,
          replaceUILicense: replaceUILicense,
          removeLicense: formikArrayRemove,
          removeUILicense: removeUILicense,
          searchConfig: _this2.props.searchConfig,
          serializeLicenses: _this2.props.serializeLicenses,
          link: link
        });
      }), /*#__PURE__*/React__default['default'].createElement(LicenseModal, {
        searchConfig: this.props.searchConfig,
        trigger: /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Button, {
          type: "button",
          key: "standard"
        }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Icon, {
          name: "add"
        }), i18next.t('Add standard')),
        onLicenseChange: function onLicenseChange(selectedLicense) {
          formikArrayPush(selectedLicense);
        },
        mode: "standard",
        action: "add",
        serializeLicenses: this.props.serializeLicenses
      }), /*#__PURE__*/React__default['default'].createElement(LicenseModal, {
        searchConfig: this.props.searchConfig,
        trigger: /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Button, {
          type: "button",
          key: "custom"
        }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Icon, {
          name: "add"
        }), i18next.t('Add custom')),
        onLicenseChange: function onLicenseChange(selectedLicense) {
          formikArrayPush(selectedLicense);
        },
        mode: "custom",
        action: "add"
      }))));
    }
  }]);

  return LicenseFieldForm;
}(React.Component);

var LicenseField = /*#__PURE__*/function (_Component2) {
  _inherits(LicenseField, _Component2);

  var _super2 = _createSuper(LicenseField);

  function LicenseField() {
    _classCallCheck(this, LicenseField);

    return _super2.apply(this, arguments);
  }

  _createClass(LicenseField, [{
    key: "render",
    value: function render() {
      var _this3 = this;

      return /*#__PURE__*/React__default['default'].createElement(formik.FieldArray, {
        name: this.props.fieldPath,
        component: function component(formikProps) {
          return /*#__PURE__*/React__default['default'].createElement(LicenseFieldForm, Object.assign({}, formikProps, _this3.props));
        }
      });
    }
  }]);

  return LicenseField;
}(React.Component);
LicenseField.defaultProps = {
  fieldPath: 'metadata.rights',
  label: i18next.t('Licenses'),
  uiFieldPath: 'ui.rights',
  labelIcon: 'drivers license',
  required: false
};

var _excluded$3 = ["record", "saveClick", "formState"];
var initialState = {
  isLoading: false,
  previewButtonClicked: false,
  previousFormState: ''
};
var PreviewButtonComponent = /*#__PURE__*/function (_Component) {
  _inherits(PreviewButtonComponent, _Component);

  var _super = _createSuper(PreviewButtonComponent);

  function PreviewButtonComponent() {
    var _this;

    _classCallCheck(this, PreviewButtonComponent);

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

    _this = _super.call.apply(_super, [this].concat(args));
    _this.state = initialState;

    _this.isDisabled = function (formik) {
      return formik.isSubmitting;
    };

    return _this;
  }

  _createClass(PreviewButtonComponent, [{
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$props = this.props,
          record = _this$props.record,
          saveClick = _this$props.saveClick,
          formState = _this$props.formState,
          uiProps = _objectWithoutProperties(_this$props, _excluded$3);

      var _this$state = this.state,
          isLoading = _this$state.isLoading,
          previewButtonClicked = _this$state.previewButtonClicked,
          previousFormState = _this$state.previousFormState;

      if (previewButtonClicked && formState !== previousFormState) {
        switch (formState) {
          case FORM_SAVING:
            this.setState({
              previousFormState: formState
            });
            break;

          case FORM_SAVE_SUCCEEDED:
            this.setState(initialState);
            window.location = "/records/".concat(record.id, "?preview=1");
            break;

          case FORM_SAVE_FAILED:
          case FORM_SAVE_PARTIALLY_SUCCEEDED:
            window.scrollTo({
              top: 0,
              left: 0,
              behavior: 'smooth'
            });
            this.setState({
              isLoading: false,
              previewButtonClicked: false,
              previousFormState: formState
            });
            break;
        }
      }

      return /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.ActionButton, Object.assign({
        name: "preview",
        isDisabled: this.isDisabled,
        onClick: function onClick(event, formik) {
          saveClick(event, formik);

          _this2.setState({
            isLoading: true,
            previewButtonClicked: true
          });
        },
        icon: true,
        labelPosition: "center"
      }, uiProps), function (formik) {
        return /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, formik.isSubmitting && isLoading ? /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Icon, {
          size: "large",
          loading: true,
          name: "spinner"
        }) : /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Icon, {
          name: "eye"
        }), i18next.t('Preview'));
      });
    }
  }]);

  return PreviewButtonComponent;
}(React.Component);

var mapStateToProps$2 = function mapStateToProps(state) {
  return {
    formState: state.deposit.formState,
    record: state.deposit.record
  };
};

var mapDispatchToProps$2 = function mapDispatchToProps(dispatch) {
  return {
    saveClick: function saveClick(event, formik) {
      return dispatch(submitAction(FORM_SAVING, event, formik));
    }
  };
};

var PreviewButton = reactRedux.connect(mapStateToProps$2, mapDispatchToProps$2)(PreviewButtonComponent);

var PublicationDateField = /*#__PURE__*/function (_Component) {
  _inherits(PublicationDateField, _Component);

  var _super = _createSuper(PublicationDateField);

  function PublicationDateField() {
    _classCallCheck(this, PublicationDateField);

    return _super.apply(this, arguments);
  }

  _createClass(PublicationDateField, [{
    key: "render",
    value: function render() {
      var _this$props = this.props,
          fieldPath = _this$props.fieldPath,
          label = _this$props.label,
          labelIcon = _this$props.labelIcon,
          placeholder = _this$props.placeholder,
          required = _this$props.required;
      return /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.TextField, {
        fieldPath: fieldPath,
        helpText: i18next.t('In case your upload was already published elsewhere, please use the date of the first publication. Format: YYYY-MM-DD, YYYY-MM, or YYYY. For intervals use DATE/DATE, e.g. 1939/1945.'),
        label: /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.FieldLabel, {
          htmlFor: fieldPath,
          icon: labelIcon,
          label: label
        }),
        placeholder: placeholder,
        required: required
      });
    }
  }]);

  return PublicationDateField;
}(React.Component);
PublicationDateField.defaultProps = {
  fieldPath: 'metadata.publication_date',
  label: i18next.t('Publication date'),
  labelIcon: 'calendar',
  placeholder: i18next.t('YYYY-MM-DD or YYYY-MM-DD/YYYY-MM-DD for intervals. MM and DD are optional.')
};

var _excluded$2 = ["formState", "publishClick", "numberOfFiles", "errors"];
var PublishButtonComponent = /*#__PURE__*/function (_Component) {
  _inherits(PublishButtonComponent, _Component);

  var _super = _createSuper(PublishButtonComponent);

  function PublishButtonComponent() {
    var _this;

    _classCallCheck(this, PublishButtonComponent);

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

    _this = _super.call.apply(_super, [this].concat(args));
    _this.state = {
      confirmOpen: false
    };

    _this.handleOpen = function () {
      return _this.setState({
        confirmOpen: true
      });
    };

    _this.handleClose = function () {
      return _this.setState({
        confirmOpen: false
      });
    };

    return _this;
  }

  _createClass(PublishButtonComponent, [{
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$props = this.props,
          formState = _this$props.formState,
          publishClick = _this$props.publishClick,
          numberOfFiles = _this$props.numberOfFiles,
          errors = _this$props.errors,
          uiProps = _objectWithoutProperties(_this$props, _excluded$2);

      var handlePublish = function handlePublish(event, formik) {
        publishClick(event, formik);

        _this2.handleClose();
      };

      var isDisabled = function isDisabled(formik) {
        var filesEnabled = _get__default['default'](formik.values, 'files.enabled', false);

        var filesMissing = filesEnabled && !numberOfFiles;
        var hasErrors = !_isEmpty__default['default'](errors);
        return formik.isSubmitting || hasErrors || filesMissing;
      };

      var action = i18next.t('publish');
      var capitalizedAction = toCapitalCase(action);
      return /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.ActionButton, Object.assign({
        isDisabled: isDisabled,
        name: "publish",
        onClick: this.handleOpen,
        positive: true,
        icon: true,
        labelPosition: "left"
      }, uiProps), function (formik) {
        return /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, formik.isSubmitting && formState === FORM_PUBLISHING ? /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Icon, {
          size: "large",
          loading: true,
          name: "spinner"
        }) : /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Icon, {
          name: "upload"
        }), capitalizedAction);
      }), this.state.confirmOpen && /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Modal, {
        open: this.state.confirmOpen,
        onClose: this.handleClose,
        size: "small"
      }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Modal.Content, null, /*#__PURE__*/React__default['default'].createElement("h3", null, i18next.t("Are you sure you want to {{action}} this record?", {
        action: action
      }))), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Modal.Actions, null, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Button, {
        onClick: this.handleClose,
        floated: "left"
      }, "Cancel"), /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.ActionButton, {
        name: "publish",
        onClick: handlePublish,
        positive: true,
        content: capitalizedAction
      }))));
    }
  }]);

  return PublishButtonComponent;
}(React.Component);

var mapStateToProps$1 = function mapStateToProps(state) {
  return {
    formState: state.deposit.formState,
    numberOfFiles: Object.values(state.files.entries).length,
    errors: state.deposit.errors
  };
};

var mapDispatchToProps$1 = function mapDispatchToProps(dispatch) {
  return {
    publishClick: function publishClick(event, formik) {
      return dispatch(submitAction(FORM_PUBLISHING, event, formik));
    }
  };
};

var PublishButton = reactRedux.connect(mapStateToProps$1, mapDispatchToProps$1)(PublishButtonComponent);

var PublisherField = /*#__PURE__*/function (_Component) {
  _inherits(PublisherField, _Component);

  var _super = _createSuper(PublisherField);

  function PublisherField() {
    _classCallCheck(this, PublisherField);

    return _super.apply(this, arguments);
  }

  _createClass(PublisherField, [{
    key: "render",
    value: function render() {
      var _this$props = this.props,
          fieldPath = _this$props.fieldPath,
          label = _this$props.label,
          labelIcon = _this$props.labelIcon,
          placeholder = _this$props.placeholder;
      return /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.TextField, {
        fieldPath: fieldPath,
        helpText: i18next.t('The publisher is used to formulate the citation, so consider the prominence of the role.'),
        label: /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.FieldLabel, {
          htmlFor: fieldPath,
          icon: labelIcon,
          label: label
        }),
        placeholder: placeholder
      });
    }
  }]);

  return PublisherField;
}(React.Component);
PublisherField.defaultProps = {
  fieldPath: 'metadata.publisher',
  label: i18next.t('Publisher'),
  labelIcon: 'building outline',
  placeholder: i18next.t('Enter publisher name')
};

var _excluded$1 = ["fieldPath", "label", "labelIcon", "options"];
var ResourceTypeField = /*#__PURE__*/function (_Component) {
  _inherits(ResourceTypeField, _Component);

  var _super = _createSuper(ResourceTypeField);

  function ResourceTypeField() {
    var _this;

    _classCallCheck(this, ResourceTypeField);

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

    _this = _super.call.apply(_super, [this].concat(args));

    _this.groupErrors = function (errors, fieldPath) {
      var fieldErrors = _get__default['default'](errors, fieldPath);

      if (fieldErrors) {
        return {
          content: fieldErrors
        };
      }

      return null;
    };

    _this._label = function (option) {
      return option.type_name + (option.subtype_name ? ' / ' + option.subtype_name : '');
    };

    _this.createOptions = function (propsOptions) {
      return propsOptions.map(function (o) {
        return _objectSpread2(_objectSpread2({}, o), {}, {
          label: _this._label(o)
        });
      }).sort(function (o1, o2) {
        return o1.label.localeCompare(o2.label);
      }).map(function (o) {
        return {
          text: /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, /*#__PURE__*/React__default['default'].createElement("i", {
            className: o.icon + ' icon'
          }), /*#__PURE__*/React__default['default'].createElement("span", {
            className: "text"
          }, o.label)),
          value: o.id
        };
      });
    };

    return _this;
  }

  _createClass(ResourceTypeField, [{
    key: "render",
    value: function render() {
      var _this$props = this.props,
          fieldPath = _this$props.fieldPath,
          label = _this$props.label,
          labelIcon = _this$props.labelIcon,
          options = _this$props.options,
          restProps = _objectWithoutProperties(_this$props, _excluded$1);

      var frontEndOptions = this.createOptions(options);
      return /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.SelectField, Object.assign({
        fieldPath: fieldPath,
        label: /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.FieldLabel, {
          htmlFor: fieldPath,
          icon: labelIcon,
          label: label
        }),
        optimized: true,
        options: frontEndOptions
      }, restProps));
    }
  }]);

  return ResourceTypeField;
}(React.Component);
ResourceTypeField.defaultProps = {
  fieldPath: 'metadata.resource_type',
  label: i18next.t('Resource type'),
  labelIcon: 'tag',
  labelclassname: 'field-label-class'
};

var RelatedWorksField = /*#__PURE__*/function (_Component) {
  _inherits(RelatedWorksField, _Component);

  var _super = _createSuper(RelatedWorksField);

  function RelatedWorksField() {
    _classCallCheck(this, RelatedWorksField);

    return _super.apply(this, arguments);
  }

  _createClass(RelatedWorksField, [{
    key: "render",
    value: function render() {
      var _this$props = this.props,
          fieldPath = _this$props.fieldPath,
          label = _this$props.label,
          labelIcon = _this$props.labelIcon,
          required = _this$props.required,
          options = _this$props.options;
      return /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, /*#__PURE__*/React__default['default'].createElement("label", {
        className: "helptext",
        style: {
          marginBottom: '10px'
        }
      }, i18next.t('Specify identifiers of related works. Supported identifiers include DOI, Handle, ARK, PURL, ISSN, ISBN, PubMed ID, PubMed Central ID, ADS Bibliographic Code, arXiv, Life Science Identifiers (LSID), EAN-13, ISTC, URNs, and URLs.')), /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.ArrayField, {
        addButtonLabel: i18next.t('Add related work'),
        defaultNewValue: emptyRelatedWork,
        fieldPath: fieldPath,
        label: /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.FieldLabel, {
          htmlFor: fieldPath,
          icon: labelIcon,
          label: label
        }),
        required: required
      }, function (_ref) {
        _ref.array;
            var arrayHelpers = _ref.arrayHelpers,
            indexPath = _ref.indexPath,
            key = _ref.key;
        return /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.GroupField, {
          optimized: true
        }, /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.SelectField, {
          clearable: true,
          fieldPath: "".concat(key, ".relation_type"),
          label: i18next.t('Relation'),
          optimized: true,
          options: options.relations,
          placeholder: i18next.t('Select relation...'),
          required: true,
          width: 3
        }), /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.SelectField, {
          clearable: true,
          fieldPath: "".concat(key, ".scheme"),
          label: i18next.t('Scheme'),
          optimized: true,
          options: options.scheme,
          required: true,
          width: 2
        }), /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.TextField, {
          fieldPath: "".concat(key, ".identifier"),
          label: i18next.t('Identifier'),
          required: true,
          width: 4
        }), /*#__PURE__*/React__default['default'].createElement(ResourceTypeField, {
          clearable: true,
          fieldPath: "".concat(key, ".resource_type"),
          labelIcon: '' // Otherwise breaks alignment
          ,
          options: options.resource_type,
          width: 6,
          labelclassname: "small field-label-class"
        }), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Form.Field, {
          width: 1
        }, /*#__PURE__*/React__default['default'].createElement("label", null, "\xA0"), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Button, {
          icon: true,
          onClick: function onClick() {
            return arrayHelpers.remove(indexPath);
          }
        }, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Icon, {
          name: "close"
        }))));
      }));
    }
  }]);

  return RelatedWorksField;
}(React.Component);
RelatedWorksField.defaultProps = {
  fieldPath: 'metadata.related_identifiers',
  label: i18next.t('Related works'),
  labelIcon: 'barcode'
};

var _excluded = ["formState", "saveClick"];
var SaveButtonComponent = /*#__PURE__*/function (_Component) {
  _inherits(SaveButtonComponent, _Component);

  var _super = _createSuper(SaveButtonComponent);

  function SaveButtonComponent() {
    var _this;

    _classCallCheck(this, SaveButtonComponent);

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

    _this = _super.call.apply(_super, [this].concat(args));

    _this.isDisabled = function (formik) {
      return formik.isSubmitting;
    };

    return _this;
  }

  _createClass(SaveButtonComponent, [{
    key: "render",
    value: function render() {
      var _this$props = this.props,
          formState = _this$props.formState,
          saveClick = _this$props.saveClick,
          uiProps = _objectWithoutProperties(_this$props, _excluded);

      function handleClick(e, formik) {
        saveClick(e, formik);
        window.scrollTo({
          top: 0,
          left: 0,
          behavior: 'smooth'
        });
      }

      return /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.ActionButton, Object.assign({
        isDisabled: this.isDisabled,
        name: "save",
        onClick: handleClick,
        icon: true,
        labelPosition: "center"
      }, uiProps), function (formik) {
        return /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, formik.isSubmitting && formState === FORM_SAVING ? /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Icon, {
          size: "large",
          loading: true,
          name: "spinner"
        }) : /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Icon, {
          name: "save"
        }), i18next.t('Save draft'));
      });
    }
  }]);

  return SaveButtonComponent;
}(React.Component);

var mapStateToProps = function mapStateToProps(state) {
  return {
    formState: state.deposit.formState
  };
};

var mapDispatchToProps = function mapDispatchToProps(dispatch) {
  return {
    saveClick: function saveClick(event, formik) {
      return dispatch(submitAction(FORM_SAVING, event, formik));
    }
  };
};

var SaveButton = reactRedux.connect(mapStateToProps, mapDispatchToProps)(SaveButtonComponent);

var SubjectsField = /*#__PURE__*/function (_Component) {
  _inherits(SubjectsField, _Component);

  var _super = _createSuper(SubjectsField);

  function SubjectsField() {
    var _this;

    _classCallCheck(this, SubjectsField);

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

    _this = _super.call.apply(_super, [this].concat(args));
    _this.state = {
      limitTo: 'all'
    };

    _this.serializeSubjects = function (subjects) {
      return subjects.map(function (subject) {
        var scheme = subject.scheme ? "(".concat(subject.scheme, ") ") : '';
        return _objectSpread2(_objectSpread2({
          text: scheme + subject.subject,
          value: subject.subject,
          key: subject.subject
        }, subject.id ? {
          id: subject.id
        } : {}), {}, {
          subject: subject.subject
        });
      });
    };

    _this.prepareSuggest = function (searchQuery) {
      var limitTo = _this.state.limitTo;
      var prefix = limitTo === 'all' ? '' : "".concat(limitTo, ":");
      return "".concat(prefix).concat(searchQuery);
    };

    return _this;
  }

  _createClass(SubjectsField, [{
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$props = this.props,
          fieldPath = _this$props.fieldPath,
          label = _this$props.label,
          labelIcon = _this$props.labelIcon,
          required = _this$props.required,
          multiple = _this$props.multiple,
          placeholder = _this$props.placeholder,
          clearable = _this$props.clearable,
          limitToOptions = _this$props.limitToOptions;
      return /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.GroupField, null, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Form.Field, {
        width: 5
      }, /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.FieldLabel, {
        htmlFor: fieldPath,
        icon: labelIcon,
        label: label
      }), /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.GroupField, null, /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Form.Field, {
        width: 7,
        style: {
          marginBottom: 'auto',
          marginTop: 'auto'
        }
      }, i18next.t('Suggest from')), /*#__PURE__*/React__default['default'].createElement(semanticUiReact.Form.Dropdown, {
        defaultValue: limitToOptions[0].value,
        fluid: true,
        onChange: function onChange(event, data) {
          return _this2.setState({
            limitTo: data.value
          });
        },
        options: limitToOptions,
        selection: true,
        width: 8
      }))), /*#__PURE__*/React__default['default'].createElement(formik.Field, {
        name: this.props.fieldPath
      }, function (_ref) {
        var values = _ref.form.values;
        return /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.RemoteSelectField, {
          clearable: clearable,
          fieldPath: fieldPath,
          initialSuggestions: formik.getIn(values, fieldPath, []),
          multiple: multiple,
          noQueryMessage: i18next.t('Search or create subjects..'),
          placeholder: placeholder,
          preSearchChange: _this2.prepareSuggest,
          required: required,
          serializeSuggestions: _this2.serializeSubjects,
          serializeAddedValue: function serializeAddedValue(value) {
            return {
              text: value,
              value: value,
              key: value,
              subject: value
            };
          },
          suggestionAPIUrl: "/api/subjects",
          onValueChange: function onValueChange(_ref2, selectedSuggestions) {
            var formikProps = _ref2.formikProps;
            formikProps.form.setFieldValue(fieldPath, // save the suggestion objects so we can extract information
            // about which value added by the user
            selectedSuggestions);
          },
          value: formik.getIn(values, fieldPath, []).map(function (val) {
            return val.subject;
          }),
          label: /*#__PURE__*/React__default['default'].createElement("label", null, "\xA0")
          /** For alignment purposes */
          ,
          allowAdditions: true,
          width: 11
        });
      }));
    }
  }]);

  return SubjectsField;
}(React.Component);
SubjectsField.defaultProps = {
  fieldPath: 'metadata.subjects',
  label: i18next.t('Subjects'),
  labelIcon: 'tag',
  multiple: true,
  clearable: true,
  placeholder: i18next.t('Search for a subject by name')
};

var TitlesField = /*#__PURE__*/function (_Component) {
  _inherits(TitlesField, _Component);

  var _super = _createSuper(TitlesField);

  function TitlesField() {
    _classCallCheck(this, TitlesField);

    return _super.apply(this, arguments);
  }

  _createClass(TitlesField, [{
    key: "render",
    value: function render() {
      var _this$props = this.props,
          fieldPath = _this$props.fieldPath;
          _this$props.options;
          var label = _this$props.label,
          required = _this$props.required;
          _this$props.recordUI;
      return /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, null, /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.TextField, {
        fieldPath: fieldPath,
        label: /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.FieldLabel, {
          htmlFor: fieldPath,
          icon: 'book',
          label: label
        }),
        required: required
      }));
    }
  }]);

  return TitlesField;
}(React.Component);
TitlesField.defaultProps = {
  fieldPath: 'metadata.title',
  label: i18next.t('Title')
};

var VersionField = /*#__PURE__*/function (_Component) {
  _inherits(VersionField, _Component);

  var _super = _createSuper(VersionField);

  function VersionField() {
    _classCallCheck(this, VersionField);

    return _super.apply(this, arguments);
  }

  _createClass(VersionField, [{
    key: "render",
    value: function render() {
      var _this$props = this.props,
          fieldPath = _this$props.fieldPath,
          label = _this$props.label,
          labelIcon = _this$props.labelIcon,
          placeholder = _this$props.placeholder;
      var helpText = /*#__PURE__*/React__default['default'].createElement("span", null, /*#__PURE__*/React__default['default'].createElement(Trans, null, "Mostly relevant for software and dataset uploads. A semantic version string is preferred see", /*#__PURE__*/React__default['default'].createElement("a", {
        href: "https://semver.org/",
        target: "_blank"
      }, ' ', "semver.org"), ", but any version string is accepted."));
      return /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.TextField, {
        fieldPath: fieldPath,
        helpText: helpText,
        label: /*#__PURE__*/React__default['default'].createElement(reactInvenioForms.FieldLabel, {
          htmlFor: fieldPath,
          icon: labelIcon,
          label: label
        }),
        placeholder: placeholder
      });
    }
  }]);

  return VersionField;
}(React.Component);
VersionField.defaultProps = {
  fieldPath: 'metadata.version',
  label: i18next.t('Version'),
  labelIcon: 'code branch',
  placeholder: ''
};

exports.AccessRightField = AccessRightField;
exports.AdditionalTitlesField = AdditionalTitlesField;
exports.AffiliationsField = AffiliationsField;
exports.ComingSoonField = ComingSoonField;
exports.CreatibutorsField = CreatibutorsField;
exports.DatesField = DatesField;
exports.DeleteButton = DeleteButton;
exports.DepositApiClient = DepositApiClient;
exports.DepositController = DepositController;
exports.DepositErrorHandler = DepositErrorHandler;
exports.DepositFormApp = DepositFormApp;
exports.DepositFormTitle = DepositFormTitle;
exports.DepositRecordSerializer = DepositRecordSerializer;
exports.DescriptionsField = DescriptionsField;
exports.FileUploader = FileUploader;
exports.FormFeedback = FormFeedback;
exports.FundingField = FundingField;
exports.IdentifiersField = IdentifiersField;
exports.LanguagesField = LanguagesField;
exports.LicenseField = LicenseField;
exports.NewVersionButton = NewVersionButton;
exports.PIDField = PIDField;
exports.PreviewButton = PreviewButton;
exports.PublicationDateField = PublicationDateField;
exports.PublishButton = PublishButton;
exports.PublisherField = PublisherField;
exports.RelatedWorksField = RelatedWorksField;
exports.ResourceTypeField = ResourceTypeField;
exports.SaveButton = SaveButton;
exports.SubjectsField = SubjectsField;
exports.TitlesField = TitlesField;
exports.VersionField = VersionField;
exports.connect = connect;
exports.getInputFromDOM = getInputFromDOM;
//# sourceMappingURL=index.js.map