You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

6755 lines
199 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. /******/ (() => { // webpackBootstrap
  2. /******/ var __webpack_modules__ = ({
  3. /***/ "./resources/js/components/field-error.riot":
  4. /*!**************************************************!*\
  5. !*** ./resources/js/components/field-error.riot ***!
  6. \**************************************************/
  7. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  8. "use strict";
  9. __webpack_require__.r(__webpack_exports__);
  10. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  11. /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
  12. /* harmony export */ });
  13. /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
  14. 'css': null,
  15. 'exports': {
  16. state: {
  17. errors: [
  18. ],
  19. },
  20. /**
  21. *
  22. *
  23. * @param {Object} props [description]
  24. * @param {Object} state [description]
  25. *
  26. */
  27. onMounted(props, state)
  28. {
  29. // getting parent element for entire field
  30. const parent = this.root.closest('.field-group')
  31. // getting current element by name
  32. const element = document.querySelector('[name="' + props.name + '"]')
  33. // getting form
  34. const form = element.closest('form')
  35. // element, form are exists and nofieldupdate is not set
  36. // each change of the element dispatch a event to form validation
  37. if (element && form && !props.nofieldupdate) {
  38. element.addEventListener('input', (event) => {
  39. this.dispatchCustomEvent(event, form, props.name)
  40. })
  41. }
  42. // add custom event to listen to form-validation
  43. this.root.addEventListener('form-validation', (event) => {
  44. this.onFormValidation(event, parent)
  45. })
  46. },
  47. /**
  48. * process form validation triggered by form
  49. *
  50. * @param {Event} event
  51. * @param {Element} parent
  52. *
  53. */
  54. onFormValidation(event, parent)
  55. {
  56. // if detail is a value, set to errors
  57. if (event.detail) {
  58. this.state.errors = event.detail
  59. parent.classList.add('field--error')
  60. parent.classList.remove('field--valid')
  61. } else {
  62. this.state.errors = []
  63. parent.classList.remove('field--error')
  64. parent.classList.add('field--valid')
  65. }
  66. this.update()
  67. },
  68. /**
  69. * create event to send to form validation
  70. *
  71. * @param {Event} event
  72. * @param {Element} form
  73. * @param {string} name
  74. *
  75. */
  76. dispatchCustomEvent(event, form, name)
  77. {
  78. const fieldUpdateEvent = new CustomEvent('field-update', {
  79. 'detail': {
  80. 'name': name,
  81. 'value': event.target.value
  82. }
  83. })
  84. form.dispatchEvent(fieldUpdateEvent)
  85. }
  86. },
  87. 'template': function(
  88. template,
  89. expressionTypes,
  90. bindingTypes,
  91. getComponent
  92. ) {
  93. return template(
  94. '<div expr4="expr4" class="field-error"></div>',
  95. [
  96. {
  97. 'type': bindingTypes.IF,
  98. 'evaluate': function(
  99. _scope
  100. ) {
  101. return _scope.state.errors.length > 0;
  102. },
  103. 'redundantAttribute': 'expr4',
  104. 'selector': '[expr4]',
  105. 'template': template(
  106. '<ul><li expr5="expr5"></li></ul>',
  107. [
  108. {
  109. 'type': bindingTypes.EACH,
  110. 'getKey': null,
  111. 'condition': null,
  112. 'template': template(
  113. ' ',
  114. [
  115. {
  116. 'expressions': [
  117. {
  118. 'type': expressionTypes.TEXT,
  119. 'childNodeIndex': 0,
  120. 'evaluate': function(
  121. _scope
  122. ) {
  123. return [
  124. _scope.error
  125. ].join(
  126. ''
  127. );
  128. }
  129. }
  130. ]
  131. }
  132. ]
  133. ),
  134. 'redundantAttribute': 'expr5',
  135. 'selector': '[expr5]',
  136. 'itemName': 'error',
  137. 'indexName': null,
  138. 'evaluate': function(
  139. _scope
  140. ) {
  141. return _scope.state.errors;
  142. }
  143. }
  144. ]
  145. )
  146. }
  147. ]
  148. );
  149. },
  150. 'name': 'field-error'
  151. });
  152. /***/ }),
  153. /***/ "./resources/js/components/note-form.riot":
  154. /*!************************************************!*\
  155. !*** ./resources/js/components/note-form.riot ***!
  156. \************************************************/
  157. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  158. "use strict";
  159. __webpack_require__.r(__webpack_exports__);
  160. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  161. /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
  162. /* harmony export */ });
  163. /* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! axios */ "./node_modules/axios/index.js");
  164. /* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_0__);
  165. /* harmony import */ var riot__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! riot */ "./node_modules/riot/riot.esm.js");
  166. /* harmony import */ var _FormValidator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./../FormValidator */ "./resources/js/FormValidator.js");
  167. /* harmony import */ var _field_error_riot__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./field-error.riot */ "./resources/js/components/field-error.riot");
  168. riot__WEBPACK_IMPORTED_MODULE_3__.register('field-error', _field_error_riot__WEBPACK_IMPORTED_MODULE_2__.default)
  169. riot__WEBPACK_IMPORTED_MODULE_3__.mount('field-error')
  170. /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
  171. 'css': null,
  172. 'exports': {
  173. state: {
  174. note: undefined
  175. },
  176. onBeforeMount() {
  177. // show error if props is missing
  178. if (!this.props.bucketId) {
  179. console.error('ID of Bucket is Missing!')
  180. }
  181. },
  182. /**
  183. *
  184. *
  185. */
  186. onMounted(props, state) {
  187. // create form validation
  188. const formValidation = new _FormValidator__WEBPACK_IMPORTED_MODULE_1__.default('form', {
  189. 'title': {
  190. 'length': {
  191. 'maximum': 255
  192. }
  193. },
  194. 'content': {
  195. 'length': {
  196. 'maximum': 10922
  197. }
  198. }
  199. }, (event, data) => {
  200. this.handleSubmit(event, data)
  201. })
  202. },
  203. /**
  204. *
  205. *
  206. */
  207. handleSubmit(event, data) {
  208. let method = 'post'
  209. if (this.state.note && this.state.note._id) {
  210. method = 'put'
  211. }
  212. axios__WEBPACK_IMPORTED_MODULE_0___default()({
  213. method: method,
  214. url: '/api/note/' + this.props.bucketId,
  215. data: data
  216. }).then((response) => {
  217. this.state.note = response.data.data
  218. this.update()
  219. })
  220. }
  221. },
  222. 'template': function(
  223. template,
  224. expressionTypes,
  225. bindingTypes,
  226. getComponent
  227. ) {
  228. return template(
  229. '<div class="note-form"><div class="panel"><div class="panel__body"><form id="form" novalidate><input expr1="expr1" type="hidden" name="_id"/><div class="field-group"><label class="field-label">\n title\n <input type="text" class="field-text" name="title"/></label></div><div class="field-group"><label class="field-label">\n content\n <textarea name="content" class="field-text"></textarea></label></div><div class><div class="tabs"></div></div><div><button expr2="expr2" class="button"></button><button expr3="expr3" class="button" type="submit"></button></div></form></div></div></div>',
  230. [
  231. {
  232. 'type': bindingTypes.IF,
  233. 'evaluate': function(
  234. _scope
  235. ) {
  236. return _scope.state.note && _scope.state.note._id;
  237. },
  238. 'redundantAttribute': 'expr1',
  239. 'selector': '[expr1]',
  240. 'template': template(
  241. null,
  242. [
  243. {
  244. 'expressions': [
  245. {
  246. 'type': expressionTypes.ATTRIBUTE,
  247. 'name': 'value',
  248. 'evaluate': function(
  249. _scope
  250. ) {
  251. return _scope.state.note._id;
  252. }
  253. }
  254. ]
  255. }
  256. ]
  257. )
  258. },
  259. {
  260. 'type': bindingTypes.IF,
  261. 'evaluate': function(
  262. _scope
  263. ) {
  264. return !_scope.state.note || (_scope.state.note && !_scope.state.note._id);
  265. },
  266. 'redundantAttribute': 'expr2',
  267. 'selector': '[expr2]',
  268. 'template': template(
  269. '\n Create\n ',
  270. []
  271. )
  272. },
  273. {
  274. 'type': bindingTypes.IF,
  275. 'evaluate': function(
  276. _scope
  277. ) {
  278. return _scope.state.note && _scope.state.note._id;
  279. },
  280. 'redundantAttribute': 'expr3',
  281. 'selector': '[expr3]',
  282. 'template': template(
  283. '\n Save\n ',
  284. []
  285. )
  286. }
  287. ]
  288. );
  289. },
  290. 'name': 'app-note-form'
  291. });
  292. /***/ }),
  293. /***/ "./node_modules/axios/index.js":
  294. /*!*************************************!*\
  295. !*** ./node_modules/axios/index.js ***!
  296. \*************************************/
  297. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  298. module.exports = __webpack_require__(/*! ./lib/axios */ "./node_modules/axios/lib/axios.js");
  299. /***/ }),
  300. /***/ "./node_modules/axios/lib/adapters/xhr.js":
  301. /*!************************************************!*\
  302. !*** ./node_modules/axios/lib/adapters/xhr.js ***!
  303. \************************************************/
  304. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  305. "use strict";
  306. var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js");
  307. var settle = __webpack_require__(/*! ./../core/settle */ "./node_modules/axios/lib/core/settle.js");
  308. var cookies = __webpack_require__(/*! ./../helpers/cookies */ "./node_modules/axios/lib/helpers/cookies.js");
  309. var buildURL = __webpack_require__(/*! ./../helpers/buildURL */ "./node_modules/axios/lib/helpers/buildURL.js");
  310. var buildFullPath = __webpack_require__(/*! ../core/buildFullPath */ "./node_modules/axios/lib/core/buildFullPath.js");
  311. var parseHeaders = __webpack_require__(/*! ./../helpers/parseHeaders */ "./node_modules/axios/lib/helpers/parseHeaders.js");
  312. var isURLSameOrigin = __webpack_require__(/*! ./../helpers/isURLSameOrigin */ "./node_modules/axios/lib/helpers/isURLSameOrigin.js");
  313. var createError = __webpack_require__(/*! ../core/createError */ "./node_modules/axios/lib/core/createError.js");
  314. module.exports = function xhrAdapter(config) {
  315. return new Promise(function dispatchXhrRequest(resolve, reject) {
  316. var requestData = config.data;
  317. var requestHeaders = config.headers;
  318. if (utils.isFormData(requestData)) {
  319. delete requestHeaders['Content-Type']; // Let the browser set it
  320. }
  321. var request = new XMLHttpRequest();
  322. // HTTP basic authentication
  323. if (config.auth) {
  324. var username = config.auth.username || '';
  325. var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';
  326. requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
  327. }
  328. var fullPath = buildFullPath(config.baseURL, config.url);
  329. request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);
  330. // Set the request timeout in MS
  331. request.timeout = config.timeout;
  332. // Listen for ready state
  333. request.onreadystatechange = function handleLoad() {
  334. if (!request || request.readyState !== 4) {
  335. return;
  336. }
  337. // The request errored out and we didn't get a response, this will be
  338. // handled by onerror instead
  339. // With one exception: request that using file: protocol, most browsers
  340. // will return status as 0 even though it's a successful request
  341. if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
  342. return;
  343. }
  344. // Prepare the response
  345. var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
  346. var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response;
  347. var response = {
  348. data: responseData,
  349. status: request.status,
  350. statusText: request.statusText,
  351. headers: responseHeaders,
  352. config: config,
  353. request: request
  354. };
  355. settle(resolve, reject, response);
  356. // Clean up request
  357. request = null;
  358. };
  359. // Handle browser request cancellation (as opposed to a manual cancellation)
  360. request.onabort = function handleAbort() {
  361. if (!request) {
  362. return;
  363. }
  364. reject(createError('Request aborted', config, 'ECONNABORTED', request));
  365. // Clean up request
  366. request = null;
  367. };
  368. // Handle low level network errors
  369. request.onerror = function handleError() {
  370. // Real errors are hidden from us by the browser
  371. // onerror should only fire if it's a network error
  372. reject(createError('Network Error', config, null, request));
  373. // Clean up request
  374. request = null;
  375. };
  376. // Handle timeout
  377. request.ontimeout = function handleTimeout() {
  378. var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded';
  379. if (config.timeoutErrorMessage) {
  380. timeoutErrorMessage = config.timeoutErrorMessage;
  381. }
  382. reject(createError(timeoutErrorMessage, config, 'ECONNABORTED',
  383. request));
  384. // Clean up request
  385. request = null;
  386. };
  387. // Add xsrf header
  388. // This is only done if running in a standard browser environment.
  389. // Specifically not if we're in a web worker, or react-native.
  390. if (utils.isStandardBrowserEnv()) {
  391. // Add xsrf header
  392. var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?
  393. cookies.read(config.xsrfCookieName) :
  394. undefined;
  395. if (xsrfValue) {
  396. requestHeaders[config.xsrfHeaderName] = xsrfValue;
  397. }
  398. }
  399. // Add headers to the request
  400. if ('setRequestHeader' in request) {
  401. utils.forEach(requestHeaders, function setRequestHeader(val, key) {
  402. if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
  403. // Remove Content-Type if data is undefined
  404. delete requestHeaders[key];
  405. } else {
  406. // Otherwise add header to the request
  407. request.setRequestHeader(key, val);
  408. }
  409. });
  410. }
  411. // Add withCredentials to request if needed
  412. if (!utils.isUndefined(config.withCredentials)) {
  413. request.withCredentials = !!config.withCredentials;
  414. }
  415. // Add responseType to request if needed
  416. if (config.responseType) {
  417. try {
  418. request.responseType = config.responseType;
  419. } catch (e) {
  420. // Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2.
  421. // But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function.
  422. if (config.responseType !== 'json') {
  423. throw e;
  424. }
  425. }
  426. }
  427. // Handle progress if needed
  428. if (typeof config.onDownloadProgress === 'function') {
  429. request.addEventListener('progress', config.onDownloadProgress);
  430. }
  431. // Not all browsers support upload events
  432. if (typeof config.onUploadProgress === 'function' && request.upload) {
  433. request.upload.addEventListener('progress', config.onUploadProgress);
  434. }
  435. if (config.cancelToken) {
  436. // Handle cancellation
  437. config.cancelToken.promise.then(function onCanceled(cancel) {
  438. if (!request) {
  439. return;
  440. }
  441. request.abort();
  442. reject(cancel);
  443. // Clean up request
  444. request = null;
  445. });
  446. }
  447. if (!requestData) {
  448. requestData = null;
  449. }
  450. // Send the request
  451. request.send(requestData);
  452. });
  453. };
  454. /***/ }),
  455. /***/ "./node_modules/axios/lib/axios.js":
  456. /*!*****************************************!*\
  457. !*** ./node_modules/axios/lib/axios.js ***!
  458. \*****************************************/
  459. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  460. "use strict";
  461. var utils = __webpack_require__(/*! ./utils */ "./node_modules/axios/lib/utils.js");
  462. var bind = __webpack_require__(/*! ./helpers/bind */ "./node_modules/axios/lib/helpers/bind.js");
  463. var Axios = __webpack_require__(/*! ./core/Axios */ "./node_modules/axios/lib/core/Axios.js");
  464. var mergeConfig = __webpack_require__(/*! ./core/mergeConfig */ "./node_modules/axios/lib/core/mergeConfig.js");
  465. var defaults = __webpack_require__(/*! ./defaults */ "./node_modules/axios/lib/defaults.js");
  466. /**
  467. * Create an instance of Axios
  468. *
  469. * @param {Object} defaultConfig The default config for the instance
  470. * @return {Axios} A new instance of Axios
  471. */
  472. function createInstance(defaultConfig) {
  473. var context = new Axios(defaultConfig);
  474. var instance = bind(Axios.prototype.request, context);
  475. // Copy axios.prototype to instance
  476. utils.extend(instance, Axios.prototype, context);
  477. // Copy context to instance
  478. utils.extend(instance, context);
  479. return instance;
  480. }
  481. // Create the default instance to be exported
  482. var axios = createInstance(defaults);
  483. // Expose Axios class to allow class inheritance
  484. axios.Axios = Axios;
  485. // Factory for creating new instances
  486. axios.create = function create(instanceConfig) {
  487. return createInstance(mergeConfig(axios.defaults, instanceConfig));
  488. };
  489. // Expose Cancel & CancelToken
  490. axios.Cancel = __webpack_require__(/*! ./cancel/Cancel */ "./node_modules/axios/lib/cancel/Cancel.js");
  491. axios.CancelToken = __webpack_require__(/*! ./cancel/CancelToken */ "./node_modules/axios/lib/cancel/CancelToken.js");
  492. axios.isCancel = __webpack_require__(/*! ./cancel/isCancel */ "./node_modules/axios/lib/cancel/isCancel.js");
  493. // Expose all/spread
  494. axios.all = function all(promises) {
  495. return Promise.all(promises);
  496. };
  497. axios.spread = __webpack_require__(/*! ./helpers/spread */ "./node_modules/axios/lib/helpers/spread.js");
  498. // Expose isAxiosError
  499. axios.isAxiosError = __webpack_require__(/*! ./helpers/isAxiosError */ "./node_modules/axios/lib/helpers/isAxiosError.js");
  500. module.exports = axios;
  501. // Allow use of default import syntax in TypeScript
  502. module.exports.default = axios;
  503. /***/ }),
  504. /***/ "./node_modules/axios/lib/cancel/Cancel.js":
  505. /*!*************************************************!*\
  506. !*** ./node_modules/axios/lib/cancel/Cancel.js ***!
  507. \*************************************************/
  508. /***/ ((module) => {
  509. "use strict";
  510. /**
  511. * A `Cancel` is an object that is thrown when an operation is canceled.
  512. *
  513. * @class
  514. * @param {string=} message The message.
  515. */
  516. function Cancel(message) {
  517. this.message = message;
  518. }
  519. Cancel.prototype.toString = function toString() {
  520. return 'Cancel' + (this.message ? ': ' + this.message : '');
  521. };
  522. Cancel.prototype.__CANCEL__ = true;
  523. module.exports = Cancel;
  524. /***/ }),
  525. /***/ "./node_modules/axios/lib/cancel/CancelToken.js":
  526. /*!******************************************************!*\
  527. !*** ./node_modules/axios/lib/cancel/CancelToken.js ***!
  528. \******************************************************/
  529. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  530. "use strict";
  531. var Cancel = __webpack_require__(/*! ./Cancel */ "./node_modules/axios/lib/cancel/Cancel.js");
  532. /**
  533. * A `CancelToken` is an object that can be used to request cancellation of an operation.
  534. *
  535. * @class
  536. * @param {Function} executor The executor function.
  537. */
  538. function CancelToken(executor) {
  539. if (typeof executor !== 'function') {
  540. throw new TypeError('executor must be a function.');
  541. }
  542. var resolvePromise;
  543. this.promise = new Promise(function promiseExecutor(resolve) {
  544. resolvePromise = resolve;
  545. });
  546. var token = this;
  547. executor(function cancel(message) {
  548. if (token.reason) {
  549. // Cancellation has already been requested
  550. return;
  551. }
  552. token.reason = new Cancel(message);
  553. resolvePromise(token.reason);
  554. });
  555. }
  556. /**
  557. * Throws a `Cancel` if cancellation has been requested.
  558. */
  559. CancelToken.prototype.throwIfRequested = function throwIfRequested() {
  560. if (this.reason) {
  561. throw this.reason;
  562. }
  563. };
  564. /**
  565. * Returns an object that contains a new `CancelToken` and a function that, when called,
  566. * cancels the `CancelToken`.
  567. */
  568. CancelToken.source = function source() {
  569. var cancel;
  570. var token = new CancelToken(function executor(c) {
  571. cancel = c;
  572. });
  573. return {
  574. token: token,
  575. cancel: cancel
  576. };
  577. };
  578. module.exports = CancelToken;
  579. /***/ }),
  580. /***/ "./node_modules/axios/lib/cancel/isCancel.js":
  581. /*!***************************************************!*\
  582. !*** ./node_modules/axios/lib/cancel/isCancel.js ***!
  583. \***************************************************/
  584. /***/ ((module) => {
  585. "use strict";
  586. module.exports = function isCancel(value) {
  587. return !!(value && value.__CANCEL__);
  588. };
  589. /***/ }),
  590. /***/ "./node_modules/axios/lib/core/Axios.js":
  591. /*!**********************************************!*\
  592. !*** ./node_modules/axios/lib/core/Axios.js ***!
  593. \**********************************************/
  594. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  595. "use strict";
  596. var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js");
  597. var buildURL = __webpack_require__(/*! ../helpers/buildURL */ "./node_modules/axios/lib/helpers/buildURL.js");
  598. var InterceptorManager = __webpack_require__(/*! ./InterceptorManager */ "./node_modules/axios/lib/core/InterceptorManager.js");
  599. var dispatchRequest = __webpack_require__(/*! ./dispatchRequest */ "./node_modules/axios/lib/core/dispatchRequest.js");
  600. var mergeConfig = __webpack_require__(/*! ./mergeConfig */ "./node_modules/axios/lib/core/mergeConfig.js");
  601. /**
  602. * Create a new instance of Axios
  603. *
  604. * @param {Object} instanceConfig The default config for the instance
  605. */
  606. function Axios(instanceConfig) {
  607. this.defaults = instanceConfig;
  608. this.interceptors = {
  609. request: new InterceptorManager(),
  610. response: new InterceptorManager()
  611. };
  612. }
  613. /**
  614. * Dispatch a request
  615. *
  616. * @param {Object} config The config specific for this request (merged with this.defaults)
  617. */
  618. Axios.prototype.request = function request(config) {
  619. /*eslint no-param-reassign:0*/
  620. // Allow for axios('example/url'[, config]) a la fetch API
  621. if (typeof config === 'string') {
  622. config = arguments[1] || {};
  623. config.url = arguments[0];
  624. } else {
  625. config = config || {};
  626. }
  627. config = mergeConfig(this.defaults, config);
  628. // Set config.method
  629. if (config.method) {
  630. config.method = config.method.toLowerCase();
  631. } else if (this.defaults.method) {
  632. config.method = this.defaults.method.toLowerCase();
  633. } else {
  634. config.method = 'get';
  635. }
  636. // Hook up interceptors middleware
  637. var chain = [dispatchRequest, undefined];
  638. var promise = Promise.resolve(config);
  639. this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
  640. chain.unshift(interceptor.fulfilled, interceptor.rejected);
  641. });
  642. this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
  643. chain.push(interceptor.fulfilled, interceptor.rejected);
  644. });
  645. while (chain.length) {
  646. promise = promise.then(chain.shift(), chain.shift());
  647. }
  648. return promise;
  649. };
  650. Axios.prototype.getUri = function getUri(config) {
  651. config = mergeConfig(this.defaults, config);
  652. return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, '');
  653. };
  654. // Provide aliases for supported request methods
  655. utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
  656. /*eslint func-names:0*/
  657. Axios.prototype[method] = function(url, config) {
  658. return this.request(mergeConfig(config || {}, {
  659. method: method,
  660. url: url,
  661. data: (config || {}).data
  662. }));
  663. };
  664. });
  665. utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
  666. /*eslint func-names:0*/
  667. Axios.prototype[method] = function(url, data, config) {
  668. return this.request(mergeConfig(config || {}, {
  669. method: method,
  670. url: url,
  671. data: data
  672. }));
  673. };
  674. });
  675. module.exports = Axios;
  676. /***/ }),
  677. /***/ "./node_modules/axios/lib/core/InterceptorManager.js":
  678. /*!***********************************************************!*\
  679. !*** ./node_modules/axios/lib/core/InterceptorManager.js ***!
  680. \***********************************************************/
  681. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  682. "use strict";
  683. var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js");
  684. function InterceptorManager() {
  685. this.handlers = [];
  686. }
  687. /**
  688. * Add a new interceptor to the stack
  689. *
  690. * @param {Function} fulfilled The function to handle `then` for a `Promise`
  691. * @param {Function} rejected The function to handle `reject` for a `Promise`
  692. *
  693. * @return {Number} An ID used to remove interceptor later
  694. */
  695. InterceptorManager.prototype.use = function use(fulfilled, rejected) {
  696. this.handlers.push({
  697. fulfilled: fulfilled,
  698. rejected: rejected
  699. });
  700. return this.handlers.length - 1;
  701. };
  702. /**
  703. * Remove an interceptor from the stack
  704. *
  705. * @param {Number} id The ID that was returned by `use`
  706. */
  707. InterceptorManager.prototype.eject = function eject(id) {
  708. if (this.handlers[id]) {
  709. this.handlers[id] = null;
  710. }
  711. };
  712. /**
  713. * Iterate over all the registered interceptors
  714. *
  715. * This method is particularly useful for skipping over any
  716. * interceptors that may have become `null` calling `eject`.
  717. *
  718. * @param {Function} fn The function to call for each interceptor
  719. */
  720. InterceptorManager.prototype.forEach = function forEach(fn) {
  721. utils.forEach(this.handlers, function forEachHandler(h) {
  722. if (h !== null) {
  723. fn(h);
  724. }
  725. });
  726. };
  727. module.exports = InterceptorManager;
  728. /***/ }),
  729. /***/ "./node_modules/axios/lib/core/buildFullPath.js":
  730. /*!******************************************************!*\
  731. !*** ./node_modules/axios/lib/core/buildFullPath.js ***!
  732. \******************************************************/
  733. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  734. "use strict";
  735. var isAbsoluteURL = __webpack_require__(/*! ../helpers/isAbsoluteURL */ "./node_modules/axios/lib/helpers/isAbsoluteURL.js");
  736. var combineURLs = __webpack_require__(/*! ../helpers/combineURLs */ "./node_modules/axios/lib/helpers/combineURLs.js");
  737. /**
  738. * Creates a new URL by combining the baseURL with the requestedURL,
  739. * only when the requestedURL is not already an absolute URL.
  740. * If the requestURL is absolute, this function returns the requestedURL untouched.
  741. *
  742. * @param {string} baseURL The base URL
  743. * @param {string} requestedURL Absolute or relative URL to combine
  744. * @returns {string} The combined full path
  745. */
  746. module.exports = function buildFullPath(baseURL, requestedURL) {
  747. if (baseURL && !isAbsoluteURL(requestedURL)) {
  748. return combineURLs(baseURL, requestedURL);
  749. }
  750. return requestedURL;
  751. };
  752. /***/ }),
  753. /***/ "./node_modules/axios/lib/core/createError.js":
  754. /*!****************************************************!*\
  755. !*** ./node_modules/axios/lib/core/createError.js ***!
  756. \****************************************************/
  757. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  758. "use strict";
  759. var enhanceError = __webpack_require__(/*! ./enhanceError */ "./node_modules/axios/lib/core/enhanceError.js");
  760. /**
  761. * Create an Error with the specified message, config, error code, request and response.
  762. *
  763. * @param {string} message The error message.
  764. * @param {Object} config The config.
  765. * @param {string} [code] The error code (for example, 'ECONNABORTED').
  766. * @param {Object} [request] The request.
  767. * @param {Object} [response] The response.
  768. * @returns {Error} The created error.
  769. */
  770. module.exports = function createError(message, config, code, request, response) {
  771. var error = new Error(message);
  772. return enhanceError(error, config, code, request, response);
  773. };
  774. /***/ }),
  775. /***/ "./node_modules/axios/lib/core/dispatchRequest.js":
  776. /*!********************************************************!*\
  777. !*** ./node_modules/axios/lib/core/dispatchRequest.js ***!
  778. \********************************************************/
  779. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  780. "use strict";
  781. var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js");
  782. var transformData = __webpack_require__(/*! ./transformData */ "./node_modules/axios/lib/core/transformData.js");
  783. var isCancel = __webpack_require__(/*! ../cancel/isCancel */ "./node_modules/axios/lib/cancel/isCancel.js");
  784. var defaults = __webpack_require__(/*! ../defaults */ "./node_modules/axios/lib/defaults.js");
  785. /**
  786. * Throws a `Cancel` if cancellation has been requested.
  787. */
  788. function throwIfCancellationRequested(config) {
  789. if (config.cancelToken) {
  790. config.cancelToken.throwIfRequested();
  791. }
  792. }
  793. /**
  794. * Dispatch a request to the server using the configured adapter.
  795. *
  796. * @param {object} config The config that is to be used for the request
  797. * @returns {Promise} The Promise to be fulfilled
  798. */
  799. module.exports = function dispatchRequest(config) {
  800. throwIfCancellationRequested(config);
  801. // Ensure headers exist
  802. config.headers = config.headers || {};
  803. // Transform request data
  804. config.data = transformData(
  805. config.data,
  806. config.headers,
  807. config.transformRequest
  808. );
  809. // Flatten headers
  810. config.headers = utils.merge(
  811. config.headers.common || {},
  812. config.headers[config.method] || {},
  813. config.headers
  814. );
  815. utils.forEach(
  816. ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
  817. function cleanHeaderConfig(method) {
  818. delete config.headers[method];
  819. }
  820. );
  821. var adapter = config.adapter || defaults.adapter;
  822. return adapter(config).then(function onAdapterResolution(response) {
  823. throwIfCancellationRequested(config);
  824. // Transform response data
  825. response.data = transformData(
  826. response.data,
  827. response.headers,
  828. config.transformResponse
  829. );
  830. return response;
  831. }, function onAdapterRejection(reason) {
  832. if (!isCancel(reason)) {
  833. throwIfCancellationRequested(config);
  834. // Transform response data
  835. if (reason && reason.response) {
  836. reason.response.data = transformData(
  837. reason.response.data,
  838. reason.response.headers,
  839. config.transformResponse
  840. );
  841. }
  842. }
  843. return Promise.reject(reason);
  844. });
  845. };
  846. /***/ }),
  847. /***/ "./node_modules/axios/lib/core/enhanceError.js":
  848. /*!*****************************************************!*\
  849. !*** ./node_modules/axios/lib/core/enhanceError.js ***!
  850. \*****************************************************/
  851. /***/ ((module) => {
  852. "use strict";
  853. /**
  854. * Update an Error with the specified config, error code, and response.
  855. *
  856. * @param {Error} error The error to update.
  857. * @param {Object} config The config.
  858. * @param {string} [code] The error code (for example, 'ECONNABORTED').
  859. * @param {Object} [request] The request.
  860. * @param {Object} [response] The response.
  861. * @returns {Error} The error.
  862. */
  863. module.exports = function enhanceError(error, config, code, request, response) {
  864. error.config = config;
  865. if (code) {
  866. error.code = code;
  867. }
  868. error.request = request;
  869. error.response = response;
  870. error.isAxiosError = true;
  871. error.toJSON = function toJSON() {
  872. return {
  873. // Standard
  874. message: this.message,
  875. name: this.name,
  876. // Microsoft
  877. description: this.description,
  878. number: this.number,
  879. // Mozilla
  880. fileName: this.fileName,
  881. lineNumber: this.lineNumber,
  882. columnNumber: this.columnNumber,
  883. stack: this.stack,
  884. // Axios
  885. config: this.config,
  886. code: this.code
  887. };
  888. };
  889. return error;
  890. };
  891. /***/ }),
  892. /***/ "./node_modules/axios/lib/core/mergeConfig.js":
  893. /*!****************************************************!*\
  894. !*** ./node_modules/axios/lib/core/mergeConfig.js ***!
  895. \****************************************************/
  896. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  897. "use strict";
  898. var utils = __webpack_require__(/*! ../utils */ "./node_modules/axios/lib/utils.js");
  899. /**
  900. * Config-specific merge-function which creates a new config-object
  901. * by merging two configuration objects together.
  902. *
  903. * @param {Object} config1
  904. * @param {Object} config2
  905. * @returns {Object} New object resulting from merging config2 to config1
  906. */
  907. module.exports = function mergeConfig(config1, config2) {
  908. // eslint-disable-next-line no-param-reassign
  909. config2 = config2 || {};
  910. var config = {};
  911. var valueFromConfig2Keys = ['url', 'method', 'data'];
  912. var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy', 'params'];
  913. var defaultToConfig2Keys = [
  914. 'baseURL', 'transformRequest', 'transformResponse', 'paramsSerializer',
  915. 'timeout', 'timeoutMessage', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName',
  916. 'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', 'decompress',
  917. 'maxContentLength', 'maxBodyLength', 'maxRedirects', 'transport', 'httpAgent',
  918. 'httpsAgent', 'cancelToken', 'socketPath', 'responseEncoding'
  919. ];
  920. var directMergeKeys = ['validateStatus'];
  921. function getMergedValue(target, source) {
  922. if (utils.isPlainObject(target) && utils.isPlainObject(source)) {
  923. return utils.merge(target, source);
  924. } else if (utils.isPlainObject(source)) {
  925. return utils.merge({}, source);
  926. } else if (utils.isArray(source)) {
  927. return source.slice();
  928. }
  929. return source;
  930. }
  931. function mergeDeepProperties(prop) {
  932. if (!utils.isUndefined(config2[prop])) {
  933. config[prop] = getMergedValue(config1[prop], config2[prop]);
  934. } else if (!utils.isUndefined(config1[prop])) {
  935. config[prop] = getMergedValue(undefined, config1[prop]);
  936. }
  937. }
  938. utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) {
  939. if (!utils.isUndefined(config2[prop])) {
  940. config[prop] = getMergedValue(undefined, config2[prop]);
  941. }
  942. });
  943. utils.forEach(mergeDeepPropertiesKeys, mergeDeepProperties);
  944. utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) {
  945. if (!utils.isUndefined(config2[prop])) {
  946. config[prop] = getMergedValue(undefined, config2[prop]);
  947. } else if (!utils.isUndefined(config1[prop])) {
  948. config[prop] = getMergedValue(undefined, config1[prop]);
  949. }
  950. });
  951. utils.forEach(directMergeKeys, function merge(prop) {
  952. if (prop in config2) {
  953. config[prop] = getMergedValue(config1[prop], config2[prop]);
  954. } else if (prop in config1) {
  955. config[prop] = getMergedValue(undefined, config1[prop]);
  956. }
  957. });
  958. var axiosKeys = valueFromConfig2Keys
  959. .concat(mergeDeepPropertiesKeys)
  960. .concat(defaultToConfig2Keys)
  961. .concat(directMergeKeys);
  962. var otherKeys = Object
  963. .keys(config1)
  964. .concat(Object.keys(config2))
  965. .filter(function filterAxiosKeys(key) {
  966. return axiosKeys.indexOf(key) === -1;
  967. });
  968. utils.forEach(otherKeys, mergeDeepProperties);
  969. return config;
  970. };
  971. /***/ }),
  972. /***/ "./node_modules/axios/lib/core/settle.js":
  973. /*!***********************************************!*\
  974. !*** ./node_modules/axios/lib/core/settle.js ***!
  975. \***********************************************/
  976. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  977. "use strict";
  978. var createError = __webpack_require__(/*! ./createError */ "./node_modules/axios/lib/core/createError.js");
  979. /**
  980. * Resolve or reject a Promise based on response status.
  981. *
  982. * @param {Function} resolve A function that resolves the promise.
  983. * @param {Function} reject A function that rejects the promise.
  984. * @param {object} response The response.
  985. */
  986. module.exports = function settle(resolve, reject, response) {
  987. var validateStatus = response.config.validateStatus;
  988. if (!response.status || !validateStatus || validateStatus(response.status)) {
  989. resolve(response);
  990. } else {
  991. reject(createError(
  992. 'Request failed with status code ' + response.status,
  993. response.config,
  994. null,
  995. response.request,
  996. response
  997. ));
  998. }
  999. };
  1000. /***/ }),
  1001. /***/ "./node_modules/axios/lib/core/transformData.js":
  1002. /*!******************************************************!*\
  1003. !*** ./node_modules/axios/lib/core/transformData.js ***!
  1004. \******************************************************/
  1005. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1006. "use strict";
  1007. var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js");
  1008. /**
  1009. * Transform the data for a request or a response
  1010. *
  1011. * @param {Object|String} data The data to be transformed
  1012. * @param {Array} headers The headers for the request or response
  1013. * @param {Array|Function} fns A single function or Array of functions
  1014. * @returns {*} The resulting transformed data
  1015. */
  1016. module.exports = function transformData(data, headers, fns) {
  1017. /*eslint no-param-reassign:0*/
  1018. utils.forEach(fns, function transform(fn) {
  1019. data = fn(data, headers);
  1020. });
  1021. return data;
  1022. };
  1023. /***/ }),
  1024. /***/ "./node_modules/axios/lib/defaults.js":
  1025. /*!********************************************!*\
  1026. !*** ./node_modules/axios/lib/defaults.js ***!
  1027. \********************************************/
  1028. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1029. "use strict";
  1030. /* provided dependency */ var process = __webpack_require__(/*! process/browser */ "./node_modules/process/browser.js");
  1031. var utils = __webpack_require__(/*! ./utils */ "./node_modules/axios/lib/utils.js");
  1032. var normalizeHeaderName = __webpack_require__(/*! ./helpers/normalizeHeaderName */ "./node_modules/axios/lib/helpers/normalizeHeaderName.js");
  1033. var DEFAULT_CONTENT_TYPE = {
  1034. 'Content-Type': 'application/x-www-form-urlencoded'
  1035. };
  1036. function setContentTypeIfUnset(headers, value) {
  1037. if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
  1038. headers['Content-Type'] = value;
  1039. }
  1040. }
  1041. function getDefaultAdapter() {
  1042. var adapter;
  1043. if (typeof XMLHttpRequest !== 'undefined') {
  1044. // For browsers use XHR adapter
  1045. adapter = __webpack_require__(/*! ./adapters/xhr */ "./node_modules/axios/lib/adapters/xhr.js");
  1046. } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
  1047. // For node use HTTP adapter
  1048. adapter = __webpack_require__(/*! ./adapters/http */ "./node_modules/axios/lib/adapters/xhr.js");
  1049. }
  1050. return adapter;
  1051. }
  1052. var defaults = {
  1053. adapter: getDefaultAdapter(),
  1054. transformRequest: [function transformRequest(data, headers) {
  1055. normalizeHeaderName(headers, 'Accept');
  1056. normalizeHeaderName(headers, 'Content-Type');
  1057. if (utils.isFormData(data) ||
  1058. utils.isArrayBuffer(data) ||
  1059. utils.isBuffer(data) ||
  1060. utils.isStream(data) ||
  1061. utils.isFile(data) ||
  1062. utils.isBlob(data)
  1063. ) {
  1064. return data;
  1065. }
  1066. if (utils.isArrayBufferView(data)) {
  1067. return data.buffer;
  1068. }
  1069. if (utils.isURLSearchParams(data)) {
  1070. setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
  1071. return data.toString();
  1072. }
  1073. if (utils.isObject(data)) {
  1074. setContentTypeIfUnset(headers, 'application/json;charset=utf-8');
  1075. return JSON.stringify(data);
  1076. }
  1077. return data;
  1078. }],
  1079. transformResponse: [function transformResponse(data) {
  1080. /*eslint no-param-reassign:0*/
  1081. if (typeof data === 'string') {
  1082. try {
  1083. data = JSON.parse(data);
  1084. } catch (e) { /* Ignore */ }
  1085. }
  1086. return data;
  1087. }],
  1088. /**
  1089. * A timeout in milliseconds to abort a request. If set to 0 (default) a
  1090. * timeout is not created.
  1091. */
  1092. timeout: 0,
  1093. xsrfCookieName: 'XSRF-TOKEN',
  1094. xsrfHeaderName: 'X-XSRF-TOKEN',
  1095. maxContentLength: -1,
  1096. maxBodyLength: -1,
  1097. validateStatus: function validateStatus(status) {
  1098. return status >= 200 && status < 300;
  1099. }
  1100. };
  1101. defaults.headers = {
  1102. common: {
  1103. 'Accept': 'application/json, text/plain, */*'
  1104. }
  1105. };
  1106. utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
  1107. defaults.headers[method] = {};
  1108. });
  1109. utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
  1110. defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
  1111. });
  1112. module.exports = defaults;
  1113. /***/ }),
  1114. /***/ "./node_modules/axios/lib/helpers/bind.js":
  1115. /*!************************************************!*\
  1116. !*** ./node_modules/axios/lib/helpers/bind.js ***!
  1117. \************************************************/
  1118. /***/ ((module) => {
  1119. "use strict";
  1120. module.exports = function bind(fn, thisArg) {
  1121. return function wrap() {
  1122. var args = new Array(arguments.length);
  1123. for (var i = 0; i < args.length; i++) {
  1124. args[i] = arguments[i];
  1125. }
  1126. return fn.apply(thisArg, args);
  1127. };
  1128. };
  1129. /***/ }),
  1130. /***/ "./node_modules/axios/lib/helpers/buildURL.js":
  1131. /*!****************************************************!*\
  1132. !*** ./node_modules/axios/lib/helpers/buildURL.js ***!
  1133. \****************************************************/
  1134. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1135. "use strict";
  1136. var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js");
  1137. function encode(val) {
  1138. return encodeURIComponent(val).
  1139. replace(/%3A/gi, ':').
  1140. replace(/%24/g, '$').
  1141. replace(/%2C/gi, ',').
  1142. replace(/%20/g, '+').
  1143. replace(/%5B/gi, '[').
  1144. replace(/%5D/gi, ']');
  1145. }
  1146. /**
  1147. * Build a URL by appending params to the end
  1148. *
  1149. * @param {string} url The base of the url (e.g., http://www.google.com)
  1150. * @param {object} [params] The params to be appended
  1151. * @returns {string} The formatted url
  1152. */
  1153. module.exports = function buildURL(url, params, paramsSerializer) {
  1154. /*eslint no-param-reassign:0*/
  1155. if (!params) {
  1156. return url;
  1157. }
  1158. var serializedParams;
  1159. if (paramsSerializer) {
  1160. serializedParams = paramsSerializer(params);
  1161. } else if (utils.isURLSearchParams(params)) {
  1162. serializedParams = params.toString();
  1163. } else {
  1164. var parts = [];
  1165. utils.forEach(params, function serialize(val, key) {
  1166. if (val === null || typeof val === 'undefined') {
  1167. return;
  1168. }
  1169. if (utils.isArray(val)) {
  1170. key = key + '[]';
  1171. } else {
  1172. val = [val];
  1173. }
  1174. utils.forEach(val, function parseValue(v) {
  1175. if (utils.isDate(v)) {
  1176. v = v.toISOString();
  1177. } else if (utils.isObject(v)) {
  1178. v = JSON.stringify(v);
  1179. }
  1180. parts.push(encode(key) + '=' + encode(v));
  1181. });
  1182. });
  1183. serializedParams = parts.join('&');
  1184. }
  1185. if (serializedParams) {
  1186. var hashmarkIndex = url.indexOf('#');
  1187. if (hashmarkIndex !== -1) {
  1188. url = url.slice(0, hashmarkIndex);
  1189. }
  1190. url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
  1191. }
  1192. return url;
  1193. };
  1194. /***/ }),
  1195. /***/ "./node_modules/axios/lib/helpers/combineURLs.js":
  1196. /*!*******************************************************!*\
  1197. !*** ./node_modules/axios/lib/helpers/combineURLs.js ***!
  1198. \*******************************************************/
  1199. /***/ ((module) => {
  1200. "use strict";
  1201. /**
  1202. * Creates a new URL by combining the specified URLs
  1203. *
  1204. * @param {string} baseURL The base URL
  1205. * @param {string} relativeURL The relative URL
  1206. * @returns {string} The combined URL
  1207. */
  1208. module.exports = function combineURLs(baseURL, relativeURL) {
  1209. return relativeURL
  1210. ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
  1211. : baseURL;
  1212. };
  1213. /***/ }),
  1214. /***/ "./node_modules/axios/lib/helpers/cookies.js":
  1215. /*!***************************************************!*\
  1216. !*** ./node_modules/axios/lib/helpers/cookies.js ***!
  1217. \***************************************************/
  1218. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1219. "use strict";
  1220. var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js");
  1221. module.exports = (
  1222. utils.isStandardBrowserEnv() ?
  1223. // Standard browser envs support document.cookie
  1224. (function standardBrowserEnv() {
  1225. return {
  1226. write: function write(name, value, expires, path, domain, secure) {
  1227. var cookie = [];
  1228. cookie.push(name + '=' + encodeURIComponent(value));
  1229. if (utils.isNumber(expires)) {
  1230. cookie.push('expires=' + new Date(expires).toGMTString());
  1231. }
  1232. if (utils.isString(path)) {
  1233. cookie.push('path=' + path);
  1234. }
  1235. if (utils.isString(domain)) {
  1236. cookie.push('domain=' + domain);
  1237. }
  1238. if (secure === true) {
  1239. cookie.push('secure');
  1240. }
  1241. document.cookie = cookie.join('; ');
  1242. },
  1243. read: function read(name) {
  1244. var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
  1245. return (match ? decodeURIComponent(match[3]) : null);
  1246. },
  1247. remove: function remove(name) {
  1248. this.write(name, '', Date.now() - 86400000);
  1249. }
  1250. };
  1251. })() :
  1252. // Non standard browser env (web workers, react-native) lack needed support.
  1253. (function nonStandardBrowserEnv() {
  1254. return {
  1255. write: function write() {},
  1256. read: function read() { return null; },
  1257. remove: function remove() {}
  1258. };
  1259. })()
  1260. );
  1261. /***/ }),
  1262. /***/ "./node_modules/axios/lib/helpers/isAbsoluteURL.js":
  1263. /*!*********************************************************!*\
  1264. !*** ./node_modules/axios/lib/helpers/isAbsoluteURL.js ***!
  1265. \*********************************************************/
  1266. /***/ ((module) => {
  1267. "use strict";
  1268. /**
  1269. * Determines whether the specified URL is absolute
  1270. *
  1271. * @param {string} url The URL to test
  1272. * @returns {boolean} True if the specified URL is absolute, otherwise false
  1273. */
  1274. module.exports = function isAbsoluteURL(url) {
  1275. // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
  1276. // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
  1277. // by any combination of letters, digits, plus, period, or hyphen.
  1278. return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
  1279. };
  1280. /***/ }),
  1281. /***/ "./node_modules/axios/lib/helpers/isAxiosError.js":
  1282. /*!********************************************************!*\
  1283. !*** ./node_modules/axios/lib/helpers/isAxiosError.js ***!
  1284. \********************************************************/
  1285. /***/ ((module) => {
  1286. "use strict";
  1287. /**
  1288. * Determines whether the payload is an error thrown by Axios
  1289. *
  1290. * @param {*} payload The value to test
  1291. * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
  1292. */
  1293. module.exports = function isAxiosError(payload) {
  1294. return (typeof payload === 'object') && (payload.isAxiosError === true);
  1295. };
  1296. /***/ }),
  1297. /***/ "./node_modules/axios/lib/helpers/isURLSameOrigin.js":
  1298. /*!***********************************************************!*\
  1299. !*** ./node_modules/axios/lib/helpers/isURLSameOrigin.js ***!
  1300. \***********************************************************/
  1301. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1302. "use strict";
  1303. var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js");
  1304. module.exports = (
  1305. utils.isStandardBrowserEnv() ?
  1306. // Standard browser envs have full support of the APIs needed to test
  1307. // whether the request URL is of the same origin as current location.
  1308. (function standardBrowserEnv() {
  1309. var msie = /(msie|trident)/i.test(navigator.userAgent);
  1310. var urlParsingNode = document.createElement('a');
  1311. var originURL;
  1312. /**
  1313. * Parse a URL to discover it's components
  1314. *
  1315. * @param {String} url The URL to be parsed
  1316. * @returns {Object}
  1317. */
  1318. function resolveURL(url) {
  1319. var href = url;
  1320. if (msie) {
  1321. // IE needs attribute set twice to normalize properties
  1322. urlParsingNode.setAttribute('href', href);
  1323. href = urlParsingNode.href;
  1324. }
  1325. urlParsingNode.setAttribute('href', href);
  1326. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  1327. return {
  1328. href: urlParsingNode.href,
  1329. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  1330. host: urlParsingNode.host,
  1331. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  1332. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  1333. hostname: urlParsingNode.hostname,
  1334. port: urlParsingNode.port,
  1335. pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
  1336. urlParsingNode.pathname :
  1337. '/' + urlParsingNode.pathname
  1338. };
  1339. }
  1340. originURL = resolveURL(window.location.href);
  1341. /**
  1342. * Determine if a URL shares the same origin as the current location
  1343. *
  1344. * @param {String} requestURL The URL to test
  1345. * @returns {boolean} True if URL shares the same origin, otherwise false
  1346. */
  1347. return function isURLSameOrigin(requestURL) {
  1348. var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
  1349. return (parsed.protocol === originURL.protocol &&
  1350. parsed.host === originURL.host);
  1351. };
  1352. })() :
  1353. // Non standard browser envs (web workers, react-native) lack needed support.
  1354. (function nonStandardBrowserEnv() {
  1355. return function isURLSameOrigin() {
  1356. return true;
  1357. };
  1358. })()
  1359. );
  1360. /***/ }),
  1361. /***/ "./node_modules/axios/lib/helpers/normalizeHeaderName.js":
  1362. /*!***************************************************************!*\
  1363. !*** ./node_modules/axios/lib/helpers/normalizeHeaderName.js ***!
  1364. \***************************************************************/
  1365. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1366. "use strict";
  1367. var utils = __webpack_require__(/*! ../utils */ "./node_modules/axios/lib/utils.js");
  1368. module.exports = function normalizeHeaderName(headers, normalizedName) {
  1369. utils.forEach(headers, function processHeader(value, name) {
  1370. if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
  1371. headers[normalizedName] = value;
  1372. delete headers[name];
  1373. }
  1374. });
  1375. };
  1376. /***/ }),
  1377. /***/ "./node_modules/axios/lib/helpers/parseHeaders.js":
  1378. /*!********************************************************!*\
  1379. !*** ./node_modules/axios/lib/helpers/parseHeaders.js ***!
  1380. \********************************************************/
  1381. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1382. "use strict";
  1383. var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js");
  1384. // Headers whose duplicates are ignored by node
  1385. // c.f. https://nodejs.org/api/http.html#http_message_headers
  1386. var ignoreDuplicateOf = [
  1387. 'age', 'authorization', 'content-length', 'content-type', 'etag',
  1388. 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
  1389. 'last-modified', 'location', 'max-forwards', 'proxy-authorization',
  1390. 'referer', 'retry-after', 'user-agent'
  1391. ];
  1392. /**
  1393. * Parse headers into an object
  1394. *
  1395. * ```
  1396. * Date: Wed, 27 Aug 2014 08:58:49 GMT
  1397. * Content-Type: application/json
  1398. * Connection: keep-alive
  1399. * Transfer-Encoding: chunked
  1400. * ```
  1401. *
  1402. * @param {String} headers Headers needing to be parsed
  1403. * @returns {Object} Headers parsed into an object
  1404. */
  1405. module.exports = function parseHeaders(headers) {
  1406. var parsed = {};
  1407. var key;
  1408. var val;
  1409. var i;
  1410. if (!headers) { return parsed; }
  1411. utils.forEach(headers.split('\n'), function parser(line) {
  1412. i = line.indexOf(':');
  1413. key = utils.trim(line.substr(0, i)).toLowerCase();
  1414. val = utils.trim(line.substr(i + 1));
  1415. if (key) {
  1416. if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
  1417. return;
  1418. }
  1419. if (key === 'set-cookie') {
  1420. parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);
  1421. } else {
  1422. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  1423. }
  1424. }
  1425. });
  1426. return parsed;
  1427. };
  1428. /***/ }),
  1429. /***/ "./node_modules/axios/lib/helpers/spread.js":
  1430. /*!**************************************************!*\
  1431. !*** ./node_modules/axios/lib/helpers/spread.js ***!
  1432. \**************************************************/
  1433. /***/ ((module) => {
  1434. "use strict";
  1435. /**
  1436. * Syntactic sugar for invoking a function and expanding an array for arguments.
  1437. *
  1438. * Common use case would be to use `Function.prototype.apply`.
  1439. *
  1440. * ```js
  1441. * function f(x, y, z) {}
  1442. * var args = [1, 2, 3];
  1443. * f.apply(null, args);
  1444. * ```
  1445. *
  1446. * With `spread` this example can be re-written.
  1447. *
  1448. * ```js
  1449. * spread(function(x, y, z) {})([1, 2, 3]);
  1450. * ```
  1451. *
  1452. * @param {Function} callback
  1453. * @returns {Function}
  1454. */
  1455. module.exports = function spread(callback) {
  1456. return function wrap(arr) {
  1457. return callback.apply(null, arr);
  1458. };
  1459. };
  1460. /***/ }),
  1461. /***/ "./node_modules/axios/lib/utils.js":
  1462. /*!*****************************************!*\
  1463. !*** ./node_modules/axios/lib/utils.js ***!
  1464. \*****************************************/
  1465. /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
  1466. "use strict";
  1467. var bind = __webpack_require__(/*! ./helpers/bind */ "./node_modules/axios/lib/helpers/bind.js");
  1468. /*global toString:true*/
  1469. // utils is a library of generic helper functions non-specific to axios
  1470. var toString = Object.prototype.toString;
  1471. /**
  1472. * Determine if a value is an Array
  1473. *
  1474. * @param {Object} val The value to test
  1475. * @returns {boolean} True if value is an Array, otherwise false
  1476. */
  1477. function isArray(val) {
  1478. return toString.call(val) === '[object Array]';
  1479. }
  1480. /**
  1481. * Determine if a value is undefined
  1482. *
  1483. * @param {Object} val The value to test
  1484. * @returns {boolean} True if the value is undefined, otherwise false
  1485. */
  1486. function isUndefined(val) {
  1487. return typeof val === 'undefined';
  1488. }
  1489. /**
  1490. * Determine if a value is a Buffer
  1491. *
  1492. * @param {Object} val The value to test
  1493. * @returns {boolean} True if value is a Buffer, otherwise false
  1494. */
  1495. function isBuffer(val) {
  1496. return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
  1497. && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);
  1498. }
  1499. /**
  1500. * Determine if a value is an ArrayBuffer
  1501. *
  1502. * @param {Object} val The value to test
  1503. * @returns {boolean} True if value is an ArrayBuffer, otherwise false
  1504. */
  1505. function isArrayBuffer(val) {
  1506. return toString.call(val) === '[object ArrayBuffer]';
  1507. }
  1508. /**
  1509. * Determine if a value is a FormData
  1510. *
  1511. * @param {Object} val The value to test
  1512. * @returns {boolean} True if value is an FormData, otherwise false
  1513. */
  1514. function isFormData(val) {
  1515. return (typeof FormData !== 'undefined') && (val instanceof FormData);
  1516. }
  1517. /**
  1518. * Determine if a value is a view on an ArrayBuffer
  1519. *
  1520. * @param {Object} val The value to test
  1521. * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
  1522. */
  1523. function isArrayBufferView(val) {
  1524. var result;
  1525. if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
  1526. result = ArrayBuffer.isView(val);
  1527. } else {
  1528. result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer);
  1529. }
  1530. return result;
  1531. }
  1532. /**
  1533. * Determine if a value is a String
  1534. *
  1535. * @param {Object} val The value to test
  1536. * @returns {boolean} True if value is a String, otherwise false
  1537. */
  1538. function isString(val) {
  1539. return typeof val === 'string';
  1540. }
  1541. /**
  1542. * Determine if a value is a Number
  1543. *
  1544. * @param {Object} val The value to test
  1545. * @returns {boolean} True if value is a Number, otherwise false
  1546. */
  1547. function isNumber(val) {
  1548. return typeof val === 'number';
  1549. }
  1550. /**
  1551. * Determine if a value is an Object
  1552. *
  1553. * @param {Object} val The value to test
  1554. * @returns {boolean} True if value is an Object, otherwise false
  1555. */
  1556. function isObject(val) {
  1557. return val !== null && typeof val === 'object';
  1558. }
  1559. /**
  1560. * Determine if a value is a plain Object
  1561. *
  1562. * @param {Object} val The value to test
  1563. * @return {boolean} True if value is a plain Object, otherwise false
  1564. */
  1565. function isPlainObject(val) {
  1566. if (toString.call(val) !== '[object Object]') {
  1567. return false;
  1568. }
  1569. var prototype = Object.getPrototypeOf(val);
  1570. return prototype === null || prototype === Object.prototype;
  1571. }
  1572. /**
  1573. * Determine if a value is a Date
  1574. *
  1575. * @param {Object} val The value to test
  1576. * @returns {boolean} True if value is a Date, otherwise false
  1577. */
  1578. function isDate(val) {
  1579. return toString.call(val) === '[object Date]';
  1580. }
  1581. /**
  1582. * Determine if a value is a File
  1583. *
  1584. * @param {Object} val The value to test
  1585. * @returns {boolean} True if value is a File, otherwise false
  1586. */
  1587. function isFile(val) {
  1588. return toString.call(val) === '[object File]';
  1589. }
  1590. /**
  1591. * Determine if a value is a Blob
  1592. *
  1593. * @param {Object} val The value to test
  1594. * @returns {boolean} True if value is a Blob, otherwise false
  1595. */
  1596. function isBlob(val) {
  1597. return toString.call(val) === '[object Blob]';
  1598. }
  1599. /**
  1600. * Determine if a value is a Function
  1601. *
  1602. * @param {Object} val The value to test
  1603. * @returns {boolean} True if value is a Function, otherwise false
  1604. */
  1605. function isFunction(val) {
  1606. return toString.call(val) === '[object Function]';
  1607. }
  1608. /**
  1609. * Determine if a value is a Stream
  1610. *
  1611. * @param {Object} val The value to test
  1612. * @returns {boolean} True if value is a Stream, otherwise false
  1613. */
  1614. function isStream(val) {
  1615. return isObject(val) && isFunction(val.pipe);
  1616. }
  1617. /**
  1618. * Determine if a value is a URLSearchParams object
  1619. *
  1620. * @param {Object} val The value to test
  1621. * @returns {boolean} True if value is a URLSearchParams object, otherwise false
  1622. */
  1623. function isURLSearchParams(val) {
  1624. return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams;
  1625. }
  1626. /**
  1627. * Trim excess whitespace off the beginning and end of a string
  1628. *
  1629. * @param {String} str The String to trim
  1630. * @returns {String} The String freed of excess whitespace
  1631. */
  1632. function trim(str) {
  1633. return str.replace(/^\s*/, '').replace(/\s*$/, '');
  1634. }
  1635. /**
  1636. * Determine if we're running in a standard browser environment
  1637. *
  1638. * This allows axios to run in a web worker, and react-native.
  1639. * Both environments support XMLHttpRequest, but not fully standard globals.
  1640. *
  1641. * web workers:
  1642. * typeof window -> undefined
  1643. * typeof document -> undefined
  1644. *
  1645. * react-native:
  1646. * navigator.product -> 'ReactNative'
  1647. * nativescript
  1648. * navigator.product -> 'NativeScript' or 'NS'
  1649. */
  1650. function isStandardBrowserEnv() {
  1651. if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||
  1652. navigator.product === 'NativeScript' ||
  1653. navigator.product === 'NS')) {
  1654. return false;
  1655. }
  1656. return (
  1657. typeof window !== 'undefined' &&
  1658. typeof document !== 'undefined'
  1659. );
  1660. }
  1661. /**
  1662. * Iterate over an Array or an Object invoking a function for each item.
  1663. *
  1664. * If `obj` is an Array callback will be called passing
  1665. * the value, index, and complete array for each item.
  1666. *
  1667. * If 'obj' is an Object callback will be called passing
  1668. * the value, key, and complete object for each property.
  1669. *
  1670. * @param {Object|Array} obj The object to iterate
  1671. * @param {Function} fn The callback to invoke for each item
  1672. */
  1673. function forEach(obj, fn) {
  1674. // Don't bother if no value provided
  1675. if (obj === null || typeof obj === 'undefined') {
  1676. return;
  1677. }
  1678. // Force an array if not already something iterable
  1679. if (typeof obj !== 'object') {
  1680. /*eslint no-param-reassign:0*/
  1681. obj = [obj];
  1682. }
  1683. if (isArray(obj)) {
  1684. // Iterate over array values
  1685. for (var i = 0, l = obj.length; i < l; i++) {
  1686. fn.call(null, obj[i], i, obj);
  1687. }
  1688. } else {
  1689. // Iterate over object keys
  1690. for (var key in obj) {
  1691. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  1692. fn.call(null, obj[key], key, obj);
  1693. }
  1694. }
  1695. }
  1696. }
  1697. /**
  1698. * Accepts varargs expecting each argument to be an object, then
  1699. * immutably merges the properties of each object and returns result.
  1700. *
  1701. * When multiple objects contain the same key the later object in
  1702. * the arguments list will take precedence.
  1703. *
  1704. * Example:
  1705. *
  1706. * ```js
  1707. * var result = merge({foo: 123}, {foo: 456});
  1708. * console.log(result.foo); // outputs 456
  1709. * ```
  1710. *
  1711. * @param {Object} obj1 Object to merge
  1712. * @returns {Object} Result of all merge properties
  1713. */
  1714. function merge(/* obj1, obj2, obj3, ... */) {
  1715. var result = {};
  1716. function assignValue(val, key) {
  1717. if (isPlainObject(result[key]) && isPlainObject(val)) {
  1718. result[key] = merge(result[key], val);
  1719. } else if (isPlainObject(val)) {
  1720. result[key] = merge({}, val);
  1721. } else if (isArray(val)) {
  1722. result[key] = val.slice();
  1723. } else {
  1724. result[key] = val;
  1725. }
  1726. }
  1727. for (var i = 0, l = arguments.length; i < l; i++) {
  1728. forEach(arguments[i], assignValue);
  1729. }
  1730. return result;
  1731. }
  1732. /**
  1733. * Extends object a by mutably adding to it the properties of object b.
  1734. *
  1735. * @param {Object} a The object to be extended
  1736. * @param {Object} b The object to copy properties from
  1737. * @param {Object} thisArg The object to bind function to
  1738. * @return {Object} The resulting value of object a
  1739. */
  1740. function extend(a, b, thisArg) {
  1741. forEach(b, function assignValue(val, key) {
  1742. if (thisArg && typeof val === 'function') {
  1743. a[key] = bind(val, thisArg);
  1744. } else {
  1745. a[key] = val;
  1746. }
  1747. });
  1748. return a;
  1749. }
  1750. /**
  1751. * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
  1752. *
  1753. * @param {string} content with BOM
  1754. * @return {string} content value without BOM
  1755. */
  1756. function stripBOM(content) {
  1757. if (content.charCodeAt(0) === 0xFEFF) {
  1758. content = content.slice(1);
  1759. }
  1760. return content;
  1761. }
  1762. module.exports = {
  1763. isArray: isArray,
  1764. isArrayBuffer: isArrayBuffer,
  1765. isBuffer: isBuffer,
  1766. isFormData: isFormData,
  1767. isArrayBufferView: isArrayBufferView,
  1768. isString: isString,
  1769. isNumber: isNumber,
  1770. isObject: isObject,
  1771. isPlainObject: isPlainObject,
  1772. isUndefined: isUndefined,
  1773. isDate: isDate,
  1774. isFile: isFile,
  1775. isBlob: isBlob,
  1776. isFunction: isFunction,
  1777. isStream: isStream,
  1778. isURLSearchParams: isURLSearchParams,
  1779. isStandardBrowserEnv: isStandardBrowserEnv,
  1780. forEach: forEach,
  1781. merge: merge,
  1782. extend: extend,
  1783. trim: trim,
  1784. stripBOM: stripBOM
  1785. };
  1786. /***/ }),
  1787. /***/ "./resources/js/FormValidator.js":
  1788. /*!***************************************!*\
  1789. !*** ./resources/js/FormValidator.js ***!
  1790. \***************************************/
  1791. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  1792. "use strict";
  1793. __webpack_require__.r(__webpack_exports__);
  1794. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  1795. /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
  1796. /* harmony export */ });
  1797. /* harmony import */ var validate_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! validate.js */ "./node_modules/validate.js/validate.js");
  1798. /* harmony import */ var validate_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(validate_js__WEBPACK_IMPORTED_MODULE_0__);
  1799. /* harmony import */ var form_serialize__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! form-serialize */ "./node_modules/form-serialize/index.js");
  1800. /* harmony import */ var form_serialize__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(form_serialize__WEBPACK_IMPORTED_MODULE_1__);
  1801. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  1802. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  1803. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  1804. /**
  1805. * Form Validator with RiotJS Components
  1806. *
  1807. *
  1808. *
  1809. *
  1810. */
  1811. var FormValidator = /*#__PURE__*/function () {
  1812. /**
  1813. *
  1814. * @param {[type]} formSelector [description]
  1815. * @param {[type]} constraits [description]
  1816. */
  1817. function FormValidator(formSelector, constraits, onSuccess) {
  1818. var _this = this;
  1819. _classCallCheck(this, FormValidator);
  1820. // getting selector to find form-element
  1821. this.formSelector = formSelector; // constraits for validate.js
  1822. this.constraits = constraits; // get form and elements
  1823. this.form = document.querySelector(this.formSelector);
  1824. if (!this.form) {
  1825. console.error('FormValidator: form not found, querySelector not found "' + this.formSelector + '"');
  1826. }
  1827. this.elements = this.form.querySelectorAll('field-error'); // adding submit event
  1828. this.form.addEventListener('submit', function (event) {
  1829. _this.onSubmit(event);
  1830. }); // adding event if a element is updated
  1831. this.form.addEventListener('field-update', function (event) {
  1832. _this.onFieldUpdate(event);
  1833. });
  1834. this.onSuccess = onSuccess;
  1835. }
  1836. /**
  1837. *
  1838. * @param {[type]} event [description]
  1839. * @return {[type]} [description]
  1840. */
  1841. _createClass(FormValidator, [{
  1842. key: "onSubmit",
  1843. value: function onSubmit(event) {
  1844. var _this2 = this;
  1845. event.preventDefault();
  1846. var errors = validate_js__WEBPACK_IMPORTED_MODULE_0___default()(form_serialize__WEBPACK_IMPORTED_MODULE_1___default()(event.target, {
  1847. hash: true
  1848. }), this.constraits, {
  1849. fullMessages: false
  1850. });
  1851. if (errors) {
  1852. // send each element a event
  1853. this.elements.forEach(function (element) {
  1854. var elementErrors = false; // check for errors by name
  1855. if (errors[element.attributes.name.nodeValue]) {
  1856. elementErrors = errors[element.attributes.name.nodeValue];
  1857. }
  1858. _this2.dispatchCustomEvent(elementErrors, element);
  1859. });
  1860. } else {
  1861. this.onSuccess(event, form_serialize__WEBPACK_IMPORTED_MODULE_1___default()(event.target, {
  1862. hash: true
  1863. }));
  1864. }
  1865. }
  1866. /**
  1867. *
  1868. *
  1869. * @param {Event} event
  1870. *
  1871. */
  1872. }, {
  1873. key: "onFieldUpdate",
  1874. value: function onFieldUpdate(event) {
  1875. var _this3 = this;
  1876. // workaround, make sure that value for single is undefined if it is empty
  1877. if (event.detail.value == '') {
  1878. event.detail.value = undefined;
  1879. }
  1880. var errors = validate_js__WEBPACK_IMPORTED_MODULE_0___default().single(event.detail.value, this.constraits[event.detail.name]); // search for element by name and dispatch event
  1881. this.elements.forEach(function (element) {
  1882. if (element.attributes.name.nodeValue == event.detail.name) {
  1883. _this3.dispatchCustomEvent(errors, element);
  1884. }
  1885. });
  1886. }
  1887. /**
  1888. * dispatch event to single element
  1889. *
  1890. * @param {Array} errors
  1891. * @param {Element} element
  1892. *
  1893. */
  1894. }, {
  1895. key: "dispatchCustomEvent",
  1896. value: function dispatchCustomEvent(errors, element) {
  1897. var detail = false;
  1898. if (errors) {
  1899. detail = errors;
  1900. }
  1901. var formValidationEvent = new CustomEvent('form-validation', {
  1902. 'detail': detail
  1903. });
  1904. element.dispatchEvent(formValidationEvent);
  1905. }
  1906. }]);
  1907. return FormValidator;
  1908. }();
  1909. /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (FormValidator);
  1910. /***/ }),
  1911. /***/ "./node_modules/form-serialize/index.js":
  1912. /*!**********************************************!*\
  1913. !*** ./node_modules/form-serialize/index.js ***!
  1914. \**********************************************/
  1915. /***/ ((module) => {
  1916. // get successful control from form and assemble into object
  1917. // http://www.w3.org/TR/html401/interact/forms.html#h-17.13.2
  1918. // types which indicate a submit action and are not successful controls
  1919. // these will be ignored
  1920. var k_r_submitter = /^(?:submit|button|image|reset|file)$/i;
  1921. // node names which could be successful controls
  1922. var k_r_success_contrls = /^(?:input|select|textarea|keygen)/i;
  1923. // Matches bracket notation.
  1924. var brackets = /(\[[^\[\]]*\])/g;
  1925. // serializes form fields
  1926. // @param form MUST be an HTMLForm element
  1927. // @param options is an optional argument to configure the serialization. Default output
  1928. // with no options specified is a url encoded string
  1929. // - hash: [true | false] Configure the output type. If true, the output will
  1930. // be a js object.
  1931. // - serializer: [function] Optional serializer function to override the default one.
  1932. // The function takes 3 arguments (result, key, value) and should return new result
  1933. // hash and url encoded str serializers are provided with this module
  1934. // - disabled: [true | false]. If true serialize disabled fields.
  1935. // - empty: [true | false]. If true serialize empty fields
  1936. function serialize(form, options) {
  1937. if (typeof options != 'object') {
  1938. options = { hash: !!options };
  1939. }
  1940. else if (options.hash === undefined) {
  1941. options.hash = true;
  1942. }
  1943. var result = (options.hash) ? {} : '';
  1944. var serializer = options.serializer || ((options.hash) ? hash_serializer : str_serialize);
  1945. var elements = form && form.elements ? form.elements : [];
  1946. //Object store each radio and set if it's empty or not
  1947. var radio_store = Object.create(null);
  1948. for (var i=0 ; i<elements.length ; ++i) {
  1949. var element = elements[i];
  1950. // ingore disabled fields
  1951. if ((!options.disabled && element.disabled) || !element.name) {
  1952. continue;
  1953. }
  1954. // ignore anyhting that is not considered a success field
  1955. if (!k_r_success_contrls.test(element.nodeName) ||
  1956. k_r_submitter.test(element.type)) {
  1957. continue;
  1958. }
  1959. var key = element.name;
  1960. var val = element.value;
  1961. // we can't just use element.value for checkboxes cause some browsers lie to us
  1962. // they say "on" for value when the box isn't checked
  1963. if ((element.type === 'checkbox' || element.type === 'radio') && !element.checked) {
  1964. val = undefined;
  1965. }
  1966. // If we want empty elements
  1967. if (options.empty) {
  1968. // for checkbox
  1969. if (element.type === 'checkbox' && !element.checked) {
  1970. val = '';
  1971. }
  1972. // for radio
  1973. if (element.type === 'radio') {
  1974. if (!radio_store[element.name] && !element.checked) {
  1975. radio_store[element.name] = false;
  1976. }
  1977. else if (element.checked) {
  1978. radio_store[element.name] = true;
  1979. }
  1980. }
  1981. // if options empty is true, continue only if its radio
  1982. if (val == undefined && element.type == 'radio') {
  1983. continue;
  1984. }
  1985. }
  1986. else {
  1987. // value-less fields are ignored unless options.empty is true
  1988. if (!val) {
  1989. continue;
  1990. }
  1991. }
  1992. // multi select boxes
  1993. if (element.type === 'select-multiple') {
  1994. val = [];
  1995. var selectOptions = element.options;
  1996. var isSelectedOptions = false;
  1997. for (var j=0 ; j<selectOptions.length ; ++j) {
  1998. var option = selectOptions[j];
  1999. var allowedEmpty = options.empty && !option.value;
  2000. var hasValue = (option.value || allowedEmpty);
  2001. if (option.selected && hasValue) {
  2002. isSelectedOptions = true;
  2003. // If using a hash serializer be sure to add the
  2004. // correct notation for an array in the multi-select
  2005. // context. Here the name attribute on the select element
  2006. // might be missing the trailing bracket pair. Both names
  2007. // "foo" and "foo[]" should be arrays.
  2008. if (options.hash && key.slice(key.length - 2) !== '[]') {
  2009. result = serializer(result, key + '[]', option.value);
  2010. }
  2011. else {
  2012. result = serializer(result, key, option.value);
  2013. }
  2014. }
  2015. }
  2016. // Serialize if no selected options and options.empty is true
  2017. if (!isSelectedOptions && options.empty) {
  2018. result = serializer(result, key, '');
  2019. }
  2020. continue;
  2021. }
  2022. result = serializer(result, key, val);
  2023. }
  2024. // Check for all empty radio buttons and serialize them with key=""
  2025. if (options.empty) {
  2026. for (var key in radio_store) {
  2027. if (!radio_store[key]) {
  2028. result = serializer(result, key, '');
  2029. }
  2030. }
  2031. }
  2032. return result;
  2033. }
  2034. function parse_keys(string) {
  2035. var keys = [];
  2036. var prefix = /^([^\[\]]*)/;
  2037. var children = new RegExp(brackets);
  2038. var match = prefix.exec(string);
  2039. if (match[1]) {
  2040. keys.push(match[1]);
  2041. }
  2042. while ((match = children.exec(string)) !== null) {
  2043. keys.push(match[1]);
  2044. }
  2045. return keys;
  2046. }
  2047. function hash_assign(result, keys, value) {
  2048. if (keys.length === 0) {
  2049. result = value;
  2050. return result;
  2051. }
  2052. var key = keys.shift();
  2053. var between = key.match(/^\[(.+?)\]$/);
  2054. if (key === '[]') {
  2055. result = result || [];
  2056. if (Array.isArray(result)) {
  2057. result.push(hash_assign(null, keys, value));
  2058. }
  2059. else {
  2060. // This might be the result of bad name attributes like "[][foo]",
  2061. // in this case the original `result` object will already be
  2062. // assigned to an object literal. Rather than coerce the object to
  2063. // an array, or cause an exception the attribute "_values" is
  2064. // assigned as an array.
  2065. result._values = result._values || [];
  2066. result._values.push(hash_assign(null, keys, value));
  2067. }
  2068. return result;
  2069. }
  2070. // Key is an attribute name and can be assigned directly.
  2071. if (!between) {
  2072. result[key] = hash_assign(result[key], keys, value);
  2073. }
  2074. else {
  2075. var string = between[1];
  2076. // +var converts the variable into a number
  2077. // better than parseInt because it doesn't truncate away trailing
  2078. // letters and actually fails if whole thing is not a number
  2079. var index = +string;
  2080. // If the characters between the brackets is not a number it is an
  2081. // attribute name and can be assigned directly.
  2082. if (isNaN(index)) {
  2083. result = result || {};
  2084. result[string] = hash_assign(result[string], keys, value);
  2085. }
  2086. else {
  2087. result = result || [];
  2088. result[index] = hash_assign(result[index], keys, value);
  2089. }
  2090. }
  2091. return result;
  2092. }
  2093. // Object/hash encoding serializer.
  2094. function hash_serializer(result, key, value) {
  2095. var matches = key.match(brackets);
  2096. // Has brackets? Use the recursive assignment function to walk the keys,
  2097. // construct any missing objects in the result tree and make the assignment
  2098. // at the end of the chain.
  2099. if (matches) {
  2100. var keys = parse_keys(key);
  2101. hash_assign(result, keys, value);
  2102. }
  2103. else {
  2104. // Non bracket notation can make assignments directly.
  2105. var existing = result[key];
  2106. // If the value has been assigned already (for instance when a radio and
  2107. // a checkbox have the same name attribute) convert the previous value
  2108. // into an array before pushing into it.
  2109. //
  2110. // NOTE: If this requirement were removed all hash creation and
  2111. // assignment could go through `hash_assign`.
  2112. if (existing) {
  2113. if (!Array.isArray(existing)) {
  2114. result[key] = [ existing ];
  2115. }
  2116. result[key].push(value);
  2117. }
  2118. else {
  2119. result[key] = value;
  2120. }
  2121. }
  2122. return result;
  2123. }
  2124. // urlform encoding serializer
  2125. function str_serialize(result, key, value) {
  2126. // encode newlines as \r\n cause the html spec says so
  2127. value = value.replace(/(\r)?\n/g, '\r\n');
  2128. value = encodeURIComponent(value);
  2129. // spaces should be '+' rather than '%20'.
  2130. value = value.replace(/%20/g, '+');
  2131. return result + (result ? '&' : '') + encodeURIComponent(key) + '=' + value;
  2132. }
  2133. module.exports = serialize;
  2134. /***/ }),
  2135. /***/ "./node_modules/process/browser.js":
  2136. /*!*****************************************!*\
  2137. !*** ./node_modules/process/browser.js ***!
  2138. \*****************************************/
  2139. /***/ ((module) => {
  2140. // shim for using process in browser
  2141. var process = module.exports = {};
  2142. // cached from whatever global is present so that test runners that stub it
  2143. // don't break things. But we need to wrap it in a try catch in case it is
  2144. // wrapped in strict mode code which doesn't define any globals. It's inside a
  2145. // function because try/catches deoptimize in certain engines.
  2146. var cachedSetTimeout;
  2147. var cachedClearTimeout;
  2148. function defaultSetTimout() {
  2149. throw new Error('setTimeout has not been defined');
  2150. }
  2151. function defaultClearTimeout () {
  2152. throw new Error('clearTimeout has not been defined');
  2153. }
  2154. (function () {
  2155. try {
  2156. if (typeof setTimeout === 'function') {
  2157. cachedSetTimeout = setTimeout;
  2158. } else {
  2159. cachedSetTimeout = defaultSetTimout;
  2160. }
  2161. } catch (e) {
  2162. cachedSetTimeout = defaultSetTimout;
  2163. }
  2164. try {
  2165. if (typeof clearTimeout === 'function') {
  2166. cachedClearTimeout = clearTimeout;
  2167. } else {
  2168. cachedClearTimeout = defaultClearTimeout;
  2169. }
  2170. } catch (e) {
  2171. cachedClearTimeout = defaultClearTimeout;
  2172. }
  2173. } ())
  2174. function runTimeout(fun) {
  2175. if (cachedSetTimeout === setTimeout) {
  2176. //normal enviroments in sane situations
  2177. return setTimeout(fun, 0);
  2178. }
  2179. // if setTimeout wasn't available but was latter defined
  2180. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  2181. cachedSetTimeout = setTimeout;
  2182. return setTimeout(fun, 0);
  2183. }
  2184. try {
  2185. // when when somebody has screwed with setTimeout but no I.E. maddness
  2186. return cachedSetTimeout(fun, 0);
  2187. } catch(e){
  2188. try {
  2189. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  2190. return cachedSetTimeout.call(null, fun, 0);
  2191. } catch(e){
  2192. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  2193. return cachedSetTimeout.call(this, fun, 0);
  2194. }
  2195. }
  2196. }
  2197. function runClearTimeout(marker) {
  2198. if (cachedClearTimeout === clearTimeout) {
  2199. //normal enviroments in sane situations
  2200. return clearTimeout(marker);
  2201. }
  2202. // if clearTimeout wasn't available but was latter defined
  2203. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  2204. cachedClearTimeout = clearTimeout;
  2205. return clearTimeout(marker);
  2206. }
  2207. try {
  2208. // when when somebody has screwed with setTimeout but no I.E. maddness
  2209. return cachedClearTimeout(marker);
  2210. } catch (e){
  2211. try {
  2212. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  2213. return cachedClearTimeout.call(null, marker);
  2214. } catch (e){
  2215. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  2216. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  2217. return cachedClearTimeout.call(this, marker);
  2218. }
  2219. }
  2220. }
  2221. var queue = [];
  2222. var draining = false;
  2223. var currentQueue;
  2224. var queueIndex = -1;
  2225. function cleanUpNextTick() {
  2226. if (!draining || !currentQueue) {
  2227. return;
  2228. }
  2229. draining = false;
  2230. if (currentQueue.length) {
  2231. queue = currentQueue.concat(queue);
  2232. } else {
  2233. queueIndex = -1;
  2234. }
  2235. if (queue.length) {
  2236. drainQueue();
  2237. }
  2238. }
  2239. function drainQueue() {
  2240. if (draining) {
  2241. return;
  2242. }
  2243. var timeout = runTimeout(cleanUpNextTick);
  2244. draining = true;
  2245. var len = queue.length;
  2246. while(len) {
  2247. currentQueue = queue;
  2248. queue = [];
  2249. while (++queueIndex < len) {
  2250. if (currentQueue) {
  2251. currentQueue[queueIndex].run();
  2252. }
  2253. }
  2254. queueIndex = -1;
  2255. len = queue.length;
  2256. }
  2257. currentQueue = null;
  2258. draining = false;
  2259. runClearTimeout(timeout);
  2260. }
  2261. process.nextTick = function (fun) {
  2262. var args = new Array(arguments.length - 1);
  2263. if (arguments.length > 1) {
  2264. for (var i = 1; i < arguments.length; i++) {
  2265. args[i - 1] = arguments[i];
  2266. }
  2267. }
  2268. queue.push(new Item(fun, args));
  2269. if (queue.length === 1 && !draining) {
  2270. runTimeout(drainQueue);
  2271. }
  2272. };
  2273. // v8 likes predictible objects
  2274. function Item(fun, array) {
  2275. this.fun = fun;
  2276. this.array = array;
  2277. }
  2278. Item.prototype.run = function () {
  2279. this.fun.apply(null, this.array);
  2280. };
  2281. process.title = 'browser';
  2282. process.browser = true;
  2283. process.env = {};
  2284. process.argv = [];
  2285. process.version = ''; // empty string to avoid regexp issues
  2286. process.versions = {};
  2287. function noop() {}
  2288. process.on = noop;
  2289. process.addListener = noop;
  2290. process.once = noop;
  2291. process.off = noop;
  2292. process.removeListener = noop;
  2293. process.removeAllListeners = noop;
  2294. process.emit = noop;
  2295. process.prependListener = noop;
  2296. process.prependOnceListener = noop;
  2297. process.listeners = function (name) { return [] }
  2298. process.binding = function (name) {
  2299. throw new Error('process.binding is not supported');
  2300. };
  2301. process.cwd = function () { return '/' };
  2302. process.chdir = function (dir) {
  2303. throw new Error('process.chdir is not supported');
  2304. };
  2305. process.umask = function() { return 0; };
  2306. /***/ }),
  2307. /***/ "./node_modules/riot/riot.esm.js":
  2308. /*!***************************************!*\
  2309. !*** ./node_modules/riot/riot.esm.js ***!
  2310. \***************************************/
  2311. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  2312. "use strict";
  2313. __webpack_require__.r(__webpack_exports__);
  2314. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  2315. /* harmony export */ "__": () => (/* binding */ __),
  2316. /* harmony export */ "component": () => (/* binding */ component),
  2317. /* harmony export */ "install": () => (/* binding */ install),
  2318. /* harmony export */ "mount": () => (/* binding */ mount),
  2319. /* harmony export */ "pure": () => (/* binding */ pure),
  2320. /* harmony export */ "register": () => (/* binding */ register),
  2321. /* harmony export */ "uninstall": () => (/* binding */ uninstall),
  2322. /* harmony export */ "unmount": () => (/* binding */ unmount),
  2323. /* harmony export */ "unregister": () => (/* binding */ unregister),
  2324. /* harmony export */ "version": () => (/* binding */ version),
  2325. /* harmony export */ "withTypes": () => (/* binding */ withTypes)
  2326. /* harmony export */ });
  2327. /* Riot v6.0.1, @license MIT */
  2328. /**
  2329. * Convert a string from camel case to dash-case
  2330. * @param {string} string - probably a component tag name
  2331. * @returns {string} component name normalized
  2332. */
  2333. function camelToDashCase(string) {
  2334. return string.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  2335. }
  2336. /**
  2337. * Convert a string containing dashes to camel case
  2338. * @param {string} string - input string
  2339. * @returns {string} my-string -> myString
  2340. */
  2341. function dashToCamelCase(string) {
  2342. return string.replace(/-(\w)/g, (_, c) => c.toUpperCase());
  2343. }
  2344. /**
  2345. * Get all the element attributes as object
  2346. * @param {HTMLElement} element - DOM node we want to parse
  2347. * @returns {Object} all the attributes found as a key value pairs
  2348. */
  2349. function DOMattributesToObject(element) {
  2350. return Array.from(element.attributes).reduce((acc, attribute) => {
  2351. acc[dashToCamelCase(attribute.name)] = attribute.value;
  2352. return acc;
  2353. }, {});
  2354. }
  2355. /**
  2356. * Move all the child nodes from a source tag to another
  2357. * @param {HTMLElement} source - source node
  2358. * @param {HTMLElement} target - target node
  2359. * @returns {undefined} it's a void method ¯\_()_/¯
  2360. */
  2361. // Ignore this helper because it's needed only for svg tags
  2362. function moveChildren(source, target) {
  2363. if (source.firstChild) {
  2364. target.appendChild(source.firstChild);
  2365. moveChildren(source, target);
  2366. }
  2367. }
  2368. /**
  2369. * Remove the child nodes from any DOM node
  2370. * @param {HTMLElement} node - target node
  2371. * @returns {undefined}
  2372. */
  2373. function cleanNode(node) {
  2374. clearChildren(node.childNodes);
  2375. }
  2376. /**
  2377. * Clear multiple children in a node
  2378. * @param {HTMLElement[]} children - direct children nodes
  2379. * @returns {undefined}
  2380. */
  2381. function clearChildren(children) {
  2382. Array.from(children).forEach(removeChild);
  2383. }
  2384. /**
  2385. * Remove a node
  2386. * @param {HTMLElement}node - node to remove
  2387. * @returns {undefined}
  2388. */
  2389. const removeChild = node => node && node.parentNode && node.parentNode.removeChild(node);
  2390. /**
  2391. * Insert before a node
  2392. * @param {HTMLElement} newNode - node to insert
  2393. * @param {HTMLElement} refNode - ref child
  2394. * @returns {undefined}
  2395. */
  2396. const insertBefore = (newNode, refNode) => refNode && refNode.parentNode && refNode.parentNode.insertBefore(newNode, refNode);
  2397. /**
  2398. * Replace a node
  2399. * @param {HTMLElement} newNode - new node to add to the DOM
  2400. * @param {HTMLElement} replaced - node to replace
  2401. * @returns {undefined}
  2402. */
  2403. const replaceChild = (newNode, replaced) => replaced && replaced.parentNode && replaced.parentNode.replaceChild(newNode, replaced);
  2404. // Riot.js constants that can be used accross more modules
  2405. const COMPONENTS_IMPLEMENTATION_MAP$1 = new Map(),
  2406. DOM_COMPONENT_INSTANCE_PROPERTY$1 = Symbol('riot-component'),
  2407. PLUGINS_SET$1 = new Set(),
  2408. IS_DIRECTIVE = 'is',
  2409. VALUE_ATTRIBUTE = 'value',
  2410. MOUNT_METHOD_KEY = 'mount',
  2411. UPDATE_METHOD_KEY = 'update',
  2412. UNMOUNT_METHOD_KEY = 'unmount',
  2413. SHOULD_UPDATE_KEY = 'shouldUpdate',
  2414. ON_BEFORE_MOUNT_KEY = 'onBeforeMount',
  2415. ON_MOUNTED_KEY = 'onMounted',
  2416. ON_BEFORE_UPDATE_KEY = 'onBeforeUpdate',
  2417. ON_UPDATED_KEY = 'onUpdated',
  2418. ON_BEFORE_UNMOUNT_KEY = 'onBeforeUnmount',
  2419. ON_UNMOUNTED_KEY = 'onUnmounted',
  2420. PROPS_KEY = 'props',
  2421. STATE_KEY = 'state',
  2422. SLOTS_KEY = 'slots',
  2423. ROOT_KEY = 'root',
  2424. IS_PURE_SYMBOL = Symbol('pure'),
  2425. IS_COMPONENT_UPDATING = Symbol('is_updating'),
  2426. PARENT_KEY_SYMBOL = Symbol('parent'),
  2427. ATTRIBUTES_KEY_SYMBOL = Symbol('attributes'),
  2428. TEMPLATE_KEY_SYMBOL = Symbol('template');
  2429. var globals = /*#__PURE__*/Object.freeze({
  2430. __proto__: null,
  2431. COMPONENTS_IMPLEMENTATION_MAP: COMPONENTS_IMPLEMENTATION_MAP$1,
  2432. DOM_COMPONENT_INSTANCE_PROPERTY: DOM_COMPONENT_INSTANCE_PROPERTY$1,
  2433. PLUGINS_SET: PLUGINS_SET$1,
  2434. IS_DIRECTIVE: IS_DIRECTIVE,
  2435. VALUE_ATTRIBUTE: VALUE_ATTRIBUTE,
  2436. MOUNT_METHOD_KEY: MOUNT_METHOD_KEY,
  2437. UPDATE_METHOD_KEY: UPDATE_METHOD_KEY,
  2438. UNMOUNT_METHOD_KEY: UNMOUNT_METHOD_KEY,
  2439. SHOULD_UPDATE_KEY: SHOULD_UPDATE_KEY,
  2440. ON_BEFORE_MOUNT_KEY: ON_BEFORE_MOUNT_KEY,
  2441. ON_MOUNTED_KEY: ON_MOUNTED_KEY,
  2442. ON_BEFORE_UPDATE_KEY: ON_BEFORE_UPDATE_KEY,
  2443. ON_UPDATED_KEY: ON_UPDATED_KEY,
  2444. ON_BEFORE_UNMOUNT_KEY: ON_BEFORE_UNMOUNT_KEY,
  2445. ON_UNMOUNTED_KEY: ON_UNMOUNTED_KEY,
  2446. PROPS_KEY: PROPS_KEY,
  2447. STATE_KEY: STATE_KEY,
  2448. SLOTS_KEY: SLOTS_KEY,
  2449. ROOT_KEY: ROOT_KEY,
  2450. IS_PURE_SYMBOL: IS_PURE_SYMBOL,
  2451. IS_COMPONENT_UPDATING: IS_COMPONENT_UPDATING,
  2452. PARENT_KEY_SYMBOL: PARENT_KEY_SYMBOL,
  2453. ATTRIBUTES_KEY_SYMBOL: ATTRIBUTES_KEY_SYMBOL,
  2454. TEMPLATE_KEY_SYMBOL: TEMPLATE_KEY_SYMBOL
  2455. });
  2456. const EACH = 0;
  2457. const IF = 1;
  2458. const SIMPLE = 2;
  2459. const TAG = 3;
  2460. const SLOT = 4;
  2461. var bindingTypes = {
  2462. EACH,
  2463. IF,
  2464. SIMPLE,
  2465. TAG,
  2466. SLOT
  2467. };
  2468. const ATTRIBUTE = 0;
  2469. const EVENT = 1;
  2470. const TEXT = 2;
  2471. const VALUE = 3;
  2472. var expressionTypes = {
  2473. ATTRIBUTE,
  2474. EVENT,
  2475. TEXT,
  2476. VALUE
  2477. };
  2478. const HEAD_SYMBOL = Symbol('head');
  2479. const TAIL_SYMBOL = Symbol('tail');
  2480. /**
  2481. * Create the <template> fragments text nodes
  2482. * @return {Object} {{head: Text, tail: Text}}
  2483. */
  2484. function createHeadTailPlaceholders() {
  2485. const head = document.createTextNode('');
  2486. const tail = document.createTextNode('');
  2487. head[HEAD_SYMBOL] = true;
  2488. tail[TAIL_SYMBOL] = true;
  2489. return {
  2490. head,
  2491. tail
  2492. };
  2493. }
  2494. /**
  2495. * Create the template meta object in case of <template> fragments
  2496. * @param {TemplateChunk} componentTemplate - template chunk object
  2497. * @returns {Object} the meta property that will be passed to the mount function of the TemplateChunk
  2498. */
  2499. function createTemplateMeta(componentTemplate) {
  2500. const fragment = componentTemplate.dom.cloneNode(true);
  2501. const {
  2502. head,
  2503. tail
  2504. } = createHeadTailPlaceholders();
  2505. return {
  2506. avoidDOMInjection: true,
  2507. fragment,
  2508. head,
  2509. tail,
  2510. children: [head, ...Array.from(fragment.childNodes), tail]
  2511. };
  2512. }
  2513. /**
  2514. * Helper function to set an immutable property
  2515. * @param {Object} source - object where the new property will be set
  2516. * @param {string} key - object key where the new property will be stored
  2517. * @param {*} value - value of the new property
  2518. * @param {Object} options - set the propery overriding the default options
  2519. * @returns {Object} - the original object modified
  2520. */
  2521. function defineProperty(source, key, value, options) {
  2522. if (options === void 0) {
  2523. options = {};
  2524. }
  2525. /* eslint-disable fp/no-mutating-methods */
  2526. Object.defineProperty(source, key, Object.assign({
  2527. value,
  2528. enumerable: false,
  2529. writable: false,
  2530. configurable: true
  2531. }, options));
  2532. /* eslint-enable fp/no-mutating-methods */
  2533. return source;
  2534. }
  2535. /**
  2536. * Define multiple properties on a target object
  2537. * @param {Object} source - object where the new properties will be set
  2538. * @param {Object} properties - object containing as key pair the key + value properties
  2539. * @param {Object} options - set the propery overriding the default options
  2540. * @returns {Object} the original object modified
  2541. */
  2542. function defineProperties(source, properties, options) {
  2543. Object.entries(properties).forEach(_ref => {
  2544. let [key, value] = _ref;
  2545. defineProperty(source, key, value, options);
  2546. });
  2547. return source;
  2548. }
  2549. /**
  2550. * Define default properties if they don't exist on the source object
  2551. * @param {Object} source - object that will receive the default properties
  2552. * @param {Object} defaults - object containing additional optional keys
  2553. * @returns {Object} the original object received enhanced
  2554. */
  2555. function defineDefaults(source, defaults) {
  2556. Object.entries(defaults).forEach(_ref2 => {
  2557. let [key, value] = _ref2;
  2558. if (!source[key]) source[key] = value;
  2559. });
  2560. return source;
  2561. }
  2562. /**
  2563. * Get the current <template> fragment children located in between the head and tail comments
  2564. * @param {Comment} head - head comment node
  2565. * @param {Comment} tail - tail comment node
  2566. * @return {Array[]} children list of the nodes found in this template fragment
  2567. */
  2568. function getFragmentChildren(_ref) {
  2569. let {
  2570. head,
  2571. tail
  2572. } = _ref;
  2573. const nodes = walkNodes([head], head.nextSibling, n => n === tail, false);
  2574. nodes.push(tail);
  2575. return nodes;
  2576. }
  2577. /**
  2578. * Recursive function to walk all the <template> children nodes
  2579. * @param {Array[]} children - children nodes collection
  2580. * @param {ChildNode} node - current node
  2581. * @param {Function} check - exit function check
  2582. * @param {boolean} isFilterActive - filter flag to skip nodes managed by other bindings
  2583. * @returns {Array[]} children list of the nodes found in this template fragment
  2584. */
  2585. function walkNodes(children, node, check, isFilterActive) {
  2586. const {
  2587. nextSibling
  2588. } = node; // filter tail and head nodes together with all the nodes in between
  2589. // this is needed only to fix a really ugly edge case https://github.com/riot/riot/issues/2892
  2590. if (!isFilterActive && !node[HEAD_SYMBOL] && !node[TAIL_SYMBOL]) {
  2591. children.push(node);
  2592. }
  2593. if (!nextSibling || check(node)) return children;
  2594. return walkNodes(children, nextSibling, check, // activate the filters to skip nodes between <template> fragments that will be managed by other bindings
  2595. isFilterActive && !node[TAIL_SYMBOL] || nextSibling[HEAD_SYMBOL]);
  2596. }
  2597. /**
  2598. * Quick type checking
  2599. * @param {*} element - anything
  2600. * @param {string} type - type definition
  2601. * @returns {boolean} true if the type corresponds
  2602. */
  2603. function checkType(element, type) {
  2604. return typeof element === type;
  2605. }
  2606. /**
  2607. * Check if an element is part of an svg
  2608. * @param {HTMLElement} el - element to check
  2609. * @returns {boolean} true if we are in an svg context
  2610. */
  2611. function isSvg(el) {
  2612. const owner = el.ownerSVGElement;
  2613. return !!owner || owner === null;
  2614. }
  2615. /**
  2616. * Check if an element is a template tag
  2617. * @param {HTMLElement} el - element to check
  2618. * @returns {boolean} true if it's a <template>
  2619. */
  2620. function isTemplate(el) {
  2621. return el.tagName.toLowerCase() === 'template';
  2622. }
  2623. /**
  2624. * Check that will be passed if its argument is a function
  2625. * @param {*} value - value to check
  2626. * @returns {boolean} - true if the value is a function
  2627. */
  2628. function isFunction(value) {
  2629. return checkType(value, 'function');
  2630. }
  2631. /**
  2632. * Check if a value is a Boolean
  2633. * @param {*} value - anything
  2634. * @returns {boolean} true only for the value is a boolean
  2635. */
  2636. function isBoolean(value) {
  2637. return checkType(value, 'boolean');
  2638. }
  2639. /**
  2640. * Check if a value is an Object
  2641. * @param {*} value - anything
  2642. * @returns {boolean} true only for the value is an object
  2643. */
  2644. function isObject(value) {
  2645. return !isNil(value) && value.constructor === Object;
  2646. }
  2647. /**
  2648. * Check if a value is null or undefined
  2649. * @param {*} value - anything
  2650. * @returns {boolean} true only for the 'undefined' and 'null' types
  2651. */
  2652. function isNil(value) {
  2653. return value === null || value === undefined;
  2654. }
  2655. /**
  2656. * ISC License
  2657. *
  2658. * Copyright (c) 2020, Andrea Giammarchi, @WebReflection
  2659. *
  2660. * Permission to use, copy, modify, and/or distribute this software for any
  2661. * purpose with or without fee is hereby granted, provided that the above
  2662. * copyright notice and this permission notice appear in all copies.
  2663. *
  2664. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  2665. * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  2666. * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  2667. * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  2668. * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  2669. * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  2670. * PERFORMANCE OF THIS SOFTWARE.
  2671. */
  2672. // fork of https://github.com/WebReflection/udomdiff version 1.1.0
  2673. // due to https://github.com/WebReflection/udomdiff/pull/2
  2674. /* eslint-disable */
  2675. /**
  2676. * @param {Node[]} a The list of current/live children
  2677. * @param {Node[]} b The list of future children
  2678. * @param {(entry: Node, action: number) => Node} get
  2679. * The callback invoked per each entry related DOM operation.
  2680. * @param {Node} [before] The optional node used as anchor to insert before.
  2681. * @returns {Node[]} The same list of future children.
  2682. */
  2683. var udomdiff = ((a, b, get, before) => {
  2684. const bLength = b.length;
  2685. let aEnd = a.length;
  2686. let bEnd = bLength;
  2687. let aStart = 0;
  2688. let bStart = 0;
  2689. let map = null;
  2690. while (aStart < aEnd || bStart < bEnd) {
  2691. // append head, tail, or nodes in between: fast path
  2692. if (aEnd === aStart) {
  2693. // we could be in a situation where the rest of nodes that
  2694. // need to be added are not at the end, and in such case
  2695. // the node to `insertBefore`, if the index is more than 0
  2696. // must be retrieved, otherwise it's gonna be the first item.
  2697. const node = bEnd < bLength ? bStart ? get(b[bStart - 1], -0).nextSibling : get(b[bEnd - bStart], 0) : before;
  2698. while (bStart < bEnd) insertBefore(get(b[bStart++], 1), node);
  2699. } // remove head or tail: fast path
  2700. else if (bEnd === bStart) {
  2701. while (aStart < aEnd) {
  2702. // remove the node only if it's unknown or not live
  2703. if (!map || !map.has(a[aStart])) removeChild(get(a[aStart], -1));
  2704. aStart++;
  2705. }
  2706. } // same node: fast path
  2707. else if (a[aStart] === b[bStart]) {
  2708. aStart++;
  2709. bStart++;
  2710. } // same tail: fast path
  2711. else if (a[aEnd - 1] === b[bEnd - 1]) {
  2712. aEnd--;
  2713. bEnd--;
  2714. } // The once here single last swap "fast path" has been removed in v1.1.0
  2715. // https://github.com/WebReflection/udomdiff/blob/single-final-swap/esm/index.js#L69-L85
  2716. // reverse swap: also fast path
  2717. else if (a[aStart] === b[bEnd - 1] && b[bStart] === a[aEnd - 1]) {
  2718. // this is a "shrink" operation that could happen in these cases:
  2719. // [1, 2, 3, 4, 5]
  2720. // [1, 4, 3, 2, 5]
  2721. // or asymmetric too
  2722. // [1, 2, 3, 4, 5]
  2723. // [1, 2, 3, 5, 6, 4]
  2724. const node = get(a[--aEnd], -1).nextSibling;
  2725. insertBefore(get(b[bStart++], 1), get(a[aStart++], -1).nextSibling);
  2726. insertBefore(get(b[--bEnd], 1), node); // mark the future index as identical (yeah, it's dirty, but cheap 👍)
  2727. // The main reason to do this, is that when a[aEnd] will be reached,
  2728. // the loop will likely be on the fast path, as identical to b[bEnd].
  2729. // In the best case scenario, the next loop will skip the tail,
  2730. // but in the worst one, this node will be considered as already
  2731. // processed, bailing out pretty quickly from the map index check
  2732. a[aEnd] = b[bEnd];
  2733. } // map based fallback, "slow" path
  2734. else {
  2735. // the map requires an O(bEnd - bStart) operation once
  2736. // to store all future nodes indexes for later purposes.
  2737. // In the worst case scenario, this is a full O(N) cost,
  2738. // and such scenario happens at least when all nodes are different,
  2739. // but also if both first and last items of the lists are different
  2740. if (!map) {
  2741. map = new Map();
  2742. let i = bStart;
  2743. while (i < bEnd) map.set(b[i], i++);
  2744. } // if it's a future node, hence it needs some handling
  2745. if (map.has(a[aStart])) {
  2746. // grab the index of such node, 'cause it might have been processed
  2747. const index = map.get(a[aStart]); // if it's not already processed, look on demand for the next LCS
  2748. if (bStart < index && index < bEnd) {
  2749. let i = aStart; // counts the amount of nodes that are the same in the future
  2750. let sequence = 1;
  2751. while (++i < aEnd && i < bEnd && map.get(a[i]) === index + sequence) sequence++; // effort decision here: if the sequence is longer than replaces
  2752. // needed to reach such sequence, which would brings again this loop
  2753. // to the fast path, prepend the difference before a sequence,
  2754. // and move only the future list index forward, so that aStart
  2755. // and bStart will be aligned again, hence on the fast path.
  2756. // An example considering aStart and bStart are both 0:
  2757. // a: [1, 2, 3, 4]
  2758. // b: [7, 1, 2, 3, 6]
  2759. // this would place 7 before 1 and, from that time on, 1, 2, and 3
  2760. // will be processed at zero cost
  2761. if (sequence > index - bStart) {
  2762. const node = get(a[aStart], 0);
  2763. while (bStart < index) insertBefore(get(b[bStart++], 1), node);
  2764. } // if the effort wasn't good enough, fallback to a replace,
  2765. // moving both source and target indexes forward, hoping that some
  2766. // similar node will be found later on, to go back to the fast path
  2767. else {
  2768. replaceChild(get(b[bStart++], 1), get(a[aStart++], -1));
  2769. }
  2770. } // otherwise move the source forward, 'cause there's nothing to do
  2771. else aStart++;
  2772. } // this node has no meaning in the future list, so it's more than safe
  2773. // to remove it, and check the next live node out instead, meaning
  2774. // that only the live list index should be forwarded
  2775. else removeChild(get(a[aStart++], -1));
  2776. }
  2777. }
  2778. return b;
  2779. });
  2780. const UNMOUNT_SCOPE = Symbol('unmount');
  2781. const EachBinding = {
  2782. // dynamic binding properties
  2783. // childrenMap: null,
  2784. // node: null,
  2785. // root: null,
  2786. // condition: null,
  2787. // evaluate: null,
  2788. // template: null,
  2789. // isTemplateTag: false,
  2790. nodes: [],
  2791. // getKey: null,
  2792. // indexName: null,
  2793. // itemName: null,
  2794. // afterPlaceholder: null,
  2795. // placeholder: null,
  2796. // API methods
  2797. mount(scope, parentScope) {
  2798. return this.update(scope, parentScope);
  2799. },
  2800. update(scope, parentScope) {
  2801. const {
  2802. placeholder,
  2803. nodes,
  2804. childrenMap
  2805. } = this;
  2806. const collection = scope === UNMOUNT_SCOPE ? null : this.evaluate(scope);
  2807. const items = collection ? Array.from(collection) : []; // prepare the diffing
  2808. const {
  2809. newChildrenMap,
  2810. batches,
  2811. futureNodes
  2812. } = createPatch(items, scope, parentScope, this); // patch the DOM only if there are new nodes
  2813. udomdiff(nodes, futureNodes, patch(Array.from(childrenMap.values()), parentScope), placeholder); // trigger the mounts and the updates
  2814. batches.forEach(fn => fn()); // update the children map
  2815. this.childrenMap = newChildrenMap;
  2816. this.nodes = futureNodes; // make sure that the loop edge nodes are marked
  2817. markEdgeNodes(this.nodes);
  2818. return this;
  2819. },
  2820. unmount(scope, parentScope) {
  2821. this.update(UNMOUNT_SCOPE, parentScope);
  2822. return this;
  2823. }
  2824. };
  2825. /**
  2826. * Patch the DOM while diffing
  2827. * @param {any[]} redundant - list of all the children (template, nodes, context) added via each
  2828. * @param {*} parentScope - scope of the parent template
  2829. * @returns {Function} patch function used by domdiff
  2830. */
  2831. function patch(redundant, parentScope) {
  2832. return (item, info) => {
  2833. if (info < 0) {
  2834. // get the last element added to the childrenMap saved previously
  2835. const element = redundant[redundant.length - 1];
  2836. if (element) {
  2837. // get the nodes and the template in stored in the last child of the childrenMap
  2838. const {
  2839. template,
  2840. nodes,
  2841. context
  2842. } = element; // remove the last node (notice <template> tags might have more children nodes)
  2843. nodes.pop(); // notice that we pass null as last argument because
  2844. // the root node and its children will be removed by domdiff
  2845. if (!nodes.length) {
  2846. // we have cleared all the children nodes and we can unmount this template
  2847. redundant.pop();
  2848. template.unmount(context, parentScope, null);
  2849. }
  2850. }
  2851. }
  2852. return item;
  2853. };
  2854. }
  2855. /**
  2856. * Check whether a template must be filtered from a loop
  2857. * @param {Function} condition - filter function
  2858. * @param {Object} context - argument passed to the filter function
  2859. * @returns {boolean} true if this item should be skipped
  2860. */
  2861. function mustFilterItem(condition, context) {
  2862. return condition ? !condition(context) : false;
  2863. }
  2864. /**
  2865. * Extend the scope of the looped template
  2866. * @param {Object} scope - current template scope
  2867. * @param {Object} options - options
  2868. * @param {string} options.itemName - key to identify the looped item in the new context
  2869. * @param {string} options.indexName - key to identify the index of the looped item
  2870. * @param {number} options.index - current index
  2871. * @param {*} options.item - collection item looped
  2872. * @returns {Object} enhanced scope object
  2873. */
  2874. function extendScope(scope, _ref) {
  2875. let {
  2876. itemName,
  2877. indexName,
  2878. index,
  2879. item
  2880. } = _ref;
  2881. defineProperty(scope, itemName, item);
  2882. if (indexName) defineProperty(scope, indexName, index);
  2883. return scope;
  2884. }
  2885. /**
  2886. * Mark the first and last nodes in order to ignore them in case we need to retrieve the <template> fragment nodes
  2887. * @param {Array[]} nodes - each binding nodes list
  2888. * @returns {undefined} void function
  2889. */
  2890. function markEdgeNodes(nodes) {
  2891. const first = nodes[0];
  2892. const last = nodes[nodes.length - 1];
  2893. if (first) first[HEAD_SYMBOL] = true;
  2894. if (last) last[TAIL_SYMBOL] = true;
  2895. }
  2896. /**
  2897. * Loop the current template items
  2898. * @param {Array} items - expression collection value
  2899. * @param {*} scope - template scope
  2900. * @param {*} parentScope - scope of the parent template
  2901. * @param {EachBinding} binding - each binding object instance
  2902. * @returns {Object} data
  2903. * @returns {Map} data.newChildrenMap - a Map containing the new children template structure
  2904. * @returns {Array} data.batches - array containing the template lifecycle functions to trigger
  2905. * @returns {Array} data.futureNodes - array containing the nodes we need to diff
  2906. */
  2907. function createPatch(items, scope, parentScope, binding) {
  2908. const {
  2909. condition,
  2910. template,
  2911. childrenMap,
  2912. itemName,
  2913. getKey,
  2914. indexName,
  2915. root,
  2916. isTemplateTag
  2917. } = binding;
  2918. const newChildrenMap = new Map();
  2919. const batches = [];
  2920. const futureNodes = [];
  2921. items.forEach((item, index) => {
  2922. const context = extendScope(Object.create(scope), {
  2923. itemName,
  2924. indexName,
  2925. index,
  2926. item
  2927. });
  2928. const key = getKey ? getKey(context) : index;
  2929. const oldItem = childrenMap.get(key);
  2930. const nodes = [];
  2931. if (mustFilterItem(condition, context)) {
  2932. return;
  2933. }
  2934. const mustMount = !oldItem;
  2935. const componentTemplate = oldItem ? oldItem.template : template.clone();
  2936. const el = componentTemplate.el || root.cloneNode();
  2937. const meta = isTemplateTag && mustMount ? createTemplateMeta(componentTemplate) : componentTemplate.meta;
  2938. if (mustMount) {
  2939. batches.push(() => componentTemplate.mount(el, context, parentScope, meta));
  2940. } else {
  2941. batches.push(() => componentTemplate.update(context, parentScope));
  2942. } // create the collection of nodes to update or to add
  2943. // in case of template tags we need to add all its children nodes
  2944. if (isTemplateTag) {
  2945. nodes.push(...(mustMount ? meta.children : getFragmentChildren(meta)));
  2946. } else {
  2947. nodes.push(el);
  2948. } // delete the old item from the children map
  2949. childrenMap.delete(key);
  2950. futureNodes.push(...nodes); // update the children map
  2951. newChildrenMap.set(key, {
  2952. nodes,
  2953. template: componentTemplate,
  2954. context,
  2955. index
  2956. });
  2957. });
  2958. return {
  2959. newChildrenMap,
  2960. batches,
  2961. futureNodes
  2962. };
  2963. }
  2964. function create$6(node, _ref2) {
  2965. let {
  2966. evaluate,
  2967. condition,
  2968. itemName,
  2969. indexName,
  2970. getKey,
  2971. template
  2972. } = _ref2;
  2973. const placeholder = document.createTextNode('');
  2974. const root = node.cloneNode();
  2975. insertBefore(placeholder, node);
  2976. removeChild(node);
  2977. return Object.assign({}, EachBinding, {
  2978. childrenMap: new Map(),
  2979. node,
  2980. root,
  2981. condition,
  2982. evaluate,
  2983. isTemplateTag: isTemplate(root),
  2984. template: template.createDOM(node),
  2985. getKey,
  2986. indexName,
  2987. itemName,
  2988. placeholder
  2989. });
  2990. }
  2991. /**
  2992. * Binding responsible for the `if` directive
  2993. */
  2994. const IfBinding = {
  2995. // dynamic binding properties
  2996. // node: null,
  2997. // evaluate: null,
  2998. // isTemplateTag: false,
  2999. // placeholder: null,
  3000. // template: null,
  3001. // API methods
  3002. mount(scope, parentScope) {
  3003. return this.update(scope, parentScope);
  3004. },
  3005. update(scope, parentScope) {
  3006. const value = !!this.evaluate(scope);
  3007. const mustMount = !this.value && value;
  3008. const mustUnmount = this.value && !value;
  3009. const mount = () => {
  3010. const pristine = this.node.cloneNode();
  3011. insertBefore(pristine, this.placeholder);
  3012. this.template = this.template.clone();
  3013. this.template.mount(pristine, scope, parentScope);
  3014. };
  3015. switch (true) {
  3016. case mustMount:
  3017. mount();
  3018. break;
  3019. case mustUnmount:
  3020. this.unmount(scope);
  3021. break;
  3022. default:
  3023. if (value) this.template.update(scope, parentScope);
  3024. }
  3025. this.value = value;
  3026. return this;
  3027. },
  3028. unmount(scope, parentScope) {
  3029. this.template.unmount(scope, parentScope, true);
  3030. return this;
  3031. }
  3032. };
  3033. function create$5(node, _ref) {
  3034. let {
  3035. evaluate,
  3036. template
  3037. } = _ref;
  3038. const placeholder = document.createTextNode('');
  3039. insertBefore(placeholder, node);
  3040. removeChild(node);
  3041. return Object.assign({}, IfBinding, {
  3042. node,
  3043. evaluate,
  3044. placeholder,
  3045. template: template.createDOM(node)
  3046. });
  3047. }
  3048. /**
  3049. * Throw an error with a descriptive message
  3050. * @param { string } message - error message
  3051. * @returns { undefined } hoppla.. at this point the program should stop working
  3052. */
  3053. function panic(message) {
  3054. throw new Error(message);
  3055. }
  3056. /**
  3057. * Returns the memoized (cached) function.
  3058. * // borrowed from https://www.30secondsofcode.org/js/s/memoize
  3059. * @param {Function} fn - function to memoize
  3060. * @returns {Function} memoize function
  3061. */
  3062. function memoize(fn) {
  3063. const cache = new Map();
  3064. const cached = val => {
  3065. return cache.has(val) ? cache.get(val) : cache.set(val, fn.call(this, val)) && cache.get(val);
  3066. };
  3067. cached.cache = cache;
  3068. return cached;
  3069. }
  3070. /**
  3071. * Evaluate a list of attribute expressions
  3072. * @param {Array} attributes - attribute expressions generated by the riot compiler
  3073. * @returns {Object} key value pairs with the result of the computation
  3074. */
  3075. function evaluateAttributeExpressions(attributes) {
  3076. return attributes.reduce((acc, attribute) => {
  3077. const {
  3078. value,
  3079. type
  3080. } = attribute;
  3081. switch (true) {
  3082. // spread attribute
  3083. case !attribute.name && type === ATTRIBUTE:
  3084. return Object.assign({}, acc, value);
  3085. // value attribute
  3086. case type === VALUE:
  3087. acc.value = attribute.value;
  3088. break;
  3089. // normal attributes
  3090. default:
  3091. acc[dashToCamelCase(attribute.name)] = attribute.value;
  3092. }
  3093. return acc;
  3094. }, {});
  3095. }
  3096. const ElementProto = typeof Element === 'undefined' ? {} : Element.prototype;
  3097. const isNativeHtmlProperty = memoize(name => ElementProto.hasOwnProperty(name)); // eslint-disable-line
  3098. /**
  3099. * Add all the attributes provided
  3100. * @param {HTMLElement} node - target node
  3101. * @param {Object} attributes - object containing the attributes names and values
  3102. * @returns {undefined} sorry it's a void function :(
  3103. */
  3104. function setAllAttributes(node, attributes) {
  3105. Object.entries(attributes).forEach(_ref => {
  3106. let [name, value] = _ref;
  3107. return attributeExpression(node, {
  3108. name
  3109. }, value);
  3110. });
  3111. }
  3112. /**
  3113. * Remove all the attributes provided
  3114. * @param {HTMLElement} node - target node
  3115. * @param {Object} newAttributes - object containing all the new attribute names
  3116. * @param {Object} oldAttributes - object containing all the old attribute names
  3117. * @returns {undefined} sorry it's a void function :(
  3118. */
  3119. function removeAllAttributes(node, newAttributes, oldAttributes) {
  3120. const newKeys = newAttributes ? Object.keys(newAttributes) : [];
  3121. Object.keys(oldAttributes).filter(name => !newKeys.includes(name)).forEach(attribute => node.removeAttribute(attribute));
  3122. }
  3123. /**
  3124. * Check whether the attribute value can be rendered
  3125. * @param {*} value - expression value
  3126. * @returns {boolean} true if we can render this attribute value
  3127. */
  3128. function canRenderAttribute(value) {
  3129. return value === true || ['string', 'number'].includes(typeof value);
  3130. }
  3131. /**
  3132. * Check whether the attribute should be removed
  3133. * @param {*} value - expression value
  3134. * @returns {boolean} boolean - true if the attribute can be removed}
  3135. */
  3136. function shouldRemoveAttribute(value) {
  3137. return !value && value !== 0;
  3138. }
  3139. /**
  3140. * This methods handles the DOM attributes updates
  3141. * @param {HTMLElement} node - target node
  3142. * @param {Object} expression - expression object
  3143. * @param {string} expression.name - attribute name
  3144. * @param {*} value - new expression value
  3145. * @param {*} oldValue - the old expression cached value
  3146. * @returns {undefined}
  3147. */
  3148. function attributeExpression(node, _ref2, value, oldValue) {
  3149. let {
  3150. name
  3151. } = _ref2;
  3152. // is it a spread operator? {...attributes}
  3153. if (!name) {
  3154. if (oldValue) {
  3155. // remove all the old attributes
  3156. removeAllAttributes(node, value, oldValue);
  3157. } // is the value still truthy?
  3158. if (value) {
  3159. setAllAttributes(node, value);
  3160. }
  3161. return;
  3162. } // handle boolean attributes
  3163. if (!isNativeHtmlProperty(name) && (isBoolean(value) || isObject(value) || isFunction(value))) {
  3164. node[name] = value;
  3165. }
  3166. if (shouldRemoveAttribute(value)) {
  3167. node.removeAttribute(name);
  3168. } else if (canRenderAttribute(value)) {
  3169. node.setAttribute(name, normalizeValue(name, value));
  3170. }
  3171. }
  3172. /**
  3173. * Get the value as string
  3174. * @param {string} name - attribute name
  3175. * @param {*} value - user input value
  3176. * @returns {string} input value as string
  3177. */
  3178. function normalizeValue(name, value) {
  3179. // be sure that expressions like selected={ true } will be always rendered as selected='selected'
  3180. return value === true ? name : value;
  3181. }
  3182. const RE_EVENTS_PREFIX = /^on/;
  3183. const getCallbackAndOptions = value => Array.isArray(value) ? value : [value, false]; // see also https://medium.com/@WebReflection/dom-handleevent-a-cross-platform-standard-since-year-2000-5bf17287fd38
  3184. const EventListener = {
  3185. handleEvent(event) {
  3186. this[event.type](event);
  3187. }
  3188. };
  3189. const ListenersWeakMap = new WeakMap();
  3190. const createListener = node => {
  3191. const listener = Object.create(EventListener);
  3192. ListenersWeakMap.set(node, listener);
  3193. return listener;
  3194. };
  3195. /**
  3196. * Set a new event listener
  3197. * @param {HTMLElement} node - target node
  3198. * @param {Object} expression - expression object
  3199. * @param {string} expression.name - event name
  3200. * @param {*} value - new expression value
  3201. * @returns {value} the callback just received
  3202. */
  3203. function eventExpression(node, _ref, value) {
  3204. let {
  3205. name
  3206. } = _ref;
  3207. const normalizedEventName = name.replace(RE_EVENTS_PREFIX, '');
  3208. const eventListener = ListenersWeakMap.get(node) || createListener(node);
  3209. const [callback, options] = getCallbackAndOptions(value);
  3210. const handler = eventListener[normalizedEventName];
  3211. const mustRemoveEvent = handler && !callback;
  3212. const mustAddEvent = callback && !handler;
  3213. if (mustRemoveEvent) {
  3214. node.removeEventListener(normalizedEventName, eventListener);
  3215. }
  3216. if (mustAddEvent) {
  3217. node.addEventListener(normalizedEventName, eventListener, options);
  3218. }
  3219. eventListener[normalizedEventName] = callback;
  3220. }
  3221. /**
  3222. * Normalize the user value in order to render a empty string in case of falsy values
  3223. * @param {*} value - user input value
  3224. * @returns {string} hopefully a string
  3225. */
  3226. function normalizeStringValue(value) {
  3227. return isNil(value) ? '' : value;
  3228. }
  3229. /**
  3230. * Get the the target text node to update or create one from of a comment node
  3231. * @param {HTMLElement} node - any html element containing childNodes
  3232. * @param {number} childNodeIndex - index of the text node in the childNodes list
  3233. * @returns {Text} the text node to update
  3234. */
  3235. const getTextNode = (node, childNodeIndex) => {
  3236. const target = node.childNodes[childNodeIndex];
  3237. if (target.nodeType === Node.COMMENT_NODE) {
  3238. const textNode = document.createTextNode('');
  3239. node.replaceChild(textNode, target);
  3240. return textNode;
  3241. }
  3242. return target;
  3243. };
  3244. /**
  3245. * This methods handles a simple text expression update
  3246. * @param {HTMLElement} node - target node
  3247. * @param {Object} data - expression object
  3248. * @param {*} value - new expression value
  3249. * @returns {undefined}
  3250. */
  3251. function textExpression(node, data, value) {
  3252. node.data = normalizeStringValue(value);
  3253. }
  3254. /**
  3255. * This methods handles the input fileds value updates
  3256. * @param {HTMLElement} node - target node
  3257. * @param {Object} expression - expression object
  3258. * @param {*} value - new expression value
  3259. * @returns {undefined}
  3260. */
  3261. function valueExpression(node, expression, value) {
  3262. node.value = normalizeStringValue(value);
  3263. }
  3264. var expressions = {
  3265. [ATTRIBUTE]: attributeExpression,
  3266. [EVENT]: eventExpression,
  3267. [TEXT]: textExpression,
  3268. [VALUE]: valueExpression
  3269. };
  3270. const Expression = {
  3271. // Static props
  3272. // node: null,
  3273. // value: null,
  3274. // API methods
  3275. /**
  3276. * Mount the expression evaluating its initial value
  3277. * @param {*} scope - argument passed to the expression to evaluate its current values
  3278. * @returns {Expression} self
  3279. */
  3280. mount(scope) {
  3281. // hopefully a pure function
  3282. this.value = this.evaluate(scope); // IO() DOM updates
  3283. apply(this, this.value);
  3284. return this;
  3285. },
  3286. /**
  3287. * Update the expression if its value changed
  3288. * @param {*} scope - argument passed to the expression to evaluate its current values
  3289. * @returns {Expression} self
  3290. */
  3291. update(scope) {
  3292. // pure function
  3293. const value = this.evaluate(scope);
  3294. if (this.value !== value) {
  3295. // IO() DOM updates
  3296. apply(this, value);
  3297. this.value = value;
  3298. }
  3299. return this;
  3300. },
  3301. /**
  3302. * Expression teardown method
  3303. * @returns {Expression} self
  3304. */
  3305. unmount() {
  3306. // unmount only the event handling expressions
  3307. if (this.type === EVENT) apply(this, null);
  3308. return this;
  3309. }
  3310. };
  3311. /**
  3312. * IO() function to handle the DOM updates
  3313. * @param {Expression} expression - expression object
  3314. * @param {*} value - current expression value
  3315. * @returns {undefined}
  3316. */
  3317. function apply(expression, value) {
  3318. return expressions[expression.type](expression.node, expression, value, expression.value);
  3319. }
  3320. function create$4(node, data) {
  3321. return Object.assign({}, Expression, data, {
  3322. node: data.type === TEXT ? getTextNode(node, data.childNodeIndex) : node
  3323. });
  3324. }
  3325. /**
  3326. * Create a flat object having as keys a list of methods that if dispatched will propagate
  3327. * on the whole collection
  3328. * @param {Array} collection - collection to iterate
  3329. * @param {Array<string>} methods - methods to execute on each item of the collection
  3330. * @param {*} context - context returned by the new methods created
  3331. * @returns {Object} a new object to simplify the the nested methods dispatching
  3332. */
  3333. function flattenCollectionMethods(collection, methods, context) {
  3334. return methods.reduce((acc, method) => {
  3335. return Object.assign({}, acc, {
  3336. [method]: scope => {
  3337. return collection.map(item => item[method](scope)) && context;
  3338. }
  3339. });
  3340. }, {});
  3341. }
  3342. function create$3(node, _ref) {
  3343. let {
  3344. expressions
  3345. } = _ref;
  3346. return Object.assign({}, flattenCollectionMethods(expressions.map(expression => create$4(node, expression)), ['mount', 'update', 'unmount']));
  3347. }
  3348. function extendParentScope(attributes, scope, parentScope) {
  3349. if (!attributes || !attributes.length) return parentScope;
  3350. const expressions = attributes.map(attr => Object.assign({}, attr, {
  3351. value: attr.evaluate(scope)
  3352. }));
  3353. return Object.assign(Object.create(parentScope || null), evaluateAttributeExpressions(expressions));
  3354. } // this function is only meant to fix an edge case
  3355. // https://github.com/riot/riot/issues/2842
  3356. const getRealParent = (scope, parentScope) => scope[PARENT_KEY_SYMBOL] || parentScope;
  3357. const SlotBinding = {
  3358. // dynamic binding properties
  3359. // node: null,
  3360. // name: null,
  3361. attributes: [],
  3362. // template: null,
  3363. getTemplateScope(scope, parentScope) {
  3364. return extendParentScope(this.attributes, scope, parentScope);
  3365. },
  3366. // API methods
  3367. mount(scope, parentScope) {
  3368. const templateData = scope.slots ? scope.slots.find(_ref => {
  3369. let {
  3370. id
  3371. } = _ref;
  3372. return id === this.name;
  3373. }) : false;
  3374. const {
  3375. parentNode
  3376. } = this.node;
  3377. const realParent = getRealParent(scope, parentScope);
  3378. this.template = templateData && create(templateData.html, templateData.bindings).createDOM(parentNode);
  3379. if (this.template) {
  3380. cleanNode(this.node);
  3381. this.template.mount(this.node, this.getTemplateScope(scope, realParent), realParent);
  3382. this.template.children = Array.from(this.node.childNodes);
  3383. }
  3384. moveSlotInnerContent(this.node);
  3385. removeChild(this.node);
  3386. return this;
  3387. },
  3388. update(scope, parentScope) {
  3389. if (this.template) {
  3390. const realParent = getRealParent(scope, parentScope);
  3391. this.template.update(this.getTemplateScope(scope, realParent), realParent);
  3392. }
  3393. return this;
  3394. },
  3395. unmount(scope, parentScope, mustRemoveRoot) {
  3396. if (this.template) {
  3397. this.template.unmount(this.getTemplateScope(scope, parentScope), null, mustRemoveRoot);
  3398. }
  3399. return this;
  3400. }
  3401. };
  3402. /**
  3403. * Move the inner content of the slots outside of them
  3404. * @param {HTMLElement} slot - slot node
  3405. * @returns {undefined} it's a void method ¯\_()_/¯
  3406. */
  3407. function moveSlotInnerContent(slot) {
  3408. const child = slot && slot.firstChild;
  3409. if (!child) return;
  3410. insertBefore(child, slot);
  3411. moveSlotInnerContent(slot);
  3412. }
  3413. /**
  3414. * Create a single slot binding
  3415. * @param {HTMLElement} node - slot node
  3416. * @param {string} name - slot id
  3417. * @param {AttributeExpressionData[]} attributes - slot attributes
  3418. * @returns {Object} Slot binding object
  3419. */
  3420. function createSlot(node, _ref2) {
  3421. let {
  3422. name,
  3423. attributes
  3424. } = _ref2;
  3425. return Object.assign({}, SlotBinding, {
  3426. attributes,
  3427. node,
  3428. name
  3429. });
  3430. }
  3431. /**
  3432. * Create a new tag object if it was registered before, otherwise fallback to the simple
  3433. * template chunk
  3434. * @param {Function} component - component factory function
  3435. * @param {Array<Object>} slots - array containing the slots markup
  3436. * @param {Array} attributes - dynamic attributes that will be received by the tag element
  3437. * @returns {TagImplementation|TemplateChunk} a tag implementation or a template chunk as fallback
  3438. */
  3439. function getTag(component, slots, attributes) {
  3440. if (slots === void 0) {
  3441. slots = [];
  3442. }
  3443. if (attributes === void 0) {
  3444. attributes = [];
  3445. }
  3446. // if this tag was registered before we will return its implementation
  3447. if (component) {
  3448. return component({
  3449. slots,
  3450. attributes
  3451. });
  3452. } // otherwise we return a template chunk
  3453. return create(slotsToMarkup(slots), [...slotBindings(slots), {
  3454. // the attributes should be registered as binding
  3455. // if we fallback to a normal template chunk
  3456. expressions: attributes.map(attr => {
  3457. return Object.assign({
  3458. type: ATTRIBUTE
  3459. }, attr);
  3460. })
  3461. }]);
  3462. }
  3463. /**
  3464. * Merge all the slots bindings into a single array
  3465. * @param {Array<Object>} slots - slots collection
  3466. * @returns {Array<Bindings>} flatten bindings array
  3467. */
  3468. function slotBindings(slots) {
  3469. return slots.reduce((acc, _ref) => {
  3470. let {
  3471. bindings
  3472. } = _ref;
  3473. return acc.concat(bindings);
  3474. }, []);
  3475. }
  3476. /**
  3477. * Merge all the slots together in a single markup string
  3478. * @param {Array<Object>} slots - slots collection
  3479. * @returns {string} markup of all the slots in a single string
  3480. */
  3481. function slotsToMarkup(slots) {
  3482. return slots.reduce((acc, slot) => {
  3483. return acc + slot.html;
  3484. }, '');
  3485. }
  3486. const TagBinding = {
  3487. // dynamic binding properties
  3488. // node: null,
  3489. // evaluate: null,
  3490. // name: null,
  3491. // slots: null,
  3492. // tag: null,
  3493. // attributes: null,
  3494. // getComponent: null,
  3495. mount(scope) {
  3496. return this.update(scope);
  3497. },
  3498. update(scope, parentScope) {
  3499. const name = this.evaluate(scope); // simple update
  3500. if (name && name === this.name) {
  3501. this.tag.update(scope);
  3502. } else {
  3503. // unmount the old tag if it exists
  3504. this.unmount(scope, parentScope, true); // mount the new tag
  3505. this.name = name;
  3506. this.tag = getTag(this.getComponent(name), this.slots, this.attributes);
  3507. this.tag.mount(this.node, scope);
  3508. }
  3509. return this;
  3510. },
  3511. unmount(scope, parentScope, keepRootTag) {
  3512. if (this.tag) {
  3513. // keep the root tag
  3514. this.tag.unmount(keepRootTag);
  3515. }
  3516. return this;
  3517. }
  3518. };
  3519. function create$2(node, _ref2) {
  3520. let {
  3521. evaluate,
  3522. getComponent,
  3523. slots,
  3524. attributes
  3525. } = _ref2;
  3526. return Object.assign({}, TagBinding, {
  3527. node,
  3528. evaluate,
  3529. slots,
  3530. attributes,
  3531. getComponent
  3532. });
  3533. }
  3534. var bindings = {
  3535. [IF]: create$5,
  3536. [SIMPLE]: create$3,
  3537. [EACH]: create$6,
  3538. [TAG]: create$2,
  3539. [SLOT]: createSlot
  3540. };
  3541. /**
  3542. * Text expressions in a template tag will get childNodeIndex value normalized
  3543. * depending on the position of the <template> tag offset
  3544. * @param {Expression[]} expressions - riot expressions array
  3545. * @param {number} textExpressionsOffset - offset of the <template> tag
  3546. * @returns {Expression[]} expressions containing the text expressions normalized
  3547. */
  3548. function fixTextExpressionsOffset(expressions, textExpressionsOffset) {
  3549. return expressions.map(e => e.type === TEXT ? Object.assign({}, e, {
  3550. childNodeIndex: e.childNodeIndex + textExpressionsOffset
  3551. }) : e);
  3552. }
  3553. /**
  3554. * Bind a new expression object to a DOM node
  3555. * @param {HTMLElement} root - DOM node where to bind the expression
  3556. * @param {TagBindingData} binding - binding data
  3557. * @param {number|null} templateTagOffset - if it's defined we need to fix the text expressions childNodeIndex offset
  3558. * @returns {Binding} Binding object
  3559. */
  3560. function create$1(root, binding, templateTagOffset) {
  3561. const {
  3562. selector,
  3563. type,
  3564. redundantAttribute,
  3565. expressions
  3566. } = binding; // find the node to apply the bindings
  3567. const node = selector ? root.querySelector(selector) : root; // remove eventually additional attributes created only to select this node
  3568. if (redundantAttribute) node.removeAttribute(redundantAttribute);
  3569. const bindingExpressions = expressions || []; // init the binding
  3570. return (bindings[type] || bindings[SIMPLE])(node, Object.assign({}, binding, {
  3571. expressions: templateTagOffset && !selector ? fixTextExpressionsOffset(bindingExpressions, templateTagOffset) : bindingExpressions
  3572. }));
  3573. }
  3574. function createHTMLTree(html, root) {
  3575. const template = isTemplate(root) ? root : document.createElement('template');
  3576. template.innerHTML = html;
  3577. return template.content;
  3578. } // for svg nodes we need a bit more work
  3579. function createSVGTree(html, container) {
  3580. // create the SVGNode
  3581. const svgNode = container.ownerDocument.importNode(new window.DOMParser().parseFromString(`<svg xmlns="http://www.w3.org/2000/svg">${html}</svg>`, 'application/xml').documentElement, true);
  3582. return svgNode;
  3583. }
  3584. /**
  3585. * Create the DOM that will be injected
  3586. * @param {Object} root - DOM node to find out the context where the fragment will be created
  3587. * @param {string} html - DOM to create as string
  3588. * @returns {HTMLDocumentFragment|HTMLElement} a new html fragment
  3589. */
  3590. function createDOMTree(root, html) {
  3591. if (isSvg(root)) return createSVGTree(html, root);
  3592. return createHTMLTree(html, root);
  3593. }
  3594. /**
  3595. * Inject the DOM tree into a target node
  3596. * @param {HTMLElement} el - target element
  3597. * @param {DocumentFragment|SVGElement} dom - dom tree to inject
  3598. * @returns {undefined}
  3599. */
  3600. function injectDOM(el, dom) {
  3601. switch (true) {
  3602. case isSvg(el):
  3603. moveChildren(dom, el);
  3604. break;
  3605. case isTemplate(el):
  3606. el.parentNode.replaceChild(dom, el);
  3607. break;
  3608. default:
  3609. el.appendChild(dom);
  3610. }
  3611. }
  3612. /**
  3613. * Create the Template DOM skeleton
  3614. * @param {HTMLElement} el - root node where the DOM will be injected
  3615. * @param {string|HTMLElement} html - HTML markup or HTMLElement that will be injected into the root node
  3616. * @returns {?DocumentFragment} fragment that will be injected into the root node
  3617. */
  3618. function createTemplateDOM(el, html) {
  3619. return html && (typeof html === 'string' ? createDOMTree(el, html) : html);
  3620. }
  3621. /**
  3622. * Get the offset of the <template> tag
  3623. * @param {HTMLElement} parentNode - template tag parent node
  3624. * @param {HTMLElement} el - the template tag we want to render
  3625. * @param {Object} meta - meta properties needed to handle the <template> tags in loops
  3626. * @returns {number} offset of the <template> tag calculated from its siblings DOM nodes
  3627. */
  3628. function getTemplateTagOffset(parentNode, el, meta) {
  3629. const siblings = Array.from(parentNode.childNodes);
  3630. return Math.max(siblings.indexOf(el), siblings.indexOf(meta.head) + 1, 0);
  3631. }
  3632. /**
  3633. * Template Chunk model
  3634. * @type {Object}
  3635. */
  3636. const TemplateChunk = Object.freeze({
  3637. // Static props
  3638. // bindings: null,
  3639. // bindingsData: null,
  3640. // html: null,
  3641. // isTemplateTag: false,
  3642. // fragment: null,
  3643. // children: null,
  3644. // dom: null,
  3645. // el: null,
  3646. /**
  3647. * Create the template DOM structure that will be cloned on each mount
  3648. * @param {HTMLElement} el - the root node
  3649. * @returns {TemplateChunk} self
  3650. */
  3651. createDOM(el) {
  3652. // make sure that the DOM gets created before cloning the template
  3653. this.dom = this.dom || createTemplateDOM(el, this.html) || document.createDocumentFragment();
  3654. return this;
  3655. },
  3656. // API methods
  3657. /**
  3658. * Attach the template to a DOM node
  3659. * @param {HTMLElement} el - target DOM node
  3660. * @param {*} scope - template data
  3661. * @param {*} parentScope - scope of the parent template tag
  3662. * @param {Object} meta - meta properties needed to handle the <template> tags in loops
  3663. * @returns {TemplateChunk} self
  3664. */
  3665. mount(el, scope, parentScope, meta) {
  3666. if (meta === void 0) {
  3667. meta = {};
  3668. }
  3669. if (!el) throw new Error('Please provide DOM node to mount properly your template');
  3670. if (this.el) this.unmount(scope); // <template> tags require a bit more work
  3671. // the template fragment might be already created via meta outside of this call
  3672. const {
  3673. fragment,
  3674. children,
  3675. avoidDOMInjection
  3676. } = meta; // <template> bindings of course can not have a root element
  3677. // so we check the parent node to set the query selector bindings
  3678. const {
  3679. parentNode
  3680. } = children ? children[0] : el;
  3681. const isTemplateTag = isTemplate(el);
  3682. const templateTagOffset = isTemplateTag ? getTemplateTagOffset(parentNode, el, meta) : null; // create the DOM if it wasn't created before
  3683. this.createDOM(el); // create the DOM of this template cloning the original DOM structure stored in this instance
  3684. // notice that if a documentFragment was passed (via meta) we will use it instead
  3685. const cloneNode = fragment || this.dom.cloneNode(true); // store root node
  3686. // notice that for template tags the root note will be the parent tag
  3687. this.el = isTemplateTag ? parentNode : el; // create the children array only for the <template> fragments
  3688. this.children = isTemplateTag ? children || Array.from(cloneNode.childNodes) : null; // inject the DOM into the el only if a fragment is available
  3689. if (!avoidDOMInjection && cloneNode) injectDOM(el, cloneNode); // create the bindings
  3690. this.bindings = this.bindingsData.map(binding => create$1(this.el, binding, templateTagOffset));
  3691. this.bindings.forEach(b => b.mount(scope, parentScope)); // store the template meta properties
  3692. this.meta = meta;
  3693. return this;
  3694. },
  3695. /**
  3696. * Update the template with fresh data
  3697. * @param {*} scope - template data
  3698. * @param {*} parentScope - scope of the parent template tag
  3699. * @returns {TemplateChunk} self
  3700. */
  3701. update(scope, parentScope) {
  3702. this.bindings.forEach(b => b.update(scope, parentScope));
  3703. return this;
  3704. },
  3705. /**
  3706. * Remove the template from the node where it was initially mounted
  3707. * @param {*} scope - template data
  3708. * @param {*} parentScope - scope of the parent template tag
  3709. * @param {boolean|null} mustRemoveRoot - if true remove the root element,
  3710. * if false or undefined clean the root tag content, if null don't touch the DOM
  3711. * @returns {TemplateChunk} self
  3712. */
  3713. unmount(scope, parentScope, mustRemoveRoot) {
  3714. if (mustRemoveRoot === void 0) {
  3715. mustRemoveRoot = false;
  3716. }
  3717. const el = this.el;
  3718. if (!el) {
  3719. return this;
  3720. }
  3721. this.bindings.forEach(b => b.unmount(scope, parentScope, mustRemoveRoot));
  3722. switch (true) {
  3723. // pure components should handle the DOM unmount updates by themselves
  3724. // for mustRemoveRoot === null don't touch the DOM
  3725. case el[IS_PURE_SYMBOL] || mustRemoveRoot === null:
  3726. break;
  3727. // if children are declared, clear them
  3728. // applicable for <template> and <slot/> bindings
  3729. case Array.isArray(this.children):
  3730. clearChildren(this.children);
  3731. break;
  3732. // clean the node children only
  3733. case !mustRemoveRoot:
  3734. cleanNode(el);
  3735. break;
  3736. // remove the root node only if the mustRemoveRoot is truly
  3737. case !!mustRemoveRoot:
  3738. removeChild(el);
  3739. break;
  3740. }
  3741. this.el = null;
  3742. return this;
  3743. },
  3744. /**
  3745. * Clone the template chunk
  3746. * @returns {TemplateChunk} a clone of this object resetting the this.el property
  3747. */
  3748. clone() {
  3749. return Object.assign({}, this, {
  3750. meta: {},
  3751. el: null
  3752. });
  3753. }
  3754. });
  3755. /**
  3756. * Create a template chunk wiring also the bindings
  3757. * @param {string|HTMLElement} html - template string
  3758. * @param {BindingData[]} bindings - bindings collection
  3759. * @returns {TemplateChunk} a new TemplateChunk copy
  3760. */
  3761. function create(html, bindings) {
  3762. if (bindings === void 0) {
  3763. bindings = [];
  3764. }
  3765. return Object.assign({}, TemplateChunk, {
  3766. html,
  3767. bindingsData: bindings
  3768. });
  3769. }
  3770. /**
  3771. * Method used to bind expressions to a DOM node
  3772. * @param {string|HTMLElement} html - your static template html structure
  3773. * @param {Array} bindings - list of the expressions to bind to update the markup
  3774. * @returns {TemplateChunk} a new TemplateChunk object having the `update`,`mount`, `unmount` and `clone` methods
  3775. *
  3776. * @example
  3777. *
  3778. * riotDOMBindings
  3779. * .template(
  3780. * `<div expr0><!----></div><div><p expr1><!----><section expr2></section></p>`,
  3781. * [
  3782. * {
  3783. * selector: '[expr0]',
  3784. * redundantAttribute: 'expr0',
  3785. * expressions: [
  3786. * {
  3787. * type: expressionTypes.TEXT,
  3788. * childNodeIndex: 0,
  3789. * evaluate(scope) {
  3790. * return scope.time;
  3791. * },
  3792. * },
  3793. * ],
  3794. * },
  3795. * {
  3796. * selector: '[expr1]',
  3797. * redundantAttribute: 'expr1',
  3798. * expressions: [
  3799. * {
  3800. * type: expressionTypes.TEXT,
  3801. * childNodeIndex: 0,
  3802. * evaluate(scope) {
  3803. * return scope.name;
  3804. * },
  3805. * },
  3806. * {
  3807. * type: 'attribute',
  3808. * name: 'style',
  3809. * evaluate(scope) {
  3810. * return scope.style;
  3811. * },
  3812. * },
  3813. * ],
  3814. * },
  3815. * {
  3816. * selector: '[expr2]',
  3817. * redundantAttribute: 'expr2',
  3818. * type: bindingTypes.IF,
  3819. * evaluate(scope) {
  3820. * return scope.isVisible;
  3821. * },
  3822. * template: riotDOMBindings.template('hello there'),
  3823. * },
  3824. * ]
  3825. * )
  3826. */
  3827. var DOMBindings = /*#__PURE__*/Object.freeze({
  3828. __proto__: null,
  3829. template: create,
  3830. createBinding: create$1,
  3831. createExpression: create$4,
  3832. bindingTypes: bindingTypes,
  3833. expressionTypes: expressionTypes
  3834. });
  3835. function noop() {
  3836. return this;
  3837. }
  3838. /**
  3839. * Autobind the methods of a source object to itself
  3840. * @param {Object} source - probably a riot tag instance
  3841. * @param {Array<string>} methods - list of the methods to autobind
  3842. * @returns {Object} the original object received
  3843. */
  3844. function autobindMethods(source, methods) {
  3845. methods.forEach(method => {
  3846. source[method] = source[method].bind(source);
  3847. });
  3848. return source;
  3849. }
  3850. /**
  3851. * Call the first argument received only if it's a function otherwise return it as it is
  3852. * @param {*} source - anything
  3853. * @returns {*} anything
  3854. */
  3855. function callOrAssign(source) {
  3856. return isFunction(source) ? source.prototype && source.prototype.constructor ? new source() : source() : source;
  3857. }
  3858. /**
  3859. * Converts any DOM node/s to a loopable array
  3860. * @param { HTMLElement|NodeList } els - single html element or a node list
  3861. * @returns { Array } always a loopable object
  3862. */
  3863. function domToArray(els) {
  3864. // can this object be already looped?
  3865. if (!Array.isArray(els)) {
  3866. // is it a node list?
  3867. if (/^\[object (HTMLCollection|NodeList|Object)\]$/.test(Object.prototype.toString.call(els)) && typeof els.length === 'number') return Array.from(els);else // if it's a single node
  3868. // it will be returned as "array" with one single entry
  3869. return [els];
  3870. } // this object could be looped out of the box
  3871. return els;
  3872. }
  3873. /**
  3874. * Simple helper to find DOM nodes returning them as array like loopable object
  3875. * @param { string|DOMNodeList } selector - either the query or the DOM nodes to arraify
  3876. * @param { HTMLElement } ctx - context defining where the query will search for the DOM nodes
  3877. * @returns { Array } DOM nodes found as array
  3878. */
  3879. function $(selector, ctx) {
  3880. return domToArray(typeof selector === 'string' ? (ctx || document).querySelectorAll(selector) : selector);
  3881. }
  3882. /**
  3883. * Normalize the return values, in case of a single value we avoid to return an array
  3884. * @param { Array } values - list of values we want to return
  3885. * @returns { Array|string|boolean } either the whole list of values or the single one found
  3886. * @private
  3887. */
  3888. const normalize = values => values.length === 1 ? values[0] : values;
  3889. /**
  3890. * Parse all the nodes received to get/remove/check their attributes
  3891. * @param { HTMLElement|NodeList|Array } els - DOM node/s to parse
  3892. * @param { string|Array } name - name or list of attributes
  3893. * @param { string } method - method that will be used to parse the attributes
  3894. * @returns { Array|string } result of the parsing in a list or a single value
  3895. * @private
  3896. */
  3897. function parseNodes(els, name, method) {
  3898. const names = typeof name === 'string' ? [name] : name;
  3899. return normalize(domToArray(els).map(el => {
  3900. return normalize(names.map(n => el[method](n)));
  3901. }));
  3902. }
  3903. /**
  3904. * Set any attribute on a single or a list of DOM nodes
  3905. * @param { HTMLElement|NodeList|Array } els - DOM node/s to parse
  3906. * @param { string|Object } name - either the name of the attribute to set
  3907. * or a list of properties as object key - value
  3908. * @param { string } value - the new value of the attribute (optional)
  3909. * @returns { HTMLElement|NodeList|Array } the original array of elements passed to this function
  3910. *
  3911. * @example
  3912. *
  3913. * import { set } from 'bianco.attr'
  3914. *
  3915. * const img = document.createElement('img')
  3916. *
  3917. * set(img, 'width', 100)
  3918. *
  3919. * // or also
  3920. * set(img, {
  3921. * width: 300,
  3922. * height: 300
  3923. * })
  3924. *
  3925. */
  3926. function set(els, name, value) {
  3927. const attrs = typeof name === 'object' ? name : {
  3928. [name]: value
  3929. };
  3930. const props = Object.keys(attrs);
  3931. domToArray(els).forEach(el => {
  3932. props.forEach(prop => el.setAttribute(prop, attrs[prop]));
  3933. });
  3934. return els;
  3935. }
  3936. /**
  3937. * Get any attribute from a single or a list of DOM nodes
  3938. * @param { HTMLElement|NodeList|Array } els - DOM node/s to parse
  3939. * @param { string|Array } name - name or list of attributes to get
  3940. * @returns { Array|string } list of the attributes found
  3941. *
  3942. * @example
  3943. *
  3944. * import { get } from 'bianco.attr'
  3945. *
  3946. * const img = document.createElement('img')
  3947. *
  3948. * get(img, 'width') // => '200'
  3949. *
  3950. * // or also
  3951. * get(img, ['width', 'height']) // => ['200', '300']
  3952. *
  3953. * // or also
  3954. * get([img1, img2], ['width', 'height']) // => [['200', '300'], ['500', '200']]
  3955. */
  3956. function get(els, name) {
  3957. return parseNodes(els, name, 'getAttribute');
  3958. }
  3959. const CSS_BY_NAME = new Map();
  3960. const STYLE_NODE_SELECTOR = 'style[riot]'; // memoized curried function
  3961. const getStyleNode = (style => {
  3962. return () => {
  3963. // lazy evaluation:
  3964. // if this function was already called before
  3965. // we return its cached result
  3966. if (style) return style; // create a new style element or use an existing one
  3967. // and cache it internally
  3968. style = $(STYLE_NODE_SELECTOR)[0] || document.createElement('style');
  3969. set(style, 'type', 'text/css');
  3970. /* istanbul ignore next */
  3971. if (!style.parentNode) document.head.appendChild(style);
  3972. return style;
  3973. };
  3974. })();
  3975. /**
  3976. * Object that will be used to inject and manage the css of every tag instance
  3977. */
  3978. var cssManager = {
  3979. CSS_BY_NAME,
  3980. /**
  3981. * Save a tag style to be later injected into DOM
  3982. * @param { string } name - if it's passed we will map the css to a tagname
  3983. * @param { string } css - css string
  3984. * @returns {Object} self
  3985. */
  3986. add(name, css) {
  3987. if (!CSS_BY_NAME.has(name)) {
  3988. CSS_BY_NAME.set(name, css);
  3989. this.inject();
  3990. }
  3991. return this;
  3992. },
  3993. /**
  3994. * Inject all previously saved tag styles into DOM
  3995. * innerHTML seems slow: http://jsperf.com/riot-insert-style
  3996. * @returns {Object} self
  3997. */
  3998. inject() {
  3999. getStyleNode().innerHTML = [...CSS_BY_NAME.values()].join('\n');
  4000. return this;
  4001. },
  4002. /**
  4003. * Remove a tag style from the DOM
  4004. * @param {string} name a registered tagname
  4005. * @returns {Object} self
  4006. */
  4007. remove(name) {
  4008. if (CSS_BY_NAME.has(name)) {
  4009. CSS_BY_NAME.delete(name);
  4010. this.inject();
  4011. }
  4012. return this;
  4013. }
  4014. };
  4015. /**
  4016. * Function to curry any javascript method
  4017. * @param {Function} fn - the target function we want to curry
  4018. * @param {...[args]} acc - initial arguments
  4019. * @returns {Function|*} it will return a function until the target function
  4020. * will receive all of its arguments
  4021. */
  4022. function curry(fn) {
  4023. for (var _len = arguments.length, acc = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  4024. acc[_key - 1] = arguments[_key];
  4025. }
  4026. return function () {
  4027. for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  4028. args[_key2] = arguments[_key2];
  4029. }
  4030. args = [...acc, ...args];
  4031. return args.length < fn.length ? curry(fn, ...args) : fn(...args);
  4032. };
  4033. }
  4034. /**
  4035. * Get the tag name of any DOM node
  4036. * @param {HTMLElement} element - DOM node we want to inspect
  4037. * @returns {string} name to identify this dom node in riot
  4038. */
  4039. function getName(element) {
  4040. return get(element, IS_DIRECTIVE) || element.tagName.toLowerCase();
  4041. }
  4042. const COMPONENT_CORE_HELPERS = Object.freeze({
  4043. // component helpers
  4044. $(selector) {
  4045. return $(selector, this.root)[0];
  4046. },
  4047. $$(selector) {
  4048. return $(selector, this.root);
  4049. }
  4050. });
  4051. const PURE_COMPONENT_API = Object.freeze({
  4052. [MOUNT_METHOD_KEY]: noop,
  4053. [UPDATE_METHOD_KEY]: noop,
  4054. [UNMOUNT_METHOD_KEY]: noop
  4055. });
  4056. const COMPONENT_LIFECYCLE_METHODS = Object.freeze({
  4057. [SHOULD_UPDATE_KEY]: noop,
  4058. [ON_BEFORE_MOUNT_KEY]: noop,
  4059. [ON_MOUNTED_KEY]: noop,
  4060. [ON_BEFORE_UPDATE_KEY]: noop,
  4061. [ON_UPDATED_KEY]: noop,
  4062. [ON_BEFORE_UNMOUNT_KEY]: noop,
  4063. [ON_UNMOUNTED_KEY]: noop
  4064. });
  4065. const MOCKED_TEMPLATE_INTERFACE = Object.assign({}, PURE_COMPONENT_API, {
  4066. clone: noop,
  4067. createDOM: noop
  4068. });
  4069. /**
  4070. * Performance optimization for the recursive components
  4071. * @param {RiotComponentWrapper} componentWrapper - riot compiler generated object
  4072. * @returns {Object} component like interface
  4073. */
  4074. const memoizedCreateComponent = memoize(createComponent);
  4075. /**
  4076. * Evaluate the component properties either from its real attributes or from its initial user properties
  4077. * @param {HTMLElement} element - component root
  4078. * @param {Object} initialProps - initial props
  4079. * @returns {Object} component props key value pairs
  4080. */
  4081. function evaluateInitialProps(element, initialProps) {
  4082. if (initialProps === void 0) {
  4083. initialProps = {};
  4084. }
  4085. return Object.assign({}, DOMattributesToObject(element), callOrAssign(initialProps));
  4086. }
  4087. /**
  4088. * Bind a DOM node to its component object
  4089. * @param {HTMLElement} node - html node mounted
  4090. * @param {Object} component - Riot.js component object
  4091. * @returns {Object} the component object received as second argument
  4092. */
  4093. const bindDOMNodeToComponentObject = (node, component) => node[DOM_COMPONENT_INSTANCE_PROPERTY$1] = component;
  4094. /**
  4095. * Wrap the Riot.js core API methods using a mapping function
  4096. * @param {Function} mapFunction - lifting function
  4097. * @returns {Object} an object having the { mount, update, unmount } functions
  4098. */
  4099. function createCoreAPIMethods(mapFunction) {
  4100. return [MOUNT_METHOD_KEY, UPDATE_METHOD_KEY, UNMOUNT_METHOD_KEY].reduce((acc, method) => {
  4101. acc[method] = mapFunction(method);
  4102. return acc;
  4103. }, {});
  4104. }
  4105. /**
  4106. * Factory function to create the component templates only once
  4107. * @param {Function} template - component template creation function
  4108. * @param {RiotComponentWrapper} componentWrapper - riot compiler generated object
  4109. * @returns {TemplateChunk} template chunk object
  4110. */
  4111. function componentTemplateFactory(template, componentWrapper) {
  4112. const components = createSubcomponents(componentWrapper.exports ? componentWrapper.exports.components : {});
  4113. return template(create, expressionTypes, bindingTypes, name => {
  4114. // improve support for recursive components
  4115. if (name === componentWrapper.name) return memoizedCreateComponent(componentWrapper); // return the registered components
  4116. return components[name] || COMPONENTS_IMPLEMENTATION_MAP$1.get(name);
  4117. });
  4118. }
  4119. /**
  4120. * Create a pure component
  4121. * @param {Function} pureFactoryFunction - pure component factory function
  4122. * @param {Array} options.slots - component slots
  4123. * @param {Array} options.attributes - component attributes
  4124. * @param {Array} options.template - template factory function
  4125. * @param {Array} options.template - template factory function
  4126. * @param {any} options.props - initial component properties
  4127. * @returns {Object} pure component object
  4128. */
  4129. function createPureComponent(pureFactoryFunction, _ref) {
  4130. let {
  4131. slots,
  4132. attributes,
  4133. props,
  4134. css,
  4135. template
  4136. } = _ref;
  4137. if (template) panic('Pure components can not have html');
  4138. if (css) panic('Pure components do not have css');
  4139. const component = defineDefaults(pureFactoryFunction({
  4140. slots,
  4141. attributes,
  4142. props
  4143. }), PURE_COMPONENT_API);
  4144. return createCoreAPIMethods(method => function () {
  4145. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  4146. args[_key] = arguments[_key];
  4147. }
  4148. // intercept the mount calls to bind the DOM node to the pure object created
  4149. // see also https://github.com/riot/riot/issues/2806
  4150. if (method === MOUNT_METHOD_KEY) {
  4151. const [el] = args; // mark this node as pure element
  4152. el[IS_PURE_SYMBOL] = true;
  4153. bindDOMNodeToComponentObject(el, component);
  4154. }
  4155. component[method](...args);
  4156. return component;
  4157. });
  4158. }
  4159. /**
  4160. * Create the component interface needed for the @riotjs/dom-bindings tag bindings
  4161. * @param {RiotComponentWrapper} componentWrapper - riot compiler generated object
  4162. * @param {string} componentWrapper.css - component css
  4163. * @param {Function} componentWrapper.template - function that will return the dom-bindings template function
  4164. * @param {Object} componentWrapper.exports - component interface
  4165. * @param {string} componentWrapper.name - component name
  4166. * @returns {Object} component like interface
  4167. */
  4168. function createComponent(componentWrapper) {
  4169. const {
  4170. css,
  4171. template,
  4172. exports,
  4173. name
  4174. } = componentWrapper;
  4175. const templateFn = template ? componentTemplateFactory(template, componentWrapper) : MOCKED_TEMPLATE_INTERFACE;
  4176. return _ref2 => {
  4177. let {
  4178. slots,
  4179. attributes,
  4180. props
  4181. } = _ref2;
  4182. // pure components rendering will be managed by the end user
  4183. if (exports && exports[IS_PURE_SYMBOL]) return createPureComponent(exports, {
  4184. slots,
  4185. attributes,
  4186. props,
  4187. css,
  4188. template
  4189. });
  4190. const componentAPI = callOrAssign(exports) || {};
  4191. const component = defineComponent({
  4192. css,
  4193. template: templateFn,
  4194. componentAPI,
  4195. name
  4196. })({
  4197. slots,
  4198. attributes,
  4199. props
  4200. }); // notice that for the components create via tag binding
  4201. // we need to invert the mount (state/parentScope) arguments
  4202. // the template bindings will only forward the parentScope updates
  4203. // and never deal with the component state
  4204. return {
  4205. mount(element, parentScope, state) {
  4206. return component.mount(element, state, parentScope);
  4207. },
  4208. update(parentScope, state) {
  4209. return component.update(state, parentScope);
  4210. },
  4211. unmount(preserveRoot) {
  4212. return component.unmount(preserveRoot);
  4213. }
  4214. };
  4215. };
  4216. }
  4217. /**
  4218. * Component definition function
  4219. * @param {Object} implementation - the componen implementation will be generated via compiler
  4220. * @param {Object} component - the component initial properties
  4221. * @returns {Object} a new component implementation object
  4222. */
  4223. function defineComponent(_ref3) {
  4224. let {
  4225. css,
  4226. template,
  4227. componentAPI,
  4228. name
  4229. } = _ref3;
  4230. // add the component css into the DOM
  4231. if (css && name) cssManager.add(name, css);
  4232. return curry(enhanceComponentAPI)(defineProperties( // set the component defaults without overriding the original component API
  4233. defineDefaults(componentAPI, Object.assign({}, COMPONENT_LIFECYCLE_METHODS, {
  4234. [PROPS_KEY]: {},
  4235. [STATE_KEY]: {}
  4236. })), Object.assign({
  4237. // defined during the component creation
  4238. [SLOTS_KEY]: null,
  4239. [ROOT_KEY]: null
  4240. }, COMPONENT_CORE_HELPERS, {
  4241. name,
  4242. css,
  4243. template
  4244. })));
  4245. }
  4246. /**
  4247. * Create the bindings to update the component attributes
  4248. * @param {HTMLElement} node - node where we will bind the expressions
  4249. * @param {Array} attributes - list of attribute bindings
  4250. * @returns {TemplateChunk} - template bindings object
  4251. */
  4252. function createAttributeBindings(node, attributes) {
  4253. if (attributes === void 0) {
  4254. attributes = [];
  4255. }
  4256. const expressions = attributes.map(a => create$4(node, a));
  4257. const binding = {};
  4258. return Object.assign(binding, Object.assign({
  4259. expressions
  4260. }, createCoreAPIMethods(method => scope => {
  4261. expressions.forEach(e => e[method](scope));
  4262. return binding;
  4263. })));
  4264. }
  4265. /**
  4266. * Create the subcomponents that can be included inside a tag in runtime
  4267. * @param {Object} components - components imported in runtime
  4268. * @returns {Object} all the components transformed into Riot.Component factory functions
  4269. */
  4270. function createSubcomponents(components) {
  4271. if (components === void 0) {
  4272. components = {};
  4273. }
  4274. return Object.entries(callOrAssign(components)).reduce((acc, _ref4) => {
  4275. let [key, value] = _ref4;
  4276. acc[camelToDashCase(key)] = createComponent(value);
  4277. return acc;
  4278. }, {});
  4279. }
  4280. /**
  4281. * Run the component instance through all the plugins set by the user
  4282. * @param {Object} component - component instance
  4283. * @returns {Object} the component enhanced by the plugins
  4284. */
  4285. function runPlugins(component) {
  4286. return [...PLUGINS_SET$1].reduce((c, fn) => fn(c) || c, component);
  4287. }
  4288. /**
  4289. * Compute the component current state merging it with its previous state
  4290. * @param {Object} oldState - previous state object
  4291. * @param {Object} newState - new state givent to the `update` call
  4292. * @returns {Object} new object state
  4293. */
  4294. function computeState(oldState, newState) {
  4295. return Object.assign({}, oldState, callOrAssign(newState));
  4296. }
  4297. /**
  4298. * Add eventually the "is" attribute to link this DOM node to its css
  4299. * @param {HTMLElement} element - target root node
  4300. * @param {string} name - name of the component mounted
  4301. * @returns {undefined} it's a void function
  4302. */
  4303. function addCssHook(element, name) {
  4304. if (getName(element) !== name) {
  4305. set(element, IS_DIRECTIVE, name);
  4306. }
  4307. }
  4308. /**
  4309. * Component creation factory function that will enhance the user provided API
  4310. * @param {Object} component - a component implementation previously defined
  4311. * @param {Array} options.slots - component slots generated via riot compiler
  4312. * @param {Array} options.attributes - attribute expressions generated via riot compiler
  4313. * @returns {Riot.Component} a riot component instance
  4314. */
  4315. function enhanceComponentAPI(component, _ref5) {
  4316. let {
  4317. slots,
  4318. attributes,
  4319. props
  4320. } = _ref5;
  4321. return autobindMethods(runPlugins(defineProperties(isObject(component) ? Object.create(component) : component, {
  4322. mount(element, state, parentScope) {
  4323. if (state === void 0) {
  4324. state = {};
  4325. }
  4326. this[PARENT_KEY_SYMBOL] = parentScope;
  4327. this[ATTRIBUTES_KEY_SYMBOL] = createAttributeBindings(element, attributes).mount(parentScope);
  4328. defineProperty(this, PROPS_KEY, Object.freeze(Object.assign({}, evaluateInitialProps(element, props), evaluateAttributeExpressions(this[ATTRIBUTES_KEY_SYMBOL].expressions))));
  4329. this[STATE_KEY] = computeState(this[STATE_KEY], state);
  4330. this[TEMPLATE_KEY_SYMBOL] = this.template.createDOM(element).clone(); // link this object to the DOM node
  4331. bindDOMNodeToComponentObject(element, this); // add eventually the 'is' attribute
  4332. component.name && addCssHook(element, component.name); // define the root element
  4333. defineProperty(this, ROOT_KEY, element); // define the slots array
  4334. defineProperty(this, SLOTS_KEY, slots); // before mount lifecycle event
  4335. this[ON_BEFORE_MOUNT_KEY](this[PROPS_KEY], this[STATE_KEY]); // mount the template
  4336. this[TEMPLATE_KEY_SYMBOL].mount(element, this, parentScope);
  4337. this[ON_MOUNTED_KEY](this[PROPS_KEY], this[STATE_KEY]);
  4338. return this;
  4339. },
  4340. update(state, parentScope) {
  4341. if (state === void 0) {
  4342. state = {};
  4343. }
  4344. if (parentScope) {
  4345. this[PARENT_KEY_SYMBOL] = parentScope;
  4346. this[ATTRIBUTES_KEY_SYMBOL].update(parentScope);
  4347. }
  4348. const newProps = evaluateAttributeExpressions(this[ATTRIBUTES_KEY_SYMBOL].expressions);
  4349. if (this[SHOULD_UPDATE_KEY](newProps, this[PROPS_KEY]) === false) return;
  4350. defineProperty(this, PROPS_KEY, Object.freeze(Object.assign({}, this[PROPS_KEY], newProps)));
  4351. this[STATE_KEY] = computeState(this[STATE_KEY], state);
  4352. this[ON_BEFORE_UPDATE_KEY](this[PROPS_KEY], this[STATE_KEY]); // avoiding recursive updates
  4353. // see also https://github.com/riot/riot/issues/2895
  4354. if (!this[IS_COMPONENT_UPDATING]) {
  4355. this[IS_COMPONENT_UPDATING] = true;
  4356. this[TEMPLATE_KEY_SYMBOL].update(this, this[PARENT_KEY_SYMBOL]);
  4357. }
  4358. this[ON_UPDATED_KEY](this[PROPS_KEY], this[STATE_KEY]);
  4359. this[IS_COMPONENT_UPDATING] = false;
  4360. return this;
  4361. },
  4362. unmount(preserveRoot) {
  4363. this[ON_BEFORE_UNMOUNT_KEY](this[PROPS_KEY], this[STATE_KEY]);
  4364. this[ATTRIBUTES_KEY_SYMBOL].unmount(); // if the preserveRoot is null the template html will be left untouched
  4365. // in that case the DOM cleanup will happen differently from a parent node
  4366. this[TEMPLATE_KEY_SYMBOL].unmount(this, this[PARENT_KEY_SYMBOL], preserveRoot === null ? null : !preserveRoot);
  4367. this[ON_UNMOUNTED_KEY](this[PROPS_KEY], this[STATE_KEY]);
  4368. return this;
  4369. }
  4370. })), Object.keys(component).filter(prop => isFunction(component[prop])));
  4371. }
  4372. /**
  4373. * Component initialization function starting from a DOM node
  4374. * @param {HTMLElement} element - element to upgrade
  4375. * @param {Object} initialProps - initial component properties
  4376. * @param {string} componentName - component id
  4377. * @returns {Object} a new component instance bound to a DOM node
  4378. */
  4379. function mountComponent(element, initialProps, componentName) {
  4380. const name = componentName || getName(element);
  4381. if (!COMPONENTS_IMPLEMENTATION_MAP$1.has(name)) panic(`The component named "${name}" was never registered`);
  4382. const component = COMPONENTS_IMPLEMENTATION_MAP$1.get(name)({
  4383. props: initialProps
  4384. });
  4385. return component.mount(element);
  4386. }
  4387. /**
  4388. * Similar to compose but performs from left-to-right function composition.<br/>
  4389. * {@link https://30secondsofcode.org/function#composeright see also}
  4390. * @param {...[function]} fns) - list of unary function
  4391. * @returns {*} result of the computation
  4392. */
  4393. /**
  4394. * Performs right-to-left function composition.<br/>
  4395. * Use Array.prototype.reduce() to perform right-to-left function composition.<br/>
  4396. * The last (rightmost) function can accept one or more arguments; the remaining functions must be unary.<br/>
  4397. * {@link https://30secondsofcode.org/function#compose original source code}
  4398. * @param {...[function]} fns) - list of unary function
  4399. * @returns {*} result of the computation
  4400. */
  4401. function compose() {
  4402. for (var _len2 = arguments.length, fns = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  4403. fns[_key2] = arguments[_key2];
  4404. }
  4405. return fns.reduce((f, g) => function () {
  4406. return f(g(...arguments));
  4407. });
  4408. }
  4409. const {
  4410. DOM_COMPONENT_INSTANCE_PROPERTY,
  4411. COMPONENTS_IMPLEMENTATION_MAP,
  4412. PLUGINS_SET
  4413. } = globals;
  4414. /**
  4415. * Riot public api
  4416. */
  4417. /**
  4418. * Register a custom tag by name
  4419. * @param {string} name - component name
  4420. * @param {Object} implementation - tag implementation
  4421. * @returns {Map} map containing all the components implementations
  4422. */
  4423. function register(name, _ref) {
  4424. let {
  4425. css,
  4426. template,
  4427. exports
  4428. } = _ref;
  4429. if (COMPONENTS_IMPLEMENTATION_MAP.has(name)) panic(`The component "${name}" was already registered`);
  4430. COMPONENTS_IMPLEMENTATION_MAP.set(name, createComponent({
  4431. name,
  4432. css,
  4433. template,
  4434. exports
  4435. }));
  4436. return COMPONENTS_IMPLEMENTATION_MAP;
  4437. }
  4438. /**
  4439. * Unregister a riot web component
  4440. * @param {string} name - component name
  4441. * @returns {Map} map containing all the components implementations
  4442. */
  4443. function unregister(name) {
  4444. if (!COMPONENTS_IMPLEMENTATION_MAP.has(name)) panic(`The component "${name}" was never registered`);
  4445. COMPONENTS_IMPLEMENTATION_MAP.delete(name);
  4446. cssManager.remove(name);
  4447. return COMPONENTS_IMPLEMENTATION_MAP;
  4448. }
  4449. /**
  4450. * Mounting function that will work only for the components that were globally registered
  4451. * @param {string|HTMLElement} selector - query for the selection or a DOM element
  4452. * @param {Object} initialProps - the initial component properties
  4453. * @param {string} name - optional component name
  4454. * @returns {Array} list of riot components
  4455. */
  4456. function mount(selector, initialProps, name) {
  4457. return $(selector).map(element => mountComponent(element, initialProps, name));
  4458. }
  4459. /**
  4460. * Sweet unmounting helper function for the DOM node mounted manually by the user
  4461. * @param {string|HTMLElement} selector - query for the selection or a DOM element
  4462. * @param {boolean|null} keepRootElement - if true keep the root element
  4463. * @returns {Array} list of nodes unmounted
  4464. */
  4465. function unmount(selector, keepRootElement) {
  4466. return $(selector).map(element => {
  4467. if (element[DOM_COMPONENT_INSTANCE_PROPERTY]) {
  4468. element[DOM_COMPONENT_INSTANCE_PROPERTY].unmount(keepRootElement);
  4469. }
  4470. return element;
  4471. });
  4472. }
  4473. /**
  4474. * Define a riot plugin
  4475. * @param {Function} plugin - function that will receive all the components created
  4476. * @returns {Set} the set containing all the plugins installed
  4477. */
  4478. function install(plugin) {
  4479. if (!isFunction(plugin)) panic('Plugins must be of type function');
  4480. if (PLUGINS_SET.has(plugin)) panic('This plugin was already installed');
  4481. PLUGINS_SET.add(plugin);
  4482. return PLUGINS_SET;
  4483. }
  4484. /**
  4485. * Uninstall a riot plugin
  4486. * @param {Function} plugin - plugin previously installed
  4487. * @returns {Set} the set containing all the plugins installed
  4488. */
  4489. function uninstall(plugin) {
  4490. if (!PLUGINS_SET.has(plugin)) panic('This plugin was never installed');
  4491. PLUGINS_SET.delete(plugin);
  4492. return PLUGINS_SET;
  4493. }
  4494. /**
  4495. * Helper method to create component without relying on the registered ones
  4496. * @param {Object} implementation - component implementation
  4497. * @returns {Function} function that will allow you to mount a riot component on a DOM node
  4498. */
  4499. function component(implementation) {
  4500. return function (el, props, _temp) {
  4501. let {
  4502. slots,
  4503. attributes,
  4504. parentScope
  4505. } = _temp === void 0 ? {} : _temp;
  4506. return compose(c => c.mount(el, parentScope), c => c({
  4507. props,
  4508. slots,
  4509. attributes
  4510. }), createComponent)(implementation);
  4511. };
  4512. }
  4513. /**
  4514. * Lift a riot component Interface into a pure riot object
  4515. * @param {Function} func - RiotPureComponent factory function
  4516. * @returns {Function} the lifted original function received as argument
  4517. */
  4518. function pure(func) {
  4519. if (!isFunction(func)) panic('riot.pure accepts only arguments of type "function"');
  4520. func[IS_PURE_SYMBOL] = true;
  4521. return func;
  4522. }
  4523. /**
  4524. * no-op function needed to add the proper types to your component via typescript
  4525. * @param {Function|Object} component - component default export
  4526. * @returns {Function|Object} returns exactly what it has received
  4527. */
  4528. const withTypes = component => component;
  4529. /** @type {string} current riot version */
  4530. const version = 'v6.0.1'; // expose some internal stuff that might be used from external tools
  4531. const __ = {
  4532. cssManager,
  4533. DOMBindings,
  4534. createComponent,
  4535. defineComponent,
  4536. globals
  4537. };
  4538. /***/ }),
  4539. /***/ "./node_modules/validate.js/validate.js":
  4540. /*!**********************************************!*\
  4541. !*** ./node_modules/validate.js/validate.js ***!
  4542. \**********************************************/
  4543. /***/ (function(module, exports, __webpack_require__) {
  4544. /* module decorator */ module = __webpack_require__.nmd(module);
  4545. /*!
  4546. * validate.js 0.13.1
  4547. *
  4548. * (c) 2013-2019 Nicklas Ansman, 2013 Wrapp
  4549. * Validate.js may be freely distributed under the MIT license.
  4550. * For all details and documentation:
  4551. * http://validatejs.org/
  4552. */
  4553. (function(exports, module, define) {
  4554. "use strict";
  4555. // The main function that calls the validators specified by the constraints.
  4556. // The options are the following:
  4557. // - format (string) - An option that controls how the returned value is formatted
  4558. // * flat - Returns a flat array of just the error messages
  4559. // * grouped - Returns the messages grouped by attribute (default)
  4560. // * detailed - Returns an array of the raw validation data
  4561. // - fullMessages (boolean) - If `true` (default) the attribute name is prepended to the error.
  4562. //
  4563. // Please note that the options are also passed to each validator.
  4564. var validate = function(attributes, constraints, options) {
  4565. options = v.extend({}, v.options, options);
  4566. var results = v.runValidations(attributes, constraints, options)
  4567. , attr
  4568. , validator;
  4569. if (results.some(function(r) { return v.isPromise(r.error); })) {
  4570. throw new Error("Use validate.async if you want support for promises");
  4571. }
  4572. return validate.processValidationResults(results, options);
  4573. };
  4574. var v = validate;
  4575. // Copies over attributes from one or more sources to a single destination.
  4576. // Very much similar to underscore's extend.
  4577. // The first argument is the target object and the remaining arguments will be
  4578. // used as sources.
  4579. v.extend = function(obj) {
  4580. [].slice.call(arguments, 1).forEach(function(source) {
  4581. for (var attr in source) {
  4582. obj[attr] = source[attr];
  4583. }
  4584. });
  4585. return obj;
  4586. };
  4587. v.extend(validate, {
  4588. // This is the version of the library as a semver.
  4589. // The toString function will allow it to be coerced into a string
  4590. version: {
  4591. major: 0,
  4592. minor: 13,
  4593. patch: 1,
  4594. metadata: null,
  4595. toString: function() {
  4596. var version = v.format("%{major}.%{minor}.%{patch}", v.version);
  4597. if (!v.isEmpty(v.version.metadata)) {
  4598. version += "+" + v.version.metadata;
  4599. }
  4600. return version;
  4601. }
  4602. },
  4603. // Below is the dependencies that are used in validate.js
  4604. // The constructor of the Promise implementation.
  4605. // If you are using Q.js, RSVP or any other A+ compatible implementation
  4606. // override this attribute to be the constructor of that promise.
  4607. // Since jQuery promises aren't A+ compatible they won't work.
  4608. Promise: typeof Promise !== "undefined" ? Promise : /* istanbul ignore next */ null,
  4609. EMPTY_STRING_REGEXP: /^\s*$/,
  4610. // Runs the validators specified by the constraints object.
  4611. // Will return an array of the format:
  4612. // [{attribute: "<attribute name>", error: "<validation result>"}, ...]
  4613. runValidations: function(attributes, constraints, options) {
  4614. var results = []
  4615. , attr
  4616. , validatorName
  4617. , value
  4618. , validators
  4619. , validator
  4620. , validatorOptions
  4621. , error;
  4622. if (v.isDomElement(attributes) || v.isJqueryElement(attributes)) {
  4623. attributes = v.collectFormValues(attributes);
  4624. }
  4625. // Loops through each constraints, finds the correct validator and run it.
  4626. for (attr in constraints) {
  4627. value = v.getDeepObjectValue(attributes, attr);
  4628. // This allows the constraints for an attribute to be a function.
  4629. // The function will be called with the value, attribute name, the complete dict of
  4630. // attributes as well as the options and constraints passed in.
  4631. // This is useful when you want to have different
  4632. // validations depending on the attribute value.
  4633. validators = v.result(constraints[attr], value, attributes, attr, options, constraints);
  4634. for (validatorName in validators) {
  4635. validator = v.validators[validatorName];
  4636. if (!validator) {
  4637. error = v.format("Unknown validator %{name}", {name: validatorName});
  4638. throw new Error(error);
  4639. }
  4640. validatorOptions = validators[validatorName];
  4641. // This allows the options to be a function. The function will be
  4642. // called with the value, attribute name, the complete dict of
  4643. // attributes as well as the options and constraints passed in.
  4644. // This is useful when you want to have different
  4645. // validations depending on the attribute value.
  4646. validatorOptions = v.result(validatorOptions, value, attributes, attr, options, constraints);
  4647. if (!validatorOptions) {
  4648. continue;
  4649. }
  4650. results.push({
  4651. attribute: attr,
  4652. value: value,
  4653. validator: validatorName,
  4654. globalOptions: options,
  4655. attributes: attributes,
  4656. options: validatorOptions,
  4657. error: validator.call(validator,
  4658. value,
  4659. validatorOptions,
  4660. attr,
  4661. attributes,
  4662. options)
  4663. });
  4664. }
  4665. }
  4666. return results;
  4667. },
  4668. // Takes the output from runValidations and converts it to the correct
  4669. // output format.
  4670. processValidationResults: function(errors, options) {
  4671. errors = v.pruneEmptyErrors(errors, options);
  4672. errors = v.expandMultipleErrors(errors, options);
  4673. errors = v.convertErrorMessages(errors, options);
  4674. var format = options.format || "grouped";
  4675. if (typeof v.formatters[format] === 'function') {
  4676. errors = v.formatters[format](errors);
  4677. } else {
  4678. throw new Error(v.format("Unknown format %{format}", options));
  4679. }
  4680. return v.isEmpty(errors) ? undefined : errors;
  4681. },
  4682. // Runs the validations with support for promises.
  4683. // This function will return a promise that is settled when all the
  4684. // validation promises have been completed.
  4685. // It can be called even if no validations returned a promise.
  4686. async: function(attributes, constraints, options) {
  4687. options = v.extend({}, v.async.options, options);
  4688. var WrapErrors = options.wrapErrors || function(errors) {
  4689. return errors;
  4690. };
  4691. // Removes unknown attributes
  4692. if (options.cleanAttributes !== false) {
  4693. attributes = v.cleanAttributes(attributes, constraints);
  4694. }
  4695. var results = v.runValidations(attributes, constraints, options);
  4696. return new v.Promise(function(resolve, reject) {
  4697. v.waitForResults(results).then(function() {
  4698. var errors = v.processValidationResults(results, options);
  4699. if (errors) {
  4700. reject(new WrapErrors(errors, options, attributes, constraints));
  4701. } else {
  4702. resolve(attributes);
  4703. }
  4704. }, function(err) {
  4705. reject(err);
  4706. });
  4707. });
  4708. },
  4709. single: function(value, constraints, options) {
  4710. options = v.extend({}, v.single.options, options, {
  4711. format: "flat",
  4712. fullMessages: false
  4713. });
  4714. return v({single: value}, {single: constraints}, options);
  4715. },
  4716. // Returns a promise that is resolved when all promises in the results array
  4717. // are settled. The promise returned from this function is always resolved,
  4718. // never rejected.
  4719. // This function modifies the input argument, it replaces the promises
  4720. // with the value returned from the promise.
  4721. waitForResults: function(results) {
  4722. // Create a sequence of all the results starting with a resolved promise.
  4723. return results.reduce(function(memo, result) {
  4724. // If this result isn't a promise skip it in the sequence.
  4725. if (!v.isPromise(result.error)) {
  4726. return memo;
  4727. }
  4728. return memo.then(function() {
  4729. return result.error.then(function(error) {
  4730. result.error = error || null;
  4731. });
  4732. });
  4733. }, new v.Promise(function(r) { r(); })); // A resolved promise
  4734. },
  4735. // If the given argument is a call: function the and: function return the value
  4736. // otherwise just return the value. Additional arguments will be passed as
  4737. // arguments to the function.
  4738. // Example:
  4739. // ```
  4740. // result('foo') // 'foo'
  4741. // result(Math.max, 1, 2) // 2
  4742. // ```
  4743. result: function(value) {
  4744. var args = [].slice.call(arguments, 1);
  4745. if (typeof value === 'function') {
  4746. value = value.apply(null, args);
  4747. }
  4748. return value;
  4749. },
  4750. // Checks if the value is a number. This function does not consider NaN a
  4751. // number like many other `isNumber` functions do.
  4752. isNumber: function(value) {
  4753. return typeof value === 'number' && !isNaN(value);
  4754. },
  4755. // Returns false if the object is not a function
  4756. isFunction: function(value) {
  4757. return typeof value === 'function';
  4758. },
  4759. // A simple check to verify that the value is an integer. Uses `isNumber`
  4760. // and a simple modulo check.
  4761. isInteger: function(value) {
  4762. return v.isNumber(value) && value % 1 === 0;
  4763. },
  4764. // Checks if the value is a boolean
  4765. isBoolean: function(value) {
  4766. return typeof value === 'boolean';
  4767. },
  4768. // Uses the `Object` function to check if the given argument is an object.
  4769. isObject: function(obj) {
  4770. return obj === Object(obj);
  4771. },
  4772. // Simply checks if the object is an instance of a date
  4773. isDate: function(obj) {
  4774. return obj instanceof Date;
  4775. },
  4776. // Returns false if the object is `null` of `undefined`
  4777. isDefined: function(obj) {
  4778. return obj !== null && obj !== undefined;
  4779. },
  4780. // Checks if the given argument is a promise. Anything with a `then`
  4781. // function is considered a promise.
  4782. isPromise: function(p) {
  4783. return !!p && v.isFunction(p.then);
  4784. },
  4785. isJqueryElement: function(o) {
  4786. return o && v.isString(o.jquery);
  4787. },
  4788. isDomElement: function(o) {
  4789. if (!o) {
  4790. return false;
  4791. }
  4792. if (!o.querySelectorAll || !o.querySelector) {
  4793. return false;
  4794. }
  4795. if (v.isObject(document) && o === document) {
  4796. return true;
  4797. }
  4798. // http://stackoverflow.com/a/384380/699304
  4799. /* istanbul ignore else */
  4800. if (typeof HTMLElement === "object") {
  4801. return o instanceof HTMLElement;
  4802. } else {
  4803. return o &&
  4804. typeof o === "object" &&
  4805. o !== null &&
  4806. o.nodeType === 1 &&
  4807. typeof o.nodeName === "string";
  4808. }
  4809. },
  4810. isEmpty: function(value) {
  4811. var attr;
  4812. // Null and undefined are empty
  4813. if (!v.isDefined(value)) {
  4814. return true;
  4815. }
  4816. // functions are non empty
  4817. if (v.isFunction(value)) {
  4818. return false;
  4819. }
  4820. // Whitespace only strings are empty
  4821. if (v.isString(value)) {
  4822. return v.EMPTY_STRING_REGEXP.test(value);
  4823. }
  4824. // For arrays we use the length property
  4825. if (v.isArray(value)) {
  4826. return value.length === 0;
  4827. }
  4828. // Dates have no attributes but aren't empty
  4829. if (v.isDate(value)) {
  4830. return false;
  4831. }
  4832. // If we find at least one property we consider it non empty
  4833. if (v.isObject(value)) {
  4834. for (attr in value) {
  4835. return false;
  4836. }
  4837. return true;
  4838. }
  4839. return false;
  4840. },
  4841. // Formats the specified strings with the given values like so:
  4842. // ```
  4843. // format("Foo: %{foo}", {foo: "bar"}) // "Foo bar"
  4844. // ```
  4845. // If you want to write %{...} without having it replaced simply
  4846. // prefix it with % like this `Foo: %%{foo}` and it will be returned
  4847. // as `"Foo: %{foo}"`
  4848. format: v.extend(function(str, vals) {
  4849. if (!v.isString(str)) {
  4850. return str;
  4851. }
  4852. return str.replace(v.format.FORMAT_REGEXP, function(m0, m1, m2) {
  4853. if (m1 === '%') {
  4854. return "%{" + m2 + "}";
  4855. } else {
  4856. return String(vals[m2]);
  4857. }
  4858. });
  4859. }, {
  4860. // Finds %{key} style patterns in the given string
  4861. FORMAT_REGEXP: /(%?)%\{([^\}]+)\}/g
  4862. }),
  4863. // "Prettifies" the given string.
  4864. // Prettifying means replacing [.\_-] with spaces as well as splitting
  4865. // camel case words.
  4866. prettify: function(str) {
  4867. if (v.isNumber(str)) {
  4868. // If there are more than 2 decimals round it to two
  4869. if ((str * 100) % 1 === 0) {
  4870. return "" + str;
  4871. } else {
  4872. return parseFloat(Math.round(str * 100) / 100).toFixed(2);
  4873. }
  4874. }
  4875. if (v.isArray(str)) {
  4876. return str.map(function(s) { return v.prettify(s); }).join(", ");
  4877. }
  4878. if (v.isObject(str)) {
  4879. if (!v.isDefined(str.toString)) {
  4880. return JSON.stringify(str);
  4881. }
  4882. return str.toString();
  4883. }
  4884. // Ensure the string is actually a string
  4885. str = "" + str;
  4886. return str
  4887. // Splits keys separated by periods
  4888. .replace(/([^\s])\.([^\s])/g, '$1 $2')
  4889. // Removes backslashes
  4890. .replace(/\\+/g, '')
  4891. // Replaces - and - with space
  4892. .replace(/[_-]/g, ' ')
  4893. // Splits camel cased words
  4894. .replace(/([a-z])([A-Z])/g, function(m0, m1, m2) {
  4895. return "" + m1 + " " + m2.toLowerCase();
  4896. })
  4897. .toLowerCase();
  4898. },
  4899. stringifyValue: function(value, options) {
  4900. var prettify = options && options.prettify || v.prettify;
  4901. return prettify(value);
  4902. },
  4903. isString: function(value) {
  4904. return typeof value === 'string';
  4905. },
  4906. isArray: function(value) {
  4907. return {}.toString.call(value) === '[object Array]';
  4908. },
  4909. // Checks if the object is a hash, which is equivalent to an object that
  4910. // is neither an array nor a function.
  4911. isHash: function(value) {
  4912. return v.isObject(value) && !v.isArray(value) && !v.isFunction(value);
  4913. },
  4914. contains: function(obj, value) {
  4915. if (!v.isDefined(obj)) {
  4916. return false;
  4917. }
  4918. if (v.isArray(obj)) {
  4919. return obj.indexOf(value) !== -1;
  4920. }
  4921. return value in obj;
  4922. },
  4923. unique: function(array) {
  4924. if (!v.isArray(array)) {
  4925. return array;
  4926. }
  4927. return array.filter(function(el, index, array) {
  4928. return array.indexOf(el) == index;
  4929. });
  4930. },
  4931. forEachKeyInKeypath: function(object, keypath, callback) {
  4932. if (!v.isString(keypath)) {
  4933. return undefined;
  4934. }
  4935. var key = ""
  4936. , i
  4937. , escape = false;
  4938. for (i = 0; i < keypath.length; ++i) {
  4939. switch (keypath[i]) {
  4940. case '.':
  4941. if (escape) {
  4942. escape = false;
  4943. key += '.';
  4944. } else {
  4945. object = callback(object, key, false);
  4946. key = "";
  4947. }
  4948. break;
  4949. case '\\':
  4950. if (escape) {
  4951. escape = false;
  4952. key += '\\';
  4953. } else {
  4954. escape = true;
  4955. }
  4956. break;
  4957. default:
  4958. escape = false;
  4959. key += keypath[i];
  4960. break;
  4961. }
  4962. }
  4963. return callback(object, key, true);
  4964. },
  4965. getDeepObjectValue: function(obj, keypath) {
  4966. if (!v.isObject(obj)) {
  4967. return undefined;
  4968. }
  4969. return v.forEachKeyInKeypath(obj, keypath, function(obj, key) {
  4970. if (v.isObject(obj)) {
  4971. return obj[key];
  4972. }
  4973. });
  4974. },
  4975. // This returns an object with all the values of the form.
  4976. // It uses the input name as key and the value as value
  4977. // So for example this:
  4978. // <input type="text" name="email" value="foo@bar.com" />
  4979. // would return:
  4980. // {email: "foo@bar.com"}
  4981. collectFormValues: function(form, options) {
  4982. var values = {}
  4983. , i
  4984. , j
  4985. , input
  4986. , inputs
  4987. , option
  4988. , value;
  4989. if (v.isJqueryElement(form)) {
  4990. form = form[0];
  4991. }
  4992. if (!form) {
  4993. return values;
  4994. }
  4995. options = options || {};
  4996. inputs = form.querySelectorAll("input[name], textarea[name]");
  4997. for (i = 0; i < inputs.length; ++i) {
  4998. input = inputs.item(i);
  4999. if (v.isDefined(input.getAttribute("data-ignored"))) {
  5000. continue;
  5001. }
  5002. var name = input.name.replace(/\./g, "\\\\.");
  5003. value = v.sanitizeFormValue(input.value, options);
  5004. if (input.type === "number") {
  5005. value = value ? +value : null;
  5006. } else if (input.type === "checkbox") {
  5007. if (input.attributes.value) {
  5008. if (!input.checked) {
  5009. value = values[name] || null;
  5010. }
  5011. } else {
  5012. value = input.checked;
  5013. }
  5014. } else if (input.type === "radio") {
  5015. if (!input.checked) {
  5016. value = values[name] || null;
  5017. }
  5018. }
  5019. values[name] = value;
  5020. }
  5021. inputs = form.querySelectorAll("select[name]");
  5022. for (i = 0; i < inputs.length; ++i) {
  5023. input = inputs.item(i);
  5024. if (v.isDefined(input.getAttribute("data-ignored"))) {
  5025. continue;
  5026. }
  5027. if (input.multiple) {
  5028. value = [];
  5029. for (j in input.options) {
  5030. option = input.options[j];
  5031. if (option && option.selected) {
  5032. value.push(v.sanitizeFormValue(option.value, options));
  5033. }
  5034. }
  5035. } else {
  5036. var _val = typeof input.options[input.selectedIndex] !== 'undefined' ? input.options[input.selectedIndex].value : /* istanbul ignore next */ '';
  5037. value = v.sanitizeFormValue(_val, options);
  5038. }
  5039. values[input.name] = value;
  5040. }
  5041. return values;
  5042. },
  5043. sanitizeFormValue: function(value, options) {
  5044. if (options.trim && v.isString(value)) {
  5045. value = value.trim();
  5046. }
  5047. if (options.nullify !== false && value === "") {
  5048. return null;
  5049. }
  5050. return value;
  5051. },
  5052. capitalize: function(str) {
  5053. if (!v.isString(str)) {
  5054. return str;
  5055. }
  5056. return str[0].toUpperCase() + str.slice(1);
  5057. },
  5058. // Remove all errors who's error attribute is empty (null or undefined)
  5059. pruneEmptyErrors: function(errors) {
  5060. return errors.filter(function(error) {
  5061. return !v.isEmpty(error.error);
  5062. });
  5063. },
  5064. // In
  5065. // [{error: ["err1", "err2"], ...}]
  5066. // Out
  5067. // [{error: "err1", ...}, {error: "err2", ...}]
  5068. //
  5069. // All attributes in an error with multiple messages are duplicated
  5070. // when expanding the errors.
  5071. expandMultipleErrors: function(errors) {
  5072. var ret = [];
  5073. errors.forEach(function(error) {
  5074. // Removes errors without a message
  5075. if (v.isArray(error.error)) {
  5076. error.error.forEach(function(msg) {
  5077. ret.push(v.extend({}, error, {error: msg}));
  5078. });
  5079. } else {
  5080. ret.push(error);
  5081. }
  5082. });
  5083. return ret;
  5084. },
  5085. // Converts the error mesages by prepending the attribute name unless the
  5086. // message is prefixed by ^
  5087. convertErrorMessages: function(errors, options) {
  5088. options = options || {};
  5089. var ret = []
  5090. , prettify = options.prettify || v.prettify;
  5091. errors.forEach(function(errorInfo) {
  5092. var error = v.result(errorInfo.error,
  5093. errorInfo.value,
  5094. errorInfo.attribute,
  5095. errorInfo.options,
  5096. errorInfo.attributes,
  5097. errorInfo.globalOptions);
  5098. if (!v.isString(error)) {
  5099. ret.push(errorInfo);
  5100. return;
  5101. }
  5102. if (error[0] === '^') {
  5103. error = error.slice(1);
  5104. } else if (options.fullMessages !== false) {
  5105. error = v.capitalize(prettify(errorInfo.attribute)) + " " + error;
  5106. }
  5107. error = error.replace(/\\\^/g, "^");
  5108. error = v.format(error, {
  5109. value: v.stringifyValue(errorInfo.value, options)
  5110. });
  5111. ret.push(v.extend({}, errorInfo, {error: error}));
  5112. });
  5113. return ret;
  5114. },
  5115. // In:
  5116. // [{attribute: "<attributeName>", ...}]
  5117. // Out:
  5118. // {"<attributeName>": [{attribute: "<attributeName>", ...}]}
  5119. groupErrorsByAttribute: function(errors) {
  5120. var ret = {};
  5121. errors.forEach(function(error) {
  5122. var list = ret[error.attribute];
  5123. if (list) {
  5124. list.push(error);
  5125. } else {
  5126. ret[error.attribute] = [error];
  5127. }
  5128. });
  5129. return ret;
  5130. },
  5131. // In:
  5132. // [{error: "<message 1>", ...}, {error: "<message 2>", ...}]
  5133. // Out:
  5134. // ["<message 1>", "<message 2>"]
  5135. flattenErrorsToArray: function(errors) {
  5136. return errors
  5137. .map(function(error) { return error.error; })
  5138. .filter(function(value, index, self) {
  5139. return self.indexOf(value) === index;
  5140. });
  5141. },
  5142. cleanAttributes: function(attributes, whitelist) {
  5143. function whitelistCreator(obj, key, last) {
  5144. if (v.isObject(obj[key])) {
  5145. return obj[key];
  5146. }
  5147. return (obj[key] = last ? true : {});
  5148. }
  5149. function buildObjectWhitelist(whitelist) {
  5150. var ow = {}
  5151. , lastObject
  5152. , attr;
  5153. for (attr in whitelist) {
  5154. if (!whitelist[attr]) {
  5155. continue;
  5156. }
  5157. v.forEachKeyInKeypath(ow, attr, whitelistCreator);
  5158. }
  5159. return ow;
  5160. }
  5161. function cleanRecursive(attributes, whitelist) {
  5162. if (!v.isObject(attributes)) {
  5163. return attributes;
  5164. }
  5165. var ret = v.extend({}, attributes)
  5166. , w
  5167. , attribute;
  5168. for (attribute in attributes) {
  5169. w = whitelist[attribute];
  5170. if (v.isObject(w)) {
  5171. ret[attribute] = cleanRecursive(ret[attribute], w);
  5172. } else if (!w) {
  5173. delete ret[attribute];
  5174. }
  5175. }
  5176. return ret;
  5177. }
  5178. if (!v.isObject(whitelist) || !v.isObject(attributes)) {
  5179. return {};
  5180. }
  5181. whitelist = buildObjectWhitelist(whitelist);
  5182. return cleanRecursive(attributes, whitelist);
  5183. },
  5184. exposeModule: function(validate, root, exports, module, define) {
  5185. if (exports) {
  5186. if (module && module.exports) {
  5187. exports = module.exports = validate;
  5188. }
  5189. exports.validate = validate;
  5190. } else {
  5191. root.validate = validate;
  5192. if (validate.isFunction(define) && define.amd) {
  5193. define([], function () { return validate; });
  5194. }
  5195. }
  5196. },
  5197. warn: function(msg) {
  5198. if (typeof console !== "undefined" && console.warn) {
  5199. console.warn("[validate.js] " + msg);
  5200. }
  5201. },
  5202. error: function(msg) {
  5203. if (typeof console !== "undefined" && console.error) {
  5204. console.error("[validate.js] " + msg);
  5205. }
  5206. }
  5207. });
  5208. validate.validators = {
  5209. // Presence validates that the value isn't empty
  5210. presence: function(value, options) {
  5211. options = v.extend({}, this.options, options);
  5212. if (options.allowEmpty !== false ? !v.isDefined(value) : v.isEmpty(value)) {
  5213. return options.message || this.message || "can't be blank";
  5214. }
  5215. },
  5216. length: function(value, options, attribute) {
  5217. // Empty values are allowed
  5218. if (!v.isDefined(value)) {
  5219. return;
  5220. }
  5221. options = v.extend({}, this.options, options);
  5222. var is = options.is
  5223. , maximum = options.maximum
  5224. , minimum = options.minimum
  5225. , tokenizer = options.tokenizer || function(val) { return val; }
  5226. , err
  5227. , errors = [];
  5228. value = tokenizer(value);
  5229. var length = value.length;
  5230. if(!v.isNumber(length)) {
  5231. return options.message || this.notValid || "has an incorrect length";
  5232. }
  5233. // Is checks
  5234. if (v.isNumber(is) && length !== is) {
  5235. err = options.wrongLength ||
  5236. this.wrongLength ||
  5237. "is the wrong length (should be %{count} characters)";
  5238. errors.push(v.format(err, {count: is}));
  5239. }
  5240. if (v.isNumber(minimum) && length < minimum) {
  5241. err = options.tooShort ||
  5242. this.tooShort ||
  5243. "is too short (minimum is %{count} characters)";
  5244. errors.push(v.format(err, {count: minimum}));
  5245. }
  5246. if (v.isNumber(maximum) && length > maximum) {
  5247. err = options.tooLong ||
  5248. this.tooLong ||
  5249. "is too long (maximum is %{count} characters)";
  5250. errors.push(v.format(err, {count: maximum}));
  5251. }
  5252. if (errors.length > 0) {
  5253. return options.message || errors;
  5254. }
  5255. },
  5256. numericality: function(value, options, attribute, attributes, globalOptions) {
  5257. // Empty values are fine
  5258. if (!v.isDefined(value)) {
  5259. return;
  5260. }
  5261. options = v.extend({}, this.options, options);
  5262. var errors = []
  5263. , name
  5264. , count
  5265. , checks = {
  5266. greaterThan: function(v, c) { return v > c; },
  5267. greaterThanOrEqualTo: function(v, c) { return v >= c; },
  5268. equalTo: function(v, c) { return v === c; },
  5269. lessThan: function(v, c) { return v < c; },
  5270. lessThanOrEqualTo: function(v, c) { return v <= c; },
  5271. divisibleBy: function(v, c) { return v % c === 0; }
  5272. }
  5273. , prettify = options.prettify ||
  5274. (globalOptions && globalOptions.prettify) ||
  5275. v.prettify;
  5276. // Strict will check that it is a valid looking number
  5277. if (v.isString(value) && options.strict) {
  5278. var pattern = "^-?(0|[1-9]\\d*)";
  5279. if (!options.onlyInteger) {
  5280. pattern += "(\\.\\d+)?";
  5281. }
  5282. pattern += "$";
  5283. if (!(new RegExp(pattern).test(value))) {
  5284. return options.message ||
  5285. options.notValid ||
  5286. this.notValid ||
  5287. this.message ||
  5288. "must be a valid number";
  5289. }
  5290. }
  5291. // Coerce the value to a number unless we're being strict.
  5292. if (options.noStrings !== true && v.isString(value) && !v.isEmpty(value)) {
  5293. value = +value;
  5294. }
  5295. // If it's not a number we shouldn't continue since it will compare it.
  5296. if (!v.isNumber(value)) {
  5297. return options.message ||
  5298. options.notValid ||
  5299. this.notValid ||
  5300. this.message ||
  5301. "is not a number";
  5302. }
  5303. // Same logic as above, sort of. Don't bother with comparisons if this
  5304. // doesn't pass.
  5305. if (options.onlyInteger && !v.isInteger(value)) {
  5306. return options.message ||
  5307. options.notInteger ||
  5308. this.notInteger ||
  5309. this.message ||
  5310. "must be an integer";
  5311. }
  5312. for (name in checks) {
  5313. count = options[name];
  5314. if (v.isNumber(count) && !checks[name](value, count)) {
  5315. // This picks the default message if specified
  5316. // For example the greaterThan check uses the message from
  5317. // this.notGreaterThan so we capitalize the name and prepend "not"
  5318. var key = "not" + v.capitalize(name);
  5319. var msg = options[key] ||
  5320. this[key] ||
  5321. this.message ||
  5322. "must be %{type} %{count}";
  5323. errors.push(v.format(msg, {
  5324. count: count,
  5325. type: prettify(name)
  5326. }));
  5327. }
  5328. }
  5329. if (options.odd && value % 2 !== 1) {
  5330. errors.push(options.notOdd ||
  5331. this.notOdd ||
  5332. this.message ||
  5333. "must be odd");
  5334. }
  5335. if (options.even && value % 2 !== 0) {
  5336. errors.push(options.notEven ||
  5337. this.notEven ||
  5338. this.message ||
  5339. "must be even");
  5340. }
  5341. if (errors.length) {
  5342. return options.message || errors;
  5343. }
  5344. },
  5345. datetime: v.extend(function(value, options) {
  5346. if (!v.isFunction(this.parse) || !v.isFunction(this.format)) {
  5347. throw new Error("Both the parse and format functions needs to be set to use the datetime/date validator");
  5348. }
  5349. // Empty values are fine
  5350. if (!v.isDefined(value)) {
  5351. return;
  5352. }
  5353. options = v.extend({}, this.options, options);
  5354. var err
  5355. , errors = []
  5356. , earliest = options.earliest ? this.parse(options.earliest, options) : NaN
  5357. , latest = options.latest ? this.parse(options.latest, options) : NaN;
  5358. value = this.parse(value, options);
  5359. // 86400000 is the number of milliseconds in a day, this is used to remove
  5360. // the time from the date
  5361. if (isNaN(value) || options.dateOnly && value % 86400000 !== 0) {
  5362. err = options.notValid ||
  5363. options.message ||
  5364. this.notValid ||
  5365. "must be a valid date";
  5366. return v.format(err, {value: arguments[0]});
  5367. }
  5368. if (!isNaN(earliest) && value < earliest) {
  5369. err = options.tooEarly ||
  5370. options.message ||
  5371. this.tooEarly ||
  5372. "must be no earlier than %{date}";
  5373. err = v.format(err, {
  5374. value: this.format(value, options),
  5375. date: this.format(earliest, options)
  5376. });
  5377. errors.push(err);
  5378. }
  5379. if (!isNaN(latest) && value > latest) {
  5380. err = options.tooLate ||
  5381. options.message ||
  5382. this.tooLate ||
  5383. "must be no later than %{date}";
  5384. err = v.format(err, {
  5385. date: this.format(latest, options),
  5386. value: this.format(value, options)
  5387. });
  5388. errors.push(err);
  5389. }
  5390. if (errors.length) {
  5391. return v.unique(errors);
  5392. }
  5393. }, {
  5394. parse: null,
  5395. format: null
  5396. }),
  5397. date: function(value, options) {
  5398. options = v.extend({}, options, {dateOnly: true});
  5399. return v.validators.datetime.call(v.validators.datetime, value, options);
  5400. },
  5401. format: function(value, options) {
  5402. if (v.isString(options) || (options instanceof RegExp)) {
  5403. options = {pattern: options};
  5404. }
  5405. options = v.extend({}, this.options, options);
  5406. var message = options.message || this.message || "is invalid"
  5407. , pattern = options.pattern
  5408. , match;
  5409. // Empty values are allowed
  5410. if (!v.isDefined(value)) {
  5411. return;
  5412. }
  5413. if (!v.isString(value)) {
  5414. return message;
  5415. }
  5416. if (v.isString(pattern)) {
  5417. pattern = new RegExp(options.pattern, options.flags);
  5418. }
  5419. match = pattern.exec(value);
  5420. if (!match || match[0].length != value.length) {
  5421. return message;
  5422. }
  5423. },
  5424. inclusion: function(value, options) {
  5425. // Empty values are fine
  5426. if (!v.isDefined(value)) {
  5427. return;
  5428. }
  5429. if (v.isArray(options)) {
  5430. options = {within: options};
  5431. }
  5432. options = v.extend({}, this.options, options);
  5433. if (v.contains(options.within, value)) {
  5434. return;
  5435. }
  5436. var message = options.message ||
  5437. this.message ||
  5438. "^%{value} is not included in the list";
  5439. return v.format(message, {value: value});
  5440. },
  5441. exclusion: function(value, options) {
  5442. // Empty values are fine
  5443. if (!v.isDefined(value)) {
  5444. return;
  5445. }
  5446. if (v.isArray(options)) {
  5447. options = {within: options};
  5448. }
  5449. options = v.extend({}, this.options, options);
  5450. if (!v.contains(options.within, value)) {
  5451. return;
  5452. }
  5453. var message = options.message || this.message || "^%{value} is restricted";
  5454. if (v.isString(options.within[value])) {
  5455. value = options.within[value];
  5456. }
  5457. return v.format(message, {value: value});
  5458. },
  5459. email: v.extend(function(value, options) {
  5460. options = v.extend({}, this.options, options);
  5461. var message = options.message || this.message || "is not a valid email";
  5462. // Empty values are fine
  5463. if (!v.isDefined(value)) {
  5464. return;
  5465. }
  5466. if (!v.isString(value)) {
  5467. return message;
  5468. }
  5469. if (!this.PATTERN.exec(value)) {
  5470. return message;
  5471. }
  5472. }, {
  5473. PATTERN: /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i
  5474. }),
  5475. equality: function(value, options, attribute, attributes, globalOptions) {
  5476. if (!v.isDefined(value)) {
  5477. return;
  5478. }
  5479. if (v.isString(options)) {
  5480. options = {attribute: options};
  5481. }
  5482. options = v.extend({}, this.options, options);
  5483. var message = options.message ||
  5484. this.message ||
  5485. "is not equal to %{attribute}";
  5486. if (v.isEmpty(options.attribute) || !v.isString(options.attribute)) {
  5487. throw new Error("The attribute must be a non empty string");
  5488. }
  5489. var otherValue = v.getDeepObjectValue(attributes, options.attribute)
  5490. , comparator = options.comparator || function(v1, v2) {
  5491. return v1 === v2;
  5492. }
  5493. , prettify = options.prettify ||
  5494. (globalOptions && globalOptions.prettify) ||
  5495. v.prettify;
  5496. if (!comparator(value, otherValue, options, attribute, attributes)) {
  5497. return v.format(message, {attribute: prettify(options.attribute)});
  5498. }
  5499. },
  5500. // A URL validator that is used to validate URLs with the ability to
  5501. // restrict schemes and some domains.
  5502. url: function(value, options) {
  5503. if (!v.isDefined(value)) {
  5504. return;
  5505. }
  5506. options = v.extend({}, this.options, options);
  5507. var message = options.message || this.message || "is not a valid url"
  5508. , schemes = options.schemes || this.schemes || ['http', 'https']
  5509. , allowLocal = options.allowLocal || this.allowLocal || false
  5510. , allowDataUrl = options.allowDataUrl || this.allowDataUrl || false;
  5511. if (!v.isString(value)) {
  5512. return message;
  5513. }
  5514. // https://gist.github.com/dperini/729294
  5515. var regex =
  5516. "^" +
  5517. // protocol identifier
  5518. "(?:(?:" + schemes.join("|") + ")://)" +
  5519. // user:pass authentication
  5520. "(?:\\S+(?::\\S*)?@)?" +
  5521. "(?:";
  5522. var tld = "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))";
  5523. if (allowLocal) {
  5524. tld += "?";
  5525. } else {
  5526. regex +=
  5527. // IP address exclusion
  5528. // private & local networks
  5529. "(?!(?:10|127)(?:\\.\\d{1,3}){3})" +
  5530. "(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})" +
  5531. "(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})";
  5532. }
  5533. regex +=
  5534. // IP address dotted notation octets
  5535. // excludes loopback network 0.0.0.0
  5536. // excludes reserved space >= 224.0.0.0
  5537. // excludes network & broacast addresses
  5538. // (first & last IP address of each class)
  5539. "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
  5540. "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
  5541. "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
  5542. "|" +
  5543. // host name
  5544. "(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)" +
  5545. // domain name
  5546. "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*" +
  5547. tld +
  5548. ")" +
  5549. // port number
  5550. "(?::\\d{2,5})?" +
  5551. // resource path
  5552. "(?:[/?#]\\S*)?" +
  5553. "$";
  5554. if (allowDataUrl) {
  5555. // RFC 2397
  5556. var mediaType = "\\w+\\/[-+.\\w]+(?:;[\\w=]+)*";
  5557. var urlchar = "[A-Za-z0-9-_.!~\\*'();\\/?:@&=+$,%]*";
  5558. var dataurl = "data:(?:"+mediaType+")?(?:;base64)?,"+urlchar;
  5559. regex = "(?:"+regex+")|(?:^"+dataurl+"$)";
  5560. }
  5561. var PATTERN = new RegExp(regex, 'i');
  5562. if (!PATTERN.exec(value)) {
  5563. return message;
  5564. }
  5565. },
  5566. type: v.extend(function(value, originalOptions, attribute, attributes, globalOptions) {
  5567. if (v.isString(originalOptions)) {
  5568. originalOptions = {type: originalOptions};
  5569. }
  5570. if (!v.isDefined(value)) {
  5571. return;
  5572. }
  5573. var options = v.extend({}, this.options, originalOptions);
  5574. var type = options.type;
  5575. if (!v.isDefined(type)) {
  5576. throw new Error("No type was specified");
  5577. }
  5578. var check;
  5579. if (v.isFunction(type)) {
  5580. check = type;
  5581. } else {
  5582. check = this.types[type];
  5583. }
  5584. if (!v.isFunction(check)) {
  5585. throw new Error("validate.validators.type.types." + type + " must be a function.");
  5586. }
  5587. if (!check(value, options, attribute, attributes, globalOptions)) {
  5588. var message = originalOptions.message ||
  5589. this.messages[type] ||
  5590. this.message ||
  5591. options.message ||
  5592. (v.isFunction(type) ? "must be of the correct type" : "must be of type %{type}");
  5593. if (v.isFunction(message)) {
  5594. message = message(value, originalOptions, attribute, attributes, globalOptions);
  5595. }
  5596. return v.format(message, {attribute: v.prettify(attribute), type: type});
  5597. }
  5598. }, {
  5599. types: {
  5600. object: function(value) {
  5601. return v.isObject(value) && !v.isArray(value);
  5602. },
  5603. array: v.isArray,
  5604. integer: v.isInteger,
  5605. number: v.isNumber,
  5606. string: v.isString,
  5607. date: v.isDate,
  5608. boolean: v.isBoolean
  5609. },
  5610. messages: {}
  5611. })
  5612. };
  5613. validate.formatters = {
  5614. detailed: function(errors) {return errors;},
  5615. flat: v.flattenErrorsToArray,
  5616. grouped: function(errors) {
  5617. var attr;
  5618. errors = v.groupErrorsByAttribute(errors);
  5619. for (attr in errors) {
  5620. errors[attr] = v.flattenErrorsToArray(errors[attr]);
  5621. }
  5622. return errors;
  5623. },
  5624. constraint: function(errors) {
  5625. var attr;
  5626. errors = v.groupErrorsByAttribute(errors);
  5627. for (attr in errors) {
  5628. errors[attr] = errors[attr].map(function(result) {
  5629. return result.validator;
  5630. }).sort();
  5631. }
  5632. return errors;
  5633. }
  5634. };
  5635. validate.exposeModule(validate, this, exports, module, __webpack_require__.amdD);
  5636. }).call(this,
  5637. true ? /* istanbul ignore next */ exports : 0,
  5638. true ? /* istanbul ignore next */ module : 0,
  5639. __webpack_require__.amdD);
  5640. /***/ })
  5641. /******/ });
  5642. /************************************************************************/
  5643. /******/ // The module cache
  5644. /******/ var __webpack_module_cache__ = {};
  5645. /******/
  5646. /******/ // The require function
  5647. /******/ function __webpack_require__(moduleId) {
  5648. /******/ // Check if module is in cache
  5649. /******/ var cachedModule = __webpack_module_cache__[moduleId];
  5650. /******/ if (cachedModule !== undefined) {
  5651. /******/ return cachedModule.exports;
  5652. /******/ }
  5653. /******/ // Create a new module (and put it into the cache)
  5654. /******/ var module = __webpack_module_cache__[moduleId] = {
  5655. /******/ id: moduleId,
  5656. /******/ loaded: false,
  5657. /******/ exports: {}
  5658. /******/ };
  5659. /******/
  5660. /******/ // Execute the module function
  5661. /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  5662. /******/
  5663. /******/ // Flag the module as loaded
  5664. /******/ module.loaded = true;
  5665. /******/
  5666. /******/ // Return the exports of the module
  5667. /******/ return module.exports;
  5668. /******/ }
  5669. /******/
  5670. /************************************************************************/
  5671. /******/ /* webpack/runtime/amd define */
  5672. /******/ (() => {
  5673. /******/ __webpack_require__.amdD = function () {
  5674. /******/ throw new Error('define cannot be used indirect');
  5675. /******/ };
  5676. /******/ })();
  5677. /******/
  5678. /******/ /* webpack/runtime/compat get default export */
  5679. /******/ (() => {
  5680. /******/ // getDefaultExport function for compatibility with non-harmony modules
  5681. /******/ __webpack_require__.n = (module) => {
  5682. /******/ var getter = module && module.__esModule ?
  5683. /******/ () => (module['default']) :
  5684. /******/ () => (module);
  5685. /******/ __webpack_require__.d(getter, { a: getter });
  5686. /******/ return getter;
  5687. /******/ };
  5688. /******/ })();
  5689. /******/
  5690. /******/ /* webpack/runtime/define property getters */
  5691. /******/ (() => {
  5692. /******/ // define getter functions for harmony exports
  5693. /******/ __webpack_require__.d = (exports, definition) => {
  5694. /******/ for(var key in definition) {
  5695. /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
  5696. /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
  5697. /******/ }
  5698. /******/ }
  5699. /******/ };
  5700. /******/ })();
  5701. /******/
  5702. /******/ /* webpack/runtime/hasOwnProperty shorthand */
  5703. /******/ (() => {
  5704. /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
  5705. /******/ })();
  5706. /******/
  5707. /******/ /* webpack/runtime/make namespace object */
  5708. /******/ (() => {
  5709. /******/ // define __esModule on exports
  5710. /******/ __webpack_require__.r = (exports) => {
  5711. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  5712. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  5713. /******/ }
  5714. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  5715. /******/ };
  5716. /******/ })();
  5717. /******/
  5718. /******/ /* webpack/runtime/node module decorator */
  5719. /******/ (() => {
  5720. /******/ __webpack_require__.nmd = (module) => {
  5721. /******/ module.paths = [];
  5722. /******/ if (!module.children) module.children = [];
  5723. /******/ return module;
  5724. /******/ };
  5725. /******/ })();
  5726. /******/
  5727. /************************************************************************/
  5728. var __webpack_exports__ = {};
  5729. // This entry need to be wrapped in an IIFE because it need to be in strict mode.
  5730. (() => {
  5731. "use strict";
  5732. /*!***************************************!*\
  5733. !*** ./resources/js/bucket-single.js ***!
  5734. \***************************************/
  5735. __webpack_require__.r(__webpack_exports__);
  5736. /* harmony import */ var riot__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! riot */ "./node_modules/riot/riot.esm.js");
  5737. /* harmony import */ var _components_note_form_riot__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./components/note-form.riot */ "./resources/js/components/note-form.riot");
  5738. riot__WEBPACK_IMPORTED_MODULE_1__.register('note-form', _components_note_form_riot__WEBPACK_IMPORTED_MODULE_0__.default);
  5739. riot__WEBPACK_IMPORTED_MODULE_1__.mount('note-form');
  5740. })();
  5741. /******/ })()
  5742. ;