@bigbinary/neeto-molecules 1.0.74 → 1.0.76-beta

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2911 @@
1
+ import React, { useRef, useState, useContext } from 'react';
2
+ import { useFormikContext, Field } from 'formik';
3
+ import { isEditorEmpty, FormikEditor, EditorContent } from '@bigbinary/neeto-editor';
4
+ import { Label, Button, Toastr, Input as Input$1, Typography } from '@bigbinary/neetoui';
5
+ import { Select, Input, MultiEmailInput, ActionBlock, Form } from '@bigbinary/neetoui/formik';
6
+ import { useTranslation, Trans } from 'react-i18next';
7
+ import { t } from 'i18next';
8
+ import { prop } from 'ramda';
9
+ import * as yup from 'yup';
10
+ import { string } from 'yup';
11
+ import { isNotEmpty, noop, isPresent } from '@bigbinary/neeto-commons-frontend/pure';
12
+ import { Upload } from '@bigbinary/neeto-icons';
13
+ import require$$0 from 'stream';
14
+ import { withEventTargetValue } from '@bigbinary/neeto-commons-frontend/utils';
15
+ import DynamicVariables from '@bigbinary/neeto-molecules/DynamicVariables';
16
+
17
+ var INITIAL_FORM_VALUES = {
18
+ sendTo: [],
19
+ sendToCc: [],
20
+ sendToBcc: [],
21
+ replyTo: "",
22
+ showCopyEmails: false,
23
+ subject: "",
24
+ message: ""
25
+ };
26
+ var EMAIL_FORM_VALIDATION_SCHEMA = yup.object().shape({
27
+ subject: yup.string().required(t("neetoMolecules.emailForm.errors.subjectRequired")),
28
+ message: yup.string().test("message", t("neetoMolecules.emailForm.errors.messageRequired"), function (value) {
29
+ return !isEditorEmpty(value);
30
+ })
31
+ });
32
+ var SEND_TO_FIELD_VALIDATION = yup.object().shape({
33
+ sendTo: yup.array().min(1, t("neetoMolecules.emailForm.errors.required", {
34
+ entity: t("neetoMolecules.emailForm.fields.sendToEmailAddress")
35
+ })).test("all-emails-valid", t("neetoMolecules.emailForm.errors.invalidEmailAddress"), function (emails) {
36
+ return emails === null || emails === void 0 ? void 0 : emails.every(prop("valid"));
37
+ }).nullable()
38
+ });
39
+ var REPLY_TO_FIELD_VALIDATION = yup.object().shape({
40
+ replyTo: yup.string().nullable().email(t("neetoMolecules.emailForm.errors.invalidEmailAddress")).required(t("neetoMolecules.emailForm.errors.required", {
41
+ entity: t("neetoMolecules.emailForm.fields.replyToEmailAddress")
42
+ }))
43
+ });
44
+ var EDITOR_ADDONS = ["highlight", "emoji", "code-block", "block-quote", "image-upload", "divider", "video-embed"];
45
+ var ALLOWED_FILE_PICKER_TYPES = [".csv"];
46
+
47
+ /* eslint-disable @bigbinary/neeto/use-zustand-for-global-state-management */
48
+ var EmailFormContext = /*#__PURE__*/React.createContext({
49
+ showSendToField: false,
50
+ showReplyToField: false
51
+ });
52
+
53
+ var ReplyToField = function ReplyToField(_ref) {
54
+ var replyToOptions = _ref.replyToOptions;
55
+ var _useTranslation = useTranslation(),
56
+ t = _useTranslation.t;
57
+ var isDropdownField = isNotEmpty(replyToOptions);
58
+ var _useFormikContext = useFormikContext(),
59
+ setFieldValue = _useFormikContext.setFieldValue;
60
+ if (isDropdownField) {
61
+ return /*#__PURE__*/React.createElement(Select, {
62
+ className: "w-full",
63
+ "data-testid": "replyToOptions",
64
+ label: t("neetoMolecules.emailForm.labels.replyTo"),
65
+ name: "replyTo",
66
+ options: replyToOptions,
67
+ onChange: function onChange(_ref2) {
68
+ var value = _ref2.value;
69
+ return setFieldValue("replyTo", value);
70
+ }
71
+ });
72
+ }
73
+ return /*#__PURE__*/React.createElement(Input, {
74
+ autoFocus: true,
75
+ required: true,
76
+ className: "w-full",
77
+ "data-testid": "replyToInput",
78
+ label: t("neetoMolecules.emailForm.labels.replyTo"),
79
+ name: "replyTo",
80
+ placeholder: t("neetoMolecules.emailForm.placeholders.emailPlaceholder"),
81
+ size: "large"
82
+ });
83
+ };
84
+
85
+ function _arrayLikeToArray(arr, len) {
86
+ if (len == null || len > arr.length) len = arr.length;
87
+ for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
88
+ return arr2;
89
+ }
90
+
91
+ function _arrayWithoutHoles(arr) {
92
+ if (Array.isArray(arr)) return _arrayLikeToArray(arr);
93
+ }
94
+
95
+ function _iterableToArray(iter) {
96
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
97
+ }
98
+
99
+ function _unsupportedIterableToArray(o, minLen) {
100
+ if (!o) return;
101
+ if (typeof o === "string") return _arrayLikeToArray(o, minLen);
102
+ var n = Object.prototype.toString.call(o).slice(8, -1);
103
+ if (n === "Object" && o.constructor) n = o.constructor.name;
104
+ if (n === "Map" || n === "Set") return Array.from(o);
105
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
106
+ }
107
+
108
+ function _nonIterableSpread() {
109
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
110
+ }
111
+
112
+ function _toConsumableArray(arr) {
113
+ return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
114
+ }
115
+
116
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
117
+ try {
118
+ var info = gen[key](arg);
119
+ var value = info.value;
120
+ } catch (error) {
121
+ reject(error);
122
+ return;
123
+ }
124
+ if (info.done) {
125
+ resolve(value);
126
+ } else {
127
+ Promise.resolve(value).then(_next, _throw);
128
+ }
129
+ }
130
+ function _asyncToGenerator(fn) {
131
+ return function () {
132
+ var self = this,
133
+ args = arguments;
134
+ return new Promise(function (resolve, reject) {
135
+ var gen = fn.apply(self, args);
136
+ function _next(value) {
137
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
138
+ }
139
+ function _throw(err) {
140
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
141
+ }
142
+ _next(undefined);
143
+ });
144
+ };
145
+ }
146
+
147
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
148
+
149
+ var regeneratorRuntime$1 = {exports: {}};
150
+
151
+ var _typeof$1 = {exports: {}};
152
+
153
+ (function (module) {
154
+ function _typeof(obj) {
155
+ "@babel/helpers - typeof";
156
+
157
+ return (module.exports = _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
158
+ return typeof obj;
159
+ } : function (obj) {
160
+ return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
161
+ }, module.exports.__esModule = true, module.exports["default"] = module.exports), _typeof(obj);
162
+ }
163
+ module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports;
164
+ } (_typeof$1));
165
+
166
+ (function (module) {
167
+ var _typeof = _typeof$1.exports["default"];
168
+ function _regeneratorRuntime() {
169
+ module.exports = _regeneratorRuntime = function _regeneratorRuntime() {
170
+ return exports;
171
+ }, module.exports.__esModule = true, module.exports["default"] = module.exports;
172
+ var exports = {},
173
+ Op = Object.prototype,
174
+ hasOwn = Op.hasOwnProperty,
175
+ defineProperty = Object.defineProperty || function (obj, key, desc) {
176
+ obj[key] = desc.value;
177
+ },
178
+ $Symbol = "function" == typeof Symbol ? Symbol : {},
179
+ iteratorSymbol = $Symbol.iterator || "@@iterator",
180
+ asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator",
181
+ toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
182
+ function define(obj, key, value) {
183
+ return Object.defineProperty(obj, key, {
184
+ value: value,
185
+ enumerable: !0,
186
+ configurable: !0,
187
+ writable: !0
188
+ }), obj[key];
189
+ }
190
+ try {
191
+ define({}, "");
192
+ } catch (err) {
193
+ define = function define(obj, key, value) {
194
+ return obj[key] = value;
195
+ };
196
+ }
197
+ function wrap(innerFn, outerFn, self, tryLocsList) {
198
+ var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,
199
+ generator = Object.create(protoGenerator.prototype),
200
+ context = new Context(tryLocsList || []);
201
+ return defineProperty(generator, "_invoke", {
202
+ value: makeInvokeMethod(innerFn, self, context)
203
+ }), generator;
204
+ }
205
+ function tryCatch(fn, obj, arg) {
206
+ try {
207
+ return {
208
+ type: "normal",
209
+ arg: fn.call(obj, arg)
210
+ };
211
+ } catch (err) {
212
+ return {
213
+ type: "throw",
214
+ arg: err
215
+ };
216
+ }
217
+ }
218
+ exports.wrap = wrap;
219
+ var ContinueSentinel = {};
220
+ function Generator() {}
221
+ function GeneratorFunction() {}
222
+ function GeneratorFunctionPrototype() {}
223
+ var IteratorPrototype = {};
224
+ define(IteratorPrototype, iteratorSymbol, function () {
225
+ return this;
226
+ });
227
+ var getProto = Object.getPrototypeOf,
228
+ NativeIteratorPrototype = getProto && getProto(getProto(values([])));
229
+ NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);
230
+ var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
231
+ function defineIteratorMethods(prototype) {
232
+ ["next", "throw", "return"].forEach(function (method) {
233
+ define(prototype, method, function (arg) {
234
+ return this._invoke(method, arg);
235
+ });
236
+ });
237
+ }
238
+ function AsyncIterator(generator, PromiseImpl) {
239
+ function invoke(method, arg, resolve, reject) {
240
+ var record = tryCatch(generator[method], generator, arg);
241
+ if ("throw" !== record.type) {
242
+ var result = record.arg,
243
+ value = result.value;
244
+ return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) {
245
+ invoke("next", value, resolve, reject);
246
+ }, function (err) {
247
+ invoke("throw", err, resolve, reject);
248
+ }) : PromiseImpl.resolve(value).then(function (unwrapped) {
249
+ result.value = unwrapped, resolve(result);
250
+ }, function (error) {
251
+ return invoke("throw", error, resolve, reject);
252
+ });
253
+ }
254
+ reject(record.arg);
255
+ }
256
+ var previousPromise;
257
+ defineProperty(this, "_invoke", {
258
+ value: function value(method, arg) {
259
+ function callInvokeWithMethodAndArg() {
260
+ return new PromiseImpl(function (resolve, reject) {
261
+ invoke(method, arg, resolve, reject);
262
+ });
263
+ }
264
+ return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
265
+ }
266
+ });
267
+ }
268
+ function makeInvokeMethod(innerFn, self, context) {
269
+ var state = "suspendedStart";
270
+ return function (method, arg) {
271
+ if ("executing" === state) throw new Error("Generator is already running");
272
+ if ("completed" === state) {
273
+ if ("throw" === method) throw arg;
274
+ return doneResult();
275
+ }
276
+ for (context.method = method, context.arg = arg;;) {
277
+ var delegate = context.delegate;
278
+ if (delegate) {
279
+ var delegateResult = maybeInvokeDelegate(delegate, context);
280
+ if (delegateResult) {
281
+ if (delegateResult === ContinueSentinel) continue;
282
+ return delegateResult;
283
+ }
284
+ }
285
+ if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) {
286
+ if ("suspendedStart" === state) throw state = "completed", context.arg;
287
+ context.dispatchException(context.arg);
288
+ } else "return" === context.method && context.abrupt("return", context.arg);
289
+ state = "executing";
290
+ var record = tryCatch(innerFn, self, context);
291
+ if ("normal" === record.type) {
292
+ if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue;
293
+ return {
294
+ value: record.arg,
295
+ done: context.done
296
+ };
297
+ }
298
+ "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg);
299
+ }
300
+ };
301
+ }
302
+ function maybeInvokeDelegate(delegate, context) {
303
+ var methodName = context.method,
304
+ method = delegate.iterator[methodName];
305
+ if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel;
306
+ var record = tryCatch(method, delegate.iterator, context.arg);
307
+ if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel;
308
+ var info = record.arg;
309
+ return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel);
310
+ }
311
+ function pushTryEntry(locs) {
312
+ var entry = {
313
+ tryLoc: locs[0]
314
+ };
315
+ 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);
316
+ }
317
+ function resetTryEntry(entry) {
318
+ var record = entry.completion || {};
319
+ record.type = "normal", delete record.arg, entry.completion = record;
320
+ }
321
+ function Context(tryLocsList) {
322
+ this.tryEntries = [{
323
+ tryLoc: "root"
324
+ }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);
325
+ }
326
+ function values(iterable) {
327
+ if (iterable) {
328
+ var iteratorMethod = iterable[iteratorSymbol];
329
+ if (iteratorMethod) return iteratorMethod.call(iterable);
330
+ if ("function" == typeof iterable.next) return iterable;
331
+ if (!isNaN(iterable.length)) {
332
+ var i = -1,
333
+ next = function next() {
334
+ for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;
335
+ return next.value = undefined, next.done = !0, next;
336
+ };
337
+ return next.next = next;
338
+ }
339
+ }
340
+ return {
341
+ next: doneResult
342
+ };
343
+ }
344
+ function doneResult() {
345
+ return {
346
+ value: undefined,
347
+ done: !0
348
+ };
349
+ }
350
+ return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", {
351
+ value: GeneratorFunctionPrototype,
352
+ configurable: !0
353
+ }), defineProperty(GeneratorFunctionPrototype, "constructor", {
354
+ value: GeneratorFunction,
355
+ configurable: !0
356
+ }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) {
357
+ var ctor = "function" == typeof genFun && genFun.constructor;
358
+ return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name));
359
+ }, exports.mark = function (genFun) {
360
+ return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun;
361
+ }, exports.awrap = function (arg) {
362
+ return {
363
+ __await: arg
364
+ };
365
+ }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
366
+ return this;
367
+ }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
368
+ void 0 === PromiseImpl && (PromiseImpl = Promise);
369
+ var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
370
+ return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {
371
+ return result.done ? result.value : iter.next();
372
+ });
373
+ }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () {
374
+ return this;
375
+ }), define(Gp, "toString", function () {
376
+ return "[object Generator]";
377
+ }), exports.keys = function (val) {
378
+ var object = Object(val),
379
+ keys = [];
380
+ for (var key in object) keys.push(key);
381
+ return keys.reverse(), function next() {
382
+ for (; keys.length;) {
383
+ var key = keys.pop();
384
+ if (key in object) return next.value = key, next.done = !1, next;
385
+ }
386
+ return next.done = !0, next;
387
+ };
388
+ }, exports.values = values, Context.prototype = {
389
+ constructor: Context,
390
+ reset: function reset(skipTempReset) {
391
+ if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined);
392
+ },
393
+ stop: function stop() {
394
+ this.done = !0;
395
+ var rootRecord = this.tryEntries[0].completion;
396
+ if ("throw" === rootRecord.type) throw rootRecord.arg;
397
+ return this.rval;
398
+ },
399
+ dispatchException: function dispatchException(exception) {
400
+ if (this.done) throw exception;
401
+ var context = this;
402
+ function handle(loc, caught) {
403
+ return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught;
404
+ }
405
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
406
+ var entry = this.tryEntries[i],
407
+ record = entry.completion;
408
+ if ("root" === entry.tryLoc) return handle("end");
409
+ if (entry.tryLoc <= this.prev) {
410
+ var hasCatch = hasOwn.call(entry, "catchLoc"),
411
+ hasFinally = hasOwn.call(entry, "finallyLoc");
412
+ if (hasCatch && hasFinally) {
413
+ if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
414
+ if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
415
+ } else if (hasCatch) {
416
+ if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
417
+ } else {
418
+ if (!hasFinally) throw new Error("try statement without catch or finally");
419
+ if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
420
+ }
421
+ }
422
+ }
423
+ },
424
+ abrupt: function abrupt(type, arg) {
425
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
426
+ var entry = this.tryEntries[i];
427
+ if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
428
+ var finallyEntry = entry;
429
+ break;
430
+ }
431
+ }
432
+ finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);
433
+ var record = finallyEntry ? finallyEntry.completion : {};
434
+ return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);
435
+ },
436
+ complete: function complete(record, afterLoc) {
437
+ if ("throw" === record.type) throw record.arg;
438
+ return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel;
439
+ },
440
+ finish: function finish(finallyLoc) {
441
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
442
+ var entry = this.tryEntries[i];
443
+ if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;
444
+ }
445
+ },
446
+ "catch": function _catch(tryLoc) {
447
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
448
+ var entry = this.tryEntries[i];
449
+ if (entry.tryLoc === tryLoc) {
450
+ var record = entry.completion;
451
+ if ("throw" === record.type) {
452
+ var thrown = record.arg;
453
+ resetTryEntry(entry);
454
+ }
455
+ return thrown;
456
+ }
457
+ }
458
+ throw new Error("illegal catch attempt");
459
+ },
460
+ delegateYield: function delegateYield(iterable, resultName, nextLoc) {
461
+ return this.delegate = {
462
+ iterator: values(iterable),
463
+ resultName: resultName,
464
+ nextLoc: nextLoc
465
+ }, "next" === this.method && (this.arg = undefined), ContinueSentinel;
466
+ }
467
+ }, exports;
468
+ }
469
+ module.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports["default"] = module.exports;
470
+ } (regeneratorRuntime$1));
471
+
472
+ // TODO(Babel 8): Remove this file.
473
+
474
+ var runtime = regeneratorRuntime$1.exports();
475
+ var regenerator = runtime;
476
+
477
+ // Copied from https://github.com/facebook/regenerator/blob/main/packages/runtime/runtime.js#L736=
478
+ try {
479
+ regeneratorRuntime = runtime;
480
+ } catch (accidentalStrictMode) {
481
+ if (typeof globalThis === "object") {
482
+ globalThis.regeneratorRuntime = runtime;
483
+ } else {
484
+ Function("r", "regeneratorRuntime = r")(runtime);
485
+ }
486
+ }
487
+
488
+ var FilePicker = function FilePicker(_ref) {
489
+ var _ref$types = _ref.types,
490
+ types = _ref$types === void 0 ? [] : _ref$types,
491
+ onChange = _ref.onChange,
492
+ children = _ref.children;
493
+ var inputRef = useRef();
494
+ var accept = types.reduce(function (acc, ext) {
495
+ return "".concat(acc, ", ").concat(ext);
496
+ }, "");
497
+ var handleInputChange = function handleInputChange(_ref2) {
498
+ var target = _ref2.target;
499
+ if (!target.files) return;
500
+ onChange(target.files);
501
+
502
+ // This will trigger handleClick when same file is uploaded again.
503
+ inputRef.current.value = "";
504
+ handleClick();
505
+ };
506
+ var handleClick = function handleClick() {
507
+ if (!inputRef.current) return;
508
+ inputRef.current.click();
509
+ };
510
+ return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
511
+ onClick: handleClick
512
+ }, children), /*#__PURE__*/React.createElement("input", {
513
+ accept: accept,
514
+ className: "hidden",
515
+ ref: inputRef,
516
+ type: "file",
517
+ onChange: handleInputChange
518
+ }));
519
+ };
520
+
521
+ var papaparse = {exports: {}};
522
+
523
+ /* @license
524
+ Papa Parse
525
+ v5.4.0
526
+ https://github.com/mholt/PapaParse
527
+ License: MIT
528
+ */
529
+
530
+ (function (module, exports) {
531
+ (function(root, factory)
532
+ {
533
+ /* globals define */
534
+ {
535
+ // Node. Does not work with strict CommonJS, but
536
+ // only CommonJS-like environments that support module.exports,
537
+ // like Node.
538
+ module.exports = factory();
539
+ }
540
+ // in strict mode we cannot access arguments.callee, so we need a named reference to
541
+ // stringify the factory method for the blob worker
542
+ // eslint-disable-next-line func-name
543
+ }(commonjsGlobal, function moduleFactory()
544
+ {
545
+
546
+ var global = (function() {
547
+ // alternative method, similar to `Function('return this')()`
548
+ // but without using `eval` (which is disabled when
549
+ // using Content Security Policy).
550
+
551
+ if (typeof self !== 'undefined') { return self; }
552
+ if (typeof window !== 'undefined') { return window; }
553
+ if (typeof global !== 'undefined') { return global; }
554
+
555
+ // When running tests none of the above have been defined
556
+ return {};
557
+ })();
558
+
559
+
560
+ function getWorkerBlob() {
561
+ var URL = global.URL || global.webkitURL || null;
562
+ var code = moduleFactory.toString();
563
+ return Papa.BLOB_URL || (Papa.BLOB_URL = URL.createObjectURL(new Blob(["var global = (function() { if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } if (typeof global !== 'undefined') { return global; } return {}; })(); global.IS_PAPA_WORKER=true; ", '(', code, ')();'], {type: 'text/javascript'})));
564
+ }
565
+
566
+ var IS_WORKER = !global.document && !!global.postMessage,
567
+ IS_PAPA_WORKER = global.IS_PAPA_WORKER || false;
568
+
569
+ var workers = {}, workerIdCounter = 0;
570
+
571
+ var Papa = {};
572
+
573
+ Papa.parse = CsvToJson;
574
+ Papa.unparse = JsonToCsv;
575
+
576
+ Papa.RECORD_SEP = String.fromCharCode(30);
577
+ Papa.UNIT_SEP = String.fromCharCode(31);
578
+ Papa.BYTE_ORDER_MARK = '\ufeff';
579
+ Papa.BAD_DELIMITERS = ['\r', '\n', '"', Papa.BYTE_ORDER_MARK];
580
+ Papa.WORKERS_SUPPORTED = !IS_WORKER && !!global.Worker;
581
+ Papa.NODE_STREAM_INPUT = 1;
582
+
583
+ // Configurable chunk sizes for local and remote files, respectively
584
+ Papa.LocalChunkSize = 1024 * 1024 * 10; // 10 MB
585
+ Papa.RemoteChunkSize = 1024 * 1024 * 5; // 5 MB
586
+ Papa.DefaultDelimiter = ','; // Used if not specified and detection fails
587
+
588
+ // Exposed for testing and development only
589
+ Papa.Parser = Parser;
590
+ Papa.ParserHandle = ParserHandle;
591
+ Papa.NetworkStreamer = NetworkStreamer;
592
+ Papa.FileStreamer = FileStreamer;
593
+ Papa.StringStreamer = StringStreamer;
594
+ Papa.ReadableStreamStreamer = ReadableStreamStreamer;
595
+ if (typeof PAPA_BROWSER_CONTEXT === 'undefined') {
596
+ Papa.DuplexStreamStreamer = DuplexStreamStreamer;
597
+ }
598
+
599
+ if (global.jQuery)
600
+ {
601
+ var $ = global.jQuery;
602
+ $.fn.parse = function(options)
603
+ {
604
+ var config = options.config || {};
605
+ var queue = [];
606
+
607
+ this.each(function(idx)
608
+ {
609
+ var supported = $(this).prop('tagName').toUpperCase() === 'INPUT'
610
+ && $(this).attr('type').toLowerCase() === 'file'
611
+ && global.FileReader;
612
+
613
+ if (!supported || !this.files || this.files.length === 0)
614
+ return true; // continue to next input element
615
+
616
+ for (var i = 0; i < this.files.length; i++)
617
+ {
618
+ queue.push({
619
+ file: this.files[i],
620
+ inputElem: this,
621
+ instanceConfig: $.extend({}, config)
622
+ });
623
+ }
624
+ });
625
+
626
+ parseNextFile(); // begin parsing
627
+ return this; // maintains chainability
628
+
629
+
630
+ function parseNextFile()
631
+ {
632
+ if (queue.length === 0)
633
+ {
634
+ if (isFunction(options.complete))
635
+ options.complete();
636
+ return;
637
+ }
638
+
639
+ var f = queue[0];
640
+
641
+ if (isFunction(options.before))
642
+ {
643
+ var returned = options.before(f.file, f.inputElem);
644
+
645
+ if (typeof returned === 'object')
646
+ {
647
+ if (returned.action === 'abort')
648
+ {
649
+ error('AbortError', f.file, f.inputElem, returned.reason);
650
+ return; // Aborts all queued files immediately
651
+ }
652
+ else if (returned.action === 'skip')
653
+ {
654
+ fileComplete(); // parse the next file in the queue, if any
655
+ return;
656
+ }
657
+ else if (typeof returned.config === 'object')
658
+ f.instanceConfig = $.extend(f.instanceConfig, returned.config);
659
+ }
660
+ else if (returned === 'skip')
661
+ {
662
+ fileComplete(); // parse the next file in the queue, if any
663
+ return;
664
+ }
665
+ }
666
+
667
+ // Wrap up the user's complete callback, if any, so that ours also gets executed
668
+ var userCompleteFunc = f.instanceConfig.complete;
669
+ f.instanceConfig.complete = function(results)
670
+ {
671
+ if (isFunction(userCompleteFunc))
672
+ userCompleteFunc(results, f.file, f.inputElem);
673
+ fileComplete();
674
+ };
675
+
676
+ Papa.parse(f.file, f.instanceConfig);
677
+ }
678
+
679
+ function error(name, file, elem, reason)
680
+ {
681
+ if (isFunction(options.error))
682
+ options.error({name: name}, file, elem, reason);
683
+ }
684
+
685
+ function fileComplete()
686
+ {
687
+ queue.splice(0, 1);
688
+ parseNextFile();
689
+ }
690
+ };
691
+ }
692
+
693
+
694
+ if (IS_PAPA_WORKER)
695
+ {
696
+ global.onmessage = workerThreadReceivedMessage;
697
+ }
698
+
699
+
700
+
701
+
702
+ function CsvToJson(_input, _config)
703
+ {
704
+ _config = _config || {};
705
+ var dynamicTyping = _config.dynamicTyping || false;
706
+ if (isFunction(dynamicTyping)) {
707
+ _config.dynamicTypingFunction = dynamicTyping;
708
+ // Will be filled on first row call
709
+ dynamicTyping = {};
710
+ }
711
+ _config.dynamicTyping = dynamicTyping;
712
+
713
+ _config.transform = isFunction(_config.transform) ? _config.transform : false;
714
+
715
+ if (_config.worker && Papa.WORKERS_SUPPORTED)
716
+ {
717
+ var w = newWorker();
718
+
719
+ w.userStep = _config.step;
720
+ w.userChunk = _config.chunk;
721
+ w.userComplete = _config.complete;
722
+ w.userError = _config.error;
723
+
724
+ _config.step = isFunction(_config.step);
725
+ _config.chunk = isFunction(_config.chunk);
726
+ _config.complete = isFunction(_config.complete);
727
+ _config.error = isFunction(_config.error);
728
+ delete _config.worker; // prevent infinite loop
729
+
730
+ w.postMessage({
731
+ input: _input,
732
+ config: _config,
733
+ workerId: w.id
734
+ });
735
+
736
+ return;
737
+ }
738
+
739
+ var streamer = null;
740
+ if (_input === Papa.NODE_STREAM_INPUT && typeof PAPA_BROWSER_CONTEXT === 'undefined')
741
+ {
742
+ // create a node Duplex stream for use
743
+ // with .pipe
744
+ streamer = new DuplexStreamStreamer(_config);
745
+ return streamer.getStream();
746
+ }
747
+ else if (typeof _input === 'string')
748
+ {
749
+ _input = stripBom(_input);
750
+ if (_config.download)
751
+ streamer = new NetworkStreamer(_config);
752
+ else
753
+ streamer = new StringStreamer(_config);
754
+ }
755
+ else if (_input.readable === true && isFunction(_input.read) && isFunction(_input.on))
756
+ {
757
+ streamer = new ReadableStreamStreamer(_config);
758
+ }
759
+ else if ((global.File && _input instanceof File) || _input instanceof Object) // ...Safari. (see issue #106)
760
+ streamer = new FileStreamer(_config);
761
+
762
+ return streamer.stream(_input);
763
+
764
+ // Strip character from UTF-8 BOM encoded files that cause issue parsing the file
765
+ function stripBom(string) {
766
+ if (string.charCodeAt(0) === 0xfeff) {
767
+ return string.slice(1);
768
+ }
769
+ return string;
770
+ }
771
+ }
772
+
773
+
774
+
775
+
776
+
777
+
778
+ function JsonToCsv(_input, _config)
779
+ {
780
+ // Default configuration
781
+
782
+ /** whether to surround every datum with quotes */
783
+ var _quotes = false;
784
+
785
+ /** whether to write headers */
786
+ var _writeHeader = true;
787
+
788
+ /** delimiting character(s) */
789
+ var _delimiter = ',';
790
+
791
+ /** newline character(s) */
792
+ var _newline = '\r\n';
793
+
794
+ /** quote character */
795
+ var _quoteChar = '"';
796
+
797
+ /** escaped quote character, either "" or <config.escapeChar>" */
798
+ var _escapedQuote = _quoteChar + _quoteChar;
799
+
800
+ /** whether to skip empty lines */
801
+ var _skipEmptyLines = false;
802
+
803
+ /** the columns (keys) we expect when we unparse objects */
804
+ var _columns = null;
805
+
806
+ /** whether to prevent outputting cells that can be parsed as formulae by spreadsheet software (Excel and LibreOffice) */
807
+ var _escapeFormulae = false;
808
+
809
+ unpackConfig();
810
+
811
+ var quoteCharRegex = new RegExp(escapeRegExp(_quoteChar), 'g');
812
+
813
+ if (typeof _input === 'string')
814
+ _input = JSON.parse(_input);
815
+
816
+ if (Array.isArray(_input))
817
+ {
818
+ if (!_input.length || Array.isArray(_input[0]))
819
+ return serialize(null, _input, _skipEmptyLines);
820
+ else if (typeof _input[0] === 'object')
821
+ return serialize(_columns || Object.keys(_input[0]), _input, _skipEmptyLines);
822
+ }
823
+ else if (typeof _input === 'object')
824
+ {
825
+ if (typeof _input.data === 'string')
826
+ _input.data = JSON.parse(_input.data);
827
+
828
+ if (Array.isArray(_input.data))
829
+ {
830
+ if (!_input.fields)
831
+ _input.fields = _input.meta && _input.meta.fields || _columns;
832
+
833
+ if (!_input.fields)
834
+ _input.fields = Array.isArray(_input.data[0])
835
+ ? _input.fields
836
+ : typeof _input.data[0] === 'object'
837
+ ? Object.keys(_input.data[0])
838
+ : [];
839
+
840
+ if (!(Array.isArray(_input.data[0])) && typeof _input.data[0] !== 'object')
841
+ _input.data = [_input.data]; // handles input like [1,2,3] or ['asdf']
842
+ }
843
+
844
+ return serialize(_input.fields || [], _input.data || [], _skipEmptyLines);
845
+ }
846
+
847
+ // Default (any valid paths should return before this)
848
+ throw new Error('Unable to serialize unrecognized input');
849
+
850
+
851
+ function unpackConfig()
852
+ {
853
+ if (typeof _config !== 'object')
854
+ return;
855
+
856
+ if (typeof _config.delimiter === 'string'
857
+ && !Papa.BAD_DELIMITERS.filter(function(value) { return _config.delimiter.indexOf(value) !== -1; }).length)
858
+ {
859
+ _delimiter = _config.delimiter;
860
+ }
861
+
862
+ if (typeof _config.quotes === 'boolean'
863
+ || typeof _config.quotes === 'function'
864
+ || Array.isArray(_config.quotes))
865
+ _quotes = _config.quotes;
866
+
867
+ if (typeof _config.skipEmptyLines === 'boolean'
868
+ || typeof _config.skipEmptyLines === 'string')
869
+ _skipEmptyLines = _config.skipEmptyLines;
870
+
871
+ if (typeof _config.newline === 'string')
872
+ _newline = _config.newline;
873
+
874
+ if (typeof _config.quoteChar === 'string')
875
+ _quoteChar = _config.quoteChar;
876
+
877
+ if (typeof _config.header === 'boolean')
878
+ _writeHeader = _config.header;
879
+
880
+ if (Array.isArray(_config.columns)) {
881
+
882
+ if (_config.columns.length === 0) throw new Error('Option columns is empty');
883
+
884
+ _columns = _config.columns;
885
+ }
886
+
887
+ if (_config.escapeChar !== undefined) {
888
+ _escapedQuote = _config.escapeChar + _quoteChar;
889
+ }
890
+
891
+ if (typeof _config.escapeFormulae === 'boolean' || _config.escapeFormulae instanceof RegExp) {
892
+ _escapeFormulae = _config.escapeFormulae instanceof RegExp ? _config.escapeFormulae : /^[=+\-@\t\r].*$/;
893
+ }
894
+ }
895
+
896
+ /** The double for loop that iterates the data and writes out a CSV string including header row */
897
+ function serialize(fields, data, skipEmptyLines)
898
+ {
899
+ var csv = '';
900
+
901
+ if (typeof fields === 'string')
902
+ fields = JSON.parse(fields);
903
+ if (typeof data === 'string')
904
+ data = JSON.parse(data);
905
+
906
+ var hasHeader = Array.isArray(fields) && fields.length > 0;
907
+ var dataKeyedByField = !(Array.isArray(data[0]));
908
+
909
+ // If there a header row, write it first
910
+ if (hasHeader && _writeHeader)
911
+ {
912
+ for (var i = 0; i < fields.length; i++)
913
+ {
914
+ if (i > 0)
915
+ csv += _delimiter;
916
+ csv += safe(fields[i], i);
917
+ }
918
+ if (data.length > 0)
919
+ csv += _newline;
920
+ }
921
+
922
+ // Then write out the data
923
+ for (var row = 0; row < data.length; row++)
924
+ {
925
+ var maxCol = hasHeader ? fields.length : data[row].length;
926
+
927
+ var emptyLine = false;
928
+ var nullLine = hasHeader ? Object.keys(data[row]).length === 0 : data[row].length === 0;
929
+ if (skipEmptyLines && !hasHeader)
930
+ {
931
+ emptyLine = skipEmptyLines === 'greedy' ? data[row].join('').trim() === '' : data[row].length === 1 && data[row][0].length === 0;
932
+ }
933
+ if (skipEmptyLines === 'greedy' && hasHeader) {
934
+ var line = [];
935
+ for (var c = 0; c < maxCol; c++) {
936
+ var cx = dataKeyedByField ? fields[c] : c;
937
+ line.push(data[row][cx]);
938
+ }
939
+ emptyLine = line.join('').trim() === '';
940
+ }
941
+ if (!emptyLine)
942
+ {
943
+ for (var col = 0; col < maxCol; col++)
944
+ {
945
+ if (col > 0 && !nullLine)
946
+ csv += _delimiter;
947
+ var colIdx = hasHeader && dataKeyedByField ? fields[col] : col;
948
+ csv += safe(data[row][colIdx], col);
949
+ }
950
+ if (row < data.length - 1 && (!skipEmptyLines || (maxCol > 0 && !nullLine)))
951
+ {
952
+ csv += _newline;
953
+ }
954
+ }
955
+ }
956
+ return csv;
957
+ }
958
+
959
+ /** Encloses a value around quotes if needed (makes a value safe for CSV insertion) */
960
+ function safe(str, col)
961
+ {
962
+ if (typeof str === 'undefined' || str === null)
963
+ return '';
964
+
965
+ if (str.constructor === Date)
966
+ return JSON.stringify(str).slice(1, 25);
967
+
968
+ var needsQuotes = false;
969
+
970
+ if (_escapeFormulae && typeof str === "string" && _escapeFormulae.test(str)) {
971
+ str = "'" + str;
972
+ needsQuotes = true;
973
+ }
974
+
975
+ var escapedQuoteStr = str.toString().replace(quoteCharRegex, _escapedQuote);
976
+
977
+ needsQuotes = needsQuotes
978
+ || _quotes === true
979
+ || (typeof _quotes === 'function' && _quotes(str, col))
980
+ || (Array.isArray(_quotes) && _quotes[col])
981
+ || hasAny(escapedQuoteStr, Papa.BAD_DELIMITERS)
982
+ || escapedQuoteStr.indexOf(_delimiter) > -1
983
+ || escapedQuoteStr.charAt(0) === ' '
984
+ || escapedQuoteStr.charAt(escapedQuoteStr.length - 1) === ' ';
985
+
986
+ return needsQuotes ? _quoteChar + escapedQuoteStr + _quoteChar : escapedQuoteStr;
987
+ }
988
+
989
+ function hasAny(str, substrings)
990
+ {
991
+ for (var i = 0; i < substrings.length; i++)
992
+ if (str.indexOf(substrings[i]) > -1)
993
+ return true;
994
+ return false;
995
+ }
996
+ }
997
+
998
+ /** ChunkStreamer is the base prototype for various streamer implementations. */
999
+ function ChunkStreamer(config)
1000
+ {
1001
+ this._handle = null;
1002
+ this._finished = false;
1003
+ this._completed = false;
1004
+ this._halted = false;
1005
+ this._input = null;
1006
+ this._baseIndex = 0;
1007
+ this._partialLine = '';
1008
+ this._rowCount = 0;
1009
+ this._start = 0;
1010
+ this._nextChunk = null;
1011
+ this.isFirstChunk = true;
1012
+ this._completeResults = {
1013
+ data: [],
1014
+ errors: [],
1015
+ meta: {}
1016
+ };
1017
+ replaceConfig.call(this, config);
1018
+
1019
+ this.parseChunk = function(chunk, isFakeChunk)
1020
+ {
1021
+ // First chunk pre-processing
1022
+ if (this.isFirstChunk && isFunction(this._config.beforeFirstChunk))
1023
+ {
1024
+ var modifiedChunk = this._config.beforeFirstChunk(chunk);
1025
+ if (modifiedChunk !== undefined)
1026
+ chunk = modifiedChunk;
1027
+ }
1028
+ this.isFirstChunk = false;
1029
+ this._halted = false;
1030
+
1031
+ // Rejoin the line we likely just split in two by chunking the file
1032
+ var aggregate = this._partialLine + chunk;
1033
+ this._partialLine = '';
1034
+
1035
+ var results = this._handle.parse(aggregate, this._baseIndex, !this._finished);
1036
+
1037
+ if (this._handle.paused() || this._handle.aborted()) {
1038
+ this._halted = true;
1039
+ return;
1040
+ }
1041
+
1042
+ var lastIndex = results.meta.cursor;
1043
+
1044
+ if (!this._finished)
1045
+ {
1046
+ this._partialLine = aggregate.substring(lastIndex - this._baseIndex);
1047
+ this._baseIndex = lastIndex;
1048
+ }
1049
+
1050
+ if (results && results.data)
1051
+ this._rowCount += results.data.length;
1052
+
1053
+ var finishedIncludingPreview = this._finished || (this._config.preview && this._rowCount >= this._config.preview);
1054
+
1055
+ if (IS_PAPA_WORKER)
1056
+ {
1057
+ global.postMessage({
1058
+ results: results,
1059
+ workerId: Papa.WORKER_ID,
1060
+ finished: finishedIncludingPreview
1061
+ });
1062
+ }
1063
+ else if (isFunction(this._config.chunk) && !isFakeChunk)
1064
+ {
1065
+ this._config.chunk(results, this._handle);
1066
+ if (this._handle.paused() || this._handle.aborted()) {
1067
+ this._halted = true;
1068
+ return;
1069
+ }
1070
+ results = undefined;
1071
+ this._completeResults = undefined;
1072
+ }
1073
+
1074
+ if (!this._config.step && !this._config.chunk) {
1075
+ this._completeResults.data = this._completeResults.data.concat(results.data);
1076
+ this._completeResults.errors = this._completeResults.errors.concat(results.errors);
1077
+ this._completeResults.meta = results.meta;
1078
+ }
1079
+
1080
+ if (!this._completed && finishedIncludingPreview && isFunction(this._config.complete) && (!results || !results.meta.aborted)) {
1081
+ this._config.complete(this._completeResults, this._input);
1082
+ this._completed = true;
1083
+ }
1084
+
1085
+ if (!finishedIncludingPreview && (!results || !results.meta.paused))
1086
+ this._nextChunk();
1087
+
1088
+ return results;
1089
+ };
1090
+
1091
+ this._sendError = function(error)
1092
+ {
1093
+ if (isFunction(this._config.error))
1094
+ this._config.error(error);
1095
+ else if (IS_PAPA_WORKER && this._config.error)
1096
+ {
1097
+ global.postMessage({
1098
+ workerId: Papa.WORKER_ID,
1099
+ error: error,
1100
+ finished: false
1101
+ });
1102
+ }
1103
+ };
1104
+
1105
+ function replaceConfig(config)
1106
+ {
1107
+ // Deep-copy the config so we can edit it
1108
+ var configCopy = copy(config);
1109
+ configCopy.chunkSize = parseInt(configCopy.chunkSize); // parseInt VERY important so we don't concatenate strings!
1110
+ if (!config.step && !config.chunk)
1111
+ configCopy.chunkSize = null; // disable Range header if not streaming; bad values break IIS - see issue #196
1112
+ this._handle = new ParserHandle(configCopy);
1113
+ this._handle.streamer = this;
1114
+ this._config = configCopy; // persist the copy to the caller
1115
+ }
1116
+ }
1117
+
1118
+
1119
+ function NetworkStreamer(config)
1120
+ {
1121
+ config = config || {};
1122
+ if (!config.chunkSize)
1123
+ config.chunkSize = Papa.RemoteChunkSize;
1124
+ ChunkStreamer.call(this, config);
1125
+
1126
+ var xhr;
1127
+
1128
+ if (IS_WORKER)
1129
+ {
1130
+ this._nextChunk = function()
1131
+ {
1132
+ this._readChunk();
1133
+ this._chunkLoaded();
1134
+ };
1135
+ }
1136
+ else
1137
+ {
1138
+ this._nextChunk = function()
1139
+ {
1140
+ this._readChunk();
1141
+ };
1142
+ }
1143
+
1144
+ this.stream = function(url)
1145
+ {
1146
+ this._input = url;
1147
+ this._nextChunk(); // Starts streaming
1148
+ };
1149
+
1150
+ this._readChunk = function()
1151
+ {
1152
+ if (this._finished)
1153
+ {
1154
+ this._chunkLoaded();
1155
+ return;
1156
+ }
1157
+
1158
+ xhr = new XMLHttpRequest();
1159
+
1160
+ if (this._config.withCredentials)
1161
+ {
1162
+ xhr.withCredentials = this._config.withCredentials;
1163
+ }
1164
+
1165
+ if (!IS_WORKER)
1166
+ {
1167
+ xhr.onload = bindFunction(this._chunkLoaded, this);
1168
+ xhr.onerror = bindFunction(this._chunkError, this);
1169
+ }
1170
+
1171
+ xhr.open(this._config.downloadRequestBody ? 'POST' : 'GET', this._input, !IS_WORKER);
1172
+ // Headers can only be set when once the request state is OPENED
1173
+ if (this._config.downloadRequestHeaders)
1174
+ {
1175
+ var headers = this._config.downloadRequestHeaders;
1176
+
1177
+ for (var headerName in headers)
1178
+ {
1179
+ xhr.setRequestHeader(headerName, headers[headerName]);
1180
+ }
1181
+ }
1182
+
1183
+ if (this._config.chunkSize)
1184
+ {
1185
+ var end = this._start + this._config.chunkSize - 1; // minus one because byte range is inclusive
1186
+ xhr.setRequestHeader('Range', 'bytes=' + this._start + '-' + end);
1187
+ }
1188
+
1189
+ try {
1190
+ xhr.send(this._config.downloadRequestBody);
1191
+ }
1192
+ catch (err) {
1193
+ this._chunkError(err.message);
1194
+ }
1195
+
1196
+ if (IS_WORKER && xhr.status === 0)
1197
+ this._chunkError();
1198
+ };
1199
+
1200
+ this._chunkLoaded = function()
1201
+ {
1202
+ if (xhr.readyState !== 4)
1203
+ return;
1204
+
1205
+ if (xhr.status < 200 || xhr.status >= 400)
1206
+ {
1207
+ this._chunkError();
1208
+ return;
1209
+ }
1210
+
1211
+ // Use chunckSize as it may be a diference on reponse lentgh due to characters with more than 1 byte
1212
+ this._start += this._config.chunkSize ? this._config.chunkSize : xhr.responseText.length;
1213
+ this._finished = !this._config.chunkSize || this._start >= getFileSize(xhr);
1214
+ this.parseChunk(xhr.responseText);
1215
+ };
1216
+
1217
+ this._chunkError = function(errorMessage)
1218
+ {
1219
+ var errorText = xhr.statusText || errorMessage;
1220
+ this._sendError(new Error(errorText));
1221
+ };
1222
+
1223
+ function getFileSize(xhr)
1224
+ {
1225
+ var contentRange = xhr.getResponseHeader('Content-Range');
1226
+ if (contentRange === null) { // no content range, then finish!
1227
+ return -1;
1228
+ }
1229
+ return parseInt(contentRange.substring(contentRange.lastIndexOf('/') + 1));
1230
+ }
1231
+ }
1232
+ NetworkStreamer.prototype = Object.create(ChunkStreamer.prototype);
1233
+ NetworkStreamer.prototype.constructor = NetworkStreamer;
1234
+
1235
+
1236
+ function FileStreamer(config)
1237
+ {
1238
+ config = config || {};
1239
+ if (!config.chunkSize)
1240
+ config.chunkSize = Papa.LocalChunkSize;
1241
+ ChunkStreamer.call(this, config);
1242
+
1243
+ var reader, slice;
1244
+
1245
+ // FileReader is better than FileReaderSync (even in worker) - see http://stackoverflow.com/q/24708649/1048862
1246
+ // But Firefox is a pill, too - see issue #76: https://github.com/mholt/PapaParse/issues/76
1247
+ var usingAsyncReader = typeof FileReader !== 'undefined'; // Safari doesn't consider it a function - see issue #105
1248
+
1249
+ this.stream = function(file)
1250
+ {
1251
+ this._input = file;
1252
+ slice = file.slice || file.webkitSlice || file.mozSlice;
1253
+
1254
+ if (usingAsyncReader)
1255
+ {
1256
+ reader = new FileReader(); // Preferred method of reading files, even in workers
1257
+ reader.onload = bindFunction(this._chunkLoaded, this);
1258
+ reader.onerror = bindFunction(this._chunkError, this);
1259
+ }
1260
+ else
1261
+ reader = new FileReaderSync(); // Hack for running in a web worker in Firefox
1262
+
1263
+ this._nextChunk(); // Starts streaming
1264
+ };
1265
+
1266
+ this._nextChunk = function()
1267
+ {
1268
+ if (!this._finished && (!this._config.preview || this._rowCount < this._config.preview))
1269
+ this._readChunk();
1270
+ };
1271
+
1272
+ this._readChunk = function()
1273
+ {
1274
+ var input = this._input;
1275
+ if (this._config.chunkSize)
1276
+ {
1277
+ var end = Math.min(this._start + this._config.chunkSize, this._input.size);
1278
+ input = slice.call(input, this._start, end);
1279
+ }
1280
+ var txt = reader.readAsText(input, this._config.encoding);
1281
+ if (!usingAsyncReader)
1282
+ this._chunkLoaded({ target: { result: txt } }); // mimic the async signature
1283
+ };
1284
+
1285
+ this._chunkLoaded = function(event)
1286
+ {
1287
+ // Very important to increment start each time before handling results
1288
+ this._start += this._config.chunkSize;
1289
+ this._finished = !this._config.chunkSize || this._start >= this._input.size;
1290
+ this.parseChunk(event.target.result);
1291
+ };
1292
+
1293
+ this._chunkError = function()
1294
+ {
1295
+ this._sendError(reader.error);
1296
+ };
1297
+
1298
+ }
1299
+ FileStreamer.prototype = Object.create(ChunkStreamer.prototype);
1300
+ FileStreamer.prototype.constructor = FileStreamer;
1301
+
1302
+
1303
+ function StringStreamer(config)
1304
+ {
1305
+ config = config || {};
1306
+ ChunkStreamer.call(this, config);
1307
+
1308
+ var remaining;
1309
+ this.stream = function(s)
1310
+ {
1311
+ remaining = s;
1312
+ return this._nextChunk();
1313
+ };
1314
+ this._nextChunk = function()
1315
+ {
1316
+ if (this._finished) return;
1317
+ var size = this._config.chunkSize;
1318
+ var chunk;
1319
+ if(size) {
1320
+ chunk = remaining.substring(0, size);
1321
+ remaining = remaining.substring(size);
1322
+ } else {
1323
+ chunk = remaining;
1324
+ remaining = '';
1325
+ }
1326
+ this._finished = !remaining;
1327
+ return this.parseChunk(chunk);
1328
+ };
1329
+ }
1330
+ StringStreamer.prototype = Object.create(StringStreamer.prototype);
1331
+ StringStreamer.prototype.constructor = StringStreamer;
1332
+
1333
+
1334
+ function ReadableStreamStreamer(config)
1335
+ {
1336
+ config = config || {};
1337
+
1338
+ ChunkStreamer.call(this, config);
1339
+
1340
+ var queue = [];
1341
+ var parseOnData = true;
1342
+ var streamHasEnded = false;
1343
+
1344
+ this.pause = function()
1345
+ {
1346
+ ChunkStreamer.prototype.pause.apply(this, arguments);
1347
+ this._input.pause();
1348
+ };
1349
+
1350
+ this.resume = function()
1351
+ {
1352
+ ChunkStreamer.prototype.resume.apply(this, arguments);
1353
+ this._input.resume();
1354
+ };
1355
+
1356
+ this.stream = function(stream)
1357
+ {
1358
+ this._input = stream;
1359
+
1360
+ this._input.on('data', this._streamData);
1361
+ this._input.on('end', this._streamEnd);
1362
+ this._input.on('error', this._streamError);
1363
+ };
1364
+
1365
+ this._checkIsFinished = function()
1366
+ {
1367
+ if (streamHasEnded && queue.length === 1) {
1368
+ this._finished = true;
1369
+ }
1370
+ };
1371
+
1372
+ this._nextChunk = function()
1373
+ {
1374
+ this._checkIsFinished();
1375
+ if (queue.length)
1376
+ {
1377
+ this.parseChunk(queue.shift());
1378
+ }
1379
+ else
1380
+ {
1381
+ parseOnData = true;
1382
+ }
1383
+ };
1384
+
1385
+ this._streamData = bindFunction(function(chunk)
1386
+ {
1387
+ try
1388
+ {
1389
+ queue.push(typeof chunk === 'string' ? chunk : chunk.toString(this._config.encoding));
1390
+
1391
+ if (parseOnData)
1392
+ {
1393
+ parseOnData = false;
1394
+ this._checkIsFinished();
1395
+ this.parseChunk(queue.shift());
1396
+ }
1397
+ }
1398
+ catch (error)
1399
+ {
1400
+ this._streamError(error);
1401
+ }
1402
+ }, this);
1403
+
1404
+ this._streamError = bindFunction(function(error)
1405
+ {
1406
+ this._streamCleanUp();
1407
+ this._sendError(error);
1408
+ }, this);
1409
+
1410
+ this._streamEnd = bindFunction(function()
1411
+ {
1412
+ this._streamCleanUp();
1413
+ streamHasEnded = true;
1414
+ this._streamData('');
1415
+ }, this);
1416
+
1417
+ this._streamCleanUp = bindFunction(function()
1418
+ {
1419
+ this._input.removeListener('data', this._streamData);
1420
+ this._input.removeListener('end', this._streamEnd);
1421
+ this._input.removeListener('error', this._streamError);
1422
+ }, this);
1423
+ }
1424
+ ReadableStreamStreamer.prototype = Object.create(ChunkStreamer.prototype);
1425
+ ReadableStreamStreamer.prototype.constructor = ReadableStreamStreamer;
1426
+
1427
+
1428
+ function DuplexStreamStreamer(_config) {
1429
+ var Duplex = require$$0.Duplex;
1430
+ var config = copy(_config);
1431
+ var parseOnWrite = true;
1432
+ var writeStreamHasFinished = false;
1433
+ var parseCallbackQueue = [];
1434
+ var stream = null;
1435
+
1436
+ this._onCsvData = function(results)
1437
+ {
1438
+ var data = results.data;
1439
+ if (!stream.push(data) && !this._handle.paused()) {
1440
+ // the writeable consumer buffer has filled up
1441
+ // so we need to pause until more items
1442
+ // can be processed
1443
+ this._handle.pause();
1444
+ }
1445
+ };
1446
+
1447
+ this._onCsvComplete = function()
1448
+ {
1449
+ // node will finish the read stream when
1450
+ // null is pushed
1451
+ stream.push(null);
1452
+ };
1453
+
1454
+ config.step = bindFunction(this._onCsvData, this);
1455
+ config.complete = bindFunction(this._onCsvComplete, this);
1456
+ ChunkStreamer.call(this, config);
1457
+
1458
+ this._nextChunk = function()
1459
+ {
1460
+ if (writeStreamHasFinished && parseCallbackQueue.length === 1) {
1461
+ this._finished = true;
1462
+ }
1463
+ if (parseCallbackQueue.length) {
1464
+ parseCallbackQueue.shift()();
1465
+ } else {
1466
+ parseOnWrite = true;
1467
+ }
1468
+ };
1469
+
1470
+ this._addToParseQueue = function(chunk, callback)
1471
+ {
1472
+ // add to queue so that we can indicate
1473
+ // completion via callback
1474
+ // node will automatically pause the incoming stream
1475
+ // when too many items have been added without their
1476
+ // callback being invoked
1477
+ parseCallbackQueue.push(bindFunction(function() {
1478
+ this.parseChunk(typeof chunk === 'string' ? chunk : chunk.toString(config.encoding));
1479
+ if (isFunction(callback)) {
1480
+ return callback();
1481
+ }
1482
+ }, this));
1483
+ if (parseOnWrite) {
1484
+ parseOnWrite = false;
1485
+ this._nextChunk();
1486
+ }
1487
+ };
1488
+
1489
+ this._onRead = function()
1490
+ {
1491
+ if (this._handle.paused()) {
1492
+ // the writeable consumer can handle more data
1493
+ // so resume the chunk parsing
1494
+ this._handle.resume();
1495
+ }
1496
+ };
1497
+
1498
+ this._onWrite = function(chunk, encoding, callback)
1499
+ {
1500
+ this._addToParseQueue(chunk, callback);
1501
+ };
1502
+
1503
+ this._onWriteComplete = function()
1504
+ {
1505
+ writeStreamHasFinished = true;
1506
+ // have to write empty string
1507
+ // so parser knows its done
1508
+ this._addToParseQueue('');
1509
+ };
1510
+
1511
+ this.getStream = function()
1512
+ {
1513
+ return stream;
1514
+ };
1515
+ stream = new Duplex({
1516
+ readableObjectMode: true,
1517
+ decodeStrings: false,
1518
+ read: bindFunction(this._onRead, this),
1519
+ write: bindFunction(this._onWrite, this)
1520
+ });
1521
+ stream.once('finish', bindFunction(this._onWriteComplete, this));
1522
+ }
1523
+ if (typeof PAPA_BROWSER_CONTEXT === 'undefined') {
1524
+ DuplexStreamStreamer.prototype = Object.create(ChunkStreamer.prototype);
1525
+ DuplexStreamStreamer.prototype.constructor = DuplexStreamStreamer;
1526
+ }
1527
+
1528
+
1529
+ // Use one ParserHandle per entire CSV file or string
1530
+ function ParserHandle(_config)
1531
+ {
1532
+ // One goal is to minimize the use of regular expressions...
1533
+ var MAX_FLOAT = Math.pow(2, 53);
1534
+ var MIN_FLOAT = -MAX_FLOAT;
1535
+ var FLOAT = /^\s*-?(\d+\.?|\.\d+|\d+\.\d+)([eE][-+]?\d+)?\s*$/;
1536
+ var ISO_DATE = /^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/;
1537
+ var self = this;
1538
+ var _stepCounter = 0; // Number of times step was called (number of rows parsed)
1539
+ var _rowCounter = 0; // Number of rows that have been parsed so far
1540
+ var _input; // The input being parsed
1541
+ var _parser; // The core parser being used
1542
+ var _paused = false; // Whether we are paused or not
1543
+ var _aborted = false; // Whether the parser has aborted or not
1544
+ var _delimiterError; // Temporary state between delimiter detection and processing results
1545
+ var _fields = []; // Fields are from the header row of the input, if there is one
1546
+ var _results = { // The last results returned from the parser
1547
+ data: [],
1548
+ errors: [],
1549
+ meta: {}
1550
+ };
1551
+
1552
+ if (isFunction(_config.step))
1553
+ {
1554
+ var userStep = _config.step;
1555
+ _config.step = function(results)
1556
+ {
1557
+ _results = results;
1558
+
1559
+ if (needsHeaderRow())
1560
+ processResults();
1561
+ else // only call user's step function after header row
1562
+ {
1563
+ processResults();
1564
+
1565
+ // It's possbile that this line was empty and there's no row here after all
1566
+ if (_results.data.length === 0)
1567
+ return;
1568
+
1569
+ _stepCounter += results.data.length;
1570
+ if (_config.preview && _stepCounter > _config.preview)
1571
+ _parser.abort();
1572
+ else {
1573
+ _results.data = _results.data[0];
1574
+ userStep(_results, self);
1575
+ }
1576
+ }
1577
+ };
1578
+ }
1579
+
1580
+ /**
1581
+ * Parses input. Most users won't need, and shouldn't mess with, the baseIndex
1582
+ * and ignoreLastRow parameters. They are used by streamers (wrapper functions)
1583
+ * when an input comes in multiple chunks, like from a file.
1584
+ */
1585
+ this.parse = function(input, baseIndex, ignoreLastRow)
1586
+ {
1587
+ var quoteChar = _config.quoteChar || '"';
1588
+ if (!_config.newline)
1589
+ _config.newline = guessLineEndings(input, quoteChar);
1590
+
1591
+ _delimiterError = false;
1592
+ if (!_config.delimiter)
1593
+ {
1594
+ var delimGuess = guessDelimiter(input, _config.newline, _config.skipEmptyLines, _config.comments, _config.delimitersToGuess);
1595
+ if (delimGuess.successful)
1596
+ _config.delimiter = delimGuess.bestDelimiter;
1597
+ else
1598
+ {
1599
+ _delimiterError = true; // add error after parsing (otherwise it would be overwritten)
1600
+ _config.delimiter = Papa.DefaultDelimiter;
1601
+ }
1602
+ _results.meta.delimiter = _config.delimiter;
1603
+ }
1604
+ else if(isFunction(_config.delimiter))
1605
+ {
1606
+ _config.delimiter = _config.delimiter(input);
1607
+ _results.meta.delimiter = _config.delimiter;
1608
+ }
1609
+
1610
+ var parserConfig = copy(_config);
1611
+ if (_config.preview && _config.header)
1612
+ parserConfig.preview++; // to compensate for header row
1613
+
1614
+ _input = input;
1615
+ _parser = new Parser(parserConfig);
1616
+ _results = _parser.parse(_input, baseIndex, ignoreLastRow);
1617
+ processResults();
1618
+ return _paused ? { meta: { paused: true } } : (_results || { meta: { paused: false } });
1619
+ };
1620
+
1621
+ this.paused = function()
1622
+ {
1623
+ return _paused;
1624
+ };
1625
+
1626
+ this.pause = function()
1627
+ {
1628
+ _paused = true;
1629
+ _parser.abort();
1630
+
1631
+ // If it is streaming via "chunking", the reader will start appending correctly already so no need to substring,
1632
+ // otherwise we can get duplicate content within a row
1633
+ _input = isFunction(_config.chunk) ? "" : _input.substring(_parser.getCharIndex());
1634
+ };
1635
+
1636
+ this.resume = function()
1637
+ {
1638
+ if(self.streamer._halted) {
1639
+ _paused = false;
1640
+ self.streamer.parseChunk(_input, true);
1641
+ } else {
1642
+ // Bugfix: #636 In case the processing hasn't halted yet
1643
+ // wait for it to halt in order to resume
1644
+ setTimeout(self.resume, 3);
1645
+ }
1646
+ };
1647
+
1648
+ this.aborted = function()
1649
+ {
1650
+ return _aborted;
1651
+ };
1652
+
1653
+ this.abort = function()
1654
+ {
1655
+ _aborted = true;
1656
+ _parser.abort();
1657
+ _results.meta.aborted = true;
1658
+ if (isFunction(_config.complete))
1659
+ _config.complete(_results);
1660
+ _input = '';
1661
+ };
1662
+
1663
+ function testEmptyLine(s) {
1664
+ return _config.skipEmptyLines === 'greedy' ? s.join('').trim() === '' : s.length === 1 && s[0].length === 0;
1665
+ }
1666
+
1667
+ function testFloat(s) {
1668
+ if (FLOAT.test(s)) {
1669
+ var floatValue = parseFloat(s);
1670
+ if (floatValue > MIN_FLOAT && floatValue < MAX_FLOAT) {
1671
+ return true;
1672
+ }
1673
+ }
1674
+ return false;
1675
+ }
1676
+
1677
+ function processResults()
1678
+ {
1679
+ if (_results && _delimiterError)
1680
+ {
1681
+ addError('Delimiter', 'UndetectableDelimiter', 'Unable to auto-detect delimiting character; defaulted to \'' + Papa.DefaultDelimiter + '\'');
1682
+ _delimiterError = false;
1683
+ }
1684
+
1685
+ if (_config.skipEmptyLines)
1686
+ {
1687
+ _results.data = _results.data.filter(function(d) {
1688
+ return !testEmptyLine(d);
1689
+ });
1690
+ }
1691
+
1692
+ if (needsHeaderRow())
1693
+ fillHeaderFields();
1694
+
1695
+ return applyHeaderAndDynamicTypingAndTransformation();
1696
+ }
1697
+
1698
+ function needsHeaderRow()
1699
+ {
1700
+ return _config.header && _fields.length === 0;
1701
+ }
1702
+
1703
+ function fillHeaderFields()
1704
+ {
1705
+ if (!_results)
1706
+ return;
1707
+
1708
+ function addHeader(header, i)
1709
+ {
1710
+ if (isFunction(_config.transformHeader))
1711
+ header = _config.transformHeader(header, i);
1712
+
1713
+ _fields.push(header);
1714
+ }
1715
+
1716
+ if (Array.isArray(_results.data[0]))
1717
+ {
1718
+ for (var i = 0; needsHeaderRow() && i < _results.data.length; i++)
1719
+ _results.data[i].forEach(addHeader);
1720
+
1721
+ _results.data.splice(0, 1);
1722
+ }
1723
+ // if _results.data[0] is not an array, we are in a step where _results.data is the row.
1724
+ else
1725
+ _results.data.forEach(addHeader);
1726
+ }
1727
+
1728
+ function shouldApplyDynamicTyping(field) {
1729
+ // Cache function values to avoid calling it for each row
1730
+ if (_config.dynamicTypingFunction && _config.dynamicTyping[field] === undefined) {
1731
+ _config.dynamicTyping[field] = _config.dynamicTypingFunction(field);
1732
+ }
1733
+ return (_config.dynamicTyping[field] || _config.dynamicTyping) === true;
1734
+ }
1735
+
1736
+ function parseDynamic(field, value)
1737
+ {
1738
+ if (shouldApplyDynamicTyping(field))
1739
+ {
1740
+ if (value === 'true' || value === 'TRUE')
1741
+ return true;
1742
+ else if (value === 'false' || value === 'FALSE')
1743
+ return false;
1744
+ else if (testFloat(value))
1745
+ return parseFloat(value);
1746
+ else if (ISO_DATE.test(value))
1747
+ return new Date(value);
1748
+ else
1749
+ return (value === '' ? null : value);
1750
+ }
1751
+ return value;
1752
+ }
1753
+
1754
+ function applyHeaderAndDynamicTypingAndTransformation()
1755
+ {
1756
+ if (!_results || (!_config.header && !_config.dynamicTyping && !_config.transform))
1757
+ return _results;
1758
+
1759
+ function processRow(rowSource, i)
1760
+ {
1761
+ var row = _config.header ? {} : [];
1762
+
1763
+ var j;
1764
+ for (j = 0; j < rowSource.length; j++)
1765
+ {
1766
+ var field = j;
1767
+ var value = rowSource[j];
1768
+
1769
+ if (_config.header)
1770
+ field = j >= _fields.length ? '__parsed_extra' : _fields[j];
1771
+
1772
+ if (_config.transform)
1773
+ value = _config.transform(value,field);
1774
+
1775
+ value = parseDynamic(field, value);
1776
+
1777
+ if (field === '__parsed_extra')
1778
+ {
1779
+ row[field] = row[field] || [];
1780
+ row[field].push(value);
1781
+ }
1782
+ else
1783
+ row[field] = value;
1784
+ }
1785
+
1786
+
1787
+ if (_config.header)
1788
+ {
1789
+ if (j > _fields.length)
1790
+ addError('FieldMismatch', 'TooManyFields', 'Too many fields: expected ' + _fields.length + ' fields but parsed ' + j, _rowCounter + i);
1791
+ else if (j < _fields.length)
1792
+ addError('FieldMismatch', 'TooFewFields', 'Too few fields: expected ' + _fields.length + ' fields but parsed ' + j, _rowCounter + i);
1793
+ }
1794
+
1795
+ return row;
1796
+ }
1797
+
1798
+ var incrementBy = 1;
1799
+ if (!_results.data.length || Array.isArray(_results.data[0]))
1800
+ {
1801
+ _results.data = _results.data.map(processRow);
1802
+ incrementBy = _results.data.length;
1803
+ }
1804
+ else
1805
+ _results.data = processRow(_results.data, 0);
1806
+
1807
+
1808
+ if (_config.header && _results.meta)
1809
+ _results.meta.fields = _fields;
1810
+
1811
+ _rowCounter += incrementBy;
1812
+ return _results;
1813
+ }
1814
+
1815
+ function guessDelimiter(input, newline, skipEmptyLines, comments, delimitersToGuess) {
1816
+ var bestDelim, bestDelta, fieldCountPrevRow, maxFieldCount;
1817
+
1818
+ delimitersToGuess = delimitersToGuess || [',', '\t', '|', ';', Papa.RECORD_SEP, Papa.UNIT_SEP];
1819
+
1820
+ for (var i = 0; i < delimitersToGuess.length; i++) {
1821
+ var delim = delimitersToGuess[i];
1822
+ var delta = 0, avgFieldCount = 0, emptyLinesCount = 0;
1823
+ fieldCountPrevRow = undefined;
1824
+
1825
+ var preview = new Parser({
1826
+ comments: comments,
1827
+ delimiter: delim,
1828
+ newline: newline,
1829
+ preview: 10
1830
+ }).parse(input);
1831
+
1832
+ for (var j = 0; j < preview.data.length; j++) {
1833
+ if (skipEmptyLines && testEmptyLine(preview.data[j])) {
1834
+ emptyLinesCount++;
1835
+ continue;
1836
+ }
1837
+ var fieldCount = preview.data[j].length;
1838
+ avgFieldCount += fieldCount;
1839
+
1840
+ if (typeof fieldCountPrevRow === 'undefined') {
1841
+ fieldCountPrevRow = fieldCount;
1842
+ continue;
1843
+ }
1844
+ else if (fieldCount > 0) {
1845
+ delta += Math.abs(fieldCount - fieldCountPrevRow);
1846
+ fieldCountPrevRow = fieldCount;
1847
+ }
1848
+ }
1849
+
1850
+ if (preview.data.length > 0)
1851
+ avgFieldCount /= (preview.data.length - emptyLinesCount);
1852
+
1853
+ if ((typeof bestDelta === 'undefined' || delta <= bestDelta)
1854
+ && (typeof maxFieldCount === 'undefined' || avgFieldCount > maxFieldCount) && avgFieldCount > 1.99) {
1855
+ bestDelta = delta;
1856
+ bestDelim = delim;
1857
+ maxFieldCount = avgFieldCount;
1858
+ }
1859
+ }
1860
+
1861
+ _config.delimiter = bestDelim;
1862
+
1863
+ return {
1864
+ successful: !!bestDelim,
1865
+ bestDelimiter: bestDelim
1866
+ };
1867
+ }
1868
+
1869
+ function guessLineEndings(input, quoteChar)
1870
+ {
1871
+ input = input.substring(0, 1024 * 1024); // max length 1 MB
1872
+ // Replace all the text inside quotes
1873
+ var re = new RegExp(escapeRegExp(quoteChar) + '([^]*?)' + escapeRegExp(quoteChar), 'gm');
1874
+ input = input.replace(re, '');
1875
+
1876
+ var r = input.split('\r');
1877
+
1878
+ var n = input.split('\n');
1879
+
1880
+ var nAppearsFirst = (n.length > 1 && n[0].length < r[0].length);
1881
+
1882
+ if (r.length === 1 || nAppearsFirst)
1883
+ return '\n';
1884
+
1885
+ var numWithN = 0;
1886
+ for (var i = 0; i < r.length; i++)
1887
+ {
1888
+ if (r[i][0] === '\n')
1889
+ numWithN++;
1890
+ }
1891
+
1892
+ return numWithN >= r.length / 2 ? '\r\n' : '\r';
1893
+ }
1894
+
1895
+ function addError(type, code, msg, row)
1896
+ {
1897
+ var error = {
1898
+ type: type,
1899
+ code: code,
1900
+ message: msg
1901
+ };
1902
+ if(row !== undefined) {
1903
+ error.row = row;
1904
+ }
1905
+ _results.errors.push(error);
1906
+ }
1907
+ }
1908
+
1909
+ /** https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions */
1910
+ function escapeRegExp(string)
1911
+ {
1912
+ return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
1913
+ }
1914
+
1915
+ /** The core parser implements speedy and correct CSV parsing */
1916
+ function Parser(config)
1917
+ {
1918
+ // Unpack the config object
1919
+ config = config || {};
1920
+ var delim = config.delimiter;
1921
+ var newline = config.newline;
1922
+ var comments = config.comments;
1923
+ var step = config.step;
1924
+ var preview = config.preview;
1925
+ var fastMode = config.fastMode;
1926
+ var quoteChar;
1927
+ if (config.quoteChar === undefined || config.quoteChar === null) {
1928
+ quoteChar = '"';
1929
+ } else {
1930
+ quoteChar = config.quoteChar;
1931
+ }
1932
+ var escapeChar = quoteChar;
1933
+ if (config.escapeChar !== undefined) {
1934
+ escapeChar = config.escapeChar;
1935
+ }
1936
+
1937
+ // Delimiter must be valid
1938
+ if (typeof delim !== 'string'
1939
+ || Papa.BAD_DELIMITERS.indexOf(delim) > -1)
1940
+ delim = ',';
1941
+
1942
+ // Comment character must be valid
1943
+ if (comments === delim)
1944
+ throw new Error('Comment character same as delimiter');
1945
+ else if (comments === true)
1946
+ comments = '#';
1947
+ else if (typeof comments !== 'string'
1948
+ || Papa.BAD_DELIMITERS.indexOf(comments) > -1)
1949
+ comments = false;
1950
+
1951
+ // Newline must be valid: \r, \n, or \r\n
1952
+ if (newline !== '\n' && newline !== '\r' && newline !== '\r\n')
1953
+ newline = '\n';
1954
+
1955
+ // We're gonna need these at the Parser scope
1956
+ var cursor = 0;
1957
+ var aborted = false;
1958
+
1959
+ this.parse = function(input, baseIndex, ignoreLastRow)
1960
+ {
1961
+ // For some reason, in Chrome, this speeds things up (!?)
1962
+ if (typeof input !== 'string')
1963
+ throw new Error('Input must be a string');
1964
+
1965
+ // We don't need to compute some of these every time parse() is called,
1966
+ // but having them in a more local scope seems to perform better
1967
+ var inputLen = input.length,
1968
+ delimLen = delim.length,
1969
+ newlineLen = newline.length,
1970
+ commentsLen = comments.length;
1971
+ var stepIsFunction = isFunction(step);
1972
+
1973
+ // Establish starting state
1974
+ cursor = 0;
1975
+ var data = [], errors = [], row = [], lastCursor = 0;
1976
+
1977
+ if (!input)
1978
+ return returnable();
1979
+
1980
+ // Rename headers if there are duplicates
1981
+ if (config.header)
1982
+ {
1983
+ var firstLine = input.split(newline)[0];
1984
+ var headers = firstLine.split(delim);
1985
+ var separator = '_';
1986
+ var headerMap = [];
1987
+ var headerCount = {};
1988
+ var duplicateHeaders = false;
1989
+
1990
+ for (var j in headers) {
1991
+ var header = headers[j];
1992
+ if (isFunction(config.transformHeader))
1993
+ header = config.transformHeader(header, j);
1994
+ var headerName = header;
1995
+
1996
+ var count = headerCount[header] || 0;
1997
+ if (count > 0) {
1998
+ duplicateHeaders = true;
1999
+ headerName = header + separator + count;
2000
+ }
2001
+ headerCount[header] = count + 1;
2002
+
2003
+ headerMap.push(headerName);
2004
+ }
2005
+ if (duplicateHeaders) {
2006
+ var editedInput = input.split(newline);
2007
+ editedInput[0] = headerMap.join(delim);
2008
+ input = editedInput.join(newline);
2009
+ }
2010
+ }
2011
+ if (fastMode || (fastMode !== false && input.indexOf(quoteChar) === -1))
2012
+ {
2013
+ var rows = input.split(newline);
2014
+ for (var i = 0; i < rows.length; i++)
2015
+ {
2016
+ row = rows[i];
2017
+ cursor += row.length;
2018
+ if (i !== rows.length - 1)
2019
+ cursor += newline.length;
2020
+ else if (ignoreLastRow)
2021
+ return returnable();
2022
+ if (comments && row.substring(0, commentsLen) === comments)
2023
+ continue;
2024
+ if (stepIsFunction)
2025
+ {
2026
+ data = [];
2027
+ pushRow(row.split(delim));
2028
+ doStep();
2029
+ if (aborted)
2030
+ return returnable();
2031
+ }
2032
+ else
2033
+ pushRow(row.split(delim));
2034
+ if (preview && i >= preview)
2035
+ {
2036
+ data = data.slice(0, preview);
2037
+ return returnable(true);
2038
+ }
2039
+ }
2040
+ return returnable();
2041
+ }
2042
+
2043
+ var nextDelim = input.indexOf(delim, cursor);
2044
+ var nextNewline = input.indexOf(newline, cursor);
2045
+ var quoteCharRegex = new RegExp(escapeRegExp(escapeChar) + escapeRegExp(quoteChar), 'g');
2046
+ var quoteSearch = input.indexOf(quoteChar, cursor);
2047
+
2048
+ // Parser loop
2049
+ for (;;)
2050
+ {
2051
+ // Field has opening quote
2052
+ if (input[cursor] === quoteChar)
2053
+ {
2054
+ // Start our search for the closing quote where the cursor is
2055
+ quoteSearch = cursor;
2056
+
2057
+ // Skip the opening quote
2058
+ cursor++;
2059
+
2060
+ for (;;)
2061
+ {
2062
+ // Find closing quote
2063
+ quoteSearch = input.indexOf(quoteChar, quoteSearch + 1);
2064
+
2065
+ //No other quotes are found - no other delimiters
2066
+ if (quoteSearch === -1)
2067
+ {
2068
+ if (!ignoreLastRow) {
2069
+ // No closing quote... what a pity
2070
+ errors.push({
2071
+ type: 'Quotes',
2072
+ code: 'MissingQuotes',
2073
+ message: 'Quoted field unterminated',
2074
+ row: data.length, // row has yet to be inserted
2075
+ index: cursor
2076
+ });
2077
+ }
2078
+ return finish();
2079
+ }
2080
+
2081
+ // Closing quote at EOF
2082
+ if (quoteSearch === inputLen - 1)
2083
+ {
2084
+ var value = input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar);
2085
+ return finish(value);
2086
+ }
2087
+
2088
+ // If this quote is escaped, it's part of the data; skip it
2089
+ // If the quote character is the escape character, then check if the next character is the escape character
2090
+ if (quoteChar === escapeChar && input[quoteSearch + 1] === escapeChar)
2091
+ {
2092
+ quoteSearch++;
2093
+ continue;
2094
+ }
2095
+
2096
+ // If the quote character is not the escape character, then check if the previous character was the escape character
2097
+ if (quoteChar !== escapeChar && quoteSearch !== 0 && input[quoteSearch - 1] === escapeChar)
2098
+ {
2099
+ continue;
2100
+ }
2101
+
2102
+ if(nextDelim !== -1 && nextDelim < (quoteSearch + 1)) {
2103
+ nextDelim = input.indexOf(delim, (quoteSearch + 1));
2104
+ }
2105
+ if(nextNewline !== -1 && nextNewline < (quoteSearch + 1)) {
2106
+ nextNewline = input.indexOf(newline, (quoteSearch + 1));
2107
+ }
2108
+ // Check up to nextDelim or nextNewline, whichever is closest
2109
+ var checkUpTo = nextNewline === -1 ? nextDelim : Math.min(nextDelim, nextNewline);
2110
+ var spacesBetweenQuoteAndDelimiter = extraSpaces(checkUpTo);
2111
+
2112
+ // Closing quote followed by delimiter or 'unnecessary spaces + delimiter'
2113
+ if (input.substr(quoteSearch + 1 + spacesBetweenQuoteAndDelimiter, delimLen) === delim)
2114
+ {
2115
+ row.push(input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar));
2116
+ cursor = quoteSearch + 1 + spacesBetweenQuoteAndDelimiter + delimLen;
2117
+
2118
+ // If char after following delimiter is not quoteChar, we find next quote char position
2119
+ if (input[quoteSearch + 1 + spacesBetweenQuoteAndDelimiter + delimLen] !== quoteChar)
2120
+ {
2121
+ quoteSearch = input.indexOf(quoteChar, cursor);
2122
+ }
2123
+ nextDelim = input.indexOf(delim, cursor);
2124
+ nextNewline = input.indexOf(newline, cursor);
2125
+ break;
2126
+ }
2127
+
2128
+ var spacesBetweenQuoteAndNewLine = extraSpaces(nextNewline);
2129
+
2130
+ // Closing quote followed by newline or 'unnecessary spaces + newLine'
2131
+ if (input.substring(quoteSearch + 1 + spacesBetweenQuoteAndNewLine, quoteSearch + 1 + spacesBetweenQuoteAndNewLine + newlineLen) === newline)
2132
+ {
2133
+ row.push(input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar));
2134
+ saveRow(quoteSearch + 1 + spacesBetweenQuoteAndNewLine + newlineLen);
2135
+ nextDelim = input.indexOf(delim, cursor); // because we may have skipped the nextDelim in the quoted field
2136
+ quoteSearch = input.indexOf(quoteChar, cursor); // we search for first quote in next line
2137
+
2138
+ if (stepIsFunction)
2139
+ {
2140
+ doStep();
2141
+ if (aborted)
2142
+ return returnable();
2143
+ }
2144
+
2145
+ if (preview && data.length >= preview)
2146
+ return returnable(true);
2147
+
2148
+ break;
2149
+ }
2150
+
2151
+
2152
+ // Checks for valid closing quotes are complete (escaped quotes or quote followed by EOF/delimiter/newline) -- assume these quotes are part of an invalid text string
2153
+ errors.push({
2154
+ type: 'Quotes',
2155
+ code: 'InvalidQuotes',
2156
+ message: 'Trailing quote on quoted field is malformed',
2157
+ row: data.length, // row has yet to be inserted
2158
+ index: cursor
2159
+ });
2160
+
2161
+ quoteSearch++;
2162
+ continue;
2163
+
2164
+ }
2165
+
2166
+ continue;
2167
+ }
2168
+
2169
+ // Comment found at start of new line
2170
+ if (comments && row.length === 0 && input.substring(cursor, cursor + commentsLen) === comments)
2171
+ {
2172
+ if (nextNewline === -1) // Comment ends at EOF
2173
+ return returnable();
2174
+ cursor = nextNewline + newlineLen;
2175
+ nextNewline = input.indexOf(newline, cursor);
2176
+ nextDelim = input.indexOf(delim, cursor);
2177
+ continue;
2178
+ }
2179
+
2180
+ // Next delimiter comes before next newline, so we've reached end of field
2181
+ if (nextDelim !== -1 && (nextDelim < nextNewline || nextNewline === -1))
2182
+ {
2183
+ row.push(input.substring(cursor, nextDelim));
2184
+ cursor = nextDelim + delimLen;
2185
+ // we look for next delimiter char
2186
+ nextDelim = input.indexOf(delim, cursor);
2187
+ continue;
2188
+ }
2189
+
2190
+ // End of row
2191
+ if (nextNewline !== -1)
2192
+ {
2193
+ row.push(input.substring(cursor, nextNewline));
2194
+ saveRow(nextNewline + newlineLen);
2195
+
2196
+ if (stepIsFunction)
2197
+ {
2198
+ doStep();
2199
+ if (aborted)
2200
+ return returnable();
2201
+ }
2202
+
2203
+ if (preview && data.length >= preview)
2204
+ return returnable(true);
2205
+
2206
+ continue;
2207
+ }
2208
+
2209
+ break;
2210
+ }
2211
+
2212
+
2213
+ return finish();
2214
+
2215
+
2216
+ function pushRow(row)
2217
+ {
2218
+ data.push(row);
2219
+ lastCursor = cursor;
2220
+ }
2221
+
2222
+ /**
2223
+ * checks if there are extra spaces after closing quote and given index without any text
2224
+ * if Yes, returns the number of spaces
2225
+ */
2226
+ function extraSpaces(index) {
2227
+ var spaceLength = 0;
2228
+ if (index !== -1) {
2229
+ var textBetweenClosingQuoteAndIndex = input.substring(quoteSearch + 1, index);
2230
+ if (textBetweenClosingQuoteAndIndex && textBetweenClosingQuoteAndIndex.trim() === '') {
2231
+ spaceLength = textBetweenClosingQuoteAndIndex.length;
2232
+ }
2233
+ }
2234
+ return spaceLength;
2235
+ }
2236
+
2237
+ /**
2238
+ * Appends the remaining input from cursor to the end into
2239
+ * row, saves the row, calls step, and returns the results.
2240
+ */
2241
+ function finish(value)
2242
+ {
2243
+ if (ignoreLastRow)
2244
+ return returnable();
2245
+ if (typeof value === 'undefined')
2246
+ value = input.substring(cursor);
2247
+ row.push(value);
2248
+ cursor = inputLen; // important in case parsing is paused
2249
+ pushRow(row);
2250
+ if (stepIsFunction)
2251
+ doStep();
2252
+ return returnable();
2253
+ }
2254
+
2255
+ /**
2256
+ * Appends the current row to the results. It sets the cursor
2257
+ * to newCursor and finds the nextNewline. The caller should
2258
+ * take care to execute user's step function and check for
2259
+ * preview and end parsing if necessary.
2260
+ */
2261
+ function saveRow(newCursor)
2262
+ {
2263
+ cursor = newCursor;
2264
+ pushRow(row);
2265
+ row = [];
2266
+ nextNewline = input.indexOf(newline, cursor);
2267
+ }
2268
+
2269
+ /** Returns an object with the results, errors, and meta. */
2270
+ function returnable(stopped)
2271
+ {
2272
+ return {
2273
+ data: data,
2274
+ errors: errors,
2275
+ meta: {
2276
+ delimiter: delim,
2277
+ linebreak: newline,
2278
+ aborted: aborted,
2279
+ truncated: !!stopped,
2280
+ cursor: lastCursor + (baseIndex || 0)
2281
+ }
2282
+ };
2283
+ }
2284
+
2285
+ /** Executes the user's step function and resets data & errors. */
2286
+ function doStep()
2287
+ {
2288
+ step(returnable());
2289
+ data = [];
2290
+ errors = [];
2291
+ }
2292
+ };
2293
+
2294
+ /** Sets the abort flag */
2295
+ this.abort = function()
2296
+ {
2297
+ aborted = true;
2298
+ };
2299
+
2300
+ /** Gets the cursor position */
2301
+ this.getCharIndex = function()
2302
+ {
2303
+ return cursor;
2304
+ };
2305
+ }
2306
+
2307
+
2308
+ function newWorker()
2309
+ {
2310
+ if (!Papa.WORKERS_SUPPORTED)
2311
+ return false;
2312
+
2313
+ var workerUrl = getWorkerBlob();
2314
+ var w = new global.Worker(workerUrl);
2315
+ w.onmessage = mainThreadReceivedMessage;
2316
+ w.id = workerIdCounter++;
2317
+ workers[w.id] = w;
2318
+ return w;
2319
+ }
2320
+
2321
+ /** Callback when main thread receives a message */
2322
+ function mainThreadReceivedMessage(e)
2323
+ {
2324
+ var msg = e.data;
2325
+ var worker = workers[msg.workerId];
2326
+ var aborted = false;
2327
+
2328
+ if (msg.error)
2329
+ worker.userError(msg.error, msg.file);
2330
+ else if (msg.results && msg.results.data)
2331
+ {
2332
+ var abort = function() {
2333
+ aborted = true;
2334
+ completeWorker(msg.workerId, { data: [], errors: [], meta: { aborted: true } });
2335
+ };
2336
+
2337
+ var handle = {
2338
+ abort: abort,
2339
+ pause: notImplemented,
2340
+ resume: notImplemented
2341
+ };
2342
+
2343
+ if (isFunction(worker.userStep))
2344
+ {
2345
+ for (var i = 0; i < msg.results.data.length; i++)
2346
+ {
2347
+ worker.userStep({
2348
+ data: msg.results.data[i],
2349
+ errors: msg.results.errors,
2350
+ meta: msg.results.meta
2351
+ }, handle);
2352
+ if (aborted)
2353
+ break;
2354
+ }
2355
+ delete msg.results; // free memory ASAP
2356
+ }
2357
+ else if (isFunction(worker.userChunk))
2358
+ {
2359
+ worker.userChunk(msg.results, handle, msg.file);
2360
+ delete msg.results;
2361
+ }
2362
+ }
2363
+
2364
+ if (msg.finished && !aborted)
2365
+ completeWorker(msg.workerId, msg.results);
2366
+ }
2367
+
2368
+ function completeWorker(workerId, results) {
2369
+ var worker = workers[workerId];
2370
+ if (isFunction(worker.userComplete))
2371
+ worker.userComplete(results);
2372
+ worker.terminate();
2373
+ delete workers[workerId];
2374
+ }
2375
+
2376
+ function notImplemented() {
2377
+ throw new Error('Not implemented.');
2378
+ }
2379
+
2380
+ /** Callback when worker thread receives a message */
2381
+ function workerThreadReceivedMessage(e)
2382
+ {
2383
+ var msg = e.data;
2384
+
2385
+ if (typeof Papa.WORKER_ID === 'undefined' && msg)
2386
+ Papa.WORKER_ID = msg.workerId;
2387
+
2388
+ if (typeof msg.input === 'string')
2389
+ {
2390
+ global.postMessage({
2391
+ workerId: Papa.WORKER_ID,
2392
+ results: Papa.parse(msg.input, msg.config),
2393
+ finished: true
2394
+ });
2395
+ }
2396
+ else if ((global.File && msg.input instanceof File) || msg.input instanceof Object) // thank you, Safari (see issue #106)
2397
+ {
2398
+ var results = Papa.parse(msg.input, msg.config);
2399
+ if (results)
2400
+ global.postMessage({
2401
+ workerId: Papa.WORKER_ID,
2402
+ results: results,
2403
+ finished: true
2404
+ });
2405
+ }
2406
+ }
2407
+
2408
+ /** Makes a deep copy of an array or object (mostly) */
2409
+ function copy(obj)
2410
+ {
2411
+ if (typeof obj !== 'object' || obj === null)
2412
+ return obj;
2413
+ var cpy = Array.isArray(obj) ? [] : {};
2414
+ for (var key in obj)
2415
+ cpy[key] = copy(obj[key]);
2416
+ return cpy;
2417
+ }
2418
+
2419
+ function bindFunction(f, self)
2420
+ {
2421
+ return function() { f.apply(self, arguments); };
2422
+ }
2423
+
2424
+ function isFunction(func)
2425
+ {
2426
+ return typeof func === 'function';
2427
+ }
2428
+
2429
+ return Papa;
2430
+ }));
2431
+ } (papaparse));
2432
+
2433
+ var Papa = papaparse.exports;
2434
+
2435
+ var isValidEmail = function isValidEmail(email) {
2436
+ return string().email().isValidSync(email);
2437
+ };
2438
+ var createEmailOptions = function createEmailOptions() {
2439
+ var emails = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
2440
+ return emails.map(function (email) {
2441
+ return {
2442
+ label: email,
2443
+ value: email,
2444
+ valid: isValidEmail(email)
2445
+ };
2446
+ });
2447
+ };
2448
+ var parseCsvEmails = /*#__PURE__*/function () {
2449
+ var _ref = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(file, onSuccess) {
2450
+ return regenerator.wrap(function _callee$(_context) {
2451
+ while (1) switch (_context.prev = _context.next) {
2452
+ case 0:
2453
+ Papa.parse(file, {
2454
+ header: true,
2455
+ skipEmptyLines: true,
2456
+ transformHeader: function transformHeader(h) {
2457
+ return h.toLowerCase().replace(/\W/g, "");
2458
+ },
2459
+ complete: function complete(results) {
2460
+ var emails = results.data.filter(prop("email")).map(function (item) {
2461
+ return item.email.trim();
2462
+ });
2463
+ onSuccess(createEmailOptions(emails));
2464
+ }
2465
+ });
2466
+ case 1:
2467
+ case "end":
2468
+ return _context.stop();
2469
+ }
2470
+ }, _callee);
2471
+ }));
2472
+ return function parseCsvEmails(_x, _x2) {
2473
+ return _ref.apply(this, arguments);
2474
+ };
2475
+ }();
2476
+ var getValidationSchema = function getValidationSchema(_ref2) {
2477
+ var showSendToField = _ref2.showSendToField,
2478
+ showReplyToField = _ref2.showReplyToField,
2479
+ customValidations = _ref2.customValidations;
2480
+ var schema = EMAIL_FORM_VALIDATION_SCHEMA.clone();
2481
+ if (showSendToField) schema = schema.concat(SEND_TO_FIELD_VALIDATION);
2482
+ if (showReplyToField) schema = schema.concat(REPLY_TO_FIELD_VALIDATION);
2483
+ return schema.concat(customValidations);
2484
+ };
2485
+
2486
+ var SendToField = function SendToField() {
2487
+ var _useTranslation = useTranslation(),
2488
+ t = _useTranslation.t;
2489
+ var _useFormikContext = useFormikContext(),
2490
+ setFieldValue = _useFormikContext.setFieldValue,
2491
+ values = _useFormikContext.values;
2492
+ var showCopyEmailFieldValue = values.showCopyEmails,
2493
+ existingSendToEmails = values.sendTo;
2494
+ var handleCSVFile = /*#__PURE__*/function () {
2495
+ var _ref = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(files) {
2496
+ var setNotifyEmails;
2497
+ return regenerator.wrap(function _callee$(_context) {
2498
+ while (1) switch (_context.prev = _context.next) {
2499
+ case 0:
2500
+ _context.prev = 0;
2501
+ setNotifyEmails = function setNotifyEmails(values) {
2502
+ return setFieldValue("sendTo", [].concat(_toConsumableArray(existingSendToEmails), _toConsumableArray(values)));
2503
+ };
2504
+ _context.next = 4;
2505
+ return parseCsvEmails(files[0], setNotifyEmails);
2506
+ case 4:
2507
+ _context.next = 9;
2508
+ break;
2509
+ case 6:
2510
+ _context.prev = 6;
2511
+ _context.t0 = _context["catch"](0);
2512
+ Toastr.error(_context.t0);
2513
+ case 9:
2514
+ case "end":
2515
+ return _context.stop();
2516
+ }
2517
+ }, _callee, null, [[0, 6]]);
2518
+ }));
2519
+ return function handleCSVFile(_x) {
2520
+ return _ref.apply(this, arguments);
2521
+ };
2522
+ }();
2523
+ return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
2524
+ className: "flex w-full flex-col gap-2"
2525
+ }, /*#__PURE__*/React.createElement("div", {
2526
+ className: "flex items-center justify-between"
2527
+ }, /*#__PURE__*/React.createElement(Label, null, t("neetoMolecules.emailForm.labels.sendTo")), /*#__PURE__*/React.createElement(FilePicker, {
2528
+ types: ALLOWED_FILE_PICKER_TYPES,
2529
+ onChange: handleCSVFile
2530
+ }, /*#__PURE__*/React.createElement(Button, {
2531
+ "data-cy": "upload-csv-button",
2532
+ icon: Upload,
2533
+ label: t("neetoMolecules.emailForm.uploadCSV"),
2534
+ size: "small",
2535
+ style: "link"
2536
+ }))), /*#__PURE__*/React.createElement(MultiEmailInput, {
2537
+ id: "sendTo",
2538
+ label: "",
2539
+ name: "sendTo",
2540
+ placeholder: t("neetoMolecules.emailForm.placeholders.commaSeparatedEmails"),
2541
+ suffix: /*#__PURE__*/React.createElement(Button, {
2542
+ "data-cy": "cc-bcc-button",
2543
+ label: t("neetoMolecules.emailForm.labels.ccBcc"),
2544
+ size: "small",
2545
+ style: "link",
2546
+ onClick: function onClick() {
2547
+ return setFieldValue("showCopyEmails", !showCopyEmailFieldValue);
2548
+ }
2549
+ })
2550
+ })), showCopyEmailFieldValue && /*#__PURE__*/React.createElement("div", {
2551
+ className: "flex w-full flex-col gap-6"
2552
+ }, /*#__PURE__*/React.createElement(MultiEmailInput, {
2553
+ label: t("neetoMolecules.emailForm.labels.cc"),
2554
+ name: "sendToCc",
2555
+ placeholder: t("neetoMolecules.emailForm.placeholders.commaSeparatedEmails")
2556
+ }), /*#__PURE__*/React.createElement(MultiEmailInput, {
2557
+ label: t("neetoMolecules.emailForm.labels.bCc"),
2558
+ name: "sendToBcc",
2559
+ placeholder: t("neetoMolecules.emailForm.placeholders.commaSeparatedEmails")
2560
+ })));
2561
+ };
2562
+
2563
+ function _arrayWithHoles(arr) {
2564
+ if (Array.isArray(arr)) return arr;
2565
+ }
2566
+
2567
+ function _iterableToArrayLimit(arr, i) {
2568
+ var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"];
2569
+ if (null != _i) {
2570
+ var _s,
2571
+ _e,
2572
+ _x,
2573
+ _r,
2574
+ _arr = [],
2575
+ _n = !0,
2576
+ _d = !1;
2577
+ try {
2578
+ if (_x = (_i = _i.call(arr)).next, 0 === i) {
2579
+ if (Object(_i) !== _i) return;
2580
+ _n = !1;
2581
+ } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0);
2582
+ } catch (err) {
2583
+ _d = !0, _e = err;
2584
+ } finally {
2585
+ try {
2586
+ if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return;
2587
+ } finally {
2588
+ if (_d) throw _e;
2589
+ }
2590
+ }
2591
+ return _arr;
2592
+ }
2593
+ }
2594
+
2595
+ function _nonIterableRest() {
2596
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
2597
+ }
2598
+
2599
+ function _slicedToArray(arr, i) {
2600
+ return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
2601
+ }
2602
+
2603
+ var SubjectField = function SubjectField(_ref) {
2604
+ var name = _ref.name,
2605
+ text = _ref.text,
2606
+ updateText = _ref.updateText,
2607
+ _ref$subjectVariables = _ref.subjectVariables,
2608
+ subjectVariables = _ref$subjectVariables === void 0 ? [] : _ref$subjectVariables,
2609
+ error = _ref.error,
2610
+ _ref$required = _ref.required,
2611
+ required = _ref$required === void 0 ? false : _ref$required;
2612
+ var _useState = useState(false),
2613
+ _useState2 = _slicedToArray(_useState, 2),
2614
+ isFieldFocusedOnce = _useState2[0],
2615
+ setIsFieldFocusedOnce = _useState2[1];
2616
+ var _useTranslation = useTranslation(),
2617
+ t = _useTranslation.t;
2618
+ var tagClickHandler = function tagClickHandler(_ref2) {
2619
+ var slug = _ref2.key;
2620
+ var textAreaElement = document.querySelector("textarea[name=".concat(name, "]"));
2621
+ var splitIndex = isFieldFocusedOnce && textAreaElement ? textAreaElement.selectionEnd : text.length;
2622
+ var updatedSubject = [text.slice(0, splitIndex), " {{".concat(slug, "}}"), text.slice(splitIndex)].join("");
2623
+ updateText(updatedSubject);
2624
+ };
2625
+ return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Input$1, {
2626
+ error: error,
2627
+ name: name,
2628
+ required: required,
2629
+ label: t("neetoMolecules.emailForm.labels.subject"),
2630
+ size: "large",
2631
+ value: text,
2632
+ suffix: /*#__PURE__*/React.createElement(DynamicVariables, {
2633
+ variables: subjectVariables,
2634
+ dropdownProps: {
2635
+ className: "neeto-ui-dropdown__popup overflow-y-auto",
2636
+ buttonSize: "small"
2637
+ },
2638
+ onVariableClick: tagClickHandler
2639
+ }),
2640
+ onChange: withEventTargetValue(updateText),
2641
+ onFocus: function onFocus() {
2642
+ return setIsFieldFocusedOnce(true);
2643
+ }
2644
+ }), /*#__PURE__*/React.createElement(Typography, {
2645
+ className: "neeto-ui-text-gray-600 mt-2",
2646
+ "data-cy": "subject-input-variable-label",
2647
+ style: "body3"
2648
+ }, /*#__PURE__*/React.createElement(Trans, {
2649
+ components: {
2650
+ span: /*#__PURE__*/React.createElement("span", {
2651
+ className: "font-semibold"
2652
+ })
2653
+ },
2654
+ i18nKey: "neetoMolecules.emailForm.helpText",
2655
+ values: {
2656
+ type: "subject"
2657
+ }
2658
+ })));
2659
+ };
2660
+
2661
+ var EmailForm = function EmailForm(_ref) {
2662
+ var _ref$messageVariables = _ref.messageVariables,
2663
+ messageVariables = _ref$messageVariables === void 0 ? [] : _ref$messageVariables,
2664
+ _ref$subjectVariables = _ref.subjectVariables,
2665
+ subjectVariables = _ref$subjectVariables === void 0 ? [] : _ref$subjectVariables,
2666
+ handleCancel = _ref.handleCancel,
2667
+ isLoading = _ref.isLoading,
2668
+ _ref$replyToOptions = _ref.replyToOptions,
2669
+ replyToOptions = _ref$replyToOptions === void 0 ? [] : _ref$replyToOptions,
2670
+ _ref$isUpdating = _ref.isUpdating,
2671
+ isUpdating = _ref$isUpdating === void 0 ? false : _ref$isUpdating;
2672
+ var _useTranslation = useTranslation(),
2673
+ t = _useTranslation.t;
2674
+ var _useContext = useContext(EmailFormContext),
2675
+ showSendToField = _useContext.showSendToField,
2676
+ showReplyToField = _useContext.showReplyToField;
2677
+ var _useFormikContext = useFormikContext(),
2678
+ setFieldValue = _useFormikContext.setFieldValue,
2679
+ dirty = _useFormikContext.dirty;
2680
+ return /*#__PURE__*/React.createElement("div", {
2681
+ className: "flex flex-1 flex-col items-start gap-2",
2682
+ "data-testid": "email-form"
2683
+ }, /*#__PURE__*/React.createElement("div", {
2684
+ className: "flex items-stretch gap-8"
2685
+ }, /*#__PURE__*/React.createElement("div", {
2686
+ className: "flex flex-col items-start justify-start gap-6"
2687
+ }, /*#__PURE__*/React.createElement(Field, {
2688
+ name: "subject"
2689
+ }, function (_ref2) {
2690
+ var value = _ref2.field.value,
2691
+ error = _ref2.meta.error;
2692
+ return /*#__PURE__*/React.createElement("div", {
2693
+ className: "w-full"
2694
+ }, /*#__PURE__*/React.createElement(SubjectField, {
2695
+ error: t(error),
2696
+ name: "subject",
2697
+ subjectVariables: subjectVariables,
2698
+ text: value,
2699
+ updateText: function updateText(text) {
2700
+ return setFieldValue("subject", text);
2701
+ }
2702
+ }));
2703
+ }), showSendToField && /*#__PURE__*/React.createElement(SendToField, null), showReplyToField && /*#__PURE__*/React.createElement(ReplyToField, {
2704
+ replyToOptions: replyToOptions
2705
+ }), /*#__PURE__*/React.createElement("div", {
2706
+ className: "w-full"
2707
+ }, /*#__PURE__*/React.createElement(FormikEditor, {
2708
+ required: true,
2709
+ addons: EDITOR_ADDONS,
2710
+ "data-cy": "message-input-field",
2711
+ id: "form_message",
2712
+ label: t("neetoMolecules.emailForm.labels.message"),
2713
+ name: "message",
2714
+ variables: messageVariables
2715
+ }), /*#__PURE__*/React.createElement(Typography, {
2716
+ className: "neeto-ui-text-gray-500 mt-2",
2717
+ "data-cy": "message-input-variable-label",
2718
+ style: "body3"
2719
+ }, /*#__PURE__*/React.createElement(Trans, {
2720
+ i18nKey: "neetoMolecules.emailForm.helpText",
2721
+ values: {
2722
+ type: "message"
2723
+ },
2724
+ components: {
2725
+ span: /*#__PURE__*/React.createElement("span", {
2726
+ className: "font-semibold"
2727
+ })
2728
+ }
2729
+ }))))), /*#__PURE__*/React.createElement(ActionBlock, {
2730
+ className: "mt-6 w-full justify-start",
2731
+ cancelButtonProps: {
2732
+ disabled: false,
2733
+ onClick: handleCancel,
2734
+ className: "ml-3"
2735
+ },
2736
+ submitButtonProps: {
2737
+ loading: isLoading,
2738
+ disabled: !dirty || isUpdating
2739
+ }
2740
+ }));
2741
+ };
2742
+
2743
+ function _typeof(obj) {
2744
+ "@babel/helpers - typeof";
2745
+
2746
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
2747
+ return typeof obj;
2748
+ } : function (obj) {
2749
+ return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
2750
+ }, _typeof(obj);
2751
+ }
2752
+
2753
+ function _toPrimitive(input, hint) {
2754
+ if (_typeof(input) !== "object" || input === null) return input;
2755
+ var prim = input[Symbol.toPrimitive];
2756
+ if (prim !== undefined) {
2757
+ var res = prim.call(input, hint || "default");
2758
+ if (_typeof(res) !== "object") return res;
2759
+ throw new TypeError("@@toPrimitive must return a primitive value.");
2760
+ }
2761
+ return (hint === "string" ? String : Number)(input);
2762
+ }
2763
+
2764
+ function _toPropertyKey(arg) {
2765
+ var key = _toPrimitive(arg, "string");
2766
+ return _typeof(key) === "symbol" ? key : String(key);
2767
+ }
2768
+
2769
+ function _defineProperty(obj, key, value) {
2770
+ key = _toPropertyKey(key);
2771
+ if (key in obj) {
2772
+ Object.defineProperty(obj, key, {
2773
+ value: value,
2774
+ enumerable: true,
2775
+ configurable: true,
2776
+ writable: true
2777
+ });
2778
+ } else {
2779
+ obj[key] = value;
2780
+ }
2781
+ return obj;
2782
+ }
2783
+
2784
+ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
2785
+ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
2786
+ var EmailFormProvider = function EmailFormProvider(_ref) {
2787
+ var _ref$onSubmit = _ref.onSubmit,
2788
+ onSubmit = _ref$onSubmit === void 0 ? noop : _ref$onSubmit,
2789
+ _ref$initialValues = _ref.initialValues,
2790
+ initialValues = _ref$initialValues === void 0 ? INITIAL_FORM_VALUES : _ref$initialValues,
2791
+ children = _ref.children,
2792
+ formikProps = _ref.formikProps,
2793
+ _ref$validationSchema = _ref.validationSchema,
2794
+ customValidations = _ref$validationSchema === void 0 ? yup.object({}) : _ref$validationSchema,
2795
+ _ref$showSendToField = _ref.showSendToField,
2796
+ showSendToField = _ref$showSendToField === void 0 ? false : _ref$showSendToField,
2797
+ _ref$showReplyToField = _ref.showReplyToField,
2798
+ showReplyToField = _ref$showReplyToField === void 0 ? false : _ref$showReplyToField;
2799
+ return /*#__PURE__*/React.createElement("div", {
2800
+ "data-testid": "email-form-provider"
2801
+ }, /*#__PURE__*/React.createElement(EmailFormContext.Provider, {
2802
+ value: {
2803
+ showSendToField: showSendToField,
2804
+ showReplyToField: showReplyToField
2805
+ }
2806
+ }, /*#__PURE__*/React.createElement(Form, {
2807
+ formikProps: _objectSpread({
2808
+ enableReinitialize: true,
2809
+ validationSchema: getValidationSchema({
2810
+ showSendToField: showSendToField,
2811
+ showReplyToField: showReplyToField,
2812
+ customValidations: customValidations
2813
+ }),
2814
+ initialValues: initialValues,
2815
+ onSubmit: onSubmit
2816
+ }, formikProps)
2817
+ }, children)));
2818
+ };
2819
+
2820
+ var MemoizedEditorContent = /*#__PURE__*/React.memo(EditorContent);
2821
+ var EmailPreview = function EmailPreview(_ref) {
2822
+ var _ref$to = _ref.to,
2823
+ to = _ref$to === void 0 ? [] : _ref$to,
2824
+ from = _ref.from,
2825
+ subject = _ref.subject,
2826
+ body = _ref.body,
2827
+ productName = _ref.productName,
2828
+ actionButtonText = _ref.actionButtonText,
2829
+ logo = _ref.logo;
2830
+ var _useTranslation = useTranslation(),
2831
+ t = _useTranslation.t;
2832
+ return /*#__PURE__*/React.createElement("div", {
2833
+ className: "neeto-ui-border-gray-300 neeto-ui-shadow-m neeto-ui-bg-white flex flex-1 flex-col border",
2834
+ "data-cy": "email-preview-card",
2835
+ "data-testid": "email-preview"
2836
+ }, /*#__PURE__*/React.createElement("div", {
2837
+ className: "neeto-ui-border-gray-300 space-y-3 divide-y divide-gray-200 border-b p-6"
2838
+ }, /*#__PURE__*/React.createElement("div", {
2839
+ className: "flex gap-2",
2840
+ "data-cy": "email-send-to-preview",
2841
+ "data-testid": "email-to-block"
2842
+ }, /*#__PURE__*/React.createElement(Typography, {
2843
+ className: "neeto-ui-text-gray-500",
2844
+ lineHeight: "normal",
2845
+ style: "body2"
2846
+ }, t("neetoMolecules.emailPreview.to"), ":"), isPresent(to) && isNotEmpty(to) ? /*#__PURE__*/React.createElement(Typography, {
2847
+ className: "neeto-ui-text-gray-800 min-w-0 flex-grow break-words",
2848
+ lineHeight: "normal",
2849
+ style: "body2"
2850
+ }, to.join(", ")) : /*#__PURE__*/React.createElement("div", {
2851
+ className: "neeto-ui-bg-gray-300 neeto-ui-rounded-full mt-2 h-2 w-40"
2852
+ })), from && /*#__PURE__*/React.createElement("div", {
2853
+ className: "flex items-center gap-2 pt-3"
2854
+ }, /*#__PURE__*/React.createElement(Typography, {
2855
+ className: "neeto-ui-text-gray-500",
2856
+ lineHeight: "normal",
2857
+ style: "body2"
2858
+ }, t("neetoMolecules.emailPreview.from"), ":"), /*#__PURE__*/React.createElement(Typography, {
2859
+ className: "neeto-ui-text-gray-800 min-w-0 flex-grow break-words",
2860
+ "data-cy": "email-send-from-preview",
2861
+ lineHeight: "normal",
2862
+ style: "body2"
2863
+ }, from)), /*#__PURE__*/React.createElement("div", {
2864
+ className: "flex items-center gap-2 pt-3"
2865
+ }, /*#__PURE__*/React.createElement(Typography, {
2866
+ className: "neeto-ui-text-gray-500",
2867
+ lineHeight: "normal",
2868
+ style: "body2"
2869
+ }, t("neetoMolecules.emailPreview.subject"), ":"), /*#__PURE__*/React.createElement(Typography, {
2870
+ className: "neeto-ui-text-gray-800 min-w-0 flex-grow break-words",
2871
+ "data-cy": "email-subject-preview",
2872
+ lineHeight: "normal",
2873
+ style: "body2"
2874
+ }, subject || /*#__PURE__*/React.createElement("span", {
2875
+ className: "neeto-ui-bg-gray-300 neeto-ui-rounded-full h-2 w-40"
2876
+ })))), /*#__PURE__*/React.createElement("div", {
2877
+ className: "neeto-ui-text-gray-800 flex flex-1 flex-col justify-between space-y-6 p-6 pr-10 text-base leading-relaxed",
2878
+ "data-cy": "email-body-preview-container"
2879
+ }, body ? /*#__PURE__*/React.createElement(MemoizedEditorContent, {
2880
+ content: body
2881
+ }) : /*#__PURE__*/React.createElement("div", {
2882
+ className: "space-y-4"
2883
+ }, /*#__PURE__*/React.createElement("div", {
2884
+ className: "neeto-ui-bg-gray-300 neeto-ui-rounded-full h-2 w-80"
2885
+ }), /*#__PURE__*/React.createElement("div", {
2886
+ className: "neeto-ui-bg-gray-300 neeto-ui-rounded-full h-2 w-72"
2887
+ }), /*#__PURE__*/React.createElement("div", {
2888
+ className: "neeto-ui-bg-gray-300 neeto-ui-rounded-full h-2 w-80"
2889
+ })), actionButtonText && /*#__PURE__*/React.createElement("div", {
2890
+ className: "mt-6 flex w-full items-center justify-center"
2891
+ }, /*#__PURE__*/React.createElement(Button, {
2892
+ className: "pointer-events-none",
2893
+ label: actionButtonText
2894
+ })), logo && /*#__PURE__*/React.createElement("img", {
2895
+ alt: t("neetoMolecules.emailPreview.logoAltText"),
2896
+ className: "h-20 w-36 object-cover",
2897
+ "data-cy": "company-logo-preview",
2898
+ src: logo
2899
+ })), productName && /*#__PURE__*/React.createElement("div", {
2900
+ className: "neeto-ui-bg-gray-100 mt-auto p-2",
2901
+ "data-testid": "product-name-block"
2902
+ }, /*#__PURE__*/React.createElement(Typography, {
2903
+ className: "neeto-ui-text-gray-600 text-center leading-6",
2904
+ style: "body3"
2905
+ }, t("neetoMolecules.emailPreview.poweredBy"), /*#__PURE__*/React.createElement("span", {
2906
+ className: "neeto-ui-text-gray-800 font-medium"
2907
+ }, productName))));
2908
+ };
2909
+
2910
+ export { EmailForm, EmailFormProvider, EmailPreview };
2911
+ //# sourceMappingURL=EmailForm.js.map